@xeokit/xeokit-sdk 2.4.0-alpha-68 → 2.4.0-alpha-70
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var e,t=l().mark(eT),n=l().mark(tT),r=l().mark(pD);function i(e){return function(e){if(Array.isArray(e))return d(e)}(e)||function(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}(e)||A(e)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function a(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function s(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?a(Object(n),!0).forEach((function(t){o(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):a(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}function o(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function l(){/*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */l=function(){return e};var e={},t=Object.prototype,n=t.hasOwnProperty,r="function"==typeof Symbol?Symbol:{},i=r.iterator||"@@iterator",a=r.asyncIterator||"@@asyncIterator",s=r.toStringTag||"@@toStringTag";function o(e,t,n){return Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}),e[t]}try{o({},"")}catch(e){o=function(e,t,n){return e[t]=n}}function u(e,t,n,r){var i=t&&t.prototype instanceof p?t:p,a=Object.create(i.prototype),s=new D(r||[]);return a._invoke=function(e,t,n){var r="suspendedStart";return function(i,a){if("executing"===r)throw new Error("Generator is already running");if("completed"===r){if("throw"===i)throw a;return R()}for(n.method=i,n.arg=a;;){var s=n.delegate;if(s){var o=g(s,n);if(o){if(o===f)continue;return o}}if("next"===n.method)n.sent=n._sent=n.arg;else if("throw"===n.method){if("suspendedStart"===r)throw r="completed",n.arg;n.dispatchException(n.arg)}else"return"===n.method&&n.abrupt("return",n.arg);r="executing";var l=c(e,t,n);if("normal"===l.type){if(r=n.done?"completed":"suspendedYield",l.arg===f)continue;return{value:l.arg,done:n.done}}"throw"===l.type&&(r="completed",n.method="throw",n.arg=l.arg)}}}(e,n,s),a}function c(e,t,n){try{return{type:"normal",arg:e.call(t,n)}}catch(e){return{type:"throw",arg:e}}}e.wrap=u;var f={};function p(){}function A(){}function d(){}var v={};o(v,i,(function(){return this}));var h=Object.getPrototypeOf,I=h&&h(h(P([])));I&&I!==t&&n.call(I,i)&&(v=I);var y=d.prototype=p.prototype=Object.create(v);function m(e){["next","throw","return"].forEach((function(t){o(e,t,(function(e){return this._invoke(t,e)}))}))}function w(e,t){function r(i,a,s,o){var l=c(e[i],e,a);if("throw"!==l.type){var u=l.arg,f=u.value;return f&&"object"==E(f)&&n.call(f,"__await")?t.resolve(f.__await).then((function(e){r("next",e,s,o)}),(function(e){r("throw",e,s,o)})):t.resolve(f).then((function(e){u.value=e,s(u)}),(function(e){return r("throw",e,s,o)}))}o(l.arg)}var i;this._invoke=function(e,n){function a(){return new t((function(t,i){r(e,n,t,i)}))}return i=i?i.then(a,a):a()}}function g(e,t){var n=e.iterator[t.method];if(void 0===n){if(t.delegate=null,"throw"===t.method){if(e.iterator.return&&(t.method="return",t.arg=void 0,g(e,t),"throw"===t.method))return f;t.method="throw",t.arg=new TypeError("The iterator does not provide a 'throw' method")}return f}var r=c(n,e.iterator,t.arg);if("throw"===r.type)return t.method="throw",t.arg=r.arg,t.delegate=null,f;var i=r.arg;return i?i.done?(t[e.resultName]=i.value,t.next=e.nextLoc,"return"!==t.method&&(t.method="next",t.arg=void 0),t.delegate=null,f):i:(t.method="throw",t.arg=new TypeError("iterator result is not an object"),t.delegate=null,f)}function T(e){var t={tryLoc:e[0]};1 in e&&(t.catchLoc=e[1]),2 in e&&(t.finallyLoc=e[2],t.afterLoc=e[3]),this.tryEntries.push(t)}function b(e){var t=e.completion||{};t.type="normal",delete t.arg,e.completion=t}function D(e){this.tryEntries=[{tryLoc:"root"}],e.forEach(T,this),this.reset(!0)}function P(e){if(e){var t=e[i];if(t)return t.call(e);if("function"==typeof e.next)return e;if(!isNaN(e.length)){var r=-1,a=function t(){for(;++r<e.length;)if(n.call(e,r))return t.value=e[r],t.done=!1,t;return t.value=void 0,t.done=!0,t};return a.next=a}}return{next:R}}function R(){return{value:void 0,done:!0}}return A.prototype=d,o(y,"constructor",d),o(d,"constructor",A),A.displayName=o(d,s,"GeneratorFunction"),e.isGeneratorFunction=function(e){var t="function"==typeof e&&e.constructor;return!!t&&(t===A||"GeneratorFunction"===(t.displayName||t.name))},e.mark=function(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,d):(e.__proto__=d,o(e,s,"GeneratorFunction")),e.prototype=Object.create(y),e},e.awrap=function(e){return{__await:e}},m(w.prototype),o(w.prototype,a,(function(){return this})),e.AsyncIterator=w,e.async=function(t,n,r,i,a){void 0===a&&(a=Promise);var s=new w(u(t,n,r,i),a);return e.isGeneratorFunction(n)?s:s.next().then((function(e){return e.done?e.value:s.next()}))},m(y),o(y,s,"Generator"),o(y,i,(function(){return this})),o(y,"toString",(function(){return"[object Generator]"})),e.keys=function(e){var t=[];for(var n in e)t.push(n);return t.reverse(),function n(){for(;t.length;){var r=t.pop();if(r in e)return n.value=r,n.done=!1,n}return n.done=!0,n}},e.values=P,D.prototype={constructor:D,reset:function(e){if(this.prev=0,this.next=0,this.sent=this._sent=void 0,this.done=!1,this.delegate=null,this.method="next",this.arg=void 0,this.tryEntries.forEach(b),!e)for(var t in this)"t"===t.charAt(0)&&n.call(this,t)&&!isNaN(+t.slice(1))&&(this[t]=void 0)},stop:function(){this.done=!0;var e=this.tryEntries[0].completion;if("throw"===e.type)throw e.arg;return this.rval},dispatchException:function(e){if(this.done)throw e;var t=this;function r(n,r){return s.type="throw",s.arg=e,t.next=n,r&&(t.method="next",t.arg=void 0),!!r}for(var i=this.tryEntries.length-1;i>=0;--i){var a=this.tryEntries[i],s=a.completion;if("root"===a.tryLoc)return r("end");if(a.tryLoc<=this.prev){var o=n.call(a,"catchLoc"),l=n.call(a,"finallyLoc");if(o&&l){if(this.prev<a.catchLoc)return r(a.catchLoc,!0);if(this.prev<a.finallyLoc)return r(a.finallyLoc)}else if(o){if(this.prev<a.catchLoc)return r(a.catchLoc,!0)}else{if(!l)throw new Error("try statement without catch or finally");if(this.prev<a.finallyLoc)return r(a.finallyLoc)}}}},abrupt:function(e,t){for(var r=this.tryEntries.length-1;r>=0;--r){var i=this.tryEntries[r];if(i.tryLoc<=this.prev&&n.call(i,"finallyLoc")&&this.prev<i.finallyLoc){var a=i;break}}a&&("break"===e||"continue"===e)&&a.tryLoc<=t&&t<=a.finallyLoc&&(a=null);var s=a?a.completion:{};return s.type=e,s.arg=t,a?(this.method="next",this.next=a.finallyLoc,f):this.complete(s)},complete:function(e,t){if("throw"===e.type)throw e.arg;return"break"===e.type||"continue"===e.type?this.next=e.arg:"return"===e.type?(this.rval=this.arg=e.arg,this.method="return",this.next="end"):"normal"===e.type&&t&&(this.next=t),f},finish:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var n=this.tryEntries[t];if(n.finallyLoc===e)return this.complete(n.completion,n.afterLoc),b(n),f}},catch:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var n=this.tryEntries[t];if(n.tryLoc===e){var r=n.completion;if("throw"===r.type){var i=r.arg;b(n)}return i}}throw new Error("illegal catch attempt")},delegateYield:function(e,t,n){return this.delegate={iterator:P(e),resultName:t,nextLoc:n},"next"===this.method&&(this.arg=void 0),f}},e}function u(e,t,n,r,i,a,s){try{var o=e[a](s),l=o.value}catch(e){return void n(e)}o.done?t(l):Promise.resolve(l).then(r,i)}function c(e){return function(){var t=this,n=arguments;return new Promise((function(r,i){var a=e.apply(t,n);function s(e){u(a,r,i,s,o,"next",e)}function o(e){u(a,r,i,s,o,"throw",e)}s(void 0)}))}}function f(e,t){var n="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!n){if(Array.isArray(e)||(n=A(e))||t&&e&&"number"==typeof e.length){n&&(e=n);var r=0,i=function(){};return{s:i,n:function(){return r>=e.length?{done:!0}:{done:!1,value:e[r++]}},e:function(e){throw e},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var a,s=!0,o=!1;return{s:function(){n=n.call(e)},n:function(){var e=n.next();return s=e.done,e},e:function(e){o=!0,a=e},f:function(){try{s||null==n.return||n.return()}finally{if(o)throw a}}}}function p(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null==n)return;var r,i,a=[],s=!0,o=!1;try{for(n=n.call(e);!(s=(r=n.next()).done)&&(a.push(r.value),!t||a.length!==t);s=!0);}catch(e){o=!0,i=e}finally{try{s||null==n.return||n.return()}finally{if(o)throw i}}return a}(e,t)||A(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function A(e,t){if(e){if("string"==typeof e)return d(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?d(e,t):void 0}}function d(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n<t;n++)r[n]=e[n];return r}function v(){return v="undefined"!=typeof Reflect&&Reflect.get?Reflect.get.bind():function(e,t,n){var r=h(e,t);if(r){var i=Object.getOwnPropertyDescriptor(r,t);return i.get?i.get.call(arguments.length<3?e:n):i.value}},v.apply(this,arguments)}function h(e,t){for(;!Object.prototype.hasOwnProperty.call(e,t)&&null!==(e=T(e)););return e}function I(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&y(e,t)}function y(e,t){return y=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},y(e,t)}function m(e){var t=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(e){return!1}}();return function(){var n,r=T(e);if(t){var i=T(this).constructor;n=Reflect.construct(r,arguments,i)}else n=r.apply(this,arguments);return w(this,n)}}function w(e,t){if(t&&("object"===E(t)||"function"==typeof t))return t;if(void 0!==t)throw new TypeError("Derived constructors may only return object or undefined");return g(e)}function g(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function T(e){return T=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},T(e)}function E(e){return E="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},E(e)}function b(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function D(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}function P(e,t,n){return t&&D(e.prototype,t),n&&D(e,n),Object.defineProperty(e,"prototype",{writable:!1}),e}function R(e){return new B(e)}function C(e){return function(){return new _(e.apply(this,arguments))}}function _(e){var t,n;function r(t,n){try{var a=e[t](n),s=a.value,o=s instanceof B;Promise.resolve(o?s.wrapped:s).then((function(e){o?r("return"===t?"return":"next",e):i(a.done?"return":"normal",e)}),(function(e){r("throw",e)}))}catch(e){i("throw",e)}}function i(e,i){switch(e){case"return":t.resolve({value:i,done:!0});break;case"throw":t.reject(i);break;default:t.resolve({value:i,done:!1})}(t=t.next)?r(t.key,t.arg):n=null}this._invoke=function(e,i){return new Promise((function(a,s){var o={key:e,arg:i,resolve:a,reject:s,next:null};n?n=n.next=o:(t=n=o,r(e,i))}))},"function"!=typeof e.return&&(this.return=void 0)}function B(e){this.wrapped=e}function O(e){var t,n,r,i=2;for("undefined"!=typeof Symbol&&(n=Symbol.asyncIterator,r=Symbol.iterator);i--;){if(n&&null!=(t=e[n]))return t.call(e);if(r&&null!=(t=e[r]))return new S(t.call(e));n="@@asyncIterator",r="@@iterator"}throw new TypeError("Object is not async iterable")}function S(e){function t(e){if(Object(e)!==e)return Promise.reject(new TypeError(e+" is not an object."));var t=e.done;return Promise.resolve(e.value).then((function(e){return{value:e,done:t}}))}return S=function(e){this.s=e,this.n=e.next},S.prototype={s:null,n:null,next:function(){return t(this.n.apply(this.s,arguments))},return:function(e){var n=this.s.return;return void 0===n?Promise.resolve({value:e,done:!0}):t(n.apply(this.s,arguments))},throw:function(e){var n=this.s.return;return void 0===n?Promise.reject(e):t(n.apply(this.s,arguments))}},new S(e)}_.prototype["function"==typeof Symbol&&Symbol.asyncIterator||"@@asyncIterator"]=function(){return this},_.prototype.next=function(e){return this._invoke("next",e)},_.prototype.throw=function(e){return this._invoke("throw",e)},_.prototype.return=function(e){return this._invoke("return",e)};var N,L,x,M,F,H,U,G=function(){function e(t,n){b(this,e),this.items=t||[],this._lastUniqueId=(n||0)+1}return P(e,[{key:"addItem",value:function(){var e;if(2===arguments.length){var t=arguments[0];if(e=arguments[1],this.items[t])throw"ID clash: '"+t+"'";return this.items[t]=e,t}for(e=arguments[0]||{};;){var n=this._lastUniqueId++;if(!this.items[n])return this.items[n]=e,n}}},{key:"removeItem",value:function(e){var t=this.items[e];return delete this.items[e],t}}]),e}(),k=new G,V=P((function e(t){b(this,e),this.id=t,this.parentItem=null,this.groups=[],this.menuElement=null,this.shown=!1,this.mouseOver=0})),j=P((function e(){b(this,e),this.items=[]})),Q=P((function e(t,n,r,i,a){b(this,e),this.id=t,this.getTitle=n,this.doAction=r,this.getEnabled=i,this.getShown=a,this.itemElement=null,this.subMenu=null,this.enabled=!0})),W=function(){function e(){var t=this,n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};b(this,e),this._id=k.addItem(),this._context=null,this._enabled=!1,this._itemsCfg=[],this._rootMenu=null,this._menuList=[],this._menuMap={},this._itemList=[],this._itemMap={},this._shown=!1,this._nextId=0,this._eventSubs={},!1!==n.hideOnMouseDown&&(document.addEventListener("mousedown",(function(e){e.target.classList.contains("xeokit-context-menu-item")||t.hide()})),document.addEventListener("touchstart",this._canvasTouchStartHandler=function(e){e.target.classList.contains("xeokit-context-menu-item")||t.hide()})),n.items&&(this.items=n.items),this._hideOnAction=!1!==n.hideOnAction,this.context=n.context,this.enabled=!1!==n.enabled,this.hide()}return P(e,[{key:"on",value:function(e,t){var n=this._eventSubs[e];n||(n=[],this._eventSubs[e]=n),n.push(t)}},{key:"fire",value:function(e,t){var n=this._eventSubs[e];if(n)for(var r=0,i=n.length;r<i;r++)n[r](t)}},{key:"items",get:function(){return this._itemsCfg},set:function(e){this._clear(),this._itemsCfg=e||[],this._parseItems(e),this._createUI()}},{key:"enabled",get:function(){return this._enabled},set:function(e){(e=!!e)!==this._enabled&&(this._enabled=e,this._enabled||this.hide())}},{key:"context",get:function(){return this._context},set:function(e){this._context=e}},{key:"show",value:function(e,t){this._context?this._enabled&&(this._shown||(this._hideAllMenus(),this._updateItemsTitles(),this._updateItemsEnabledStatus(),this._showMenu(this._rootMenu.id,e,t),this._shown=!0,this.fire("shown",{}))):console.error("ContextMenu cannot be shown without a context - set context first")}},{key:"shown",get:function(){return this._shown}},{key:"hide",value:function(){this._enabled&&this._shown&&(this._hideAllMenus(),this._shown=!1,this.fire("hidden",{}))}},{key:"destroy",value:function(){this._context=null,this._clear(),null!==this._id&&(k.removeItem(this._id),this._id=null)}},{key:"_clear",value:function(){for(var e=0,t=this._menuList.length;e<t;e++){var n=this._menuList[e].menuElement;n.parentElement.removeChild(n)}this._itemsCfg=[],this._rootMenu=null,this._menuList=[],this._menuMap={},this._itemList=[],this._itemMap={}}},{key:"_parseItems",value:function(e){var t=this;this._rootMenu=function e(n){for(var r=t._getNextId(),i=new V(r),a=0,s=n.length;a<s;a++){var o=n[a],l=new j;i.groups.push(l);for(var u=function(n,r){var a=o[n],s=a.items,u=s&&s.length>0,c=t._getNextId(),f=a.getTitle||function(){return a.title||""},p=a.doAction||a.callback||function(){},A=a.getEnabled||function(){return!0},d=a.getShown||function(){return!0},v=new Q(c,f,p,A,d);if(v.parentMenu=i,l.items.push(v),u){var h=e(s);v.subMenu=h,h.parentItem=v}t._itemList.push(v),t._itemMap[v.id]=v},c=0,f=o.length;c<f;c++)u(c)}return t._menuList.push(i),t._menuMap[i.id]=i,i}(e)}},{key:"_getNextId",value:function(){return"ContextMenu_"+this._id+"_"+this._nextId++}},{key:"_createUI",value:function(){var e=this;!function t(n){e._createMenuUI(n);for(var r=n.groups,i=0,a=r.length;i<a;i++)for(var s=r[i].items,o=0,l=s.length;o<l;o++){var u=s[o].subMenu;u&&t(u)}}(this._rootMenu)}},{key:"_createMenuUI",value:function(e){var t=this,n=e.groups,r=[];if(r.push('<div class="xeokit-context-menu '+e.id+'" style="z-index:300000; position: absolute;">'),r.push("<ul>"),n)for(var i=0,a=n.length;i<a;i++){var s=i,o=a,l=n[i].items;if(l)for(var u=0,c=l.length;u<c;u++){var f=l[u],p=f.subMenu,A=f.title||"";p?r.push('<li id="'+f.id+'" class="xeokit-context-menu-item" style="'+(s===o-1||u<c-1?"border-bottom: 0":"border-bottom: 1px solid black")+'">'+A+" [MORE]</li>"):r.push('<li id="'+f.id+'" class="xeokit-context-menu-item" style="'+(s===o-1||u<c-1?"border-bottom: 0":"border-bottom: 1px solid black")+'">'+A+"</li>")}}r.push("</ul>"),r.push("</div>");var d=r.join("");document.body.insertAdjacentHTML("beforeend",d);var v=document.querySelector("."+e.id);e.menuElement=v,v.style["border-radius"]="4px",v.style.display="none",v.style["z-index"]=3e5,v.style.background="white",v.style.border="1px solid black",v.style["box-shadow"]="0 4px 5px 0 gray",v.oncontextmenu=function(e){e.preventDefault()};var h=this,I=null;if(n)for(var y=0,m=n.length;y<m;y++){var w=n[y].items;if(w)for(var g=function(e,n){var r=w[e],i=r.subMenu;if(r.itemElement=document.getElementById(r.id),!r.itemElement)return console.error("ContextMenu item element not found: "+r.id),"continue";r.itemElement.addEventListener("mouseenter",(function(e){e.preventDefault();var t=r.subMenu;if(t){if(I&&I.id!==t.id&&(h._hideMenu(I.id),I=null),!1!==r.enabled){var n=r.itemElement,i=t.menuElement,a=n.getBoundingClientRect();i.getBoundingClientRect();a.right+200>window.innerWidth?h._showMenu(t.id,a.left-200,a.top-1):h._showMenu(t.id,a.right-5,a.top-1),I=t}}else I&&(h._hideMenu(I.id),I=null)})),i||(r.itemElement.addEventListener("click",(function(e){e.preventDefault(),h._context&&!1!==r.enabled&&(r.doAction&&r.doAction(h._context),t._hideOnAction?h.hide():(h._updateItemsTitles(),h._updateItemsEnabledStatus()))})),r.itemElement.addEventListener("mouseenter",(function(e){e.preventDefault(),!1!==r.enabled&&r.doHover&&r.doHover(h._context)})))},T=0,E=w.length;T<E;T++)g(T)}}},{key:"_updateItemsTitles",value:function(){if(this._context)for(var e=0,t=this._itemList.length;e<t;e++){var n=this._itemList[e],r=n.itemElement;if(r){var i=n.getShown;if(i&&i(this._context)){var a=n.getTitle(this._context);n.subMenu,r.innerText=a}}}}},{key:"_updateItemsEnabledStatus",value:function(){if(this._context)for(var e=0,t=this._itemList.length;e<t;e++){var n=this._itemList[e],r=n.itemElement;if(r){var i=n.getEnabled;if(i){var a=n.getShown;if(a){var s=a(this._context);if(n.shown=s,s){r.style.visibility="visible",r.style.height="auto",r.style.padding=null;var o=i(this._context);n.enabled=o,o?r.classList.remove("disabled"):r.classList.add("disabled")}else r.style.visibility="hidden",r.style.height="0",r.style.padding="0"}}}}}},{key:"_showMenu",value:function(e,t,n){var r=this._menuMap[e];if(r){if(!r.shown){var i=r.menuElement;i&&(this._showMenuElement(i,t,n),r.shown=!0)}}else console.error("Menu not found: "+e)}},{key:"_hideMenu",value:function(e){var t=this._menuMap[e];if(t){if(t.shown){var n=t.menuElement;n&&(this._hideMenuElement(n),t.shown=!1)}}else console.error("Menu not found: "+e)}},{key:"_hideAllMenus",value:function(){for(var e=0,t=this._menuList.length;e<t;e++){var n=this._menuList[e];this._hideMenu(n.id)}}},{key:"_showMenuElement",value:function(e,t,n){e.style.display="block";var r=e.offsetHeight,i=e.offsetWidth;n+r>window.innerHeight&&(n=window.innerHeight-r),t+i>window.innerWidth&&(t=window.innerWidth-i),e.style.left=t+"px",e.style.top=n+"px"}},{key:"_hideMenuElement",value:function(e){e.style.display="none"}}]),e}(),z=function(){function e(t,n,r){b(this,e),this.id=r&&r.id?r.id:t,this.viewer=n,this._subIdMap=null,this._subIdEvents=null,this._eventSubs=null,this._eventSubsNum=null,this._events=null,this._eventCallDepth=0,n.addPlugin(this)}return P(e,[{key:"fire",value:function(e,t,n){this._events||(this._events={}),this._eventSubs||(this._eventSubs={},this._eventSubsNum={}),!0!==n&&(this._events[e]=t||!0);var r,i=this._eventSubs[e];if(i)for(var a in i)i.hasOwnProperty(a)&&(r=i[a],this._eventCallDepth++,this._eventCallDepth<300?r.callback.call(r.scope,t):this.error("fire: potential stack overflow from recursive event '"+e+"' - dropping this event"),this._eventCallDepth--)}},{key:"on",value:function(e,t,n){this._events||(this._events={}),this._subIdMap||(this._subIdMap=new G),this._subIdEvents||(this._subIdEvents={}),this._eventSubs||(this._eventSubs={}),this._eventSubsNum||(this._eventSubsNum={});var r=this._eventSubs[e];r?this._eventSubsNum[e]++:(r={},this._eventSubs[e]=r,this._eventSubsNum[e]=1);var i=this._subIdMap.addItem();r[i]={callback:t,scope:n||this},this._subIdEvents[i]=e;var a=this._events[e];return void 0!==a&&t.call(n||this,a),i}},{key:"off",value:function(e){if(null!=e&&this._subIdEvents){var t=this._subIdEvents[e];if(t){delete this._subIdEvents[e];var n=this._eventSubs[t];n&&(delete n[e],this._eventSubsNum[t]--),this._subIdMap.removeItem(e)}}}},{key:"once",value:function(e,t,n){var r=this,i=this.on(e,(function(e){r.off(i),t.call(n||this,e)}),n)}},{key:"hasSubs",value:function(e){return this._eventSubsNum&&this._eventSubsNum[e]>0}},{key:"log",value:function(e){console.log("[xeokit plugin ".concat(this.id,"]: ").concat(e))}},{key:"warn",value:function(e){console.warn("[xeokit plugin ".concat(this.id,"]: ").concat(e))}},{key:"error",value:function(e){console.error("[xeokit plugin ".concat(this.id,"]: ").concat(e))}},{key:"send",value:function(e,t){}},{key:"destroy",value:function(){this.viewer.removePlugin(this)}}]),e}(),K=!0,Y=K?Float64Array:Float32Array,X=new Y(16),q=new Y(16),J=new Y(4),Z={setDoublePrecisionEnabled:function(e){Y=(K=e)?Float64Array:Float32Array},getDoublePrecisionEnabled:function(){return K},MIN_DOUBLE:-Number.MAX_SAFE_INTEGER,MAX_DOUBLE:Number.MAX_SAFE_INTEGER,MAX_INT:1e7,DEGTORAD:.0174532925,RADTODEG:57.295779513,unglobalizeObjectId:function(e,t){var n=t.indexOf("#");return n===e.length&&t.startsWith(e)?t.substring(n+1):t},globalizeObjectId:function(e,t){return e+"#"+t},safeInv:function(e){var t=1/e;return isNaN(t)||!isFinite(t)?1:t},vec2:function(e){return new Y(e||2)},vec3:function(e){return new Y(e||3)},vec4:function(e){return new Y(e||4)},mat3:function(e){return new Y(e||9)},mat3ToMat4:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:new Y(16);return t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=0,t[4]=e[3],t[5]=e[4],t[6]=e[5],t[7]=0,t[8]=e[6],t[9]=e[7],t[10]=e[8],t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t},mat4:function(e){return new Y(e||16)},mat4ToMat3:function(e,t){},doublesToFloats:function(e,t,n){for(var r=new Y(2),i=0,a=e.length;i<a;i++)Z.splitDouble(e[i],r),t[i]=r[0],n[i]=r[1]},splitDouble:function(e,t){var n=Y.from([e])[0],r=e-n;t[0]=n,t[1]=r},createUUID:function(){for(var e=[],t=0;t<256;t++)e[t]=(t<16?"0":"")+t.toString(16);return function(){var t=4294967295*Math.random()|0,n=4294967295*Math.random()|0,r=4294967295*Math.random()|0,i=4294967295*Math.random()|0;return"".concat(e[255&t]+e[t>>8&255]+e[t>>16&255]+e[t>>24&255],"-").concat(e[255&n]).concat(e[n>>8&255],"-").concat(e[n>>16&15|64]).concat(e[n>>24&255],"-").concat(e[63&r|128]).concat(e[r>>8&255],"-").concat(e[r>>16&255]).concat(e[r>>24&255]).concat(e[255&i]).concat(e[i>>8&255]).concat(e[i>>16&255]).concat(e[i>>24&255])}}(),clamp:function(e,t,n){return Math.max(t,Math.min(n,e))},fmod:function(e,t){if(e<t)return console.error("math.fmod : Attempting to find modulus within negative range - would be infinite loop - ignoring"),e;for(;t<=e;)e-=t;return e},compareVec3:function(e,t){return e[0]===t[0]&&e[1]===t[1]&&e[2]===t[2]},negateVec3:function(e,t){return t||(t=e),t[0]=-e[0],t[1]=-e[1],t[2]=-e[2],t},negateVec4:function(e,t){return t||(t=e),t[0]=-e[0],t[1]=-e[1],t[2]=-e[2],t[3]=-e[3],t},addVec4:function(e,t,n){return n||(n=e),n[0]=e[0]+t[0],n[1]=e[1]+t[1],n[2]=e[2]+t[2],n[3]=e[3]+t[3],n},addVec4Scalar:function(e,t,n){return n||(n=e),n[0]=e[0]+t,n[1]=e[1]+t,n[2]=e[2]+t,n[3]=e[3]+t,n},addVec3:function(e,t,n){return n||(n=e),n[0]=e[0]+t[0],n[1]=e[1]+t[1],n[2]=e[2]+t[2],n},addVec3Scalar:function(e,t,n){return n||(n=e),n[0]=e[0]+t,n[1]=e[1]+t,n[2]=e[2]+t,n},subVec4:function(e,t,n){return n||(n=e),n[0]=e[0]-t[0],n[1]=e[1]-t[1],n[2]=e[2]-t[2],n[3]=e[3]-t[3],n},subVec3:function(e,t,n){return n||(n=e),n[0]=e[0]-t[0],n[1]=e[1]-t[1],n[2]=e[2]-t[2],n},subVec2:function(e,t,n){return n||(n=e),n[0]=e[0]-t[0],n[1]=e[1]-t[1],n},geometricMeanVec2:function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];for(var r=new Y(t[0]),i=1;i<t.length;i++)r[0]+=t[i][0],r[1]+=t[i][1];return r[0]/=t.length,r[1]/=t.length,r},subVec4Scalar:function(e,t,n){return n||(n=e),n[0]=e[0]-t,n[1]=e[1]-t,n[2]=e[2]-t,n[3]=e[3]-t,n},subScalarVec4:function(e,t,n){return n||(n=e),n[0]=t-e[0],n[1]=t-e[1],n[2]=t-e[2],n[3]=t-e[3],n},mulVec4:function(e,t,n){return n||(n=e),n[0]=e[0]*t[0],n[1]=e[1]*t[1],n[2]=e[2]*t[2],n[3]=e[3]*t[3],n},mulVec4Scalar:function(e,t,n){return n||(n=e),n[0]=e[0]*t,n[1]=e[1]*t,n[2]=e[2]*t,n[3]=e[3]*t,n},mulVec3Scalar:function(e,t,n){return n||(n=e),n[0]=e[0]*t,n[1]=e[1]*t,n[2]=e[2]*t,n},mulVec2Scalar:function(e,t,n){return n||(n=e),n[0]=e[0]*t,n[1]=e[1]*t,n},divVec3:function(e,t,n){return n||(n=e),n[0]=e[0]/t[0],n[1]=e[1]/t[1],n[2]=e[2]/t[2],n},divVec4:function(e,t,n){return n||(n=e),n[0]=e[0]/t[0],n[1]=e[1]/t[1],n[2]=e[2]/t[2],n[3]=e[3]/t[3],n},divScalarVec3:function(e,t,n){return n||(n=t),n[0]=e/t[0],n[1]=e/t[1],n[2]=e/t[2],n},divVec3Scalar:function(e,t,n){return n||(n=e),n[0]=e[0]/t,n[1]=e[1]/t,n[2]=e[2]/t,n},divVec4Scalar:function(e,t,n){return n||(n=e),n[0]=e[0]/t,n[1]=e[1]/t,n[2]=e[2]/t,n[3]=e[3]/t,n},divScalarVec4:function(e,t,n){return n||(n=t),n[0]=e/t[0],n[1]=e/t[1],n[2]=e/t[2],n[3]=e/t[3],n},dotVec4:function(e,t){return e[0]*t[0]+e[1]*t[1]+e[2]*t[2]+e[3]*t[3]},cross3Vec4:function(e,t){var n=e[0],r=e[1],i=e[2],a=t[0],s=t[1],o=t[2];return[r*o-i*s,i*a-n*o,n*s-r*a,0]},cross3Vec3:function(e,t,n){n||(n=e);var r=e[0],i=e[1],a=e[2],s=t[0],o=t[1],l=t[2];return n[0]=i*l-a*o,n[1]=a*s-r*l,n[2]=r*o-i*s,n},sqLenVec4:function(e){return Z.dotVec4(e,e)},lenVec4:function(e){return Math.sqrt(Z.sqLenVec4(e))},dotVec3:function(e,t){return e[0]*t[0]+e[1]*t[1]+e[2]*t[2]},dotVec2:function(e,t){return e[0]*t[0]+e[1]*t[1]},sqLenVec3:function(e){return Z.dotVec3(e,e)},sqLenVec2:function(e){return Z.dotVec2(e,e)},lenVec3:function(e){return Math.sqrt(Z.sqLenVec3(e))},distVec3:(U=new Y(3),function(e,t){return Z.lenVec3(Z.subVec3(e,t,U))}),lenVec2:function(e){return Math.sqrt(Z.sqLenVec2(e))},distVec2:function(){var e=new Y(2);return function(t,n){return Z.lenVec2(Z.subVec2(t,n,e))}}(),rcpVec3:function(e,t){return Z.divScalarVec3(1,e,t)},normalizeVec4:function(e,t){var n=1/Z.lenVec4(e);return Z.mulVec4Scalar(e,n,t)},normalizeVec3:function(e,t){var n=1/Z.lenVec3(e);return Z.mulVec3Scalar(e,n,t)},normalizeVec2:function(e,t){var n=1/Z.lenVec2(e);return Z.mulVec2Scalar(e,n,t)},angleVec3:function(e,t){var n=Z.dotVec3(e,t)/Math.sqrt(Z.sqLenVec3(e)*Z.sqLenVec3(t));return n=n<-1?-1:n>1?1:n,Math.acos(n)},vec3FromMat4Scale:function(){var e=new Y(3);return function(t,n){return e[0]=t[0],e[1]=t[1],e[2]=t[2],n[0]=Z.lenVec3(e),e[0]=t[4],e[1]=t[5],e[2]=t[6],n[1]=Z.lenVec3(e),e[0]=t[8],e[1]=t[9],e[2]=t[10],n[2]=Z.lenVec3(e),n}}(),vecToArray:function(){function e(e){return Math.round(1e5*e)/1e5}return function(t){for(var n=0,r=(t=Array.prototype.slice.call(t)).length;n<r;n++)t[n]=e(t[n]);return t}}(),xyzArrayToObject:function(e){return{x:e[0],y:e[1],z:e[2]}},xyzObjectToArray:function(e,t){return(t=t||Z.vec3())[0]=e.x,t[1]=e.y,t[2]=e.z,t},dupMat4:function(e){return e.slice(0,16)},mat4To3:function(e){return[e[0],e[1],e[2],e[4],e[5],e[6],e[8],e[9],e[10]]},m4s:function(e){return[e,e,e,e,e,e,e,e,e,e,e,e,e,e,e,e]},setMat4ToZeroes:function(){return Z.m4s(0)},setMat4ToOnes:function(){return Z.m4s(1)},diagonalMat4v:function(e){return new Y([e[0],0,0,0,0,e[1],0,0,0,0,e[2],0,0,0,0,e[3]])},diagonalMat4c:function(e,t,n,r){return Z.diagonalMat4v([e,t,n,r])},diagonalMat4s:function(e){return Z.diagonalMat4c(e,e,e,e)},identityMat4:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:new Y(16);return e[0]=1,e[1]=0,e[2]=0,e[3]=0,e[4]=0,e[5]=1,e[6]=0,e[7]=0,e[8]=0,e[9]=0,e[10]=1,e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,e},identityMat3:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:new Y(9);return e[0]=1,e[1]=0,e[2]=0,e[3]=0,e[4]=1,e[5]=0,e[6]=0,e[7]=0,e[8]=1,e},isIdentityMat4:function(e){return 1===e[0]&&0===e[1]&&0===e[2]&&0===e[3]&&0===e[4]&&1===e[5]&&0===e[6]&&0===e[7]&&0===e[8]&&0===e[9]&&1===e[10]&&0===e[11]&&0===e[12]&&0===e[13]&&0===e[14]&&1===e[15]},negateMat4:function(e,t){return t||(t=e),t[0]=-e[0],t[1]=-e[1],t[2]=-e[2],t[3]=-e[3],t[4]=-e[4],t[5]=-e[5],t[6]=-e[6],t[7]=-e[7],t[8]=-e[8],t[9]=-e[9],t[10]=-e[10],t[11]=-e[11],t[12]=-e[12],t[13]=-e[13],t[14]=-e[14],t[15]=-e[15],t},addMat4:function(e,t,n){return n||(n=e),n[0]=e[0]+t[0],n[1]=e[1]+t[1],n[2]=e[2]+t[2],n[3]=e[3]+t[3],n[4]=e[4]+t[4],n[5]=e[5]+t[5],n[6]=e[6]+t[6],n[7]=e[7]+t[7],n[8]=e[8]+t[8],n[9]=e[9]+t[9],n[10]=e[10]+t[10],n[11]=e[11]+t[11],n[12]=e[12]+t[12],n[13]=e[13]+t[13],n[14]=e[14]+t[14],n[15]=e[15]+t[15],n},addMat4Scalar:function(e,t,n){return n||(n=e),n[0]=e[0]+t,n[1]=e[1]+t,n[2]=e[2]+t,n[3]=e[3]+t,n[4]=e[4]+t,n[5]=e[5]+t,n[6]=e[6]+t,n[7]=e[7]+t,n[8]=e[8]+t,n[9]=e[9]+t,n[10]=e[10]+t,n[11]=e[11]+t,n[12]=e[12]+t,n[13]=e[13]+t,n[14]=e[14]+t,n[15]=e[15]+t,n},addScalarMat4:function(e,t,n){return Z.addMat4Scalar(t,e,n)},subMat4:function(e,t,n){return n||(n=e),n[0]=e[0]-t[0],n[1]=e[1]-t[1],n[2]=e[2]-t[2],n[3]=e[3]-t[3],n[4]=e[4]-t[4],n[5]=e[5]-t[5],n[6]=e[6]-t[6],n[7]=e[7]-t[7],n[8]=e[8]-t[8],n[9]=e[9]-t[9],n[10]=e[10]-t[10],n[11]=e[11]-t[11],n[12]=e[12]-t[12],n[13]=e[13]-t[13],n[14]=e[14]-t[14],n[15]=e[15]-t[15],n},subMat4Scalar:function(e,t,n){return n||(n=e),n[0]=e[0]-t,n[1]=e[1]-t,n[2]=e[2]-t,n[3]=e[3]-t,n[4]=e[4]-t,n[5]=e[5]-t,n[6]=e[6]-t,n[7]=e[7]-t,n[8]=e[8]-t,n[9]=e[9]-t,n[10]=e[10]-t,n[11]=e[11]-t,n[12]=e[12]-t,n[13]=e[13]-t,n[14]=e[14]-t,n[15]=e[15]-t,n},subScalarMat4:function(e,t,n){return n||(n=t),n[0]=e-t[0],n[1]=e-t[1],n[2]=e-t[2],n[3]=e-t[3],n[4]=e-t[4],n[5]=e-t[5],n[6]=e-t[6],n[7]=e-t[7],n[8]=e-t[8],n[9]=e-t[9],n[10]=e-t[10],n[11]=e-t[11],n[12]=e-t[12],n[13]=e-t[13],n[14]=e-t[14],n[15]=e-t[15],n},mulMat4:function(e,t,n){n||(n=e);var r=e[0],i=e[1],a=e[2],s=e[3],o=e[4],l=e[5],u=e[6],c=e[7],f=e[8],p=e[9],A=e[10],d=e[11],v=e[12],h=e[13],I=e[14],y=e[15],m=t[0],w=t[1],g=t[2],T=t[3],E=t[4],b=t[5],D=t[6],P=t[7],R=t[8],C=t[9],_=t[10],B=t[11],O=t[12],S=t[13],N=t[14],L=t[15];return n[0]=m*r+w*o+g*f+T*v,n[1]=m*i+w*l+g*p+T*h,n[2]=m*a+w*u+g*A+T*I,n[3]=m*s+w*c+g*d+T*y,n[4]=E*r+b*o+D*f+P*v,n[5]=E*i+b*l+D*p+P*h,n[6]=E*a+b*u+D*A+P*I,n[7]=E*s+b*c+D*d+P*y,n[8]=R*r+C*o+_*f+B*v,n[9]=R*i+C*l+_*p+B*h,n[10]=R*a+C*u+_*A+B*I,n[11]=R*s+C*c+_*d+B*y,n[12]=O*r+S*o+N*f+L*v,n[13]=O*i+S*l+N*p+L*h,n[14]=O*a+S*u+N*A+L*I,n[15]=O*s+S*c+N*d+L*y,n},mulMat3:function(e,t,n){n||(n=new Y(9));var r=e[0],i=e[3],a=e[6],s=e[1],o=e[4],l=e[7],u=e[2],c=e[5],f=e[8],p=t[0],A=t[3],d=t[6],v=t[1],h=t[4],I=t[7],y=t[2],m=t[5],w=t[8];return n[0]=r*p+i*v+a*y,n[3]=r*A+i*h+a*m,n[6]=r*d+i*I+a*w,n[1]=s*p+o*v+l*y,n[4]=s*A+o*h+l*m,n[7]=s*d+o*I+l*w,n[2]=u*p+c*v+f*y,n[5]=u*A+c*h+f*m,n[8]=u*d+c*I+f*w,n},mulMat4Scalar:function(e,t,n){return n||(n=e),n[0]=e[0]*t,n[1]=e[1]*t,n[2]=e[2]*t,n[3]=e[3]*t,n[4]=e[4]*t,n[5]=e[5]*t,n[6]=e[6]*t,n[7]=e[7]*t,n[8]=e[8]*t,n[9]=e[9]*t,n[10]=e[10]*t,n[11]=e[11]*t,n[12]=e[12]*t,n[13]=e[13]*t,n[14]=e[14]*t,n[15]=e[15]*t,n},mulMat4v4:function(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:Z.vec4(),r=t[0],i=t[1],a=t[2],s=t[3];return n[0]=e[0]*r+e[4]*i+e[8]*a+e[12]*s,n[1]=e[1]*r+e[5]*i+e[9]*a+e[13]*s,n[2]=e[2]*r+e[6]*i+e[10]*a+e[14]*s,n[3]=e[3]*r+e[7]*i+e[11]*a+e[15]*s,n},transposeMat4:function(e,t){var n=e[4],r=e[14],i=e[8],a=e[13],s=e[12],o=e[9];if(!t||e===t){var l=e[1],u=e[2],c=e[3],f=e[6],p=e[7],A=e[11];return e[1]=n,e[2]=i,e[3]=s,e[4]=l,e[6]=o,e[7]=a,e[8]=u,e[9]=f,e[11]=r,e[12]=c,e[13]=p,e[14]=A,e}return t[0]=e[0],t[1]=n,t[2]=i,t[3]=s,t[4]=e[1],t[5]=e[5],t[6]=o,t[7]=a,t[8]=e[2],t[9]=e[6],t[10]=e[10],t[11]=r,t[12]=e[3],t[13]=e[7],t[14]=e[11],t[15]=e[15],t},transposeMat3:function(e,t){if(t===e){var n=e[1],r=e[2],i=e[5];t[1]=e[3],t[2]=e[6],t[3]=n,t[5]=e[7],t[6]=r,t[7]=i}else t[0]=e[0],t[1]=e[3],t[2]=e[6],t[3]=e[1],t[4]=e[4],t[5]=e[7],t[6]=e[2],t[7]=e[5],t[8]=e[8];return t},determinantMat4:function(e){var t=e[0],n=e[1],r=e[2],i=e[3],a=e[4],s=e[5],o=e[6],l=e[7],u=e[8],c=e[9],f=e[10],p=e[11],A=e[12],d=e[13],v=e[14],h=e[15];return A*c*o*i-u*d*o*i-A*s*f*i+a*d*f*i+u*s*v*i-a*c*v*i-A*c*r*l+u*d*r*l+A*n*f*l-t*d*f*l-u*n*v*l+t*c*v*l+A*s*r*p-a*d*r*p-A*n*o*p+t*d*o*p+a*n*v*p-t*s*v*p-u*s*r*h+a*c*r*h+u*n*o*h-t*c*o*h-a*n*f*h+t*s*f*h},inverseMat4:function(e,t){t||(t=e);var n=e[0],r=e[1],i=e[2],a=e[3],s=e[4],o=e[5],l=e[6],u=e[7],c=e[8],f=e[9],p=e[10],A=e[11],d=e[12],v=e[13],h=e[14],I=e[15],y=n*o-r*s,m=n*l-i*s,w=n*u-a*s,g=r*l-i*o,T=r*u-a*o,E=i*u-a*l,b=c*v-f*d,D=c*h-p*d,P=c*I-A*d,R=f*h-p*v,C=f*I-A*v,_=p*I-A*h,B=1/(y*_-m*C+w*R+g*P-T*D+E*b);return t[0]=(o*_-l*C+u*R)*B,t[1]=(-r*_+i*C-a*R)*B,t[2]=(v*E-h*T+I*g)*B,t[3]=(-f*E+p*T-A*g)*B,t[4]=(-s*_+l*P-u*D)*B,t[5]=(n*_-i*P+a*D)*B,t[6]=(-d*E+h*w-I*m)*B,t[7]=(c*E-p*w+A*m)*B,t[8]=(s*C-o*P+u*b)*B,t[9]=(-n*C+r*P-a*b)*B,t[10]=(d*T-v*w+I*y)*B,t[11]=(-c*T+f*w-A*y)*B,t[12]=(-s*R+o*D-l*b)*B,t[13]=(n*R-r*D+i*b)*B,t[14]=(-d*g+v*m-h*y)*B,t[15]=(c*g-f*m+p*y)*B,t},traceMat4:function(e){return e[0]+e[5]+e[10]+e[15]},translationMat4v:function(e,t){var n=t||Z.identityMat4();return n[12]=e[0],n[13]=e[1],n[14]=e[2],n},translationMat3v:function(e,t){var n=t||Z.identityMat3();return n[6]=e[0],n[7]=e[1],n},translationMat4c:(H=new Y(3),function(e,t,n,r){return H[0]=e,H[1]=t,H[2]=n,Z.translationMat4v(H,r)}),translationMat4s:function(e,t){return Z.translationMat4c(e,e,e,t)},translateMat4v:function(e,t){return Z.translateMat4c(e[0],e[1],e[2],t)},translateMat4c:function(e,t,n,r){var i=r[3];r[0]+=i*e,r[1]+=i*t,r[2]+=i*n;var a=r[7];r[4]+=a*e,r[5]+=a*t,r[6]+=a*n;var s=r[11];r[8]+=s*e,r[9]+=s*t,r[10]+=s*n;var o=r[15];return r[12]+=o*e,r[13]+=o*t,r[14]+=o*n,r},setMat4Translation:function(e,t,n){return n[0]=e[0],n[1]=e[1],n[2]=e[2],n[3]=e[3],n[4]=e[4],n[5]=e[5],n[6]=e[6],n[7]=e[7],n[8]=e[8],n[9]=e[9],n[10]=e[10],n[11]=e[11],n[12]=t[0],n[13]=t[1],n[14]=t[2],n[15]=e[15],n},rotationMat4v:function(e,t,n){var r,i,a,s,o,l,u=Z.normalizeVec4([t[0],t[1],t[2],0],[]),c=Math.sin(e),f=Math.cos(e),p=1-f,A=u[0],d=u[1],v=u[2];return r=A*d,i=d*v,a=v*A,s=A*c,o=d*c,l=v*c,(n=n||Z.mat4())[0]=p*A*A+f,n[1]=p*r+l,n[2]=p*a-o,n[3]=0,n[4]=p*r-l,n[5]=p*d*d+f,n[6]=p*i+s,n[7]=0,n[8]=p*a+o,n[9]=p*i-s,n[10]=p*v*v+f,n[11]=0,n[12]=0,n[13]=0,n[14]=0,n[15]=1,n},rotationMat4c:function(e,t,n,r,i){return Z.rotationMat4v(e,[t,n,r],i)},scalingMat4v:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Z.identityMat4();return t[0]=e[0],t[5]=e[1],t[10]=e[2],t},scalingMat3v:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Z.identityMat3();return t[0]=e[0],t[4]=e[1],t},scalingMat4c:function(){var e=new Y(3);return function(t,n,r,i){return e[0]=t,e[1]=n,e[2]=r,Z.scalingMat4v(e,i)}}(),scaleMat4c:function(e,t,n,r){return r[0]*=e,r[4]*=t,r[8]*=n,r[1]*=e,r[5]*=t,r[9]*=n,r[2]*=e,r[6]*=t,r[10]*=n,r[3]*=e,r[7]*=t,r[11]*=n,r},scaleMat4v:function(e,t){var n=e[0],r=e[1],i=e[2];return t[0]*=n,t[4]*=r,t[8]*=i,t[1]*=n,t[5]*=r,t[9]*=i,t[2]*=n,t[6]*=r,t[10]*=i,t[3]*=n,t[7]*=r,t[11]*=i,t},scalingMat4s:function(e){return Z.scalingMat4c(e,e,e)},rotationTranslationMat4:function(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:Z.mat4(),r=e[0],i=e[1],a=e[2],s=e[3],o=r+r,l=i+i,u=a+a,c=r*o,f=r*l,p=r*u,A=i*l,d=i*u,v=a*u,h=s*o,I=s*l,y=s*u;return n[0]=1-(A+v),n[1]=f+y,n[2]=p-I,n[3]=0,n[4]=f-y,n[5]=1-(c+v),n[6]=d+h,n[7]=0,n[8]=p+I,n[9]=d-h,n[10]=1-(c+A),n[11]=0,n[12]=t[0],n[13]=t[1],n[14]=t[2],n[15]=1,n},mat4ToEuler:function(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:Z.vec4(),r=Z.clamp,i=e[0],a=e[4],s=e[8],o=e[1],l=e[5],u=e[9],c=e[2],f=e[6],p=e[10];return"XYZ"===t?(n[1]=Math.asin(r(s,-1,1)),Math.abs(s)<.99999?(n[0]=Math.atan2(-u,p),n[2]=Math.atan2(-a,i)):(n[0]=Math.atan2(f,l),n[2]=0)):"YXZ"===t?(n[0]=Math.asin(-r(u,-1,1)),Math.abs(u)<.99999?(n[1]=Math.atan2(s,p),n[2]=Math.atan2(o,l)):(n[1]=Math.atan2(-c,i),n[2]=0)):"ZXY"===t?(n[0]=Math.asin(r(f,-1,1)),Math.abs(f)<.99999?(n[1]=Math.atan2(-c,p),n[2]=Math.atan2(-a,l)):(n[1]=0,n[2]=Math.atan2(o,i))):"ZYX"===t?(n[1]=Math.asin(-r(c,-1,1)),Math.abs(c)<.99999?(n[0]=Math.atan2(f,p),n[2]=Math.atan2(o,i)):(n[0]=0,n[2]=Math.atan2(-a,l))):"YZX"===t?(n[2]=Math.asin(r(o,-1,1)),Math.abs(o)<.99999?(n[0]=Math.atan2(-u,l),n[1]=Math.atan2(-c,i)):(n[0]=0,n[1]=Math.atan2(s,p))):"XZY"===t&&(n[2]=Math.asin(-r(a,-1,1)),Math.abs(a)<.99999?(n[0]=Math.atan2(f,l),n[1]=Math.atan2(s,i)):(n[0]=Math.atan2(-u,p),n[1]=0)),n},composeMat4:function(e,t,n){var r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:Z.mat4();return Z.quaternionToRotationMat4(t,r),Z.scaleMat4v(n,r),Z.translateMat4v(e,r),r},decomposeMat4:function(){var e=new Y(3),t=new Y(16);return function(n,r,i,a){e[0]=n[0],e[1]=n[1],e[2]=n[2];var s=Z.lenVec3(e);e[0]=n[4],e[1]=n[5],e[2]=n[6];var o=Z.lenVec3(e);e[8]=n[8],e[9]=n[9],e[10]=n[10];var l=Z.lenVec3(e);Z.determinantMat4(n)<0&&(s=-s),r[0]=n[12],r[1]=n[13],r[2]=n[14],t.set(n);var u=1/s,c=1/o,f=1/l;return t[0]*=u,t[1]*=u,t[2]*=u,t[4]*=c,t[5]*=c,t[6]*=c,t[8]*=f,t[9]*=f,t[10]*=f,Z.mat4ToQuaternion(t,i),a[0]=s,a[1]=o,a[2]=l,this}}(),getColMat4:function(e,t){var n=4*t;return[e[n],e[n+1],e[n+2],e[n+3]]},setRowMat4:function(e,t,n){e[t]=n[0],e[t+4]=n[1],e[t+8]=n[2],e[t+12]=n[3]},lookAtMat4v:function(e,t,n,r){r||(r=Z.mat4());var i,a,s,o,l,u,c,f,p,A,d=e[0],v=e[1],h=e[2],I=n[0],y=n[1],m=n[2],w=t[0],g=t[1],T=t[2];return d===w&&v===g&&h===T?Z.identityMat4():(i=d-w,a=v-g,s=h-T,o=y*(s*=A=1/Math.sqrt(i*i+a*a+s*s))-m*(a*=A),l=m*(i*=A)-I*s,u=I*a-y*i,(A=Math.sqrt(o*o+l*l+u*u))?(o*=A=1/A,l*=A,u*=A):(o=0,l=0,u=0),c=a*u-s*l,f=s*o-i*u,p=i*l-a*o,(A=Math.sqrt(c*c+f*f+p*p))?(c*=A=1/A,f*=A,p*=A):(c=0,f=0,p=0),r[0]=o,r[1]=c,r[2]=i,r[3]=0,r[4]=l,r[5]=f,r[6]=a,r[7]=0,r[8]=u,r[9]=p,r[10]=s,r[11]=0,r[12]=-(o*d+l*v+u*h),r[13]=-(c*d+f*v+p*h),r[14]=-(i*d+a*v+s*h),r[15]=1,r)},lookAtMat4c:function(e,t,n,r,i,a,s,o,l){return Z.lookAtMat4v([e,t,n],[r,i,a],[s,o,l],[])},orthoMat4c:function(e,t,n,r,i,a,s){s||(s=Z.mat4());var o=t-e,l=r-n,u=a-i;return s[0]=2/o,s[1]=0,s[2]=0,s[3]=0,s[4]=0,s[5]=2/l,s[6]=0,s[7]=0,s[8]=0,s[9]=0,s[10]=-2/u,s[11]=0,s[12]=-(e+t)/o,s[13]=-(r+n)/l,s[14]=-(a+i)/u,s[15]=1,s},frustumMat4v:function(e,t,n){n||(n=Z.mat4());var r=[e[0],e[1],e[2],0],i=[t[0],t[1],t[2],0];Z.addVec4(i,r,X),Z.subVec4(i,r,q);var a=2*r[2],s=q[0],o=q[1],l=q[2];return n[0]=a/s,n[1]=0,n[2]=0,n[3]=0,n[4]=0,n[5]=a/o,n[6]=0,n[7]=0,n[8]=X[0]/s,n[9]=X[1]/o,n[10]=-X[2]/l,n[11]=-1,n[12]=0,n[13]=0,n[14]=-a*i[2]/l,n[15]=0,n},frustumMat4:function(e,t,n,r,i,a,s){s||(s=Z.mat4());var o=t-e,l=r-n,u=a-i;return s[0]=2*i/o,s[1]=0,s[2]=0,s[3]=0,s[4]=0,s[5]=2*i/l,s[6]=0,s[7]=0,s[8]=(t+e)/o,s[9]=(r+n)/l,s[10]=-(a+i)/u,s[11]=-1,s[12]=0,s[13]=0,s[14]=-a*i*2/u,s[15]=0,s},perspectiveMat4:function(e,t,n,r,i){var a=[],s=[];return a[2]=n,s[2]=r,s[1]=a[2]*Math.tan(e/2),a[1]=-s[1],s[0]=s[1]*t,a[0]=-s[0],Z.frustumMat4v(a,s,i)},compareMat4:function(e,t){return e[0]===t[0]&&e[1]===t[1]&&e[2]===t[2]&&e[3]===t[3]&&e[4]===t[4]&&e[5]===t[5]&&e[6]===t[6]&&e[7]===t[7]&&e[8]===t[8]&&e[9]===t[9]&&e[10]===t[10]&&e[11]===t[11]&&e[12]===t[12]&&e[13]===t[13]&&e[14]===t[14]&&e[15]===t[15]},transformPoint3:function(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:Z.vec3(),r=t[0],i=t[1],a=t[2];return n[0]=e[0]*r+e[4]*i+e[8]*a+e[12],n[1]=e[1]*r+e[5]*i+e[9]*a+e[13],n[2]=e[2]*r+e[6]*i+e[10]*a+e[14],n},transformPoint4:function(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:Z.vec4();return n[0]=e[0]*t[0]+e[4]*t[1]+e[8]*t[2]+e[12]*t[3],n[1]=e[1]*t[0]+e[5]*t[1]+e[9]*t[2]+e[13]*t[3],n[2]=e[2]*t[0]+e[6]*t[1]+e[10]*t[2]+e[14]*t[3],n[3]=e[3]*t[0]+e[7]*t[1]+e[11]*t[2]+e[15]*t[3],n},transformPoints3:function(e,t,n){for(var r,i,a,s,o,l=n||[],u=t.length,c=e[0],f=e[1],p=e[2],A=e[3],d=e[4],v=e[5],h=e[6],I=e[7],y=e[8],m=e[9],w=e[10],g=e[11],T=e[12],E=e[13],b=e[14],D=e[15],P=0;P<u;++P)r=(s=t[P])[0],i=s[1],a=s[2],(o=l[P]||(l[P]=[0,0,0]))[0]=c*r+d*i+y*a+T,o[1]=f*r+v*i+m*a+E,o[2]=p*r+h*i+w*a+b,o[3]=A*r+I*i+g*a+D;return l.length=u,l},transformPositions3:function(e,t){var n,r,i,a,s=arguments.length>2&&void 0!==arguments[2]?arguments[2]:t,o=t.length,l=e[0],u=e[1],c=e[2];e[3];var f=e[4],p=e[5],A=e[6];e[7];var d=e[8],v=e[9],h=e[10];e[11];var I=e[12],y=e[13],m=e[14];for(e[15],n=0;n<o;n+=3)r=t[n+0],i=t[n+1],a=t[n+2],s[n+0]=l*r+f*i+d*a+I,s[n+1]=u*r+p*i+v*a+y,s[n+2]=c*r+A*i+h*a+m;return s},transformPositions4:function(e,t){var n,r,i,a,s=arguments.length>2&&void 0!==arguments[2]?arguments[2]:t,o=t.length,l=e[0],u=e[1],c=e[2],f=e[3],p=e[4],A=e[5],d=e[6],v=e[7],h=e[8],I=e[9],y=e[10],m=e[11],w=e[12],g=e[13],T=e[14],E=e[15];for(n=0;n<o;n+=4)r=t[n+0],i=t[n+1],a=t[n+2],s[n+0]=l*r+p*i+h*a+w,s[n+1]=u*r+A*i+I*a+g,s[n+2]=c*r+d*i+y*a+T,s[n+3]=f*r+v*i+m*a+E;return s},transformVec3:function(e,t,n){var r=t[0],i=t[1],a=t[2];return(n=n||this.vec3())[0]=e[0]*r+e[4]*i+e[8]*a,n[1]=e[1]*r+e[5]*i+e[9]*a,n[2]=e[2]*r+e[6]*i+e[10]*a,n},transformVec4:function(e,t,n){var r=t[0],i=t[1],a=t[2],s=t[3];return(n=n||Z.vec4())[0]=e[0]*r+e[4]*i+e[8]*a+e[12]*s,n[1]=e[1]*r+e[5]*i+e[9]*a+e[13]*s,n[2]=e[2]*r+e[6]*i+e[10]*a+e[14]*s,n[3]=e[3]*r+e[7]*i+e[11]*a+e[15]*s,n},rotateVec2:function(e,t,n){var r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:e,i=Math.cos(n),a=Math.sin(n),s=e[0]-t[0],o=e[1]-t[1];return r[0]=s*i-o*a+t[0],r[1]=s*a+o*i+t[1],e},rotateVec3X:function(e,t,n,r){var i=[],a=[];return i[0]=e[0]-t[0],i[1]=e[1]-t[1],i[2]=e[2]-t[2],a[0]=i[0],a[1]=i[1]*Math.cos(n)-i[2]*Math.sin(n),a[2]=i[1]*Math.sin(n)+i[2]*Math.cos(n),r[0]=a[0]+t[0],r[1]=a[1]+t[1],r[2]=a[2]+t[2],r},rotateVec3Y:function(e,t,n,r){var i=[],a=[];return i[0]=e[0]-t[0],i[1]=e[1]-t[1],i[2]=e[2]-t[2],a[0]=i[2]*Math.sin(n)+i[0]*Math.cos(n),a[1]=i[1],a[2]=i[2]*Math.cos(n)-i[0]*Math.sin(n),r[0]=a[0]+t[0],r[1]=a[1]+t[1],r[2]=a[2]+t[2],r},rotateVec3Z:function(e,t,n,r){var i=[],a=[];return i[0]=e[0]-t[0],i[1]=e[1]-t[1],i[2]=e[2]-t[2],a[0]=i[0]*Math.cos(n)-i[1]*Math.sin(n),a[1]=i[0]*Math.sin(n)+i[1]*Math.cos(n),a[2]=i[2],r[0]=a[0]+t[0],r[1]=a[1]+t[1],r[2]=a[2]+t[2],r},projectVec4:function(e,t){var n=1/e[3];return(t=t||Z.vec2())[0]=e[0]*n,t[1]=e[1]*n,t},unprojectVec3:(x=new Y(16),M=new Y(16),F=new Y(16),function(e,t,n,r){return this.transformVec3(this.mulMat4(this.inverseMat4(t,x),this.inverseMat4(n,M),F),e,r)}),lerpVec3:function(e,t,n,r,i,a){var s=a||Z.vec3(),o=(e-t)/(n-t);return s[0]=r[0]+o*(i[0]-r[0]),s[1]=r[1]+o*(i[1]-r[1]),s[2]=r[2]+o*(i[2]-r[2]),s},lerpMat4:function(e,t,n,r,i,a){var s=a||Z.mat4(),o=(e-t)/(n-t);return s[0]=r[0]+o*(i[0]-r[0]),s[1]=r[1]+o*(i[1]-r[1]),s[2]=r[2]+o*(i[2]-r[2]),s[3]=r[3]+o*(i[3]-r[3]),s[4]=r[4]+o*(i[4]-r[4]),s[5]=r[5]+o*(i[5]-r[5]),s[6]=r[6]+o*(i[6]-r[6]),s[7]=r[7]+o*(i[7]-r[7]),s[8]=r[8]+o*(i[8]-r[8]),s[9]=r[9]+o*(i[9]-r[9]),s[10]=r[10]+o*(i[10]-r[10]),s[11]=r[11]+o*(i[11]-r[11]),s[12]=r[12]+o*(i[12]-r[12]),s[13]=r[13]+o*(i[13]-r[13]),s[14]=r[14]+o*(i[14]-r[14]),s[15]=r[15]+o*(i[15]-r[15]),s},flatten:function(e){var t,n,r,i,a,s=[];for(t=0,n=e.length;t<n;t++)for(r=0,i=(a=e[t]).length;r<i;r++)s.push(a[r]);return s},identityQuaternion:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:Z.vec4();return e[0]=0,e[1]=0,e[2]=0,e[3]=1,e},eulerToQuaternion:function(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:Z.vec4(),r=e[0]*Z.DEGTORAD/2,i=e[1]*Z.DEGTORAD/2,a=e[2]*Z.DEGTORAD/2,s=Math.cos(r),o=Math.cos(i),l=Math.cos(a),u=Math.sin(r),c=Math.sin(i),f=Math.sin(a);return"XYZ"===t?(n[0]=u*o*l+s*c*f,n[1]=s*c*l-u*o*f,n[2]=s*o*f+u*c*l,n[3]=s*o*l-u*c*f):"YXZ"===t?(n[0]=u*o*l+s*c*f,n[1]=s*c*l-u*o*f,n[2]=s*o*f-u*c*l,n[3]=s*o*l+u*c*f):"ZXY"===t?(n[0]=u*o*l-s*c*f,n[1]=s*c*l+u*o*f,n[2]=s*o*f+u*c*l,n[3]=s*o*l-u*c*f):"ZYX"===t?(n[0]=u*o*l-s*c*f,n[1]=s*c*l+u*o*f,n[2]=s*o*f-u*c*l,n[3]=s*o*l+u*c*f):"YZX"===t?(n[0]=u*o*l+s*c*f,n[1]=s*c*l+u*o*f,n[2]=s*o*f-u*c*l,n[3]=s*o*l-u*c*f):"XZY"===t&&(n[0]=u*o*l-s*c*f,n[1]=s*c*l-u*o*f,n[2]=s*o*f+u*c*l,n[3]=s*o*l+u*c*f),n},mat4ToQuaternion:function(e){var t,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Z.vec4(),r=e[0],i=e[4],a=e[8],s=e[1],o=e[5],l=e[9],u=e[2],c=e[6],f=e[10],p=r+o+f;return p>0?(t=.5/Math.sqrt(p+1),n[3]=.25/t,n[0]=(c-l)*t,n[1]=(a-u)*t,n[2]=(s-i)*t):r>o&&r>f?(t=2*Math.sqrt(1+r-o-f),n[3]=(c-l)/t,n[0]=.25*t,n[1]=(i+s)/t,n[2]=(a+u)/t):o>f?(t=2*Math.sqrt(1+o-r-f),n[3]=(a-u)/t,n[0]=(i+s)/t,n[1]=.25*t,n[2]=(l+c)/t):(t=2*Math.sqrt(1+f-r-o),n[3]=(s-i)/t,n[0]=(a+u)/t,n[1]=(l+c)/t,n[2]=.25*t),n},vec3PairToQuaternion:function(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:Z.vec4(),r=Math.sqrt(Z.dotVec3(e,e)*Z.dotVec3(t,t)),i=r+Z.dotVec3(e,t);return i<1e-8*r?(i=0,Math.abs(e[0])>Math.abs(e[2])?(n[0]=-e[1],n[1]=e[0],n[2]=0):(n[0]=0,n[1]=-e[2],n[2]=e[1])):Z.cross3Vec3(e,t,n),n[3]=i,Z.normalizeQuaternion(n)},angleAxisToQuaternion:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Z.vec4(),n=e[3]/2,r=Math.sin(n);return t[0]=r*e[0],t[1]=r*e[1],t[2]=r*e[2],t[3]=Math.cos(n),t},quaternionToEuler:function(){var e=new Y(16);return function(t,n,r){return r=r||Z.vec3(),Z.quaternionToRotationMat4(t,e),Z.mat4ToEuler(e,n,r),r}}(),mulQuaternions:function(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:Z.vec4(),r=e[0],i=e[1],a=e[2],s=e[3],o=t[0],l=t[1],u=t[2],c=t[3];return n[0]=s*o+r*c+i*u-a*l,n[1]=s*l+i*c+a*o-r*u,n[2]=s*u+a*c+r*l-i*o,n[3]=s*c-r*o-i*l-a*u,n},vec3ApplyQuaternion:function(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:Z.vec3(),r=t[0],i=t[1],a=t[2],s=e[0],o=e[1],l=e[2],u=e[3],c=u*r+o*a-l*i,f=u*i+l*r-s*a,p=u*a+s*i-o*r,A=-s*r-o*i-l*a;return n[0]=c*u+A*-s+f*-l-p*-o,n[1]=f*u+A*-o+p*-s-c*-l,n[2]=p*u+A*-l+c*-o-f*-s,n},quaternionToMat4:function(e,t){t=Z.identityMat4(t);var n=e[0],r=e[1],i=e[2],a=e[3],s=2*n,o=2*r,l=2*i,u=s*a,c=o*a,f=l*a,p=s*n,A=o*n,d=l*n,v=o*r,h=l*r,I=l*i;return t[0]=1-(v+I),t[1]=A+f,t[2]=d-c,t[4]=A-f,t[5]=1-(p+I),t[6]=h+u,t[8]=d+c,t[9]=h-u,t[10]=1-(p+v),t},quaternionToRotationMat4:function(e,t){var n=e[0],r=e[1],i=e[2],a=e[3],s=n+n,o=r+r,l=i+i,u=n*s,c=n*o,f=n*l,p=r*o,A=r*l,d=i*l,v=a*s,h=a*o,I=a*l;return t[0]=1-(p+d),t[4]=c-I,t[8]=f+h,t[1]=c+I,t[5]=1-(u+d),t[9]=A-v,t[2]=f-h,t[6]=A+v,t[10]=1-(u+p),t[3]=0,t[7]=0,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t},normalizeQuaternion:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:e,n=Z.lenVec4([e[0],e[1],e[2],e[3]]);return t[0]=e[0]/n,t[1]=e[1]/n,t[2]=e[2]/n,t[3]=e[3]/n,t},conjugateQuaternion:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:e;return t[0]=-e[0],t[1]=-e[1],t[2]=-e[2],t[3]=e[3],t},inverseQuaternion:function(e,t){return Z.normalizeQuaternion(Z.conjugateQuaternion(e,t))},quaternionToAngleAxis:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Z.vec4(),n=(e=Z.normalizeQuaternion(e,J))[3],r=2*Math.acos(n),i=Math.sqrt(1-n*n);return i<.001?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=e[0]/i,t[1]=e[1]/i,t[2]=e[2]/i),t[3]=r,t},AABB3:function(e){return new Y(e||6)},AABB2:function(e){return new Y(e||4)},OBB3:function(e){return new Y(e||32)},OBB2:function(e){return new Y(e||16)},Sphere3:function(e,t,n,r){return new Y([e,t,n,r])},transformOBB3:function(e,t){var n,r,i,a,s=arguments.length>2&&void 0!==arguments[2]?arguments[2]:t,o=t.length,l=e[0],u=e[1],c=e[2],f=e[3],p=e[4],A=e[5],d=e[6],v=e[7],h=e[8],I=e[9],y=e[10],m=e[11],w=e[12],g=e[13],T=e[14],E=e[15];for(n=0;n<o;n+=4)r=t[n+0],i=t[n+1],a=t[n+2],s[n+0]=l*r+p*i+h*a+w,s[n+1]=u*r+A*i+I*a+g,s[n+2]=c*r+d*i+y*a+T,s[n+3]=f*r+v*i+m*a+E;return s},containsAABB3:function(e,t){return e[0]<=t[0]&&t[3]<=e[3]&&e[1]<=t[1]&&t[4]<=e[4]&&e[2]<=t[2]&&t[5]<=e[5]},getAABB3Diag:function(){var e=new Y(3),t=new Y(3),n=new Y(3);return function(r){return e[0]=r[0],e[1]=r[1],e[2]=r[2],t[0]=r[3],t[1]=r[4],t[2]=r[5],Z.subVec3(t,e,n),Math.abs(Z.lenVec3(n))}}(),getAABB3DiagPoint:function(){var e=new Y(3),t=new Y(3),n=new Y(3);return function(r,i){e[0]=r[0],e[1]=r[1],e[2]=r[2],t[0]=r[3],t[1]=r[4],t[2]=r[5];var a=Z.subVec3(t,e,n),s=i[0]-r[0],o=r[3]-i[0],l=i[1]-r[1],u=r[4]-i[1],c=i[2]-r[2],f=r[5]-i[2];return a[0]+=s>o?s:o,a[1]+=l>u?l:u,a[2]+=c>f?c:f,Math.abs(Z.lenVec3(a))}}(),getAABB3Area:function(e){return(e[3]-e[0])*(e[4]-e[1])*(e[5]-e[2])},getAABB3Center:function(e,t){var n=t||Z.vec3();return n[0]=(e[0]+e[3])/2,n[1]=(e[1]+e[4])/2,n[2]=(e[2]+e[5])/2,n},getAABB2Center:function(e,t){var n=t||Z.vec2();return n[0]=(e[2]+e[0])/2,n[1]=(e[3]+e[1])/2,n},collapseAABB3:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:Z.AABB3();return e[0]=Z.MAX_DOUBLE,e[1]=Z.MAX_DOUBLE,e[2]=Z.MAX_DOUBLE,e[3]=Z.MIN_DOUBLE,e[4]=Z.MIN_DOUBLE,e[5]=Z.MIN_DOUBLE,e},AABB3ToOBB3:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Z.OBB3();return t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=1,t[4]=e[3],t[5]=e[1],t[6]=e[2],t[7]=1,t[8]=e[3],t[9]=e[4],t[10]=e[2],t[11]=1,t[12]=e[0],t[13]=e[4],t[14]=e[2],t[15]=1,t[16]=e[0],t[17]=e[1],t[18]=e[5],t[19]=1,t[20]=e[3],t[21]=e[1],t[22]=e[5],t[23]=1,t[24]=e[3],t[25]=e[4],t[26]=e[5],t[27]=1,t[28]=e[0],t[29]=e[4],t[30]=e[5],t[31]=1,t},positions3ToAABB3:function(){var e=new Y(3);return function(t,n,r){n=n||Z.AABB3();for(var i,a,s,o=Z.MAX_DOUBLE,l=Z.MAX_DOUBLE,u=Z.MAX_DOUBLE,c=Z.MIN_DOUBLE,f=Z.MIN_DOUBLE,p=Z.MIN_DOUBLE,A=0,d=t.length;A<d;A+=3)r?(e[0]=t[A+0],e[1]=t[A+1],e[2]=t[A+2],Z.decompressPosition(e,r,e),i=e[0],a=e[1],s=e[2]):(i=t[A+0],a=t[A+1],s=t[A+2]),i<o&&(o=i),a<l&&(l=a),s<u&&(u=s),i>c&&(c=i),a>f&&(f=a),s>p&&(p=s);return n[0]=o,n[1]=l,n[2]=u,n[3]=c,n[4]=f,n[5]=p,n}}(),OBB3ToAABB3:function(e){for(var t,n,r,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Z.AABB3(),a=Z.MAX_DOUBLE,s=Z.MAX_DOUBLE,o=Z.MAX_DOUBLE,l=Z.MIN_DOUBLE,u=Z.MIN_DOUBLE,c=Z.MIN_DOUBLE,f=0,p=e.length;f<p;f+=4)(t=e[f+0])<a&&(a=t),(n=e[f+1])<s&&(s=n),(r=e[f+2])<o&&(o=r),t>l&&(l=t),n>u&&(u=n),r>c&&(c=r);return i[0]=a,i[1]=s,i[2]=o,i[3]=l,i[4]=u,i[5]=c,i},points3ToAABB3:function(e){for(var t,n,r,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Z.AABB3(),a=Z.MAX_DOUBLE,s=Z.MAX_DOUBLE,o=Z.MAX_DOUBLE,l=Z.MIN_DOUBLE,u=Z.MIN_DOUBLE,c=Z.MIN_DOUBLE,f=0,p=e.length;f<p;f++)(t=e[f][0])<a&&(a=t),(n=e[f][1])<s&&(s=n),(r=e[f][2])<o&&(o=r),t>l&&(l=t),n>u&&(u=n),r>c&&(c=r);return i[0]=a,i[1]=s,i[2]=o,i[3]=l,i[4]=u,i[5]=c,i},points3ToSphere3:function(){var e=new Y(3);return function(t,n){n=n||Z.vec4();var r,i=0,a=0,s=0,o=t.length;for(r=0;r<o;r++)i+=t[r][0],a+=t[r][1],s+=t[r][2];n[0]=i/o,n[1]=a/o,n[2]=s/o;var l,u=0;for(r=0;r<o;r++)(l=Math.abs(Z.lenVec3(Z.subVec3(t[r],n,e))))>u&&(u=l);return n[3]=u,n}}(),positions3ToSphere3:function(){var e=new Y(3),t=new Y(3);return function(n,r){r=r||Z.vec4();var i,a=0,s=0,o=0,l=n.length,u=0;for(i=0;i<l;i+=3)a+=n[i],s+=n[i+1],o+=n[i+2];var c,f=l/3;for(r[0]=a/f,r[1]=s/f,r[2]=o/f,i=0;i<l;i+=3)e[0]=n[i],e[1]=n[i+1],e[2]=n[i+2],(c=Math.abs(Z.lenVec3(Z.subVec3(e,r,t))))>u&&(u=c);return r[3]=u,r}}(),OBB3ToSphere3:function(){var e=new Y(3),t=new Y(3);return function(n,r){r=r||Z.vec4();var i,a=0,s=0,o=0,l=n.length,u=l/4;for(i=0;i<l;i+=4)a+=n[i+0],s+=n[i+1],o+=n[i+2];r[0]=a/u,r[1]=s/u,r[2]=o/u;var c,f=0;for(i=0;i<l;i+=4)e[0]=n[i+0],e[1]=n[i+1],e[2]=n[i+2],(c=Math.abs(Z.lenVec3(Z.subVec3(e,r,t))))>f&&(f=c);return r[3]=f,r}}(),getSphere3Center:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Z.vec3();return t[0]=e[0],t[1]=e[1],t[2]=e[2],t},getPositionsCenter:function(e){for(var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Z.vec3(),n=0,r=0,i=0,a=0,s=e.length;a<s;a+=3)n+=e[a+0],r+=e[a+1],i+=e[a+2];var o=e.length/3;return t[0]=n/o,t[1]=r/o,t[2]=i/o,t},expandAABB3:function(e,t){return e[0]>t[0]&&(e[0]=t[0]),e[1]>t[1]&&(e[1]=t[1]),e[2]>t[2]&&(e[2]=t[2]),e[3]<t[3]&&(e[3]=t[3]),e[4]<t[4]&&(e[4]=t[4]),e[5]<t[5]&&(e[5]=t[5]),e},expandAABB3Point3:function(e,t){return e[0]>t[0]&&(e[0]=t[0]),e[1]>t[1]&&(e[1]=t[1]),e[2]>t[2]&&(e[2]=t[2]),e[3]<t[0]&&(e[3]=t[0]),e[4]<t[1]&&(e[4]=t[1]),e[5]<t[2]&&(e[5]=t[2]),e},expandAABB3Points3:function(e,t){for(var n,r,i,a=0,s=t.length;a<s;a+=3)n=t[a],r=t[a+1],i=t[a+2],e[0]>n&&(e[0]=n),e[1]>r&&(e[1]=r),e[2]>i&&(e[2]=i),e[3]<n&&(e[3]=n),e[4]<r&&(e[4]=r),e[5]<i&&(e[5]=i);return e},collapseAABB2:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:Z.AABB2();return e[0]=Z.MAX_DOUBLE,e[1]=Z.MAX_DOUBLE,e[2]=Z.MIN_DOUBLE,e[3]=Z.MIN_DOUBLE,e},point3AABB3Intersect:function(e,t){return e[0]>t[0]||e[3]<t[0]||e[1]>t[1]||e[4]<t[1]||e[2]>t[2]||e[5]<t[2]},planeAABB3Intersect:function(e,t,n){var r,i;return e[0]>0?(r=e[0]*n[0],i=e[0]*n[3]):(r=e[0]*n[3],i=e[0]*n[0]),e[1]>0?(r+=e[1]*n[1],i+=e[1]*n[4]):(r+=e[1]*n[4],i+=e[1]*n[1]),e[2]>0?(r+=e[2]*n[2],i+=e[2]*n[5]):(r+=e[2]*n[5],i+=e[2]*n[2]),r<=-t&&i<=-t?-1:r>=-t&&i>=-t?1:0},OBB3ToAABB2:function(e){for(var t,n,r,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Z.AABB2(),a=Z.MAX_DOUBLE,s=Z.MAX_DOUBLE,o=Z.MIN_DOUBLE,l=Z.MIN_DOUBLE,u=0,c=e.length;u<c;u+=4)t=e[u+0],n=e[u+1],(t*=r=1/(e[u+3]||1))<a&&(a=t),(n*=r)<s&&(s=n),t>o&&(o=t),n>l&&(l=n);return i[0]=a,i[1]=s,i[2]=o,i[3]=l,i},expandAABB2:function(e,t){return e[0]>t[0]&&(e[0]=t[0]),e[1]>t[1]&&(e[1]=t[1]),e[2]<t[2]&&(e[2]=t[2]),e[3]<t[3]&&(e[3]=t[3]),e},expandAABB2Point2:function(e,t){return e[0]>t[0]&&(e[0]=t[0]),e[1]>t[1]&&(e[1]=t[1]),e[2]<t[0]&&(e[2]=t[0]),e[3]<t[1]&&(e[3]=t[1]),e},AABB2ToCanvas:function(e,t,n){var r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:e,i=.5*(e[0]+1),a=.5*(e[1]+1),s=.5*(e[2]+1),o=.5*(e[3]+1);return r[0]=Math.floor(i*t),r[1]=n-Math.floor(o*n),r[2]=Math.floor(s*t),r[3]=n-Math.floor(a*n),r},tangentQuadraticBezier:function(e,t,n,r){return 2*(1-e)*(n-t)+2*e*(r-n)},tangentQuadraticBezier3:function(e,t,n,r,i){return-3*t*(1-e)*(1-e)+3*n*(1-e)*(1-e)-6*e*n*(1-e)+6*e*r*(1-e)-3*e*e*r+3*e*e*i},tangentSpline:function(e){return 6*e*e-6*e+(3*e*e-4*e+1)+(-6*e*e+6*e)+(3*e*e-2*e)},catmullRomInterpolate:function(e,t,n,r,i){var a=.5*(n-e),s=.5*(r-t),o=i*i;return(2*t-2*n+a+s)*(i*o)+(-3*t+3*n-2*a-s)*o+a*i+t},b2p0:function(e,t){var n=1-e;return n*n*t},b2p1:function(e,t){return 2*(1-e)*e*t},b2p2:function(e,t){return e*e*t},b2:function(e,t,n,r){return this.b2p0(e,t)+this.b2p1(e,n)+this.b2p2(e,r)},b3p0:function(e,t){var n=1-e;return n*n*n*t},b3p1:function(e,t){var n=1-e;return 3*n*n*e*t},b3p2:function(e,t){return 3*(1-e)*e*e*t},b3p3:function(e,t){return e*e*e*t},b3:function(e,t,n,r,i){return this.b3p0(e,t)+this.b3p1(e,n)+this.b3p2(e,r)+this.b3p3(e,i)},triangleNormal:function(e,t,n){var r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:Z.vec3(),i=t[0]-e[0],a=t[1]-e[1],s=t[2]-e[2],o=n[0]-e[0],l=n[1]-e[1],u=n[2]-e[2],c=a*u-s*l,f=s*o-i*u,p=i*l-a*o,A=Math.sqrt(c*c+f*f+p*p);return 0===A?(r[0]=0,r[1]=0,r[2]=0):(r[0]=c/A,r[1]=f/A,r[2]=p/A),r},rayTriangleIntersect:function(){var e=new Y(3),t=new Y(3),n=new Y(3),r=new Y(3),i=new Y(3);return function(a,s,o,l,u,c){c=c||Z.vec3();var f=Z.subVec3(l,o,e),p=Z.subVec3(u,o,t),A=Z.cross3Vec3(s,p,n),d=Z.dotVec3(f,A);if(d<1e-6)return null;var v=Z.subVec3(a,o,r),h=Z.dotVec3(v,A);if(h<0||h>d)return null;var I=Z.cross3Vec3(v,f,i),y=Z.dotVec3(s,I);if(y<0||h+y>d)return null;var m=Z.dotVec3(p,I)/d;return c[0]=a[0]+m*s[0],c[1]=a[1]+m*s[1],c[2]=a[2]+m*s[2],c}}(),rayPlaneIntersect:function(){var e=new Y(3),t=new Y(3),n=new Y(3),r=new Y(3);return function(i,a,s,o,l,u){u=u||Z.vec3(),a=Z.normalizeVec3(a,e);var c=Z.subVec3(o,s,t),f=Z.subVec3(l,s,n),p=Z.cross3Vec3(c,f,r);Z.normalizeVec3(p,p);var A=-Z.dotVec3(s,p),d=-(Z.dotVec3(i,p)+A)/Z.dotVec3(a,p);return u[0]=i[0]+d*a[0],u[1]=i[1]+d*a[1],u[2]=i[2]+d*a[2],u}}(),cartesianToBarycentric:function(){var e=new Y(3),t=new Y(3),n=new Y(3);return function(r,i,a,s,o){var l=Z.subVec3(s,i,e),u=Z.subVec3(a,i,t),c=Z.subVec3(r,i,n),f=Z.dotVec3(l,l),p=Z.dotVec3(l,u),A=Z.dotVec3(l,c),d=Z.dotVec3(u,u),v=Z.dotVec3(u,c),h=f*d-p*p;if(0===h)return null;var I=1/h,y=(d*A-p*v)*I,m=(f*v-p*A)*I;return o[0]=1-y-m,o[1]=m,o[2]=y,o}}(),barycentricInsideTriangle:function(e){var t=e[1],n=e[2];return n>=0&&t>=0&&n+t<1},barycentricToCartesian:function(e,t,n,r){var i=arguments.length>4&&void 0!==arguments[4]?arguments[4]:Z.vec3(),a=e[0],s=e[1],o=e[2];return i[0]=t[0]*a+n[0]*s+r[0]*o,i[1]=t[1]*a+n[1]*s+r[1]*o,i[2]=t[2]*a+n[2]*s+r[2]*o,i},mergeVertices:function(e,t,n,r){var i,a,s,o,l,u,c={},f=[],p=[],A=t?[]:null,d=n?[]:null,v=[],h=Math.pow(10,4),I=0;for(l=0,u=e.length;l<u;l+=3)i=e[l],a=e[l+1],s=e[l+2],void 0===c[o="".concat(Math.round(i*h),"_").concat(Math.round(a*h),"_").concat(Math.round(s*h))]&&(c[o]=p.length/3,p.push(i),p.push(a),p.push(s),t&&(A.push(t[l]),A.push(t[l+1]),A.push(t[l+2])),n&&(d.push(n[I]),d.push(n[I+1]))),f[l/3]=c[o],I+=2;for(l=0,u=r.length;l<u;l++)v[l]=f[r[l]];var y={positions:p,indices:v};return A&&(y.normals=A),d&&(y.uv=d),y},buildNormals:function(){var e=new Y(3),t=new Y(3),n=new Y(3),r=new Y(3),i=new Y(3),a=new Y(3);return function(s,o,l){var u,c,f,p,A,d,v,h,I,y=new Array(s.length/3);for(u=0,c=o.length;u<c;u+=3){f=o[u],p=o[u+1],A=o[u+2],e[0]=s[3*f],e[1]=s[3*f+1],e[2]=s[3*f+2],t[0]=s[3*p],t[1]=s[3*p+1],t[2]=s[3*p+2],n[0]=s[3*A],n[1]=s[3*A+1],n[2]=s[3*A+2],Z.subVec3(t,e,r),Z.subVec3(n,e,i);var m=Z.vec3();Z.normalizeVec3(Z.cross3Vec3(r,i,a),m),y[f]||(y[f]=[]),y[p]||(y[p]=[]),y[A]||(y[A]=[]),y[f].push(m),y[p].push(m),y[A].push(m)}for(l=l&&l.length===s.length?l:new Float32Array(s.length),u=0,c=y.length;u<c;u++){d=y[u].length,v=0,h=0,I=0;for(var w=0;w<d;w++)v+=y[u][w][0],h+=y[u][w][1],I+=y[u][w][2];l[3*u]=v/d,l[3*u+1]=h/d,l[3*u+2]=I/d}return l}}(),buildTangents:function(){var e=new Y(3),t=new Y(3),n=new Y(3),r=new Y(3),i=new Y(3),a=new Y(3),s=new Y(3);return function(o,l,u){for(var c=new Float32Array(o.length),f=0;f<l.length;f+=3){var p=l[f],A=o.subarray(3*p,3*p+3),d=u.subarray(2*p,2*p+2);p=l[f+1];var v=o.subarray(3*p,3*p+3),h=u.subarray(2*p,2*p+2);p=l[f+2];for(var I=o.subarray(3*p,3*p+3),y=u.subarray(2*p,2*p+2),m=Z.subVec3(v,A,e),w=Z.subVec3(I,A,t),g=Z.subVec2(h,d,n),T=Z.subVec2(y,d,r),E=1/(g[0]*T[1]-g[1]*T[0]),b=Z.mulVec3Scalar(Z.subVec3(Z.mulVec3Scalar(m,T[1],i),Z.mulVec3Scalar(w,g[1],a),s),E,a),D=void 0,P=0;P<3;P++)c[D=3*l[f+P]]+=b[0],c[D+1]+=b[1],c[D+2]+=b[2]}return c}}(),buildPickTriangles:function(e,t,n){for(var r,i,a,s,o,l=t.length,u=n?new Uint16Array(9*l):new Float32Array(9*l),c=new Uint8Array(12*l),f=0,p=0,A=0,d=0;d<l;d+=3)o=f>>24&255,s=f>>16&255,a=f>>8&255,i=255&f,r=3*t[d],u[p++]=e[r],u[p++]=e[r+1],u[p++]=e[r+2],c[A++]=i,c[A++]=a,c[A++]=s,c[A++]=o,r=3*t[d+1],u[p++]=e[r],u[p++]=e[r+1],u[p++]=e[r+2],c[A++]=i,c[A++]=a,c[A++]=s,c[A++]=o,r=3*t[d+2],u[p++]=e[r],u[p++]=e[r+1],u[p++]=e[r+2],c[A++]=i,c[A++]=a,c[A++]=s,c[A++]=o,f++;return{positions:u,colors:c}},faceToVertexNormals:function(e,t){var n,r,i,a,s,o,l,u,c,f,p,A=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},d=A.smoothNormalsAngleThreshold||20,v={},h=[],I={},y=4,m=Math.pow(10,y);for(l=0,c=e.length;l<c;l+=3){o=l/3,r=e[l],i=e[l+1],a=e[l+2],void 0===v[s="".concat(Math.round(r*m),"_").concat(Math.round(i*m),"_").concat(Math.round(a*m))]?v[s]=[o]:v[s].push(o);var w=Z.normalizeVec3([t[l],t[l+1],t[l+2]]);h[o]=w,n=Z.vec4([w[0],w[1],w[2],1]),I[o]=n}for(s in v)if(v.hasOwnProperty(s)){var g=v[s],T=g.length;for(l=0;l<T;l++){var E=g[l];for(n=I[E],u=0;u<T;u++)if(l!==u){var b=g[u];f=h[E],p=h[b];var D=Math.abs(Z.angleVec3(f,p)/Z.DEGTORAD);D<d&&(n[0]+=p[0],n[1]+=p[1],n[2]+=p[2],n[3]+=1)}}}for(l=0,c=t.length;l<c;l+=3)n=I[l/3],t[l+0]=n[0]/n[3],t[l+1]=n[1]/n[3],t[l+2]=n[2]/n[3]},transformRay:function(){var e=new Y(4),t=new Y(4);return function(n,r,i,a,s){e[0]=r[0],e[1]=r[1],e[2]=r[2],e[3]=1,Z.transformVec4(n,e,t),a[0]=t[0],a[1]=t[1],a[2]=t[2],e[0]=i[0],e[1]=i[1],e[2]=i[2],Z.transformVec3(n,e,t),Z.normalizeVec3(t),s[0]=t[0],s[1]=t[1],s[2]=t[2]}}(),canvasPosToWorldRay:function(){var e=new Y(16),t=new Y(16),n=new Y(4),r=new Y(4),i=new Y(4),a=new Y(4);return function(s,o,l,u,c,f){var p=Z.mulMat4(l,o,e),A=Z.inverseMat4(p,t),d=s.width,v=s.height,h=(u[0]-d/2)/(d/2),I=-(u[1]-v/2)/(v/2);n[0]=h,n[1]=I,n[2]=-1,n[3]=1,Z.transformVec4(A,n,r),Z.mulVec4Scalar(r,1/r[3]),i[0]=h,i[1]=I,i[2]=1,i[3]=1,Z.transformVec4(A,i,a),Z.mulVec4Scalar(a,1/a[3]),c[0]=a[0],c[1]=a[1],c[2]=a[2],Z.subVec3(a,r,f),Z.normalizeVec3(f)}}(),canvasPosToLocalRay:(N=new Y(3),L=new Y(3),function(e,t,n,r,i,a,s){Z.canvasPosToWorldRay(e,t,n,i,N,L),Z.worldRayToLocalRay(r,N,L,a,s)}),worldRayToLocalRay:function(){var e=new Y(16),t=new Y(4),n=new Y(4);return function(r,i,a,s,o){var l=Z.inverseMat4(r,e);t[0]=i[0],t[1]=i[1],t[2]=i[2],t[3]=1,Z.transformVec4(l,t,n),s[0]=n[0],s[1]=n[1],s[2]=n[2],Z.transformVec3(l,a,o)}}(),buildKDTree:function(){var e=new Float32Array;function t(n,r,i,a){var s,o,l=new Y(6),u={triangles:null,left:null,right:null,leaf:!1,splitDim:0,aabb:l};for(l[0]=l[1]=l[2]=Number.POSITIVE_INFINITY,l[3]=l[4]=l[5]=Number.NEGATIVE_INFINITY,s=0,o=n.length;s<o;++s)for(var c=3*n[s],f=0;f<3;++f){var p=3*r[c+f];i[p]<l[0]&&(l[0]=i[p]),i[p]>l[3]&&(l[3]=i[p]),i[p+1]<l[1]&&(l[1]=i[p+1]),i[p+1]>l[4]&&(l[4]=i[p+1]),i[p+2]<l[2]&&(l[2]=i[p+2]),i[p+2]>l[5]&&(l[5]=i[p+2])}if(n.length<20||a>10)return u.triangles=n,u.leaf=!0,u;e[0]=l[3]-l[0],e[1]=l[4]-l[1],e[2]=l[5]-l[2];var A=0;e[1]>e[A]&&(A=1),e[2]>e[A]&&(A=2),u.splitDim=A;var d=(l[A]+l[A+3])/2,v=new Array(n.length),h=0,I=new Array(n.length),y=0;for(s=0,o=n.length;s<o;++s){var m=r[c=3*n[s]],w=3*r[c+1],g=3*r[c+2];i[3*m+A]<=d||i[w+A]<=d||i[g+A]<=d?v[h++]=n[s]:I[y++]=n[s]}return v.length=h,I.length=y,u.left=t(v,r,i,a+1),u.right=t(I,r,i,a+1),u}return function(e,n){for(var r=e.length/3,i=new Array(r),a=0;a<r;++a)i[a]=a;return t(i,e,n,0)}}(),decompressPosition:function(e,t,n){(n=n||e)[0]=e[0]*t[0]+t[12],n[1]=e[1]*t[5]+t[13],n[2]=e[2]*t[10]+t[14]},decompressPositions:function(e,t){for(var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:new Float32Array(e.length),r=0,i=e.length;r<i;r+=3)n[r+0]=e[r+0]*t[0]+t[12],n[r+1]=e[r+1]*t[5]+t[13],n[r+2]=e[r+2]*t[10]+t[14];return n},decompressUV:function(e,t,n){n[0]=e[0]*t[0]+t[6],n[1]=e[1]*t[4]+t[7]},decompressUVs:function(e,t){for(var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:new Float32Array(e.length),r=0,i=e.length;r<i;r+=3)n[r+0]=e[r+0]*t[0]+t[6],n[r+1]=e[r+1]*t[4]+t[7];return n},octDecodeVec2:function(e,t){var n=e[0],r=e[1];n=(2*n+1)/255,r=(2*r+1)/255;var i=1-Math.abs(n)-Math.abs(r);i<0&&(n=(1-Math.abs(r))*(n>=0?1:-1),r=(1-Math.abs(n))*(r>=0?1:-1));var a=Math.sqrt(n*n+r*r+i*i);return t[0]=n/a,t[1]=r/a,t[2]=i/a,t},octDecodeVec2s:function(e,t){for(var n=0,r=0,i=e.length;n<i;n+=2){var a=e[n+0],s=e[n+1];a=(2*a+1)/255,s=(2*s+1)/255;var o=1-Math.abs(a)-Math.abs(s);o<0&&(a=(1-Math.abs(s))*(a>=0?1:-1),s=(1-Math.abs(a))*(s>=0?1:-1));var l=Math.sqrt(a*a+s*s+o*o);t[r+0]=a/l,t[r+1]=s/l,t[r+2]=o/l,r+=3}return t}};Z.buildEdgeIndices=function(){var e=[],t=[],n=[],r=[],i=[],a=0,s=new Uint16Array(3),o=new Uint16Array(3),l=new Uint16Array(3),u=Z.vec3(),c=Z.vec3(),f=Z.vec3(),p=Z.vec3(),A=Z.vec3(),d=Z.vec3(),v=Z.vec3();return function(h,I,y,m){!function(i,a){var s,o,l,u,c,f,p={},A=Math.pow(10,4),d=0;for(c=0,f=i.length;c<f;c+=3)s=i[c],o=i[c+1],l=i[c+2],void 0===p[u=Math.round(s*A)+"_"+Math.round(o*A)+"_"+Math.round(l*A)]&&(p[u]=d/3,e[d++]=s,e[d++]=o,e[d++]=l),t[c/3]=p[u];for(c=0,f=a.length;c<f;c++)r[c]=t[a[c]],n[r[c]]=a[c]}(h,I),function(t,n){a=0;for(var h=0,I=t;h<I;h+=3){var y=3*r[h],m=3*r[h+1],w=3*r[h+2];n?(s[0]=e[y],s[1]=e[y+1],s[2]=e[y+2],o[0]=e[m],o[1]=e[m+1],o[2]=e[m+2],l[0]=e[w],l[1]=e[w+1],l[2]=e[w+2],Z.decompressPosition(s,n,u),Z.decompressPosition(o,n,c),Z.decompressPosition(l,n,f)):(u[0]=e[y],u[1]=e[y+1],u[2]=e[y+2],c[0]=e[m],c[1]=e[m+1],c[2]=e[m+2],f[0]=e[w],f[1]=e[w+1],f[2]=e[w+2]),Z.subVec3(f,c,p),Z.subVec3(u,c,A),Z.cross3Vec3(p,A,d),Z.normalizeVec3(d,v);var g=i[a]||(i[a]={normal:Z.vec3()});g.normal[0]=v[0],g.normal[1]=v[1],g.normal[2]=v[2],a++}}(I.length,y);for(var w,g,T,E,b,D,P,R,C,_,B=[],O=Math.cos(Z.DEGTORAD*m),S={},N=!1,L=0,x=I.length;L<x;L+=3)for(var M=L/3,F=0;F<3;F++)w=r[L+F],g=r[L+(F+1)%3],void 0===S[b=(T=Math.min(w,g))+","+(E=Math.max(w,g))]?S[b]={index1:T,index2:E,face1:M,face2:void 0}:S[b].face2=M;for(b in S)void 0!==(D=S[b]).face2&&(P=i[D.face1].normal,R=i[D.face2].normal,Z.dotVec3(P,R)>O)||(C=n[D.index1],_=n[D.index2],(!N&&C>65535||_>65535)&&(N=!0),B.push(C),B.push(_));return N?new Uint32Array(B):new Uint16Array(B)}}();var $=function(){function e(){b(this,e),this._head=[],this._headLength=0,this._tail=[],this._index=0,this._length=0}return P(e,[{key:"length",get:function(){return this._length}},{key:"shift",value:function(){if(this._index>=this._headLength){var e=this._head;if(e.length=0,this._head=this._tail,this._tail=e,this._index=0,this._headLength=this._head.length,!this._headLength)return}var t=this._head[this._index];return this._index<0?delete this._head[this._index++]:this._head[this._index++]=void 0,this._length--,t}},{key:"push",value:function(e){return this._length++,this._tail.push(e),this}},{key:"unshift",value:function(e){return this._head[--this._index]=e,this._length++,this}}]),e}(),ee={build:{version:"0.8"},client:{browser:navigator&&navigator.userAgent?navigator.userAgent:"n/a"},components:{scenes:0,models:0,meshes:0,objects:0},memory:{meshes:0,positions:0,colors:0,normals:0,uvs:0,indices:0,textures:0,transforms:0,materials:0,programs:0},frame:{frameCount:0,fps:0,useProgram:0,bindTexture:0,bindArray:0,drawElements:0,drawArrays:0,tasksRun:0,tasksScheduled:0}};var te=[["0",10],["A",26],["a",26],["_",1],["$",1]].map((function(e){for(var t=[],n=e[0].charCodeAt(0),r=n+e[1],i=n;i<r;++i)t.push(i);return String.fromCharCode.apply(null,t)})).join("");function ne(e,t){return(t&&4!==t?[0,6]:[0,6,12,18]).map((function(t){return te.substr(parseInt(e/(1<<t))%64,1)})).reverse().join("")}var re=function(){for(var e={},t=window.location.search.substring(1).split("&"),n=0;n<t.length;n++){var r=t[n].split("=");if(void 0===e[r[0]])e[r[0]]=decodeURIComponent(r[1]);else if("string"==typeof e[r[0]]){var i=[e[r[0]],decodeURIComponent(r[1])];e[r[0]]=i}else e[r[0]].push(decodeURIComponent(r[1]))}return e}();var ie,ae={xmlToJson:function e(t,n){if(t.nodeType===t.TEXT_NODE){var r=t.nodeValue;if(null===r.match(/^\s+$/))return r}else if(t.nodeType===t.ELEMENT_NODE||t.nodeType===t.DOCUMENT_NODE){var i={type:t.nodeName,children:[]};if(t.nodeType===t.ELEMENT_NODE)for(var a=0;a<t.attributes.length;a++){var s=t.attributes[a];i[n[s.nodeName]||s.nodeName]=s.nodeValue}for(var o=0;o<t.childNodes.length;o++){(a=e(t.childNodes[o],n))&&i.children.push(a)}return i}},clone:function(e){return JSON.parse(JSON.stringify(e))},compressGuid:function(e){var t=[0,2,4,6,8,10,12,14,16,18,20,22,24,26,28,30].map((function(t){return parseInt(e.substr(t,2),16)}));return ne(t[0],2)+[1,4,7,10,13].map((function(e){return ne((t[e]<<16)+(t[e+1]<<8)+t[e+2])})).join("")},findNodeOfType:function(e,t){var n=[];return function e(r){r.type===t&&n.push(r),(r.children||[]).forEach((function(t){e(t)}))}(e),n},timeout:function(e){return new Promise((function(t,n){setTimeout(t,e)}))},httpRequest:function(e){return new Promise((function(t,n){var r=new XMLHttpRequest;r.open(e.method||"GET",e.url,!0),r.onload=function(i){console.log(e.url,r.readyState,r.status),4===r.readyState&&(200===r.status?t(r.responseXML):n(r.statusText))},r.send(null)}))},loadJSON:function(e,t,n){var r=function(e){};t=t||r,n=n||r;var i=new XMLHttpRequest;i.overrideMimeType("application/json"),i.open("GET",e,!0),i.addEventListener("load",(function(e){var r=e.target.response;if(200===this.status){var i;try{i=JSON.parse(r)}catch(e){n("utils.loadJSON(): Failed to parse JSON response - ".concat(e))}t(i)}else if(0===this.status){console.warn("loadFile: HTTP Status 0 received.");try{t(JSON.parse(r))}catch(e){n("utils.loadJSON(): Failed to parse JSON response - ".concat(e))}}else n(e)}),!1),i.addEventListener("error",(function(e){n(e)}),!1),i.send(null)},loadArraybuffer:function(e,t,n){var r=function(e){};t=t||r,n=n||r;var i=e.match(/^data:(.*?)(;base64)?,(.*)$/);if(i){var a=!!i[2],s=i[3];s=window.decodeURIComponent(s),a&&(s=window.atob(s));try{for(var o=new ArrayBuffer(s.length),l=new Uint8Array(o),u=0;u<s.length;u++)l[u]=s.charCodeAt(u);window.setTimeout((function(){t(o)}),0)}catch(e){window.setTimeout((function(){n(e)}),0)}}else{var c=new XMLHttpRequest;c.open("GET",e,!0),c.responseType="arraybuffer",c.onreadystatechange=function(){4===c.readyState&&(200===c.status?t(c.response):n("loadArrayBuffer error : "+c.response))},c.send(null)}},queryString:re,isArray:function(e){return e&&!e.propertyIsEnumerable("length")&&"object"===E(e)&&"number"==typeof e.length},isString:function(e){return"string"==typeof e||e instanceof String},isNumeric:function(e){return!isNaN(parseFloat(e))&&isFinite(e)},isID:function(e){return ae.isString(e)||ae.isNumeric(e)},isSameComponent:function(e,t){return!(!e||!t)&&(ae.isNumeric(e)||ae.isString(e)?"".concat(e):e.id)===(ae.isNumeric(t)||ae.isString(t)?"".concat(t):t.id)},isFunction:function(e){return"function"==typeof e},isObject:function(e){var t={}.constructor;return!!e&&e.constructor===t},copy:function(e){return ae.apply(e,{})},apply:function(e,t){for(var n in e)e.hasOwnProperty(n)&&(t[n]=e[n]);return t},apply2:function(e,t){for(var n in e)e.hasOwnProperty(n)&&void 0!==e[n]&&null!==e[n]&&(t[n]=e[n]);return t},applyIf:function(e,t){for(var n in e)e.hasOwnProperty(n)&&(void 0!==t[n]&&null!==t[n]||(t[n]=e[n]));return t},isEmptyObject:function(e){for(var t in e)if(e.hasOwnProperty(t))return!1;return!0},inQuotes:function(e){return ae.isNumeric(e)?"".concat(e):"'".concat(e,"'")},concat:function(e,t){var n=new e.constructor(e.length+t.length);return n.set(e),n.set(t,e.length),n},flattenParentChildHierarchy:function(e){var t=[];return function e(n){n.id=n.uuid,delete n.oid,t.push(n);var r=n.children;if(r)for(var i=0,a=r.length;i<a;i++){r[i].parent=n.id,e(r[i])}n.children=[]}(e),t}},se={},oe=new G,le=new $,ue={sceneId:null,time:null,startTime:null,prevTime:null,deltaTime:null},ce=[],fe=0,pe=0;var Ae=new function(){this.version="1.0.0",this.scenes={},this._superTypes={},this._addScene=function(e){if(e.id){if(Ae.scenes[e.id])return void console.error("[ERROR] Scene ".concat(ae.inQuotes(e.id)," already exists"))}else e.id=oe.addItem({});Ae.scenes[e.id]=e;var t=e.ticksPerOcclusionTest,n=e.ticksPerRender;se[e.id]={ticksPerOcclusionTest:t,ticksPerRender:n,renderCountdown:n},ee.components.scenes++,e.once("destroyed",(function(){oe.removeItem(e.id),delete Ae.scenes[e.id],delete se[e.id],ee.components.scenes--}))},this.clear=function(){var e;for(var t in Ae.scenes)Ae.scenes.hasOwnProperty(t)&&(e=Ae.scenes[t],"default.scene"===t?e.clear():(e.destroy(),delete Ae.scenes[e.id]))},this.scheduleTask=function(e,t){le.push(e),le.push(t)},this.runTasks=function(){for(var e,t,n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:-1,r=(new Date).getTime(),i=0;le.length>0&&(n<0||r<n);)e=le.shift(),(t=le.shift())?e.call(t):e(),r=(new Date).getTime(),i++;return i},this.getNumTasks=function(){return le.length}},de=function e(){var t=Date.now();if(ie=t-fe,fe>0&&ie>0){var n=1e3/ie;pe+=n,ce.push(n),ce.length>=30&&(pe-=ce.shift()),ee.frame.fps=Math.round(pe/ce.length)}!function(e){var t=Ae.runTasks(e+10),n=Ae.getNumTasks();ee.frame.tasksRun=t,ee.frame.tasksScheduled=n,ee.frame.tasksBudget=10}(t),function(e){for(var t in ue.time=e,Ae.scenes)if(Ae.scenes.hasOwnProperty(t)){var n=Ae.scenes[t];ue.sceneId=t,ue.startTime=n.startTime,ue.deltaTime=null!=ue.prevTime?ue.time-ue.prevTime:0,n.fire("tick",ue,!0)}ue.prevTime=e}(t),function(){var e,t,n,r,i,a=Ae.scenes,s=!1;for(i in a)a.hasOwnProperty(i)&&(e=a[i],(t=se[i])||(t=se[i]={}),n=e.ticksPerOcclusionTest,t.ticksPerOcclusionTest!==n&&(t.ticksPerOcclusionTest=n,t.renderCountdown=n),--e.occlusionTestCountdown<=0&&(e.doOcclusionTest(),e.occlusionTestCountdown=n),r=e.ticksPerRender,t.ticksPerRender!==r&&(t.ticksPerRender=r,t.renderCountdown=r),0==--t.renderCountdown&&(e.render(s),t.renderCountdown=r))}(),fe=t,void 0!==window.requestPostAnimationFrame?window.requestPostAnimationFrame(e):requestAnimationFrame(e)};void 0!==window.requestPostAnimationFrame?window.requestPostAnimationFrame(de):requestAnimationFrame(de);var ve=function(){function e(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:null,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(b(this,e),this.scene=null,"Scene"===this.type)this.scene=this,this.viewer=n.viewer;else{if("Scene"===t.type)this.scene=t;else{if(!(t instanceof e))throw"Invalid param: owner must be a Component";this.scene=t.scene}this._owner=t}this._dontClear=!!n.dontClear,this._renderer=this.scene._renderer,this.meta=n.meta||{},this.id=n.id,this.destroyed=!1,this._attached={},this._attachments=null,this._subIdMap=null,this._subIdEvents=null,this._eventSubs=null,this._eventSubsNum=null,this._events=null,this._eventCallDepth=0,this._ownedComponents=null,this!==this.scene&&this.scene._addComponent(this),this._updateScheduled=!1,t&&t._own(this)}return P(e,[{key:"type",get:function(){return"Component"}},{key:"isComponent",get:function(){return!0}},{key:"glRedraw",value:function(){this._renderer&&(this._renderer.imageDirty(),this.castsShadow&&this._renderer.shadowsDirty())}},{key:"glResort",value:function(){this._renderer&&this._renderer.needStateSort()}},{key:"owner",get:function(){return this._owner}},{key:"isType",value:function(e){return this.type===e}},{key:"fire",value:function(e,t,n){this._events||(this._events={}),this._eventSubs||(this._eventSubs={},this._eventSubsNum={}),!0!==n&&(this._events[e]=t||!0);var r,i=this._eventSubs[e];if(i)for(var a in i)i.hasOwnProperty(a)&&(r=i[a],this._eventCallDepth++,this._eventCallDepth<300?r.callback.call(r.scope,t):this.error("fire: potential stack overflow from recursive event '"+e+"' - dropping this event"),this._eventCallDepth--)}},{key:"on",value:function(e,t,n){this._events||(this._events={}),this._subIdMap||(this._subIdMap=new G),this._subIdEvents||(this._subIdEvents={}),this._eventSubs||(this._eventSubs={}),this._eventSubsNum||(this._eventSubsNum={});var r=this._eventSubs[e];r?this._eventSubsNum[e]++:(r={},this._eventSubs[e]=r,this._eventSubsNum[e]=1);var i=this._subIdMap.addItem();r[i]={callback:t,scope:n||this},this._subIdEvents[i]=e;var a=this._events[e];return void 0!==a&&t.call(n||this,a),i}},{key:"off",value:function(e){if(null!=e&&this._subIdEvents){var t=this._subIdEvents[e];if(t){delete this._subIdEvents[e];var n=this._eventSubs[t];n&&(delete n[e],this._eventSubsNum[t]--),this._subIdMap.removeItem(e)}}}},{key:"once",value:function(e,t,n){var r=this,i=this.on(e,(function(e){r.off(i),t.call(n||this,e)}),n)}},{key:"hasSubs",value:function(e){return this._eventSubsNum&&this._eventSubsNum[e]>0}},{key:"log",value:function(e){e="[LOG]"+this._message(e),window.console.log(e),this.scene.fire("log",e)}},{key:"_message",value:function(e){return" ["+this.type+" "+ae.inQuotes(this.id)+"]: "+e}},{key:"warn",value:function(e){e="[WARN]"+this._message(e),window.console.warn(e),this.scene.fire("warn",e)}},{key:"error",value:function(e){e="[ERROR]"+this._message(e),window.console.error(e),this.scene.fire("error",e)}},{key:"_attach",value:function(e){var t=e.name;if(t){var n=e.component,r=e.sceneDefault,i=e.sceneSingleton,a=e.type,s=e.on,o=!1!==e.recompiles;if(n&&(ae.isNumeric(n)||ae.isString(n))){var l=n;if(!(n=this.scene.components[l]))return void this.error("Component not found: "+ae.inQuotes(l))}if(!n)if(!0===i){var u=this.scene.types[a];for(var c in u)if(u.hasOwnProperty){n=u[c];break}if(!n)return this.error("Scene has no default component for '"+t+"'"),null}else if(!0===r&&!(n=this.scene[t]))return this.error("Scene has no default component for '"+t+"'"),null;if(n){if(n.scene.id!==this.scene.id)return void this.error("Not in same scene: "+n.type+" "+ae.inQuotes(n.id));if(a&&!n.isType(a))return void this.error("Expected a "+a+" type or subtype: "+n.type+" "+ae.inQuotes(n.id))}this._attachments||(this._attachments={});var f,p,A,d=this._attached[t];if(d){if(n&&d.id===n.id)return;var v=this._attachments[d.id];for(p=0,A=(f=v.subs).length;p<A;p++)d.off(f[p]);delete this._attached[t],delete this._attachments[d.id];var h=v.params.onDetached;h&&(ae.isFunction(h)?h(d):h.scope?h.callback.call(h.scope,d):h.callback(d)),v.managingLifecycle&&d.destroy()}if(n){var I={params:e,component:n,subs:[],managingLifecycle:!1};I.subs.push(n.once("destroyed",(function(){I.params.component=null,this._attach(I.params)}),this)),o&&I.subs.push(n.on("dirty",(function(){this.fire("dirty",this)}),this)),this._attached[t]=n,this._attachments[n.id]=I;var y,m,w,g,T=e.onAttached;if(T&&(ae.isFunction(T)?T(n):T.scope?T.callback.call(T.scope,n):T.callback(n)),s)for(y in s)if(s.hasOwnProperty(y)){if(m=s[y],ae.isFunction(m)?(w=m,g=null):(w=m.callback,g=m.scope),!w)continue;I.subs.push(n.on(y,w,g))}}return o&&this.fire("dirty",this),this.fire(t,n),n}this.error("Component 'name' expected")}},{key:"_checkComponent",value:function(e,t){if(!t.isComponent){if(!ae.isID(t))return void this.error("Expected a Component or ID");var n=t;if(!(t=this.scene.components[n]))return void this.error("Component not found: "+n)}if(e===t.type){if(t.scene.id===this.scene.id)return t;this.error("Not in same scene: "+t.type)}else this.error("Expected a "+e+" Component")}},{key:"_checkComponent2",value:function(e,t){if(!t.isComponent){if(!ae.isID(t))return void this.error("Expected a Component or ID");var n=t;if(!(t=this.scene.components[n]))return void this.error("Component not found: "+n)}if(t.scene.id===this.scene.id){for(var r=0,i=e.length;r<i;r++)if(e[r]===t.type)return t;return this.error("Expected component types: "+e),null}this.error("Not in same scene: "+t.type)}},{key:"_own",value:function(e){var t=this;this._ownedComponents||(this._ownedComponents={}),this._ownedComponents[e.id]||(this._ownedComponents[e.id]=e),e.once("destroyed",(function(){delete t._ownedComponents[e.id]}),this)}},{key:"_needUpdate",value:function(e){this._updateScheduled||(this._updateScheduled=!0,0===e?this._doUpdate():Ae.scheduleTask(this._doUpdate,this))}},{key:"_doUpdate",value:function(){this._updateScheduled&&(this._updateScheduled=!1,this._update&&this._update())}},{key:"_update",value:function(){}},{key:"clear",value:function(){if(this._ownedComponents)for(var e in this._ownedComponents){if(this._ownedComponents.hasOwnProperty(e))this._ownedComponents[e].destroy(),delete this._ownedComponents[e]}}},{key:"destroy",value:function(){if(!this.destroyed){var e,t,n,r,i,a;if(this.fire("destroyed",this.destroyed=!0),this._attachments)for(e in this._attachments)if(this._attachments.hasOwnProperty(e)){for(n=(t=this._attachments[e]).component,i=0,a=(r=t.subs).length;i<a;i++)n.off(r[i]);t.managingLifecycle&&n.destroy()}if(this._ownedComponents)for(e in this._ownedComponents)this._ownedComponents.hasOwnProperty(e)&&((n=this._ownedComponents[e]).destroy(),delete this._ownedComponents[e]);this.scene._removeComponent(this),this._attached={},this._attachments=null,this._subIdMap=null,this._subIdEvents=null,this._eventSubs=null,this._events=null,this._eventCallDepth=0,this._ownedComponents=null,this._updateScheduled=!1}}}]),e}(),he=Z.vec3(),Ie=function(){var e=new Float64Array(16),t=new Float64Array(4),n=new Float64Array(4);return function(r,i,a){return a=a||e,t[0]=i[0],t[1]=i[1],t[2]=i[2],t[3]=1,Z.transformVec4(r,t,n),Z.setMat4Translation(r,n,a),a.slice()}}();function ye(e,t,n){var r=Float32Array.from([e[0]])[0],i=e[0]-r,a=Float32Array.from([e[1]])[0],s=e[1]-a,o=Float32Array.from([e[2]])[0],l=e[2]-o;t[0]=r,t[1]=a,t[2]=o,n[0]=i,n[1]=s,n[2]=l}function me(e,t,n){var r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:1e3,i=Z.getPositionsCenter(e,he),a=Math.round(i[0]/r)*r,s=Math.round(i[1]/r)*r,o=Math.round(i[2]/r)*r;n[0]=a,n[1]=s,n[2]=o;var l=0!==n[0]||0!==n[1]||0!==n[2];if(l)for(var u=0,c=e.length;u<c;u+=3)t[u+0]=e[u+0]-a,t[u+1]=e[u+1]-s,t[u+2]=e[u+2]-o;return l}function we(e,t,n){return n[0]=e[0]+t[0],n[1]=e[1]+t[1],n[2]=e[2]+t[2],n}function ge(e,t,n,r){var i=Z.dotVec3(t,n)+e,a=Z.normalizeVec3(t,he);return Z.mulVec3Scalar(a,-i,r),r}var Te=1,Ee=4,be=8,De=16,Pe=32,Re=256,Ce=512,_e=1024,Be=2048,Oe=new Float32Array([0,0,0]),Se=new Uint16Array([0,0,0]),Ne=function(){function e(t,n,r,i,a,s,o){b(this,e),this._isObject=n,this.scene=t.scene,this.model=t,this.meshes=i,this._numPrimitives=0;for(var l=0,u=this.meshes.length;l<u;l++){var c=this.meshes[l];c.parent=this,this._numPrimitives+=c.numPrimitives}this.id=r,this.originalSystemId=Z.unglobalizeObjectId(t.id,r),this._flags=a,this._aabb=s,this._offsetAABB=Z.AABB3(s),this._offset=Z.vec3(),this._colorizeUpdated=!1,this._opacityUpdated=!1,this._lodCullable=!!o,this._culled=!1,this._culledVFC=!1,this._culledLOD=!1,this._isObject&&t.scene._registerObject(this)}return P(e,[{key:"isEntity",get:function(){return!0}},{key:"isModel",get:function(){return!1}},{key:"isObject",get:function(){return this._isObject}},{key:"aabb",get:function(){return this._offsetAABB}},{key:"numPrimitives",get:function(){return this._numPrimitives}},{key:"numTriangles",get:function(){return this._numPrimitives}},{key:"visible",get:function(){return this._getFlag(Te)},set:function(e){if(!!(this._flags&Te)!==e){this._flags=e?this._flags|Te:this._flags&~Te;for(var t=0,n=this.meshes.length;t<n;t++)this.meshes[t]._setVisible(this._flags);this._isObject&&this.model.scene._objectVisibilityUpdated(this),this.model.glRedraw()}}},{key:"highlighted",get:function(){return this._getFlag(Ce)},set:function(e){if(!!(this._flags&Ce)!==e){this._flags=e?this._flags|Ce:this._flags&~Ce;for(var t=0,n=this.meshes.length;t<n;t++)this.meshes[t]._setHighlighted(this._flags);this._isObject&&this.model.scene._objectHighlightedUpdated(this),this.model.glRedraw()}}},{key:"xrayed",get:function(){return this._getFlag(Re)},set:function(e){if(!!(this._flags&Re)!==e){this._flags=e?this._flags|Re:this._flags&~Re;for(var t=0,n=this.meshes.length;t<n;t++)this.meshes[t]._setXRayed(this._flags);this._isObject&&this.model.scene._objectXRayedUpdated(this),this.model.glRedraw()}}},{key:"selected",get:function(){return this._getFlag(_e)},set:function(e){if(!!(this._flags&_e)!==e){this._flags=e?this._flags|_e:this._flags&~_e;for(var t=0,n=this.meshes.length;t<n;t++)this.meshes[t]._setSelected(this._flags);this._isObject&&this.model.scene._objectSelectedUpdated(this),this.model.glRedraw()}}},{key:"edges",get:function(){return this._getFlag(Be)},set:function(e){if(!!(this._flags&Be)!==e){this._flags=e?this._flags|Be:this._flags&~Be;for(var t=0,n=this.meshes.length;t<n;t++)this.meshes[t]._setEdges(this._flags);this.model.glRedraw()}}},{key:"culledVFC",get:function(){return!!this._culledVFC},set:function(e){this._culledVFC=e,this._setCulled()}},{key:"culledLOD",get:function(){return!!this._culledLOD},set:function(e){this._culledLOD=e,this._setCulled()}},{key:"culled",get:function(){return!!this._culled},set:function(e){this._culled=e,this._setCulled()}},{key:"_setCulled",value:function(){var e=!!this._culled||!(!this._culledLOD||!this._lodCullable)||!!this._culledVFC;if(!!(this._flags&Ee)!==e){this._flags=e?this._flags|Ee:this._flags&~Ee;for(var t=0,n=this.meshes.length;t<n;t++)this.meshes[t]._setCulled(this._flags);this.model.glRedraw()}}},{key:"clippable",get:function(){return this._getFlag(De)},set:function(e){if(!!(this._flags&De)!==e){this._flags=e?this._flags|De:this._flags&~De;for(var t=0,n=this.meshes.length;t<n;t++)this.meshes[t]._setClippable(this._flags);this.model.glRedraw()}}},{key:"collidable",get:function(){return this._getFlag(Pe)},set:function(e){if(!!(this._flags&Pe)!==e){this._flags=e?this._flags|Pe:this._flags&~Pe;for(var t=0,n=this.meshes.length;t<n;t++)this.meshes[t]._setCollidable(this._flags)}}},{key:"pickable",get:function(){return this._getFlag(be)},set:function(e){if(!!(this._flags&be)!==e){this._flags=e?this._flags|be:this._flags&~be;for(var t=0,n=this.meshes.length;t<n;t++)this.meshes[t]._setPickable(this._flags)}}},{key:"colorize",get:function(){if(0===this.meshes.length)return null;var e=this.meshes[0]._colorize;return Oe[0]=e[0]/255,Oe[1]=e[1]/255,Oe[2]=e[2]/255,Oe},set:function(e){if(e){Se[0]=Math.floor(255*e[0]),Se[1]=Math.floor(255*e[1]),Se[2]=Math.floor(255*e[2]);for(var t=0,n=this.meshes.length;t<n;t++)this.meshes[t]._setColorize(Se)}else for(var r=0,i=this.meshes.length;r<i;r++)this.meshes[r]._setColorize(null);if(this._isObject){var a=!!e;this.scene._objectColorizeUpdated(this,a),this._colorizeUpdated=a}this.model.glRedraw()}},{key:"opacity",get:function(){return this.meshes.length>0?this.meshes[0]._colorize[3]/255:1},set:function(e){if(0!==this.meshes.length){var t=null!=e,n=this.meshes[0]._colorize[3],r=255;if(t){if(e<0?e=0:e>1&&(e=1),n===(r=Math.floor(255*e)))return}else if(n===(r=255))return;for(var i=0,a=this.meshes.length;i<a;i++)this.meshes[i]._setOpacity(r,this._flags);this._isObject&&(this.scene._objectOpacityUpdated(this,t),this._opacityUpdated=t),this.model.glRedraw()}}},{key:"offset",get:function(){return this._offset},set:function(e){e?(this._offset[0]=e[0],this._offset[1]=e[1],this._offset[2]=e[2]):(this._offset[0]=0,this._offset[1]=0,this._offset[2]=0);for(var t=0,n=this.meshes.length;t<n;t++)this.meshes[t]._setOffset(this._offset);this._offsetAABB[0]=this._aabb[0]+this._offset[0],this._offsetAABB[1]=this._aabb[1]+this._offset[1],this._offsetAABB[2]=this._aabb[2]+this._offset[2],this._offsetAABB[3]=this._aabb[3]+this._offset[0],this._offsetAABB[4]=this._aabb[4]+this._offset[1],this._offsetAABB[5]=this._aabb[5]+this._offset[2],this.scene._aabbDirty=!0,this.scene._objectOffsetUpdated(this,e),this.model._aabbDirty=!0,this.model.glRedraw()}},{key:"saoEnabled",get:function(){return this.model.saoEnabled}},{key:"getEachVertex",value:function(e){for(var t=0,n=this.meshes.length;t<n;t++)this.meshes[t].getEachVertex(e)}},{key:"_getFlag",value:function(e){return!!(this._flags&e)}},{key:"_finalize",value:function(){var e=this.model.scene;this._isObject&&(this.visible&&e._objectVisibilityUpdated(this),this.highlighted&&e._objectHighlightedUpdated(this),this.xrayed&&e._objectXRayedUpdated(this),this.selected&&e._objectSelectedUpdated(this));for(var t=0,n=this.meshes.length;t<n;t++)this.meshes[t]._finalize(this._flags)}},{key:"_finalize2",value:function(){for(var e=0,t=this.meshes.length;e<t;e++)this.meshes[e]._finalize2()}},{key:"_destroy",value:function(){var e=this.model.scene;this._isObject&&(e._deregisterObject(this),this.visible&&e._objectVisibilityUpdated(this,!1),this.xrayed&&e._objectXRayedUpdated(this),this.selected&&e._objectSelectedUpdated(this),this.highlighted&&e._objectHighlightedUpdated(this),this._opacityUpdated&&this.scene._objectColorizeUpdated(this,!1),this._opacityUpdated&&this.scene._objectOpacityUpdated(this,!1),this.scene._objectOffsetUpdated(this,!1));for(var t=0,n=this.meshes.length;t<n;t++)this.meshes[t]._destroy();e._aabbDirty=!0}}]),e}(),Le=Z.vec4(),xe=Z.vec4(),Me=function(e){I(n,ve);var t=m(n);function n(e,r){var i;return b(this,n),(i=t.call(this,e,r))._entity=null,i._visible=null,i._worldPos=Z.vec3(),i._origin=Z.vec3(),i._rtcPos=Z.vec3(),i._viewPos=Z.vec3(),i._canvasPos=Z.vec2(),i._occludable=!1,i._onCameraViewMatrix=i.scene.camera.on("matrix",(function(){i._viewPosDirty=!0,i._needUpdate()})),i._onCameraProjMatrix=i.scene.camera.on("projMatrix",(function(){i._canvasPosDirty=!0,i._needUpdate()})),i._onEntityDestroyed=null,i._onEntityModelDestroyed=null,i._renderer.addMarker(g(i)),i.entity=r.entity,i.worldPos=r.worldPos,i.occludable=r.occludable,i}return P(n,[{key:"_update",value:function(){if(this._viewPosDirty&&(Z.transformPoint3(this.scene.camera.viewMatrix,this._worldPos,this._viewPos),this._viewPosDirty=!1,this._canvasPosDirty=!0,this.fire("viewPos",this._viewPos)),this._canvasPosDirty){Le.set(this._viewPos),Le[3]=1,Z.transformPoint4(this.scene.camera.projMatrix,Le,xe);var e=this.scene.canvas.boundary;this._canvasPos[0]=Math.floor((1+xe[0]/xe[3])*e[2]/2),this._canvasPos[1]=Math.floor((1-xe[1]/xe[3])*e[3]/2),this._canvasPosDirty=!1,this.fire("canvasPos",this._canvasPos)}}},{key:"_setVisible",value:function(e){this._visible,this._visible=e,this.fire("visible",this._visible)}},{key:"entity",get:function(){return this._entity},set:function(e){var t=this;if(this._entity){if(this._entity===e)return;null!==this._onEntityDestroyed&&(this._entity.off(this._onEntityDestroyed),this._onEntityDestroyed=null),null!==this._onEntityModelDestroyed&&(this._entity.model.off(this._onEntityModelDestroyed),this._onEntityModelDestroyed=null)}this._entity=e,this._entity&&(this._entity instanceof Ne?this._onEntityModelDestroyed=this._entity.model.on("destroyed",(function(){t._entity=null,t._onEntityModelDestroyed=null})):this._onEntityDestroyed=this._entity.on("destroyed",(function(){t._entity=null,t._onEntityDestroyed=null}))),this.fire("entity",this._entity,!0)}},{key:"occludable",get:function(){return this._occludable},set:function(e){(e=!!e)!==this._occludable&&(this._occludable=e)}},{key:"worldPos",get:function(){return this._worldPos},set:function(e){this._worldPos.set(e||[0,0,0]),ye(this._worldPos,this._origin,this._rtcPos),this._occludable&&this._renderer.markerWorldPosUpdated(this),this._viewPosDirty=!0,this.fire("worldPos",this._worldPos),this._needUpdate()}},{key:"origin",get:function(){return this._origin}},{key:"rtcPos",get:function(){return this._rtcPos}},{key:"viewPos",get:function(){return this._update(),this._viewPos}},{key:"canvasPos",get:function(){return this._update(),this._canvasPos}},{key:"visible",get:function(){return!!this._visible}},{key:"destroy",value:function(){this.fire("destroyed",!0),this.scene.camera.off(this._onCameraViewMatrix),this.scene.camera.off(this._onCameraProjMatrix),this._entity&&(null!==this._onEntityDestroyed&&this._entity.off(this._onEntityDestroyed),null!==this._onEntityModelDestroyed&&this._entity.model.off(this._onEntityModelDestroyed)),this._renderer.removeMarker(this),v(T(n.prototype),"destroy",this).call(this)}}]),n}(),Fe=function(){function e(t){var n=this,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};b(this,e),this._color=r.color||"black",this._highlightClass="viewer-ruler-wire-highlighted",this._wire=document.createElement("div"),this._wire.className+=this._wire.className?" viewer-ruler-wire":"viewer-ruler-wire",this._wireClickable=document.createElement("div"),this._wireClickable.className+=this._wireClickable.className?" viewer-ruler-wire-clickable":"viewer-ruler-wire-clickable",this._thickness=r.thickness||1,this._thicknessClickable=r.thicknessClickable||6;var i=this._wire,a=i.style;a.border="solid "+this._thickness+"px "+this._color,a.position="absolute",a["z-index"]=void 0===r.zIndex?"2000001":r.zIndex,a.width="0px",a.height="0px",a.visibility="visible",a.top="0px",a.left="0px",a["-webkit-transform-origin"]="0 0",a["-moz-transform-origin"]="0 0",a["-ms-transform-origin"]="0 0",a["-o-transform-origin"]="0 0",a["transform-origin"]="0 0",a["-webkit-transform"]="rotate(0deg)",a["-moz-transform"]="rotate(0deg)",a["-ms-transform"]="rotate(0deg)",a["-o-transform"]="rotate(0deg)",a.transform="rotate(0deg)",a.opacity=1,a["pointer-events"]="none",r.onContextMenu,t.appendChild(i);var s=this._wireClickable,o=s.style;o.border="solid "+this._thicknessClickable+"px "+this._color,o.position="absolute",o["z-index"]=void 0===r.zIndex?"2000002":r.zIndex+1,o.width="0px",o.height="0px",o.visibility="visible",o.top="0px",o.left="0px",o["-webkit-transform-origin"]="0 0",o["-moz-transform-origin"]="0 0",o["-ms-transform-origin"]="0 0",o["-o-transform-origin"]="0 0",o["transform-origin"]="0 0",o["-webkit-transform"]="rotate(0deg)",o["-moz-transform"]="rotate(0deg)",o["-ms-transform"]="rotate(0deg)",o["-o-transform"]="rotate(0deg)",o.transform="rotate(0deg)",o.opacity=0,o["pointer-events"]="none",r.onContextMenu,t.appendChild(s),r.onMouseOver&&s.addEventListener("mouseover",(function(e){r.onMouseOver(e,n)})),r.onMouseLeave&&s.addEventListener("mouseleave",(function(e){r.onMouseLeave(e,n)})),r.onMouseWheel&&s.addEventListener("wheel",(function(e){r.onMouseWheel(e,n)})),r.onContextMenu&&s.addEventListener("contextmenu",(function(e){r.onContextMenu(e,n),e.preventDefault()})),this._x1=0,this._y1=0,this._x2=0,this._y2=0,this._update()}return P(e,[{key:"_visible",get:function(){return"visible"===this._wire.style.visibility}},{key:"_update",value:function(){var e=Math.abs(Math.sqrt((this._x1-this._x2)*(this._x1-this._x2)+(this._y1-this._y2)*(this._y1-this._y2))),t=180*Math.atan2(this._y2-this._y1,this._x2-this._x1)/Math.PI,n=this._wire.style;n.width=Math.round(e)+"px",n.left=Math.round(this._x1)+"px",n.top=Math.round(this._y1)+"px",n["-webkit-transform"]="rotate("+t+"deg)",n["-moz-transform"]="rotate("+t+"deg)",n["-ms-transform"]="rotate("+t+"deg)",n["-o-transform"]="rotate("+t+"deg)",n.transform="rotate("+t+"deg)";var r=this._wireClickable.style;r.width=Math.round(e)+"px",r.left=Math.round(this._x1)+"px",r.top=Math.round(this._y1)+"px",r["-webkit-transform"]="rotate("+t+"deg)",r["-moz-transform"]="rotate("+t+"deg)",r["-ms-transform"]="rotate("+t+"deg)",r["-o-transform"]="rotate("+t+"deg)",r.transform="rotate("+t+"deg)"}},{key:"setStartAndEnd",value:function(e,t,n,r){this._x1=e,this._y1=t,this._x2=n,this._y2=r,this._update()}},{key:"setColor",value:function(e){this._color=e||"black",this._wire.style.border="solid "+this._thickness+"px "+this._color}},{key:"setOpacity",value:function(e){this._wire.style.opacity=e}},{key:"setVisible",value:function(e){e=!!e,this._visible!==e&&(this._wire.style.visibility=e?"visible":"hidden")}},{key:"setClickable",value:function(e){this._wireClickable.style["pointer-events"]=e?"all":"none"}},{key:"setHighlighted",value:function(e){this._highlighted!==e&&(this._highlighted=!!e,this._highlighted?this._wire.classList.add(this._highlightClass):this._wire.classList.remove(this._highlightClass))}},{key:"destroy",value:function(e){this._wire.parentElement&&this._wire.parentElement.removeChild(this._wire),this._wireClickable.parentElement&&this._wireClickable.parentElement.removeChild(this._wireClickable)}}]),e}(),He=function(){function e(t){var n=this,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};b(this,e),this._highlightClass="viewer-ruler-dot-highlighted",this._x=0,this._y=0,this._visible=!0,this._dot=document.createElement("div"),this._dot.className+=this._dot.className?" viewer-ruler-dot":"viewer-ruler-dot",this._dotClickable=document.createElement("div"),this._dotClickable.className+=this._dotClickable.className?" viewer-ruler-dot-clickable":"viewer-ruler-dot-clickable";var i=this._dot,a=i.style;a["border-radius"]="25px",a.border="solid 2px white",a.background="lightgreen",a.position="absolute",a["z-index"]=void 0===r.zIndex?"40000005":r.zIndex,a.width="8px",a.height="8px",a.visibility=!1!==r.visible?"visible":"hidden",a.top="0px",a.left="0px",a["box-shadow"]="0 2px 5px 0 #182A3D;",a.opacity=1,a["pointer-events"]="none",r.onContextMenu,t.appendChild(i);var s=this._dotClickable,o=s.style;o["border-radius"]="35px",o.border="solid 10px white",o.position="absolute",o["z-index"]=void 0===r.zIndex?"40000007":r.zIndex+1,o.width="8px",o.height="8px",o.visibility="visible",o.top="0px",o.left="0px",o.opacity=0,o["pointer-events"]="none",r.onContextMenu,t.appendChild(s),r.onMouseOver&&s.addEventListener("mouseover",(function(e){r.onMouseOver(e,n)})),r.onMouseLeave&&s.addEventListener("mouseleave",(function(e){r.onMouseLeave(e,n)})),r.onMouseWheel&&s.addEventListener("wheel",(function(e){r.onMouseWheel(e,n)})),r.onContextMenu&&s.addEventListener("contextmenu",(function(e){r.onContextMenu(e,n),e.preventDefault()})),this.setPos(r.x||0,r.y||0),this.setFillColor(r.fillColor),this.setBorderColor(r.borderColor)}return P(e,[{key:"setPos",value:function(e,t){this._x=e,this._y=t;var n=this._dot.style;n.left=Math.round(e)-4+"px",n.top=Math.round(t)-4+"px";var r=this._dotClickable.style;r.left=Math.round(e)-9+"px",r.top=Math.round(t)-9+"px"}},{key:"setFillColor",value:function(e){this._dot.style.background=e||"lightgreen"}},{key:"setBorderColor",value:function(e){this._dot.style.border="solid 2px"+(e||"black")}},{key:"setOpacity",value:function(e){this._dot.style.opacity=e}},{key:"setVisible",value:function(e){this._visible!==e&&(this._visible=!!e,this._dot.style.visibility=this._visible?"visible":"hidden")}},{key:"setClickable",value:function(e){this._dotClickable.style["pointer-events"]=e?"all":"none"}},{key:"setHighlighted",value:function(e){this._highlighted!==e&&(this._highlighted=!!e,this._highlighted?this._dot.classList.add(this._highlightClass):this._dot.classList.remove(this._highlightClass))}},{key:"destroy",value:function(){this.setVisible(!1),this._dot.parentElement&&this._dot.parentElement.removeChild(this._dot),this._dotClickable.parentElement&&this._dotClickable.parentElement.removeChild(this._dotClickable)}}]),e}(),Ue=function(){function e(t){var n=this,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};b(this,e),this._highlightClass="viewer-ruler-label-highlighted",this._prefix=r.prefix||"",this._x=0,this._y=0,this._visible=!0,this._culled=!1,this._label=document.createElement("div"),this._label.className+=this._label.className?" viewer-ruler-label":"viewer-ruler-label";var i=this._label,a=i.style;a["border-radius"]="5px",a.color="white",a.padding="4px",a.border="solid 1px",a.background="lightgreen",a.position="absolute",a["z-index"]=void 0===r.zIndex?"5000005":r.zIndex,a.width="auto",a.height="auto",a.visibility="visible",a.top="0px",a.left="0px",a["pointer-events"]="all",a.opacity=1,r.onContextMenu,i.innerText="",t.appendChild(i),this.setPos(r.x||0,r.y||0),this.setFillColor(r.fillColor),this.setBorderColor(r.fillColor),this.setText(r.text),r.onMouseOver&&i.addEventListener("mouseover",(function(e){r.onMouseOver(e,n),e.preventDefault()})),r.onMouseLeave&&i.addEventListener("mouseleave",(function(e){r.onMouseLeave(e,n),e.preventDefault()})),r.onMouseWheel&&i.addEventListener("wheel",(function(e){r.onMouseWheel(e,n)})),r.onContextMenu&&i.addEventListener("contextmenu",(function(e){r.onContextMenu(e,n),e.preventDefault()}))}return P(e,[{key:"setPos",value:function(e,t){this._x=e,this._y=t;var n=this._label.style;n.left=Math.round(e)-20+"px",n.top=Math.round(t)-12+"px"}},{key:"setPosOnWire",value:function(e,t,n,r){var i=e+.5*(n-e),a=t+.5*(r-t),s=this._label.style;s.left=Math.round(i)-20+"px",s.top=Math.round(a)-12+"px"}},{key:"setPosBetweenWires",value:function(e,t,n,r,i,a){var s=(e+n+i)/3,o=(t+r+a)/3,l=this._label.style;l.left=Math.round(s)-20+"px",l.top=Math.round(o)-12+"px"}},{key:"setText",value:function(e){this._label.innerHTML=this._prefix+(e||"")}},{key:"setFillColor",value:function(e){this._fillColor=e||"lightgreen",this._label.style.background=this._fillColor}},{key:"setBorderColor",value:function(e){this._borderColor=e||"black",this._label.style.border="solid 1px "+this._borderColor}},{key:"setOpacity",value:function(e){this._label.style.opacity=e}},{key:"setVisible",value:function(e){this._visible!==e&&(this._visible=!!e,this._label.style.visibility=this._visible&&!this._culled?"visible":"hidden")}},{key:"setCulled",value:function(e){this._culled!==e&&(this._culled=!!e,this._label.style.visibility=this._visible&&!this._culled?"visible":"hidden")}},{key:"setHighlighted",value:function(e){this._highlighted!==e&&(this._highlighted=!!e,this._highlighted?this._label.classList.add(this._highlightClass):this._label.classList.remove(this._highlightClass))}},{key:"setClickable",value:function(e){this._label.style["pointer-events"]=e?"all":"none"}},{key:"destroy",value:function(){this._label.parentElement&&this._label.parentElement.removeChild(this._label)}}]),e}(),Ge=Z.vec3(),ke=Z.vec3(),Ve=function(e){I(n,ve);var t=m(n);function n(e){var r,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(b(this,n),(r=t.call(this,e.viewer.scene,i)).plugin=e,r._container=i.container,!r._container)throw"config missing: container";r._color=i.color||e.defaultColor;var a=r.plugin.viewer.scene;r._originMarker=new Me(a,i.origin),r._cornerMarker=new Me(a,i.corner),r._targetMarker=new Me(a,i.target),r._originWorld=Z.vec3(),r._cornerWorld=Z.vec3(),r._targetWorld=Z.vec3(),r._wp=new Float64Array(12),r._vp=new Float64Array(12),r._pp=new Float64Array(12),r._cp=new Int16Array(6);var s=i.onMouseOver?function(e){i.onMouseOver(e,g(r))}:null,o=i.onMouseLeave?function(e){i.onMouseLeave(e,g(r))}:null,l=i.onContextMenu?function(e){i.onContextMenu(e,g(r))}:null,u=function(e){r.plugin.viewer.scene.canvas.canvas.dispatchEvent(new WheelEvent("wheel",e))};return r._originDot=new He(r._container,{fillColor:r._color,zIndex:void 0!==e.zIndex?e.zIndex+2:void 0,onMouseOver:s,onMouseLeave:o,onMouseWheel:u,onContextMenu:l}),r._cornerDot=new He(r._container,{fillColor:r._color,zIndex:void 0!==e.zIndex?e.zIndex+2:void 0,onMouseOver:s,onMouseLeave:o,onMouseWheel:u,onContextMenu:l}),r._targetDot=new He(r._container,{fillColor:r._color,zIndex:void 0!==e.zIndex?e.zIndex+2:void 0,onMouseOver:s,onMouseLeave:o,onMouseWheel:u,onContextMenu:l}),r._originWire=new Fe(r._container,{color:r._color||"blue",thickness:1,zIndex:e.zIndex,onMouseOver:s,onMouseLeave:o,onMouseWheel:u,onContextMenu:l}),r._targetWire=new Fe(r._container,{color:r._color||"red",thickness:1,zIndex:void 0!==e.zIndex?e.zIndex+1:void 0,onMouseOver:s,onMouseLeave:o,onMouseWheel:u,onContextMenu:l}),r._angleLabel=new Ue(r._container,{fillColor:r._color||"#00BBFF",prefix:"",text:"",zIndex:e.zIndex+2,onMouseOver:s,onMouseLeave:o,onMouseWheel:u,onContextMenu:l}),r._wpDirty=!1,r._vpDirty=!1,r._cpDirty=!1,r._visible=!1,r._originVisible=!1,r._cornerVisible=!1,r._targetVisible=!1,r._originWireVisible=!1,r._targetWireVisible=!1,r._angleVisible=!1,r._labelsVisible=!1,r._clickable=!1,r._originMarker.on("worldPos",(function(e){r._originWorld.set(e||[0,0,0]),r._wpDirty=!0,r._needUpdate(0)})),r._cornerMarker.on("worldPos",(function(e){r._cornerWorld.set(e||[0,0,0]),r._wpDirty=!0,r._needUpdate(0)})),r._targetMarker.on("worldPos",(function(e){r._targetWorld.set(e||[0,0,0]),r._wpDirty=!0,r._needUpdate(0)})),r._onViewMatrix=a.camera.on("viewMatrix",(function(){r._vpDirty=!0,r._needUpdate(0)})),r._onProjMatrix=a.camera.on("projMatrix",(function(){r._cpDirty=!0,r._needUpdate()})),r._onCanvasBoundary=a.canvas.on("boundary",(function(){r._cpDirty=!0,r._needUpdate(0)})),r.approximate=i.approximate,r.visible=i.visible,r.originVisible=i.originVisible,r.cornerVisible=i.cornerVisible,r.targetVisible=i.targetVisible,r.originWireVisible=i.originWireVisible,r.targetWireVisible=i.targetWireVisible,r.angleVisible=i.angleVisible,r.labelsVisible=i.labelsVisible,r}return P(n,[{key:"_update",value:function(){if(this._visible){var e=this.plugin.viewer.scene;if(this._wpDirty&&(this._wp[0]=this._originWorld[0],this._wp[1]=this._originWorld[1],this._wp[2]=this._originWorld[2],this._wp[3]=1,this._wp[4]=this._cornerWorld[0],this._wp[5]=this._cornerWorld[1],this._wp[6]=this._cornerWorld[2],this._wp[7]=1,this._wp[8]=this._targetWorld[0],this._wp[9]=this._targetWorld[1],this._wp[10]=this._targetWorld[2],this._wp[11]=1,this._wpDirty=!1,this._vpDirty=!0),this._vpDirty&&(Z.transformPositions4(e.camera.viewMatrix,this._wp,this._vp),this._vp[3]=1,this._vp[7]=1,this._vp[11]=1,this._vpDirty=!1,this._cpDirty=!0),this._cpDirty){var t=-.3,n=this._originMarker.viewPos[2],r=this._cornerMarker.viewPos[2],i=this._targetMarker.viewPos[2];if(n>t||r>t||i>t)return this._originDot.setVisible(!1),this._cornerDot.setVisible(!1),this._targetDot.setVisible(!1),this._originWire.setVisible(!1),this._targetWire.setVisible(!1),void this._angleLabel.setCulled(!0);Z.transformPositions4(e.camera.project.matrix,this._vp,this._pp);for(var a=this._pp,s=this._cp,o=e.canvas.canvas.getBoundingClientRect(),l=this._container.getBoundingClientRect(),u=o.top-l.top,c=o.left-l.left,f=e.canvas.boundary,p=f[2],A=f[3],d=0,v=0,h=a.length;v<h;v+=4)s[d]=c+Math.floor((1+a[v+0]/a[v+3])*p/2),s[d+1]=u+Math.floor((1-a[v+1]/a[v+3])*A/2),d+=2;if(this._originDot.setPos(s[0],s[1]),this._cornerDot.setPos(s[2],s[3]),this._targetDot.setPos(s[4],s[5]),this._originWire.setStartAndEnd(s[0],s[1],s[2],s[3]),this._targetWire.setStartAndEnd(s[2],s[3],s[4],s[5]),this._angleLabel.setPosBetweenWires(s[0],s[1],s[2],s[3],s[4],s[5]),Z.subVec3(this._originWorld,this._cornerWorld,Ge),Z.subVec3(this._targetWorld,this._cornerWorld,ke),!(0===Ge[0]&&0===Ge[1]&&0===Ge[2]||0===ke[0]&&0===ke[1]&&0===ke[2])){var I=this._approximate?" ~ ":" = ";Z.normalizeVec3(Ge),Z.normalizeVec3(ke);var y=Math.abs(Z.angleVec3(Ge,ke));this._angle=y/Z.DEGTORAD,this._angleLabel.setText(I+this._angle.toFixed(2)+"°")}else this._angleLabel.setText("");this._originDot.setVisible(this._visible&&this._originVisible),this._cornerDot.setVisible(this._visible&&this._cornerVisible),this._targetDot.setVisible(this._visible&&this._targetVisible),this._originWire.setVisible(this._visible&&this._originWireVisible),this._targetWire.setVisible(this._visible&&this._targetWireVisible),this._angleLabel.setCulled(!(this._visible&&this._angleVisible&&this.labelsVisible)),this._cpDirty=!1}}}},{key:"approximate",get:function(){return this._approximate},set:function(e){e=!1!==e,this._approximate!==e&&(this._approximate=e,this._cpDirty=!0,this._needUpdate(0))}},{key:"origin",get:function(){return this._originMarker}},{key:"corner",get:function(){return this._cornerMarker}},{key:"target",get:function(){return this._targetMarker}},{key:"angle",get:function(){return this._update(),this._angle}},{key:"color",get:function(){return this._color},set:function(e){this._originDot.setFillColor(e),this._cornerDot.setFillColor(e),this._targetDot.setFillColor(e),this._originWire.setColor(e||"blue"),this._targetWire.setColor(e||"red"),this._angleLabel.setFillColor(e||"#00BBFF"),this._color=e}},{key:"visible",get:function(){return this._visible},set:function(e){e=!1!==e,this._visible=e,this._originDot.setVisible(this._visible&&this._originVisible),this._cornerDot.setVisible(this._visible&&this._cornerVisible),this._targetDot.setVisible(this._visible&&this._targetVisible),this._originWire.setVisible(this._visible&&this._originWireVisible),this._targetWire.setVisible(this._visible&&this._targetWireVisible),this._angleLabel.setVisible(this._visible&&this._angleVisible),this._cpDirty=!0,this._needUpdate()}},{key:"originVisible",get:function(){return this._originVisible},set:function(e){e=!1!==e,this._originVisible=e,this._originDot.setVisible(this._visible&&this._originVisible),this._cpDirty=!0,this._needUpdate()}},{key:"cornerVisible",get:function(){return this._cornerVisible},set:function(e){e=!1!==e,this._cornerVisible=e,this._cornerDot.setVisible(this._visible&&this._cornerVisible),this._cpDirty=!0,this._needUpdate()}},{key:"targetVisible",get:function(){return this._targetVisible},set:function(e){e=!1!==e,this._targetVisible=e,this._targetDot.setVisible(this._visible&&this._targetVisible),this._cpDirty=!0,this._needUpdate()}},{key:"originWireVisible",get:function(){return this._originWireVisible},set:function(e){e=!1!==e,this._originWireVisible=e,this._originWire.setVisible(this._visible&&this._originWireVisible),this._cpDirty=!0,this._needUpdate()}},{key:"targetWireVisible",get:function(){return this._targetWireVisible},set:function(e){e=!1!==e,this._targetWireVisible=e,this._targetWire.setVisible(this._visible&&this._targetWireVisible),this._cpDirty=!0,this._needUpdate()}},{key:"angleVisible",get:function(){return this._angleVisible},set:function(e){e=!1!==e,this._angleVisible=e,this._angleLabel.setVisible(this._visible&&this._angleVisible),this._cpDirty=!0,this._needUpdate()}},{key:"labelsVisible",get:function(){return this._labelsVisible},set:function(e){e=void 0!==e?Boolean(e):this.plugin.defaultLabelsVisible,this._labelsVisible=e;var t=this._visible&&this._labelsVisible;this._angleLabel.setVisible(t),this._cpDirty=!0,this._needUpdate()}},{key:"setHighlighted",value:function(e){this._originDot.setHighlighted(e),this._cornerDot.setHighlighted(e),this._targetDot.setHighlighted(e),this._originWire.setHighlighted(e),this._targetWire.setHighlighted(e),this._angleLabel.setHighlighted(e)}},{key:"clickable",get:function(){return this._clickable},set:function(e){e=!!e,this._clickable=e,this._originDot.setClickable(this._clickable),this._cornerDot.setClickable(this._clickable),this._targetDot.setClickable(this._clickable),this._originWire.setClickable(this._clickable),this._targetWire.setClickable(this._clickable),this._angleLabel.setClickable(this._clickable)}},{key:"destroy",value:function(){var e=this.plugin.viewer.scene;this._onViewMatrix&&e.camera.off(this._onViewMatrix),this._onProjMatrix&&e.camera.off(this._onProjMatrix),this._onCanvasBoundary&&e.canvas.off(this._onCanvasBoundary),this._originDot.destroy(),this._cornerDot.destroy(),this._targetDot.destroy(),this._originWire.destroy(),this._targetWire.destroy(),this._angleLabel.destroy(),v(T(n.prototype),"destroy",this).call(this)}}]),n}(),je=function(e){I(n,ve);var t=m(n);function n(e){var r;b(this,n),(r=t.call(this,e.viewer.scene)).plugin=e,r._active=!1,r._state=0,r._currentAngleMeasurement=null;var i=document.createElement("div"),a=r.scene.canvas.canvas;return a.parentNode.insertBefore(i,a),i.style.background="black",i.style.border="2px solid blue",i.style.borderRadius="10px",i.style.width="5px",i.style.height="5px",i.style.margin="-200px -200px",i.style.zIndex="100",i.style.position="absolute",i.style.pointerEvents="none",r.markerDiv=i,r._onMouseHoverSurface=null,r._onHoverNothing=null,r._onMouseHoverOff=null,r._onPickedNothing=null,r._onPickedSurface=null,r._onInputMouseDown=null,r._onInputMouseUp=null,r._onCanvasTouchStart=null,r._onCanvasTouchEnd=null,r}return P(n,[{key:"active",get:function(){return this._active}},{key:"activate",value:function(){var e=this;if(!this._active){var t,n,r=this.plugin,i=this.scene,a=r.viewer.cameraControl,s=i.canvas.canvas,o=i.input,l=!1,u=null,c=Z.vec3(),f=Z.vec2(),p=Z.vec2(),A=Z.vec2();Z.vec3(),this._onMouseHoverSurface=a.on("hoverSnapOrSurface",(function(t){switch(l=!0,u=t.entity,c.set(t.worldPos),f.set(t.canvasPos),e._state){case 0:e.markerDiv.style.marginLeft="".concat(t.canvasPos[0]-5,"px"),e.markerDiv.style.marginTop="".concat(t.canvasPos[1]-5,"px"),e.markerDiv.style.background="pink",e.markerDiv.style.border="2px solid red";break;case 1:e._currentAngleMeasurement&&(e._currentAngleMeasurement.originWireVisible=!0,e._currentAngleMeasurement.targetWireVisible=!1,e._currentAngleMeasurement.cornerVisible=!0,e._currentAngleMeasurement.angleVisible=!1,e._currentAngleMeasurement.corner.worldPos=t.worldPos),e.markerDiv.style.marginLeft="-10000px",e.markerDiv.style.marginTop="-10000px",s.style.cursor="pointer";break;case 2:e._currentAngleMeasurement&&(e._currentAngleMeasurement.targetWireVisible=!0,e._currentAngleMeasurement.targetVisible=!0,e._currentAngleMeasurement.angleVisible=!0,e._currentAngleMeasurement.target.worldPos=t.worldPos),e.markerDiv.style.marginLeft="-10000px",e.markerDiv.style.marginTop="-10000px",s.style.cursor="pointer"}})),this._onInputMouseDown=o.on("mousedown",(function(e){t=e[0],n=e[1]})),this._onInputMouseUp=o.on("mouseup",(function(r){if(!(r[0]>t+5||r[0]<t-5||r[1]>n+5||r[1]<n-5))switch(e._state){case 0:l&&(e._currentAngleMeasurement=e.plugin.createMeasurement({id:Z.createUUID(),origin:{entity:u,worldPos:c},corner:{entity:u,worldPos:c},target:{entity:u,worldPos:c},approximate:!0}),e._currentAngleMeasurement.originVisible=!0,e._currentAngleMeasurement.originWireVisible=!0,e._currentAngleMeasurement.cornerVisible=!1,e._currentAngleMeasurement.targetWireVisible=!1,e._currentAngleMeasurement.targetVisible=!1,e._currentAngleMeasurement.angleVisible=!1,e._state=1,e.fire("measurementStart",e._currentAngleMeasurement));break;case 1:l?(e._currentAngleMeasurement.targetWireVisible=!1,e._currentAngleMeasurement.targetVisible=!0,e._currentAngleMeasurement.angleVisible=!0,e._state=2):e._currentAngleMeasurement&&(e._currentAngleMeasurement.destroy(),e._currentAngleMeasurement=null,e._state=0,e.fire("measurementCancel",e._currentAngleMeasurement));break;case 2:l?(e._currentAngleMeasurement.targetVisible=!0,e._currentAngleMeasurement.angleVisible=!0,e.fire("measurementEnd",e._currentAngleMeasurement),e._currentAngleMeasurement=null,e._state=0):e._currentAngleMeasurement&&(e._currentAngleMeasurement.destroy(),e._currentAngleMeasurement=null,e._state=0,e.fire("measurementCancel",e._currentAngleMeasurement))}})),this._onMouseHoverOff=a.on("hoverSnapOrSurfaceOff",(function(t){if(l=!1,e.markerDiv.style.marginLeft="-100px",e.markerDiv.style.marginTop="-100px",e._currentAngleMeasurement){switch(e._state){case 0:e._currentAngleMeasurement.originVisible=!1;break;case 1:e._currentAngleMeasurement.cornerVisible=!1,e._currentAngleMeasurement.originWireVisible=!1,e._currentAngleMeasurement.targetVisible=!1,e._currentAngleMeasurement.targetWireVisible=!1,e._currentAngleMeasurement.angleVisible=!1;break;case 2:e._currentAngleMeasurement.targetVisible=!1,e._currentAngleMeasurement.targetWireVisible=!1,e._currentAngleMeasurement.angleVisible=!1}s.style.cursor="default"}})),s.addEventListener("touchstart",this._onCanvasTouchStart=function(e){var t=e.touches,n=e.changedTouches;1===t.length&&1===n.length&&Qe(t[0],p)},{passive:!0}),s.addEventListener("touchend",this._onCanvasTouchEnd=function(t){var n=t.touches,r=t.changedTouches;if(0===n.length&&1===r.length){if(Qe(r[0],A),A[0]>p[0]+5||A[0]<p[0]-5||A[1]>p[1]+5||A[1]<p[1]-5)return;var a=i.pick({canvasPos:A,pickSurface:!0});if(a&&a.worldPos)switch(e._state){case 0:e._currentAngleMeasurement=e.plugin.createMeasurement({id:Z.createUUID(),origin:{entity:a.entity,worldPos:a.worldPos},corner:{entity:a.entity,worldPos:a.worldPos},target:{entity:a.entity,worldPos:a.worldPos},approximate:!0}),e._currentAngleMeasurement.originVisible=!0,e._currentAngleMeasurement.originWireVisible=!0,e._currentAngleMeasurement.cornerVisible=!1,e._currentAngleMeasurement.targetWireVisible=!1,e._currentAngleMeasurement.targetVisible=!1,e._currentAngleMeasurement.angleVisible=!1,e._currentAngleMeasurement.clickable=!1,e._state=1,e.fire("measurementStart",e._currentAngleMeasurement);break;case 1:e._currentAngleMeasurement.corner.worldPos=a.worldPos,e._currentAngleMeasurement.targetWireVisible=!1,e._currentAngleMeasurement.targetVisible=!0,e._currentAngleMeasurement.angleVisible=!0,e._state=2;break;case 2:e._currentAngleMeasurement.target.worldPos=a.worldPos,e._currentAngleMeasurement.targetVisible=!0,e._currentAngleMeasurement.angleVisible=!0,e._currentAngleMeasurement.clickable=!0,e.fire("measurementEnd",e._currentAngleMeasurement),e._currentAngleMeasurement=null,e._state=0}else e._currentAngleMeasurement&&(e._currentAngleMeasurement.destroy(),e._currentAngleMeasurement=null,e._state=0,e.fire("measurementCancel",e._currentAngleMeasurement))}},{passive:!0}),this._active=!0}}},{key:"deactivate",value:function(){if(this._active){this.reset();var e=this.plugin.viewer.scene.input,t=this.plugin.viewer.cameraControl,n=this.plugin.viewer.scene.canvas.canvas;e.off(this._onInputMouseDown),e.off(this._onInputMouseUp),t.off(this._onMouseHoverSurface),t.off(this._onPickedSurface),t.off(this._onHoverNothing),t.off(this._onPickedNothing),n.removeEventListener("touchstart",this._onCanvasTouchStart),n.removeEventListener("touchend",this._onCanvasTouchEnd),this._currentAngleMeasurement=null,this._active=!1}}},{key:"reset",value:function(){this._active&&(this._currentAngleMeasurement&&(this._currentAngleMeasurement.destroy(),this._currentAngleMeasurement=null),this._state=0)}},{key:"destroy",value:function(){this.deactivate(),v(T(n.prototype),"destroy",this).call(this)}}]),n}(),Qe=function(e,t){if(e){for(var n=e.target,r=0,i=0;n.offsetParent;)r+=n.offsetLeft,i+=n.offsetTop,n=n.offsetParent;t[0]=e.pageX-r,t[1]=e.pageY-i}else e=window.event,t[0]=e.x,t[1]=e.y;return t},We=function(e){I(n,z);var t=m(n);function n(e){var r,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return b(this,n),(r=t.call(this,"AngleMeasurements",e))._container=i.container||document.body,r._control=new je(g(r)),r._measurements={},r.defaultColor=void 0!==i.defaultColor?i.defaultColor:"#00BBFF",r.defaultLabelsVisible=!1!==i.defaultLabelsVisible,r.zIndex=i.zIndex||1e4,r._onMouseOver=function(e,t){r.fire("mouseOver",{plugin:g(r),angleMeasurement:t,measurement:t,event:e})},r._onMouseLeave=function(e,t){r.fire("mouseLeave",{plugin:g(r),angleMeasurement:t,measurement:t,event:e})},r._onContextMenu=function(e,t){r.fire("contextMenu",{plugin:g(r),angleMeasurement:t,measurement:t,event:e})},r}return P(n,[{key:"getContainerElement",value:function(){return this._container}},{key:"send",value:function(e,t){}},{key:"control",get:function(){return this._control}},{key:"measurements",get:function(){return this._measurements}},{key:"createMeasurement",value:function(){var e=this,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.viewer.scene.components[t.id]&&(this.error("Viewer scene component with this ID already exists: "+t.id),delete t.id);var n=t.origin,r=t.corner,i=t.target,a=new Ve(this,{id:t.id,plugin:this,container:this._container,origin:{entity:n.entity,worldPos:n.worldPos},corner:{entity:r.entity,worldPos:r.worldPos},target:{entity:i.entity,worldPos:i.worldPos},visible:t.visible,originVisible:!0,originWireVisible:!0,cornerVisible:!0,targetWireVisible:!0,targetVisible:!0,onMouseOver:this._onMouseOver,onMouseLeave:this._onMouseLeave,onContextMenu:this._onContextMenu});return this._measurements[a.id]=a,a.on("destroyed",(function(){delete e._measurements[a.id]})),this.fire("measurementCreated",a),a}},{key:"destroyMeasurement",value:function(e){var t=this._measurements[e];t?(t.destroy(),this.fire("measurementDestroyed",t)):this.log("AngleMeasurement not found: "+e)}},{key:"setLabelsShown",value:function(e){for(var t=0,n=Object.entries(this.measurements);t<n.length;t++){var r=p(n[t],2);r[0];r[1].labelShown=e}}},{key:"clear",value:function(){for(var e=Object.keys(this._measurements),t=0,n=e.length;t<n;t++)this.destroyMeasurement(e[t])}},{key:"destroy",value:function(){this.clear(),v(T(n.prototype),"destroy",this).call(this)}}]),n}(),ze=function(e){I(n,Me);var t=m(n);function n(e,r){var i;if(b(this,n),(i=t.call(this,e,r)).plugin=r.plugin,i._container=r.container,!i._container)throw"config missing: container";if(!r.markerElement&&!r.markerHTML)throw"config missing: need either markerElement or markerHTML";if(!r.labelElement&&!r.labelHTML)throw"config missing: need either labelElement or labelHTML";return i._htmlDirty=!1,r.markerElement?(i._marker=r.markerElement,i._marker.addEventListener("click",i._onMouseClickedExternalMarker=function(){i.plugin.fire("markerClicked",g(i))}),i._marker.addEventListener("mouseenter",i._onMouseEnterExternalMarker=function(){i.plugin.fire("markerMouseEnter",g(i))}),i._marker.addEventListener("mouseleave",i._onMouseLeaveExternalMarker=function(){i.plugin.fire("markerMouseLeave",g(i))}),i._markerExternal=!0):(i._markerHTML=r.markerHTML,i._htmlDirty=!0,i._markerExternal=!1),r.labelElement?(i._label=r.labelElement,i._labelExternal=!0):(i._labelHTML=r.labelHTML,i._htmlDirty=!0,i._labelExternal=!1),i._markerShown=!!r.markerShown,i._labelShown=!!r.labelShown,i._values=r.values||{},i._layoutDirty=!0,i._visibilityDirty=!0,i._buildHTML(),i._onTick=i.scene.on("tick",(function(){i._htmlDirty&&(i._buildHTML(),i._htmlDirty=!1,i._layoutDirty=!0,i._visibilityDirty=!0),(i._layoutDirty||i._visibilityDirty)&&(i._markerShown||i._labelShown)&&(i._updatePosition(),i._layoutDirty=!1),i._visibilityDirty&&(i._marker.style.visibility=i.visible&&i._markerShown?"visible":"hidden",i._label.style.visibility=i.visible&&i._markerShown&&i._labelShown?"visible":"hidden",i._visibilityDirty=!1)})),i.on("canvasPos",(function(){i._layoutDirty=!0})),i.on("visible",(function(){i._visibilityDirty=!0})),i.setMarkerShown(!1!==r.markerShown),i.setLabelShown(r.labelShown),i.eye=r.eye?r.eye.slice():null,i.look=r.look?r.look.slice():null,i.up=r.up?r.up.slice():null,i.projection=r.projection,i}return P(n,[{key:"_buildHTML",value:function(){var e=this;if(!this._markerExternal){this._marker&&(this._container.removeChild(this._marker),this._marker=null);var t=this._markerHTML||"<p></p>";ae.isArray(t)&&(t=t.join("")),t=this._renderTemplate(t);var n=document.createRange().createContextualFragment(t);this._marker=n.firstChild,this._container.appendChild(this._marker),this._marker.style.visibility=this._markerShown?"visible":"hidden",this._marker.addEventListener("click",(function(){e.plugin.fire("markerClicked",e)})),this._marker.addEventListener("mouseenter",(function(){e.plugin.fire("markerMouseEnter",e)})),this._marker.addEventListener("mouseleave",(function(){e.plugin.fire("markerMouseLeave",e)})),this._marker.addEventListener("wheel",(function(t){e.plugin.viewer.scene.canvas.canvas.dispatchEvent(new WheelEvent("wheel",t))}))}if(!this._labelExternal){this._label&&(this._container.removeChild(this._label),this._label=null);var r=this._labelHTML||"<p></p>";ae.isArray(r)&&(r=r.join("")),r=this._renderTemplate(r);var i=document.createRange().createContextualFragment(r);this._label=i.firstChild,this._container.appendChild(this._label),this._label.style.visibility=this._markerShown&&this._labelShown?"visible":"hidden",this._label.addEventListener("wheel",(function(t){e.plugin.viewer.scene.canvas.canvas.dispatchEvent(new WheelEvent("wheel",t))}))}}},{key:"_updatePosition",value:function(){var e=this.scene.canvas.boundary,t=e[0],n=e[1],r=this.canvasPos;this._marker.style.left=Math.floor(t+r[0])-12+"px",this._marker.style.top=Math.floor(n+r[1])-12+"px",this._marker.style["z-index"]=90005+Math.floor(this._viewPos[2])+1;this._label.style.left=20+Math.floor(t+r[0]+20)+"px",this._label.style.top=Math.floor(n+r[1]+-17)+"px",this._label.style["z-index"]=90005+Math.floor(this._viewPos[2])+1}},{key:"_renderTemplate",value:function(e){for(var t in this._values)if(this._values.hasOwnProperty(t)){var n=this._values[t];e=e.replace(new RegExp("{{"+t+"}}","g"),n)}return e}},{key:"setMarkerShown",value:function(e){e=!!e,this._markerShown!==e&&(this._markerShown=e,this._visibilityDirty=!0)}},{key:"getMarkerShown",value:function(){return this._markerShown}},{key:"setLabelShown",value:function(e){e=!!e,this._labelShown!==e&&(this._labelShown=e,this._visibilityDirty=!0)}},{key:"getLabelShown",value:function(){return this._labelShown}},{key:"setField",value:function(e,t){this._values[e]=t||"",this._htmlDirty=!0}},{key:"getField",value:function(e){return this._values[e]}},{key:"setValues",value:function(e){for(var t in e)if(e.hasOwnProperty(t)){var n=e[t];this.setField(t,n)}}},{key:"getValues",value:function(){return this._values}},{key:"destroy",value:function(){this._marker&&(this._markerExternal?(this._marker.removeEventListener("click",this._onMouseClickedExternalMarker),this._marker.removeEventListener("mouseenter",this._onMouseEnterExternalMarker),this._marker.removeEventListener("mouseleave",this._onMouseLeaveExternalMarker),this._marker=null):this._marker.parentNode.removeChild(this._marker)),this._label&&(this._labelExternal||this._label.parentNode.removeChild(this._label),this._label=null),this.scene.off(this._onTick),v(T(n.prototype),"destroy",this).call(this)}}]),n}(),Ke=Z.vec3(),Ye=Z.vec3(),Xe=Z.vec3(),qe=function(e){I(n,z);var t=m(n);function n(e,r){var i;return b(this,n),(i=t.call(this,"Annotations",e))._labelHTML=r.labelHTML||"<div></div>",i._markerHTML=r.markerHTML||"<div></div>",i._container=r.container||document.body,i._values=r.values||{},i.annotations={},i.surfaceOffset=r.surfaceOffset,i}return P(n,[{key:"getContainerElement",value:function(){return this._container}},{key:"send",value:function(e,t){if("clearAnnotations"===e)this.clear()}},{key:"surfaceOffset",get:function(){return this._surfaceOffset},set:function(e){null==e&&(e=.3),this._surfaceOffset=e}},{key:"createAnnotation",value:function(e){var t,n,r=this;if(this.viewer.scene.components[e.id]&&(this.error("Viewer component with this ID already exists: "+e.id),delete e.id),e.pickResult=e.pickResult||e.pickRecord,e.pickResult){var i=e.pickResult;if(i.worldPos&&i.worldNormal){var a=Z.normalizeVec3(i.worldNormal,Ke),s=Z.mulVec3Scalar(a,this._surfaceOffset,Ye);t=Z.addVec3(i.worldPos,s,Xe),n=i.entity}else this.error("Param 'pickResult' does not have both worldPos and worldNormal")}else t=e.worldPos,n=e.entity;var o=null;e.markerElementId&&((o=document.getElementById(e.markerElementId))||this.error("Can't find DOM element for 'markerElementId' value '"+e.markerElementId+"' - defaulting to internally-generated empty DIV"));var l=null;e.labelElementId&&((l=document.getElementById(e.labelElementId))||this.error("Can't find DOM element for 'labelElementId' value '"+e.labelElementId+"' - defaulting to internally-generated empty DIV"));var u=new ze(this.viewer.scene,{id:e.id,plugin:this,entity:n,worldPos:t,container:this._container,markerElement:o,labelElement:l,markerHTML:e.markerHTML||this._markerHTML,labelHTML:e.labelHTML||this._labelHTML,occludable:e.occludable,values:ae.apply(e.values,ae.apply(this._values,{})),markerShown:e.markerShown,labelShown:e.labelShown,eye:e.eye,look:e.look,up:e.up,projection:e.projection,visible:!1!==e.visible});return this.annotations[u.id]=u,u.on("destroyed",(function(){delete r.annotations[u.id],r.fire("annotationDestroyed",u.id)})),this.fire("annotationCreated",u.id),u}},{key:"destroyAnnotation",value:function(e){var t=this.annotations[e];t?t.destroy():this.log("Annotation not found: "+e)}},{key:"clear",value:function(){for(var e=Object.keys(this.annotations),t=0,n=e.length;t<n;t++)this.destroyAnnotation(e[t])}},{key:"destroy",value:function(){this.clear(),v(T(n.prototype),"destroy",this).call(this)}}]),n}(),Je=function(e){I(n,ve);var t=m(n);function n(e){var r,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return b(this,n),(r=t.call(this,e,i))._canvas=i.canvas,r._element=null,r._isCustom=!1,i.elementId&&(r._element=document.getElementById(i.elementId),r._element?r._adjustPosition():r.error("Can't find given Spinner HTML element: '"+i.elementId+"' - will automatically create default element")),r._element||r._createDefaultSpinner(),r.processes=0,r}return P(n,[{key:"type",get:function(){return"Spinner"}},{key:"_createDefaultSpinner",value:function(){this._injectDefaultCSS();var e=document.createElement("div"),t=e.style;t["z-index"]="9000",t.position="absolute",e.innerHTML='<div class="sk-fading-circle"> <div class="sk-circle1 sk-circle"></div> <div class="sk-circle2 sk-circle"></div> <div class="sk-circle3 sk-circle"></div> <div class="sk-circle4 sk-circle"></div> <div class="sk-circle5 sk-circle"></div> <div class="sk-circle6 sk-circle"></div> <div class="sk-circle7 sk-circle"></div> <div class="sk-circle8 sk-circle"></div> <div class="sk-circle9 sk-circle"></div> <div class="sk-circle10 sk-circle"></div> <div class="sk-circle11 sk-circle"></div> <div class="sk-circle12 sk-circle"></div> </div>',this._canvas.parentElement.appendChild(e),this._element=e,this._isCustom=!1,this._adjustPosition()}},{key:"_injectDefaultCSS",value:function(){var e="xeokit-spinner-css";if(!document.getElementById(e)){var t=document.createElement("style");t.innerHTML=".sk-fading-circle { background: transparent; margin: 20px auto; width: 50px; height:50px; position: relative; } .sk-fading-circle .sk-circle { width: 120%; height: 120%; position: absolute; left: 0; top: 0; } .sk-fading-circle .sk-circle:before { content: ''; display: block; margin: 0 auto; width: 15%; height: 15%; background-color: #ff8800; border-radius: 100%; -webkit-animation: sk-circleFadeDelay 1.2s infinite ease-in-out both; animation: sk-circleFadeDelay 1.2s infinite ease-in-out both; } .sk-fading-circle .sk-circle2 { -webkit-transform: rotate(30deg); -ms-transform: rotate(30deg); transform: rotate(30deg); } .sk-fading-circle .sk-circle3 { -webkit-transform: rotate(60deg); -ms-transform: rotate(60deg); transform: rotate(60deg); } .sk-fading-circle .sk-circle4 { -webkit-transform: rotate(90deg); -ms-transform: rotate(90deg); transform: rotate(90deg); } .sk-fading-circle .sk-circle5 { -webkit-transform: rotate(120deg); -ms-transform: rotate(120deg); transform: rotate(120deg); } .sk-fading-circle .sk-circle6 { -webkit-transform: rotate(150deg); -ms-transform: rotate(150deg); transform: rotate(150deg); } .sk-fading-circle .sk-circle7 { -webkit-transform: rotate(180deg); -ms-transform: rotate(180deg); transform: rotate(180deg); } .sk-fading-circle .sk-circle8 { -webkit-transform: rotate(210deg); -ms-transform: rotate(210deg); transform: rotate(210deg); } .sk-fading-circle .sk-circle9 { -webkit-transform: rotate(240deg); -ms-transform: rotate(240deg); transform: rotate(240deg); } .sk-fading-circle .sk-circle10 { -webkit-transform: rotate(270deg); -ms-transform: rotate(270deg); transform: rotate(270deg); } .sk-fading-circle .sk-circle11 { -webkit-transform: rotate(300deg); -ms-transform: rotate(300deg); transform: rotate(300deg); } .sk-fading-circle .sk-circle12 { -webkit-transform: rotate(330deg); -ms-transform: rotate(330deg); transform: rotate(330deg); } .sk-fading-circle .sk-circle2:before { -webkit-animation-delay: -1.1s; animation-delay: -1.1s; } .sk-fading-circle .sk-circle3:before { -webkit-animation-delay: -1s; animation-delay: -1s; } .sk-fading-circle .sk-circle4:before { -webkit-animation-delay: -0.9s; animation-delay: -0.9s; } .sk-fading-circle .sk-circle5:before { -webkit-animation-delay: -0.8s; animation-delay: -0.8s; } .sk-fading-circle .sk-circle6:before { -webkit-animation-delay: -0.7s; animation-delay: -0.7s; } .sk-fading-circle .sk-circle7:before { -webkit-animation-delay: -0.6s; animation-delay: -0.6s; } .sk-fading-circle .sk-circle8:before { -webkit-animation-delay: -0.5s; animation-delay: -0.5s; } .sk-fading-circle .sk-circle9:before { -webkit-animation-delay: -0.4s; animation-delay: -0.4s; } .sk-fading-circle .sk-circle10:before { -webkit-animation-delay: -0.3s; animation-delay: -0.3s; } .sk-fading-circle .sk-circle11:before { -webkit-animation-delay: -0.2s; animation-delay: -0.2s; } .sk-fading-circle .sk-circle12:before { -webkit-animation-delay: -0.1s; animation-delay: -0.1s; } @-webkit-keyframes sk-circleFadeDelay { 0%, 39%, 100% { opacity: 0; } 40% { opacity: 1; } } @keyframes sk-circleFadeDelay { 0%, 39%, 100% { opacity: 0; } 40% { opacity: 1; } }",t.id=e,document.body.appendChild(t)}}},{key:"_adjustPosition",value:function(){if(!this._isCustom){var e=this._canvas,t=this._element,n=t.style;n.left=e.offsetLeft+.5*e.clientWidth-.5*t.clientWidth+"px",n.top=e.offsetTop+.5*e.clientHeight-.5*t.clientHeight+"px"}}},{key:"processes",get:function(){return this._processes},set:function(e){if(e=e||0,this._processes!==e&&!(e<0)){var t=this._processes;this._processes=e;var n=this._element;n&&(n.style.visibility=this._processes>0?"visible":"hidden"),this.fire("processes",this._processes),0===this._processes&&this._processes!==t&&this.fire("zeroProcesses",this._processes)}}},{key:"_destroy",value:function(){this._element&&!this._isCustom&&(this._element.parentNode.removeChild(this._element),this._element=null);var e=document.getElementById("xeokit-spinner-css");e&&e.parentNode.removeChild(e)}}]),n}(),Ze={WEBGL:!1,SUPPORTED_EXTENSIONS:{}},$e=document.createElement("canvas");if($e){var et=$e.getContext("webgl",{antialias:!0})||$e.getContext("experimental-webgl",{antialias:!0});Ze.WEBGL=!!et,Ze.WEBGL&&(Ze.ANTIALIAS=et.getContextAttributes().antialias,et.getShaderPrecisionFormat?et.getShaderPrecisionFormat(et.FRAGMENT_SHADER,et.HIGH_FLOAT).precision>0?Ze.FS_MAX_FLOAT_PRECISION="highp":et.getShaderPrecisionFormat(et.FRAGMENT_SHADER,et.MEDIUM_FLOAT).precision>0?Ze.FS_MAX_FLOAT_PRECISION="mediump":Ze.FS_MAX_FLOAT_PRECISION="lowp":Ze.FS_MAX_FLOAT_PRECISION="mediump",Ze.DEPTH_BUFFER_BITS=et.getParameter(et.DEPTH_BITS),Ze.MAX_TEXTURE_SIZE=et.getParameter(et.MAX_TEXTURE_SIZE),Ze.MAX_CUBE_MAP_SIZE=et.getParameter(et.MAX_CUBE_MAP_TEXTURE_SIZE),Ze.MAX_RENDERBUFFER_SIZE=et.getParameter(et.MAX_RENDERBUFFER_SIZE),Ze.MAX_TEXTURE_UNITS=et.getParameter(et.MAX_COMBINED_TEXTURE_IMAGE_UNITS),Ze.MAX_TEXTURE_IMAGE_UNITS=et.getParameter(et.MAX_TEXTURE_IMAGE_UNITS),Ze.MAX_VERTEX_ATTRIBS=et.getParameter(et.MAX_VERTEX_ATTRIBS),Ze.MAX_VERTEX_UNIFORM_VECTORS=et.getParameter(et.MAX_VERTEX_UNIFORM_VECTORS),Ze.MAX_FRAGMENT_UNIFORM_VECTORS=et.getParameter(et.MAX_FRAGMENT_UNIFORM_VECTORS),Ze.MAX_VARYING_VECTORS=et.getParameter(et.MAX_VARYING_VECTORS),et.getSupportedExtensions().forEach((function(e){Ze.SUPPORTED_EXTENSIONS[e]=!0})))}var tt=["webgl2","experimental-webgl","webkit-3d","moz-webgl","moz-glweb20"],nt=function(e){I(n,ve);var t=m(n);function n(e){var r,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};b(this,n),(r=t.call(this,e,i))._backgroundColor=Z.vec3([i.backgroundColor?i.backgroundColor[0]:1,i.backgroundColor?i.backgroundColor[1]:1,i.backgroundColor?i.backgroundColor[2]:1]),r._backgroundColorFromAmbientLight=!!i.backgroundColorFromAmbientLight,r.canvas=i.canvas,r.gl=null,r.webgl2=!1,r.transparent=!!i.transparent,r.contextAttr=i.contextAttr||{},r.contextAttr.alpha=r.transparent,r.contextAttr.preserveDrawingBuffer=!!r.contextAttr.preserveDrawingBuffer,r.contextAttr.stencil=!1,r.contextAttr.premultipliedAlpha=!!r.contextAttr.premultipliedAlpha,r.contextAttr.antialias=!1!==r.contextAttr.antialias,r.resolutionScale=i.resolutionScale,r.canvas.width=Math.round(r.canvas.clientWidth*r._resolutionScale),r.canvas.height=Math.round(r.canvas.clientHeight*r._resolutionScale),r.boundary=[r.canvas.offsetLeft,r.canvas.offsetTop,r.canvas.clientWidth,r.canvas.clientHeight],r._initWebGL(i);var a=g(r);r.canvas.addEventListener("webglcontextlost",r._webglcontextlostListener=function(e){console.time("webglcontextrestored"),a.scene._webglContextLost(),a.fire("webglcontextlost"),e.preventDefault()},!1),r.canvas.addEventListener("webglcontextrestored",r._webglcontextrestoredListener=function(e){a._initWebGL(),a.gl&&(a.scene._webglContextRestored(a.gl),a.fire("webglcontextrestored",a.gl),e.preventDefault()),console.timeEnd("webglcontextrestored")},!1);var s=!0,o=new ResizeObserver((function(e){var t,n=f(e);try{for(n.s();!(t=n.n()).done;){t.value.contentBoxSize&&(s=!0)}}catch(e){n.e(e)}finally{n.f()}}));return o.observe(r.canvas),r._tick=r.scene.on("tick",(function(){s&&(s=!1,a.canvas.width=Math.round(a.canvas.clientWidth*a._resolutionScale),a.canvas.height=Math.round(a.canvas.clientHeight*a._resolutionScale),a.boundary[0]=a.canvas.offsetLeft,a.boundary[1]=a.canvas.offsetTop,a.boundary[2]=a.canvas.clientWidth,a.boundary[3]=a.canvas.clientHeight,a.fire("boundary",a.boundary))})),r._spinner=new Je(r.scene,{canvas:r.canvas,elementId:i.spinnerElementId}),r}return P(n,[{key:"type",get:function(){return"Canvas"}},{key:"backgroundColorFromAmbientLight",get:function(){return this._backgroundColorFromAmbientLight},set:function(e){this._backgroundColorFromAmbientLight=!1!==e,this.glRedraw()}},{key:"backgroundColor",get:function(){return this._backgroundColor},set:function(e){e?(this._backgroundColor[0]=e[0],this._backgroundColor[1]=e[1],this._backgroundColor[2]=e[2]):(this._backgroundColor[0]=1,this._backgroundColor[1]=1,this._backgroundColor[2]=1),this.glRedraw()}},{key:"resolutionScale",get:function(){return this._resolutionScale},set:function(e){if((e=e||1)!==this._resolutionScale){this._resolutionScale=e;var t=this.canvas;t.width=Math.round(t.clientWidth*this._resolutionScale),t.height=Math.round(t.clientHeight*this._resolutionScale),this.glRedraw()}}},{key:"spinner",get:function(){return this._spinner}},{key:"_createCanvas",value:function(){var e="xeokit-canvas-"+Z.createUUID(),t=document.getElementsByTagName("body")[0],n=document.createElement("div"),r=n.style;r.height="100%",r.width="100%",r.padding="0",r.margin="0",r.background="rgba(0,0,0,0);",r.float="left",r.left="0",r.top="0",r.position="absolute",r.opacity="1.0",r["z-index"]="-10000",n.innerHTML+='<canvas id="'+e+'" style="width: 100%; height: 100%; float: left; margin: 0; padding: 0;"></canvas>',t.appendChild(n),this.canvas=document.getElementById(e)}},{key:"_getElementXY",value:function(e){for(var t=0,n=0;e;)t+=e.offsetLeft-e.scrollLeft,n+=e.offsetTop-e.scrollTop,e=e.offsetParent;return{x:t,y:n}}},{key:"_initWebGL",value:function(){if(!this.gl)for(var e=0;!this.gl&&e<tt.length;e++)try{this.gl=this.canvas.getContext(tt[e],this.contextAttr)}catch(e){}this.gl||(this.error("Failed to get a WebGL context"),this.fire("webglContextFailed",!0,!0));var t=this.gl,n="__",r=t.activeTexture;t.activeTexture=function(e){n!==e&&(n=e,r.call(this,e))};var i={},a=t.bindTexture;t.bindTexture=function(e,t){i[n]!==t&&(i[n]=t,a.call(this,e,t))},this.gl&&this.webgl2&&(this.gl.hint(this.gl.FRAGMENT_SHADER_DERIVATIVE_HINT,this.gl.FASTEST),this.gl,WebGL2RenderingContext)}},{key:"getSnapshot",value:function(e){throw"Canvas#getSnapshot() has been replaced by Viewer#getSnapshot() - use that method instead."}},{key:"readPixels",value:function(e,t,n,r){return this.scene._renderer.readPixels(e,t,n,r)}},{key:"loseWebGLContext",value:function(){this.canvas.loseContext&&this.canvas.loseContext()}},{key:"destroy",value:function(){this.scene.off(this._tick),this._spinner._destroy(),this.canvas.removeEventListener("webglcontextlost",this._webglcontextlostListener),this.canvas.removeEventListener("webglcontextrestored",this._webglcontextrestoredListener),this.gl=null,v(T(n.prototype),"destroy",this).call(this)}}]),n}(),rt=function(){function e(t){b(this,e),this._scene=t,this._matPool=[],this._matPoolNextFreeIndex=0,this._rtcViewMats={},this._rtcPickViewMats={},this.reset()}return P(e,[{key:"reset",value:function(){this._matPoolNextFreeIndex=0,this._rtcViewMats={},this._rtcPickViewMats={},this.gl=this._scene.canvas.gl,this.lastProgramId=null,this.pbrEnabled=!1,this.colorTextureEnabled=!1,this.withSAO=!1,this.backfaces=!1,this.frontface=!0,this.textureUnit=0,this.drawElements=0,this.drawArrays=0,this.useProgram=0,this.bindTexture=0,this.bindArray=0,this.pass=0,this.shadowViewMatrix=null,this.shadowProjMatrix=null,this.pickViewMatrix=null,this.pickProjMatrix=null,this.pickZNear=.01,this.pickZFar=5e3,this.pickInvisible=!1,this.pickElementsCount=null,this.pickElementsOffset=null,this.lineWidth=1,this.snapPickLayerParams={},this.snapPickLayerNumber=0,this.snapPickCoordinateScale=Z.vec3(),this.snapPickOrigin=Z.vec3()}},{key:"getRTCViewMatrix",value:function(e,t){var n=this._rtcViewMats[e];return n||(n=this._getNewMat(),Ie(this._scene.camera.viewMatrix,t,n),this._rtcViewMats[e]=n),n}},{key:"getRTCPickViewMatrix",value:function(e,t){var n=this._rtcPickViewMats[e];if(!n){n=this._getNewMat();var r=this.pickViewMatrix||this._scene.camera.viewMatrix;Ie(r,t,n),this._rtcPickViewMats[e]=n}return n}},{key:"_getNewMat",value:function(){var e=this._matPool[this._matPoolNextFreeIndex];return e||(e=Z.mat4(),this._matPool[this._matPoolNextFreeIndex]=e),this._matPoolNextFreeIndex++,e}}]),e}(),it=function(){function e(){b(this,e),this.entity=null,this.primitive=null,this.primIndex=-1,this.pickSurfacePrecision=!1,this.touchInput=!1,this._canvasPos=new Int16Array([0,0]),this._origin=new Float64Array([0,0,0]),this._direction=new Float64Array([0,0,0]),this._indices=new Int32Array(3),this._localPos=new Float64Array([0,0,0]),this._worldPos=new Float64Array([0,0,0]),this._viewPos=new Float64Array([0,0,0]),this._bary=new Float64Array([0,0,0]),this._worldNormal=new Float64Array([0,0,0]),this._uv=new Float64Array([0,0]),this.reset()}return P(e,[{key:"canvasPos",get:function(){return this._gotCanvasPos?this._canvasPos:null},set:function(e){e?(this._canvasPos[0]=e[0],this._canvasPos[1]=e[1],this._gotCanvasPos=!0):this._gotCanvasPos=!1}},{key:"origin",get:function(){return this._gotOrigin?this._origin:null},set:function(e){e?(this._origin[0]=e[0],this._origin[1]=e[1],this._origin[2]=e[2],this._gotOrigin=!0):this._gotOrigin=!1}},{key:"direction",get:function(){return this._gotDirection?this._direction:null},set:function(e){e?(this._direction[0]=e[0],this._direction[1]=e[1],this._direction[2]=e[2],this._gotDirection=!0):this._gotDirection=!1}},{key:"indices",get:function(){return this.entity&&this._gotIndices?this._indices:null},set:function(e){e?(this._indices[0]=e[0],this._indices[1]=e[1],this._indices[2]=e[2],this._gotIndices=!0):this._gotIndices=!1}},{key:"localPos",get:function(){return this.entity&&this._gotLocalPos?this._localPos:null},set:function(e){e?(this._localPos[0]=e[0],this._localPos[1]=e[1],this._localPos[2]=e[2],this._gotLocalPos=!0):this._gotLocalPos=!1}},{key:"worldPos",get:function(){return this._gotWorldPos?this._worldPos:null},set:function(e){e?(this._worldPos[0]=e[0],this._worldPos[1]=e[1],this._worldPos[2]=e[2],this._gotWorldPos=!0):this._gotWorldPos=!1}},{key:"viewPos",get:function(){return this.entity&&this._gotViewPos?this._viewPos:null},set:function(e){e?(this._viewPos[0]=e[0],this._viewPos[1]=e[1],this._viewPos[2]=e[2],this._gotViewPos=!0):this._gotViewPos=!1}},{key:"bary",get:function(){return this.entity&&this._gotBary?this._bary:null},set:function(e){e?(this._bary[0]=e[0],this._bary[1]=e[1],this._bary[2]=e[2],this._gotBary=!0):this._gotBary=!1}},{key:"worldNormal",get:function(){return this.entity&&this._gotWorldNormal?this._worldNormal:null},set:function(e){e?(this._worldNormal[0]=e[0],this._worldNormal[1]=e[1],this._worldNormal[2]=e[2],this._gotWorldNormal=!0):this._gotWorldNormal=!1}},{key:"uv",get:function(){return this.entity&&this._gotUV?this._uv:null},set:function(e){e?(this._uv[0]=e[0],this._uv[1]=e[1],this._gotUV=!0):this._gotUV=!1}},{key:"reset",value:function(){this.entity=null,this.primIndex=-1,this.primitive=null,this.pickSurfacePrecision=!1,this._gotCanvasPos=!1,this._gotOrigin=!1,this._gotDirection=!1,this._gotIndices=!1,this._gotLocalPos=!1,this._gotWorldPos=!1,this._gotViewPos=!1,this._gotBary=!1,this._gotWorldNormal=!1,this._gotUV=!1,this.touchInput=!1}}]),e}(),at=function(){function e(t,n,r){if(b(this,e),this.allocated=!1,this.compiled=!1,this.handle=t.createShader(n),this.handle){if(this.allocated=!0,t.shaderSource(this.handle,r),t.compileShader(this.handle),this.compiled=t.getShaderParameter(this.handle,t.COMPILE_STATUS),!this.compiled&&!t.isContextLost()){for(var i=r.split("\n"),a=[],s=0;s<i.length;s++)a.push(s+1+": "+i[s]+"\n");this.errors=[],this.errors.push(""),this.errors.push(t.getShaderInfoLog(this.handle)),this.errors=this.errors.concat(a.join(""))}}else this.errors=["Failed to allocate"]}return P(e,[{key:"destroy",value:function(){}}]),e}(),st=P((function e(t,n){b(this,e),this.bindTexture=function(e,r){return!!e.bind(r)&&(t.uniform1i(n,r),!0)}})),ot=function(){function e(t,n){b(this,e),this._gl=t,this.location=n}return P(e,[{key:"bindArrayBuffer",value:function(e){e&&(e.bind(),this._gl.enableVertexAttribArray(this.location),this._gl.vertexAttribPointer(this.location,e.itemSize,e.itemType,e.normalized,e.stride,e.offset))}}]),e}(),lt=new G({});function ut(e){for(var t,n,r=[],i=0,a=e.length;i<a;i++)(n=(t=e[i]).indexOf("/"))>0&&"/"===t.charAt(n+1)&&(t=t.substring(0,n)),r.push(t);return r.join("\n")}function ct(e){console.error(e.join("\n"))}var ft=function(){function e(t,n){b(this,e),this.id=lt.addItem({}),this.source=n,this.init(t)}return P(e,[{key:"init",value:function(e){if(this.gl=e,this.allocated=!1,this.compiled=!1,this.linked=!1,this.validated=!1,this.errors=null,this.uniforms={},this.samplers={},this.attributes={},this._vertexShader=new at(e,e.VERTEX_SHADER,ut(this.source.vertex)),this._fragmentShader=new at(e,e.FRAGMENT_SHADER,ut(this.source.fragment)),!this._vertexShader.allocated)return this.errors=["Vertex shader failed to allocate"].concat(this._vertexShader.errors),void ct(this.errors);if(!this._fragmentShader.allocated)return this.errors=["Fragment shader failed to allocate"].concat(this._fragmentShader.errors),void ct(this.errors);if(this.allocated=!0,!this._vertexShader.compiled)return this.errors=["Vertex shader failed to compile"].concat(this._vertexShader.errors),void ct(this.errors);if(!this._fragmentShader.compiled)return this.errors=["Fragment shader failed to compile"].concat(this._fragmentShader.errors),void ct(this.errors);var t,n,r,i,a;if(this.compiled=!0,this.handle=e.createProgram(),this.handle){if(e.attachShader(this.handle,this._vertexShader.handle),e.attachShader(this.handle,this._fragmentShader.handle),e.linkProgram(this.handle),this.linked=e.getProgramParameter(this.handle,e.LINK_STATUS),this.validated=!0,!this.linked||!this.validated)return this.errors=[],this.errors.push(""),this.errors.push(e.getProgramInfoLog(this.handle)),this.errors.push("\nVertex shader:\n"),this.errors=this.errors.concat(this.source.vertex),this.errors.push("\nFragment shader:\n"),this.errors=this.errors.concat(this.source.fragment),void ct(this.errors);var s=e.getProgramParameter(this.handle,e.ACTIVE_UNIFORMS);for(n=0;n<s;++n)(r=e.getActiveUniform(this.handle,n))&&("\0"===(i=r.name)[i.length-1]&&(i=i.substr(0,i.length-1)),a=e.getUniformLocation(this.handle,i),r.type===e.SAMPLER_2D||r.type===e.SAMPLER_CUBE||35682===r.type||e instanceof WebGL2RenderingContext&&(r.type===e.UNSIGNED_INT_SAMPLER_2D||r.type===e.INT_SAMPLER_2D)?this.samplers[i]=new st(e,a):this.uniforms[i]=a);var o=e.getProgramParameter(this.handle,e.ACTIVE_ATTRIBUTES);for(n=0;n<o;n++)(t=e.getActiveAttrib(this.handle,n))&&(a=e.getAttribLocation(this.handle,t.name),this.attributes[t.name]=new ot(e,a));this.allocated=!0}else this.errors=["Failed to allocate program"]}},{key:"bind",value:function(){this.allocated&&this.gl.useProgram(this.handle)}},{key:"getLocation",value:function(e){if(this.allocated)return this.uniforms[e]}},{key:"getAttribute",value:function(e){if(this.allocated)return this.attributes[e]}},{key:"bindTexture",value:function(e,t,n){if(!this.allocated)return!1;var r=this.samplers[e];return!!r&&r.bindTexture(t,n)}},{key:"destroy",value:function(){this.allocated&&(lt.removeItem(this.id),this.gl.deleteProgram(this.handle),this.gl.deleteShader(this._vertexShader.handle),this.gl.deleteShader(this._fragmentShader.handle),this.handle=null,this.attributes=null,this.uniforms=null,this.samplers=null,this.allocated=!1)}}]),e}(),pt=function(){function e(t,n,r,i,a,s,o,l,u){switch(b(this,e),this._gl=t,this.type=n,this.allocated=!1,r.constructor){case Uint8Array:this.itemType=t.UNSIGNED_BYTE,this.itemByteSize=1;break;case Int8Array:this.itemType=t.BYTE,this.itemByteSize=1;break;case Uint16Array:this.itemType=t.UNSIGNED_SHORT,this.itemByteSize=2;break;case Int16Array:this.itemType=t.SHORT,this.itemByteSize=2;break;case Uint32Array:this.itemType=t.UNSIGNED_INT,this.itemByteSize=4;break;case Int32Array:this.itemType=t.INT,this.itemByteSize=4;break;default:this.itemType=t.FLOAT,this.itemByteSize=4}this.usage=s,this.length=0,this.dataLength=i,this.numItems=0,this.itemSize=a,this.normalized=!!o,this.stride=l||0,this.offset=u||0,this._allocate(r)}return P(e,[{key:"_allocate",value:function(e){if(this.allocated=!1,this._handle=this._gl.createBuffer(),!this._handle)throw"Failed to allocate WebGL ArrayBuffer";this._handle&&(this._gl.bindBuffer(this.type,this._handle),this._gl.bufferData(this.type,e.length>this.dataLength?e.slice(0,this.dataLength):e,this.usage),this._gl.bindBuffer(this.type,null),this.length=e.length,this.numItems=this.length/this.itemSize,this.allocated=!0)}},{key:"setData",value:function(e,t){this.allocated&&(e.length+(t||0)>this.length?(this.destroy(),this._allocate(e)):(this._gl.bindBuffer(this.type,this._handle),t||0===t?this._gl.bufferSubData(this.type,t*this.itemByteSize,e):this._gl.bufferData(this.type,e,this.usage),this._gl.bindBuffer(this.type,null)))}},{key:"bind",value:function(){this.allocated&&this._gl.bindBuffer(this.type,this._handle)}},{key:"unbind",value:function(){this.allocated&&this._gl.bindBuffer(this.type,null)}},{key:"destroy",value:function(){this.allocated&&(this._gl.deleteBuffer(this._handle),this._handle=null,this.allocated=!1)}}]),e}(),At=function(){function e(t,n){b(this,e),this.scene=t,this.aabb=Z.AABB3(),this.origin=Z.vec3(n),this.originHash=this.origin.join(),this.numMarkers=0,this.markers={},this.markerList=[],this.markerIndices={},this.positions=[],this.indices=[],this.positionsBuf=null,this.lenPositionsBuf=0,this.indicesBuf=null,this.sectionPlanesActive=[],this.culledBySectionPlanes=!1,this.occlusionTestList=[],this.lenOcclusionTestList=0,this.pixels=[],this.aabbDirty=!1,this.markerListDirty=!1,this.positionsDirty=!0,this.occlusionTestListDirty=!1}return P(e,[{key:"addMarker",value:function(e){this.markers[e.id]=e,this.markerListDirty=!0,this.numMarkers++}},{key:"markerWorldPosUpdated",value:function(e){if(this.markers[e.id]){var t=this.markerIndices[e.id];this.positions[3*t+0]=e.worldPos[0],this.positions[3*t+1]=e.worldPos[1],this.positions[3*t+2]=e.worldPos[2],this.positionsDirty=!0}}},{key:"removeMarker",value:function(e){delete this.markers[e.id],this.markerListDirty=!0,this.numMarkers--}},{key:"update",value:function(){this.markerListDirty&&(this._buildMarkerList(),this.markerListDirty=!1,this.positionsDirty=!0,this.occlusionTestListDirty=!0),this.positionsDirty&&(this._buildPositions(),this.positionsDirty=!1,this.aabbDirty=!0,this.vbosDirty=!0),this.aabbDirty&&(this._buildAABB(),this.aabbDirty=!1),this.vbosDirty&&(this._buildVBOs(),this.vbosDirty=!1),this.occlusionTestListDirty&&this._buildOcclusionTestList(),this._updateActiveSectionPlanes()}},{key:"_buildMarkerList",value:function(){for(var e in this.numMarkers=0,this.markers)this.markers.hasOwnProperty(e)&&(this.markerList[this.numMarkers]=this.markers[e],this.markerIndices[e]=this.numMarkers,this.numMarkers++);this.markerList.length=this.numMarkers}},{key:"_buildPositions",value:function(){for(var e=0,t=0;t<this.numMarkers;t++)if(this.markerList[t]){var n=this.markerList[t].worldPos;this.positions[e++]=n[0],this.positions[e++]=n[1],this.positions[e++]=n[2],this.indices[t]=t}this.positions.length=3*this.numMarkers,this.indices.length=this.numMarkers}},{key:"_buildAABB",value:function(){var e=this.aabb;Z.collapseAABB3(e),Z.expandAABB3Points3(e,this.positions);var t=this.origin;e[0]+=t[0],e[1]+=t[1],e[2]+=t[2],e[3]+=t[0],e[4]+=t[1],e[5]+=t[2]}},{key:"_buildVBOs",value:function(){if(this.positionsBuf){if(this.lenPositionsBuf===this.positions.length)return void this.positionsBuf.setData(this.positions);this.positionsBuf.destroy(),this.positionsBuf=null,this.indicesBuf.destroy(),this.indicesBuf=null}var e=this.scene.canvas.gl,t=3*this.numMarkers,n=this.numMarkers;this.positionsBuf=new pt(e,e.ARRAY_BUFFER,new Float32Array(this.positions),t,3,e.STATIC_DRAW),this.indicesBuf=new pt(e,e.ELEMENT_ARRAY_BUFFER,new Uint16Array(this.indices),n,1,e.STATIC_DRAW),this.lenPositionsBuf=this.positions.length}},{key:"_buildOcclusionTestList",value:function(){var e=this.scene.canvas,t=this.scene.camera.perspective.near,n=e.boundary,r=n[2],i=n[3],a=0;this.lenOcclusionTestList=0;for(var s=0;s<this.numMarkers;s++){var o=this.markerList[s];if(o.viewPos[2]>-t)o._setVisible(!1);else{var l=o.canvasPos,u=l[0],c=l[1];u+10<0||c+10<0||u-10>r||c-10>i?o._setVisible(!1):!o.entity||o.entity.visible?o.occludable?(this.occlusionTestList[this.lenOcclusionTestList++]=o,this.pixels[a++]=u,this.pixels[a++]=c):o._setVisible(!0):o._setVisible(!1)}}}},{key:"_updateActiveSectionPlanes",value:function(){var e=this.scene._sectionPlanesState.sectionPlanes,t=e.length;if(t>0)for(var n=0;n<t;n++){var r=e[n];if(r.active){var i=Z.planeAABB3Intersect(r.dir,r.dist,this.aabb);if(-1===i)return void(this.culledBySectionPlanes=!0);var a=0===i;this.sectionPlanesActive[n]=a}else this.sectionPlanesActive[n]=!1}this.culledBySectionPlanes=!1}},{key:"destroy",value:function(){this.markers={},this.markerList.length=0,this.positionsBuf&&this.positionsBuf.destroy(),this.indicesBuf&&this.indicesBuf.destroy()}}]),e}(),dt=Z.vec3([1,0,0]),vt=Z.vec3(),ht=function(){function e(t,n){var r=this;b(this,e),this._scene=t,this._renderBufferManager=n,this._occlusionLayers={},this._occlusionLayersList=[],this._occlusionLayersListDirty=!1,this._shaderSource=null,this._program=null,this._shaderSourceHash=null,this._shaderSourceDirty=!0,this._programDirty=!1,this._markersToOcclusionLayersMap={},this._onCameraViewMatrix=t.camera.on("viewMatrix",(function(){r._occlusionTestListDirty=!0})),this._onCameraProjMatrix=t.camera.on("projMatrix",(function(){r._occlusionTestListDirty=!0})),this._onCanvasBoundary=t.canvas.on("boundary",(function(){r._occlusionTestListDirty=!0}))}return P(e,[{key:"addMarker",value:function(e){var t=e.origin.join(),n=this._occlusionLayers[t];n||(n=new At(this._scene,e.origin),this._occlusionLayers[n.originHash]=n,this._occlusionLayersListDirty=!0),n.addMarker(e),this._markersToOcclusionLayersMap[e.id]=n,this._occlusionTestListDirty=!0}},{key:"markerWorldPosUpdated",value:function(e){var t=this._markersToOcclusionLayersMap[e.id];if(t){var n=e.origin.join();if(n!==t.originHash){1===t.numMarkers?(t.destroy(),delete this._occlusionLayers[t.originHash],this._occlusionLayersListDirty=!0):t.removeMarker(e);var r=this._occlusionLayers[n];r||(r=new At(this._scene,e.origin),this._occlusionLayers[n]=t,this._occlusionLayersListDirty=!0),r.addMarker(e),this._markersToOcclusionLayersMap[e.id]=r}else t.markerWorldPosUpdated(e)}else e.error("Marker has not been added to OcclusionTester")}},{key:"removeMarker",value:function(e){var t=e.origin.join(),n=this._occlusionLayers[t];n&&(1===n.numMarkers?(n.destroy(),delete this._occlusionLayers[n.originHash],this._occlusionLayersListDirty=!0):n.removeMarker(e),delete this._markersToOcclusionLayersMap[e.id])}},{key:"needOcclusionTest",get:function(){return this._occlusionTestListDirty}},{key:"bindRenderBuf",value:function(){var e=[this._scene.canvas.canvas.id,this._scene._sectionPlanesState.getHash()].join(";");if(e!==this._shaderSourceHash&&(this._shaderSourceHash=e,this._shaderSourceDirty=!0),this._shaderSourceDirty&&(this._buildShaderSource(),this._shaderSourceDirty=!1,this._programDirty=!0),this._programDirty&&(this._buildProgram(),this._programDirty=!1,this._occlusionTestListDirty=!0),this._occlusionLayersListDirty&&(this._buildOcclusionLayersList(),this._occlusionLayersListDirty=!1),this._occlusionTestListDirty){for(var t=0,n=this._occlusionLayersList.length;t<n;t++){this._occlusionLayersList[t].occlusionTestListDirty=!0}this._occlusionTestListDirty=!1}this._readPixelBuf=this._renderBufferManager.getRenderBuffer("occlusionReadPix"),this._readPixelBuf.bind(),this._readPixelBuf.clear()}},{key:"_buildOcclusionLayersList",value:function(){var e=0;for(var t in this._occlusionLayers)this._occlusionLayers.hasOwnProperty(t)&&(this._occlusionLayersList[e++]=this._occlusionLayers[t]);this._occlusionLayersList.length=e}},{key:"_buildShaderSource",value:function(){this._shaderSource={vertex:this._buildVertexShaderSource(),fragment:this._buildFragmentShaderSource()}}},{key:"_buildVertexShaderSource",value:function(){var e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,n=[];return n.push("#version 300 es"),n.push("// OcclusionTester vertex shader"),n.push("in vec3 position;"),n.push("uniform mat4 modelMatrix;"),n.push("uniform mat4 viewMatrix;"),n.push("uniform mat4 projMatrix;"),e.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("out float vFragDepth;")),t&&n.push("out vec4 vWorldPosition;"),n.push("void main(void) {"),n.push("vec4 worldPosition = vec4(position, 1.0); "),n.push(" vec4 viewPosition = viewMatrix * worldPosition;"),t&&n.push(" vWorldPosition = worldPosition;"),n.push(" vec4 clipPos = projMatrix * viewPosition;"),n.push(" gl_PointSize = 20.0;"),e.logarithmicDepthBufferEnabled?n.push("vFragDepth = 1.0 + clipPos.w;"):n.push("clipPos.z += -0.001;"),n.push(" gl_Position = clipPos;"),n.push("}"),n}},{key:"_buildFragmentShaderSource",value:function(){var e=this._scene,t=e._sectionPlanesState,n=t.sectionPlanes.length>0,r=[];if(r.push("#version 300 es"),r.push("// OcclusionTester fragment shader"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),e.logarithmicDepthBufferEnabled&&(r.push("uniform float logDepthBufFC;"),r.push("in float vFragDepth;")),n){r.push("in vec4 vWorldPosition;");for(var i=0;i<t.sectionPlanes.length;i++)r.push("uniform bool sectionPlaneActive"+i+";"),r.push("uniform vec3 sectionPlanePos"+i+";"),r.push("uniform vec3 sectionPlaneDir"+i+";")}if(r.push("out vec4 outColor;"),r.push("void main(void) {"),n){r.push(" float dist = 0.0;");for(var a=0;a<t.sectionPlanes.length;a++)r.push("if (sectionPlaneActive"+a+") {"),r.push(" dist += clamp(dot(-sectionPlaneDir"+a+".xyz, vWorldPosition.xyz - sectionPlanePos"+a+".xyz), 0.0, 1000.0);"),r.push("}");r.push(" if (dist > 0.0) { discard; }")}return e.logarithmicDepthBufferEnabled&&r.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),r.push(" outColor = vec4(1.0, 0.0, 0.0, 1.0); "),r.push("}"),r}},{key:"_buildProgram",value:function(){this._program&&this._program.destroy();var e=this._scene,t=e.canvas.gl,n=e._sectionPlanesState;if(this._program=new ft(t,this._shaderSource),this._program.errors)this.errors=this._program.errors;else{var r=this._program;this._uViewMatrix=r.getLocation("viewMatrix"),this._uProjMatrix=r.getLocation("projMatrix"),this._uSectionPlanes=[];for(var i=0,a=n.sectionPlanes.length;i<a;i++)this._uSectionPlanes.push({active:r.getLocation("sectionPlaneActive"+i),pos:r.getLocation("sectionPlanePos"+i),dir:r.getLocation("sectionPlaneDir"+i)});this._aPosition=r.getAttribute("position"),e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=r.getLocation("logDepthBufFC"))}}},{key:"drawMarkers",value:function(){var e=this._scene,t=e.canvas.gl,n=this._program,r=e._sectionPlanesState,i=e.camera,a=e.camera.project;if(n.bind(),t.uniformMatrix4fv(this._uProjMatrix,!1,i._project._state.matrix),e.logarithmicDepthBufferEnabled){var s=2/(Math.log(a.far+1)/Math.LN2);t.uniform1f(this._uLogDepthBufFC,s)}for(var o=0,l=this._occlusionLayersList.length;o<l;o++){var u=this._occlusionLayersList[o];if(u.update(),!u.culledBySectionPlanes){var c=u.origin;t.uniformMatrix4fv(this._uViewMatrix,!1,Ie(i.viewMatrix,c));var f=r.sectionPlanes.length;if(f>0)for(var p=r.sectionPlanes,A=0;A<f;A++){var d=this._uSectionPlanes[A];if(d){var v=u.sectionPlanesActive[A];if(t.uniform1i(d.active,v?1:0),v){var h=p[A];t.uniform3fv(d.pos,ge(h.dist,h.dir,c,vt)),t.uniform3fv(d.dir,h.dir)}}}this._aPosition.bindArrayBuffer(u.positionsBuf);var I=u.indicesBuf;I.bind(),t.drawElements(t.POINTS,I.numItems,I.itemType,0)}}}},{key:"doOcclusionTest",value:function(){for(var e=this._scene.canvas.resolutionScale,t=255*dt[0],n=255*dt[1],r=255*dt[2],i=0,a=this._occlusionLayersList.length;i<a;i++)for(var s=this._occlusionLayersList[i],o=0;o<s.lenOcclusionTestList;o++){var l=s.occlusionTestList[o],u=2*o,c=this._readPixelBuf.read(Math.round(s.pixels[u]*e),Math.round(s.pixels[u+1]*e)),f=c[0]===t&&c[1]===n&&c[2]===r;l._setVisible(f)}}},{key:"unbindRenderBuf",value:function(){this._readPixelBuf.unbind()}},{key:"destroy",value:function(){if(!this.destroyed){for(var e=0,t=this._occlusionLayersList.length;e<t;e++){this._occlusionLayersList[e].destroy()}this._program&&this._program.destroy(),this._scene.camera.off(this._onCameraViewMatrix),this._scene.camera.off(this._onCameraProjMatrix),this._scene.canvas.off(this._onCanvasBoundary),this.destroyed=!0}}}]),e}(),It=Z.vec2(),yt=function(){function e(t){b(this,e),this._scene=t,this._numSamples=null,this._program=null,this._programError=!1,this._aPosition=null,this._aUV=null,this._uDepthTexture="uDepthTexture",this._uCameraNear=null,this._uCameraFar=null,this._uCameraProjectionMatrix=null,this._uCameraInverseProjectionMatrix=null,this._uScale=null,this._uIntensity=null,this._uBias=null,this._uKernelRadius=null,this._uMinResolution=null,this._uRandomSeed=null,this._uvBuf=null,this._positionsBuf=null,this._indicesBuf=null}return P(e,[{key:"render",value:function(e){var t=this;if(this._build(),!this._programError){this._getInverseProjectMat||(this._getInverseProjectMat=function(){var e=!0;t._scene.camera.on("projMatrix",(function(){e=!0}));var n=Z.mat4();return function(){return e&&Z.inverseMat4(i.camera.projMatrix,n),n}}());var n=this._scene.canvas.gl,r=this._program,i=this._scene,a=i.sao,s=n.drawingBufferWidth,o=n.drawingBufferHeight,l=i.camera.project._state,u=l.near,c=l.far,f=l.matrix,p=this._getInverseProjectMat(),A=Math.random(),d="perspective"===i.camera.projection;It[0]=s,It[1]=o,n.viewport(0,0,s,o),n.clearColor(0,0,0,1),n.disable(n.DEPTH_TEST),n.disable(n.BLEND),n.frontFace(n.CCW),n.clear(n.COLOR_BUFFER_BIT),r.bind(),n.uniform1f(this._uCameraNear,u),n.uniform1f(this._uCameraFar,c),n.uniformMatrix4fv(this._uCameraProjectionMatrix,!1,f),n.uniformMatrix4fv(this._uCameraInverseProjectionMatrix,!1,p),n.uniform1i(this._uPerspective,d),n.uniform1f(this._uScale,a.scale*(c/5)),n.uniform1f(this._uIntensity,a.intensity),n.uniform1f(this._uBias,a.bias),n.uniform1f(this._uKernelRadius,a.kernelRadius),n.uniform1f(this._uMinResolution,a.minResolution),n.uniform2fv(this._uViewport,It),n.uniform1f(this._uRandomSeed,A);var v=e.getDepthTexture();r.bindTexture(this._uDepthTexture,v,0),this._aUV.bindArrayBuffer(this._uvBuf),this._aPosition.bindArrayBuffer(this._positionsBuf),this._indicesBuf.bind(),n.drawElements(n.TRIANGLES,this._indicesBuf.numItems,this._indicesBuf.itemType,0)}}},{key:"_build",value:function(){var e=!1,t=this._scene.sao;if(t.numSamples!==this._numSamples&&(this._numSamples=Math.floor(t.numSamples),e=!0),e){var n=this._scene.canvas.gl;if(this._program&&(this._program.destroy(),this._program=null),this._program=new ft(n,{vertex:["#version 300 es\n precision highp float;\n precision highp int;\n \n in vec3 aPosition;\n in vec2 aUV; \n \n out vec2 vUV;\n \n void main () {\n gl_Position = vec4(aPosition, 1.0);\n vUV = aUV;\n }"],fragment:["#version 300 es \n precision highp float;\n precision highp int; \n \n #define NORMAL_TEXTURE 0\n #define PI 3.14159265359\n #define PI2 6.28318530718\n #define EPSILON 1e-6\n #define NUM_SAMPLES ".concat(this._numSamples,"\n #define NUM_RINGS 4 \n \n in vec2 vUV;\n \n uniform sampler2D uDepthTexture;\n \n uniform float uCameraNear;\n uniform float uCameraFar;\n uniform mat4 uProjectMatrix;\n uniform mat4 uInverseProjectMatrix;\n \n uniform bool uPerspective;\n\n uniform float uScale;\n uniform float uIntensity;\n uniform float uBias;\n uniform float uKernelRadius;\n uniform float uMinResolution;\n uniform vec2 uViewport;\n uniform float uRandomSeed;\n\n float pow2( const in float x ) { return x*x; }\n \n highp float rand( const in vec2 uv ) {\n const highp float a = 12.9898, b = 78.233, c = 43758.5453;\n highp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI );\n return fract(sin(sn) * c);\n }\n\n vec3 packNormalToRGB( const in vec3 normal ) {\n return normalize( normal ) * 0.5 + 0.5;\n }\n\n vec3 unpackRGBToNormal( const in vec3 rgb ) {\n return 2.0 * rgb.xyz - 1.0;\n }\n\n const float packUpscale = 256. / 255.;\n const float unpackDownScale = 255. / 256.; \n\n const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );\n const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. ); \n\n const float shiftRights = 1. / 256.;\n\n vec4 packFloatToRGBA( const in float v ) {\n vec4 r = vec4( fract( v * packFactors ), v );\n r.yzw -= r.xyz * shiftRights; \n return r * packUpscale;\n }\n\n float unpackRGBAToFloat( const in vec4 v ) { \n return dot( floor( v * 255.0 + 0.5 ) / 255.0, unPackFactors );\n }\n \n float perspectiveDepthToViewZ( const in float invClipZ, const in float near, const in float far ) {\n return ( near * far ) / ( ( far - near ) * invClipZ - far );\n }\n\n float orthographicDepthToViewZ( const in float linearClipZ, const in float near, const in float far ) {\n return linearClipZ * ( near - far ) - near;\n }\n \n float getDepth( const in vec2 screenPosition ) {\n return vec4(texture(uDepthTexture, screenPosition)).r;\n }\n\n float getViewZ( const in float depth ) {\n if (uPerspective) {\n return perspectiveDepthToViewZ( depth, uCameraNear, uCameraFar );\n } else {\n return orthographicDepthToViewZ( depth, uCameraNear, uCameraFar );\n }\n }\n\n vec3 getViewPos( const in vec2 screenPos, const in float depth, const in float viewZ ) {\n \tfloat clipW = uProjectMatrix[2][3] * viewZ + uProjectMatrix[3][3];\n \tvec4 clipPosition = vec4( ( vec3( screenPos, depth ) - 0.5 ) * 2.0, 1.0 );\n \tclipPosition *= clipW; \n \treturn ( uInverseProjectMatrix * clipPosition ).xyz;\n }\n\n vec3 getViewNormal( const in vec3 viewPosition, const in vec2 screenPos ) { \n return normalize( cross( dFdx( viewPosition ), dFdy( viewPosition ) ) );\n }\n\n float scaleDividedByCameraFar;\n float minResolutionMultipliedByCameraFar;\n\n float getOcclusion( const in vec3 centerViewPosition, const in vec3 centerViewNormal, const in vec3 sampleViewPosition ) {\n \tvec3 viewDelta = sampleViewPosition - centerViewPosition;\n \tfloat viewDistance = length( viewDelta );\n \tfloat scaledScreenDistance = scaleDividedByCameraFar * viewDistance;\n \treturn max(0.0, (dot(centerViewNormal, viewDelta) - minResolutionMultipliedByCameraFar) / scaledScreenDistance - uBias) / (1.0 + pow2( scaledScreenDistance ) );\n }\n\n const float ANGLE_STEP = PI2 * float( NUM_RINGS ) / float( NUM_SAMPLES );\n const float INV_NUM_SAMPLES = 1.0 / float( NUM_SAMPLES );\n\n float getAmbientOcclusion( const in vec3 centerViewPosition ) {\n \n \tscaleDividedByCameraFar = uScale / uCameraFar;\n \tminResolutionMultipliedByCameraFar = uMinResolution * uCameraFar;\n \tvec3 centerViewNormal = getViewNormal( centerViewPosition, vUV );\n\n \tfloat angle = rand( vUV + uRandomSeed ) * PI2;\n \tvec2 radius = vec2( uKernelRadius * INV_NUM_SAMPLES ) / uViewport;\n \tvec2 radiusStep = radius;\n\n \tfloat occlusionSum = 0.0;\n \tfloat weightSum = 0.0;\n\n \tfor( int i = 0; i < NUM_SAMPLES; i ++ ) {\n \t\tvec2 sampleUv = vUV + vec2( cos( angle ), sin( angle ) ) * radius;\n \t\tradius += radiusStep;\n \t\tangle += ANGLE_STEP;\n\n \t\tfloat sampleDepth = getDepth( sampleUv );\n \t\tif( sampleDepth >= ( 1.0 - EPSILON ) ) {\n \t\t\tcontinue;\n \t\t}\n\n \t\tfloat sampleViewZ = getViewZ( sampleDepth );\n \t\tvec3 sampleViewPosition = getViewPos( sampleUv, sampleDepth, sampleViewZ );\n \t\tocclusionSum += getOcclusion( centerViewPosition, centerViewNormal, sampleViewPosition );\n \t\tweightSum += 1.0;\n \t}\n\n \tif( weightSum == 0.0 ) discard;\n\n \treturn occlusionSum * ( uIntensity / weightSum );\n }\n\n out vec4 outColor;\n \n void main() {\n \n \tfloat centerDepth = getDepth( vUV );\n \t\n \tif( centerDepth >= ( 1.0 - EPSILON ) ) {\n \t\tdiscard;\n \t}\n\n \tfloat centerViewZ = getViewZ( centerDepth );\n \tvec3 viewPosition = getViewPos( vUV, centerDepth, centerViewZ );\n\n \tfloat ambientOcclusion = getAmbientOcclusion( viewPosition );\n \n \toutColor = packFloatToRGBA( 1.0- ambientOcclusion );\n }")]}),this._program.errors)return console.error(this._program.errors.join("\n")),void(this._programError=!0);var r=new Float32Array([1,1,0,1,0,0,1,0]),i=new Float32Array([1,1,0,-1,1,0,-1,-1,0,1,-1,0]),a=new Uint32Array([0,1,2,0,2,3]);this._positionsBuf=new pt(n,n.ARRAY_BUFFER,i,i.length,3,n.STATIC_DRAW),this._uvBuf=new pt(n,n.ARRAY_BUFFER,r,r.length,2,n.STATIC_DRAW),this._indicesBuf=new pt(n,n.ELEMENT_ARRAY_BUFFER,a,a.length,1,n.STATIC_DRAW),this._program.bind(),this._uCameraNear=this._program.getLocation("uCameraNear"),this._uCameraFar=this._program.getLocation("uCameraFar"),this._uCameraProjectionMatrix=this._program.getLocation("uProjectMatrix"),this._uCameraInverseProjectionMatrix=this._program.getLocation("uInverseProjectMatrix"),this._uPerspective=this._program.getLocation("uPerspective"),this._uScale=this._program.getLocation("uScale"),this._uIntensity=this._program.getLocation("uIntensity"),this._uBias=this._program.getLocation("uBias"),this._uKernelRadius=this._program.getLocation("uKernelRadius"),this._uMinResolution=this._program.getLocation("uMinResolution"),this._uViewport=this._program.getLocation("uViewport"),this._uRandomSeed=this._program.getLocation("uRandomSeed"),this._aPosition=this._program.getAttribute("aPosition"),this._aUV=this._program.getAttribute("aUV"),this._dirty=!1}}},{key:"destroy",value:function(){this._program&&(this._program.destroy(),this._program=null)}}]),e}(),mt=new Float32Array(Dt(17,[0,1])),wt=new Float32Array(Dt(17,[1,0])),gt=new Float32Array(function(e,t){for(var n=[],r=0;r<=e;r++)n.push(bt(r,t));return n}(17,4)),Tt=new Float32Array(2),Et=function(){function e(t){b(this,e),this._scene=t,this._program=null,this._programError=!1,this._aPosition=null,this._aUV=null,this._uDepthTexture="uDepthTexture",this._uOcclusionTexture="uOcclusionTexture",this._uViewport=null,this._uCameraNear=null,this._uCameraFar=null,this._uCameraProjectionMatrix=null,this._uCameraInverseProjectionMatrix=null,this._uvBuf=null,this._positionsBuf=null,this._indicesBuf=null,this.init()}return P(e,[{key:"init",value:function(){var e=this._scene.canvas.gl;if(this._program=new ft(e,{vertex:["#version 300 es\n precision highp float;\n precision highp int;\n \n in vec3 aPosition;\n in vec2 aUV;\n uniform vec2 uViewport;\n out vec2 vUV;\n out vec2 vInvSize;\n void main () {\n vUV = aUV;\n vInvSize = 1.0 / uViewport;\n gl_Position = vec4(aPosition, 1.0);\n }"],fragment:["#version 300 es\n precision highp float;\n precision highp int;\n \n #define PI 3.14159265359\n #define PI2 6.28318530718\n #define EPSILON 1e-6\n\n #define KERNEL_RADIUS ".concat(16,"\n\n in vec2 vUV;\n in vec2 vInvSize;\n \n uniform sampler2D uDepthTexture;\n uniform sampler2D uOcclusionTexture; \n \n uniform float uCameraNear;\n uniform float uCameraFar; \n uniform float uDepthCutoff;\n\n uniform vec2 uSampleOffsets[ KERNEL_RADIUS + 1 ];\n uniform float uSampleWeights[ KERNEL_RADIUS + 1 ];\n\n const float unpackDownscale = 255. / 256.; \n\n const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );\n const vec4 unpackFactors = unpackDownscale / vec4( packFactors, 1. ); \n\n const float packUpscale = 256. / 255.;\n \n const float shiftRights = 1. / 256.;\n \n float unpackRGBAToFloat( const in vec4 v ) {\n return dot( floor( v * 255.0 + 0.5 ) / 255.0, unpackFactors );\n } \n\n vec4 packFloatToRGBA( const in float v ) {\n vec4 r = vec4( fract( v * packFactors ), v );\n r.yzw -= r.xyz * shiftRights; \n return r * packUpscale;\n }\n\n float viewZToOrthographicDepth( const in float viewZ) {\n return ( viewZ + uCameraNear ) / ( uCameraNear - uCameraFar );\n }\n \n float orthographicDepthToViewZ( const in float linearClipZ) {\n return linearClipZ * ( uCameraNear - uCameraFar ) - uCameraNear;\n }\n\n float viewZToPerspectiveDepth( const in float viewZ) {\n return (( uCameraNear + viewZ ) * uCameraFar ) / (( uCameraFar - uCameraNear ) * viewZ );\n }\n \n float perspectiveDepthToViewZ( const in float invClipZ) {\n return ( uCameraNear * uCameraFar ) / ( ( uCameraFar - uCameraNear ) * invClipZ - uCameraFar );\n }\n\n float getDepth( const in vec2 screenPosition ) {\n return vec4(texture(uDepthTexture, screenPosition)).r;\n }\n\n float getViewZ( const in float depth ) {\n return perspectiveDepthToViewZ( depth );\n }\n\n out vec4 outColor;\n \n void main() {\n \n float depth = getDepth( vUV );\n if( depth >= ( 1.0 - EPSILON ) ) {\n discard;\n }\n\n float centerViewZ = -getViewZ( depth );\n bool rBreak = false;\n bool lBreak = false;\n\n float weightSum = uSampleWeights[0];\n float occlusionSum = unpackRGBAToFloat(texture( uOcclusionTexture, vUV )) * weightSum;\n\n for( int i = 1; i <= KERNEL_RADIUS; i ++ ) {\n\n float sampleWeight = uSampleWeights[i];\n vec2 sampleUVOffset = uSampleOffsets[i] * vInvSize;\n\n vec2 sampleUV = vUV + sampleUVOffset;\n float viewZ = -getViewZ( getDepth( sampleUV ) );\n\n if( abs( viewZ - centerViewZ ) > uDepthCutoff ) {\n rBreak = true;\n }\n\n if( ! rBreak ) {\n occlusionSum += unpackRGBAToFloat(texture( uOcclusionTexture, sampleUV )) * sampleWeight;\n weightSum += sampleWeight;\n }\n\n sampleUV = vUV - sampleUVOffset;\n viewZ = -getViewZ( getDepth( sampleUV ) );\n\n if( abs( viewZ - centerViewZ ) > uDepthCutoff ) {\n lBreak = true;\n }\n\n if( ! lBreak ) {\n occlusionSum += unpackRGBAToFloat(texture( uOcclusionTexture, sampleUV )) * sampleWeight;\n weightSum += sampleWeight;\n }\n }\n\n outColor = packFloatToRGBA(occlusionSum / weightSum);\n }")]}),this._program.errors)return console.error(this._program.errors.join("\n")),void(this._programError=!0);var t=new Float32Array([1,1,0,1,0,0,1,0]),n=new Float32Array([1,1,0,-1,1,0,-1,-1,0,1,-1,0]),r=new Uint32Array([0,1,2,0,2,3]);this._positionsBuf=new pt(e,e.ARRAY_BUFFER,n,n.length,3,e.STATIC_DRAW),this._uvBuf=new pt(e,e.ARRAY_BUFFER,t,t.length,2,e.STATIC_DRAW),this._indicesBuf=new pt(e,e.ELEMENT_ARRAY_BUFFER,r,r.length,1,e.STATIC_DRAW),this._program.bind(),this._uViewport=this._program.getLocation("uViewport"),this._uCameraNear=this._program.getLocation("uCameraNear"),this._uCameraFar=this._program.getLocation("uCameraFar"),this._uDepthCutoff=this._program.getLocation("uDepthCutoff"),this._uSampleOffsets=e.getUniformLocation(this._program.handle,"uSampleOffsets"),this._uSampleWeights=e.getUniformLocation(this._program.handle,"uSampleWeights"),this._aPosition=this._program.getAttribute("aPosition"),this._aUV=this._program.getAttribute("aUV")}},{key:"render",value:function(e,t,n){var r=this;if(!this._programError){this._getInverseProjectMat||(this._getInverseProjectMat=function(){var e=!0;r._scene.camera.on("projMatrix",(function(){e=!0}));var t=Z.mat4();return function(){return e&&Z.inverseMat4(s.camera.projMatrix,t),t}}());var i=this._scene.canvas.gl,a=this._program,s=this._scene,o=i.drawingBufferWidth,l=i.drawingBufferHeight,u=s.camera.project._state,c=u.near,f=u.far;i.viewport(0,0,o,l),i.clearColor(0,0,0,1),i.enable(i.DEPTH_TEST),i.disable(i.BLEND),i.frontFace(i.CCW),i.clear(i.COLOR_BUFFER_BIT|i.DEPTH_BUFFER_BIT),a.bind(),Tt[0]=o,Tt[1]=l,i.uniform2fv(this._uViewport,Tt),i.uniform1f(this._uCameraNear,c),i.uniform1f(this._uCameraFar,f),i.uniform1f(this._uDepthCutoff,.01),0===n?i.uniform2fv(this._uSampleOffsets,wt):i.uniform2fv(this._uSampleOffsets,mt),i.uniform1fv(this._uSampleWeights,gt);var p=e.getDepthTexture(),A=t.getTexture();a.bindTexture(this._uDepthTexture,p,0),a.bindTexture(this._uOcclusionTexture,A,1),this._aUV.bindArrayBuffer(this._uvBuf),this._aPosition.bindArrayBuffer(this._positionsBuf),this._indicesBuf.bind(),i.drawElements(i.TRIANGLES,this._indicesBuf.numItems,this._indicesBuf.itemType,0)}}},{key:"destroy",value:function(){this._program.destroy()}}]),e}();function bt(e,t){return Math.exp(-e*e/(t*t*2))/(Math.sqrt(2*Math.PI)*t)}function Dt(e,t){for(var n=[],r=0;r<=e;r++)n.push(t[0]*r),n.push(t[1]*r);return n}var Pt=function(){function e(t,n,r){b(this,e),r=r||{},this.gl=n,this.allocated=!1,this.canvas=t,this.buffer=null,this.bound=!1,this.size=r.size,this._hasDepthTexture=!!r.depthTexture}return P(e,[{key:"setSize",value:function(e){this.size=e}},{key:"webglContextRestored",value:function(e){this.gl=e,this.buffer=null,this.allocated=!1,this.bound=!1}},{key:"bind",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:null;if(this._touch(e),!this.bound){var t=this.gl;t.bindFramebuffer(t.FRAMEBUFFER,this.buffer.framebuf),this.bound=!0}}},{key:"_touch",value:function(){var e,t,n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:null,r=this.gl;if(this.size?(e=this.size[0],t=this.size[1]):(e=r.drawingBufferWidth,t=r.drawingBufferHeight),this.buffer){if(this.buffer.width===e&&this.buffer.height===t)return;r.deleteTexture(this.buffer.texture),r.deleteFramebuffer(this.buffer.framebuf),r.deleteRenderbuffer(this.buffer.renderbuf)}var i,a=r.createTexture();r.bindTexture(r.TEXTURE_2D,a),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MIN_FILTER,r.NEAREST),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MAG_FILTER,r.NEAREST),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_S,r.CLAMP_TO_EDGE),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_T,r.CLAMP_TO_EDGE),n?r.texStorage2D(r.TEXTURE_2D,1,n,e,t):r.texImage2D(r.TEXTURE_2D,0,r.RGBA,e,t,0,r.RGBA,r.UNSIGNED_BYTE,null),this._hasDepthTexture&&(i=r.createTexture(),r.bindTexture(r.TEXTURE_2D,i),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MAG_FILTER,r.NEAREST),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MIN_FILTER,r.NEAREST),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_S,r.CLAMP_TO_EDGE),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_T,r.CLAMP_TO_EDGE),r.texImage2D(r.TEXTURE_2D,0,r.DEPTH_COMPONENT32F,e,t,0,r.DEPTH_COMPONENT,r.FLOAT,null));var s=r.createRenderbuffer();r.bindRenderbuffer(r.RENDERBUFFER,s),r.renderbufferStorage(r.RENDERBUFFER,r.DEPTH_COMPONENT32F,e,t);var o=r.createFramebuffer();if(r.bindFramebuffer(r.FRAMEBUFFER,o),r.framebufferTexture2D(r.FRAMEBUFFER,r.COLOR_ATTACHMENT0,r.TEXTURE_2D,a,0),this._hasDepthTexture?r.framebufferTexture2D(r.FRAMEBUFFER,r.DEPTH_ATTACHMENT,r.TEXTURE_2D,i,0):r.framebufferRenderbuffer(r.FRAMEBUFFER,r.DEPTH_ATTACHMENT,r.RENDERBUFFER,s),r.bindTexture(r.TEXTURE_2D,null),r.bindRenderbuffer(r.RENDERBUFFER,null),r.bindFramebuffer(r.FRAMEBUFFER,null),r.bindFramebuffer(r.FRAMEBUFFER,o),!r.isFramebuffer(o))throw"Invalid framebuffer";r.bindFramebuffer(r.FRAMEBUFFER,null);var l=r.checkFramebufferStatus(r.FRAMEBUFFER);switch(l){case r.FRAMEBUFFER_COMPLETE:break;case r.FRAMEBUFFER_INCOMPLETE_ATTACHMENT:throw"Incomplete framebuffer: FRAMEBUFFER_INCOMPLETE_ATTACHMENT";case r.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:throw"Incomplete framebuffer: FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT";case r.FRAMEBUFFER_INCOMPLETE_DIMENSIONS:throw"Incomplete framebuffer: FRAMEBUFFER_INCOMPLETE_DIMENSIONS";case r.FRAMEBUFFER_UNSUPPORTED:throw"Incomplete framebuffer: FRAMEBUFFER_UNSUPPORTED";default:throw"Incomplete framebuffer: "+l}this.buffer={framebuf:o,renderbuf:s,texture:a,depthTexture:i,width:e,height:t},this.bound=!1}},{key:"clear",value:function(){if(!this.bound)throw"Render buffer not bound";var e=this.gl;e.clear(e.COLOR_BUFFER_BIT|e.DEPTH_BUFFER_BIT)}},{key:"read",value:function(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null,r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:null,i=arguments.length>4&&void 0!==arguments[4]?arguments[4]:Uint8Array,a=arguments.length>5&&void 0!==arguments[5]?arguments[5]:4,s=e,o=(this.buffer.height||this.gl.drawingBufferHeight)-t,l=new i(a),u=this.gl;return u.readPixels(s,o,1,1,n||u.RGBA,r||u.UNSIGNED_BYTE,l,0),l}},{key:"readArray",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:null,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:Uint8Array,r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:4,i=new n(this.buffer.width*this.buffer.height*r),a=this.gl;return a.readPixels(0,0,this.buffer.width,this.buffer.height,e||a.RGBA,t||a.UNSIGNED_BYTE,i,0),i}},{key:"readImageAsCanvas",value:function(){var e=this.gl,t=this._getImageDataCache(),n=t.pixelData,r=t.canvas,i=t.imageData,a=t.context;e.readPixels(0,0,this.buffer.width,this.buffer.height,e.RGBA,e.UNSIGNED_BYTE,n);for(var s=this.buffer.width,o=this.buffer.height,l=o/2|0,u=4*s,c=new Uint8Array(4*s),f=0;f<l;++f){var p=f*u,A=(o-f-1)*u;c.set(n.subarray(p,p+u)),n.copyWithin(p,A,A+u),n.set(c,A)}return i.data.set(n),a.putImageData(i,0,0),r}},{key:"readImage",value:function(e){var t=this.gl,n=this._getImageDataCache(),r=n.pixelData,i=n.canvas,a=n.imageData,s=n.context,o=this.buffer,l=o.width,u=o.height;t.readPixels(0,0,l,u,t.RGBA,t.UNSIGNED_BYTE,r),a.data.set(r),s.putImageData(a,0,0),s.save(),s.globalCompositeOperation="copy",s.scale(1,-1),s.drawImage(i,0,-u,l,u),s.restore();var c=e.format||"png";return"jpeg"!==c&&"png"!==c&&"bmp"!==c&&(console.error("Unsupported image format: '"+c+"' - supported types are 'jpeg', 'bmp' and 'png' - defaulting to 'png'"),c="png"),i.toDataURL("image/".concat(c))}},{key:"_getImageDataCache",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:Uint8Array,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:4,n=this.buffer.width,r=this.buffer.height,i=this._imageDataCache;if(i&&(i.width===n&&i.height===r||(this._imageDataCache=null,i=null)),!i){var a=document.createElement("canvas"),s=a.getContext("2d");a.width=n,a.height=r,i={pixelData:new e(n*r*t),canvas:a,context:s,imageData:s.createImageData(n,r),width:n,height:r},this._imageDataCache=i}return i.context.resetTransform(),i}},{key:"unbind",value:function(){var e=this.gl;e.bindFramebuffer(e.FRAMEBUFFER,null),this.bound=!1}},{key:"getTexture",value:function(){var e=this;return this._texture||(this._texture={renderBuffer:this,bind:function(t){return!(!e.buffer||!e.buffer.texture)&&(e.gl.activeTexture(e.gl["TEXTURE"+t]),e.gl.bindTexture(e.gl.TEXTURE_2D,e.buffer.texture),!0)},unbind:function(t){e.buffer&&e.buffer.texture&&(e.gl.activeTexture(e.gl["TEXTURE"+t]),e.gl.bindTexture(e.gl.TEXTURE_2D,null))}})}},{key:"hasDepthTexture",value:function(){return this._hasDepthTexture}},{key:"getDepthTexture",value:function(){if(!this._hasDepthTexture)return null;var e=this;return this._depthTexture||(this._dethTexture={renderBuffer:this,bind:function(t){return!(!e.buffer||!e.buffer.depthTexture)&&(e.gl.activeTexture(e.gl["TEXTURE"+t]),e.gl.bindTexture(e.gl.TEXTURE_2D,e.buffer.depthTexture),!0)},unbind:function(t){e.buffer&&e.buffer.depthTexture&&(e.gl.activeTexture(e.gl["TEXTURE"+t]),e.gl.bindTexture(e.gl.TEXTURE_2D,null))}})}},{key:"destroy",value:function(){if(this.allocated){var e=this.gl;e.deleteTexture(this.buffer.texture),e.deleteTexture(this.buffer.depthTexture),e.deleteFramebuffer(this.buffer.framebuf),e.deleteRenderbuffer(this.buffer.renderbuf),this.allocated=!1,this.buffer=null,this.bound=!1}this._imageDataCache=null,this._texture=null,this._depthTexture=null}}]),e}(),Rt=function(){function e(t){b(this,e),this.scene=t,this._renderBuffersBasic={},this._renderBuffersScaled={}}return P(e,[{key:"getRenderBuffer",value:function(e,t){var n=1===this.scene.canvas.resolutionScale?this._renderBuffersBasic:this._renderBuffersScaled,r=n[e];return r||(r=new Pt(this.scene.canvas.canvas,this.scene.canvas.gl,t),n[e]=r),r}},{key:"destroy",value:function(){for(var e in this._renderBuffersBasic)this._renderBuffersBasic[e].destroy();for(var t in this._renderBuffersScaled)this._renderBuffersScaled[t].destroy()}}]),e}();function Ct(e,t){if(void 0===e._cachedExtensions&&(e._cachedExtensions={}),void 0!==e._cachedExtensions[t])return e._cachedExtensions[t];var n;switch(t){case"WEBGL_depth_texture":n=e.getExtension("WEBGL_depth_texture")||e.getExtension("MOZ_WEBGL_depth_texture")||e.getExtension("WEBKIT_WEBGL_depth_texture");break;case"EXT_texture_filter_anisotropic":n=e.getExtension("EXT_texture_filter_anisotropic")||e.getExtension("MOZ_EXT_texture_filter_anisotropic")||e.getExtension("WEBKIT_EXT_texture_filter_anisotropic");break;case"WEBGL_compressed_texture_s3tc":n=e.getExtension("WEBGL_compressed_texture_s3tc")||e.getExtension("MOZ_WEBGL_compressed_texture_s3tc")||e.getExtension("WEBKIT_WEBGL_compressed_texture_s3tc");break;case"WEBGL_compressed_texture_pvrtc":n=e.getExtension("WEBGL_compressed_texture_pvrtc")||e.getExtension("WEBKIT_WEBGL_compressed_texture_pvrtc");break;default:n=e.getExtension(t)}return e._cachedExtensions[t]=n,n}var _t=function(e,t){t=t||{};var n=new rt(e),r=e.canvas.canvas,i=e.canvas.gl,a=!!t.transparent,s=t.alphaDepthMask,o=new G({}),l={},u={},c=!0,f=!0,p=!0,A=!0,d=!0,v=!0,h=!0,I=!0,y=new Rt(e),m=!1,w=new yt(e),g=new Et(e);function T(){c&&(!function(){for(var e in l)if(l.hasOwnProperty(e)){var t=l[e],n=t.drawableMap,r=t.drawableListPreCull,i=0;for(var a in n)n.hasOwnProperty(a)&&(r[i++]=n[a]);r.length=i}}(),c=!1,f=!0),f&&(!function(){for(var e in l)if(l.hasOwnProperty(e)){var t=l[e];t.isStateSortable&&t.drawableListPreCull.sort(t.stateSortCompare)}}(),f=!1,p=!0),p&&function(){for(var e in l)if(l.hasOwnProperty(e)){for(var t=l[e],n=t.drawableListPreCull,r=t.drawableList,i=0,a=0,s=n.length;a<s;a++){var o=n[a];o.rebuildRenderFlags(),o.renderFlags.culled||(r[i++]=o)}r.length=i}}()}function E(e){if(e.castsShadow){var t=e.getShadowRenderBuf();if(t){for(var r in t.bind(),n.reset(),n.backfaces=!0,n.frontface=!0,n.shadowViewMatrix=e.getShadowViewMatrix(),n.shadowProjMatrix=e.getShadowProjMatrix(),i.viewport(0,0,i.drawingBufferWidth,i.drawingBufferHeight),i.clearColor(0,0,0,1),i.enable(i.DEPTH_TEST),i.disable(i.BLEND),i.clear(i.COLOR_BUFFER_BIT|i.DEPTH_BUFFER_BIT),l)if(l.hasOwnProperty(r))for(var a=l[r].drawableList,s=0,o=a.length;s<o;s++){var u=a[s];!1!==u.visible&&u.castsShadow&&u.drawShadow&&(u.renderFlags.colorOpaque&&u.drawShadow(n))}t.unbind()}}}function b(t,r,a,s,u,c){n.reset(),n.backfaces=!0,n.frontface=!0,n.pickOrigin=c.origin,n.pickViewMatrix=a,n.pickProjMatrix=s,n.pickInvisible=!!u.pickInvisible,i.viewport(0,0,i.drawingBufferWidth,i.drawingBufferHeight),i.clearColor(0,0,0,0),i.enable(i.DEPTH_TEST),i.disable(i.CULL_FACE),i.disable(i.BLEND),i.clear(i.COLOR_BUFFER_BIT|i.DEPTH_BUFFER_BIT);var f=u.includeEntityIds,p=u.excludeEntityIds;for(var A in l)if(l.hasOwnProperty(A))for(var d=l[A].drawableList,v=0,h=d.length;v<h;v++){var I=d[v];!I.drawPickMesh||!0!==u.pickInvisible&&!1===I.visible||!1===I.pickable||(f&&!f[I.id]||p&&p[I.id]||I.drawPickMesh(n))}var y=e.canvas.resolutionScale,m=t.read(Math.round(r[0]*y),Math.round(r[1]*y)),w=m[0]+256*m[1]+256*m[2]*256+256*m[3]*256*256;if(!(w<0))return o.items[w]}function D(t,r,a,s,o,l){if(r.drawPickTriangles){n.reset(),n.backfaces=!0,n.frontface=!0,n.pickOrigin=l.origin,n.pickViewMatrix=s,n.pickProjMatrix=o,i.viewport(0,0,i.drawingBufferWidth,i.drawingBufferHeight),i.clearColor(0,0,0,0),i.enable(i.DEPTH_TEST),i.disable(i.CULL_FACE),i.disable(i.BLEND),i.clear(i.COLOR_BUFFER_BIT|i.DEPTH_BUFFER_BIT),r.drawPickTriangles(n);var u=e.canvas.resolutionScale,c=t.read(Math.round(a[0]*u),Math.round(a[1]*u)),f=c[0]+256*c[1]+256*c[2]*256+256*c[3]*256*256;f*=3,l.primIndex=f}}this.scene=e,this._occlusionTester=null,this.capabilities={astcSupported:!!Ct(i,"WEBGL_compressed_texture_astc"),etc1Supported:!0,etc2Supported:!!Ct(i,"WEBGL_compressed_texture_etc"),dxtSupported:!!Ct(i,"WEBGL_compressed_texture_s3tc"),bptcSupported:!!Ct(i,"EXT_texture_compression_bptc"),pvrtcSupported:!(!Ct(i,"WEBGL_compressed_texture_pvrtc")&&!Ct(i,"WEBKIT_WEBGL_compressed_texture_pvrtc"))},this.setTransparentEnabled=function(e){A=e,p=!0},this.setEdgesEnabled=function(e){d=e,p=!0},this.setSAOEnabled=function(e){v=e,p=!0},this.setPBREnabled=function(e){h=e,p=!0},this.setColorTextureEnabled=function(e){I=e,p=!0},this.needStateSort=function(){f=!0},this.shadowsDirty=function(){},this.imageDirty=function(){p=!0},this.webglContextLost=function(){},this.webglContextRestored=function(e){w.init(),g.init(),p=!0},this.addDrawable=function(e,t){var n=t.type;if(n){var r=l[n];r||(r={type:t.type,count:0,isStateSortable:t.isStateSortable,stateSortCompare:t.stateSortCompare,drawableMap:{},drawableListPreCull:[],drawableList:[]},l[n]=r),r.count++,r.drawableMap[e]=t,u[e]=t,c=!0}else console.error("Renderer#addDrawable() : drawable with ID "+e+" has no 'type' - ignoring")},this.removeDrawable=function(e){var t=u[e];if(t){var n=t.type,r=l[n];--r.count<=0?delete l[n]:delete r.drawableMap[e],delete u[e],c=!0}else console.error("Renderer#removeDrawable() : drawable not found with ID "+e+" - ignoring")},this.getPickID=function(e){return o.addItem(e)},this.putPickID=function(e){o.removeItem(e)},this.clear=function(t){if(i.viewport(0,0,i.drawingBufferWidth,i.drawingBufferHeight),a)i.clearColor(1,1,1,1);else{var n=e.canvas.backgroundColorFromAmbientLight?this.lights.getAmbientColorAndIntensity():e.canvas.backgroundColor;i.clearColor(n[0],n[1],n[2],1)}i.clear(i.COLOR_BUFFER_BIT|i.DEPTH_BUFFER_BIT)},this.needsRender=function(){return p||c||f},this.render=function(t){(t=t||{}).force&&(p=!0),T(),p&&(!function(t){var r=e.sao;v&&r.possible&&function(t){var r=e.sao,a=y.getRenderBuffer("saoDepth",{depthTexture:!0});a.bind(),a.clear(),function(e){n.reset(),n.pass=e.pass,i.viewport(0,0,i.drawingBufferWidth,i.drawingBufferHeight),i.clearColor(0,0,0,0),i.enable(i.DEPTH_TEST),i.frontFace(i.CCW),i.enable(i.CULL_FACE),i.depthMask(!0),!1!==e.clear&&i.clear(i.COLOR_BUFFER_BIT|i.DEPTH_BUFFER_BIT);for(var t in l)if(l.hasOwnProperty(t))for(var r=l[t].drawableList,a=0,s=r.length;a<s;a++){var o=r[a];!0!==o.culled&&!1!==o.visible&&o.drawDepth&&o.saoEnabled&&(o.renderFlags.colorOpaque&&o.drawDepth(n))}}(t),a.unbind();var s=y.getRenderBuffer("saoOcclusion");if(s.bind(),s.clear(),w.render(a),s.unbind(),r.blur){var o=y.getRenderBuffer("saoOcclusion2");o.bind(),o.clear(),g.render(a,s,0),o.unbind(),s.bind(),s.clear(),g.render(a,o,1),s.unbind()}}(t);(function(){for(var t=e._lightsState.lights,n=0,r=t.length;n<r;n++){var i=t[n];i.castsShadow&&E(i)}})(),function(t){var r=[],o=[],u=[],c=[],f=[],p=[],m=[],w=[],g=[],T=[],E=[],b=[],D=[],P=[],R=[],C=[],_=e._lightsState.getAmbientColorAndIntensity();if(n.reset(),n.pass=t.pass,n.withSAO=!1,n.pbrEnabled=h&&!!e.pbrEnabled,n.colorTextureEnabled=I&&!!e.colorTextureEnabled,i.viewport(0,0,i.drawingBufferWidth,i.drawingBufferHeight),a)i.clearColor(0,0,0,0);else{var B=e.canvas.backgroundColorFromAmbientLight?_:e.canvas.backgroundColor;i.clearColor(B[0],B[1],B[2],1)}i.enable(i.DEPTH_TEST),i.frontFace(i.CCW),i.enable(i.CULL_FACE),i.depthMask(!0),i.lineWidth(1),n.lineWidth=1;var O,S,N,L=e.sao.possible;if(v&&L){var x=y.getRenderBuffer("saoOcclusion");n.occlusionTexture=x?x.getTexture():null}else n.occlusionTexture=null;var M=Date.now();!1!==t.clear&&i.clear(i.COLOR_BUFFER_BIT|i.DEPTH_BUFFER_BIT);var F=0,H=0,U=0,G=0,k=0,V=0,j=0,Q=0,W=0,z=0,K=0,Y=0,X=0,q=0,J=0,Z=0;for(var $ in l)if(l.hasOwnProperty($)){var te=l[$].drawableList;for(O=0,S=te.length;O<S;O++)if(!0!==(N=te[O]).culled&&!1!==N.visible){var ne=N.renderFlags;ne.colorOpaque&&(v&&L&&N.saoEnabled?r[F++]=N:N.drawColorOpaque(n)),A&&ne.colorTransparent&&(u[U++]=N),ne.xrayedSilhouetteTransparent&&(m[j++]=N),ne.xrayedSilhouetteOpaque&&(f[k++]=N),ne.highlightedSilhouetteTransparent&&(E[K++]=N),ne.highlightedSilhouetteOpaque&&(g[W++]=N),ne.selectedSilhouetteTransparent&&(R[J++]=N),ne.selectedSilhouetteOpaque&&(D[X++]=N),d&&(ne.edgesOpaque&&(o[H++]=N),ne.edgesTransparent&&(c[G++]=N)),ne.selectedEdgesTransparent&&(C[Z++]=N),ne.selectedEdgesOpaque&&(P[q++]=N),ne.xrayedEdgesTransparent&&(w[Q++]=N),ne.xrayedEdgesOpaque&&(p[V++]=N),ne.highlightedEdgesTransparent&&(b[Y++]=N),ne.highlightedEdgesOpaque&&(T[z++]=N)}}if(F>0)for(n.withSAO=!0,O=0;O<F;O++)r[O].drawColorOpaque(n);if(H>0)for(O=0;O<H;O++)o[O].drawEdgesColorOpaque(n);if(k>0)for(O=0;O<k;O++)f[O].drawSilhouetteXRayed(n);if(V>0)for(O=0;O<V;O++)p[O].drawEdgesXRayed(n);if(j>0||Q>0||U>0||G>0){if(i.enable(i.CULL_FACE),i.enable(i.BLEND),a?(i.blendEquation(i.FUNC_ADD),i.blendFuncSeparate(i.SRC_ALPHA,i.ONE_MINUS_SRC_ALPHA,i.ONE,i.ONE_MINUS_SRC_ALPHA)):(i.blendEquation(i.FUNC_ADD),i.blendFunc(i.SRC_ALPHA,i.ONE_MINUS_SRC_ALPHA)),n.backfaces=!1,s||i.depthMask(!1),(U>0||G>0)&&i.blendFunc(i.SRC_ALPHA,i.ONE_MINUS_SRC_ALPHA),G>0)for(O=0;O<G;O++)(N=c[O]).drawEdgesColorTransparent(n);if(U>0)for(O=0;O<U;O++)(N=u[O]).drawColorTransparent(n);if(Q>0)for(O=0;O<Q;O++)w[O].drawEdgesXRayed(n);if(j>0)for(O=0;O<j;O++)m[O].drawSilhouetteXRayed(n);i.disable(i.BLEND),s||i.depthMask(!0)}if(W>0||z>0){if(n.lastProgramId=null,e.highlightMaterial.glowThrough&&i.clear(i.DEPTH_BUFFER_BIT),z>0)for(O=0;O<z;O++)T[O].drawEdgesHighlighted(n);if(W>0)for(O=0;O<W;O++)g[O].drawSilhouetteHighlighted(n)}if(K>0||Y>0||W>0){if(n.lastProgramId=null,e.selectedMaterial.glowThrough&&i.clear(i.DEPTH_BUFFER_BIT),i.enable(i.BLEND),a?(i.blendEquation(i.FUNC_ADD),i.blendFuncSeparate(i.SRC_ALPHA,i.ONE_MINUS_SRC_ALPHA,i.ONE,i.ONE_MINUS_SRC_ALPHA)):i.blendFunc(i.SRC_ALPHA,i.ONE_MINUS_SRC_ALPHA),i.enable(i.CULL_FACE),Y>0)for(O=0;O<Y;O++)b[O].drawEdgesHighlighted(n);if(K>0)for(O=0;O<K;O++)E[O].drawSilhouetteHighlighted(n);i.disable(i.BLEND)}if(X>0||q>0){if(n.lastProgramId=null,e.selectedMaterial.glowThrough&&i.clear(i.DEPTH_BUFFER_BIT),q>0)for(O=0;O<q;O++)P[O].drawEdgesSelected(n);if(X>0)for(O=0;O<X;O++)D[O].drawSilhouetteSelected(n)}if(J>0||Z>0){if(n.lastProgramId=null,e.selectedMaterial.glowThrough&&i.clear(i.DEPTH_BUFFER_BIT),i.enable(i.CULL_FACE),i.enable(i.BLEND),a?(i.blendEquation(i.FUNC_ADD),i.blendFuncSeparate(i.SRC_ALPHA,i.ONE_MINUS_SRC_ALPHA,i.ONE,i.ONE_MINUS_SRC_ALPHA)):i.blendFunc(i.SRC_ALPHA,i.ONE_MINUS_SRC_ALPHA),Z>0)for(O=0;O<Z;O++)C[O].drawEdgesSelected(n);if(J>0)for(O=0;O<J;O++)R[O].drawSilhouetteSelected(n);i.disable(i.BLEND)}var re=Date.now(),ie=ee.frame;ie.renderTime=(re-M)/1e3,ie.drawElements=n.drawElements,ie.drawArrays=n.drawArrays,ie.useProgram=n.useProgram,ie.bindTexture=n.bindTexture,ie.bindArray=n.bindArray;for(var ae=Ze.MAX_TEXTURE_IMAGE_UNITS,se=0;se<ae;se++)i.activeTexture(i.TEXTURE0+se);i.bindTexture(i.TEXTURE_CUBE_MAP,null),i.bindTexture(i.TEXTURE_2D,null);for(var oe=Ze.MAX_VERTEX_ATTRIBS,le=0;le<oe;le++)i.disableVertexAttribArray(le)}(t)}(t),ee.frame.frameCount++,p=!1)},this.pick=function(){var t=Z.vec3(),n=Z.mat4(),i=Z.mat4(),a=Z.vec3(),s=Z.vec3([0,1,0]),o=new it,u=Z.vec2(),c=Z.vec3(),f=Z.vec3(),p=Z.vec3();return Z.vec3(),Z.vec3(),function(A){var d,v=arguments.length>1&&void 0!==arguments[1]?arguments[1]:o;v.reset(),T();var h=null,I=null;if(v.pickSurface=A.pickSurface,A.canvasPos)c[0]=A.canvasPos[0],c[1]=A.canvasPos[1],h=e.camera.viewMatrix,I=e.camera.projMatrix,v.canvasPos=A.canvasPos;else{var m=Z.frustumMat4(-1,1,-1,1,.01,e.camera.project.far,n);A.matrix?(h=A.matrix,I=m):(f.set(A.origin||[0,0,0]),p.set(A.direction||[0,0,1]),d=Z.addVec3(f,p,t),a[0]=Math.random(),a[1]=Math.random(),a[2]=Math.random(),Z.normalizeVec3(a),Z.cross3Vec3(p,a,s),h=Z.lookAtMat4v(f,d,s,i),I=m,v.origin=f,v.direction=p),c[0]=.5*r.clientWidth,c[1]=.5*r.clientHeight}for(var w in l)if(l.hasOwnProperty(w))for(var g=l[w].drawableList,E=0,R=g.length;E<R;E++){var C=g[E];C.setPickMatrices&&C.setPickMatrices(h,I)}var _=y.getRenderBuffer("pick");_.bind();var B=b(_,c,h,I,A,v);if(!B)return _.unbind(),null;var S=B.delegatePickedEntity?B.delegatePickedEntity():B;return S?(A.pickSurface&&(B.canPickTriangle&&B.canPickTriangle()?(D(_,B,c,h,I,v),B.pickTriangleSurface(h,I,v),v.pickSurfacePrecision=!1):B.canPickWorldPos&&B.canPickWorldPos()&&(u[0]=e.camera.project.near,u[1]=e.camera.project.far,P(_,B,c,h,I,u,v),!1!==A.pickSurfaceNormal&&O(_,B,c,h,I,v),v.pickSurfacePrecision=!1)),_.unbind(),v.entity=S,v):(_.unbind(),null)}}();var P=function(){var t=Z.vec4(),a=Z.vec4(),s=Z.vec4(),o=Z.vec4(),l=Z.vec4(),u=Z.mat4(),c=Z.mat4(),f=Z.mat4();return function(p,A,d,v,h,I,y){n.reset(),n.backfaces=!0,n.frontface=!0,n.pickOrigin=y.origin,n.pickViewMatrix=v,n.pickProjMatrix=h,n.pickZNear=I[0],n.pickZFar=I[1],n.pickElementsCount=A.pickElementsCount,n.pickElementsOffset=A.pickElementsOffset,i.viewport(0,0,i.drawingBufferWidth,i.drawingBufferHeight),i.clearColor(0,0,0,0),i.enable(i.DEPTH_TEST),i.disable(i.CULL_FACE),i.disable(i.BLEND),i.clear(i.COLOR_BUFFER_BIT|i.DEPTH_BUFFER_BIT),A.drawPickDepths(n);var m,w=e.canvas.resolutionScale,g=function(e){var t=[e[0]/256,e[1]/256,e[2]/256,e[3]/256],n=[1/16777216,1/65536,1/256,1];return Z.dotVec4(t,n)}(p.read(Math.round(d[0]*w),Math.round(d[1]*w))),T=(d[0]-r.clientWidth/2)/(r.clientWidth/2),E=-(d[1]-r.clientHeight/2)/(r.clientHeight/2),b=A.origin;if(b){var D=Ie(v,b,u);m=Z.mulMat4(h,D,c)}else m=Z.mulMat4(h,v,c);var P=Z.inverseMat4(m,f);t[0]=T,t[1]=E,t[2]=-1,t[3]=1;var R=Z.transformVec4(P,t);R=Z.mulVec4Scalar(R,1/R[3]),a[0]=T,a[1]=E,a[2]=1,a[3]=1;var C=Z.transformVec4(P,a);C=Z.mulVec4Scalar(C,1/C[3]);var _=Z.subVec3(C,R,s),B=Z.addVec3(R,Z.mulVec4Scalar(_,g,o),l);b&&Z.addVec3(B,b),y.worldPos=B}}();function R(e){for(var t in e.snapPickLayerParams={},e.snapPickLayerNumber=0,l)for(var n=l[t].drawableList,r=0,i=n.length;r<i;r++){var a=n[r];a.drawSnapInitDepthBuf&&!a.culled&&a.visible&&a.pickable&&a.drawSnapInitDepthBuf(e)}return e.snapPickLayerParams}function C(e){for(var t in e.snapPickLayerParams={},e.snapPickLayerNumber=0,l)for(var n=l[t].drawableList,r=0,i=n.length;r<i;r++){var a=n[r];a.drawSnapDepths&&!a.culled&&a.visible&&a.pickable&&a.drawSnapDepths(e)}return e.snapPickLayerParams}function _(e,t){return e/t*2-1}function B(e,t){return 1-e/t*2}function O(t,r,a,s,o,l){n.reset(),n.backfaces=!0,n.frontface=!0,n.pickOrigin=l.origin,n.pickViewMatrix=s,n.pickProjMatrix=o,i.viewport(0,0,i.drawingBufferWidth,i.drawingBufferHeight),i.clearColor(0,0,0,0),i.enable(i.DEPTH_TEST),i.disable(i.CULL_FACE),i.disable(i.BLEND),i.clear(i.COLOR_BUFFER_BIT|i.DEPTH_BUFFER_BIT),r.drawPickNormals(n);var u=e.canvas.resolutionScale,c=t.read(Math.round(a[0]*u),Math.round(a[1]*u)),f=[c[0]/256-.5,c[1]/256-.5,c[2]/256-.5];Z.normalizeVec3(f),l.worldNormal=f}this.snapPick=function(t){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:50,a=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"vertex";n.reset(),n.backfaces=!0,n.frontface=!0,n.pickZNear=e.camera.project.near,n.pickZFar=e.camera.project.far;var s=y.getRenderBuffer("uniquePickColors-aabs",{depthTexture:!0,size:[2*r+1,2*r+1]});n.snapVectorA=[_(t[0],i.drawingBufferWidth),B(t[1],i.drawingBufferHeight)],n.snapInvVectorAB=[i.drawingBufferWidth/(2*r),i.drawingBufferHeight/(2*r)],n.snapMode=a,s.bind(i.RGBA32I),i.viewport(0,0,s.size[0],s.size[1]),i.enable(i.DEPTH_TEST),i.frontFace(i.CCW),i.disable(i.CULL_FACE),i.depthMask(!0),i.disable(i.BLEND),i.depthFunc(i.LESS),i.clear(i.DEPTH_BUFFER_BIT),i.clearBufferiv(i.COLOR,0,new Int32Array([0,0,0,0]));var o=e.camera.viewMatrix,u=e.camera.projMatrix;for(var c in l)if(l.hasOwnProperty(c))for(var f=l[c].drawableList,p=0,A=f.length;p<A;p++){var d=f[p];d.setPickMatrices&&d.setPickMatrices(o,u)}var v=R(n),h=C(n),I=s.readArray(i.RGBA_INTEGER,i.INT,Int32Array,4);s.unbind();var m=null,w=r,g=r,T=4*w+g*s.size[0]*4,E=I.slice(T,T+4);if(0!==E[3]){var b=v[Math.abs(E[3])],D=b.origin,P=b.coordinateScale;m=[E[0]*P[0]+D[0],E[1]*P[1]+D[1],E[2]*P[2]+D[2]]}for(var O=[],S=0;S<I.length;S+=4)if(I[S+3]>0){var N=Math.floor(S/4),L=s.size[0];s.size[1];var x=N%L-Math.floor(L/2),M=Math.floor(N/L)-Math.floor(L/2),F=Math.sqrt(Math.pow(x,2)+Math.pow(M,2));O.push({x:x,y:M,dist:F,result:[I[S+0],I[S+1],I[S+2],I[S+3]]})}var H=null;if(O.length>0){O.sort((function(e,t){return e.dist-t.dist}));var U=h[(O=O[0].result)[3]],G=U.origin,k=U.coordinateScale;H=[O[0]*k[0]+G[0],O[1]*k[1]+G[1],O[2]*k[2]+G[2]]}if(null===m&&null==H)return null;var V=null;return null!==H&&(V=e.camera.projectWorldPos(H)),{worldPos:m,snappedWorldPos:H,snappedCanvasPos:V}},this.addMarker=function(t){this._occlusionTester=this._occlusionTester||new ht(e,y),this._occlusionTester.addMarker(t),e.occlusionTestCountdown=0},this.markerWorldPosUpdated=function(e){this._occlusionTester.markerWorldPosUpdated(e)},this.removeMarker=function(e){this._occlusionTester.removeMarker(e)},this.doOcclusionTest=function(){if(this._occlusionTester&&this._occlusionTester.needOcclusionTest){for(var e in T(),this._occlusionTester.bindRenderBuf(),n.reset(),n.backfaces=!0,n.frontface=!0,i.viewport(0,0,i.drawingBufferWidth,i.drawingBufferHeight),i.clearColor(0,0,0,0),i.enable(i.DEPTH_TEST),i.disable(i.CULL_FACE),i.disable(i.BLEND),i.clear(i.COLOR_BUFFER_BIT|i.DEPTH_BUFFER_BIT),l)if(l.hasOwnProperty(e))for(var t=l[e].drawableList,r=0,a=t.length;r<a;r++){var s=t[r];s.drawOcclusion&&!0!==s.culled&&!1!==s.visible&&!1!==s.pickable&&s.drawOcclusion(n)}this._occlusionTester.drawMarkers(n),this._occlusionTester.doOcclusionTest(),this._occlusionTester.unbindRenderBuf()}},this.readPixels=function(e,t,n,r){var i,a,s,o,l=y.getRenderBuffer("snapshot");for(l.bind(),l.clear(),this.render({force:!0,opaqueOnly:r}),a=0;a<n;a++)s=2*a,o=4*a,i=l.read(e[s],e[s+1]),t[o]=i[0],t[o+1]=i[1],t[o+2]=i[2],t[o+3]=i[3];l.unbind(),p=!0},this.beginSnapshot=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=y.getRenderBuffer("snapshot");e.width&&e.height&&t.setSize([e.width,e.height]),t.bind(),t.clear(),m=!0},this.renderSnapshot=function(){m&&(y.getRenderBuffer("snapshot").clear(),this.render({force:!0,opaqueOnly:!1}),p=!0)},this.readSnapshot=function(e){return y.getRenderBuffer("snapshot").readImage(e)},this.readSnapshotAsCanvas=function(){return y.getRenderBuffer("snapshot").readImageAsCanvas()},this.endSnapshot=function(){m&&(y.getRenderBuffer("snapshot").unbind(),m=!1)},this.destroy=function(){l={},u={},y.destroy(),w.destroy(),g.destroy(),this._occlusionTester&&this._occlusionTester.destroy()}},Bt=function(e){I(n,ve);var t=m(n);function n(e){var r,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return b(this,n),(r=t.call(this,e,i)).KEY_BACKSPACE=8,r.KEY_TAB=9,r.KEY_ENTER=13,r.KEY_SHIFT=16,r.KEY_CTRL=17,r.KEY_ALT=18,r.KEY_PAUSE_BREAK=19,r.KEY_CAPS_LOCK=20,r.KEY_ESCAPE=27,r.KEY_PAGE_UP=33,r.KEY_PAGE_DOWN=34,r.KEY_END=35,r.KEY_HOME=36,r.KEY_LEFT_ARROW=37,r.KEY_UP_ARROW=38,r.KEY_RIGHT_ARROW=39,r.KEY_DOWN_ARROW=40,r.KEY_INSERT=45,r.KEY_DELETE=46,r.KEY_NUM_0=48,r.KEY_NUM_1=49,r.KEY_NUM_2=50,r.KEY_NUM_3=51,r.KEY_NUM_4=52,r.KEY_NUM_5=53,r.KEY_NUM_6=54,r.KEY_NUM_7=55,r.KEY_NUM_8=56,r.KEY_NUM_9=57,r.KEY_A=65,r.KEY_B=66,r.KEY_C=67,r.KEY_D=68,r.KEY_E=69,r.KEY_F=70,r.KEY_G=71,r.KEY_H=72,r.KEY_I=73,r.KEY_J=74,r.KEY_K=75,r.KEY_L=76,r.KEY_M=77,r.KEY_N=78,r.KEY_O=79,r.KEY_P=80,r.KEY_Q=81,r.KEY_R=82,r.KEY_S=83,r.KEY_T=84,r.KEY_U=85,r.KEY_V=86,r.KEY_W=87,r.KEY_X=88,r.KEY_Y=89,r.KEY_Z=90,r.KEY_LEFT_WINDOW=91,r.KEY_RIGHT_WINDOW=92,r.KEY_SELECT_KEY=93,r.KEY_NUMPAD_0=96,r.KEY_NUMPAD_1=97,r.KEY_NUMPAD_2=98,r.KEY_NUMPAD_3=99,r.KEY_NUMPAD_4=100,r.KEY_NUMPAD_5=101,r.KEY_NUMPAD_6=102,r.KEY_NUMPAD_7=103,r.KEY_NUMPAD_8=104,r.KEY_NUMPAD_9=105,r.KEY_MULTIPLY=106,r.KEY_ADD=107,r.KEY_SUBTRACT=109,r.KEY_DECIMAL_POINT=110,r.KEY_DIVIDE=111,r.KEY_F1=112,r.KEY_F2=113,r.KEY_F3=114,r.KEY_F4=115,r.KEY_F5=116,r.KEY_F6=117,r.KEY_F7=118,r.KEY_F8=119,r.KEY_F9=120,r.KEY_F10=121,r.KEY_F11=122,r.KEY_F12=123,r.KEY_NUM_LOCK=144,r.KEY_SCROLL_LOCK=145,r.KEY_SEMI_COLON=186,r.KEY_EQUAL_SIGN=187,r.KEY_COMMA=188,r.KEY_DASH=189,r.KEY_PERIOD=190,r.KEY_FORWARD_SLASH=191,r.KEY_GRAVE_ACCENT=192,r.KEY_OPEN_BRACKET=219,r.KEY_BACK_SLASH=220,r.KEY_CLOSE_BRACKET=221,r.KEY_SINGLE_QUOTE=222,r.KEY_SPACE=32,r.element=i.element,r.altDown=!1,r.ctrlDown=!1,r.mouseDownLeft=!1,r.mouseDownMiddle=!1,r.mouseDownRight=!1,r.keyDown=[],r.enabled=!0,r.keyboardEnabled=!0,r.mouseover=!1,r.mouseCanvasPos=Z.vec2(),r._keyboardEventsElement=i.keyboardEventsElement||document,r._bindEvents(),r}return P(n,[{key:"_bindEvents",value:function(){var e=this;if(!this._eventsBound){this._keyboardEventsElement.addEventListener("keydown",this._keyDownListener=function(t){e.enabled&&e.keyboardEnabled&&"INPUT"!==t.target.tagName&&"TEXTAREA"!==t.target.tagName&&(t.keyCode===e.KEY_CTRL?e.ctrlDown=!0:t.keyCode===e.KEY_ALT?e.altDown=!0:t.keyCode===e.KEY_SHIFT&&(e.shiftDown=!0),e.keyDown[t.keyCode]=!0,e.fire("keydown",t.keyCode,!0))},!1),this._keyboardEventsElement.addEventListener("keyup",this._keyUpListener=function(t){e.enabled&&e.keyboardEnabled&&"INPUT"!==t.target.tagName&&"TEXTAREA"!==t.target.tagName&&(t.keyCode===e.KEY_CTRL?e.ctrlDown=!1:t.keyCode===e.KEY_ALT?e.altDown=!1:t.keyCode===e.KEY_SHIFT&&(e.shiftDown=!1),e.keyDown[t.keyCode]=!1,e.fire("keyup",t.keyCode,!0))}),this.element.addEventListener("mouseenter",this._mouseEnterListener=function(t){e.enabled&&(e.mouseover=!0,e._getMouseCanvasPos(t),e.fire("mouseenter",e.mouseCanvasPos,!0))}),this.element.addEventListener("mouseleave",this._mouseLeaveListener=function(t){e.enabled&&(e.mouseover=!1,e._getMouseCanvasPos(t),e.fire("mouseleave",e.mouseCanvasPos,!0))}),this.element.addEventListener("mousedown",this._mouseDownListener=function(t){if(e.enabled){switch(t.which){case 1:e.mouseDownLeft=!0;break;case 2:e.mouseDownMiddle=!0;break;case 3:e.mouseDownRight=!0}e._getMouseCanvasPos(t),e.element.focus(),e.fire("mousedown",e.mouseCanvasPos,!0),e.mouseover&&t.preventDefault()}}),document.addEventListener("mouseup",this._mouseUpListener=function(t){if(e.enabled){switch(t.which){case 1:e.mouseDownLeft=!1;break;case 2:e.mouseDownMiddle=!1;break;case 3:e.mouseDownRight=!1}e.fire("mouseup",e.mouseCanvasPos,!0)}},!0),document.addEventListener("click",this._clickListener=function(t){if(e.enabled){switch(t.which){case 1:case 3:e.mouseDownLeft=!1,e.mouseDownRight=!1;break;case 2:e.mouseDownMiddle=!1}e._getMouseCanvasPos(t),e.fire("click",e.mouseCanvasPos,!0),e.mouseover&&t.preventDefault()}}),document.addEventListener("dblclick",this._dblClickListener=function(t){if(e.enabled){switch(t.which){case 1:case 3:e.mouseDownLeft=!1,e.mouseDownRight=!1;break;case 2:e.mouseDownMiddle=!1}e._getMouseCanvasPos(t),e.fire("dblclick",e.mouseCanvasPos,!0),e.mouseover&&t.preventDefault()}}),this.element.addEventListener("mousemove",this._mouseMoveListener=function(t){e.enabled&&(e._getMouseCanvasPos(t),e.fire("mousemove",e.mouseCanvasPos,!0),e.mouseover&&t.preventDefault())}),this.element.addEventListener("wheel",this._mouseWheelListener=function(t,n){if(e.enabled){var r=Math.max(-1,Math.min(1,40*-t.deltaY));e.fire("mousewheel",r,!0)}},{passive:!0});var t,n;this.on("mousedown",(function(e){t=e[0],n=e[1]})),this.on("mouseup",(function(r){t>=r[0]-2&&t<=r[0]+2&&n>=r[1]-2&&n<=r[1]+2&&e.fire("mouseclicked",r,!0)})),this._eventsBound=!0}}},{key:"_unbindEvents",value:function(){this._eventsBound&&(this._keyboardEventsElement.removeEventListener("keydown",this._keyDownListener),this._keyboardEventsElement.removeEventListener("keyup",this._keyUpListener),this.element.removeEventListener("mouseenter",this._mouseEnterListener),this.element.removeEventListener("mouseleave",this._mouseLeaveListener),this.element.removeEventListener("mousedown",this._mouseDownListener),document.removeEventListener("mouseup",this._mouseDownListener),document.removeEventListener("click",this._clickListener),document.removeEventListener("dblclick",this._dblClickListener),this.element.removeEventListener("mousemove",this._mouseMoveListener),this.element.removeEventListener("wheel",this._mouseWheelListener),window.OrientationChangeEvent&&window.removeEventListener("orientationchange",this._orientationchangedListener),window.DeviceMotionEvent&&window.removeEventListener("devicemotion",this._deviceMotionListener),window.DeviceOrientationEvent&&window.removeEventListener("deviceorientation",this._deviceOrientListener),this._eventsBound=!1)}},{key:"_getMouseCanvasPos",value:function(e){if(e){for(var t=e.target,n=0,r=0;t.offsetParent;)n+=t.offsetLeft,r+=t.offsetTop,t=t.offsetParent;this.mouseCanvasPos[0]=e.pageX-n,this.mouseCanvasPos[1]=e.pageY-r}else e=window.event,this.mouseCanvasPos[0]=e.x,this.mouseCanvasPos[1]=e.y}},{key:"setEnabled",value:function(e){this.enabled!==e&&this.fire("enabled",this.enabled=e)}},{key:"getEnabled",value:function(){return this.enabled}},{key:"setKeyboardEnabled",value:function(e){this.keyboardEnabled=e}},{key:"getKeyboardEnabled",value:function(){return this.keyboardEnabled}},{key:"destroy",value:function(){v(T(n.prototype),"destroy",this).call(this),this._unbindEvents()}}]),n}(),Ot=new G({}),St=function(){function e(t){for(var n in b(this,e),this.id=Ot.addItem({}),t)t.hasOwnProperty(n)&&(this[n]=t[n])}return P(e,[{key:"destroy",value:function(){Ot.removeItem(this.id)}}]),e}(),Nt=function(e){I(n,ve);var t=m(n);function n(e){var r,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return b(this,n),(r=t.call(this,e,i))._state=new St({boundary:[0,0,100,100]}),r.boundary=i.boundary,r.autoBoundary=i.autoBoundary,r}return P(n,[{key:"type",get:function(){return"Viewport"}},{key:"boundary",get:function(){return this._state.boundary},set:function(e){if(!this._autoBoundary){if(!e){var t=this.scene.canvas.boundary;e=[0,0,t[2],t[3]]}this._state.boundary=e,this.glRedraw(),this.fire("boundary",this._state.boundary)}}},{key:"autoBoundary",get:function(){return this._autoBoundary},set:function(e){(e=!!e)!==this._autoBoundary&&(this._autoBoundary=e,this._autoBoundary?this._onCanvasSize=this.scene.canvas.on("boundary",(function(e){var t=e[2],n=e[3];this._state.boundary=[0,0,t,n],this.glRedraw(),this.fire("boundary",this._state.boundary)}),this):this._onCanvasSize&&(this.scene.canvas.off(this._onCanvasSize),this._onCanvasSize=null),this.fire("autoBoundary",this._autoBoundary))}},{key:"_getState",value:function(){return this._state}},{key:"destroy",value:function(){v(T(n.prototype),"destroy",this).call(this),this._state.destroy()}}]),n}(),Lt=function(e){I(n,ve);var t=m(n);function n(e){var r,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return b(this,n),(r=t.call(this,e,i)).camera=e,r._state=new St({matrix:Z.mat4(),inverseMatrix:Z.mat4(),transposedMatrix:Z.mat4(),near:.1,far:2e3}),r._inverseMatrixDirty=!0,r._transposedMatrixDirty=!0,r._fov=60,r._canvasResized=r.scene.canvas.on("boundary",r._needUpdate,g(r)),r.fov=i.fov,r.fovAxis=i.fovAxis,r.near=i.near,r.far=i.far,r}return P(n,[{key:"type",get:function(){return"Perspective"}},{key:"_update",value:function(){var e=this.scene.viewport.boundary,t=e[2]/e[3],n=this._fovAxis,r=this._fov;("x"===n||"min"===n&&t<1||"max"===n&&t>1)&&(r/=t),r=Math.min(r,120),Z.perspectiveMat4(r*(Math.PI/180),t,this._state.near,this._state.far,this._state.matrix),this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!0,this.glRedraw(),this.camera._updateScheduled=!0,this.fire("matrix",this._state.matrix)}},{key:"fov",get:function(){return this._fov},set:function(e){(e=null!=e?e:60)!==this._fov&&(this._fov=e,this._needUpdate(0),this.fire("fov",this._fov))}},{key:"fovAxis",get:function(){return this._fovAxis},set:function(e){e=e||"min",this._fovAxis!==e&&("x"!==e&&"y"!==e&&"min"!==e&&(this.error("Unsupported value for 'fovAxis': "+e+" - defaulting to 'min'"),e="min"),this._fovAxis=e,this._needUpdate(0),this.fire("fovAxis",this._fovAxis))}},{key:"near",get:function(){return this._state.near},set:function(e){var t=null!=e?e:.1;this._state.near!==t&&(this._state.near=t,this._needUpdate(0),this.fire("near",this._state.near))}},{key:"far",get:function(){return this._state.far},set:function(e){var t=null!=e?e:2e3;this._state.far!==t&&(this._state.far=t,this._needUpdate(0),this.fire("far",this._state.far))}},{key:"matrix",get:function(){return this._updateScheduled&&this._doUpdate(),this._state.matrix}},{key:"inverseMatrix",get:function(){return this._updateScheduled&&this._doUpdate(),this._inverseMatrixDirty&&(Z.inverseMat4(this._state.matrix,this._state.inverseMatrix),this._inverseMatrixDirty=!1),this._state.inverseMatrix}},{key:"transposedMatrix",get:function(){return this._updateScheduled&&this._doUpdate(),this._transposedMatrixDirty&&(Z.transposeMat4(this._state.matrix,this._state.transposedMatrix),this._transposedMatrixDirty=!1),this._state.transposedMatrix}},{key:"unproject",value:function(e,t,n,r,i){var a=this.scene.canvas.canvas,s=a.offsetWidth/2,o=a.offsetHeight/2;return n[0]=(e[0]-s)/s,n[1]=(e[1]-o)/o,n[2]=t,n[3]=1,Z.mulMat4v4(this.inverseMatrix,n,r),Z.mulVec3Scalar(r,1/r[3]),r[3]=1,r[1]*=-1,Z.mulMat4v4(this.camera.inverseViewMatrix,r,i),i}},{key:"destroy",value:function(){v(T(n.prototype),"destroy",this).call(this),this._state.destroy(),this.scene.canvas.off(this._canvasResized)}}]),n}(),xt=function(e){I(n,ve);var t=m(n);function n(e){var r,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return b(this,n),(r=t.call(this,e,i)).camera=e,r._state=new St({matrix:Z.mat4(),inverseMatrix:Z.mat4(),transposedMatrix:Z.mat4(),near:.1,far:2e3}),r._inverseMatrixDirty=!0,r._transposedMatrixDirty=!0,r.scale=i.scale,r.near=i.near,r.far=i.far,r._onCanvasBoundary=r.scene.canvas.on("boundary",r._needUpdate,g(r)),r}return P(n,[{key:"type",get:function(){return"Ortho"}},{key:"_update",value:function(){var e,t,n,r,i=this.scene,a=.5*this._scale,s=i.viewport.boundary,o=s[2],l=s[3],u=o/l;o>l?(e=-a,t=a,n=a/u,r=-a/u):(e=-a*u,t=a*u,n=a,r=-a),Z.orthoMat4c(e,t,r,n,this._state.near,this._state.far,this._state.matrix),this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!0,this.glRedraw(),this.fire("matrix",this._state.matrix)}},{key:"scale",get:function(){return this._scale},set:function(e){null==e&&(e=1),e<=0&&(e=.01),this._scale=e,this._needUpdate(0),this.fire("scale",this._scale)}},{key:"near",get:function(){return this._state.near},set:function(e){var t=null!=e?e:.1;this._state.near!==t&&(this._state.near=t,this._needUpdate(0),this.fire("near",this._state.near))}},{key:"far",get:function(){return this._state.far},set:function(e){var t=null!=e?e:2e3;this._state.far!==t&&(this._state.far=t,this._needUpdate(0),this.fire("far",this._state.far))}},{key:"matrix",get:function(){return this._updateScheduled&&this._doUpdate(),this._state.matrix}},{key:"inverseMatrix",get:function(){return this._updateScheduled&&this._doUpdate(),this._inverseMatrixDirty&&(Z.inverseMat4(this._state.matrix,this._state.inverseMatrix),this._inverseMatrixDirty=!1),this._state.inverseMatrix}},{key:"transposedMatrix",get:function(){return this._updateScheduled&&this._doUpdate(),this._transposedMatrixDirty&&(Z.transposeMat4(this._state.matrix,this._state.transposedMatrix),this._transposedMatrixDirty=!1),this._state.transposedMatrix}},{key:"unproject",value:function(e,t,n,r,i){var a=this.scene.canvas.canvas,s=a.offsetWidth/2,o=a.offsetHeight/2;return n[0]=(e[0]-s)/s,n[1]=(e[1]-o)/o,n[2]=t,n[3]=1,Z.mulMat4v4(this.inverseMatrix,n,r),Z.mulVec3Scalar(r,1/r[3]),r[3]=1,r[1]*=-1,Z.mulMat4v4(this.camera.inverseViewMatrix,r,i),i}},{key:"destroy",value:function(){v(T(n.prototype),"destroy",this).call(this),this._state.destroy(),this.scene.canvas.off(this._onCanvasBoundary)}}]),n}(),Mt=function(e){I(n,ve);var t=m(n);function n(e){var r,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return b(this,n),(r=t.call(this,e,i)).camera=e,r._state=new St({matrix:Z.mat4(),inverseMatrix:Z.mat4(),transposedMatrix:Z.mat4(),near:.1,far:1e4}),r._left=-1,r._right=1,r._bottom=-1,r._top=1,r._inverseMatrixDirty=!0,r._transposedMatrixDirty=!0,r.left=i.left,r.right=i.right,r.bottom=i.bottom,r.top=i.top,r.near=i.near,r.far=i.far,r}return P(n,[{key:"type",get:function(){return"Frustum"}},{key:"_update",value:function(){Z.frustumMat4(this._left,this._right,this._bottom,this._top,this._state.near,this._state.far,this._state.matrix),this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!0,this.glRedraw(),this.fire("matrix",this._state.matrix)}},{key:"left",get:function(){return this._left},set:function(e){this._left=null!=e?e:-1,this._needUpdate(0),this.fire("left",this._left)}},{key:"right",get:function(){return this._right},set:function(e){this._right=null!=e?e:1,this._needUpdate(0),this.fire("right",this._right)}},{key:"top",get:function(){return this._top},set:function(e){this._top=null!=e?e:1,this._needUpdate(0),this.fire("top",this._top)}},{key:"bottom",get:function(){return this._bottom},set:function(e){this._bottom=null!=e?e:-1,this._needUpdate(0),this.fire("bottom",this._bottom)}},{key:"near",get:function(){return this._state.near},set:function(e){this._state.near=null!=e?e:.1,this._needUpdate(0),this.fire("near",this._state.near)}},{key:"far",get:function(){return this._state.far},set:function(e){this._state.far=null!=e?e:1e4,this._needUpdate(0),this.fire("far",this._state.far)}},{key:"matrix",get:function(){return this._updateScheduled&&this._doUpdate(),this._state.matrix}},{key:"inverseMatrix",get:function(){return this._updateScheduled&&this._doUpdate(),this._inverseMatrixDirty&&(Z.inverseMat4(this._state.matrix,this._state.inverseMatrix),this._inverseMatrixDirty=!1),this._state.inverseMatrix}},{key:"transposedMatrix",get:function(){return this._updateScheduled&&this._doUpdate(),this._transposedMatrixDirty&&(Z.transposeMat4(this._state.matrix,this._state.transposedMatrix),this._transposedMatrixDirty=!1),this._state.transposedMatrix}},{key:"unproject",value:function(e,t,n,r,i){var a=this.scene.canvas.canvas,s=a.offsetWidth/2,o=a.offsetHeight/2;return n[0]=(e[0]-s)/s,n[1]=(e[1]-o)/o,n[2]=t,n[3]=1,Z.mulMat4v4(this.inverseMatrix,n,r),Z.mulVec3Scalar(r,1/r[3]),r[3]=1,r[1]*=-1,Z.mulMat4v4(this.camera.inverseViewMatrix,r,i),i}},{key:"destroy",value:function(){v(T(n.prototype),"destroy",this).call(this),this._state.destroy(),v(T(n.prototype),"destroy",this).call(this)}}]),n}(),Ft=function(e){I(n,ve);var t=m(n);function n(e){var r,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return b(this,n),(r=t.call(this,e,i)).camera=e,r._state=new St({matrix:Z.mat4(),inverseMatrix:Z.mat4(),transposedMatrix:Z.mat4()}),r._inverseMatrixDirty=!0,r._transposedMatrixDirty=!1,r.matrix=i.matrix,r}return P(n,[{key:"type",get:function(){return"CustomProjection"}},{key:"matrix",get:function(){return this._state.matrix},set:function(e){this._state.matrix.set(e||[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!0,this.glRedraw(),this.fire("matrix",this._state.matrix)}},{key:"inverseMatrix",get:function(){return this._updateScheduled&&this._doUpdate(),this._inverseMatrixDirty&&(Z.inverseMat4(this._state.matrix,this._state.inverseMatrix),this._inverseMatrixDirty=!1),this._state.inverseMatrix}},{key:"transposedMatrix",get:function(){return this._updateScheduled&&this._doUpdate(),this._transposedMatrixDirty&&(Z.transposeMat4(this._state.matrix,this._state.transposedMatrix),this._transposedMatrixDirty=!1),this._state.transposedMatrix}},{key:"unproject",value:function(e,t,n,r,i){var a=this.scene.canvas.canvas,s=a.offsetWidth/2,o=a.offsetHeight/2;return n[0]=(e[0]-s)/s,n[1]=(e[1]-o)/o,n[2]=t,n[3]=1,Z.mulMat4v4(this.inverseMatrix,n,r),Z.mulVec3Scalar(r,1/r[3]),r[3]=1,r[1]*=-1,Z.mulMat4v4(this.camera.inverseViewMatrix,r,i),i}},{key:"destroy",value:function(){v(T(n.prototype),"destroy",this).call(this),this._state.destroy()}}]),n}(),Ht=Z.vec3(),Ut=Z.vec3(),Gt=Z.vec3(),kt=Z.vec3(),Vt=Z.vec3(),jt=Z.vec3(),Qt=Z.vec4(),Wt=Z.vec4(),zt=Z.vec4(),Kt=Z.mat4(),Yt=Z.mat4(),Xt=Z.vec3(),qt=Z.vec3(),Jt=Z.vec3(),Zt=Z.vec3(),$t=function(e){I(n,ve);var t=m(n);function n(e){var r,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return b(this,n),(r=t.call(this,e,i))._state=new St({deviceMatrix:Z.mat4(),hasDeviceMatrix:!1,matrix:Z.mat4(),normalMatrix:Z.mat4(),inverseMatrix:Z.mat4()}),r._perspective=new Lt(g(r)),r._ortho=new xt(g(r)),r._frustum=new Mt(g(r)),r._customProjection=new Ft(g(r)),r._project=r._perspective,r._eye=Z.vec3([0,0,10]),r._look=Z.vec3([0,0,0]),r._up=Z.vec3([0,1,0]),r._worldUp=Z.vec3([0,1,0]),r._worldRight=Z.vec3([1,0,0]),r._worldForward=Z.vec3([0,0,-1]),r.deviceMatrix=i.deviceMatrix,r.eye=i.eye,r.look=i.look,r.up=i.up,r.worldAxis=i.worldAxis,r.gimbalLock=i.gimbalLock,r.constrainPitch=i.constrainPitch,r.projection=i.projection,r._perspective.on("matrix",(function(){"perspective"===r._projectionType&&r.fire("projMatrix",r._perspective.matrix)})),r._ortho.on("matrix",(function(){"ortho"===r._projectionType&&r.fire("projMatrix",r._ortho.matrix)})),r._frustum.on("matrix",(function(){"frustum"===r._projectionType&&r.fire("projMatrix",r._frustum.matrix)})),r._customProjection.on("matrix",(function(){"customProjection"===r._projectionType&&r.fire("projMatrix",r._customProjection.matrix)})),r}return P(n,[{key:"type",get:function(){return"Camera"}},{key:"_update",value:function(){var e,t=this._state;"ortho"===this.projection?(Z.subVec3(this._eye,this._look,Xt),Z.normalizeVec3(Xt,qt),Z.mulVec3Scalar(qt,1e3,Jt),Z.addVec3(this._look,Jt,Zt),e=Zt):e=this._eye,t.hasDeviceMatrix?(Z.lookAtMat4v(e,this._look,this._up,Yt),Z.mulMat4(t.deviceMatrix,Yt,t.matrix)):Z.lookAtMat4v(e,this._look,this._up,t.matrix),Z.inverseMat4(this._state.matrix,this._state.inverseMatrix),Z.transposeMat4(this._state.inverseMatrix,this._state.normalMatrix),this.glRedraw(),this.fire("matrix",this._state.matrix),this.fire("viewMatrix",this._state.matrix)}},{key:"orbitYaw",value:function(e){var t=Z.subVec3(this._eye,this._look,Ht);Z.rotationMat4v(.0174532925*e,this._gimbalLock?this._worldUp:this._up,Kt),t=Z.transformPoint3(Kt,t,Ut),this.eye=Z.addVec3(this._look,t,Gt),this.up=Z.transformPoint3(Kt,this._up,kt)}},{key:"orbitPitch",value:function(e){if(!(this._constrainPitch&&(e=Z.dotVec3(this._up,this._worldUp)/Z.DEGTORAD)<1)){var t=Z.subVec3(this._eye,this._look,Ht),n=Z.cross3Vec3(Z.normalizeVec3(t,Ut),Z.normalizeVec3(this._up,Gt));Z.rotationMat4v(.0174532925*e,n,Kt),t=Z.transformPoint3(Kt,t,kt),this.up=Z.transformPoint3(Kt,this._up,Vt),this.eye=Z.addVec3(t,this._look,jt)}}},{key:"yaw",value:function(e){var t=Z.subVec3(this._look,this._eye,Ht);Z.rotationMat4v(.0174532925*e,this._gimbalLock?this._worldUp:this._up,Kt),t=Z.transformPoint3(Kt,t,Ut),this.look=Z.addVec3(t,this._eye,Gt),this._gimbalLock&&(this.up=Z.transformPoint3(Kt,this._up,kt))}},{key:"pitch",value:function(e){if(!(this._constrainPitch&&(e=Z.dotVec3(this._up,this._worldUp)/Z.DEGTORAD)<1)){var t=Z.subVec3(this._look,this._eye,Ht),n=Z.cross3Vec3(Z.normalizeVec3(t,Ut),Z.normalizeVec3(this._up,Gt));Z.rotationMat4v(.0174532925*e,n,Kt),this.up=Z.transformPoint3(Kt,this._up,jt),t=Z.transformPoint3(Kt,t,kt),this.look=Z.addVec3(t,this._eye,Vt)}}},{key:"pan",value:function(e){var t,n=Z.subVec3(this._eye,this._look,Ht),r=[0,0,0];if(0!==e[0]){var i=Z.cross3Vec3(Z.normalizeVec3(n,[]),Z.normalizeVec3(this._up,Ut));t=Z.mulVec3Scalar(i,e[0]),r[0]+=t[0],r[1]+=t[1],r[2]+=t[2]}0!==e[1]&&(t=Z.mulVec3Scalar(Z.normalizeVec3(this._up,Gt),e[1]),r[0]+=t[0],r[1]+=t[1],r[2]+=t[2]),0!==e[2]&&(t=Z.mulVec3Scalar(Z.normalizeVec3(n,kt),e[2]),r[0]+=t[0],r[1]+=t[1],r[2]+=t[2]),this.eye=Z.addVec3(this._eye,r,Vt),this.look=Z.addVec3(this._look,r,jt)}},{key:"zoom",value:function(e){var t=Z.subVec3(this._eye,this._look,Ht),n=Math.abs(Z.lenVec3(t,Ut)),r=Math.abs(n+e);if(!(r<.5)){var i=Z.normalizeVec3(t,Gt);this.eye=Z.addVec3(this._look,Z.mulVec3Scalar(i,r),kt)}}},{key:"eye",get:function(){return this._eye},set:function(e){this._eye.set(e||[0,0,10]),this._needUpdate(0),this.fire("eye",this._eye)}},{key:"look",get:function(){return this._look},set:function(e){this._look.set(e||[0,0,0]),this._needUpdate(0),this.fire("look",this._look)}},{key:"up",get:function(){return this._up},set:function(e){this._up.set(e||[0,1,0]),this._needUpdate(0),this.fire("up",this._up)}},{key:"deviceMatrix",get:function(){return this._state.deviceMatrix},set:function(e){this._state.deviceMatrix.set(e||[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),this._state.hasDeviceMatrix=!!e,this._needUpdate(0),this.fire("deviceMatrix",this._state.deviceMatrix)}},{key:"worldAxis",get:function(){return this._worldAxis},set:function(e){e=e||[1,0,0,0,1,0,0,0,1],this._worldAxis?this._worldAxis.set(e):this._worldAxis=Z.vec3(e),this._worldRight[0]=this._worldAxis[0],this._worldRight[1]=this._worldAxis[1],this._worldRight[2]=this._worldAxis[2],this._worldUp[0]=this._worldAxis[3],this._worldUp[1]=this._worldAxis[4],this._worldUp[2]=this._worldAxis[5],this._worldForward[0]=this._worldAxis[6],this._worldForward[1]=this._worldAxis[7],this._worldForward[2]=this._worldAxis[8],this.fire("worldAxis",this._worldAxis)}},{key:"worldUp",get:function(){return this._worldUp}},{key:"xUp",get:function(){return this._worldUp[0]>this._worldUp[1]&&this._worldUp[0]>this._worldUp[2]}},{key:"yUp",get:function(){return this._worldUp[1]>this._worldUp[0]&&this._worldUp[1]>this._worldUp[2]}},{key:"zUp",get:function(){return this._worldUp[2]>this._worldUp[0]&&this._worldUp[2]>this._worldUp[1]}},{key:"worldRight",get:function(){return this._worldRight}},{key:"worldForward",get:function(){return this._worldForward}},{key:"gimbalLock",get:function(){return this._gimbalLock},set:function(e){this._gimbalLock=!1!==e,this.fire("gimbalLock",this._gimbalLock)}},{key:"constrainPitch",set:function(e){this._constrainPitch=!!e,this.fire("constrainPitch",this._constrainPitch)}},{key:"eyeLookDist",get:function(){return Z.lenVec3(Z.subVec3(this._look,this._eye,Ht))}},{key:"matrix",get:function(){return this._updateScheduled&&this._doUpdate(),this._state.matrix}},{key:"viewMatrix",get:function(){return this._updateScheduled&&this._doUpdate(),this._state.matrix}},{key:"normalMatrix",get:function(){return this._updateScheduled&&this._doUpdate(),this._state.normalMatrix}},{key:"viewNormalMatrix",get:function(){return this._updateScheduled&&this._doUpdate(),this._state.normalMatrix}},{key:"inverseViewMatrix",get:function(){return this._updateScheduled&&this._doUpdate(),this._state.inverseMatrix}},{key:"projMatrix",get:function(){return this[this.projection].matrix}},{key:"perspective",get:function(){return this._perspective}},{key:"ortho",get:function(){return this._ortho}},{key:"frustum",get:function(){return this._frustum}},{key:"customProjection",get:function(){return this._customProjection}},{key:"projection",get:function(){return this._projectionType},set:function(e){e=e||"perspective",this._projectionType!==e&&("perspective"===e?this._project=this._perspective:"ortho"===e?this._project=this._ortho:"frustum"===e?this._project=this._frustum:"customProjection"===e?this._project=this._customProjection:(this.error("Unsupported value for 'projection': "+e+" defaulting to 'perspective'"),this._project=this._perspective,e="perspective"),this._project._update(),this._projectionType=e,this.glRedraw(),this._update(),this.fire("dirty"),this.fire("projection",this._projectionType),this.fire("projMatrix",this._project.matrix))}},{key:"project",get:function(){return this._project}},{key:"projectWorldPos",value:function(e){var t=Qt,n=Wt,r=zt;t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=1,Z.mulMat4v4(this.viewMatrix,t,n),Z.mulMat4v4(this.projMatrix,n,r),Z.mulVec3Scalar(r,1/r[3]),r[3]=1,r[1]*=-1;var i=this.scene.canvas.canvas,a=i.offsetWidth/2,s=i.offsetHeight/2;return[r[0]*a+a,r[1]*s+s]}},{key:"destroy",value:function(){v(T(n.prototype),"destroy",this).call(this),this._state.destroy()}}]),n}(),en=function(e){I(n,ve);var t=m(n);function n(e){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return b(this,n),t.call(this,e,r)}return P(n,[{key:"type",get:function(){return"Light"}},{key:"isLight",get:function(){return!0}}]),n}(),tn=function(e){I(n,en);var t=m(n);function n(e){var r,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};b(this,n),(r=t.call(this,e,i))._shadowRenderBuf=null,r._shadowViewMatrix=null,r._shadowProjMatrix=null,r._shadowViewMatrixDirty=!0,r._shadowProjMatrixDirty=!0;var a=r.scene.camera,s=r.scene.canvas;return r._onCameraViewMatrix=a.on("viewMatrix",(function(){r._shadowViewMatrixDirty=!0})),r._onCameraProjMatrix=a.on("projMatrix",(function(){r._shadowProjMatrixDirty=!0})),r._onCanvasBoundary=s.on("boundary",(function(){r._shadowProjMatrixDirty=!0})),r._state=new St({type:"dir",dir:Z.vec3([1,1,1]),color:Z.vec3([.7,.7,.8]),intensity:1,space:i.space||"view",castsShadow:!1,getShadowViewMatrix:function(){if(r._shadowViewMatrixDirty){r._shadowViewMatrix||(r._shadowViewMatrix=Z.identityMat4());var e=r.scene.camera,t=r._state.dir,n=e.look,i=[n[0]-t[0],n[1]-t[1],n[2]-t[2]];Z.lookAtMat4v(i,n,[0,1,0],r._shadowViewMatrix),r._shadowViewMatrixDirty=!1}return r._shadowViewMatrix},getShadowProjMatrix:function(){return r._shadowProjMatrixDirty&&(r._shadowProjMatrix||(r._shadowProjMatrix=Z.identityMat4()),Z.orthoMat4c(-40,40,-40,40,-40,80,r._shadowProjMatrix),r._shadowProjMatrixDirty=!1),r._shadowProjMatrix},getShadowRenderBuf:function(){return r._shadowRenderBuf||(r._shadowRenderBuf=new Pt(r.scene.canvas.canvas,r.scene.canvas.gl,{size:[1024,1024]})),r._shadowRenderBuf}}),r.dir=i.dir,r.color=i.color,r.intensity=i.intensity,r.castsShadow=i.castsShadow,r.scene._lightCreated(g(r)),r}return P(n,[{key:"type",get:function(){return"DirLight"}},{key:"dir",get:function(){return this._state.dir},set:function(e){this._state.dir.set(e||[1,1,1]),this._shadowViewMatrixDirty=!0,this.glRedraw()}},{key:"color",get:function(){return this._state.color},set:function(e){this._state.color.set(e||[.7,.7,.8]),this.glRedraw()}},{key:"intensity",get:function(){return this._state.intensity},set:function(e){e=void 0!==e?e:1,this._state.intensity=e,this.glRedraw()}},{key:"castsShadow",get:function(){return this._state.castsShadow},set:function(e){e=!!e,this._state.castsShadow!==e&&(this._state.castsShadow=e,this._shadowViewMatrixDirty=!0,this.glRedraw())}},{key:"destroy",value:function(){var e=this.scene.camera,t=this.scene.canvas;e.off(this._onCameraViewMatrix),e.off(this._onCameraProjMatrix),t.off(this._onCanvasBoundary),v(T(n.prototype),"destroy",this).call(this),this._state.destroy(),this._shadowRenderBuf&&this._shadowRenderBuf.destroy(),this.scene._lightDestroyed(this),this.glRedraw()}}]),n}(),nn=function(e){I(n,en);var t=m(n);function n(e){var r,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return b(this,n),(r=t.call(this,e,i))._state={type:"ambient",color:Z.vec3([.7,.7,.7]),intensity:1},r.color=i.color,r.intensity=i.intensity,r.scene._lightCreated(g(r)),r}return P(n,[{key:"type",get:function(){return"AmbientLight"}},{key:"color",get:function(){return this._state.color},set:function(e){this._state.color.set(e||[.7,.7,.8]),this.glRedraw()}},{key:"intensity",get:function(){return this._state.intensity},set:function(e){this._state.intensity=void 0!==e?e:1,this.glRedraw()}},{key:"destroy",value:function(){v(T(n.prototype),"destroy",this).call(this),this.scene._lightDestroyed(this)}}]),n}(),rn=function(e){I(n,ve);var t=m(n);function n(e){var r,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return b(this,n),r=t.call(this,e,i),ee.memory.meshes++,r}return P(n,[{key:"type",get:function(){return"Geometry"}},{key:"isGeometry",get:function(){return!0}},{key:"destroy",value:function(){v(T(n.prototype),"destroy",this).call(this),ee.memory.meshes--}}]),n}(),an=function(){var e=[],t=[],n=[],r=[],i=[],a=0,s=new Uint16Array(3),o=new Uint16Array(3),l=new Uint16Array(3),u=Z.vec3(),c=Z.vec3(),f=Z.vec3(),p=Z.vec3(),A=Z.vec3(),d=Z.vec3(),v=Z.vec3();return function(h,I,y,m){!function(i,a){var s,o,l,u,c,f,p={},A=Math.pow(10,4),d=0;for(c=0,f=i.length;c<f;c+=3)s=i[c],o=i[c+1],l=i[c+2],void 0===p[u=Math.round(s*A)+"_"+Math.round(o*A)+"_"+Math.round(l*A)]&&(p[u]=d/3,e[d++]=s,e[d++]=o,e[d++]=l),t[c/3]=p[u];for(c=0,f=a.length;c<f;c++)r[c]=t[a[c]],n[r[c]]=a[c]}(h,I),function(t,n){a=0;for(var h=0,I=t;h<I;h+=3){var y=3*r[h],m=3*r[h+1],w=3*r[h+2];n?(s[0]=e[y],s[1]=e[y+1],s[2]=e[y+2],o[0]=e[m],o[1]=e[m+1],o[2]=e[m+2],l[0]=e[w],l[1]=e[w+1],l[2]=e[w+2],Z.decompressPosition(s,n,u),Z.decompressPosition(o,n,c),Z.decompressPosition(l,n,f)):(u[0]=e[y],u[1]=e[y+1],u[2]=e[y+2],c[0]=e[m],c[1]=e[m+1],c[2]=e[m+2],f[0]=e[w],f[1]=e[w+1],f[2]=e[w+2]),Z.subVec3(f,c,p),Z.subVec3(u,c,A),Z.cross3Vec3(p,A,d),Z.normalizeVec3(d,v);var g=i[a]||(i[a]={normal:Z.vec3()});g.normal[0]=v[0],g.normal[1]=v[1],g.normal[2]=v[2],a++}}(I.length,y);for(var w,g,T,E,b,D,P,R,C,_,B=[],O=Math.cos(Z.DEGTORAD*m),S={},N=!1,L=0,x=I.length;L<x;L+=3)for(var M=L/3,F=0;F<3;F++)w=r[L+F],g=r[L+(F+1)%3],void 0===S[b=(T=Math.min(w,g))+","+(E=Math.max(w,g))]?S[b]={index1:T,index2:E,face1:M,face2:void 0}:S[b].face2=M;for(b in S)void 0!==(D=S[b]).face2&&(P=i[D.face1].normal,R=i[D.face2].normal,Z.dotVec3(P,R)>O)||(C=n[D.index1],_=n[D.index2],(!N&&C>65535||_>65535)&&(N=!0),B.push(C),B.push(_));return N?new Uint32Array(B):new Uint16Array(B)}}();var sn=function(){var e=Z.mat4(),t=Z.mat4();return function(n,r){r=r||Z.mat4();var i=n[0],a=n[1],s=n[2],o=n[3]-i,l=n[4]-a,u=n[5]-s,c=65535;return Z.identityMat4(e),Z.translationMat4v(n,e),Z.identityMat4(t),Z.scalingMat4v([o/c,l/c,u/c],t),Z.mulMat4(e,t,r),r}}(),on=function(){var e=Z.mat4(),t=Z.mat4();return function(n,r,i){var a,s=new Uint16Array(n.length),o=new Float32Array([i[0]!==r[0]?65535/(i[0]-r[0]):0,i[1]!==r[1]?65535/(i[1]-r[1]):0,i[2]!==r[2]?65535/(i[2]-r[2]):0]);for(a=0;a<n.length;a+=3)s[a+0]=Math.max(0,Math.min(65535,Math.floor((n[a+0]-r[0])*o[0]))),s[a+1]=Math.max(0,Math.min(65535,Math.floor((n[a+1]-r[1])*o[1]))),s[a+2]=Math.max(0,Math.min(65535,Math.floor((n[a+2]-r[2])*o[2])));return Z.identityMat4(e),Z.translationMat4v(r,e),Z.identityMat4(t),Z.scalingMat4v([(i[0]-r[0])/65535,(i[1]-r[1])/65535,(i[2]-r[2])/65535],t),{quantized:s,decodeMatrix:Z.mulMat4(e,t,Z.identityMat4())}}}();var ln=function(){var e=Z.mat3(),t=Z.mat3();return function(n,r,i){var a,s=new Uint16Array(n.length),o=new Float32Array([65535/(i[0]-r[0]),65535/(i[1]-r[1])]);for(a=0;a<n.length;a+=2)s[a+0]=Math.max(0,Math.min(65535,Math.floor((n[a+0]-r[0])*o[0]))),s[a+1]=Math.max(0,Math.min(65535,Math.floor((n[a+1]-r[1])*o[1])));return Z.identityMat3(e),Z.translationMat3v(r,e),Z.identityMat3(t),Z.scalingMat3v([(i[0]-r[0])/65535,(i[1]-r[1])/65535],t),{quantized:s,decodeMatrix:Z.mulMat3(e,t,Z.identityMat3())}}}();function un(e,t,n,r){var i=e[t]/(Math.abs(e[t])+Math.abs(e[t+1])+Math.abs(e[t+2])),a=e[t+1]/(Math.abs(e[t])+Math.abs(e[t+1])+Math.abs(e[t+2]));if(e[t+2]<0){var s=(1-Math.abs(a))*(i>=0?1:-1),o=(1-Math.abs(i))*(a>=0?1:-1);i=s,a=o}return new Int8Array([Math[n](127.5*i+(i<0?-1:0)),Math[r](127.5*a+(a<0?-1:0))])}function cn(e){var t=e[0],n=e[1];t/=t<0?127:128,n/=n<0?127:128;var r=1-Math.abs(t)-Math.abs(n);r<0&&(t=(1-Math.abs(n))*(t>=0?1:-1),n=(1-Math.abs(t))*(n>=0?1:-1));var i=Math.sqrt(t*t+n*n+r*r);return[t/i,n/i,r/i]}function fn(e,t,n){return e[t]*n[0]+e[t+1]*n[1]+e[t+2]*n[2]}var pn={getPositionsBounds:function(e){var t,n,r=new Float32Array(3),i=new Float32Array(3);for(t=0;t<3;t++)r[t]=Number.MAX_VALUE,i[t]=-Number.MAX_VALUE;for(t=0;t<e.length;t+=3)for(n=0;n<3;n++)r[n]=Math.min(r[n],e[t+n]),i[n]=Math.max(i[n],e[t+n]);return{min:r,max:i}},createPositionsDecodeMatrix:sn,compressPositions:on,compressPosition:function(e,t,n){var r=new Float32Array([t[3]!==t[0]?65535/(t[3]-t[0]):0,t[4]!==t[1]?65535/(t[4]-t[1]):0,t[5]!==t[2]?65535/(t[5]-t[2]):0]);n[0]=Math.max(0,Math.min(65535,Math.floor((e[0]-t[0])*r[0]))),n[1]=Math.max(0,Math.min(65535,Math.floor((e[1]-t[1])*r[1]))),n[2]=Math.max(0,Math.min(65535,Math.floor((e[2]-t[2])*r[2])))},decompressPositions:function(e,t){for(var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:new Float32Array(e.length),r=0,i=e.length;r<i;r+=3)n[r+0]=e[r+0]*t[0]+t[12],n[r+1]=e[r+1]*t[5]+t[13],n[r+2]=e[r+2]*t[10]+t[14];return n},decompressPosition:function(e,t,n){return n[0]=e[0]*t[0]+t[12],n[1]=e[1]*t[5]+t[13],n[2]=e[2]*t[10]+t[14],n},decompressAABB:function(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:e;return n[0]=e[0]*t[0]+t[12],n[1]=e[1]*t[5]+t[13],n[2]=e[2]*t[10]+t[14],n[3]=e[3]*t[0]+t[12],n[4]=e[4]*t[5]+t[13],n[5]=e[5]*t[10]+t[14],n},getUVBounds:function(e){var t,n,r=new Float32Array(2),i=new Float32Array(2);for(t=0;t<2;t++)r[t]=Number.MAX_VALUE,i[t]=-Number.MAX_VALUE;for(t=0;t<e.length;t+=2)for(n=0;n<2;n++)r[n]=Math.min(r[n],e[t+n]),i[n]=Math.max(i[n],e[t+n]);return{min:r,max:i}},compressUVs:ln,decompressUVs:function(e,t){for(var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:new Float32Array(e.length),r=0,i=e.length;r<i;r+=3)n[r+0]=e[r+0]*t[0]+t[6],n[r+1]=e[r+1]*t[4]+t[7];return n},decompressUV:function(e,t,n){n[0]=e[0]*t[0]+t[6],n[1]=e[1]*t[4]+t[7]},compressNormals:function(e){for(var t,n,r,i,a=new Int8Array(e.length),s=0;s<e.length;s+=3)n=t=un(e,s,"floor","floor"),r=i=fn(e,s,cn(t)),(r=fn(e,s,cn(t=un(e,s,"ceil","floor"))))>i&&(n=t,i=r),(r=fn(e,s,cn(t=un(e,s,"floor","ceil"))))>i&&(n=t,i=r),(r=fn(e,s,cn(t=un(e,s,"ceil","ceil"))))>i&&(n=t,i=r),a[s]=n[0],a[s+1]=n[1];return a},decompressNormals:function(e,t){for(var n=0,r=0,i=e.length;n<i;n+=2){var a=e[n+0],s=e[n+1];a=(2*a+1)/255,s=(2*s+1)/255;var o=1-Math.abs(a)-Math.abs(s);o<0&&(a=(1-Math.abs(s))*(a>=0?1:-1),s=(1-Math.abs(a))*(s>=0?1:-1));var l=Math.sqrt(a*a+s*s+o*o);t[r+0]=a/l,t[r+1]=s/l,t[r+2]=o/l,r+=3}return t},decompressNormal:function(e,t){var n=e[0],r=e[1];n=(2*n+1)/255,r=(2*r+1)/255;var i=1-Math.abs(n)-Math.abs(r);i<0&&(n=(1-Math.abs(r))*(n>=0?1:-1),r=(1-Math.abs(n))*(r>=0?1:-1));var a=Math.sqrt(n*n+r*r+i*i);return t[0]=n/a,t[1]=r/a,t[2]=i/a,t}},An=ee.memory,dn=Z.AABB3(),vn=function(e){I(n,rn);var t=m(n);function n(e){var r,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};b(this,n),(r=t.call(this,e,i))._state=new St({compressGeometry:!!i.compressGeometry,primitive:null,primitiveName:null,positions:null,normals:null,colors:null,uv:null,indices:null,positionsDecodeMatrix:null,uvDecodeMatrix:null,positionsBuf:null,normalsBuf:null,colorsbuf:null,uvBuf:null,indicesBuf:null,hash:""}),r._numTriangles=0,r._edgeThreshold=i.edgeThreshold||10,r._edgeIndicesBuf=null,r._pickTrianglePositionsBuf=null,r._pickTriangleColorsBuf=null,r._aabbDirty=!0,r._boundingSphere=!0,r._aabb=null,r._aabbDirty=!0,r._obb=null,r._obbDirty=!0;var a=r._state,s=r.scene.canvas.gl;switch(i.primitive=i.primitive||"triangles",i.primitive){case"points":a.primitive=s.POINTS,a.primitiveName=i.primitive;break;case"lines":a.primitive=s.LINES,a.primitiveName=i.primitive;break;case"line-loop":a.primitive=s.LINE_LOOP,a.primitiveName=i.primitive;break;case"line-strip":a.primitive=s.LINE_STRIP,a.primitiveName=i.primitive;break;case"triangles":a.primitive=s.TRIANGLES,a.primitiveName=i.primitive;break;case"triangle-strip":a.primitive=s.TRIANGLE_STRIP,a.primitiveName=i.primitive;break;case"triangle-fan":a.primitive=s.TRIANGLE_FAN,a.primitiveName=i.primitive;break;default:r.error("Unsupported value for 'primitive': '"+i.primitive+"' - supported values are 'points', 'lines', 'line-loop', 'line-strip', 'triangles', 'triangle-strip' and 'triangle-fan'. Defaulting to 'triangles'."),a.primitive=s.TRIANGLES,a.primitiveName=i.primitive}if(i.positions)if(r._state.compressGeometry){var o=pn.getPositionsBounds(i.positions),l=pn.compressPositions(i.positions,o.min,o.max);a.positions=l.quantized,a.positionsDecodeMatrix=l.decodeMatrix}else a.positions=i.positions.constructor===Float32Array?i.positions:new Float32Array(i.positions);if(i.colors&&(a.colors=i.colors.constructor===Float32Array?i.colors:new Float32Array(i.colors)),i.uv)if(r._state.compressGeometry){var u=pn.getUVBounds(i.uv),c=pn.compressUVs(i.uv,u.min,u.max);a.uv=c.quantized,a.uvDecodeMatrix=c.decodeMatrix}else a.uv=i.uv.constructor===Float32Array?i.uv:new Float32Array(i.uv);return i.normals&&(r._state.compressGeometry?a.normals=pn.compressNormals(i.normals):a.normals=i.normals.constructor===Float32Array?i.normals:new Float32Array(i.normals)),i.indices&&(a.indices=i.indices.constructor===Uint32Array||i.indices.constructor===Uint16Array?i.indices:new Uint32Array(i.indices),"triangles"===r._state.primitiveName&&(r._numTriangles=i.indices.length/3)),r._buildHash(),An.meshes++,r._buildVBOs(),r}return P(n,[{key:"type",get:function(){return"ReadableGeometry"}},{key:"isReadableGeometry",get:function(){return!0}},{key:"_buildVBOs",value:function(){var e=this._state,t=this.scene.canvas.gl;if(e.indices&&(e.indicesBuf=new pt(t,t.ELEMENT_ARRAY_BUFFER,e.indices,e.indices.length,1,t.STATIC_DRAW),An.indices+=e.indicesBuf.numItems),e.positions&&(e.positionsBuf=new pt(t,t.ARRAY_BUFFER,e.positions,e.positions.length,3,t.STATIC_DRAW),An.positions+=e.positionsBuf.numItems),e.normals){var n=e.compressGeometry;e.normalsBuf=new pt(t,t.ARRAY_BUFFER,e.normals,e.normals.length,3,t.STATIC_DRAW,n),An.normals+=e.normalsBuf.numItems}e.colors&&(e.colorsBuf=new pt(t,t.ARRAY_BUFFER,e.colors,e.colors.length,4,t.STATIC_DRAW),An.colors+=e.colorsBuf.numItems),e.uv&&(e.uvBuf=new pt(t,t.ARRAY_BUFFER,e.uv,e.uv.length,2,t.STATIC_DRAW),An.uvs+=e.uvBuf.numItems)}},{key:"_buildHash",value:function(){var e=this._state,t=["/g"];t.push("/"+e.primitive+";"),e.positions&&t.push("p"),e.colors&&t.push("c"),(e.normals||e.autoVertexNormals)&&t.push("n"),e.uv&&t.push("u"),e.compressGeometry&&t.push("cp"),t.push(";"),e.hash=t.join("")}},{key:"_getEdgeIndices",value:function(){return this._edgeIndicesBuf||this._buildEdgeIndices(),this._edgeIndicesBuf}},{key:"_getPickTrianglePositions",value:function(){return this._pickTrianglePositionsBuf||this._buildPickTriangleVBOs(),this._pickTrianglePositionsBuf}},{key:"_getPickTriangleColors",value:function(){return this._pickTriangleColorsBuf||this._buildPickTriangleVBOs(),this._pickTriangleColorsBuf}},{key:"_buildEdgeIndices",value:function(){var e=this._state;if(e.positions&&e.indices){var t=this.scene.canvas.gl,n=an(e.positions,e.indices,e.positionsDecodeMatrix,this._edgeThreshold);this._edgeIndicesBuf=new pt(t,t.ELEMENT_ARRAY_BUFFER,n,n.length,1,t.STATIC_DRAW),An.indices+=this._edgeIndicesBuf.numItems}}},{key:"_buildPickTriangleVBOs",value:function(){var e=this._state;if(e.positions&&e.indices){var t=this.scene.canvas.gl,n=Z.buildPickTriangles(e.positions,e.indices,e.compressGeometry),r=n.positions,i=n.colors;this._pickTrianglePositionsBuf=new pt(t,t.ARRAY_BUFFER,r,r.length,3,t.STATIC_DRAW),this._pickTriangleColorsBuf=new pt(t,t.ARRAY_BUFFER,i,i.length,4,t.STATIC_DRAW,!0),An.positions+=this._pickTrianglePositionsBuf.numItems,An.colors+=this._pickTriangleColorsBuf.numItems}}},{key:"_buildPickVertexVBOs",value:function(){}},{key:"_webglContextLost",value:function(){this._sceneVertexBufs&&this._sceneVertexBufs.webglContextLost()}},{key:"_webglContextRestored",value:function(){this._sceneVertexBufs&&this._sceneVertexBufs.webglContextRestored(),this._buildVBOs(),this._edgeIndicesBuf=null,this._pickVertexPositionsBuf=null,this._pickTrianglePositionsBuf=null,this._pickTriangleColorsBuf=null,this._pickVertexPositionsBuf=null,this._pickVertexColorsBuf=null}},{key:"primitive",get:function(){return this._state.primitiveName}},{key:"compressGeometry",get:function(){return this._state.compressGeometry}},{key:"positions",get:function(){return this._state.positions?this._state.compressGeometry?(this._decompressedPositions||(this._decompressedPositions=new Float32Array(this._state.positions.length),pn.decompressPositions(this._state.positions,this._state.positionsDecodeMatrix,this._decompressedPositions)),this._decompressedPositions):this._state.positions:null},set:function(e){var t=this._state,n=t.positions;if(n)if(n.length===e.length){if(this._state.compressGeometry){var r=pn.getPositionsBounds(e),i=pn.compressPositions(e,r.min,r.max);e=i.quantized,t.positionsDecodeMatrix=i.decodeMatrix}n.set(e),t.positionsBuf&&t.positionsBuf.setData(n),this._setAABBDirty(),this.glRedraw()}else this.error("can't update geometry positions - new positions are wrong length");else this.error("can't update geometry positions - geometry has no positions")}},{key:"normals",get:function(){if(this._state.normals){if(!this._state.compressGeometry)return this._state.normals;if(!this._decompressedNormals){var e=this._state.normals.length,t=e+e/2;this._decompressedNormals=new Float32Array(t),pn.decompressNormals(this._state.normals,this._decompressedNormals)}return this._decompressedNormals}},set:function(e){if(this._state.compressGeometry)this.error("can't update geometry normals - quantized geometry is immutable");else{var t=this._state,n=t.normals;n?n.length===e.length?(n.set(e),t.normalsBuf&&t.normalsBuf.setData(n),this.glRedraw()):this.error("can't update geometry normals - new normals are wrong length"):this.error("can't update geometry normals - geometry has no normals")}}},{key:"uv",get:function(){return this._state.uv?this._state.compressGeometry?(this._decompressedUV||(this._decompressedUV=new Float32Array(this._state.uv.length),pn.decompressUVs(this._state.uv,this._state.uvDecodeMatrix,this._decompressedUV)),this._decompressedUV):this._state.uv:null},set:function(e){if(this._state.compressGeometry)this.error("can't update geometry UVs - quantized geometry is immutable");else{var t=this._state,n=t.uv;n?n.length===e.length?(n.set(e),t.uvBuf&&t.uvBuf.setData(n),this.glRedraw()):this.error("can't update geometry UVs - new UVs are wrong length"):this.error("can't update geometry UVs - geometry has no UVs")}}},{key:"colors",get:function(){return this._state.colors},set:function(e){if(this._state.compressGeometry)this.error("can't update geometry colors - quantized geometry is immutable");else{var t=this._state,n=t.colors;n?n.length===e.length?(n.set(e),t.colorsBuf&&t.colorsBuf.setData(n),this.glRedraw()):this.error("can't update geometry colors - new colors are wrong length"):this.error("can't update geometry colors - geometry has no colors")}}},{key:"indices",get:function(){return this._state.indices}},{key:"aabb",get:function(){return this._aabbDirty&&(this._aabb||(this._aabb=Z.AABB3()),Z.positions3ToAABB3(this._state.positions,this._aabb,this._state.positionsDecodeMatrix),this._aabbDirty=!1),this._aabb}},{key:"obb",get:function(){return this._obbDirty&&(this._obb||(this._obb=Z.OBB3()),Z.positions3ToAABB3(this._state.positions,dn,this._state.positionsDecodeMatrix),Z.AABB3ToOBB3(dn,this._obb),this._obbDirty=!1),this._obb}},{key:"numTriangles",get:function(){return this._numTriangles}},{key:"_setAABBDirty",value:function(){this._aabbDirty||(this._aabbDirty=!0,this._aabbDirty=!0,this._obbDirty=!0)}},{key:"_getState",value:function(){return this._state}},{key:"destroy",value:function(){v(T(n.prototype),"destroy",this).call(this);var e=this._state;e.indicesBuf&&e.indicesBuf.destroy(),e.positionsBuf&&e.positionsBuf.destroy(),e.normalsBuf&&e.normalsBuf.destroy(),e.uvBuf&&e.uvBuf.destroy(),e.colorsBuf&&e.colorsBuf.destroy(),this._edgeIndicesBuf&&this._edgeIndicesBuf.destroy(),this._pickTrianglePositionsBuf&&this._pickTrianglePositionsBuf.destroy(),this._pickTriangleColorsBuf&&this._pickTriangleColorsBuf.destroy(),this._pickVertexPositionsBuf&&this._pickVertexPositionsBuf.destroy(),this._pickVertexColorsBuf&&this._pickVertexColorsBuf.destroy(),e.destroy(),An.meshes--}}]),n}();function hn(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.xSize||1;t<0&&(console.error("negative xSize not allowed - will invert"),t*=-1);var n=e.ySize||1;n<0&&(console.error("negative ySize not allowed - will invert"),n*=-1);var r=e.zSize||1;r<0&&(console.error("negative zSize not allowed - will invert"),r*=-1);var i=e.center,a=i?i[0]:0,s=i?i[1]:0,o=i?i[2]:0,l=-t+a,u=-n+s,c=-r+o,f=t+a,p=n+s,A=r+o;return ae.apply(e,{positions:[f,p,A,l,p,A,l,u,A,f,u,A,f,p,A,f,u,A,f,u,c,f,p,c,f,p,A,f,p,c,l,p,c,l,p,A,l,p,A,l,p,c,l,u,c,l,u,A,l,u,c,f,u,c,f,u,A,l,u,A,f,u,c,l,u,c,l,p,c,f,p,c],normals:[0,0,1,0,0,1,0,0,1,0,0,1,1,0,0,1,0,0,1,0,0,1,0,0,0,1,0,0,1,0,0,1,0,0,1,0,-1,0,0,-1,0,0,-1,0,0,-1,0,0,0,-1,0,0,-1,0,0,-1,0,0,-1,0,0,0,-1,0,0,-1,0,0,-1,0,0,-1],uv:[1,0,0,0,0,1,1,1,0,0,0,1,1,1,1,0,1,1,1,0,0,0,0,1,1,0,0,0,0,1,1,1,0,1,1,1,1,0,0,0,0,1,1,1,1,0,0,0],indices:[0,1,2,0,2,3,4,5,6,4,6,7,8,9,10,8,10,11,12,13,14,12,14,15,16,17,18,16,18,19,20,21,22,20,22,23]})}var In=function(e){I(n,ve);var t=m(n);function n(e){var r,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return b(this,n),r=t.call(this,e,i),ee.memory.materials++,r}return P(n,[{key:"type",get:function(){return"Material"}},{key:"destroy",value:function(){v(T(n.prototype),"destroy",this).call(this),ee.memory.materials--}}]),n}(),yn={opaque:0,mask:1,blend:2},mn=["opaque","mask","blend"],wn=function(e){I(n,In);var t=m(n);function n(e){var r,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return b(this,n),(r=t.call(this,e,i))._state=new St({type:"PhongMaterial",ambient:Z.vec3([1,1,1]),diffuse:Z.vec3([1,1,1]),specular:Z.vec3([1,1,1]),emissive:Z.vec3([0,0,0]),alpha:null,shininess:null,reflectivity:null,alphaMode:null,alphaCutoff:null,lineWidth:null,pointSize:null,backfaces:null,frontface:null,hash:null}),r.ambient=i.ambient,r.diffuse=i.diffuse,r.specular=i.specular,r.emissive=i.emissive,r.alpha=i.alpha,r.shininess=i.shininess,r.reflectivity=i.reflectivity,r.lineWidth=i.lineWidth,r.pointSize=i.pointSize,i.ambientMap&&(r._ambientMap=r._checkComponent("Texture",i.ambientMap)),i.diffuseMap&&(r._diffuseMap=r._checkComponent("Texture",i.diffuseMap)),i.specularMap&&(r._specularMap=r._checkComponent("Texture",i.specularMap)),i.emissiveMap&&(r._emissiveMap=r._checkComponent("Texture",i.emissiveMap)),i.alphaMap&&(r._alphaMap=r._checkComponent("Texture",i.alphaMap)),i.reflectivityMap&&(r._reflectivityMap=r._checkComponent("Texture",i.reflectivityMap)),i.normalMap&&(r._normalMap=r._checkComponent("Texture",i.normalMap)),i.occlusionMap&&(r._occlusionMap=r._checkComponent("Texture",i.occlusionMap)),i.diffuseFresnel&&(r._diffuseFresnel=r._checkComponent("Fresnel",i.diffuseFresnel)),i.specularFresnel&&(r._specularFresnel=r._checkComponent("Fresnel",i.specularFresnel)),i.emissiveFresnel&&(r._emissiveFresnel=r._checkComponent("Fresnel",i.emissiveFresnel)),i.alphaFresnel&&(r._alphaFresnel=r._checkComponent("Fresnel",i.alphaFresnel)),i.reflectivityFresnel&&(r._reflectivityFresnel=r._checkComponent("Fresnel",i.reflectivityFresnel)),r.alphaMode=i.alphaMode,r.alphaCutoff=i.alphaCutoff,r.backfaces=i.backfaces,r.frontface=i.frontface,r._makeHash(),r}return P(n,[{key:"type",get:function(){return"PhongMaterial"}},{key:"_makeHash",value:function(){var e=this._state,t=["/p"];this._normalMap&&(t.push("/nm"),this._normalMap.hasMatrix&&t.push("/mat")),this._ambientMap&&(t.push("/am"),this._ambientMap.hasMatrix&&t.push("/mat"),t.push("/"+this._ambientMap.encoding)),this._diffuseMap&&(t.push("/dm"),this._diffuseMap.hasMatrix&&t.push("/mat"),t.push("/"+this._diffuseMap.encoding)),this._specularMap&&(t.push("/sm"),this._specularMap.hasMatrix&&t.push("/mat")),this._emissiveMap&&(t.push("/em"),this._emissiveMap.hasMatrix&&t.push("/mat"),t.push("/"+this._emissiveMap.encoding)),this._alphaMap&&(t.push("/opm"),this._alphaMap.hasMatrix&&t.push("/mat")),this._reflectivityMap&&(t.push("/rm"),this._reflectivityMap.hasMatrix&&t.push("/mat")),this._occlusionMap&&(t.push("/ocm"),this._occlusionMap.hasMatrix&&t.push("/mat")),this._diffuseFresnel&&t.push("/df"),this._specularFresnel&&t.push("/sf"),this._emissiveFresnel&&t.push("/ef"),this._alphaFresnel&&t.push("/of"),this._reflectivityFresnel&&t.push("/rf"),t.push(";"),e.hash=t.join("")}},{key:"ambient",get:function(){return this._state.ambient},set:function(e){var t=this._state.ambient;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.ambient=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=.2,t[1]=.2,t[2]=.2),this.glRedraw()}},{key:"diffuse",get:function(){return this._state.diffuse},set:function(e){var t=this._state.diffuse;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.diffuse=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=1,t[1]=1,t[2]=1),this.glRedraw()}},{key:"specular",get:function(){return this._state.specular},set:function(e){var t=this._state.specular;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.specular=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=1,t[1]=1,t[2]=1),this.glRedraw()}},{key:"emissive",get:function(){return this._state.emissive},set:function(e){var t=this._state.emissive;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.emissive=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=0,t[1]=0,t[2]=0),this.glRedraw()}},{key:"alpha",get:function(){return this._state.alpha},set:function(e){e=null!=e?e:1,this._state.alpha!==e&&(this._state.alpha=e,this.glRedraw())}},{key:"shininess",get:function(){return this._state.shininess},set:function(e){this._state.shininess=void 0!==e?e:80,this.glRedraw()}},{key:"lineWidth",get:function(){return this._state.lineWidth},set:function(e){this._state.lineWidth=e||1,this.glRedraw()}},{key:"pointSize",get:function(){return this._state.pointSize},set:function(e){this._state.pointSize=e||1,this.glRedraw()}},{key:"reflectivity",get:function(){return this._state.reflectivity},set:function(e){this._state.reflectivity=void 0!==e?e:1,this.glRedraw()}},{key:"normalMap",get:function(){return this._normalMap}},{key:"ambientMap",get:function(){return this._ambientMap}},{key:"diffuseMap",get:function(){return this._diffuseMap}},{key:"specularMap",get:function(){return this._specularMap}},{key:"emissiveMap",get:function(){return this._emissiveMap}},{key:"alphaMap",get:function(){return this._alphaMap}},{key:"reflectivityMap",get:function(){return this._reflectivityMap}},{key:"occlusionMap",get:function(){return this._occlusionMap}},{key:"diffuseFresnel",get:function(){return this._diffuseFresnel}},{key:"specularFresnel",get:function(){return this._specularFresnel}},{key:"emissiveFresnel",get:function(){return this._emissiveFresnel}},{key:"alphaFresnel",get:function(){return this._alphaFresnel}},{key:"reflectivityFresnel",get:function(){return this._reflectivityFresnel}},{key:"alphaMode",get:function(){return mn[this._state.alphaMode]},set:function(e){var t=yn[e=e||"opaque"];void 0===t&&(this.error("Unsupported value for 'alphaMode': "+e+" - defaulting to 'opaque'"),t="opaque"),this._state.alphaMode!==t&&(this._state.alphaMode=t,this.glRedraw())}},{key:"alphaCutoff",get:function(){return this._state.alphaCutoff},set:function(e){null==e&&(e=.5),this._state.alphaCutoff!==e&&(this._state.alphaCutoff=e)}},{key:"backfaces",get:function(){return this._state.backfaces},set:function(e){e=!!e,this._state.backfaces!==e&&(this._state.backfaces=e,this.glRedraw())}},{key:"frontface",get:function(){return this._state.frontface?"ccw":"cw"},set:function(e){e="cw"!==e,this._state.frontface!==e&&(this._state.frontface=e,this.glRedraw())}},{key:"destroy",value:function(){v(T(n.prototype),"destroy",this).call(this),this._state.destroy()}}]),n}(),gn={default:{fill:!0,fillColor:[.4,.4,.4],fillAlpha:.2,edges:!0,edgeColor:[.2,.2,.2],edgeAlpha:.5,edgeWidth:1},defaultWhiteBG:{fill:!0,fillColor:[1,1,1],fillAlpha:.6,edgeColor:[.2,.2,.2],edgeAlpha:1,edgeWidth:1},defaultLightBG:{fill:!0,fillColor:[.4,.4,.4],fillAlpha:.2,edges:!0,edgeColor:[.2,.2,.2],edgeAlpha:.5,edgeWidth:1},defaultDarkBG:{fill:!0,fillColor:[.4,.4,.4],fillAlpha:.2,edges:!0,edgeColor:[.5,.5,.5],edgeAlpha:.5,edgeWidth:1},phosphorous:{fill:!0,fillColor:[0,0,0],fillAlpha:.4,edges:!0,edgeColor:[.9,.9,.9],edgeAlpha:.5,edgeWidth:2},sunset:{fill:!0,fillColor:[.9,.9,.6],fillAlpha:.2,edges:!0,edgeColor:[.9,.9,.9],edgeAlpha:.5,edgeWidth:1},vectorscope:{fill:!0,fillColor:[0,0,0],fillAlpha:.7,edges:!0,edgeColor:[.2,1,.2],edgeAlpha:1,edgeWidth:2},battlezone:{fill:!0,fillColor:[0,0,0],fillAlpha:1,edges:!0,edgeColor:[.2,1,.2],edgeAlpha:1,edgeWidth:3},sepia:{fill:!0,fillColor:[.970588207244873,.7965892553329468,.6660899519920349],fillAlpha:.4,edges:!0,edgeColor:[.529411792755127,.4577854573726654,.4100345969200134],edgeAlpha:1,edgeWidth:1},yellowHighlight:{fill:!0,fillColor:[1,1,0],fillAlpha:.5,edges:!0,edgeColor:[.529411792755127,.4577854573726654,.4100345969200134],edgeAlpha:1,edgeWidth:1},greenSelected:{fill:!0,fillColor:[0,1,0],fillAlpha:.5,edges:!0,edgeColor:[.4577854573726654,.529411792755127,.4100345969200134],edgeAlpha:1,edgeWidth:1},gamegrid:{fill:!0,fillColor:[.2,.2,.7],fillAlpha:.9,edges:!0,edgeColor:[.4,.4,1.6],edgeAlpha:.8,edgeWidth:3}},Tn=function(e){I(n,In);var t=m(n);function n(e){var r,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return b(this,n),(r=t.call(this,e,i))._state=new St({type:"EmphasisMaterial",fill:null,fillColor:null,fillAlpha:null,edges:null,edgeColor:null,edgeAlpha:null,edgeWidth:null,backfaces:!0,glowThrough:!0}),r._preset="default",i.preset?(r.preset=i.preset,void 0!==i.fill&&(r.fill=i.fill),i.fillColor&&(r.fillColor=i.fillColor),void 0!==i.fillAlpha&&(r.fillAlpha=i.fillAlpha),void 0!==i.edges&&(r.edges=i.edges),i.edgeColor&&(r.edgeColor=i.edgeColor),void 0!==i.edgeAlpha&&(r.edgeAlpha=i.edgeAlpha),void 0!==i.edgeWidth&&(r.edgeWidth=i.edgeWidth),void 0!==i.backfaces&&(r.backfaces=i.backfaces),void 0!==i.glowThrough&&(r.glowThrough=i.glowThrough)):(r.fill=i.fill,r.fillColor=i.fillColor,r.fillAlpha=i.fillAlpha,r.edges=i.edges,r.edgeColor=i.edgeColor,r.edgeAlpha=i.edgeAlpha,r.edgeWidth=i.edgeWidth,r.backfaces=i.backfaces,r.glowThrough=i.glowThrough),r}return P(n,[{key:"type",get:function(){return"EmphasisMaterial"}},{key:"presets",get:function(){return gn}},{key:"fill",get:function(){return this._state.fill},set:function(e){e=!1!==e,this._state.fill!==e&&(this._state.fill=e,this.glRedraw())}},{key:"fillColor",get:function(){return this._state.fillColor},set:function(e){var t=this._state.fillColor;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.fillColor=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=.4,t[1]=.4,t[2]=.4),this.glRedraw()}},{key:"fillAlpha",get:function(){return this._state.fillAlpha},set:function(e){e=null!=e?e:.2,this._state.fillAlpha!==e&&(this._state.fillAlpha=e,this.glRedraw())}},{key:"edges",get:function(){return this._state.edges},set:function(e){e=!1!==e,this._state.edges!==e&&(this._state.edges=e,this.glRedraw())}},{key:"edgeColor",get:function(){return this._state.edgeColor},set:function(e){var t=this._state.edgeColor;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.edgeColor=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=.2,t[1]=.2,t[2]=.2),this.glRedraw()}},{key:"edgeAlpha",get:function(){return this._state.edgeAlpha},set:function(e){e=null!=e?e:.5,this._state.edgeAlpha!==e&&(this._state.edgeAlpha=e,this.glRedraw())}},{key:"edgeWidth",get:function(){return this._state.edgeWidth},set:function(e){this._state.edgeWidth=e||1,this.glRedraw()}},{key:"backfaces",get:function(){return this._state.backfaces},set:function(e){e=!!e,this._state.backfaces!==e&&(this._state.backfaces=e,this.glRedraw())}},{key:"glowThrough",get:function(){return this._state.glowThrough},set:function(e){e=!1!==e,this._state.glowThrough!==e&&(this._state.glowThrough=e,this.glRedraw())}},{key:"preset",get:function(){return this._preset},set:function(e){if(e=e||"default",this._preset!==e){var t=gn[e];t?(this.fill=t.fill,this.fillColor=t.fillColor,this.fillAlpha=t.fillAlpha,this.edges=t.edges,this.edgeColor=t.edgeColor,this.edgeAlpha=t.edgeAlpha,this.edgeWidth=t.edgeWidth,this.glowThrough=t.glowThrough,this._preset=e):this.error("unsupported preset: '"+e+"' - supported values are "+Object.keys(gn).join(", "))}}},{key:"destroy",value:function(){v(T(n.prototype),"destroy",this).call(this),this._state.destroy()}}]),n}(),En={default:{edgeColor:[0,0,0],edgeAlpha:1,edgeWidth:1},defaultWhiteBG:{edgeColor:[.2,.2,.2],edgeAlpha:1,edgeWidth:1},defaultLightBG:{edgeColor:[.2,.2,.2],edgeAlpha:1,edgeWidth:1},defaultDarkBG:{edgeColor:[.5,.5,.5],edgeAlpha:1,edgeWidth:1}},bn=function(e){I(n,In);var t=m(n);function n(e){var r,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return b(this,n),(r=t.call(this,e,i))._state=new St({type:"EdgeMaterial",edges:null,edgeColor:null,edgeAlpha:null,edgeWidth:null}),r._preset="default",i.preset?(r.preset=i.preset,i.edgeColor&&(r.edgeColor=i.edgeColor),void 0!==i.edgeAlpha&&(r.edgeAlpha=i.edgeAlpha),void 0!==i.edgeWidth&&(r.edgeWidth=i.edgeWidth)):(r.edgeColor=i.edgeColor,r.edgeAlpha=i.edgeAlpha,r.edgeWidth=i.edgeWidth),r.edges=!1!==i.edges,r}return P(n,[{key:"type",get:function(){return"EdgeMaterial"}},{key:"presets",get:function(){return En}},{key:"edges",get:function(){return this._state.edges},set:function(e){e=!1!==e,this._state.edges!==e&&(this._state.edges=e,this.glRedraw())}},{key:"edgeColor",get:function(){return this._state.edgeColor},set:function(e){var t=this._state.edgeColor;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.edgeColor=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=.2,t[1]=.2,t[2]=.2),this.glRedraw()}},{key:"edgeAlpha",get:function(){return this._state.edgeAlpha},set:function(e){e=null!=e?e:1,this._state.edgeAlpha!==e&&(this._state.edgeAlpha=e,this.glRedraw())}},{key:"edgeWidth",get:function(){return this._state.edgeWidth},set:function(e){this._state.edgeWidth=e||1,this.glRedraw()}},{key:"preset",get:function(){return this._preset},set:function(e){if(e=e||"default",this._preset!==e){var t=En[e];t?(this.edgeColor=t.edgeColor,this.edgeAlpha=t.edgeAlpha,this.edgeWidth=t.edgeWidth,this._preset=e):this.error("unsupported preset: '"+e+"' - supported values are "+Object.keys(En).join(", "))}}},{key:"destroy",value:function(){v(T(n.prototype),"destroy",this).call(this),this._state.destroy()}}]),n}(),Dn={meters:{abbrev:"m"},metres:{abbrev:"m"},centimeters:{abbrev:"cm"},centimetres:{abbrev:"cm"},millimeters:{abbrev:"mm"},millimetres:{abbrev:"mm"},yards:{abbrev:"yd"},feet:{abbrev:"ft"},inches:{abbrev:"in"}},Pn=function(e){I(n,ve);var t=m(n);function n(e){var r,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return b(this,n),(r=t.call(this,e,i))._units="meters",r._scale=1,r._origin=Z.vec3([0,0,0]),r.units=i.units,r.scale=i.scale,r.origin=i.origin,r}return P(n,[{key:"unitsInfo",get:function(){return Dn}},{key:"units",get:function(){return this._units},set:function(e){e||(e="meters"),Dn[e]||(this.error("Unsupported value for 'units': "+e+" defaulting to 'meters'"),e="meters"),this._units=e,this.fire("units",this._units)}},{key:"scale",get:function(){return this._scale},set:function(e){(e=e||1)<=0?this.error("scale value should be larger than zero"):(this._scale=e,this.fire("scale",this._scale))}},{key:"origin",get:function(){return this._origin},set:function(e){if(!e)return this._origin[0]=0,this._origin[1]=0,void(this._origin[2]=0);this._origin[0]=e[0],this._origin[1]=e[1],this._origin[2]=e[2],this.fire("origin",this._origin)}},{key:"worldToRealPos",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Z.vec3(3);t[0]=this._origin[0]+this._scale*e[0],t[1]=this._origin[1]+this._scale*e[1],t[2]=this._origin[2]+this._scale*e[2]}},{key:"realToWorldPos",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Z.vec3(3);return t[0]=(e[0]-this._origin[0])/this._scale,t[1]=(e[1]-this._origin[1])/this._scale,t[2]=(e[2]-this._origin[2])/this._scale,t}}]),n}(),Rn=function(e){I(n,ve);var t=m(n);function n(e){var r,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return b(this,n),(r=t.call(this,e,i))._supported=Ze.SUPPORTED_EXTENSIONS.OES_standard_derivatives,r.enabled=i.enabled,r.kernelRadius=i.kernelRadius,r.intensity=i.intensity,r.bias=i.bias,r.scale=i.scale,r.minResolution=i.minResolution,r.numSamples=i.numSamples,r.blur=i.blur,r.blendCutoff=i.blendCutoff,r.blendFactor=i.blendFactor,r}return P(n,[{key:"supported",get:function(){return this._supported}},{key:"enabled",get:function(){return this._enabled},set:function(e){e=!!e,this._enabled!==e&&(this._enabled=e,this.glRedraw())}},{key:"possible",get:function(){if(!this._supported)return!1;if(!this._enabled)return!1;var e=this.scene.camera.projection;return"customProjection"!==e&&"frustum"!==e}},{key:"active",get:function(){return this._active}},{key:"kernelRadius",get:function(){return this._kernelRadius},set:function(e){null==e&&(e=100),this._kernelRadius!==e&&(this._kernelRadius=e,this.glRedraw())}},{key:"intensity",get:function(){return this._intensity},set:function(e){null==e&&(e=.15),this._intensity!==e&&(this._intensity=e,this.glRedraw())}},{key:"bias",get:function(){return this._bias},set:function(e){null==e&&(e=.5),this._bias!==e&&(this._bias=e,this.glRedraw())}},{key:"scale",get:function(){return this._scale},set:function(e){null==e&&(e=1),this._scale!==e&&(this._scale=e,this.glRedraw())}},{key:"minResolution",get:function(){return this._minResolution},set:function(e){null==e&&(e=0),this._minResolution!==e&&(this._minResolution=e,this.glRedraw())}},{key:"numSamples",get:function(){return this._numSamples},set:function(e){null==e&&(e=10),this._numSamples!==e&&(this._numSamples=e,this.glRedraw())}},{key:"blur",get:function(){return this._blur},set:function(e){e=!1!==e,this._blur!==e&&(this._blur=e,this.glRedraw())}},{key:"blendCutoff",get:function(){return this._blendCutoff},set:function(e){null==e&&(e=.3),this._blendCutoff!==e&&(this._blendCutoff=e,this.glRedraw())}},{key:"blendFactor",get:function(){return this._blendFactor},set:function(e){null==e&&(e=1),this._blendFactor!==e&&(this._blendFactor=e,this.glRedraw())}},{key:"destroy",value:function(){v(T(n.prototype),"destroy",this).call(this)}}]),n}(),Cn={default:{pointSize:4,roundPoints:!0,perspectivePoints:!0},square:{pointSize:4,roundPoints:!1,perspectivePoints:!0},round:{pointSize:4,roundPoints:!0,perspectivePoints:!0}},_n=function(e){I(n,In);var t=m(n);function n(e){var r,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return b(this,n),(r=t.call(this,e,i))._state=new St({type:"PointsMaterial",pointSize:null,roundPoints:null,perspectivePoints:null,minPerspectivePointSize:null,maxPerspectivePointSize:null,filterIntensity:null,minIntensity:null,maxIntensity:null}),i.preset?(r.preset=i.preset,void 0!==i.pointSize&&(r.pointSize=i.pointSize),void 0!==i.roundPoints&&(r.roundPoints=i.roundPoints),void 0!==i.perspectivePoints&&(r.perspectivePoints=i.perspectivePoints),void 0!==i.minPerspectivePointSize&&(r.minPerspectivePointSize=i.minPerspectivePointSize),void 0!==i.maxPerspectivePointSize&&(r.maxPerspectivePointSize=i.minPerspectivePointSize)):(r._preset="default",r.pointSize=i.pointSize,r.roundPoints=i.roundPoints,r.perspectivePoints=i.perspectivePoints,r.minPerspectivePointSize=i.minPerspectivePointSize,r.maxPerspectivePointSize=i.maxPerspectivePointSize),r.filterIntensity=i.filterIntensity,r.minIntensity=i.minIntensity,r.maxIntensity=i.maxIntensity,r}return P(n,[{key:"type",get:function(){return"PointsMaterial"}},{key:"presets",get:function(){return Cn}},{key:"pointSize",get:function(){return this._state.pointSize},set:function(e){this._state.pointSize=e||2,this.glRedraw()}},{key:"roundPoints",get:function(){return this._state.roundPoints},set:function(e){e=!1!==e,this._state.roundPoints!==e&&(this._state.roundPoints=e,this.scene._needRecompile=!0,this.glRedraw())}},{key:"perspectivePoints",get:function(){return this._state.perspectivePoints},set:function(e){e=!1!==e,this._state.perspectivePoints!==e&&(this._state.perspectivePoints=e,this.scene._needRecompile=!0,this.glRedraw())}},{key:"minPerspectivePointSize",get:function(){return this._state.minPerspectivePointSize},set:function(e){this._state.minPerspectivePointSize=e||1,this.scene._needRecompile=!0,this.glRedraw()}},{key:"maxPerspectivePointSize",get:function(){return this._state.maxPerspectivePointSize},set:function(e){this._state.maxPerspectivePointSize=e||6,this.scene._needRecompile=!0,this.glRedraw()}},{key:"filterIntensity",get:function(){return this._state.filterIntensity},set:function(e){e=!1!==e,this._state.filterIntensity!==e&&(this._state.filterIntensity=e,this.scene._needRecompile=!0,this.glRedraw())}},{key:"minIntensity",get:function(){return this._state.minIntensity},set:function(e){this._state.minIntensity=null!=e?e:0,this.glRedraw()}},{key:"maxIntensity",get:function(){return this._state.maxIntensity},set:function(e){this._state.maxIntensity=null!=e?e:1,this.glRedraw()}},{key:"preset",get:function(){return this._preset},set:function(e){if(e=e||"default",this._preset!==e){var t=Cn[e];t?(this.pointSize=t.pointSize,this.roundPoints=t.roundPoints,this.perspectivePoints=t.perspectivePoints,this.minPerspectivePointSize=t.minPerspectivePointSize,this.maxPerspectivePointSize=t.maxPerspectivePointSize,this._preset=e):this.error("unsupported preset: '"+e+"' - supported values are "+Object.keys(Cn).join(", "))}}},{key:"hash",get:function(){return[this.pointSize,this.roundPoints,this.perspectivePoints,this.minPerspectivePointSize,this.maxPerspectivePointSize,this.filterIntensity].join(";")}},{key:"destroy",value:function(){v(T(n.prototype),"destroy",this).call(this),this._state.destroy()}}]),n}(),Bn={default:{lineWidth:1},thick:{lineWidth:2},thicker:{lineWidth:4}},On=function(e){I(n,In);var t=m(n);function n(e){var r,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return b(this,n),(r=t.call(this,e,i))._state=new St({type:"LinesMaterial",lineWidth:null}),i.preset?(r.preset=i.preset,void 0!==i.lineWidth&&(r.lineWidth=i.lineWidth)):(r._preset="default",r.lineWidth=i.lineWidth),r}return P(n,[{key:"type",get:function(){return"LinesMaterial"}},{key:"presets",get:function(){return Bn}},{key:"lineWidth",get:function(){return this._state.lineWidth},set:function(e){this._state.lineWidth=e||1,this.glRedraw()}},{key:"preset",get:function(){return this._preset},set:function(e){if(e=e||"default",this._preset!==e){var t=Bn[e];t?(this.lineWidth=t.lineWidth,this._preset=e):this.error("unsupported preset: '"+e+"' - supported values are "+Object.keys(Bn).join(", "))}}},{key:"hash",get:function(){return[""+this.lineWidth].join(";")}},{key:"destroy",value:function(){v(T(n.prototype),"destroy",this).call(this),this._state.destroy()}}]),n}(),Sn=Z.vec3(),Nn=Z.vec3(),Ln=Z.mat4(),xn=function(){function e(){b(this,e),this.normal=Z.vec3(),this.offset=0,this.testVertex=Z.vec3()}return P(e,[{key:"set",value:function(e,t,n,r){var i=1/Math.sqrt(e*e+t*t+n*n);this.normal[0]=e*i,this.normal[1]=t*i,this.normal[2]=n*i,this.offset=r*i,this.testVertex[0]=this.normal[0]>=0?1:0,this.testVertex[1]=this.normal[1]>=0?1:0,this.testVertex[2]=this.normal[2]>=0?1:0}}]),e}(),Mn=P((function e(){b(this,e),this.planes=[new xn,new xn,new xn,new xn,new xn,new xn]}));function Fn(e,t,n){var r=Z.mulMat4(n,t,Ln),i=r[0],a=r[1],s=r[2],o=r[3],l=r[4],u=r[5],c=r[6],f=r[7],p=r[8],A=r[9],d=r[10],v=r[11],h=r[12],I=r[13],y=r[14],m=r[15];e.planes[0].set(o-i,f-l,v-p,m-h),e.planes[1].set(o+i,f+l,v+p,m+h),e.planes[2].set(o-a,f-u,v-A,m-I),e.planes[3].set(o+a,f+u,v+A,m+I),e.planes[4].set(o-s,f-c,v-d,m-y),e.planes[5].set(o+s,f+c,v+d,m+y)}function Hn(e,t){var n=Mn.INSIDE,r=Sn,i=Nn;r[0]=t[0],r[1]=t[1],r[2]=t[2],i[0]=t[3],i[1]=t[4],i[2]=t[5];for(var a=[r,i],s=0;s<6;++s){var o=e.planes[s];if(o.normal[0]*a[o.testVertex[0]][0]+o.normal[1]*a[o.testVertex[1]][1]+o.normal[2]*a[o.testVertex[2]][2]+o.offset<0)return Mn.OUTSIDE;o.normal[0]*a[1-o.testVertex[0]][0]+o.normal[1]*a[1-o.testVertex[1]][1]+o.normal[2]*a[1-o.testVertex[2]][2]+o.offset<0&&(n=Mn.INTERSECT)}return n}Mn.INSIDE=0,Mn.INTERSECT=1,Mn.OUTSIDE=2;var Un=function(){function e(t,n){b(this,e),this.primLODLevels=t,this.entitiesInLOD={},this.primCountInLOD={},this.targetFps=n,this.lodLevelIndex=0,this.consecutiveFramesWithTargetFps=0,this.consecutiveFramesWithoutTargetFps=0}return P(e,[{key:"initializeLodState",value:function(e){var t=Object.values(e.objects);if(0!==t.length){for(var n={},r={},i=0,a=t.length;i<a;i++){var s=t[i];s.numPrimitives,Z.getAABB3Diag(s.aabb);var o,l=0;for(l=0,o=this.primLODLevels.length;l<o&&!(s.numPrimitives>=this.primLODLevels[l]);l++);var u=this.primLODLevels[l]||0;u in n||(n[u]=[]),n[u].push(s),u in r||(r[u]=0),r[u]+=s.numPrimitives}this.entitiesInLOD=n,this.primCountInLOD=r}}}]),e}(),Gn=function(){function e(t,n,r,i){b(this,e),this.id=n.id,this.scene=t,this.sceneModel=n,this.lodState=new Un(r,i),this.lodState.initializeLodState(n)}return P(e,[{key:"_increaseLODLevelIndex",value:function(){var e=this.lodState;if(e.lodLevelIndex===e.primLODLevels.length)return!1;for(var t=e.entitiesInLOD[e.primLODLevels[e.lodLevelIndex]]||[],n=0,r=t.length;n<r;n++)t[n].culledLOD=!0;return e.lodLevelIndex++,!0}},{key:"_decreaseLODLevelIndex",value:function(){var e=this.lodState;if(0===e.lodLevelIndex)return!1;for(var t=e.entitiesInLOD[e.primLODLevels[e.lodLevelIndex-1]]||[],n=0,r=t.length;n<r;n++)t[n].culledLOD=!1;return e.lodLevelIndex--,!0}},{key:"applyLodCulling",value:function(e){var t=this.lodState,n=!1;return e<t.targetFps?++t.consecutiveFramesWithoutTargetFps>0&&(t.consecutiveFramesWithoutTargetFps=0,n=this._increaseLODLevelIndex()):e>t.targetFps+4&&++t.consecutiveFramesWithTargetFps>1&&(t.consecutiveFramesWithTargetFps=0,n=this._decreaseLODLevelIndex()),n}},{key:"resetLodCulling",value:function(){var e=!1,t=!1;do{e|=t=this._decreaseLODLevelIndex()}while(t);return e}}]),e}(),kn=function(e){I(n,ve);var t=m(n);function n(e){var r,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return b(this,n),(r=t.call(this,e,i))._scene=e,r._lodLevels=[2e3,600,150,80,20],r._lodManagers={},r._lodManagerList=[],r.enabled=i.enabled,r.targetFPS=i.targetFPS,r._init(),r}return P(n,[{key:"_init",value:function(){var e=this,t=new Array(4),n=0,r=-1,i=Date.now(),a=0,s=0,o=s;this._scene.on("rendering",(function(){if(-1!==r)for(var t=0,n=e._lodManagerList.length;t<n;t++)e._lodManagerList[t].applyLodCulling(r)})),this._scene.on("rendered",(function(){i=Date.now(),window.requestAnimationFrame((function(){n++;var e=Date.now();a=e-i,i=e,t[n%4]=a;var s=0;if(n>4){for(var o=0;o<4;o++)s+=t[o];r=4/s*1e3}}))})),this._scene.camera.on("matrix",(function(){o=s})),this._scene.on("tick",(function(){if(s-o>3)for(var t=0,n=e._lodManagerList.length;t<n;t++)e._lodManagerList[t].resetLodCulling();s++}))}},{key:"enabled",get:function(){return this._enabled},set:function(e){e=!!e,this._enabled!==e&&(this._enabled=e,this.glRedraw())}},{key:"targetFPS",get:function(){return this._targetFPS},set:function(e){null==e&&(e=30),this._targetFPS!==e&&(this._targetFPS=e,this.glRedraw())}},{key:"getLODManager",value:function(e){var t=new Gn(this.scene,e,this._lodLevels,this._targetFPS);return this._lodManagers[t.id]=t,this._lodManagerList=Object.values(this._lodManagers),t}},{key:"putLODManager",value:function(e){delete this._lodManagers[e.id],this._lodManagerList=Object.values(this._lodManagers)}},{key:"destroy",value:function(){v(T(n.prototype),"destroy",this).call(this)}}]),n}(),Vn={},jn={};!function(e){if("object"===E(jn)&&void 0!==Vn)Vn.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{("undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this).RBush3D=e()}}((function(){return function e(t,n,r){function i(s,o){if(!n[s]){if(!t[s]){var l="function"==typeof require&&require;if(!o&&l)return l(s,!0);if(a)return a(s,!0);var u=new Error("Cannot find module '"+s+"'");throw u.code="MODULE_NOT_FOUND",u}var c=n[s]={exports:{}};t[s][0].call(c.exports,(function(e){return i(t[s][1][e]||e)}),c,c.exports,e,t,n,r)}return n[s].exports}for(var a="function"==typeof require&&require,s=0;s<r.length;s++)i(r[s]);return i}({1:[function(e,t,n){Object.defineProperty(n,"__esModule",{value:!0});var r=e("quickselect"),i=[],a=function(e){return i.push(e)},s=function e(t){t&&(a(t),c(t)||t.children.forEach(e))},o=function(e){var t=i.pop();return t?(t.children=e,t.height=1,t.leaf=!0,t.minX=1/0,t.minY=1/0,t.minZ=1/0,t.maxX=-1/0,t.maxY=-1/0,t.maxZ=-1/0):t={children:e,height:1,leaf:!0,minX:1/0,minY:1/0,minZ:1/0,maxX:-1/0,maxY:-1/0,maxZ:-1/0},t},l=[],u=function(e,t){var n=l.pop();return n?(n.dist=e,n.node=t):n={dist:e,node:t},n},c=function(e){return e.leaf},f=function(e,t){return e.leaf},p=function(e,t,n){if(!n)return t.indexOf(e);for(var r=0;r<t.length;r++)if(n(e,t[r]))return r;return-1},A=function(e){d(e,0,e.children.length,e)},d=function(e,t,n,r){var i=r;i?(i.minX=1/0,i.minY=1/0,i.minZ=1/0,i.maxX=-1/0,i.maxY=-1/0,i.maxZ=-1/0):i=o([]);for(var a=t,s=void 0;a<n;a++)s=e.children[a],v(i,s);return i},v=function(e,t){return e.minX=Math.min(e.minX,t.minX),e.minY=Math.min(e.minY,t.minY),e.minZ=Math.min(e.minZ,t.minZ),e.maxX=Math.max(e.maxX,t.maxX),e.maxY=Math.max(e.maxY,t.maxY),e.maxZ=Math.max(e.maxZ,t.maxZ),e},h=function(e){return(e.maxX-e.minX)*(e.maxY-e.minY)*(e.maxZ-e.minZ)},I=function(e){return e.maxX-e.minX+(e.maxY-e.minY)+(e.maxZ-e.minZ)},y=function(e,t){var n=Math.min(e.minX,t.minX),r=Math.min(e.minY,t.minY),i=Math.min(e.minZ,t.minZ);return(Math.max(e.maxX,t.maxX)-n)*(Math.max(e.maxY,t.maxY)-r)*(Math.max(e.maxZ,t.maxZ)-i)},m=function(e,t){var n=Math.max(e.minX,t.minX),r=Math.max(e.minY,t.minY),i=Math.max(e.minZ,t.minZ),a=Math.min(e.maxX,t.maxX),s=Math.min(e.maxY,t.maxY),o=Math.min(e.maxZ,t.maxZ);return Math.max(0,a-n)*Math.max(0,s-r)*Math.max(0,o-i)},w=function(e,t){return e.minX<=t.minX&&e.minY<=t.minY&&e.minZ<=t.minZ&&t.maxX<=e.maxX&&t.maxY<=e.maxY&&t.maxZ<=e.maxZ};n.intersects=function(e,t){return t.minX<=e.maxX&&t.minY<=e.maxY&&t.minZ<=e.maxZ&&t.maxX>=e.minX&&t.maxY>=e.minY&&t.maxZ>=e.minZ},n.boxRayIntersects=function(e,t,n,r,i,a,s){var o=(e.minX-t)*i,l=(e.maxX-t)*i,u=(e.minY-n)*a,c=(e.maxY-n)*a,f=(e.minZ-r)*s,p=(e.maxZ-r)*s,A=Math.min(f,p),d=Math.max(f,p),v=Math.min(u,c),h=Math.max(u,c),I=Math.min(o,l),y=Math.max(o,l),m=Math.max(0,I,v,A);return Math.min(y,h,d)>=m?m:1/0};var g=function(e,t,n,i,a){for(var s,o=[t,n];o.length;)(n=o.pop())-(t=o.pop())<=i||(s=t+Math.ceil((n-t)/i/2)*i,r(e,s,t,n,a),o.push(t,s,s,n))},T=function(e,t){return e.minX-t.minX},E=function(e,t){return e.minY-t.minY},b=function(e,t){return e.minZ-t.minZ},D=function(){function e(e){void 0===e&&(e=16),this.maxEntries=Math.max(e,8),this.minEntries=Math.max(4,Math.ceil(.4*this.maxEntries)),this.clear()}return e.alloc=function(){return this.pool.pop()||new this},e.free=function(e){e.clear(),this.pool.push(e)},e.prototype.searchCustom=function(e,t){var n=this.data,r=[];if(!e(n,f(n)))return r;for(var i=[];n;){for(var a=0,s=n.children.length;a<s;a++){var o=n.children[a];e(o,f(n))&&(f(n)?r.push(o):t(o)?this._all(o,r):i.push(o))}n=i.pop()}return r},e.prototype.analyzeTriangles=function(e){void 0===e&&(e=this.data);var t=0;if(c(e))for(var n=0,r=e.children.length;n<r;n++)t+=e.children[n].numPrimitives;else for(n=0,r=e.children.length;n<r;n++)t+=this.analyzeTriangles(e.children[n]);return e.totalTriangles=t},e.prototype.groupNodesByNumTrianglesThreshold=function(e,t){void 0===t&&(this.analyzeTriangles(),t=this.data);for(var n=[],r=0,i=t.children.length;r<i;r++){var a=t.children[r];n.push({item:a,triangles:a.totalTriangles||a.numPrimitives})}n.sort((function(e,t){return-(e.item.triangles-t.item.triangles)}));var s=[],o=[],l=0;for(r=0,i=n.length;r<i;r++){var u=n[r];if(l+u.triangles<e)o.push(u),l+=u.triangles;else if(o.length&&(s.push(o),o=[],l=0),l+u.triangles<e)r--;else if(f(t,u.item))s.push([u]);else{for(var c=this.groupNodesByNumTrianglesThreshold(e,u.item),p=[],A=0,d=0,v=c.length;d<v-1;d++)s.push(c[r]);if(c.length>1){for(d=0,v=(c=c[c.length-1]).length;d<v;d++)(A+=c[d].triangles)<e?p.push(c[d]):(0==A&&p.push(c[d]),s.push(p),A=0,p=[]);p.forEach((function(e){o.push(e),l+=e.triangles}))}}}return o.length&&s.push(o),s},e.prototype.search=function(e){var t=this.data,r=[];if(!n.intersects(e,t))return r;for(var i=[];t;){for(var a=0,s=t.children.length;a<s;a++){var o=t.children[a];n.intersects(e,o)&&(f(t)?r.push(o):w(e,o)?this._all(o,r):i.push(o))}t=i.pop()}return r},e.prototype.collides=function(e){var t=this.data;if(!n.intersects(e,t))return!1;for(var r=[];t;){for(var i=0,a=t.children.length;i<a;i++){var s=t.children[i];if(n.intersects(e,s)){if(f(t)||w(e,s))return!0;r.push(s)}}t=r.pop()}return!1},e.prototype.raycastInv=function(e,t,r,i,a,s,o){void 0===o&&(o=1/0);var c=this.data;if(i===1/0&&a===1/0&&s===1/0)return u(1/0,void 0);if(n.boxRayIntersects(c,e,t,r,i,a,s)===1/0)return u(1/0,void 0);for(var p,A=[u(0,c)],d=function(e,t){var n=A[e];A[e]=A[t],A[t]=n},v=function(){var e=A[0],t=A.length-1;A[0]=A[t],A.length=t;for(var n=0;;){var r=n<<1|1;if(r>=t)break;var i=r+1;if(i<t&&A[i].dist<A[r].dist&&(r=i),A[n].dist<A[r].dist)break;d(n,r),n=r}return function(e){l.push(e)}(e),e.node},h=function(e,t){var n=A.length;for(A.push(u(e,t));n>0;){var r=n-1>>1;if(A[r].dist<=A[n].dist)break;d(n,r),n=r}},I=o;A.length&&A[0].dist<I;)for(var y=0,m=(c=v()).children.length;y<m;y++){var w=c.children[y],g=n.boxRayIntersects(w,e,t,r,i,a,s);if(f(c)){if(g<I){if(0===g)return u(g,w);I=g,p=w}}else h(g,w)}return u(I<o?I:1/0,p)},e.prototype.raycast=function(e,t,n,r,i,a,s){return void 0===s&&(s=1/0),this.raycastInv(e,t,n,1/r,1/i,1/a,s)},e.prototype.all=function(){return this._all(this.data,[])},e.prototype.load=function(e){if(!e||!e.length)return this;if(e.length<this.minEntries){for(var t=0,n=e.length;t<n;t++)this.insert(e[t]);return this}var r=this.build(e.slice(),0,e.length-1,0);if(this.data.children.length)if(this.data.height===r.height)this.splitRoot(this.data,r);else{if(this.data.height<r.height){var i=this.data;this.data=r,r=i}this._insert(r,this.data.height-r.height-1,!0)}else this.data=r;return this},e.prototype.insert=function(e){return e&&this._insert(e,this.data.height-1),this},e.prototype.clear=function(){return this.data&&s(this.data),this.data=o([]),this},e.prototype.remove=function(e,t){if(!e)return this;for(var n,r,i=this.data,a=0,s=!1,o=[],l=[];i||o.length;){if(i||(i=o.pop(),a=l.pop(),r=o[o.length-1],s=!0),c(i)&&-1!==(n=p(e,i.children,t)))return i.children.splice(n,1),o.push(i),this.condense(o),this;s||c(i)||!w(i,e)?r?(a++,i=r.children[a],s=!1):i=void 0:(o.push(i),l.push(a),a=0,r=i,i=i.children[0])}return this},e.prototype.toJSON=function(){return this.data},e.prototype.fromJSON=function(e){return s(this.data),this.data=e,this},e.prototype.build=function(e,t,n,r){var i,a=n-t+1,s=this.maxEntries;if(a<=s)return i=o(e.slice(t,n+1)),A(i),i;r||(r=Math.ceil(Math.log(a)/Math.log(s)),s=Math.ceil(a/Math.pow(s,r-1))),(i=o([])).leaf=!1,i.height=r;var l=Math.ceil(a/s),u=l*Math.ceil(Math.pow(s,2/3)),c=l*Math.ceil(Math.pow(s,1/3));g(e,t,n,c,T);for(var f=t;f<=n;f+=c){var p=Math.min(f+c-1,n);g(e,f,p,u,E);for(var d=f;d<=p;d+=u){var v=Math.min(d+u-1,p);g(e,d,v,l,b);for(var h=d;h<=v;h+=l){var I=Math.min(h+l-1,v);i.children.push(this.build(e,h,I,r-1))}}}return A(i),i},e.prototype._all=function(e,t){for(var n=[];e;)c(e)?t.push.apply(t,e.children):n.push.apply(n,e.children),e=n.pop();return t},e.prototype.chooseSubtree=function(e,t,n,r){for(var i,a,s;r.push(t),!c(t)&&r.length-1!==n;){i=a=1/0;for(var o=0,l=t.children.length;o<l;o++){var u=t.children[o],f=h(u),p=y(e,u)-f;p<a?(a=p,i=f<i?f:i,s=u):p===a&&f<i&&(i=f,s=u)}t=s||t.children[0]}return t},e.prototype.split=function(e,t){var n=e[t],r=n.children.length,i=this.minEntries;this.chooseSplitAxis(n,i,r);var a=this.chooseSplitIndex(n,i,r),s=o(n.children.splice(a,n.children.length-a));s.height=n.height,s.leaf=n.leaf,A(n),A(s),t?e[t-1].children.push(s):this.splitRoot(n,s)},e.prototype.splitRoot=function(e,t){this.data=o([e,t]),this.data.height=e.height+1,this.data.leaf=!1,A(this.data)},e.prototype.chooseSplitIndex=function(e,t,n){for(var r,i=1/0,a=1/0,s=t;s<=n-t;s++){var o=d(e,0,s),l=d(e,s,n),u=m(o,l),c=h(o)+h(l);u<i?(i=u,r=s,a=c<a?c:a):u===i&&c<a&&(a=c,r=s)}return r},e.prototype.chooseSplitAxis=function(e,t,n){var r=this.allDistMargin(e,t,n,T),i=this.allDistMargin(e,t,n,E),a=this.allDistMargin(e,t,n,b);r<i&&r<a?e.children.sort(T):i<r&&i<a&&e.children.sort(E)},e.prototype.allDistMargin=function(e,t,n,r){e.children.sort(r);for(var i=d(e,0,t),a=d(e,n-t,n),s=I(i)+I(a),o=t;o<n-t;o++){var l=e.children[o];v(i,l),s+=I(i)}for(o=n-t-1;o>=t;o--){l=e.children[o];v(a,l),s+=I(a)}return s},e.prototype.adjustParentBBoxes=function(e,t,n){for(var r=n;r>=0;r--)v(t[r],e)},e.prototype.condense=function(e){for(var t=e.length-1,n=void 0;t>=0;t--)0===e[t].children.length?t>0?((n=e[t-1].children).splice(n.indexOf(e[t]),1),a(e[t])):this.clear():A(e[t])},e.prototype._insert=function(e,t,n){var r=[],i=this.chooseSubtree(e,this.data,t,r);for(i.children.push(e),v(i,e);t>=0&&r[t].children.length>this.maxEntries;)this.split(r,t),t--;this.adjustParentBBoxes(e,r,t)},e.pool=[],e}();n.RBush3D=D},{quickselect:2}],2:[function(e,t,n){!function(e,r){"object"===E(n)&&void 0!==t?t.exports=r():e.quickselect=r()}(this,(function(){function e(n,r,i,a,s){for(;a>i;){if(a-i>600){var o=a-i+1,l=r-i+1,u=Math.log(o),c=.5*Math.exp(2*u/3),f=.5*Math.sqrt(u*c*(o-c)/o)*(l-o/2<0?-1:1);e(n,r,Math.max(i,Math.floor(r-l*c/o+f)),Math.min(a,Math.floor(r+(o-l)*c/o+f)),s)}var p=n[r],A=i,d=a;for(t(n,i,r),s(n[a],p)>0&&t(n,i,a);A<d;){for(t(n,A,d),A++,d--;s(n[A],p)<0;)A++;for(;s(n[d],p)>0;)d--}0===s(n[i],p)?t(n,i,d):t(n,++d,a),d<=r&&(i=d+1),r<=d&&(a=d-1)}}function t(e,t,n){var r=e[t];e[t]=e[n],e[n]=r}function n(e,t){return e<t?-1:e>t?1:0}return function(t,r,i,a,s){e(t,r,i||0,a||t.length-1,s||n)}}))},{}]},{},[1])(1)}));var Qn=Vn.exports.RBush3D,Wn=function(e){function t(e){var t=0;return e.meshes.forEach((function(e){t+=e.numPrimitives})),t}function n(e,t){var n={pos:{x:0,y:0},left:0,right:e,top:0,bottom:t,dir:0};function r(){(0==n.dir&&n.pos.x+1>=n.right||1==n.dir&&n.pos.y+1>=n.bottom||2==n.dir&&n.pos.x-1<=n.left-1||3==n.dir&&n.pos.y-1<=n.top-1)&&(n.dir=(n.dir+1)%4,0==n.dir&&n.left++,1==n.dir&&n.top++,2==n.dir&&n.right--,3==n.dir&&n.bottom--),0==n.dir&&n.pos.x++,1==n.dir&&n.pos.y++,2==n.dir&&n.pos.x--,3==n.dir&&n.pos.y--}for(var i=[],a=e*t;i.length<a;r())i.push(n.pos.x+"_"+n.pos.y);return i}var r,i,a,s,o=0,l=(i=function(t,n){for(var r=n||function(e){return!0},i=(e.aabbTree.data.maxX-e.aabbTree.data.minX)/10,a=(e.aabbTree.data.maxZ-e.aabbTree.data.minZ)/10,s=[],o=e.aabbTree.data.minX,l=0;l<10;l++,o+=i)for(var u=e.aabbTree.data.minZ,c=0;c<10;c++,u+=a)s.push({minX:o,maxX:o+i,minY:-1e8,maxY:1e8,minZ:u,maxZ:u+a,indexX:l,indexZ:c});var f={cellsByEntity:{},entitiesByCell:{},cellsX:10,cellsZ:10};return(s||[]).forEach((function(t){e.aabbTree.search(t).filter((function(e){return r(e.entity)})).forEach((function(e){var n=e.entity.id;f.cellsByEntity[n]=f.cellsByEntity[n]||{cells:[],entity:e.entity},f.cellsByEntity[n].cells.push(t);var r=t.indexX+"_"+t.indexZ;f.entitiesByCell[r]=f.entitiesByCell[r]||{entities:[],cell:t},f.entitiesByCell[r].entities.push(e.entity)}))})),f}((r={cellSideInMeters:.05,entityFilterFunc:function(e){return!0},maxPolygonsPerCluster:9e4,minPercentOfClustredPolygons:.9}).cellSideInMeters,r.entityFilterFunc),a=function(e,n){var r={},i=0;Object.keys(n).forEach((function(e){var a=n[e].cells.length,s=t(n[e].entity);r[a]=(r[a]||0)+s,i+=s}));var a=Object.keys(r);a.sort((function(e,t){return e-t}));for(var s=0,o=0,l=0;l<a.length&&o<e;l++)s=a[l],o+=r[s]/i;return{maxCellsPerEntity:s,polygonStats:{percentClustered:o,numberClustered:Math.round(o*i),numberUnclustered:i-Math.round(o*i)}}}(r.minPercentOfClustredPolygons,i.cellsByEntity),s=function(e,r,i,a,s,o){var l={},u={accumEntities:[]},c=[];n(e,r).forEach((function(e){var n=function(e,t,n,r){return(n[e]||{entities:[]}).entities.filter((function(e){return r[e.id].cells.length<=t}))}(e,i,a,s).filter((function(e){return!(e.id in l)}));n.forEach((function(e){l[e.id]=!0})),n.sort((function(e,n){return t(e)-t(n)}));var r=u.accumEntities.concat(n),f=[],p=o,A=0;do{for(;A<r.length;A++){var d=r[A],v=t(d);v>p&&(c.push(f),f=[],p=o),f.push(d),p-=v}}while(A<r.length);u.accumEntities=f})),u.accumEntities.length&&c.push(u.accumEntities);var f=[];Object.keys(s).forEach((function(e){e in l||f.push(s[e].entity)}));var p=o,A=[];f.forEach((function(e){var n=t(e);n>p&&(c.push(A),A=[],p=o),A.push(e),p-=n})),A.length&&c.push(A);var d={};return c.forEach((function(e,t){e.forEach((function(e){d[e.id]=t}))})),{clusters:c,entityIdToClusterIdMapping:d}}(i.cellsX,i.cellsZ,a.maxCellsPerEntity,i.entitiesByCell,i.cellsByEntity,r.maxPolygonsPerCluster),{clusters:{total:s.clusters.length},clusteringResult:s});o+=l.clusters.total,console.log("Total clusters: "+o);var u=[];return l.clusteringResult.clusters.forEach((function(e){e.forEach((function(e){u.push(e.id)}))})),l.orderedEntityIds=u,l};
|
|
1
|
+
var e,t=l().mark(eT),n=l().mark(tT),r=l().mark(pD);function i(e){return function(e){if(Array.isArray(e))return d(e)}(e)||function(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}(e)||A(e)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function a(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function s(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?a(Object(n),!0).forEach((function(t){o(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):a(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}function o(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function l(){/*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */l=function(){return e};var e={},t=Object.prototype,n=t.hasOwnProperty,r="function"==typeof Symbol?Symbol:{},i=r.iterator||"@@iterator",a=r.asyncIterator||"@@asyncIterator",s=r.toStringTag||"@@toStringTag";function o(e,t,n){return Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}),e[t]}try{o({},"")}catch(e){o=function(e,t,n){return e[t]=n}}function u(e,t,n,r){var i=t&&t.prototype instanceof p?t:p,a=Object.create(i.prototype),s=new D(r||[]);return a._invoke=function(e,t,n){var r="suspendedStart";return function(i,a){if("executing"===r)throw new Error("Generator is already running");if("completed"===r){if("throw"===i)throw a;return R()}for(n.method=i,n.arg=a;;){var s=n.delegate;if(s){var o=g(s,n);if(o){if(o===f)continue;return o}}if("next"===n.method)n.sent=n._sent=n.arg;else if("throw"===n.method){if("suspendedStart"===r)throw r="completed",n.arg;n.dispatchException(n.arg)}else"return"===n.method&&n.abrupt("return",n.arg);r="executing";var l=c(e,t,n);if("normal"===l.type){if(r=n.done?"completed":"suspendedYield",l.arg===f)continue;return{value:l.arg,done:n.done}}"throw"===l.type&&(r="completed",n.method="throw",n.arg=l.arg)}}}(e,n,s),a}function c(e,t,n){try{return{type:"normal",arg:e.call(t,n)}}catch(e){return{type:"throw",arg:e}}}e.wrap=u;var f={};function p(){}function A(){}function d(){}var v={};o(v,i,(function(){return this}));var h=Object.getPrototypeOf,I=h&&h(h(P([])));I&&I!==t&&n.call(I,i)&&(v=I);var y=d.prototype=p.prototype=Object.create(v);function m(e){["next","throw","return"].forEach((function(t){o(e,t,(function(e){return this._invoke(t,e)}))}))}function w(e,t){function r(i,a,s,o){var l=c(e[i],e,a);if("throw"!==l.type){var u=l.arg,f=u.value;return f&&"object"==E(f)&&n.call(f,"__await")?t.resolve(f.__await).then((function(e){r("next",e,s,o)}),(function(e){r("throw",e,s,o)})):t.resolve(f).then((function(e){u.value=e,s(u)}),(function(e){return r("throw",e,s,o)}))}o(l.arg)}var i;this._invoke=function(e,n){function a(){return new t((function(t,i){r(e,n,t,i)}))}return i=i?i.then(a,a):a()}}function g(e,t){var n=e.iterator[t.method];if(void 0===n){if(t.delegate=null,"throw"===t.method){if(e.iterator.return&&(t.method="return",t.arg=void 0,g(e,t),"throw"===t.method))return f;t.method="throw",t.arg=new TypeError("The iterator does not provide a 'throw' method")}return f}var r=c(n,e.iterator,t.arg);if("throw"===r.type)return t.method="throw",t.arg=r.arg,t.delegate=null,f;var i=r.arg;return i?i.done?(t[e.resultName]=i.value,t.next=e.nextLoc,"return"!==t.method&&(t.method="next",t.arg=void 0),t.delegate=null,f):i:(t.method="throw",t.arg=new TypeError("iterator result is not an object"),t.delegate=null,f)}function T(e){var t={tryLoc:e[0]};1 in e&&(t.catchLoc=e[1]),2 in e&&(t.finallyLoc=e[2],t.afterLoc=e[3]),this.tryEntries.push(t)}function b(e){var t=e.completion||{};t.type="normal",delete t.arg,e.completion=t}function D(e){this.tryEntries=[{tryLoc:"root"}],e.forEach(T,this),this.reset(!0)}function P(e){if(e){var t=e[i];if(t)return t.call(e);if("function"==typeof e.next)return e;if(!isNaN(e.length)){var r=-1,a=function t(){for(;++r<e.length;)if(n.call(e,r))return t.value=e[r],t.done=!1,t;return t.value=void 0,t.done=!0,t};return a.next=a}}return{next:R}}function R(){return{value:void 0,done:!0}}return A.prototype=d,o(y,"constructor",d),o(d,"constructor",A),A.displayName=o(d,s,"GeneratorFunction"),e.isGeneratorFunction=function(e){var t="function"==typeof e&&e.constructor;return!!t&&(t===A||"GeneratorFunction"===(t.displayName||t.name))},e.mark=function(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,d):(e.__proto__=d,o(e,s,"GeneratorFunction")),e.prototype=Object.create(y),e},e.awrap=function(e){return{__await:e}},m(w.prototype),o(w.prototype,a,(function(){return this})),e.AsyncIterator=w,e.async=function(t,n,r,i,a){void 0===a&&(a=Promise);var s=new w(u(t,n,r,i),a);return e.isGeneratorFunction(n)?s:s.next().then((function(e){return e.done?e.value:s.next()}))},m(y),o(y,s,"Generator"),o(y,i,(function(){return this})),o(y,"toString",(function(){return"[object Generator]"})),e.keys=function(e){var t=[];for(var n in e)t.push(n);return t.reverse(),function n(){for(;t.length;){var r=t.pop();if(r in e)return n.value=r,n.done=!1,n}return n.done=!0,n}},e.values=P,D.prototype={constructor:D,reset:function(e){if(this.prev=0,this.next=0,this.sent=this._sent=void 0,this.done=!1,this.delegate=null,this.method="next",this.arg=void 0,this.tryEntries.forEach(b),!e)for(var t in this)"t"===t.charAt(0)&&n.call(this,t)&&!isNaN(+t.slice(1))&&(this[t]=void 0)},stop:function(){this.done=!0;var e=this.tryEntries[0].completion;if("throw"===e.type)throw e.arg;return this.rval},dispatchException:function(e){if(this.done)throw e;var t=this;function r(n,r){return s.type="throw",s.arg=e,t.next=n,r&&(t.method="next",t.arg=void 0),!!r}for(var i=this.tryEntries.length-1;i>=0;--i){var a=this.tryEntries[i],s=a.completion;if("root"===a.tryLoc)return r("end");if(a.tryLoc<=this.prev){var o=n.call(a,"catchLoc"),l=n.call(a,"finallyLoc");if(o&&l){if(this.prev<a.catchLoc)return r(a.catchLoc,!0);if(this.prev<a.finallyLoc)return r(a.finallyLoc)}else if(o){if(this.prev<a.catchLoc)return r(a.catchLoc,!0)}else{if(!l)throw new Error("try statement without catch or finally");if(this.prev<a.finallyLoc)return r(a.finallyLoc)}}}},abrupt:function(e,t){for(var r=this.tryEntries.length-1;r>=0;--r){var i=this.tryEntries[r];if(i.tryLoc<=this.prev&&n.call(i,"finallyLoc")&&this.prev<i.finallyLoc){var a=i;break}}a&&("break"===e||"continue"===e)&&a.tryLoc<=t&&t<=a.finallyLoc&&(a=null);var s=a?a.completion:{};return s.type=e,s.arg=t,a?(this.method="next",this.next=a.finallyLoc,f):this.complete(s)},complete:function(e,t){if("throw"===e.type)throw e.arg;return"break"===e.type||"continue"===e.type?this.next=e.arg:"return"===e.type?(this.rval=this.arg=e.arg,this.method="return",this.next="end"):"normal"===e.type&&t&&(this.next=t),f},finish:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var n=this.tryEntries[t];if(n.finallyLoc===e)return this.complete(n.completion,n.afterLoc),b(n),f}},catch:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var n=this.tryEntries[t];if(n.tryLoc===e){var r=n.completion;if("throw"===r.type){var i=r.arg;b(n)}return i}}throw new Error("illegal catch attempt")},delegateYield:function(e,t,n){return this.delegate={iterator:P(e),resultName:t,nextLoc:n},"next"===this.method&&(this.arg=void 0),f}},e}function u(e,t,n,r,i,a,s){try{var o=e[a](s),l=o.value}catch(e){return void n(e)}o.done?t(l):Promise.resolve(l).then(r,i)}function c(e){return function(){var t=this,n=arguments;return new Promise((function(r,i){var a=e.apply(t,n);function s(e){u(a,r,i,s,o,"next",e)}function o(e){u(a,r,i,s,o,"throw",e)}s(void 0)}))}}function f(e,t){var n="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!n){if(Array.isArray(e)||(n=A(e))||t&&e&&"number"==typeof e.length){n&&(e=n);var r=0,i=function(){};return{s:i,n:function(){return r>=e.length?{done:!0}:{done:!1,value:e[r++]}},e:function(e){throw e},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var a,s=!0,o=!1;return{s:function(){n=n.call(e)},n:function(){var e=n.next();return s=e.done,e},e:function(e){o=!0,a=e},f:function(){try{s||null==n.return||n.return()}finally{if(o)throw a}}}}function p(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null==n)return;var r,i,a=[],s=!0,o=!1;try{for(n=n.call(e);!(s=(r=n.next()).done)&&(a.push(r.value),!t||a.length!==t);s=!0);}catch(e){o=!0,i=e}finally{try{s||null==n.return||n.return()}finally{if(o)throw i}}return a}(e,t)||A(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function A(e,t){if(e){if("string"==typeof e)return d(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?d(e,t):void 0}}function d(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n<t;n++)r[n]=e[n];return r}function v(){return v="undefined"!=typeof Reflect&&Reflect.get?Reflect.get.bind():function(e,t,n){var r=h(e,t);if(r){var i=Object.getOwnPropertyDescriptor(r,t);return i.get?i.get.call(arguments.length<3?e:n):i.value}},v.apply(this,arguments)}function h(e,t){for(;!Object.prototype.hasOwnProperty.call(e,t)&&null!==(e=T(e)););return e}function I(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&y(e,t)}function y(e,t){return y=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},y(e,t)}function m(e){var t=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(e){return!1}}();return function(){var n,r=T(e);if(t){var i=T(this).constructor;n=Reflect.construct(r,arguments,i)}else n=r.apply(this,arguments);return w(this,n)}}function w(e,t){if(t&&("object"===E(t)||"function"==typeof t))return t;if(void 0!==t)throw new TypeError("Derived constructors may only return object or undefined");return g(e)}function g(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function T(e){return T=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},T(e)}function E(e){return E="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},E(e)}function b(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function D(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}function P(e,t,n){return t&&D(e.prototype,t),n&&D(e,n),Object.defineProperty(e,"prototype",{writable:!1}),e}function R(e){return new B(e)}function C(e){return function(){return new _(e.apply(this,arguments))}}function _(e){var t,n;function r(t,n){try{var a=e[t](n),s=a.value,o=s instanceof B;Promise.resolve(o?s.wrapped:s).then((function(e){o?r("return"===t?"return":"next",e):i(a.done?"return":"normal",e)}),(function(e){r("throw",e)}))}catch(e){i("throw",e)}}function i(e,i){switch(e){case"return":t.resolve({value:i,done:!0});break;case"throw":t.reject(i);break;default:t.resolve({value:i,done:!1})}(t=t.next)?r(t.key,t.arg):n=null}this._invoke=function(e,i){return new Promise((function(a,s){var o={key:e,arg:i,resolve:a,reject:s,next:null};n?n=n.next=o:(t=n=o,r(e,i))}))},"function"!=typeof e.return&&(this.return=void 0)}function B(e){this.wrapped=e}function O(e){var t,n,r,i=2;for("undefined"!=typeof Symbol&&(n=Symbol.asyncIterator,r=Symbol.iterator);i--;){if(n&&null!=(t=e[n]))return t.call(e);if(r&&null!=(t=e[r]))return new S(t.call(e));n="@@asyncIterator",r="@@iterator"}throw new TypeError("Object is not async iterable")}function S(e){function t(e){if(Object(e)!==e)return Promise.reject(new TypeError(e+" is not an object."));var t=e.done;return Promise.resolve(e.value).then((function(e){return{value:e,done:t}}))}return S=function(e){this.s=e,this.n=e.next},S.prototype={s:null,n:null,next:function(){return t(this.n.apply(this.s,arguments))},return:function(e){var n=this.s.return;return void 0===n?Promise.resolve({value:e,done:!0}):t(n.apply(this.s,arguments))},throw:function(e){var n=this.s.return;return void 0===n?Promise.reject(e):t(n.apply(this.s,arguments))}},new S(e)}_.prototype["function"==typeof Symbol&&Symbol.asyncIterator||"@@asyncIterator"]=function(){return this},_.prototype.next=function(e){return this._invoke("next",e)},_.prototype.throw=function(e){return this._invoke("throw",e)},_.prototype.return=function(e){return this._invoke("return",e)};var N,L,x,M,F,H,U,G=function(){function e(t,n){b(this,e),this.items=t||[],this._lastUniqueId=(n||0)+1}return P(e,[{key:"addItem",value:function(){var e;if(2===arguments.length){var t=arguments[0];if(e=arguments[1],this.items[t])throw"ID clash: '"+t+"'";return this.items[t]=e,t}for(e=arguments[0]||{};;){var n=this._lastUniqueId++;if(!this.items[n])return this.items[n]=e,n}}},{key:"removeItem",value:function(e){var t=this.items[e];return delete this.items[e],t}}]),e}(),k=new G,V=P((function e(t){b(this,e),this.id=t,this.parentItem=null,this.groups=[],this.menuElement=null,this.shown=!1,this.mouseOver=0})),j=P((function e(){b(this,e),this.items=[]})),Q=P((function e(t,n,r,i,a){b(this,e),this.id=t,this.getTitle=n,this.doAction=r,this.getEnabled=i,this.getShown=a,this.itemElement=null,this.subMenu=null,this.enabled=!0})),W=function(){function e(){var t=this,n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};b(this,e),this._id=k.addItem(),this._context=null,this._enabled=!1,this._itemsCfg=[],this._rootMenu=null,this._menuList=[],this._menuMap={},this._itemList=[],this._itemMap={},this._shown=!1,this._nextId=0,this._eventSubs={},!1!==n.hideOnMouseDown&&(document.addEventListener("mousedown",(function(e){e.target.classList.contains("xeokit-context-menu-item")||t.hide()})),document.addEventListener("touchstart",this._canvasTouchStartHandler=function(e){e.target.classList.contains("xeokit-context-menu-item")||t.hide()})),n.items&&(this.items=n.items),this._hideOnAction=!1!==n.hideOnAction,this.context=n.context,this.enabled=!1!==n.enabled,this.hide()}return P(e,[{key:"on",value:function(e,t){var n=this._eventSubs[e];n||(n=[],this._eventSubs[e]=n),n.push(t)}},{key:"fire",value:function(e,t){var n=this._eventSubs[e];if(n)for(var r=0,i=n.length;r<i;r++)n[r](t)}},{key:"items",get:function(){return this._itemsCfg},set:function(e){this._clear(),this._itemsCfg=e||[],this._parseItems(e),this._createUI()}},{key:"enabled",get:function(){return this._enabled},set:function(e){(e=!!e)!==this._enabled&&(this._enabled=e,this._enabled||this.hide())}},{key:"context",get:function(){return this._context},set:function(e){this._context=e}},{key:"show",value:function(e,t){this._context?this._enabled&&(this._shown||(this._hideAllMenus(),this._updateItemsTitles(),this._updateItemsEnabledStatus(),this._showMenu(this._rootMenu.id,e,t),this._shown=!0,this.fire("shown",{}))):console.error("ContextMenu cannot be shown without a context - set context first")}},{key:"shown",get:function(){return this._shown}},{key:"hide",value:function(){this._enabled&&this._shown&&(this._hideAllMenus(),this._shown=!1,this.fire("hidden",{}))}},{key:"destroy",value:function(){this._context=null,this._clear(),null!==this._id&&(k.removeItem(this._id),this._id=null)}},{key:"_clear",value:function(){for(var e=0,t=this._menuList.length;e<t;e++){var n=this._menuList[e].menuElement;n.parentElement.removeChild(n)}this._itemsCfg=[],this._rootMenu=null,this._menuList=[],this._menuMap={},this._itemList=[],this._itemMap={}}},{key:"_parseItems",value:function(e){var t=this;this._rootMenu=function e(n){for(var r=t._getNextId(),i=new V(r),a=0,s=n.length;a<s;a++){var o=n[a],l=new j;i.groups.push(l);for(var u=function(n,r){var a=o[n],s=a.items,u=s&&s.length>0,c=t._getNextId(),f=a.getTitle||function(){return a.title||""},p=a.doAction||a.callback||function(){},A=a.getEnabled||function(){return!0},d=a.getShown||function(){return!0},v=new Q(c,f,p,A,d);if(v.parentMenu=i,l.items.push(v),u){var h=e(s);v.subMenu=h,h.parentItem=v}t._itemList.push(v),t._itemMap[v.id]=v},c=0,f=o.length;c<f;c++)u(c)}return t._menuList.push(i),t._menuMap[i.id]=i,i}(e)}},{key:"_getNextId",value:function(){return"ContextMenu_"+this._id+"_"+this._nextId++}},{key:"_createUI",value:function(){var e=this;!function t(n){e._createMenuUI(n);for(var r=n.groups,i=0,a=r.length;i<a;i++)for(var s=r[i].items,o=0,l=s.length;o<l;o++){var u=s[o].subMenu;u&&t(u)}}(this._rootMenu)}},{key:"_createMenuUI",value:function(e){var t=this,n=e.groups,r=[];if(r.push('<div class="xeokit-context-menu '+e.id+'" style="z-index:300000; position: absolute;">'),r.push("<ul>"),n)for(var i=0,a=n.length;i<a;i++){var s=i,o=a,l=n[i].items;if(l)for(var u=0,c=l.length;u<c;u++){var f=l[u],p=f.subMenu,A=f.title||"";p?r.push('<li id="'+f.id+'" class="xeokit-context-menu-item" style="'+(s===o-1||u<c-1?"border-bottom: 0":"border-bottom: 1px solid black")+'">'+A+" [MORE]</li>"):r.push('<li id="'+f.id+'" class="xeokit-context-menu-item" style="'+(s===o-1||u<c-1?"border-bottom: 0":"border-bottom: 1px solid black")+'">'+A+"</li>")}}r.push("</ul>"),r.push("</div>");var d=r.join("");document.body.insertAdjacentHTML("beforeend",d);var v=document.querySelector("."+e.id);e.menuElement=v,v.style["border-radius"]="4px",v.style.display="none",v.style["z-index"]=3e5,v.style.background="white",v.style.border="1px solid black",v.style["box-shadow"]="0 4px 5px 0 gray",v.oncontextmenu=function(e){e.preventDefault()};var h=this,I=null;if(n)for(var y=0,m=n.length;y<m;y++){var w=n[y].items;if(w)for(var g=function(e,n){var r=w[e],i=r.subMenu;if(r.itemElement=document.getElementById(r.id),!r.itemElement)return console.error("ContextMenu item element not found: "+r.id),"continue";r.itemElement.addEventListener("mouseenter",(function(e){e.preventDefault();var t=r.subMenu;if(t){if(I&&I.id!==t.id&&(h._hideMenu(I.id),I=null),!1!==r.enabled){var n=r.itemElement,i=t.menuElement,a=n.getBoundingClientRect();i.getBoundingClientRect();a.right+200>window.innerWidth?h._showMenu(t.id,a.left-200,a.top-1):h._showMenu(t.id,a.right-5,a.top-1),I=t}}else I&&(h._hideMenu(I.id),I=null)})),i||(r.itemElement.addEventListener("click",(function(e){e.preventDefault(),h._context&&!1!==r.enabled&&(r.doAction&&r.doAction(h._context),t._hideOnAction?h.hide():(h._updateItemsTitles(),h._updateItemsEnabledStatus()))})),r.itemElement.addEventListener("mouseenter",(function(e){e.preventDefault(),!1!==r.enabled&&r.doHover&&r.doHover(h._context)})))},T=0,E=w.length;T<E;T++)g(T)}}},{key:"_updateItemsTitles",value:function(){if(this._context)for(var e=0,t=this._itemList.length;e<t;e++){var n=this._itemList[e],r=n.itemElement;if(r){var i=n.getShown;if(i&&i(this._context)){var a=n.getTitle(this._context);n.subMenu,r.innerText=a}}}}},{key:"_updateItemsEnabledStatus",value:function(){if(this._context)for(var e=0,t=this._itemList.length;e<t;e++){var n=this._itemList[e],r=n.itemElement;if(r){var i=n.getEnabled;if(i){var a=n.getShown;if(a){var s=a(this._context);if(n.shown=s,s){r.style.visibility="visible",r.style.height="auto",r.style.padding=null;var o=i(this._context);n.enabled=o,o?r.classList.remove("disabled"):r.classList.add("disabled")}else r.style.visibility="hidden",r.style.height="0",r.style.padding="0"}}}}}},{key:"_showMenu",value:function(e,t,n){var r=this._menuMap[e];if(r){if(!r.shown){var i=r.menuElement;i&&(this._showMenuElement(i,t,n),r.shown=!0)}}else console.error("Menu not found: "+e)}},{key:"_hideMenu",value:function(e){var t=this._menuMap[e];if(t){if(t.shown){var n=t.menuElement;n&&(this._hideMenuElement(n),t.shown=!1)}}else console.error("Menu not found: "+e)}},{key:"_hideAllMenus",value:function(){for(var e=0,t=this._menuList.length;e<t;e++){var n=this._menuList[e];this._hideMenu(n.id)}}},{key:"_showMenuElement",value:function(e,t,n){e.style.display="block";var r=e.offsetHeight,i=e.offsetWidth;n+r>window.innerHeight&&(n=window.innerHeight-r),t+i>window.innerWidth&&(t=window.innerWidth-i),e.style.left=t+"px",e.style.top=n+"px"}},{key:"_hideMenuElement",value:function(e){e.style.display="none"}}]),e}(),z=function(){function e(t,n,r){b(this,e),this.id=r&&r.id?r.id:t,this.viewer=n,this._subIdMap=null,this._subIdEvents=null,this._eventSubs=null,this._eventSubsNum=null,this._events=null,this._eventCallDepth=0,n.addPlugin(this)}return P(e,[{key:"fire",value:function(e,t,n){this._events||(this._events={}),this._eventSubs||(this._eventSubs={},this._eventSubsNum={}),!0!==n&&(this._events[e]=t||!0);var r,i=this._eventSubs[e];if(i)for(var a in i)i.hasOwnProperty(a)&&(r=i[a],this._eventCallDepth++,this._eventCallDepth<300?r.callback.call(r.scope,t):this.error("fire: potential stack overflow from recursive event '"+e+"' - dropping this event"),this._eventCallDepth--)}},{key:"on",value:function(e,t,n){this._events||(this._events={}),this._subIdMap||(this._subIdMap=new G),this._subIdEvents||(this._subIdEvents={}),this._eventSubs||(this._eventSubs={}),this._eventSubsNum||(this._eventSubsNum={});var r=this._eventSubs[e];r?this._eventSubsNum[e]++:(r={},this._eventSubs[e]=r,this._eventSubsNum[e]=1);var i=this._subIdMap.addItem();r[i]={callback:t,scope:n||this},this._subIdEvents[i]=e;var a=this._events[e];return void 0!==a&&t.call(n||this,a),i}},{key:"off",value:function(e){if(null!=e&&this._subIdEvents){var t=this._subIdEvents[e];if(t){delete this._subIdEvents[e];var n=this._eventSubs[t];n&&(delete n[e],this._eventSubsNum[t]--),this._subIdMap.removeItem(e)}}}},{key:"once",value:function(e,t,n){var r=this,i=this.on(e,(function(e){r.off(i),t.call(n||this,e)}),n)}},{key:"hasSubs",value:function(e){return this._eventSubsNum&&this._eventSubsNum[e]>0}},{key:"log",value:function(e){console.log("[xeokit plugin ".concat(this.id,"]: ").concat(e))}},{key:"warn",value:function(e){console.warn("[xeokit plugin ".concat(this.id,"]: ").concat(e))}},{key:"error",value:function(e){console.error("[xeokit plugin ".concat(this.id,"]: ").concat(e))}},{key:"send",value:function(e,t){}},{key:"destroy",value:function(){this.viewer.removePlugin(this)}}]),e}(),K=!0,Y=K?Float64Array:Float32Array,X=new Y(16),q=new Y(16),J=new Y(4),Z={setDoublePrecisionEnabled:function(e){Y=(K=e)?Float64Array:Float32Array},getDoublePrecisionEnabled:function(){return K},MIN_DOUBLE:-Number.MAX_SAFE_INTEGER,MAX_DOUBLE:Number.MAX_SAFE_INTEGER,MAX_INT:1e7,DEGTORAD:.0174532925,RADTODEG:57.295779513,unglobalizeObjectId:function(e,t){var n=t.indexOf("#");return n===e.length&&t.startsWith(e)?t.substring(n+1):t},globalizeObjectId:function(e,t){return e+"#"+t},safeInv:function(e){var t=1/e;return isNaN(t)||!isFinite(t)?1:t},vec2:function(e){return new Y(e||2)},vec3:function(e){return new Y(e||3)},vec4:function(e){return new Y(e||4)},mat3:function(e){return new Y(e||9)},mat3ToMat4:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:new Y(16);return t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=0,t[4]=e[3],t[5]=e[4],t[6]=e[5],t[7]=0,t[8]=e[6],t[9]=e[7],t[10]=e[8],t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t},mat4:function(e){return new Y(e||16)},mat4ToMat3:function(e,t){},doublesToFloats:function(e,t,n){for(var r=new Y(2),i=0,a=e.length;i<a;i++)Z.splitDouble(e[i],r),t[i]=r[0],n[i]=r[1]},splitDouble:function(e,t){var n=Y.from([e])[0],r=e-n;t[0]=n,t[1]=r},createUUID:function(){for(var e=[],t=0;t<256;t++)e[t]=(t<16?"0":"")+t.toString(16);return function(){var t=4294967295*Math.random()|0,n=4294967295*Math.random()|0,r=4294967295*Math.random()|0,i=4294967295*Math.random()|0;return"".concat(e[255&t]+e[t>>8&255]+e[t>>16&255]+e[t>>24&255],"-").concat(e[255&n]).concat(e[n>>8&255],"-").concat(e[n>>16&15|64]).concat(e[n>>24&255],"-").concat(e[63&r|128]).concat(e[r>>8&255],"-").concat(e[r>>16&255]).concat(e[r>>24&255]).concat(e[255&i]).concat(e[i>>8&255]).concat(e[i>>16&255]).concat(e[i>>24&255])}}(),clamp:function(e,t,n){return Math.max(t,Math.min(n,e))},fmod:function(e,t){if(e<t)return console.error("math.fmod : Attempting to find modulus within negative range - would be infinite loop - ignoring"),e;for(;t<=e;)e-=t;return e},compareVec3:function(e,t){return e[0]===t[0]&&e[1]===t[1]&&e[2]===t[2]},negateVec3:function(e,t){return t||(t=e),t[0]=-e[0],t[1]=-e[1],t[2]=-e[2],t},negateVec4:function(e,t){return t||(t=e),t[0]=-e[0],t[1]=-e[1],t[2]=-e[2],t[3]=-e[3],t},addVec4:function(e,t,n){return n||(n=e),n[0]=e[0]+t[0],n[1]=e[1]+t[1],n[2]=e[2]+t[2],n[3]=e[3]+t[3],n},addVec4Scalar:function(e,t,n){return n||(n=e),n[0]=e[0]+t,n[1]=e[1]+t,n[2]=e[2]+t,n[3]=e[3]+t,n},addVec3:function(e,t,n){return n||(n=e),n[0]=e[0]+t[0],n[1]=e[1]+t[1],n[2]=e[2]+t[2],n},addVec3Scalar:function(e,t,n){return n||(n=e),n[0]=e[0]+t,n[1]=e[1]+t,n[2]=e[2]+t,n},subVec4:function(e,t,n){return n||(n=e),n[0]=e[0]-t[0],n[1]=e[1]-t[1],n[2]=e[2]-t[2],n[3]=e[3]-t[3],n},subVec3:function(e,t,n){return n||(n=e),n[0]=e[0]-t[0],n[1]=e[1]-t[1],n[2]=e[2]-t[2],n},subVec2:function(e,t,n){return n||(n=e),n[0]=e[0]-t[0],n[1]=e[1]-t[1],n},geometricMeanVec2:function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];for(var r=new Y(t[0]),i=1;i<t.length;i++)r[0]+=t[i][0],r[1]+=t[i][1];return r[0]/=t.length,r[1]/=t.length,r},subVec4Scalar:function(e,t,n){return n||(n=e),n[0]=e[0]-t,n[1]=e[1]-t,n[2]=e[2]-t,n[3]=e[3]-t,n},subScalarVec4:function(e,t,n){return n||(n=e),n[0]=t-e[0],n[1]=t-e[1],n[2]=t-e[2],n[3]=t-e[3],n},mulVec4:function(e,t,n){return n||(n=e),n[0]=e[0]*t[0],n[1]=e[1]*t[1],n[2]=e[2]*t[2],n[3]=e[3]*t[3],n},mulVec4Scalar:function(e,t,n){return n||(n=e),n[0]=e[0]*t,n[1]=e[1]*t,n[2]=e[2]*t,n[3]=e[3]*t,n},mulVec3Scalar:function(e,t,n){return n||(n=e),n[0]=e[0]*t,n[1]=e[1]*t,n[2]=e[2]*t,n},mulVec2Scalar:function(e,t,n){return n||(n=e),n[0]=e[0]*t,n[1]=e[1]*t,n},divVec3:function(e,t,n){return n||(n=e),n[0]=e[0]/t[0],n[1]=e[1]/t[1],n[2]=e[2]/t[2],n},divVec4:function(e,t,n){return n||(n=e),n[0]=e[0]/t[0],n[1]=e[1]/t[1],n[2]=e[2]/t[2],n[3]=e[3]/t[3],n},divScalarVec3:function(e,t,n){return n||(n=t),n[0]=e/t[0],n[1]=e/t[1],n[2]=e/t[2],n},divVec3Scalar:function(e,t,n){return n||(n=e),n[0]=e[0]/t,n[1]=e[1]/t,n[2]=e[2]/t,n},divVec4Scalar:function(e,t,n){return n||(n=e),n[0]=e[0]/t,n[1]=e[1]/t,n[2]=e[2]/t,n[3]=e[3]/t,n},divScalarVec4:function(e,t,n){return n||(n=t),n[0]=e/t[0],n[1]=e/t[1],n[2]=e/t[2],n[3]=e/t[3],n},dotVec4:function(e,t){return e[0]*t[0]+e[1]*t[1]+e[2]*t[2]+e[3]*t[3]},cross3Vec4:function(e,t){var n=e[0],r=e[1],i=e[2],a=t[0],s=t[1],o=t[2];return[r*o-i*s,i*a-n*o,n*s-r*a,0]},cross3Vec3:function(e,t,n){n||(n=e);var r=e[0],i=e[1],a=e[2],s=t[0],o=t[1],l=t[2];return n[0]=i*l-a*o,n[1]=a*s-r*l,n[2]=r*o-i*s,n},sqLenVec4:function(e){return Z.dotVec4(e,e)},lenVec4:function(e){return Math.sqrt(Z.sqLenVec4(e))},dotVec3:function(e,t){return e[0]*t[0]+e[1]*t[1]+e[2]*t[2]},dotVec2:function(e,t){return e[0]*t[0]+e[1]*t[1]},sqLenVec3:function(e){return Z.dotVec3(e,e)},sqLenVec2:function(e){return Z.dotVec2(e,e)},lenVec3:function(e){return Math.sqrt(Z.sqLenVec3(e))},distVec3:(U=new Y(3),function(e,t){return Z.lenVec3(Z.subVec3(e,t,U))}),lenVec2:function(e){return Math.sqrt(Z.sqLenVec2(e))},distVec2:function(){var e=new Y(2);return function(t,n){return Z.lenVec2(Z.subVec2(t,n,e))}}(),rcpVec3:function(e,t){return Z.divScalarVec3(1,e,t)},normalizeVec4:function(e,t){var n=1/Z.lenVec4(e);return Z.mulVec4Scalar(e,n,t)},normalizeVec3:function(e,t){var n=1/Z.lenVec3(e);return Z.mulVec3Scalar(e,n,t)},normalizeVec2:function(e,t){var n=1/Z.lenVec2(e);return Z.mulVec2Scalar(e,n,t)},angleVec3:function(e,t){var n=Z.dotVec3(e,t)/Math.sqrt(Z.sqLenVec3(e)*Z.sqLenVec3(t));return n=n<-1?-1:n>1?1:n,Math.acos(n)},vec3FromMat4Scale:function(){var e=new Y(3);return function(t,n){return e[0]=t[0],e[1]=t[1],e[2]=t[2],n[0]=Z.lenVec3(e),e[0]=t[4],e[1]=t[5],e[2]=t[6],n[1]=Z.lenVec3(e),e[0]=t[8],e[1]=t[9],e[2]=t[10],n[2]=Z.lenVec3(e),n}}(),vecToArray:function(){function e(e){return Math.round(1e5*e)/1e5}return function(t){for(var n=0,r=(t=Array.prototype.slice.call(t)).length;n<r;n++)t[n]=e(t[n]);return t}}(),xyzArrayToObject:function(e){return{x:e[0],y:e[1],z:e[2]}},xyzObjectToArray:function(e,t){return(t=t||Z.vec3())[0]=e.x,t[1]=e.y,t[2]=e.z,t},dupMat4:function(e){return e.slice(0,16)},mat4To3:function(e){return[e[0],e[1],e[2],e[4],e[5],e[6],e[8],e[9],e[10]]},m4s:function(e){return[e,e,e,e,e,e,e,e,e,e,e,e,e,e,e,e]},setMat4ToZeroes:function(){return Z.m4s(0)},setMat4ToOnes:function(){return Z.m4s(1)},diagonalMat4v:function(e){return new Y([e[0],0,0,0,0,e[1],0,0,0,0,e[2],0,0,0,0,e[3]])},diagonalMat4c:function(e,t,n,r){return Z.diagonalMat4v([e,t,n,r])},diagonalMat4s:function(e){return Z.diagonalMat4c(e,e,e,e)},identityMat4:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:new Y(16);return e[0]=1,e[1]=0,e[2]=0,e[3]=0,e[4]=0,e[5]=1,e[6]=0,e[7]=0,e[8]=0,e[9]=0,e[10]=1,e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,e},identityMat3:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:new Y(9);return e[0]=1,e[1]=0,e[2]=0,e[3]=0,e[4]=1,e[5]=0,e[6]=0,e[7]=0,e[8]=1,e},isIdentityMat4:function(e){return 1===e[0]&&0===e[1]&&0===e[2]&&0===e[3]&&0===e[4]&&1===e[5]&&0===e[6]&&0===e[7]&&0===e[8]&&0===e[9]&&1===e[10]&&0===e[11]&&0===e[12]&&0===e[13]&&0===e[14]&&1===e[15]},negateMat4:function(e,t){return t||(t=e),t[0]=-e[0],t[1]=-e[1],t[2]=-e[2],t[3]=-e[3],t[4]=-e[4],t[5]=-e[5],t[6]=-e[6],t[7]=-e[7],t[8]=-e[8],t[9]=-e[9],t[10]=-e[10],t[11]=-e[11],t[12]=-e[12],t[13]=-e[13],t[14]=-e[14],t[15]=-e[15],t},addMat4:function(e,t,n){return n||(n=e),n[0]=e[0]+t[0],n[1]=e[1]+t[1],n[2]=e[2]+t[2],n[3]=e[3]+t[3],n[4]=e[4]+t[4],n[5]=e[5]+t[5],n[6]=e[6]+t[6],n[7]=e[7]+t[7],n[8]=e[8]+t[8],n[9]=e[9]+t[9],n[10]=e[10]+t[10],n[11]=e[11]+t[11],n[12]=e[12]+t[12],n[13]=e[13]+t[13],n[14]=e[14]+t[14],n[15]=e[15]+t[15],n},addMat4Scalar:function(e,t,n){return n||(n=e),n[0]=e[0]+t,n[1]=e[1]+t,n[2]=e[2]+t,n[3]=e[3]+t,n[4]=e[4]+t,n[5]=e[5]+t,n[6]=e[6]+t,n[7]=e[7]+t,n[8]=e[8]+t,n[9]=e[9]+t,n[10]=e[10]+t,n[11]=e[11]+t,n[12]=e[12]+t,n[13]=e[13]+t,n[14]=e[14]+t,n[15]=e[15]+t,n},addScalarMat4:function(e,t,n){return Z.addMat4Scalar(t,e,n)},subMat4:function(e,t,n){return n||(n=e),n[0]=e[0]-t[0],n[1]=e[1]-t[1],n[2]=e[2]-t[2],n[3]=e[3]-t[3],n[4]=e[4]-t[4],n[5]=e[5]-t[5],n[6]=e[6]-t[6],n[7]=e[7]-t[7],n[8]=e[8]-t[8],n[9]=e[9]-t[9],n[10]=e[10]-t[10],n[11]=e[11]-t[11],n[12]=e[12]-t[12],n[13]=e[13]-t[13],n[14]=e[14]-t[14],n[15]=e[15]-t[15],n},subMat4Scalar:function(e,t,n){return n||(n=e),n[0]=e[0]-t,n[1]=e[1]-t,n[2]=e[2]-t,n[3]=e[3]-t,n[4]=e[4]-t,n[5]=e[5]-t,n[6]=e[6]-t,n[7]=e[7]-t,n[8]=e[8]-t,n[9]=e[9]-t,n[10]=e[10]-t,n[11]=e[11]-t,n[12]=e[12]-t,n[13]=e[13]-t,n[14]=e[14]-t,n[15]=e[15]-t,n},subScalarMat4:function(e,t,n){return n||(n=t),n[0]=e-t[0],n[1]=e-t[1],n[2]=e-t[2],n[3]=e-t[3],n[4]=e-t[4],n[5]=e-t[5],n[6]=e-t[6],n[7]=e-t[7],n[8]=e-t[8],n[9]=e-t[9],n[10]=e-t[10],n[11]=e-t[11],n[12]=e-t[12],n[13]=e-t[13],n[14]=e-t[14],n[15]=e-t[15],n},mulMat4:function(e,t,n){n||(n=e);var r=e[0],i=e[1],a=e[2],s=e[3],o=e[4],l=e[5],u=e[6],c=e[7],f=e[8],p=e[9],A=e[10],d=e[11],v=e[12],h=e[13],I=e[14],y=e[15],m=t[0],w=t[1],g=t[2],T=t[3],E=t[4],b=t[5],D=t[6],P=t[7],R=t[8],C=t[9],_=t[10],B=t[11],O=t[12],S=t[13],N=t[14],L=t[15];return n[0]=m*r+w*o+g*f+T*v,n[1]=m*i+w*l+g*p+T*h,n[2]=m*a+w*u+g*A+T*I,n[3]=m*s+w*c+g*d+T*y,n[4]=E*r+b*o+D*f+P*v,n[5]=E*i+b*l+D*p+P*h,n[6]=E*a+b*u+D*A+P*I,n[7]=E*s+b*c+D*d+P*y,n[8]=R*r+C*o+_*f+B*v,n[9]=R*i+C*l+_*p+B*h,n[10]=R*a+C*u+_*A+B*I,n[11]=R*s+C*c+_*d+B*y,n[12]=O*r+S*o+N*f+L*v,n[13]=O*i+S*l+N*p+L*h,n[14]=O*a+S*u+N*A+L*I,n[15]=O*s+S*c+N*d+L*y,n},mulMat3:function(e,t,n){n||(n=new Y(9));var r=e[0],i=e[3],a=e[6],s=e[1],o=e[4],l=e[7],u=e[2],c=e[5],f=e[8],p=t[0],A=t[3],d=t[6],v=t[1],h=t[4],I=t[7],y=t[2],m=t[5],w=t[8];return n[0]=r*p+i*v+a*y,n[3]=r*A+i*h+a*m,n[6]=r*d+i*I+a*w,n[1]=s*p+o*v+l*y,n[4]=s*A+o*h+l*m,n[7]=s*d+o*I+l*w,n[2]=u*p+c*v+f*y,n[5]=u*A+c*h+f*m,n[8]=u*d+c*I+f*w,n},mulMat4Scalar:function(e,t,n){return n||(n=e),n[0]=e[0]*t,n[1]=e[1]*t,n[2]=e[2]*t,n[3]=e[3]*t,n[4]=e[4]*t,n[5]=e[5]*t,n[6]=e[6]*t,n[7]=e[7]*t,n[8]=e[8]*t,n[9]=e[9]*t,n[10]=e[10]*t,n[11]=e[11]*t,n[12]=e[12]*t,n[13]=e[13]*t,n[14]=e[14]*t,n[15]=e[15]*t,n},mulMat4v4:function(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:Z.vec4(),r=t[0],i=t[1],a=t[2],s=t[3];return n[0]=e[0]*r+e[4]*i+e[8]*a+e[12]*s,n[1]=e[1]*r+e[5]*i+e[9]*a+e[13]*s,n[2]=e[2]*r+e[6]*i+e[10]*a+e[14]*s,n[3]=e[3]*r+e[7]*i+e[11]*a+e[15]*s,n},transposeMat4:function(e,t){var n=e[4],r=e[14],i=e[8],a=e[13],s=e[12],o=e[9];if(!t||e===t){var l=e[1],u=e[2],c=e[3],f=e[6],p=e[7],A=e[11];return e[1]=n,e[2]=i,e[3]=s,e[4]=l,e[6]=o,e[7]=a,e[8]=u,e[9]=f,e[11]=r,e[12]=c,e[13]=p,e[14]=A,e}return t[0]=e[0],t[1]=n,t[2]=i,t[3]=s,t[4]=e[1],t[5]=e[5],t[6]=o,t[7]=a,t[8]=e[2],t[9]=e[6],t[10]=e[10],t[11]=r,t[12]=e[3],t[13]=e[7],t[14]=e[11],t[15]=e[15],t},transposeMat3:function(e,t){if(t===e){var n=e[1],r=e[2],i=e[5];t[1]=e[3],t[2]=e[6],t[3]=n,t[5]=e[7],t[6]=r,t[7]=i}else t[0]=e[0],t[1]=e[3],t[2]=e[6],t[3]=e[1],t[4]=e[4],t[5]=e[7],t[6]=e[2],t[7]=e[5],t[8]=e[8];return t},determinantMat4:function(e){var t=e[0],n=e[1],r=e[2],i=e[3],a=e[4],s=e[5],o=e[6],l=e[7],u=e[8],c=e[9],f=e[10],p=e[11],A=e[12],d=e[13],v=e[14],h=e[15];return A*c*o*i-u*d*o*i-A*s*f*i+a*d*f*i+u*s*v*i-a*c*v*i-A*c*r*l+u*d*r*l+A*n*f*l-t*d*f*l-u*n*v*l+t*c*v*l+A*s*r*p-a*d*r*p-A*n*o*p+t*d*o*p+a*n*v*p-t*s*v*p-u*s*r*h+a*c*r*h+u*n*o*h-t*c*o*h-a*n*f*h+t*s*f*h},inverseMat4:function(e,t){t||(t=e);var n=e[0],r=e[1],i=e[2],a=e[3],s=e[4],o=e[5],l=e[6],u=e[7],c=e[8],f=e[9],p=e[10],A=e[11],d=e[12],v=e[13],h=e[14],I=e[15],y=n*o-r*s,m=n*l-i*s,w=n*u-a*s,g=r*l-i*o,T=r*u-a*o,E=i*u-a*l,b=c*v-f*d,D=c*h-p*d,P=c*I-A*d,R=f*h-p*v,C=f*I-A*v,_=p*I-A*h,B=1/(y*_-m*C+w*R+g*P-T*D+E*b);return t[0]=(o*_-l*C+u*R)*B,t[1]=(-r*_+i*C-a*R)*B,t[2]=(v*E-h*T+I*g)*B,t[3]=(-f*E+p*T-A*g)*B,t[4]=(-s*_+l*P-u*D)*B,t[5]=(n*_-i*P+a*D)*B,t[6]=(-d*E+h*w-I*m)*B,t[7]=(c*E-p*w+A*m)*B,t[8]=(s*C-o*P+u*b)*B,t[9]=(-n*C+r*P-a*b)*B,t[10]=(d*T-v*w+I*y)*B,t[11]=(-c*T+f*w-A*y)*B,t[12]=(-s*R+o*D-l*b)*B,t[13]=(n*R-r*D+i*b)*B,t[14]=(-d*g+v*m-h*y)*B,t[15]=(c*g-f*m+p*y)*B,t},traceMat4:function(e){return e[0]+e[5]+e[10]+e[15]},translationMat4v:function(e,t){var n=t||Z.identityMat4();return n[12]=e[0],n[13]=e[1],n[14]=e[2],n},translationMat3v:function(e,t){var n=t||Z.identityMat3();return n[6]=e[0],n[7]=e[1],n},translationMat4c:(H=new Y(3),function(e,t,n,r){return H[0]=e,H[1]=t,H[2]=n,Z.translationMat4v(H,r)}),translationMat4s:function(e,t){return Z.translationMat4c(e,e,e,t)},translateMat4v:function(e,t){return Z.translateMat4c(e[0],e[1],e[2],t)},translateMat4c:function(e,t,n,r){var i=r[3];r[0]+=i*e,r[1]+=i*t,r[2]+=i*n;var a=r[7];r[4]+=a*e,r[5]+=a*t,r[6]+=a*n;var s=r[11];r[8]+=s*e,r[9]+=s*t,r[10]+=s*n;var o=r[15];return r[12]+=o*e,r[13]+=o*t,r[14]+=o*n,r},setMat4Translation:function(e,t,n){return n[0]=e[0],n[1]=e[1],n[2]=e[2],n[3]=e[3],n[4]=e[4],n[5]=e[5],n[6]=e[6],n[7]=e[7],n[8]=e[8],n[9]=e[9],n[10]=e[10],n[11]=e[11],n[12]=t[0],n[13]=t[1],n[14]=t[2],n[15]=e[15],n},rotationMat4v:function(e,t,n){var r,i,a,s,o,l,u=Z.normalizeVec4([t[0],t[1],t[2],0],[]),c=Math.sin(e),f=Math.cos(e),p=1-f,A=u[0],d=u[1],v=u[2];return r=A*d,i=d*v,a=v*A,s=A*c,o=d*c,l=v*c,(n=n||Z.mat4())[0]=p*A*A+f,n[1]=p*r+l,n[2]=p*a-o,n[3]=0,n[4]=p*r-l,n[5]=p*d*d+f,n[6]=p*i+s,n[7]=0,n[8]=p*a+o,n[9]=p*i-s,n[10]=p*v*v+f,n[11]=0,n[12]=0,n[13]=0,n[14]=0,n[15]=1,n},rotationMat4c:function(e,t,n,r,i){return Z.rotationMat4v(e,[t,n,r],i)},scalingMat4v:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Z.identityMat4();return t[0]=e[0],t[5]=e[1],t[10]=e[2],t},scalingMat3v:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Z.identityMat3();return t[0]=e[0],t[4]=e[1],t},scalingMat4c:function(){var e=new Y(3);return function(t,n,r,i){return e[0]=t,e[1]=n,e[2]=r,Z.scalingMat4v(e,i)}}(),scaleMat4c:function(e,t,n,r){return r[0]*=e,r[4]*=t,r[8]*=n,r[1]*=e,r[5]*=t,r[9]*=n,r[2]*=e,r[6]*=t,r[10]*=n,r[3]*=e,r[7]*=t,r[11]*=n,r},scaleMat4v:function(e,t){var n=e[0],r=e[1],i=e[2];return t[0]*=n,t[4]*=r,t[8]*=i,t[1]*=n,t[5]*=r,t[9]*=i,t[2]*=n,t[6]*=r,t[10]*=i,t[3]*=n,t[7]*=r,t[11]*=i,t},scalingMat4s:function(e){return Z.scalingMat4c(e,e,e)},rotationTranslationMat4:function(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:Z.mat4(),r=e[0],i=e[1],a=e[2],s=e[3],o=r+r,l=i+i,u=a+a,c=r*o,f=r*l,p=r*u,A=i*l,d=i*u,v=a*u,h=s*o,I=s*l,y=s*u;return n[0]=1-(A+v),n[1]=f+y,n[2]=p-I,n[3]=0,n[4]=f-y,n[5]=1-(c+v),n[6]=d+h,n[7]=0,n[8]=p+I,n[9]=d-h,n[10]=1-(c+A),n[11]=0,n[12]=t[0],n[13]=t[1],n[14]=t[2],n[15]=1,n},mat4ToEuler:function(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:Z.vec4(),r=Z.clamp,i=e[0],a=e[4],s=e[8],o=e[1],l=e[5],u=e[9],c=e[2],f=e[6],p=e[10];return"XYZ"===t?(n[1]=Math.asin(r(s,-1,1)),Math.abs(s)<.99999?(n[0]=Math.atan2(-u,p),n[2]=Math.atan2(-a,i)):(n[0]=Math.atan2(f,l),n[2]=0)):"YXZ"===t?(n[0]=Math.asin(-r(u,-1,1)),Math.abs(u)<.99999?(n[1]=Math.atan2(s,p),n[2]=Math.atan2(o,l)):(n[1]=Math.atan2(-c,i),n[2]=0)):"ZXY"===t?(n[0]=Math.asin(r(f,-1,1)),Math.abs(f)<.99999?(n[1]=Math.atan2(-c,p),n[2]=Math.atan2(-a,l)):(n[1]=0,n[2]=Math.atan2(o,i))):"ZYX"===t?(n[1]=Math.asin(-r(c,-1,1)),Math.abs(c)<.99999?(n[0]=Math.atan2(f,p),n[2]=Math.atan2(o,i)):(n[0]=0,n[2]=Math.atan2(-a,l))):"YZX"===t?(n[2]=Math.asin(r(o,-1,1)),Math.abs(o)<.99999?(n[0]=Math.atan2(-u,l),n[1]=Math.atan2(-c,i)):(n[0]=0,n[1]=Math.atan2(s,p))):"XZY"===t&&(n[2]=Math.asin(-r(a,-1,1)),Math.abs(a)<.99999?(n[0]=Math.atan2(f,l),n[1]=Math.atan2(s,i)):(n[0]=Math.atan2(-u,p),n[1]=0)),n},composeMat4:function(e,t,n){var r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:Z.mat4();return Z.quaternionToRotationMat4(t,r),Z.scaleMat4v(n,r),Z.translateMat4v(e,r),r},decomposeMat4:function(){var e=new Y(3),t=new Y(16);return function(n,r,i,a){e[0]=n[0],e[1]=n[1],e[2]=n[2];var s=Z.lenVec3(e);e[0]=n[4],e[1]=n[5],e[2]=n[6];var o=Z.lenVec3(e);e[8]=n[8],e[9]=n[9],e[10]=n[10];var l=Z.lenVec3(e);Z.determinantMat4(n)<0&&(s=-s),r[0]=n[12],r[1]=n[13],r[2]=n[14],t.set(n);var u=1/s,c=1/o,f=1/l;return t[0]*=u,t[1]*=u,t[2]*=u,t[4]*=c,t[5]*=c,t[6]*=c,t[8]*=f,t[9]*=f,t[10]*=f,Z.mat4ToQuaternion(t,i),a[0]=s,a[1]=o,a[2]=l,this}}(),getColMat4:function(e,t){var n=4*t;return[e[n],e[n+1],e[n+2],e[n+3]]},setRowMat4:function(e,t,n){e[t]=n[0],e[t+4]=n[1],e[t+8]=n[2],e[t+12]=n[3]},lookAtMat4v:function(e,t,n,r){r||(r=Z.mat4());var i,a,s,o,l,u,c,f,p,A,d=e[0],v=e[1],h=e[2],I=n[0],y=n[1],m=n[2],w=t[0],g=t[1],T=t[2];return d===w&&v===g&&h===T?Z.identityMat4():(i=d-w,a=v-g,s=h-T,o=y*(s*=A=1/Math.sqrt(i*i+a*a+s*s))-m*(a*=A),l=m*(i*=A)-I*s,u=I*a-y*i,(A=Math.sqrt(o*o+l*l+u*u))?(o*=A=1/A,l*=A,u*=A):(o=0,l=0,u=0),c=a*u-s*l,f=s*o-i*u,p=i*l-a*o,(A=Math.sqrt(c*c+f*f+p*p))?(c*=A=1/A,f*=A,p*=A):(c=0,f=0,p=0),r[0]=o,r[1]=c,r[2]=i,r[3]=0,r[4]=l,r[5]=f,r[6]=a,r[7]=0,r[8]=u,r[9]=p,r[10]=s,r[11]=0,r[12]=-(o*d+l*v+u*h),r[13]=-(c*d+f*v+p*h),r[14]=-(i*d+a*v+s*h),r[15]=1,r)},lookAtMat4c:function(e,t,n,r,i,a,s,o,l){return Z.lookAtMat4v([e,t,n],[r,i,a],[s,o,l],[])},orthoMat4c:function(e,t,n,r,i,a,s){s||(s=Z.mat4());var o=t-e,l=r-n,u=a-i;return s[0]=2/o,s[1]=0,s[2]=0,s[3]=0,s[4]=0,s[5]=2/l,s[6]=0,s[7]=0,s[8]=0,s[9]=0,s[10]=-2/u,s[11]=0,s[12]=-(e+t)/o,s[13]=-(r+n)/l,s[14]=-(a+i)/u,s[15]=1,s},frustumMat4v:function(e,t,n){n||(n=Z.mat4());var r=[e[0],e[1],e[2],0],i=[t[0],t[1],t[2],0];Z.addVec4(i,r,X),Z.subVec4(i,r,q);var a=2*r[2],s=q[0],o=q[1],l=q[2];return n[0]=a/s,n[1]=0,n[2]=0,n[3]=0,n[4]=0,n[5]=a/o,n[6]=0,n[7]=0,n[8]=X[0]/s,n[9]=X[1]/o,n[10]=-X[2]/l,n[11]=-1,n[12]=0,n[13]=0,n[14]=-a*i[2]/l,n[15]=0,n},frustumMat4:function(e,t,n,r,i,a,s){s||(s=Z.mat4());var o=t-e,l=r-n,u=a-i;return s[0]=2*i/o,s[1]=0,s[2]=0,s[3]=0,s[4]=0,s[5]=2*i/l,s[6]=0,s[7]=0,s[8]=(t+e)/o,s[9]=(r+n)/l,s[10]=-(a+i)/u,s[11]=-1,s[12]=0,s[13]=0,s[14]=-a*i*2/u,s[15]=0,s},perspectiveMat4:function(e,t,n,r,i){var a=[],s=[];return a[2]=n,s[2]=r,s[1]=a[2]*Math.tan(e/2),a[1]=-s[1],s[0]=s[1]*t,a[0]=-s[0],Z.frustumMat4v(a,s,i)},compareMat4:function(e,t){return e[0]===t[0]&&e[1]===t[1]&&e[2]===t[2]&&e[3]===t[3]&&e[4]===t[4]&&e[5]===t[5]&&e[6]===t[6]&&e[7]===t[7]&&e[8]===t[8]&&e[9]===t[9]&&e[10]===t[10]&&e[11]===t[11]&&e[12]===t[12]&&e[13]===t[13]&&e[14]===t[14]&&e[15]===t[15]},transformPoint3:function(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:Z.vec3(),r=t[0],i=t[1],a=t[2];return n[0]=e[0]*r+e[4]*i+e[8]*a+e[12],n[1]=e[1]*r+e[5]*i+e[9]*a+e[13],n[2]=e[2]*r+e[6]*i+e[10]*a+e[14],n},transformPoint4:function(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:Z.vec4();return n[0]=e[0]*t[0]+e[4]*t[1]+e[8]*t[2]+e[12]*t[3],n[1]=e[1]*t[0]+e[5]*t[1]+e[9]*t[2]+e[13]*t[3],n[2]=e[2]*t[0]+e[6]*t[1]+e[10]*t[2]+e[14]*t[3],n[3]=e[3]*t[0]+e[7]*t[1]+e[11]*t[2]+e[15]*t[3],n},transformPoints3:function(e,t,n){for(var r,i,a,s,o,l=n||[],u=t.length,c=e[0],f=e[1],p=e[2],A=e[3],d=e[4],v=e[5],h=e[6],I=e[7],y=e[8],m=e[9],w=e[10],g=e[11],T=e[12],E=e[13],b=e[14],D=e[15],P=0;P<u;++P)r=(s=t[P])[0],i=s[1],a=s[2],(o=l[P]||(l[P]=[0,0,0]))[0]=c*r+d*i+y*a+T,o[1]=f*r+v*i+m*a+E,o[2]=p*r+h*i+w*a+b,o[3]=A*r+I*i+g*a+D;return l.length=u,l},transformPositions3:function(e,t){var n,r,i,a,s=arguments.length>2&&void 0!==arguments[2]?arguments[2]:t,o=t.length,l=e[0],u=e[1],c=e[2];e[3];var f=e[4],p=e[5],A=e[6];e[7];var d=e[8],v=e[9],h=e[10];e[11];var I=e[12],y=e[13],m=e[14];for(e[15],n=0;n<o;n+=3)r=t[n+0],i=t[n+1],a=t[n+2],s[n+0]=l*r+f*i+d*a+I,s[n+1]=u*r+p*i+v*a+y,s[n+2]=c*r+A*i+h*a+m;return s},transformPositions4:function(e,t){var n,r,i,a,s=arguments.length>2&&void 0!==arguments[2]?arguments[2]:t,o=t.length,l=e[0],u=e[1],c=e[2],f=e[3],p=e[4],A=e[5],d=e[6],v=e[7],h=e[8],I=e[9],y=e[10],m=e[11],w=e[12],g=e[13],T=e[14],E=e[15];for(n=0;n<o;n+=4)r=t[n+0],i=t[n+1],a=t[n+2],s[n+0]=l*r+p*i+h*a+w,s[n+1]=u*r+A*i+I*a+g,s[n+2]=c*r+d*i+y*a+T,s[n+3]=f*r+v*i+m*a+E;return s},transformVec3:function(e,t,n){var r=t[0],i=t[1],a=t[2];return(n=n||this.vec3())[0]=e[0]*r+e[4]*i+e[8]*a,n[1]=e[1]*r+e[5]*i+e[9]*a,n[2]=e[2]*r+e[6]*i+e[10]*a,n},transformVec4:function(e,t,n){var r=t[0],i=t[1],a=t[2],s=t[3];return(n=n||Z.vec4())[0]=e[0]*r+e[4]*i+e[8]*a+e[12]*s,n[1]=e[1]*r+e[5]*i+e[9]*a+e[13]*s,n[2]=e[2]*r+e[6]*i+e[10]*a+e[14]*s,n[3]=e[3]*r+e[7]*i+e[11]*a+e[15]*s,n},rotateVec2:function(e,t,n){var r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:e,i=Math.cos(n),a=Math.sin(n),s=e[0]-t[0],o=e[1]-t[1];return r[0]=s*i-o*a+t[0],r[1]=s*a+o*i+t[1],e},rotateVec3X:function(e,t,n,r){var i=[],a=[];return i[0]=e[0]-t[0],i[1]=e[1]-t[1],i[2]=e[2]-t[2],a[0]=i[0],a[1]=i[1]*Math.cos(n)-i[2]*Math.sin(n),a[2]=i[1]*Math.sin(n)+i[2]*Math.cos(n),r[0]=a[0]+t[0],r[1]=a[1]+t[1],r[2]=a[2]+t[2],r},rotateVec3Y:function(e,t,n,r){var i=[],a=[];return i[0]=e[0]-t[0],i[1]=e[1]-t[1],i[2]=e[2]-t[2],a[0]=i[2]*Math.sin(n)+i[0]*Math.cos(n),a[1]=i[1],a[2]=i[2]*Math.cos(n)-i[0]*Math.sin(n),r[0]=a[0]+t[0],r[1]=a[1]+t[1],r[2]=a[2]+t[2],r},rotateVec3Z:function(e,t,n,r){var i=[],a=[];return i[0]=e[0]-t[0],i[1]=e[1]-t[1],i[2]=e[2]-t[2],a[0]=i[0]*Math.cos(n)-i[1]*Math.sin(n),a[1]=i[0]*Math.sin(n)+i[1]*Math.cos(n),a[2]=i[2],r[0]=a[0]+t[0],r[1]=a[1]+t[1],r[2]=a[2]+t[2],r},projectVec4:function(e,t){var n=1/e[3];return(t=t||Z.vec2())[0]=e[0]*n,t[1]=e[1]*n,t},unprojectVec3:(x=new Y(16),M=new Y(16),F=new Y(16),function(e,t,n,r){return this.transformVec3(this.mulMat4(this.inverseMat4(t,x),this.inverseMat4(n,M),F),e,r)}),lerpVec3:function(e,t,n,r,i,a){var s=a||Z.vec3(),o=(e-t)/(n-t);return s[0]=r[0]+o*(i[0]-r[0]),s[1]=r[1]+o*(i[1]-r[1]),s[2]=r[2]+o*(i[2]-r[2]),s},lerpMat4:function(e,t,n,r,i,a){var s=a||Z.mat4(),o=(e-t)/(n-t);return s[0]=r[0]+o*(i[0]-r[0]),s[1]=r[1]+o*(i[1]-r[1]),s[2]=r[2]+o*(i[2]-r[2]),s[3]=r[3]+o*(i[3]-r[3]),s[4]=r[4]+o*(i[4]-r[4]),s[5]=r[5]+o*(i[5]-r[5]),s[6]=r[6]+o*(i[6]-r[6]),s[7]=r[7]+o*(i[7]-r[7]),s[8]=r[8]+o*(i[8]-r[8]),s[9]=r[9]+o*(i[9]-r[9]),s[10]=r[10]+o*(i[10]-r[10]),s[11]=r[11]+o*(i[11]-r[11]),s[12]=r[12]+o*(i[12]-r[12]),s[13]=r[13]+o*(i[13]-r[13]),s[14]=r[14]+o*(i[14]-r[14]),s[15]=r[15]+o*(i[15]-r[15]),s},flatten:function(e){var t,n,r,i,a,s=[];for(t=0,n=e.length;t<n;t++)for(r=0,i=(a=e[t]).length;r<i;r++)s.push(a[r]);return s},identityQuaternion:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:Z.vec4();return e[0]=0,e[1]=0,e[2]=0,e[3]=1,e},eulerToQuaternion:function(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:Z.vec4(),r=e[0]*Z.DEGTORAD/2,i=e[1]*Z.DEGTORAD/2,a=e[2]*Z.DEGTORAD/2,s=Math.cos(r),o=Math.cos(i),l=Math.cos(a),u=Math.sin(r),c=Math.sin(i),f=Math.sin(a);return"XYZ"===t?(n[0]=u*o*l+s*c*f,n[1]=s*c*l-u*o*f,n[2]=s*o*f+u*c*l,n[3]=s*o*l-u*c*f):"YXZ"===t?(n[0]=u*o*l+s*c*f,n[1]=s*c*l-u*o*f,n[2]=s*o*f-u*c*l,n[3]=s*o*l+u*c*f):"ZXY"===t?(n[0]=u*o*l-s*c*f,n[1]=s*c*l+u*o*f,n[2]=s*o*f+u*c*l,n[3]=s*o*l-u*c*f):"ZYX"===t?(n[0]=u*o*l-s*c*f,n[1]=s*c*l+u*o*f,n[2]=s*o*f-u*c*l,n[3]=s*o*l+u*c*f):"YZX"===t?(n[0]=u*o*l+s*c*f,n[1]=s*c*l+u*o*f,n[2]=s*o*f-u*c*l,n[3]=s*o*l-u*c*f):"XZY"===t&&(n[0]=u*o*l-s*c*f,n[1]=s*c*l-u*o*f,n[2]=s*o*f+u*c*l,n[3]=s*o*l+u*c*f),n},mat4ToQuaternion:function(e){var t,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Z.vec4(),r=e[0],i=e[4],a=e[8],s=e[1],o=e[5],l=e[9],u=e[2],c=e[6],f=e[10],p=r+o+f;return p>0?(t=.5/Math.sqrt(p+1),n[3]=.25/t,n[0]=(c-l)*t,n[1]=(a-u)*t,n[2]=(s-i)*t):r>o&&r>f?(t=2*Math.sqrt(1+r-o-f),n[3]=(c-l)/t,n[0]=.25*t,n[1]=(i+s)/t,n[2]=(a+u)/t):o>f?(t=2*Math.sqrt(1+o-r-f),n[3]=(a-u)/t,n[0]=(i+s)/t,n[1]=.25*t,n[2]=(l+c)/t):(t=2*Math.sqrt(1+f-r-o),n[3]=(s-i)/t,n[0]=(a+u)/t,n[1]=(l+c)/t,n[2]=.25*t),n},vec3PairToQuaternion:function(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:Z.vec4(),r=Math.sqrt(Z.dotVec3(e,e)*Z.dotVec3(t,t)),i=r+Z.dotVec3(e,t);return i<1e-8*r?(i=0,Math.abs(e[0])>Math.abs(e[2])?(n[0]=-e[1],n[1]=e[0],n[2]=0):(n[0]=0,n[1]=-e[2],n[2]=e[1])):Z.cross3Vec3(e,t,n),n[3]=i,Z.normalizeQuaternion(n)},angleAxisToQuaternion:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Z.vec4(),n=e[3]/2,r=Math.sin(n);return t[0]=r*e[0],t[1]=r*e[1],t[2]=r*e[2],t[3]=Math.cos(n),t},quaternionToEuler:function(){var e=new Y(16);return function(t,n,r){return r=r||Z.vec3(),Z.quaternionToRotationMat4(t,e),Z.mat4ToEuler(e,n,r),r}}(),mulQuaternions:function(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:Z.vec4(),r=e[0],i=e[1],a=e[2],s=e[3],o=t[0],l=t[1],u=t[2],c=t[3];return n[0]=s*o+r*c+i*u-a*l,n[1]=s*l+i*c+a*o-r*u,n[2]=s*u+a*c+r*l-i*o,n[3]=s*c-r*o-i*l-a*u,n},vec3ApplyQuaternion:function(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:Z.vec3(),r=t[0],i=t[1],a=t[2],s=e[0],o=e[1],l=e[2],u=e[3],c=u*r+o*a-l*i,f=u*i+l*r-s*a,p=u*a+s*i-o*r,A=-s*r-o*i-l*a;return n[0]=c*u+A*-s+f*-l-p*-o,n[1]=f*u+A*-o+p*-s-c*-l,n[2]=p*u+A*-l+c*-o-f*-s,n},quaternionToMat4:function(e,t){t=Z.identityMat4(t);var n=e[0],r=e[1],i=e[2],a=e[3],s=2*n,o=2*r,l=2*i,u=s*a,c=o*a,f=l*a,p=s*n,A=o*n,d=l*n,v=o*r,h=l*r,I=l*i;return t[0]=1-(v+I),t[1]=A+f,t[2]=d-c,t[4]=A-f,t[5]=1-(p+I),t[6]=h+u,t[8]=d+c,t[9]=h-u,t[10]=1-(p+v),t},quaternionToRotationMat4:function(e,t){var n=e[0],r=e[1],i=e[2],a=e[3],s=n+n,o=r+r,l=i+i,u=n*s,c=n*o,f=n*l,p=r*o,A=r*l,d=i*l,v=a*s,h=a*o,I=a*l;return t[0]=1-(p+d),t[4]=c-I,t[8]=f+h,t[1]=c+I,t[5]=1-(u+d),t[9]=A-v,t[2]=f-h,t[6]=A+v,t[10]=1-(u+p),t[3]=0,t[7]=0,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t},normalizeQuaternion:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:e,n=Z.lenVec4([e[0],e[1],e[2],e[3]]);return t[0]=e[0]/n,t[1]=e[1]/n,t[2]=e[2]/n,t[3]=e[3]/n,t},conjugateQuaternion:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:e;return t[0]=-e[0],t[1]=-e[1],t[2]=-e[2],t[3]=e[3],t},inverseQuaternion:function(e,t){return Z.normalizeQuaternion(Z.conjugateQuaternion(e,t))},quaternionToAngleAxis:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Z.vec4(),n=(e=Z.normalizeQuaternion(e,J))[3],r=2*Math.acos(n),i=Math.sqrt(1-n*n);return i<.001?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=e[0]/i,t[1]=e[1]/i,t[2]=e[2]/i),t[3]=r,t},AABB3:function(e){return new Y(e||6)},AABB2:function(e){return new Y(e||4)},OBB3:function(e){return new Y(e||32)},OBB2:function(e){return new Y(e||16)},Sphere3:function(e,t,n,r){return new Y([e,t,n,r])},transformOBB3:function(e,t){var n,r,i,a,s=arguments.length>2&&void 0!==arguments[2]?arguments[2]:t,o=t.length,l=e[0],u=e[1],c=e[2],f=e[3],p=e[4],A=e[5],d=e[6],v=e[7],h=e[8],I=e[9],y=e[10],m=e[11],w=e[12],g=e[13],T=e[14],E=e[15];for(n=0;n<o;n+=4)r=t[n+0],i=t[n+1],a=t[n+2],s[n+0]=l*r+p*i+h*a+w,s[n+1]=u*r+A*i+I*a+g,s[n+2]=c*r+d*i+y*a+T,s[n+3]=f*r+v*i+m*a+E;return s},containsAABB3:function(e,t){return e[0]<=t[0]&&t[3]<=e[3]&&e[1]<=t[1]&&t[4]<=e[4]&&e[2]<=t[2]&&t[5]<=e[5]},getAABB3Diag:function(){var e=new Y(3),t=new Y(3),n=new Y(3);return function(r){return e[0]=r[0],e[1]=r[1],e[2]=r[2],t[0]=r[3],t[1]=r[4],t[2]=r[5],Z.subVec3(t,e,n),Math.abs(Z.lenVec3(n))}}(),getAABB3DiagPoint:function(){var e=new Y(3),t=new Y(3),n=new Y(3);return function(r,i){e[0]=r[0],e[1]=r[1],e[2]=r[2],t[0]=r[3],t[1]=r[4],t[2]=r[5];var a=Z.subVec3(t,e,n),s=i[0]-r[0],o=r[3]-i[0],l=i[1]-r[1],u=r[4]-i[1],c=i[2]-r[2],f=r[5]-i[2];return a[0]+=s>o?s:o,a[1]+=l>u?l:u,a[2]+=c>f?c:f,Math.abs(Z.lenVec3(a))}}(),getAABB3Area:function(e){return(e[3]-e[0])*(e[4]-e[1])*(e[5]-e[2])},getAABB3Center:function(e,t){var n=t||Z.vec3();return n[0]=(e[0]+e[3])/2,n[1]=(e[1]+e[4])/2,n[2]=(e[2]+e[5])/2,n},getAABB2Center:function(e,t){var n=t||Z.vec2();return n[0]=(e[2]+e[0])/2,n[1]=(e[3]+e[1])/2,n},collapseAABB3:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:Z.AABB3();return e[0]=Z.MAX_DOUBLE,e[1]=Z.MAX_DOUBLE,e[2]=Z.MAX_DOUBLE,e[3]=Z.MIN_DOUBLE,e[4]=Z.MIN_DOUBLE,e[5]=Z.MIN_DOUBLE,e},AABB3ToOBB3:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Z.OBB3();return t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=1,t[4]=e[3],t[5]=e[1],t[6]=e[2],t[7]=1,t[8]=e[3],t[9]=e[4],t[10]=e[2],t[11]=1,t[12]=e[0],t[13]=e[4],t[14]=e[2],t[15]=1,t[16]=e[0],t[17]=e[1],t[18]=e[5],t[19]=1,t[20]=e[3],t[21]=e[1],t[22]=e[5],t[23]=1,t[24]=e[3],t[25]=e[4],t[26]=e[5],t[27]=1,t[28]=e[0],t[29]=e[4],t[30]=e[5],t[31]=1,t},positions3ToAABB3:function(){var e=new Y(3);return function(t,n,r){n=n||Z.AABB3();for(var i,a,s,o=Z.MAX_DOUBLE,l=Z.MAX_DOUBLE,u=Z.MAX_DOUBLE,c=Z.MIN_DOUBLE,f=Z.MIN_DOUBLE,p=Z.MIN_DOUBLE,A=0,d=t.length;A<d;A+=3)r?(e[0]=t[A+0],e[1]=t[A+1],e[2]=t[A+2],Z.decompressPosition(e,r,e),i=e[0],a=e[1],s=e[2]):(i=t[A+0],a=t[A+1],s=t[A+2]),i<o&&(o=i),a<l&&(l=a),s<u&&(u=s),i>c&&(c=i),a>f&&(f=a),s>p&&(p=s);return n[0]=o,n[1]=l,n[2]=u,n[3]=c,n[4]=f,n[5]=p,n}}(),OBB3ToAABB3:function(e){for(var t,n,r,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Z.AABB3(),a=Z.MAX_DOUBLE,s=Z.MAX_DOUBLE,o=Z.MAX_DOUBLE,l=Z.MIN_DOUBLE,u=Z.MIN_DOUBLE,c=Z.MIN_DOUBLE,f=0,p=e.length;f<p;f+=4)(t=e[f+0])<a&&(a=t),(n=e[f+1])<s&&(s=n),(r=e[f+2])<o&&(o=r),t>l&&(l=t),n>u&&(u=n),r>c&&(c=r);return i[0]=a,i[1]=s,i[2]=o,i[3]=l,i[4]=u,i[5]=c,i},points3ToAABB3:function(e){for(var t,n,r,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Z.AABB3(),a=Z.MAX_DOUBLE,s=Z.MAX_DOUBLE,o=Z.MAX_DOUBLE,l=Z.MIN_DOUBLE,u=Z.MIN_DOUBLE,c=Z.MIN_DOUBLE,f=0,p=e.length;f<p;f++)(t=e[f][0])<a&&(a=t),(n=e[f][1])<s&&(s=n),(r=e[f][2])<o&&(o=r),t>l&&(l=t),n>u&&(u=n),r>c&&(c=r);return i[0]=a,i[1]=s,i[2]=o,i[3]=l,i[4]=u,i[5]=c,i},points3ToSphere3:function(){var e=new Y(3);return function(t,n){n=n||Z.vec4();var r,i=0,a=0,s=0,o=t.length;for(r=0;r<o;r++)i+=t[r][0],a+=t[r][1],s+=t[r][2];n[0]=i/o,n[1]=a/o,n[2]=s/o;var l,u=0;for(r=0;r<o;r++)(l=Math.abs(Z.lenVec3(Z.subVec3(t[r],n,e))))>u&&(u=l);return n[3]=u,n}}(),positions3ToSphere3:function(){var e=new Y(3),t=new Y(3);return function(n,r){r=r||Z.vec4();var i,a=0,s=0,o=0,l=n.length,u=0;for(i=0;i<l;i+=3)a+=n[i],s+=n[i+1],o+=n[i+2];var c,f=l/3;for(r[0]=a/f,r[1]=s/f,r[2]=o/f,i=0;i<l;i+=3)e[0]=n[i],e[1]=n[i+1],e[2]=n[i+2],(c=Math.abs(Z.lenVec3(Z.subVec3(e,r,t))))>u&&(u=c);return r[3]=u,r}}(),OBB3ToSphere3:function(){var e=new Y(3),t=new Y(3);return function(n,r){r=r||Z.vec4();var i,a=0,s=0,o=0,l=n.length,u=l/4;for(i=0;i<l;i+=4)a+=n[i+0],s+=n[i+1],o+=n[i+2];r[0]=a/u,r[1]=s/u,r[2]=o/u;var c,f=0;for(i=0;i<l;i+=4)e[0]=n[i+0],e[1]=n[i+1],e[2]=n[i+2],(c=Math.abs(Z.lenVec3(Z.subVec3(e,r,t))))>f&&(f=c);return r[3]=f,r}}(),getSphere3Center:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Z.vec3();return t[0]=e[0],t[1]=e[1],t[2]=e[2],t},getPositionsCenter:function(e){for(var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Z.vec3(),n=0,r=0,i=0,a=0,s=e.length;a<s;a+=3)n+=e[a+0],r+=e[a+1],i+=e[a+2];var o=e.length/3;return t[0]=n/o,t[1]=r/o,t[2]=i/o,t},expandAABB3:function(e,t){return e[0]>t[0]&&(e[0]=t[0]),e[1]>t[1]&&(e[1]=t[1]),e[2]>t[2]&&(e[2]=t[2]),e[3]<t[3]&&(e[3]=t[3]),e[4]<t[4]&&(e[4]=t[4]),e[5]<t[5]&&(e[5]=t[5]),e},expandAABB3Point3:function(e,t){return e[0]>t[0]&&(e[0]=t[0]),e[1]>t[1]&&(e[1]=t[1]),e[2]>t[2]&&(e[2]=t[2]),e[3]<t[0]&&(e[3]=t[0]),e[4]<t[1]&&(e[4]=t[1]),e[5]<t[2]&&(e[5]=t[2]),e},expandAABB3Points3:function(e,t){for(var n,r,i,a=0,s=t.length;a<s;a+=3)n=t[a],r=t[a+1],i=t[a+2],e[0]>n&&(e[0]=n),e[1]>r&&(e[1]=r),e[2]>i&&(e[2]=i),e[3]<n&&(e[3]=n),e[4]<r&&(e[4]=r),e[5]<i&&(e[5]=i);return e},collapseAABB2:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:Z.AABB2();return e[0]=Z.MAX_DOUBLE,e[1]=Z.MAX_DOUBLE,e[2]=Z.MIN_DOUBLE,e[3]=Z.MIN_DOUBLE,e},point3AABB3Intersect:function(e,t){return e[0]>t[0]||e[3]<t[0]||e[1]>t[1]||e[4]<t[1]||e[2]>t[2]||e[5]<t[2]},planeAABB3Intersect:function(e,t,n){var r,i;return e[0]>0?(r=e[0]*n[0],i=e[0]*n[3]):(r=e[0]*n[3],i=e[0]*n[0]),e[1]>0?(r+=e[1]*n[1],i+=e[1]*n[4]):(r+=e[1]*n[4],i+=e[1]*n[1]),e[2]>0?(r+=e[2]*n[2],i+=e[2]*n[5]):(r+=e[2]*n[5],i+=e[2]*n[2]),r<=-t&&i<=-t?-1:r>=-t&&i>=-t?1:0},OBB3ToAABB2:function(e){for(var t,n,r,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Z.AABB2(),a=Z.MAX_DOUBLE,s=Z.MAX_DOUBLE,o=Z.MIN_DOUBLE,l=Z.MIN_DOUBLE,u=0,c=e.length;u<c;u+=4)t=e[u+0],n=e[u+1],(t*=r=1/(e[u+3]||1))<a&&(a=t),(n*=r)<s&&(s=n),t>o&&(o=t),n>l&&(l=n);return i[0]=a,i[1]=s,i[2]=o,i[3]=l,i},expandAABB2:function(e,t){return e[0]>t[0]&&(e[0]=t[0]),e[1]>t[1]&&(e[1]=t[1]),e[2]<t[2]&&(e[2]=t[2]),e[3]<t[3]&&(e[3]=t[3]),e},expandAABB2Point2:function(e,t){return e[0]>t[0]&&(e[0]=t[0]),e[1]>t[1]&&(e[1]=t[1]),e[2]<t[0]&&(e[2]=t[0]),e[3]<t[1]&&(e[3]=t[1]),e},AABB2ToCanvas:function(e,t,n){var r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:e,i=.5*(e[0]+1),a=.5*(e[1]+1),s=.5*(e[2]+1),o=.5*(e[3]+1);return r[0]=Math.floor(i*t),r[1]=n-Math.floor(o*n),r[2]=Math.floor(s*t),r[3]=n-Math.floor(a*n),r},tangentQuadraticBezier:function(e,t,n,r){return 2*(1-e)*(n-t)+2*e*(r-n)},tangentQuadraticBezier3:function(e,t,n,r,i){return-3*t*(1-e)*(1-e)+3*n*(1-e)*(1-e)-6*e*n*(1-e)+6*e*r*(1-e)-3*e*e*r+3*e*e*i},tangentSpline:function(e){return 6*e*e-6*e+(3*e*e-4*e+1)+(-6*e*e+6*e)+(3*e*e-2*e)},catmullRomInterpolate:function(e,t,n,r,i){var a=.5*(n-e),s=.5*(r-t),o=i*i;return(2*t-2*n+a+s)*(i*o)+(-3*t+3*n-2*a-s)*o+a*i+t},b2p0:function(e,t){var n=1-e;return n*n*t},b2p1:function(e,t){return 2*(1-e)*e*t},b2p2:function(e,t){return e*e*t},b2:function(e,t,n,r){return this.b2p0(e,t)+this.b2p1(e,n)+this.b2p2(e,r)},b3p0:function(e,t){var n=1-e;return n*n*n*t},b3p1:function(e,t){var n=1-e;return 3*n*n*e*t},b3p2:function(e,t){return 3*(1-e)*e*e*t},b3p3:function(e,t){return e*e*e*t},b3:function(e,t,n,r,i){return this.b3p0(e,t)+this.b3p1(e,n)+this.b3p2(e,r)+this.b3p3(e,i)},triangleNormal:function(e,t,n){var r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:Z.vec3(),i=t[0]-e[0],a=t[1]-e[1],s=t[2]-e[2],o=n[0]-e[0],l=n[1]-e[1],u=n[2]-e[2],c=a*u-s*l,f=s*o-i*u,p=i*l-a*o,A=Math.sqrt(c*c+f*f+p*p);return 0===A?(r[0]=0,r[1]=0,r[2]=0):(r[0]=c/A,r[1]=f/A,r[2]=p/A),r},rayTriangleIntersect:function(){var e=new Y(3),t=new Y(3),n=new Y(3),r=new Y(3),i=new Y(3);return function(a,s,o,l,u,c){c=c||Z.vec3();var f=Z.subVec3(l,o,e),p=Z.subVec3(u,o,t),A=Z.cross3Vec3(s,p,n),d=Z.dotVec3(f,A);if(d<1e-6)return null;var v=Z.subVec3(a,o,r),h=Z.dotVec3(v,A);if(h<0||h>d)return null;var I=Z.cross3Vec3(v,f,i),y=Z.dotVec3(s,I);if(y<0||h+y>d)return null;var m=Z.dotVec3(p,I)/d;return c[0]=a[0]+m*s[0],c[1]=a[1]+m*s[1],c[2]=a[2]+m*s[2],c}}(),rayPlaneIntersect:function(){var e=new Y(3),t=new Y(3),n=new Y(3),r=new Y(3);return function(i,a,s,o,l,u){u=u||Z.vec3(),a=Z.normalizeVec3(a,e);var c=Z.subVec3(o,s,t),f=Z.subVec3(l,s,n),p=Z.cross3Vec3(c,f,r);Z.normalizeVec3(p,p);var A=-Z.dotVec3(s,p),d=-(Z.dotVec3(i,p)+A)/Z.dotVec3(a,p);return u[0]=i[0]+d*a[0],u[1]=i[1]+d*a[1],u[2]=i[2]+d*a[2],u}}(),cartesianToBarycentric:function(){var e=new Y(3),t=new Y(3),n=new Y(3);return function(r,i,a,s,o){var l=Z.subVec3(s,i,e),u=Z.subVec3(a,i,t),c=Z.subVec3(r,i,n),f=Z.dotVec3(l,l),p=Z.dotVec3(l,u),A=Z.dotVec3(l,c),d=Z.dotVec3(u,u),v=Z.dotVec3(u,c),h=f*d-p*p;if(0===h)return null;var I=1/h,y=(d*A-p*v)*I,m=(f*v-p*A)*I;return o[0]=1-y-m,o[1]=m,o[2]=y,o}}(),barycentricInsideTriangle:function(e){var t=e[1],n=e[2];return n>=0&&t>=0&&n+t<1},barycentricToCartesian:function(e,t,n,r){var i=arguments.length>4&&void 0!==arguments[4]?arguments[4]:Z.vec3(),a=e[0],s=e[1],o=e[2];return i[0]=t[0]*a+n[0]*s+r[0]*o,i[1]=t[1]*a+n[1]*s+r[1]*o,i[2]=t[2]*a+n[2]*s+r[2]*o,i},mergeVertices:function(e,t,n,r){var i,a,s,o,l,u,c={},f=[],p=[],A=t?[]:null,d=n?[]:null,v=[],h=Math.pow(10,4),I=0;for(l=0,u=e.length;l<u;l+=3)i=e[l],a=e[l+1],s=e[l+2],void 0===c[o="".concat(Math.round(i*h),"_").concat(Math.round(a*h),"_").concat(Math.round(s*h))]&&(c[o]=p.length/3,p.push(i),p.push(a),p.push(s),t&&(A.push(t[l]),A.push(t[l+1]),A.push(t[l+2])),n&&(d.push(n[I]),d.push(n[I+1]))),f[l/3]=c[o],I+=2;for(l=0,u=r.length;l<u;l++)v[l]=f[r[l]];var y={positions:p,indices:v};return A&&(y.normals=A),d&&(y.uv=d),y},buildNormals:function(){var e=new Y(3),t=new Y(3),n=new Y(3),r=new Y(3),i=new Y(3),a=new Y(3);return function(s,o,l){var u,c,f,p,A,d,v,h,I,y=new Array(s.length/3);for(u=0,c=o.length;u<c;u+=3){f=o[u],p=o[u+1],A=o[u+2],e[0]=s[3*f],e[1]=s[3*f+1],e[2]=s[3*f+2],t[0]=s[3*p],t[1]=s[3*p+1],t[2]=s[3*p+2],n[0]=s[3*A],n[1]=s[3*A+1],n[2]=s[3*A+2],Z.subVec3(t,e,r),Z.subVec3(n,e,i);var m=Z.vec3();Z.normalizeVec3(Z.cross3Vec3(r,i,a),m),y[f]||(y[f]=[]),y[p]||(y[p]=[]),y[A]||(y[A]=[]),y[f].push(m),y[p].push(m),y[A].push(m)}for(l=l&&l.length===s.length?l:new Float32Array(s.length),u=0,c=y.length;u<c;u++){d=y[u].length,v=0,h=0,I=0;for(var w=0;w<d;w++)v+=y[u][w][0],h+=y[u][w][1],I+=y[u][w][2];l[3*u]=v/d,l[3*u+1]=h/d,l[3*u+2]=I/d}return l}}(),buildTangents:function(){var e=new Y(3),t=new Y(3),n=new Y(3),r=new Y(3),i=new Y(3),a=new Y(3),s=new Y(3);return function(o,l,u){for(var c=new Float32Array(o.length),f=0;f<l.length;f+=3){var p=l[f],A=o.subarray(3*p,3*p+3),d=u.subarray(2*p,2*p+2);p=l[f+1];var v=o.subarray(3*p,3*p+3),h=u.subarray(2*p,2*p+2);p=l[f+2];for(var I=o.subarray(3*p,3*p+3),y=u.subarray(2*p,2*p+2),m=Z.subVec3(v,A,e),w=Z.subVec3(I,A,t),g=Z.subVec2(h,d,n),T=Z.subVec2(y,d,r),E=1/(g[0]*T[1]-g[1]*T[0]),b=Z.mulVec3Scalar(Z.subVec3(Z.mulVec3Scalar(m,T[1],i),Z.mulVec3Scalar(w,g[1],a),s),E,a),D=void 0,P=0;P<3;P++)c[D=3*l[f+P]]+=b[0],c[D+1]+=b[1],c[D+2]+=b[2]}return c}}(),buildPickTriangles:function(e,t,n){for(var r,i,a,s,o,l=t.length,u=n?new Uint16Array(9*l):new Float32Array(9*l),c=new Uint8Array(12*l),f=0,p=0,A=0,d=0;d<l;d+=3)o=f>>24&255,s=f>>16&255,a=f>>8&255,i=255&f,r=3*t[d],u[p++]=e[r],u[p++]=e[r+1],u[p++]=e[r+2],c[A++]=i,c[A++]=a,c[A++]=s,c[A++]=o,r=3*t[d+1],u[p++]=e[r],u[p++]=e[r+1],u[p++]=e[r+2],c[A++]=i,c[A++]=a,c[A++]=s,c[A++]=o,r=3*t[d+2],u[p++]=e[r],u[p++]=e[r+1],u[p++]=e[r+2],c[A++]=i,c[A++]=a,c[A++]=s,c[A++]=o,f++;return{positions:u,colors:c}},faceToVertexNormals:function(e,t){var n,r,i,a,s,o,l,u,c,f,p,A=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},d=A.smoothNormalsAngleThreshold||20,v={},h=[],I={},y=4,m=Math.pow(10,y);for(l=0,c=e.length;l<c;l+=3){o=l/3,r=e[l],i=e[l+1],a=e[l+2],void 0===v[s="".concat(Math.round(r*m),"_").concat(Math.round(i*m),"_").concat(Math.round(a*m))]?v[s]=[o]:v[s].push(o);var w=Z.normalizeVec3([t[l],t[l+1],t[l+2]]);h[o]=w,n=Z.vec4([w[0],w[1],w[2],1]),I[o]=n}for(s in v)if(v.hasOwnProperty(s)){var g=v[s],T=g.length;for(l=0;l<T;l++){var E=g[l];for(n=I[E],u=0;u<T;u++)if(l!==u){var b=g[u];f=h[E],p=h[b];var D=Math.abs(Z.angleVec3(f,p)/Z.DEGTORAD);D<d&&(n[0]+=p[0],n[1]+=p[1],n[2]+=p[2],n[3]+=1)}}}for(l=0,c=t.length;l<c;l+=3)n=I[l/3],t[l+0]=n[0]/n[3],t[l+1]=n[1]/n[3],t[l+2]=n[2]/n[3]},transformRay:function(){var e=new Y(4),t=new Y(4);return function(n,r,i,a,s){e[0]=r[0],e[1]=r[1],e[2]=r[2],e[3]=1,Z.transformVec4(n,e,t),a[0]=t[0],a[1]=t[1],a[2]=t[2],e[0]=i[0],e[1]=i[1],e[2]=i[2],Z.transformVec3(n,e,t),Z.normalizeVec3(t),s[0]=t[0],s[1]=t[1],s[2]=t[2]}}(),canvasPosToWorldRay:function(){var e=new Y(16),t=new Y(16),n=new Y(4),r=new Y(4),i=new Y(4),a=new Y(4);return function(s,o,l,u,c,f){var p=Z.mulMat4(l,o,e),A=Z.inverseMat4(p,t),d=s.width,v=s.height,h=(u[0]-d/2)/(d/2),I=-(u[1]-v/2)/(v/2);n[0]=h,n[1]=I,n[2]=-1,n[3]=1,Z.transformVec4(A,n,r),Z.mulVec4Scalar(r,1/r[3]),i[0]=h,i[1]=I,i[2]=1,i[3]=1,Z.transformVec4(A,i,a),Z.mulVec4Scalar(a,1/a[3]),c[0]=a[0],c[1]=a[1],c[2]=a[2],Z.subVec3(a,r,f),Z.normalizeVec3(f)}}(),canvasPosToLocalRay:(N=new Y(3),L=new Y(3),function(e,t,n,r,i,a,s){Z.canvasPosToWorldRay(e,t,n,i,N,L),Z.worldRayToLocalRay(r,N,L,a,s)}),worldRayToLocalRay:function(){var e=new Y(16),t=new Y(4),n=new Y(4);return function(r,i,a,s,o){var l=Z.inverseMat4(r,e);t[0]=i[0],t[1]=i[1],t[2]=i[2],t[3]=1,Z.transformVec4(l,t,n),s[0]=n[0],s[1]=n[1],s[2]=n[2],Z.transformVec3(l,a,o)}}(),buildKDTree:function(){var e=new Float32Array;function t(n,r,i,a){var s,o,l=new Y(6),u={triangles:null,left:null,right:null,leaf:!1,splitDim:0,aabb:l};for(l[0]=l[1]=l[2]=Number.POSITIVE_INFINITY,l[3]=l[4]=l[5]=Number.NEGATIVE_INFINITY,s=0,o=n.length;s<o;++s)for(var c=3*n[s],f=0;f<3;++f){var p=3*r[c+f];i[p]<l[0]&&(l[0]=i[p]),i[p]>l[3]&&(l[3]=i[p]),i[p+1]<l[1]&&(l[1]=i[p+1]),i[p+1]>l[4]&&(l[4]=i[p+1]),i[p+2]<l[2]&&(l[2]=i[p+2]),i[p+2]>l[5]&&(l[5]=i[p+2])}if(n.length<20||a>10)return u.triangles=n,u.leaf=!0,u;e[0]=l[3]-l[0],e[1]=l[4]-l[1],e[2]=l[5]-l[2];var A=0;e[1]>e[A]&&(A=1),e[2]>e[A]&&(A=2),u.splitDim=A;var d=(l[A]+l[A+3])/2,v=new Array(n.length),h=0,I=new Array(n.length),y=0;for(s=0,o=n.length;s<o;++s){var m=r[c=3*n[s]],w=3*r[c+1],g=3*r[c+2];i[3*m+A]<=d||i[w+A]<=d||i[g+A]<=d?v[h++]=n[s]:I[y++]=n[s]}return v.length=h,I.length=y,u.left=t(v,r,i,a+1),u.right=t(I,r,i,a+1),u}return function(e,n){for(var r=e.length/3,i=new Array(r),a=0;a<r;++a)i[a]=a;return t(i,e,n,0)}}(),decompressPosition:function(e,t,n){(n=n||e)[0]=e[0]*t[0]+t[12],n[1]=e[1]*t[5]+t[13],n[2]=e[2]*t[10]+t[14]},decompressPositions:function(e,t){for(var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:new Float32Array(e.length),r=0,i=e.length;r<i;r+=3)n[r+0]=e[r+0]*t[0]+t[12],n[r+1]=e[r+1]*t[5]+t[13],n[r+2]=e[r+2]*t[10]+t[14];return n},decompressUV:function(e,t,n){n[0]=e[0]*t[0]+t[6],n[1]=e[1]*t[4]+t[7]},decompressUVs:function(e,t){for(var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:new Float32Array(e.length),r=0,i=e.length;r<i;r+=3)n[r+0]=e[r+0]*t[0]+t[6],n[r+1]=e[r+1]*t[4]+t[7];return n},octDecodeVec2:function(e,t){var n=e[0],r=e[1];n=(2*n+1)/255,r=(2*r+1)/255;var i=1-Math.abs(n)-Math.abs(r);i<0&&(n=(1-Math.abs(r))*(n>=0?1:-1),r=(1-Math.abs(n))*(r>=0?1:-1));var a=Math.sqrt(n*n+r*r+i*i);return t[0]=n/a,t[1]=r/a,t[2]=i/a,t},octDecodeVec2s:function(e,t){for(var n=0,r=0,i=e.length;n<i;n+=2){var a=e[n+0],s=e[n+1];a=(2*a+1)/255,s=(2*s+1)/255;var o=1-Math.abs(a)-Math.abs(s);o<0&&(a=(1-Math.abs(s))*(a>=0?1:-1),s=(1-Math.abs(a))*(s>=0?1:-1));var l=Math.sqrt(a*a+s*s+o*o);t[r+0]=a/l,t[r+1]=s/l,t[r+2]=o/l,r+=3}return t}};Z.buildEdgeIndices=function(){var e=[],t=[],n=[],r=[],i=[],a=0,s=new Uint16Array(3),o=new Uint16Array(3),l=new Uint16Array(3),u=Z.vec3(),c=Z.vec3(),f=Z.vec3(),p=Z.vec3(),A=Z.vec3(),d=Z.vec3(),v=Z.vec3();return function(h,I,y,m){!function(i,a){var s,o,l,u,c,f,p={},A=Math.pow(10,4),d=0;for(c=0,f=i.length;c<f;c+=3)s=i[c],o=i[c+1],l=i[c+2],void 0===p[u=Math.round(s*A)+"_"+Math.round(o*A)+"_"+Math.round(l*A)]&&(p[u]=d/3,e[d++]=s,e[d++]=o,e[d++]=l),t[c/3]=p[u];for(c=0,f=a.length;c<f;c++)r[c]=t[a[c]],n[r[c]]=a[c]}(h,I),function(t,n){a=0;for(var h=0,I=t;h<I;h+=3){var y=3*r[h],m=3*r[h+1],w=3*r[h+2];n?(s[0]=e[y],s[1]=e[y+1],s[2]=e[y+2],o[0]=e[m],o[1]=e[m+1],o[2]=e[m+2],l[0]=e[w],l[1]=e[w+1],l[2]=e[w+2],Z.decompressPosition(s,n,u),Z.decompressPosition(o,n,c),Z.decompressPosition(l,n,f)):(u[0]=e[y],u[1]=e[y+1],u[2]=e[y+2],c[0]=e[m],c[1]=e[m+1],c[2]=e[m+2],f[0]=e[w],f[1]=e[w+1],f[2]=e[w+2]),Z.subVec3(f,c,p),Z.subVec3(u,c,A),Z.cross3Vec3(p,A,d),Z.normalizeVec3(d,v);var g=i[a]||(i[a]={normal:Z.vec3()});g.normal[0]=v[0],g.normal[1]=v[1],g.normal[2]=v[2],a++}}(I.length,y);for(var w,g,T,E,b,D,P,R,C,_,B=[],O=Math.cos(Z.DEGTORAD*m),S={},N=!1,L=0,x=I.length;L<x;L+=3)for(var M=L/3,F=0;F<3;F++)w=r[L+F],g=r[L+(F+1)%3],void 0===S[b=(T=Math.min(w,g))+","+(E=Math.max(w,g))]?S[b]={index1:T,index2:E,face1:M,face2:void 0}:S[b].face2=M;for(b in S)void 0!==(D=S[b]).face2&&(P=i[D.face1].normal,R=i[D.face2].normal,Z.dotVec3(P,R)>O)||(C=n[D.index1],_=n[D.index2],(!N&&C>65535||_>65535)&&(N=!0),B.push(C),B.push(_));return N?new Uint32Array(B):new Uint16Array(B)}}();var $=function(){function e(){b(this,e),this._head=[],this._headLength=0,this._tail=[],this._index=0,this._length=0}return P(e,[{key:"length",get:function(){return this._length}},{key:"shift",value:function(){if(this._index>=this._headLength){var e=this._head;if(e.length=0,this._head=this._tail,this._tail=e,this._index=0,this._headLength=this._head.length,!this._headLength)return}var t=this._head[this._index];return this._index<0?delete this._head[this._index++]:this._head[this._index++]=void 0,this._length--,t}},{key:"push",value:function(e){return this._length++,this._tail.push(e),this}},{key:"unshift",value:function(e){return this._head[--this._index]=e,this._length++,this}}]),e}(),ee={build:{version:"0.8"},client:{browser:navigator&&navigator.userAgent?navigator.userAgent:"n/a"},components:{scenes:0,models:0,meshes:0,objects:0},memory:{meshes:0,positions:0,colors:0,normals:0,uvs:0,indices:0,textures:0,transforms:0,materials:0,programs:0},frame:{frameCount:0,fps:0,useProgram:0,bindTexture:0,bindArray:0,drawElements:0,drawArrays:0,tasksRun:0,tasksScheduled:0}};var te=[["0",10],["A",26],["a",26],["_",1],["$",1]].map((function(e){for(var t=[],n=e[0].charCodeAt(0),r=n+e[1],i=n;i<r;++i)t.push(i);return String.fromCharCode.apply(null,t)})).join("");function ne(e,t){return(t&&4!==t?[0,6]:[0,6,12,18]).map((function(t){return te.substr(parseInt(e/(1<<t))%64,1)})).reverse().join("")}var re=function(){for(var e={},t=window.location.search.substring(1).split("&"),n=0;n<t.length;n++){var r=t[n].split("=");if(void 0===e[r[0]])e[r[0]]=decodeURIComponent(r[1]);else if("string"==typeof e[r[0]]){var i=[e[r[0]],decodeURIComponent(r[1])];e[r[0]]=i}else e[r[0]].push(decodeURIComponent(r[1]))}return e}();var ie,ae={xmlToJson:function e(t,n){if(t.nodeType===t.TEXT_NODE){var r=t.nodeValue;if(null===r.match(/^\s+$/))return r}else if(t.nodeType===t.ELEMENT_NODE||t.nodeType===t.DOCUMENT_NODE){var i={type:t.nodeName,children:[]};if(t.nodeType===t.ELEMENT_NODE)for(var a=0;a<t.attributes.length;a++){var s=t.attributes[a];i[n[s.nodeName]||s.nodeName]=s.nodeValue}for(var o=0;o<t.childNodes.length;o++){(a=e(t.childNodes[o],n))&&i.children.push(a)}return i}},clone:function(e){return JSON.parse(JSON.stringify(e))},compressGuid:function(e){var t=[0,2,4,6,8,10,12,14,16,18,20,22,24,26,28,30].map((function(t){return parseInt(e.substr(t,2),16)}));return ne(t[0],2)+[1,4,7,10,13].map((function(e){return ne((t[e]<<16)+(t[e+1]<<8)+t[e+2])})).join("")},findNodeOfType:function(e,t){var n=[];return function e(r){r.type===t&&n.push(r),(r.children||[]).forEach((function(t){e(t)}))}(e),n},timeout:function(e){return new Promise((function(t,n){setTimeout(t,e)}))},httpRequest:function(e){return new Promise((function(t,n){var r=new XMLHttpRequest;r.open(e.method||"GET",e.url,!0),r.onload=function(i){console.log(e.url,r.readyState,r.status),4===r.readyState&&(200===r.status?t(r.responseXML):n(r.statusText))},r.send(null)}))},loadJSON:function(e,t,n){var r=function(e){};t=t||r,n=n||r;var i=new XMLHttpRequest;i.overrideMimeType("application/json"),i.open("GET",e,!0),i.addEventListener("load",(function(e){var r=e.target.response;if(200===this.status){var i;try{i=JSON.parse(r)}catch(e){n("utils.loadJSON(): Failed to parse JSON response - ".concat(e))}t(i)}else if(0===this.status){console.warn("loadFile: HTTP Status 0 received.");try{t(JSON.parse(r))}catch(e){n("utils.loadJSON(): Failed to parse JSON response - ".concat(e))}}else n(e)}),!1),i.addEventListener("error",(function(e){n(e)}),!1),i.send(null)},loadArraybuffer:function(e,t,n){var r=function(e){};t=t||r,n=n||r;var i=e.match(/^data:(.*?)(;base64)?,(.*)$/);if(i){var a=!!i[2],s=i[3];s=window.decodeURIComponent(s),a&&(s=window.atob(s));try{for(var o=new ArrayBuffer(s.length),l=new Uint8Array(o),u=0;u<s.length;u++)l[u]=s.charCodeAt(u);window.setTimeout((function(){t(o)}),0)}catch(e){window.setTimeout((function(){n(e)}),0)}}else{var c=new XMLHttpRequest;c.open("GET",e,!0),c.responseType="arraybuffer",c.onreadystatechange=function(){4===c.readyState&&(200===c.status?t(c.response):n("loadArrayBuffer error : "+c.response))},c.send(null)}},queryString:re,isArray:function(e){return e&&!e.propertyIsEnumerable("length")&&"object"===E(e)&&"number"==typeof e.length},isString:function(e){return"string"==typeof e||e instanceof String},isNumeric:function(e){return!isNaN(parseFloat(e))&&isFinite(e)},isID:function(e){return ae.isString(e)||ae.isNumeric(e)},isSameComponent:function(e,t){return!(!e||!t)&&(ae.isNumeric(e)||ae.isString(e)?"".concat(e):e.id)===(ae.isNumeric(t)||ae.isString(t)?"".concat(t):t.id)},isFunction:function(e){return"function"==typeof e},isObject:function(e){var t={}.constructor;return!!e&&e.constructor===t},copy:function(e){return ae.apply(e,{})},apply:function(e,t){for(var n in e)e.hasOwnProperty(n)&&(t[n]=e[n]);return t},apply2:function(e,t){for(var n in e)e.hasOwnProperty(n)&&void 0!==e[n]&&null!==e[n]&&(t[n]=e[n]);return t},applyIf:function(e,t){for(var n in e)e.hasOwnProperty(n)&&(void 0!==t[n]&&null!==t[n]||(t[n]=e[n]));return t},isEmptyObject:function(e){for(var t in e)if(e.hasOwnProperty(t))return!1;return!0},inQuotes:function(e){return ae.isNumeric(e)?"".concat(e):"'".concat(e,"'")},concat:function(e,t){var n=new e.constructor(e.length+t.length);return n.set(e),n.set(t,e.length),n},flattenParentChildHierarchy:function(e){var t=[];return function e(n){n.id=n.uuid,delete n.oid,t.push(n);var r=n.children;if(r)for(var i=0,a=r.length;i<a;i++){r[i].parent=n.id,e(r[i])}n.children=[]}(e),t}},se={},oe=new G,le=new $,ue={sceneId:null,time:null,startTime:null,prevTime:null,deltaTime:null},ce=[],fe=0,pe=0;var Ae=new function(){this.version="1.0.0",this.scenes={},this._superTypes={},this._addScene=function(e){if(e.id){if(Ae.scenes[e.id])return void console.error("[ERROR] Scene ".concat(ae.inQuotes(e.id)," already exists"))}else e.id=oe.addItem({});Ae.scenes[e.id]=e;var t=e.ticksPerOcclusionTest,n=e.ticksPerRender;se[e.id]={ticksPerOcclusionTest:t,ticksPerRender:n,renderCountdown:n},ee.components.scenes++,e.once("destroyed",(function(){oe.removeItem(e.id),delete Ae.scenes[e.id],delete se[e.id],ee.components.scenes--}))},this.clear=function(){var e;for(var t in Ae.scenes)Ae.scenes.hasOwnProperty(t)&&(e=Ae.scenes[t],"default.scene"===t?e.clear():(e.destroy(),delete Ae.scenes[e.id]))},this.scheduleTask=function(e,t){le.push(e),le.push(t)},this.runTasks=function(){for(var e,t,n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:-1,r=(new Date).getTime(),i=0;le.length>0&&(n<0||r<n);)e=le.shift(),(t=le.shift())?e.call(t):e(),r=(new Date).getTime(),i++;return i},this.getNumTasks=function(){return le.length}},de=function e(){var t=Date.now();if(ie=t-fe,fe>0&&ie>0){var n=1e3/ie;pe+=n,ce.push(n),ce.length>=30&&(pe-=ce.shift()),ee.frame.fps=Math.round(pe/ce.length)}!function(e){var t=Ae.runTasks(e+10),n=Ae.getNumTasks();ee.frame.tasksRun=t,ee.frame.tasksScheduled=n,ee.frame.tasksBudget=10}(t),function(e){for(var t in ue.time=e,Ae.scenes)if(Ae.scenes.hasOwnProperty(t)){var n=Ae.scenes[t];ue.sceneId=t,ue.startTime=n.startTime,ue.deltaTime=null!=ue.prevTime?ue.time-ue.prevTime:0,n.fire("tick",ue,!0)}ue.prevTime=e}(t),function(){var e,t,n,r,i,a=Ae.scenes,s=!1;for(i in a)a.hasOwnProperty(i)&&(e=a[i],(t=se[i])||(t=se[i]={}),n=e.ticksPerOcclusionTest,t.ticksPerOcclusionTest!==n&&(t.ticksPerOcclusionTest=n,t.renderCountdown=n),--e.occlusionTestCountdown<=0&&(e.doOcclusionTest(),e.occlusionTestCountdown=n),r=e.ticksPerRender,t.ticksPerRender!==r&&(t.ticksPerRender=r,t.renderCountdown=r),0==--t.renderCountdown&&(e.render(s),t.renderCountdown=r))}(),fe=t,void 0!==window.requestPostAnimationFrame?window.requestPostAnimationFrame(e):requestAnimationFrame(e)};void 0!==window.requestPostAnimationFrame?window.requestPostAnimationFrame(de):requestAnimationFrame(de);var ve=function(){function e(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:null,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(b(this,e),this.scene=null,"Scene"===this.type)this.scene=this,this.viewer=n.viewer;else{if("Scene"===t.type)this.scene=t;else{if(!(t instanceof e))throw"Invalid param: owner must be a Component";this.scene=t.scene}this._owner=t}this._dontClear=!!n.dontClear,this._renderer=this.scene._renderer,this.meta=n.meta||{},this.id=n.id,this.destroyed=!1,this._attached={},this._attachments=null,this._subIdMap=null,this._subIdEvents=null,this._eventSubs=null,this._eventSubsNum=null,this._events=null,this._eventCallDepth=0,this._ownedComponents=null,this!==this.scene&&this.scene._addComponent(this),this._updateScheduled=!1,t&&t._own(this)}return P(e,[{key:"type",get:function(){return"Component"}},{key:"isComponent",get:function(){return!0}},{key:"glRedraw",value:function(){this._renderer&&(this._renderer.imageDirty(),this.castsShadow&&this._renderer.shadowsDirty())}},{key:"glResort",value:function(){this._renderer&&this._renderer.needStateSort()}},{key:"owner",get:function(){return this._owner}},{key:"isType",value:function(e){return this.type===e}},{key:"fire",value:function(e,t,n){this._events||(this._events={}),this._eventSubs||(this._eventSubs={},this._eventSubsNum={}),!0!==n&&(this._events[e]=t||!0);var r,i=this._eventSubs[e];if(i)for(var a in i)i.hasOwnProperty(a)&&(r=i[a],this._eventCallDepth++,this._eventCallDepth<300?r.callback.call(r.scope,t):this.error("fire: potential stack overflow from recursive event '"+e+"' - dropping this event"),this._eventCallDepth--)}},{key:"on",value:function(e,t,n){this._events||(this._events={}),this._subIdMap||(this._subIdMap=new G),this._subIdEvents||(this._subIdEvents={}),this._eventSubs||(this._eventSubs={}),this._eventSubsNum||(this._eventSubsNum={});var r=this._eventSubs[e];r?this._eventSubsNum[e]++:(r={},this._eventSubs[e]=r,this._eventSubsNum[e]=1);var i=this._subIdMap.addItem();r[i]={callback:t,scope:n||this},this._subIdEvents[i]=e;var a=this._events[e];return void 0!==a&&t.call(n||this,a),i}},{key:"off",value:function(e){if(null!=e&&this._subIdEvents){var t=this._subIdEvents[e];if(t){delete this._subIdEvents[e];var n=this._eventSubs[t];n&&(delete n[e],this._eventSubsNum[t]--),this._subIdMap.removeItem(e)}}}},{key:"once",value:function(e,t,n){var r=this,i=this.on(e,(function(e){r.off(i),t.call(n||this,e)}),n)}},{key:"hasSubs",value:function(e){return this._eventSubsNum&&this._eventSubsNum[e]>0}},{key:"log",value:function(e){e="[LOG]"+this._message(e),window.console.log(e),this.scene.fire("log",e)}},{key:"_message",value:function(e){return" ["+this.type+" "+ae.inQuotes(this.id)+"]: "+e}},{key:"warn",value:function(e){e="[WARN]"+this._message(e),window.console.warn(e),this.scene.fire("warn",e)}},{key:"error",value:function(e){e="[ERROR]"+this._message(e),window.console.error(e),this.scene.fire("error",e)}},{key:"_attach",value:function(e){var t=e.name;if(t){var n=e.component,r=e.sceneDefault,i=e.sceneSingleton,a=e.type,s=e.on,o=!1!==e.recompiles;if(n&&(ae.isNumeric(n)||ae.isString(n))){var l=n;if(!(n=this.scene.components[l]))return void this.error("Component not found: "+ae.inQuotes(l))}if(!n)if(!0===i){var u=this.scene.types[a];for(var c in u)if(u.hasOwnProperty){n=u[c];break}if(!n)return this.error("Scene has no default component for '"+t+"'"),null}else if(!0===r&&!(n=this.scene[t]))return this.error("Scene has no default component for '"+t+"'"),null;if(n){if(n.scene.id!==this.scene.id)return void this.error("Not in same scene: "+n.type+" "+ae.inQuotes(n.id));if(a&&!n.isType(a))return void this.error("Expected a "+a+" type or subtype: "+n.type+" "+ae.inQuotes(n.id))}this._attachments||(this._attachments={});var f,p,A,d=this._attached[t];if(d){if(n&&d.id===n.id)return;var v=this._attachments[d.id];for(p=0,A=(f=v.subs).length;p<A;p++)d.off(f[p]);delete this._attached[t],delete this._attachments[d.id];var h=v.params.onDetached;h&&(ae.isFunction(h)?h(d):h.scope?h.callback.call(h.scope,d):h.callback(d)),v.managingLifecycle&&d.destroy()}if(n){var I={params:e,component:n,subs:[],managingLifecycle:!1};I.subs.push(n.once("destroyed",(function(){I.params.component=null,this._attach(I.params)}),this)),o&&I.subs.push(n.on("dirty",(function(){this.fire("dirty",this)}),this)),this._attached[t]=n,this._attachments[n.id]=I;var y,m,w,g,T=e.onAttached;if(T&&(ae.isFunction(T)?T(n):T.scope?T.callback.call(T.scope,n):T.callback(n)),s)for(y in s)if(s.hasOwnProperty(y)){if(m=s[y],ae.isFunction(m)?(w=m,g=null):(w=m.callback,g=m.scope),!w)continue;I.subs.push(n.on(y,w,g))}}return o&&this.fire("dirty",this),this.fire(t,n),n}this.error("Component 'name' expected")}},{key:"_checkComponent",value:function(e,t){if(!t.isComponent){if(!ae.isID(t))return void this.error("Expected a Component or ID");var n=t;if(!(t=this.scene.components[n]))return void this.error("Component not found: "+n)}if(e===t.type){if(t.scene.id===this.scene.id)return t;this.error("Not in same scene: "+t.type)}else this.error("Expected a "+e+" Component")}},{key:"_checkComponent2",value:function(e,t){if(!t.isComponent){if(!ae.isID(t))return void this.error("Expected a Component or ID");var n=t;if(!(t=this.scene.components[n]))return void this.error("Component not found: "+n)}if(t.scene.id===this.scene.id){for(var r=0,i=e.length;r<i;r++)if(e[r]===t.type)return t;return this.error("Expected component types: "+e),null}this.error("Not in same scene: "+t.type)}},{key:"_own",value:function(e){var t=this;this._ownedComponents||(this._ownedComponents={}),this._ownedComponents[e.id]||(this._ownedComponents[e.id]=e),e.once("destroyed",(function(){delete t._ownedComponents[e.id]}),this)}},{key:"_needUpdate",value:function(e){this._updateScheduled||(this._updateScheduled=!0,0===e?this._doUpdate():Ae.scheduleTask(this._doUpdate,this))}},{key:"_doUpdate",value:function(){this._updateScheduled&&(this._updateScheduled=!1,this._update&&this._update())}},{key:"_update",value:function(){}},{key:"clear",value:function(){if(this._ownedComponents)for(var e in this._ownedComponents){if(this._ownedComponents.hasOwnProperty(e))this._ownedComponents[e].destroy(),delete this._ownedComponents[e]}}},{key:"destroy",value:function(){if(!this.destroyed){var e,t,n,r,i,a;if(this.fire("destroyed",this.destroyed=!0),this._attachments)for(e in this._attachments)if(this._attachments.hasOwnProperty(e)){for(n=(t=this._attachments[e]).component,i=0,a=(r=t.subs).length;i<a;i++)n.off(r[i]);t.managingLifecycle&&n.destroy()}if(this._ownedComponents)for(e in this._ownedComponents)this._ownedComponents.hasOwnProperty(e)&&((n=this._ownedComponents[e]).destroy(),delete this._ownedComponents[e]);this.scene._removeComponent(this),this._attached={},this._attachments=null,this._subIdMap=null,this._subIdEvents=null,this._eventSubs=null,this._events=null,this._eventCallDepth=0,this._ownedComponents=null,this._updateScheduled=!1}}}]),e}(),he=Z.vec3(),Ie=function(){var e=new Float64Array(16),t=new Float64Array(4),n=new Float64Array(4);return function(r,i,a){return a=a||e,t[0]=i[0],t[1]=i[1],t[2]=i[2],t[3]=1,Z.transformVec4(r,t,n),Z.setMat4Translation(r,n,a),a.slice()}}();function ye(e,t,n){var r=Float32Array.from([e[0]])[0],i=e[0]-r,a=Float32Array.from([e[1]])[0],s=e[1]-a,o=Float32Array.from([e[2]])[0],l=e[2]-o;t[0]=r,t[1]=a,t[2]=o,n[0]=i,n[1]=s,n[2]=l}function me(e,t,n){var r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:1e3,i=Z.getPositionsCenter(e,he),a=Math.round(i[0]/r)*r,s=Math.round(i[1]/r)*r,o=Math.round(i[2]/r)*r;n[0]=a,n[1]=s,n[2]=o;var l=0!==n[0]||0!==n[1]||0!==n[2];if(l)for(var u=0,c=e.length;u<c;u+=3)t[u+0]=e[u+0]-a,t[u+1]=e[u+1]-s,t[u+2]=e[u+2]-o;return l}function we(e,t,n){return n[0]=e[0]+t[0],n[1]=e[1]+t[1],n[2]=e[2]+t[2],n}function ge(e,t,n,r){var i=Z.dotVec3(t,n)+e,a=Z.normalizeVec3(t,he);return Z.mulVec3Scalar(a,-i,r),r}var Te=1,Ee=4,be=8,De=16,Pe=32,Re=256,Ce=512,_e=1024,Be=2048,Oe=new Float32Array([0,0,0]),Se=new Uint16Array([0,0,0]),Ne=function(){function e(t,n,r,i,a,s,o){b(this,e),this._isObject=n,this.scene=t.scene,this.model=t,this.meshes=i,this._numPrimitives=0;for(var l=0,u=this.meshes.length;l<u;l++){var c=this.meshes[l];c.parent=this,this._numPrimitives+=c.numPrimitives}this.id=r,this.originalSystemId=Z.unglobalizeObjectId(t.id,r),this._flags=a,this._aabb=s,this._offsetAABB=Z.AABB3(s),this._offset=Z.vec3(),this._colorizeUpdated=!1,this._opacityUpdated=!1,this._lodCullable=!!o,this._culled=!1,this._culledVFC=!1,this._culledLOD=!1,this._isObject&&t.scene._registerObject(this)}return P(e,[{key:"isEntity",get:function(){return!0}},{key:"isModel",get:function(){return!1}},{key:"isObject",get:function(){return this._isObject}},{key:"aabb",get:function(){return this._offsetAABB}},{key:"numPrimitives",get:function(){return this._numPrimitives}},{key:"numTriangles",get:function(){return this._numPrimitives}},{key:"visible",get:function(){return this._getFlag(Te)},set:function(e){if(!!(this._flags&Te)!==e){this._flags=e?this._flags|Te:this._flags&~Te;for(var t=0,n=this.meshes.length;t<n;t++)this.meshes[t]._setVisible(this._flags);this._isObject&&this.model.scene._objectVisibilityUpdated(this),this.model.glRedraw()}}},{key:"highlighted",get:function(){return this._getFlag(Ce)},set:function(e){if(!!(this._flags&Ce)!==e){this._flags=e?this._flags|Ce:this._flags&~Ce;for(var t=0,n=this.meshes.length;t<n;t++)this.meshes[t]._setHighlighted(this._flags);this._isObject&&this.model.scene._objectHighlightedUpdated(this),this.model.glRedraw()}}},{key:"xrayed",get:function(){return this._getFlag(Re)},set:function(e){if(!!(this._flags&Re)!==e){this._flags=e?this._flags|Re:this._flags&~Re;for(var t=0,n=this.meshes.length;t<n;t++)this.meshes[t]._setXRayed(this._flags);this._isObject&&this.model.scene._objectXRayedUpdated(this),this.model.glRedraw()}}},{key:"selected",get:function(){return this._getFlag(_e)},set:function(e){if(!!(this._flags&_e)!==e){this._flags=e?this._flags|_e:this._flags&~_e;for(var t=0,n=this.meshes.length;t<n;t++)this.meshes[t]._setSelected(this._flags);this._isObject&&this.model.scene._objectSelectedUpdated(this),this.model.glRedraw()}}},{key:"edges",get:function(){return this._getFlag(Be)},set:function(e){if(!!(this._flags&Be)!==e){this._flags=e?this._flags|Be:this._flags&~Be;for(var t=0,n=this.meshes.length;t<n;t++)this.meshes[t]._setEdges(this._flags);this.model.glRedraw()}}},{key:"culledVFC",get:function(){return!!this._culledVFC},set:function(e){this._culledVFC=e,this._setCulled()}},{key:"culledLOD",get:function(){return!!this._culledLOD},set:function(e){this._culledLOD=e,this._setCulled()}},{key:"culled",get:function(){return!!this._culled},set:function(e){this._culled=e,this._setCulled()}},{key:"_setCulled",value:function(){var e=!!this._culled||!(!this._culledLOD||!this._lodCullable)||!!this._culledVFC;if(!!(this._flags&Ee)!==e){this._flags=e?this._flags|Ee:this._flags&~Ee;for(var t=0,n=this.meshes.length;t<n;t++)this.meshes[t]._setCulled(this._flags);this.model.glRedraw()}}},{key:"clippable",get:function(){return this._getFlag(De)},set:function(e){if(!!(this._flags&De)!==e){this._flags=e?this._flags|De:this._flags&~De;for(var t=0,n=this.meshes.length;t<n;t++)this.meshes[t]._setClippable(this._flags);this.model.glRedraw()}}},{key:"collidable",get:function(){return this._getFlag(Pe)},set:function(e){if(!!(this._flags&Pe)!==e){this._flags=e?this._flags|Pe:this._flags&~Pe;for(var t=0,n=this.meshes.length;t<n;t++)this.meshes[t]._setCollidable(this._flags)}}},{key:"pickable",get:function(){return this._getFlag(be)},set:function(e){if(!!(this._flags&be)!==e){this._flags=e?this._flags|be:this._flags&~be;for(var t=0,n=this.meshes.length;t<n;t++)this.meshes[t]._setPickable(this._flags)}}},{key:"colorize",get:function(){if(0===this.meshes.length)return null;var e=this.meshes[0]._colorize;return Oe[0]=e[0]/255,Oe[1]=e[1]/255,Oe[2]=e[2]/255,Oe},set:function(e){if(e){Se[0]=Math.floor(255*e[0]),Se[1]=Math.floor(255*e[1]),Se[2]=Math.floor(255*e[2]);for(var t=0,n=this.meshes.length;t<n;t++)this.meshes[t]._setColorize(Se)}else for(var r=0,i=this.meshes.length;r<i;r++)this.meshes[r]._setColorize(null);if(this._isObject){var a=!!e;this.scene._objectColorizeUpdated(this,a),this._colorizeUpdated=a}this.model.glRedraw()}},{key:"opacity",get:function(){return this.meshes.length>0?this.meshes[0]._colorize[3]/255:1},set:function(e){if(0!==this.meshes.length){var t=null!=e,n=this.meshes[0]._colorize[3],r=255;if(t){if(e<0?e=0:e>1&&(e=1),n===(r=Math.floor(255*e)))return}else if(n===(r=255))return;for(var i=0,a=this.meshes.length;i<a;i++)this.meshes[i]._setOpacity(r,this._flags);this._isObject&&(this.scene._objectOpacityUpdated(this,t),this._opacityUpdated=t),this.model.glRedraw()}}},{key:"offset",get:function(){return this._offset},set:function(e){e?(this._offset[0]=e[0],this._offset[1]=e[1],this._offset[2]=e[2]):(this._offset[0]=0,this._offset[1]=0,this._offset[2]=0);for(var t=0,n=this.meshes.length;t<n;t++)this.meshes[t]._setOffset(this._offset);this._offsetAABB[0]=this._aabb[0]+this._offset[0],this._offsetAABB[1]=this._aabb[1]+this._offset[1],this._offsetAABB[2]=this._aabb[2]+this._offset[2],this._offsetAABB[3]=this._aabb[3]+this._offset[0],this._offsetAABB[4]=this._aabb[4]+this._offset[1],this._offsetAABB[5]=this._aabb[5]+this._offset[2],this.scene._aabbDirty=!0,this.scene._objectOffsetUpdated(this,e),this.model._aabbDirty=!0,this.model.glRedraw()}},{key:"saoEnabled",get:function(){return this.model.saoEnabled}},{key:"getEachVertex",value:function(e){for(var t=0,n=this.meshes.length;t<n;t++)this.meshes[t].getEachVertex(e)}},{key:"_getFlag",value:function(e){return!!(this._flags&e)}},{key:"_finalize",value:function(){var e=this.model.scene;this._isObject&&(this.visible&&e._objectVisibilityUpdated(this),this.highlighted&&e._objectHighlightedUpdated(this),this.xrayed&&e._objectXRayedUpdated(this),this.selected&&e._objectSelectedUpdated(this));for(var t=0,n=this.meshes.length;t<n;t++)this.meshes[t]._finalize(this._flags)}},{key:"_finalize2",value:function(){for(var e=0,t=this.meshes.length;e<t;e++)this.meshes[e]._finalize2()}},{key:"_destroy",value:function(){var e=this.model.scene;this._isObject&&(e._deregisterObject(this),this.visible&&e._objectVisibilityUpdated(this,!1),this.xrayed&&e._objectXRayedUpdated(this),this.selected&&e._objectSelectedUpdated(this),this.highlighted&&e._objectHighlightedUpdated(this),this._opacityUpdated&&this.scene._objectColorizeUpdated(this,!1),this._opacityUpdated&&this.scene._objectOpacityUpdated(this,!1),this.scene._objectOffsetUpdated(this,!1));for(var t=0,n=this.meshes.length;t<n;t++)this.meshes[t]._destroy();e._aabbDirty=!0}}]),e}(),Le=Z.vec4(),xe=Z.vec4(),Me=function(e){I(n,ve);var t=m(n);function n(e,r){var i;return b(this,n),(i=t.call(this,e,r))._entity=null,i._visible=null,i._worldPos=Z.vec3(),i._origin=Z.vec3(),i._rtcPos=Z.vec3(),i._viewPos=Z.vec3(),i._canvasPos=Z.vec2(),i._occludable=!1,i._onCameraViewMatrix=i.scene.camera.on("matrix",(function(){i._viewPosDirty=!0,i._needUpdate()})),i._onCameraProjMatrix=i.scene.camera.on("projMatrix",(function(){i._canvasPosDirty=!0,i._needUpdate()})),i._onEntityDestroyed=null,i._onEntityModelDestroyed=null,i._renderer.addMarker(g(i)),i.entity=r.entity,i.worldPos=r.worldPos,i.occludable=r.occludable,i}return P(n,[{key:"_update",value:function(){if(this._viewPosDirty&&(Z.transformPoint3(this.scene.camera.viewMatrix,this._worldPos,this._viewPos),this._viewPosDirty=!1,this._canvasPosDirty=!0,this.fire("viewPos",this._viewPos)),this._canvasPosDirty){Le.set(this._viewPos),Le[3]=1,Z.transformPoint4(this.scene.camera.projMatrix,Le,xe);var e=this.scene.canvas.boundary;this._canvasPos[0]=Math.floor((1+xe[0]/xe[3])*e[2]/2),this._canvasPos[1]=Math.floor((1-xe[1]/xe[3])*e[3]/2),this._canvasPosDirty=!1,this.fire("canvasPos",this._canvasPos)}}},{key:"_setVisible",value:function(e){this._visible,this._visible=e,this.fire("visible",this._visible)}},{key:"entity",get:function(){return this._entity},set:function(e){var t=this;if(this._entity){if(this._entity===e)return;null!==this._onEntityDestroyed&&(this._entity.off(this._onEntityDestroyed),this._onEntityDestroyed=null),null!==this._onEntityModelDestroyed&&(this._entity.model.off(this._onEntityModelDestroyed),this._onEntityModelDestroyed=null)}this._entity=e,this._entity&&(this._entity instanceof Ne?this._onEntityModelDestroyed=this._entity.model.on("destroyed",(function(){t._entity=null,t._onEntityModelDestroyed=null})):this._onEntityDestroyed=this._entity.on("destroyed",(function(){t._entity=null,t._onEntityDestroyed=null}))),this.fire("entity",this._entity,!0)}},{key:"occludable",get:function(){return this._occludable},set:function(e){(e=!!e)!==this._occludable&&(this._occludable=e)}},{key:"worldPos",get:function(){return this._worldPos},set:function(e){this._worldPos.set(e||[0,0,0]),ye(this._worldPos,this._origin,this._rtcPos),this._occludable&&this._renderer.markerWorldPosUpdated(this),this._viewPosDirty=!0,this.fire("worldPos",this._worldPos),this._needUpdate()}},{key:"origin",get:function(){return this._origin}},{key:"rtcPos",get:function(){return this._rtcPos}},{key:"viewPos",get:function(){return this._update(),this._viewPos}},{key:"canvasPos",get:function(){return this._update(),this._canvasPos}},{key:"visible",get:function(){return!!this._visible}},{key:"destroy",value:function(){this.fire("destroyed",!0),this.scene.camera.off(this._onCameraViewMatrix),this.scene.camera.off(this._onCameraProjMatrix),this._entity&&(null!==this._onEntityDestroyed&&this._entity.off(this._onEntityDestroyed),null!==this._onEntityModelDestroyed&&this._entity.model.off(this._onEntityModelDestroyed)),this._renderer.removeMarker(this),v(T(n.prototype),"destroy",this).call(this)}}]),n}(),Fe=function(){function e(t){var n=this,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};b(this,e),this._color=r.color||"black",this._highlightClass="viewer-ruler-wire-highlighted",this._wire=document.createElement("div"),this._wire.className+=this._wire.className?" viewer-ruler-wire":"viewer-ruler-wire",this._wireClickable=document.createElement("div"),this._wireClickable.className+=this._wireClickable.className?" viewer-ruler-wire-clickable":"viewer-ruler-wire-clickable",this._thickness=r.thickness||1,this._thicknessClickable=r.thicknessClickable||6;var i=this._wire,a=i.style;a.border="solid "+this._thickness+"px "+this._color,a.position="absolute",a["z-index"]=void 0===r.zIndex?"2000001":r.zIndex,a.width="0px",a.height="0px",a.visibility="visible",a.top="0px",a.left="0px",a["-webkit-transform-origin"]="0 0",a["-moz-transform-origin"]="0 0",a["-ms-transform-origin"]="0 0",a["-o-transform-origin"]="0 0",a["transform-origin"]="0 0",a["-webkit-transform"]="rotate(0deg)",a["-moz-transform"]="rotate(0deg)",a["-ms-transform"]="rotate(0deg)",a["-o-transform"]="rotate(0deg)",a.transform="rotate(0deg)",a.opacity=1,a["pointer-events"]="none",r.onContextMenu,t.appendChild(i);var s=this._wireClickable,o=s.style;o.border="solid "+this._thicknessClickable+"px "+this._color,o.position="absolute",o["z-index"]=void 0===r.zIndex?"2000002":r.zIndex+1,o.width="0px",o.height="0px",o.visibility="visible",o.top="0px",o.left="0px",o["-webkit-transform-origin"]="0 0",o["-moz-transform-origin"]="0 0",o["-ms-transform-origin"]="0 0",o["-o-transform-origin"]="0 0",o["transform-origin"]="0 0",o["-webkit-transform"]="rotate(0deg)",o["-moz-transform"]="rotate(0deg)",o["-ms-transform"]="rotate(0deg)",o["-o-transform"]="rotate(0deg)",o.transform="rotate(0deg)",o.opacity=0,o["pointer-events"]="none",r.onContextMenu,t.appendChild(s),r.onMouseOver&&s.addEventListener("mouseover",(function(e){r.onMouseOver(e,n)})),r.onMouseLeave&&s.addEventListener("mouseleave",(function(e){r.onMouseLeave(e,n)})),r.onMouseWheel&&s.addEventListener("wheel",(function(e){r.onMouseWheel(e,n)})),r.onContextMenu&&s.addEventListener("contextmenu",(function(e){r.onContextMenu(e,n),e.preventDefault()})),this._x1=0,this._y1=0,this._x2=0,this._y2=0,this._update()}return P(e,[{key:"_visible",get:function(){return"visible"===this._wire.style.visibility}},{key:"_update",value:function(){var e=Math.abs(Math.sqrt((this._x1-this._x2)*(this._x1-this._x2)+(this._y1-this._y2)*(this._y1-this._y2))),t=180*Math.atan2(this._y2-this._y1,this._x2-this._x1)/Math.PI,n=this._wire.style;n.width=Math.round(e)+"px",n.left=Math.round(this._x1)+"px",n.top=Math.round(this._y1)+"px",n["-webkit-transform"]="rotate("+t+"deg)",n["-moz-transform"]="rotate("+t+"deg)",n["-ms-transform"]="rotate("+t+"deg)",n["-o-transform"]="rotate("+t+"deg)",n.transform="rotate("+t+"deg)";var r=this._wireClickable.style;r.width=Math.round(e)+"px",r.left=Math.round(this._x1)+"px",r.top=Math.round(this._y1)+"px",r["-webkit-transform"]="rotate("+t+"deg)",r["-moz-transform"]="rotate("+t+"deg)",r["-ms-transform"]="rotate("+t+"deg)",r["-o-transform"]="rotate("+t+"deg)",r.transform="rotate("+t+"deg)"}},{key:"setStartAndEnd",value:function(e,t,n,r){this._x1=e,this._y1=t,this._x2=n,this._y2=r,this._update()}},{key:"setColor",value:function(e){this._color=e||"black",this._wire.style.border="solid "+this._thickness+"px "+this._color}},{key:"setOpacity",value:function(e){this._wire.style.opacity=e}},{key:"setVisible",value:function(e){e=!!e,this._visible!==e&&(this._wire.style.visibility=e?"visible":"hidden")}},{key:"setClickable",value:function(e){this._wireClickable.style["pointer-events"]=e?"all":"none"}},{key:"setHighlighted",value:function(e){this._highlighted!==e&&(this._highlighted=!!e,this._highlighted?this._wire.classList.add(this._highlightClass):this._wire.classList.remove(this._highlightClass))}},{key:"destroy",value:function(e){this._wire.parentElement&&this._wire.parentElement.removeChild(this._wire),this._wireClickable.parentElement&&this._wireClickable.parentElement.removeChild(this._wireClickable)}}]),e}(),He=function(){function e(t){var n=this,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};b(this,e),this._highlightClass="viewer-ruler-dot-highlighted",this._x=0,this._y=0,this._visible=!0,this._dot=document.createElement("div"),this._dot.className+=this._dot.className?" viewer-ruler-dot":"viewer-ruler-dot",this._dotClickable=document.createElement("div"),this._dotClickable.className+=this._dotClickable.className?" viewer-ruler-dot-clickable":"viewer-ruler-dot-clickable";var i=this._dot,a=i.style;a["border-radius"]="25px",a.border="solid 2px white",a.background="lightgreen",a.position="absolute",a["z-index"]=void 0===r.zIndex?"40000005":r.zIndex,a.width="8px",a.height="8px",a.visibility=!1!==r.visible?"visible":"hidden",a.top="0px",a.left="0px",a["box-shadow"]="0 2px 5px 0 #182A3D;",a.opacity=1,a["pointer-events"]="none",r.onContextMenu,t.appendChild(i);var s=this._dotClickable,o=s.style;o["border-radius"]="35px",o.border="solid 10px white",o.position="absolute",o["z-index"]=void 0===r.zIndex?"40000007":r.zIndex+1,o.width="8px",o.height="8px",o.visibility="visible",o.top="0px",o.left="0px",o.opacity=0,o["pointer-events"]="none",r.onContextMenu,t.appendChild(s),r.onMouseOver&&s.addEventListener("mouseover",(function(e){r.onMouseOver(e,n)})),r.onMouseLeave&&s.addEventListener("mouseleave",(function(e){r.onMouseLeave(e,n)})),r.onMouseWheel&&s.addEventListener("wheel",(function(e){r.onMouseWheel(e,n)})),r.onContextMenu&&s.addEventListener("contextmenu",(function(e){r.onContextMenu(e,n),e.preventDefault()})),this.setPos(r.x||0,r.y||0),this.setFillColor(r.fillColor),this.setBorderColor(r.borderColor)}return P(e,[{key:"setPos",value:function(e,t){this._x=e,this._y=t;var n=this._dot.style;n.left=Math.round(e)-4+"px",n.top=Math.round(t)-4+"px";var r=this._dotClickable.style;r.left=Math.round(e)-9+"px",r.top=Math.round(t)-9+"px"}},{key:"setFillColor",value:function(e){this._dot.style.background=e||"lightgreen"}},{key:"setBorderColor",value:function(e){this._dot.style.border="solid 2px"+(e||"black")}},{key:"setOpacity",value:function(e){this._dot.style.opacity=e}},{key:"setVisible",value:function(e){this._visible!==e&&(this._visible=!!e,this._dot.style.visibility=this._visible?"visible":"hidden")}},{key:"setClickable",value:function(e){this._dotClickable.style["pointer-events"]=e?"all":"none"}},{key:"setHighlighted",value:function(e){this._highlighted!==e&&(this._highlighted=!!e,this._highlighted?this._dot.classList.add(this._highlightClass):this._dot.classList.remove(this._highlightClass))}},{key:"destroy",value:function(){this.setVisible(!1),this._dot.parentElement&&this._dot.parentElement.removeChild(this._dot),this._dotClickable.parentElement&&this._dotClickable.parentElement.removeChild(this._dotClickable)}}]),e}(),Ue=function(){function e(t){var n=this,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};b(this,e),this._highlightClass="viewer-ruler-label-highlighted",this._prefix=r.prefix||"",this._x=0,this._y=0,this._visible=!0,this._culled=!1,this._label=document.createElement("div"),this._label.className+=this._label.className?" viewer-ruler-label":"viewer-ruler-label";var i=this._label,a=i.style;a["border-radius"]="5px",a.color="white",a.padding="4px",a.border="solid 1px",a.background="lightgreen",a.position="absolute",a["z-index"]=void 0===r.zIndex?"5000005":r.zIndex,a.width="auto",a.height="auto",a.visibility="visible",a.top="0px",a.left="0px",a["pointer-events"]="all",a.opacity=1,r.onContextMenu,i.innerText="",t.appendChild(i),this.setPos(r.x||0,r.y||0),this.setFillColor(r.fillColor),this.setBorderColor(r.fillColor),this.setText(r.text),r.onMouseOver&&i.addEventListener("mouseover",(function(e){r.onMouseOver(e,n),e.preventDefault()})),r.onMouseLeave&&i.addEventListener("mouseleave",(function(e){r.onMouseLeave(e,n),e.preventDefault()})),r.onMouseWheel&&i.addEventListener("wheel",(function(e){r.onMouseWheel(e,n)})),r.onContextMenu&&i.addEventListener("contextmenu",(function(e){r.onContextMenu(e,n),e.preventDefault()}))}return P(e,[{key:"setPos",value:function(e,t){this._x=e,this._y=t;var n=this._label.style;n.left=Math.round(e)-20+"px",n.top=Math.round(t)-12+"px"}},{key:"setPosOnWire",value:function(e,t,n,r){var i=e+.5*(n-e),a=t+.5*(r-t),s=this._label.style;s.left=Math.round(i)-20+"px",s.top=Math.round(a)-12+"px"}},{key:"setPosBetweenWires",value:function(e,t,n,r,i,a){var s=(e+n+i)/3,o=(t+r+a)/3,l=this._label.style;l.left=Math.round(s)-20+"px",l.top=Math.round(o)-12+"px"}},{key:"setText",value:function(e){this._label.innerHTML=this._prefix+(e||"")}},{key:"setFillColor",value:function(e){this._fillColor=e||"lightgreen",this._label.style.background=this._fillColor}},{key:"setBorderColor",value:function(e){this._borderColor=e||"black",this._label.style.border="solid 1px "+this._borderColor}},{key:"setOpacity",value:function(e){this._label.style.opacity=e}},{key:"setVisible",value:function(e){this._visible!==e&&(this._visible=!!e,this._label.style.visibility=this._visible&&!this._culled?"visible":"hidden")}},{key:"setCulled",value:function(e){this._culled!==e&&(this._culled=!!e,this._label.style.visibility=this._visible&&!this._culled?"visible":"hidden")}},{key:"setHighlighted",value:function(e){this._highlighted!==e&&(this._highlighted=!!e,this._highlighted?this._label.classList.add(this._highlightClass):this._label.classList.remove(this._highlightClass))}},{key:"setClickable",value:function(e){this._label.style["pointer-events"]=e?"all":"none"}},{key:"destroy",value:function(){this._label.parentElement&&this._label.parentElement.removeChild(this._label)}}]),e}(),Ge=Z.vec3(),ke=Z.vec3(),Ve=function(e){I(n,ve);var t=m(n);function n(e){var r,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(b(this,n),(r=t.call(this,e.viewer.scene,i)).plugin=e,r._container=i.container,!r._container)throw"config missing: container";r._color=i.color||e.defaultColor;var a=r.plugin.viewer.scene;r._originMarker=new Me(a,i.origin),r._cornerMarker=new Me(a,i.corner),r._targetMarker=new Me(a,i.target),r._originWorld=Z.vec3(),r._cornerWorld=Z.vec3(),r._targetWorld=Z.vec3(),r._wp=new Float64Array(12),r._vp=new Float64Array(12),r._pp=new Float64Array(12),r._cp=new Int16Array(6);var s=i.onMouseOver?function(e){i.onMouseOver(e,g(r))}:null,o=i.onMouseLeave?function(e){i.onMouseLeave(e,g(r))}:null,l=i.onContextMenu?function(e){i.onContextMenu(e,g(r))}:null,u=function(e){r.plugin.viewer.scene.canvas.canvas.dispatchEvent(new WheelEvent("wheel",e))};return r._originDot=new He(r._container,{fillColor:r._color,zIndex:void 0!==e.zIndex?e.zIndex+2:void 0,onMouseOver:s,onMouseLeave:o,onMouseWheel:u,onContextMenu:l}),r._cornerDot=new He(r._container,{fillColor:r._color,zIndex:void 0!==e.zIndex?e.zIndex+2:void 0,onMouseOver:s,onMouseLeave:o,onMouseWheel:u,onContextMenu:l}),r._targetDot=new He(r._container,{fillColor:r._color,zIndex:void 0!==e.zIndex?e.zIndex+2:void 0,onMouseOver:s,onMouseLeave:o,onMouseWheel:u,onContextMenu:l}),r._originWire=new Fe(r._container,{color:r._color||"blue",thickness:1,zIndex:e.zIndex,onMouseOver:s,onMouseLeave:o,onMouseWheel:u,onContextMenu:l}),r._targetWire=new Fe(r._container,{color:r._color||"red",thickness:1,zIndex:void 0!==e.zIndex?e.zIndex+1:void 0,onMouseOver:s,onMouseLeave:o,onMouseWheel:u,onContextMenu:l}),r._angleLabel=new Ue(r._container,{fillColor:r._color||"#00BBFF",prefix:"",text:"",zIndex:e.zIndex+2,onMouseOver:s,onMouseLeave:o,onMouseWheel:u,onContextMenu:l}),r._wpDirty=!1,r._vpDirty=!1,r._cpDirty=!1,r._visible=!1,r._originVisible=!1,r._cornerVisible=!1,r._targetVisible=!1,r._originWireVisible=!1,r._targetWireVisible=!1,r._angleVisible=!1,r._labelsVisible=!1,r._clickable=!1,r._originMarker.on("worldPos",(function(e){r._originWorld.set(e||[0,0,0]),r._wpDirty=!0,r._needUpdate(0)})),r._cornerMarker.on("worldPos",(function(e){r._cornerWorld.set(e||[0,0,0]),r._wpDirty=!0,r._needUpdate(0)})),r._targetMarker.on("worldPos",(function(e){r._targetWorld.set(e||[0,0,0]),r._wpDirty=!0,r._needUpdate(0)})),r._onViewMatrix=a.camera.on("viewMatrix",(function(){r._vpDirty=!0,r._needUpdate(0)})),r._onProjMatrix=a.camera.on("projMatrix",(function(){r._cpDirty=!0,r._needUpdate()})),r._onCanvasBoundary=a.canvas.on("boundary",(function(){r._cpDirty=!0,r._needUpdate(0)})),r.approximate=i.approximate,r.visible=i.visible,r.originVisible=i.originVisible,r.cornerVisible=i.cornerVisible,r.targetVisible=i.targetVisible,r.originWireVisible=i.originWireVisible,r.targetWireVisible=i.targetWireVisible,r.angleVisible=i.angleVisible,r.labelsVisible=i.labelsVisible,r}return P(n,[{key:"_update",value:function(){if(this._visible){var e=this.plugin.viewer.scene;if(this._wpDirty&&(this._wp[0]=this._originWorld[0],this._wp[1]=this._originWorld[1],this._wp[2]=this._originWorld[2],this._wp[3]=1,this._wp[4]=this._cornerWorld[0],this._wp[5]=this._cornerWorld[1],this._wp[6]=this._cornerWorld[2],this._wp[7]=1,this._wp[8]=this._targetWorld[0],this._wp[9]=this._targetWorld[1],this._wp[10]=this._targetWorld[2],this._wp[11]=1,this._wpDirty=!1,this._vpDirty=!0),this._vpDirty&&(Z.transformPositions4(e.camera.viewMatrix,this._wp,this._vp),this._vp[3]=1,this._vp[7]=1,this._vp[11]=1,this._vpDirty=!1,this._cpDirty=!0),this._cpDirty){var t=-.3,n=this._originMarker.viewPos[2],r=this._cornerMarker.viewPos[2],i=this._targetMarker.viewPos[2];if(n>t||r>t||i>t)return this._originDot.setVisible(!1),this._cornerDot.setVisible(!1),this._targetDot.setVisible(!1),this._originWire.setVisible(!1),this._targetWire.setVisible(!1),void this._angleLabel.setCulled(!0);Z.transformPositions4(e.camera.project.matrix,this._vp,this._pp);for(var a=this._pp,s=this._cp,o=e.canvas.canvas.getBoundingClientRect(),l=this._container.getBoundingClientRect(),u=o.top-l.top,c=o.left-l.left,f=e.canvas.boundary,p=f[2],A=f[3],d=0,v=0,h=a.length;v<h;v+=4)s[d]=c+Math.floor((1+a[v+0]/a[v+3])*p/2),s[d+1]=u+Math.floor((1-a[v+1]/a[v+3])*A/2),d+=2;if(this._originDot.setPos(s[0],s[1]),this._cornerDot.setPos(s[2],s[3]),this._targetDot.setPos(s[4],s[5]),this._originWire.setStartAndEnd(s[0],s[1],s[2],s[3]),this._targetWire.setStartAndEnd(s[2],s[3],s[4],s[5]),this._angleLabel.setPosBetweenWires(s[0],s[1],s[2],s[3],s[4],s[5]),Z.subVec3(this._originWorld,this._cornerWorld,Ge),Z.subVec3(this._targetWorld,this._cornerWorld,ke),!(0===Ge[0]&&0===Ge[1]&&0===Ge[2]||0===ke[0]&&0===ke[1]&&0===ke[2])){var I=this._approximate?" ~ ":" = ";Z.normalizeVec3(Ge),Z.normalizeVec3(ke);var y=Math.abs(Z.angleVec3(Ge,ke));this._angle=y/Z.DEGTORAD,this._angleLabel.setText(I+this._angle.toFixed(2)+"°")}else this._angleLabel.setText("");this._originDot.setVisible(this._visible&&this._originVisible),this._cornerDot.setVisible(this._visible&&this._cornerVisible),this._targetDot.setVisible(this._visible&&this._targetVisible),this._originWire.setVisible(this._visible&&this._originWireVisible),this._targetWire.setVisible(this._visible&&this._targetWireVisible),this._angleLabel.setCulled(!(this._visible&&this._angleVisible&&this.labelsVisible)),this._cpDirty=!1}}}},{key:"approximate",get:function(){return this._approximate},set:function(e){e=!1!==e,this._approximate!==e&&(this._approximate=e,this._cpDirty=!0,this._needUpdate(0))}},{key:"origin",get:function(){return this._originMarker}},{key:"corner",get:function(){return this._cornerMarker}},{key:"target",get:function(){return this._targetMarker}},{key:"angle",get:function(){return this._update(),this._angle}},{key:"color",get:function(){return this._color},set:function(e){this._originDot.setFillColor(e),this._cornerDot.setFillColor(e),this._targetDot.setFillColor(e),this._originWire.setColor(e||"blue"),this._targetWire.setColor(e||"red"),this._angleLabel.setFillColor(e||"#00BBFF"),this._color=e}},{key:"visible",get:function(){return this._visible},set:function(e){e=!1!==e,this._visible=e,this._originDot.setVisible(this._visible&&this._originVisible),this._cornerDot.setVisible(this._visible&&this._cornerVisible),this._targetDot.setVisible(this._visible&&this._targetVisible),this._originWire.setVisible(this._visible&&this._originWireVisible),this._targetWire.setVisible(this._visible&&this._targetWireVisible),this._angleLabel.setVisible(this._visible&&this._angleVisible),this._cpDirty=!0,this._needUpdate()}},{key:"originVisible",get:function(){return this._originVisible},set:function(e){e=!1!==e,this._originVisible=e,this._originDot.setVisible(this._visible&&this._originVisible),this._cpDirty=!0,this._needUpdate()}},{key:"cornerVisible",get:function(){return this._cornerVisible},set:function(e){e=!1!==e,this._cornerVisible=e,this._cornerDot.setVisible(this._visible&&this._cornerVisible),this._cpDirty=!0,this._needUpdate()}},{key:"targetVisible",get:function(){return this._targetVisible},set:function(e){e=!1!==e,this._targetVisible=e,this._targetDot.setVisible(this._visible&&this._targetVisible),this._cpDirty=!0,this._needUpdate()}},{key:"originWireVisible",get:function(){return this._originWireVisible},set:function(e){e=!1!==e,this._originWireVisible=e,this._originWire.setVisible(this._visible&&this._originWireVisible),this._cpDirty=!0,this._needUpdate()}},{key:"targetWireVisible",get:function(){return this._targetWireVisible},set:function(e){e=!1!==e,this._targetWireVisible=e,this._targetWire.setVisible(this._visible&&this._targetWireVisible),this._cpDirty=!0,this._needUpdate()}},{key:"angleVisible",get:function(){return this._angleVisible},set:function(e){e=!1!==e,this._angleVisible=e,this._angleLabel.setVisible(this._visible&&this._angleVisible),this._cpDirty=!0,this._needUpdate()}},{key:"labelsVisible",get:function(){return this._labelsVisible},set:function(e){e=void 0!==e?Boolean(e):this.plugin.defaultLabelsVisible,this._labelsVisible=e;var t=this._visible&&this._labelsVisible;this._angleLabel.setVisible(t),this._cpDirty=!0,this._needUpdate()}},{key:"setHighlighted",value:function(e){this._originDot.setHighlighted(e),this._cornerDot.setHighlighted(e),this._targetDot.setHighlighted(e),this._originWire.setHighlighted(e),this._targetWire.setHighlighted(e),this._angleLabel.setHighlighted(e)}},{key:"clickable",get:function(){return this._clickable},set:function(e){e=!!e,this._clickable=e,this._originDot.setClickable(this._clickable),this._cornerDot.setClickable(this._clickable),this._targetDot.setClickable(this._clickable),this._originWire.setClickable(this._clickable),this._targetWire.setClickable(this._clickable),this._angleLabel.setClickable(this._clickable)}},{key:"destroy",value:function(){var e=this.plugin.viewer.scene;this._onViewMatrix&&e.camera.off(this._onViewMatrix),this._onProjMatrix&&e.camera.off(this._onProjMatrix),this._onCanvasBoundary&&e.canvas.off(this._onCanvasBoundary),this._originDot.destroy(),this._cornerDot.destroy(),this._targetDot.destroy(),this._originWire.destroy(),this._targetWire.destroy(),this._angleLabel.destroy(),v(T(n.prototype),"destroy",this).call(this)}}]),n}(),je=function(e){I(n,ve);var t=m(n);function n(e){var r;b(this,n),(r=t.call(this,e.viewer.scene)).plugin=e,r._active=!1,r._state=0,r._currentAngleMeasurement=null;var i=document.createElement("div"),a=r.scene.canvas.canvas;return a.parentNode.insertBefore(i,a),i.style.background="black",i.style.border="2px solid blue",i.style.borderRadius="10px",i.style.width="5px",i.style.height="5px",i.style.margin="-200px -200px",i.style.zIndex="100",i.style.position="absolute",i.style.pointerEvents="none",r.markerDiv=i,r._onMouseHoverSurface=null,r._onHoverNothing=null,r._onMouseHoverOff=null,r._onPickedNothing=null,r._onPickedSurface=null,r._onInputMouseDown=null,r._onInputMouseUp=null,r._onCanvasTouchStart=null,r._onCanvasTouchEnd=null,r}return P(n,[{key:"active",get:function(){return this._active}},{key:"activate",value:function(){var e=this;if(!this._active){var t,n,r=this.plugin,i=this.scene,a=r.viewer.cameraControl,s=i.canvas.canvas,o=i.input,l=!1,u=null,c=Z.vec3(),f=Z.vec2(),p=Z.vec2(),A=Z.vec2();Z.vec3(),this._onMouseHoverSurface=a.on("hoverSnapOrSurface",(function(t){switch(l=!0,u=t.entity,c.set(t.worldPos),f.set(t.canvasPos),e._state){case 0:e.markerDiv.style.marginLeft="".concat(t.canvasPos[0]-5,"px"),e.markerDiv.style.marginTop="".concat(t.canvasPos[1]-5,"px"),e.markerDiv.style.background="pink",e.markerDiv.style.border="2px solid red";break;case 1:e._currentAngleMeasurement&&(e._currentAngleMeasurement.originWireVisible=!0,e._currentAngleMeasurement.targetWireVisible=!1,e._currentAngleMeasurement.cornerVisible=!0,e._currentAngleMeasurement.angleVisible=!1,e._currentAngleMeasurement.corner.worldPos=t.worldPos),e.markerDiv.style.marginLeft="-10000px",e.markerDiv.style.marginTop="-10000px",s.style.cursor="pointer";break;case 2:e._currentAngleMeasurement&&(e._currentAngleMeasurement.targetWireVisible=!0,e._currentAngleMeasurement.targetVisible=!0,e._currentAngleMeasurement.angleVisible=!0,e._currentAngleMeasurement.target.worldPos=t.worldPos),e.markerDiv.style.marginLeft="-10000px",e.markerDiv.style.marginTop="-10000px",s.style.cursor="pointer"}})),this._onInputMouseDown=o.on("mousedown",(function(e){t=e[0],n=e[1]})),this._onInputMouseUp=o.on("mouseup",(function(r){if(!(r[0]>t+5||r[0]<t-5||r[1]>n+5||r[1]<n-5))switch(e._state){case 0:l&&(e._currentAngleMeasurement=e.plugin.createMeasurement({id:Z.createUUID(),origin:{entity:u,worldPos:c},corner:{entity:u,worldPos:c},target:{entity:u,worldPos:c},approximate:!0}),e._currentAngleMeasurement.originVisible=!0,e._currentAngleMeasurement.originWireVisible=!0,e._currentAngleMeasurement.cornerVisible=!1,e._currentAngleMeasurement.targetWireVisible=!1,e._currentAngleMeasurement.targetVisible=!1,e._currentAngleMeasurement.angleVisible=!1,e._state=1,e.fire("measurementStart",e._currentAngleMeasurement));break;case 1:l?(e._currentAngleMeasurement.targetWireVisible=!1,e._currentAngleMeasurement.targetVisible=!0,e._currentAngleMeasurement.angleVisible=!0,e._state=2):e._currentAngleMeasurement&&(e._currentAngleMeasurement.destroy(),e._currentAngleMeasurement=null,e._state=0,e.fire("measurementCancel",e._currentAngleMeasurement));break;case 2:l?(e._currentAngleMeasurement.targetVisible=!0,e._currentAngleMeasurement.angleVisible=!0,e.fire("measurementEnd",e._currentAngleMeasurement),e._currentAngleMeasurement=null,e._state=0):e._currentAngleMeasurement&&(e._currentAngleMeasurement.destroy(),e._currentAngleMeasurement=null,e._state=0,e.fire("measurementCancel",e._currentAngleMeasurement))}})),this._onMouseHoverOff=a.on("hoverSnapOrSurfaceOff",(function(t){if(l=!1,e.markerDiv.style.marginLeft="-100px",e.markerDiv.style.marginTop="-100px",e._currentAngleMeasurement){switch(e._state){case 0:e._currentAngleMeasurement.originVisible=!1;break;case 1:e._currentAngleMeasurement.cornerVisible=!1,e._currentAngleMeasurement.originWireVisible=!1,e._currentAngleMeasurement.targetVisible=!1,e._currentAngleMeasurement.targetWireVisible=!1,e._currentAngleMeasurement.angleVisible=!1;break;case 2:e._currentAngleMeasurement.targetVisible=!1,e._currentAngleMeasurement.targetWireVisible=!1,e._currentAngleMeasurement.angleVisible=!1}s.style.cursor="default"}})),s.addEventListener("touchstart",this._onCanvasTouchStart=function(e){var t=e.touches,n=e.changedTouches;1===t.length&&1===n.length&&Qe(t[0],p)},{passive:!0}),s.addEventListener("touchend",this._onCanvasTouchEnd=function(t){var n=t.touches,r=t.changedTouches;if(0===n.length&&1===r.length){if(Qe(r[0],A),A[0]>p[0]+5||A[0]<p[0]-5||A[1]>p[1]+5||A[1]<p[1]-5)return;var a=i.pick({canvasPos:A,pickSurface:!0});if(a&&a.worldPos)switch(e._state){case 0:e._currentAngleMeasurement=e.plugin.createMeasurement({id:Z.createUUID(),origin:{entity:a.entity,worldPos:a.worldPos},corner:{entity:a.entity,worldPos:a.worldPos},target:{entity:a.entity,worldPos:a.worldPos},approximate:!0}),e._currentAngleMeasurement.originVisible=!0,e._currentAngleMeasurement.originWireVisible=!0,e._currentAngleMeasurement.cornerVisible=!1,e._currentAngleMeasurement.targetWireVisible=!1,e._currentAngleMeasurement.targetVisible=!1,e._currentAngleMeasurement.angleVisible=!1,e._currentAngleMeasurement.clickable=!1,e._state=1,e.fire("measurementStart",e._currentAngleMeasurement);break;case 1:e._currentAngleMeasurement.corner.worldPos=a.worldPos,e._currentAngleMeasurement.targetWireVisible=!1,e._currentAngleMeasurement.targetVisible=!0,e._currentAngleMeasurement.angleVisible=!0,e._state=2;break;case 2:e._currentAngleMeasurement.target.worldPos=a.worldPos,e._currentAngleMeasurement.targetVisible=!0,e._currentAngleMeasurement.angleVisible=!0,e._currentAngleMeasurement.clickable=!0,e.fire("measurementEnd",e._currentAngleMeasurement),e._currentAngleMeasurement=null,e._state=0}else e._currentAngleMeasurement&&(e._currentAngleMeasurement.destroy(),e._currentAngleMeasurement=null,e._state=0,e.fire("measurementCancel",e._currentAngleMeasurement))}},{passive:!0}),this._active=!0}}},{key:"deactivate",value:function(){if(this._active){this.reset();var e=this.plugin.viewer.scene.input,t=this.plugin.viewer.cameraControl,n=this.plugin.viewer.scene.canvas.canvas;e.off(this._onInputMouseDown),e.off(this._onInputMouseUp),t.off(this._onMouseHoverSurface),t.off(this._onPickedSurface),t.off(this._onHoverNothing),t.off(this._onPickedNothing),n.removeEventListener("touchstart",this._onCanvasTouchStart),n.removeEventListener("touchend",this._onCanvasTouchEnd),this._currentAngleMeasurement=null,this._active=!1}}},{key:"reset",value:function(){this._active&&(this._currentAngleMeasurement&&(this._currentAngleMeasurement.destroy(),this._currentAngleMeasurement=null),this._state=0)}},{key:"destroy",value:function(){this.deactivate(),v(T(n.prototype),"destroy",this).call(this)}}]),n}(),Qe=function(e,t){if(e){for(var n=e.target,r=0,i=0;n.offsetParent;)r+=n.offsetLeft,i+=n.offsetTop,n=n.offsetParent;t[0]=e.pageX-r,t[1]=e.pageY-i}else e=window.event,t[0]=e.x,t[1]=e.y;return t},We=function(e){I(n,z);var t=m(n);function n(e){var r,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return b(this,n),(r=t.call(this,"AngleMeasurements",e))._container=i.container||document.body,r._control=new je(g(r)),r._measurements={},r.defaultColor=void 0!==i.defaultColor?i.defaultColor:"#00BBFF",r.defaultLabelsVisible=!1!==i.defaultLabelsVisible,r.zIndex=i.zIndex||1e4,r._onMouseOver=function(e,t){r.fire("mouseOver",{plugin:g(r),angleMeasurement:t,measurement:t,event:e})},r._onMouseLeave=function(e,t){r.fire("mouseLeave",{plugin:g(r),angleMeasurement:t,measurement:t,event:e})},r._onContextMenu=function(e,t){r.fire("contextMenu",{plugin:g(r),angleMeasurement:t,measurement:t,event:e})},r}return P(n,[{key:"getContainerElement",value:function(){return this._container}},{key:"send",value:function(e,t){}},{key:"control",get:function(){return this._control}},{key:"measurements",get:function(){return this._measurements}},{key:"createMeasurement",value:function(){var e=this,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.viewer.scene.components[t.id]&&(this.error("Viewer scene component with this ID already exists: "+t.id),delete t.id);var n=t.origin,r=t.corner,i=t.target,a=new Ve(this,{id:t.id,plugin:this,container:this._container,origin:{entity:n.entity,worldPos:n.worldPos},corner:{entity:r.entity,worldPos:r.worldPos},target:{entity:i.entity,worldPos:i.worldPos},visible:t.visible,originVisible:!0,originWireVisible:!0,cornerVisible:!0,targetWireVisible:!0,targetVisible:!0,onMouseOver:this._onMouseOver,onMouseLeave:this._onMouseLeave,onContextMenu:this._onContextMenu});return this._measurements[a.id]=a,a.on("destroyed",(function(){delete e._measurements[a.id]})),this.fire("measurementCreated",a),a}},{key:"destroyMeasurement",value:function(e){var t=this._measurements[e];t?(t.destroy(),this.fire("measurementDestroyed",t)):this.log("AngleMeasurement not found: "+e)}},{key:"setLabelsShown",value:function(e){for(var t=0,n=Object.entries(this.measurements);t<n.length;t++){var r=p(n[t],2);r[0];r[1].labelShown=e}}},{key:"clear",value:function(){for(var e=Object.keys(this._measurements),t=0,n=e.length;t<n;t++)this.destroyMeasurement(e[t])}},{key:"destroy",value:function(){this.clear(),v(T(n.prototype),"destroy",this).call(this)}}]),n}(),ze=function(e){I(n,Me);var t=m(n);function n(e,r){var i;if(b(this,n),(i=t.call(this,e,r)).plugin=r.plugin,i._container=r.container,!i._container)throw"config missing: container";if(!r.markerElement&&!r.markerHTML)throw"config missing: need either markerElement or markerHTML";if(!r.labelElement&&!r.labelHTML)throw"config missing: need either labelElement or labelHTML";return i._htmlDirty=!1,r.markerElement?(i._marker=r.markerElement,i._marker.addEventListener("click",i._onMouseClickedExternalMarker=function(){i.plugin.fire("markerClicked",g(i))}),i._marker.addEventListener("mouseenter",i._onMouseEnterExternalMarker=function(){i.plugin.fire("markerMouseEnter",g(i))}),i._marker.addEventListener("mouseleave",i._onMouseLeaveExternalMarker=function(){i.plugin.fire("markerMouseLeave",g(i))}),i._markerExternal=!0):(i._markerHTML=r.markerHTML,i._htmlDirty=!0,i._markerExternal=!1),r.labelElement?(i._label=r.labelElement,i._labelExternal=!0):(i._labelHTML=r.labelHTML,i._htmlDirty=!0,i._labelExternal=!1),i._markerShown=!!r.markerShown,i._labelShown=!!r.labelShown,i._values=r.values||{},i._layoutDirty=!0,i._visibilityDirty=!0,i._buildHTML(),i._onTick=i.scene.on("tick",(function(){i._htmlDirty&&(i._buildHTML(),i._htmlDirty=!1,i._layoutDirty=!0,i._visibilityDirty=!0),(i._layoutDirty||i._visibilityDirty)&&(i._markerShown||i._labelShown)&&(i._updatePosition(),i._layoutDirty=!1),i._visibilityDirty&&(i._marker.style.visibility=i.visible&&i._markerShown?"visible":"hidden",i._label.style.visibility=i.visible&&i._markerShown&&i._labelShown?"visible":"hidden",i._visibilityDirty=!1)})),i.on("canvasPos",(function(){i._layoutDirty=!0})),i.on("visible",(function(){i._visibilityDirty=!0})),i.setMarkerShown(!1!==r.markerShown),i.setLabelShown(r.labelShown),i.eye=r.eye?r.eye.slice():null,i.look=r.look?r.look.slice():null,i.up=r.up?r.up.slice():null,i.projection=r.projection,i}return P(n,[{key:"_buildHTML",value:function(){var e=this;if(!this._markerExternal){this._marker&&(this._container.removeChild(this._marker),this._marker=null);var t=this._markerHTML||"<p></p>";ae.isArray(t)&&(t=t.join("")),t=this._renderTemplate(t);var n=document.createRange().createContextualFragment(t);this._marker=n.firstChild,this._container.appendChild(this._marker),this._marker.style.visibility=this._markerShown?"visible":"hidden",this._marker.addEventListener("click",(function(){e.plugin.fire("markerClicked",e)})),this._marker.addEventListener("mouseenter",(function(){e.plugin.fire("markerMouseEnter",e)})),this._marker.addEventListener("mouseleave",(function(){e.plugin.fire("markerMouseLeave",e)})),this._marker.addEventListener("wheel",(function(t){e.plugin.viewer.scene.canvas.canvas.dispatchEvent(new WheelEvent("wheel",t))}))}if(!this._labelExternal){this._label&&(this._container.removeChild(this._label),this._label=null);var r=this._labelHTML||"<p></p>";ae.isArray(r)&&(r=r.join("")),r=this._renderTemplate(r);var i=document.createRange().createContextualFragment(r);this._label=i.firstChild,this._container.appendChild(this._label),this._label.style.visibility=this._markerShown&&this._labelShown?"visible":"hidden",this._label.addEventListener("wheel",(function(t){e.plugin.viewer.scene.canvas.canvas.dispatchEvent(new WheelEvent("wheel",t))}))}}},{key:"_updatePosition",value:function(){var e=this.scene.canvas.boundary,t=e[0],n=e[1],r=this.canvasPos;this._marker.style.left=Math.floor(t+r[0])-12+"px",this._marker.style.top=Math.floor(n+r[1])-12+"px",this._marker.style["z-index"]=90005+Math.floor(this._viewPos[2])+1;this._label.style.left=20+Math.floor(t+r[0]+20)+"px",this._label.style.top=Math.floor(n+r[1]+-17)+"px",this._label.style["z-index"]=90005+Math.floor(this._viewPos[2])+1}},{key:"_renderTemplate",value:function(e){for(var t in this._values)if(this._values.hasOwnProperty(t)){var n=this._values[t];e=e.replace(new RegExp("{{"+t+"}}","g"),n)}return e}},{key:"setMarkerShown",value:function(e){e=!!e,this._markerShown!==e&&(this._markerShown=e,this._visibilityDirty=!0)}},{key:"getMarkerShown",value:function(){return this._markerShown}},{key:"setLabelShown",value:function(e){e=!!e,this._labelShown!==e&&(this._labelShown=e,this._visibilityDirty=!0)}},{key:"getLabelShown",value:function(){return this._labelShown}},{key:"setField",value:function(e,t){this._values[e]=t||"",this._htmlDirty=!0}},{key:"getField",value:function(e){return this._values[e]}},{key:"setValues",value:function(e){for(var t in e)if(e.hasOwnProperty(t)){var n=e[t];this.setField(t,n)}}},{key:"getValues",value:function(){return this._values}},{key:"destroy",value:function(){this._marker&&(this._markerExternal?(this._marker.removeEventListener("click",this._onMouseClickedExternalMarker),this._marker.removeEventListener("mouseenter",this._onMouseEnterExternalMarker),this._marker.removeEventListener("mouseleave",this._onMouseLeaveExternalMarker),this._marker=null):this._marker.parentNode.removeChild(this._marker)),this._label&&(this._labelExternal||this._label.parentNode.removeChild(this._label),this._label=null),this.scene.off(this._onTick),v(T(n.prototype),"destroy",this).call(this)}}]),n}(),Ke=Z.vec3(),Ye=Z.vec3(),Xe=Z.vec3(),qe=function(e){I(n,z);var t=m(n);function n(e,r){var i;return b(this,n),(i=t.call(this,"Annotations",e))._labelHTML=r.labelHTML||"<div></div>",i._markerHTML=r.markerHTML||"<div></div>",i._container=r.container||document.body,i._values=r.values||{},i.annotations={},i.surfaceOffset=r.surfaceOffset,i}return P(n,[{key:"getContainerElement",value:function(){return this._container}},{key:"send",value:function(e,t){if("clearAnnotations"===e)this.clear()}},{key:"surfaceOffset",get:function(){return this._surfaceOffset},set:function(e){null==e&&(e=.3),this._surfaceOffset=e}},{key:"createAnnotation",value:function(e){var t,n,r=this;if(this.viewer.scene.components[e.id]&&(this.error("Viewer component with this ID already exists: "+e.id),delete e.id),e.pickResult=e.pickResult||e.pickRecord,e.pickResult){var i=e.pickResult;if(i.worldPos&&i.worldNormal){var a=Z.normalizeVec3(i.worldNormal,Ke),s=Z.mulVec3Scalar(a,this._surfaceOffset,Ye);t=Z.addVec3(i.worldPos,s,Xe),n=i.entity}else this.error("Param 'pickResult' does not have both worldPos and worldNormal")}else t=e.worldPos,n=e.entity;var o=null;e.markerElementId&&((o=document.getElementById(e.markerElementId))||this.error("Can't find DOM element for 'markerElementId' value '"+e.markerElementId+"' - defaulting to internally-generated empty DIV"));var l=null;e.labelElementId&&((l=document.getElementById(e.labelElementId))||this.error("Can't find DOM element for 'labelElementId' value '"+e.labelElementId+"' - defaulting to internally-generated empty DIV"));var u=new ze(this.viewer.scene,{id:e.id,plugin:this,entity:n,worldPos:t,container:this._container,markerElement:o,labelElement:l,markerHTML:e.markerHTML||this._markerHTML,labelHTML:e.labelHTML||this._labelHTML,occludable:e.occludable,values:ae.apply(e.values,ae.apply(this._values,{})),markerShown:e.markerShown,labelShown:e.labelShown,eye:e.eye,look:e.look,up:e.up,projection:e.projection,visible:!1!==e.visible});return this.annotations[u.id]=u,u.on("destroyed",(function(){delete r.annotations[u.id],r.fire("annotationDestroyed",u.id)})),this.fire("annotationCreated",u.id),u}},{key:"destroyAnnotation",value:function(e){var t=this.annotations[e];t?t.destroy():this.log("Annotation not found: "+e)}},{key:"clear",value:function(){for(var e=Object.keys(this.annotations),t=0,n=e.length;t<n;t++)this.destroyAnnotation(e[t])}},{key:"destroy",value:function(){this.clear(),v(T(n.prototype),"destroy",this).call(this)}}]),n}(),Je=function(e){I(n,ve);var t=m(n);function n(e){var r,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return b(this,n),(r=t.call(this,e,i))._canvas=i.canvas,r._element=null,r._isCustom=!1,i.elementId&&(r._element=document.getElementById(i.elementId),r._element?r._adjustPosition():r.error("Can't find given Spinner HTML element: '"+i.elementId+"' - will automatically create default element")),r._element||r._createDefaultSpinner(),r.processes=0,r}return P(n,[{key:"type",get:function(){return"Spinner"}},{key:"_createDefaultSpinner",value:function(){this._injectDefaultCSS();var e=document.createElement("div"),t=e.style;t["z-index"]="9000",t.position="absolute",e.innerHTML='<div class="sk-fading-circle"> <div class="sk-circle1 sk-circle"></div> <div class="sk-circle2 sk-circle"></div> <div class="sk-circle3 sk-circle"></div> <div class="sk-circle4 sk-circle"></div> <div class="sk-circle5 sk-circle"></div> <div class="sk-circle6 sk-circle"></div> <div class="sk-circle7 sk-circle"></div> <div class="sk-circle8 sk-circle"></div> <div class="sk-circle9 sk-circle"></div> <div class="sk-circle10 sk-circle"></div> <div class="sk-circle11 sk-circle"></div> <div class="sk-circle12 sk-circle"></div> </div>',this._canvas.parentElement.appendChild(e),this._element=e,this._isCustom=!1,this._adjustPosition()}},{key:"_injectDefaultCSS",value:function(){var e="xeokit-spinner-css";if(!document.getElementById(e)){var t=document.createElement("style");t.innerHTML=".sk-fading-circle { background: transparent; margin: 20px auto; width: 50px; height:50px; position: relative; } .sk-fading-circle .sk-circle { width: 120%; height: 120%; position: absolute; left: 0; top: 0; } .sk-fading-circle .sk-circle:before { content: ''; display: block; margin: 0 auto; width: 15%; height: 15%; background-color: #ff8800; border-radius: 100%; -webkit-animation: sk-circleFadeDelay 1.2s infinite ease-in-out both; animation: sk-circleFadeDelay 1.2s infinite ease-in-out both; } .sk-fading-circle .sk-circle2 { -webkit-transform: rotate(30deg); -ms-transform: rotate(30deg); transform: rotate(30deg); } .sk-fading-circle .sk-circle3 { -webkit-transform: rotate(60deg); -ms-transform: rotate(60deg); transform: rotate(60deg); } .sk-fading-circle .sk-circle4 { -webkit-transform: rotate(90deg); -ms-transform: rotate(90deg); transform: rotate(90deg); } .sk-fading-circle .sk-circle5 { -webkit-transform: rotate(120deg); -ms-transform: rotate(120deg); transform: rotate(120deg); } .sk-fading-circle .sk-circle6 { -webkit-transform: rotate(150deg); -ms-transform: rotate(150deg); transform: rotate(150deg); } .sk-fading-circle .sk-circle7 { -webkit-transform: rotate(180deg); -ms-transform: rotate(180deg); transform: rotate(180deg); } .sk-fading-circle .sk-circle8 { -webkit-transform: rotate(210deg); -ms-transform: rotate(210deg); transform: rotate(210deg); } .sk-fading-circle .sk-circle9 { -webkit-transform: rotate(240deg); -ms-transform: rotate(240deg); transform: rotate(240deg); } .sk-fading-circle .sk-circle10 { -webkit-transform: rotate(270deg); -ms-transform: rotate(270deg); transform: rotate(270deg); } .sk-fading-circle .sk-circle11 { -webkit-transform: rotate(300deg); -ms-transform: rotate(300deg); transform: rotate(300deg); } .sk-fading-circle .sk-circle12 { -webkit-transform: rotate(330deg); -ms-transform: rotate(330deg); transform: rotate(330deg); } .sk-fading-circle .sk-circle2:before { -webkit-animation-delay: -1.1s; animation-delay: -1.1s; } .sk-fading-circle .sk-circle3:before { -webkit-animation-delay: -1s; animation-delay: -1s; } .sk-fading-circle .sk-circle4:before { -webkit-animation-delay: -0.9s; animation-delay: -0.9s; } .sk-fading-circle .sk-circle5:before { -webkit-animation-delay: -0.8s; animation-delay: -0.8s; } .sk-fading-circle .sk-circle6:before { -webkit-animation-delay: -0.7s; animation-delay: -0.7s; } .sk-fading-circle .sk-circle7:before { -webkit-animation-delay: -0.6s; animation-delay: -0.6s; } .sk-fading-circle .sk-circle8:before { -webkit-animation-delay: -0.5s; animation-delay: -0.5s; } .sk-fading-circle .sk-circle9:before { -webkit-animation-delay: -0.4s; animation-delay: -0.4s; } .sk-fading-circle .sk-circle10:before { -webkit-animation-delay: -0.3s; animation-delay: -0.3s; } .sk-fading-circle .sk-circle11:before { -webkit-animation-delay: -0.2s; animation-delay: -0.2s; } .sk-fading-circle .sk-circle12:before { -webkit-animation-delay: -0.1s; animation-delay: -0.1s; } @-webkit-keyframes sk-circleFadeDelay { 0%, 39%, 100% { opacity: 0; } 40% { opacity: 1; } } @keyframes sk-circleFadeDelay { 0%, 39%, 100% { opacity: 0; } 40% { opacity: 1; } }",t.id=e,document.body.appendChild(t)}}},{key:"_adjustPosition",value:function(){if(!this._isCustom){var e=this._canvas,t=this._element,n=t.style;n.left=e.offsetLeft+.5*e.clientWidth-.5*t.clientWidth+"px",n.top=e.offsetTop+.5*e.clientHeight-.5*t.clientHeight+"px"}}},{key:"processes",get:function(){return this._processes},set:function(e){if(e=e||0,this._processes!==e&&!(e<0)){var t=this._processes;this._processes=e;var n=this._element;n&&(n.style.visibility=this._processes>0?"visible":"hidden"),this.fire("processes",this._processes),0===this._processes&&this._processes!==t&&this.fire("zeroProcesses",this._processes)}}},{key:"_destroy",value:function(){this._element&&!this._isCustom&&(this._element.parentNode.removeChild(this._element),this._element=null);var e=document.getElementById("xeokit-spinner-css");e&&e.parentNode.removeChild(e)}}]),n}(),Ze={WEBGL:!1,SUPPORTED_EXTENSIONS:{}},$e=document.createElement("canvas");if($e){var et=$e.getContext("webgl",{antialias:!0})||$e.getContext("experimental-webgl",{antialias:!0});Ze.WEBGL=!!et,Ze.WEBGL&&(Ze.ANTIALIAS=et.getContextAttributes().antialias,et.getShaderPrecisionFormat?et.getShaderPrecisionFormat(et.FRAGMENT_SHADER,et.HIGH_FLOAT).precision>0?Ze.FS_MAX_FLOAT_PRECISION="highp":et.getShaderPrecisionFormat(et.FRAGMENT_SHADER,et.MEDIUM_FLOAT).precision>0?Ze.FS_MAX_FLOAT_PRECISION="mediump":Ze.FS_MAX_FLOAT_PRECISION="lowp":Ze.FS_MAX_FLOAT_PRECISION="mediump",Ze.DEPTH_BUFFER_BITS=et.getParameter(et.DEPTH_BITS),Ze.MAX_TEXTURE_SIZE=et.getParameter(et.MAX_TEXTURE_SIZE),Ze.MAX_CUBE_MAP_SIZE=et.getParameter(et.MAX_CUBE_MAP_TEXTURE_SIZE),Ze.MAX_RENDERBUFFER_SIZE=et.getParameter(et.MAX_RENDERBUFFER_SIZE),Ze.MAX_TEXTURE_UNITS=et.getParameter(et.MAX_COMBINED_TEXTURE_IMAGE_UNITS),Ze.MAX_TEXTURE_IMAGE_UNITS=et.getParameter(et.MAX_TEXTURE_IMAGE_UNITS),Ze.MAX_VERTEX_ATTRIBS=et.getParameter(et.MAX_VERTEX_ATTRIBS),Ze.MAX_VERTEX_UNIFORM_VECTORS=et.getParameter(et.MAX_VERTEX_UNIFORM_VECTORS),Ze.MAX_FRAGMENT_UNIFORM_VECTORS=et.getParameter(et.MAX_FRAGMENT_UNIFORM_VECTORS),Ze.MAX_VARYING_VECTORS=et.getParameter(et.MAX_VARYING_VECTORS),et.getSupportedExtensions().forEach((function(e){Ze.SUPPORTED_EXTENSIONS[e]=!0})))}var tt=["webgl2","experimental-webgl","webkit-3d","moz-webgl","moz-glweb20"],nt=function(e){I(n,ve);var t=m(n);function n(e){var r,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};b(this,n),(r=t.call(this,e,i))._backgroundColor=Z.vec3([i.backgroundColor?i.backgroundColor[0]:1,i.backgroundColor?i.backgroundColor[1]:1,i.backgroundColor?i.backgroundColor[2]:1]),r._backgroundColorFromAmbientLight=!!i.backgroundColorFromAmbientLight,r.canvas=i.canvas,r.gl=null,r.webgl2=!1,r.transparent=!!i.transparent,r.contextAttr=i.contextAttr||{},r.contextAttr.alpha=r.transparent,r.contextAttr.preserveDrawingBuffer=!!r.contextAttr.preserveDrawingBuffer,r.contextAttr.stencil=!1,r.contextAttr.premultipliedAlpha=!!r.contextAttr.premultipliedAlpha,r.contextAttr.antialias=!1!==r.contextAttr.antialias,r.resolutionScale=i.resolutionScale,r.canvas.width=Math.round(r.canvas.clientWidth*r._resolutionScale),r.canvas.height=Math.round(r.canvas.clientHeight*r._resolutionScale),r.boundary=[r.canvas.offsetLeft,r.canvas.offsetTop,r.canvas.clientWidth,r.canvas.clientHeight],r._initWebGL(i);var a=g(r);r.canvas.addEventListener("webglcontextlost",r._webglcontextlostListener=function(e){console.time("webglcontextrestored"),a.scene._webglContextLost(),a.fire("webglcontextlost"),e.preventDefault()},!1),r.canvas.addEventListener("webglcontextrestored",r._webglcontextrestoredListener=function(e){a._initWebGL(),a.gl&&(a.scene._webglContextRestored(a.gl),a.fire("webglcontextrestored",a.gl),e.preventDefault()),console.timeEnd("webglcontextrestored")},!1);var s=!0,o=new ResizeObserver((function(e){var t,n=f(e);try{for(n.s();!(t=n.n()).done;){t.value.contentBoxSize&&(s=!0)}}catch(e){n.e(e)}finally{n.f()}}));return o.observe(r.canvas),r._tick=r.scene.on("tick",(function(){s&&(s=!1,a.canvas.width=Math.round(a.canvas.clientWidth*a._resolutionScale),a.canvas.height=Math.round(a.canvas.clientHeight*a._resolutionScale),a.boundary[0]=a.canvas.offsetLeft,a.boundary[1]=a.canvas.offsetTop,a.boundary[2]=a.canvas.clientWidth,a.boundary[3]=a.canvas.clientHeight,a.fire("boundary",a.boundary))})),r._spinner=new Je(r.scene,{canvas:r.canvas,elementId:i.spinnerElementId}),r}return P(n,[{key:"type",get:function(){return"Canvas"}},{key:"backgroundColorFromAmbientLight",get:function(){return this._backgroundColorFromAmbientLight},set:function(e){this._backgroundColorFromAmbientLight=!1!==e,this.glRedraw()}},{key:"backgroundColor",get:function(){return this._backgroundColor},set:function(e){e?(this._backgroundColor[0]=e[0],this._backgroundColor[1]=e[1],this._backgroundColor[2]=e[2]):(this._backgroundColor[0]=1,this._backgroundColor[1]=1,this._backgroundColor[2]=1),this.glRedraw()}},{key:"resolutionScale",get:function(){return this._resolutionScale},set:function(e){if((e=e||1)!==this._resolutionScale){this._resolutionScale=e;var t=this.canvas;t.width=Math.round(t.clientWidth*this._resolutionScale),t.height=Math.round(t.clientHeight*this._resolutionScale),this.glRedraw()}}},{key:"spinner",get:function(){return this._spinner}},{key:"_createCanvas",value:function(){var e="xeokit-canvas-"+Z.createUUID(),t=document.getElementsByTagName("body")[0],n=document.createElement("div"),r=n.style;r.height="100%",r.width="100%",r.padding="0",r.margin="0",r.background="rgba(0,0,0,0);",r.float="left",r.left="0",r.top="0",r.position="absolute",r.opacity="1.0",r["z-index"]="-10000",n.innerHTML+='<canvas id="'+e+'" style="width: 100%; height: 100%; float: left; margin: 0; padding: 0;"></canvas>',t.appendChild(n),this.canvas=document.getElementById(e)}},{key:"_getElementXY",value:function(e){for(var t=0,n=0;e;)t+=e.offsetLeft-e.scrollLeft,n+=e.offsetTop-e.scrollTop,e=e.offsetParent;return{x:t,y:n}}},{key:"_initWebGL",value:function(){if(!this.gl)for(var e=0;!this.gl&&e<tt.length;e++)try{this.gl=this.canvas.getContext(tt[e],this.contextAttr)}catch(e){}this.gl||(this.error("Failed to get a WebGL context"),this.fire("webglContextFailed",!0,!0));var t=this.gl,n="__",r=t.activeTexture;t.activeTexture=function(e){n!==e&&(n=e,r.call(this,e))};var i={},a=t.bindTexture;t.bindTexture=function(e,t){i[n]!==t&&(i[n]=t,a.call(this,e,t))},this.gl&&this.webgl2&&(this.gl.hint(this.gl.FRAGMENT_SHADER_DERIVATIVE_HINT,this.gl.FASTEST),this.gl,WebGL2RenderingContext)}},{key:"getSnapshot",value:function(e){throw"Canvas#getSnapshot() has been replaced by Viewer#getSnapshot() - use that method instead."}},{key:"readPixels",value:function(e,t,n,r){return this.scene._renderer.readPixels(e,t,n,r)}},{key:"loseWebGLContext",value:function(){this.canvas.loseContext&&this.canvas.loseContext()}},{key:"destroy",value:function(){this.scene.off(this._tick),this._spinner._destroy(),this.canvas.removeEventListener("webglcontextlost",this._webglcontextlostListener),this.canvas.removeEventListener("webglcontextrestored",this._webglcontextrestoredListener),this.gl=null,v(T(n.prototype),"destroy",this).call(this)}}]),n}(),rt=function(){function e(t){b(this,e),this._scene=t,this._matPool=[],this._matPoolNextFreeIndex=0,this._rtcViewMats={},this._rtcPickViewMats={},this.reset()}return P(e,[{key:"reset",value:function(){this._matPoolNextFreeIndex=0,this._rtcViewMats={},this._rtcPickViewMats={},this.gl=this._scene.canvas.gl,this.lastProgramId=null,this.pbrEnabled=!1,this.colorTextureEnabled=!1,this.withSAO=!1,this.backfaces=!1,this.frontface=!0,this.textureUnit=0,this.drawElements=0,this.drawArrays=0,this.useProgram=0,this.bindTexture=0,this.bindArray=0,this.pass=0,this.shadowViewMatrix=null,this.shadowProjMatrix=null,this.pickViewMatrix=null,this.pickProjMatrix=null,this.pickZNear=.01,this.pickZFar=5e3,this.pickInvisible=!1,this.pickElementsCount=null,this.pickElementsOffset=null,this.lineWidth=1,this.snapPickLayerParams={},this.snapPickLayerNumber=0,this.snapPickCoordinateScale=Z.vec3(),this.snapPickOrigin=Z.vec3()}},{key:"getRTCViewMatrix",value:function(e,t){var n=this._rtcViewMats[e];return n||(n=this._getNewMat(),Ie(this._scene.camera.viewMatrix,t,n),this._rtcViewMats[e]=n),n}},{key:"getRTCPickViewMatrix",value:function(e,t){var n=this._rtcPickViewMats[e];if(!n){n=this._getNewMat();var r=this.pickViewMatrix||this._scene.camera.viewMatrix;Ie(r,t,n),this._rtcPickViewMats[e]=n}return n}},{key:"_getNewMat",value:function(){var e=this._matPool[this._matPoolNextFreeIndex];return e||(e=Z.mat4(),this._matPool[this._matPoolNextFreeIndex]=e),this._matPoolNextFreeIndex++,e}}]),e}(),it=function(){function e(){b(this,e),this.entity=null,this.primitive=null,this.primIndex=-1,this.pickSurfacePrecision=!1,this.touchInput=!1,this._canvasPos=new Int16Array([0,0]),this._origin=new Float64Array([0,0,0]),this._direction=new Float64Array([0,0,0]),this._indices=new Int32Array(3),this._localPos=new Float64Array([0,0,0]),this._worldPos=new Float64Array([0,0,0]),this._viewPos=new Float64Array([0,0,0]),this._bary=new Float64Array([0,0,0]),this._worldNormal=new Float64Array([0,0,0]),this._uv=new Float64Array([0,0]),this.reset()}return P(e,[{key:"canvasPos",get:function(){return this._gotCanvasPos?this._canvasPos:null},set:function(e){e?(this._canvasPos[0]=e[0],this._canvasPos[1]=e[1],this._gotCanvasPos=!0):this._gotCanvasPos=!1}},{key:"origin",get:function(){return this._gotOrigin?this._origin:null},set:function(e){e?(this._origin[0]=e[0],this._origin[1]=e[1],this._origin[2]=e[2],this._gotOrigin=!0):this._gotOrigin=!1}},{key:"direction",get:function(){return this._gotDirection?this._direction:null},set:function(e){e?(this._direction[0]=e[0],this._direction[1]=e[1],this._direction[2]=e[2],this._gotDirection=!0):this._gotDirection=!1}},{key:"indices",get:function(){return this.entity&&this._gotIndices?this._indices:null},set:function(e){e?(this._indices[0]=e[0],this._indices[1]=e[1],this._indices[2]=e[2],this._gotIndices=!0):this._gotIndices=!1}},{key:"localPos",get:function(){return this.entity&&this._gotLocalPos?this._localPos:null},set:function(e){e?(this._localPos[0]=e[0],this._localPos[1]=e[1],this._localPos[2]=e[2],this._gotLocalPos=!0):this._gotLocalPos=!1}},{key:"worldPos",get:function(){return this._gotWorldPos?this._worldPos:null},set:function(e){e?(this._worldPos[0]=e[0],this._worldPos[1]=e[1],this._worldPos[2]=e[2],this._gotWorldPos=!0):this._gotWorldPos=!1}},{key:"viewPos",get:function(){return this.entity&&this._gotViewPos?this._viewPos:null},set:function(e){e?(this._viewPos[0]=e[0],this._viewPos[1]=e[1],this._viewPos[2]=e[2],this._gotViewPos=!0):this._gotViewPos=!1}},{key:"bary",get:function(){return this.entity&&this._gotBary?this._bary:null},set:function(e){e?(this._bary[0]=e[0],this._bary[1]=e[1],this._bary[2]=e[2],this._gotBary=!0):this._gotBary=!1}},{key:"worldNormal",get:function(){return this.entity&&this._gotWorldNormal?this._worldNormal:null},set:function(e){e?(this._worldNormal[0]=e[0],this._worldNormal[1]=e[1],this._worldNormal[2]=e[2],this._gotWorldNormal=!0):this._gotWorldNormal=!1}},{key:"uv",get:function(){return this.entity&&this._gotUV?this._uv:null},set:function(e){e?(this._uv[0]=e[0],this._uv[1]=e[1],this._gotUV=!0):this._gotUV=!1}},{key:"reset",value:function(){this.entity=null,this.primIndex=-1,this.primitive=null,this.pickSurfacePrecision=!1,this._gotCanvasPos=!1,this._gotOrigin=!1,this._gotDirection=!1,this._gotIndices=!1,this._gotLocalPos=!1,this._gotWorldPos=!1,this._gotViewPos=!1,this._gotBary=!1,this._gotWorldNormal=!1,this._gotUV=!1,this.touchInput=!1}}]),e}(),at=function(){function e(t,n,r){if(b(this,e),this.allocated=!1,this.compiled=!1,this.handle=t.createShader(n),this.handle){if(this.allocated=!0,t.shaderSource(this.handle,r),t.compileShader(this.handle),this.compiled=t.getShaderParameter(this.handle,t.COMPILE_STATUS),!this.compiled&&!t.isContextLost()){for(var i=r.split("\n"),a=[],s=0;s<i.length;s++)a.push(s+1+": "+i[s]+"\n");this.errors=[],this.errors.push(""),this.errors.push(t.getShaderInfoLog(this.handle)),this.errors=this.errors.concat(a.join(""))}}else this.errors=["Failed to allocate"]}return P(e,[{key:"destroy",value:function(){}}]),e}(),st=P((function e(t,n){b(this,e),this.bindTexture=function(e,r){return!!e.bind(r)&&(t.uniform1i(n,r),!0)}})),ot=function(){function e(t,n){b(this,e),this._gl=t,this.location=n}return P(e,[{key:"bindArrayBuffer",value:function(e){e&&(e.bind(),this._gl.enableVertexAttribArray(this.location),this._gl.vertexAttribPointer(this.location,e.itemSize,e.itemType,e.normalized,e.stride,e.offset))}}]),e}(),lt=new G({});function ut(e){for(var t,n,r=[],i=0,a=e.length;i<a;i++)(n=(t=e[i]).indexOf("/"))>0&&"/"===t.charAt(n+1)&&(t=t.substring(0,n)),r.push(t);return r.join("\n")}function ct(e){console.error(e.join("\n"))}var ft=function(){function e(t,n){b(this,e),this.id=lt.addItem({}),this.source=n,this.init(t)}return P(e,[{key:"init",value:function(e){if(this.gl=e,this.allocated=!1,this.compiled=!1,this.linked=!1,this.validated=!1,this.errors=null,this.uniforms={},this.samplers={},this.attributes={},this._vertexShader=new at(e,e.VERTEX_SHADER,ut(this.source.vertex)),this._fragmentShader=new at(e,e.FRAGMENT_SHADER,ut(this.source.fragment)),!this._vertexShader.allocated)return this.errors=["Vertex shader failed to allocate"].concat(this._vertexShader.errors),void ct(this.errors);if(!this._fragmentShader.allocated)return this.errors=["Fragment shader failed to allocate"].concat(this._fragmentShader.errors),void ct(this.errors);if(this.allocated=!0,!this._vertexShader.compiled)return this.errors=["Vertex shader failed to compile"].concat(this._vertexShader.errors),void ct(this.errors);if(!this._fragmentShader.compiled)return this.errors=["Fragment shader failed to compile"].concat(this._fragmentShader.errors),void ct(this.errors);var t,n,r,i,a;if(this.compiled=!0,this.handle=e.createProgram(),this.handle){if(e.attachShader(this.handle,this._vertexShader.handle),e.attachShader(this.handle,this._fragmentShader.handle),e.linkProgram(this.handle),this.linked=e.getProgramParameter(this.handle,e.LINK_STATUS),this.validated=!0,!this.linked||!this.validated)return this.errors=[],this.errors.push(""),this.errors.push(e.getProgramInfoLog(this.handle)),this.errors.push("\nVertex shader:\n"),this.errors=this.errors.concat(this.source.vertex),this.errors.push("\nFragment shader:\n"),this.errors=this.errors.concat(this.source.fragment),void ct(this.errors);var s=e.getProgramParameter(this.handle,e.ACTIVE_UNIFORMS);for(n=0;n<s;++n)(r=e.getActiveUniform(this.handle,n))&&("\0"===(i=r.name)[i.length-1]&&(i=i.substr(0,i.length-1)),a=e.getUniformLocation(this.handle,i),r.type===e.SAMPLER_2D||r.type===e.SAMPLER_CUBE||35682===r.type||e instanceof WebGL2RenderingContext&&(r.type===e.UNSIGNED_INT_SAMPLER_2D||r.type===e.INT_SAMPLER_2D)?this.samplers[i]=new st(e,a):this.uniforms[i]=a);var o=e.getProgramParameter(this.handle,e.ACTIVE_ATTRIBUTES);for(n=0;n<o;n++)(t=e.getActiveAttrib(this.handle,n))&&(a=e.getAttribLocation(this.handle,t.name),this.attributes[t.name]=new ot(e,a));this.allocated=!0}else this.errors=["Failed to allocate program"]}},{key:"bind",value:function(){this.allocated&&this.gl.useProgram(this.handle)}},{key:"getLocation",value:function(e){if(this.allocated)return this.uniforms[e]}},{key:"getAttribute",value:function(e){if(this.allocated)return this.attributes[e]}},{key:"bindTexture",value:function(e,t,n){if(!this.allocated)return!1;var r=this.samplers[e];return!!r&&r.bindTexture(t,n)}},{key:"destroy",value:function(){this.allocated&&(lt.removeItem(this.id),this.gl.deleteProgram(this.handle),this.gl.deleteShader(this._vertexShader.handle),this.gl.deleteShader(this._fragmentShader.handle),this.handle=null,this.attributes=null,this.uniforms=null,this.samplers=null,this.allocated=!1)}}]),e}(),pt=function(){function e(t,n,r,i,a,s,o,l,u){switch(b(this,e),this._gl=t,this.type=n,this.allocated=!1,r.constructor){case Uint8Array:this.itemType=t.UNSIGNED_BYTE,this.itemByteSize=1;break;case Int8Array:this.itemType=t.BYTE,this.itemByteSize=1;break;case Uint16Array:this.itemType=t.UNSIGNED_SHORT,this.itemByteSize=2;break;case Int16Array:this.itemType=t.SHORT,this.itemByteSize=2;break;case Uint32Array:this.itemType=t.UNSIGNED_INT,this.itemByteSize=4;break;case Int32Array:this.itemType=t.INT,this.itemByteSize=4;break;default:this.itemType=t.FLOAT,this.itemByteSize=4}this.usage=s,this.length=0,this.dataLength=i,this.numItems=0,this.itemSize=a,this.normalized=!!o,this.stride=l||0,this.offset=u||0,this._allocate(r)}return P(e,[{key:"_allocate",value:function(e){if(this.allocated=!1,this._handle=this._gl.createBuffer(),!this._handle)throw"Failed to allocate WebGL ArrayBuffer";this._handle&&(this._gl.bindBuffer(this.type,this._handle),this._gl.bufferData(this.type,e.length>this.dataLength?e.slice(0,this.dataLength):e,this.usage),this._gl.bindBuffer(this.type,null),this.length=e.length,this.numItems=this.length/this.itemSize,this.allocated=!0)}},{key:"setData",value:function(e,t){this.allocated&&(e.length+(t||0)>this.length?(this.destroy(),this._allocate(e)):(this._gl.bindBuffer(this.type,this._handle),t||0===t?this._gl.bufferSubData(this.type,t*this.itemByteSize,e):this._gl.bufferData(this.type,e,this.usage),this._gl.bindBuffer(this.type,null)))}},{key:"bind",value:function(){this.allocated&&this._gl.bindBuffer(this.type,this._handle)}},{key:"unbind",value:function(){this.allocated&&this._gl.bindBuffer(this.type,null)}},{key:"destroy",value:function(){this.allocated&&(this._gl.deleteBuffer(this._handle),this._handle=null,this.allocated=!1)}}]),e}(),At=function(){function e(t,n){b(this,e),this.scene=t,this.aabb=Z.AABB3(),this.origin=Z.vec3(n),this.originHash=this.origin.join(),this.numMarkers=0,this.markers={},this.markerList=[],this.markerIndices={},this.positions=[],this.indices=[],this.positionsBuf=null,this.lenPositionsBuf=0,this.indicesBuf=null,this.sectionPlanesActive=[],this.culledBySectionPlanes=!1,this.occlusionTestList=[],this.lenOcclusionTestList=0,this.pixels=[],this.aabbDirty=!1,this.markerListDirty=!1,this.positionsDirty=!0,this.occlusionTestListDirty=!1}return P(e,[{key:"addMarker",value:function(e){this.markers[e.id]=e,this.markerListDirty=!0,this.numMarkers++}},{key:"markerWorldPosUpdated",value:function(e){if(this.markers[e.id]){var t=this.markerIndices[e.id];this.positions[3*t+0]=e.worldPos[0],this.positions[3*t+1]=e.worldPos[1],this.positions[3*t+2]=e.worldPos[2],this.positionsDirty=!0}}},{key:"removeMarker",value:function(e){delete this.markers[e.id],this.markerListDirty=!0,this.numMarkers--}},{key:"update",value:function(){this.markerListDirty&&(this._buildMarkerList(),this.markerListDirty=!1,this.positionsDirty=!0,this.occlusionTestListDirty=!0),this.positionsDirty&&(this._buildPositions(),this.positionsDirty=!1,this.aabbDirty=!0,this.vbosDirty=!0),this.aabbDirty&&(this._buildAABB(),this.aabbDirty=!1),this.vbosDirty&&(this._buildVBOs(),this.vbosDirty=!1),this.occlusionTestListDirty&&this._buildOcclusionTestList(),this._updateActiveSectionPlanes()}},{key:"_buildMarkerList",value:function(){for(var e in this.numMarkers=0,this.markers)this.markers.hasOwnProperty(e)&&(this.markerList[this.numMarkers]=this.markers[e],this.markerIndices[e]=this.numMarkers,this.numMarkers++);this.markerList.length=this.numMarkers}},{key:"_buildPositions",value:function(){for(var e=0,t=0;t<this.numMarkers;t++)if(this.markerList[t]){var n=this.markerList[t].worldPos;this.positions[e++]=n[0],this.positions[e++]=n[1],this.positions[e++]=n[2],this.indices[t]=t}this.positions.length=3*this.numMarkers,this.indices.length=this.numMarkers}},{key:"_buildAABB",value:function(){var e=this.aabb;Z.collapseAABB3(e),Z.expandAABB3Points3(e,this.positions);var t=this.origin;e[0]+=t[0],e[1]+=t[1],e[2]+=t[2],e[3]+=t[0],e[4]+=t[1],e[5]+=t[2]}},{key:"_buildVBOs",value:function(){if(this.positionsBuf){if(this.lenPositionsBuf===this.positions.length)return void this.positionsBuf.setData(this.positions);this.positionsBuf.destroy(),this.positionsBuf=null,this.indicesBuf.destroy(),this.indicesBuf=null}var e=this.scene.canvas.gl,t=3*this.numMarkers,n=this.numMarkers;this.positionsBuf=new pt(e,e.ARRAY_BUFFER,new Float32Array(this.positions),t,3,e.STATIC_DRAW),this.indicesBuf=new pt(e,e.ELEMENT_ARRAY_BUFFER,new Uint16Array(this.indices),n,1,e.STATIC_DRAW),this.lenPositionsBuf=this.positions.length}},{key:"_buildOcclusionTestList",value:function(){var e=this.scene.canvas,t=this.scene.camera.perspective.near,n=e.boundary,r=n[2],i=n[3],a=0;this.lenOcclusionTestList=0;for(var s=0;s<this.numMarkers;s++){var o=this.markerList[s];if(o.viewPos[2]>-t)o._setVisible(!1);else{var l=o.canvasPos,u=l[0],c=l[1];u+10<0||c+10<0||u-10>r||c-10>i?o._setVisible(!1):!o.entity||o.entity.visible?o.occludable?(this.occlusionTestList[this.lenOcclusionTestList++]=o,this.pixels[a++]=u,this.pixels[a++]=c):o._setVisible(!0):o._setVisible(!1)}}}},{key:"_updateActiveSectionPlanes",value:function(){var e=this.scene._sectionPlanesState.sectionPlanes,t=e.length;if(t>0)for(var n=0;n<t;n++){var r=e[n];if(r.active){var i=Z.planeAABB3Intersect(r.dir,r.dist,this.aabb);if(-1===i)return void(this.culledBySectionPlanes=!0);var a=0===i;this.sectionPlanesActive[n]=a}else this.sectionPlanesActive[n]=!1}this.culledBySectionPlanes=!1}},{key:"destroy",value:function(){this.markers={},this.markerList.length=0,this.positionsBuf&&this.positionsBuf.destroy(),this.indicesBuf&&this.indicesBuf.destroy()}}]),e}(),dt=Z.vec3([1,0,0]),vt=Z.vec3(),ht=function(){function e(t,n){var r=this;b(this,e),this._scene=t,this._renderBufferManager=n,this._occlusionLayers={},this._occlusionLayersList=[],this._occlusionLayersListDirty=!1,this._shaderSource=null,this._program=null,this._shaderSourceHash=null,this._shaderSourceDirty=!0,this._programDirty=!1,this._markersToOcclusionLayersMap={},this._onCameraViewMatrix=t.camera.on("viewMatrix",(function(){r._occlusionTestListDirty=!0})),this._onCameraProjMatrix=t.camera.on("projMatrix",(function(){r._occlusionTestListDirty=!0})),this._onCanvasBoundary=t.canvas.on("boundary",(function(){r._occlusionTestListDirty=!0}))}return P(e,[{key:"addMarker",value:function(e){var t=e.origin.join(),n=this._occlusionLayers[t];n||(n=new At(this._scene,e.origin),this._occlusionLayers[n.originHash]=n,this._occlusionLayersListDirty=!0),n.addMarker(e),this._markersToOcclusionLayersMap[e.id]=n,this._occlusionTestListDirty=!0}},{key:"markerWorldPosUpdated",value:function(e){var t=this._markersToOcclusionLayersMap[e.id];if(t){var n=e.origin.join();if(n!==t.originHash){1===t.numMarkers?(t.destroy(),delete this._occlusionLayers[t.originHash],this._occlusionLayersListDirty=!0):t.removeMarker(e);var r=this._occlusionLayers[n];r||(r=new At(this._scene,e.origin),this._occlusionLayers[n]=t,this._occlusionLayersListDirty=!0),r.addMarker(e),this._markersToOcclusionLayersMap[e.id]=r}else t.markerWorldPosUpdated(e)}else e.error("Marker has not been added to OcclusionTester")}},{key:"removeMarker",value:function(e){var t=e.origin.join(),n=this._occlusionLayers[t];n&&(1===n.numMarkers?(n.destroy(),delete this._occlusionLayers[n.originHash],this._occlusionLayersListDirty=!0):n.removeMarker(e),delete this._markersToOcclusionLayersMap[e.id])}},{key:"needOcclusionTest",get:function(){return this._occlusionTestListDirty}},{key:"bindRenderBuf",value:function(){var e=[this._scene.canvas.canvas.id,this._scene._sectionPlanesState.getHash()].join(";");if(e!==this._shaderSourceHash&&(this._shaderSourceHash=e,this._shaderSourceDirty=!0),this._shaderSourceDirty&&(this._buildShaderSource(),this._shaderSourceDirty=!1,this._programDirty=!0),this._programDirty&&(this._buildProgram(),this._programDirty=!1,this._occlusionTestListDirty=!0),this._occlusionLayersListDirty&&(this._buildOcclusionLayersList(),this._occlusionLayersListDirty=!1),this._occlusionTestListDirty){for(var t=0,n=this._occlusionLayersList.length;t<n;t++){this._occlusionLayersList[t].occlusionTestListDirty=!0}this._occlusionTestListDirty=!1}this._readPixelBuf=this._renderBufferManager.getRenderBuffer("occlusionReadPix"),this._readPixelBuf.bind(),this._readPixelBuf.clear()}},{key:"_buildOcclusionLayersList",value:function(){var e=0;for(var t in this._occlusionLayers)this._occlusionLayers.hasOwnProperty(t)&&(this._occlusionLayersList[e++]=this._occlusionLayers[t]);this._occlusionLayersList.length=e}},{key:"_buildShaderSource",value:function(){this._shaderSource={vertex:this._buildVertexShaderSource(),fragment:this._buildFragmentShaderSource()}}},{key:"_buildVertexShaderSource",value:function(){var e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,n=[];return n.push("#version 300 es"),n.push("// OcclusionTester vertex shader"),n.push("in vec3 position;"),n.push("uniform mat4 modelMatrix;"),n.push("uniform mat4 viewMatrix;"),n.push("uniform mat4 projMatrix;"),e.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("out float vFragDepth;")),t&&n.push("out vec4 vWorldPosition;"),n.push("void main(void) {"),n.push("vec4 worldPosition = vec4(position, 1.0); "),n.push(" vec4 viewPosition = viewMatrix * worldPosition;"),t&&n.push(" vWorldPosition = worldPosition;"),n.push(" vec4 clipPos = projMatrix * viewPosition;"),n.push(" gl_PointSize = 20.0;"),e.logarithmicDepthBufferEnabled?n.push("vFragDepth = 1.0 + clipPos.w;"):n.push("clipPos.z += -0.001;"),n.push(" gl_Position = clipPos;"),n.push("}"),n}},{key:"_buildFragmentShaderSource",value:function(){var e=this._scene,t=e._sectionPlanesState,n=t.sectionPlanes.length>0,r=[];if(r.push("#version 300 es"),r.push("// OcclusionTester fragment shader"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),e.logarithmicDepthBufferEnabled&&(r.push("uniform float logDepthBufFC;"),r.push("in float vFragDepth;")),n){r.push("in vec4 vWorldPosition;");for(var i=0;i<t.sectionPlanes.length;i++)r.push("uniform bool sectionPlaneActive"+i+";"),r.push("uniform vec3 sectionPlanePos"+i+";"),r.push("uniform vec3 sectionPlaneDir"+i+";")}if(r.push("out vec4 outColor;"),r.push("void main(void) {"),n){r.push(" float dist = 0.0;");for(var a=0;a<t.sectionPlanes.length;a++)r.push("if (sectionPlaneActive"+a+") {"),r.push(" dist += clamp(dot(-sectionPlaneDir"+a+".xyz, vWorldPosition.xyz - sectionPlanePos"+a+".xyz), 0.0, 1000.0);"),r.push("}");r.push(" if (dist > 0.0) { discard; }")}return e.logarithmicDepthBufferEnabled&&r.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),r.push(" outColor = vec4(1.0, 0.0, 0.0, 1.0); "),r.push("}"),r}},{key:"_buildProgram",value:function(){this._program&&this._program.destroy();var e=this._scene,t=e.canvas.gl,n=e._sectionPlanesState;if(this._program=new ft(t,this._shaderSource),this._program.errors)this.errors=this._program.errors;else{var r=this._program;this._uViewMatrix=r.getLocation("viewMatrix"),this._uProjMatrix=r.getLocation("projMatrix"),this._uSectionPlanes=[];for(var i=0,a=n.sectionPlanes.length;i<a;i++)this._uSectionPlanes.push({active:r.getLocation("sectionPlaneActive"+i),pos:r.getLocation("sectionPlanePos"+i),dir:r.getLocation("sectionPlaneDir"+i)});this._aPosition=r.getAttribute("position"),e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=r.getLocation("logDepthBufFC"))}}},{key:"drawMarkers",value:function(){var e=this._scene,t=e.canvas.gl,n=this._program,r=e._sectionPlanesState,i=e.camera,a=e.camera.project;if(n.bind(),t.uniformMatrix4fv(this._uProjMatrix,!1,i._project._state.matrix),e.logarithmicDepthBufferEnabled){var s=2/(Math.log(a.far+1)/Math.LN2);t.uniform1f(this._uLogDepthBufFC,s)}for(var o=0,l=this._occlusionLayersList.length;o<l;o++){var u=this._occlusionLayersList[o];if(u.update(),!u.culledBySectionPlanes){var c=u.origin;t.uniformMatrix4fv(this._uViewMatrix,!1,Ie(i.viewMatrix,c));var f=r.sectionPlanes.length;if(f>0)for(var p=r.sectionPlanes,A=0;A<f;A++){var d=this._uSectionPlanes[A];if(d){var v=u.sectionPlanesActive[A];if(t.uniform1i(d.active,v?1:0),v){var h=p[A];t.uniform3fv(d.pos,ge(h.dist,h.dir,c,vt)),t.uniform3fv(d.dir,h.dir)}}}this._aPosition.bindArrayBuffer(u.positionsBuf);var I=u.indicesBuf;I.bind(),t.drawElements(t.POINTS,I.numItems,I.itemType,0)}}}},{key:"doOcclusionTest",value:function(){for(var e=this._scene.canvas.resolutionScale,t=255*dt[0],n=255*dt[1],r=255*dt[2],i=0,a=this._occlusionLayersList.length;i<a;i++)for(var s=this._occlusionLayersList[i],o=0;o<s.lenOcclusionTestList;o++){var l=s.occlusionTestList[o],u=2*o,c=this._readPixelBuf.read(Math.round(s.pixels[u]*e),Math.round(s.pixels[u+1]*e)),f=c[0]===t&&c[1]===n&&c[2]===r;l._setVisible(f)}}},{key:"unbindRenderBuf",value:function(){this._readPixelBuf.unbind()}},{key:"destroy",value:function(){if(!this.destroyed){for(var e=0,t=this._occlusionLayersList.length;e<t;e++){this._occlusionLayersList[e].destroy()}this._program&&this._program.destroy(),this._scene.camera.off(this._onCameraViewMatrix),this._scene.camera.off(this._onCameraProjMatrix),this._scene.canvas.off(this._onCanvasBoundary),this.destroyed=!0}}}]),e}(),It=Z.vec2(),yt=function(){function e(t){b(this,e),this._scene=t,this._numSamples=null,this._program=null,this._programError=!1,this._aPosition=null,this._aUV=null,this._uDepthTexture="uDepthTexture",this._uCameraNear=null,this._uCameraFar=null,this._uCameraProjectionMatrix=null,this._uCameraInverseProjectionMatrix=null,this._uScale=null,this._uIntensity=null,this._uBias=null,this._uKernelRadius=null,this._uMinResolution=null,this._uRandomSeed=null,this._uvBuf=null,this._positionsBuf=null,this._indicesBuf=null}return P(e,[{key:"render",value:function(e){var t=this;if(this._build(),!this._programError){this._getInverseProjectMat||(this._getInverseProjectMat=function(){var e=!0;t._scene.camera.on("projMatrix",(function(){e=!0}));var n=Z.mat4();return function(){return e&&Z.inverseMat4(i.camera.projMatrix,n),n}}());var n=this._scene.canvas.gl,r=this._program,i=this._scene,a=i.sao,s=n.drawingBufferWidth,o=n.drawingBufferHeight,l=i.camera.project._state,u=l.near,c=l.far,f=l.matrix,p=this._getInverseProjectMat(),A=Math.random(),d="perspective"===i.camera.projection;It[0]=s,It[1]=o,n.viewport(0,0,s,o),n.clearColor(0,0,0,1),n.disable(n.DEPTH_TEST),n.disable(n.BLEND),n.frontFace(n.CCW),n.clear(n.COLOR_BUFFER_BIT),r.bind(),n.uniform1f(this._uCameraNear,u),n.uniform1f(this._uCameraFar,c),n.uniformMatrix4fv(this._uCameraProjectionMatrix,!1,f),n.uniformMatrix4fv(this._uCameraInverseProjectionMatrix,!1,p),n.uniform1i(this._uPerspective,d),n.uniform1f(this._uScale,a.scale*(c/5)),n.uniform1f(this._uIntensity,a.intensity),n.uniform1f(this._uBias,a.bias),n.uniform1f(this._uKernelRadius,a.kernelRadius),n.uniform1f(this._uMinResolution,a.minResolution),n.uniform2fv(this._uViewport,It),n.uniform1f(this._uRandomSeed,A);var v=e.getDepthTexture();r.bindTexture(this._uDepthTexture,v,0),this._aUV.bindArrayBuffer(this._uvBuf),this._aPosition.bindArrayBuffer(this._positionsBuf),this._indicesBuf.bind(),n.drawElements(n.TRIANGLES,this._indicesBuf.numItems,this._indicesBuf.itemType,0)}}},{key:"_build",value:function(){var e=!1,t=this._scene.sao;if(t.numSamples!==this._numSamples&&(this._numSamples=Math.floor(t.numSamples),e=!0),e){var n=this._scene.canvas.gl;if(this._program&&(this._program.destroy(),this._program=null),this._program=new ft(n,{vertex:["#version 300 es\n precision highp float;\n precision highp int;\n \n in vec3 aPosition;\n in vec2 aUV; \n \n out vec2 vUV;\n \n void main () {\n gl_Position = vec4(aPosition, 1.0);\n vUV = aUV;\n }"],fragment:["#version 300 es \n precision highp float;\n precision highp int; \n \n #define NORMAL_TEXTURE 0\n #define PI 3.14159265359\n #define PI2 6.28318530718\n #define EPSILON 1e-6\n #define NUM_SAMPLES ".concat(this._numSamples,"\n #define NUM_RINGS 4 \n \n in vec2 vUV;\n \n uniform sampler2D uDepthTexture;\n \n uniform float uCameraNear;\n uniform float uCameraFar;\n uniform mat4 uProjectMatrix;\n uniform mat4 uInverseProjectMatrix;\n \n uniform bool uPerspective;\n\n uniform float uScale;\n uniform float uIntensity;\n uniform float uBias;\n uniform float uKernelRadius;\n uniform float uMinResolution;\n uniform vec2 uViewport;\n uniform float uRandomSeed;\n\n float pow2( const in float x ) { return x*x; }\n \n highp float rand( const in vec2 uv ) {\n const highp float a = 12.9898, b = 78.233, c = 43758.5453;\n highp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI );\n return fract(sin(sn) * c);\n }\n\n vec3 packNormalToRGB( const in vec3 normal ) {\n return normalize( normal ) * 0.5 + 0.5;\n }\n\n vec3 unpackRGBToNormal( const in vec3 rgb ) {\n return 2.0 * rgb.xyz - 1.0;\n }\n\n const float packUpscale = 256. / 255.;\n const float unpackDownScale = 255. / 256.; \n\n const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );\n const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. ); \n\n const float shiftRights = 1. / 256.;\n\n vec4 packFloatToRGBA( const in float v ) {\n vec4 r = vec4( fract( v * packFactors ), v );\n r.yzw -= r.xyz * shiftRights; \n return r * packUpscale;\n }\n\n float unpackRGBAToFloat( const in vec4 v ) { \n return dot( floor( v * 255.0 + 0.5 ) / 255.0, unPackFactors );\n }\n \n float perspectiveDepthToViewZ( const in float invClipZ, const in float near, const in float far ) {\n return ( near * far ) / ( ( far - near ) * invClipZ - far );\n }\n\n float orthographicDepthToViewZ( const in float linearClipZ, const in float near, const in float far ) {\n return linearClipZ * ( near - far ) - near;\n }\n \n float getDepth( const in vec2 screenPosition ) {\n return vec4(texture(uDepthTexture, screenPosition)).r;\n }\n\n float getViewZ( const in float depth ) {\n if (uPerspective) {\n return perspectiveDepthToViewZ( depth, uCameraNear, uCameraFar );\n } else {\n return orthographicDepthToViewZ( depth, uCameraNear, uCameraFar );\n }\n }\n\n vec3 getViewPos( const in vec2 screenPos, const in float depth, const in float viewZ ) {\n \tfloat clipW = uProjectMatrix[2][3] * viewZ + uProjectMatrix[3][3];\n \tvec4 clipPosition = vec4( ( vec3( screenPos, depth ) - 0.5 ) * 2.0, 1.0 );\n \tclipPosition *= clipW; \n \treturn ( uInverseProjectMatrix * clipPosition ).xyz;\n }\n\n vec3 getViewNormal( const in vec3 viewPosition, const in vec2 screenPos ) { \n return normalize( cross( dFdx( viewPosition ), dFdy( viewPosition ) ) );\n }\n\n float scaleDividedByCameraFar;\n float minResolutionMultipliedByCameraFar;\n\n float getOcclusion( const in vec3 centerViewPosition, const in vec3 centerViewNormal, const in vec3 sampleViewPosition ) {\n \tvec3 viewDelta = sampleViewPosition - centerViewPosition;\n \tfloat viewDistance = length( viewDelta );\n \tfloat scaledScreenDistance = scaleDividedByCameraFar * viewDistance;\n \treturn max(0.0, (dot(centerViewNormal, viewDelta) - minResolutionMultipliedByCameraFar) / scaledScreenDistance - uBias) / (1.0 + pow2( scaledScreenDistance ) );\n }\n\n const float ANGLE_STEP = PI2 * float( NUM_RINGS ) / float( NUM_SAMPLES );\n const float INV_NUM_SAMPLES = 1.0 / float( NUM_SAMPLES );\n\n float getAmbientOcclusion( const in vec3 centerViewPosition ) {\n \n \tscaleDividedByCameraFar = uScale / uCameraFar;\n \tminResolutionMultipliedByCameraFar = uMinResolution * uCameraFar;\n \tvec3 centerViewNormal = getViewNormal( centerViewPosition, vUV );\n\n \tfloat angle = rand( vUV + uRandomSeed ) * PI2;\n \tvec2 radius = vec2( uKernelRadius * INV_NUM_SAMPLES ) / uViewport;\n \tvec2 radiusStep = radius;\n\n \tfloat occlusionSum = 0.0;\n \tfloat weightSum = 0.0;\n\n \tfor( int i = 0; i < NUM_SAMPLES; i ++ ) {\n \t\tvec2 sampleUv = vUV + vec2( cos( angle ), sin( angle ) ) * radius;\n \t\tradius += radiusStep;\n \t\tangle += ANGLE_STEP;\n\n \t\tfloat sampleDepth = getDepth( sampleUv );\n \t\tif( sampleDepth >= ( 1.0 - EPSILON ) ) {\n \t\t\tcontinue;\n \t\t}\n\n \t\tfloat sampleViewZ = getViewZ( sampleDepth );\n \t\tvec3 sampleViewPosition = getViewPos( sampleUv, sampleDepth, sampleViewZ );\n \t\tocclusionSum += getOcclusion( centerViewPosition, centerViewNormal, sampleViewPosition );\n \t\tweightSum += 1.0;\n \t}\n\n \tif( weightSum == 0.0 ) discard;\n\n \treturn occlusionSum * ( uIntensity / weightSum );\n }\n\n out vec4 outColor;\n \n void main() {\n \n \tfloat centerDepth = getDepth( vUV );\n \t\n \tif( centerDepth >= ( 1.0 - EPSILON ) ) {\n \t\tdiscard;\n \t}\n\n \tfloat centerViewZ = getViewZ( centerDepth );\n \tvec3 viewPosition = getViewPos( vUV, centerDepth, centerViewZ );\n\n \tfloat ambientOcclusion = getAmbientOcclusion( viewPosition );\n \n \toutColor = packFloatToRGBA( 1.0- ambientOcclusion );\n }")]}),this._program.errors)return console.error(this._program.errors.join("\n")),void(this._programError=!0);var r=new Float32Array([1,1,0,1,0,0,1,0]),i=new Float32Array([1,1,0,-1,1,0,-1,-1,0,1,-1,0]),a=new Uint32Array([0,1,2,0,2,3]);this._positionsBuf=new pt(n,n.ARRAY_BUFFER,i,i.length,3,n.STATIC_DRAW),this._uvBuf=new pt(n,n.ARRAY_BUFFER,r,r.length,2,n.STATIC_DRAW),this._indicesBuf=new pt(n,n.ELEMENT_ARRAY_BUFFER,a,a.length,1,n.STATIC_DRAW),this._program.bind(),this._uCameraNear=this._program.getLocation("uCameraNear"),this._uCameraFar=this._program.getLocation("uCameraFar"),this._uCameraProjectionMatrix=this._program.getLocation("uProjectMatrix"),this._uCameraInverseProjectionMatrix=this._program.getLocation("uInverseProjectMatrix"),this._uPerspective=this._program.getLocation("uPerspective"),this._uScale=this._program.getLocation("uScale"),this._uIntensity=this._program.getLocation("uIntensity"),this._uBias=this._program.getLocation("uBias"),this._uKernelRadius=this._program.getLocation("uKernelRadius"),this._uMinResolution=this._program.getLocation("uMinResolution"),this._uViewport=this._program.getLocation("uViewport"),this._uRandomSeed=this._program.getLocation("uRandomSeed"),this._aPosition=this._program.getAttribute("aPosition"),this._aUV=this._program.getAttribute("aUV"),this._dirty=!1}}},{key:"destroy",value:function(){this._program&&(this._program.destroy(),this._program=null)}}]),e}(),mt=new Float32Array(Dt(17,[0,1])),wt=new Float32Array(Dt(17,[1,0])),gt=new Float32Array(function(e,t){for(var n=[],r=0;r<=e;r++)n.push(bt(r,t));return n}(17,4)),Tt=new Float32Array(2),Et=function(){function e(t){b(this,e),this._scene=t,this._program=null,this._programError=!1,this._aPosition=null,this._aUV=null,this._uDepthTexture="uDepthTexture",this._uOcclusionTexture="uOcclusionTexture",this._uViewport=null,this._uCameraNear=null,this._uCameraFar=null,this._uCameraProjectionMatrix=null,this._uCameraInverseProjectionMatrix=null,this._uvBuf=null,this._positionsBuf=null,this._indicesBuf=null,this.init()}return P(e,[{key:"init",value:function(){var e=this._scene.canvas.gl;if(this._program=new ft(e,{vertex:["#version 300 es\n precision highp float;\n precision highp int;\n \n in vec3 aPosition;\n in vec2 aUV;\n uniform vec2 uViewport;\n out vec2 vUV;\n out vec2 vInvSize;\n void main () {\n vUV = aUV;\n vInvSize = 1.0 / uViewport;\n gl_Position = vec4(aPosition, 1.0);\n }"],fragment:["#version 300 es\n precision highp float;\n precision highp int;\n \n #define PI 3.14159265359\n #define PI2 6.28318530718\n #define EPSILON 1e-6\n\n #define KERNEL_RADIUS ".concat(16,"\n\n in vec2 vUV;\n in vec2 vInvSize;\n \n uniform sampler2D uDepthTexture;\n uniform sampler2D uOcclusionTexture; \n \n uniform float uCameraNear;\n uniform float uCameraFar; \n uniform float uDepthCutoff;\n\n uniform vec2 uSampleOffsets[ KERNEL_RADIUS + 1 ];\n uniform float uSampleWeights[ KERNEL_RADIUS + 1 ];\n\n const float unpackDownscale = 255. / 256.; \n\n const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );\n const vec4 unpackFactors = unpackDownscale / vec4( packFactors, 1. ); \n\n const float packUpscale = 256. / 255.;\n \n const float shiftRights = 1. / 256.;\n \n float unpackRGBAToFloat( const in vec4 v ) {\n return dot( floor( v * 255.0 + 0.5 ) / 255.0, unpackFactors );\n } \n\n vec4 packFloatToRGBA( const in float v ) {\n vec4 r = vec4( fract( v * packFactors ), v );\n r.yzw -= r.xyz * shiftRights; \n return r * packUpscale;\n }\n\n float viewZToOrthographicDepth( const in float viewZ) {\n return ( viewZ + uCameraNear ) / ( uCameraNear - uCameraFar );\n }\n \n float orthographicDepthToViewZ( const in float linearClipZ) {\n return linearClipZ * ( uCameraNear - uCameraFar ) - uCameraNear;\n }\n\n float viewZToPerspectiveDepth( const in float viewZ) {\n return (( uCameraNear + viewZ ) * uCameraFar ) / (( uCameraFar - uCameraNear ) * viewZ );\n }\n \n float perspectiveDepthToViewZ( const in float invClipZ) {\n return ( uCameraNear * uCameraFar ) / ( ( uCameraFar - uCameraNear ) * invClipZ - uCameraFar );\n }\n\n float getDepth( const in vec2 screenPosition ) {\n return vec4(texture(uDepthTexture, screenPosition)).r;\n }\n\n float getViewZ( const in float depth ) {\n return perspectiveDepthToViewZ( depth );\n }\n\n out vec4 outColor;\n \n void main() {\n \n float depth = getDepth( vUV );\n if( depth >= ( 1.0 - EPSILON ) ) {\n discard;\n }\n\n float centerViewZ = -getViewZ( depth );\n bool rBreak = false;\n bool lBreak = false;\n\n float weightSum = uSampleWeights[0];\n float occlusionSum = unpackRGBAToFloat(texture( uOcclusionTexture, vUV )) * weightSum;\n\n for( int i = 1; i <= KERNEL_RADIUS; i ++ ) {\n\n float sampleWeight = uSampleWeights[i];\n vec2 sampleUVOffset = uSampleOffsets[i] * vInvSize;\n\n vec2 sampleUV = vUV + sampleUVOffset;\n float viewZ = -getViewZ( getDepth( sampleUV ) );\n\n if( abs( viewZ - centerViewZ ) > uDepthCutoff ) {\n rBreak = true;\n }\n\n if( ! rBreak ) {\n occlusionSum += unpackRGBAToFloat(texture( uOcclusionTexture, sampleUV )) * sampleWeight;\n weightSum += sampleWeight;\n }\n\n sampleUV = vUV - sampleUVOffset;\n viewZ = -getViewZ( getDepth( sampleUV ) );\n\n if( abs( viewZ - centerViewZ ) > uDepthCutoff ) {\n lBreak = true;\n }\n\n if( ! lBreak ) {\n occlusionSum += unpackRGBAToFloat(texture( uOcclusionTexture, sampleUV )) * sampleWeight;\n weightSum += sampleWeight;\n }\n }\n\n outColor = packFloatToRGBA(occlusionSum / weightSum);\n }")]}),this._program.errors)return console.error(this._program.errors.join("\n")),void(this._programError=!0);var t=new Float32Array([1,1,0,1,0,0,1,0]),n=new Float32Array([1,1,0,-1,1,0,-1,-1,0,1,-1,0]),r=new Uint32Array([0,1,2,0,2,3]);this._positionsBuf=new pt(e,e.ARRAY_BUFFER,n,n.length,3,e.STATIC_DRAW),this._uvBuf=new pt(e,e.ARRAY_BUFFER,t,t.length,2,e.STATIC_DRAW),this._indicesBuf=new pt(e,e.ELEMENT_ARRAY_BUFFER,r,r.length,1,e.STATIC_DRAW),this._program.bind(),this._uViewport=this._program.getLocation("uViewport"),this._uCameraNear=this._program.getLocation("uCameraNear"),this._uCameraFar=this._program.getLocation("uCameraFar"),this._uDepthCutoff=this._program.getLocation("uDepthCutoff"),this._uSampleOffsets=e.getUniformLocation(this._program.handle,"uSampleOffsets"),this._uSampleWeights=e.getUniformLocation(this._program.handle,"uSampleWeights"),this._aPosition=this._program.getAttribute("aPosition"),this._aUV=this._program.getAttribute("aUV")}},{key:"render",value:function(e,t,n){var r=this;if(!this._programError){this._getInverseProjectMat||(this._getInverseProjectMat=function(){var e=!0;r._scene.camera.on("projMatrix",(function(){e=!0}));var t=Z.mat4();return function(){return e&&Z.inverseMat4(s.camera.projMatrix,t),t}}());var i=this._scene.canvas.gl,a=this._program,s=this._scene,o=i.drawingBufferWidth,l=i.drawingBufferHeight,u=s.camera.project._state,c=u.near,f=u.far;i.viewport(0,0,o,l),i.clearColor(0,0,0,1),i.enable(i.DEPTH_TEST),i.disable(i.BLEND),i.frontFace(i.CCW),i.clear(i.COLOR_BUFFER_BIT|i.DEPTH_BUFFER_BIT),a.bind(),Tt[0]=o,Tt[1]=l,i.uniform2fv(this._uViewport,Tt),i.uniform1f(this._uCameraNear,c),i.uniform1f(this._uCameraFar,f),i.uniform1f(this._uDepthCutoff,.01),0===n?i.uniform2fv(this._uSampleOffsets,wt):i.uniform2fv(this._uSampleOffsets,mt),i.uniform1fv(this._uSampleWeights,gt);var p=e.getDepthTexture(),A=t.getTexture();a.bindTexture(this._uDepthTexture,p,0),a.bindTexture(this._uOcclusionTexture,A,1),this._aUV.bindArrayBuffer(this._uvBuf),this._aPosition.bindArrayBuffer(this._positionsBuf),this._indicesBuf.bind(),i.drawElements(i.TRIANGLES,this._indicesBuf.numItems,this._indicesBuf.itemType,0)}}},{key:"destroy",value:function(){this._program.destroy()}}]),e}();function bt(e,t){return Math.exp(-e*e/(t*t*2))/(Math.sqrt(2*Math.PI)*t)}function Dt(e,t){for(var n=[],r=0;r<=e;r++)n.push(t[0]*r),n.push(t[1]*r);return n}var Pt=function(){function e(t,n,r){b(this,e),r=r||{},this.gl=n,this.allocated=!1,this.canvas=t,this.buffer=null,this.bound=!1,this.size=r.size,this._hasDepthTexture=!!r.depthTexture}return P(e,[{key:"setSize",value:function(e){this.size=e}},{key:"webglContextRestored",value:function(e){this.gl=e,this.buffer=null,this.allocated=!1,this.bound=!1}},{key:"bind",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:null;if(this._touch(e),!this.bound){var t=this.gl;t.bindFramebuffer(t.FRAMEBUFFER,this.buffer.framebuf),this.bound=!0}}},{key:"_touch",value:function(){var e,t,n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:null,r=this.gl;if(this.size?(e=this.size[0],t=this.size[1]):(e=r.drawingBufferWidth,t=r.drawingBufferHeight),this.buffer){if(this.buffer.width===e&&this.buffer.height===t)return;r.deleteTexture(this.buffer.texture),r.deleteFramebuffer(this.buffer.framebuf),r.deleteRenderbuffer(this.buffer.renderbuf)}var i,a=r.createTexture();r.bindTexture(r.TEXTURE_2D,a),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MIN_FILTER,r.NEAREST),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MAG_FILTER,r.NEAREST),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_S,r.CLAMP_TO_EDGE),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_T,r.CLAMP_TO_EDGE),n?r.texStorage2D(r.TEXTURE_2D,1,n,e,t):r.texImage2D(r.TEXTURE_2D,0,r.RGBA,e,t,0,r.RGBA,r.UNSIGNED_BYTE,null),this._hasDepthTexture&&(i=r.createTexture(),r.bindTexture(r.TEXTURE_2D,i),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MAG_FILTER,r.NEAREST),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MIN_FILTER,r.NEAREST),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_S,r.CLAMP_TO_EDGE),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_T,r.CLAMP_TO_EDGE),r.texImage2D(r.TEXTURE_2D,0,r.DEPTH_COMPONENT32F,e,t,0,r.DEPTH_COMPONENT,r.FLOAT,null));var s=r.createRenderbuffer();r.bindRenderbuffer(r.RENDERBUFFER,s),r.renderbufferStorage(r.RENDERBUFFER,r.DEPTH_COMPONENT32F,e,t);var o=r.createFramebuffer();if(r.bindFramebuffer(r.FRAMEBUFFER,o),r.framebufferTexture2D(r.FRAMEBUFFER,r.COLOR_ATTACHMENT0,r.TEXTURE_2D,a,0),this._hasDepthTexture?r.framebufferTexture2D(r.FRAMEBUFFER,r.DEPTH_ATTACHMENT,r.TEXTURE_2D,i,0):r.framebufferRenderbuffer(r.FRAMEBUFFER,r.DEPTH_ATTACHMENT,r.RENDERBUFFER,s),r.bindTexture(r.TEXTURE_2D,null),r.bindRenderbuffer(r.RENDERBUFFER,null),r.bindFramebuffer(r.FRAMEBUFFER,null),r.bindFramebuffer(r.FRAMEBUFFER,o),!r.isFramebuffer(o))throw"Invalid framebuffer";r.bindFramebuffer(r.FRAMEBUFFER,null);var l=r.checkFramebufferStatus(r.FRAMEBUFFER);switch(l){case r.FRAMEBUFFER_COMPLETE:break;case r.FRAMEBUFFER_INCOMPLETE_ATTACHMENT:throw"Incomplete framebuffer: FRAMEBUFFER_INCOMPLETE_ATTACHMENT";case r.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:throw"Incomplete framebuffer: FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT";case r.FRAMEBUFFER_INCOMPLETE_DIMENSIONS:throw"Incomplete framebuffer: FRAMEBUFFER_INCOMPLETE_DIMENSIONS";case r.FRAMEBUFFER_UNSUPPORTED:throw"Incomplete framebuffer: FRAMEBUFFER_UNSUPPORTED";default:throw"Incomplete framebuffer: "+l}this.buffer={framebuf:o,renderbuf:s,texture:a,depthTexture:i,width:e,height:t},this.bound=!1}},{key:"clear",value:function(){if(!this.bound)throw"Render buffer not bound";var e=this.gl;e.clear(e.COLOR_BUFFER_BIT|e.DEPTH_BUFFER_BIT)}},{key:"read",value:function(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null,r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:null,i=arguments.length>4&&void 0!==arguments[4]?arguments[4]:Uint8Array,a=arguments.length>5&&void 0!==arguments[5]?arguments[5]:4,s=e,o=(this.buffer.height||this.gl.drawingBufferHeight)-t,l=new i(a),u=this.gl;return u.readPixels(s,o,1,1,n||u.RGBA,r||u.UNSIGNED_BYTE,l,0),l}},{key:"readArray",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:null,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:Uint8Array,r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:4,i=new n(this.buffer.width*this.buffer.height*r),a=this.gl;return a.readPixels(0,0,this.buffer.width,this.buffer.height,e||a.RGBA,t||a.UNSIGNED_BYTE,i,0),i}},{key:"readImageAsCanvas",value:function(){var e=this.gl,t=this._getImageDataCache(),n=t.pixelData,r=t.canvas,i=t.imageData,a=t.context;e.readPixels(0,0,this.buffer.width,this.buffer.height,e.RGBA,e.UNSIGNED_BYTE,n);for(var s=this.buffer.width,o=this.buffer.height,l=o/2|0,u=4*s,c=new Uint8Array(4*s),f=0;f<l;++f){var p=f*u,A=(o-f-1)*u;c.set(n.subarray(p,p+u)),n.copyWithin(p,A,A+u),n.set(c,A)}return i.data.set(n),a.putImageData(i,0,0),r}},{key:"readImage",value:function(e){var t=this.gl,n=this._getImageDataCache(),r=n.pixelData,i=n.canvas,a=n.imageData,s=n.context,o=this.buffer,l=o.width,u=o.height;t.readPixels(0,0,l,u,t.RGBA,t.UNSIGNED_BYTE,r),a.data.set(r),s.putImageData(a,0,0),s.save(),s.globalCompositeOperation="copy",s.scale(1,-1),s.drawImage(i,0,-u,l,u),s.restore();var c=e.format||"png";return"jpeg"!==c&&"png"!==c&&"bmp"!==c&&(console.error("Unsupported image format: '"+c+"' - supported types are 'jpeg', 'bmp' and 'png' - defaulting to 'png'"),c="png"),i.toDataURL("image/".concat(c))}},{key:"_getImageDataCache",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:Uint8Array,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:4,n=this.buffer.width,r=this.buffer.height,i=this._imageDataCache;if(i&&(i.width===n&&i.height===r||(this._imageDataCache=null,i=null)),!i){var a=document.createElement("canvas"),s=a.getContext("2d");a.width=n,a.height=r,i={pixelData:new e(n*r*t),canvas:a,context:s,imageData:s.createImageData(n,r),width:n,height:r},this._imageDataCache=i}return i.context.resetTransform(),i}},{key:"unbind",value:function(){var e=this.gl;e.bindFramebuffer(e.FRAMEBUFFER,null),this.bound=!1}},{key:"getTexture",value:function(){var e=this;return this._texture||(this._texture={renderBuffer:this,bind:function(t){return!(!e.buffer||!e.buffer.texture)&&(e.gl.activeTexture(e.gl["TEXTURE"+t]),e.gl.bindTexture(e.gl.TEXTURE_2D,e.buffer.texture),!0)},unbind:function(t){e.buffer&&e.buffer.texture&&(e.gl.activeTexture(e.gl["TEXTURE"+t]),e.gl.bindTexture(e.gl.TEXTURE_2D,null))}})}},{key:"hasDepthTexture",value:function(){return this._hasDepthTexture}},{key:"getDepthTexture",value:function(){if(!this._hasDepthTexture)return null;var e=this;return this._depthTexture||(this._dethTexture={renderBuffer:this,bind:function(t){return!(!e.buffer||!e.buffer.depthTexture)&&(e.gl.activeTexture(e.gl["TEXTURE"+t]),e.gl.bindTexture(e.gl.TEXTURE_2D,e.buffer.depthTexture),!0)},unbind:function(t){e.buffer&&e.buffer.depthTexture&&(e.gl.activeTexture(e.gl["TEXTURE"+t]),e.gl.bindTexture(e.gl.TEXTURE_2D,null))}})}},{key:"destroy",value:function(){if(this.allocated){var e=this.gl;e.deleteTexture(this.buffer.texture),e.deleteTexture(this.buffer.depthTexture),e.deleteFramebuffer(this.buffer.framebuf),e.deleteRenderbuffer(this.buffer.renderbuf),this.allocated=!1,this.buffer=null,this.bound=!1}this._imageDataCache=null,this._texture=null,this._depthTexture=null}}]),e}(),Rt=function(){function e(t){b(this,e),this.scene=t,this._renderBuffersBasic={},this._renderBuffersScaled={}}return P(e,[{key:"getRenderBuffer",value:function(e,t){var n=1===this.scene.canvas.resolutionScale?this._renderBuffersBasic:this._renderBuffersScaled,r=n[e];return r||(r=new Pt(this.scene.canvas.canvas,this.scene.canvas.gl,t),n[e]=r),r}},{key:"destroy",value:function(){for(var e in this._renderBuffersBasic)this._renderBuffersBasic[e].destroy();for(var t in this._renderBuffersScaled)this._renderBuffersScaled[t].destroy()}}]),e}();function Ct(e,t){if(void 0===e._cachedExtensions&&(e._cachedExtensions={}),void 0!==e._cachedExtensions[t])return e._cachedExtensions[t];var n;switch(t){case"WEBGL_depth_texture":n=e.getExtension("WEBGL_depth_texture")||e.getExtension("MOZ_WEBGL_depth_texture")||e.getExtension("WEBKIT_WEBGL_depth_texture");break;case"EXT_texture_filter_anisotropic":n=e.getExtension("EXT_texture_filter_anisotropic")||e.getExtension("MOZ_EXT_texture_filter_anisotropic")||e.getExtension("WEBKIT_EXT_texture_filter_anisotropic");break;case"WEBGL_compressed_texture_s3tc":n=e.getExtension("WEBGL_compressed_texture_s3tc")||e.getExtension("MOZ_WEBGL_compressed_texture_s3tc")||e.getExtension("WEBKIT_WEBGL_compressed_texture_s3tc");break;case"WEBGL_compressed_texture_pvrtc":n=e.getExtension("WEBGL_compressed_texture_pvrtc")||e.getExtension("WEBKIT_WEBGL_compressed_texture_pvrtc");break;default:n=e.getExtension(t)}return e._cachedExtensions[t]=n,n}var _t=function(e,t){t=t||{};var n=new rt(e),r=e.canvas.canvas,i=e.canvas.gl,a=!!t.transparent,s=t.alphaDepthMask,o=new G({}),l={},u={},c=!0,f=!0,p=!0,A=!0,d=!0,v=!0,h=!0,I=!0,y=new Rt(e),m=!1,w=new yt(e),g=new Et(e);function T(){c&&(!function(){for(var e in l)if(l.hasOwnProperty(e)){var t=l[e],n=t.drawableMap,r=t.drawableListPreCull,i=0;for(var a in n)n.hasOwnProperty(a)&&(r[i++]=n[a]);r.length=i}}(),c=!1,f=!0),f&&(!function(){for(var e in l)if(l.hasOwnProperty(e)){var t=l[e];t.isStateSortable&&t.drawableListPreCull.sort(t.stateSortCompare)}}(),f=!1,p=!0),p&&function(){for(var e in l)if(l.hasOwnProperty(e)){for(var t=l[e],n=t.drawableListPreCull,r=t.drawableList,i=0,a=0,s=n.length;a<s;a++){var o=n[a];o.rebuildRenderFlags(),o.renderFlags.culled||(r[i++]=o)}r.length=i}}()}function E(e){if(e.castsShadow){var t=e.getShadowRenderBuf();if(t){for(var r in t.bind(),n.reset(),n.backfaces=!0,n.frontface=!0,n.shadowViewMatrix=e.getShadowViewMatrix(),n.shadowProjMatrix=e.getShadowProjMatrix(),i.viewport(0,0,i.drawingBufferWidth,i.drawingBufferHeight),i.clearColor(0,0,0,1),i.enable(i.DEPTH_TEST),i.disable(i.BLEND),i.clear(i.COLOR_BUFFER_BIT|i.DEPTH_BUFFER_BIT),l)if(l.hasOwnProperty(r))for(var a=l[r].drawableList,s=0,o=a.length;s<o;s++){var u=a[s];!1!==u.visible&&u.castsShadow&&u.drawShadow&&(u.renderFlags.colorOpaque&&u.drawShadow(n))}t.unbind()}}}function b(t,r,a,s,u,c){n.reset(),n.backfaces=!0,n.frontface=!0,n.pickOrigin=c.origin,n.pickViewMatrix=a,n.pickProjMatrix=s,n.pickInvisible=!!u.pickInvisible,i.viewport(0,0,i.drawingBufferWidth,i.drawingBufferHeight),i.clearColor(0,0,0,0),i.enable(i.DEPTH_TEST),i.disable(i.CULL_FACE),i.disable(i.BLEND),i.clear(i.COLOR_BUFFER_BIT|i.DEPTH_BUFFER_BIT);var f=u.includeEntityIds,p=u.excludeEntityIds;for(var A in l)if(l.hasOwnProperty(A))for(var d=l[A].drawableList,v=0,h=d.length;v<h;v++){var I=d[v];!I.drawPickMesh||!0!==u.pickInvisible&&!1===I.visible||!1===I.pickable||(f&&!f[I.id]||p&&p[I.id]||I.drawPickMesh(n))}var y=e.canvas.resolutionScale,m=t.read(Math.round(r[0]*y),Math.round(r[1]*y)),w=m[0]+256*m[1]+256*m[2]*256+256*m[3]*256*256;if(!(w<0))return o.items[w]}function D(t,r,a,s,o,l){if(r.drawPickTriangles){n.reset(),n.backfaces=!0,n.frontface=!0,n.pickOrigin=l.origin,n.pickViewMatrix=s,n.pickProjMatrix=o,i.viewport(0,0,i.drawingBufferWidth,i.drawingBufferHeight),i.clearColor(0,0,0,0),i.enable(i.DEPTH_TEST),i.disable(i.CULL_FACE),i.disable(i.BLEND),i.clear(i.COLOR_BUFFER_BIT|i.DEPTH_BUFFER_BIT),r.drawPickTriangles(n);var u=e.canvas.resolutionScale,c=t.read(Math.round(a[0]*u),Math.round(a[1]*u)),f=c[0]+256*c[1]+256*c[2]*256+256*c[3]*256*256;f*=3,l.primIndex=f}}this.scene=e,this._occlusionTester=null,this.capabilities={astcSupported:!!Ct(i,"WEBGL_compressed_texture_astc"),etc1Supported:!0,etc2Supported:!!Ct(i,"WEBGL_compressed_texture_etc"),dxtSupported:!!Ct(i,"WEBGL_compressed_texture_s3tc"),bptcSupported:!!Ct(i,"EXT_texture_compression_bptc"),pvrtcSupported:!(!Ct(i,"WEBGL_compressed_texture_pvrtc")&&!Ct(i,"WEBKIT_WEBGL_compressed_texture_pvrtc"))},this.setTransparentEnabled=function(e){A=e,p=!0},this.setEdgesEnabled=function(e){d=e,p=!0},this.setSAOEnabled=function(e){v=e,p=!0},this.setPBREnabled=function(e){h=e,p=!0},this.setColorTextureEnabled=function(e){I=e,p=!0},this.needStateSort=function(){f=!0},this.shadowsDirty=function(){},this.imageDirty=function(){p=!0},this.webglContextLost=function(){},this.webglContextRestored=function(e){w.init(),g.init(),p=!0},this.addDrawable=function(e,t){var n=t.type;if(n){var r=l[n];r||(r={type:t.type,count:0,isStateSortable:t.isStateSortable,stateSortCompare:t.stateSortCompare,drawableMap:{},drawableListPreCull:[],drawableList:[]},l[n]=r),r.count++,r.drawableMap[e]=t,u[e]=t,c=!0}else console.error("Renderer#addDrawable() : drawable with ID "+e+" has no 'type' - ignoring")},this.removeDrawable=function(e){var t=u[e];if(t){var n=t.type,r=l[n];--r.count<=0?delete l[n]:delete r.drawableMap[e],delete u[e],c=!0}else console.error("Renderer#removeDrawable() : drawable not found with ID "+e+" - ignoring")},this.getPickID=function(e){return o.addItem(e)},this.putPickID=function(e){o.removeItem(e)},this.clear=function(t){if(i.viewport(0,0,i.drawingBufferWidth,i.drawingBufferHeight),a)i.clearColor(1,1,1,1);else{var n=e.canvas.backgroundColorFromAmbientLight?this.lights.getAmbientColorAndIntensity():e.canvas.backgroundColor;i.clearColor(n[0],n[1],n[2],1)}i.clear(i.COLOR_BUFFER_BIT|i.DEPTH_BUFFER_BIT)},this.needsRender=function(){return p||c||f},this.render=function(t){(t=t||{}).force&&(p=!0),T(),p&&(!function(t){var r=e.sao;v&&r.possible&&function(t){var r=e.sao,a=y.getRenderBuffer("saoDepth",{depthTexture:!0});a.bind(),a.clear(),function(e){n.reset(),n.pass=e.pass,i.viewport(0,0,i.drawingBufferWidth,i.drawingBufferHeight),i.clearColor(0,0,0,0),i.enable(i.DEPTH_TEST),i.frontFace(i.CCW),i.enable(i.CULL_FACE),i.depthMask(!0),!1!==e.clear&&i.clear(i.COLOR_BUFFER_BIT|i.DEPTH_BUFFER_BIT);for(var t in l)if(l.hasOwnProperty(t))for(var r=l[t].drawableList,a=0,s=r.length;a<s;a++){var o=r[a];!0!==o.culled&&!1!==o.visible&&o.drawDepth&&o.saoEnabled&&(o.renderFlags.colorOpaque&&o.drawDepth(n))}}(t),a.unbind();var s=y.getRenderBuffer("saoOcclusion");if(s.bind(),s.clear(),w.render(a),s.unbind(),r.blur){var o=y.getRenderBuffer("saoOcclusion2");o.bind(),o.clear(),g.render(a,s,0),o.unbind(),s.bind(),s.clear(),g.render(a,o,1),s.unbind()}}(t);(function(){for(var t=e._lightsState.lights,n=0,r=t.length;n<r;n++){var i=t[n];i.castsShadow&&E(i)}})(),function(t){var r=[],o=[],u=[],c=[],f=[],p=[],m=[],w=[],g=[],T=[],E=[],b=[],D=[],P=[],R=[],C=[],_=e._lightsState.getAmbientColorAndIntensity();if(n.reset(),n.pass=t.pass,n.withSAO=!1,n.pbrEnabled=h&&!!e.pbrEnabled,n.colorTextureEnabled=I&&!!e.colorTextureEnabled,i.viewport(0,0,i.drawingBufferWidth,i.drawingBufferHeight),a)i.clearColor(0,0,0,0);else{var B=e.canvas.backgroundColorFromAmbientLight?_:e.canvas.backgroundColor;i.clearColor(B[0],B[1],B[2],1)}i.enable(i.DEPTH_TEST),i.frontFace(i.CCW),i.enable(i.CULL_FACE),i.depthMask(!0),i.lineWidth(1),n.lineWidth=1;var O,S,N,L=e.sao.possible;if(v&&L){var x=y.getRenderBuffer("saoOcclusion");n.occlusionTexture=x?x.getTexture():null}else n.occlusionTexture=null;var M=Date.now();!1!==t.clear&&i.clear(i.COLOR_BUFFER_BIT|i.DEPTH_BUFFER_BIT);var F=0,H=0,U=0,G=0,k=0,V=0,j=0,Q=0,W=0,z=0,K=0,Y=0,X=0,q=0,J=0,Z=0;for(var $ in l)if(l.hasOwnProperty($)){var te=l[$].drawableList;for(O=0,S=te.length;O<S;O++)if(!0!==(N=te[O]).culled&&!1!==N.visible){var ne=N.renderFlags;ne.colorOpaque&&(v&&L&&N.saoEnabled?r[F++]=N:N.drawColorOpaque(n)),A&&ne.colorTransparent&&(u[U++]=N),ne.xrayedSilhouetteTransparent&&(m[j++]=N),ne.xrayedSilhouetteOpaque&&(f[k++]=N),ne.highlightedSilhouetteTransparent&&(E[K++]=N),ne.highlightedSilhouetteOpaque&&(g[W++]=N),ne.selectedSilhouetteTransparent&&(R[J++]=N),ne.selectedSilhouetteOpaque&&(D[X++]=N),d&&(ne.edgesOpaque&&(o[H++]=N),ne.edgesTransparent&&(c[G++]=N)),ne.selectedEdgesTransparent&&(C[Z++]=N),ne.selectedEdgesOpaque&&(P[q++]=N),ne.xrayedEdgesTransparent&&(w[Q++]=N),ne.xrayedEdgesOpaque&&(p[V++]=N),ne.highlightedEdgesTransparent&&(b[Y++]=N),ne.highlightedEdgesOpaque&&(T[z++]=N)}}if(F>0)for(n.withSAO=!0,O=0;O<F;O++)r[O].drawColorOpaque(n);if(H>0)for(O=0;O<H;O++)o[O].drawEdgesColorOpaque(n);if(k>0)for(O=0;O<k;O++)f[O].drawSilhouetteXRayed(n);if(V>0)for(O=0;O<V;O++)p[O].drawEdgesXRayed(n);if(j>0||Q>0||U>0||G>0){if(i.enable(i.CULL_FACE),i.enable(i.BLEND),a?(i.blendEquation(i.FUNC_ADD),i.blendFuncSeparate(i.SRC_ALPHA,i.ONE_MINUS_SRC_ALPHA,i.ONE,i.ONE_MINUS_SRC_ALPHA)):(i.blendEquation(i.FUNC_ADD),i.blendFunc(i.SRC_ALPHA,i.ONE_MINUS_SRC_ALPHA)),n.backfaces=!1,s||i.depthMask(!1),(U>0||G>0)&&i.blendFunc(i.SRC_ALPHA,i.ONE_MINUS_SRC_ALPHA),G>0)for(O=0;O<G;O++)(N=c[O]).drawEdgesColorTransparent(n);if(U>0)for(O=0;O<U;O++)(N=u[O]).drawColorTransparent(n);if(Q>0)for(O=0;O<Q;O++)w[O].drawEdgesXRayed(n);if(j>0)for(O=0;O<j;O++)m[O].drawSilhouetteXRayed(n);i.disable(i.BLEND),s||i.depthMask(!0)}if(W>0||z>0){if(n.lastProgramId=null,e.highlightMaterial.glowThrough&&i.clear(i.DEPTH_BUFFER_BIT),z>0)for(O=0;O<z;O++)T[O].drawEdgesHighlighted(n);if(W>0)for(O=0;O<W;O++)g[O].drawSilhouetteHighlighted(n)}if(K>0||Y>0||W>0){if(n.lastProgramId=null,e.selectedMaterial.glowThrough&&i.clear(i.DEPTH_BUFFER_BIT),i.enable(i.BLEND),a?(i.blendEquation(i.FUNC_ADD),i.blendFuncSeparate(i.SRC_ALPHA,i.ONE_MINUS_SRC_ALPHA,i.ONE,i.ONE_MINUS_SRC_ALPHA)):i.blendFunc(i.SRC_ALPHA,i.ONE_MINUS_SRC_ALPHA),i.enable(i.CULL_FACE),Y>0)for(O=0;O<Y;O++)b[O].drawEdgesHighlighted(n);if(K>0)for(O=0;O<K;O++)E[O].drawSilhouetteHighlighted(n);i.disable(i.BLEND)}if(X>0||q>0){if(n.lastProgramId=null,e.selectedMaterial.glowThrough&&i.clear(i.DEPTH_BUFFER_BIT),q>0)for(O=0;O<q;O++)P[O].drawEdgesSelected(n);if(X>0)for(O=0;O<X;O++)D[O].drawSilhouetteSelected(n)}if(J>0||Z>0){if(n.lastProgramId=null,e.selectedMaterial.glowThrough&&i.clear(i.DEPTH_BUFFER_BIT),i.enable(i.CULL_FACE),i.enable(i.BLEND),a?(i.blendEquation(i.FUNC_ADD),i.blendFuncSeparate(i.SRC_ALPHA,i.ONE_MINUS_SRC_ALPHA,i.ONE,i.ONE_MINUS_SRC_ALPHA)):i.blendFunc(i.SRC_ALPHA,i.ONE_MINUS_SRC_ALPHA),Z>0)for(O=0;O<Z;O++)C[O].drawEdgesSelected(n);if(J>0)for(O=0;O<J;O++)R[O].drawSilhouetteSelected(n);i.disable(i.BLEND)}var re=Date.now(),ie=ee.frame;ie.renderTime=(re-M)/1e3,ie.drawElements=n.drawElements,ie.drawArrays=n.drawArrays,ie.useProgram=n.useProgram,ie.bindTexture=n.bindTexture,ie.bindArray=n.bindArray;for(var ae=Ze.MAX_TEXTURE_IMAGE_UNITS,se=0;se<ae;se++)i.activeTexture(i.TEXTURE0+se);i.bindTexture(i.TEXTURE_CUBE_MAP,null),i.bindTexture(i.TEXTURE_2D,null);for(var oe=Ze.MAX_VERTEX_ATTRIBS,le=0;le<oe;le++)i.disableVertexAttribArray(le)}(t)}(t),ee.frame.frameCount++,p=!1)},this.pick=function(){var t=Z.vec3(),n=Z.mat4(),i=Z.mat4(),a=Z.vec3(),s=Z.vec3([0,1,0]),o=new it,u=Z.vec2(),c=Z.vec3(),f=Z.vec3(),p=Z.vec3();return Z.vec3(),Z.vec3(),function(A){var d,v=arguments.length>1&&void 0!==arguments[1]?arguments[1]:o;v.reset(),T();var h=null,I=null;if(v.pickSurface=A.pickSurface,A.canvasPos)c[0]=A.canvasPos[0],c[1]=A.canvasPos[1],h=e.camera.viewMatrix,I=e.camera.projMatrix,v.canvasPos=A.canvasPos;else{var m=Z.frustumMat4(-1,1,-1,1,.01,e.camera.project.far,n);A.matrix?(h=A.matrix,I=m):(f.set(A.origin||[0,0,0]),p.set(A.direction||[0,0,1]),d=Z.addVec3(f,p,t),a[0]=Math.random(),a[1]=Math.random(),a[2]=Math.random(),Z.normalizeVec3(a),Z.cross3Vec3(p,a,s),h=Z.lookAtMat4v(f,d,s,i),I=m,v.origin=f,v.direction=p),c[0]=.5*r.clientWidth,c[1]=.5*r.clientHeight}for(var w in l)if(l.hasOwnProperty(w))for(var g=l[w].drawableList,E=0,R=g.length;E<R;E++){var C=g[E];C.setPickMatrices&&C.setPickMatrices(h,I)}var _=y.getRenderBuffer("pick");_.bind();var B=b(_,c,h,I,A,v);if(!B)return _.unbind(),null;var S=B.delegatePickedEntity?B.delegatePickedEntity():B;return S?(A.pickSurface&&(B.canPickTriangle&&B.canPickTriangle()?(D(_,B,c,h,I,v),B.pickTriangleSurface(h,I,v),v.pickSurfacePrecision=!1):B.canPickWorldPos&&B.canPickWorldPos()&&(u[0]=e.camera.project.near,u[1]=e.camera.project.far,P(_,B,c,h,I,u,v),!1!==A.pickSurfaceNormal&&O(_,B,c,h,I,v),v.pickSurfacePrecision=!1)),_.unbind(),v.entity=S,v):(_.unbind(),null)}}();var P=function(){var t=Z.vec4(),a=Z.vec4(),s=Z.vec4(),o=Z.vec4(),l=Z.vec4(),u=Z.mat4(),c=Z.mat4(),f=Z.mat4();return function(p,A,d,v,h,I,y){n.reset(),n.backfaces=!0,n.frontface=!0,n.pickOrigin=y.origin,n.pickViewMatrix=v,n.pickProjMatrix=h,n.pickZNear=I[0],n.pickZFar=I[1],n.pickElementsCount=A.pickElementsCount,n.pickElementsOffset=A.pickElementsOffset,i.viewport(0,0,i.drawingBufferWidth,i.drawingBufferHeight),i.clearColor(0,0,0,0),i.enable(i.DEPTH_TEST),i.disable(i.CULL_FACE),i.disable(i.BLEND),i.clear(i.COLOR_BUFFER_BIT|i.DEPTH_BUFFER_BIT),A.drawPickDepths(n);var m,w=e.canvas.resolutionScale,g=function(e){var t=[e[0]/256,e[1]/256,e[2]/256,e[3]/256],n=[1/16777216,1/65536,1/256,1];return Z.dotVec4(t,n)}(p.read(Math.round(d[0]*w),Math.round(d[1]*w))),T=(d[0]-r.clientWidth/2)/(r.clientWidth/2),E=-(d[1]-r.clientHeight/2)/(r.clientHeight/2),b=A.origin;if(b){var D=Ie(v,b,u);m=Z.mulMat4(h,D,c)}else m=Z.mulMat4(h,v,c);var P=Z.inverseMat4(m,f);t[0]=T,t[1]=E,t[2]=-1,t[3]=1;var R=Z.transformVec4(P,t);R=Z.mulVec4Scalar(R,1/R[3]),a[0]=T,a[1]=E,a[2]=1,a[3]=1;var C=Z.transformVec4(P,a);C=Z.mulVec4Scalar(C,1/C[3]);var _=Z.subVec3(C,R,s),B=Z.addVec3(R,Z.mulVec4Scalar(_,g,o),l);b&&Z.addVec3(B,b),y.worldPos=B}}();function R(e){for(var t in e.snapPickLayerParams={},e.snapPickLayerNumber=0,l)for(var n=l[t].drawableList,r=0,i=n.length;r<i;r++){var a=n[r];a.drawSnapInitDepthBuf&&!a.culled&&a.visible&&a.pickable&&a.drawSnapInitDepthBuf(e)}return e.snapPickLayerParams}function C(e){for(var t in e.snapPickLayerParams={},e.snapPickLayerNumber=0,l)for(var n=l[t].drawableList,r=0,i=n.length;r<i;r++){var a=n[r];a.drawSnapDepths&&!a.culled&&a.visible&&a.pickable&&a.drawSnapDepths(e)}return e.snapPickLayerParams}function _(e,t){return e/t*2-1}function B(e,t){return 1-e/t*2}function O(t,r,a,s,o,l){n.reset(),n.backfaces=!0,n.frontface=!0,n.pickOrigin=l.origin,n.pickViewMatrix=s,n.pickProjMatrix=o,i.viewport(0,0,i.drawingBufferWidth,i.drawingBufferHeight),i.clearColor(0,0,0,0),i.enable(i.DEPTH_TEST),i.disable(i.CULL_FACE),i.disable(i.BLEND),i.clear(i.COLOR_BUFFER_BIT|i.DEPTH_BUFFER_BIT),r.drawPickNormals(n);var u=e.canvas.resolutionScale,c=t.read(Math.round(a[0]*u),Math.round(a[1]*u)),f=[c[0]/256-.5,c[1]/256-.5,c[2]/256-.5];Z.normalizeVec3(f),l.worldNormal=f}this.snapPick=function(t){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:50,a=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"vertex";n.reset(),n.backfaces=!0,n.frontface=!0,n.pickZNear=e.camera.project.near,n.pickZFar=e.camera.project.far;var s=y.getRenderBuffer("uniquePickColors-aabs",{depthTexture:!0,size:[2*r+1,2*r+1]});n.snapVectorA=[_(t[0],i.drawingBufferWidth),B(t[1],i.drawingBufferHeight)],n.snapInvVectorAB=[i.drawingBufferWidth/(2*r),i.drawingBufferHeight/(2*r)],n.snapMode=a,s.bind(i.RGBA32I),i.viewport(0,0,s.size[0],s.size[1]),i.enable(i.DEPTH_TEST),i.frontFace(i.CCW),i.disable(i.CULL_FACE),i.depthMask(!0),i.disable(i.BLEND),i.depthFunc(i.LESS),i.clear(i.DEPTH_BUFFER_BIT),i.clearBufferiv(i.COLOR,0,new Int32Array([0,0,0,0]));var o=e.camera.viewMatrix,u=e.camera.projMatrix;for(var c in l)if(l.hasOwnProperty(c))for(var f=l[c].drawableList,p=0,A=f.length;p<A;p++){var d=f[p];d.setPickMatrices&&d.setPickMatrices(o,u)}var v=R(n),h=C(n),I=s.readArray(i.RGBA_INTEGER,i.INT,Int32Array,4);s.unbind();var m=null,w=r,g=r,T=4*w+g*s.size[0]*4,E=I.slice(T,T+4);if(0!==E[3]){var b=v[Math.abs(E[3])],D=b.origin,P=b.coordinateScale;m=[E[0]*P[0]+D[0],E[1]*P[1]+D[1],E[2]*P[2]+D[2]]}for(var O=[],S=0;S<I.length;S+=4)if(I[S+3]>0){var N=Math.floor(S/4),L=s.size[0];s.size[1];var x=N%L-Math.floor(L/2),M=Math.floor(N/L)-Math.floor(L/2),F=Math.sqrt(Math.pow(x,2)+Math.pow(M,2));O.push({x:x,y:M,dist:F,result:[I[S+0],I[S+1],I[S+2],I[S+3]]})}var H=null;if(O.length>0){O.sort((function(e,t){return e.dist-t.dist}));var U=h[(O=O[0].result)[3]],G=U.origin,k=U.coordinateScale;H=[O[0]*k[0]+G[0],O[1]*k[1]+G[1],O[2]*k[2]+G[2]]}if(null===m&&null==H)return null;var V=null;return null!==H&&(V=e.camera.projectWorldPos(H)),{worldPos:m,snappedWorldPos:H,snappedCanvasPos:V}},this.addMarker=function(t){this._occlusionTester=this._occlusionTester||new ht(e,y),this._occlusionTester.addMarker(t),e.occlusionTestCountdown=0},this.markerWorldPosUpdated=function(e){this._occlusionTester.markerWorldPosUpdated(e)},this.removeMarker=function(e){this._occlusionTester.removeMarker(e)},this.doOcclusionTest=function(){if(this._occlusionTester&&this._occlusionTester.needOcclusionTest){for(var e in T(),this._occlusionTester.bindRenderBuf(),n.reset(),n.backfaces=!0,n.frontface=!0,i.viewport(0,0,i.drawingBufferWidth,i.drawingBufferHeight),i.clearColor(0,0,0,0),i.enable(i.DEPTH_TEST),i.disable(i.CULL_FACE),i.disable(i.BLEND),i.clear(i.COLOR_BUFFER_BIT|i.DEPTH_BUFFER_BIT),l)if(l.hasOwnProperty(e))for(var t=l[e].drawableList,r=0,a=t.length;r<a;r++){var s=t[r];s.drawOcclusion&&!0!==s.culled&&!1!==s.visible&&!1!==s.pickable&&s.drawOcclusion(n)}this._occlusionTester.drawMarkers(n),this._occlusionTester.doOcclusionTest(),this._occlusionTester.unbindRenderBuf()}},this.readPixels=function(e,t,n,r){var i,a,s,o,l=y.getRenderBuffer("snapshot");for(l.bind(),l.clear(),this.render({force:!0,opaqueOnly:r}),a=0;a<n;a++)s=2*a,o=4*a,i=l.read(e[s],e[s+1]),t[o]=i[0],t[o+1]=i[1],t[o+2]=i[2],t[o+3]=i[3];l.unbind(),p=!0},this.beginSnapshot=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=y.getRenderBuffer("snapshot");e.width&&e.height&&t.setSize([e.width,e.height]),t.bind(),t.clear(),m=!0},this.renderSnapshot=function(){m&&(y.getRenderBuffer("snapshot").clear(),this.render({force:!0,opaqueOnly:!1}),p=!0)},this.readSnapshot=function(e){return y.getRenderBuffer("snapshot").readImage(e)},this.readSnapshotAsCanvas=function(){return y.getRenderBuffer("snapshot").readImageAsCanvas()},this.endSnapshot=function(){m&&(y.getRenderBuffer("snapshot").unbind(),m=!1)},this.destroy=function(){l={},u={},y.destroy(),w.destroy(),g.destroy(),this._occlusionTester&&this._occlusionTester.destroy()}},Bt=function(e){I(n,ve);var t=m(n);function n(e){var r,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return b(this,n),(r=t.call(this,e,i)).KEY_BACKSPACE=8,r.KEY_TAB=9,r.KEY_ENTER=13,r.KEY_SHIFT=16,r.KEY_CTRL=17,r.KEY_ALT=18,r.KEY_PAUSE_BREAK=19,r.KEY_CAPS_LOCK=20,r.KEY_ESCAPE=27,r.KEY_PAGE_UP=33,r.KEY_PAGE_DOWN=34,r.KEY_END=35,r.KEY_HOME=36,r.KEY_LEFT_ARROW=37,r.KEY_UP_ARROW=38,r.KEY_RIGHT_ARROW=39,r.KEY_DOWN_ARROW=40,r.KEY_INSERT=45,r.KEY_DELETE=46,r.KEY_NUM_0=48,r.KEY_NUM_1=49,r.KEY_NUM_2=50,r.KEY_NUM_3=51,r.KEY_NUM_4=52,r.KEY_NUM_5=53,r.KEY_NUM_6=54,r.KEY_NUM_7=55,r.KEY_NUM_8=56,r.KEY_NUM_9=57,r.KEY_A=65,r.KEY_B=66,r.KEY_C=67,r.KEY_D=68,r.KEY_E=69,r.KEY_F=70,r.KEY_G=71,r.KEY_H=72,r.KEY_I=73,r.KEY_J=74,r.KEY_K=75,r.KEY_L=76,r.KEY_M=77,r.KEY_N=78,r.KEY_O=79,r.KEY_P=80,r.KEY_Q=81,r.KEY_R=82,r.KEY_S=83,r.KEY_T=84,r.KEY_U=85,r.KEY_V=86,r.KEY_W=87,r.KEY_X=88,r.KEY_Y=89,r.KEY_Z=90,r.KEY_LEFT_WINDOW=91,r.KEY_RIGHT_WINDOW=92,r.KEY_SELECT_KEY=93,r.KEY_NUMPAD_0=96,r.KEY_NUMPAD_1=97,r.KEY_NUMPAD_2=98,r.KEY_NUMPAD_3=99,r.KEY_NUMPAD_4=100,r.KEY_NUMPAD_5=101,r.KEY_NUMPAD_6=102,r.KEY_NUMPAD_7=103,r.KEY_NUMPAD_8=104,r.KEY_NUMPAD_9=105,r.KEY_MULTIPLY=106,r.KEY_ADD=107,r.KEY_SUBTRACT=109,r.KEY_DECIMAL_POINT=110,r.KEY_DIVIDE=111,r.KEY_F1=112,r.KEY_F2=113,r.KEY_F3=114,r.KEY_F4=115,r.KEY_F5=116,r.KEY_F6=117,r.KEY_F7=118,r.KEY_F8=119,r.KEY_F9=120,r.KEY_F10=121,r.KEY_F11=122,r.KEY_F12=123,r.KEY_NUM_LOCK=144,r.KEY_SCROLL_LOCK=145,r.KEY_SEMI_COLON=186,r.KEY_EQUAL_SIGN=187,r.KEY_COMMA=188,r.KEY_DASH=189,r.KEY_PERIOD=190,r.KEY_FORWARD_SLASH=191,r.KEY_GRAVE_ACCENT=192,r.KEY_OPEN_BRACKET=219,r.KEY_BACK_SLASH=220,r.KEY_CLOSE_BRACKET=221,r.KEY_SINGLE_QUOTE=222,r.KEY_SPACE=32,r.element=i.element,r.altDown=!1,r.ctrlDown=!1,r.mouseDownLeft=!1,r.mouseDownMiddle=!1,r.mouseDownRight=!1,r.keyDown=[],r.enabled=!0,r.keyboardEnabled=!0,r.mouseover=!1,r.mouseCanvasPos=Z.vec2(),r._keyboardEventsElement=i.keyboardEventsElement||document,r._bindEvents(),r}return P(n,[{key:"_bindEvents",value:function(){var e=this;if(!this._eventsBound){this._keyboardEventsElement.addEventListener("keydown",this._keyDownListener=function(t){e.enabled&&e.keyboardEnabled&&"INPUT"!==t.target.tagName&&"TEXTAREA"!==t.target.tagName&&(t.keyCode===e.KEY_CTRL?e.ctrlDown=!0:t.keyCode===e.KEY_ALT?e.altDown=!0:t.keyCode===e.KEY_SHIFT&&(e.shiftDown=!0),e.keyDown[t.keyCode]=!0,e.fire("keydown",t.keyCode,!0))},!1),this._keyboardEventsElement.addEventListener("keyup",this._keyUpListener=function(t){e.enabled&&e.keyboardEnabled&&"INPUT"!==t.target.tagName&&"TEXTAREA"!==t.target.tagName&&(t.keyCode===e.KEY_CTRL?e.ctrlDown=!1:t.keyCode===e.KEY_ALT?e.altDown=!1:t.keyCode===e.KEY_SHIFT&&(e.shiftDown=!1),e.keyDown[t.keyCode]=!1,e.fire("keyup",t.keyCode,!0))}),this.element.addEventListener("mouseenter",this._mouseEnterListener=function(t){e.enabled&&(e.mouseover=!0,e._getMouseCanvasPos(t),e.fire("mouseenter",e.mouseCanvasPos,!0))}),this.element.addEventListener("mouseleave",this._mouseLeaveListener=function(t){e.enabled&&(e.mouseover=!1,e._getMouseCanvasPos(t),e.fire("mouseleave",e.mouseCanvasPos,!0))}),this.element.addEventListener("mousedown",this._mouseDownListener=function(t){if(e.enabled){switch(t.which){case 1:e.mouseDownLeft=!0;break;case 2:e.mouseDownMiddle=!0;break;case 3:e.mouseDownRight=!0}e._getMouseCanvasPos(t),e.element.focus(),e.fire("mousedown",e.mouseCanvasPos,!0),e.mouseover&&t.preventDefault()}}),document.addEventListener("mouseup",this._mouseUpListener=function(t){if(e.enabled){switch(t.which){case 1:e.mouseDownLeft=!1;break;case 2:e.mouseDownMiddle=!1;break;case 3:e.mouseDownRight=!1}e.fire("mouseup",e.mouseCanvasPos,!0)}},!0),document.addEventListener("click",this._clickListener=function(t){if(e.enabled){switch(t.which){case 1:case 3:e.mouseDownLeft=!1,e.mouseDownRight=!1;break;case 2:e.mouseDownMiddle=!1}e._getMouseCanvasPos(t),e.fire("click",e.mouseCanvasPos,!0),e.mouseover&&t.preventDefault()}}),document.addEventListener("dblclick",this._dblClickListener=function(t){if(e.enabled){switch(t.which){case 1:case 3:e.mouseDownLeft=!1,e.mouseDownRight=!1;break;case 2:e.mouseDownMiddle=!1}e._getMouseCanvasPos(t),e.fire("dblclick",e.mouseCanvasPos,!0),e.mouseover&&t.preventDefault()}}),this.element.addEventListener("mousemove",this._mouseMoveListener=function(t){e.enabled&&(e._getMouseCanvasPos(t),e.fire("mousemove",e.mouseCanvasPos,!0),e.mouseover&&t.preventDefault())}),this.element.addEventListener("wheel",this._mouseWheelListener=function(t,n){if(e.enabled){var r=Math.max(-1,Math.min(1,40*-t.deltaY));e.fire("mousewheel",r,!0)}},{passive:!0});var t,n;this.on("mousedown",(function(e){t=e[0],n=e[1]})),this.on("mouseup",(function(r){t>=r[0]-2&&t<=r[0]+2&&n>=r[1]-2&&n<=r[1]+2&&e.fire("mouseclicked",r,!0)})),this._eventsBound=!0}}},{key:"_unbindEvents",value:function(){this._eventsBound&&(this._keyboardEventsElement.removeEventListener("keydown",this._keyDownListener),this._keyboardEventsElement.removeEventListener("keyup",this._keyUpListener),this.element.removeEventListener("mouseenter",this._mouseEnterListener),this.element.removeEventListener("mouseleave",this._mouseLeaveListener),this.element.removeEventListener("mousedown",this._mouseDownListener),document.removeEventListener("mouseup",this._mouseDownListener),document.removeEventListener("click",this._clickListener),document.removeEventListener("dblclick",this._dblClickListener),this.element.removeEventListener("mousemove",this._mouseMoveListener),this.element.removeEventListener("wheel",this._mouseWheelListener),window.OrientationChangeEvent&&window.removeEventListener("orientationchange",this._orientationchangedListener),window.DeviceMotionEvent&&window.removeEventListener("devicemotion",this._deviceMotionListener),window.DeviceOrientationEvent&&window.removeEventListener("deviceorientation",this._deviceOrientListener),this._eventsBound=!1)}},{key:"_getMouseCanvasPos",value:function(e){if(e){for(var t=e.target,n=0,r=0;t.offsetParent;)n+=t.offsetLeft,r+=t.offsetTop,t=t.offsetParent;this.mouseCanvasPos[0]=e.pageX-n,this.mouseCanvasPos[1]=e.pageY-r}else e=window.event,this.mouseCanvasPos[0]=e.x,this.mouseCanvasPos[1]=e.y}},{key:"setEnabled",value:function(e){this.enabled!==e&&this.fire("enabled",this.enabled=e)}},{key:"getEnabled",value:function(){return this.enabled}},{key:"setKeyboardEnabled",value:function(e){this.keyboardEnabled=e}},{key:"getKeyboardEnabled",value:function(){return this.keyboardEnabled}},{key:"destroy",value:function(){v(T(n.prototype),"destroy",this).call(this),this._unbindEvents()}}]),n}(),Ot=new G({}),St=function(){function e(t){for(var n in b(this,e),this.id=Ot.addItem({}),t)t.hasOwnProperty(n)&&(this[n]=t[n])}return P(e,[{key:"destroy",value:function(){Ot.removeItem(this.id)}}]),e}(),Nt=function(e){I(n,ve);var t=m(n);function n(e){var r,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return b(this,n),(r=t.call(this,e,i))._state=new St({boundary:[0,0,100,100]}),r.boundary=i.boundary,r.autoBoundary=i.autoBoundary,r}return P(n,[{key:"type",get:function(){return"Viewport"}},{key:"boundary",get:function(){return this._state.boundary},set:function(e){if(!this._autoBoundary){if(!e){var t=this.scene.canvas.boundary;e=[0,0,t[2],t[3]]}this._state.boundary=e,this.glRedraw(),this.fire("boundary",this._state.boundary)}}},{key:"autoBoundary",get:function(){return this._autoBoundary},set:function(e){(e=!!e)!==this._autoBoundary&&(this._autoBoundary=e,this._autoBoundary?this._onCanvasSize=this.scene.canvas.on("boundary",(function(e){var t=e[2],n=e[3];this._state.boundary=[0,0,t,n],this.glRedraw(),this.fire("boundary",this._state.boundary)}),this):this._onCanvasSize&&(this.scene.canvas.off(this._onCanvasSize),this._onCanvasSize=null),this.fire("autoBoundary",this._autoBoundary))}},{key:"_getState",value:function(){return this._state}},{key:"destroy",value:function(){v(T(n.prototype),"destroy",this).call(this),this._state.destroy()}}]),n}(),Lt=function(e){I(n,ve);var t=m(n);function n(e){var r,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return b(this,n),(r=t.call(this,e,i)).camera=e,r._state=new St({matrix:Z.mat4(),inverseMatrix:Z.mat4(),transposedMatrix:Z.mat4(),near:.1,far:2e3}),r._inverseMatrixDirty=!0,r._transposedMatrixDirty=!0,r._fov=60,r._canvasResized=r.scene.canvas.on("boundary",r._needUpdate,g(r)),r.fov=i.fov,r.fovAxis=i.fovAxis,r.near=i.near,r.far=i.far,r}return P(n,[{key:"type",get:function(){return"Perspective"}},{key:"_update",value:function(){var e=this.scene.canvas.boundary,t=e[2]/e[3],n=this._fovAxis,r=this._fov;("x"===n||"min"===n&&t<1||"max"===n&&t>1)&&(r/=t),r=Math.min(r,120),Z.perspectiveMat4(r*(Math.PI/180),t,this._state.near,this._state.far,this._state.matrix),this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!0,this.glRedraw(),this.camera._updateScheduled=!0,this.fire("matrix",this._state.matrix)}},{key:"fov",get:function(){return this._fov},set:function(e){(e=null!=e?e:60)!==this._fov&&(this._fov=e,this._needUpdate(0),this.fire("fov",this._fov))}},{key:"fovAxis",get:function(){return this._fovAxis},set:function(e){e=e||"min",this._fovAxis!==e&&("x"!==e&&"y"!==e&&"min"!==e&&(this.error("Unsupported value for 'fovAxis': "+e+" - defaulting to 'min'"),e="min"),this._fovAxis=e,this._needUpdate(0),this.fire("fovAxis",this._fovAxis))}},{key:"near",get:function(){return this._state.near},set:function(e){var t=null!=e?e:.1;this._state.near!==t&&(this._state.near=t,this._needUpdate(0),this.fire("near",this._state.near))}},{key:"far",get:function(){return this._state.far},set:function(e){var t=null!=e?e:2e3;this._state.far!==t&&(this._state.far=t,this._needUpdate(0),this.fire("far",this._state.far))}},{key:"matrix",get:function(){return this._updateScheduled&&this._doUpdate(),this._state.matrix}},{key:"inverseMatrix",get:function(){return this._updateScheduled&&this._doUpdate(),this._inverseMatrixDirty&&(Z.inverseMat4(this._state.matrix,this._state.inverseMatrix),this._inverseMatrixDirty=!1),this._state.inverseMatrix}},{key:"transposedMatrix",get:function(){return this._updateScheduled&&this._doUpdate(),this._transposedMatrixDirty&&(Z.transposeMat4(this._state.matrix,this._state.transposedMatrix),this._transposedMatrixDirty=!1),this._state.transposedMatrix}},{key:"unproject",value:function(e,t,n,r,i){var a=this.scene.canvas.canvas,s=a.offsetWidth/2,o=a.offsetHeight/2;return n[0]=(e[0]-s)/s,n[1]=(e[1]-o)/o,n[2]=t,n[3]=1,Z.mulMat4v4(this.inverseMatrix,n,r),Z.mulVec3Scalar(r,1/r[3]),r[3]=1,r[1]*=-1,Z.mulMat4v4(this.camera.inverseViewMatrix,r,i),i}},{key:"destroy",value:function(){v(T(n.prototype),"destroy",this).call(this),this._state.destroy(),this.scene.canvas.off(this._canvasResized)}}]),n}(),xt=function(e){I(n,ve);var t=m(n);function n(e){var r,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return b(this,n),(r=t.call(this,e,i)).camera=e,r._state=new St({matrix:Z.mat4(),inverseMatrix:Z.mat4(),transposedMatrix:Z.mat4(),near:.1,far:2e3}),r._inverseMatrixDirty=!0,r._transposedMatrixDirty=!0,r.scale=i.scale,r.near=i.near,r.far=i.far,r._onCanvasBoundary=r.scene.canvas.on("boundary",r._needUpdate,g(r)),r}return P(n,[{key:"type",get:function(){return"Ortho"}},{key:"_update",value:function(){var e,t,n,r,i=this.scene,a=.5*this._scale,s=i.canvas.boundary,o=s[2],l=s[3],u=o/l;o>l?(e=-a,t=a,n=a/u,r=-a/u):(e=-a*u,t=a*u,n=a,r=-a),Z.orthoMat4c(e,t,r,n,this._state.near,this._state.far,this._state.matrix),this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!0,this.glRedraw(),this.fire("matrix",this._state.matrix)}},{key:"scale",get:function(){return this._scale},set:function(e){null==e&&(e=1),e<=0&&(e=.01),this._scale=e,this._needUpdate(0),this.fire("scale",this._scale)}},{key:"near",get:function(){return this._state.near},set:function(e){var t=null!=e?e:.1;this._state.near!==t&&(this._state.near=t,this._needUpdate(0),this.fire("near",this._state.near))}},{key:"far",get:function(){return this._state.far},set:function(e){var t=null!=e?e:2e3;this._state.far!==t&&(this._state.far=t,this._needUpdate(0),this.fire("far",this._state.far))}},{key:"matrix",get:function(){return this._updateScheduled&&this._doUpdate(),this._state.matrix}},{key:"inverseMatrix",get:function(){return this._updateScheduled&&this._doUpdate(),this._inverseMatrixDirty&&(Z.inverseMat4(this._state.matrix,this._state.inverseMatrix),this._inverseMatrixDirty=!1),this._state.inverseMatrix}},{key:"transposedMatrix",get:function(){return this._updateScheduled&&this._doUpdate(),this._transposedMatrixDirty&&(Z.transposeMat4(this._state.matrix,this._state.transposedMatrix),this._transposedMatrixDirty=!1),this._state.transposedMatrix}},{key:"unproject",value:function(e,t,n,r,i){var a=this.scene.canvas.canvas,s=a.offsetWidth/2,o=a.offsetHeight/2;return n[0]=(e[0]-s)/s,n[1]=(e[1]-o)/o,n[2]=t,n[3]=1,Z.mulMat4v4(this.inverseMatrix,n,r),Z.mulVec3Scalar(r,1/r[3]),r[3]=1,r[1]*=-1,Z.mulMat4v4(this.camera.inverseViewMatrix,r,i),i}},{key:"destroy",value:function(){v(T(n.prototype),"destroy",this).call(this),this._state.destroy(),this.scene.canvas.off(this._onCanvasBoundary)}}]),n}(),Mt=function(e){I(n,ve);var t=m(n);function n(e){var r,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return b(this,n),(r=t.call(this,e,i)).camera=e,r._state=new St({matrix:Z.mat4(),inverseMatrix:Z.mat4(),transposedMatrix:Z.mat4(),near:.1,far:1e4}),r._left=-1,r._right=1,r._bottom=-1,r._top=1,r._inverseMatrixDirty=!0,r._transposedMatrixDirty=!0,r.left=i.left,r.right=i.right,r.bottom=i.bottom,r.top=i.top,r.near=i.near,r.far=i.far,r}return P(n,[{key:"type",get:function(){return"Frustum"}},{key:"_update",value:function(){Z.frustumMat4(this._left,this._right,this._bottom,this._top,this._state.near,this._state.far,this._state.matrix),this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!0,this.glRedraw(),this.fire("matrix",this._state.matrix)}},{key:"left",get:function(){return this._left},set:function(e){this._left=null!=e?e:-1,this._needUpdate(0),this.fire("left",this._left)}},{key:"right",get:function(){return this._right},set:function(e){this._right=null!=e?e:1,this._needUpdate(0),this.fire("right",this._right)}},{key:"top",get:function(){return this._top},set:function(e){this._top=null!=e?e:1,this._needUpdate(0),this.fire("top",this._top)}},{key:"bottom",get:function(){return this._bottom},set:function(e){this._bottom=null!=e?e:-1,this._needUpdate(0),this.fire("bottom",this._bottom)}},{key:"near",get:function(){return this._state.near},set:function(e){this._state.near=null!=e?e:.1,this._needUpdate(0),this.fire("near",this._state.near)}},{key:"far",get:function(){return this._state.far},set:function(e){this._state.far=null!=e?e:1e4,this._needUpdate(0),this.fire("far",this._state.far)}},{key:"matrix",get:function(){return this._updateScheduled&&this._doUpdate(),this._state.matrix}},{key:"inverseMatrix",get:function(){return this._updateScheduled&&this._doUpdate(),this._inverseMatrixDirty&&(Z.inverseMat4(this._state.matrix,this._state.inverseMatrix),this._inverseMatrixDirty=!1),this._state.inverseMatrix}},{key:"transposedMatrix",get:function(){return this._updateScheduled&&this._doUpdate(),this._transposedMatrixDirty&&(Z.transposeMat4(this._state.matrix,this._state.transposedMatrix),this._transposedMatrixDirty=!1),this._state.transposedMatrix}},{key:"unproject",value:function(e,t,n,r,i){var a=this.scene.canvas.canvas,s=a.offsetWidth/2,o=a.offsetHeight/2;return n[0]=(e[0]-s)/s,n[1]=(e[1]-o)/o,n[2]=t,n[3]=1,Z.mulMat4v4(this.inverseMatrix,n,r),Z.mulVec3Scalar(r,1/r[3]),r[3]=1,r[1]*=-1,Z.mulMat4v4(this.camera.inverseViewMatrix,r,i),i}},{key:"destroy",value:function(){v(T(n.prototype),"destroy",this).call(this),this._state.destroy(),v(T(n.prototype),"destroy",this).call(this)}}]),n}(),Ft=function(e){I(n,ve);var t=m(n);function n(e){var r,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return b(this,n),(r=t.call(this,e,i)).camera=e,r._state=new St({matrix:Z.mat4(),inverseMatrix:Z.mat4(),transposedMatrix:Z.mat4()}),r._inverseMatrixDirty=!0,r._transposedMatrixDirty=!1,r.matrix=i.matrix,r}return P(n,[{key:"type",get:function(){return"CustomProjection"}},{key:"matrix",get:function(){return this._state.matrix},set:function(e){this._state.matrix.set(e||[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!0,this.glRedraw(),this.fire("matrix",this._state.matrix)}},{key:"inverseMatrix",get:function(){return this._updateScheduled&&this._doUpdate(),this._inverseMatrixDirty&&(Z.inverseMat4(this._state.matrix,this._state.inverseMatrix),this._inverseMatrixDirty=!1),this._state.inverseMatrix}},{key:"transposedMatrix",get:function(){return this._updateScheduled&&this._doUpdate(),this._transposedMatrixDirty&&(Z.transposeMat4(this._state.matrix,this._state.transposedMatrix),this._transposedMatrixDirty=!1),this._state.transposedMatrix}},{key:"unproject",value:function(e,t,n,r,i){var a=this.scene.canvas.canvas,s=a.offsetWidth/2,o=a.offsetHeight/2;return n[0]=(e[0]-s)/s,n[1]=(e[1]-o)/o,n[2]=t,n[3]=1,Z.mulMat4v4(this.inverseMatrix,n,r),Z.mulVec3Scalar(r,1/r[3]),r[3]=1,r[1]*=-1,Z.mulMat4v4(this.camera.inverseViewMatrix,r,i),i}},{key:"destroy",value:function(){v(T(n.prototype),"destroy",this).call(this),this._state.destroy()}}]),n}(),Ht=Z.vec3(),Ut=Z.vec3(),Gt=Z.vec3(),kt=Z.vec3(),Vt=Z.vec3(),jt=Z.vec3(),Qt=Z.vec4(),Wt=Z.vec4(),zt=Z.vec4(),Kt=Z.mat4(),Yt=Z.mat4(),Xt=Z.vec3(),qt=Z.vec3(),Jt=Z.vec3(),Zt=Z.vec3(),$t=function(e){I(n,ve);var t=m(n);function n(e){var r,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return b(this,n),(r=t.call(this,e,i))._state=new St({deviceMatrix:Z.mat4(),hasDeviceMatrix:!1,matrix:Z.mat4(),normalMatrix:Z.mat4(),inverseMatrix:Z.mat4()}),r._perspective=new Lt(g(r)),r._ortho=new xt(g(r)),r._frustum=new Mt(g(r)),r._customProjection=new Ft(g(r)),r._project=r._perspective,r._eye=Z.vec3([0,0,10]),r._look=Z.vec3([0,0,0]),r._up=Z.vec3([0,1,0]),r._worldUp=Z.vec3([0,1,0]),r._worldRight=Z.vec3([1,0,0]),r._worldForward=Z.vec3([0,0,-1]),r.deviceMatrix=i.deviceMatrix,r.eye=i.eye,r.look=i.look,r.up=i.up,r.worldAxis=i.worldAxis,r.gimbalLock=i.gimbalLock,r.constrainPitch=i.constrainPitch,r.projection=i.projection,r._perspective.on("matrix",(function(){"perspective"===r._projectionType&&r.fire("projMatrix",r._perspective.matrix)})),r._ortho.on("matrix",(function(){"ortho"===r._projectionType&&r.fire("projMatrix",r._ortho.matrix)})),r._frustum.on("matrix",(function(){"frustum"===r._projectionType&&r.fire("projMatrix",r._frustum.matrix)})),r._customProjection.on("matrix",(function(){"customProjection"===r._projectionType&&r.fire("projMatrix",r._customProjection.matrix)})),r}return P(n,[{key:"type",get:function(){return"Camera"}},{key:"_update",value:function(){var e,t=this._state;"ortho"===this.projection?(Z.subVec3(this._eye,this._look,Xt),Z.normalizeVec3(Xt,qt),Z.mulVec3Scalar(qt,1e3,Jt),Z.addVec3(this._look,Jt,Zt),e=Zt):e=this._eye,t.hasDeviceMatrix?(Z.lookAtMat4v(e,this._look,this._up,Yt),Z.mulMat4(t.deviceMatrix,Yt,t.matrix)):Z.lookAtMat4v(e,this._look,this._up,t.matrix),Z.inverseMat4(this._state.matrix,this._state.inverseMatrix),Z.transposeMat4(this._state.inverseMatrix,this._state.normalMatrix),this.glRedraw(),this.fire("matrix",this._state.matrix),this.fire("viewMatrix",this._state.matrix)}},{key:"orbitYaw",value:function(e){var t=Z.subVec3(this._eye,this._look,Ht);Z.rotationMat4v(.0174532925*e,this._gimbalLock?this._worldUp:this._up,Kt),t=Z.transformPoint3(Kt,t,Ut),this.eye=Z.addVec3(this._look,t,Gt),this.up=Z.transformPoint3(Kt,this._up,kt)}},{key:"orbitPitch",value:function(e){if(!(this._constrainPitch&&(e=Z.dotVec3(this._up,this._worldUp)/Z.DEGTORAD)<1)){var t=Z.subVec3(this._eye,this._look,Ht),n=Z.cross3Vec3(Z.normalizeVec3(t,Ut),Z.normalizeVec3(this._up,Gt));Z.rotationMat4v(.0174532925*e,n,Kt),t=Z.transformPoint3(Kt,t,kt),this.up=Z.transformPoint3(Kt,this._up,Vt),this.eye=Z.addVec3(t,this._look,jt)}}},{key:"yaw",value:function(e){var t=Z.subVec3(this._look,this._eye,Ht);Z.rotationMat4v(.0174532925*e,this._gimbalLock?this._worldUp:this._up,Kt),t=Z.transformPoint3(Kt,t,Ut),this.look=Z.addVec3(t,this._eye,Gt),this._gimbalLock&&(this.up=Z.transformPoint3(Kt,this._up,kt))}},{key:"pitch",value:function(e){if(!(this._constrainPitch&&(e=Z.dotVec3(this._up,this._worldUp)/Z.DEGTORAD)<1)){var t=Z.subVec3(this._look,this._eye,Ht),n=Z.cross3Vec3(Z.normalizeVec3(t,Ut),Z.normalizeVec3(this._up,Gt));Z.rotationMat4v(.0174532925*e,n,Kt),this.up=Z.transformPoint3(Kt,this._up,jt),t=Z.transformPoint3(Kt,t,kt),this.look=Z.addVec3(t,this._eye,Vt)}}},{key:"pan",value:function(e){var t,n=Z.subVec3(this._eye,this._look,Ht),r=[0,0,0];if(0!==e[0]){var i=Z.cross3Vec3(Z.normalizeVec3(n,[]),Z.normalizeVec3(this._up,Ut));t=Z.mulVec3Scalar(i,e[0]),r[0]+=t[0],r[1]+=t[1],r[2]+=t[2]}0!==e[1]&&(t=Z.mulVec3Scalar(Z.normalizeVec3(this._up,Gt),e[1]),r[0]+=t[0],r[1]+=t[1],r[2]+=t[2]),0!==e[2]&&(t=Z.mulVec3Scalar(Z.normalizeVec3(n,kt),e[2]),r[0]+=t[0],r[1]+=t[1],r[2]+=t[2]),this.eye=Z.addVec3(this._eye,r,Vt),this.look=Z.addVec3(this._look,r,jt)}},{key:"zoom",value:function(e){var t=Z.subVec3(this._eye,this._look,Ht),n=Math.abs(Z.lenVec3(t,Ut)),r=Math.abs(n+e);if(!(r<.5)){var i=Z.normalizeVec3(t,Gt);this.eye=Z.addVec3(this._look,Z.mulVec3Scalar(i,r),kt)}}},{key:"eye",get:function(){return this._eye},set:function(e){this._eye.set(e||[0,0,10]),this._needUpdate(0),this.fire("eye",this._eye)}},{key:"look",get:function(){return this._look},set:function(e){this._look.set(e||[0,0,0]),this._needUpdate(0),this.fire("look",this._look)}},{key:"up",get:function(){return this._up},set:function(e){this._up.set(e||[0,1,0]),this._needUpdate(0),this.fire("up",this._up)}},{key:"deviceMatrix",get:function(){return this._state.deviceMatrix},set:function(e){this._state.deviceMatrix.set(e||[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),this._state.hasDeviceMatrix=!!e,this._needUpdate(0),this.fire("deviceMatrix",this._state.deviceMatrix)}},{key:"worldAxis",get:function(){return this._worldAxis},set:function(e){e=e||[1,0,0,0,1,0,0,0,1],this._worldAxis?this._worldAxis.set(e):this._worldAxis=Z.vec3(e),this._worldRight[0]=this._worldAxis[0],this._worldRight[1]=this._worldAxis[1],this._worldRight[2]=this._worldAxis[2],this._worldUp[0]=this._worldAxis[3],this._worldUp[1]=this._worldAxis[4],this._worldUp[2]=this._worldAxis[5],this._worldForward[0]=this._worldAxis[6],this._worldForward[1]=this._worldAxis[7],this._worldForward[2]=this._worldAxis[8],this.fire("worldAxis",this._worldAxis)}},{key:"worldUp",get:function(){return this._worldUp}},{key:"xUp",get:function(){return this._worldUp[0]>this._worldUp[1]&&this._worldUp[0]>this._worldUp[2]}},{key:"yUp",get:function(){return this._worldUp[1]>this._worldUp[0]&&this._worldUp[1]>this._worldUp[2]}},{key:"zUp",get:function(){return this._worldUp[2]>this._worldUp[0]&&this._worldUp[2]>this._worldUp[1]}},{key:"worldRight",get:function(){return this._worldRight}},{key:"worldForward",get:function(){return this._worldForward}},{key:"gimbalLock",get:function(){return this._gimbalLock},set:function(e){this._gimbalLock=!1!==e,this.fire("gimbalLock",this._gimbalLock)}},{key:"constrainPitch",set:function(e){this._constrainPitch=!!e,this.fire("constrainPitch",this._constrainPitch)}},{key:"eyeLookDist",get:function(){return Z.lenVec3(Z.subVec3(this._look,this._eye,Ht))}},{key:"matrix",get:function(){return this._updateScheduled&&this._doUpdate(),this._state.matrix}},{key:"viewMatrix",get:function(){return this._updateScheduled&&this._doUpdate(),this._state.matrix}},{key:"normalMatrix",get:function(){return this._updateScheduled&&this._doUpdate(),this._state.normalMatrix}},{key:"viewNormalMatrix",get:function(){return this._updateScheduled&&this._doUpdate(),this._state.normalMatrix}},{key:"inverseViewMatrix",get:function(){return this._updateScheduled&&this._doUpdate(),this._state.inverseMatrix}},{key:"projMatrix",get:function(){return this[this.projection].matrix}},{key:"perspective",get:function(){return this._perspective}},{key:"ortho",get:function(){return this._ortho}},{key:"frustum",get:function(){return this._frustum}},{key:"customProjection",get:function(){return this._customProjection}},{key:"projection",get:function(){return this._projectionType},set:function(e){e=e||"perspective",this._projectionType!==e&&("perspective"===e?this._project=this._perspective:"ortho"===e?this._project=this._ortho:"frustum"===e?this._project=this._frustum:"customProjection"===e?this._project=this._customProjection:(this.error("Unsupported value for 'projection': "+e+" defaulting to 'perspective'"),this._project=this._perspective,e="perspective"),this._project._update(),this._projectionType=e,this.glRedraw(),this._update(),this.fire("dirty"),this.fire("projection",this._projectionType),this.fire("projMatrix",this._project.matrix))}},{key:"project",get:function(){return this._project}},{key:"projectWorldPos",value:function(e){var t=Qt,n=Wt,r=zt;t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=1,Z.mulMat4v4(this.viewMatrix,t,n),Z.mulMat4v4(this.projMatrix,n,r),Z.mulVec3Scalar(r,1/r[3]),r[3]=1,r[1]*=-1;var i=this.scene.canvas.canvas,a=i.offsetWidth/2,s=i.offsetHeight/2;return[r[0]*a+a,r[1]*s+s]}},{key:"destroy",value:function(){v(T(n.prototype),"destroy",this).call(this),this._state.destroy()}}]),n}(),en=function(e){I(n,ve);var t=m(n);function n(e){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return b(this,n),t.call(this,e,r)}return P(n,[{key:"type",get:function(){return"Light"}},{key:"isLight",get:function(){return!0}}]),n}(),tn=function(e){I(n,en);var t=m(n);function n(e){var r,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};b(this,n),(r=t.call(this,e,i))._shadowRenderBuf=null,r._shadowViewMatrix=null,r._shadowProjMatrix=null,r._shadowViewMatrixDirty=!0,r._shadowProjMatrixDirty=!0;var a=r.scene.camera,s=r.scene.canvas;return r._onCameraViewMatrix=a.on("viewMatrix",(function(){r._shadowViewMatrixDirty=!0})),r._onCameraProjMatrix=a.on("projMatrix",(function(){r._shadowProjMatrixDirty=!0})),r._onCanvasBoundary=s.on("boundary",(function(){r._shadowProjMatrixDirty=!0})),r._state=new St({type:"dir",dir:Z.vec3([1,1,1]),color:Z.vec3([.7,.7,.8]),intensity:1,space:i.space||"view",castsShadow:!1,getShadowViewMatrix:function(){if(r._shadowViewMatrixDirty){r._shadowViewMatrix||(r._shadowViewMatrix=Z.identityMat4());var e=r.scene.camera,t=r._state.dir,n=e.look,i=[n[0]-t[0],n[1]-t[1],n[2]-t[2]];Z.lookAtMat4v(i,n,[0,1,0],r._shadowViewMatrix),r._shadowViewMatrixDirty=!1}return r._shadowViewMatrix},getShadowProjMatrix:function(){return r._shadowProjMatrixDirty&&(r._shadowProjMatrix||(r._shadowProjMatrix=Z.identityMat4()),Z.orthoMat4c(-40,40,-40,40,-40,80,r._shadowProjMatrix),r._shadowProjMatrixDirty=!1),r._shadowProjMatrix},getShadowRenderBuf:function(){return r._shadowRenderBuf||(r._shadowRenderBuf=new Pt(r.scene.canvas.canvas,r.scene.canvas.gl,{size:[1024,1024]})),r._shadowRenderBuf}}),r.dir=i.dir,r.color=i.color,r.intensity=i.intensity,r.castsShadow=i.castsShadow,r.scene._lightCreated(g(r)),r}return P(n,[{key:"type",get:function(){return"DirLight"}},{key:"dir",get:function(){return this._state.dir},set:function(e){this._state.dir.set(e||[1,1,1]),this._shadowViewMatrixDirty=!0,this.glRedraw()}},{key:"color",get:function(){return this._state.color},set:function(e){this._state.color.set(e||[.7,.7,.8]),this.glRedraw()}},{key:"intensity",get:function(){return this._state.intensity},set:function(e){e=void 0!==e?e:1,this._state.intensity=e,this.glRedraw()}},{key:"castsShadow",get:function(){return this._state.castsShadow},set:function(e){e=!!e,this._state.castsShadow!==e&&(this._state.castsShadow=e,this._shadowViewMatrixDirty=!0,this.glRedraw())}},{key:"destroy",value:function(){var e=this.scene.camera,t=this.scene.canvas;e.off(this._onCameraViewMatrix),e.off(this._onCameraProjMatrix),t.off(this._onCanvasBoundary),v(T(n.prototype),"destroy",this).call(this),this._state.destroy(),this._shadowRenderBuf&&this._shadowRenderBuf.destroy(),this.scene._lightDestroyed(this),this.glRedraw()}}]),n}(),nn=function(e){I(n,en);var t=m(n);function n(e){var r,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return b(this,n),(r=t.call(this,e,i))._state={type:"ambient",color:Z.vec3([.7,.7,.7]),intensity:1},r.color=i.color,r.intensity=i.intensity,r.scene._lightCreated(g(r)),r}return P(n,[{key:"type",get:function(){return"AmbientLight"}},{key:"color",get:function(){return this._state.color},set:function(e){this._state.color.set(e||[.7,.7,.8]),this.glRedraw()}},{key:"intensity",get:function(){return this._state.intensity},set:function(e){this._state.intensity=void 0!==e?e:1,this.glRedraw()}},{key:"destroy",value:function(){v(T(n.prototype),"destroy",this).call(this),this.scene._lightDestroyed(this)}}]),n}(),rn=function(e){I(n,ve);var t=m(n);function n(e){var r,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return b(this,n),r=t.call(this,e,i),ee.memory.meshes++,r}return P(n,[{key:"type",get:function(){return"Geometry"}},{key:"isGeometry",get:function(){return!0}},{key:"destroy",value:function(){v(T(n.prototype),"destroy",this).call(this),ee.memory.meshes--}}]),n}(),an=function(){var e=[],t=[],n=[],r=[],i=[],a=0,s=new Uint16Array(3),o=new Uint16Array(3),l=new Uint16Array(3),u=Z.vec3(),c=Z.vec3(),f=Z.vec3(),p=Z.vec3(),A=Z.vec3(),d=Z.vec3(),v=Z.vec3();return function(h,I,y,m){!function(i,a){var s,o,l,u,c,f,p={},A=Math.pow(10,4),d=0;for(c=0,f=i.length;c<f;c+=3)s=i[c],o=i[c+1],l=i[c+2],void 0===p[u=Math.round(s*A)+"_"+Math.round(o*A)+"_"+Math.round(l*A)]&&(p[u]=d/3,e[d++]=s,e[d++]=o,e[d++]=l),t[c/3]=p[u];for(c=0,f=a.length;c<f;c++)r[c]=t[a[c]],n[r[c]]=a[c]}(h,I),function(t,n){a=0;for(var h=0,I=t;h<I;h+=3){var y=3*r[h],m=3*r[h+1],w=3*r[h+2];n?(s[0]=e[y],s[1]=e[y+1],s[2]=e[y+2],o[0]=e[m],o[1]=e[m+1],o[2]=e[m+2],l[0]=e[w],l[1]=e[w+1],l[2]=e[w+2],Z.decompressPosition(s,n,u),Z.decompressPosition(o,n,c),Z.decompressPosition(l,n,f)):(u[0]=e[y],u[1]=e[y+1],u[2]=e[y+2],c[0]=e[m],c[1]=e[m+1],c[2]=e[m+2],f[0]=e[w],f[1]=e[w+1],f[2]=e[w+2]),Z.subVec3(f,c,p),Z.subVec3(u,c,A),Z.cross3Vec3(p,A,d),Z.normalizeVec3(d,v);var g=i[a]||(i[a]={normal:Z.vec3()});g.normal[0]=v[0],g.normal[1]=v[1],g.normal[2]=v[2],a++}}(I.length,y);for(var w,g,T,E,b,D,P,R,C,_,B=[],O=Math.cos(Z.DEGTORAD*m),S={},N=!1,L=0,x=I.length;L<x;L+=3)for(var M=L/3,F=0;F<3;F++)w=r[L+F],g=r[L+(F+1)%3],void 0===S[b=(T=Math.min(w,g))+","+(E=Math.max(w,g))]?S[b]={index1:T,index2:E,face1:M,face2:void 0}:S[b].face2=M;for(b in S)void 0!==(D=S[b]).face2&&(P=i[D.face1].normal,R=i[D.face2].normal,Z.dotVec3(P,R)>O)||(C=n[D.index1],_=n[D.index2],(!N&&C>65535||_>65535)&&(N=!0),B.push(C),B.push(_));return N?new Uint32Array(B):new Uint16Array(B)}}();var sn=function(){var e=Z.mat4(),t=Z.mat4();return function(n,r){r=r||Z.mat4();var i=n[0],a=n[1],s=n[2],o=n[3]-i,l=n[4]-a,u=n[5]-s,c=65535;return Z.identityMat4(e),Z.translationMat4v(n,e),Z.identityMat4(t),Z.scalingMat4v([o/c,l/c,u/c],t),Z.mulMat4(e,t,r),r}}(),on=function(){var e=Z.mat4(),t=Z.mat4();return function(n,r,i){var a,s=new Uint16Array(n.length),o=new Float32Array([i[0]!==r[0]?65535/(i[0]-r[0]):0,i[1]!==r[1]?65535/(i[1]-r[1]):0,i[2]!==r[2]?65535/(i[2]-r[2]):0]);for(a=0;a<n.length;a+=3)s[a+0]=Math.max(0,Math.min(65535,Math.floor((n[a+0]-r[0])*o[0]))),s[a+1]=Math.max(0,Math.min(65535,Math.floor((n[a+1]-r[1])*o[1]))),s[a+2]=Math.max(0,Math.min(65535,Math.floor((n[a+2]-r[2])*o[2])));return Z.identityMat4(e),Z.translationMat4v(r,e),Z.identityMat4(t),Z.scalingMat4v([(i[0]-r[0])/65535,(i[1]-r[1])/65535,(i[2]-r[2])/65535],t),{quantized:s,decodeMatrix:Z.mulMat4(e,t,Z.identityMat4())}}}();var ln=function(){var e=Z.mat3(),t=Z.mat3();return function(n,r,i){var a,s=new Uint16Array(n.length),o=new Float32Array([65535/(i[0]-r[0]),65535/(i[1]-r[1])]);for(a=0;a<n.length;a+=2)s[a+0]=Math.max(0,Math.min(65535,Math.floor((n[a+0]-r[0])*o[0]))),s[a+1]=Math.max(0,Math.min(65535,Math.floor((n[a+1]-r[1])*o[1])));return Z.identityMat3(e),Z.translationMat3v(r,e),Z.identityMat3(t),Z.scalingMat3v([(i[0]-r[0])/65535,(i[1]-r[1])/65535],t),{quantized:s,decodeMatrix:Z.mulMat3(e,t,Z.identityMat3())}}}();function un(e,t,n,r){var i=e[t]/(Math.abs(e[t])+Math.abs(e[t+1])+Math.abs(e[t+2])),a=e[t+1]/(Math.abs(e[t])+Math.abs(e[t+1])+Math.abs(e[t+2]));if(e[t+2]<0){var s=(1-Math.abs(a))*(i>=0?1:-1),o=(1-Math.abs(i))*(a>=0?1:-1);i=s,a=o}return new Int8Array([Math[n](127.5*i+(i<0?-1:0)),Math[r](127.5*a+(a<0?-1:0))])}function cn(e){var t=e[0],n=e[1];t/=t<0?127:128,n/=n<0?127:128;var r=1-Math.abs(t)-Math.abs(n);r<0&&(t=(1-Math.abs(n))*(t>=0?1:-1),n=(1-Math.abs(t))*(n>=0?1:-1));var i=Math.sqrt(t*t+n*n+r*r);return[t/i,n/i,r/i]}function fn(e,t,n){return e[t]*n[0]+e[t+1]*n[1]+e[t+2]*n[2]}var pn={getPositionsBounds:function(e){var t,n,r=new Float32Array(3),i=new Float32Array(3);for(t=0;t<3;t++)r[t]=Number.MAX_VALUE,i[t]=-Number.MAX_VALUE;for(t=0;t<e.length;t+=3)for(n=0;n<3;n++)r[n]=Math.min(r[n],e[t+n]),i[n]=Math.max(i[n],e[t+n]);return{min:r,max:i}},createPositionsDecodeMatrix:sn,compressPositions:on,compressPosition:function(e,t,n){var r=new Float32Array([t[3]!==t[0]?65535/(t[3]-t[0]):0,t[4]!==t[1]?65535/(t[4]-t[1]):0,t[5]!==t[2]?65535/(t[5]-t[2]):0]);n[0]=Math.max(0,Math.min(65535,Math.floor((e[0]-t[0])*r[0]))),n[1]=Math.max(0,Math.min(65535,Math.floor((e[1]-t[1])*r[1]))),n[2]=Math.max(0,Math.min(65535,Math.floor((e[2]-t[2])*r[2])))},decompressPositions:function(e,t){for(var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:new Float32Array(e.length),r=0,i=e.length;r<i;r+=3)n[r+0]=e[r+0]*t[0]+t[12],n[r+1]=e[r+1]*t[5]+t[13],n[r+2]=e[r+2]*t[10]+t[14];return n},decompressPosition:function(e,t,n){return n[0]=e[0]*t[0]+t[12],n[1]=e[1]*t[5]+t[13],n[2]=e[2]*t[10]+t[14],n},decompressAABB:function(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:e;return n[0]=e[0]*t[0]+t[12],n[1]=e[1]*t[5]+t[13],n[2]=e[2]*t[10]+t[14],n[3]=e[3]*t[0]+t[12],n[4]=e[4]*t[5]+t[13],n[5]=e[5]*t[10]+t[14],n},getUVBounds:function(e){var t,n,r=new Float32Array(2),i=new Float32Array(2);for(t=0;t<2;t++)r[t]=Number.MAX_VALUE,i[t]=-Number.MAX_VALUE;for(t=0;t<e.length;t+=2)for(n=0;n<2;n++)r[n]=Math.min(r[n],e[t+n]),i[n]=Math.max(i[n],e[t+n]);return{min:r,max:i}},compressUVs:ln,decompressUVs:function(e,t){for(var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:new Float32Array(e.length),r=0,i=e.length;r<i;r+=3)n[r+0]=e[r+0]*t[0]+t[6],n[r+1]=e[r+1]*t[4]+t[7];return n},decompressUV:function(e,t,n){n[0]=e[0]*t[0]+t[6],n[1]=e[1]*t[4]+t[7]},compressNormals:function(e){for(var t,n,r,i,a=new Int8Array(e.length),s=0;s<e.length;s+=3)n=t=un(e,s,"floor","floor"),r=i=fn(e,s,cn(t)),(r=fn(e,s,cn(t=un(e,s,"ceil","floor"))))>i&&(n=t,i=r),(r=fn(e,s,cn(t=un(e,s,"floor","ceil"))))>i&&(n=t,i=r),(r=fn(e,s,cn(t=un(e,s,"ceil","ceil"))))>i&&(n=t,i=r),a[s]=n[0],a[s+1]=n[1];return a},decompressNormals:function(e,t){for(var n=0,r=0,i=e.length;n<i;n+=2){var a=e[n+0],s=e[n+1];a=(2*a+1)/255,s=(2*s+1)/255;var o=1-Math.abs(a)-Math.abs(s);o<0&&(a=(1-Math.abs(s))*(a>=0?1:-1),s=(1-Math.abs(a))*(s>=0?1:-1));var l=Math.sqrt(a*a+s*s+o*o);t[r+0]=a/l,t[r+1]=s/l,t[r+2]=o/l,r+=3}return t},decompressNormal:function(e,t){var n=e[0],r=e[1];n=(2*n+1)/255,r=(2*r+1)/255;var i=1-Math.abs(n)-Math.abs(r);i<0&&(n=(1-Math.abs(r))*(n>=0?1:-1),r=(1-Math.abs(n))*(r>=0?1:-1));var a=Math.sqrt(n*n+r*r+i*i);return t[0]=n/a,t[1]=r/a,t[2]=i/a,t}},An=ee.memory,dn=Z.AABB3(),vn=function(e){I(n,rn);var t=m(n);function n(e){var r,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};b(this,n),(r=t.call(this,e,i))._state=new St({compressGeometry:!!i.compressGeometry,primitive:null,primitiveName:null,positions:null,normals:null,colors:null,uv:null,indices:null,positionsDecodeMatrix:null,uvDecodeMatrix:null,positionsBuf:null,normalsBuf:null,colorsbuf:null,uvBuf:null,indicesBuf:null,hash:""}),r._numTriangles=0,r._edgeThreshold=i.edgeThreshold||10,r._edgeIndicesBuf=null,r._pickTrianglePositionsBuf=null,r._pickTriangleColorsBuf=null,r._aabbDirty=!0,r._boundingSphere=!0,r._aabb=null,r._aabbDirty=!0,r._obb=null,r._obbDirty=!0;var a=r._state,s=r.scene.canvas.gl;switch(i.primitive=i.primitive||"triangles",i.primitive){case"points":a.primitive=s.POINTS,a.primitiveName=i.primitive;break;case"lines":a.primitive=s.LINES,a.primitiveName=i.primitive;break;case"line-loop":a.primitive=s.LINE_LOOP,a.primitiveName=i.primitive;break;case"line-strip":a.primitive=s.LINE_STRIP,a.primitiveName=i.primitive;break;case"triangles":a.primitive=s.TRIANGLES,a.primitiveName=i.primitive;break;case"triangle-strip":a.primitive=s.TRIANGLE_STRIP,a.primitiveName=i.primitive;break;case"triangle-fan":a.primitive=s.TRIANGLE_FAN,a.primitiveName=i.primitive;break;default:r.error("Unsupported value for 'primitive': '"+i.primitive+"' - supported values are 'points', 'lines', 'line-loop', 'line-strip', 'triangles', 'triangle-strip' and 'triangle-fan'. Defaulting to 'triangles'."),a.primitive=s.TRIANGLES,a.primitiveName=i.primitive}if(i.positions)if(r._state.compressGeometry){var o=pn.getPositionsBounds(i.positions),l=pn.compressPositions(i.positions,o.min,o.max);a.positions=l.quantized,a.positionsDecodeMatrix=l.decodeMatrix}else a.positions=i.positions.constructor===Float32Array?i.positions:new Float32Array(i.positions);if(i.colors&&(a.colors=i.colors.constructor===Float32Array?i.colors:new Float32Array(i.colors)),i.uv)if(r._state.compressGeometry){var u=pn.getUVBounds(i.uv),c=pn.compressUVs(i.uv,u.min,u.max);a.uv=c.quantized,a.uvDecodeMatrix=c.decodeMatrix}else a.uv=i.uv.constructor===Float32Array?i.uv:new Float32Array(i.uv);return i.normals&&(r._state.compressGeometry?a.normals=pn.compressNormals(i.normals):a.normals=i.normals.constructor===Float32Array?i.normals:new Float32Array(i.normals)),i.indices&&(a.indices=i.indices.constructor===Uint32Array||i.indices.constructor===Uint16Array?i.indices:new Uint32Array(i.indices),"triangles"===r._state.primitiveName&&(r._numTriangles=i.indices.length/3)),r._buildHash(),An.meshes++,r._buildVBOs(),r}return P(n,[{key:"type",get:function(){return"ReadableGeometry"}},{key:"isReadableGeometry",get:function(){return!0}},{key:"_buildVBOs",value:function(){var e=this._state,t=this.scene.canvas.gl;if(e.indices&&(e.indicesBuf=new pt(t,t.ELEMENT_ARRAY_BUFFER,e.indices,e.indices.length,1,t.STATIC_DRAW),An.indices+=e.indicesBuf.numItems),e.positions&&(e.positionsBuf=new pt(t,t.ARRAY_BUFFER,e.positions,e.positions.length,3,t.STATIC_DRAW),An.positions+=e.positionsBuf.numItems),e.normals){var n=e.compressGeometry;e.normalsBuf=new pt(t,t.ARRAY_BUFFER,e.normals,e.normals.length,3,t.STATIC_DRAW,n),An.normals+=e.normalsBuf.numItems}e.colors&&(e.colorsBuf=new pt(t,t.ARRAY_BUFFER,e.colors,e.colors.length,4,t.STATIC_DRAW),An.colors+=e.colorsBuf.numItems),e.uv&&(e.uvBuf=new pt(t,t.ARRAY_BUFFER,e.uv,e.uv.length,2,t.STATIC_DRAW),An.uvs+=e.uvBuf.numItems)}},{key:"_buildHash",value:function(){var e=this._state,t=["/g"];t.push("/"+e.primitive+";"),e.positions&&t.push("p"),e.colors&&t.push("c"),(e.normals||e.autoVertexNormals)&&t.push("n"),e.uv&&t.push("u"),e.compressGeometry&&t.push("cp"),t.push(";"),e.hash=t.join("")}},{key:"_getEdgeIndices",value:function(){return this._edgeIndicesBuf||this._buildEdgeIndices(),this._edgeIndicesBuf}},{key:"_getPickTrianglePositions",value:function(){return this._pickTrianglePositionsBuf||this._buildPickTriangleVBOs(),this._pickTrianglePositionsBuf}},{key:"_getPickTriangleColors",value:function(){return this._pickTriangleColorsBuf||this._buildPickTriangleVBOs(),this._pickTriangleColorsBuf}},{key:"_buildEdgeIndices",value:function(){var e=this._state;if(e.positions&&e.indices){var t=this.scene.canvas.gl,n=an(e.positions,e.indices,e.positionsDecodeMatrix,this._edgeThreshold);this._edgeIndicesBuf=new pt(t,t.ELEMENT_ARRAY_BUFFER,n,n.length,1,t.STATIC_DRAW),An.indices+=this._edgeIndicesBuf.numItems}}},{key:"_buildPickTriangleVBOs",value:function(){var e=this._state;if(e.positions&&e.indices){var t=this.scene.canvas.gl,n=Z.buildPickTriangles(e.positions,e.indices,e.compressGeometry),r=n.positions,i=n.colors;this._pickTrianglePositionsBuf=new pt(t,t.ARRAY_BUFFER,r,r.length,3,t.STATIC_DRAW),this._pickTriangleColorsBuf=new pt(t,t.ARRAY_BUFFER,i,i.length,4,t.STATIC_DRAW,!0),An.positions+=this._pickTrianglePositionsBuf.numItems,An.colors+=this._pickTriangleColorsBuf.numItems}}},{key:"_buildPickVertexVBOs",value:function(){}},{key:"_webglContextLost",value:function(){this._sceneVertexBufs&&this._sceneVertexBufs.webglContextLost()}},{key:"_webglContextRestored",value:function(){this._sceneVertexBufs&&this._sceneVertexBufs.webglContextRestored(),this._buildVBOs(),this._edgeIndicesBuf=null,this._pickVertexPositionsBuf=null,this._pickTrianglePositionsBuf=null,this._pickTriangleColorsBuf=null,this._pickVertexPositionsBuf=null,this._pickVertexColorsBuf=null}},{key:"primitive",get:function(){return this._state.primitiveName}},{key:"compressGeometry",get:function(){return this._state.compressGeometry}},{key:"positions",get:function(){return this._state.positions?this._state.compressGeometry?(this._decompressedPositions||(this._decompressedPositions=new Float32Array(this._state.positions.length),pn.decompressPositions(this._state.positions,this._state.positionsDecodeMatrix,this._decompressedPositions)),this._decompressedPositions):this._state.positions:null},set:function(e){var t=this._state,n=t.positions;if(n)if(n.length===e.length){if(this._state.compressGeometry){var r=pn.getPositionsBounds(e),i=pn.compressPositions(e,r.min,r.max);e=i.quantized,t.positionsDecodeMatrix=i.decodeMatrix}n.set(e),t.positionsBuf&&t.positionsBuf.setData(n),this._setAABBDirty(),this.glRedraw()}else this.error("can't update geometry positions - new positions are wrong length");else this.error("can't update geometry positions - geometry has no positions")}},{key:"normals",get:function(){if(this._state.normals){if(!this._state.compressGeometry)return this._state.normals;if(!this._decompressedNormals){var e=this._state.normals.length,t=e+e/2;this._decompressedNormals=new Float32Array(t),pn.decompressNormals(this._state.normals,this._decompressedNormals)}return this._decompressedNormals}},set:function(e){if(this._state.compressGeometry)this.error("can't update geometry normals - quantized geometry is immutable");else{var t=this._state,n=t.normals;n?n.length===e.length?(n.set(e),t.normalsBuf&&t.normalsBuf.setData(n),this.glRedraw()):this.error("can't update geometry normals - new normals are wrong length"):this.error("can't update geometry normals - geometry has no normals")}}},{key:"uv",get:function(){return this._state.uv?this._state.compressGeometry?(this._decompressedUV||(this._decompressedUV=new Float32Array(this._state.uv.length),pn.decompressUVs(this._state.uv,this._state.uvDecodeMatrix,this._decompressedUV)),this._decompressedUV):this._state.uv:null},set:function(e){if(this._state.compressGeometry)this.error("can't update geometry UVs - quantized geometry is immutable");else{var t=this._state,n=t.uv;n?n.length===e.length?(n.set(e),t.uvBuf&&t.uvBuf.setData(n),this.glRedraw()):this.error("can't update geometry UVs - new UVs are wrong length"):this.error("can't update geometry UVs - geometry has no UVs")}}},{key:"colors",get:function(){return this._state.colors},set:function(e){if(this._state.compressGeometry)this.error("can't update geometry colors - quantized geometry is immutable");else{var t=this._state,n=t.colors;n?n.length===e.length?(n.set(e),t.colorsBuf&&t.colorsBuf.setData(n),this.glRedraw()):this.error("can't update geometry colors - new colors are wrong length"):this.error("can't update geometry colors - geometry has no colors")}}},{key:"indices",get:function(){return this._state.indices}},{key:"aabb",get:function(){return this._aabbDirty&&(this._aabb||(this._aabb=Z.AABB3()),Z.positions3ToAABB3(this._state.positions,this._aabb,this._state.positionsDecodeMatrix),this._aabbDirty=!1),this._aabb}},{key:"obb",get:function(){return this._obbDirty&&(this._obb||(this._obb=Z.OBB3()),Z.positions3ToAABB3(this._state.positions,dn,this._state.positionsDecodeMatrix),Z.AABB3ToOBB3(dn,this._obb),this._obbDirty=!1),this._obb}},{key:"numTriangles",get:function(){return this._numTriangles}},{key:"_setAABBDirty",value:function(){this._aabbDirty||(this._aabbDirty=!0,this._aabbDirty=!0,this._obbDirty=!0)}},{key:"_getState",value:function(){return this._state}},{key:"destroy",value:function(){v(T(n.prototype),"destroy",this).call(this);var e=this._state;e.indicesBuf&&e.indicesBuf.destroy(),e.positionsBuf&&e.positionsBuf.destroy(),e.normalsBuf&&e.normalsBuf.destroy(),e.uvBuf&&e.uvBuf.destroy(),e.colorsBuf&&e.colorsBuf.destroy(),this._edgeIndicesBuf&&this._edgeIndicesBuf.destroy(),this._pickTrianglePositionsBuf&&this._pickTrianglePositionsBuf.destroy(),this._pickTriangleColorsBuf&&this._pickTriangleColorsBuf.destroy(),this._pickVertexPositionsBuf&&this._pickVertexPositionsBuf.destroy(),this._pickVertexColorsBuf&&this._pickVertexColorsBuf.destroy(),e.destroy(),An.meshes--}}]),n}();function hn(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.xSize||1;t<0&&(console.error("negative xSize not allowed - will invert"),t*=-1);var n=e.ySize||1;n<0&&(console.error("negative ySize not allowed - will invert"),n*=-1);var r=e.zSize||1;r<0&&(console.error("negative zSize not allowed - will invert"),r*=-1);var i=e.center,a=i?i[0]:0,s=i?i[1]:0,o=i?i[2]:0,l=-t+a,u=-n+s,c=-r+o,f=t+a,p=n+s,A=r+o;return ae.apply(e,{positions:[f,p,A,l,p,A,l,u,A,f,u,A,f,p,A,f,u,A,f,u,c,f,p,c,f,p,A,f,p,c,l,p,c,l,p,A,l,p,A,l,p,c,l,u,c,l,u,A,l,u,c,f,u,c,f,u,A,l,u,A,f,u,c,l,u,c,l,p,c,f,p,c],normals:[0,0,1,0,0,1,0,0,1,0,0,1,1,0,0,1,0,0,1,0,0,1,0,0,0,1,0,0,1,0,0,1,0,0,1,0,-1,0,0,-1,0,0,-1,0,0,-1,0,0,0,-1,0,0,-1,0,0,-1,0,0,-1,0,0,0,-1,0,0,-1,0,0,-1,0,0,-1],uv:[1,0,0,0,0,1,1,1,0,0,0,1,1,1,1,0,1,1,1,0,0,0,0,1,1,0,0,0,0,1,1,1,0,1,1,1,1,0,0,0,0,1,1,1,1,0,0,0],indices:[0,1,2,0,2,3,4,5,6,4,6,7,8,9,10,8,10,11,12,13,14,12,14,15,16,17,18,16,18,19,20,21,22,20,22,23]})}var In=function(e){I(n,ve);var t=m(n);function n(e){var r,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return b(this,n),r=t.call(this,e,i),ee.memory.materials++,r}return P(n,[{key:"type",get:function(){return"Material"}},{key:"destroy",value:function(){v(T(n.prototype),"destroy",this).call(this),ee.memory.materials--}}]),n}(),yn={opaque:0,mask:1,blend:2},mn=["opaque","mask","blend"],wn=function(e){I(n,In);var t=m(n);function n(e){var r,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return b(this,n),(r=t.call(this,e,i))._state=new St({type:"PhongMaterial",ambient:Z.vec3([1,1,1]),diffuse:Z.vec3([1,1,1]),specular:Z.vec3([1,1,1]),emissive:Z.vec3([0,0,0]),alpha:null,shininess:null,reflectivity:null,alphaMode:null,alphaCutoff:null,lineWidth:null,pointSize:null,backfaces:null,frontface:null,hash:null}),r.ambient=i.ambient,r.diffuse=i.diffuse,r.specular=i.specular,r.emissive=i.emissive,r.alpha=i.alpha,r.shininess=i.shininess,r.reflectivity=i.reflectivity,r.lineWidth=i.lineWidth,r.pointSize=i.pointSize,i.ambientMap&&(r._ambientMap=r._checkComponent("Texture",i.ambientMap)),i.diffuseMap&&(r._diffuseMap=r._checkComponent("Texture",i.diffuseMap)),i.specularMap&&(r._specularMap=r._checkComponent("Texture",i.specularMap)),i.emissiveMap&&(r._emissiveMap=r._checkComponent("Texture",i.emissiveMap)),i.alphaMap&&(r._alphaMap=r._checkComponent("Texture",i.alphaMap)),i.reflectivityMap&&(r._reflectivityMap=r._checkComponent("Texture",i.reflectivityMap)),i.normalMap&&(r._normalMap=r._checkComponent("Texture",i.normalMap)),i.occlusionMap&&(r._occlusionMap=r._checkComponent("Texture",i.occlusionMap)),i.diffuseFresnel&&(r._diffuseFresnel=r._checkComponent("Fresnel",i.diffuseFresnel)),i.specularFresnel&&(r._specularFresnel=r._checkComponent("Fresnel",i.specularFresnel)),i.emissiveFresnel&&(r._emissiveFresnel=r._checkComponent("Fresnel",i.emissiveFresnel)),i.alphaFresnel&&(r._alphaFresnel=r._checkComponent("Fresnel",i.alphaFresnel)),i.reflectivityFresnel&&(r._reflectivityFresnel=r._checkComponent("Fresnel",i.reflectivityFresnel)),r.alphaMode=i.alphaMode,r.alphaCutoff=i.alphaCutoff,r.backfaces=i.backfaces,r.frontface=i.frontface,r._makeHash(),r}return P(n,[{key:"type",get:function(){return"PhongMaterial"}},{key:"_makeHash",value:function(){var e=this._state,t=["/p"];this._normalMap&&(t.push("/nm"),this._normalMap.hasMatrix&&t.push("/mat")),this._ambientMap&&(t.push("/am"),this._ambientMap.hasMatrix&&t.push("/mat"),t.push("/"+this._ambientMap.encoding)),this._diffuseMap&&(t.push("/dm"),this._diffuseMap.hasMatrix&&t.push("/mat"),t.push("/"+this._diffuseMap.encoding)),this._specularMap&&(t.push("/sm"),this._specularMap.hasMatrix&&t.push("/mat")),this._emissiveMap&&(t.push("/em"),this._emissiveMap.hasMatrix&&t.push("/mat"),t.push("/"+this._emissiveMap.encoding)),this._alphaMap&&(t.push("/opm"),this._alphaMap.hasMatrix&&t.push("/mat")),this._reflectivityMap&&(t.push("/rm"),this._reflectivityMap.hasMatrix&&t.push("/mat")),this._occlusionMap&&(t.push("/ocm"),this._occlusionMap.hasMatrix&&t.push("/mat")),this._diffuseFresnel&&t.push("/df"),this._specularFresnel&&t.push("/sf"),this._emissiveFresnel&&t.push("/ef"),this._alphaFresnel&&t.push("/of"),this._reflectivityFresnel&&t.push("/rf"),t.push(";"),e.hash=t.join("")}},{key:"ambient",get:function(){return this._state.ambient},set:function(e){var t=this._state.ambient;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.ambient=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=.2,t[1]=.2,t[2]=.2),this.glRedraw()}},{key:"diffuse",get:function(){return this._state.diffuse},set:function(e){var t=this._state.diffuse;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.diffuse=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=1,t[1]=1,t[2]=1),this.glRedraw()}},{key:"specular",get:function(){return this._state.specular},set:function(e){var t=this._state.specular;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.specular=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=1,t[1]=1,t[2]=1),this.glRedraw()}},{key:"emissive",get:function(){return this._state.emissive},set:function(e){var t=this._state.emissive;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.emissive=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=0,t[1]=0,t[2]=0),this.glRedraw()}},{key:"alpha",get:function(){return this._state.alpha},set:function(e){e=null!=e?e:1,this._state.alpha!==e&&(this._state.alpha=e,this.glRedraw())}},{key:"shininess",get:function(){return this._state.shininess},set:function(e){this._state.shininess=void 0!==e?e:80,this.glRedraw()}},{key:"lineWidth",get:function(){return this._state.lineWidth},set:function(e){this._state.lineWidth=e||1,this.glRedraw()}},{key:"pointSize",get:function(){return this._state.pointSize},set:function(e){this._state.pointSize=e||1,this.glRedraw()}},{key:"reflectivity",get:function(){return this._state.reflectivity},set:function(e){this._state.reflectivity=void 0!==e?e:1,this.glRedraw()}},{key:"normalMap",get:function(){return this._normalMap}},{key:"ambientMap",get:function(){return this._ambientMap}},{key:"diffuseMap",get:function(){return this._diffuseMap}},{key:"specularMap",get:function(){return this._specularMap}},{key:"emissiveMap",get:function(){return this._emissiveMap}},{key:"alphaMap",get:function(){return this._alphaMap}},{key:"reflectivityMap",get:function(){return this._reflectivityMap}},{key:"occlusionMap",get:function(){return this._occlusionMap}},{key:"diffuseFresnel",get:function(){return this._diffuseFresnel}},{key:"specularFresnel",get:function(){return this._specularFresnel}},{key:"emissiveFresnel",get:function(){return this._emissiveFresnel}},{key:"alphaFresnel",get:function(){return this._alphaFresnel}},{key:"reflectivityFresnel",get:function(){return this._reflectivityFresnel}},{key:"alphaMode",get:function(){return mn[this._state.alphaMode]},set:function(e){var t=yn[e=e||"opaque"];void 0===t&&(this.error("Unsupported value for 'alphaMode': "+e+" - defaulting to 'opaque'"),t="opaque"),this._state.alphaMode!==t&&(this._state.alphaMode=t,this.glRedraw())}},{key:"alphaCutoff",get:function(){return this._state.alphaCutoff},set:function(e){null==e&&(e=.5),this._state.alphaCutoff!==e&&(this._state.alphaCutoff=e)}},{key:"backfaces",get:function(){return this._state.backfaces},set:function(e){e=!!e,this._state.backfaces!==e&&(this._state.backfaces=e,this.glRedraw())}},{key:"frontface",get:function(){return this._state.frontface?"ccw":"cw"},set:function(e){e="cw"!==e,this._state.frontface!==e&&(this._state.frontface=e,this.glRedraw())}},{key:"destroy",value:function(){v(T(n.prototype),"destroy",this).call(this),this._state.destroy()}}]),n}(),gn={default:{fill:!0,fillColor:[.4,.4,.4],fillAlpha:.2,edges:!0,edgeColor:[.2,.2,.2],edgeAlpha:.5,edgeWidth:1},defaultWhiteBG:{fill:!0,fillColor:[1,1,1],fillAlpha:.6,edgeColor:[.2,.2,.2],edgeAlpha:1,edgeWidth:1},defaultLightBG:{fill:!0,fillColor:[.4,.4,.4],fillAlpha:.2,edges:!0,edgeColor:[.2,.2,.2],edgeAlpha:.5,edgeWidth:1},defaultDarkBG:{fill:!0,fillColor:[.4,.4,.4],fillAlpha:.2,edges:!0,edgeColor:[.5,.5,.5],edgeAlpha:.5,edgeWidth:1},phosphorous:{fill:!0,fillColor:[0,0,0],fillAlpha:.4,edges:!0,edgeColor:[.9,.9,.9],edgeAlpha:.5,edgeWidth:2},sunset:{fill:!0,fillColor:[.9,.9,.6],fillAlpha:.2,edges:!0,edgeColor:[.9,.9,.9],edgeAlpha:.5,edgeWidth:1},vectorscope:{fill:!0,fillColor:[0,0,0],fillAlpha:.7,edges:!0,edgeColor:[.2,1,.2],edgeAlpha:1,edgeWidth:2},battlezone:{fill:!0,fillColor:[0,0,0],fillAlpha:1,edges:!0,edgeColor:[.2,1,.2],edgeAlpha:1,edgeWidth:3},sepia:{fill:!0,fillColor:[.970588207244873,.7965892553329468,.6660899519920349],fillAlpha:.4,edges:!0,edgeColor:[.529411792755127,.4577854573726654,.4100345969200134],edgeAlpha:1,edgeWidth:1},yellowHighlight:{fill:!0,fillColor:[1,1,0],fillAlpha:.5,edges:!0,edgeColor:[.529411792755127,.4577854573726654,.4100345969200134],edgeAlpha:1,edgeWidth:1},greenSelected:{fill:!0,fillColor:[0,1,0],fillAlpha:.5,edges:!0,edgeColor:[.4577854573726654,.529411792755127,.4100345969200134],edgeAlpha:1,edgeWidth:1},gamegrid:{fill:!0,fillColor:[.2,.2,.7],fillAlpha:.9,edges:!0,edgeColor:[.4,.4,1.6],edgeAlpha:.8,edgeWidth:3}},Tn=function(e){I(n,In);var t=m(n);function n(e){var r,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return b(this,n),(r=t.call(this,e,i))._state=new St({type:"EmphasisMaterial",fill:null,fillColor:null,fillAlpha:null,edges:null,edgeColor:null,edgeAlpha:null,edgeWidth:null,backfaces:!0,glowThrough:!0}),r._preset="default",i.preset?(r.preset=i.preset,void 0!==i.fill&&(r.fill=i.fill),i.fillColor&&(r.fillColor=i.fillColor),void 0!==i.fillAlpha&&(r.fillAlpha=i.fillAlpha),void 0!==i.edges&&(r.edges=i.edges),i.edgeColor&&(r.edgeColor=i.edgeColor),void 0!==i.edgeAlpha&&(r.edgeAlpha=i.edgeAlpha),void 0!==i.edgeWidth&&(r.edgeWidth=i.edgeWidth),void 0!==i.backfaces&&(r.backfaces=i.backfaces),void 0!==i.glowThrough&&(r.glowThrough=i.glowThrough)):(r.fill=i.fill,r.fillColor=i.fillColor,r.fillAlpha=i.fillAlpha,r.edges=i.edges,r.edgeColor=i.edgeColor,r.edgeAlpha=i.edgeAlpha,r.edgeWidth=i.edgeWidth,r.backfaces=i.backfaces,r.glowThrough=i.glowThrough),r}return P(n,[{key:"type",get:function(){return"EmphasisMaterial"}},{key:"presets",get:function(){return gn}},{key:"fill",get:function(){return this._state.fill},set:function(e){e=!1!==e,this._state.fill!==e&&(this._state.fill=e,this.glRedraw())}},{key:"fillColor",get:function(){return this._state.fillColor},set:function(e){var t=this._state.fillColor;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.fillColor=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=.4,t[1]=.4,t[2]=.4),this.glRedraw()}},{key:"fillAlpha",get:function(){return this._state.fillAlpha},set:function(e){e=null!=e?e:.2,this._state.fillAlpha!==e&&(this._state.fillAlpha=e,this.glRedraw())}},{key:"edges",get:function(){return this._state.edges},set:function(e){e=!1!==e,this._state.edges!==e&&(this._state.edges=e,this.glRedraw())}},{key:"edgeColor",get:function(){return this._state.edgeColor},set:function(e){var t=this._state.edgeColor;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.edgeColor=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=.2,t[1]=.2,t[2]=.2),this.glRedraw()}},{key:"edgeAlpha",get:function(){return this._state.edgeAlpha},set:function(e){e=null!=e?e:.5,this._state.edgeAlpha!==e&&(this._state.edgeAlpha=e,this.glRedraw())}},{key:"edgeWidth",get:function(){return this._state.edgeWidth},set:function(e){this._state.edgeWidth=e||1,this.glRedraw()}},{key:"backfaces",get:function(){return this._state.backfaces},set:function(e){e=!!e,this._state.backfaces!==e&&(this._state.backfaces=e,this.glRedraw())}},{key:"glowThrough",get:function(){return this._state.glowThrough},set:function(e){e=!1!==e,this._state.glowThrough!==e&&(this._state.glowThrough=e,this.glRedraw())}},{key:"preset",get:function(){return this._preset},set:function(e){if(e=e||"default",this._preset!==e){var t=gn[e];t?(this.fill=t.fill,this.fillColor=t.fillColor,this.fillAlpha=t.fillAlpha,this.edges=t.edges,this.edgeColor=t.edgeColor,this.edgeAlpha=t.edgeAlpha,this.edgeWidth=t.edgeWidth,this.glowThrough=t.glowThrough,this._preset=e):this.error("unsupported preset: '"+e+"' - supported values are "+Object.keys(gn).join(", "))}}},{key:"destroy",value:function(){v(T(n.prototype),"destroy",this).call(this),this._state.destroy()}}]),n}(),En={default:{edgeColor:[0,0,0],edgeAlpha:1,edgeWidth:1},defaultWhiteBG:{edgeColor:[.2,.2,.2],edgeAlpha:1,edgeWidth:1},defaultLightBG:{edgeColor:[.2,.2,.2],edgeAlpha:1,edgeWidth:1},defaultDarkBG:{edgeColor:[.5,.5,.5],edgeAlpha:1,edgeWidth:1}},bn=function(e){I(n,In);var t=m(n);function n(e){var r,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return b(this,n),(r=t.call(this,e,i))._state=new St({type:"EdgeMaterial",edges:null,edgeColor:null,edgeAlpha:null,edgeWidth:null}),r._preset="default",i.preset?(r.preset=i.preset,i.edgeColor&&(r.edgeColor=i.edgeColor),void 0!==i.edgeAlpha&&(r.edgeAlpha=i.edgeAlpha),void 0!==i.edgeWidth&&(r.edgeWidth=i.edgeWidth)):(r.edgeColor=i.edgeColor,r.edgeAlpha=i.edgeAlpha,r.edgeWidth=i.edgeWidth),r.edges=!1!==i.edges,r}return P(n,[{key:"type",get:function(){return"EdgeMaterial"}},{key:"presets",get:function(){return En}},{key:"edges",get:function(){return this._state.edges},set:function(e){e=!1!==e,this._state.edges!==e&&(this._state.edges=e,this.glRedraw())}},{key:"edgeColor",get:function(){return this._state.edgeColor},set:function(e){var t=this._state.edgeColor;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.edgeColor=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=.2,t[1]=.2,t[2]=.2),this.glRedraw()}},{key:"edgeAlpha",get:function(){return this._state.edgeAlpha},set:function(e){e=null!=e?e:1,this._state.edgeAlpha!==e&&(this._state.edgeAlpha=e,this.glRedraw())}},{key:"edgeWidth",get:function(){return this._state.edgeWidth},set:function(e){this._state.edgeWidth=e||1,this.glRedraw()}},{key:"preset",get:function(){return this._preset},set:function(e){if(e=e||"default",this._preset!==e){var t=En[e];t?(this.edgeColor=t.edgeColor,this.edgeAlpha=t.edgeAlpha,this.edgeWidth=t.edgeWidth,this._preset=e):this.error("unsupported preset: '"+e+"' - supported values are "+Object.keys(En).join(", "))}}},{key:"destroy",value:function(){v(T(n.prototype),"destroy",this).call(this),this._state.destroy()}}]),n}(),Dn={meters:{abbrev:"m"},metres:{abbrev:"m"},centimeters:{abbrev:"cm"},centimetres:{abbrev:"cm"},millimeters:{abbrev:"mm"},millimetres:{abbrev:"mm"},yards:{abbrev:"yd"},feet:{abbrev:"ft"},inches:{abbrev:"in"}},Pn=function(e){I(n,ve);var t=m(n);function n(e){var r,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return b(this,n),(r=t.call(this,e,i))._units="meters",r._scale=1,r._origin=Z.vec3([0,0,0]),r.units=i.units,r.scale=i.scale,r.origin=i.origin,r}return P(n,[{key:"unitsInfo",get:function(){return Dn}},{key:"units",get:function(){return this._units},set:function(e){e||(e="meters"),Dn[e]||(this.error("Unsupported value for 'units': "+e+" defaulting to 'meters'"),e="meters"),this._units=e,this.fire("units",this._units)}},{key:"scale",get:function(){return this._scale},set:function(e){(e=e||1)<=0?this.error("scale value should be larger than zero"):(this._scale=e,this.fire("scale",this._scale))}},{key:"origin",get:function(){return this._origin},set:function(e){if(!e)return this._origin[0]=0,this._origin[1]=0,void(this._origin[2]=0);this._origin[0]=e[0],this._origin[1]=e[1],this._origin[2]=e[2],this.fire("origin",this._origin)}},{key:"worldToRealPos",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Z.vec3(3);t[0]=this._origin[0]+this._scale*e[0],t[1]=this._origin[1]+this._scale*e[1],t[2]=this._origin[2]+this._scale*e[2]}},{key:"realToWorldPos",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Z.vec3(3);return t[0]=(e[0]-this._origin[0])/this._scale,t[1]=(e[1]-this._origin[1])/this._scale,t[2]=(e[2]-this._origin[2])/this._scale,t}}]),n}(),Rn=function(e){I(n,ve);var t=m(n);function n(e){var r,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return b(this,n),(r=t.call(this,e,i))._supported=Ze.SUPPORTED_EXTENSIONS.OES_standard_derivatives,r.enabled=i.enabled,r.kernelRadius=i.kernelRadius,r.intensity=i.intensity,r.bias=i.bias,r.scale=i.scale,r.minResolution=i.minResolution,r.numSamples=i.numSamples,r.blur=i.blur,r.blendCutoff=i.blendCutoff,r.blendFactor=i.blendFactor,r}return P(n,[{key:"supported",get:function(){return this._supported}},{key:"enabled",get:function(){return this._enabled},set:function(e){e=!!e,this._enabled!==e&&(this._enabled=e,this.glRedraw())}},{key:"possible",get:function(){if(!this._supported)return!1;if(!this._enabled)return!1;var e=this.scene.camera.projection;return"customProjection"!==e&&"frustum"!==e}},{key:"active",get:function(){return this._active}},{key:"kernelRadius",get:function(){return this._kernelRadius},set:function(e){null==e&&(e=100),this._kernelRadius!==e&&(this._kernelRadius=e,this.glRedraw())}},{key:"intensity",get:function(){return this._intensity},set:function(e){null==e&&(e=.15),this._intensity!==e&&(this._intensity=e,this.glRedraw())}},{key:"bias",get:function(){return this._bias},set:function(e){null==e&&(e=.5),this._bias!==e&&(this._bias=e,this.glRedraw())}},{key:"scale",get:function(){return this._scale},set:function(e){null==e&&(e=1),this._scale!==e&&(this._scale=e,this.glRedraw())}},{key:"minResolution",get:function(){return this._minResolution},set:function(e){null==e&&(e=0),this._minResolution!==e&&(this._minResolution=e,this.glRedraw())}},{key:"numSamples",get:function(){return this._numSamples},set:function(e){null==e&&(e=10),this._numSamples!==e&&(this._numSamples=e,this.glRedraw())}},{key:"blur",get:function(){return this._blur},set:function(e){e=!1!==e,this._blur!==e&&(this._blur=e,this.glRedraw())}},{key:"blendCutoff",get:function(){return this._blendCutoff},set:function(e){null==e&&(e=.3),this._blendCutoff!==e&&(this._blendCutoff=e,this.glRedraw())}},{key:"blendFactor",get:function(){return this._blendFactor},set:function(e){null==e&&(e=1),this._blendFactor!==e&&(this._blendFactor=e,this.glRedraw())}},{key:"destroy",value:function(){v(T(n.prototype),"destroy",this).call(this)}}]),n}(),Cn={default:{pointSize:4,roundPoints:!0,perspectivePoints:!0},square:{pointSize:4,roundPoints:!1,perspectivePoints:!0},round:{pointSize:4,roundPoints:!0,perspectivePoints:!0}},_n=function(e){I(n,In);var t=m(n);function n(e){var r,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return b(this,n),(r=t.call(this,e,i))._state=new St({type:"PointsMaterial",pointSize:null,roundPoints:null,perspectivePoints:null,minPerspectivePointSize:null,maxPerspectivePointSize:null,filterIntensity:null,minIntensity:null,maxIntensity:null}),i.preset?(r.preset=i.preset,void 0!==i.pointSize&&(r.pointSize=i.pointSize),void 0!==i.roundPoints&&(r.roundPoints=i.roundPoints),void 0!==i.perspectivePoints&&(r.perspectivePoints=i.perspectivePoints),void 0!==i.minPerspectivePointSize&&(r.minPerspectivePointSize=i.minPerspectivePointSize),void 0!==i.maxPerspectivePointSize&&(r.maxPerspectivePointSize=i.minPerspectivePointSize)):(r._preset="default",r.pointSize=i.pointSize,r.roundPoints=i.roundPoints,r.perspectivePoints=i.perspectivePoints,r.minPerspectivePointSize=i.minPerspectivePointSize,r.maxPerspectivePointSize=i.maxPerspectivePointSize),r.filterIntensity=i.filterIntensity,r.minIntensity=i.minIntensity,r.maxIntensity=i.maxIntensity,r}return P(n,[{key:"type",get:function(){return"PointsMaterial"}},{key:"presets",get:function(){return Cn}},{key:"pointSize",get:function(){return this._state.pointSize},set:function(e){this._state.pointSize=e||2,this.glRedraw()}},{key:"roundPoints",get:function(){return this._state.roundPoints},set:function(e){e=!1!==e,this._state.roundPoints!==e&&(this._state.roundPoints=e,this.scene._needRecompile=!0,this.glRedraw())}},{key:"perspectivePoints",get:function(){return this._state.perspectivePoints},set:function(e){e=!1!==e,this._state.perspectivePoints!==e&&(this._state.perspectivePoints=e,this.scene._needRecompile=!0,this.glRedraw())}},{key:"minPerspectivePointSize",get:function(){return this._state.minPerspectivePointSize},set:function(e){this._state.minPerspectivePointSize=e||1,this.scene._needRecompile=!0,this.glRedraw()}},{key:"maxPerspectivePointSize",get:function(){return this._state.maxPerspectivePointSize},set:function(e){this._state.maxPerspectivePointSize=e||6,this.scene._needRecompile=!0,this.glRedraw()}},{key:"filterIntensity",get:function(){return this._state.filterIntensity},set:function(e){e=!1!==e,this._state.filterIntensity!==e&&(this._state.filterIntensity=e,this.scene._needRecompile=!0,this.glRedraw())}},{key:"minIntensity",get:function(){return this._state.minIntensity},set:function(e){this._state.minIntensity=null!=e?e:0,this.glRedraw()}},{key:"maxIntensity",get:function(){return this._state.maxIntensity},set:function(e){this._state.maxIntensity=null!=e?e:1,this.glRedraw()}},{key:"preset",get:function(){return this._preset},set:function(e){if(e=e||"default",this._preset!==e){var t=Cn[e];t?(this.pointSize=t.pointSize,this.roundPoints=t.roundPoints,this.perspectivePoints=t.perspectivePoints,this.minPerspectivePointSize=t.minPerspectivePointSize,this.maxPerspectivePointSize=t.maxPerspectivePointSize,this._preset=e):this.error("unsupported preset: '"+e+"' - supported values are "+Object.keys(Cn).join(", "))}}},{key:"hash",get:function(){return[this.pointSize,this.roundPoints,this.perspectivePoints,this.minPerspectivePointSize,this.maxPerspectivePointSize,this.filterIntensity].join(";")}},{key:"destroy",value:function(){v(T(n.prototype),"destroy",this).call(this),this._state.destroy()}}]),n}(),Bn={default:{lineWidth:1},thick:{lineWidth:2},thicker:{lineWidth:4}},On=function(e){I(n,In);var t=m(n);function n(e){var r,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return b(this,n),(r=t.call(this,e,i))._state=new St({type:"LinesMaterial",lineWidth:null}),i.preset?(r.preset=i.preset,void 0!==i.lineWidth&&(r.lineWidth=i.lineWidth)):(r._preset="default",r.lineWidth=i.lineWidth),r}return P(n,[{key:"type",get:function(){return"LinesMaterial"}},{key:"presets",get:function(){return Bn}},{key:"lineWidth",get:function(){return this._state.lineWidth},set:function(e){this._state.lineWidth=e||1,this.glRedraw()}},{key:"preset",get:function(){return this._preset},set:function(e){if(e=e||"default",this._preset!==e){var t=Bn[e];t?(this.lineWidth=t.lineWidth,this._preset=e):this.error("unsupported preset: '"+e+"' - supported values are "+Object.keys(Bn).join(", "))}}},{key:"hash",get:function(){return[""+this.lineWidth].join(";")}},{key:"destroy",value:function(){v(T(n.prototype),"destroy",this).call(this),this._state.destroy()}}]),n}(),Sn=Z.vec3(),Nn=Z.vec3(),Ln=Z.mat4(),xn=function(){function e(){b(this,e),this.normal=Z.vec3(),this.offset=0,this.testVertex=Z.vec3()}return P(e,[{key:"set",value:function(e,t,n,r){var i=1/Math.sqrt(e*e+t*t+n*n);this.normal[0]=e*i,this.normal[1]=t*i,this.normal[2]=n*i,this.offset=r*i,this.testVertex[0]=this.normal[0]>=0?1:0,this.testVertex[1]=this.normal[1]>=0?1:0,this.testVertex[2]=this.normal[2]>=0?1:0}}]),e}(),Mn=P((function e(){b(this,e),this.planes=[new xn,new xn,new xn,new xn,new xn,new xn]}));function Fn(e,t,n){var r=Z.mulMat4(n,t,Ln),i=r[0],a=r[1],s=r[2],o=r[3],l=r[4],u=r[5],c=r[6],f=r[7],p=r[8],A=r[9],d=r[10],v=r[11],h=r[12],I=r[13],y=r[14],m=r[15];e.planes[0].set(o-i,f-l,v-p,m-h),e.planes[1].set(o+i,f+l,v+p,m+h),e.planes[2].set(o-a,f-u,v-A,m-I),e.planes[3].set(o+a,f+u,v+A,m+I),e.planes[4].set(o-s,f-c,v-d,m-y),e.planes[5].set(o+s,f+c,v+d,m+y)}function Hn(e,t){var n=Mn.INSIDE,r=Sn,i=Nn;r[0]=t[0],r[1]=t[1],r[2]=t[2],i[0]=t[3],i[1]=t[4],i[2]=t[5];for(var a=[r,i],s=0;s<6;++s){var o=e.planes[s];if(o.normal[0]*a[o.testVertex[0]][0]+o.normal[1]*a[o.testVertex[1]][1]+o.normal[2]*a[o.testVertex[2]][2]+o.offset<0)return Mn.OUTSIDE;o.normal[0]*a[1-o.testVertex[0]][0]+o.normal[1]*a[1-o.testVertex[1]][1]+o.normal[2]*a[1-o.testVertex[2]][2]+o.offset<0&&(n=Mn.INTERSECT)}return n}Mn.INSIDE=0,Mn.INTERSECT=1,Mn.OUTSIDE=2;var Un=function(){function e(t,n){b(this,e),this.primLODLevels=t,this.entitiesInLOD={},this.primCountInLOD={},this.targetFps=n,this.lodLevelIndex=0,this.consecutiveFramesWithTargetFps=0,this.consecutiveFramesWithoutTargetFps=0}return P(e,[{key:"initializeLodState",value:function(e){var t=Object.values(e.objects);if(0!==t.length){for(var n={},r={},i=0,a=t.length;i<a;i++){var s=t[i];s.numPrimitives,Z.getAABB3Diag(s.aabb);var o,l=0;for(l=0,o=this.primLODLevels.length;l<o&&!(s.numPrimitives>=this.primLODLevels[l]);l++);var u=this.primLODLevels[l]||0;u in n||(n[u]=[]),n[u].push(s),u in r||(r[u]=0),r[u]+=s.numPrimitives}this.entitiesInLOD=n,this.primCountInLOD=r}}}]),e}(),Gn=function(){function e(t,n,r,i){b(this,e),this.id=n.id,this.scene=t,this.sceneModel=n,this.lodState=new Un(r,i),this.lodState.initializeLodState(n)}return P(e,[{key:"_increaseLODLevelIndex",value:function(){var e=this.lodState;if(e.lodLevelIndex===e.primLODLevels.length)return!1;for(var t=e.entitiesInLOD[e.primLODLevels[e.lodLevelIndex]]||[],n=0,r=t.length;n<r;n++)t[n].culledLOD=!0;return e.lodLevelIndex++,!0}},{key:"_decreaseLODLevelIndex",value:function(){var e=this.lodState;if(0===e.lodLevelIndex)return!1;for(var t=e.entitiesInLOD[e.primLODLevels[e.lodLevelIndex-1]]||[],n=0,r=t.length;n<r;n++)t[n].culledLOD=!1;return e.lodLevelIndex--,!0}},{key:"applyLodCulling",value:function(e){var t=this.lodState,n=!1;return e<t.targetFps?++t.consecutiveFramesWithoutTargetFps>0&&(t.consecutiveFramesWithoutTargetFps=0,n=this._increaseLODLevelIndex()):e>t.targetFps+4&&++t.consecutiveFramesWithTargetFps>1&&(t.consecutiveFramesWithTargetFps=0,n=this._decreaseLODLevelIndex()),n}},{key:"resetLodCulling",value:function(){var e=!1,t=!1;do{e|=t=this._decreaseLODLevelIndex()}while(t);return e}}]),e}(),kn=function(e){I(n,ve);var t=m(n);function n(e){var r,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return b(this,n),(r=t.call(this,e,i))._scene=e,r._lodLevels=[2e3,600,150,80,20],r._lodManagers={},r._lodManagerList=[],r.enabled=i.enabled,r.targetFPS=i.targetFPS,r._init(),r}return P(n,[{key:"_init",value:function(){var e=this,t=new Array(4),n=0,r=-1,i=Date.now(),a=0,s=0,o=s;this._scene.on("rendering",(function(){if(-1!==r)for(var t=0,n=e._lodManagerList.length;t<n;t++)e._lodManagerList[t].applyLodCulling(r)})),this._scene.on("rendered",(function(){i=Date.now(),window.requestAnimationFrame((function(){n++;var e=Date.now();a=e-i,i=e,t[n%4]=a;var s=0;if(n>4){for(var o=0;o<4;o++)s+=t[o];r=4/s*1e3}}))})),this._scene.camera.on("matrix",(function(){o=s})),this._scene.on("tick",(function(){if(s-o>3)for(var t=0,n=e._lodManagerList.length;t<n;t++)e._lodManagerList[t].resetLodCulling();s++}))}},{key:"enabled",get:function(){return this._enabled},set:function(e){e=!!e,this._enabled!==e&&(this._enabled=e,this.glRedraw())}},{key:"targetFPS",get:function(){return this._targetFPS},set:function(e){null==e&&(e=30),this._targetFPS!==e&&(this._targetFPS=e,this.glRedraw())}},{key:"getLODManager",value:function(e){var t=new Gn(this.scene,e,this._lodLevels,this._targetFPS);return this._lodManagers[t.id]=t,this._lodManagerList=Object.values(this._lodManagers),t}},{key:"putLODManager",value:function(e){delete this._lodManagers[e.id],this._lodManagerList=Object.values(this._lodManagers)}},{key:"destroy",value:function(){v(T(n.prototype),"destroy",this).call(this)}}]),n}(),Vn={},jn={};!function(e){if("object"===E(jn)&&void 0!==Vn)Vn.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{("undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this).RBush3D=e()}}((function(){return function e(t,n,r){function i(s,o){if(!n[s]){if(!t[s]){var l="function"==typeof require&&require;if(!o&&l)return l(s,!0);if(a)return a(s,!0);var u=new Error("Cannot find module '"+s+"'");throw u.code="MODULE_NOT_FOUND",u}var c=n[s]={exports:{}};t[s][0].call(c.exports,(function(e){return i(t[s][1][e]||e)}),c,c.exports,e,t,n,r)}return n[s].exports}for(var a="function"==typeof require&&require,s=0;s<r.length;s++)i(r[s]);return i}({1:[function(e,t,n){Object.defineProperty(n,"__esModule",{value:!0});var r=e("quickselect"),i=[],a=function(e){return i.push(e)},s=function e(t){t&&(a(t),c(t)||t.children.forEach(e))},o=function(e){var t=i.pop();return t?(t.children=e,t.height=1,t.leaf=!0,t.minX=1/0,t.minY=1/0,t.minZ=1/0,t.maxX=-1/0,t.maxY=-1/0,t.maxZ=-1/0):t={children:e,height:1,leaf:!0,minX:1/0,minY:1/0,minZ:1/0,maxX:-1/0,maxY:-1/0,maxZ:-1/0},t},l=[],u=function(e,t){var n=l.pop();return n?(n.dist=e,n.node=t):n={dist:e,node:t},n},c=function(e){return e.leaf},f=function(e,t){return e.leaf},p=function(e,t,n){if(!n)return t.indexOf(e);for(var r=0;r<t.length;r++)if(n(e,t[r]))return r;return-1},A=function(e){d(e,0,e.children.length,e)},d=function(e,t,n,r){var i=r;i?(i.minX=1/0,i.minY=1/0,i.minZ=1/0,i.maxX=-1/0,i.maxY=-1/0,i.maxZ=-1/0):i=o([]);for(var a=t,s=void 0;a<n;a++)s=e.children[a],v(i,s);return i},v=function(e,t){return e.minX=Math.min(e.minX,t.minX),e.minY=Math.min(e.minY,t.minY),e.minZ=Math.min(e.minZ,t.minZ),e.maxX=Math.max(e.maxX,t.maxX),e.maxY=Math.max(e.maxY,t.maxY),e.maxZ=Math.max(e.maxZ,t.maxZ),e},h=function(e){return(e.maxX-e.minX)*(e.maxY-e.minY)*(e.maxZ-e.minZ)},I=function(e){return e.maxX-e.minX+(e.maxY-e.minY)+(e.maxZ-e.minZ)},y=function(e,t){var n=Math.min(e.minX,t.minX),r=Math.min(e.minY,t.minY),i=Math.min(e.minZ,t.minZ);return(Math.max(e.maxX,t.maxX)-n)*(Math.max(e.maxY,t.maxY)-r)*(Math.max(e.maxZ,t.maxZ)-i)},m=function(e,t){var n=Math.max(e.minX,t.minX),r=Math.max(e.minY,t.minY),i=Math.max(e.minZ,t.minZ),a=Math.min(e.maxX,t.maxX),s=Math.min(e.maxY,t.maxY),o=Math.min(e.maxZ,t.maxZ);return Math.max(0,a-n)*Math.max(0,s-r)*Math.max(0,o-i)},w=function(e,t){return e.minX<=t.minX&&e.minY<=t.minY&&e.minZ<=t.minZ&&t.maxX<=e.maxX&&t.maxY<=e.maxY&&t.maxZ<=e.maxZ};n.intersects=function(e,t){return t.minX<=e.maxX&&t.minY<=e.maxY&&t.minZ<=e.maxZ&&t.maxX>=e.minX&&t.maxY>=e.minY&&t.maxZ>=e.minZ},n.boxRayIntersects=function(e,t,n,r,i,a,s){var o=(e.minX-t)*i,l=(e.maxX-t)*i,u=(e.minY-n)*a,c=(e.maxY-n)*a,f=(e.minZ-r)*s,p=(e.maxZ-r)*s,A=Math.min(f,p),d=Math.max(f,p),v=Math.min(u,c),h=Math.max(u,c),I=Math.min(o,l),y=Math.max(o,l),m=Math.max(0,I,v,A);return Math.min(y,h,d)>=m?m:1/0};var g=function(e,t,n,i,a){for(var s,o=[t,n];o.length;)(n=o.pop())-(t=o.pop())<=i||(s=t+Math.ceil((n-t)/i/2)*i,r(e,s,t,n,a),o.push(t,s,s,n))},T=function(e,t){return e.minX-t.minX},E=function(e,t){return e.minY-t.minY},b=function(e,t){return e.minZ-t.minZ},D=function(){function e(e){void 0===e&&(e=16),this.maxEntries=Math.max(e,8),this.minEntries=Math.max(4,Math.ceil(.4*this.maxEntries)),this.clear()}return e.alloc=function(){return this.pool.pop()||new this},e.free=function(e){e.clear(),this.pool.push(e)},e.prototype.searchCustom=function(e,t){var n=this.data,r=[];if(!e(n,f(n)))return r;for(var i=[];n;){for(var a=0,s=n.children.length;a<s;a++){var o=n.children[a];e(o,f(n))&&(f(n)?r.push(o):t(o)?this._all(o,r):i.push(o))}n=i.pop()}return r},e.prototype.analyzeTriangles=function(e){void 0===e&&(e=this.data);var t=0;if(c(e))for(var n=0,r=e.children.length;n<r;n++)t+=e.children[n].numPrimitives;else for(n=0,r=e.children.length;n<r;n++)t+=this.analyzeTriangles(e.children[n]);return e.totalTriangles=t},e.prototype.groupNodesByNumTrianglesThreshold=function(e,t){void 0===t&&(this.analyzeTriangles(),t=this.data);for(var n=[],r=0,i=t.children.length;r<i;r++){var a=t.children[r];n.push({item:a,triangles:a.totalTriangles||a.numPrimitives})}n.sort((function(e,t){return-(e.item.triangles-t.item.triangles)}));var s=[],o=[],l=0;for(r=0,i=n.length;r<i;r++){var u=n[r];if(l+u.triangles<e)o.push(u),l+=u.triangles;else if(o.length&&(s.push(o),o=[],l=0),l+u.triangles<e)r--;else if(f(t,u.item))s.push([u]);else{for(var c=this.groupNodesByNumTrianglesThreshold(e,u.item),p=[],A=0,d=0,v=c.length;d<v-1;d++)s.push(c[r]);if(c.length>1){for(d=0,v=(c=c[c.length-1]).length;d<v;d++)(A+=c[d].triangles)<e?p.push(c[d]):(0==A&&p.push(c[d]),s.push(p),A=0,p=[]);p.forEach((function(e){o.push(e),l+=e.triangles}))}}}return o.length&&s.push(o),s},e.prototype.search=function(e){var t=this.data,r=[];if(!n.intersects(e,t))return r;for(var i=[];t;){for(var a=0,s=t.children.length;a<s;a++){var o=t.children[a];n.intersects(e,o)&&(f(t)?r.push(o):w(e,o)?this._all(o,r):i.push(o))}t=i.pop()}return r},e.prototype.collides=function(e){var t=this.data;if(!n.intersects(e,t))return!1;for(var r=[];t;){for(var i=0,a=t.children.length;i<a;i++){var s=t.children[i];if(n.intersects(e,s)){if(f(t)||w(e,s))return!0;r.push(s)}}t=r.pop()}return!1},e.prototype.raycastInv=function(e,t,r,i,a,s,o){void 0===o&&(o=1/0);var c=this.data;if(i===1/0&&a===1/0&&s===1/0)return u(1/0,void 0);if(n.boxRayIntersects(c,e,t,r,i,a,s)===1/0)return u(1/0,void 0);for(var p,A=[u(0,c)],d=function(e,t){var n=A[e];A[e]=A[t],A[t]=n},v=function(){var e=A[0],t=A.length-1;A[0]=A[t],A.length=t;for(var n=0;;){var r=n<<1|1;if(r>=t)break;var i=r+1;if(i<t&&A[i].dist<A[r].dist&&(r=i),A[n].dist<A[r].dist)break;d(n,r),n=r}return function(e){l.push(e)}(e),e.node},h=function(e,t){var n=A.length;for(A.push(u(e,t));n>0;){var r=n-1>>1;if(A[r].dist<=A[n].dist)break;d(n,r),n=r}},I=o;A.length&&A[0].dist<I;)for(var y=0,m=(c=v()).children.length;y<m;y++){var w=c.children[y],g=n.boxRayIntersects(w,e,t,r,i,a,s);if(f(c)){if(g<I){if(0===g)return u(g,w);I=g,p=w}}else h(g,w)}return u(I<o?I:1/0,p)},e.prototype.raycast=function(e,t,n,r,i,a,s){return void 0===s&&(s=1/0),this.raycastInv(e,t,n,1/r,1/i,1/a,s)},e.prototype.all=function(){return this._all(this.data,[])},e.prototype.load=function(e){if(!e||!e.length)return this;if(e.length<this.minEntries){for(var t=0,n=e.length;t<n;t++)this.insert(e[t]);return this}var r=this.build(e.slice(),0,e.length-1,0);if(this.data.children.length)if(this.data.height===r.height)this.splitRoot(this.data,r);else{if(this.data.height<r.height){var i=this.data;this.data=r,r=i}this._insert(r,this.data.height-r.height-1,!0)}else this.data=r;return this},e.prototype.insert=function(e){return e&&this._insert(e,this.data.height-1),this},e.prototype.clear=function(){return this.data&&s(this.data),this.data=o([]),this},e.prototype.remove=function(e,t){if(!e)return this;for(var n,r,i=this.data,a=0,s=!1,o=[],l=[];i||o.length;){if(i||(i=o.pop(),a=l.pop(),r=o[o.length-1],s=!0),c(i)&&-1!==(n=p(e,i.children,t)))return i.children.splice(n,1),o.push(i),this.condense(o),this;s||c(i)||!w(i,e)?r?(a++,i=r.children[a],s=!1):i=void 0:(o.push(i),l.push(a),a=0,r=i,i=i.children[0])}return this},e.prototype.toJSON=function(){return this.data},e.prototype.fromJSON=function(e){return s(this.data),this.data=e,this},e.prototype.build=function(e,t,n,r){var i,a=n-t+1,s=this.maxEntries;if(a<=s)return i=o(e.slice(t,n+1)),A(i),i;r||(r=Math.ceil(Math.log(a)/Math.log(s)),s=Math.ceil(a/Math.pow(s,r-1))),(i=o([])).leaf=!1,i.height=r;var l=Math.ceil(a/s),u=l*Math.ceil(Math.pow(s,2/3)),c=l*Math.ceil(Math.pow(s,1/3));g(e,t,n,c,T);for(var f=t;f<=n;f+=c){var p=Math.min(f+c-1,n);g(e,f,p,u,E);for(var d=f;d<=p;d+=u){var v=Math.min(d+u-1,p);g(e,d,v,l,b);for(var h=d;h<=v;h+=l){var I=Math.min(h+l-1,v);i.children.push(this.build(e,h,I,r-1))}}}return A(i),i},e.prototype._all=function(e,t){for(var n=[];e;)c(e)?t.push.apply(t,e.children):n.push.apply(n,e.children),e=n.pop();return t},e.prototype.chooseSubtree=function(e,t,n,r){for(var i,a,s;r.push(t),!c(t)&&r.length-1!==n;){i=a=1/0;for(var o=0,l=t.children.length;o<l;o++){var u=t.children[o],f=h(u),p=y(e,u)-f;p<a?(a=p,i=f<i?f:i,s=u):p===a&&f<i&&(i=f,s=u)}t=s||t.children[0]}return t},e.prototype.split=function(e,t){var n=e[t],r=n.children.length,i=this.minEntries;this.chooseSplitAxis(n,i,r);var a=this.chooseSplitIndex(n,i,r),s=o(n.children.splice(a,n.children.length-a));s.height=n.height,s.leaf=n.leaf,A(n),A(s),t?e[t-1].children.push(s):this.splitRoot(n,s)},e.prototype.splitRoot=function(e,t){this.data=o([e,t]),this.data.height=e.height+1,this.data.leaf=!1,A(this.data)},e.prototype.chooseSplitIndex=function(e,t,n){for(var r,i=1/0,a=1/0,s=t;s<=n-t;s++){var o=d(e,0,s),l=d(e,s,n),u=m(o,l),c=h(o)+h(l);u<i?(i=u,r=s,a=c<a?c:a):u===i&&c<a&&(a=c,r=s)}return r},e.prototype.chooseSplitAxis=function(e,t,n){var r=this.allDistMargin(e,t,n,T),i=this.allDistMargin(e,t,n,E),a=this.allDistMargin(e,t,n,b);r<i&&r<a?e.children.sort(T):i<r&&i<a&&e.children.sort(E)},e.prototype.allDistMargin=function(e,t,n,r){e.children.sort(r);for(var i=d(e,0,t),a=d(e,n-t,n),s=I(i)+I(a),o=t;o<n-t;o++){var l=e.children[o];v(i,l),s+=I(i)}for(o=n-t-1;o>=t;o--){l=e.children[o];v(a,l),s+=I(a)}return s},e.prototype.adjustParentBBoxes=function(e,t,n){for(var r=n;r>=0;r--)v(t[r],e)},e.prototype.condense=function(e){for(var t=e.length-1,n=void 0;t>=0;t--)0===e[t].children.length?t>0?((n=e[t-1].children).splice(n.indexOf(e[t]),1),a(e[t])):this.clear():A(e[t])},e.prototype._insert=function(e,t,n){var r=[],i=this.chooseSubtree(e,this.data,t,r);for(i.children.push(e),v(i,e);t>=0&&r[t].children.length>this.maxEntries;)this.split(r,t),t--;this.adjustParentBBoxes(e,r,t)},e.pool=[],e}();n.RBush3D=D},{quickselect:2}],2:[function(e,t,n){!function(e,r){"object"===E(n)&&void 0!==t?t.exports=r():e.quickselect=r()}(this,(function(){function e(n,r,i,a,s){for(;a>i;){if(a-i>600){var o=a-i+1,l=r-i+1,u=Math.log(o),c=.5*Math.exp(2*u/3),f=.5*Math.sqrt(u*c*(o-c)/o)*(l-o/2<0?-1:1);e(n,r,Math.max(i,Math.floor(r-l*c/o+f)),Math.min(a,Math.floor(r+(o-l)*c/o+f)),s)}var p=n[r],A=i,d=a;for(t(n,i,r),s(n[a],p)>0&&t(n,i,a);A<d;){for(t(n,A,d),A++,d--;s(n[A],p)<0;)A++;for(;s(n[d],p)>0;)d--}0===s(n[i],p)?t(n,i,d):t(n,++d,a),d<=r&&(i=d+1),r<=d&&(a=d-1)}}function t(e,t,n){var r=e[t];e[t]=e[n],e[n]=r}function n(e,t){return e<t?-1:e>t?1:0}return function(t,r,i,a,s){e(t,r,i||0,a||t.length-1,s||n)}}))},{}]},{},[1])(1)}));var Qn=Vn.exports.RBush3D,Wn=function(e){function t(e){var t=0;return e.meshes.forEach((function(e){t+=e.numPrimitives})),t}function n(e,t){var n={pos:{x:0,y:0},left:0,right:e,top:0,bottom:t,dir:0};function r(){(0==n.dir&&n.pos.x+1>=n.right||1==n.dir&&n.pos.y+1>=n.bottom||2==n.dir&&n.pos.x-1<=n.left-1||3==n.dir&&n.pos.y-1<=n.top-1)&&(n.dir=(n.dir+1)%4,0==n.dir&&n.left++,1==n.dir&&n.top++,2==n.dir&&n.right--,3==n.dir&&n.bottom--),0==n.dir&&n.pos.x++,1==n.dir&&n.pos.y++,2==n.dir&&n.pos.x--,3==n.dir&&n.pos.y--}for(var i=[],a=e*t;i.length<a;r())i.push(n.pos.x+"_"+n.pos.y);return i}var r,i,a,s,o=0,l=(i=function(t,n){for(var r=n||function(e){return!0},i=(e.aabbTree.data.maxX-e.aabbTree.data.minX)/10,a=(e.aabbTree.data.maxZ-e.aabbTree.data.minZ)/10,s=[],o=e.aabbTree.data.minX,l=0;l<10;l++,o+=i)for(var u=e.aabbTree.data.minZ,c=0;c<10;c++,u+=a)s.push({minX:o,maxX:o+i,minY:-1e8,maxY:1e8,minZ:u,maxZ:u+a,indexX:l,indexZ:c});var f={cellsByEntity:{},entitiesByCell:{},cellsX:10,cellsZ:10};return(s||[]).forEach((function(t){e.aabbTree.search(t).filter((function(e){return r(e.entity)})).forEach((function(e){var n=e.entity.id;f.cellsByEntity[n]=f.cellsByEntity[n]||{cells:[],entity:e.entity},f.cellsByEntity[n].cells.push(t);var r=t.indexX+"_"+t.indexZ;f.entitiesByCell[r]=f.entitiesByCell[r]||{entities:[],cell:t},f.entitiesByCell[r].entities.push(e.entity)}))})),f}((r={cellSideInMeters:.05,entityFilterFunc:function(e){return!0},maxPolygonsPerCluster:9e4,minPercentOfClustredPolygons:.9}).cellSideInMeters,r.entityFilterFunc),a=function(e,n){var r={},i=0;Object.keys(n).forEach((function(e){var a=n[e].cells.length,s=t(n[e].entity);r[a]=(r[a]||0)+s,i+=s}));var a=Object.keys(r);a.sort((function(e,t){return e-t}));for(var s=0,o=0,l=0;l<a.length&&o<e;l++)s=a[l],o+=r[s]/i;return{maxCellsPerEntity:s,polygonStats:{percentClustered:o,numberClustered:Math.round(o*i),numberUnclustered:i-Math.round(o*i)}}}(r.minPercentOfClustredPolygons,i.cellsByEntity),s=function(e,r,i,a,s,o){var l={},u={accumEntities:[]},c=[];n(e,r).forEach((function(e){var n=function(e,t,n,r){return(n[e]||{entities:[]}).entities.filter((function(e){return r[e.id].cells.length<=t}))}(e,i,a,s).filter((function(e){return!(e.id in l)}));n.forEach((function(e){l[e.id]=!0})),n.sort((function(e,n){return t(e)-t(n)}));var r=u.accumEntities.concat(n),f=[],p=o,A=0;do{for(;A<r.length;A++){var d=r[A],v=t(d);v>p&&(c.push(f),f=[],p=o),f.push(d),p-=v}}while(A<r.length);u.accumEntities=f})),u.accumEntities.length&&c.push(u.accumEntities);var f=[];Object.keys(s).forEach((function(e){e in l||f.push(s[e].entity)}));var p=o,A=[];f.forEach((function(e){var n=t(e);n>p&&(c.push(A),A=[],p=o),A.push(e),p-=n})),A.length&&c.push(A);var d={};return c.forEach((function(e,t){e.forEach((function(e){d[e.id]=t}))})),{clusters:c,entityIdToClusterIdMapping:d}}(i.cellsX,i.cellsZ,a.maxCellsPerEntity,i.entitiesByCell,i.cellsByEntity,r.maxPolygonsPerCluster),{clusters:{total:s.clusters.length},clusteringResult:s});o+=l.clusters.total,console.log("Total clusters: "+o);var u=[];return l.clusteringResult.clusters.forEach((function(e){e.forEach((function(e){u.push(e.id)}))})),l.orderedEntityIds=u,l};
|
|
2
2
|
/**
|
|
3
3
|
* @author https://github.com/tmarti, with support from https://tribia.com/
|
|
4
4
|
* @license MIT
|
|
@@ -23,7 +23,7 @@ function zn(e,t){t.length;for(var n=e.length,r=[],i=[],a=function(n){var a=e[n];
|
|
|
23
23
|
/**
|
|
24
24
|
* @author https://github.com/tmarti, with support from https://tribia.com/
|
|
25
25
|
* @license MIT
|
|
26
|
-
**/var ic=null;function ac(e,t){var n,r,i,a,s,o,l=3*e,u=3*t,c=Math.min(n=ic[l],r=ic[l+1],i=ic[l+2]),f=Math.min(a=ic[u],s=ic[u+1],o=ic[u+2]);if(c!==f)return c-f;var p=Math.max(n,r,i),A=Math.max(a,s,o);return p!==A?p-A:0}function sc(e,t){for(var n=new Int32Array(e.length/3),r=0,i=n.length;r<i;r++)n[r]=r;ic=new Int32Array(e.length);for(var a=0,s=e.length;a<s;a++)ic[a]=e[a]>>t;n.sort(ac);for(var o=new Int32Array(e.length),l=0,u=n.length;l<u;l++)o[3*l+0]=e[3*n[l]+0],o[3*l+1]=e[3*n[l]+1],o[3*l+2]=e[3*n[l]+2];return o}var oc=null;function lc(e,t){var n=oc[2*e]-oc[2*t];return 0!==n?n:oc[2*e+1]-oc[2*t+1]}function uc(e){if(0===(e||[]).length)return[];for(var t=new Int32Array(e.length/2),n=0,r=t.length;n<r;n++)t[n]=n;for(var i=0,a=e.length;i<a;i+=2)if(e[i]>e[i+1]){var s=e[i];e[i]=e[i+1],e[i+1]=s}oc=new Int32Array(e),t.sort(lc);for(var o=new Int32Array(e.length),l=0,u=t.length;l<u;l++)o[2*l+0]=e[2*t[l]+0],o[2*l+1]=e[2*t[l]+1];return o}function cc(e,t){var n={},r={};e.forEach((function(e){for(var t=e.indices,i=e.edgeIndices,a=e.positionsCompressed,s=0,o=t.length;s<o;s+=3){var l=a[3*t[s]]+"_"+a[3*t[s]+1]+"_"+a[3*t[s]+2]+"/"+a[3*t[s+1]]+"_"+a[3*t[s+1]+1]+"_"+a[3*t[s+1]+2]+"/"+a[3*t[s+2]]+"_"+a[3*t[s+2]+1]+"_"+a[3*t[s+2]+2];n[l]=!0}e.edgeIndices.length/2;for(var u=0,c=i.length;u<c;u+=2){var f=a[3*i[u]]+"_"+a[3*i[u]+1]+"_"+a[3*i[u]+2]+"/"+a[3*i[u+1]]+"_"+a[3*i[u+1]+1]+"_"+a[3*i[u+1]+2]+"/";r[f]=!0}}));var i=t.indices;t.edgeIndices;for(var a=t.positionsCompressed,s=0,o=i.length;s<o;s+=3){var l=a[3*i[s]]+"_"+a[3*i[s]+1]+"_"+a[3*i[s]+2]+"/"+a[3*i[s+1]]+"_"+a[3*i[s+1]+1]+"_"+a[3*i[s+1]+2]+"/"+a[3*i[s+2]]+"_"+a[3*i[s+2]+1]+"_"+a[3*i[s+2]+2];if(!(l in n))throw console.log("Not found "+l),"Ohhhh!"}}var fc=Z.vec4(),pc=Z.vec3(),Ac=function(){function e(t,n){b(this,e),this._scene=t,this._withSAO=n,this._hash=this._getHash(),this._allocate()}return P(e,[{key:"getValid",value:function(){return this._hash===this._getHash()}},{key:"_getHash",value:function(){var e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}},{key:"drawLayer",value:function(e,t,n){var r=this._scene,i=r.camera,a=t.model,s=r.canvas.gl,o=t._state,l=o.textureState,u=t._state.origin;if(this._program||(this._allocate(),!this.errors)){e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e,o)),l.bindCommonTextures(this._program,this._uTexturePerObjectIdPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this._uTexturePerObjectIdColorsAndFlags,this._uTextureCameraMatrices,this._uTextureModelMatrices,this._uTexturePerObjectIdOffsets);var c=i.eye;e.pickViewMatrix&&(l.bindPickCameraTexture(this._program,this._uTextureCameraMatrices),c=e.pickOrigin||c);var f=Z.vec3([c[0]-u[0],c[1]-u[1],c[2]-u[2]]);s.uniform3fv(this._uCameraEyeRtc,f),s.uniform1i(this._uRenderPass,n);var p=r._sectionPlanesState.sectionPlanes.length;if(p>0)for(var A=r._sectionPlanesState.sectionPlanes,d=t.layerIndex*p,v=a.renderFlags,h=0;h<p;h++){var I=this._uSectionPlanes[h];if(I){var y=v.sectionPlanesActivePerLayer[d+h];if(s.uniform1i(I.active,y?1:0),y){var m=A[h];if(u){var w=ge(m.dist,m.dir,u,pc);s.uniform3fv(I.pos,w)}else s.uniform3fv(I.pos,m.pos);s.uniform3fv(I.dir,m.dir)}}}o.numIndices8Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),s.drawArrays(s.TRIANGLES,0,o.numIndices8Bits)),o.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),s.drawArrays(s.TRIANGLES,0,o.numIndices16Bits)),o.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),s.drawArrays(s.TRIANGLES,0,o.numIndices32Bits)),e.drawElements++}}},{key:"_allocate",value:function(){var e=this._scene,t=e.canvas.gl,n=e._lightsState;if(this._program=new ft(t,this._buildShader()),this._program.errors)this.errors=this._program.errors;else{var r=this._program;this._uRenderPass=r.getLocation("renderPass"),this._uLightAmbient=r.getLocation("lightAmbient"),this._uLightColor=[],this._uLightDir=[],this._uLightPos=[],this._uLightAttenuation=[];for(var i=n.lights,a=0,s=i.length;a<s;a++)switch(i[a].type){case"dir":this._uLightColor[a]=r.getLocation("lightColor"+a),this._uLightPos[a]=null,this._uLightDir[a]=r.getLocation("lightDir"+a);break;case"point":this._uLightColor[a]=r.getLocation("lightColor"+a),this._uLightPos[a]=r.getLocation("lightPos"+a),this._uLightDir[a]=null,this._uLightAttenuation[a]=r.getLocation("lightAttenuation"+a);break;case"spot":this._uLightColor[a]=r.getLocation("lightColor"+a),this._uLightPos[a]=r.getLocation("lightPos"+a),this._uLightDir[a]=r.getLocation("lightDir"+a),this._uLightAttenuation[a]=r.getLocation("lightAttenuation"+a)}this._uSectionPlanes=[];for(var o=0,l=e._sectionPlanesState.sectionPlanes.length;o<l;o++)this._uSectionPlanes.push({active:r.getLocation("sectionPlaneActive"+o),pos:r.getLocation("sectionPlanePos"+o),dir:r.getLocation("sectionPlaneDir"+o)});this._withSAO&&(this._uOcclusionTexture="uOcclusionTexture",this._uSAOParams=r.getLocation("uSAOParams")),e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=r.getLocation("logDepthBufFC")),this._uTexturePerObjectIdPositionsDecodeMatrix="uTexturePerObjectIdPositionsDecodeMatrix",this._uTexturePerObjectIdColorsAndFlags="uTexturePerObjectIdColorsAndFlags",this._uTexturePerVertexIdCoordinates="uTexturePerVertexIdCoordinates",this._uTexturePerPolygonIdNormals="uTexturePerPolygonIdNormals",this._uTexturePerPolygonIdIndices="uTexturePerPolygonIdIndices",this._uTexturePerPolygonIdPortionIds="uTexturePerPolygonIdPortionIds",this._uTextureCameraMatrices="uTextureCameraMatrices",this._uTextureModelMatrices="uTextureModelMatrices",this._uTexturePerObjectIdOffsets="uTexturePerObjectIdOffsets",this._uCameraEyeRtc=r.getLocation("uCameraEyeRtc")}}},{key:"_bindProgram",value:function(e){var t=this._scene,n=t.canvas.gl,r=this._program,i=t._lightsState.lights,a=t.camera.project;r.bind(),this._uLightAmbient&&n.uniform4fv(this._uLightAmbient,t._lightsState.getAmbientColorAndIntensity());for(var s=0,o=i.length;s<o;s++){var l=i[s];this._uLightColor[s]&&n.uniform4f(this._uLightColor[s],l.color[0],l.color[1],l.color[2],l.intensity),this._uLightPos[s]&&(n.uniform3fv(this._uLightPos[s],l.pos),this._uLightAttenuation[s]&&n.uniform1f(this._uLightAttenuation[s],l.attenuation)),this._uLightDir[s]&&n.uniform3fv(this._uLightDir[s],l.dir)}if(this._withSAO){var u=t.sao;if(u.possible){var c=n.drawingBufferWidth,f=n.drawingBufferHeight;fc[0]=c,fc[1]=f,fc[2]=u.blendCutoff,fc[3]=u.blendFactor,n.uniform4fv(this._uSAOParams,fc),this._program.bindTexture(this._uOcclusionTexture,e.occlusionTexture,10)}}if(t.logarithmicDepthBufferEnabled){var p=2/(Math.log(a.far+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,p)}}},{key:"_buildShader",value:function(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}},{key:"_buildVertexShader",value:function(){var e,t=this._scene,n=t._sectionPlanesState,r=t._lightsState,i=n.sectionPlanes.length>0,a=[];a.push("#version 300 es"),a.push("// Triangles dataTexture draw vertex shader"),a.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),a.push("precision highp float;"),a.push("precision highp int;"),a.push("precision highp usampler2D;"),a.push("precision highp isampler2D;"),a.push("precision highp sampler2D;"),a.push("#else"),a.push("precision mediump float;"),a.push("precision mediump int;"),a.push("precision mediump usampler2D;"),a.push("precision mediump isampler2D;"),a.push("precision mediump sampler2D;"),a.push("#endif"),a.push("uniform int renderPass;"),t.entityOffsetsEnabled&&a.push("in vec3 offset;"),a.push("uniform highp sampler2D uTexturePerObjectIdPositionsDecodeMatrix;"),a.push("uniform lowp usampler2D uTexturePerObjectIdColorsAndFlags;"),a.push("uniform highp sampler2D uTexturePerObjectIdOffsets;"),a.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),a.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),a.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),a.push("uniform highp sampler2D uTextureCameraMatrices;"),a.push("uniform highp sampler2D uTextureModelMatrices;"),a.push("uniform vec3 uCameraEyeRtc;"),a.push("vec3 positions[3];"),t.logarithmicDepthBufferEnabled&&(a.push("uniform float logDepthBufFC;"),a.push("out float vFragDepth;"),a.push("out float isPerspective;")),a.push("bool isPerspectiveMatrix(mat4 m) {"),a.push(" return (m[2][3] == - 1.0);"),a.push("}"),a.push("uniform vec4 lightAmbient;");for(var s=0,o=r.lights.length;s<o;s++)"ambient"!==(e=r.lights[s]).type&&(a.push("uniform vec4 lightColor"+s+";"),"dir"===e.type&&a.push("uniform vec3 lightDir"+s+";"),"point"===e.type&&a.push("uniform vec3 lightPos"+s+";"),"spot"===e.type&&(a.push("uniform vec3 lightPos"+s+";"),a.push("uniform vec3 lightDir"+s+";")));i&&(a.push("out vec4 vWorldPosition;"),a.push("flat out uint vFlags2;")),a.push("out vec4 vColor;"),a.push("void main(void) {"),a.push("int polygonIndex = gl_VertexID / 3;"),a.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),a.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),a.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),a.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),a.push("uvec4 flags = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),a.push("uvec4 flags2 = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),a.push("if (int(flags.x) != renderPass) {"),a.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),a.push(" return;"),a.push("} else {"),a.push("mat4 viewMatrix = mat4 (texelFetch (uTextureCameraMatrices, ivec2(0, 0), 0), texelFetch (uTextureCameraMatrices, ivec2(1, 0), 0), texelFetch (uTextureCameraMatrices, ivec2(2, 0), 0), texelFetch (uTextureCameraMatrices, ivec2(3, 0), 0));"),a.push("mat4 viewNormalMatrix = mat4 (texelFetch (uTextureCameraMatrices, ivec2(0, 1), 0), texelFetch (uTextureCameraMatrices, ivec2(1, 1), 0), texelFetch (uTextureCameraMatrices, ivec2(2, 1), 0), texelFetch (uTextureCameraMatrices, ivec2(3, 1), 0));"),a.push("mat4 projMatrix = mat4 (texelFetch (uTextureCameraMatrices, ivec2(0, 2), 0), texelFetch (uTextureCameraMatrices, ivec2(1, 2), 0), texelFetch (uTextureCameraMatrices, ivec2(2, 2), 0), texelFetch (uTextureCameraMatrices, ivec2(3, 2), 0));"),a.push("mat4 worldMatrix = mat4 (texelFetch (uTextureModelMatrices, ivec2(0, 0), 0), texelFetch (uTextureModelMatrices, ivec2(1, 0), 0), texelFetch (uTextureModelMatrices, ivec2(2, 0), 0), texelFetch (uTextureModelMatrices, ivec2(3, 0), 0));"),a.push("mat4 worldNormalMatrix = mat4 (texelFetch (uTextureModelMatrices, ivec2(0, 1), 0), texelFetch (uTextureModelMatrices, ivec2(1, 1), 0), texelFetch (uTextureModelMatrices, ivec2(2, 1), 0), texelFetch (uTextureModelMatrices, ivec2(3, 1), 0));"),a.push("ivec4 packedVertexBase = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),a.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),a.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),a.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),a.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),a.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),a.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),a.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),a.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),a.push("mat4 positionsDecodeMatrix = mat4 (texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),a.push("uint solid = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),a.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),a.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),a.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),a.push("uvec4 color = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),a.push("if (color.a == 0u) {"),a.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),a.push(" return;"),a.push("};"),a.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),a.push("vec3 position;"),a.push("position = positions[gl_VertexID % 3];"),a.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*positionsDecodeMatrix)) * vec4(normal,1)).xyz);"),a.push("if (solid != 1u) {"),a.push("if (isPerspectiveMatrix(projMatrix)) {"),a.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(worldMatrix * positionsDecodeMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),a.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),a.push("position = positions[2 - (gl_VertexID % 3)];"),a.push("viewNormal = -viewNormal;"),a.push("}"),a.push("} else {"),a.push("if (viewNormal.z < 0.0) {"),a.push("position = positions[2 - (gl_VertexID % 3)];"),a.push("viewNormal = -viewNormal;"),a.push("}"),a.push("}"),a.push("}"),a.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),a.push("vec4 offset = vec4(texelFetch (uTexturePerObjectIdOffsets, objectIndexCoords, 0).rgb, 0.0);"),a.push("worldPosition.xyz = worldPosition.xyz + offset.xyz;"),a.push("vec4 viewPosition = viewMatrix * worldPosition; "),a.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),a.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),a.push("float lambertian = 1.0;");for(var l=0,u=r.lights.length;l<u;l++)if("ambient"!==(e=r.lights[l]).type){if("dir"===e.type)"view"===e.space?a.push("viewLightDir = normalize(lightDir"+l+");"):a.push("viewLightDir = normalize((viewMatrix * vec4(lightDir"+l+", 0.0)).xyz);");else if("point"===e.type)"view"===e.space?a.push("viewLightDir = -normalize(lightPos"+l+" - viewPosition.xyz);"):a.push("viewLightDir = -normalize((viewMatrix * vec4(lightPos"+l+", 0.0)).xyz);");else{if("spot"!==e.type)continue;"view"===e.space?a.push("viewLightDir = normalize(lightDir"+l+");"):a.push("viewLightDir = normalize((viewMatrix * vec4(lightDir"+l+", 0.0)).xyz);")}a.push("lambertian = max(dot(-viewNormal, viewLightDir), 0.0);"),a.push("reflectedColor += lambertian * (lightColor"+l+".rgb * lightColor"+l+".a);")}return a.push("vec3 rgb = vec3(color.rgb) / 255.0;"),a.push("vColor = vec4((lightAmbient.rgb * lightAmbient.a * rgb) + (reflectedColor * rgb), float(color.a) / 255.0);"),a.push("vec4 clipPos = projMatrix * viewPosition;"),t.logarithmicDepthBufferEnabled&&(a.push("vFragDepth = 1.0 + clipPos.w;"),a.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i&&(a.push("vWorldPosition = worldPosition;"),a.push("vFlags2 = flags2.r;")),a.push("gl_Position = clipPos;"),a.push("}"),a.push("}"),a}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,n=t.sectionPlanes.length>0,r=[];if(r.push("#version 300 es"),r.push("// Triangles dataTexture draw fragment shader"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),e.logarithmicDepthBufferEnabled&&(r.push("in float isPerspective;"),r.push("uniform float logDepthBufFC;"),r.push("in float vFragDepth;")),this._withSAO&&(r.push("uniform sampler2D uOcclusionTexture;"),r.push("uniform vec4 uSAOParams;"),r.push("const float packUpscale = 256. / 255.;"),r.push("const float unpackDownScale = 255. / 256.;"),r.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),r.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),r.push("float unpackRGBToFloat( const in vec4 v ) {"),r.push(" return dot( v, unPackFactors );"),r.push("}")),n){r.push("in vec4 vWorldPosition;"),r.push("flat in uint vFlags2;");for(var i=0,a=t.sectionPlanes.length;i<a;i++)r.push("uniform bool sectionPlaneActive"+i+";"),r.push("uniform vec3 sectionPlanePos"+i+";"),r.push("uniform vec3 sectionPlaneDir"+i+";")}if(r.push("in vec4 vColor;"),r.push("out vec4 outColor;"),r.push("void main(void) {"),n){r.push(" bool clippable = vFlags2 > 0u;"),r.push(" if (clippable) {"),r.push(" float dist = 0.0;");for(var s=0,o=t.sectionPlanes.length;s<o;s++)r.push("if (sectionPlaneActive"+s+") {"),r.push(" dist += clamp(dot(-sectionPlaneDir"+s+".xyz, vWorldPosition.xyz - sectionPlanePos"+s+".xyz), 0.0, 1000.0);"),r.push("}");r.push(" if (dist > 0.0) { "),r.push(" discard;"),r.push(" }"),r.push("}")}return e.logarithmicDepthBufferEnabled&&r.push(" gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),this._withSAO?(r.push(" float viewportWidth = uSAOParams[0];"),r.push(" float viewportHeight = uSAOParams[1];"),r.push(" float blendCutoff = uSAOParams[2];"),r.push(" float blendFactor = uSAOParams[3];"),r.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),r.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBToFloat(texture(uOcclusionTexture, uv))) * blendFactor;"),r.push(" outColor = vec4(vColor.rgb * ambient, 1.0);")):r.push(" outColor = vColor;"),r.push("}"),r}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),e}(),dc=new Float32Array([1,1,1]);Z.vec4();var vc=Z.vec3(),hc=function(){function e(t,n){b(this,e),this._scene=t,this._hash=this._getHash(),this._allocate()}return P(e,[{key:"getValid",value:function(){return this._hash===this._getHash()}},{key:"_getHash",value:function(){return this._scene._sectionPlanesState.getHash()}},{key:"drawLayer",value:function(e,t,n){var r=this._scene,i=r.camera,a=t.model,s=r.canvas.gl,o=t._state,l=o.textureState,u=t._state.origin;if(this._program||(this._allocate(),!this.errors)){e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e,o)),l.bindCommonTextures(this._program,this._uTexturePerObjectIdPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this._uTexturePerObjectIdColorsAndFlags,this._uTextureCameraMatrices,this._uTextureModelMatrices,this._uTexturePerObjectIdOffsets);var c=i.eye;e.pickViewMatrix&&(l.bindPickCameraTexture(this._program,this._uTextureCameraMatrices),c=e.pickOrigin||c);var f=[c[0]-u[0],c[1]-u[1],c[2]-u[2]];if(s.uniform3fv(this._uCameraEyeRtc,f),s.uniform1i(this._uRenderPass,n),n===eo.SILHOUETTE_XRAYED){var p=r.xrayMaterial._state,A=p.fillColor,d=p.fillAlpha;s.uniform4f(this._uColor,A[0],A[1],A[2],d)}else if(n===eo.SILHOUETTE_HIGHLIGHTED){var v=r.highlightMaterial._state,h=v.fillColor,I=v.fillAlpha;s.uniform4f(this._uColor,h[0],h[1],h[2],I)}else if(n===eo.SILHOUETTE_SELECTED){var y=r.selectedMaterial._state,m=y.fillColor,w=y.fillAlpha;s.uniform4f(this._uColor,m[0],m[1],m[2],w)}else s.uniform4fv(this._uColor,dc);var g=r._sectionPlanesState.sectionPlanes.length;if(g>0)for(var T=r._sectionPlanesState.sectionPlanes,E=t.layerIndex*g,b=a.renderFlags,D=0;D<g;D++){var P=this._uSectionPlanes[D];if(P){var R=b.sectionPlanesActivePerLayer[E+D];if(s.uniform1i(P.active,R?1:0),R){var C=T[D];if(u){var _=ge(C.dist,C.dir,u,vc);s.uniform3fv(P.pos,_)}else s.uniform3fv(P.pos,C.pos);s.uniform3fv(P.dir,C.dir)}}}o.numIndices8Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),s.drawArrays(s.TRIANGLES,0,o.numIndices8Bits)),o.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),s.drawArrays(s.TRIANGLES,0,o.numIndices16Bits)),o.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),s.drawArrays(s.TRIANGLES,0,o.numIndices32Bits)),e.drawElements++}}},{key:"_allocate",value:function(){var e=this._scene,t=e.canvas.gl;if(this._program=new ft(t,this._buildShader()),this._program.errors)this.errors=this._program.errors;else{var n=this._program;this._uRenderPass=n.getLocation("renderPass"),this._uColor=n.getLocation("color"),this._uSectionPlanes=[];for(var r=0,i=e._sectionPlanesState.sectionPlanes.length;r<i;r++)this._uSectionPlanes.push({active:n.getLocation("sectionPlaneActive"+r),pos:n.getLocation("sectionPlanePos"+r),dir:n.getLocation("sectionPlaneDir"+r)});e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=n.getLocation("logDepthBufFC")),this._uTexturePerObjectIdPositionsDecodeMatrix="uTexturePerObjectIdPositionsDecodeMatrix",this._uTexturePerObjectIdColorsAndFlags="uTexturePerObjectIdColorsAndFlags",this._uTexturePerVertexIdCoordinates="uTexturePerVertexIdCoordinates",this._uTexturePerPolygonIdNormals="uTexturePerPolygonIdNormals",this._uTexturePerPolygonIdIndices="uTexturePerPolygonIdIndices",this._uTexturePerPolygonIdPortionIds="uTexturePerPolygonIdPortionIds",this._uTextureCameraMatrices="uTextureCameraMatrices",this._uTextureModelMatrices="uTextureModelMatrices",this._uTexturePerObjectIdOffsets="uTexturePerObjectIdOffsets",this._uCameraEyeRtc=n.getLocation("uCameraEyeRtc")}}},{key:"_bindProgram",value:function(e){var t=this._scene,n=t.canvas.gl,r=t.camera.project;if(this._program.bind(),t.logarithmicDepthBufferEnabled){var i=2/(Math.log(r.far+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,i)}}},{key:"_buildShader",value:function(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,n=[];return n.push("#version 300 es"),n.push("// Triangles dataTexture silhouette vertex shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("precision highp usampler2D;"),n.push("precision highp isampler2D;"),n.push("precision highp sampler2D;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("precision mediump usampler2D;"),n.push("precision mediump isampler2D;"),n.push("precision mediump sampler2D;"),n.push("#endif"),n.push("uniform int renderPass;"),e.entityOffsetsEnabled&&n.push("in vec3 offset;"),n.push("uniform highp sampler2D uTexturePerObjectIdPositionsDecodeMatrix;"),n.push("uniform lowp usampler2D uTexturePerObjectIdColorsAndFlags;"),n.push("uniform highp sampler2D uTexturePerObjectIdOffsets;"),n.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),n.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),n.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),n.push("uniform highp sampler2D uTextureCameraMatrices;"),n.push("uniform highp sampler2D uTextureModelMatrices;"),n.push("uniform vec3 uCameraEyeRtc;"),n.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("out float vFragDepth;"),n.push("out float isPerspective;")),n.push("bool isPerspectiveMatrix(mat4 m) {"),n.push(" return (m[2][3] == - 1.0);"),n.push("}"),t&&(n.push("out vec4 vWorldPosition;"),n.push("flat out uint vFlags2;")),n.push("void main(void) {"),n.push("mat4 viewMatrix = mat4 (texelFetch (uTextureCameraMatrices, ivec2(0, 0), 0), texelFetch (uTextureCameraMatrices, ivec2(1, 0), 0), texelFetch (uTextureCameraMatrices, ivec2(2, 0), 0), texelFetch (uTextureCameraMatrices, ivec2(3, 0), 0));"),n.push("mat4 viewNormalMatrix = mat4 (texelFetch (uTextureCameraMatrices, ivec2(0, 1), 0), texelFetch (uTextureCameraMatrices, ivec2(1, 1), 0), texelFetch (uTextureCameraMatrices, ivec2(2, 1), 0), texelFetch (uTextureCameraMatrices, ivec2(3, 1), 0));"),n.push("mat4 projMatrix = mat4 (texelFetch (uTextureCameraMatrices, ivec2(0, 2), 0), texelFetch (uTextureCameraMatrices, ivec2(1, 2), 0), texelFetch (uTextureCameraMatrices, ivec2(2, 2), 0), texelFetch (uTextureCameraMatrices, ivec2(3, 2), 0));"),n.push("mat4 worldMatrix = mat4 (texelFetch (uTextureModelMatrices, ivec2(0, 0), 0), texelFetch (uTextureModelMatrices, ivec2(1, 0), 0), texelFetch (uTextureModelMatrices, ivec2(2, 0), 0), texelFetch (uTextureModelMatrices, ivec2(3, 0), 0));"),n.push("mat4 worldNormalMatrix = mat4 (texelFetch (uTextureModelMatrices, ivec2(0, 1), 0), texelFetch (uTextureModelMatrices, ivec2(1, 1), 0), texelFetch (uTextureModelMatrices, ivec2(2, 1), 0), texelFetch (uTextureModelMatrices, ivec2(3, 1), 0));"),n.push("int polygonIndex = gl_VertexID / 3;"),n.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),n.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),n.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),n.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),n.push("uvec4 flags = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),n.push("uvec4 flags2 = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),n.push("if (int(flags.y) != renderPass) {"),n.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),n.push(" return;"),n.push("} else {"),n.push("ivec4 packedVertexBase = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),n.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),n.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),n.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),n.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),n.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),n.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),n.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),n.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),n.push("mat4 positionsDecodeMatrix = mat4 (texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),n.push("uint solid = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),n.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),n.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),n.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),n.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),n.push("vec3 position;"),n.push("position = positions[gl_VertexID % 3];"),n.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*positionsDecodeMatrix)) * vec4(normal,1)).xyz);"),n.push("if (solid != 1u) {"),n.push("if (isPerspectiveMatrix(projMatrix)) {"),n.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(worldMatrix * positionsDecodeMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),n.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),n.push("position = positions[2 - (gl_VertexID % 3)];"),n.push("viewNormal = -viewNormal;"),n.push("}"),n.push("} else {"),n.push("if (viewNormal.z < 0.0) {"),n.push("position = positions[2 - (gl_VertexID % 3)];"),n.push("viewNormal = -viewNormal;"),n.push("}"),n.push("}"),n.push("}"),n.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),n.push("vec4 offset = vec4(texelFetch (uTexturePerObjectIdOffsets, objectIndexCoords, 0).rgb, 0.0);"),n.push("worldPosition.xyz = worldPosition.xyz + offset.xyz;"),n.push("vec4 viewPosition = viewMatrix * worldPosition; "),n.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(n.push("vFragDepth = 1.0 + clipPos.w;"),n.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(n.push("vWorldPosition = worldPosition;"),n.push("vFlags2 = flags2.r;")),n.push("gl_Position = clipPos;"),n.push("}"),n.push("}"),n}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,n=t.sectionPlanes.length>0,r=[];if(r.push("#version 300 es"),r.push("// Triangles dataTexture draw fragment shader"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),e.logarithmicDepthBufferEnabled&&(r.push("in float isPerspective;"),r.push("uniform float logDepthBufFC;"),r.push("varying float vFragDepth;")),n){r.push("in vec4 vWorldPosition;"),r.push("flat in uint vFlags2;");for(var i=0,a=t.sectionPlanes.length;i<a;i++)r.push("uniform bool sectionPlaneActive"+i+";"),r.push("uniform vec3 sectionPlanePos"+i+";"),r.push("uniform vec3 sectionPlaneDir"+i+";")}if(r.push("uniform vec4 color;"),r.push("out vec4 outColor;"),r.push("void main(void) {"),n){r.push(" bool clippable = vFlags2 > 0u;"),r.push(" if (clippable) {"),r.push(" float dist = 0.0;");for(var s=0,o=t.sectionPlanes.length;s<o;s++)r.push("if (sectionPlaneActive"+s+") {"),r.push(" dist += clamp(dot(-sectionPlaneDir"+s+".xyz, vWorldPosition.xyz - sectionPlanePos"+s+".xyz), 0.0, 1000.0);"),r.push("}");r.push(" if (dist > 0.0) { "),r.push(" discard;"),r.push(" }"),r.push("}")}return e.logarithmicDepthBufferEnabled&&r.push(" gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),r.push(" outColor = color;"),r.push("}"),r}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),e}(),Ic=Z.vec3(),yc=new Float32Array([0,0,0,1]),mc=function(){function e(t){b(this,e),this._scene=t,this._hash=this._getHash(),this._allocate()}return P(e,[{key:"getValid",value:function(){return this._hash===this._getHash()}},{key:"_getHash",value:function(){return this._scene._sectionPlanesState.getHash()}},{key:"drawLayer",value:function(e,t,n){var r=t.model,i=r.scene,a=i.camera,s=i.canvas.gl,o=t._state,l=o.textureState,u=t._state.origin;if(this._program||(this._allocate(t),!this.errors)){if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram()),l.bindCommonTextures(this._program,this._uTexturePerObjectIdPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this._uTexturePerObjectIdColorsAndFlags,this._uTextureCameraMatrices,this._uTextureModelMatrices,this._uTexturePerObjectIdOffsets),e.pickViewMatrix&&l.bindPickCameraTexture(this._program,this._uTextureCameraMatrices),s.uniform1i(this._uRenderPass,n),n===eo.EDGES_XRAYED){var c=i.xrayMaterial._state,f=c.edgeColor,p=c.edgeAlpha;s.uniform4f(this._uColor,f[0],f[1],f[2],p)}else if(n===eo.EDGES_HIGHLIGHTED){var A=i.highlightMaterial._state,d=A.edgeColor,v=A.edgeAlpha;s.uniform4f(this._uColor,d[0],d[1],d[2],v)}else if(n===eo.EDGES_SELECTED){var h=i.selectedMaterial._state,I=h.edgeColor,y=h.edgeAlpha;s.uniform4f(this._uColor,I[0],I[1],I[2],y)}else s.uniform4fv(this._uColor,yc);s.uniformMatrix4fv(this._uViewMatrix,!1,u?Ie(a.viewMatrix,u):a.viewMatrix),s.uniformMatrix4fv(this._uWorldMatrix,!1,r.worldMatrix);var m=i._sectionPlanesState.sectionPlanes.length;if(m>0)for(var w=i._sectionPlanesState.sectionPlanes,g=t.layerIndex*m,T=r.renderFlags,E=0;E<m;E++){var b=this._uSectionPlanes[E];if(b){var D=T.sectionPlanesActivePerLayer[g+E];if(s.uniform1i(b.active,D?1:0),D){var P=w[E];if(u){var R=ge(P.dist,P.dir,u,Ic);s.uniform3fv(b.pos,R)}else s.uniform3fv(b.pos,P.pos);s.uniform3fv(b.dir,P.dir)}}}o.numEdgeIndices8Bits>0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,8),s.drawArrays(s.LINES,0,o.numEdgeIndices8Bits)),o.numEdgeIndices16Bits>0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,16),s.drawArrays(s.LINES,0,o.numEdgeIndices16Bits)),o.numEdgeIndices32Bits>0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,32),s.drawArrays(s.LINES,0,o.numEdgeIndices32Bits)),e.drawElements++}}},{key:"_allocate",value:function(){var e=this._scene,t=e.canvas.gl;if(this._program=new ft(t,this._buildShader()),this._program.errors)this.errors=this._program.errors;else{var n=this._program;this._uRenderPass=n.getLocation("renderPass"),this._uColor=n.getLocation("color"),this._uSectionPlanes=[];for(var r=0,i=e._sectionPlanesState.sectionPlanes.length;r<i;r++)this._uSectionPlanes.push({active:n.getLocation("sectionPlaneActive"+r),pos:n.getLocation("sectionPlanePos"+r),dir:n.getLocation("sectionPlaneDir"+r)});e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=n.getLocation("logDepthBufFC")),this._uTexturePerObjectIdPositionsDecodeMatrix="uTexturePerObjectIdPositionsDecodeMatrix",this._uTexturePerObjectIdColorsAndFlags="uTexturePerObjectIdColorsAndFlags",this._uTexturePerVertexIdCoordinates="uTexturePerVertexIdCoordinates",this._uTexturePerPolygonIdEdgeIndices="uTexturePerPolygonIdEdgeIndices",this._uTexturePerEdgeIdPortionIds="uTexturePerEdgeIdPortionIds",this._uTextureCameraMatrices="uTextureCameraMatrices",this._uTextureModelMatrices="uTextureModelMatrices",this._uTexturePerObjectIdOffsets="uTexturePerObjectIdOffsets"}}},{key:"_bindProgram",value:function(){var e=this._scene,t=e.canvas.gl,n=this._program,r=e.camera.project;if(n.bind(),e.logarithmicDepthBufferEnabled){var i=2/(Math.log(r.far+1)/Math.LN2);t.uniform1f(this._uLogDepthBufFC,i)}}},{key:"_buildShader",value:function(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,n=[];return n.push("#version 300 es"),n.push("// Batched geometry edges drawing vertex shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("precision highp usampler2D;"),n.push("precision highp isampler2D;"),n.push("precision highp sampler2D;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("precision mediump usampler2D;"),n.push("precision mediump isampler2D;"),n.push("precision mediump sampler2D;"),n.push("#endif"),n.push("uniform int renderPass;"),e.entityOffsetsEnabled&&n.push("in vec3 offset;"),n.push("uniform highp sampler2D uTexturePerObjectIdPositionsDecodeMatrix;"),n.push("uniform lowp usampler2D uTexturePerObjectIdColorsAndFlags;"),n.push("uniform highp sampler2D uTexturePerObjectIdOffsets;"),n.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),n.push("uniform highp usampler2D uTexturePerPolygonIdEdgeIndices;"),n.push("uniform mediump usampler2D uTexturePerEdgeIdPortionIds;"),n.push("uniform highp sampler2D uTextureCameraMatrices;"),n.push("uniform highp sampler2D uTextureModelMatrices;"),n.push("uniform vec4 color;"),e.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("out float vFragDepth;"),n.push("bool isPerspectiveMatrix(mat4 m) {"),n.push(" return (m[2][3] == - 1.0);"),n.push("}"),n.push("out float isPerspective;")),t&&(n.push("out vec4 vWorldPosition;"),n.push("flat out uint vFlags2;")),n.push("out vec4 vColor;"),n.push("void main(void) {"),n.push("mat4 viewMatrix = mat4 (texelFetch (uTextureCameraMatrices, ivec2(0, 0), 0), texelFetch (uTextureCameraMatrices, ivec2(1, 0), 0), texelFetch (uTextureCameraMatrices, ivec2(2, 0), 0), texelFetch (uTextureCameraMatrices, ivec2(3, 0), 0));"),n.push("mat4 projMatrix = mat4 (texelFetch (uTextureCameraMatrices, ivec2(0, 2), 0), texelFetch (uTextureCameraMatrices, ivec2(1, 2), 0), texelFetch (uTextureCameraMatrices, ivec2(2, 2), 0), texelFetch (uTextureCameraMatrices, ivec2(3, 2), 0));"),n.push("mat4 worldMatrix = mat4 (texelFetch (uTextureModelMatrices, ivec2(0, 0), 0), texelFetch (uTextureModelMatrices, ivec2(1, 0), 0), texelFetch (uTextureModelMatrices, ivec2(2, 0), 0), texelFetch (uTextureModelMatrices, ivec2(3, 0), 0));"),n.push("int edgeIndex = gl_VertexID / 2;"),n.push("int h_packed_object_id_index = (edgeIndex >> 3) & 4095;"),n.push("int v_packed_object_id_index = (edgeIndex >> 3) >> 12;"),n.push("int objectIndex = int(texelFetch(uTexturePerEdgeIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),n.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),n.push("uvec4 flags = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),n.push("uvec4 flags2 = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),n.push("if (int(flags.z) != renderPass) {"),n.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),n.push(" return;"),n.push("} else {"),n.push("ivec4 packedVertexBase = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),n.push("ivec4 packedEdgeIndexBaseOffset = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+6, objectIndexCoords.y), 0));"),n.push("int edgeIndexBaseOffset = (packedEdgeIndexBaseOffset.r << 24) + (packedEdgeIndexBaseOffset.g << 16) + (packedEdgeIndexBaseOffset.b << 8) + packedEdgeIndexBaseOffset.a;"),n.push("int h_index = (edgeIndex - edgeIndexBaseOffset) & 4095;"),n.push("int v_index = (edgeIndex - edgeIndexBaseOffset) >> 12;"),n.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdEdgeIndices, ivec2(h_index, v_index), 0));"),n.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),n.push("int indexPositionH = uniqueVertexIndexes[gl_VertexID % 2] & 4095;"),n.push("int indexPositionV = uniqueVertexIndexes[gl_VertexID % 2] >> 12;"),n.push("mat4 positionsDecodeMatrix = mat4 (texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),n.push("uvec4 flags = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),n.push("uvec4 flags2 = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),n.push("vec3 position = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH, indexPositionV), 0));"),n.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),n.push("vec4 offset = vec4(texelFetch (uTexturePerObjectIdOffsets, objectIndexCoords, 0).rgb, 0.0);"),n.push("worldPosition.xyz = worldPosition.xyz + offset.xyz;"),n.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(n.push(" vWorldPosition = worldPosition;"),n.push(" vFlags2 = flags2.r;")),n.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(n.push("vFragDepth = 1.0 + clipPos.w;"),n.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),n.push("gl_Position = clipPos;"),n.push("vColor = vec4(color.r, color.g, color.b, color.a);"),n.push("}"),n.push("}"),n}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,n=t.sectionPlanes.length>0,r=[];if(r.push("#version 300 es"),r.push("// Batched geometry edges drawing fragment shader"),e.logarithmicDepthBufferEnabled&&r.push("#extension GL_EXT_frag_depth : enable"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),e.logarithmicDepthBufferEnabled&&(r.push("in float isPerspective;"),r.push("uniform float logDepthBufFC;"),r.push("in float vFragDepth;")),n){r.push("in vec4 vWorldPosition;"),r.push("flat in uint vFlags2;");for(var i=0,a=t.sectionPlanes.length;i<a;i++)r.push("uniform bool sectionPlaneActive"+i+";"),r.push("uniform vec3 sectionPlanePos"+i+";"),r.push("uniform vec3 sectionPlaneDir"+i+";")}if(r.push("in vec4 vColor;"),r.push("out vec4 outColor;"),r.push("void main(void) {"),n){r.push(" bool clippable = vFlags2 > 0u;"),r.push(" if (clippable) {"),r.push(" float dist = 0.0;");for(var s=0,o=t.sectionPlanes.length;s<o;s++)r.push("if (sectionPlaneActive"+s+") {"),r.push(" dist += clamp(dot(-sectionPlaneDir"+s+".xyz, vWorldPosition.xyz - sectionPlanePos"+s+".xyz), 0.0, 1000.0);"),r.push("}");r.push(" if (dist > 0.0) { discard; }"),r.push("}")}return e.logarithmicDepthBufferEnabled&&r.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),r.push(" outColor = vColor;"),r.push("}"),r}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),e}(),wc=Z.vec3(),gc=function(){function e(t){b(this,e),this._scene=t,this._hash=this._getHash(),this._allocate()}return P(e,[{key:"getValid",value:function(){return this._hash===this._getHash()}},{key:"_getHash",value:function(){return this._scene._sectionPlanesState.getHash()}},{key:"drawLayer",value:function(e,t,n){var r=t.model,i=r.scene;i.camera;var a=i.canvas.gl,s=t._state,o=s.textureState,l=t._state.origin;if(this._program||(this._allocate(t),!this.errors)){e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram()),o.bindCommonTextures(this._program,this._uTexturePerObjectIdPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this._uTexturePerObjectIdColorsAndFlags,this._uTextureCameraMatrices,this._uTextureModelMatrices,this._uTexturePerObjectIdOffsets),e.pickViewMatrix&&o.bindPickCameraTexture(this._program,this._uTextureCameraMatrices),a.uniform1i(this._uRenderPass,n);var u=i._sectionPlanesState.sectionPlanes.length;if(u>0)for(var c=i._sectionPlanesState.sectionPlanes,f=t.layerIndex*u,p=r.renderFlags,A=0;A<u;A++){var d=this._uSectionPlanes[A];if(d){var v=p.sectionPlanesActivePerLayer[f+A];if(a.uniform1i(d.active,v?1:0),v){var h=c[A];if(l){var I=ge(h.dist,h.dir,l,wc);a.uniform3fv(d.pos,I)}else a.uniform3fv(d.pos,h.pos);a.uniform3fv(d.dir,h.dir)}}}s.numEdgeIndices8Bits>0&&(o.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,8),a.drawArrays(a.LINES,0,s.numEdgeIndices8Bits)),s.numEdgeIndices16Bits>0&&(o.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,16),a.drawArrays(a.LINES,0,s.numEdgeIndices16Bits)),s.numEdgeIndices32Bits>0&&(o.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,32),a.drawArrays(a.LINES,0,s.numEdgeIndices32Bits)),e.drawElements++}}},{key:"_allocate",value:function(){var e=this._scene,t=e.canvas.gl;if(this._program=new ft(t,this._buildShader()),this._program.errors)this.errors=this._program.errors;else{var n=this._program;this._uRenderPass=n.getLocation("renderPass"),this._uSectionPlanes=[];for(var r=0,i=e._sectionPlanesState.sectionPlanes.length;r<i;r++)this._uSectionPlanes.push({active:n.getLocation("sectionPlaneActive"+r),pos:n.getLocation("sectionPlanePos"+r),dir:n.getLocation("sectionPlaneDir"+r)});e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=n.getLocation("logDepthBufFC")),this._uTexturePerObjectIdPositionsDecodeMatrix="uTexturePerObjectIdPositionsDecodeMatrix",this._uTexturePerObjectIdColorsAndFlags="uTexturePerObjectIdColorsAndFlags",this._uTexturePerVertexIdCoordinates="uTexturePerVertexIdCoordinates",this._uTexturePerPolygonIdEdgeIndices="uTexturePerPolygonIdEdgeIndices",this._uTexturePerEdgeIdPortionIds="uTexturePerEdgeIdPortionIds",this._uTextureCameraMatrices="uTextureCameraMatrices",this._uTextureModelMatrices="uTextureModelMatrices",this._uTexturePerObjectIdOffsets="uTexturePerObjectIdOffsets"}}},{key:"_bindProgram",value:function(){var e=this._scene,t=e.canvas.gl,n=this._program,r=e.camera.project;if(n.bind(),e.logarithmicDepthBufferEnabled){var i=2/(Math.log(r.far+1)/Math.LN2);t.uniform1f(this._uLogDepthBufFC,i)}}},{key:"_buildShader",value:function(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,n=[];return n.push("#version 300 es"),n.push("// Batched geometry edges drawing vertex shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("precision highp usampler2D;"),n.push("precision highp isampler2D;"),n.push("precision highp sampler2D;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("precision mediump usampler2D;"),n.push("precision mediump isampler2D;"),n.push("precision mediump sampler2D;"),n.push("#endif"),n.push("uniform int renderPass;"),e.entityOffsetsEnabled&&n.push("in vec3 offset;"),n.push("uniform highp sampler2D uTexturePerObjectIdPositionsDecodeMatrix;"),n.push("uniform lowp usampler2D uTexturePerObjectIdColorsAndFlags;"),n.push("uniform highp sampler2D uTexturePerObjectIdOffsets;"),n.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),n.push("uniform highp usampler2D uTexturePerPolygonIdEdgeIndices;"),n.push("uniform mediump usampler2D uTexturePerEdgeIdPortionIds;"),n.push("uniform highp sampler2D uTextureCameraMatrices;"),n.push("uniform highp sampler2D uTextureModelMatrices;"),e.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("out float vFragDepth;"),n.push("bool isPerspectiveMatrix(mat4 m) {"),n.push(" return (m[2][3] == - 1.0);"),n.push("}"),n.push("out float isPerspective;")),t&&(n.push("out vec4 vWorldPosition;"),n.push("flat out uint vFlags2;")),n.push("out vec4 vColor;"),n.push("void main(void) {"),n.push("mat4 viewMatrix = mat4 (texelFetch (uTextureCameraMatrices, ivec2(0, 0), 0), texelFetch (uTextureCameraMatrices, ivec2(1, 0), 0), texelFetch (uTextureCameraMatrices, ivec2(2, 0), 0), texelFetch (uTextureCameraMatrices, ivec2(3, 0), 0));"),n.push("mat4 projMatrix = mat4 (texelFetch (uTextureCameraMatrices, ivec2(0, 2), 0), texelFetch (uTextureCameraMatrices, ivec2(1, 2), 0), texelFetch (uTextureCameraMatrices, ivec2(2, 2), 0), texelFetch (uTextureCameraMatrices, ivec2(3, 2), 0));"),n.push("mat4 worldMatrix = mat4 (texelFetch (uTextureModelMatrices, ivec2(0, 0), 0), texelFetch (uTextureModelMatrices, ivec2(1, 0), 0), texelFetch (uTextureModelMatrices, ivec2(2, 0), 0), texelFetch (uTextureModelMatrices, ivec2(3, 0), 0));"),n.push("int edgeIndex = gl_VertexID / 2;"),n.push("int h_packed_object_id_index = (edgeIndex >> 3) & 4095;"),n.push("int v_packed_object_id_index = (edgeIndex >> 3) >> 12;"),n.push("int objectIndex = int(texelFetch(uTexturePerEdgeIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),n.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),n.push("uvec4 flags = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),n.push("uvec4 flags2 = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),n.push("if (int(flags.z) != renderPass) {"),n.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),n.push(" return;"),n.push("} else {"),n.push("ivec4 packedVertexBase = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),n.push("ivec4 packedEdgeIndexBaseOffset = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+6, objectIndexCoords.y), 0));"),n.push("int edgeIndexBaseOffset = (packedEdgeIndexBaseOffset.r << 24) + (packedEdgeIndexBaseOffset.g << 16) + (packedEdgeIndexBaseOffset.b << 8) + packedEdgeIndexBaseOffset.a;"),n.push("int h_index = (edgeIndex - edgeIndexBaseOffset) & 4095;"),n.push("int v_index = (edgeIndex - edgeIndexBaseOffset) >> 12;"),n.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdEdgeIndices, ivec2(h_index, v_index), 0));"),n.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),n.push("int indexPositionH = uniqueVertexIndexes[gl_VertexID % 2] & 4095;"),n.push("int indexPositionV = uniqueVertexIndexes[gl_VertexID % 2] >> 12;"),n.push("mat4 positionsDecodeMatrix = mat4 (texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),n.push("uvec4 flags = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),n.push("uvec4 flags2 = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),n.push("vec3 position = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH, indexPositionV), 0));"),n.push("uvec4 color = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),n.push("if (color.a == 0u) {"),n.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),n.push(" return;"),n.push("};"),n.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),n.push("vec4 offset = vec4(texelFetch (uTexturePerObjectIdOffsets, objectIndexCoords, 0).rgb, 0.0);"),n.push("worldPosition.xyz = worldPosition.xyz + offset.xyz;"),n.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(n.push(" vWorldPosition = worldPosition;"),n.push(" vFlags2 = flags2.r;")),n.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(n.push("vFragDepth = 1.0 + clipPos.w;"),n.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),n.push("gl_Position = clipPos;"),n.push("vec4 rgb = vec4(color.rgba);"),n.push("vColor = vec4(float(rgb.r*0.5) / 255.0, float(rgb.g*0.5) / 255.0, float(rgb.b*0.5) / 255.0, float(rgb.a) / 255.0);"),n.push("}"),n.push("}"),n}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,n=t.sectionPlanes.length>0,r=[];if(r.push("#version 300 es"),r.push("// Batched geometry edges drawing fragment shader"),e.logarithmicDepthBufferEnabled&&r.push("#extension GL_EXT_frag_depth : enable"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),e.logarithmicDepthBufferEnabled&&(r.push("in float isPerspective;"),r.push("uniform float logDepthBufFC;"),r.push("in float vFragDepth;")),n){r.push("in vec4 vWorldPosition;"),r.push("flat in uint vFlags2;");for(var i=0,a=t.sectionPlanes.length;i<a;i++)r.push("uniform bool sectionPlaneActive"+i+";"),r.push("uniform vec3 sectionPlanePos"+i+";"),r.push("uniform vec3 sectionPlaneDir"+i+";")}if(r.push("in vec4 vColor;"),r.push("out vec4 outColor;"),r.push("void main(void) {"),n){r.push(" bool clippable = vFlags2 > 0u;"),r.push(" if (clippable) {"),r.push(" float dist = 0.0;");for(var s=0,o=t.sectionPlanes.length;s<o;s++)r.push("if (sectionPlaneActive"+s+") {"),r.push(" dist += clamp(dot(-sectionPlaneDir"+s+".xyz, vWorldPosition.xyz - sectionPlanePos"+s+".xyz), 0.0, 1000.0);"),r.push("}");r.push(" if (dist > 0.0) { discard; }"),r.push("}")}return e.logarithmicDepthBufferEnabled&&r.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),r.push(" outColor = vColor;"),r.push("}"),r}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),e}(),Tc=Z.vec3(),Ec=function(){function e(t){b(this,e),this._scene=t,this._hash=this._getHash(),this._allocate()}return P(e,[{key:"getValid",value:function(){return this._hash===this._getHash()}},{key:"_getHash",value:function(){return this._scene._sectionPlanesState.getHash()}},{key:"drawLayer",value:function(e,t,n){var r=t.model,i=r.scene,a=i.camera,s=i.canvas.gl,o=t._state,l=o.textureState,u=t._state.origin;this._program||this._allocate(t),e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),l.bindCommonTextures(this._program,this._uTexturePerObjectIdPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this._uTexturePerObjectIdColorsAndFlags,this._uTextureCameraMatrices,this._uTextureModelMatrices,this._uTexturePerObjectIdOffsets);var c=a.eye;e.pickViewMatrix&&(l.bindPickCameraTexture(this._program,this._uTextureCameraMatrices),c=e.pickOrigin||c);var f=[c[0]-u[0],c[1]-u[1],c[2]-u[2]];if(s.uniform3fv(this._uCameraEyeRtc,f),s.uniform1i(this._uRenderPass,n),i.logarithmicDepthBufferEnabled){var p=2/(Math.log(a.project.far+1)/Math.LN2);s.uniform1f(this._uLogDepthBufFC,p)}var A=i._sectionPlanesState.sectionPlanes.length;if(A>0)for(var d=i._sectionPlanesState.sectionPlanes,v=t.layerIndex*A,h=r.renderFlags,I=0;I<A;I++){var y=this._uSectionPlanes[I];if(y){var m=h.sectionPlanesActivePerLayer[v+I];if(s.uniform1i(y.active,m?1:0),m){var w=d[I];if(u){var g=ge(w.dist,w.dir,u,Tc);s.uniform3fv(y.pos,g)}else s.uniform3fv(y.pos,w.pos);s.uniform3fv(y.dir,w.dir)}}}o.numIndices8Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),s.drawArrays(s.TRIANGLES,0,o.numIndices8Bits)),o.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),s.drawArrays(s.TRIANGLES,0,o.numIndices16Bits)),o.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),s.drawArrays(s.TRIANGLES,0,o.numIndices32Bits)),e.drawElements++}},{key:"_allocate",value:function(){var e=this._scene,t=e.canvas.gl;if(this._program=new ft(t,this._buildShader()),this._program.errors)this.errors=this._program.errors;else{var n=this._program;this._uRenderPass=n.getLocation("renderPass"),this._uPickInvisible=n.getLocation("pickInvisible"),this._uSectionPlanes=[];for(var r=0,i=e._sectionPlanesState.sectionPlanes.length;r<i;r++)this._uSectionPlanes.push({active:n.getLocation("sectionPlaneActive"+r),pos:n.getLocation("sectionPlanePos"+r),dir:n.getLocation("sectionPlaneDir"+r)});this._withSAO&&(this._uOcclusionTexture="uOcclusionTexture",this._uSAOParams=n.getLocation("uSAOParams")),e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=n.getLocation("logDepthBufFC")),this._uTexturePerObjectIdPositionsDecodeMatrix="uTexturePerObjectIdPositionsDecodeMatrix",this._uTexturePerObjectIdColorsAndFlags="uTexturePerObjectIdColorsAndFlags",this._uTexturePerVertexIdCoordinates="uTexturePerVertexIdCoordinates",this._uTexturePerPolygonIdNormals="uTexturePerPolygonIdNormals",this._uTexturePerPolygonIdIndices="uTexturePerPolygonIdIndices",this._uTexturePerPolygonIdPortionIds="uTexturePerPolygonIdPortionIds",this._uTextureCameraMatrices="uTextureCameraMatrices",this._uTextureModelMatrices="uTextureModelMatrices",this._uTexturePerObjectIdOffsets="uTexturePerObjectIdOffsets",this._uCameraEyeRtc=n.getLocation("uCameraEyeRtc")}}},{key:"_bindProgram",value:function(e){var t=this._scene.canvas.gl;this._program.bind(),t.uniform1i(this._uPickInvisible,e.pickInvisible)}},{key:"_buildShader",value:function(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,n=[];return n.push("#version 300 es"),n.push("// Batched geometry picking vertex shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("precision highp usampler2D;"),n.push("precision highp isampler2D;"),n.push("precision highp sampler2D;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("precision mediump usampler2D;"),n.push("precision mediump isampler2D;"),n.push("precision mediump sampler2D;"),n.push("#endif"),n.push("uniform int renderPass;"),e.entityOffsetsEnabled&&n.push("in vec3 offset;"),n.push("uniform bool pickInvisible;"),n.push("uniform highp sampler2D uTexturePerObjectIdPositionsDecodeMatrix;"),n.push("uniform lowp usampler2D uTexturePerObjectIdColorsAndFlags;"),n.push("uniform highp sampler2D uTexturePerObjectIdOffsets;"),n.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),n.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),n.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),n.push("uniform highp sampler2D uTextureCameraMatrices;"),n.push("uniform highp sampler2D uTextureModelMatrices;"),n.push("uniform vec3 uCameraEyeRtc;"),n.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("out float vFragDepth;"),n.push("out float isPerspective;")),n.push("bool isPerspectiveMatrix(mat4 m) {"),n.push(" return (m[2][3] == - 1.0);"),n.push("}"),t&&(n.push("smooth out vec4 vWorldPosition;"),n.push("flat out uvec4 vFlags2;")),n.push("out vec4 vPickColor;"),n.push("void main(void) {"),n.push("mat4 viewMatrix = mat4 (texelFetch (uTextureCameraMatrices, ivec2(0, 0), 0), texelFetch (uTextureCameraMatrices, ivec2(1, 0), 0), texelFetch (uTextureCameraMatrices, ivec2(2, 0), 0), texelFetch (uTextureCameraMatrices, ivec2(3, 0), 0));"),n.push("mat4 viewNormalMatrix = mat4 (texelFetch (uTextureCameraMatrices, ivec2(0, 1), 0), texelFetch (uTextureCameraMatrices, ivec2(1, 1), 0), texelFetch (uTextureCameraMatrices, ivec2(2, 1), 0), texelFetch (uTextureCameraMatrices, ivec2(3, 1), 0));"),n.push("mat4 projMatrix = mat4 (texelFetch (uTextureCameraMatrices, ivec2(0, 2), 0), texelFetch (uTextureCameraMatrices, ivec2(1, 2), 0), texelFetch (uTextureCameraMatrices, ivec2(2, 2), 0), texelFetch (uTextureCameraMatrices, ivec2(3, 2), 0));"),n.push("mat4 worldMatrix = mat4 (texelFetch (uTextureModelMatrices, ivec2(0, 0), 0), texelFetch (uTextureModelMatrices, ivec2(1, 0), 0), texelFetch (uTextureModelMatrices, ivec2(2, 0), 0), texelFetch (uTextureModelMatrices, ivec2(3, 0), 0));"),n.push("mat4 worldNormalMatrix = mat4 (texelFetch (uTextureModelMatrices, ivec2(0, 1), 0), texelFetch (uTextureModelMatrices, ivec2(1, 1), 0), texelFetch (uTextureModelMatrices, ivec2(2, 1), 0), texelFetch (uTextureModelMatrices, ivec2(3, 1), 0));"),n.push("int polygonIndex = gl_VertexID / 3;"),n.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),n.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),n.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),n.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),n.push("uvec4 flags = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),n.push("uvec4 flags2 = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),n.push("if (int(flags.w) != renderPass) {"),n.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),n.push(" return;"),n.push("} else {"),n.push("ivec4 packedVertexBase = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),n.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),n.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),n.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),n.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),n.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),n.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),n.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),n.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),n.push("mat4 positionsDecodeMatrix = mat4 (texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),n.push("uint solid = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),n.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),n.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),n.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),n.push("uvec4 color = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),n.push("if (color.a == 0u) {"),n.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),n.push(" return;"),n.push("};"),n.push("vPickColor = vec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+1, objectIndexCoords.y), 0)) / 255.0;"),n.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),n.push("vec3 position;"),n.push("position = positions[gl_VertexID % 3];"),n.push("if (solid != 1u) {"),n.push("if (isPerspectiveMatrix(projMatrix)) {"),n.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(worldMatrix * positionsDecodeMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),n.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),n.push("position = positions[2 - (gl_VertexID % 3)];"),n.push("}"),n.push("} else {"),n.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*positionsDecodeMatrix)) * vec4(normal,1)).xyz);"),n.push("if (viewNormal.z < 0.0) {"),n.push("position = positions[2 - (gl_VertexID % 3)];"),n.push("}"),n.push("}"),n.push("}"),n.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),n.push("vec4 offset = vec4(texelFetch (uTexturePerObjectIdOffsets, objectIndexCoords, 0).rgb, 0.0);"),n.push("worldPosition.xyz = worldPosition.xyz + offset.xyz;"),n.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(n.push(" vWorldPosition = worldPosition;"),n.push(" vFlags2 = flags2;")),n.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(n.push("vFragDepth = 1.0 + clipPos.w;"),n.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),n.push("gl_Position = clipPos;"),n.push(" }"),n.push("}"),n}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,n=t.sectionPlanes.length>0,r=[];if(r.push("#version 300 es"),r.push("// Batched geometry picking fragment shader"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),e.logarithmicDepthBufferEnabled&&(r.push("in float isPerspective;"),r.push("uniform float logDepthBufFC;"),r.push("in float vFragDepth;")),n){r.push("in vec4 vWorldPosition;"),r.push("flat in uvec4 vFlags2;");for(var i=0;i<t.sectionPlanes.length;i++)r.push("uniform bool sectionPlaneActive"+i+";"),r.push("uniform vec3 sectionPlanePos"+i+";"),r.push("uniform vec3 sectionPlaneDir"+i+";")}if(r.push("in vec4 vPickColor;"),r.push("out vec4 outPickColor;"),r.push("void main(void) {"),n){r.push(" bool clippable = (float(vFlags2.x) > 0.0);"),r.push(" if (clippable) {"),r.push(" float dist = 0.0;");for(i=0;i<t.sectionPlanes.length;i++)r.push(" if (sectionPlaneActive"+i+") {"),r.push(" dist += clamp(dot(-sectionPlaneDir"+i+".xyz, vWorldPosition.xyz - sectionPlanePos"+i+".xyz), 0.0, 1000.0);"),r.push(" }");r.push(" if (dist > 0.0) { discard; }"),r.push(" }")}return e.logarithmicDepthBufferEnabled&&r.push(" gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),r.push(" outPickColor = vPickColor; "),r.push("}"),r}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),e}(),bc=Z.vec3(),Dc=function(){function e(t){b(this,e),this._scene=t,this._hash=this._getHash(),this._allocate()}return P(e,[{key:"getValid",value:function(){return this._hash===this._getHash()}},{key:"_getHash",value:function(){return this._scene._sectionPlanesState.getHash()}},{key:"drawLayer",value:function(e,t,n){var r=t.model,i=r.scene,a=i.camera,s=i.canvas.gl,o=t._state,l=o.textureState,u=t._state.origin;this._program||this._allocate(),e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram()),l.bindCommonTextures(this._program,this._uTexturePerObjectIdPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this._uTexturePerObjectIdColorsAndFlags,this._uTextureCameraMatrices,this._uTextureModelMatrices,this._uTexturePerObjectIdOffsets);var c=a.eye;e.pickViewMatrix&&(l.bindPickCameraTexture(this._program,this._uTextureCameraMatrices),c=e.pickOrigin||c);var f=[c[0]-u[0],c[1]-u[1],c[2]-u[2]];if(s.uniform3fv(this._uCameraEyeRtc,f),s.uniform1i(this._uRenderPass,n),s.uniform1i(this._uPickInvisible,e.pickInvisible),s.uniform1f(this._uPickZNear,e.pickZNear),s.uniform1f(this._uPickZFar,e.pickZFar),i.logarithmicDepthBufferEnabled){var p=2/(Math.log(e.pickZFar+1)/Math.LN2);s.uniform1f(this._uLogDepthBufFC,p)}var A=i._sectionPlanesState.sectionPlanes.length;if(A>0)for(var d=i._sectionPlanesState.sectionPlanes,v=t.layerIndex*A,h=r.renderFlags,I=0;I<A;I++){var y=this._uSectionPlanes[I];if(y){var m=h.sectionPlanesActivePerLayer[v+I];if(s.uniform1i(y.active,m?1:0),m){var w=d[I];if(u){var g=ge(w.dist,w.dir,u,bc);s.uniform3fv(y.pos,g)}else s.uniform3fv(y.pos,w.pos);s.uniform3fv(y.dir,w.dir)}}}o.numIndices8Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),s.drawArrays(s.TRIANGLES,0,o.numIndices8Bits)),o.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),s.drawArrays(s.TRIANGLES,0,o.numIndices16Bits)),o.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),s.drawArrays(s.TRIANGLES,0,o.numIndices32Bits)),e.drawElements++}},{key:"_allocate",value:function(){var e=this._scene,t=e.canvas.gl;if(this._program=new ft(t,this._buildShader()),this._program.errors)this.errors=this._program.errors;else{var n=this._program;this._uRenderPass=n.getLocation("renderPass"),this._uPickInvisible=n.getLocation("pickInvisible"),this._uSectionPlanes=[];for(var r=0,i=e._sectionPlanesState.sectionPlanes.length;r<i;r++)this._uSectionPlanes.push({active:n.getLocation("sectionPlaneActive"+r),pos:n.getLocation("sectionPlanePos"+r),dir:n.getLocation("sectionPlaneDir"+r)});this._aPackedVertexId=n.getAttribute("packedVertexId"),this._uPickZNear=n.getLocation("pickZNear"),this._uPickZFar=n.getLocation("pickZFar"),e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=n.getLocation("logDepthBufFC")),this._uTexturePerObjectIdPositionsDecodeMatrix="uTexturePerObjectIdPositionsDecodeMatrix",this._uTexturePerObjectIdColorsAndFlags="uTexturePerObjectIdColorsAndFlags",this._uTexturePerVertexIdCoordinates="uTexturePerVertexIdCoordinates",this._uTexturePerPolygonIdNormals="uTexturePerPolygonIdNormals",this._uTexturePerPolygonIdIndices="uTexturePerPolygonIdIndices",this._uTexturePerPolygonIdPortionIds="uTexturePerPolygonIdPortionIds",this._uTextureCameraMatrices="uTextureCameraMatrices",this._uTextureModelMatrices="uTextureModelMatrices",this._uTexturePerObjectIdOffsets="uTexturePerObjectIdOffsets",this._uCameraEyeRtc=n.getLocation("uCameraEyeRtc")}}},{key:"_bindProgram",value:function(){this._program.bind()}},{key:"_buildShader",value:function(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,n=[];return n.push("#version 300 es"),n.push("// Triangles dataTexture pick depth vertex shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("precision highp usampler2D;"),n.push("precision highp isampler2D;"),n.push("precision highp sampler2D;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("precision mediump usampler2D;"),n.push("precision mediump isampler2D;"),n.push("precision mediump sampler2D;"),n.push("#endif"),n.push("uniform int renderPass;"),e.entityOffsetsEnabled&&n.push("in vec3 offset;"),n.push("uniform bool pickInvisible;"),n.push("uniform highp sampler2D uTexturePerObjectIdPositionsDecodeMatrix;"),n.push("uniform lowp usampler2D uTexturePerObjectIdColorsAndFlags;"),n.push("uniform highp sampler2D uTexturePerObjectIdOffsets;"),n.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),n.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),n.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),n.push("uniform highp sampler2D uTextureCameraMatrices;"),n.push("uniform highp sampler2D uTextureModelMatrices;"),n.push("uniform vec3 uCameraEyeRtc;"),n.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("out float vFragDepth;"),n.push("out float isPerspective;")),n.push("bool isPerspectiveMatrix(mat4 m) {"),n.push(" return (m[2][3] == - 1.0);"),n.push("}"),t&&(n.push("out vec4 vWorldPosition;"),n.push("flat out uint vFlags2;")),n.push("out vec4 vViewPosition;"),n.push("void main(void) {"),n.push("mat4 viewMatrix = mat4 (texelFetch (uTextureCameraMatrices, ivec2(0, 0), 0), texelFetch (uTextureCameraMatrices, ivec2(1, 0), 0), texelFetch (uTextureCameraMatrices, ivec2(2, 0), 0), texelFetch (uTextureCameraMatrices, ivec2(3, 0), 0));"),n.push("mat4 viewNormalMatrix = mat4 (texelFetch (uTextureCameraMatrices, ivec2(0, 1), 0), texelFetch (uTextureCameraMatrices, ivec2(1, 1), 0), texelFetch (uTextureCameraMatrices, ivec2(2, 1), 0), texelFetch (uTextureCameraMatrices, ivec2(3, 1), 0));"),n.push("mat4 projMatrix = mat4 (texelFetch (uTextureCameraMatrices, ivec2(0, 2), 0), texelFetch (uTextureCameraMatrices, ivec2(1, 2), 0), texelFetch (uTextureCameraMatrices, ivec2(2, 2), 0), texelFetch (uTextureCameraMatrices, ivec2(3, 2), 0));"),n.push("mat4 worldMatrix = mat4 (texelFetch (uTextureModelMatrices, ivec2(0, 0), 0), texelFetch (uTextureModelMatrices, ivec2(1, 0), 0), texelFetch (uTextureModelMatrices, ivec2(2, 0), 0), texelFetch (uTextureModelMatrices, ivec2(3, 0), 0));"),n.push("mat4 worldNormalMatrix = mat4 (texelFetch (uTextureModelMatrices, ivec2(0, 1), 0), texelFetch (uTextureModelMatrices, ivec2(1, 1), 0), texelFetch (uTextureModelMatrices, ivec2(2, 1), 0), texelFetch (uTextureModelMatrices, ivec2(3, 1), 0));"),n.push("int polygonIndex = gl_VertexID / 3;"),n.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),n.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),n.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),n.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),n.push("uvec4 flags = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),n.push("uvec4 flags2 = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),n.push("if (int(flags.w) != renderPass) {"),n.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),n.push(" return;"),n.push("} else {"),n.push("ivec4 packedVertexBase = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),n.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),n.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),n.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),n.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),n.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),n.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),n.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),n.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),n.push("mat4 positionsDecodeMatrix = mat4 (texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),n.push("uint solid = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),n.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),n.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),n.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),n.push("uvec4 color = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),n.push("if (color.a == 0u) {"),n.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),n.push(" return;"),n.push("};"),n.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),n.push("vec3 position;"),n.push("position = positions[gl_VertexID % 3];"),n.push("if (solid != 1u) {"),n.push("if (isPerspectiveMatrix(projMatrix)) {"),n.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(worldMatrix * positionsDecodeMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),n.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),n.push("position = positions[2 - (gl_VertexID % 3)];"),n.push("}"),n.push("} else {"),n.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*positionsDecodeMatrix)) * vec4(normal,1)).xyz);"),n.push("if (viewNormal.z < 0.0) {"),n.push("position = positions[2 - (gl_VertexID % 3)];"),n.push("}"),n.push("}"),n.push("}"),n.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),n.push("vec4 offset = vec4(texelFetch (uTexturePerObjectIdOffsets, objectIndexCoords, 0).rgb, 0.0);"),n.push("worldPosition.xyz = worldPosition.xyz + offset.xyz;"),n.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(n.push(" vWorldPosition = worldPosition;"),n.push(" vFlags2 = flags2.r;")),n.push("vViewPosition = viewPosition;"),n.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(n.push("vFragDepth = 1.0 + clipPos.w;"),n.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),n.push("gl_Position = clipPos;"),n.push(" }"),n.push("}"),n}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,n=t.sectionPlanes.length>0,r=[];if(r.push("#version 300 es"),r.push("// Triangles dataTexture pick depth fragment shader"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),e.logarithmicDepthBufferEnabled&&(r.push("in float isPerspective;"),r.push("uniform float logDepthBufFC;"),r.push("in float vFragDepth;")),r.push("uniform float pickZNear;"),r.push("uniform float pickZFar;"),n){r.push("in vec4 vWorldPosition;"),r.push("flat in uint vFlags2;");for(var i=0;i<t.sectionPlanes.length;i++)r.push("uniform bool sectionPlaneActive"+i+";"),r.push("uniform vec3 sectionPlanePos"+i+";"),r.push("uniform vec3 sectionPlaneDir"+i+";")}if(r.push("in vec4 vViewPosition;"),r.push("vec4 packDepth(const in float depth) {"),r.push(" const vec4 bitShift = vec4(256.0*256.0*256.0, 256.0*256.0, 256.0, 1.0);"),r.push(" const vec4 bitMask = vec4(0.0, 1.0/256.0, 1.0/256.0, 1.0/256.0);"),r.push(" vec4 res = fract(depth * bitShift);"),r.push(" res -= res.xxyz * bitMask;"),r.push(" return res;"),r.push("}"),r.push("out vec4 outPackedDepth;"),r.push("void main(void) {"),n){r.push(" bool clippable = vFlags2 > 0u;"),r.push(" if (clippable) {"),r.push(" float dist = 0.0;");for(i=0;i<t.sectionPlanes.length;i++)r.push(" if (sectionPlaneActive"+i+") {"),r.push(" dist += clamp(dot(-sectionPlaneDir"+i+".xyz, vWorldPosition.xyz - sectionPlanePos"+i+".xyz), 0.0, 1000.0);"),r.push(" }");r.push(" if (dist > 0.0) { discard; }"),r.push(" }")}return e.logarithmicDepthBufferEnabled&&r.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),r.push(" float zNormalizedDepth = abs((pickZNear + vViewPosition.z) / (pickZFar - pickZNear));"),r.push(" outPackedDepth = packDepth(zNormalizedDepth); "),r.push("}"),r}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),e}(),Pc=Z.vec3(),Rc=function(){function e(t){b(this,e),this._scene=t,this._hash=this._getHash(),this._allocate()}return P(e,[{key:"getValid",value:function(){return this._hash===this._getHash()}},{key:"_getHash",value:function(){return this._scene._sectionPlanesState.getHash()}},{key:"drawLayer",value:function(e,t,n){var r=t.model,i=r.scene,a=i.camera,s=i.canvas.gl,o=t._state,l=o.textureState,u=t._state.origin;e.snapPickOrigin[0]=u[0],e.snapPickOrigin[1]=u[1],e.snapPickOrigin[2]=u[2];var c=t.aabb,f=[Z.safeInv(c[3]-c[0])*Z.MAX_INT,Z.safeInv(c[4]-c[1])*Z.MAX_INT,Z.safeInv(c[5]-c[2])*Z.MAX_INT];e.snapPickCoordinateScale[0]=Z.safeInv(f[0]),e.snapPickCoordinateScale[1]=Z.safeInv(f[1]),e.snapPickCoordinateScale[2]=Z.safeInv(f[2]),this._program||this._allocate(),e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram()),l.bindCommonTextures(this._program,this._uTexturePerObjectIdPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this._uTexturePerObjectIdColorsAndFlags,this._uTextureCameraMatrices,this._uTextureModelMatrices,this._uTexturePerObjectIdOffsets);var p=a.eye;e.pickViewMatrix&&(l.bindPickCameraTexture(this._program,this._uTextureCameraMatrices),p=e.pickOrigin||p);var A=[p[0]-u[0],p[1]-u[1],p[2]-u[2]];if(s.uniform3fv(this._uCameraEyeRtc,A),s.uniform2fv(this.uVectorA,e.snapVectorA),s.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),s.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),s.uniform3fv(this._uCoordinateScaler,f),s.uniform1i(this._uRenderPass,n),s.uniform1i(this._uPickInvisible,e.pickInvisible),i.logarithmicDepthBufferEnabled){var d=2/(Math.log(e.pickZFar+1)/Math.LN2);s.uniform1f(this._uLogDepthBufFC,d)}var v=i._sectionPlanesState.sectionPlanes.length;if(v>0)for(var h=i._sectionPlanesState.sectionPlanes,I=t.layerIndex*v,y=r.renderFlags,m=0;m<v;m++){var w=this._uSectionPlanes[m];if(w){var g=y.sectionPlanesActivePerLayer[I+m];if(s.uniform1i(w.active,g?1:0),g){var T=h[m];if(u){var E=ge(T.dist,T.dir,u,Pc);s.uniform3fv(w.pos,E)}else s.uniform3fv(w.pos,T.pos);s.uniform3fv(w.dir,T.dir)}}}var b="edge"===e.snapMode?s.LINES:s.POINTS;o.numEdgeIndices8Bits>0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,8),s.drawArrays(b,0,o.numEdgeIndices8Bits)),o.numEdgeIndices16Bits>0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,16),s.drawArrays(b,0,o.numEdgeIndices16Bits)),o.numEdgeIndices32Bits>0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,32),s.drawArrays(b,0,o.numEdgeIndices32Bits)),e.drawElements++}},{key:"_allocate",value:function(){var e=this._scene,t=e.canvas.gl;if(this._program=new ft(t,this._buildShader()),this._program.errors)this.errors=this._program.errors;else{var n=this._program;this._uRenderPass=n.getLocation("renderPass"),this._uPickInvisible=n.getLocation("pickInvisible"),this._uSectionPlanes=[];for(var r=0,i=e._sectionPlanesState.sectionPlanes.length;r<i;r++)this._uSectionPlanes.push({active:n.getLocation("sectionPlaneActive"+r),pos:n.getLocation("sectionPlanePos"+r),dir:n.getLocation("sectionPlaneDir"+r)});e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=n.getLocation("logDepthBufFC")),this._uTexturePerObjectIdPositionsDecodeMatrix="uTexturePerObjectIdPositionsDecodeMatrix",this._uTexturePerObjectIdColorsAndFlags="uTexturePerObjectIdColorsAndFlags",this._uTexturePerVertexIdCoordinates="uTexturePerVertexIdCoordinates",this._uTexturePerPolygonIdEdgeIndices="uTexturePerPolygonIdEdgeIndices",this._uTexturePerEdgeIdPortionIds="uTexturePerEdgeIdPortionIds",this._uTextureCameraMatrices="uTextureCameraMatrices",this._uTextureModelMatrices="uTextureModelMatrices",this._uTexturePerObjectIdOffsets="uTexturePerObjectIdOffsets",this._uCameraEyeRtc=n.getLocation("uCameraEyeRtc"),this.uVectorA=n.getLocation("uSnapVectorA"),this.uInverseVectorAB=n.getLocation("uSnapInvVectorAB"),this._uLayerNumber=n.getLocation("uLayerNumber"),this._uCoordinateScaler=n.getLocation("uCoordinateLayer")}}},{key:"_bindProgram",value:function(){this._program.bind()}},{key:"_buildShader",value:function(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,n=[];return n.push("#version 300 es"),n.push("// Batched geometry edges drawing vertex shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("precision highp usampler2D;"),n.push("precision highp isampler2D;"),n.push("precision highp sampler2D;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("precision mediump usampler2D;"),n.push("precision mediump isampler2D;"),n.push("precision mediump sampler2D;"),n.push("#endif"),n.push("uniform int renderPass;"),e.entityOffsetsEnabled&&n.push("in vec3 offset;"),n.push("uniform highp sampler2D uTexturePerObjectIdPositionsDecodeMatrix;"),n.push("uniform lowp usampler2D uTexturePerObjectIdColorsAndFlags;"),n.push("uniform highp sampler2D uTexturePerObjectIdOffsets;"),n.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),n.push("uniform highp usampler2D uTexturePerPolygonIdEdgeIndices;"),n.push("uniform mediump usampler2D uTexturePerEdgeIdPortionIds;"),n.push("uniform highp sampler2D uTextureCameraMatrices;"),n.push("uniform highp sampler2D uTextureModelMatrices;"),n.push("uniform vec3 uCameraEyeRtc;"),n.push("uniform vec2 uSnapVectorA;"),n.push("uniform vec2 uSnapInvVectorAB;"),n.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("out float vFragDepth;"),n.push("bool isPerspectiveMatrix(mat4 m) {"),n.push(" return (m[2][3] == - 1.0);"),n.push("}"),n.push("out float isPerspective;")),n.push("vec2 remapClipPos(vec2 clipPos) {"),n.push(" float x = (clipPos.x - uSnapVectorA.x) * uSnapInvVectorAB.x;"),n.push(" float y = (clipPos.y - uSnapVectorA.y) * uSnapInvVectorAB.y;"),n.push(" return vec2(x, y);"),n.push("}"),t&&(n.push("out vec4 vWorldPosition;"),n.push("flat out uint vFlags2;")),n.push("out vec4 vViewPosition;"),n.push("out highp vec3 relativeToOriginPosition;"),n.push("void main(void) {"),n.push("mat4 viewMatrix = mat4 (texelFetch (uTextureCameraMatrices, ivec2(0, 0), 0), texelFetch (uTextureCameraMatrices, ivec2(1, 0), 0), texelFetch (uTextureCameraMatrices, ivec2(2, 0), 0), texelFetch (uTextureCameraMatrices, ivec2(3, 0), 0));"),n.push("mat4 viewNormalMatrix = mat4 (texelFetch (uTextureCameraMatrices, ivec2(0, 1), 0), texelFetch (uTextureCameraMatrices, ivec2(1, 1), 0), texelFetch (uTextureCameraMatrices, ivec2(2, 1), 0), texelFetch (uTextureCameraMatrices, ivec2(3, 1), 0));"),n.push("mat4 projMatrix = mat4 (texelFetch (uTextureCameraMatrices, ivec2(0, 2), 0), texelFetch (uTextureCameraMatrices, ivec2(1, 2), 0), texelFetch (uTextureCameraMatrices, ivec2(2, 2), 0), texelFetch (uTextureCameraMatrices, ivec2(3, 2), 0));"),n.push("mat4 worldMatrix = mat4 (texelFetch (uTextureModelMatrices, ivec2(0, 0), 0), texelFetch (uTextureModelMatrices, ivec2(1, 0), 0), texelFetch (uTextureModelMatrices, ivec2(2, 0), 0), texelFetch (uTextureModelMatrices, ivec2(3, 0), 0));"),n.push("mat4 worldNormalMatrix = mat4 (texelFetch (uTextureModelMatrices, ivec2(0, 1), 0), texelFetch (uTextureModelMatrices, ivec2(1, 1), 0), texelFetch (uTextureModelMatrices, ivec2(2, 1), 0), texelFetch (uTextureModelMatrices, ivec2(3, 1), 0));"),n.push("int edgeIndex = gl_VertexID / 2;"),n.push("int h_packed_object_id_index = (edgeIndex >> 3) & 4095;"),n.push("int v_packed_object_id_index = (edgeIndex >> 3) >> 12;"),n.push("int objectIndex = int(texelFetch(uTexturePerEdgeIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),n.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),n.push("uvec4 flags = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),n.push("uvec4 flags2 = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),n.push("{"),n.push("ivec4 packedVertexBase = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),n.push("ivec4 packedEdgeIndexBaseOffset = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+6, objectIndexCoords.y), 0));"),n.push("int edgeIndexBaseOffset = (packedEdgeIndexBaseOffset.r << 24) + (packedEdgeIndexBaseOffset.g << 16) + (packedEdgeIndexBaseOffset.b << 8) + packedEdgeIndexBaseOffset.a;"),n.push("int h_index = (edgeIndex - edgeIndexBaseOffset) & 4095;"),n.push("int v_index = (edgeIndex - edgeIndexBaseOffset) >> 12;"),n.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdEdgeIndices, ivec2(h_index, v_index), 0));"),n.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),n.push("int indexPositionH = uniqueVertexIndexes[gl_VertexID % 2] & 4095;"),n.push("int indexPositionV = uniqueVertexIndexes[gl_VertexID % 2] >> 12;"),n.push("mat4 positionsDecodeMatrix = mat4 (texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),n.push("uvec4 flags = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),n.push("uvec4 flags2 = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),n.push("vec3 position = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH, indexPositionV), 0));"),n.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),n.push("vec4 offset = vec4(texelFetch (uTexturePerObjectIdOffsets, objectIndexCoords, 0).rgb, 0.0);"),n.push("worldPosition.xyz = worldPosition.xyz + offset.xyz;"),n.push("relativeToOriginPosition = worldPosition.xyz;"),n.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(n.push(" vWorldPosition = worldPosition;"),n.push(" vFlags2 = flags2.r;")),n.push("vViewPosition = viewPosition;"),n.push("vec4 clipPos = projMatrix * viewPosition;"),n.push("float tmp = clipPos.w;"),n.push("clipPos.xyzw /= tmp;"),n.push("clipPos.xy = remapClipPos(clipPos.xy);"),n.push("clipPos.xyzw *= tmp;"),n.push("vViewPosition = clipPos;"),e.logarithmicDepthBufferEnabled&&(n.push("vFragDepth = 1.0 + clipPos.w;"),n.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),n.push("gl_Position = clipPos;"),n.push("gl_PointSize = 1.0;"),n.push(" }"),n.push("}"),n}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,n=t.sectionPlanes.length>0,r=[];if(r.push("#version 300 es"),r.push("// Triangles dataTexture pick depth fragment shader"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),e.logarithmicDepthBufferEnabled&&(r.push("in float isPerspective;"),r.push("uniform float logDepthBufFC;"),r.push("in float vFragDepth;")),r.push("uniform int uLayerNumber;"),r.push("uniform vec3 uCoordinateLayer;"),n){r.push("in vec4 vWorldPosition;"),r.push("flat in uint vFlags2;");for(var i=0,a=t.sectionPlanes.length;i<a;i++)r.push("uniform bool sectionPlaneActive"+i+";"),r.push("uniform vec3 sectionPlanePos"+i+";"),r.push("uniform vec3 sectionPlaneDir"+i+";")}if(r.push("in highp vec3 relativeToOriginPosition;"),r.push("out highp ivec4 outCoords;"),r.push("void main(void) {"),n){r.push(" bool clippable = vFlags2 > 0u;"),r.push(" if (clippable) {"),r.push(" float dist = 0.0;");for(var s=0;s<t.sectionPlanes.length;s++)r.push(" if (sectionPlaneActive"+s+") {"),r.push(" dist += clamp(dot(-sectionPlaneDir"+s+".xyz, vWorldPosition.xyz - sectionPlanePos"+s+".xyz), 0.0, 1000.0);"),r.push(" }");r.push(" if (dist > 0.0) { discard; }"),r.push(" }")}return e.logarithmicDepthBufferEnabled&&r.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),r.push("outCoords = ivec4(relativeToOriginPosition.xyz*uCoordinateLayer.xyz, uLayerNumber);"),r.push("}"),r}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),e}(),Cc=Z.vec3(),_c=function(){function e(t){b(this,e),this._scene=t,this._hash=this._getHash(),this._allocate()}return P(e,[{key:"getValid",value:function(){return this._hash===this._getHash()}},{key:"_getHash",value:function(){return this._scene._sectionPlanesState.getHash()}},{key:"drawLayer",value:function(e,t,n){var r=t.model,i=r.scene,a=i.camera,s=i.canvas.gl,o=t._state,l=o.textureState,u=t._state.origin;e.snapPickOrigin[0]=u[0],e.snapPickOrigin[1]=u[1],e.snapPickOrigin[2]=u[2];var c=t.aabb,f=[Z.safeInv(c[3]-c[0])*Z.MAX_INT,Z.safeInv(c[4]-c[1])*Z.MAX_INT,Z.safeInv(c[5]-c[2])*Z.MAX_INT];e.snapPickCoordinateScale[0]=Z.safeInv(f[0]),e.snapPickCoordinateScale[1]=Z.safeInv(f[1]),e.snapPickCoordinateScale[2]=Z.safeInv(f[2]),this._program||this._allocate(),e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram()),l.bindCommonTextures(this._program,this._uTexturePerObjectIdPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this._uTexturePerObjectIdColorsAndFlags,this._uTextureCameraMatrices,this._uTextureModelMatrices,this._uTexturePerObjectIdOffsets);var p=a.eye;e.pickViewMatrix&&(l.bindPickCameraTexture(this._program,this._uTextureCameraMatrices),p=e.pickOrigin||p);var A=[p[0]-u[0],p[1]-u[1],p[2]-u[2]];if(s.uniform3fv(this._uCameraEyeRtc,A),s.uniform2fv(this._uVectorA,e.snapVectorA),s.uniform2fv(this._uInverseVectorAB,e.snapInvVectorAB),s.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),s.uniform3fv(this._uCoordinateScaler,f),s.uniform1i(this._uRenderPass,n),s.uniform1i(this._uPickInvisible,e.pickInvisible),i.logarithmicDepthBufferEnabled){var d=2/(Math.log(e.pickZFar+1)/Math.LN2);s.uniform1f(this._uLogDepthBufFC,d)}var v=i._sectionPlanesState.sectionPlanes.length;if(v>0)for(var h=i._sectionPlanesState.sectionPlanes,I=t.layerIndex*v,y=r.renderFlags,m=0;m<v;m++){var w=this._uSectionPlanes[m];if(w){var g=y.sectionPlanesActivePerLayer[I+m];if(s.uniform1i(w.active,g?1:0),g){var T=h[m];if(u){var E=getPlaneRTCPos(T.dist,T.dir,u,Cc);s.uniform3fv(w.pos,E)}else s.uniform3fv(w.pos,T.pos);s.uniform3fv(w.dir,T.dir)}}}o.numIndices8Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),s.drawArrays(s.TRIANGLES,0,o.numIndices8Bits)),o.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),s.drawArrays(s.TRIANGLES,0,o.numIndices16Bits)),o.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),s.drawArrays(s.TRIANGLES,0,o.numIndices32Bits)),e.drawElements++}},{key:"_allocate",value:function(){var e=this._scene,t=e.canvas.gl;if(this._program=new ft(t,this._buildShader()),this._program.errors)this.errors=this._program.errors;else{var n=this._program;this._uRenderPass=n.getLocation("renderPass"),this._uPickInvisible=n.getLocation("pickInvisible"),this._uSectionPlanes=[];for(var r=0,i=e._sectionPlanesState.sectionPlanes.length;r<i;r++)this._uSectionPlanes.push({active:n.getLocation("sectionPlaneActive"+r),pos:n.getLocation("sectionPlanePos"+r),dir:n.getLocation("sectionPlaneDir"+r)});e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=n.getLocation("logDepthBufFC")),this._uTexturePerObjectIdPositionsDecodeMatrix="uTexturePerObjectIdPositionsDecodeMatrix",this._uTexturePerObjectIdColorsAndFlags="uTexturePerObjectIdColorsAndFlags",this._uTexturePerVertexIdCoordinates="uTexturePerVertexIdCoordinates",this._uTexturePerPolygonIdIndices="uTexturePerPolygonIdIndices",this._uTexturePerPolygonIdPortionIds="uTexturePerPolygonIdPortionIds",this._uTextureCameraMatrices="uTextureCameraMatrices",this._uTextureModelMatrices="uTextureModelMatrices",this._uTexturePerObjectIdOffsets="uTexturePerObjectIdOffsets",this._uCameraEyeRtc=n.getLocation("uCameraEyeRtc"),this._uVectorA=n.getLocation("uVectorAB"),this._uInverseVectorAB=n.getLocation("uInverseVectorAB"),this._uLayerNumber=n.getLocation("uLayerNumber"),this._uCoordinateScaler=n.getLocation("uCoordinateScaler")}}},{key:"_bindProgram",value:function(){this._program.bind()}},{key:"_buildShader",value:function(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,n=[];return n.push("#version 300 es"),n.push("// TrianglesDataTextureSnapDepthBufInitRenderer vertex shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("precision highp usampler2D;"),n.push("precision highp isampler2D;"),n.push("precision highp sampler2D;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("precision mediump usampler2D;"),n.push("precision mediump isampler2D;"),n.push("precision mediump sampler2D;"),n.push("#endif"),n.push("uniform int renderPass;"),e.entityOffsetsEnabled&&n.push("in vec3 offset;"),n.push("uniform highp sampler2D uTexturePerObjectIdPositionsDecodeMatrix;"),n.push("uniform lowp usampler2D uTexturePerObjectIdColorsAndFlags;"),n.push("uniform highp sampler2D uTexturePerObjectIdOffsets;"),n.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),n.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),n.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),n.push("uniform highp sampler2D uTextureCameraMatrices;"),n.push("uniform highp sampler2D uTextureModelMatrices;"),n.push("uniform vec3 uCameraEyeRtc;"),n.push("uniform vec2 uVectorAB;"),n.push("uniform vec2 uInverseVectorAB;"),n.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("out float vFragDepth;"),n.push("out float isPerspective;")),n.push("bool isPerspectiveMatrix(mat4 m) {"),n.push(" return (m[2][3] == - 1.0);"),n.push("}"),n.push("vec2 remapClipPos(vec2 clipPos) {"),n.push(" float x = (clipPos.x - uVectorAB.x) * uInverseVectorAB.x;"),n.push(" float y = (clipPos.y - uVectorAB.y) * uInverseVectorAB.y;"),n.push(" return vec2(x, y);"),n.push("}"),t&&(n.push("out vec4 vWorldPosition;"),n.push("flat out uint vFlags2;")),n.push("out highp vec3 relativeToOriginPosition;"),n.push("void main(void) {"),n.push("int polygonIndex = gl_VertexID / 3;"),n.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),n.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),n.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),n.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),n.push("uvec4 flags = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),n.push("uvec4 flags2 = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),n.push("{"),n.push("uvec4 color = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),n.push("if (color.a == 0u) {"),n.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),n.push(" return;"),n.push("};"),n.push("mat4 viewMatrix = mat4 (texelFetch (uTextureCameraMatrices, ivec2(0, 0), 0), texelFetch (uTextureCameraMatrices, ivec2(1, 0), 0), texelFetch (uTextureCameraMatrices, ivec2(2, 0), 0), texelFetch (uTextureCameraMatrices, ivec2(3, 0), 0));"),n.push("mat4 viewNormalMatrix = mat4 (texelFetch (uTextureCameraMatrices, ivec2(0, 1), 0), texelFetch (uTextureCameraMatrices, ivec2(1, 1), 0), texelFetch (uTextureCameraMatrices, ivec2(2, 1), 0), texelFetch (uTextureCameraMatrices, ivec2(3, 1), 0));"),n.push("mat4 projMatrix = mat4 (texelFetch (uTextureCameraMatrices, ivec2(0, 2), 0), texelFetch (uTextureCameraMatrices, ivec2(1, 2), 0), texelFetch (uTextureCameraMatrices, ivec2(2, 2), 0), texelFetch (uTextureCameraMatrices, ivec2(3, 2), 0));"),n.push("mat4 worldMatrix = mat4 (texelFetch (uTextureModelMatrices, ivec2(0, 0), 0), texelFetch (uTextureModelMatrices, ivec2(1, 0), 0), texelFetch (uTextureModelMatrices, ivec2(2, 0), 0), texelFetch (uTextureModelMatrices, ivec2(3, 0), 0));"),n.push("mat4 worldNormalMatrix = mat4 (texelFetch (uTextureModelMatrices, ivec2(0, 1), 0), texelFetch (uTextureModelMatrices, ivec2(1, 1), 0), texelFetch (uTextureModelMatrices, ivec2(2, 1), 0), texelFetch (uTextureModelMatrices, ivec2(3, 1), 0));"),n.push("ivec4 packedVertexBase = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),n.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),n.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),n.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),n.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),n.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),n.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),n.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),n.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),n.push("mat4 positionsDecodeMatrix = mat4 (texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),n.push("uint solid = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),n.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),n.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),n.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),n.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),n.push("vec3 position;"),n.push("position = positions[gl_VertexID % 3];"),n.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*positionsDecodeMatrix)) * vec4(normal,1)).xyz);"),n.push("if (solid != 1u) {"),n.push(" if (isPerspectiveMatrix(projMatrix)) {"),n.push(" vec3 uCameraEyeRtcInQuantizedSpace = (inverse(worldMatrix * positionsDecodeMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),n.push(" if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),n.push(" position = positions[2 - (gl_VertexID % 3)];"),n.push(" viewNormal = -viewNormal;"),n.push(" }"),n.push(" } else {"),n.push(" if (viewNormal.z < 0.0) {"),n.push(" position = positions[2 - (gl_VertexID % 3)];"),n.push(" viewNormal = -viewNormal;"),n.push(" }"),n.push(" }"),n.push("}"),n.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),n.push("vec4 offset = vec4(texelFetch (uTexturePerObjectIdOffsets, objectIndexCoords, 0).rgb, 0.0);"),n.push("worldPosition.xyz = worldPosition.xyz + offset.xyz;"),n.push("relativeToOriginPosition = worldPosition.xyz;"),n.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(n.push("vWorldPosition = worldPosition;"),n.push("vFlags2 = flags2.r;")),n.push("vec4 clipPos = projMatrix * viewPosition;"),n.push("float tmp = clipPos.w;"),n.push("clipPos.xyzw /= tmp;"),n.push("clipPos.xy = remapClipPos(clipPos.xy);"),n.push("clipPos.z += 0.0001;"),n.push("clipPos.xyzw *= tmp;"),e.logarithmicDepthBufferEnabled&&(n.push("vFragDepth = 1.0 + clipPos.w;"),n.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),n.push("gl_Position = clipPos;"),n.push(" }"),n.push("}"),n}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,n=t.sectionPlanes.length>0,r=[];if(r.push("#version 300 es"),r.push("// TrianglesDataTextureSnapDepthBufInitRenderer fragment shader"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),e.logarithmicDepthBufferEnabled&&(r.push("in float isPerspective;"),r.push("uniform float logDepthBufFC;"),r.push("in float vFragDepth;")),r.push("uniform int uLayerNumber;"),r.push("uniform vec3 uCoordinateScaler;"),n){r.push("in vec4 vWorldPosition;"),r.push("flat in uint vFlags2;");for(var i=0,a=t.sectionPlanes.length;i<a;i++)r.push("uniform bool sectionPlaneActive"+i+";"),r.push("uniform vec3 sectionPlanePos"+i+";"),r.push("uniform vec3 sectionPlaneDir"+i+";")}if(r.push("in highp vec3 relativeToOriginPosition;"),r.push("out highp ivec4 outCoords;"),r.push("void main(void) {"),n){r.push(" bool clippable = vFlags2 > 0u;"),r.push(" if (clippable) {"),r.push(" float dist = 0.0;");for(var s=0;s<t.sectionPlanes.length;s++)r.push(" if (sectionPlaneActive"+s+") {"),r.push(" dist += clamp(dot(-sectionPlaneDir"+s+".xyz, vWorldPosition.xyz - sectionPlanePos"+s+".xyz), 0.0, 1000.0);"),r.push(" }");r.push(" if (dist > 0.0) { discard; }"),r.push(" }")}return e.logarithmicDepthBufferEnabled&&r.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),r.push("outCoords = ivec4(relativeToOriginPosition.xyz * uCoordinateScaler.xyz, - uLayerNumber);"),r.push("}"),r}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),e}(),Bc=Z.vec3(),Oc=function(){function e(t){b(this,e),this._scene=t,this._hash=this._getHash(),this._allocate()}return P(e,[{key:"getValid",value:function(){return this._hash===this._getHash()}},{key:"_getHash",value:function(){return this._scene._sectionPlanesState.getHash()}},{key:"drawLayer",value:function(e,t,n){var r=t.model,i=r.scene,a=i.camera,s=i.canvas.gl,o=t._state,l=o.textureState,u=t._state.origin;this._program||this._allocate(t),e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram()),l.bindCommonTextures(this._program,this._uTexturePerObjectIdPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this._uTexturePerObjectIdColorsAndFlags,this._uTextureCameraMatrices,this._uTextureModelMatrices,this._uTexturePerObjectIdOffsets);var c=a.eye;e.pickViewMatrix&&(l.bindPickCameraTexture(this._program,this._uTextureCameraMatrices),c=e.pickOrigin||c);var f=[c[0]-u[0],c[1]-u[1],c[2]-u[2]];if(s.uniform3fv(this._uCameraEyeRtc,f),s.uniform1i(this._uRenderPass,n),s.uniform3fv(this._uCameraEyeRtc,f),s.uniform1i(this._uPickInvisible,e.pickInvisible),i.logarithmicDepthBufferEnabled){var p=2/(Math.log(a.project.far+1)/Math.LN2);s.uniform1f(this._uLogDepthBufFC,p)}var A=i._sectionPlanesState.sectionPlanes.length;if(A>0)for(var d=i._sectionPlanesState.sectionPlanes,v=t.layerIndex*A,h=r.renderFlags,I=0;I<A;I++){var y=this._uSectionPlanes[I];if(y){var m=h.sectionPlanesActivePerLayer[v+I];if(s.uniform1i(y.active,m?1:0),m){var w=d[I];if(u){var g=ge(w.dist,w.dir,u,Bc);s.uniform3fv(y.pos,g)}else s.uniform3fv(y.pos,w.pos);s.uniform3fv(y.dir,w.dir)}}}o.numIndices8Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),s.drawArrays(s.TRIANGLES,0,o.numIndices8Bits)),o.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),s.drawArrays(s.TRIANGLES,0,o.numIndices16Bits)),o.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),s.drawArrays(s.TRIANGLES,0,o.numIndices32Bits)),e.drawElements++}},{key:"_allocate",value:function(){var e=this._scene,t=e.canvas.gl;if(this._program=new ft(t,this._buildShader()),this._program.errors)this.errors=this._program.errors;else{var n=this._program;this._uRenderPass=n.getLocation("renderPass"),this._uPickInvisible=n.getLocation("pickInvisible"),this._uSectionPlanes=[];for(var r=0,i=e._sectionPlanesState.sectionPlanes.length;r<i;r++)this._uSectionPlanes.push({active:n.getLocation("sectionPlaneActive"+r),pos:n.getLocation("sectionPlanePos"+r),dir:n.getLocation("sectionPlaneDir"+r)});e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=n.getLocation("logDepthBufFC")),this._uTexturePerObjectIdPositionsDecodeMatrix="uTexturePerObjectIdPositionsDecodeMatrix",this._uTexturePerObjectIdColorsAndFlags="uTexturePerObjectIdColorsAndFlags",this._uTexturePerVertexIdCoordinates="uTexturePerVertexIdCoordinates",this._uTexturePerPolygonIdNormals="uTexturePerPolygonIdNormals",this._uTexturePerPolygonIdIndices="uTexturePerPolygonIdIndices",this._uTexturePerPolygonIdPortionIds="uTexturePerPolygonIdPortionIds",this._uTextureCameraMatrices="uTextureCameraMatrices",this._uTextureModelMatrices="uTextureModelMatrices",this._uTexturePerObjectIdOffsets="uTexturePerObjectIdOffsets",this._uCameraEyeRtc=n.getLocation("uCameraEyeRtc")}}},{key:"_bindProgram",value:function(){this._program.bind()}},{key:"_buildShader",value:function(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,n=[];return n.push("#version 300 es"),n.push("// Triangles dataTexture pick normals vertex shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("precision highp usampler2D;"),n.push("precision highp isampler2D;"),n.push("precision highp sampler2D;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("precision mediump usampler2D;"),n.push("precision mediump isampler2D;"),n.push("precision mediump sampler2D;"),n.push("#endif"),n.push("uniform int renderPass;"),e.entityOffsetsEnabled&&n.push("in vec3 offset;"),n.push("uniform bool pickInvisible;"),n.push("uniform highp sampler2D uTexturePerObjectIdPositionsDecodeMatrix;"),n.push("uniform lowp usampler2D uTexturePerObjectIdColorsAndFlags;"),n.push("uniform highp sampler2D uTexturePerObjectIdOffsets;"),n.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),n.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),n.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),n.push("uniform highp sampler2D uTextureCameraMatrices;"),n.push("uniform highp sampler2D uTextureModelMatrices;"),n.push("uniform vec3 uCameraEyeRtc;"),n.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("out float vFragDepth;"),n.push("out float isPerspective;")),n.push("bool isPerspectiveMatrix(mat4 m) {"),n.push(" return (m[2][3] == - 1.0);"),n.push("}"),t&&(n.push("out vec4 vWorldPosition;"),n.push("flat out uint vFlags2;")),n.push("out vec3 vWorldNormal;"),n.push("void main(void) {"),n.push("mat4 viewMatrix = mat4 (texelFetch (uTextureCameraMatrices, ivec2(0, 0), 0), texelFetch (uTextureCameraMatrices, ivec2(1, 0), 0), texelFetch (uTextureCameraMatrices, ivec2(2, 0), 0), texelFetch (uTextureCameraMatrices, ivec2(3, 0), 0));"),n.push("mat4 projMatrix = mat4 (texelFetch (uTextureCameraMatrices, ivec2(0, 2), 0), texelFetch (uTextureCameraMatrices, ivec2(1, 2), 0), texelFetch (uTextureCameraMatrices, ivec2(2, 2), 0), texelFetch (uTextureCameraMatrices, ivec2(3, 2), 0));"),n.push("mat4 worldMatrix = mat4 (texelFetch (uTextureModelMatrices, ivec2(0, 0), 0), texelFetch (uTextureModelMatrices, ivec2(1, 0), 0), texelFetch (uTextureModelMatrices, ivec2(2, 0), 0), texelFetch (uTextureModelMatrices, ivec2(3, 0), 0));"),n.push("int polygonIndex = gl_VertexID / 3;"),n.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),n.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),n.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),n.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),n.push("uvec4 flags = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),n.push("uvec4 flags2 = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),n.push("if (int(flags.w) != renderPass) {"),n.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),n.push(" return;"),n.push("} else {"),n.push("ivec4 packedVertexBase = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),n.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),n.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),n.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),n.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),n.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),n.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),n.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),n.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),n.push("mat4 positionsDecodeMatrix = mat4 (texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),n.push("uint solid = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),n.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),n.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),n.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),n.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),n.push("vec3 position;"),n.push("position = positions[gl_VertexID % 3];"),n.push("if (solid != 1u) {"),n.push("if (isPerspectiveMatrix(projMatrix)) {"),n.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(worldMatrix * positionsDecodeMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),n.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),n.push("position = positions[2 - (gl_VertexID % 3)];"),n.push("normal = -normal;"),n.push("}"),n.push("} else {"),n.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*positionsDecodeMatrix)) * vec4(normal,1)).xyz);"),n.push("if (viewNormal.z < 0.0) {"),n.push("position = positions[2 - (gl_VertexID % 3)];"),n.push("normal = -normal;"),n.push("}"),n.push("}"),n.push("}"),n.push("normal = -normal;"),n.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),n.push("vec4 offset = vec4(texelFetch (uTexturePerObjectIdOffsets, objectIndexCoords, 0).rgb, 0.0);"),n.push("worldPosition.xyz = worldPosition.xyz + offset.xyz;"),n.push("vec4 viewPosition = viewMatrix * worldPosition; "),n.push("vWorldNormal = normal.xyz;"),n.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(n.push("vFragDepth = 1.0 + clipPos.w;"),n.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(n.push(" vWorldPosition = worldPosition;"),n.push(" vFlags2 = flags2.w;")),n.push("gl_Position = clipPos;"),n.push("}"),n.push("}"),n}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,n=t.sectionPlanes.length>0,r=[];if(r.push("#version 300 es"),r.push("// Triangles dataTexture pick normals fragment shader"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),e.logarithmicDepthBufferEnabled&&(r.push("in float isPerspective;"),r.push("uniform float logDepthBufFC;"),r.push("in float vFragDepth;")),n){r.push("in vec4 vWorldPosition;"),r.push("flat in uint vFlags2;");for(var i=0;i<t.sectionPlanes.length;i++)r.push("uniform bool sectionPlaneActive"+i+";"),r.push("uniform vec3 sectionPlanePos"+i+";"),r.push("uniform vec3 sectionPlaneDir"+i+";")}if(r.push("in vec3 vWorldNormal;"),r.push("out vec4 outNormal;"),r.push("void main(void) {"),n){r.push(" bool clippable = vFlags2 > 0u;"),r.push(" if (clippable) {"),r.push(" float dist = 0.0;");for(i=0;i<t.sectionPlanes.length;i++)r.push(" if (sectionPlaneActive"+i+") {"),r.push(" dist += clamp(dot(-sectionPlaneDir"+i+".xyz, vWorldPosition.xyz - sectionPlanePos"+i+".xyz), 0.0, 1000.0);"),r.push(" }");r.push(" if (dist > 0.0) { discard; }"),r.push(" }")}return e.logarithmicDepthBufferEnabled&&r.push(" gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),r.push(" outNormal = vec4((vWorldNormal * 0.5) + 0.5, 1.0);"),r.push("}"),r}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),e}();Z.vec3();var Sc=function(){function e(t){b(this,e),this._scene=t,this._hash=this._getHash(),this._allocate()}return P(e,[{key:"getValid",value:function(){return this._hash===this._getHash()}},{key:"_getHash",value:function(){return this._scene._sectionPlanesState.getHash()}},{key:"drawLayer",value:function(e,t,n){}},{key:"_allocate",value:function(){var e=this._scene,t=e.canvas.gl;if(this._program=new ft(t,this._buildShader()),this._program.errors)this.errors=this._program.errors;else{var n=this._program;this._uRenderPass=n.getLocation("renderPass"),this._uPositionsDecodeMatrix=n.getLocation("positionsDecodeMatrix"),this._uWorldMatrix=n.getLocation("worldMatrix"),this._uViewMatrix=n.getLocation("viewMatrix"),this._uProjMatrix=n.getLocation("projMatrix"),this._uSectionPlanes=[];for(var r=0,i=e._sectionPlanesState.sectionPlanes.length;r<i;r++)this._uSectionPlanes.push({active:n.getLocation("sectionPlaneActive"+r),pos:n.getLocation("sectionPlanePos"+r),dir:n.getLocation("sectionPlaneDir"+r)});this._aPosition=n.getAttribute("position"),this._aOffset=n.getAttribute("offset"),this._aColor=n.getAttribute("color"),this._aFlags=n.getAttribute("flags"),this._aFlags2=n.getAttribute("flags2"),e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=n.getLocation("logDepthBufFC"))}}},{key:"_bindProgram",value:function(){var e=this._scene,t=e.canvas.gl,n=e.camera.project;if(this._program.bind(),t.uniformMatrix4fv(this._uProjMatrix,!1,n.matrix),e.logarithmicDepthBufferEnabled){var r=2/(Math.log(n.far+1)/Math.LN2);t.uniform1f(this._uLogDepthBufFC,r)}}},{key:"_buildShader",value:function(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,n=[];return n.push("// Triangles dataTexture occlusion vertex shader"),e.logarithmicDepthBufferEnabled&&Ze.SUPPORTED_EXTENSIONS.EXT_frag_depth&&n.push("#extension GL_EXT_frag_depth : enable"),n.push("uniform int renderPass;"),n.push("attribute vec3 position;"),e.entityOffsetsEnabled&&n.push("attribute vec3 offset;"),n.push("attribute vec4 color;"),n.push("attribute vec4 flags;"),n.push("attribute vec4 flags2;"),n.push("uniform mat4 worldMatrix;"),n.push("uniform mat4 viewMatrix;"),n.push("uniform mat4 projMatrix;"),n.push("uniform mat4 positionsDecodeMatrix;"),e.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),Ze.SUPPORTED_EXTENSIONS.EXT_frag_depth&&n.push("varying float vFragDepth;"),n.push("bool isPerspectiveMatrix(mat4 m) {"),n.push(" return (m[2][3] == - 1.0);"),n.push("}"),n.push("varying float isPerspective;")),t&&(n.push("varying vec4 vWorldPosition;"),n.push("varying vec4 vFlags2;")),n.push("void main(void) {"),n.push("if (int(flags.x) != renderPass) {"),n.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),n.push(" } else {"),n.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&n.push(" worldPosition.xyz = worldPosition.xyz + offset;"),n.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(n.push(" vWorldPosition = worldPosition;"),n.push(" vFlags2 = flags2;")),n.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(Ze.SUPPORTED_EXTENSIONS.EXT_frag_depth?n.push("vFragDepth = 1.0 + clipPos.w;"):(n.push("clipPos.z = log2( max( 1e-6, clipPos.w + 1.0 ) ) * logDepthBufFC - 1.0;"),n.push("clipPos.z *= clipPos.w;")),n.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),n.push("gl_Position = clipPos;"),n.push(" }"),n.push("}"),n}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,n=t.sectionPlanes.length>0,r=[];if(r.push("// Triangles dataTexture occlusion fragment shader"),e.logarithmicDepthBufferEnabled&&Ze.SUPPORTED_EXTENSIONS.EXT_frag_depth&&r.push("#extension GL_EXT_frag_depth : enable"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),e.logarithmicDepthBufferEnabled&&Ze.SUPPORTED_EXTENSIONS.EXT_frag_depth&&(r.push("varying float isPerspective;"),r.push("uniform float logDepthBufFC;"),r.push("varying float vFragDepth;")),n){r.push("varying vec4 vWorldPosition;"),r.push("varying vec4 vFlags2;");for(var i=0;i<t.sectionPlanes.length;i++)r.push("uniform bool sectionPlaneActive"+i+";"),r.push("uniform vec3 sectionPlanePos"+i+";"),r.push("uniform vec3 sectionPlaneDir"+i+";")}if(r.push("void main(void) {"),n){r.push(" bool clippable = (float(vFlags2.x) > 0.0);"),r.push(" if (clippable) {"),r.push(" float dist = 0.0;");for(var a=0;a<t.sectionPlanes.length;a++)r.push(" if (sectionPlaneActive"+a+") {"),r.push(" dist += clamp(dot(-sectionPlaneDir"+a+".xyz, vWorldPosition.xyz - sectionPlanePos"+a+".xyz), 0.0, 1000.0);"),r.push(" }");r.push(" if (dist > 0.0) { discard; }"),r.push(" }")}return e.logarithmicDepthBufferEnabled&&Ze.SUPPORTED_EXTENSIONS.EXT_frag_depth&&r.push(" gl_FragDepthEXT = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),r.push(" gl_FragColor = vec4(0.0, 0.0, 1.0, 1.0); "),r.push("}"),r}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),e}();Z.vec4();var Nc=Z.vec3(),Lc=function(){function e(t){b(this,e),this._scene=t,this._allocate(),this._hash=this._getHash()}return P(e,[{key:"getValid",value:function(){return this._hash===this._getHash()}},{key:"_getHash",value:function(){return this._scene._sectionPlanesState.getHash()}},{key:"drawLayer",value:function(e,t,n){var r=this._scene,i=r.camera,a=t.model,s=r.canvas.gl,o=t._state,l=o.textureState,u=t._state.origin;if(this._program||(this._allocate(),!this.errors)){e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e,o)),l.bindCommonTextures(this._program,this._uTexturePerObjectIdPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this._uTexturePerObjectIdColorsAndFlags,this._uTextureCameraMatrices,this._uTextureModelMatrices,this._uTexturePerObjectIdOffsets);var c=i.eye;e.pickViewMatrix&&(l.bindPickCameraTexture(this._program,this._uTextureCameraMatrices),c=e.pickOrigin||c);var f=[c[0]-u[0],c[1]-u[1],c[2]-u[2]];s.uniform3fv(this._uCameraEyeRtc,f),s.uniform1i(this._uRenderPass,n);var p=r._sectionPlanesState.sectionPlanes.length;if(p>0)for(var A=r._sectionPlanesState.sectionPlanes,d=t.layerIndex*p,v=a.renderFlags,h=0;h<p;h++){var I=this._uSectionPlanes[h];if(I){var y=v.sectionPlanesActivePerLayer[d+h];if(s.uniform1i(I.active,y?1:0),y){var m=A[h];if(u){var w=ge(m.dist,m.dir,u,Nc);s.uniform3fv(I.pos,w)}else s.uniform3fv(I.pos,m.pos);s.uniform3fv(I.dir,m.dir)}}}o.numIndices8Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),s.drawArrays(s.TRIANGLES,0,o.numIndices8Bits)),o.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),s.drawArrays(s.TRIANGLES,0,o.numIndices16Bits)),o.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),s.drawArrays(s.TRIANGLES,0,o.numIndices32Bits)),e.drawElements++}}},{key:"_allocate",value:function(){var e=this._scene,t=e.canvas.gl;if(this._program=new ft(t,this._buildShader()),this._program.errors)this.errors=this._program.errors;else{var n=this._program;this._uRenderPass=n.getLocation("renderPass"),this._uPositionsDecodeMatrix=n.getLocation("positionsDecodeMatrix"),this._uWorldMatrix=n.getLocation("worldMatrix"),this._uViewMatrix=n.getLocation("viewMatrix"),this._uProjMatrix=n.getLocation("projMatrix"),this._uSectionPlanes=[];for(var r=0,i=e._sectionPlanesState.sectionPlanes.length;r<i;r++)this._uSectionPlanes.push({active:n.getLocation("sectionPlaneActive"+r),pos:n.getLocation("sectionPlanePos"+r),dir:n.getLocation("sectionPlaneDir"+r)});e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=n.getLocation("logDepthBufFC")),this._uTexturePerObjectIdPositionsDecodeMatrix="uTexturePerObjectIdPositionsDecodeMatrix",this._uTexturePerObjectIdColorsAndFlags="uTexturePerObjectIdColorsAndFlags",this._uTexturePerVertexIdCoordinates="uTexturePerVertexIdCoordinates",this._uTexturePerPolygonIdNormals="uTexturePerPolygonIdNormals",this._uTexturePerPolygonIdIndices="uTexturePerPolygonIdIndices",this._uTexturePerPolygonIdPortionIds="uTexturePerPolygonIdPortionIds",this._uTextureCameraMatrices="uTextureCameraMatrices",this._uTextureModelMatrices="uTextureModelMatrices",this._uTexturePerObjectIdOffsets="uTexturePerObjectIdOffsets",this._uCameraEyeRtc=n.getLocation("uCameraEyeRtc")}}},{key:"_bindProgram",value:function(e){var t=this._scene,n=t.canvas.gl,r=this._program,i=t.camera.project;if(r.bind(),n.uniformMatrix4fv(this._uProjMatrix,!1,i.matrix),t.logarithmicDepthBufferEnabled){var a=2/(Math.log(i.far+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,a)}}},{key:"_buildShader",value:function(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState;e._lightsState;var n=t.sectionPlanes.length>0,r=[];return r.push("#version 300 es"),r.push("// Triangles dataTexture draw vertex shader"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("precision highp usampler2D;"),r.push("precision highp isampler2D;"),r.push("precision highp sampler2D;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("precision mediump usampler2D;"),r.push("precision mediump isampler2D;"),r.push("precision mediump sampler2D;"),r.push("#endif"),r.push("uniform int renderPass;"),e.entityOffsetsEnabled&&r.push("in vec3 offset;"),r.push("uniform highp sampler2D uTexturePerObjectIdPositionsDecodeMatrix;"),r.push("uniform lowp usampler2D uTexturePerObjectIdColorsAndFlags;"),r.push("uniform highp sampler2D uTexturePerObjectIdOffsets;"),r.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),r.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),r.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),r.push("uniform highp sampler2D uTextureCameraMatrices;"),r.push("uniform highp sampler2D uTextureModelMatrices;"),r.push("uniform vec3 uCameraEyeRtc;"),r.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(r.push("uniform float logDepthBufFC;"),r.push("out float vFragDepth;"),r.push("out float isPerspective;")),r.push("bool isPerspectiveMatrix(mat4 m) {"),r.push(" return (m[2][3] == - 1.0);"),r.push("}"),r.push("out highp vec2 vHighPrecisionZW;"),n&&(r.push("out vec4 vWorldPosition;"),r.push("flat out uint vFlags2;")),r.push("void main(void) {"),r.push("int polygonIndex = gl_VertexID / 3;"),r.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),r.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),r.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),r.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),r.push("uvec4 flags = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),r.push("uvec4 flags2 = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),r.push("if (int(flags.x) != renderPass) {"),r.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),r.push(" return;"),r.push("} else {"),r.push("mat4 viewMatrix = mat4 (texelFetch (uTextureCameraMatrices, ivec2(0, 0), 0), texelFetch (uTextureCameraMatrices, ivec2(1, 0), 0), texelFetch (uTextureCameraMatrices, ivec2(2, 0), 0), texelFetch (uTextureCameraMatrices, ivec2(3, 0), 0));"),r.push("mat4 viewNormalMatrix = mat4 (texelFetch (uTextureCameraMatrices, ivec2(0, 1), 0), texelFetch (uTextureCameraMatrices, ivec2(1, 1), 0), texelFetch (uTextureCameraMatrices, ivec2(2, 1), 0), texelFetch (uTextureCameraMatrices, ivec2(3, 1), 0));"),r.push("mat4 projMatrix = mat4 (texelFetch (uTextureCameraMatrices, ivec2(0, 2), 0), texelFetch (uTextureCameraMatrices, ivec2(1, 2), 0), texelFetch (uTextureCameraMatrices, ivec2(2, 2), 0), texelFetch (uTextureCameraMatrices, ivec2(3, 2), 0));"),r.push("mat4 worldMatrix = mat4 (texelFetch (uTextureModelMatrices, ivec2(0, 0), 0), texelFetch (uTextureModelMatrices, ivec2(1, 0), 0), texelFetch (uTextureModelMatrices, ivec2(2, 0), 0), texelFetch (uTextureModelMatrices, ivec2(3, 0), 0));"),r.push("mat4 worldNormalMatrix = mat4 (texelFetch (uTextureModelMatrices, ivec2(0, 1), 0), texelFetch (uTextureModelMatrices, ivec2(1, 1), 0), texelFetch (uTextureModelMatrices, ivec2(2, 1), 0), texelFetch (uTextureModelMatrices, ivec2(3, 1), 0));"),r.push("ivec4 packedVertexBase = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),r.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),r.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),r.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),r.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),r.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),r.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),r.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),r.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),r.push("mat4 positionsDecodeMatrix = mat4 (texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),r.push("uint solid = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),r.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),r.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),r.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),r.push("uvec4 color = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),r.push("if (color.a == 0u) {"),r.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),r.push(" return;"),r.push("};"),r.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),r.push("vec3 position;"),r.push("position = positions[gl_VertexID % 3];"),r.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*positionsDecodeMatrix)) * vec4(normal,1)).xyz);"),r.push("if (solid != 1u) {"),r.push("if (isPerspectiveMatrix(projMatrix)) {"),r.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(worldMatrix * positionsDecodeMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),r.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),r.push("position = positions[2 - (gl_VertexID % 3)];"),r.push("viewNormal = -viewNormal;"),r.push("}"),r.push("} else {"),r.push("if (viewNormal.z < 0.0) {"),r.push("position = positions[2 - (gl_VertexID % 3)];"),r.push("viewNormal = -viewNormal;"),r.push("}"),r.push("}"),r.push("}"),r.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),r.push("vec4 offset = vec4(texelFetch (uTexturePerObjectIdOffsets, objectIndexCoords, 0).rgb, 0.0);"),r.push("worldPosition.xyz = worldPosition.xyz + offset.xyz;"),r.push("vec4 viewPosition = viewMatrix * worldPosition; "),r.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(r.push("vFragDepth = 1.0 + clipPos.w;"),r.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),n&&(r.push("vWorldPosition = worldPosition;"),r.push("vFlags2 = flags2.r;")),r.push("gl_Position = clipPos;"),r.push("vHighPrecisionZW = gl_Position.zw;"),r.push("}"),r.push("}"),r}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,n=t.sectionPlanes.length>0,r=[];if(r.push("#version 300 es"),r.push("// Triangles dataTexture draw fragment shader"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),r.push("in highp vec2 vHighPrecisionZW;"),r.push("out vec4 outColor;"),e.logarithmicDepthBufferEnabled&&(r.push("in float isPerspective;"),r.push("uniform float logDepthBufFC;"),r.push("in float vFragDepth;")),n){r.push("in vec4 vWorldPosition;"),r.push("flat in uint vFlags2;");for(var i=0,a=t.sectionPlanes.length;i<a;i++)r.push("uniform bool sectionPlaneActive"+i+";"),r.push("uniform vec3 sectionPlanePos"+i+";"),r.push("uniform vec3 sectionPlaneDir"+i+";")}if(r.push("void main(void) {"),n){r.push(" bool clippable = vFlags2 > 0u;"),r.push(" if (clippable) {"),r.push(" float dist = 0.0;");for(var s=0,o=t.sectionPlanes.length;s<o;s++)r.push("if (sectionPlaneActive"+s+") {"),r.push(" dist += clamp(dot(-sectionPlaneDir"+s+".xyz, vWorldPosition.xyz - sectionPlanePos"+s+".xyz), 0.0, 1000.0);"),r.push("}");r.push(" if (dist > 0.0) { "),r.push(" discard;"),r.push(" }"),r.push("}")}return e.logarithmicDepthBufferEnabled&&r.push(" gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),r.push("float fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;"),r.push(" outColor = vec4(vec3(1.0 - fragCoordZ), 1.0); "),r.push("}"),r}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),e}(),xc=Z.vec3(),Mc=function(){function e(t){b(this,e),this._scene=t,this._hash=this._getHash(),this._allocate()}return P(e,[{key:"getValid",value:function(){return this._hash===this._getHash()}},{key:"_getHash",value:function(){return this._scene._sectionPlanesState.getHash()}},{key:"drawLayer",value:function(e,t,n){var r=t.model,i=r.scene,a=i.camera,s=i.canvas.gl,o=t._state,l=t._state.origin;if(this._program||(this._allocate(t),!this.errors)){e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(t)),s.uniform1i(this._uRenderPass,n),s.uniformMatrix4fv(this._uViewMatrix,!1,l?Ie(a.viewMatrix,l):a.viewMatrix),s.uniformMatrix4fv(this._uViewNormalMatrix,!1,a.viewNormalMatrix),s.uniformMatrix4fv(this._uWorldMatrix,!1,r.worldMatrix),s.uniformMatrix4fv(this._uWorldNormalMatrix,!1,r.worldNormalMatrix);var u=i._sectionPlanesState.sectionPlanes.length;if(u>0)for(var c=i._sectionPlanesState.sectionPlanes,f=t.layerIndex*u,p=r.renderFlags,A=0;A<u;A++){var d=this._uSectionPlanes[A];if(d){var v=p.sectionPlanesActivePerLayer[f+A];if(s.uniform1i(d.active,v?1:0),v){var h=c[A];if(l){var I=ge(h.dist,h.dir,l,xc);s.uniform3fv(d.pos,I)}else s.uniform3fv(d.pos,h.pos);s.uniform3fv(d.dir,h.dir)}}}s.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,t._state.positionsDecodeMatrix),this._aPosition.bindArrayBuffer(o.positionsBuf),this._aOffset.bindArrayBuffer(o.offsetsBuf),this._aNormal.bindArrayBuffer(o.normalsBuf),this._aColor.bindArrayBuffer(o.colorsBuf),this._aFlags.bindArrayBuffer(o.flagsBuf),this._aFlags2&&this._aFlags2.bindArrayBuffer(o.flags2Buf),o.indicesBuf.bind(),s.drawElements(s.TRIANGLES,o.indicesBuf.numItems,o.indicesBuf.itemType,0)}}},{key:"_allocate",value:function(){var e=this._scene,t=e.canvas.gl;if(this._program=new ft(t,this._buildShader()),this._program.errors)this.errors=this._program.errors;else{var n=this._program;this._uRenderPass=n.getLocation("renderPass"),this._uPositionsDecodeMatrix=n.getLocation("positionsDecodeMatrix"),this._uWorldMatrix=n.getLocation("worldMatrix"),this._uWorldNormalMatrix=n.getLocation("worldNormalMatrix"),this._uViewMatrix=n.getLocation("viewMatrix"),this._uViewNormalMatrix=n.getLocation("viewNormalMatrix"),this._uProjMatrix=n.getLocation("projMatrix"),this._uSectionPlanes=[];for(var r=0,i=e._sectionPlanesState.sectionPlanes.length;r<i;r++)this._uSectionPlanes.push({active:n.getLocation("sectionPlaneActive"+r),pos:n.getLocation("sectionPlanePos"+r),dir:n.getLocation("sectionPlaneDir"+r)});this._aPosition=n.getAttribute("position"),this._aOffset=n.getAttribute("offset"),this._aNormal=n.getAttribute("normal"),this._aColor=n.getAttribute("color"),this._aFlags=n.getAttribute("flags"),this._aFlags2&&(this._aFlags2=n.getAttribute("flags2")),e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=n.getLocation("logDepthBufFC"))}}},{key:"_bindProgram",value:function(){var e=this._scene,t=e.canvas.gl,n=e.camera.project;if(this._program.bind(),t.uniformMatrix4fv(this._uProjMatrix,!1,n.matrix),e.logarithmicDepthBufferEnabled){var r=2/(Math.log(n.far+1)/Math.LN2);t.uniform1f(this._uLogDepthBufFC,r)}}},{key:"_buildShader",value:function(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,n=[];return n.push("// Batched geometry normals vertex shader"),e.logarithmicDepthBufferEnabled&&Ze.SUPPORTED_EXTENSIONS.EXT_frag_depth&&n.push("#extension GL_EXT_frag_depth : enable"),n.push("uniform int renderPass;"),n.push("attribute vec3 position;"),e.entityOffsetsEnabled&&n.push("attribute vec3 offset;"),n.push("attribute vec3 normal;"),n.push("attribute vec4 color;"),n.push("attribute vec4 flags;"),n.push("attribute vec4 flags2;"),n.push("uniform mat4 worldMatrix;"),n.push("uniform mat4 worldNormalMatrix;"),n.push("uniform mat4 viewMatrix;"),n.push("uniform mat4 projMatrix;"),n.push("uniform mat4 viewNormalMatrix;"),n.push("uniform mat4 positionsDecodeMatrix;"),e.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),Ze.SUPPORTED_EXTENSIONS.EXT_frag_depth&&n.push("varying float vFragDepth;"),n.push("bool isPerspectiveMatrix(mat4 m) {"),n.push(" return (m[2][3] == - 1.0);"),n.push("}"),n.push("varying float isPerspective;")),n.push("vec3 octDecode(vec2 oct) {"),n.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),n.push(" if (v.z < 0.0) {"),n.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),n.push(" }"),n.push(" return normalize(v);"),n.push("}"),t&&(n.push("varying vec4 vWorldPosition;"),n.push("varying vec4 vFlags2;")),n.push("varying vec3 vViewNormal;"),n.push("void main(void) {"),n.push("if (int(flags.x) != renderPass) {"),n.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),n.push(" } else {"),n.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&n.push(" worldPosition.xyz = worldPosition.xyz + offset;"),n.push(" vec4 viewPosition = viewMatrix * worldPosition; "),n.push(" vec4 worldNormal = worldNormalMatrix * vec4(octDecode(normal.xy), 0.0); "),n.push(" vec3 viewNormal = normalize((viewNormalMatrix * worldNormal).xyz);"),t&&(n.push(" vWorldPosition = worldPosition;"),n.push(" vFlags2 = flags2;")),n.push(" vViewNormal = viewNormal;"),n.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(Ze.SUPPORTED_EXTENSIONS.EXT_frag_depth?n.push("vFragDepth = 1.0 + clipPos.w;"):(n.push("clipPos.z = log2( max( 1e-6, clipPos.w + 1.0 ) ) * logDepthBufFC - 1.0;"),n.push("clipPos.z *= clipPos.w;")),n.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),n.push("gl_Position = clipPos;"),n.push(" }"),n.push("}"),n}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,n=t.sectionPlanes.length>0,r=[];if(r.push("// Batched geometry normals fragment shader"),e.logarithmicDepthBufferEnabled&&Ze.SUPPORTED_EXTENSIONS.EXT_frag_depth&&r.push("#extension GL_EXT_frag_depth : enable"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),e.logarithmicDepthBufferEnabled&&Ze.SUPPORTED_EXTENSIONS.EXT_frag_depth&&(r.push("varying float isPerspective;"),r.push("uniform float logDepthBufFC;"),r.push("varying float vFragDepth;")),n){r.push("varying vec4 vWorldPosition;"),r.push("varying vec4 vFlags2;");for(var i=0;i<t.sectionPlanes.length;i++)r.push("uniform bool sectionPlaneActive"+i+";"),r.push("uniform vec3 sectionPlanePos"+i+";"),r.push("uniform vec3 sectionPlaneDir"+i+";")}if(r.push("varying vec3 vViewNormal;"),r.push("vec3 packNormalToRGB( const in vec3 normal ) {"),r.push(" return normalize( normal ) * 0.5 + 0.5;"),r.push("}"),r.push("void main(void) {"),n){r.push(" bool clippable = (float(vFlags2.x) > 0.0);"),r.push(" if (clippable) {"),r.push(" float dist = 0.0;");for(var a=0;a<t.sectionPlanes.length;a++)r.push(" if (sectionPlaneActive"+a+") {"),r.push(" dist += clamp(dot(-sectionPlaneDir"+a+".xyz, vWorldPosition.xyz - sectionPlanePos"+a+".xyz), 0.0, 1000.0);"),r.push(" }");r.push(" if (dist > 0.0) { discard; }"),r.push(" }")}return e.logarithmicDepthBufferEnabled&&Ze.SUPPORTED_EXTENSIONS.EXT_frag_depth&&r.push(" gl_FragDepthEXT = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),r.push(" gl_FragColor = vec4(packNormalToRGB(vViewNormal), 1.0); "),r.push("}"),r}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),e}();Z.vec3();var Fc=function(){function e(t){b(this,e),this._scene=t,this._hash=this._getHash(),this._allocate()}return P(e,[{key:"getValid",value:function(){return this._hash===this._getHash()}},{key:"_getHash",value:function(){return this._scene._sectionPlanesState.getHash()}},{key:"drawLayer",value:function(e,t){}},{key:"_allocate",value:function(){var e=this._scene,t=e.canvas.gl,n=e._sectionPlanesState;if(this._program=new ft(t,this._buildShader()),this._program.errors)this.errors=this._program.errors;else{var r=this._program;this._uPositionsDecodeMatrix=r.getLocation("positionsDecodeMatrix"),this._uShadowViewMatrix=r.getLocation("shadowViewMatrix"),this._uShadowProjMatrix=r.getLocation("shadowProjMatrix"),e.logarithmicDepthBufferEnabled&&(this._uZFar=r.getLocation("zFar")),this._uSectionPlanes=[];for(var i=0,a=n.sectionPlanes.length;i<a;i++)this._uSectionPlanes.push({active:r.getLocation("sectionPlaneActive"+i),pos:r.getLocation("sectionPlanePos"+i),dir:r.getLocation("sectionPlaneDir"+i)});this._aPosition=r.getAttribute("position"),this._aOffset=r.getAttribute("offset"),this._aColor=r.getAttribute("color"),this._aFlags=r.getAttribute("flags"),this._aFlags2=r.getAttribute("flags2")}}},{key:"_bindProgram",value:function(e){var t=this._scene.canvas.gl;this._program.bind(),t.uniformMatrix4fv(this._uShadowViewMatrix,!1,e.shadowViewMatrix),t.uniformMatrix4fv(this._uShadowProjMatrix,!1,e.shadowProjMatrix),this._lastLightId=null}},{key:"_buildShader",value:function(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,n=[];return n.push("// Batched geometry shadow vertex shader"),n.push("attribute vec3 position;"),e.entityOffsetsEnabled&&n.push("attribute vec3 offset;"),n.push("attribute vec4 color;"),n.push("attribute vec4 flags;"),n.push("attribute vec4 flags2;"),n.push("uniform mat4 shadowViewMatrix;"),n.push("uniform mat4 shadowProjMatrix;"),n.push("uniform mat4 positionsDecodeMatrix;"),t&&(n.push("varying vec4 vWorldPosition;"),n.push("varying vec4 vFlags2;")),n.push("varying vec4 vViewPosition;"),n.push("void main(void) {"),n.push(" bool visible = (float(flags.x) > 0.0);"),n.push(" bool transparent = ((float(color.a) / 255.0) < 1.0);"),n.push(" if (!visible || transparent) {"),n.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),n.push(" } else {"),n.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),e.entityOffsetsEnabled&&n.push(" worldPosition.xyz = worldPosition.xyz + offset;"),n.push(" vec4 viewPosition = shadowViewMatrix * worldPosition; "),t&&(n.push(" vWorldPosition = worldPosition;"),n.push(" vFlags2 = flags2;")),n.push(" vViewPosition = viewPosition;"),n.push(" gl_Position = shadowProjMatrix * viewPosition;"),n.push(" }"),n.push("}"),n}},{key:"_buildFragmentShader",value:function(){var e=this._scene._sectionPlanesState,t=e.sectionPlanes.length>0,n=[];if(n.push("// Batched geometry shadow fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),t){n.push("varying vec4 vWorldPosition;"),n.push("varying vec4 vFlags2;");for(var r=0;r<e.sectionPlanes.length;r++)n.push("uniform bool sectionPlaneActive"+r+";"),n.push("uniform vec3 sectionPlanePos"+r+";"),n.push("uniform vec3 sectionPlaneDir"+r+";")}if(n.push("varying vec4 vViewPosition;"),n.push("vec4 encodeFloat( const in float v ) {"),n.push(" const vec4 bitShift = vec4(256 * 256 * 256, 256 * 256, 256, 1.0);"),n.push(" const vec4 bitMask = vec4(0, 1.0 / 256.0, 1.0 / 256.0, 1.0 / 256.0);"),n.push(" vec4 comp = fract(v * bitShift);"),n.push(" comp -= comp.xxyz * bitMask;"),n.push(" return comp;"),n.push("}"),n.push("void main(void) {"),t){n.push(" bool clippable = (float(vFlags2.x) > 0.0);"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(var i=0;i<e.sectionPlanes.length;i++)n.push(" if (sectionPlaneActive"+i+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+i+".xyz, vWorldPosition.xyz - sectionPlanePos"+i+".xyz), 0.0, 1000.0);"),n.push(" }");n.push(" if (dist > 0.0) { discard; }"),n.push(" }")}return n.push(" gl_FragColor = encodeFloat( gl_FragCoord.z); "),n.push("}"),n}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),e}(),Hc=Z.vec4(),Uc=Z.vec3(),Gc={linear:"linearToLinear",sRGB:"sRGBToLinear",gamma:"gammaToLinear"},kc=function(){function e(t,n){b(this,e),this._scene=t,this._withSAO=n,this._hash=this._getHash(),this._allocate()}return P(e,[{key:"getValid",value:function(){return this._hash===this._getHash()}},{key:"_getHash",value:function(){var e=this._scene;return[e.gammaOutput,e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}},{key:"drawLayer",value:function(e,t,n){var r=this._scene,i=r.camera,a=t.model,s=r.canvas.gl,o=t._state,l=t._state.origin;if(this._program||(this._allocate(),!this.errors)){e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),s.uniform1i(this._uRenderPass,n),s.uniformMatrix4fv(this._uViewMatrix,!1,l?Ie(i.viewMatrix,l):i.viewMatrix),s.uniformMatrix4fv(this._uViewNormalMatrix,!1,i.viewNormalMatrix),s.uniformMatrix4fv(this._uWorldMatrix,!1,a.worldMatrix),s.uniformMatrix4fv(this._uWorldNormalMatrix,!1,a.worldNormalMatrix);var u=r._sectionPlanesState.sectionPlanes.length;if(u>0)for(var c=r._sectionPlanesState.sectionPlanes,f=t.layerIndex*u,p=a.renderFlags,A=0;A<u;A++){var d=this._uSectionPlanes[A];if(d){var v=p.sectionPlanesActivePerLayer[f+A];if(s.uniform1i(d.active,v?1:0),v){var h=c[A];if(l){var I=ge(h.dist,h.dir,l,Uc);s.uniform3fv(d.pos,I)}else s.uniform3fv(d.pos,h.pos);s.uniform3fv(d.dir,h.dir)}}}s.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,t._state.positionsDecodeMatrix),this._aPosition.bindArrayBuffer(o.positionsBuf),this._aNormal&&this._aNormal.bindArrayBuffer(o.normalsBuf),this._aColor&&this._aColor.bindArrayBuffer(o.colorsBuf),this._aMetallicRoughness&&this._aMetallicRoughness.bindArrayBuffer(o.metallicRoughnessBuf),this._aFlags&&this._aFlags.bindArrayBuffer(o.flagsBuf),this._aFlags2&&this._aFlags2.bindArrayBuffer(o.flags2Buf),this._aOffset&&this._aOffset.bindArrayBuffer(o.offsetsBuf),o.indicesBuf.bind(),s.drawElements(s.TRIANGLES,o.indicesBuf.numItems,o.indicesBuf.itemType,0),e.drawElements++}}},{key:"_allocate",value:function(){var e=this._scene,t=e.canvas.gl,n=e._lightsState;if(this._program=new ft(t,this._buildShader()),this._program.errors)this.errors=this._program.errors;else{var r=this._program;this._uRenderPass=r.getLocation("renderPass"),this._uPositionsDecodeMatrix=r.getLocation("positionsDecodeMatrix"),this._uWorldMatrix=r.getLocation("worldMatrix"),this._uWorldNormalMatrix=r.getLocation("worldNormalMatrix"),this._uViewMatrix=r.getLocation("viewMatrix"),this._uViewNormalMatrix=r.getLocation("viewNormalMatrix"),this._uProjMatrix=r.getLocation("projMatrix"),this._uGammaFactor=r.getLocation("gammaFactor"),this._uLightAmbient=r.getLocation("lightAmbient"),this._uLightColor=[],this._uLightDir=[],this._uLightPos=[],this._uLightAttenuation=[];for(var i=n.lights,a=0,s=i.length;a<s;a++)switch(i[a].type){case"dir":this._uLightColor[a]=r.getLocation("lightColor"+a),this._uLightPos[a]=null,this._uLightDir[a]=r.getLocation("lightDir"+a);break;case"point":this._uLightColor[a]=r.getLocation("lightColor"+a),this._uLightPos[a]=r.getLocation("lightPos"+a),this._uLightDir[a]=null,this._uLightAttenuation[a]=r.getLocation("lightAttenuation"+a);break;case"spot":this._uLightColor[a]=r.getLocation("lightColor"+a),this._uLightPos[a]=r.getLocation("lightPos"+a),this._uLightDir[a]=r.getLocation("lightDir"+a),this._uLightAttenuation[a]=r.getLocation("lightAttenuation"+a)}n.reflectionMaps.length>0&&(this._uReflectionMap="reflectionMap"),n.lightMaps.length>0&&(this._uLightMap="lightMap"),this._uSectionPlanes=[];for(var o=0,l=e._sectionPlanesState.sectionPlanes.length;o<l;o++)this._uSectionPlanes.push({active:r.getLocation("sectionPlaneActive"+o),pos:r.getLocation("sectionPlanePos"+o),dir:r.getLocation("sectionPlaneDir"+o)});this._aPosition=r.getAttribute("position"),this._aOffset=r.getAttribute("offset"),this._aNormal=r.getAttribute("normal"),this._aColor=r.getAttribute("color"),this._aMetallicRoughness=r.getAttribute("metallicRoughness"),this._aFlags=r.getAttribute("flags"),this._aFlags2=r.getAttribute("flags2"),this._withSAO&&(this._uOcclusionTexture="uOcclusionTexture",this._uSAOParams=r.getLocation("uSAOParams")),e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=r.getLocation("logDepthBufFC"))}}},{key:"_bindProgram",value:function(e){var t=Ze.MAX_TEXTURE_UNITS,n=this._scene,r=n.canvas.gl,i=this._program,a=n._lightsState,s=a.lights,o=n.camera.project;i.bind(),r.uniformMatrix4fv(this._uProjMatrix,!1,o.matrix),this._uLightAmbient&&r.uniform4fv(this._uLightAmbient,n._lightsState.getAmbientColorAndIntensity());for(var l=0,u=s.length;l<u;l++){var c=s[l];this._uLightColor[l]&&r.uniform4f(this._uLightColor[l],c.color[0],c.color[1],c.color[2],c.intensity),this._uLightPos[l]&&(r.uniform3fv(this._uLightPos[l],c.pos),this._uLightAttenuation[l]&&r.uniform1f(this._uLightAttenuation[l],c.attenuation)),this._uLightDir[l]&&r.uniform3fv(this._uLightDir[l],c.dir)}if(a.reflectionMaps.length>0&&a.reflectionMaps[0].texture&&this._uReflectionMap&&(i.bindTexture(this._uReflectionMap,a.reflectionMaps[0].texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%t,e.bindTexture++),a.lightMaps.length>0&&a.lightMaps[0].texture&&this._uLightMap&&(i.bindTexture(this._uLightMap,a.lightMaps[0].texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%t,e.bindTexture++),this._withSAO){var f=n.sao;if(f.possible){var p=r.drawingBufferWidth,A=r.drawingBufferHeight;Hc[0]=p,Hc[1]=A,Hc[2]=f.blendCutoff,Hc[3]=f.blendFactor,r.uniform4fv(this._uSAOParams,Hc),this._program.bindTexture(this._uOcclusionTexture,e.occlusionTexture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%t,e.bindTexture++}}if(n.logarithmicDepthBufferEnabled){var d=2/(Math.log(o.far+1)/Math.LN2);r.uniform1f(this._uLogDepthBufFC,d)}this._uGammaFactor&&r.uniform1f(this._uGammaFactor,n.gammaFactor)}},{key:"_buildShader",value:function(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState,n=e._lightsState,r=t.sectionPlanes.length>0,i=t.clippingCaps,a=[];return a.push("// Triangles dataTexture quality draw vertex shader"),e.logarithmicDepthBufferEnabled&&Ze.SUPPORTED_EXTENSIONS.EXT_frag_depth&&a.push("#extension GL_EXT_frag_depth : enable"),a.push("uniform int renderPass;"),a.push("attribute vec3 position;"),a.push("attribute vec3 normal;"),a.push("attribute vec4 color;"),a.push("attribute vec2 metallicRoughness;"),a.push("attribute vec4 flags;"),a.push("attribute vec4 flags2;"),e.entityOffsetsEnabled&&a.push("attribute vec3 offset;"),a.push("uniform mat4 worldMatrix;"),a.push("uniform mat4 worldNormalMatrix;"),a.push("uniform mat4 viewMatrix;"),a.push("uniform mat4 projMatrix;"),a.push("uniform mat4 viewNormalMatrix;"),a.push("uniform mat4 positionsDecodeMatrix;"),e.logarithmicDepthBufferEnabled&&(a.push("uniform float logDepthBufFC;"),Ze.SUPPORTED_EXTENSIONS.EXT_frag_depth&&a.push("varying float vFragDepth;"),a.push("bool isPerspectiveMatrix(mat4 m) {"),a.push(" return (m[2][3] == - 1.0);"),a.push("}"),a.push("varying float isPerspective;")),a.push("vec3 octDecode(vec2 oct) {"),a.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),a.push(" if (v.z < 0.0) {"),a.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),a.push(" }"),a.push(" return normalize(v);"),a.push("}"),a.push("varying vec4 vViewPosition;"),a.push("varying vec3 vViewNormal;"),a.push("varying vec4 vColor;"),a.push("varying vec2 vMetallicRoughness;"),n.lightMaps.length>0&&a.push("varying vec3 vWorldNormal;"),r&&(a.push("varying vec4 vWorldPosition;"),a.push("varying vec4 vFlags2;"),i&&a.push("varying vec4 vClipPosition;")),a.push("void main(void) {"),a.push("if (int(flags.x) != renderPass) {"),a.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),a.push("} else {"),a.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&a.push("worldPosition.xyz = worldPosition.xyz + offset;"),a.push("vec4 viewPosition = viewMatrix * worldPosition; "),a.push("vec4 worldNormal = worldNormalMatrix * vec4(octDecode(normal.xy), 0.0); "),a.push("vec3 viewNormal = normalize((viewNormalMatrix * worldNormal).xyz);"),a.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(a.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),Ze.SUPPORTED_EXTENSIONS.EXT_frag_depth?a.push("vFragDepth = 1.0 + clipPos.w;"):(a.push("clipPos.z = log2( max( 1e-6, clipPos.w + 1.0 ) ) * logDepthBufFC - 1.0;"),a.push("clipPos.z *= clipPos.w;"))),r&&(a.push("vWorldPosition = worldPosition;"),a.push("vFlags2 = flags2;"),i&&a.push("vClipPosition = clipPos;")),a.push("vViewPosition = viewPosition;"),a.push("vViewNormal = viewNormal;"),a.push("vColor = color;"),a.push("vMetallicRoughness = metallicRoughness;"),n.lightMaps.length>0&&a.push("vWorldNormal = worldNormal.xyz;"),a.push("gl_Position = clipPos;"),a.push("}"),a.push("}"),a}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e.gammaOutput,n=e._sectionPlanesState,r=e._lightsState,i=n.sectionPlanes.length>0,a=n.clippingCaps,s=[];s.push("// Triangles dataTexture quality draw fragment shader"),e.logarithmicDepthBufferEnabled&&Ze.SUPPORTED_EXTENSIONS.EXT_frag_depth&&s.push("#extension GL_EXT_frag_depth : enable"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&Ze.SUPPORTED_EXTENSIONS.EXT_frag_depth&&(s.push("varying float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("varying float vFragDepth;")),s.push("varying vec4 vViewPosition;"),s.push("varying vec3 vViewNormal;"),s.push("varying vec4 vColor;"),s.push("varying vec2 vMetallicRoughness;"),r.lightMaps.length>0&&s.push("varying vec3 vWorldNormal;"),s.push("uniform mat4 viewMatrix;"),r.reflectionMaps.length>0&&s.push("uniform samplerCube reflectionMap;"),r.lightMaps.length>0&&s.push("uniform samplerCube lightMap;"),s.push("uniform vec4 lightAmbient;");for(var o=0,l=r.lights.length;o<l;o++){var u=r.lights[o];"ambient"!==u.type&&(s.push("uniform vec4 lightColor"+o+";"),"dir"===u.type&&s.push("uniform vec3 lightDir"+o+";"),"point"===u.type&&s.push("uniform vec3 lightPos"+o+";"),"spot"===u.type&&(s.push("uniform vec3 lightPos"+o+";"),s.push("uniform vec3 lightDir"+o+";")))}if(this._withSAO&&(s.push("uniform sampler2D uOcclusionTexture;"),s.push("uniform vec4 uSAOParams;"),s.push("const float packUpscale = 256. / 255.;"),s.push("const float unpackDownScale = 255. / 256.;"),s.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),s.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),s.push("float unpackRGBAToDepth( const in vec4 v ) {"),s.push(" return dot( v, unPackFactors );"),s.push("}")),s.push("uniform float gammaFactor;"),s.push("vec4 linearToLinear( in vec4 value ) {"),s.push(" return value;"),s.push("}"),s.push("vec4 sRGBToLinear( in vec4 value ) {"),s.push(" return vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.w );"),s.push("}"),s.push("vec4 gammaToLinear( in vec4 value) {"),s.push(" return vec4( pow( value.xyz, vec3( gammaFactor ) ), value.w );"),s.push("}"),t&&(s.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),s.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),s.push("}")),i){s.push("varying vec4 vWorldPosition;"),s.push("varying vec4 vFlags2;"),a&&s.push("varying vec4 vClipPosition;");for(var c=0,f=n.sectionPlanes.length;c<f;c++)s.push("uniform bool sectionPlaneActive"+c+";"),s.push("uniform vec3 sectionPlanePos"+c+";"),s.push("uniform vec3 sectionPlaneDir"+c+";")}if(s.push("#define PI 3.14159265359"),s.push("#define RECIPROCAL_PI 0.31830988618"),s.push("#define RECIPROCAL_PI2 0.15915494"),s.push("#define EPSILON 1e-6"),s.push("#define saturate(a) clamp( a, 0.0, 1.0 )"),s.push("vec3 inverseTransformDirection(in vec3 dir, in mat4 matrix) {"),s.push(" return normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );"),s.push("}"),s.push("struct IncidentLight {"),s.push(" vec3 color;"),s.push(" vec3 direction;"),s.push("};"),s.push("struct ReflectedLight {"),s.push(" vec3 diffuse;"),s.push(" vec3 specular;"),s.push("};"),s.push("struct Geometry {"),s.push(" vec3 position;"),s.push(" vec3 viewNormal;"),s.push(" vec3 worldNormal;"),s.push(" vec3 viewEyeDir;"),s.push("};"),s.push("struct Material {"),s.push(" vec3 diffuseColor;"),s.push(" float specularRoughness;"),s.push(" vec3 specularColor;"),s.push(" float shine;"),s.push("};"),s.push("float GGXRoughnessToBlinnExponent(const in float ggxRoughness) {"),s.push(" float r = ggxRoughness + 0.0001;"),s.push(" return (2.0 / (r * r) - 2.0);"),s.push("}"),s.push("float getSpecularMIPLevel(const in float blinnShininessExponent, const in int maxMIPLevel) {"),s.push(" float maxMIPLevelScalar = float( maxMIPLevel );"),s.push(" float desiredMIPLevel = maxMIPLevelScalar - 0.79248 - 0.5 * log2( ( blinnShininessExponent * blinnShininessExponent ) + 1.0 );"),s.push(" return clamp( desiredMIPLevel, 0.0, maxMIPLevelScalar );"),s.push("}"),r.reflectionMaps.length>0&&(s.push("vec3 getLightProbeIndirectRadiance(const in vec3 reflectVec, const in float blinnShininessExponent, const in int maxMIPLevel) {"),s.push(" float mipLevel = 0.5 * getSpecularMIPLevel(blinnShininessExponent, maxMIPLevel);"),s.push(" vec3 envMapColor = "+Gc[r.reflectionMaps[0].encoding]+"(textureCube(reflectionMap, reflectVec, mipLevel)).rgb;"),s.push(" return envMapColor;"),s.push("}")),s.push("vec3 F_Schlick(const in vec3 specularColor, const in float dotLH) {"),s.push(" float fresnel = exp2( ( -5.55473 * dotLH - 6.98316 ) * dotLH );"),s.push(" return ( 1.0 - specularColor ) * fresnel + specularColor;"),s.push("}"),s.push("float G_GGX_Smith(const in float alpha, const in float dotNL, const in float dotNV) {"),s.push(" float a2 = ( alpha * alpha );"),s.push(" float gl = dotNL + sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),s.push(" float gv = dotNV + sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),s.push(" return 1.0 / ( gl * gv );"),s.push("}"),s.push("float G_GGX_SmithCorrelated(const in float alpha, const in float dotNL, const in float dotNV) {"),s.push(" float a2 = ( alpha * alpha );"),s.push(" float gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),s.push(" float gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),s.push(" return 0.5 / max( gv + gl, EPSILON );"),s.push("}"),s.push("float D_GGX(const in float alpha, const in float dotNH) {"),s.push(" float a2 = ( alpha * alpha );"),s.push(" float denom = ( dotNH * dotNH) * ( a2 - 1.0 ) + 1.0;"),s.push(" return RECIPROCAL_PI * a2 / ( denom * denom);"),s.push("}"),s.push("vec3 BRDF_Specular_GGX(const in IncidentLight incidentLight, const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),s.push(" float alpha = ( roughness * roughness );"),s.push(" vec3 halfDir = normalize( incidentLight.direction + geometry.viewEyeDir );"),s.push(" float dotNL = saturate( dot( geometry.viewNormal, incidentLight.direction ) );"),s.push(" float dotNV = saturate( dot( geometry.viewNormal, geometry.viewEyeDir ) );"),s.push(" float dotNH = saturate( dot( geometry.viewNormal, halfDir ) );"),s.push(" float dotLH = saturate( dot( incidentLight.direction, halfDir ) );"),s.push(" vec3 F = F_Schlick( specularColor, dotLH );"),s.push(" float G = G_GGX_SmithCorrelated( alpha, dotNL, dotNV );"),s.push(" float D = D_GGX( alpha, dotNH );"),s.push(" return F * (G * D);"),s.push("}"),s.push("vec3 BRDF_Specular_GGX_Environment(const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),s.push(" float dotNV = saturate(dot(geometry.viewNormal, geometry.viewEyeDir));"),s.push(" const vec4 c0 = vec4( -1, -0.0275, -0.572, 0.022);"),s.push(" const vec4 c1 = vec4( 1, 0.0425, 1.04, -0.04);"),s.push(" vec4 r = roughness * c0 + c1;"),s.push(" float a004 = min(r.x * r.x, exp2(-9.28 * dotNV)) * r.x + r.y;"),s.push(" vec2 AB = vec2(-1.04, 1.04) * a004 + r.zw;"),s.push(" return specularColor * AB.x + AB.y;"),s.push("}"),(r.lightMaps.length>0||r.reflectionMaps.length>0)&&(s.push("void computePBRLightMapping(const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),r.lightMaps.length>0&&(s.push(" vec3 irradiance = "+Gc[r.lightMaps[0].encoding]+"(textureCube(lightMap, geometry.worldNormal)).rgb;"),s.push(" irradiance *= PI;"),s.push(" vec3 diffuseBRDFContrib = (RECIPROCAL_PI * material.diffuseColor);"),s.push(" reflectedLight.diffuse += irradiance * diffuseBRDFContrib;")),r.reflectionMaps.length>0&&(s.push(" vec3 reflectVec = reflect(geometry.viewEyeDir, geometry.viewNormal);"),s.push(" reflectVec = inverseTransformDirection(reflectVec, viewMatrix);"),s.push(" float blinnExpFromRoughness = GGXRoughnessToBlinnExponent(material.specularRoughness);"),s.push(" vec3 radiance = getLightProbeIndirectRadiance(reflectVec, blinnExpFromRoughness, 8);"),s.push(" vec3 specularBRDFContrib = BRDF_Specular_GGX_Environment(geometry, material.specularColor, material.specularRoughness);"),s.push(" reflectedLight.specular += radiance * specularBRDFContrib;")),s.push("}")),s.push("void computePBRLighting(const in IncidentLight incidentLight, const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),s.push(" float dotNL = saturate(dot(geometry.viewNormal, incidentLight.direction));"),s.push(" vec3 irradiance = dotNL * incidentLight.color * PI;"),s.push(" reflectedLight.diffuse += irradiance * (RECIPROCAL_PI * material.diffuseColor);"),s.push(" reflectedLight.specular += irradiance * BRDF_Specular_GGX(incidentLight, geometry, material.specularColor, material.specularRoughness);"),s.push("}"),s.push("void main(void) {"),i){s.push(" bool clippable = (float(vFlags2.x) > 0.0);"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var p=0,A=n.sectionPlanes.length;p<A;p++)s.push("if (sectionPlaneActive"+p+") {"),s.push(" dist += clamp(dot(-sectionPlaneDir"+p+".xyz, vWorldPosition.xyz - sectionPlanePos"+p+".xyz), 0.0, 1000.0);"),s.push("}");a?(s.push(" if (dist > (0.002 * vClipPosition.w)) {"),s.push(" discard;"),s.push(" }"),s.push(" if (dist > 0.0) { "),s.push(" gl_FragColor=vec4(1.0, 0.0, 0.0, 1.0);"),e.logarithmicDepthBufferEnabled&&Ze.SUPPORTED_EXTENSIONS.EXT_frag_depth&&s.push(" gl_FragDepthEXT = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" return;"),s.push("}")):(s.push(" if (dist > 0.0) { "),s.push(" discard;"),s.push(" }")),s.push("}")}s.push("IncidentLight light;"),s.push("Material material;"),s.push("Geometry geometry;"),s.push("ReflectedLight reflectedLight = ReflectedLight(vec3(0.0,0.0,0.0), vec3(0.0,0.0,0.0));"),s.push("vec3 rgb = (vec3(float(vColor.r) / 255.0, float(vColor.g) / 255.0, float(vColor.b) / 255.0));"),s.push("float alpha = float(vColor.a) / 255.0;"),s.push("vec3 diffuseColor = rgb;"),s.push("float specularF0 = 1.0;"),s.push("float metallic = float(vMetallicRoughness.r) / 255.0;"),s.push("float roughness = float(vMetallicRoughness.g) / 255.0;"),s.push("float dielectricSpecular = 0.16 * specularF0 * specularF0;"),s.push("material.diffuseColor = diffuseColor * (1.0 - dielectricSpecular) * (1.0 - metallic);"),s.push("material.specularRoughness = clamp(roughness, 0.04, 1.0);"),s.push("material.specularColor = mix(vec3(dielectricSpecular), diffuseColor, metallic);"),s.push("geometry.position = vViewPosition.xyz;"),s.push("geometry.viewNormal = -normalize(vViewNormal);"),s.push("geometry.viewEyeDir = normalize(vViewPosition.xyz);"),r.lightMaps.length>0&&s.push("geometry.worldNormal = normalize(vWorldNormal);"),(r.lightMaps.length>0||r.reflectionMaps.length>0)&&s.push("computePBRLightMapping(geometry, material, reflectedLight);");for(var d=0,v=r.lights.length;d<v;d++){var h=r.lights[d];if("ambient"!==h.type){if("dir"===h.type)"view"===h.space?s.push("light.direction = normalize(lightDir"+d+");"):s.push("light.direction = normalize((viewMatrix * vec4(lightDir"+d+", 0.0)).xyz);");else if("point"===h.type)"view"===h.space?s.push("light.direction = normalize(lightPos"+d+" - vViewPosition.xyz);"):s.push("light.direction = normalize((viewMatrix * vec4(lightPos"+d+", 0.0)).xyz);");else{if("spot"!==h.type)continue;"view"===h.space?s.push("light.direction = normalize(lightDir"+d+");"):s.push("light.direction = normalize((viewMatrix * vec4(lightDir"+d+", 0.0)).xyz);")}s.push("light.color = lightColor"+d+".rgb * lightColor"+d+".a;"),s.push("computePBRLighting(light, geometry, material, reflectedLight);")}}return s.push("vec3 outgoingLight = (lightAmbient.rgb * lightAmbient.a * rgb) + (reflectedLight.diffuse) + (reflectedLight.specular);"),s.push("vec4 fragColor;"),this._withSAO?(s.push(" float viewportWidth = uSAOParams[0];"),s.push(" float viewportHeight = uSAOParams[1];"),s.push(" float blendCutoff = uSAOParams[2];"),s.push(" float blendFactor = uSAOParams[3];"),s.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),s.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBAToDepth(texture2D(uOcclusionTexture, uv))) * blendFactor;"),s.push(" fragColor = vec4(outgoingLight.rgb * ambient, alpha);")):s.push(" fragColor = vec4(outgoingLight.rgb, alpha);"),t&&s.push("fragColor = linearToGamma(fragColor, gammaFactor);"),s.push("gl_FragColor = fragColor;"),e.logarithmicDepthBufferEnabled&&Ze.SUPPORTED_EXTENSIONS.EXT_frag_depth&&s.push(" gl_FragDepthEXT = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("}"),s}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),e}(),Vc=Z.vec3(),jc=function(){function e(t){b(this,e),this._scene=t,this._hash=this._getHash(),this._allocate()}return P(e,[{key:"getValid",value:function(){return this._hash===this._getHash()}},{key:"_getHash",value:function(){return this._scene._sectionPlanesState.getHash()}},{key:"drawLayer",value:function(e,t,n){var r=t.model,i=r.scene,a=i.camera,s=i.canvas.gl,o=t._state,l=t._state.origin;this._program||this._allocate(t),e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram()),this._program.bindTexture(this._uTexturePerObjectIdPositionsDecodeMatrix,{bind:function(e){return s.activeTexture(s["TEXTURE"+e]),s.bindTexture(s.TEXTURE_2D,o.texturePerObjectIdPositionsDecodeMatrix),!0},unbind:function(e){s.activeTexture(s["TEXTURE"+e]),s.bindTexture(s.TEXTURE_2D,null)}},1),this._program.bindTexture(this._uTexturePerVertexIdCoordinates,{bind:function(e){return s.activeTexture(s["TEXTURE"+e]),s.bindTexture(s.TEXTURE_2D,o.texturePerVertexIdCoordinates),!0},unbind:function(e){s.activeTexture(s["TEXTURE"+e]),s.bindTexture(s.TEXTURE_2D,null)}},2),this._program.bindTexture(this._uTexturePerObjectIdColorsAndFlags,{bind:function(e){return s.activeTexture(s["TEXTURE"+e]),s.bindTexture(s.TEXTURE_2D,o.texturePerObjectIdColorsAndFlags),!0},unbind:function(e){s.activeTexture(s["TEXTURE"+e]),s.bindTexture(s.TEXTURE_2D,null)}},3),s.uniform1i(this._uRenderPass,n),s.uniform1i(this._uPickInvisible,e.pickInvisible),s.uniformMatrix4fv(this._uWorldMatrix,!1,r.worldMatrix);var u=e.pickViewMatrix||a.viewMatrix,c=l?Ie(u,l):u;if(s.uniformMatrix4fv(this._uViewMatrix,!1,c),s.uniformMatrix4fv(this._uProjMatrix,!1,e.pickProjMatrix),i.logarithmicDepthBufferEnabled){var f=2/(Math.log(a.project.far+1)/Math.LN2);s.uniform1f(this._uLogDepthBufFC,f)}var p=i._sectionPlanesState.sectionPlanes.length;if(p>0)for(var A=i._sectionPlanesState.sectionPlanes,d=t.layerIndex*p,v=r.renderFlags,h=0;h<p;h++){var I=this._uSectionPlanes[h],y=v.sectionPlanesActivePerLayer[d+h];if(s.uniform1i(I.active,y?1:0),y){var m=A[h];if(l){var w=ge(m.dist,m.dir,l,Vc);s.uniform3fv(I.pos,w)}else s.uniform3fv(I.pos,m.pos);s.uniform3fv(I.dir,m.dir)}}o.numIndices8Bits>0&&(this._program.bindTexture(this._uTexturePerPolygonIdPortionIds,{bind:function(e){return s.activeTexture(s["TEXTURE"+e]),s.bindTexture(s.TEXTURE_2D,o.texturePerPolygonIdPortionIds8Bits),!0},unbind:function(e){s.activeTexture(s["TEXTURE"+e]),s.bindTexture(s.TEXTURE_2D,null)}},4),this._program.bindTexture(this._uTexturePerPolygonIdIndices,{bind:function(e){return s.activeTexture(s["TEXTURE"+e]),s.bindTexture(s.TEXTURE_2D,o.texturePerPolygonIdIndices8Bits),!0},unbind:function(e){s.activeTexture(s["TEXTURE"+e]),s.bindTexture(s.TEXTURE_2D,null)}},5),s.drawArrays(s.TRIANGLES,0,o.numIndices8Bits)),o.numIndices16Bits>0&&(this._program.bindTexture(this._uTexturePerPolygonIdPortionIds,{bind:function(e){return s.activeTexture(s["TEXTURE"+e]),s.bindTexture(s.TEXTURE_2D,o.texturePerPolygonIdPortionIds16Bits),!0},unbind:function(e){s.activeTexture(s["TEXTURE"+e]),s.bindTexture(s.TEXTURE_2D,null)}},4),this._program.bindTexture(this._uTexturePerPolygonIdIndices,{bind:function(e){return s.activeTexture(s["TEXTURE"+e]),s.bindTexture(s.TEXTURE_2D,o.texturePerPolygonIdIndices16Bits),!0},unbind:function(e){s.activeTexture(s["TEXTURE"+e]),s.bindTexture(s.TEXTURE_2D,null)}},5),s.drawArrays(s.TRIANGLES,0,o.numIndices16Bits)),o.numIndices32Bits>0&&(this._program.bindTexture(this._uTexturePerPolygonIdPortionIds,{bind:function(e){return s.activeTexture(s["TEXTURE"+e]),s.bindTexture(s.TEXTURE_2D,o.texturePerPolygonIdPortionIds32Bits),!0},unbind:function(e){s.activeTexture(s["TEXTURE"+e]),s.bindTexture(s.TEXTURE_2D,null)}},4),this._program.bindTexture(this._uTexturePerPolygonIdIndices,{bind:function(e){return s.activeTexture(s["TEXTURE"+e]),s.bindTexture(s.TEXTURE_2D,o.texturePerPolygonIdIndices32Bits),!0},unbind:function(e){s.activeTexture(s["TEXTURE"+e]),s.bindTexture(s.TEXTURE_2D,null)}},5),s.drawArrays(s.TRIANGLES,0,o.numIndices32Bits)),e.drawElements++}},{key:"_allocate",value:function(){var e=this._scene,t=e.canvas.gl;if(this._program=new ft(t,this._buildShader()),this._program.errors)this.errors=this._program.errors;else{var n=this._program;this._uRenderPass=n.getLocation("renderPass"),this._uPickInvisible=n.getLocation("pickInvisible"),this._uPositionsDecodeMatrix=n.getLocation("positionsDecodeMatrix"),this._uWorldMatrix=n.getLocation("worldMatrix"),this._uViewMatrix=n.getLocation("viewMatrix"),this._uProjMatrix=n.getLocation("projMatrix"),this._uSectionPlanes=[];for(var r=0,i=e._sectionPlanesState.sectionPlanes.length;r<i;r++)this._uSectionPlanes.push({active:n.getLocation("sectionPlaneActive"+r),pos:n.getLocation("sectionPlanePos"+r),dir:n.getLocation("sectionPlaneDir"+r)});this._aPackedVertexId=n.getAttribute("packedVertexId"),e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=n.getLocation("logDepthBufFC")),this._uTexturePerObjectIdPositionsDecodeMatrix="uTexturePerObjectIdPositionsDecodeMatrix",this._uTexturePerObjectIdColorsAndFlags="uTexturePerObjectIdColorsAndFlags",this._uTexturePerVertexIdCoordinates="uTexturePerVertexIdCoordinates",this._uTexturePerPolygonIdNormals="uTexturePerPolygonIdNormals",this._uTexturePerPolygonIdIndices="uTexturePerPolygonIdIndices",this._uTexturePerPolygonIdPortionIds="uTexturePerPolygonIdPortionIds"}}},{key:"_bindProgram",value:function(){this._program.bind()}},{key:"_buildShader",value:function(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,n=[];return n.push("#version 300 es"),n.push("// Triangles dataTexture pick flat normals vertex shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("precision highp usampler2D;"),n.push("precision highp isampler2D;"),n.push("precision highp sampler2D;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("precision mediump usampler2D;"),n.push("precision mediump isampler2D;"),n.push("precision mediump sampler2D;"),n.push("#endif"),n.push("uniform int renderPass;"),n.push("in uvec3 packedVertexId;"),e.entityOffsetsEnabled&&n.push("in vec3 offset;"),n.push("uniform bool pickInvisible;"),n.push("uniform mat4 worldMatrix;"),n.push("uniform mat4 viewMatrix;"),n.push("uniform mat4 projMatrix;"),n.push("uniform sampler2D uTexturePerObjectIdPositionsDecodeMatrix;"),n.push("uniform usampler2D uTexturePerObjectIdColorsAndFlags;"),n.push("uniform usampler2D uTexturePerVertexIdCoordinates;"),n.push("uniform usampler2D uTexturePerPolygonIdIndices;"),n.push("uniform isampler2D uTexturePerPolygonIdNormals;"),n.push("uniform usampler2D uTexturePerPolygonIdPortionIds;"),e.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("out float vFragDepth;"),n.push("bool isPerspectiveMatrix(mat4 m) {"),n.push(" return (m[2][3] == - 1.0);"),n.push("}"),n.push("out float isPerspective;")),n.push("out vec4 vWorldPosition;"),t&&n.push("out int vFlags2;"),n.push("void main(void) {"),n.push("int polygonIndex = gl_VertexID / 3;"),n.push("int h_normal_index = polygonIndex & 4095;"),n.push("int v_normal_index = polygonIndex >> 12;"),n.push("int h_packed_object_id_index = ((polygonIndex >> 3) / 2) & 4095;"),n.push("int v_packed_object_id_index = ((polygonIndex >> 3) / 2) >> 12;"),n.push("ivec3 packedObjectId = ivec3(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).rgb);"),n.push("int objectIndex;"),n.push("if (((polygonIndex >> 3) % 2) == 0) {"),n.push(" objectIndex = (packedObjectId.r << 4) + (packedObjectId.g >> 4);"),n.push("} else {"),n.push(" objectIndex = ((packedObjectId.g & 15) << 8) + packedObjectId.b;"),n.push("}"),n.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),n.push("ivec4 packedVertexBase = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),n.push("int h_index = polygonIndex & 4095;"),n.push("int v_index = polygonIndex >> 12;"),n.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),n.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),n.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),n.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),n.push("mat4 positionsDecodeMatrix = mat4 (texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),n.push("uvec4 flags = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),n.push("uvec4 flags2 = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),n.push("vec3 position1 = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),n.push("vec3 position2 = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),n.push("vec3 position3 = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),n.push("vec3 normal = normalize(cross(position3 - position1, position2 - position1));"),n.push("int vertexNumber = gl_VertexID % 3;"),n.push("vec3 position;"),n.push("if (vertexNumber == 0) position = position1;"),n.push("else if (vertexNumber == 1) position = position2;"),n.push("else position = position3;"),n.push("if (int(flags.w) != renderPass) {"),n.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),n.push(" } else {"),n.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&n.push(" worldPosition.xyz = worldPosition.xyz + offset;"),n.push(" vec4 viewPosition = viewMatrix * worldPosition; "),n.push(" vWorldPosition = worldPosition;"),t&&n.push(" vFlags2 = flags2.r;"),n.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(n.push("vFragDepth = 1.0 + clipPos.w;"),n.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),n.push("gl_Position = clipPos;"),n.push(" }"),n.push("}"),n}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,n=t.sectionPlanes.length>0,r=[];if(r.push("#version 300 es"),r.push("// Triangles dataTexture pick flat normals fragment shader"),r.push("#extension GL_OES_standard_derivatives : enable"),e.logarithmicDepthBufferEnabled&&r.push("#extension GL_EXT_frag_depth : enable"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),e.logarithmicDepthBufferEnabled&&(r.push("in float isPerspective;"),r.push("uniform float logDepthBufFC;"),r.push("in float vFragDepth;")),r.push("in vec4 vWorldPosition;"),n){r.push("in int vFlags2;");for(var i=0;i<t.sectionPlanes.length;i++)r.push("uniform bool sectionPlaneActive"+i+";"),r.push("uniform vec3 sectionPlanePos"+i+";"),r.push("uniform vec3 sectionPlaneDir"+i+";")}if(r.push("out vec4 outNormal;"),r.push("void main(void) {"),n){r.push(" bool clippable = vFlags2 > 0;"),r.push(" if (clippable) {"),r.push(" float dist = 0.0;");for(i=0;i<t.sectionPlanes.length;i++)r.push(" if (sectionPlaneActive"+i+") {"),r.push(" dist += clamp(dot(-sectionPlaneDir"+i+".xyz, vWorldPosition.xyz - sectionPlanePos"+i+".xyz), 0.0, 1000.0);"),r.push(" }");r.push(" if (dist > 0.0) { discard; }"),r.push(" }")}return e.logarithmicDepthBufferEnabled&&r.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),r.push(" vec3 xTangent = dFdx( vWorldPosition.xyz );"),r.push(" vec3 yTangent = dFdy( vWorldPosition.xyz );"),r.push(" vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"),r.push(" outNormal = vec4((worldNormal * 0.5) + 0.5, 1.0);"),r.push("}"),r}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),e}(),Qc=function(){function e(t){b(this,e),this._scene=t}return P(e,[{key:"_compile",value:function(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._colorRendererWithSAO&&!this._colorRendererWithSAO.getValid()&&(this._colorRendererWithSAO.destroy(),this._colorRendererWithSAO=null),this._flatColorRenderer&&!this._flatColorRenderer.getValid()&&(this._flatColorRenderer.destroy(),this._flatColorRenderer=null),this._flatColorRendererWithSAO&&!this._flatColorRendererWithSAO.getValid()&&(this._flatColorRendererWithSAO.destroy(),this._flatColorRendererWithSAO=null),this._colorQualityRenderer&&!this._colorQualityRenderer.getValid()&&(this._colorQualityRenderer.destroy(),this._colorQualityRenderer=null),this._colorQualityRendererWithSAO&&!this._colorQualityRendererWithSAO.getValid()&&(this._colorQualityRendererWithSAO.destroy(),this._colorQualityRendererWithSAO=null),this._depthRenderer&&!this._depthRenderer.getValid()&&(this._depthRenderer.destroy(),this._depthRenderer=null),this._normalsRenderer&&!this._normalsRenderer.getValid()&&(this._normalsRenderer.destroy(),this._normalsRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null),this._edgesRenderer&&!this._edgesRenderer.getValid()&&(this._edgesRenderer.destroy(),this._edgesRenderer=null),this._edgesColorRenderer&&!this._edgesColorRenderer.getValid()&&(this._edgesColorRenderer.destroy(),this._edgesColorRenderer=null),this._pickMeshRenderer&&!this._pickMeshRenderer.getValid()&&(this._pickMeshRenderer.destroy(),this._pickMeshRenderer=null),this._pickDepthRenderer&&!this._pickDepthRenderer.getValid()&&(this._pickDepthRenderer.destroy(),this._pickDepthRenderer=null),this._vertexDepthRenderer&&!this._vertexDepthRenderer.getValid()&&(this._vertexDepthRenderer.destroy(),this._vertexDepthRenderer=null),this._snapDepthBufInitRenderer&&!this._snapDepthBufInitRenderer.getValid()&&(this._snapDepthBufInitRenderer.destroy(),this._snapDepthBufInitRenderer=null),this._pickNormalsRenderer&&!1===this._pickNormalsRenderer.getValid()&&(this._pickNormalsRenderer.destroy(),this._pickNormalsRenderer=null),this._pickNormalsFlatRenderer&&!1===this._pickNormalsFlatRenderer.getValid()&&(this._pickNormalsFlatRenderer.destroy(),this._pickNormalsFlatRenderer=null),this._occlusionRenderer&&!1===this._occlusionRenderer.getValid()&&(this._occlusionRenderer.destroy(),this._occlusionRenderer=null),this._shadowRenderer&&!this._shadowRenderer.getValid()&&(this._shadowRenderer.destroy(),this._shadowRenderer=null)}},{key:"colorRenderer",get:function(){return this._colorRenderer||(this._colorRenderer=new Ac(this._scene,!1)),this._colorRenderer}},{key:"colorRendererWithSAO",get:function(){return this._colorRendererWithSAO||(this._colorRendererWithSAO=new Ac(this._scene,!0)),this._colorRendererWithSAO}},{key:"colorQualityRenderer",get:function(){return this._colorQualityRenderer||(this._colorQualityRenderer=new kc(this._scene,!1)),this._colorQualityRenderer}},{key:"colorQualityRendererWithSAO",get:function(){return this._colorQualityRendererWithSAO||(this._colorQualityRendererWithSAO=new kc(this._scene,!0)),this._colorQualityRendererWithSAO}},{key:"silhouetteRenderer",get:function(){return this._silhouetteRenderer||(this._silhouetteRenderer=new hc(this._scene)),this._silhouetteRenderer}},{key:"depthRenderer",get:function(){return this._depthRenderer||(this._depthRenderer=new Lc(this._scene)),this._depthRenderer}},{key:"normalsRenderer",get:function(){return this._normalsRenderer||(this._normalsRenderer=new Mc(this._scene)),this._normalsRenderer}},{key:"edgesRenderer",get:function(){return this._edgesRenderer||(this._edgesRenderer=new mc(this._scene)),this._edgesRenderer}},{key:"edgesColorRenderer",get:function(){return this._edgesColorRenderer||(this._edgesColorRenderer=new gc(this._scene)),this._edgesColorRenderer}},{key:"pickMeshRenderer",get:function(){return this._pickMeshRenderer||(this._pickMeshRenderer=new Ec(this._scene)),this._pickMeshRenderer}},{key:"pickNormalsRenderer",get:function(){return this._pickNormalsRenderer||(this._pickNormalsRenderer=new Oc(this._scene)),this._pickNormalsRenderer}},{key:"pickNormalsFlatRenderer",get:function(){return this._pickNormalsFlatRenderer||(this._pickNormalsFlatRenderer=new jc(this._scene)),this._pickNormalsFlatRenderer}},{key:"pickDepthRenderer",get:function(){return this._pickDepthRenderer||(this._pickDepthRenderer=new Dc(this._scene)),this._pickDepthRenderer}},{key:"vertexDepthRenderer",get:function(){return this._vertexDepthRenderer||(this._vertexDepthRenderer=new Rc(this._scene)),this._vertexDepthRenderer}},{key:"snapDepthBufInitRenderer",get:function(){return this._snapDepthBufInitRenderer||(this._snapDepthBufInitRenderer=new _c(this._scene)),this._snapDepthBufInitRenderer}},{key:"occlusionRenderer",get:function(){return this._occlusionRenderer||(this._occlusionRenderer=new Sc(this._scene)),this._occlusionRenderer}},{key:"shadowRenderer",get:function(){return this._shadowRenderer||(this._shadowRenderer=new Fc(this._scene)),this._shadowRenderer}},{key:"_destroy",value:function(){this._colorRenderer&&this._colorRenderer.destroy(),this._colorRendererWithSAO&&this._colorRendererWithSAO.destroy(),this._flatColorRenderer&&this._flatColorRenderer.destroy(),this._flatColorRendererWithSAO&&this._flatColorRendererWithSAO.destroy(),this._colorQualityRenderer&&this._colorQualityRenderer.destroy(),this._colorQualityRendererWithSAO&&this._colorQualityRendererWithSAO.destroy(),this._depthRenderer&&this._depthRenderer.destroy(),this._normalsRenderer&&this._normalsRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._edgesRenderer&&this._edgesRenderer.destroy(),this._edgesColorRenderer&&this._edgesColorRenderer.destroy(),this._pickMeshRenderer&&this._pickMeshRenderer.destroy(),this._pickDepthRenderer&&this._pickDepthRenderer.destroy(),this._vertexDepthRenderer&&this._vertexDepthRenderer.destroy(),this._snapDepthBufInitRenderer&&this._snapDepthBufInitRenderer.destroy(),this._pickNormalsRenderer&&this._pickNormalsRenderer.destroy(),this._pickNormalsFlatRenderer&&this._pickNormalsFlatRenderer.destroy(),this._occlusionRenderer&&this._occlusionRenderer.destroy(),this._shadowRenderer&&this._shadowRenderer.destroy()}}]),e}(),Wc={};var zc=P((function e(){b(this,e),this.positionsCompressed=[],this.metallicRoughness=[],this.indices8Bits=[],this.indices16Bits=[],this.indices32Bits=[],this.edgeIndices8Bits=[],this.edgeIndices16Bits=[],this.edgeIndices32Bits=[],this.perObjectColors=[],this.perObjectPickColors=[],this.perObjectSolid=[],this.perObjectOffsets=[],this.perObjectPositionsDecodeMatrices=[],this.perObjectInstancePositioningMatrices=[],this.perObjectVertexBases=[],this.perObjectIndexBaseOffsets=[],this.perObjectEdgeIndexBaseOffsets=[],this.perTriangleNumberPortionId8Bits=[],this.perTriangleNumberPortionId16Bits=[],this.perTriangleNumberPortionId32Bits=[],this.perEdgeNumberPortionId8Bits=[],this.perEdgeNumberPortionId16Bits=[],this.perEdgeNumberPortionId32Bits=[]})),Kc=function(){function e(){b(this,e),this.texturePerObjectIdColorsAndFlags=null,this.texturePerObjectIdOffsets=null,this.texturePerObjectIdPositionsDecodeMatrix=null,this.texturePerVertexIdCoordinates=null,this.texturePerPolygonIdPortionIds8Bits=null,this.texturePerPolygonIdPortionIds16Bits=null,this.texturePerPolygonIdPortionIds32Bits=null,this.texturePerEdgeIdPortionIds8Bits=null,this.texturePerEdgeIdPortionIds16Bits=null,this.texturePerEdgeIdPortionIds32Bits=null,this.texturePerPolygonIdIndices8Bits=null,this.texturePerPolygonIdIndices16Bits=null,this.texturePerPolygonIdIndices32Bits=null,this.texturePerPolygonIdEdgeIndices8Bits=null,this.texturePerPolygonIdEdgeIndices16Bits=null,this.texturePerPolygonIdEdgeIndices32Bits=null,this.textureCameraMatrices=null,this.texturePickCameraMatrices=null,this.textureModelMatrices=null}return P(e,[{key:"finalize",value:function(){this.indicesPerBitnessTextures={8:this.texturePerPolygonIdIndices8Bits,16:this.texturePerPolygonIdIndices16Bits,32:this.texturePerPolygonIdIndices32Bits},this.indicesPortionIdsPerBitnessTextures={8:this.texturePerPolygonIdPortionIds8Bits,16:this.texturePerPolygonIdPortionIds16Bits,32:this.texturePerPolygonIdPortionIds32Bits},this.edgeIndicesPerBitnessTextures={8:this.texturePerPolygonIdEdgeIndices8Bits,16:this.texturePerPolygonIdEdgeIndices16Bits,32:this.texturePerPolygonIdEdgeIndices32Bits},this.edgeIndicesPortionIdsPerBitnessTextures={8:this.texturePerEdgeIdPortionIds8Bits,16:this.texturePerEdgeIdPortionIds16Bits,32:this.texturePerEdgeIdPortionIds32Bits}}},{key:"bindCommonTextures",value:function(e,t,n,r,i,a,s){this.texturePerObjectIdPositionsDecodeMatrix.bindTexture(e,t,1),this.texturePerVertexIdCoordinates.bindTexture(e,n,2),this.texturePerObjectIdColorsAndFlags.bindTexture(e,r,3),this.textureCameraMatrices.bindTexture(e,i,4),this.textureModelMatrices.bindTexture(e,a,5),this.texturePerObjectIdOffsets.bindTexture(e,s,6)}},{key:"bindPickCameraTexture",value:function(e,t){this.texturePickCameraMatrices.bindTexture(e,t,4)}},{key:"bindTriangleIndicesTextures",value:function(e,t,n,r){this.indicesPortionIdsPerBitnessTextures[r].bindTexture(e,t,7),this.indicesPerBitnessTextures[r].bindTexture(e,n,8)}},{key:"bindEdgeIndicesTextures",value:function(e,t,n,r){this.edgeIndicesPortionIdsPerBitnessTextures[r].bindTexture(e,t,7),this.edgeIndicesPerBitnessTextures[r].bindTexture(e,n,8)}}]),e}(),Yc=function(){function e(t,n,r,i){var a=arguments.length>4&&void 0!==arguments[4]?arguments[4]:null;b(this,e),this._gl=t,this._texture=n,this._textureWidth=r,this._textureHeight=i,this._textureData=a}return P(e,[{key:"bindTexture",value:function(e,t,n){return e.bindTexture(t,this,n)}},{key:"bind",value:function(e){return this._gl.activeTexture(this._gl["TEXTURE"+e]),this._gl.bindTexture(this._gl.TEXTURE_2D,this._texture),!0}},{key:"unbind",value:function(e){}}]),e}(),Xc={sizeDataColorsAndFlags:0,sizeDataPositionDecodeMatrices:0,sizeDataTextureOffsets:0,sizeDataTexturePositions:0,sizeDataTextureIndices:0,sizeDataTextureEdgeIndices:0,sizeDataTexturePortionIds:0,numberOfGeometries:0,numberOfPortions:0,numberOfLayers:0,numberOfTextures:0,totalPolygons:0,totalPolygons8Bits:0,totalPolygons16Bits:0,totalPolygons32Bits:0,totalEdges:0,totalEdges8Bits:0,totalEdges16Bits:0,totalEdges32Bits:0,cannotCreatePortion:{because10BitsObjectId:0,becauseTextureSize:0},overheadSizeAlignementIndices:0,overheadSizeAlignementEdgeIndices:0};window.printDataTextureRamStats=function(){console.log(JSON.stringify(Xc,null,4));var e=0;Object.keys(Xc).forEach((function(t){t.startsWith("size")&&(e+=Xc[t])})),console.log("Total size ".concat(e," bytes (").concat((e/1e3/1e3).toFixed(2)," MB)")),console.log("Avg bytes / triangle: ".concat((e/Xc.totalPolygons).toFixed(2)));var t={};Object.keys(Xc).forEach((function(n){n.startsWith("size")&&(t[n]="".concat((Xc[n]/e*100).toFixed(2)," % of total"))})),console.log(JSON.stringify({percentualRamUsage:t},null,4))};var qc=function(){function e(){b(this,e)}return P(e,[{key:"disableBindedTextureFiltering",value:function(e){e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE)}},{key:"generateCameraDataTexture",value:function(e,t,n,r){var i=e.createTexture();e.bindTexture(e.TEXTURE_2D,i),e.texStorage2D(e.TEXTURE_2D,1,e.RGBA32F,4,3),this.disableBindedTextureFiltering(e),e.bindTexture(e.TEXTURE_2D,null);var a=new Yc(e,i,4,3),s=!0;a.updateViewMatrix=function(n,i){e.bindTexture(e.TEXTURE_2D,a._texture),e.texSubImage2D(e.TEXTURE_2D,0,0,0,4,1,e.RGBA,e.FLOAT,new Float32Array(r?Ie(n,r):n)),e.texSubImage2D(e.TEXTURE_2D,0,0,1,4,1,e.RGBA,e.FLOAT,new Float32Array(t.viewNormalMatrix)),e.texSubImage2D(e.TEXTURE_2D,0,0,2,4,1,e.RGBA,e.FLOAT,new Float32Array(i))};var o=function(){s&&(s=!1,a.updateViewMatrix(t.viewMatrix,t.project.matrix))};return t.on("matrix",(function(){return s=!0})),n.on("rendering",o),o(),a}},{key:"generatePickCameraDataTexture",value:function(e,t,n){var r=e.createTexture();e.bindTexture(e.TEXTURE_2D,r),e.texStorage2D(e.TEXTURE_2D,1,e.RGBA32F,4,3),this.disableBindedTextureFiltering(e),e.bindTexture(e.TEXTURE_2D,null);var i=new Yc(e,r,4,3);return i.updateViewMatrix=function(r,a){e.bindTexture(e.TEXTURE_2D,i._texture),e.texSubImage2D(e.TEXTURE_2D,0,0,0,4,1,e.RGBA,e.FLOAT,new Float32Array(n?Ie(r,n):r)),e.texSubImage2D(e.TEXTURE_2D,0,0,1,4,1,e.RGBA,e.FLOAT,new Float32Array(t.viewNormalMatrix)),e.texSubImage2D(e.TEXTURE_2D,0,0,2,4,1,e.RGBA,e.FLOAT,new Float32Array(a))},i}},{key:"generateModelTexture",value:function(e,t){var n=e.createTexture();return e.bindTexture(e.TEXTURE_2D,n),e.texStorage2D(e.TEXTURE_2D,1,e.RGBA32F,4,2),e.texSubImage2D(e.TEXTURE_2D,0,0,0,4,1,e.RGBA,e.FLOAT,new Float32Array(t.worldMatrix)),e.texSubImage2D(e.TEXTURE_2D,0,0,1,4,1,e.RGBA,e.FLOAT,new Float32Array(t.worldNormalMatrix)),this.disableBindedTextureFiltering(e),e.bindTexture(e.TEXTURE_2D,null),new Yc(e,n,4,2)}},{key:"generateTextureForColorsAndFlags",value:function(e,t,n,r,i,a,s){var o=t.length;this.numPortions=o;var l=4096,u=Math.ceil(o/512);if(0===u)throw"texture height===0";var c=new Uint8Array(16384*u);Xc.sizeDataColorsAndFlags+=c.byteLength,Xc.numberOfTextures++;for(var f=0;f<o;f++)c.set(t[f],32*f+0),c.set(n[f],32*f+4),c.set([0,0,0,0],32*f+8),c.set([0,0,0,0],32*f+12),c.set([r[f]>>24&255,r[f]>>16&255,r[f]>>8&255,255&r[f]],32*f+16),c.set([i[f]>>24&255,i[f]>>16&255,i[f]>>8&255,255&i[f]],32*f+20),c.set([a[f]>>24&255,a[f]>>16&255,a[f]>>8&255,255&a[f]],32*f+24),c.set([s[f]?1:0,0,0,0],32*f+28);var p=e.createTexture();return e.bindTexture(e.TEXTURE_2D,p),e.texStorage2D(e.TEXTURE_2D,1,e.RGBA8UI,l,u),e.texSubImage2D(e.TEXTURE_2D,0,0,0,l,u,e.RGBA_INTEGER,e.UNSIGNED_BYTE,c,0),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.bindTexture(e.TEXTURE_2D,null),new Yc(e,p,l,u,c)}},{key:"generateTextureForObjectOffsets",value:function(e,t){var n=512,r=Math.ceil(t/n);if(0===r)throw"texture height===0";var i=new Float32Array(1536*r).fill(0);Xc.sizeDataTextureOffsets+=i.byteLength,Xc.numberOfTextures++;var a=e.createTexture();return e.bindTexture(e.TEXTURE_2D,a),e.texStorage2D(e.TEXTURE_2D,1,e.RGB32F,n,r),e.texSubImage2D(e.TEXTURE_2D,0,0,0,n,r,e.RGB,e.FLOAT,i,0),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.bindTexture(e.TEXTURE_2D,null),new Yc(e,a,n,r,i)}},{key:"generateTextureForPositionsDecodeMatrices",value:function(e,t,n){var r=t.length;if(0===r)throw"num decode+entity matrices===0";var i=2048,a=Math.ceil(r/512),s=new Float32Array(8192*a);Xc.sizeDataPositionDecodeMatrices+=s.byteLength,Xc.numberOfTextures++;for(var o=Z.mat4(),l=0;l<t.length;l++)s.set(Z.mulMat4(n[l],t[l],o),16*l);var u=e.createTexture();return e.bindTexture(e.TEXTURE_2D,u),e.texStorage2D(e.TEXTURE_2D,1,e.RGBA32F,i,a),e.texSubImage2D(e.TEXTURE_2D,0,0,0,i,a,e.RGBA,e.FLOAT,s,0),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.bindTexture(e.TEXTURE_2D,null),new Yc(e,u,i,a)}},{key:"generateTextureFor8BitIndices",value:function(e,t){if(0===t.length)return{texture:null,textureHeight:0};var n=4096,r=Math.ceil(t.length/3/n);if(0===r)throw"texture height===0";var i=new Uint8Array(n*r*3);Xc.sizeDataTextureIndices+=i.byteLength,Xc.numberOfTextures++,i.fill(0),i.set(t,0);var a=e.createTexture();return e.bindTexture(e.TEXTURE_2D,a),e.texStorage2D(e.TEXTURE_2D,1,e.RGB8UI,n,r),e.texSubImage2D(e.TEXTURE_2D,0,0,0,n,r,e.RGB_INTEGER,e.UNSIGNED_BYTE,i,0),this.disableBindedTextureFiltering(e),e.bindTexture(e.TEXTURE_2D,null),new Yc(e,a,n,r)}},{key:"generateTextureFor16BitIndices",value:function(e,t){if(0===t.length)return{texture:null,textureHeight:0};var n=4096,r=Math.ceil(t.length/3/n);if(0===r)throw"texture height===0";var i=new Uint16Array(n*r*3);Xc.sizeDataTextureIndices+=i.byteLength,Xc.numberOfTextures++,i.fill(0),i.set(t,0);var a=e.createTexture();return e.bindTexture(e.TEXTURE_2D,a),e.texStorage2D(e.TEXTURE_2D,1,e.RGB16UI,n,r),e.texSubImage2D(e.TEXTURE_2D,0,0,0,n,r,e.RGB_INTEGER,e.UNSIGNED_SHORT,i,0),this.disableBindedTextureFiltering(e),e.bindTexture(e.TEXTURE_2D,null),new Yc(e,a,n,r)}},{key:"generateTextureFor32BitIndices",value:function(e,t){if(0===t.length)return{texture:null,textureHeight:0};var n=4096,r=Math.ceil(t.length/3/n);if(0===r)throw"texture height===0";var i=new Uint32Array(n*r*3);Xc.sizeDataTextureIndices+=i.byteLength,Xc.numberOfTextures++,i.fill(0),i.set(t,0);var a=e.createTexture();return e.bindTexture(e.TEXTURE_2D,a),e.texStorage2D(e.TEXTURE_2D,1,e.RGB32UI,n,r),e.texSubImage2D(e.TEXTURE_2D,0,0,0,n,r,e.RGB_INTEGER,e.UNSIGNED_INT,i,0),this.disableBindedTextureFiltering(e),e.bindTexture(e.TEXTURE_2D,null),new Yc(e,a,n,r)}},{key:"generateTextureFor8BitsEdgeIndices",value:function(e,t){if(0===t.length)return{texture:null,textureHeight:0};var n=4096,r=Math.ceil(t.length/2/n);if(0===r)throw"texture height===0";var i=new Uint8Array(n*r*2);Xc.sizeDataTextureEdgeIndices+=i.byteLength,Xc.numberOfTextures++,i.fill(0),i.set(t,0);var a=e.createTexture();return e.bindTexture(e.TEXTURE_2D,a),e.texStorage2D(e.TEXTURE_2D,1,e.RG8UI,n,r),e.texSubImage2D(e.TEXTURE_2D,0,0,0,n,r,e.RG_INTEGER,e.UNSIGNED_BYTE,i,0),this.disableBindedTextureFiltering(e),e.bindTexture(e.TEXTURE_2D,null),new Yc(e,a,n,r)}},{key:"generateTextureFor16BitsEdgeIndices",value:function(e,t){if(0===t.length)return{texture:null,textureHeight:0};var n=4096,r=Math.ceil(t.length/2/n);if(0===r)throw"texture height===0";var i=new Uint16Array(n*r*2);Xc.sizeDataTextureEdgeIndices+=i.byteLength,Xc.numberOfTextures++,i.fill(0),i.set(t,0);var a=e.createTexture();return e.bindTexture(e.TEXTURE_2D,a),e.texStorage2D(e.TEXTURE_2D,1,e.RG16UI,n,r),e.texSubImage2D(e.TEXTURE_2D,0,0,0,n,r,e.RG_INTEGER,e.UNSIGNED_SHORT,i,0),this.disableBindedTextureFiltering(e),e.bindTexture(e.TEXTURE_2D,null),new Yc(e,a,n,r)}},{key:"generateTextureFor32BitsEdgeIndices",value:function(e,t){if(0===t.length)return{texture:null,textureHeight:0};var n=4096,r=Math.ceil(t.length/2/n);if(0===r)throw"texture height===0";var i=new Uint32Array(n*r*2);Xc.sizeDataTextureEdgeIndices+=i.byteLength,Xc.numberOfTextures++,i.fill(0),i.set(t,0);var a=e.createTexture();return e.bindTexture(e.TEXTURE_2D,a),e.texStorage2D(e.TEXTURE_2D,1,e.RG32UI,n,r),e.texSubImage2D(e.TEXTURE_2D,0,0,0,n,r,e.RG_INTEGER,e.UNSIGNED_INT,i,0),this.disableBindedTextureFiltering(e),e.bindTexture(e.TEXTURE_2D,null),new Yc(e,a,n,r)}},{key:"generateTextureForPositions",value:function(e,t){var n=t.length/3,r=4096,i=Math.ceil(n/r);if(0===i)throw"texture height===0";var a=new Uint16Array(r*i*3);Xc.sizeDataTexturePositions+=a.byteLength,Xc.numberOfTextures++,a.fill(0),a.set(t,0);var s=e.createTexture();return e.bindTexture(e.TEXTURE_2D,s),e.texStorage2D(e.TEXTURE_2D,1,e.RGB16UI,r,i),e.texSubImage2D(e.TEXTURE_2D,0,0,0,r,i,e.RGB_INTEGER,e.UNSIGNED_SHORT,a,0),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.bindTexture(e.TEXTURE_2D,null),new Yc(e,s,r,i)}},{key:"generateTextureForPackedPortionIds",value:function(e,t){if(0===t.length)return{texture:null,textureHeight:0};var n=t.length,r=4096,i=Math.ceil(n/r);if(0===i)throw"texture height===0";var a=new Uint16Array(r*i);a.set(t,0),Xc.sizeDataTexturePortionIds+=a.byteLength,Xc.numberOfTextures++;var s=e.createTexture();return e.bindTexture(e.TEXTURE_2D,s),e.texStorage2D(e.TEXTURE_2D,1,e.R16UI,r,i),e.texSubImage2D(e.TEXTURE_2D,0,0,0,r,i,e.RED_INTEGER,e.UNSIGNED_SHORT,a,0),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.bindTexture(e.TEXTURE_2D,null),new Yc(e,s,r,i)}}]),e}(),Jc=Z.vec4([0,0,0,1]),Zc=Z.vec4([0,0,0,1]),$c=Z.vec4([0,0,0,1]),ef=new Uint8Array(4),tf=new Float32Array(3);Z.AABB3();var nf=Z.AABB3();Z.OBB3();var rf=0,af=Z.identityMat4(),sf=function(){function e(t,n){var r,i,a;b(this,e),Xc.numberOfLayers++,this._layerNumber=rf++,this.sortId="TriDTX-".concat(this._layerNumber),this.layerIndex=n.layerIndex,this._dataTextureRenderers=(r=t.scene,i=r.id,(a=Wc[i])||(a=new Qc(r),Wc[i]=a,a._compile(),r.on("compile",(function(){a._compile()})),r.on("destroyed",(function(){delete Wc[i],a._destroy()}))),a),this.model=t,this._buffer=new zc,this._dataTextureState=new Kc,this._dataTextureGenerator=new qc,this._state=new St({origin:Z.vec3(n.origin),metallicRoughnessBuf:null,positionsDecodeMatrix:Z.mat4(),textureState:this._dataTextureState,numIndices8Bits:0,numIndices16Bits:0,numIndices32Bits:0,numEdgeIndices8Bits:0,numEdgeIndices16Bits:0,numEdgeIndices32Bits:0,numVertices:0}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numSelectedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numClippableLayerPortions=0,this._numEdgesLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this._subPortions=[],this._portionToSubPortionsMap=[],this._bucketGeometries={},this.aabb=Z.collapseAABB3(),this._numUpdatesInFrame=0,this._finalized=!1}return P(e,[{key:"canCreatePortion",value:function(e){if(this._finalized)throw"Already finalized";var t=e.buckets.length;this._numPortions+t>65536&&Xc.cannotCreatePortion.because10BitsObjectId++;var n=this._numPortions+t<=65536,r=void 0!==e.geometryId&&null!==e.geometryId?"".concat(e.geometryId,"#").concat(0):"".concat(e.id,"#").concat(0);if(!this._bucketGeometries[r]){var i=Math.max(this._state.numIndices8Bits,this._state.numIndices16Bits,this._state.numIndices32Bits),a=0,s=0;e.buckets.forEach((function(e){a+=e.positionsCompressed.length/3,s+=e.indices.length/3})),(this._state.numVertices+a>16777216||i+s>16777216)&&Xc.cannotCreatePortion.becauseTextureSize++,n&&(n=this._state.numVertices+a<=16777216&&i+s<=16777216)}return n}},{key:"createPortion",value:function(e){var t=this;if(this._finalized)throw"Already finalized";var n=[],r=e.worldAABB;e.buckets.forEach((function(i,a){var s=void 0!==e.geometryId&&null!==e.geometryId?"".concat(e.geometryId,"#").concat(a):"".concat(e.id,"#").concat(a),o=t._bucketGeometries[s];o||(o=t._createBucketGeometry(e,i),t._bucketGeometries[s]=o);var l=Z.collapseAABB3(nf),u=t._createSubPortion(e,o,i,l);Z.expandAABB3(r,l),n.push(u)}));var i=this._state.origin;0===i[0]&&0===i[1]&&0===i[2]||(r[0]+=i[0],r[1]+=i[1],r[2]+=i[2],r[3]+=i[0],r[4]+=i[1],r[5]+=i[2]),Z.expandAABB3(this.aabb,r);var a=this._portionToSubPortionsMap.length;return this._portionToSubPortionsMap.push(n),this.model.numPortions++,a}},{key:"_createBucketGeometry",value:function(e,t){if(t.indices){var n=8*Math.ceil(t.indices.length/3/8)*3;Xc.overheadSizeAlignementIndices+=2*(n-t.indices.length);var r=new Uint32Array(n);r.fill(0),r.set(t.indices),t.indices=r}if(t.edgeIndices){var i=8*Math.ceil(t.edgeIndices.length/2/8)*2;Xc.overheadSizeAlignementEdgeIndices+=2*(i-t.edgeIndices.length);var a=new Uint32Array(i);a.fill(0),a.set(t.edgeIndices),t.edgeIndices=a}for(var s,o=t.positionsCompressed,l=t.indices,u=t.edgeIndices,c=this._buffer,f=c.positionsCompressed.length/3,p=o.length/3,A=0,d=o.length;A<d;A++)c.positionsCompressed.push(o[A]);var v,h=0;if(l){var I;h=l.length/3,s=(I=p<=256?c.indices8Bits:p<=65536?c.indices16Bits:c.indices32Bits).length/3;for(var y=0,m=l.length;y<m;y++)I.push(l[y])}var w=0;if(u){var g;w=u.length/2,v=(g=p<=256?c.edgeIndices8Bits:p<=65536?c.edgeIndices16Bits:c.edgeIndices32Bits).length/2;for(var T=0,E=u.length;T<E;T++)g.push(u[T])}this._state.numVertices+=p,Xc.numberOfGeometries++;var b=Z.collapseAABB3();return Z.expandAABB3Points3(b,t.positionsCompressed),pn.decompressAABB(b,e.positionsDecodeMatrix),{vertexBase:f,numVertices:p,numTriangles:h,numEdges:w,indicesBase:s,edgeIndicesBase:v,aabb:b,obb:null}}},{key:"_createSubPortion",value:function(e,t,n,r){var i=e.color;e.metallic,e.roughness;var a,s,o=e.colors,l=e.opacity,u=e.meshMatrix,c=e.sceneModelMatrix,f=e.pickColor,p=this._buffer,A=this._state;if(p.perObjectPositionsDecodeMatrices.push(e.positionsDecodeMatrix),p.perObjectInstancePositioningMatrices.push(u||af),u||c){t.obb||(t.obb=Z.AABB3ToOBB3(t.aabb));for(var d=t.obb,v=0,h=d.length;v<h;v+=4)Jc[0]=d[v+0],Jc[1]=d[v+1],Jc[2]=d[v+2],Jc[3]=1,u&&Z.transformPoint4(u,Jc,Zc),c?(Z.transformPoint4(c,Zc,$c),Z.expandAABB3Point3(r,$c)):Z.expandAABB3Point3(r,Zc)}else Z.expandAABB3(r,t.aabb);p.perObjectSolid.push(!!e.solid),o?p.perObjectColors.push([255*o[0],255*o[1],255*o[2],255]):i&&p.perObjectColors.push([i[0],i[1],i[2],l]),p.perObjectPickColors.push(f),p.perObjectVertexBases.push(t.vertexBase),a=t.numVertices<=256?A.numIndices8Bits:t.numVertices<=65536?A.numIndices16Bits:A.numIndices32Bits,p.perObjectIndexBaseOffsets.push(a/3-t.indicesBase),s=t.numVertices<=256?A.numEdgeIndices8Bits:t.numVertices<=65536?A.numEdgeIndices16Bits:A.numEdgeIndices32Bits,p.perObjectEdgeIndexBaseOffsets.push(s/2-t.edgeIndicesBase);var I=this._subPortions.length;if(t.numTriangles>0){var y,m=3*t.numTriangles;t.numVertices<=256?(y=p.perTriangleNumberPortionId8Bits,A.numIndices8Bits+=m,Xc.totalPolygons8Bits+=t.numTriangles):t.numVertices<=65536?(y=p.perTriangleNumberPortionId16Bits,A.numIndices16Bits+=m,Xc.totalPolygons16Bits+=t.numTriangles):(y=p.perTriangleNumberPortionId32Bits,A.numIndices32Bits+=m,Xc.totalPolygons32Bits+=t.numTriangles),Xc.totalPolygons+=t.numTriangles;for(var w=0;w<t.numTriangles;w+=8)y.push(I)}if(t.numEdges>0){var g,T=2*t.numEdges;t.numVertices<=256?(g=p.perEdgeNumberPortionId8Bits,A.numEdgeIndices8Bits+=T,Xc.totalEdges8Bits+=t.numEdges):t.numVertices<=65536?(g=p.perEdgeNumberPortionId16Bits,A.numEdgeIndices16Bits+=T,Xc.totalEdges16Bits+=t.numEdges):(g=p.perEdgeNumberPortionId32Bits,A.numEdgeIndices32Bits+=T,Xc.totalEdges32Bits+=t.numEdges),Xc.totalEdges+=t.numEdges;for(var E=0;E<t.numEdges;E+=8)g.push(I)}return this._subPortions.push({numVertices:t.numTriangles}),this._numPortions++,Xc.numberOfPortions++,I}},{key:"finalize",value:function(){var e=this;if(!this._finalized){var t=this._state,n=this._dataTextureState,r=this.model.scene.canvas.gl,i=this._buffer;t.gl=r,n.texturePerObjectIdColorsAndFlags=this._dataTextureGenerator.generateTextureForColorsAndFlags(r,i.perObjectColors,i.perObjectPickColors,i.perObjectVertexBases,i.perObjectIndexBaseOffsets,i.perObjectEdgeIndexBaseOffsets,i.perObjectSolid),n.texturePerObjectIdOffsets=this._dataTextureGenerator.generateTextureForObjectOffsets(r,this._numPortions),n.texturePerObjectIdPositionsDecodeMatrix=this._dataTextureGenerator.generateTextureForPositionsDecodeMatrices(r,i.perObjectPositionsDecodeMatrices,i.perObjectInstancePositioningMatrices),n.texturePerVertexIdCoordinates=this._dataTextureGenerator.generateTextureForPositions(r,i.positionsCompressed),n.texturePerPolygonIdPortionIds8Bits=this._dataTextureGenerator.generateTextureForPackedPortionIds(r,i.perTriangleNumberPortionId8Bits),n.texturePerPolygonIdPortionIds16Bits=this._dataTextureGenerator.generateTextureForPackedPortionIds(r,i.perTriangleNumberPortionId16Bits),n.texturePerPolygonIdPortionIds32Bits=this._dataTextureGenerator.generateTextureForPackedPortionIds(r,i.perTriangleNumberPortionId32Bits),i.perEdgeNumberPortionId8Bits.length>0&&(n.texturePerEdgeIdPortionIds8Bits=this._dataTextureGenerator.generateTextureForPackedPortionIds(r,i.perEdgeNumberPortionId8Bits)),i.perEdgeNumberPortionId16Bits.length>0&&(n.texturePerEdgeIdPortionIds16Bits=this._dataTextureGenerator.generateTextureForPackedPortionIds(r,i.perEdgeNumberPortionId16Bits)),i.perEdgeNumberPortionId32Bits.length>0&&(n.texturePerEdgeIdPortionIds32Bits=this._dataTextureGenerator.generateTextureForPackedPortionIds(r,i.perEdgeNumberPortionId32Bits)),i.indices8Bits.length>0&&(n.texturePerPolygonIdIndices8Bits=this._dataTextureGenerator.generateTextureFor8BitIndices(r,i.indices8Bits)),i.indices16Bits.length>0&&(n.texturePerPolygonIdIndices16Bits=this._dataTextureGenerator.generateTextureFor16BitIndices(r,i.indices16Bits)),i.indices32Bits.length>0&&(n.texturePerPolygonIdIndices32Bits=this._dataTextureGenerator.generateTextureFor32BitIndices(r,i.indices32Bits)),i.edgeIndices8Bits.length>0&&(n.texturePerPolygonIdEdgeIndices8Bits=this._dataTextureGenerator.generateTextureFor8BitsEdgeIndices(r,i.edgeIndices8Bits)),i.edgeIndices16Bits.length>0&&(n.texturePerPolygonIdEdgeIndices16Bits=this._dataTextureGenerator.generateTextureFor16BitsEdgeIndices(r,i.edgeIndices16Bits)),i.edgeIndices32Bits.length>0&&(n.texturePerPolygonIdEdgeIndices32Bits=this._dataTextureGenerator.generateTextureFor32BitsEdgeIndices(r,i.edgeIndices32Bits)),this.model._modelMatricesTexture||(this.model._modelMatricesTexture=this._dataTextureGenerator.generateModelTexture(r,this.model)),n.textureModelMatrices=this.model._modelMatricesTexture,n.cameraTexture=this._dataTextureGenerator.generateCameraDataTexture(this.model.scene.canvas.gl,this.model.scene.camera,this.model.scene,this._state.origin.slice()),n.textureCameraMatrices=n.cameraTexture,n.texturePickCameraMatrices=this._dataTextureGenerator.generatePickCameraDataTexture(this.model.scene.canvas.gl,this.model.scene.camera,this._state.origin.slice()),n.finalize(),this._buffer=null,this._bucketGeometries={},this._finalized=!0,this._deferredSetFlagsDirty=!1,this._onSceneRendering=this.model.scene.on("rendering",(function(){e._deferredSetFlagsDirty&&e._uploadDeferredFlags(),e._numUpdatesInFrame=0}))}}},{key:"isEmpty",value:function(){return 0===this._numPortions}},{key:"initFlags",value:function(e,t,n){t&Te&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&Ce&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&Re&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&_e&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&De&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&Be&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&be&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&Ee&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),n&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++);this._setFlags(e,t,n,true),this._setFlags2(e,t,true)}},{key:"flushInitFlags",value:function(){this._setDeferredFlags(),this._setDeferredFlags2()}},{key:"setVisible",value:function(e,t,n){if(!this._finalized)throw"Not finalized";t&Te?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,n)}},{key:"setHighlighted",value:function(e,t,n){if(!this._finalized)throw"Not finalized";t&Ce?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,n)}},{key:"setXRayed",value:function(e,t,n){if(!this._finalized)throw"Not finalized";t&Re?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,n)}},{key:"setSelected",value:function(e,t,n){if(!this._finalized)throw"Not finalized";t&_e?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,n)}},{key:"setEdges",value:function(e,t,n){if(!this._finalized)throw"Not finalized";t&Be?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,n)}},{key:"setClippable",value:function(e,t){if(!this._finalized)throw"Not finalized";t&De?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags2(e,t)}},{key:"_beginDeferredFlags",value:function(){this._deferredSetFlagsActive=!0}},{key:"_uploadDeferredFlags",value:function(){if(this._deferredSetFlagsActive=!1,this._deferredSetFlagsDirty){this._deferredSetFlagsDirty=!1;var e=this.model.scene.canvas.gl,t=this._dataTextureState;e.bindTexture(e.TEXTURE_2D,t.texturePerObjectIdColorsAndFlags._texture),e.texSubImage2D(e.TEXTURE_2D,0,0,0,t.texturePerObjectIdColorsAndFlags._textureWidth,t.texturePerObjectIdColorsAndFlags._textureHeight,e.RGBA_INTEGER,e.UNSIGNED_BYTE,t.texturePerObjectIdColorsAndFlags._textureData),e.bindTexture(e.TEXTURE_2D,t.texturePerObjectIdOffsets._texture),e.texSubImage2D(e.TEXTURE_2D,0,0,0,t.texturePerObjectIdOffsets._textureWidth,t.texturePerObjectIdOffsets._textureHeight,e.RGB,e.FLOAT,t.texturePerObjectIdOffsets._textureData)}}},{key:"setCulled",value:function(e,t,n){if(!this._finalized)throw"Not finalized";t&Ee?(this._numCulledLayerPortions+=this._portionToSubPortionsMap[e].length,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions-=this._portionToSubPortionsMap[e].length,this.model.numCulledLayerPortions--),this._setFlags(e,t,n)}},{key:"setCollidable",value:function(e,t){if(!this._finalized)throw"Not finalized"}},{key:"setPickable",value:function(e,t,n){if(!this._finalized)throw"Not finalized";t&be?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,n)}},{key:"setColor",value:function(e,t){for(var n=this._portionToSubPortionsMap[e],r=0,i=n.length;r<i;r++)this._subPortionSetColor(n[r],t)}},{key:"_subPortionSetColor",value:function(e,t){if(!this._finalized)throw"Not finalized";var n=this._dataTextureState,r=this.model.scene.canvas.gl;ef[0]=t[0],ef[1]=t[1],ef[2]=t[2],ef[3]=t[3],n.texturePerObjectIdColorsAndFlags._textureData.set(ef,32*e),this._deferredSetFlagsActive?this._deferredSetFlagsDirty=!0:(++this._numUpdatesInFrame>=10&&this._beginDeferredFlags(),r.bindTexture(r.TEXTURE_2D,n.texturePerObjectIdColorsAndFlags._texture),r.texSubImage2D(r.TEXTURE_2D,0,e%512*8,Math.floor(e/512),1,1,r.RGBA_INTEGER,r.UNSIGNED_BYTE,ef))}},{key:"setTransparent",value:function(e,t,n){n?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,n)}},{key:"_setFlags",value:function(e,t,n){for(var r=arguments.length>3&&void 0!==arguments[3]&&arguments[3],i=this._portionToSubPortionsMap[e],a=0,s=i.length;a<s;a++)this._subPortionSetFlags(i[a],t,n,r)}},{key:"_subPortionSetFlags",value:function(e,t,n){var r=arguments.length>3&&void 0!==arguments[3]&&arguments[3];if(!this._finalized)throw"Not finalized";var i,a,s=!!(t&Te),o=!!(t&Re),l=!!(t&Ce),u=!!(t&_e),c=!!(t&Be),f=!!(t&be),p=!!(t&Ee);i=!s||p||o?eo.NOT_RENDERED:n?eo.COLOR_TRANSPARENT:eo.COLOR_OPAQUE,a=!s||p?eo.NOT_RENDERED:u?eo.SILHOUETTE_SELECTED:l?eo.SILHOUETTE_HIGHLIGHTED:o?eo.SILHOUETTE_XRAYED:eo.NOT_RENDERED;var A=0;A=!s||p?eo.NOT_RENDERED:u?eo.EDGES_SELECTED:l?eo.EDGES_HIGHLIGHTED:o?eo.EDGES_XRAYED:c?n?eo.EDGES_COLOR_TRANSPARENT:eo.EDGES_COLOR_OPAQUE:eo.NOT_RENDERED;var d=s&&f?eo.PICK:eo.NOT_RENDERED,v=this._dataTextureState,h=this.model.scene.canvas.gl;ef[0]=i,ef[1]=a,ef[2]=A,ef[3]=d,v.texturePerObjectIdColorsAndFlags._textureData.set(ef,32*e+8),this._deferredSetFlagsActive||r?this._deferredSetFlagsDirty=!0:(++this._numUpdatesInFrame>=10&&this._beginDeferredFlags(),h.bindTexture(h.TEXTURE_2D,v.texturePerObjectIdColorsAndFlags._texture),h.texSubImage2D(h.TEXTURE_2D,0,e%512*8+2,Math.floor(e/512),1,1,h.RGBA_INTEGER,h.UNSIGNED_BYTE,ef))}},{key:"_setDeferredFlags",value:function(){}},{key:"_setFlags2",value:function(e,t){for(var n=arguments.length>2&&void 0!==arguments[2]&&arguments[2],r=this._portionToSubPortionsMap[e],i=0,a=r.length;i<a;i++)this._subPortionSetFlags2(r[i],t,n)}},{key:"_subPortionSetFlags2",value:function(e,t){var n=arguments.length>2&&void 0!==arguments[2]&&arguments[2];if(!this._finalized)throw"Not finalized";var r=t&De?255:0,i=this._dataTextureState,a=this.model.scene.canvas.gl;ef[0]=r,ef[1]=0,ef[2]=1,ef[3]=2,i.texturePerObjectIdColorsAndFlags._textureData.set(ef,32*e+12),this._deferredSetFlagsActive||n?this._deferredSetFlagsDirty=!0:(++this._numUpdatesInFrame>=10&&this._beginDeferredFlags(),a.bindTexture(a.TEXTURE_2D,i.texturePerObjectIdColorsAndFlags._texture),a.texSubImage2D(a.TEXTURE_2D,0,e%512*8+3,Math.floor(e/512),1,1,a.RGBA_INTEGER,a.UNSIGNED_BYTE,ef))}},{key:"_setDeferredFlags2",value:function(){}},{key:"setOffset",value:function(e,t){for(var n=this._portionToSubPortionsMap[e],r=0,i=n.length;r<i;r++)this._subPortionSetOffset(n[r],t)}},{key:"_subPortionSetOffset",value:function(e,t){if(!this._finalized)throw"Not finalized";var n=this._dataTextureState,r=this.model.scene.canvas.gl;tf[0]=t[0],tf[1]=t[1],tf[2]=t[2],n.texturePerObjectIdOffsets._textureData.set(tf,3*e),this._deferredSetFlagsActive?this._deferredSetFlagsDirty=!0:(++this._numUpdatesInFrame>=10&&this._beginDeferredFlags(),r.bindTexture(r.TEXTURE_2D,n.texturePerObjectIdOffsets._texture),r.texSubImage2D(r.TEXTURE_2D,0,0,e,1,1,r.RGB,r.FLOAT,tf))}},{key:"drawColorOpaque",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&(this._updateBackfaceCull(e,t),t.withSAO&&this.model.saoEnabled?t.pbrEnabled&&this.model.pbrEnabled?this._dataTextureRenderers.colorQualityRendererWithSAO&&this._dataTextureRenderers.colorQualityRendererWithSAO.drawLayer(t,this,eo.COLOR_OPAQUE):this._dataTextureRenderers.colorRendererWithSAO&&this._dataTextureRenderers.colorRendererWithSAO.drawLayer(t,this,eo.COLOR_OPAQUE):t.pbrEnabled&&this.model.pbrEnabled?this._dataTextureRenderers.colorQualityRenderer&&this._dataTextureRenderers.colorQualityRenderer.drawLayer(t,this,eo.COLOR_OPAQUE):this._dataTextureRenderers.colorRenderer&&this._dataTextureRenderers.colorRenderer.drawLayer(t,this,eo.COLOR_OPAQUE))}},{key:"_updateBackfaceCull",value:function(e,t){var n=this.model.backfaces||e.sectioned;if(t.backfaces!==n){var r=t.gl;n?r.disable(r.CULL_FACE):r.enable(r.CULL_FACE),t.backfaces=n}}},{key:"drawColorTransparent",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numTransparentLayerPortions&&this._numXRayedLayerPortions!==this._numPortions&&(this._updateBackfaceCull(e,t),t.pbrEnabled&&this.model.pbrEnabled?this._dataTextureRenderers.colorQualityRenderer&&this._dataTextureRenderers.colorQualityRenderer.drawLayer(t,this,eo.COLOR_TRANSPARENT):this._dataTextureRenderers.colorRenderer&&this._dataTextureRenderers.colorRenderer.drawLayer(t,this,eo.COLOR_TRANSPARENT))}},{key:"drawDepth",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&(this._updateBackfaceCull(e,t),this._dataTextureRenderers.depthRenderer&&this._dataTextureRenderers.depthRenderer.drawLayer(t,this,eo.COLOR_OPAQUE))}},{key:"drawNormals",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&(this._updateBackfaceCull(e,t),this._dataTextureRenderers.normalsRenderer&&this._dataTextureRenderers.normalsRenderer.drawLayer(t,this,eo.COLOR_OPAQUE))}},{key:"drawSilhouetteXRayed",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&(this._updateBackfaceCull(e,t),this._dataTextureRenderers.silhouetteRenderer&&this._dataTextureRenderers.silhouetteRenderer.drawLayer(t,this,eo.SILHOUETTE_XRAYED))}},{key:"drawSilhouetteHighlighted",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&(this._updateBackfaceCull(e,t),this._dataTextureRenderers.silhouetteRenderer&&this._dataTextureRenderers.silhouetteRenderer.drawLayer(t,this,eo.SILHOUETTE_HIGHLIGHTED))}},{key:"drawSilhouetteSelected",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&(this._updateBackfaceCull(e,t),this._dataTextureRenderers.silhouetteRenderer&&this._dataTextureRenderers.silhouetteRenderer.drawLayer(t,this,eo.SILHOUETTE_SELECTED))}},{key:"drawEdgesColorOpaque",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numEdgesLayerPortions&&this._dataTextureRenderers.edgesColorRenderer&&this._dataTextureRenderers.edgesColorRenderer.drawLayer(t,this,eo.EDGES_COLOR_OPAQUE)}},{key:"drawEdgesColorTransparent",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numEdgesLayerPortions&&0!==this._numTransparentLayerPortions&&this._dataTextureRenderers.edgesColorRenderer&&this._dataTextureRenderers.edgesColorRenderer.drawLayer(t,this,eo.EDGES_COLOR_TRANSPARENT)}},{key:"drawEdgesHighlighted",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&this._dataTextureRenderers.edgesRenderer&&this._dataTextureRenderers.edgesRenderer.drawLayer(t,this,eo.EDGES_HIGHLIGHTED)}},{key:"drawEdgesSelected",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&this._dataTextureRenderers.edgesRenderer&&this._dataTextureRenderers.edgesRenderer.drawLayer(t,this,eo.EDGES_SELECTED)}},{key:"drawEdgesXRayed",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&this._dataTextureRenderers.edgesRenderer&&this._dataTextureRenderers.edgesRenderer.drawLayer(t,this,eo.EDGES_XRAYED)}},{key:"drawOcclusion",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._dataTextureRenderers.occlusionRenderer&&this._dataTextureRenderers.occlusionRenderer.drawLayer(t,this,eo.COLOR_OPAQUE))}},{key:"drawShadow",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._dataTextureRenderers.shadowRenderer&&this._dataTextureRenderers.shadowRenderer.drawLayer(t,this,eo.COLOR_OPAQUE))}},{key:"setPickMatrices",value:function(e,t){0!==this._numVisibleLayerPortions&&this._dataTextureState.texturePickCameraMatrices.updateViewMatrix(e,t)}},{key:"drawPickMesh",value:function(e,t){0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._dataTextureRenderers.pickMeshRenderer&&this._dataTextureRenderers.pickMeshRenderer.drawLayer(t,this,eo.PICK))}},{key:"drawPickDepths",value:function(e,t){0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._dataTextureRenderers.pickDepthRenderer&&this._dataTextureRenderers.pickDepthRenderer.drawLayer(t,this,eo.PICK))}},{key:"drawSnapInitDepthBuf",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._dataTextureRenderers.snapDepthBufInitRenderer&&this._dataTextureRenderers.snapDepthBufInitRenderer.drawLayer(t,this,eo.PICK))}},{key:"drawSnapDepths",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._dataTextureRenderers.vertexDepthRenderer&&this._dataTextureRenderers.vertexDepthRenderer.drawLayer(t,this,eo.PICK))}},{key:"drawPickNormals",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._dataTextureRenderers.pickNormalsRenderer&&this._dataTextureRenderers.pickNormalsRenderer.drawLayer(t,this,eo.PICK))}},{key:"destroy",value:function(){if(!this._destroyed){var e=this._state;e.metallicRoughnessBuf&&(e.metallicRoughnessBuf.destroy(),e.metallicRoughnessBuf=null),this.model.scene.off(this._onSceneRendering),e.destroy(),this._destroyed=!0}}}]),e}(),of=Z.vec3();Z.mat4();var lf=Z.vec3([1,1,1]),uf=Z.vec3([0,0,0]),cf=Z.vec3([0,0,0]),ff=Z.identityQuaternion();Z.identityMat4();var pf=new Uint8Array([255,255,255]),Af=function(e){I(n,ve);var t=m(n);function n(e){var r,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return b(this,n),(r=t.call(this,e,i))._dtxEnabled=r.scene.dtxEnabled&&!1!==i.dtxEnabled,r._enableVertexWelding=!1,r._enableIndexBucketing=!0,r._vboBatchingLayerScratchMemory=$s(),r._textureTranscoder=i.textureTranscoder||$u(r.scene.viewer),r._maxGeometryBatchSize=i.maxGeometryBatchSize,r._aabb=Z.collapseAABB3(),r._aabbDirty=!1,r._quantizationRanges={},r._vboInstancingLayers={},r._vboBatchingLayers={},r._dtxLayers={},r.layerList=[],r._entityList=[],r._geometries={},r._dtxBuckets={},r._textures={},r._textureSets={},r._meshes={},r._entities={},r._scheduledMeshes={},r.renderFlags=new $i,r.numGeometries=0,r.numPortions=0,r.numVisibleLayerPortions=0,r.numTransparentLayerPortions=0,r.numXRayedLayerPortions=0,r.numHighlightedLayerPortions=0,r.numSelectedLayerPortions=0,r.numEdgesLayerPortions=0,r.numPickableLayerPortions=0,r.numClippableLayerPortions=0,r.numCulledLayerPortions=0,r.numEntities=0,r._numTriangles=0,r._numLines=0,r._numPoints=0,r._edgeThreshold=i.edgeThreshold||10,r._origin=Z.vec3(i.origin||[0,0,0]),r._position=Z.vec3(i.position||[0,0,0]),r._rotation=Z.vec3(i.rotation||[0,0,0]),r._quaternion=Z.vec4(i.quaternion||[0,0,0,1]),i.rotation&&Z.eulerToQuaternion(r._rotation,"XYZ",r._quaternion),r._scale=Z.vec3(i.scale||[1,1,1]),r._sceneModelMatrix=Z.mat4(),Z.composeMat4(r._position,r._quaternion,r._scale,r._sceneModelMatrix),r._worldNormalMatrix=Z.mat4(),Z.inverseMat4(r._sceneModelMatrix,r._worldNormalMatrix),Z.transposeMat4(r._worldNormalMatrix),(i.matrix||i.position||i.rotation||i.scale||i.quaternion)&&(r._viewMatrix=Z.mat4(),r._viewNormalMatrix=Z.mat4(),r._viewMatrixDirty=!0,r._sceneModelMatrixNonIdentity=!0),r._opacity=1,r._colorize=[1,1,1],r._saoEnabled=!1!==i.saoEnabled,r._pbrEnabled=!1!==i.pbrEnabled,r._colorTextureEnabled=!1!==i.colorTextureEnabled,r._isModel=i.isModel,r._isModel&&r.scene._registerModel(g(r)),r._onCameraViewMatrix=r.scene.camera.on("matrix",(function(){r._viewMatrixDirty=!0})),r.scene.vfc.enabled&&(r._vfcManager=r.scene.vfc.getVFCManager(g(r))),r._createDefaultTextureSet(),r.visible=i.visible,r.culled=i.culled,r.pickable=i.pickable,r.clippable=i.clippable,r.collidable=i.collidable,r.castsShadow=i.castsShadow,r.receivesShadow=i.receivesShadow,r.xrayed=i.xrayed,r.highlighted=i.highlighted,r.selected=i.selected,r.edges=i.edges,r.colorize=i.colorize,r.opacity=i.opacity,r.backfaces=i.backfaces,r}return P(n,[{key:"_createDefaultTextureSet",value:function(){var e=new Vu({id:"defaultColorTexture",texture:new Fa({gl:this.scene.canvas.gl,preloadColor:[1,1,1,1]})}),t=new Vu({id:"defaultMetalRoughTexture",texture:new Fa({gl:this.scene.canvas.gl,preloadColor:[0,1,1,1]})}),n=new Vu({id:"defaultNormalsTexture",texture:new Fa({gl:this.scene.canvas.gl,preloadColor:[0,0,0,0]})}),r=new Vu({id:"defaultEmissiveTexture",texture:new Fa({gl:this.scene.canvas.gl,preloadColor:[0,0,0,1]})}),i=new Vu({id:"defaultOcclusionTexture",texture:new Fa({gl:this.scene.canvas.gl,preloadColor:[1,1,1,1]})});this._textures.defaultColorTexture=e,this._textures.defaultMetalRoughTexture=t,this._textures.defaultNormalsTexture=n,this._textures.defaultEmissiveTexture=r,this._textures.defaultOcclusionTexture=i,this._textureSets.defaultTextureSet=new ku({id:"defaultTextureSet",model:this,colorTexture:e,metallicRoughnessTexture:t,normalsTexture:n,emissiveTexture:r,occlusionTexture:i})}},{key:"isPerformanceModel",get:function(){return!0}},{key:"objects",get:function(){return this._entities}},{key:"origin",get:function(){return this._origin}},{key:"position",get:function(){return this._position}},{key:"rotation",get:function(){return this._rotation}},{key:"quaternion",get:function(){return this._quaternion}},{key:"scale",get:function(){return this._scale}},{key:"matrix",get:function(){return this._sceneModelMatrix}},{key:"worldMatrix",get:function(){return this._sceneModelMatrix}},{key:"worldNormalMatrix",get:function(){return this._worldNormalMatrix}},{key:"viewMatrix",get:function(){return this._viewMatrix?(this._viewMatrixDirty&&(Z.mulMat4(this.scene.camera.viewMatrix,this._sceneModelMatrix,this._viewMatrix),Z.inverseMat4(this._viewMatrix,this._viewNormalMatrix),Z.transposeMat4(this._viewNormalMatrix),this._viewMatrixDirty=!1),this._viewMatrix):this.scene.camera.viewMatrix}},{key:"viewNormalMatrix",get:function(){return this._viewNormalMatrix?(this._viewMatrixDirty&&(Z.mulMat4(this.scene.camera.viewMatrix,this._sceneModelMatrix,this._viewMatrix),Z.inverseMat4(this._viewMatrix,this._viewNormalMatrix),Z.transposeMat4(this._viewNormalMatrix),this._viewMatrixDirty=!1),this._viewNormalMatrix):this.scene.camera.viewNormalMatrix}},{key:"backfaces",get:function(){return this._backfaces},set:function(e){e=!!e,this._backfaces=e,this.glRedraw()}},{key:"entityList",get:function(){return this._entityList}},{key:"isEntity",get:function(){return!0}},{key:"isModel",get:function(){return this._isModel}},{key:"isObject",get:function(){return!1}},{key:"aabb",get:function(){return this._aabbDirty&&this._rebuildAABB(),this._aabb}},{key:"numTriangles",get:function(){return this._numTriangles}},{key:"numLines",get:function(){return this._numLines}},{key:"numPoints",get:function(){return this._numPoints}},{key:"visible",get:function(){return this.numVisibleLayerPortions>0},set:function(e){e=!1!==e,this._visible=e;for(var t=0,n=this._entityList.length;t<n;t++)this._entityList[t].visible=e;this.glRedraw()}},{key:"xrayed",get:function(){return this.numXRayedLayerPortions>0},set:function(e){e=!!e,this._xrayed=e;for(var t=0,n=this._entityList.length;t<n;t++)this._entityList[t].xrayed=e;this.glRedraw()}},{key:"highlighted",get:function(){return this.numHighlightedLayerPortions>0},set:function(e){e=!!e,this._highlighted=e;for(var t=0,n=this._entityList.length;t<n;t++)this._entityList[t].highlighted=e;this.glRedraw()}},{key:"selected",get:function(){return this.numSelectedLayerPortions>0},set:function(e){e=!!e,this._selected=e;for(var t=0,n=this._entityList.length;t<n;t++)this._entityList[t].selected=e;this.glRedraw()}},{key:"edges",get:function(){return this.numEdgesLayerPortions>0},set:function(e){e=!!e,this._edges=e;for(var t=0,n=this._entityList.length;t<n;t++)this._entityList[t].edges=e;this.glRedraw()}},{key:"culled",get:function(){return this._culled},set:function(e){e=!!e,this._culled=e;for(var t=0,n=this._entityList.length;t<n;t++)this._entityList[t].culled=e;this.glRedraw()}},{key:"clippable",get:function(){return this._clippable},set:function(e){e=!1!==e,this._clippable=e;for(var t=0,n=this._entityList.length;t<n;t++)this._entityList[t].clippable=e;this.glRedraw()}},{key:"collidable",get:function(){return this._collidable},set:function(e){e=!1!==e,this._collidable=e;for(var t=0,n=this._entityList.length;t<n;t++)this._entityList[t].collidable=e}},{key:"pickable",get:function(){return this.numPickableLayerPortions>0},set:function(e){e=!1!==e,this._pickable=e;for(var t=0,n=this._entityList.length;t<n;t++)this._entityList[t].pickable=e}},{key:"colorize",get:function(){return this._colorize},set:function(e){this._colorize=e;for(var t=0,n=this._entityList.length;t<n;t++)this._entityList[t].colorize=e}},{key:"opacity",get:function(){return this._opacity},set:function(e){this._opacity=e;for(var t=0,n=this._entityList.length;t<n;t++)this._entityList[t].opacity=e}},{key:"castsShadow",get:function(){return this._castsShadow},set:function(e){(e=!1!==e)!==this._castsShadow&&(this._castsShadow=e,this.glRedraw())}},{key:"receivesShadow",get:function(){return this._receivesShadow},set:function(e){(e=!1!==e)!==this._receivesShadow&&(this._receivesShadow=e,this.glRedraw())}},{key:"saoEnabled",get:function(){return this._saoEnabled}},{key:"pbrEnabled",get:function(){return this._pbrEnabled}},{key:"colorTextureEnabled",get:function(){return this._colorTextureEnabled}},{key:"isDrawable",get:function(){return!0}},{key:"isStateSortable",get:function(){return!1}},{key:"xrayMaterial",get:function(){return this.scene.xrayMaterial}},{key:"highlightMaterial",get:function(){return this.scene.highlightMaterial}},{key:"selectedMaterial",get:function(){return this.scene.selectedMaterial}},{key:"edgeMaterial",get:function(){return this.scene.edgeMaterial}},{key:"getPickViewMatrix",value:function(e){return this._viewMatrix?this._viewMatrix:e}},{key:"createQuantizationRange",value:function(e){void 0!==e.id&&null!==e.id?e.aabb?this.error("[createQuantizationRange] Config missing: aabb"):this._quantizationRanges[e.id]?this.error("[createQuantizationRange] QuantizationRange already created: "+e.id):this._quantizationRanges[e.id]={id:e.id,aabb:e.aabb,matrix:Mo(e.aabb,Z.mat4())}:this.error("[createQuantizationRange] Config missing: id")}},{key:"createGeometry",value:function(e){if(void 0!==e.id&&null!==e.id)if(this._geometries[e.id])this.error("[createGeometry] Geometry already created: "+e.id);else if(void 0!==e.primitive&&null!==e.primitive||(e.primitive="triangles"),"points"===e.primitive||"lines"===e.primitive||"triangles"===e.primitive||"solid"===e.primitive||"surface"===e.primitive){if(!e.positions&&!e.positionsCompressed&&!e.buckets)return this.error("[createGeometry] Param expected: `positions`, `positionsCompressed' or 'buckets"),null;if(e.positionsCompressed&&!e.positionsDecodeMatrix&&!e.positionsDecodeBoundary)return this.error("[createGeometry] Param expected: `positionsDecodeMatrix` or 'positionsDecodeBoundary' (required for `positionsCompressed')"),null;if(e.positionsDecodeMatrix&&e.positionsDecodeBoundary)return this.error("[createGeometry] Only one of these params expected: `positionsDecodeMatrix` or 'positionsDecodeBoundary' (required for `positionsCompressed')"),null;if(e.uvCompressed&&!e.uvDecodeMatrix)return this.error("[createGeometry] Param expected: `uvDecodeMatrix` (required for `uvCompressed')"),null;if(!e.buckets&&!e.indices&&"points"!==e.primitive)return this.error("[createGeometry] Param expected: indices (required for '".concat(e.primitive,"' primitive type)")),null;if(e.positionsDecodeBoundary&&(e.positionsDecodeMatrix=Mo(e.positionsDecodeBoundary,Z.mat4())),e.positions){var t=Z.collapseAABB3();e.positionsDecodeMatrix=Z.mat4(),Z.expandAABB3Points3(t,e.positions),e.positionsCompressed=xo(e.positions,t,e.positionsDecodeMatrix)}else e.positionsDecodeMatrix=new Float64Array(e.positionsDecodeMatrix),e.positionsCompressed=new Uint16Array(e.positionsCompressed);if(e.colorsCompressed&&e.colorsCompressed.length>0)e.colorsCompressed=new Uint8Array(e.colorsCompressed);else if(e.colors&&e.colors.length>0){for(var n=e.colors,r=new Uint8Array(n.length),i=0,a=n.length;i<a;i++)r[i]=255*n[i];e.colorsCompressed=r}if(e.buckets||e.edgeIndices||"triangles"!==e.primitive&&"solid"!==e.primitive&&"surface"!==e.primitive||(e.positions?e.edgeIndices=an(e.positions,e.indices,null,5):e.edgeIndices=an(e.positionsCompressed,e.indices,e.positionsDecodeMatrix,2)),e.buckets&&(this._dtxBuckets[e.id]=e.buckets),e.uv){var s=pn.getUVBounds(e.uv),o=pn.compressUVs(e.uv,s.min,s.max);e.uvCompressed=o.quantized,e.uvDecodeMatrix=o.decodeMatrix}else e.uvCompressed&&(e.uvCompressed=new Uint16Array(e.uvCompressed),e.uvDecodeMatrix=new Float64Array(e.uvDecodeMatrix));e.normals&&(e.normals=null),this._geometries[e.id]=e,this._numTriangles+=e.indices?Math.round(e.indices.length/3):0,this.numGeometries++}else this.error("[createGeometry] Unsupported value for 'primitive': '".concat(primitive,"' - supported values are 'points', 'lines', 'triangles', 'solid' and 'surface'. Defaulting to 'triangles'."));else this.error("[createGeometry] Config missing: id")}},{key:"createTexture",value:function(e){var t=this,n=e.id;if(null!=n)if(this._textures[n])this.error("[createTexture] Texture already created: "+n);else{if(!e.src&&!e.image&&!e.buffers)return this.error("[createTexture] Param expected: `src`, `image' or 'buffers'"),null;var r=e.minFilter||1008;1006!==r&&1007!==r&&1008!==r&&1005!==r&&1004!==r&&(this.error("[createTexture] Unsupported value for 'minFilter' - \n supported values are LinearFilter, LinearMipMapNearestFilter, NearestMipMapNearestFilter, \n NearestMipMapLinearFilter and LinearMipmapLinearFilter. Defaulting to LinearMipmapLinearFilter."),r=1008);var i=e.magFilter||1006;1006!==i&&1003!==i&&(this.error("[createTexture] Unsupported value for 'magFilter' - supported values are LinearFilter and NearestFilter. Defaulting to LinearFilter."),i=1006);var a=e.wrapS||1e3;1001!==a&&1002!==a&&1e3!==a&&(this.error("[createTexture] Unsupported value for 'wrapS' - supported values are ClampToEdgeWrapping, MirroredRepeatWrapping and RepeatWrapping. Defaulting to RepeatWrapping."),a=1e3);var s=e.wrapT||1e3;1001!==s&&1002!==s&&1e3!==s&&(this.error("[createTexture] Unsupported value for 'wrapT' - supported values are ClampToEdgeWrapping, MirroredRepeatWrapping and RepeatWrapping. Defaulting to RepeatWrapping."),s=1e3);var o=e.wrapR||1e3;1001!==o&&1002!==o&&1e3!==o&&(this.error("[createTexture] Unsupported value for 'wrapR' - supported values are ClampToEdgeWrapping, MirroredRepeatWrapping and RepeatWrapping. Defaulting to RepeatWrapping."),o=1e3);var l=e.encoding||3e3;3e3!==l&&3001!==l&&(this.error("[createTexture] Unsupported value for 'encoding' - supported values are LinearEncoding and sRGBEncoding. Defaulting to LinearEncoding."),l=3e3);var u=new Fa({gl:this.scene.canvas.gl,minFilter:r,magFilter:i,wrapS:a,wrapT:s,wrapR:o,encoding:l});if(e.preloadColor&&u.setPreloadColor(e.preloadColor),e.image){var c=e.image;c.crossOrigin="Anonymous",u.setImage(c,{minFilter:r,magFilter:i,wrapS:a,wrapT:s,wrapR:o,flipY:e.flipY,encoding:l})}else if(e.src){var f=e.src.split(".").pop();switch(f){case"jpeg":case"jpg":case"png":case"gif":var p=new Image;p.onload=function(){u.setImage(p,{minFilter:r,magFilter:i,wrapS:a,wrapT:s,wrapR:o,flipY:e.flipY,encoding:l}),t.glRedraw()},p.src=e.src;break;default:this._textureTranscoder?ae.loadArraybuffer(e.src,(function(e){e.byteLength?t._textureTranscoder.transcode([e],u).then((function(){t.glRedraw()})):t.error("[createTexture] Can't create texture from 'src': file data is zero length")}),(function(e){this.error("[createTexture] Can't create texture from 'src': ".concat(e))})):this.error("[createTexture] Can't create texture from 'src' - SceneModel needs to be configured with a TextureTranscoder for this file type ('".concat(f,"')"))}}else e.buffers&&(this._textureTranscoder?this._textureTranscoder.transcode(e.buffers,u).then((function(){t.glRedraw()})):this.error("[createTexture] Can't create texture from 'buffers' - SceneModel needs to be configured with a TextureTranscoder for this option"));this._textures[n]=new Vu({id:n,texture:u})}else this.error("[createTexture] Config missing: id")}},{key:"createTextureSet",value:function(e){var t=e.id;if(null!=t)if(this._textureSets[t])this.error("[createTextureSet] Texture set already created: ".concat(t));else{var n,r,i,a,s;if(void 0!==e.colorTextureId&&null!==e.colorTextureId){if(!(n=this._textures[e.colorTextureId]))return void this.error("[createTextureSet] Texture not found: ".concat(e.colorTextureId," - ensure that you create it first with createTexture()"))}else n=this._textures.defaultColorTexture;if(void 0!==e.metallicRoughnessTextureId&&null!==e.metallicRoughnessTextureId){if(!(r=this._textures[e.metallicRoughnessTextureId]))return void this.error("[createTextureSet] Texture not found: ".concat(e.metallicRoughnessTextureId," - ensure that you create it first with createTexture()"))}else r=this._textures.defaultMetalRoughTexture;if(void 0!==e.normalsTextureId&&null!==e.normalsTextureId){if(!(i=this._textures[e.normalsTextureId]))return void this.error("[createTextureSet] Texture not found: ".concat(e.normalsTextureId," - ensure that you create it first with createTexture()"))}else i=this._textures.defaultNormalsTexture;if(void 0!==e.emissiveTextureId&&null!==e.emissiveTextureId){if(!(a=this._textures[e.emissiveTextureId]))return void this.error("[createTextureSet] Texture not found: ".concat(e.emissiveTextureId," - ensure that you create it first with createTexture()"))}else a=this._textures.defaultEmissiveTexture;if(void 0!==e.occlusionTextureId&&null!==e.occlusionTextureId){if(!(s=this._textures[e.occlusionTextureId]))return void this.error("[createTextureSet] Texture not found: ".concat(e.occlusionTextureId," - ensure that you create it first with createTexture()"))}else s=this._textures.defaultOcclusionTexture;var o=new ku({id:t,model:this,colorTexture:n,metallicRoughnessTexture:r,normalsTexture:i,emissiveTexture:a,occlusionTexture:s});this._textureSets[t]=o}else this.error("[createTextureSet] Config missing: id")}},{key:"createMesh",value:function(e){if(void 0!==e.id&&null!==e.id)if(this._scheduledMeshes[e.id])this.error("[createMesh] SceneModel already has a mesh with this ID: ".concat(e.id));else{var t=!(void 0!==e.geometryId);if(e.sceneModelMatrix=this._sceneModelMatrixNonIdentity?this._sceneModelMatrix:null,t){var n=!!this._dtxEnabled;if(void 0!==e.primitive&&null!==e.primitive||(e.primitive="triangles"),"points"!==e.primitive&&"lines"!==e.primitive&&"triangles"!==e.primitive&&"solid"!==e.primitive&&"surface"!==e.primitive)return void this.error("Unsupported value for 'primitive': '".concat(primitive,"' ('geometryId' is absent) - supported values are 'points', 'lines', 'triangles', 'solid' and 'surface'."));if(!e.positions&&!e.positionsCompressed&&!e.buckets)return this.error("Param expected: 'positions', 'positionsCompressed' or `buckets` ('geometryId' is absent)"),null;if(e.positions&&(e.positionsDecodeMatrix||e.positionsDecodeBoundary))return this.error("Illegal params: 'positions' not expected with 'positionsDecodeMatrix'/'positionsDecodeBoundary' ('geometryId' is absent)"),null;if(e.positionsCompressed&&!e.positionsDecodeMatrix&&!e.positionsDecodeBoundary)return this.error("Param expected: 'positionsCompressed' should be accompanied by 'positionsDecodeMatrix'/'positionsDecodeBoundary' ('geometryId' is absent)"),null;if(e.uvCompressed&&!e.uvDecodeMatrix)return this.error("Param expected: 'uvCompressed' should be accompanied by `uvDecodeMatrix` ('geometryId' is absent)"),null;if(!e.buckets&&!e.indices&&"points"!==e.primitive)return this.error("Param expected: indices (required for '".concat(e.primitive,"' primitive type)")),null;if((e.matrix||e.position||e.rotation||e.scale)&&(e.positionsCompressed||e.positionsDecodeBoundary))return this.error("Unexpected params: 'matrix', 'rotation', 'scale', 'position' not allowed with 'positionsCompressed'"),null;if(e.origin=e.origin?Z.addVec3(this._origin,e.origin,Z.vec3()):this._origin,e.matrix)e.meshMatrix=e.matrix;else if(e.scale||e.rotation||e.position){var r=e.scale||lf,i=e.position||uf,a=e.rotation||cf;Z.eulerToQuaternion(a,"XYZ",ff),e.meshMatrix=Z.composeMat4(i,ff,r,Z.mat4())}if(e.positionsDecodeBoundary&&(e.positionsDecodeMatrix=Mo(e.positionsDecodeBoundary,Z.mat4())),n){if(e.type=2,e.color=e.color?new Uint8Array([Math.floor(255*e.color[0]),Math.floor(255*e.color[1]),Math.floor(255*e.color[2])]):pf,e.opacity=void 0!==e.opacity&&null!==e.opacity?Math.floor(255*e.opacity):255,e.positions){var s=Z.vec3(),o=[];me(e.positions,o,s)&&(e.positions=o,e.origin=Z.addVec3(e.origin,s,s))}if(e.positions){var l=Z.collapseAABB3();e.positionsDecodeMatrix=Z.mat4(),Z.expandAABB3Points3(l,e.positions),e.positionsCompressed=xo(e.positions,l,e.positionsDecodeMatrix)}e.buckets||e.edgeIndices||"triangles"!==e.primitive&&"solid"!==e.primitive&&"surface"!==e.primitive||(e.positions?e.edgeIndices=an(e.positions,e.indices,null,2):e.edgeIndices=an(e.positionsCompressed,e.indices,e.positionsDecodeMatrix,2)),e.buckets||(e.buckets=df(e,this._enableVertexWelding&&this._enableIndexBucketing))}else{if(e.type=1,e.color=e.color?new Uint8Array([Math.floor(255*e.color[0]),Math.floor(255*e.color[1]),Math.floor(255*e.color[2])]):[255,255,255],e.opacity=void 0!==e.opacity&&null!==e.opacity?Math.floor(255*e.opacity):255,e.metallic=void 0!==e.metallic&&null!==e.metallic?Math.floor(255*e.metallic):0,e.roughness=void 0!==e.roughness&&null!==e.roughness?Math.floor(255*e.roughness):255,e.positions){var u=[];me(e.positions,u,of)&&(e.positions=u,e.origin=Z.addVec3(e.origin,of,Z.vec3()))}if(e.buckets||e.edgeIndices||"triangles"!==e.primitive&&"solid"!==e.primitive&&"surface"!==e.primitive||(e.positions?e.edgeIndices=an(e.positions,e.indices,null,2):e.edgeIndices=an(e.positionsCompressed,e.indices,e.positionsDecodeMatrix,2)),e.textureSetId&&(e.textureSet=this._textureSets[e.textureSetId],!e.textureSet))return void this.error("[createMesh] Texture set not found: ".concat(e.textureSetId," - ensure that you create it first with createTextureSet()"))}}else{if(e.positions||e.positionsCompressed||e.indices||e.edgeIndices||e.normals||e.normalsCompressed||e.uv||e.uvCompressed||e.positionsDecodeMatrix)return void this.error("Mesh geometry parameters not expected when instancing a geometry (not expected: positions, positionsCompressed, indices, edgeIndices, normals, normalsCompressed, uv, uvCompressed, positionsDecodeMatrix)");if(e.geometry=this._geometries[e.geometryId],!e.geometry)return void this.error("[createMesh] Geometry not found: ".concat(e.geometryId," - ensure that you create it first with createGeometry()"));if(e.origin=e.origin?Z.addVec3(this._origin,e.origin,Z.vec3()):this._origin,e.positionsDecodeMatrix=e.geometry.positionsDecodeMatrix,e.matrix)e.meshMatrix=e.matrix.slice();else{var c=e.scale||lf,f=e.position||uf,p=e.rotation||cf;Z.eulerToQuaternion(p,"XYZ",ff),e.meshMatrix=Z.composeMat4(f,ff,c,Z.mat4())}if(!!this._dtxEnabled){e.type=2,e.color=e.color?new Uint8Array([Math.floor(255*e.color[0]),Math.floor(255*e.color[1]),Math.floor(255*e.color[2])]):pf,e.opacity=void 0!==e.opacity&&null!==e.opacity?Math.floor(255*e.opacity):255;var A=this._dtxBuckets[e.geometryId];A||(A=df(e.geometry,this._enableVertexWelding,this._enableIndexBucketing),this._dtxBuckets[e.geometryId]=A),e.buckets=A}else e.type=0,e.color=e.color?new Uint8Array([Math.floor(255*e.color[0]),Math.floor(255*e.color[1]),Math.floor(255*e.color[2])]):pf,e.opacity=void 0!==e.opacity&&null!==e.opacity?Math.floor(255*e.opacity):255,e.metallic=void 0!==e.metallic&&null!==e.metallic?Math.floor(255*e.metallic):0,e.roughness=void 0!==e.roughness&&null!==e.roughness?Math.floor(255*e.roughness):255,e.textureSetId&&(e.textureSet=this._textureSets[e.textureSetId]),function(e){if(e.obb=Z.OBB3(),e.positionsCompressed&&e.positionsCompressed.length>0){var t=Z.collapseAABB3();Z.expandAABB3Points3(t,e.positionsCompressed),pn.decompressAABB(t,e.positionsDecodeMatrix),Z.AABB3ToOBB3(t,e.obb)}else if(e.positions&&e.positions.length>0){var n=Z.collapseAABB3();Z.expandAABB3Points3(n,e.positions),Z.AABB3ToOBB3(n,e.obb)}}(e.geometry)}e.numPrimitives=this._getNumPrimitives(e),this._vfcManager&&!this._vfcManager.finalized?this._vfcManager.addMesh(e):this._createMesh(e)}else this.error("[createMesh] SceneModel.createMesh() config missing: id")}},{key:"_createMesh",value:function(e){var t=new qs(this,e.id,e.color,e.opacity);t.pickId=this.scene._renderer.getPickID(t);var n=t.pickId,r=n>>24&255,i=n>>16&255,a=n>>8&255,s=255&n;switch(e.pickColor=new Uint8Array([s,a,i,r]),e.worldAABB=Z.collapseAABB3(),e.aabb=e.worldAABB,e.solid="solid"===e.primitive,t.origin=Z.vec3(e.origin),e.type){case 2:t.layer=this._getDTXLayer(e);break;case 1:t.layer=this._getVBOBatchingLayer(e);break;case 0:t.layer=this._getVBOInstancingLayer(e)}t.portionId=t.layer.createPortion(e),t.aabb=e.worldAABB,t.numPrimitives=e.numPrimitives,Z.expandAABB3(this._aabb,t.aabb),this._meshes[e.id]=t}},{key:"_getNumPrimitives",value:function(e){var t=0;switch(e.geometry?e.geometry.primitive:e.primitive){case"triangles":case"solid":case"surface":switch(e.type){case 2:for(var n=0,r=e.buckets.length;n<r;n++)t+=e.buckets[n].indices.length;break;case 1:t+=e.indices.length;break;case 0:t+=e.geometry.indices.length}return Math.round(t/3);case"points":switch(e.type){case 2:for(var i=0,a=e.buckets.length;i<a;i++)t+=e.buckets[i].positionsCompressed.length;break;case 1:case 0:t+=e.positions?e.positions.length:e.positionsCompressed.length}return Math.round(t);case"lines":case"line-strip":switch(e.type){case 2:for(var s=0,o=e.buckets.length;s<o;s++)t+=e.buckets[s].indices.length;break;case 1:t+=e.indices.length;break;case 0:t+=e.geometry.indices.length}return Math.round(t/2)}return 0}},{key:"_getDTXLayer",value:function(e){var t=e.origin,n="".concat(Math.round(t[0]),".").concat(Math.round(t[1]),".").concat(Math.round(t[2])),r=this._dtxLayers[n];if(r){if(r.canCreatePortion(e))return r;r.finalize(),delete this._dtxLayers[n],r=null}return console.log("[SceneModel ".concat(this.id,"]: creating TrianglesDataTextureLayer")),r=new sf(this,{layerIndex:0,origin:t}),this._dtxLayers[n]=r,this.layerList.push(r),r}},{key:"_getVBOBatchingLayer",value:function(e){var t=this,n=e.origin,r=e.positionsDecodeMatrix||e.positionsDecodeBoundary?this._createHashStringFromMatrix(e.positionsDecodeMatrix||e.positionsDecodeBoundary):"-",i=e.textureSetId||"-",a="".concat(Math.round(n[0]),".").concat(Math.round(n[1]),".").concat(Math.round(n[2]),".").concat(e.primitive,".").concat(r,".").concat(i),s=this._vboBatchingLayers[a];if(s)return s;for(var o=e.textureSet;!s;){switch(e.primitive){case"triangles":case"solid":case"surface":console.log("[SceneModel ".concat(this.id,"]: creating TrianglesBatchingLayer")),s=new il({model:t,textureSet:o,layerIndex:0,scratchMemory:this._vboBatchingLayerScratchMemory,positionsDecodeMatrix:e.positionsDecodeMatrix,uvDecodeMatrix:e.uvDecodeMatrix,origin:n,maxGeometryBatchSize:this._maxGeometryBatchSize,solid:"solid"===e.primitive,autoNormals:!0});break;case"lines":console.log("[SceneModel ".concat(this.id,"]: creating LinesBatchingLayer")),s=new Zl({model:t,layerIndex:0,scratchMemory:this._vboBatchingLayerScratchMemory,positionsDecodeMatrix:e.positionsDecodeMatrix,uvDecodeMatrix:e.uvDecodeMatrix,origin:n,maxGeometryBatchSize:this._maxGeometryBatchSize});break;case"points":console.log("[SceneModel ".concat(this.id,"]: creating PointsBatchingLayer")),s=new bu({model:t,layerIndex:0,scratchMemory:this._vboBatchingLayerScratchMemory,positionsDecodeMatrix:e.positionsDecodeMatrix,uvDecodeMatrix:e.uvDecodeMatrix,origin:n,maxGeometryBatchSize:this._maxGeometryBatchSize})}var l=e.positionsCompressed?e.positionsCompressed.length:e.positions.length;("points"===e.primitive?s.canCreatePortion(l):s.canCreatePortion(l,e.indices.length))||(s.finalize(),delete this._vboBatchingLayers[a],s=null)}return this._vboBatchingLayers[a]=s,this.layerList.push(s),s}},{key:"_createHashStringFromMatrix",value:function(e){for(var t=e.join(""),n=0,r=0;r<t.length;r++){n=(n<<5)-n+t.charCodeAt(r),n|=0}return(n>>>0).toString(16)}},{key:"_getVBOInstancingLayer",value:function(e){var t=this,n=e.origin,r=e.textureSetId||"-",i=e.geometryId,a="".concat(Math.round(n[0]),".").concat(Math.round(n[1]),".").concat(Math.round(n[2]),".").concat(r,".").concat(i),s=this._vboInstancingLayers[a];if(s)return s;for(var o=e.textureSet,l=e.geometry;!s;)switch(l.primitive){case"triangles":case"surface":console.log("[SceneModel ".concat(this.id,"]: creating TrianglesInstancingLayer")),s=new Vl({model:t,textureSet:o,geometry:l,origin:n,layerIndex:0,solid:!1});break;case"solid":console.log("[SceneModel ".concat(this.id,"]: creating TrianglesInstancingLayer")),s=new Vl({model:t,textureSet:o,geometry:l,origin:n,layerIndex:0,solid:!0});break;case"lines":console.log("[SceneModel ".concat(this.id,"]: creating LinesInstancingLayer")),s=new uu({model:t,textureSet:o,geometry:l,origin:n,layerIndex:0});break;case"points":console.log("[SceneModel ".concat(this.id,"]: creating PointsInstancingLayer")),s=new Gu({model:t,textureSet:o,geometry:l,origin:n,layerIndex:0})}return this._vboInstancingLayers[a]=s,this.layerList.push(s),s}},{key:"createEntity",value:function(e){if(void 0===e.id?e.id=Z.createUUID():this.scene.components[e.id]&&(this.error("Scene already has a Component with this ID: ".concat(e.id," - will assign random ID")),e.id=Z.createUUID()),void 0!==e.meshIds){var t=0;if(this._visible&&!1!==e.visible&&(t|=Te),this._pickable&&!1!==e.pickable&&(t|=be),this._culled&&!1!==e.culled&&(t|=Ee),this._clippable&&!1!==e.clippable&&(t|=De),this._collidable&&!1!==e.collidable&&(t|=Pe),this._edges&&!1!==e.edges&&(t|=Be),this._xrayed&&!1!==e.xrayed&&(t|=Re),this._highlighted&&!1!==e.highlighted&&(t|=Ce),this._selected&&!1!==e.selected&&(t|=_e),e.flags=t,this._vfcManager&&!this._vfcManager.finalized){for(var n=0,r=e.meshIds.length;n<r;n++){var i=e.meshIds[n];if(this._scheduledMeshes[i])return void this.error("[createEntity] Mesh not found: ".concat(i))}this._vfcManager.addEntity(e)}else this._createEntity(e)}else this.error("Config missing: meshIds")}},{key:"_createEntity",value:function(e){for(var t=[],n=Z.collapseAABB3(),r=0,i=e.meshIds.length;r<i;r++){var a=e.meshIds[r],s=this._meshes[a];s?s.parent?this.error('Mesh with ID "'.concat(a,'" already belongs to object with ID "').concat(s.parent.id,'" - ignoring this mesh')):(Z.expandAABB3(n,s.aabb),t.push(s)):this.error('Mesh with this ID not found: "'.concat(a,'" - ignoring this mesh'))}var o=new Ne(this,e.isObject,e.id,t,e.flags,n,!0);this._entityList.push(o),this._entities[e.id]=o,this.numEntities++}},{key:"finalize",value:function(){if(!this.destroyed){this._vfcManager&&this._vfcManager.finalize((function(){}));for(var e=0,t=this.layerList.length;e<t;e++){this.layerList[e].finalize()}this._geometries={},this._dtxBuckets={},this._textures={},this._textureSets={},this._dtxLayers={},this._vboInstancingLayers={},this._vboBatchingLayers={};for(var n=0,r=this._entityList.length;n<r;n++){this._entityList[n]._finalize()}for(var i=0,a=this._entityList.length;i<a;i++){this._entityList[i]._finalize2()}this.layerList.sort((function(e,t){return e.sortId<t.sortId?-1:e.sortId>t.sortId?1:0}));for(var s=0,o=this.layerList.length;s<o;s++){this.layerList[s].layerIndex=s}this.glRedraw(),this.scene._aabbDirty=!0,this.scene.lod.enabled&&(this._lodManager=this.scene.lod.getLODManager(this))}}},{key:"_rebuildAABB",value:function(){Z.collapseAABB3(this._aabb);for(var e=0,t=this._entityList.length;e<t;e++){var n=this._entityList[e];Z.expandAABB3(this._aabb,n.aabb)}this._aabbDirty=!1}},{key:"stateSortCompare",value:function(e,t){}},{key:"rebuildRenderFlags",value:function(){this.renderFlags.reset(),this._updateRenderFlagsVisibleLayers(),this.renderFlags.numLayers>0&&0===this.renderFlags.numVisibleLayers?this.renderFlags.culled=!0:this._updateRenderFlags()}},{key:"_updateRenderFlagsVisibleLayers",value:function(){var e=this.renderFlags;e.numLayers=this.layerList.length,e.numVisibleLayers=0;for(var t=0,n=this.layerList.length;t<n;t++){var r=this.layerList[t];this._getActiveSectionPlanesForLayer(r)&&(e.visibleLayers[e.numVisibleLayers++]=t)}}},{key:"_getActiveSectionPlanesForLayer",value:function(e){var t=this.renderFlags,n=this.scene._sectionPlanesState.sectionPlanes,r=n.length,i=e.layerIndex*r;if(r>0)for(var a=0;a<r;a++){n[a].active?(t.sectionPlanesActivePerLayer[i+a]=!0,t.sectioned=!0):t.sectionPlanesActivePerLayer[i+a]=!1}return!0}},{key:"_updateRenderFlags",value:function(){if(0!==this.numVisibleLayerPortions&&this.numCulledLayerPortions!==this.numPortions){var e=this.renderFlags;if(e.colorOpaque=this.numTransparentLayerPortions<this.numPortions,this.numTransparentLayerPortions>0&&(e.colorTransparent=!0),this.numXRayedLayerPortions>0){var t=this.scene.xrayMaterial._state;t.fill&&(t.fillAlpha<1?e.xrayedSilhouetteTransparent=!0:e.xrayedSilhouetteOpaque=!0),t.edges&&(t.edgeAlpha<1?e.xrayedEdgesTransparent=!0:e.xrayedEdgesOpaque=!0)}if(this.numEdgesLayerPortions>0)this.scene.edgeMaterial._state.edges&&(e.edgesOpaque=this.numTransparentLayerPortions<this.numPortions,this.numTransparentLayerPortions>0&&(e.edgesTransparent=!0));if(this.numSelectedLayerPortions>0){var n=this.scene.selectedMaterial._state;n.fill&&(n.fillAlpha<1?e.selectedSilhouetteTransparent=!0:e.selectedSilhouetteOpaque=!0),n.edges&&(n.edgeAlpha<1?e.selectedEdgesTransparent=!0:e.selectedEdgesOpaque=!0)}if(this.numHighlightedLayerPortions>0){var r=this.scene.highlightMaterial._state;r.fill&&(r.fillAlpha<1?e.highlightedSilhouetteTransparent=!0:e.highlightedSilhouetteOpaque=!0),r.edges&&(r.edgeAlpha<1?e.highlightedEdgesTransparent=!0:e.highlightedEdgesOpaque=!0)}}}},{key:"drawColorOpaque",value:function(e){for(var t=this.renderFlags,n=0,r=t.visibleLayers.length;n<r;n++){var i=t.visibleLayers[n];this.layerList[i].drawColorOpaque(t,e)}}},{key:"drawColorTransparent",value:function(e){for(var t=this.renderFlags,n=0,r=t.visibleLayers.length;n<r;n++){var i=t.visibleLayers[n];this.layerList[i].drawColorTransparent(t,e)}}},{key:"drawDepth",value:function(e){for(var t=this.renderFlags,n=0,r=t.visibleLayers.length;n<r;n++){var i=t.visibleLayers[n];this.layerList[i].drawDepth(t,e)}}},{key:"drawNormals",value:function(e){for(var t=this.renderFlags,n=0,r=t.visibleLayers.length;n<r;n++){var i=t.visibleLayers[n];this.layerList[i].drawNormals(t,e)}}},{key:"drawSilhouetteXRayed",value:function(e){for(var t=this.renderFlags,n=0,r=t.visibleLayers.length;n<r;n++){var i=t.visibleLayers[n];this.layerList[i].drawSilhouetteXRayed(t,e)}}},{key:"drawSilhouetteHighlighted",value:function(e){for(var t=this.renderFlags,n=0,r=t.visibleLayers.length;n<r;n++){var i=t.visibleLayers[n];this.layerList[i].drawSilhouetteHighlighted(t,e)}}},{key:"drawSilhouetteSelected",value:function(e){for(var t=this.renderFlags,n=0,r=t.visibleLayers.length;n<r;n++){var i=t.visibleLayers[n];this.layerList[i].drawSilhouetteSelected(t,e)}}},{key:"drawEdgesColorOpaque",value:function(e){for(var t=this.renderFlags,n=0,r=t.visibleLayers.length;n<r;n++){var i=t.visibleLayers[n];this.layerList[i].drawEdgesColorOpaque(t,e)}}},{key:"drawEdgesColorTransparent",value:function(e){for(var t=this.renderFlags,n=0,r=t.visibleLayers.length;n<r;n++){var i=t.visibleLayers[n];this.layerList[i].drawEdgesColorTransparent(t,e)}}},{key:"drawEdgesXRayed",value:function(e){for(var t=this.renderFlags,n=0,r=t.visibleLayers.length;n<r;n++){var i=t.visibleLayers[n];this.layerList[i].drawEdgesXRayed(t,e)}}},{key:"drawEdgesHighlighted",value:function(e){for(var t=this.renderFlags,n=0,r=t.visibleLayers.length;n<r;n++){var i=t.visibleLayers[n];this.layerList[i].drawEdgesHighlighted(t,e)}}},{key:"drawEdgesSelected",value:function(e){for(var t=this.renderFlags,n=0,r=t.visibleLayers.length;n<r;n++){var i=t.visibleLayers[n];this.layerList[i].drawEdgesSelected(t,e)}}},{key:"drawOcclusion",value:function(e){if(0!==this.numVisibleLayerPortions)for(var t=this.renderFlags,n=0,r=t.visibleLayers.length;n<r;n++){var i=t.visibleLayers[n];this.layerList[i].drawOcclusion(t,e)}}},{key:"drawShadow",value:function(e){if(0!==this.numVisibleLayerPortions)for(var t=this.renderFlags,n=0,r=t.visibleLayers.length;n<r;n++){var i=t.visibleLayers[n];this.layerList[i].drawShadow(t,e)}}},{key:"setPickMatrices",value:function(e,t){if(0!==this._numVisibleLayerPortions)for(var n=this.renderFlags,r=0,i=n.visibleLayers.length;r<i;r++){var a=n.visibleLayers[r],s=this.layerList[a];s.setPickMatrices&&s.setPickMatrices(e,t)}}},{key:"drawPickMesh",value:function(e){if(0!==this.numVisibleLayerPortions)for(var t=this.renderFlags,n=0,r=t.visibleLayers.length;n<r;n++){var i=t.visibleLayers[n];this.layerList[i].drawPickMesh(t,e)}}},{key:"drawPickDepths",value:function(e){if(0!==this.numVisibleLayerPortions)for(var t=this.renderFlags,n=0,r=t.visibleLayers.length;n<r;n++){var i=t.visibleLayers[n];this.layerList[i].drawPickDepths(t,e)}}},{key:"drawPickNormals",value:function(e){if(0!==this.numVisibleLayerPortions)for(var t=this.renderFlags,n=0,r=t.visibleLayers.length;n<r;n++){var i=t.visibleLayers[n];this.layerList[i].drawPickNormals(t,e)}}},{key:"drawSnapInitDepthBuf",value:function(e){if(0!==this.numVisibleLayerPortions)for(var t=this.renderFlags,n=0,r=t.visibleLayers.length;n<r;n++){var i=t.visibleLayers[n],a=this.layerList[i];a.drawSnapInitDepthBuf&&(e.snapPickOrigin=[0,0,0],e.snapPickCoordinateScale=[1,1,1],e.snapPickLayerNumber++,a.drawSnapInitDepthBuf(t,e),e.snapPickLayerParams[e.snapPickLayerNumber]={origin:e.snapPickOrigin.slice(),coordinateScale:e.snapPickCoordinateScale.slice()})}}},{key:"drawSnapDepths",value:function(e){if(0!==this.numVisibleLayerPortions)for(var t=this.renderFlags,n=0,r=t.visibleLayers.length;n<r;n++){var i=t.visibleLayers[n],a=this.layerList[i];a.drawSnapDepths&&(e.snapPickOrigin=[0,0,0],e.snapPickCoordinateScale=[1,1,1],e.snapPickLayerNumber++,a.drawSnapDepths(t,e),e.snapPickLayerParams[e.snapPickLayerNumber]={origin:e.snapPickOrigin.slice(),coordinateScale:e.snapPickCoordinateScale.slice()})}}},{key:"destroy",value:function(){for(var e in this._vboBatchingLayers)this._vboBatchingLayers.hasOwnProperty(e)&&this._vboBatchingLayers[e].destroy();for(var t in this._vboBatchingLayers={},this._vboInstancingLayers)this._vboInstancingLayers.hasOwnProperty(t)&&this._vboInstancingLayers[t].destroy();this._vboInstancingLayers={},this.scene.camera.off(this._onCameraViewMatrix);for(var r=0,i=this.layerList.length;r<i;r++)this.layerList[r].destroy();this.layerList=[];for(var a=0,s=this._entityList.length;a<s;a++)this._entityList[a]._destroy();this._geometries={},this._dtxBuckets={},this._textures={},this._textureSets={},this._meshes={},this._entities={},this.scene._aabbDirty=!0,this._isModel&&this.scene._deregisterModel(this),0!==Zs&&0==--Zs&&Js._clear(),this._vfcManager&&this.scene.vfc.putVFCManager(this._vfcManager),this._lodManager&&this.scene.lod.putLODManager(this._lodManager),v(T(n.prototype),"destroy",this).call(this)}}]),n}();function df(e,t,n){var r,i,a,s;if(t){var o=p(rc({positionsCompressed:e.positionsCompressed,indices:e.indices,edgeIndices:e.edgeIndices}),3);r=o[0],i=o[1],a=o[2]}else r=e.positionsCompressed,i=e.indices,a=e.edgeIndices;n?s=function(e,t){var n=arguments.length>2&&void 0!==arguments[2]&&arguments[2],r=e.positionsCompressed||[],i=sc(e.indices||[],t),a=uc(e.edgeIndices||[]);function s(e,t){if(e>t){var n=e;e=t,t=n}function r(n,r){return n!==e?e-n:r!==t?t-r:0}for(var i=0,s=(a.length>>1)-1;i<=s;){var o=s+i>>1,l=r(a[2*o],a[2*o+1]);if(l>0)i=o+1;else{if(!(l<0))return o;s=o-1}}return-i-1}var o=new Int32Array(a.length/2);o.fill(0);var l=r.length/3;if(l>8*(1<<t))return[e];var u=new Int32Array(l);u.fill(-1);var c=[];function f(){u.fill(-1);var e={positionsCompressed:[],indices:[],edgeIndices:[],maxNumPositions:(1<<t)-t,numPositions:0,bucketNumber:c.length};return c.push(e),e}for(var p=f(),A=0,d=i.length;A<d;A+=3){var v=0,h=i[A],I=i[A+1],y=i[A+2];if(-1===u[h]&&v++,-1===u[I]&&v++,-1===u[y]&&v++,v+p.numPositions>p.maxNumPositions&&(p=f()),p.bucketNumber>8)return[e];-1===u[h]&&(u[h]=p.numPositions++,p.positionsCompressed.push(r[3*h]),p.positionsCompressed.push(r[3*h+1]),p.positionsCompressed.push(r[3*h+2])),-1===u[I]&&(u[I]=p.numPositions++,p.positionsCompressed.push(r[3*I]),p.positionsCompressed.push(r[3*I+1]),p.positionsCompressed.push(r[3*I+2])),-1===u[y]&&(u[y]=p.numPositions++,p.positionsCompressed.push(r[3*y]),p.positionsCompressed.push(r[3*y+1]),p.positionsCompressed.push(r[3*y+2])),p.indices.push(u[h]),p.indices.push(u[I]),p.indices.push(u[y]);var m=void 0;(m=s(h,I))>=0&&0===o[m]&&(o[m]=1,p.edgeIndices.push(u[a[2*m]]),p.edgeIndices.push(u[a[2*m+1]])),(m=s(h,y))>=0&&0===o[m]&&(o[m]=1,p.edgeIndices.push(u[a[2*m]]),p.edgeIndices.push(u[a[2*m+1]])),(m=s(I,y))>=0&&0===o[m]&&(o[m]=1,p.edgeIndices.push(u[a[2*m]]),p.edgeIndices.push(u[a[2*m+1]]))}var w=t/8*2,g=t/8,T=2*r.length+(i.length+a.length)*w,E=0;return r.length,c.forEach((function(e){E+=2*e.positionsCompressed.length+(e.indices.length+e.edgeIndices.length)*g,e.positionsCompressed.length})),E>T?[e]:(n&&cc(c,e),c)}({positionsCompressed:r,indices:i,edgeIndices:a},r.length/3>65536?16:8):s=[{positionsCompressed:r,indices:i,edgeIndices:a}];return s}var vf=function(e){I(n,Af);var t=m(n);function n(e){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return b(this,n),t.call(this,e,r)}return P(n)}(),hf=function(e){I(n,ve);var t=m(n);function n(e){var r,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return b(this,n),(r=t.call(this,e,i))._skyboxMesh=new ca(g(r),{geometry:new vn(g(r),{primitive:"triangles",positions:[1,1,1,-1,1,1,-1,-1,1,1,-1,1,1,1,1,1,-1,1,1,-1,-1,1,1,-1,1,1,1,1,1,-1,-1,1,-1,-1,1,1,-1,1,1,-1,1,-1,-1,-1,-1,-1,-1,1,-1,-1,-1,1,-1,-1,1,-1,1,-1,-1,1,1,-1,-1,-1,-1,-1,-1,1,-1,1,1,-1],uv:[.5,.6666,.25,.6666,.25,.3333,.5,.3333,.5,.6666,.5,.3333,.75,.3333,.75,.6666,.5,.6666,.5,1,.25,1,.25,.6666,.25,.6666,0,.6666,0,.3333,.25,.3333,.25,0,.5,0,.5,.3333,.25,.3333,.75,.3333,1,.3333,1,.6666,.75,.6666],indices:[0,1,2,0,2,3,4,5,6,4,6,7,8,9,10,8,10,11,12,13,14,12,14,15,16,17,18,16,18,19,20,21,22,20,22,23]}),background:!0,scale:[2e3,2e3,2e3],rotation:[0,-90,0],material:new wn(g(r),{ambient:[0,0,0],diffuse:[0,0,0],specular:[0,0,0],emissive:[1,1,1],emissiveMap:new ja(g(r),{src:i.src,flipY:!0,wrapS:"clampToEdge",wrapT:"clampToEdge",encoding:i.encoding||"sRGB"}),backfaces:!0}),visible:!1,pickable:!1,clippable:!1,collidable:!1}),r.size=i.size,r.active=i.active,r}return P(n,[{key:"size",get:function(){return this._size},set:function(e){this._size=e||1e3,this._skyboxMesh.scale=[this._size,this._size,this._size]}},{key:"active",get:function(){return this._skyboxMesh.visible},set:function(e){this._skyboxMesh.visible=e}}]),n}(),If=function(){function e(){b(this,e)}return P(e,[{key:"transcode",value:function(e,t){}},{key:"destroy",value:function(){}}]),e}(),yf=Z.vec4(),mf=Z.vec4(),wf=Z.vec3(),gf=Z.vec3(),Tf=Z.vec3(),Ef=Z.vec4(),bf=Z.vec4(),Df=Z.vec4(),Pf=function(){function e(t){b(this,e),this._scene=t}return P(e,[{key:"dollyToCanvasPos",value:function(e,t,n){var r=!1,i=this._scene.camera;if(e){var a=Z.subVec3(e,i.eye,wf);r=Z.lenVec3(a)<n}if("perspective"===i.projection){i.ortho.scale=i.ortho.scale-n;var s=this._unproject(t,Ef),o=Z.subVec3(s,i.eye,Df),l=Z.mulVec3Scalar(Z.normalizeVec3(o),-n,[]);if(i.eye=[i.eye[0]-l[0],i.eye[1]-l[1],i.eye[2]-l[2]],i.look=[i.look[0]-l[0],i.look[1]-l[1],i.look[2]-l[2]],e){var u=Z.subVec3(e,i.eye,wf),c=Z.lenVec3(u),f=Z.mulVec3Scalar(Z.normalizeVec3(Z.subVec3(i.look,i.eye,gf)),c);i.look=[i.eye[0]+f[0],i.eye[1]+f[1],i.eye[2]+f[2]]}}else if("ortho"===i.projection){var p=this._unproject(t,Ef);i.ortho.scale=i.ortho.scale-n,i.ortho._update();var A=this._unproject(t,bf),d=Z.subVec3(A,p,Df),v=Z.mulVec3Scalar(Z.normalizeVec3(Z.subVec3(i.look,i.eye,wf)),-n,gf),h=Z.addVec3(d,v,Tf);i.eye=[i.eye[0]-h[0],i.eye[1]-h[1],i.eye[2]-h[2]],i.look=[i.look[0]-h[0],i.look[1]-h[1],i.look[2]-h[2]]}return r}},{key:"_unproject",value:function(e,t){var n=this._scene.camera,r=n.project.transposedMatrix,i=r.subarray(8,12),a=r.subarray(12),s=[0,0,-1,1],o=Z.dotVec4(s,i)/Z.dotVec4(s,a);return n.project.unproject(e,o,yf,mf,t),t}},{key:"destroy",value:function(){}}]),e}(),Rf=Z.vec3(),Cf=Z.vec3(),_f=Z.vec3(),Bf=Z.vec4(),Of=Z.vec4(),Sf=Z.vec4(),Nf=function(){function e(t,n){var r=this;b(this,e),this._scene=t,this._configs=n,this._pivotWorldPos=Z.vec3(),this._cameraOffset=Z.vec3(),this._azimuth=0,this._polar=0,this._radius=0,this._pivotPosSet=!1,this._pivoting=!1,this._shown=!1,this._pivotViewPos=Z.vec4(),this._pivotProjPos=Z.vec4(),this._pivotCanvasPos=Z.vec2(),this._cameraDirty=!0,this._onViewMatrix=this._scene.camera.on("viewMatrix",(function(){r._cameraDirty=!0})),this._onProjMatrix=this._scene.camera.on("projMatrix",(function(){r._cameraDirty=!0})),this._onTick=this._scene.on("tick",(function(){r.updatePivotElement()}))}return P(e,[{key:"updatePivotElement",value:function(){var e=this._scene.camera,t=this._scene.canvas;if(this._pivoting&&this._cameraDirty){Z.transformPoint3(e.viewMatrix,this.getPivotPos(),this._pivotViewPos),this._pivotViewPos[3]=1,Z.transformPoint4(e.projMatrix,this._pivotViewPos,this._pivotProjPos);var n=t.boundary,r=n[2],i=n[3];this._pivotCanvasPos[0]=Math.floor((1+this._pivotProjPos[0]/this._pivotProjPos[3])*r/2),this._pivotCanvasPos[1]=Math.floor((1-this._pivotProjPos[1]/this._pivotProjPos[3])*i/2);var a=t._lastBoundingClientRect;if(!a||t._canvasSizeChanged){var s=t.canvas;a=t._lastBoundingClientRect=s.getBoundingClientRect()}this._pivotElement&&(this._pivotElement.style.left=Math.floor(a.left+this._pivotCanvasPos[0])-this._pivotElement.clientWidth/2+window.scrollX+"px",this._pivotElement.style.top=Math.floor(a.top+this._pivotCanvasPos[1])-this._pivotElement.clientHeight/2+window.scrollY+"px"),this._cameraDirty=!1}}},{key:"setPivotElement",value:function(e){this._pivotElement=e}},{key:"startPivot",value:function(){if(this._cameraLookingDownwards())return this._pivoting=!1,!1;var e=this._scene.camera,t=Z.lookAtMat4v(e.eye,e.look,e.worldUp);Z.transformPoint3(t,this.getPivotPos(),this._cameraOffset);var n=this.getPivotPos();this._cameraOffset[2]+=Z.distVec3(e.eye,n),t=Z.inverseMat4(t);var r=Z.transformVec3(t,this._cameraOffset),i=Z.vec3();if(Z.subVec3(e.eye,n,i),Z.addVec3(i,r),e.zUp){var a=i[1];i[1]=i[2],i[2]=a}this._radius=Z.lenVec3(i),this._polar=Math.acos(i[1]/this._radius),this._azimuth=Math.atan2(i[0],i[2]),this._pivoting=!0}},{key:"_cameraLookingDownwards",value:function(){var e=this._scene.camera,t=Z.normalizeVec3(Z.subVec3(e.look,e.eye,Rf)),n=Z.cross3Vec3(t,e.worldUp,Cf);return Z.sqLenVec3(n)<=1e-4}},{key:"getPivoting",value:function(){return this._pivoting}},{key:"setPivotPos",value:function(e){this._pivotWorldPos.set(e),this._pivotPosSet=!0}},{key:"setCanvasPivotPos",value:function(e){var t=this._scene.camera,n=Math.abs(Z.distVec3(this._scene.center,t.eye)),r=t.project.transposedMatrix,i=r.subarray(8,12),a=r.subarray(12),s=[0,0,-1,1],o=Z.dotVec4(s,i)/Z.dotVec4(s,a),l=Bf;t.project.unproject(e,o,Of,Sf,l);var u=Z.normalizeVec3(Z.subVec3(l,t.eye,Rf)),c=Z.addVec3(t.eye,Z.mulVec3Scalar(u,n,Cf),_f);this.setPivotPos(c)}},{key:"getPivotPos",value:function(){return this._pivotPosSet?this._pivotWorldPos:this._scene.camera.look}},{key:"continuePivot",value:function(e,t){if(this._pivoting&&(0!==e||0!==t)){var n=this._scene.camera,r=-e,i=-t;1===n.worldUp[2]&&(r=-r),this._azimuth+=.01*-r,this._polar+=.01*i,this._polar=Z.clamp(this._polar,.001,Math.PI-.001);var a=[this._radius*Math.sin(this._polar)*Math.sin(this._azimuth),this._radius*Math.cos(this._polar),this._radius*Math.sin(this._polar)*Math.cos(this._azimuth)];if(1===n.worldUp[2]){var s=a[1];a[1]=a[2],a[2]=s}var o=Z.lenVec3(Z.subVec3(n.look,n.eye,Z.vec3())),l=this.getPivotPos();Z.addVec3(a,l);var u=Z.lookAtMat4v(a,l,n.worldUp);u=Z.inverseMat4(u);var c=Z.transformVec3(u,this._cameraOffset);u[12]-=c[0],u[13]-=c[1],u[14]-=c[2];var f=[u[8],u[9],u[10]];n.eye=[u[12],u[13],u[14]],Z.subVec3(n.eye,Z.mulVec3Scalar(f,o),n.look),n.up=[u[4],u[5],u[6]],this.showPivot()}}},{key:"showPivot",value:function(){var e=this;this._shown||(null!==this._hideTimeout&&(window.clearTimeout(this._hideTimeout),this._hideTimeout=null),this._pivotElement&&(this.updatePivotElement(),this._pivotElement.style.visibility="visible",this._shown=!0,this._hideTimeout=window.setTimeout((function(){e.hidePivot()}),1e3)))}},{key:"hidePivot",value:function(){this._shown&&(null!==this._hideTimeout&&(window.clearTimeout(this._hideTimeout),this._hideTimeout=null),this._pivotElement&&(this._pivotElement.style.visibility="hidden"),this._shown=!1)}},{key:"endPivot",value:function(){this._pivoting=!1}},{key:"destroy",value:function(){this._scene.camera.off(this._onViewMatrix),this._scene.camera.off(this._onProjMatrix),this._scene.off(this._onTick)}}]),e}(),Lf=function(){function e(t,n){b(this,e),this._scene=t.scene,this._cameraControl=t,this._scene.canvas.canvas.oncontextmenu=function(e){e.preventDefault()},this._configs=n,this.schedulePickEntity=!1,this.schedulePickSurface=!1,this.scheduleSnapOrPick=!1,this.pickCursorPos=Z.vec2(),this.picked=!1,this.pickedSurface=!1,this.pickResult=null,this._lastPickedEntityId=null,this._needFireEvents=!1}return P(e,[{key:"update",value:function(){if(this._configs.pointerEnabled&&(this.schedulePickEntity||this.schedulePickSurface)){this.picked=!1,this.pickedSurface=!1,this.snappedOrPicked=!1,this.hoveredSnappedOrSurfaceOff=!1,this._needFireEvents=!1;var e=this._cameraControl.hasSubs("hoverSurface");if(this.scheduleSnapOrPick){var t=this._scene.snapPick({canvasPos:this.pickCursorPos,snapRadius:this._configs.snapRadius,snapMode:this._configs.snapMode});t&&t.snappedWorldPos?(this.snapPickResult=t,this.snappedOrPicked=!0,this._needFireEvents=!0):(this.schedulePickSurface=!0,this.snapPickResult=null)}if(this.schedulePickSurface&&this.pickResult&&this.pickResult.worldPos){var n=this.pickResult.canvasPos;if(n[0]===this.pickCursorPos[0]&&n[1]===this.pickCursorPos[1])return this.picked=!0,this.pickedSurface=!0,this._needFireEvents=e,this.schedulePickEntity=!1,this.schedulePickSurface=!1,this.scheduleSnapOrPick?this.snappedOrPicked=!0:this.hoveredSnappedOrSurfaceOff=!0,void(this.scheduleSnapOrPick=!1)}if(this.schedulePickEntity&&this.pickResult&&(this.pickResult.canvasPos||this.pickResult.snappedCanvasPos)){var r=this.pickResult.canvasPos||this.pickResult.snappedCanvasPos;if(r[0]===this.pickCursorPos[0]&&r[1]===this.pickCursorPos[1])return this.picked=!0,this.pickedSurface=!1,this._needFireEvents=!1,this.schedulePickEntity=!1,void(this.schedulePickSurface=!1)}this.schedulePickSurface||this.scheduleSnapOrPick&&!this.snapPickResult?(this.pickResult=this._scene.pick({pickSurface:!0,pickSurfaceNormal:!1,canvasPos:this.pickCursorPos}),this.pickResult?(this.picked=!0,this.scheduleSnapOrPick?this.snappedOrPicked=!0:this.pickedSurface=!0,this._needFireEvents=!0):this.scheduleSnapOrPick&&(this.hoveredSnappedOrSurfaceOff=!0,this._needFireEvents=!0)):(this.pickResult=this._scene.pick({canvasPos:this.pickCursorPos}),this.pickResult&&(this.picked=!0,this.pickedSurface=!1,this._needFireEvents=!0)),this.scheduleSnapOrPick=!1,this.schedulePickEntity=!1,this.schedulePickSurface=!1}}},{key:"fireEvents",value:function(){if(this._needFireEvents){if(this.hoveredSnappedOrSurfaceOff&&this._cameraControl.fire("hoverSnapOrSurfaceOff",{canvasPos:this.pickCursorPos},!0),this.snappedOrPicked)if(this.snapPickResult){var e=new it;e.worldPos=this.snapPickResult.snappedWorldPos,e.canvasPos=this.snapPickResult.snappedCanvasPos,this._cameraControl.fire("hoverSnapOrSurface",e,!0),this.snapPickResult=null}else this._cameraControl.fire("hoverSnapOrSurface",this.pickResult,!0);if(this.picked&&this.pickResult&&(this.pickResult.entity||this.pickResult.worldPos)){if(this.pickResult.entity){var t=this.pickResult.entity.id;this._lastPickedEntityId!==t&&(void 0!==this._lastPickedEntityId&&this._cameraControl.fire("hoverOut",{entity:this._scene.objects[this._lastPickedEntityId]},!0),this._cameraControl.fire("hoverEnter",this.pickResult,!0),this._lastPickedEntityId=t)}this._cameraControl.fire("hover",this.pickResult,!0),this.pickResult.worldPos&&(this.pickedSurface=!0,this._cameraControl.fire("hoverSurface",this.pickResult,!0))}else void 0!==this._lastPickedEntityId&&(this._cameraControl.fire("hoverOut",{entity:this._scene.objects[this._lastPickedEntityId]},!0),this._lastPickedEntityId=void 0),this._cameraControl.fire("hoverOff",{canvasPos:this.pickCursorPos},!0);this.pickResult=null,this._needFireEvents=!1}}},{key:"destroy",value:function(){}}]),e}(),xf=Z.vec2(),Mf=function(){function e(t,n,r,i,a){b(this,e),this._scene=t;var s,o,l,u=n.pickController,c=0,f=0,p=0,A=0,d=!1,v=Z.vec3(),h=!0,I=this._scene.canvas.canvas,y=[];function m(){var e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];I.style.cursor="move",w(),e&&g()}function w(){c=i.pointerCanvasPos[0],f=i.pointerCanvasPos[1],p=i.pointerCanvasPos[0],A=i.pointerCanvasPos[1]}function g(){u.pickCursorPos=i.pointerCanvasPos,u.schedulePickSurface=!0,u.update(),u.picked&&u.pickedSurface&&u.pickResult&&u.pickResult.worldPos?(d=!0,v.set(u.pickResult.worldPos)):d=!1}document.addEventListener("keydown",this._documentKeyDownHandler=function(e){if(r.active&&r.pointerEnabled&&t.input.keyboardEnabled){var n=e.keyCode;y[n]=!0}}),document.addEventListener("keyup",this._documentKeyUpHandler=function(e){if(r.active&&r.pointerEnabled&&t.input.keyboardEnabled){var n=e.keyCode;y[n]=!1}}),I.addEventListener("mousedown",this._mouseDownHandler=function(e){if(r.active&&r.pointerEnabled)switch(e.which){case 1:y[t.input.KEY_SHIFT]||r.planView?(s=!0,m()):(s=!0,m(!1));break;case 2:o=!0,m();break;case 3:l=!0,r.panRightClick&&m()}}),document.addEventListener("mousemove",this._documentMouseMoveHandler=function(){if(r.active&&r.pointerEnabled&&(s||o||l)){var e=t.canvas.boundary,n=e[2],u=e[3],p=i.pointerCanvasPos[0],A=i.pointerCanvasPos[1];if(y[t.input.KEY_SHIFT]||r.planView||!r.panRightClick&&o||r.panRightClick&&l){var h=p-c,I=A-f,m=t.camera;if("perspective"===m.projection){var w=Math.abs(d?Z.lenVec3(Z.subVec3(v,t.camera.eye,[])):t.camera.eyeLookDist)*Math.tan(m.perspective.fov/2*Math.PI/180);a.panDeltaX+=1.5*h*w/u,a.panDeltaY+=1.5*I*w/u}else a.panDeltaX+=.5*m.ortho.scale*(h/u),a.panDeltaY+=.5*m.ortho.scale*(I/u)}else!s||o||l||r.planView||(r.firstPerson?(a.rotateDeltaY-=(p-c)/n*r.dragRotationRate/2,a.rotateDeltaX+=(A-f)/u*(r.dragRotationRate/4)):(a.rotateDeltaY-=(p-c)/n*(1.5*r.dragRotationRate),a.rotateDeltaX+=(A-f)/u*(1.5*r.dragRotationRate)));c=p,f=A}}),I.addEventListener("mousemove",this._canvasMouseMoveHandler=function(e){r.active&&r.pointerEnabled&&i.mouseover&&(h=!0)}),document.addEventListener("mouseup",this._documentMouseUpHandler=function(e){if(r.active&&r.pointerEnabled)switch(e.which){case 1:case 2:case 3:s=!1,o=!1,l=!1}}),I.addEventListener("mouseup",this._mouseUpHandler=function(e){if(r.active&&r.pointerEnabled){if(3===e.which){!function(e,t){if(e){for(var n=e.target,r=0,i=0,a=0,s=0;n.offsetParent;)r+=n.offsetLeft,i+=n.offsetTop,a+=n.scrollLeft,s+=n.scrollTop,n=n.offsetParent;t[0]=e.pageX+a-r,t[1]=e.pageY+s-i}else e=window.event,t[0]=e.x,t[1]=e.y}(e,xf);var t=xf[0],i=xf[1];Math.abs(t-p)<3&&Math.abs(i-A)<3&&n.cameraControl.fire("rightClick",{pagePos:[Math.round(e.pageX),Math.round(e.pageY)],canvasPos:xf,event:e},!0)}I.style.removeProperty("cursor")}}),I.addEventListener("mouseenter",this._mouseEnterHandler=function(){r.active&&r.pointerEnabled});var T=1/60,E=null;I.addEventListener("wheel",this._mouseWheelHandler=function(e){if(r.active&&r.pointerEnabled){var t=performance.now()/1e3,n=null!==E?t-E:0;E=t,n>.05&&(n=.05),n<T&&(n=T);var s=Math.max(-1,Math.min(1,40*-e.deltaY));if(0!==s){var o=s/Math.abs(s);a.dollyDelta+=-o*n*r.mouseWheelDollyRate,h&&(i.followPointerDirty=!0,h=!1)}}},{passive:!0})}return P(e,[{key:"reset",value:function(){}},{key:"destroy",value:function(){var e=this._scene.canvas.canvas;document.removeEventListener("keydown",this._documentKeyDownHandler),document.removeEventListener("keyup",this._documentKeyUpHandler),e.removeEventListener("mousedown",this._mouseDownHandler),document.removeEventListener("mousemove",this._documentMouseMoveHandler),e.removeEventListener("mousemove",this._canvasMouseMoveHandler),document.removeEventListener("mouseup",this._documentMouseUpHandler),e.removeEventListener("mouseup",this._mouseUpHandler),e.removeEventListener("mouseenter",this._mouseEnterHandler),e.removeEventListener("wheel",this._mouseWheelHandler)}}]),e}(),Ff=Z.vec3(),Hf=Z.vec3(),Uf=Z.vec3(),Gf=Z.vec3(),kf=Z.vec3(),Vf={eye:Z.vec3(),look:Z.vec3(),up:Z.vec3()},jf=function(){function e(t,n,r,i){b(this,e),this._scene=t;var a=n.cameraControl,s=t.camera;this._onSceneKeyDown=t.input.on("keydown",(function(){if(r.active&&r.pointerEnabled&&t.input.keyboardEnabled&&i.mouseover){var e=a._isKeyDownForAction(a.AXIS_VIEW_RIGHT),o=a._isKeyDownForAction(a.AXIS_VIEW_BACK),l=a._isKeyDownForAction(a.AXIS_VIEW_LEFT),u=a._isKeyDownForAction(a.AXIS_VIEW_FRONT),c=a._isKeyDownForAction(a.AXIS_VIEW_TOP),f=a._isKeyDownForAction(a.AXIS_VIEW_BOTTOM);if(e||o||l||u||c||f){var p=t.aabb,A=Z.getAABB3Diag(p);Z.getAABB3Center(p,Ff);var d=Math.abs(A/Math.tan(n.cameraFlight.fitFOV*Z.DEGTORAD)),v=1.1*A;Vf.orthoScale=v,e?(Vf.eye.set(Z.addVec3(Ff,Z.mulVec3Scalar(s.worldRight,d,Hf),kf)),Vf.look.set(Ff),Vf.up.set(s.worldUp)):o?(Vf.eye.set(Z.addVec3(Ff,Z.mulVec3Scalar(s.worldForward,d,Hf),kf)),Vf.look.set(Ff),Vf.up.set(s.worldUp)):l?(Vf.eye.set(Z.addVec3(Ff,Z.mulVec3Scalar(s.worldRight,-d,Hf),kf)),Vf.look.set(Ff),Vf.up.set(s.worldUp)):u?(Vf.eye.set(Z.addVec3(Ff,Z.mulVec3Scalar(s.worldForward,-d,Hf),kf)),Vf.look.set(Ff),Vf.up.set(s.worldUp)):c?(Vf.eye.set(Z.addVec3(Ff,Z.mulVec3Scalar(s.worldUp,d,Hf),kf)),Vf.look.set(Ff),Vf.up.set(Z.normalizeVec3(Z.mulVec3Scalar(s.worldForward,1,Uf),Gf))):f&&(Vf.eye.set(Z.addVec3(Ff,Z.mulVec3Scalar(s.worldUp,-d,Hf),kf)),Vf.look.set(Ff),Vf.up.set(Z.normalizeVec3(Z.mulVec3Scalar(s.worldForward,-1,Uf)))),!r.firstPerson&&r.followPointer&&n.pivotController.setPivotPos(Ff),n.cameraFlight.duration>0?n.cameraFlight.flyTo(Vf,(function(){n.pivotController.getPivoting()&&r.followPointer&&n.pivotController.showPivot()})):(n.cameraFlight.jumpTo(Vf),n.pivotController.getPivoting()&&r.followPointer&&n.pivotController.showPivot())}}}))}return P(e,[{key:"reset",value:function(){}},{key:"destroy",value:function(){this._scene.input.off(this._onSceneKeyDown)}}]),e}(),Qf=function(){function e(t,n,r,i,a){var s=this;b(this,e),this._scene=t;var o=n.pickController,l=n.pivotController,u=n.cameraControl;this._clicks=0,this._timeout=null,this._lastPickedEntityId=null;var c=!1,f=!1,p=this._scene.canvas.canvas,A=function(e){var r;e&&e.worldPos&&(r=e.worldPos);var i=e&&e.entity?e.entity.aabb:t.aabb;if(r){var a=t.camera;Z.subVec3(a.eye,a.look,[]),n.cameraFlight.flyTo({aabb:i})}else n.cameraFlight.flyTo({aabb:i})};p.addEventListener("mousemove",this._canvasMouseMoveHandler=function(e){if(r.active&&r.pointerEnabled&&!c&&!f){var n=u.hasSubs("hover"),a=u.hasSubs("hoverOut"),l=u.hasSubs("hoverOff"),p=u.hasSubs("hoverSurface"),A=u.hasSubs("hoverSnapOrSurface");if(n||a||l||p||A)if(o.pickCursorPos=i.pointerCanvasPos,o.schedulePickEntity=!0,o.schedulePickSurface=p,o.scheduleSnapOrPick=A,o.update(),o.pickResult){if(o.pickResult.entity){var d=o.pickResult.entity.id;s._lastPickedEntityId!==d&&(void 0!==s._lastPickedEntityId&&u.fire("hoverOut",{entity:t.objects[s._lastPickedEntityId]},!0),u.fire("hoverEnter",o.pickResult,!0),s._lastPickedEntityId=d)}u.fire("hover",o.pickResult,!0),(o.pickResult.worldPos||o.pickResult.snappedWorldPos)&&u.fire("hoverSurface",o.pickResult,!0)}else void 0!==s._lastPickedEntityId&&(u.fire("hoverOut",{entity:t.objects[s._lastPickedEntityId]},!0),s._lastPickedEntityId=void 0),u.fire("hoverOff",{canvasPos:o.pickCursorPos},!0)}}),p.addEventListener("mousedown",this._canvasMouseDownHandler=function(e){if(1===e.which&&(c=!0),3===e.which&&(f=!0),1===e.which&&r.active&&r.pointerEnabled&&(i.mouseDownClientX=e.clientX,i.mouseDownClientY=e.clientY,i.mouseDownCursorX=i.pointerCanvasPos[0],i.mouseDownCursorY=i.pointerCanvasPos[1],!r.firstPerson&&r.followPointer&&(o.pickCursorPos=i.pointerCanvasPos,o.schedulePickSurface=!0,o.update(),1===e.which))){var n=o.pickResult;n&&n.worldPos?(l.setPivotPos(n.worldPos),l.startPivot()):(r.smartPivot?l.setCanvasPivotPos(i.pointerCanvasPos):l.setPivotPos(t.camera.look),l.startPivot())}}),document.addEventListener("mouseup",this._documentMouseUpHandler=function(e){1===e.which&&(c=!1),3===e.which&&(f=!1)}),p.addEventListener("mouseup",this._canvasMouseUpHandler=function(e){if(r.active&&r.pointerEnabled&&(1===e.which&&(l.hidePivot(),!(Math.abs(e.clientX-i.mouseDownClientX)>3||Math.abs(e.clientY-i.mouseDownClientY)>3)))){var a=u.hasSubs("picked"),c=u.hasSubs("pickedNothing"),f=u.hasSubs("pickedSurface"),p=u.hasSubs("doublePicked"),d=u.hasSubs("doublePickedSurface"),v=u.hasSubs("doublePickedNothing");if(!(r.doublePickFlyTo||p||d||v))return(a||c||f)&&(o.pickCursorPos=i.pointerCanvasPos,o.schedulePickEntity=!0,o.schedulePickSurface=f,o.update(),o.pickResult?(u.fire("picked",o.pickResult,!0),o.pickedSurface&&u.fire("pickedSurface",o.pickResult,!0)):u.fire("pickedNothing",{canvasPos:i.pointerCanvasPos},!0)),void(s._clicks=0);if(s._clicks++,1===s._clicks){o.pickCursorPos=i.pointerCanvasPos,o.schedulePickEntity=r.doublePickFlyTo,o.schedulePickSurface=f,o.update();var h=o.pickResult,I=o.pickedSurface;s._timeout=setTimeout((function(){h?(u.fire("picked",h,!0),I&&(u.fire("pickedSurface",h,!0),!r.firstPerson&&r.followPointer&&(n.pivotController.setPivotPos(h.worldPos),n.pivotController.startPivot()&&n.pivotController.showPivot()))):u.fire("pickedNothing",{canvasPos:i.pointerCanvasPos},!0),s._clicks=0}),r.doubleClickTimeFrame)}else{if(null!==s._timeout&&(window.clearTimeout(s._timeout),s._timeout=null),o.pickCursorPos=i.pointerCanvasPos,o.schedulePickEntity=r.doublePickFlyTo||p||d,o.schedulePickSurface=o.schedulePickEntity&&d,o.update(),o.pickResult){if(u.fire("doublePicked",o.pickResult,!0),o.pickedSurface&&u.fire("doublePickedSurface",o.pickResult,!0),r.doublePickFlyTo&&(A(o.pickResult),!r.firstPerson&&r.followPointer)){var y=o.pickResult.entity.aabb,m=Z.getAABB3Center(y);n.pivotController.setPivotPos(m),n.pivotController.startPivot()&&n.pivotController.showPivot()}}else if(u.fire("doublePickedNothing",{canvasPos:i.pointerCanvasPos},!0),r.doublePickFlyTo&&(A(),!r.firstPerson&&r.followPointer)){var w=t.aabb,g=Z.getAABB3Center(w);n.pivotController.setPivotPos(g),n.pivotController.startPivot()&&n.pivotController.showPivot()}s._clicks=0}}},!1)}return P(e,[{key:"reset",value:function(){this._clicks=0,this._lastPickedEntityId=null,this._timeout&&(window.clearTimeout(this._timeout),this._timeout=null)}},{key:"destroy",value:function(){var e=this._scene.canvas.canvas;e.removeEventListener("mousemove",this._canvasMouseMoveHandler),e.removeEventListener("mousedown",this._canvasMouseDownHandler),document.removeEventListener("mouseup",this._documentMouseUpHandler),e.removeEventListener("mouseup",this._canvasMouseUpHandler),this._timeout&&(window.clearTimeout(this._timeout),this._timeout=null)}}]),e}(),Wf=function(){function e(t,n,r,i,a){b(this,e),this._scene=t;var s=t.input,o=[],l=t.canvas.canvas,u=!0;this._onSceneMouseMove=s.on("mousemove",(function(){u=!0})),this._onSceneKeyDown=s.on("keydown",(function(e){r.active&&r.pointerEnabled&&t.input.keyboardEnabled&&i.mouseover&&(o[e]=!0,e===s.KEY_SHIFT&&(l.style.cursor="move"))})),this._onSceneKeyUp=s.on("keyup",(function(e){r.active&&r.pointerEnabled&&t.input.keyboardEnabled&&(o[e]=!1,e===s.KEY_SHIFT&&(l.style.cursor=null))})),this._onTick=t.on("tick",(function(e){if(r.active&&r.pointerEnabled&&t.input.keyboardEnabled&&i.mouseover){var l=n.cameraControl,c=e.deltaTime/1e3;if(!r.planView){var f=l._isKeyDownForAction(l.ROTATE_Y_POS,o),p=l._isKeyDownForAction(l.ROTATE_Y_NEG,o),A=l._isKeyDownForAction(l.ROTATE_X_POS,o),d=l._isKeyDownForAction(l.ROTATE_X_NEG,o),v=c*r.keyboardRotationRate;(f||p||A||d)&&(!r.firstPerson&&r.followPointer&&n.pivotController.startPivot(),f?a.rotateDeltaY+=v:p&&(a.rotateDeltaY-=v),A?a.rotateDeltaX+=v:d&&(a.rotateDeltaX-=v),!r.firstPerson&&r.followPointer&&n.pivotController.startPivot())}if(!o[s.KEY_CTRL]&&!o[s.KEY_ALT]){var h=l._isKeyDownForAction(l.DOLLY_BACKWARDS,o),I=l._isKeyDownForAction(l.DOLLY_FORWARDS,o);if(h||I){var y=c*r.keyboardDollyRate;!r.firstPerson&&r.followPointer&&n.pivotController.startPivot(),I?a.dollyDelta-=y:h&&(a.dollyDelta+=y),u&&(i.followPointerDirty=!0,u=!1)}}var m=l._isKeyDownForAction(l.PAN_FORWARDS,o),w=l._isKeyDownForAction(l.PAN_BACKWARDS,o),g=l._isKeyDownForAction(l.PAN_LEFT,o),T=l._isKeyDownForAction(l.PAN_RIGHT,o),E=l._isKeyDownForAction(l.PAN_UP,o),b=l._isKeyDownForAction(l.PAN_DOWN,o),D=(o[s.KEY_ALT]?.3:1)*c*r.keyboardPanRate;(m||w||g||T||E||b)&&(!r.firstPerson&&r.followPointer&&n.pivotController.startPivot(),b?a.panDeltaY+=D:E&&(a.panDeltaY+=-D),T?a.panDeltaX+=-D:g&&(a.panDeltaX+=D),w?a.panDeltaZ+=D:m&&(a.panDeltaZ+=-D))}}))}return P(e,[{key:"reset",value:function(){}},{key:"destroy",value:function(){this._scene.off(this._onTick),this._scene.input.off(this._onSceneMouseMove),this._scene.input.off(this._onSceneKeyDown),this._scene.input.off(this._onSceneKeyUp)}}]),e}(),zf=Z.vec3(),Kf=function(){function e(t,n,r,i,a){b(this,e),this._scene=t;var s=t.camera,o=n.pickController,l=n.pivotController,u=n.panController,c=1,f=1,p=null;this._onTick=t.on("tick",(function(){if(r.active&&r.pointerEnabled){var e="default";if(Math.abs(a.dollyDelta)<.001&&(a.dollyDelta=0),Math.abs(a.rotateDeltaX)<.001&&(a.rotateDeltaX=0),Math.abs(a.rotateDeltaY)<.001&&(a.rotateDeltaY=0),0===a.rotateDeltaX&&0===a.rotateDeltaY||(a.dollyDelta=0),r.followPointer&&--c<=0&&(c=1,0!==a.dollyDelta)){if(0===a.rotateDeltaY&&0===a.rotateDeltaX&&r.followPointer&&i.followPointerDirty&&(o.pickCursorPos=i.pointerCanvasPos,o.schedulePickSurface=!0,o.update(),o.pickResult&&o.pickResult.worldPos?p=o.pickResult.worldPos:(f=1,p=null),i.followPointerDirty=!1),p){var n=Math.abs(Z.lenVec3(Z.subVec3(p,t.camera.eye,zf)));f=n/r.dollyProximityThreshold}f<r.dollyMinSpeed&&(f=r.dollyMinSpeed)}var A=a.dollyDelta*f;if(0===a.rotateDeltaY&&0===a.rotateDeltaX||(!r.firstPerson&&r.followPointer&&l.getPivoting()?(l.continuePivot(a.rotateDeltaY,a.rotateDeltaX),l.showPivot()):(0!==a.rotateDeltaX&&(r.firstPerson?s.pitch(-a.rotateDeltaX):s.orbitPitch(a.rotateDeltaX)),0!==a.rotateDeltaY&&(r.firstPerson?s.yaw(a.rotateDeltaY):s.orbitYaw(a.rotateDeltaY))),a.rotateDeltaX*=r.rotationInertia,a.rotateDeltaY*=r.rotationInertia,e="grabbing"),Math.abs(a.panDeltaX)<.001&&(a.panDeltaX=0),Math.abs(a.panDeltaY)<.001&&(a.panDeltaY=0),Math.abs(a.panDeltaZ)<.001&&(a.panDeltaZ=0),0!==a.panDeltaX||0!==a.panDeltaY||0!==a.panDeltaZ){var d,v,h=Z.vec3();if(h[0]=a.panDeltaX,h[1]=a.panDeltaY,h[2]=a.panDeltaZ,r.constrainVertical){s.xUp?(d=s.eye[0],v=s.look[0]):s.yUp?(d=s.eye[1],v=s.look[1]):s.zUp&&(d=s.eye[2],v=s.look[2]),s.pan(h);var I=s.eye,y=s.look;s.xUp?(I[0]=d,y[0]=v):s.yUp?(I[1]=d,y[1]=v):s.zUp&&(I[2]=d,y[2]=v),s.eye=I,s.look=y}else s.pan(h);e="grabbing"}if(a.panDeltaX*=r.panInertia,a.panDeltaY*=r.panInertia,a.panDeltaZ*=r.panInertia,0!==A){if(e=A<0?"zoom-in":"zoom-out",r.firstPerson){var m,w;if(r.constrainVertical&&(s.xUp?(m=s.eye[0],w=s.look[0]):s.yUp?(m=s.eye[1],w=s.look[1]):s.zUp&&(m=s.eye[2],w=s.look[2])),r.followPointer)u.dollyToCanvasPos(p,i.pointerCanvasPos,-A)&&(i.followPointerDirty=!0);else s.pan([0,0,A]),s.ortho.scale=s.ortho.scale-A;if(r.constrainVertical){var g=s.eye,T=s.look;s.xUp?(g[0]=m,T[0]=w):s.yUp?(g[1]=m,T[1]=w):s.zUp&&(g[2]=m,T[2]=w),s.eye=g,s.look=T}}else if(r.planView){if(r.followPointer)u.dollyToCanvasPos(p,i.pointerCanvasPos,-A)&&(i.followPointerDirty=!0);else s.ortho.scale=s.ortho.scale+A,s.zoom(A)}else{if(r.followPointer)u.dollyToCanvasPos(p,i.pointerCanvasPos,-A)&&(i.followPointerDirty=!0);else s.ortho.scale=s.ortho.scale+A,s.zoom(A)}a.dollyDelta*=r.dollyInertia}o.fireEvents(),document.body.style.cursor=e}}))}return P(e,[{key:"destroy",value:function(){this._scene.off(this._onTick)}}]),e}(),Yf=function(){function e(t,n,r,i,a){b(this,e),this._scene=t;var s=this._scene.canvas.canvas;s.addEventListener("mouseenter",this._mouseEnterHandler=function(){i.mouseover=!0}),s.addEventListener("mouseleave",this._mouseLeaveHandler=function(){i.mouseover=!1,s.style.cursor=null}),document.addEventListener("mousemove",this._mouseMoveHandler=function(e){Xf(e,s,i.pointerCanvasPos)}),s.addEventListener("mousedown",this._mouseDownHandler=function(e){r.active&&r.pointerEnabled&&(Xf(e,s,i.pointerCanvasPos),i.mouseover=!0)}),s.addEventListener("mouseup",this._mouseUpHandler=function(e){r.active&&r.pointerEnabled})}return P(e,[{key:"reset",value:function(){}},{key:"destroy",value:function(){var e=this._scene.canvas.canvas;document.removeEventListener("mousemove",this._mouseMoveHandler),e.removeEventListener("mouseenter",this._mouseEnterHandler),e.removeEventListener("mouseleave",this._mouseLeaveHandler),e.removeEventListener("mousedown",this._mouseDownHandler),e.removeEventListener("mouseup",this._mouseUpHandler)}}]),e}();function Xf(e,t,n){if(e){var r=t.getBoundingClientRect(),i=r.x,a=r.y;n[0]=e.clientX-i,n[1]=e.clientY-a}else e=window.event,n[0]=e.x,n[1]=e.y;return n}var qf=function(e,t){if(e){for(var n=e.target,r=0,i=0;n.offsetParent;)r+=n.offsetLeft,i+=n.offsetTop,n=n.offsetParent;t[0]=e.pageX-r,t[1]=e.pageY-i}else e=window.event,t[0]=e.x,t[1]=e.y;return t},Jf=function(){function e(t,n,r,i,a){b(this,e),this._scene=t;var s=n.pickController,o=n.pivotController,l=Z.vec2(),u=Z.vec2(),c=Z.vec2(),f=Z.vec2(),p=[],A=this._scene.canvas.canvas,d=0,v=!1;this._onTick=t.on("tick",(function(){v=!1})),A.addEventListener("touchstart",this._canvasTouchStartHandler=function(e){if(r.active&&r.pointerEnabled){e.preventDefault();var n=e.touches,a=e.changedTouches;for(i.touchStartTime=Date.now(),1===n.length&&1===a.length&&(qf(n[0],l),r.followPointer&&(s.pickCursorPos=l,s.schedulePickSurface=!0,s.update(),r.planView||(s.picked&&s.pickedSurface&&s.pickResult&&s.pickResult.worldPos?(o.setPivotPos(s.pickResult.worldPos),!r.firstPerson&&o.startPivot()&&o.showPivot()):(r.smartPivot?o.setCanvasPivotPos(i.pointerCanvasPos):o.setPivotPos(t.camera.look),!r.firstPerson&&o.startPivot()&&o.showPivot()))));p.length<n.length;)p.push(Z.vec2());for(var u=0,c=n.length;u<c;++u)qf(n[u],p[u]);d=n.length}}),A.addEventListener("touchmove",this._canvasTouchMoveHandler=function(e){if(r.active&&r.pointerEnabled&&(e.stopPropagation(),e.preventDefault(),!v)){v=!0;var n=t.canvas.boundary,o=n[2],l=n[3],A=e.touches;if(e.touches.length===d){if(1===d){qf(A[0],u),Z.subVec2(u,p[0],f);var h=f[0],I=f[1];if(null!==i.longTouchTimeout&&(Math.abs(h)>r.longTapRadius||Math.abs(I)>r.longTapRadius)&&(clearTimeout(i.longTouchTimeout),i.longTouchTimeout=null),r.planView){var y=t.camera;if("perspective"===y.projection){var m=Math.abs(t.camera.eyeLookDist)*Math.tan(y.perspective.fov/2*Math.PI/180);a.panDeltaX+=h*m/l*r.touchPanRate,a.panDeltaY+=I*m/l*r.touchPanRate}else a.panDeltaX+=.5*y.ortho.scale*(h/l)*r.touchPanRate,a.panDeltaY+=.5*y.ortho.scale*(I/l)*r.touchPanRate}else a.rotateDeltaY-=h/o*(1*r.dragRotationRate),a.rotateDeltaX+=I/l*(1.5*r.dragRotationRate)}else if(2===d){var w=A[0],g=A[1];qf(w,u),qf(g,c);var T=Z.geometricMeanVec2(p[0],p[1]),E=Z.geometricMeanVec2(u,c),b=Z.vec2();Z.subVec2(T,E,b);var D=b[0],P=b[1],R=t.camera,C=Z.distVec2([w.pageX,w.pageY],[g.pageX,g.pageY]),_=(Z.distVec2(p[0],p[1])-C)*r.touchDollyRate;if(a.dollyDelta=_,Math.abs(_)<1)if("perspective"===R.projection){var B=s.pickResult?s.pickResult.worldPos:t.center,O=Math.abs(Z.lenVec3(Z.subVec3(B,t.camera.eye,[])))*Math.tan(R.perspective.fov/2*Math.PI/180);a.panDeltaX-=D*O/l*r.touchPanRate,a.panDeltaY-=P*O/l*r.touchPanRate}else a.panDeltaX-=.5*R.ortho.scale*(D/l)*r.touchPanRate,a.panDeltaY-=.5*R.ortho.scale*(P/l)*r.touchPanRate;i.pointerCanvasPos=E}for(var S=0;S<d;++S)qf(A[S],p[S])}}})}return P(e,[{key:"reset",value:function(){}},{key:"destroy",value:function(){var e=this._scene.canvas.canvas;e.removeEventListener("touchstart",this._canvasTouchStartHandler),e.removeEventListener("touchmove",this._canvasTouchMoveHandler),this._scene.off(this._onTick)}}]),e}(),Zf=function(e,t){if(e){for(var n=e.target,r=0,i=0;n.offsetParent;)r+=n.offsetLeft,i+=n.offsetTop,n=n.offsetParent;t[0]=e.pageX-r,t[1]=e.pageY-i}else e=window.event,t[0]=e.x,t[1]=e.y;return t},$f=function(){function e(t,n,r,i,a){b(this,e),this._scene=t;var s,o=n.pickController,l=n.cameraControl,u=[],c=new Float32Array(2),f=-1,p=-1,A=this._scene.canvas.canvas,d=function(e){var r;e&&e.worldPos&&(r=e.worldPos);var i=e?e.entity.aabb:t.aabb;if(r){var a=t.camera;Z.subVec3(a.eye,a.look,[]),n.cameraFlight.flyTo({aabb:i})}else n.cameraFlight.flyTo({aabb:i})};A.addEventListener("touchstart",this._canvasTouchStartHandler=function(e){if(r.active&&r.pointerEnabled){null!==i.longTouchTimeout&&(clearTimeout(i.longTouchTimeout),i.longTouchTimeout=null);var t=e.touches,a=e.changedTouches;if(s=Date.now(),1===t.length&&1===a.length){f=s,Zf(t[0],c);var o=c[0],l=c[1],p=t[0].pageX,A=t[0].pageY;i.longTouchTimeout=setTimeout((function(){n.cameraControl.fire("rightClick",{pagePos:[Math.round(p),Math.round(A)],canvasPos:[Math.round(o),Math.round(l)],event:e},!0),i.longTouchTimeout=null}),r.longTapTimeout)}else f=-1;for(;u.length<t.length;)u.push(new Float32Array(2));for(var d=0,v=t.length;d<v;++d)Zf(t[d],u[d]);u.length=t.length}},{passive:!0}),A.addEventListener("touchend",this._canvasTouchEndHandler=function(e){if(r.active&&r.pointerEnabled){var t=Date.now(),n=e.touches,a=e.changedTouches,s=l.hasSubs("pickedSurface");null!==i.longTouchTimeout&&(clearTimeout(i.longTouchTimeout),i.longTouchTimeout=null),0===n.length&&1===a.length&&f>-1&&t-f<150&&(p>-1&&f-p<325?(Zf(a[0],o.pickCursorPos),o.schedulePickEntity=!0,o.schedulePickSurface=s,o.update(),o.pickResult?(o.pickResult.touchInput=!0,l.fire("doublePicked",o.pickResult),o.pickedSurface&&l.fire("doublePickedSurface",o.pickResult),r.doublePickFlyTo&&d(o.pickResult)):(l.fire("doublePickedNothing"),r.doublePickFlyTo&&d()),p=-1):Z.distVec2(u[0],c)<4&&(Zf(a[0],o.pickCursorPos),o.schedulePickEntity=!0,o.schedulePickSurface=s,o.update(),o.pickResult?(o.pickResult.touchInput=!0,l.fire("picked",o.pickResult),o.pickedSurface&&l.fire("pickedSurface",o.pickResult)):l.fire("pickedNothing"),p=t),f=-1),u.length=n.length;for(var A=0,v=n.length;A<v;++A)u[A][0]=n[A].pageX,u[A][1]=n[A].pageY}},{passive:!0})}return P(e,[{key:"reset",value:function(){}},{key:"destroy",value:function(){var e=this._scene.canvas.canvas;e.removeEventListener("touchstart",this._canvasTouchStartHandler),e.removeEventListener("touchend",this._canvasTouchEndHandler)}}]),e}(),ep=function(e){I(n,ve);var t=m(n);function n(e){var r,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};b(this,n),(r=t.call(this,e,i)).PAN_LEFT=0,r.PAN_RIGHT=1,r.PAN_UP=2,r.PAN_DOWN=3,r.PAN_FORWARDS=4,r.PAN_BACKWARDS=5,r.ROTATE_X_POS=6,r.ROTATE_X_NEG=7,r.ROTATE_Y_POS=8,r.ROTATE_Y_NEG=9,r.DOLLY_FORWARDS=10,r.DOLLY_BACKWARDS=11,r.AXIS_VIEW_RIGHT=12,r.AXIS_VIEW_BACK=13,r.AXIS_VIEW_LEFT=14,r.AXIS_VIEW_FRONT=15,r.AXIS_VIEW_TOP=16,r.AXIS_VIEW_BOTTOM=17,r._keyMap={},r.scene.canvas.canvas.oncontextmenu=function(e){e.preventDefault()},r._configs={longTapTimeout:600,longTapRadius:5,active:!0,keyboardLayout:"qwerty",navMode:"orbit",planView:!1,firstPerson:!1,followPointer:!0,doublePickFlyTo:!0,panRightClick:!0,showPivot:!1,pointerEnabled:!0,constrainVertical:!1,smartPivot:!1,doubleClickTimeFrame:250,snapMode:"vertex",snapRadius:30,dragRotationRate:360,keyboardRotationRate:90,rotationInertia:0,keyboardPanRate:1,touchPanRate:1,panInertia:.5,keyboardDollyRate:10,mouseWheelDollyRate:100,touchDollyRate:.2,dollyInertia:0,dollyProximityThreshold:30,dollyMinSpeed:.04},r._states={pointerCanvasPos:Z.vec2(),mouseover:!1,followPointerDirty:!0,mouseDownClientX:0,mouseDownClientY:0,mouseDownCursorX:0,mouseDownCursorY:0,touchStartTime:null,activeTouches:[],tapStartPos:Z.vec2(),tapStartTime:-1,lastTapTime:-1,longTouchTimeout:null},r._updates={rotateDeltaX:0,rotateDeltaY:0,panDeltaX:0,panDeltaY:0,panDeltaZ:0,dollyDelta:0};var a=r.scene;return r._controllers={cameraControl:g(r),pickController:new Lf(g(r),r._configs),pivotController:new Nf(a,r._configs),panController:new Pf(a),cameraFlight:new Cs(g(r),{duration:.5})},r._handlers=[new Yf(r.scene,r._controllers,r._configs,r._states,r._updates),new Jf(r.scene,r._controllers,r._configs,r._states,r._updates),new Mf(r.scene,r._controllers,r._configs,r._states,r._updates),new jf(r.scene,r._controllers,r._configs,r._states,r._updates),new Qf(r.scene,r._controllers,r._configs,r._states,r._updates),new $f(r.scene,r._controllers,r._configs,r._states,r._updates),new Wf(r.scene,r._controllers,r._configs,r._states,r._updates)],r._cameraUpdater=new Kf(r.scene,r._controllers,r._configs,r._states,r._updates),r.navMode=i.navMode,i.planView&&(r.planView=i.planView),r.constrainVertical=i.constrainVertical,i.keyboardLayout?r.keyboardLayout=i.keyboardLayout:r.keyMap=i.keyMap,r.doublePickFlyTo=i.doublePickFlyTo,r.panRightClick=i.panRightClick,r.active=i.active,r.followPointer=i.followPointer,r.rotationInertia=i.rotationInertia,r.keyboardPanRate=i.keyboardPanRate,r.touchPanRate=i.touchPanRate,r.keyboardRotationRate=i.keyboardRotationRate,r.dragRotationRate=i.dragRotationRate,r.touchDollyRate=i.touchDollyRate,r.dollyInertia=i.dollyInertia,r.dollyProximityThreshold=i.dollyProximityThreshold,r.dollyMinSpeed=i.dollyMinSpeed,r.panInertia=i.panInertia,r.pointerEnabled=!0,r.keyboardDollyRate=i.keyboardDollyRate,r.mouseWheelDollyRate=i.mouseWheelDollyRate,r}return P(n,[{key:"keyMap",get:function(){return this._keyMap},set:function(e){if(e=e||"qwerty",ae.isString(e)){var t=this.scene.input,n={};switch(e){default:this.error("Unsupported value for 'keyMap': "+e+" defaulting to 'qwerty'");case"qwerty":n[this.PAN_LEFT]=[t.KEY_A],n[this.PAN_RIGHT]=[t.KEY_D],n[this.PAN_UP]=[t.KEY_Z],n[this.PAN_DOWN]=[t.KEY_X],n[this.PAN_BACKWARDS]=[],n[this.PAN_FORWARDS]=[],n[this.DOLLY_FORWARDS]=[t.KEY_W,t.KEY_ADD],n[this.DOLLY_BACKWARDS]=[t.KEY_S,t.KEY_SUBTRACT],n[this.ROTATE_X_POS]=[t.KEY_DOWN_ARROW],n[this.ROTATE_X_NEG]=[t.KEY_UP_ARROW],n[this.ROTATE_Y_POS]=[t.KEY_Q,t.KEY_LEFT_ARROW],n[this.ROTATE_Y_NEG]=[t.KEY_E,t.KEY_RIGHT_ARROW],n[this.AXIS_VIEW_RIGHT]=[t.KEY_NUM_1],n[this.AXIS_VIEW_BACK]=[t.KEY_NUM_2],n[this.AXIS_VIEW_LEFT]=[t.KEY_NUM_3],n[this.AXIS_VIEW_FRONT]=[t.KEY_NUM_4],n[this.AXIS_VIEW_TOP]=[t.KEY_NUM_5],n[this.AXIS_VIEW_BOTTOM]=[t.KEY_NUM_6];break;case"azerty":n[this.PAN_LEFT]=[t.KEY_Q],n[this.PAN_RIGHT]=[t.KEY_D],n[this.PAN_UP]=[t.KEY_W],n[this.PAN_DOWN]=[t.KEY_X],n[this.PAN_BACKWARDS]=[],n[this.PAN_FORWARDS]=[],n[this.DOLLY_FORWARDS]=[t.KEY_Z,t.KEY_ADD],n[this.DOLLY_BACKWARDS]=[t.KEY_S,t.KEY_SUBTRACT],n[this.ROTATE_X_POS]=[t.KEY_DOWN_ARROW],n[this.ROTATE_X_NEG]=[t.KEY_UP_ARROW],n[this.ROTATE_Y_POS]=[t.KEY_A,t.KEY_LEFT_ARROW],n[this.ROTATE_Y_NEG]=[t.KEY_E,t.KEY_RIGHT_ARROW],n[this.AXIS_VIEW_RIGHT]=[t.KEY_NUM_1],n[this.AXIS_VIEW_BACK]=[t.KEY_NUM_2],n[this.AXIS_VIEW_LEFT]=[t.KEY_NUM_3],n[this.AXIS_VIEW_FRONT]=[t.KEY_NUM_4],n[this.AXIS_VIEW_TOP]=[t.KEY_NUM_5],n[this.AXIS_VIEW_BOTTOM]=[t.KEY_NUM_6]}this._keyMap=n}else{var r=e;this._keyMap=r}}},{key:"_isKeyDownForAction",value:function(e,t){var n=this._keyMap[e];if(!n)return!1;t||(t=this.scene.input.keyDown);for(var r=0,i=n.length;r<i;r++){if(t[n[r]])return!0}return!1}},{key:"pivotElement",set:function(e){this._controllers.pivotController.setPivotElement(e)}},{key:"active",get:function(){return this._configs.active},set:function(e){this._configs.active=!1!==e}},{key:"snapMode",get:function(){return this._configs.snapMode},set:function(e){"vertex"!==(e=e||"vertex")&&"edge"!==e&&(this.error("Unsupported value for snapMode: "+e+" - supported values are 'vertex' and 'edge' - defaulting to 'vertex'"),e="vertex"),this._configs.snapMode=e}},{key:"snapRadius",get:function(){return this._configs.snapRadius},set:function(e){e=e||30,this._configs.snapRadius=e}},{key:"navMode",get:function(){return this._configs.navMode},set:function(e){"firstPerson"!==(e=e||"orbit")&&"orbit"!==e&&"planView"!==e&&(this.error("Unsupported value for navMode: "+e+" - supported values are 'orbit', 'firstPerson' and 'planView' - defaulting to 'orbit'"),e="orbit"),this._configs.firstPerson="firstPerson"===e,this._configs.planView="planView"===e,(this._configs.firstPerson||this._configs.planView)&&(this._controllers.pivotController.hidePivot(),this._controllers.pivotController.endPivot()),this._configs.navMode=e}},{key:"pointerEnabled",get:function(){return this._configs.pointerEnabled},set:function(e){this._reset(),this._configs.pointerEnabled=!!e}},{key:"_reset",value:function(){for(var e=0,t=this._handlers.length;e<t;e++){var n=this._handlers[e];n.reset&&n.reset()}this._updates.panDeltaX=0,this._updates.panDeltaY=0,this._updates.rotateDeltaX=0,this._updates.rotateDeltaY=0,this._updates.dolyDelta=0}},{key:"followPointer",get:function(){return this._configs.followPointer},set:function(e){this._configs.followPointer=!1!==e}},{key:"pivotPos",get:function(){return this._controllers.pivotController.getPivotPos()},set:function(e){this._controllers.pivotController.setPivotPos(e)}},{key:"dollyToPointer",get:function(){return this.warn("dollyToPointer property is deprecated - replaced with followPointer"),this.followPointer},set:function(e){this.warn("dollyToPointer property is deprecated - replaced with followPointer"),this.followPointer=e}},{key:"panToPointer",get:function(){return this.warn("panToPointer property is deprecated - replaced with followPointer"),!1},set:function(e){this.warn("panToPointer property is deprecated - replaced with followPointer")}},{key:"planView",get:function(){return this.warn("planView property is deprecated - replaced with navMode"),this._configs.planView},set:function(e){this._configs.planView=!!e,this._configs.firstPerson=!1,this._configs.planView&&(this._controllers.pivotController.hidePivot(),this._controllers.pivotController.endPivot()),this.warn("planView property is deprecated - replaced with navMode")}},{key:"firstPerson",get:function(){return this.warn("firstPerson property is deprecated - replaced with navMode"),this._configs.firstPerson},set:function(e){this.warn("firstPerson property is deprecated - replaced with navMode"),this._configs.firstPerson=!!e,this._configs.planView=!1,this._configs.firstPerson&&(this._controllers.pivotController.hidePivot(),this._controllers.pivotController.endPivot())}},{key:"constrainVertical",get:function(){return this._configs.constrainVertical},set:function(e){this._configs.constrainVertical=!!e}},{key:"doublePickFlyTo",get:function(){return this._configs.doublePickFlyTo},set:function(e){this._configs.doublePickFlyTo=!1!==e}},{key:"panRightClick",get:function(){return this._configs.panRightClick},set:function(e){this._configs.panRightClick=!1!==e}},{key:"rotationInertia",get:function(){return this._configs.rotationInertia},set:function(e){this._configs.rotationInertia=null!=e?e:0}},{key:"keyboardPanRate",get:function(){return this._configs.keyboardPanRate},set:function(e){this._configs.keyboardPanRate=null!=e?e:5}},{key:"touchPanRate",get:function(){return this._configs.touchPanRate},set:function(e){this._configs.touchPanRate=null!=e?e:1}},{key:"keyboardRotationRate",get:function(){return this._configs.keyboardRotationRate},set:function(e){this._configs.keyboardRotationRate=null!=e?e:90}},{key:"dragRotationRate",get:function(){return this._configs.dragRotationRate},set:function(e){this._configs.dragRotationRate=null!=e?e:360}},{key:"keyboardDollyRate",get:function(){return this._configs.keyboardDollyRate},set:function(e){this._configs.keyboardDollyRate=null!=e?e:15}},{key:"touchDollyRate",get:function(){return this._configs.touchDollyRate},set:function(e){this._configs.touchDollyRate=null!=e?e:.2}},{key:"mouseWheelDollyRate",get:function(){return this._configs.mouseWheelDollyRate},set:function(e){this._configs.mouseWheelDollyRate=null!=e?e:100}},{key:"dollyInertia",get:function(){return this._configs.dollyInertia},set:function(e){this._configs.dollyInertia=null!=e?e:0}},{key:"dollyProximityThreshold",get:function(){return this._configs.dollyProximityThreshold},set:function(e){this._configs.dollyProximityThreshold=null!=e?e:35}},{key:"dollyMinSpeed",get:function(){return this._configs.dollyMinSpeed},set:function(e){this._configs.dollyMinSpeed=null!=e?e:.04}},{key:"panInertia",get:function(){return this._configs.panInertia},set:function(e){this._configs.panInertia=null!=e?e:.5}},{key:"keyboardLayout",get:function(){return this._configs.keyboardLayout},set:function(e){"qwerty"!==(e=e||"qwerty")&&"azerty"!==e&&(this.error("Unsupported value for keyboardLayout - defaulting to 'qwerty'"),e="qwerty"),this._configs.keyboardLayout=e,this.keyMap=this._configs.keyboardLayout}},{key:"smartPivot",get:function(){return this._configs.smartPivot},set:function(e){this._configs.smartPivot=!1!==e}},{key:"doubleClickTimeFrame",get:function(){return this._configs.doubleClickTimeFrame},set:function(e){this._configs.doubleClickTimeFrame=null!=e?e:250}},{key:"destroy",value:function(){this._destroyHandlers(),this._destroyControllers(),this._cameraUpdater.destroy(),v(T(n.prototype),"destroy",this).call(this)}},{key:"_destroyHandlers",value:function(){for(var e=0,t=this._handlers.length;e<t;e++){var n=this._handlers[e];n.destroy&&n.destroy()}}},{key:"_destroyControllers",value:function(){for(var e=0,t=this._controllers.length;e<t;e++){var n=this._controllers[e];n.destroy&&n.destroy()}}}]),n}(),tp=P((function e(t,n,r,i,a){b(this,e),this.name=t,this.type=r,this.value=n,this.valueType=i,this.description=a})),np=P((function e(t){if(b(this,e),this.id=t.id,this.originalSystemId=t.originalSystemId,this.metaModels=[],this.name=t.name,this.type=t.type,this.properties=[],t.properties)for(var n=t.properties,r=0,i=n.length;r<i;r++){var a=n[r];this.properties.push(new tp(a.name,a.value,a.type,a.valueType,a.description))}})),rp=function(){function e(t){b(this,e),this.metaModel=null,this.metaModels=[],this.id=t.id,this.parentId=t.parentId,this.parent=null,this.originalSystemId=t.originalSystemId,this.name=t.name,this.type=t.type,this.propertySetIds=t.propertySetIds,this.propertySets=[],this.attributes=t.attributes||{}}return P(e,[{key:"getObjectIDsInSubtree",value:function(){var e=[];return function t(n){if(n){e.push(n.id);var r=n.children;if(r)for(var i=0,a=r.length;i<a;i++)t(r[i])}}(this),e}},{key:"withMetaObjectsInSubtree",value:function(e){!function t(n){if(n){e(n);var r=n.children;if(r)for(var i=0,a=r.length;i<a;i++)t(r[i])}}(this)}},{key:"getObjectIDsInSubtreeByType",value:function(e){for(var t={},n=0,r=e.length;n<r;n++)t[e[n]]=e[n];var i=[];return function e(n){if(n){t[n.type]&&i.push(n.id);var r=n.children;if(r)for(var a=0,s=r.length;a<s;a++)e(r[a])}}(this),i}},{key:"getJSON",value:function(){var e={id:this.id,type:this.type,name:this.name};return this.parent&&(e.parent=this.parent.id),e}}]),e}(),ip=function(){function e(t){b(this,e),this.id=t.id,this.projectId=t.projectId,this.revisionId=t.revisionId,this.author=t.author,this.createdAt=t.createdAt,this.creatingApplication=t.creatingApplication,this.schema=t.schema,this.metaScene=t.metaScene,this.propertySets=[],this.rootMetaObject=null,this.rootMetaObjects=[],this.metaObjects=[],this.graph=t.graph||{},this.metaScene.metaModels[this.id]=this,this.finalized=!1}return P(e,[{key:"loadData",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(this.finalized)throw"MetaScene already finalized - can't add more data";this._globalizeIDs(e,t);var n=this.metaScene;if(e.propertySets)for(var r=0,i=e.propertySets.length;r<i;r++){var a=e.propertySets[r],s=n.propertySets[a.id];s||(s=new np({id:a.id,originalSystemId:a.originalSystemId||a.id,type:a.type,name:a.name,properties:a.properties}),n.propertySets[s.id]=s),s.metaModels.push(this),this.propertySets.push(s)}if(e.metaObjects)for(var o=0,l=e.metaObjects.length;o<l;o++){var u=e.metaObjects[o],c=u.id,f=n.metaObjects[c];if(!f){var p=u.type,A=u.originalSystemId,d=u.propertySets||u.propertySetIds;f=new rp({id:c,originalSystemId:A,parentId:u.parent,type:p,name:u.name,attributes:u.attributes,propertySetIds:d}),this.metaScene.metaObjects[c]=f}f.metaModels.push(this),u.parent||(this.rootMetaObjects.push(f),n.rootMetaObjects[c]=f),this.metaObjects.push(f)}}},{key:"finalize",value:function(){if(this.finalized)throw"MetaScene already finalized - can't re-finalize";var e=this.metaScene;for(var t in e.metaObjects){var n=e.metaObjects[t];if(n.children&&(n.children=[]),n.propertySets&&(n.propertySets=[]),n.propertySetIds)for(var r=0,i=n.propertySetIds.length;r<i;r++){var a=n.propertySetIds[r],s=e.propertySets[a];n.propertySets.push(s)}}for(var o in e.metaObjects){var l=e.metaObjects[o];if(l.parentId){var u=e.metaObjects[l.parentId];u&&(l.parent=u,(u.children||(u.children=[])).push(l))}}for(var c in e.metaObjectsByType={},e.metaObjects){var f=e.metaObjects[c],p=f.type;(e.metaObjectsByType[p]||(e.metaObjectsByType[p]={}))[c]=f}this.finalized=!0,this.metaScene.fire("metaModelCreated",this.id)}},{key:"getJSON",value:function(){var e=[];return function t(n){var r={id:n.id,extId:n.extId,type:n.type,name:n.name};n.parent&&(r.parent=n.parent.id),e.push(r);var i=n.children;if(i)for(var a=0,s=i.length;a<s;a++)t(i[a])}(this.rootMetaObject),{id:this.id,projectId:this.projectId,revisionId:this.revisionId,metaObjects:e}}},{key:"_globalizeIDs",value:function(e,t){var n=!!t.globalizeObjectIds;if(e.metaObjects)for(var r=0,i=e.metaObjects.length;r<i;r++){var a=e.metaObjects[r];if(a.originalSystemId=a.id,a.originalParentSystemId=a.parent,n&&(a.id=Z.globalizeObjectId(this.id,a.id),a.parent=Z.globalizeObjectId(this.id,a.parent)),n){var s=a.propertySetIds;if(s){for(var o=[],l=0,u=s.length;l<u;l++)o.push(Z.globalizeObjectId(this.id,s[l]));a.propertySetIds=o,a.originalSystemPropertySetIds=s}}else a.originalSystemPropertySetIds=a.propertySetIds}if(e.propertySets)for(var c=0,f=e.propertySets.length;c<f;c++){var p=e.propertySets[c];p.originalSystemId=p.id,n&&(p.id=Z.globalizeObjectId(mothis.id,p.id))}}}]),e}(),ap=function(){function e(t,n){b(this,e),this.viewer=t,this.scene=n,this.metaModels={},this.propertySets={},this.metaObjects={},this.metaObjectsByType={},this.rootMetaObjects={},this._eventSubs={}}return P(e,[{key:"on",value:function(e,t){var n=this._eventSubs[e];n||(n=[],this._eventSubs[e]=n),n.push(t)}},{key:"fire",value:function(e,t){var n=this._eventSubs[e];if(n)for(var r=0,i=n.length;r<i;r++)n[r](t)}},{key:"off",value:function(e){}},{key:"createMetaModel",value:function(e,t){var n=new ip({metaScene:this,id:e,projectId:t.projectId||"none",revisionId:t.revisionId||"none",author:t.author||"none",createdAt:t.createdAt||"none",creatingApplication:t.creatingApplication||"none",schema:t.schema||"none",propertySets:[]});return n.loadData(t),n.finalize(),n}},{key:"destroyMetaModel",value:function(e){var t=this.metaModels[e];if(t){if(t.propertySets)for(var n=0,r=t.propertySets.length;n<r;n++){var i=t.propertySets[n];if(1===i.metaModels.length)delete this.propertySets[i.id];else{for(var a=[],s=0,o=i.metaModels.length;s<o;s++)i.metaModels[n].id!==e&&a.push(i.metaModels[n]);i.metaModels=a}}if(t.metaObjects)for(var l=0,u=t.metaObjects.length;l<u;l++){var c=t.metaObjects[l];c.type;var f=c.id;if(1===c.metaModels.length)delete this.metaObjects[f],c.parent||delete this.rootMetaObjects[f];else{for(var p=[],A=t.id,d=0,v=c.metaModels.length;d<v;d++)c.metaModels[d].id!==A&&p.push(c.metaModels[d]);c.metaModels=p}}for(var h in this.metaObjects){var I=this.metaObjects[h];if(I.children&&(I.children=[]),I.propertySets&&(I.propertySets=[]),I.propertySetIds)for(var y=0,m=I.propertySetIds.length;y<m;y++){var w=I.propertySetIds[y],g=this.propertySets[w];I.propertySets.push(g)}}for(var T in this.metaObjectsByType={},this.metaObjects){var E=this.metaObjects[T],b=E.type;E.children&&(E.children=null),(this.metaObjectsByType[b]||(this.metaObjectsByType[b]={}))[T]=E}for(var D in this.metaObjects){var P=this.metaObjects[D];if(P.parentId){var R=this.metaObjects[P.parentId];R&&(P.parent=R,(R.children||(R.children=[])).push(P))}}delete this.metaModels[e],this.fire("metaModelDestroyed",e)}}},{key:"getObjectIDsByType",value:function(e){var t=this.metaObjectsByType[e];return t?Object.keys(t):[]}},{key:"getObjectIDsInSubtree",value:function(e,t,n){var r=[],i=this.metaObjects[e],a=t&&t.length>0?sp(t):null,s=n&&n.length>0?sp(n):null;return function e(t){if(t){var n=!0;(s&&s[t.type]||a&&!a[t.type])&&(n=!1),n&&r.push(t.id);var i=t.children;if(i)for(var o=0,l=i.length;o<l;o++)e(i[o])}}(i),r}},{key:"withMetaObjectsInSubtree",value:function(e,t){var n=this.metaObjects[e];n&&n.withMetaObjectsInSubtree(t)}}]),e}();function sp(e){for(var t={},n=0,r=e.length;n<r;n++)t[e[n]]=!0;return t}
|
|
26
|
+
**/var ic=null;function ac(e,t){var n,r,i,a,s,o,l=3*e,u=3*t,c=Math.min(n=ic[l],r=ic[l+1],i=ic[l+2]),f=Math.min(a=ic[u],s=ic[u+1],o=ic[u+2]);if(c!==f)return c-f;var p=Math.max(n,r,i),A=Math.max(a,s,o);return p!==A?p-A:0}function sc(e,t){for(var n=new Int32Array(e.length/3),r=0,i=n.length;r<i;r++)n[r]=r;ic=new Int32Array(e.length);for(var a=0,s=e.length;a<s;a++)ic[a]=e[a]>>t;n.sort(ac);for(var o=new Int32Array(e.length),l=0,u=n.length;l<u;l++)o[3*l+0]=e[3*n[l]+0],o[3*l+1]=e[3*n[l]+1],o[3*l+2]=e[3*n[l]+2];return o}var oc=null;function lc(e,t){var n=oc[2*e]-oc[2*t];return 0!==n?n:oc[2*e+1]-oc[2*t+1]}function uc(e){if(0===(e||[]).length)return[];for(var t=new Int32Array(e.length/2),n=0,r=t.length;n<r;n++)t[n]=n;for(var i=0,a=e.length;i<a;i+=2)if(e[i]>e[i+1]){var s=e[i];e[i]=e[i+1],e[i+1]=s}oc=new Int32Array(e),t.sort(lc);for(var o=new Int32Array(e.length),l=0,u=t.length;l<u;l++)o[2*l+0]=e[2*t[l]+0],o[2*l+1]=e[2*t[l]+1];return o}function cc(e,t){var n={},r={};e.forEach((function(e){for(var t=e.indices,i=e.edgeIndices,a=e.positionsCompressed,s=0,o=t.length;s<o;s+=3){var l=a[3*t[s]]+"_"+a[3*t[s]+1]+"_"+a[3*t[s]+2]+"/"+a[3*t[s+1]]+"_"+a[3*t[s+1]+1]+"_"+a[3*t[s+1]+2]+"/"+a[3*t[s+2]]+"_"+a[3*t[s+2]+1]+"_"+a[3*t[s+2]+2];n[l]=!0}e.edgeIndices.length/2;for(var u=0,c=i.length;u<c;u+=2){var f=a[3*i[u]]+"_"+a[3*i[u]+1]+"_"+a[3*i[u]+2]+"/"+a[3*i[u+1]]+"_"+a[3*i[u+1]+1]+"_"+a[3*i[u+1]+2]+"/";r[f]=!0}}));var i=t.indices;t.edgeIndices;for(var a=t.positionsCompressed,s=0,o=i.length;s<o;s+=3){var l=a[3*i[s]]+"_"+a[3*i[s]+1]+"_"+a[3*i[s]+2]+"/"+a[3*i[s+1]]+"_"+a[3*i[s+1]+1]+"_"+a[3*i[s+1]+2]+"/"+a[3*i[s+2]]+"_"+a[3*i[s+2]+1]+"_"+a[3*i[s+2]+2];if(!(l in n))throw console.log("Not found "+l),"Ohhhh!"}}var fc=Z.vec4(),pc=Z.vec3(),Ac=function(){function e(t,n){b(this,e),this._scene=t,this._withSAO=n,this._hash=this._getHash(),this._allocate()}return P(e,[{key:"getValid",value:function(){return this._hash===this._getHash()}},{key:"_getHash",value:function(){var e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}},{key:"drawLayer",value:function(e,t,n){var r=this._scene,i=r.camera,a=t.model,s=r.canvas.gl,o=t._state,l=o.textureState,u=t._state.origin;if(this._program||(this._allocate(),!this.errors)){e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e,o)),l.bindCommonTextures(this._program,this._uTexturePerObjectIdPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this._uTexturePerObjectIdColorsAndFlags,this._uTextureCameraMatrices,this._uTextureModelMatrices,this._uTexturePerObjectIdOffsets);var c=i.eye;e.pickViewMatrix&&(l.bindPickCameraTexture(this._program,this._uTextureCameraMatrices),c=e.pickOrigin||c);var f=Z.vec3([c[0]-u[0],c[1]-u[1],c[2]-u[2]]);s.uniform3fv(this._uCameraEyeRtc,f),s.uniform1i(this._uRenderPass,n);var p=r._sectionPlanesState.sectionPlanes.length;if(p>0)for(var A=r._sectionPlanesState.sectionPlanes,d=t.layerIndex*p,v=a.renderFlags,h=0;h<p;h++){var I=this._uSectionPlanes[h];if(I){var y=v.sectionPlanesActivePerLayer[d+h];if(s.uniform1i(I.active,y?1:0),y){var m=A[h];if(u){var w=ge(m.dist,m.dir,u,pc);s.uniform3fv(I.pos,w)}else s.uniform3fv(I.pos,m.pos);s.uniform3fv(I.dir,m.dir)}}}o.numIndices8Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),s.drawArrays(s.TRIANGLES,0,o.numIndices8Bits)),o.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),s.drawArrays(s.TRIANGLES,0,o.numIndices16Bits)),o.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),s.drawArrays(s.TRIANGLES,0,o.numIndices32Bits)),e.drawElements++}}},{key:"_allocate",value:function(){var e=this._scene,t=e.canvas.gl,n=e._lightsState;if(this._program=new ft(t,this._buildShader()),this._program.errors)this.errors=this._program.errors;else{var r=this._program;this._uRenderPass=r.getLocation("renderPass"),this._uLightAmbient=r.getLocation("lightAmbient"),this._uLightColor=[],this._uLightDir=[],this._uLightPos=[],this._uLightAttenuation=[];for(var i=n.lights,a=0,s=i.length;a<s;a++)switch(i[a].type){case"dir":this._uLightColor[a]=r.getLocation("lightColor"+a),this._uLightPos[a]=null,this._uLightDir[a]=r.getLocation("lightDir"+a);break;case"point":this._uLightColor[a]=r.getLocation("lightColor"+a),this._uLightPos[a]=r.getLocation("lightPos"+a),this._uLightDir[a]=null,this._uLightAttenuation[a]=r.getLocation("lightAttenuation"+a);break;case"spot":this._uLightColor[a]=r.getLocation("lightColor"+a),this._uLightPos[a]=r.getLocation("lightPos"+a),this._uLightDir[a]=r.getLocation("lightDir"+a),this._uLightAttenuation[a]=r.getLocation("lightAttenuation"+a)}this._uSectionPlanes=[];for(var o=0,l=e._sectionPlanesState.sectionPlanes.length;o<l;o++)this._uSectionPlanes.push({active:r.getLocation("sectionPlaneActive"+o),pos:r.getLocation("sectionPlanePos"+o),dir:r.getLocation("sectionPlaneDir"+o)});this._withSAO&&(this._uOcclusionTexture="uOcclusionTexture",this._uSAOParams=r.getLocation("uSAOParams")),e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=r.getLocation("logDepthBufFC")),this._uTexturePerObjectIdPositionsDecodeMatrix="uTexturePerObjectIdPositionsDecodeMatrix",this._uTexturePerObjectIdColorsAndFlags="uTexturePerObjectIdColorsAndFlags",this._uTexturePerVertexIdCoordinates="uTexturePerVertexIdCoordinates",this._uTexturePerPolygonIdNormals="uTexturePerPolygonIdNormals",this._uTexturePerPolygonIdIndices="uTexturePerPolygonIdIndices",this._uTexturePerPolygonIdPortionIds="uTexturePerPolygonIdPortionIds",this._uTextureCameraMatrices="uTextureCameraMatrices",this._uTextureModelMatrices="uTextureModelMatrices",this._uTexturePerObjectIdOffsets="uTexturePerObjectIdOffsets",this._uCameraEyeRtc=r.getLocation("uCameraEyeRtc")}}},{key:"_bindProgram",value:function(e){var t=this._scene,n=t.canvas.gl,r=this._program,i=t._lightsState.lights,a=t.camera.project;r.bind(),this._uLightAmbient&&n.uniform4fv(this._uLightAmbient,t._lightsState.getAmbientColorAndIntensity());for(var s=0,o=i.length;s<o;s++){var l=i[s];this._uLightColor[s]&&n.uniform4f(this._uLightColor[s],l.color[0],l.color[1],l.color[2],l.intensity),this._uLightPos[s]&&(n.uniform3fv(this._uLightPos[s],l.pos),this._uLightAttenuation[s]&&n.uniform1f(this._uLightAttenuation[s],l.attenuation)),this._uLightDir[s]&&n.uniform3fv(this._uLightDir[s],l.dir)}if(this._withSAO){var u=t.sao;if(u.possible){var c=n.drawingBufferWidth,f=n.drawingBufferHeight;fc[0]=c,fc[1]=f,fc[2]=u.blendCutoff,fc[3]=u.blendFactor,n.uniform4fv(this._uSAOParams,fc),this._program.bindTexture(this._uOcclusionTexture,e.occlusionTexture,10)}}if(t.logarithmicDepthBufferEnabled){var p=2/(Math.log(a.far+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,p)}}},{key:"_buildShader",value:function(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}},{key:"_buildVertexShader",value:function(){var e,t=this._scene,n=t._sectionPlanesState,r=t._lightsState,i=n.sectionPlanes.length>0,a=[];a.push("#version 300 es"),a.push("// Triangles dataTexture draw vertex shader"),a.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),a.push("precision highp float;"),a.push("precision highp int;"),a.push("precision highp usampler2D;"),a.push("precision highp isampler2D;"),a.push("precision highp sampler2D;"),a.push("#else"),a.push("precision mediump float;"),a.push("precision mediump int;"),a.push("precision mediump usampler2D;"),a.push("precision mediump isampler2D;"),a.push("precision mediump sampler2D;"),a.push("#endif"),a.push("uniform int renderPass;"),t.entityOffsetsEnabled&&a.push("in vec3 offset;"),a.push("uniform highp sampler2D uTexturePerObjectIdPositionsDecodeMatrix;"),a.push("uniform lowp usampler2D uTexturePerObjectIdColorsAndFlags;"),a.push("uniform highp sampler2D uTexturePerObjectIdOffsets;"),a.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),a.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),a.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),a.push("uniform highp sampler2D uTextureCameraMatrices;"),a.push("uniform highp sampler2D uTextureModelMatrices;"),a.push("uniform vec3 uCameraEyeRtc;"),a.push("vec3 positions[3];"),t.logarithmicDepthBufferEnabled&&(a.push("uniform float logDepthBufFC;"),a.push("out float vFragDepth;"),a.push("out float isPerspective;")),a.push("bool isPerspectiveMatrix(mat4 m) {"),a.push(" return (m[2][3] == - 1.0);"),a.push("}"),a.push("uniform vec4 lightAmbient;");for(var s=0,o=r.lights.length;s<o;s++)"ambient"!==(e=r.lights[s]).type&&(a.push("uniform vec4 lightColor"+s+";"),"dir"===e.type&&a.push("uniform vec3 lightDir"+s+";"),"point"===e.type&&a.push("uniform vec3 lightPos"+s+";"),"spot"===e.type&&(a.push("uniform vec3 lightPos"+s+";"),a.push("uniform vec3 lightDir"+s+";")));i&&(a.push("out vec4 vWorldPosition;"),a.push("flat out uint vFlags2;")),a.push("out vec4 vColor;"),a.push("void main(void) {"),a.push("int polygonIndex = gl_VertexID / 3;"),a.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),a.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),a.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),a.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),a.push("uvec4 flags = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),a.push("uvec4 flags2 = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),a.push("if (int(flags.x) != renderPass) {"),a.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),a.push(" return;"),a.push("} else {"),a.push("mat4 viewMatrix = mat4 (texelFetch (uTextureCameraMatrices, ivec2(0, 0), 0), texelFetch (uTextureCameraMatrices, ivec2(1, 0), 0), texelFetch (uTextureCameraMatrices, ivec2(2, 0), 0), texelFetch (uTextureCameraMatrices, ivec2(3, 0), 0));"),a.push("mat4 viewNormalMatrix = mat4 (texelFetch (uTextureCameraMatrices, ivec2(0, 1), 0), texelFetch (uTextureCameraMatrices, ivec2(1, 1), 0), texelFetch (uTextureCameraMatrices, ivec2(2, 1), 0), texelFetch (uTextureCameraMatrices, ivec2(3, 1), 0));"),a.push("mat4 projMatrix = mat4 (texelFetch (uTextureCameraMatrices, ivec2(0, 2), 0), texelFetch (uTextureCameraMatrices, ivec2(1, 2), 0), texelFetch (uTextureCameraMatrices, ivec2(2, 2), 0), texelFetch (uTextureCameraMatrices, ivec2(3, 2), 0));"),a.push("mat4 worldMatrix = mat4 (texelFetch (uTextureModelMatrices, ivec2(0, 0), 0), texelFetch (uTextureModelMatrices, ivec2(1, 0), 0), texelFetch (uTextureModelMatrices, ivec2(2, 0), 0), texelFetch (uTextureModelMatrices, ivec2(3, 0), 0));"),a.push("mat4 worldNormalMatrix = mat4 (texelFetch (uTextureModelMatrices, ivec2(0, 1), 0), texelFetch (uTextureModelMatrices, ivec2(1, 1), 0), texelFetch (uTextureModelMatrices, ivec2(2, 1), 0), texelFetch (uTextureModelMatrices, ivec2(3, 1), 0));"),a.push("ivec4 packedVertexBase = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),a.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),a.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),a.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),a.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),a.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),a.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),a.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),a.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),a.push("mat4 positionsDecodeMatrix = mat4 (texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),a.push("uint solid = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),a.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),a.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),a.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),a.push("uvec4 color = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),a.push("if (color.a == 0u) {"),a.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),a.push(" return;"),a.push("};"),a.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),a.push("vec3 position;"),a.push("position = positions[gl_VertexID % 3];"),a.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*positionsDecodeMatrix)) * vec4(normal,1)).xyz);"),a.push("if (solid != 1u) {"),a.push("if (isPerspectiveMatrix(projMatrix)) {"),a.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(worldMatrix * positionsDecodeMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),a.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),a.push("position = positions[2 - (gl_VertexID % 3)];"),a.push("viewNormal = -viewNormal;"),a.push("}"),a.push("} else {"),a.push("if (viewNormal.z < 0.0) {"),a.push("position = positions[2 - (gl_VertexID % 3)];"),a.push("viewNormal = -viewNormal;"),a.push("}"),a.push("}"),a.push("}"),a.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),a.push("vec4 offset = vec4(texelFetch (uTexturePerObjectIdOffsets, objectIndexCoords, 0).rgb, 0.0);"),a.push("worldPosition.xyz = worldPosition.xyz + offset.xyz;"),a.push("vec4 viewPosition = viewMatrix * worldPosition; "),a.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),a.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),a.push("float lambertian = 1.0;");for(var l=0,u=r.lights.length;l<u;l++)if("ambient"!==(e=r.lights[l]).type){if("dir"===e.type)"view"===e.space?a.push("viewLightDir = normalize(lightDir"+l+");"):a.push("viewLightDir = normalize((viewMatrix * vec4(lightDir"+l+", 0.0)).xyz);");else if("point"===e.type)"view"===e.space?a.push("viewLightDir = -normalize(lightPos"+l+" - viewPosition.xyz);"):a.push("viewLightDir = -normalize((viewMatrix * vec4(lightPos"+l+", 0.0)).xyz);");else{if("spot"!==e.type)continue;"view"===e.space?a.push("viewLightDir = normalize(lightDir"+l+");"):a.push("viewLightDir = normalize((viewMatrix * vec4(lightDir"+l+", 0.0)).xyz);")}a.push("lambertian = max(dot(-viewNormal, viewLightDir), 0.0);"),a.push("reflectedColor += lambertian * (lightColor"+l+".rgb * lightColor"+l+".a);")}return a.push("vec3 rgb = vec3(color.rgb) / 255.0;"),a.push("vColor = vec4((lightAmbient.rgb * lightAmbient.a * rgb) + (reflectedColor * rgb), float(color.a) / 255.0);"),a.push("vec4 clipPos = projMatrix * viewPosition;"),t.logarithmicDepthBufferEnabled&&(a.push("vFragDepth = 1.0 + clipPos.w;"),a.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i&&(a.push("vWorldPosition = worldPosition;"),a.push("vFlags2 = flags2.r;")),a.push("gl_Position = clipPos;"),a.push("}"),a.push("}"),a}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,n=t.sectionPlanes.length>0,r=[];if(r.push("#version 300 es"),r.push("// Triangles dataTexture draw fragment shader"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),e.logarithmicDepthBufferEnabled&&(r.push("in float isPerspective;"),r.push("uniform float logDepthBufFC;"),r.push("in float vFragDepth;")),this._withSAO&&(r.push("uniform sampler2D uOcclusionTexture;"),r.push("uniform vec4 uSAOParams;"),r.push("const float packUpscale = 256. / 255.;"),r.push("const float unpackDownScale = 255. / 256.;"),r.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),r.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),r.push("float unpackRGBToFloat( const in vec4 v ) {"),r.push(" return dot( v, unPackFactors );"),r.push("}")),n){r.push("in vec4 vWorldPosition;"),r.push("flat in uint vFlags2;");for(var i=0,a=t.sectionPlanes.length;i<a;i++)r.push("uniform bool sectionPlaneActive"+i+";"),r.push("uniform vec3 sectionPlanePos"+i+";"),r.push("uniform vec3 sectionPlaneDir"+i+";")}if(r.push("in vec4 vColor;"),r.push("out vec4 outColor;"),r.push("void main(void) {"),n){r.push(" bool clippable = vFlags2 > 0u;"),r.push(" if (clippable) {"),r.push(" float dist = 0.0;");for(var s=0,o=t.sectionPlanes.length;s<o;s++)r.push("if (sectionPlaneActive"+s+") {"),r.push(" dist += clamp(dot(-sectionPlaneDir"+s+".xyz, vWorldPosition.xyz - sectionPlanePos"+s+".xyz), 0.0, 1000.0);"),r.push("}");r.push(" if (dist > 0.0) { "),r.push(" discard;"),r.push(" }"),r.push("}")}return e.logarithmicDepthBufferEnabled&&r.push(" gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),this._withSAO?(r.push(" float viewportWidth = uSAOParams[0];"),r.push(" float viewportHeight = uSAOParams[1];"),r.push(" float blendCutoff = uSAOParams[2];"),r.push(" float blendFactor = uSAOParams[3];"),r.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),r.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBToFloat(texture(uOcclusionTexture, uv))) * blendFactor;"),r.push(" outColor = vec4(vColor.rgb * ambient, 1.0);")):r.push(" outColor = vColor;"),r.push("}"),r}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),e}(),dc=new Float32Array([1,1,1]);Z.vec4();var vc=Z.vec3(),hc=function(){function e(t,n){b(this,e),this._scene=t,this._hash=this._getHash(),this._allocate()}return P(e,[{key:"getValid",value:function(){return this._hash===this._getHash()}},{key:"_getHash",value:function(){return this._scene._sectionPlanesState.getHash()}},{key:"drawLayer",value:function(e,t,n){var r=this._scene,i=r.camera,a=t.model,s=r.canvas.gl,o=t._state,l=o.textureState,u=t._state.origin;if(this._program||(this._allocate(),!this.errors)){e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e,o)),l.bindCommonTextures(this._program,this._uTexturePerObjectIdPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this._uTexturePerObjectIdColorsAndFlags,this._uTextureCameraMatrices,this._uTextureModelMatrices,this._uTexturePerObjectIdOffsets);var c=i.eye;e.pickViewMatrix&&(l.bindPickCameraTexture(this._program,this._uTextureCameraMatrices),c=e.pickOrigin||c);var f=[c[0]-u[0],c[1]-u[1],c[2]-u[2]];if(s.uniform3fv(this._uCameraEyeRtc,f),s.uniform1i(this._uRenderPass,n),n===eo.SILHOUETTE_XRAYED){var p=r.xrayMaterial._state,A=p.fillColor,d=p.fillAlpha;s.uniform4f(this._uColor,A[0],A[1],A[2],d)}else if(n===eo.SILHOUETTE_HIGHLIGHTED){var v=r.highlightMaterial._state,h=v.fillColor,I=v.fillAlpha;s.uniform4f(this._uColor,h[0],h[1],h[2],I)}else if(n===eo.SILHOUETTE_SELECTED){var y=r.selectedMaterial._state,m=y.fillColor,w=y.fillAlpha;s.uniform4f(this._uColor,m[0],m[1],m[2],w)}else s.uniform4fv(this._uColor,dc);var g=r._sectionPlanesState.sectionPlanes.length;if(g>0)for(var T=r._sectionPlanesState.sectionPlanes,E=t.layerIndex*g,b=a.renderFlags,D=0;D<g;D++){var P=this._uSectionPlanes[D];if(P){var R=b.sectionPlanesActivePerLayer[E+D];if(s.uniform1i(P.active,R?1:0),R){var C=T[D];if(u){var _=ge(C.dist,C.dir,u,vc);s.uniform3fv(P.pos,_)}else s.uniform3fv(P.pos,C.pos);s.uniform3fv(P.dir,C.dir)}}}o.numIndices8Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),s.drawArrays(s.TRIANGLES,0,o.numIndices8Bits)),o.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),s.drawArrays(s.TRIANGLES,0,o.numIndices16Bits)),o.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),s.drawArrays(s.TRIANGLES,0,o.numIndices32Bits)),e.drawElements++}}},{key:"_allocate",value:function(){var e=this._scene,t=e.canvas.gl;if(this._program=new ft(t,this._buildShader()),this._program.errors)this.errors=this._program.errors;else{var n=this._program;this._uRenderPass=n.getLocation("renderPass"),this._uColor=n.getLocation("color"),this._uSectionPlanes=[];for(var r=0,i=e._sectionPlanesState.sectionPlanes.length;r<i;r++)this._uSectionPlanes.push({active:n.getLocation("sectionPlaneActive"+r),pos:n.getLocation("sectionPlanePos"+r),dir:n.getLocation("sectionPlaneDir"+r)});e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=n.getLocation("logDepthBufFC")),this._uTexturePerObjectIdPositionsDecodeMatrix="uTexturePerObjectIdPositionsDecodeMatrix",this._uTexturePerObjectIdColorsAndFlags="uTexturePerObjectIdColorsAndFlags",this._uTexturePerVertexIdCoordinates="uTexturePerVertexIdCoordinates",this._uTexturePerPolygonIdNormals="uTexturePerPolygonIdNormals",this._uTexturePerPolygonIdIndices="uTexturePerPolygonIdIndices",this._uTexturePerPolygonIdPortionIds="uTexturePerPolygonIdPortionIds",this._uTextureCameraMatrices="uTextureCameraMatrices",this._uTextureModelMatrices="uTextureModelMatrices",this._uTexturePerObjectIdOffsets="uTexturePerObjectIdOffsets",this._uCameraEyeRtc=n.getLocation("uCameraEyeRtc")}}},{key:"_bindProgram",value:function(e){var t=this._scene,n=t.canvas.gl,r=t.camera.project;if(this._program.bind(),t.logarithmicDepthBufferEnabled){var i=2/(Math.log(r.far+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,i)}}},{key:"_buildShader",value:function(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,n=[];return n.push("#version 300 es"),n.push("// Triangles dataTexture silhouette vertex shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("precision highp usampler2D;"),n.push("precision highp isampler2D;"),n.push("precision highp sampler2D;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("precision mediump usampler2D;"),n.push("precision mediump isampler2D;"),n.push("precision mediump sampler2D;"),n.push("#endif"),n.push("uniform int renderPass;"),e.entityOffsetsEnabled&&n.push("in vec3 offset;"),n.push("uniform highp sampler2D uTexturePerObjectIdPositionsDecodeMatrix;"),n.push("uniform lowp usampler2D uTexturePerObjectIdColorsAndFlags;"),n.push("uniform highp sampler2D uTexturePerObjectIdOffsets;"),n.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),n.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),n.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),n.push("uniform highp sampler2D uTextureCameraMatrices;"),n.push("uniform highp sampler2D uTextureModelMatrices;"),n.push("uniform vec3 uCameraEyeRtc;"),n.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("out float vFragDepth;"),n.push("out float isPerspective;")),n.push("bool isPerspectiveMatrix(mat4 m) {"),n.push(" return (m[2][3] == - 1.0);"),n.push("}"),t&&(n.push("out vec4 vWorldPosition;"),n.push("flat out uint vFlags2;")),n.push("void main(void) {"),n.push("mat4 viewMatrix = mat4 (texelFetch (uTextureCameraMatrices, ivec2(0, 0), 0), texelFetch (uTextureCameraMatrices, ivec2(1, 0), 0), texelFetch (uTextureCameraMatrices, ivec2(2, 0), 0), texelFetch (uTextureCameraMatrices, ivec2(3, 0), 0));"),n.push("mat4 viewNormalMatrix = mat4 (texelFetch (uTextureCameraMatrices, ivec2(0, 1), 0), texelFetch (uTextureCameraMatrices, ivec2(1, 1), 0), texelFetch (uTextureCameraMatrices, ivec2(2, 1), 0), texelFetch (uTextureCameraMatrices, ivec2(3, 1), 0));"),n.push("mat4 projMatrix = mat4 (texelFetch (uTextureCameraMatrices, ivec2(0, 2), 0), texelFetch (uTextureCameraMatrices, ivec2(1, 2), 0), texelFetch (uTextureCameraMatrices, ivec2(2, 2), 0), texelFetch (uTextureCameraMatrices, ivec2(3, 2), 0));"),n.push("mat4 worldMatrix = mat4 (texelFetch (uTextureModelMatrices, ivec2(0, 0), 0), texelFetch (uTextureModelMatrices, ivec2(1, 0), 0), texelFetch (uTextureModelMatrices, ivec2(2, 0), 0), texelFetch (uTextureModelMatrices, ivec2(3, 0), 0));"),n.push("mat4 worldNormalMatrix = mat4 (texelFetch (uTextureModelMatrices, ivec2(0, 1), 0), texelFetch (uTextureModelMatrices, ivec2(1, 1), 0), texelFetch (uTextureModelMatrices, ivec2(2, 1), 0), texelFetch (uTextureModelMatrices, ivec2(3, 1), 0));"),n.push("int polygonIndex = gl_VertexID / 3;"),n.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),n.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),n.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),n.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),n.push("uvec4 flags = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),n.push("uvec4 flags2 = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),n.push("if (int(flags.y) != renderPass) {"),n.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),n.push(" return;"),n.push("} else {"),n.push("ivec4 packedVertexBase = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),n.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),n.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),n.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),n.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),n.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),n.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),n.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),n.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),n.push("mat4 positionsDecodeMatrix = mat4 (texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),n.push("uint solid = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),n.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),n.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),n.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),n.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),n.push("vec3 position;"),n.push("position = positions[gl_VertexID % 3];"),n.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*positionsDecodeMatrix)) * vec4(normal,1)).xyz);"),n.push("if (solid != 1u) {"),n.push("if (isPerspectiveMatrix(projMatrix)) {"),n.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(worldMatrix * positionsDecodeMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),n.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),n.push("position = positions[2 - (gl_VertexID % 3)];"),n.push("viewNormal = -viewNormal;"),n.push("}"),n.push("} else {"),n.push("if (viewNormal.z < 0.0) {"),n.push("position = positions[2 - (gl_VertexID % 3)];"),n.push("viewNormal = -viewNormal;"),n.push("}"),n.push("}"),n.push("}"),n.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),n.push("vec4 offset = vec4(texelFetch (uTexturePerObjectIdOffsets, objectIndexCoords, 0).rgb, 0.0);"),n.push("worldPosition.xyz = worldPosition.xyz + offset.xyz;"),n.push("vec4 viewPosition = viewMatrix * worldPosition; "),n.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(n.push("vFragDepth = 1.0 + clipPos.w;"),n.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(n.push("vWorldPosition = worldPosition;"),n.push("vFlags2 = flags2.r;")),n.push("gl_Position = clipPos;"),n.push("}"),n.push("}"),n}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,n=t.sectionPlanes.length>0,r=[];if(r.push("#version 300 es"),r.push("// Triangles dataTexture draw fragment shader"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),e.logarithmicDepthBufferEnabled&&(r.push("in float isPerspective;"),r.push("uniform float logDepthBufFC;"),r.push("varying float vFragDepth;")),n){r.push("in vec4 vWorldPosition;"),r.push("flat in uint vFlags2;");for(var i=0,a=t.sectionPlanes.length;i<a;i++)r.push("uniform bool sectionPlaneActive"+i+";"),r.push("uniform vec3 sectionPlanePos"+i+";"),r.push("uniform vec3 sectionPlaneDir"+i+";")}if(r.push("uniform vec4 color;"),r.push("out vec4 outColor;"),r.push("void main(void) {"),n){r.push(" bool clippable = vFlags2 > 0u;"),r.push(" if (clippable) {"),r.push(" float dist = 0.0;");for(var s=0,o=t.sectionPlanes.length;s<o;s++)r.push("if (sectionPlaneActive"+s+") {"),r.push(" dist += clamp(dot(-sectionPlaneDir"+s+".xyz, vWorldPosition.xyz - sectionPlanePos"+s+".xyz), 0.0, 1000.0);"),r.push("}");r.push(" if (dist > 0.0) { "),r.push(" discard;"),r.push(" }"),r.push("}")}return e.logarithmicDepthBufferEnabled&&r.push(" gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),r.push(" outColor = color;"),r.push("}"),r}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),e}(),Ic=Z.vec3(),yc=new Float32Array([0,0,0,1]),mc=function(){function e(t){b(this,e),this._scene=t,this._hash=this._getHash(),this._allocate()}return P(e,[{key:"getValid",value:function(){return this._hash===this._getHash()}},{key:"_getHash",value:function(){return this._scene._sectionPlanesState.getHash()}},{key:"drawLayer",value:function(e,t,n){var r=t.model,i=r.scene,a=i.camera,s=i.canvas.gl,o=t._state,l=o.textureState,u=t._state.origin;if(this._program||(this._allocate(t),!this.errors)){if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram()),l.bindCommonTextures(this._program,this._uTexturePerObjectIdPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this._uTexturePerObjectIdColorsAndFlags,this._uTextureCameraMatrices,this._uTextureModelMatrices,this._uTexturePerObjectIdOffsets),e.pickViewMatrix&&l.bindPickCameraTexture(this._program,this._uTextureCameraMatrices),s.uniform1i(this._uRenderPass,n),n===eo.EDGES_XRAYED){var c=i.xrayMaterial._state,f=c.edgeColor,p=c.edgeAlpha;s.uniform4f(this._uColor,f[0],f[1],f[2],p)}else if(n===eo.EDGES_HIGHLIGHTED){var A=i.highlightMaterial._state,d=A.edgeColor,v=A.edgeAlpha;s.uniform4f(this._uColor,d[0],d[1],d[2],v)}else if(n===eo.EDGES_SELECTED){var h=i.selectedMaterial._state,I=h.edgeColor,y=h.edgeAlpha;s.uniform4f(this._uColor,I[0],I[1],I[2],y)}else s.uniform4fv(this._uColor,yc);s.uniformMatrix4fv(this._uViewMatrix,!1,u?Ie(a.viewMatrix,u):a.viewMatrix),s.uniformMatrix4fv(this._uWorldMatrix,!1,r.worldMatrix);var m=i._sectionPlanesState.sectionPlanes.length;if(m>0)for(var w=i._sectionPlanesState.sectionPlanes,g=t.layerIndex*m,T=r.renderFlags,E=0;E<m;E++){var b=this._uSectionPlanes[E];if(b){var D=T.sectionPlanesActivePerLayer[g+E];if(s.uniform1i(b.active,D?1:0),D){var P=w[E];if(u){var R=ge(P.dist,P.dir,u,Ic);s.uniform3fv(b.pos,R)}else s.uniform3fv(b.pos,P.pos);s.uniform3fv(b.dir,P.dir)}}}o.numEdgeIndices8Bits>0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,8),s.drawArrays(s.LINES,0,o.numEdgeIndices8Bits)),o.numEdgeIndices16Bits>0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,16),s.drawArrays(s.LINES,0,o.numEdgeIndices16Bits)),o.numEdgeIndices32Bits>0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,32),s.drawArrays(s.LINES,0,o.numEdgeIndices32Bits)),e.drawElements++}}},{key:"_allocate",value:function(){var e=this._scene,t=e.canvas.gl;if(this._program=new ft(t,this._buildShader()),this._program.errors)this.errors=this._program.errors;else{var n=this._program;this._uRenderPass=n.getLocation("renderPass"),this._uColor=n.getLocation("color"),this._uSectionPlanes=[];for(var r=0,i=e._sectionPlanesState.sectionPlanes.length;r<i;r++)this._uSectionPlanes.push({active:n.getLocation("sectionPlaneActive"+r),pos:n.getLocation("sectionPlanePos"+r),dir:n.getLocation("sectionPlaneDir"+r)});e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=n.getLocation("logDepthBufFC")),this._uTexturePerObjectIdPositionsDecodeMatrix="uTexturePerObjectIdPositionsDecodeMatrix",this._uTexturePerObjectIdColorsAndFlags="uTexturePerObjectIdColorsAndFlags",this._uTexturePerVertexIdCoordinates="uTexturePerVertexIdCoordinates",this._uTexturePerPolygonIdEdgeIndices="uTexturePerPolygonIdEdgeIndices",this._uTexturePerEdgeIdPortionIds="uTexturePerEdgeIdPortionIds",this._uTextureCameraMatrices="uTextureCameraMatrices",this._uTextureModelMatrices="uTextureModelMatrices",this._uTexturePerObjectIdOffsets="uTexturePerObjectIdOffsets"}}},{key:"_bindProgram",value:function(){var e=this._scene,t=e.canvas.gl,n=this._program,r=e.camera.project;if(n.bind(),e.logarithmicDepthBufferEnabled){var i=2/(Math.log(r.far+1)/Math.LN2);t.uniform1f(this._uLogDepthBufFC,i)}}},{key:"_buildShader",value:function(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,n=[];return n.push("#version 300 es"),n.push("// Batched geometry edges drawing vertex shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("precision highp usampler2D;"),n.push("precision highp isampler2D;"),n.push("precision highp sampler2D;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("precision mediump usampler2D;"),n.push("precision mediump isampler2D;"),n.push("precision mediump sampler2D;"),n.push("#endif"),n.push("uniform int renderPass;"),e.entityOffsetsEnabled&&n.push("in vec3 offset;"),n.push("uniform highp sampler2D uTexturePerObjectIdPositionsDecodeMatrix;"),n.push("uniform lowp usampler2D uTexturePerObjectIdColorsAndFlags;"),n.push("uniform highp sampler2D uTexturePerObjectIdOffsets;"),n.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),n.push("uniform highp usampler2D uTexturePerPolygonIdEdgeIndices;"),n.push("uniform mediump usampler2D uTexturePerEdgeIdPortionIds;"),n.push("uniform highp sampler2D uTextureCameraMatrices;"),n.push("uniform highp sampler2D uTextureModelMatrices;"),n.push("uniform vec4 color;"),e.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("out float vFragDepth;"),n.push("bool isPerspectiveMatrix(mat4 m) {"),n.push(" return (m[2][3] == - 1.0);"),n.push("}"),n.push("out float isPerspective;")),t&&(n.push("out vec4 vWorldPosition;"),n.push("flat out uint vFlags2;")),n.push("out vec4 vColor;"),n.push("void main(void) {"),n.push("mat4 viewMatrix = mat4 (texelFetch (uTextureCameraMatrices, ivec2(0, 0), 0), texelFetch (uTextureCameraMatrices, ivec2(1, 0), 0), texelFetch (uTextureCameraMatrices, ivec2(2, 0), 0), texelFetch (uTextureCameraMatrices, ivec2(3, 0), 0));"),n.push("mat4 projMatrix = mat4 (texelFetch (uTextureCameraMatrices, ivec2(0, 2), 0), texelFetch (uTextureCameraMatrices, ivec2(1, 2), 0), texelFetch (uTextureCameraMatrices, ivec2(2, 2), 0), texelFetch (uTextureCameraMatrices, ivec2(3, 2), 0));"),n.push("mat4 worldMatrix = mat4 (texelFetch (uTextureModelMatrices, ivec2(0, 0), 0), texelFetch (uTextureModelMatrices, ivec2(1, 0), 0), texelFetch (uTextureModelMatrices, ivec2(2, 0), 0), texelFetch (uTextureModelMatrices, ivec2(3, 0), 0));"),n.push("int edgeIndex = gl_VertexID / 2;"),n.push("int h_packed_object_id_index = (edgeIndex >> 3) & 4095;"),n.push("int v_packed_object_id_index = (edgeIndex >> 3) >> 12;"),n.push("int objectIndex = int(texelFetch(uTexturePerEdgeIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),n.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),n.push("uvec4 flags = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),n.push("uvec4 flags2 = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),n.push("if (int(flags.z) != renderPass) {"),n.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),n.push(" return;"),n.push("} else {"),n.push("ivec4 packedVertexBase = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),n.push("ivec4 packedEdgeIndexBaseOffset = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+6, objectIndexCoords.y), 0));"),n.push("int edgeIndexBaseOffset = (packedEdgeIndexBaseOffset.r << 24) + (packedEdgeIndexBaseOffset.g << 16) + (packedEdgeIndexBaseOffset.b << 8) + packedEdgeIndexBaseOffset.a;"),n.push("int h_index = (edgeIndex - edgeIndexBaseOffset) & 4095;"),n.push("int v_index = (edgeIndex - edgeIndexBaseOffset) >> 12;"),n.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdEdgeIndices, ivec2(h_index, v_index), 0));"),n.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),n.push("int indexPositionH = uniqueVertexIndexes[gl_VertexID % 2] & 4095;"),n.push("int indexPositionV = uniqueVertexIndexes[gl_VertexID % 2] >> 12;"),n.push("mat4 positionsDecodeMatrix = mat4 (texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),n.push("uvec4 flags = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),n.push("uvec4 flags2 = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),n.push("vec3 position = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH, indexPositionV), 0));"),n.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),n.push("vec4 offset = vec4(texelFetch (uTexturePerObjectIdOffsets, objectIndexCoords, 0).rgb, 0.0);"),n.push("worldPosition.xyz = worldPosition.xyz + offset.xyz;"),n.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(n.push(" vWorldPosition = worldPosition;"),n.push(" vFlags2 = flags2.r;")),n.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(n.push("vFragDepth = 1.0 + clipPos.w;"),n.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),n.push("gl_Position = clipPos;"),n.push("vColor = vec4(color.r, color.g, color.b, color.a);"),n.push("}"),n.push("}"),n}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,n=t.sectionPlanes.length>0,r=[];if(r.push("#version 300 es"),r.push("// Batched geometry edges drawing fragment shader"),e.logarithmicDepthBufferEnabled&&r.push("#extension GL_EXT_frag_depth : enable"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),e.logarithmicDepthBufferEnabled&&(r.push("in float isPerspective;"),r.push("uniform float logDepthBufFC;"),r.push("in float vFragDepth;")),n){r.push("in vec4 vWorldPosition;"),r.push("flat in uint vFlags2;");for(var i=0,a=t.sectionPlanes.length;i<a;i++)r.push("uniform bool sectionPlaneActive"+i+";"),r.push("uniform vec3 sectionPlanePos"+i+";"),r.push("uniform vec3 sectionPlaneDir"+i+";")}if(r.push("in vec4 vColor;"),r.push("out vec4 outColor;"),r.push("void main(void) {"),n){r.push(" bool clippable = vFlags2 > 0u;"),r.push(" if (clippable) {"),r.push(" float dist = 0.0;");for(var s=0,o=t.sectionPlanes.length;s<o;s++)r.push("if (sectionPlaneActive"+s+") {"),r.push(" dist += clamp(dot(-sectionPlaneDir"+s+".xyz, vWorldPosition.xyz - sectionPlanePos"+s+".xyz), 0.0, 1000.0);"),r.push("}");r.push(" if (dist > 0.0) { discard; }"),r.push("}")}return e.logarithmicDepthBufferEnabled&&r.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),r.push(" outColor = vColor;"),r.push("}"),r}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),e}(),wc=Z.vec3(),gc=function(){function e(t){b(this,e),this._scene=t,this._hash=this._getHash(),this._allocate()}return P(e,[{key:"getValid",value:function(){return this._hash===this._getHash()}},{key:"_getHash",value:function(){return this._scene._sectionPlanesState.getHash()}},{key:"drawLayer",value:function(e,t,n){var r=t.model,i=r.scene;i.camera;var a=i.canvas.gl,s=t._state,o=s.textureState,l=t._state.origin;if(this._program||(this._allocate(t),!this.errors)){e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram()),o.bindCommonTextures(this._program,this._uTexturePerObjectIdPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this._uTexturePerObjectIdColorsAndFlags,this._uTextureCameraMatrices,this._uTextureModelMatrices,this._uTexturePerObjectIdOffsets),e.pickViewMatrix&&o.bindPickCameraTexture(this._program,this._uTextureCameraMatrices),a.uniform1i(this._uRenderPass,n);var u=i._sectionPlanesState.sectionPlanes.length;if(u>0)for(var c=i._sectionPlanesState.sectionPlanes,f=t.layerIndex*u,p=r.renderFlags,A=0;A<u;A++){var d=this._uSectionPlanes[A];if(d){var v=p.sectionPlanesActivePerLayer[f+A];if(a.uniform1i(d.active,v?1:0),v){var h=c[A];if(l){var I=ge(h.dist,h.dir,l,wc);a.uniform3fv(d.pos,I)}else a.uniform3fv(d.pos,h.pos);a.uniform3fv(d.dir,h.dir)}}}s.numEdgeIndices8Bits>0&&(o.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,8),a.drawArrays(a.LINES,0,s.numEdgeIndices8Bits)),s.numEdgeIndices16Bits>0&&(o.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,16),a.drawArrays(a.LINES,0,s.numEdgeIndices16Bits)),s.numEdgeIndices32Bits>0&&(o.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,32),a.drawArrays(a.LINES,0,s.numEdgeIndices32Bits)),e.drawElements++}}},{key:"_allocate",value:function(){var e=this._scene,t=e.canvas.gl;if(this._program=new ft(t,this._buildShader()),this._program.errors)this.errors=this._program.errors;else{var n=this._program;this._uRenderPass=n.getLocation("renderPass"),this._uSectionPlanes=[];for(var r=0,i=e._sectionPlanesState.sectionPlanes.length;r<i;r++)this._uSectionPlanes.push({active:n.getLocation("sectionPlaneActive"+r),pos:n.getLocation("sectionPlanePos"+r),dir:n.getLocation("sectionPlaneDir"+r)});e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=n.getLocation("logDepthBufFC")),this._uTexturePerObjectIdPositionsDecodeMatrix="uTexturePerObjectIdPositionsDecodeMatrix",this._uTexturePerObjectIdColorsAndFlags="uTexturePerObjectIdColorsAndFlags",this._uTexturePerVertexIdCoordinates="uTexturePerVertexIdCoordinates",this._uTexturePerPolygonIdEdgeIndices="uTexturePerPolygonIdEdgeIndices",this._uTexturePerEdgeIdPortionIds="uTexturePerEdgeIdPortionIds",this._uTextureCameraMatrices="uTextureCameraMatrices",this._uTextureModelMatrices="uTextureModelMatrices",this._uTexturePerObjectIdOffsets="uTexturePerObjectIdOffsets"}}},{key:"_bindProgram",value:function(){var e=this._scene,t=e.canvas.gl,n=this._program,r=e.camera.project;if(n.bind(),e.logarithmicDepthBufferEnabled){var i=2/(Math.log(r.far+1)/Math.LN2);t.uniform1f(this._uLogDepthBufFC,i)}}},{key:"_buildShader",value:function(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,n=[];return n.push("#version 300 es"),n.push("// Batched geometry edges drawing vertex shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("precision highp usampler2D;"),n.push("precision highp isampler2D;"),n.push("precision highp sampler2D;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("precision mediump usampler2D;"),n.push("precision mediump isampler2D;"),n.push("precision mediump sampler2D;"),n.push("#endif"),n.push("uniform int renderPass;"),e.entityOffsetsEnabled&&n.push("in vec3 offset;"),n.push("uniform highp sampler2D uTexturePerObjectIdPositionsDecodeMatrix;"),n.push("uniform lowp usampler2D uTexturePerObjectIdColorsAndFlags;"),n.push("uniform highp sampler2D uTexturePerObjectIdOffsets;"),n.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),n.push("uniform highp usampler2D uTexturePerPolygonIdEdgeIndices;"),n.push("uniform mediump usampler2D uTexturePerEdgeIdPortionIds;"),n.push("uniform highp sampler2D uTextureCameraMatrices;"),n.push("uniform highp sampler2D uTextureModelMatrices;"),e.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("out float vFragDepth;"),n.push("bool isPerspectiveMatrix(mat4 m) {"),n.push(" return (m[2][3] == - 1.0);"),n.push("}"),n.push("out float isPerspective;")),t&&(n.push("out vec4 vWorldPosition;"),n.push("flat out uint vFlags2;")),n.push("out vec4 vColor;"),n.push("void main(void) {"),n.push("mat4 viewMatrix = mat4 (texelFetch (uTextureCameraMatrices, ivec2(0, 0), 0), texelFetch (uTextureCameraMatrices, ivec2(1, 0), 0), texelFetch (uTextureCameraMatrices, ivec2(2, 0), 0), texelFetch (uTextureCameraMatrices, ivec2(3, 0), 0));"),n.push("mat4 projMatrix = mat4 (texelFetch (uTextureCameraMatrices, ivec2(0, 2), 0), texelFetch (uTextureCameraMatrices, ivec2(1, 2), 0), texelFetch (uTextureCameraMatrices, ivec2(2, 2), 0), texelFetch (uTextureCameraMatrices, ivec2(3, 2), 0));"),n.push("mat4 worldMatrix = mat4 (texelFetch (uTextureModelMatrices, ivec2(0, 0), 0), texelFetch (uTextureModelMatrices, ivec2(1, 0), 0), texelFetch (uTextureModelMatrices, ivec2(2, 0), 0), texelFetch (uTextureModelMatrices, ivec2(3, 0), 0));"),n.push("int edgeIndex = gl_VertexID / 2;"),n.push("int h_packed_object_id_index = (edgeIndex >> 3) & 4095;"),n.push("int v_packed_object_id_index = (edgeIndex >> 3) >> 12;"),n.push("int objectIndex = int(texelFetch(uTexturePerEdgeIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),n.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),n.push("uvec4 flags = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),n.push("uvec4 flags2 = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),n.push("if (int(flags.z) != renderPass) {"),n.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),n.push(" return;"),n.push("} else {"),n.push("ivec4 packedVertexBase = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),n.push("ivec4 packedEdgeIndexBaseOffset = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+6, objectIndexCoords.y), 0));"),n.push("int edgeIndexBaseOffset = (packedEdgeIndexBaseOffset.r << 24) + (packedEdgeIndexBaseOffset.g << 16) + (packedEdgeIndexBaseOffset.b << 8) + packedEdgeIndexBaseOffset.a;"),n.push("int h_index = (edgeIndex - edgeIndexBaseOffset) & 4095;"),n.push("int v_index = (edgeIndex - edgeIndexBaseOffset) >> 12;"),n.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdEdgeIndices, ivec2(h_index, v_index), 0));"),n.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),n.push("int indexPositionH = uniqueVertexIndexes[gl_VertexID % 2] & 4095;"),n.push("int indexPositionV = uniqueVertexIndexes[gl_VertexID % 2] >> 12;"),n.push("mat4 positionsDecodeMatrix = mat4 (texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),n.push("uvec4 flags = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),n.push("uvec4 flags2 = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),n.push("vec3 position = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH, indexPositionV), 0));"),n.push("uvec4 color = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),n.push("if (color.a == 0u) {"),n.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),n.push(" return;"),n.push("};"),n.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),n.push("vec4 offset = vec4(texelFetch (uTexturePerObjectIdOffsets, objectIndexCoords, 0).rgb, 0.0);"),n.push("worldPosition.xyz = worldPosition.xyz + offset.xyz;"),n.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(n.push(" vWorldPosition = worldPosition;"),n.push(" vFlags2 = flags2.r;")),n.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(n.push("vFragDepth = 1.0 + clipPos.w;"),n.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),n.push("gl_Position = clipPos;"),n.push("vec4 rgb = vec4(color.rgba);"),n.push("vColor = vec4(float(rgb.r*0.5) / 255.0, float(rgb.g*0.5) / 255.0, float(rgb.b*0.5) / 255.0, float(rgb.a) / 255.0);"),n.push("}"),n.push("}"),n}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,n=t.sectionPlanes.length>0,r=[];if(r.push("#version 300 es"),r.push("// Batched geometry edges drawing fragment shader"),e.logarithmicDepthBufferEnabled&&r.push("#extension GL_EXT_frag_depth : enable"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),e.logarithmicDepthBufferEnabled&&(r.push("in float isPerspective;"),r.push("uniform float logDepthBufFC;"),r.push("in float vFragDepth;")),n){r.push("in vec4 vWorldPosition;"),r.push("flat in uint vFlags2;");for(var i=0,a=t.sectionPlanes.length;i<a;i++)r.push("uniform bool sectionPlaneActive"+i+";"),r.push("uniform vec3 sectionPlanePos"+i+";"),r.push("uniform vec3 sectionPlaneDir"+i+";")}if(r.push("in vec4 vColor;"),r.push("out vec4 outColor;"),r.push("void main(void) {"),n){r.push(" bool clippable = vFlags2 > 0u;"),r.push(" if (clippable) {"),r.push(" float dist = 0.0;");for(var s=0,o=t.sectionPlanes.length;s<o;s++)r.push("if (sectionPlaneActive"+s+") {"),r.push(" dist += clamp(dot(-sectionPlaneDir"+s+".xyz, vWorldPosition.xyz - sectionPlanePos"+s+".xyz), 0.0, 1000.0);"),r.push("}");r.push(" if (dist > 0.0) { discard; }"),r.push("}")}return e.logarithmicDepthBufferEnabled&&r.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),r.push(" outColor = vColor;"),r.push("}"),r}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),e}(),Tc=Z.vec3(),Ec=function(){function e(t){b(this,e),this._scene=t,this._hash=this._getHash(),this._allocate()}return P(e,[{key:"getValid",value:function(){return this._hash===this._getHash()}},{key:"_getHash",value:function(){return this._scene._sectionPlanesState.getHash()}},{key:"drawLayer",value:function(e,t,n){var r=t.model,i=r.scene,a=i.camera,s=i.canvas.gl,o=t._state,l=o.textureState,u=t._state.origin;this._program||this._allocate(t),e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),l.bindCommonTextures(this._program,this._uTexturePerObjectIdPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this._uTexturePerObjectIdColorsAndFlags,this._uTextureCameraMatrices,this._uTextureModelMatrices,this._uTexturePerObjectIdOffsets);var c=a.eye;e.pickViewMatrix&&(l.bindPickCameraTexture(this._program,this._uTextureCameraMatrices),c=e.pickOrigin||c);var f=[c[0]-u[0],c[1]-u[1],c[2]-u[2]];if(s.uniform3fv(this._uCameraEyeRtc,f),s.uniform1i(this._uRenderPass,n),i.logarithmicDepthBufferEnabled){var p=2/(Math.log(a.project.far+1)/Math.LN2);s.uniform1f(this._uLogDepthBufFC,p)}var A=i._sectionPlanesState.sectionPlanes.length;if(A>0)for(var d=i._sectionPlanesState.sectionPlanes,v=t.layerIndex*A,h=r.renderFlags,I=0;I<A;I++){var y=this._uSectionPlanes[I];if(y){var m=h.sectionPlanesActivePerLayer[v+I];if(s.uniform1i(y.active,m?1:0),m){var w=d[I];if(u){var g=ge(w.dist,w.dir,u,Tc);s.uniform3fv(y.pos,g)}else s.uniform3fv(y.pos,w.pos);s.uniform3fv(y.dir,w.dir)}}}o.numIndices8Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),s.drawArrays(s.TRIANGLES,0,o.numIndices8Bits)),o.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),s.drawArrays(s.TRIANGLES,0,o.numIndices16Bits)),o.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),s.drawArrays(s.TRIANGLES,0,o.numIndices32Bits)),e.drawElements++}},{key:"_allocate",value:function(){var e=this._scene,t=e.canvas.gl;if(this._program=new ft(t,this._buildShader()),this._program.errors)this.errors=this._program.errors;else{var n=this._program;this._uRenderPass=n.getLocation("renderPass"),this._uPickInvisible=n.getLocation("pickInvisible"),this._uSectionPlanes=[];for(var r=0,i=e._sectionPlanesState.sectionPlanes.length;r<i;r++)this._uSectionPlanes.push({active:n.getLocation("sectionPlaneActive"+r),pos:n.getLocation("sectionPlanePos"+r),dir:n.getLocation("sectionPlaneDir"+r)});this._withSAO&&(this._uOcclusionTexture="uOcclusionTexture",this._uSAOParams=n.getLocation("uSAOParams")),e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=n.getLocation("logDepthBufFC")),this._uTexturePerObjectIdPositionsDecodeMatrix="uTexturePerObjectIdPositionsDecodeMatrix",this._uTexturePerObjectIdColorsAndFlags="uTexturePerObjectIdColorsAndFlags",this._uTexturePerVertexIdCoordinates="uTexturePerVertexIdCoordinates",this._uTexturePerPolygonIdNormals="uTexturePerPolygonIdNormals",this._uTexturePerPolygonIdIndices="uTexturePerPolygonIdIndices",this._uTexturePerPolygonIdPortionIds="uTexturePerPolygonIdPortionIds",this._uTextureCameraMatrices="uTextureCameraMatrices",this._uTextureModelMatrices="uTextureModelMatrices",this._uTexturePerObjectIdOffsets="uTexturePerObjectIdOffsets",this._uCameraEyeRtc=n.getLocation("uCameraEyeRtc")}}},{key:"_bindProgram",value:function(e){var t=this._scene.canvas.gl;this._program.bind(),t.uniform1i(this._uPickInvisible,e.pickInvisible)}},{key:"_buildShader",value:function(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,n=[];return n.push("#version 300 es"),n.push("// Batched geometry picking vertex shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("precision highp usampler2D;"),n.push("precision highp isampler2D;"),n.push("precision highp sampler2D;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("precision mediump usampler2D;"),n.push("precision mediump isampler2D;"),n.push("precision mediump sampler2D;"),n.push("#endif"),n.push("uniform int renderPass;"),e.entityOffsetsEnabled&&n.push("in vec3 offset;"),n.push("uniform bool pickInvisible;"),n.push("uniform highp sampler2D uTexturePerObjectIdPositionsDecodeMatrix;"),n.push("uniform lowp usampler2D uTexturePerObjectIdColorsAndFlags;"),n.push("uniform highp sampler2D uTexturePerObjectIdOffsets;"),n.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),n.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),n.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),n.push("uniform highp sampler2D uTextureCameraMatrices;"),n.push("uniform highp sampler2D uTextureModelMatrices;"),n.push("uniform vec3 uCameraEyeRtc;"),n.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("out float vFragDepth;"),n.push("out float isPerspective;")),n.push("bool isPerspectiveMatrix(mat4 m) {"),n.push(" return (m[2][3] == - 1.0);"),n.push("}"),t&&(n.push("smooth out vec4 vWorldPosition;"),n.push("flat out uvec4 vFlags2;")),n.push("out vec4 vPickColor;"),n.push("void main(void) {"),n.push("mat4 viewMatrix = mat4 (texelFetch (uTextureCameraMatrices, ivec2(0, 0), 0), texelFetch (uTextureCameraMatrices, ivec2(1, 0), 0), texelFetch (uTextureCameraMatrices, ivec2(2, 0), 0), texelFetch (uTextureCameraMatrices, ivec2(3, 0), 0));"),n.push("mat4 viewNormalMatrix = mat4 (texelFetch (uTextureCameraMatrices, ivec2(0, 1), 0), texelFetch (uTextureCameraMatrices, ivec2(1, 1), 0), texelFetch (uTextureCameraMatrices, ivec2(2, 1), 0), texelFetch (uTextureCameraMatrices, ivec2(3, 1), 0));"),n.push("mat4 projMatrix = mat4 (texelFetch (uTextureCameraMatrices, ivec2(0, 2), 0), texelFetch (uTextureCameraMatrices, ivec2(1, 2), 0), texelFetch (uTextureCameraMatrices, ivec2(2, 2), 0), texelFetch (uTextureCameraMatrices, ivec2(3, 2), 0));"),n.push("mat4 worldMatrix = mat4 (texelFetch (uTextureModelMatrices, ivec2(0, 0), 0), texelFetch (uTextureModelMatrices, ivec2(1, 0), 0), texelFetch (uTextureModelMatrices, ivec2(2, 0), 0), texelFetch (uTextureModelMatrices, ivec2(3, 0), 0));"),n.push("mat4 worldNormalMatrix = mat4 (texelFetch (uTextureModelMatrices, ivec2(0, 1), 0), texelFetch (uTextureModelMatrices, ivec2(1, 1), 0), texelFetch (uTextureModelMatrices, ivec2(2, 1), 0), texelFetch (uTextureModelMatrices, ivec2(3, 1), 0));"),n.push("int polygonIndex = gl_VertexID / 3;"),n.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),n.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),n.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),n.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),n.push("uvec4 flags = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),n.push("uvec4 flags2 = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),n.push("if (int(flags.w) != renderPass) {"),n.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),n.push(" return;"),n.push("} else {"),n.push("ivec4 packedVertexBase = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),n.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),n.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),n.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),n.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),n.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),n.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),n.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),n.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),n.push("mat4 positionsDecodeMatrix = mat4 (texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),n.push("uint solid = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),n.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),n.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),n.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),n.push("uvec4 color = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),n.push("if (color.a == 0u) {"),n.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),n.push(" return;"),n.push("};"),n.push("vPickColor = vec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+1, objectIndexCoords.y), 0)) / 255.0;"),n.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),n.push("vec3 position;"),n.push("position = positions[gl_VertexID % 3];"),n.push("if (solid != 1u) {"),n.push("if (isPerspectiveMatrix(projMatrix)) {"),n.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(worldMatrix * positionsDecodeMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),n.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),n.push("position = positions[2 - (gl_VertexID % 3)];"),n.push("}"),n.push("} else {"),n.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*positionsDecodeMatrix)) * vec4(normal,1)).xyz);"),n.push("if (viewNormal.z < 0.0) {"),n.push("position = positions[2 - (gl_VertexID % 3)];"),n.push("}"),n.push("}"),n.push("}"),n.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),n.push("vec4 offset = vec4(texelFetch (uTexturePerObjectIdOffsets, objectIndexCoords, 0).rgb, 0.0);"),n.push("worldPosition.xyz = worldPosition.xyz + offset.xyz;"),n.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(n.push(" vWorldPosition = worldPosition;"),n.push(" vFlags2 = flags2;")),n.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(n.push("vFragDepth = 1.0 + clipPos.w;"),n.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),n.push("gl_Position = clipPos;"),n.push(" }"),n.push("}"),n}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,n=t.sectionPlanes.length>0,r=[];if(r.push("#version 300 es"),r.push("// Batched geometry picking fragment shader"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),e.logarithmicDepthBufferEnabled&&(r.push("in float isPerspective;"),r.push("uniform float logDepthBufFC;"),r.push("in float vFragDepth;")),n){r.push("in vec4 vWorldPosition;"),r.push("flat in uvec4 vFlags2;");for(var i=0;i<t.sectionPlanes.length;i++)r.push("uniform bool sectionPlaneActive"+i+";"),r.push("uniform vec3 sectionPlanePos"+i+";"),r.push("uniform vec3 sectionPlaneDir"+i+";")}if(r.push("in vec4 vPickColor;"),r.push("out vec4 outPickColor;"),r.push("void main(void) {"),n){r.push(" bool clippable = (float(vFlags2.x) > 0.0);"),r.push(" if (clippable) {"),r.push(" float dist = 0.0;");for(i=0;i<t.sectionPlanes.length;i++)r.push(" if (sectionPlaneActive"+i+") {"),r.push(" dist += clamp(dot(-sectionPlaneDir"+i+".xyz, vWorldPosition.xyz - sectionPlanePos"+i+".xyz), 0.0, 1000.0);"),r.push(" }");r.push(" if (dist > 0.0) { discard; }"),r.push(" }")}return e.logarithmicDepthBufferEnabled&&r.push(" gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),r.push(" outPickColor = vPickColor; "),r.push("}"),r}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),e}(),bc=Z.vec3(),Dc=function(){function e(t){b(this,e),this._scene=t,this._hash=this._getHash(),this._allocate()}return P(e,[{key:"getValid",value:function(){return this._hash===this._getHash()}},{key:"_getHash",value:function(){return this._scene._sectionPlanesState.getHash()}},{key:"drawLayer",value:function(e,t,n){var r=t.model,i=r.scene,a=i.camera,s=i.canvas.gl,o=t._state,l=o.textureState,u=t._state.origin;this._program||this._allocate(),e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram()),l.bindCommonTextures(this._program,this._uTexturePerObjectIdPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this._uTexturePerObjectIdColorsAndFlags,this._uTextureCameraMatrices,this._uTextureModelMatrices,this._uTexturePerObjectIdOffsets);var c=a.eye;e.pickViewMatrix&&(l.bindPickCameraTexture(this._program,this._uTextureCameraMatrices),c=e.pickOrigin||c);var f=[c[0]-u[0],c[1]-u[1],c[2]-u[2]];if(s.uniform3fv(this._uCameraEyeRtc,f),s.uniform1i(this._uRenderPass,n),s.uniform1i(this._uPickInvisible,e.pickInvisible),s.uniform1f(this._uPickZNear,e.pickZNear),s.uniform1f(this._uPickZFar,e.pickZFar),i.logarithmicDepthBufferEnabled){var p=2/(Math.log(e.pickZFar+1)/Math.LN2);s.uniform1f(this._uLogDepthBufFC,p)}var A=i._sectionPlanesState.sectionPlanes.length;if(A>0)for(var d=i._sectionPlanesState.sectionPlanes,v=t.layerIndex*A,h=r.renderFlags,I=0;I<A;I++){var y=this._uSectionPlanes[I];if(y){var m=h.sectionPlanesActivePerLayer[v+I];if(s.uniform1i(y.active,m?1:0),m){var w=d[I];if(u){var g=ge(w.dist,w.dir,u,bc);s.uniform3fv(y.pos,g)}else s.uniform3fv(y.pos,w.pos);s.uniform3fv(y.dir,w.dir)}}}o.numIndices8Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),s.drawArrays(s.TRIANGLES,0,o.numIndices8Bits)),o.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),s.drawArrays(s.TRIANGLES,0,o.numIndices16Bits)),o.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),s.drawArrays(s.TRIANGLES,0,o.numIndices32Bits)),e.drawElements++}},{key:"_allocate",value:function(){var e=this._scene,t=e.canvas.gl;if(this._program=new ft(t,this._buildShader()),this._program.errors)this.errors=this._program.errors;else{var n=this._program;this._uRenderPass=n.getLocation("renderPass"),this._uPickInvisible=n.getLocation("pickInvisible"),this._uSectionPlanes=[];for(var r=0,i=e._sectionPlanesState.sectionPlanes.length;r<i;r++)this._uSectionPlanes.push({active:n.getLocation("sectionPlaneActive"+r),pos:n.getLocation("sectionPlanePos"+r),dir:n.getLocation("sectionPlaneDir"+r)});this._aPackedVertexId=n.getAttribute("packedVertexId"),this._uPickZNear=n.getLocation("pickZNear"),this._uPickZFar=n.getLocation("pickZFar"),e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=n.getLocation("logDepthBufFC")),this._uTexturePerObjectIdPositionsDecodeMatrix="uTexturePerObjectIdPositionsDecodeMatrix",this._uTexturePerObjectIdColorsAndFlags="uTexturePerObjectIdColorsAndFlags",this._uTexturePerVertexIdCoordinates="uTexturePerVertexIdCoordinates",this._uTexturePerPolygonIdNormals="uTexturePerPolygonIdNormals",this._uTexturePerPolygonIdIndices="uTexturePerPolygonIdIndices",this._uTexturePerPolygonIdPortionIds="uTexturePerPolygonIdPortionIds",this._uTextureCameraMatrices="uTextureCameraMatrices",this._uTextureModelMatrices="uTextureModelMatrices",this._uTexturePerObjectIdOffsets="uTexturePerObjectIdOffsets",this._uCameraEyeRtc=n.getLocation("uCameraEyeRtc")}}},{key:"_bindProgram",value:function(){this._program.bind()}},{key:"_buildShader",value:function(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,n=[];return n.push("#version 300 es"),n.push("// Triangles dataTexture pick depth vertex shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("precision highp usampler2D;"),n.push("precision highp isampler2D;"),n.push("precision highp sampler2D;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("precision mediump usampler2D;"),n.push("precision mediump isampler2D;"),n.push("precision mediump sampler2D;"),n.push("#endif"),n.push("uniform int renderPass;"),e.entityOffsetsEnabled&&n.push("in vec3 offset;"),n.push("uniform bool pickInvisible;"),n.push("uniform highp sampler2D uTexturePerObjectIdPositionsDecodeMatrix;"),n.push("uniform lowp usampler2D uTexturePerObjectIdColorsAndFlags;"),n.push("uniform highp sampler2D uTexturePerObjectIdOffsets;"),n.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),n.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),n.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),n.push("uniform highp sampler2D uTextureCameraMatrices;"),n.push("uniform highp sampler2D uTextureModelMatrices;"),n.push("uniform vec3 uCameraEyeRtc;"),n.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("out float vFragDepth;"),n.push("out float isPerspective;")),n.push("bool isPerspectiveMatrix(mat4 m) {"),n.push(" return (m[2][3] == - 1.0);"),n.push("}"),t&&(n.push("out vec4 vWorldPosition;"),n.push("flat out uint vFlags2;")),n.push("out vec4 vViewPosition;"),n.push("void main(void) {"),n.push("mat4 viewMatrix = mat4 (texelFetch (uTextureCameraMatrices, ivec2(0, 0), 0), texelFetch (uTextureCameraMatrices, ivec2(1, 0), 0), texelFetch (uTextureCameraMatrices, ivec2(2, 0), 0), texelFetch (uTextureCameraMatrices, ivec2(3, 0), 0));"),n.push("mat4 viewNormalMatrix = mat4 (texelFetch (uTextureCameraMatrices, ivec2(0, 1), 0), texelFetch (uTextureCameraMatrices, ivec2(1, 1), 0), texelFetch (uTextureCameraMatrices, ivec2(2, 1), 0), texelFetch (uTextureCameraMatrices, ivec2(3, 1), 0));"),n.push("mat4 projMatrix = mat4 (texelFetch (uTextureCameraMatrices, ivec2(0, 2), 0), texelFetch (uTextureCameraMatrices, ivec2(1, 2), 0), texelFetch (uTextureCameraMatrices, ivec2(2, 2), 0), texelFetch (uTextureCameraMatrices, ivec2(3, 2), 0));"),n.push("mat4 worldMatrix = mat4 (texelFetch (uTextureModelMatrices, ivec2(0, 0), 0), texelFetch (uTextureModelMatrices, ivec2(1, 0), 0), texelFetch (uTextureModelMatrices, ivec2(2, 0), 0), texelFetch (uTextureModelMatrices, ivec2(3, 0), 0));"),n.push("mat4 worldNormalMatrix = mat4 (texelFetch (uTextureModelMatrices, ivec2(0, 1), 0), texelFetch (uTextureModelMatrices, ivec2(1, 1), 0), texelFetch (uTextureModelMatrices, ivec2(2, 1), 0), texelFetch (uTextureModelMatrices, ivec2(3, 1), 0));"),n.push("int polygonIndex = gl_VertexID / 3;"),n.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),n.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),n.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),n.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),n.push("uvec4 flags = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),n.push("uvec4 flags2 = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),n.push("if (int(flags.w) != renderPass) {"),n.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),n.push(" return;"),n.push("} else {"),n.push("ivec4 packedVertexBase = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),n.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),n.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),n.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),n.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),n.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),n.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),n.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),n.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),n.push("mat4 positionsDecodeMatrix = mat4 (texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),n.push("uint solid = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),n.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),n.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),n.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),n.push("uvec4 color = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),n.push("if (color.a == 0u) {"),n.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),n.push(" return;"),n.push("};"),n.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),n.push("vec3 position;"),n.push("position = positions[gl_VertexID % 3];"),n.push("if (solid != 1u) {"),n.push("if (isPerspectiveMatrix(projMatrix)) {"),n.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(worldMatrix * positionsDecodeMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),n.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),n.push("position = positions[2 - (gl_VertexID % 3)];"),n.push("}"),n.push("} else {"),n.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*positionsDecodeMatrix)) * vec4(normal,1)).xyz);"),n.push("if (viewNormal.z < 0.0) {"),n.push("position = positions[2 - (gl_VertexID % 3)];"),n.push("}"),n.push("}"),n.push("}"),n.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),n.push("vec4 offset = vec4(texelFetch (uTexturePerObjectIdOffsets, objectIndexCoords, 0).rgb, 0.0);"),n.push("worldPosition.xyz = worldPosition.xyz + offset.xyz;"),n.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(n.push(" vWorldPosition = worldPosition;"),n.push(" vFlags2 = flags2.r;")),n.push("vViewPosition = viewPosition;"),n.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(n.push("vFragDepth = 1.0 + clipPos.w;"),n.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),n.push("gl_Position = clipPos;"),n.push(" }"),n.push("}"),n}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,n=t.sectionPlanes.length>0,r=[];if(r.push("#version 300 es"),r.push("// Triangles dataTexture pick depth fragment shader"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),e.logarithmicDepthBufferEnabled&&(r.push("in float isPerspective;"),r.push("uniform float logDepthBufFC;"),r.push("in float vFragDepth;")),r.push("uniform float pickZNear;"),r.push("uniform float pickZFar;"),n){r.push("in vec4 vWorldPosition;"),r.push("flat in uint vFlags2;");for(var i=0;i<t.sectionPlanes.length;i++)r.push("uniform bool sectionPlaneActive"+i+";"),r.push("uniform vec3 sectionPlanePos"+i+";"),r.push("uniform vec3 sectionPlaneDir"+i+";")}if(r.push("in vec4 vViewPosition;"),r.push("vec4 packDepth(const in float depth) {"),r.push(" const vec4 bitShift = vec4(256.0*256.0*256.0, 256.0*256.0, 256.0, 1.0);"),r.push(" const vec4 bitMask = vec4(0.0, 1.0/256.0, 1.0/256.0, 1.0/256.0);"),r.push(" vec4 res = fract(depth * bitShift);"),r.push(" res -= res.xxyz * bitMask;"),r.push(" return res;"),r.push("}"),r.push("out vec4 outPackedDepth;"),r.push("void main(void) {"),n){r.push(" bool clippable = vFlags2 > 0u;"),r.push(" if (clippable) {"),r.push(" float dist = 0.0;");for(i=0;i<t.sectionPlanes.length;i++)r.push(" if (sectionPlaneActive"+i+") {"),r.push(" dist += clamp(dot(-sectionPlaneDir"+i+".xyz, vWorldPosition.xyz - sectionPlanePos"+i+".xyz), 0.0, 1000.0);"),r.push(" }");r.push(" if (dist > 0.0) { discard; }"),r.push(" }")}return e.logarithmicDepthBufferEnabled&&r.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),r.push(" float zNormalizedDepth = abs((pickZNear + vViewPosition.z) / (pickZFar - pickZNear));"),r.push(" outPackedDepth = packDepth(zNormalizedDepth); "),r.push("}"),r}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),e}(),Pc=Z.vec3(),Rc=function(){function e(t){b(this,e),this._scene=t,this._hash=this._getHash(),this._allocate()}return P(e,[{key:"getValid",value:function(){return this._hash===this._getHash()}},{key:"_getHash",value:function(){return this._scene._sectionPlanesState.getHash()}},{key:"drawLayer",value:function(e,t,n){var r=t.model,i=r.scene,a=i.camera,s=i.canvas.gl,o=t._state,l=o.textureState,u=t._state.origin;e.snapPickOrigin[0]=u[0],e.snapPickOrigin[1]=u[1],e.snapPickOrigin[2]=u[2];var c=t.aabb,f=[Z.safeInv(c[3]-c[0])*Z.MAX_INT,Z.safeInv(c[4]-c[1])*Z.MAX_INT,Z.safeInv(c[5]-c[2])*Z.MAX_INT];e.snapPickCoordinateScale[0]=Z.safeInv(f[0]),e.snapPickCoordinateScale[1]=Z.safeInv(f[1]),e.snapPickCoordinateScale[2]=Z.safeInv(f[2]),this._program||this._allocate(),e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram()),l.bindCommonTextures(this._program,this._uTexturePerObjectIdPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this._uTexturePerObjectIdColorsAndFlags,this._uTextureCameraMatrices,this._uTextureModelMatrices,this._uTexturePerObjectIdOffsets);var p=a.eye;e.pickViewMatrix&&(l.bindPickCameraTexture(this._program,this._uTextureCameraMatrices),p=e.pickOrigin||p);var A=[p[0]-u[0],p[1]-u[1],p[2]-u[2]];if(s.uniform3fv(this._uCameraEyeRtc,A),s.uniform2fv(this.uVectorA,e.snapVectorA),s.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),s.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),s.uniform3fv(this._uCoordinateScaler,f),s.uniform1i(this._uRenderPass,n),s.uniform1i(this._uPickInvisible,e.pickInvisible),i.logarithmicDepthBufferEnabled){var d=2/(Math.log(e.pickZFar+1)/Math.LN2);s.uniform1f(this._uLogDepthBufFC,d)}var v=i._sectionPlanesState.sectionPlanes.length;if(v>0)for(var h=i._sectionPlanesState.sectionPlanes,I=t.layerIndex*v,y=r.renderFlags,m=0;m<v;m++){var w=this._uSectionPlanes[m];if(w){var g=y.sectionPlanesActivePerLayer[I+m];if(s.uniform1i(w.active,g?1:0),g){var T=h[m];if(u){var E=ge(T.dist,T.dir,u,Pc);s.uniform3fv(w.pos,E)}else s.uniform3fv(w.pos,T.pos);s.uniform3fv(w.dir,T.dir)}}}var b="edge"===e.snapMode?s.LINES:s.POINTS;o.numEdgeIndices8Bits>0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,8),s.drawArrays(b,0,o.numEdgeIndices8Bits)),o.numEdgeIndices16Bits>0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,16),s.drawArrays(b,0,o.numEdgeIndices16Bits)),o.numEdgeIndices32Bits>0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,32),s.drawArrays(b,0,o.numEdgeIndices32Bits)),e.drawElements++}},{key:"_allocate",value:function(){var e=this._scene,t=e.canvas.gl;if(this._program=new ft(t,this._buildShader()),this._program.errors)this.errors=this._program.errors;else{var n=this._program;this._uRenderPass=n.getLocation("renderPass"),this._uPickInvisible=n.getLocation("pickInvisible"),this._uSectionPlanes=[];for(var r=0,i=e._sectionPlanesState.sectionPlanes.length;r<i;r++)this._uSectionPlanes.push({active:n.getLocation("sectionPlaneActive"+r),pos:n.getLocation("sectionPlanePos"+r),dir:n.getLocation("sectionPlaneDir"+r)});e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=n.getLocation("logDepthBufFC")),this._uTexturePerObjectIdPositionsDecodeMatrix="uTexturePerObjectIdPositionsDecodeMatrix",this._uTexturePerObjectIdColorsAndFlags="uTexturePerObjectIdColorsAndFlags",this._uTexturePerVertexIdCoordinates="uTexturePerVertexIdCoordinates",this._uTexturePerPolygonIdEdgeIndices="uTexturePerPolygonIdEdgeIndices",this._uTexturePerEdgeIdPortionIds="uTexturePerEdgeIdPortionIds",this._uTextureCameraMatrices="uTextureCameraMatrices",this._uTextureModelMatrices="uTextureModelMatrices",this._uTexturePerObjectIdOffsets="uTexturePerObjectIdOffsets",this._uCameraEyeRtc=n.getLocation("uCameraEyeRtc"),this.uVectorA=n.getLocation("uSnapVectorA"),this.uInverseVectorAB=n.getLocation("uSnapInvVectorAB"),this._uLayerNumber=n.getLocation("uLayerNumber"),this._uCoordinateScaler=n.getLocation("uCoordinateLayer")}}},{key:"_bindProgram",value:function(){this._program.bind()}},{key:"_buildShader",value:function(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,n=[];return n.push("#version 300 es"),n.push("// Batched geometry edges drawing vertex shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("precision highp usampler2D;"),n.push("precision highp isampler2D;"),n.push("precision highp sampler2D;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("precision mediump usampler2D;"),n.push("precision mediump isampler2D;"),n.push("precision mediump sampler2D;"),n.push("#endif"),n.push("uniform int renderPass;"),e.entityOffsetsEnabled&&n.push("in vec3 offset;"),n.push("uniform highp sampler2D uTexturePerObjectIdPositionsDecodeMatrix;"),n.push("uniform lowp usampler2D uTexturePerObjectIdColorsAndFlags;"),n.push("uniform highp sampler2D uTexturePerObjectIdOffsets;"),n.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),n.push("uniform highp usampler2D uTexturePerPolygonIdEdgeIndices;"),n.push("uniform mediump usampler2D uTexturePerEdgeIdPortionIds;"),n.push("uniform highp sampler2D uTextureCameraMatrices;"),n.push("uniform highp sampler2D uTextureModelMatrices;"),n.push("uniform vec3 uCameraEyeRtc;"),n.push("uniform vec2 uSnapVectorA;"),n.push("uniform vec2 uSnapInvVectorAB;"),n.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("out float vFragDepth;"),n.push("bool isPerspectiveMatrix(mat4 m) {"),n.push(" return (m[2][3] == - 1.0);"),n.push("}"),n.push("out float isPerspective;")),n.push("vec2 remapClipPos(vec2 clipPos) {"),n.push(" float x = (clipPos.x - uSnapVectorA.x) * uSnapInvVectorAB.x;"),n.push(" float y = (clipPos.y - uSnapVectorA.y) * uSnapInvVectorAB.y;"),n.push(" return vec2(x, y);"),n.push("}"),t&&(n.push("out vec4 vWorldPosition;"),n.push("flat out uint vFlags2;")),n.push("out vec4 vViewPosition;"),n.push("out highp vec3 relativeToOriginPosition;"),n.push("void main(void) {"),n.push("mat4 viewMatrix = mat4 (texelFetch (uTextureCameraMatrices, ivec2(0, 0), 0), texelFetch (uTextureCameraMatrices, ivec2(1, 0), 0), texelFetch (uTextureCameraMatrices, ivec2(2, 0), 0), texelFetch (uTextureCameraMatrices, ivec2(3, 0), 0));"),n.push("mat4 viewNormalMatrix = mat4 (texelFetch (uTextureCameraMatrices, ivec2(0, 1), 0), texelFetch (uTextureCameraMatrices, ivec2(1, 1), 0), texelFetch (uTextureCameraMatrices, ivec2(2, 1), 0), texelFetch (uTextureCameraMatrices, ivec2(3, 1), 0));"),n.push("mat4 projMatrix = mat4 (texelFetch (uTextureCameraMatrices, ivec2(0, 2), 0), texelFetch (uTextureCameraMatrices, ivec2(1, 2), 0), texelFetch (uTextureCameraMatrices, ivec2(2, 2), 0), texelFetch (uTextureCameraMatrices, ivec2(3, 2), 0));"),n.push("mat4 worldMatrix = mat4 (texelFetch (uTextureModelMatrices, ivec2(0, 0), 0), texelFetch (uTextureModelMatrices, ivec2(1, 0), 0), texelFetch (uTextureModelMatrices, ivec2(2, 0), 0), texelFetch (uTextureModelMatrices, ivec2(3, 0), 0));"),n.push("mat4 worldNormalMatrix = mat4 (texelFetch (uTextureModelMatrices, ivec2(0, 1), 0), texelFetch (uTextureModelMatrices, ivec2(1, 1), 0), texelFetch (uTextureModelMatrices, ivec2(2, 1), 0), texelFetch (uTextureModelMatrices, ivec2(3, 1), 0));"),n.push("int edgeIndex = gl_VertexID / 2;"),n.push("int h_packed_object_id_index = (edgeIndex >> 3) & 4095;"),n.push("int v_packed_object_id_index = (edgeIndex >> 3) >> 12;"),n.push("int objectIndex = int(texelFetch(uTexturePerEdgeIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),n.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),n.push("uvec4 flags = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),n.push("uvec4 flags2 = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),n.push("{"),n.push("ivec4 packedVertexBase = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),n.push("ivec4 packedEdgeIndexBaseOffset = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+6, objectIndexCoords.y), 0));"),n.push("int edgeIndexBaseOffset = (packedEdgeIndexBaseOffset.r << 24) + (packedEdgeIndexBaseOffset.g << 16) + (packedEdgeIndexBaseOffset.b << 8) + packedEdgeIndexBaseOffset.a;"),n.push("int h_index = (edgeIndex - edgeIndexBaseOffset) & 4095;"),n.push("int v_index = (edgeIndex - edgeIndexBaseOffset) >> 12;"),n.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdEdgeIndices, ivec2(h_index, v_index), 0));"),n.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),n.push("int indexPositionH = uniqueVertexIndexes[gl_VertexID % 2] & 4095;"),n.push("int indexPositionV = uniqueVertexIndexes[gl_VertexID % 2] >> 12;"),n.push("mat4 positionsDecodeMatrix = mat4 (texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),n.push("uvec4 flags = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),n.push("uvec4 flags2 = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),n.push("vec3 position = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH, indexPositionV), 0));"),n.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),n.push("vec4 offset = vec4(texelFetch (uTexturePerObjectIdOffsets, objectIndexCoords, 0).rgb, 0.0);"),n.push("worldPosition.xyz = worldPosition.xyz + offset.xyz;"),n.push("relativeToOriginPosition = worldPosition.xyz;"),n.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(n.push(" vWorldPosition = worldPosition;"),n.push(" vFlags2 = flags2.r;")),n.push("vViewPosition = viewPosition;"),n.push("vec4 clipPos = projMatrix * viewPosition;"),n.push("float tmp = clipPos.w;"),n.push("clipPos.xyzw /= tmp;"),n.push("clipPos.xy = remapClipPos(clipPos.xy);"),n.push("clipPos.xyzw *= tmp;"),n.push("vViewPosition = clipPos;"),e.logarithmicDepthBufferEnabled&&(n.push("vFragDepth = 1.0 + clipPos.w;"),n.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),n.push("gl_Position = clipPos;"),n.push("gl_PointSize = 1.0;"),n.push(" }"),n.push("}"),n}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,n=t.sectionPlanes.length>0,r=[];if(r.push("#version 300 es"),r.push("// Triangles dataTexture pick depth fragment shader"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),e.logarithmicDepthBufferEnabled&&(r.push("in float isPerspective;"),r.push("uniform float logDepthBufFC;"),r.push("in float vFragDepth;")),r.push("uniform int uLayerNumber;"),r.push("uniform vec3 uCoordinateLayer;"),n){r.push("in vec4 vWorldPosition;"),r.push("flat in uint vFlags2;");for(var i=0,a=t.sectionPlanes.length;i<a;i++)r.push("uniform bool sectionPlaneActive"+i+";"),r.push("uniform vec3 sectionPlanePos"+i+";"),r.push("uniform vec3 sectionPlaneDir"+i+";")}if(r.push("in highp vec3 relativeToOriginPosition;"),r.push("out highp ivec4 outCoords;"),r.push("void main(void) {"),n){r.push(" bool clippable = vFlags2 > 0u;"),r.push(" if (clippable) {"),r.push(" float dist = 0.0;");for(var s=0;s<t.sectionPlanes.length;s++)r.push(" if (sectionPlaneActive"+s+") {"),r.push(" dist += clamp(dot(-sectionPlaneDir"+s+".xyz, vWorldPosition.xyz - sectionPlanePos"+s+".xyz), 0.0, 1000.0);"),r.push(" }");r.push(" if (dist > 0.0) { discard; }"),r.push(" }")}return e.logarithmicDepthBufferEnabled&&r.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),r.push("outCoords = ivec4(relativeToOriginPosition.xyz*uCoordinateLayer.xyz, uLayerNumber);"),r.push("}"),r}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),e}(),Cc=Z.vec3(),_c=function(){function e(t){b(this,e),this._scene=t,this._hash=this._getHash(),this._allocate()}return P(e,[{key:"getValid",value:function(){return this._hash===this._getHash()}},{key:"_getHash",value:function(){return this._scene._sectionPlanesState.getHash()}},{key:"drawLayer",value:function(e,t,n){var r=t.model,i=r.scene,a=i.camera,s=i.canvas.gl,o=t._state,l=o.textureState,u=t._state.origin;e.snapPickOrigin[0]=u[0],e.snapPickOrigin[1]=u[1],e.snapPickOrigin[2]=u[2];var c=t.aabb,f=[Z.safeInv(c[3]-c[0])*Z.MAX_INT,Z.safeInv(c[4]-c[1])*Z.MAX_INT,Z.safeInv(c[5]-c[2])*Z.MAX_INT];e.snapPickCoordinateScale[0]=Z.safeInv(f[0]),e.snapPickCoordinateScale[1]=Z.safeInv(f[1]),e.snapPickCoordinateScale[2]=Z.safeInv(f[2]),this._program||this._allocate(),e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram()),l.bindCommonTextures(this._program,this._uTexturePerObjectIdPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this._uTexturePerObjectIdColorsAndFlags,this._uTextureCameraMatrices,this._uTextureModelMatrices,this._uTexturePerObjectIdOffsets);var p=a.eye;e.pickViewMatrix&&(l.bindPickCameraTexture(this._program,this._uTextureCameraMatrices),p=e.pickOrigin||p);var A=[p[0]-u[0],p[1]-u[1],p[2]-u[2]];if(s.uniform3fv(this._uCameraEyeRtc,A),s.uniform2fv(this._uVectorA,e.snapVectorA),s.uniform2fv(this._uInverseVectorAB,e.snapInvVectorAB),s.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),s.uniform3fv(this._uCoordinateScaler,f),s.uniform1i(this._uRenderPass,n),s.uniform1i(this._uPickInvisible,e.pickInvisible),i.logarithmicDepthBufferEnabled){var d=2/(Math.log(e.pickZFar+1)/Math.LN2);s.uniform1f(this._uLogDepthBufFC,d)}var v=i._sectionPlanesState.sectionPlanes.length;if(v>0)for(var h=i._sectionPlanesState.sectionPlanes,I=t.layerIndex*v,y=r.renderFlags,m=0;m<v;m++){var w=this._uSectionPlanes[m];if(w){var g=y.sectionPlanesActivePerLayer[I+m];if(s.uniform1i(w.active,g?1:0),g){var T=h[m];if(u){var E=getPlaneRTCPos(T.dist,T.dir,u,Cc);s.uniform3fv(w.pos,E)}else s.uniform3fv(w.pos,T.pos);s.uniform3fv(w.dir,T.dir)}}}o.numIndices8Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),s.drawArrays(s.TRIANGLES,0,o.numIndices8Bits)),o.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),s.drawArrays(s.TRIANGLES,0,o.numIndices16Bits)),o.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),s.drawArrays(s.TRIANGLES,0,o.numIndices32Bits)),e.drawElements++}},{key:"_allocate",value:function(){var e=this._scene,t=e.canvas.gl;if(this._program=new ft(t,this._buildShader()),this._program.errors)this.errors=this._program.errors;else{var n=this._program;this._uRenderPass=n.getLocation("renderPass"),this._uPickInvisible=n.getLocation("pickInvisible"),this._uSectionPlanes=[];for(var r=0,i=e._sectionPlanesState.sectionPlanes.length;r<i;r++)this._uSectionPlanes.push({active:n.getLocation("sectionPlaneActive"+r),pos:n.getLocation("sectionPlanePos"+r),dir:n.getLocation("sectionPlaneDir"+r)});e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=n.getLocation("logDepthBufFC")),this._uTexturePerObjectIdPositionsDecodeMatrix="uTexturePerObjectIdPositionsDecodeMatrix",this._uTexturePerObjectIdColorsAndFlags="uTexturePerObjectIdColorsAndFlags",this._uTexturePerVertexIdCoordinates="uTexturePerVertexIdCoordinates",this._uTexturePerPolygonIdIndices="uTexturePerPolygonIdIndices",this._uTexturePerPolygonIdPortionIds="uTexturePerPolygonIdPortionIds",this._uTextureCameraMatrices="uTextureCameraMatrices",this._uTextureModelMatrices="uTextureModelMatrices",this._uTexturePerObjectIdOffsets="uTexturePerObjectIdOffsets",this._uCameraEyeRtc=n.getLocation("uCameraEyeRtc"),this._uVectorA=n.getLocation("uVectorAB"),this._uInverseVectorAB=n.getLocation("uInverseVectorAB"),this._uLayerNumber=n.getLocation("uLayerNumber"),this._uCoordinateScaler=n.getLocation("uCoordinateScaler")}}},{key:"_bindProgram",value:function(){this._program.bind()}},{key:"_buildShader",value:function(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,n=[];return n.push("#version 300 es"),n.push("// TrianglesDataTextureSnapDepthBufInitRenderer vertex shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("precision highp usampler2D;"),n.push("precision highp isampler2D;"),n.push("precision highp sampler2D;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("precision mediump usampler2D;"),n.push("precision mediump isampler2D;"),n.push("precision mediump sampler2D;"),n.push("#endif"),n.push("uniform int renderPass;"),e.entityOffsetsEnabled&&n.push("in vec3 offset;"),n.push("uniform highp sampler2D uTexturePerObjectIdPositionsDecodeMatrix;"),n.push("uniform lowp usampler2D uTexturePerObjectIdColorsAndFlags;"),n.push("uniform highp sampler2D uTexturePerObjectIdOffsets;"),n.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),n.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),n.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),n.push("uniform highp sampler2D uTextureCameraMatrices;"),n.push("uniform highp sampler2D uTextureModelMatrices;"),n.push("uniform vec3 uCameraEyeRtc;"),n.push("uniform vec2 uVectorAB;"),n.push("uniform vec2 uInverseVectorAB;"),n.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("out float vFragDepth;"),n.push("out float isPerspective;")),n.push("bool isPerspectiveMatrix(mat4 m) {"),n.push(" return (m[2][3] == - 1.0);"),n.push("}"),n.push("vec2 remapClipPos(vec2 clipPos) {"),n.push(" float x = (clipPos.x - uVectorAB.x) * uInverseVectorAB.x;"),n.push(" float y = (clipPos.y - uVectorAB.y) * uInverseVectorAB.y;"),n.push(" return vec2(x, y);"),n.push("}"),t&&(n.push("out vec4 vWorldPosition;"),n.push("flat out uint vFlags2;")),n.push("out highp vec3 relativeToOriginPosition;"),n.push("void main(void) {"),n.push("int polygonIndex = gl_VertexID / 3;"),n.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),n.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),n.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),n.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),n.push("uvec4 flags = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),n.push("uvec4 flags2 = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),n.push("{"),n.push("uvec4 color = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),n.push("if (color.a == 0u) {"),n.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),n.push(" return;"),n.push("};"),n.push("mat4 viewMatrix = mat4 (texelFetch (uTextureCameraMatrices, ivec2(0, 0), 0), texelFetch (uTextureCameraMatrices, ivec2(1, 0), 0), texelFetch (uTextureCameraMatrices, ivec2(2, 0), 0), texelFetch (uTextureCameraMatrices, ivec2(3, 0), 0));"),n.push("mat4 viewNormalMatrix = mat4 (texelFetch (uTextureCameraMatrices, ivec2(0, 1), 0), texelFetch (uTextureCameraMatrices, ivec2(1, 1), 0), texelFetch (uTextureCameraMatrices, ivec2(2, 1), 0), texelFetch (uTextureCameraMatrices, ivec2(3, 1), 0));"),n.push("mat4 projMatrix = mat4 (texelFetch (uTextureCameraMatrices, ivec2(0, 2), 0), texelFetch (uTextureCameraMatrices, ivec2(1, 2), 0), texelFetch (uTextureCameraMatrices, ivec2(2, 2), 0), texelFetch (uTextureCameraMatrices, ivec2(3, 2), 0));"),n.push("mat4 worldMatrix = mat4 (texelFetch (uTextureModelMatrices, ivec2(0, 0), 0), texelFetch (uTextureModelMatrices, ivec2(1, 0), 0), texelFetch (uTextureModelMatrices, ivec2(2, 0), 0), texelFetch (uTextureModelMatrices, ivec2(3, 0), 0));"),n.push("mat4 worldNormalMatrix = mat4 (texelFetch (uTextureModelMatrices, ivec2(0, 1), 0), texelFetch (uTextureModelMatrices, ivec2(1, 1), 0), texelFetch (uTextureModelMatrices, ivec2(2, 1), 0), texelFetch (uTextureModelMatrices, ivec2(3, 1), 0));"),n.push("ivec4 packedVertexBase = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),n.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),n.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),n.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),n.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),n.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),n.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),n.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),n.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),n.push("mat4 positionsDecodeMatrix = mat4 (texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),n.push("uint solid = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),n.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),n.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),n.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),n.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),n.push("vec3 position;"),n.push("position = positions[gl_VertexID % 3];"),n.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*positionsDecodeMatrix)) * vec4(normal,1)).xyz);"),n.push("if (solid != 1u) {"),n.push(" if (isPerspectiveMatrix(projMatrix)) {"),n.push(" vec3 uCameraEyeRtcInQuantizedSpace = (inverse(worldMatrix * positionsDecodeMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),n.push(" if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),n.push(" position = positions[2 - (gl_VertexID % 3)];"),n.push(" viewNormal = -viewNormal;"),n.push(" }"),n.push(" } else {"),n.push(" if (viewNormal.z < 0.0) {"),n.push(" position = positions[2 - (gl_VertexID % 3)];"),n.push(" viewNormal = -viewNormal;"),n.push(" }"),n.push(" }"),n.push("}"),n.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),n.push("vec4 offset = vec4(texelFetch (uTexturePerObjectIdOffsets, objectIndexCoords, 0).rgb, 0.0);"),n.push("worldPosition.xyz = worldPosition.xyz + offset.xyz;"),n.push("relativeToOriginPosition = worldPosition.xyz;"),n.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(n.push("vWorldPosition = worldPosition;"),n.push("vFlags2 = flags2.r;")),n.push("vec4 clipPos = projMatrix * viewPosition;"),n.push("float tmp = clipPos.w;"),n.push("clipPos.xyzw /= tmp;"),n.push("clipPos.xy = remapClipPos(clipPos.xy);"),n.push("clipPos.z += 0.0001;"),n.push("clipPos.xyzw *= tmp;"),e.logarithmicDepthBufferEnabled&&(n.push("vFragDepth = 1.0 + clipPos.w;"),n.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),n.push("gl_Position = clipPos;"),n.push(" }"),n.push("}"),n}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,n=t.sectionPlanes.length>0,r=[];if(r.push("#version 300 es"),r.push("// TrianglesDataTextureSnapDepthBufInitRenderer fragment shader"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),e.logarithmicDepthBufferEnabled&&(r.push("in float isPerspective;"),r.push("uniform float logDepthBufFC;"),r.push("in float vFragDepth;")),r.push("uniform int uLayerNumber;"),r.push("uniform vec3 uCoordinateScaler;"),n){r.push("in vec4 vWorldPosition;"),r.push("flat in uint vFlags2;");for(var i=0,a=t.sectionPlanes.length;i<a;i++)r.push("uniform bool sectionPlaneActive"+i+";"),r.push("uniform vec3 sectionPlanePos"+i+";"),r.push("uniform vec3 sectionPlaneDir"+i+";")}if(r.push("in highp vec3 relativeToOriginPosition;"),r.push("out highp ivec4 outCoords;"),r.push("void main(void) {"),n){r.push(" bool clippable = vFlags2 > 0u;"),r.push(" if (clippable) {"),r.push(" float dist = 0.0;");for(var s=0;s<t.sectionPlanes.length;s++)r.push(" if (sectionPlaneActive"+s+") {"),r.push(" dist += clamp(dot(-sectionPlaneDir"+s+".xyz, vWorldPosition.xyz - sectionPlanePos"+s+".xyz), 0.0, 1000.0);"),r.push(" }");r.push(" if (dist > 0.0) { discard; }"),r.push(" }")}return e.logarithmicDepthBufferEnabled&&r.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),r.push("outCoords = ivec4(relativeToOriginPosition.xyz * uCoordinateScaler.xyz, - uLayerNumber);"),r.push("}"),r}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),e}(),Bc=Z.vec3(),Oc=function(){function e(t){b(this,e),this._scene=t,this._hash=this._getHash(),this._allocate()}return P(e,[{key:"getValid",value:function(){return this._hash===this._getHash()}},{key:"_getHash",value:function(){return this._scene._sectionPlanesState.getHash()}},{key:"drawLayer",value:function(e,t,n){var r=t.model,i=r.scene,a=i.camera,s=i.canvas.gl,o=t._state,l=o.textureState,u=t._state.origin;this._program||this._allocate(t),e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram()),l.bindCommonTextures(this._program,this._uTexturePerObjectIdPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this._uTexturePerObjectIdColorsAndFlags,this._uTextureCameraMatrices,this._uTextureModelMatrices,this._uTexturePerObjectIdOffsets);var c=a.eye;e.pickViewMatrix&&(l.bindPickCameraTexture(this._program,this._uTextureCameraMatrices),c=e.pickOrigin||c);var f=[c[0]-u[0],c[1]-u[1],c[2]-u[2]];if(s.uniform3fv(this._uCameraEyeRtc,f),s.uniform1i(this._uRenderPass,n),s.uniform3fv(this._uCameraEyeRtc,f),s.uniform1i(this._uPickInvisible,e.pickInvisible),i.logarithmicDepthBufferEnabled){var p=2/(Math.log(a.project.far+1)/Math.LN2);s.uniform1f(this._uLogDepthBufFC,p)}var A=i._sectionPlanesState.sectionPlanes.length;if(A>0)for(var d=i._sectionPlanesState.sectionPlanes,v=t.layerIndex*A,h=r.renderFlags,I=0;I<A;I++){var y=this._uSectionPlanes[I];if(y){var m=h.sectionPlanesActivePerLayer[v+I];if(s.uniform1i(y.active,m?1:0),m){var w=d[I];if(u){var g=ge(w.dist,w.dir,u,Bc);s.uniform3fv(y.pos,g)}else s.uniform3fv(y.pos,w.pos);s.uniform3fv(y.dir,w.dir)}}}o.numIndices8Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),s.drawArrays(s.TRIANGLES,0,o.numIndices8Bits)),o.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),s.drawArrays(s.TRIANGLES,0,o.numIndices16Bits)),o.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),s.drawArrays(s.TRIANGLES,0,o.numIndices32Bits)),e.drawElements++}},{key:"_allocate",value:function(){var e=this._scene,t=e.canvas.gl;if(this._program=new ft(t,this._buildShader()),this._program.errors)this.errors=this._program.errors;else{var n=this._program;this._uRenderPass=n.getLocation("renderPass"),this._uPickInvisible=n.getLocation("pickInvisible"),this._uSectionPlanes=[];for(var r=0,i=e._sectionPlanesState.sectionPlanes.length;r<i;r++)this._uSectionPlanes.push({active:n.getLocation("sectionPlaneActive"+r),pos:n.getLocation("sectionPlanePos"+r),dir:n.getLocation("sectionPlaneDir"+r)});e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=n.getLocation("logDepthBufFC")),this._uTexturePerObjectIdPositionsDecodeMatrix="uTexturePerObjectIdPositionsDecodeMatrix",this._uTexturePerObjectIdColorsAndFlags="uTexturePerObjectIdColorsAndFlags",this._uTexturePerVertexIdCoordinates="uTexturePerVertexIdCoordinates",this._uTexturePerPolygonIdNormals="uTexturePerPolygonIdNormals",this._uTexturePerPolygonIdIndices="uTexturePerPolygonIdIndices",this._uTexturePerPolygonIdPortionIds="uTexturePerPolygonIdPortionIds",this._uTextureCameraMatrices="uTextureCameraMatrices",this._uTextureModelMatrices="uTextureModelMatrices",this._uTexturePerObjectIdOffsets="uTexturePerObjectIdOffsets",this._uCameraEyeRtc=n.getLocation("uCameraEyeRtc")}}},{key:"_bindProgram",value:function(){this._program.bind()}},{key:"_buildShader",value:function(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,n=[];return n.push("#version 300 es"),n.push("// Triangles dataTexture pick normals vertex shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("precision highp usampler2D;"),n.push("precision highp isampler2D;"),n.push("precision highp sampler2D;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("precision mediump usampler2D;"),n.push("precision mediump isampler2D;"),n.push("precision mediump sampler2D;"),n.push("#endif"),n.push("uniform int renderPass;"),e.entityOffsetsEnabled&&n.push("in vec3 offset;"),n.push("uniform bool pickInvisible;"),n.push("uniform highp sampler2D uTexturePerObjectIdPositionsDecodeMatrix;"),n.push("uniform lowp usampler2D uTexturePerObjectIdColorsAndFlags;"),n.push("uniform highp sampler2D uTexturePerObjectIdOffsets;"),n.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),n.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),n.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),n.push("uniform highp sampler2D uTextureCameraMatrices;"),n.push("uniform highp sampler2D uTextureModelMatrices;"),n.push("uniform vec3 uCameraEyeRtc;"),n.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("out float vFragDepth;"),n.push("out float isPerspective;")),n.push("bool isPerspectiveMatrix(mat4 m) {"),n.push(" return (m[2][3] == - 1.0);"),n.push("}"),t&&(n.push("out vec4 vWorldPosition;"),n.push("flat out uint vFlags2;")),n.push("out vec3 vWorldNormal;"),n.push("void main(void) {"),n.push("mat4 viewMatrix = mat4 (texelFetch (uTextureCameraMatrices, ivec2(0, 0), 0), texelFetch (uTextureCameraMatrices, ivec2(1, 0), 0), texelFetch (uTextureCameraMatrices, ivec2(2, 0), 0), texelFetch (uTextureCameraMatrices, ivec2(3, 0), 0));"),n.push("mat4 projMatrix = mat4 (texelFetch (uTextureCameraMatrices, ivec2(0, 2), 0), texelFetch (uTextureCameraMatrices, ivec2(1, 2), 0), texelFetch (uTextureCameraMatrices, ivec2(2, 2), 0), texelFetch (uTextureCameraMatrices, ivec2(3, 2), 0));"),n.push("mat4 worldMatrix = mat4 (texelFetch (uTextureModelMatrices, ivec2(0, 0), 0), texelFetch (uTextureModelMatrices, ivec2(1, 0), 0), texelFetch (uTextureModelMatrices, ivec2(2, 0), 0), texelFetch (uTextureModelMatrices, ivec2(3, 0), 0));"),n.push("int polygonIndex = gl_VertexID / 3;"),n.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),n.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),n.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),n.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),n.push("uvec4 flags = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),n.push("uvec4 flags2 = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),n.push("if (int(flags.w) != renderPass) {"),n.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),n.push(" return;"),n.push("} else {"),n.push("ivec4 packedVertexBase = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),n.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),n.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),n.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),n.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),n.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),n.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),n.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),n.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),n.push("mat4 positionsDecodeMatrix = mat4 (texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),n.push("uint solid = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),n.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),n.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),n.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),n.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),n.push("vec3 position;"),n.push("position = positions[gl_VertexID % 3];"),n.push("if (solid != 1u) {"),n.push("if (isPerspectiveMatrix(projMatrix)) {"),n.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(worldMatrix * positionsDecodeMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),n.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),n.push("position = positions[2 - (gl_VertexID % 3)];"),n.push("normal = -normal;"),n.push("}"),n.push("} else {"),n.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*positionsDecodeMatrix)) * vec4(normal,1)).xyz);"),n.push("if (viewNormal.z < 0.0) {"),n.push("position = positions[2 - (gl_VertexID % 3)];"),n.push("normal = -normal;"),n.push("}"),n.push("}"),n.push("}"),n.push("normal = -normal;"),n.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),n.push("vec4 offset = vec4(texelFetch (uTexturePerObjectIdOffsets, objectIndexCoords, 0).rgb, 0.0);"),n.push("worldPosition.xyz = worldPosition.xyz + offset.xyz;"),n.push("vec4 viewPosition = viewMatrix * worldPosition; "),n.push("vWorldNormal = normal.xyz;"),n.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(n.push("vFragDepth = 1.0 + clipPos.w;"),n.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(n.push(" vWorldPosition = worldPosition;"),n.push(" vFlags2 = flags2.w;")),n.push("gl_Position = clipPos;"),n.push("}"),n.push("}"),n}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,n=t.sectionPlanes.length>0,r=[];if(r.push("#version 300 es"),r.push("// Triangles dataTexture pick normals fragment shader"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),e.logarithmicDepthBufferEnabled&&(r.push("in float isPerspective;"),r.push("uniform float logDepthBufFC;"),r.push("in float vFragDepth;")),n){r.push("in vec4 vWorldPosition;"),r.push("flat in uint vFlags2;");for(var i=0;i<t.sectionPlanes.length;i++)r.push("uniform bool sectionPlaneActive"+i+";"),r.push("uniform vec3 sectionPlanePos"+i+";"),r.push("uniform vec3 sectionPlaneDir"+i+";")}if(r.push("in vec3 vWorldNormal;"),r.push("out vec4 outNormal;"),r.push("void main(void) {"),n){r.push(" bool clippable = vFlags2 > 0u;"),r.push(" if (clippable) {"),r.push(" float dist = 0.0;");for(i=0;i<t.sectionPlanes.length;i++)r.push(" if (sectionPlaneActive"+i+") {"),r.push(" dist += clamp(dot(-sectionPlaneDir"+i+".xyz, vWorldPosition.xyz - sectionPlanePos"+i+".xyz), 0.0, 1000.0);"),r.push(" }");r.push(" if (dist > 0.0) { discard; }"),r.push(" }")}return e.logarithmicDepthBufferEnabled&&r.push(" gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),r.push(" outNormal = vec4((vWorldNormal * 0.5) + 0.5, 1.0);"),r.push("}"),r}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),e}();Z.vec3();var Sc=function(){function e(t){b(this,e),this._scene=t,this._hash=this._getHash(),this._allocate()}return P(e,[{key:"getValid",value:function(){return this._hash===this._getHash()}},{key:"_getHash",value:function(){return this._scene._sectionPlanesState.getHash()}},{key:"drawLayer",value:function(e,t,n){}},{key:"_allocate",value:function(){var e=this._scene,t=e.canvas.gl;if(this._program=new ft(t,this._buildShader()),this._program.errors)this.errors=this._program.errors;else{var n=this._program;this._uRenderPass=n.getLocation("renderPass"),this._uPositionsDecodeMatrix=n.getLocation("positionsDecodeMatrix"),this._uWorldMatrix=n.getLocation("worldMatrix"),this._uViewMatrix=n.getLocation("viewMatrix"),this._uProjMatrix=n.getLocation("projMatrix"),this._uSectionPlanes=[];for(var r=0,i=e._sectionPlanesState.sectionPlanes.length;r<i;r++)this._uSectionPlanes.push({active:n.getLocation("sectionPlaneActive"+r),pos:n.getLocation("sectionPlanePos"+r),dir:n.getLocation("sectionPlaneDir"+r)});this._aPosition=n.getAttribute("position"),this._aOffset=n.getAttribute("offset"),this._aColor=n.getAttribute("color"),this._aFlags=n.getAttribute("flags"),this._aFlags2=n.getAttribute("flags2"),e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=n.getLocation("logDepthBufFC"))}}},{key:"_bindProgram",value:function(){var e=this._scene,t=e.canvas.gl,n=e.camera.project;if(this._program.bind(),t.uniformMatrix4fv(this._uProjMatrix,!1,n.matrix),e.logarithmicDepthBufferEnabled){var r=2/(Math.log(n.far+1)/Math.LN2);t.uniform1f(this._uLogDepthBufFC,r)}}},{key:"_buildShader",value:function(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,n=[];return n.push("// Triangles dataTexture occlusion vertex shader"),e.logarithmicDepthBufferEnabled&&Ze.SUPPORTED_EXTENSIONS.EXT_frag_depth&&n.push("#extension GL_EXT_frag_depth : enable"),n.push("uniform int renderPass;"),n.push("attribute vec3 position;"),e.entityOffsetsEnabled&&n.push("attribute vec3 offset;"),n.push("attribute vec4 color;"),n.push("attribute vec4 flags;"),n.push("attribute vec4 flags2;"),n.push("uniform mat4 worldMatrix;"),n.push("uniform mat4 viewMatrix;"),n.push("uniform mat4 projMatrix;"),n.push("uniform mat4 positionsDecodeMatrix;"),e.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),Ze.SUPPORTED_EXTENSIONS.EXT_frag_depth&&n.push("varying float vFragDepth;"),n.push("bool isPerspectiveMatrix(mat4 m) {"),n.push(" return (m[2][3] == - 1.0);"),n.push("}"),n.push("varying float isPerspective;")),t&&(n.push("varying vec4 vWorldPosition;"),n.push("varying vec4 vFlags2;")),n.push("void main(void) {"),n.push("if (int(flags.x) != renderPass) {"),n.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),n.push(" } else {"),n.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&n.push(" worldPosition.xyz = worldPosition.xyz + offset;"),n.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(n.push(" vWorldPosition = worldPosition;"),n.push(" vFlags2 = flags2;")),n.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(Ze.SUPPORTED_EXTENSIONS.EXT_frag_depth?n.push("vFragDepth = 1.0 + clipPos.w;"):(n.push("clipPos.z = log2( max( 1e-6, clipPos.w + 1.0 ) ) * logDepthBufFC - 1.0;"),n.push("clipPos.z *= clipPos.w;")),n.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),n.push("gl_Position = clipPos;"),n.push(" }"),n.push("}"),n}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,n=t.sectionPlanes.length>0,r=[];if(r.push("// Triangles dataTexture occlusion fragment shader"),e.logarithmicDepthBufferEnabled&&Ze.SUPPORTED_EXTENSIONS.EXT_frag_depth&&r.push("#extension GL_EXT_frag_depth : enable"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),e.logarithmicDepthBufferEnabled&&Ze.SUPPORTED_EXTENSIONS.EXT_frag_depth&&(r.push("varying float isPerspective;"),r.push("uniform float logDepthBufFC;"),r.push("varying float vFragDepth;")),n){r.push("varying vec4 vWorldPosition;"),r.push("varying vec4 vFlags2;");for(var i=0;i<t.sectionPlanes.length;i++)r.push("uniform bool sectionPlaneActive"+i+";"),r.push("uniform vec3 sectionPlanePos"+i+";"),r.push("uniform vec3 sectionPlaneDir"+i+";")}if(r.push("void main(void) {"),n){r.push(" bool clippable = (float(vFlags2.x) > 0.0);"),r.push(" if (clippable) {"),r.push(" float dist = 0.0;");for(var a=0;a<t.sectionPlanes.length;a++)r.push(" if (sectionPlaneActive"+a+") {"),r.push(" dist += clamp(dot(-sectionPlaneDir"+a+".xyz, vWorldPosition.xyz - sectionPlanePos"+a+".xyz), 0.0, 1000.0);"),r.push(" }");r.push(" if (dist > 0.0) { discard; }"),r.push(" }")}return e.logarithmicDepthBufferEnabled&&Ze.SUPPORTED_EXTENSIONS.EXT_frag_depth&&r.push(" gl_FragDepthEXT = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),r.push(" gl_FragColor = vec4(0.0, 0.0, 1.0, 1.0); "),r.push("}"),r}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),e}();Z.vec4();var Nc=Z.vec3(),Lc=function(){function e(t){b(this,e),this._scene=t,this._allocate(),this._hash=this._getHash()}return P(e,[{key:"getValid",value:function(){return this._hash===this._getHash()}},{key:"_getHash",value:function(){return this._scene._sectionPlanesState.getHash()}},{key:"drawLayer",value:function(e,t,n){var r=this._scene,i=r.camera,a=t.model,s=r.canvas.gl,o=t._state,l=o.textureState,u=t._state.origin;if(this._program||(this._allocate(),!this.errors)){e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e,o)),l.bindCommonTextures(this._program,this._uTexturePerObjectIdPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this._uTexturePerObjectIdColorsAndFlags,this._uTextureCameraMatrices,this._uTextureModelMatrices,this._uTexturePerObjectIdOffsets);var c=i.eye;e.pickViewMatrix&&(l.bindPickCameraTexture(this._program,this._uTextureCameraMatrices),c=e.pickOrigin||c);var f=[c[0]-u[0],c[1]-u[1],c[2]-u[2]];s.uniform3fv(this._uCameraEyeRtc,f),s.uniform1i(this._uRenderPass,n);var p=r._sectionPlanesState.sectionPlanes.length;if(p>0)for(var A=r._sectionPlanesState.sectionPlanes,d=t.layerIndex*p,v=a.renderFlags,h=0;h<p;h++){var I=this._uSectionPlanes[h];if(I){var y=v.sectionPlanesActivePerLayer[d+h];if(s.uniform1i(I.active,y?1:0),y){var m=A[h];if(u){var w=ge(m.dist,m.dir,u,Nc);s.uniform3fv(I.pos,w)}else s.uniform3fv(I.pos,m.pos);s.uniform3fv(I.dir,m.dir)}}}o.numIndices8Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),s.drawArrays(s.TRIANGLES,0,o.numIndices8Bits)),o.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),s.drawArrays(s.TRIANGLES,0,o.numIndices16Bits)),o.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),s.drawArrays(s.TRIANGLES,0,o.numIndices32Bits)),e.drawElements++}}},{key:"_allocate",value:function(){var e=this._scene,t=e.canvas.gl;if(this._program=new ft(t,this._buildShader()),this._program.errors)this.errors=this._program.errors;else{var n=this._program;this._uRenderPass=n.getLocation("renderPass"),this._uPositionsDecodeMatrix=n.getLocation("positionsDecodeMatrix"),this._uWorldMatrix=n.getLocation("worldMatrix"),this._uViewMatrix=n.getLocation("viewMatrix"),this._uProjMatrix=n.getLocation("projMatrix"),this._uSectionPlanes=[];for(var r=0,i=e._sectionPlanesState.sectionPlanes.length;r<i;r++)this._uSectionPlanes.push({active:n.getLocation("sectionPlaneActive"+r),pos:n.getLocation("sectionPlanePos"+r),dir:n.getLocation("sectionPlaneDir"+r)});e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=n.getLocation("logDepthBufFC")),this._uTexturePerObjectIdPositionsDecodeMatrix="uTexturePerObjectIdPositionsDecodeMatrix",this._uTexturePerObjectIdColorsAndFlags="uTexturePerObjectIdColorsAndFlags",this._uTexturePerVertexIdCoordinates="uTexturePerVertexIdCoordinates",this._uTexturePerPolygonIdNormals="uTexturePerPolygonIdNormals",this._uTexturePerPolygonIdIndices="uTexturePerPolygonIdIndices",this._uTexturePerPolygonIdPortionIds="uTexturePerPolygonIdPortionIds",this._uTextureCameraMatrices="uTextureCameraMatrices",this._uTextureModelMatrices="uTextureModelMatrices",this._uTexturePerObjectIdOffsets="uTexturePerObjectIdOffsets",this._uCameraEyeRtc=n.getLocation("uCameraEyeRtc")}}},{key:"_bindProgram",value:function(e){var t=this._scene,n=t.canvas.gl,r=this._program,i=t.camera.project;if(r.bind(),n.uniformMatrix4fv(this._uProjMatrix,!1,i.matrix),t.logarithmicDepthBufferEnabled){var a=2/(Math.log(i.far+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,a)}}},{key:"_buildShader",value:function(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState;e._lightsState;var n=t.sectionPlanes.length>0,r=[];return r.push("#version 300 es"),r.push("// Triangles dataTexture draw vertex shader"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("precision highp usampler2D;"),r.push("precision highp isampler2D;"),r.push("precision highp sampler2D;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("precision mediump usampler2D;"),r.push("precision mediump isampler2D;"),r.push("precision mediump sampler2D;"),r.push("#endif"),r.push("uniform int renderPass;"),e.entityOffsetsEnabled&&r.push("in vec3 offset;"),r.push("uniform highp sampler2D uTexturePerObjectIdPositionsDecodeMatrix;"),r.push("uniform lowp usampler2D uTexturePerObjectIdColorsAndFlags;"),r.push("uniform highp sampler2D uTexturePerObjectIdOffsets;"),r.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),r.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),r.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),r.push("uniform highp sampler2D uTextureCameraMatrices;"),r.push("uniform highp sampler2D uTextureModelMatrices;"),r.push("uniform vec3 uCameraEyeRtc;"),r.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(r.push("uniform float logDepthBufFC;"),r.push("out float vFragDepth;"),r.push("out float isPerspective;")),r.push("bool isPerspectiveMatrix(mat4 m) {"),r.push(" return (m[2][3] == - 1.0);"),r.push("}"),r.push("out highp vec2 vHighPrecisionZW;"),n&&(r.push("out vec4 vWorldPosition;"),r.push("flat out uint vFlags2;")),r.push("void main(void) {"),r.push("int polygonIndex = gl_VertexID / 3;"),r.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),r.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),r.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),r.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),r.push("uvec4 flags = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),r.push("uvec4 flags2 = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),r.push("if (int(flags.x) != renderPass) {"),r.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),r.push(" return;"),r.push("} else {"),r.push("mat4 viewMatrix = mat4 (texelFetch (uTextureCameraMatrices, ivec2(0, 0), 0), texelFetch (uTextureCameraMatrices, ivec2(1, 0), 0), texelFetch (uTextureCameraMatrices, ivec2(2, 0), 0), texelFetch (uTextureCameraMatrices, ivec2(3, 0), 0));"),r.push("mat4 viewNormalMatrix = mat4 (texelFetch (uTextureCameraMatrices, ivec2(0, 1), 0), texelFetch (uTextureCameraMatrices, ivec2(1, 1), 0), texelFetch (uTextureCameraMatrices, ivec2(2, 1), 0), texelFetch (uTextureCameraMatrices, ivec2(3, 1), 0));"),r.push("mat4 projMatrix = mat4 (texelFetch (uTextureCameraMatrices, ivec2(0, 2), 0), texelFetch (uTextureCameraMatrices, ivec2(1, 2), 0), texelFetch (uTextureCameraMatrices, ivec2(2, 2), 0), texelFetch (uTextureCameraMatrices, ivec2(3, 2), 0));"),r.push("mat4 worldMatrix = mat4 (texelFetch (uTextureModelMatrices, ivec2(0, 0), 0), texelFetch (uTextureModelMatrices, ivec2(1, 0), 0), texelFetch (uTextureModelMatrices, ivec2(2, 0), 0), texelFetch (uTextureModelMatrices, ivec2(3, 0), 0));"),r.push("mat4 worldNormalMatrix = mat4 (texelFetch (uTextureModelMatrices, ivec2(0, 1), 0), texelFetch (uTextureModelMatrices, ivec2(1, 1), 0), texelFetch (uTextureModelMatrices, ivec2(2, 1), 0), texelFetch (uTextureModelMatrices, ivec2(3, 1), 0));"),r.push("ivec4 packedVertexBase = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),r.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),r.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),r.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),r.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),r.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),r.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),r.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),r.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),r.push("mat4 positionsDecodeMatrix = mat4 (texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),r.push("uint solid = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),r.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),r.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),r.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),r.push("uvec4 color = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),r.push("if (color.a == 0u) {"),r.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),r.push(" return;"),r.push("};"),r.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),r.push("vec3 position;"),r.push("position = positions[gl_VertexID % 3];"),r.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*positionsDecodeMatrix)) * vec4(normal,1)).xyz);"),r.push("if (solid != 1u) {"),r.push("if (isPerspectiveMatrix(projMatrix)) {"),r.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(worldMatrix * positionsDecodeMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),r.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),r.push("position = positions[2 - (gl_VertexID % 3)];"),r.push("viewNormal = -viewNormal;"),r.push("}"),r.push("} else {"),r.push("if (viewNormal.z < 0.0) {"),r.push("position = positions[2 - (gl_VertexID % 3)];"),r.push("viewNormal = -viewNormal;"),r.push("}"),r.push("}"),r.push("}"),r.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),r.push("vec4 offset = vec4(texelFetch (uTexturePerObjectIdOffsets, objectIndexCoords, 0).rgb, 0.0);"),r.push("worldPosition.xyz = worldPosition.xyz + offset.xyz;"),r.push("vec4 viewPosition = viewMatrix * worldPosition; "),r.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(r.push("vFragDepth = 1.0 + clipPos.w;"),r.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),n&&(r.push("vWorldPosition = worldPosition;"),r.push("vFlags2 = flags2.r;")),r.push("gl_Position = clipPos;"),r.push("vHighPrecisionZW = gl_Position.zw;"),r.push("}"),r.push("}"),r}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,n=t.sectionPlanes.length>0,r=[];if(r.push("#version 300 es"),r.push("// Triangles dataTexture draw fragment shader"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),r.push("in highp vec2 vHighPrecisionZW;"),r.push("out vec4 outColor;"),e.logarithmicDepthBufferEnabled&&(r.push("in float isPerspective;"),r.push("uniform float logDepthBufFC;"),r.push("in float vFragDepth;")),n){r.push("in vec4 vWorldPosition;"),r.push("flat in uint vFlags2;");for(var i=0,a=t.sectionPlanes.length;i<a;i++)r.push("uniform bool sectionPlaneActive"+i+";"),r.push("uniform vec3 sectionPlanePos"+i+";"),r.push("uniform vec3 sectionPlaneDir"+i+";")}if(r.push("void main(void) {"),n){r.push(" bool clippable = vFlags2 > 0u;"),r.push(" if (clippable) {"),r.push(" float dist = 0.0;");for(var s=0,o=t.sectionPlanes.length;s<o;s++)r.push("if (sectionPlaneActive"+s+") {"),r.push(" dist += clamp(dot(-sectionPlaneDir"+s+".xyz, vWorldPosition.xyz - sectionPlanePos"+s+".xyz), 0.0, 1000.0);"),r.push("}");r.push(" if (dist > 0.0) { "),r.push(" discard;"),r.push(" }"),r.push("}")}return e.logarithmicDepthBufferEnabled&&r.push(" gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),r.push("float fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;"),r.push(" outColor = vec4(vec3(1.0 - fragCoordZ), 1.0); "),r.push("}"),r}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),e}(),xc=Z.vec3(),Mc=function(){function e(t){b(this,e),this._scene=t,this._hash=this._getHash(),this._allocate()}return P(e,[{key:"getValid",value:function(){return this._hash===this._getHash()}},{key:"_getHash",value:function(){return this._scene._sectionPlanesState.getHash()}},{key:"drawLayer",value:function(e,t,n){var r=t.model,i=r.scene,a=i.camera,s=i.canvas.gl,o=t._state,l=t._state.origin;if(this._program||(this._allocate(t),!this.errors)){e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(t)),s.uniform1i(this._uRenderPass,n),s.uniformMatrix4fv(this._uViewMatrix,!1,l?Ie(a.viewMatrix,l):a.viewMatrix),s.uniformMatrix4fv(this._uViewNormalMatrix,!1,a.viewNormalMatrix),s.uniformMatrix4fv(this._uWorldMatrix,!1,r.worldMatrix),s.uniformMatrix4fv(this._uWorldNormalMatrix,!1,r.worldNormalMatrix);var u=i._sectionPlanesState.sectionPlanes.length;if(u>0)for(var c=i._sectionPlanesState.sectionPlanes,f=t.layerIndex*u,p=r.renderFlags,A=0;A<u;A++){var d=this._uSectionPlanes[A];if(d){var v=p.sectionPlanesActivePerLayer[f+A];if(s.uniform1i(d.active,v?1:0),v){var h=c[A];if(l){var I=ge(h.dist,h.dir,l,xc);s.uniform3fv(d.pos,I)}else s.uniform3fv(d.pos,h.pos);s.uniform3fv(d.dir,h.dir)}}}s.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,t._state.positionsDecodeMatrix),this._aPosition.bindArrayBuffer(o.positionsBuf),this._aOffset.bindArrayBuffer(o.offsetsBuf),this._aNormal.bindArrayBuffer(o.normalsBuf),this._aColor.bindArrayBuffer(o.colorsBuf),this._aFlags.bindArrayBuffer(o.flagsBuf),this._aFlags2&&this._aFlags2.bindArrayBuffer(o.flags2Buf),o.indicesBuf.bind(),s.drawElements(s.TRIANGLES,o.indicesBuf.numItems,o.indicesBuf.itemType,0)}}},{key:"_allocate",value:function(){var e=this._scene,t=e.canvas.gl;if(this._program=new ft(t,this._buildShader()),this._program.errors)this.errors=this._program.errors;else{var n=this._program;this._uRenderPass=n.getLocation("renderPass"),this._uPositionsDecodeMatrix=n.getLocation("positionsDecodeMatrix"),this._uWorldMatrix=n.getLocation("worldMatrix"),this._uWorldNormalMatrix=n.getLocation("worldNormalMatrix"),this._uViewMatrix=n.getLocation("viewMatrix"),this._uViewNormalMatrix=n.getLocation("viewNormalMatrix"),this._uProjMatrix=n.getLocation("projMatrix"),this._uSectionPlanes=[];for(var r=0,i=e._sectionPlanesState.sectionPlanes.length;r<i;r++)this._uSectionPlanes.push({active:n.getLocation("sectionPlaneActive"+r),pos:n.getLocation("sectionPlanePos"+r),dir:n.getLocation("sectionPlaneDir"+r)});this._aPosition=n.getAttribute("position"),this._aOffset=n.getAttribute("offset"),this._aNormal=n.getAttribute("normal"),this._aColor=n.getAttribute("color"),this._aFlags=n.getAttribute("flags"),this._aFlags2&&(this._aFlags2=n.getAttribute("flags2")),e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=n.getLocation("logDepthBufFC"))}}},{key:"_bindProgram",value:function(){var e=this._scene,t=e.canvas.gl,n=e.camera.project;if(this._program.bind(),t.uniformMatrix4fv(this._uProjMatrix,!1,n.matrix),e.logarithmicDepthBufferEnabled){var r=2/(Math.log(n.far+1)/Math.LN2);t.uniform1f(this._uLogDepthBufFC,r)}}},{key:"_buildShader",value:function(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,n=[];return n.push("// Batched geometry normals vertex shader"),e.logarithmicDepthBufferEnabled&&Ze.SUPPORTED_EXTENSIONS.EXT_frag_depth&&n.push("#extension GL_EXT_frag_depth : enable"),n.push("uniform int renderPass;"),n.push("attribute vec3 position;"),e.entityOffsetsEnabled&&n.push("attribute vec3 offset;"),n.push("attribute vec3 normal;"),n.push("attribute vec4 color;"),n.push("attribute vec4 flags;"),n.push("attribute vec4 flags2;"),n.push("uniform mat4 worldMatrix;"),n.push("uniform mat4 worldNormalMatrix;"),n.push("uniform mat4 viewMatrix;"),n.push("uniform mat4 projMatrix;"),n.push("uniform mat4 viewNormalMatrix;"),n.push("uniform mat4 positionsDecodeMatrix;"),e.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),Ze.SUPPORTED_EXTENSIONS.EXT_frag_depth&&n.push("varying float vFragDepth;"),n.push("bool isPerspectiveMatrix(mat4 m) {"),n.push(" return (m[2][3] == - 1.0);"),n.push("}"),n.push("varying float isPerspective;")),n.push("vec3 octDecode(vec2 oct) {"),n.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),n.push(" if (v.z < 0.0) {"),n.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),n.push(" }"),n.push(" return normalize(v);"),n.push("}"),t&&(n.push("varying vec4 vWorldPosition;"),n.push("varying vec4 vFlags2;")),n.push("varying vec3 vViewNormal;"),n.push("void main(void) {"),n.push("if (int(flags.x) != renderPass) {"),n.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),n.push(" } else {"),n.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&n.push(" worldPosition.xyz = worldPosition.xyz + offset;"),n.push(" vec4 viewPosition = viewMatrix * worldPosition; "),n.push(" vec4 worldNormal = worldNormalMatrix * vec4(octDecode(normal.xy), 0.0); "),n.push(" vec3 viewNormal = normalize((viewNormalMatrix * worldNormal).xyz);"),t&&(n.push(" vWorldPosition = worldPosition;"),n.push(" vFlags2 = flags2;")),n.push(" vViewNormal = viewNormal;"),n.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(Ze.SUPPORTED_EXTENSIONS.EXT_frag_depth?n.push("vFragDepth = 1.0 + clipPos.w;"):(n.push("clipPos.z = log2( max( 1e-6, clipPos.w + 1.0 ) ) * logDepthBufFC - 1.0;"),n.push("clipPos.z *= clipPos.w;")),n.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),n.push("gl_Position = clipPos;"),n.push(" }"),n.push("}"),n}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,n=t.sectionPlanes.length>0,r=[];if(r.push("// Batched geometry normals fragment shader"),e.logarithmicDepthBufferEnabled&&Ze.SUPPORTED_EXTENSIONS.EXT_frag_depth&&r.push("#extension GL_EXT_frag_depth : enable"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),e.logarithmicDepthBufferEnabled&&Ze.SUPPORTED_EXTENSIONS.EXT_frag_depth&&(r.push("varying float isPerspective;"),r.push("uniform float logDepthBufFC;"),r.push("varying float vFragDepth;")),n){r.push("varying vec4 vWorldPosition;"),r.push("varying vec4 vFlags2;");for(var i=0;i<t.sectionPlanes.length;i++)r.push("uniform bool sectionPlaneActive"+i+";"),r.push("uniform vec3 sectionPlanePos"+i+";"),r.push("uniform vec3 sectionPlaneDir"+i+";")}if(r.push("varying vec3 vViewNormal;"),r.push("vec3 packNormalToRGB( const in vec3 normal ) {"),r.push(" return normalize( normal ) * 0.5 + 0.5;"),r.push("}"),r.push("void main(void) {"),n){r.push(" bool clippable = (float(vFlags2.x) > 0.0);"),r.push(" if (clippable) {"),r.push(" float dist = 0.0;");for(var a=0;a<t.sectionPlanes.length;a++)r.push(" if (sectionPlaneActive"+a+") {"),r.push(" dist += clamp(dot(-sectionPlaneDir"+a+".xyz, vWorldPosition.xyz - sectionPlanePos"+a+".xyz), 0.0, 1000.0);"),r.push(" }");r.push(" if (dist > 0.0) { discard; }"),r.push(" }")}return e.logarithmicDepthBufferEnabled&&Ze.SUPPORTED_EXTENSIONS.EXT_frag_depth&&r.push(" gl_FragDepthEXT = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),r.push(" gl_FragColor = vec4(packNormalToRGB(vViewNormal), 1.0); "),r.push("}"),r}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),e}();Z.vec3();var Fc=function(){function e(t){b(this,e),this._scene=t,this._hash=this._getHash(),this._allocate()}return P(e,[{key:"getValid",value:function(){return this._hash===this._getHash()}},{key:"_getHash",value:function(){return this._scene._sectionPlanesState.getHash()}},{key:"drawLayer",value:function(e,t){}},{key:"_allocate",value:function(){var e=this._scene,t=e.canvas.gl,n=e._sectionPlanesState;if(this._program=new ft(t,this._buildShader()),this._program.errors)this.errors=this._program.errors;else{var r=this._program;this._uPositionsDecodeMatrix=r.getLocation("positionsDecodeMatrix"),this._uShadowViewMatrix=r.getLocation("shadowViewMatrix"),this._uShadowProjMatrix=r.getLocation("shadowProjMatrix"),e.logarithmicDepthBufferEnabled&&(this._uZFar=r.getLocation("zFar")),this._uSectionPlanes=[];for(var i=0,a=n.sectionPlanes.length;i<a;i++)this._uSectionPlanes.push({active:r.getLocation("sectionPlaneActive"+i),pos:r.getLocation("sectionPlanePos"+i),dir:r.getLocation("sectionPlaneDir"+i)});this._aPosition=r.getAttribute("position"),this._aOffset=r.getAttribute("offset"),this._aColor=r.getAttribute("color"),this._aFlags=r.getAttribute("flags"),this._aFlags2=r.getAttribute("flags2")}}},{key:"_bindProgram",value:function(e){var t=this._scene.canvas.gl;this._program.bind(),t.uniformMatrix4fv(this._uShadowViewMatrix,!1,e.shadowViewMatrix),t.uniformMatrix4fv(this._uShadowProjMatrix,!1,e.shadowProjMatrix),this._lastLightId=null}},{key:"_buildShader",value:function(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,n=[];return n.push("// Batched geometry shadow vertex shader"),n.push("attribute vec3 position;"),e.entityOffsetsEnabled&&n.push("attribute vec3 offset;"),n.push("attribute vec4 color;"),n.push("attribute vec4 flags;"),n.push("attribute vec4 flags2;"),n.push("uniform mat4 shadowViewMatrix;"),n.push("uniform mat4 shadowProjMatrix;"),n.push("uniform mat4 positionsDecodeMatrix;"),t&&(n.push("varying vec4 vWorldPosition;"),n.push("varying vec4 vFlags2;")),n.push("varying vec4 vViewPosition;"),n.push("void main(void) {"),n.push(" bool visible = (float(flags.x) > 0.0);"),n.push(" bool transparent = ((float(color.a) / 255.0) < 1.0);"),n.push(" if (!visible || transparent) {"),n.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),n.push(" } else {"),n.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),e.entityOffsetsEnabled&&n.push(" worldPosition.xyz = worldPosition.xyz + offset;"),n.push(" vec4 viewPosition = shadowViewMatrix * worldPosition; "),t&&(n.push(" vWorldPosition = worldPosition;"),n.push(" vFlags2 = flags2;")),n.push(" vViewPosition = viewPosition;"),n.push(" gl_Position = shadowProjMatrix * viewPosition;"),n.push(" }"),n.push("}"),n}},{key:"_buildFragmentShader",value:function(){var e=this._scene._sectionPlanesState,t=e.sectionPlanes.length>0,n=[];if(n.push("// Batched geometry shadow fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),t){n.push("varying vec4 vWorldPosition;"),n.push("varying vec4 vFlags2;");for(var r=0;r<e.sectionPlanes.length;r++)n.push("uniform bool sectionPlaneActive"+r+";"),n.push("uniform vec3 sectionPlanePos"+r+";"),n.push("uniform vec3 sectionPlaneDir"+r+";")}if(n.push("varying vec4 vViewPosition;"),n.push("vec4 encodeFloat( const in float v ) {"),n.push(" const vec4 bitShift = vec4(256 * 256 * 256, 256 * 256, 256, 1.0);"),n.push(" const vec4 bitMask = vec4(0, 1.0 / 256.0, 1.0 / 256.0, 1.0 / 256.0);"),n.push(" vec4 comp = fract(v * bitShift);"),n.push(" comp -= comp.xxyz * bitMask;"),n.push(" return comp;"),n.push("}"),n.push("void main(void) {"),t){n.push(" bool clippable = (float(vFlags2.x) > 0.0);"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(var i=0;i<e.sectionPlanes.length;i++)n.push(" if (sectionPlaneActive"+i+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+i+".xyz, vWorldPosition.xyz - sectionPlanePos"+i+".xyz), 0.0, 1000.0);"),n.push(" }");n.push(" if (dist > 0.0) { discard; }"),n.push(" }")}return n.push(" gl_FragColor = encodeFloat( gl_FragCoord.z); "),n.push("}"),n}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),e}(),Hc=Z.vec4(),Uc=Z.vec3(),Gc={linear:"linearToLinear",sRGB:"sRGBToLinear",gamma:"gammaToLinear"},kc=function(){function e(t,n){b(this,e),this._scene=t,this._withSAO=n,this._hash=this._getHash(),this._allocate()}return P(e,[{key:"getValid",value:function(){return this._hash===this._getHash()}},{key:"_getHash",value:function(){var e=this._scene;return[e.gammaOutput,e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}},{key:"drawLayer",value:function(e,t,n){var r=this._scene,i=r.camera,a=t.model,s=r.canvas.gl,o=t._state,l=t._state.origin;if(this._program||(this._allocate(),!this.errors)){e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),s.uniform1i(this._uRenderPass,n),s.uniformMatrix4fv(this._uViewMatrix,!1,l?Ie(i.viewMatrix,l):i.viewMatrix),s.uniformMatrix4fv(this._uViewNormalMatrix,!1,i.viewNormalMatrix),s.uniformMatrix4fv(this._uWorldMatrix,!1,a.worldMatrix),s.uniformMatrix4fv(this._uWorldNormalMatrix,!1,a.worldNormalMatrix);var u=r._sectionPlanesState.sectionPlanes.length;if(u>0)for(var c=r._sectionPlanesState.sectionPlanes,f=t.layerIndex*u,p=a.renderFlags,A=0;A<u;A++){var d=this._uSectionPlanes[A];if(d){var v=p.sectionPlanesActivePerLayer[f+A];if(s.uniform1i(d.active,v?1:0),v){var h=c[A];if(l){var I=ge(h.dist,h.dir,l,Uc);s.uniform3fv(d.pos,I)}else s.uniform3fv(d.pos,h.pos);s.uniform3fv(d.dir,h.dir)}}}s.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,t._state.positionsDecodeMatrix),this._aPosition.bindArrayBuffer(o.positionsBuf),this._aNormal&&this._aNormal.bindArrayBuffer(o.normalsBuf),this._aColor&&this._aColor.bindArrayBuffer(o.colorsBuf),this._aMetallicRoughness&&this._aMetallicRoughness.bindArrayBuffer(o.metallicRoughnessBuf),this._aFlags&&this._aFlags.bindArrayBuffer(o.flagsBuf),this._aFlags2&&this._aFlags2.bindArrayBuffer(o.flags2Buf),this._aOffset&&this._aOffset.bindArrayBuffer(o.offsetsBuf),o.indicesBuf.bind(),s.drawElements(s.TRIANGLES,o.indicesBuf.numItems,o.indicesBuf.itemType,0),e.drawElements++}}},{key:"_allocate",value:function(){var e=this._scene,t=e.canvas.gl,n=e._lightsState;if(this._program=new ft(t,this._buildShader()),this._program.errors)this.errors=this._program.errors;else{var r=this._program;this._uRenderPass=r.getLocation("renderPass"),this._uPositionsDecodeMatrix=r.getLocation("positionsDecodeMatrix"),this._uWorldMatrix=r.getLocation("worldMatrix"),this._uWorldNormalMatrix=r.getLocation("worldNormalMatrix"),this._uViewMatrix=r.getLocation("viewMatrix"),this._uViewNormalMatrix=r.getLocation("viewNormalMatrix"),this._uProjMatrix=r.getLocation("projMatrix"),this._uGammaFactor=r.getLocation("gammaFactor"),this._uLightAmbient=r.getLocation("lightAmbient"),this._uLightColor=[],this._uLightDir=[],this._uLightPos=[],this._uLightAttenuation=[];for(var i=n.lights,a=0,s=i.length;a<s;a++)switch(i[a].type){case"dir":this._uLightColor[a]=r.getLocation("lightColor"+a),this._uLightPos[a]=null,this._uLightDir[a]=r.getLocation("lightDir"+a);break;case"point":this._uLightColor[a]=r.getLocation("lightColor"+a),this._uLightPos[a]=r.getLocation("lightPos"+a),this._uLightDir[a]=null,this._uLightAttenuation[a]=r.getLocation("lightAttenuation"+a);break;case"spot":this._uLightColor[a]=r.getLocation("lightColor"+a),this._uLightPos[a]=r.getLocation("lightPos"+a),this._uLightDir[a]=r.getLocation("lightDir"+a),this._uLightAttenuation[a]=r.getLocation("lightAttenuation"+a)}n.reflectionMaps.length>0&&(this._uReflectionMap="reflectionMap"),n.lightMaps.length>0&&(this._uLightMap="lightMap"),this._uSectionPlanes=[];for(var o=0,l=e._sectionPlanesState.sectionPlanes.length;o<l;o++)this._uSectionPlanes.push({active:r.getLocation("sectionPlaneActive"+o),pos:r.getLocation("sectionPlanePos"+o),dir:r.getLocation("sectionPlaneDir"+o)});this._aPosition=r.getAttribute("position"),this._aOffset=r.getAttribute("offset"),this._aNormal=r.getAttribute("normal"),this._aColor=r.getAttribute("color"),this._aMetallicRoughness=r.getAttribute("metallicRoughness"),this._aFlags=r.getAttribute("flags"),this._aFlags2=r.getAttribute("flags2"),this._withSAO&&(this._uOcclusionTexture="uOcclusionTexture",this._uSAOParams=r.getLocation("uSAOParams")),e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=r.getLocation("logDepthBufFC"))}}},{key:"_bindProgram",value:function(e){var t=Ze.MAX_TEXTURE_UNITS,n=this._scene,r=n.canvas.gl,i=this._program,a=n._lightsState,s=a.lights,o=n.camera.project;i.bind(),r.uniformMatrix4fv(this._uProjMatrix,!1,o.matrix),this._uLightAmbient&&r.uniform4fv(this._uLightAmbient,n._lightsState.getAmbientColorAndIntensity());for(var l=0,u=s.length;l<u;l++){var c=s[l];this._uLightColor[l]&&r.uniform4f(this._uLightColor[l],c.color[0],c.color[1],c.color[2],c.intensity),this._uLightPos[l]&&(r.uniform3fv(this._uLightPos[l],c.pos),this._uLightAttenuation[l]&&r.uniform1f(this._uLightAttenuation[l],c.attenuation)),this._uLightDir[l]&&r.uniform3fv(this._uLightDir[l],c.dir)}if(a.reflectionMaps.length>0&&a.reflectionMaps[0].texture&&this._uReflectionMap&&(i.bindTexture(this._uReflectionMap,a.reflectionMaps[0].texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%t,e.bindTexture++),a.lightMaps.length>0&&a.lightMaps[0].texture&&this._uLightMap&&(i.bindTexture(this._uLightMap,a.lightMaps[0].texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%t,e.bindTexture++),this._withSAO){var f=n.sao;if(f.possible){var p=r.drawingBufferWidth,A=r.drawingBufferHeight;Hc[0]=p,Hc[1]=A,Hc[2]=f.blendCutoff,Hc[3]=f.blendFactor,r.uniform4fv(this._uSAOParams,Hc),this._program.bindTexture(this._uOcclusionTexture,e.occlusionTexture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%t,e.bindTexture++}}if(n.logarithmicDepthBufferEnabled){var d=2/(Math.log(o.far+1)/Math.LN2);r.uniform1f(this._uLogDepthBufFC,d)}this._uGammaFactor&&r.uniform1f(this._uGammaFactor,n.gammaFactor)}},{key:"_buildShader",value:function(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState,n=e._lightsState,r=t.sectionPlanes.length>0,i=t.clippingCaps,a=[];return a.push("// Triangles dataTexture quality draw vertex shader"),e.logarithmicDepthBufferEnabled&&Ze.SUPPORTED_EXTENSIONS.EXT_frag_depth&&a.push("#extension GL_EXT_frag_depth : enable"),a.push("uniform int renderPass;"),a.push("attribute vec3 position;"),a.push("attribute vec3 normal;"),a.push("attribute vec4 color;"),a.push("attribute vec2 metallicRoughness;"),a.push("attribute vec4 flags;"),a.push("attribute vec4 flags2;"),e.entityOffsetsEnabled&&a.push("attribute vec3 offset;"),a.push("uniform mat4 worldMatrix;"),a.push("uniform mat4 worldNormalMatrix;"),a.push("uniform mat4 viewMatrix;"),a.push("uniform mat4 projMatrix;"),a.push("uniform mat4 viewNormalMatrix;"),a.push("uniform mat4 positionsDecodeMatrix;"),e.logarithmicDepthBufferEnabled&&(a.push("uniform float logDepthBufFC;"),Ze.SUPPORTED_EXTENSIONS.EXT_frag_depth&&a.push("varying float vFragDepth;"),a.push("bool isPerspectiveMatrix(mat4 m) {"),a.push(" return (m[2][3] == - 1.0);"),a.push("}"),a.push("varying float isPerspective;")),a.push("vec3 octDecode(vec2 oct) {"),a.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),a.push(" if (v.z < 0.0) {"),a.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),a.push(" }"),a.push(" return normalize(v);"),a.push("}"),a.push("varying vec4 vViewPosition;"),a.push("varying vec3 vViewNormal;"),a.push("varying vec4 vColor;"),a.push("varying vec2 vMetallicRoughness;"),n.lightMaps.length>0&&a.push("varying vec3 vWorldNormal;"),r&&(a.push("varying vec4 vWorldPosition;"),a.push("varying vec4 vFlags2;"),i&&a.push("varying vec4 vClipPosition;")),a.push("void main(void) {"),a.push("if (int(flags.x) != renderPass) {"),a.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),a.push("} else {"),a.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&a.push("worldPosition.xyz = worldPosition.xyz + offset;"),a.push("vec4 viewPosition = viewMatrix * worldPosition; "),a.push("vec4 worldNormal = worldNormalMatrix * vec4(octDecode(normal.xy), 0.0); "),a.push("vec3 viewNormal = normalize((viewNormalMatrix * worldNormal).xyz);"),a.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(a.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),Ze.SUPPORTED_EXTENSIONS.EXT_frag_depth?a.push("vFragDepth = 1.0 + clipPos.w;"):(a.push("clipPos.z = log2( max( 1e-6, clipPos.w + 1.0 ) ) * logDepthBufFC - 1.0;"),a.push("clipPos.z *= clipPos.w;"))),r&&(a.push("vWorldPosition = worldPosition;"),a.push("vFlags2 = flags2;"),i&&a.push("vClipPosition = clipPos;")),a.push("vViewPosition = viewPosition;"),a.push("vViewNormal = viewNormal;"),a.push("vColor = color;"),a.push("vMetallicRoughness = metallicRoughness;"),n.lightMaps.length>0&&a.push("vWorldNormal = worldNormal.xyz;"),a.push("gl_Position = clipPos;"),a.push("}"),a.push("}"),a}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e.gammaOutput,n=e._sectionPlanesState,r=e._lightsState,i=n.sectionPlanes.length>0,a=n.clippingCaps,s=[];s.push("// Triangles dataTexture quality draw fragment shader"),e.logarithmicDepthBufferEnabled&&Ze.SUPPORTED_EXTENSIONS.EXT_frag_depth&&s.push("#extension GL_EXT_frag_depth : enable"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&Ze.SUPPORTED_EXTENSIONS.EXT_frag_depth&&(s.push("varying float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("varying float vFragDepth;")),s.push("varying vec4 vViewPosition;"),s.push("varying vec3 vViewNormal;"),s.push("varying vec4 vColor;"),s.push("varying vec2 vMetallicRoughness;"),r.lightMaps.length>0&&s.push("varying vec3 vWorldNormal;"),s.push("uniform mat4 viewMatrix;"),r.reflectionMaps.length>0&&s.push("uniform samplerCube reflectionMap;"),r.lightMaps.length>0&&s.push("uniform samplerCube lightMap;"),s.push("uniform vec4 lightAmbient;");for(var o=0,l=r.lights.length;o<l;o++){var u=r.lights[o];"ambient"!==u.type&&(s.push("uniform vec4 lightColor"+o+";"),"dir"===u.type&&s.push("uniform vec3 lightDir"+o+";"),"point"===u.type&&s.push("uniform vec3 lightPos"+o+";"),"spot"===u.type&&(s.push("uniform vec3 lightPos"+o+";"),s.push("uniform vec3 lightDir"+o+";")))}if(this._withSAO&&(s.push("uniform sampler2D uOcclusionTexture;"),s.push("uniform vec4 uSAOParams;"),s.push("const float packUpscale = 256. / 255.;"),s.push("const float unpackDownScale = 255. / 256.;"),s.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),s.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),s.push("float unpackRGBAToDepth( const in vec4 v ) {"),s.push(" return dot( v, unPackFactors );"),s.push("}")),s.push("uniform float gammaFactor;"),s.push("vec4 linearToLinear( in vec4 value ) {"),s.push(" return value;"),s.push("}"),s.push("vec4 sRGBToLinear( in vec4 value ) {"),s.push(" return vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.w );"),s.push("}"),s.push("vec4 gammaToLinear( in vec4 value) {"),s.push(" return vec4( pow( value.xyz, vec3( gammaFactor ) ), value.w );"),s.push("}"),t&&(s.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),s.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),s.push("}")),i){s.push("varying vec4 vWorldPosition;"),s.push("varying vec4 vFlags2;"),a&&s.push("varying vec4 vClipPosition;");for(var c=0,f=n.sectionPlanes.length;c<f;c++)s.push("uniform bool sectionPlaneActive"+c+";"),s.push("uniform vec3 sectionPlanePos"+c+";"),s.push("uniform vec3 sectionPlaneDir"+c+";")}if(s.push("#define PI 3.14159265359"),s.push("#define RECIPROCAL_PI 0.31830988618"),s.push("#define RECIPROCAL_PI2 0.15915494"),s.push("#define EPSILON 1e-6"),s.push("#define saturate(a) clamp( a, 0.0, 1.0 )"),s.push("vec3 inverseTransformDirection(in vec3 dir, in mat4 matrix) {"),s.push(" return normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );"),s.push("}"),s.push("struct IncidentLight {"),s.push(" vec3 color;"),s.push(" vec3 direction;"),s.push("};"),s.push("struct ReflectedLight {"),s.push(" vec3 diffuse;"),s.push(" vec3 specular;"),s.push("};"),s.push("struct Geometry {"),s.push(" vec3 position;"),s.push(" vec3 viewNormal;"),s.push(" vec3 worldNormal;"),s.push(" vec3 viewEyeDir;"),s.push("};"),s.push("struct Material {"),s.push(" vec3 diffuseColor;"),s.push(" float specularRoughness;"),s.push(" vec3 specularColor;"),s.push(" float shine;"),s.push("};"),s.push("float GGXRoughnessToBlinnExponent(const in float ggxRoughness) {"),s.push(" float r = ggxRoughness + 0.0001;"),s.push(" return (2.0 / (r * r) - 2.0);"),s.push("}"),s.push("float getSpecularMIPLevel(const in float blinnShininessExponent, const in int maxMIPLevel) {"),s.push(" float maxMIPLevelScalar = float( maxMIPLevel );"),s.push(" float desiredMIPLevel = maxMIPLevelScalar - 0.79248 - 0.5 * log2( ( blinnShininessExponent * blinnShininessExponent ) + 1.0 );"),s.push(" return clamp( desiredMIPLevel, 0.0, maxMIPLevelScalar );"),s.push("}"),r.reflectionMaps.length>0&&(s.push("vec3 getLightProbeIndirectRadiance(const in vec3 reflectVec, const in float blinnShininessExponent, const in int maxMIPLevel) {"),s.push(" float mipLevel = 0.5 * getSpecularMIPLevel(blinnShininessExponent, maxMIPLevel);"),s.push(" vec3 envMapColor = "+Gc[r.reflectionMaps[0].encoding]+"(textureCube(reflectionMap, reflectVec, mipLevel)).rgb;"),s.push(" return envMapColor;"),s.push("}")),s.push("vec3 F_Schlick(const in vec3 specularColor, const in float dotLH) {"),s.push(" float fresnel = exp2( ( -5.55473 * dotLH - 6.98316 ) * dotLH );"),s.push(" return ( 1.0 - specularColor ) * fresnel + specularColor;"),s.push("}"),s.push("float G_GGX_Smith(const in float alpha, const in float dotNL, const in float dotNV) {"),s.push(" float a2 = ( alpha * alpha );"),s.push(" float gl = dotNL + sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),s.push(" float gv = dotNV + sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),s.push(" return 1.0 / ( gl * gv );"),s.push("}"),s.push("float G_GGX_SmithCorrelated(const in float alpha, const in float dotNL, const in float dotNV) {"),s.push(" float a2 = ( alpha * alpha );"),s.push(" float gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),s.push(" float gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),s.push(" return 0.5 / max( gv + gl, EPSILON );"),s.push("}"),s.push("float D_GGX(const in float alpha, const in float dotNH) {"),s.push(" float a2 = ( alpha * alpha );"),s.push(" float denom = ( dotNH * dotNH) * ( a2 - 1.0 ) + 1.0;"),s.push(" return RECIPROCAL_PI * a2 / ( denom * denom);"),s.push("}"),s.push("vec3 BRDF_Specular_GGX(const in IncidentLight incidentLight, const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),s.push(" float alpha = ( roughness * roughness );"),s.push(" vec3 halfDir = normalize( incidentLight.direction + geometry.viewEyeDir );"),s.push(" float dotNL = saturate( dot( geometry.viewNormal, incidentLight.direction ) );"),s.push(" float dotNV = saturate( dot( geometry.viewNormal, geometry.viewEyeDir ) );"),s.push(" float dotNH = saturate( dot( geometry.viewNormal, halfDir ) );"),s.push(" float dotLH = saturate( dot( incidentLight.direction, halfDir ) );"),s.push(" vec3 F = F_Schlick( specularColor, dotLH );"),s.push(" float G = G_GGX_SmithCorrelated( alpha, dotNL, dotNV );"),s.push(" float D = D_GGX( alpha, dotNH );"),s.push(" return F * (G * D);"),s.push("}"),s.push("vec3 BRDF_Specular_GGX_Environment(const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),s.push(" float dotNV = saturate(dot(geometry.viewNormal, geometry.viewEyeDir));"),s.push(" const vec4 c0 = vec4( -1, -0.0275, -0.572, 0.022);"),s.push(" const vec4 c1 = vec4( 1, 0.0425, 1.04, -0.04);"),s.push(" vec4 r = roughness * c0 + c1;"),s.push(" float a004 = min(r.x * r.x, exp2(-9.28 * dotNV)) * r.x + r.y;"),s.push(" vec2 AB = vec2(-1.04, 1.04) * a004 + r.zw;"),s.push(" return specularColor * AB.x + AB.y;"),s.push("}"),(r.lightMaps.length>0||r.reflectionMaps.length>0)&&(s.push("void computePBRLightMapping(const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),r.lightMaps.length>0&&(s.push(" vec3 irradiance = "+Gc[r.lightMaps[0].encoding]+"(textureCube(lightMap, geometry.worldNormal)).rgb;"),s.push(" irradiance *= PI;"),s.push(" vec3 diffuseBRDFContrib = (RECIPROCAL_PI * material.diffuseColor);"),s.push(" reflectedLight.diffuse += irradiance * diffuseBRDFContrib;")),r.reflectionMaps.length>0&&(s.push(" vec3 reflectVec = reflect(geometry.viewEyeDir, geometry.viewNormal);"),s.push(" reflectVec = inverseTransformDirection(reflectVec, viewMatrix);"),s.push(" float blinnExpFromRoughness = GGXRoughnessToBlinnExponent(material.specularRoughness);"),s.push(" vec3 radiance = getLightProbeIndirectRadiance(reflectVec, blinnExpFromRoughness, 8);"),s.push(" vec3 specularBRDFContrib = BRDF_Specular_GGX_Environment(geometry, material.specularColor, material.specularRoughness);"),s.push(" reflectedLight.specular += radiance * specularBRDFContrib;")),s.push("}")),s.push("void computePBRLighting(const in IncidentLight incidentLight, const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),s.push(" float dotNL = saturate(dot(geometry.viewNormal, incidentLight.direction));"),s.push(" vec3 irradiance = dotNL * incidentLight.color * PI;"),s.push(" reflectedLight.diffuse += irradiance * (RECIPROCAL_PI * material.diffuseColor);"),s.push(" reflectedLight.specular += irradiance * BRDF_Specular_GGX(incidentLight, geometry, material.specularColor, material.specularRoughness);"),s.push("}"),s.push("void main(void) {"),i){s.push(" bool clippable = (float(vFlags2.x) > 0.0);"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var p=0,A=n.sectionPlanes.length;p<A;p++)s.push("if (sectionPlaneActive"+p+") {"),s.push(" dist += clamp(dot(-sectionPlaneDir"+p+".xyz, vWorldPosition.xyz - sectionPlanePos"+p+".xyz), 0.0, 1000.0);"),s.push("}");a?(s.push(" if (dist > (0.002 * vClipPosition.w)) {"),s.push(" discard;"),s.push(" }"),s.push(" if (dist > 0.0) { "),s.push(" gl_FragColor=vec4(1.0, 0.0, 0.0, 1.0);"),e.logarithmicDepthBufferEnabled&&Ze.SUPPORTED_EXTENSIONS.EXT_frag_depth&&s.push(" gl_FragDepthEXT = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" return;"),s.push("}")):(s.push(" if (dist > 0.0) { "),s.push(" discard;"),s.push(" }")),s.push("}")}s.push("IncidentLight light;"),s.push("Material material;"),s.push("Geometry geometry;"),s.push("ReflectedLight reflectedLight = ReflectedLight(vec3(0.0,0.0,0.0), vec3(0.0,0.0,0.0));"),s.push("vec3 rgb = (vec3(float(vColor.r) / 255.0, float(vColor.g) / 255.0, float(vColor.b) / 255.0));"),s.push("float alpha = float(vColor.a) / 255.0;"),s.push("vec3 diffuseColor = rgb;"),s.push("float specularF0 = 1.0;"),s.push("float metallic = float(vMetallicRoughness.r) / 255.0;"),s.push("float roughness = float(vMetallicRoughness.g) / 255.0;"),s.push("float dielectricSpecular = 0.16 * specularF0 * specularF0;"),s.push("material.diffuseColor = diffuseColor * (1.0 - dielectricSpecular) * (1.0 - metallic);"),s.push("material.specularRoughness = clamp(roughness, 0.04, 1.0);"),s.push("material.specularColor = mix(vec3(dielectricSpecular), diffuseColor, metallic);"),s.push("geometry.position = vViewPosition.xyz;"),s.push("geometry.viewNormal = -normalize(vViewNormal);"),s.push("geometry.viewEyeDir = normalize(vViewPosition.xyz);"),r.lightMaps.length>0&&s.push("geometry.worldNormal = normalize(vWorldNormal);"),(r.lightMaps.length>0||r.reflectionMaps.length>0)&&s.push("computePBRLightMapping(geometry, material, reflectedLight);");for(var d=0,v=r.lights.length;d<v;d++){var h=r.lights[d];if("ambient"!==h.type){if("dir"===h.type)"view"===h.space?s.push("light.direction = normalize(lightDir"+d+");"):s.push("light.direction = normalize((viewMatrix * vec4(lightDir"+d+", 0.0)).xyz);");else if("point"===h.type)"view"===h.space?s.push("light.direction = normalize(lightPos"+d+" - vViewPosition.xyz);"):s.push("light.direction = normalize((viewMatrix * vec4(lightPos"+d+", 0.0)).xyz);");else{if("spot"!==h.type)continue;"view"===h.space?s.push("light.direction = normalize(lightDir"+d+");"):s.push("light.direction = normalize((viewMatrix * vec4(lightDir"+d+", 0.0)).xyz);")}s.push("light.color = lightColor"+d+".rgb * lightColor"+d+".a;"),s.push("computePBRLighting(light, geometry, material, reflectedLight);")}}return s.push("vec3 outgoingLight = (lightAmbient.rgb * lightAmbient.a * rgb) + (reflectedLight.diffuse) + (reflectedLight.specular);"),s.push("vec4 fragColor;"),this._withSAO?(s.push(" float viewportWidth = uSAOParams[0];"),s.push(" float viewportHeight = uSAOParams[1];"),s.push(" float blendCutoff = uSAOParams[2];"),s.push(" float blendFactor = uSAOParams[3];"),s.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),s.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBAToDepth(texture2D(uOcclusionTexture, uv))) * blendFactor;"),s.push(" fragColor = vec4(outgoingLight.rgb * ambient, alpha);")):s.push(" fragColor = vec4(outgoingLight.rgb, alpha);"),t&&s.push("fragColor = linearToGamma(fragColor, gammaFactor);"),s.push("gl_FragColor = fragColor;"),e.logarithmicDepthBufferEnabled&&Ze.SUPPORTED_EXTENSIONS.EXT_frag_depth&&s.push(" gl_FragDepthEXT = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("}"),s}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),e}(),Vc=Z.vec3(),jc=function(){function e(t){b(this,e),this._scene=t,this._hash=this._getHash(),this._allocate()}return P(e,[{key:"getValid",value:function(){return this._hash===this._getHash()}},{key:"_getHash",value:function(){return this._scene._sectionPlanesState.getHash()}},{key:"drawLayer",value:function(e,t,n){var r=t.model,i=r.scene,a=i.camera,s=i.canvas.gl,o=t._state,l=t._state.origin;this._program||this._allocate(t),e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram()),this._program.bindTexture(this._uTexturePerObjectIdPositionsDecodeMatrix,{bind:function(e){return s.activeTexture(s["TEXTURE"+e]),s.bindTexture(s.TEXTURE_2D,o.texturePerObjectIdPositionsDecodeMatrix),!0},unbind:function(e){s.activeTexture(s["TEXTURE"+e]),s.bindTexture(s.TEXTURE_2D,null)}},1),this._program.bindTexture(this._uTexturePerVertexIdCoordinates,{bind:function(e){return s.activeTexture(s["TEXTURE"+e]),s.bindTexture(s.TEXTURE_2D,o.texturePerVertexIdCoordinates),!0},unbind:function(e){s.activeTexture(s["TEXTURE"+e]),s.bindTexture(s.TEXTURE_2D,null)}},2),this._program.bindTexture(this._uTexturePerObjectIdColorsAndFlags,{bind:function(e){return s.activeTexture(s["TEXTURE"+e]),s.bindTexture(s.TEXTURE_2D,o.texturePerObjectIdColorsAndFlags),!0},unbind:function(e){s.activeTexture(s["TEXTURE"+e]),s.bindTexture(s.TEXTURE_2D,null)}},3),s.uniform1i(this._uRenderPass,n),s.uniform1i(this._uPickInvisible,e.pickInvisible),s.uniformMatrix4fv(this._uWorldMatrix,!1,r.worldMatrix);var u=e.pickViewMatrix||a.viewMatrix,c=l?Ie(u,l):u;if(s.uniformMatrix4fv(this._uViewMatrix,!1,c),s.uniformMatrix4fv(this._uProjMatrix,!1,e.pickProjMatrix),i.logarithmicDepthBufferEnabled){var f=2/(Math.log(a.project.far+1)/Math.LN2);s.uniform1f(this._uLogDepthBufFC,f)}var p=i._sectionPlanesState.sectionPlanes.length;if(p>0)for(var A=i._sectionPlanesState.sectionPlanes,d=t.layerIndex*p,v=r.renderFlags,h=0;h<p;h++){var I=this._uSectionPlanes[h],y=v.sectionPlanesActivePerLayer[d+h];if(s.uniform1i(I.active,y?1:0),y){var m=A[h];if(l){var w=ge(m.dist,m.dir,l,Vc);s.uniform3fv(I.pos,w)}else s.uniform3fv(I.pos,m.pos);s.uniform3fv(I.dir,m.dir)}}o.numIndices8Bits>0&&(this._program.bindTexture(this._uTexturePerPolygonIdPortionIds,{bind:function(e){return s.activeTexture(s["TEXTURE"+e]),s.bindTexture(s.TEXTURE_2D,o.texturePerPolygonIdPortionIds8Bits),!0},unbind:function(e){s.activeTexture(s["TEXTURE"+e]),s.bindTexture(s.TEXTURE_2D,null)}},4),this._program.bindTexture(this._uTexturePerPolygonIdIndices,{bind:function(e){return s.activeTexture(s["TEXTURE"+e]),s.bindTexture(s.TEXTURE_2D,o.texturePerPolygonIdIndices8Bits),!0},unbind:function(e){s.activeTexture(s["TEXTURE"+e]),s.bindTexture(s.TEXTURE_2D,null)}},5),s.drawArrays(s.TRIANGLES,0,o.numIndices8Bits)),o.numIndices16Bits>0&&(this._program.bindTexture(this._uTexturePerPolygonIdPortionIds,{bind:function(e){return s.activeTexture(s["TEXTURE"+e]),s.bindTexture(s.TEXTURE_2D,o.texturePerPolygonIdPortionIds16Bits),!0},unbind:function(e){s.activeTexture(s["TEXTURE"+e]),s.bindTexture(s.TEXTURE_2D,null)}},4),this._program.bindTexture(this._uTexturePerPolygonIdIndices,{bind:function(e){return s.activeTexture(s["TEXTURE"+e]),s.bindTexture(s.TEXTURE_2D,o.texturePerPolygonIdIndices16Bits),!0},unbind:function(e){s.activeTexture(s["TEXTURE"+e]),s.bindTexture(s.TEXTURE_2D,null)}},5),s.drawArrays(s.TRIANGLES,0,o.numIndices16Bits)),o.numIndices32Bits>0&&(this._program.bindTexture(this._uTexturePerPolygonIdPortionIds,{bind:function(e){return s.activeTexture(s["TEXTURE"+e]),s.bindTexture(s.TEXTURE_2D,o.texturePerPolygonIdPortionIds32Bits),!0},unbind:function(e){s.activeTexture(s["TEXTURE"+e]),s.bindTexture(s.TEXTURE_2D,null)}},4),this._program.bindTexture(this._uTexturePerPolygonIdIndices,{bind:function(e){return s.activeTexture(s["TEXTURE"+e]),s.bindTexture(s.TEXTURE_2D,o.texturePerPolygonIdIndices32Bits),!0},unbind:function(e){s.activeTexture(s["TEXTURE"+e]),s.bindTexture(s.TEXTURE_2D,null)}},5),s.drawArrays(s.TRIANGLES,0,o.numIndices32Bits)),e.drawElements++}},{key:"_allocate",value:function(){var e=this._scene,t=e.canvas.gl;if(this._program=new ft(t,this._buildShader()),this._program.errors)this.errors=this._program.errors;else{var n=this._program;this._uRenderPass=n.getLocation("renderPass"),this._uPickInvisible=n.getLocation("pickInvisible"),this._uPositionsDecodeMatrix=n.getLocation("positionsDecodeMatrix"),this._uWorldMatrix=n.getLocation("worldMatrix"),this._uViewMatrix=n.getLocation("viewMatrix"),this._uProjMatrix=n.getLocation("projMatrix"),this._uSectionPlanes=[];for(var r=0,i=e._sectionPlanesState.sectionPlanes.length;r<i;r++)this._uSectionPlanes.push({active:n.getLocation("sectionPlaneActive"+r),pos:n.getLocation("sectionPlanePos"+r),dir:n.getLocation("sectionPlaneDir"+r)});this._aPackedVertexId=n.getAttribute("packedVertexId"),e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=n.getLocation("logDepthBufFC")),this._uTexturePerObjectIdPositionsDecodeMatrix="uTexturePerObjectIdPositionsDecodeMatrix",this._uTexturePerObjectIdColorsAndFlags="uTexturePerObjectIdColorsAndFlags",this._uTexturePerVertexIdCoordinates="uTexturePerVertexIdCoordinates",this._uTexturePerPolygonIdNormals="uTexturePerPolygonIdNormals",this._uTexturePerPolygonIdIndices="uTexturePerPolygonIdIndices",this._uTexturePerPolygonIdPortionIds="uTexturePerPolygonIdPortionIds"}}},{key:"_bindProgram",value:function(){this._program.bind()}},{key:"_buildShader",value:function(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,n=[];return n.push("#version 300 es"),n.push("// Triangles dataTexture pick flat normals vertex shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("precision highp usampler2D;"),n.push("precision highp isampler2D;"),n.push("precision highp sampler2D;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("precision mediump usampler2D;"),n.push("precision mediump isampler2D;"),n.push("precision mediump sampler2D;"),n.push("#endif"),n.push("uniform int renderPass;"),n.push("in uvec3 packedVertexId;"),e.entityOffsetsEnabled&&n.push("in vec3 offset;"),n.push("uniform bool pickInvisible;"),n.push("uniform mat4 worldMatrix;"),n.push("uniform mat4 viewMatrix;"),n.push("uniform mat4 projMatrix;"),n.push("uniform sampler2D uTexturePerObjectIdPositionsDecodeMatrix;"),n.push("uniform usampler2D uTexturePerObjectIdColorsAndFlags;"),n.push("uniform usampler2D uTexturePerVertexIdCoordinates;"),n.push("uniform usampler2D uTexturePerPolygonIdIndices;"),n.push("uniform isampler2D uTexturePerPolygonIdNormals;"),n.push("uniform usampler2D uTexturePerPolygonIdPortionIds;"),e.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("out float vFragDepth;"),n.push("bool isPerspectiveMatrix(mat4 m) {"),n.push(" return (m[2][3] == - 1.0);"),n.push("}"),n.push("out float isPerspective;")),n.push("out vec4 vWorldPosition;"),t&&n.push("out int vFlags2;"),n.push("void main(void) {"),n.push("int polygonIndex = gl_VertexID / 3;"),n.push("int h_normal_index = polygonIndex & 4095;"),n.push("int v_normal_index = polygonIndex >> 12;"),n.push("int h_packed_object_id_index = ((polygonIndex >> 3) / 2) & 4095;"),n.push("int v_packed_object_id_index = ((polygonIndex >> 3) / 2) >> 12;"),n.push("ivec3 packedObjectId = ivec3(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).rgb);"),n.push("int objectIndex;"),n.push("if (((polygonIndex >> 3) % 2) == 0) {"),n.push(" objectIndex = (packedObjectId.r << 4) + (packedObjectId.g >> 4);"),n.push("} else {"),n.push(" objectIndex = ((packedObjectId.g & 15) << 8) + packedObjectId.b;"),n.push("}"),n.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),n.push("ivec4 packedVertexBase = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),n.push("int h_index = polygonIndex & 4095;"),n.push("int v_index = polygonIndex >> 12;"),n.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),n.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),n.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),n.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),n.push("mat4 positionsDecodeMatrix = mat4 (texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),n.push("uvec4 flags = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),n.push("uvec4 flags2 = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),n.push("vec3 position1 = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),n.push("vec3 position2 = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),n.push("vec3 position3 = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),n.push("vec3 normal = normalize(cross(position3 - position1, position2 - position1));"),n.push("int vertexNumber = gl_VertexID % 3;"),n.push("vec3 position;"),n.push("if (vertexNumber == 0) position = position1;"),n.push("else if (vertexNumber == 1) position = position2;"),n.push("else position = position3;"),n.push("if (int(flags.w) != renderPass) {"),n.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),n.push(" } else {"),n.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&n.push(" worldPosition.xyz = worldPosition.xyz + offset;"),n.push(" vec4 viewPosition = viewMatrix * worldPosition; "),n.push(" vWorldPosition = worldPosition;"),t&&n.push(" vFlags2 = flags2.r;"),n.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(n.push("vFragDepth = 1.0 + clipPos.w;"),n.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),n.push("gl_Position = clipPos;"),n.push(" }"),n.push("}"),n}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,n=t.sectionPlanes.length>0,r=[];if(r.push("#version 300 es"),r.push("// Triangles dataTexture pick flat normals fragment shader"),r.push("#extension GL_OES_standard_derivatives : enable"),e.logarithmicDepthBufferEnabled&&r.push("#extension GL_EXT_frag_depth : enable"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),e.logarithmicDepthBufferEnabled&&(r.push("in float isPerspective;"),r.push("uniform float logDepthBufFC;"),r.push("in float vFragDepth;")),r.push("in vec4 vWorldPosition;"),n){r.push("in int vFlags2;");for(var i=0;i<t.sectionPlanes.length;i++)r.push("uniform bool sectionPlaneActive"+i+";"),r.push("uniform vec3 sectionPlanePos"+i+";"),r.push("uniform vec3 sectionPlaneDir"+i+";")}if(r.push("out vec4 outNormal;"),r.push("void main(void) {"),n){r.push(" bool clippable = vFlags2 > 0;"),r.push(" if (clippable) {"),r.push(" float dist = 0.0;");for(i=0;i<t.sectionPlanes.length;i++)r.push(" if (sectionPlaneActive"+i+") {"),r.push(" dist += clamp(dot(-sectionPlaneDir"+i+".xyz, vWorldPosition.xyz - sectionPlanePos"+i+".xyz), 0.0, 1000.0);"),r.push(" }");r.push(" if (dist > 0.0) { discard; }"),r.push(" }")}return e.logarithmicDepthBufferEnabled&&r.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),r.push(" vec3 xTangent = dFdx( vWorldPosition.xyz );"),r.push(" vec3 yTangent = dFdy( vWorldPosition.xyz );"),r.push(" vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"),r.push(" outNormal = vec4((worldNormal * 0.5) + 0.5, 1.0);"),r.push("}"),r}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),e}(),Qc=function(){function e(t){b(this,e),this._scene=t}return P(e,[{key:"_compile",value:function(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._colorRendererWithSAO&&!this._colorRendererWithSAO.getValid()&&(this._colorRendererWithSAO.destroy(),this._colorRendererWithSAO=null),this._flatColorRenderer&&!this._flatColorRenderer.getValid()&&(this._flatColorRenderer.destroy(),this._flatColorRenderer=null),this._flatColorRendererWithSAO&&!this._flatColorRendererWithSAO.getValid()&&(this._flatColorRendererWithSAO.destroy(),this._flatColorRendererWithSAO=null),this._colorQualityRenderer&&!this._colorQualityRenderer.getValid()&&(this._colorQualityRenderer.destroy(),this._colorQualityRenderer=null),this._colorQualityRendererWithSAO&&!this._colorQualityRendererWithSAO.getValid()&&(this._colorQualityRendererWithSAO.destroy(),this._colorQualityRendererWithSAO=null),this._depthRenderer&&!this._depthRenderer.getValid()&&(this._depthRenderer.destroy(),this._depthRenderer=null),this._normalsRenderer&&!this._normalsRenderer.getValid()&&(this._normalsRenderer.destroy(),this._normalsRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null),this._edgesRenderer&&!this._edgesRenderer.getValid()&&(this._edgesRenderer.destroy(),this._edgesRenderer=null),this._edgesColorRenderer&&!this._edgesColorRenderer.getValid()&&(this._edgesColorRenderer.destroy(),this._edgesColorRenderer=null),this._pickMeshRenderer&&!this._pickMeshRenderer.getValid()&&(this._pickMeshRenderer.destroy(),this._pickMeshRenderer=null),this._pickDepthRenderer&&!this._pickDepthRenderer.getValid()&&(this._pickDepthRenderer.destroy(),this._pickDepthRenderer=null),this._vertexDepthRenderer&&!this._vertexDepthRenderer.getValid()&&(this._vertexDepthRenderer.destroy(),this._vertexDepthRenderer=null),this._snapDepthBufInitRenderer&&!this._snapDepthBufInitRenderer.getValid()&&(this._snapDepthBufInitRenderer.destroy(),this._snapDepthBufInitRenderer=null),this._pickNormalsRenderer&&!1===this._pickNormalsRenderer.getValid()&&(this._pickNormalsRenderer.destroy(),this._pickNormalsRenderer=null),this._pickNormalsFlatRenderer&&!1===this._pickNormalsFlatRenderer.getValid()&&(this._pickNormalsFlatRenderer.destroy(),this._pickNormalsFlatRenderer=null),this._occlusionRenderer&&!1===this._occlusionRenderer.getValid()&&(this._occlusionRenderer.destroy(),this._occlusionRenderer=null),this._shadowRenderer&&!this._shadowRenderer.getValid()&&(this._shadowRenderer.destroy(),this._shadowRenderer=null)}},{key:"colorRenderer",get:function(){return this._colorRenderer||(this._colorRenderer=new Ac(this._scene,!1)),this._colorRenderer}},{key:"colorRendererWithSAO",get:function(){return this._colorRendererWithSAO||(this._colorRendererWithSAO=new Ac(this._scene,!0)),this._colorRendererWithSAO}},{key:"colorQualityRenderer",get:function(){return this._colorQualityRenderer||(this._colorQualityRenderer=new kc(this._scene,!1)),this._colorQualityRenderer}},{key:"colorQualityRendererWithSAO",get:function(){return this._colorQualityRendererWithSAO||(this._colorQualityRendererWithSAO=new kc(this._scene,!0)),this._colorQualityRendererWithSAO}},{key:"silhouetteRenderer",get:function(){return this._silhouetteRenderer||(this._silhouetteRenderer=new hc(this._scene)),this._silhouetteRenderer}},{key:"depthRenderer",get:function(){return this._depthRenderer||(this._depthRenderer=new Lc(this._scene)),this._depthRenderer}},{key:"normalsRenderer",get:function(){return this._normalsRenderer||(this._normalsRenderer=new Mc(this._scene)),this._normalsRenderer}},{key:"edgesRenderer",get:function(){return this._edgesRenderer||(this._edgesRenderer=new mc(this._scene)),this._edgesRenderer}},{key:"edgesColorRenderer",get:function(){return this._edgesColorRenderer||(this._edgesColorRenderer=new gc(this._scene)),this._edgesColorRenderer}},{key:"pickMeshRenderer",get:function(){return this._pickMeshRenderer||(this._pickMeshRenderer=new Ec(this._scene)),this._pickMeshRenderer}},{key:"pickNormalsRenderer",get:function(){return this._pickNormalsRenderer||(this._pickNormalsRenderer=new Oc(this._scene)),this._pickNormalsRenderer}},{key:"pickNormalsFlatRenderer",get:function(){return this._pickNormalsFlatRenderer||(this._pickNormalsFlatRenderer=new jc(this._scene)),this._pickNormalsFlatRenderer}},{key:"pickDepthRenderer",get:function(){return this._pickDepthRenderer||(this._pickDepthRenderer=new Dc(this._scene)),this._pickDepthRenderer}},{key:"vertexDepthRenderer",get:function(){return this._vertexDepthRenderer||(this._vertexDepthRenderer=new Rc(this._scene)),this._vertexDepthRenderer}},{key:"snapDepthBufInitRenderer",get:function(){return this._snapDepthBufInitRenderer||(this._snapDepthBufInitRenderer=new _c(this._scene)),this._snapDepthBufInitRenderer}},{key:"occlusionRenderer",get:function(){return this._occlusionRenderer||(this._occlusionRenderer=new Sc(this._scene)),this._occlusionRenderer}},{key:"shadowRenderer",get:function(){return this._shadowRenderer||(this._shadowRenderer=new Fc(this._scene)),this._shadowRenderer}},{key:"_destroy",value:function(){this._colorRenderer&&this._colorRenderer.destroy(),this._colorRendererWithSAO&&this._colorRendererWithSAO.destroy(),this._flatColorRenderer&&this._flatColorRenderer.destroy(),this._flatColorRendererWithSAO&&this._flatColorRendererWithSAO.destroy(),this._colorQualityRenderer&&this._colorQualityRenderer.destroy(),this._colorQualityRendererWithSAO&&this._colorQualityRendererWithSAO.destroy(),this._depthRenderer&&this._depthRenderer.destroy(),this._normalsRenderer&&this._normalsRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._edgesRenderer&&this._edgesRenderer.destroy(),this._edgesColorRenderer&&this._edgesColorRenderer.destroy(),this._pickMeshRenderer&&this._pickMeshRenderer.destroy(),this._pickDepthRenderer&&this._pickDepthRenderer.destroy(),this._vertexDepthRenderer&&this._vertexDepthRenderer.destroy(),this._snapDepthBufInitRenderer&&this._snapDepthBufInitRenderer.destroy(),this._pickNormalsRenderer&&this._pickNormalsRenderer.destroy(),this._pickNormalsFlatRenderer&&this._pickNormalsFlatRenderer.destroy(),this._occlusionRenderer&&this._occlusionRenderer.destroy(),this._shadowRenderer&&this._shadowRenderer.destroy()}}]),e}(),Wc={};var zc=P((function e(){b(this,e),this.positionsCompressed=[],this.metallicRoughness=[],this.indices8Bits=[],this.indices16Bits=[],this.indices32Bits=[],this.edgeIndices8Bits=[],this.edgeIndices16Bits=[],this.edgeIndices32Bits=[],this.perObjectColors=[],this.perObjectPickColors=[],this.perObjectSolid=[],this.perObjectOffsets=[],this.perObjectPositionsDecodeMatrices=[],this.perObjectInstancePositioningMatrices=[],this.perObjectVertexBases=[],this.perObjectIndexBaseOffsets=[],this.perObjectEdgeIndexBaseOffsets=[],this.perTriangleNumberPortionId8Bits=[],this.perTriangleNumberPortionId16Bits=[],this.perTriangleNumberPortionId32Bits=[],this.perEdgeNumberPortionId8Bits=[],this.perEdgeNumberPortionId16Bits=[],this.perEdgeNumberPortionId32Bits=[]})),Kc=function(){function e(){b(this,e),this.texturePerObjectIdColorsAndFlags=null,this.texturePerObjectIdOffsets=null,this.texturePerObjectIdPositionsDecodeMatrix=null,this.texturePerVertexIdCoordinates=null,this.texturePerPolygonIdPortionIds8Bits=null,this.texturePerPolygonIdPortionIds16Bits=null,this.texturePerPolygonIdPortionIds32Bits=null,this.texturePerEdgeIdPortionIds8Bits=null,this.texturePerEdgeIdPortionIds16Bits=null,this.texturePerEdgeIdPortionIds32Bits=null,this.texturePerPolygonIdIndices8Bits=null,this.texturePerPolygonIdIndices16Bits=null,this.texturePerPolygonIdIndices32Bits=null,this.texturePerPolygonIdEdgeIndices8Bits=null,this.texturePerPolygonIdEdgeIndices16Bits=null,this.texturePerPolygonIdEdgeIndices32Bits=null,this.textureCameraMatrices=null,this.texturePickCameraMatrices=null,this.textureModelMatrices=null}return P(e,[{key:"finalize",value:function(){this.indicesPerBitnessTextures={8:this.texturePerPolygonIdIndices8Bits,16:this.texturePerPolygonIdIndices16Bits,32:this.texturePerPolygonIdIndices32Bits},this.indicesPortionIdsPerBitnessTextures={8:this.texturePerPolygonIdPortionIds8Bits,16:this.texturePerPolygonIdPortionIds16Bits,32:this.texturePerPolygonIdPortionIds32Bits},this.edgeIndicesPerBitnessTextures={8:this.texturePerPolygonIdEdgeIndices8Bits,16:this.texturePerPolygonIdEdgeIndices16Bits,32:this.texturePerPolygonIdEdgeIndices32Bits},this.edgeIndicesPortionIdsPerBitnessTextures={8:this.texturePerEdgeIdPortionIds8Bits,16:this.texturePerEdgeIdPortionIds16Bits,32:this.texturePerEdgeIdPortionIds32Bits}}},{key:"bindCommonTextures",value:function(e,t,n,r,i,a,s){this.texturePerObjectIdPositionsDecodeMatrix.bindTexture(e,t,1),this.texturePerVertexIdCoordinates.bindTexture(e,n,2),this.texturePerObjectIdColorsAndFlags.bindTexture(e,r,3),this.textureCameraMatrices.bindTexture(e,i,4),this.textureModelMatrices.bindTexture(e,a,5),this.texturePerObjectIdOffsets.bindTexture(e,s,6)}},{key:"bindPickCameraTexture",value:function(e,t){this.texturePickCameraMatrices.bindTexture(e,t,4)}},{key:"bindTriangleIndicesTextures",value:function(e,t,n,r){this.indicesPortionIdsPerBitnessTextures[r].bindTexture(e,t,7),this.indicesPerBitnessTextures[r].bindTexture(e,n,8)}},{key:"bindEdgeIndicesTextures",value:function(e,t,n,r){this.edgeIndicesPortionIdsPerBitnessTextures[r].bindTexture(e,t,7),this.edgeIndicesPerBitnessTextures[r].bindTexture(e,n,8)}}]),e}(),Yc=function(){function e(t,n,r,i){var a=arguments.length>4&&void 0!==arguments[4]?arguments[4]:null;b(this,e),this._gl=t,this._texture=n,this._textureWidth=r,this._textureHeight=i,this._textureData=a}return P(e,[{key:"bindTexture",value:function(e,t,n){return e.bindTexture(t,this,n)}},{key:"bind",value:function(e){return this._gl.activeTexture(this._gl["TEXTURE"+e]),this._gl.bindTexture(this._gl.TEXTURE_2D,this._texture),!0}},{key:"unbind",value:function(e){}}]),e}(),Xc={sizeDataColorsAndFlags:0,sizeDataPositionDecodeMatrices:0,sizeDataTextureOffsets:0,sizeDataTexturePositions:0,sizeDataTextureIndices:0,sizeDataTextureEdgeIndices:0,sizeDataTexturePortionIds:0,numberOfGeometries:0,numberOfPortions:0,numberOfLayers:0,numberOfTextures:0,totalPolygons:0,totalPolygons8Bits:0,totalPolygons16Bits:0,totalPolygons32Bits:0,totalEdges:0,totalEdges8Bits:0,totalEdges16Bits:0,totalEdges32Bits:0,cannotCreatePortion:{because10BitsObjectId:0,becauseTextureSize:0},overheadSizeAlignementIndices:0,overheadSizeAlignementEdgeIndices:0};window.printDataTextureRamStats=function(){console.log(JSON.stringify(Xc,null,4));var e=0;Object.keys(Xc).forEach((function(t){t.startsWith("size")&&(e+=Xc[t])})),console.log("Total size ".concat(e," bytes (").concat((e/1e3/1e3).toFixed(2)," MB)")),console.log("Avg bytes / triangle: ".concat((e/Xc.totalPolygons).toFixed(2)));var t={};Object.keys(Xc).forEach((function(n){n.startsWith("size")&&(t[n]="".concat((Xc[n]/e*100).toFixed(2)," % of total"))})),console.log(JSON.stringify({percentualRamUsage:t},null,4))};var qc=function(){function e(){b(this,e)}return P(e,[{key:"disableBindedTextureFiltering",value:function(e){e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE)}},{key:"generateCameraDataTexture",value:function(e,t,n,r){var i=e.createTexture();e.bindTexture(e.TEXTURE_2D,i),e.texStorage2D(e.TEXTURE_2D,1,e.RGBA32F,4,3),this.disableBindedTextureFiltering(e),e.bindTexture(e.TEXTURE_2D,null);var a=new Yc(e,i,4,3),s=!0;a.updateViewMatrix=function(n,i){e.bindTexture(e.TEXTURE_2D,a._texture),e.texSubImage2D(e.TEXTURE_2D,0,0,0,4,1,e.RGBA,e.FLOAT,new Float32Array(r?Ie(n,r):n)),e.texSubImage2D(e.TEXTURE_2D,0,0,1,4,1,e.RGBA,e.FLOAT,new Float32Array(t.viewNormalMatrix)),e.texSubImage2D(e.TEXTURE_2D,0,0,2,4,1,e.RGBA,e.FLOAT,new Float32Array(i))};var o=function(){s&&(s=!1,a.updateViewMatrix(t.viewMatrix,t.project.matrix))};return t.on("matrix",(function(){return s=!0})),n.on("rendering",o),o(),a}},{key:"generatePickCameraDataTexture",value:function(e,t,n){var r=e.createTexture();e.bindTexture(e.TEXTURE_2D,r),e.texStorage2D(e.TEXTURE_2D,1,e.RGBA32F,4,3),this.disableBindedTextureFiltering(e),e.bindTexture(e.TEXTURE_2D,null);var i=new Yc(e,r,4,3);return i.updateViewMatrix=function(r,a){e.bindTexture(e.TEXTURE_2D,i._texture),e.texSubImage2D(e.TEXTURE_2D,0,0,0,4,1,e.RGBA,e.FLOAT,new Float32Array(n?Ie(r,n):r)),e.texSubImage2D(e.TEXTURE_2D,0,0,1,4,1,e.RGBA,e.FLOAT,new Float32Array(t.viewNormalMatrix)),e.texSubImage2D(e.TEXTURE_2D,0,0,2,4,1,e.RGBA,e.FLOAT,new Float32Array(a))},i}},{key:"generateModelTexture",value:function(e,t){var n=e.createTexture();return e.bindTexture(e.TEXTURE_2D,n),e.texStorage2D(e.TEXTURE_2D,1,e.RGBA32F,4,2),e.texSubImage2D(e.TEXTURE_2D,0,0,0,4,1,e.RGBA,e.FLOAT,new Float32Array(t.worldMatrix)),e.texSubImage2D(e.TEXTURE_2D,0,0,1,4,1,e.RGBA,e.FLOAT,new Float32Array(t.worldNormalMatrix)),this.disableBindedTextureFiltering(e),e.bindTexture(e.TEXTURE_2D,null),new Yc(e,n,4,2)}},{key:"generateTextureForColorsAndFlags",value:function(e,t,n,r,i,a,s){var o=t.length;this.numPortions=o;var l=4096,u=Math.ceil(o/512);if(0===u)throw"texture height===0";var c=new Uint8Array(16384*u);Xc.sizeDataColorsAndFlags+=c.byteLength,Xc.numberOfTextures++;for(var f=0;f<o;f++)c.set(t[f],32*f+0),c.set(n[f],32*f+4),c.set([0,0,0,0],32*f+8),c.set([0,0,0,0],32*f+12),c.set([r[f]>>24&255,r[f]>>16&255,r[f]>>8&255,255&r[f]],32*f+16),c.set([i[f]>>24&255,i[f]>>16&255,i[f]>>8&255,255&i[f]],32*f+20),c.set([a[f]>>24&255,a[f]>>16&255,a[f]>>8&255,255&a[f]],32*f+24),c.set([s[f]?1:0,0,0,0],32*f+28);var p=e.createTexture();return e.bindTexture(e.TEXTURE_2D,p),e.texStorage2D(e.TEXTURE_2D,1,e.RGBA8UI,l,u),e.texSubImage2D(e.TEXTURE_2D,0,0,0,l,u,e.RGBA_INTEGER,e.UNSIGNED_BYTE,c,0),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.bindTexture(e.TEXTURE_2D,null),new Yc(e,p,l,u,c)}},{key:"generateTextureForObjectOffsets",value:function(e,t){var n=512,r=Math.ceil(t/n);if(0===r)throw"texture height===0";var i=new Float32Array(1536*r).fill(0);Xc.sizeDataTextureOffsets+=i.byteLength,Xc.numberOfTextures++;var a=e.createTexture();return e.bindTexture(e.TEXTURE_2D,a),e.texStorage2D(e.TEXTURE_2D,1,e.RGB32F,n,r),e.texSubImage2D(e.TEXTURE_2D,0,0,0,n,r,e.RGB,e.FLOAT,i,0),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.bindTexture(e.TEXTURE_2D,null),new Yc(e,a,n,r,i)}},{key:"generateTextureForPositionsDecodeMatrices",value:function(e,t,n){var r=t.length;if(0===r)throw"num decode+entity matrices===0";var i=2048,a=Math.ceil(r/512),s=new Float32Array(8192*a);Xc.sizeDataPositionDecodeMatrices+=s.byteLength,Xc.numberOfTextures++;for(var o=Z.mat4(),l=0;l<t.length;l++)s.set(Z.mulMat4(n[l],t[l],o),16*l);var u=e.createTexture();return e.bindTexture(e.TEXTURE_2D,u),e.texStorage2D(e.TEXTURE_2D,1,e.RGBA32F,i,a),e.texSubImage2D(e.TEXTURE_2D,0,0,0,i,a,e.RGBA,e.FLOAT,s,0),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.bindTexture(e.TEXTURE_2D,null),new Yc(e,u,i,a)}},{key:"generateTextureFor8BitIndices",value:function(e,t){if(0===t.length)return{texture:null,textureHeight:0};var n=4096,r=Math.ceil(t.length/3/n);if(0===r)throw"texture height===0";var i=new Uint8Array(n*r*3);Xc.sizeDataTextureIndices+=i.byteLength,Xc.numberOfTextures++,i.fill(0),i.set(t,0);var a=e.createTexture();return e.bindTexture(e.TEXTURE_2D,a),e.texStorage2D(e.TEXTURE_2D,1,e.RGB8UI,n,r),e.texSubImage2D(e.TEXTURE_2D,0,0,0,n,r,e.RGB_INTEGER,e.UNSIGNED_BYTE,i,0),this.disableBindedTextureFiltering(e),e.bindTexture(e.TEXTURE_2D,null),new Yc(e,a,n,r)}},{key:"generateTextureFor16BitIndices",value:function(e,t){if(0===t.length)return{texture:null,textureHeight:0};var n=4096,r=Math.ceil(t.length/3/n);if(0===r)throw"texture height===0";var i=new Uint16Array(n*r*3);Xc.sizeDataTextureIndices+=i.byteLength,Xc.numberOfTextures++,i.fill(0),i.set(t,0);var a=e.createTexture();return e.bindTexture(e.TEXTURE_2D,a),e.texStorage2D(e.TEXTURE_2D,1,e.RGB16UI,n,r),e.texSubImage2D(e.TEXTURE_2D,0,0,0,n,r,e.RGB_INTEGER,e.UNSIGNED_SHORT,i,0),this.disableBindedTextureFiltering(e),e.bindTexture(e.TEXTURE_2D,null),new Yc(e,a,n,r)}},{key:"generateTextureFor32BitIndices",value:function(e,t){if(0===t.length)return{texture:null,textureHeight:0};var n=4096,r=Math.ceil(t.length/3/n);if(0===r)throw"texture height===0";var i=new Uint32Array(n*r*3);Xc.sizeDataTextureIndices+=i.byteLength,Xc.numberOfTextures++,i.fill(0),i.set(t,0);var a=e.createTexture();return e.bindTexture(e.TEXTURE_2D,a),e.texStorage2D(e.TEXTURE_2D,1,e.RGB32UI,n,r),e.texSubImage2D(e.TEXTURE_2D,0,0,0,n,r,e.RGB_INTEGER,e.UNSIGNED_INT,i,0),this.disableBindedTextureFiltering(e),e.bindTexture(e.TEXTURE_2D,null),new Yc(e,a,n,r)}},{key:"generateTextureFor8BitsEdgeIndices",value:function(e,t){if(0===t.length)return{texture:null,textureHeight:0};var n=4096,r=Math.ceil(t.length/2/n);if(0===r)throw"texture height===0";var i=new Uint8Array(n*r*2);Xc.sizeDataTextureEdgeIndices+=i.byteLength,Xc.numberOfTextures++,i.fill(0),i.set(t,0);var a=e.createTexture();return e.bindTexture(e.TEXTURE_2D,a),e.texStorage2D(e.TEXTURE_2D,1,e.RG8UI,n,r),e.texSubImage2D(e.TEXTURE_2D,0,0,0,n,r,e.RG_INTEGER,e.UNSIGNED_BYTE,i,0),this.disableBindedTextureFiltering(e),e.bindTexture(e.TEXTURE_2D,null),new Yc(e,a,n,r)}},{key:"generateTextureFor16BitsEdgeIndices",value:function(e,t){if(0===t.length)return{texture:null,textureHeight:0};var n=4096,r=Math.ceil(t.length/2/n);if(0===r)throw"texture height===0";var i=new Uint16Array(n*r*2);Xc.sizeDataTextureEdgeIndices+=i.byteLength,Xc.numberOfTextures++,i.fill(0),i.set(t,0);var a=e.createTexture();return e.bindTexture(e.TEXTURE_2D,a),e.texStorage2D(e.TEXTURE_2D,1,e.RG16UI,n,r),e.texSubImage2D(e.TEXTURE_2D,0,0,0,n,r,e.RG_INTEGER,e.UNSIGNED_SHORT,i,0),this.disableBindedTextureFiltering(e),e.bindTexture(e.TEXTURE_2D,null),new Yc(e,a,n,r)}},{key:"generateTextureFor32BitsEdgeIndices",value:function(e,t){if(0===t.length)return{texture:null,textureHeight:0};var n=4096,r=Math.ceil(t.length/2/n);if(0===r)throw"texture height===0";var i=new Uint32Array(n*r*2);Xc.sizeDataTextureEdgeIndices+=i.byteLength,Xc.numberOfTextures++,i.fill(0),i.set(t,0);var a=e.createTexture();return e.bindTexture(e.TEXTURE_2D,a),e.texStorage2D(e.TEXTURE_2D,1,e.RG32UI,n,r),e.texSubImage2D(e.TEXTURE_2D,0,0,0,n,r,e.RG_INTEGER,e.UNSIGNED_INT,i,0),this.disableBindedTextureFiltering(e),e.bindTexture(e.TEXTURE_2D,null),new Yc(e,a,n,r)}},{key:"generateTextureForPositions",value:function(e,t){var n=t.length/3,r=4096,i=Math.ceil(n/r);if(0===i)throw"texture height===0";var a=new Uint16Array(r*i*3);Xc.sizeDataTexturePositions+=a.byteLength,Xc.numberOfTextures++,a.fill(0),a.set(t,0);var s=e.createTexture();return e.bindTexture(e.TEXTURE_2D,s),e.texStorage2D(e.TEXTURE_2D,1,e.RGB16UI,r,i),e.texSubImage2D(e.TEXTURE_2D,0,0,0,r,i,e.RGB_INTEGER,e.UNSIGNED_SHORT,a,0),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.bindTexture(e.TEXTURE_2D,null),new Yc(e,s,r,i)}},{key:"generateTextureForPackedPortionIds",value:function(e,t){if(0===t.length)return{texture:null,textureHeight:0};var n=t.length,r=4096,i=Math.ceil(n/r);if(0===i)throw"texture height===0";var a=new Uint16Array(r*i);a.set(t,0),Xc.sizeDataTexturePortionIds+=a.byteLength,Xc.numberOfTextures++;var s=e.createTexture();return e.bindTexture(e.TEXTURE_2D,s),e.texStorage2D(e.TEXTURE_2D,1,e.R16UI,r,i),e.texSubImage2D(e.TEXTURE_2D,0,0,0,r,i,e.RED_INTEGER,e.UNSIGNED_SHORT,a,0),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.bindTexture(e.TEXTURE_2D,null),new Yc(e,s,r,i)}}]),e}(),Jc=Z.vec4([0,0,0,1]),Zc=Z.vec4([0,0,0,1]),$c=Z.vec4([0,0,0,1]),ef=new Uint8Array(4),tf=new Float32Array(3);Z.AABB3();var nf=Z.AABB3();Z.OBB3();var rf=0,af=Z.identityMat4(),sf=function(){function e(t,n){var r,i,a;b(this,e),Xc.numberOfLayers++,this._layerNumber=rf++,this.sortId="TriDTX-".concat(this._layerNumber),this.layerIndex=n.layerIndex,this._dataTextureRenderers=(r=t.scene,i=r.id,(a=Wc[i])||(a=new Qc(r),Wc[i]=a,a._compile(),r.on("compile",(function(){a._compile()})),r.on("destroyed",(function(){delete Wc[i],a._destroy()}))),a),this.model=t,this._buffer=new zc,this._dataTextureState=new Kc,this._dataTextureGenerator=new qc,this._state=new St({origin:Z.vec3(n.origin),metallicRoughnessBuf:null,positionsDecodeMatrix:Z.mat4(),textureState:this._dataTextureState,numIndices8Bits:0,numIndices16Bits:0,numIndices32Bits:0,numEdgeIndices8Bits:0,numEdgeIndices16Bits:0,numEdgeIndices32Bits:0,numVertices:0}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numSelectedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numClippableLayerPortions=0,this._numEdgesLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this._subPortions=[],this._portionToSubPortionsMap=[],this._bucketGeometries={},this.aabb=Z.collapseAABB3(),this._numUpdatesInFrame=0,this._finalized=!1}return P(e,[{key:"canCreatePortion",value:function(e){if(this._finalized)throw"Already finalized";var t=e.buckets.length;this._numPortions+t>65536&&Xc.cannotCreatePortion.because10BitsObjectId++;var n=this._numPortions+t<=65536,r=void 0!==e.geometryId&&null!==e.geometryId?"".concat(e.geometryId,"#").concat(0):"".concat(e.id,"#").concat(0);if(!this._bucketGeometries[r]){var i=Math.max(this._state.numIndices8Bits,this._state.numIndices16Bits,this._state.numIndices32Bits),a=0,s=0;e.buckets.forEach((function(e){a+=e.positionsCompressed.length/3,s+=e.indices.length/3})),(this._state.numVertices+a>16777216||i+s>16777216)&&Xc.cannotCreatePortion.becauseTextureSize++,n&&(n=this._state.numVertices+a<=16777216&&i+s<=16777216)}return n}},{key:"createPortion",value:function(e){var t=this;if(this._finalized)throw"Already finalized";var n=[],r=e.worldAABB;e.buckets.forEach((function(i,a){var s=void 0!==e.geometryId&&null!==e.geometryId?"".concat(e.geometryId,"#").concat(a):"".concat(e.id,"#").concat(a),o=t._bucketGeometries[s];o||(o=t._createBucketGeometry(e,i),t._bucketGeometries[s]=o);var l=Z.collapseAABB3(nf),u=t._createSubPortion(e,o,i,l);Z.expandAABB3(r,l),n.push(u)}));var i=this._state.origin;0===i[0]&&0===i[1]&&0===i[2]||(r[0]+=i[0],r[1]+=i[1],r[2]+=i[2],r[3]+=i[0],r[4]+=i[1],r[5]+=i[2]),Z.expandAABB3(this.aabb,r);var a=this._portionToSubPortionsMap.length;return this._portionToSubPortionsMap.push(n),this.model.numPortions++,a}},{key:"_createBucketGeometry",value:function(e,t){if(t.indices){var n=8*Math.ceil(t.indices.length/3/8)*3;Xc.overheadSizeAlignementIndices+=2*(n-t.indices.length);var r=new Uint32Array(n);r.fill(0),r.set(t.indices),t.indices=r}if(t.edgeIndices){var i=8*Math.ceil(t.edgeIndices.length/2/8)*2;Xc.overheadSizeAlignementEdgeIndices+=2*(i-t.edgeIndices.length);var a=new Uint32Array(i);a.fill(0),a.set(t.edgeIndices),t.edgeIndices=a}for(var s,o=t.positionsCompressed,l=t.indices,u=t.edgeIndices,c=this._buffer,f=c.positionsCompressed.length/3,p=o.length/3,A=0,d=o.length;A<d;A++)c.positionsCompressed.push(o[A]);var v,h=0;if(l){var I;h=l.length/3,s=(I=p<=256?c.indices8Bits:p<=65536?c.indices16Bits:c.indices32Bits).length/3;for(var y=0,m=l.length;y<m;y++)I.push(l[y])}var w=0;if(u){var g;w=u.length/2,v=(g=p<=256?c.edgeIndices8Bits:p<=65536?c.edgeIndices16Bits:c.edgeIndices32Bits).length/2;for(var T=0,E=u.length;T<E;T++)g.push(u[T])}this._state.numVertices+=p,Xc.numberOfGeometries++;var b=Z.collapseAABB3();return Z.expandAABB3Points3(b,t.positionsCompressed),pn.decompressAABB(b,e.positionsDecodeMatrix),{vertexBase:f,numVertices:p,numTriangles:h,numEdges:w,indicesBase:s,edgeIndicesBase:v,aabb:b,obb:null}}},{key:"_createSubPortion",value:function(e,t,n,r){var i=e.color;e.metallic,e.roughness;var a,s,o=e.colors,l=e.opacity,u=e.meshMatrix,c=e.sceneModelMatrix,f=e.pickColor,p=this._buffer,A=this._state;if(p.perObjectPositionsDecodeMatrices.push(e.positionsDecodeMatrix),p.perObjectInstancePositioningMatrices.push(u||af),u||c){t.obb||(t.obb=Z.AABB3ToOBB3(t.aabb));for(var d=t.obb,v=0,h=d.length;v<h;v+=4)Jc[0]=d[v+0],Jc[1]=d[v+1],Jc[2]=d[v+2],Jc[3]=1,u&&Z.transformPoint4(u,Jc,Zc),c?(Z.transformPoint4(c,Zc,$c),Z.expandAABB3Point3(r,$c)):Z.expandAABB3Point3(r,Zc)}else Z.expandAABB3(r,t.aabb);p.perObjectSolid.push(!!e.solid),o?p.perObjectColors.push([255*o[0],255*o[1],255*o[2],255]):i&&p.perObjectColors.push([i[0],i[1],i[2],l]),p.perObjectPickColors.push(f),p.perObjectVertexBases.push(t.vertexBase),a=t.numVertices<=256?A.numIndices8Bits:t.numVertices<=65536?A.numIndices16Bits:A.numIndices32Bits,p.perObjectIndexBaseOffsets.push(a/3-t.indicesBase),s=t.numVertices<=256?A.numEdgeIndices8Bits:t.numVertices<=65536?A.numEdgeIndices16Bits:A.numEdgeIndices32Bits,p.perObjectEdgeIndexBaseOffsets.push(s/2-t.edgeIndicesBase);var I=this._subPortions.length;if(t.numTriangles>0){var y,m=3*t.numTriangles;t.numVertices<=256?(y=p.perTriangleNumberPortionId8Bits,A.numIndices8Bits+=m,Xc.totalPolygons8Bits+=t.numTriangles):t.numVertices<=65536?(y=p.perTriangleNumberPortionId16Bits,A.numIndices16Bits+=m,Xc.totalPolygons16Bits+=t.numTriangles):(y=p.perTriangleNumberPortionId32Bits,A.numIndices32Bits+=m,Xc.totalPolygons32Bits+=t.numTriangles),Xc.totalPolygons+=t.numTriangles;for(var w=0;w<t.numTriangles;w+=8)y.push(I)}if(t.numEdges>0){var g,T=2*t.numEdges;t.numVertices<=256?(g=p.perEdgeNumberPortionId8Bits,A.numEdgeIndices8Bits+=T,Xc.totalEdges8Bits+=t.numEdges):t.numVertices<=65536?(g=p.perEdgeNumberPortionId16Bits,A.numEdgeIndices16Bits+=T,Xc.totalEdges16Bits+=t.numEdges):(g=p.perEdgeNumberPortionId32Bits,A.numEdgeIndices32Bits+=T,Xc.totalEdges32Bits+=t.numEdges),Xc.totalEdges+=t.numEdges;for(var E=0;E<t.numEdges;E+=8)g.push(I)}return this._subPortions.push({numVertices:t.numTriangles}),this._numPortions++,Xc.numberOfPortions++,I}},{key:"finalize",value:function(){var e=this;if(!this._finalized){var t=this._state,n=this._dataTextureState,r=this.model.scene.canvas.gl,i=this._buffer;t.gl=r,n.texturePerObjectIdColorsAndFlags=this._dataTextureGenerator.generateTextureForColorsAndFlags(r,i.perObjectColors,i.perObjectPickColors,i.perObjectVertexBases,i.perObjectIndexBaseOffsets,i.perObjectEdgeIndexBaseOffsets,i.perObjectSolid),n.texturePerObjectIdOffsets=this._dataTextureGenerator.generateTextureForObjectOffsets(r,this._numPortions),n.texturePerObjectIdPositionsDecodeMatrix=this._dataTextureGenerator.generateTextureForPositionsDecodeMatrices(r,i.perObjectPositionsDecodeMatrices,i.perObjectInstancePositioningMatrices),n.texturePerVertexIdCoordinates=this._dataTextureGenerator.generateTextureForPositions(r,i.positionsCompressed),n.texturePerPolygonIdPortionIds8Bits=this._dataTextureGenerator.generateTextureForPackedPortionIds(r,i.perTriangleNumberPortionId8Bits),n.texturePerPolygonIdPortionIds16Bits=this._dataTextureGenerator.generateTextureForPackedPortionIds(r,i.perTriangleNumberPortionId16Bits),n.texturePerPolygonIdPortionIds32Bits=this._dataTextureGenerator.generateTextureForPackedPortionIds(r,i.perTriangleNumberPortionId32Bits),i.perEdgeNumberPortionId8Bits.length>0&&(n.texturePerEdgeIdPortionIds8Bits=this._dataTextureGenerator.generateTextureForPackedPortionIds(r,i.perEdgeNumberPortionId8Bits)),i.perEdgeNumberPortionId16Bits.length>0&&(n.texturePerEdgeIdPortionIds16Bits=this._dataTextureGenerator.generateTextureForPackedPortionIds(r,i.perEdgeNumberPortionId16Bits)),i.perEdgeNumberPortionId32Bits.length>0&&(n.texturePerEdgeIdPortionIds32Bits=this._dataTextureGenerator.generateTextureForPackedPortionIds(r,i.perEdgeNumberPortionId32Bits)),i.indices8Bits.length>0&&(n.texturePerPolygonIdIndices8Bits=this._dataTextureGenerator.generateTextureFor8BitIndices(r,i.indices8Bits)),i.indices16Bits.length>0&&(n.texturePerPolygonIdIndices16Bits=this._dataTextureGenerator.generateTextureFor16BitIndices(r,i.indices16Bits)),i.indices32Bits.length>0&&(n.texturePerPolygonIdIndices32Bits=this._dataTextureGenerator.generateTextureFor32BitIndices(r,i.indices32Bits)),i.edgeIndices8Bits.length>0&&(n.texturePerPolygonIdEdgeIndices8Bits=this._dataTextureGenerator.generateTextureFor8BitsEdgeIndices(r,i.edgeIndices8Bits)),i.edgeIndices16Bits.length>0&&(n.texturePerPolygonIdEdgeIndices16Bits=this._dataTextureGenerator.generateTextureFor16BitsEdgeIndices(r,i.edgeIndices16Bits)),i.edgeIndices32Bits.length>0&&(n.texturePerPolygonIdEdgeIndices32Bits=this._dataTextureGenerator.generateTextureFor32BitsEdgeIndices(r,i.edgeIndices32Bits)),this.model._modelMatricesTexture||(this.model._modelMatricesTexture=this._dataTextureGenerator.generateModelTexture(r,this.model)),n.textureModelMatrices=this.model._modelMatricesTexture,n.cameraTexture=this._dataTextureGenerator.generateCameraDataTexture(this.model.scene.canvas.gl,this.model.scene.camera,this.model.scene,this._state.origin.slice()),n.textureCameraMatrices=n.cameraTexture,n.texturePickCameraMatrices=this._dataTextureGenerator.generatePickCameraDataTexture(this.model.scene.canvas.gl,this.model.scene.camera,this._state.origin.slice()),n.finalize(),this._buffer=null,this._bucketGeometries={},this._finalized=!0,this._deferredSetFlagsDirty=!1,this._onSceneRendering=this.model.scene.on("rendering",(function(){e._deferredSetFlagsDirty&&e._uploadDeferredFlags(),e._numUpdatesInFrame=0}))}}},{key:"isEmpty",value:function(){return 0===this._numPortions}},{key:"initFlags",value:function(e,t,n){t&Te&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&Ce&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&Re&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&_e&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&De&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&Be&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&be&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&Ee&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),n&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++);this._setFlags(e,t,n,true),this._setFlags2(e,t,true)}},{key:"flushInitFlags",value:function(){this._setDeferredFlags(),this._setDeferredFlags2()}},{key:"setVisible",value:function(e,t,n){if(!this._finalized)throw"Not finalized";t&Te?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,n)}},{key:"setHighlighted",value:function(e,t,n){if(!this._finalized)throw"Not finalized";t&Ce?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,n)}},{key:"setXRayed",value:function(e,t,n){if(!this._finalized)throw"Not finalized";t&Re?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,n)}},{key:"setSelected",value:function(e,t,n){if(!this._finalized)throw"Not finalized";t&_e?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,n)}},{key:"setEdges",value:function(e,t,n){if(!this._finalized)throw"Not finalized";t&Be?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,n)}},{key:"setClippable",value:function(e,t){if(!this._finalized)throw"Not finalized";t&De?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags2(e,t)}},{key:"_beginDeferredFlags",value:function(){this._deferredSetFlagsActive=!0}},{key:"_uploadDeferredFlags",value:function(){if(this._deferredSetFlagsActive=!1,this._deferredSetFlagsDirty){this._deferredSetFlagsDirty=!1;var e=this.model.scene.canvas.gl,t=this._dataTextureState;e.bindTexture(e.TEXTURE_2D,t.texturePerObjectIdColorsAndFlags._texture),e.texSubImage2D(e.TEXTURE_2D,0,0,0,t.texturePerObjectIdColorsAndFlags._textureWidth,t.texturePerObjectIdColorsAndFlags._textureHeight,e.RGBA_INTEGER,e.UNSIGNED_BYTE,t.texturePerObjectIdColorsAndFlags._textureData),e.bindTexture(e.TEXTURE_2D,t.texturePerObjectIdOffsets._texture),e.texSubImage2D(e.TEXTURE_2D,0,0,0,t.texturePerObjectIdOffsets._textureWidth,t.texturePerObjectIdOffsets._textureHeight,e.RGB,e.FLOAT,t.texturePerObjectIdOffsets._textureData)}}},{key:"setCulled",value:function(e,t,n){if(!this._finalized)throw"Not finalized";t&Ee?(this._numCulledLayerPortions+=this._portionToSubPortionsMap[e].length,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions-=this._portionToSubPortionsMap[e].length,this.model.numCulledLayerPortions--),this._setFlags(e,t,n)}},{key:"setCollidable",value:function(e,t){if(!this._finalized)throw"Not finalized"}},{key:"setPickable",value:function(e,t,n){if(!this._finalized)throw"Not finalized";t&be?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,n)}},{key:"setColor",value:function(e,t){for(var n=this._portionToSubPortionsMap[e],r=0,i=n.length;r<i;r++)this._subPortionSetColor(n[r],t)}},{key:"_subPortionSetColor",value:function(e,t){if(!this._finalized)throw"Not finalized";var n=this._dataTextureState,r=this.model.scene.canvas.gl;ef[0]=t[0],ef[1]=t[1],ef[2]=t[2],ef[3]=t[3],n.texturePerObjectIdColorsAndFlags._textureData.set(ef,32*e),this._deferredSetFlagsActive?this._deferredSetFlagsDirty=!0:(++this._numUpdatesInFrame>=10&&this._beginDeferredFlags(),r.bindTexture(r.TEXTURE_2D,n.texturePerObjectIdColorsAndFlags._texture),r.texSubImage2D(r.TEXTURE_2D,0,e%512*8,Math.floor(e/512),1,1,r.RGBA_INTEGER,r.UNSIGNED_BYTE,ef))}},{key:"setTransparent",value:function(e,t,n){n?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,n)}},{key:"_setFlags",value:function(e,t,n){for(var r=arguments.length>3&&void 0!==arguments[3]&&arguments[3],i=this._portionToSubPortionsMap[e],a=0,s=i.length;a<s;a++)this._subPortionSetFlags(i[a],t,n,r)}},{key:"_subPortionSetFlags",value:function(e,t,n){var r=arguments.length>3&&void 0!==arguments[3]&&arguments[3];if(!this._finalized)throw"Not finalized";var i,a,s=!!(t&Te),o=!!(t&Re),l=!!(t&Ce),u=!!(t&_e),c=!!(t&Be),f=!!(t&be),p=!!(t&Ee);i=!s||p||o?eo.NOT_RENDERED:n?eo.COLOR_TRANSPARENT:eo.COLOR_OPAQUE,a=!s||p?eo.NOT_RENDERED:u?eo.SILHOUETTE_SELECTED:l?eo.SILHOUETTE_HIGHLIGHTED:o?eo.SILHOUETTE_XRAYED:eo.NOT_RENDERED;var A=0;A=!s||p?eo.NOT_RENDERED:u?eo.EDGES_SELECTED:l?eo.EDGES_HIGHLIGHTED:o?eo.EDGES_XRAYED:c?n?eo.EDGES_COLOR_TRANSPARENT:eo.EDGES_COLOR_OPAQUE:eo.NOT_RENDERED;var d=s&&f?eo.PICK:eo.NOT_RENDERED,v=this._dataTextureState,h=this.model.scene.canvas.gl;ef[0]=i,ef[1]=a,ef[2]=A,ef[3]=d,v.texturePerObjectIdColorsAndFlags._textureData.set(ef,32*e+8),this._deferredSetFlagsActive||r?this._deferredSetFlagsDirty=!0:(++this._numUpdatesInFrame>=10&&this._beginDeferredFlags(),h.bindTexture(h.TEXTURE_2D,v.texturePerObjectIdColorsAndFlags._texture),h.texSubImage2D(h.TEXTURE_2D,0,e%512*8+2,Math.floor(e/512),1,1,h.RGBA_INTEGER,h.UNSIGNED_BYTE,ef))}},{key:"_setDeferredFlags",value:function(){}},{key:"_setFlags2",value:function(e,t){for(var n=arguments.length>2&&void 0!==arguments[2]&&arguments[2],r=this._portionToSubPortionsMap[e],i=0,a=r.length;i<a;i++)this._subPortionSetFlags2(r[i],t,n)}},{key:"_subPortionSetFlags2",value:function(e,t){var n=arguments.length>2&&void 0!==arguments[2]&&arguments[2];if(!this._finalized)throw"Not finalized";var r=t&De?255:0,i=this._dataTextureState,a=this.model.scene.canvas.gl;ef[0]=r,ef[1]=0,ef[2]=1,ef[3]=2,i.texturePerObjectIdColorsAndFlags._textureData.set(ef,32*e+12),this._deferredSetFlagsActive||n?this._deferredSetFlagsDirty=!0:(++this._numUpdatesInFrame>=10&&this._beginDeferredFlags(),a.bindTexture(a.TEXTURE_2D,i.texturePerObjectIdColorsAndFlags._texture),a.texSubImage2D(a.TEXTURE_2D,0,e%512*8+3,Math.floor(e/512),1,1,a.RGBA_INTEGER,a.UNSIGNED_BYTE,ef))}},{key:"_setDeferredFlags2",value:function(){}},{key:"setOffset",value:function(e,t){for(var n=this._portionToSubPortionsMap[e],r=0,i=n.length;r<i;r++)this._subPortionSetOffset(n[r],t)}},{key:"_subPortionSetOffset",value:function(e,t){if(!this._finalized)throw"Not finalized";var n=this._dataTextureState,r=this.model.scene.canvas.gl;tf[0]=t[0],tf[1]=t[1],tf[2]=t[2],n.texturePerObjectIdOffsets._textureData.set(tf,3*e),this._deferredSetFlagsActive?this._deferredSetFlagsDirty=!0:(++this._numUpdatesInFrame>=10&&this._beginDeferredFlags(),r.bindTexture(r.TEXTURE_2D,n.texturePerObjectIdOffsets._texture),r.texSubImage2D(r.TEXTURE_2D,0,0,e,1,1,r.RGB,r.FLOAT,tf))}},{key:"drawColorOpaque",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&(this._updateBackfaceCull(e,t),t.withSAO&&this.model.saoEnabled?t.pbrEnabled&&this.model.pbrEnabled?this._dataTextureRenderers.colorQualityRendererWithSAO&&this._dataTextureRenderers.colorQualityRendererWithSAO.drawLayer(t,this,eo.COLOR_OPAQUE):this._dataTextureRenderers.colorRendererWithSAO&&this._dataTextureRenderers.colorRendererWithSAO.drawLayer(t,this,eo.COLOR_OPAQUE):t.pbrEnabled&&this.model.pbrEnabled?this._dataTextureRenderers.colorQualityRenderer&&this._dataTextureRenderers.colorQualityRenderer.drawLayer(t,this,eo.COLOR_OPAQUE):this._dataTextureRenderers.colorRenderer&&this._dataTextureRenderers.colorRenderer.drawLayer(t,this,eo.COLOR_OPAQUE))}},{key:"_updateBackfaceCull",value:function(e,t){var n=this.model.backfaces||e.sectioned;if(t.backfaces!==n){var r=t.gl;n?r.disable(r.CULL_FACE):r.enable(r.CULL_FACE),t.backfaces=n}}},{key:"drawColorTransparent",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numTransparentLayerPortions&&this._numXRayedLayerPortions!==this._numPortions&&(this._updateBackfaceCull(e,t),t.pbrEnabled&&this.model.pbrEnabled?this._dataTextureRenderers.colorQualityRenderer&&this._dataTextureRenderers.colorQualityRenderer.drawLayer(t,this,eo.COLOR_TRANSPARENT):this._dataTextureRenderers.colorRenderer&&this._dataTextureRenderers.colorRenderer.drawLayer(t,this,eo.COLOR_TRANSPARENT))}},{key:"drawDepth",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&(this._updateBackfaceCull(e,t),this._dataTextureRenderers.depthRenderer&&this._dataTextureRenderers.depthRenderer.drawLayer(t,this,eo.COLOR_OPAQUE))}},{key:"drawNormals",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&(this._updateBackfaceCull(e,t),this._dataTextureRenderers.normalsRenderer&&this._dataTextureRenderers.normalsRenderer.drawLayer(t,this,eo.COLOR_OPAQUE))}},{key:"drawSilhouetteXRayed",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&(this._updateBackfaceCull(e,t),this._dataTextureRenderers.silhouetteRenderer&&this._dataTextureRenderers.silhouetteRenderer.drawLayer(t,this,eo.SILHOUETTE_XRAYED))}},{key:"drawSilhouetteHighlighted",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&(this._updateBackfaceCull(e,t),this._dataTextureRenderers.silhouetteRenderer&&this._dataTextureRenderers.silhouetteRenderer.drawLayer(t,this,eo.SILHOUETTE_HIGHLIGHTED))}},{key:"drawSilhouetteSelected",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&(this._updateBackfaceCull(e,t),this._dataTextureRenderers.silhouetteRenderer&&this._dataTextureRenderers.silhouetteRenderer.drawLayer(t,this,eo.SILHOUETTE_SELECTED))}},{key:"drawEdgesColorOpaque",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numEdgesLayerPortions&&this._dataTextureRenderers.edgesColorRenderer&&this._dataTextureRenderers.edgesColorRenderer.drawLayer(t,this,eo.EDGES_COLOR_OPAQUE)}},{key:"drawEdgesColorTransparent",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numEdgesLayerPortions&&0!==this._numTransparentLayerPortions&&this._dataTextureRenderers.edgesColorRenderer&&this._dataTextureRenderers.edgesColorRenderer.drawLayer(t,this,eo.EDGES_COLOR_TRANSPARENT)}},{key:"drawEdgesHighlighted",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&this._dataTextureRenderers.edgesRenderer&&this._dataTextureRenderers.edgesRenderer.drawLayer(t,this,eo.EDGES_HIGHLIGHTED)}},{key:"drawEdgesSelected",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&this._dataTextureRenderers.edgesRenderer&&this._dataTextureRenderers.edgesRenderer.drawLayer(t,this,eo.EDGES_SELECTED)}},{key:"drawEdgesXRayed",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&this._dataTextureRenderers.edgesRenderer&&this._dataTextureRenderers.edgesRenderer.drawLayer(t,this,eo.EDGES_XRAYED)}},{key:"drawOcclusion",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._dataTextureRenderers.occlusionRenderer&&this._dataTextureRenderers.occlusionRenderer.drawLayer(t,this,eo.COLOR_OPAQUE))}},{key:"drawShadow",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._dataTextureRenderers.shadowRenderer&&this._dataTextureRenderers.shadowRenderer.drawLayer(t,this,eo.COLOR_OPAQUE))}},{key:"setPickMatrices",value:function(e,t){0!==this._numVisibleLayerPortions&&this._dataTextureState.texturePickCameraMatrices.updateViewMatrix(e,t)}},{key:"drawPickMesh",value:function(e,t){0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._dataTextureRenderers.pickMeshRenderer&&this._dataTextureRenderers.pickMeshRenderer.drawLayer(t,this,eo.PICK))}},{key:"drawPickDepths",value:function(e,t){0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._dataTextureRenderers.pickDepthRenderer&&this._dataTextureRenderers.pickDepthRenderer.drawLayer(t,this,eo.PICK))}},{key:"drawSnapInitDepthBuf",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._dataTextureRenderers.snapDepthBufInitRenderer&&this._dataTextureRenderers.snapDepthBufInitRenderer.drawLayer(t,this,eo.PICK))}},{key:"drawSnapDepths",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._dataTextureRenderers.vertexDepthRenderer&&this._dataTextureRenderers.vertexDepthRenderer.drawLayer(t,this,eo.PICK))}},{key:"drawPickNormals",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._dataTextureRenderers.pickNormalsRenderer&&this._dataTextureRenderers.pickNormalsRenderer.drawLayer(t,this,eo.PICK))}},{key:"destroy",value:function(){if(!this._destroyed){var e=this._state;e.metallicRoughnessBuf&&(e.metallicRoughnessBuf.destroy(),e.metallicRoughnessBuf=null),this.model.scene.off(this._onSceneRendering),e.destroy(),this._destroyed=!0}}}]),e}(),of=Z.vec3();Z.mat4();var lf=Z.vec3([1,1,1]),uf=Z.vec3([0,0,0]),cf=Z.vec3([0,0,0]),ff=Z.identityQuaternion();Z.identityMat4();var pf=new Uint8Array([255,255,255]),Af=function(e){I(n,ve);var t=m(n);function n(e){var r,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return b(this,n),(r=t.call(this,e,i))._dtxEnabled=r.scene.dtxEnabled&&!1!==i.dtxEnabled,r._enableVertexWelding=!1,r._enableIndexBucketing=!0,r._vboBatchingLayerScratchMemory=$s(),r._textureTranscoder=i.textureTranscoder||$u(r.scene.viewer),r._maxGeometryBatchSize=i.maxGeometryBatchSize,r._aabb=Z.collapseAABB3(),r._aabbDirty=!1,r._quantizationRanges={},r._vboInstancingLayers={},r._vboBatchingLayers={},r._dtxLayers={},r.layerList=[],r._entityList=[],r._geometries={},r._dtxBuckets={},r._textures={},r._textureSets={},r._meshes={},r._entities={},r._scheduledMeshes={},r.renderFlags=new $i,r.numGeometries=0,r.numPortions=0,r.numVisibleLayerPortions=0,r.numTransparentLayerPortions=0,r.numXRayedLayerPortions=0,r.numHighlightedLayerPortions=0,r.numSelectedLayerPortions=0,r.numEdgesLayerPortions=0,r.numPickableLayerPortions=0,r.numClippableLayerPortions=0,r.numCulledLayerPortions=0,r.numEntities=0,r._numTriangles=0,r._numLines=0,r._numPoints=0,r._edgeThreshold=i.edgeThreshold||10,r._origin=Z.vec3(i.origin||[0,0,0]),r._position=Z.vec3(i.position||[0,0,0]),r._rotation=Z.vec3(i.rotation||[0,0,0]),r._quaternion=Z.vec4(i.quaternion||[0,0,0,1]),i.rotation&&Z.eulerToQuaternion(r._rotation,"XYZ",r._quaternion),r._scale=Z.vec3(i.scale||[1,1,1]),r._sceneModelMatrix=Z.mat4(),Z.composeMat4(r._position,r._quaternion,r._scale,r._sceneModelMatrix),r._worldNormalMatrix=Z.mat4(),Z.inverseMat4(r._sceneModelMatrix,r._worldNormalMatrix),Z.transposeMat4(r._worldNormalMatrix),(i.matrix||i.position||i.rotation||i.scale||i.quaternion)&&(r._viewMatrix=Z.mat4(),r._viewNormalMatrix=Z.mat4(),r._viewMatrixDirty=!0,r._sceneModelMatrixNonIdentity=!0),r._opacity=1,r._colorize=[1,1,1],r._saoEnabled=!1!==i.saoEnabled,r._pbrEnabled=!1!==i.pbrEnabled,r._colorTextureEnabled=!1!==i.colorTextureEnabled,r._isModel=i.isModel,r._isModel&&r.scene._registerModel(g(r)),r._onCameraViewMatrix=r.scene.camera.on("matrix",(function(){r._viewMatrixDirty=!0})),r.scene.vfc.enabled&&(r._vfcManager=r.scene.vfc.getVFCManager(g(r))),r._createDefaultTextureSet(),r.visible=i.visible,r.culled=i.culled,r.pickable=i.pickable,r.clippable=i.clippable,r.collidable=i.collidable,r.castsShadow=i.castsShadow,r.receivesShadow=i.receivesShadow,r.xrayed=i.xrayed,r.highlighted=i.highlighted,r.selected=i.selected,r.edges=i.edges,r.colorize=i.colorize,r.opacity=i.opacity,r.backfaces=i.backfaces,r}return P(n,[{key:"_createDefaultTextureSet",value:function(){var e=new Vu({id:"defaultColorTexture",texture:new Fa({gl:this.scene.canvas.gl,preloadColor:[1,1,1,1]})}),t=new Vu({id:"defaultMetalRoughTexture",texture:new Fa({gl:this.scene.canvas.gl,preloadColor:[0,1,1,1]})}),n=new Vu({id:"defaultNormalsTexture",texture:new Fa({gl:this.scene.canvas.gl,preloadColor:[0,0,0,0]})}),r=new Vu({id:"defaultEmissiveTexture",texture:new Fa({gl:this.scene.canvas.gl,preloadColor:[0,0,0,1]})}),i=new Vu({id:"defaultOcclusionTexture",texture:new Fa({gl:this.scene.canvas.gl,preloadColor:[1,1,1,1]})});this._textures.defaultColorTexture=e,this._textures.defaultMetalRoughTexture=t,this._textures.defaultNormalsTexture=n,this._textures.defaultEmissiveTexture=r,this._textures.defaultOcclusionTexture=i,this._textureSets.defaultTextureSet=new ku({id:"defaultTextureSet",model:this,colorTexture:e,metallicRoughnessTexture:t,normalsTexture:n,emissiveTexture:r,occlusionTexture:i})}},{key:"isPerformanceModel",get:function(){return!0}},{key:"objects",get:function(){return this._entities}},{key:"origin",get:function(){return this._origin}},{key:"position",get:function(){return this._position}},{key:"rotation",get:function(){return this._rotation}},{key:"quaternion",get:function(){return this._quaternion}},{key:"scale",get:function(){return this._scale}},{key:"matrix",get:function(){return this._sceneModelMatrix}},{key:"worldMatrix",get:function(){return this._sceneModelMatrix}},{key:"worldNormalMatrix",get:function(){return this._worldNormalMatrix}},{key:"viewMatrix",get:function(){return this._viewMatrix?(this._viewMatrixDirty&&(Z.mulMat4(this.scene.camera.viewMatrix,this._sceneModelMatrix,this._viewMatrix),Z.inverseMat4(this._viewMatrix,this._viewNormalMatrix),Z.transposeMat4(this._viewNormalMatrix),this._viewMatrixDirty=!1),this._viewMatrix):this.scene.camera.viewMatrix}},{key:"viewNormalMatrix",get:function(){return this._viewNormalMatrix?(this._viewMatrixDirty&&(Z.mulMat4(this.scene.camera.viewMatrix,this._sceneModelMatrix,this._viewMatrix),Z.inverseMat4(this._viewMatrix,this._viewNormalMatrix),Z.transposeMat4(this._viewNormalMatrix),this._viewMatrixDirty=!1),this._viewNormalMatrix):this.scene.camera.viewNormalMatrix}},{key:"backfaces",get:function(){return this._backfaces},set:function(e){e=!!e,this._backfaces=e,this.glRedraw()}},{key:"entityList",get:function(){return this._entityList}},{key:"isEntity",get:function(){return!0}},{key:"isModel",get:function(){return this._isModel}},{key:"isObject",get:function(){return!1}},{key:"aabb",get:function(){return this._aabbDirty&&this._rebuildAABB(),this._aabb}},{key:"numTriangles",get:function(){return this._numTriangles}},{key:"numLines",get:function(){return this._numLines}},{key:"numPoints",get:function(){return this._numPoints}},{key:"visible",get:function(){return this.numVisibleLayerPortions>0},set:function(e){e=!1!==e,this._visible=e;for(var t=0,n=this._entityList.length;t<n;t++)this._entityList[t].visible=e;this.glRedraw()}},{key:"xrayed",get:function(){return this.numXRayedLayerPortions>0},set:function(e){e=!!e,this._xrayed=e;for(var t=0,n=this._entityList.length;t<n;t++)this._entityList[t].xrayed=e;this.glRedraw()}},{key:"highlighted",get:function(){return this.numHighlightedLayerPortions>0},set:function(e){e=!!e,this._highlighted=e;for(var t=0,n=this._entityList.length;t<n;t++)this._entityList[t].highlighted=e;this.glRedraw()}},{key:"selected",get:function(){return this.numSelectedLayerPortions>0},set:function(e){e=!!e,this._selected=e;for(var t=0,n=this._entityList.length;t<n;t++)this._entityList[t].selected=e;this.glRedraw()}},{key:"edges",get:function(){return this.numEdgesLayerPortions>0},set:function(e){e=!!e,this._edges=e;for(var t=0,n=this._entityList.length;t<n;t++)this._entityList[t].edges=e;this.glRedraw()}},{key:"culled",get:function(){return this._culled},set:function(e){e=!!e,this._culled=e;for(var t=0,n=this._entityList.length;t<n;t++)this._entityList[t].culled=e;this.glRedraw()}},{key:"clippable",get:function(){return this._clippable},set:function(e){e=!1!==e,this._clippable=e;for(var t=0,n=this._entityList.length;t<n;t++)this._entityList[t].clippable=e;this.glRedraw()}},{key:"collidable",get:function(){return this._collidable},set:function(e){e=!1!==e,this._collidable=e;for(var t=0,n=this._entityList.length;t<n;t++)this._entityList[t].collidable=e}},{key:"pickable",get:function(){return this.numPickableLayerPortions>0},set:function(e){e=!1!==e,this._pickable=e;for(var t=0,n=this._entityList.length;t<n;t++)this._entityList[t].pickable=e}},{key:"colorize",get:function(){return this._colorize},set:function(e){this._colorize=e;for(var t=0,n=this._entityList.length;t<n;t++)this._entityList[t].colorize=e}},{key:"opacity",get:function(){return this._opacity},set:function(e){this._opacity=e;for(var t=0,n=this._entityList.length;t<n;t++)this._entityList[t].opacity=e}},{key:"castsShadow",get:function(){return this._castsShadow},set:function(e){(e=!1!==e)!==this._castsShadow&&(this._castsShadow=e,this.glRedraw())}},{key:"receivesShadow",get:function(){return this._receivesShadow},set:function(e){(e=!1!==e)!==this._receivesShadow&&(this._receivesShadow=e,this.glRedraw())}},{key:"saoEnabled",get:function(){return this._saoEnabled}},{key:"pbrEnabled",get:function(){return this._pbrEnabled}},{key:"colorTextureEnabled",get:function(){return this._colorTextureEnabled}},{key:"isDrawable",get:function(){return!0}},{key:"isStateSortable",get:function(){return!1}},{key:"xrayMaterial",get:function(){return this.scene.xrayMaterial}},{key:"highlightMaterial",get:function(){return this.scene.highlightMaterial}},{key:"selectedMaterial",get:function(){return this.scene.selectedMaterial}},{key:"edgeMaterial",get:function(){return this.scene.edgeMaterial}},{key:"getPickViewMatrix",value:function(e){return this._viewMatrix?this._viewMatrix:e}},{key:"createQuantizationRange",value:function(e){void 0!==e.id&&null!==e.id?e.aabb?this.error("[createQuantizationRange] Config missing: aabb"):this._quantizationRanges[e.id]?this.error("[createQuantizationRange] QuantizationRange already created: "+e.id):this._quantizationRanges[e.id]={id:e.id,aabb:e.aabb,matrix:Mo(e.aabb,Z.mat4())}:this.error("[createQuantizationRange] Config missing: id")}},{key:"createGeometry",value:function(e){if(void 0!==e.id&&null!==e.id)if(this._geometries[e.id])this.error("[createGeometry] Geometry already created: "+e.id);else if(void 0!==e.primitive&&null!==e.primitive||(e.primitive="triangles"),"points"===e.primitive||"lines"===e.primitive||"triangles"===e.primitive||"solid"===e.primitive||"surface"===e.primitive){if(!e.positions&&!e.positionsCompressed&&!e.buckets)return this.error("[createGeometry] Param expected: `positions`, `positionsCompressed' or 'buckets"),null;if(e.positionsCompressed&&!e.positionsDecodeMatrix&&!e.positionsDecodeBoundary)return this.error("[createGeometry] Param expected: `positionsDecodeMatrix` or 'positionsDecodeBoundary' (required for `positionsCompressed')"),null;if(e.positionsDecodeMatrix&&e.positionsDecodeBoundary)return this.error("[createGeometry] Only one of these params expected: `positionsDecodeMatrix` or 'positionsDecodeBoundary' (required for `positionsCompressed')"),null;if(e.uvCompressed&&!e.uvDecodeMatrix)return this.error("[createGeometry] Param expected: `uvDecodeMatrix` (required for `uvCompressed')"),null;if(!e.buckets&&!e.indices&&"points"!==e.primitive)return this.error("[createGeometry] Param expected: indices (required for '".concat(e.primitive,"' primitive type)")),null;if(e.positionsDecodeBoundary&&(e.positionsDecodeMatrix=Mo(e.positionsDecodeBoundary,Z.mat4())),e.positions){var t=Z.collapseAABB3();e.positionsDecodeMatrix=Z.mat4(),Z.expandAABB3Points3(t,e.positions),e.positionsCompressed=xo(e.positions,t,e.positionsDecodeMatrix)}else e.positionsDecodeMatrix=new Float64Array(e.positionsDecodeMatrix),e.positionsCompressed=new Uint16Array(e.positionsCompressed);if(e.colorsCompressed&&e.colorsCompressed.length>0)e.colorsCompressed=new Uint8Array(e.colorsCompressed);else if(e.colors&&e.colors.length>0){for(var n=e.colors,r=new Uint8Array(n.length),i=0,a=n.length;i<a;i++)r[i]=255*n[i];e.colorsCompressed=r}if(e.buckets||e.edgeIndices||"triangles"!==e.primitive&&"solid"!==e.primitive&&"surface"!==e.primitive||(e.positions?e.edgeIndices=an(e.positions,e.indices,null,5):e.edgeIndices=an(e.positionsCompressed,e.indices,e.positionsDecodeMatrix,2)),e.buckets&&(this._dtxBuckets[e.id]=e.buckets),e.uv){var s=pn.getUVBounds(e.uv),o=pn.compressUVs(e.uv,s.min,s.max);e.uvCompressed=o.quantized,e.uvDecodeMatrix=o.decodeMatrix}else e.uvCompressed&&(e.uvCompressed=new Uint16Array(e.uvCompressed),e.uvDecodeMatrix=new Float64Array(e.uvDecodeMatrix));e.normals&&(e.normals=null),this._geometries[e.id]=e,this._numTriangles+=e.indices?Math.round(e.indices.length/3):0,this.numGeometries++}else this.error("[createGeometry] Unsupported value for 'primitive': '".concat(primitive,"' - supported values are 'points', 'lines', 'triangles', 'solid' and 'surface'. Defaulting to 'triangles'."));else this.error("[createGeometry] Config missing: id")}},{key:"createTexture",value:function(e){var t=this,n=e.id;if(null!=n)if(this._textures[n])this.error("[createTexture] Texture already created: "+n);else{if(!e.src&&!e.image&&!e.buffers)return this.error("[createTexture] Param expected: `src`, `image' or 'buffers'"),null;var r=e.minFilter||1008;1006!==r&&1007!==r&&1008!==r&&1005!==r&&1004!==r&&(this.error("[createTexture] Unsupported value for 'minFilter' - \n supported values are LinearFilter, LinearMipMapNearestFilter, NearestMipMapNearestFilter, \n NearestMipMapLinearFilter and LinearMipmapLinearFilter. Defaulting to LinearMipmapLinearFilter."),r=1008);var i=e.magFilter||1006;1006!==i&&1003!==i&&(this.error("[createTexture] Unsupported value for 'magFilter' - supported values are LinearFilter and NearestFilter. Defaulting to LinearFilter."),i=1006);var a=e.wrapS||1e3;1001!==a&&1002!==a&&1e3!==a&&(this.error("[createTexture] Unsupported value for 'wrapS' - supported values are ClampToEdgeWrapping, MirroredRepeatWrapping and RepeatWrapping. Defaulting to RepeatWrapping."),a=1e3);var s=e.wrapT||1e3;1001!==s&&1002!==s&&1e3!==s&&(this.error("[createTexture] Unsupported value for 'wrapT' - supported values are ClampToEdgeWrapping, MirroredRepeatWrapping and RepeatWrapping. Defaulting to RepeatWrapping."),s=1e3);var o=e.wrapR||1e3;1001!==o&&1002!==o&&1e3!==o&&(this.error("[createTexture] Unsupported value for 'wrapR' - supported values are ClampToEdgeWrapping, MirroredRepeatWrapping and RepeatWrapping. Defaulting to RepeatWrapping."),o=1e3);var l=e.encoding||3e3;3e3!==l&&3001!==l&&(this.error("[createTexture] Unsupported value for 'encoding' - supported values are LinearEncoding and sRGBEncoding. Defaulting to LinearEncoding."),l=3e3);var u=new Fa({gl:this.scene.canvas.gl,minFilter:r,magFilter:i,wrapS:a,wrapT:s,wrapR:o,encoding:l});if(e.preloadColor&&u.setPreloadColor(e.preloadColor),e.image){var c=e.image;c.crossOrigin="Anonymous",u.setImage(c,{minFilter:r,magFilter:i,wrapS:a,wrapT:s,wrapR:o,flipY:e.flipY,encoding:l})}else if(e.src){var f=e.src.split(".").pop();switch(f){case"jpeg":case"jpg":case"png":case"gif":var p=new Image;p.onload=function(){u.setImage(p,{minFilter:r,magFilter:i,wrapS:a,wrapT:s,wrapR:o,flipY:e.flipY,encoding:l}),t.glRedraw()},p.src=e.src;break;default:this._textureTranscoder?ae.loadArraybuffer(e.src,(function(e){e.byteLength?t._textureTranscoder.transcode([e],u).then((function(){t.glRedraw()})):t.error("[createTexture] Can't create texture from 'src': file data is zero length")}),(function(e){this.error("[createTexture] Can't create texture from 'src': ".concat(e))})):this.error("[createTexture] Can't create texture from 'src' - SceneModel needs to be configured with a TextureTranscoder for this file type ('".concat(f,"')"))}}else e.buffers&&(this._textureTranscoder?this._textureTranscoder.transcode(e.buffers,u).then((function(){t.glRedraw()})):this.error("[createTexture] Can't create texture from 'buffers' - SceneModel needs to be configured with a TextureTranscoder for this option"));this._textures[n]=new Vu({id:n,texture:u})}else this.error("[createTexture] Config missing: id")}},{key:"createTextureSet",value:function(e){var t=e.id;if(null!=t)if(this._textureSets[t])this.error("[createTextureSet] Texture set already created: ".concat(t));else{var n,r,i,a,s;if(void 0!==e.colorTextureId&&null!==e.colorTextureId){if(!(n=this._textures[e.colorTextureId]))return void this.error("[createTextureSet] Texture not found: ".concat(e.colorTextureId," - ensure that you create it first with createTexture()"))}else n=this._textures.defaultColorTexture;if(void 0!==e.metallicRoughnessTextureId&&null!==e.metallicRoughnessTextureId){if(!(r=this._textures[e.metallicRoughnessTextureId]))return void this.error("[createTextureSet] Texture not found: ".concat(e.metallicRoughnessTextureId," - ensure that you create it first with createTexture()"))}else r=this._textures.defaultMetalRoughTexture;if(void 0!==e.normalsTextureId&&null!==e.normalsTextureId){if(!(i=this._textures[e.normalsTextureId]))return void this.error("[createTextureSet] Texture not found: ".concat(e.normalsTextureId," - ensure that you create it first with createTexture()"))}else i=this._textures.defaultNormalsTexture;if(void 0!==e.emissiveTextureId&&null!==e.emissiveTextureId){if(!(a=this._textures[e.emissiveTextureId]))return void this.error("[createTextureSet] Texture not found: ".concat(e.emissiveTextureId," - ensure that you create it first with createTexture()"))}else a=this._textures.defaultEmissiveTexture;if(void 0!==e.occlusionTextureId&&null!==e.occlusionTextureId){if(!(s=this._textures[e.occlusionTextureId]))return void this.error("[createTextureSet] Texture not found: ".concat(e.occlusionTextureId," - ensure that you create it first with createTexture()"))}else s=this._textures.defaultOcclusionTexture;var o=new ku({id:t,model:this,colorTexture:n,metallicRoughnessTexture:r,normalsTexture:i,emissiveTexture:a,occlusionTexture:s});this._textureSets[t]=o}else this.error("[createTextureSet] Config missing: id")}},{key:"createMesh",value:function(e){if(void 0!==e.id&&null!==e.id)if(this._scheduledMeshes[e.id])this.error("[createMesh] SceneModel already has a mesh with this ID: ".concat(e.id));else{var t=!(void 0!==e.geometryId);if(e.sceneModelMatrix=this._sceneModelMatrixNonIdentity?this._sceneModelMatrix:null,t){var n=!!this._dtxEnabled;if(void 0!==e.primitive&&null!==e.primitive||(e.primitive="triangles"),"points"!==e.primitive&&"lines"!==e.primitive&&"triangles"!==e.primitive&&"solid"!==e.primitive&&"surface"!==e.primitive)return void this.error("Unsupported value for 'primitive': '".concat(primitive,"' ('geometryId' is absent) - supported values are 'points', 'lines', 'triangles', 'solid' and 'surface'."));if(!e.positions&&!e.positionsCompressed&&!e.buckets)return this.error("Param expected: 'positions', 'positionsCompressed' or `buckets` ('geometryId' is absent)"),null;if(e.positions&&(e.positionsDecodeMatrix||e.positionsDecodeBoundary))return this.error("Illegal params: 'positions' not expected with 'positionsDecodeMatrix'/'positionsDecodeBoundary' ('geometryId' is absent)"),null;if(e.positionsCompressed&&!e.positionsDecodeMatrix&&!e.positionsDecodeBoundary)return this.error("Param expected: 'positionsCompressed' should be accompanied by 'positionsDecodeMatrix'/'positionsDecodeBoundary' ('geometryId' is absent)"),null;if(e.uvCompressed&&!e.uvDecodeMatrix)return this.error("Param expected: 'uvCompressed' should be accompanied by `uvDecodeMatrix` ('geometryId' is absent)"),null;if(!e.buckets&&!e.indices&&"points"!==e.primitive)return this.error("Param expected: indices (required for '".concat(e.primitive,"' primitive type)")),null;if((e.matrix||e.position||e.rotation||e.scale)&&(e.positionsCompressed||e.positionsDecodeBoundary))return this.error("Unexpected params: 'matrix', 'rotation', 'scale', 'position' not allowed with 'positionsCompressed'"),null;if(e.origin=e.origin?Z.addVec3(this._origin,e.origin,Z.vec3()):this._origin,e.matrix)e.meshMatrix=e.matrix;else if(e.scale||e.rotation||e.position){var r=e.scale||lf,i=e.position||uf,a=e.rotation||cf;Z.eulerToQuaternion(a,"XYZ",ff),e.meshMatrix=Z.composeMat4(i,ff,r,Z.mat4())}if(e.positionsDecodeBoundary&&(e.positionsDecodeMatrix=Mo(e.positionsDecodeBoundary,Z.mat4())),n){if(e.type=2,e.color=e.color?new Uint8Array([Math.floor(255*e.color[0]),Math.floor(255*e.color[1]),Math.floor(255*e.color[2])]):pf,e.opacity=void 0!==e.opacity&&null!==e.opacity?Math.floor(255*e.opacity):255,e.positions){var s=Z.vec3(),o=[];me(e.positions,o,s)&&(e.positions=o,e.origin=Z.addVec3(e.origin,s,s))}if(e.positions){var l=Z.collapseAABB3();e.positionsDecodeMatrix=Z.mat4(),Z.expandAABB3Points3(l,e.positions),e.positionsCompressed=xo(e.positions,l,e.positionsDecodeMatrix)}e.buckets||e.edgeIndices||"triangles"!==e.primitive&&"solid"!==e.primitive&&"surface"!==e.primitive||(e.positions?e.edgeIndices=an(e.positions,e.indices,null,2):e.edgeIndices=an(e.positionsCompressed,e.indices,e.positionsDecodeMatrix,2)),e.buckets||(e.buckets=df(e,this._enableVertexWelding&&this._enableIndexBucketing))}else{if(e.type=1,e.color=e.color?new Uint8Array([Math.floor(255*e.color[0]),Math.floor(255*e.color[1]),Math.floor(255*e.color[2])]):[255,255,255],e.opacity=void 0!==e.opacity&&null!==e.opacity?Math.floor(255*e.opacity):255,e.metallic=void 0!==e.metallic&&null!==e.metallic?Math.floor(255*e.metallic):0,e.roughness=void 0!==e.roughness&&null!==e.roughness?Math.floor(255*e.roughness):255,e.positions){var u=[];me(e.positions,u,of)&&(e.positions=u,e.origin=Z.addVec3(e.origin,of,Z.vec3()))}if(e.buckets||e.edgeIndices||"triangles"!==e.primitive&&"solid"!==e.primitive&&"surface"!==e.primitive||(e.positions?e.edgeIndices=an(e.positions,e.indices,null,2):e.edgeIndices=an(e.positionsCompressed,e.indices,e.positionsDecodeMatrix,2)),e.textureSetId&&(e.textureSet=this._textureSets[e.textureSetId],!e.textureSet))return void this.error("[createMesh] Texture set not found: ".concat(e.textureSetId," - ensure that you create it first with createTextureSet()"))}}else{if(e.positions||e.positionsCompressed||e.indices||e.edgeIndices||e.normals||e.normalsCompressed||e.uv||e.uvCompressed||e.positionsDecodeMatrix)return void this.error("Mesh geometry parameters not expected when instancing a geometry (not expected: positions, positionsCompressed, indices, edgeIndices, normals, normalsCompressed, uv, uvCompressed, positionsDecodeMatrix)");if(e.geometry=this._geometries[e.geometryId],!e.geometry)return void this.error("[createMesh] Geometry not found: ".concat(e.geometryId," - ensure that you create it first with createGeometry()"));if(e.origin=e.origin?Z.addVec3(this._origin,e.origin,Z.vec3()):this._origin,e.positionsDecodeMatrix=e.geometry.positionsDecodeMatrix,e.matrix)e.meshMatrix=e.matrix.slice();else{var c=e.scale||lf,f=e.position||uf,p=e.rotation||cf;Z.eulerToQuaternion(p,"XYZ",ff),e.meshMatrix=Z.composeMat4(f,ff,c,Z.mat4())}if(!!this._dtxEnabled){e.type=2,e.color=e.color?new Uint8Array([Math.floor(255*e.color[0]),Math.floor(255*e.color[1]),Math.floor(255*e.color[2])]):pf,e.opacity=void 0!==e.opacity&&null!==e.opacity?Math.floor(255*e.opacity):255;var A=this._dtxBuckets[e.geometryId];A||(A=df(e.geometry,this._enableVertexWelding,this._enableIndexBucketing),this._dtxBuckets[e.geometryId]=A),e.buckets=A}else e.type=0,e.color=e.color?new Uint8Array([Math.floor(255*e.color[0]),Math.floor(255*e.color[1]),Math.floor(255*e.color[2])]):pf,e.opacity=void 0!==e.opacity&&null!==e.opacity?Math.floor(255*e.opacity):255,e.metallic=void 0!==e.metallic&&null!==e.metallic?Math.floor(255*e.metallic):0,e.roughness=void 0!==e.roughness&&null!==e.roughness?Math.floor(255*e.roughness):255,e.textureSetId&&(e.textureSet=this._textureSets[e.textureSetId]),function(e){if(e.obb=Z.OBB3(),e.positionsCompressed&&e.positionsCompressed.length>0){var t=Z.collapseAABB3();Z.expandAABB3Points3(t,e.positionsCompressed),pn.decompressAABB(t,e.positionsDecodeMatrix),Z.AABB3ToOBB3(t,e.obb)}else if(e.positions&&e.positions.length>0){var n=Z.collapseAABB3();Z.expandAABB3Points3(n,e.positions),Z.AABB3ToOBB3(n,e.obb)}}(e.geometry)}e.numPrimitives=this._getNumPrimitives(e),this._vfcManager&&!this._vfcManager.finalized?this._vfcManager.addMesh(e):this._createMesh(e)}else this.error("[createMesh] SceneModel.createMesh() config missing: id")}},{key:"_createMesh",value:function(e){var t=new qs(this,e.id,e.color,e.opacity);t.pickId=this.scene._renderer.getPickID(t);var n=t.pickId,r=n>>24&255,i=n>>16&255,a=n>>8&255,s=255&n;switch(e.pickColor=new Uint8Array([s,a,i,r]),e.worldAABB=Z.collapseAABB3(),e.aabb=e.worldAABB,e.solid="solid"===e.primitive,t.origin=Z.vec3(e.origin),e.type){case 2:t.layer=this._getDTXLayer(e);break;case 1:t.layer=this._getVBOBatchingLayer(e);break;case 0:t.layer=this._getVBOInstancingLayer(e)}t.portionId=t.layer.createPortion(e),t.aabb=e.worldAABB,t.numPrimitives=e.numPrimitives,Z.expandAABB3(this._aabb,t.aabb),this._meshes[e.id]=t}},{key:"_getNumPrimitives",value:function(e){var t=0;switch(e.geometry?e.geometry.primitive:e.primitive){case"triangles":case"solid":case"surface":switch(e.type){case 2:for(var n=0,r=e.buckets.length;n<r;n++)t+=e.buckets[n].indices.length;break;case 1:t+=e.indices.length;break;case 0:t+=e.geometry.indices.length}return Math.round(t/3);case"points":switch(e.type){case 2:for(var i=0,a=e.buckets.length;i<a;i++)t+=e.buckets[i].positionsCompressed.length;break;case 1:case 0:t+=e.positions?e.positions.length:e.positionsCompressed.length}return Math.round(t);case"lines":case"line-strip":switch(e.type){case 2:for(var s=0,o=e.buckets.length;s<o;s++)t+=e.buckets[s].indices.length;break;case 1:t+=e.indices.length;break;case 0:t+=e.geometry.indices.length}return Math.round(t/2)}return 0}},{key:"_getDTXLayer",value:function(e){var t=e.origin,n="".concat(Math.round(t[0]),".").concat(Math.round(t[1]),".").concat(Math.round(t[2])),r=this._dtxLayers[n];if(r){if(r.canCreatePortion(e))return r;r.finalize(),delete this._dtxLayers[n],r=null}return console.log("[SceneModel ".concat(this.id,"]: creating TrianglesDataTextureLayer")),r=new sf(this,{layerIndex:0,origin:t}),this._dtxLayers[n]=r,this.layerList.push(r),r}},{key:"_getVBOBatchingLayer",value:function(e){var t=this,n=e.origin,r=e.positionsDecodeMatrix||e.positionsDecodeBoundary?this._createHashStringFromMatrix(e.positionsDecodeMatrix||e.positionsDecodeBoundary):"-",i=e.textureSetId||"-",a="".concat(Math.round(n[0]),".").concat(Math.round(n[1]),".").concat(Math.round(n[2]),".").concat(e.primitive,".").concat(r,".").concat(i),s=this._vboBatchingLayers[a];if(s)return s;for(var o=e.textureSet;!s;){switch(e.primitive){case"triangles":case"solid":case"surface":console.log("[SceneModel ".concat(this.id,"]: creating TrianglesBatchingLayer")),s=new il({model:t,textureSet:o,layerIndex:0,scratchMemory:this._vboBatchingLayerScratchMemory,positionsDecodeMatrix:e.positionsDecodeMatrix,uvDecodeMatrix:e.uvDecodeMatrix,origin:n,maxGeometryBatchSize:this._maxGeometryBatchSize,solid:"solid"===e.primitive,autoNormals:!0});break;case"lines":console.log("[SceneModel ".concat(this.id,"]: creating LinesBatchingLayer")),s=new Zl({model:t,layerIndex:0,scratchMemory:this._vboBatchingLayerScratchMemory,positionsDecodeMatrix:e.positionsDecodeMatrix,uvDecodeMatrix:e.uvDecodeMatrix,origin:n,maxGeometryBatchSize:this._maxGeometryBatchSize});break;case"points":console.log("[SceneModel ".concat(this.id,"]: creating PointsBatchingLayer")),s=new bu({model:t,layerIndex:0,scratchMemory:this._vboBatchingLayerScratchMemory,positionsDecodeMatrix:e.positionsDecodeMatrix,uvDecodeMatrix:e.uvDecodeMatrix,origin:n,maxGeometryBatchSize:this._maxGeometryBatchSize})}var l=e.positionsCompressed?e.positionsCompressed.length:e.positions.length;("points"===e.primitive?s.canCreatePortion(l):s.canCreatePortion(l,e.indices.length))||(s.finalize(),delete this._vboBatchingLayers[a],s=null)}return this._vboBatchingLayers[a]=s,this.layerList.push(s),s}},{key:"_createHashStringFromMatrix",value:function(e){for(var t=e.join(""),n=0,r=0;r<t.length;r++){n=(n<<5)-n+t.charCodeAt(r),n|=0}return(n>>>0).toString(16)}},{key:"_getVBOInstancingLayer",value:function(e){var t=this,n=e.origin,r=e.textureSetId||"-",i=e.geometryId,a="".concat(Math.round(n[0]),".").concat(Math.round(n[1]),".").concat(Math.round(n[2]),".").concat(r,".").concat(i),s=this._vboInstancingLayers[a];if(s)return s;for(var o=e.textureSet,l=e.geometry;!s;)switch(l.primitive){case"triangles":case"surface":console.log("[SceneModel ".concat(this.id,"]: creating TrianglesInstancingLayer")),s=new Vl({model:t,textureSet:o,geometry:l,origin:n,layerIndex:0,solid:!1});break;case"solid":console.log("[SceneModel ".concat(this.id,"]: creating TrianglesInstancingLayer")),s=new Vl({model:t,textureSet:o,geometry:l,origin:n,layerIndex:0,solid:!0});break;case"lines":console.log("[SceneModel ".concat(this.id,"]: creating LinesInstancingLayer")),s=new uu({model:t,textureSet:o,geometry:l,origin:n,layerIndex:0});break;case"points":console.log("[SceneModel ".concat(this.id,"]: creating PointsInstancingLayer")),s=new Gu({model:t,textureSet:o,geometry:l,origin:n,layerIndex:0})}return this._vboInstancingLayers[a]=s,this.layerList.push(s),s}},{key:"createEntity",value:function(e){if(void 0===e.id?e.id=Z.createUUID():this.scene.components[e.id]&&(this.error("Scene already has a Component with this ID: ".concat(e.id," - will assign random ID")),e.id=Z.createUUID()),void 0!==e.meshIds){var t=0;if(this._visible&&!1!==e.visible&&(t|=Te),this._pickable&&!1!==e.pickable&&(t|=be),this._culled&&!1!==e.culled&&(t|=Ee),this._clippable&&!1!==e.clippable&&(t|=De),this._collidable&&!1!==e.collidable&&(t|=Pe),this._edges&&!1!==e.edges&&(t|=Be),this._xrayed&&!1!==e.xrayed&&(t|=Re),this._highlighted&&!1!==e.highlighted&&(t|=Ce),this._selected&&!1!==e.selected&&(t|=_e),e.flags=t,this._vfcManager&&!this._vfcManager.finalized){for(var n=0,r=e.meshIds.length;n<r;n++){var i=e.meshIds[n];if(this._scheduledMeshes[i])return void this.error("[createEntity] Mesh not found: ".concat(i))}this._vfcManager.addEntity(e)}else this._createEntity(e)}else this.error("Config missing: meshIds")}},{key:"_createEntity",value:function(e){for(var t=[],n=Z.collapseAABB3(),r=0,i=e.meshIds.length;r<i;r++){var a=e.meshIds[r],s=this._meshes[a];s?s.parent?this.error('Mesh with ID "'.concat(a,'" already belongs to object with ID "').concat(s.parent.id,'" - ignoring this mesh')):(Z.expandAABB3(n,s.aabb),t.push(s)):this.error('Mesh with this ID not found: "'.concat(a,'" - ignoring this mesh'))}var o=new Ne(this,e.isObject,e.id,t,e.flags,n,!0);this._entityList.push(o),this._entities[e.id]=o,this.numEntities++}},{key:"finalize",value:function(){if(!this.destroyed){this._vfcManager&&this._vfcManager.finalize((function(){}));for(var e=0,t=this.layerList.length;e<t;e++){this.layerList[e].finalize()}this._geometries={},this._dtxBuckets={},this._textures={},this._textureSets={},this._dtxLayers={},this._vboInstancingLayers={},this._vboBatchingLayers={};for(var n=0,r=this._entityList.length;n<r;n++){this._entityList[n]._finalize()}for(var i=0,a=this._entityList.length;i<a;i++){this._entityList[i]._finalize2()}this.layerList.sort((function(e,t){return e.sortId<t.sortId?-1:e.sortId>t.sortId?1:0}));for(var s=0,o=this.layerList.length;s<o;s++){this.layerList[s].layerIndex=s}this.glRedraw(),this.scene._aabbDirty=!0,this.scene.lod.enabled&&(this._lodManager=this.scene.lod.getLODManager(this))}}},{key:"_rebuildAABB",value:function(){Z.collapseAABB3(this._aabb);for(var e=0,t=this._entityList.length;e<t;e++){var n=this._entityList[e];Z.expandAABB3(this._aabb,n.aabb)}this._aabbDirty=!1}},{key:"stateSortCompare",value:function(e,t){}},{key:"rebuildRenderFlags",value:function(){this.renderFlags.reset(),this._updateRenderFlagsVisibleLayers(),this.renderFlags.numLayers>0&&0===this.renderFlags.numVisibleLayers?this.renderFlags.culled=!0:this._updateRenderFlags()}},{key:"_updateRenderFlagsVisibleLayers",value:function(){var e=this.renderFlags;e.numLayers=this.layerList.length,e.numVisibleLayers=0;for(var t=0,n=this.layerList.length;t<n;t++){var r=this.layerList[t];this._getActiveSectionPlanesForLayer(r)&&(e.visibleLayers[e.numVisibleLayers++]=t)}}},{key:"_getActiveSectionPlanesForLayer",value:function(e){var t=this.renderFlags,n=this.scene._sectionPlanesState.sectionPlanes,r=n.length,i=e.layerIndex*r;if(r>0)for(var a=0;a<r;a++){n[a].active?(t.sectionPlanesActivePerLayer[i+a]=!0,t.sectioned=!0):t.sectionPlanesActivePerLayer[i+a]=!1}return!0}},{key:"_updateRenderFlags",value:function(){if(0!==this.numVisibleLayerPortions&&this.numCulledLayerPortions!==this.numPortions){var e=this.renderFlags;if(e.colorOpaque=this.numTransparentLayerPortions<this.numPortions,this.numTransparentLayerPortions>0&&(e.colorTransparent=!0),this.numXRayedLayerPortions>0){var t=this.scene.xrayMaterial._state;t.fill&&(t.fillAlpha<1?e.xrayedSilhouetteTransparent=!0:e.xrayedSilhouetteOpaque=!0),t.edges&&(t.edgeAlpha<1?e.xrayedEdgesTransparent=!0:e.xrayedEdgesOpaque=!0)}if(this.numEdgesLayerPortions>0)this.scene.edgeMaterial._state.edges&&(e.edgesOpaque=this.numTransparentLayerPortions<this.numPortions,this.numTransparentLayerPortions>0&&(e.edgesTransparent=!0));if(this.numSelectedLayerPortions>0){var n=this.scene.selectedMaterial._state;n.fill&&(n.fillAlpha<1?e.selectedSilhouetteTransparent=!0:e.selectedSilhouetteOpaque=!0),n.edges&&(n.edgeAlpha<1?e.selectedEdgesTransparent=!0:e.selectedEdgesOpaque=!0)}if(this.numHighlightedLayerPortions>0){var r=this.scene.highlightMaterial._state;r.fill&&(r.fillAlpha<1?e.highlightedSilhouetteTransparent=!0:e.highlightedSilhouetteOpaque=!0),r.edges&&(r.edgeAlpha<1?e.highlightedEdgesTransparent=!0:e.highlightedEdgesOpaque=!0)}}}},{key:"drawColorOpaque",value:function(e){for(var t=this.renderFlags,n=0,r=t.visibleLayers.length;n<r;n++){var i=t.visibleLayers[n];this.layerList[i].drawColorOpaque(t,e)}}},{key:"drawColorTransparent",value:function(e){for(var t=this.renderFlags,n=0,r=t.visibleLayers.length;n<r;n++){var i=t.visibleLayers[n];this.layerList[i].drawColorTransparent(t,e)}}},{key:"drawDepth",value:function(e){for(var t=this.renderFlags,n=0,r=t.visibleLayers.length;n<r;n++){var i=t.visibleLayers[n];this.layerList[i].drawDepth(t,e)}}},{key:"drawNormals",value:function(e){for(var t=this.renderFlags,n=0,r=t.visibleLayers.length;n<r;n++){var i=t.visibleLayers[n];this.layerList[i].drawNormals(t,e)}}},{key:"drawSilhouetteXRayed",value:function(e){for(var t=this.renderFlags,n=0,r=t.visibleLayers.length;n<r;n++){var i=t.visibleLayers[n];this.layerList[i].drawSilhouetteXRayed(t,e)}}},{key:"drawSilhouetteHighlighted",value:function(e){for(var t=this.renderFlags,n=0,r=t.visibleLayers.length;n<r;n++){var i=t.visibleLayers[n];this.layerList[i].drawSilhouetteHighlighted(t,e)}}},{key:"drawSilhouetteSelected",value:function(e){for(var t=this.renderFlags,n=0,r=t.visibleLayers.length;n<r;n++){var i=t.visibleLayers[n];this.layerList[i].drawSilhouetteSelected(t,e)}}},{key:"drawEdgesColorOpaque",value:function(e){for(var t=this.renderFlags,n=0,r=t.visibleLayers.length;n<r;n++){var i=t.visibleLayers[n];this.layerList[i].drawEdgesColorOpaque(t,e)}}},{key:"drawEdgesColorTransparent",value:function(e){for(var t=this.renderFlags,n=0,r=t.visibleLayers.length;n<r;n++){var i=t.visibleLayers[n];this.layerList[i].drawEdgesColorTransparent(t,e)}}},{key:"drawEdgesXRayed",value:function(e){for(var t=this.renderFlags,n=0,r=t.visibleLayers.length;n<r;n++){var i=t.visibleLayers[n];this.layerList[i].drawEdgesXRayed(t,e)}}},{key:"drawEdgesHighlighted",value:function(e){for(var t=this.renderFlags,n=0,r=t.visibleLayers.length;n<r;n++){var i=t.visibleLayers[n];this.layerList[i].drawEdgesHighlighted(t,e)}}},{key:"drawEdgesSelected",value:function(e){for(var t=this.renderFlags,n=0,r=t.visibleLayers.length;n<r;n++){var i=t.visibleLayers[n];this.layerList[i].drawEdgesSelected(t,e)}}},{key:"drawOcclusion",value:function(e){if(0!==this.numVisibleLayerPortions)for(var t=this.renderFlags,n=0,r=t.visibleLayers.length;n<r;n++){var i=t.visibleLayers[n];this.layerList[i].drawOcclusion(t,e)}}},{key:"drawShadow",value:function(e){if(0!==this.numVisibleLayerPortions)for(var t=this.renderFlags,n=0,r=t.visibleLayers.length;n<r;n++){var i=t.visibleLayers[n];this.layerList[i].drawShadow(t,e)}}},{key:"setPickMatrices",value:function(e,t){if(0!==this._numVisibleLayerPortions)for(var n=this.renderFlags,r=0,i=n.visibleLayers.length;r<i;r++){var a=n.visibleLayers[r],s=this.layerList[a];s.setPickMatrices&&s.setPickMatrices(e,t)}}},{key:"drawPickMesh",value:function(e){if(0!==this.numVisibleLayerPortions)for(var t=this.renderFlags,n=0,r=t.visibleLayers.length;n<r;n++){var i=t.visibleLayers[n];this.layerList[i].drawPickMesh(t,e)}}},{key:"drawPickDepths",value:function(e){if(0!==this.numVisibleLayerPortions)for(var t=this.renderFlags,n=0,r=t.visibleLayers.length;n<r;n++){var i=t.visibleLayers[n];this.layerList[i].drawPickDepths(t,e)}}},{key:"drawPickNormals",value:function(e){if(0!==this.numVisibleLayerPortions)for(var t=this.renderFlags,n=0,r=t.visibleLayers.length;n<r;n++){var i=t.visibleLayers[n];this.layerList[i].drawPickNormals(t,e)}}},{key:"drawSnapInitDepthBuf",value:function(e){if(0!==this.numVisibleLayerPortions)for(var t=this.renderFlags,n=0,r=t.visibleLayers.length;n<r;n++){var i=t.visibleLayers[n],a=this.layerList[i];a.drawSnapInitDepthBuf&&(e.snapPickOrigin=[0,0,0],e.snapPickCoordinateScale=[1,1,1],e.snapPickLayerNumber++,a.drawSnapInitDepthBuf(t,e),e.snapPickLayerParams[e.snapPickLayerNumber]={origin:e.snapPickOrigin.slice(),coordinateScale:e.snapPickCoordinateScale.slice()})}}},{key:"drawSnapDepths",value:function(e){if(0!==this.numVisibleLayerPortions)for(var t=this.renderFlags,n=0,r=t.visibleLayers.length;n<r;n++){var i=t.visibleLayers[n],a=this.layerList[i];a.drawSnapDepths&&(e.snapPickOrigin=[0,0,0],e.snapPickCoordinateScale=[1,1,1],e.snapPickLayerNumber++,a.drawSnapDepths(t,e),e.snapPickLayerParams[e.snapPickLayerNumber]={origin:e.snapPickOrigin.slice(),coordinateScale:e.snapPickCoordinateScale.slice()})}}},{key:"destroy",value:function(){for(var e in this._vboBatchingLayers)this._vboBatchingLayers.hasOwnProperty(e)&&this._vboBatchingLayers[e].destroy();for(var t in this._vboBatchingLayers={},this._vboInstancingLayers)this._vboInstancingLayers.hasOwnProperty(t)&&this._vboInstancingLayers[t].destroy();this._vboInstancingLayers={},this.scene.camera.off(this._onCameraViewMatrix);for(var r=0,i=this.layerList.length;r<i;r++)this.layerList[r].destroy();this.layerList=[];for(var a=0,s=this._entityList.length;a<s;a++)this._entityList[a]._destroy();this._geometries={},this._dtxBuckets={},this._textures={},this._textureSets={},this._meshes={},this._entities={},this.scene._aabbDirty=!0,this._isModel&&this.scene._deregisterModel(this),0!==Zs&&0==--Zs&&Js._clear(),this._vfcManager&&this.scene.vfc.putVFCManager(this._vfcManager),this._lodManager&&this.scene.lod.putLODManager(this._lodManager),v(T(n.prototype),"destroy",this).call(this)}}]),n}();function df(e,t,n){var r,i,a,s;if(t){var o=p(rc({positionsCompressed:e.positionsCompressed,indices:e.indices,edgeIndices:e.edgeIndices}),3);r=o[0],i=o[1],a=o[2]}else r=e.positionsCompressed,i=e.indices,a=e.edgeIndices;n?s=function(e,t){var n=arguments.length>2&&void 0!==arguments[2]&&arguments[2],r=e.positionsCompressed||[],i=sc(e.indices||[],t),a=uc(e.edgeIndices||[]);function s(e,t){if(e>t){var n=e;e=t,t=n}function r(n,r){return n!==e?e-n:r!==t?t-r:0}for(var i=0,s=(a.length>>1)-1;i<=s;){var o=s+i>>1,l=r(a[2*o],a[2*o+1]);if(l>0)i=o+1;else{if(!(l<0))return o;s=o-1}}return-i-1}var o=new Int32Array(a.length/2);o.fill(0);var l=r.length/3;if(l>8*(1<<t))return[e];var u=new Int32Array(l);u.fill(-1);var c=[];function f(){u.fill(-1);var e={positionsCompressed:[],indices:[],edgeIndices:[],maxNumPositions:(1<<t)-t,numPositions:0,bucketNumber:c.length};return c.push(e),e}for(var p=f(),A=0,d=i.length;A<d;A+=3){var v=0,h=i[A],I=i[A+1],y=i[A+2];if(-1===u[h]&&v++,-1===u[I]&&v++,-1===u[y]&&v++,v+p.numPositions>p.maxNumPositions&&(p=f()),p.bucketNumber>8)return[e];-1===u[h]&&(u[h]=p.numPositions++,p.positionsCompressed.push(r[3*h]),p.positionsCompressed.push(r[3*h+1]),p.positionsCompressed.push(r[3*h+2])),-1===u[I]&&(u[I]=p.numPositions++,p.positionsCompressed.push(r[3*I]),p.positionsCompressed.push(r[3*I+1]),p.positionsCompressed.push(r[3*I+2])),-1===u[y]&&(u[y]=p.numPositions++,p.positionsCompressed.push(r[3*y]),p.positionsCompressed.push(r[3*y+1]),p.positionsCompressed.push(r[3*y+2])),p.indices.push(u[h]),p.indices.push(u[I]),p.indices.push(u[y]);var m=void 0;(m=s(h,I))>=0&&0===o[m]&&(o[m]=1,p.edgeIndices.push(u[a[2*m]]),p.edgeIndices.push(u[a[2*m+1]])),(m=s(h,y))>=0&&0===o[m]&&(o[m]=1,p.edgeIndices.push(u[a[2*m]]),p.edgeIndices.push(u[a[2*m+1]])),(m=s(I,y))>=0&&0===o[m]&&(o[m]=1,p.edgeIndices.push(u[a[2*m]]),p.edgeIndices.push(u[a[2*m+1]]))}var w=t/8*2,g=t/8,T=2*r.length+(i.length+a.length)*w,E=0;return r.length,c.forEach((function(e){E+=2*e.positionsCompressed.length+(e.indices.length+e.edgeIndices.length)*g,e.positionsCompressed.length})),E>T?[e]:(n&&cc(c,e),c)}({positionsCompressed:r,indices:i,edgeIndices:a},r.length/3>65536?16:8):s=[{positionsCompressed:r,indices:i,edgeIndices:a}];return s}var vf=function(e){I(n,Af);var t=m(n);function n(e){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return b(this,n),t.call(this,e,r)}return P(n)}(),hf=function(e){I(n,ve);var t=m(n);function n(e){var r,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return b(this,n),(r=t.call(this,e,i))._skyboxMesh=new ca(g(r),{geometry:new vn(g(r),{primitive:"triangles",positions:[1,1,1,-1,1,1,-1,-1,1,1,-1,1,1,1,1,1,-1,1,1,-1,-1,1,1,-1,1,1,1,1,1,-1,-1,1,-1,-1,1,1,-1,1,1,-1,1,-1,-1,-1,-1,-1,-1,1,-1,-1,-1,1,-1,-1,1,-1,1,-1,-1,1,1,-1,-1,-1,-1,-1,-1,1,-1,1,1,-1],uv:[.5,.6666,.25,.6666,.25,.3333,.5,.3333,.5,.6666,.5,.3333,.75,.3333,.75,.6666,.5,.6666,.5,1,.25,1,.25,.6666,.25,.6666,0,.6666,0,.3333,.25,.3333,.25,0,.5,0,.5,.3333,.25,.3333,.75,.3333,1,.3333,1,.6666,.75,.6666],indices:[0,1,2,0,2,3,4,5,6,4,6,7,8,9,10,8,10,11,12,13,14,12,14,15,16,17,18,16,18,19,20,21,22,20,22,23]}),background:!0,scale:[2e3,2e3,2e3],rotation:[0,-90,0],material:new wn(g(r),{ambient:[0,0,0],diffuse:[0,0,0],specular:[0,0,0],emissive:[1,1,1],emissiveMap:new ja(g(r),{src:i.src,flipY:!0,wrapS:"clampToEdge",wrapT:"clampToEdge",encoding:i.encoding||"sRGB"}),backfaces:!0}),visible:!1,pickable:!1,clippable:!1,collidable:!1}),r.size=i.size,r.active=i.active,r}return P(n,[{key:"size",get:function(){return this._size},set:function(e){this._size=e||1e3,this._skyboxMesh.scale=[this._size,this._size,this._size]}},{key:"active",get:function(){return this._skyboxMesh.visible},set:function(e){this._skyboxMesh.visible=e}}]),n}(),If=function(){function e(){b(this,e)}return P(e,[{key:"transcode",value:function(e,t){}},{key:"destroy",value:function(){}}]),e}(),yf=Z.vec4(),mf=Z.vec4(),wf=Z.vec3(),gf=Z.vec3(),Tf=Z.vec3(),Ef=Z.vec4(),bf=Z.vec4(),Df=Z.vec4(),Pf=function(){function e(t){b(this,e),this._scene=t}return P(e,[{key:"dollyToCanvasPos",value:function(e,t,n){var r=!1,i=this._scene.camera;if(e){var a=Z.subVec3(e,i.eye,wf);r=Z.lenVec3(a)<n}if("perspective"===i.projection){i.ortho.scale=i.ortho.scale-n;var s=this._unproject(t,Ef),o=Z.subVec3(s,i.eye,Df),l=Z.mulVec3Scalar(Z.normalizeVec3(o),-n,[]);if(i.eye=[i.eye[0]-l[0],i.eye[1]-l[1],i.eye[2]-l[2]],i.look=[i.look[0]-l[0],i.look[1]-l[1],i.look[2]-l[2]],e){var u=Z.subVec3(e,i.eye,wf),c=Z.lenVec3(u),f=Z.mulVec3Scalar(Z.normalizeVec3(Z.subVec3(i.look,i.eye,gf)),c);i.look=[i.eye[0]+f[0],i.eye[1]+f[1],i.eye[2]+f[2]]}}else if("ortho"===i.projection){var p=this._unproject(t,Ef);i.ortho.scale=i.ortho.scale-n,i.ortho._update();var A=this._unproject(t,bf),d=Z.subVec3(A,p,Df),v=Z.mulVec3Scalar(Z.normalizeVec3(Z.subVec3(i.look,i.eye,wf)),-n,gf),h=Z.addVec3(d,v,Tf);i.eye=[i.eye[0]-h[0],i.eye[1]-h[1],i.eye[2]-h[2]],i.look=[i.look[0]-h[0],i.look[1]-h[1],i.look[2]-h[2]]}return r}},{key:"_unproject",value:function(e,t){var n=this._scene.camera,r=n.project.transposedMatrix,i=r.subarray(8,12),a=r.subarray(12),s=[0,0,-1,1],o=Z.dotVec4(s,i)/Z.dotVec4(s,a);return n.project.unproject(e,o,yf,mf,t),t}},{key:"destroy",value:function(){}}]),e}(),Rf=Z.vec3(),Cf=Z.vec3(),_f=Z.vec3(),Bf=Z.vec4(),Of=Z.vec4(),Sf=Z.vec4(),Nf=function(){function e(t,n){var r=this;b(this,e),this._scene=t,this._configs=n,this._pivotWorldPos=Z.vec3(),this._cameraOffset=Z.vec3(),this._azimuth=0,this._polar=0,this._radius=0,this._pivotPosSet=!1,this._pivoting=!1,this._shown=!1,this._pivotViewPos=Z.vec4(),this._pivotProjPos=Z.vec4(),this._pivotCanvasPos=Z.vec2(),this._cameraDirty=!0,this._onViewMatrix=this._scene.camera.on("viewMatrix",(function(){r._cameraDirty=!0})),this._onProjMatrix=this._scene.camera.on("projMatrix",(function(){r._cameraDirty=!0})),this._onTick=this._scene.on("tick",(function(){r.updatePivotElement()}))}return P(e,[{key:"updatePivotElement",value:function(){var e=this._scene.camera,t=this._scene.canvas;if(this._pivoting&&this._cameraDirty){Z.transformPoint3(e.viewMatrix,this.getPivotPos(),this._pivotViewPos),this._pivotViewPos[3]=1,Z.transformPoint4(e.projMatrix,this._pivotViewPos,this._pivotProjPos);var n=t.boundary,r=n[2],i=n[3];this._pivotCanvasPos[0]=Math.floor((1+this._pivotProjPos[0]/this._pivotProjPos[3])*r/2),this._pivotCanvasPos[1]=Math.floor((1-this._pivotProjPos[1]/this._pivotProjPos[3])*i/2);var a=t._lastBoundingClientRect;if(!a||t._canvasSizeChanged){var s=t.canvas;a=t._lastBoundingClientRect=s.getBoundingClientRect()}this._pivotElement&&(this._pivotElement.style.left=Math.floor(a.left+this._pivotCanvasPos[0])-this._pivotElement.clientWidth/2+window.scrollX+"px",this._pivotElement.style.top=Math.floor(a.top+this._pivotCanvasPos[1])-this._pivotElement.clientHeight/2+window.scrollY+"px"),this._cameraDirty=!1}}},{key:"setPivotElement",value:function(e){this._pivotElement=e}},{key:"startPivot",value:function(){if(this._cameraLookingDownwards())return this._pivoting=!1,!1;var e=this._scene.camera,t=Z.lookAtMat4v(e.eye,e.look,e.worldUp);Z.transformPoint3(t,this.getPivotPos(),this._cameraOffset);var n=this.getPivotPos();this._cameraOffset[2]+=Z.distVec3(e.eye,n),t=Z.inverseMat4(t);var r=Z.transformVec3(t,this._cameraOffset),i=Z.vec3();if(Z.subVec3(e.eye,n,i),Z.addVec3(i,r),e.zUp){var a=i[1];i[1]=i[2],i[2]=a}this._radius=Z.lenVec3(i),this._polar=Math.acos(i[1]/this._radius),this._azimuth=Math.atan2(i[0],i[2]),this._pivoting=!0}},{key:"_cameraLookingDownwards",value:function(){var e=this._scene.camera,t=Z.normalizeVec3(Z.subVec3(e.look,e.eye,Rf)),n=Z.cross3Vec3(t,e.worldUp,Cf);return Z.sqLenVec3(n)<=1e-4}},{key:"getPivoting",value:function(){return this._pivoting}},{key:"setPivotPos",value:function(e){this._pivotWorldPos.set(e),this._pivotPosSet=!0}},{key:"setCanvasPivotPos",value:function(e){var t=this._scene.camera,n=Math.abs(Z.distVec3(this._scene.center,t.eye)),r=t.project.transposedMatrix,i=r.subarray(8,12),a=r.subarray(12),s=[0,0,-1,1],o=Z.dotVec4(s,i)/Z.dotVec4(s,a),l=Bf;t.project.unproject(e,o,Of,Sf,l);var u=Z.normalizeVec3(Z.subVec3(l,t.eye,Rf)),c=Z.addVec3(t.eye,Z.mulVec3Scalar(u,n,Cf),_f);this.setPivotPos(c)}},{key:"getPivotPos",value:function(){return this._pivotPosSet?this._pivotWorldPos:this._scene.camera.look}},{key:"continuePivot",value:function(e,t){if(this._pivoting&&(0!==e||0!==t)){var n=this._scene.camera,r=-e,i=-t;1===n.worldUp[2]&&(r=-r),this._azimuth+=.01*-r,this._polar+=.01*i,this._polar=Z.clamp(this._polar,.001,Math.PI-.001);var a=[this._radius*Math.sin(this._polar)*Math.sin(this._azimuth),this._radius*Math.cos(this._polar),this._radius*Math.sin(this._polar)*Math.cos(this._azimuth)];if(1===n.worldUp[2]){var s=a[1];a[1]=a[2],a[2]=s}var o=Z.lenVec3(Z.subVec3(n.look,n.eye,Z.vec3())),l=this.getPivotPos();Z.addVec3(a,l);var u=Z.lookAtMat4v(a,l,n.worldUp);u=Z.inverseMat4(u);var c=Z.transformVec3(u,this._cameraOffset);u[12]-=c[0],u[13]-=c[1],u[14]-=c[2];var f=[u[8],u[9],u[10]];n.eye=[u[12],u[13],u[14]],Z.subVec3(n.eye,Z.mulVec3Scalar(f,o),n.look),n.up=[u[4],u[5],u[6]],this.showPivot()}}},{key:"showPivot",value:function(){var e=this;this._shown||(null!==this._hideTimeout&&(window.clearTimeout(this._hideTimeout),this._hideTimeout=null),this._pivotElement&&(this.updatePivotElement(),this._pivotElement.style.visibility="visible",this._shown=!0,this._hideTimeout=window.setTimeout((function(){e.hidePivot()}),1e3)))}},{key:"hidePivot",value:function(){this._shown&&(null!==this._hideTimeout&&(window.clearTimeout(this._hideTimeout),this._hideTimeout=null),this._pivotElement&&(this._pivotElement.style.visibility="hidden"),this._shown=!1)}},{key:"endPivot",value:function(){this._pivoting=!1}},{key:"destroy",value:function(){this._scene.camera.off(this._onViewMatrix),this._scene.camera.off(this._onProjMatrix),this._scene.off(this._onTick)}}]),e}(),Lf=function(){function e(t,n){b(this,e),this._scene=t.scene,this._cameraControl=t,this._scene.canvas.canvas.oncontextmenu=function(e){e.preventDefault()},this._configs=n,this.schedulePickEntity=!1,this.schedulePickSurface=!1,this.scheduleSnapOrPick=!1,this.pickCursorPos=Z.vec2(),this.picked=!1,this.pickedSurface=!1,this.pickResult=null,this._lastPickedEntityId=null,this._needFireEvents=!1}return P(e,[{key:"update",value:function(){if(this._configs.pointerEnabled&&(this.schedulePickEntity||this.schedulePickSurface)){this.picked=!1,this.pickedSurface=!1,this.snappedOrPicked=!1,this.hoveredSnappedOrSurfaceOff=!1,this._needFireEvents=!1;var e=this._cameraControl.hasSubs("hoverSurface");if(this.scheduleSnapOrPick){var t=this._scene.snapPick({canvasPos:this.pickCursorPos,snapRadius:this._configs.snapRadius,snapMode:this._configs.snapMode});t&&t.snappedWorldPos?(this.snapPickResult=t,this.snappedOrPicked=!0,this._needFireEvents=!0):(this.schedulePickSurface=!0,this.snapPickResult=null)}if(this.schedulePickSurface&&this.pickResult&&this.pickResult.worldPos){var n=this.pickResult.canvasPos;if(n[0]===this.pickCursorPos[0]&&n[1]===this.pickCursorPos[1])return this.picked=!0,this.pickedSurface=!0,this._needFireEvents=e,this.schedulePickEntity=!1,this.schedulePickSurface=!1,this.scheduleSnapOrPick?this.snappedOrPicked=!0:this.hoveredSnappedOrSurfaceOff=!0,void(this.scheduleSnapOrPick=!1)}if(this.schedulePickEntity&&this.pickResult&&(this.pickResult.canvasPos||this.pickResult.snappedCanvasPos)){var r=this.pickResult.canvasPos||this.pickResult.snappedCanvasPos;if(r[0]===this.pickCursorPos[0]&&r[1]===this.pickCursorPos[1])return this.picked=!0,this.pickedSurface=!1,this._needFireEvents=!1,this.schedulePickEntity=!1,void(this.schedulePickSurface=!1)}this.schedulePickSurface||this.scheduleSnapOrPick&&!this.snapPickResult?(this.pickResult=this._scene.pick({pickSurface:!0,pickSurfaceNormal:!1,canvasPos:this.pickCursorPos}),this.pickResult?(this.picked=!0,this.scheduleSnapOrPick?this.snappedOrPicked=!0:this.pickedSurface=!0,this._needFireEvents=!0):this.scheduleSnapOrPick&&(this.hoveredSnappedOrSurfaceOff=!0,this._needFireEvents=!0)):(this.pickResult=this._scene.pick({canvasPos:this.pickCursorPos}),this.pickResult&&(this.picked=!0,this.pickedSurface=!1,this._needFireEvents=!0)),this.scheduleSnapOrPick=!1,this.schedulePickEntity=!1,this.schedulePickSurface=!1}}},{key:"fireEvents",value:function(){if(this._needFireEvents){if(this.hoveredSnappedOrSurfaceOff&&this._cameraControl.fire("hoverSnapOrSurfaceOff",{canvasPos:this.pickCursorPos},!0),this.snappedOrPicked)if(this.snapPickResult){var e=new it;e.worldPos=this.snapPickResult.snappedWorldPos,e.canvasPos=this.snapPickResult.snappedCanvasPos,this._cameraControl.fire("hoverSnapOrSurface",e,!0),this.snapPickResult=null}else this._cameraControl.fire("hoverSnapOrSurface",this.pickResult,!0);if(this.picked&&this.pickResult&&(this.pickResult.entity||this.pickResult.worldPos)){if(this.pickResult.entity){var t=this.pickResult.entity.id;this._lastPickedEntityId!==t&&(void 0!==this._lastPickedEntityId&&this._cameraControl.fire("hoverOut",{entity:this._scene.objects[this._lastPickedEntityId]},!0),this._cameraControl.fire("hoverEnter",this.pickResult,!0),this._lastPickedEntityId=t)}this._cameraControl.fire("hover",this.pickResult,!0),this.pickResult.worldPos&&(this.pickedSurface=!0,this._cameraControl.fire("hoverSurface",this.pickResult,!0))}else void 0!==this._lastPickedEntityId&&(this._cameraControl.fire("hoverOut",{entity:this._scene.objects[this._lastPickedEntityId]},!0),this._lastPickedEntityId=void 0),this._cameraControl.fire("hoverOff",{canvasPos:this.pickCursorPos},!0);this.pickResult=null,this._needFireEvents=!1}}},{key:"destroy",value:function(){}}]),e}(),xf=Z.vec2(),Mf=function(){function e(t,n,r,i,a){b(this,e),this._scene=t;var s,o,l,u=n.pickController,c=0,f=0,p=0,A=0,d=!1,v=Z.vec3(),h=!0,I=this._scene.canvas.canvas,y=[];function m(){var e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];I.style.cursor="move",w(),e&&g()}function w(){c=i.pointerCanvasPos[0],f=i.pointerCanvasPos[1],p=i.pointerCanvasPos[0],A=i.pointerCanvasPos[1]}function g(){u.pickCursorPos=i.pointerCanvasPos,u.schedulePickSurface=!0,u.update(),u.picked&&u.pickedSurface&&u.pickResult&&u.pickResult.worldPos?(d=!0,v.set(u.pickResult.worldPos)):d=!1}document.addEventListener("keydown",this._documentKeyDownHandler=function(e){if(r.active&&r.pointerEnabled&&t.input.keyboardEnabled){var n=e.keyCode;y[n]=!0}}),document.addEventListener("keyup",this._documentKeyUpHandler=function(e){if(r.active&&r.pointerEnabled&&t.input.keyboardEnabled){var n=e.keyCode;y[n]=!1}}),I.addEventListener("mousedown",this._mouseDownHandler=function(e){if(r.active&&r.pointerEnabled)switch(e.which){case 1:y[t.input.KEY_SHIFT]||r.planView?(s=!0,m()):(s=!0,m(!1));break;case 2:o=!0,m();break;case 3:l=!0,r.panRightClick&&m()}}),document.addEventListener("mousemove",this._documentMouseMoveHandler=function(){if(r.active&&r.pointerEnabled&&(s||o||l)){var e=t.canvas.boundary,n=e[2],u=e[3],p=i.pointerCanvasPos[0],A=i.pointerCanvasPos[1];if(y[t.input.KEY_SHIFT]||r.planView||!r.panRightClick&&o||r.panRightClick&&l){var h=p-c,I=A-f,m=t.camera;if("perspective"===m.projection){var w=Math.abs(d?Z.lenVec3(Z.subVec3(v,t.camera.eye,[])):t.camera.eyeLookDist)*Math.tan(m.perspective.fov/2*Math.PI/180);a.panDeltaX+=1.5*h*w/u,a.panDeltaY+=1.5*I*w/u}else a.panDeltaX+=.5*m.ortho.scale*(h/u),a.panDeltaY+=.5*m.ortho.scale*(I/u)}else!s||o||l||r.planView||(r.firstPerson?(a.rotateDeltaY-=(p-c)/n*r.dragRotationRate/2,a.rotateDeltaX+=(A-f)/u*(r.dragRotationRate/4)):(a.rotateDeltaY-=(p-c)/n*(1.5*r.dragRotationRate),a.rotateDeltaX+=(A-f)/u*(1.5*r.dragRotationRate)));c=p,f=A}}),I.addEventListener("mousemove",this._canvasMouseMoveHandler=function(e){r.active&&r.pointerEnabled&&i.mouseover&&(h=!0)}),document.addEventListener("mouseup",this._documentMouseUpHandler=function(e){if(r.active&&r.pointerEnabled)switch(e.which){case 1:case 2:case 3:s=!1,o=!1,l=!1}}),I.addEventListener("mouseup",this._mouseUpHandler=function(e){if(r.active&&r.pointerEnabled){if(3===e.which){!function(e,t){if(e){for(var n=e.target,r=0,i=0,a=0,s=0;n.offsetParent;)r+=n.offsetLeft,i+=n.offsetTop,a+=n.scrollLeft,s+=n.scrollTop,n=n.offsetParent;t[0]=e.pageX+a-r,t[1]=e.pageY+s-i}else e=window.event,t[0]=e.x,t[1]=e.y}(e,xf);var t=xf[0],i=xf[1];Math.abs(t-p)<3&&Math.abs(i-A)<3&&n.cameraControl.fire("rightClick",{pagePos:[Math.round(e.pageX),Math.round(e.pageY)],canvasPos:xf,event:e},!0)}I.style.removeProperty("cursor")}}),I.addEventListener("mouseenter",this._mouseEnterHandler=function(){r.active&&r.pointerEnabled});var T=1/60,E=null;I.addEventListener("wheel",this._mouseWheelHandler=function(e){if(r.active&&r.pointerEnabled){var t=performance.now()/1e3,n=null!==E?t-E:0;E=t,n>.05&&(n=.05),n<T&&(n=T);var s=Math.max(-1,Math.min(1,40*-e.deltaY));if(0!==s){var o=s/Math.abs(s);a.dollyDelta+=-o*n*r.mouseWheelDollyRate,h&&(i.followPointerDirty=!0,h=!1)}}},{passive:!0})}return P(e,[{key:"reset",value:function(){}},{key:"destroy",value:function(){var e=this._scene.canvas.canvas;document.removeEventListener("keydown",this._documentKeyDownHandler),document.removeEventListener("keyup",this._documentKeyUpHandler),e.removeEventListener("mousedown",this._mouseDownHandler),document.removeEventListener("mousemove",this._documentMouseMoveHandler),e.removeEventListener("mousemove",this._canvasMouseMoveHandler),document.removeEventListener("mouseup",this._documentMouseUpHandler),e.removeEventListener("mouseup",this._mouseUpHandler),e.removeEventListener("mouseenter",this._mouseEnterHandler),e.removeEventListener("wheel",this._mouseWheelHandler)}}]),e}(),Ff=Z.vec3(),Hf=Z.vec3(),Uf=Z.vec3(),Gf=Z.vec3(),kf=Z.vec3(),Vf={eye:Z.vec3(),look:Z.vec3(),up:Z.vec3()},jf=function(){function e(t,n,r,i){b(this,e),this._scene=t;var a=n.cameraControl,s=t.camera;this._onSceneKeyDown=t.input.on("keydown",(function(){if(r.active&&r.pointerEnabled&&t.input.keyboardEnabled&&i.mouseover){var e=a._isKeyDownForAction(a.AXIS_VIEW_RIGHT),o=a._isKeyDownForAction(a.AXIS_VIEW_BACK),l=a._isKeyDownForAction(a.AXIS_VIEW_LEFT),u=a._isKeyDownForAction(a.AXIS_VIEW_FRONT),c=a._isKeyDownForAction(a.AXIS_VIEW_TOP),f=a._isKeyDownForAction(a.AXIS_VIEW_BOTTOM);if(e||o||l||u||c||f){var p=t.aabb,A=Z.getAABB3Diag(p);Z.getAABB3Center(p,Ff);var d=Math.abs(A/Math.tan(n.cameraFlight.fitFOV*Z.DEGTORAD)),v=1.1*A;Vf.orthoScale=v,e?(Vf.eye.set(Z.addVec3(Ff,Z.mulVec3Scalar(s.worldRight,d,Hf),kf)),Vf.look.set(Ff),Vf.up.set(s.worldUp)):o?(Vf.eye.set(Z.addVec3(Ff,Z.mulVec3Scalar(s.worldForward,d,Hf),kf)),Vf.look.set(Ff),Vf.up.set(s.worldUp)):l?(Vf.eye.set(Z.addVec3(Ff,Z.mulVec3Scalar(s.worldRight,-d,Hf),kf)),Vf.look.set(Ff),Vf.up.set(s.worldUp)):u?(Vf.eye.set(Z.addVec3(Ff,Z.mulVec3Scalar(s.worldForward,-d,Hf),kf)),Vf.look.set(Ff),Vf.up.set(s.worldUp)):c?(Vf.eye.set(Z.addVec3(Ff,Z.mulVec3Scalar(s.worldUp,d,Hf),kf)),Vf.look.set(Ff),Vf.up.set(Z.normalizeVec3(Z.mulVec3Scalar(s.worldForward,1,Uf),Gf))):f&&(Vf.eye.set(Z.addVec3(Ff,Z.mulVec3Scalar(s.worldUp,-d,Hf),kf)),Vf.look.set(Ff),Vf.up.set(Z.normalizeVec3(Z.mulVec3Scalar(s.worldForward,-1,Uf)))),!r.firstPerson&&r.followPointer&&n.pivotController.setPivotPos(Ff),n.cameraFlight.duration>0?n.cameraFlight.flyTo(Vf,(function(){n.pivotController.getPivoting()&&r.followPointer&&n.pivotController.showPivot()})):(n.cameraFlight.jumpTo(Vf),n.pivotController.getPivoting()&&r.followPointer&&n.pivotController.showPivot())}}}))}return P(e,[{key:"reset",value:function(){}},{key:"destroy",value:function(){this._scene.input.off(this._onSceneKeyDown)}}]),e}(),Qf=function(){function e(t,n,r,i,a){var s=this;b(this,e),this._scene=t;var o=n.pickController,l=n.pivotController,u=n.cameraControl;this._clicks=0,this._timeout=null,this._lastPickedEntityId=null;var c=!1,f=!1,p=this._scene.canvas.canvas,A=function(e){var r;e&&e.worldPos&&(r=e.worldPos);var i=e&&e.entity?e.entity.aabb:t.aabb;if(r){var a=t.camera;Z.subVec3(a.eye,a.look,[]),n.cameraFlight.flyTo({aabb:i})}else n.cameraFlight.flyTo({aabb:i})};p.addEventListener("mousemove",this._canvasMouseMoveHandler=function(e){if(r.active&&r.pointerEnabled&&!c&&!f){var n=u.hasSubs("hover"),a=u.hasSubs("hoverOut"),l=u.hasSubs("hoverOff"),p=u.hasSubs("hoverSurface"),A=u.hasSubs("hoverSnapOrSurface");if(n||a||l||p||A)if(o.pickCursorPos=i.pointerCanvasPos,o.schedulePickEntity=!0,o.schedulePickSurface=p,o.scheduleSnapOrPick=A,o.update(),o.pickResult){if(o.pickResult.entity){var d=o.pickResult.entity.id;s._lastPickedEntityId!==d&&(void 0!==s._lastPickedEntityId&&u.fire("hoverOut",{entity:t.objects[s._lastPickedEntityId]},!0),u.fire("hoverEnter",o.pickResult,!0),s._lastPickedEntityId=d)}u.fire("hover",o.pickResult,!0),(o.pickResult.worldPos||o.pickResult.snappedWorldPos)&&u.fire("hoverSurface",o.pickResult,!0)}else void 0!==s._lastPickedEntityId&&(u.fire("hoverOut",{entity:t.objects[s._lastPickedEntityId]},!0),s._lastPickedEntityId=void 0),u.fire("hoverOff",{canvasPos:o.pickCursorPos},!0)}}),p.addEventListener("mousedown",this._canvasMouseDownHandler=function(e){if(1===e.which&&(c=!0),3===e.which&&(f=!0),1===e.which&&r.active&&r.pointerEnabled&&(i.mouseDownClientX=e.clientX,i.mouseDownClientY=e.clientY,i.mouseDownCursorX=i.pointerCanvasPos[0],i.mouseDownCursorY=i.pointerCanvasPos[1],!r.firstPerson&&r.followPointer&&(o.pickCursorPos=i.pointerCanvasPos,o.schedulePickSurface=!0,o.update(),1===e.which))){var n=o.pickResult;n&&n.worldPos?(l.setPivotPos(n.worldPos),l.startPivot()):(r.smartPivot?l.setCanvasPivotPos(i.pointerCanvasPos):l.setPivotPos(t.camera.look),l.startPivot())}}),document.addEventListener("mouseup",this._documentMouseUpHandler=function(e){1===e.which&&(c=!1),3===e.which&&(f=!1)}),p.addEventListener("mouseup",this._canvasMouseUpHandler=function(e){if(r.active&&r.pointerEnabled&&(1===e.which&&(l.hidePivot(),!(Math.abs(e.clientX-i.mouseDownClientX)>3||Math.abs(e.clientY-i.mouseDownClientY)>3)))){var a=u.hasSubs("picked"),c=u.hasSubs("pickedNothing"),f=u.hasSubs("pickedSurface"),p=u.hasSubs("doublePicked"),d=u.hasSubs("doublePickedSurface"),v=u.hasSubs("doublePickedNothing");if(!(r.doublePickFlyTo||p||d||v))return(a||c||f)&&(o.pickCursorPos=i.pointerCanvasPos,o.schedulePickEntity=!0,o.schedulePickSurface=f,o.update(),o.pickResult?(u.fire("picked",o.pickResult,!0),o.pickedSurface&&u.fire("pickedSurface",o.pickResult,!0)):u.fire("pickedNothing",{canvasPos:i.pointerCanvasPos},!0)),void(s._clicks=0);if(s._clicks++,1===s._clicks){o.pickCursorPos=i.pointerCanvasPos,o.schedulePickEntity=r.doublePickFlyTo,o.schedulePickSurface=f,o.update();var h=o.pickResult,I=o.pickedSurface;s._timeout=setTimeout((function(){h?(u.fire("picked",h,!0),I&&(u.fire("pickedSurface",h,!0),!r.firstPerson&&r.followPointer&&(n.pivotController.setPivotPos(h.worldPos),n.pivotController.startPivot()&&n.pivotController.showPivot()))):u.fire("pickedNothing",{canvasPos:i.pointerCanvasPos},!0),s._clicks=0}),r.doubleClickTimeFrame)}else{if(null!==s._timeout&&(window.clearTimeout(s._timeout),s._timeout=null),o.pickCursorPos=i.pointerCanvasPos,o.schedulePickEntity=r.doublePickFlyTo||p||d,o.schedulePickSurface=o.schedulePickEntity&&d,o.update(),o.pickResult){if(u.fire("doublePicked",o.pickResult,!0),o.pickedSurface&&u.fire("doublePickedSurface",o.pickResult,!0),r.doublePickFlyTo&&(A(o.pickResult),!r.firstPerson&&r.followPointer)){var y=o.pickResult.entity.aabb,m=Z.getAABB3Center(y);n.pivotController.setPivotPos(m),n.pivotController.startPivot()&&n.pivotController.showPivot()}}else if(u.fire("doublePickedNothing",{canvasPos:i.pointerCanvasPos},!0),r.doublePickFlyTo&&(A(),!r.firstPerson&&r.followPointer)){var w=t.aabb,g=Z.getAABB3Center(w);n.pivotController.setPivotPos(g),n.pivotController.startPivot()&&n.pivotController.showPivot()}s._clicks=0}}},!1)}return P(e,[{key:"reset",value:function(){this._clicks=0,this._lastPickedEntityId=null,this._timeout&&(window.clearTimeout(this._timeout),this._timeout=null)}},{key:"destroy",value:function(){var e=this._scene.canvas.canvas;e.removeEventListener("mousemove",this._canvasMouseMoveHandler),e.removeEventListener("mousedown",this._canvasMouseDownHandler),document.removeEventListener("mouseup",this._documentMouseUpHandler),e.removeEventListener("mouseup",this._canvasMouseUpHandler),this._timeout&&(window.clearTimeout(this._timeout),this._timeout=null)}}]),e}(),Wf=function(){function e(t,n,r,i,a){b(this,e),this._scene=t;var s=t.input,o=[],l=t.canvas.canvas,u=!0;this._onSceneMouseMove=s.on("mousemove",(function(){u=!0})),this._onSceneKeyDown=s.on("keydown",(function(e){r.active&&r.pointerEnabled&&t.input.keyboardEnabled&&i.mouseover&&(o[e]=!0,e===s.KEY_SHIFT&&(l.style.cursor="move"))})),this._onSceneKeyUp=s.on("keyup",(function(e){r.active&&r.pointerEnabled&&t.input.keyboardEnabled&&(o[e]=!1,e===s.KEY_SHIFT&&(l.style.cursor=null))})),this._onTick=t.on("tick",(function(e){if(r.active&&r.pointerEnabled&&t.input.keyboardEnabled&&i.mouseover){var l=n.cameraControl,c=e.deltaTime/1e3;if(!r.planView){var f=l._isKeyDownForAction(l.ROTATE_Y_POS,o),p=l._isKeyDownForAction(l.ROTATE_Y_NEG,o),A=l._isKeyDownForAction(l.ROTATE_X_POS,o),d=l._isKeyDownForAction(l.ROTATE_X_NEG,o),v=c*r.keyboardRotationRate;(f||p||A||d)&&(!r.firstPerson&&r.followPointer&&n.pivotController.startPivot(),f?a.rotateDeltaY+=v:p&&(a.rotateDeltaY-=v),A?a.rotateDeltaX+=v:d&&(a.rotateDeltaX-=v),!r.firstPerson&&r.followPointer&&n.pivotController.startPivot())}if(!o[s.KEY_CTRL]&&!o[s.KEY_ALT]){var h=l._isKeyDownForAction(l.DOLLY_BACKWARDS,o),I=l._isKeyDownForAction(l.DOLLY_FORWARDS,o);if(h||I){var y=c*r.keyboardDollyRate;!r.firstPerson&&r.followPointer&&n.pivotController.startPivot(),I?a.dollyDelta-=y:h&&(a.dollyDelta+=y),u&&(i.followPointerDirty=!0,u=!1)}}var m=l._isKeyDownForAction(l.PAN_FORWARDS,o),w=l._isKeyDownForAction(l.PAN_BACKWARDS,o),g=l._isKeyDownForAction(l.PAN_LEFT,o),T=l._isKeyDownForAction(l.PAN_RIGHT,o),E=l._isKeyDownForAction(l.PAN_UP,o),b=l._isKeyDownForAction(l.PAN_DOWN,o),D=(o[s.KEY_ALT]?.3:1)*c*r.keyboardPanRate;(m||w||g||T||E||b)&&(!r.firstPerson&&r.followPointer&&n.pivotController.startPivot(),b?a.panDeltaY+=D:E&&(a.panDeltaY+=-D),T?a.panDeltaX+=-D:g&&(a.panDeltaX+=D),w?a.panDeltaZ+=D:m&&(a.panDeltaZ+=-D))}}))}return P(e,[{key:"reset",value:function(){}},{key:"destroy",value:function(){this._scene.off(this._onTick),this._scene.input.off(this._onSceneMouseMove),this._scene.input.off(this._onSceneKeyDown),this._scene.input.off(this._onSceneKeyUp)}}]),e}(),zf=Z.vec3(),Kf=function(){function e(t,n,r,i,a){b(this,e),this._scene=t;var s=t.camera,o=n.pickController,l=n.pivotController,u=n.panController,c=1,f=1,p=null;this._onTick=t.on("tick",(function(){if(r.active&&r.pointerEnabled){var e="default";if(Math.abs(a.dollyDelta)<.001&&(a.dollyDelta=0),Math.abs(a.rotateDeltaX)<.001&&(a.rotateDeltaX=0),Math.abs(a.rotateDeltaY)<.001&&(a.rotateDeltaY=0),0===a.rotateDeltaX&&0===a.rotateDeltaY||(a.dollyDelta=0),r.followPointer&&--c<=0&&(c=1,0!==a.dollyDelta)){if(0===a.rotateDeltaY&&0===a.rotateDeltaX&&r.followPointer&&i.followPointerDirty&&(o.pickCursorPos=i.pointerCanvasPos,o.schedulePickSurface=!0,o.update(),o.pickResult&&o.pickResult.worldPos?p=o.pickResult.worldPos:(f=1,p=null),i.followPointerDirty=!1),p){var n=Math.abs(Z.lenVec3(Z.subVec3(p,t.camera.eye,zf)));f=n/r.dollyProximityThreshold}f<r.dollyMinSpeed&&(f=r.dollyMinSpeed)}var A=a.dollyDelta*f;if(0===a.rotateDeltaY&&0===a.rotateDeltaX||(!r.firstPerson&&r.followPointer&&l.getPivoting()?(l.continuePivot(a.rotateDeltaY,a.rotateDeltaX),l.showPivot()):(0!==a.rotateDeltaX&&(r.firstPerson?s.pitch(-a.rotateDeltaX):s.orbitPitch(a.rotateDeltaX)),0!==a.rotateDeltaY&&(r.firstPerson?s.yaw(a.rotateDeltaY):s.orbitYaw(a.rotateDeltaY))),a.rotateDeltaX*=r.rotationInertia,a.rotateDeltaY*=r.rotationInertia,e="grabbing"),Math.abs(a.panDeltaX)<.001&&(a.panDeltaX=0),Math.abs(a.panDeltaY)<.001&&(a.panDeltaY=0),Math.abs(a.panDeltaZ)<.001&&(a.panDeltaZ=0),0!==a.panDeltaX||0!==a.panDeltaY||0!==a.panDeltaZ){var d,v,h=Z.vec3();if(h[0]=a.panDeltaX,h[1]=a.panDeltaY,h[2]=a.panDeltaZ,r.constrainVertical){s.xUp?(d=s.eye[0],v=s.look[0]):s.yUp?(d=s.eye[1],v=s.look[1]):s.zUp&&(d=s.eye[2],v=s.look[2]),s.pan(h);var I=s.eye,y=s.look;s.xUp?(I[0]=d,y[0]=v):s.yUp?(I[1]=d,y[1]=v):s.zUp&&(I[2]=d,y[2]=v),s.eye=I,s.look=y}else s.pan(h);e="grabbing"}if(a.panDeltaX*=r.panInertia,a.panDeltaY*=r.panInertia,a.panDeltaZ*=r.panInertia,0!==A){if(e=A<0?"zoom-in":"zoom-out",r.firstPerson){var m,w;if(r.constrainVertical&&(s.xUp?(m=s.eye[0],w=s.look[0]):s.yUp?(m=s.eye[1],w=s.look[1]):s.zUp&&(m=s.eye[2],w=s.look[2])),r.followPointer)u.dollyToCanvasPos(p,i.pointerCanvasPos,-A)&&(i.followPointerDirty=!0);else s.pan([0,0,A]),s.ortho.scale=s.ortho.scale-A;if(r.constrainVertical){var g=s.eye,T=s.look;s.xUp?(g[0]=m,T[0]=w):s.yUp?(g[1]=m,T[1]=w):s.zUp&&(g[2]=m,T[2]=w),s.eye=g,s.look=T}}else if(r.planView){if(r.followPointer)u.dollyToCanvasPos(p,i.pointerCanvasPos,-A)&&(i.followPointerDirty=!0);else s.ortho.scale=s.ortho.scale+A,s.zoom(A)}else{if(r.followPointer)u.dollyToCanvasPos(p,i.pointerCanvasPos,-A)&&(i.followPointerDirty=!0);else s.ortho.scale=s.ortho.scale+A,s.zoom(A)}a.dollyDelta*=r.dollyInertia}o.fireEvents(),document.body.style.cursor=e}}))}return P(e,[{key:"destroy",value:function(){this._scene.off(this._onTick)}}]),e}(),Yf=function(){function e(t,n,r,i,a){b(this,e),this._scene=t;var s=this._scene.canvas.canvas;s.addEventListener("mouseenter",this._mouseEnterHandler=function(){i.mouseover=!0}),s.addEventListener("mouseleave",this._mouseLeaveHandler=function(){i.mouseover=!1,s.style.cursor=null}),document.addEventListener("mousemove",this._mouseMoveHandler=function(e){Xf(e,s,i.pointerCanvasPos)}),s.addEventListener("mousedown",this._mouseDownHandler=function(e){r.active&&r.pointerEnabled&&(Xf(e,s,i.pointerCanvasPos),i.mouseover=!0)}),s.addEventListener("mouseup",this._mouseUpHandler=function(e){r.active&&r.pointerEnabled})}return P(e,[{key:"reset",value:function(){}},{key:"destroy",value:function(){var e=this._scene.canvas.canvas;document.removeEventListener("mousemove",this._mouseMoveHandler),e.removeEventListener("mouseenter",this._mouseEnterHandler),e.removeEventListener("mouseleave",this._mouseLeaveHandler),e.removeEventListener("mousedown",this._mouseDownHandler),e.removeEventListener("mouseup",this._mouseUpHandler)}}]),e}();function Xf(e,t,n){if(e){var r=t.getBoundingClientRect(),i=r.x,a=r.y;n[0]=e.clientX-i,n[1]=e.clientY-a}else e=window.event,n[0]=e.x,n[1]=e.y;return n}var qf=function(e,t){if(e){for(var n=e.target,r=0,i=0;n.offsetParent;)r+=n.offsetLeft,i+=n.offsetTop,n=n.offsetParent;t[0]=e.pageX-r,t[1]=e.pageY-i}else e=window.event,t[0]=e.x,t[1]=e.y;return t},Jf=function(){function e(t,n,r,i,a){b(this,e),this._scene=t;var s=n.pickController,o=n.pivotController,l=Z.vec2(),u=Z.vec2(),c=Z.vec2(),f=Z.vec2(),p=[],A=this._scene.canvas.canvas,d=0,v=!1;this._onTick=t.on("tick",(function(){v=!1})),A.addEventListener("touchstart",this._canvasTouchStartHandler=function(e){if(r.active&&r.pointerEnabled){e.preventDefault();var n=e.touches,a=e.changedTouches;for(i.touchStartTime=Date.now(),1===n.length&&1===a.length&&(qf(n[0],l),r.followPointer&&(s.pickCursorPos=l,s.schedulePickSurface=!0,s.update(),r.planView||(s.picked&&s.pickedSurface&&s.pickResult&&s.pickResult.worldPos?(o.setPivotPos(s.pickResult.worldPos),!r.firstPerson&&o.startPivot()&&o.showPivot()):(r.smartPivot?o.setCanvasPivotPos(i.pointerCanvasPos):o.setPivotPos(t.camera.look),!r.firstPerson&&o.startPivot()&&o.showPivot()))));p.length<n.length;)p.push(Z.vec2());for(var u=0,c=n.length;u<c;++u)qf(n[u],p[u]);d=n.length}}),A.addEventListener("touchmove",this._canvasTouchMoveHandler=function(e){if(r.active&&r.pointerEnabled&&(e.stopPropagation(),e.preventDefault(),!v)){v=!0;var n=t.canvas.boundary,o=n[2],l=n[3],A=e.touches;if(e.touches.length===d){if(1===d){qf(A[0],u),Z.subVec2(u,p[0],f);var h=f[0],I=f[1];if(null!==i.longTouchTimeout&&(Math.abs(h)>r.longTapRadius||Math.abs(I)>r.longTapRadius)&&(clearTimeout(i.longTouchTimeout),i.longTouchTimeout=null),r.planView){var y=t.camera;if("perspective"===y.projection){var m=Math.abs(t.camera.eyeLookDist)*Math.tan(y.perspective.fov/2*Math.PI/180);a.panDeltaX+=h*m/l*r.touchPanRate,a.panDeltaY+=I*m/l*r.touchPanRate}else a.panDeltaX+=.5*y.ortho.scale*(h/l)*r.touchPanRate,a.panDeltaY+=.5*y.ortho.scale*(I/l)*r.touchPanRate}else a.rotateDeltaY-=h/o*(1*r.dragRotationRate),a.rotateDeltaX+=I/l*(1.5*r.dragRotationRate)}else if(2===d){var w=A[0],g=A[1];qf(w,u),qf(g,c);var T=Z.geometricMeanVec2(p[0],p[1]),E=Z.geometricMeanVec2(u,c),b=Z.vec2();Z.subVec2(T,E,b);var D=b[0],P=b[1],R=t.camera,C=Z.distVec2([w.pageX,w.pageY],[g.pageX,g.pageY]),_=(Z.distVec2(p[0],p[1])-C)*r.touchDollyRate;if(a.dollyDelta=_,Math.abs(_)<1)if("perspective"===R.projection){var B=s.pickResult?s.pickResult.worldPos:t.center,O=Math.abs(Z.lenVec3(Z.subVec3(B,t.camera.eye,[])))*Math.tan(R.perspective.fov/2*Math.PI/180);a.panDeltaX-=D*O/l*r.touchPanRate,a.panDeltaY-=P*O/l*r.touchPanRate}else a.panDeltaX-=.5*R.ortho.scale*(D/l)*r.touchPanRate,a.panDeltaY-=.5*R.ortho.scale*(P/l)*r.touchPanRate;i.pointerCanvasPos=E}for(var S=0;S<d;++S)qf(A[S],p[S])}}})}return P(e,[{key:"reset",value:function(){}},{key:"destroy",value:function(){var e=this._scene.canvas.canvas;e.removeEventListener("touchstart",this._canvasTouchStartHandler),e.removeEventListener("touchmove",this._canvasTouchMoveHandler),this._scene.off(this._onTick)}}]),e}(),Zf=function(e,t){if(e){for(var n=e.target,r=0,i=0;n.offsetParent;)r+=n.offsetLeft,i+=n.offsetTop,n=n.offsetParent;t[0]=e.pageX-r,t[1]=e.pageY-i}else e=window.event,t[0]=e.x,t[1]=e.y;return t},$f=function(){function e(t,n,r,i,a){b(this,e),this._scene=t;var s,o=n.pickController,l=n.cameraControl,u=[],c=new Float32Array(2),f=-1,p=-1,A=this._scene.canvas.canvas,d=function(e){var r;e&&e.worldPos&&(r=e.worldPos);var i=e?e.entity.aabb:t.aabb;if(r){var a=t.camera;Z.subVec3(a.eye,a.look,[]),n.cameraFlight.flyTo({aabb:i})}else n.cameraFlight.flyTo({aabb:i})};A.addEventListener("touchstart",this._canvasTouchStartHandler=function(e){if(r.active&&r.pointerEnabled){null!==i.longTouchTimeout&&(clearTimeout(i.longTouchTimeout),i.longTouchTimeout=null);var t=e.touches,a=e.changedTouches;if(s=Date.now(),1===t.length&&1===a.length){f=s,Zf(t[0],c);var o=c[0],l=c[1],p=t[0].pageX,A=t[0].pageY;i.longTouchTimeout=setTimeout((function(){n.cameraControl.fire("rightClick",{pagePos:[Math.round(p),Math.round(A)],canvasPos:[Math.round(o),Math.round(l)],event:e},!0),i.longTouchTimeout=null}),r.longTapTimeout)}else f=-1;for(;u.length<t.length;)u.push(new Float32Array(2));for(var d=0,v=t.length;d<v;++d)Zf(t[d],u[d]);u.length=t.length}},{passive:!0}),A.addEventListener("touchend",this._canvasTouchEndHandler=function(e){if(r.active&&r.pointerEnabled){var t=Date.now(),n=e.touches,a=e.changedTouches,s=l.hasSubs("pickedSurface");null!==i.longTouchTimeout&&(clearTimeout(i.longTouchTimeout),i.longTouchTimeout=null),0===n.length&&1===a.length&&f>-1&&t-f<150&&(p>-1&&f-p<325?(Zf(a[0],o.pickCursorPos),o.schedulePickEntity=!0,o.schedulePickSurface=s,o.update(),o.pickResult?(o.pickResult.touchInput=!0,l.fire("doublePicked",o.pickResult),o.pickedSurface&&l.fire("doublePickedSurface",o.pickResult),r.doublePickFlyTo&&d(o.pickResult)):(l.fire("doublePickedNothing"),r.doublePickFlyTo&&d()),p=-1):Z.distVec2(u[0],c)<4&&(Zf(a[0],o.pickCursorPos),o.schedulePickEntity=!0,o.schedulePickSurface=s,o.update(),o.pickResult?(o.pickResult.touchInput=!0,l.fire("picked",o.pickResult),o.pickedSurface&&l.fire("pickedSurface",o.pickResult)):l.fire("pickedNothing"),p=t),f=-1),u.length=n.length;for(var A=0,v=n.length;A<v;++A)u[A][0]=n[A].pageX,u[A][1]=n[A].pageY}},{passive:!0})}return P(e,[{key:"reset",value:function(){}},{key:"destroy",value:function(){var e=this._scene.canvas.canvas;e.removeEventListener("touchstart",this._canvasTouchStartHandler),e.removeEventListener("touchend",this._canvasTouchEndHandler)}}]),e}(),ep=function(e){I(n,ve);var t=m(n);function n(e){var r,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};b(this,n),(r=t.call(this,e,i)).PAN_LEFT=0,r.PAN_RIGHT=1,r.PAN_UP=2,r.PAN_DOWN=3,r.PAN_FORWARDS=4,r.PAN_BACKWARDS=5,r.ROTATE_X_POS=6,r.ROTATE_X_NEG=7,r.ROTATE_Y_POS=8,r.ROTATE_Y_NEG=9,r.DOLLY_FORWARDS=10,r.DOLLY_BACKWARDS=11,r.AXIS_VIEW_RIGHT=12,r.AXIS_VIEW_BACK=13,r.AXIS_VIEW_LEFT=14,r.AXIS_VIEW_FRONT=15,r.AXIS_VIEW_TOP=16,r.AXIS_VIEW_BOTTOM=17,r._keyMap={},r.scene.canvas.canvas.oncontextmenu=function(e){e.preventDefault()},r._configs={longTapTimeout:600,longTapRadius:5,active:!0,keyboardLayout:"qwerty",navMode:"orbit",planView:!1,firstPerson:!1,followPointer:!0,doublePickFlyTo:!0,panRightClick:!0,showPivot:!1,pointerEnabled:!0,constrainVertical:!1,smartPivot:!1,doubleClickTimeFrame:250,snapMode:"vertex",snapRadius:30,dragRotationRate:360,keyboardRotationRate:90,rotationInertia:0,keyboardPanRate:1,touchPanRate:1,panInertia:.5,keyboardDollyRate:10,mouseWheelDollyRate:100,touchDollyRate:.2,dollyInertia:0,dollyProximityThreshold:30,dollyMinSpeed:.04},r._states={pointerCanvasPos:Z.vec2(),mouseover:!1,followPointerDirty:!0,mouseDownClientX:0,mouseDownClientY:0,mouseDownCursorX:0,mouseDownCursorY:0,touchStartTime:null,activeTouches:[],tapStartPos:Z.vec2(),tapStartTime:-1,lastTapTime:-1,longTouchTimeout:null},r._updates={rotateDeltaX:0,rotateDeltaY:0,panDeltaX:0,panDeltaY:0,panDeltaZ:0,dollyDelta:0};var a=r.scene;return r._controllers={cameraControl:g(r),pickController:new Lf(g(r),r._configs),pivotController:new Nf(a,r._configs),panController:new Pf(a),cameraFlight:new Cs(g(r),{duration:.5})},r._handlers=[new Yf(r.scene,r._controllers,r._configs,r._states,r._updates),new Jf(r.scene,r._controllers,r._configs,r._states,r._updates),new Mf(r.scene,r._controllers,r._configs,r._states,r._updates),new jf(r.scene,r._controllers,r._configs,r._states,r._updates),new Qf(r.scene,r._controllers,r._configs,r._states,r._updates),new $f(r.scene,r._controllers,r._configs,r._states,r._updates),new Wf(r.scene,r._controllers,r._configs,r._states,r._updates)],r._cameraUpdater=new Kf(r.scene,r._controllers,r._configs,r._states,r._updates),r.navMode=i.navMode,i.planView&&(r.planView=i.planView),r.constrainVertical=i.constrainVertical,i.keyboardLayout?r.keyboardLayout=i.keyboardLayout:r.keyMap=i.keyMap,r.doublePickFlyTo=i.doublePickFlyTo,r.panRightClick=i.panRightClick,r.active=i.active,r.followPointer=i.followPointer,r.rotationInertia=i.rotationInertia,r.keyboardPanRate=i.keyboardPanRate,r.touchPanRate=i.touchPanRate,r.keyboardRotationRate=i.keyboardRotationRate,r.dragRotationRate=i.dragRotationRate,r.touchDollyRate=i.touchDollyRate,r.dollyInertia=i.dollyInertia,r.dollyProximityThreshold=i.dollyProximityThreshold,r.dollyMinSpeed=i.dollyMinSpeed,r.panInertia=i.panInertia,r.pointerEnabled=!0,r.keyboardDollyRate=i.keyboardDollyRate,r.mouseWheelDollyRate=i.mouseWheelDollyRate,r}return P(n,[{key:"keyMap",get:function(){return this._keyMap},set:function(e){if(e=e||"qwerty",ae.isString(e)){var t=this.scene.input,n={};switch(e){default:this.error("Unsupported value for 'keyMap': "+e+" defaulting to 'qwerty'");case"qwerty":n[this.PAN_LEFT]=[t.KEY_A],n[this.PAN_RIGHT]=[t.KEY_D],n[this.PAN_UP]=[t.KEY_Z],n[this.PAN_DOWN]=[t.KEY_X],n[this.PAN_BACKWARDS]=[],n[this.PAN_FORWARDS]=[],n[this.DOLLY_FORWARDS]=[t.KEY_W,t.KEY_ADD],n[this.DOLLY_BACKWARDS]=[t.KEY_S,t.KEY_SUBTRACT],n[this.ROTATE_X_POS]=[t.KEY_DOWN_ARROW],n[this.ROTATE_X_NEG]=[t.KEY_UP_ARROW],n[this.ROTATE_Y_POS]=[t.KEY_Q,t.KEY_LEFT_ARROW],n[this.ROTATE_Y_NEG]=[t.KEY_E,t.KEY_RIGHT_ARROW],n[this.AXIS_VIEW_RIGHT]=[t.KEY_NUM_1],n[this.AXIS_VIEW_BACK]=[t.KEY_NUM_2],n[this.AXIS_VIEW_LEFT]=[t.KEY_NUM_3],n[this.AXIS_VIEW_FRONT]=[t.KEY_NUM_4],n[this.AXIS_VIEW_TOP]=[t.KEY_NUM_5],n[this.AXIS_VIEW_BOTTOM]=[t.KEY_NUM_6];break;case"azerty":n[this.PAN_LEFT]=[t.KEY_Q],n[this.PAN_RIGHT]=[t.KEY_D],n[this.PAN_UP]=[t.KEY_W],n[this.PAN_DOWN]=[t.KEY_X],n[this.PAN_BACKWARDS]=[],n[this.PAN_FORWARDS]=[],n[this.DOLLY_FORWARDS]=[t.KEY_Z,t.KEY_ADD],n[this.DOLLY_BACKWARDS]=[t.KEY_S,t.KEY_SUBTRACT],n[this.ROTATE_X_POS]=[t.KEY_DOWN_ARROW],n[this.ROTATE_X_NEG]=[t.KEY_UP_ARROW],n[this.ROTATE_Y_POS]=[t.KEY_A,t.KEY_LEFT_ARROW],n[this.ROTATE_Y_NEG]=[t.KEY_E,t.KEY_RIGHT_ARROW],n[this.AXIS_VIEW_RIGHT]=[t.KEY_NUM_1],n[this.AXIS_VIEW_BACK]=[t.KEY_NUM_2],n[this.AXIS_VIEW_LEFT]=[t.KEY_NUM_3],n[this.AXIS_VIEW_FRONT]=[t.KEY_NUM_4],n[this.AXIS_VIEW_TOP]=[t.KEY_NUM_5],n[this.AXIS_VIEW_BOTTOM]=[t.KEY_NUM_6]}this._keyMap=n}else{var r=e;this._keyMap=r}}},{key:"_isKeyDownForAction",value:function(e,t){var n=this._keyMap[e];if(!n)return!1;t||(t=this.scene.input.keyDown);for(var r=0,i=n.length;r<i;r++){if(t[n[r]])return!0}return!1}},{key:"pivotElement",set:function(e){this._controllers.pivotController.setPivotElement(e)}},{key:"active",get:function(){return this._configs.active},set:function(e){this._configs.active=!1!==e}},{key:"snapMode",get:function(){return this._configs.snapMode},set:function(e){"vertex"!==(e=e||"vertex")&&"edge"!==e&&(this.error("Unsupported value for snapMode: "+e+" - supported values are 'vertex' and 'edge' - defaulting to 'vertex'"),e="vertex"),this._configs.snapMode=e}},{key:"snapRadius",get:function(){return this._configs.snapRadius},set:function(e){e=e||30,this._configs.snapRadius=e}},{key:"navMode",get:function(){return this._configs.navMode},set:function(e){"firstPerson"!==(e=e||"orbit")&&"orbit"!==e&&"planView"!==e&&(this.error("Unsupported value for navMode: "+e+" - supported values are 'orbit', 'firstPerson' and 'planView' - defaulting to 'orbit'"),e="orbit"),this._configs.firstPerson="firstPerson"===e,this._configs.planView="planView"===e,(this._configs.firstPerson||this._configs.planView)&&(this._controllers.pivotController.hidePivot(),this._controllers.pivotController.endPivot()),this._configs.navMode=e}},{key:"pointerEnabled",get:function(){return this._configs.pointerEnabled},set:function(e){this._reset(),this._configs.pointerEnabled=!!e}},{key:"_reset",value:function(){for(var e=0,t=this._handlers.length;e<t;e++){var n=this._handlers[e];n.reset&&n.reset()}this._updates.panDeltaX=0,this._updates.panDeltaY=0,this._updates.rotateDeltaX=0,this._updates.rotateDeltaY=0,this._updates.dolyDelta=0}},{key:"followPointer",get:function(){return this._configs.followPointer},set:function(e){this._configs.followPointer=!1!==e}},{key:"pivotPos",get:function(){return this._controllers.pivotController.getPivotPos()},set:function(e){this._controllers.pivotController.setPivotPos(e)}},{key:"dollyToPointer",get:function(){return this.warn("dollyToPointer property is deprecated - replaced with followPointer"),this.followPointer},set:function(e){this.warn("dollyToPointer property is deprecated - replaced with followPointer"),this.followPointer=e}},{key:"panToPointer",get:function(){return this.warn("panToPointer property is deprecated - replaced with followPointer"),!1},set:function(e){this.warn("panToPointer property is deprecated - replaced with followPointer")}},{key:"planView",get:function(){return this.warn("planView property is deprecated - replaced with navMode"),this._configs.planView},set:function(e){this._configs.planView=!!e,this._configs.firstPerson=!1,this._configs.planView&&(this._controllers.pivotController.hidePivot(),this._controllers.pivotController.endPivot()),this.warn("planView property is deprecated - replaced with navMode")}},{key:"firstPerson",get:function(){return this.warn("firstPerson property is deprecated - replaced with navMode"),this._configs.firstPerson},set:function(e){this.warn("firstPerson property is deprecated - replaced with navMode"),this._configs.firstPerson=!!e,this._configs.planView=!1,this._configs.firstPerson&&(this._controllers.pivotController.hidePivot(),this._controllers.pivotController.endPivot())}},{key:"constrainVertical",get:function(){return this._configs.constrainVertical},set:function(e){this._configs.constrainVertical=!!e}},{key:"doublePickFlyTo",get:function(){return this._configs.doublePickFlyTo},set:function(e){this._configs.doublePickFlyTo=!1!==e}},{key:"panRightClick",get:function(){return this._configs.panRightClick},set:function(e){this._configs.panRightClick=!1!==e}},{key:"rotationInertia",get:function(){return this._configs.rotationInertia},set:function(e){this._configs.rotationInertia=null!=e?e:0}},{key:"keyboardPanRate",get:function(){return this._configs.keyboardPanRate},set:function(e){this._configs.keyboardPanRate=null!=e?e:5}},{key:"touchPanRate",get:function(){return this._configs.touchPanRate},set:function(e){this._configs.touchPanRate=null!=e?e:1}},{key:"keyboardRotationRate",get:function(){return this._configs.keyboardRotationRate},set:function(e){this._configs.keyboardRotationRate=null!=e?e:90}},{key:"dragRotationRate",get:function(){return this._configs.dragRotationRate},set:function(e){this._configs.dragRotationRate=null!=e?e:360}},{key:"keyboardDollyRate",get:function(){return this._configs.keyboardDollyRate},set:function(e){this._configs.keyboardDollyRate=null!=e?e:15}},{key:"touchDollyRate",get:function(){return this._configs.touchDollyRate},set:function(e){this._configs.touchDollyRate=null!=e?e:.2}},{key:"mouseWheelDollyRate",get:function(){return this._configs.mouseWheelDollyRate},set:function(e){this._configs.mouseWheelDollyRate=null!=e?e:100}},{key:"dollyInertia",get:function(){return this._configs.dollyInertia},set:function(e){this._configs.dollyInertia=null!=e?e:0}},{key:"dollyProximityThreshold",get:function(){return this._configs.dollyProximityThreshold},set:function(e){this._configs.dollyProximityThreshold=null!=e?e:35}},{key:"dollyMinSpeed",get:function(){return this._configs.dollyMinSpeed},set:function(e){this._configs.dollyMinSpeed=null!=e?e:.04}},{key:"panInertia",get:function(){return this._configs.panInertia},set:function(e){this._configs.panInertia=null!=e?e:.5}},{key:"keyboardLayout",get:function(){return this._configs.keyboardLayout},set:function(e){"qwerty"!==(e=e||"qwerty")&&"azerty"!==e&&(this.error("Unsupported value for keyboardLayout - defaulting to 'qwerty'"),e="qwerty"),this._configs.keyboardLayout=e,this.keyMap=this._configs.keyboardLayout}},{key:"smartPivot",get:function(){return this._configs.smartPivot},set:function(e){this._configs.smartPivot=!1!==e}},{key:"doubleClickTimeFrame",get:function(){return this._configs.doubleClickTimeFrame},set:function(e){this._configs.doubleClickTimeFrame=null!=e?e:250}},{key:"destroy",value:function(){this._destroyHandlers(),this._destroyControllers(),this._cameraUpdater.destroy(),v(T(n.prototype),"destroy",this).call(this)}},{key:"_destroyHandlers",value:function(){for(var e=0,t=this._handlers.length;e<t;e++){var n=this._handlers[e];n.destroy&&n.destroy()}}},{key:"_destroyControllers",value:function(){for(var e=0,t=this._controllers.length;e<t;e++){var n=this._controllers[e];n.destroy&&n.destroy()}}}]),n}(),tp=P((function e(t,n,r,i,a){b(this,e),this.name=t,this.type=r,this.value=n,this.valueType=i,this.description=a})),np=P((function e(t){if(b(this,e),this.id=t.id,this.originalSystemId=t.originalSystemId,this.metaModels=[],this.name=t.name,this.type=t.type,this.properties=[],t.properties)for(var n=t.properties,r=0,i=n.length;r<i;r++){var a=n[r];this.properties.push(new tp(a.name,a.value,a.type,a.valueType,a.description))}})),rp=function(){function e(t){b(this,e),this.metaModel=null,this.metaModels=[],this.id=t.id,this.parentId=t.parentId,this.parent=null,this.originalSystemId=t.originalSystemId,this.name=t.name,this.type=t.type,this.propertySetIds=t.propertySetIds,this.propertySets=[],this.attributes=t.attributes||{}}return P(e,[{key:"getObjectIDsInSubtree",value:function(){var e=[];return function t(n){if(n){e.push(n.id);var r=n.children;if(r)for(var i=0,a=r.length;i<a;i++)t(r[i])}}(this),e}},{key:"withMetaObjectsInSubtree",value:function(e){!function t(n){if(n){e(n);var r=n.children;if(r)for(var i=0,a=r.length;i<a;i++)t(r[i])}}(this)}},{key:"getObjectIDsInSubtreeByType",value:function(e){for(var t={},n=0,r=e.length;n<r;n++)t[e[n]]=e[n];var i=[];return function e(n){if(n){t[n.type]&&i.push(n.id);var r=n.children;if(r)for(var a=0,s=r.length;a<s;a++)e(r[a])}}(this),i}},{key:"getJSON",value:function(){var e={id:this.id,type:this.type,name:this.name};return this.parent&&(e.parent=this.parent.id),e}}]),e}(),ip=function(){function e(t){b(this,e),this.id=t.id,this.projectId=t.projectId,this.revisionId=t.revisionId,this.author=t.author,this.createdAt=t.createdAt,this.creatingApplication=t.creatingApplication,this.schema=t.schema,this.metaScene=t.metaScene,this.propertySets=[],this.rootMetaObject=null,this.rootMetaObjects=[],this.metaObjects=[],this.graph=t.graph||{},this.metaScene.metaModels[this.id]=this,this.finalized=!1}return P(e,[{key:"loadData",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(this.finalized)throw"MetaScene already finalized - can't add more data";this._globalizeIDs(e,t);var n=this.metaScene;if(e.propertySets)for(var r=0,i=e.propertySets.length;r<i;r++){var a=e.propertySets[r],s=n.propertySets[a.id];s||(s=new np({id:a.id,originalSystemId:a.originalSystemId||a.id,type:a.type,name:a.name,properties:a.properties}),n.propertySets[s.id]=s),s.metaModels.push(this),this.propertySets.push(s)}if(e.metaObjects)for(var o=0,l=e.metaObjects.length;o<l;o++){var u=e.metaObjects[o],c=u.id,f=n.metaObjects[c];if(!f){var p=u.type,A=u.originalSystemId,d=u.propertySets||u.propertySetIds;f=new rp({id:c,originalSystemId:A,parentId:u.parent,type:p,name:u.name,attributes:u.attributes,propertySetIds:d}),this.metaScene.metaObjects[c]=f}f.metaModels.push(this),u.parent||(this.rootMetaObjects.push(f),n.rootMetaObjects[c]=f),this.metaObjects.push(f)}}},{key:"finalize",value:function(){if(this.finalized)throw"MetaScene already finalized - can't re-finalize";var e=this.metaScene;for(var t in e.metaObjects){var n=e.metaObjects[t];if(n.children&&(n.children=[]),n.propertySets&&(n.propertySets=[]),n.propertySetIds)for(var r=0,i=n.propertySetIds.length;r<i;r++){var a=n.propertySetIds[r],s=e.propertySets[a];n.propertySets.push(s)}}for(var o in e.metaObjects){var l=e.metaObjects[o];if(l.parentId){var u=e.metaObjects[l.parentId];u&&(l.parent=u,(u.children||(u.children=[])).push(l))}}for(var c in e.metaObjectsByType={},e.metaObjects){var f=e.metaObjects[c],p=f.type;(e.metaObjectsByType[p]||(e.metaObjectsByType[p]={}))[c]=f}this.finalized=!0,this.metaScene.fire("metaModelCreated",this.id)}},{key:"getJSON",value:function(){var e=[];return function t(n){var r={id:n.id,extId:n.extId,type:n.type,name:n.name};n.parent&&(r.parent=n.parent.id),e.push(r);var i=n.children;if(i)for(var a=0,s=i.length;a<s;a++)t(i[a])}(this.rootMetaObject),{id:this.id,projectId:this.projectId,revisionId:this.revisionId,metaObjects:e}}},{key:"_globalizeIDs",value:function(e,t){var n=!!t.globalizeObjectIds;if(e.metaObjects)for(var r=0,i=e.metaObjects.length;r<i;r++){var a=e.metaObjects[r];if(a.originalSystemId=a.id,a.originalParentSystemId=a.parent,n&&(a.id=Z.globalizeObjectId(this.id,a.id),a.parent=Z.globalizeObjectId(this.id,a.parent)),n){var s=a.propertySetIds;if(s){for(var o=[],l=0,u=s.length;l<u;l++)o.push(Z.globalizeObjectId(this.id,s[l]));a.propertySetIds=o,a.originalSystemPropertySetIds=s}}else a.originalSystemPropertySetIds=a.propertySetIds}if(e.propertySets)for(var c=0,f=e.propertySets.length;c<f;c++){var p=e.propertySets[c];p.originalSystemId=p.id,n&&(p.id=Z.globalizeObjectId(mothis.id,p.id))}}}]),e}(),ap=function(){function e(t,n){b(this,e),this.viewer=t,this.scene=n,this.metaModels={},this.propertySets={},this.metaObjects={},this.metaObjectsByType={},this.rootMetaObjects={},this._eventSubs={}}return P(e,[{key:"on",value:function(e,t){var n=this._eventSubs[e];n||(n=[],this._eventSubs[e]=n),n.push(t)}},{key:"fire",value:function(e,t){var n=this._eventSubs[e];if(n)for(var r=0,i=n.length;r<i;r++)n[r](t)}},{key:"off",value:function(e){}},{key:"createMetaModel",value:function(e,t){var n=new ip({metaScene:this,id:e,projectId:t.projectId||"none",revisionId:t.revisionId||"none",author:t.author||"none",createdAt:t.createdAt||"none",creatingApplication:t.creatingApplication||"none",schema:t.schema||"none",propertySets:[]});return n.loadData(t),n.finalize(),n}},{key:"destroyMetaModel",value:function(e){var t=this.metaModels[e];if(t){if(t.propertySets)for(var n=0,r=t.propertySets.length;n<r;n++){var i=t.propertySets[n];if(1===i.metaModels.length)delete this.propertySets[i.id];else{for(var a=[],s=0,o=i.metaModels.length;s<o;s++)i.metaModels[s].id!==e&&a.push(i.metaModels[s]);i.metaModels=a}}if(t.metaObjects)for(var l=0,u=t.metaObjects.length;l<u;l++){var c=t.metaObjects[l];c.type;var f=c.id;if(1===c.metaModels.length)delete this.metaObjects[f],c.parent||delete this.rootMetaObjects[f];else{for(var p=[],A=t.id,d=0,v=c.metaModels.length;d<v;d++)c.metaModels[d].id!==A&&p.push(c.metaModels[d]);c.metaModels=p}}for(var h in this.metaObjects){var I=this.metaObjects[h];if(I.children&&(I.children=[]),I.propertySets&&(I.propertySets=[]),I.propertySetIds)for(var y=0,m=I.propertySetIds.length;y<m;y++){var w=I.propertySetIds[y],g=this.propertySets[w];I.propertySets.push(g)}}for(var T in this.metaObjectsByType={},this.metaObjects){var E=this.metaObjects[T],b=E.type;E.children&&(E.children=null),(this.metaObjectsByType[b]||(this.metaObjectsByType[b]={}))[T]=E}for(var D in this.metaObjects){var P=this.metaObjects[D];if(P.parentId){var R=this.metaObjects[P.parentId];R&&(P.parent=R,(R.children||(R.children=[])).push(P))}}delete this.metaModels[e],this.fire("metaModelDestroyed",e)}}},{key:"getObjectIDsByType",value:function(e){var t=this.metaObjectsByType[e];return t?Object.keys(t):[]}},{key:"getObjectIDsInSubtree",value:function(e,t,n){var r=[],i=this.metaObjects[e],a=t&&t.length>0?sp(t):null,s=n&&n.length>0?sp(n):null;return function e(t){if(t){var n=!0;(s&&s[t.type]||a&&!a[t.type])&&(n=!1),n&&r.push(t.id);var i=t.children;if(i)for(var o=0,l=i.length;o<l;o++)e(i[o])}}(i),r}},{key:"withMetaObjectsInSubtree",value:function(e,t){var n=this.metaObjects[e];n&&n.withMetaObjectsInSubtree(t)}}]),e}();function sp(e){for(var t={},n=0,r=e.length;n<r;n++)t[e[n]]=!0;return t}
|
|
27
27
|
/*!
|
|
28
28
|
* html2canvas 1.4.1 <https://html2canvas.hertzen.com>
|
|
29
29
|
* Copyright (c) 2022 Niklas von Hertzen <https://hertzen.com>
|