@xeokit/xeokit-sdk 2.4.0-alpha-15 → 2.4.0-alpha-16

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=o().mark(Iv),i=o().mark(Cv),s=o().mark(Ny);function r(e){return function(e){if(Array.isArray(e))return f(e)}(e)||function(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}(e)||d(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 n(e,t){var i="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!i){if(Array.isArray(e)||(i=d(e))||t&&e&&"number"==typeof e.length){i&&(e=i);var s=0,r=function(){};return{s:r,n:function(){return s>=e.length?{done:!0}:{done:!1,value:e[s++]}},e:function(e){throw e},f:r}}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 n,o=!0,a=!1;return{s:function(){i=i.call(e)},n:function(){var e=i.next();return o=e.done,e},e:function(e){a=!0,n=e},f:function(){try{o||null==i.return||i.return()}finally{if(a)throw n}}}}function o(){/*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */o=function(){return e};var e={},t=Object.prototype,i=t.hasOwnProperty,s="function"==typeof Symbol?Symbol:{},r=s.iterator||"@@iterator",n=s.asyncIterator||"@@asyncIterator",a=s.toStringTag||"@@toStringTag";function u(e,t,i){return Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}),e[t]}try{u({},"")}catch(e){u=function(e,t,i){return e[t]=i}}function h(e,t,i,s){var r=t&&t.prototype instanceof p?t:p,n=Object.create(r.prototype),o=new M(s||[]);return n._invoke=function(e,t,i){var s="suspendedStart";return function(r,n){if("executing"===s)throw new Error("Generator is already running");if("completed"===s){if("throw"===r)throw n;return C()}for(i.method=r,i.arg=n;;){var o=i.delegate;if(o){var a=x(o,i);if(a){if(a===c)continue;return a}}if("next"===i.method)i.sent=i._sent=i.arg;else if("throw"===i.method){if("suspendedStart"===s)throw s="completed",i.arg;i.dispatchException(i.arg)}else"return"===i.method&&i.abrupt("return",i.arg);s="executing";var u=l(e,t,i);if("normal"===u.type){if(s=i.done?"completed":"suspendedYield",u.arg===c)continue;return{value:u.arg,done:i.done}}"throw"===u.type&&(s="completed",i.method="throw",i.arg=u.arg)}}}(e,i,o),n}function l(e,t,i){try{return{type:"normal",arg:e.call(t,i)}}catch(e){return{type:"throw",arg:e}}}e.wrap=h;var c={};function p(){}function d(){}function f(){}var m={};u(m,r,(function(){return this}));var v=Object.getPrototypeOf,g=v&&v(v(I([])));g&&g!==t&&i.call(g,r)&&(m=g);var _=f.prototype=p.prototype=Object.create(m);function y(e){["next","throw","return"].forEach((function(t){u(e,t,(function(e){return this._invoke(t,e)}))}))}function b(e,t){function s(r,n,o,a){var u=l(e[r],e,n);if("throw"!==u.type){var h=u.arg,c=h.value;return c&&"object"==T(c)&&i.call(c,"__await")?t.resolve(c.__await).then((function(e){s("next",e,o,a)}),(function(e){s("throw",e,o,a)})):t.resolve(c).then((function(e){h.value=e,o(h)}),(function(e){return s("throw",e,o,a)}))}a(u.arg)}var r;this._invoke=function(e,i){function n(){return new t((function(t,r){s(e,i,t,r)}))}return r=r?r.then(n,n):n()}}function x(e,t){var i=e.iterator[t.method];if(void 0===i){if(t.delegate=null,"throw"===t.method){if(e.iterator.return&&(t.method="return",t.arg=void 0,x(e,t),"throw"===t.method))return c;t.method="throw",t.arg=new TypeError("The iterator does not provide a 'throw' method")}return c}var s=l(i,e.iterator,t.arg);if("throw"===s.type)return t.method="throw",t.arg=s.arg,t.delegate=null,c;var r=s.arg;return r?r.done?(t[e.resultName]=r.value,t.next=e.nextLoc,"return"!==t.method&&(t.method="next",t.arg=void 0),t.delegate=null,c):r:(t.method="throw",t.arg=new TypeError("iterator result is not an object"),t.delegate=null,c)}function P(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 w(e){var t=e.completion||{};t.type="normal",delete t.arg,e.completion=t}function M(e){this.tryEntries=[{tryLoc:"root"}],e.forEach(P,this),this.reset(!0)}function I(e){if(e){var t=e[r];if(t)return t.call(e);if("function"==typeof e.next)return e;if(!isNaN(e.length)){var s=-1,n=function t(){for(;++s<e.length;)if(i.call(e,s))return t.value=e[s],t.done=!1,t;return t.value=void 0,t.done=!0,t};return n.next=n}}return{next:C}}function C(){return{value:void 0,done:!0}}return d.prototype=f,u(_,"constructor",f),u(f,"constructor",d),d.displayName=u(f,a,"GeneratorFunction"),e.isGeneratorFunction=function(e){var t="function"==typeof e&&e.constructor;return!!t&&(t===d||"GeneratorFunction"===(t.displayName||t.name))},e.mark=function(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,f):(e.__proto__=f,u(e,a,"GeneratorFunction")),e.prototype=Object.create(_),e},e.awrap=function(e){return{__await:e}},y(b.prototype),u(b.prototype,n,(function(){return this})),e.AsyncIterator=b,e.async=function(t,i,s,r,n){void 0===n&&(n=Promise);var o=new b(h(t,i,s,r),n);return e.isGeneratorFunction(i)?o:o.next().then((function(e){return e.done?e.value:o.next()}))},y(_),u(_,a,"Generator"),u(_,r,(function(){return this})),u(_,"toString",(function(){return"[object Generator]"})),e.keys=function(e){var t=[];for(var i in e)t.push(i);return t.reverse(),function i(){for(;t.length;){var s=t.pop();if(s in e)return i.value=s,i.done=!1,i}return i.done=!0,i}},e.values=I,M.prototype={constructor:M,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(w),!e)for(var t in this)"t"===t.charAt(0)&&i.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 s(i,s){return o.type="throw",o.arg=e,t.next=i,s&&(t.method="next",t.arg=void 0),!!s}for(var r=this.tryEntries.length-1;r>=0;--r){var n=this.tryEntries[r],o=n.completion;if("root"===n.tryLoc)return s("end");if(n.tryLoc<=this.prev){var a=i.call(n,"catchLoc"),u=i.call(n,"finallyLoc");if(a&&u){if(this.prev<n.catchLoc)return s(n.catchLoc,!0);if(this.prev<n.finallyLoc)return s(n.finallyLoc)}else if(a){if(this.prev<n.catchLoc)return s(n.catchLoc,!0)}else{if(!u)throw new Error("try statement without catch or finally");if(this.prev<n.finallyLoc)return s(n.finallyLoc)}}}},abrupt:function(e,t){for(var s=this.tryEntries.length-1;s>=0;--s){var r=this.tryEntries[s];if(r.tryLoc<=this.prev&&i.call(r,"finallyLoc")&&this.prev<r.finallyLoc){var n=r;break}}n&&("break"===e||"continue"===e)&&n.tryLoc<=t&&t<=n.finallyLoc&&(n=null);var o=n?n.completion:{};return o.type=e,o.arg=t,n?(this.method="next",this.next=n.finallyLoc,c):this.complete(o)},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),c},finish:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var i=this.tryEntries[t];if(i.finallyLoc===e)return this.complete(i.completion,i.afterLoc),w(i),c}},catch:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var i=this.tryEntries[t];if(i.tryLoc===e){var s=i.completion;if("throw"===s.type){var r=s.arg;w(i)}return r}}throw new Error("illegal catch attempt")},delegateYield:function(e,t,i){return this.delegate={iterator:I(e),resultName:t,nextLoc:i},"next"===this.method&&(this.arg=void 0),c}},e}function a(e,t,i,s,r,n,o){try{var a=e[n](o),u=a.value}catch(e){return void i(e)}a.done?t(u):Promise.resolve(u).then(s,r)}function u(e){return function(){var t=this,i=arguments;return new Promise((function(s,r){var n=e.apply(t,i);function o(e){a(n,s,r,o,u,"next",e)}function u(e){a(n,s,r,o,u,"throw",e)}o(void 0)}))}}function h(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(e);t&&(s=s.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,s)}return i}function l(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?h(Object(i),!0).forEach((function(t){c(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):h(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}function c(e,t,i){return t in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}function p(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var i=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null==i)return;var s,r,n=[],o=!0,a=!1;try{for(i=i.call(e);!(o=(s=i.next()).done)&&(n.push(s.value),!t||n.length!==t);o=!0);}catch(e){a=!0,r=e}finally{try{o||null==i.return||i.return()}finally{if(a)throw r}}return n}(e,t)||d(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 d(e,t){if(e){if("string"==typeof e)return f(e,t);var i=Object.prototype.toString.call(e).slice(8,-1);return"Object"===i&&e.constructor&&(i=e.constructor.name),"Map"===i||"Set"===i?Array.from(e):"Arguments"===i||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(i)?f(e,t):void 0}}function f(e,t){(null==t||t>e.length)&&(t=e.length);for(var i=0,s=new Array(t);i<t;i++)s[i]=e[i];return s}function m(){return m="undefined"!=typeof Reflect&&Reflect.get?Reflect.get.bind():function(e,t,i){var s=v(e,t);if(s){var r=Object.getOwnPropertyDescriptor(s,t);return r.get?r.get.call(arguments.length<3?e:i):r.value}},m.apply(this,arguments)}function v(e,t){for(;!Object.prototype.hasOwnProperty.call(e,t)&&null!==(e=P(e)););return e}function g(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&&_(e,t)}function _(e,t){return _=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},_(e,t)}function y(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 i,s=P(e);if(t){var r=P(this).constructor;i=Reflect.construct(s,arguments,r)}else i=s.apply(this,arguments);return b(this,i)}}function b(e,t){if(t&&("object"===T(t)||"function"==typeof t))return t;if(void 0!==t)throw new TypeError("Derived constructors may only return object or undefined");return x(e)}function x(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function P(e){return P=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},P(e)}function T(e){return T="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},T(e)}function w(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function M(e,t){for(var i=0;i<t.length;i++){var s=t[i];s.enumerable=s.enumerable||!1,s.configurable=!0,"value"in s&&(s.writable=!0),Object.defineProperty(e,s.key,s)}}function I(e,t,i){return t&&M(e.prototype,t),i&&M(e,i),Object.defineProperty(e,"prototype",{writable:!1}),e}function C(e){return new k(e)}function D(e){return function(){return new A(e.apply(this,arguments))}}function A(e){var t,i;function s(t,i){try{var n=e[t](i),o=n.value,a=o instanceof k;Promise.resolve(a?o.wrapped:o).then((function(e){a?s("return"===t?"return":"next",e):r(n.done?"return":"normal",e)}),(function(e){s("throw",e)}))}catch(e){r("throw",e)}}function r(e,r){switch(e){case"return":t.resolve({value:r,done:!0});break;case"throw":t.reject(r);break;default:t.resolve({value:r,done:!1})}(t=t.next)?s(t.key,t.arg):i=null}this._invoke=function(e,r){return new Promise((function(n,o){var a={key:e,arg:r,resolve:n,reject:o,next:null};i?i=i.next=a:(t=i=a,s(e,r))}))},"function"!=typeof e.return&&(this.return=void 0)}function k(e){this.wrapped=e}function E(e){var t,i,s,r=2;for("undefined"!=typeof Symbol&&(i=Symbol.asyncIterator,s=Symbol.iterator);r--;){if(i&&null!=(t=e[i]))return t.call(e);if(s&&null!=(t=e[s]))return new F(t.call(e));i="@@asyncIterator",s="@@iterator"}throw new TypeError("Object is not async iterable")}function F(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 F=function(e){this.s=e,this.n=e.next},F.prototype={s:null,n:null,next:function(){return t(this.n.apply(this.s,arguments))},return:function(e){var i=this.s.return;return void 0===i?Promise.resolve({value:e,done:!0}):t(i.apply(this.s,arguments))},throw:function(e){var i=this.s.return;return void 0===i?Promise.reject(e):t(i.apply(this.s,arguments))}},new F(e)}A.prototype["function"==typeof Symbol&&Symbol.asyncIterator||"@@asyncIterator"]=function(){return this},A.prototype.next=function(e){return this._invoke("next",e)},A.prototype.throw=function(e){return this._invoke("throw",e)},A.prototype.return=function(e){return this._invoke("return",e)};var R,S,O,B,L,N,j,G=function(){function e(t,i){w(this,e),this.items=t||[],this._lastUniqueId=(i||0)+1}return I(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 i=this._lastUniqueId++;if(!this.items[i])return this.items[i]=e,i}}},{key:"removeItem",value:function(e){var t=this.items[e];return delete this.items[e],t}}]),e}(),H=new G,V=I((function e(t){w(this,e),this.id=t,this.parentItem=null,this.groups=[],this.menuElement=null,this.shown=!1,this.mouseOver=0})),U=I((function e(){w(this,e),this.items=[]})),z=I((function e(t,i,s,r,n){w(this,e),this.id=t,this.getTitle=i,this.doAction=s,this.getEnabled=r,this.getShown=n,this.itemElement=null,this.subMenu=null,this.enabled=!0})),W=function(){function e(){var t=this,i=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};w(this,e),this._id=H.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!==i.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()})),i.items&&(this.items=i.items),this._hideOnMouseSelect=!1!==i.hideOnMouseSelect,this.context=i.context,this.enabled=!1!==i.enabled,this.hide()}return I(e,[{key:"on",value:function(e,t){var i=this._eventSubs[e];i||(i=[],this._eventSubs[e]=i),i.push(t)}},{key:"fire",value:function(e,t){var i=this._eventSubs[e];if(i)for(var s=0,r=i.length;s<r;s++)i[s](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&&(H.removeItem(this._id),this._id=null)}},{key:"_clear",value:function(){for(var e=0,t=this._menuList.length;e<t;e++){var i=this._menuList[e].menuElement;i.parentElement.removeChild(i)}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(i){for(var s=t._getNextId(),r=new V(s),n=0,o=i.length;n<o;n++){var a=i[n],u=new U;r.groups.push(u);for(var h=function(i,s){var n=a[i],o=n.items,h=o&&o.length>0,l=t._getNextId(),c=n.getTitle||function(){return n.title||""},p=n.doAction||n.callback||function(){},d=n.getEnabled||function(){return!0},f=n.getShown||function(){return!0},m=new z(l,c,p,d,f);if(m.parentMenu=r,u.items.push(m),h){var v=e(o);m.subMenu=v,v.parentItem=m}t._itemList.push(m),t._itemMap[m.id]=m},l=0,c=a.length;l<c;l++)h(l)}return t._menuList.push(r),t._menuMap[r.id]=r,r}(e)}},{key:"_getNextId",value:function(){return"ContextMenu_"+this._id+this._nextId++}},{key:"_createUI",value:function(){var e=this;!function t(i){e._createMenuUI(i);for(var s=i.groups,r=0,n=s.length;r<n;r++)for(var o=s[r].items,a=0,u=o.length;a<u;a++){var h=o[a].subMenu;h&&t(h)}}(this._rootMenu)}},{key:"_createMenuUI",value:function(e){var t=this,i=e.groups,s=[];if(s.push('<div class="xeokit-context-menu '+e.id+'" style="z-index:300000; position: absolute;">'),s.push("<ul>"),i)for(var r=0,n=i.length;r<n;r++){var o=r,a=n,u=i[r].items;if(u)for(var h=0,l=u.length;h<l;h++){var c=u[h],p=c.subMenu,d=c.title||"";p?s.push('<li id="'+c.id+'" class="xeokit-context-menu-item" style="'+(o===a-1||h<l-1?"border-bottom: 0":"border-bottom: 1px solid black")+'">'+d+" [MORE]</li>"):s.push('<li id="'+c.id+'" class="xeokit-context-menu-item" style="'+(o===a-1||h<l-1?"border-bottom: 0":"border-bottom: 1px solid black")+'">'+d+"</li>")}}s.push("</ul>"),s.push("</div>");var f=s.join("");document.body.insertAdjacentHTML("beforeend",f);var m=document.querySelector("."+e.id);e.menuElement=m,m.style["border-radius"]="4px",m.style.display="none",m.style["z-index"]=3e5,m.style.background="white",m.style.border="1px solid black",m.style["box-shadow"]="0 4px 5px 0 gray",m.oncontextmenu=function(e){e.preventDefault()};var v=this,g=null;if(i)for(var _=0,y=i.length;_<y;_++){var b=i[_].items;if(b)for(var x=function(e,i){var s=b[e],r=s.subMenu;if(s.itemElement=document.getElementById(s.id),!s.itemElement)return console.error("ContextMenu item element not found: "+s.id),"continue";s.itemElement.addEventListener("mouseenter",(function(e){e.preventDefault();var t=s.subMenu;if(t){if(g&&g.id!==t.id&&(v._hideMenu(g.id),g=null),!1!==s.enabled){var i=s.itemElement,r=t.menuElement,n=i.getBoundingClientRect();r.getBoundingClientRect();n.right+200>window.innerWidth?v._showMenu(t.id,n.left-200,n.top-1):v._showMenu(t.id,n.right-5,n.top-1),g=t}}else g&&(v._hideMenu(g.id),g=null)})),r||(s.itemElement.addEventListener("click",(function(e){e.preventDefault(),v._context&&!1!==s.enabled&&(s.doAction&&s.doAction(v._context),t._hideOnMouseSelect?v.hide():(v._updateItemsTitles(),v._updateItemsEnabledStatus()))})),s.itemElement.addEventListener("mouseenter",(function(e){e.preventDefault(),!1!==s.enabled&&s.doHover&&s.doHover(v._context)})))},P=0,T=b.length;P<T;P++)x(P)}}},{key:"_updateItemsTitles",value:function(){if(this._context)for(var e=0,t=this._itemList.length;e<t;e++){var i=this._itemList[e],s=i.itemElement;if(s){var r=i.getShown;if(r&&r(this._context)){var n=i.getTitle(this._context);i.subMenu,s.innerText=n}}}}},{key:"_updateItemsEnabledStatus",value:function(){if(this._context)for(var e=0,t=this._itemList.length;e<t;e++){var i=this._itemList[e],s=i.itemElement;if(s){var r=i.getEnabled;if(r){var n=i.getShown;if(n){var o=n(this._context);if(i.shown=o,o){s.style.visibility="visible",s.style.height="auto",s.style.padding=null;var a=r(this._context);i.enabled=a,a?s.classList.remove("disabled"):s.classList.add("disabled")}else s.style.visibility="hidden",s.style.height="0",s.style.padding="0"}}}}}},{key:"_showMenu",value:function(e,t,i){var s=this._menuMap[e];if(s){if(!s.shown){var r=s.menuElement;r&&(this._showMenuElement(r,t,i),s.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 i=t.menuElement;i&&(this._hideMenuElement(i),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 i=this._menuList[e];this._hideMenu(i.id)}}},{key:"_showMenuElement",value:function(e,t,i){e.style.display="block";var s=e.offsetHeight,r=e.offsetWidth;i+s>window.innerHeight&&(i=window.innerHeight-s),t+r>window.innerWidth&&(t=window.innerWidth-r),e.style.left=t+"px",e.style.top=i+"px"}},{key:"_hideMenuElement",value:function(e){e.style.display="none"}}]),e}(),X=function(){function e(t,i,s){w(this,e),this.id=s&&s.id?s.id:t,this.viewer=i,this._subIdMap=null,this._subIdEvents=null,this._eventSubs=null,this._eventSubsNum=null,this._events=null,this._eventCallDepth=0,i.addPlugin(this)}return I(e,[{key:"fire",value:function(e,t,i){this._events||(this._events={}),this._eventSubs||(this._eventSubs={},this._eventSubsNum={}),!0!==i&&(this._events[e]=t||!0);var s,r=this._eventSubs[e];if(r)for(var n in r)r.hasOwnProperty(n)&&(s=r[n],this._eventCallDepth++,this._eventCallDepth<300?s.callback.call(s.scope,t):this.error("fire: potential stack overflow from recursive event '"+e+"' - dropping this event"),this._eventCallDepth--)}},{key:"on",value:function(e,t,i){this._events||(this._events={}),this._subIdMap||(this._subIdMap=new G),this._subIdEvents||(this._subIdEvents={}),this._eventSubs||(this._eventSubs={}),this._eventSubsNum||(this._eventSubsNum={});var s=this._eventSubs[e];s?this._eventSubsNum[e]++:(s={},this._eventSubs[e]=s,this._eventSubsNum[e]=1);var r=this._subIdMap.addItem();s[r]={callback:t,scope:i||this},this._subIdEvents[r]=e;var n=this._events[e];return void 0!==n&&t.call(i||this,n),r}},{key:"off",value:function(e){if(null!=e&&this._subIdEvents){var t=this._subIdEvents[e];if(t){delete this._subIdEvents[e];var i=this._eventSubs[t];i&&(delete i[e],this._eventSubsNum[t]--),this._subIdMap.removeItem(e)}}}},{key:"once",value:function(e,t,i){var s=this,r=this.on(e,(function(e){s.off(r),t.call(i||this,e)}),i)}},{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}(),Y=!0,K=Y?Float64Array:Float32Array,J=new K(16),Z=new K(16),Q=new K(4),q={setDoublePrecisionEnabled:function(e){K=(Y=e)?Float64Array:Float32Array},getDoublePrecisionEnabled:function(){return Y},MIN_DOUBLE:-Number.MAX_SAFE_INTEGER,MAX_DOUBLE:Number.MAX_SAFE_INTEGER,DEGTORAD:.0174532925,RADTODEG:57.295779513,unglobalizeObjectId:function(e,t){var i=t.indexOf("#");return i===e.length&&t.startsWith(e)?t.substring(i+1):t},globalizeObjectId:function(e,t){return e+"#"+t},vec2:function(e){return new K(e||2)},vec3:function(e){return new K(e||3)},vec4:function(e){return new K(e||4)},mat3:function(e){return new K(e||9)},mat3ToMat4:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:new K(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 K(e||16)},mat4ToMat3:function(e,t){},doublesToFloats:function(e,t,i){for(var s=new K(2),r=0,n=e.length;r<n;r++)q.splitDouble(e[r],s),t[r]=s[0],i[r]=s[1]},splitDouble:function(e,t){var i=K.from([e])[0],s=e-i;t[0]=i,t[1]=s},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,i=4294967295*Math.random()|0,s=4294967295*Math.random()|0,r=4294967295*Math.random()|0;return"".concat(e[255&t]+e[t>>8&255]+e[t>>16&255]+e[t>>24&255],"-").concat(e[255&i]).concat(e[i>>8&255],"-").concat(e[i>>16&15|64]).concat(e[i>>24&255],"-").concat(e[63&s|128]).concat(e[s>>8&255],"-").concat(e[s>>16&255]).concat(e[s>>24&255]).concat(e[255&r]).concat(e[r>>8&255]).concat(e[r>>16&255]).concat(e[r>>24&255])}}(),clamp:function(e,t,i){return Math.max(t,Math.min(i,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,i){return i||(i=e),i[0]=e[0]+t[0],i[1]=e[1]+t[1],i[2]=e[2]+t[2],i[3]=e[3]+t[3],i},addVec4Scalar:function(e,t,i){return i||(i=e),i[0]=e[0]+t,i[1]=e[1]+t,i[2]=e[2]+t,i[3]=e[3]+t,i},addVec3:function(e,t,i){return i||(i=e),i[0]=e[0]+t[0],i[1]=e[1]+t[1],i[2]=e[2]+t[2],i},addVec3Scalar:function(e,t,i){return i||(i=e),i[0]=e[0]+t,i[1]=e[1]+t,i[2]=e[2]+t,i},subVec4:function(e,t,i){return i||(i=e),i[0]=e[0]-t[0],i[1]=e[1]-t[1],i[2]=e[2]-t[2],i[3]=e[3]-t[3],i},subVec3:function(e,t,i){return i||(i=e),i[0]=e[0]-t[0],i[1]=e[1]-t[1],i[2]=e[2]-t[2],i},subVec2:function(e,t,i){return i||(i=e),i[0]=e[0]-t[0],i[1]=e[1]-t[1],i},geometricMeanVec2:function(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];for(var s=new K(t[0]),r=1;r<t.length;r++)s[0]+=t[r][0],s[1]+=t[r][1];return s[0]/=t.length,s[1]/=t.length,s},subVec4Scalar:function(e,t,i){return i||(i=e),i[0]=e[0]-t,i[1]=e[1]-t,i[2]=e[2]-t,i[3]=e[3]-t,i},subScalarVec4:function(e,t,i){return i||(i=e),i[0]=t-e[0],i[1]=t-e[1],i[2]=t-e[2],i[3]=t-e[3],i},mulVec4:function(e,t,i){return i||(i=e),i[0]=e[0]*t[0],i[1]=e[1]*t[1],i[2]=e[2]*t[2],i[3]=e[3]*t[3],i},mulVec4Scalar:function(e,t,i){return i||(i=e),i[0]=e[0]*t,i[1]=e[1]*t,i[2]=e[2]*t,i[3]=e[3]*t,i},mulVec3Scalar:function(e,t,i){return i||(i=e),i[0]=e[0]*t,i[1]=e[1]*t,i[2]=e[2]*t,i},mulVec2Scalar:function(e,t,i){return i||(i=e),i[0]=e[0]*t,i[1]=e[1]*t,i},divVec3:function(e,t,i){return i||(i=e),i[0]=e[0]/t[0],i[1]=e[1]/t[1],i[2]=e[2]/t[2],i},divVec4:function(e,t,i){return i||(i=e),i[0]=e[0]/t[0],i[1]=e[1]/t[1],i[2]=e[2]/t[2],i[3]=e[3]/t[3],i},divScalarVec3:function(e,t,i){return i||(i=t),i[0]=e/t[0],i[1]=e/t[1],i[2]=e/t[2],i},divVec3Scalar:function(e,t,i){return i||(i=e),i[0]=e[0]/t,i[1]=e[1]/t,i[2]=e[2]/t,i},divVec4Scalar:function(e,t,i){return i||(i=e),i[0]=e[0]/t,i[1]=e[1]/t,i[2]=e[2]/t,i[3]=e[3]/t,i},divScalarVec4:function(e,t,i){return i||(i=t),i[0]=e/t[0],i[1]=e/t[1],i[2]=e/t[2],i[3]=e/t[3],i},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 i=e[0],s=e[1],r=e[2],n=t[0],o=t[1],a=t[2];return[s*a-r*o,r*n-i*a,i*o-s*n,0]},cross3Vec3:function(e,t,i){i||(i=e);var s=e[0],r=e[1],n=e[2],o=t[0],a=t[1],u=t[2];return i[0]=r*u-n*a,i[1]=n*o-s*u,i[2]=s*a-r*o,i},sqLenVec4:function(e){return q.dotVec4(e,e)},lenVec4:function(e){return Math.sqrt(q.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 q.dotVec3(e,e)},sqLenVec2:function(e){return q.dotVec2(e,e)},lenVec3:function(e){return Math.sqrt(q.sqLenVec3(e))},distVec3:(j=new K(3),function(e,t){return q.lenVec3(q.subVec3(e,t,j))}),lenVec2:function(e){return Math.sqrt(q.sqLenVec2(e))},distVec2:function(){var e=new K(2);return function(t,i){return q.lenVec2(q.subVec2(t,i,e))}}(),rcpVec3:function(e,t){return q.divScalarVec3(1,e,t)},normalizeVec4:function(e,t){var i=1/q.lenVec4(e);return q.mulVec4Scalar(e,i,t)},normalizeVec3:function(e,t){var i=1/q.lenVec3(e);return q.mulVec3Scalar(e,i,t)},normalizeVec2:function(e,t){var i=1/q.lenVec2(e);return q.mulVec2Scalar(e,i,t)},angleVec3:function(e,t){var i=q.dotVec3(e,t)/Math.sqrt(q.sqLenVec3(e)*q.sqLenVec3(t));return i=i<-1?-1:i>1?1:i,Math.acos(i)},vec3FromMat4Scale:function(){var e=new K(3);return function(t,i){return e[0]=t[0],e[1]=t[1],e[2]=t[2],i[0]=q.lenVec3(e),e[0]=t[4],e[1]=t[5],e[2]=t[6],i[1]=q.lenVec3(e),e[0]=t[8],e[1]=t[9],e[2]=t[10],i[2]=q.lenVec3(e),i}}(),vecToArray:function(){function e(e){return Math.round(1e5*e)/1e5}return function(t){for(var i=0,s=(t=Array.prototype.slice.call(t)).length;i<s;i++)t[i]=e(t[i]);return t}}(),xyzArrayToObject:function(e){return{x:e[0],y:e[1],z:e[2]}},xyzObjectToArray:function(e,t){return(t=t||q.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 q.m4s(0)},setMat4ToOnes:function(){return q.m4s(1)},diagonalMat4v:function(e){return new K([e[0],0,0,0,0,e[1],0,0,0,0,e[2],0,0,0,0,e[3]])},diagonalMat4c:function(e,t,i,s){return q.diagonalMat4v([e,t,i,s])},diagonalMat4s:function(e){return q.diagonalMat4c(e,e,e,e)},identityMat4:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:new K(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 K(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,i){return i||(i=e),i[0]=e[0]+t[0],i[1]=e[1]+t[1],i[2]=e[2]+t[2],i[3]=e[3]+t[3],i[4]=e[4]+t[4],i[5]=e[5]+t[5],i[6]=e[6]+t[6],i[7]=e[7]+t[7],i[8]=e[8]+t[8],i[9]=e[9]+t[9],i[10]=e[10]+t[10],i[11]=e[11]+t[11],i[12]=e[12]+t[12],i[13]=e[13]+t[13],i[14]=e[14]+t[14],i[15]=e[15]+t[15],i},addMat4Scalar:function(e,t,i){return i||(i=e),i[0]=e[0]+t,i[1]=e[1]+t,i[2]=e[2]+t,i[3]=e[3]+t,i[4]=e[4]+t,i[5]=e[5]+t,i[6]=e[6]+t,i[7]=e[7]+t,i[8]=e[8]+t,i[9]=e[9]+t,i[10]=e[10]+t,i[11]=e[11]+t,i[12]=e[12]+t,i[13]=e[13]+t,i[14]=e[14]+t,i[15]=e[15]+t,i},addScalarMat4:function(e,t,i){return q.addMat4Scalar(t,e,i)},subMat4:function(e,t,i){return i||(i=e),i[0]=e[0]-t[0],i[1]=e[1]-t[1],i[2]=e[2]-t[2],i[3]=e[3]-t[3],i[4]=e[4]-t[4],i[5]=e[5]-t[5],i[6]=e[6]-t[6],i[7]=e[7]-t[7],i[8]=e[8]-t[8],i[9]=e[9]-t[9],i[10]=e[10]-t[10],i[11]=e[11]-t[11],i[12]=e[12]-t[12],i[13]=e[13]-t[13],i[14]=e[14]-t[14],i[15]=e[15]-t[15],i},subMat4Scalar:function(e,t,i){return i||(i=e),i[0]=e[0]-t,i[1]=e[1]-t,i[2]=e[2]-t,i[3]=e[3]-t,i[4]=e[4]-t,i[5]=e[5]-t,i[6]=e[6]-t,i[7]=e[7]-t,i[8]=e[8]-t,i[9]=e[9]-t,i[10]=e[10]-t,i[11]=e[11]-t,i[12]=e[12]-t,i[13]=e[13]-t,i[14]=e[14]-t,i[15]=e[15]-t,i},subScalarMat4:function(e,t,i){return i||(i=t),i[0]=e-t[0],i[1]=e-t[1],i[2]=e-t[2],i[3]=e-t[3],i[4]=e-t[4],i[5]=e-t[5],i[6]=e-t[6],i[7]=e-t[7],i[8]=e-t[8],i[9]=e-t[9],i[10]=e-t[10],i[11]=e-t[11],i[12]=e-t[12],i[13]=e-t[13],i[14]=e-t[14],i[15]=e-t[15],i},mulMat4:function(e,t,i){i||(i=e);var s=e[0],r=e[1],n=e[2],o=e[3],a=e[4],u=e[5],h=e[6],l=e[7],c=e[8],p=e[9],d=e[10],f=e[11],m=e[12],v=e[13],g=e[14],_=e[15],y=t[0],b=t[1],x=t[2],P=t[3],T=t[4],w=t[5],M=t[6],I=t[7],C=t[8],D=t[9],A=t[10],k=t[11],E=t[12],F=t[13],R=t[14],S=t[15];return i[0]=y*s+b*a+x*c+P*m,i[1]=y*r+b*u+x*p+P*v,i[2]=y*n+b*h+x*d+P*g,i[3]=y*o+b*l+x*f+P*_,i[4]=T*s+w*a+M*c+I*m,i[5]=T*r+w*u+M*p+I*v,i[6]=T*n+w*h+M*d+I*g,i[7]=T*o+w*l+M*f+I*_,i[8]=C*s+D*a+A*c+k*m,i[9]=C*r+D*u+A*p+k*v,i[10]=C*n+D*h+A*d+k*g,i[11]=C*o+D*l+A*f+k*_,i[12]=E*s+F*a+R*c+S*m,i[13]=E*r+F*u+R*p+S*v,i[14]=E*n+F*h+R*d+S*g,i[15]=E*o+F*l+R*f+S*_,i},mulMat3:function(e,t,i){i||(i=new K(9));var s=e[0],r=e[3],n=e[6],o=e[1],a=e[4],u=e[7],h=e[2],l=e[5],c=e[8],p=t[0],d=t[3],f=t[6],m=t[1],v=t[4],g=t[7],_=t[2],y=t[5],b=t[8];return i[0]=s*p+r*m+n*_,i[3]=s*d+r*v+n*y,i[6]=s*f+r*g+n*b,i[1]=o*p+a*m+u*_,i[4]=o*d+a*v+u*y,i[7]=o*f+a*g+u*b,i[2]=h*p+l*m+c*_,i[5]=h*d+l*v+c*y,i[8]=h*f+l*g+c*b,i},mulMat4Scalar:function(e,t,i){return i||(i=e),i[0]=e[0]*t,i[1]=e[1]*t,i[2]=e[2]*t,i[3]=e[3]*t,i[4]=e[4]*t,i[5]=e[5]*t,i[6]=e[6]*t,i[7]=e[7]*t,i[8]=e[8]*t,i[9]=e[9]*t,i[10]=e[10]*t,i[11]=e[11]*t,i[12]=e[12]*t,i[13]=e[13]*t,i[14]=e[14]*t,i[15]=e[15]*t,i},mulMat4v4:function(e,t){var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:q.vec4(),s=t[0],r=t[1],n=t[2],o=t[3];return i[0]=e[0]*s+e[4]*r+e[8]*n+e[12]*o,i[1]=e[1]*s+e[5]*r+e[9]*n+e[13]*o,i[2]=e[2]*s+e[6]*r+e[10]*n+e[14]*o,i[3]=e[3]*s+e[7]*r+e[11]*n+e[15]*o,i},transposeMat4:function(e,t){var i=e[4],s=e[14],r=e[8],n=e[13],o=e[12],a=e[9];if(!t||e===t){var u=e[1],h=e[2],l=e[3],c=e[6],p=e[7],d=e[11];return e[1]=i,e[2]=r,e[3]=o,e[4]=u,e[6]=a,e[7]=n,e[8]=h,e[9]=c,e[11]=s,e[12]=l,e[13]=p,e[14]=d,e}return t[0]=e[0],t[1]=i,t[2]=r,t[3]=o,t[4]=e[1],t[5]=e[5],t[6]=a,t[7]=n,t[8]=e[2],t[9]=e[6],t[10]=e[10],t[11]=s,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 i=e[1],s=e[2],r=e[5];t[1]=e[3],t[2]=e[6],t[3]=i,t[5]=e[7],t[6]=s,t[7]=r}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],i=e[1],s=e[2],r=e[3],n=e[4],o=e[5],a=e[6],u=e[7],h=e[8],l=e[9],c=e[10],p=e[11],d=e[12],f=e[13],m=e[14],v=e[15];return d*l*a*r-h*f*a*r-d*o*c*r+n*f*c*r+h*o*m*r-n*l*m*r-d*l*s*u+h*f*s*u+d*i*c*u-t*f*c*u-h*i*m*u+t*l*m*u+d*o*s*p-n*f*s*p-d*i*a*p+t*f*a*p+n*i*m*p-t*o*m*p-h*o*s*v+n*l*s*v+h*i*a*v-t*l*a*v-n*i*c*v+t*o*c*v},inverseMat4:function(e,t){t||(t=e);var i=e[0],s=e[1],r=e[2],n=e[3],o=e[4],a=e[5],u=e[6],h=e[7],l=e[8],c=e[9],p=e[10],d=e[11],f=e[12],m=e[13],v=e[14],g=e[15],_=i*a-s*o,y=i*u-r*o,b=i*h-n*o,x=s*u-r*a,P=s*h-n*a,T=r*h-n*u,w=l*m-c*f,M=l*v-p*f,I=l*g-d*f,C=c*v-p*m,D=c*g-d*m,A=p*g-d*v,k=1/(_*A-y*D+b*C+x*I-P*M+T*w);return t[0]=(a*A-u*D+h*C)*k,t[1]=(-s*A+r*D-n*C)*k,t[2]=(m*T-v*P+g*x)*k,t[3]=(-c*T+p*P-d*x)*k,t[4]=(-o*A+u*I-h*M)*k,t[5]=(i*A-r*I+n*M)*k,t[6]=(-f*T+v*b-g*y)*k,t[7]=(l*T-p*b+d*y)*k,t[8]=(o*D-a*I+h*w)*k,t[9]=(-i*D+s*I-n*w)*k,t[10]=(f*P-m*b+g*_)*k,t[11]=(-l*P+c*b-d*_)*k,t[12]=(-o*C+a*M-u*w)*k,t[13]=(i*C-s*M+r*w)*k,t[14]=(-f*x+m*y-v*_)*k,t[15]=(l*x-c*y+p*_)*k,t},traceMat4:function(e){return e[0]+e[5]+e[10]+e[15]},translationMat4v:function(e,t){var i=t||q.identityMat4();return i[12]=e[0],i[13]=e[1],i[14]=e[2],i},translationMat3v:function(e,t){var i=t||q.identityMat3();return i[6]=e[0],i[7]=e[1],i},translationMat4c:(N=new K(3),function(e,t,i,s){return N[0]=e,N[1]=t,N[2]=i,q.translationMat4v(N,s)}),translationMat4s:function(e,t){return q.translationMat4c(e,e,e,t)},translateMat4v:function(e,t){return q.translateMat4c(e[0],e[1],e[2],t)},translateMat4c:function(e,t,i,s){var r=s[3];s[0]+=r*e,s[1]+=r*t,s[2]+=r*i;var n=s[7];s[4]+=n*e,s[5]+=n*t,s[6]+=n*i;var o=s[11];s[8]+=o*e,s[9]+=o*t,s[10]+=o*i;var a=s[15];return s[12]+=a*e,s[13]+=a*t,s[14]+=a*i,s},setMat4Translation:function(e,t,i){return i[0]=e[0],i[1]=e[1],i[2]=e[2],i[3]=e[3],i[4]=e[4],i[5]=e[5],i[6]=e[6],i[7]=e[7],i[8]=e[8],i[9]=e[9],i[10]=e[10],i[11]=e[11],i[12]=t[0],i[13]=t[1],i[14]=t[2],i[15]=e[15],i},rotationMat4v:function(e,t,i){var s,r,n,o,a,u,h=q.normalizeVec4([t[0],t[1],t[2],0],[]),l=Math.sin(e),c=Math.cos(e),p=1-c,d=h[0],f=h[1],m=h[2];return s=d*f,r=f*m,n=m*d,o=d*l,a=f*l,u=m*l,(i=i||q.mat4())[0]=p*d*d+c,i[1]=p*s+u,i[2]=p*n-a,i[3]=0,i[4]=p*s-u,i[5]=p*f*f+c,i[6]=p*r+o,i[7]=0,i[8]=p*n+a,i[9]=p*r-o,i[10]=p*m*m+c,i[11]=0,i[12]=0,i[13]=0,i[14]=0,i[15]=1,i},rotationMat4c:function(e,t,i,s,r){return q.rotationMat4v(e,[t,i,s],r)},scalingMat4v:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:q.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]:q.identityMat3();return t[0]=e[0],t[4]=e[1],t},scalingMat4c:function(){var e=new K(3);return function(t,i,s,r){return e[0]=t,e[1]=i,e[2]=s,q.scalingMat4v(e,r)}}(),scaleMat4c:function(e,t,i,s){return s[0]*=e,s[4]*=t,s[8]*=i,s[1]*=e,s[5]*=t,s[9]*=i,s[2]*=e,s[6]*=t,s[10]*=i,s[3]*=e,s[7]*=t,s[11]*=i,s},scaleMat4v:function(e,t){var i=e[0],s=e[1],r=e[2];return t[0]*=i,t[4]*=s,t[8]*=r,t[1]*=i,t[5]*=s,t[9]*=r,t[2]*=i,t[6]*=s,t[10]*=r,t[3]*=i,t[7]*=s,t[11]*=r,t},scalingMat4s:function(e){return q.scalingMat4c(e,e,e)},rotationTranslationMat4:function(e,t){var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:q.mat4(),s=e[0],r=e[1],n=e[2],o=e[3],a=s+s,u=r+r,h=n+n,l=s*a,c=s*u,p=s*h,d=r*u,f=r*h,m=n*h,v=o*a,g=o*u,_=o*h;return i[0]=1-(d+m),i[1]=c+_,i[2]=p-g,i[3]=0,i[4]=c-_,i[5]=1-(l+m),i[6]=f+v,i[7]=0,i[8]=p+g,i[9]=f-v,i[10]=1-(l+d),i[11]=0,i[12]=t[0],i[13]=t[1],i[14]=t[2],i[15]=1,i},mat4ToEuler:function(e,t){var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:q.vec4(),s=q.clamp,r=e[0],n=e[4],o=e[8],a=e[1],u=e[5],h=e[9],l=e[2],c=e[6],p=e[10];return"XYZ"===t?(i[1]=Math.asin(s(o,-1,1)),Math.abs(o)<.99999?(i[0]=Math.atan2(-h,p),i[2]=Math.atan2(-n,r)):(i[0]=Math.atan2(c,u),i[2]=0)):"YXZ"===t?(i[0]=Math.asin(-s(h,-1,1)),Math.abs(h)<.99999?(i[1]=Math.atan2(o,p),i[2]=Math.atan2(a,u)):(i[1]=Math.atan2(-l,r),i[2]=0)):"ZXY"===t?(i[0]=Math.asin(s(c,-1,1)),Math.abs(c)<.99999?(i[1]=Math.atan2(-l,p),i[2]=Math.atan2(-n,u)):(i[1]=0,i[2]=Math.atan2(a,r))):"ZYX"===t?(i[1]=Math.asin(-s(l,-1,1)),Math.abs(l)<.99999?(i[0]=Math.atan2(c,p),i[2]=Math.atan2(a,r)):(i[0]=0,i[2]=Math.atan2(-n,u))):"YZX"===t?(i[2]=Math.asin(s(a,-1,1)),Math.abs(a)<.99999?(i[0]=Math.atan2(-h,u),i[1]=Math.atan2(-l,r)):(i[0]=0,i[1]=Math.atan2(o,p))):"XZY"===t&&(i[2]=Math.asin(-s(n,-1,1)),Math.abs(n)<.99999?(i[0]=Math.atan2(c,u),i[1]=Math.atan2(o,r)):(i[0]=Math.atan2(-h,p),i[1]=0)),i},composeMat4:function(e,t,i){var s=arguments.length>3&&void 0!==arguments[3]?arguments[3]:q.mat4();return q.quaternionToRotationMat4(t,s),q.scaleMat4v(i,s),q.translateMat4v(e,s),s},decomposeMat4:function(){var e=new K(3),t=new K(16);return function(i,s,r,n){e[0]=i[0],e[1]=i[1],e[2]=i[2];var o=q.lenVec3(e);e[0]=i[4],e[1]=i[5],e[2]=i[6];var a=q.lenVec3(e);e[8]=i[8],e[9]=i[9],e[10]=i[10];var u=q.lenVec3(e);q.determinantMat4(i)<0&&(o=-o),s[0]=i[12],s[1]=i[13],s[2]=i[14],t.set(i);var h=1/o,l=1/a,c=1/u;return t[0]*=h,t[1]*=h,t[2]*=h,t[4]*=l,t[5]*=l,t[6]*=l,t[8]*=c,t[9]*=c,t[10]*=c,q.mat4ToQuaternion(t,r),n[0]=o,n[1]=a,n[2]=u,this}}(),getColMat4:function(e,t){var i=4*t;return[e[i],e[i+1],e[i+2],e[i+3]]},setRowMat4:function(e,t,i){e[t]=i[0],e[t+4]=i[1],e[t+8]=i[2],e[t+12]=i[3]},lookAtMat4v:function(e,t,i,s){s||(s=q.mat4());var r,n,o,a,u,h,l,c,p,d,f=e[0],m=e[1],v=e[2],g=i[0],_=i[1],y=i[2],b=t[0],x=t[1],P=t[2];return f===b&&m===x&&v===P?q.identityMat4():(r=f-b,n=m-x,o=v-P,a=_*(o*=d=1/Math.sqrt(r*r+n*n+o*o))-y*(n*=d),u=y*(r*=d)-g*o,h=g*n-_*r,(d=Math.sqrt(a*a+u*u+h*h))?(a*=d=1/d,u*=d,h*=d):(a=0,u=0,h=0),l=n*h-o*u,c=o*a-r*h,p=r*u-n*a,(d=Math.sqrt(l*l+c*c+p*p))?(l*=d=1/d,c*=d,p*=d):(l=0,c=0,p=0),s[0]=a,s[1]=l,s[2]=r,s[3]=0,s[4]=u,s[5]=c,s[6]=n,s[7]=0,s[8]=h,s[9]=p,s[10]=o,s[11]=0,s[12]=-(a*f+u*m+h*v),s[13]=-(l*f+c*m+p*v),s[14]=-(r*f+n*m+o*v),s[15]=1,s)},lookAtMat4c:function(e,t,i,s,r,n,o,a,u){return q.lookAtMat4v([e,t,i],[s,r,n],[o,a,u],[])},orthoMat4c:function(e,t,i,s,r,n,o){o||(o=q.mat4());var a=t-e,u=s-i,h=n-r;return o[0]=2/a,o[1]=0,o[2]=0,o[3]=0,o[4]=0,o[5]=2/u,o[6]=0,o[7]=0,o[8]=0,o[9]=0,o[10]=-2/h,o[11]=0,o[12]=-(e+t)/a,o[13]=-(s+i)/u,o[14]=-(n+r)/h,o[15]=1,o},frustumMat4v:function(e,t,i){i||(i=q.mat4());var s=[e[0],e[1],e[2],0],r=[t[0],t[1],t[2],0];q.addVec4(r,s,J),q.subVec4(r,s,Z);var n=2*s[2],o=Z[0],a=Z[1],u=Z[2];return i[0]=n/o,i[1]=0,i[2]=0,i[3]=0,i[4]=0,i[5]=n/a,i[6]=0,i[7]=0,i[8]=J[0]/o,i[9]=J[1]/a,i[10]=-J[2]/u,i[11]=-1,i[12]=0,i[13]=0,i[14]=-n*r[2]/u,i[15]=0,i},frustumMat4:function(e,t,i,s,r,n,o){o||(o=q.mat4());var a=t-e,u=s-i,h=n-r;return o[0]=2*r/a,o[1]=0,o[2]=0,o[3]=0,o[4]=0,o[5]=2*r/u,o[6]=0,o[7]=0,o[8]=(t+e)/a,o[9]=(s+i)/u,o[10]=-(n+r)/h,o[11]=-1,o[12]=0,o[13]=0,o[14]=-n*r*2/h,o[15]=0,o},perspectiveMat4:function(e,t,i,s,r){var n=[],o=[];return n[2]=i,o[2]=s,o[1]=n[2]*Math.tan(e/2),n[1]=-o[1],o[0]=o[1]*t,n[0]=-o[0],q.frustumMat4v(n,o,r)},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 i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:q.vec3(),s=t[0],r=t[1],n=t[2];return i[0]=e[0]*s+e[4]*r+e[8]*n+e[12],i[1]=e[1]*s+e[5]*r+e[9]*n+e[13],i[2]=e[2]*s+e[6]*r+e[10]*n+e[14],i},transformPoint4:function(e,t){var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:q.vec4();return i[0]=e[0]*t[0]+e[4]*t[1]+e[8]*t[2]+e[12]*t[3],i[1]=e[1]*t[0]+e[5]*t[1]+e[9]*t[2]+e[13]*t[3],i[2]=e[2]*t[0]+e[6]*t[1]+e[10]*t[2]+e[14]*t[3],i[3]=e[3]*t[0]+e[7]*t[1]+e[11]*t[2]+e[15]*t[3],i},transformPoints3:function(e,t,i){for(var s,r,n,o,a,u=i||[],h=t.length,l=e[0],c=e[1],p=e[2],d=e[3],f=e[4],m=e[5],v=e[6],g=e[7],_=e[8],y=e[9],b=e[10],x=e[11],P=e[12],T=e[13],w=e[14],M=e[15],I=0;I<h;++I)s=(o=t[I])[0],r=o[1],n=o[2],(a=u[I]||(u[I]=[0,0,0]))[0]=l*s+f*r+_*n+P,a[1]=c*s+m*r+y*n+T,a[2]=p*s+v*r+b*n+w,a[3]=d*s+g*r+x*n+M;return u.length=h,u},transformPositions3:function(e,t){var i,s,r,n,o=arguments.length>2&&void 0!==arguments[2]?arguments[2]:t,a=t.length,u=e[0],h=e[1],l=e[2];e[3];var c=e[4],p=e[5],d=e[6];e[7];var f=e[8],m=e[9],v=e[10];e[11];var g=e[12],_=e[13],y=e[14];for(e[15],i=0;i<a;i+=3)s=t[i+0],r=t[i+1],n=t[i+2],o[i+0]=u*s+c*r+f*n+g,o[i+1]=h*s+p*r+m*n+_,o[i+2]=l*s+d*r+v*n+y;return o},transformPositions4:function(e,t){var i,s,r,n,o=arguments.length>2&&void 0!==arguments[2]?arguments[2]:t,a=t.length,u=e[0],h=e[1],l=e[2],c=e[3],p=e[4],d=e[5],f=e[6],m=e[7],v=e[8],g=e[9],_=e[10],y=e[11],b=e[12],x=e[13],P=e[14],T=e[15];for(i=0;i<a;i+=4)s=t[i+0],r=t[i+1],n=t[i+2],o[i+0]=u*s+p*r+v*n+b,o[i+1]=h*s+d*r+g*n+x,o[i+2]=l*s+f*r+_*n+P,o[i+3]=c*s+m*r+y*n+T;return o},transformVec3:function(e,t,i){var s=t[0],r=t[1],n=t[2];return(i=i||this.vec3())[0]=e[0]*s+e[4]*r+e[8]*n,i[1]=e[1]*s+e[5]*r+e[9]*n,i[2]=e[2]*s+e[6]*r+e[10]*n,i},transformVec4:function(e,t,i){var s=t[0],r=t[1],n=t[2],o=t[3];return(i=i||q.vec4())[0]=e[0]*s+e[4]*r+e[8]*n+e[12]*o,i[1]=e[1]*s+e[5]*r+e[9]*n+e[13]*o,i[2]=e[2]*s+e[6]*r+e[10]*n+e[14]*o,i[3]=e[3]*s+e[7]*r+e[11]*n+e[15]*o,i},rotateVec2:function(e,t,i){var s=arguments.length>3&&void 0!==arguments[3]?arguments[3]:e,r=Math.cos(i),n=Math.sin(i),o=e[0]-t[0],a=e[1]-t[1];return s[0]=o*r-a*n+t[0],s[1]=o*n+a*r+t[1],e},rotateVec3X:function(e,t,i,s){var r=[],n=[];return r[0]=e[0]-t[0],r[1]=e[1]-t[1],r[2]=e[2]-t[2],n[0]=r[0],n[1]=r[1]*Math.cos(i)-r[2]*Math.sin(i),n[2]=r[1]*Math.sin(i)+r[2]*Math.cos(i),s[0]=n[0]+t[0],s[1]=n[1]+t[1],s[2]=n[2]+t[2],s},rotateVec3Y:function(e,t,i,s){var r=[],n=[];return r[0]=e[0]-t[0],r[1]=e[1]-t[1],r[2]=e[2]-t[2],n[0]=r[2]*Math.sin(i)+r[0]*Math.cos(i),n[1]=r[1],n[2]=r[2]*Math.cos(i)-r[0]*Math.sin(i),s[0]=n[0]+t[0],s[1]=n[1]+t[1],s[2]=n[2]+t[2],s},rotateVec3Z:function(e,t,i,s){var r=[],n=[];return r[0]=e[0]-t[0],r[1]=e[1]-t[1],r[2]=e[2]-t[2],n[0]=r[0]*Math.cos(i)-r[1]*Math.sin(i),n[1]=r[0]*Math.sin(i)+r[1]*Math.cos(i),n[2]=r[2],s[0]=n[0]+t[0],s[1]=n[1]+t[1],s[2]=n[2]+t[2],s},projectVec4:function(e,t){var i=1/e[3];return(t=t||q.vec2())[0]=e[0]*i,t[1]=e[1]*i,t},unprojectVec3:(O=new K(16),B=new K(16),L=new K(16),function(e,t,i,s){return this.transformVec3(this.mulMat4(this.inverseMat4(t,O),this.inverseMat4(i,B),L),e,s)}),lerpVec3:function(e,t,i,s,r,n){var o=n||q.vec3(),a=(e-t)/(i-t);return o[0]=s[0]+a*(r[0]-s[0]),o[1]=s[1]+a*(r[1]-s[1]),o[2]=s[2]+a*(r[2]-s[2]),o},lerpMat4:function(e,t,i,s,r,n){var o=n||q.mat4(),a=(e-t)/(i-t);return o[0]=s[0]+a*(r[0]-s[0]),o[1]=s[1]+a*(r[1]-s[1]),o[2]=s[2]+a*(r[2]-s[2]),o[3]=s[3]+a*(r[3]-s[3]),o[4]=s[4]+a*(r[4]-s[4]),o[5]=s[5]+a*(r[5]-s[5]),o[6]=s[6]+a*(r[6]-s[6]),o[7]=s[7]+a*(r[7]-s[7]),o[8]=s[8]+a*(r[8]-s[8]),o[9]=s[9]+a*(r[9]-s[9]),o[10]=s[10]+a*(r[10]-s[10]),o[11]=s[11]+a*(r[11]-s[11]),o[12]=s[12]+a*(r[12]-s[12]),o[13]=s[13]+a*(r[13]-s[13]),o[14]=s[14]+a*(r[14]-s[14]),o[15]=s[15]+a*(r[15]-s[15]),o},flatten:function(e){var t,i,s,r,n,o=[];for(t=0,i=e.length;t<i;t++)for(s=0,r=(n=e[t]).length;s<r;s++)o.push(n[s]);return o},identityQuaternion:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:q.vec4();return e[0]=0,e[1]=0,e[2]=0,e[3]=1,e},eulerToQuaternion:function(e,t){var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:q.vec4(),s=e[0]*q.DEGTORAD/2,r=e[1]*q.DEGTORAD/2,n=e[2]*q.DEGTORAD/2,o=Math.cos(s),a=Math.cos(r),u=Math.cos(n),h=Math.sin(s),l=Math.sin(r),c=Math.sin(n);return"XYZ"===t?(i[0]=h*a*u+o*l*c,i[1]=o*l*u-h*a*c,i[2]=o*a*c+h*l*u,i[3]=o*a*u-h*l*c):"YXZ"===t?(i[0]=h*a*u+o*l*c,i[1]=o*l*u-h*a*c,i[2]=o*a*c-h*l*u,i[3]=o*a*u+h*l*c):"ZXY"===t?(i[0]=h*a*u-o*l*c,i[1]=o*l*u+h*a*c,i[2]=o*a*c+h*l*u,i[3]=o*a*u-h*l*c):"ZYX"===t?(i[0]=h*a*u-o*l*c,i[1]=o*l*u+h*a*c,i[2]=o*a*c-h*l*u,i[3]=o*a*u+h*l*c):"YZX"===t?(i[0]=h*a*u+o*l*c,i[1]=o*l*u+h*a*c,i[2]=o*a*c-h*l*u,i[3]=o*a*u-h*l*c):"XZY"===t&&(i[0]=h*a*u-o*l*c,i[1]=o*l*u-h*a*c,i[2]=o*a*c+h*l*u,i[3]=o*a*u+h*l*c),i},mat4ToQuaternion:function(e){var t,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:q.vec4(),s=e[0],r=e[4],n=e[8],o=e[1],a=e[5],u=e[9],h=e[2],l=e[6],c=e[10],p=s+a+c;return p>0?(t=.5/Math.sqrt(p+1),i[3]=.25/t,i[0]=(l-u)*t,i[1]=(n-h)*t,i[2]=(o-r)*t):s>a&&s>c?(t=2*Math.sqrt(1+s-a-c),i[3]=(l-u)/t,i[0]=.25*t,i[1]=(r+o)/t,i[2]=(n+h)/t):a>c?(t=2*Math.sqrt(1+a-s-c),i[3]=(n-h)/t,i[0]=(r+o)/t,i[1]=.25*t,i[2]=(u+l)/t):(t=2*Math.sqrt(1+c-s-a),i[3]=(o-r)/t,i[0]=(n+h)/t,i[1]=(u+l)/t,i[2]=.25*t),i},vec3PairToQuaternion:function(e,t){var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:q.vec4(),s=Math.sqrt(q.dotVec3(e,e)*q.dotVec3(t,t)),r=s+q.dotVec3(e,t);return r<1e-8*s?(r=0,Math.abs(e[0])>Math.abs(e[2])?(i[0]=-e[1],i[1]=e[0],i[2]=0):(i[0]=0,i[1]=-e[2],i[2]=e[1])):q.cross3Vec3(e,t,i),i[3]=r,q.normalizeQuaternion(i)},angleAxisToQuaternion:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:q.vec4(),i=e[3]/2,s=Math.sin(i);return t[0]=s*e[0],t[1]=s*e[1],t[2]=s*e[2],t[3]=Math.cos(i),t},quaternionToEuler:function(){var e=new K(16);return function(t,i,s){return s=s||q.vec3(),q.quaternionToRotationMat4(t,e),q.mat4ToEuler(e,i,s),s}}(),mulQuaternions:function(e,t){var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:q.vec4(),s=e[0],r=e[1],n=e[2],o=e[3],a=t[0],u=t[1],h=t[2],l=t[3];return i[0]=o*a+s*l+r*h-n*u,i[1]=o*u+r*l+n*a-s*h,i[2]=o*h+n*l+s*u-r*a,i[3]=o*l-s*a-r*u-n*h,i},vec3ApplyQuaternion:function(e,t){var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:q.vec3(),s=t[0],r=t[1],n=t[2],o=e[0],a=e[1],u=e[2],h=e[3],l=h*s+a*n-u*r,c=h*r+u*s-o*n,p=h*n+o*r-a*s,d=-o*s-a*r-u*n;return i[0]=l*h+d*-o+c*-u-p*-a,i[1]=c*h+d*-a+p*-o-l*-u,i[2]=p*h+d*-u+l*-a-c*-o,i},quaternionToMat4:function(e,t){t=q.identityMat4(t);var i=e[0],s=e[1],r=e[2],n=e[3],o=2*i,a=2*s,u=2*r,h=o*n,l=a*n,c=u*n,p=o*i,d=a*i,f=u*i,m=a*s,v=u*s,g=u*r;return t[0]=1-(m+g),t[1]=d+c,t[2]=f-l,t[4]=d-c,t[5]=1-(p+g),t[6]=v+h,t[8]=f+l,t[9]=v-h,t[10]=1-(p+m),t},quaternionToRotationMat4:function(e,t){var i=e[0],s=e[1],r=e[2],n=e[3],o=i+i,a=s+s,u=r+r,h=i*o,l=i*a,c=i*u,p=s*a,d=s*u,f=r*u,m=n*o,v=n*a,g=n*u;return t[0]=1-(p+f),t[4]=l-g,t[8]=c+v,t[1]=l+g,t[5]=1-(h+f),t[9]=d-m,t[2]=c-v,t[6]=d+m,t[10]=1-(h+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,i=q.lenVec4([e[0],e[1],e[2],e[3]]);return t[0]=e[0]/i,t[1]=e[1]/i,t[2]=e[2]/i,t[3]=e[3]/i,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 q.normalizeQuaternion(q.conjugateQuaternion(e,t))},quaternionToAngleAxis:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:q.vec4(),i=(e=q.normalizeQuaternion(e,Q))[3],s=2*Math.acos(i),r=Math.sqrt(1-i*i);return r<.001?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=e[0]/r,t[1]=e[1]/r,t[2]=e[2]/r),t[3]=s,t},AABB3:function(e){return new K(e||6)},AABB2:function(e){return new K(e||4)},OBB3:function(e){return new K(e||32)},OBB2:function(e){return new K(e||16)},Sphere3:function(e,t,i,s){return new K([e,t,i,s])},transformOBB3:function(e,t){var i,s,r,n,o=arguments.length>2&&void 0!==arguments[2]?arguments[2]:t,a=t.length,u=e[0],h=e[1],l=e[2],c=e[3],p=e[4],d=e[5],f=e[6],m=e[7],v=e[8],g=e[9],_=e[10],y=e[11],b=e[12],x=e[13],P=e[14],T=e[15];for(i=0;i<a;i+=4)s=t[i+0],r=t[i+1],n=t[i+2],o[i+0]=u*s+p*r+v*n+b,o[i+1]=h*s+d*r+g*n+x,o[i+2]=l*s+f*r+_*n+P,o[i+3]=c*s+m*r+y*n+T;return o},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 K(3),t=new K(3),i=new K(3);return function(s){return e[0]=s[0],e[1]=s[1],e[2]=s[2],t[0]=s[3],t[1]=s[4],t[2]=s[5],q.subVec3(t,e,i),Math.abs(q.lenVec3(i))}}(),getAABB3DiagPoint:function(){var e=new K(3),t=new K(3),i=new K(3);return function(s,r){e[0]=s[0],e[1]=s[1],e[2]=s[2],t[0]=s[3],t[1]=s[4],t[2]=s[5];var n=q.subVec3(t,e,i),o=r[0]-s[0],a=s[3]-r[0],u=r[1]-s[1],h=s[4]-r[1],l=r[2]-s[2],c=s[5]-r[2];return n[0]+=o>a?o:a,n[1]+=u>h?u:h,n[2]+=l>c?l:c,Math.abs(q.lenVec3(n))}}(),getAABB3Area:function(e){return(e[3]-e[0])*(e[4]-e[1])*(e[5]-e[2])},getAABB3Center:function(e,t){var i=t||q.vec3();return i[0]=(e[0]+e[3])/2,i[1]=(e[1]+e[4])/2,i[2]=(e[2]+e[5])/2,i},getAABB2Center:function(e,t){var i=t||q.vec2();return i[0]=(e[2]+e[0])/2,i[1]=(e[3]+e[1])/2,i},collapseAABB3:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:q.AABB3();return e[0]=q.MAX_DOUBLE,e[1]=q.MAX_DOUBLE,e[2]=q.MAX_DOUBLE,e[3]=q.MIN_DOUBLE,e[4]=q.MIN_DOUBLE,e[5]=q.MIN_DOUBLE,e},AABB3ToOBB3:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:q.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 K(3);return function(t,i,s){i=i||q.AABB3();for(var r,n,o,a=q.MAX_DOUBLE,u=q.MAX_DOUBLE,h=q.MAX_DOUBLE,l=q.MIN_DOUBLE,c=q.MIN_DOUBLE,p=q.MIN_DOUBLE,d=0,f=t.length;d<f;d+=3)s?(e[0]=t[d+0],e[1]=t[d+1],e[2]=t[d+2],q.decompressPosition(e,s,e),r=e[0],n=e[1],o=e[2]):(r=t[d+0],n=t[d+1],o=t[d+2]),r<a&&(a=r),n<u&&(u=n),o<h&&(h=o),r>l&&(l=r),n>c&&(c=n),o>p&&(p=o);return i[0]=a,i[1]=u,i[2]=h,i[3]=l,i[4]=c,i[5]=p,i}}(),OBB3ToAABB3:function(e){for(var t,i,s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:q.AABB3(),n=q.MAX_DOUBLE,o=q.MAX_DOUBLE,a=q.MAX_DOUBLE,u=q.MIN_DOUBLE,h=q.MIN_DOUBLE,l=q.MIN_DOUBLE,c=0,p=e.length;c<p;c+=4)(t=e[c+0])<n&&(n=t),(i=e[c+1])<o&&(o=i),(s=e[c+2])<a&&(a=s),t>u&&(u=t),i>h&&(h=i),s>l&&(l=s);return r[0]=n,r[1]=o,r[2]=a,r[3]=u,r[4]=h,r[5]=l,r},points3ToAABB3:function(e){for(var t,i,s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:q.AABB3(),n=q.MAX_DOUBLE,o=q.MAX_DOUBLE,a=q.MAX_DOUBLE,u=q.MIN_DOUBLE,h=q.MIN_DOUBLE,l=q.MIN_DOUBLE,c=0,p=e.length;c<p;c++)(t=e[c][0])<n&&(n=t),(i=e[c][1])<o&&(o=i),(s=e[c][2])<a&&(a=s),t>u&&(u=t),i>h&&(h=i),s>l&&(l=s);return r[0]=n,r[1]=o,r[2]=a,r[3]=u,r[4]=h,r[5]=l,r},points3ToSphere3:function(){var e=new K(3);return function(t,i){i=i||q.vec4();var s,r=0,n=0,o=0,a=t.length;for(s=0;s<a;s++)r+=t[s][0],n+=t[s][1],o+=t[s][2];i[0]=r/a,i[1]=n/a,i[2]=o/a;var u,h=0;for(s=0;s<a;s++)(u=Math.abs(q.lenVec3(q.subVec3(t[s],i,e))))>h&&(h=u);return i[3]=h,i}}(),positions3ToSphere3:function(){var e=new K(3),t=new K(3);return function(i,s){s=s||q.vec4();var r,n=0,o=0,a=0,u=i.length,h=0;for(r=0;r<u;r+=3)n+=i[r],o+=i[r+1],a+=i[r+2];var l,c=u/3;for(s[0]=n/c,s[1]=o/c,s[2]=a/c,r=0;r<u;r+=3)e[0]=i[r],e[1]=i[r+1],e[2]=i[r+2],(l=Math.abs(q.lenVec3(q.subVec3(e,s,t))))>h&&(h=l);return s[3]=h,s}}(),OBB3ToSphere3:function(){var e=new K(3),t=new K(3);return function(i,s){s=s||q.vec4();var r,n=0,o=0,a=0,u=i.length,h=u/4;for(r=0;r<u;r+=4)n+=i[r+0],o+=i[r+1],a+=i[r+2];s[0]=n/h,s[1]=o/h,s[2]=a/h;var l,c=0;for(r=0;r<u;r+=4)e[0]=i[r+0],e[1]=i[r+1],e[2]=i[r+2],(l=Math.abs(q.lenVec3(q.subVec3(e,s,t))))>c&&(c=l);return s[3]=c,s}}(),getSphere3Center:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:q.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]:q.vec3(),i=0,s=0,r=0,n=0,o=e.length;n<o;n+=3)i+=e[n+0],s+=e[n+1],r+=e[n+2];var a=e.length/3;return t[0]=i/a,t[1]=s/a,t[2]=r/a,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 i,s,r,n=0,o=t.length;n<o;n+=3)i=t[n],s=t[n+1],r=t[n+2],e[0]>i&&(e[0]=i),e[1]>s&&(e[1]=s),e[2]>r&&(e[2]=r),e[3]<i&&(e[3]=i),e[4]<s&&(e[4]=s),e[5]<r&&(e[5]=r);return e},collapseAABB2:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:q.AABB2();return e[0]=q.MAX_DOUBLE,e[1]=q.MAX_DOUBLE,e[2]=q.MIN_DOUBLE,e[3]=q.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,i){var s,r;return e[0]>0?(s=e[0]*i[0],r=e[0]*i[3]):(s=e[0]*i[3],r=e[0]*i[0]),e[1]>0?(s+=e[1]*i[1],r+=e[1]*i[4]):(s+=e[1]*i[4],r+=e[1]*i[1]),e[2]>0?(s+=e[2]*i[2],r+=e[2]*i[5]):(s+=e[2]*i[5],r+=e[2]*i[2]),s<=-t&&r<=-t?-1:s>=-t&&r>=-t?1:0},OBB3ToAABB2:function(e){for(var t,i,s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:q.AABB2(),n=q.MAX_DOUBLE,o=q.MAX_DOUBLE,a=q.MIN_DOUBLE,u=q.MIN_DOUBLE,h=0,l=e.length;h<l;h+=4)t=e[h+0],i=e[h+1],(t*=s=1/(e[h+3]||1))<n&&(n=t),(i*=s)<o&&(o=i),t>a&&(a=t),i>u&&(u=i);return r[0]=n,r[1]=o,r[2]=a,r[3]=u,r},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,i){var s=arguments.length>3&&void 0!==arguments[3]?arguments[3]:e,r=.5*(e[0]+1),n=.5*(e[1]+1),o=.5*(e[2]+1),a=.5*(e[3]+1);return s[0]=Math.floor(r*t),s[1]=i-Math.floor(a*i),s[2]=Math.floor(o*t),s[3]=i-Math.floor(n*i),s},tangentQuadraticBezier:function(e,t,i,s){return 2*(1-e)*(i-t)+2*e*(s-i)},tangentQuadraticBezier3:function(e,t,i,s,r){return-3*t*(1-e)*(1-e)+3*i*(1-e)*(1-e)-6*e*i*(1-e)+6*e*s*(1-e)-3*e*e*s+3*e*e*r},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,i,s,r){var n=.5*(i-e),o=.5*(s-t),a=r*r;return(2*t-2*i+n+o)*(r*a)+(-3*t+3*i-2*n-o)*a+n*r+t},b2p0:function(e,t){var i=1-e;return i*i*t},b2p1:function(e,t){return 2*(1-e)*e*t},b2p2:function(e,t){return e*e*t},b2:function(e,t,i,s){return this.b2p0(e,t)+this.b2p1(e,i)+this.b2p2(e,s)},b3p0:function(e,t){var i=1-e;return i*i*i*t},b3p1:function(e,t){var i=1-e;return 3*i*i*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,i,s,r){return this.b3p0(e,t)+this.b3p1(e,i)+this.b3p2(e,s)+this.b3p3(e,r)},triangleNormal:function(e,t,i){var s=arguments.length>3&&void 0!==arguments[3]?arguments[3]:q.vec3(),r=t[0]-e[0],n=t[1]-e[1],o=t[2]-e[2],a=i[0]-e[0],u=i[1]-e[1],h=i[2]-e[2],l=n*h-o*u,c=o*a-r*h,p=r*u-n*a,d=Math.sqrt(l*l+c*c+p*p);return 0===d?(s[0]=0,s[1]=0,s[2]=0):(s[0]=l/d,s[1]=c/d,s[2]=p/d),s},rayTriangleIntersect:function(){var e=new K(3),t=new K(3),i=new K(3),s=new K(3),r=new K(3);return function(n,o,a,u,h,l){l=l||q.vec3();var c=q.subVec3(u,a,e),p=q.subVec3(h,a,t),d=q.cross3Vec3(o,p,i),f=q.dotVec3(c,d);if(f<1e-6)return null;var m=q.subVec3(n,a,s),v=q.dotVec3(m,d);if(v<0||v>f)return null;var g=q.cross3Vec3(m,c,r),_=q.dotVec3(o,g);if(_<0||v+_>f)return null;var y=q.dotVec3(p,g)/f;return l[0]=n[0]+y*o[0],l[1]=n[1]+y*o[1],l[2]=n[2]+y*o[2],l}}(),rayPlaneIntersect:function(){var e=new K(3),t=new K(3),i=new K(3),s=new K(3);return function(r,n,o,a,u,h){h=h||q.vec3(),n=q.normalizeVec3(n,e);var l=q.subVec3(a,o,t),c=q.subVec3(u,o,i),p=q.cross3Vec3(l,c,s);q.normalizeVec3(p,p);var d=-q.dotVec3(o,p),f=-(q.dotVec3(r,p)+d)/q.dotVec3(n,p);return h[0]=r[0]+f*n[0],h[1]=r[1]+f*n[1],h[2]=r[2]+f*n[2],h}}(),cartesianToBarycentric:function(){var e=new K(3),t=new K(3),i=new K(3);return function(s,r,n,o,a){var u=q.subVec3(o,r,e),h=q.subVec3(n,r,t),l=q.subVec3(s,r,i),c=q.dotVec3(u,u),p=q.dotVec3(u,h),d=q.dotVec3(u,l),f=q.dotVec3(h,h),m=q.dotVec3(h,l),v=c*f-p*p;if(0===v)return null;var g=1/v,_=(f*d-p*m)*g,y=(c*m-p*d)*g;return a[0]=1-_-y,a[1]=y,a[2]=_,a}}(),barycentricInsideTriangle:function(e){var t=e[1],i=e[2];return i>=0&&t>=0&&i+t<1},barycentricToCartesian:function(e,t,i,s){var r=arguments.length>4&&void 0!==arguments[4]?arguments[4]:q.vec3(),n=e[0],o=e[1],a=e[2];return r[0]=t[0]*n+i[0]*o+s[0]*a,r[1]=t[1]*n+i[1]*o+s[1]*a,r[2]=t[2]*n+i[2]*o+s[2]*a,r},mergeVertices:function(e,t,i,s){var r,n,o,a,u,h,l={},c=[],p=[],d=t?[]:null,f=i?[]:null,m=[],v=Math.pow(10,4),g=0;for(u=0,h=e.length;u<h;u+=3)r=e[u],n=e[u+1],o=e[u+2],void 0===l[a="".concat(Math.round(r*v),"_").concat(Math.round(n*v),"_").concat(Math.round(o*v))]&&(l[a]=p.length/3,p.push(r),p.push(n),p.push(o),t&&(d.push(t[u]),d.push(t[u+1]),d.push(t[u+2])),i&&(f.push(i[g]),f.push(i[g+1]))),c[u/3]=l[a],g+=2;for(u=0,h=s.length;u<h;u++)m[u]=c[s[u]];var _={positions:p,indices:m};return d&&(_.normals=d),f&&(_.uv=f),_},buildNormals:function(){var e=new K(3),t=new K(3),i=new K(3),s=new K(3),r=new K(3),n=new K(3);return function(o,a,u){var h,l,c,p,d,f,m,v,g,_=new Array(o.length/3);for(h=0,l=a.length;h<l;h+=3){c=a[h],p=a[h+1],d=a[h+2],e[0]=o[3*c],e[1]=o[3*c+1],e[2]=o[3*c+2],t[0]=o[3*p],t[1]=o[3*p+1],t[2]=o[3*p+2],i[0]=o[3*d],i[1]=o[3*d+1],i[2]=o[3*d+2],q.subVec3(t,e,s),q.subVec3(i,e,r);var y=q.vec3();q.normalizeVec3(q.cross3Vec3(s,r,n),y),_[c]||(_[c]=[]),_[p]||(_[p]=[]),_[d]||(_[d]=[]),_[c].push(y),_[p].push(y),_[d].push(y)}for(u=u&&u.length===o.length?u:new Float32Array(o.length),h=0,l=_.length;h<l;h++){f=_[h].length,m=0,v=0,g=0;for(var b=0;b<f;b++)m+=_[h][b][0],v+=_[h][b][1],g+=_[h][b][2];u[3*h]=m/f,u[3*h+1]=v/f,u[3*h+2]=g/f}return u}}(),buildTangents:function(){var e=new K(3),t=new K(3),i=new K(3),s=new K(3),r=new K(3),n=new K(3),o=new K(3);return function(a,u,h){for(var l=new Float32Array(a.length),c=0;c<u.length;c+=3){var p=u[c],d=a.subarray(3*p,3*p+3),f=h.subarray(2*p,2*p+2);p=u[c+1];var m=a.subarray(3*p,3*p+3),v=h.subarray(2*p,2*p+2);p=u[c+2];for(var g=a.subarray(3*p,3*p+3),_=h.subarray(2*p,2*p+2),y=q.subVec3(m,d,e),b=q.subVec3(g,d,t),x=q.subVec2(v,f,i),P=q.subVec2(_,f,s),T=1/(x[0]*P[1]-x[1]*P[0]),w=q.mulVec3Scalar(q.subVec3(q.mulVec3Scalar(y,P[1],r),q.mulVec3Scalar(b,x[1],n),o),T,n),M=void 0,I=0;I<3;I++)l[M=3*u[c+I]]+=w[0],l[M+1]+=w[1],l[M+2]+=w[2]}return l}}(),buildPickTriangles:function(e,t,i){for(var s,r,n,o,a,u=t.length,h=i?new Uint16Array(9*u):new Float32Array(9*u),l=new Uint8Array(12*u),c=0,p=0,d=0,f=0;f<u;f+=3)a=c>>24&255,o=c>>16&255,n=c>>8&255,r=255&c,s=3*t[f],h[p++]=e[s],h[p++]=e[s+1],h[p++]=e[s+2],l[d++]=r,l[d++]=n,l[d++]=o,l[d++]=a,s=3*t[f+1],h[p++]=e[s],h[p++]=e[s+1],h[p++]=e[s+2],l[d++]=r,l[d++]=n,l[d++]=o,l[d++]=a,s=3*t[f+2],h[p++]=e[s],h[p++]=e[s+1],h[p++]=e[s+2],l[d++]=r,l[d++]=n,l[d++]=o,l[d++]=a,c++;return{positions:h,colors:l}},faceToVertexNormals:function(e,t){var i,s,r,n,o,a,u,h,l,c,p,d=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},f=d.smoothNormalsAngleThreshold||20,m={},v=[],g={},_=4,y=Math.pow(10,_);for(u=0,l=e.length;u<l;u+=3){a=u/3,s=e[u],r=e[u+1],n=e[u+2],void 0===m[o="".concat(Math.round(s*y),"_").concat(Math.round(r*y),"_").concat(Math.round(n*y))]?m[o]=[a]:m[o].push(a);var b=q.normalizeVec3([t[u],t[u+1],t[u+2]]);v[a]=b,i=q.vec4([b[0],b[1],b[2],1]),g[a]=i}for(o in m)if(m.hasOwnProperty(o)){var x=m[o],P=x.length;for(u=0;u<P;u++){var T=x[u];for(i=g[T],h=0;h<P;h++)if(u!==h){var w=x[h];c=v[T],p=v[w];var M=Math.abs(q.angleVec3(c,p)/q.DEGTORAD);M<f&&(i[0]+=p[0],i[1]+=p[1],i[2]+=p[2],i[3]+=1)}}}for(u=0,l=t.length;u<l;u+=3)i=g[u/3],t[u+0]=i[0]/i[3],t[u+1]=i[1]/i[3],t[u+2]=i[2]/i[3]},transformRay:function(){var e=new K(4),t=new K(4);return function(i,s,r,n,o){e[0]=s[0],e[1]=s[1],e[2]=s[2],e[3]=1,q.transformVec4(i,e,t),n[0]=t[0],n[1]=t[1],n[2]=t[2],e[0]=r[0],e[1]=r[1],e[2]=r[2],q.transformVec3(i,e,t),q.normalizeVec3(t),o[0]=t[0],o[1]=t[1],o[2]=t[2]}}(),canvasPosToWorldRay:function(){var e=new K(16),t=new K(16),i=new K(4),s=new K(4),r=new K(4),n=new K(4);return function(o,a,u,h,l,c){var p=q.mulMat4(u,a,e),d=q.inverseMat4(p,t),f=o.width,m=o.height,v=(h[0]-f/2)/(f/2),g=-(h[1]-m/2)/(m/2);i[0]=v,i[1]=g,i[2]=-1,i[3]=1,q.transformVec4(d,i,s),q.mulVec4Scalar(s,1/s[3]),r[0]=v,r[1]=g,r[2]=1,r[3]=1,q.transformVec4(d,r,n),q.mulVec4Scalar(n,1/n[3]),l[0]=n[0],l[1]=n[1],l[2]=n[2],q.subVec3(n,s,c),q.normalizeVec3(c)}}(),canvasPosToLocalRay:(R=new K(3),S=new K(3),function(e,t,i,s,r,n,o){q.canvasPosToWorldRay(e,t,i,r,R,S),q.worldRayToLocalRay(s,R,S,n,o)}),worldRayToLocalRay:function(){var e=new K(16),t=new K(4),i=new K(4);return function(s,r,n,o,a){var u=q.inverseMat4(s,e);t[0]=r[0],t[1]=r[1],t[2]=r[2],t[3]=1,q.transformVec4(u,t,i),o[0]=i[0],o[1]=i[1],o[2]=i[2],q.transformVec3(u,n,a)}}(),buildKDTree:function(){var e=new Float32Array;function t(i,s,r,n){var o,a,u=new K(6),h={triangles:null,left:null,right:null,leaf:!1,splitDim:0,aabb:u};for(u[0]=u[1]=u[2]=Number.POSITIVE_INFINITY,u[3]=u[4]=u[5]=Number.NEGATIVE_INFINITY,o=0,a=i.length;o<a;++o)for(var l=3*i[o],c=0;c<3;++c){var p=3*s[l+c];r[p]<u[0]&&(u[0]=r[p]),r[p]>u[3]&&(u[3]=r[p]),r[p+1]<u[1]&&(u[1]=r[p+1]),r[p+1]>u[4]&&(u[4]=r[p+1]),r[p+2]<u[2]&&(u[2]=r[p+2]),r[p+2]>u[5]&&(u[5]=r[p+2])}if(i.length<20||n>10)return h.triangles=i,h.leaf=!0,h;e[0]=u[3]-u[0],e[1]=u[4]-u[1],e[2]=u[5]-u[2];var d=0;e[1]>e[d]&&(d=1),e[2]>e[d]&&(d=2),h.splitDim=d;var f=(u[d]+u[d+3])/2,m=new Array(i.length),v=0,g=new Array(i.length),_=0;for(o=0,a=i.length;o<a;++o){var y=s[l=3*i[o]],b=3*s[l+1],x=3*s[l+2];r[3*y+d]<=f||r[b+d]<=f||r[x+d]<=f?m[v++]=i[o]:g[_++]=i[o]}return m.length=v,g.length=_,h.left=t(m,s,r,n+1),h.right=t(g,s,r,n+1),h}return function(e,i){for(var s=e.length/3,r=new Array(s),n=0;n<s;++n)r[n]=n;return t(r,e,i,0)}}(),decompressPosition:function(e,t,i){(i=i||e)[0]=e[0]*t[0]+t[12],i[1]=e[1]*t[5]+t[13],i[2]=e[2]*t[10]+t[14]},decompressPositions:function(e,t){for(var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:new Float32Array(e.length),s=0,r=e.length;s<r;s+=3)i[s+0]=e[s+0]*t[0]+t[12],i[s+1]=e[s+1]*t[5]+t[13],i[s+2]=e[s+2]*t[10]+t[14];return i},decompressUV:function(e,t,i){i[0]=e[0]*t[0]+t[6],i[1]=e[1]*t[4]+t[7]},decompressUVs:function(e,t){for(var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:new Float32Array(e.length),s=0,r=e.length;s<r;s+=3)i[s+0]=e[s+0]*t[0]+t[6],i[s+1]=e[s+1]*t[4]+t[7];return i},octDecodeVec2:function(e,t){var i=e[0],s=e[1];i=(2*i+1)/255,s=(2*s+1)/255;var r=1-Math.abs(i)-Math.abs(s);r<0&&(i=(1-Math.abs(s))*(i>=0?1:-1),s=(1-Math.abs(i))*(s>=0?1:-1));var n=Math.sqrt(i*i+s*s+r*r);return t[0]=i/n,t[1]=s/n,t[2]=r/n,t},octDecodeVec2s:function(e,t){for(var i=0,s=0,r=e.length;i<r;i+=2){var n=e[i+0],o=e[i+1];n=(2*n+1)/255,o=(2*o+1)/255;var a=1-Math.abs(n)-Math.abs(o);a<0&&(n=(1-Math.abs(o))*(n>=0?1:-1),o=(1-Math.abs(n))*(o>=0?1:-1));var u=Math.sqrt(n*n+o*o+a*a);t[s+0]=n/u,t[s+1]=o/u,t[s+2]=a/u,s+=3}return t}};q.buildEdgeIndices=function(){var e=[],t=[],i=[],s=[],r=[],n=0,o=new Uint16Array(3),a=new Uint16Array(3),u=new Uint16Array(3),h=q.vec3(),l=q.vec3(),c=q.vec3(),p=q.vec3(),d=q.vec3(),f=q.vec3(),m=q.vec3();return function(v,g,_,y){!function(r,n){var o,a,u,h,l,c,p={},d=Math.pow(10,4),f=0;for(l=0,c=r.length;l<c;l+=3)o=r[l],a=r[l+1],u=r[l+2],void 0===p[h=Math.round(o*d)+"_"+Math.round(a*d)+"_"+Math.round(u*d)]&&(p[h]=f/3,e[f++]=o,e[f++]=a,e[f++]=u),t[l/3]=p[h];for(l=0,c=n.length;l<c;l++)s[l]=t[n[l]],i[s[l]]=n[l]}(v,g),function(t,i){n=0;for(var v=0,g=t;v<g;v+=3){var _=3*s[v],y=3*s[v+1],b=3*s[v+2];i?(o[0]=e[_],o[1]=e[_+1],o[2]=e[_+2],a[0]=e[y],a[1]=e[y+1],a[2]=e[y+2],u[0]=e[b],u[1]=e[b+1],u[2]=e[b+2],q.decompressPosition(o,i,h),q.decompressPosition(a,i,l),q.decompressPosition(u,i,c)):(h[0]=e[_],h[1]=e[_+1],h[2]=e[_+2],l[0]=e[y],l[1]=e[y+1],l[2]=e[y+2],c[0]=e[b],c[1]=e[b+1],c[2]=e[b+2]),q.subVec3(c,l,p),q.subVec3(h,l,d),q.cross3Vec3(p,d,f),q.normalizeVec3(f,m);var x=r[n]||(r[n]={normal:q.vec3()});x.normal[0]=m[0],x.normal[1]=m[1],x.normal[2]=m[2],n++}}(g.length,_);for(var b,x,P,T,w,M,I,C,D,A,k=[],E=Math.cos(q.DEGTORAD*y),F={},R=!1,S=0,O=g.length;S<O;S+=3)for(var B=S/3,L=0;L<3;L++)b=s[S+L],x=s[S+(L+1)%3],void 0===F[w=(P=Math.min(b,x))+","+(T=Math.max(b,x))]?F[w]={index1:P,index2:T,face1:B,face2:void 0}:F[w].face2=B;for(w in F)void 0!==(M=F[w]).face2&&(I=r[M.face1].normal,C=r[M.face2].normal,q.dotVec3(I,C)>E)||(D=i[M.index1],A=i[M.index2],(!R&&D>65535||A>65535)&&(R=!0),k.push(D),k.push(A));return R?new Uint32Array(k):new Uint16Array(k)}}();var $=function(){function e(){w(this,e),this._head=[],this._headLength=0,this._tail=[],this._index=0,this._length=0}return I(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=[],i=e[0].charCodeAt(0),s=i+e[1],r=i;r<s;++r)t.push(r);return String.fromCharCode.apply(null,t)})).join("");function ie(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 se=function(){for(var e={},t=window.location.search.substring(1).split("&"),i=0;i<t.length;i++){var s=t[i].split("=");if(void 0===e[s[0]])e[s[0]]=decodeURIComponent(s[1]);else if("string"==typeof e[s[0]]){var r=[e[s[0]],decodeURIComponent(s[1])];e[s[0]]=r}else e[s[0]].push(decodeURIComponent(s[1]))}return e}();var re={xmlToJson:function e(t,i){if(t.nodeType===t.TEXT_NODE){var s=t.nodeValue;if(null===s.match(/^\s+$/))return s}else if(t.nodeType===t.ELEMENT_NODE||t.nodeType===t.DOCUMENT_NODE){var r={type:t.nodeName,children:[]};if(t.nodeType===t.ELEMENT_NODE)for(var n=0;n<t.attributes.length;n++){var o=t.attributes[n];r[i[o.nodeName]||o.nodeName]=o.nodeValue}for(var a=0;a<t.childNodes.length;a++){(n=e(t.childNodes[a],i))&&r.children.push(n)}return r}},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 ie(t[0],2)+[1,4,7,10,13].map((function(e){return ie((t[e]<<16)+(t[e+1]<<8)+t[e+2])})).join("")},findNodeOfType:function(e,t){var i=[];return function e(s){s.type===t&&i.push(s),(s.children||[]).forEach((function(t){e(t)}))}(e),i},timeout:function(e){return new Promise((function(t,i){setTimeout(t,e)}))},httpRequest:function(e){return new Promise((function(t,i){var s=new XMLHttpRequest;s.open(e.method||"GET",e.url,!0),s.onload=function(r){console.log(e.url,s.readyState,s.status),4===s.readyState&&(200===s.status?t(s.responseXML):i(s.statusText))},s.send(null)}))},loadJSON:function(e,t,i){var s=function(e){};t=t||s,i=i||s;var r=new XMLHttpRequest;r.overrideMimeType("application/json"),r.open("GET",e,!0),r.addEventListener("load",(function(e){var s=e.target.response;if(200===this.status){var r;try{r=JSON.parse(s)}catch(e){i("utils.loadJSON(): Failed to parse JSON response - ".concat(e))}t(r)}else if(0===this.status){console.warn("loadFile: HTTP Status 0 received.");try{t(JSON.parse(s))}catch(e){i("utils.loadJSON(): Failed to parse JSON response - ".concat(e))}}else i(e)}),!1),r.addEventListener("error",(function(e){i(e)}),!1),r.send(null)},loadArraybuffer:function(e,t,i){var s=function(e){};t=t||s,i=i||s;var r=e.match(/^data:(.*?)(;base64)?,(.*)$/);if(r){var n=!!r[2],o=r[3];o=window.decodeURIComponent(o),n&&(o=window.atob(o));try{for(var a=new ArrayBuffer(o.length),u=new Uint8Array(a),h=0;h<o.length;h++)u[h]=o.charCodeAt(h);window.setTimeout((function(){t(a)}),0)}catch(e){window.setTimeout((function(){i(e)}),0)}}else{var l=new XMLHttpRequest;l.open("GET",e,!0),l.responseType="arraybuffer",l.onreadystatechange=function(){4===l.readyState&&(200===l.status?t(l.response):i("loadArrayBuffer error : "+l.response))},l.send(null)}},queryString:se,isArray:function(e){return e&&!e.propertyIsEnumerable("length")&&"object"===T(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 re.isString(e)||re.isNumeric(e)},isSameComponent:function(e,t){return!(!e||!t)&&(re.isNumeric(e)||re.isString(e)?"".concat(e):e.id)===(re.isNumeric(t)||re.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 re.apply(e,{})},apply:function(e,t){for(var i in e)e.hasOwnProperty(i)&&(t[i]=e[i]);return t},apply2:function(e,t){for(var i in e)e.hasOwnProperty(i)&&void 0!==e[i]&&null!==e[i]&&(t[i]=e[i]);return t},applyIf:function(e,t){for(var i in e)e.hasOwnProperty(i)&&(void 0!==t[i]&&null!==t[i]||(t[i]=e[i]));return t},isEmptyObject:function(e){for(var t in e)if(e.hasOwnProperty(t))return!1;return!0},inQuotes:function(e){return re.isNumeric(e)?"".concat(e):"'".concat(e,"'")},concat:function(e,t){var i=new e.constructor(e.length+t.length);return i.set(e),i.set(t,e.length),i},flattenParentChildHierarchy:function(e){var t=[];return function e(i){i.id=i.uuid,delete i.oid,t.push(i);var s=i.children;if(s)for(var r=0,n=s.length;r<n;r++){s[r].parent=i.id,e(s[r])}i.children=[]}(e),t}},ne={},oe=new G,ae=new $,ue={sceneId:null,time:null,startTime:null,prevTime:null,deltaTime:null},he=[],le=0,ce=0;var pe=new function(){this.version="1.0.0",this.scenes={},this._superTypes={},this._addScene=function(e){if(e.id){if(pe.scenes[e.id])return void console.error("[ERROR] Scene ".concat(re.inQuotes(e.id)," already exists"))}else e.id=oe.addItem({});pe.scenes[e.id]=e;var t=e.ticksPerOcclusionTest,i=e.ticksPerRender;ne[e.id]={ticksPerOcclusionTest:t,ticksPerRender:i,renderCountdown:i},ee.components.scenes++,e.once("destroyed",(function(){oe.removeItem(e.id),delete pe.scenes[e.id],delete ne[e.id],ee.components.scenes--}))},this.clear=function(){var e;for(var t in pe.scenes)pe.scenes.hasOwnProperty(t)&&(e=pe.scenes[t],"default.scene"===t?e.clear():(e.destroy(),delete pe.scenes[e.id]))},this.scheduleTask=function(e,t){ae.push(e),ae.push(t)},this.runTasks=function(){for(var e,t,i=arguments.length>0&&void 0!==arguments[0]?arguments[0]:-1,s=(new Date).getTime(),r=0;ae.length>0&&(i<0||s<i);)e=ae.shift(),(t=ae.shift())?e.call(t):e(),s=(new Date).getTime(),r++;return r},this.getNumTasks=function(){return ae.length}},de=function e(){var t=Date.now();if(le>0){var i=1e3/(t-le);ce+=i,he.push(i),he.length>=30&&(ce-=he.shift()),ee.frame.fps=Math.round(ce/he.length)}!function(e){var t=pe.runTasks(e+10),i=pe.getNumTasks();ee.frame.tasksRun=t,ee.frame.tasksScheduled=i,ee.frame.tasksBudget=10}(t),function(e){for(var t in ue.time=e,pe.scenes)if(pe.scenes.hasOwnProperty(t)){var i=pe.scenes[t];ue.sceneId=t,ue.startTime=i.startTime,ue.deltaTime=null!=ue.prevTime?ue.time-ue.prevTime:0,i.fire("tick",ue,!0)}ue.prevTime=e}(t),function(){var e,t,i,s,r,n=pe.scenes,o=!1;for(r in n)n.hasOwnProperty(r)&&(e=n[r],(t=ne[r])||(t=ne[r]={}),i=e.ticksPerOcclusionTest,t.ticksPerOcclusionTest!==i&&(t.ticksPerOcclusionTest=i,t.renderCountdown=i),--e.occlusionTestCountdown<=0&&(e.doOcclusionTest(),e.occlusionTestCountdown=i),s=e.ticksPerRender,t.ticksPerRender!==s&&(t.ticksPerRender=s,t.renderCountdown=s),0==--t.renderCountdown&&(e.render(o),t.renderCountdown=s))}(),le=t,void 0!==window.requestPostAnimationFrame?window.requestPostAnimationFrame(e):requestAnimationFrame(e)};void 0!==window.requestPostAnimationFrame?window.requestPostAnimationFrame(de):requestAnimationFrame(de);var fe=function(){function e(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:null,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(w(this,e),this.scene=null,"Scene"===this.type)this.scene=this,this.viewer=i.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=!!i.dontClear,this._renderer=this.scene._renderer,this.meta=i.meta||{},this.id=i.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 I(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,i){this._events||(this._events={}),this._eventSubs||(this._eventSubs={},this._eventSubsNum={}),!0!==i&&(this._events[e]=t||!0);var s,r=this._eventSubs[e];if(r)for(var n in r)r.hasOwnProperty(n)&&(s=r[n],this._eventCallDepth++,this._eventCallDepth<300?s.callback.call(s.scope,t):this.error("fire: potential stack overflow from recursive event '"+e+"' - dropping this event"),this._eventCallDepth--)}},{key:"on",value:function(e,t,i){this._events||(this._events={}),this._subIdMap||(this._subIdMap=new G),this._subIdEvents||(this._subIdEvents={}),this._eventSubs||(this._eventSubs={}),this._eventSubsNum||(this._eventSubsNum={});var s=this._eventSubs[e];s?this._eventSubsNum[e]++:(s={},this._eventSubs[e]=s,this._eventSubsNum[e]=1);var r=this._subIdMap.addItem();s[r]={callback:t,scope:i||this},this._subIdEvents[r]=e;var n=this._events[e];return void 0!==n&&t.call(i||this,n),r}},{key:"off",value:function(e){if(null!=e&&this._subIdEvents){var t=this._subIdEvents[e];if(t){delete this._subIdEvents[e];var i=this._eventSubs[t];i&&(delete i[e],this._eventSubsNum[t]--),this._subIdMap.removeItem(e)}}}},{key:"once",value:function(e,t,i){var s=this,r=this.on(e,(function(e){s.off(r),t.call(i||this,e)}),i)}},{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+" "+re.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 i=e.component,s=e.sceneDefault,r=e.sceneSingleton,n=e.type,o=e.on,a=!1!==e.recompiles;if(i&&(re.isNumeric(i)||re.isString(i))){var u=i;if(!(i=this.scene.components[u]))return void this.error("Component not found: "+re.inQuotes(u))}if(!i)if(!0===r){var h=this.scene.types[n];for(var l in h)if(h.hasOwnProperty){i=h[l];break}if(!i)return this.error("Scene has no default component for '"+t+"'"),null}else if(!0===s&&!(i=this.scene[t]))return this.error("Scene has no default component for '"+t+"'"),null;if(i){if(i.scene.id!==this.scene.id)return void this.error("Not in same scene: "+i.type+" "+re.inQuotes(i.id));if(n&&!i.isType(n))return void this.error("Expected a "+n+" type or subtype: "+i.type+" "+re.inQuotes(i.id))}this._attachments||(this._attachments={});var c,p,d,f=this._attached[t];if(f){if(i&&f.id===i.id)return;var m=this._attachments[f.id];for(p=0,d=(c=m.subs).length;p<d;p++)f.off(c[p]);delete this._attached[t],delete this._attachments[f.id];var v=m.params.onDetached;v&&(re.isFunction(v)?v(f):v.scope?v.callback.call(v.scope,f):v.callback(f)),m.managingLifecycle&&f.destroy()}if(i){var g={params:e,component:i,subs:[],managingLifecycle:!1};g.subs.push(i.once("destroyed",(function(){g.params.component=null,this._attach(g.params)}),this)),a&&g.subs.push(i.on("dirty",(function(){this.fire("dirty",this)}),this)),this._attached[t]=i,this._attachments[i.id]=g;var _,y,b,x,P=e.onAttached;if(P&&(re.isFunction(P)?P(i):P.scope?P.callback.call(P.scope,i):P.callback(i)),o)for(_ in o)if(o.hasOwnProperty(_)){if(y=o[_],re.isFunction(y)?(b=y,x=null):(b=y.callback,x=y.scope),!b)continue;g.subs.push(i.on(_,b,x))}}return a&&this.fire("dirty",this),this.fire(t,i),i}this.error("Component 'name' expected")}},{key:"_checkComponent",value:function(e,t){if(!t.isComponent){if(!re.isID(t))return void this.error("Expected a Component or ID");var i=t;if(!(t=this.scene.components[i]))return void this.error("Component not found: "+i)}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(!re.isID(t))return void this.error("Expected a Component or ID");var i=t;if(!(t=this.scene.components[i]))return void this.error("Component not found: "+i)}if(t.scene.id===this.scene.id){for(var s=0,r=e.length;s<r;s++)if(e[s]===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():pe.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,i,s,r,n;if(this.fire("destroyed",this.destroyed=!0),this._attachments)for(e in this._attachments)if(this._attachments.hasOwnProperty(e)){for(i=(t=this._attachments[e]).component,r=0,n=(s=t.subs).length;r<n;r++)i.off(s[r]);t.managingLifecycle&&i.destroy()}if(this._ownedComponents)for(e in this._ownedComponents)this._ownedComponents.hasOwnProperty(e)&&((i=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}(),me=1,ve=4,ge=8,_e=16,ye=32,be=256,xe=512,Pe=1024,Te=2048,we=new Float32Array([0,0,0]),Me=new Uint16Array([0,0,0]),Ie=function(){function e(t,i,s,r,n,o){w(this,e),this._isObject=i,this.scene=t.scene,this.model=t,this.meshes=r,this._numTriangles=0;for(var a=0,u=this.meshes.length;a<u;a++){var h=this.meshes[a];h.parent=this,this._numTriangles+=h.numTriangles}this.id=s,this.originalSystemId=q.unglobalizeObjectId(t.id,s),this._flags=n,this._aabb=o,this._offsetAABB=q.AABB3(o),this._offset=q.vec3(),this._colorizeUpdated=!1,this._opacityUpdated=!1,this._culled=!1,this._culledVFC=!1,this._culledLOD=!1,this._isObject&&t.scene._registerObject(this)}return I(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:"numTriangles",get:function(){return this._numTriangles}},{key:"visible",get:function(){return this._getFlag(me)},set:function(e){if(!!(this._flags&me)!==e){this._flags=e?this._flags|me:this._flags&~me;for(var t=0,i=this.meshes.length;t<i;t++)this.meshes[t]._setVisible(this._flags);this._isObject&&this.model.scene._objectVisibilityUpdated(this),this.model.glRedraw()}}},{key:"highlighted",get:function(){return this._getFlag(xe)},set:function(e){if(!!(this._flags&xe)!==e){this._flags=e?this._flags|xe:this._flags&~xe;for(var t=0,i=this.meshes.length;t<i;t++)this.meshes[t]._setHighlighted(this._flags);this._isObject&&this.model.scene._objectHighlightedUpdated(this),this.model.glRedraw()}}},{key:"xrayed",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,i=this.meshes.length;t<i;t++)this.meshes[t]._setXRayed(this._flags);this._isObject&&this.model.scene._objectXRayedUpdated(this),this.model.glRedraw()}}},{key:"selected",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,i=this.meshes.length;t<i;t++)this.meshes[t]._setSelected(this._flags);this._isObject&&this.model.scene._objectSelectedUpdated(this),this.model.glRedraw()}}},{key:"edges",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,i=this.meshes.length;t<i;t++)this.meshes[t]._setEdges(this._flags);this.model.glRedraw()}}},{key:"culledVFC",get:function(){return!!this._culledVFC},set:function(e){this._culledVFC=e,this.internalSetCulled()}},{key:"culledLOD",get:function(){return!!this._culledLOD},set:function(e){this._culledLOD=e,this.internalSetCulled()}},{key:"culled",get:function(){return!!this._culled},set:function(e){this._culled=e,this.internalSetCulled()}},{key:"internalSetCulled",value:function(){var e=!!this._culled||!!this._culledLOD||!!this._culledVFC;if(!!(this._flags&ve)!==e){this._flags=e?this._flags|ve:this._flags&~ve;for(var t=0,i=this.meshes.length;t<i;t++)this.meshes[t]._setCulled(this._flags);this.model.glRedraw()}}},{key:"clippable",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,i=this.meshes.length;t<i;t++)this.meshes[t]._setClippable(this._flags);this.model.glRedraw()}}},{key:"collidable",get:function(){return this._getFlag(ye)},set:function(e){if(!!(this._flags&ye)!==e){this._flags=e?this._flags|ye:this._flags&~ye;for(var t=0,i=this.meshes.length;t<i;t++)this.meshes[t]._setCollidable(this._flags)}}},{key:"pickable",get:function(){return this._getFlag(ge)},set:function(e){if(!!(this._flags&ge)!==e){this._flags=e?this._flags|ge:this._flags&~ge;for(var t=0,i=this.meshes.length;t<i;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 we[0]=e[0]/255,we[1]=e[1]/255,we[2]=e[2]/255,we},set:function(e){if(e){Me[0]=Math.floor(255*e[0]),Me[1]=Math.floor(255*e[1]),Me[2]=Math.floor(255*e[2]);for(var t=0,i=this.meshes.length;t<i;t++)this.meshes[t]._setColorize(Me)}else for(var s=0,r=this.meshes.length;s<r;s++)this.meshes[s]._setColorize(null);if(this._isObject){var n=!!e;this.scene._objectColorizeUpdated(this,n),this._colorizeUpdated=n}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,i=this.meshes[0]._colorize[3],s=255;if(t){if(e<0?e=0:e>1&&(e=1),i===(s=Math.floor(255*e)))return}else if(i===(s=255))return;for(var r=0,n=this.meshes.length;r<n;r++)this.meshes[r]._setOpacity(s,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,i=this.meshes.length;t<i;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:"castsShadow",get:function(){return!1},set:function(e){}},{key:"receivesShadow",get:function(){return!1},set:function(e){}},{key:"saoEnabled",get:function(){return this.model.saoEnabled}},{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,i=this.meshes.length;t<i;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,i=this.meshes.length;t<i;t++)this.meshes[t]._destroy();e._aabbDirty=!0}}]),e}(),Ce=q.vec3(),De=function(){var e=new Float64Array(16),t=new Float64Array(4),i=new Float64Array(4);return function(s,r,n){return n=n||e,t[0]=r[0],t[1]=r[1],t[2]=r[2],t[3]=1,q.transformVec4(s,t,i),q.setMat4Translation(s,i,n),n.slice()}}();function Ae(e,t,i){var s=Float32Array.from([e[0]])[0],r=e[0]-s,n=Float32Array.from([e[1]])[0],o=e[1]-n,a=Float32Array.from([e[2]])[0],u=e[2]-a;t[0]=s,t[1]=n,t[2]=a,i[0]=r,i[1]=o,i[2]=u}function ke(e,t,i){var s=arguments.length>3&&void 0!==arguments[3]?arguments[3]:1e3,r=q.getPositionsCenter(e,Ce),n=Math.round(r[0]/s)*s,o=Math.round(r[1]/s)*s,a=Math.round(r[2]/s)*s;i[0]=n,i[1]=o,i[2]=a;var u=0!==i[0]||0!==i[1]||0!==i[2];if(u)for(var h=0,l=e.length;h<l;h+=3)t[h+0]=e[h+0]-n,t[h+1]=e[h+1]-o,t[h+2]=e[h+2]-a;return u}function Ee(e,t,i,s){var r=q.dotVec3(t,i)+e,n=q.normalizeVec3(t,Ce);return q.mulVec3Scalar(n,-r,s),s}var Fe=q.vec4(),Re=q.vec4(),Se=function(e){g(i,fe);var t=y(i);function i(e,s){var r;return w(this,i),(r=t.call(this,e,s))._entity=null,r._visible=null,r._worldPos=q.vec3(),r._origin=q.vec3(),r._rtcPos=q.vec3(),r._viewPos=q.vec3(),r._canvasPos=q.vec2(),r._occludable=!1,r._onCameraViewMatrix=r.scene.camera.on("matrix",(function(){r._viewPosDirty=!0,r._needUpdate()})),r._onCameraProjMatrix=r.scene.camera.on("projMatrix",(function(){r._canvasPosDirty=!0,r._needUpdate()})),r._onEntityDestroyed=null,r._onEntityModelDestroyed=null,r._renderer.addMarker(x(r)),r.entity=s.entity,r.worldPos=s.worldPos,r.occludable=s.occludable,r}return I(i,[{key:"_update",value:function(){if(this._viewPosDirty&&(q.transformPoint3(this.scene.camera.viewMatrix,this._worldPos,this._viewPos),this._viewPosDirty=!1,this._canvasPosDirty=!0,this.fire("viewPos",this._viewPos)),this._canvasPosDirty){Fe.set(this._viewPos),Fe[3]=1,q.transformPoint4(this.scene.camera.projMatrix,Fe,Re);var e=this.scene.canvas.boundary;this._canvasPos[0]=Math.floor((1+Re[0]/Re[3])*e[2]/2),this._canvasPos[1]=Math.floor((1-Re[1]/Re[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 Ie?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]),Ae(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),m(P(i.prototype),"destroy",this).call(this)}}]),i}(),Oe=function(){function e(t){var i=this,s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};w(this,e),this._color=s.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=s.thickness||1,this._thicknessClickable=s.thicknessClickable||6;var r=this._wire,n=r.style;n.border="solid "+this._thickness+"px "+this._color,n.position="absolute",n["z-index"]=void 0===s.zIndex?"2000001":s.zIndex,n.width="0px",n.height="0px",n.visibility="visible",n.top="0px",n.left="0px",n["-webkit-transform-origin"]="0 0",n["-moz-transform-origin"]="0 0",n["-ms-transform-origin"]="0 0",n["-o-transform-origin"]="0 0",n["transform-origin"]="0 0",n["-webkit-transform"]="rotate(0deg)",n["-moz-transform"]="rotate(0deg)",n["-ms-transform"]="rotate(0deg)",n["-o-transform"]="rotate(0deg)",n.transform="rotate(0deg)",n.opacity=1,n["pointer-events"]="none",s.onContextMenu,t.appendChild(r);var o=this._wireClickable,a=o.style;a.border="solid "+this._thicknessClickable+"px "+this._color,a.position="absolute",a["z-index"]=void 0===s.zIndex?"2000002":s.zIndex+1,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=0,a["pointer-events"]="all",s.onContextMenu,t.appendChild(o),s.onMouseOver&&o.addEventListener("mouseover",(function(e){s.onMouseOver(e,i)})),s.onMouseLeave&&o.addEventListener("mouseleave",(function(e){s.onMouseLeave(e,i)})),s.onContextMenu&&o.addEventListener("contextmenu",(function(e){s.onContextMenu(e,i),e.preventDefault()})),this._x1=0,this._y1=0,this._x2=0,this._y2=0,this._update()}return I(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,i=this._wire.style;i.width=Math.round(e)+"px",i.left=Math.round(this._x1)+"px",i.top=Math.round(this._y1)+"px",i["-webkit-transform"]="rotate("+t+"deg)",i["-moz-transform"]="rotate("+t+"deg)",i["-ms-transform"]="rotate("+t+"deg)",i["-o-transform"]="rotate("+t+"deg)",i.transform="rotate("+t+"deg)";var s=this._wireClickable.style;s.width=Math.round(e)+"px",s.left=Math.round(this._x1)+"px",s.top=Math.round(this._y1)+"px",s["-webkit-transform"]="rotate("+t+"deg)",s["-moz-transform"]="rotate("+t+"deg)",s["-ms-transform"]="rotate("+t+"deg)",s["-o-transform"]="rotate("+t+"deg)",s.transform="rotate("+t+"deg)"}},{key:"setStartAndEnd",value:function(e,t,i,s){this._x1=e,this._y1=t,this._x2=i,this._y2=s,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.removeChild(this._wire),this._wireClickable.parentElement.removeChild(this._wireClickable)}}]),e}(),Be=function(){function e(t){var i=this,s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};w(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 r=this._dot,n=r.style;n["border-radius"]="25px",n.border="solid 2px white",n.background="lightgreen",n.position="absolute",n["z-index"]=void 0===s.zIndex?"40000005":s.zIndex,n.width="8px",n.height="8px",n.visibility=!1!==s.visible?"visible":"hidden",n.top="0px",n.left="0px",n["box-shadow"]="0 2px 5px 0 #182A3D;",n.opacity=1,n["pointer-events"]="none",s.onContextMenu,t.appendChild(r);var o=this._dotClickable,a=o.style;a["border-radius"]="35px",a.border="solid 10px white",a.position="absolute",a["z-index"]=void 0===s.zIndex?"40000007":s.zIndex+1,a.width="8px",a.height="8px",a.visibility="visible",a.top="0px",a.left="0px",a.opacity=0,a["pointer-events"]="none",s.onContextMenu,t.appendChild(o),s.onMouseOver&&o.addEventListener("mouseover",(function(e){s.onMouseOver(e,i)})),s.onMouseLeave&&o.addEventListener("mouseleave",(function(e){s.onMouseLeave(e,i)})),s.onContextMenu&&o.addEventListener("contextmenu",(function(e){s.onContextMenu(e,i),e.preventDefault()})),this.setPos(s.x||0,s.y||0),this.setFillColor(s.fillColor),this.setBorderColor(s.borderColor)}return I(e,[{key:"setPos",value:function(e,t){this._x=e,this._y=t;var i=this._dot.style;i.left=Math.round(e)-4+"px",i.top=Math.round(t)-4+"px";var s=this._dotClickable.style;s.left=Math.round(e)-9+"px",s.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.removeChild(this._dot),this._dotClickable.parentElement.removeChild(this._dotClickable)}}]),e}(),Le=function(){function e(t){var i=this,s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};w(this,e),this._highlightClass="viewer-ruler-label-highlighted",this._prefix=s.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 r=this._label,n=r.style;n["border-radius"]="5px",n.color="white",n.padding="4px",n.border="solid 1px",n.background="lightgreen",n.position="absolute",n["z-index"]=void 0===s.zIndex?"5000005":s.zIndex,n.width="auto",n.height="auto",n.visibility="visible",n.top="0px",n.left="0px",n["pointer-events"]="all",n.opacity=1,s.onContextMenu,r.innerText="",t.appendChild(r),this.setPos(s.x||0,s.y||0),this.setFillColor(s.fillColor),this.setBorderColor(s.fillColor),this.setText(s.text),s.onMouseOver&&r.addEventListener("mouseover",(function(e){s.onMouseOver(e,i),e.preventDefault()})),s.onMouseLeave&&r.addEventListener("mouseleave",(function(e){s.onMouseLeave(e,i),e.preventDefault()})),s.onContextMenu&&r.addEventListener("contextmenu",(function(e){s.onContextMenu(e,i),e.preventDefault()}))}return I(e,[{key:"setPos",value:function(e,t){this._x=e,this._y=t;var i=this._label.style;i.left=Math.round(e)-20+"px",i.top=Math.round(t)-12+"px"}},{key:"setPosOnWire",value:function(e,t,i,s){var r=e+.5*(i-e),n=t+.5*(s-t),o=this._label.style;o.left=Math.round(r)-20+"px",o.top=Math.round(n)-12+"px"}},{key:"setPosBetweenWires",value:function(e,t,i,s,r,n){var o=(e+i+r)/3,a=(t+s+n)/3,u=this._label.style;u.left=Math.round(o)-20+"px",u.top=Math.round(a)-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.removeChild(this._label)}}]),e}(),Ne=q.vec3(),je=q.vec3(),Ge=function(e){g(i,fe);var t=y(i);function i(e){var s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(w(this,i),(s=t.call(this,e.viewer.scene,r)).plugin=e,s._container=r.container,!s._container)throw"config missing: container";s._color=r.color||e.defaultColor;var n=s.plugin.viewer.scene;s._originMarker=new Se(n,r.origin),s._cornerMarker=new Se(n,r.corner),s._targetMarker=new Se(n,r.target),s._originWorld=q.vec3(),s._cornerWorld=q.vec3(),s._targetWorld=q.vec3(),s._wp=new Float64Array(12),s._vp=new Float64Array(12),s._pp=new Float64Array(12),s._cp=new Int16Array(6);var o=r.onMouseOver?function(e){r.onMouseOver(e,x(s))}:null,a=r.onMouseLeave?function(e){r.onMouseLeave(e,x(s))}:null,u=r.onContextMenu?function(e){r.onContextMenu(e,x(s))}:null;return s._originDot=new Be(s._container,{fillColor:s._color,zIndex:void 0!==e.zIndex?e.zIndex+2:void 0,onMouseOver:o,onMouseLeave:a,onContextMenu:u}),s._cornerDot=new Be(s._container,{fillColor:s._color,zIndex:void 0!==e.zIndex?e.zIndex+2:void 0,onMouseOver:o,onMouseLeave:a,onContextMenu:u}),s._targetDot=new Be(s._container,{fillColor:s._color,zIndex:void 0!==e.zIndex?e.zIndex+2:void 0,onMouseOver:o,onMouseLeave:a,onContextMenu:u}),s._originWire=new Oe(s._container,{color:s._color||"blue",thickness:1,zIndex:e.zIndex,onMouseOver:o,onMouseLeave:a,onContextMenu:u}),s._targetWire=new Oe(s._container,{color:s._color||"red",thickness:1,zIndex:void 0!==e.zIndex?e.zIndex+1:void 0,onMouseOver:o,onMouseLeave:a,onContextMenu:u}),s._angleLabel=new Le(s._container,{fillColor:s._color||"#00BBFF",prefix:"",text:"",zIndex:e.zIndex+2,onMouseOver:o,onMouseLeave:a,onContextMenu:u}),s._wpDirty=!1,s._vpDirty=!1,s._cpDirty=!1,s._visible=!1,s._originVisible=!1,s._cornerVisible=!1,s._targetVisible=!1,s._originWireVisible=!1,s._targetWireVisible=!1,s._angleVisible=!1,s._labelsVisible=!1,s._clickable=!1,s._originMarker.on("worldPos",(function(e){s._originWorld.set(e||[0,0,0]),s._wpDirty=!0,s._needUpdate(0)})),s._cornerMarker.on("worldPos",(function(e){s._cornerWorld.set(e||[0,0,0]),s._wpDirty=!0,s._needUpdate(0)})),s._targetMarker.on("worldPos",(function(e){s._targetWorld.set(e||[0,0,0]),s._wpDirty=!0,s._needUpdate(0)})),s._onViewMatrix=n.camera.on("viewMatrix",(function(){s._vpDirty=!0,s._needUpdate(0)})),s._onProjMatrix=n.camera.on("projMatrix",(function(){s._cpDirty=!0,s._needUpdate()})),s._onCanvasBoundary=n.canvas.on("boundary",(function(){s._cpDirty=!0,s._needUpdate(0)})),s.approximate=r.approximate,s.visible=r.visible,s.originVisible=r.originVisible,s.cornerVisible=r.cornerVisible,s.targetVisible=r.targetVisible,s.originWireVisible=r.originWireVisible,s.targetWireVisible=r.targetWireVisible,s.angleVisible=r.angleVisible,s.labelsVisible=r.labelsVisible,s}return I(i,[{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&&(q.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,i=this._originMarker.viewPos[2],s=this._cornerMarker.viewPos[2],r=this._targetMarker.viewPos[2];if(i>t||s>t||r>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);q.transformPositions4(e.camera.project.matrix,this._vp,this._pp);for(var n=this._pp,o=this._cp,a=e.canvas.canvas.getBoundingClientRect(),u=this._container.getBoundingClientRect(),h=a.top-u.top,l=a.left-u.left,c=e.canvas.boundary,p=c[2],d=c[3],f=0,m=0,v=n.length;m<v;m+=4)o[f]=l+Math.floor((1+n[m+0]/n[m+3])*p/2),o[f+1]=h+Math.floor((1-n[m+1]/n[m+3])*d/2),f+=2;if(this._originDot.setPos(o[0],o[1]),this._cornerDot.setPos(o[2],o[3]),this._targetDot.setPos(o[4],o[5]),this._originWire.setStartAndEnd(o[0],o[1],o[2],o[3]),this._targetWire.setStartAndEnd(o[2],o[3],o[4],o[5]),this._angleLabel.setPosBetweenWires(o[0],o[1],o[2],o[3],o[4],o[5]),q.subVec3(this._originWorld,this._cornerWorld,Ne),q.subVec3(this._targetWorld,this._cornerWorld,je),!(0===Ne[0]&&0===Ne[1]&&0===Ne[2]||0===je[0]&&0===je[1]&&0===je[2])){var g=this._approximate?" ~ ":" = ";q.normalizeVec3(Ne),q.normalizeVec3(je);var _=Math.abs(q.angleVec3(Ne,je));this._angle=_/q.DEGTORAD,this._angleLabel.setText(g+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(),m(P(i.prototype),"destroy",this).call(this)}}]),i}(),He=function(e){g(i,fe);var t=y(i);function i(e){var s;return w(this,i),(s=t.call(this,e.viewer.scene)).plugin=e,s._active=!1,s._state=0,s._currentAngleMeasurement=null,s._onMouseHoverSurface=null,s._onHoverNothing=null,s._onMouseHoverOff=null,s._onPickedNothing=null,s._onPickedSurface=null,s._onInputMouseDown=null,s._onInputMouseUp=null,s._onCanvasTouchStart=null,s._onCanvasTouchEnd=null,s}return I(i,[{key:"active",get:function(){return this._active}},{key:"activate",value:function(){var e=this;if(!this._active){var t,i,s=this.plugin,r=this.scene,n=s.viewer.cameraControl,o=r.canvas.canvas,a=r.input,u=r.pickSurfacePrecisionEnabled,h=!1,l=null,c=q.vec3(),p=q.vec2(),d=q.vec2(),f=q.vec2();q.vec3(),this._onMouseHoverSurface=n.on("hoverSurface",(function(t){if(h=!0,l=t.entity,c.set(t.worldPos),p.set(t.canvasPos),e._currentAngleMeasurement)switch(e._state){case 1:e._currentAngleMeasurement.originWireVisible=!0,e._currentAngleMeasurement.targetWireVisible=!1,e._currentAngleMeasurement.cornerVisible=!0,e._currentAngleMeasurement.angleVisible=!1,e._currentAngleMeasurement.corner.entity=t.entity,e._currentAngleMeasurement.corner.worldPos=t.worldPos,o.style.cursor="pointer";break;case 2:e._currentAngleMeasurement.targetWireVisible=!0,e._currentAngleMeasurement.targetVisible=!0,e._currentAngleMeasurement.angleVisible=!0,e._currentAngleMeasurement.target.entity=t.entity,e._currentAngleMeasurement.target.worldPos=t.worldPos,o.style.cursor="pointer"}})),this._onInputMouseDown=a.on("mousedown",(function(e){t=e[0],i=e[1]})),this._onInputMouseUp=a.on("mouseup",(function(s){if(!(s[0]>t+5||s[0]<t-5||s[1]>i+5||s[1]<i-5))switch(e._state){case 0:if(h){if(u){var n=r.pick({canvasPos:p,pickSurface:!0,pickSurfacePrecision:u});n&&n.worldPos&&worldPos.set(n.worldPos)}e._currentAngleMeasurement=e.plugin.createMeasurement({id:q.createUUID(),origin:{entity:l,worldPos:c},corner:{entity:l,worldPos:c},target:{entity:l,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:if(h){if(u){var o=r.pick({canvasPos:p,pickSurface:!0,pickSurfacePrecision:!0});o&&o.worldPos&&(e._currentAngleMeasurement.corner.worldPos=o.worldPos)}e._currentAngleMeasurement.targetWireVisible=!1,e._currentAngleMeasurement.targetVisible=!0,e._currentAngleMeasurement.angleVisible=!0,e._state=2}else e._currentAngleMeasurement&&(e._currentAngleMeasurement.destroy(),e._currentAngleMeasurement=null,e._state=0,e.fire("measurementCancel",e._currentAngleMeasurement));break;case 2:if(h){if(u){var a=r.pick({canvasPos:p,pickSurface:!0,pickSurfacePrecision:!0});a&&a.worldPos&&(e._currentAngleMeasurement.target.worldPos=a.worldPos,e._currentAngleMeasurement.approximate=!1)}e._currentAngleMeasurement.targetVisible=!0,e._currentAngleMeasurement.angleVisible=!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))}})),this._onHoverNothing=n.on("hoverOff",(function(t){if(h=!1,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}o.style.cursor="default"}})),o.addEventListener("touchstart",this._onCanvasTouchStart=function(e){var t=e.touches,i=e.changedTouches;1===t.length&&1===i.length&&Ve(t[0],d)},{passive:!0}),o.addEventListener("touchend",this._onCanvasTouchEnd=function(t){var i=t.touches,s=t.changedTouches;if(0===i.length&&1===s.length){if(Ve(s[0],f),f[0]>d[0]+5||f[0]<d[0]-5||f[1]>d[1]+5||f[1]<d[1]-5)return;var n=r.pick({canvasPos:f,pickSurface:!0,pickSurfacePrecision:!1});if(n&&n.worldPos)switch(e._state){case 0:e._currentAngleMeasurement=e.plugin.createMeasurement({id:q.createUUID(),origin:{entity:n.entity,worldPos:n.worldPos},corner:{entity:n.entity,worldPos:n.worldPos},target:{entity:n.entity,worldPos:n.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=n.worldPos,e._currentAngleMeasurement.targetWireVisible=!1,e._currentAngleMeasurement.targetVisible=!0,e._currentAngleMeasurement.angleVisible=!0,e._state=2;break;case 2:e._currentAngleMeasurement.target.worldPos=n.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,i=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),i.removeEventListener("touchstart",this._onCanvasTouchStart),i.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(),m(P(i.prototype),"destroy",this).call(this)}}]),i}(),Ve=function(e,t){if(e){for(var i=e.target,s=0,r=0;i.offsetParent;)s+=i.offsetLeft,r+=i.offsetTop,i=i.offsetParent;t[0]=e.pageX-s,t[1]=e.pageY-r}else e=window.event,t[0]=e.x,t[1]=e.y;return t},Ue=function(e){g(i,X);var t=y(i);function i(e){var s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return w(this,i),(s=t.call(this,"AngleMeasurements",e))._container=r.container||document.body,s._control=new He(x(s)),s._measurements={},s.defaultColor=void 0!==r.defaultColor?r.defaultColor:"#00BBFF",s.defaultLabelsVisible=!1!==r.defaultLabelsVisible,s.zIndex=r.zIndex||1e4,s._onMouseOver=function(e,t){s.fire("mouseOver",{plugin:x(s),angleMeasurement:t,measurement:t,event:e})},s._onMouseLeave=function(e,t){s.fire("mouseLeave",{plugin:x(s),angleMeasurement:t,measurement:t,event:e})},s._onContextMenu=function(e,t){s.fire("contextMenu",{plugin:x(s),angleMeasurement:t,measurement:t,event:e})},s}return I(i,[{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 i=t.origin,s=t.corner,r=t.target,n=new Ge(this,{id:t.id,plugin:this,container:this._container,origin:{entity:i.entity,worldPos:i.worldPos},corner:{entity:s.entity,worldPos:s.worldPos},target:{entity:r.entity,worldPos:r.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[n.id]=n,n.on("destroyed",(function(){delete e._measurements[n.id]})),this.fire("measurementCreated",n),n}},{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,i=Object.entries(this.measurements);t<i.length;t++){var s=p(i[t],2);s[0];s[1].labelShown=e}}},{key:"clear",value:function(){for(var e=Object.keys(this._measurements),t=0,i=e.length;t<i;t++)this.destroyMeasurement(e[t])}},{key:"destroy",value:function(){this.clear(),m(P(i.prototype),"destroy",this).call(this)}}]),i}(),ze=function(e){g(i,Se);var t=y(i);function i(e,s){var r;if(w(this,i),(r=t.call(this,e,s)).plugin=s.plugin,r._container=s.container,!r._container)throw"config missing: container";if(!s.markerElement&&!s.markerHTML)throw"config missing: need either markerElement or markerHTML";if(!s.labelElement&&!s.labelHTML)throw"config missing: need either labelElement or labelHTML";return r._htmlDirty=!1,s.markerElement?(r._marker=s.markerElement,r._marker.addEventListener("click",r._onMouseClickedExternalMarker=function(){r.plugin.fire("markerClicked",x(r))}),r._marker.addEventListener("mouseenter",r._onMouseEnterExternalMarker=function(){r.plugin.fire("markerMouseEnter",x(r))}),r._marker.addEventListener("mouseleave",r._onMouseLeaveExternalMarker=function(){r.plugin.fire("markerMouseLeave",x(r))}),r._markerExternal=!0):(r._markerHTML=s.markerHTML,r._htmlDirty=!0,r._markerExternal=!1),s.labelElement?(r._label=s.labelElement,r._labelExternal=!0):(r._labelHTML=s.labelHTML,r._htmlDirty=!0,r._labelExternal=!1),r._markerShown=!!s.markerShown,r._labelShown=!!s.labelShown,r._values=s.values||{},r._layoutDirty=!0,r._visibilityDirty=!0,r._buildHTML(),r._onTick=r.scene.on("tick",(function(){r._htmlDirty&&(r._buildHTML(),r._htmlDirty=!1,r._layoutDirty=!0,r._visibilityDirty=!0),(r._layoutDirty||r._visibilityDirty)&&(r._markerShown||r._labelShown)&&(r._updatePosition(),r._layoutDirty=!1),r._visibilityDirty&&(r._marker.style.visibility=r.visible&&r._markerShown?"visible":"hidden",r._label.style.visibility=r.visible&&r._markerShown&&r._labelShown?"visible":"hidden",r._visibilityDirty=!1)})),r.on("canvasPos",(function(){r._layoutDirty=!0})),r.on("visible",(function(){r._visibilityDirty=!0})),r.setMarkerShown(!1!==s.markerShown),r.setLabelShown(s.labelShown),r.eye=s.eye?s.eye.slice():null,r.look=s.look?s.look.slice():null,r.up=s.up?s.up.slice():null,r.projection=s.projection,r}return I(i,[{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>";re.isArray(t)&&(t=t.join("")),t=this._renderTemplate(t);var i=document.createRange().createContextualFragment(t);this._marker=i.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)}))}if(!this._labelExternal){this._label&&(this._container.removeChild(this._label),this._label=null);var s=this._labelHTML||"<p></p>";re.isArray(s)&&(s=s.join("")),s=this._renderTemplate(s);var r=document.createRange().createContextualFragment(s);this._label=r.firstChild,this._container.appendChild(this._label),this._label.style.visibility=this._markerShown&&this._labelShown?"visible":"hidden"}}},{key:"_updatePosition",value:function(){var e=this.scene.canvas.boundary,t=e[0],i=e[1],s=this.canvasPos;this._marker.style.left=Math.floor(t+s[0])-12+"px",this._marker.style.top=Math.floor(i+s[1])-12+"px",this._marker.style["z-index"]=cfg._markerZIndex;this._label.style.left=20+Math.floor(t+s[0]+20)+"px",this._label.style.top=Math.floor(i+s[1]+-17)+"px",this._label.style["z-index"]=cfg._labelZIndex}},{key:"_renderTemplate",value:function(e){for(var t in this._values)if(this._values.hasOwnProperty(t)){var i=this._values[t];e=e.replace(new RegExp("{{"+t+"}}","g"),i)}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 i=e[t];this.setField(t,i)}}},{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),m(P(i.prototype),"destroy",this).call(this)}}]),i}(),We=q.vec3(),Xe=q.vec3(),Ye=q.vec3(),Ke=function(e){g(i,X);var t=y(i);function i(e,s){var r;w(this,i),r=t.call(this,"Annotations",e);var n=90005+Math.floor(r._viewPos[2])+1;return r._labelHTML=s.labelHTML||"<div></div>",r._markerHTML=s.markerHTML||"<div></div>",r._container=s.container||document.body,r._markerZIndex=s.markerZIndex||n,r._labelZIndex=s.labelZIndex||n,r._values=s.values||{},r.annotations={},r.surfaceOffset=s.surfaceOffset,r}return I(i,[{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,i,s=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 r=e.pickResult;if(r.worldPos&&r.worldNormal){var n=q.normalizeVec3(r.worldNormal,We),o=q.mulVec3Scalar(n,this._surfaceOffset,Xe);t=q.addVec3(r.worldPos,o,Ye),i=r.entity}else this.error("Param 'pickResult' does not have both worldPos and worldNormal")}else t=e.worldPos,i=e.entity;var a=null;e.markerElementId&&((a=document.getElementById(e.markerElementId))||this.error("Can't find DOM element for 'markerElementId' value '"+e.markerElementId+"' - defaulting to internally-generated empty DIV"));var u=null;e.labelElementId&&((u=document.getElementById(e.labelElementId))||this.error("Can't find DOM element for 'labelElementId' value '"+e.labelElementId+"' - defaulting to internally-generated empty DIV"));var h=new ze(this.viewer.scene,{id:e.id,plugin:this,entity:i,worldPos:t,container:this._container,markerElement:a,labelElement:u,markerHTML:e.markerHTML||this._markerHTML,markerZIndex:e.markerZIndex||this._markerZIndex,labelHTML:e.labelHTML||this._labelHTML,labelZIndex:e.labelZIndex||this._labelZIndex,occludable:e.occludable,values:re.apply(e.values,re.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[h.id]=h,h.on("destroyed",(function(){delete s.annotations[h.id],s.fire("annotationDestroyed",h.id)})),this.fire("annotationCreated",h.id),h}},{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,i=e.length;t<i;t++)this.destroyAnnotation(e[t])}},{key:"destroy",value:function(){this.clear(),m(P(i.prototype),"destroy",this).call(this)}}]),i}(),Je=function(e){g(i,fe);var t=y(i);function i(e){var s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return w(this,i),(s=t.call(this,e,r))._canvas=r.canvas,s._element=null,s._isCustom=!1,r.elementId&&(s._element=document.getElementById(r.elementId),s._element?s._adjustPosition():s.error("Can't find given Spinner HTML element: '"+r.elementId+"' - will automatically create default element")),s._element||s._createDefaultSpinner(),s.processes=0,s}return I(i,[{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,i=t.style;i.left=e.offsetLeft+.5*e.clientWidth-.5*t.clientWidth+"px",i.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 i=this._element;i&&(i.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)}}]),i}(),Ze={WEBGL:!1,SUPPORTED_EXTENSIONS:{}},Qe=document.createElement("canvas");if(Qe){var qe=Qe.getContext("webgl",{antialias:!0})||Qe.getContext("experimental-webgl",{antialias:!0});Ze.WEBGL=!!qe,Ze.WEBGL&&(Ze.ANTIALIAS=qe.getContextAttributes().antialias,qe.getShaderPrecisionFormat?qe.getShaderPrecisionFormat(qe.FRAGMENT_SHADER,qe.HIGH_FLOAT).precision>0?Ze.FS_MAX_FLOAT_PRECISION="highp":qe.getShaderPrecisionFormat(qe.FRAGMENT_SHADER,qe.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=qe.getParameter(qe.DEPTH_BITS),Ze.MAX_TEXTURE_SIZE=qe.getParameter(qe.MAX_TEXTURE_SIZE),Ze.MAX_CUBE_MAP_SIZE=qe.getParameter(qe.MAX_CUBE_MAP_TEXTURE_SIZE),Ze.MAX_RENDERBUFFER_SIZE=qe.getParameter(qe.MAX_RENDERBUFFER_SIZE),Ze.MAX_TEXTURE_UNITS=qe.getParameter(qe.MAX_COMBINED_TEXTURE_IMAGE_UNITS),Ze.MAX_TEXTURE_IMAGE_UNITS=qe.getParameter(qe.MAX_TEXTURE_IMAGE_UNITS),Ze.MAX_VERTEX_ATTRIBS=qe.getParameter(qe.MAX_VERTEX_ATTRIBS),Ze.MAX_VERTEX_UNIFORM_VECTORS=qe.getParameter(qe.MAX_VERTEX_UNIFORM_VECTORS),Ze.MAX_FRAGMENT_UNIFORM_VECTORS=qe.getParameter(qe.MAX_FRAGMENT_UNIFORM_VECTORS),Ze.MAX_VARYING_VECTORS=qe.getParameter(qe.MAX_VARYING_VECTORS),qe.getSupportedExtensions().forEach((function(e){Ze.SUPPORTED_EXTENSIONS[e]=!0})))}var $e=["webgl2","experimental-webgl","webkit-3d","moz-webgl","moz-glweb20"],et=function(e){g(i,fe);var t=y(i);function i(e){var s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};w(this,i),(s=t.call(this,e,r))._backgroundColor=q.vec3([r.backgroundColor?r.backgroundColor[0]:1,r.backgroundColor?r.backgroundColor[1]:1,r.backgroundColor?r.backgroundColor[2]:1]),s._backgroundColorFromAmbientLight=!!r.backgroundColorFromAmbientLight,s.canvas=r.canvas,s.gl=null,s.webgl2=!1,s.transparent=!!r.transparent,s.optimizeResizeDetection=!0,s.contextAttr=r.contextAttr||{},s.contextAttr.alpha=s.transparent,s.contextAttr.preserveDrawingBuffer=!!s.contextAttr.preserveDrawingBuffer,s.contextAttr.stencil=!1,s.contextAttr.premultipliedAlpha=!!s.contextAttr.premultipliedAlpha,s.contextAttr.antialias=!1!==s.contextAttr.antialias,s.resolutionScale=r.resolutionScale,s.canvas.width=Math.round(s.canvas.clientWidth*s._resolutionScale),s.canvas.height=Math.round(s.canvas.clientHeight*s._resolutionScale),s.boundary=[s.canvas.offsetLeft,s.canvas.offsetTop,s.canvas.clientWidth,s.canvas.clientHeight],s._initWebGL(r);var n=x(s);s.canvas.addEventListener("webglcontextlost",s._webglcontextlostListener=function(e){console.time("webglcontextrestored"),n.scene._webglContextLost(),n.fire("webglcontextlost"),e.preventDefault()},!1),s.canvas.addEventListener("webglcontextrestored",s._webglcontextrestoredListener=function(e){n._initWebGL(),n.gl&&(n.scene._webglContextRestored(n.gl),n.fire("webglcontextrestored",n.gl),e.preventDefault()),console.timeEnd("webglcontextrestored")},!1);var o=null,a=null,u=null,h=null,l=null,c=null,p=null,d=null,f=0;return s._tick=s.scene.on("tick",(function(){if(f++,n._canvasSizeChanged=!1,!(n.optimizeResizeDetection&&f<10)){f=0;var e=s.canvas,t=s._resolutionScale!==o,i=window.innerWidth!==a||window.innerHeight!==u,r=e.clientWidth!==h||e.clientHeight!==l,m=e.offsetLeft!==c||e.offsetTop!==p,v=e.parentElement;if(t||i||r||m||v!==d){if(n._canvasSizeChanged=!0,s._spinner._adjustPosition(),t||r||m){var g=e.clientWidth,_=e.clientHeight;if(t||r){var y,b=0;for(var x in pe.scenes)pe.scenes.hasOwnProperty(x)&&(y=pe.scenes[x],b+=Math.round(y.canvas.canvas.clientWidth*s._resolutionScale*(y.canvas.canvas.clientHeight*s._resolutionScale)));ee.memory.pixels=b,e.width=Math.round(e.clientWidth*s._resolutionScale),e.height=Math.round(e.clientHeight*s._resolutionScale)}var P=s.boundary;P[0]=e.offsetLeft,P[1]=e.offsetTop,P[2]=g,P[3]=_,t||s.fire("boundary",P),h=g,l=_}t&&(o=s._resolutionScale),i&&(a=window.innerWidth,u=window.innerHeight),m&&(c=e.offsetLeft,p=e.offsetTop),d=v}}})),s._spinner=new Je(s.scene,{canvas:s.canvas,elementId:r.spinnerElementId}),s}return I(i,[{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-"+q.createUUID(),t=document.getElementsByTagName("body")[0],i=document.createElement("div"),s=i.style;s.height="100%",s.width="100%",s.padding="0",s.margin="0",s.background="rgba(0,0,0,0);",s.float="left",s.left="0",s.top="0",s.position="absolute",s.opacity="1.0",s["z-index"]="-10000",i.innerHTML+='<canvas id="'+e+'" style="width: 100%; height: 100%; float: left; margin: 0; padding: 0;"></canvas>',t.appendChild(i),this.canvas=document.getElementById(e)}},{key:"_getElementXY",value:function(e){for(var t=0,i=0;e;)t+=e.offsetLeft-e.scrollLeft,i+=e.offsetTop-e.scrollTop,e=e.offsetParent;return{x:t,y:i}}},{key:"_initWebGL",value:function(){if(!this.gl)for(var e=0;!this.gl&&e<$e.length;e++)try{this.gl=this.canvas.getContext($e[e],this.contextAttr)}catch(e){}this.gl||(this.error("Failed to get a WebGL context"),this.fire("webglContextFailed",!0,!0));var t=this.gl,i="__",s=t.activeTexture;t.activeTexture=function(e){i!==e&&(i=e,s.call(this,e))};var r={},n=t.bindTexture;t.bindTexture=function(e,t){r[i]!==t&&(r[i]=t,n.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,i,s){return this.scene._renderer.readPixels(e,t,i,s)}},{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,m(P(i.prototype),"destroy",this).call(this)}}]),i}(),tt=function(){function e(t){w(this,e),this._scene=t,this._matPool=[],this._matPoolNextFreeIndex=0,this._rtcViewMats={},this._rtcPickViewMats={},this.reset()}return I(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.lineWidth=1}},{key:"getRTCViewMatrix",value:function(e,t){var i=this._rtcViewMats[e];return i||(i=this._getNewMat(),De(this._scene.camera.viewMatrix,t,i),this._rtcViewMats[e]=i),i}},{key:"getRTCPickViewMatrix",value:function(e,t){var i=this._rtcPickViewMats[e];if(!i){i=this._getNewMat();var s=this.pickViewMatrix||this._scene.camera.viewMatrix;De(s,t,i),this._rtcPickViewMats[e]=i}return i}},{key:"_getNewMat",value:function(){var e=this._matPool[this._matPoolNextFreeIndex];return e||(e=q.mat4(),this._matPool[this._matPoolNextFreeIndex]=e),this._matPoolNextFreeIndex++,e}}]),e}(),it=function(){function e(){w(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 I(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.entity&&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}(),st=function(){function e(t,i,s){if(w(this,e),this.allocated=!1,this.compiled=!1,this.handle=t.createShader(i),this.handle){if(this.allocated=!0,t.shaderSource(this.handle,s),t.compileShader(this.handle),this.compiled=t.getShaderParameter(this.handle,t.COMPILE_STATUS),!this.compiled&&!t.isContextLost()){for(var r=s.split("\n"),n=[],o=0;o<r.length;o++)n.push(o+1+": "+r[o]+"\n");this.errors=[],this.errors.push(""),this.errors.push(t.getShaderInfoLog(this.handle)),this.errors=this.errors.concat(n.join(""))}}else this.errors=["Failed to allocate"]}return I(e,[{key:"destroy",value:function(){}}]),e}(),rt=I((function e(t,i){w(this,e),this.bindTexture=function(e,s){return!!e.bind(s)&&(t.uniform1i(i,s),!0)}})),nt=function(){function e(t,i){w(this,e),this._gl=t,this.location=i}return I(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}(),ot=new G({});function at(e){for(var t,i,s=[],r=0,n=e.length;r<n;r++)(i=(t=e[r]).indexOf("/"))>0&&"/"===t.charAt(i+1)&&(t=t.substring(0,i)),s.push(t);return s.join("\n")}function ut(e){console.error(e.join("\n"))}var ht=function(){function e(t,i){w(this,e),this.id=ot.addItem({}),this.source=i,this.init(t)}return I(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 st(e,e.VERTEX_SHADER,at(this.source.vertex)),this._fragmentShader=new st(e,e.FRAGMENT_SHADER,at(this.source.fragment)),!this._vertexShader.allocated)return this.errors=["Vertex shader failed to allocate"].concat(this._vertexShader.errors),void ut(this.errors);if(!this._fragmentShader.allocated)return this.errors=["Fragment shader failed to allocate"].concat(this._fragmentShader.errors),void ut(this.errors);if(this.allocated=!0,!this._vertexShader.compiled)return this.errors=["Vertex shader failed to compile"].concat(this._vertexShader.errors),void ut(this.errors);if(!this._fragmentShader.compiled)return this.errors=["Fragment shader failed to compile"].concat(this._fragmentShader.errors),void ut(this.errors);var t,i,s,r,n;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 ut(this.errors);var o=e.getProgramParameter(this.handle,e.ACTIVE_UNIFORMS);for(i=0;i<o;++i)(s=e.getActiveUniform(this.handle,i))&&("\0"===(r=s.name)[r.length-1]&&(r=r.substr(0,r.length-1)),n=e.getUniformLocation(this.handle,r),s.type===e.SAMPLER_2D||s.type===e.SAMPLER_CUBE||35682===s.type||e instanceof WebGL2RenderingContext&&(s.type===e.UNSIGNED_INT_SAMPLER_2D||s.type===e.INT_SAMPLER_2D)?this.samplers[r]=new rt(e,n):this.uniforms[r]=n);var a=e.getProgramParameter(this.handle,e.ACTIVE_ATTRIBUTES);for(i=0;i<a;i++)(t=e.getActiveAttrib(this.handle,i))&&(n=e.getAttribLocation(this.handle,t.name),this.attributes[t.name]=new nt(e,n));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,i){if(!this.allocated)return!1;var s=this.samplers[e];return!!s&&s.bindTexture(t,i)}},{key:"destroy",value:function(){this.allocated&&(ot.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}(),lt=function(){function e(t,i,s,r,n,o,a,u,h){switch(w(this,e),this._gl=t,this.type=i,this.allocated=!1,s.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=o,this.length=0,this.dataLength=r,this.numItems=0,this.itemSize=n,this.normalized=!!a,this.stride=u||0,this.offset=h||0,this._allocate(s)}return I(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}(),ct=function(){function e(t,i){w(this,e),this.scene=t,this.aabb=q.AABB3(),this.origin=q.vec3(i),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 I(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 i=this.markerList[t].worldPos;this.positions[e++]=i[0],this.positions[e++]=i[1],this.positions[e++]=i[2],this.indices[t]=t}this.positions.length=3*this.numMarkers,this.indices.length=this.numMarkers}},{key:"_buildAABB",value:function(){var e=this.aabb;q.collapseAABB3(e),q.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,i=this.numMarkers;this.positionsBuf=new lt(e,e.ARRAY_BUFFER,new Float32Array(this.positions),t,3,e.STATIC_DRAW),this.indicesBuf=new lt(e,e.ELEMENT_ARRAY_BUFFER,new Uint16Array(this.indices),i,1,e.STATIC_DRAW),this.lenPositionsBuf=this.positions.length}},{key:"_buildOcclusionTestList",value:function(){var e=this.scene.canvas,t=this.scene.camera.perspective.near,i=e.boundary,s=i[2],r=i[3],n=0;this.lenOcclusionTestList=0;for(var o=0;o<this.numMarkers;o++){var a=this.markerList[o];if(a.viewPos[2]>-t)a._setVisible(!1);else{var u=a.canvasPos,h=u[0],l=u[1];h+10<0||l+10<0||h-10>s||l-10>r?a._setVisible(!1):!a.entity||a.entity.visible?a.occludable?(this.occlusionTestList[this.lenOcclusionTestList++]=a,this.pixels[n++]=h,this.pixels[n++]=l):a._setVisible(!0):a._setVisible(!1)}}}},{key:"_updateActiveSectionPlanes",value:function(){var e=this.scene._sectionPlanesState.sectionPlanes,t=e.length;if(t>0)for(var i=0;i<t;i++){var s=e[i];if(s.active){var r=q.planeAABB3Intersect(s.dir,s.dist,this.aabb);if(-1===r)return void(this.culledBySectionPlanes=!0);var n=0===r;this.sectionPlanesActive[i]=n}else this.sectionPlanesActive[i]=!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}(),pt=q.vec3([1,0,0]),dt=q.vec3(),ft=function(){function e(t,i){var s=this;w(this,e),this._scene=t,this._renderBufferManager=i,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(){s._occlusionTestListDirty=!0})),this._onCameraProjMatrix=t.camera.on("projMatrix",(function(){s._occlusionTestListDirty=!0})),this._onCanvasBoundary=t.canvas.on("boundary",(function(){s._occlusionTestListDirty=!0}))}return I(e,[{key:"addMarker",value:function(e){var t=e.origin.join(),i=this._occlusionLayers[t];i||(i=new ct(this._scene,e.origin),this._occlusionLayers[i.originHash]=i,this._occlusionLayersListDirty=!0),i.addMarker(e),this._markersToOcclusionLayersMap[e.id]=i,this._occlusionTestListDirty=!0}},{key:"markerWorldPosUpdated",value:function(e){var t=this._markersToOcclusionLayersMap[e.id];if(t){var i=e.origin.join();if(i!==t.originHash){1===t.numMarkers?(t.destroy(),delete this._occlusionLayers[t.originHash],this._occlusionLayersListDirty=!0):t.removeMarker(e);var s=this._occlusionLayers[i];s||(s=new ct(this._scene,e.origin),this._occlusionLayers[i]=t,this._occlusionLayersListDirty=!0),s.addMarker(e),this._markersToOcclusionLayersMap[e.id]=s}else t.markerWorldPosUpdated(e)}else e.error("Marker has not been added to OcclusionTester")}},{key:"removeMarker",value:function(e){var t=e.origin.join(),i=this._occlusionLayers[t];i&&(1===i.numMarkers?(i.destroy(),delete this._occlusionLayers[i.originHash],this._occlusionLayersListDirty=!0):i.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,i=this._occlusionLayersList.length;t<i;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,i=[];return i.push("#version 300 es"),i.push("// OcclusionTester vertex shader"),i.push("in vec3 position;"),i.push("uniform mat4 modelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;")),t&&i.push("out vec4 vWorldPosition;"),i.push("void main(void) {"),i.push("vec4 worldPosition = vec4(position, 1.0); "),i.push(" vec4 viewPosition = viewMatrix * worldPosition;"),t&&i.push(" vWorldPosition = worldPosition;"),i.push(" vec4 clipPos = projMatrix * viewPosition;"),i.push(" gl_PointSize = 20.0;"),e.logarithmicDepthBufferEnabled?i.push("vFragDepth = 1.0 + clipPos.w;"):i.push("clipPos.z += -0.001;"),i.push(" gl_Position = clipPos;"),i.push("}"),i}},{key:"_buildFragmentShaderSource",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.sectionPlanes.length>0,s=[];if(s.push("#version 300 es"),s.push("// OcclusionTester fragment shader"),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&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;");for(var r=0;r<t.sectionPlanes.length;r++)s.push("uniform bool sectionPlaneActive"+r+";"),s.push("uniform vec3 sectionPlanePos"+r+";"),s.push("uniform vec3 sectionPlaneDir"+r+";")}if(s.push("out vec4 outColor;"),s.push("void main(void) {"),i){s.push(" float dist = 0.0;");for(var n=0;n<t.sectionPlanes.length;n++)s.push("if (sectionPlaneActive"+n+") {"),s.push(" dist += clamp(dot(-sectionPlaneDir"+n+".xyz, vWorldPosition.xyz - sectionPlanePos"+n+".xyz), 0.0, 1000.0);"),s.push("}");s.push(" if (dist > 0.0) { discard; }")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = vec4(1.0, 0.0, 0.0, 1.0); "),s.push("}"),s}},{key:"_buildProgram",value:function(){this._program&&this._program.destroy();var e=this._scene,t=e.canvas.gl,i=e._sectionPlanesState;if(this._program=new ht(t,this._shaderSource),this._program.errors)this.errors=this._program.errors;else{var s=this._program;this._uViewMatrix=s.getLocation("viewMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uSectionPlanes=[];for(var r=0,n=i.sectionPlanes.length;r<n;r++)this._uSectionPlanes.push({active:s.getLocation("sectionPlaneActive"+r),pos:s.getLocation("sectionPlanePos"+r),dir:s.getLocation("sectionPlaneDir"+r)});this._aPosition=s.getAttribute("position"),e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=s.getLocation("logDepthBufFC"))}}},{key:"drawMarkers",value:function(){var e=this._scene,t=e.canvas.gl,i=this._program,s=e._sectionPlanesState,r=e.camera,n=e.camera.project;if(i.bind(),t.uniformMatrix4fv(this._uProjMatrix,!1,r._project._state.matrix),e.logarithmicDepthBufferEnabled){var o=2/(Math.log(n.far+1)/Math.LN2);t.uniform1f(this._uLogDepthBufFC,o)}for(var a=0,u=this._occlusionLayersList.length;a<u;a++){var h=this._occlusionLayersList[a];if(h.update(),!h.culledBySectionPlanes){var l=h.origin;t.uniformMatrix4fv(this._uViewMatrix,!1,De(r.viewMatrix,l));var c=s.sectionPlanes.length;if(c>0)for(var p=s.sectionPlanes,d=0;d<c;d++){var f=this._uSectionPlanes[d];if(f){var m=h.sectionPlanesActive[d];if(t.uniform1i(f.active,m?1:0),m){var v=p[d];t.uniform3fv(f.pos,Ee(v.dist,v.dir,l,dt)),t.uniform3fv(f.dir,v.dir)}}}this._aPosition.bindArrayBuffer(h.positionsBuf);var g=h.indicesBuf;g.bind(),t.drawElements(t.POINTS,g.numItems,g.itemType,0)}}}},{key:"doOcclusionTest",value:function(){for(var e=this._scene.canvas.resolutionScale,t=255*pt[0],i=255*pt[1],s=255*pt[2],r=0,n=this._occlusionLayersList.length;r<n;r++)for(var o=this._occlusionLayersList[r],a=0;a<o.lenOcclusionTestList;a++){var u=o.occlusionTestList[a],h=2*a,l=this._readPixelBuf.read(Math.round(o.pixels[h]*e),Math.round(o.pixels[h+1]*e)),c=l[0]===t&&l[1]===i&&l[2]===s;u._setVisible(c)}}},{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}(),mt=q.vec2(),vt=function(){function e(t){w(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 I(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 i=q.mat4();return function(){return e&&q.inverseMat4(r.camera.projMatrix,i),i}}());var i=this._scene.canvas.gl,s=this._program,r=this._scene,n=r.sao,o=i.drawingBufferWidth,a=i.drawingBufferHeight,u=r.camera.project._state,h=u.near,l=u.far,c=u.matrix,p=this._getInverseProjectMat(),d=Math.random(),f="perspective"===r.camera.projection;mt[0]=o,mt[1]=a,i.viewport(0,0,o,a),i.clearColor(0,0,0,1),i.disable(i.DEPTH_TEST),i.disable(i.BLEND),i.frontFace(i.CCW),i.clear(i.COLOR_BUFFER_BIT),s.bind(),i.uniform1f(this._uCameraNear,h),i.uniform1f(this._uCameraFar,l),i.uniformMatrix4fv(this._uCameraProjectionMatrix,!1,c),i.uniformMatrix4fv(this._uCameraInverseProjectionMatrix,!1,p),i.uniform1i(this._uPerspective,f),i.uniform1f(this._uScale,n.scale*(l/5)),i.uniform1f(this._uIntensity,n.intensity),i.uniform1f(this._uBias,n.bias),i.uniform1f(this._uKernelRadius,n.kernelRadius),i.uniform1f(this._uMinResolution,n.minResolution),i.uniform2fv(this._uViewport,mt),i.uniform1f(this._uRandomSeed,d);var m=e.getDepthTexture();s.bindTexture(this._uDepthTexture,m,0),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:"_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 i=this._scene.canvas.gl;if(this._program&&(this._program.destroy(),this._program=null),this._program=new ht(i,{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 s=new Float32Array([1,1,0,1,0,0,1,0]),r=new Float32Array([1,1,0,-1,1,0,-1,-1,0,1,-1,0]),n=new Uint32Array([0,1,2,0,2,3]);this._positionsBuf=new lt(i,i.ARRAY_BUFFER,r,r.length,3,i.STATIC_DRAW),this._uvBuf=new lt(i,i.ARRAY_BUFFER,s,s.length,2,i.STATIC_DRAW),this._indicesBuf=new lt(i,i.ELEMENT_ARRAY_BUFFER,n,n.length,1,i.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}(),gt=new Float32Array(Tt(17,[0,1])),_t=new Float32Array(Tt(17,[1,0])),yt=new Float32Array(function(e,t){for(var i=[],s=0;s<=e;s++)i.push(Pt(s,t));return i}(17,4)),bt=new Float32Array(2),xt=function(){function e(t){w(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 I(e,[{key:"init",value:function(){var e=this._scene.canvas.gl;if(this._program=new ht(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]),i=new Float32Array([1,1,0,-1,1,0,-1,-1,0,1,-1,0]),s=new Uint32Array([0,1,2,0,2,3]);this._positionsBuf=new lt(e,e.ARRAY_BUFFER,i,i.length,3,e.STATIC_DRAW),this._uvBuf=new lt(e,e.ARRAY_BUFFER,t,t.length,2,e.STATIC_DRAW),this._indicesBuf=new lt(e,e.ELEMENT_ARRAY_BUFFER,s,s.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,i){var s=this;if(!this._programError){this._getInverseProjectMat||(this._getInverseProjectMat=function(){var e=!0;s._scene.camera.on("projMatrix",(function(){e=!0}));var t=q.mat4();return function(){return e&&q.inverseMat4(o.camera.projMatrix,t),t}}());var r=this._scene.canvas.gl,n=this._program,o=this._scene,a=r.drawingBufferWidth,u=r.drawingBufferHeight,h=o.camera.project._state,l=h.near,c=h.far;r.viewport(0,0,a,u),r.clearColor(0,0,0,1),r.enable(r.DEPTH_TEST),r.disable(r.BLEND),r.frontFace(r.CCW),r.clear(r.COLOR_BUFFER_BIT|r.DEPTH_BUFFER_BIT),n.bind(),bt[0]=a,bt[1]=u,r.uniform2fv(this._uViewport,bt),r.uniform1f(this._uCameraNear,l),r.uniform1f(this._uCameraFar,c),r.uniform1f(this._uDepthCutoff,.01),0===i?r.uniform2fv(this._uSampleOffsets,_t):r.uniform2fv(this._uSampleOffsets,gt),r.uniform1fv(this._uSampleWeights,yt);var p=e.getDepthTexture(),d=t.getTexture();n.bindTexture(this._uDepthTexture,p,0),n.bindTexture(this._uOcclusionTexture,d,1),this._aUV.bindArrayBuffer(this._uvBuf),this._aPosition.bindArrayBuffer(this._positionsBuf),this._indicesBuf.bind(),r.drawElements(r.TRIANGLES,this._indicesBuf.numItems,this._indicesBuf.itemType,0)}}},{key:"destroy",value:function(){this._program.destroy()}}]),e}();function Pt(e,t){return Math.exp(-e*e/(t*t*2))/(Math.sqrt(2*Math.PI)*t)}function Tt(e,t){for(var i=[],s=0;s<=e;s++)i.push(t[0]*s),i.push(t[1]*s);return i}var wt=function(){var e=document.createElement("canvas"),t=String.fromCharCode;if(!e.getContext)return{saveAsBMP:function(){},saveAsPNG:function(){},saveAsJPEG:function(){}};var i=!!e.getContext("2d").getImageData,s=!!e.toDataURL,r=!!window.btoa,n=function(e){var i="",s=e.width,r=e.height;i+="BM";var n=s*r*4+54;i+=t(n%256),n=Math.floor(n/256),i+=t(n%256),n=Math.floor(n/256),i+=t(n%256),n=Math.floor(n/256),i+=t(n%256),i+=t(0,0,0,0,54,0,0,0),i+=t(40,0,0,0);var o=s;i+=t(o%256),o=Math.floor(o/256),i+=t(o%256),o=Math.floor(o/256),i+=t(o%256),o=Math.floor(o/256),i+=t(o%256);var a=r;i+=t(a%256),a=Math.floor(a/256),i+=t(a%256),a=Math.floor(a/256),i+=t(a%256),a=Math.floor(a/256),i+=t(a%256),i+=t(1,0,32,0),i+=t(0,0,0,0);var u=s*r*4;i+=t(u%256),u=Math.floor(u/256),i+=t(u%256),u=Math.floor(u/256),i+=t(u%256),u=Math.floor(u/256),i+=t(u%256),i+=t(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);var h,l,c,p,d=e.data,f="",m=r;do{for(c=s*(m-1)*4,p="",h=0;h<s;h++)p+=t(d[c+(l=4*h)+2],d[c+l+1],d[c+l],d[c+l+3]);f+=p}while(--m);return function(e){var i,s,r="";if("string"==typeof e)r=e;else for(s=e,i=0;i<s.length;i++)r+=t(s[i]);return btoa(r)}(i+f)},o=function(e){window.open(e)||(document.location.href=e)},a=function(e,t){return"data:"+t+";base64,"+e},u=function(e){var t=document.createElement("img");return t.src=e,t},h=function(e,t,i,s){if(t&&i){var r=document.createElement("canvas");r.width=t,r.height=i,r.style.width=t+"px",r.style.height=i+"px";var n=r.getContext("2d");return s?(n.save(),n.scale(1,-1),n.imageSmoothingEnabled=!0,n.drawImage(e,0,0,e.width,e.height,0,0,t,-i),n.restore()):(n.imageSmoothingEnabled=!0,n.drawImage(e,0,0,e.width,e.height,0,0,t,i)),r}return e};return{saveAsPNG:function(e,t,i,r,n){if(!s)return!1;var a=h(e,i,r,n).toDataURL("image/png");return t?u(a):(o(a),!0)},saveAsJPEG:function(e,t,i,r,n){if(!s)return!1;var a="image/jpeg",l=h(e,i,r,n).toDataURL(a);return 5==l.indexOf(a)&&(t?u(l):(o(l),!0))},saveAsBMP:function(e,t,l,c,p){if(!(s&&i&&r))return!1;var d="image/bmp",f=function(e){var t=parseInt(e.width),i=parseInt(e.height);return e.getContext("2d").getImageData(0,0,t,i)}(h(e,l,c,p)),m=n(f);return t?u(a(m,d)):(o(a(m,d)),!0)}}}(),Mt=function(){function e(t,i,s){w(this,e),s=s||{},this.gl=i,this.allocated=!1,this.canvas=t,this.buffer=null,this.bound=!1,this.size=s.size,this._hasDepthTexture=!!s.depthTexture}return I(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(){if(this._touch(),!this.bound){var e=this.gl;e.bindFramebuffer(e.FRAMEBUFFER,this.buffer.framebuf),this.bound=!0}}},{key:"_touch",value:function(){var e,t,i=this.gl;if(this.size?(e=this.size[0],t=this.size[1]):(e=i.drawingBufferWidth,t=i.drawingBufferHeight),this.buffer){if(this.buffer.width===e&&this.buffer.height===t)return;i.deleteTexture(this.buffer.texture),i.deleteFramebuffer(this.buffer.framebuf),i.deleteRenderbuffer(this.buffer.renderbuf)}var s,r=i.createTexture();i.bindTexture(i.TEXTURE_2D,r),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_MIN_FILTER,i.NEAREST),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_MAG_FILTER,i.NEAREST),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_WRAP_S,i.CLAMP_TO_EDGE),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_WRAP_T,i.CLAMP_TO_EDGE),i.texImage2D(i.TEXTURE_2D,0,i.RGBA,e,t,0,i.RGBA,i.UNSIGNED_BYTE,null),this._hasDepthTexture&&(s=i.createTexture(),i.bindTexture(i.TEXTURE_2D,s),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_MAG_FILTER,i.NEAREST),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_MIN_FILTER,i.NEAREST),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_WRAP_S,i.CLAMP_TO_EDGE),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_WRAP_T,i.CLAMP_TO_EDGE),i.texImage2D(i.TEXTURE_2D,0,i.DEPTH_COMPONENT32F,e,t,0,i.DEPTH_COMPONENT,i.FLOAT,null));var n=i.createRenderbuffer();i.bindRenderbuffer(i.RENDERBUFFER,n),i.renderbufferStorage(i.RENDERBUFFER,i.DEPTH_COMPONENT32F,e,t);var o=i.createFramebuffer();if(i.bindFramebuffer(i.FRAMEBUFFER,o),i.framebufferTexture2D(i.FRAMEBUFFER,i.COLOR_ATTACHMENT0,i.TEXTURE_2D,r,0),this._hasDepthTexture?i.framebufferTexture2D(i.FRAMEBUFFER,i.DEPTH_ATTACHMENT,i.TEXTURE_2D,s,0):i.framebufferRenderbuffer(i.FRAMEBUFFER,i.DEPTH_ATTACHMENT,i.RENDERBUFFER,n),i.bindTexture(i.TEXTURE_2D,null),i.bindRenderbuffer(i.RENDERBUFFER,null),i.bindFramebuffer(i.FRAMEBUFFER,null),i.bindFramebuffer(i.FRAMEBUFFER,o),!i.isFramebuffer(o))throw"Invalid framebuffer";i.bindFramebuffer(i.FRAMEBUFFER,null);var a=i.checkFramebufferStatus(i.FRAMEBUFFER);switch(a){case i.FRAMEBUFFER_COMPLETE:break;case i.FRAMEBUFFER_INCOMPLETE_ATTACHMENT:throw"Incomplete framebuffer: FRAMEBUFFER_INCOMPLETE_ATTACHMENT";case i.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:throw"Incomplete framebuffer: FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT";case i.FRAMEBUFFER_INCOMPLETE_DIMENSIONS:throw"Incomplete framebuffer: FRAMEBUFFER_INCOMPLETE_DIMENSIONS";case i.FRAMEBUFFER_UNSUPPORTED:throw"Incomplete framebuffer: FRAMEBUFFER_UNSUPPORTED";default:throw"Incomplete framebuffer: "+a}this.buffer={framebuf:o,renderbuf:n,texture:r,depthTexture:s,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 i=e,s=this.gl.drawingBufferHeight-t,r=new Uint8Array(4),n=this.gl;return n.readPixels(i,s,1,1,n.RGBA,n.UNSIGNED_BYTE,r),r}},{key:"readImage",value:function(e){var t=this.gl,i=this._getImageDataCache(),s=i.pixelData,r=i.canvas,n=i.imageData,o=i.context;t.readPixels(0,0,this.buffer.width,this.buffer.height,t.RGBA,t.UNSIGNED_BYTE,s),n.data.set(s),o.putImageData(n,0,0);var a,u=e.width||r.width,h=e.height||r.height,l=e.format||"jpeg",c=!0;switch(l){case"jpeg":a=wt.saveAsJPEG(r,!0,u,h,c);break;case"png":a=wt.saveAsPNG(r,!0,u,h,c);break;case"bmp":a=wt.saveAsBMP(r,!0,u,h,c);break;default:console.error("Unsupported image format: '"+l+"' - supported types are 'jpeg', 'bmp' and 'png' - defaulting to 'jpeg'"),a=wt.saveAsJPEG(r,!0,u,h,c)}return a.src}},{key:"_getImageDataCache",value:function(){var e=this.buffer.width,t=this.buffer.height,i=this._imageDataCache;if(i&&(i.width===e&&i.height===t||(this._imageDataCache=null,i=null)),!i){var s=document.createElement("canvas");s.width=e,s.height=t;var r=s.getContext("2d"),n=r.createImageData(e,t);i={pixelData:new Uint8Array(e*t*4),canvas:s,context:r,imageData:n,width:e,height:t},this._imageDataCache=i}return 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}(),It=function(){function e(t){w(this,e),this.scene=t,this._renderBuffersBasic={},this._renderBuffersScaled={}}return I(e,[{key:"getRenderBuffer",value:function(e,t){var i=1===this.scene.canvas.resolutionScale?this._renderBuffersBasic:this._renderBuffersScaled,s=i[e];return s||(s=new Mt(this.scene.canvas.canvas,this.scene.canvas.gl,t),i[e]=s),s}},{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 i;switch(t){case"WEBGL_depth_texture":i=e.getExtension("WEBGL_depth_texture")||e.getExtension("MOZ_WEBGL_depth_texture")||e.getExtension("WEBKIT_WEBGL_depth_texture");break;case"EXT_texture_filter_anisotropic":i=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":i=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":i=e.getExtension("WEBGL_compressed_texture_pvrtc")||e.getExtension("WEBKIT_WEBGL_compressed_texture_pvrtc");break;default:i=e.getExtension(t)}return e._cachedExtensions[t]=i,i}var Dt=function(){var e=[],t=[],i=[],s=[],r=[],n=0,o=new Uint16Array(3),a=new Uint16Array(3),u=new Uint16Array(3),h=q.vec3(),l=q.vec3(),c=q.vec3(),p=q.vec3(),d=q.vec3(),f=q.vec3(),m=q.vec3();return function(v,g,_,y){!function(r,n){var o,a,u,h,l,c,p={},d=Math.pow(10,4),f=0;for(l=0,c=r.length;l<c;l+=3)o=r[l],a=r[l+1],u=r[l+2],void 0===p[h=Math.round(o*d)+"_"+Math.round(a*d)+"_"+Math.round(u*d)]&&(p[h]=f/3,e[f++]=o,e[f++]=a,e[f++]=u),t[l/3]=p[h];for(l=0,c=n.length;l<c;l++)s[l]=t[n[l]],i[s[l]]=n[l]}(v,g),function(t,i){n=0;for(var v=0,g=t;v<g;v+=3){var _=3*s[v],y=3*s[v+1],b=3*s[v+2];i?(o[0]=e[_],o[1]=e[_+1],o[2]=e[_+2],a[0]=e[y],a[1]=e[y+1],a[2]=e[y+2],u[0]=e[b],u[1]=e[b+1],u[2]=e[b+2],q.decompressPosition(o,i,h),q.decompressPosition(a,i,l),q.decompressPosition(u,i,c)):(h[0]=e[_],h[1]=e[_+1],h[2]=e[_+2],l[0]=e[y],l[1]=e[y+1],l[2]=e[y+2],c[0]=e[b],c[1]=e[b+1],c[2]=e[b+2]),q.subVec3(c,l,p),q.subVec3(h,l,d),q.cross3Vec3(p,d,f),q.normalizeVec3(f,m);var x=r[n]||(r[n]={normal:q.vec3()});x.normal[0]=m[0],x.normal[1]=m[1],x.normal[2]=m[2],n++}}(g.length,_);for(var b,x,P,T,w,M,I,C,D,A,k=[],E=Math.cos(q.DEGTORAD*y),F={},R=!1,S=0,O=g.length;S<O;S+=3)for(var B=S/3,L=0;L<3;L++)b=s[S+L],x=s[S+(L+1)%3],void 0===F[w=(P=Math.min(b,x))+","+(T=Math.max(b,x))]?F[w]={index1:P,index2:T,face1:B,face2:void 0}:F[w].face2=B;for(w in F)void 0!==(M=F[w]).face2&&(I=r[M.face1].normal,C=r[M.face2].normal,q.dotVec3(I,C)>E)||(D=i[M.index1],A=i[M.index2],(!R&&D>65535||A>65535)&&(R=!0),k.push(D),k.push(A));return R?new Uint32Array(k):new Uint16Array(k)}}(),At=function(){function e(t,i,s,r){var n=arguments.length>4&&void 0!==arguments[4]?arguments[4]:null,o=arguments.length>5&&void 0!==arguments[5]?arguments[5]:0;w(this,e),this.model=t,this.object=null,this.parent=null,this.id=i,this.pickId=this.model.scene._renderer.getPickID(this),this.aabb=q.AABB3(),this._layer=n,this._portionId=o,this._color=[s[0],s[1],s[2],r],this._colorize=[s[0],s[1],s[2],r],this._colorizing=!1,this._transparent=r<255,this.numTriangles=0,this.origin=null}return I(e,[{key:"_finalize",value:function(e){this._layer.initFlags(this._portionId,e,this._transparent)}},{key:"_finalize2",value:function(){this._layer.flushInitFlags&&this._layer.flushInitFlags()}},{key:"_setVisible",value:function(e){this._layer.setVisible(this._portionId,e,this._transparent)}},{key:"_setColor",value:function(e){this._color[0]=e[0],this._color[1]=e[1],this._color[2]=e[2],this._colorizing||this._layer.setColor(this._portionId,this._color,!1)}},{key:"_setColorize",value:function(e){e?(this._colorize[0]=e[0],this._colorize[1]=e[1],this._colorize[2]=e[2],this._layer.setColor(this._portionId,this._colorize,false),this._colorizing=!0):(this._layer.setColor(this._portionId,this._color,false),this._colorizing=!1)}},{key:"_setOpacity",value:function(e,t){var i=e<255,s=this._transparent!==i;this._color[3]=e,this._colorize[3]=e,this._transparent=i,this._colorizing?this._layer.setColor(this._portionId,this._colorize):this._layer.setColor(this._portionId,this._color),s&&this._layer.setTransparent(this._portionId,t,i)}},{key:"_setOffset",value:function(e){this._layer.setOffset(this._portionId,e)}},{key:"_setHighlighted",value:function(e){this._layer.setHighlighted(this._portionId,e,this._transparent)}},{key:"_setXRayed",value:function(e){this._layer.setXRayed(this._portionId,e,this._transparent)}},{key:"_setSelected",value:function(e){this._layer.setSelected(this._portionId,e,this._transparent)}},{key:"_setEdges",value:function(e){this._layer.setEdges(this._portionId,e,this._transparent)}},{key:"_setClippable",value:function(e){this._layer.setClippable(this._portionId,e,this._transparent)}},{key:"_setCollidable",value:function(e){this._layer.setCollidable(this._portionId,e)}},{key:"_setPickable",value:function(e){this._layer.setPickable(this._portionId,e,this._transparent)}},{key:"_setCulled",value:function(e){this._layer.setCulled(this._portionId,e,this._transparent)}},{key:"canPickTriangle",value:function(){return!1}},{key:"drawPickTriangles",value:function(e,t){}},{key:"pickTriangleSurface",value:function(e){}},{key:"precisionRayPickSurface",value:function(e,t,i,s){return!!this._layer.precisionRayPickSurface&&this._layer.precisionRayPickSurface(this._portionId,e,t,i,s)}},{key:"canPickWorldPos",value:function(){return!0}},{key:"drawPickDepths",value:function(e){this.model.drawPickDepths(e)}},{key:"drawPickNormals",value:function(e){this.model.drawPickNormals(e)}},{key:"delegatePickedEntity",value:function(){return this.parent}},{key:"_destroy",value:function(){this.model.scene._renderer.putPickID(this.pickId)}}]),e}(),kt=1,Et=4,Ft=8,Rt=16,St=32,Ot=256,Bt=512,Lt=1024,Nt=2048,jt=new Float32Array([0,0,0]),Gt=new Uint16Array([0,0,0]),Ht=function(){function e(t,i,s,r,n,o){w(this,e),this._isObject=i,this.scene=t.scene,this.model=t,this.meshes=r,this._numTriangles=0;for(var a=0,u=this.meshes.length;a<u;a++){var h=this.meshes[a];h.parent=this,this._numTriangles+=h.numTriangles}this.id=s,this.originalSystemId=q.unglobalizeObjectId(t.id,s),this._flags=n,this._aabb=o,this._offsetAABB=q.AABB3(o),this._offset=q.vec3(),this._colorizeUpdated=!1,this._opacityUpdated=!1,this._culled=!1,this._culledVFC=!1,this._culledLOD=!1,this._isObject&&t.scene._registerObject(this)}return I(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:"numTriangles",get:function(){return this._numTriangles}},{key:"visible",get:function(){return this._getFlag(kt)},set:function(e){if(!!(this._flags&kt)!==e){this._flags=e?this._flags|kt:this._flags&~kt;for(var t=0,i=this.meshes.length;t<i;t++)this.meshes[t]._setVisible(this._flags);this._isObject&&this.model.scene._objectVisibilityUpdated(this),this.model.glRedraw()}}},{key:"highlighted",get:function(){return this._getFlag(Bt)},set:function(e){if(!!(this._flags&Bt)!==e){this._flags=e?this._flags|Bt:this._flags&~Bt;for(var t=0,i=this.meshes.length;t<i;t++)this.meshes[t]._setHighlighted(this._flags);this._isObject&&this.model.scene._objectHighlightedUpdated(this),this.model.glRedraw()}}},{key:"xrayed",get:function(){return this._getFlag(Ot)},set:function(e){if(!!(this._flags&Ot)!==e){this._flags=e?this._flags|Ot:this._flags&~Ot;for(var t=0,i=this.meshes.length;t<i;t++)this.meshes[t]._setXRayed(this._flags);this._isObject&&this.model.scene._objectXRayedUpdated(this),this.model.glRedraw()}}},{key:"selected",get:function(){return this._getFlag(Lt)},set:function(e){if(!!(this._flags&Lt)!==e){this._flags=e?this._flags|Lt:this._flags&~Lt;for(var t=0,i=this.meshes.length;t<i;t++)this.meshes[t]._setSelected(this._flags);this._isObject&&this.model.scene._objectSelectedUpdated(this),this.model.glRedraw()}}},{key:"edges",get:function(){return this._getFlag(Nt)},set:function(e){if(!!(this._flags&Nt)!==e){this._flags=e?this._flags|Nt:this._flags&~Nt;for(var t=0,i=this.meshes.length;t<i;t++)this.meshes[t]._setEdges(this._flags);this.model.glRedraw()}}},{key:"culledVFC",get:function(){return!!this._culledVFC},set:function(e){this._culledVFC=e,this.internalSetCulled()}},{key:"culledLOD",get:function(){return!!this._culledLOD},set:function(e){this._culledLOD=e,this.internalSetCulled()}},{key:"culled",get:function(){return!!this._culled},set:function(e){this._culled=e,this.internalSetCulled()}},{key:"internalSetCulled",value:function(){var e=!!this._culled||!!this._culledLOD||!!this._culledVFC;if(!!(this._flags&Et)!==e){this._flags=e?this._flags|Et:this._flags&~Et;for(var t=0,i=this.meshes.length;t<i;t++)this.meshes[t]._setCulled(this._flags);this.model.glRedraw()}}},{key:"clippable",get:function(){return this._getFlag(Rt)},set:function(e){if(!!(this._flags&Rt)!==e){this._flags=e?this._flags|Rt:this._flags&~Rt;for(var t=0,i=this.meshes.length;t<i;t++)this.meshes[t]._setClippable(this._flags);this.model.glRedraw()}}},{key:"collidable",get:function(){return this._getFlag(St)},set:function(e){if(!!(this._flags&St)!==e){this._flags=e?this._flags|St:this._flags&~St;for(var t=0,i=this.meshes.length;t<i;t++)this.meshes[t]._setCollidable(this._flags)}}},{key:"pickable",get:function(){return this._getFlag(Ft)},set:function(e){if(!!(this._flags&Ft)!==e){this._flags=e?this._flags|Ft:this._flags&~Ft;for(var t=0,i=this.meshes.length;t<i;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 jt[0]=e[0]/255,jt[1]=e[1]/255,jt[2]=e[2]/255,jt},set:function(e){if(e){Gt[0]=Math.floor(255*e[0]),Gt[1]=Math.floor(255*e[1]),Gt[2]=Math.floor(255*e[2]);for(var t=0,i=this.meshes.length;t<i;t++)this.meshes[t]._setColorize(Gt)}else for(var s=0,r=this.meshes.length;s<r;s++)this.meshes[s]._setColorize(null);if(this._isObject){var n=!!e;this.scene._objectColorizeUpdated(this,n),this._colorizeUpdated=n}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,i=this.meshes[0]._colorize[3],s=255;if(t){if(e<0?e=0:e>1&&(e=1),i===(s=Math.floor(255*e)))return}else if(i===(s=255))return;for(var r=0,n=this.meshes.length;r<n;r++)this.meshes[r]._setOpacity(s,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,i=this.meshes.length;t<i;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:"castsShadow",get:function(){return!1},set:function(e){}},{key:"receivesShadow",get:function(){return!1},set:function(e){}},{key:"saoEnabled",get:function(){return this.model.saoEnabled}},{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,i=this.meshes.length;t<i;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,i=this.meshes.length;t<i;t++)this.meshes[t]._destroy();e._aabbDirty=!0}}]),e}(),Vt=0,Ut=1,zt=2,Wt=3,Xt=4,Yt=5,Kt=6,Jt=7,Zt=8,Qt=9,qt=10,$t=11,ei=new G({}),ti=function(){function e(t){for(var i in w(this,e),this.id=ei.addItem({}),t)t.hasOwnProperty(i)&&(this[i]=t[i])}return I(e,[{key:"destroy",value:function(){ei.removeItem(this.id)}}]),e}();var ii=function(){var e=q.mat4(),t=q.mat4();return function(i,s){s=s||q.mat4();var r=i[0],n=i[1],o=i[2],a=i[3]-r,u=i[4]-n,h=i[5]-o,l=65535;return q.identityMat4(e),q.translationMat4v(i,e),q.identityMat4(t),q.scalingMat4v([a/l,u/l,h/l],t),q.mulMat4(e,t,s),s}}(),si=function(){var e=q.mat4(),t=q.mat4();return function(i,s,r){var n,o=new Uint16Array(i.length),a=new Float32Array([r[0]!==s[0]?65535/(r[0]-s[0]):0,r[1]!==s[1]?65535/(r[1]-s[1]):0,r[2]!==s[2]?65535/(r[2]-s[2]):0]);for(n=0;n<i.length;n+=3)o[n+0]=Math.max(0,Math.min(65535,Math.floor((i[n+0]-s[0])*a[0]))),o[n+1]=Math.max(0,Math.min(65535,Math.floor((i[n+1]-s[1])*a[1]))),o[n+2]=Math.max(0,Math.min(65535,Math.floor((i[n+2]-s[2])*a[2])));return q.identityMat4(e),q.translationMat4v(s,e),q.identityMat4(t),q.scalingMat4v([(r[0]-s[0])/65535,(r[1]-s[1])/65535,(r[2]-s[2])/65535],t),{quantized:o,decodeMatrix:q.mulMat4(e,t,q.identityMat4())}}}();var ri=function(){var e=q.mat3(),t=q.mat3();return function(i,s,r){var n,o=new Uint16Array(i.length),a=new Float32Array([65535/(r[0]-s[0]),65535/(r[1]-s[1])]);for(n=0;n<i.length;n+=2)o[n+0]=Math.max(0,Math.min(65535,Math.floor((i[n+0]-s[0])*a[0]))),o[n+1]=Math.max(0,Math.min(65535,Math.floor((i[n+1]-s[1])*a[1])));return q.identityMat3(e),q.translationMat3v(s,e),q.identityMat3(t),q.scalingMat3v([(r[0]-s[0])/65535,(r[1]-s[1])/65535],t),{quantized:o,decodeMatrix:q.mulMat3(e,t,q.identityMat3())}}}();function ni(e,t,i,s){var r=e[t]/(Math.abs(e[t])+Math.abs(e[t+1])+Math.abs(e[t+2])),n=e[t+1]/(Math.abs(e[t])+Math.abs(e[t+1])+Math.abs(e[t+2]));if(e[t+2]<0){var o=(1-Math.abs(n))*(r>=0?1:-1),a=(1-Math.abs(r))*(n>=0?1:-1);r=o,n=a}return new Int8Array([Math[i](127.5*r+(r<0?-1:0)),Math[s](127.5*n+(n<0?-1:0))])}function oi(e){var t=e[0],i=e[1];t/=t<0?127:128,i/=i<0?127:128;var s=1-Math.abs(t)-Math.abs(i);s<0&&(t=(1-Math.abs(i))*(t>=0?1:-1),i=(1-Math.abs(t))*(i>=0?1:-1));var r=Math.sqrt(t*t+i*i+s*s);return[t/r,i/r,s/r]}function ai(e,t,i){return e[t]*i[0]+e[t+1]*i[1]+e[t+2]*i[2]}var ui={getPositionsBounds:function(e){var t,i,s=new Float32Array(3),r=new Float32Array(3);for(t=0;t<3;t++)s[t]=Number.MAX_VALUE,r[t]=-Number.MAX_VALUE;for(t=0;t<e.length;t+=3)for(i=0;i<3;i++)s[i]=Math.min(s[i],e[t+i]),r[i]=Math.max(r[i],e[t+i]);return{min:s,max:r}},createPositionsDecodeMatrix:ii,compressPositions:si,compressPosition:function(e,t,i){var s=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]);i[0]=Math.max(0,Math.min(65535,Math.floor((e[0]-t[0])*s[0]))),i[1]=Math.max(0,Math.min(65535,Math.floor((e[1]-t[1])*s[1]))),i[2]=Math.max(0,Math.min(65535,Math.floor((e[2]-t[2])*s[2])))},decompressPositions:function(e,t){for(var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:new Float32Array(e.length),s=0,r=e.length;s<r;s+=3)i[s+0]=e[s+0]*t[0]+t[12],i[s+1]=e[s+1]*t[5]+t[13],i[s+2]=e[s+2]*t[10]+t[14];return i},decompressPosition:function(e,t,i){return i[0]=e[0]*t[0]+t[12],i[1]=e[1]*t[5]+t[13],i[2]=e[2]*t[10]+t[14],i},decompressAABB:function(e,t){var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:e;return i[0]=e[0]*t[0]+t[12],i[1]=e[1]*t[5]+t[13],i[2]=e[2]*t[10]+t[14],i[3]=e[3]*t[0]+t[12],i[4]=e[4]*t[5]+t[13],i[5]=e[5]*t[10]+t[14],i},getUVBounds:function(e){var t,i,s=new Float32Array(2),r=new Float32Array(2);for(t=0;t<2;t++)s[t]=Number.MAX_VALUE,r[t]=-Number.MAX_VALUE;for(t=0;t<e.length;t+=2)for(i=0;i<2;i++)s[i]=Math.min(s[i],e[t+i]),r[i]=Math.max(r[i],e[t+i]);return{min:s,max:r}},compressUVs:ri,decompressUVs:function(e,t){for(var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:new Float32Array(e.length),s=0,r=e.length;s<r;s+=3)i[s+0]=e[s+0]*t[0]+t[6],i[s+1]=e[s+1]*t[4]+t[7];return i},decompressUV:function(e,t,i){i[0]=e[0]*t[0]+t[6],i[1]=e[1]*t[4]+t[7]},compressNormals:function(e){for(var t,i,s,r,n=new Int8Array(e.length),o=0;o<e.length;o+=3)i=t=ni(e,o,"floor","floor"),s=r=ai(e,o,oi(t)),(s=ai(e,o,oi(t=ni(e,o,"ceil","floor"))))>r&&(i=t,r=s),(s=ai(e,o,oi(t=ni(e,o,"floor","ceil"))))>r&&(i=t,r=s),(s=ai(e,o,oi(t=ni(e,o,"ceil","ceil"))))>r&&(i=t,r=s),n[o]=i[0],n[o+1]=i[1];return n},decompressNormals:function(e,t){for(var i=0,s=0,r=e.length;i<r;i+=2){var n=e[i+0],o=e[i+1];n=(2*n+1)/255,o=(2*o+1)/255;var a=1-Math.abs(n)-Math.abs(o);a<0&&(n=(1-Math.abs(o))*(n>=0?1:-1),o=(1-Math.abs(n))*(o>=0?1:-1));var u=Math.sqrt(n*n+o*o+a*a);t[s+0]=n/u,t[s+1]=o/u,t[s+2]=a/u,s+=3}return t},decompressNormal:function(e,t){var i=e[0],s=e[1];i=(2*i+1)/255,s=(2*s+1)/255;var r=1-Math.abs(i)-Math.abs(s);r<0&&(i=(1-Math.abs(s))*(i>=0?1:-1),s=(1-Math.abs(i))*(s>=0?1:-1));var n=Math.sqrt(i*i+s*s+r*r);return t[0]=i/n,t[1]=s/n,t[2]=r/n,t}},hi=function(e){g(i,fe);var t=y(i);function i(e){var s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return w(this,i),(s=t.call(this,e,r)).camera=e,s._state=new ti({matrix:q.mat4(),inverseMatrix:q.mat4(),transposedMatrix:q.mat4(),near:.1,far:2e3}),s._inverseMatrixDirty=!0,s._transposedMatrixDirty=!0,s._fov=60,s._canvasResized=s.scene.canvas.on("boundary",s._needUpdate,x(s)),s.fov=r.fov,s.fovAxis=r.fovAxis,s.near=r.near,s.far=r.far,s}return I(i,[{key:"type",get:function(){return"Perspective"}},{key:"_update",value:function(){var e=this.scene.viewport.boundary,t=e[2]/e[3],i=this._fovAxis,s=this._fov;("x"===i||"min"===i&&t<1||"max"===i&&t>1)&&(s/=t),s=Math.min(s,120),q.perspectiveMat4(s*(Math.PI/180),t,this._state.near,this._state.far,this._state.matrix),this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!0,this.glRedraw(),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&&(q.inverseMat4(this._state.matrix,this._state.inverseMatrix),this._inverseMatrixDirty=!1),this._state.inverseMatrix}},{key:"transposedMatrix",get:function(){return this._updateScheduled&&this._doUpdate(),this._transposedMatrixDirty&&(q.transposeMat4(this._state.matrix,this._state.transposedMatrix),this._transposedMatrixDirty=!1),this._state.transposedMatrix}},{key:"unproject",value:function(e,t,i,s,r){var n=this.scene.canvas.canvas,o=n.offsetWidth/2,a=n.offsetHeight/2;return i[0]=(e[0]-o)/o,i[1]=(e[1]-a)/a,i[2]=t,i[3]=1,q.mulMat4v4(this.inverseMatrix,i,s),q.mulVec3Scalar(s,1/s[3]),s[3]=1,s[1]*=-1,q.mulMat4v4(this.camera.inverseViewMatrix,s,r),r}},{key:"destroy",value:function(){m(P(i.prototype),"destroy",this).call(this),this._state.destroy(),this.scene.canvas.off(this._canvasResized)}}]),i}(),li=function(e){g(i,fe);var t=y(i);function i(e){var s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return w(this,i),(s=t.call(this,e,r)).camera=e,s._state=new ti({matrix:q.mat4(),inverseMatrix:q.mat4(),transposedMatrix:q.mat4(),near:.1,far:2e3}),s._inverseMatrixDirty=!0,s._transposedMatrixDirty=!0,s.scale=r.scale,s.near=r.near,s.far=r.far,s._onCanvasBoundary=s.scene.canvas.on("boundary",s._needUpdate,x(s)),s}return I(i,[{key:"type",get:function(){return"Ortho"}},{key:"_update",value:function(){var e,t,i,s,r=this.scene,n=.5*this._scale,o=r.viewport.boundary,a=o[2],u=o[3],h=a/u;a>u?(e=-n,t=n,i=n/h,s=-n/h):(e=-n*h,t=n*h,i=n,s=-n),q.orthoMat4c(e,t,s,i,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&&(q.inverseMat4(this._state.matrix,this._state.inverseMatrix),this._inverseMatrixDirty=!1),this._state.inverseMatrix}},{key:"transposedMatrix",get:function(){return this._updateScheduled&&this._doUpdate(),this._transposedMatrixDirty&&(q.transposeMat4(this._state.matrix,this._state.transposedMatrix),this._transposedMatrixDirty=!1),this._state.transposedMatrix}},{key:"unproject",value:function(e,t,i,s,r){var n=this.scene.canvas.canvas,o=n.offsetWidth/2,a=n.offsetHeight/2;return i[0]=(e[0]-o)/o,i[1]=(e[1]-a)/a,i[2]=t,i[3]=1,q.mulMat4v4(this.inverseMatrix,i,s),q.mulVec3Scalar(s,1/s[3]),s[3]=1,s[1]*=-1,q.mulMat4v4(this.camera.inverseViewMatrix,s,r),r}},{key:"destroy",value:function(){m(P(i.prototype),"destroy",this).call(this),this._state.destroy(),this.scene.canvas.off(this._onCanvasBoundary)}}]),i}(),ci=function(e){g(i,fe);var t=y(i);function i(e){var s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return w(this,i),(s=t.call(this,e,r)).camera=e,s._state=new ti({matrix:q.mat4(),inverseMatrix:q.mat4(),transposedMatrix:q.mat4(),near:.1,far:1e4}),s._left=-1,s._right=1,s._bottom=-1,s._top=1,s._inverseMatrixDirty=!0,s._transposedMatrixDirty=!0,s.left=r.left,s.right=r.right,s.bottom=r.bottom,s.top=r.top,s.near=r.near,s.far=r.far,s}return I(i,[{key:"type",get:function(){return"Frustum"}},{key:"_update",value:function(){q.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&&(q.inverseMat4(this._state.matrix,this._state.inverseMatrix),this._inverseMatrixDirty=!1),this._state.inverseMatrix}},{key:"transposedMatrix",get:function(){return this._updateScheduled&&this._doUpdate(),this._transposedMatrixDirty&&(q.transposeMat4(this._state.matrix,this._state.transposedMatrix),this._transposedMatrixDirty=!1),this._state.transposedMatrix}},{key:"unproject",value:function(e,t,i,s,r){var n=this.scene.canvas.canvas,o=n.offsetWidth/2,a=n.offsetHeight/2;return i[0]=(e[0]-o)/o,i[1]=(e[1]-a)/a,i[2]=t,i[3]=1,q.mulMat4v4(this.inverseMatrix,i,s),q.mulVec3Scalar(s,1/s[3]),s[3]=1,s[1]*=-1,q.mulMat4v4(this.camera.inverseViewMatrix,s,r),r}},{key:"destroy",value:function(){m(P(i.prototype),"destroy",this).call(this),this._state.destroy(),m(P(i.prototype),"destroy",this).call(this)}}]),i}(),pi=function(e){g(i,fe);var t=y(i);function i(e){var s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return w(this,i),(s=t.call(this,e,r)).camera=e,s._state=new ti({matrix:q.mat4(),inverseMatrix:q.mat4(),transposedMatrix:q.mat4()}),s._inverseMatrixDirty=!0,s._transposedMatrixDirty=!1,s.matrix=r.matrix,s}return I(i,[{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&&(q.inverseMat4(this._state.matrix,this._state.inverseMatrix),this._inverseMatrixDirty=!1),this._state.inverseMatrix}},{key:"transposedMatrix",get:function(){return this._updateScheduled&&this._doUpdate(),this._transposedMatrixDirty&&(q.transposeMat4(this._state.matrix,this._state.transposedMatrix),this._transposedMatrixDirty=!1),this._state.transposedMatrix}},{key:"unproject",value:function(e,t,i,s,r){var n=this.scene.canvas.canvas,o=n.offsetWidth/2,a=n.offsetHeight/2;return i[0]=(e[0]-o)/o,i[1]=(e[1]-a)/a,i[2]=t,i[3]=1,q.mulMat4v4(this.inverseMatrix,i,s),q.mulVec3Scalar(s,1/s[3]),s[3]=1,s[1]*=-1,q.mulMat4v4(this.camera.inverseViewMatrix,s,r),r}},{key:"destroy",value:function(){m(P(i.prototype),"destroy",this).call(this),this._state.destroy()}}]),i}(),di=q.vec3(),fi=q.vec3(),mi=q.vec3(),vi=q.vec3(),gi=q.vec3(),_i=q.vec3(),yi=q.mat4(),bi=q.mat4(),xi=q.vec3(),Pi=q.vec3(),Ti=q.vec3(),wi=q.vec3(),Mi=function(e){g(i,fe);var t=y(i);function i(e){var s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return w(this,i),(s=t.call(this,e,r))._state=new ti({deviceMatrix:q.mat4(),hasDeviceMatrix:!1,matrix:q.mat4(),normalMatrix:q.mat4(),inverseMatrix:q.mat4()}),s._perspective=new hi(x(s)),s._ortho=new li(x(s)),s._frustum=new ci(x(s)),s._customProjection=new pi(x(s)),s._project=s._perspective,s._eye=q.vec3([0,0,10]),s._look=q.vec3([0,0,0]),s._up=q.vec3([0,1,0]),s._worldUp=q.vec3([0,1,0]),s._worldRight=q.vec3([1,0,0]),s._worldForward=q.vec3([0,0,-1]),s.deviceMatrix=r.deviceMatrix,s.eye=r.eye,s.look=r.look,s.up=r.up,s.worldAxis=r.worldAxis,s.gimbalLock=r.gimbalLock,s.constrainPitch=r.constrainPitch,s.projection=r.projection,s._perspective.on("matrix",(function(){"perspective"===s._projectionType&&s.fire("projMatrix",s._perspective.matrix)})),s._ortho.on("matrix",(function(){"ortho"===s._projectionType&&s.fire("projMatrix",s._ortho.matrix)})),s._frustum.on("matrix",(function(){"frustum"===s._projectionType&&s.fire("projMatrix",s._frustum.matrix)})),s._customProjection.on("matrix",(function(){"customProjection"===s._projectionType&&s.fire("projMatrix",s._customProjection.matrix)})),s}return I(i,[{key:"type",get:function(){return"Camera"}},{key:"_update",value:function(){var e,t=this._state;"ortho"===this.projection?(q.subVec3(this._eye,this._look,xi),q.normalizeVec3(xi,Pi),q.mulVec3Scalar(Pi,1e3,Ti),q.addVec3(this._look,Ti,wi),e=wi):e=this._eye,t.hasDeviceMatrix?(q.lookAtMat4v(e,this._look,this._up,bi),q.mulMat4(t.deviceMatrix,bi,t.matrix)):q.lookAtMat4v(e,this._look,this._up,t.matrix),q.inverseMat4(this._state.matrix,this._state.inverseMatrix),q.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=q.subVec3(this._eye,this._look,di);q.rotationMat4v(.0174532925*e,this._gimbalLock?this._worldUp:this._up,yi),t=q.transformPoint3(yi,t,fi),this.eye=q.addVec3(this._look,t,mi),this.up=q.transformPoint3(yi,this._up,vi)}},{key:"orbitPitch",value:function(e){if(!(this._constrainPitch&&(e=q.dotVec3(this._up,this._worldUp)/q.DEGTORAD)<1)){var t=q.subVec3(this._eye,this._look,di),i=q.cross3Vec3(q.normalizeVec3(t,fi),q.normalizeVec3(this._up,mi));q.rotationMat4v(.0174532925*e,i,yi),t=q.transformPoint3(yi,t,vi),this.up=q.transformPoint3(yi,this._up,gi),this.eye=q.addVec3(t,this._look,_i)}}},{key:"yaw",value:function(e){var t=q.subVec3(this._look,this._eye,di);q.rotationMat4v(.0174532925*e,this._gimbalLock?this._worldUp:this._up,yi),t=q.transformPoint3(yi,t,fi),this.look=q.addVec3(t,this._eye,mi),this._gimbalLock&&(this.up=q.transformPoint3(yi,this._up,vi))}},{key:"pitch",value:function(e){if(!(this._constrainPitch&&(e=q.dotVec3(this._up,this._worldUp)/q.DEGTORAD)<1)){var t=q.subVec3(this._look,this._eye,di),i=q.cross3Vec3(q.normalizeVec3(t,fi),q.normalizeVec3(this._up,mi));q.rotationMat4v(.0174532925*e,i,yi),this.up=q.transformPoint3(yi,this._up,_i),t=q.transformPoint3(yi,t,vi),this.look=q.addVec3(t,this._eye,gi)}}},{key:"pan",value:function(e){var t,i=q.subVec3(this._eye,this._look,di),s=[0,0,0];if(0!==e[0]){var r=q.cross3Vec3(q.normalizeVec3(i,[]),q.normalizeVec3(this._up,fi));t=q.mulVec3Scalar(r,e[0]),s[0]+=t[0],s[1]+=t[1],s[2]+=t[2]}0!==e[1]&&(t=q.mulVec3Scalar(q.normalizeVec3(this._up,mi),e[1]),s[0]+=t[0],s[1]+=t[1],s[2]+=t[2]),0!==e[2]&&(t=q.mulVec3Scalar(q.normalizeVec3(i,vi),e[2]),s[0]+=t[0],s[1]+=t[1],s[2]+=t[2]),this.eye=q.addVec3(this._eye,s,gi),this.look=q.addVec3(this._look,s,_i)}},{key:"zoom",value:function(e){var t=q.subVec3(this._eye,this._look,di),i=Math.abs(q.lenVec3(t,fi)),s=Math.abs(i+e);if(!(s<.5)){var r=q.normalizeVec3(t,mi);this.eye=q.addVec3(this._look,q.mulVec3Scalar(r,s),vi)}}},{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=q.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 q.lenVec3(q.subVec3(this._look,this._eye,di))}},{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:"destroy",value:function(){m(P(i.prototype),"destroy",this).call(this),this._state.destroy()}}]),i}(),Ii=q.vec4(),Ci=q.vec3(),Di=function(){function e(t,i){w(this,e),this._scene=t,this._withSAO=i,this._hash=this._getHash(),this._allocate()}return I(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,i){var s=this._scene,r=s.camera,n=t.model,o=s.canvas.gl,a=t._state,u=a.textureState,h=t._state.origin;if(this._program||(this._allocate(),!this.errors)){e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e,a)),u.bindCommonTextures(this._program,this._uTexturePerObjectIdPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this._uTexturePerObjectIdColorsAndFlags,this._uTextureCameraMatrices,this._uTextureModelMatrices,this._uTexturePerObjectIdOffsets);var l=r.eye;e.pickViewMatrix&&(u.bindPickCameraTexture(this._program,this._uTextureCameraMatrices),l=e.pickOrigin||l);var c=[l[0]-h[0],l[1]-h[1],l[2]-h[2]];o.uniform3fv(this._uCameraEyeRtc,c),o.uniform1i(this._uRenderPass,i);var p=s._sectionPlanesState.sectionPlanes.length;if(p>0)for(var d=s._sectionPlanesState.sectionPlanes,f=t.layerIndex*p,m=n.renderFlags,v=0;v<p;v++){var g=this._uSectionPlanes[v];if(g){var _=m.sectionPlanesActivePerLayer[f+v];if(o.uniform1i(g.active,_?1:0),_){var y=d[v];if(h){var b=Ee(y.dist,y.dir,h,Ci);o.uniform3fv(g.pos,b)}else o.uniform3fv(g.pos,y.pos);o.uniform3fv(g.dir,y.dir)}}}a.numIndices8Bits>0&&(u.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),o.drawArrays(o.TRIANGLES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(u.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),o.drawArrays(o.TRIANGLES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(u.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),o.drawArrays(o.TRIANGLES,0,a.numIndices32Bits)),e.drawElements++}}},{key:"_allocate",value:function(){var e=this._scene,t=e.canvas.gl,i=e._lightsState;if(this._program=new ht(t,this._buildShader()),this._program.errors)this.errors=this._program.errors;else{var s=this._program;this._uRenderPass=s.getLocation("renderPass"),this._uLightAmbient=s.getLocation("lightAmbient"),this._uLightColor=[],this._uLightDir=[],this._uLightPos=[],this._uLightAttenuation=[];for(var r=i.lights,n=0,o=r.length;n<o;n++)switch(r[n].type){case"dir":this._uLightColor[n]=s.getLocation("lightColor"+n),this._uLightPos[n]=null,this._uLightDir[n]=s.getLocation("lightDir"+n);break;case"point":this._uLightColor[n]=s.getLocation("lightColor"+n),this._uLightPos[n]=s.getLocation("lightPos"+n),this._uLightDir[n]=null,this._uLightAttenuation[n]=s.getLocation("lightAttenuation"+n);break;case"spot":this._uLightColor[n]=s.getLocation("lightColor"+n),this._uLightPos[n]=s.getLocation("lightPos"+n),this._uLightDir[n]=s.getLocation("lightDir"+n),this._uLightAttenuation[n]=s.getLocation("lightAttenuation"+n)}this._uSectionPlanes=[];for(var a=0,u=e._sectionPlanesState.sectionPlanes.length;a<u;a++)this._uSectionPlanes.push({active:s.getLocation("sectionPlaneActive"+a),pos:s.getLocation("sectionPlanePos"+a),dir:s.getLocation("sectionPlaneDir"+a)});this._withSAO&&(this._uOcclusionTexture="uOcclusionTexture",this._uSAOParams=s.getLocation("uSAOParams")),e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=s.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=s.getLocation("uCameraEyeRtc")}}},{key:"_bindProgram",value:function(e){var t=this._scene,i=t.canvas.gl,s=this._program,r=t._lightsState.lights,n=t.camera.project;s.bind(),this._uLightAmbient&&i.uniform4fv(this._uLightAmbient,t._lightsState.getAmbientColorAndIntensity());for(var o=0,a=r.length;o<a;o++){var u=r[o];this._uLightColor[o]&&i.uniform4f(this._uLightColor[o],u.color[0],u.color[1],u.color[2],u.intensity),this._uLightPos[o]&&(i.uniform3fv(this._uLightPos[o],u.pos),this._uLightAttenuation[o]&&i.uniform1f(this._uLightAttenuation[o],u.attenuation)),this._uLightDir[o]&&i.uniform3fv(this._uLightDir[o],u.dir)}if(this._withSAO){var h=t.sao;if(h.possible){var l=i.drawingBufferWidth,c=i.drawingBufferHeight;Ii[0]=l,Ii[1]=c,Ii[2]=h.blendCutoff,Ii[3]=h.blendFactor,i.uniform4fv(this._uSAOParams,Ii),this._program.bindTexture(this._uOcclusionTexture,e.occlusionTexture,10)}}if(t.logarithmicDepthBufferEnabled){var p=2/(Math.log(n.far+1)/Math.LN2);i.uniform1f(this._uLogDepthBufFC,p)}}},{key:"_buildShader",value:function(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}},{key:"_buildVertexShader",value:function(){var e,t=this._scene,i=t._sectionPlanesState,s=t._lightsState,r=i.sectionPlanes.length>0,n=[];n.push("#version 300 es"),n.push("// Triangles dataTexture draw 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;"),t.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];"),t.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("uniform vec4 lightAmbient;");for(var o=0,a=s.lights.length;o<a;o++)"ambient"!==(e=s.lights[o]).type&&(n.push("uniform vec4 lightColor"+o+";"),"dir"===e.type&&n.push("uniform vec3 lightDir"+o+";"),"point"===e.type&&n.push("uniform vec3 lightPos"+o+";"),"spot"===e.type&&(n.push("uniform vec3 lightPos"+o+";"),n.push("uniform vec3 lightDir"+o+";")));r&&(n.push("out vec4 vWorldPosition;"),n.push("flat out uint vFlags2;")),n.push("out vec4 vColor;"),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("if (int(flags.x) != renderPass) {"),n.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),n.push(" return;"),n.push("} else {"),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*8+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*8+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0));"),n.push("mat4 entityMatrix = mat4 (texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*8+6, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0));"),n.push("positionsDecodeMatrix = entityMatrix * positionsDecodeMatrix;"),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("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("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),n.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),n.push("float lambertian = 1.0;");for(var u=0,h=s.lights.length;u<h;u++)if("ambient"!==(e=s.lights[u]).type){if("dir"===e.type)"view"===e.space?n.push("viewLightDir = normalize(lightDir"+u+");"):n.push("viewLightDir = normalize((viewMatrix * vec4(lightDir"+u+", 0.0)).xyz);");else if("point"===e.type)"view"===e.space?n.push("viewLightDir = -normalize(lightPos"+u+" - viewPosition.xyz);"):n.push("viewLightDir = -normalize((viewMatrix * vec4(lightPos"+u+", 0.0)).xyz);");else{if("spot"!==e.type)continue;"view"===e.space?n.push("viewLightDir = normalize(lightDir"+u+");"):n.push("viewLightDir = normalize((viewMatrix * vec4(lightDir"+u+", 0.0)).xyz);")}n.push("lambertian = max(dot(-viewNormal, viewLightDir), 0.0);"),n.push("reflectedColor += lambertian * (lightColor"+u+".rgb * lightColor"+u+".a);")}return n.push("vec3 rgb = vec3(color.rgb) / 255.0;"),n.push("vColor = vec4((lightAmbient.rgb * lightAmbient.a * rgb) + (reflectedColor * rgb), float(color.a) / 255.0);"),n.push("vec4 clipPos = projMatrix * viewPosition;"),t.logarithmicDepthBufferEnabled&&(n.push("vFragDepth = 1.0 + clipPos.w;"),n.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),r&&(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,i=t.sectionPlanes.length>0,s=[];if(s.push("#version 300 es"),s.push("// Triangles dataTexture draw fragment shader"),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&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),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 unpackRGBToFloat( const in vec4 v ) {"),s.push(" return dot( v, unPackFactors );"),s.push("}")),i){s.push("in vec4 vWorldPosition;"),s.push("flat in uint vFlags2;");for(var r=0,n=t.sectionPlanes.length;r<n;r++)s.push("uniform bool sectionPlaneActive"+r+";"),s.push("uniform vec3 sectionPlanePos"+r+";"),s.push("uniform vec3 sectionPlaneDir"+r+";")}if(s.push("in vec4 vColor;"),s.push("out vec4 outColor;"),s.push("void main(void) {"),i){s.push(" bool clippable = vFlags2 > 0u;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var o=0,a=t.sectionPlanes.length;o<a;o++)s.push("if (sectionPlaneActive"+o+") {"),s.push(" dist += clamp(dot(-sectionPlaneDir"+o+".xyz, vWorldPosition.xyz - sectionPlanePos"+o+".xyz), 0.0, 1000.0);"),s.push("}");s.push(" if (dist > 0.0) { "),s.push(" discard;"),s.push(" }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),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, unpackRGBToFloat(texture(uOcclusionTexture, uv))) * blendFactor;"),s.push(" outColor = vec4(vColor.rgb * ambient, 1.0);")):s.push(" outColor = vColor;"),s.push("}"),s}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),e}(),Ai=new Float32Array([1,1,1]);q.vec4();var ki=q.vec3(),Ei=function(){function e(t,i){w(this,e),this._scene=t,this._hash=this._getHash(),this._allocate()}return I(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,i){var s=this._scene,r=s.camera,n=t.model,o=s.canvas.gl,a=t._state,u=a.textureState,h=t._state.origin;if(this._program||(this._allocate(),!this.errors)){e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e,a)),u.bindCommonTextures(this._program,this._uTexturePerObjectIdPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this._uTexturePerObjectIdColorsAndFlags,this._uTextureCameraMatrices,this._uTextureModelMatrices,this._uTexturePerObjectIdOffsets);var l=r.eye;e.pickViewMatrix&&(u.bindPickCameraTexture(this._program,this._uTextureCameraMatrices),l=e.pickOrigin||l);var c=[l[0]-h[0],l[1]-h[1],l[2]-h[2]];if(o.uniform3fv(this._uCameraEyeRtc,c),o.uniform1i(this._uRenderPass,i),i===Yt){var p=s.xrayMaterial._state,d=p.fillColor,f=p.fillAlpha;o.uniform4f(this._uColor,d[0],d[1],d[2],f)}else if(i===Wt){var m=s.highlightMaterial._state,v=m.fillColor,g=m.fillAlpha;o.uniform4f(this._uColor,v[0],v[1],v[2],g)}else if(i===Xt){var _=s.selectedMaterial._state,y=_.fillColor,b=_.fillAlpha;o.uniform4f(this._uColor,y[0],y[1],y[2],b)}else o.uniform4fv(this._uColor,Ai);var x=s._sectionPlanesState.sectionPlanes.length;if(x>0)for(var P=s._sectionPlanesState.sectionPlanes,T=t.layerIndex*x,w=n.renderFlags,M=0;M<x;M++){var I=this._uSectionPlanes[M];if(I){var C=w.sectionPlanesActivePerLayer[T+M];if(o.uniform1i(I.active,C?1:0),C){var D=P[M];if(h){var A=Ee(D.dist,D.dir,h,ki);o.uniform3fv(I.pos,A)}else o.uniform3fv(I.pos,D.pos);o.uniform3fv(I.dir,D.dir)}}}a.numIndices8Bits>0&&(u.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),o.drawArrays(o.TRIANGLES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(u.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),o.drawArrays(o.TRIANGLES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(u.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),o.drawArrays(o.TRIANGLES,0,a.numIndices32Bits)),e.drawElements++}}},{key:"_allocate",value:function(){var e=this._scene,t=e.canvas.gl;if(this._program=new ht(t,this._buildShader()),this._program.errors)this.errors=this._program.errors;else{var i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uColor=i.getLocation("color"),this._uSectionPlanes=[];for(var s=0,r=e._sectionPlanesState.sectionPlanes.length;s<r;s++)this._uSectionPlanes.push({active:i.getLocation("sectionPlaneActive"+s),pos:i.getLocation("sectionPlanePos"+s),dir:i.getLocation("sectionPlaneDir"+s)});e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=i.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=i.getLocation("uCameraEyeRtc")}}},{key:"_bindProgram",value:function(e){var t=this._scene,i=t.canvas.gl,s=t.camera.project;if(this._program.bind(),t.logarithmicDepthBufferEnabled){var r=2/(Math.log(s.far+1)/Math.LN2);i.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,i=[];return i.push("#version 300 es"),i.push("// Triangles dataTexture silhouette vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform highp sampler2D uTexturePerObjectIdPositionsDecodeMatrix;"),i.push("uniform lowp usampler2D uTexturePerObjectIdColorsAndFlags;"),i.push("uniform highp sampler2D uTexturePerObjectIdOffsets;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),i.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),i.push("uniform highp sampler2D uTextureCameraMatrices;"),i.push("uniform highp sampler2D uTextureModelMatrices;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;")),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),t&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("void main(void) {"),i.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));"),i.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));"),i.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));"),i.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));"),i.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));"),i.push("int polygonIndex = gl_VertexID / 3;"),i.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.y) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("} else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),i.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),i.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),i.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),i.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),i.push("mat4 positionsDecodeMatrix = mat4 (texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*8+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0));"),i.push("mat4 entityMatrix = mat4 (texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*8+6, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0));"),i.push("positionsDecodeMatrix = entityMatrix * positionsDecodeMatrix;"),i.push("uint solid = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),i.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),i.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),i.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),i.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),i.push("vec3 position;"),i.push("position = positions[gl_VertexID % 3];"),i.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*positionsDecodeMatrix)) * vec4(normal,1)).xyz);"),i.push("if (solid != 1u) {"),i.push("if (isPerspectiveMatrix(projMatrix)) {"),i.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(worldMatrix * positionsDecodeMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),i.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("viewNormal = -viewNormal;"),i.push("}"),i.push("} else {"),i.push("if (viewNormal.z < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("viewNormal = -viewNormal;"),i.push("}"),i.push("}"),i.push("}"),i.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),i.push("vec4 offset = vec4(texelFetch (uTexturePerObjectIdOffsets, objectIndexCoords, 0).rgb, 0.0);"),i.push("worldPosition.xyz = worldPosition.xyz + offset.xyz;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags2 = flags2.r;")),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.sectionPlanes.length>0,s=[];if(s.push("#version 300 es"),s.push("// Triangles dataTexture draw fragment shader"),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&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("varying float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("flat in uint vFlags2;");for(var r=0,n=t.sectionPlanes.length;r<n;r++)s.push("uniform bool sectionPlaneActive"+r+";"),s.push("uniform vec3 sectionPlanePos"+r+";"),s.push("uniform vec3 sectionPlaneDir"+r+";")}if(s.push("uniform vec4 color;"),s.push("out vec4 outColor;"),s.push("void main(void) {"),i){s.push(" bool clippable = vFlags2 > 0u;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var o=0,a=t.sectionPlanes.length;o<a;o++)s.push("if (sectionPlaneActive"+o+") {"),s.push(" dist += clamp(dot(-sectionPlaneDir"+o+".xyz, vWorldPosition.xyz - sectionPlanePos"+o+".xyz), 0.0, 1000.0);"),s.push("}");s.push(" if (dist > 0.0) { "),s.push(" discard;"),s.push(" }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = color;"),s.push("}"),s}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),e}(),Fi=q.vec3(),Ri=new Float32Array([0,0,0,1]),Si=function(){function e(t){w(this,e),this._scene=t,this._hash=this._getHash(),this._allocate()}return I(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,i){var s=t.model,r=s.scene,n=r.camera,o=r.canvas.gl,a=t._state,u=a.textureState,h=t._state.origin;if(this._program||(this._allocate(t),!this.errors)){if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram()),u.bindCommonTextures(this._program,this._uTexturePerObjectIdPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this._uTexturePerObjectIdColorsAndFlags,this._uTextureCameraMatrices,this._uTextureModelMatrices,this._uTexturePerObjectIdOffsets),e.pickViewMatrix&&u.bindPickCameraTexture(this._program,this._uTextureCameraMatrices),o.uniform1i(this._uRenderPass,i),i===qt){var l=r.xrayMaterial._state,c=l.edgeColor,p=l.edgeAlpha;o.uniform4f(this._uColor,c[0],c[1],c[2],p)}else if(i===Zt){var d=r.highlightMaterial._state,f=d.edgeColor,m=d.edgeAlpha;o.uniform4f(this._uColor,f[0],f[1],f[2],m)}else if(i===Qt){var v=r.selectedMaterial._state,g=v.edgeColor,_=v.edgeAlpha;o.uniform4f(this._uColor,g[0],g[1],g[2],_)}else o.uniform4fv(this._uColor,Ri);o.uniformMatrix4fv(this._uViewMatrix,!1,h?De(n.viewMatrix,h):n.viewMatrix),o.uniformMatrix4fv(this._uWorldMatrix,!1,s.worldMatrix);var y=r._sectionPlanesState.sectionPlanes.length;if(y>0)for(var b=r._sectionPlanesState.sectionPlanes,x=t.layerIndex*y,P=s.renderFlags,T=0;T<y;T++){var w=this._uSectionPlanes[T];if(w){var M=P.sectionPlanesActivePerLayer[x+T];if(o.uniform1i(w.active,M?1:0),M){var I=b[T];if(h){var C=Ee(I.dist,I.dir,h,Fi);o.uniform3fv(w.pos,C)}else o.uniform3fv(w.pos,I.pos);o.uniform3fv(w.dir,I.dir)}}}a.numEdgeIndices8Bits>0&&(u.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,8),o.drawArrays(o.LINES,0,a.numEdgeIndices8Bits)),a.numEdgeIndices16Bits>0&&(u.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,16),o.drawArrays(o.LINES,0,a.numEdgeIndices16Bits)),a.numEdgeIndices32Bits>0&&(u.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,32),o.drawArrays(o.LINES,0,a.numEdgeIndices32Bits)),e.drawElements++}}},{key:"_allocate",value:function(){var e=this._scene,t=e.canvas.gl;if(this._program=new ht(t,this._buildShader()),this._program.errors)this.errors=this._program.errors;else{var i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uColor=i.getLocation("color"),this._uSectionPlanes=[];for(var s=0,r=e._sectionPlanesState.sectionPlanes.length;s<r;s++)this._uSectionPlanes.push({active:i.getLocation("sectionPlaneActive"+s),pos:i.getLocation("sectionPlanePos"+s),dir:i.getLocation("sectionPlaneDir"+s)});e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=i.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,i=this._program,s=e.camera.project;if(i.bind(),e.logarithmicDepthBufferEnabled){var r=2/(Math.log(s.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,i=[];return i.push("#version 300 es"),i.push("// Batched geometry edges drawing vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform highp sampler2D uTexturePerObjectIdPositionsDecodeMatrix;"),i.push("uniform lowp usampler2D uTexturePerObjectIdColorsAndFlags;"),i.push("uniform highp sampler2D uTexturePerObjectIdOffsets;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdEdgeIndices;"),i.push("uniform mediump usampler2D uTexturePerEdgeIdPortionIds;"),i.push("uniform highp sampler2D uTextureCameraMatrices;"),i.push("uniform highp sampler2D uTextureModelMatrices;"),i.push("uniform vec4 color;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.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));"),i.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));"),i.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));"),i.push("int edgeIndex = gl_VertexID / 2;"),i.push("int h_packed_object_id_index = (edgeIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (edgeIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerEdgeIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.z) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("} else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedEdgeIndexBaseOffset = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+6, objectIndexCoords.y), 0));"),i.push("int edgeIndexBaseOffset = (packedEdgeIndexBaseOffset.r << 24) + (packedEdgeIndexBaseOffset.g << 16) + (packedEdgeIndexBaseOffset.b << 8) + packedEdgeIndexBaseOffset.a;"),i.push("int h_index = (edgeIndex - edgeIndexBaseOffset) & 4095;"),i.push("int v_index = (edgeIndex - edgeIndexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdEdgeIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("int indexPositionH = uniqueVertexIndexes[gl_VertexID % 2] & 4095;"),i.push("int indexPositionV = uniqueVertexIndexes[gl_VertexID % 2] >> 12;"),i.push("mat4 positionsDecodeMatrix = mat4 (texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*8+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0));"),i.push("mat4 entityMatrix = mat4 (texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*8+6, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0));"),i.push("positionsDecodeMatrix = entityMatrix * positionsDecodeMatrix;"),i.push("uvec4 flags = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("vec3 position = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH, indexPositionV), 0));"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),i.push("vec4 offset = vec4(texelFetch (uTexturePerObjectIdOffsets, objectIndexCoords, 0).rgb, 0.0);"),i.push("worldPosition.xyz = worldPosition.xyz + offset.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags2 = flags2.r;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("vColor = vec4(color.r, color.g, color.b, color.a);"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.sectionPlanes.length>0,s=[];if(s.push("#version 300 es"),s.push("// Batched geometry edges drawing fragment shader"),e.logarithmicDepthBufferEnabled&&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&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("flat in uint vFlags2;");for(var r=0,n=t.sectionPlanes.length;r<n;r++)s.push("uniform bool sectionPlaneActive"+r+";"),s.push("uniform vec3 sectionPlanePos"+r+";"),s.push("uniform vec3 sectionPlaneDir"+r+";")}if(s.push("in vec4 vColor;"),s.push("out vec4 outColor;"),s.push("void main(void) {"),i){s.push(" bool clippable = vFlags2 > 0u;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var o=0,a=t.sectionPlanes.length;o<a;o++)s.push("if (sectionPlaneActive"+o+") {"),s.push(" dist += clamp(dot(-sectionPlaneDir"+o+".xyz, vWorldPosition.xyz - sectionPlanePos"+o+".xyz), 0.0, 1000.0);"),s.push("}");s.push(" if (dist > 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = vColor;"),s.push("}"),s}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),e}(),Oi=q.vec3(),Bi=function(){function e(t){w(this,e),this._scene=t,this._hash=this._getHash(),this._allocate()}return I(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,i){var s=t.model,r=s.scene;r.camera;var n=r.canvas.gl,o=t._state,a=o.textureState,u=t._state.origin;if(this._program||(this._allocate(t),!this.errors)){e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram()),a.bindCommonTextures(this._program,this._uTexturePerObjectIdPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this._uTexturePerObjectIdColorsAndFlags,this._uTextureCameraMatrices,this._uTextureModelMatrices,this._uTexturePerObjectIdOffsets),e.pickViewMatrix&&a.bindPickCameraTexture(this._program,this._uTextureCameraMatrices),n.uniform1i(this._uRenderPass,i);var h=r._sectionPlanesState.sectionPlanes.length;if(h>0)for(var l=r._sectionPlanesState.sectionPlanes,c=t.layerIndex*h,p=s.renderFlags,d=0;d<h;d++){var f=this._uSectionPlanes[d];if(f){var m=p.sectionPlanesActivePerLayer[c+d];if(n.uniform1i(f.active,m?1:0),m){var v=l[d];if(u){var g=Ee(v.dist,v.dir,u,Oi);n.uniform3fv(f.pos,g)}else n.uniform3fv(f.pos,v.pos);n.uniform3fv(f.dir,v.dir)}}}o.numEdgeIndices8Bits>0&&(a.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,8),n.drawArrays(n.LINES,0,o.numEdgeIndices8Bits)),o.numEdgeIndices16Bits>0&&(a.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,16),n.drawArrays(n.LINES,0,o.numEdgeIndices16Bits)),o.numEdgeIndices32Bits>0&&(a.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,32),n.drawArrays(n.LINES,0,o.numEdgeIndices32Bits)),e.drawElements++}}},{key:"_allocate",value:function(){var e=this._scene,t=e.canvas.gl;if(this._program=new ht(t,this._buildShader()),this._program.errors)this.errors=this._program.errors;else{var i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uSectionPlanes=[];for(var s=0,r=e._sectionPlanesState.sectionPlanes.length;s<r;s++)this._uSectionPlanes.push({active:i.getLocation("sectionPlaneActive"+s),pos:i.getLocation("sectionPlanePos"+s),dir:i.getLocation("sectionPlaneDir"+s)});e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=i.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,i=this._program,s=e.camera.project;if(i.bind(),e.logarithmicDepthBufferEnabled){var r=2/(Math.log(s.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,i=[];return i.push("#version 300 es"),i.push("// Batched geometry edges drawing vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform highp sampler2D uTexturePerObjectIdPositionsDecodeMatrix;"),i.push("uniform lowp usampler2D uTexturePerObjectIdColorsAndFlags;"),i.push("uniform highp sampler2D uTexturePerObjectIdOffsets;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdEdgeIndices;"),i.push("uniform mediump usampler2D uTexturePerEdgeIdPortionIds;"),i.push("uniform highp sampler2D uTextureCameraMatrices;"),i.push("uniform highp sampler2D uTextureModelMatrices;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.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));"),i.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));"),i.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));"),i.push("int edgeIndex = gl_VertexID / 2;"),i.push("int h_packed_object_id_index = (edgeIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (edgeIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerEdgeIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.z) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("} else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedEdgeIndexBaseOffset = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+6, objectIndexCoords.y), 0));"),i.push("int edgeIndexBaseOffset = (packedEdgeIndexBaseOffset.r << 24) + (packedEdgeIndexBaseOffset.g << 16) + (packedEdgeIndexBaseOffset.b << 8) + packedEdgeIndexBaseOffset.a;"),i.push("int h_index = (edgeIndex - edgeIndexBaseOffset) & 4095;"),i.push("int v_index = (edgeIndex - edgeIndexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdEdgeIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("int indexPositionH = uniqueVertexIndexes[gl_VertexID % 2] & 4095;"),i.push("int indexPositionV = uniqueVertexIndexes[gl_VertexID % 2] >> 12;"),i.push("mat4 positionsDecodeMatrix = mat4 (texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*8+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0));"),i.push("mat4 entityMatrix = mat4 (texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*8+6, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0));"),i.push("positionsDecodeMatrix = entityMatrix * positionsDecodeMatrix;"),i.push("uvec4 flags = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("vec3 position = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH, indexPositionV), 0));"),i.push("uvec4 color = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push("if (color.a == 0u) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("};"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),i.push("vec4 offset = vec4(texelFetch (uTexturePerObjectIdOffsets, objectIndexCoords, 0).rgb, 0.0);"),i.push("worldPosition.xyz = worldPosition.xyz + offset.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags2 = flags2.r;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("vec4 rgb = vec4(color.rgba);"),i.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);"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.sectionPlanes.length>0,s=[];if(s.push("#version 300 es"),s.push("// Batched geometry edges drawing fragment shader"),e.logarithmicDepthBufferEnabled&&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&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("flat in uint vFlags2;");for(var r=0,n=t.sectionPlanes.length;r<n;r++)s.push("uniform bool sectionPlaneActive"+r+";"),s.push("uniform vec3 sectionPlanePos"+r+";"),s.push("uniform vec3 sectionPlaneDir"+r+";")}if(s.push("in vec4 vColor;"),s.push("out vec4 outColor;"),s.push("void main(void) {"),i){s.push(" bool clippable = vFlags2 > 0u;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var o=0,a=t.sectionPlanes.length;o<a;o++)s.push("if (sectionPlaneActive"+o+") {"),s.push(" dist += clamp(dot(-sectionPlaneDir"+o+".xyz, vWorldPosition.xyz - sectionPlanePos"+o+".xyz), 0.0, 1000.0);"),s.push("}");s.push(" if (dist > 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = vColor;"),s.push("}"),s}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),e}(),Li=q.vec3(),Ni=function(){function e(t){w(this,e),this._scene=t,this._hash=this._getHash(),this._allocate()}return I(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,i){var s=t.model,r=s.scene,n=r.camera,o=r.canvas.gl,a=t._state,u=a.textureState,h=t._state.origin;this._program||this._allocate(t),e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),u.bindCommonTextures(this._program,this._uTexturePerObjectIdPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this._uTexturePerObjectIdColorsAndFlags,this._uTextureCameraMatrices,this._uTextureModelMatrices,this._uTexturePerObjectIdOffsets);var l=n.eye;e.pickViewMatrix&&(u.bindPickCameraTexture(this._program,this._uTextureCameraMatrices),l=e.pickOrigin||l);var c=[l[0]-h[0],l[1]-h[1],l[2]-h[2]];if(o.uniform3fv(this._uCameraEyeRtc,c),o.uniform1i(this._uRenderPass,i),r.logarithmicDepthBufferEnabled){var p=2/(Math.log(n.project.far+1)/Math.LN2);o.uniform1f(this._uLogDepthBufFC,p)}var d=r._sectionPlanesState.sectionPlanes.length;if(d>0)for(var f=r._sectionPlanesState.sectionPlanes,m=t.layerIndex*d,v=s.renderFlags,g=0;g<d;g++){var _=this._uSectionPlanes[g];if(_){var y=v.sectionPlanesActivePerLayer[m+g];if(o.uniform1i(_.active,y?1:0),y){var b=f[g];if(h){var x=Ee(b.dist,b.dir,h,Li);o.uniform3fv(_.pos,x)}else o.uniform3fv(_.pos,b.pos);o.uniform3fv(_.dir,b.dir)}}}a.numIndices8Bits>0&&(u.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),o.drawArrays(o.TRIANGLES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(u.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),o.drawArrays(o.TRIANGLES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(u.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),o.drawArrays(o.TRIANGLES,0,a.numIndices32Bits)),e.drawElements++}},{key:"_allocate",value:function(){var e=this._scene,t=e.canvas.gl;if(this._program=new ht(t,this._buildShader()),this._program.errors)this.errors=this._program.errors;else{var i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPickInvisible=i.getLocation("pickInvisible"),this._uSectionPlanes=[];for(var s=0,r=e._sectionPlanesState.sectionPlanes.length;s<r;s++)this._uSectionPlanes.push({active:i.getLocation("sectionPlaneActive"+s),pos:i.getLocation("sectionPlanePos"+s),dir:i.getLocation("sectionPlaneDir"+s)});this._withSAO&&(this._uOcclusionTexture="uOcclusionTexture",this._uSAOParams=i.getLocation("uSAOParams")),e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=i.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=i.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,i=[];return i.push("#version 300 es"),i.push("// Batched geometry picking vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform bool pickInvisible;"),i.push("uniform highp sampler2D uTexturePerObjectIdPositionsDecodeMatrix;"),i.push("uniform lowp usampler2D uTexturePerObjectIdColorsAndFlags;"),i.push("uniform highp sampler2D uTexturePerObjectIdOffsets;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),i.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),i.push("uniform highp sampler2D uTextureCameraMatrices;"),i.push("uniform highp sampler2D uTextureModelMatrices;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;")),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),t&&(i.push("smooth out vec4 vWorldPosition;"),i.push("flat out uvec4 vFlags2;")),i.push("out vec4 vPickColor;"),i.push("void main(void) {"),i.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));"),i.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));"),i.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));"),i.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));"),i.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));"),i.push("int polygonIndex = gl_VertexID / 3;"),i.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.w) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("} else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),i.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),i.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),i.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),i.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),i.push("mat4 positionsDecodeMatrix = mat4 (texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*8+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0));"),i.push("mat4 entityMatrix = mat4 (texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*8+6, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0));"),i.push("positionsDecodeMatrix = entityMatrix * positionsDecodeMatrix;"),i.push("uint solid = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),i.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),i.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),i.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),i.push("uvec4 color = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push("if (color.a == 0u) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("};"),i.push("vPickColor = vec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+1, objectIndexCoords.y), 0)) / 255.0;"),i.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),i.push("vec3 position;"),i.push("position = positions[gl_VertexID % 3];"),i.push("if (solid != 1u) {"),i.push("if (isPerspectiveMatrix(projMatrix)) {"),i.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(worldMatrix * positionsDecodeMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),i.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("}"),i.push("} else {"),i.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*positionsDecodeMatrix)) * vec4(normal,1)).xyz);"),i.push("if (viewNormal.z < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("}"),i.push("}"),i.push("}"),i.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),i.push("vec4 offset = vec4(texelFetch (uTexturePerObjectIdOffsets, objectIndexCoords, 0).rgb, 0.0);"),i.push("worldPosition.xyz = worldPosition.xyz + offset.xyz;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags2 = flags2;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push(" }"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.sectionPlanes.length>0,s=[];if(s.push("#version 300 es"),s.push("// Batched geometry picking fragment shader"),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&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("flat in uvec4 vFlags2;");for(var r=0;r<t.sectionPlanes.length;r++)s.push("uniform bool sectionPlaneActive"+r+";"),s.push("uniform vec3 sectionPlanePos"+r+";"),s.push("uniform vec3 sectionPlaneDir"+r+";")}if(s.push("in vec4 vPickColor;"),s.push("out vec4 outPickColor;"),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(r=0;r<t.sectionPlanes.length;r++)s.push(" if (sectionPlaneActive"+r+") {"),s.push(" dist += clamp(dot(-sectionPlaneDir"+r+".xyz, vWorldPosition.xyz - sectionPlanePos"+r+".xyz), 0.0, 1000.0);"),s.push(" }");s.push(" if (dist > 0.0) { discard; }"),s.push(" }")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outPickColor = vPickColor; "),s.push("}"),s}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),e}(),ji=q.vec3(),Gi=function(){function e(t){w(this,e),this._scene=t,this._hash=this._getHash(),this._allocate()}return I(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,i){var s=t.model,r=s.scene,n=r.camera,o=r.canvas.gl,a=t._state,u=a.textureState,h=t._state.origin;this._program||this._allocate(),e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram()),u.bindCommonTextures(this._program,this._uTexturePerObjectIdPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this._uTexturePerObjectIdColorsAndFlags,this._uTextureCameraMatrices,this._uTextureModelMatrices,this._uTexturePerObjectIdOffsets);var l=n.eye;e.pickViewMatrix&&(u.bindPickCameraTexture(this._program,this._uTextureCameraMatrices),l=e.pickOrigin||l);var c=[l[0]-h[0],l[1]-h[1],l[2]-h[2]];if(o.uniform3fv(this._uCameraEyeRtc,c),o.uniform1i(this._uRenderPass,i),o.uniform1i(this._uPickInvisible,e.pickInvisible),o.uniform1f(this._uPickZNear,e.pickZNear),o.uniform1f(this._uPickZFar,e.pickZFar),r.logarithmicDepthBufferEnabled){var p=2/(Math.log(e.pickZFar+1)/Math.LN2);o.uniform1f(this._uLogDepthBufFC,p)}var d=r._sectionPlanesState.sectionPlanes.length;if(d>0)for(var f=r._sectionPlanesState.sectionPlanes,m=t.layerIndex*d,v=s.renderFlags,g=0;g<d;g++){var _=this._uSectionPlanes[g];if(_){var y=v.sectionPlanesActivePerLayer[m+g];if(o.uniform1i(_.active,y?1:0),y){var b=f[g];if(h){var x=Ee(b.dist,b.dir,h,ji);o.uniform3fv(_.pos,x)}else o.uniform3fv(_.pos,b.pos);o.uniform3fv(_.dir,b.dir)}}}a.numIndices8Bits>0&&(u.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),o.drawArrays(o.TRIANGLES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(u.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),o.drawArrays(o.TRIANGLES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(u.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),o.drawArrays(o.TRIANGLES,0,a.numIndices32Bits)),e.drawElements++}},{key:"_allocate",value:function(){var e=this._scene,t=e.canvas.gl;if(this._program=new ht(t,this._buildShader()),this._program.errors)this.errors=this._program.errors;else{var i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPickInvisible=i.getLocation("pickInvisible"),this._uSectionPlanes=[];for(var s=0,r=e._sectionPlanesState.sectionPlanes.length;s<r;s++)this._uSectionPlanes.push({active:i.getLocation("sectionPlaneActive"+s),pos:i.getLocation("sectionPlanePos"+s),dir:i.getLocation("sectionPlaneDir"+s)});this._aPackedVertexId=i.getAttribute("packedVertexId"),this._uPickZNear=i.getLocation("pickZNear"),this._uPickZFar=i.getLocation("pickZFar"),e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=i.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=i.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,i=[];return i.push("#version 300 es"),i.push("// Triangles dataTexture pick depth vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform bool pickInvisible;"),i.push("uniform highp sampler2D uTexturePerObjectIdPositionsDecodeMatrix;"),i.push("uniform lowp usampler2D uTexturePerObjectIdColorsAndFlags;"),i.push("uniform highp sampler2D uTexturePerObjectIdOffsets;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),i.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),i.push("uniform highp sampler2D uTextureCameraMatrices;"),i.push("uniform highp sampler2D uTextureModelMatrices;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;")),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("out vec4 vViewPosition;"),i.push("void main(void) {"),i.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));"),i.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));"),i.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));"),i.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));"),i.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));"),i.push("int polygonIndex = gl_VertexID / 3;"),i.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.w) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("} else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),i.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),i.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),i.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),i.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),i.push("mat4 positionsDecodeMatrix = mat4 (texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*8+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0));"),i.push("mat4 entityMatrix = mat4 (texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*8+6, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0));"),i.push("positionsDecodeMatrix = entityMatrix * positionsDecodeMatrix;"),i.push("uint solid = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),i.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),i.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),i.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),i.push("uvec4 color = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push("if (color.a == 0u) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("};"),i.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),i.push("vec3 position;"),i.push("position = positions[gl_VertexID % 3];"),i.push("if (solid != 1u) {"),i.push("if (isPerspectiveMatrix(projMatrix)) {"),i.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(worldMatrix * positionsDecodeMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),i.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("}"),i.push("} else {"),i.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*positionsDecodeMatrix)) * vec4(normal,1)).xyz);"),i.push("if (viewNormal.z < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("}"),i.push("}"),i.push("}"),i.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),i.push("vec4 offset = vec4(texelFetch (uTexturePerObjectIdOffsets, objectIndexCoords, 0).rgb, 0.0);"),i.push("worldPosition.xyz = worldPosition.xyz + offset.xyz;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags2 = flags2.r;")),i.push("vViewPosition = viewPosition;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push(" }"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.sectionPlanes.length>0,s=[];if(s.push("#version 300 es"),s.push("// Triangles dataTexture pick depth fragment shader"),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&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),s.push("uniform float pickZNear;"),s.push("uniform float pickZFar;"),i){s.push("in vec4 vWorldPosition;"),s.push("flat in uint vFlags2;");for(var r=0;r<t.sectionPlanes.length;r++)s.push("uniform bool sectionPlaneActive"+r+";"),s.push("uniform vec3 sectionPlanePos"+r+";"),s.push("uniform vec3 sectionPlaneDir"+r+";")}if(s.push("in vec4 vViewPosition;"),s.push("vec4 packDepth(const in float depth) {"),s.push(" const vec4 bitShift = vec4(256.0*256.0*256.0, 256.0*256.0, 256.0, 1.0);"),s.push(" const vec4 bitMask = vec4(0.0, 1.0/256.0, 1.0/256.0, 1.0/256.0);"),s.push(" vec4 res = fract(depth * bitShift);"),s.push(" res -= res.xxyz * bitMask;"),s.push(" return res;"),s.push("}"),s.push("out vec4 outPackedDepth;"),s.push("void main(void) {"),i){s.push(" bool clippable = vFlags2 > 0u;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(r=0;r<t.sectionPlanes.length;r++)s.push(" if (sectionPlaneActive"+r+") {"),s.push(" dist += clamp(dot(-sectionPlaneDir"+r+".xyz, vWorldPosition.xyz - sectionPlanePos"+r+".xyz), 0.0, 1000.0);"),s.push(" }");s.push(" if (dist > 0.0) { discard; }"),s.push(" }")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" float zNormalizedDepth = abs((pickZNear + vViewPosition.z) / (pickZFar - pickZNear));"),s.push(" outPackedDepth = packDepth(zNormalizedDepth); "),s.push("}"),s}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),e}(),Hi=q.vec3(),Vi=function(){function e(t){w(this,e),this._scene=t,this._hash=this._getHash(),this._allocate()}return I(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,i){var s=t.model,r=s.scene,n=r.camera,o=r.canvas.gl,a=t._state,u=a.textureState,h=t._state.origin;this._program||this._allocate(t),e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram()),u.bindCommonTextures(this._program,this._uTexturePerObjectIdPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this._uTexturePerObjectIdColorsAndFlags,this._uTextureCameraMatrices,this._uTextureModelMatrices,this._uTexturePerObjectIdOffsets);var l=n.eye;e.pickViewMatrix&&(u.bindPickCameraTexture(this._program,this._uTextureCameraMatrices),l=e.pickOrigin||l);var c=[l[0]-h[0],l[1]-h[1],l[2]-h[2]];if(o.uniform3fv(this._uCameraEyeRtc,c),o.uniform1i(this._uRenderPass,i),o.uniform3fv(this._uCameraEyeRtc,c),o.uniform1i(this._uPickInvisible,e.pickInvisible),r.logarithmicDepthBufferEnabled){var p=2/(Math.log(n.project.far+1)/Math.LN2);o.uniform1f(this._uLogDepthBufFC,p)}var d=r._sectionPlanesState.sectionPlanes.length;if(d>0)for(var f=r._sectionPlanesState.sectionPlanes,m=t.layerIndex*d,v=s.renderFlags,g=0;g<d;g++){var _=this._uSectionPlanes[g];if(_){var y=v.sectionPlanesActivePerLayer[m+g];if(o.uniform1i(_.active,y?1:0),y){var b=f[g];if(h){var x=Ee(b.dist,b.dir,h,Hi);o.uniform3fv(_.pos,x)}else o.uniform3fv(_.pos,b.pos);o.uniform3fv(_.dir,b.dir)}}}a.numIndices8Bits>0&&(u.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),o.drawArrays(o.TRIANGLES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(u.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),o.drawArrays(o.TRIANGLES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(u.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),o.drawArrays(o.TRIANGLES,0,a.numIndices32Bits)),e.drawElements++}},{key:"_allocate",value:function(){var e=this._scene,t=e.canvas.gl;if(this._program=new ht(t,this._buildShader()),this._program.errors)this.errors=this._program.errors;else{var i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPickInvisible=i.getLocation("pickInvisible"),this._uSectionPlanes=[];for(var s=0,r=e._sectionPlanesState.sectionPlanes.length;s<r;s++)this._uSectionPlanes.push({active:i.getLocation("sectionPlaneActive"+s),pos:i.getLocation("sectionPlanePos"+s),dir:i.getLocation("sectionPlaneDir"+s)});e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=i.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=i.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,i=[];return i.push("#version 300 es"),i.push("// Triangles dataTexture pick normals vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform bool pickInvisible;"),i.push("uniform highp sampler2D uTexturePerObjectIdPositionsDecodeMatrix;"),i.push("uniform lowp usampler2D uTexturePerObjectIdColorsAndFlags;"),i.push("uniform highp sampler2D uTexturePerObjectIdOffsets;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),i.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),i.push("uniform highp sampler2D uTextureCameraMatrices;"),i.push("uniform highp sampler2D uTextureModelMatrices;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;")),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("out vec3 vWorldNormal;"),i.push("void main(void) {"),i.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));"),i.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));"),i.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));"),i.push("int polygonIndex = gl_VertexID / 3;"),i.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.w) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("} else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),i.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),i.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),i.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),i.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),i.push("mat4 positionsDecodeMatrix = mat4 (texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*8+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0));"),i.push("mat4 entityMatrix = mat4 (texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*8+6, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0));"),i.push("positionsDecodeMatrix = entityMatrix * positionsDecodeMatrix;"),i.push("uint solid = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),i.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),i.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),i.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),i.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),i.push("vec3 position;"),i.push("position = positions[gl_VertexID % 3];"),i.push("if (solid != 1u) {"),i.push("if (isPerspectiveMatrix(projMatrix)) {"),i.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(worldMatrix * positionsDecodeMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),i.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("normal = -normal;"),i.push("}"),i.push("} else {"),i.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*positionsDecodeMatrix)) * vec4(normal,1)).xyz);"),i.push("if (viewNormal.z < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("normal = -normal;"),i.push("}"),i.push("}"),i.push("}"),i.push("normal = -normal;"),i.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),i.push("vec4 offset = vec4(texelFetch (uTexturePerObjectIdOffsets, objectIndexCoords, 0).rgb, 0.0);"),i.push("worldPosition.xyz = worldPosition.xyz + offset.xyz;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vWorldNormal = normal.xyz;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags2 = flags2.w;")),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.sectionPlanes.length>0,s=[];if(s.push("#version 300 es"),s.push("// Triangles dataTexture pick normals fragment shader"),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&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("flat in uint vFlags2;");for(var r=0;r<t.sectionPlanes.length;r++)s.push("uniform bool sectionPlaneActive"+r+";"),s.push("uniform vec3 sectionPlanePos"+r+";"),s.push("uniform vec3 sectionPlaneDir"+r+";")}if(s.push("in vec3 vWorldNormal;"),s.push("out vec4 outNormal;"),s.push("void main(void) {"),i){s.push(" bool clippable = vFlags2 > 0u;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(r=0;r<t.sectionPlanes.length;r++)s.push(" if (sectionPlaneActive"+r+") {"),s.push(" dist += clamp(dot(-sectionPlaneDir"+r+".xyz, vWorldPosition.xyz - sectionPlanePos"+r+".xyz), 0.0, 1000.0);"),s.push(" }");s.push(" if (dist > 0.0) { discard; }"),s.push(" }")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outNormal = vec4((vWorldNormal * 0.5) + 0.5, 1.0);"),s.push("}"),s}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),e}();q.vec3();var Ui=function(){function e(t){w(this,e),this._scene=t,this._hash=this._getHash(),this._allocate()}return I(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,i){}},{key:"_allocate",value:function(){var e=this._scene,t=e.canvas.gl;if(this._program=new ht(t,this._buildShader()),this._program.errors)this.errors=this._program.errors;else{var i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPositionsDecodeMatrix=i.getLocation("positionsDecodeMatrix"),this._uWorldMatrix=i.getLocation("worldMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(var s=0,r=e._sectionPlanesState.sectionPlanes.length;s<r;s++)this._uSectionPlanes.push({active:i.getLocation("sectionPlaneActive"+s),pos:i.getLocation("sectionPlanePos"+s),dir:i.getLocation("sectionPlaneDir"+s)});this._aPosition=i.getAttribute("position"),this._aOffset=i.getAttribute("offset"),this._aColor=i.getAttribute("color"),this._aFlags=i.getAttribute("flags"),this._aFlags2=i.getAttribute("flags2"),e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=i.getLocation("logDepthBufFC"))}}},{key:"_bindProgram",value:function(){var e=this._scene,t=e.canvas.gl,i=e.camera.project;if(this._program.bind(),t.uniformMatrix4fv(this._uProjMatrix,!1,i.matrix),e.logarithmicDepthBufferEnabled){var s=2/(Math.log(i.far+1)/Math.LN2);t.uniform1f(this._uLogDepthBufFC,s)}}},{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,i=[];return i.push("// Triangles dataTexture occlusion vertex shader"),e.logarithmicDepthBufferEnabled&&Ze.SUPPORTED_EXTENSIONS.EXT_frag_depth&&i.push("#extension GL_EXT_frag_depth : enable"),i.push("uniform int renderPass;"),i.push("attribute vec3 position;"),e.entityOffsetsEnabled&&i.push("attribute vec3 offset;"),i.push("attribute vec4 color;"),i.push("attribute vec4 flags;"),i.push("attribute vec4 flags2;"),i.push("uniform mat4 worldMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform mat4 positionsDecodeMatrix;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),Ze.SUPPORTED_EXTENSIONS.EXT_frag_depth&&i.push("varying float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("varying float isPerspective;")),t&&(i.push("varying vec4 vWorldPosition;"),i.push("varying vec4 vFlags2;")),i.push("void main(void) {"),i.push("if (int(flags.x) != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags2 = flags2;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(Ze.SUPPORTED_EXTENSIONS.EXT_frag_depth?i.push("vFragDepth = 1.0 + clipPos.w;"):(i.push("clipPos.z = log2( max( 1e-6, clipPos.w + 1.0 ) ) * logDepthBufFC - 1.0;"),i.push("clipPos.z *= clipPos.w;")),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push(" }"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.sectionPlanes.length>0,s=[];if(s.push("// Triangles dataTexture occlusion 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;")),i){s.push("varying vec4 vWorldPosition;"),s.push("varying vec4 vFlags2;");for(var r=0;r<t.sectionPlanes.length;r++)s.push("uniform bool sectionPlaneActive"+r+";"),s.push("uniform vec3 sectionPlanePos"+r+";"),s.push("uniform vec3 sectionPlaneDir"+r+";")}if(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 n=0;n<t.sectionPlanes.length;n++)s.push(" if (sectionPlaneActive"+n+") {"),s.push(" dist += clamp(dot(-sectionPlaneDir"+n+".xyz, vWorldPosition.xyz - sectionPlanePos"+n+".xyz), 0.0, 1000.0);"),s.push(" }");s.push(" if (dist > 0.0) { discard; }"),s.push(" }")}return 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(" gl_FragColor = vec4(0.0, 0.0, 1.0, 1.0); "),s.push("}"),s}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),e}();q.vec4();var zi=q.vec3(),Wi=function(){function e(t){w(this,e),this._scene=t,this._allocate(),this._hash=this._getHash()}return I(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,i){var s=this._scene,r=s.camera,n=t.model,o=s.canvas.gl,a=t._state,u=a.textureState,h=t._state.origin;if(this._program||(this._allocate(),!this.errors)){e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e,a)),u.bindCommonTextures(this._program,this._uTexturePerObjectIdPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this._uTexturePerObjectIdColorsAndFlags,this._uTextureCameraMatrices,this._uTextureModelMatrices,this._uTexturePerObjectIdOffsets);var l=r.eye;e.pickViewMatrix&&(u.bindPickCameraTexture(this._program,this._uTextureCameraMatrices),l=e.pickOrigin||l);var c=[l[0]-h[0],l[1]-h[1],l[2]-h[2]];o.uniform3fv(this._uCameraEyeRtc,c),o.uniform1i(this._uRenderPass,i);var p=s._sectionPlanesState.sectionPlanes.length;if(p>0)for(var d=s._sectionPlanesState.sectionPlanes,f=t.layerIndex*p,m=n.renderFlags,v=0;v<p;v++){var g=this._uSectionPlanes[v];if(g){var _=m.sectionPlanesActivePerLayer[f+v];if(o.uniform1i(g.active,_?1:0),_){var y=d[v];if(h){var b=Ee(y.dist,y.dir,h,zi);o.uniform3fv(g.pos,b)}else o.uniform3fv(g.pos,y.pos);o.uniform3fv(g.dir,y.dir)}}}a.numIndices8Bits>0&&(u.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),o.drawArrays(o.TRIANGLES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(u.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),o.drawArrays(o.TRIANGLES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(u.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),o.drawArrays(o.TRIANGLES,0,a.numIndices32Bits)),e.drawElements++}}},{key:"_allocate",value:function(){var e=this._scene,t=e.canvas.gl;if(this._program=new ht(t,this._buildShader()),this._program.errors)this.errors=this._program.errors;else{var i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPositionsDecodeMatrix=i.getLocation("positionsDecodeMatrix"),this._uWorldMatrix=i.getLocation("worldMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(var s=0,r=e._sectionPlanesState.sectionPlanes.length;s<r;s++)this._uSectionPlanes.push({active:i.getLocation("sectionPlaneActive"+s),pos:i.getLocation("sectionPlanePos"+s),dir:i.getLocation("sectionPlaneDir"+s)});e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=i.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=i.getLocation("uCameraEyeRtc")}}},{key:"_bindProgram",value:function(e){var t=this._scene,i=t.canvas.gl,s=this._program,r=t.camera.project;if(s.bind(),i.uniformMatrix4fv(this._uProjMatrix,!1,r.matrix),t.logarithmicDepthBufferEnabled){var n=2/(Math.log(r.far+1)/Math.LN2);i.uniform1f(this._uLogDepthBufFC,n)}}},{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 i=t.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Triangles dataTexture draw vertex shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("precision highp usampler2D;"),s.push("precision highp isampler2D;"),s.push("precision highp sampler2D;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("precision mediump usampler2D;"),s.push("precision mediump isampler2D;"),s.push("precision mediump sampler2D;"),s.push("#endif"),s.push("uniform int renderPass;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("uniform highp sampler2D uTexturePerObjectIdPositionsDecodeMatrix;"),s.push("uniform lowp usampler2D uTexturePerObjectIdColorsAndFlags;"),s.push("uniform highp sampler2D uTexturePerObjectIdOffsets;"),s.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),s.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),s.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),s.push("uniform highp sampler2D uTextureCameraMatrices;"),s.push("uniform highp sampler2D uTextureModelMatrices;"),s.push("uniform vec3 uCameraEyeRtc;"),s.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("out float isPerspective;")),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out highp vec2 vHighPrecisionZW;"),i&&(s.push("out vec4 vWorldPosition;"),s.push("flat out uint vFlags2;")),s.push("void main(void) {"),s.push("int polygonIndex = gl_VertexID / 3;"),s.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),s.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),s.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),s.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),s.push("uvec4 flags = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),s.push("uvec4 flags2 = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),s.push("if (int(flags.x) != renderPass) {"),s.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),s.push(" return;"),s.push("} else {"),s.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));"),s.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));"),s.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));"),s.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));"),s.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));"),s.push("ivec4 packedVertexBase = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),s.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),s.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),s.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),s.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),s.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),s.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),s.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),s.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),s.push("mat4 positionsDecodeMatrix = mat4 (texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*8+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0));"),s.push("mat4 entityMatrix = mat4 (texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*8+6, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0));"),s.push("positionsDecodeMatrix = entityMatrix * positionsDecodeMatrix;"),s.push("uint solid = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),s.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),s.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),s.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),s.push("uvec4 color = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),s.push("if (color.a == 0u) {"),s.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),s.push(" return;"),s.push("};"),s.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),s.push("vec3 position;"),s.push("position = positions[gl_VertexID % 3];"),s.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*positionsDecodeMatrix)) * vec4(normal,1)).xyz);"),s.push("if (solid != 1u) {"),s.push("if (isPerspectiveMatrix(projMatrix)) {"),s.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(worldMatrix * positionsDecodeMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),s.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),s.push("position = positions[2 - (gl_VertexID % 3)];"),s.push("viewNormal = -viewNormal;"),s.push("}"),s.push("} else {"),s.push("if (viewNormal.z < 0.0) {"),s.push("position = positions[2 - (gl_VertexID % 3)];"),s.push("viewNormal = -viewNormal;"),s.push("}"),s.push("}"),s.push("}"),s.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),s.push("vec4 offset = vec4(texelFetch (uTexturePerObjectIdOffsets, objectIndexCoords, 0).rgb, 0.0);"),s.push("worldPosition.xyz = worldPosition.xyz + offset.xyz;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags2 = flags2.r;")),s.push("gl_Position = clipPos;"),s.push("vHighPrecisionZW = gl_Position.zw;"),s.push("}"),s.push("}"),s}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.sectionPlanes.length>0,s=[];if(s.push("#version 300 es"),s.push("// Triangles dataTexture draw fragment shader"),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"),s.push("in highp vec2 vHighPrecisionZW;"),s.push("out vec4 outColor;"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("flat in uint vFlags2;");for(var r=0,n=t.sectionPlanes.length;r<n;r++)s.push("uniform bool sectionPlaneActive"+r+";"),s.push("uniform vec3 sectionPlanePos"+r+";"),s.push("uniform vec3 sectionPlaneDir"+r+";")}if(s.push("void main(void) {"),i){s.push(" bool clippable = vFlags2 > 0u;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var o=0,a=t.sectionPlanes.length;o<a;o++)s.push("if (sectionPlaneActive"+o+") {"),s.push(" dist += clamp(dot(-sectionPlaneDir"+o+".xyz, vWorldPosition.xyz - sectionPlanePos"+o+".xyz), 0.0, 1000.0);"),s.push("}");s.push(" if (dist > 0.0) { "),s.push(" discard;"),s.push(" }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("float fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;"),s.push(" outColor = vec4(vec3(1.0 - fragCoordZ), 1.0); "),s.push("}"),s}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),e}(),Xi=q.vec3(),Yi=function(){function e(t){w(this,e),this._scene=t,this._hash=this._getHash(),this._allocate()}return I(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,i){var s=t.model,r=s.scene,n=r.camera,o=r.canvas.gl,a=t._state,u=t._state.origin;if(this._program||(this._allocate(t),!this.errors)){e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(t)),o.uniform1i(this._uRenderPass,i),o.uniformMatrix4fv(this._uViewMatrix,!1,u?De(n.viewMatrix,u):n.viewMatrix),o.uniformMatrix4fv(this._uViewNormalMatrix,!1,n.viewNormalMatrix),o.uniformMatrix4fv(this._uWorldMatrix,!1,s.worldMatrix),o.uniformMatrix4fv(this._uWorldNormalMatrix,!1,s.worldNormalMatrix);var h=r._sectionPlanesState.sectionPlanes.length;if(h>0)for(var l=r._sectionPlanesState.sectionPlanes,c=t.layerIndex*h,p=s.renderFlags,d=0;d<h;d++){var f=this._uSectionPlanes[d];if(f){var m=p.sectionPlanesActivePerLayer[c+d];if(o.uniform1i(f.active,m?1:0),m){var v=l[d];if(u){var g=Ee(v.dist,v.dir,u,Xi);o.uniform3fv(f.pos,g)}else o.uniform3fv(f.pos,v.pos);o.uniform3fv(f.dir,v.dir)}}}o.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,t._state.positionsDecodeMatrix),this._aPosition.bindArrayBuffer(a.positionsBuf),this._aOffset.bindArrayBuffer(a.offsetsBuf),this._aNormal.bindArrayBuffer(a.normalsBuf),this._aColor.bindArrayBuffer(a.colorsBuf),this._aFlags.bindArrayBuffer(a.flagsBuf),this._aFlags2&&this._aFlags2.bindArrayBuffer(a.flags2Buf),a.indicesBuf.bind(),o.drawElements(o.TRIANGLES,a.indicesBuf.numItems,a.indicesBuf.itemType,0)}}},{key:"_allocate",value:function(){var e=this._scene,t=e.canvas.gl;if(this._program=new ht(t,this._buildShader()),this._program.errors)this.errors=this._program.errors;else{var i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPositionsDecodeMatrix=i.getLocation("positionsDecodeMatrix"),this._uWorldMatrix=i.getLocation("worldMatrix"),this._uWorldNormalMatrix=i.getLocation("worldNormalMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uViewNormalMatrix=i.getLocation("viewNormalMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(var s=0,r=e._sectionPlanesState.sectionPlanes.length;s<r;s++)this._uSectionPlanes.push({active:i.getLocation("sectionPlaneActive"+s),pos:i.getLocation("sectionPlanePos"+s),dir:i.getLocation("sectionPlaneDir"+s)});this._aPosition=i.getAttribute("position"),this._aOffset=i.getAttribute("offset"),this._aNormal=i.getAttribute("normal"),this._aColor=i.getAttribute("color"),this._aFlags=i.getAttribute("flags"),this._aFlags2&&(this._aFlags2=i.getAttribute("flags2")),e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=i.getLocation("logDepthBufFC"))}}},{key:"_bindProgram",value:function(){var e=this._scene,t=e.canvas.gl,i=e.camera.project;if(this._program.bind(),t.uniformMatrix4fv(this._uProjMatrix,!1,i.matrix),e.logarithmicDepthBufferEnabled){var s=2/(Math.log(i.far+1)/Math.LN2);t.uniform1f(this._uLogDepthBufFC,s)}}},{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,i=[];return i.push("// Batched geometry normals vertex shader"),e.logarithmicDepthBufferEnabled&&Ze.SUPPORTED_EXTENSIONS.EXT_frag_depth&&i.push("#extension GL_EXT_frag_depth : enable"),i.push("uniform int renderPass;"),i.push("attribute vec3 position;"),e.entityOffsetsEnabled&&i.push("attribute vec3 offset;"),i.push("attribute vec3 normal;"),i.push("attribute vec4 color;"),i.push("attribute vec4 flags;"),i.push("attribute vec4 flags2;"),i.push("uniform mat4 worldMatrix;"),i.push("uniform mat4 worldNormalMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform mat4 viewNormalMatrix;"),i.push("uniform mat4 positionsDecodeMatrix;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),Ze.SUPPORTED_EXTENSIONS.EXT_frag_depth&&i.push("varying float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("varying float isPerspective;")),i.push("vec3 octDecode(vec2 oct) {"),i.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),i.push(" if (v.z < 0.0) {"),i.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);"),i.push(" }"),i.push(" return normalize(v);"),i.push("}"),t&&(i.push("varying vec4 vWorldPosition;"),i.push("varying vec4 vFlags2;")),i.push("varying vec3 vViewNormal;"),i.push("void main(void) {"),i.push("if (int(flags.x) != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vec4 worldNormal = worldNormalMatrix * vec4(octDecode(normal.xy), 0.0); "),i.push(" vec3 viewNormal = normalize((viewNormalMatrix * worldNormal).xyz);"),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags2 = flags2;")),i.push(" vViewNormal = viewNormal;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(Ze.SUPPORTED_EXTENSIONS.EXT_frag_depth?i.push("vFragDepth = 1.0 + clipPos.w;"):(i.push("clipPos.z = log2( max( 1e-6, clipPos.w + 1.0 ) ) * logDepthBufFC - 1.0;"),i.push("clipPos.z *= clipPos.w;")),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push(" }"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.sectionPlanes.length>0,s=[];if(s.push("// Batched geometry normals 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;")),i){s.push("varying vec4 vWorldPosition;"),s.push("varying vec4 vFlags2;");for(var r=0;r<t.sectionPlanes.length;r++)s.push("uniform bool sectionPlaneActive"+r+";"),s.push("uniform vec3 sectionPlanePos"+r+";"),s.push("uniform vec3 sectionPlaneDir"+r+";")}if(s.push("varying vec3 vViewNormal;"),s.push("vec3 packNormalToRGB( const in vec3 normal ) {"),s.push(" return normalize( normal ) * 0.5 + 0.5;"),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 n=0;n<t.sectionPlanes.length;n++)s.push(" if (sectionPlaneActive"+n+") {"),s.push(" dist += clamp(dot(-sectionPlaneDir"+n+".xyz, vWorldPosition.xyz - sectionPlanePos"+n+".xyz), 0.0, 1000.0);"),s.push(" }");s.push(" if (dist > 0.0) { discard; }"),s.push(" }")}return 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(" gl_FragColor = vec4(packNormalToRGB(vViewNormal), 1.0); "),s.push("}"),s}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),e}();q.vec3();var Ki=function(){function e(t){w(this,e),this._scene=t,this._hash=this._getHash(),this._allocate()}return I(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,i=e._sectionPlanesState;if(this._program=new ht(t,this._buildShader()),this._program.errors)this.errors=this._program.errors;else{var s=this._program;this._uPositionsDecodeMatrix=s.getLocation("positionsDecodeMatrix"),this._uShadowViewMatrix=s.getLocation("shadowViewMatrix"),this._uShadowProjMatrix=s.getLocation("shadowProjMatrix"),e.logarithmicDepthBufferEnabled&&(this._uZFar=s.getLocation("zFar")),this._uSectionPlanes=[];for(var r=0,n=i.sectionPlanes.length;r<n;r++)this._uSectionPlanes.push({active:s.getLocation("sectionPlaneActive"+r),pos:s.getLocation("sectionPlanePos"+r),dir:s.getLocation("sectionPlaneDir"+r)});this._aPosition=s.getAttribute("position"),this._aOffset=s.getAttribute("offset"),this._aColor=s.getAttribute("color"),this._aFlags=s.getAttribute("flags"),this._aFlags2=s.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,i=[];return i.push("// Batched geometry shadow vertex shader"),i.push("attribute vec3 position;"),e.entityOffsetsEnabled&&i.push("attribute vec3 offset;"),i.push("attribute vec4 color;"),i.push("attribute vec4 flags;"),i.push("attribute vec4 flags2;"),i.push("uniform mat4 shadowViewMatrix;"),i.push("uniform mat4 shadowProjMatrix;"),i.push("uniform mat4 positionsDecodeMatrix;"),t&&(i.push("varying vec4 vWorldPosition;"),i.push("varying vec4 vFlags2;")),i.push("varying vec4 vViewPosition;"),i.push("void main(void) {"),i.push(" bool visible = (float(flags.x) > 0.0);"),i.push(" bool transparent = ((float(color.a) / 255.0) < 1.0);"),i.push(" if (!visible || transparent) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = shadowViewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags2 = flags2;")),i.push(" vViewPosition = viewPosition;"),i.push(" gl_Position = shadowProjMatrix * viewPosition;"),i.push(" }"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene._sectionPlanesState,t=e.sectionPlanes.length>0,i=[];if(i.push("// Batched geometry shadow fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),t){i.push("varying vec4 vWorldPosition;"),i.push("varying vec4 vFlags2;");for(var s=0;s<e.sectionPlanes.length;s++)i.push("uniform bool sectionPlaneActive"+s+";"),i.push("uniform vec3 sectionPlanePos"+s+";"),i.push("uniform vec3 sectionPlaneDir"+s+";")}if(i.push("varying vec4 vViewPosition;"),i.push("vec4 encodeFloat( const in float v ) {"),i.push(" const vec4 bitShift = vec4(256 * 256 * 256, 256 * 256, 256, 1.0);"),i.push(" const vec4 bitMask = vec4(0, 1.0 / 256.0, 1.0 / 256.0, 1.0 / 256.0);"),i.push(" vec4 comp = fract(v * bitShift);"),i.push(" comp -= comp.xxyz * bitMask;"),i.push(" return comp;"),i.push("}"),i.push("void main(void) {"),t){i.push(" bool clippable = (float(vFlags2.x) > 0.0);"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var r=0;r<e.sectionPlanes.length;r++)i.push(" if (sectionPlaneActive"+r+") {"),i.push(" dist += clamp(dot(-sectionPlaneDir"+r+".xyz, vWorldPosition.xyz - sectionPlanePos"+r+".xyz), 0.0, 1000.0);"),i.push(" }");i.push(" if (dist > 0.0) { discard; }"),i.push(" }")}return i.push(" gl_FragColor = encodeFloat( gl_FragCoord.z); "),i.push("}"),i}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),e}(),Ji=q.vec4(),Zi=q.vec3(),Qi={linear:"linearToLinear",sRGB:"sRGBToLinear",gamma:"gammaToLinear"},qi=function(){function e(t,i){w(this,e),this._scene=t,this._withSAO=i,this._hash=this._getHash(),this._allocate()}return I(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,i){var s=this._scene,r=s.camera,n=t.model,o=s.canvas.gl,a=t._state,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.uniform1i(this._uRenderPass,i),o.uniformMatrix4fv(this._uViewMatrix,!1,u?De(r.viewMatrix,u):r.viewMatrix),o.uniformMatrix4fv(this._uViewNormalMatrix,!1,r.viewNormalMatrix),o.uniformMatrix4fv(this._uWorldMatrix,!1,n.worldMatrix),o.uniformMatrix4fv(this._uWorldNormalMatrix,!1,n.worldNormalMatrix);var h=s._sectionPlanesState.sectionPlanes.length;if(h>0)for(var l=s._sectionPlanesState.sectionPlanes,c=t.layerIndex*h,p=n.renderFlags,d=0;d<h;d++){var f=this._uSectionPlanes[d];if(f){var m=p.sectionPlanesActivePerLayer[c+d];if(o.uniform1i(f.active,m?1:0),m){var v=l[d];if(u){var g=Ee(v.dist,v.dir,u,Zi);o.uniform3fv(f.pos,g)}else o.uniform3fv(f.pos,v.pos);o.uniform3fv(f.dir,v.dir)}}}o.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,t._state.positionsDecodeMatrix),this._aPosition.bindArrayBuffer(a.positionsBuf),this._aNormal&&this._aNormal.bindArrayBuffer(a.normalsBuf),this._aColor&&this._aColor.bindArrayBuffer(a.colorsBuf),this._aMetallicRoughness&&this._aMetallicRoughness.bindArrayBuffer(a.metallicRoughnessBuf),this._aFlags&&this._aFlags.bindArrayBuffer(a.flagsBuf),this._aFlags2&&this._aFlags2.bindArrayBuffer(a.flags2Buf),this._aOffset&&this._aOffset.bindArrayBuffer(a.offsetsBuf),a.indicesBuf.bind(),o.drawElements(o.TRIANGLES,a.indicesBuf.numItems,a.indicesBuf.itemType,0),e.drawElements++}}},{key:"_allocate",value:function(){var e=this._scene,t=e.canvas.gl,i=e._lightsState;if(this._program=new ht(t,this._buildShader()),this._program.errors)this.errors=this._program.errors;else{var s=this._program;this._uRenderPass=s.getLocation("renderPass"),this._uPositionsDecodeMatrix=s.getLocation("positionsDecodeMatrix"),this._uWorldMatrix=s.getLocation("worldMatrix"),this._uWorldNormalMatrix=s.getLocation("worldNormalMatrix"),this._uViewMatrix=s.getLocation("viewMatrix"),this._uViewNormalMatrix=s.getLocation("viewNormalMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uGammaFactor=s.getLocation("gammaFactor"),this._uLightAmbient=s.getLocation("lightAmbient"),this._uLightColor=[],this._uLightDir=[],this._uLightPos=[],this._uLightAttenuation=[];for(var r=i.lights,n=0,o=r.length;n<o;n++)switch(r[n].type){case"dir":this._uLightColor[n]=s.getLocation("lightColor"+n),this._uLightPos[n]=null,this._uLightDir[n]=s.getLocation("lightDir"+n);break;case"point":this._uLightColor[n]=s.getLocation("lightColor"+n),this._uLightPos[n]=s.getLocation("lightPos"+n),this._uLightDir[n]=null,this._uLightAttenuation[n]=s.getLocation("lightAttenuation"+n);break;case"spot":this._uLightColor[n]=s.getLocation("lightColor"+n),this._uLightPos[n]=s.getLocation("lightPos"+n),this._uLightDir[n]=s.getLocation("lightDir"+n),this._uLightAttenuation[n]=s.getLocation("lightAttenuation"+n)}i.reflectionMaps.length>0&&(this._uReflectionMap="reflectionMap"),i.lightMaps.length>0&&(this._uLightMap="lightMap"),this._uSectionPlanes=[];for(var a=0,u=e._sectionPlanesState.sectionPlanes.length;a<u;a++)this._uSectionPlanes.push({active:s.getLocation("sectionPlaneActive"+a),pos:s.getLocation("sectionPlanePos"+a),dir:s.getLocation("sectionPlaneDir"+a)});this._aPosition=s.getAttribute("position"),this._aOffset=s.getAttribute("offset"),this._aNormal=s.getAttribute("normal"),this._aColor=s.getAttribute("color"),this._aMetallicRoughness=s.getAttribute("metallicRoughness"),this._aFlags=s.getAttribute("flags"),this._aFlags2=s.getAttribute("flags2"),this._withSAO&&(this._uOcclusionTexture="uOcclusionTexture",this._uSAOParams=s.getLocation("uSAOParams")),e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=s.getLocation("logDepthBufFC"))}}},{key:"_bindProgram",value:function(e){var t=Ze.MAX_TEXTURE_UNITS,i=this._scene,s=i.canvas.gl,r=this._program,n=i._lightsState,o=n.lights,a=i.camera.project;r.bind(),s.uniformMatrix4fv(this._uProjMatrix,!1,a.matrix),this._uLightAmbient&&s.uniform4fv(this._uLightAmbient,i._lightsState.getAmbientColorAndIntensity());for(var u=0,h=o.length;u<h;u++){var l=o[u];this._uLightColor[u]&&s.uniform4f(this._uLightColor[u],l.color[0],l.color[1],l.color[2],l.intensity),this._uLightPos[u]&&(s.uniform3fv(this._uLightPos[u],l.pos),this._uLightAttenuation[u]&&s.uniform1f(this._uLightAttenuation[u],l.attenuation)),this._uLightDir[u]&&s.uniform3fv(this._uLightDir[u],l.dir)}if(n.reflectionMaps.length>0&&n.reflectionMaps[0].texture&&this._uReflectionMap&&(r.bindTexture(this._uReflectionMap,n.reflectionMaps[0].texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%t,e.bindTexture++),n.lightMaps.length>0&&n.lightMaps[0].texture&&this._uLightMap&&(r.bindTexture(this._uLightMap,n.lightMaps[0].texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%t,e.bindTexture++),this._withSAO){var c=i.sao;if(c.possible){var p=s.drawingBufferWidth,d=s.drawingBufferHeight;Ji[0]=p,Ji[1]=d,Ji[2]=c.blendCutoff,Ji[3]=c.blendFactor,s.uniform4fv(this._uSAOParams,Ji),this._program.bindTexture(this._uOcclusionTexture,e.occlusionTexture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%t,e.bindTexture++}}if(i.logarithmicDepthBufferEnabled){var f=2/(Math.log(a.far+1)/Math.LN2);s.uniform1f(this._uLogDepthBufFC,f)}this._uGammaFactor&&s.uniform1f(this._uGammaFactor,i.gammaFactor)}},{key:"_buildShader",value:function(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=e._lightsState,s=t.sectionPlanes.length>0,r=t.clippingCaps,n=[];return n.push("// Triangles dataTexture quality draw 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;"),n.push("attribute vec3 normal;"),n.push("attribute vec4 color;"),n.push("attribute vec2 metallicRoughness;"),n.push("attribute vec4 flags;"),n.push("attribute vec4 flags2;"),e.entityOffsetsEnabled&&n.push("attribute vec3 offset;"),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("}"),n.push("varying vec4 vViewPosition;"),n.push("varying vec3 vViewNormal;"),n.push("varying vec4 vColor;"),n.push("varying vec2 vMetallicRoughness;"),i.lightMaps.length>0&&n.push("varying vec3 vWorldNormal;"),s&&(n.push("varying vec4 vWorldPosition;"),n.push("varying vec4 vFlags2;"),r&&n.push("varying vec4 vClipPosition;")),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);"),n.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(n.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),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;"))),s&&(n.push("vWorldPosition = worldPosition;"),n.push("vFlags2 = flags2;"),r&&n.push("vClipPosition = clipPos;")),n.push("vViewPosition = viewPosition;"),n.push("vViewNormal = viewNormal;"),n.push("vColor = color;"),n.push("vMetallicRoughness = metallicRoughness;"),i.lightMaps.length>0&&n.push("vWorldNormal = worldNormal.xyz;"),n.push("gl_Position = clipPos;"),n.push("}"),n.push("}"),n}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e.gammaOutput,i=e._sectionPlanesState,s=e._lightsState,r=i.sectionPlanes.length>0,n=i.clippingCaps,o=[];o.push("// Triangles dataTexture quality draw fragment shader"),e.logarithmicDepthBufferEnabled&&Ze.SUPPORTED_EXTENSIONS.EXT_frag_depth&&o.push("#extension GL_EXT_frag_depth : enable"),o.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),o.push("precision highp float;"),o.push("precision highp int;"),o.push("#else"),o.push("precision mediump float;"),o.push("precision mediump int;"),o.push("#endif"),e.logarithmicDepthBufferEnabled&&Ze.SUPPORTED_EXTENSIONS.EXT_frag_depth&&(o.push("varying float isPerspective;"),o.push("uniform float logDepthBufFC;"),o.push("varying float vFragDepth;")),o.push("varying vec4 vViewPosition;"),o.push("varying vec3 vViewNormal;"),o.push("varying vec4 vColor;"),o.push("varying vec2 vMetallicRoughness;"),s.lightMaps.length>0&&o.push("varying vec3 vWorldNormal;"),o.push("uniform mat4 viewMatrix;"),s.reflectionMaps.length>0&&o.push("uniform samplerCube reflectionMap;"),s.lightMaps.length>0&&o.push("uniform samplerCube lightMap;"),o.push("uniform vec4 lightAmbient;");for(var a=0,u=s.lights.length;a<u;a++){var h=s.lights[a];"ambient"!==h.type&&(o.push("uniform vec4 lightColor"+a+";"),"dir"===h.type&&o.push("uniform vec3 lightDir"+a+";"),"point"===h.type&&o.push("uniform vec3 lightPos"+a+";"),"spot"===h.type&&(o.push("uniform vec3 lightPos"+a+";"),o.push("uniform vec3 lightDir"+a+";")))}if(this._withSAO&&(o.push("uniform sampler2D uOcclusionTexture;"),o.push("uniform vec4 uSAOParams;"),o.push("const float packUpscale = 256. / 255.;"),o.push("const float unpackDownScale = 255. / 256.;"),o.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),o.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),o.push("float unpackRGBAToDepth( const in vec4 v ) {"),o.push(" return dot( v, unPackFactors );"),o.push("}")),o.push("uniform float gammaFactor;"),o.push("vec4 linearToLinear( in vec4 value ) {"),o.push(" return value;"),o.push("}"),o.push("vec4 sRGBToLinear( in vec4 value ) {"),o.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 );"),o.push("}"),o.push("vec4 gammaToLinear( in vec4 value) {"),o.push(" return vec4( pow( value.xyz, vec3( gammaFactor ) ), value.w );"),o.push("}"),t&&(o.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),o.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),o.push("}")),r){o.push("varying vec4 vWorldPosition;"),o.push("varying vec4 vFlags2;"),n&&o.push("varying vec4 vClipPosition;");for(var l=0,c=i.sectionPlanes.length;l<c;l++)o.push("uniform bool sectionPlaneActive"+l+";"),o.push("uniform vec3 sectionPlanePos"+l+";"),o.push("uniform vec3 sectionPlaneDir"+l+";")}if(o.push("#define PI 3.14159265359"),o.push("#define RECIPROCAL_PI 0.31830988618"),o.push("#define RECIPROCAL_PI2 0.15915494"),o.push("#define EPSILON 1e-6"),o.push("#define saturate(a) clamp( a, 0.0, 1.0 )"),o.push("vec3 inverseTransformDirection(in vec3 dir, in mat4 matrix) {"),o.push(" return normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );"),o.push("}"),o.push("struct IncidentLight {"),o.push(" vec3 color;"),o.push(" vec3 direction;"),o.push("};"),o.push("struct ReflectedLight {"),o.push(" vec3 diffuse;"),o.push(" vec3 specular;"),o.push("};"),o.push("struct Geometry {"),o.push(" vec3 position;"),o.push(" vec3 viewNormal;"),o.push(" vec3 worldNormal;"),o.push(" vec3 viewEyeDir;"),o.push("};"),o.push("struct Material {"),o.push(" vec3 diffuseColor;"),o.push(" float specularRoughness;"),o.push(" vec3 specularColor;"),o.push(" float shine;"),o.push("};"),o.push("float GGXRoughnessToBlinnExponent(const in float ggxRoughness) {"),o.push(" float r = ggxRoughness + 0.0001;"),o.push(" return (2.0 / (r * r) - 2.0);"),o.push("}"),o.push("float getSpecularMIPLevel(const in float blinnShininessExponent, const in int maxMIPLevel) {"),o.push(" float maxMIPLevelScalar = float( maxMIPLevel );"),o.push(" float desiredMIPLevel = maxMIPLevelScalar - 0.79248 - 0.5 * log2( ( blinnShininessExponent * blinnShininessExponent ) + 1.0 );"),o.push(" return clamp( desiredMIPLevel, 0.0, maxMIPLevelScalar );"),o.push("}"),s.reflectionMaps.length>0&&(o.push("vec3 getLightProbeIndirectRadiance(const in vec3 reflectVec, const in float blinnShininessExponent, const in int maxMIPLevel) {"),o.push(" float mipLevel = 0.5 * getSpecularMIPLevel(blinnShininessExponent, maxMIPLevel);"),o.push(" vec3 envMapColor = "+Qi[s.reflectionMaps[0].encoding]+"(textureCube(reflectionMap, reflectVec, mipLevel)).rgb;"),o.push(" return envMapColor;"),o.push("}")),o.push("vec3 F_Schlick(const in vec3 specularColor, const in float dotLH) {"),o.push(" float fresnel = exp2( ( -5.55473 * dotLH - 6.98316 ) * dotLH );"),o.push(" return ( 1.0 - specularColor ) * fresnel + specularColor;"),o.push("}"),o.push("float G_GGX_Smith(const in float alpha, const in float dotNL, const in float dotNV) {"),o.push(" float a2 = ( alpha * alpha );"),o.push(" float gl = dotNL + sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),o.push(" float gv = dotNV + sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),o.push(" return 1.0 / ( gl * gv );"),o.push("}"),o.push("float G_GGX_SmithCorrelated(const in float alpha, const in float dotNL, const in float dotNV) {"),o.push(" float a2 = ( alpha * alpha );"),o.push(" float gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),o.push(" float gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),o.push(" return 0.5 / max( gv + gl, EPSILON );"),o.push("}"),o.push("float D_GGX(const in float alpha, const in float dotNH) {"),o.push(" float a2 = ( alpha * alpha );"),o.push(" float denom = ( dotNH * dotNH) * ( a2 - 1.0 ) + 1.0;"),o.push(" return RECIPROCAL_PI * a2 / ( denom * denom);"),o.push("}"),o.push("vec3 BRDF_Specular_GGX(const in IncidentLight incidentLight, const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),o.push(" float alpha = ( roughness * roughness );"),o.push(" vec3 halfDir = normalize( incidentLight.direction + geometry.viewEyeDir );"),o.push(" float dotNL = saturate( dot( geometry.viewNormal, incidentLight.direction ) );"),o.push(" float dotNV = saturate( dot( geometry.viewNormal, geometry.viewEyeDir ) );"),o.push(" float dotNH = saturate( dot( geometry.viewNormal, halfDir ) );"),o.push(" float dotLH = saturate( dot( incidentLight.direction, halfDir ) );"),o.push(" vec3 F = F_Schlick( specularColor, dotLH );"),o.push(" float G = G_GGX_SmithCorrelated( alpha, dotNL, dotNV );"),o.push(" float D = D_GGX( alpha, dotNH );"),o.push(" return F * (G * D);"),o.push("}"),o.push("vec3 BRDF_Specular_GGX_Environment(const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),o.push(" float dotNV = saturate(dot(geometry.viewNormal, geometry.viewEyeDir));"),o.push(" const vec4 c0 = vec4( -1, -0.0275, -0.572, 0.022);"),o.push(" const vec4 c1 = vec4( 1, 0.0425, 1.04, -0.04);"),o.push(" vec4 r = roughness * c0 + c1;"),o.push(" float a004 = min(r.x * r.x, exp2(-9.28 * dotNV)) * r.x + r.y;"),o.push(" vec2 AB = vec2(-1.04, 1.04) * a004 + r.zw;"),o.push(" return specularColor * AB.x + AB.y;"),o.push("}"),(s.lightMaps.length>0||s.reflectionMaps.length>0)&&(o.push("void computePBRLightMapping(const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),s.lightMaps.length>0&&(o.push(" vec3 irradiance = "+Qi[s.lightMaps[0].encoding]+"(textureCube(lightMap, geometry.worldNormal)).rgb;"),o.push(" irradiance *= PI;"),o.push(" vec3 diffuseBRDFContrib = (RECIPROCAL_PI * material.diffuseColor);"),o.push(" reflectedLight.diffuse += irradiance * diffuseBRDFContrib;")),s.reflectionMaps.length>0&&(o.push(" vec3 reflectVec = reflect(geometry.viewEyeDir, geometry.viewNormal);"),o.push(" reflectVec = inverseTransformDirection(reflectVec, viewMatrix);"),o.push(" float blinnExpFromRoughness = GGXRoughnessToBlinnExponent(material.specularRoughness);"),o.push(" vec3 radiance = getLightProbeIndirectRadiance(reflectVec, blinnExpFromRoughness, 8);"),o.push(" vec3 specularBRDFContrib = BRDF_Specular_GGX_Environment(geometry, material.specularColor, material.specularRoughness);"),o.push(" reflectedLight.specular += radiance * specularBRDFContrib;")),o.push("}")),o.push("void computePBRLighting(const in IncidentLight incidentLight, const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),o.push(" float dotNL = saturate(dot(geometry.viewNormal, incidentLight.direction));"),o.push(" vec3 irradiance = dotNL * incidentLight.color * PI;"),o.push(" reflectedLight.diffuse += irradiance * (RECIPROCAL_PI * material.diffuseColor);"),o.push(" reflectedLight.specular += irradiance * BRDF_Specular_GGX(incidentLight, geometry, material.specularColor, material.specularRoughness);"),o.push("}"),o.push("void main(void) {"),r){o.push(" bool clippable = (float(vFlags2.x) > 0.0);"),o.push(" if (clippable) {"),o.push(" float dist = 0.0;");for(var p=0,d=i.sectionPlanes.length;p<d;p++)o.push("if (sectionPlaneActive"+p+") {"),o.push(" dist += clamp(dot(-sectionPlaneDir"+p+".xyz, vWorldPosition.xyz - sectionPlanePos"+p+".xyz), 0.0, 1000.0);"),o.push("}");n?(o.push(" if (dist > (0.002 * vClipPosition.w)) {"),o.push(" discard;"),o.push(" }"),o.push(" if (dist > 0.0) { "),o.push(" gl_FragColor=vec4(1.0, 0.0, 0.0, 1.0);"),e.logarithmicDepthBufferEnabled&&Ze.SUPPORTED_EXTENSIONS.EXT_frag_depth&&o.push(" gl_FragDepthEXT = log2( vFragDepth ) * logDepthBufFC * 0.5;"),o.push(" return;"),o.push("}")):(o.push(" if (dist > 0.0) { "),o.push(" discard;"),o.push(" }")),o.push("}")}o.push("IncidentLight light;"),o.push("Material material;"),o.push("Geometry geometry;"),o.push("ReflectedLight reflectedLight = ReflectedLight(vec3(0.0,0.0,0.0), vec3(0.0,0.0,0.0));"),o.push("vec3 rgb = (vec3(float(vColor.r) / 255.0, float(vColor.g) / 255.0, float(vColor.b) / 255.0));"),o.push("float alpha = float(vColor.a) / 255.0;"),o.push("vec3 diffuseColor = rgb;"),o.push("float specularF0 = 1.0;"),o.push("float metallic = float(vMetallicRoughness.r) / 255.0;"),o.push("float roughness = float(vMetallicRoughness.g) / 255.0;"),o.push("float dielectricSpecular = 0.16 * specularF0 * specularF0;"),o.push("material.diffuseColor = diffuseColor * (1.0 - dielectricSpecular) * (1.0 - metallic);"),o.push("material.specularRoughness = clamp(roughness, 0.04, 1.0);"),o.push("material.specularColor = mix(vec3(dielectricSpecular), diffuseColor, metallic);"),o.push("geometry.position = vViewPosition.xyz;"),o.push("geometry.viewNormal = -normalize(vViewNormal);"),o.push("geometry.viewEyeDir = normalize(vViewPosition.xyz);"),s.lightMaps.length>0&&o.push("geometry.worldNormal = normalize(vWorldNormal);"),(s.lightMaps.length>0||s.reflectionMaps.length>0)&&o.push("computePBRLightMapping(geometry, material, reflectedLight);");for(var f=0,m=s.lights.length;f<m;f++){var v=s.lights[f];if("ambient"!==v.type){if("dir"===v.type)"view"===v.space?o.push("light.direction = normalize(lightDir"+f+");"):o.push("light.direction = normalize((viewMatrix * vec4(lightDir"+f+", 0.0)).xyz);");else if("point"===v.type)"view"===v.space?o.push("light.direction = normalize(lightPos"+f+" - vViewPosition.xyz);"):o.push("light.direction = normalize((viewMatrix * vec4(lightPos"+f+", 0.0)).xyz);");else{if("spot"!==v.type)continue;"view"===v.space?o.push("light.direction = normalize(lightDir"+f+");"):o.push("light.direction = normalize((viewMatrix * vec4(lightDir"+f+", 0.0)).xyz);")}o.push("light.color = lightColor"+f+".rgb * lightColor"+f+".a;"),o.push("computePBRLighting(light, geometry, material, reflectedLight);")}}return o.push("vec3 outgoingLight = (lightAmbient.rgb * lightAmbient.a * rgb) + (reflectedLight.diffuse) + (reflectedLight.specular);"),o.push("vec4 fragColor;"),this._withSAO?(o.push(" float viewportWidth = uSAOParams[0];"),o.push(" float viewportHeight = uSAOParams[1];"),o.push(" float blendCutoff = uSAOParams[2];"),o.push(" float blendFactor = uSAOParams[3];"),o.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),o.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBAToDepth(texture2D(uOcclusionTexture, uv))) * blendFactor;"),o.push(" fragColor = vec4(outgoingLight.rgb * ambient, alpha);")):o.push(" fragColor = vec4(outgoingLight.rgb, alpha);"),t&&o.push("fragColor = linearToGamma(fragColor, gammaFactor);"),o.push("gl_FragColor = fragColor;"),e.logarithmicDepthBufferEnabled&&Ze.SUPPORTED_EXTENSIONS.EXT_frag_depth&&o.push(" gl_FragDepthEXT = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),o.push("}"),o}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),e}(),$i=q.vec3(),es=function(){function e(t){w(this,e),this._scene=t,this._hash=this._getHash(),this._allocate()}return I(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,i){var s=t.model,r=s.scene,n=r.camera,o=r.canvas.gl,a=t._state,u=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 o.activeTexture(o["TEXTURE"+e]),o.bindTexture(o.TEXTURE_2D,a.texturePerObjectIdPositionsDecodeMatrix),!0},unbind:function(e){o.activeTexture(o["TEXTURE"+e]),o.bindTexture(o.TEXTURE_2D,null)}},1),this._program.bindTexture(this._uTexturePerVertexIdCoordinates,{bind:function(e){return o.activeTexture(o["TEXTURE"+e]),o.bindTexture(o.TEXTURE_2D,a.texturePerVertexIdCoordinates),!0},unbind:function(e){o.activeTexture(o["TEXTURE"+e]),o.bindTexture(o.TEXTURE_2D,null)}},2),this._program.bindTexture(this._uTexturePerObjectIdColorsAndFlags,{bind:function(e){return o.activeTexture(o["TEXTURE"+e]),o.bindTexture(o.TEXTURE_2D,a.texturePerObjectIdColorsAndFlags),!0},unbind:function(e){o.activeTexture(o["TEXTURE"+e]),o.bindTexture(o.TEXTURE_2D,null)}},3),o.uniform1i(this._uRenderPass,i),o.uniform1i(this._uPickInvisible,e.pickInvisible),o.uniformMatrix4fv(this._uWorldMatrix,!1,s.worldMatrix);var h=e.pickViewMatrix||n.viewMatrix,l=u?De(h,u):h;if(o.uniformMatrix4fv(this._uViewMatrix,!1,l),o.uniformMatrix4fv(this._uProjMatrix,!1,e.pickProjMatrix),r.logarithmicDepthBufferEnabled){var c=2/(Math.log(n.project.far+1)/Math.LN2);o.uniform1f(this._uLogDepthBufFC,c)}var p=r._sectionPlanesState.sectionPlanes.length;if(p>0)for(var d=r._sectionPlanesState.sectionPlanes,f=t.layerIndex*p,m=s.renderFlags,v=0;v<p;v++){var g=this._uSectionPlanes[v],_=m.sectionPlanesActivePerLayer[f+v];if(o.uniform1i(g.active,_?1:0),_){var y=d[v];if(u){var b=Ee(y.dist,y.dir,u,$i);o.uniform3fv(g.pos,b)}else o.uniform3fv(g.pos,y.pos);o.uniform3fv(g.dir,y.dir)}}a.numIndices8Bits>0&&(this._program.bindTexture(this._uTexturePerPolygonIdPortionIds,{bind:function(e){return o.activeTexture(o["TEXTURE"+e]),o.bindTexture(o.TEXTURE_2D,a.texturePerPolygonIdPortionIds8Bits),!0},unbind:function(e){o.activeTexture(o["TEXTURE"+e]),o.bindTexture(o.TEXTURE_2D,null)}},4),this._program.bindTexture(this._uTexturePerPolygonIdIndices,{bind:function(e){return o.activeTexture(o["TEXTURE"+e]),o.bindTexture(o.TEXTURE_2D,a.texturePerPolygonIdIndices8Bits),!0},unbind:function(e){o.activeTexture(o["TEXTURE"+e]),o.bindTexture(o.TEXTURE_2D,null)}},5),o.drawArrays(o.TRIANGLES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(this._program.bindTexture(this._uTexturePerPolygonIdPortionIds,{bind:function(e){return o.activeTexture(o["TEXTURE"+e]),o.bindTexture(o.TEXTURE_2D,a.texturePerPolygonIdPortionIds16Bits),!0},unbind:function(e){o.activeTexture(o["TEXTURE"+e]),o.bindTexture(o.TEXTURE_2D,null)}},4),this._program.bindTexture(this._uTexturePerPolygonIdIndices,{bind:function(e){return o.activeTexture(o["TEXTURE"+e]),o.bindTexture(o.TEXTURE_2D,a.texturePerPolygonIdIndices16Bits),!0},unbind:function(e){o.activeTexture(o["TEXTURE"+e]),o.bindTexture(o.TEXTURE_2D,null)}},5),o.drawArrays(o.TRIANGLES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(this._program.bindTexture(this._uTexturePerPolygonIdPortionIds,{bind:function(e){return o.activeTexture(o["TEXTURE"+e]),o.bindTexture(o.TEXTURE_2D,a.texturePerPolygonIdPortionIds32Bits),!0},unbind:function(e){o.activeTexture(o["TEXTURE"+e]),o.bindTexture(o.TEXTURE_2D,null)}},4),this._program.bindTexture(this._uTexturePerPolygonIdIndices,{bind:function(e){return o.activeTexture(o["TEXTURE"+e]),o.bindTexture(o.TEXTURE_2D,a.texturePerPolygonIdIndices32Bits),!0},unbind:function(e){o.activeTexture(o["TEXTURE"+e]),o.bindTexture(o.TEXTURE_2D,null)}},5),o.drawArrays(o.TRIANGLES,0,a.numIndices32Bits)),e.drawElements++}},{key:"_allocate",value:function(){var e=this._scene,t=e.canvas.gl;if(this._program=new ht(t,this._buildShader()),this._program.errors)this.errors=this._program.errors;else{var i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPickInvisible=i.getLocation("pickInvisible"),this._uPositionsDecodeMatrix=i.getLocation("positionsDecodeMatrix"),this._uWorldMatrix=i.getLocation("worldMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(var s=0,r=e._sectionPlanesState.sectionPlanes.length;s<r;s++)this._uSectionPlanes.push({active:i.getLocation("sectionPlaneActive"+s),pos:i.getLocation("sectionPlanePos"+s),dir:i.getLocation("sectionPlaneDir"+s)});this._aPackedVertexId=i.getAttribute("packedVertexId"),e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=i.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,i=[];return i.push("#version 300 es"),i.push("// Triangles dataTexture pick flat normals vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in uvec3 packedVertexId;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform bool pickInvisible;"),i.push("uniform mat4 worldMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform sampler2D uTexturePerObjectIdPositionsDecodeMatrix;"),i.push("uniform usampler2D uTexturePerObjectIdColorsAndFlags;"),i.push("uniform usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform usampler2D uTexturePerPolygonIdIndices;"),i.push("uniform isampler2D uTexturePerPolygonIdNormals;"),i.push("uniform usampler2D uTexturePerPolygonIdPortionIds;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),i.push("out vec4 vWorldPosition;"),t&&i.push("out int vFlags2;"),i.push("void main(void) {"),i.push("int polygonIndex = gl_VertexID / 3;"),i.push("int h_normal_index = polygonIndex & 4095;"),i.push("int v_normal_index = polygonIndex >> 12;"),i.push("int h_packed_object_id_index = ((polygonIndex >> 3) / 2) & 4095;"),i.push("int v_packed_object_id_index = ((polygonIndex >> 3) / 2) >> 12;"),i.push("ivec3 packedObjectId = ivec3(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).rgb);"),i.push("int objectIndex;"),i.push("if (((polygonIndex >> 3) % 2) == 0) {"),i.push(" objectIndex = (packedObjectId.r << 4) + (packedObjectId.g >> 4);"),i.push("} else {"),i.push(" objectIndex = ((packedObjectId.g & 15) << 8) + packedObjectId.b;"),i.push("}"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("int h_index = polygonIndex & 4095;"),i.push("int v_index = polygonIndex >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),i.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),i.push("mat4 positionsDecodeMatrix = mat4 (texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*8+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0));"),i.push("uvec4 flags = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("vec3 position1 = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),i.push("vec3 position2 = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),i.push("vec3 position3 = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),i.push("vec3 normal = normalize(cross(position3 - position1, position2 - position1));"),i.push("int vertexNumber = gl_VertexID % 3;"),i.push("vec3 position;"),i.push("if (vertexNumber == 0) position = position1;"),i.push("else if (vertexNumber == 1) position = position2;"),i.push("else position = position3;"),i.push("if (int(flags.w) != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vWorldPosition = worldPosition;"),t&&i.push(" vFlags2 = flags2.r;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push(" }"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.sectionPlanes.length>0,s=[];if(s.push("#version 300 es"),s.push("// Triangles dataTexture pick flat normals fragment shader"),s.push("#extension GL_OES_standard_derivatives : enable"),e.logarithmicDepthBufferEnabled&&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&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),s.push("in vec4 vWorldPosition;"),i){s.push("in int vFlags2;");for(var r=0;r<t.sectionPlanes.length;r++)s.push("uniform bool sectionPlaneActive"+r+";"),s.push("uniform vec3 sectionPlanePos"+r+";"),s.push("uniform vec3 sectionPlaneDir"+r+";")}if(s.push("out vec4 outNormal;"),s.push("void main(void) {"),i){s.push(" bool clippable = vFlags2 > 0;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(r=0;r<t.sectionPlanes.length;r++)s.push(" if (sectionPlaneActive"+r+") {"),s.push(" dist += clamp(dot(-sectionPlaneDir"+r+".xyz, vWorldPosition.xyz - sectionPlanePos"+r+".xyz), 0.0, 1000.0);"),s.push(" }");s.push(" if (dist > 0.0) { discard; }"),s.push(" }")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" vec3 xTangent = dFdx( vWorldPosition.xyz );"),s.push(" vec3 yTangent = dFdy( vWorldPosition.xyz );"),s.push(" vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"),s.push(" outNormal = vec4((worldNormal * 0.5) + 0.5, 1.0);"),s.push("}"),s}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),e}(),ts=function(){function e(t){w(this,e),this._scene=t}return I(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._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 Di(this._scene,!1)),this._colorRenderer}},{key:"colorRendererWithSAO",get:function(){return this._colorRendererWithSAO||(this._colorRendererWithSAO=new Di(this._scene,!0)),this._colorRendererWithSAO}},{key:"colorQualityRenderer",get:function(){return this._colorQualityRenderer||(this._colorQualityRenderer=new qi(this._scene,!1)),this._colorQualityRenderer}},{key:"colorQualityRendererWithSAO",get:function(){return this._colorQualityRendererWithSAO||(this._colorQualityRendererWithSAO=new qi(this._scene,!0)),this._colorQualityRendererWithSAO}},{key:"silhouetteRenderer",get:function(){return this._silhouetteRenderer||(this._silhouetteRenderer=new Ei(this._scene)),this._silhouetteRenderer}},{key:"depthRenderer",get:function(){return this._depthRenderer||(this._depthRenderer=new Wi(this._scene)),this._depthRenderer}},{key:"normalsRenderer",get:function(){return this._normalsRenderer||(this._normalsRenderer=new Yi(this._scene)),this._normalsRenderer}},{key:"edgesRenderer",get:function(){return this._edgesRenderer||(this._edgesRenderer=new Si(this._scene)),this._edgesRenderer}},{key:"edgesColorRenderer",get:function(){return this._edgesColorRenderer||(this._edgesColorRenderer=new Bi(this._scene)),this._edgesColorRenderer}},{key:"pickMeshRenderer",get:function(){return this._pickMeshRenderer||(this._pickMeshRenderer=new Ni(this._scene)),this._pickMeshRenderer}},{key:"pickNormalsRenderer",get:function(){return this._pickNormalsRenderer||(this._pickNormalsRenderer=new Vi(this._scene)),this._pickNormalsRenderer}},{key:"pickNormalsFlatRenderer",get:function(){return this._pickNormalsFlatRenderer||(this._pickNormalsFlatRenderer=new es(this._scene)),this._pickNormalsFlatRenderer}},{key:"pickDepthRenderer",get:function(){return this._pickDepthRenderer||(this._pickDepthRenderer=new Gi(this._scene)),this._pickDepthRenderer}},{key:"occlusionRenderer",get:function(){return this._occlusionRenderer||(this._occlusionRenderer=new Ui(this._scene)),this._occlusionRenderer}},{key:"shadowRenderer",get:function(){return this._shadowRenderer||(this._shadowRenderer=new Ki(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._pickNormalsRenderer&&this._pickNormalsRenderer.destroy(),this._pickNormalsFlatRenderer&&this._pickNormalsFlatRenderer.destroy(),this._occlusionRenderer&&this._occlusionRenderer.destroy(),this._shadowRenderer&&this._shadowRenderer.destroy()}}]),e}(),is={};Ze.SUPPORTED_EXTENSIONS.OES_element_index_uint;var ss=I((function e(){w(this,e),this.positions=[],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=[]})),rs=null;
1
+ var e,t=o().mark(Iv),i=o().mark(Cv),s=o().mark(Ny);function r(e){return function(e){if(Array.isArray(e))return f(e)}(e)||function(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}(e)||d(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 n(e,t){var i="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!i){if(Array.isArray(e)||(i=d(e))||t&&e&&"number"==typeof e.length){i&&(e=i);var s=0,r=function(){};return{s:r,n:function(){return s>=e.length?{done:!0}:{done:!1,value:e[s++]}},e:function(e){throw e},f:r}}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 n,o=!0,a=!1;return{s:function(){i=i.call(e)},n:function(){var e=i.next();return o=e.done,e},e:function(e){a=!0,n=e},f:function(){try{o||null==i.return||i.return()}finally{if(a)throw n}}}}function o(){/*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */o=function(){return e};var e={},t=Object.prototype,i=t.hasOwnProperty,s="function"==typeof Symbol?Symbol:{},r=s.iterator||"@@iterator",n=s.asyncIterator||"@@asyncIterator",a=s.toStringTag||"@@toStringTag";function u(e,t,i){return Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}),e[t]}try{u({},"")}catch(e){u=function(e,t,i){return e[t]=i}}function h(e,t,i,s){var r=t&&t.prototype instanceof p?t:p,n=Object.create(r.prototype),o=new M(s||[]);return n._invoke=function(e,t,i){var s="suspendedStart";return function(r,n){if("executing"===s)throw new Error("Generator is already running");if("completed"===s){if("throw"===r)throw n;return C()}for(i.method=r,i.arg=n;;){var o=i.delegate;if(o){var a=x(o,i);if(a){if(a===c)continue;return a}}if("next"===i.method)i.sent=i._sent=i.arg;else if("throw"===i.method){if("suspendedStart"===s)throw s="completed",i.arg;i.dispatchException(i.arg)}else"return"===i.method&&i.abrupt("return",i.arg);s="executing";var u=l(e,t,i);if("normal"===u.type){if(s=i.done?"completed":"suspendedYield",u.arg===c)continue;return{value:u.arg,done:i.done}}"throw"===u.type&&(s="completed",i.method="throw",i.arg=u.arg)}}}(e,i,o),n}function l(e,t,i){try{return{type:"normal",arg:e.call(t,i)}}catch(e){return{type:"throw",arg:e}}}e.wrap=h;var c={};function p(){}function d(){}function f(){}var m={};u(m,r,(function(){return this}));var v=Object.getPrototypeOf,g=v&&v(v(I([])));g&&g!==t&&i.call(g,r)&&(m=g);var _=f.prototype=p.prototype=Object.create(m);function y(e){["next","throw","return"].forEach((function(t){u(e,t,(function(e){return this._invoke(t,e)}))}))}function b(e,t){function s(r,n,o,a){var u=l(e[r],e,n);if("throw"!==u.type){var h=u.arg,c=h.value;return c&&"object"==T(c)&&i.call(c,"__await")?t.resolve(c.__await).then((function(e){s("next",e,o,a)}),(function(e){s("throw",e,o,a)})):t.resolve(c).then((function(e){h.value=e,o(h)}),(function(e){return s("throw",e,o,a)}))}a(u.arg)}var r;this._invoke=function(e,i){function n(){return new t((function(t,r){s(e,i,t,r)}))}return r=r?r.then(n,n):n()}}function x(e,t){var i=e.iterator[t.method];if(void 0===i){if(t.delegate=null,"throw"===t.method){if(e.iterator.return&&(t.method="return",t.arg=void 0,x(e,t),"throw"===t.method))return c;t.method="throw",t.arg=new TypeError("The iterator does not provide a 'throw' method")}return c}var s=l(i,e.iterator,t.arg);if("throw"===s.type)return t.method="throw",t.arg=s.arg,t.delegate=null,c;var r=s.arg;return r?r.done?(t[e.resultName]=r.value,t.next=e.nextLoc,"return"!==t.method&&(t.method="next",t.arg=void 0),t.delegate=null,c):r:(t.method="throw",t.arg=new TypeError("iterator result is not an object"),t.delegate=null,c)}function P(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 w(e){var t=e.completion||{};t.type="normal",delete t.arg,e.completion=t}function M(e){this.tryEntries=[{tryLoc:"root"}],e.forEach(P,this),this.reset(!0)}function I(e){if(e){var t=e[r];if(t)return t.call(e);if("function"==typeof e.next)return e;if(!isNaN(e.length)){var s=-1,n=function t(){for(;++s<e.length;)if(i.call(e,s))return t.value=e[s],t.done=!1,t;return t.value=void 0,t.done=!0,t};return n.next=n}}return{next:C}}function C(){return{value:void 0,done:!0}}return d.prototype=f,u(_,"constructor",f),u(f,"constructor",d),d.displayName=u(f,a,"GeneratorFunction"),e.isGeneratorFunction=function(e){var t="function"==typeof e&&e.constructor;return!!t&&(t===d||"GeneratorFunction"===(t.displayName||t.name))},e.mark=function(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,f):(e.__proto__=f,u(e,a,"GeneratorFunction")),e.prototype=Object.create(_),e},e.awrap=function(e){return{__await:e}},y(b.prototype),u(b.prototype,n,(function(){return this})),e.AsyncIterator=b,e.async=function(t,i,s,r,n){void 0===n&&(n=Promise);var o=new b(h(t,i,s,r),n);return e.isGeneratorFunction(i)?o:o.next().then((function(e){return e.done?e.value:o.next()}))},y(_),u(_,a,"Generator"),u(_,r,(function(){return this})),u(_,"toString",(function(){return"[object Generator]"})),e.keys=function(e){var t=[];for(var i in e)t.push(i);return t.reverse(),function i(){for(;t.length;){var s=t.pop();if(s in e)return i.value=s,i.done=!1,i}return i.done=!0,i}},e.values=I,M.prototype={constructor:M,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(w),!e)for(var t in this)"t"===t.charAt(0)&&i.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 s(i,s){return o.type="throw",o.arg=e,t.next=i,s&&(t.method="next",t.arg=void 0),!!s}for(var r=this.tryEntries.length-1;r>=0;--r){var n=this.tryEntries[r],o=n.completion;if("root"===n.tryLoc)return s("end");if(n.tryLoc<=this.prev){var a=i.call(n,"catchLoc"),u=i.call(n,"finallyLoc");if(a&&u){if(this.prev<n.catchLoc)return s(n.catchLoc,!0);if(this.prev<n.finallyLoc)return s(n.finallyLoc)}else if(a){if(this.prev<n.catchLoc)return s(n.catchLoc,!0)}else{if(!u)throw new Error("try statement without catch or finally");if(this.prev<n.finallyLoc)return s(n.finallyLoc)}}}},abrupt:function(e,t){for(var s=this.tryEntries.length-1;s>=0;--s){var r=this.tryEntries[s];if(r.tryLoc<=this.prev&&i.call(r,"finallyLoc")&&this.prev<r.finallyLoc){var n=r;break}}n&&("break"===e||"continue"===e)&&n.tryLoc<=t&&t<=n.finallyLoc&&(n=null);var o=n?n.completion:{};return o.type=e,o.arg=t,n?(this.method="next",this.next=n.finallyLoc,c):this.complete(o)},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),c},finish:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var i=this.tryEntries[t];if(i.finallyLoc===e)return this.complete(i.completion,i.afterLoc),w(i),c}},catch:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var i=this.tryEntries[t];if(i.tryLoc===e){var s=i.completion;if("throw"===s.type){var r=s.arg;w(i)}return r}}throw new Error("illegal catch attempt")},delegateYield:function(e,t,i){return this.delegate={iterator:I(e),resultName:t,nextLoc:i},"next"===this.method&&(this.arg=void 0),c}},e}function a(e,t,i,s,r,n,o){try{var a=e[n](o),u=a.value}catch(e){return void i(e)}a.done?t(u):Promise.resolve(u).then(s,r)}function u(e){return function(){var t=this,i=arguments;return new Promise((function(s,r){var n=e.apply(t,i);function o(e){a(n,s,r,o,u,"next",e)}function u(e){a(n,s,r,o,u,"throw",e)}o(void 0)}))}}function h(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(e);t&&(s=s.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,s)}return i}function l(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?h(Object(i),!0).forEach((function(t){c(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):h(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}function c(e,t,i){return t in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}function p(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var i=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null==i)return;var s,r,n=[],o=!0,a=!1;try{for(i=i.call(e);!(o=(s=i.next()).done)&&(n.push(s.value),!t||n.length!==t);o=!0);}catch(e){a=!0,r=e}finally{try{o||null==i.return||i.return()}finally{if(a)throw r}}return n}(e,t)||d(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 d(e,t){if(e){if("string"==typeof e)return f(e,t);var i=Object.prototype.toString.call(e).slice(8,-1);return"Object"===i&&e.constructor&&(i=e.constructor.name),"Map"===i||"Set"===i?Array.from(e):"Arguments"===i||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(i)?f(e,t):void 0}}function f(e,t){(null==t||t>e.length)&&(t=e.length);for(var i=0,s=new Array(t);i<t;i++)s[i]=e[i];return s}function m(){return m="undefined"!=typeof Reflect&&Reflect.get?Reflect.get.bind():function(e,t,i){var s=v(e,t);if(s){var r=Object.getOwnPropertyDescriptor(s,t);return r.get?r.get.call(arguments.length<3?e:i):r.value}},m.apply(this,arguments)}function v(e,t){for(;!Object.prototype.hasOwnProperty.call(e,t)&&null!==(e=P(e)););return e}function g(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&&_(e,t)}function _(e,t){return _=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},_(e,t)}function y(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 i,s=P(e);if(t){var r=P(this).constructor;i=Reflect.construct(s,arguments,r)}else i=s.apply(this,arguments);return b(this,i)}}function b(e,t){if(t&&("object"===T(t)||"function"==typeof t))return t;if(void 0!==t)throw new TypeError("Derived constructors may only return object or undefined");return x(e)}function x(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function P(e){return P=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},P(e)}function T(e){return T="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},T(e)}function w(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function M(e,t){for(var i=0;i<t.length;i++){var s=t[i];s.enumerable=s.enumerable||!1,s.configurable=!0,"value"in s&&(s.writable=!0),Object.defineProperty(e,s.key,s)}}function I(e,t,i){return t&&M(e.prototype,t),i&&M(e,i),Object.defineProperty(e,"prototype",{writable:!1}),e}function C(e){return new k(e)}function D(e){return function(){return new A(e.apply(this,arguments))}}function A(e){var t,i;function s(t,i){try{var n=e[t](i),o=n.value,a=o instanceof k;Promise.resolve(a?o.wrapped:o).then((function(e){a?s("return"===t?"return":"next",e):r(n.done?"return":"normal",e)}),(function(e){s("throw",e)}))}catch(e){r("throw",e)}}function r(e,r){switch(e){case"return":t.resolve({value:r,done:!0});break;case"throw":t.reject(r);break;default:t.resolve({value:r,done:!1})}(t=t.next)?s(t.key,t.arg):i=null}this._invoke=function(e,r){return new Promise((function(n,o){var a={key:e,arg:r,resolve:n,reject:o,next:null};i?i=i.next=a:(t=i=a,s(e,r))}))},"function"!=typeof e.return&&(this.return=void 0)}function k(e){this.wrapped=e}function E(e){var t,i,s,r=2;for("undefined"!=typeof Symbol&&(i=Symbol.asyncIterator,s=Symbol.iterator);r--;){if(i&&null!=(t=e[i]))return t.call(e);if(s&&null!=(t=e[s]))return new F(t.call(e));i="@@asyncIterator",s="@@iterator"}throw new TypeError("Object is not async iterable")}function F(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 F=function(e){this.s=e,this.n=e.next},F.prototype={s:null,n:null,next:function(){return t(this.n.apply(this.s,arguments))},return:function(e){var i=this.s.return;return void 0===i?Promise.resolve({value:e,done:!0}):t(i.apply(this.s,arguments))},throw:function(e){var i=this.s.return;return void 0===i?Promise.reject(e):t(i.apply(this.s,arguments))}},new F(e)}A.prototype["function"==typeof Symbol&&Symbol.asyncIterator||"@@asyncIterator"]=function(){return this},A.prototype.next=function(e){return this._invoke("next",e)},A.prototype.throw=function(e){return this._invoke("throw",e)},A.prototype.return=function(e){return this._invoke("return",e)};var R,S,O,B,L,N,j,G=function(){function e(t,i){w(this,e),this.items=t||[],this._lastUniqueId=(i||0)+1}return I(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 i=this._lastUniqueId++;if(!this.items[i])return this.items[i]=e,i}}},{key:"removeItem",value:function(e){var t=this.items[e];return delete this.items[e],t}}]),e}(),H=new G,V=I((function e(t){w(this,e),this.id=t,this.parentItem=null,this.groups=[],this.menuElement=null,this.shown=!1,this.mouseOver=0})),U=I((function e(){w(this,e),this.items=[]})),z=I((function e(t,i,s,r,n){w(this,e),this.id=t,this.getTitle=i,this.doAction=s,this.getEnabled=r,this.getShown=n,this.itemElement=null,this.subMenu=null,this.enabled=!0})),W=function(){function e(){var t=this,i=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};w(this,e),this._id=H.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!==i.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()})),i.items&&(this.items=i.items),this._hideOnAction=!1!==i.hideOnAction,this.context=i.context,this.enabled=!1!==i.enabled,this.hide()}return I(e,[{key:"on",value:function(e,t){var i=this._eventSubs[e];i||(i=[],this._eventSubs[e]=i),i.push(t)}},{key:"fire",value:function(e,t){var i=this._eventSubs[e];if(i)for(var s=0,r=i.length;s<r;s++)i[s](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&&(H.removeItem(this._id),this._id=null)}},{key:"_clear",value:function(){for(var e=0,t=this._menuList.length;e<t;e++){var i=this._menuList[e].menuElement;i.parentElement.removeChild(i)}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(i){for(var s=t._getNextId(),r=new V(s),n=0,o=i.length;n<o;n++){var a=i[n],u=new U;r.groups.push(u);for(var h=function(i,s){var n=a[i],o=n.items,h=o&&o.length>0,l=t._getNextId(),c=n.getTitle||function(){return n.title||""},p=n.doAction||n.callback||function(){},d=n.getEnabled||function(){return!0},f=n.getShown||function(){return!0},m=new z(l,c,p,d,f);if(m.parentMenu=r,u.items.push(m),h){var v=e(o);m.subMenu=v,v.parentItem=m}t._itemList.push(m),t._itemMap[m.id]=m},l=0,c=a.length;l<c;l++)h(l)}return t._menuList.push(r),t._menuMap[r.id]=r,r}(e)}},{key:"_getNextId",value:function(){return"ContextMenu_"+this._id+this._nextId++}},{key:"_createUI",value:function(){var e=this;!function t(i){e._createMenuUI(i);for(var s=i.groups,r=0,n=s.length;r<n;r++)for(var o=s[r].items,a=0,u=o.length;a<u;a++){var h=o[a].subMenu;h&&t(h)}}(this._rootMenu)}},{key:"_createMenuUI",value:function(e){var t=this,i=e.groups,s=[];if(s.push('<div class="xeokit-context-menu '+e.id+'" style="z-index:300000; position: absolute;">'),s.push("<ul>"),i)for(var r=0,n=i.length;r<n;r++){var o=r,a=n,u=i[r].items;if(u)for(var h=0,l=u.length;h<l;h++){var c=u[h],p=c.subMenu,d=c.title||"";p?s.push('<li id="'+c.id+'" class="xeokit-context-menu-item" style="'+(o===a-1||h<l-1?"border-bottom: 0":"border-bottom: 1px solid black")+'">'+d+" [MORE]</li>"):s.push('<li id="'+c.id+'" class="xeokit-context-menu-item" style="'+(o===a-1||h<l-1?"border-bottom: 0":"border-bottom: 1px solid black")+'">'+d+"</li>")}}s.push("</ul>"),s.push("</div>");var f=s.join("");document.body.insertAdjacentHTML("beforeend",f);var m=document.querySelector("."+e.id);e.menuElement=m,m.style["border-radius"]="4px",m.style.display="none",m.style["z-index"]=3e5,m.style.background="white",m.style.border="1px solid black",m.style["box-shadow"]="0 4px 5px 0 gray",m.oncontextmenu=function(e){e.preventDefault()};var v=this,g=null;if(i)for(var _=0,y=i.length;_<y;_++){var b=i[_].items;if(b)for(var x=function(e,i){var s=b[e],r=s.subMenu;if(s.itemElement=document.getElementById(s.id),!s.itemElement)return console.error("ContextMenu item element not found: "+s.id),"continue";s.itemElement.addEventListener("mouseenter",(function(e){e.preventDefault();var t=s.subMenu;if(t){if(g&&g.id!==t.id&&(v._hideMenu(g.id),g=null),!1!==s.enabled){var i=s.itemElement,r=t.menuElement,n=i.getBoundingClientRect();r.getBoundingClientRect();n.right+200>window.innerWidth?v._showMenu(t.id,n.left-200,n.top-1):v._showMenu(t.id,n.right-5,n.top-1),g=t}}else g&&(v._hideMenu(g.id),g=null)})),r||(s.itemElement.addEventListener("click",(function(e){e.preventDefault(),v._context&&!1!==s.enabled&&(s.doAction&&s.doAction(v._context),t._hideOnAction?v.hide():(v._updateItemsTitles(),v._updateItemsEnabledStatus()))})),s.itemElement.addEventListener("mouseenter",(function(e){e.preventDefault(),!1!==s.enabled&&s.doHover&&s.doHover(v._context)})))},P=0,T=b.length;P<T;P++)x(P)}}},{key:"_updateItemsTitles",value:function(){if(this._context)for(var e=0,t=this._itemList.length;e<t;e++){var i=this._itemList[e],s=i.itemElement;if(s){var r=i.getShown;if(r&&r(this._context)){var n=i.getTitle(this._context);i.subMenu,s.innerText=n}}}}},{key:"_updateItemsEnabledStatus",value:function(){if(this._context)for(var e=0,t=this._itemList.length;e<t;e++){var i=this._itemList[e],s=i.itemElement;if(s){var r=i.getEnabled;if(r){var n=i.getShown;if(n){var o=n(this._context);if(i.shown=o,o){s.style.visibility="visible",s.style.height="auto",s.style.padding=null;var a=r(this._context);i.enabled=a,a?s.classList.remove("disabled"):s.classList.add("disabled")}else s.style.visibility="hidden",s.style.height="0",s.style.padding="0"}}}}}},{key:"_showMenu",value:function(e,t,i){var s=this._menuMap[e];if(s){if(!s.shown){var r=s.menuElement;r&&(this._showMenuElement(r,t,i),s.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 i=t.menuElement;i&&(this._hideMenuElement(i),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 i=this._menuList[e];this._hideMenu(i.id)}}},{key:"_showMenuElement",value:function(e,t,i){e.style.display="block";var s=e.offsetHeight,r=e.offsetWidth;i+s>window.innerHeight&&(i=window.innerHeight-s),t+r>window.innerWidth&&(t=window.innerWidth-r),e.style.left=t+"px",e.style.top=i+"px"}},{key:"_hideMenuElement",value:function(e){e.style.display="none"}}]),e}(),X=function(){function e(t,i,s){w(this,e),this.id=s&&s.id?s.id:t,this.viewer=i,this._subIdMap=null,this._subIdEvents=null,this._eventSubs=null,this._eventSubsNum=null,this._events=null,this._eventCallDepth=0,i.addPlugin(this)}return I(e,[{key:"fire",value:function(e,t,i){this._events||(this._events={}),this._eventSubs||(this._eventSubs={},this._eventSubsNum={}),!0!==i&&(this._events[e]=t||!0);var s,r=this._eventSubs[e];if(r)for(var n in r)r.hasOwnProperty(n)&&(s=r[n],this._eventCallDepth++,this._eventCallDepth<300?s.callback.call(s.scope,t):this.error("fire: potential stack overflow from recursive event '"+e+"' - dropping this event"),this._eventCallDepth--)}},{key:"on",value:function(e,t,i){this._events||(this._events={}),this._subIdMap||(this._subIdMap=new G),this._subIdEvents||(this._subIdEvents={}),this._eventSubs||(this._eventSubs={}),this._eventSubsNum||(this._eventSubsNum={});var s=this._eventSubs[e];s?this._eventSubsNum[e]++:(s={},this._eventSubs[e]=s,this._eventSubsNum[e]=1);var r=this._subIdMap.addItem();s[r]={callback:t,scope:i||this},this._subIdEvents[r]=e;var n=this._events[e];return void 0!==n&&t.call(i||this,n),r}},{key:"off",value:function(e){if(null!=e&&this._subIdEvents){var t=this._subIdEvents[e];if(t){delete this._subIdEvents[e];var i=this._eventSubs[t];i&&(delete i[e],this._eventSubsNum[t]--),this._subIdMap.removeItem(e)}}}},{key:"once",value:function(e,t,i){var s=this,r=this.on(e,(function(e){s.off(r),t.call(i||this,e)}),i)}},{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}(),Y=!0,K=Y?Float64Array:Float32Array,J=new K(16),Z=new K(16),Q=new K(4),q={setDoublePrecisionEnabled:function(e){K=(Y=e)?Float64Array:Float32Array},getDoublePrecisionEnabled:function(){return Y},MIN_DOUBLE:-Number.MAX_SAFE_INTEGER,MAX_DOUBLE:Number.MAX_SAFE_INTEGER,DEGTORAD:.0174532925,RADTODEG:57.295779513,unglobalizeObjectId:function(e,t){var i=t.indexOf("#");return i===e.length&&t.startsWith(e)?t.substring(i+1):t},globalizeObjectId:function(e,t){return e+"#"+t},vec2:function(e){return new K(e||2)},vec3:function(e){return new K(e||3)},vec4:function(e){return new K(e||4)},mat3:function(e){return new K(e||9)},mat3ToMat4:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:new K(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 K(e||16)},mat4ToMat3:function(e,t){},doublesToFloats:function(e,t,i){for(var s=new K(2),r=0,n=e.length;r<n;r++)q.splitDouble(e[r],s),t[r]=s[0],i[r]=s[1]},splitDouble:function(e,t){var i=K.from([e])[0],s=e-i;t[0]=i,t[1]=s},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,i=4294967295*Math.random()|0,s=4294967295*Math.random()|0,r=4294967295*Math.random()|0;return"".concat(e[255&t]+e[t>>8&255]+e[t>>16&255]+e[t>>24&255],"-").concat(e[255&i]).concat(e[i>>8&255],"-").concat(e[i>>16&15|64]).concat(e[i>>24&255],"-").concat(e[63&s|128]).concat(e[s>>8&255],"-").concat(e[s>>16&255]).concat(e[s>>24&255]).concat(e[255&r]).concat(e[r>>8&255]).concat(e[r>>16&255]).concat(e[r>>24&255])}}(),clamp:function(e,t,i){return Math.max(t,Math.min(i,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,i){return i||(i=e),i[0]=e[0]+t[0],i[1]=e[1]+t[1],i[2]=e[2]+t[2],i[3]=e[3]+t[3],i},addVec4Scalar:function(e,t,i){return i||(i=e),i[0]=e[0]+t,i[1]=e[1]+t,i[2]=e[2]+t,i[3]=e[3]+t,i},addVec3:function(e,t,i){return i||(i=e),i[0]=e[0]+t[0],i[1]=e[1]+t[1],i[2]=e[2]+t[2],i},addVec3Scalar:function(e,t,i){return i||(i=e),i[0]=e[0]+t,i[1]=e[1]+t,i[2]=e[2]+t,i},subVec4:function(e,t,i){return i||(i=e),i[0]=e[0]-t[0],i[1]=e[1]-t[1],i[2]=e[2]-t[2],i[3]=e[3]-t[3],i},subVec3:function(e,t,i){return i||(i=e),i[0]=e[0]-t[0],i[1]=e[1]-t[1],i[2]=e[2]-t[2],i},subVec2:function(e,t,i){return i||(i=e),i[0]=e[0]-t[0],i[1]=e[1]-t[1],i},geometricMeanVec2:function(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];for(var s=new K(t[0]),r=1;r<t.length;r++)s[0]+=t[r][0],s[1]+=t[r][1];return s[0]/=t.length,s[1]/=t.length,s},subVec4Scalar:function(e,t,i){return i||(i=e),i[0]=e[0]-t,i[1]=e[1]-t,i[2]=e[2]-t,i[3]=e[3]-t,i},subScalarVec4:function(e,t,i){return i||(i=e),i[0]=t-e[0],i[1]=t-e[1],i[2]=t-e[2],i[3]=t-e[3],i},mulVec4:function(e,t,i){return i||(i=e),i[0]=e[0]*t[0],i[1]=e[1]*t[1],i[2]=e[2]*t[2],i[3]=e[3]*t[3],i},mulVec4Scalar:function(e,t,i){return i||(i=e),i[0]=e[0]*t,i[1]=e[1]*t,i[2]=e[2]*t,i[3]=e[3]*t,i},mulVec3Scalar:function(e,t,i){return i||(i=e),i[0]=e[0]*t,i[1]=e[1]*t,i[2]=e[2]*t,i},mulVec2Scalar:function(e,t,i){return i||(i=e),i[0]=e[0]*t,i[1]=e[1]*t,i},divVec3:function(e,t,i){return i||(i=e),i[0]=e[0]/t[0],i[1]=e[1]/t[1],i[2]=e[2]/t[2],i},divVec4:function(e,t,i){return i||(i=e),i[0]=e[0]/t[0],i[1]=e[1]/t[1],i[2]=e[2]/t[2],i[3]=e[3]/t[3],i},divScalarVec3:function(e,t,i){return i||(i=t),i[0]=e/t[0],i[1]=e/t[1],i[2]=e/t[2],i},divVec3Scalar:function(e,t,i){return i||(i=e),i[0]=e[0]/t,i[1]=e[1]/t,i[2]=e[2]/t,i},divVec4Scalar:function(e,t,i){return i||(i=e),i[0]=e[0]/t,i[1]=e[1]/t,i[2]=e[2]/t,i[3]=e[3]/t,i},divScalarVec4:function(e,t,i){return i||(i=t),i[0]=e/t[0],i[1]=e/t[1],i[2]=e/t[2],i[3]=e/t[3],i},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 i=e[0],s=e[1],r=e[2],n=t[0],o=t[1],a=t[2];return[s*a-r*o,r*n-i*a,i*o-s*n,0]},cross3Vec3:function(e,t,i){i||(i=e);var s=e[0],r=e[1],n=e[2],o=t[0],a=t[1],u=t[2];return i[0]=r*u-n*a,i[1]=n*o-s*u,i[2]=s*a-r*o,i},sqLenVec4:function(e){return q.dotVec4(e,e)},lenVec4:function(e){return Math.sqrt(q.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 q.dotVec3(e,e)},sqLenVec2:function(e){return q.dotVec2(e,e)},lenVec3:function(e){return Math.sqrt(q.sqLenVec3(e))},distVec3:(j=new K(3),function(e,t){return q.lenVec3(q.subVec3(e,t,j))}),lenVec2:function(e){return Math.sqrt(q.sqLenVec2(e))},distVec2:function(){var e=new K(2);return function(t,i){return q.lenVec2(q.subVec2(t,i,e))}}(),rcpVec3:function(e,t){return q.divScalarVec3(1,e,t)},normalizeVec4:function(e,t){var i=1/q.lenVec4(e);return q.mulVec4Scalar(e,i,t)},normalizeVec3:function(e,t){var i=1/q.lenVec3(e);return q.mulVec3Scalar(e,i,t)},normalizeVec2:function(e,t){var i=1/q.lenVec2(e);return q.mulVec2Scalar(e,i,t)},angleVec3:function(e,t){var i=q.dotVec3(e,t)/Math.sqrt(q.sqLenVec3(e)*q.sqLenVec3(t));return i=i<-1?-1:i>1?1:i,Math.acos(i)},vec3FromMat4Scale:function(){var e=new K(3);return function(t,i){return e[0]=t[0],e[1]=t[1],e[2]=t[2],i[0]=q.lenVec3(e),e[0]=t[4],e[1]=t[5],e[2]=t[6],i[1]=q.lenVec3(e),e[0]=t[8],e[1]=t[9],e[2]=t[10],i[2]=q.lenVec3(e),i}}(),vecToArray:function(){function e(e){return Math.round(1e5*e)/1e5}return function(t){for(var i=0,s=(t=Array.prototype.slice.call(t)).length;i<s;i++)t[i]=e(t[i]);return t}}(),xyzArrayToObject:function(e){return{x:e[0],y:e[1],z:e[2]}},xyzObjectToArray:function(e,t){return(t=t||q.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 q.m4s(0)},setMat4ToOnes:function(){return q.m4s(1)},diagonalMat4v:function(e){return new K([e[0],0,0,0,0,e[1],0,0,0,0,e[2],0,0,0,0,e[3]])},diagonalMat4c:function(e,t,i,s){return q.diagonalMat4v([e,t,i,s])},diagonalMat4s:function(e){return q.diagonalMat4c(e,e,e,e)},identityMat4:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:new K(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 K(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,i){return i||(i=e),i[0]=e[0]+t[0],i[1]=e[1]+t[1],i[2]=e[2]+t[2],i[3]=e[3]+t[3],i[4]=e[4]+t[4],i[5]=e[5]+t[5],i[6]=e[6]+t[6],i[7]=e[7]+t[7],i[8]=e[8]+t[8],i[9]=e[9]+t[9],i[10]=e[10]+t[10],i[11]=e[11]+t[11],i[12]=e[12]+t[12],i[13]=e[13]+t[13],i[14]=e[14]+t[14],i[15]=e[15]+t[15],i},addMat4Scalar:function(e,t,i){return i||(i=e),i[0]=e[0]+t,i[1]=e[1]+t,i[2]=e[2]+t,i[3]=e[3]+t,i[4]=e[4]+t,i[5]=e[5]+t,i[6]=e[6]+t,i[7]=e[7]+t,i[8]=e[8]+t,i[9]=e[9]+t,i[10]=e[10]+t,i[11]=e[11]+t,i[12]=e[12]+t,i[13]=e[13]+t,i[14]=e[14]+t,i[15]=e[15]+t,i},addScalarMat4:function(e,t,i){return q.addMat4Scalar(t,e,i)},subMat4:function(e,t,i){return i||(i=e),i[0]=e[0]-t[0],i[1]=e[1]-t[1],i[2]=e[2]-t[2],i[3]=e[3]-t[3],i[4]=e[4]-t[4],i[5]=e[5]-t[5],i[6]=e[6]-t[6],i[7]=e[7]-t[7],i[8]=e[8]-t[8],i[9]=e[9]-t[9],i[10]=e[10]-t[10],i[11]=e[11]-t[11],i[12]=e[12]-t[12],i[13]=e[13]-t[13],i[14]=e[14]-t[14],i[15]=e[15]-t[15],i},subMat4Scalar:function(e,t,i){return i||(i=e),i[0]=e[0]-t,i[1]=e[1]-t,i[2]=e[2]-t,i[3]=e[3]-t,i[4]=e[4]-t,i[5]=e[5]-t,i[6]=e[6]-t,i[7]=e[7]-t,i[8]=e[8]-t,i[9]=e[9]-t,i[10]=e[10]-t,i[11]=e[11]-t,i[12]=e[12]-t,i[13]=e[13]-t,i[14]=e[14]-t,i[15]=e[15]-t,i},subScalarMat4:function(e,t,i){return i||(i=t),i[0]=e-t[0],i[1]=e-t[1],i[2]=e-t[2],i[3]=e-t[3],i[4]=e-t[4],i[5]=e-t[5],i[6]=e-t[6],i[7]=e-t[7],i[8]=e-t[8],i[9]=e-t[9],i[10]=e-t[10],i[11]=e-t[11],i[12]=e-t[12],i[13]=e-t[13],i[14]=e-t[14],i[15]=e-t[15],i},mulMat4:function(e,t,i){i||(i=e);var s=e[0],r=e[1],n=e[2],o=e[3],a=e[4],u=e[5],h=e[6],l=e[7],c=e[8],p=e[9],d=e[10],f=e[11],m=e[12],v=e[13],g=e[14],_=e[15],y=t[0],b=t[1],x=t[2],P=t[3],T=t[4],w=t[5],M=t[6],I=t[7],C=t[8],D=t[9],A=t[10],k=t[11],E=t[12],F=t[13],R=t[14],S=t[15];return i[0]=y*s+b*a+x*c+P*m,i[1]=y*r+b*u+x*p+P*v,i[2]=y*n+b*h+x*d+P*g,i[3]=y*o+b*l+x*f+P*_,i[4]=T*s+w*a+M*c+I*m,i[5]=T*r+w*u+M*p+I*v,i[6]=T*n+w*h+M*d+I*g,i[7]=T*o+w*l+M*f+I*_,i[8]=C*s+D*a+A*c+k*m,i[9]=C*r+D*u+A*p+k*v,i[10]=C*n+D*h+A*d+k*g,i[11]=C*o+D*l+A*f+k*_,i[12]=E*s+F*a+R*c+S*m,i[13]=E*r+F*u+R*p+S*v,i[14]=E*n+F*h+R*d+S*g,i[15]=E*o+F*l+R*f+S*_,i},mulMat3:function(e,t,i){i||(i=new K(9));var s=e[0],r=e[3],n=e[6],o=e[1],a=e[4],u=e[7],h=e[2],l=e[5],c=e[8],p=t[0],d=t[3],f=t[6],m=t[1],v=t[4],g=t[7],_=t[2],y=t[5],b=t[8];return i[0]=s*p+r*m+n*_,i[3]=s*d+r*v+n*y,i[6]=s*f+r*g+n*b,i[1]=o*p+a*m+u*_,i[4]=o*d+a*v+u*y,i[7]=o*f+a*g+u*b,i[2]=h*p+l*m+c*_,i[5]=h*d+l*v+c*y,i[8]=h*f+l*g+c*b,i},mulMat4Scalar:function(e,t,i){return i||(i=e),i[0]=e[0]*t,i[1]=e[1]*t,i[2]=e[2]*t,i[3]=e[3]*t,i[4]=e[4]*t,i[5]=e[5]*t,i[6]=e[6]*t,i[7]=e[7]*t,i[8]=e[8]*t,i[9]=e[9]*t,i[10]=e[10]*t,i[11]=e[11]*t,i[12]=e[12]*t,i[13]=e[13]*t,i[14]=e[14]*t,i[15]=e[15]*t,i},mulMat4v4:function(e,t){var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:q.vec4(),s=t[0],r=t[1],n=t[2],o=t[3];return i[0]=e[0]*s+e[4]*r+e[8]*n+e[12]*o,i[1]=e[1]*s+e[5]*r+e[9]*n+e[13]*o,i[2]=e[2]*s+e[6]*r+e[10]*n+e[14]*o,i[3]=e[3]*s+e[7]*r+e[11]*n+e[15]*o,i},transposeMat4:function(e,t){var i=e[4],s=e[14],r=e[8],n=e[13],o=e[12],a=e[9];if(!t||e===t){var u=e[1],h=e[2],l=e[3],c=e[6],p=e[7],d=e[11];return e[1]=i,e[2]=r,e[3]=o,e[4]=u,e[6]=a,e[7]=n,e[8]=h,e[9]=c,e[11]=s,e[12]=l,e[13]=p,e[14]=d,e}return t[0]=e[0],t[1]=i,t[2]=r,t[3]=o,t[4]=e[1],t[5]=e[5],t[6]=a,t[7]=n,t[8]=e[2],t[9]=e[6],t[10]=e[10],t[11]=s,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 i=e[1],s=e[2],r=e[5];t[1]=e[3],t[2]=e[6],t[3]=i,t[5]=e[7],t[6]=s,t[7]=r}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],i=e[1],s=e[2],r=e[3],n=e[4],o=e[5],a=e[6],u=e[7],h=e[8],l=e[9],c=e[10],p=e[11],d=e[12],f=e[13],m=e[14],v=e[15];return d*l*a*r-h*f*a*r-d*o*c*r+n*f*c*r+h*o*m*r-n*l*m*r-d*l*s*u+h*f*s*u+d*i*c*u-t*f*c*u-h*i*m*u+t*l*m*u+d*o*s*p-n*f*s*p-d*i*a*p+t*f*a*p+n*i*m*p-t*o*m*p-h*o*s*v+n*l*s*v+h*i*a*v-t*l*a*v-n*i*c*v+t*o*c*v},inverseMat4:function(e,t){t||(t=e);var i=e[0],s=e[1],r=e[2],n=e[3],o=e[4],a=e[5],u=e[6],h=e[7],l=e[8],c=e[9],p=e[10],d=e[11],f=e[12],m=e[13],v=e[14],g=e[15],_=i*a-s*o,y=i*u-r*o,b=i*h-n*o,x=s*u-r*a,P=s*h-n*a,T=r*h-n*u,w=l*m-c*f,M=l*v-p*f,I=l*g-d*f,C=c*v-p*m,D=c*g-d*m,A=p*g-d*v,k=1/(_*A-y*D+b*C+x*I-P*M+T*w);return t[0]=(a*A-u*D+h*C)*k,t[1]=(-s*A+r*D-n*C)*k,t[2]=(m*T-v*P+g*x)*k,t[3]=(-c*T+p*P-d*x)*k,t[4]=(-o*A+u*I-h*M)*k,t[5]=(i*A-r*I+n*M)*k,t[6]=(-f*T+v*b-g*y)*k,t[7]=(l*T-p*b+d*y)*k,t[8]=(o*D-a*I+h*w)*k,t[9]=(-i*D+s*I-n*w)*k,t[10]=(f*P-m*b+g*_)*k,t[11]=(-l*P+c*b-d*_)*k,t[12]=(-o*C+a*M-u*w)*k,t[13]=(i*C-s*M+r*w)*k,t[14]=(-f*x+m*y-v*_)*k,t[15]=(l*x-c*y+p*_)*k,t},traceMat4:function(e){return e[0]+e[5]+e[10]+e[15]},translationMat4v:function(e,t){var i=t||q.identityMat4();return i[12]=e[0],i[13]=e[1],i[14]=e[2],i},translationMat3v:function(e,t){var i=t||q.identityMat3();return i[6]=e[0],i[7]=e[1],i},translationMat4c:(N=new K(3),function(e,t,i,s){return N[0]=e,N[1]=t,N[2]=i,q.translationMat4v(N,s)}),translationMat4s:function(e,t){return q.translationMat4c(e,e,e,t)},translateMat4v:function(e,t){return q.translateMat4c(e[0],e[1],e[2],t)},translateMat4c:function(e,t,i,s){var r=s[3];s[0]+=r*e,s[1]+=r*t,s[2]+=r*i;var n=s[7];s[4]+=n*e,s[5]+=n*t,s[6]+=n*i;var o=s[11];s[8]+=o*e,s[9]+=o*t,s[10]+=o*i;var a=s[15];return s[12]+=a*e,s[13]+=a*t,s[14]+=a*i,s},setMat4Translation:function(e,t,i){return i[0]=e[0],i[1]=e[1],i[2]=e[2],i[3]=e[3],i[4]=e[4],i[5]=e[5],i[6]=e[6],i[7]=e[7],i[8]=e[8],i[9]=e[9],i[10]=e[10],i[11]=e[11],i[12]=t[0],i[13]=t[1],i[14]=t[2],i[15]=e[15],i},rotationMat4v:function(e,t,i){var s,r,n,o,a,u,h=q.normalizeVec4([t[0],t[1],t[2],0],[]),l=Math.sin(e),c=Math.cos(e),p=1-c,d=h[0],f=h[1],m=h[2];return s=d*f,r=f*m,n=m*d,o=d*l,a=f*l,u=m*l,(i=i||q.mat4())[0]=p*d*d+c,i[1]=p*s+u,i[2]=p*n-a,i[3]=0,i[4]=p*s-u,i[5]=p*f*f+c,i[6]=p*r+o,i[7]=0,i[8]=p*n+a,i[9]=p*r-o,i[10]=p*m*m+c,i[11]=0,i[12]=0,i[13]=0,i[14]=0,i[15]=1,i},rotationMat4c:function(e,t,i,s,r){return q.rotationMat4v(e,[t,i,s],r)},scalingMat4v:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:q.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]:q.identityMat3();return t[0]=e[0],t[4]=e[1],t},scalingMat4c:function(){var e=new K(3);return function(t,i,s,r){return e[0]=t,e[1]=i,e[2]=s,q.scalingMat4v(e,r)}}(),scaleMat4c:function(e,t,i,s){return s[0]*=e,s[4]*=t,s[8]*=i,s[1]*=e,s[5]*=t,s[9]*=i,s[2]*=e,s[6]*=t,s[10]*=i,s[3]*=e,s[7]*=t,s[11]*=i,s},scaleMat4v:function(e,t){var i=e[0],s=e[1],r=e[2];return t[0]*=i,t[4]*=s,t[8]*=r,t[1]*=i,t[5]*=s,t[9]*=r,t[2]*=i,t[6]*=s,t[10]*=r,t[3]*=i,t[7]*=s,t[11]*=r,t},scalingMat4s:function(e){return q.scalingMat4c(e,e,e)},rotationTranslationMat4:function(e,t){var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:q.mat4(),s=e[0],r=e[1],n=e[2],o=e[3],a=s+s,u=r+r,h=n+n,l=s*a,c=s*u,p=s*h,d=r*u,f=r*h,m=n*h,v=o*a,g=o*u,_=o*h;return i[0]=1-(d+m),i[1]=c+_,i[2]=p-g,i[3]=0,i[4]=c-_,i[5]=1-(l+m),i[6]=f+v,i[7]=0,i[8]=p+g,i[9]=f-v,i[10]=1-(l+d),i[11]=0,i[12]=t[0],i[13]=t[1],i[14]=t[2],i[15]=1,i},mat4ToEuler:function(e,t){var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:q.vec4(),s=q.clamp,r=e[0],n=e[4],o=e[8],a=e[1],u=e[5],h=e[9],l=e[2],c=e[6],p=e[10];return"XYZ"===t?(i[1]=Math.asin(s(o,-1,1)),Math.abs(o)<.99999?(i[0]=Math.atan2(-h,p),i[2]=Math.atan2(-n,r)):(i[0]=Math.atan2(c,u),i[2]=0)):"YXZ"===t?(i[0]=Math.asin(-s(h,-1,1)),Math.abs(h)<.99999?(i[1]=Math.atan2(o,p),i[2]=Math.atan2(a,u)):(i[1]=Math.atan2(-l,r),i[2]=0)):"ZXY"===t?(i[0]=Math.asin(s(c,-1,1)),Math.abs(c)<.99999?(i[1]=Math.atan2(-l,p),i[2]=Math.atan2(-n,u)):(i[1]=0,i[2]=Math.atan2(a,r))):"ZYX"===t?(i[1]=Math.asin(-s(l,-1,1)),Math.abs(l)<.99999?(i[0]=Math.atan2(c,p),i[2]=Math.atan2(a,r)):(i[0]=0,i[2]=Math.atan2(-n,u))):"YZX"===t?(i[2]=Math.asin(s(a,-1,1)),Math.abs(a)<.99999?(i[0]=Math.atan2(-h,u),i[1]=Math.atan2(-l,r)):(i[0]=0,i[1]=Math.atan2(o,p))):"XZY"===t&&(i[2]=Math.asin(-s(n,-1,1)),Math.abs(n)<.99999?(i[0]=Math.atan2(c,u),i[1]=Math.atan2(o,r)):(i[0]=Math.atan2(-h,p),i[1]=0)),i},composeMat4:function(e,t,i){var s=arguments.length>3&&void 0!==arguments[3]?arguments[3]:q.mat4();return q.quaternionToRotationMat4(t,s),q.scaleMat4v(i,s),q.translateMat4v(e,s),s},decomposeMat4:function(){var e=new K(3),t=new K(16);return function(i,s,r,n){e[0]=i[0],e[1]=i[1],e[2]=i[2];var o=q.lenVec3(e);e[0]=i[4],e[1]=i[5],e[2]=i[6];var a=q.lenVec3(e);e[8]=i[8],e[9]=i[9],e[10]=i[10];var u=q.lenVec3(e);q.determinantMat4(i)<0&&(o=-o),s[0]=i[12],s[1]=i[13],s[2]=i[14],t.set(i);var h=1/o,l=1/a,c=1/u;return t[0]*=h,t[1]*=h,t[2]*=h,t[4]*=l,t[5]*=l,t[6]*=l,t[8]*=c,t[9]*=c,t[10]*=c,q.mat4ToQuaternion(t,r),n[0]=o,n[1]=a,n[2]=u,this}}(),getColMat4:function(e,t){var i=4*t;return[e[i],e[i+1],e[i+2],e[i+3]]},setRowMat4:function(e,t,i){e[t]=i[0],e[t+4]=i[1],e[t+8]=i[2],e[t+12]=i[3]},lookAtMat4v:function(e,t,i,s){s||(s=q.mat4());var r,n,o,a,u,h,l,c,p,d,f=e[0],m=e[1],v=e[2],g=i[0],_=i[1],y=i[2],b=t[0],x=t[1],P=t[2];return f===b&&m===x&&v===P?q.identityMat4():(r=f-b,n=m-x,o=v-P,a=_*(o*=d=1/Math.sqrt(r*r+n*n+o*o))-y*(n*=d),u=y*(r*=d)-g*o,h=g*n-_*r,(d=Math.sqrt(a*a+u*u+h*h))?(a*=d=1/d,u*=d,h*=d):(a=0,u=0,h=0),l=n*h-o*u,c=o*a-r*h,p=r*u-n*a,(d=Math.sqrt(l*l+c*c+p*p))?(l*=d=1/d,c*=d,p*=d):(l=0,c=0,p=0),s[0]=a,s[1]=l,s[2]=r,s[3]=0,s[4]=u,s[5]=c,s[6]=n,s[7]=0,s[8]=h,s[9]=p,s[10]=o,s[11]=0,s[12]=-(a*f+u*m+h*v),s[13]=-(l*f+c*m+p*v),s[14]=-(r*f+n*m+o*v),s[15]=1,s)},lookAtMat4c:function(e,t,i,s,r,n,o,a,u){return q.lookAtMat4v([e,t,i],[s,r,n],[o,a,u],[])},orthoMat4c:function(e,t,i,s,r,n,o){o||(o=q.mat4());var a=t-e,u=s-i,h=n-r;return o[0]=2/a,o[1]=0,o[2]=0,o[3]=0,o[4]=0,o[5]=2/u,o[6]=0,o[7]=0,o[8]=0,o[9]=0,o[10]=-2/h,o[11]=0,o[12]=-(e+t)/a,o[13]=-(s+i)/u,o[14]=-(n+r)/h,o[15]=1,o},frustumMat4v:function(e,t,i){i||(i=q.mat4());var s=[e[0],e[1],e[2],0],r=[t[0],t[1],t[2],0];q.addVec4(r,s,J),q.subVec4(r,s,Z);var n=2*s[2],o=Z[0],a=Z[1],u=Z[2];return i[0]=n/o,i[1]=0,i[2]=0,i[3]=0,i[4]=0,i[5]=n/a,i[6]=0,i[7]=0,i[8]=J[0]/o,i[9]=J[1]/a,i[10]=-J[2]/u,i[11]=-1,i[12]=0,i[13]=0,i[14]=-n*r[2]/u,i[15]=0,i},frustumMat4:function(e,t,i,s,r,n,o){o||(o=q.mat4());var a=t-e,u=s-i,h=n-r;return o[0]=2*r/a,o[1]=0,o[2]=0,o[3]=0,o[4]=0,o[5]=2*r/u,o[6]=0,o[7]=0,o[8]=(t+e)/a,o[9]=(s+i)/u,o[10]=-(n+r)/h,o[11]=-1,o[12]=0,o[13]=0,o[14]=-n*r*2/h,o[15]=0,o},perspectiveMat4:function(e,t,i,s,r){var n=[],o=[];return n[2]=i,o[2]=s,o[1]=n[2]*Math.tan(e/2),n[1]=-o[1],o[0]=o[1]*t,n[0]=-o[0],q.frustumMat4v(n,o,r)},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 i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:q.vec3(),s=t[0],r=t[1],n=t[2];return i[0]=e[0]*s+e[4]*r+e[8]*n+e[12],i[1]=e[1]*s+e[5]*r+e[9]*n+e[13],i[2]=e[2]*s+e[6]*r+e[10]*n+e[14],i},transformPoint4:function(e,t){var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:q.vec4();return i[0]=e[0]*t[0]+e[4]*t[1]+e[8]*t[2]+e[12]*t[3],i[1]=e[1]*t[0]+e[5]*t[1]+e[9]*t[2]+e[13]*t[3],i[2]=e[2]*t[0]+e[6]*t[1]+e[10]*t[2]+e[14]*t[3],i[3]=e[3]*t[0]+e[7]*t[1]+e[11]*t[2]+e[15]*t[3],i},transformPoints3:function(e,t,i){for(var s,r,n,o,a,u=i||[],h=t.length,l=e[0],c=e[1],p=e[2],d=e[3],f=e[4],m=e[5],v=e[6],g=e[7],_=e[8],y=e[9],b=e[10],x=e[11],P=e[12],T=e[13],w=e[14],M=e[15],I=0;I<h;++I)s=(o=t[I])[0],r=o[1],n=o[2],(a=u[I]||(u[I]=[0,0,0]))[0]=l*s+f*r+_*n+P,a[1]=c*s+m*r+y*n+T,a[2]=p*s+v*r+b*n+w,a[3]=d*s+g*r+x*n+M;return u.length=h,u},transformPositions3:function(e,t){var i,s,r,n,o=arguments.length>2&&void 0!==arguments[2]?arguments[2]:t,a=t.length,u=e[0],h=e[1],l=e[2];e[3];var c=e[4],p=e[5],d=e[6];e[7];var f=e[8],m=e[9],v=e[10];e[11];var g=e[12],_=e[13],y=e[14];for(e[15],i=0;i<a;i+=3)s=t[i+0],r=t[i+1],n=t[i+2],o[i+0]=u*s+c*r+f*n+g,o[i+1]=h*s+p*r+m*n+_,o[i+2]=l*s+d*r+v*n+y;return o},transformPositions4:function(e,t){var i,s,r,n,o=arguments.length>2&&void 0!==arguments[2]?arguments[2]:t,a=t.length,u=e[0],h=e[1],l=e[2],c=e[3],p=e[4],d=e[5],f=e[6],m=e[7],v=e[8],g=e[9],_=e[10],y=e[11],b=e[12],x=e[13],P=e[14],T=e[15];for(i=0;i<a;i+=4)s=t[i+0],r=t[i+1],n=t[i+2],o[i+0]=u*s+p*r+v*n+b,o[i+1]=h*s+d*r+g*n+x,o[i+2]=l*s+f*r+_*n+P,o[i+3]=c*s+m*r+y*n+T;return o},transformVec3:function(e,t,i){var s=t[0],r=t[1],n=t[2];return(i=i||this.vec3())[0]=e[0]*s+e[4]*r+e[8]*n,i[1]=e[1]*s+e[5]*r+e[9]*n,i[2]=e[2]*s+e[6]*r+e[10]*n,i},transformVec4:function(e,t,i){var s=t[0],r=t[1],n=t[2],o=t[3];return(i=i||q.vec4())[0]=e[0]*s+e[4]*r+e[8]*n+e[12]*o,i[1]=e[1]*s+e[5]*r+e[9]*n+e[13]*o,i[2]=e[2]*s+e[6]*r+e[10]*n+e[14]*o,i[3]=e[3]*s+e[7]*r+e[11]*n+e[15]*o,i},rotateVec2:function(e,t,i){var s=arguments.length>3&&void 0!==arguments[3]?arguments[3]:e,r=Math.cos(i),n=Math.sin(i),o=e[0]-t[0],a=e[1]-t[1];return s[0]=o*r-a*n+t[0],s[1]=o*n+a*r+t[1],e},rotateVec3X:function(e,t,i,s){var r=[],n=[];return r[0]=e[0]-t[0],r[1]=e[1]-t[1],r[2]=e[2]-t[2],n[0]=r[0],n[1]=r[1]*Math.cos(i)-r[2]*Math.sin(i),n[2]=r[1]*Math.sin(i)+r[2]*Math.cos(i),s[0]=n[0]+t[0],s[1]=n[1]+t[1],s[2]=n[2]+t[2],s},rotateVec3Y:function(e,t,i,s){var r=[],n=[];return r[0]=e[0]-t[0],r[1]=e[1]-t[1],r[2]=e[2]-t[2],n[0]=r[2]*Math.sin(i)+r[0]*Math.cos(i),n[1]=r[1],n[2]=r[2]*Math.cos(i)-r[0]*Math.sin(i),s[0]=n[0]+t[0],s[1]=n[1]+t[1],s[2]=n[2]+t[2],s},rotateVec3Z:function(e,t,i,s){var r=[],n=[];return r[0]=e[0]-t[0],r[1]=e[1]-t[1],r[2]=e[2]-t[2],n[0]=r[0]*Math.cos(i)-r[1]*Math.sin(i),n[1]=r[0]*Math.sin(i)+r[1]*Math.cos(i),n[2]=r[2],s[0]=n[0]+t[0],s[1]=n[1]+t[1],s[2]=n[2]+t[2],s},projectVec4:function(e,t){var i=1/e[3];return(t=t||q.vec2())[0]=e[0]*i,t[1]=e[1]*i,t},unprojectVec3:(O=new K(16),B=new K(16),L=new K(16),function(e,t,i,s){return this.transformVec3(this.mulMat4(this.inverseMat4(t,O),this.inverseMat4(i,B),L),e,s)}),lerpVec3:function(e,t,i,s,r,n){var o=n||q.vec3(),a=(e-t)/(i-t);return o[0]=s[0]+a*(r[0]-s[0]),o[1]=s[1]+a*(r[1]-s[1]),o[2]=s[2]+a*(r[2]-s[2]),o},lerpMat4:function(e,t,i,s,r,n){var o=n||q.mat4(),a=(e-t)/(i-t);return o[0]=s[0]+a*(r[0]-s[0]),o[1]=s[1]+a*(r[1]-s[1]),o[2]=s[2]+a*(r[2]-s[2]),o[3]=s[3]+a*(r[3]-s[3]),o[4]=s[4]+a*(r[4]-s[4]),o[5]=s[5]+a*(r[5]-s[5]),o[6]=s[6]+a*(r[6]-s[6]),o[7]=s[7]+a*(r[7]-s[7]),o[8]=s[8]+a*(r[8]-s[8]),o[9]=s[9]+a*(r[9]-s[9]),o[10]=s[10]+a*(r[10]-s[10]),o[11]=s[11]+a*(r[11]-s[11]),o[12]=s[12]+a*(r[12]-s[12]),o[13]=s[13]+a*(r[13]-s[13]),o[14]=s[14]+a*(r[14]-s[14]),o[15]=s[15]+a*(r[15]-s[15]),o},flatten:function(e){var t,i,s,r,n,o=[];for(t=0,i=e.length;t<i;t++)for(s=0,r=(n=e[t]).length;s<r;s++)o.push(n[s]);return o},identityQuaternion:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:q.vec4();return e[0]=0,e[1]=0,e[2]=0,e[3]=1,e},eulerToQuaternion:function(e,t){var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:q.vec4(),s=e[0]*q.DEGTORAD/2,r=e[1]*q.DEGTORAD/2,n=e[2]*q.DEGTORAD/2,o=Math.cos(s),a=Math.cos(r),u=Math.cos(n),h=Math.sin(s),l=Math.sin(r),c=Math.sin(n);return"XYZ"===t?(i[0]=h*a*u+o*l*c,i[1]=o*l*u-h*a*c,i[2]=o*a*c+h*l*u,i[3]=o*a*u-h*l*c):"YXZ"===t?(i[0]=h*a*u+o*l*c,i[1]=o*l*u-h*a*c,i[2]=o*a*c-h*l*u,i[3]=o*a*u+h*l*c):"ZXY"===t?(i[0]=h*a*u-o*l*c,i[1]=o*l*u+h*a*c,i[2]=o*a*c+h*l*u,i[3]=o*a*u-h*l*c):"ZYX"===t?(i[0]=h*a*u-o*l*c,i[1]=o*l*u+h*a*c,i[2]=o*a*c-h*l*u,i[3]=o*a*u+h*l*c):"YZX"===t?(i[0]=h*a*u+o*l*c,i[1]=o*l*u+h*a*c,i[2]=o*a*c-h*l*u,i[3]=o*a*u-h*l*c):"XZY"===t&&(i[0]=h*a*u-o*l*c,i[1]=o*l*u-h*a*c,i[2]=o*a*c+h*l*u,i[3]=o*a*u+h*l*c),i},mat4ToQuaternion:function(e){var t,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:q.vec4(),s=e[0],r=e[4],n=e[8],o=e[1],a=e[5],u=e[9],h=e[2],l=e[6],c=e[10],p=s+a+c;return p>0?(t=.5/Math.sqrt(p+1),i[3]=.25/t,i[0]=(l-u)*t,i[1]=(n-h)*t,i[2]=(o-r)*t):s>a&&s>c?(t=2*Math.sqrt(1+s-a-c),i[3]=(l-u)/t,i[0]=.25*t,i[1]=(r+o)/t,i[2]=(n+h)/t):a>c?(t=2*Math.sqrt(1+a-s-c),i[3]=(n-h)/t,i[0]=(r+o)/t,i[1]=.25*t,i[2]=(u+l)/t):(t=2*Math.sqrt(1+c-s-a),i[3]=(o-r)/t,i[0]=(n+h)/t,i[1]=(u+l)/t,i[2]=.25*t),i},vec3PairToQuaternion:function(e,t){var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:q.vec4(),s=Math.sqrt(q.dotVec3(e,e)*q.dotVec3(t,t)),r=s+q.dotVec3(e,t);return r<1e-8*s?(r=0,Math.abs(e[0])>Math.abs(e[2])?(i[0]=-e[1],i[1]=e[0],i[2]=0):(i[0]=0,i[1]=-e[2],i[2]=e[1])):q.cross3Vec3(e,t,i),i[3]=r,q.normalizeQuaternion(i)},angleAxisToQuaternion:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:q.vec4(),i=e[3]/2,s=Math.sin(i);return t[0]=s*e[0],t[1]=s*e[1],t[2]=s*e[2],t[3]=Math.cos(i),t},quaternionToEuler:function(){var e=new K(16);return function(t,i,s){return s=s||q.vec3(),q.quaternionToRotationMat4(t,e),q.mat4ToEuler(e,i,s),s}}(),mulQuaternions:function(e,t){var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:q.vec4(),s=e[0],r=e[1],n=e[2],o=e[3],a=t[0],u=t[1],h=t[2],l=t[3];return i[0]=o*a+s*l+r*h-n*u,i[1]=o*u+r*l+n*a-s*h,i[2]=o*h+n*l+s*u-r*a,i[3]=o*l-s*a-r*u-n*h,i},vec3ApplyQuaternion:function(e,t){var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:q.vec3(),s=t[0],r=t[1],n=t[2],o=e[0],a=e[1],u=e[2],h=e[3],l=h*s+a*n-u*r,c=h*r+u*s-o*n,p=h*n+o*r-a*s,d=-o*s-a*r-u*n;return i[0]=l*h+d*-o+c*-u-p*-a,i[1]=c*h+d*-a+p*-o-l*-u,i[2]=p*h+d*-u+l*-a-c*-o,i},quaternionToMat4:function(e,t){t=q.identityMat4(t);var i=e[0],s=e[1],r=e[2],n=e[3],o=2*i,a=2*s,u=2*r,h=o*n,l=a*n,c=u*n,p=o*i,d=a*i,f=u*i,m=a*s,v=u*s,g=u*r;return t[0]=1-(m+g),t[1]=d+c,t[2]=f-l,t[4]=d-c,t[5]=1-(p+g),t[6]=v+h,t[8]=f+l,t[9]=v-h,t[10]=1-(p+m),t},quaternionToRotationMat4:function(e,t){var i=e[0],s=e[1],r=e[2],n=e[3],o=i+i,a=s+s,u=r+r,h=i*o,l=i*a,c=i*u,p=s*a,d=s*u,f=r*u,m=n*o,v=n*a,g=n*u;return t[0]=1-(p+f),t[4]=l-g,t[8]=c+v,t[1]=l+g,t[5]=1-(h+f),t[9]=d-m,t[2]=c-v,t[6]=d+m,t[10]=1-(h+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,i=q.lenVec4([e[0],e[1],e[2],e[3]]);return t[0]=e[0]/i,t[1]=e[1]/i,t[2]=e[2]/i,t[3]=e[3]/i,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 q.normalizeQuaternion(q.conjugateQuaternion(e,t))},quaternionToAngleAxis:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:q.vec4(),i=(e=q.normalizeQuaternion(e,Q))[3],s=2*Math.acos(i),r=Math.sqrt(1-i*i);return r<.001?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=e[0]/r,t[1]=e[1]/r,t[2]=e[2]/r),t[3]=s,t},AABB3:function(e){return new K(e||6)},AABB2:function(e){return new K(e||4)},OBB3:function(e){return new K(e||32)},OBB2:function(e){return new K(e||16)},Sphere3:function(e,t,i,s){return new K([e,t,i,s])},transformOBB3:function(e,t){var i,s,r,n,o=arguments.length>2&&void 0!==arguments[2]?arguments[2]:t,a=t.length,u=e[0],h=e[1],l=e[2],c=e[3],p=e[4],d=e[5],f=e[6],m=e[7],v=e[8],g=e[9],_=e[10],y=e[11],b=e[12],x=e[13],P=e[14],T=e[15];for(i=0;i<a;i+=4)s=t[i+0],r=t[i+1],n=t[i+2],o[i+0]=u*s+p*r+v*n+b,o[i+1]=h*s+d*r+g*n+x,o[i+2]=l*s+f*r+_*n+P,o[i+3]=c*s+m*r+y*n+T;return o},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 K(3),t=new K(3),i=new K(3);return function(s){return e[0]=s[0],e[1]=s[1],e[2]=s[2],t[0]=s[3],t[1]=s[4],t[2]=s[5],q.subVec3(t,e,i),Math.abs(q.lenVec3(i))}}(),getAABB3DiagPoint:function(){var e=new K(3),t=new K(3),i=new K(3);return function(s,r){e[0]=s[0],e[1]=s[1],e[2]=s[2],t[0]=s[3],t[1]=s[4],t[2]=s[5];var n=q.subVec3(t,e,i),o=r[0]-s[0],a=s[3]-r[0],u=r[1]-s[1],h=s[4]-r[1],l=r[2]-s[2],c=s[5]-r[2];return n[0]+=o>a?o:a,n[1]+=u>h?u:h,n[2]+=l>c?l:c,Math.abs(q.lenVec3(n))}}(),getAABB3Area:function(e){return(e[3]-e[0])*(e[4]-e[1])*(e[5]-e[2])},getAABB3Center:function(e,t){var i=t||q.vec3();return i[0]=(e[0]+e[3])/2,i[1]=(e[1]+e[4])/2,i[2]=(e[2]+e[5])/2,i},getAABB2Center:function(e,t){var i=t||q.vec2();return i[0]=(e[2]+e[0])/2,i[1]=(e[3]+e[1])/2,i},collapseAABB3:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:q.AABB3();return e[0]=q.MAX_DOUBLE,e[1]=q.MAX_DOUBLE,e[2]=q.MAX_DOUBLE,e[3]=q.MIN_DOUBLE,e[4]=q.MIN_DOUBLE,e[5]=q.MIN_DOUBLE,e},AABB3ToOBB3:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:q.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 K(3);return function(t,i,s){i=i||q.AABB3();for(var r,n,o,a=q.MAX_DOUBLE,u=q.MAX_DOUBLE,h=q.MAX_DOUBLE,l=q.MIN_DOUBLE,c=q.MIN_DOUBLE,p=q.MIN_DOUBLE,d=0,f=t.length;d<f;d+=3)s?(e[0]=t[d+0],e[1]=t[d+1],e[2]=t[d+2],q.decompressPosition(e,s,e),r=e[0],n=e[1],o=e[2]):(r=t[d+0],n=t[d+1],o=t[d+2]),r<a&&(a=r),n<u&&(u=n),o<h&&(h=o),r>l&&(l=r),n>c&&(c=n),o>p&&(p=o);return i[0]=a,i[1]=u,i[2]=h,i[3]=l,i[4]=c,i[5]=p,i}}(),OBB3ToAABB3:function(e){for(var t,i,s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:q.AABB3(),n=q.MAX_DOUBLE,o=q.MAX_DOUBLE,a=q.MAX_DOUBLE,u=q.MIN_DOUBLE,h=q.MIN_DOUBLE,l=q.MIN_DOUBLE,c=0,p=e.length;c<p;c+=4)(t=e[c+0])<n&&(n=t),(i=e[c+1])<o&&(o=i),(s=e[c+2])<a&&(a=s),t>u&&(u=t),i>h&&(h=i),s>l&&(l=s);return r[0]=n,r[1]=o,r[2]=a,r[3]=u,r[4]=h,r[5]=l,r},points3ToAABB3:function(e){for(var t,i,s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:q.AABB3(),n=q.MAX_DOUBLE,o=q.MAX_DOUBLE,a=q.MAX_DOUBLE,u=q.MIN_DOUBLE,h=q.MIN_DOUBLE,l=q.MIN_DOUBLE,c=0,p=e.length;c<p;c++)(t=e[c][0])<n&&(n=t),(i=e[c][1])<o&&(o=i),(s=e[c][2])<a&&(a=s),t>u&&(u=t),i>h&&(h=i),s>l&&(l=s);return r[0]=n,r[1]=o,r[2]=a,r[3]=u,r[4]=h,r[5]=l,r},points3ToSphere3:function(){var e=new K(3);return function(t,i){i=i||q.vec4();var s,r=0,n=0,o=0,a=t.length;for(s=0;s<a;s++)r+=t[s][0],n+=t[s][1],o+=t[s][2];i[0]=r/a,i[1]=n/a,i[2]=o/a;var u,h=0;for(s=0;s<a;s++)(u=Math.abs(q.lenVec3(q.subVec3(t[s],i,e))))>h&&(h=u);return i[3]=h,i}}(),positions3ToSphere3:function(){var e=new K(3),t=new K(3);return function(i,s){s=s||q.vec4();var r,n=0,o=0,a=0,u=i.length,h=0;for(r=0;r<u;r+=3)n+=i[r],o+=i[r+1],a+=i[r+2];var l,c=u/3;for(s[0]=n/c,s[1]=o/c,s[2]=a/c,r=0;r<u;r+=3)e[0]=i[r],e[1]=i[r+1],e[2]=i[r+2],(l=Math.abs(q.lenVec3(q.subVec3(e,s,t))))>h&&(h=l);return s[3]=h,s}}(),OBB3ToSphere3:function(){var e=new K(3),t=new K(3);return function(i,s){s=s||q.vec4();var r,n=0,o=0,a=0,u=i.length,h=u/4;for(r=0;r<u;r+=4)n+=i[r+0],o+=i[r+1],a+=i[r+2];s[0]=n/h,s[1]=o/h,s[2]=a/h;var l,c=0;for(r=0;r<u;r+=4)e[0]=i[r+0],e[1]=i[r+1],e[2]=i[r+2],(l=Math.abs(q.lenVec3(q.subVec3(e,s,t))))>c&&(c=l);return s[3]=c,s}}(),getSphere3Center:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:q.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]:q.vec3(),i=0,s=0,r=0,n=0,o=e.length;n<o;n+=3)i+=e[n+0],s+=e[n+1],r+=e[n+2];var a=e.length/3;return t[0]=i/a,t[1]=s/a,t[2]=r/a,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 i,s,r,n=0,o=t.length;n<o;n+=3)i=t[n],s=t[n+1],r=t[n+2],e[0]>i&&(e[0]=i),e[1]>s&&(e[1]=s),e[2]>r&&(e[2]=r),e[3]<i&&(e[3]=i),e[4]<s&&(e[4]=s),e[5]<r&&(e[5]=r);return e},collapseAABB2:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:q.AABB2();return e[0]=q.MAX_DOUBLE,e[1]=q.MAX_DOUBLE,e[2]=q.MIN_DOUBLE,e[3]=q.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,i){var s,r;return e[0]>0?(s=e[0]*i[0],r=e[0]*i[3]):(s=e[0]*i[3],r=e[0]*i[0]),e[1]>0?(s+=e[1]*i[1],r+=e[1]*i[4]):(s+=e[1]*i[4],r+=e[1]*i[1]),e[2]>0?(s+=e[2]*i[2],r+=e[2]*i[5]):(s+=e[2]*i[5],r+=e[2]*i[2]),s<=-t&&r<=-t?-1:s>=-t&&r>=-t?1:0},OBB3ToAABB2:function(e){for(var t,i,s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:q.AABB2(),n=q.MAX_DOUBLE,o=q.MAX_DOUBLE,a=q.MIN_DOUBLE,u=q.MIN_DOUBLE,h=0,l=e.length;h<l;h+=4)t=e[h+0],i=e[h+1],(t*=s=1/(e[h+3]||1))<n&&(n=t),(i*=s)<o&&(o=i),t>a&&(a=t),i>u&&(u=i);return r[0]=n,r[1]=o,r[2]=a,r[3]=u,r},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,i){var s=arguments.length>3&&void 0!==arguments[3]?arguments[3]:e,r=.5*(e[0]+1),n=.5*(e[1]+1),o=.5*(e[2]+1),a=.5*(e[3]+1);return s[0]=Math.floor(r*t),s[1]=i-Math.floor(a*i),s[2]=Math.floor(o*t),s[3]=i-Math.floor(n*i),s},tangentQuadraticBezier:function(e,t,i,s){return 2*(1-e)*(i-t)+2*e*(s-i)},tangentQuadraticBezier3:function(e,t,i,s,r){return-3*t*(1-e)*(1-e)+3*i*(1-e)*(1-e)-6*e*i*(1-e)+6*e*s*(1-e)-3*e*e*s+3*e*e*r},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,i,s,r){var n=.5*(i-e),o=.5*(s-t),a=r*r;return(2*t-2*i+n+o)*(r*a)+(-3*t+3*i-2*n-o)*a+n*r+t},b2p0:function(e,t){var i=1-e;return i*i*t},b2p1:function(e,t){return 2*(1-e)*e*t},b2p2:function(e,t){return e*e*t},b2:function(e,t,i,s){return this.b2p0(e,t)+this.b2p1(e,i)+this.b2p2(e,s)},b3p0:function(e,t){var i=1-e;return i*i*i*t},b3p1:function(e,t){var i=1-e;return 3*i*i*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,i,s,r){return this.b3p0(e,t)+this.b3p1(e,i)+this.b3p2(e,s)+this.b3p3(e,r)},triangleNormal:function(e,t,i){var s=arguments.length>3&&void 0!==arguments[3]?arguments[3]:q.vec3(),r=t[0]-e[0],n=t[1]-e[1],o=t[2]-e[2],a=i[0]-e[0],u=i[1]-e[1],h=i[2]-e[2],l=n*h-o*u,c=o*a-r*h,p=r*u-n*a,d=Math.sqrt(l*l+c*c+p*p);return 0===d?(s[0]=0,s[1]=0,s[2]=0):(s[0]=l/d,s[1]=c/d,s[2]=p/d),s},rayTriangleIntersect:function(){var e=new K(3),t=new K(3),i=new K(3),s=new K(3),r=new K(3);return function(n,o,a,u,h,l){l=l||q.vec3();var c=q.subVec3(u,a,e),p=q.subVec3(h,a,t),d=q.cross3Vec3(o,p,i),f=q.dotVec3(c,d);if(f<1e-6)return null;var m=q.subVec3(n,a,s),v=q.dotVec3(m,d);if(v<0||v>f)return null;var g=q.cross3Vec3(m,c,r),_=q.dotVec3(o,g);if(_<0||v+_>f)return null;var y=q.dotVec3(p,g)/f;return l[0]=n[0]+y*o[0],l[1]=n[1]+y*o[1],l[2]=n[2]+y*o[2],l}}(),rayPlaneIntersect:function(){var e=new K(3),t=new K(3),i=new K(3),s=new K(3);return function(r,n,o,a,u,h){h=h||q.vec3(),n=q.normalizeVec3(n,e);var l=q.subVec3(a,o,t),c=q.subVec3(u,o,i),p=q.cross3Vec3(l,c,s);q.normalizeVec3(p,p);var d=-q.dotVec3(o,p),f=-(q.dotVec3(r,p)+d)/q.dotVec3(n,p);return h[0]=r[0]+f*n[0],h[1]=r[1]+f*n[1],h[2]=r[2]+f*n[2],h}}(),cartesianToBarycentric:function(){var e=new K(3),t=new K(3),i=new K(3);return function(s,r,n,o,a){var u=q.subVec3(o,r,e),h=q.subVec3(n,r,t),l=q.subVec3(s,r,i),c=q.dotVec3(u,u),p=q.dotVec3(u,h),d=q.dotVec3(u,l),f=q.dotVec3(h,h),m=q.dotVec3(h,l),v=c*f-p*p;if(0===v)return null;var g=1/v,_=(f*d-p*m)*g,y=(c*m-p*d)*g;return a[0]=1-_-y,a[1]=y,a[2]=_,a}}(),barycentricInsideTriangle:function(e){var t=e[1],i=e[2];return i>=0&&t>=0&&i+t<1},barycentricToCartesian:function(e,t,i,s){var r=arguments.length>4&&void 0!==arguments[4]?arguments[4]:q.vec3(),n=e[0],o=e[1],a=e[2];return r[0]=t[0]*n+i[0]*o+s[0]*a,r[1]=t[1]*n+i[1]*o+s[1]*a,r[2]=t[2]*n+i[2]*o+s[2]*a,r},mergeVertices:function(e,t,i,s){var r,n,o,a,u,h,l={},c=[],p=[],d=t?[]:null,f=i?[]:null,m=[],v=Math.pow(10,4),g=0;for(u=0,h=e.length;u<h;u+=3)r=e[u],n=e[u+1],o=e[u+2],void 0===l[a="".concat(Math.round(r*v),"_").concat(Math.round(n*v),"_").concat(Math.round(o*v))]&&(l[a]=p.length/3,p.push(r),p.push(n),p.push(o),t&&(d.push(t[u]),d.push(t[u+1]),d.push(t[u+2])),i&&(f.push(i[g]),f.push(i[g+1]))),c[u/3]=l[a],g+=2;for(u=0,h=s.length;u<h;u++)m[u]=c[s[u]];var _={positions:p,indices:m};return d&&(_.normals=d),f&&(_.uv=f),_},buildNormals:function(){var e=new K(3),t=new K(3),i=new K(3),s=new K(3),r=new K(3),n=new K(3);return function(o,a,u){var h,l,c,p,d,f,m,v,g,_=new Array(o.length/3);for(h=0,l=a.length;h<l;h+=3){c=a[h],p=a[h+1],d=a[h+2],e[0]=o[3*c],e[1]=o[3*c+1],e[2]=o[3*c+2],t[0]=o[3*p],t[1]=o[3*p+1],t[2]=o[3*p+2],i[0]=o[3*d],i[1]=o[3*d+1],i[2]=o[3*d+2],q.subVec3(t,e,s),q.subVec3(i,e,r);var y=q.vec3();q.normalizeVec3(q.cross3Vec3(s,r,n),y),_[c]||(_[c]=[]),_[p]||(_[p]=[]),_[d]||(_[d]=[]),_[c].push(y),_[p].push(y),_[d].push(y)}for(u=u&&u.length===o.length?u:new Float32Array(o.length),h=0,l=_.length;h<l;h++){f=_[h].length,m=0,v=0,g=0;for(var b=0;b<f;b++)m+=_[h][b][0],v+=_[h][b][1],g+=_[h][b][2];u[3*h]=m/f,u[3*h+1]=v/f,u[3*h+2]=g/f}return u}}(),buildTangents:function(){var e=new K(3),t=new K(3),i=new K(3),s=new K(3),r=new K(3),n=new K(3),o=new K(3);return function(a,u,h){for(var l=new Float32Array(a.length),c=0;c<u.length;c+=3){var p=u[c],d=a.subarray(3*p,3*p+3),f=h.subarray(2*p,2*p+2);p=u[c+1];var m=a.subarray(3*p,3*p+3),v=h.subarray(2*p,2*p+2);p=u[c+2];for(var g=a.subarray(3*p,3*p+3),_=h.subarray(2*p,2*p+2),y=q.subVec3(m,d,e),b=q.subVec3(g,d,t),x=q.subVec2(v,f,i),P=q.subVec2(_,f,s),T=1/(x[0]*P[1]-x[1]*P[0]),w=q.mulVec3Scalar(q.subVec3(q.mulVec3Scalar(y,P[1],r),q.mulVec3Scalar(b,x[1],n),o),T,n),M=void 0,I=0;I<3;I++)l[M=3*u[c+I]]+=w[0],l[M+1]+=w[1],l[M+2]+=w[2]}return l}}(),buildPickTriangles:function(e,t,i){for(var s,r,n,o,a,u=t.length,h=i?new Uint16Array(9*u):new Float32Array(9*u),l=new Uint8Array(12*u),c=0,p=0,d=0,f=0;f<u;f+=3)a=c>>24&255,o=c>>16&255,n=c>>8&255,r=255&c,s=3*t[f],h[p++]=e[s],h[p++]=e[s+1],h[p++]=e[s+2],l[d++]=r,l[d++]=n,l[d++]=o,l[d++]=a,s=3*t[f+1],h[p++]=e[s],h[p++]=e[s+1],h[p++]=e[s+2],l[d++]=r,l[d++]=n,l[d++]=o,l[d++]=a,s=3*t[f+2],h[p++]=e[s],h[p++]=e[s+1],h[p++]=e[s+2],l[d++]=r,l[d++]=n,l[d++]=o,l[d++]=a,c++;return{positions:h,colors:l}},faceToVertexNormals:function(e,t){var i,s,r,n,o,a,u,h,l,c,p,d=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},f=d.smoothNormalsAngleThreshold||20,m={},v=[],g={},_=4,y=Math.pow(10,_);for(u=0,l=e.length;u<l;u+=3){a=u/3,s=e[u],r=e[u+1],n=e[u+2],void 0===m[o="".concat(Math.round(s*y),"_").concat(Math.round(r*y),"_").concat(Math.round(n*y))]?m[o]=[a]:m[o].push(a);var b=q.normalizeVec3([t[u],t[u+1],t[u+2]]);v[a]=b,i=q.vec4([b[0],b[1],b[2],1]),g[a]=i}for(o in m)if(m.hasOwnProperty(o)){var x=m[o],P=x.length;for(u=0;u<P;u++){var T=x[u];for(i=g[T],h=0;h<P;h++)if(u!==h){var w=x[h];c=v[T],p=v[w];var M=Math.abs(q.angleVec3(c,p)/q.DEGTORAD);M<f&&(i[0]+=p[0],i[1]+=p[1],i[2]+=p[2],i[3]+=1)}}}for(u=0,l=t.length;u<l;u+=3)i=g[u/3],t[u+0]=i[0]/i[3],t[u+1]=i[1]/i[3],t[u+2]=i[2]/i[3]},transformRay:function(){var e=new K(4),t=new K(4);return function(i,s,r,n,o){e[0]=s[0],e[1]=s[1],e[2]=s[2],e[3]=1,q.transformVec4(i,e,t),n[0]=t[0],n[1]=t[1],n[2]=t[2],e[0]=r[0],e[1]=r[1],e[2]=r[2],q.transformVec3(i,e,t),q.normalizeVec3(t),o[0]=t[0],o[1]=t[1],o[2]=t[2]}}(),canvasPosToWorldRay:function(){var e=new K(16),t=new K(16),i=new K(4),s=new K(4),r=new K(4),n=new K(4);return function(o,a,u,h,l,c){var p=q.mulMat4(u,a,e),d=q.inverseMat4(p,t),f=o.width,m=o.height,v=(h[0]-f/2)/(f/2),g=-(h[1]-m/2)/(m/2);i[0]=v,i[1]=g,i[2]=-1,i[3]=1,q.transformVec4(d,i,s),q.mulVec4Scalar(s,1/s[3]),r[0]=v,r[1]=g,r[2]=1,r[3]=1,q.transformVec4(d,r,n),q.mulVec4Scalar(n,1/n[3]),l[0]=n[0],l[1]=n[1],l[2]=n[2],q.subVec3(n,s,c),q.normalizeVec3(c)}}(),canvasPosToLocalRay:(R=new K(3),S=new K(3),function(e,t,i,s,r,n,o){q.canvasPosToWorldRay(e,t,i,r,R,S),q.worldRayToLocalRay(s,R,S,n,o)}),worldRayToLocalRay:function(){var e=new K(16),t=new K(4),i=new K(4);return function(s,r,n,o,a){var u=q.inverseMat4(s,e);t[0]=r[0],t[1]=r[1],t[2]=r[2],t[3]=1,q.transformVec4(u,t,i),o[0]=i[0],o[1]=i[1],o[2]=i[2],q.transformVec3(u,n,a)}}(),buildKDTree:function(){var e=new Float32Array;function t(i,s,r,n){var o,a,u=new K(6),h={triangles:null,left:null,right:null,leaf:!1,splitDim:0,aabb:u};for(u[0]=u[1]=u[2]=Number.POSITIVE_INFINITY,u[3]=u[4]=u[5]=Number.NEGATIVE_INFINITY,o=0,a=i.length;o<a;++o)for(var l=3*i[o],c=0;c<3;++c){var p=3*s[l+c];r[p]<u[0]&&(u[0]=r[p]),r[p]>u[3]&&(u[3]=r[p]),r[p+1]<u[1]&&(u[1]=r[p+1]),r[p+1]>u[4]&&(u[4]=r[p+1]),r[p+2]<u[2]&&(u[2]=r[p+2]),r[p+2]>u[5]&&(u[5]=r[p+2])}if(i.length<20||n>10)return h.triangles=i,h.leaf=!0,h;e[0]=u[3]-u[0],e[1]=u[4]-u[1],e[2]=u[5]-u[2];var d=0;e[1]>e[d]&&(d=1),e[2]>e[d]&&(d=2),h.splitDim=d;var f=(u[d]+u[d+3])/2,m=new Array(i.length),v=0,g=new Array(i.length),_=0;for(o=0,a=i.length;o<a;++o){var y=s[l=3*i[o]],b=3*s[l+1],x=3*s[l+2];r[3*y+d]<=f||r[b+d]<=f||r[x+d]<=f?m[v++]=i[o]:g[_++]=i[o]}return m.length=v,g.length=_,h.left=t(m,s,r,n+1),h.right=t(g,s,r,n+1),h}return function(e,i){for(var s=e.length/3,r=new Array(s),n=0;n<s;++n)r[n]=n;return t(r,e,i,0)}}(),decompressPosition:function(e,t,i){(i=i||e)[0]=e[0]*t[0]+t[12],i[1]=e[1]*t[5]+t[13],i[2]=e[2]*t[10]+t[14]},decompressPositions:function(e,t){for(var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:new Float32Array(e.length),s=0,r=e.length;s<r;s+=3)i[s+0]=e[s+0]*t[0]+t[12],i[s+1]=e[s+1]*t[5]+t[13],i[s+2]=e[s+2]*t[10]+t[14];return i},decompressUV:function(e,t,i){i[0]=e[0]*t[0]+t[6],i[1]=e[1]*t[4]+t[7]},decompressUVs:function(e,t){for(var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:new Float32Array(e.length),s=0,r=e.length;s<r;s+=3)i[s+0]=e[s+0]*t[0]+t[6],i[s+1]=e[s+1]*t[4]+t[7];return i},octDecodeVec2:function(e,t){var i=e[0],s=e[1];i=(2*i+1)/255,s=(2*s+1)/255;var r=1-Math.abs(i)-Math.abs(s);r<0&&(i=(1-Math.abs(s))*(i>=0?1:-1),s=(1-Math.abs(i))*(s>=0?1:-1));var n=Math.sqrt(i*i+s*s+r*r);return t[0]=i/n,t[1]=s/n,t[2]=r/n,t},octDecodeVec2s:function(e,t){for(var i=0,s=0,r=e.length;i<r;i+=2){var n=e[i+0],o=e[i+1];n=(2*n+1)/255,o=(2*o+1)/255;var a=1-Math.abs(n)-Math.abs(o);a<0&&(n=(1-Math.abs(o))*(n>=0?1:-1),o=(1-Math.abs(n))*(o>=0?1:-1));var u=Math.sqrt(n*n+o*o+a*a);t[s+0]=n/u,t[s+1]=o/u,t[s+2]=a/u,s+=3}return t}};q.buildEdgeIndices=function(){var e=[],t=[],i=[],s=[],r=[],n=0,o=new Uint16Array(3),a=new Uint16Array(3),u=new Uint16Array(3),h=q.vec3(),l=q.vec3(),c=q.vec3(),p=q.vec3(),d=q.vec3(),f=q.vec3(),m=q.vec3();return function(v,g,_,y){!function(r,n){var o,a,u,h,l,c,p={},d=Math.pow(10,4),f=0;for(l=0,c=r.length;l<c;l+=3)o=r[l],a=r[l+1],u=r[l+2],void 0===p[h=Math.round(o*d)+"_"+Math.round(a*d)+"_"+Math.round(u*d)]&&(p[h]=f/3,e[f++]=o,e[f++]=a,e[f++]=u),t[l/3]=p[h];for(l=0,c=n.length;l<c;l++)s[l]=t[n[l]],i[s[l]]=n[l]}(v,g),function(t,i){n=0;for(var v=0,g=t;v<g;v+=3){var _=3*s[v],y=3*s[v+1],b=3*s[v+2];i?(o[0]=e[_],o[1]=e[_+1],o[2]=e[_+2],a[0]=e[y],a[1]=e[y+1],a[2]=e[y+2],u[0]=e[b],u[1]=e[b+1],u[2]=e[b+2],q.decompressPosition(o,i,h),q.decompressPosition(a,i,l),q.decompressPosition(u,i,c)):(h[0]=e[_],h[1]=e[_+1],h[2]=e[_+2],l[0]=e[y],l[1]=e[y+1],l[2]=e[y+2],c[0]=e[b],c[1]=e[b+1],c[2]=e[b+2]),q.subVec3(c,l,p),q.subVec3(h,l,d),q.cross3Vec3(p,d,f),q.normalizeVec3(f,m);var x=r[n]||(r[n]={normal:q.vec3()});x.normal[0]=m[0],x.normal[1]=m[1],x.normal[2]=m[2],n++}}(g.length,_);for(var b,x,P,T,w,M,I,C,D,A,k=[],E=Math.cos(q.DEGTORAD*y),F={},R=!1,S=0,O=g.length;S<O;S+=3)for(var B=S/3,L=0;L<3;L++)b=s[S+L],x=s[S+(L+1)%3],void 0===F[w=(P=Math.min(b,x))+","+(T=Math.max(b,x))]?F[w]={index1:P,index2:T,face1:B,face2:void 0}:F[w].face2=B;for(w in F)void 0!==(M=F[w]).face2&&(I=r[M.face1].normal,C=r[M.face2].normal,q.dotVec3(I,C)>E)||(D=i[M.index1],A=i[M.index2],(!R&&D>65535||A>65535)&&(R=!0),k.push(D),k.push(A));return R?new Uint32Array(k):new Uint16Array(k)}}();var $=function(){function e(){w(this,e),this._head=[],this._headLength=0,this._tail=[],this._index=0,this._length=0}return I(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=[],i=e[0].charCodeAt(0),s=i+e[1],r=i;r<s;++r)t.push(r);return String.fromCharCode.apply(null,t)})).join("");function ie(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 se=function(){for(var e={},t=window.location.search.substring(1).split("&"),i=0;i<t.length;i++){var s=t[i].split("=");if(void 0===e[s[0]])e[s[0]]=decodeURIComponent(s[1]);else if("string"==typeof e[s[0]]){var r=[e[s[0]],decodeURIComponent(s[1])];e[s[0]]=r}else e[s[0]].push(decodeURIComponent(s[1]))}return e}();var re={xmlToJson:function e(t,i){if(t.nodeType===t.TEXT_NODE){var s=t.nodeValue;if(null===s.match(/^\s+$/))return s}else if(t.nodeType===t.ELEMENT_NODE||t.nodeType===t.DOCUMENT_NODE){var r={type:t.nodeName,children:[]};if(t.nodeType===t.ELEMENT_NODE)for(var n=0;n<t.attributes.length;n++){var o=t.attributes[n];r[i[o.nodeName]||o.nodeName]=o.nodeValue}for(var a=0;a<t.childNodes.length;a++){(n=e(t.childNodes[a],i))&&r.children.push(n)}return r}},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 ie(t[0],2)+[1,4,7,10,13].map((function(e){return ie((t[e]<<16)+(t[e+1]<<8)+t[e+2])})).join("")},findNodeOfType:function(e,t){var i=[];return function e(s){s.type===t&&i.push(s),(s.children||[]).forEach((function(t){e(t)}))}(e),i},timeout:function(e){return new Promise((function(t,i){setTimeout(t,e)}))},httpRequest:function(e){return new Promise((function(t,i){var s=new XMLHttpRequest;s.open(e.method||"GET",e.url,!0),s.onload=function(r){console.log(e.url,s.readyState,s.status),4===s.readyState&&(200===s.status?t(s.responseXML):i(s.statusText))},s.send(null)}))},loadJSON:function(e,t,i){var s=function(e){};t=t||s,i=i||s;var r=new XMLHttpRequest;r.overrideMimeType("application/json"),r.open("GET",e,!0),r.addEventListener("load",(function(e){var s=e.target.response;if(200===this.status){var r;try{r=JSON.parse(s)}catch(e){i("utils.loadJSON(): Failed to parse JSON response - ".concat(e))}t(r)}else if(0===this.status){console.warn("loadFile: HTTP Status 0 received.");try{t(JSON.parse(s))}catch(e){i("utils.loadJSON(): Failed to parse JSON response - ".concat(e))}}else i(e)}),!1),r.addEventListener("error",(function(e){i(e)}),!1),r.send(null)},loadArraybuffer:function(e,t,i){var s=function(e){};t=t||s,i=i||s;var r=e.match(/^data:(.*?)(;base64)?,(.*)$/);if(r){var n=!!r[2],o=r[3];o=window.decodeURIComponent(o),n&&(o=window.atob(o));try{for(var a=new ArrayBuffer(o.length),u=new Uint8Array(a),h=0;h<o.length;h++)u[h]=o.charCodeAt(h);window.setTimeout((function(){t(a)}),0)}catch(e){window.setTimeout((function(){i(e)}),0)}}else{var l=new XMLHttpRequest;l.open("GET",e,!0),l.responseType="arraybuffer",l.onreadystatechange=function(){4===l.readyState&&(200===l.status?t(l.response):i("loadArrayBuffer error : "+l.response))},l.send(null)}},queryString:se,isArray:function(e){return e&&!e.propertyIsEnumerable("length")&&"object"===T(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 re.isString(e)||re.isNumeric(e)},isSameComponent:function(e,t){return!(!e||!t)&&(re.isNumeric(e)||re.isString(e)?"".concat(e):e.id)===(re.isNumeric(t)||re.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 re.apply(e,{})},apply:function(e,t){for(var i in e)e.hasOwnProperty(i)&&(t[i]=e[i]);return t},apply2:function(e,t){for(var i in e)e.hasOwnProperty(i)&&void 0!==e[i]&&null!==e[i]&&(t[i]=e[i]);return t},applyIf:function(e,t){for(var i in e)e.hasOwnProperty(i)&&(void 0!==t[i]&&null!==t[i]||(t[i]=e[i]));return t},isEmptyObject:function(e){for(var t in e)if(e.hasOwnProperty(t))return!1;return!0},inQuotes:function(e){return re.isNumeric(e)?"".concat(e):"'".concat(e,"'")},concat:function(e,t){var i=new e.constructor(e.length+t.length);return i.set(e),i.set(t,e.length),i},flattenParentChildHierarchy:function(e){var t=[];return function e(i){i.id=i.uuid,delete i.oid,t.push(i);var s=i.children;if(s)for(var r=0,n=s.length;r<n;r++){s[r].parent=i.id,e(s[r])}i.children=[]}(e),t}},ne={},oe=new G,ae=new $,ue={sceneId:null,time:null,startTime:null,prevTime:null,deltaTime:null},he=[],le=0,ce=0;var pe=new function(){this.version="1.0.0",this.scenes={},this._superTypes={},this._addScene=function(e){if(e.id){if(pe.scenes[e.id])return void console.error("[ERROR] Scene ".concat(re.inQuotes(e.id)," already exists"))}else e.id=oe.addItem({});pe.scenes[e.id]=e;var t=e.ticksPerOcclusionTest,i=e.ticksPerRender;ne[e.id]={ticksPerOcclusionTest:t,ticksPerRender:i,renderCountdown:i},ee.components.scenes++,e.once("destroyed",(function(){oe.removeItem(e.id),delete pe.scenes[e.id],delete ne[e.id],ee.components.scenes--}))},this.clear=function(){var e;for(var t in pe.scenes)pe.scenes.hasOwnProperty(t)&&(e=pe.scenes[t],"default.scene"===t?e.clear():(e.destroy(),delete pe.scenes[e.id]))},this.scheduleTask=function(e,t){ae.push(e),ae.push(t)},this.runTasks=function(){for(var e,t,i=arguments.length>0&&void 0!==arguments[0]?arguments[0]:-1,s=(new Date).getTime(),r=0;ae.length>0&&(i<0||s<i);)e=ae.shift(),(t=ae.shift())?e.call(t):e(),s=(new Date).getTime(),r++;return r},this.getNumTasks=function(){return ae.length}},de=function e(){var t=Date.now();if(le>0){var i=1e3/(t-le);ce+=i,he.push(i),he.length>=30&&(ce-=he.shift()),ee.frame.fps=Math.round(ce/he.length)}!function(e){var t=pe.runTasks(e+10),i=pe.getNumTasks();ee.frame.tasksRun=t,ee.frame.tasksScheduled=i,ee.frame.tasksBudget=10}(t),function(e){for(var t in ue.time=e,pe.scenes)if(pe.scenes.hasOwnProperty(t)){var i=pe.scenes[t];ue.sceneId=t,ue.startTime=i.startTime,ue.deltaTime=null!=ue.prevTime?ue.time-ue.prevTime:0,i.fire("tick",ue,!0)}ue.prevTime=e}(t),function(){var e,t,i,s,r,n=pe.scenes,o=!1;for(r in n)n.hasOwnProperty(r)&&(e=n[r],(t=ne[r])||(t=ne[r]={}),i=e.ticksPerOcclusionTest,t.ticksPerOcclusionTest!==i&&(t.ticksPerOcclusionTest=i,t.renderCountdown=i),--e.occlusionTestCountdown<=0&&(e.doOcclusionTest(),e.occlusionTestCountdown=i),s=e.ticksPerRender,t.ticksPerRender!==s&&(t.ticksPerRender=s,t.renderCountdown=s),0==--t.renderCountdown&&(e.render(o),t.renderCountdown=s))}(),le=t,void 0!==window.requestPostAnimationFrame?window.requestPostAnimationFrame(e):requestAnimationFrame(e)};void 0!==window.requestPostAnimationFrame?window.requestPostAnimationFrame(de):requestAnimationFrame(de);var fe=function(){function e(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:null,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(w(this,e),this.scene=null,"Scene"===this.type)this.scene=this,this.viewer=i.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=!!i.dontClear,this._renderer=this.scene._renderer,this.meta=i.meta||{},this.id=i.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 I(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,i){this._events||(this._events={}),this._eventSubs||(this._eventSubs={},this._eventSubsNum={}),!0!==i&&(this._events[e]=t||!0);var s,r=this._eventSubs[e];if(r)for(var n in r)r.hasOwnProperty(n)&&(s=r[n],this._eventCallDepth++,this._eventCallDepth<300?s.callback.call(s.scope,t):this.error("fire: potential stack overflow from recursive event '"+e+"' - dropping this event"),this._eventCallDepth--)}},{key:"on",value:function(e,t,i){this._events||(this._events={}),this._subIdMap||(this._subIdMap=new G),this._subIdEvents||(this._subIdEvents={}),this._eventSubs||(this._eventSubs={}),this._eventSubsNum||(this._eventSubsNum={});var s=this._eventSubs[e];s?this._eventSubsNum[e]++:(s={},this._eventSubs[e]=s,this._eventSubsNum[e]=1);var r=this._subIdMap.addItem();s[r]={callback:t,scope:i||this},this._subIdEvents[r]=e;var n=this._events[e];return void 0!==n&&t.call(i||this,n),r}},{key:"off",value:function(e){if(null!=e&&this._subIdEvents){var t=this._subIdEvents[e];if(t){delete this._subIdEvents[e];var i=this._eventSubs[t];i&&(delete i[e],this._eventSubsNum[t]--),this._subIdMap.removeItem(e)}}}},{key:"once",value:function(e,t,i){var s=this,r=this.on(e,(function(e){s.off(r),t.call(i||this,e)}),i)}},{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+" "+re.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 i=e.component,s=e.sceneDefault,r=e.sceneSingleton,n=e.type,o=e.on,a=!1!==e.recompiles;if(i&&(re.isNumeric(i)||re.isString(i))){var u=i;if(!(i=this.scene.components[u]))return void this.error("Component not found: "+re.inQuotes(u))}if(!i)if(!0===r){var h=this.scene.types[n];for(var l in h)if(h.hasOwnProperty){i=h[l];break}if(!i)return this.error("Scene has no default component for '"+t+"'"),null}else if(!0===s&&!(i=this.scene[t]))return this.error("Scene has no default component for '"+t+"'"),null;if(i){if(i.scene.id!==this.scene.id)return void this.error("Not in same scene: "+i.type+" "+re.inQuotes(i.id));if(n&&!i.isType(n))return void this.error("Expected a "+n+" type or subtype: "+i.type+" "+re.inQuotes(i.id))}this._attachments||(this._attachments={});var c,p,d,f=this._attached[t];if(f){if(i&&f.id===i.id)return;var m=this._attachments[f.id];for(p=0,d=(c=m.subs).length;p<d;p++)f.off(c[p]);delete this._attached[t],delete this._attachments[f.id];var v=m.params.onDetached;v&&(re.isFunction(v)?v(f):v.scope?v.callback.call(v.scope,f):v.callback(f)),m.managingLifecycle&&f.destroy()}if(i){var g={params:e,component:i,subs:[],managingLifecycle:!1};g.subs.push(i.once("destroyed",(function(){g.params.component=null,this._attach(g.params)}),this)),a&&g.subs.push(i.on("dirty",(function(){this.fire("dirty",this)}),this)),this._attached[t]=i,this._attachments[i.id]=g;var _,y,b,x,P=e.onAttached;if(P&&(re.isFunction(P)?P(i):P.scope?P.callback.call(P.scope,i):P.callback(i)),o)for(_ in o)if(o.hasOwnProperty(_)){if(y=o[_],re.isFunction(y)?(b=y,x=null):(b=y.callback,x=y.scope),!b)continue;g.subs.push(i.on(_,b,x))}}return a&&this.fire("dirty",this),this.fire(t,i),i}this.error("Component 'name' expected")}},{key:"_checkComponent",value:function(e,t){if(!t.isComponent){if(!re.isID(t))return void this.error("Expected a Component or ID");var i=t;if(!(t=this.scene.components[i]))return void this.error("Component not found: "+i)}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(!re.isID(t))return void this.error("Expected a Component or ID");var i=t;if(!(t=this.scene.components[i]))return void this.error("Component not found: "+i)}if(t.scene.id===this.scene.id){for(var s=0,r=e.length;s<r;s++)if(e[s]===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():pe.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,i,s,r,n;if(this.fire("destroyed",this.destroyed=!0),this._attachments)for(e in this._attachments)if(this._attachments.hasOwnProperty(e)){for(i=(t=this._attachments[e]).component,r=0,n=(s=t.subs).length;r<n;r++)i.off(s[r]);t.managingLifecycle&&i.destroy()}if(this._ownedComponents)for(e in this._ownedComponents)this._ownedComponents.hasOwnProperty(e)&&((i=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}(),me=1,ve=4,ge=8,_e=16,ye=32,be=256,xe=512,Pe=1024,Te=2048,we=new Float32Array([0,0,0]),Me=new Uint16Array([0,0,0]),Ie=function(){function e(t,i,s,r,n,o){w(this,e),this._isObject=i,this.scene=t.scene,this.model=t,this.meshes=r,this._numTriangles=0;for(var a=0,u=this.meshes.length;a<u;a++){var h=this.meshes[a];h.parent=this,this._numTriangles+=h.numTriangles}this.id=s,this.originalSystemId=q.unglobalizeObjectId(t.id,s),this._flags=n,this._aabb=o,this._offsetAABB=q.AABB3(o),this._offset=q.vec3(),this._colorizeUpdated=!1,this._opacityUpdated=!1,this._culled=!1,this._culledVFC=!1,this._culledLOD=!1,this._isObject&&t.scene._registerObject(this)}return I(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:"numTriangles",get:function(){return this._numTriangles}},{key:"visible",get:function(){return this._getFlag(me)},set:function(e){if(!!(this._flags&me)!==e){this._flags=e?this._flags|me:this._flags&~me;for(var t=0,i=this.meshes.length;t<i;t++)this.meshes[t]._setVisible(this._flags);this._isObject&&this.model.scene._objectVisibilityUpdated(this),this.model.glRedraw()}}},{key:"highlighted",get:function(){return this._getFlag(xe)},set:function(e){if(!!(this._flags&xe)!==e){this._flags=e?this._flags|xe:this._flags&~xe;for(var t=0,i=this.meshes.length;t<i;t++)this.meshes[t]._setHighlighted(this._flags);this._isObject&&this.model.scene._objectHighlightedUpdated(this),this.model.glRedraw()}}},{key:"xrayed",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,i=this.meshes.length;t<i;t++)this.meshes[t]._setXRayed(this._flags);this._isObject&&this.model.scene._objectXRayedUpdated(this),this.model.glRedraw()}}},{key:"selected",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,i=this.meshes.length;t<i;t++)this.meshes[t]._setSelected(this._flags);this._isObject&&this.model.scene._objectSelectedUpdated(this),this.model.glRedraw()}}},{key:"edges",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,i=this.meshes.length;t<i;t++)this.meshes[t]._setEdges(this._flags);this.model.glRedraw()}}},{key:"culledVFC",get:function(){return!!this._culledVFC},set:function(e){this._culledVFC=e,this.internalSetCulled()}},{key:"culledLOD",get:function(){return!!this._culledLOD},set:function(e){this._culledLOD=e,this.internalSetCulled()}},{key:"culled",get:function(){return!!this._culled},set:function(e){this._culled=e,this.internalSetCulled()}},{key:"internalSetCulled",value:function(){var e=!!this._culled||!!this._culledLOD||!!this._culledVFC;if(!!(this._flags&ve)!==e){this._flags=e?this._flags|ve:this._flags&~ve;for(var t=0,i=this.meshes.length;t<i;t++)this.meshes[t]._setCulled(this._flags);this.model.glRedraw()}}},{key:"clippable",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,i=this.meshes.length;t<i;t++)this.meshes[t]._setClippable(this._flags);this.model.glRedraw()}}},{key:"collidable",get:function(){return this._getFlag(ye)},set:function(e){if(!!(this._flags&ye)!==e){this._flags=e?this._flags|ye:this._flags&~ye;for(var t=0,i=this.meshes.length;t<i;t++)this.meshes[t]._setCollidable(this._flags)}}},{key:"pickable",get:function(){return this._getFlag(ge)},set:function(e){if(!!(this._flags&ge)!==e){this._flags=e?this._flags|ge:this._flags&~ge;for(var t=0,i=this.meshes.length;t<i;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 we[0]=e[0]/255,we[1]=e[1]/255,we[2]=e[2]/255,we},set:function(e){if(e){Me[0]=Math.floor(255*e[0]),Me[1]=Math.floor(255*e[1]),Me[2]=Math.floor(255*e[2]);for(var t=0,i=this.meshes.length;t<i;t++)this.meshes[t]._setColorize(Me)}else for(var s=0,r=this.meshes.length;s<r;s++)this.meshes[s]._setColorize(null);if(this._isObject){var n=!!e;this.scene._objectColorizeUpdated(this,n),this._colorizeUpdated=n}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,i=this.meshes[0]._colorize[3],s=255;if(t){if(e<0?e=0:e>1&&(e=1),i===(s=Math.floor(255*e)))return}else if(i===(s=255))return;for(var r=0,n=this.meshes.length;r<n;r++)this.meshes[r]._setOpacity(s,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,i=this.meshes.length;t<i;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:"castsShadow",get:function(){return!1},set:function(e){}},{key:"receivesShadow",get:function(){return!1},set:function(e){}},{key:"saoEnabled",get:function(){return this.model.saoEnabled}},{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,i=this.meshes.length;t<i;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,i=this.meshes.length;t<i;t++)this.meshes[t]._destroy();e._aabbDirty=!0}}]),e}(),Ce=q.vec3(),De=function(){var e=new Float64Array(16),t=new Float64Array(4),i=new Float64Array(4);return function(s,r,n){return n=n||e,t[0]=r[0],t[1]=r[1],t[2]=r[2],t[3]=1,q.transformVec4(s,t,i),q.setMat4Translation(s,i,n),n.slice()}}();function Ae(e,t,i){var s=Float32Array.from([e[0]])[0],r=e[0]-s,n=Float32Array.from([e[1]])[0],o=e[1]-n,a=Float32Array.from([e[2]])[0],u=e[2]-a;t[0]=s,t[1]=n,t[2]=a,i[0]=r,i[1]=o,i[2]=u}function ke(e,t,i){var s=arguments.length>3&&void 0!==arguments[3]?arguments[3]:1e3,r=q.getPositionsCenter(e,Ce),n=Math.round(r[0]/s)*s,o=Math.round(r[1]/s)*s,a=Math.round(r[2]/s)*s;i[0]=n,i[1]=o,i[2]=a;var u=0!==i[0]||0!==i[1]||0!==i[2];if(u)for(var h=0,l=e.length;h<l;h+=3)t[h+0]=e[h+0]-n,t[h+1]=e[h+1]-o,t[h+2]=e[h+2]-a;return u}function Ee(e,t,i,s){var r=q.dotVec3(t,i)+e,n=q.normalizeVec3(t,Ce);return q.mulVec3Scalar(n,-r,s),s}var Fe=q.vec4(),Re=q.vec4(),Se=function(e){g(i,fe);var t=y(i);function i(e,s){var r;return w(this,i),(r=t.call(this,e,s))._entity=null,r._visible=null,r._worldPos=q.vec3(),r._origin=q.vec3(),r._rtcPos=q.vec3(),r._viewPos=q.vec3(),r._canvasPos=q.vec2(),r._occludable=!1,r._onCameraViewMatrix=r.scene.camera.on("matrix",(function(){r._viewPosDirty=!0,r._needUpdate()})),r._onCameraProjMatrix=r.scene.camera.on("projMatrix",(function(){r._canvasPosDirty=!0,r._needUpdate()})),r._onEntityDestroyed=null,r._onEntityModelDestroyed=null,r._renderer.addMarker(x(r)),r.entity=s.entity,r.worldPos=s.worldPos,r.occludable=s.occludable,r}return I(i,[{key:"_update",value:function(){if(this._viewPosDirty&&(q.transformPoint3(this.scene.camera.viewMatrix,this._worldPos,this._viewPos),this._viewPosDirty=!1,this._canvasPosDirty=!0,this.fire("viewPos",this._viewPos)),this._canvasPosDirty){Fe.set(this._viewPos),Fe[3]=1,q.transformPoint4(this.scene.camera.projMatrix,Fe,Re);var e=this.scene.canvas.boundary;this._canvasPos[0]=Math.floor((1+Re[0]/Re[3])*e[2]/2),this._canvasPos[1]=Math.floor((1-Re[1]/Re[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 Ie?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]),Ae(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),m(P(i.prototype),"destroy",this).call(this)}}]),i}(),Oe=function(){function e(t){var i=this,s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};w(this,e),this._color=s.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=s.thickness||1,this._thicknessClickable=s.thicknessClickable||6;var r=this._wire,n=r.style;n.border="solid "+this._thickness+"px "+this._color,n.position="absolute",n["z-index"]=void 0===s.zIndex?"2000001":s.zIndex,n.width="0px",n.height="0px",n.visibility="visible",n.top="0px",n.left="0px",n["-webkit-transform-origin"]="0 0",n["-moz-transform-origin"]="0 0",n["-ms-transform-origin"]="0 0",n["-o-transform-origin"]="0 0",n["transform-origin"]="0 0",n["-webkit-transform"]="rotate(0deg)",n["-moz-transform"]="rotate(0deg)",n["-ms-transform"]="rotate(0deg)",n["-o-transform"]="rotate(0deg)",n.transform="rotate(0deg)",n.opacity=1,n["pointer-events"]="none",s.onContextMenu,t.appendChild(r);var o=this._wireClickable,a=o.style;a.border="solid "+this._thicknessClickable+"px "+this._color,a.position="absolute",a["z-index"]=void 0===s.zIndex?"2000002":s.zIndex+1,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=0,a["pointer-events"]="all",s.onContextMenu,t.appendChild(o),s.onMouseOver&&o.addEventListener("mouseover",(function(e){s.onMouseOver(e,i)})),s.onMouseLeave&&o.addEventListener("mouseleave",(function(e){s.onMouseLeave(e,i)})),s.onContextMenu&&o.addEventListener("contextmenu",(function(e){s.onContextMenu(e,i),e.preventDefault()})),this._x1=0,this._y1=0,this._x2=0,this._y2=0,this._update()}return I(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,i=this._wire.style;i.width=Math.round(e)+"px",i.left=Math.round(this._x1)+"px",i.top=Math.round(this._y1)+"px",i["-webkit-transform"]="rotate("+t+"deg)",i["-moz-transform"]="rotate("+t+"deg)",i["-ms-transform"]="rotate("+t+"deg)",i["-o-transform"]="rotate("+t+"deg)",i.transform="rotate("+t+"deg)";var s=this._wireClickable.style;s.width=Math.round(e)+"px",s.left=Math.round(this._x1)+"px",s.top=Math.round(this._y1)+"px",s["-webkit-transform"]="rotate("+t+"deg)",s["-moz-transform"]="rotate("+t+"deg)",s["-ms-transform"]="rotate("+t+"deg)",s["-o-transform"]="rotate("+t+"deg)",s.transform="rotate("+t+"deg)"}},{key:"setStartAndEnd",value:function(e,t,i,s){this._x1=e,this._y1=t,this._x2=i,this._y2=s,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.removeChild(this._wire),this._wireClickable.parentElement.removeChild(this._wireClickable)}}]),e}(),Be=function(){function e(t){var i=this,s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};w(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 r=this._dot,n=r.style;n["border-radius"]="25px",n.border="solid 2px white",n.background="lightgreen",n.position="absolute",n["z-index"]=void 0===s.zIndex?"40000005":s.zIndex,n.width="8px",n.height="8px",n.visibility=!1!==s.visible?"visible":"hidden",n.top="0px",n.left="0px",n["box-shadow"]="0 2px 5px 0 #182A3D;",n.opacity=1,n["pointer-events"]="none",s.onContextMenu,t.appendChild(r);var o=this._dotClickable,a=o.style;a["border-radius"]="35px",a.border="solid 10px white",a.position="absolute",a["z-index"]=void 0===s.zIndex?"40000007":s.zIndex+1,a.width="8px",a.height="8px",a.visibility="visible",a.top="0px",a.left="0px",a.opacity=0,a["pointer-events"]="none",s.onContextMenu,t.appendChild(o),s.onMouseOver&&o.addEventListener("mouseover",(function(e){s.onMouseOver(e,i)})),s.onMouseLeave&&o.addEventListener("mouseleave",(function(e){s.onMouseLeave(e,i)})),s.onContextMenu&&o.addEventListener("contextmenu",(function(e){s.onContextMenu(e,i),e.preventDefault()})),this.setPos(s.x||0,s.y||0),this.setFillColor(s.fillColor),this.setBorderColor(s.borderColor)}return I(e,[{key:"setPos",value:function(e,t){this._x=e,this._y=t;var i=this._dot.style;i.left=Math.round(e)-4+"px",i.top=Math.round(t)-4+"px";var s=this._dotClickable.style;s.left=Math.round(e)-9+"px",s.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.removeChild(this._dot),this._dotClickable.parentElement.removeChild(this._dotClickable)}}]),e}(),Le=function(){function e(t){var i=this,s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};w(this,e),this._highlightClass="viewer-ruler-label-highlighted",this._prefix=s.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 r=this._label,n=r.style;n["border-radius"]="5px",n.color="white",n.padding="4px",n.border="solid 1px",n.background="lightgreen",n.position="absolute",n["z-index"]=void 0===s.zIndex?"5000005":s.zIndex,n.width="auto",n.height="auto",n.visibility="visible",n.top="0px",n.left="0px",n["pointer-events"]="all",n.opacity=1,s.onContextMenu,r.innerText="",t.appendChild(r),this.setPos(s.x||0,s.y||0),this.setFillColor(s.fillColor),this.setBorderColor(s.fillColor),this.setText(s.text),s.onMouseOver&&r.addEventListener("mouseover",(function(e){s.onMouseOver(e,i),e.preventDefault()})),s.onMouseLeave&&r.addEventListener("mouseleave",(function(e){s.onMouseLeave(e,i),e.preventDefault()})),s.onContextMenu&&r.addEventListener("contextmenu",(function(e){s.onContextMenu(e,i),e.preventDefault()}))}return I(e,[{key:"setPos",value:function(e,t){this._x=e,this._y=t;var i=this._label.style;i.left=Math.round(e)-20+"px",i.top=Math.round(t)-12+"px"}},{key:"setPosOnWire",value:function(e,t,i,s){var r=e+.5*(i-e),n=t+.5*(s-t),o=this._label.style;o.left=Math.round(r)-20+"px",o.top=Math.round(n)-12+"px"}},{key:"setPosBetweenWires",value:function(e,t,i,s,r,n){var o=(e+i+r)/3,a=(t+s+n)/3,u=this._label.style;u.left=Math.round(o)-20+"px",u.top=Math.round(a)-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.removeChild(this._label)}}]),e}(),Ne=q.vec3(),je=q.vec3(),Ge=function(e){g(i,fe);var t=y(i);function i(e){var s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(w(this,i),(s=t.call(this,e.viewer.scene,r)).plugin=e,s._container=r.container,!s._container)throw"config missing: container";s._color=r.color||e.defaultColor;var n=s.plugin.viewer.scene;s._originMarker=new Se(n,r.origin),s._cornerMarker=new Se(n,r.corner),s._targetMarker=new Se(n,r.target),s._originWorld=q.vec3(),s._cornerWorld=q.vec3(),s._targetWorld=q.vec3(),s._wp=new Float64Array(12),s._vp=new Float64Array(12),s._pp=new Float64Array(12),s._cp=new Int16Array(6);var o=r.onMouseOver?function(e){r.onMouseOver(e,x(s))}:null,a=r.onMouseLeave?function(e){r.onMouseLeave(e,x(s))}:null,u=r.onContextMenu?function(e){r.onContextMenu(e,x(s))}:null;return s._originDot=new Be(s._container,{fillColor:s._color,zIndex:void 0!==e.zIndex?e.zIndex+2:void 0,onMouseOver:o,onMouseLeave:a,onContextMenu:u}),s._cornerDot=new Be(s._container,{fillColor:s._color,zIndex:void 0!==e.zIndex?e.zIndex+2:void 0,onMouseOver:o,onMouseLeave:a,onContextMenu:u}),s._targetDot=new Be(s._container,{fillColor:s._color,zIndex:void 0!==e.zIndex?e.zIndex+2:void 0,onMouseOver:o,onMouseLeave:a,onContextMenu:u}),s._originWire=new Oe(s._container,{color:s._color||"blue",thickness:1,zIndex:e.zIndex,onMouseOver:o,onMouseLeave:a,onContextMenu:u}),s._targetWire=new Oe(s._container,{color:s._color||"red",thickness:1,zIndex:void 0!==e.zIndex?e.zIndex+1:void 0,onMouseOver:o,onMouseLeave:a,onContextMenu:u}),s._angleLabel=new Le(s._container,{fillColor:s._color||"#00BBFF",prefix:"",text:"",zIndex:e.zIndex+2,onMouseOver:o,onMouseLeave:a,onContextMenu:u}),s._wpDirty=!1,s._vpDirty=!1,s._cpDirty=!1,s._visible=!1,s._originVisible=!1,s._cornerVisible=!1,s._targetVisible=!1,s._originWireVisible=!1,s._targetWireVisible=!1,s._angleVisible=!1,s._labelsVisible=!1,s._clickable=!1,s._originMarker.on("worldPos",(function(e){s._originWorld.set(e||[0,0,0]),s._wpDirty=!0,s._needUpdate(0)})),s._cornerMarker.on("worldPos",(function(e){s._cornerWorld.set(e||[0,0,0]),s._wpDirty=!0,s._needUpdate(0)})),s._targetMarker.on("worldPos",(function(e){s._targetWorld.set(e||[0,0,0]),s._wpDirty=!0,s._needUpdate(0)})),s._onViewMatrix=n.camera.on("viewMatrix",(function(){s._vpDirty=!0,s._needUpdate(0)})),s._onProjMatrix=n.camera.on("projMatrix",(function(){s._cpDirty=!0,s._needUpdate()})),s._onCanvasBoundary=n.canvas.on("boundary",(function(){s._cpDirty=!0,s._needUpdate(0)})),s.approximate=r.approximate,s.visible=r.visible,s.originVisible=r.originVisible,s.cornerVisible=r.cornerVisible,s.targetVisible=r.targetVisible,s.originWireVisible=r.originWireVisible,s.targetWireVisible=r.targetWireVisible,s.angleVisible=r.angleVisible,s.labelsVisible=r.labelsVisible,s}return I(i,[{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&&(q.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,i=this._originMarker.viewPos[2],s=this._cornerMarker.viewPos[2],r=this._targetMarker.viewPos[2];if(i>t||s>t||r>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);q.transformPositions4(e.camera.project.matrix,this._vp,this._pp);for(var n=this._pp,o=this._cp,a=e.canvas.canvas.getBoundingClientRect(),u=this._container.getBoundingClientRect(),h=a.top-u.top,l=a.left-u.left,c=e.canvas.boundary,p=c[2],d=c[3],f=0,m=0,v=n.length;m<v;m+=4)o[f]=l+Math.floor((1+n[m+0]/n[m+3])*p/2),o[f+1]=h+Math.floor((1-n[m+1]/n[m+3])*d/2),f+=2;if(this._originDot.setPos(o[0],o[1]),this._cornerDot.setPos(o[2],o[3]),this._targetDot.setPos(o[4],o[5]),this._originWire.setStartAndEnd(o[0],o[1],o[2],o[3]),this._targetWire.setStartAndEnd(o[2],o[3],o[4],o[5]),this._angleLabel.setPosBetweenWires(o[0],o[1],o[2],o[3],o[4],o[5]),q.subVec3(this._originWorld,this._cornerWorld,Ne),q.subVec3(this._targetWorld,this._cornerWorld,je),!(0===Ne[0]&&0===Ne[1]&&0===Ne[2]||0===je[0]&&0===je[1]&&0===je[2])){var g=this._approximate?" ~ ":" = ";q.normalizeVec3(Ne),q.normalizeVec3(je);var _=Math.abs(q.angleVec3(Ne,je));this._angle=_/q.DEGTORAD,this._angleLabel.setText(g+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(),m(P(i.prototype),"destroy",this).call(this)}}]),i}(),He=function(e){g(i,fe);var t=y(i);function i(e){var s;return w(this,i),(s=t.call(this,e.viewer.scene)).plugin=e,s._active=!1,s._state=0,s._currentAngleMeasurement=null,s._onMouseHoverSurface=null,s._onHoverNothing=null,s._onMouseHoverOff=null,s._onPickedNothing=null,s._onPickedSurface=null,s._onInputMouseDown=null,s._onInputMouseUp=null,s._onCanvasTouchStart=null,s._onCanvasTouchEnd=null,s}return I(i,[{key:"active",get:function(){return this._active}},{key:"activate",value:function(){var e=this;if(!this._active){var t,i,s=this.plugin,r=this.scene,n=s.viewer.cameraControl,o=r.canvas.canvas,a=r.input,u=r.pickSurfacePrecisionEnabled,h=!1,l=null,c=q.vec3(),p=q.vec2(),d=q.vec2(),f=q.vec2();q.vec3(),this._onMouseHoverSurface=n.on("hoverSurface",(function(t){if(h=!0,l=t.entity,c.set(t.worldPos),p.set(t.canvasPos),e._currentAngleMeasurement)switch(e._state){case 1:e._currentAngleMeasurement.originWireVisible=!0,e._currentAngleMeasurement.targetWireVisible=!1,e._currentAngleMeasurement.cornerVisible=!0,e._currentAngleMeasurement.angleVisible=!1,e._currentAngleMeasurement.corner.entity=t.entity,e._currentAngleMeasurement.corner.worldPos=t.worldPos,o.style.cursor="pointer";break;case 2:e._currentAngleMeasurement.targetWireVisible=!0,e._currentAngleMeasurement.targetVisible=!0,e._currentAngleMeasurement.angleVisible=!0,e._currentAngleMeasurement.target.entity=t.entity,e._currentAngleMeasurement.target.worldPos=t.worldPos,o.style.cursor="pointer"}})),this._onInputMouseDown=a.on("mousedown",(function(e){t=e[0],i=e[1]})),this._onInputMouseUp=a.on("mouseup",(function(s){if(!(s[0]>t+5||s[0]<t-5||s[1]>i+5||s[1]<i-5))switch(e._state){case 0:if(h){if(u){var n=r.pick({canvasPos:p,pickSurface:!0,pickSurfacePrecision:u});n&&n.worldPos&&worldPos.set(n.worldPos)}e._currentAngleMeasurement=e.plugin.createMeasurement({id:q.createUUID(),origin:{entity:l,worldPos:c},corner:{entity:l,worldPos:c},target:{entity:l,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:if(h){if(u){var o=r.pick({canvasPos:p,pickSurface:!0,pickSurfacePrecision:!0});o&&o.worldPos&&(e._currentAngleMeasurement.corner.worldPos=o.worldPos)}e._currentAngleMeasurement.targetWireVisible=!1,e._currentAngleMeasurement.targetVisible=!0,e._currentAngleMeasurement.angleVisible=!0,e._state=2}else e._currentAngleMeasurement&&(e._currentAngleMeasurement.destroy(),e._currentAngleMeasurement=null,e._state=0,e.fire("measurementCancel",e._currentAngleMeasurement));break;case 2:if(h){if(u){var a=r.pick({canvasPos:p,pickSurface:!0,pickSurfacePrecision:!0});a&&a.worldPos&&(e._currentAngleMeasurement.target.worldPos=a.worldPos,e._currentAngleMeasurement.approximate=!1)}e._currentAngleMeasurement.targetVisible=!0,e._currentAngleMeasurement.angleVisible=!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))}})),this._onHoverNothing=n.on("hoverOff",(function(t){if(h=!1,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}o.style.cursor="default"}})),o.addEventListener("touchstart",this._onCanvasTouchStart=function(e){var t=e.touches,i=e.changedTouches;1===t.length&&1===i.length&&Ve(t[0],d)},{passive:!0}),o.addEventListener("touchend",this._onCanvasTouchEnd=function(t){var i=t.touches,s=t.changedTouches;if(0===i.length&&1===s.length){if(Ve(s[0],f),f[0]>d[0]+5||f[0]<d[0]-5||f[1]>d[1]+5||f[1]<d[1]-5)return;var n=r.pick({canvasPos:f,pickSurface:!0,pickSurfacePrecision:!1});if(n&&n.worldPos)switch(e._state){case 0:e._currentAngleMeasurement=e.plugin.createMeasurement({id:q.createUUID(),origin:{entity:n.entity,worldPos:n.worldPos},corner:{entity:n.entity,worldPos:n.worldPos},target:{entity:n.entity,worldPos:n.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=n.worldPos,e._currentAngleMeasurement.targetWireVisible=!1,e._currentAngleMeasurement.targetVisible=!0,e._currentAngleMeasurement.angleVisible=!0,e._state=2;break;case 2:e._currentAngleMeasurement.target.worldPos=n.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,i=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),i.removeEventListener("touchstart",this._onCanvasTouchStart),i.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(),m(P(i.prototype),"destroy",this).call(this)}}]),i}(),Ve=function(e,t){if(e){for(var i=e.target,s=0,r=0;i.offsetParent;)s+=i.offsetLeft,r+=i.offsetTop,i=i.offsetParent;t[0]=e.pageX-s,t[1]=e.pageY-r}else e=window.event,t[0]=e.x,t[1]=e.y;return t},Ue=function(e){g(i,X);var t=y(i);function i(e){var s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return w(this,i),(s=t.call(this,"AngleMeasurements",e))._container=r.container||document.body,s._control=new He(x(s)),s._measurements={},s.defaultColor=void 0!==r.defaultColor?r.defaultColor:"#00BBFF",s.defaultLabelsVisible=!1!==r.defaultLabelsVisible,s.zIndex=r.zIndex||1e4,s._onMouseOver=function(e,t){s.fire("mouseOver",{plugin:x(s),angleMeasurement:t,measurement:t,event:e})},s._onMouseLeave=function(e,t){s.fire("mouseLeave",{plugin:x(s),angleMeasurement:t,measurement:t,event:e})},s._onContextMenu=function(e,t){s.fire("contextMenu",{plugin:x(s),angleMeasurement:t,measurement:t,event:e})},s}return I(i,[{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 i=t.origin,s=t.corner,r=t.target,n=new Ge(this,{id:t.id,plugin:this,container:this._container,origin:{entity:i.entity,worldPos:i.worldPos},corner:{entity:s.entity,worldPos:s.worldPos},target:{entity:r.entity,worldPos:r.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[n.id]=n,n.on("destroyed",(function(){delete e._measurements[n.id]})),this.fire("measurementCreated",n),n}},{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,i=Object.entries(this.measurements);t<i.length;t++){var s=p(i[t],2);s[0];s[1].labelShown=e}}},{key:"clear",value:function(){for(var e=Object.keys(this._measurements),t=0,i=e.length;t<i;t++)this.destroyMeasurement(e[t])}},{key:"destroy",value:function(){this.clear(),m(P(i.prototype),"destroy",this).call(this)}}]),i}(),ze=function(e){g(i,Se);var t=y(i);function i(e,s){var r;if(w(this,i),(r=t.call(this,e,s)).plugin=s.plugin,r._container=s.container,!r._container)throw"config missing: container";if(!s.markerElement&&!s.markerHTML)throw"config missing: need either markerElement or markerHTML";if(!s.labelElement&&!s.labelHTML)throw"config missing: need either labelElement or labelHTML";return r._htmlDirty=!1,s.markerElement?(r._marker=s.markerElement,r._marker.addEventListener("click",r._onMouseClickedExternalMarker=function(){r.plugin.fire("markerClicked",x(r))}),r._marker.addEventListener("mouseenter",r._onMouseEnterExternalMarker=function(){r.plugin.fire("markerMouseEnter",x(r))}),r._marker.addEventListener("mouseleave",r._onMouseLeaveExternalMarker=function(){r.plugin.fire("markerMouseLeave",x(r))}),r._markerExternal=!0):(r._markerHTML=s.markerHTML,r._htmlDirty=!0,r._markerExternal=!1),s.labelElement?(r._label=s.labelElement,r._labelExternal=!0):(r._labelHTML=s.labelHTML,r._htmlDirty=!0,r._labelExternal=!1),r._markerShown=!!s.markerShown,r._labelShown=!!s.labelShown,r._values=s.values||{},r._layoutDirty=!0,r._visibilityDirty=!0,r._buildHTML(),r._onTick=r.scene.on("tick",(function(){r._htmlDirty&&(r._buildHTML(),r._htmlDirty=!1,r._layoutDirty=!0,r._visibilityDirty=!0),(r._layoutDirty||r._visibilityDirty)&&(r._markerShown||r._labelShown)&&(r._updatePosition(),r._layoutDirty=!1),r._visibilityDirty&&(r._marker.style.visibility=r.visible&&r._markerShown?"visible":"hidden",r._label.style.visibility=r.visible&&r._markerShown&&r._labelShown?"visible":"hidden",r._visibilityDirty=!1)})),r.on("canvasPos",(function(){r._layoutDirty=!0})),r.on("visible",(function(){r._visibilityDirty=!0})),r.setMarkerShown(!1!==s.markerShown),r.setLabelShown(s.labelShown),r.eye=s.eye?s.eye.slice():null,r.look=s.look?s.look.slice():null,r.up=s.up?s.up.slice():null,r.projection=s.projection,r}return I(i,[{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>";re.isArray(t)&&(t=t.join("")),t=this._renderTemplate(t);var i=document.createRange().createContextualFragment(t);this._marker=i.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)}))}if(!this._labelExternal){this._label&&(this._container.removeChild(this._label),this._label=null);var s=this._labelHTML||"<p></p>";re.isArray(s)&&(s=s.join("")),s=this._renderTemplate(s);var r=document.createRange().createContextualFragment(s);this._label=r.firstChild,this._container.appendChild(this._label),this._label.style.visibility=this._markerShown&&this._labelShown?"visible":"hidden"}}},{key:"_updatePosition",value:function(){var e=this.scene.canvas.boundary,t=e[0],i=e[1],s=this.canvasPos;this._marker.style.left=Math.floor(t+s[0])-12+"px",this._marker.style.top=Math.floor(i+s[1])-12+"px",this._marker.style["z-index"]=90005+Math.floor(this._viewPos[2])+1;this._label.style.left=20+Math.floor(t+s[0]+20)+"px",this._label.style.top=Math.floor(i+s[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 i=this._values[t];e=e.replace(new RegExp("{{"+t+"}}","g"),i)}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 i=e[t];this.setField(t,i)}}},{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),m(P(i.prototype),"destroy",this).call(this)}}]),i}(),We=q.vec3(),Xe=q.vec3(),Ye=q.vec3(),Ke=function(e){g(i,X);var t=y(i);function i(e,s){var r;return w(this,i),(r=t.call(this,"Annotations",e))._labelHTML=s.labelHTML||"<div></div>",r._markerHTML=s.markerHTML||"<div></div>",r._container=s.container||document.body,r._values=s.values||{},r.annotations={},r.surfaceOffset=s.surfaceOffset,r}return I(i,[{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,i,s=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 r=e.pickResult;if(r.worldPos&&r.worldNormal){var n=q.normalizeVec3(r.worldNormal,We),o=q.mulVec3Scalar(n,this._surfaceOffset,Xe);t=q.addVec3(r.worldPos,o,Ye),i=r.entity}else this.error("Param 'pickResult' does not have both worldPos and worldNormal")}else t=e.worldPos,i=e.entity;var a=null;e.markerElementId&&((a=document.getElementById(e.markerElementId))||this.error("Can't find DOM element for 'markerElementId' value '"+e.markerElementId+"' - defaulting to internally-generated empty DIV"));var u=null;e.labelElementId&&((u=document.getElementById(e.labelElementId))||this.error("Can't find DOM element for 'labelElementId' value '"+e.labelElementId+"' - defaulting to internally-generated empty DIV"));var h=new ze(this.viewer.scene,{id:e.id,plugin:this,entity:i,worldPos:t,container:this._container,markerElement:a,labelElement:u,markerHTML:e.markerHTML||this._markerHTML,labelHTML:e.labelHTML||this._labelHTML,occludable:e.occludable,values:re.apply(e.values,re.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[h.id]=h,h.on("destroyed",(function(){delete s.annotations[h.id],s.fire("annotationDestroyed",h.id)})),this.fire("annotationCreated",h.id),h}},{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,i=e.length;t<i;t++)this.destroyAnnotation(e[t])}},{key:"destroy",value:function(){this.clear(),m(P(i.prototype),"destroy",this).call(this)}}]),i}(),Je=function(e){g(i,fe);var t=y(i);function i(e){var s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return w(this,i),(s=t.call(this,e,r))._canvas=r.canvas,s._element=null,s._isCustom=!1,r.elementId&&(s._element=document.getElementById(r.elementId),s._element?s._adjustPosition():s.error("Can't find given Spinner HTML element: '"+r.elementId+"' - will automatically create default element")),s._element||s._createDefaultSpinner(),s.processes=0,s}return I(i,[{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,i=t.style;i.left=e.offsetLeft+.5*e.clientWidth-.5*t.clientWidth+"px",i.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 i=this._element;i&&(i.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)}}]),i}(),Ze={WEBGL:!1,SUPPORTED_EXTENSIONS:{}},Qe=document.createElement("canvas");if(Qe){var qe=Qe.getContext("webgl",{antialias:!0})||Qe.getContext("experimental-webgl",{antialias:!0});Ze.WEBGL=!!qe,Ze.WEBGL&&(Ze.ANTIALIAS=qe.getContextAttributes().antialias,qe.getShaderPrecisionFormat?qe.getShaderPrecisionFormat(qe.FRAGMENT_SHADER,qe.HIGH_FLOAT).precision>0?Ze.FS_MAX_FLOAT_PRECISION="highp":qe.getShaderPrecisionFormat(qe.FRAGMENT_SHADER,qe.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=qe.getParameter(qe.DEPTH_BITS),Ze.MAX_TEXTURE_SIZE=qe.getParameter(qe.MAX_TEXTURE_SIZE),Ze.MAX_CUBE_MAP_SIZE=qe.getParameter(qe.MAX_CUBE_MAP_TEXTURE_SIZE),Ze.MAX_RENDERBUFFER_SIZE=qe.getParameter(qe.MAX_RENDERBUFFER_SIZE),Ze.MAX_TEXTURE_UNITS=qe.getParameter(qe.MAX_COMBINED_TEXTURE_IMAGE_UNITS),Ze.MAX_TEXTURE_IMAGE_UNITS=qe.getParameter(qe.MAX_TEXTURE_IMAGE_UNITS),Ze.MAX_VERTEX_ATTRIBS=qe.getParameter(qe.MAX_VERTEX_ATTRIBS),Ze.MAX_VERTEX_UNIFORM_VECTORS=qe.getParameter(qe.MAX_VERTEX_UNIFORM_VECTORS),Ze.MAX_FRAGMENT_UNIFORM_VECTORS=qe.getParameter(qe.MAX_FRAGMENT_UNIFORM_VECTORS),Ze.MAX_VARYING_VECTORS=qe.getParameter(qe.MAX_VARYING_VECTORS),qe.getSupportedExtensions().forEach((function(e){Ze.SUPPORTED_EXTENSIONS[e]=!0})))}var $e=["webgl2","experimental-webgl","webkit-3d","moz-webgl","moz-glweb20"],et=function(e){g(i,fe);var t=y(i);function i(e){var s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};w(this,i),(s=t.call(this,e,r))._backgroundColor=q.vec3([r.backgroundColor?r.backgroundColor[0]:1,r.backgroundColor?r.backgroundColor[1]:1,r.backgroundColor?r.backgroundColor[2]:1]),s._backgroundColorFromAmbientLight=!!r.backgroundColorFromAmbientLight,s.canvas=r.canvas,s.gl=null,s.webgl2=!1,s.transparent=!!r.transparent,s.optimizeResizeDetection=!0,s.contextAttr=r.contextAttr||{},s.contextAttr.alpha=s.transparent,s.contextAttr.preserveDrawingBuffer=!!s.contextAttr.preserveDrawingBuffer,s.contextAttr.stencil=!1,s.contextAttr.premultipliedAlpha=!!s.contextAttr.premultipliedAlpha,s.contextAttr.antialias=!1!==s.contextAttr.antialias,s.resolutionScale=r.resolutionScale,s.canvas.width=Math.round(s.canvas.clientWidth*s._resolutionScale),s.canvas.height=Math.round(s.canvas.clientHeight*s._resolutionScale),s.boundary=[s.canvas.offsetLeft,s.canvas.offsetTop,s.canvas.clientWidth,s.canvas.clientHeight],s._initWebGL(r);var n=x(s);s.canvas.addEventListener("webglcontextlost",s._webglcontextlostListener=function(e){console.time("webglcontextrestored"),n.scene._webglContextLost(),n.fire("webglcontextlost"),e.preventDefault()},!1),s.canvas.addEventListener("webglcontextrestored",s._webglcontextrestoredListener=function(e){n._initWebGL(),n.gl&&(n.scene._webglContextRestored(n.gl),n.fire("webglcontextrestored",n.gl),e.preventDefault()),console.timeEnd("webglcontextrestored")},!1);var o=null,a=null,u=null,h=null,l=null,c=null,p=null,d=null,f=0;return s._tick=s.scene.on("tick",(function(){if(f++,n._canvasSizeChanged=!1,!(n.optimizeResizeDetection&&f<10)){f=0;var e=s.canvas,t=s._resolutionScale!==o,i=window.innerWidth!==a||window.innerHeight!==u,r=e.clientWidth!==h||e.clientHeight!==l,m=e.offsetLeft!==c||e.offsetTop!==p,v=e.parentElement;if(t||i||r||m||v!==d){if(n._canvasSizeChanged=!0,s._spinner._adjustPosition(),t||r||m){var g=e.clientWidth,_=e.clientHeight;if(t||r){var y,b=0;for(var x in pe.scenes)pe.scenes.hasOwnProperty(x)&&(y=pe.scenes[x],b+=Math.round(y.canvas.canvas.clientWidth*s._resolutionScale*(y.canvas.canvas.clientHeight*s._resolutionScale)));ee.memory.pixels=b,e.width=Math.round(e.clientWidth*s._resolutionScale),e.height=Math.round(e.clientHeight*s._resolutionScale)}var P=s.boundary;P[0]=e.offsetLeft,P[1]=e.offsetTop,P[2]=g,P[3]=_,t||s.fire("boundary",P),h=g,l=_}t&&(o=s._resolutionScale),i&&(a=window.innerWidth,u=window.innerHeight),m&&(c=e.offsetLeft,p=e.offsetTop),d=v}}})),s._spinner=new Je(s.scene,{canvas:s.canvas,elementId:r.spinnerElementId}),s}return I(i,[{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-"+q.createUUID(),t=document.getElementsByTagName("body")[0],i=document.createElement("div"),s=i.style;s.height="100%",s.width="100%",s.padding="0",s.margin="0",s.background="rgba(0,0,0,0);",s.float="left",s.left="0",s.top="0",s.position="absolute",s.opacity="1.0",s["z-index"]="-10000",i.innerHTML+='<canvas id="'+e+'" style="width: 100%; height: 100%; float: left; margin: 0; padding: 0;"></canvas>',t.appendChild(i),this.canvas=document.getElementById(e)}},{key:"_getElementXY",value:function(e){for(var t=0,i=0;e;)t+=e.offsetLeft-e.scrollLeft,i+=e.offsetTop-e.scrollTop,e=e.offsetParent;return{x:t,y:i}}},{key:"_initWebGL",value:function(){if(!this.gl)for(var e=0;!this.gl&&e<$e.length;e++)try{this.gl=this.canvas.getContext($e[e],this.contextAttr)}catch(e){}this.gl||(this.error("Failed to get a WebGL context"),this.fire("webglContextFailed",!0,!0));var t=this.gl,i="__",s=t.activeTexture;t.activeTexture=function(e){i!==e&&(i=e,s.call(this,e))};var r={},n=t.bindTexture;t.bindTexture=function(e,t){r[i]!==t&&(r[i]=t,n.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,i,s){return this.scene._renderer.readPixels(e,t,i,s)}},{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,m(P(i.prototype),"destroy",this).call(this)}}]),i}(),tt=function(){function e(t){w(this,e),this._scene=t,this._matPool=[],this._matPoolNextFreeIndex=0,this._rtcViewMats={},this._rtcPickViewMats={},this.reset()}return I(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.lineWidth=1}},{key:"getRTCViewMatrix",value:function(e,t){var i=this._rtcViewMats[e];return i||(i=this._getNewMat(),De(this._scene.camera.viewMatrix,t,i),this._rtcViewMats[e]=i),i}},{key:"getRTCPickViewMatrix",value:function(e,t){var i=this._rtcPickViewMats[e];if(!i){i=this._getNewMat();var s=this.pickViewMatrix||this._scene.camera.viewMatrix;De(s,t,i),this._rtcPickViewMats[e]=i}return i}},{key:"_getNewMat",value:function(){var e=this._matPool[this._matPoolNextFreeIndex];return e||(e=q.mat4(),this._matPool[this._matPoolNextFreeIndex]=e),this._matPoolNextFreeIndex++,e}}]),e}(),it=function(){function e(){w(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 I(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.entity&&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}(),st=function(){function e(t,i,s){if(w(this,e),this.allocated=!1,this.compiled=!1,this.handle=t.createShader(i),this.handle){if(this.allocated=!0,t.shaderSource(this.handle,s),t.compileShader(this.handle),this.compiled=t.getShaderParameter(this.handle,t.COMPILE_STATUS),!this.compiled&&!t.isContextLost()){for(var r=s.split("\n"),n=[],o=0;o<r.length;o++)n.push(o+1+": "+r[o]+"\n");this.errors=[],this.errors.push(""),this.errors.push(t.getShaderInfoLog(this.handle)),this.errors=this.errors.concat(n.join(""))}}else this.errors=["Failed to allocate"]}return I(e,[{key:"destroy",value:function(){}}]),e}(),rt=I((function e(t,i){w(this,e),this.bindTexture=function(e,s){return!!e.bind(s)&&(t.uniform1i(i,s),!0)}})),nt=function(){function e(t,i){w(this,e),this._gl=t,this.location=i}return I(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}(),ot=new G({});function at(e){for(var t,i,s=[],r=0,n=e.length;r<n;r++)(i=(t=e[r]).indexOf("/"))>0&&"/"===t.charAt(i+1)&&(t=t.substring(0,i)),s.push(t);return s.join("\n")}function ut(e){console.error(e.join("\n"))}var ht=function(){function e(t,i){w(this,e),this.id=ot.addItem({}),this.source=i,this.init(t)}return I(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 st(e,e.VERTEX_SHADER,at(this.source.vertex)),this._fragmentShader=new st(e,e.FRAGMENT_SHADER,at(this.source.fragment)),!this._vertexShader.allocated)return this.errors=["Vertex shader failed to allocate"].concat(this._vertexShader.errors),void ut(this.errors);if(!this._fragmentShader.allocated)return this.errors=["Fragment shader failed to allocate"].concat(this._fragmentShader.errors),void ut(this.errors);if(this.allocated=!0,!this._vertexShader.compiled)return this.errors=["Vertex shader failed to compile"].concat(this._vertexShader.errors),void ut(this.errors);if(!this._fragmentShader.compiled)return this.errors=["Fragment shader failed to compile"].concat(this._fragmentShader.errors),void ut(this.errors);var t,i,s,r,n;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 ut(this.errors);var o=e.getProgramParameter(this.handle,e.ACTIVE_UNIFORMS);for(i=0;i<o;++i)(s=e.getActiveUniform(this.handle,i))&&("\0"===(r=s.name)[r.length-1]&&(r=r.substr(0,r.length-1)),n=e.getUniformLocation(this.handle,r),s.type===e.SAMPLER_2D||s.type===e.SAMPLER_CUBE||35682===s.type||e instanceof WebGL2RenderingContext&&(s.type===e.UNSIGNED_INT_SAMPLER_2D||s.type===e.INT_SAMPLER_2D)?this.samplers[r]=new rt(e,n):this.uniforms[r]=n);var a=e.getProgramParameter(this.handle,e.ACTIVE_ATTRIBUTES);for(i=0;i<a;i++)(t=e.getActiveAttrib(this.handle,i))&&(n=e.getAttribLocation(this.handle,t.name),this.attributes[t.name]=new nt(e,n));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,i){if(!this.allocated)return!1;var s=this.samplers[e];return!!s&&s.bindTexture(t,i)}},{key:"destroy",value:function(){this.allocated&&(ot.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}(),lt=function(){function e(t,i,s,r,n,o,a,u,h){switch(w(this,e),this._gl=t,this.type=i,this.allocated=!1,s.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=o,this.length=0,this.dataLength=r,this.numItems=0,this.itemSize=n,this.normalized=!!a,this.stride=u||0,this.offset=h||0,this._allocate(s)}return I(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}(),ct=function(){function e(t,i){w(this,e),this.scene=t,this.aabb=q.AABB3(),this.origin=q.vec3(i),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 I(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 i=this.markerList[t].worldPos;this.positions[e++]=i[0],this.positions[e++]=i[1],this.positions[e++]=i[2],this.indices[t]=t}this.positions.length=3*this.numMarkers,this.indices.length=this.numMarkers}},{key:"_buildAABB",value:function(){var e=this.aabb;q.collapseAABB3(e),q.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,i=this.numMarkers;this.positionsBuf=new lt(e,e.ARRAY_BUFFER,new Float32Array(this.positions),t,3,e.STATIC_DRAW),this.indicesBuf=new lt(e,e.ELEMENT_ARRAY_BUFFER,new Uint16Array(this.indices),i,1,e.STATIC_DRAW),this.lenPositionsBuf=this.positions.length}},{key:"_buildOcclusionTestList",value:function(){var e=this.scene.canvas,t=this.scene.camera.perspective.near,i=e.boundary,s=i[2],r=i[3],n=0;this.lenOcclusionTestList=0;for(var o=0;o<this.numMarkers;o++){var a=this.markerList[o];if(a.viewPos[2]>-t)a._setVisible(!1);else{var u=a.canvasPos,h=u[0],l=u[1];h+10<0||l+10<0||h-10>s||l-10>r?a._setVisible(!1):!a.entity||a.entity.visible?a.occludable?(this.occlusionTestList[this.lenOcclusionTestList++]=a,this.pixels[n++]=h,this.pixels[n++]=l):a._setVisible(!0):a._setVisible(!1)}}}},{key:"_updateActiveSectionPlanes",value:function(){var e=this.scene._sectionPlanesState.sectionPlanes,t=e.length;if(t>0)for(var i=0;i<t;i++){var s=e[i];if(s.active){var r=q.planeAABB3Intersect(s.dir,s.dist,this.aabb);if(-1===r)return void(this.culledBySectionPlanes=!0);var n=0===r;this.sectionPlanesActive[i]=n}else this.sectionPlanesActive[i]=!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}(),pt=q.vec3([1,0,0]),dt=q.vec3(),ft=function(){function e(t,i){var s=this;w(this,e),this._scene=t,this._renderBufferManager=i,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(){s._occlusionTestListDirty=!0})),this._onCameraProjMatrix=t.camera.on("projMatrix",(function(){s._occlusionTestListDirty=!0})),this._onCanvasBoundary=t.canvas.on("boundary",(function(){s._occlusionTestListDirty=!0}))}return I(e,[{key:"addMarker",value:function(e){var t=e.origin.join(),i=this._occlusionLayers[t];i||(i=new ct(this._scene,e.origin),this._occlusionLayers[i.originHash]=i,this._occlusionLayersListDirty=!0),i.addMarker(e),this._markersToOcclusionLayersMap[e.id]=i,this._occlusionTestListDirty=!0}},{key:"markerWorldPosUpdated",value:function(e){var t=this._markersToOcclusionLayersMap[e.id];if(t){var i=e.origin.join();if(i!==t.originHash){1===t.numMarkers?(t.destroy(),delete this._occlusionLayers[t.originHash],this._occlusionLayersListDirty=!0):t.removeMarker(e);var s=this._occlusionLayers[i];s||(s=new ct(this._scene,e.origin),this._occlusionLayers[i]=t,this._occlusionLayersListDirty=!0),s.addMarker(e),this._markersToOcclusionLayersMap[e.id]=s}else t.markerWorldPosUpdated(e)}else e.error("Marker has not been added to OcclusionTester")}},{key:"removeMarker",value:function(e){var t=e.origin.join(),i=this._occlusionLayers[t];i&&(1===i.numMarkers?(i.destroy(),delete this._occlusionLayers[i.originHash],this._occlusionLayersListDirty=!0):i.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,i=this._occlusionLayersList.length;t<i;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,i=[];return i.push("#version 300 es"),i.push("// OcclusionTester vertex shader"),i.push("in vec3 position;"),i.push("uniform mat4 modelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;")),t&&i.push("out vec4 vWorldPosition;"),i.push("void main(void) {"),i.push("vec4 worldPosition = vec4(position, 1.0); "),i.push(" vec4 viewPosition = viewMatrix * worldPosition;"),t&&i.push(" vWorldPosition = worldPosition;"),i.push(" vec4 clipPos = projMatrix * viewPosition;"),i.push(" gl_PointSize = 20.0;"),e.logarithmicDepthBufferEnabled?i.push("vFragDepth = 1.0 + clipPos.w;"):i.push("clipPos.z += -0.001;"),i.push(" gl_Position = clipPos;"),i.push("}"),i}},{key:"_buildFragmentShaderSource",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.sectionPlanes.length>0,s=[];if(s.push("#version 300 es"),s.push("// OcclusionTester fragment shader"),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&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;");for(var r=0;r<t.sectionPlanes.length;r++)s.push("uniform bool sectionPlaneActive"+r+";"),s.push("uniform vec3 sectionPlanePos"+r+";"),s.push("uniform vec3 sectionPlaneDir"+r+";")}if(s.push("out vec4 outColor;"),s.push("void main(void) {"),i){s.push(" float dist = 0.0;");for(var n=0;n<t.sectionPlanes.length;n++)s.push("if (sectionPlaneActive"+n+") {"),s.push(" dist += clamp(dot(-sectionPlaneDir"+n+".xyz, vWorldPosition.xyz - sectionPlanePos"+n+".xyz), 0.0, 1000.0);"),s.push("}");s.push(" if (dist > 0.0) { discard; }")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = vec4(1.0, 0.0, 0.0, 1.0); "),s.push("}"),s}},{key:"_buildProgram",value:function(){this._program&&this._program.destroy();var e=this._scene,t=e.canvas.gl,i=e._sectionPlanesState;if(this._program=new ht(t,this._shaderSource),this._program.errors)this.errors=this._program.errors;else{var s=this._program;this._uViewMatrix=s.getLocation("viewMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uSectionPlanes=[];for(var r=0,n=i.sectionPlanes.length;r<n;r++)this._uSectionPlanes.push({active:s.getLocation("sectionPlaneActive"+r),pos:s.getLocation("sectionPlanePos"+r),dir:s.getLocation("sectionPlaneDir"+r)});this._aPosition=s.getAttribute("position"),e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=s.getLocation("logDepthBufFC"))}}},{key:"drawMarkers",value:function(){var e=this._scene,t=e.canvas.gl,i=this._program,s=e._sectionPlanesState,r=e.camera,n=e.camera.project;if(i.bind(),t.uniformMatrix4fv(this._uProjMatrix,!1,r._project._state.matrix),e.logarithmicDepthBufferEnabled){var o=2/(Math.log(n.far+1)/Math.LN2);t.uniform1f(this._uLogDepthBufFC,o)}for(var a=0,u=this._occlusionLayersList.length;a<u;a++){var h=this._occlusionLayersList[a];if(h.update(),!h.culledBySectionPlanes){var l=h.origin;t.uniformMatrix4fv(this._uViewMatrix,!1,De(r.viewMatrix,l));var c=s.sectionPlanes.length;if(c>0)for(var p=s.sectionPlanes,d=0;d<c;d++){var f=this._uSectionPlanes[d];if(f){var m=h.sectionPlanesActive[d];if(t.uniform1i(f.active,m?1:0),m){var v=p[d];t.uniform3fv(f.pos,Ee(v.dist,v.dir,l,dt)),t.uniform3fv(f.dir,v.dir)}}}this._aPosition.bindArrayBuffer(h.positionsBuf);var g=h.indicesBuf;g.bind(),t.drawElements(t.POINTS,g.numItems,g.itemType,0)}}}},{key:"doOcclusionTest",value:function(){for(var e=this._scene.canvas.resolutionScale,t=255*pt[0],i=255*pt[1],s=255*pt[2],r=0,n=this._occlusionLayersList.length;r<n;r++)for(var o=this._occlusionLayersList[r],a=0;a<o.lenOcclusionTestList;a++){var u=o.occlusionTestList[a],h=2*a,l=this._readPixelBuf.read(Math.round(o.pixels[h]*e),Math.round(o.pixels[h+1]*e)),c=l[0]===t&&l[1]===i&&l[2]===s;u._setVisible(c)}}},{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}(),mt=q.vec2(),vt=function(){function e(t){w(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 I(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 i=q.mat4();return function(){return e&&q.inverseMat4(r.camera.projMatrix,i),i}}());var i=this._scene.canvas.gl,s=this._program,r=this._scene,n=r.sao,o=i.drawingBufferWidth,a=i.drawingBufferHeight,u=r.camera.project._state,h=u.near,l=u.far,c=u.matrix,p=this._getInverseProjectMat(),d=Math.random(),f="perspective"===r.camera.projection;mt[0]=o,mt[1]=a,i.viewport(0,0,o,a),i.clearColor(0,0,0,1),i.disable(i.DEPTH_TEST),i.disable(i.BLEND),i.frontFace(i.CCW),i.clear(i.COLOR_BUFFER_BIT),s.bind(),i.uniform1f(this._uCameraNear,h),i.uniform1f(this._uCameraFar,l),i.uniformMatrix4fv(this._uCameraProjectionMatrix,!1,c),i.uniformMatrix4fv(this._uCameraInverseProjectionMatrix,!1,p),i.uniform1i(this._uPerspective,f),i.uniform1f(this._uScale,n.scale*(l/5)),i.uniform1f(this._uIntensity,n.intensity),i.uniform1f(this._uBias,n.bias),i.uniform1f(this._uKernelRadius,n.kernelRadius),i.uniform1f(this._uMinResolution,n.minResolution),i.uniform2fv(this._uViewport,mt),i.uniform1f(this._uRandomSeed,d);var m=e.getDepthTexture();s.bindTexture(this._uDepthTexture,m,0),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:"_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 i=this._scene.canvas.gl;if(this._program&&(this._program.destroy(),this._program=null),this._program=new ht(i,{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 s=new Float32Array([1,1,0,1,0,0,1,0]),r=new Float32Array([1,1,0,-1,1,0,-1,-1,0,1,-1,0]),n=new Uint32Array([0,1,2,0,2,3]);this._positionsBuf=new lt(i,i.ARRAY_BUFFER,r,r.length,3,i.STATIC_DRAW),this._uvBuf=new lt(i,i.ARRAY_BUFFER,s,s.length,2,i.STATIC_DRAW),this._indicesBuf=new lt(i,i.ELEMENT_ARRAY_BUFFER,n,n.length,1,i.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}(),gt=new Float32Array(Tt(17,[0,1])),_t=new Float32Array(Tt(17,[1,0])),yt=new Float32Array(function(e,t){for(var i=[],s=0;s<=e;s++)i.push(Pt(s,t));return i}(17,4)),bt=new Float32Array(2),xt=function(){function e(t){w(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 I(e,[{key:"init",value:function(){var e=this._scene.canvas.gl;if(this._program=new ht(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]),i=new Float32Array([1,1,0,-1,1,0,-1,-1,0,1,-1,0]),s=new Uint32Array([0,1,2,0,2,3]);this._positionsBuf=new lt(e,e.ARRAY_BUFFER,i,i.length,3,e.STATIC_DRAW),this._uvBuf=new lt(e,e.ARRAY_BUFFER,t,t.length,2,e.STATIC_DRAW),this._indicesBuf=new lt(e,e.ELEMENT_ARRAY_BUFFER,s,s.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,i){var s=this;if(!this._programError){this._getInverseProjectMat||(this._getInverseProjectMat=function(){var e=!0;s._scene.camera.on("projMatrix",(function(){e=!0}));var t=q.mat4();return function(){return e&&q.inverseMat4(o.camera.projMatrix,t),t}}());var r=this._scene.canvas.gl,n=this._program,o=this._scene,a=r.drawingBufferWidth,u=r.drawingBufferHeight,h=o.camera.project._state,l=h.near,c=h.far;r.viewport(0,0,a,u),r.clearColor(0,0,0,1),r.enable(r.DEPTH_TEST),r.disable(r.BLEND),r.frontFace(r.CCW),r.clear(r.COLOR_BUFFER_BIT|r.DEPTH_BUFFER_BIT),n.bind(),bt[0]=a,bt[1]=u,r.uniform2fv(this._uViewport,bt),r.uniform1f(this._uCameraNear,l),r.uniform1f(this._uCameraFar,c),r.uniform1f(this._uDepthCutoff,.01),0===i?r.uniform2fv(this._uSampleOffsets,_t):r.uniform2fv(this._uSampleOffsets,gt),r.uniform1fv(this._uSampleWeights,yt);var p=e.getDepthTexture(),d=t.getTexture();n.bindTexture(this._uDepthTexture,p,0),n.bindTexture(this._uOcclusionTexture,d,1),this._aUV.bindArrayBuffer(this._uvBuf),this._aPosition.bindArrayBuffer(this._positionsBuf),this._indicesBuf.bind(),r.drawElements(r.TRIANGLES,this._indicesBuf.numItems,this._indicesBuf.itemType,0)}}},{key:"destroy",value:function(){this._program.destroy()}}]),e}();function Pt(e,t){return Math.exp(-e*e/(t*t*2))/(Math.sqrt(2*Math.PI)*t)}function Tt(e,t){for(var i=[],s=0;s<=e;s++)i.push(t[0]*s),i.push(t[1]*s);return i}var wt=function(){var e=document.createElement("canvas"),t=String.fromCharCode;if(!e.getContext)return{saveAsBMP:function(){},saveAsPNG:function(){},saveAsJPEG:function(){}};var i=!!e.getContext("2d").getImageData,s=!!e.toDataURL,r=!!window.btoa,n=function(e){var i="",s=e.width,r=e.height;i+="BM";var n=s*r*4+54;i+=t(n%256),n=Math.floor(n/256),i+=t(n%256),n=Math.floor(n/256),i+=t(n%256),n=Math.floor(n/256),i+=t(n%256),i+=t(0,0,0,0,54,0,0,0),i+=t(40,0,0,0);var o=s;i+=t(o%256),o=Math.floor(o/256),i+=t(o%256),o=Math.floor(o/256),i+=t(o%256),o=Math.floor(o/256),i+=t(o%256);var a=r;i+=t(a%256),a=Math.floor(a/256),i+=t(a%256),a=Math.floor(a/256),i+=t(a%256),a=Math.floor(a/256),i+=t(a%256),i+=t(1,0,32,0),i+=t(0,0,0,0);var u=s*r*4;i+=t(u%256),u=Math.floor(u/256),i+=t(u%256),u=Math.floor(u/256),i+=t(u%256),u=Math.floor(u/256),i+=t(u%256),i+=t(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);var h,l,c,p,d=e.data,f="",m=r;do{for(c=s*(m-1)*4,p="",h=0;h<s;h++)p+=t(d[c+(l=4*h)+2],d[c+l+1],d[c+l],d[c+l+3]);f+=p}while(--m);return function(e){var i,s,r="";if("string"==typeof e)r=e;else for(s=e,i=0;i<s.length;i++)r+=t(s[i]);return btoa(r)}(i+f)},o=function(e){window.open(e)||(document.location.href=e)},a=function(e,t){return"data:"+t+";base64,"+e},u=function(e){var t=document.createElement("img");return t.src=e,t},h=function(e,t,i,s){if(t&&i){var r=document.createElement("canvas");r.width=t,r.height=i,r.style.width=t+"px",r.style.height=i+"px";var n=r.getContext("2d");return s?(n.save(),n.scale(1,-1),n.imageSmoothingEnabled=!0,n.drawImage(e,0,0,e.width,e.height,0,0,t,-i),n.restore()):(n.imageSmoothingEnabled=!0,n.drawImage(e,0,0,e.width,e.height,0,0,t,i)),r}return e};return{saveAsPNG:function(e,t,i,r,n){if(!s)return!1;var a=h(e,i,r,n).toDataURL("image/png");return t?u(a):(o(a),!0)},saveAsJPEG:function(e,t,i,r,n){if(!s)return!1;var a="image/jpeg",l=h(e,i,r,n).toDataURL(a);return 5==l.indexOf(a)&&(t?u(l):(o(l),!0))},saveAsBMP:function(e,t,l,c,p){if(!(s&&i&&r))return!1;var d="image/bmp",f=function(e){var t=parseInt(e.width),i=parseInt(e.height);return e.getContext("2d").getImageData(0,0,t,i)}(h(e,l,c,p)),m=n(f);return t?u(a(m,d)):(o(a(m,d)),!0)}}}(),Mt=function(){function e(t,i,s){w(this,e),s=s||{},this.gl=i,this.allocated=!1,this.canvas=t,this.buffer=null,this.bound=!1,this.size=s.size,this._hasDepthTexture=!!s.depthTexture}return I(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(){if(this._touch(),!this.bound){var e=this.gl;e.bindFramebuffer(e.FRAMEBUFFER,this.buffer.framebuf),this.bound=!0}}},{key:"_touch",value:function(){var e,t,i=this.gl;if(this.size?(e=this.size[0],t=this.size[1]):(e=i.drawingBufferWidth,t=i.drawingBufferHeight),this.buffer){if(this.buffer.width===e&&this.buffer.height===t)return;i.deleteTexture(this.buffer.texture),i.deleteFramebuffer(this.buffer.framebuf),i.deleteRenderbuffer(this.buffer.renderbuf)}var s,r=i.createTexture();i.bindTexture(i.TEXTURE_2D,r),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_MIN_FILTER,i.NEAREST),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_MAG_FILTER,i.NEAREST),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_WRAP_S,i.CLAMP_TO_EDGE),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_WRAP_T,i.CLAMP_TO_EDGE),i.texImage2D(i.TEXTURE_2D,0,i.RGBA,e,t,0,i.RGBA,i.UNSIGNED_BYTE,null),this._hasDepthTexture&&(s=i.createTexture(),i.bindTexture(i.TEXTURE_2D,s),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_MAG_FILTER,i.NEAREST),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_MIN_FILTER,i.NEAREST),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_WRAP_S,i.CLAMP_TO_EDGE),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_WRAP_T,i.CLAMP_TO_EDGE),i.texImage2D(i.TEXTURE_2D,0,i.DEPTH_COMPONENT32F,e,t,0,i.DEPTH_COMPONENT,i.FLOAT,null));var n=i.createRenderbuffer();i.bindRenderbuffer(i.RENDERBUFFER,n),i.renderbufferStorage(i.RENDERBUFFER,i.DEPTH_COMPONENT32F,e,t);var o=i.createFramebuffer();if(i.bindFramebuffer(i.FRAMEBUFFER,o),i.framebufferTexture2D(i.FRAMEBUFFER,i.COLOR_ATTACHMENT0,i.TEXTURE_2D,r,0),this._hasDepthTexture?i.framebufferTexture2D(i.FRAMEBUFFER,i.DEPTH_ATTACHMENT,i.TEXTURE_2D,s,0):i.framebufferRenderbuffer(i.FRAMEBUFFER,i.DEPTH_ATTACHMENT,i.RENDERBUFFER,n),i.bindTexture(i.TEXTURE_2D,null),i.bindRenderbuffer(i.RENDERBUFFER,null),i.bindFramebuffer(i.FRAMEBUFFER,null),i.bindFramebuffer(i.FRAMEBUFFER,o),!i.isFramebuffer(o))throw"Invalid framebuffer";i.bindFramebuffer(i.FRAMEBUFFER,null);var a=i.checkFramebufferStatus(i.FRAMEBUFFER);switch(a){case i.FRAMEBUFFER_COMPLETE:break;case i.FRAMEBUFFER_INCOMPLETE_ATTACHMENT:throw"Incomplete framebuffer: FRAMEBUFFER_INCOMPLETE_ATTACHMENT";case i.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:throw"Incomplete framebuffer: FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT";case i.FRAMEBUFFER_INCOMPLETE_DIMENSIONS:throw"Incomplete framebuffer: FRAMEBUFFER_INCOMPLETE_DIMENSIONS";case i.FRAMEBUFFER_UNSUPPORTED:throw"Incomplete framebuffer: FRAMEBUFFER_UNSUPPORTED";default:throw"Incomplete framebuffer: "+a}this.buffer={framebuf:o,renderbuf:n,texture:r,depthTexture:s,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 i=e,s=this.gl.drawingBufferHeight-t,r=new Uint8Array(4),n=this.gl;return n.readPixels(i,s,1,1,n.RGBA,n.UNSIGNED_BYTE,r),r}},{key:"readImage",value:function(e){var t=this.gl,i=this._getImageDataCache(),s=i.pixelData,r=i.canvas,n=i.imageData,o=i.context;t.readPixels(0,0,this.buffer.width,this.buffer.height,t.RGBA,t.UNSIGNED_BYTE,s),n.data.set(s),o.putImageData(n,0,0);var a,u=e.width||r.width,h=e.height||r.height,l=e.format||"jpeg",c=!0;switch(l){case"jpeg":a=wt.saveAsJPEG(r,!0,u,h,c);break;case"png":a=wt.saveAsPNG(r,!0,u,h,c);break;case"bmp":a=wt.saveAsBMP(r,!0,u,h,c);break;default:console.error("Unsupported image format: '"+l+"' - supported types are 'jpeg', 'bmp' and 'png' - defaulting to 'jpeg'"),a=wt.saveAsJPEG(r,!0,u,h,c)}return a.src}},{key:"_getImageDataCache",value:function(){var e=this.buffer.width,t=this.buffer.height,i=this._imageDataCache;if(i&&(i.width===e&&i.height===t||(this._imageDataCache=null,i=null)),!i){var s=document.createElement("canvas");s.width=e,s.height=t;var r=s.getContext("2d"),n=r.createImageData(e,t);i={pixelData:new Uint8Array(e*t*4),canvas:s,context:r,imageData:n,width:e,height:t},this._imageDataCache=i}return 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}(),It=function(){function e(t){w(this,e),this.scene=t,this._renderBuffersBasic={},this._renderBuffersScaled={}}return I(e,[{key:"getRenderBuffer",value:function(e,t){var i=1===this.scene.canvas.resolutionScale?this._renderBuffersBasic:this._renderBuffersScaled,s=i[e];return s||(s=new Mt(this.scene.canvas.canvas,this.scene.canvas.gl,t),i[e]=s),s}},{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 i;switch(t){case"WEBGL_depth_texture":i=e.getExtension("WEBGL_depth_texture")||e.getExtension("MOZ_WEBGL_depth_texture")||e.getExtension("WEBKIT_WEBGL_depth_texture");break;case"EXT_texture_filter_anisotropic":i=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":i=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":i=e.getExtension("WEBGL_compressed_texture_pvrtc")||e.getExtension("WEBKIT_WEBGL_compressed_texture_pvrtc");break;default:i=e.getExtension(t)}return e._cachedExtensions[t]=i,i}var Dt=function(){var e=[],t=[],i=[],s=[],r=[],n=0,o=new Uint16Array(3),a=new Uint16Array(3),u=new Uint16Array(3),h=q.vec3(),l=q.vec3(),c=q.vec3(),p=q.vec3(),d=q.vec3(),f=q.vec3(),m=q.vec3();return function(v,g,_,y){!function(r,n){var o,a,u,h,l,c,p={},d=Math.pow(10,4),f=0;for(l=0,c=r.length;l<c;l+=3)o=r[l],a=r[l+1],u=r[l+2],void 0===p[h=Math.round(o*d)+"_"+Math.round(a*d)+"_"+Math.round(u*d)]&&(p[h]=f/3,e[f++]=o,e[f++]=a,e[f++]=u),t[l/3]=p[h];for(l=0,c=n.length;l<c;l++)s[l]=t[n[l]],i[s[l]]=n[l]}(v,g),function(t,i){n=0;for(var v=0,g=t;v<g;v+=3){var _=3*s[v],y=3*s[v+1],b=3*s[v+2];i?(o[0]=e[_],o[1]=e[_+1],o[2]=e[_+2],a[0]=e[y],a[1]=e[y+1],a[2]=e[y+2],u[0]=e[b],u[1]=e[b+1],u[2]=e[b+2],q.decompressPosition(o,i,h),q.decompressPosition(a,i,l),q.decompressPosition(u,i,c)):(h[0]=e[_],h[1]=e[_+1],h[2]=e[_+2],l[0]=e[y],l[1]=e[y+1],l[2]=e[y+2],c[0]=e[b],c[1]=e[b+1],c[2]=e[b+2]),q.subVec3(c,l,p),q.subVec3(h,l,d),q.cross3Vec3(p,d,f),q.normalizeVec3(f,m);var x=r[n]||(r[n]={normal:q.vec3()});x.normal[0]=m[0],x.normal[1]=m[1],x.normal[2]=m[2],n++}}(g.length,_);for(var b,x,P,T,w,M,I,C,D,A,k=[],E=Math.cos(q.DEGTORAD*y),F={},R=!1,S=0,O=g.length;S<O;S+=3)for(var B=S/3,L=0;L<3;L++)b=s[S+L],x=s[S+(L+1)%3],void 0===F[w=(P=Math.min(b,x))+","+(T=Math.max(b,x))]?F[w]={index1:P,index2:T,face1:B,face2:void 0}:F[w].face2=B;for(w in F)void 0!==(M=F[w]).face2&&(I=r[M.face1].normal,C=r[M.face2].normal,q.dotVec3(I,C)>E)||(D=i[M.index1],A=i[M.index2],(!R&&D>65535||A>65535)&&(R=!0),k.push(D),k.push(A));return R?new Uint32Array(k):new Uint16Array(k)}}(),At=function(){function e(t,i,s,r){var n=arguments.length>4&&void 0!==arguments[4]?arguments[4]:null,o=arguments.length>5&&void 0!==arguments[5]?arguments[5]:0;w(this,e),this.model=t,this.object=null,this.parent=null,this.id=i,this.pickId=this.model.scene._renderer.getPickID(this),this.aabb=q.AABB3(),this._layer=n,this._portionId=o,this._color=[s[0],s[1],s[2],r],this._colorize=[s[0],s[1],s[2],r],this._colorizing=!1,this._transparent=r<255,this.numTriangles=0,this.origin=null}return I(e,[{key:"_finalize",value:function(e){this._layer.initFlags(this._portionId,e,this._transparent)}},{key:"_finalize2",value:function(){this._layer.flushInitFlags&&this._layer.flushInitFlags()}},{key:"_setVisible",value:function(e){this._layer.setVisible(this._portionId,e,this._transparent)}},{key:"_setColor",value:function(e){this._color[0]=e[0],this._color[1]=e[1],this._color[2]=e[2],this._colorizing||this._layer.setColor(this._portionId,this._color,!1)}},{key:"_setColorize",value:function(e){e?(this._colorize[0]=e[0],this._colorize[1]=e[1],this._colorize[2]=e[2],this._layer.setColor(this._portionId,this._colorize,false),this._colorizing=!0):(this._layer.setColor(this._portionId,this._color,false),this._colorizing=!1)}},{key:"_setOpacity",value:function(e,t){var i=e<255,s=this._transparent!==i;this._color[3]=e,this._colorize[3]=e,this._transparent=i,this._colorizing?this._layer.setColor(this._portionId,this._colorize):this._layer.setColor(this._portionId,this._color),s&&this._layer.setTransparent(this._portionId,t,i)}},{key:"_setOffset",value:function(e){this._layer.setOffset(this._portionId,e)}},{key:"_setHighlighted",value:function(e){this._layer.setHighlighted(this._portionId,e,this._transparent)}},{key:"_setXRayed",value:function(e){this._layer.setXRayed(this._portionId,e,this._transparent)}},{key:"_setSelected",value:function(e){this._layer.setSelected(this._portionId,e,this._transparent)}},{key:"_setEdges",value:function(e){this._layer.setEdges(this._portionId,e,this._transparent)}},{key:"_setClippable",value:function(e){this._layer.setClippable(this._portionId,e,this._transparent)}},{key:"_setCollidable",value:function(e){this._layer.setCollidable(this._portionId,e)}},{key:"_setPickable",value:function(e){this._layer.setPickable(this._portionId,e,this._transparent)}},{key:"_setCulled",value:function(e){this._layer.setCulled(this._portionId,e,this._transparent)}},{key:"canPickTriangle",value:function(){return!1}},{key:"drawPickTriangles",value:function(e,t){}},{key:"pickTriangleSurface",value:function(e){}},{key:"precisionRayPickSurface",value:function(e,t,i,s){return!!this._layer.precisionRayPickSurface&&this._layer.precisionRayPickSurface(this._portionId,e,t,i,s)}},{key:"canPickWorldPos",value:function(){return!0}},{key:"drawPickDepths",value:function(e){this.model.drawPickDepths(e)}},{key:"drawPickNormals",value:function(e){this.model.drawPickNormals(e)}},{key:"delegatePickedEntity",value:function(){return this.parent}},{key:"_destroy",value:function(){this.model.scene._renderer.putPickID(this.pickId)}}]),e}(),kt=1,Et=4,Ft=8,Rt=16,St=32,Ot=256,Bt=512,Lt=1024,Nt=2048,jt=new Float32Array([0,0,0]),Gt=new Uint16Array([0,0,0]),Ht=function(){function e(t,i,s,r,n,o){w(this,e),this._isObject=i,this.scene=t.scene,this.model=t,this.meshes=r,this._numTriangles=0;for(var a=0,u=this.meshes.length;a<u;a++){var h=this.meshes[a];h.parent=this,this._numTriangles+=h.numTriangles}this.id=s,this.originalSystemId=q.unglobalizeObjectId(t.id,s),this._flags=n,this._aabb=o,this._offsetAABB=q.AABB3(o),this._offset=q.vec3(),this._colorizeUpdated=!1,this._opacityUpdated=!1,this._culled=!1,this._culledVFC=!1,this._culledLOD=!1,this._isObject&&t.scene._registerObject(this)}return I(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:"numTriangles",get:function(){return this._numTriangles}},{key:"visible",get:function(){return this._getFlag(kt)},set:function(e){if(!!(this._flags&kt)!==e){this._flags=e?this._flags|kt:this._flags&~kt;for(var t=0,i=this.meshes.length;t<i;t++)this.meshes[t]._setVisible(this._flags);this._isObject&&this.model.scene._objectVisibilityUpdated(this),this.model.glRedraw()}}},{key:"highlighted",get:function(){return this._getFlag(Bt)},set:function(e){if(!!(this._flags&Bt)!==e){this._flags=e?this._flags|Bt:this._flags&~Bt;for(var t=0,i=this.meshes.length;t<i;t++)this.meshes[t]._setHighlighted(this._flags);this._isObject&&this.model.scene._objectHighlightedUpdated(this),this.model.glRedraw()}}},{key:"xrayed",get:function(){return this._getFlag(Ot)},set:function(e){if(!!(this._flags&Ot)!==e){this._flags=e?this._flags|Ot:this._flags&~Ot;for(var t=0,i=this.meshes.length;t<i;t++)this.meshes[t]._setXRayed(this._flags);this._isObject&&this.model.scene._objectXRayedUpdated(this),this.model.glRedraw()}}},{key:"selected",get:function(){return this._getFlag(Lt)},set:function(e){if(!!(this._flags&Lt)!==e){this._flags=e?this._flags|Lt:this._flags&~Lt;for(var t=0,i=this.meshes.length;t<i;t++)this.meshes[t]._setSelected(this._flags);this._isObject&&this.model.scene._objectSelectedUpdated(this),this.model.glRedraw()}}},{key:"edges",get:function(){return this._getFlag(Nt)},set:function(e){if(!!(this._flags&Nt)!==e){this._flags=e?this._flags|Nt:this._flags&~Nt;for(var t=0,i=this.meshes.length;t<i;t++)this.meshes[t]._setEdges(this._flags);this.model.glRedraw()}}},{key:"culledVFC",get:function(){return!!this._culledVFC},set:function(e){this._culledVFC=e,this.internalSetCulled()}},{key:"culledLOD",get:function(){return!!this._culledLOD},set:function(e){this._culledLOD=e,this.internalSetCulled()}},{key:"culled",get:function(){return!!this._culled},set:function(e){this._culled=e,this.internalSetCulled()}},{key:"internalSetCulled",value:function(){var e=!!this._culled||!!this._culledLOD||!!this._culledVFC;if(!!(this._flags&Et)!==e){this._flags=e?this._flags|Et:this._flags&~Et;for(var t=0,i=this.meshes.length;t<i;t++)this.meshes[t]._setCulled(this._flags);this.model.glRedraw()}}},{key:"clippable",get:function(){return this._getFlag(Rt)},set:function(e){if(!!(this._flags&Rt)!==e){this._flags=e?this._flags|Rt:this._flags&~Rt;for(var t=0,i=this.meshes.length;t<i;t++)this.meshes[t]._setClippable(this._flags);this.model.glRedraw()}}},{key:"collidable",get:function(){return this._getFlag(St)},set:function(e){if(!!(this._flags&St)!==e){this._flags=e?this._flags|St:this._flags&~St;for(var t=0,i=this.meshes.length;t<i;t++)this.meshes[t]._setCollidable(this._flags)}}},{key:"pickable",get:function(){return this._getFlag(Ft)},set:function(e){if(!!(this._flags&Ft)!==e){this._flags=e?this._flags|Ft:this._flags&~Ft;for(var t=0,i=this.meshes.length;t<i;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 jt[0]=e[0]/255,jt[1]=e[1]/255,jt[2]=e[2]/255,jt},set:function(e){if(e){Gt[0]=Math.floor(255*e[0]),Gt[1]=Math.floor(255*e[1]),Gt[2]=Math.floor(255*e[2]);for(var t=0,i=this.meshes.length;t<i;t++)this.meshes[t]._setColorize(Gt)}else for(var s=0,r=this.meshes.length;s<r;s++)this.meshes[s]._setColorize(null);if(this._isObject){var n=!!e;this.scene._objectColorizeUpdated(this,n),this._colorizeUpdated=n}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,i=this.meshes[0]._colorize[3],s=255;if(t){if(e<0?e=0:e>1&&(e=1),i===(s=Math.floor(255*e)))return}else if(i===(s=255))return;for(var r=0,n=this.meshes.length;r<n;r++)this.meshes[r]._setOpacity(s,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,i=this.meshes.length;t<i;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:"castsShadow",get:function(){return!1},set:function(e){}},{key:"receivesShadow",get:function(){return!1},set:function(e){}},{key:"saoEnabled",get:function(){return this.model.saoEnabled}},{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,i=this.meshes.length;t<i;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,i=this.meshes.length;t<i;t++)this.meshes[t]._destroy();e._aabbDirty=!0}}]),e}(),Vt=0,Ut=1,zt=2,Wt=3,Xt=4,Yt=5,Kt=6,Jt=7,Zt=8,Qt=9,qt=10,$t=11,ei=new G({}),ti=function(){function e(t){for(var i in w(this,e),this.id=ei.addItem({}),t)t.hasOwnProperty(i)&&(this[i]=t[i])}return I(e,[{key:"destroy",value:function(){ei.removeItem(this.id)}}]),e}();var ii=function(){var e=q.mat4(),t=q.mat4();return function(i,s){s=s||q.mat4();var r=i[0],n=i[1],o=i[2],a=i[3]-r,u=i[4]-n,h=i[5]-o,l=65535;return q.identityMat4(e),q.translationMat4v(i,e),q.identityMat4(t),q.scalingMat4v([a/l,u/l,h/l],t),q.mulMat4(e,t,s),s}}(),si=function(){var e=q.mat4(),t=q.mat4();return function(i,s,r){var n,o=new Uint16Array(i.length),a=new Float32Array([r[0]!==s[0]?65535/(r[0]-s[0]):0,r[1]!==s[1]?65535/(r[1]-s[1]):0,r[2]!==s[2]?65535/(r[2]-s[2]):0]);for(n=0;n<i.length;n+=3)o[n+0]=Math.max(0,Math.min(65535,Math.floor((i[n+0]-s[0])*a[0]))),o[n+1]=Math.max(0,Math.min(65535,Math.floor((i[n+1]-s[1])*a[1]))),o[n+2]=Math.max(0,Math.min(65535,Math.floor((i[n+2]-s[2])*a[2])));return q.identityMat4(e),q.translationMat4v(s,e),q.identityMat4(t),q.scalingMat4v([(r[0]-s[0])/65535,(r[1]-s[1])/65535,(r[2]-s[2])/65535],t),{quantized:o,decodeMatrix:q.mulMat4(e,t,q.identityMat4())}}}();var ri=function(){var e=q.mat3(),t=q.mat3();return function(i,s,r){var n,o=new Uint16Array(i.length),a=new Float32Array([65535/(r[0]-s[0]),65535/(r[1]-s[1])]);for(n=0;n<i.length;n+=2)o[n+0]=Math.max(0,Math.min(65535,Math.floor((i[n+0]-s[0])*a[0]))),o[n+1]=Math.max(0,Math.min(65535,Math.floor((i[n+1]-s[1])*a[1])));return q.identityMat3(e),q.translationMat3v(s,e),q.identityMat3(t),q.scalingMat3v([(r[0]-s[0])/65535,(r[1]-s[1])/65535],t),{quantized:o,decodeMatrix:q.mulMat3(e,t,q.identityMat3())}}}();function ni(e,t,i,s){var r=e[t]/(Math.abs(e[t])+Math.abs(e[t+1])+Math.abs(e[t+2])),n=e[t+1]/(Math.abs(e[t])+Math.abs(e[t+1])+Math.abs(e[t+2]));if(e[t+2]<0){var o=(1-Math.abs(n))*(r>=0?1:-1),a=(1-Math.abs(r))*(n>=0?1:-1);r=o,n=a}return new Int8Array([Math[i](127.5*r+(r<0?-1:0)),Math[s](127.5*n+(n<0?-1:0))])}function oi(e){var t=e[0],i=e[1];t/=t<0?127:128,i/=i<0?127:128;var s=1-Math.abs(t)-Math.abs(i);s<0&&(t=(1-Math.abs(i))*(t>=0?1:-1),i=(1-Math.abs(t))*(i>=0?1:-1));var r=Math.sqrt(t*t+i*i+s*s);return[t/r,i/r,s/r]}function ai(e,t,i){return e[t]*i[0]+e[t+1]*i[1]+e[t+2]*i[2]}var ui={getPositionsBounds:function(e){var t,i,s=new Float32Array(3),r=new Float32Array(3);for(t=0;t<3;t++)s[t]=Number.MAX_VALUE,r[t]=-Number.MAX_VALUE;for(t=0;t<e.length;t+=3)for(i=0;i<3;i++)s[i]=Math.min(s[i],e[t+i]),r[i]=Math.max(r[i],e[t+i]);return{min:s,max:r}},createPositionsDecodeMatrix:ii,compressPositions:si,compressPosition:function(e,t,i){var s=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]);i[0]=Math.max(0,Math.min(65535,Math.floor((e[0]-t[0])*s[0]))),i[1]=Math.max(0,Math.min(65535,Math.floor((e[1]-t[1])*s[1]))),i[2]=Math.max(0,Math.min(65535,Math.floor((e[2]-t[2])*s[2])))},decompressPositions:function(e,t){for(var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:new Float32Array(e.length),s=0,r=e.length;s<r;s+=3)i[s+0]=e[s+0]*t[0]+t[12],i[s+1]=e[s+1]*t[5]+t[13],i[s+2]=e[s+2]*t[10]+t[14];return i},decompressPosition:function(e,t,i){return i[0]=e[0]*t[0]+t[12],i[1]=e[1]*t[5]+t[13],i[2]=e[2]*t[10]+t[14],i},decompressAABB:function(e,t){var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:e;return i[0]=e[0]*t[0]+t[12],i[1]=e[1]*t[5]+t[13],i[2]=e[2]*t[10]+t[14],i[3]=e[3]*t[0]+t[12],i[4]=e[4]*t[5]+t[13],i[5]=e[5]*t[10]+t[14],i},getUVBounds:function(e){var t,i,s=new Float32Array(2),r=new Float32Array(2);for(t=0;t<2;t++)s[t]=Number.MAX_VALUE,r[t]=-Number.MAX_VALUE;for(t=0;t<e.length;t+=2)for(i=0;i<2;i++)s[i]=Math.min(s[i],e[t+i]),r[i]=Math.max(r[i],e[t+i]);return{min:s,max:r}},compressUVs:ri,decompressUVs:function(e,t){for(var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:new Float32Array(e.length),s=0,r=e.length;s<r;s+=3)i[s+0]=e[s+0]*t[0]+t[6],i[s+1]=e[s+1]*t[4]+t[7];return i},decompressUV:function(e,t,i){i[0]=e[0]*t[0]+t[6],i[1]=e[1]*t[4]+t[7]},compressNormals:function(e){for(var t,i,s,r,n=new Int8Array(e.length),o=0;o<e.length;o+=3)i=t=ni(e,o,"floor","floor"),s=r=ai(e,o,oi(t)),(s=ai(e,o,oi(t=ni(e,o,"ceil","floor"))))>r&&(i=t,r=s),(s=ai(e,o,oi(t=ni(e,o,"floor","ceil"))))>r&&(i=t,r=s),(s=ai(e,o,oi(t=ni(e,o,"ceil","ceil"))))>r&&(i=t,r=s),n[o]=i[0],n[o+1]=i[1];return n},decompressNormals:function(e,t){for(var i=0,s=0,r=e.length;i<r;i+=2){var n=e[i+0],o=e[i+1];n=(2*n+1)/255,o=(2*o+1)/255;var a=1-Math.abs(n)-Math.abs(o);a<0&&(n=(1-Math.abs(o))*(n>=0?1:-1),o=(1-Math.abs(n))*(o>=0?1:-1));var u=Math.sqrt(n*n+o*o+a*a);t[s+0]=n/u,t[s+1]=o/u,t[s+2]=a/u,s+=3}return t},decompressNormal:function(e,t){var i=e[0],s=e[1];i=(2*i+1)/255,s=(2*s+1)/255;var r=1-Math.abs(i)-Math.abs(s);r<0&&(i=(1-Math.abs(s))*(i>=0?1:-1),s=(1-Math.abs(i))*(s>=0?1:-1));var n=Math.sqrt(i*i+s*s+r*r);return t[0]=i/n,t[1]=s/n,t[2]=r/n,t}},hi=function(e){g(i,fe);var t=y(i);function i(e){var s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return w(this,i),(s=t.call(this,e,r)).camera=e,s._state=new ti({matrix:q.mat4(),inverseMatrix:q.mat4(),transposedMatrix:q.mat4(),near:.1,far:2e3}),s._inverseMatrixDirty=!0,s._transposedMatrixDirty=!0,s._fov=60,s._canvasResized=s.scene.canvas.on("boundary",s._needUpdate,x(s)),s.fov=r.fov,s.fovAxis=r.fovAxis,s.near=r.near,s.far=r.far,s}return I(i,[{key:"type",get:function(){return"Perspective"}},{key:"_update",value:function(){var e=this.scene.viewport.boundary,t=e[2]/e[3],i=this._fovAxis,s=this._fov;("x"===i||"min"===i&&t<1||"max"===i&&t>1)&&(s/=t),s=Math.min(s,120),q.perspectiveMat4(s*(Math.PI/180),t,this._state.near,this._state.far,this._state.matrix),this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!0,this.glRedraw(),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&&(q.inverseMat4(this._state.matrix,this._state.inverseMatrix),this._inverseMatrixDirty=!1),this._state.inverseMatrix}},{key:"transposedMatrix",get:function(){return this._updateScheduled&&this._doUpdate(),this._transposedMatrixDirty&&(q.transposeMat4(this._state.matrix,this._state.transposedMatrix),this._transposedMatrixDirty=!1),this._state.transposedMatrix}},{key:"unproject",value:function(e,t,i,s,r){var n=this.scene.canvas.canvas,o=n.offsetWidth/2,a=n.offsetHeight/2;return i[0]=(e[0]-o)/o,i[1]=(e[1]-a)/a,i[2]=t,i[3]=1,q.mulMat4v4(this.inverseMatrix,i,s),q.mulVec3Scalar(s,1/s[3]),s[3]=1,s[1]*=-1,q.mulMat4v4(this.camera.inverseViewMatrix,s,r),r}},{key:"destroy",value:function(){m(P(i.prototype),"destroy",this).call(this),this._state.destroy(),this.scene.canvas.off(this._canvasResized)}}]),i}(),li=function(e){g(i,fe);var t=y(i);function i(e){var s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return w(this,i),(s=t.call(this,e,r)).camera=e,s._state=new ti({matrix:q.mat4(),inverseMatrix:q.mat4(),transposedMatrix:q.mat4(),near:.1,far:2e3}),s._inverseMatrixDirty=!0,s._transposedMatrixDirty=!0,s.scale=r.scale,s.near=r.near,s.far=r.far,s._onCanvasBoundary=s.scene.canvas.on("boundary",s._needUpdate,x(s)),s}return I(i,[{key:"type",get:function(){return"Ortho"}},{key:"_update",value:function(){var e,t,i,s,r=this.scene,n=.5*this._scale,o=r.viewport.boundary,a=o[2],u=o[3],h=a/u;a>u?(e=-n,t=n,i=n/h,s=-n/h):(e=-n*h,t=n*h,i=n,s=-n),q.orthoMat4c(e,t,s,i,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&&(q.inverseMat4(this._state.matrix,this._state.inverseMatrix),this._inverseMatrixDirty=!1),this._state.inverseMatrix}},{key:"transposedMatrix",get:function(){return this._updateScheduled&&this._doUpdate(),this._transposedMatrixDirty&&(q.transposeMat4(this._state.matrix,this._state.transposedMatrix),this._transposedMatrixDirty=!1),this._state.transposedMatrix}},{key:"unproject",value:function(e,t,i,s,r){var n=this.scene.canvas.canvas,o=n.offsetWidth/2,a=n.offsetHeight/2;return i[0]=(e[0]-o)/o,i[1]=(e[1]-a)/a,i[2]=t,i[3]=1,q.mulMat4v4(this.inverseMatrix,i,s),q.mulVec3Scalar(s,1/s[3]),s[3]=1,s[1]*=-1,q.mulMat4v4(this.camera.inverseViewMatrix,s,r),r}},{key:"destroy",value:function(){m(P(i.prototype),"destroy",this).call(this),this._state.destroy(),this.scene.canvas.off(this._onCanvasBoundary)}}]),i}(),ci=function(e){g(i,fe);var t=y(i);function i(e){var s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return w(this,i),(s=t.call(this,e,r)).camera=e,s._state=new ti({matrix:q.mat4(),inverseMatrix:q.mat4(),transposedMatrix:q.mat4(),near:.1,far:1e4}),s._left=-1,s._right=1,s._bottom=-1,s._top=1,s._inverseMatrixDirty=!0,s._transposedMatrixDirty=!0,s.left=r.left,s.right=r.right,s.bottom=r.bottom,s.top=r.top,s.near=r.near,s.far=r.far,s}return I(i,[{key:"type",get:function(){return"Frustum"}},{key:"_update",value:function(){q.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&&(q.inverseMat4(this._state.matrix,this._state.inverseMatrix),this._inverseMatrixDirty=!1),this._state.inverseMatrix}},{key:"transposedMatrix",get:function(){return this._updateScheduled&&this._doUpdate(),this._transposedMatrixDirty&&(q.transposeMat4(this._state.matrix,this._state.transposedMatrix),this._transposedMatrixDirty=!1),this._state.transposedMatrix}},{key:"unproject",value:function(e,t,i,s,r){var n=this.scene.canvas.canvas,o=n.offsetWidth/2,a=n.offsetHeight/2;return i[0]=(e[0]-o)/o,i[1]=(e[1]-a)/a,i[2]=t,i[3]=1,q.mulMat4v4(this.inverseMatrix,i,s),q.mulVec3Scalar(s,1/s[3]),s[3]=1,s[1]*=-1,q.mulMat4v4(this.camera.inverseViewMatrix,s,r),r}},{key:"destroy",value:function(){m(P(i.prototype),"destroy",this).call(this),this._state.destroy(),m(P(i.prototype),"destroy",this).call(this)}}]),i}(),pi=function(e){g(i,fe);var t=y(i);function i(e){var s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return w(this,i),(s=t.call(this,e,r)).camera=e,s._state=new ti({matrix:q.mat4(),inverseMatrix:q.mat4(),transposedMatrix:q.mat4()}),s._inverseMatrixDirty=!0,s._transposedMatrixDirty=!1,s.matrix=r.matrix,s}return I(i,[{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&&(q.inverseMat4(this._state.matrix,this._state.inverseMatrix),this._inverseMatrixDirty=!1),this._state.inverseMatrix}},{key:"transposedMatrix",get:function(){return this._updateScheduled&&this._doUpdate(),this._transposedMatrixDirty&&(q.transposeMat4(this._state.matrix,this._state.transposedMatrix),this._transposedMatrixDirty=!1),this._state.transposedMatrix}},{key:"unproject",value:function(e,t,i,s,r){var n=this.scene.canvas.canvas,o=n.offsetWidth/2,a=n.offsetHeight/2;return i[0]=(e[0]-o)/o,i[1]=(e[1]-a)/a,i[2]=t,i[3]=1,q.mulMat4v4(this.inverseMatrix,i,s),q.mulVec3Scalar(s,1/s[3]),s[3]=1,s[1]*=-1,q.mulMat4v4(this.camera.inverseViewMatrix,s,r),r}},{key:"destroy",value:function(){m(P(i.prototype),"destroy",this).call(this),this._state.destroy()}}]),i}(),di=q.vec3(),fi=q.vec3(),mi=q.vec3(),vi=q.vec3(),gi=q.vec3(),_i=q.vec3(),yi=q.mat4(),bi=q.mat4(),xi=q.vec3(),Pi=q.vec3(),Ti=q.vec3(),wi=q.vec3(),Mi=function(e){g(i,fe);var t=y(i);function i(e){var s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return w(this,i),(s=t.call(this,e,r))._state=new ti({deviceMatrix:q.mat4(),hasDeviceMatrix:!1,matrix:q.mat4(),normalMatrix:q.mat4(),inverseMatrix:q.mat4()}),s._perspective=new hi(x(s)),s._ortho=new li(x(s)),s._frustum=new ci(x(s)),s._customProjection=new pi(x(s)),s._project=s._perspective,s._eye=q.vec3([0,0,10]),s._look=q.vec3([0,0,0]),s._up=q.vec3([0,1,0]),s._worldUp=q.vec3([0,1,0]),s._worldRight=q.vec3([1,0,0]),s._worldForward=q.vec3([0,0,-1]),s.deviceMatrix=r.deviceMatrix,s.eye=r.eye,s.look=r.look,s.up=r.up,s.worldAxis=r.worldAxis,s.gimbalLock=r.gimbalLock,s.constrainPitch=r.constrainPitch,s.projection=r.projection,s._perspective.on("matrix",(function(){"perspective"===s._projectionType&&s.fire("projMatrix",s._perspective.matrix)})),s._ortho.on("matrix",(function(){"ortho"===s._projectionType&&s.fire("projMatrix",s._ortho.matrix)})),s._frustum.on("matrix",(function(){"frustum"===s._projectionType&&s.fire("projMatrix",s._frustum.matrix)})),s._customProjection.on("matrix",(function(){"customProjection"===s._projectionType&&s.fire("projMatrix",s._customProjection.matrix)})),s}return I(i,[{key:"type",get:function(){return"Camera"}},{key:"_update",value:function(){var e,t=this._state;"ortho"===this.projection?(q.subVec3(this._eye,this._look,xi),q.normalizeVec3(xi,Pi),q.mulVec3Scalar(Pi,1e3,Ti),q.addVec3(this._look,Ti,wi),e=wi):e=this._eye,t.hasDeviceMatrix?(q.lookAtMat4v(e,this._look,this._up,bi),q.mulMat4(t.deviceMatrix,bi,t.matrix)):q.lookAtMat4v(e,this._look,this._up,t.matrix),q.inverseMat4(this._state.matrix,this._state.inverseMatrix),q.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=q.subVec3(this._eye,this._look,di);q.rotationMat4v(.0174532925*e,this._gimbalLock?this._worldUp:this._up,yi),t=q.transformPoint3(yi,t,fi),this.eye=q.addVec3(this._look,t,mi),this.up=q.transformPoint3(yi,this._up,vi)}},{key:"orbitPitch",value:function(e){if(!(this._constrainPitch&&(e=q.dotVec3(this._up,this._worldUp)/q.DEGTORAD)<1)){var t=q.subVec3(this._eye,this._look,di),i=q.cross3Vec3(q.normalizeVec3(t,fi),q.normalizeVec3(this._up,mi));q.rotationMat4v(.0174532925*e,i,yi),t=q.transformPoint3(yi,t,vi),this.up=q.transformPoint3(yi,this._up,gi),this.eye=q.addVec3(t,this._look,_i)}}},{key:"yaw",value:function(e){var t=q.subVec3(this._look,this._eye,di);q.rotationMat4v(.0174532925*e,this._gimbalLock?this._worldUp:this._up,yi),t=q.transformPoint3(yi,t,fi),this.look=q.addVec3(t,this._eye,mi),this._gimbalLock&&(this.up=q.transformPoint3(yi,this._up,vi))}},{key:"pitch",value:function(e){if(!(this._constrainPitch&&(e=q.dotVec3(this._up,this._worldUp)/q.DEGTORAD)<1)){var t=q.subVec3(this._look,this._eye,di),i=q.cross3Vec3(q.normalizeVec3(t,fi),q.normalizeVec3(this._up,mi));q.rotationMat4v(.0174532925*e,i,yi),this.up=q.transformPoint3(yi,this._up,_i),t=q.transformPoint3(yi,t,vi),this.look=q.addVec3(t,this._eye,gi)}}},{key:"pan",value:function(e){var t,i=q.subVec3(this._eye,this._look,di),s=[0,0,0];if(0!==e[0]){var r=q.cross3Vec3(q.normalizeVec3(i,[]),q.normalizeVec3(this._up,fi));t=q.mulVec3Scalar(r,e[0]),s[0]+=t[0],s[1]+=t[1],s[2]+=t[2]}0!==e[1]&&(t=q.mulVec3Scalar(q.normalizeVec3(this._up,mi),e[1]),s[0]+=t[0],s[1]+=t[1],s[2]+=t[2]),0!==e[2]&&(t=q.mulVec3Scalar(q.normalizeVec3(i,vi),e[2]),s[0]+=t[0],s[1]+=t[1],s[2]+=t[2]),this.eye=q.addVec3(this._eye,s,gi),this.look=q.addVec3(this._look,s,_i)}},{key:"zoom",value:function(e){var t=q.subVec3(this._eye,this._look,di),i=Math.abs(q.lenVec3(t,fi)),s=Math.abs(i+e);if(!(s<.5)){var r=q.normalizeVec3(t,mi);this.eye=q.addVec3(this._look,q.mulVec3Scalar(r,s),vi)}}},{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=q.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 q.lenVec3(q.subVec3(this._look,this._eye,di))}},{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:"destroy",value:function(){m(P(i.prototype),"destroy",this).call(this),this._state.destroy()}}]),i}(),Ii=q.vec4(),Ci=q.vec3(),Di=function(){function e(t,i){w(this,e),this._scene=t,this._withSAO=i,this._hash=this._getHash(),this._allocate()}return I(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,i){var s=this._scene,r=s.camera,n=t.model,o=s.canvas.gl,a=t._state,u=a.textureState,h=t._state.origin;if(this._program||(this._allocate(),!this.errors)){e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e,a)),u.bindCommonTextures(this._program,this._uTexturePerObjectIdPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this._uTexturePerObjectIdColorsAndFlags,this._uTextureCameraMatrices,this._uTextureModelMatrices,this._uTexturePerObjectIdOffsets);var l=r.eye;e.pickViewMatrix&&(u.bindPickCameraTexture(this._program,this._uTextureCameraMatrices),l=e.pickOrigin||l);var c=[l[0]-h[0],l[1]-h[1],l[2]-h[2]];o.uniform3fv(this._uCameraEyeRtc,c),o.uniform1i(this._uRenderPass,i);var p=s._sectionPlanesState.sectionPlanes.length;if(p>0)for(var d=s._sectionPlanesState.sectionPlanes,f=t.layerIndex*p,m=n.renderFlags,v=0;v<p;v++){var g=this._uSectionPlanes[v];if(g){var _=m.sectionPlanesActivePerLayer[f+v];if(o.uniform1i(g.active,_?1:0),_){var y=d[v];if(h){var b=Ee(y.dist,y.dir,h,Ci);o.uniform3fv(g.pos,b)}else o.uniform3fv(g.pos,y.pos);o.uniform3fv(g.dir,y.dir)}}}a.numIndices8Bits>0&&(u.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),o.drawArrays(o.TRIANGLES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(u.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),o.drawArrays(o.TRIANGLES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(u.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),o.drawArrays(o.TRIANGLES,0,a.numIndices32Bits)),e.drawElements++}}},{key:"_allocate",value:function(){var e=this._scene,t=e.canvas.gl,i=e._lightsState;if(this._program=new ht(t,this._buildShader()),this._program.errors)this.errors=this._program.errors;else{var s=this._program;this._uRenderPass=s.getLocation("renderPass"),this._uLightAmbient=s.getLocation("lightAmbient"),this._uLightColor=[],this._uLightDir=[],this._uLightPos=[],this._uLightAttenuation=[];for(var r=i.lights,n=0,o=r.length;n<o;n++)switch(r[n].type){case"dir":this._uLightColor[n]=s.getLocation("lightColor"+n),this._uLightPos[n]=null,this._uLightDir[n]=s.getLocation("lightDir"+n);break;case"point":this._uLightColor[n]=s.getLocation("lightColor"+n),this._uLightPos[n]=s.getLocation("lightPos"+n),this._uLightDir[n]=null,this._uLightAttenuation[n]=s.getLocation("lightAttenuation"+n);break;case"spot":this._uLightColor[n]=s.getLocation("lightColor"+n),this._uLightPos[n]=s.getLocation("lightPos"+n),this._uLightDir[n]=s.getLocation("lightDir"+n),this._uLightAttenuation[n]=s.getLocation("lightAttenuation"+n)}this._uSectionPlanes=[];for(var a=0,u=e._sectionPlanesState.sectionPlanes.length;a<u;a++)this._uSectionPlanes.push({active:s.getLocation("sectionPlaneActive"+a),pos:s.getLocation("sectionPlanePos"+a),dir:s.getLocation("sectionPlaneDir"+a)});this._withSAO&&(this._uOcclusionTexture="uOcclusionTexture",this._uSAOParams=s.getLocation("uSAOParams")),e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=s.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=s.getLocation("uCameraEyeRtc")}}},{key:"_bindProgram",value:function(e){var t=this._scene,i=t.canvas.gl,s=this._program,r=t._lightsState.lights,n=t.camera.project;s.bind(),this._uLightAmbient&&i.uniform4fv(this._uLightAmbient,t._lightsState.getAmbientColorAndIntensity());for(var o=0,a=r.length;o<a;o++){var u=r[o];this._uLightColor[o]&&i.uniform4f(this._uLightColor[o],u.color[0],u.color[1],u.color[2],u.intensity),this._uLightPos[o]&&(i.uniform3fv(this._uLightPos[o],u.pos),this._uLightAttenuation[o]&&i.uniform1f(this._uLightAttenuation[o],u.attenuation)),this._uLightDir[o]&&i.uniform3fv(this._uLightDir[o],u.dir)}if(this._withSAO){var h=t.sao;if(h.possible){var l=i.drawingBufferWidth,c=i.drawingBufferHeight;Ii[0]=l,Ii[1]=c,Ii[2]=h.blendCutoff,Ii[3]=h.blendFactor,i.uniform4fv(this._uSAOParams,Ii),this._program.bindTexture(this._uOcclusionTexture,e.occlusionTexture,10)}}if(t.logarithmicDepthBufferEnabled){var p=2/(Math.log(n.far+1)/Math.LN2);i.uniform1f(this._uLogDepthBufFC,p)}}},{key:"_buildShader",value:function(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}},{key:"_buildVertexShader",value:function(){var e,t=this._scene,i=t._sectionPlanesState,s=t._lightsState,r=i.sectionPlanes.length>0,n=[];n.push("#version 300 es"),n.push("// Triangles dataTexture draw 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;"),t.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];"),t.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("uniform vec4 lightAmbient;");for(var o=0,a=s.lights.length;o<a;o++)"ambient"!==(e=s.lights[o]).type&&(n.push("uniform vec4 lightColor"+o+";"),"dir"===e.type&&n.push("uniform vec3 lightDir"+o+";"),"point"===e.type&&n.push("uniform vec3 lightPos"+o+";"),"spot"===e.type&&(n.push("uniform vec3 lightPos"+o+";"),n.push("uniform vec3 lightDir"+o+";")));r&&(n.push("out vec4 vWorldPosition;"),n.push("flat out uint vFlags2;")),n.push("out vec4 vColor;"),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("if (int(flags.x) != renderPass) {"),n.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),n.push(" return;"),n.push("} else {"),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*8+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*8+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0));"),n.push("mat4 entityMatrix = mat4 (texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*8+6, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0));"),n.push("positionsDecodeMatrix = entityMatrix * positionsDecodeMatrix;"),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("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("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),n.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),n.push("float lambertian = 1.0;");for(var u=0,h=s.lights.length;u<h;u++)if("ambient"!==(e=s.lights[u]).type){if("dir"===e.type)"view"===e.space?n.push("viewLightDir = normalize(lightDir"+u+");"):n.push("viewLightDir = normalize((viewMatrix * vec4(lightDir"+u+", 0.0)).xyz);");else if("point"===e.type)"view"===e.space?n.push("viewLightDir = -normalize(lightPos"+u+" - viewPosition.xyz);"):n.push("viewLightDir = -normalize((viewMatrix * vec4(lightPos"+u+", 0.0)).xyz);");else{if("spot"!==e.type)continue;"view"===e.space?n.push("viewLightDir = normalize(lightDir"+u+");"):n.push("viewLightDir = normalize((viewMatrix * vec4(lightDir"+u+", 0.0)).xyz);")}n.push("lambertian = max(dot(-viewNormal, viewLightDir), 0.0);"),n.push("reflectedColor += lambertian * (lightColor"+u+".rgb * lightColor"+u+".a);")}return n.push("vec3 rgb = vec3(color.rgb) / 255.0;"),n.push("vColor = vec4((lightAmbient.rgb * lightAmbient.a * rgb) + (reflectedColor * rgb), float(color.a) / 255.0);"),n.push("vec4 clipPos = projMatrix * viewPosition;"),t.logarithmicDepthBufferEnabled&&(n.push("vFragDepth = 1.0 + clipPos.w;"),n.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),r&&(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,i=t.sectionPlanes.length>0,s=[];if(s.push("#version 300 es"),s.push("// Triangles dataTexture draw fragment shader"),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&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),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 unpackRGBToFloat( const in vec4 v ) {"),s.push(" return dot( v, unPackFactors );"),s.push("}")),i){s.push("in vec4 vWorldPosition;"),s.push("flat in uint vFlags2;");for(var r=0,n=t.sectionPlanes.length;r<n;r++)s.push("uniform bool sectionPlaneActive"+r+";"),s.push("uniform vec3 sectionPlanePos"+r+";"),s.push("uniform vec3 sectionPlaneDir"+r+";")}if(s.push("in vec4 vColor;"),s.push("out vec4 outColor;"),s.push("void main(void) {"),i){s.push(" bool clippable = vFlags2 > 0u;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var o=0,a=t.sectionPlanes.length;o<a;o++)s.push("if (sectionPlaneActive"+o+") {"),s.push(" dist += clamp(dot(-sectionPlaneDir"+o+".xyz, vWorldPosition.xyz - sectionPlanePos"+o+".xyz), 0.0, 1000.0);"),s.push("}");s.push(" if (dist > 0.0) { "),s.push(" discard;"),s.push(" }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),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, unpackRGBToFloat(texture(uOcclusionTexture, uv))) * blendFactor;"),s.push(" outColor = vec4(vColor.rgb * ambient, 1.0);")):s.push(" outColor = vColor;"),s.push("}"),s}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),e}(),Ai=new Float32Array([1,1,1]);q.vec4();var ki=q.vec3(),Ei=function(){function e(t,i){w(this,e),this._scene=t,this._hash=this._getHash(),this._allocate()}return I(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,i){var s=this._scene,r=s.camera,n=t.model,o=s.canvas.gl,a=t._state,u=a.textureState,h=t._state.origin;if(this._program||(this._allocate(),!this.errors)){e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e,a)),u.bindCommonTextures(this._program,this._uTexturePerObjectIdPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this._uTexturePerObjectIdColorsAndFlags,this._uTextureCameraMatrices,this._uTextureModelMatrices,this._uTexturePerObjectIdOffsets);var l=r.eye;e.pickViewMatrix&&(u.bindPickCameraTexture(this._program,this._uTextureCameraMatrices),l=e.pickOrigin||l);var c=[l[0]-h[0],l[1]-h[1],l[2]-h[2]];if(o.uniform3fv(this._uCameraEyeRtc,c),o.uniform1i(this._uRenderPass,i),i===Yt){var p=s.xrayMaterial._state,d=p.fillColor,f=p.fillAlpha;o.uniform4f(this._uColor,d[0],d[1],d[2],f)}else if(i===Wt){var m=s.highlightMaterial._state,v=m.fillColor,g=m.fillAlpha;o.uniform4f(this._uColor,v[0],v[1],v[2],g)}else if(i===Xt){var _=s.selectedMaterial._state,y=_.fillColor,b=_.fillAlpha;o.uniform4f(this._uColor,y[0],y[1],y[2],b)}else o.uniform4fv(this._uColor,Ai);var x=s._sectionPlanesState.sectionPlanes.length;if(x>0)for(var P=s._sectionPlanesState.sectionPlanes,T=t.layerIndex*x,w=n.renderFlags,M=0;M<x;M++){var I=this._uSectionPlanes[M];if(I){var C=w.sectionPlanesActivePerLayer[T+M];if(o.uniform1i(I.active,C?1:0),C){var D=P[M];if(h){var A=Ee(D.dist,D.dir,h,ki);o.uniform3fv(I.pos,A)}else o.uniform3fv(I.pos,D.pos);o.uniform3fv(I.dir,D.dir)}}}a.numIndices8Bits>0&&(u.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),o.drawArrays(o.TRIANGLES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(u.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),o.drawArrays(o.TRIANGLES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(u.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),o.drawArrays(o.TRIANGLES,0,a.numIndices32Bits)),e.drawElements++}}},{key:"_allocate",value:function(){var e=this._scene,t=e.canvas.gl;if(this._program=new ht(t,this._buildShader()),this._program.errors)this.errors=this._program.errors;else{var i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uColor=i.getLocation("color"),this._uSectionPlanes=[];for(var s=0,r=e._sectionPlanesState.sectionPlanes.length;s<r;s++)this._uSectionPlanes.push({active:i.getLocation("sectionPlaneActive"+s),pos:i.getLocation("sectionPlanePos"+s),dir:i.getLocation("sectionPlaneDir"+s)});e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=i.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=i.getLocation("uCameraEyeRtc")}}},{key:"_bindProgram",value:function(e){var t=this._scene,i=t.canvas.gl,s=t.camera.project;if(this._program.bind(),t.logarithmicDepthBufferEnabled){var r=2/(Math.log(s.far+1)/Math.LN2);i.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,i=[];return i.push("#version 300 es"),i.push("// Triangles dataTexture silhouette vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform highp sampler2D uTexturePerObjectIdPositionsDecodeMatrix;"),i.push("uniform lowp usampler2D uTexturePerObjectIdColorsAndFlags;"),i.push("uniform highp sampler2D uTexturePerObjectIdOffsets;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),i.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),i.push("uniform highp sampler2D uTextureCameraMatrices;"),i.push("uniform highp sampler2D uTextureModelMatrices;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;")),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),t&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("void main(void) {"),i.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));"),i.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));"),i.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));"),i.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));"),i.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));"),i.push("int polygonIndex = gl_VertexID / 3;"),i.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.y) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("} else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),i.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),i.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),i.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),i.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),i.push("mat4 positionsDecodeMatrix = mat4 (texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*8+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0));"),i.push("mat4 entityMatrix = mat4 (texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*8+6, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0));"),i.push("positionsDecodeMatrix = entityMatrix * positionsDecodeMatrix;"),i.push("uint solid = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),i.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),i.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),i.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),i.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),i.push("vec3 position;"),i.push("position = positions[gl_VertexID % 3];"),i.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*positionsDecodeMatrix)) * vec4(normal,1)).xyz);"),i.push("if (solid != 1u) {"),i.push("if (isPerspectiveMatrix(projMatrix)) {"),i.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(worldMatrix * positionsDecodeMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),i.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("viewNormal = -viewNormal;"),i.push("}"),i.push("} else {"),i.push("if (viewNormal.z < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("viewNormal = -viewNormal;"),i.push("}"),i.push("}"),i.push("}"),i.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),i.push("vec4 offset = vec4(texelFetch (uTexturePerObjectIdOffsets, objectIndexCoords, 0).rgb, 0.0);"),i.push("worldPosition.xyz = worldPosition.xyz + offset.xyz;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags2 = flags2.r;")),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.sectionPlanes.length>0,s=[];if(s.push("#version 300 es"),s.push("// Triangles dataTexture draw fragment shader"),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&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("varying float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("flat in uint vFlags2;");for(var r=0,n=t.sectionPlanes.length;r<n;r++)s.push("uniform bool sectionPlaneActive"+r+";"),s.push("uniform vec3 sectionPlanePos"+r+";"),s.push("uniform vec3 sectionPlaneDir"+r+";")}if(s.push("uniform vec4 color;"),s.push("out vec4 outColor;"),s.push("void main(void) {"),i){s.push(" bool clippable = vFlags2 > 0u;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var o=0,a=t.sectionPlanes.length;o<a;o++)s.push("if (sectionPlaneActive"+o+") {"),s.push(" dist += clamp(dot(-sectionPlaneDir"+o+".xyz, vWorldPosition.xyz - sectionPlanePos"+o+".xyz), 0.0, 1000.0);"),s.push("}");s.push(" if (dist > 0.0) { "),s.push(" discard;"),s.push(" }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = color;"),s.push("}"),s}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),e}(),Fi=q.vec3(),Ri=new Float32Array([0,0,0,1]),Si=function(){function e(t){w(this,e),this._scene=t,this._hash=this._getHash(),this._allocate()}return I(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,i){var s=t.model,r=s.scene,n=r.camera,o=r.canvas.gl,a=t._state,u=a.textureState,h=t._state.origin;if(this._program||(this._allocate(t),!this.errors)){if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram()),u.bindCommonTextures(this._program,this._uTexturePerObjectIdPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this._uTexturePerObjectIdColorsAndFlags,this._uTextureCameraMatrices,this._uTextureModelMatrices,this._uTexturePerObjectIdOffsets),e.pickViewMatrix&&u.bindPickCameraTexture(this._program,this._uTextureCameraMatrices),o.uniform1i(this._uRenderPass,i),i===qt){var l=r.xrayMaterial._state,c=l.edgeColor,p=l.edgeAlpha;o.uniform4f(this._uColor,c[0],c[1],c[2],p)}else if(i===Zt){var d=r.highlightMaterial._state,f=d.edgeColor,m=d.edgeAlpha;o.uniform4f(this._uColor,f[0],f[1],f[2],m)}else if(i===Qt){var v=r.selectedMaterial._state,g=v.edgeColor,_=v.edgeAlpha;o.uniform4f(this._uColor,g[0],g[1],g[2],_)}else o.uniform4fv(this._uColor,Ri);o.uniformMatrix4fv(this._uViewMatrix,!1,h?De(n.viewMatrix,h):n.viewMatrix),o.uniformMatrix4fv(this._uWorldMatrix,!1,s.worldMatrix);var y=r._sectionPlanesState.sectionPlanes.length;if(y>0)for(var b=r._sectionPlanesState.sectionPlanes,x=t.layerIndex*y,P=s.renderFlags,T=0;T<y;T++){var w=this._uSectionPlanes[T];if(w){var M=P.sectionPlanesActivePerLayer[x+T];if(o.uniform1i(w.active,M?1:0),M){var I=b[T];if(h){var C=Ee(I.dist,I.dir,h,Fi);o.uniform3fv(w.pos,C)}else o.uniform3fv(w.pos,I.pos);o.uniform3fv(w.dir,I.dir)}}}a.numEdgeIndices8Bits>0&&(u.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,8),o.drawArrays(o.LINES,0,a.numEdgeIndices8Bits)),a.numEdgeIndices16Bits>0&&(u.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,16),o.drawArrays(o.LINES,0,a.numEdgeIndices16Bits)),a.numEdgeIndices32Bits>0&&(u.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,32),o.drawArrays(o.LINES,0,a.numEdgeIndices32Bits)),e.drawElements++}}},{key:"_allocate",value:function(){var e=this._scene,t=e.canvas.gl;if(this._program=new ht(t,this._buildShader()),this._program.errors)this.errors=this._program.errors;else{var i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uColor=i.getLocation("color"),this._uSectionPlanes=[];for(var s=0,r=e._sectionPlanesState.sectionPlanes.length;s<r;s++)this._uSectionPlanes.push({active:i.getLocation("sectionPlaneActive"+s),pos:i.getLocation("sectionPlanePos"+s),dir:i.getLocation("sectionPlaneDir"+s)});e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=i.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,i=this._program,s=e.camera.project;if(i.bind(),e.logarithmicDepthBufferEnabled){var r=2/(Math.log(s.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,i=[];return i.push("#version 300 es"),i.push("// Batched geometry edges drawing vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform highp sampler2D uTexturePerObjectIdPositionsDecodeMatrix;"),i.push("uniform lowp usampler2D uTexturePerObjectIdColorsAndFlags;"),i.push("uniform highp sampler2D uTexturePerObjectIdOffsets;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdEdgeIndices;"),i.push("uniform mediump usampler2D uTexturePerEdgeIdPortionIds;"),i.push("uniform highp sampler2D uTextureCameraMatrices;"),i.push("uniform highp sampler2D uTextureModelMatrices;"),i.push("uniform vec4 color;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.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));"),i.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));"),i.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));"),i.push("int edgeIndex = gl_VertexID / 2;"),i.push("int h_packed_object_id_index = (edgeIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (edgeIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerEdgeIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.z) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("} else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedEdgeIndexBaseOffset = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+6, objectIndexCoords.y), 0));"),i.push("int edgeIndexBaseOffset = (packedEdgeIndexBaseOffset.r << 24) + (packedEdgeIndexBaseOffset.g << 16) + (packedEdgeIndexBaseOffset.b << 8) + packedEdgeIndexBaseOffset.a;"),i.push("int h_index = (edgeIndex - edgeIndexBaseOffset) & 4095;"),i.push("int v_index = (edgeIndex - edgeIndexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdEdgeIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("int indexPositionH = uniqueVertexIndexes[gl_VertexID % 2] & 4095;"),i.push("int indexPositionV = uniqueVertexIndexes[gl_VertexID % 2] >> 12;"),i.push("mat4 positionsDecodeMatrix = mat4 (texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*8+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0));"),i.push("mat4 entityMatrix = mat4 (texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*8+6, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0));"),i.push("positionsDecodeMatrix = entityMatrix * positionsDecodeMatrix;"),i.push("uvec4 flags = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("vec3 position = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH, indexPositionV), 0));"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),i.push("vec4 offset = vec4(texelFetch (uTexturePerObjectIdOffsets, objectIndexCoords, 0).rgb, 0.0);"),i.push("worldPosition.xyz = worldPosition.xyz + offset.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags2 = flags2.r;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("vColor = vec4(color.r, color.g, color.b, color.a);"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.sectionPlanes.length>0,s=[];if(s.push("#version 300 es"),s.push("// Batched geometry edges drawing fragment shader"),e.logarithmicDepthBufferEnabled&&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&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("flat in uint vFlags2;");for(var r=0,n=t.sectionPlanes.length;r<n;r++)s.push("uniform bool sectionPlaneActive"+r+";"),s.push("uniform vec3 sectionPlanePos"+r+";"),s.push("uniform vec3 sectionPlaneDir"+r+";")}if(s.push("in vec4 vColor;"),s.push("out vec4 outColor;"),s.push("void main(void) {"),i){s.push(" bool clippable = vFlags2 > 0u;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var o=0,a=t.sectionPlanes.length;o<a;o++)s.push("if (sectionPlaneActive"+o+") {"),s.push(" dist += clamp(dot(-sectionPlaneDir"+o+".xyz, vWorldPosition.xyz - sectionPlanePos"+o+".xyz), 0.0, 1000.0);"),s.push("}");s.push(" if (dist > 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = vColor;"),s.push("}"),s}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),e}(),Oi=q.vec3(),Bi=function(){function e(t){w(this,e),this._scene=t,this._hash=this._getHash(),this._allocate()}return I(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,i){var s=t.model,r=s.scene;r.camera;var n=r.canvas.gl,o=t._state,a=o.textureState,u=t._state.origin;if(this._program||(this._allocate(t),!this.errors)){e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram()),a.bindCommonTextures(this._program,this._uTexturePerObjectIdPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this._uTexturePerObjectIdColorsAndFlags,this._uTextureCameraMatrices,this._uTextureModelMatrices,this._uTexturePerObjectIdOffsets),e.pickViewMatrix&&a.bindPickCameraTexture(this._program,this._uTextureCameraMatrices),n.uniform1i(this._uRenderPass,i);var h=r._sectionPlanesState.sectionPlanes.length;if(h>0)for(var l=r._sectionPlanesState.sectionPlanes,c=t.layerIndex*h,p=s.renderFlags,d=0;d<h;d++){var f=this._uSectionPlanes[d];if(f){var m=p.sectionPlanesActivePerLayer[c+d];if(n.uniform1i(f.active,m?1:0),m){var v=l[d];if(u){var g=Ee(v.dist,v.dir,u,Oi);n.uniform3fv(f.pos,g)}else n.uniform3fv(f.pos,v.pos);n.uniform3fv(f.dir,v.dir)}}}o.numEdgeIndices8Bits>0&&(a.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,8),n.drawArrays(n.LINES,0,o.numEdgeIndices8Bits)),o.numEdgeIndices16Bits>0&&(a.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,16),n.drawArrays(n.LINES,0,o.numEdgeIndices16Bits)),o.numEdgeIndices32Bits>0&&(a.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,32),n.drawArrays(n.LINES,0,o.numEdgeIndices32Bits)),e.drawElements++}}},{key:"_allocate",value:function(){var e=this._scene,t=e.canvas.gl;if(this._program=new ht(t,this._buildShader()),this._program.errors)this.errors=this._program.errors;else{var i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uSectionPlanes=[];for(var s=0,r=e._sectionPlanesState.sectionPlanes.length;s<r;s++)this._uSectionPlanes.push({active:i.getLocation("sectionPlaneActive"+s),pos:i.getLocation("sectionPlanePos"+s),dir:i.getLocation("sectionPlaneDir"+s)});e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=i.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,i=this._program,s=e.camera.project;if(i.bind(),e.logarithmicDepthBufferEnabled){var r=2/(Math.log(s.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,i=[];return i.push("#version 300 es"),i.push("// Batched geometry edges drawing vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform highp sampler2D uTexturePerObjectIdPositionsDecodeMatrix;"),i.push("uniform lowp usampler2D uTexturePerObjectIdColorsAndFlags;"),i.push("uniform highp sampler2D uTexturePerObjectIdOffsets;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdEdgeIndices;"),i.push("uniform mediump usampler2D uTexturePerEdgeIdPortionIds;"),i.push("uniform highp sampler2D uTextureCameraMatrices;"),i.push("uniform highp sampler2D uTextureModelMatrices;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.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));"),i.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));"),i.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));"),i.push("int edgeIndex = gl_VertexID / 2;"),i.push("int h_packed_object_id_index = (edgeIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (edgeIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerEdgeIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.z) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("} else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedEdgeIndexBaseOffset = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+6, objectIndexCoords.y), 0));"),i.push("int edgeIndexBaseOffset = (packedEdgeIndexBaseOffset.r << 24) + (packedEdgeIndexBaseOffset.g << 16) + (packedEdgeIndexBaseOffset.b << 8) + packedEdgeIndexBaseOffset.a;"),i.push("int h_index = (edgeIndex - edgeIndexBaseOffset) & 4095;"),i.push("int v_index = (edgeIndex - edgeIndexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdEdgeIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("int indexPositionH = uniqueVertexIndexes[gl_VertexID % 2] & 4095;"),i.push("int indexPositionV = uniqueVertexIndexes[gl_VertexID % 2] >> 12;"),i.push("mat4 positionsDecodeMatrix = mat4 (texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*8+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0));"),i.push("mat4 entityMatrix = mat4 (texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*8+6, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0));"),i.push("positionsDecodeMatrix = entityMatrix * positionsDecodeMatrix;"),i.push("uvec4 flags = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("vec3 position = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH, indexPositionV), 0));"),i.push("uvec4 color = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push("if (color.a == 0u) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("};"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),i.push("vec4 offset = vec4(texelFetch (uTexturePerObjectIdOffsets, objectIndexCoords, 0).rgb, 0.0);"),i.push("worldPosition.xyz = worldPosition.xyz + offset.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags2 = flags2.r;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("vec4 rgb = vec4(color.rgba);"),i.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);"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.sectionPlanes.length>0,s=[];if(s.push("#version 300 es"),s.push("// Batched geometry edges drawing fragment shader"),e.logarithmicDepthBufferEnabled&&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&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("flat in uint vFlags2;");for(var r=0,n=t.sectionPlanes.length;r<n;r++)s.push("uniform bool sectionPlaneActive"+r+";"),s.push("uniform vec3 sectionPlanePos"+r+";"),s.push("uniform vec3 sectionPlaneDir"+r+";")}if(s.push("in vec4 vColor;"),s.push("out vec4 outColor;"),s.push("void main(void) {"),i){s.push(" bool clippable = vFlags2 > 0u;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var o=0,a=t.sectionPlanes.length;o<a;o++)s.push("if (sectionPlaneActive"+o+") {"),s.push(" dist += clamp(dot(-sectionPlaneDir"+o+".xyz, vWorldPosition.xyz - sectionPlanePos"+o+".xyz), 0.0, 1000.0);"),s.push("}");s.push(" if (dist > 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = vColor;"),s.push("}"),s}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),e}(),Li=q.vec3(),Ni=function(){function e(t){w(this,e),this._scene=t,this._hash=this._getHash(),this._allocate()}return I(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,i){var s=t.model,r=s.scene,n=r.camera,o=r.canvas.gl,a=t._state,u=a.textureState,h=t._state.origin;this._program||this._allocate(t),e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),u.bindCommonTextures(this._program,this._uTexturePerObjectIdPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this._uTexturePerObjectIdColorsAndFlags,this._uTextureCameraMatrices,this._uTextureModelMatrices,this._uTexturePerObjectIdOffsets);var l=n.eye;e.pickViewMatrix&&(u.bindPickCameraTexture(this._program,this._uTextureCameraMatrices),l=e.pickOrigin||l);var c=[l[0]-h[0],l[1]-h[1],l[2]-h[2]];if(o.uniform3fv(this._uCameraEyeRtc,c),o.uniform1i(this._uRenderPass,i),r.logarithmicDepthBufferEnabled){var p=2/(Math.log(n.project.far+1)/Math.LN2);o.uniform1f(this._uLogDepthBufFC,p)}var d=r._sectionPlanesState.sectionPlanes.length;if(d>0)for(var f=r._sectionPlanesState.sectionPlanes,m=t.layerIndex*d,v=s.renderFlags,g=0;g<d;g++){var _=this._uSectionPlanes[g];if(_){var y=v.sectionPlanesActivePerLayer[m+g];if(o.uniform1i(_.active,y?1:0),y){var b=f[g];if(h){var x=Ee(b.dist,b.dir,h,Li);o.uniform3fv(_.pos,x)}else o.uniform3fv(_.pos,b.pos);o.uniform3fv(_.dir,b.dir)}}}a.numIndices8Bits>0&&(u.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),o.drawArrays(o.TRIANGLES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(u.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),o.drawArrays(o.TRIANGLES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(u.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),o.drawArrays(o.TRIANGLES,0,a.numIndices32Bits)),e.drawElements++}},{key:"_allocate",value:function(){var e=this._scene,t=e.canvas.gl;if(this._program=new ht(t,this._buildShader()),this._program.errors)this.errors=this._program.errors;else{var i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPickInvisible=i.getLocation("pickInvisible"),this._uSectionPlanes=[];for(var s=0,r=e._sectionPlanesState.sectionPlanes.length;s<r;s++)this._uSectionPlanes.push({active:i.getLocation("sectionPlaneActive"+s),pos:i.getLocation("sectionPlanePos"+s),dir:i.getLocation("sectionPlaneDir"+s)});this._withSAO&&(this._uOcclusionTexture="uOcclusionTexture",this._uSAOParams=i.getLocation("uSAOParams")),e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=i.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=i.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,i=[];return i.push("#version 300 es"),i.push("// Batched geometry picking vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform bool pickInvisible;"),i.push("uniform highp sampler2D uTexturePerObjectIdPositionsDecodeMatrix;"),i.push("uniform lowp usampler2D uTexturePerObjectIdColorsAndFlags;"),i.push("uniform highp sampler2D uTexturePerObjectIdOffsets;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),i.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),i.push("uniform highp sampler2D uTextureCameraMatrices;"),i.push("uniform highp sampler2D uTextureModelMatrices;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;")),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),t&&(i.push("smooth out vec4 vWorldPosition;"),i.push("flat out uvec4 vFlags2;")),i.push("out vec4 vPickColor;"),i.push("void main(void) {"),i.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));"),i.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));"),i.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));"),i.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));"),i.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));"),i.push("int polygonIndex = gl_VertexID / 3;"),i.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.w) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("} else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),i.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),i.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),i.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),i.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),i.push("mat4 positionsDecodeMatrix = mat4 (texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*8+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0));"),i.push("mat4 entityMatrix = mat4 (texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*8+6, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0));"),i.push("positionsDecodeMatrix = entityMatrix * positionsDecodeMatrix;"),i.push("uint solid = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),i.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),i.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),i.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),i.push("uvec4 color = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push("if (color.a == 0u) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("};"),i.push("vPickColor = vec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+1, objectIndexCoords.y), 0)) / 255.0;"),i.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),i.push("vec3 position;"),i.push("position = positions[gl_VertexID % 3];"),i.push("if (solid != 1u) {"),i.push("if (isPerspectiveMatrix(projMatrix)) {"),i.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(worldMatrix * positionsDecodeMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),i.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("}"),i.push("} else {"),i.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*positionsDecodeMatrix)) * vec4(normal,1)).xyz);"),i.push("if (viewNormal.z < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("}"),i.push("}"),i.push("}"),i.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),i.push("vec4 offset = vec4(texelFetch (uTexturePerObjectIdOffsets, objectIndexCoords, 0).rgb, 0.0);"),i.push("worldPosition.xyz = worldPosition.xyz + offset.xyz;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags2 = flags2;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push(" }"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.sectionPlanes.length>0,s=[];if(s.push("#version 300 es"),s.push("// Batched geometry picking fragment shader"),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&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("flat in uvec4 vFlags2;");for(var r=0;r<t.sectionPlanes.length;r++)s.push("uniform bool sectionPlaneActive"+r+";"),s.push("uniform vec3 sectionPlanePos"+r+";"),s.push("uniform vec3 sectionPlaneDir"+r+";")}if(s.push("in vec4 vPickColor;"),s.push("out vec4 outPickColor;"),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(r=0;r<t.sectionPlanes.length;r++)s.push(" if (sectionPlaneActive"+r+") {"),s.push(" dist += clamp(dot(-sectionPlaneDir"+r+".xyz, vWorldPosition.xyz - sectionPlanePos"+r+".xyz), 0.0, 1000.0);"),s.push(" }");s.push(" if (dist > 0.0) { discard; }"),s.push(" }")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outPickColor = vPickColor; "),s.push("}"),s}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),e}(),ji=q.vec3(),Gi=function(){function e(t){w(this,e),this._scene=t,this._hash=this._getHash(),this._allocate()}return I(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,i){var s=t.model,r=s.scene,n=r.camera,o=r.canvas.gl,a=t._state,u=a.textureState,h=t._state.origin;this._program||this._allocate(),e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram()),u.bindCommonTextures(this._program,this._uTexturePerObjectIdPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this._uTexturePerObjectIdColorsAndFlags,this._uTextureCameraMatrices,this._uTextureModelMatrices,this._uTexturePerObjectIdOffsets);var l=n.eye;e.pickViewMatrix&&(u.bindPickCameraTexture(this._program,this._uTextureCameraMatrices),l=e.pickOrigin||l);var c=[l[0]-h[0],l[1]-h[1],l[2]-h[2]];if(o.uniform3fv(this._uCameraEyeRtc,c),o.uniform1i(this._uRenderPass,i),o.uniform1i(this._uPickInvisible,e.pickInvisible),o.uniform1f(this._uPickZNear,e.pickZNear),o.uniform1f(this._uPickZFar,e.pickZFar),r.logarithmicDepthBufferEnabled){var p=2/(Math.log(e.pickZFar+1)/Math.LN2);o.uniform1f(this._uLogDepthBufFC,p)}var d=r._sectionPlanesState.sectionPlanes.length;if(d>0)for(var f=r._sectionPlanesState.sectionPlanes,m=t.layerIndex*d,v=s.renderFlags,g=0;g<d;g++){var _=this._uSectionPlanes[g];if(_){var y=v.sectionPlanesActivePerLayer[m+g];if(o.uniform1i(_.active,y?1:0),y){var b=f[g];if(h){var x=Ee(b.dist,b.dir,h,ji);o.uniform3fv(_.pos,x)}else o.uniform3fv(_.pos,b.pos);o.uniform3fv(_.dir,b.dir)}}}a.numIndices8Bits>0&&(u.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),o.drawArrays(o.TRIANGLES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(u.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),o.drawArrays(o.TRIANGLES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(u.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),o.drawArrays(o.TRIANGLES,0,a.numIndices32Bits)),e.drawElements++}},{key:"_allocate",value:function(){var e=this._scene,t=e.canvas.gl;if(this._program=new ht(t,this._buildShader()),this._program.errors)this.errors=this._program.errors;else{var i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPickInvisible=i.getLocation("pickInvisible"),this._uSectionPlanes=[];for(var s=0,r=e._sectionPlanesState.sectionPlanes.length;s<r;s++)this._uSectionPlanes.push({active:i.getLocation("sectionPlaneActive"+s),pos:i.getLocation("sectionPlanePos"+s),dir:i.getLocation("sectionPlaneDir"+s)});this._aPackedVertexId=i.getAttribute("packedVertexId"),this._uPickZNear=i.getLocation("pickZNear"),this._uPickZFar=i.getLocation("pickZFar"),e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=i.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=i.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,i=[];return i.push("#version 300 es"),i.push("// Triangles dataTexture pick depth vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform bool pickInvisible;"),i.push("uniform highp sampler2D uTexturePerObjectIdPositionsDecodeMatrix;"),i.push("uniform lowp usampler2D uTexturePerObjectIdColorsAndFlags;"),i.push("uniform highp sampler2D uTexturePerObjectIdOffsets;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),i.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),i.push("uniform highp sampler2D uTextureCameraMatrices;"),i.push("uniform highp sampler2D uTextureModelMatrices;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;")),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("out vec4 vViewPosition;"),i.push("void main(void) {"),i.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));"),i.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));"),i.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));"),i.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));"),i.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));"),i.push("int polygonIndex = gl_VertexID / 3;"),i.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.w) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("} else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),i.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),i.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),i.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),i.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),i.push("mat4 positionsDecodeMatrix = mat4 (texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*8+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0));"),i.push("mat4 entityMatrix = mat4 (texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*8+6, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0));"),i.push("positionsDecodeMatrix = entityMatrix * positionsDecodeMatrix;"),i.push("uint solid = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),i.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),i.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),i.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),i.push("uvec4 color = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push("if (color.a == 0u) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("};"),i.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),i.push("vec3 position;"),i.push("position = positions[gl_VertexID % 3];"),i.push("if (solid != 1u) {"),i.push("if (isPerspectiveMatrix(projMatrix)) {"),i.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(worldMatrix * positionsDecodeMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),i.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("}"),i.push("} else {"),i.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*positionsDecodeMatrix)) * vec4(normal,1)).xyz);"),i.push("if (viewNormal.z < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("}"),i.push("}"),i.push("}"),i.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),i.push("vec4 offset = vec4(texelFetch (uTexturePerObjectIdOffsets, objectIndexCoords, 0).rgb, 0.0);"),i.push("worldPosition.xyz = worldPosition.xyz + offset.xyz;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags2 = flags2.r;")),i.push("vViewPosition = viewPosition;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push(" }"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.sectionPlanes.length>0,s=[];if(s.push("#version 300 es"),s.push("// Triangles dataTexture pick depth fragment shader"),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&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),s.push("uniform float pickZNear;"),s.push("uniform float pickZFar;"),i){s.push("in vec4 vWorldPosition;"),s.push("flat in uint vFlags2;");for(var r=0;r<t.sectionPlanes.length;r++)s.push("uniform bool sectionPlaneActive"+r+";"),s.push("uniform vec3 sectionPlanePos"+r+";"),s.push("uniform vec3 sectionPlaneDir"+r+";")}if(s.push("in vec4 vViewPosition;"),s.push("vec4 packDepth(const in float depth) {"),s.push(" const vec4 bitShift = vec4(256.0*256.0*256.0, 256.0*256.0, 256.0, 1.0);"),s.push(" const vec4 bitMask = vec4(0.0, 1.0/256.0, 1.0/256.0, 1.0/256.0);"),s.push(" vec4 res = fract(depth * bitShift);"),s.push(" res -= res.xxyz * bitMask;"),s.push(" return res;"),s.push("}"),s.push("out vec4 outPackedDepth;"),s.push("void main(void) {"),i){s.push(" bool clippable = vFlags2 > 0u;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(r=0;r<t.sectionPlanes.length;r++)s.push(" if (sectionPlaneActive"+r+") {"),s.push(" dist += clamp(dot(-sectionPlaneDir"+r+".xyz, vWorldPosition.xyz - sectionPlanePos"+r+".xyz), 0.0, 1000.0);"),s.push(" }");s.push(" if (dist > 0.0) { discard; }"),s.push(" }")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" float zNormalizedDepth = abs((pickZNear + vViewPosition.z) / (pickZFar - pickZNear));"),s.push(" outPackedDepth = packDepth(zNormalizedDepth); "),s.push("}"),s}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),e}(),Hi=q.vec3(),Vi=function(){function e(t){w(this,e),this._scene=t,this._hash=this._getHash(),this._allocate()}return I(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,i){var s=t.model,r=s.scene,n=r.camera,o=r.canvas.gl,a=t._state,u=a.textureState,h=t._state.origin;this._program||this._allocate(t),e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram()),u.bindCommonTextures(this._program,this._uTexturePerObjectIdPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this._uTexturePerObjectIdColorsAndFlags,this._uTextureCameraMatrices,this._uTextureModelMatrices,this._uTexturePerObjectIdOffsets);var l=n.eye;e.pickViewMatrix&&(u.bindPickCameraTexture(this._program,this._uTextureCameraMatrices),l=e.pickOrigin||l);var c=[l[0]-h[0],l[1]-h[1],l[2]-h[2]];if(o.uniform3fv(this._uCameraEyeRtc,c),o.uniform1i(this._uRenderPass,i),o.uniform3fv(this._uCameraEyeRtc,c),o.uniform1i(this._uPickInvisible,e.pickInvisible),r.logarithmicDepthBufferEnabled){var p=2/(Math.log(n.project.far+1)/Math.LN2);o.uniform1f(this._uLogDepthBufFC,p)}var d=r._sectionPlanesState.sectionPlanes.length;if(d>0)for(var f=r._sectionPlanesState.sectionPlanes,m=t.layerIndex*d,v=s.renderFlags,g=0;g<d;g++){var _=this._uSectionPlanes[g];if(_){var y=v.sectionPlanesActivePerLayer[m+g];if(o.uniform1i(_.active,y?1:0),y){var b=f[g];if(h){var x=Ee(b.dist,b.dir,h,Hi);o.uniform3fv(_.pos,x)}else o.uniform3fv(_.pos,b.pos);o.uniform3fv(_.dir,b.dir)}}}a.numIndices8Bits>0&&(u.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),o.drawArrays(o.TRIANGLES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(u.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),o.drawArrays(o.TRIANGLES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(u.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),o.drawArrays(o.TRIANGLES,0,a.numIndices32Bits)),e.drawElements++}},{key:"_allocate",value:function(){var e=this._scene,t=e.canvas.gl;if(this._program=new ht(t,this._buildShader()),this._program.errors)this.errors=this._program.errors;else{var i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPickInvisible=i.getLocation("pickInvisible"),this._uSectionPlanes=[];for(var s=0,r=e._sectionPlanesState.sectionPlanes.length;s<r;s++)this._uSectionPlanes.push({active:i.getLocation("sectionPlaneActive"+s),pos:i.getLocation("sectionPlanePos"+s),dir:i.getLocation("sectionPlaneDir"+s)});e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=i.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=i.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,i=[];return i.push("#version 300 es"),i.push("// Triangles dataTexture pick normals vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform bool pickInvisible;"),i.push("uniform highp sampler2D uTexturePerObjectIdPositionsDecodeMatrix;"),i.push("uniform lowp usampler2D uTexturePerObjectIdColorsAndFlags;"),i.push("uniform highp sampler2D uTexturePerObjectIdOffsets;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),i.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),i.push("uniform highp sampler2D uTextureCameraMatrices;"),i.push("uniform highp sampler2D uTextureModelMatrices;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;")),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("out vec3 vWorldNormal;"),i.push("void main(void) {"),i.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));"),i.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));"),i.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));"),i.push("int polygonIndex = gl_VertexID / 3;"),i.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.w) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("} else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),i.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),i.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),i.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),i.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),i.push("mat4 positionsDecodeMatrix = mat4 (texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*8+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0));"),i.push("mat4 entityMatrix = mat4 (texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*8+6, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0));"),i.push("positionsDecodeMatrix = entityMatrix * positionsDecodeMatrix;"),i.push("uint solid = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),i.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),i.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),i.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),i.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),i.push("vec3 position;"),i.push("position = positions[gl_VertexID % 3];"),i.push("if (solid != 1u) {"),i.push("if (isPerspectiveMatrix(projMatrix)) {"),i.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(worldMatrix * positionsDecodeMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),i.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("normal = -normal;"),i.push("}"),i.push("} else {"),i.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*positionsDecodeMatrix)) * vec4(normal,1)).xyz);"),i.push("if (viewNormal.z < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("normal = -normal;"),i.push("}"),i.push("}"),i.push("}"),i.push("normal = -normal;"),i.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),i.push("vec4 offset = vec4(texelFetch (uTexturePerObjectIdOffsets, objectIndexCoords, 0).rgb, 0.0);"),i.push("worldPosition.xyz = worldPosition.xyz + offset.xyz;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vWorldNormal = normal.xyz;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags2 = flags2.w;")),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.sectionPlanes.length>0,s=[];if(s.push("#version 300 es"),s.push("// Triangles dataTexture pick normals fragment shader"),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&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("flat in uint vFlags2;");for(var r=0;r<t.sectionPlanes.length;r++)s.push("uniform bool sectionPlaneActive"+r+";"),s.push("uniform vec3 sectionPlanePos"+r+";"),s.push("uniform vec3 sectionPlaneDir"+r+";")}if(s.push("in vec3 vWorldNormal;"),s.push("out vec4 outNormal;"),s.push("void main(void) {"),i){s.push(" bool clippable = vFlags2 > 0u;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(r=0;r<t.sectionPlanes.length;r++)s.push(" if (sectionPlaneActive"+r+") {"),s.push(" dist += clamp(dot(-sectionPlaneDir"+r+".xyz, vWorldPosition.xyz - sectionPlanePos"+r+".xyz), 0.0, 1000.0);"),s.push(" }");s.push(" if (dist > 0.0) { discard; }"),s.push(" }")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outNormal = vec4((vWorldNormal * 0.5) + 0.5, 1.0);"),s.push("}"),s}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),e}();q.vec3();var Ui=function(){function e(t){w(this,e),this._scene=t,this._hash=this._getHash(),this._allocate()}return I(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,i){}},{key:"_allocate",value:function(){var e=this._scene,t=e.canvas.gl;if(this._program=new ht(t,this._buildShader()),this._program.errors)this.errors=this._program.errors;else{var i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPositionsDecodeMatrix=i.getLocation("positionsDecodeMatrix"),this._uWorldMatrix=i.getLocation("worldMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(var s=0,r=e._sectionPlanesState.sectionPlanes.length;s<r;s++)this._uSectionPlanes.push({active:i.getLocation("sectionPlaneActive"+s),pos:i.getLocation("sectionPlanePos"+s),dir:i.getLocation("sectionPlaneDir"+s)});this._aPosition=i.getAttribute("position"),this._aOffset=i.getAttribute("offset"),this._aColor=i.getAttribute("color"),this._aFlags=i.getAttribute("flags"),this._aFlags2=i.getAttribute("flags2"),e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=i.getLocation("logDepthBufFC"))}}},{key:"_bindProgram",value:function(){var e=this._scene,t=e.canvas.gl,i=e.camera.project;if(this._program.bind(),t.uniformMatrix4fv(this._uProjMatrix,!1,i.matrix),e.logarithmicDepthBufferEnabled){var s=2/(Math.log(i.far+1)/Math.LN2);t.uniform1f(this._uLogDepthBufFC,s)}}},{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,i=[];return i.push("// Triangles dataTexture occlusion vertex shader"),e.logarithmicDepthBufferEnabled&&Ze.SUPPORTED_EXTENSIONS.EXT_frag_depth&&i.push("#extension GL_EXT_frag_depth : enable"),i.push("uniform int renderPass;"),i.push("attribute vec3 position;"),e.entityOffsetsEnabled&&i.push("attribute vec3 offset;"),i.push("attribute vec4 color;"),i.push("attribute vec4 flags;"),i.push("attribute vec4 flags2;"),i.push("uniform mat4 worldMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform mat4 positionsDecodeMatrix;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),Ze.SUPPORTED_EXTENSIONS.EXT_frag_depth&&i.push("varying float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("varying float isPerspective;")),t&&(i.push("varying vec4 vWorldPosition;"),i.push("varying vec4 vFlags2;")),i.push("void main(void) {"),i.push("if (int(flags.x) != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags2 = flags2;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(Ze.SUPPORTED_EXTENSIONS.EXT_frag_depth?i.push("vFragDepth = 1.0 + clipPos.w;"):(i.push("clipPos.z = log2( max( 1e-6, clipPos.w + 1.0 ) ) * logDepthBufFC - 1.0;"),i.push("clipPos.z *= clipPos.w;")),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push(" }"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.sectionPlanes.length>0,s=[];if(s.push("// Triangles dataTexture occlusion 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;")),i){s.push("varying vec4 vWorldPosition;"),s.push("varying vec4 vFlags2;");for(var r=0;r<t.sectionPlanes.length;r++)s.push("uniform bool sectionPlaneActive"+r+";"),s.push("uniform vec3 sectionPlanePos"+r+";"),s.push("uniform vec3 sectionPlaneDir"+r+";")}if(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 n=0;n<t.sectionPlanes.length;n++)s.push(" if (sectionPlaneActive"+n+") {"),s.push(" dist += clamp(dot(-sectionPlaneDir"+n+".xyz, vWorldPosition.xyz - sectionPlanePos"+n+".xyz), 0.0, 1000.0);"),s.push(" }");s.push(" if (dist > 0.0) { discard; }"),s.push(" }")}return 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(" gl_FragColor = vec4(0.0, 0.0, 1.0, 1.0); "),s.push("}"),s}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),e}();q.vec4();var zi=q.vec3(),Wi=function(){function e(t){w(this,e),this._scene=t,this._allocate(),this._hash=this._getHash()}return I(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,i){var s=this._scene,r=s.camera,n=t.model,o=s.canvas.gl,a=t._state,u=a.textureState,h=t._state.origin;if(this._program||(this._allocate(),!this.errors)){e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e,a)),u.bindCommonTextures(this._program,this._uTexturePerObjectIdPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this._uTexturePerObjectIdColorsAndFlags,this._uTextureCameraMatrices,this._uTextureModelMatrices,this._uTexturePerObjectIdOffsets);var l=r.eye;e.pickViewMatrix&&(u.bindPickCameraTexture(this._program,this._uTextureCameraMatrices),l=e.pickOrigin||l);var c=[l[0]-h[0],l[1]-h[1],l[2]-h[2]];o.uniform3fv(this._uCameraEyeRtc,c),o.uniform1i(this._uRenderPass,i);var p=s._sectionPlanesState.sectionPlanes.length;if(p>0)for(var d=s._sectionPlanesState.sectionPlanes,f=t.layerIndex*p,m=n.renderFlags,v=0;v<p;v++){var g=this._uSectionPlanes[v];if(g){var _=m.sectionPlanesActivePerLayer[f+v];if(o.uniform1i(g.active,_?1:0),_){var y=d[v];if(h){var b=Ee(y.dist,y.dir,h,zi);o.uniform3fv(g.pos,b)}else o.uniform3fv(g.pos,y.pos);o.uniform3fv(g.dir,y.dir)}}}a.numIndices8Bits>0&&(u.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),o.drawArrays(o.TRIANGLES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(u.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),o.drawArrays(o.TRIANGLES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(u.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),o.drawArrays(o.TRIANGLES,0,a.numIndices32Bits)),e.drawElements++}}},{key:"_allocate",value:function(){var e=this._scene,t=e.canvas.gl;if(this._program=new ht(t,this._buildShader()),this._program.errors)this.errors=this._program.errors;else{var i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPositionsDecodeMatrix=i.getLocation("positionsDecodeMatrix"),this._uWorldMatrix=i.getLocation("worldMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(var s=0,r=e._sectionPlanesState.sectionPlanes.length;s<r;s++)this._uSectionPlanes.push({active:i.getLocation("sectionPlaneActive"+s),pos:i.getLocation("sectionPlanePos"+s),dir:i.getLocation("sectionPlaneDir"+s)});e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=i.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=i.getLocation("uCameraEyeRtc")}}},{key:"_bindProgram",value:function(e){var t=this._scene,i=t.canvas.gl,s=this._program,r=t.camera.project;if(s.bind(),i.uniformMatrix4fv(this._uProjMatrix,!1,r.matrix),t.logarithmicDepthBufferEnabled){var n=2/(Math.log(r.far+1)/Math.LN2);i.uniform1f(this._uLogDepthBufFC,n)}}},{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 i=t.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Triangles dataTexture draw vertex shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("precision highp usampler2D;"),s.push("precision highp isampler2D;"),s.push("precision highp sampler2D;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("precision mediump usampler2D;"),s.push("precision mediump isampler2D;"),s.push("precision mediump sampler2D;"),s.push("#endif"),s.push("uniform int renderPass;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("uniform highp sampler2D uTexturePerObjectIdPositionsDecodeMatrix;"),s.push("uniform lowp usampler2D uTexturePerObjectIdColorsAndFlags;"),s.push("uniform highp sampler2D uTexturePerObjectIdOffsets;"),s.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),s.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),s.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),s.push("uniform highp sampler2D uTextureCameraMatrices;"),s.push("uniform highp sampler2D uTextureModelMatrices;"),s.push("uniform vec3 uCameraEyeRtc;"),s.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("out float isPerspective;")),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out highp vec2 vHighPrecisionZW;"),i&&(s.push("out vec4 vWorldPosition;"),s.push("flat out uint vFlags2;")),s.push("void main(void) {"),s.push("int polygonIndex = gl_VertexID / 3;"),s.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),s.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),s.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),s.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),s.push("uvec4 flags = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),s.push("uvec4 flags2 = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),s.push("if (int(flags.x) != renderPass) {"),s.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),s.push(" return;"),s.push("} else {"),s.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));"),s.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));"),s.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));"),s.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));"),s.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));"),s.push("ivec4 packedVertexBase = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),s.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),s.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),s.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),s.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),s.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),s.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),s.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),s.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),s.push("mat4 positionsDecodeMatrix = mat4 (texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*8+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0));"),s.push("mat4 entityMatrix = mat4 (texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*8+6, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0));"),s.push("positionsDecodeMatrix = entityMatrix * positionsDecodeMatrix;"),s.push("uint solid = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),s.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),s.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),s.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),s.push("uvec4 color = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),s.push("if (color.a == 0u) {"),s.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),s.push(" return;"),s.push("};"),s.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),s.push("vec3 position;"),s.push("position = positions[gl_VertexID % 3];"),s.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*positionsDecodeMatrix)) * vec4(normal,1)).xyz);"),s.push("if (solid != 1u) {"),s.push("if (isPerspectiveMatrix(projMatrix)) {"),s.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(worldMatrix * positionsDecodeMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),s.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),s.push("position = positions[2 - (gl_VertexID % 3)];"),s.push("viewNormal = -viewNormal;"),s.push("}"),s.push("} else {"),s.push("if (viewNormal.z < 0.0) {"),s.push("position = positions[2 - (gl_VertexID % 3)];"),s.push("viewNormal = -viewNormal;"),s.push("}"),s.push("}"),s.push("}"),s.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),s.push("vec4 offset = vec4(texelFetch (uTexturePerObjectIdOffsets, objectIndexCoords, 0).rgb, 0.0);"),s.push("worldPosition.xyz = worldPosition.xyz + offset.xyz;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags2 = flags2.r;")),s.push("gl_Position = clipPos;"),s.push("vHighPrecisionZW = gl_Position.zw;"),s.push("}"),s.push("}"),s}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.sectionPlanes.length>0,s=[];if(s.push("#version 300 es"),s.push("// Triangles dataTexture draw fragment shader"),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"),s.push("in highp vec2 vHighPrecisionZW;"),s.push("out vec4 outColor;"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("flat in uint vFlags2;");for(var r=0,n=t.sectionPlanes.length;r<n;r++)s.push("uniform bool sectionPlaneActive"+r+";"),s.push("uniform vec3 sectionPlanePos"+r+";"),s.push("uniform vec3 sectionPlaneDir"+r+";")}if(s.push("void main(void) {"),i){s.push(" bool clippable = vFlags2 > 0u;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var o=0,a=t.sectionPlanes.length;o<a;o++)s.push("if (sectionPlaneActive"+o+") {"),s.push(" dist += clamp(dot(-sectionPlaneDir"+o+".xyz, vWorldPosition.xyz - sectionPlanePos"+o+".xyz), 0.0, 1000.0);"),s.push("}");s.push(" if (dist > 0.0) { "),s.push(" discard;"),s.push(" }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("float fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;"),s.push(" outColor = vec4(vec3(1.0 - fragCoordZ), 1.0); "),s.push("}"),s}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),e}(),Xi=q.vec3(),Yi=function(){function e(t){w(this,e),this._scene=t,this._hash=this._getHash(),this._allocate()}return I(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,i){var s=t.model,r=s.scene,n=r.camera,o=r.canvas.gl,a=t._state,u=t._state.origin;if(this._program||(this._allocate(t),!this.errors)){e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(t)),o.uniform1i(this._uRenderPass,i),o.uniformMatrix4fv(this._uViewMatrix,!1,u?De(n.viewMatrix,u):n.viewMatrix),o.uniformMatrix4fv(this._uViewNormalMatrix,!1,n.viewNormalMatrix),o.uniformMatrix4fv(this._uWorldMatrix,!1,s.worldMatrix),o.uniformMatrix4fv(this._uWorldNormalMatrix,!1,s.worldNormalMatrix);var h=r._sectionPlanesState.sectionPlanes.length;if(h>0)for(var l=r._sectionPlanesState.sectionPlanes,c=t.layerIndex*h,p=s.renderFlags,d=0;d<h;d++){var f=this._uSectionPlanes[d];if(f){var m=p.sectionPlanesActivePerLayer[c+d];if(o.uniform1i(f.active,m?1:0),m){var v=l[d];if(u){var g=Ee(v.dist,v.dir,u,Xi);o.uniform3fv(f.pos,g)}else o.uniform3fv(f.pos,v.pos);o.uniform3fv(f.dir,v.dir)}}}o.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,t._state.positionsDecodeMatrix),this._aPosition.bindArrayBuffer(a.positionsBuf),this._aOffset.bindArrayBuffer(a.offsetsBuf),this._aNormal.bindArrayBuffer(a.normalsBuf),this._aColor.bindArrayBuffer(a.colorsBuf),this._aFlags.bindArrayBuffer(a.flagsBuf),this._aFlags2&&this._aFlags2.bindArrayBuffer(a.flags2Buf),a.indicesBuf.bind(),o.drawElements(o.TRIANGLES,a.indicesBuf.numItems,a.indicesBuf.itemType,0)}}},{key:"_allocate",value:function(){var e=this._scene,t=e.canvas.gl;if(this._program=new ht(t,this._buildShader()),this._program.errors)this.errors=this._program.errors;else{var i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPositionsDecodeMatrix=i.getLocation("positionsDecodeMatrix"),this._uWorldMatrix=i.getLocation("worldMatrix"),this._uWorldNormalMatrix=i.getLocation("worldNormalMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uViewNormalMatrix=i.getLocation("viewNormalMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(var s=0,r=e._sectionPlanesState.sectionPlanes.length;s<r;s++)this._uSectionPlanes.push({active:i.getLocation("sectionPlaneActive"+s),pos:i.getLocation("sectionPlanePos"+s),dir:i.getLocation("sectionPlaneDir"+s)});this._aPosition=i.getAttribute("position"),this._aOffset=i.getAttribute("offset"),this._aNormal=i.getAttribute("normal"),this._aColor=i.getAttribute("color"),this._aFlags=i.getAttribute("flags"),this._aFlags2&&(this._aFlags2=i.getAttribute("flags2")),e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=i.getLocation("logDepthBufFC"))}}},{key:"_bindProgram",value:function(){var e=this._scene,t=e.canvas.gl,i=e.camera.project;if(this._program.bind(),t.uniformMatrix4fv(this._uProjMatrix,!1,i.matrix),e.logarithmicDepthBufferEnabled){var s=2/(Math.log(i.far+1)/Math.LN2);t.uniform1f(this._uLogDepthBufFC,s)}}},{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,i=[];return i.push("// Batched geometry normals vertex shader"),e.logarithmicDepthBufferEnabled&&Ze.SUPPORTED_EXTENSIONS.EXT_frag_depth&&i.push("#extension GL_EXT_frag_depth : enable"),i.push("uniform int renderPass;"),i.push("attribute vec3 position;"),e.entityOffsetsEnabled&&i.push("attribute vec3 offset;"),i.push("attribute vec3 normal;"),i.push("attribute vec4 color;"),i.push("attribute vec4 flags;"),i.push("attribute vec4 flags2;"),i.push("uniform mat4 worldMatrix;"),i.push("uniform mat4 worldNormalMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform mat4 viewNormalMatrix;"),i.push("uniform mat4 positionsDecodeMatrix;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),Ze.SUPPORTED_EXTENSIONS.EXT_frag_depth&&i.push("varying float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("varying float isPerspective;")),i.push("vec3 octDecode(vec2 oct) {"),i.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),i.push(" if (v.z < 0.0) {"),i.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);"),i.push(" }"),i.push(" return normalize(v);"),i.push("}"),t&&(i.push("varying vec4 vWorldPosition;"),i.push("varying vec4 vFlags2;")),i.push("varying vec3 vViewNormal;"),i.push("void main(void) {"),i.push("if (int(flags.x) != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vec4 worldNormal = worldNormalMatrix * vec4(octDecode(normal.xy), 0.0); "),i.push(" vec3 viewNormal = normalize((viewNormalMatrix * worldNormal).xyz);"),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags2 = flags2;")),i.push(" vViewNormal = viewNormal;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(Ze.SUPPORTED_EXTENSIONS.EXT_frag_depth?i.push("vFragDepth = 1.0 + clipPos.w;"):(i.push("clipPos.z = log2( max( 1e-6, clipPos.w + 1.0 ) ) * logDepthBufFC - 1.0;"),i.push("clipPos.z *= clipPos.w;")),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push(" }"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.sectionPlanes.length>0,s=[];if(s.push("// Batched geometry normals 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;")),i){s.push("varying vec4 vWorldPosition;"),s.push("varying vec4 vFlags2;");for(var r=0;r<t.sectionPlanes.length;r++)s.push("uniform bool sectionPlaneActive"+r+";"),s.push("uniform vec3 sectionPlanePos"+r+";"),s.push("uniform vec3 sectionPlaneDir"+r+";")}if(s.push("varying vec3 vViewNormal;"),s.push("vec3 packNormalToRGB( const in vec3 normal ) {"),s.push(" return normalize( normal ) * 0.5 + 0.5;"),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 n=0;n<t.sectionPlanes.length;n++)s.push(" if (sectionPlaneActive"+n+") {"),s.push(" dist += clamp(dot(-sectionPlaneDir"+n+".xyz, vWorldPosition.xyz - sectionPlanePos"+n+".xyz), 0.0, 1000.0);"),s.push(" }");s.push(" if (dist > 0.0) { discard; }"),s.push(" }")}return 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(" gl_FragColor = vec4(packNormalToRGB(vViewNormal), 1.0); "),s.push("}"),s}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),e}();q.vec3();var Ki=function(){function e(t){w(this,e),this._scene=t,this._hash=this._getHash(),this._allocate()}return I(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,i=e._sectionPlanesState;if(this._program=new ht(t,this._buildShader()),this._program.errors)this.errors=this._program.errors;else{var s=this._program;this._uPositionsDecodeMatrix=s.getLocation("positionsDecodeMatrix"),this._uShadowViewMatrix=s.getLocation("shadowViewMatrix"),this._uShadowProjMatrix=s.getLocation("shadowProjMatrix"),e.logarithmicDepthBufferEnabled&&(this._uZFar=s.getLocation("zFar")),this._uSectionPlanes=[];for(var r=0,n=i.sectionPlanes.length;r<n;r++)this._uSectionPlanes.push({active:s.getLocation("sectionPlaneActive"+r),pos:s.getLocation("sectionPlanePos"+r),dir:s.getLocation("sectionPlaneDir"+r)});this._aPosition=s.getAttribute("position"),this._aOffset=s.getAttribute("offset"),this._aColor=s.getAttribute("color"),this._aFlags=s.getAttribute("flags"),this._aFlags2=s.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,i=[];return i.push("// Batched geometry shadow vertex shader"),i.push("attribute vec3 position;"),e.entityOffsetsEnabled&&i.push("attribute vec3 offset;"),i.push("attribute vec4 color;"),i.push("attribute vec4 flags;"),i.push("attribute vec4 flags2;"),i.push("uniform mat4 shadowViewMatrix;"),i.push("uniform mat4 shadowProjMatrix;"),i.push("uniform mat4 positionsDecodeMatrix;"),t&&(i.push("varying vec4 vWorldPosition;"),i.push("varying vec4 vFlags2;")),i.push("varying vec4 vViewPosition;"),i.push("void main(void) {"),i.push(" bool visible = (float(flags.x) > 0.0);"),i.push(" bool transparent = ((float(color.a) / 255.0) < 1.0);"),i.push(" if (!visible || transparent) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = shadowViewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags2 = flags2;")),i.push(" vViewPosition = viewPosition;"),i.push(" gl_Position = shadowProjMatrix * viewPosition;"),i.push(" }"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene._sectionPlanesState,t=e.sectionPlanes.length>0,i=[];if(i.push("// Batched geometry shadow fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),t){i.push("varying vec4 vWorldPosition;"),i.push("varying vec4 vFlags2;");for(var s=0;s<e.sectionPlanes.length;s++)i.push("uniform bool sectionPlaneActive"+s+";"),i.push("uniform vec3 sectionPlanePos"+s+";"),i.push("uniform vec3 sectionPlaneDir"+s+";")}if(i.push("varying vec4 vViewPosition;"),i.push("vec4 encodeFloat( const in float v ) {"),i.push(" const vec4 bitShift = vec4(256 * 256 * 256, 256 * 256, 256, 1.0);"),i.push(" const vec4 bitMask = vec4(0, 1.0 / 256.0, 1.0 / 256.0, 1.0 / 256.0);"),i.push(" vec4 comp = fract(v * bitShift);"),i.push(" comp -= comp.xxyz * bitMask;"),i.push(" return comp;"),i.push("}"),i.push("void main(void) {"),t){i.push(" bool clippable = (float(vFlags2.x) > 0.0);"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var r=0;r<e.sectionPlanes.length;r++)i.push(" if (sectionPlaneActive"+r+") {"),i.push(" dist += clamp(dot(-sectionPlaneDir"+r+".xyz, vWorldPosition.xyz - sectionPlanePos"+r+".xyz), 0.0, 1000.0);"),i.push(" }");i.push(" if (dist > 0.0) { discard; }"),i.push(" }")}return i.push(" gl_FragColor = encodeFloat( gl_FragCoord.z); "),i.push("}"),i}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),e}(),Ji=q.vec4(),Zi=q.vec3(),Qi={linear:"linearToLinear",sRGB:"sRGBToLinear",gamma:"gammaToLinear"},qi=function(){function e(t,i){w(this,e),this._scene=t,this._withSAO=i,this._hash=this._getHash(),this._allocate()}return I(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,i){var s=this._scene,r=s.camera,n=t.model,o=s.canvas.gl,a=t._state,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.uniform1i(this._uRenderPass,i),o.uniformMatrix4fv(this._uViewMatrix,!1,u?De(r.viewMatrix,u):r.viewMatrix),o.uniformMatrix4fv(this._uViewNormalMatrix,!1,r.viewNormalMatrix),o.uniformMatrix4fv(this._uWorldMatrix,!1,n.worldMatrix),o.uniformMatrix4fv(this._uWorldNormalMatrix,!1,n.worldNormalMatrix);var h=s._sectionPlanesState.sectionPlanes.length;if(h>0)for(var l=s._sectionPlanesState.sectionPlanes,c=t.layerIndex*h,p=n.renderFlags,d=0;d<h;d++){var f=this._uSectionPlanes[d];if(f){var m=p.sectionPlanesActivePerLayer[c+d];if(o.uniform1i(f.active,m?1:0),m){var v=l[d];if(u){var g=Ee(v.dist,v.dir,u,Zi);o.uniform3fv(f.pos,g)}else o.uniform3fv(f.pos,v.pos);o.uniform3fv(f.dir,v.dir)}}}o.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,t._state.positionsDecodeMatrix),this._aPosition.bindArrayBuffer(a.positionsBuf),this._aNormal&&this._aNormal.bindArrayBuffer(a.normalsBuf),this._aColor&&this._aColor.bindArrayBuffer(a.colorsBuf),this._aMetallicRoughness&&this._aMetallicRoughness.bindArrayBuffer(a.metallicRoughnessBuf),this._aFlags&&this._aFlags.bindArrayBuffer(a.flagsBuf),this._aFlags2&&this._aFlags2.bindArrayBuffer(a.flags2Buf),this._aOffset&&this._aOffset.bindArrayBuffer(a.offsetsBuf),a.indicesBuf.bind(),o.drawElements(o.TRIANGLES,a.indicesBuf.numItems,a.indicesBuf.itemType,0),e.drawElements++}}},{key:"_allocate",value:function(){var e=this._scene,t=e.canvas.gl,i=e._lightsState;if(this._program=new ht(t,this._buildShader()),this._program.errors)this.errors=this._program.errors;else{var s=this._program;this._uRenderPass=s.getLocation("renderPass"),this._uPositionsDecodeMatrix=s.getLocation("positionsDecodeMatrix"),this._uWorldMatrix=s.getLocation("worldMatrix"),this._uWorldNormalMatrix=s.getLocation("worldNormalMatrix"),this._uViewMatrix=s.getLocation("viewMatrix"),this._uViewNormalMatrix=s.getLocation("viewNormalMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uGammaFactor=s.getLocation("gammaFactor"),this._uLightAmbient=s.getLocation("lightAmbient"),this._uLightColor=[],this._uLightDir=[],this._uLightPos=[],this._uLightAttenuation=[];for(var r=i.lights,n=0,o=r.length;n<o;n++)switch(r[n].type){case"dir":this._uLightColor[n]=s.getLocation("lightColor"+n),this._uLightPos[n]=null,this._uLightDir[n]=s.getLocation("lightDir"+n);break;case"point":this._uLightColor[n]=s.getLocation("lightColor"+n),this._uLightPos[n]=s.getLocation("lightPos"+n),this._uLightDir[n]=null,this._uLightAttenuation[n]=s.getLocation("lightAttenuation"+n);break;case"spot":this._uLightColor[n]=s.getLocation("lightColor"+n),this._uLightPos[n]=s.getLocation("lightPos"+n),this._uLightDir[n]=s.getLocation("lightDir"+n),this._uLightAttenuation[n]=s.getLocation("lightAttenuation"+n)}i.reflectionMaps.length>0&&(this._uReflectionMap="reflectionMap"),i.lightMaps.length>0&&(this._uLightMap="lightMap"),this._uSectionPlanes=[];for(var a=0,u=e._sectionPlanesState.sectionPlanes.length;a<u;a++)this._uSectionPlanes.push({active:s.getLocation("sectionPlaneActive"+a),pos:s.getLocation("sectionPlanePos"+a),dir:s.getLocation("sectionPlaneDir"+a)});this._aPosition=s.getAttribute("position"),this._aOffset=s.getAttribute("offset"),this._aNormal=s.getAttribute("normal"),this._aColor=s.getAttribute("color"),this._aMetallicRoughness=s.getAttribute("metallicRoughness"),this._aFlags=s.getAttribute("flags"),this._aFlags2=s.getAttribute("flags2"),this._withSAO&&(this._uOcclusionTexture="uOcclusionTexture",this._uSAOParams=s.getLocation("uSAOParams")),e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=s.getLocation("logDepthBufFC"))}}},{key:"_bindProgram",value:function(e){var t=Ze.MAX_TEXTURE_UNITS,i=this._scene,s=i.canvas.gl,r=this._program,n=i._lightsState,o=n.lights,a=i.camera.project;r.bind(),s.uniformMatrix4fv(this._uProjMatrix,!1,a.matrix),this._uLightAmbient&&s.uniform4fv(this._uLightAmbient,i._lightsState.getAmbientColorAndIntensity());for(var u=0,h=o.length;u<h;u++){var l=o[u];this._uLightColor[u]&&s.uniform4f(this._uLightColor[u],l.color[0],l.color[1],l.color[2],l.intensity),this._uLightPos[u]&&(s.uniform3fv(this._uLightPos[u],l.pos),this._uLightAttenuation[u]&&s.uniform1f(this._uLightAttenuation[u],l.attenuation)),this._uLightDir[u]&&s.uniform3fv(this._uLightDir[u],l.dir)}if(n.reflectionMaps.length>0&&n.reflectionMaps[0].texture&&this._uReflectionMap&&(r.bindTexture(this._uReflectionMap,n.reflectionMaps[0].texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%t,e.bindTexture++),n.lightMaps.length>0&&n.lightMaps[0].texture&&this._uLightMap&&(r.bindTexture(this._uLightMap,n.lightMaps[0].texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%t,e.bindTexture++),this._withSAO){var c=i.sao;if(c.possible){var p=s.drawingBufferWidth,d=s.drawingBufferHeight;Ji[0]=p,Ji[1]=d,Ji[2]=c.blendCutoff,Ji[3]=c.blendFactor,s.uniform4fv(this._uSAOParams,Ji),this._program.bindTexture(this._uOcclusionTexture,e.occlusionTexture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%t,e.bindTexture++}}if(i.logarithmicDepthBufferEnabled){var f=2/(Math.log(a.far+1)/Math.LN2);s.uniform1f(this._uLogDepthBufFC,f)}this._uGammaFactor&&s.uniform1f(this._uGammaFactor,i.gammaFactor)}},{key:"_buildShader",value:function(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=e._lightsState,s=t.sectionPlanes.length>0,r=t.clippingCaps,n=[];return n.push("// Triangles dataTexture quality draw 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;"),n.push("attribute vec3 normal;"),n.push("attribute vec4 color;"),n.push("attribute vec2 metallicRoughness;"),n.push("attribute vec4 flags;"),n.push("attribute vec4 flags2;"),e.entityOffsetsEnabled&&n.push("attribute vec3 offset;"),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("}"),n.push("varying vec4 vViewPosition;"),n.push("varying vec3 vViewNormal;"),n.push("varying vec4 vColor;"),n.push("varying vec2 vMetallicRoughness;"),i.lightMaps.length>0&&n.push("varying vec3 vWorldNormal;"),s&&(n.push("varying vec4 vWorldPosition;"),n.push("varying vec4 vFlags2;"),r&&n.push("varying vec4 vClipPosition;")),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);"),n.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(n.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),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;"))),s&&(n.push("vWorldPosition = worldPosition;"),n.push("vFlags2 = flags2;"),r&&n.push("vClipPosition = clipPos;")),n.push("vViewPosition = viewPosition;"),n.push("vViewNormal = viewNormal;"),n.push("vColor = color;"),n.push("vMetallicRoughness = metallicRoughness;"),i.lightMaps.length>0&&n.push("vWorldNormal = worldNormal.xyz;"),n.push("gl_Position = clipPos;"),n.push("}"),n.push("}"),n}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e.gammaOutput,i=e._sectionPlanesState,s=e._lightsState,r=i.sectionPlanes.length>0,n=i.clippingCaps,o=[];o.push("// Triangles dataTexture quality draw fragment shader"),e.logarithmicDepthBufferEnabled&&Ze.SUPPORTED_EXTENSIONS.EXT_frag_depth&&o.push("#extension GL_EXT_frag_depth : enable"),o.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),o.push("precision highp float;"),o.push("precision highp int;"),o.push("#else"),o.push("precision mediump float;"),o.push("precision mediump int;"),o.push("#endif"),e.logarithmicDepthBufferEnabled&&Ze.SUPPORTED_EXTENSIONS.EXT_frag_depth&&(o.push("varying float isPerspective;"),o.push("uniform float logDepthBufFC;"),o.push("varying float vFragDepth;")),o.push("varying vec4 vViewPosition;"),o.push("varying vec3 vViewNormal;"),o.push("varying vec4 vColor;"),o.push("varying vec2 vMetallicRoughness;"),s.lightMaps.length>0&&o.push("varying vec3 vWorldNormal;"),o.push("uniform mat4 viewMatrix;"),s.reflectionMaps.length>0&&o.push("uniform samplerCube reflectionMap;"),s.lightMaps.length>0&&o.push("uniform samplerCube lightMap;"),o.push("uniform vec4 lightAmbient;");for(var a=0,u=s.lights.length;a<u;a++){var h=s.lights[a];"ambient"!==h.type&&(o.push("uniform vec4 lightColor"+a+";"),"dir"===h.type&&o.push("uniform vec3 lightDir"+a+";"),"point"===h.type&&o.push("uniform vec3 lightPos"+a+";"),"spot"===h.type&&(o.push("uniform vec3 lightPos"+a+";"),o.push("uniform vec3 lightDir"+a+";")))}if(this._withSAO&&(o.push("uniform sampler2D uOcclusionTexture;"),o.push("uniform vec4 uSAOParams;"),o.push("const float packUpscale = 256. / 255.;"),o.push("const float unpackDownScale = 255. / 256.;"),o.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),o.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),o.push("float unpackRGBAToDepth( const in vec4 v ) {"),o.push(" return dot( v, unPackFactors );"),o.push("}")),o.push("uniform float gammaFactor;"),o.push("vec4 linearToLinear( in vec4 value ) {"),o.push(" return value;"),o.push("}"),o.push("vec4 sRGBToLinear( in vec4 value ) {"),o.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 );"),o.push("}"),o.push("vec4 gammaToLinear( in vec4 value) {"),o.push(" return vec4( pow( value.xyz, vec3( gammaFactor ) ), value.w );"),o.push("}"),t&&(o.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),o.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),o.push("}")),r){o.push("varying vec4 vWorldPosition;"),o.push("varying vec4 vFlags2;"),n&&o.push("varying vec4 vClipPosition;");for(var l=0,c=i.sectionPlanes.length;l<c;l++)o.push("uniform bool sectionPlaneActive"+l+";"),o.push("uniform vec3 sectionPlanePos"+l+";"),o.push("uniform vec3 sectionPlaneDir"+l+";")}if(o.push("#define PI 3.14159265359"),o.push("#define RECIPROCAL_PI 0.31830988618"),o.push("#define RECIPROCAL_PI2 0.15915494"),o.push("#define EPSILON 1e-6"),o.push("#define saturate(a) clamp( a, 0.0, 1.0 )"),o.push("vec3 inverseTransformDirection(in vec3 dir, in mat4 matrix) {"),o.push(" return normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );"),o.push("}"),o.push("struct IncidentLight {"),o.push(" vec3 color;"),o.push(" vec3 direction;"),o.push("};"),o.push("struct ReflectedLight {"),o.push(" vec3 diffuse;"),o.push(" vec3 specular;"),o.push("};"),o.push("struct Geometry {"),o.push(" vec3 position;"),o.push(" vec3 viewNormal;"),o.push(" vec3 worldNormal;"),o.push(" vec3 viewEyeDir;"),o.push("};"),o.push("struct Material {"),o.push(" vec3 diffuseColor;"),o.push(" float specularRoughness;"),o.push(" vec3 specularColor;"),o.push(" float shine;"),o.push("};"),o.push("float GGXRoughnessToBlinnExponent(const in float ggxRoughness) {"),o.push(" float r = ggxRoughness + 0.0001;"),o.push(" return (2.0 / (r * r) - 2.0);"),o.push("}"),o.push("float getSpecularMIPLevel(const in float blinnShininessExponent, const in int maxMIPLevel) {"),o.push(" float maxMIPLevelScalar = float( maxMIPLevel );"),o.push(" float desiredMIPLevel = maxMIPLevelScalar - 0.79248 - 0.5 * log2( ( blinnShininessExponent * blinnShininessExponent ) + 1.0 );"),o.push(" return clamp( desiredMIPLevel, 0.0, maxMIPLevelScalar );"),o.push("}"),s.reflectionMaps.length>0&&(o.push("vec3 getLightProbeIndirectRadiance(const in vec3 reflectVec, const in float blinnShininessExponent, const in int maxMIPLevel) {"),o.push(" float mipLevel = 0.5 * getSpecularMIPLevel(blinnShininessExponent, maxMIPLevel);"),o.push(" vec3 envMapColor = "+Qi[s.reflectionMaps[0].encoding]+"(textureCube(reflectionMap, reflectVec, mipLevel)).rgb;"),o.push(" return envMapColor;"),o.push("}")),o.push("vec3 F_Schlick(const in vec3 specularColor, const in float dotLH) {"),o.push(" float fresnel = exp2( ( -5.55473 * dotLH - 6.98316 ) * dotLH );"),o.push(" return ( 1.0 - specularColor ) * fresnel + specularColor;"),o.push("}"),o.push("float G_GGX_Smith(const in float alpha, const in float dotNL, const in float dotNV) {"),o.push(" float a2 = ( alpha * alpha );"),o.push(" float gl = dotNL + sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),o.push(" float gv = dotNV + sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),o.push(" return 1.0 / ( gl * gv );"),o.push("}"),o.push("float G_GGX_SmithCorrelated(const in float alpha, const in float dotNL, const in float dotNV) {"),o.push(" float a2 = ( alpha * alpha );"),o.push(" float gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),o.push(" float gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),o.push(" return 0.5 / max( gv + gl, EPSILON );"),o.push("}"),o.push("float D_GGX(const in float alpha, const in float dotNH) {"),o.push(" float a2 = ( alpha * alpha );"),o.push(" float denom = ( dotNH * dotNH) * ( a2 - 1.0 ) + 1.0;"),o.push(" return RECIPROCAL_PI * a2 / ( denom * denom);"),o.push("}"),o.push("vec3 BRDF_Specular_GGX(const in IncidentLight incidentLight, const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),o.push(" float alpha = ( roughness * roughness );"),o.push(" vec3 halfDir = normalize( incidentLight.direction + geometry.viewEyeDir );"),o.push(" float dotNL = saturate( dot( geometry.viewNormal, incidentLight.direction ) );"),o.push(" float dotNV = saturate( dot( geometry.viewNormal, geometry.viewEyeDir ) );"),o.push(" float dotNH = saturate( dot( geometry.viewNormal, halfDir ) );"),o.push(" float dotLH = saturate( dot( incidentLight.direction, halfDir ) );"),o.push(" vec3 F = F_Schlick( specularColor, dotLH );"),o.push(" float G = G_GGX_SmithCorrelated( alpha, dotNL, dotNV );"),o.push(" float D = D_GGX( alpha, dotNH );"),o.push(" return F * (G * D);"),o.push("}"),o.push("vec3 BRDF_Specular_GGX_Environment(const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),o.push(" float dotNV = saturate(dot(geometry.viewNormal, geometry.viewEyeDir));"),o.push(" const vec4 c0 = vec4( -1, -0.0275, -0.572, 0.022);"),o.push(" const vec4 c1 = vec4( 1, 0.0425, 1.04, -0.04);"),o.push(" vec4 r = roughness * c0 + c1;"),o.push(" float a004 = min(r.x * r.x, exp2(-9.28 * dotNV)) * r.x + r.y;"),o.push(" vec2 AB = vec2(-1.04, 1.04) * a004 + r.zw;"),o.push(" return specularColor * AB.x + AB.y;"),o.push("}"),(s.lightMaps.length>0||s.reflectionMaps.length>0)&&(o.push("void computePBRLightMapping(const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),s.lightMaps.length>0&&(o.push(" vec3 irradiance = "+Qi[s.lightMaps[0].encoding]+"(textureCube(lightMap, geometry.worldNormal)).rgb;"),o.push(" irradiance *= PI;"),o.push(" vec3 diffuseBRDFContrib = (RECIPROCAL_PI * material.diffuseColor);"),o.push(" reflectedLight.diffuse += irradiance * diffuseBRDFContrib;")),s.reflectionMaps.length>0&&(o.push(" vec3 reflectVec = reflect(geometry.viewEyeDir, geometry.viewNormal);"),o.push(" reflectVec = inverseTransformDirection(reflectVec, viewMatrix);"),o.push(" float blinnExpFromRoughness = GGXRoughnessToBlinnExponent(material.specularRoughness);"),o.push(" vec3 radiance = getLightProbeIndirectRadiance(reflectVec, blinnExpFromRoughness, 8);"),o.push(" vec3 specularBRDFContrib = BRDF_Specular_GGX_Environment(geometry, material.specularColor, material.specularRoughness);"),o.push(" reflectedLight.specular += radiance * specularBRDFContrib;")),o.push("}")),o.push("void computePBRLighting(const in IncidentLight incidentLight, const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),o.push(" float dotNL = saturate(dot(geometry.viewNormal, incidentLight.direction));"),o.push(" vec3 irradiance = dotNL * incidentLight.color * PI;"),o.push(" reflectedLight.diffuse += irradiance * (RECIPROCAL_PI * material.diffuseColor);"),o.push(" reflectedLight.specular += irradiance * BRDF_Specular_GGX(incidentLight, geometry, material.specularColor, material.specularRoughness);"),o.push("}"),o.push("void main(void) {"),r){o.push(" bool clippable = (float(vFlags2.x) > 0.0);"),o.push(" if (clippable) {"),o.push(" float dist = 0.0;");for(var p=0,d=i.sectionPlanes.length;p<d;p++)o.push("if (sectionPlaneActive"+p+") {"),o.push(" dist += clamp(dot(-sectionPlaneDir"+p+".xyz, vWorldPosition.xyz - sectionPlanePos"+p+".xyz), 0.0, 1000.0);"),o.push("}");n?(o.push(" if (dist > (0.002 * vClipPosition.w)) {"),o.push(" discard;"),o.push(" }"),o.push(" if (dist > 0.0) { "),o.push(" gl_FragColor=vec4(1.0, 0.0, 0.0, 1.0);"),e.logarithmicDepthBufferEnabled&&Ze.SUPPORTED_EXTENSIONS.EXT_frag_depth&&o.push(" gl_FragDepthEXT = log2( vFragDepth ) * logDepthBufFC * 0.5;"),o.push(" return;"),o.push("}")):(o.push(" if (dist > 0.0) { "),o.push(" discard;"),o.push(" }")),o.push("}")}o.push("IncidentLight light;"),o.push("Material material;"),o.push("Geometry geometry;"),o.push("ReflectedLight reflectedLight = ReflectedLight(vec3(0.0,0.0,0.0), vec3(0.0,0.0,0.0));"),o.push("vec3 rgb = (vec3(float(vColor.r) / 255.0, float(vColor.g) / 255.0, float(vColor.b) / 255.0));"),o.push("float alpha = float(vColor.a) / 255.0;"),o.push("vec3 diffuseColor = rgb;"),o.push("float specularF0 = 1.0;"),o.push("float metallic = float(vMetallicRoughness.r) / 255.0;"),o.push("float roughness = float(vMetallicRoughness.g) / 255.0;"),o.push("float dielectricSpecular = 0.16 * specularF0 * specularF0;"),o.push("material.diffuseColor = diffuseColor * (1.0 - dielectricSpecular) * (1.0 - metallic);"),o.push("material.specularRoughness = clamp(roughness, 0.04, 1.0);"),o.push("material.specularColor = mix(vec3(dielectricSpecular), diffuseColor, metallic);"),o.push("geometry.position = vViewPosition.xyz;"),o.push("geometry.viewNormal = -normalize(vViewNormal);"),o.push("geometry.viewEyeDir = normalize(vViewPosition.xyz);"),s.lightMaps.length>0&&o.push("geometry.worldNormal = normalize(vWorldNormal);"),(s.lightMaps.length>0||s.reflectionMaps.length>0)&&o.push("computePBRLightMapping(geometry, material, reflectedLight);");for(var f=0,m=s.lights.length;f<m;f++){var v=s.lights[f];if("ambient"!==v.type){if("dir"===v.type)"view"===v.space?o.push("light.direction = normalize(lightDir"+f+");"):o.push("light.direction = normalize((viewMatrix * vec4(lightDir"+f+", 0.0)).xyz);");else if("point"===v.type)"view"===v.space?o.push("light.direction = normalize(lightPos"+f+" - vViewPosition.xyz);"):o.push("light.direction = normalize((viewMatrix * vec4(lightPos"+f+", 0.0)).xyz);");else{if("spot"!==v.type)continue;"view"===v.space?o.push("light.direction = normalize(lightDir"+f+");"):o.push("light.direction = normalize((viewMatrix * vec4(lightDir"+f+", 0.0)).xyz);")}o.push("light.color = lightColor"+f+".rgb * lightColor"+f+".a;"),o.push("computePBRLighting(light, geometry, material, reflectedLight);")}}return o.push("vec3 outgoingLight = (lightAmbient.rgb * lightAmbient.a * rgb) + (reflectedLight.diffuse) + (reflectedLight.specular);"),o.push("vec4 fragColor;"),this._withSAO?(o.push(" float viewportWidth = uSAOParams[0];"),o.push(" float viewportHeight = uSAOParams[1];"),o.push(" float blendCutoff = uSAOParams[2];"),o.push(" float blendFactor = uSAOParams[3];"),o.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),o.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBAToDepth(texture2D(uOcclusionTexture, uv))) * blendFactor;"),o.push(" fragColor = vec4(outgoingLight.rgb * ambient, alpha);")):o.push(" fragColor = vec4(outgoingLight.rgb, alpha);"),t&&o.push("fragColor = linearToGamma(fragColor, gammaFactor);"),o.push("gl_FragColor = fragColor;"),e.logarithmicDepthBufferEnabled&&Ze.SUPPORTED_EXTENSIONS.EXT_frag_depth&&o.push(" gl_FragDepthEXT = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),o.push("}"),o}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),e}(),$i=q.vec3(),es=function(){function e(t){w(this,e),this._scene=t,this._hash=this._getHash(),this._allocate()}return I(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,i){var s=t.model,r=s.scene,n=r.camera,o=r.canvas.gl,a=t._state,u=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 o.activeTexture(o["TEXTURE"+e]),o.bindTexture(o.TEXTURE_2D,a.texturePerObjectIdPositionsDecodeMatrix),!0},unbind:function(e){o.activeTexture(o["TEXTURE"+e]),o.bindTexture(o.TEXTURE_2D,null)}},1),this._program.bindTexture(this._uTexturePerVertexIdCoordinates,{bind:function(e){return o.activeTexture(o["TEXTURE"+e]),o.bindTexture(o.TEXTURE_2D,a.texturePerVertexIdCoordinates),!0},unbind:function(e){o.activeTexture(o["TEXTURE"+e]),o.bindTexture(o.TEXTURE_2D,null)}},2),this._program.bindTexture(this._uTexturePerObjectIdColorsAndFlags,{bind:function(e){return o.activeTexture(o["TEXTURE"+e]),o.bindTexture(o.TEXTURE_2D,a.texturePerObjectIdColorsAndFlags),!0},unbind:function(e){o.activeTexture(o["TEXTURE"+e]),o.bindTexture(o.TEXTURE_2D,null)}},3),o.uniform1i(this._uRenderPass,i),o.uniform1i(this._uPickInvisible,e.pickInvisible),o.uniformMatrix4fv(this._uWorldMatrix,!1,s.worldMatrix);var h=e.pickViewMatrix||n.viewMatrix,l=u?De(h,u):h;if(o.uniformMatrix4fv(this._uViewMatrix,!1,l),o.uniformMatrix4fv(this._uProjMatrix,!1,e.pickProjMatrix),r.logarithmicDepthBufferEnabled){var c=2/(Math.log(n.project.far+1)/Math.LN2);o.uniform1f(this._uLogDepthBufFC,c)}var p=r._sectionPlanesState.sectionPlanes.length;if(p>0)for(var d=r._sectionPlanesState.sectionPlanes,f=t.layerIndex*p,m=s.renderFlags,v=0;v<p;v++){var g=this._uSectionPlanes[v],_=m.sectionPlanesActivePerLayer[f+v];if(o.uniform1i(g.active,_?1:0),_){var y=d[v];if(u){var b=Ee(y.dist,y.dir,u,$i);o.uniform3fv(g.pos,b)}else o.uniform3fv(g.pos,y.pos);o.uniform3fv(g.dir,y.dir)}}a.numIndices8Bits>0&&(this._program.bindTexture(this._uTexturePerPolygonIdPortionIds,{bind:function(e){return o.activeTexture(o["TEXTURE"+e]),o.bindTexture(o.TEXTURE_2D,a.texturePerPolygonIdPortionIds8Bits),!0},unbind:function(e){o.activeTexture(o["TEXTURE"+e]),o.bindTexture(o.TEXTURE_2D,null)}},4),this._program.bindTexture(this._uTexturePerPolygonIdIndices,{bind:function(e){return o.activeTexture(o["TEXTURE"+e]),o.bindTexture(o.TEXTURE_2D,a.texturePerPolygonIdIndices8Bits),!0},unbind:function(e){o.activeTexture(o["TEXTURE"+e]),o.bindTexture(o.TEXTURE_2D,null)}},5),o.drawArrays(o.TRIANGLES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(this._program.bindTexture(this._uTexturePerPolygonIdPortionIds,{bind:function(e){return o.activeTexture(o["TEXTURE"+e]),o.bindTexture(o.TEXTURE_2D,a.texturePerPolygonIdPortionIds16Bits),!0},unbind:function(e){o.activeTexture(o["TEXTURE"+e]),o.bindTexture(o.TEXTURE_2D,null)}},4),this._program.bindTexture(this._uTexturePerPolygonIdIndices,{bind:function(e){return o.activeTexture(o["TEXTURE"+e]),o.bindTexture(o.TEXTURE_2D,a.texturePerPolygonIdIndices16Bits),!0},unbind:function(e){o.activeTexture(o["TEXTURE"+e]),o.bindTexture(o.TEXTURE_2D,null)}},5),o.drawArrays(o.TRIANGLES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(this._program.bindTexture(this._uTexturePerPolygonIdPortionIds,{bind:function(e){return o.activeTexture(o["TEXTURE"+e]),o.bindTexture(o.TEXTURE_2D,a.texturePerPolygonIdPortionIds32Bits),!0},unbind:function(e){o.activeTexture(o["TEXTURE"+e]),o.bindTexture(o.TEXTURE_2D,null)}},4),this._program.bindTexture(this._uTexturePerPolygonIdIndices,{bind:function(e){return o.activeTexture(o["TEXTURE"+e]),o.bindTexture(o.TEXTURE_2D,a.texturePerPolygonIdIndices32Bits),!0},unbind:function(e){o.activeTexture(o["TEXTURE"+e]),o.bindTexture(o.TEXTURE_2D,null)}},5),o.drawArrays(o.TRIANGLES,0,a.numIndices32Bits)),e.drawElements++}},{key:"_allocate",value:function(){var e=this._scene,t=e.canvas.gl;if(this._program=new ht(t,this._buildShader()),this._program.errors)this.errors=this._program.errors;else{var i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPickInvisible=i.getLocation("pickInvisible"),this._uPositionsDecodeMatrix=i.getLocation("positionsDecodeMatrix"),this._uWorldMatrix=i.getLocation("worldMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(var s=0,r=e._sectionPlanesState.sectionPlanes.length;s<r;s++)this._uSectionPlanes.push({active:i.getLocation("sectionPlaneActive"+s),pos:i.getLocation("sectionPlanePos"+s),dir:i.getLocation("sectionPlaneDir"+s)});this._aPackedVertexId=i.getAttribute("packedVertexId"),e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=i.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,i=[];return i.push("#version 300 es"),i.push("// Triangles dataTexture pick flat normals vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in uvec3 packedVertexId;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform bool pickInvisible;"),i.push("uniform mat4 worldMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform sampler2D uTexturePerObjectIdPositionsDecodeMatrix;"),i.push("uniform usampler2D uTexturePerObjectIdColorsAndFlags;"),i.push("uniform usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform usampler2D uTexturePerPolygonIdIndices;"),i.push("uniform isampler2D uTexturePerPolygonIdNormals;"),i.push("uniform usampler2D uTexturePerPolygonIdPortionIds;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),i.push("out vec4 vWorldPosition;"),t&&i.push("out int vFlags2;"),i.push("void main(void) {"),i.push("int polygonIndex = gl_VertexID / 3;"),i.push("int h_normal_index = polygonIndex & 4095;"),i.push("int v_normal_index = polygonIndex >> 12;"),i.push("int h_packed_object_id_index = ((polygonIndex >> 3) / 2) & 4095;"),i.push("int v_packed_object_id_index = ((polygonIndex >> 3) / 2) >> 12;"),i.push("ivec3 packedObjectId = ivec3(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).rgb);"),i.push("int objectIndex;"),i.push("if (((polygonIndex >> 3) % 2) == 0) {"),i.push(" objectIndex = (packedObjectId.r << 4) + (packedObjectId.g >> 4);"),i.push("} else {"),i.push(" objectIndex = ((packedObjectId.g & 15) << 8) + packedObjectId.b;"),i.push("}"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("int h_index = polygonIndex & 4095;"),i.push("int v_index = polygonIndex >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),i.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),i.push("mat4 positionsDecodeMatrix = mat4 (texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*8+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0));"),i.push("uvec4 flags = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("vec3 position1 = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),i.push("vec3 position2 = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),i.push("vec3 position3 = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),i.push("vec3 normal = normalize(cross(position3 - position1, position2 - position1));"),i.push("int vertexNumber = gl_VertexID % 3;"),i.push("vec3 position;"),i.push("if (vertexNumber == 0) position = position1;"),i.push("else if (vertexNumber == 1) position = position2;"),i.push("else position = position3;"),i.push("if (int(flags.w) != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vWorldPosition = worldPosition;"),t&&i.push(" vFlags2 = flags2.r;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push(" }"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.sectionPlanes.length>0,s=[];if(s.push("#version 300 es"),s.push("// Triangles dataTexture pick flat normals fragment shader"),s.push("#extension GL_OES_standard_derivatives : enable"),e.logarithmicDepthBufferEnabled&&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&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),s.push("in vec4 vWorldPosition;"),i){s.push("in int vFlags2;");for(var r=0;r<t.sectionPlanes.length;r++)s.push("uniform bool sectionPlaneActive"+r+";"),s.push("uniform vec3 sectionPlanePos"+r+";"),s.push("uniform vec3 sectionPlaneDir"+r+";")}if(s.push("out vec4 outNormal;"),s.push("void main(void) {"),i){s.push(" bool clippable = vFlags2 > 0;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(r=0;r<t.sectionPlanes.length;r++)s.push(" if (sectionPlaneActive"+r+") {"),s.push(" dist += clamp(dot(-sectionPlaneDir"+r+".xyz, vWorldPosition.xyz - sectionPlanePos"+r+".xyz), 0.0, 1000.0);"),s.push(" }");s.push(" if (dist > 0.0) { discard; }"),s.push(" }")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" vec3 xTangent = dFdx( vWorldPosition.xyz );"),s.push(" vec3 yTangent = dFdy( vWorldPosition.xyz );"),s.push(" vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"),s.push(" outNormal = vec4((worldNormal * 0.5) + 0.5, 1.0);"),s.push("}"),s}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),e}(),ts=function(){function e(t){w(this,e),this._scene=t}return I(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._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 Di(this._scene,!1)),this._colorRenderer}},{key:"colorRendererWithSAO",get:function(){return this._colorRendererWithSAO||(this._colorRendererWithSAO=new Di(this._scene,!0)),this._colorRendererWithSAO}},{key:"colorQualityRenderer",get:function(){return this._colorQualityRenderer||(this._colorQualityRenderer=new qi(this._scene,!1)),this._colorQualityRenderer}},{key:"colorQualityRendererWithSAO",get:function(){return this._colorQualityRendererWithSAO||(this._colorQualityRendererWithSAO=new qi(this._scene,!0)),this._colorQualityRendererWithSAO}},{key:"silhouetteRenderer",get:function(){return this._silhouetteRenderer||(this._silhouetteRenderer=new Ei(this._scene)),this._silhouetteRenderer}},{key:"depthRenderer",get:function(){return this._depthRenderer||(this._depthRenderer=new Wi(this._scene)),this._depthRenderer}},{key:"normalsRenderer",get:function(){return this._normalsRenderer||(this._normalsRenderer=new Yi(this._scene)),this._normalsRenderer}},{key:"edgesRenderer",get:function(){return this._edgesRenderer||(this._edgesRenderer=new Si(this._scene)),this._edgesRenderer}},{key:"edgesColorRenderer",get:function(){return this._edgesColorRenderer||(this._edgesColorRenderer=new Bi(this._scene)),this._edgesColorRenderer}},{key:"pickMeshRenderer",get:function(){return this._pickMeshRenderer||(this._pickMeshRenderer=new Ni(this._scene)),this._pickMeshRenderer}},{key:"pickNormalsRenderer",get:function(){return this._pickNormalsRenderer||(this._pickNormalsRenderer=new Vi(this._scene)),this._pickNormalsRenderer}},{key:"pickNormalsFlatRenderer",get:function(){return this._pickNormalsFlatRenderer||(this._pickNormalsFlatRenderer=new es(this._scene)),this._pickNormalsFlatRenderer}},{key:"pickDepthRenderer",get:function(){return this._pickDepthRenderer||(this._pickDepthRenderer=new Gi(this._scene)),this._pickDepthRenderer}},{key:"occlusionRenderer",get:function(){return this._occlusionRenderer||(this._occlusionRenderer=new Ui(this._scene)),this._occlusionRenderer}},{key:"shadowRenderer",get:function(){return this._shadowRenderer||(this._shadowRenderer=new Ki(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._pickNormalsRenderer&&this._pickNormalsRenderer.destroy(),this._pickNormalsFlatRenderer&&this._pickNormalsFlatRenderer.destroy(),this._occlusionRenderer&&this._occlusionRenderer.destroy(),this._shadowRenderer&&this._shadowRenderer.destroy()}}]),e}(),is={};Ze.SUPPORTED_EXTENSIONS.OES_element_index_uint;var ss=I((function e(){w(this,e),this.positions=[],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=[]})),rs=null;
2
2
  /**
3
3
  * @author https://github.com/tmarti, with support from https://tribia.com/
4
4
  * @license MIT
@@ -14,7 +14,7 @@ var e,t=o().mark(Iv),i=o().mark(Cv),s=o().mark(Ny);function r(e){return function
14
14
  /**
15
15
  * @author https://github.com/tmarti, with support from https://tribia.com/
16
16
  * @license MIT
17
- **/var us=null;function hs(e,t){var i,s,r,n,o,a,u=3*e,h=3*t,l=Math.min(i=us[u],s=us[u+1],r=us[u+2]),c=Math.min(n=us[h],o=us[h+1],a=us[h+2]);if(l!=c)return l-c;var p=Math.max(i,s,r),d=Math.max(n,o,a);return p!=d?p-d:0}function ls(e,t){for(var i=new Int32Array(e.length/3),s=0,r=i.length;s<r;s++)i[s]=s;us=new Int32Array(e.length);for(var n=0,o=e.length;n<o;n++)us[n]=e[n]>>t;i.sort(hs);for(var a=new Int32Array(e.length),u=0,h=i.length;u<h;u++)a[3*u+0]=e[3*i[u]+0],a[3*u+1]=e[3*i[u]+1],a[3*u+2]=e[3*i[u]+2];return a}var cs=null;function ps(e,t){var i=cs[2*e]-cs[2*t];return 0!=i?i:cs[2*e+1]-cs[2*t+1]}function ds(e){if(0==(e||[]).length)return[];for(var t=new Int32Array(e.length/2),i=0,s=t.length;i<s;i++)t[i]=i;for(var r=0,n=e.length;r<n;r+=2)if(e[r]>e[r+1]){var o=e[r];e[r]=e[r+1],e[r+1]=o}cs=new Int32Array(e),t.sort(ps);for(var a=new Int32Array(e.length),u=0,h=t.length;u<h;u++)a[2*u+0]=e[2*t[u]+0],a[2*u+1]=e[2*t[u]+1];return a}function fs(e,t){var i={},s={};e.forEach((function(e){for(var t=e.indices,r=e.edgeIndices,n=e.positions,o=0,a=t.length;o<a;o+=3){var u=n[3*t[o]]+"_"+n[3*t[o]+1]+"_"+n[3*t[o]+2]+"/"+n[3*t[o+1]]+"_"+n[3*t[o+1]+1]+"_"+n[3*t[o+1]+2]+"/"+n[3*t[o+2]]+"_"+n[3*t[o+2]+1]+"_"+n[3*t[o+2]+2];i[u]=!0}e.edgeIndices.length/2;for(o=0,a=r.length;o<a;o+=2){u=n[3*r[o]]+"_"+n[3*r[o]+1]+"_"+n[3*r[o]+2]+"/"+n[3*r[o+1]]+"_"+n[3*r[o+1]+1]+"_"+n[3*r[o+1]+2]+"/";s[u]=!0}}));var r=t.indices;t.edgeIndices;for(var n=t.positions,o=0,a=r.length;o<a;o+=3){var u=n[3*r[o]]+"_"+n[3*r[o]+1]+"_"+n[3*r[o]+2]+"/"+n[3*r[o+1]]+"_"+n[3*r[o+1]+1]+"_"+n[3*r[o+1]+2]+"/"+n[3*r[o+2]]+"_"+n[3*r[o+2]+1]+"_"+n[3*r[o+2]+2];if(!(u in i))throw console.log("Not found "+u),"Ohhhh!"}}var ms={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(ms,null,4));var e=0;Object.keys(ms).forEach((function(t){t.startsWith("size")&&(e+=ms[t])})),console.log("Total size ".concat(e," bytes (").concat((e/1e3/1e3).toFixed(2)," MB)")),console.log("Avg bytes / triangle: ".concat((e/ms.totalPolygons).toFixed(2)));var t={};Object.keys(ms).forEach((function(i){i.startsWith("size")&&(t[i]="".concat((ms[i]/e*100).toFixed(2)," % of total"))})),console.log(JSON.stringify({percentualRamUsage:t},null,4))};var vs=function(){function e(t,i,s,r){var n=arguments.length>4&&void 0!==arguments[4]?arguments[4]:null;w(this,e),this._gl=t,this._texture=i,this._textureWidth=s,this._textureHeight=r,this._textureData=n}return I(e,[{key:"bindTexture",value:function(e,t,i){return e.bindTexture(t,this,i)}},{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}(),gs=function(){function e(){w(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 I(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,i,s,r,n,o){this.texturePerObjectIdPositionsDecodeMatrix.bindTexture(e,t,1),this.texturePerVertexIdCoordinates.bindTexture(e,i,2),this.texturePerObjectIdColorsAndFlags.bindTexture(e,s,3),this.textureCameraMatrices.bindTexture(e,r,4),this.textureModelMatrices.bindTexture(e,n,5),this.texturePerObjectIdOffsets.bindTexture(e,o,6)}},{key:"bindPickCameraTexture",value:function(e,t){this.texturePickCameraMatrices.bindTexture(e,t,4)}},{key:"bindTriangleIndicesTextures",value:function(e,t,i,s){this.indicesPortionIdsPerBitnessTextures[s].bindTexture(e,t,7),this.indicesPerBitnessTextures[s].bindTexture(e,i,8)}},{key:"bindEdgeIndicesTextures",value:function(e,t,i,s){this.edgeIndicesPortionIdsPerBitnessTextures[s].bindTexture(e,t,7),this.edgeIndicesPerBitnessTextures[s].bindTexture(e,i,8)}}]),e}(),_s=function(){function e(){w(this,e)}return I(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,i,s){var r=!(arguments.length>4&&void 0!==arguments[4])||arguments[4],n=4,o=3,a=e.createTexture();e.bindTexture(e.TEXTURE_2D,a),e.texStorage2D(e.TEXTURE_2D,1,e.RGBA32F,n,o),this.disableBindedTextureFiltering(e),e.bindTexture(e.TEXTURE_2D,null);var u=new vs(e,a,n,o),h=!0;if(u._updateViewMatrix=function(i,r){e.bindTexture(e.TEXTURE_2D,u._texture),e.texSubImage2D(e.TEXTURE_2D,0,0,0,4,1,e.RGBA,e.FLOAT,new Float32Array(s?De(i,s):i)),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(r))},r){var l=function(){h&&(h=!1,u._updateViewMatrix(t.viewMatrix,t.project.matrix))};t.on("matrix",(function(){return h=!0})),i.on("rendering",l),l()}return u}},{key:"generatePeformanceModelDataTexture",value:function(e,t){var i=e.createTexture();return e.bindTexture(e.TEXTURE_2D,i),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 vs(e,i,4,2)}},{key:"generateTextureForColorsAndFlags",value:function(e,t,i,s,r,n,o){var a=t.length;this.numPortions=a;var u=4096,h=Math.ceil(a/512);if(0==h)throw"texture height == 0";var l=new Uint8Array(16384*h);ms.sizeDataColorsAndFlags+=l.byteLength,ms.numberOfTextures++;for(var c=0;c<a;c++)l.set(t[c],32*c+0),l.set(i[c],32*c+4),l.set([0,0,0,0],32*c+8),l.set([0,0,0,0],32*c+12),l.set([s[c]>>24&255,s[c]>>16&255,s[c]>>8&255,255&s[c]],32*c+16),l.set([r[c]>>24&255,r[c]>>16&255,r[c]>>8&255,255&r[c]],32*c+20),l.set([n[c]>>24&255,n[c]>>16&255,n[c]>>8&255,255&n[c]],32*c+24),l.set([o[c]?1:0,0,0,0],32*c+28);var p=e.createTexture();return e.bindTexture(e.TEXTURE_2D,p),e.texStorage2D(e.TEXTURE_2D,1,e.RGBA8UI,u,h),e.texSubImage2D(e.TEXTURE_2D,0,0,0,u,h,e.RGBA_INTEGER,e.UNSIGNED_BYTE,l,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 vs(e,p,u,h,l)}},{key:"generateTextureForObjectOffsets",value:function(e,t){var i=512,s=Math.ceil(t/i);if(0==s)throw"texture height == 0";var r=new Float32Array(1536*s).fill(0);ms.sizeDataTextureOffsets+=r.byteLength,ms.numberOfTextures++;var n=e.createTexture();return e.bindTexture(e.TEXTURE_2D,n),e.texStorage2D(e.TEXTURE_2D,1,e.RGB32F,i,s),e.texSubImage2D(e.TEXTURE_2D,0,0,0,i,s,e.RGB,e.FLOAT,r,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 vs(e,n,i,s,r)}},{key:"generateTextureForPositionsDecodeMatrices",value:function(e,t,i){var s=t.length;if(0==s)throw"num decode+entity matrices == 0";var r=4096,n=Math.ceil(s/512),o=new Float32Array(16384*n);ms.sizeDataPositionDecodeMatrices+=o.byteLength,ms.numberOfTextures++;for(var a=0;a<t.length;a++)o.set(t[a],32*a),o.set(i[a],32*a+16);var u=e.createTexture();return e.bindTexture(e.TEXTURE_2D,u),e.texStorage2D(e.TEXTURE_2D,1,e.RGBA32F,r,n),e.texSubImage2D(e.TEXTURE_2D,0,0,0,r,n,e.RGBA,e.FLOAT,o,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 vs(e,u,r,n)}},{key:"generateTextureFor8BitIndices",value:function(e,t){if(0==t.length)return{texture:null,textureHeight:0};var i=4096,s=Math.ceil(t.length/3/i);if(0==s)throw"texture height == 0";var r=new Uint8Array(i*s*3);ms.sizeDataTextureIndices+=r.byteLength,ms.numberOfTextures++,r.fill(0),r.set(t,0);var n=e.createTexture();return e.bindTexture(e.TEXTURE_2D,n),e.texStorage2D(e.TEXTURE_2D,1,e.RGB8UI,i,s),e.texSubImage2D(e.TEXTURE_2D,0,0,0,i,s,e.RGB_INTEGER,e.UNSIGNED_BYTE,r,0),this.disableBindedTextureFiltering(e),e.bindTexture(e.TEXTURE_2D,null),new vs(e,n,i,s)}},{key:"generateTextureFor16BitIndices",value:function(e,t){if(0==t.length)return{texture:null,textureHeight:0};var i=4096,s=Math.ceil(t.length/3/i);if(0==s)throw"texture height == 0";var r=new Uint16Array(i*s*3);ms.sizeDataTextureIndices+=r.byteLength,ms.numberOfTextures++,r.fill(0),r.set(t,0);var n=e.createTexture();return e.bindTexture(e.TEXTURE_2D,n),e.texStorage2D(e.TEXTURE_2D,1,e.RGB16UI,i,s),e.texSubImage2D(e.TEXTURE_2D,0,0,0,i,s,e.RGB_INTEGER,e.UNSIGNED_SHORT,r,0),this.disableBindedTextureFiltering(e),e.bindTexture(e.TEXTURE_2D,null),new vs(e,n,i,s)}},{key:"generateTextureFor32BitIndices",value:function(e,t){if(0==t.length)return{texture:null,textureHeight:0};var i=4096,s=Math.ceil(t.length/3/i);if(0==s)throw"texture height == 0";var r=new Uint32Array(i*s*3);ms.sizeDataTextureIndices+=r.byteLength,ms.numberOfTextures++,r.fill(0),r.set(t,0);var n=e.createTexture();return e.bindTexture(e.TEXTURE_2D,n),e.texStorage2D(e.TEXTURE_2D,1,e.RGB32UI,i,s),e.texSubImage2D(e.TEXTURE_2D,0,0,0,i,s,e.RGB_INTEGER,e.UNSIGNED_INT,r,0),this.disableBindedTextureFiltering(e),e.bindTexture(e.TEXTURE_2D,null),new vs(e,n,i,s)}},{key:"generateTextureFor8BitsEdgeIndices",value:function(e,t){if(0==t.length)return{texture:null,textureHeight:0};var i=4096,s=Math.ceil(t.length/2/i);if(0==s)throw"texture height == 0";var r=new Uint8Array(i*s*2);ms.sizeDataTextureEdgeIndices+=r.byteLength,ms.numberOfTextures++,r.fill(0),r.set(t,0);var n=e.createTexture();return e.bindTexture(e.TEXTURE_2D,n),e.texStorage2D(e.TEXTURE_2D,1,e.RG8UI,i,s),e.texSubImage2D(e.TEXTURE_2D,0,0,0,i,s,e.RG_INTEGER,e.UNSIGNED_BYTE,r,0),this.disableBindedTextureFiltering(e),e.bindTexture(e.TEXTURE_2D,null),new vs(e,n,i,s)}},{key:"generateTextureFor16BitsEdgeIndices",value:function(e,t){if(0==t.length)return{texture:null,textureHeight:0};var i=4096,s=Math.ceil(t.length/2/i);if(0==s)throw"texture height == 0";var r=new Uint16Array(i*s*2);ms.sizeDataTextureEdgeIndices+=r.byteLength,ms.numberOfTextures++,r.fill(0),r.set(t,0);var n=e.createTexture();return e.bindTexture(e.TEXTURE_2D,n),e.texStorage2D(e.TEXTURE_2D,1,e.RG16UI,i,s),e.texSubImage2D(e.TEXTURE_2D,0,0,0,i,s,e.RG_INTEGER,e.UNSIGNED_SHORT,r,0),this.disableBindedTextureFiltering(e),e.bindTexture(e.TEXTURE_2D,null),new vs(e,n,i,s)}},{key:"generateTextureFor32BitsEdgeIndices",value:function(e,t){if(0==t.length)return{texture:null,textureHeight:0};var i=4096,s=Math.ceil(t.length/2/i);if(0==s)throw"texture height == 0";var r=new Uint32Array(i*s*2);ms.sizeDataTextureEdgeIndices+=r.byteLength,ms.numberOfTextures++,r.fill(0),r.set(t,0);var n=e.createTexture();return e.bindTexture(e.TEXTURE_2D,n),e.texStorage2D(e.TEXTURE_2D,1,e.RG32UI,i,s),e.texSubImage2D(e.TEXTURE_2D,0,0,0,i,s,e.RG_INTEGER,e.UNSIGNED_INT,r,0),this.disableBindedTextureFiltering(e),e.bindTexture(e.TEXTURE_2D,null),new vs(e,n,i,s)}},{key:"generateTextureForPositions",value:function(e,t){var i=t.length/3,s=4096,r=Math.ceil(i/s);if(0==r)throw"texture height == 0";var n=new Uint16Array(s*r*3);ms.sizeDataTexturePositions+=n.byteLength,ms.numberOfTextures++,n.fill(0),n.set(t,0);var o=e.createTexture();return e.bindTexture(e.TEXTURE_2D,o),e.texStorage2D(e.TEXTURE_2D,1,e.RGB16UI,s,r),e.texSubImage2D(e.TEXTURE_2D,0,0,0,s,r,e.RGB_INTEGER,e.UNSIGNED_SHORT,n,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 vs(e,o,s,r)}},{key:"generateTextureForPackedPortionIds",value:function(e,t){if(0==t.length)return{texture:null,textureHeight:0};var i=t.length,s=4096,r=Math.ceil(i/s);if(0==r)throw"texture height == 0";var n=new Uint16Array(s*r);n.set(t,0),ms.sizeDataTexturePortionIds+=n.byteLength,ms.numberOfTextures++;var o=e.createTexture();return e.bindTexture(e.TEXTURE_2D,o),e.texStorage2D(e.TEXTURE_2D,1,e.R16UI,s,r),e.texSubImage2D(e.TEXTURE_2D,0,0,0,s,r,e.RED_INTEGER,e.UNSIGNED_SHORT,n,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 vs(e,o,s,r)}}]),e}(),ys=q.identityMat4();q.mat4(),q.mat4();var bs=q.vec4([0,0,0,1]),xs=q.vec4([0,0,0,1]),Ps=q.vec4([0,0,0,1]),Ts=q.OBB3(),ws=new Uint8Array(4),Ms=new Float32Array(3),Is=q.vec3(),Cs=q.vec3(),Ds=q.vec3(),As=q.vec3(),ks=q.vec3(),Es=q.vec3(),Fs=q.vec3(),Rs=0,Ss=function(){function e(t,i){var s,r,n;w(this,e),this._layerNumber=Rs++,ms.numberOfLayers++,this.sortId="TrianglesDataTextureLayer-".concat(this._layerNumber),this.layerIndex=i.layerIndex,this._dataTextureRenderers=(s=t.scene,r=s.id,(n=is[r])||(n=new ts(s),is[r]=n,n._compile(),s.on("compile",(function(){n._compile()})),s.on("destroyed",(function(){delete is[r],n._destroy()}))),n),this.model=t,this._buffer=new ss,this._dataTextureState=new gs,this.dataTextureGenerator=new _s,this._state=new ti({metallicRoughnessBuf:null,positionsDecodeMatrix:q.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._modelAABB=q.collapseAABB3(),this._portions=[],this._finalized=!1,this._subPortionIdMapping=[],this._instancedGeometrySubPortionData={},this.aabb=q.collapseAABB3(),this.numUpdatesInFrame=0}return I(e,[{key:"canCreatePortion",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null;if(this._finalized)throw"Already finalized";var i=this._state,s=e.preparedBuckets.length;this._numPortions+s>65536&&ms.cannotCreatePortion.because10BitsObjectId++;var r=this._numPortions+s<=65536,n=null!==t&&t+"#0"in this._instancedGeometrySubPortionData;if(!n){var o=Math.max(i.numIndices8Bits,i.numIndices16Bits,i.numIndices32Bits),a=0,u=e.indices.length/3;e.preparedBuckets.forEach((function(e){a+=e.positions.length/3})),(i.numVertices+a>16777216||o+u>16777216)&&ms.cannotCreatePortion.becauseTextureSize++,r&&(r=i.numVertices+a<=16777216&&o+u<=16777216)}return r}},{key:"createPortion",value:function(e){var t=this,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null;if(this._finalized)throw"Already finalized";var s=null!==i,r=this._subPortionIdMapping.length,n=[];this._subPortionIdMapping.push(n);var o=s?i.aabb:e.aabb;return e.preparedBuckets.forEach((function(r,a){var u;if(s){var h=e.id+"#"+a;h in t._instancedGeometrySubPortionData||(t._instancedGeometrySubPortionData[h]=t.createSubPortionGeometry(r)),u=t._instancedGeometrySubPortionData[h]}else u=t.createSubPortionGeometry(r);var l=q.collapseAABB3(),c=t.createSubPortionObject(s?i:e,u,r.positions,e.positionsDecodeMatrix,s?i.origin:e.origin,l,s,e.solid);q.expandAABB3(o,l),n.push(c)})),this.model.numPortions++,r}},{key:"createSubPortionGeometry",value:function(e){var t=this._state;if(e.indices){var i=8*Math.ceil(e.indices.length/3/8)*3;ms.overheadSizeAlignementIndices+=2*(i-e.indices.length);var s=new Uint32Array(i);s.fill(0),s.set(e.indices),e.indices=s}if(e.edgeIndices){var r=8*Math.ceil(e.edgeIndices.length/2/8)*2;ms.overheadSizeAlignementEdgeIndices+=2*(r-e.edgeIndices.length);var n=new Uint32Array(r);n.fill(0),n.set(e.edgeIndices),e.edgeIndices=n}for(var o,a=e.positions,u=e.indices,h=e.edgeIndices,l=this._buffer,c=l.positions.length/3,p=a.length/3,d=0,f=a.length;d<f;d++)l.positions.push(a[d]);var m,v=0;if(u){var g;v=u.length/3,o=(g=p<=256?l.indices8Bits:p<=65536?l.indices16Bits:l.indices32Bits).length/3;for(var _=0,y=u.length;_<y;_++)g.push(u[_])}var b=0;if(h){var x;b=h.length/2,m=(x=p<=256?l.edgeIndices8Bits:p<=65536?l.edgeIndices16Bits:l.edgeIndices32Bits).length/2;for(var P=0,T=h.length;P<T;P++)x.push(h[P])}return t.numVertices+=p,ms.numberOfGeometries++,{vertexBase:c,numVertices:p,numTriangles:v,numEdges:b,indicesBase:o,edgeIndicesBase:m}}},{key:"createSubPortionObject",value:function(e,t,i,s,r,n,o,a){var u=e.color;e.metallic,e.roughness;var h=e.colors,l=e.opacity,c=e.meshMatrix,p=e.worldMatrix,d=e.pickColor;this.model.scene;var f,m,v=this._buffer,g=this._state;if(v.perObjectPositionsDecodeMatrices.push(s),o?v.perObjectInstancePositioningMatrices.push(c):v.perObjectInstancePositioningMatrices.push(ys),o){var _=q.collapseAABB3();q.expandAABB3Points3(_,i),ui.decompressAABB(_,s);for(var y=q.AABB3ToOBB3(_),b=0,x=y.length;b<x;b+=4)bs[0]=y[b+0],bs[1]=y[b+1],bs[2]=y[b+2],q.transformPoint4(c,bs,xs),p?(q.transformPoint4(p,xs,Ps),q.expandAABB3Point3(n,Ps)):q.expandAABB3Point3(n,xs)}else if(s){var P=ui.getPositionsBounds(i),T=ui.decompressPosition(P.min,s,[]),w=ui.decompressPosition(P.max,s,[]);n[0]=T[0],n[1]=T[1],n[2]=T[2],n[3]=w[0],n[4]=w[1],n[5]=w[2],p&&(q.AABB3ToOBB3(n,Ts),q.transformOBB3(p,Ts),q.OBB3ToAABB3(Ts,n))}else if(c)for(var M=0,I=i.length;M<I;M+=3)bs[0]=i[M+0],bs[1]=i[M+1],bs[2]=i[M+2],q.transformPoint4(c,bs,xs),i[M+0]=xs[0],i[M+1]=xs[1],i[M+2]=xs[2],q.expandAABB3Point3(this._modelAABB,xs),p?(q.transformPoint4(p,xs,Ps),q.expandAABB3Point3(n,Ps)):q.expandAABB3Point3(n,xs);else for(var C=0,D=i.length;C<D;C+=3)bs[0]=i[C+0],bs[1]=i[C+1],bs[2]=i[C+2],q.expandAABB3Point3(this._modelAABB,bs),p?(q.transformPoint4(p,bs,xs),q.expandAABB3Point3(n,xs)):q.expandAABB3Point3(n,bs);r&&(this._state.origin=r,n[0]+=r[0],n[1]+=r[1],n[2]+=r[2],n[3]+=r[0],n[4]+=r[1],n[5]+=r[2]),q.expandAABB3(this.aabb,n),v.perObjectSolid.push(a),h?v.perObjectColors.push([255*h[0],255*h[1],255*h[2],255]):u&&v.perObjectColors.push([u[0],u[1],u[2],l]),v.perObjectPickColors.push(d),v.perObjectVertexBases.push(t.vertexBase),f=t.numVertices<=256?g.numIndices8Bits:t.numVertices<=65536?g.numIndices16Bits:g.numIndices32Bits,v.perObjectIndexBaseOffsets.push(f/3-t.indicesBase),m=t.numVertices<=256?g.numEdgeIndices8Bits:t.numVertices<=65536?g.numEdgeIndices16Bits:g.numEdgeIndices32Bits,v.perObjectEdgeIndexBaseOffsets.push(m/2-t.edgeIndicesBase);var A=this._portions.length;if(t.numTriangles>0){var k,E=3*t.numTriangles;t.numVertices<=256?(k=v.perTriangleNumberPortionId8Bits,g.numIndices8Bits+=E,ms.totalPolygons8Bits+=t.numTriangles):t.numVertices<=65536?(k=v.perTriangleNumberPortionId16Bits,g.numIndices16Bits+=E,ms.totalPolygons16Bits+=t.numTriangles):(k=v.perTriangleNumberPortionId32Bits,g.numIndices32Bits+=E,ms.totalPolygons32Bits+=t.numTriangles),ms.totalPolygons+=t.numTriangles;for(var F=0;F<t.numTriangles;F+=8)k.push(A)}if(t.numEdges>0){var R,S=2*t.numEdges;t.numVertices<=256?(R=v.perEdgeNumberPortionId8Bits,g.numEdgeIndices8Bits+=S,ms.totalEdges8Bits+=t.numEdges):t.numVertices<=65536?(R=v.perEdgeNumberPortionId16Bits,g.numEdgeIndices16Bits+=S,ms.totalEdges16Bits+=t.numEdges):(R=v.perEdgeNumberPortionId32Bits,g.numEdgeIndices32Bits+=S,ms.totalEdges32Bits+=t.numEdges),ms.totalEdges+=t.numEdges;for(var O=0;O<t.numEdges;O+=8)R.push(A)}return v.perObjectOffsets.push([0,0,0]),this._portions.push({numVerts:t.numTriangles}),this._numPortions++,ms.numberOfPortions++,A}},{key:"finalize",value:function(){if(this._finalized)this.model.error("Already finalized");else{var e=this._state,t=this._dataTextureState,i=this.model.scene.canvas.gl,s=this._buffer;e.gl=i,t.texturePerObjectIdColorsAndFlags=this.dataTextureGenerator.generateTextureForColorsAndFlags(i,s.perObjectColors,s.perObjectPickColors,s.perObjectVertexBases,s.perObjectIndexBaseOffsets,s.perObjectEdgeIndexBaseOffsets,s.perObjectSolid),t.texturePerObjectIdOffsets=this.dataTextureGenerator.generateTextureForObjectOffsets(i,this._numPortions),t.texturePerObjectIdPositionsDecodeMatrix=this.dataTextureGenerator.generateTextureForPositionsDecodeMatrices(i,s.perObjectPositionsDecodeMatrices,s.perObjectInstancePositioningMatrices),t.texturePerVertexIdCoordinates=this.dataTextureGenerator.generateTextureForPositions(i,s.positions),t.texturePerPolygonIdPortionIds8Bits=this.dataTextureGenerator.generateTextureForPackedPortionIds(i,s.perTriangleNumberPortionId8Bits),t.texturePerPolygonIdPortionIds16Bits=this.dataTextureGenerator.generateTextureForPackedPortionIds(i,s.perTriangleNumberPortionId16Bits),t.texturePerPolygonIdPortionIds32Bits=this.dataTextureGenerator.generateTextureForPackedPortionIds(i,s.perTriangleNumberPortionId32Bits),s.perEdgeNumberPortionId8Bits.length>0&&(t.texturePerEdgeIdPortionIds8Bits=this.dataTextureGenerator.generateTextureForPackedPortionIds(i,s.perEdgeNumberPortionId8Bits)),s.perEdgeNumberPortionId16Bits.length>0&&(t.texturePerEdgeIdPortionIds16Bits=this.dataTextureGenerator.generateTextureForPackedPortionIds(i,s.perEdgeNumberPortionId16Bits)),s.perEdgeNumberPortionId32Bits.length>0&&(t.texturePerEdgeIdPortionIds32Bits=this.dataTextureGenerator.generateTextureForPackedPortionIds(i,s.perEdgeNumberPortionId32Bits)),s.indices8Bits.length>0&&(t.texturePerPolygonIdIndices8Bits=this.dataTextureGenerator.generateTextureFor8BitIndices(i,s.indices8Bits)),s.indices16Bits.length>0&&(t.texturePerPolygonIdIndices16Bits=this.dataTextureGenerator.generateTextureFor16BitIndices(i,s.indices16Bits)),s.indices32Bits.length>0&&(t.texturePerPolygonIdIndices32Bits=this.dataTextureGenerator.generateTextureFor32BitIndices(i,s.indices32Bits)),s.edgeIndices8Bits.length>0&&(t.texturePerPolygonIdEdgeIndices8Bits=this.dataTextureGenerator.generateTextureFor8BitsEdgeIndices(i,s.edgeIndices8Bits)),s.edgeIndices16Bits.length>0&&(t.texturePerPolygonIdEdgeIndices16Bits=this.dataTextureGenerator.generateTextureFor16BitsEdgeIndices(i,s.edgeIndices16Bits)),s.edgeIndices32Bits.length>0&&(t.texturePerPolygonIdEdgeIndices32Bits=this.dataTextureGenerator.generateTextureFor32BitsEdgeIndices(i,s.edgeIndices32Bits)),this.model._modelMatricesTexture||(this.model._modelMatricesTexture=this.dataTextureGenerator.generatePeformanceModelDataTexture(i,this.model)),t.textureModelMatrices=this.model._modelMatricesTexture,this.model.cameraTexture||(this.model.cameraTexture=this.dataTextureGenerator.generateCameraDataTexture(this.model.scene.canvas.gl,this.model.scene.camera,this.model.scene,this._state.origin.slice())),t.textureCameraMatrices=this.model.cameraTexture,this.model.pickCameraTexture||(this.model.pickCameraTexture=this.dataTextureGenerator.generateCameraDataTexture(this.model.scene.canvas.gl,this.model.scene.camera,this.model.scene,this._state.origin.slice(),!1)),t.texturePickCameraMatrices=this.model.pickCameraTexture,t.finalize(),this._buffer=null,this._instancedGeometrySubPortionData={},this._finalized=!0}}},{key:"attachToRenderingEvent",value:function(){var e=this;this.model.scene.on("rendering",(function(){e._deferredSetFlagsDirty&&e.commitDeferredFlags(),e.numUpdatesInFrame=0}))}},{key:"isEmpty",value:function(){return 0==this._numPortions}},{key:"initFlags",value:function(e,t,i){t&kt&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&Bt&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&Ot&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&Lt&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&Rt&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&Nt&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&Ft&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&Et&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),i&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++);this._setFlags(e,t,i,true),this._setFlags2(e,t,true)}},{key:"flushInitFlags",value:function(){this._setDeferredFlags(),this._setDeferredFlags2()}},{key:"setVisible",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&kt?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,i)}},{key:"setHighlighted",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&Bt?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,i)}},{key:"setXRayed",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&Ot?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,i)}},{key:"setSelected",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&Lt?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,i)}},{key:"setEdges",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&Nt?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,i)}},{key:"setClippable",value:function(e,t){if(!this._finalized)throw"Not finalized";t&Rt?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags2(e,t)}},{key:"beginDeferredFlags",value:function(){this._deferredSetFlagsActive=!0}},{key:"commitDeferredFlags",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,i){if(!this._finalized)throw"Not finalized";t&Et?(this._numCulledLayerPortions+=this._subPortionIdMapping[e].length,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions-=this._subPortionIdMapping[e].length,this.model.numCulledLayerPortions--),this._setFlags(e,t,i)}},{key:"setCollidable",value:function(e,t){if(!this._finalized)throw"Not finalized"}},{key:"setPickable",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&Ft?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,i)}},{key:"setColor",value:function(e,t){for(var i=this._subPortionIdMapping[e],s=0,r=i.length;s<r;s++)this._subPortionSetColor(i[s],t)}},{key:"_subPortionSetColor",value:function(e,t){if(!this._finalized)throw"Not finalized";var i=this._dataTextureState,s=this.model.scene.canvas.gl;ws[0]=t[0],ws[1]=t[1],ws[2]=t[2],ws[3]=t[3],i.texturePerObjectIdColorsAndFlags._textureData.set(ws,32*e),this._deferredSetFlagsActive?this._deferredSetFlagsDirty=!0:(++this.numUpdatesInFrame>=10&&this.beginDeferredFlags(),s.bindTexture(s.TEXTURE_2D,i.texturePerObjectIdColorsAndFlags._texture),s.texSubImage2D(s.TEXTURE_2D,0,e%512*8,Math.floor(e/512),1,1,s.RGBA_INTEGER,s.UNSIGNED_BYTE,ws))}},{key:"setTransparent",value:function(e,t,i){i?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,i)}},{key:"_setFlags",value:function(e,t,i){for(var s=this._subPortionIdMapping[e],r=0,n=s.length;r<n;r++)this._subPortionSetFlags(s[r],t,i)}},{key:"_subPortionSetFlags",value:function(e,t,i){if(!this._finalized)throw"Not finalized";var s,r,n=!!(t&kt),o=!!(t&Ot),a=!!(t&Bt),u=!!(t&Lt),h=!!(t&Nt),l=!!(t&Ft),c=!!(t&Et);s=!n||c||o?Vt:i?zt:Ut,r=!n||c?Vt:u?Xt:a?Wt:o?Yt:Vt;var p=0;p=!n||c?Vt:u?Qt:a?Zt:o?qt:h?i?Jt:Kt:Vt;var d=n&&!c&&l?$t:Vt,f=this._dataTextureState,m=this.model.scene.canvas.gl;ws[0]=s,ws[1]=r,ws[2]=p,ws[3]=d,f.texturePerObjectIdColorsAndFlags._textureData.set(ws,32*e+8),this._deferredSetFlagsActive?this._deferredSetFlagsDirty=!0:(++this.numUpdatesInFrame>=10&&this.beginDeferredFlags(),m.bindTexture(m.TEXTURE_2D,f.texturePerObjectIdColorsAndFlags._texture),m.texSubImage2D(m.TEXTURE_2D,0,e%512*8+2,Math.floor(e/512),1,1,m.RGBA_INTEGER,m.UNSIGNED_BYTE,ws))}},{key:"_setDeferredFlags",value:function(){}},{key:"_setFlags2",value:function(e,t){for(var i=this._subPortionIdMapping[e],s=0,r=i.length;s<r;s++)this._subPortionSetFlags2(i[s],t)}},{key:"_subPortionSetFlags2",value:function(e,t){if(!this._finalized)throw"Not finalized";var i=t&Rt?255:0,s=this._dataTextureState,r=this.model.scene.canvas.gl;ws[0]=i,ws[1]=0,ws[2]=1,ws[3]=2,s.texturePerObjectIdColorsAndFlags._textureData.set(ws,32*e+12),this._deferredSetFlagsActive?this._deferredSetFlagsDirty=!0:(++this.numUpdatesInFrame>=10&&this.beginDeferredFlags(),r.bindTexture(r.TEXTURE_2D,s.texturePerObjectIdColorsAndFlags._texture),r.texSubImage2D(r.TEXTURE_2D,0,e%512*8+3,Math.floor(e/512),1,1,r.RGBA_INTEGER,r.UNSIGNED_BYTE,ws))}},{key:"_setDeferredFlags2",value:function(){}},{key:"setOffset",value:function(e,t){for(var i=this._subPortionIdMapping[e],s=0,r=i.length;s<r;s++)this._subPortionSetOffset(i[s],t)}},{key:"_subPortionSetOffset",value:function(e,t){if(!this._finalized)throw"Not finalized";var i=this._dataTextureState,s=this.model.scene.canvas.gl;Ms[0]=t[0],Ms[1]=t[1],Ms[2]=t[2],i.texturePerObjectIdOffsets._textureData.set(Ms,3*e),this._deferredSetFlagsActive?this._deferredSetFlagsDirty=!0:(++this.numUpdatesInFrame>=10&&this.beginDeferredFlags(),s.bindTexture(s.TEXTURE_2D,i.texturePerObjectIdOffsets._texture),s.texSubImage2D(s.TEXTURE_2D,0,0,e,1,1,s.RGB,s.FLOAT,Ms))}},{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,Ut):this._dataTextureRenderers.colorRendererWithSAO&&this._dataTextureRenderers.colorRendererWithSAO.drawLayer(t,this,Ut):t.pbrEnabled&&this.model.pbrEnabled?this._dataTextureRenderers.colorQualityRenderer&&this._dataTextureRenderers.colorQualityRenderer.drawLayer(t,this,Ut):this._dataTextureRenderers.colorRenderer&&this._dataTextureRenderers.colorRenderer.drawLayer(t,this,Ut))}},{key:"_updateBackfaceCull",value:function(e,t){var i=this.model.backfaces||e.sectioned;if(t.backfaces!==i){var s=t.gl;i?s.disable(s.CULL_FACE):s.enable(s.CULL_FACE),t.backfaces=i}}},{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,zt):this._dataTextureRenderers.colorRenderer&&this._dataTextureRenderers.colorRenderer.drawLayer(t,this,zt))}},{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,Ut))}},{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,Ut))}},{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,Yt))}},{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,Wt))}},{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,Xt))}},{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,Kt)}},{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,Jt)}},{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,Zt)}},{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,Qt)}},{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,qt)}},{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,Ut))}},{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,Ut))}},{key:"drawPickMesh",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._dataTextureRenderers.pickMeshRenderer&&this._dataTextureRenderers.pickMeshRenderer.drawLayer(t,this,$t))}},{key:"drawPickDepths",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._dataTextureRenderers.pickDepthRenderer&&this._dataTextureRenderers.pickDepthRenderer.drawLayer(t,this,$t))}},{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,$t))}},{key:"precisionRayPickSurface",value:function(e,t,i,s,r){if(!this.model.scene.pickSurfacePrecisionEnabled)return!1;var n=this._state,o=this._portions[e];if(!o)return this.model.error("portion not found: "+e),!1;var a=o.quantizedPositions,u=o.indices,h=n.origin,l=o.offset,c=Is,p=Cs;c.set(h?q.subVec3(t,h,Ds):t),p.set(i),l&&q.subVec3(c,l),q.transformRay(this.model.worldNormalMatrix,c,p,c,p);for(var d=As,f=ks,m=Es,v=!1,g=0,_=Fs,y=0,b=u.length;y<b;y+=3){var x=3*u[y],P=3*u[y+1],T=3*u[y+2];if(d[0]=a[x],d[1]=a[x+1],d[2]=a[x+2],f[0]=a[P],f[1]=a[P+1],f[2]=a[P+2],m[0]=a[T],m[1]=a[T+1],m[2]=a[T+2],q.decompressPosition(d,n.positionsDecodeMatrix),q.decompressPosition(f,n.positionsDecodeMatrix),q.decompressPosition(m,n.positionsDecodeMatrix),q.rayTriangleIntersect(c,p,d,f,m,_)){q.transformPoint3(this.model.worldMatrix,_,_),l&&q.addVec3(_,l),h&&q.addVec3(_,h);var w=Math.abs(q.lenVec3(q.subVec3(_,t,[])));(!v||w>g)&&(g=w,s.set(_),r&&q.triangleNormal(d,f,m,r),v=!0)}}return v&&r&&(q.transformVec3(this.model.worldNormalMatrix,r,r),q.normalizeVec3(r)),v}},{key:"destroy",value:function(){var e=this._state;e.metallicRoughnessBuf&&(e.metallicRoughnessBuf.destroy(),e.metallicRoughnessBuf=null),e.destroy()}}]),e}();function Os(e,t,i){var s,r,n,o;if(t){var a=p(as({positions:e.positions,indices:e.indices,edgeIndices:e.edgeIndices}),3);s=a[0],r=a[1],n=a[2]}else s=e.positions,r=e.indices,n=e.edgeIndices;i?o=function(e,t){var i=arguments.length>2&&void 0!==arguments[2]&&arguments[2],s=e.positions||[],r=ls(e.indices||[],t),n=ds(e.edgeIndices||[]);function o(e,t){if(e>t){var i=e;e=t,t=i}function s(i,s){return i!=e?e-i:s!=t?t-s:0}for(var r=0,o=(n.length>>1)-1;r<=o;){var a=o+r>>1,u=s(n[2*a],n[2*a+1]);if(u>0)r=a+1;else{if(!(u<0))return a;o=a-1}}return-r-1}var a=new Int32Array(n.length/2);a.fill(0);var u=s.length/3;if(u>8*(1<<t))return[e];var h=new Int32Array(u);h.fill(-1);var l=[];function c(){h.fill(-1);var e={positions:[],indices:[],edgeIndices:[],maxNumPositions:(1<<t)-t,numPositions:0,bucketNumber:l.length};return l.push(e),e}for(var p=c(),d=0,f=r.length;d<f;d+=3){var m=0,v=r[d],g=r[d+1],_=r[d+2];if(-1==h[v]&&m++,-1==h[g]&&m++,-1==h[_]&&m++,m+p.numPositions>p.maxNumPositions&&(p=c()),p.bucketNumber>8)return[e];-1==h[v]&&(h[v]=p.numPositions++,p.positions.push(s[3*v]),p.positions.push(s[3*v+1]),p.positions.push(s[3*v+2])),-1==h[g]&&(h[g]=p.numPositions++,p.positions.push(s[3*g]),p.positions.push(s[3*g+1]),p.positions.push(s[3*g+2])),-1==h[_]&&(h[_]=p.numPositions++,p.positions.push(s[3*_]),p.positions.push(s[3*_+1]),p.positions.push(s[3*_+2])),p.indices.push(h[v]),p.indices.push(h[g]),p.indices.push(h[_]);var y=void 0;(y=o(v,g))>=0&&0==a[y]&&(a[y]=1,p.edgeIndices.push(h[n[2*y]]),p.edgeIndices.push(h[n[2*y+1]])),(y=o(v,_))>=0&&0==a[y]&&(a[y]=1,p.edgeIndices.push(h[n[2*y]]),p.edgeIndices.push(h[n[2*y+1]])),(y=o(g,_))>=0&&0==a[y]&&(a[y]=1,p.edgeIndices.push(h[n[2*y]]),p.edgeIndices.push(h[n[2*y+1]]))}var b=t/8*2,x=t/8,P=2*s.length+(r.length+n.length)*b,T=0;return s.length,l.forEach((function(e){T+=2*e.positions.length+(e.indices.length+e.edgeIndices.length)*x,e.positions.length})),T>P?[e]:(i&&fs(l,e),l)}({positions:s,indices:r,edgeIndices:n},s.length/3>65536?16:8):o=[{positions:s,indices:r,edgeIndices:n}];return e.preparedBuckets=o,e}var Bs=function(){function e(){w(this,e),this.visibleLayers=[],this.sectionPlanesActivePerLayer=[],this.reset()}return I(e,[{key:"reset",value:function(){this.culled=!1,this.sectioned=!1,this.numLayers=0,this.numVisibleLayers=0,this.colorOpaque=!1,this.colorTransparent=!1,this.edgesOpaque=!1,this.edgesTransparent=!1,this.xrayedSilhouetteOpaque=!1,this.xrayedEdgesOpaque=!1,this.xrayedSilhouetteTransparent=!1,this.xrayedEdgesTransparent=!1,this.highlightedSilhouetteOpaque=!1,this.highlightedEdgesOpaque=!1,this.highlightedSilhouetteTransparent=!1,this.highlightedEdgesTransparent=!1,this.selectedSilhouetteOpaque=!1,this.selectedEdgesOpaque=!1,this.selectedSilhouetteTransparent=!1,this.selectedEdgesTransparent=!1}}]),e}(),Ls=!1,Ns=[];var js=function(){function e(t,i){w(this,e),this.triangleLODLevels=t,this.nodesInLOD={},this.triangleCountInLOD={},this.targetFps=i,this.lodLevelIndex=0,this.consecutiveFramesWithTargetFps=0,this.consecutiveFramesWithoutTargetFps=0}return I(e,[{key:"initializeLodState",value:function(e){if(0!=e._nodeList.length){for(var t=e._nodeList,i={},s={},r=0,n=t.length;r<n;r++){var o,a=t[r],u=void 0;for(u=0,o=this.triangleLODLevels.length;u<o&&!(a.numTriangles>=this.triangleLODLevels[u]);u++);var h=this.triangleLODLevels[u]||0;h in i||(i[h]=[]),i[h].push(a),h in s||(s[h]=0),s[h]+=a.numTriangles}this.nodesInLOD=i,this.triangleCountInLOD=s}}}]),e}(),Gs=function(){function e(t,i,s){w(this,e),this.model=t,this.lodState=new js(i,s),console.time("initializeLodState"),this.lodState.initializeLodState(t),console.timeEnd("initializeLodState"),function(e,t){if(!Ls){Ls=!0;var i=new Array(4),s=0,r=-1,n=Date.now(),o=0;e.on("rendering",(function(){if(-1!=r)for(var e=0,t=Ns.length;e<t;e++)Ns[e].applyLodCulling(r)})),e.on("rendered",(function(){n=Date.now(),window.requestAnimationFrame((function(){s++;var e=Date.now();o=e-n,n=e,i[s%4]=o;var t=0;if(s>4){for(var a=0;a<4;a++)t+=i[a];r=4/t*1e3}}))}));var a=0,u=a;e.camera.on("matrix",(function(){u=a})),e.on("tick",(function(){if(a-u>3)for(var e=0,t=Ns.length;e<t;e++)Ns[e].resetLodCulling();a++}))}Ns.push(t)}(this.model.scene,this)}return I(e,[{key:"_increaseLODLevelIndex",value:function(){var e=this.lodState;if(e.lodLevelIndex==e.triangleLODLevels.length)return!1;for(var t=e.nodesInLOD[e.triangleLODLevels[e.lodLevelIndex]]||[],i=0,s=t.length;i<s;i++)t[i].culledLOD=!0;return e.lodLevelIndex++,!0}},{key:"_decreaseLODLevelIndex",value:function(){var e=this.lodState;if(0==e.lodLevelIndex)return!1;for(var t=e.nodesInLOD[e.triangleLODLevels[e.lodLevelIndex-1]]||[],i=0,s=t.length;i<s;i++)t[i].culledLOD=!1;return e.lodLevelIndex--,!0}},{key:"applyLodCulling",value:function(e){var t=this.lodState;this.model;var i=!1;return e<t.targetFps?++t.consecutiveFramesWithoutTargetFps>0&&(t.consecutiveFramesWithoutTargetFps=0,i=this._increaseLODLevelIndex()):e>t.targetFps+4&&++t.consecutiveFramesWithTargetFps>1&&(t.consecutiveFramesWithTargetFps=0,i=this._decreaseLODLevelIndex()),i&&console.log("LOD level = "+t.lodLevelIndex),i}},{key:"resetLodCulling",value:function(){this.model;var e=!1,t=!1;do{e|=t=this._decreaseLODLevelIndex()}while(t);return e&&console.log("LOD resetted"),e}}]),e}(),Hs={},Vs={};!function(e){if("object"===T(Vs)&&void 0!==Hs)Hs.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,i,s){function r(o,a){if(!i[o]){if(!t[o]){var u="function"==typeof require&&require;if(!a&&u)return u(o,!0);if(n)return n(o,!0);var h=new Error("Cannot find module '"+o+"'");throw h.code="MODULE_NOT_FOUND",h}var l=i[o]={exports:{}};t[o][0].call(l.exports,(function(e){return r(t[o][1][e]||e)}),l,l.exports,e,t,i,s)}return i[o].exports}for(var n="function"==typeof require&&require,o=0;o<s.length;o++)r(s[o]);return r}({1:[function(e,t,i){Object.defineProperty(i,"__esModule",{value:!0});var s=e("quickselect"),r=[],n=function(e){return r.push(e)},o=function e(t){t&&(n(t),l(t)||t.children.forEach(e))},a=function(e){var t=r.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},u=[],h=function(e,t){var i=u.pop();return i?(i.dist=e,i.node=t):i={dist:e,node:t},i},l=function(e){return e.leaf},c=function(e,t){return e.leaf},p=function(e,t,i){if(!i)return t.indexOf(e);for(var s=0;s<t.length;s++)if(i(e,t[s]))return s;return-1},d=function(e){f(e,0,e.children.length,e)},f=function(e,t,i,s){var r=s;r?(r.minX=1/0,r.minY=1/0,r.minZ=1/0,r.maxX=-1/0,r.maxY=-1/0,r.maxZ=-1/0):r=a([]);for(var n=t,o=void 0;n<i;n++)o=e.children[n],m(r,o);return r},m=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},v=function(e){return(e.maxX-e.minX)*(e.maxY-e.minY)*(e.maxZ-e.minZ)},g=function(e){return e.maxX-e.minX+(e.maxY-e.minY)+(e.maxZ-e.minZ)},_=function(e,t){var i=Math.min(e.minX,t.minX),s=Math.min(e.minY,t.minY),r=Math.min(e.minZ,t.minZ);return(Math.max(e.maxX,t.maxX)-i)*(Math.max(e.maxY,t.maxY)-s)*(Math.max(e.maxZ,t.maxZ)-r)},y=function(e,t){var i=Math.max(e.minX,t.minX),s=Math.max(e.minY,t.minY),r=Math.max(e.minZ,t.minZ),n=Math.min(e.maxX,t.maxX),o=Math.min(e.maxY,t.maxY),a=Math.min(e.maxZ,t.maxZ);return Math.max(0,n-i)*Math.max(0,o-s)*Math.max(0,a-r)},b=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};i.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},i.boxRayIntersects=function(e,t,i,s,r,n,o){var a=(e.minX-t)*r,u=(e.maxX-t)*r,h=(e.minY-i)*n,l=(e.maxY-i)*n,c=(e.minZ-s)*o,p=(e.maxZ-s)*o,d=Math.min(c,p),f=Math.max(c,p),m=Math.min(h,l),v=Math.max(h,l),g=Math.min(a,u),_=Math.max(a,u),y=Math.max(0,g,m,d);return Math.min(_,v,f)>=y?y:1/0};var x=function(e,t,i,r,n){for(var o,a=[t,i];a.length;)(i=a.pop())-(t=a.pop())<=r||(o=t+Math.ceil((i-t)/r/2)*r,s(e,o,t,i,n),a.push(t,o,o,i))},P=function(e,t){return e.minX-t.minX},T=function(e,t){return e.minY-t.minY},w=function(e,t){return e.minZ-t.minZ},M=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 i=this.data,s=[];if(!e(i,c(i)))return s;for(var r=[];i;){for(var n=0,o=i.children.length;n<o;n++){var a=i.children[n];e(a,c(i))&&(c(i)?s.push(a):t(a)?this._all(a,s):r.push(a))}i=r.pop()}return s},e.prototype.analyzeTriangles=function(e){void 0===e&&(e=this.data);var t=0;if(l(e))for(var i=0,s=e.children.length;i<s;i++)t+=e.children[i].numTriangles;else for(i=0,s=e.children.length;i<s;i++)t+=this.analyzeTriangles(e.children[i]);return e.totalTriangles=t},e.prototype.groupNodesByNumTrianglesThreshold=function(e,t){void 0===t&&(this.analyzeTriangles(),t=this.data);for(var i=[],s=0,r=t.children.length;s<r;s++){var n=t.children[s];i.push({item:n,triangles:n.totalTriangles||n.numTriangles})}i.sort((function(e,t){return-(e.item.triangles-t.item.triangles)}));var o=[],a=[],u=0;for(s=0,r=i.length;s<r;s++){var h=i[s];if(u+h.triangles<e)a.push(h),u+=h.triangles;else if(a.length&&(o.push(a),a=[],u=0),u+h.triangles<e)s--;else if(c(t,h.item))o.push([h]);else{for(var l=this.groupNodesByNumTrianglesThreshold(e,h.item),p=[],d=0,f=0,m=l.length;f<m-1;f++)o.push(l[s]);if(l.length>1){for(f=0,m=(l=l[l.length-1]).length;f<m;f++)(d+=l[f].triangles)<e?p.push(l[f]):(0==d&&p.push(l[f]),o.push(p),d=0,p=[]);p.forEach((function(e){a.push(e),u+=e.triangles}))}}}return a.length&&o.push(a),o},e.prototype.search=function(e){var t=this.data,s=[];if(!i.intersects(e,t))return s;for(var r=[];t;){for(var n=0,o=t.children.length;n<o;n++){var a=t.children[n];i.intersects(e,a)&&(c(t)?s.push(a):b(e,a)?this._all(a,s):r.push(a))}t=r.pop()}return s},e.prototype.collides=function(e){var t=this.data;if(!i.intersects(e,t))return!1;for(var s=[];t;){for(var r=0,n=t.children.length;r<n;r++){var o=t.children[r];if(i.intersects(e,o)){if(c(t)||b(e,o))return!0;s.push(o)}}t=s.pop()}return!1},e.prototype.raycastInv=function(e,t,s,r,n,o,a){void 0===a&&(a=1/0);var l=this.data;if(r===1/0&&n===1/0&&o===1/0)return h(1/0,void 0);if(i.boxRayIntersects(l,e,t,s,r,n,o)===1/0)return h(1/0,void 0);for(var p,d=[h(0,l)],f=function(e,t){var i=d[e];d[e]=d[t],d[t]=i},m=function(){var e=d[0],t=d.length-1;d[0]=d[t],d.length=t;for(var i=0;;){var s=i<<1|1;if(s>=t)break;var r=s+1;if(r<t&&d[r].dist<d[s].dist&&(s=r),d[i].dist<d[s].dist)break;f(i,s),i=s}return function(e){u.push(e)}(e),e.node},v=function(e,t){var i=d.length;for(d.push(h(e,t));i>0;){var s=i-1>>1;if(d[s].dist<=d[i].dist)break;f(i,s),i=s}},g=a;d.length&&d[0].dist<g;)for(var _=0,y=(l=m()).children.length;_<y;_++){var b=l.children[_],x=i.boxRayIntersects(b,e,t,s,r,n,o);if(c(l)){if(x<g){if(0===x)return h(x,b);g=x,p=b}}else v(x,b)}return h(g<a?g:1/0,p)},e.prototype.raycast=function(e,t,i,s,r,n,o){return void 0===o&&(o=1/0),this.raycastInv(e,t,i,1/s,1/r,1/n,o)},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,i=e.length;t<i;t++)this.insert(e[t]);return this}var s=this.build(e.slice(),0,e.length-1,0);if(this.data.children.length)if(this.data.height===s.height)this.splitRoot(this.data,s);else{if(this.data.height<s.height){var r=this.data;this.data=s,s=r}this._insert(s,this.data.height-s.height-1,!0)}else this.data=s;return this},e.prototype.insert=function(e){return e&&this._insert(e,this.data.height-1),this},e.prototype.clear=function(){return this.data&&o(this.data),this.data=a([]),this},e.prototype.remove=function(e,t){if(!e)return this;for(var i,s,r=this.data,n=0,o=!1,a=[],u=[];r||a.length;){if(r||(r=a.pop(),n=u.pop(),s=a[a.length-1],o=!0),l(r)&&-1!==(i=p(e,r.children,t)))return r.children.splice(i,1),a.push(r),this.condense(a),this;o||l(r)||!b(r,e)?s?(n++,r=s.children[n],o=!1):r=void 0:(a.push(r),u.push(n),n=0,s=r,r=r.children[0])}return this},e.prototype.toJSON=function(){return this.data},e.prototype.fromJSON=function(e){return o(this.data),this.data=e,this},e.prototype.build=function(e,t,i,s){var r,n=i-t+1,o=this.maxEntries;if(n<=o)return r=a(e.slice(t,i+1)),d(r),r;s||(s=Math.ceil(Math.log(n)/Math.log(o)),o=Math.ceil(n/Math.pow(o,s-1))),(r=a([])).leaf=!1,r.height=s;var u=Math.ceil(n/o),h=u*Math.ceil(Math.pow(o,2/3)),l=u*Math.ceil(Math.pow(o,1/3));x(e,t,i,l,P);for(var c=t;c<=i;c+=l){var p=Math.min(c+l-1,i);x(e,c,p,h,T);for(var f=c;f<=p;f+=h){var m=Math.min(f+h-1,p);x(e,f,m,u,w);for(var v=f;v<=m;v+=u){var g=Math.min(v+u-1,m);r.children.push(this.build(e,v,g,s-1))}}}return d(r),r},e.prototype._all=function(e,t){for(var i=[];e;)l(e)?t.push.apply(t,e.children):i.push.apply(i,e.children),e=i.pop();return t},e.prototype.chooseSubtree=function(e,t,i,s){for(var r,n,o;s.push(t),!l(t)&&s.length-1!==i;){r=n=1/0;for(var a=0,u=t.children.length;a<u;a++){var h=t.children[a],c=v(h),p=_(e,h)-c;p<n?(n=p,r=c<r?c:r,o=h):p===n&&c<r&&(r=c,o=h)}t=o||t.children[0]}return t},e.prototype.split=function(e,t){var i=e[t],s=i.children.length,r=this.minEntries;this.chooseSplitAxis(i,r,s);var n=this.chooseSplitIndex(i,r,s),o=a(i.children.splice(n,i.children.length-n));o.height=i.height,o.leaf=i.leaf,d(i),d(o),t?e[t-1].children.push(o):this.splitRoot(i,o)},e.prototype.splitRoot=function(e,t){this.data=a([e,t]),this.data.height=e.height+1,this.data.leaf=!1,d(this.data)},e.prototype.chooseSplitIndex=function(e,t,i){for(var s,r=1/0,n=1/0,o=t;o<=i-t;o++){var a=f(e,0,o),u=f(e,o,i),h=y(a,u),l=v(a)+v(u);h<r?(r=h,s=o,n=l<n?l:n):h===r&&l<n&&(n=l,s=o)}return s},e.prototype.chooseSplitAxis=function(e,t,i){var s=this.allDistMargin(e,t,i,P),r=this.allDistMargin(e,t,i,T),n=this.allDistMargin(e,t,i,w);s<r&&s<n?e.children.sort(P):r<s&&r<n&&e.children.sort(T)},e.prototype.allDistMargin=function(e,t,i,s){e.children.sort(s);for(var r=f(e,0,t),n=f(e,i-t,i),o=g(r)+g(n),a=t;a<i-t;a++){var u=e.children[a];m(r,u),o+=g(r)}for(a=i-t-1;a>=t;a--){u=e.children[a];m(n,u),o+=g(n)}return o},e.prototype.adjustParentBBoxes=function(e,t,i){for(var s=i;s>=0;s--)m(t[s],e)},e.prototype.condense=function(e){for(var t=e.length-1,i=void 0;t>=0;t--)0===e[t].children.length?t>0?((i=e[t-1].children).splice(i.indexOf(e[t]),1),n(e[t])):this.clear():d(e[t])},e.prototype._insert=function(e,t,i){var s=[],r=this.chooseSubtree(e,this.data,t,s);for(r.children.push(e),m(r,e);t>=0&&s[t].children.length>this.maxEntries;)this.split(s,t),t--;this.adjustParentBBoxes(e,s,t)},e.pool=[],e}();i.RBush3D=M},{quickselect:2}],2:[function(e,t,i){!function(e,s){"object"===T(i)&&void 0!==t?t.exports=s():e.quickselect=s()}(this,(function(){function e(i,s,r,n,o){for(;n>r;){if(n-r>600){var a=n-r+1,u=s-r+1,h=Math.log(a),l=.5*Math.exp(2*h/3),c=.5*Math.sqrt(h*l*(a-l)/a)*(u-a/2<0?-1:1);e(i,s,Math.max(r,Math.floor(s-u*l/a+c)),Math.min(n,Math.floor(s+(a-u)*l/a+c)),o)}var p=i[s],d=r,f=n;for(t(i,r,s),o(i[n],p)>0&&t(i,r,n);d<f;){for(t(i,d,f),d++,f--;o(i[d],p)<0;)d++;for(;o(i[f],p)>0;)f--}0===o(i[r],p)?t(i,r,f):t(i,++f,n),f<=s&&(r=f+1),s<=f&&(n=f-1)}}function t(e,t,i){var s=e[t];e[t]=e[i],e[i]=s}function i(e,t){return e<t?-1:e>t?1:0}return function(t,s,r,n,o){e(t,s,r||0,n||t.length-1,o||i)}}))},{}]},{},[1])(1)}));var Us=Hs.exports.RBush3D,zs=function(e){function t(e){var t=0;return e.meshes.forEach((function(e){t+=e.numTriangles})),t}function i(e,t){var i={pos:{x:0,y:0},left:0,right:e,top:0,bottom:t,dir:0};function s(){(0==i.dir&&i.pos.x+1>=i.right||1==i.dir&&i.pos.y+1>=i.bottom||2==i.dir&&i.pos.x-1<=i.left-1||3==i.dir&&i.pos.y-1<=i.top-1)&&(i.dir=(i.dir+1)%4,0==i.dir&&i.left++,1==i.dir&&i.top++,2==i.dir&&i.right--,3==i.dir&&i.bottom--),0==i.dir&&i.pos.x++,1==i.dir&&i.pos.y++,2==i.dir&&i.pos.x--,3==i.dir&&i.pos.y--}for(var r=[],n=e*t;r.length<n;s())r.push(i.pos.x+"_"+i.pos.y);return r}var s=0,r=function(s){var r=function(t,i){for(var s=i||function(e){return!0},r=(e.aabbTree.data.maxX-e.aabbTree.data.minX)/10,n=(e.aabbTree.data.maxZ-e.aabbTree.data.minZ)/10,o=[],a=e.aabbTree.data.minX,u=0;u<10;u++,a+=r)for(var h=e.aabbTree.data.minZ,l=0;l<10;l++,h+=n)o.push({minX:a,maxX:a+r,minY:-1e8,maxY:1e8,minZ:h,maxZ:h+n,indexX:u,indexZ:l});var c={cellsByEntity:{},entitiesByCell:{},cellsX:10,cellsZ:10};return(o||[]).forEach((function(t){e.aabbTree.search(t).filter((function(e){return s(e.entity)})).forEach((function(e){var i=e.entity.id;c.cellsByEntity[i]=c.cellsByEntity[i]||{cells:[],entity:e.entity},c.cellsByEntity[i].cells.push(t);var s=t.indexX+"_"+t.indexZ;c.entitiesByCell[s]=c.entitiesByCell[s]||{entities:[],cell:t},c.entitiesByCell[s].entities.push(e.entity)}))})),c}(s.cellSideInMeters,s.entityFilterFunc),n=function(e,i){var s={},r=0;Object.keys(i).forEach((function(e){var n=i[e].cells.length,o=t(i[e].entity);s[n]=(s[n]||0)+o,r+=o}));var n=Object.keys(s);n.sort((function(e,t){return e-t}));for(var o=0,a=0,u=0;u<n.length&&a<e;u++)o=n[u],a+=s[o]/r;return{maxCellsPerEntity:o,polygonStats:{percentClustered:a,numberClustered:Math.round(a*r),numberUnclustered:r-Math.round(a*r)}}}(s.minPercentOfClustredPolygons,r.cellsByEntity),o=function(e,s,r,n,o,a){var u={},h={accumEntities:[]},l=[];i(e,s).forEach((function(e){var i=function(e,t,i,s){return(i[e]||{entities:[]}).entities.filter((function(e){return s[e.id].cells.length<=t}))}(e,r,n,o).filter((function(e){return!(e.id in u)}));i.forEach((function(e){u[e.id]=!0})),i.sort((function(e,i){return t(e)-t(i)}));var s=h.accumEntities.concat(i),c=[],p=a,d=0;do{for(;d<s.length;d++){var f=s[d],m=t(f);m>p&&(l.push(c),c=[],p=a),c.push(f),p-=m}}while(d<s.length);h.accumEntities=c})),h.accumEntities.length&&l.push(h.accumEntities);var c=[];Object.keys(o).forEach((function(e){e in u||c.push(o[e].entity)}));var p=a,d=[];c.forEach((function(e){var i=t(e);i>p&&(l.push(d),d=[],p=a),d.push(e),p-=i})),d.length&&l.push(d);var f={};return l.forEach((function(e,t){e.forEach((function(e){f[e.id]=t}))})),{clusters:l,entityIdToClusterIdMapping:f}}(r.cellsX,r.cellsZ,n.maxCellsPerEntity,r.entitiesByCell,r.cellsByEntity,s.maxPolygonsPerCluster);return{clusters:{total:o.clusters.length},clusteringResult:o}}({cellSideInMeters:.05,entityFilterFunc:function(e){return!0},maxPolygonsPerCluster:9e4,minPercentOfClustredPolygons:.9});s+=r.clusters.total,console.log("Total clusters: "+s);var n=[];return r.clusteringResult.clusters.forEach((function(e){e.forEach((function(e){n.push(e.id)}))})),r.orderedEntityIds=n,r};
17
+ **/var us=null;function hs(e,t){var i,s,r,n,o,a,u=3*e,h=3*t,l=Math.min(i=us[u],s=us[u+1],r=us[u+2]),c=Math.min(n=us[h],o=us[h+1],a=us[h+2]);if(l!=c)return l-c;var p=Math.max(i,s,r),d=Math.max(n,o,a);return p!=d?p-d:0}function ls(e,t){for(var i=new Int32Array(e.length/3),s=0,r=i.length;s<r;s++)i[s]=s;us=new Int32Array(e.length);for(var n=0,o=e.length;n<o;n++)us[n]=e[n]>>t;i.sort(hs);for(var a=new Int32Array(e.length),u=0,h=i.length;u<h;u++)a[3*u+0]=e[3*i[u]+0],a[3*u+1]=e[3*i[u]+1],a[3*u+2]=e[3*i[u]+2];return a}var cs=null;function ps(e,t){var i=cs[2*e]-cs[2*t];return 0!=i?i:cs[2*e+1]-cs[2*t+1]}function ds(e){if(0==(e||[]).length)return[];for(var t=new Int32Array(e.length/2),i=0,s=t.length;i<s;i++)t[i]=i;for(var r=0,n=e.length;r<n;r+=2)if(e[r]>e[r+1]){var o=e[r];e[r]=e[r+1],e[r+1]=o}cs=new Int32Array(e),t.sort(ps);for(var a=new Int32Array(e.length),u=0,h=t.length;u<h;u++)a[2*u+0]=e[2*t[u]+0],a[2*u+1]=e[2*t[u]+1];return a}function fs(e,t){var i={},s={};e.forEach((function(e){for(var t=e.indices,r=e.edgeIndices,n=e.positions,o=0,a=t.length;o<a;o+=3){var u=n[3*t[o]]+"_"+n[3*t[o]+1]+"_"+n[3*t[o]+2]+"/"+n[3*t[o+1]]+"_"+n[3*t[o+1]+1]+"_"+n[3*t[o+1]+2]+"/"+n[3*t[o+2]]+"_"+n[3*t[o+2]+1]+"_"+n[3*t[o+2]+2];i[u]=!0}e.edgeIndices.length/2;for(o=0,a=r.length;o<a;o+=2){u=n[3*r[o]]+"_"+n[3*r[o]+1]+"_"+n[3*r[o]+2]+"/"+n[3*r[o+1]]+"_"+n[3*r[o+1]+1]+"_"+n[3*r[o+1]+2]+"/";s[u]=!0}}));var r=t.indices;t.edgeIndices;for(var n=t.positions,o=0,a=r.length;o<a;o+=3){var u=n[3*r[o]]+"_"+n[3*r[o]+1]+"_"+n[3*r[o]+2]+"/"+n[3*r[o+1]]+"_"+n[3*r[o+1]+1]+"_"+n[3*r[o+1]+2]+"/"+n[3*r[o+2]]+"_"+n[3*r[o+2]+1]+"_"+n[3*r[o+2]+2];if(!(u in i))throw console.log("Not found "+u),"Ohhhh!"}}var ms={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(ms,null,4));var e=0;Object.keys(ms).forEach((function(t){t.startsWith("size")&&(e+=ms[t])})),console.log("Total size ".concat(e," bytes (").concat((e/1e3/1e3).toFixed(2)," MB)")),console.log("Avg bytes / triangle: ".concat((e/ms.totalPolygons).toFixed(2)));var t={};Object.keys(ms).forEach((function(i){i.startsWith("size")&&(t[i]="".concat((ms[i]/e*100).toFixed(2)," % of total"))})),console.log(JSON.stringify({percentualRamUsage:t},null,4))};var vs=function(){function e(t,i,s,r){var n=arguments.length>4&&void 0!==arguments[4]?arguments[4]:null;w(this,e),this._gl=t,this._texture=i,this._textureWidth=s,this._textureHeight=r,this._textureData=n}return I(e,[{key:"bindTexture",value:function(e,t,i){return e.bindTexture(t,this,i)}},{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}(),gs=function(){function e(){w(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 I(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,i,s,r,n,o){this.texturePerObjectIdPositionsDecodeMatrix.bindTexture(e,t,1),this.texturePerVertexIdCoordinates.bindTexture(e,i,2),this.texturePerObjectIdColorsAndFlags.bindTexture(e,s,3),this.textureCameraMatrices.bindTexture(e,r,4),this.textureModelMatrices.bindTexture(e,n,5),this.texturePerObjectIdOffsets.bindTexture(e,o,6)}},{key:"bindPickCameraTexture",value:function(e,t){this.texturePickCameraMatrices.bindTexture(e,t,4)}},{key:"bindTriangleIndicesTextures",value:function(e,t,i,s){this.indicesPortionIdsPerBitnessTextures[s].bindTexture(e,t,7),this.indicesPerBitnessTextures[s].bindTexture(e,i,8)}},{key:"bindEdgeIndicesTextures",value:function(e,t,i,s){this.edgeIndicesPortionIdsPerBitnessTextures[s].bindTexture(e,t,7),this.edgeIndicesPerBitnessTextures[s].bindTexture(e,i,8)}}]),e}(),_s=function(){function e(){w(this,e)}return I(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,i,s){var r=!(arguments.length>4&&void 0!==arguments[4])||arguments[4],n=4,o=3,a=e.createTexture();e.bindTexture(e.TEXTURE_2D,a),e.texStorage2D(e.TEXTURE_2D,1,e.RGBA32F,n,o),this.disableBindedTextureFiltering(e),e.bindTexture(e.TEXTURE_2D,null);var u=new vs(e,a,n,o),h=!0;if(u._updateViewMatrix=function(i,r){e.bindTexture(e.TEXTURE_2D,u._texture),e.texSubImage2D(e.TEXTURE_2D,0,0,0,4,1,e.RGBA,e.FLOAT,new Float32Array(s?De(i,s):i)),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(r))},r){var l=function(){h&&(h=!1,u._updateViewMatrix(t.viewMatrix,t.project.matrix))};t.on("matrix",(function(){return h=!0})),i.on("rendering",l),l()}return u}},{key:"generatePeformanceModelDataTexture",value:function(e,t){var i=e.createTexture();return e.bindTexture(e.TEXTURE_2D,i),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 vs(e,i,4,2)}},{key:"generateTextureForColorsAndFlags",value:function(e,t,i,s,r,n,o){var a=t.length;this.numPortions=a;var u=4096,h=Math.ceil(a/512);if(0==h)throw"texture height == 0";var l=new Uint8Array(16384*h);ms.sizeDataColorsAndFlags+=l.byteLength,ms.numberOfTextures++;for(var c=0;c<a;c++)l.set(t[c],32*c+0),l.set(i[c],32*c+4),l.set([0,0,0,0],32*c+8),l.set([0,0,0,0],32*c+12),l.set([s[c]>>24&255,s[c]>>16&255,s[c]>>8&255,255&s[c]],32*c+16),l.set([r[c]>>24&255,r[c]>>16&255,r[c]>>8&255,255&r[c]],32*c+20),l.set([n[c]>>24&255,n[c]>>16&255,n[c]>>8&255,255&n[c]],32*c+24),l.set([o[c]?1:0,0,0,0],32*c+28);var p=e.createTexture();return e.bindTexture(e.TEXTURE_2D,p),e.texStorage2D(e.TEXTURE_2D,1,e.RGBA8UI,u,h),e.texSubImage2D(e.TEXTURE_2D,0,0,0,u,h,e.RGBA_INTEGER,e.UNSIGNED_BYTE,l,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 vs(e,p,u,h,l)}},{key:"generateTextureForObjectOffsets",value:function(e,t){var i=512,s=Math.ceil(t/i);if(0==s)throw"texture height == 0";var r=new Float32Array(1536*s).fill(0);ms.sizeDataTextureOffsets+=r.byteLength,ms.numberOfTextures++;var n=e.createTexture();return e.bindTexture(e.TEXTURE_2D,n),e.texStorage2D(e.TEXTURE_2D,1,e.RGB32F,i,s),e.texSubImage2D(e.TEXTURE_2D,0,0,0,i,s,e.RGB,e.FLOAT,r,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 vs(e,n,i,s,r)}},{key:"generateTextureForPositionsDecodeMatrices",value:function(e,t,i){var s=t.length;if(0==s)throw"num decode+entity matrices == 0";var r=4096,n=Math.ceil(s/512),o=new Float32Array(16384*n);ms.sizeDataPositionDecodeMatrices+=o.byteLength,ms.numberOfTextures++;for(var a=0;a<t.length;a++)o.set(t[a],32*a),o.set(i[a],32*a+16);var u=e.createTexture();return e.bindTexture(e.TEXTURE_2D,u),e.texStorage2D(e.TEXTURE_2D,1,e.RGBA32F,r,n),e.texSubImage2D(e.TEXTURE_2D,0,0,0,r,n,e.RGBA,e.FLOAT,o,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 vs(e,u,r,n)}},{key:"generateTextureFor8BitIndices",value:function(e,t){if(0==t.length)return{texture:null,textureHeight:0};var i=4096,s=Math.ceil(t.length/3/i);if(0==s)throw"texture height == 0";var r=new Uint8Array(i*s*3);ms.sizeDataTextureIndices+=r.byteLength,ms.numberOfTextures++,r.fill(0),r.set(t,0);var n=e.createTexture();return e.bindTexture(e.TEXTURE_2D,n),e.texStorage2D(e.TEXTURE_2D,1,e.RGB8UI,i,s),e.texSubImage2D(e.TEXTURE_2D,0,0,0,i,s,e.RGB_INTEGER,e.UNSIGNED_BYTE,r,0),this.disableBindedTextureFiltering(e),e.bindTexture(e.TEXTURE_2D,null),new vs(e,n,i,s)}},{key:"generateTextureFor16BitIndices",value:function(e,t){if(0==t.length)return{texture:null,textureHeight:0};var i=4096,s=Math.ceil(t.length/3/i);if(0==s)throw"texture height == 0";var r=new Uint16Array(i*s*3);ms.sizeDataTextureIndices+=r.byteLength,ms.numberOfTextures++,r.fill(0),r.set(t,0);var n=e.createTexture();return e.bindTexture(e.TEXTURE_2D,n),e.texStorage2D(e.TEXTURE_2D,1,e.RGB16UI,i,s),e.texSubImage2D(e.TEXTURE_2D,0,0,0,i,s,e.RGB_INTEGER,e.UNSIGNED_SHORT,r,0),this.disableBindedTextureFiltering(e),e.bindTexture(e.TEXTURE_2D,null),new vs(e,n,i,s)}},{key:"generateTextureFor32BitIndices",value:function(e,t){if(0==t.length)return{texture:null,textureHeight:0};var i=4096,s=Math.ceil(t.length/3/i);if(0==s)throw"texture height == 0";var r=new Uint32Array(i*s*3);ms.sizeDataTextureIndices+=r.byteLength,ms.numberOfTextures++,r.fill(0),r.set(t,0);var n=e.createTexture();return e.bindTexture(e.TEXTURE_2D,n),e.texStorage2D(e.TEXTURE_2D,1,e.RGB32UI,i,s),e.texSubImage2D(e.TEXTURE_2D,0,0,0,i,s,e.RGB_INTEGER,e.UNSIGNED_INT,r,0),this.disableBindedTextureFiltering(e),e.bindTexture(e.TEXTURE_2D,null),new vs(e,n,i,s)}},{key:"generateTextureFor8BitsEdgeIndices",value:function(e,t){if(0==t.length)return{texture:null,textureHeight:0};var i=4096,s=Math.ceil(t.length/2/i);if(0==s)throw"texture height == 0";var r=new Uint8Array(i*s*2);ms.sizeDataTextureEdgeIndices+=r.byteLength,ms.numberOfTextures++,r.fill(0),r.set(t,0);var n=e.createTexture();return e.bindTexture(e.TEXTURE_2D,n),e.texStorage2D(e.TEXTURE_2D,1,e.RG8UI,i,s),e.texSubImage2D(e.TEXTURE_2D,0,0,0,i,s,e.RG_INTEGER,e.UNSIGNED_BYTE,r,0),this.disableBindedTextureFiltering(e),e.bindTexture(e.TEXTURE_2D,null),new vs(e,n,i,s)}},{key:"generateTextureFor16BitsEdgeIndices",value:function(e,t){if(0==t.length)return{texture:null,textureHeight:0};var i=4096,s=Math.ceil(t.length/2/i);if(0==s)throw"texture height == 0";var r=new Uint16Array(i*s*2);ms.sizeDataTextureEdgeIndices+=r.byteLength,ms.numberOfTextures++,r.fill(0),r.set(t,0);var n=e.createTexture();return e.bindTexture(e.TEXTURE_2D,n),e.texStorage2D(e.TEXTURE_2D,1,e.RG16UI,i,s),e.texSubImage2D(e.TEXTURE_2D,0,0,0,i,s,e.RG_INTEGER,e.UNSIGNED_SHORT,r,0),this.disableBindedTextureFiltering(e),e.bindTexture(e.TEXTURE_2D,null),new vs(e,n,i,s)}},{key:"generateTextureFor32BitsEdgeIndices",value:function(e,t){if(0==t.length)return{texture:null,textureHeight:0};var i=4096,s=Math.ceil(t.length/2/i);if(0==s)throw"texture height == 0";var r=new Uint32Array(i*s*2);ms.sizeDataTextureEdgeIndices+=r.byteLength,ms.numberOfTextures++,r.fill(0),r.set(t,0);var n=e.createTexture();return e.bindTexture(e.TEXTURE_2D,n),e.texStorage2D(e.TEXTURE_2D,1,e.RG32UI,i,s),e.texSubImage2D(e.TEXTURE_2D,0,0,0,i,s,e.RG_INTEGER,e.UNSIGNED_INT,r,0),this.disableBindedTextureFiltering(e),e.bindTexture(e.TEXTURE_2D,null),new vs(e,n,i,s)}},{key:"generateTextureForPositions",value:function(e,t){var i=t.length/3,s=4096,r=Math.ceil(i/s);if(0==r)throw"texture height == 0";var n=new Uint16Array(s*r*3);ms.sizeDataTexturePositions+=n.byteLength,ms.numberOfTextures++,n.fill(0),n.set(t,0);var o=e.createTexture();return e.bindTexture(e.TEXTURE_2D,o),e.texStorage2D(e.TEXTURE_2D,1,e.RGB16UI,s,r),e.texSubImage2D(e.TEXTURE_2D,0,0,0,s,r,e.RGB_INTEGER,e.UNSIGNED_SHORT,n,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 vs(e,o,s,r)}},{key:"generateTextureForPackedPortionIds",value:function(e,t){if(0==t.length)return{texture:null,textureHeight:0};var i=t.length,s=4096,r=Math.ceil(i/s);if(0==r)throw"texture height == 0";var n=new Uint16Array(s*r);n.set(t,0),ms.sizeDataTexturePortionIds+=n.byteLength,ms.numberOfTextures++;var o=e.createTexture();return e.bindTexture(e.TEXTURE_2D,o),e.texStorage2D(e.TEXTURE_2D,1,e.R16UI,s,r),e.texSubImage2D(e.TEXTURE_2D,0,0,0,s,r,e.RED_INTEGER,e.UNSIGNED_SHORT,n,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 vs(e,o,s,r)}}]),e}(),ys=q.identityMat4();q.mat4(),q.mat4();var bs=q.vec4([0,0,0,1]),xs=q.vec4([0,0,0,1]),Ps=q.vec4([0,0,0,1]),Ts=q.OBB3(),ws=new Uint8Array(4),Ms=new Float32Array(3),Is=q.vec3(),Cs=q.vec3(),Ds=q.vec3(),As=q.vec3(),ks=q.vec3(),Es=q.vec3(),Fs=q.vec3(),Rs=0,Ss=function(){function e(t,i){var s,r,n;w(this,e),this._layerNumber=Rs++,ms.numberOfLayers++,this.sortId="TrianglesDataTextureLayer-".concat(this._layerNumber),this.layerIndex=i.layerIndex,this._dataTextureRenderers=(s=t.scene,r=s.id,(n=is[r])||(n=new ts(s),is[r]=n,n._compile(),s.on("compile",(function(){n._compile()})),s.on("destroyed",(function(){delete is[r],n._destroy()}))),n),this.model=t,this._buffer=new ss,this._dataTextureState=new gs,this.dataTextureGenerator=new _s,this._state=new ti({metallicRoughnessBuf:null,positionsDecodeMatrix:q.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._modelAABB=q.collapseAABB3(),this._portions=[],this._finalized=!1,this._subPortionIdMapping=[],this._instancedGeometrySubPortionData={},this.aabb=q.collapseAABB3(),this.numUpdatesInFrame=0}return I(e,[{key:"canCreatePortion",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null;if(this._finalized)throw"Already finalized";var i=this._state,s=e.preparedBuckets.length;this._numPortions+s>65536&&ms.cannotCreatePortion.because10BitsObjectId++;var r=this._numPortions+s<=65536,n=null!==t&&t+"#0"in this._instancedGeometrySubPortionData;if(!n){var o=Math.max(i.numIndices8Bits,i.numIndices16Bits,i.numIndices32Bits),a=0,u=e.indices.length/3;e.preparedBuckets.forEach((function(e){a+=e.positions.length/3})),(i.numVertices+a>16777216||o+u>16777216)&&ms.cannotCreatePortion.becauseTextureSize++,r&&(r=i.numVertices+a<=16777216&&o+u<=16777216)}return r}},{key:"createPortion",value:function(e){var t=this,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null;if(this._finalized)throw"Already finalized";var s=null!==i,r=this._subPortionIdMapping.length,n=[];this._subPortionIdMapping.push(n);var o=s?i.aabb:e.aabb;return e.preparedBuckets.forEach((function(r,a){var u;if(s){var h=e.id+"#"+a;h in t._instancedGeometrySubPortionData||(t._instancedGeometrySubPortionData[h]=t.createSubPortionGeometry(r)),u=t._instancedGeometrySubPortionData[h]}else u=t.createSubPortionGeometry(r);var l=q.collapseAABB3(),c=t.createSubPortionObject(s?i:e,u,r.positions,e.positionsDecodeMatrix,s?i.origin:e.origin,l,s,e.solid);q.expandAABB3(o,l),n.push(c)})),this.model.numPortions++,r}},{key:"createSubPortionGeometry",value:function(e){var t=this._state;if(e.indices){var i=8*Math.ceil(e.indices.length/3/8)*3;ms.overheadSizeAlignementIndices+=2*(i-e.indices.length);var s=new Uint32Array(i);s.fill(0),s.set(e.indices),e.indices=s}if(e.edgeIndices){var r=8*Math.ceil(e.edgeIndices.length/2/8)*2;ms.overheadSizeAlignementEdgeIndices+=2*(r-e.edgeIndices.length);var n=new Uint32Array(r);n.fill(0),n.set(e.edgeIndices),e.edgeIndices=n}for(var o,a=e.positions,u=e.indices,h=e.edgeIndices,l=this._buffer,c=l.positions.length/3,p=a.length/3,d=0,f=a.length;d<f;d++)l.positions.push(a[d]);var m,v=0;if(u){var g;v=u.length/3,o=(g=p<=256?l.indices8Bits:p<=65536?l.indices16Bits:l.indices32Bits).length/3;for(var _=0,y=u.length;_<y;_++)g.push(u[_])}var b=0;if(h){var x;b=h.length/2,m=(x=p<=256?l.edgeIndices8Bits:p<=65536?l.edgeIndices16Bits:l.edgeIndices32Bits).length/2;for(var P=0,T=h.length;P<T;P++)x.push(h[P])}return t.numVertices+=p,ms.numberOfGeometries++,{vertexBase:c,numVertices:p,numTriangles:v,numEdges:b,indicesBase:o,edgeIndicesBase:m}}},{key:"createSubPortionObject",value:function(e,t,i,s,r,n,o,a){var u=e.color;e.metallic,e.roughness;var h=e.colors,l=e.opacity,c=e.meshMatrix,p=e.worldMatrix,d=e.pickColor;this.model.scene;var f,m,v=this._buffer,g=this._state;if(v.perObjectPositionsDecodeMatrices.push(s),o?v.perObjectInstancePositioningMatrices.push(c):v.perObjectInstancePositioningMatrices.push(ys),o){var _=q.collapseAABB3();q.expandAABB3Points3(_,i),ui.decompressAABB(_,s);for(var y=q.AABB3ToOBB3(_),b=0,x=y.length;b<x;b+=4)bs[0]=y[b+0],bs[1]=y[b+1],bs[2]=y[b+2],q.transformPoint4(c,bs,xs),p?(q.transformPoint4(p,xs,Ps),q.expandAABB3Point3(n,Ps)):q.expandAABB3Point3(n,xs)}else if(s){var P=ui.getPositionsBounds(i),T=ui.decompressPosition(P.min,s,[]),w=ui.decompressPosition(P.max,s,[]);n[0]=T[0],n[1]=T[1],n[2]=T[2],n[3]=w[0],n[4]=w[1],n[5]=w[2],p&&(q.AABB3ToOBB3(n,Ts),q.transformOBB3(p,Ts),q.OBB3ToAABB3(Ts,n))}else if(c)for(var M=0,I=i.length;M<I;M+=3)bs[0]=i[M+0],bs[1]=i[M+1],bs[2]=i[M+2],q.transformPoint4(c,bs,xs),i[M+0]=xs[0],i[M+1]=xs[1],i[M+2]=xs[2],q.expandAABB3Point3(this._modelAABB,xs),p?(q.transformPoint4(p,xs,Ps),q.expandAABB3Point3(n,Ps)):q.expandAABB3Point3(n,xs);else for(var C=0,D=i.length;C<D;C+=3)bs[0]=i[C+0],bs[1]=i[C+1],bs[2]=i[C+2],q.expandAABB3Point3(this._modelAABB,bs),p?(q.transformPoint4(p,bs,xs),q.expandAABB3Point3(n,xs)):q.expandAABB3Point3(n,bs);r&&(this._state.origin=r,n[0]+=r[0],n[1]+=r[1],n[2]+=r[2],n[3]+=r[0],n[4]+=r[1],n[5]+=r[2]),q.expandAABB3(this.aabb,n),v.perObjectSolid.push(a),h?v.perObjectColors.push([255*h[0],255*h[1],255*h[2],255]):u&&v.perObjectColors.push([u[0],u[1],u[2],l]),v.perObjectPickColors.push(d),v.perObjectVertexBases.push(t.vertexBase),f=t.numVertices<=256?g.numIndices8Bits:t.numVertices<=65536?g.numIndices16Bits:g.numIndices32Bits,v.perObjectIndexBaseOffsets.push(f/3-t.indicesBase),m=t.numVertices<=256?g.numEdgeIndices8Bits:t.numVertices<=65536?g.numEdgeIndices16Bits:g.numEdgeIndices32Bits,v.perObjectEdgeIndexBaseOffsets.push(m/2-t.edgeIndicesBase);var A=this._portions.length;if(t.numTriangles>0){var k,E=3*t.numTriangles;t.numVertices<=256?(k=v.perTriangleNumberPortionId8Bits,g.numIndices8Bits+=E,ms.totalPolygons8Bits+=t.numTriangles):t.numVertices<=65536?(k=v.perTriangleNumberPortionId16Bits,g.numIndices16Bits+=E,ms.totalPolygons16Bits+=t.numTriangles):(k=v.perTriangleNumberPortionId32Bits,g.numIndices32Bits+=E,ms.totalPolygons32Bits+=t.numTriangles),ms.totalPolygons+=t.numTriangles;for(var F=0;F<t.numTriangles;F+=8)k.push(A)}if(t.numEdges>0){var R,S=2*t.numEdges;t.numVertices<=256?(R=v.perEdgeNumberPortionId8Bits,g.numEdgeIndices8Bits+=S,ms.totalEdges8Bits+=t.numEdges):t.numVertices<=65536?(R=v.perEdgeNumberPortionId16Bits,g.numEdgeIndices16Bits+=S,ms.totalEdges16Bits+=t.numEdges):(R=v.perEdgeNumberPortionId32Bits,g.numEdgeIndices32Bits+=S,ms.totalEdges32Bits+=t.numEdges),ms.totalEdges+=t.numEdges;for(var O=0;O<t.numEdges;O+=8)R.push(A)}return v.perObjectOffsets.push([0,0,0]),this._portions.push({numVerts:t.numTriangles}),this._numPortions++,ms.numberOfPortions++,A}},{key:"finalize",value:function(){if(this._finalized)this.model.error("Already finalized");else{var e=this._state,t=this._dataTextureState,i=this.model.scene.canvas.gl,s=this._buffer;e.gl=i,t.texturePerObjectIdColorsAndFlags=this.dataTextureGenerator.generateTextureForColorsAndFlags(i,s.perObjectColors,s.perObjectPickColors,s.perObjectVertexBases,s.perObjectIndexBaseOffsets,s.perObjectEdgeIndexBaseOffsets,s.perObjectSolid),t.texturePerObjectIdOffsets=this.dataTextureGenerator.generateTextureForObjectOffsets(i,this._numPortions),t.texturePerObjectIdPositionsDecodeMatrix=this.dataTextureGenerator.generateTextureForPositionsDecodeMatrices(i,s.perObjectPositionsDecodeMatrices,s.perObjectInstancePositioningMatrices),t.texturePerVertexIdCoordinates=this.dataTextureGenerator.generateTextureForPositions(i,s.positions),t.texturePerPolygonIdPortionIds8Bits=this.dataTextureGenerator.generateTextureForPackedPortionIds(i,s.perTriangleNumberPortionId8Bits),t.texturePerPolygonIdPortionIds16Bits=this.dataTextureGenerator.generateTextureForPackedPortionIds(i,s.perTriangleNumberPortionId16Bits),t.texturePerPolygonIdPortionIds32Bits=this.dataTextureGenerator.generateTextureForPackedPortionIds(i,s.perTriangleNumberPortionId32Bits),s.perEdgeNumberPortionId8Bits.length>0&&(t.texturePerEdgeIdPortionIds8Bits=this.dataTextureGenerator.generateTextureForPackedPortionIds(i,s.perEdgeNumberPortionId8Bits)),s.perEdgeNumberPortionId16Bits.length>0&&(t.texturePerEdgeIdPortionIds16Bits=this.dataTextureGenerator.generateTextureForPackedPortionIds(i,s.perEdgeNumberPortionId16Bits)),s.perEdgeNumberPortionId32Bits.length>0&&(t.texturePerEdgeIdPortionIds32Bits=this.dataTextureGenerator.generateTextureForPackedPortionIds(i,s.perEdgeNumberPortionId32Bits)),s.indices8Bits.length>0&&(t.texturePerPolygonIdIndices8Bits=this.dataTextureGenerator.generateTextureFor8BitIndices(i,s.indices8Bits)),s.indices16Bits.length>0&&(t.texturePerPolygonIdIndices16Bits=this.dataTextureGenerator.generateTextureFor16BitIndices(i,s.indices16Bits)),s.indices32Bits.length>0&&(t.texturePerPolygonIdIndices32Bits=this.dataTextureGenerator.generateTextureFor32BitIndices(i,s.indices32Bits)),s.edgeIndices8Bits.length>0&&(t.texturePerPolygonIdEdgeIndices8Bits=this.dataTextureGenerator.generateTextureFor8BitsEdgeIndices(i,s.edgeIndices8Bits)),s.edgeIndices16Bits.length>0&&(t.texturePerPolygonIdEdgeIndices16Bits=this.dataTextureGenerator.generateTextureFor16BitsEdgeIndices(i,s.edgeIndices16Bits)),s.edgeIndices32Bits.length>0&&(t.texturePerPolygonIdEdgeIndices32Bits=this.dataTextureGenerator.generateTextureFor32BitsEdgeIndices(i,s.edgeIndices32Bits)),this.model._modelMatricesTexture||(this.model._modelMatricesTexture=this.dataTextureGenerator.generatePeformanceModelDataTexture(i,this.model)),t.textureModelMatrices=this.model._modelMatricesTexture,this.model.cameraTexture||(this.model.cameraTexture=this.dataTextureGenerator.generateCameraDataTexture(this.model.scene.canvas.gl,this.model.scene.camera,this.model.scene,this._state.origin.slice())),t.textureCameraMatrices=this.model.cameraTexture,this.model.pickCameraTexture||(this.model.pickCameraTexture=this.dataTextureGenerator.generateCameraDataTexture(this.model.scene.canvas.gl,this.model.scene.camera,this.model.scene,this._state.origin.slice(),!1)),t.texturePickCameraMatrices=this.model.pickCameraTexture,t.finalize(),this._buffer=null,this._instancedGeometrySubPortionData={},this._finalized=!0}}},{key:"attachToRenderingEvent",value:function(){var e=this;this.model.scene.on("rendering",(function(){e._deferredSetFlagsDirty&&e.commitDeferredFlags(),e.numUpdatesInFrame=0}))}},{key:"isEmpty",value:function(){return 0==this._numPortions}},{key:"initFlags",value:function(e,t,i){t&kt&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&Bt&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&Ot&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&Lt&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&Rt&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&Nt&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&Ft&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&Et&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),i&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++);this._setFlags(e,t,i,true),this._setFlags2(e,t,true)}},{key:"flushInitFlags",value:function(){this._setDeferredFlags(),this._setDeferredFlags2()}},{key:"setVisible",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&kt?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,i)}},{key:"setHighlighted",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&Bt?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,i)}},{key:"setXRayed",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&Ot?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,i)}},{key:"setSelected",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&Lt?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,i)}},{key:"setEdges",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&Nt?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,i)}},{key:"setClippable",value:function(e,t){if(!this._finalized)throw"Not finalized";t&Rt?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags2(e,t)}},{key:"beginDeferredFlags",value:function(){this._deferredSetFlagsActive=!0}},{key:"commitDeferredFlags",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,i){if(!this._finalized)throw"Not finalized";t&Et?(this._numCulledLayerPortions+=this._subPortionIdMapping[e].length,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions-=this._subPortionIdMapping[e].length,this.model.numCulledLayerPortions--),this._setFlags(e,t,i)}},{key:"setCollidable",value:function(e,t){if(!this._finalized)throw"Not finalized"}},{key:"setPickable",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&Ft?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,i)}},{key:"setColor",value:function(e,t){for(var i=this._subPortionIdMapping[e],s=0,r=i.length;s<r;s++)this._subPortionSetColor(i[s],t)}},{key:"_subPortionSetColor",value:function(e,t){if(!this._finalized)throw"Not finalized";var i=this._dataTextureState,s=this.model.scene.canvas.gl;ws[0]=t[0],ws[1]=t[1],ws[2]=t[2],ws[3]=t[3],i.texturePerObjectIdColorsAndFlags._textureData.set(ws,32*e),this._deferredSetFlagsActive?this._deferredSetFlagsDirty=!0:(++this.numUpdatesInFrame>=10&&this.beginDeferredFlags(),s.bindTexture(s.TEXTURE_2D,i.texturePerObjectIdColorsAndFlags._texture),s.texSubImage2D(s.TEXTURE_2D,0,e%512*8,Math.floor(e/512),1,1,s.RGBA_INTEGER,s.UNSIGNED_BYTE,ws))}},{key:"setTransparent",value:function(e,t,i){i?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,i)}},{key:"_setFlags",value:function(e,t,i){for(var s=this._subPortionIdMapping[e],r=0,n=s.length;r<n;r++)this._subPortionSetFlags(s[r],t,i)}},{key:"_subPortionSetFlags",value:function(e,t,i){if(!this._finalized)throw"Not finalized";var s,r,n=!!(t&kt),o=!!(t&Ot),a=!!(t&Bt),u=!!(t&Lt),h=!!(t&Nt),l=!!(t&Ft),c=!!(t&Et);s=!n||c||o?Vt:i?zt:Ut,r=!n||c?Vt:u?Xt:a?Wt:o?Yt:Vt;var p=0;p=!n||c?Vt:u?Qt:a?Zt:o?qt:h?i?Jt:Kt:Vt;var d=n&&!c&&l?$t:Vt,f=this._dataTextureState,m=this.model.scene.canvas.gl;ws[0]=s,ws[1]=r,ws[2]=p,ws[3]=d,f.texturePerObjectIdColorsAndFlags._textureData.set(ws,32*e+8),this._deferredSetFlagsActive?this._deferredSetFlagsDirty=!0:(++this.numUpdatesInFrame>=10&&this.beginDeferredFlags(),m.bindTexture(m.TEXTURE_2D,f.texturePerObjectIdColorsAndFlags._texture),m.texSubImage2D(m.TEXTURE_2D,0,e%512*8+2,Math.floor(e/512),1,1,m.RGBA_INTEGER,m.UNSIGNED_BYTE,ws))}},{key:"_setDeferredFlags",value:function(){}},{key:"_setFlags2",value:function(e,t){for(var i=this._subPortionIdMapping[e],s=0,r=i.length;s<r;s++)this._subPortionSetFlags2(i[s],t)}},{key:"_subPortionSetFlags2",value:function(e,t){if(!this._finalized)throw"Not finalized";var i=t&Rt?255:0,s=this._dataTextureState,r=this.model.scene.canvas.gl;ws[0]=i,ws[1]=0,ws[2]=1,ws[3]=2,s.texturePerObjectIdColorsAndFlags._textureData.set(ws,32*e+12),this._deferredSetFlagsActive?this._deferredSetFlagsDirty=!0:(++this.numUpdatesInFrame>=10&&this.beginDeferredFlags(),r.bindTexture(r.TEXTURE_2D,s.texturePerObjectIdColorsAndFlags._texture),r.texSubImage2D(r.TEXTURE_2D,0,e%512*8+3,Math.floor(e/512),1,1,r.RGBA_INTEGER,r.UNSIGNED_BYTE,ws))}},{key:"_setDeferredFlags2",value:function(){}},{key:"setOffset",value:function(e,t){for(var i=this._subPortionIdMapping[e],s=0,r=i.length;s<r;s++)this._subPortionSetOffset(i[s],t)}},{key:"_subPortionSetOffset",value:function(e,t){if(!this._finalized)throw"Not finalized";var i=this._dataTextureState,s=this.model.scene.canvas.gl;Ms[0]=t[0],Ms[1]=t[1],Ms[2]=t[2],i.texturePerObjectIdOffsets._textureData.set(Ms,3*e),this._deferredSetFlagsActive?this._deferredSetFlagsDirty=!0:(++this.numUpdatesInFrame>=10&&this.beginDeferredFlags(),s.bindTexture(s.TEXTURE_2D,i.texturePerObjectIdOffsets._texture),s.texSubImage2D(s.TEXTURE_2D,0,0,e,1,1,s.RGB,s.FLOAT,Ms))}},{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,Ut):this._dataTextureRenderers.colorRendererWithSAO&&this._dataTextureRenderers.colorRendererWithSAO.drawLayer(t,this,Ut):t.pbrEnabled&&this.model.pbrEnabled?this._dataTextureRenderers.colorQualityRenderer&&this._dataTextureRenderers.colorQualityRenderer.drawLayer(t,this,Ut):this._dataTextureRenderers.colorRenderer&&this._dataTextureRenderers.colorRenderer.drawLayer(t,this,Ut))}},{key:"_updateBackfaceCull",value:function(e,t){var i=this.model.backfaces||e.sectioned;if(t.backfaces!==i){var s=t.gl;i?s.disable(s.CULL_FACE):s.enable(s.CULL_FACE),t.backfaces=i}}},{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,zt):this._dataTextureRenderers.colorRenderer&&this._dataTextureRenderers.colorRenderer.drawLayer(t,this,zt))}},{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,Ut))}},{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,Ut))}},{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,Yt))}},{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,Wt))}},{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,Xt))}},{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,Kt)}},{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,Jt)}},{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,Zt)}},{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,Qt)}},{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,qt)}},{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,Ut))}},{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,Ut))}},{key:"drawPickMesh",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._dataTextureRenderers.pickMeshRenderer&&this._dataTextureRenderers.pickMeshRenderer.drawLayer(t,this,$t))}},{key:"drawPickDepths",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._dataTextureRenderers.pickDepthRenderer&&this._dataTextureRenderers.pickDepthRenderer.drawLayer(t,this,$t))}},{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,$t))}},{key:"precisionRayPickSurface",value:function(e,t,i,s,r){if(!this.model.scene.pickSurfacePrecisionEnabled)return!1;var n=this._state,o=this._portions[e];if(!o)return this.model.error("portion not found: "+e),!1;var a=o.quantizedPositions,u=o.indices,h=n.origin,l=o.offset,c=Is,p=Cs;c.set(h?q.subVec3(t,h,Ds):t),p.set(i),l&&q.subVec3(c,l),q.transformRay(this.model.worldNormalMatrix,c,p,c,p);for(var d=As,f=ks,m=Es,v=!1,g=0,_=Fs,y=0,b=u.length;y<b;y+=3){var x=3*u[y],P=3*u[y+1],T=3*u[y+2];if(d[0]=a[x],d[1]=a[x+1],d[2]=a[x+2],f[0]=a[P],f[1]=a[P+1],f[2]=a[P+2],m[0]=a[T],m[1]=a[T+1],m[2]=a[T+2],q.decompressPosition(d,n.positionsDecodeMatrix),q.decompressPosition(f,n.positionsDecodeMatrix),q.decompressPosition(m,n.positionsDecodeMatrix),q.rayTriangleIntersect(c,p,d,f,m,_)){q.transformPoint3(this.model.worldMatrix,_,_),l&&q.addVec3(_,l),h&&q.addVec3(_,h);var w=Math.abs(q.lenVec3(q.subVec3(_,t,[])));(!v||w>g)&&(g=w,s.set(_),r&&q.triangleNormal(d,f,m,r),v=!0)}}return v&&r&&(q.transformVec3(this.model.worldNormalMatrix,r,r),q.normalizeVec3(r)),v}},{key:"destroy",value:function(){var e=this._state;e.metallicRoughnessBuf&&(e.metallicRoughnessBuf.destroy(),e.metallicRoughnessBuf=null),e.destroy()}}]),e}();function Os(e,t,i){var s,r,n,o;if(t){var a=p(as({positions:e.positions,indices:e.indices,edgeIndices:e.edgeIndices}),3);s=a[0],r=a[1],n=a[2]}else s=e.positions,r=e.indices,n=e.edgeIndices;i?o=function(e,t){var i=arguments.length>2&&void 0!==arguments[2]&&arguments[2],s=e.positions||[],r=ls(e.indices||[],t),n=ds(e.edgeIndices||[]);function o(e,t){if(e>t){var i=e;e=t,t=i}function s(i,s){return i!=e?e-i:s!=t?t-s:0}for(var r=0,o=(n.length>>1)-1;r<=o;){var a=o+r>>1,u=s(n[2*a],n[2*a+1]);if(u>0)r=a+1;else{if(!(u<0))return a;o=a-1}}return-r-1}var a=new Int32Array(n.length/2);a.fill(0);var u=s.length/3;if(u>8*(1<<t))return[e];var h=new Int32Array(u);h.fill(-1);var l=[];function c(){h.fill(-1);var e={positions:[],indices:[],edgeIndices:[],maxNumPositions:(1<<t)-t,numPositions:0,bucketNumber:l.length};return l.push(e),e}for(var p=c(),d=0,f=r.length;d<f;d+=3){var m=0,v=r[d],g=r[d+1],_=r[d+2];if(-1==h[v]&&m++,-1==h[g]&&m++,-1==h[_]&&m++,m+p.numPositions>p.maxNumPositions&&(p=c()),p.bucketNumber>8)return[e];-1==h[v]&&(h[v]=p.numPositions++,p.positions.push(s[3*v]),p.positions.push(s[3*v+1]),p.positions.push(s[3*v+2])),-1==h[g]&&(h[g]=p.numPositions++,p.positions.push(s[3*g]),p.positions.push(s[3*g+1]),p.positions.push(s[3*g+2])),-1==h[_]&&(h[_]=p.numPositions++,p.positions.push(s[3*_]),p.positions.push(s[3*_+1]),p.positions.push(s[3*_+2])),p.indices.push(h[v]),p.indices.push(h[g]),p.indices.push(h[_]);var y=void 0;(y=o(v,g))>=0&&0==a[y]&&(a[y]=1,p.edgeIndices.push(h[n[2*y]]),p.edgeIndices.push(h[n[2*y+1]])),(y=o(v,_))>=0&&0==a[y]&&(a[y]=1,p.edgeIndices.push(h[n[2*y]]),p.edgeIndices.push(h[n[2*y+1]])),(y=o(g,_))>=0&&0==a[y]&&(a[y]=1,p.edgeIndices.push(h[n[2*y]]),p.edgeIndices.push(h[n[2*y+1]]))}var b=t/8*2,x=t/8,P=2*s.length+(r.length+n.length)*b,T=0;return s.length,l.forEach((function(e){T+=2*e.positions.length+(e.indices.length+e.edgeIndices.length)*x,e.positions.length})),T>P?[e]:(i&&fs(l,e),l)}({positions:s,indices:r,edgeIndices:n},s.length/3>65536?16:8):o=[{positions:s,indices:r,edgeIndices:n}];return e.preparedBuckets=o,e}var Bs=function(){function e(){w(this,e),this.visibleLayers=[],this.sectionPlanesActivePerLayer=[],this.reset()}return I(e,[{key:"reset",value:function(){this.culled=!1,this.sectioned=!1,this.numLayers=0,this.numVisibleLayers=0,this.colorOpaque=!1,this.colorTransparent=!1,this.edgesOpaque=!1,this.edgesTransparent=!1,this.xrayedSilhouetteOpaque=!1,this.xrayedEdgesOpaque=!1,this.xrayedSilhouetteTransparent=!1,this.xrayedEdgesTransparent=!1,this.highlightedSilhouetteOpaque=!1,this.highlightedEdgesOpaque=!1,this.highlightedSilhouetteTransparent=!1,this.highlightedEdgesTransparent=!1,this.selectedSilhouetteOpaque=!1,this.selectedEdgesOpaque=!1,this.selectedSilhouetteTransparent=!1,this.selectedEdgesTransparent=!1}}]),e}(),Ls=!1,Ns=[];var js=function(){function e(t,i){w(this,e),this.triangleLODLevels=t,this.nodesInLOD={},this.triangleCountInLOD={},this.targetFps=i,this.lodLevelIndex=0,this.consecutiveFramesWithTargetFps=0,this.consecutiveFramesWithoutTargetFps=0}return I(e,[{key:"initializeLodState",value:function(e){if(0!=e._nodeList.length){for(var t=e._nodeList,i={},s={},r=0,n=t.length;r<n;r++){var o,a=t[r],u=void 0;for(u=0,o=this.triangleLODLevels.length;u<o&&!(a.numTriangles>=this.triangleLODLevels[u]);u++);var h=this.triangleLODLevels[u]||0;h in i||(i[h]=[]),i[h].push(a),h in s||(s[h]=0),s[h]+=a.numTriangles}this.nodesInLOD=i,this.triangleCountInLOD=s}}}]),e}(),Gs=function(){function e(t,i,s){w(this,e),this.model=t,this.lodState=new js(i,s),console.time("initializeLodState"),this.lodState.initializeLodState(t),console.timeEnd("initializeLodState"),function(e,t){if(!Ls){Ls=!0;var i=new Array(4),s=0,r=-1,n=Date.now(),o=0;e.on("rendering",(function(){if(-1!=r)for(var e=0,t=Ns.length;e<t;e++)Ns[e].applyLodCulling(r)})),e.on("rendered",(function(){n=Date.now(),window.requestAnimationFrame((function(){s++;var e=Date.now();o=e-n,n=e,i[s%4]=o;var t=0;if(s>4){for(var a=0;a<4;a++)t+=i[a];r=4/t*1e3}}))}));var a=0,u=a;e.camera.on("matrix",(function(){u=a})),e.on("tick",(function(){if(a-u>3)for(var e=0,t=Ns.length;e<t;e++)Ns[e].resetLodCulling();a++}))}Ns.push(t)}(this.model.scene,this)}return I(e,[{key:"_increaseLODLevelIndex",value:function(){var e=this.lodState;if(e.lodLevelIndex==e.triangleLODLevels.length)return!1;for(var t=e.nodesInLOD[e.triangleLODLevels[e.lodLevelIndex]]||[],i=0,s=t.length;i<s;i++)t[i].culledLOD=!0;return e.lodLevelIndex++,!0}},{key:"_decreaseLODLevelIndex",value:function(){var e=this.lodState;if(0==e.lodLevelIndex)return!1;for(var t=e.nodesInLOD[e.triangleLODLevels[e.lodLevelIndex-1]]||[],i=0,s=t.length;i<s;i++)t[i].culledLOD=!1;return e.lodLevelIndex--,!0}},{key:"applyLodCulling",value:function(e){var t=this.lodState;this.model;var i=!1;return e<t.targetFps?++t.consecutiveFramesWithoutTargetFps>0&&(t.consecutiveFramesWithoutTargetFps=0,i=this._increaseLODLevelIndex()):e>t.targetFps+4&&++t.consecutiveFramesWithTargetFps>1&&(t.consecutiveFramesWithTargetFps=0,i=this._decreaseLODLevelIndex()),i&&console.log("LOD level = "+t.lodLevelIndex),i}},{key:"resetLodCulling",value:function(){this.model;var e=!1,t=!1;do{e|=t=this._decreaseLODLevelIndex()}while(t);return e&&console.log("LOD resetted"),e}}]),e}(),Hs={},Vs={};!function(e){if("object"===T(Vs)&&void 0!==Hs)Hs.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,i,s){function r(o,a){if(!i[o]){if(!t[o]){var u="function"==typeof require&&require;if(!a&&u)return u(o,!0);if(n)return n(o,!0);var h=new Error("Cannot find module '"+o+"'");throw h.code="MODULE_NOT_FOUND",h}var l=i[o]={exports:{}};t[o][0].call(l.exports,(function(e){return r(t[o][1][e]||e)}),l,l.exports,e,t,i,s)}return i[o].exports}for(var n="function"==typeof require&&require,o=0;o<s.length;o++)r(s[o]);return r}({1:[function(e,t,i){Object.defineProperty(i,"__esModule",{value:!0});var s=e("quickselect"),r=[],n=function(e){return r.push(e)},o=function e(t){t&&(n(t),l(t)||t.children.forEach(e))},a=function(e){var t=r.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},u=[],h=function(e,t){var i=u.pop();return i?(i.dist=e,i.node=t):i={dist:e,node:t},i},l=function(e){return e.leaf},c=function(e,t){return e.leaf},p=function(e,t,i){if(!i)return t.indexOf(e);for(var s=0;s<t.length;s++)if(i(e,t[s]))return s;return-1},d=function(e){f(e,0,e.children.length,e)},f=function(e,t,i,s){var r=s;r?(r.minX=1/0,r.minY=1/0,r.minZ=1/0,r.maxX=-1/0,r.maxY=-1/0,r.maxZ=-1/0):r=a([]);for(var n=t,o=void 0;n<i;n++)o=e.children[n],m(r,o);return r},m=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},v=function(e){return(e.maxX-e.minX)*(e.maxY-e.minY)*(e.maxZ-e.minZ)},g=function(e){return e.maxX-e.minX+(e.maxY-e.minY)+(e.maxZ-e.minZ)},_=function(e,t){var i=Math.min(e.minX,t.minX),s=Math.min(e.minY,t.minY),r=Math.min(e.minZ,t.minZ);return(Math.max(e.maxX,t.maxX)-i)*(Math.max(e.maxY,t.maxY)-s)*(Math.max(e.maxZ,t.maxZ)-r)},y=function(e,t){var i=Math.max(e.minX,t.minX),s=Math.max(e.minY,t.minY),r=Math.max(e.minZ,t.minZ),n=Math.min(e.maxX,t.maxX),o=Math.min(e.maxY,t.maxY),a=Math.min(e.maxZ,t.maxZ);return Math.max(0,n-i)*Math.max(0,o-s)*Math.max(0,a-r)},b=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};i.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},i.boxRayIntersects=function(e,t,i,s,r,n,o){var a=(e.minX-t)*r,u=(e.maxX-t)*r,h=(e.minY-i)*n,l=(e.maxY-i)*n,c=(e.minZ-s)*o,p=(e.maxZ-s)*o,d=Math.min(c,p),f=Math.max(c,p),m=Math.min(h,l),v=Math.max(h,l),g=Math.min(a,u),_=Math.max(a,u),y=Math.max(0,g,m,d);return Math.min(_,v,f)>=y?y:1/0};var x=function(e,t,i,r,n){for(var o,a=[t,i];a.length;)(i=a.pop())-(t=a.pop())<=r||(o=t+Math.ceil((i-t)/r/2)*r,s(e,o,t,i,n),a.push(t,o,o,i))},P=function(e,t){return e.minX-t.minX},T=function(e,t){return e.minY-t.minY},w=function(e,t){return e.minZ-t.minZ},M=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 i=this.data,s=[];if(!e(i,c(i)))return s;for(var r=[];i;){for(var n=0,o=i.children.length;n<o;n++){var a=i.children[n];e(a,c(i))&&(c(i)?s.push(a):t(a)?this._all(a,s):r.push(a))}i=r.pop()}return s},e.prototype.analyzeTriangles=function(e){void 0===e&&(e=this.data);var t=0;if(l(e))for(var i=0,s=e.children.length;i<s;i++)t+=e.children[i].numTriangles;else for(i=0,s=e.children.length;i<s;i++)t+=this.analyzeTriangles(e.children[i]);return e.totalTriangles=t},e.prototype.groupNodesByNumTrianglesThreshold=function(e,t){void 0===t&&(this.analyzeTriangles(),t=this.data);for(var i=[],s=0,r=t.children.length;s<r;s++){var n=t.children[s];i.push({item:n,triangles:n.totalTriangles||n.numTriangles})}i.sort((function(e,t){return-(e.item.triangles-t.item.triangles)}));var o=[],a=[],u=0;for(s=0,r=i.length;s<r;s++){var h=i[s];if(u+h.triangles<e)a.push(h),u+=h.triangles;else if(a.length&&(o.push(a),a=[],u=0),u+h.triangles<e)s--;else if(c(t,h.item))o.push([h]);else{for(var l=this.groupNodesByNumTrianglesThreshold(e,h.item),p=[],d=0,f=0,m=l.length;f<m-1;f++)o.push(l[s]);if(l.length>1){for(f=0,m=(l=l[l.length-1]).length;f<m;f++)(d+=l[f].triangles)<e?p.push(l[f]):(0==d&&p.push(l[f]),o.push(p),d=0,p=[]);p.forEach((function(e){a.push(e),u+=e.triangles}))}}}return a.length&&o.push(a),o},e.prototype.search=function(e){var t=this.data,s=[];if(!i.intersects(e,t))return s;for(var r=[];t;){for(var n=0,o=t.children.length;n<o;n++){var a=t.children[n];i.intersects(e,a)&&(c(t)?s.push(a):b(e,a)?this._all(a,s):r.push(a))}t=r.pop()}return s},e.prototype.collides=function(e){var t=this.data;if(!i.intersects(e,t))return!1;for(var s=[];t;){for(var r=0,n=t.children.length;r<n;r++){var o=t.children[r];if(i.intersects(e,o)){if(c(t)||b(e,o))return!0;s.push(o)}}t=s.pop()}return!1},e.prototype.raycastInv=function(e,t,s,r,n,o,a){void 0===a&&(a=1/0);var l=this.data;if(r===1/0&&n===1/0&&o===1/0)return h(1/0,void 0);if(i.boxRayIntersects(l,e,t,s,r,n,o)===1/0)return h(1/0,void 0);for(var p,d=[h(0,l)],f=function(e,t){var i=d[e];d[e]=d[t],d[t]=i},m=function(){var e=d[0],t=d.length-1;d[0]=d[t],d.length=t;for(var i=0;;){var s=i<<1|1;if(s>=t)break;var r=s+1;if(r<t&&d[r].dist<d[s].dist&&(s=r),d[i].dist<d[s].dist)break;f(i,s),i=s}return function(e){u.push(e)}(e),e.node},v=function(e,t){var i=d.length;for(d.push(h(e,t));i>0;){var s=i-1>>1;if(d[s].dist<=d[i].dist)break;f(i,s),i=s}},g=a;d.length&&d[0].dist<g;)for(var _=0,y=(l=m()).children.length;_<y;_++){var b=l.children[_],x=i.boxRayIntersects(b,e,t,s,r,n,o);if(c(l)){if(x<g){if(0===x)return h(x,b);g=x,p=b}}else v(x,b)}return h(g<a?g:1/0,p)},e.prototype.raycast=function(e,t,i,s,r,n,o){return void 0===o&&(o=1/0),this.raycastInv(e,t,i,1/s,1/r,1/n,o)},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,i=e.length;t<i;t++)this.insert(e[t]);return this}var s=this.build(e.slice(),0,e.length-1,0);if(this.data.children.length)if(this.data.height===s.height)this.splitRoot(this.data,s);else{if(this.data.height<s.height){var r=this.data;this.data=s,s=r}this._insert(s,this.data.height-s.height-1,!0)}else this.data=s;return this},e.prototype.insert=function(e){return e&&this._insert(e,this.data.height-1),this},e.prototype.clear=function(){return this.data&&o(this.data),this.data=a([]),this},e.prototype.remove=function(e,t){if(!e)return this;for(var i,s,r=this.data,n=0,o=!1,a=[],u=[];r||a.length;){if(r||(r=a.pop(),n=u.pop(),s=a[a.length-1],o=!0),l(r)&&-1!==(i=p(e,r.children,t)))return r.children.splice(i,1),a.push(r),this.condense(a),this;o||l(r)||!b(r,e)?s?(n++,r=s.children[n],o=!1):r=void 0:(a.push(r),u.push(n),n=0,s=r,r=r.children[0])}return this},e.prototype.toJSON=function(){return this.data},e.prototype.fromJSON=function(e){return o(this.data),this.data=e,this},e.prototype.build=function(e,t,i,s){var r,n=i-t+1,o=this.maxEntries;if(n<=o)return r=a(e.slice(t,i+1)),d(r),r;s||(s=Math.ceil(Math.log(n)/Math.log(o)),o=Math.ceil(n/Math.pow(o,s-1))),(r=a([])).leaf=!1,r.height=s;var u=Math.ceil(n/o),h=u*Math.ceil(Math.pow(o,2/3)),l=u*Math.ceil(Math.pow(o,1/3));x(e,t,i,l,P);for(var c=t;c<=i;c+=l){var p=Math.min(c+l-1,i);x(e,c,p,h,T);for(var f=c;f<=p;f+=h){var m=Math.min(f+h-1,p);x(e,f,m,u,w);for(var v=f;v<=m;v+=u){var g=Math.min(v+u-1,m);r.children.push(this.build(e,v,g,s-1))}}}return d(r),r},e.prototype._all=function(e,t){for(var i=[];e;)l(e)?t.push.apply(t,e.children):i.push.apply(i,e.children),e=i.pop();return t},e.prototype.chooseSubtree=function(e,t,i,s){for(var r,n,o;s.push(t),!l(t)&&s.length-1!==i;){r=n=1/0;for(var a=0,u=t.children.length;a<u;a++){var h=t.children[a],c=v(h),p=_(e,h)-c;p<n?(n=p,r=c<r?c:r,o=h):p===n&&c<r&&(r=c,o=h)}t=o||t.children[0]}return t},e.prototype.split=function(e,t){var i=e[t],s=i.children.length,r=this.minEntries;this.chooseSplitAxis(i,r,s);var n=this.chooseSplitIndex(i,r,s),o=a(i.children.splice(n,i.children.length-n));o.height=i.height,o.leaf=i.leaf,d(i),d(o),t?e[t-1].children.push(o):this.splitRoot(i,o)},e.prototype.splitRoot=function(e,t){this.data=a([e,t]),this.data.height=e.height+1,this.data.leaf=!1,d(this.data)},e.prototype.chooseSplitIndex=function(e,t,i){for(var s,r=1/0,n=1/0,o=t;o<=i-t;o++){var a=f(e,0,o),u=f(e,o,i),h=y(a,u),l=v(a)+v(u);h<r?(r=h,s=o,n=l<n?l:n):h===r&&l<n&&(n=l,s=o)}return s},e.prototype.chooseSplitAxis=function(e,t,i){var s=this.allDistMargin(e,t,i,P),r=this.allDistMargin(e,t,i,T),n=this.allDistMargin(e,t,i,w);s<r&&s<n?e.children.sort(P):r<s&&r<n&&e.children.sort(T)},e.prototype.allDistMargin=function(e,t,i,s){e.children.sort(s);for(var r=f(e,0,t),n=f(e,i-t,i),o=g(r)+g(n),a=t;a<i-t;a++){var u=e.children[a];m(r,u),o+=g(r)}for(a=i-t-1;a>=t;a--){u=e.children[a];m(n,u),o+=g(n)}return o},e.prototype.adjustParentBBoxes=function(e,t,i){for(var s=i;s>=0;s--)m(t[s],e)},e.prototype.condense=function(e){for(var t=e.length-1,i=void 0;t>=0;t--)0===e[t].children.length?t>0?((i=e[t-1].children).splice(i.indexOf(e[t]),1),n(e[t])):this.clear():d(e[t])},e.prototype._insert=function(e,t,i){var s=[],r=this.chooseSubtree(e,this.data,t,s);for(r.children.push(e),m(r,e);t>=0&&s[t].children.length>this.maxEntries;)this.split(s,t),t--;this.adjustParentBBoxes(e,s,t)},e.pool=[],e}();i.RBush3D=M},{quickselect:2}],2:[function(e,t,i){!function(e,s){"object"===T(i)&&void 0!==t?t.exports=s():e.quickselect=s()}(this,(function(){function e(i,s,r,n,o){for(;n>r;){if(n-r>600){var a=n-r+1,u=s-r+1,h=Math.log(a),l=.5*Math.exp(2*h/3),c=.5*Math.sqrt(h*l*(a-l)/a)*(u-a/2<0?-1:1);e(i,s,Math.max(r,Math.floor(s-u*l/a+c)),Math.min(n,Math.floor(s+(a-u)*l/a+c)),o)}var p=i[s],d=r,f=n;for(t(i,r,s),o(i[n],p)>0&&t(i,r,n);d<f;){for(t(i,d,f),d++,f--;o(i[d],p)<0;)d++;for(;o(i[f],p)>0;)f--}0===o(i[r],p)?t(i,r,f):t(i,++f,n),f<=s&&(r=f+1),s<=f&&(n=f-1)}}function t(e,t,i){var s=e[t];e[t]=e[i],e[i]=s}function i(e,t){return e<t?-1:e>t?1:0}return function(t,s,r,n,o){e(t,s,r||0,n||t.length-1,o||i)}}))},{}]},{},[1])(1)}));var Us=Hs.exports.RBush3D,zs=function(e){function t(e){var t=0;return e.meshes.forEach((function(e){t+=e.numTriangles})),t}function i(e,t){var i={pos:{x:0,y:0},left:0,right:e,top:0,bottom:t,dir:0};function s(){(0==i.dir&&i.pos.x+1>=i.right||1==i.dir&&i.pos.y+1>=i.bottom||2==i.dir&&i.pos.x-1<=i.left-1||3==i.dir&&i.pos.y-1<=i.top-1)&&(i.dir=(i.dir+1)%4,0==i.dir&&i.left++,1==i.dir&&i.top++,2==i.dir&&i.right--,3==i.dir&&i.bottom--),0==i.dir&&i.pos.x++,1==i.dir&&i.pos.y++,2==i.dir&&i.pos.x--,3==i.dir&&i.pos.y--}for(var r=[],n=e*t;r.length<n;s())r.push(i.pos.x+"_"+i.pos.y);return r}var s,r,n,o,a=0,u=(r=function(t,i){for(var s=i||function(e){return!0},r=(e.aabbTree.data.maxX-e.aabbTree.data.minX)/10,n=(e.aabbTree.data.maxZ-e.aabbTree.data.minZ)/10,o=[],a=e.aabbTree.data.minX,u=0;u<10;u++,a+=r)for(var h=e.aabbTree.data.minZ,l=0;l<10;l++,h+=n)o.push({minX:a,maxX:a+r,minY:-1e8,maxY:1e8,minZ:h,maxZ:h+n,indexX:u,indexZ:l});var c={cellsByEntity:{},entitiesByCell:{},cellsX:10,cellsZ:10};return(o||[]).forEach((function(t){e.aabbTree.search(t).filter((function(e){return s(e.entity)})).forEach((function(e){var i=e.entity.id;c.cellsByEntity[i]=c.cellsByEntity[i]||{cells:[],entity:e.entity},c.cellsByEntity[i].cells.push(t);var s=t.indexX+"_"+t.indexZ;c.entitiesByCell[s]=c.entitiesByCell[s]||{entities:[],cell:t},c.entitiesByCell[s].entities.push(e.entity)}))})),c}((s={cellSideInMeters:.05,entityFilterFunc:function(e){return!0},maxPolygonsPerCluster:9e4,minPercentOfClustredPolygons:.9}).cellSideInMeters,s.entityFilterFunc),n=function(e,i){var s={},r=0;Object.keys(i).forEach((function(e){var n=i[e].cells.length,o=t(i[e].entity);s[n]=(s[n]||0)+o,r+=o}));var n=Object.keys(s);n.sort((function(e,t){return e-t}));for(var o=0,a=0,u=0;u<n.length&&a<e;u++)o=n[u],a+=s[o]/r;return{maxCellsPerEntity:o,polygonStats:{percentClustered:a,numberClustered:Math.round(a*r),numberUnclustered:r-Math.round(a*r)}}}(s.minPercentOfClustredPolygons,r.cellsByEntity),o=function(e,s,r,n,o,a){var u={},h={accumEntities:[]},l=[];i(e,s).forEach((function(e){var i=function(e,t,i,s){return(i[e]||{entities:[]}).entities.filter((function(e){return s[e.id].cells.length<=t}))}(e,r,n,o).filter((function(e){return!(e.id in u)}));i.forEach((function(e){u[e.id]=!0})),i.sort((function(e,i){return t(e)-t(i)}));var s=h.accumEntities.concat(i),c=[],p=a,d=0;do{for(;d<s.length;d++){var f=s[d],m=t(f);m>p&&(l.push(c),c=[],p=a),c.push(f),p-=m}}while(d<s.length);h.accumEntities=c})),h.accumEntities.length&&l.push(h.accumEntities);var c=[];Object.keys(o).forEach((function(e){e in u||c.push(o[e].entity)}));var p=a,d=[];c.forEach((function(e){var i=t(e);i>p&&(l.push(d),d=[],p=a),d.push(e),p-=i})),d.length&&l.push(d);var f={};return l.forEach((function(e,t){e.forEach((function(e){f[e.id]=t}))})),{clusters:l,entityIdToClusterIdMapping:f}}(r.cellsX,r.cellsZ,n.maxCellsPerEntity,r.entitiesByCell,r.cellsByEntity,s.maxPolygonsPerCluster),{clusters:{total:o.clusters.length},clusteringResult:o});a+=u.clusters.total,console.log("Total clusters: "+a);var h=[];return u.clusteringResult.clusters.forEach((function(e){e.forEach((function(e){h.push(e.id)}))})),u.orderedEntityIds=h,u};
18
18
  /**
19
19
  * @author https://github.com/tmarti, with support from https://tribia.com/
20
20
  * @license MIT