(function(){"use strict";try{if(typeof document<"u"){var e=document.createElement("style");e.appendChild(document.createTextNode('.bim-engine-wrapper{position:relative;width:100%;height:100%;font-family:sans-serif;box-sizing:border-box;overflow:hidden;background:linear-gradient(to bottom,#d6e0eb,#f6faff)}.bim-engine-opt-btn-container{z-index:100}.bim-construct-tree-btn{position:absolute;top:20px;left:20px!important;z-index:100}.bim-engine-version{position:absolute;bottom:6px;left:10px;font-size:11px;color:#00000040;pointer-events:none;-webkit-user-select:none;user-select:none;z-index:1;font-family:system-ui,-apple-system,sans-serif;letter-spacing:.3px}.bim-engine-size{position:absolute;bottom:6px;left:56px;font-size:11px;color:#00000059;pointer-events:none;-webkit-user-select:none;user-select:none;z-index:1;font-family:system-ui,-apple-system,sans-serif;letter-spacing:.3px}.bim-btn-group-root{display:flex;gap:8px;z-index:1000;position:absolute;pointer-events:auto;background:transparent}.bim-btn-group-root.static{position:relative;inset:auto;transform:none}.bim-btn-group-root.dir-row{flex-direction:row;align-items:center}.bim-btn-group-root.dir-column{flex-direction:column;align-items:stretch}.bim-btn-group-section{display:flex;gap:4px;background-color:var(--bim-btn-group-section-bg, rgba(17, 17, 17, .88));border-radius:6px;padding:4px;box-shadow:0 2px 8px #0000004d,0 1px 3px #0003}.bim-btn-group-root.dir-row .bim-btn-group-section{flex-direction:row;align-items:center}.bim-btn-group-root.dir-column .bim-btn-group-section{flex-direction:column}.opt-btn-wrapper{position:relative}.opt-btn{display:flex;cursor:pointer;border-radius:4px;transition:background-color .2s,color .2s,border-color .2s;color:var(--bim-btn-text-color, #ccc);background-color:var(--bim-btn-bg, transparent);padding:6px;align-items:center;position:relative;justify-content:center;border:1px solid transparent;outline:none}.opt-btn:hover{background-color:var(--bim-btn-hover-bg, #444)}.opt-btn.active{background-color:var(--bim-btn-active-bg, rgba(255, 255, 255, .15));color:var(--bim-btn-text-active-color, #fff)}.opt-btn.disabled{opacity:.5;cursor:not-allowed}.opt-btn-icon{width:var(--bim-icon-size, 24px);height:var(--bim-icon-size, 24px);display:flex;align-items:center;justify-content:center;color:var(--bim-icon-color, #ccc);flex-shrink:0}.opt-btn-icon svg{width:100%;height:100%;fill:currentColor}.opt-btn-arrow{font-size:10px;opacity:.6;transition:transform .2s;display:inline-block;margin-left:4px}.opt-btn-arrow.rotated{transform:rotate(180deg)}.opt-btn-text-wrapper{display:flex;align-items:center;justify-content:center;pointer-events:none}.opt-btn-label{display:inline}.opt-btn.no-label .opt-btn-label{display:none}.opt-btn.align-vertical:not(.no-label){flex-direction:column;text-align:center}.opt-btn.align-vertical:not(.no-label) .opt-btn-text-wrapper{margin-top:4px}.opt-btn.align-vertical:not(.no-label) .opt-btn-label{font-size:12px;line-height:1.2}.opt-btn.align-horizontal:not(.no-label){flex-direction:row}.opt-btn.align-horizontal:not(.no-label) .opt-btn-text-wrapper{margin-left:8px}.opt-btn.align-horizontal:not(.no-label) .opt-btn-label{font-size:14px}.opt-btn.no-label .opt-btn-text-wrapper{width:0;height:0;margin:0;padding:0;overflow:visible;position:absolute;top:0;right:0}.opt-btn.no-label .opt-btn-arrow{position:absolute;top:2px;right:2px;margin:0;font-size:8px}.opt-btn-dropdown{position:absolute;background-color:var(--bim-toolbar-bg, rgba(17, 17, 17, .95));border-radius:4px;padding:4px;box-shadow:0 4px 12px #0003;z-index:1001;display:flex;flex-direction:column;border:1px solid rgba(255,255,255,.1);opacity:0;visibility:hidden;transform:translateY(-10px);transition:opacity .2s ease,transform .2s cubic-bezier(.2,0,.2,1),visibility .2s}@keyframes dropdown-fade-in{0%{opacity:0;transform:translateY(-8px) scale(.98)}to{opacity:1;transform:translateY(0) scale(1)}}.opt-btn-dropdown{animation:dropdown-fade-in .2s cubic-bezier(.2,0,.2,1) forwards;opacity:1;visibility:visible;transform:none}.opt-btn-dropdown-item{display:flex;align-items:center;padding:8px 12px;cursor:pointer;border-radius:4px;color:var(--bim-btn-text-color, #ccc);transition:background .2s,border-color .2s,color .2s;box-sizing:border-box;border:1px solid transparent;outline:none}.opt-btn-dropdown-item .opt-btn-icon{color:var(--bim-icon-color, #ccc)}.opt-btn-dropdown-item:hover{background-color:var(--bim-btn-hover-bg, #444)}.opt-btn-dropdown-item.active{background-color:var(--bim-btn-active-bg, rgba(255, 255, 255, .15));color:var(--bim-btn-text-active-color, #fff)}.opt-btn-dropdown-item.align-horizontal{flex-direction:row}.opt-btn-dropdown-item.align-horizontal .opt-btn-icon{width:18px;height:18px;margin-right:8px}.opt-btn-dropdown-item.align-vertical{flex-direction:column;text-align:center}.opt-btn-dropdown-item.align-vertical .opt-btn-icon{width:24px;height:24px;margin-bottom:4px}.opt-btn-dropdown-item.align-vertical .opt-btn-dropdown-label{font-size:12px}.bim-btn-group-root.is-bottom-toolbar .opt-btn-icon{width:32px;height:32px}.bim-btn-group-root.is-bottom-toolbar .opt-btn{padding:8px}.bim-btn-group-root.is-bottom-toolbar.dir-row{max-width:calc(100% - 40px);overflow-x:auto;overflow-y:visible;scrollbar-width:thin;scrollbar-color:rgba(255,255,255,.2) transparent}.bim-btn-group-root.is-bottom-toolbar.dir-row .bim-btn-group-section{flex-shrink:0}.bim-btn-group-root.is-bottom-toolbar.dir-row::-webkit-scrollbar{height:4px}.bim-btn-group-root.is-bottom-toolbar.dir-row::-webkit-scrollbar-track{background:transparent}.bim-btn-group-root.is-bottom-toolbar.dir-row::-webkit-scrollbar-thumb{background:#fff3;border-radius:2px}.bim-btn-group-root.is-bottom-toolbar.dir-row::-webkit-scrollbar-thumb:hover{background:#fff6}.bim-btn-group-root.type-glass-pill .bim-btn-group-section{background:var(--bim-floating-bg);backdrop-filter:blur(24px);-webkit-backdrop-filter:blur(24px);border:1px solid var(--bim-floating-border);border-radius:9999px;box-shadow:none;padding:8px;gap:10px}.bim-btn-group-root.type-glass-pill .opt-btn{width:48px;height:48px;min-width:48px;border-radius:9999px;background:var(--bim-floating-btn-bg);border:1px solid var(--bim-floating-btn-border);box-shadow:var(--bim-floating-btn-shadow);color:var(--bim-text-primary);padding:0;transition:all .2s ease-out}.bim-btn-group-root.type-glass-pill .opt-btn:hover{background:var(--bim-floating-btn-bg-hover);transform:scale(1.05);box-shadow:var(--bim-floating-btn-shadow-hover)}.bim-btn-group-root.type-glass-pill .opt-btn:active{transform:scale(.98)}.bim-btn-group-root.type-glass-pill .opt-btn.active{background:var(--bim-primary);border:1px solid var(--bim-primary-active);color:var(--bim-text-inverse);box-shadow:var(--bim-shadow-glow)}.bim-btn-group-root.type-glass-pill .opt-btn.active:hover{background:var(--bim-primary-hover);transform:scale(1.05)}.bim-btn-group-root.type-glass-pill .opt-btn.active:active{transform:scale(.98)}.bim-btn-group-root.type-glass-pill .opt-btn.active .opt-btn-icon{color:var(--bim-icon-inverse)}.bim-btn-group-root.type-glass-pill .opt-btn.disabled{opacity:.3;cursor:not-allowed;transform:none;box-shadow:none}.bim-btn-group-root.type-glass-pill .opt-btn-icon{width:18px;height:18px;color:var(--bim-floating-icon-color);transition:color .2s ease-out}.bim-btn-group-root.type-glass-pill .opt-btn-icon svg{width:18px;height:18px}.bim-btn-group-root.type-glass-pill .opt-btn:hover .opt-btn-icon{color:var(--bim-floating-icon-color-hover)}.bim-btn-group-root.type-glass-pill .opt-btn-label{display:none!important}.bim-btn-group-root.type-glass-pill .opt-btn-text-wrapper{position:absolute;top:2px;right:2px;width:0;height:0;margin:0;padding:0}.bim-btn-group-root.type-glass-pill .opt-btn-arrow{font-size:8px;position:absolute;top:0;right:0;color:var(--bim-text-tertiary)}.opt-btn-dropdown.type-glass-pill{background:#fffffff2;backdrop-filter:blur(10px);-webkit-backdrop-filter:blur(10px);border:1px solid rgba(226,232,240,.6);border-radius:12px;box-shadow:0 8px 24px #0000001f;padding:6px}.opt-btn-dropdown.type-glass-pill .opt-btn-dropdown-item{display:flex;flex-direction:row;align-items:center;gap:10px;border-radius:8px;color:#334155;padding:8px 12px;font-size:13px;font-weight:400;transition:all .1s ease-out}.opt-btn-dropdown.type-glass-pill .opt-btn-dropdown-item:hover{background:#f1f5f9}.opt-btn-dropdown.type-glass-pill .opt-btn-dropdown-item:active{background:#e2e8f0}.opt-btn-dropdown.type-glass-pill .opt-btn-dropdown-item.active{background:#3b82f6;color:#fff}.opt-btn-dropdown.type-glass-pill .opt-btn-dropdown-item.active .opt-btn-icon,.opt-btn-dropdown.type-glass-pill .opt-btn-dropdown-item.active .opt-btn-dropdown-label{color:#fff}.opt-btn-dropdown.type-glass-pill .opt-btn-dropdown-item .opt-btn-icon{width:18px;height:18px;color:#334155;flex-shrink:0}.opt-btn-dropdown.type-glass-pill .opt-btn-dropdown-item .opt-btn-icon svg{width:18px;height:18px}.opt-btn-dropdown.type-glass-pill .opt-btn-dropdown-item .opt-btn-dropdown-label{white-space:nowrap;color:#334155}.opt-btn-dropdown.type-glass-pill.theme-dark{background:var(--bim-bg-overlay);backdrop-filter:blur(10px);-webkit-backdrop-filter:blur(10px);border:1px solid var(--bim-border-default);box-shadow:var(--bim-shadow-lg)}.opt-btn-dropdown.type-glass-pill.theme-dark .opt-btn-dropdown-item{color:var(--bim-text-primary)}.opt-btn-dropdown.type-glass-pill.theme-dark .opt-btn-dropdown-item:hover{background:var(--bim-floating-btn-bg)}.opt-btn-dropdown.type-glass-pill.theme-dark .opt-btn-dropdown-item:active{background:var(--bim-floating-btn-bg-hover)}.opt-btn-dropdown.type-glass-pill.theme-dark .opt-btn-dropdown-item.active{background:var(--bim-primary);color:var(--bim-text-inverse)}.opt-btn-dropdown.type-glass-pill.theme-dark .opt-btn-dropdown-item .opt-btn-icon{color:var(--bim-floating-icon-color)}.opt-btn-dropdown.type-glass-pill.theme-dark .opt-btn-dropdown-item .opt-btn-dropdown-label{color:var(--bim-text-primary)}.bim-dialog{position:absolute;background-color:var(--bim-bg-elevated);border:1px solid var(--bim-border-default);border-radius:var(--bim-panel-radius, 12px);box-shadow:var(--bim-shadow-lg);display:flex;flex-direction:column;z-index:10001;color:var(--bim-dialog-title-color, var(--bim-text-primary));overflow:hidden;min-width:200px;min-height:100px;pointer-events:auto}.bim-dialog-header{height:40px;background-color:var(--bim-bg-inset);display:flex;align-items:center;justify-content:space-between;padding:0 12px;cursor:default;-webkit-user-select:none;user-select:none;border-bottom:1px solid var(--bim-border-default);flex-shrink:0}.bim-dialog-header.draggable{cursor:move}.bim-dialog-title{font-size:14px;font-weight:500;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;color:var(--bim-dialog-title-color)}.bim-dialog-close{cursor:pointer;font-size:18px;color:var(--bim-text-tertiary);line-height:1;margin-left:8px}.bim-dialog-close:hover{color:var(--bim-text-primary)}.bim-dialog-content{flex:1;overflow:auto;font-size:14px;color:var(--bim-dialog-text-color, var(--bim-text-secondary))}.bim-dialog-resize-handle{position:absolute;width:10px;height:10px;bottom:0;right:0;cursor:se-resize;z-index:10}.bim-dialog-resize-handle:after{content:"";position:absolute;bottom:3px;right:3px;width:6px;height:6px;border-right:2px solid var(--bim-text-tertiary);border-bottom:2px solid var(--bim-text-tertiary)}.bim-dialog-resize-handle:hover:after{border-color:var(--bim-text-primary)}.originRotate{width:10px;height:10px;background-color:red}.versionText{position:absolute;right:10px;color:#86d9ff;z-index:1000;bottom:0;font-size:10px;background:transparent;pointer-events:none}.originDiv{position:absolute;top:100px;left:100px;width:30px;height:30px;border-radius:50%;z-index:1000;pointer-events:none}.tagDiv{color:gray;background:#fffc;padding:5px;font-size:12px}.catchPoint{pointer-events:none;stroke:#08dfd7;fill:transparent;stroke-width:2}.catchLine{position:absolute;width:10px;height:10px;pointer-events:none;background-color:green}.catchPlane{position:absolute;width:10px;height:10px;pointer-events:none;background-color:#ff0}.ViewCube{position:absolute;width:120px;height:120px;top:0;right:0;z-index:999}.homeViewWrapper{position:absolute;cursor:pointer;pointer-events:auto;background-image:url(/assets/viewcube/home.png);background-size:100% 100%;background-repeat:no-repeat;background-color:#fff0;color:#fff;top:10px;right:100;width:20px;height:20px;z-index:999;user-select:none;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none}.viewSettingWrapper{position:absolute;cursor:pointer;pointer-events:auto;background-size:100% 100%;background-repeat:no-repeat;font-weight:800;background-color:#fff0;color:#fff;top:30px;right:100;width:20px;height:20px;z-index:999;user-select:none;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none}.cameraToggleWrapper{position:absolute;cursor:pointer;pointer-events:auto;background-color:#ffffffe6;color:#333;font-size:26px;font-weight:700;display:none;align-items:center;justify-content:center;border-radius:4px;box-shadow:0 2px 4px #0003;transition:all .3s ease;top:70px;right:90px;width:44px;height:44px;z-index:999;user-select:none;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none}.cameraToggleWrapper.show{display:flex}.cameraToggleWrapper:hover{background-color:#fff;box-shadow:0 3px 6px #0000004d;transform:scale(1.1)}.screenshotWrapper{position:absolute;cursor:pointer;pointer-events:auto;background-color:#ffffffe6;color:#333;font-size:20px;display:none;align-items:center;justify-content:center;border-radius:4px;box-shadow:0 2px 4px #0003;transition:all .3s ease;top:120px;right:90px;width:44px;height:44px;z-index:999;user-select:none;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none}.screenshotWrapper.show{display:flex}.screenshotWrapper:hover{background-color:#fff;box-shadow:0 3px 6px #0000004d;transform:scale(1.1)}.fullscreenWrapper{position:absolute;cursor:pointer;pointer-events:auto;background-color:#ffffffe6;color:#333;font-size:26px;font-weight:700;display:none;align-items:center;justify-content:center;border-radius:4px;box-shadow:0 2px 4px #0003;transition:all .3s ease;top:170px;right:90px;width:44px;height:44px;z-index:999;user-select:none;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none}.fullscreenWrapper.show{display:flex}.fullscreenWrapper:hover{background-color:#fff;box-shadow:0 3px 6px #0000004d;transform:scale(1.1)}.measure-elevation{position:absolute;pointer-events:none}.measureSvg{position:absolute;width:1920px;height:1080px}.catch-point{position:absolute;width:10px;height:10px;background-color:red;border-radius:50%;pointer-events:none}.annotation-container{position:absolute;pointer-events:none;top:0;left:0}.measureLine{position:absolute;pointer-events:none;stroke:#009bea;fill:#009bea;filter:drop-shadow(1px 1px 2px rgba(0,0,0,.3))}.measureBack{cursor:pointer;pointer-events:auto;fill:#fff;padding:5px;top:-50px;rx:5;ry:5;filter:drop-shadow(1px 1px 2px rgba(0,0,0,.3))}.measureLabel{position:absolute;fill:#fff;font-size:14px;stroke:#009bea;font-weight:100;pointer-events:none}.measurePointer{fill:#009bea}.Hight{stroke:#fff;font-weight:500;filter:drop-shadow(2px 1px 2px rgba(255,255,255,1))}.allow-select{pointer-events:auto}.disallow-select{pointer-events:none}.angle-annotation{position:absolute;pointer-events:auto}.MapController{-webkit-touch-callout:none;-webkit-user-select:none;-khtml-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none}.engine-2d-container{position:relative;width:100%;height:100%;overflow:hidden}.engine-2d-canvas{display:block;width:100%;height:100%;outline:none}.engine-2d-cad-cursor{position:absolute;top:0;left:0;width:100%;height:100%;pointer-events:none;overflow:hidden}.engine-2d-cad-cursor__h{position:absolute;left:0;width:100%;height:1px;background:var(--e2d-cursor, rgba(255, 255, 255, .85));transform:translateY(-50%)}.engine-2d-cad-cursor__v{position:absolute;top:0;width:1px;height:100%;background:var(--e2d-cursor, rgba(255, 255, 255, .85));transform:translate(-50%)}.engine-2d-cad-cursor__box{position:absolute;width:8px;height:8px;border:1px solid var(--e2d-cursor, rgba(255, 255, 255, .85));transform:translate(-50%,-50%)}.engine-2d-context-menu{position:absolute;z-index:9999;min-width:140px;background:var(--e2d-bg2, #252526);border:1px solid var(--e2d-border, rgba(255, 255, 255, .12));border-radius:4px;box-shadow:0 4px 16px var(--e2d-shadow, rgba(0, 0, 0, .5));padding:4px 0;display:none;-webkit-user-select:none;user-select:none}.engine-2d-context-menu--visible{display:block}.engine-2d-context-menu__item{padding:7px 16px;font-size:13px;color:var(--e2d-text2, #cccccc);cursor:pointer;white-space:nowrap;transition:background .1s,color .1s}.engine-2d-context-menu__item:hover{background:var(--e2d-bg-accent, #094771);color:var(--e2d-text-accent, #ffffff)}.engine-2d-context-menu__divider{height:1px;background:var(--e2d-border, rgba(255, 255, 255, .1));margin:4px 0}.engine-2d-stats{position:absolute;top:10px;left:10px;background:var(--e2d-float-bg, rgba(0, 0, 0, .7));color:var(--e2d-text, #e0e0e0);padding:8px 12px;border-radius:4px;font-family:monospace;font-size:12px;pointer-events:none;-webkit-user-select:none;user-select:none}.engine-2d-stats div{margin:2px 0}.engine-2d-loading{position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);background:var(--e2d-float-bg, rgba(0, 0, 0, .8));color:var(--e2d-text, #e0e0e0);padding:20px 40px;border-radius:8px;font-size:16px;text-align:center}.engine-2d-loading-spinner{border:3px solid var(--e2d-border, rgba(255, 255, 255, .3));border-top:3px solid var(--e2d-accent, #4fc3f7);border-radius:50%;width:40px;height:40px;animation:engine-2d-spin 1s linear infinite;margin:0 auto 10px}@keyframes engine-2d-spin{0%{transform:rotate(0)}to{transform:rotate(360deg)}}.engine-2d-error{position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);background:#d32f2feb;color:#fff;padding:20px 40px;border-radius:8px;font-size:14px;max-width:80%;text-align:center}.engine-2d-controls-hint{position:absolute;bottom:10px;left:10px;background:var(--e2d-float-bg, rgba(0, 0, 0, .6));color:var(--e2d-text, #e0e0e0);border:1px solid var(--e2d-float-border, rgba(255, 255, 255, .08));padding:8px 12px;border-radius:4px;font-size:12px;pointer-events:none;-webkit-user-select:none;user-select:none}.engine-2d-controls-hint kbd{background:var(--e2d-icon-bg, rgba(255, 255, 255, .2));color:var(--e2d-text, #e0e0e0);padding:2px 6px;border-radius:3px;font-family:monospace}.engine-2d-search{position:absolute;top:0;left:0;width:100%;height:100%;pointer-events:none;z-index:9998;display:none}.engine-2d-search--visible{display:block}.engine-2d-search__box{position:absolute;top:14%;left:50%;transform:translate(-50%);width:480px;max-width:calc(100% - 40px);background:var(--e2d-bg, #1e1f22);border:1px solid var(--e2d-border, rgba(255, 255, 255, .14));border-radius:10px;box-shadow:0 8px 40px var(--e2d-shadow-lg, rgba(0, 0, 0, .65)),0 2px 8px var(--e2d-shadow, rgba(0, 0, 0, .4));overflow:hidden;pointer-events:auto;animation:engine-2d-search-in .18s cubic-bezier(.34,1.2,.64,1)}@keyframes engine-2d-search-in{0%{opacity:0;transform:translate(-50%) translateY(-8px) scale(.97)}to{opacity:1;transform:translate(-50%) translateY(0) scale(1)}}.engine-2d-search__input-row{display:flex;align-items:center;padding:0 12px;gap:8px;height:48px}.engine-2d-search__icon{flex-shrink:0;color:var(--e2d-icon, rgba(255, 255, 255, .4));display:flex;align-items:center}.engine-2d-search__input{flex:1;background:transparent;border:none;outline:none;color:var(--e2d-text, #e0e0e0);font-size:14px;line-height:1.4;caret-color:var(--e2d-accent, #4fc3f7)}.engine-2d-search__input::placeholder{color:var(--e2d-text3, rgba(255, 255, 255, .25))}.engine-2d-search__clear{flex-shrink:0;background:var(--e2d-icon-bg, rgba(255, 255, 255, .08));border:none;border-radius:4px;color:var(--e2d-icon, rgba(255, 255, 255, .5));cursor:pointer;display:flex;align-items:center;justify-content:center;width:22px;height:22px;padding:0;opacity:0;pointer-events:none;transition:opacity .15s,background .15s,color .15s}.engine-2d-search__clear:hover{background:var(--e2d-icon-bg-hover, rgba(255, 255, 255, .16));color:var(--e2d-close-hover, #ffffff)}.engine-2d-search__divider{height:1px;background:var(--e2d-border2, rgba(255, 255, 255, .08));display:none}.engine-2d-search__status{padding:6px 16px;font-size:11px;color:var(--e2d-text3, rgba(255, 255, 255, .35));display:none;-webkit-user-select:none;user-select:none}.engine-2d-search__list{list-style:none;margin:0;padding:4px 0;max-height:320px;overflow-y:auto;display:none;scrollbar-width:thin;scrollbar-color:var(--e2d-scrollbar, rgba(255, 255, 255, .15)) transparent}.engine-2d-search__list::-webkit-scrollbar{width:4px}.engine-2d-search__list::-webkit-scrollbar-track{background:transparent}.engine-2d-search__list::-webkit-scrollbar-thumb{background:var(--e2d-scrollbar, rgba(255, 255, 255, .15));border-radius:2px}.engine-2d-search__item{display:flex;align-items:center;gap:8px;padding:8px 14px;cursor:pointer;transition:background .1s;min-height:38px;flex-wrap:nowrap}.engine-2d-search__item:hover,.engine-2d-search__item--active{background:var(--e2d-bg-hover, rgba(79, 195, 247, .08))}.engine-2d-search__item-badge{flex-shrink:0;font-size:10px;font-weight:500;padding:2px 6px;border-radius:3px;letter-spacing:.03em;white-space:nowrap}.engine-2d-search__item-name{flex:1;font-size:13px;color:var(--e2d-text, #e0e0e0);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.engine-2d-search__item-layer{flex-shrink:0;font-size:11px;color:var(--e2d-text3, rgba(255, 255, 255, .3));white-space:nowrap;max-width:100px;overflow:hidden;text-overflow:ellipsis}.engine-2d-search__item-desc{flex-shrink:0;font-size:11px;color:var(--e2d-text4, rgba(255, 255, 255, .25));white-space:nowrap;max-width:120px;overflow:hidden;text-overflow:ellipsis}.engine-2d-search__mark{background:transparent;color:var(--e2d-accent, #4fc3f7);font-weight:600}.engine-2d-mouse-coord{position:absolute;bottom:10px;left:50%;transform:translate(-50%);display:flex;align-items:center;gap:12px;background:var(--e2d-float-bg, rgba(0, 0, 0, .65));color:var(--e2d-text, #e0e0e0);padding:5px 14px;border-radius:4px;font-family:monospace;font-size:12px;pointer-events:none;-webkit-user-select:none;user-select:none;border:1px solid var(--e2d-float-border, rgba(255, 255, 255, .08))}.engine-2d-mouse-coord__label{color:var(--e2d-coord-label, rgba(255, 255, 255, .45));font-size:11px;letter-spacing:.05em}.engine-2d-mouse-coord__value{min-width:90px;color:var(--e2d-coord-value, #76c8ff)}.panorama-annotation-container{position:absolute;top:0;left:0;width:100%;height:100%;pointer-events:none;z-index:1000;overflow:hidden}.panorama-annotation{position:absolute;pointer-events:auto;cursor:pointer;transform:translate(-50%,-50%);transition:opacity .2s ease,transform .2s ease;user-select:none;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none}.panorama-annotation:hover{z-index:1001;transform:translate(-50%,-50%) scale(1.1)}.panorama-annotation-icon{width:40px;height:40px}.panorama-annotation-icon img{width:100%;height:100%;object-fit:contain;display:block;filter:drop-shadow(0 2px 4px rgba(0,0,0,.3))}.panorama-annotation-text{max-width:200px;text-align:center;line-height:1.4}.panorama-annotation-link{transition:background-color .2s ease,transform .2s ease}.panorama-annotation-link:hover{z-index:1002}.panorama-annotation-link img{display:block;flex-shrink:0}.panorama-annotation.hidden{display:none!important}@keyframes pulse{0%,to{opacity:1}50%{opacity:.5}}.panorama-annotation.loading{animation:pulse 1.5s ease-in-out infinite}@media(max-width:768px){.panorama-annotation-icon{width:32px;height:32px}.panorama-annotation-text,.panorama-annotation-link{font-size:12px!important;padding:6px 10px!important}}.bim-right-key{position:fixed;z-index:10000;display:none;background:transparent}.bim-right-key.visible{display:block}.bim-menu{display:flex;flex-direction:column;background:var(--bim-bg-elevated);border:1px solid var(--bim-border-default);border-radius:8px;padding:6px;margin:0;list-style:none;box-shadow:var(--bim-shadow-lg);font-family:-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica Neue,Arial,sans-serif;-webkit-user-select:none;user-select:none;color:var(--bim-text-primary)}.bim-menu-group{display:flex;flex-direction:column}.bim-menu-divider{height:1px;background-color:var(--bim-divider);margin:4px 0}.bim-menu-item{display:flex;align-items:center;padding:8px 12px;cursor:pointer;transition:all .2s ease;font-size:13px;position:relative;color:var(--bim-text-primary);border-radius:6px}.bim-menu-item:hover{background-color:var(--bim-component-bg-hover)}.bim-menu-item.disabled{opacity:.5;cursor:not-allowed;pointer-events:none}.bim-menu-item-icon{display:none}.bim-menu.has-icons .bim-menu-item-icon{width:16px;height:16px;margin-right:8px;display:flex;align-items:center;justify-content:center;flex-shrink:0}.bim-menu-item-icon svg{width:100%;height:100%;fill:currentColor}.bim-menu-item-label{flex:1;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.bim-menu-item-arrow{width:12px;height:12px;margin-left:8px;display:flex;align-items:center;justify-content:center;opacity:.7}.bim-menu-item-arrow svg{width:100%;height:100%;fill:currentColor}.bim-tree{width:100%;height:100%;display:flex;flex-direction:column;overflow:hidden;font-size:14px;color:var(--bim-text-primary);-webkit-user-select:none;user-select:none;position:relative;background:transparent}.bim-tree-search{padding:6px;background-color:transparent;flex-shrink:0;position:relative}.bim-tree-search-wrapper{position:relative;width:100%;display:flex;align-items:center}.bim-tree-search-icon{position:absolute;left:8px;width:16px;height:16px;color:var(--bim-text-secondary);pointer-events:none;display:flex;align-items:center;justify-content:center}.bim-tree-search-icon svg{width:100%;height:100%}.bim-tree-search-input{width:100%;height:30px;padding:4px 8px 4px 30px;border:1px solid var(--bim-border-default);border-radius:4px;outline:none;font-size:13px;color:inherit;background-color:var(--bim-bg-elevated);transition:all .2s;box-sizing:border-box}.bim-tree-search-input:focus{border-color:var(--bim-primary);box-shadow:var(--bim-focus-ring)}.bim-tree-search-results{position:absolute;top:100%;left:8px;right:8px;background-color:var(--bim-bg-elevated);border:1px solid var(--bim-border-default);box-shadow:var(--bim-shadow-md);border-radius:4px;max-height:200px;overflow-y:auto;z-index:10;display:none}.bim-tree-search-results.is-visible{display:block}.bim-tree-search-item{padding:8px 12px;cursor:pointer;border-bottom:1px solid rgba(0,0,0,.03)}.bim-tree-search-item:last-child{border-bottom:none}.bim-tree-search-item:hover{background-color:var(--bim-component-bg-hover)}.bim-tree-search-item-title{font-weight:500;display:block}.bim-tree-search-item-path{font-size:12px;color:var(--bim-text-secondary);margin-top:2px;display:block}.bim-tree-node-content:hover{background-color:var(--bim-component-bg-hover)}.bim-tree-switcher{width:24px;height:32px;display:flex;align-items:center;justify-content:center;cursor:pointer;color:var(--bim-text-secondary);transition:transform .2s;flex-shrink:0}.bim-tree-switcher svg{width:12px;height:12px;fill:currentColor;transition:transform .2s}.bim-tree-switcher.is-expanded svg{transform:rotate(90deg)}.bim-tree-switcher.is-hidden{visibility:hidden}.bim-tree-checkbox{width:16px;height:16px;border:1px solid var(--bim-border-default);border-radius:2px;margin-right:8px;background-color:var(--bim-bg-elevated);position:relative;cursor:pointer;flex-shrink:0;transition:all .2s}.bim-tree-checkbox:hover{border-color:var(--bim-primary)}.bim-tree-checkbox.is-checked{background-color:var(--bim-primary);border-color:var(--bim-primary)}.bim-tree-checkbox.is-checked:after{content:"";position:absolute;top:1px;left:4px;width:5px;height:9px;border:2px solid var(--bim-text-inverse);border-top:0;border-left:0;transform:rotate(45deg)}.bim-tree-checkbox.is-indeterminate{background-color:var(--bim-bg-elevated);border-color:var(--bim-primary)}.bim-tree-checkbox.is-indeterminate:after{content:"";position:absolute;top:6px;left:3px;width:8px;height:2px;background-color:var(--bim-primary)}.bim-tree-node.is-disabled .bim-tree-checkbox{background-color:var(--bim-component-bg-disabled);border-color:var(--bim-border-disabled);cursor:not-allowed}.bim-tree-node.is-disabled .bim-tree-checkbox.is-checked{background-color:var(--bim-text-disabled)}.bim-tree-node.is-disabled .bim-tree-node-content{color:var(--bim-text-disabled);cursor:not-allowed}.bim-tree-icon{width:16px;height:16px;margin-right:6px;display:flex;align-items:center;justify-content:center;flex-shrink:0}.bim-tree-icon img,.bim-tree-icon svg{width:100%;height:100%}.bim-tree-title{flex:1;white-space:nowrap}.bim-tree-children{display:none;overflow:visible}.bim-tree-children.is-visible{display:block}.bim-tree-node-content.is-selected{background-color:var(--bim-component-bg-selected);color:var(--bim-primary)}.bim-tree-node-actions{display:none;align-items:center;margin-left:8px;flex-shrink:0}.bim-tree-node-content.is-selected .bim-tree-node-actions{display:flex}.bim-tree-content{flex:1;overflow-y:auto;overflow-x:hidden;overscroll-behavior:contain;scroll-behavior:auto;padding:2px 0;min-height:0}.bim-tree-node{display:flex;flex-direction:column;width:100%}.bim-tree-node-content{display:flex;align-items:center;height:32px;cursor:pointer;transition:background-color .2s;border-radius:4px;padding-right:8px;width:100%;box-sizing:border-box}.bim-tab{display:flex;flex-direction:column;width:100%;height:100%;background:transparent;color:var(--bim-text-secondary)}.bim-tab__nav{display:flex;align-items:center;gap:4px;padding:4px;margin:8px 12px;background:var(--bim-bg-inset);border-radius:8px;border:1px solid var(--bim-border-subtle)}.bim-tab__item{flex:1;display:inline-flex;align-items:center;justify-content:center;gap:6px;padding:8px 12px;border:none;border-radius:6px;background:transparent;color:var(--bim-text-secondary);cursor:pointer;transition:all .2s ease;font-size:13px;font-weight:500}.bim-tab__item:hover{color:var(--bim-text-primary);background-color:var(--bim-component-bg-hover)}.bim-tab__item.is-active{color:var(--bim-primary);background-color:var(--bim-bg-elevated);box-shadow:0 1px 3px #0000001a}.bim-tab__item.is-disabled{opacity:.5;cursor:not-allowed}.bim-tab__icon{width:16px;height:16px;display:inline-flex;align-items:center;justify-content:center;color:var(--bim-tab-icon, currentColor)}.bim-tab__icon svg{width:100%;height:100%;fill:currentColor}.bim-tab__title{white-space:nowrap}.bim-tab__content{flex:1;display:flex;position:relative;min-height:0;overflow:hidden}.bim-tab__panel{display:none;width:100%;height:100%;flex:1}.bim-tab__panel.is-active{display:flex;flex-direction:column;height:100%}.construct-tab__container{height:100%;display:flex;flex-direction:column}.construct-tab__panel-content{flex:1;display:flex;flex-direction:column;min-height:0;overflow:hidden}.construct-tab__panel-content .bim-tree{flex:1}.bim-measure-panel{width:100%;display:flex;flex-direction:column;box-sizing:border-box;color:var(--bim-text-secondary)}.bim-measure-settings{display:none;box-sizing:border-box;color:var(--bim-text-secondary)}.bim-measure-settings-title{font-size:14px;font-weight:600;margin-bottom:10px}.bim-measure-settings-row{display:flex;align-items:center;justify-content:space-between;gap:10px;margin-bottom:10px}.bim-measure-settings-row .label{color:var(--bim-text-secondary);font-size:13px;flex:0 0 auto}.bim-measure-settings-select{flex:0 0 auto;width:120px;height:28px;border-radius:6px;border:1px solid var(--bim-border-default);background:var(--bim-bg-inset);color:var(--bim-text-primary);padding:0 8px;box-sizing:border-box;outline:none}.bim-measure-settings-hint{font-size:12px;line-height:1.4;color:var(--bim-text-tertiary);margin-top:-4px;margin-bottom:8px}.bim-measure-settings-actions{margin-top:14px;display:flex;justify-content:flex-start;gap:10px}.bim-measure-settings-save,.bim-measure-settings-cancel{flex:0 0 auto!important;width:auto;min-width:0;height:30px;padding:0 12px;border-radius:4px;cursor:pointer;box-sizing:border-box}.bim-measure-settings-save{border:none;background:var(--bim-primary);color:var(--bim-text-inverse)}.bim-measure-settings-cancel{border:1px solid var(--bim-border-default);background:transparent;color:var(--bim-text-secondary)}.bim-measure-settings-save:hover,.bim-measure-settings-save:active,.bim-measure-settings-save:focus,.bim-measure-settings-cancel:hover,.bim-measure-settings-cancel:active,.bim-measure-settings-cancel:focus{background:inherit;outline:none}.bim-measure-settings-save:hover{background:var(--bim-primary-hover)}.bim-measure-tools{display:flex;flex-direction:column;gap:8px}.bim-measure-tool-grid{display:grid;grid-template-columns:repeat(4,1fr);gap:8px}.bim-measure-tool-btn{width:100%;height:42px;border-radius:6px;border:1px solid var(--bim-border-default);background:var(--bim-bg-inset);cursor:pointer;display:flex;align-items:center;justify-content:center;transition:all .2s ease;padding:0;box-sizing:border-box}.bim-measure-tool-btn:hover{background:var(--bim-component-bg-hover);border-color:var(--bim-border-strong)}.bim-measure-tool-btn.is-active{border-color:var(--bim-primary);background:var(--bim-primary-subtle)}.bim-measure-tool-btn.is-active .bim-measure-tool-icon{color:var(--bim-primary)}.bim-measure-tool-icon{width:28px;height:28px;display:inline-flex;align-items:center;justify-content:center;color:var(--bim-icon-default)}.bim-measure-tool-icon svg{width:100%;height:100%;fill:currentColor}.bim-measure-toggle{display:flex;justify-content:flex-end}.bim-measure-toggle-btn{height:22px;border-radius:4px;border:1px solid var(--bim-border-default);background:var(--bim-bg-inset);cursor:pointer;display:inline-flex;align-items:center;justify-content:center;transition:all .2s ease;padding:0 6px;gap:4px;font-size:12px;line-height:1}.bim-measure-toggle-btn:hover{background:var(--bim-component-bg-hover);border-color:var(--bim-border-strong)}.bim-measure-toggle-text{color:var(--bim-text-secondary)}.bim-measure-toggle-icon svg{width:14px;height:14px;fill:currentColor;color:var(--bim-icon-default);transition:transform .15s ease}.bim-measure-toggle-btn.is-expanded .bim-measure-toggle-icon svg{transform:rotate(180deg)}.bim-measure-mode-options{display:none;flex-direction:column;gap:8px;margin-top:12px;padding-top:12px;border-top:1px solid var(--bim-divider)}.bim-measure-mode-options.is-visible{display:flex}.bim-measure-radio-group{display:flex;align-items:center;gap:8px;font-size:13px;line-height:1.4}.bim-measure-radio-group .bim-measure-radio-label{color:var(--bim-text-secondary);min-width:58px;flex:0 0 auto}.bim-measure-radio-group .bim-measure-radio-items{display:flex;gap:4px}.bim-measure-radio-item{display:inline-flex;align-items:center;justify-content:center;height:26px;padding:0 10px;border-radius:4px;border:1px solid var(--bim-border-default);background:var(--bim-bg-inset);color:var(--bim-text-secondary);font-size:12px;cursor:pointer;transition:all .15s ease;-webkit-user-select:none;user-select:none}.bim-measure-radio-item:hover{border-color:var(--bim-border-strong);color:var(--bim-text-primary)}.bim-measure-radio-item.is-active{background:var(--bim-primary-subtle);border-color:var(--bim-primary);color:var(--bim-primary)}.bim-measure-result{margin-top:12px;padding-top:12px;border-top:1px solid var(--bim-divider);display:flex;flex-direction:column;gap:10px}.bim-measure-row{display:flex;align-items:baseline;gap:8px;font-size:13px;line-height:1.4}.bim-measure-row .label{color:var(--bim-text-secondary);min-width:84px}.bim-measure-row .value{color:var(--bim-text-primary);flex:1;word-break:break-word}.bim-measure-main-number{color:#ffd24a}.bim-measure-main-number.is-laser-text,.bim-measure-main-unit{color:var(--bim-text-primary)}.bim-measure-xyz{display:flex;flex-direction:column;gap:6px}.bim-measure-xyz .value{font-variant-numeric:tabular-nums}.bim-measure-xyz-x{color:#ff4d4f!important}.bim-measure-xyz-y{color:#52c41a!important}.bim-measure-xyz-z{color:#1677ff!important}.bim-measure-footer{margin-top:12px;padding-top:10px;border-top:1px solid var(--bim-divider);display:flex;align-items:center;justify-content:flex-start;gap:10px}.bim-measure-clear-btn{background:transparent;border:none;color:var(--bim-danger);cursor:pointer;padding:0;font-size:13px;flex:0 0 auto!important;width:auto;min-width:0}.bim-measure-clear-btn:hover,.bim-measure-clear-btn:active,.bim-measure-clear-btn:focus{background:transparent;border:none;outline:none;text-decoration:none}.bim-measure-settings-btn{width:24px;height:24px;border-radius:4px;border:none;background:transparent;cursor:pointer;display:inline-flex;align-items:center;justify-content:center;padding:0;margin-left:auto;flex:0 0 auto!important}.bim-measure-settings-btn:hover,.bim-measure-settings-btn:active,.bim-measure-settings-btn:focus{background:transparent;border:none;outline:none}.bim-measure-settings-btn svg{width:18px;height:18px;fill:currentColor;color:var(--bim-icon-default)}.section-plane-panel{display:flex;gap:8px;padding:12px 12px 16px;box-sizing:border-box}.section-plane-btn{flex:1;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:4px;padding:10px;border:1px solid var(--bim-border-default);background:var(--bim-bg-inset);border-radius:8px;cursor:pointer;transition:all .2s ease;min-width:60px;outline:none;color:var(--bim-text-primary)}.section-plane-btn:hover{background:var(--bim-component-bg-hover);border-color:var(--bim-border-strong)}.section-plane-btn:active{background:var(--bim-primary-subtle);border-color:var(--bim-primary)}.section-plane-btn.is-active{background:var(--bim-primary-subtle);border-color:var(--bim-primary);color:var(--bim-primary)}.section-plane-btn.is-active .section-plane-btn-icon{color:var(--bim-primary)}.section-plane-btn-icon{width:24px;height:24px;display:flex;align-items:center;justify-content:center;color:var(--bim-icon-default)}.section-plane-btn-icon svg{width:100%;height:100%;fill:currentColor}.section-plane-btn-label{font-size:12px;color:inherit;text-align:center;line-height:1.2}.section-axis-panel{display:flex;flex-direction:column;gap:8px;padding:12px 12px 16px;box-sizing:border-box}.section-axis-row-1{display:flex;gap:8px;padding-bottom:8px;border-bottom:1px solid var(--bim-divider)}.section-axis-row-2{display:flex;gap:8px;padding-top:8px}.section-axis-btn{flex:1;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:4px;padding:8px;background:var(--bim-bg-inset);border:1px solid var(--bim-border-default);border-radius:8px;cursor:pointer;transition:all .2s ease;outline:none;color:var(--bim-text-primary);min-height:48px}.section-axis-btn:hover{background:var(--bim-component-bg-hover);border-color:var(--bim-border-strong)}.section-axis-btn.active{background:var(--bim-primary-subtle);border-color:var(--bim-primary);color:var(--bim-primary)}.section-axis-btn.active .section-axis-btn-icon{color:var(--bim-primary)}.section-axis-btn-icon{width:24px;height:24px;display:inline-flex;align-items:center;justify-content:center;color:var(--bim-icon-default)}.section-axis-btn-icon svg{width:100%;height:100%}.section-axis-btn-label{font-size:12px;color:inherit;text-align:center;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;max-width:100%}.section-axis-btn-text{min-height:40px}.section-axis-btn-text .section-axis-btn-label{font-size:18px;font-weight:600}.section-box-panel{display:flex;flex-direction:column;padding:12px;box-sizing:border-box;-webkit-user-select:none;user-select:none}.section-box-row-buttons{display:flex;gap:6px;padding-bottom:12px;border-bottom:1px solid var(--bim-divider)}.section-box-btn{flex:1;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:4px;padding:6px;background:var(--bim-bg-inset);border:1px solid var(--bim-border-default);border-radius:8px;cursor:pointer;color:var(--bim-text-primary);min-height:44px;transition:all .2s ease}.section-box-btn:hover{background:var(--bim-component-bg-hover);border-color:var(--bim-border-strong)}.section-box-btn.active{background:var(--bim-primary-subtle);border-color:var(--bim-primary);color:var(--bim-primary)}.section-box-btn.active .section-box-btn-icon{color:var(--bim-primary)}.section-box-btn-icon{width:24px;height:24px;color:var(--bim-icon-default)}.section-box-btn-icon svg{width:100%;height:100%}.section-box-btn-label{font-size:11px;white-space:nowrap}.section-box-sliders{display:flex;flex-direction:column;gap:16px;padding-top:16px}.section-box-slider{display:flex;align-items:center;gap:12px;position:relative;z-index:1}.section-box-slider:hover{z-index:10}.section-box-slider-label{font-size:13px;font-weight:700;color:var(--bim-text-primary);min-width:14px}.section-box-slider-track{position:relative;flex:1;height:4px;background:var(--bim-border-default);border-radius:2px}.section-box-slider-range{position:absolute;top:0;height:100%;background:var(--bim-primary);border-radius:2px;pointer-events:none}.section-box-slider-handle{position:absolute;top:50%;width:14px;height:14px;background:var(--bim-bg-elevated);border:2px solid var(--bim-primary);border-radius:50%;transform:translate(-50%,-50%);cursor:grab;z-index:5;touch-action:none;transition:transform .2s,box-shadow .2s}.section-box-slider-handle:hover{transform:translate(-50%,-50%) scale(1.2);box-shadow:0 0 0 4px var(--bim-primary-subtle)}.section-box-slider-handle.dragging{cursor:grabbing;transform:translate(-50%,-50%) scale(1.2);background:var(--bim-primary)}.walk-control-panel{display:flex;align-items:center;gap:20px;padding:12px 20px;background-color:var(--bim-bg-base, #152232);border:1px solid var(--bim-border-strong, #475569);border-radius:12px;box-shadow:var(--bim-shadow-xl, 0 20px 40px rgba(0, 0, 0, .3));-webkit-user-select:none;user-select:none}.walk-divider{width:1px;height:40px;background:var(--bim-divider);flex-shrink:0}.walk-control-left{display:flex;gap:8px}.walk-icon-btn{width:48px;height:48px;display:flex;align-items:center;justify-content:center;background:var(--bim-bg-inset);border:1px solid var(--bim-border-default);border-radius:8px;cursor:pointer;transition:all .2s ease;color:var(--bim-icon-default);padding:8px}.walk-icon-btn:hover{background:var(--bim-component-bg-hover);border-color:var(--bim-border-strong)}.walk-icon-btn.active{background:var(--bim-primary-subtle);border-color:var(--bim-primary);color:var(--bim-primary)}.walk-icon-btn.active svg{fill:var(--bim-primary)}.walk-icon-btn svg{width:32px;height:32px}.walk-control-settings{display:flex;align-items:center;gap:16px;flex:1}.walk-speed-control{display:flex;align-items:center;gap:12px}.walk-speed-label{color:var(--bim-text-primary);font-size:14px;white-space:nowrap}.walk-speed-group{display:flex;align-items:center;gap:8px;background:var(--bim-bg-inset);border:1px solid var(--bim-border-subtle);border-radius:6px;padding:4px}.walk-speed-btn{width:32px;height:32px;background:var(--bim-bg-elevated);border:1px solid var(--bim-border-subtle);border-radius:4px;color:var(--bim-text-primary);font-size:18px;cursor:pointer;transition:all .2s ease}.walk-speed-btn:hover{background:var(--bim-component-bg-hover);border-color:var(--bim-border-strong)}.walk-speed-btn:disabled{opacity:.5;cursor:not-allowed}.walk-speed-display{min-width:40px;text-align:center;color:var(--bim-text-primary);font-size:14px;font-weight:700}.walk-checkbox-wrapper{display:flex;align-items:center;gap:8px;cursor:pointer}.walk-checkbox{width:18px;height:18px;cursor:pointer}.walk-checkbox:disabled{opacity:.5;cursor:not-allowed}.walk-checkbox-label{color:var(--bim-text-primary);font-size:14px;white-space:nowrap}.walk-checkbox-wrapper input:disabled+.walk-checkbox-label{opacity:.5}.walk-select-wrapper{display:flex;align-items:center;gap:8px}.walk-select-label{color:var(--bim-text-primary);font-size:14px;white-space:nowrap}.walk-select{padding:6px 12px;background:var(--bim-bg-inset);border:1px solid var(--bim-border-default);border-radius:6px;color:var(--bim-text-primary);font-size:14px;cursor:pointer;min-width:120px}.walk-select option{background:var(--bim-bg-elevated);color:var(--bim-text-primary)}.walk-exit-btn{padding:10px 24px;background:var(--bim-primary);border:none;border-radius:8px;color:var(--bim-text-inverse);font-size:14px;font-weight:600;cursor:pointer;transition:all .2s ease;white-space:nowrap}.walk-exit-btn:hover{background:var(--bim-primary-hover);transform:scale(1.02)}.walk-path-panel{padding:16px;box-sizing:border-box}.walk-path-btn{border:none;border-radius:6px;cursor:pointer;font-size:14px;transition:all .2s;box-sizing:border-box}.walk-path-btn-group{display:flex;gap:8px;margin-top:16px}.walk-path-btn-play{flex:1;height:32px;padding:0 16px;background:var(--bim-primary, #3b82f6);color:#fff}.walk-path-btn-play:hover:not(:disabled){opacity:.9}.walk-path-btn-play:disabled{opacity:.5;cursor:not-allowed}.walk-path-btn-stop{flex:1;height:32px;padding:0 16px;background:#ef4444;color:#fff}.walk-path-btn-stop:hover:not(:disabled){opacity:.9}.walk-path-btn-stop:disabled{opacity:.5;cursor:not-allowed}.walk-path-btn-small{height:28px;padding:0 12px;font-size:12px;background:var(--bim-bg-elevated, #1f2d3e);color:var(--bim-text-primary, #fff);border:1px solid var(--bim-border-default, #334155)}.walk-path-btn-small:hover{background:var(--bim-border-default, #334155)}.walk-path-btn-danger{color:#ef4444}.walk-path-settings{display:flex;flex-direction:column;gap:12px;margin-bottom:16px}.walk-path-form-group{display:flex;flex-direction:column;gap:6px}.walk-path-form-group label{font-size:12px;color:var(--bim-text-secondary, #94a3b8)}.walk-path-form-group-inline{flex-direction:row;align-items:center}.walk-path-input{padding:8px 12px;border:1px solid var(--bim-border-default, #334155);border-radius:4px;background:var(--bim-bg-elevated, #1f2d3e);color:var(--bim-text-primary, #fff);font-size:14px;width:100%;box-sizing:border-box}.walk-path-input:focus{outline:none;border-color:var(--bim-primary, #3b82f6)}.walk-path-input-wrapper{display:flex;align-items:center;gap:8px}.walk-path-input-wrapper .walk-path-input{flex:1}.walk-path-unit{color:var(--bim-text-secondary, #94a3b8);font-size:14px}.walk-path-checkbox{width:16px;height:16px;margin-right:8px}.walk-path-points-section{margin-bottom:16px}.walk-path-points-toolbar{display:flex;gap:8px;margin-bottom:12px}.walk-path-points-list{height:200px;overflow-y:auto;display:flex;flex-direction:column;gap:8px}.walk-path-empty{text-align:center;padding:32px 16px;color:var(--bim-text-secondary, #94a3b8);font-size:14px}.walk-path-point-item{display:flex;justify-content:space-between;align-items:center;padding:6px 12px;background:var(--bim-bg-elevated, #1f2d3e);border-radius:4px;transition:all .2s}.walk-path-point-item:hover{background:var(--bim-border-default, #334155)}.walk-path-point-item:hover .walk-path-point-actions{opacity:1}.walk-path-point-item-active{background:var(--bim-primary, #3b82f6)}.walk-path-point-item-active .walk-path-point-name{color:#fff}.walk-path-point-item-active .walk-path-point-actions{opacity:1}.walk-path-point-name{font-size:14px;color:var(--bim-text-primary, #fff)}.walk-path-point-actions{display:flex;gap:8px;opacity:0;transition:opacity .2s}.walk-path-btn-icon{width:28px;height:28px;border:none;border-radius:4px;background:transparent;color:var(--bim-text-primary, #fff);cursor:pointer;display:flex;align-items:center;justify-content:center;font-size:14px}.walk-path-btn-icon:hover{background:#ffffff1a}.walk-path-btn-icon-danger:hover{background:#ef444433;color:#ef4444}.bim-collapse{background-color:var(--bim-bg-elevated);border:1px solid var(--bim-border-default);border-radius:8px;font-size:14px;color:var(--bim-text-primary)}.bim-collapse.is-ghost{background-color:transparent;border:none}.bim-collapse.is-ghost .bim-collapse-item{border-bottom:none}.bim-collapse.is-ghost .bim-collapse-header{background-color:var(--bim-component-bg);padding-left:12px;padding-right:0;border-bottom:1px solid var(--bim-border-default)}.bim-collapse.is-ghost .bim-collapse-header:hover{background-color:var(--bim-component-bg-hover)}.bim-collapse.is-ghost .bim-collapse-content{background-color:transparent;border-top:none}.bim-collapse-item{border-bottom:1px solid var(--bim-border-subtle)}.bim-collapse-item:last-child{border-bottom:none}.bim-collapse-item.is-disabled .bim-collapse-header{color:var(--bim-text-disabled);cursor:not-allowed}.bim-collapse-header{display:flex;align-items:center;padding:12px 16px;background-color:var(--bim-component-bg);cursor:pointer;transition:all .2s ease;position:relative}.bim-collapse-header:hover{background-color:var(--bim-component-bg-hover)}.bim-collapse-arrow{margin-right:12px;font-size:12px;width:12px;height:12px;transition:transform .24s;display:inline-flex;align-items:center;justify-content:center}.bim-collapse-arrow svg{width:100%;height:100%;fill:currentColor}.bim-collapse-item.is-active .bim-collapse-arrow{transform:rotate(90deg)}.bim-collapse-icon{margin-right:8px;display:inline-flex;align-items:center}.bim-collapse-icon svg{width:16px;height:16px;fill:currentColor}.bim-collapse-title{flex:1;overflow:hidden;white-space:nowrap;text-overflow:ellipsis}.bim-collapse-extra{margin-left:auto}.bim-collapse-content{overflow:hidden;background-color:var(--bim-bg-elevated);border-top:1px solid var(--bim-border-subtle);transition:height .2s ease-in-out,opacity .2s ease-in-out}.bim-collapse-content.is-hidden{display:none}.bim-ai-chat{position:absolute;width:440px;height:600px;display:flex;flex-direction:column;background:var(--bim-ai-panel, rgba(11, 18, 32, .95));border:1px solid var(--bim-ai-border, rgba(255, 255, 255, .1));border-radius:16px;backdrop-filter:blur(18px);-webkit-backdrop-filter:blur(18px);box-shadow:0 12px 32px var(--bim-ai-shadow, rgba(0, 0, 0, .4));z-index:1000;font-family:Public Sans,-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,sans-serif;overflow:hidden;resize:both;min-width:360px;min-height:400px;max-width:90vw;max-height:90vh}.bim-ai-chat-header{display:flex;align-items:center;justify-content:space-between;height:56px;padding:12px 16px;border-bottom:1px solid var(--bim-ai-border, rgba(255, 255, 255, .1));flex-shrink:0;cursor:move;-webkit-user-select:none;user-select:none;border-radius:16px 16px 0 0}.bim-ai-chat-title{font-size:18px;font-weight:600;color:var(--bim-ai-text, #E5E7EB)}.bim-ai-chat-actions{display:flex;gap:8px}.bim-ai-chat-action-btn{width:32px;height:32px;border-radius:999px;border:1px solid var(--bim-ai-border, rgba(255, 255, 255, .1));background:transparent;color:var(--bim-ai-text, #E5E7EB);cursor:pointer;display:flex;align-items:center;justify-content:center;transition:all .2s ease}.bim-ai-chat-action-btn:hover{background:var(--bim-ai-subtle-fill, rgba(255, 255, 255, .05))}.bim-ai-chat-action-btn svg{width:18px;height:18px}.bim-ai-chat-messages{flex:1;overflow-y:auto;padding:12px;display:flex;flex-direction:column;gap:10px}.bim-ai-msg-ai{max-width:320px}.bim-ai-msg-ai .bim-ai-bubble{background:var(--bim-ai-panel2, rgba(15, 23, 42, .95));border:1px solid var(--bim-ai-border, rgba(255, 255, 255, .1));border-radius:16px;padding:10px}.bim-ai-msg-ai .bim-ai-bubble-content{font-size:13px;line-height:1.4;color:var(--bim-ai-text, #E5E7EB)}.bim-ai-msg-user{display:flex;justify-content:flex-end}.bim-ai-msg-user .bim-ai-bubble{max-width:300px;background:var(--bim-ai-user-bubble, rgba(29, 78, 216, .8));border-radius:16px;padding:10px;box-shadow:0 10px 26px #0003}.bim-ai-msg-user .bim-ai-bubble-content{font-size:13px;line-height:1.4;color:var(--bim-ai-user-text, #EEF2FF)}.bim-ai-step{display:flex;align-items:center;gap:10px;padding:10px;border-radius:14px;max-width:380px}.bim-ai-step-running{background:var(--bim-ai-info-soft, rgba(56, 189, 248, .1));border:1px solid rgba(56,189,248,.33)}.bim-ai-step-done{background:var(--bim-ai-success-soft, rgba(52, 211, 153, .1));border:1px solid rgba(52,211,153,.33)}.bim-ai-step-error{background:var(--bim-ai-danger-soft, rgba(239, 68, 68, .1));border:1px solid var(--bim-ai-danger-stroke, rgba(239, 68, 68, .33))}.bim-ai-step-icon{width:16px;height:16px;flex-shrink:0}.bim-ai-step-running .bim-ai-step-icon{color:var(--bim-ai-info, #38BDF8)}.bim-ai-step-done .bim-ai-step-icon{color:var(--bim-ai-success, #34D399)}.bim-ai-step-error .bim-ai-step-icon{color:var(--bim-ai-danger, #EF4444)}.bim-ai-step-text{font-size:12px;line-height:1.4;color:var(--bim-ai-text, #E5E7EB)}.bim-ai-thinking{display:flex;align-items:center;gap:10px;padding:10px;border-radius:14px;background:var(--bim-ai-panel2, rgba(15, 23, 42, .95));border:1px solid var(--bim-ai-border, rgba(255, 255, 255, .1));max-width:380px}.bim-ai-thinking-icon{width:16px;height:16px;color:var(--bim-ai-muted, #94A3B8);animation:bim-ai-spin 1s linear infinite}.bim-ai-thinking-text{font-size:12px;font-weight:600;color:var(--bim-ai-muted, #94A3B8)}@keyframes bim-ai-spin{0%{transform:rotate(0)}to{transform:rotate(360deg)}}.bim-ai-question-active{width:360px;border-radius:14px;background:var(--bim-ai-panel2, rgba(15, 23, 42, .95));border:1px solid var(--bim-ai-accent-stroke, rgba(59, 130, 246, .33));box-shadow:0 4px 16px var(--bim-ai-shadow, rgba(0, 0, 0, .4));overflow:hidden}.bim-ai-question-header{display:flex;align-items:center;gap:8px;padding:12px;border-bottom:1px solid var(--bim-ai-border, rgba(255, 255, 255, .1))}.bim-ai-question-icon{width:24px;height:24px;border-radius:6px;background:var(--bim-ai-accent-soft, rgba(59, 130, 246, .1));display:flex;align-items:center;justify-content:center;color:var(--bim-ai-accent, #3B82F6)}.bim-ai-question-icon svg{width:14px;height:14px}.bim-ai-question-title{font-size:13px;font-weight:600;color:var(--bim-ai-text, #E5E7EB)}.bim-ai-question-content{padding:12px;display:flex;flex-direction:column;gap:10px}.bim-ai-question-text{font-size:13px;line-height:1.4;color:var(--bim-ai-text, #E5E7EB)}.bim-ai-question-options{display:flex;flex-direction:column;gap:6px}.bim-ai-option{display:flex;align-items:center;gap:8px;padding:8px 10px;border-radius:8px;background:var(--bim-ai-subtle-fill, rgba(255, 255, 255, .05));border:1px solid var(--bim-ai-border, rgba(255, 255, 255, .1));cursor:pointer;transition:all .2s ease}.bim-ai-option:hover{background:var(--bim-ai-subtle-fill-hover, rgba(255, 255, 255, .08))}.bim-ai-option.selected{background:var(--bim-ai-accent-soft, rgba(59, 130, 246, .1));border-color:var(--bim-ai-accent-stroke, rgba(59, 130, 246, .33))}.bim-ai-option-radio{width:16px;height:16px;border-radius:50%;border:1.5px solid var(--bim-ai-muted, #94A3B8);flex-shrink:0;display:flex;align-items:center;justify-content:center}.bim-ai-option.selected .bim-ai-option-radio{background:var(--bim-ai-accent, #3B82F6);border-color:var(--bim-ai-accent, #3B82F6)}.bim-ai-option-radio-dot{width:6px;height:6px;border-radius:50%;background:var(--bim-ai-accent-ink, #FFFFFF);display:none}.bim-ai-option.selected .bim-ai-option-radio-dot{display:block}.bim-ai-option-text{font-size:12px;color:var(--bim-ai-text, #E5E7EB)}.bim-ai-option-input{flex:1;background:var(--bim-ai-textbox-fill, rgba(15, 23, 42, .6));border:1px solid var(--bim-ai-border, rgba(255, 255, 255, .1));border-radius:6px;padding:6px 8px;font-size:12px;color:var(--bim-ai-text, #E5E7EB);outline:none;margin-top:8px;width:100%}.bim-ai-option-input:focus{border-color:var(--bim-ai-accent-stroke, rgba(59, 130, 246, .33))}.bim-ai-question-footer{display:flex;justify-content:flex-end;padding:12px;border-top:1px solid var(--bim-ai-border, rgba(255, 255, 255, .1))}.bim-ai-question-submit{display:flex;align-items:center;gap:4px;padding:8px 12px;border-radius:8px;background:var(--bim-ai-accent, #3B82F6);color:var(--bim-ai-accent-ink, #FFFFFF);border:none;cursor:pointer;font-size:12px;font-weight:600;transition:all .2s ease}.bim-ai-question-submit:hover{filter:brightness(1.1)}.bim-ai-question-submit svg{width:12px;height:12px}.bim-ai-question-answered{max-width:340px;padding:10px;border-radius:12px;background:var(--bim-ai-panel2, rgba(15, 23, 42, .95));border:1px solid var(--bim-ai-border, rgba(255, 255, 255, .1));display:flex;flex-direction:column;gap:8px}.bim-ai-qa-row{display:flex;gap:8px;align-items:flex-start}.bim-ai-qa-badge{width:18px;height:18px;border-radius:5px;display:flex;align-items:center;justify-content:center;font-size:10px;font-weight:700;flex-shrink:0}.bim-ai-qa-badge-q{background:var(--bim-ai-accent-soft, rgba(59, 130, 246, .1));color:var(--bim-ai-accent, #3B82F6)}.bim-ai-qa-badge-a{background:var(--bim-ai-success-soft, rgba(52, 211, 153, .1));color:var(--bim-ai-success, #34D399)}.bim-ai-qa-question{font-size:12px;line-height:1.4;color:var(--bim-ai-muted, #94A3B8)}.bim-ai-qa-answer{font-size:12px;line-height:1.4;color:var(--bim-ai-text, #E5E7EB)}.bim-ai-chat-composer{padding:12px;border-top:1px solid var(--bim-ai-border, rgba(255, 255, 255, .1));display:flex;flex-direction:column;gap:8px;flex-shrink:0}.bim-ai-quick-prompts{display:flex;gap:8px;flex-wrap:wrap}.bim-ai-quick-prompt{padding:5px 8px;border-radius:999px;background:var(--bim-ai-subtle-fill, rgba(255, 255, 255, .05));border:1px solid var(--bim-ai-border, rgba(255, 255, 255, .1));color:var(--bim-ai-text, #E5E7EB);font-size:12px;font-weight:600;cursor:pointer;transition:all .2s ease}.bim-ai-quick-prompt:hover{background:var(--bim-ai-subtle-fill-hover, rgba(255, 255, 255, .08))}.bim-ai-input-row{display:flex;gap:8px;align-items:flex-end}.bim-ai-textbox{flex:1;display:flex;flex-direction:column;gap:6px;padding:10px;border-radius:16px;background:var(--bim-ai-textbox-fill, rgba(15, 23, 42, .6));border:1px solid var(--bim-ai-border, rgba(255, 255, 255, .1))}.bim-ai-textbox:focus-within{border-color:var(--bim-ai-accent-stroke, rgba(59, 130, 246, .33))}.bim-ai-textarea{background:transparent;border:none;outline:none;resize:none;font-size:13px;line-height:1.4;color:var(--bim-ai-text, #E5E7EB);min-height:20px;max-height:100px}.bim-ai-textarea::placeholder{color:var(--bim-ai-muted, #94A3B8)}.bim-ai-helper{display:flex;justify-content:space-between;font-size:11px;color:var(--bim-ai-muted, #94A3B8)}.bim-ai-send-btn{width:40px;height:40px;border-radius:14px;background:var(--bim-ai-accent, #3B82F6);border:none;cursor:pointer;display:flex;align-items:center;justify-content:center;color:var(--bim-ai-accent-ink, #FFFFFF);transition:background .2s ease;flex-shrink:0}.bim-ai-send-btn:hover{background:var(--bim-ai-accent-hover, #2563EB)}.bim-ai-send-btn svg{width:18px;height:18px}.bim-ai-chat.light{--bim-ai-panel: rgba(255, 255, 255, .95);--bim-ai-panel2: #FFFFFF;--bim-ai-border: rgba(15, 23, 42, .1);--bim-ai-text: #0F172A;--bim-ai-muted: #475569;--bim-ai-shadow: rgba(11, 18, 32, .1);--bim-ai-subtle-fill: rgba(15, 23, 42, .05);--bim-ai-subtle-fill-hover: rgba(15, 23, 42, .08);--bim-ai-textbox-fill: #F1F5F9;--bim-ai-user-bubble: #2563EB;--bim-ai-user-text: #FFFFFF;--bim-ai-accent: #2563EB;--bim-ai-accent-soft: rgba(37, 99, 235, .08);--bim-ai-accent-stroke: rgba(37, 99, 235, .2);--bim-ai-success: #059669;--bim-ai-success-soft: rgba(5, 150, 105, .08);--bim-ai-danger: #DC2626;--bim-ai-danger-soft: rgba(220, 38, 38, .08);--bim-ai-danger-stroke: rgba(220, 38, 38, .2);--bim-ai-info: #0284C7;--bim-ai-info-soft: rgba(2, 132, 199, .08)}.radial-toolbar-wrapper{position:absolute;right:20px;bottom:20px;z-index:1000;pointer-events:none}.radial-main-btn,.radial-sub-btn{border:1px solid transparent;border-radius:9999px;display:flex;align-items:center;justify-content:center;cursor:pointer;pointer-events:auto;outline:none;transition:transform .22s ease,opacity .22s ease,box-shadow .22s ease,background-color .22s ease,color .22s ease}.radial-main-btn{position:absolute;right:0;bottom:0;width:var(--rt-main-size, 70px);height:var(--rt-main-size, 70px);background:var(--rt-main-bg, rgba(255, 255, 255, .92));border-color:var(--rt-main-border, rgba(203, 213, 225, .65));box-shadow:var(--rt-main-shadow, 0 4px 12px rgba(0, 0, 0, .12));color:var(--rt-main-icon, #334155)}.radial-main-btn:hover{transform:translateZ(0) scale(1.04);background:var(--rt-main-bg-hover, #ffffff);box-shadow:var(--rt-main-shadow-hover, 0 6px 20px rgba(0, 0, 0, .14));color:var(--rt-main-icon-hover, #1e293b)}.radial-main-btn:active{transform:translateZ(0) scale(.97)}.radial-main-btn svg{width:34px;height:34px}.radial-sub-btn{position:absolute;right:var(--rt-main-offset, 10px);bottom:var(--rt-main-offset, 10px);width:var(--rt-sub-size, 50px);height:var(--rt-sub-size, 50px);background:var(--rt-sub-bg, rgba(255, 255, 255, .9));border-color:var(--rt-sub-border, rgba(203, 213, 225, .65));box-shadow:var(--rt-sub-shadow, 0 2px 8px rgba(0, 0, 0, .1));color:var(--rt-sub-icon, #334155);opacity:0;transform:translate(0) scale(.76);transform-origin:center;--rt-delay-current: var(--rt-close-delay, 0s);transition-delay:var(--rt-delay-current)}.radial-toolbar-wrapper.is-active .radial-sub-btn{--rt-delay-current: var(--rt-open-delay, 0s);opacity:1;transform:translate(var(--rt-x),var(--rt-y)) scale(1)}.radial-sub-btn:hover{background:var(--rt-sub-bg-hover, var(--bim-primary, #2563eb));box-shadow:var(--rt-sub-shadow-hover, 0 4px 14px rgba(0, 0, 0, .16));color:var(--rt-sub-icon-hover, var(--bim-text-inverse, #ffffff))}.radial-sub-btn.is-active,.radial-sub-btn[data-active=true]{background:var(--bim-primary, #2563eb);border:1px solid var(--bim-primary-active, #1d4ed8);box-shadow:var(--bim-shadow-glow, 0 0 0 2px rgba(37, 99, 235, .28));color:var(--bim-text-inverse, #ffffff)}.radial-sub-btn.is-active:hover,.radial-sub-btn[data-active=true]:hover{background:var(--bim-primary-hover, #3b82f6)}.radial-sub-btn.is-active .radial-sub-btn-icon,.radial-sub-btn[data-active=true] .radial-sub-btn-icon{color:var(--bim-icon-inverse, #ffffff)}.radial-sub-btn:active{transform:translate(var(--rt-x),var(--rt-y)) scale(.94)}.radial-sub-btn-icon{width:22px;height:22px;display:flex;align-items:center;justify-content:center}.radial-sub-btn-icon svg{width:100%;height:100%}.bottom-dock-stack{position:absolute;left:50%;bottom:20px;transform:translate(-50%);width:0;height:0;z-index:1000;pointer-events:none}.bottom-dock-panel{position:absolute;left:50%;bottom:0;transform:translate(-50%);width:fit-content;max-width:calc(100vw - 40px);pointer-events:auto;border-radius:12px;border:1px solid var(--bd-border, rgba(148, 163, 184, .35));background:var(--bd-bg, rgba(255, 255, 255, .94));box-shadow:var(--bd-shadow, 0 2px 8px rgba(15, 23, 42, .1));transition:transform .22s ease,opacity .2s ease;overflow:visible}.bottom-dock-panel.is-entering{opacity:0}.bottom-dock-panel.is-leaving{opacity:0;pointer-events:none}.bottom-dock-panel-close{position:absolute;top:5px;right:5px;transform:translate(35%,-35%);z-index:2;width:16px;height:16px;border-radius:6px;border:1px solid transparent;background:transparent;color:var(--bd-close-color, #475569);display:inline-flex;align-items:center;justify-content:center;cursor:pointer;transition:background-color .16s ease,color .16s ease,border-color .16s ease}.bottom-dock-panel-close:hover{background:var(--bd-close-bg-hover, rgba(15, 23, 42, .08));color:var(--bd-close-color-hover, #0f172a);border-color:var(--bd-close-border-hover, rgba(148, 163, 184, .3))}.bottom-dock-panel-close:active{transform:translate(35%,-35%) scale(.96)}.bottom-dock-panel-body{min-height:50px;padding:10px;background:var(--bd-body-bg, transparent);width:fit-content;max-width:calc(100vw - 40px);box-sizing:border-box;border-radius:inherit}.bottom-dock-placeholder{border-radius:8px;border:1px dashed var(--bd-placeholder-border, rgba(148, 163, 184, .55));padding:10px;color:var(--bd-placeholder-text, #64748b);font-size:12px;line-height:1.5;text-align:center}.measure-dock-panel{width:fit-content;max-width:100%;padding:0;border-radius:8px;border:none;background:color-mix(in srgb,var(--bim-bg-elevated, #e8ecf2) 92%,#ffffff 8%);box-sizing:border-box;color:var(--bim-text-secondary, #475569);font-size:13px;line-height:1.5}.measure-dock-panel-main{display:block}.measure-dock-panel-settings{display:none;flex-direction:column;gap:6px;min-height:74px;box-sizing:border-box}.measure-dock-settings-row{display:flex;align-items:center;justify-content:space-between;gap:8px}.measure-dock-settings-label{color:var(--bim-text-secondary, #64748b);font-size:12px}.measure-dock-settings-select{width:88px;height:24px;border-radius:6px;border:1px solid rgba(148,163,184,.36);background:color-mix(in srgb,var(--bim-bg-inset, #edf1f6) 90%,#ffffff 10%);color:var(--bim-text-primary, #0f172a);font-size:12px;padding:0 6px;box-sizing:border-box}.measure-dock-settings-actions{display:flex;justify-content:flex-end;gap:8px}.measure-dock-settings-btn{height:24px;min-width:52px;border-radius:6px;border:1px solid rgba(148,163,184,.36);background:color-mix(in srgb,var(--bim-bg-inset, #edf1f6) 90%,#ffffff 10%);color:var(--bim-text-secondary, #64748b);font-size:12px;line-height:1;cursor:pointer}.measure-dock-settings-btn.is-save{border-color:color-mix(in srgb,var(--bim-primary, #4f88ff) 46%,transparent 54%);color:color-mix(in srgb,var(--bim-primary, #4f88ff) 78%,#6f9dff 22%)}.measure-dock-panel-top{display:flex;align-items:center;justify-content:space-between;gap:10px}.measure-dock-clearheight-options{display:none;flex-direction:column;gap:8px;margin-bottom:10px;padding:8px;border-radius:8px;border:1px solid rgba(148,163,184,.28);background:color-mix(in srgb,var(--bim-bg-inset, #edf1f6) 90%,#ffffff 10%)}.measure-dock-clearheight-options.is-visible{display:flex}.measure-dock-clearheight-group{display:flex;align-items:center;gap:8px}.measure-dock-clearheight-label{min-width:60px;color:var(--bim-text-secondary, #64748b);font-size:12px}.measure-dock-clearheight-buttons{display:flex;gap:8px}.measure-dock-clearheight-btn{height:28px;padding:0 10px;border-radius:6px;border:1px solid rgba(148,163,184,.36);background:color-mix(in srgb,var(--bim-bg-elevated, #f8fafc) 88%,#ffffff 12%);color:var(--bim-text-secondary, #64748b);font-size:12px;line-height:1;cursor:pointer;transition:all .15s ease}.measure-dock-clearheight-btn:hover{border-color:#94a3b88f}.measure-dock-clearheight-btn.is-active{border-color:color-mix(in srgb,var(--bim-primary, #4f88ff) 70%,#9db9ff 30%);background:color-mix(in srgb,var(--bim-primary-subtle, rgba(96, 140, 255, .18)) 72%,#ffffff 28%);color:color-mix(in srgb,var(--bim-primary, #4f88ff) 78%,#6f9dff 22%)}.measure-dock-panel-mode-zone{flex:1;min-width:0;display:flex;flex-direction:column;gap:10px}.measure-dock-panel-mode-row{display:grid;grid-template-columns:repeat(5,32px);gap:10px}.measure-dock-panel-mode-row-secondary{display:none}.measure-dock-panel-mode-btn{width:32px;height:32px;border-radius:8px;border:1px solid rgba(148,163,184,.28);background:color-mix(in srgb,var(--bim-bg-inset, #edf1f6) 92%,#ffffff 8%);color:color-mix(in srgb,var(--bim-text-secondary, #64748b) 94%,#475569 6%);display:inline-flex;align-items:center;justify-content:center;padding:0;box-sizing:border-box;cursor:pointer;transition:all .15s ease}.measure-dock-panel-mode-icon{width:20px;height:20px;display:inline-flex;align-items:center;justify-content:center}.measure-dock-panel-mode-icon svg{width:100%;height:100%;fill:currentColor}.measure-dock-panel-mode-btn:hover{border-color:#94a3b880;background:color-mix(in srgb,var(--bim-component-bg-hover, #dce5f2) 64%,#ffffff 36%)}.measure-dock-panel-mode-btn.is-active{border-color:color-mix(in srgb,var(--bim-primary, #4f88ff) 70%,#9db9ff 30%);background:color-mix(in srgb,var(--bim-primary-subtle, rgba(96, 140, 255, .18)) 72%,#ffffff 28%);color:color-mix(in srgb,var(--bim-primary, #4f88ff) 78%,#6f9dff 22%);box-shadow:inset 0 0 0 1px color-mix(in srgb,var(--bim-primary, #4f88ff) 35%,transparent 65%)}.measure-dock-panel-actions{flex:0 0 auto;display:flex;flex-direction:row;gap:10px;align-items:center}.measure-dock-panel-action-btn{width:32px;height:32px;border-radius:6px;border:1px solid rgba(148,163,184,.22);background:color-mix(in srgb,var(--bim-bg-inset, #edf1f6) 92%,#ffffff 8%);color:var(--bim-text-secondary, #475569);padding:0;box-sizing:border-box;display:inline-flex;align-items:center;justify-content:center;cursor:pointer;transition:all .15s ease}.measure-dock-panel-action-btn:hover{border-color:#94a3b880;color:var(--bim-text-primary, #0f172a)}.measure-dock-panel-action-btn svg{width:18px;height:18px;fill:currentColor}.measure-dock-panel-action-expand{width:16px;height:32px}.measure-dock-panel-action-expand.is-expanded{height:74px}.measure-dock-panel-action-expand.is-collapsed{height:32px}.measure-dock-panel-action-clear{background:color-mix(in srgb,var(--bim-danger, #ef4444) 16%,#ffffff 84%);border-color:color-mix(in srgb,var(--bim-danger, #ef4444) 26%,transparent 74%);color:var(--bim-danger, #ef4444)}.measure-dock-panel-action-clear:hover{border-color:color-mix(in srgb,var(--bim-danger, #ef4444) 40%,transparent 60%);color:var(--bim-danger, #ef4444)}.measure-dock-panel-action-settings{color:color-mix(in srgb,var(--bim-text-primary, #0f172a) 86%,#000 14%)}.measure-dock-panel-mode-row .measure-dock-panel-action-btn{border-radius:8px}.measure-dock-panel-action-expand svg{transition:transform .15s ease}.measure-dock-panel-action-expand.is-expanded svg{transform:rotate(180deg)}.measure-dock-panel [data-tooltip]{position:relative}.measure-dock-panel [data-tooltip]:after{content:attr(data-tooltip);position:absolute;left:50%;bottom:calc(100% + 6px);transform:translate(-50%);padding:4px 8px;border-radius:6px;background:#0f172aeb;color:#f8fafc;font-size:12px;line-height:1.2;white-space:nowrap;pointer-events:none;opacity:0;visibility:hidden;z-index:8;transition:opacity 60ms ease}.measure-dock-panel [data-tooltip]:hover:after,.measure-dock-panel [data-tooltip]:focus-visible:after{opacity:1;visibility:visible}@media(max-width:720px){.measure-dock-panel-top{flex-direction:column}.measure-dock-clearheight-group{flex-direction:column;align-items:flex-start;gap:6px}.measure-dock-panel-actions{width:100%;flex-direction:row;justify-content:flex-end}.measure-dock-panel-action-btn,.measure-dock-panel-mode-btn{width:32px;height:32px}.measure-dock-panel-action-expand{width:16px;height:32px}.measure-dock-panel-action-expand.is-expanded{height:74px}}')),document.head.appendChild(e)}}catch(o){console.error("vite-plugin-css-injected-by-js",o)}})(); (function(Is,gc){typeof exports=="object"&&typeof module<"u"?gc(exports,require("opentype.js")):typeof define=="function"&&define.amd?define(["exports","opentype.js"],gc):(Is=typeof globalThis<"u"?globalThis:Is||self,gc(Is.IflowEngine={},Is["{}"]))})(this,(function(Is,gc){"use strict";function X2(s){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(s){for(const t in s)if(t!=="default"){const i=Object.getOwnPropertyDescriptor(s,t);Object.defineProperty(e,t,i.get?i:{enumerable:!0,get:()=>s[t]})}}return e.default=s,Object.freeze(e)}const j2=X2(gc),q2={common:{title:"BimEngine",description:"这是一个使用 BIM-ENGINE。",openTestDialog:"打开测试弹窗",openInfoDialog:"打开信息弹窗 (封装版)"},toolbar:{home:"首页",measure:"测量",zoomBox:"选框放大",info:"信息",location:"定位",setting:"设置",walk:"漫游",map:"地图",property:"构件详情",fullscreen:"全屏",walkMenu:"漫游菜单",walkPerson:"第一人称",walkBird:"第三人称",tree:"模型树",section:"剖切",sectionPlane:"拾取面剖切",sectionAxis:"轴向剖切",sectionBox:"剖切盒",cameraSwitch:"相机切换"},dialog:{testTitle:"测试弹窗",testContent:'
这是一个 可拖拽可缩放 的弹窗。

你可以尝试拖动标题栏,或者拖动右下角改变大小。
'},menu:{info:"信息",home:"首页",componentDetail:"构件详情",hideSelected:"隐藏选中构件",transparentSelected:"半透明选中构件",cancelTranslucent:"取消半透明",isolateSelected:"隔离选中构件",hideOthers:"其他构件隐藏",transparentOthers:"其他构件半透明",fitSectionBox:"剖切盒适应",showAll:"显示全部",quickSelect:"快速选择",selectSameType:"选择同类模型",selectSameLevel:"选择同层模型",selectSameLevelType:"选择同层同类模型"},tree:{searchPlaceholder:"请输入要搜索的内容"},constructTree:{title:"目录树"},tab:{component:"构件",system:"系统",space:"空间",type:"类型",major:"专业"},panel:{property:{title:"构件详情",base:"基本属性",material:"材质信息",advanced:"高级设置",tab:{props:"属性",material:"材质"}},componentDetail:{title:"构件详情",noSelection:"请先选中构件"}},measure:{btnName:"测量",dialogTitle:"测量",modes:{clearHeight:"净高",clearDistance:"净距",distance:"距离",elevation:"标高",point:"坐标",angle:"角度",area:"面积",slope:"坡度"},actions:{expand:"展开",collapse:"收起",clearAll:"删除全部",settings:"设置"},labels:{currentMode:"当前测量方式:",x:"X:",y:"Y:",z:"Z:",value:{clearHeight:"净高:",clearDistance:"净距:",distance:"距离:",elevation:"标高:",point:"坐标:",angle:"角度:",area:"面积:",slope:"坡度:"}},settings:{title:"设置",unit:"单位:",precision:"精度:",hint:"距离、净距、净高和标高默认使用该单位;角度和面积有各自默认单位。",save:"保存设置",cancel:"取消"},clearHeight:{direction:"朝向:",directionDown:"朝下",directionUp:"朝上",selectType:"选择对象:",selectPoint:"选择点",selectElement:"选择构件"}},sectionPlane:{dialogTitle:"拾取面剖切",actions:{hide:"隐藏",reverse:"反向",reset:"重置"}},sectionAxis:{dialogTitle:"轴向剖切",actions:{hide:"隐藏",reverse:"反向",axisX:"X",axisY:"Y",axisZ:"Z"}},sectionBox:{dialogTitle:"剖切盒",actions:{hide:"隐藏",reverse:"反向",fitToModel:"适应",reset:"重置"},axes:{x:"X",y:"Y",z:"Z"}},walkControl:{speed:"移动速度:",gravity:"重力",collision:"碰撞",characterModel:{label:"建筑工人",constructionWorker:"建筑工人",officeMale:"办公室男性"},walkMode:{label:"行走模式",walk:"行走模式",run:"奔跑模式"},exit:"退出",path:{dialogTitle:"路径漫游",duration:"漫游时间",durationUnit:"秒",loop:"循环播放",addPoint:"添加漫游点",deleteAll:"删除全部",point:"漫游点",play:"播放漫游",stop:"停止漫游",noPoints:"暂无漫游点,请添加"}},info:{dialogTitle:"基本信息",meshCount:"构件数量",totalTriangles:"三角面数量",totalVertices:"顶点数量"},aiChat:{title:"AI 助手",placeholder:"输入你的问题...",quickPrompt:{summarize:"总结这个模型",explain:"解释选中的构件",generate:"生成报告"},action:{new:"新建对话",history:"历史记录",settings:"设置",close:"关闭"},helper:{newline:"Shift + Enter 换行",send:"Enter 发送"},thinking:"正在思考...",other:"其他",otherPlaceholder:"请输入自定义答案",submit:"提交"},setting:{dialogTitle:"设置",presetSelect:"选择预设",presetSelectPlaceholder:"请选择预设",defaultPresetLabel:"默认预设",savePreset:"保存预设",deletePreset:"删除预设",deletePresetForbidden:"默认预设不允许删除",presetDefaultName:"预设",presetNamePrompt:"请输入预设名称",presetNameRequired:"预设名称不能为空",presetNameDuplicate:"预设名称已存在,请使用其他名称",restorePreset:"恢复预设",saveAsNewPreset:"存为新预设",selectPresetFirst:"请先选择预设",presetButton:"预设",undoChanges:"撤销修改",saveAsDialogTitle:"存为新预设",deleteDialogTitle:"删除预设",deleteDialogMessage:"确认删除当前预设吗?删除后不可恢复。",presetNamePlaceholder:"请输入预设名称",confirm:"确定",cancel:"取消",presetPickPrompt:"请输入预设序号",presetPickInvalid:"预设序号无效",renderMode:"渲染模式",modes:{simple:"性能模式",balance:"平衡模式",advanced:"效果模式"},displaySection:"显示设置",edgeLine:"边线",edgeOpacity:"边线透明度",showGrid:"显示轴网",showLevel:"显示标高",contrast:"对比度",saturation:"饱和度",lightIntensity:"光照强度",environment:"环境背景",environmentType:{none:"无",hdr:"HDR背景",sky:"天空盒"},backgroundVisible:"显示背景",ground:"显示地面",groundElevation:"地面高度",groundElevationUnit:"m"}},Z2={common:{title:"BimEngine",description:"This is a BIM-ENGINE demo.",openTestDialog:"Open Test Dialog",openInfoDialog:"Open Info Dialog (Wrapped)"},toolbar:{home:"Home",measure:"Measure",zoomBox:"Zoom Box",info:"Info",location:"Location",setting:"Settings",walk:"Walk",map:"Map",property:"Property",fullscreen:"Fullscreen",walkPerson:"Person",walkBird:"Bird Eye",walkMenu:"Menu",tree:"Tree",section:"Section",sectionPlane:"Plane Section",sectionAxis:"Axis Section",sectionBox:"Section Box",cameraSwitch:"Camera"},dialog:{testTitle:"Test Dialog",testContent:'
This is a draggable and resizable dialog.

Try dragging the title bar or resizing from the bottom-right corner.
'},menu:{info:"Info",home:"Home",componentDetail:"Component Detail",hideSelected:"Hide Selected",transparentSelected:"Transparent Selected",cancelTranslucent:"Cancel Translucent",isolateSelected:"Isolate Selected",hideOthers:"Hide Others",transparentOthers:"Transparent Others",fitSectionBox:"Fit Section Box",showAll:"Show All",quickSelect:"Quick Select",selectSameType:"Select Same Type",selectSameLevel:"Select Same Level",selectSameLevelType:"Select Same Level & Type"},tree:{searchPlaceholder:"Please enter content to search"},constructTree:{title:"Construct Tree"},tab:{component:"Component",system:"System",space:"Space",type:"Type",major:"Major"},panel:{property:{title:"Component Details",base:"Basic Info",material:"Material",advanced:"Advanced",tab:{props:"Properties",material:"Material"}},componentDetail:{title:"Component Detail",noSelection:"Please select a component first"}},measure:{btnName:"Measure",dialogTitle:"Measure",modes:{clearHeight:"Clear Height",clearDistance:"Clear Distance",distance:"Distance",elevation:"Elevation",point:"Point",angle:"Angle",area:"Area",slope:"Slope"},actions:{expand:"Expand",collapse:"Collapse",clearAll:"Clear All",settings:"Settings"},labels:{currentMode:"Mode:",x:"X:",y:"Y:",z:"Z:",value:{clearHeight:"Clear Height:",clearDistance:"Clear Distance:",distance:"Distance:",elevation:"Elevation:",point:"Point:",angle:"Angle:",area:"Area:",slope:"Slope:"}},settings:{title:"Settings",unit:"Unit:",precision:"Precision:",hint:"Distance, clear distance, clear height and elevation use this unit by default; angle and area use their own units.",save:"Save",cancel:"Cancel"},clearHeight:{direction:"Direction:",directionDown:"Down",directionUp:"Up",selectType:"Select:",selectPoint:"Point",selectElement:"Element"}},sectionPlane:{dialogTitle:"Plane Section",actions:{hide:"Hide",reverse:"Reverse",reset:"Reset"}},sectionAxis:{dialogTitle:"Axis Section",actions:{hide:"Hide",reverse:"Reverse",axisX:"X",axisY:"Y",axisZ:"Z"}},sectionBox:{dialogTitle:"Section Box",actions:{hide:"Hide",reverse:"Reverse",fitToModel:"Fit",reset:"Reset"},axes:{x:"X",y:"Y",z:"Z"}},walkControl:{speed:"Speed:",gravity:"Gravity",collision:"Collision",characterModel:{label:"Construction Worker",constructionWorker:"Construction Worker",officeMale:"Office Male"},walkMode:{label:"Walk Mode",walk:"Walk",run:"Run"},exit:"Exit",path:{dialogTitle:"Path Roaming",duration:"Duration",durationUnit:"s",loop:"Loop",addPoint:"Add Point",deleteAll:"Delete All",point:"Point",play:"Play",stop:"Stop",noPoints:"No points yet"}},info:{dialogTitle:"Basic Info",meshCount:"Mesh Count",totalTriangles:"Total Triangles",totalVertices:"Total Vertices"},aiChat:{title:"AI Assistant",placeholder:"Ask a question...",quickPrompt:{summarize:"Summarize this model",explain:"Explain selected component",generate:"Generate report"},action:{new:"New Chat",history:"History",settings:"Settings",close:"Close"},helper:{newline:"Shift + Enter for new line",send:"Enter to send"},thinking:"Thinking...",other:"Other",otherPlaceholder:"Enter custom answer",submit:"Submit"},setting:{dialogTitle:"Settings",presetSelect:"Preset",presetSelectPlaceholder:"Select preset",defaultPresetLabel:"Default Preset",savePreset:"Save Preset",deletePreset:"Delete",deletePresetForbidden:"Default preset cannot be deleted",presetDefaultName:"Preset",presetNamePrompt:"Enter preset name",presetNameRequired:"Preset name is required",presetNameDuplicate:"Preset name already exists",restorePreset:"Restore Preset",saveAsNewPreset:"Save As Preset",selectPresetFirst:"Please select a preset first",presetButton:"Preset",undoChanges:"Undo Changes",saveAsDialogTitle:"Save As Preset",deleteDialogTitle:"Delete Preset",deleteDialogMessage:"Delete current preset? This action cannot be undone.",presetNamePlaceholder:"Enter preset name",confirm:"Confirm",cancel:"Cancel",presetPickPrompt:"Please input preset number",presetPickInvalid:"Invalid preset number",renderMode:"Render Mode",modes:{simple:"Performance",balance:"Balanced",advanced:"Quality"},displaySection:"Display",edgeLine:"Edge Lines",edgeOpacity:"Edge Opacity",showGrid:"Show Grid",showLevel:"Show Level",contrast:"Contrast",saturation:"Saturation",lightIntensity:"Light Intensity",environment:"Environment",environmentType:{none:"None",hdr:"HDR",sky:"Sky"},backgroundVisible:"Show Background",ground:"Ground",groundElevation:"Ground Elevation",groundElevationUnit:"m"}},Y2={common:{title:"BimEngine",description:"這是一個使用 BIM-ENGINE。",openTestDialog:"打開測試彈窗",openInfoDialog:"打開資訊彈窗 (封裝版)"},toolbar:{home:"首頁",measure:"測量",zoomBox:"選框放大",info:"資訊",location:"定位",setting:"設定",walk:"漫遊",map:"地圖",property:"構件詳情",fullscreen:"全屏",walkMenu:"漫遊選單",walkPerson:"第一人稱",walkBird:"第三人稱",tree:"模型樹",section:"剖切",sectionPlane:"拾取面剖切",sectionAxis:"軸向剖切",sectionBox:"剖切盒",cameraSwitch:"相機切換"},dialog:{testTitle:"測試彈窗",testContent:'
這是一個 可拖曳可縮放 的彈窗。

你可以嘗試拖動標題欄,或者拖動右下角改變大小。
'},menu:{info:"資訊",home:"首頁",componentDetail:"構件詳情",hideSelected:"隱藏選中構件",transparentSelected:"半透明選中構件",cancelTranslucent:"取消半透明",isolateSelected:"隔離選中構件",hideOthers:"其他構件隱藏",transparentOthers:"其他構件半透明",fitSectionBox:"剖切盒適應",showAll:"顯示全部",quickSelect:"快速選擇",selectSameType:"選擇同類模型",selectSameLevel:"選擇同層模型",selectSameLevelType:"選擇同層同類模型"},tree:{searchPlaceholder:"請輸入要搜尋的內容"},constructTree:{title:"目錄樹"},tab:{component:"構件",system:"系統",space:"空間",type:"類型",major:"專業"},panel:{property:{title:"構件詳情",base:"基本屬性",material:"材質資訊",advanced:"進階設定",tab:{props:"屬性",material:"材質"}},componentDetail:{title:"構件詳情",noSelection:"請先選中構件"}},measure:{btnName:"測量",dialogTitle:"測量",modes:{clearHeight:"淨高",clearDistance:"淨距",distance:"距離",elevation:"標高",point:"座標",angle:"角度",area:"面積",slope:"坡度"},actions:{expand:"展開",collapse:"收起",clearAll:"刪除全部",settings:"設定"},labels:{currentMode:"當前測量方式:",x:"X:",y:"Y:",z:"Z:",value:{clearHeight:"淨高:",clearDistance:"淨距:",distance:"距離:",elevation:"標高:",point:"座標:",angle:"角度:",area:"面積:",slope:"坡度:"}},settings:{title:"設定",unit:"單位:",precision:"精度:",hint:"距離、淨距、淨高和標高預設使用該單位;角度和面積有各自預設單位。",save:"儲存設定",cancel:"取消"},clearHeight:{direction:"朝向:",directionDown:"朝下",directionUp:"朝上",selectType:"選擇對象:",selectPoint:"選擇點",selectElement:"選擇構件"}},sectionPlane:{dialogTitle:"拾取面剖切",actions:{hide:"隱藏",reverse:"反向",reset:"重設"}},sectionAxis:{dialogTitle:"軸向剖切",actions:{hide:"隱藏",reverse:"反向",axisX:"X",axisY:"Y",axisZ:"Z"}},sectionBox:{dialogTitle:"剖切盒",actions:{hide:"隱藏",reverse:"反向",fitToModel:"適應",reset:"重設"},axes:{x:"X",y:"Y",z:"Z"}},walkControl:{speed:"移動速度:",gravity:"重力",collision:"碰撞",characterModel:{label:"建築工人",constructionWorker:"建築工人",officeMale:"辦公室男性"},walkMode:{label:"行走模式",walk:"行走模式",run:"奔跑模式"},exit:"退出",path:{dialogTitle:"路徑漫遊",duration:"漫遊時間",durationUnit:"秒",loop:"循環播放",addPoint:"新增漫遊點",deleteAll:"刪除全部",point:"漫遊點",play:"播放漫遊",stop:"停止漫遊",noPoints:"暫無漫遊點,請新增"}},info:{dialogTitle:"基本資訊",meshCount:"構件數量",totalTriangles:"三角面數量",totalVertices:"頂點數量"},aiChat:{title:"AI 助手",placeholder:"輸入你的問題...",quickPrompt:{summarize:"總結這個模型",explain:"解釋選中的構件",generate:"生成報告"},action:{new:"新建對話",history:"歷史記錄",settings:"設定",close:"關閉"},helper:{newline:"Shift + Enter 換行",send:"Enter 傳送"},thinking:"正在思考...",other:"其他",otherPlaceholder:"請輸入自定義答案",submit:"提交"},setting:{dialogTitle:"設定",presetSelect:"選擇預設",presetSelectPlaceholder:"請選擇預設",defaultPresetLabel:"預設預設",savePreset:"儲存預設",deletePreset:"刪除預設",deletePresetForbidden:"預設預設不允許刪除",presetDefaultName:"預設",presetNamePrompt:"請輸入預設名稱",presetNameRequired:"預設名稱不能為空",presetNameDuplicate:"預設名稱已存在,請使用其他名稱",restorePreset:"還原預設",saveAsNewPreset:"另存為新預設",selectPresetFirst:"請先選擇預設",presetButton:"預設",undoChanges:"撤銷修改",saveAsDialogTitle:"另存為新預設",deleteDialogTitle:"刪除預設",deleteDialogMessage:"確認刪除目前預設嗎?刪除後無法復原。",presetNamePlaceholder:"請輸入預設名稱",confirm:"確定",cancel:"取消",presetPickPrompt:"請輸入預設序號",presetPickInvalid:"預設序號無效",renderMode:"渲染模式",modes:{simple:"效能模式",balance:"平衡模式",advanced:"效果模式"},displaySection:"顯示設定",edgeLine:"邊線",edgeOpacity:"邊線透明度",showGrid:"顯示軸網",showLevel:"顯示標高",contrast:"對比度",saturation:"飽和度",lightIntensity:"光照強度",environment:"環境背景",environmentType:{none:"無",hdr:"HDR背景",sky:"天空盒"},backgroundVisible:"顯示背景",ground:"顯示地面",groundElevation:"地面高度",groundElevationUnit:"m"}};class $2{currentLocale="zh-CN";messages={"zh-CN":q2,"en-US":Z2,"zh-TW":Y2};listeners=[];constructor(){}getLocale(){return this.currentLocale}setLocale(e){this.messages[e]&&this.currentLocale!==e&&(this.currentLocale=e,this.notifyListeners())}t(e){if(!e)return"";const t=e.split(".");let i=this.messages[this.currentLocale];for(const n of t)if(i&&typeof i=="object"&&n in i)i=i[n];else return e;return i}subscribe(e){return this.listeners.push(e),()=>{this.listeners=this.listeners.filter(t=>t!==e)}}notifyListeners(){this.listeners.forEach(e=>e(this.currentLocale))}}const $t=new $2,Ee=s=>$t.t(s),gy={name:"light",primary:"#2563eb",primaryHover:"#1d4ed8",primaryActive:"#1e40af",primarySubtle:"rgba(37, 99, 235, 0.1)",success:"#16a34a",successHover:"#15803d",successSubtle:"rgba(22, 163, 74, 0.1)",warning:"#d97706",warningHover:"#b45309",warningSubtle:"rgba(217, 119, 6, 0.1)",danger:"#dc2626",dangerHover:"#b91c1c",dangerSubtle:"rgba(220, 38, 38, 0.1)",info:"#0891b2",infoHover:"#0e7490",infoSubtle:"rgba(8, 145, 178, 0.1)",bgBase:"#f8fafc",bgElevated:"#ffffff",bgOverlay:"rgba(255, 255, 255, 0.98)",bgInset:"#f1f5f9",bgGlass:"rgba(255, 255, 255, 0.8)",bgGlassBlur:"24px",textPrimary:"#0f172a",textSecondary:"#475569",textTertiary:"#94a3b8",textDisabled:"#cbd5e1",textInverse:"#ffffff",textLink:"#2563eb",textLinkHover:"#1d4ed8",iconDefault:"#64748b",iconHover:"#334155",iconActive:"#2563eb",iconDisabled:"#cbd5e1",iconInverse:"#ffffff",borderDefault:"#e2e8f0",borderSubtle:"#f1f5f9",borderStrong:"#cbd5e1",borderDisabled:"#f1f5f9",divider:"#e2e8f0",componentBg:"transparent",componentBgHover:"rgba(15, 23, 42, 0.04)",componentBgActive:"rgba(15, 23, 42, 0.08)",componentBgSelected:"rgba(37, 99, 235, 0.08)",componentBgDisabled:"#f8fafc",focusRing:"rgba(37, 99, 235, 0.5)",focusRingOffset:"#ffffff",selectionBg:"rgba(37, 99, 235, 0.15)",selectionText:"#0f172a",shadowSm:"0 2px 8px rgba(0, 0, 0, 0.1), 0 4px 12px rgba(0, 0, 0, 0.08)",shadowMd:"0 4px 12px rgba(0, 0, 0, 0.12), 0 6px 20px rgba(0, 0, 0, 0.1)",shadowLg:"0 10px 25px rgba(0, 0, 0, 0.15), 0 6px 10px rgba(0, 0, 0, 0.1)",shadowXl:"0 20px 40px rgba(0, 0, 0, 0.2), 0 10px 15px rgba(0, 0, 0, 0.1)",shadowGlow:"0 2px 8px rgba(59, 130, 246, 0.3), 0 4px 16px rgba(59, 130, 246, 0.2)",scrollbarTrack:"#f1f5f9",scrollbarThumb:"#cbd5e1",scrollbarThumbHover:"#94a3b8",floatingBg:"rgba(255, 255, 255, 0.8)",floatingBorder:"rgba(226, 232, 240, 0.5)",floatingShadow:"0 4px 24px rgba(0, 0, 0, 0.06)",floatingBtnBg:"rgba(255, 255, 255, 0.9)",floatingBtnBorder:"rgba(203, 213, 225, 0.6)",floatingBtnShadow:"0 2px 8px rgba(0, 0, 0, 0.1), 0 4px 12px rgba(0, 0, 0, 0.08)",floatingBtnBgHover:"#ffffff",floatingBtnShadowHover:"0 4px 12px rgba(0, 0, 0, 0.12), 0 6px 20px rgba(0, 0, 0, 0.1)",floatingIconColor:"#334155",floatingIconColorHover:"#1e293b",panelBg:"rgba(255, 255, 255, 0.95)",panelBorder:"rgba(226, 232, 240, 0.6)",panelHeaderBg:"rgba(248, 250, 252, 0.9)",panelRadius:"12px",tabBg:"#f1f5f9",tabItemBg:"transparent",tabItemBgHover:"rgba(255, 255, 255, 0.6)",tabItemBgActive:"#ffffff",tabItemTextActive:"#2563eb",overrides:{dialog:{headerBg:"#f8fafc"},toolbar:{bg:"rgba(255, 255, 255, 0.9)",buttonBg:"rgba(255, 255, 255, 0.95)",buttonBgHover:"#ffffff",buttonBgActive:"#2563eb"},input:{bg:"#ffffff",bgFocus:"#ffffff",placeholder:"#94a3b8"}}},K2={name:"dark",primary:"#3b82f6",primaryHover:"#60a5fa",primaryActive:"#2563eb",primarySubtle:"rgba(59, 130, 246, 0.15)",success:"#22c55e",successHover:"#4ade80",successSubtle:"rgba(34, 197, 94, 0.15)",warning:"#f59e0b",warningHover:"#fbbf24",warningSubtle:"rgba(245, 158, 11, 0.15)",danger:"#ef4444",dangerHover:"#f87171",dangerSubtle:"rgba(239, 68, 68, 0.15)",info:"#06b6d4",infoHover:"#22d3ee",infoSubtle:"rgba(6, 182, 212, 0.15)",bgBase:"#152232",bgElevated:"#1f2d3e",bgOverlay:"rgba(21, 34, 50, 0.98)",bgInset:"#152232",bgGlass:"rgba(21, 34, 50, 0.85)",bgGlassBlur:"24px",textPrimary:"#ffffff",textSecondary:"#94a3b8",textTertiary:"#64748b",textDisabled:"#475569",textInverse:"#152232",textLink:"#60a5fa",textLinkHover:"#93c5fd",iconDefault:"#ffffff",iconHover:"#ffffff",iconActive:"#3b82f6",iconDisabled:"#475569",iconInverse:"#152232",borderDefault:"rgba(51, 65, 85, 0.5)",borderSubtle:"rgba(51, 65, 85, 0.5)",borderStrong:"#475569",borderDisabled:"#1e293b",divider:"#334155",componentBg:"transparent",componentBgHover:"rgba(248, 250, 252, 0.06)",componentBgActive:"rgba(248, 250, 252, 0.1)",componentBgSelected:"rgba(59, 130, 246, 0.2)",componentBgDisabled:"#1e293b",focusRing:"rgba(59, 130, 246, 0.5)",focusRingOffset:"#1e293b",selectionBg:"rgba(59, 130, 246, 0.3)",selectionText:"#f8fafc",shadowSm:"0 2px 8px rgba(0, 0, 0, 0.4), 0 4px 12px rgba(0, 0, 0, 0.3)",shadowMd:"0 4px 12px rgba(0, 0, 0, 0.5), 0 6px 20px rgba(0, 0, 0, 0.4)",shadowLg:"0 10px 25px rgba(0, 0, 0, 0.6), 0 6px 10px rgba(0, 0, 0, 0.4)",shadowXl:"0 20px 40px rgba(0, 0, 0, 0.7), 0 10px 15px rgba(0, 0, 0, 0.5)",shadowGlow:"0 2px 8px rgba(59, 130, 246, 0.4), 0 4px 16px rgba(59, 130, 246, 0.25)",scrollbarTrack:"#1e293b",scrollbarThumb:"#475569",scrollbarThumbHover:"#64748b",floatingBg:"rgba(15, 23, 42, 0.85)",floatingBorder:"rgba(51, 65, 85, 0.4)",floatingShadow:"0 4px 24px rgba(0, 0, 0, 0.25)",floatingBtnBg:"rgba(51, 65, 85, 0.6)",floatingBtnBorder:"rgba(100, 116, 139, 0.5)",floatingBtnShadow:"0 2px 8px rgba(0, 0, 0, 0.3), 0 4px 12px rgba(0, 0, 0, 0.25)",floatingBtnBgHover:"rgba(71, 85, 105, 0.7)",floatingBtnShadowHover:"0 4px 12px rgba(0, 0, 0, 0.35), 0 6px 20px rgba(0, 0, 0, 0.3)",floatingIconColor:"#e2e8f0",floatingIconColorHover:"#f8fafc",panelBg:"rgba(15, 23, 42, 0.95)",panelBorder:"rgba(51, 65, 85, 0.5)",panelHeaderBg:"rgba(15, 23, 42, 0.9)",panelRadius:"12px",tabBg:"rgba(30, 41, 59, 0.6)",tabItemBg:"transparent",tabItemBgHover:"rgba(51, 65, 85, 0.5)",tabItemBgActive:"rgba(51, 65, 85, 0.8)",tabItemTextActive:"#60a5fa",overrides:{dialog:{headerBg:"#0f172a"},toolbar:{bg:"rgba(30, 41, 59, 0.9)",buttonBg:"rgba(51, 65, 85, 0.6)",buttonBgHover:"rgba(71, 85, 105, 0.7)",buttonBgActive:"#3b82f6"},input:{bg:"#0f172a",bgFocus:"#1e293b",placeholder:"#64748b"}}};class J2{currentTheme=gy;listeners=[];constructor(){}getTheme(){return this.currentTheme}setTheme(e){e==="light"?this.applyTheme(gy):this.applyTheme(K2)}setCustomTheme(e){this.applyTheme(e)}applyTheme(e){this.currentTheme=e,this.notifyListeners()}subscribe(e){return this.listeners.push(e),e(this.currentTheme),()=>{this.listeners=this.listeners.filter(t=>t!==e)}}notifyListeners(){this.listeners.forEach(e=>e(this.currentTheme))}}const ct=new J2;class Am{container;options;groups=[];activeBtnIds=new Set;btnRefs=new Map;dropdownElement=null;hoverTimeout=null;customColors=new Set;unsubscribeLocale=null;unsubscribeTheme=null;DEFAULT_ICON='';constructor(e){const t=typeof e.container=="string"?document.getElementById(e.container):e.container;if(!t)throw new Error("Container not found");this.container=t,this.options={showLabel:!0,visibility:{},direction:"row",position:"static",align:"vertical",expand:"down",...e},["backgroundColor","btnBackgroundColor","btnHoverColor","btnActiveColor","iconColor","iconActiveColor","textColor","textActiveColor"].forEach(n=>{e[n]&&this.customColors.add(n)}),this.initContainer(),this.applyStyles()}emit(e,t){this.options.registry?.emit(e,t)}initContainer(){this.container.innerHTML="",this.container.classList.add("bim-btn-group-root"),this.options.direction==="column"?this.container.classList.add("dir-column"):this.container.classList.add("dir-row"),this.options.className&&this.container.classList.add(this.options.className),this.options.type&&this.options.type!=="default"&&this.container.classList.add(`type-${this.options.type}`),this.updatePosition(),this.setupEventInterception(this.container)}setupEventInterception(e){const t=n=>{n.stopPropagation()};["click","dblclick","contextmenu","wheel","mousedown","mouseup","mousemove","touchstart","touchend","touchmove","pointerdown","pointerup","pointermove","pointerenter","pointerleave","pointerover","pointerout"].forEach(n=>{e.addEventListener(n,t,{passive:!1})})}updatePosition(){const e=this.options.position,t=this.container.style;if(t.top="",t.bottom="",t.left="",t.right="",t.transform="",e==="static"){this.container.classList.add("static");return}if(this.container.classList.remove("static"),this.container.style.position="absolute",typeof e=="object"&&"x"in e)t.left=`${e.x}px`,t.top=`${e.y}px`;else{const i="20px";switch(e){case"top-left":t.top=i,t.left=i;break;case"top-center":t.top=i,t.left="50%",t.transform="translateX(-50%)";break;case"top-right":t.top=i,t.right=i;break;case"bottom-left":t.bottom=i,t.left=i;break;case"bottom-center":t.bottom=i,t.left="50%",t.transform="translateX(-50%)";break;case"bottom-right":t.bottom=i,t.right=i;break;case"left-center":t.left=i,t.top="50%",t.transform="translateY(-50%)";break;case"right-center":t.right=i,t.top="50%",t.transform="translateY(-50%)";break;case"center":t.top="50%",t.left="50%",t.transform="translate(-50%, -50%)";break}}}applyStyles(){const e=this.container.style;this.options.backgroundColor&&e.setProperty("--bim-btn-group-section-bg",this.options.backgroundColor),this.options.btnBackgroundColor&&e.setProperty("--bim-btn-bg",this.options.btnBackgroundColor),this.options.btnHoverColor&&e.setProperty("--bim-btn-hover-bg",this.options.btnHoverColor),this.options.btnActiveColor&&e.setProperty("--bim-btn-active-bg",this.options.btnActiveColor),this.options.iconColor&&e.setProperty("--bim-icon-color",this.options.iconColor),this.options.iconActiveColor&&e.setProperty("--bim-icon-active-color",this.options.iconActiveColor),this.options.textColor&&e.setProperty("--bim-btn-text-color",this.options.textColor),this.options.textActiveColor&&e.setProperty("--bim-btn-text-active-color",this.options.textActiveColor),document.querySelectorAll(".opt-btn-dropdown").forEach(i=>{const n=i.style;this.options.iconColor&&n.setProperty("--bim-icon-color",this.options.iconColor),this.options.iconActiveColor&&n.setProperty("--bim-icon-active-color",this.options.iconActiveColor),this.options.textColor&&n.setProperty("--bim-btn-text-color",this.options.textColor),this.options.textActiveColor&&n.setProperty("--bim-btn-text-active-color",this.options.textActiveColor),this.options.btnBackgroundColor&&n.setProperty("--bim-btn-bg",this.options.btnBackgroundColor),this.options.btnHoverColor&&n.setProperty("--bim-btn-hover-bg",this.options.btnHoverColor),this.options.btnActiveColor&&n.setProperty("--bim-btn-active-bg",this.options.btnActiveColor)})}setPrimaryColor(e){this.container.style.setProperty("--bim-primary-color",e),document.querySelectorAll(".opt-btn-dropdown").forEach(i=>{i.style.setProperty("--bim-primary-color",e)})}setTheme(e){const t={backgroundColor:e.bgElevated,btnBackgroundColor:e.componentBg,btnHoverColor:e.componentBgHover,btnActiveColor:e.componentBgActive,iconColor:e.iconDefault,iconActiveColor:e.iconActive,textColor:e.textSecondary,textActiveColor:e.textPrimary};Object.entries(t).forEach(([i,n])=>{const r=i;this.customColors.has(r)||(this.options[r]=n)}),this.container.classList.remove("theme-dark","theme-light"),this.container.classList.add(`theme-${e.name}`),this.applyStyles(),this.setPrimaryColor(e.primary),this.applyThemeCssVars(e)}applyThemeCssVars(e){const t=this.container.style;t.setProperty("--bim-primary",e.primary),t.setProperty("--bim-primary-hover",e.primaryHover),t.setProperty("--bim-primary-active",e.primaryActive),t.setProperty("--bim-bg-glass",e.bgGlass),t.setProperty("--bim-bg-glass-blur",e.bgGlassBlur),t.setProperty("--bim-bg-elevated",e.bgElevated),t.setProperty("--bim-bg-overlay",e.bgOverlay),t.setProperty("--bim-bg-inset",e.bgInset),t.setProperty("--bim-text-primary",e.textPrimary),t.setProperty("--bim-text-secondary",e.textSecondary),t.setProperty("--bim-text-tertiary",e.textTertiary),t.setProperty("--bim-text-inverse",e.textInverse),t.setProperty("--bim-icon-default",e.iconDefault),t.setProperty("--bim-icon-hover",e.iconHover),t.setProperty("--bim-icon-active",e.iconActive),t.setProperty("--bim-icon-inverse",e.iconInverse),t.setProperty("--bim-border-default",e.borderDefault),t.setProperty("--bim-border-subtle",e.borderSubtle),t.setProperty("--bim-component-bg-hover",e.componentBgHover),t.setProperty("--bim-component-bg-active",e.componentBgActive),t.setProperty("--bim-shadow-sm",e.shadowSm),t.setProperty("--bim-shadow-md",e.shadowMd),t.setProperty("--bim-shadow-lg",e.shadowLg),t.setProperty("--bim-shadow-glow",e.shadowGlow),t.setProperty("--bim-floating-bg",e.floatingBg),t.setProperty("--bim-floating-border",e.floatingBorder),t.setProperty("--bim-floating-shadow",e.floatingShadow),t.setProperty("--bim-floating-btn-bg",e.floatingBtnBg),t.setProperty("--bim-floating-btn-border",e.floatingBtnBorder),t.setProperty("--bim-floating-btn-shadow",e.floatingBtnShadow),t.setProperty("--bim-floating-btn-bg-hover",e.floatingBtnBgHover),t.setProperty("--bim-floating-btn-shadow-hover",e.floatingBtnShadowHover),t.setProperty("--bim-floating-icon-color",e.floatingIconColor),t.setProperty("--bim-floating-icon-color-hover",e.floatingIconColorHover),this.syncDropdownCssVars(e)}syncDropdownCssVars(e){document.querySelectorAll(".opt-btn-dropdown").forEach(i=>{const n=i.style;n.setProperty("--bim-primary",e.primary),n.setProperty("--bim-bg-overlay",e.bgOverlay),n.setProperty("--bim-border-default",e.borderDefault),n.setProperty("--bim-text-primary",e.textPrimary),n.setProperty("--bim-text-inverse",e.textInverse),n.setProperty("--bim-shadow-lg",e.shadowLg),n.setProperty("--bim-floating-btn-bg",e.floatingBtnBg),n.setProperty("--bim-floating-btn-bg-hover",e.floatingBtnBgHover),n.setProperty("--bim-floating-icon-color",e.floatingIconColor)})}setColors(e){this.options={...this.options,...e},Object.keys(e).forEach(t=>{this.customColors.add(t)}),this.applyStyles()}async init(){this.render(),this.unsubscribeLocale=$t.subscribe(()=>{this.setLocales()}),this.unsubscribeTheme=ct.subscribe(e=>{this.setTheme(e)})}setLocales(){this.render()}addGroup(e,t){if(this.groups.some(n=>n.id===e))return;const i={id:e,buttons:[]};if(t){const n=this.groups.findIndex(r=>r.id===t);n!==-1?this.groups.splice(n,0,i):this.groups.push(i)}else this.groups.push(i)}addButton(e){const{groupId:t,parentId:i}=e,n=this.groups.find(a=>a.id===t);if(!n)return;const r={...e,children:e.children||[]};if(i){const a=this.findButton(n.buttons,i);a&&(a.children||(a.children=[]),a.children.push(r))}else n.buttons.push(r)}findButton(e,t){for(const i of e){if(i.id===t)return i;if(i.children){const n=this.findButton(i.children,t);if(n)return n}}}render(){this.container.innerHTML="",this.btnRefs.clear(),this.groups.forEach((e,t)=>{const i=this.renderGroup(e,t,this.groups.length);this.container.appendChild(i)})}renderGroup(e,t,i){const n=document.createElement("div");return n.className="bim-btn-group-section",t{if(this.isVisible(r.id)){const a=this.renderButton(r);n.appendChild(a)}}),n}renderButton(e){const t=document.createElement("div");t.className="opt-btn-wrapper";const i=document.createElement("div");i.className="opt-btn",e.isActive&&this.activeBtnIds.add(e.id),(e.align||this.options.align||"vertical")==="horizontal"?i.classList.add("align-horizontal"):i.classList.add("align-vertical"),this.activeBtnIds.has(e.id)&&i.classList.add("active"),e.disabled&&i.classList.add("disabled"),this.options.showLabel&&e.label||(i.classList.add("no-label"),e.label&&(i.title=Ee(e.label)));const a=e.iconSize||32,o=e.minWidth||50;i.style.minWidth=`${o}px`;const l=document.createElement("div");l.className="opt-btn-icon",l.style.width=`${a}px`,l.style.height=`${a}px`,l.innerHTML=this.getIcon(e.icon),i.appendChild(l);const c=document.createElement("div");if(c.className="opt-btn-text-wrapper",this.options.showLabel&&e.label){const h=document.createElement("span");h.className="opt-btn-label",h.textContent=Ee(e.label),c.appendChild(h)}return c.hasChildNodes()&&i.appendChild(c),i.addEventListener("click",()=>this.handleClick(e)),i.addEventListener("mouseenter",()=>this.handleMouseEnter(e,i)),i.addEventListener("mouseleave",()=>this.handleMouseLeave()),this.btnRefs.set(e.id,i),t.appendChild(i),t}setBtnActive(e,t){const i=this.findButtonById(e);if(!i)return;const n=t!==void 0?t:!this.activeBtnIds.has(e);n?this.activeBtnIds.add(e):this.activeBtnIds.delete(e),i.isActive=n,this.updateButtonState(e)}handleClick(e){if(!e.disabled&&(!e.children||e.children.length===0)){if(e.keepActive){const i=!this.activeBtnIds.has(e.id);this.setBtnActive(e.id,i),i&&e.exclusive&&e.groupId&&this.deactivateExclusiveSiblings(e)}this.closeDropdown(),e.onClick&&e.onClick(e)}}deactivateExclusiveSiblings(e){const t=this.groups.find(i=>i.id===e.groupId);if(t){if(e.parentId){const n=this.findButton(t.buttons,e.parentId)?.children||[];for(const r of n)r&&r.id!==e.id&&r.parentId===e.parentId&&r.groupId===e.groupId&&this.activeBtnIds.has(r.id)&&(this.setBtnActive(r.id,!1),r.onClick&&r.onClick(r));return}for(const i of t.buttons)i.id!==e.id&&i.groupId===e.groupId&&(i.parentId||this.activeBtnIds.has(i.id)&&(this.setBtnActive(i.id,!1),i.onClick&&i.onClick(i)))}}handleMouseEnter(e,t){this.hoverTimeout&&clearTimeout(this.hoverTimeout),e.children&&e.children.length>0?this.showDropdown(e,t):this.closeDropdown()}handleMouseLeave(){this.hoverTimeout=window.setTimeout(()=>this.closeDropdown(),200)}showDropdown(e,t){if(this.closeDropdown(),!e.children)return;const i=document.createElement("div");i.className="opt-btn-dropdown",this.options.backgroundColor&&i.style.setProperty("--bim-toolbar-bg",this.options.backgroundColor);const n=i.style;this.options.iconColor&&n.setProperty("--bim-icon-color",this.options.iconColor),this.options.iconActiveColor&&n.setProperty("--bim-icon-active-color",this.options.iconActiveColor),this.options.textColor&&n.setProperty("--bim-btn-text-color",this.options.textColor),this.options.textActiveColor&&n.setProperty("--bim-btn-text-active-color",this.options.textActiveColor),this.options.btnBackgroundColor&&n.setProperty("--bim-btn-bg",this.options.btnBackgroundColor),this.options.btnHoverColor&&n.setProperty("--bim-btn-hover-bg",this.options.btnHoverColor),this.options.btnActiveColor&&n.setProperty("--bim-btn-active-bg",this.options.btnActiveColor);const r=t.getBoundingClientRect(),a=this.options.expand||"down";this.options.direction==="row"?i.style.flexDirection="column":i.style.flexDirection="row",this.options.type&&this.options.type!=="default"&&i.classList.add(`type-${this.options.type}`);const o=ct.getTheme();i.classList.add(`theme-${o.name}`),n.setProperty("--bim-primary",o.primary),n.setProperty("--bim-bg-overlay",o.bgOverlay),n.setProperty("--bim-border-default",o.borderDefault),n.setProperty("--bim-text-primary",o.textPrimary),n.setProperty("--bim-text-inverse",o.textInverse),n.setProperty("--bim-shadow-lg",o.shadowLg),n.setProperty("--bim-floating-btn-bg",o.floatingBtnBg),n.setProperty("--bim-floating-btn-bg-hover",o.floatingBtnBgHover),n.setProperty("--bim-floating-icon-color",o.floatingIconColor),document.body.appendChild(i),this.setupEventInterception(i),e.children.forEach(c=>{if(this.isVisible(c.id)){const h=this.renderDropdownItem(c);i.appendChild(h)}});const l=i.getBoundingClientRect();a==="up"?(i.style.bottom=window.innerHeight-r.top+8+"px",i.style.left=r.left+(r.width-l.width)/2+"px"):a==="down"?(i.style.top=r.bottom+8+"px",i.style.left=r.left+(r.width-l.width)/2+"px"):a==="right"?(i.style.top=r.top+(r.height-l.height)/2+"px",i.style.left=r.right+8+"px"):a==="left"&&(i.style.top=r.top+(r.height-l.height)/2+"px",i.style.right=window.innerWidth-r.left+8+"px"),i.addEventListener("mouseenter",()=>{this.hoverTimeout&&clearTimeout(this.hoverTimeout)}),i.addEventListener("mouseleave",()=>this.handleMouseLeave()),this.dropdownElement=i}renderDropdownItem(e){const t=document.createElement("div");t.className="opt-btn-dropdown-item",(e.align||"horizontal")==="horizontal"?t.classList.add("align-horizontal"):t.classList.add("align-vertical"),(this.activeBtnIds.has(e.id)||e.isActive)&&t.classList.add("active");const n=e.iconSize||32,r=e.minWidth;r&&(t.style.minWidth=`${r}px`);const a=document.createElement("div");if(a.className="opt-btn-icon",a.style.width=`${n}px`,a.style.height=`${n}px`,a.innerHTML=this.getIcon(e.icon),t.appendChild(a),this.options.showLabel&&e.label){const o=document.createElement("span");o.className="opt-btn-dropdown-label",o.textContent=Ee(e.label),t.appendChild(o)}else e.label&&(t.title=Ee(e.label));return t.addEventListener("click",o=>{o.stopPropagation(),this.handleClick(e)}),t}closeDropdown(){this.dropdownElement&&(this.dropdownElement.remove(),this.dropdownElement=null),this.btnRefs.forEach(e=>{const t=e.querySelector(".opt-btn-arrow");t&&t.classList.remove("rotated")})}updateButtonState(e){const t=this.btnRefs.get(e);t&&(this.activeBtnIds.has(e)?t.classList.add("active"):t.classList.remove("active"))}getIcon(e){return e||this.DEFAULT_ICON}updateButtonIcon(e,t){const i=this.btnRefs.get(e);if(!i)return;const n=i.querySelector(".opt-btn-icon");n&&(n.innerHTML=this.getIcon(t));const r=this.findButtonById(e);r&&(r.icon=t)}updateButtonVisibility(e,t){this.options.visibility||(this.options.visibility={}),this.options.visibility[e]=t,this.render()}setShowLabel(e){this.options.showLabel=e,this.updateLabelsVisibility()}updateLabelsVisibility(){this.btnRefs.forEach((e,t)=>{const i=this.findButtonById(t);if(!i)return;this.options.showLabel&&i.label?(e.classList.remove("no-label"),e.removeAttribute("title")):(e.classList.add("no-label"),i.label&&(e.title=Ee(i.label)))})}findButtonById(e){for(const t of this.groups){const i=this.findButton(t.buttons,e);if(i)return i}}setBackgroundColor(e){this.setColors({backgroundColor:e})}isVisible(e){return this.options.visibility?.[e]!==!1}setType(e){this.container.classList.remove("type-default","type-glass-pill"),this.options.type=e,e&&e!=="default"&&this.container.classList.add(`type-${e}`),this.render()}getType(){return this.options.type||"default"}destroy(){this.unsubscribeLocale&&(this.unsubscribeLocale(),this.unsubscribeLocale=null),this.unsubscribeTheme&&(this.unsubscribeTheme(),this.unsubscribeTheme=null),this.closeDropdown(),this.container.innerHTML="",this.btnRefs.clear()}}class Q2 extends Am{async init(){await super.init();const e=this.options.registry,{createHomeButton:t}=await Promise.resolve().then(()=>E9),{createZoomBoxButton:i}=await Promise.resolve().then(()=>T9),{createWalkMenuButton:n}=await Promise.resolve().then(()=>C9),{createMapButton:r}=await Promise.resolve().then(()=>A9),{createPropertyButton:a}=await Promise.resolve().then(()=>P9),{createSettingButton:o}=await Promise.resolve().then(()=>R9),{createInfoButton:l}=await Promise.resolve().then(()=>I9),{createFullscreenButton:c}=await Promise.resolve().then(()=>L9),{createMeasureButton:h}=await Promise.resolve().then(()=>D9),{createSectionMenuButton:d}=await Promise.resolve().then(()=>N9),{createSectionPlaneButton:p}=await Promise.resolve().then(()=>k9),{createSectionAxisButton:u}=await Promise.resolve().then(()=>O9),{createSectionBoxButton:v}=await Promise.resolve().then(()=>U9),{createAiChatButton:g}=await Promise.resolve().then(()=>B9),{createCameraSwitchButton:m}=await Promise.resolve().then(()=>F9);this.addGroup("group-1"),this.addButton(t(e)),this.addButton(m(e)),this.addButton(i(e)),this.addButton(h(e)),this.addButton(d(e)),this.addButton(p(e)),this.addButton(u(e)),this.addButton(v(e)),this.addButton(n(e)),this.addButton(r(e)),this.addButton(a(e)),this.addGroup("group-2"),this.addButton(g(e)),this.addButton(o(e)),this.addButton(l(e)),this.addButton(c(e)),this.render()}}class jn{registry;subscriptions=[];constructor(e){this.registry=e}get engineComponent(){return this.registry.engine3d?.getEngineComponent?.()??null}subscribe(e,t){const i=this.registry.on(e,t);this.subscriptions.push(i)}emit(e,t){this.registry.emit(e,t)}destroy(){this.subscriptions.forEach(e=>e()),this.subscriptions=[]}}class eE extends jn{toolbar=null;toolbarContainer=null;container;constructor(e,t){super(t),this.container=e,this.init()}init(){this.toolbarContainer=document.createElement("div"),this.toolbarContainer.id="opt-btn-groups",this.toolbarContainer.className="bim-engine-opt-btn-container is-bottom-toolbar",this.container.appendChild(this.toolbarContainer),this.toolbar=new Q2({container:this.toolbarContainer,type:"glass-pill",showLabel:!0,direction:"row",position:"bottom-right",align:"vertical",expand:"up",registry:this.registry}),this.toolbar.init()}updateTheme(e){this.toolbar?.setTheme(e)}refresh(){this.toolbar?.render()}destroy(){this.toolbar?.destroy(),this.toolbar=null,super.destroy()}addGroup(e,t){this.toolbar?.addGroup(e,t),this.toolbar?.render()}addButton(e){this.toolbar?.addButton(e),this.toolbar?.render()}setButtonVisibility(e,t){this.toolbar?.updateButtonVisibility(e,t)}setShowLabel(e){this.toolbar?.setShowLabel(e)}setBtnActive(e,t){this.toolbar?.setBtnActive(e,t)}updateButtonIcon(e,t){this.toolbar?.updateButtonIcon(e,t)}setVisible(e){this.toolbarContainer&&(this.toolbarContainer.style.visibility=e?"visible":"hidden")}setBackgroundColor(e){this.toolbar?.setBackgroundColor(e)}setColors(e){this.toolbar?.setColors(e)}hide(){this.toolbarContainer&&(this.toolbarContainer.style.display="none")}show(){this.toolbarContainer&&(this.toolbarContainer.style.display="")}getContainer(){return this.toolbarContainer}setType(e){this.toolbar?.setType(e)}getType(){return this.toolbar?.getType()||"default"}}class tE extends jn{groups=new Map;container;constructor(e,t){super(t),this.container=e}create(e,t){const i=new Am({container:this.container,registry:this.registry,...t});return i.init(),this.groups.set(e,i),i}get(e){return this.groups.get(e)}updateTheme(e){this.groups.forEach(t=>t.setTheme(e))}destroy(){this.groups.forEach(e=>e.destroy()),this.groups.clear(),super.destroy()}}class iE{element;options;container;header;contentArea;_isDestroyed=!1;_isInitialized=!1;unsubscribeTheme=null;unsubscribeLocale=null;rafId=null;constructor(e){this.options={title:"Dialog",width:300,height:"auto",position:"center",draggable:!0,resizable:!1,minWidth:200,minHeight:100,...e},this.container=e.container,this.element=this.createDom(),this.header=this.element.querySelector(".bim-dialog-header"),this.contentArea=this.element.querySelector(".bim-dialog-content"),this.init()}setTheme(e){const t=this.element.style;this.options.backgroundColor||t.setProperty("--bim-dialog-bg",e.bgElevated),this.options.headerBackgroundColor||t.setProperty("--bim-dialog-header-bg",e.bgInset),this.options.titleColor||t.setProperty("--bim-dialog-title-color",e.textPrimary),this.options.textColor||t.setProperty("--bim-dialog-text-color",e.textSecondary),this.options.borderColor||t.setProperty("--bim-dialog-border-color",e.borderDefault),t.setProperty("--bim-bg-elevated",e.bgElevated),t.setProperty("--bim-bg-inset",e.bgInset),t.setProperty("--bim-text-primary",e.textPrimary),t.setProperty("--bim-text-secondary",e.textSecondary),t.setProperty("--bim-text-tertiary",e.textTertiary),t.setProperty("--bim-border-default",e.borderDefault),t.setProperty("--bim-shadow-lg",e.shadowLg)}init(){this._isInitialized||(this.container.appendChild(this.element),this.initPosition(),this.options.draggable&&this.initDrag(),this.options.resizable&&this.initResize(),this._isInitialized=!0,this.options.onOpen&&this.options.onOpen(),this.unsubscribeTheme=ct.subscribe(e=>{this.setTheme(e)}),this.unsubscribeLocale=$t.subscribe(()=>{this.setLocales()}))}setLocales(){if(this.options.title){const e=this.header.querySelector(".bim-dialog-title");e&&(e.textContent=Ee(this.options.title))}}createDom(){const e=document.createElement("div");e.className="bim-dialog",this.options.id&&(e.id=this.options.id);const t=e.style;this.options.backgroundColor&&t.setProperty("--bim-dialog-bg",this.options.backgroundColor),this.options.headerBackgroundColor&&t.setProperty("--bim-dialog-header-bg",this.options.headerBackgroundColor),this.options.titleColor&&t.setProperty("--bim-dialog-title-color",this.options.titleColor),this.options.textColor&&t.setProperty("--bim-dialog-text-color",this.options.textColor),this.options.borderColor&&t.setProperty("--bim-dialog-border-color",this.options.borderColor),this.setSize(e,this.options.width,this.options.height),this.options.minWidth&&(e.style.minWidth=`${this.options.minWidth}px`);const i=document.createElement("div");i.className="bim-dialog-header",this.options.draggable&&i.classList.add("draggable");const n=document.createElement("span");n.className="bim-dialog-title",n.textContent=this.options.title?Ee(this.options.title):"";const r=document.createElement("span");r.className="bim-dialog-close",r.innerHTML="×",r.onclick=()=>{this.close()},i.appendChild(n),i.appendChild(r);const a=document.createElement("div");if(a.className="bim-dialog-content",typeof this.options.content=="string"?a.innerHTML=this.options.content:this.options.content instanceof HTMLElement&&a.appendChild(this.options.content),e.appendChild(i),e.appendChild(a),this.options.resizable){const c=document.createElement("div");c.className="bim-dialog-resize-handle",e.appendChild(c)}const o=c=>{c.stopPropagation()};return["click","dblclick","contextmenu","wheel","mousedown","mouseup","mousemove","touchstart","touchend","touchmove","pointerdown","pointerup","pointermove","pointerenter","pointerleave","pointerover","pointerout"].forEach(c=>{e.addEventListener(c,o,{passive:!1})}),e}setSize(e,t,i){t!==void 0&&(t==="auto"||t==="fit-content"?e.style.width=t:e.style.width=typeof t=="number"?`${t}px`:t),i!==void 0&&(i==="auto"||i==="fit-content"?e.style.height=i:e.style.height=typeof i=="number"?`${i}px`:i)}fitWidth(e=!1){this.element.style.width="fit-content",e&&this.initPosition()}fitHeight(e=!1){this.element.style.height="auto";const t=this.element.getBoundingClientRect().height,i=this.options.minHeight??100,n=this.container.clientHeight||0;let r=Math.max(i,t);n>0&&(r=Math.min(r,n)),this.element.style.height=`${r}px`,e?this.initPosition():this.clampToContainer()}clampToContainer(){const e=this.container.clientWidth,t=this.container.clientHeight,i=this.element.offsetWidth,n=this.element.offsetHeight,r=this.options.bottomOffset??70,a=this.element.offsetLeft,o=this.element.offsetTop,l=Math.max(0,e-i),c=Math.max(0,t-n-r),h=Math.max(0,Math.min(a,l)),d=Math.max(0,Math.min(o,c));this.element.style.left=`${h}px`,this.element.style.top=`${d}px`}initPosition(){const e=this.options.position,t=this.element.getBoundingClientRect(),i=this.options.bottomOffset??70;let n=0,r=0;const a=this.container.clientWidth,o=this.container.clientHeight,l=t.width,c=t.height;if(typeof e=="object"&&"x"in e)n=e.x,r=e.y;else switch(e){case"center":n=(a-l)/2,r=(o-c)/2;break;case"top-left":n=0,r=0;break;case"top-center":n=(a-l)/2,r=0;break;case"top-right":n=a-l,r=0;break;case"left-center":n=0,r=(o-c)/2;break;case"right-center":n=a-l,r=(o-c)/2;break;case"bottom-left":n=0,r=o-c-i;break;case"bottom-center":n=(a-l)/2,r=o-c-i;break;case"bottom-right":n=a-l,r=o-c-i;break;default:n=(a-l)/2,r=(o-c)/2}n=Math.max(0,Math.min(n,a-l)),r=Math.max(0,Math.min(r,o-c-i)),this.element.style.left=`${n}px`,this.element.style.top=`${r}px`}initDrag(){let e=0,t=0,i=0,n=0,r=0,a=0,o=0,l=0,c=0;const h=u=>{u.preventDefault(),u.stopPropagation(),e=u.clientX,t=u.clientY,i=this.element.offsetLeft,n=this.element.offsetTop,r=this.container.clientWidth,a=this.container.clientHeight,o=this.element.offsetWidth,l=this.element.offsetHeight,c=this.options.bottomOffset??70,document.addEventListener("mousemove",d,{capture:!0}),document.addEventListener("mouseup",p,{capture:!0})},d=u=>{u.preventDefault(),u.stopPropagation(),!this.rafId&&(this.rafId=requestAnimationFrame(()=>{const v=u.clientX-e,g=u.clientY-t;let m=i+v,f=n+g;const y=r-o,x=a-l-c;m=Math.max(0,Math.min(m,y)),f=Math.max(0,Math.min(f,x)),this.element.style.left=`${m}px`,this.element.style.top=`${f}px`,this.rafId=null}))},p=()=>{this.rafId&&(cancelAnimationFrame(this.rafId),this.rafId=null),document.removeEventListener("mousemove",d,{capture:!0}),document.removeEventListener("mouseup",p,{capture:!0})};this.header.addEventListener("mousedown",h)}initResize(){const e=this.element.querySelector(".bim-dialog-resize-handle");if(!e)return;let t=0,i=0,n=0,r=0,a=0,o=0,l=0,c=0;const h=u=>{u.preventDefault(),u.stopPropagation(),t=u.clientX,i=u.clientY,n=this.element.offsetWidth,r=this.element.offsetHeight,a=this.container.clientWidth,o=this.container.clientHeight,l=this.element.offsetLeft,c=this.element.offsetTop,document.addEventListener("mousemove",d,{capture:!0}),document.addEventListener("mouseup",p,{capture:!0})},d=u=>{u.preventDefault(),u.stopPropagation(),!this.rafId&&(this.rafId=requestAnimationFrame(()=>{const v=u.clientX-t,g=u.clientY-i,m=a-l,f=o-c,y=Math.min(m,Math.max(this.options.minWidth||100,n+v)),x=Math.min(f,Math.max(this.options.minHeight||50,r+g));this.element.style.width=`${y}px`,this.element.style.height=`${x}px`,this.rafId=null}))},p=()=>{this.rafId&&(cancelAnimationFrame(this.rafId),this.rafId=null),document.removeEventListener("mousemove",d,{capture:!0}),document.removeEventListener("mouseup",p,{capture:!0})};e.addEventListener("mousedown",h)}setContent(e){this.contentArea.innerHTML="",typeof e=="string"?this.contentArea.innerHTML=e:this.contentArea.appendChild(e)}close(){this._isDestroyed||(this.rafId&&(cancelAnimationFrame(this.rafId),this.rafId=null),this.unsubscribeTheme&&(this.unsubscribeTheme(),this.unsubscribeTheme=null),this.unsubscribeLocale&&(this.unsubscribeLocale(),this.unsubscribeLocale=null),this.element.remove(),this._isDestroyed=!0,this.options.onClose&&this.options.onClose())}destroy(){this.close()}}class vy extends jn{container;activeDialogs=[];constructor(e,t){super(t),this.container=e}create(e){const t=new iE({container:this.container,...e,onClose:()=>{this.activeDialogs=this.activeDialogs.filter(i=>i!==t),e.onClose&&e.onClose()}});return t.setTheme(ct.getTheme()),this.activeDialogs.push(t),t}updateTheme(e){this.activeDialogs.forEach(t=>{t.setTheme&&t.setTheme(e)})}destroy(){this.activeDialogs.forEach(e=>e.destroy()),this.activeDialogs=[],super.destroy()}}const zo="183",Ln={LEFT:0,MIDDLE:1,RIGHT:2,ROTATE:0,DOLLY:1,PAN:2},Dn={ROTATE:0,PAN:1,DOLLY_PAN:2,DOLLY_ROTATE:3},yy=0,Pm=1,xy=2,nE=3,sE=0,vc=1,_y=2,Ho=3,_n=0,Bi=1,Ot=2,Qt=0,ba=1,od=2,Rm=3,Im=4,ld=5,rE=6,bn=100,by=101,My=102,Sy=103,wy=104,Ir=200,Ey=201,Ty=202,Cy=203,cd=204,hd=205,yc=206,Ay=207,xc=208,Py=209,Ry=210,Iy=211,Ly=212,Dy=213,Ny=214,dd=0,ud=1,pd=2,Ma=3,fd=4,md=5,gd=6,vd=7,_c=0,ky=1,Oy=2,ji=0,yd=1,xd=2,_d=3,Sa=4,bd=5,Md=6,Sd=7,Lm="attached",Uy="detached",wd=300,Ls=301,Lr=302,Vo=303,bc=304,Go=306,Ji=1e3,cn=1001,Wo=1002,Zt=1003,Ed=1004,aE=1004,wa=1005,oE=1005,At=1006,Xo=1007,lE=1007,qn=1008,cE=1008,hn=1009,Dm=1010,Nm=1011,jo=1012,Td=1013,Zn=1014,Pi=1015,_i=1016,Cd=1017,Ad=1018,Dr=1020,km=35902,Om=35899,Um=1021,Bm=1022,qi=1023,Ds=1026,Ns=1027,Mc=1028,Sc=1029,Ea=1030,Pd=1031,hE=1032,Rd=1033,wc=33776,Ec=33777,Tc=33778,Cc=33779,Id=35840,Ld=35841,Dd=35842,Nd=35843,kd=36196,Od=37492,Ud=37496,Bd=37488,Fd=37489,zd=37490,Hd=37491,Vd=37808,Gd=37809,Wd=37810,Xd=37811,jd=37812,qd=37813,Zd=37814,Yd=37815,$d=37816,Kd=37817,Jd=37818,Qd=37819,eu=37820,tu=37821,iu=36492,nu=36494,su=36495,ru=36283,au=36284,ou=36285,lu=36286,By=2200,Fy=2201,zy=2202,qo=2300,Zo=2301,cu=2302,Fm=2303,Ta=2400,Ca=2401,Ac=2402,hu=2500,zm=2501,Hy=0,Hm=1,du=2,Vy=3200,dE=3201,uE=3202,pE=3203,Nr=0,Gy=1,Ys="",li="srgb",Zi="srgb-linear",Pc="linear",Bt="srgb",fE="",mE="rg",gE="ga",vE=0,Aa=7680,yE=7681,xE=7682,_E=7683,bE=34055,ME=34056,SE=5386,wE=512,EE=513,TE=514,CE=515,AE=516,PE=517,RE=518,Vm=519,Wy=512,Xy=513,jy=514,uu=515,qy=516,Zy=517,pu=518,Yy=519,Rc=35044,IE=35048,LE=35040,DE=35045,NE=35049,kE=35041,OE=35046,UE=35050,BE=35042,FE="100",Gm="300 es",Nn=2e3,Pa=2001,zE={COMPUTE:"compute",RENDER:"render"},HE={PERSPECTIVE:"perspective",LINEAR:"linear",FLAT:"flat"},VE={NORMAL:"normal",CENTROID:"centroid",SAMPLE:"sample",FIRST:"first",EITHER:"either"},GE={TEXTURE_COMPARE:"depthTextureCompare"};function WE(s){for(let e=s.length-1;e>=0;--e)if(s[e]>=65535)return!0;return!1}const XE={Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array};function Yo(s,e){return new XE[s](e)}function $y(s){return ArrayBuffer.isView(s)&&!(s instanceof DataView)}function Ic(s){return document.createElementNS("http://www.w3.org/1999/xhtml",s)}function Ky(){const s=Ic("canvas");return s.style.display="block",s}const Jy={};let kr=null;function jE(s){kr=s}function qE(){return kr}function Lc(...s){const e="THREE."+s.shift();kr?kr("log",e,...s):console.log(e,...s)}function Qy(s){const e=s[0];if(typeof e=="string"&&e.startsWith("TSL:")){const t=s[1];t&&t.isStackTrace?s[0]+=" "+t.getLocation():s[1]='Stack trace not available. Enable "THREE.Node.captureStackTrace" to capture stack traces.'}return s}function Ye(...s){s=Qy(s);const e="THREE."+s.shift();if(kr)kr("warn",e,...s);else{const t=s[0];t&&t.isStackTrace?console.warn(t.getError(e)):console.warn(e,...s)}}function lt(...s){s=Qy(s);const e="THREE."+s.shift();if(kr)kr("error",e,...s);else{const t=s[0];t&&t.isStackTrace?console.error(t.getError(e)):console.error(e,...s)}}function Dc(...s){const e=s.join(" ");e in Jy||(Jy[e]=!0,Ye(...s))}function ZE(s,e,t){return new Promise(function(i,n){function r(){switch(s.clientWaitSync(e,s.SYNC_FLUSH_COMMANDS_BIT,0)){case s.WAIT_FAILED:n();break;case s.TIMEOUT_EXPIRED:setTimeout(r,t);break;default:i()}}setTimeout(r,t)})}const YE={[dd]:ud,[pd]:gd,[fd]:vd,[Ma]:md,[ud]:dd,[gd]:pd,[vd]:fd,[md]:Ma};class hs{addEventListener(e,t){this._listeners===void 0&&(this._listeners={});const i=this._listeners;i[e]===void 0&&(i[e]=[]),i[e].indexOf(t)===-1&&i[e].push(t)}hasEventListener(e,t){const i=this._listeners;return i===void 0?!1:i[e]!==void 0&&i[e].indexOf(t)!==-1}removeEventListener(e,t){const i=this._listeners;if(i===void 0)return;const n=i[e];if(n!==void 0){const r=n.indexOf(t);r!==-1&&n.splice(r,1)}}dispatchEvent(e){const t=this._listeners;if(t===void 0)return;const i=t[e.type];if(i!==void 0){e.target=this;const n=i.slice(0);for(let r=0,a=n.length;r>8&255]+Qi[s>>16&255]+Qi[s>>24&255]+"-"+Qi[e&255]+Qi[e>>8&255]+"-"+Qi[e>>16&15|64]+Qi[e>>24&255]+"-"+Qi[t&63|128]+Qi[t>>8&255]+"-"+Qi[t>>16&255]+Qi[t>>24&255]+Qi[i&255]+Qi[i>>8&255]+Qi[i>>16&255]+Qi[i>>24&255]).toLowerCase()}function dt(s,e,t){return Math.max(e,Math.min(t,s))}function Wm(s,e){return(s%e+e)%e}function $E(s,e,t,i,n){return i+(s-e)*(n-i)/(t-e)}function KE(s,e,t){return s!==e?(t-s)/(e-s):0}function Nc(s,e,t){return(1-t)*s+t*e}function JE(s,e,t,i){return Nc(s,e,1-Math.exp(-t*i))}function QE(s,e=1){return e-Math.abs(Wm(s,e*2)-e)}function e3(s,e,t){return s<=e?0:s>=t?1:(s=(s-e)/(t-e),s*s*(3-2*s))}function t3(s,e,t){return s<=e?0:s>=t?1:(s=(s-e)/(t-e),s*s*s*(s*(s*6-15)+10))}function i3(s,e){return s+Math.floor(Math.random()*(e-s+1))}function n3(s,e){return s+Math.random()*(e-s)}function s3(s){return s*(.5-Math.random())}function r3(s){s!==void 0&&(ex=s);let e=ex+=1831565813;return e=Math.imul(e^e>>>15,e|1),e^=e+Math.imul(e^e>>>7,e|61),((e^e>>>14)>>>0)/4294967296}function a3(s){return s*Ra}function o3(s){return s*$o}function l3(s){return(s&s-1)===0&&s!==0}function c3(s){return Math.pow(2,Math.ceil(Math.log(s)/Math.LN2))}function h3(s){return Math.pow(2,Math.floor(Math.log(s)/Math.LN2))}function d3(s,e,t,i,n){const r=Math.cos,a=Math.sin,o=r(t/2),l=a(t/2),c=r((e+i)/2),h=a((e+i)/2),d=r((e-i)/2),p=a((e-i)/2),u=r((i-e)/2),v=a((i-e)/2);switch(n){case"XYX":s.set(o*h,l*d,l*p,o*c);break;case"YZY":s.set(l*p,o*h,l*d,o*c);break;case"ZXZ":s.set(l*d,l*p,o*h,o*c);break;case"XZX":s.set(o*h,l*v,l*u,o*c);break;case"YXY":s.set(l*u,o*h,l*v,o*c);break;case"ZYZ":s.set(l*v,l*u,o*h,o*c);break;default:Ye("MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: "+n)}}function dn(s,e){switch(e.constructor){case Float32Array:return s;case Uint32Array:return s/4294967295;case Uint16Array:return s/65535;case Uint8Array:return s/255;case Int32Array:return Math.max(s/2147483647,-1);case Int16Array:return Math.max(s/32767,-1);case Int8Array:return Math.max(s/127,-1);default:throw new Error("Invalid component type.")}}function gt(s,e){switch(e.constructor){case Float32Array:return s;case Uint32Array:return Math.round(s*4294967295);case Uint16Array:return Math.round(s*65535);case Uint8Array:return Math.round(s*255);case Int32Array:return Math.round(s*2147483647);case Int16Array:return Math.round(s*32767);case Int8Array:return Math.round(s*127);default:throw new Error("Invalid component type.")}}const Lt={DEG2RAD:Ra,RAD2DEG:$o,generateUUID:kn,clamp:dt,euclideanModulo:Wm,mapLinear:$E,inverseLerp:KE,lerp:Nc,damp:JE,pingpong:QE,smoothstep:e3,smootherstep:t3,randInt:i3,randFloat:n3,randFloatSpread:s3,seededRandom:r3,degToRad:a3,radToDeg:o3,isPowerOfTwo:l3,ceilPowerOfTwo:c3,floorPowerOfTwo:h3,setQuaternionFromProperEuler:d3,normalize:gt,denormalize:dn};class me{constructor(e=0,t=0){me.prototype.isVector2=!0,this.x=e,this.y=t}get width(){return this.x}set width(e){this.x=e}get height(){return this.y}set height(e){this.y=e}set(e,t){return this.x=e,this.y=t,this}setScalar(e){return this.x=e,this.y=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y)}copy(e){return this.x=e.x,this.y=e.y,this}add(e){return this.x+=e.x,this.y+=e.y,this}addScalar(e){return this.x+=e,this.y+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this}subScalar(e){return this.x-=e,this.y-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this}multiply(e){return this.x*=e.x,this.y*=e.y,this}multiplyScalar(e){return this.x*=e,this.y*=e,this}divide(e){return this.x/=e.x,this.y/=e.y,this}divideScalar(e){return this.multiplyScalar(1/e)}applyMatrix3(e){const t=this.x,i=this.y,n=e.elements;return this.x=n[0]*t+n[3]*i+n[6],this.y=n[1]*t+n[4]*i+n[7],this}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this}clamp(e,t){return this.x=dt(this.x,e.x,t.x),this.y=dt(this.y,e.y,t.y),this}clampScalar(e,t){return this.x=dt(this.x,e,t),this.y=dt(this.y,e,t),this}clampLength(e,t){const i=this.length();return this.divideScalar(i||1).multiplyScalar(dt(i,e,t))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this}negate(){return this.x=-this.x,this.y=-this.y,this}dot(e){return this.x*e.x+this.y*e.y}cross(e){return this.x*e.y-this.y*e.x}lengthSq(){return this.x*this.x+this.y*this.y}length(){return Math.sqrt(this.x*this.x+this.y*this.y)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)}normalize(){return this.divideScalar(this.length()||1)}angle(){return Math.atan2(-this.y,-this.x)+Math.PI}angleTo(e){const t=Math.sqrt(this.lengthSq()*e.lengthSq());if(t===0)return Math.PI/2;const i=this.dot(e)/t;return Math.acos(dt(i,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){const t=this.x-e.x,i=this.y-e.y;return t*t+i*i}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this}lerpVectors(e,t,i){return this.x=e.x+(t.x-e.x)*i,this.y=e.y+(t.y-e.y)*i,this}equals(e){return e.x===this.x&&e.y===this.y}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this}rotateAround(e,t){const i=Math.cos(t),n=Math.sin(t),r=this.x-e.x,a=this.y-e.y;return this.x=r*i-a*n+e.x,this.y=r*n+a*i+e.y,this}random(){return this.x=Math.random(),this.y=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y}}class Kt{constructor(e=0,t=0,i=0,n=1){this.isQuaternion=!0,this._x=e,this._y=t,this._z=i,this._w=n}static slerpFlat(e,t,i,n,r,a,o){let l=i[n+0],c=i[n+1],h=i[n+2],d=i[n+3],p=r[a+0],u=r[a+1],v=r[a+2],g=r[a+3];if(d!==g||l!==p||c!==u||h!==v){let m=l*p+c*u+h*v+d*g;m<0&&(p=-p,u=-u,v=-v,g=-g,m=-m);let f=1-o;if(m<.9995){const y=Math.acos(m),x=Math.sin(y);f=Math.sin(f*y)/x,o=Math.sin(o*y)/x,l=l*f+p*o,c=c*f+u*o,h=h*f+v*o,d=d*f+g*o}else{l=l*f+p*o,c=c*f+u*o,h=h*f+v*o,d=d*f+g*o;const y=1/Math.sqrt(l*l+c*c+h*h+d*d);l*=y,c*=y,h*=y,d*=y}}e[t]=l,e[t+1]=c,e[t+2]=h,e[t+3]=d}static multiplyQuaternionsFlat(e,t,i,n,r,a){const o=i[n],l=i[n+1],c=i[n+2],h=i[n+3],d=r[a],p=r[a+1],u=r[a+2],v=r[a+3];return e[t]=o*v+h*d+l*u-c*p,e[t+1]=l*v+h*p+c*d-o*u,e[t+2]=c*v+h*u+o*p-l*d,e[t+3]=h*v-o*d-l*p-c*u,e}get x(){return this._x}set x(e){this._x=e,this._onChangeCallback()}get y(){return this._y}set y(e){this._y=e,this._onChangeCallback()}get z(){return this._z}set z(e){this._z=e,this._onChangeCallback()}get w(){return this._w}set w(e){this._w=e,this._onChangeCallback()}set(e,t,i,n){return this._x=e,this._y=t,this._z=i,this._w=n,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._w)}copy(e){return this._x=e.x,this._y=e.y,this._z=e.z,this._w=e.w,this._onChangeCallback(),this}setFromEuler(e,t=!0){const i=e._x,n=e._y,r=e._z,a=e._order,o=Math.cos,l=Math.sin,c=o(i/2),h=o(n/2),d=o(r/2),p=l(i/2),u=l(n/2),v=l(r/2);switch(a){case"XYZ":this._x=p*h*d+c*u*v,this._y=c*u*d-p*h*v,this._z=c*h*v+p*u*d,this._w=c*h*d-p*u*v;break;case"YXZ":this._x=p*h*d+c*u*v,this._y=c*u*d-p*h*v,this._z=c*h*v-p*u*d,this._w=c*h*d+p*u*v;break;case"ZXY":this._x=p*h*d-c*u*v,this._y=c*u*d+p*h*v,this._z=c*h*v+p*u*d,this._w=c*h*d-p*u*v;break;case"ZYX":this._x=p*h*d-c*u*v,this._y=c*u*d+p*h*v,this._z=c*h*v-p*u*d,this._w=c*h*d+p*u*v;break;case"YZX":this._x=p*h*d+c*u*v,this._y=c*u*d+p*h*v,this._z=c*h*v-p*u*d,this._w=c*h*d-p*u*v;break;case"XZY":this._x=p*h*d-c*u*v,this._y=c*u*d-p*h*v,this._z=c*h*v+p*u*d,this._w=c*h*d+p*u*v;break;default:Ye("Quaternion: .setFromEuler() encountered an unknown order: "+a)}return t===!0&&this._onChangeCallback(),this}setFromAxisAngle(e,t){const i=t/2,n=Math.sin(i);return this._x=e.x*n,this._y=e.y*n,this._z=e.z*n,this._w=Math.cos(i),this._onChangeCallback(),this}setFromRotationMatrix(e){const t=e.elements,i=t[0],n=t[4],r=t[8],a=t[1],o=t[5],l=t[9],c=t[2],h=t[6],d=t[10],p=i+o+d;if(p>0){const u=.5/Math.sqrt(p+1);this._w=.25/u,this._x=(h-l)*u,this._y=(r-c)*u,this._z=(a-n)*u}else if(i>o&&i>d){const u=2*Math.sqrt(1+i-o-d);this._w=(h-l)/u,this._x=.25*u,this._y=(n+a)/u,this._z=(r+c)/u}else if(o>d){const u=2*Math.sqrt(1+o-i-d);this._w=(r-c)/u,this._x=(n+a)/u,this._y=.25*u,this._z=(l+h)/u}else{const u=2*Math.sqrt(1+d-i-o);this._w=(a-n)/u,this._x=(r+c)/u,this._y=(l+h)/u,this._z=.25*u}return this._onChangeCallback(),this}setFromUnitVectors(e,t){let i=e.dot(t)+1;return i<1e-8?(i=0,Math.abs(e.x)>Math.abs(e.z)?(this._x=-e.y,this._y=e.x,this._z=0,this._w=i):(this._x=0,this._y=-e.z,this._z=e.y,this._w=i)):(this._x=e.y*t.z-e.z*t.y,this._y=e.z*t.x-e.x*t.z,this._z=e.x*t.y-e.y*t.x,this._w=i),this.normalize()}angleTo(e){return 2*Math.acos(Math.abs(dt(this.dot(e),-1,1)))}rotateTowards(e,t){const i=this.angleTo(e);if(i===0)return this;const n=Math.min(1,t/i);return this.slerp(e,n),this}identity(){return this.set(0,0,0,1)}invert(){return this.conjugate()}conjugate(){return this._x*=-1,this._y*=-1,this._z*=-1,this._onChangeCallback(),this}dot(e){return this._x*e._x+this._y*e._y+this._z*e._z+this._w*e._w}lengthSq(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w}length(){return Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w)}normalize(){let e=this.length();return e===0?(this._x=0,this._y=0,this._z=0,this._w=1):(e=1/e,this._x=this._x*e,this._y=this._y*e,this._z=this._z*e,this._w=this._w*e),this._onChangeCallback(),this}multiply(e){return this.multiplyQuaternions(this,e)}premultiply(e){return this.multiplyQuaternions(e,this)}multiplyQuaternions(e,t){const i=e._x,n=e._y,r=e._z,a=e._w,o=t._x,l=t._y,c=t._z,h=t._w;return this._x=i*h+a*o+n*c-r*l,this._y=n*h+a*l+r*o-i*c,this._z=r*h+a*c+i*l-n*o,this._w=a*h-i*o-n*l-r*c,this._onChangeCallback(),this}slerp(e,t){let i=e._x,n=e._y,r=e._z,a=e._w,o=this.dot(e);o<0&&(i=-i,n=-n,r=-r,a=-a,o=-o);let l=1-t;if(o<.9995){const c=Math.acos(o),h=Math.sin(c);l=Math.sin(l*c)/h,t=Math.sin(t*c)/h,this._x=this._x*l+i*t,this._y=this._y*l+n*t,this._z=this._z*l+r*t,this._w=this._w*l+a*t,this._onChangeCallback()}else this._x=this._x*l+i*t,this._y=this._y*l+n*t,this._z=this._z*l+r*t,this._w=this._w*l+a*t,this.normalize();return this}slerpQuaternions(e,t,i){return this.copy(e).slerp(t,i)}random(){const e=2*Math.PI*Math.random(),t=2*Math.PI*Math.random(),i=Math.random(),n=Math.sqrt(1-i),r=Math.sqrt(i);return this.set(n*Math.sin(e),n*Math.cos(e),r*Math.sin(t),r*Math.cos(t))}equals(e){return e._x===this._x&&e._y===this._y&&e._z===this._z&&e._w===this._w}fromArray(e,t=0){return this._x=e[t],this._y=e[t+1],this._z=e[t+2],this._w=e[t+3],this._onChangeCallback(),this}toArray(e=[],t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,e[t+3]=this._w,e}fromBufferAttribute(e,t){return this._x=e.getX(t),this._y=e.getY(t),this._z=e.getZ(t),this._w=e.getW(t),this._onChangeCallback(),this}toJSON(){return this.toArray()}_onChange(e){return this._onChangeCallback=e,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._w}}class R{constructor(e=0,t=0,i=0){R.prototype.isVector3=!0,this.x=e,this.y=t,this.z=i}set(e,t,i){return i===void 0&&(i=this.z),this.x=e,this.y=t,this.z=i,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;case 2:this.z=t;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y,this.z)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this.z=e.z+t.z,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this.z+=e.z*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this.z=e.z-t.z,this}multiply(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this}multiplyVectors(e,t){return this.x=e.x*t.x,this.y=e.y*t.y,this.z=e.z*t.z,this}applyEuler(e){return this.applyQuaternion(tx.setFromEuler(e))}applyAxisAngle(e,t){return this.applyQuaternion(tx.setFromAxisAngle(e,t))}applyMatrix3(e){const t=this.x,i=this.y,n=this.z,r=e.elements;return this.x=r[0]*t+r[3]*i+r[6]*n,this.y=r[1]*t+r[4]*i+r[7]*n,this.z=r[2]*t+r[5]*i+r[8]*n,this}applyNormalMatrix(e){return this.applyMatrix3(e).normalize()}applyMatrix4(e){const t=this.x,i=this.y,n=this.z,r=e.elements,a=1/(r[3]*t+r[7]*i+r[11]*n+r[15]);return this.x=(r[0]*t+r[4]*i+r[8]*n+r[12])*a,this.y=(r[1]*t+r[5]*i+r[9]*n+r[13])*a,this.z=(r[2]*t+r[6]*i+r[10]*n+r[14])*a,this}applyQuaternion(e){const t=this.x,i=this.y,n=this.z,r=e.x,a=e.y,o=e.z,l=e.w,c=2*(a*n-o*i),h=2*(o*t-r*n),d=2*(r*i-a*t);return this.x=t+l*c+a*d-o*h,this.y=i+l*h+o*c-r*d,this.z=n+l*d+r*h-a*c,this}project(e){return this.applyMatrix4(e.matrixWorldInverse).applyMatrix4(e.projectionMatrix)}unproject(e){return this.applyMatrix4(e.projectionMatrixInverse).applyMatrix4(e.matrixWorld)}transformDirection(e){const t=this.x,i=this.y,n=this.z,r=e.elements;return this.x=r[0]*t+r[4]*i+r[8]*n,this.y=r[1]*t+r[5]*i+r[9]*n,this.z=r[2]*t+r[6]*i+r[10]*n,this.normalize()}divide(e){return this.x/=e.x,this.y/=e.y,this.z/=e.z,this}divideScalar(e){return this.multiplyScalar(1/e)}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this.z=Math.min(this.z,e.z),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this.z=Math.max(this.z,e.z),this}clamp(e,t){return this.x=dt(this.x,e.x,t.x),this.y=dt(this.y,e.y,t.y),this.z=dt(this.z,e.z,t.z),this}clampScalar(e,t){return this.x=dt(this.x,e,t),this.y=dt(this.y,e,t),this.z=dt(this.z,e,t),this}clampLength(e,t){const i=this.length();return this.divideScalar(i||1).multiplyScalar(dt(i,e,t))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)}normalize(){return this.divideScalar(this.length()||1)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this.z+=(e.z-this.z)*t,this}lerpVectors(e,t,i){return this.x=e.x+(t.x-e.x)*i,this.y=e.y+(t.y-e.y)*i,this.z=e.z+(t.z-e.z)*i,this}cross(e){return this.crossVectors(this,e)}crossVectors(e,t){const i=e.x,n=e.y,r=e.z,a=t.x,o=t.y,l=t.z;return this.x=n*l-r*o,this.y=r*a-i*l,this.z=i*o-n*a,this}projectOnVector(e){const t=e.lengthSq();if(t===0)return this.set(0,0,0);const i=e.dot(this)/t;return this.copy(e).multiplyScalar(i)}projectOnPlane(e){return Xm.copy(this).projectOnVector(e),this.sub(Xm)}reflect(e){return this.sub(Xm.copy(e).multiplyScalar(2*this.dot(e)))}angleTo(e){const t=Math.sqrt(this.lengthSq()*e.lengthSq());if(t===0)return Math.PI/2;const i=this.dot(e)/t;return Math.acos(dt(i,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){const t=this.x-e.x,i=this.y-e.y,n=this.z-e.z;return t*t+i*i+n*n}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)+Math.abs(this.z-e.z)}setFromSpherical(e){return this.setFromSphericalCoords(e.radius,e.phi,e.theta)}setFromSphericalCoords(e,t,i){const n=Math.sin(t)*e;return this.x=n*Math.sin(i),this.y=Math.cos(t)*e,this.z=n*Math.cos(i),this}setFromCylindrical(e){return this.setFromCylindricalCoords(e.radius,e.theta,e.y)}setFromCylindricalCoords(e,t,i){return this.x=e*Math.sin(t),this.y=i,this.z=e*Math.cos(t),this}setFromMatrixPosition(e){const t=e.elements;return this.x=t[12],this.y=t[13],this.z=t[14],this}setFromMatrixScale(e){const t=this.setFromMatrixColumn(e,0).length(),i=this.setFromMatrixColumn(e,1).length(),n=this.setFromMatrixColumn(e,2).length();return this.x=t,this.y=i,this.z=n,this}setFromMatrixColumn(e,t){return this.fromArray(e.elements,t*4)}setFromMatrix3Column(e,t){return this.fromArray(e.elements,t*3)}setFromEuler(e){return this.x=e._x,this.y=e._y,this.z=e._z,this}setFromColor(e){return this.x=e.r,this.y=e.g,this.z=e.b,this}equals(e){return e.x===this.x&&e.y===this.y&&e.z===this.z}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this.z=e[t+2],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e[t+2]=this.z,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this.z=e.getZ(t),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this}randomDirection(){const e=Math.random()*Math.PI*2,t=Math.random()*2-1,i=Math.sqrt(1-t*t);return this.x=i*Math.cos(e),this.y=t,this.z=i*Math.sin(e),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z}}const Xm=new R,tx=new Kt;class ft{constructor(e,t,i,n,r,a,o,l,c){ft.prototype.isMatrix3=!0,this.elements=[1,0,0,0,1,0,0,0,1],e!==void 0&&this.set(e,t,i,n,r,a,o,l,c)}set(e,t,i,n,r,a,o,l,c){const h=this.elements;return h[0]=e,h[1]=n,h[2]=o,h[3]=t,h[4]=r,h[5]=l,h[6]=i,h[7]=a,h[8]=c,this}identity(){return this.set(1,0,0,0,1,0,0,0,1),this}copy(e){const t=this.elements,i=e.elements;return t[0]=i[0],t[1]=i[1],t[2]=i[2],t[3]=i[3],t[4]=i[4],t[5]=i[5],t[6]=i[6],t[7]=i[7],t[8]=i[8],this}extractBasis(e,t,i){return e.setFromMatrix3Column(this,0),t.setFromMatrix3Column(this,1),i.setFromMatrix3Column(this,2),this}setFromMatrix4(e){const t=e.elements;return this.set(t[0],t[4],t[8],t[1],t[5],t[9],t[2],t[6],t[10]),this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,t){const i=e.elements,n=t.elements,r=this.elements,a=i[0],o=i[3],l=i[6],c=i[1],h=i[4],d=i[7],p=i[2],u=i[5],v=i[8],g=n[0],m=n[3],f=n[6],y=n[1],x=n[4],_=n[7],S=n[2],b=n[5],E=n[8];return r[0]=a*g+o*y+l*S,r[3]=a*m+o*x+l*b,r[6]=a*f+o*_+l*E,r[1]=c*g+h*y+d*S,r[4]=c*m+h*x+d*b,r[7]=c*f+h*_+d*E,r[2]=p*g+u*y+v*S,r[5]=p*m+u*x+v*b,r[8]=p*f+u*_+v*E,this}multiplyScalar(e){const t=this.elements;return t[0]*=e,t[3]*=e,t[6]*=e,t[1]*=e,t[4]*=e,t[7]*=e,t[2]*=e,t[5]*=e,t[8]*=e,this}determinant(){const e=this.elements,t=e[0],i=e[1],n=e[2],r=e[3],a=e[4],o=e[5],l=e[6],c=e[7],h=e[8];return t*a*h-t*o*c-i*r*h+i*o*l+n*r*c-n*a*l}invert(){const e=this.elements,t=e[0],i=e[1],n=e[2],r=e[3],a=e[4],o=e[5],l=e[6],c=e[7],h=e[8],d=h*a-o*c,p=o*l-h*r,u=c*r-a*l,v=t*d+i*p+n*u;if(v===0)return this.set(0,0,0,0,0,0,0,0,0);const g=1/v;return e[0]=d*g,e[1]=(n*c-h*i)*g,e[2]=(o*i-n*a)*g,e[3]=p*g,e[4]=(h*t-n*l)*g,e[5]=(n*r-o*t)*g,e[6]=u*g,e[7]=(i*l-c*t)*g,e[8]=(a*t-i*r)*g,this}transpose(){let e;const t=this.elements;return e=t[1],t[1]=t[3],t[3]=e,e=t[2],t[2]=t[6],t[6]=e,e=t[5],t[5]=t[7],t[7]=e,this}getNormalMatrix(e){return this.setFromMatrix4(e).invert().transpose()}transposeIntoArray(e){const t=this.elements;return e[0]=t[0],e[1]=t[3],e[2]=t[6],e[3]=t[1],e[4]=t[4],e[5]=t[7],e[6]=t[2],e[7]=t[5],e[8]=t[8],this}setUvTransform(e,t,i,n,r,a,o){const l=Math.cos(r),c=Math.sin(r);return this.set(i*l,i*c,-i*(l*a+c*o)+a+e,-n*c,n*l,-n*(-c*a+l*o)+o+t,0,0,1),this}scale(e,t){return this.premultiply(jm.makeScale(e,t)),this}rotate(e){return this.premultiply(jm.makeRotation(-e)),this}translate(e,t){return this.premultiply(jm.makeTranslation(e,t)),this}makeTranslation(e,t){return e.isVector2?this.set(1,0,e.x,0,1,e.y,0,0,1):this.set(1,0,e,0,1,t,0,0,1),this}makeRotation(e){const t=Math.cos(e),i=Math.sin(e);return this.set(t,-i,0,i,t,0,0,0,1),this}makeScale(e,t){return this.set(e,0,0,0,t,0,0,0,1),this}equals(e){const t=this.elements,i=e.elements;for(let n=0;n<9;n++)if(t[n]!==i[n])return!1;return!0}fromArray(e,t=0){for(let i=0;i<9;i++)this.elements[i]=e[i+t];return this}toArray(e=[],t=0){const i=this.elements;return e[t]=i[0],e[t+1]=i[1],e[t+2]=i[2],e[t+3]=i[3],e[t+4]=i[4],e[t+5]=i[5],e[t+6]=i[6],e[t+7]=i[7],e[t+8]=i[8],e}clone(){return new this.constructor().fromArray(this.elements)}}const jm=new ft,ix=new ft().set(.4123908,.3575843,.1804808,.212639,.7151687,.0721923,.0193308,.1191948,.9505322),nx=new ft().set(3.2409699,-1.5373832,-.4986108,-.9692436,1.8759675,.0415551,.0556301,-.203977,1.0569715);function u3(){const s={enabled:!0,workingColorSpace:Zi,spaces:{},convert:function(n,r,a){return this.enabled===!1||r===a||!r||!a||(this.spaces[r].transfer===Bt&&(n.r=$s(n.r),n.g=$s(n.g),n.b=$s(n.b)),this.spaces[r].primaries!==this.spaces[a].primaries&&(n.applyMatrix3(this.spaces[r].toXYZ),n.applyMatrix3(this.spaces[a].fromXYZ)),this.spaces[a].transfer===Bt&&(n.r=Ko(n.r),n.g=Ko(n.g),n.b=Ko(n.b))),n},workingToColorSpace:function(n,r){return this.convert(n,this.workingColorSpace,r)},colorSpaceToWorking:function(n,r){return this.convert(n,r,this.workingColorSpace)},getPrimaries:function(n){return this.spaces[n].primaries},getTransfer:function(n){return n===Ys?Pc:this.spaces[n].transfer},getToneMappingMode:function(n){return this.spaces[n].outputColorSpaceConfig.toneMappingMode||"standard"},getLuminanceCoefficients:function(n,r=this.workingColorSpace){return n.fromArray(this.spaces[r].luminanceCoefficients)},define:function(n){Object.assign(this.spaces,n)},_getMatrix:function(n,r,a){return n.copy(this.spaces[r].toXYZ).multiply(this.spaces[a].fromXYZ)},_getDrawingBufferColorSpace:function(n){return this.spaces[n].outputColorSpaceConfig.drawingBufferColorSpace},_getUnpackColorSpace:function(n=this.workingColorSpace){return this.spaces[n].workingColorSpaceConfig.unpackColorSpace},fromWorkingColorSpace:function(n,r){return Dc("ColorManagement: .fromWorkingColorSpace() has been renamed to .workingToColorSpace()."),s.workingToColorSpace(n,r)},toWorkingColorSpace:function(n,r){return Dc("ColorManagement: .toWorkingColorSpace() has been renamed to .colorSpaceToWorking()."),s.colorSpaceToWorking(n,r)}},e=[.64,.33,.3,.6,.15,.06],t=[.2126,.7152,.0722],i=[.3127,.329];return s.define({[Zi]:{primaries:e,whitePoint:i,transfer:Pc,toXYZ:ix,fromXYZ:nx,luminanceCoefficients:t,workingColorSpaceConfig:{unpackColorSpace:li},outputColorSpaceConfig:{drawingBufferColorSpace:li}},[li]:{primaries:e,whitePoint:i,transfer:Bt,toXYZ:ix,fromXYZ:nx,luminanceCoefficients:t,outputColorSpaceConfig:{drawingBufferColorSpace:li}}}),s}const Et=u3();function $s(s){return s<.04045?s*.0773993808:Math.pow(s*.9478672986+.0521327014,2.4)}function Ko(s){return s<.0031308?s*12.92:1.055*Math.pow(s,.41666)-.055}let Jo;class sx{static getDataURL(e,t="image/png"){if(/^data:/i.test(e.src)||typeof HTMLCanvasElement>"u")return e.src;let i;if(e instanceof HTMLCanvasElement)i=e;else{Jo===void 0&&(Jo=Ic("canvas")),Jo.width=e.width,Jo.height=e.height;const n=Jo.getContext("2d");e instanceof ImageData?n.putImageData(e,0,0):n.drawImage(e,0,0,e.width,e.height),i=Jo}return i.toDataURL(t)}static sRGBToLinear(e){if(typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&e instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&e instanceof ImageBitmap){const t=Ic("canvas");t.width=e.width,t.height=e.height;const i=t.getContext("2d");i.drawImage(e,0,0,e.width,e.height);const n=i.getImageData(0,0,e.width,e.height),r=n.data;for(let a=0;a1),this.pmremVersion=0}get width(){return this.source.getSize(Zm).x}get height(){return this.source.getSize(Zm).y}get depth(){return this.source.getSize(Zm).z}get image(){return this.source.data}set image(e=null){this.source.data=e}updateMatrix(){this.matrix.setUvTransform(this.offset.x,this.offset.y,this.repeat.x,this.repeat.y,this.rotation,this.center.x,this.center.y)}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}clone(){return new this.constructor().copy(this)}copy(e){return this.name=e.name,this.source=e.source,this.mipmaps=e.mipmaps.slice(0),this.mapping=e.mapping,this.channel=e.channel,this.wrapS=e.wrapS,this.wrapT=e.wrapT,this.magFilter=e.magFilter,this.minFilter=e.minFilter,this.anisotropy=e.anisotropy,this.format=e.format,this.internalFormat=e.internalFormat,this.type=e.type,this.offset.copy(e.offset),this.repeat.copy(e.repeat),this.center.copy(e.center),this.rotation=e.rotation,this.matrixAutoUpdate=e.matrixAutoUpdate,this.matrix.copy(e.matrix),this.generateMipmaps=e.generateMipmaps,this.premultiplyAlpha=e.premultiplyAlpha,this.flipY=e.flipY,this.unpackAlignment=e.unpackAlignment,this.colorSpace=e.colorSpace,this.renderTarget=e.renderTarget,this.isRenderTargetTexture=e.isRenderTargetTexture,this.isArrayTexture=e.isArrayTexture,this.userData=JSON.parse(JSON.stringify(e.userData)),this.needsUpdate=!0,this}setValues(e){for(const t in e){const i=e[t];if(i===void 0){Ye(`Texture.setValues(): parameter '${t}' has value of undefined.`);continue}const n=this[t];if(n===void 0){Ye(`Texture.setValues(): property '${t}' does not exist.`);continue}n&&i&&n.isVector2&&i.isVector2||n&&i&&n.isVector3&&i.isVector3||n&&i&&n.isMatrix3&&i.isMatrix3?n.copy(i):this[t]=i}}toJSON(e){const t=e===void 0||typeof e=="string";if(!t&&e.textures[this.uuid]!==void 0)return e.textures[this.uuid];const i={metadata:{version:4.7,type:"Texture",generator:"Texture.toJSON"},uuid:this.uuid,name:this.name,image:this.source.toJSON(e).uuid,mapping:this.mapping,channel:this.channel,repeat:[this.repeat.x,this.repeat.y],offset:[this.offset.x,this.offset.y],center:[this.center.x,this.center.y],rotation:this.rotation,wrap:[this.wrapS,this.wrapT],format:this.format,internalFormat:this.internalFormat,type:this.type,colorSpace:this.colorSpace,minFilter:this.minFilter,magFilter:this.magFilter,anisotropy:this.anisotropy,flipY:this.flipY,generateMipmaps:this.generateMipmaps,premultiplyAlpha:this.premultiplyAlpha,unpackAlignment:this.unpackAlignment};return Object.keys(this.userData).length>0&&(i.userData=this.userData),t||(e.textures[this.uuid]=i),i}dispose(){this.dispatchEvent({type:"dispose"})}transformUv(e){if(this.mapping!==wd)return e;if(e.applyMatrix3(this.matrix),e.x<0||e.x>1)switch(this.wrapS){case Ji:e.x=e.x-Math.floor(e.x);break;case cn:e.x=e.x<0?0:1;break;case Wo:Math.abs(Math.floor(e.x)%2)===1?e.x=Math.ceil(e.x)-e.x:e.x=e.x-Math.floor(e.x);break}if(e.y<0||e.y>1)switch(this.wrapT){case Ji:e.y=e.y-Math.floor(e.y);break;case cn:e.y=e.y<0?0:1;break;case Wo:Math.abs(Math.floor(e.y)%2)===1?e.y=Math.ceil(e.y)-e.y:e.y=e.y-Math.floor(e.y);break}return this.flipY&&(e.y=1-e.y),e}set needsUpdate(e){e===!0&&(this.version++,this.source.needsUpdate=!0)}set needsPMREMUpdate(e){e===!0&&this.pmremVersion++}}ei.DEFAULT_IMAGE=null,ei.DEFAULT_MAPPING=wd,ei.DEFAULT_ANISOTROPY=1;class Pt{constructor(e=0,t=0,i=0,n=1){Pt.prototype.isVector4=!0,this.x=e,this.y=t,this.z=i,this.w=n}get width(){return this.z}set width(e){this.z=e}get height(){return this.w}set height(e){this.w=e}set(e,t,i,n){return this.x=e,this.y=t,this.z=i,this.w=n,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this.w=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setW(e){return this.w=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;case 2:this.z=t;break;case 3:this.w=t;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;case 3:return this.w;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y,this.z,this.w)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this.w=e.w!==void 0?e.w:1,this}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this.w+=e.w,this}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this.w+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this.z=e.z+t.z,this.w=e.w+t.w,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this.z+=e.z*t,this.w+=e.w*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this.w-=e.w,this}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this.w-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this.z=e.z-t.z,this.w=e.w-t.w,this}multiply(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this.w*=e.w,this}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this.w*=e,this}applyMatrix4(e){const t=this.x,i=this.y,n=this.z,r=this.w,a=e.elements;return this.x=a[0]*t+a[4]*i+a[8]*n+a[12]*r,this.y=a[1]*t+a[5]*i+a[9]*n+a[13]*r,this.z=a[2]*t+a[6]*i+a[10]*n+a[14]*r,this.w=a[3]*t+a[7]*i+a[11]*n+a[15]*r,this}divide(e){return this.x/=e.x,this.y/=e.y,this.z/=e.z,this.w/=e.w,this}divideScalar(e){return this.multiplyScalar(1/e)}setAxisAngleFromQuaternion(e){this.w=2*Math.acos(e.w);const t=Math.sqrt(1-e.w*e.w);return t<1e-4?(this.x=1,this.y=0,this.z=0):(this.x=e.x/t,this.y=e.y/t,this.z=e.z/t),this}setAxisAngleFromRotationMatrix(e){let t,i,n,r;const l=e.elements,c=l[0],h=l[4],d=l[8],p=l[1],u=l[5],v=l[9],g=l[2],m=l[6],f=l[10];if(Math.abs(h-p)<.01&&Math.abs(d-g)<.01&&Math.abs(v-m)<.01){if(Math.abs(h+p)<.1&&Math.abs(d+g)<.1&&Math.abs(v+m)<.1&&Math.abs(c+u+f-3)<.1)return this.set(1,0,0,0),this;t=Math.PI;const x=(c+1)/2,_=(u+1)/2,S=(f+1)/2,b=(h+p)/4,E=(d+g)/4,w=(v+m)/4;return x>_&&x>S?x<.01?(i=0,n=.707106781,r=.707106781):(i=Math.sqrt(x),n=b/i,r=E/i):_>S?_<.01?(i=.707106781,n=0,r=.707106781):(n=Math.sqrt(_),i=b/n,r=w/n):S<.01?(i=.707106781,n=.707106781,r=0):(r=Math.sqrt(S),i=E/r,n=w/r),this.set(i,n,r,t),this}let y=Math.sqrt((m-v)*(m-v)+(d-g)*(d-g)+(p-h)*(p-h));return Math.abs(y)<.001&&(y=1),this.x=(m-v)/y,this.y=(d-g)/y,this.z=(p-h)/y,this.w=Math.acos((c+u+f-1)/2),this}setFromMatrixPosition(e){const t=e.elements;return this.x=t[12],this.y=t[13],this.z=t[14],this.w=t[15],this}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this.z=Math.min(this.z,e.z),this.w=Math.min(this.w,e.w),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this.z=Math.max(this.z,e.z),this.w=Math.max(this.w,e.w),this}clamp(e,t){return this.x=dt(this.x,e.x,t.x),this.y=dt(this.y,e.y,t.y),this.z=dt(this.z,e.z,t.z),this.w=dt(this.w,e.w,t.w),this}clampScalar(e,t){return this.x=dt(this.x,e,t),this.y=dt(this.y,e,t),this.z=dt(this.z,e,t),this.w=dt(this.w,e,t),this}clampLength(e,t){const i=this.length();return this.divideScalar(i||1).multiplyScalar(dt(i,e,t))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this.w=Math.floor(this.w),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this.w=Math.ceil(this.w),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this.w=Math.round(this.w),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this.w=Math.trunc(this.w),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this.w=-this.w,this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z+this.w*e.w}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)+Math.abs(this.w)}normalize(){return this.divideScalar(this.length()||1)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this.z+=(e.z-this.z)*t,this.w+=(e.w-this.w)*t,this}lerpVectors(e,t,i){return this.x=e.x+(t.x-e.x)*i,this.y=e.y+(t.y-e.y)*i,this.z=e.z+(t.z-e.z)*i,this.w=e.w+(t.w-e.w)*i,this}equals(e){return e.x===this.x&&e.y===this.y&&e.z===this.z&&e.w===this.w}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this.z=e[t+2],this.w=e[t+3],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e[t+2]=this.z,e[t+3]=this.w,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this.z=e.getZ(t),this.w=e.getW(t),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this.w=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z,yield this.w}}class Ym extends hs{constructor(e=1,t=1,i={}){super(),i=Object.assign({generateMipmaps:!1,internalFormat:null,minFilter:At,depthBuffer:!0,stencilBuffer:!1,resolveDepthBuffer:!0,resolveStencilBuffer:!0,depthTexture:null,samples:0,count:1,depth:1,multiview:!1},i),this.isRenderTarget=!0,this.width=e,this.height=t,this.depth=i.depth,this.scissor=new Pt(0,0,e,t),this.scissorTest=!1,this.viewport=new Pt(0,0,e,t),this.textures=[];const n={width:e,height:t,depth:i.depth},r=new ei(n),a=i.count;for(let o=0;o1);this.dispose()}this.viewport.set(0,0,e,t),this.scissor.set(0,0,e,t)}clone(){return new this.constructor().copy(this)}copy(e){this.width=e.width,this.height=e.height,this.depth=e.depth,this.scissor.copy(e.scissor),this.scissorTest=e.scissorTest,this.viewport.copy(e.viewport),this.textures.length=0;for(let t=0,i=e.textures.length;t>>0}enable(e){this.mask|=1<1){for(let t=0;t1){for(let i=0;i0&&(n.userData=this.userData),n.layers=this.layers.mask,n.matrix=this.matrix.toArray(),n.up=this.up.toArray(),this.pivot!==null&&(n.pivot=this.pivot.toArray()),this.matrixAutoUpdate===!1&&(n.matrixAutoUpdate=!1),this.morphTargetDictionary!==void 0&&(n.morphTargetDictionary=Object.assign({},this.morphTargetDictionary)),this.morphTargetInfluences!==void 0&&(n.morphTargetInfluences=this.morphTargetInfluences.slice()),this.isInstancedMesh&&(n.type="InstancedMesh",n.count=this.count,n.instanceMatrix=this.instanceMatrix.toJSON(),this.instanceColor!==null&&(n.instanceColor=this.instanceColor.toJSON())),this.isBatchedMesh&&(n.type="BatchedMesh",n.perObjectFrustumCulled=this.perObjectFrustumCulled,n.sortObjects=this.sortObjects,n.drawRanges=this._drawRanges,n.reservedRanges=this._reservedRanges,n.geometryInfo=this._geometryInfo.map(o=>({...o,boundingBox:o.boundingBox?o.boundingBox.toJSON():void 0,boundingSphere:o.boundingSphere?o.boundingSphere.toJSON():void 0})),n.instanceInfo=this._instanceInfo.map(o=>({...o})),n.availableInstanceIds=this._availableInstanceIds.slice(),n.availableGeometryIds=this._availableGeometryIds.slice(),n.nextIndexStart=this._nextIndexStart,n.nextVertexStart=this._nextVertexStart,n.geometryCount=this._geometryCount,n.maxInstanceCount=this._maxInstanceCount,n.maxVertexCount=this._maxVertexCount,n.maxIndexCount=this._maxIndexCount,n.geometryInitialized=this._geometryInitialized,n.matricesTexture=this._matricesTexture.toJSON(e),n.indirectTexture=this._indirectTexture.toJSON(e),this._colorsTexture!==null&&(n.colorsTexture=this._colorsTexture.toJSON(e)),this.boundingSphere!==null&&(n.boundingSphere=this.boundingSphere.toJSON()),this.boundingBox!==null&&(n.boundingBox=this.boundingBox.toJSON()));function r(o,l){return o[l.uuid]===void 0&&(o[l.uuid]=l.toJSON(e)),l.uuid}if(this.isScene)this.background&&(this.background.isColor?n.background=this.background.toJSON():this.background.isTexture&&(n.background=this.background.toJSON(e).uuid)),this.environment&&this.environment.isTexture&&this.environment.isRenderTargetTexture!==!0&&(n.environment=this.environment.toJSON(e).uuid);else if(this.isMesh||this.isLine||this.isPoints){n.geometry=r(e.geometries,this.geometry);const o=this.geometry.parameters;if(o!==void 0&&o.shapes!==void 0){const l=o.shapes;if(Array.isArray(l))for(let c=0,h=l.length;c0){n.children=[];for(let o=0;o0){n.animations=[];for(let o=0;o0&&(i.geometries=o),l.length>0&&(i.materials=l),c.length>0&&(i.textures=c),h.length>0&&(i.images=h),d.length>0&&(i.shapes=d),p.length>0&&(i.skeletons=p),u.length>0&&(i.animations=u),v.length>0&&(i.nodes=v)}return i.object=n,i;function a(o){const l=[];for(const c in o){const h=o[c];delete h.metadata,l.push(h)}return l}}clone(e){return new this.constructor().copy(this,e)}copy(e,t=!0){if(this.name=e.name,this.up.copy(e.up),this.position.copy(e.position),this.rotation.order=e.rotation.order,this.quaternion.copy(e.quaternion),this.scale.copy(e.scale),e.pivot!==null&&(this.pivot=e.pivot.clone()),this.matrix.copy(e.matrix),this.matrixWorld.copy(e.matrixWorld),this.matrixAutoUpdate=e.matrixAutoUpdate,this.matrixWorldAutoUpdate=e.matrixWorldAutoUpdate,this.matrixWorldNeedsUpdate=e.matrixWorldNeedsUpdate,this.layers.mask=e.layers.mask,this.visible=e.visible,this.castShadow=e.castShadow,this.receiveShadow=e.receiveShadow,this.frustumCulled=e.frustumCulled,this.renderOrder=e.renderOrder,this.static=e.static,this.animations=e.animations.slice(),this.userData=JSON.parse(JSON.stringify(e.userData)),t===!0)for(let i=0;iu+v?(c.inputState.pinching=!1,this.dispatchEvent({type:"pinchend",handedness:e.handedness,target:this})):!c.inputState.pinching&&p<=u-v&&(c.inputState.pinching=!0,this.dispatchEvent({type:"pinchstart",handedness:e.handedness,target:this}))}else l!==null&&e.gripSpace&&(r=t.getPose(e.gripSpace,i),r!==null&&(l.matrix.fromArray(r.transform.matrix),l.matrix.decompose(l.position,l.rotation,l.scale),l.matrixWorldNeedsUpdate=!0,r.linearVelocity?(l.hasLinearVelocity=!0,l.linearVelocity.copy(r.linearVelocity)):l.hasLinearVelocity=!1,r.angularVelocity?(l.hasAngularVelocity=!0,l.angularVelocity.copy(r.angularVelocity)):l.hasAngularVelocity=!1));o!==null&&(n=t.getPose(e.targetRaySpace,i),n===null&&r!==null&&(n=r),n!==null&&(o.matrix.fromArray(n.transform.matrix),o.matrix.decompose(o.position,o.rotation,o.scale),o.matrixWorldNeedsUpdate=!0,n.linearVelocity?(o.hasLinearVelocity=!0,o.linearVelocity.copy(n.linearVelocity)):o.hasLinearVelocity=!1,n.angularVelocity?(o.hasAngularVelocity=!0,o.angularVelocity.copy(n.angularVelocity)):o.hasAngularVelocity=!1,this.dispatchEvent(S3)))}return o!==null&&(o.visible=n!==null),l!==null&&(l.visible=r!==null),c!==null&&(c.visible=a!==null),this}_getHandJoint(e,t){if(e.joints[t.jointName]===void 0){const i=new pi;i.matrixAutoUpdate=!1,i.visible=!1,e.joints[t.jointName]=i,e.add(i)}return e.joints[t.jointName]}}const ux={aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,rebeccapurple:6697881,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074},Br={h:0,s:0,l:0},_u={h:0,s:0,l:0};function Km(s,e,t){return t<0&&(t+=1),t>1&&(t-=1),t<1/6?s+(e-s)*6*t:t<1/2?e:t<2/3?s+(e-s)*6*(2/3-t):s}class We{constructor(e,t,i){return this.isColor=!0,this.r=1,this.g=1,this.b=1,this.set(e,t,i)}set(e,t,i){if(t===void 0&&i===void 0){const n=e;n&&n.isColor?this.copy(n):typeof n=="number"?this.setHex(n):typeof n=="string"&&this.setStyle(n)}else this.setRGB(e,t,i);return this}setScalar(e){return this.r=e,this.g=e,this.b=e,this}setHex(e,t=li){return e=Math.floor(e),this.r=(e>>16&255)/255,this.g=(e>>8&255)/255,this.b=(e&255)/255,Et.colorSpaceToWorking(this,t),this}setRGB(e,t,i,n=Et.workingColorSpace){return this.r=e,this.g=t,this.b=i,Et.colorSpaceToWorking(this,n),this}setHSL(e,t,i,n=Et.workingColorSpace){if(e=Wm(e,1),t=dt(t,0,1),i=dt(i,0,1),t===0)this.r=this.g=this.b=i;else{const r=i<=.5?i*(1+t):i+t-i*t,a=2*i-r;this.r=Km(a,r,e+1/3),this.g=Km(a,r,e),this.b=Km(a,r,e-1/3)}return Et.colorSpaceToWorking(this,n),this}setStyle(e,t=li){function i(r){r!==void 0&&parseFloat(r)<1&&Ye("Color: Alpha component of "+e+" will be ignored.")}let n;if(n=/^(\w+)\(([^\)]*)\)/.exec(e)){let r;const a=n[1],o=n[2];switch(a){case"rgb":case"rgba":if(r=/^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return i(r[4]),this.setRGB(Math.min(255,parseInt(r[1],10))/255,Math.min(255,parseInt(r[2],10))/255,Math.min(255,parseInt(r[3],10))/255,t);if(r=/^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return i(r[4]),this.setRGB(Math.min(100,parseInt(r[1],10))/100,Math.min(100,parseInt(r[2],10))/100,Math.min(100,parseInt(r[3],10))/100,t);break;case"hsl":case"hsla":if(r=/^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return i(r[4]),this.setHSL(parseFloat(r[1])/360,parseFloat(r[2])/100,parseFloat(r[3])/100,t);break;default:Ye("Color: Unknown color model "+e)}}else if(n=/^\#([A-Fa-f\d]+)$/.exec(e)){const r=n[1],a=r.length;if(a===3)return this.setRGB(parseInt(r.charAt(0),16)/15,parseInt(r.charAt(1),16)/15,parseInt(r.charAt(2),16)/15,t);if(a===6)return this.setHex(parseInt(r,16),t);Ye("Color: Invalid hex color "+e)}else if(e&&e.length>0)return this.setColorName(e,t);return this}setColorName(e,t=li){const i=ux[e.toLowerCase()];return i!==void 0?this.setHex(i,t):Ye("Color: Unknown color "+e),this}clone(){return new this.constructor(this.r,this.g,this.b)}copy(e){return this.r=e.r,this.g=e.g,this.b=e.b,this}copySRGBToLinear(e){return this.r=$s(e.r),this.g=$s(e.g),this.b=$s(e.b),this}copyLinearToSRGB(e){return this.r=Ko(e.r),this.g=Ko(e.g),this.b=Ko(e.b),this}convertSRGBToLinear(){return this.copySRGBToLinear(this),this}convertLinearToSRGB(){return this.copyLinearToSRGB(this),this}getHex(e=li){return Et.workingToColorSpace(en.copy(this),e),Math.round(dt(en.r*255,0,255))*65536+Math.round(dt(en.g*255,0,255))*256+Math.round(dt(en.b*255,0,255))}getHexString(e=li){return("000000"+this.getHex(e).toString(16)).slice(-6)}getHSL(e,t=Et.workingColorSpace){Et.workingToColorSpace(en.copy(this),t);const i=en.r,n=en.g,r=en.b,a=Math.max(i,n,r),o=Math.min(i,n,r);let l,c;const h=(o+a)/2;if(o===a)l=0,c=0;else{const d=a-o;switch(c=h<=.5?d/(a+o):d/(2-a-o),a){case i:l=(n-r)/d+(n0&&(t.object.backgroundBlurriness=this.backgroundBlurriness),this.backgroundIntensity!==1&&(t.object.backgroundIntensity=this.backgroundIntensity),t.object.backgroundRotation=this.backgroundRotation.toArray(),this.environmentIntensity!==1&&(t.object.environmentIntensity=this.environmentIntensity),t.object.environmentRotation=this.environmentRotation.toArray(),t}}const us=new R,Js=new R,Jm=new R,Qs=new R,il=new R,nl=new R,px=new R,Qm=new R,eg=new R,tg=new R,ig=new Pt,ng=new Pt,sg=new Pt;class Ht{constructor(e=new R,t=new R,i=new R){this.a=e,this.b=t,this.c=i}static getNormal(e,t,i,n){n.subVectors(i,t),us.subVectors(e,t),n.cross(us);const r=n.lengthSq();return r>0?n.multiplyScalar(1/Math.sqrt(r)):n.set(0,0,0)}static getBarycoord(e,t,i,n,r){us.subVectors(n,t),Js.subVectors(i,t),Jm.subVectors(e,t);const a=us.dot(us),o=us.dot(Js),l=us.dot(Jm),c=Js.dot(Js),h=Js.dot(Jm),d=a*c-o*o;if(d===0)return r.set(0,0,0),null;const p=1/d,u=(c*l-o*h)*p,v=(a*h-o*l)*p;return r.set(1-u-v,v,u)}static containsPoint(e,t,i,n){return this.getBarycoord(e,t,i,n,Qs)===null?!1:Qs.x>=0&&Qs.y>=0&&Qs.x+Qs.y<=1}static getInterpolation(e,t,i,n,r,a,o,l){return this.getBarycoord(e,t,i,n,Qs)===null?(l.x=0,l.y=0,"z"in l&&(l.z=0),"w"in l&&(l.w=0),null):(l.setScalar(0),l.addScaledVector(r,Qs.x),l.addScaledVector(a,Qs.y),l.addScaledVector(o,Qs.z),l)}static getInterpolatedAttribute(e,t,i,n,r,a){return ig.setScalar(0),ng.setScalar(0),sg.setScalar(0),ig.fromBufferAttribute(e,t),ng.fromBufferAttribute(e,i),sg.fromBufferAttribute(e,n),a.setScalar(0),a.addScaledVector(ig,r.x),a.addScaledVector(ng,r.y),a.addScaledVector(sg,r.z),a}static isFrontFacing(e,t,i,n){return us.subVectors(i,t),Js.subVectors(e,t),us.cross(Js).dot(n)<0}set(e,t,i){return this.a.copy(e),this.b.copy(t),this.c.copy(i),this}setFromPointsAndIndices(e,t,i,n){return this.a.copy(e[t]),this.b.copy(e[i]),this.c.copy(e[n]),this}setFromAttributeAndIndices(e,t,i,n){return this.a.fromBufferAttribute(e,t),this.b.fromBufferAttribute(e,i),this.c.fromBufferAttribute(e,n),this}clone(){return new this.constructor().copy(this)}copy(e){return this.a.copy(e.a),this.b.copy(e.b),this.c.copy(e.c),this}getArea(){return us.subVectors(this.c,this.b),Js.subVectors(this.a,this.b),us.cross(Js).length()*.5}getMidpoint(e){return e.addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)}getNormal(e){return Ht.getNormal(this.a,this.b,this.c,e)}getPlane(e){return e.setFromCoplanarPoints(this.a,this.b,this.c)}getBarycoord(e,t){return Ht.getBarycoord(e,this.a,this.b,this.c,t)}getInterpolation(e,t,i,n,r){return Ht.getInterpolation(e,this.a,this.b,this.c,t,i,n,r)}containsPoint(e){return Ht.containsPoint(e,this.a,this.b,this.c)}isFrontFacing(e){return Ht.isFrontFacing(this.a,this.b,this.c,e)}intersectsBox(e){return e.intersectsTriangle(this)}closestPointToPoint(e,t){const i=this.a,n=this.b,r=this.c;let a,o;il.subVectors(n,i),nl.subVectors(r,i),Qm.subVectors(e,i);const l=il.dot(Qm),c=nl.dot(Qm);if(l<=0&&c<=0)return t.copy(i);eg.subVectors(e,n);const h=il.dot(eg),d=nl.dot(eg);if(h>=0&&d<=h)return t.copy(n);const p=l*d-h*c;if(p<=0&&l>=0&&h<=0)return a=l/(l-h),t.copy(i).addScaledVector(il,a);tg.subVectors(e,r);const u=il.dot(tg),v=nl.dot(tg);if(v>=0&&u<=v)return t.copy(r);const g=u*c-l*v;if(g<=0&&c>=0&&v<=0)return o=c/(c-v),t.copy(i).addScaledVector(nl,o);const m=h*v-u*d;if(m<=0&&d-h>=0&&u-v>=0)return px.subVectors(r,n),o=(d-h)/(d-h+(u-v)),t.copy(n).addScaledVector(px,o);const f=1/(m+g+p);return a=g*f,o=p*f,t.copy(i).addScaledVector(il,a).addScaledVector(nl,o)}equals(e){return e.a.equals(this.a)&&e.b.equals(this.b)&&e.c.equals(this.c)}}class vt{constructor(e=new R(1/0,1/0,1/0),t=new R(-1/0,-1/0,-1/0)){this.isBox3=!0,this.min=e,this.max=t}set(e,t){return this.min.copy(e),this.max.copy(t),this}setFromArray(e){this.makeEmpty();for(let t=0,i=e.length;t=this.min.x&&e.x<=this.max.x&&e.y>=this.min.y&&e.y<=this.max.y&&e.z>=this.min.z&&e.z<=this.max.z}containsBox(e){return this.min.x<=e.min.x&&e.max.x<=this.max.x&&this.min.y<=e.min.y&&e.max.y<=this.max.y&&this.min.z<=e.min.z&&e.max.z<=this.max.z}getParameter(e,t){return t.set((e.x-this.min.x)/(this.max.x-this.min.x),(e.y-this.min.y)/(this.max.y-this.min.y),(e.z-this.min.z)/(this.max.z-this.min.z))}intersectsBox(e){return e.max.x>=this.min.x&&e.min.x<=this.max.x&&e.max.y>=this.min.y&&e.min.y<=this.max.y&&e.max.z>=this.min.z&&e.min.z<=this.max.z}intersectsSphere(e){return this.clampPoint(e.center,ps),ps.distanceToSquared(e.center)<=e.radius*e.radius}intersectsPlane(e){let t,i;return e.normal.x>0?(t=e.normal.x*this.min.x,i=e.normal.x*this.max.x):(t=e.normal.x*this.max.x,i=e.normal.x*this.min.x),e.normal.y>0?(t+=e.normal.y*this.min.y,i+=e.normal.y*this.max.y):(t+=e.normal.y*this.max.y,i+=e.normal.y*this.min.y),e.normal.z>0?(t+=e.normal.z*this.min.z,i+=e.normal.z*this.max.z):(t+=e.normal.z*this.max.z,i+=e.normal.z*this.min.z),t<=-e.constant&&i>=-e.constant}intersectsTriangle(e){if(this.isEmpty())return!1;this.getCenter(Oc),wu.subVectors(this.max,Oc),sl.subVectors(e.a,Oc),rl.subVectors(e.b,Oc),al.subVectors(e.c,Oc),Fr.subVectors(rl,sl),zr.subVectors(al,rl),La.subVectors(sl,al);let t=[0,-Fr.z,Fr.y,0,-zr.z,zr.y,0,-La.z,La.y,Fr.z,0,-Fr.x,zr.z,0,-zr.x,La.z,0,-La.x,-Fr.y,Fr.x,0,-zr.y,zr.x,0,-La.y,La.x,0];return!rg(t,sl,rl,al,wu)||(t=[1,0,0,0,1,0,0,0,1],!rg(t,sl,rl,al,wu))?!1:(Eu.crossVectors(Fr,zr),t=[Eu.x,Eu.y,Eu.z],rg(t,sl,rl,al,wu))}clampPoint(e,t){return t.copy(e).clamp(this.min,this.max)}distanceToPoint(e){return this.clampPoint(e,ps).distanceTo(e)}getBoundingSphere(e){return this.isEmpty()?e.makeEmpty():(this.getCenter(e.center),e.radius=this.getSize(ps).length()*.5),e}intersect(e){return this.min.max(e.min),this.max.min(e.max),this.isEmpty()&&this.makeEmpty(),this}union(e){return this.min.min(e.min),this.max.max(e.max),this}applyMatrix4(e){return this.isEmpty()?this:(er[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(e),er[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(e),er[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(e),er[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(e),er[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(e),er[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(e),er[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(e),er[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(e),this.setFromPoints(er),this)}translate(e){return this.min.add(e),this.max.add(e),this}equals(e){return e.min.equals(this.min)&&e.max.equals(this.max)}toJSON(){return{min:this.min.toArray(),max:this.max.toArray()}}fromJSON(e){return this.min.fromArray(e.min),this.max.fromArray(e.max),this}}const er=[new R,new R,new R,new R,new R,new R,new R,new R],ps=new R,Su=new vt,sl=new R,rl=new R,al=new R,Fr=new R,zr=new R,La=new R,Oc=new R,wu=new R,Eu=new R,Da=new R;function rg(s,e,t,i,n){for(let r=0,a=s.length-3;r<=a;r+=3){Da.fromArray(s,r);const o=n.x*Math.abs(Da.x)+n.y*Math.abs(Da.y)+n.z*Math.abs(Da.z),l=e.dot(Da),c=t.dot(Da),h=i.dot(Da);if(Math.max(-Math.max(l,c,h),Math.min(l,c,h))>o)return!1}return!0}const tr=w3();function w3(){const s=new ArrayBuffer(4),e=new Float32Array(s),t=new Uint32Array(s),i=new Uint32Array(512),n=new Uint32Array(512);for(let l=0;l<256;++l){const c=l-127;c<-27?(i[l]=0,i[l|256]=32768,n[l]=24,n[l|256]=24):c<-14?(i[l]=1024>>-c-14,i[l|256]=1024>>-c-14|32768,n[l]=-c-1,n[l|256]=-c-1):c<=15?(i[l]=c+15<<10,i[l|256]=c+15<<10|32768,n[l]=13,n[l|256]=13):c<128?(i[l]=31744,i[l|256]=64512,n[l]=24,n[l|256]=24):(i[l]=31744,i[l|256]=64512,n[l]=13,n[l|256]=13)}const r=new Uint32Array(2048),a=new Uint32Array(64),o=new Uint32Array(64);for(let l=1;l<1024;++l){let c=l<<13,h=0;for(;(c&8388608)===0;)c<<=1,h-=8388608;c&=-8388609,h+=947912704,r[l]=c|h}for(let l=1024;l<2048;++l)r[l]=939524096+(l-1024<<13);for(let l=1;l<31;++l)a[l]=l<<23;a[31]=1199570944,a[32]=2147483648;for(let l=33;l<63;++l)a[l]=2147483648+(l-32<<23);a[63]=3347054592;for(let l=1;l<64;++l)l!==32&&(o[l]=1024);return{floatView:e,uint32View:t,baseTable:i,shiftTable:n,mantissaTable:r,exponentTable:a,offsetTable:o}}function Mn(s){Math.abs(s)>65504&&Ye("DataUtils.toHalfFloat(): Value out of range."),s=dt(s,-65504,65504),tr.floatView[0]=s;const e=tr.uint32View[0],t=e>>23&511;return tr.baseTable[t]+((e&8388607)>>tr.shiftTable[t])}function Uc(s){const e=s>>10;return tr.uint32View[0]=tr.mantissaTable[tr.offsetTable[e]+(s&1023)]+tr.exponentTable[e],tr.floatView[0]}class Bc{static toHalfFloat(e){return Mn(e)}static fromHalfFloat(e){return Uc(e)}}const Mi=new R,Tu=new me;let E3=0;class St{constructor(e,t,i=!1){if(Array.isArray(e))throw new TypeError("THREE.BufferAttribute: array should be a Typed Array.");this.isBufferAttribute=!0,Object.defineProperty(this,"id",{value:E3++}),this.name="",this.array=e,this.itemSize=t,this.count=e!==void 0?e.length/t:0,this.normalized=i,this.usage=Rc,this.updateRanges=[],this.gpuType=Pi,this.version=0}onUploadCallback(){}set needsUpdate(e){e===!0&&this.version++}setUsage(e){return this.usage=e,this}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}copy(e){return this.name=e.name,this.array=new e.array.constructor(e.array),this.itemSize=e.itemSize,this.count=e.count,this.normalized=e.normalized,this.usage=e.usage,this.gpuType=e.gpuType,this}copyAt(e,t,i){e*=this.itemSize,i*=t.itemSize;for(let n=0,r=this.itemSize;nthis.radius*this.radius&&(t.sub(this.center).normalize(),t.multiplyScalar(this.radius).add(this.center)),t}getBoundingBox(e){return this.isEmpty()?(e.makeEmpty(),e):(e.set(this.center,this.center),e.expandByScalar(this.radius),e)}applyMatrix4(e){return this.center.applyMatrix4(e),this.radius=this.radius*e.getMaxScaleOnAxis(),this}translate(e){return this.center.add(e),this}expandByPoint(e){if(this.isEmpty())return this.center.copy(e),this.radius=0,this;Fc.subVectors(e,this.center);const t=Fc.lengthSq();if(t>this.radius*this.radius){const i=Math.sqrt(t),n=(i-this.radius)*.5;this.center.addScaledVector(Fc,n/i),this.radius+=n}return this}union(e){return e.isEmpty()?this:this.isEmpty()?(this.copy(e),this):(this.center.equals(e.center)===!0?this.radius=Math.max(this.radius,e.radius):(lg.subVectors(e.center,this.center).setLength(e.radius),this.expandByPoint(Fc.copy(e.center).add(lg)),this.expandByPoint(Fc.copy(e.center).sub(lg))),this)}equals(e){return e.center.equals(this.center)&&e.radius===this.radius}clone(){return new this.constructor().copy(this)}toJSON(){return{radius:this.radius,center:this.center.toArray()}}fromJSON(e){return this.radius=e.radius,this.center.fromArray(e.center),this}}let D3=0;const Yn=new qe,cg=new Rt,ol=new R,Un=new vt,zc=new vt,Hi=new R;class at extends hs{constructor(){super(),this.isBufferGeometry=!0,Object.defineProperty(this,"id",{value:D3++}),this.uuid=kn(),this.name="",this.type="BufferGeometry",this.index=null,this.indirect=null,this.indirectOffset=0,this.attributes={},this.morphAttributes={},this.morphTargetsRelative=!1,this.groups=[],this.boundingBox=null,this.boundingSphere=null,this.drawRange={start:0,count:1/0},this.userData={}}getIndex(){return this.index}setIndex(e){return Array.isArray(e)?this.index=new(WE(e)?og:ag)(e,1):this.index=e,this}setIndirect(e,t=0){return this.indirect=e,this.indirectOffset=t,this}getIndirect(){return this.indirect}getAttribute(e){return this.attributes[e]}setAttribute(e,t){return this.attributes[e]=t,this}deleteAttribute(e){return delete this.attributes[e],this}hasAttribute(e){return this.attributes[e]!==void 0}addGroup(e,t,i=0){this.groups.push({start:e,count:t,materialIndex:i})}clearGroups(){this.groups=[]}setDrawRange(e,t){this.drawRange.start=e,this.drawRange.count=t}applyMatrix4(e){const t=this.attributes.position;t!==void 0&&(t.applyMatrix4(e),t.needsUpdate=!0);const i=this.attributes.normal;if(i!==void 0){const r=new ft().getNormalMatrix(e);i.applyNormalMatrix(r),i.needsUpdate=!0}const n=this.attributes.tangent;return n!==void 0&&(n.transformDirection(e),n.needsUpdate=!0),this.boundingBox!==null&&this.computeBoundingBox(),this.boundingSphere!==null&&this.computeBoundingSphere(),this}applyQuaternion(e){return Yn.makeRotationFromQuaternion(e),this.applyMatrix4(Yn),this}rotateX(e){return Yn.makeRotationX(e),this.applyMatrix4(Yn),this}rotateY(e){return Yn.makeRotationY(e),this.applyMatrix4(Yn),this}rotateZ(e){return Yn.makeRotationZ(e),this.applyMatrix4(Yn),this}translate(e,t,i){return Yn.makeTranslation(e,t,i),this.applyMatrix4(Yn),this}scale(e,t,i){return Yn.makeScale(e,t,i),this.applyMatrix4(Yn),this}lookAt(e){return cg.lookAt(e),cg.updateMatrix(),this.applyMatrix4(cg.matrix),this}center(){return this.computeBoundingBox(),this.boundingBox.getCenter(ol).negate(),this.translate(ol.x,ol.y,ol.z),this}setFromPoints(e){const t=this.getAttribute("position");if(t===void 0){const i=[];for(let n=0,r=e.length;nt.count&&Ye("BufferGeometry: Buffer size too small for points data. Use .dispose() and create a new geometry."),t.needsUpdate=!0}return this}computeBoundingBox(){this.boundingBox===null&&(this.boundingBox=new vt);const e=this.attributes.position,t=this.morphAttributes.position;if(e&&e.isGLBufferAttribute){lt("BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.",this),this.boundingBox.set(new R(-1/0,-1/0,-1/0),new R(1/0,1/0,1/0));return}if(e!==void 0){if(this.boundingBox.setFromBufferAttribute(e),t)for(let i=0,n=t.length;i0&&(e.userData=this.userData),this.parameters!==void 0){const l=this.parameters;for(const c in l)l[c]!==void 0&&(e[c]=l[c]);return e}e.data={attributes:{}};const t=this.index;t!==null&&(e.data.index={type:t.array.constructor.name,array:Array.prototype.slice.call(t.array)});const i=this.attributes;for(const l in i){const c=i[l];e.data.attributes[l]=c.toJSON(e.data)}const n={};let r=!1;for(const l in this.morphAttributes){const c=this.morphAttributes[l],h=[];for(let d=0,p=c.length;d0&&(n[l]=h,r=!0)}r&&(e.data.morphAttributes=n,e.data.morphTargetsRelative=this.morphTargetsRelative);const a=this.groups;a.length>0&&(e.data.groups=JSON.parse(JSON.stringify(a)));const o=this.boundingSphere;return o!==null&&(e.data.boundingSphere=o.toJSON()),e}clone(){return new this.constructor().copy(this)}copy(e){this.index=null,this.attributes={},this.morphAttributes={},this.groups=[],this.boundingBox=null,this.boundingSphere=null;const t={};this.name=e.name;const i=e.index;i!==null&&this.setIndex(i.clone());const n=e.attributes;for(const c in n){const h=n[c];this.setAttribute(c,h.clone(t))}const r=e.morphAttributes;for(const c in r){const h=[],d=r[c];for(let p=0,u=d.length;p0!=e>0&&this.version++,this._alphaTest=e}onBeforeRender(){}onBeforeCompile(){}customProgramCacheKey(){return this.onBeforeCompile.toString()}setValues(e){if(e!==void 0)for(const t in e){const i=e[t];if(i===void 0){Ye(`Material: parameter '${t}' has value of undefined.`);continue}const n=this[t];if(n===void 0){Ye(`Material: '${t}' is not a property of THREE.${this.type}.`);continue}n&&n.isColor?n.set(i):n&&n.isVector3&&i&&i.isVector3?n.copy(i):this[t]=i}}toJSON(e){const t=e===void 0||typeof e=="string";t&&(e={textures:{},images:{}});const i={metadata:{version:4.7,type:"Material",generator:"Material.toJSON"}};i.uuid=this.uuid,i.type=this.type,this.name!==""&&(i.name=this.name),this.color&&this.color.isColor&&(i.color=this.color.getHex()),this.roughness!==void 0&&(i.roughness=this.roughness),this.metalness!==void 0&&(i.metalness=this.metalness),this.sheen!==void 0&&(i.sheen=this.sheen),this.sheenColor&&this.sheenColor.isColor&&(i.sheenColor=this.sheenColor.getHex()),this.sheenRoughness!==void 0&&(i.sheenRoughness=this.sheenRoughness),this.emissive&&this.emissive.isColor&&(i.emissive=this.emissive.getHex()),this.emissiveIntensity!==void 0&&this.emissiveIntensity!==1&&(i.emissiveIntensity=this.emissiveIntensity),this.specular&&this.specular.isColor&&(i.specular=this.specular.getHex()),this.specularIntensity!==void 0&&(i.specularIntensity=this.specularIntensity),this.specularColor&&this.specularColor.isColor&&(i.specularColor=this.specularColor.getHex()),this.shininess!==void 0&&(i.shininess=this.shininess),this.clearcoat!==void 0&&(i.clearcoat=this.clearcoat),this.clearcoatRoughness!==void 0&&(i.clearcoatRoughness=this.clearcoatRoughness),this.clearcoatMap&&this.clearcoatMap.isTexture&&(i.clearcoatMap=this.clearcoatMap.toJSON(e).uuid),this.clearcoatRoughnessMap&&this.clearcoatRoughnessMap.isTexture&&(i.clearcoatRoughnessMap=this.clearcoatRoughnessMap.toJSON(e).uuid),this.clearcoatNormalMap&&this.clearcoatNormalMap.isTexture&&(i.clearcoatNormalMap=this.clearcoatNormalMap.toJSON(e).uuid,i.clearcoatNormalScale=this.clearcoatNormalScale.toArray()),this.sheenColorMap&&this.sheenColorMap.isTexture&&(i.sheenColorMap=this.sheenColorMap.toJSON(e).uuid),this.sheenRoughnessMap&&this.sheenRoughnessMap.isTexture&&(i.sheenRoughnessMap=this.sheenRoughnessMap.toJSON(e).uuid),this.dispersion!==void 0&&(i.dispersion=this.dispersion),this.iridescence!==void 0&&(i.iridescence=this.iridescence),this.iridescenceIOR!==void 0&&(i.iridescenceIOR=this.iridescenceIOR),this.iridescenceThicknessRange!==void 0&&(i.iridescenceThicknessRange=this.iridescenceThicknessRange),this.iridescenceMap&&this.iridescenceMap.isTexture&&(i.iridescenceMap=this.iridescenceMap.toJSON(e).uuid),this.iridescenceThicknessMap&&this.iridescenceThicknessMap.isTexture&&(i.iridescenceThicknessMap=this.iridescenceThicknessMap.toJSON(e).uuid),this.anisotropy!==void 0&&(i.anisotropy=this.anisotropy),this.anisotropyRotation!==void 0&&(i.anisotropyRotation=this.anisotropyRotation),this.anisotropyMap&&this.anisotropyMap.isTexture&&(i.anisotropyMap=this.anisotropyMap.toJSON(e).uuid),this.map&&this.map.isTexture&&(i.map=this.map.toJSON(e).uuid),this.matcap&&this.matcap.isTexture&&(i.matcap=this.matcap.toJSON(e).uuid),this.alphaMap&&this.alphaMap.isTexture&&(i.alphaMap=this.alphaMap.toJSON(e).uuid),this.lightMap&&this.lightMap.isTexture&&(i.lightMap=this.lightMap.toJSON(e).uuid,i.lightMapIntensity=this.lightMapIntensity),this.aoMap&&this.aoMap.isTexture&&(i.aoMap=this.aoMap.toJSON(e).uuid,i.aoMapIntensity=this.aoMapIntensity),this.bumpMap&&this.bumpMap.isTexture&&(i.bumpMap=this.bumpMap.toJSON(e).uuid,i.bumpScale=this.bumpScale),this.normalMap&&this.normalMap.isTexture&&(i.normalMap=this.normalMap.toJSON(e).uuid,i.normalMapType=this.normalMapType,i.normalScale=this.normalScale.toArray()),this.displacementMap&&this.displacementMap.isTexture&&(i.displacementMap=this.displacementMap.toJSON(e).uuid,i.displacementScale=this.displacementScale,i.displacementBias=this.displacementBias),this.roughnessMap&&this.roughnessMap.isTexture&&(i.roughnessMap=this.roughnessMap.toJSON(e).uuid),this.metalnessMap&&this.metalnessMap.isTexture&&(i.metalnessMap=this.metalnessMap.toJSON(e).uuid),this.emissiveMap&&this.emissiveMap.isTexture&&(i.emissiveMap=this.emissiveMap.toJSON(e).uuid),this.specularMap&&this.specularMap.isTexture&&(i.specularMap=this.specularMap.toJSON(e).uuid),this.specularIntensityMap&&this.specularIntensityMap.isTexture&&(i.specularIntensityMap=this.specularIntensityMap.toJSON(e).uuid),this.specularColorMap&&this.specularColorMap.isTexture&&(i.specularColorMap=this.specularColorMap.toJSON(e).uuid),this.envMap&&this.envMap.isTexture&&(i.envMap=this.envMap.toJSON(e).uuid,this.combine!==void 0&&(i.combine=this.combine)),this.envMapRotation!==void 0&&(i.envMapRotation=this.envMapRotation.toArray()),this.envMapIntensity!==void 0&&(i.envMapIntensity=this.envMapIntensity),this.reflectivity!==void 0&&(i.reflectivity=this.reflectivity),this.refractionRatio!==void 0&&(i.refractionRatio=this.refractionRatio),this.gradientMap&&this.gradientMap.isTexture&&(i.gradientMap=this.gradientMap.toJSON(e).uuid),this.transmission!==void 0&&(i.transmission=this.transmission),this.transmissionMap&&this.transmissionMap.isTexture&&(i.transmissionMap=this.transmissionMap.toJSON(e).uuid),this.thickness!==void 0&&(i.thickness=this.thickness),this.thicknessMap&&this.thicknessMap.isTexture&&(i.thicknessMap=this.thicknessMap.toJSON(e).uuid),this.attenuationDistance!==void 0&&this.attenuationDistance!==1/0&&(i.attenuationDistance=this.attenuationDistance),this.attenuationColor!==void 0&&(i.attenuationColor=this.attenuationColor.getHex()),this.size!==void 0&&(i.size=this.size),this.shadowSide!==null&&(i.shadowSide=this.shadowSide),this.sizeAttenuation!==void 0&&(i.sizeAttenuation=this.sizeAttenuation),this.blending!==ba&&(i.blending=this.blending),this.side!==_n&&(i.side=this.side),this.vertexColors===!0&&(i.vertexColors=!0),this.opacity<1&&(i.opacity=this.opacity),this.transparent===!0&&(i.transparent=!0),this.blendSrc!==cd&&(i.blendSrc=this.blendSrc),this.blendDst!==hd&&(i.blendDst=this.blendDst),this.blendEquation!==bn&&(i.blendEquation=this.blendEquation),this.blendSrcAlpha!==null&&(i.blendSrcAlpha=this.blendSrcAlpha),this.blendDstAlpha!==null&&(i.blendDstAlpha=this.blendDstAlpha),this.blendEquationAlpha!==null&&(i.blendEquationAlpha=this.blendEquationAlpha),this.blendColor&&this.blendColor.isColor&&(i.blendColor=this.blendColor.getHex()),this.blendAlpha!==0&&(i.blendAlpha=this.blendAlpha),this.depthFunc!==Ma&&(i.depthFunc=this.depthFunc),this.depthTest===!1&&(i.depthTest=this.depthTest),this.depthWrite===!1&&(i.depthWrite=this.depthWrite),this.colorWrite===!1&&(i.colorWrite=this.colorWrite),this.stencilWriteMask!==255&&(i.stencilWriteMask=this.stencilWriteMask),this.stencilFunc!==Vm&&(i.stencilFunc=this.stencilFunc),this.stencilRef!==0&&(i.stencilRef=this.stencilRef),this.stencilFuncMask!==255&&(i.stencilFuncMask=this.stencilFuncMask),this.stencilFail!==Aa&&(i.stencilFail=this.stencilFail),this.stencilZFail!==Aa&&(i.stencilZFail=this.stencilZFail),this.stencilZPass!==Aa&&(i.stencilZPass=this.stencilZPass),this.stencilWrite===!0&&(i.stencilWrite=this.stencilWrite),this.rotation!==void 0&&this.rotation!==0&&(i.rotation=this.rotation),this.polygonOffset===!0&&(i.polygonOffset=!0),this.polygonOffsetFactor!==0&&(i.polygonOffsetFactor=this.polygonOffsetFactor),this.polygonOffsetUnits!==0&&(i.polygonOffsetUnits=this.polygonOffsetUnits),this.linewidth!==void 0&&this.linewidth!==1&&(i.linewidth=this.linewidth),this.dashSize!==void 0&&(i.dashSize=this.dashSize),this.gapSize!==void 0&&(i.gapSize=this.gapSize),this.scale!==void 0&&(i.scale=this.scale),this.dithering===!0&&(i.dithering=!0),this.alphaTest>0&&(i.alphaTest=this.alphaTest),this.alphaHash===!0&&(i.alphaHash=!0),this.alphaToCoverage===!0&&(i.alphaToCoverage=!0),this.premultipliedAlpha===!0&&(i.premultipliedAlpha=!0),this.forceSinglePass===!0&&(i.forceSinglePass=!0),this.allowOverride===!1&&(i.allowOverride=!1),this.wireframe===!0&&(i.wireframe=!0),this.wireframeLinewidth>1&&(i.wireframeLinewidth=this.wireframeLinewidth),this.wireframeLinecap!=="round"&&(i.wireframeLinecap=this.wireframeLinecap),this.wireframeLinejoin!=="round"&&(i.wireframeLinejoin=this.wireframeLinejoin),this.flatShading===!0&&(i.flatShading=!0),this.visible===!1&&(i.visible=!1),this.toneMapped===!1&&(i.toneMapped=!1),this.fog===!1&&(i.fog=!1),Object.keys(this.userData).length>0&&(i.userData=this.userData);function n(r){const a=[];for(const o in r){const l=r[o];delete l.metadata,a.push(l)}return a}if(t){const r=n(e.textures),a=n(e.images);r.length>0&&(i.textures=r),a.length>0&&(i.images=a)}return i}clone(){return new this.constructor().copy(this)}copy(e){this.name=e.name,this.blending=e.blending,this.side=e.side,this.vertexColors=e.vertexColors,this.opacity=e.opacity,this.transparent=e.transparent,this.blendSrc=e.blendSrc,this.blendDst=e.blendDst,this.blendEquation=e.blendEquation,this.blendSrcAlpha=e.blendSrcAlpha,this.blendDstAlpha=e.blendDstAlpha,this.blendEquationAlpha=e.blendEquationAlpha,this.blendColor.copy(e.blendColor),this.blendAlpha=e.blendAlpha,this.depthFunc=e.depthFunc,this.depthTest=e.depthTest,this.depthWrite=e.depthWrite,this.stencilWriteMask=e.stencilWriteMask,this.stencilFunc=e.stencilFunc,this.stencilRef=e.stencilRef,this.stencilFuncMask=e.stencilFuncMask,this.stencilFail=e.stencilFail,this.stencilZFail=e.stencilZFail,this.stencilZPass=e.stencilZPass,this.stencilWrite=e.stencilWrite;const t=e.clippingPlanes;let i=null;if(t!==null){const n=t.length;i=new Array(n);for(let r=0;r!==n;++r)i[r]=t[r].clone()}return this.clippingPlanes=i,this.clipIntersection=e.clipIntersection,this.clipShadows=e.clipShadows,this.shadowSide=e.shadowSide,this.colorWrite=e.colorWrite,this.precision=e.precision,this.polygonOffset=e.polygonOffset,this.polygonOffsetFactor=e.polygonOffsetFactor,this.polygonOffsetUnits=e.polygonOffsetUnits,this.dithering=e.dithering,this.alphaTest=e.alphaTest,this.alphaHash=e.alphaHash,this.alphaToCoverage=e.alphaToCoverage,this.premultipliedAlpha=e.premultipliedAlpha,this.forceSinglePass=e.forceSinglePass,this.allowOverride=e.allowOverride,this.visible=e.visible,this.toneMapped=e.toneMapped,this.userData=JSON.parse(JSON.stringify(e.userData)),this}dispose(){this.dispatchEvent({type:"dispose"})}set needsUpdate(e){e===!0&&this.version++}}class Cu extends Ri{constructor(e){super(),this.isSpriteMaterial=!0,this.type="SpriteMaterial",this.color=new We(16777215),this.map=null,this.alphaMap=null,this.rotation=0,this.sizeAttenuation=!0,this.transparent=!0,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.alphaMap=e.alphaMap,this.rotation=e.rotation,this.sizeAttenuation=e.sizeAttenuation,this.fog=e.fog,this}}let ll;const Vc=new R,cl=new R,hl=new R,dl=new me,Gc=new me,fx=new qe,Au=new R,Wc=new R,Pu=new R,mx=new me,hg=new me,gx=new me;class Xc extends Rt{constructor(e=new Cu){if(super(),this.isSprite=!0,this.type="Sprite",ll===void 0){ll=new at;const t=new Float32Array([-.5,-.5,0,0,0,.5,-.5,0,1,0,.5,.5,0,1,1,-.5,.5,0,0,1]),i=new Hc(t,5);ll.setIndex([0,1,2,0,2,3]),ll.setAttribute("position",new Hr(i,3,0,!1)),ll.setAttribute("uv",new Hr(i,2,3,!1))}this.geometry=ll,this.material=e,this.center=new me(.5,.5),this.count=1}raycast(e,t){e.camera===null&<('Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.'),cl.setFromMatrixScale(this.matrixWorld),fx.copy(e.camera.matrixWorld),this.modelViewMatrix.multiplyMatrices(e.camera.matrixWorldInverse,this.matrixWorld),hl.setFromMatrixPosition(this.modelViewMatrix),e.camera.isPerspectiveCamera&&this.material.sizeAttenuation===!1&&cl.multiplyScalar(-hl.z);const i=this.material.rotation;let n,r;i!==0&&(r=Math.cos(i),n=Math.sin(i));const a=this.center;Ru(Au.set(-.5,-.5,0),hl,a,cl,n,r),Ru(Wc.set(.5,-.5,0),hl,a,cl,n,r),Ru(Pu.set(.5,.5,0),hl,a,cl,n,r),mx.set(0,0),hg.set(1,0),gx.set(1,1);let o=e.ray.intersectTriangle(Au,Wc,Pu,!1,Vc);if(o===null&&(Ru(Wc.set(-.5,.5,0),hl,a,cl,n,r),hg.set(0,1),o=e.ray.intersectTriangle(Au,Pu,Wc,!1,Vc),o===null))return;const l=e.ray.origin.distanceTo(Vc);le.far||t.push({distance:l,point:Vc.clone(),uv:Ht.getInterpolation(Vc,Au,Wc,Pu,mx,hg,gx,new me),face:null,object:this})}copy(e,t){return super.copy(e,t),e.center!==void 0&&this.center.copy(e.center),this.material=e.material,this}}function Ru(s,e,t,i,n,r){dl.subVectors(s,t).addScalar(.5).multiply(i),n!==void 0?(Gc.x=r*dl.x-n*dl.y,Gc.y=n*dl.x+r*dl.y):Gc.copy(dl),s.copy(e),s.x+=Gc.x,s.y+=Gc.y,s.applyMatrix4(fx)}const Iu=new R,vx=new R;class yx extends Rt{constructor(){super(),this.isLOD=!0,this._currentLevel=0,this.type="LOD",Object.defineProperties(this,{levels:{enumerable:!0,value:[]}}),this.autoUpdate=!0}copy(e){super.copy(e,!1);const t=e.levels;for(let i=0,n=t.length;i0){let i,n;for(i=1,n=t.length;i0){Iu.setFromMatrixPosition(this.matrixWorld);const n=e.ray.origin.distanceTo(Iu);this.getObjectForDistance(n).raycast(e,t)}}update(e){const t=this.levels;if(t.length>1){Iu.setFromMatrixPosition(e.matrixWorld),vx.setFromMatrixPosition(this.matrixWorld);const i=Iu.distanceTo(vx)/e.zoom;t[0].object.visible=!0;let n,r;for(n=1,r=t.length;n=a)t[n-1].object.visible=!1,t[n].object.visible=!0;else break}for(this._currentLevel=n-1;n0)if(d=a*l-o,p=a*o-l,v=r*h,d>=0)if(p>=-v)if(p<=v){const g=1/h;d*=g,p*=g,u=d*(d+a*p+2*o)+p*(a*d+p+2*l)+c}else p=r,d=Math.max(0,-(a*p+o)),u=-d*d+p*(p+2*l)+c;else p=-r,d=Math.max(0,-(a*p+o)),u=-d*d+p*(p+2*l)+c;else p<=-v?(d=Math.max(0,-(-a*r+o)),p=d>0?-r:Math.min(Math.max(-r,-l),r),u=-d*d+p*(p+2*l)+c):p<=v?(d=0,p=Math.min(Math.max(-r,-l),r),u=p*(p+2*l)+c):(d=Math.max(0,-(a*r+o)),p=d>0?r:Math.min(Math.max(-r,-l),r),u=-d*d+p*(p+2*l)+c);else p=a>0?-r:r,d=Math.max(0,-(a*p+o)),u=-d*d+p*(p+2*l)+c;return i&&i.copy(this.origin).addScaledVector(this.direction,d),n&&n.copy(dg).addScaledVector(Lu,p),u}intersectSphere(e,t){ir.subVectors(e.center,this.origin);const i=ir.dot(this.direction),n=ir.dot(ir)-i*i,r=e.radius*e.radius;if(n>r)return null;const a=Math.sqrt(r-n),o=i-a,l=i+a;return l<0?null:o<0?this.at(l,t):this.at(o,t)}intersectsSphere(e){return e.radius<0?!1:this.distanceSqToPoint(e.center)<=e.radius*e.radius}distanceToPlane(e){const t=e.normal.dot(this.direction);if(t===0)return e.distanceToPoint(this.origin)===0?0:null;const i=-(this.origin.dot(e.normal)+e.constant)/t;return i>=0?i:null}intersectPlane(e,t){const i=this.distanceToPlane(e);return i===null?null:this.at(i,t)}intersectsPlane(e){const t=e.distanceToPoint(this.origin);return t===0||e.normal.dot(this.direction)*t<0}intersectBox(e,t){let i,n,r,a,o,l;const c=1/this.direction.x,h=1/this.direction.y,d=1/this.direction.z,p=this.origin;return c>=0?(i=(e.min.x-p.x)*c,n=(e.max.x-p.x)*c):(i=(e.max.x-p.x)*c,n=(e.min.x-p.x)*c),h>=0?(r=(e.min.y-p.y)*h,a=(e.max.y-p.y)*h):(r=(e.max.y-p.y)*h,a=(e.min.y-p.y)*h),i>a||r>n||((r>i||isNaN(i))&&(i=r),(a=0?(o=(e.min.z-p.z)*d,l=(e.max.z-p.z)*d):(o=(e.max.z-p.z)*d,l=(e.min.z-p.z)*d),i>l||o>n)||((o>i||i!==i)&&(i=o),(l=0?i:n,t)}intersectsBox(e){return this.intersectBox(e,ir)!==null}intersectTriangle(e,t,i,n,r){ug.subVectors(t,e),Du.subVectors(i,e),pg.crossVectors(ug,Du);let a=this.direction.dot(pg),o;if(a>0){if(n)return null;o=1}else if(a<0)o=-1,a=-a;else return null;Vr.subVectors(this.origin,e);const l=o*this.direction.dot(Du.crossVectors(Vr,Du));if(l<0)return null;const c=o*this.direction.dot(ug.cross(Vr));if(c<0||l+c>a)return null;const h=-o*Vr.dot(pg);return h<0?null:this.at(h/a,r)}applyMatrix4(e){return this.origin.applyMatrix4(e),this.direction.transformDirection(e),this}equals(e){return e.origin.equals(this.origin)&&e.direction.equals(this.direction)}clone(){return new this.constructor().copy(this)}}class Dt extends Ri{constructor(e){super(),this.isMeshBasicMaterial=!0,this.type="MeshBasicMaterial",this.color=new We(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new Fi,this.combine=_c,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.specularMap=e.specularMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.combine=e.combine,this.reflectivity=e.reflectivity,this.refractionRatio=e.refractionRatio,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.fog=e.fog,this}}const xx=new qe,Na=new ks,Nu=new zi,_x=new R,ku=new R,Ou=new R,Uu=new R,fg=new R,Bu=new R,bx=new R,Fu=new R;class ht extends Rt{constructor(e=new at,t=new Dt){super(),this.isMesh=!0,this.type="Mesh",this.geometry=e,this.material=t,this.morphTargetDictionary=void 0,this.morphTargetInfluences=void 0,this.count=1,this.updateMorphTargets()}copy(e,t){return super.copy(e,t),e.morphTargetInfluences!==void 0&&(this.morphTargetInfluences=e.morphTargetInfluences.slice()),e.morphTargetDictionary!==void 0&&(this.morphTargetDictionary=Object.assign({},e.morphTargetDictionary)),this.material=Array.isArray(e.material)?e.material.slice():e.material,this.geometry=e.geometry,this}updateMorphTargets(){const t=this.geometry.morphAttributes,i=Object.keys(t);if(i.length>0){const n=t[i[0]];if(n!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let r=0,a=n.length;r(e.far-e.near)**2))&&(xx.copy(r).invert(),Na.copy(e.ray).applyMatrix4(xx),!(i.boundingBox!==null&&Na.intersectsBox(i.boundingBox)===!1)&&this._computeIntersections(e,t,Na)))}_computeIntersections(e,t,i){let n;const r=this.geometry,a=this.material,o=r.index,l=r.attributes.position,c=r.attributes.uv,h=r.attributes.uv1,d=r.attributes.normal,p=r.groups,u=r.drawRange;if(o!==null)if(Array.isArray(a))for(let v=0,g=p.length;vt.far?null:{distance:c,point:Fu.clone(),object:s}}function zu(s,e,t,i,n,r,a,o,l,c){s.getVertexPosition(o,ku),s.getVertexPosition(l,Ou),s.getVertexPosition(c,Uu);const h=k3(s,e,t,i,ku,Ou,Uu,bx);if(h){const d=new R;Ht.getBarycoord(bx,ku,Ou,Uu,d),n&&(h.uv=Ht.getInterpolatedAttribute(n,o,l,c,d,new me)),r&&(h.uv1=Ht.getInterpolatedAttribute(r,o,l,c,d,new me)),a&&(h.normal=Ht.getInterpolatedAttribute(a,o,l,c,d,new R),h.normal.dot(i.direction)>0&&h.normal.multiplyScalar(-1));const p={a:o,b:l,c,normal:new R,materialIndex:0};Ht.getNormal(ku,Ou,Uu,p.normal),h.face=p,h.barycoord=d}return h}const Mx=new R,Sx=new Pt,wx=new Pt,O3=new R,Ex=new qe,Hu=new R,mg=new zi,Tx=new qe,gg=new ks;class vg extends ht{constructor(e,t){super(e,t),this.isSkinnedMesh=!0,this.type="SkinnedMesh",this.bindMode=Lm,this.bindMatrix=new qe,this.bindMatrixInverse=new qe,this.boundingBox=null,this.boundingSphere=null}computeBoundingBox(){const e=this.geometry;this.boundingBox===null&&(this.boundingBox=new vt),this.boundingBox.makeEmpty();const t=e.getAttribute("position");for(let i=0;i1?null:t.copy(e.start).addScaledVector(i,r)}intersectsLine(e){const t=this.distanceToPoint(e.start),i=this.distanceToPoint(e.end);return t<0&&i>0||i<0&&t>0}intersectsBox(e){return e.intersectsPlane(this)}intersectsSphere(e){return e.intersectsPlane(this)}coplanarPoint(e){return e.copy(this.normal).multiplyScalar(-this.constant)}applyMatrix4(e,t){const i=t||z3.getNormalMatrix(e),n=this.coplanarPoint(yg).applyMatrix4(e),r=this.normal.applyMatrix3(i).normalize();return this.constant=-n.dot(r),this}translate(e){return this.constant-=e.dot(this.normal),this}equals(e){return e.normal.equals(this.normal)&&e.constant===this.constant}clone(){return new this.constructor().copy(this)}}const ka=new zi,H3=new me(.5,.5),Wu=new R;class pl{constructor(e=new Yt,t=new Yt,i=new Yt,n=new Yt,r=new Yt,a=new Yt){this.planes=[e,t,i,n,r,a]}set(e,t,i,n,r,a){const o=this.planes;return o[0].copy(e),o[1].copy(t),o[2].copy(i),o[3].copy(n),o[4].copy(r),o[5].copy(a),this}copy(e){const t=this.planes;for(let i=0;i<6;i++)t[i].copy(e.planes[i]);return this}setFromProjectionMatrix(e,t=Nn,i=!1){const n=this.planes,r=e.elements,a=r[0],o=r[1],l=r[2],c=r[3],h=r[4],d=r[5],p=r[6],u=r[7],v=r[8],g=r[9],m=r[10],f=r[11],y=r[12],x=r[13],_=r[14],S=r[15];if(n[0].setComponents(c-a,u-h,f-v,S-y).normalize(),n[1].setComponents(c+a,u+h,f+v,S+y).normalize(),n[2].setComponents(c+o,u+d,f+g,S+x).normalize(),n[3].setComponents(c-o,u-d,f-g,S-x).normalize(),i)n[4].setComponents(l,p,m,_).normalize(),n[5].setComponents(c-l,u-p,f-m,S-_).normalize();else if(n[4].setComponents(c-l,u-p,f-m,S-_).normalize(),t===Nn)n[5].setComponents(c+l,u+p,f+m,S+_).normalize();else if(t===Pa)n[5].setComponents(l,p,m,_).normalize();else throw new Error("THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: "+t);return this}intersectsObject(e){if(e.boundingSphere!==void 0)e.boundingSphere===null&&e.computeBoundingSphere(),ka.copy(e.boundingSphere).applyMatrix4(e.matrixWorld);else{const t=e.geometry;t.boundingSphere===null&&t.computeBoundingSphere(),ka.copy(t.boundingSphere).applyMatrix4(e.matrixWorld)}return this.intersectsSphere(ka)}intersectsSprite(e){ka.center.set(0,0,0);const t=H3.distanceTo(e.center);return ka.radius=.7071067811865476+t,ka.applyMatrix4(e.matrixWorld),this.intersectsSphere(ka)}intersectsSphere(e){const t=this.planes,i=e.center,n=-e.radius;for(let r=0;r<6;r++)if(t[r].distanceToPoint(i)0?e.max.x:e.min.x,Wu.y=n.normal.y>0?e.max.y:e.min.y,Wu.z=n.normal.z>0?e.max.z:e.min.z,n.distanceToPoint(Wu)<0)return!1}return!0}containsPoint(e){const t=this.planes;for(let i=0;i<6;i++)if(t[i].distanceToPoint(e)<0)return!1;return!0}clone(){return new this.constructor().copy(this)}}const Os=new qe,Us=new pl;class Xu{constructor(){this.coordinateSystem=Nn}intersectsObject(e,t){if(!t.isArrayCamera||t.cameras.length===0)return!1;for(let i=0;i=r.length&&r.push({start:-1,count:-1,z:-1,index:-1});const o=r[this.index];a.push(o),this.index++,o.start=e,o.count=t,o.z=i,o.index=n}reset(){this.list.length=0,this.index=0}}const wn=new qe,X3=new We(1,1,1),Rx=new pl,j3=new Xu,ju=new vt,Oa=new zi,Yc=new R,Ix=new R,q3=new R,_g=new W3,tn=new ht,qu=[];function Z3(s,e,t=0){const i=e.itemSize;if(s.isInterleavedBufferAttribute||s.array.constructor!==e.array.constructor){const n=s.count;for(let r=0;r65535?new Uint32Array(n):new Uint16Array(n);t.setIndex(new St(r,1))}this._geometryInitialized=!0}}_validateGeometry(e){const t=this.geometry;if(!!e.getIndex()!=!!t.getIndex())throw new Error('THREE.BatchedMesh: All geometries must consistently have "index".');for(const i in t.attributes){if(!e.hasAttribute(i))throw new Error(`THREE.BatchedMesh: Added geometry missing "${i}". All geometries must have consistent attributes.`);const n=e.getAttribute(i),r=t.getAttribute(i);if(n.itemSize!==r.itemSize||n.normalized!==r.normalized)throw new Error("THREE.BatchedMesh: All attributes must have a consistent itemSize and normalized value.")}}validateInstanceId(e){const t=this._instanceInfo;if(e<0||e>=t.length||t[e].active===!1)throw new Error(`THREE.BatchedMesh: Invalid instanceId ${e}. Instance is either out of range or has been deleted.`)}validateGeometryId(e){const t=this._geometryInfo;if(e<0||e>=t.length||t[e].active===!1)throw new Error(`THREE.BatchedMesh: Invalid geometryId ${e}. Geometry is either out of range or has been deleted.`)}setCustomSort(e){return this.customSort=e,this}computeBoundingBox(){this.boundingBox===null&&(this.boundingBox=new vt);const e=this.boundingBox,t=this._instanceInfo;e.makeEmpty();for(let i=0,n=t.length;i=this.maxInstanceCount&&this._availableInstanceIds.length===0)throw new Error("THREE.BatchedMesh: Maximum item count reached.");const i={visible:!0,active:!0,geometryIndex:e};let n=null;this._availableInstanceIds.length>0?(this._availableInstanceIds.sort(xg),n=this._availableInstanceIds.shift(),this._instanceInfo[n]=i):(n=this._instanceInfo.length,this._instanceInfo.push(i));const r=this._matricesTexture;wn.identity().toArray(r.image.data,n*16),r.needsUpdate=!0;const a=this._colorsTexture;return a&&(X3.toArray(a.image.data,n*4),a.needsUpdate=!0),this._visibilityChanged=!0,n}addGeometry(e,t=-1,i=-1){this._initializeGeometry(e),this._validateGeometry(e);const n={vertexStart:-1,vertexCount:-1,reservedVertexCount:-1,indexStart:-1,indexCount:-1,reservedIndexCount:-1,start:-1,count:-1,boundingBox:null,boundingSphere:null,active:!0},r=this._geometryInfo;n.vertexStart=this._nextVertexStart,n.reservedVertexCount=t===-1?e.getAttribute("position").count:t;const a=e.getIndex();if(a!==null&&(n.indexStart=this._nextIndexStart,n.reservedIndexCount=i===-1?a.count:i),n.indexStart!==-1&&n.indexStart+n.reservedIndexCount>this._maxIndexCount||n.vertexStart+n.reservedVertexCount>this._maxVertexCount)throw new Error("THREE.BatchedMesh: Reserved space request exceeds the maximum buffer size.");let l;return this._availableGeometryIds.length>0?(this._availableGeometryIds.sort(xg),l=this._availableGeometryIds.shift(),r[l]=n):(l=this._geometryCount,this._geometryCount++,r.push(n)),this.setGeometryAt(l,e),this._nextIndexStart=n.indexStart+n.reservedIndexCount,this._nextVertexStart=n.vertexStart+n.reservedVertexCount,l}setGeometryAt(e,t){if(e>=this._geometryCount)throw new Error("THREE.BatchedMesh: Maximum geometry count reached.");this._validateGeometry(t);const i=this.geometry,n=i.getIndex()!==null,r=i.getIndex(),a=t.getIndex(),o=this._geometryInfo[e];if(n&&a.count>o.reservedIndexCount||t.attributes.position.count>o.reservedVertexCount)throw new Error("THREE.BatchedMesh: Reserved space not large enough for provided geometry.");const l=o.vertexStart,c=o.reservedVertexCount;o.vertexCount=t.getAttribute("position").count;for(const h in i.attributes){const d=t.getAttribute(h),p=i.getAttribute(h);Z3(d,p,l);const u=d.itemSize;for(let v=d.count,g=c;v=t.length||t[e].active===!1)return this;const i=this._instanceInfo;for(let n=0,r=i.length;no).sort((a,o)=>i[a].vertexStart-i[o].vertexStart),r=this.geometry;for(let a=0,o=i.length;a=this._geometryCount)return null;const i=this.geometry,n=this._geometryInfo[e];if(n.boundingBox===null){const r=new vt,a=i.index,o=i.attributes.position;for(let l=n.start,c=n.start+n.count;l=this._geometryCount)return null;const i=this.geometry,n=this._geometryInfo[e];if(n.boundingSphere===null){const r=new zi;this.getBoundingBoxAt(e,ju),ju.getCenter(r.center);const a=i.index,o=i.attributes.position;let l=0;for(let c=n.start,h=n.start+n.count;co.active);if(Math.max(...i.map(o=>o.vertexStart+o.reservedVertexCount))>e)throw new Error(`BatchedMesh: Geometry vertex values are being used outside the range ${t}. Cannot shrink further.`);if(this.geometry.index&&Math.max(...i.map(l=>l.indexStart+l.reservedIndexCount))>t)throw new Error(`BatchedMesh: Geometry index values are being used outside the range ${t}. Cannot shrink further.`);const r=this.geometry;r.dispose(),this._maxVertexCount=e,this._maxIndexCount=t,this._geometryInitialized&&(this._geometryInitialized=!1,this.geometry=new at,this._initializeGeometry(r));const a=this.geometry;r.index&&Ua(r.index.array,a.index.array);for(const o in r.attributes)Ua(r.attributes[o].array,a.attributes[o].array)}raycast(e,t){const i=this._instanceInfo,n=this._geometryInfo,r=this.matrixWorld,a=this.geometry;tn.material=this.material,tn.geometry.index=a.index,tn.geometry.attributes=a.attributes,tn.geometry.boundingBox===null&&(tn.geometry.boundingBox=new vt),tn.geometry.boundingSphere===null&&(tn.geometry.boundingSphere=new zi);for(let o=0,l=i.length;o({...t,boundingBox:t.boundingBox!==null?t.boundingBox.clone():null,boundingSphere:t.boundingSphere!==null?t.boundingSphere.clone():null})),this._instanceInfo=e._instanceInfo.map(t=>({...t})),this._availableInstanceIds=e._availableInstanceIds.slice(),this._availableGeometryIds=e._availableGeometryIds.slice(),this._nextIndexStart=e._nextIndexStart,this._nextVertexStart=e._nextVertexStart,this._geometryCount=e._geometryCount,this._maxInstanceCount=e._maxInstanceCount,this._maxVertexCount=e._maxVertexCount,this._maxIndexCount=e._maxIndexCount,this._geometryInitialized=e._geometryInitialized,this._multiDrawCounts=e._multiDrawCounts.slice(),this._multiDrawStarts=e._multiDrawStarts.slice(),this._indirectTexture=e._indirectTexture.clone(),this._indirectTexture.image.data=this._indirectTexture.image.data.slice(),this._matricesTexture=e._matricesTexture.clone(),this._matricesTexture.image.data=this._matricesTexture.image.data.slice(),this._colorsTexture!==null&&(this._colorsTexture=e._colorsTexture.clone(),this._colorsTexture.image.data=this._colorsTexture.image.data.slice()),this}dispose(){this.geometry.dispose(),this._matricesTexture.dispose(),this._matricesTexture=null,this._indirectTexture.dispose(),this._indirectTexture=null,this._colorsTexture!==null&&(this._colorsTexture.dispose(),this._colorsTexture=null)}onBeforeRender(e,t,i,n,r){if(!this._visibilityChanged&&!this.perObjectFrustumCulled&&!this.sortObjects)return;const a=n.getIndex();let o=a===null?1:a.array.BYTES_PER_ELEMENT,l=1;r.wireframe&&(l=2,o=n.attributes.position.count>65535?4:2);const c=this._instanceInfo,h=this._multiDrawStarts,d=this._multiDrawCounts,p=this._geometryInfo,u=this.perObjectFrustumCulled,v=this._indirectTexture,g=v.image.data,m=i.isArrayCamera?j3:Rx;u&&!i.isArrayCamera&&(wn.multiplyMatrices(i.projectionMatrix,i.matrixWorldInverse).multiply(this.matrixWorld),Rx.setFromProjectionMatrix(wn,i.coordinateSystem,i.reversedDepth));let f=0;if(this.sortObjects){wn.copy(this.matrixWorld).invert(),Yc.setFromMatrixPosition(i.matrixWorld).applyMatrix4(wn),Ix.set(0,0,-1).transformDirection(i.matrixWorld).transformDirection(wn);for(let _=0,S=c.length;_0){const n=t[i[0]];if(n!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let r=0,a=n.length;ri)return;bg.applyMatrix4(s.matrixWorld);const c=e.ray.origin.distanceTo(bg);if(!(ce.far))return{distance:c,point:Nx.clone().applyMatrix4(s.matrixWorld),index:a,face:null,faceIndex:null,barycoord:null,object:s}}const kx=new R,Ox=new R;class fi extends pn{constructor(e,t){super(e,t),this.isLineSegments=!0,this.type="LineSegments"}computeLineDistances(){const e=this.geometry;if(e.index===null){const t=e.attributes.position,i=[];for(let n=0,r=t.count;n0){const n=t[i[0]];if(n!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let r=0,a=n.length;rn.far)return;r.push({distance:c,distanceToRay:Math.sqrt(o),point:l,index:e,face:null,faceIndex:null,barycoord:null,object:a})}}class Fx extends ei{constructor(e,t,i,n,r=At,a=At,o,l,c){super(e,t,i,n,r,a,o,l,c),this.isVideoTexture=!0,this.generateMipmaps=!1,this._requestVideoFrameCallbackId=0;const h=this;function d(){h.needsUpdate=!0,h._requestVideoFrameCallbackId=e.requestVideoFrameCallback(d)}"requestVideoFrameCallback"in e&&(this._requestVideoFrameCallbackId=e.requestVideoFrameCallback(d))}clone(){return new this.constructor(this.image).copy(this)}update(){const e=this.image;"requestVideoFrameCallback"in e===!1&&e.readyState>=e.HAVE_CURRENT_DATA&&(this.needsUpdate=!0)}dispose(){this._requestVideoFrameCallbackId!==0&&(this.source.data.cancelVideoFrameCallback(this._requestVideoFrameCallbackId),this._requestVideoFrameCallbackId=0),super.dispose()}}class Y3 extends Fx{constructor(e,t,i,n,r,a,o,l){super({},e,t,i,n,r,a,o,l),this.isVideoFrameTexture=!0}update(){}clone(){return new this.constructor().copy(this)}setFrame(e){this.image=e,this.needsUpdate=!0}}class $3 extends ei{constructor(e,t){super({width:e,height:t}),this.isFramebufferTexture=!0,this.magFilter=Zt,this.minFilter=Zt,this.generateMipmaps=!1,this.needsUpdate=!0}}class ip extends ei{constructor(e,t,i,n,r,a,o,l,c,h,d,p){super(null,a,o,l,c,h,n,r,d,p),this.isCompressedTexture=!0,this.image={width:t,height:i},this.mipmaps=e,this.flipY=!1,this.generateMipmaps=!1}}class K3 extends ip{constructor(e,t,i,n,r,a){super(e,t,i,r,a),this.isCompressedArrayTexture=!0,this.image.depth=n,this.wrapR=cn,this.layerUpdates=new Set}addLayerUpdate(e){this.layerUpdates.add(e)}clearLayerUpdates(){this.layerUpdates.clear()}}class J3 extends ip{constructor(e,t,i){super(void 0,e[0].width,e[0].height,t,i,Ls),this.isCompressedCubeTexture=!0,this.isCubeTexture=!0,this.image=e}}class Kc extends ei{constructor(e=[],t=Ls,i,n,r,a,o,l,c,h){super(e,t,i,n,r,a,o,l,c,h),this.isCubeTexture=!0,this.flipY=!1}get images(){return this.image}set images(e){this.image=e}}class zx extends ei{constructor(e,t,i,n,r,a,o,l,c){super(e,t,i,n,r,a,o,l,c),this.isCanvasTexture=!0,this.needsUpdate=!0}}class Wr extends ei{constructor(e,t,i=Zn,n,r,a,o=Zt,l=Zt,c,h=Ds,d=1){if(h!==Ds&&h!==Ns)throw new Error("DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat");const p={width:e,height:t,depth:d};super(p,n,r,a,o,l,h,i,c),this.isDepthTexture=!0,this.flipY=!1,this.generateMipmaps=!1,this.compareFunction=null}copy(e){return super.copy(e),this.source=new Or(Object.assign({},e.image)),this.compareFunction=e.compareFunction,this}toJSON(e){const t=super.toJSON(e);return this.compareFunction!==null&&(t.compareFunction=this.compareFunction),t}}class Hx extends Wr{constructor(e,t=Zn,i=Ls,n,r,a=Zt,o=Zt,l,c=Ds){const h={width:e,height:e,depth:1},d=[h,h,h,h,h,h];super(e,e,t,i,n,r,a,o,l,c),this.image=d,this.isCubeDepthTexture=!0,this.isCubeTexture=!0}get images(){return this.image}set images(e){this.image=e}}class wg extends ei{constructor(e=null){super(),this.sourceTexture=e,this.isExternalTexture=!0}copy(e){return super.copy(e),this.sourceTexture=e.sourceTexture,this}}class fs extends at{constructor(e=1,t=1,i=1,n=1,r=1,a=1){super(),this.type="BoxGeometry",this.parameters={width:e,height:t,depth:i,widthSegments:n,heightSegments:r,depthSegments:a};const o=this;n=Math.floor(n),r=Math.floor(r),a=Math.floor(a);const l=[],c=[],h=[],d=[];let p=0,u=0;v("z","y","x",-1,-1,i,t,e,a,r,0),v("z","y","x",1,-1,i,t,-e,a,r,1),v("x","z","y",1,1,e,i,t,n,a,2),v("x","z","y",1,-1,e,i,-t,n,a,3),v("x","y","z",1,-1,e,t,i,n,r,4),v("x","y","z",-1,-1,e,t,-i,n,r,5),this.setIndex(l),this.setAttribute("position",new et(c,3)),this.setAttribute("normal",new et(h,3)),this.setAttribute("uv",new et(d,2));function v(g,m,f,y,x,_,S,b,E,w,M){const C=_/E,I=S/w,P=_/2,k=S/2,A=b/2,B=E+1,F=w+1;let H=0,q=0;const G=new R;for(let re=0;re0?1:-1,h.push(G.x,G.y,G.z),d.push($/E),d.push(1-re/w),H+=1}}for(let re=0;re0){const M=(y-1)*g;for(let C=0;C0&&x(!0),t>0&&x(!1)),this.setIndex(h),this.setAttribute("position",new et(d,3)),this.setAttribute("normal",new et(p,3)),this.setAttribute("uv",new et(u,2));function y(){const _=new R,S=new R;let b=0;const E=(t-e)/i;for(let w=0;w<=r;w++){const M=[],C=w/r,I=C*(t-e)+e;for(let P=0;P<=n;P++){const k=P/n,A=k*l+o,B=Math.sin(A),F=Math.cos(A);S.x=I*B,S.y=-C*i+m,S.z=I*F,d.push(S.x,S.y,S.z),_.set(B,E,F).normalize(),p.push(_.x,_.y,_.z),u.push(k,1-C),M.push(v++)}g.push(M)}for(let w=0;w0||M!==0)&&(h.push(C,I,k),b+=3),(t>0||M!==r-1)&&(h.push(I,P,k),b+=3)}c.addGroup(f,b,0),f+=b}function x(_){const S=v,b=new me,E=new R;let w=0;const M=_===!0?e:t,C=_===!0?1:-1;for(let P=1;P<=n;P++)d.push(0,m*C,0),p.push(0,C,0),u.push(.5,.5),v++;const I=v;for(let P=0;P<=n;P++){const A=P/n*l+o,B=Math.cos(A),F=Math.sin(A);E.x=M*F,E.y=m*C,E.z=M*B,d.push(E.x,E.y,E.z),p.push(0,C,0),b.x=B*.5+.5,b.y=F*.5*C+.5,u.push(b.x,b.y),v++}for(let P=0;P.9&&E<.1&&(x<.2&&(a[y+0]+=1),_<.2&&(a[y+2]+=1),S<.2&&(a[y+4]+=1))}}function p(y){r.push(y.x,y.y,y.z)}function u(y,x){const _=y*3;x.x=e[_+0],x.y=e[_+1],x.z=e[_+2]}function v(){const y=new R,x=new R,_=new R,S=new R,b=new me,E=new me,w=new me;for(let M=0,C=0;M0)l=n-1;else{l=n;break}if(n=l,i[n]===a)return n/(r-1);const h=i[n],p=i[n+1]-h,u=(a-h)/p;return(n+u)/(r-1)}getTangent(e,t){let n=e-1e-4,r=e+1e-4;n<0&&(n=0),r>1&&(r=1);const a=this.getPoint(n),o=this.getPoint(r),l=t||(a.isVector2?new me:new R);return l.copy(o).sub(a).normalize(),l}getTangentAt(e,t){const i=this.getUtoTmapping(e);return this.getTangent(i,t)}computeFrenetFrames(e,t=!1){const i=new R,n=[],r=[],a=[],o=new R,l=new qe;for(let u=0;u<=e;u++){const v=u/e;n[u]=this.getTangentAt(v,new R)}r[0]=new R,a[0]=new R;let c=Number.MAX_VALUE;const h=Math.abs(n[0].x),d=Math.abs(n[0].y),p=Math.abs(n[0].z);h<=c&&(c=h,i.set(1,0,0)),d<=c&&(c=d,i.set(0,1,0)),p<=c&&i.set(0,0,1),o.crossVectors(n[0],i).normalize(),r[0].crossVectors(n[0],o),a[0].crossVectors(n[0],r[0]);for(let u=1;u<=e;u++){if(r[u]=r[u-1].clone(),a[u]=a[u-1].clone(),o.crossVectors(n[u-1],n[u]),o.length()>Number.EPSILON){o.normalize();const v=Math.acos(dt(n[u-1].dot(n[u]),-1,1));r[u].applyMatrix4(l.makeRotationAxis(o,v))}a[u].crossVectors(n[u],r[u])}if(t===!0){let u=Math.acos(dt(r[0].dot(r[e]),-1,1));u/=e,n[0].dot(o.crossVectors(r[0],r[e]))>0&&(u=-u);for(let v=1;v<=e;v++)r[v].applyMatrix4(l.makeRotationAxis(n[v],u*v)),a[v].crossVectors(n[v],r[v])}return{tangents:n,normals:r,binormals:a}}clone(){return new this.constructor().copy(this)}copy(e){return this.arcLengthDivisions=e.arcLengthDivisions,this}toJSON(){const e={metadata:{version:4.7,type:"Curve",generator:"Curve.toJSON"}};return e.arcLengthDivisions=this.arcLengthDivisions,e.type=this.type,e}fromJSON(e){return this.arcLengthDivisions=e.arcLengthDivisions,this}}class eh extends ms{constructor(e=0,t=0,i=1,n=1,r=0,a=Math.PI*2,o=!1,l=0){super(),this.isEllipseCurve=!0,this.type="EllipseCurve",this.aX=e,this.aY=t,this.xRadius=i,this.yRadius=n,this.aStartAngle=r,this.aEndAngle=a,this.aClockwise=o,this.aRotation=l}getPoint(e,t=new me){const i=t,n=Math.PI*2;let r=this.aEndAngle-this.aStartAngle;const a=Math.abs(r)n;)r-=n;r0?0:(Math.floor(Math.abs(o)/r)+1)*r:l===0&&o===r-1&&(o=r-2,l=1);let c,h;this.closed||o>0?c=n[(o-1)%r]:(cp.subVectors(n[0],n[1]).add(n[0]),c=cp);const d=n[o%r],p=n[(o+1)%r];if(this.closed||o+2n.length-2?n.length-1:a+1],d=n[a>n.length-3?n.length-1:a+2];return i.set(Xx(o,l.x,c.x,h.x,d.x),Xx(o,l.y,c.y,h.y,d.y)),i}copy(e){super.copy(e),this.points=[];for(let t=0,i=e.points.length;t=i){const a=n[r]-i,o=this.curves[r],l=o.getLength(),c=l===0?0:1-a/l;return o.getPointAt(c,t)}r++}return null}getLength(){const e=this.getCurveLengths();return e[e.length-1]}updateArcLengths(){this.needsUpdate=!0,this.cacheLengths=null,this.getCurveLengths()}getCurveLengths(){if(this.cacheLengths&&this.cacheLengths.length===this.curves.length)return this.cacheLengths;const e=[];let t=0;for(let i=0,n=this.curves.length;i1&&!t[t.length-1].equals(t[0])&&t.push(t[0]),t}copy(e){super.copy(e),this.curves=[];for(let t=0,i=e.curves.length;t0){const d=c.getPoint(0);d.equals(this.currentPoint)||this.lineTo(d.x,d.y)}this.curves.push(c);const h=c.getPoint(1);return this.currentPoint.copy(h),this}copy(e){return super.copy(e),this.currentPoint.copy(e.currentPoint),this}toJSON(){const e=super.toJSON();return e.currentPoint=this.currentPoint.toArray(),e}fromJSON(e){return super.fromJSON(e),this.currentPoint.fromArray(e.currentPoint),this}}class nr extends nh{constructor(e){super(e),this.uuid=kn(),this.type="Shape",this.holes=[]}getPointsHoles(e){const t=[];for(let i=0,n=this.holes.length;i80*t){o=s[0],l=s[1];let h=o,d=l;for(let p=t;ph&&(h=u),v>d&&(d=v)}c=Math.max(h-o,d-l),c=c!==0?32767/c:0}return sh(r,a,t,o,l,c,0),a}function Yx(s,e,t,i,n){let r;if(n===MT(s,e,t,i)>0)for(let a=e;a=e;a-=i)r=Qx(a/i|0,s[a],s[a+1],r);return r&&fl(r,r.next)&&(oh(r),r=r.next),r}function Ba(s,e){if(!s)return s;e||(e=s);let t=s,i;do if(i=!1,!t.steiner&&(fl(t,t.next)||ri(t.prev,t,t.next)===0)){if(oh(t),t=e=t.prev,t===t.next)break;i=!0}else t=t.next;while(i||t!==e);return e}function sh(s,e,t,i,n,r,a){if(!s)return;!a&&r&&gT(s,i,n,r);let o=s;for(;s.prev!==s.next;){const l=s.prev,c=s.next;if(r?lT(s,i,n,r):oT(s)){e.push(l.i,s.i,c.i),oh(s),s=c.next,o=c.next;continue}if(s=c,s===o){a?a===1?(s=cT(Ba(s),e),sh(s,e,t,i,n,r,2)):a===2&&hT(s,e,t,i,n,r):sh(Ba(s),e,t,i,n,r,1);break}}}function oT(s){const e=s.prev,t=s,i=s.next;if(ri(e,t,i)>=0)return!1;const n=e.x,r=t.x,a=i.x,o=e.y,l=t.y,c=i.y,h=Math.min(n,r,a),d=Math.min(o,l,c),p=Math.max(n,r,a),u=Math.max(o,l,c);let v=i.next;for(;v!==e;){if(v.x>=h&&v.x<=p&&v.y>=d&&v.y<=u&&rh(n,o,r,l,a,c,v.x,v.y)&&ri(v.prev,v,v.next)>=0)return!1;v=v.next}return!0}function lT(s,e,t,i){const n=s.prev,r=s,a=s.next;if(ri(n,r,a)>=0)return!1;const o=n.x,l=r.x,c=a.x,h=n.y,d=r.y,p=a.y,u=Math.min(o,l,c),v=Math.min(h,d,p),g=Math.max(o,l,c),m=Math.max(h,d,p),f=kg(u,v,e,t,i),y=kg(g,m,e,t,i);let x=s.prevZ,_=s.nextZ;for(;x&&x.z>=f&&_&&_.z<=y;){if(x.x>=u&&x.x<=g&&x.y>=v&&x.y<=m&&x!==n&&x!==a&&rh(o,h,l,d,c,p,x.x,x.y)&&ri(x.prev,x,x.next)>=0||(x=x.prevZ,_.x>=u&&_.x<=g&&_.y>=v&&_.y<=m&&_!==n&&_!==a&&rh(o,h,l,d,c,p,_.x,_.y)&&ri(_.prev,_,_.next)>=0))return!1;_=_.nextZ}for(;x&&x.z>=f;){if(x.x>=u&&x.x<=g&&x.y>=v&&x.y<=m&&x!==n&&x!==a&&rh(o,h,l,d,c,p,x.x,x.y)&&ri(x.prev,x,x.next)>=0)return!1;x=x.prevZ}for(;_&&_.z<=y;){if(_.x>=u&&_.x<=g&&_.y>=v&&_.y<=m&&_!==n&&_!==a&&rh(o,h,l,d,c,p,_.x,_.y)&&ri(_.prev,_,_.next)>=0)return!1;_=_.nextZ}return!0}function cT(s,e){let t=s;do{const i=t.prev,n=t.next.next;!fl(i,n)&&Kx(i,t,t.next,n)&&ah(i,n)&&ah(n,i)&&(e.push(i.i,t.i,n.i),oh(t),oh(t.next),t=s=n),t=t.next}while(t!==s);return Ba(t)}function hT(s,e,t,i,n,r){let a=s;do{let o=a.next.next;for(;o!==a.prev;){if(a.i!==o.i&&xT(a,o)){let l=Jx(a,o);a=Ba(a,a.next),l=Ba(l,l.next),sh(a,e,t,i,n,r,0),sh(l,e,t,i,n,r,0);return}o=o.next}a=a.next}while(a!==s)}function dT(s,e,t,i){const n=[];for(let r=0,a=e.length;r=t.next.y&&t.next.y!==t.y){const d=t.x+(n-t.y)*(t.next.x-t.x)/(t.next.y-t.y);if(d<=i&&d>r&&(r=d,a=t.x=t.x&&t.x>=l&&i!==t.x&&$x(na.x||t.x===a.x&&mT(a,t)))&&(a=t,h=d)}t=t.next}while(t!==o);return a}function mT(s,e){return ri(s.prev,s,e.prev)<0&&ri(e.next,s,s.next)<0}function gT(s,e,t,i){let n=s;do n.z===0&&(n.z=kg(n.x,n.y,e,t,i)),n.prevZ=n.prev,n.nextZ=n.next,n=n.next;while(n!==s);n.prevZ.nextZ=null,n.prevZ=null,vT(n)}function vT(s){let e,t=1;do{let i=s,n;s=null;let r=null;for(e=0;i;){e++;let a=i,o=0;for(let c=0;c0||l>0&&a;)o!==0&&(l===0||!a||i.z<=a.z)?(n=i,i=i.nextZ,o--):(n=a,a=a.nextZ,l--),r?r.nextZ=n:s=n,n.prevZ=r,r=n;i=a}r.nextZ=null,t*=2}while(e>1);return s}function kg(s,e,t,i,n){return s=(s-t)*n|0,e=(e-i)*n|0,s=(s|s<<8)&16711935,s=(s|s<<4)&252645135,s=(s|s<<2)&858993459,s=(s|s<<1)&1431655765,e=(e|e<<8)&16711935,e=(e|e<<4)&252645135,e=(e|e<<2)&858993459,e=(e|e<<1)&1431655765,s|e<<1}function yT(s){let e=s,t=s;do(e.x=(s-a)*(r-o)&&(s-a)*(i-o)>=(t-a)*(e-o)&&(t-a)*(r-o)>=(n-a)*(i-o)}function rh(s,e,t,i,n,r,a,o){return!(s===a&&e===o)&&$x(s,e,t,i,n,r,a,o)}function xT(s,e){return s.next.i!==e.i&&s.prev.i!==e.i&&!_T(s,e)&&(ah(s,e)&&ah(e,s)&&bT(s,e)&&(ri(s.prev,s,e.prev)||ri(s,e.prev,e))||fl(s,e)&&ri(s.prev,s,s.next)>0&&ri(e.prev,e,e.next)>0)}function ri(s,e,t){return(e.y-s.y)*(t.x-e.x)-(e.x-s.x)*(t.y-e.y)}function fl(s,e){return s.x===e.x&&s.y===e.y}function Kx(s,e,t,i){const n=up(ri(s,e,t)),r=up(ri(s,e,i)),a=up(ri(t,i,s)),o=up(ri(t,i,e));return!!(n!==r&&a!==o||n===0&&dp(s,t,e)||r===0&&dp(s,i,e)||a===0&&dp(t,s,i)||o===0&&dp(t,e,i))}function dp(s,e,t){return e.x<=Math.max(s.x,t.x)&&e.x>=Math.min(s.x,t.x)&&e.y<=Math.max(s.y,t.y)&&e.y>=Math.min(s.y,t.y)}function up(s){return s>0?1:s<0?-1:0}function _T(s,e){let t=s;do{if(t.i!==s.i&&t.next.i!==s.i&&t.i!==e.i&&t.next.i!==e.i&&Kx(t,t.next,s,e))return!0;t=t.next}while(t!==s);return!1}function ah(s,e){return ri(s.prev,s,s.next)<0?ri(s,e,s.next)>=0&&ri(s,s.prev,e)>=0:ri(s,e,s.prev)<0||ri(s,s.next,e)<0}function bT(s,e){let t=s,i=!1;const n=(s.x+e.x)/2,r=(s.y+e.y)/2;do t.y>r!=t.next.y>r&&t.next.y!==t.y&&n<(t.next.x-t.x)*(r-t.y)/(t.next.y-t.y)+t.x&&(i=!i),t=t.next;while(t!==s);return i}function Jx(s,e){const t=Og(s.i,s.x,s.y),i=Og(e.i,e.x,e.y),n=s.next,r=e.prev;return s.next=e,e.prev=s,t.next=n,n.prev=t,i.next=t,t.prev=i,r.next=i,i.prev=r,i}function Qx(s,e,t,i){const n=Og(s,e,t);return i?(n.next=i.next,n.prev=i,i.next.prev=n,i.next=n):(n.prev=n,n.next=n),n}function oh(s){s.next.prev=s.prev,s.prev.next=s.next,s.prevZ&&(s.prevZ.nextZ=s.nextZ),s.nextZ&&(s.nextZ.prevZ=s.prevZ)}function Og(s,e,t){return{i:s,x:e,y:t,prev:null,next:null,z:0,prevZ:null,nextZ:null,steiner:!1}}function MT(s,e,t,i){let n=0;for(let r=e,a=t-i;r2&&s[e-1].equals(s[0])&&s.pop()}function t_(s,e){for(let t=0;tNumber.EPSILON){const j=Math.sqrt(T),K=Math.sqrt(ee*ee+L*L),Z=ae.x-V/j,Pe=ae.y+de/j,ve=Q.x-L/K,ke=Q.y+ee/K,Fe=((ve-Z)*L-(ke-Pe)*ee)/(de*L-V*ee);W=Z+de*Fe-D.x,N=Pe+V*Fe-D.y;const le=W*W+N*N;if(le<=2)return new me(W,N);te=Math.sqrt(le/2)}else{let j=!1;de>Number.EPSILON?ee>Number.EPSILON&&(j=!0):de<-Number.EPSILON?ee<-Number.EPSILON&&(j=!0):Math.sign(V)===Math.sign(L)&&(j=!0),j?(W=-V,N=de,te=Math.sqrt(T)):(W=de,N=V,te=Math.sqrt(T/2))}return new me(W/te,N/te)}const G=[];for(let D=0,ae=B.length,Q=ae-1,W=D+1;D=0;D--){const ae=D/m,Q=u*Math.cos(ae*Math.PI/2),W=v*Math.sin(ae*Math.PI/2)+g;for(let N=0,te=B.length;N=0;){const W=Q;let N=Q-1;N<0&&(N=D.length-1);for(let te=0,de=h+m*2;te0)&&u.push(x,_,b),(f!==i-1||l0&&(t.defines=this.defines),t.vertexShader=this.vertexShader,t.fragmentShader=this.fragmentShader,t.lights=this.lights,t.clipping=this.clipping;const i={};for(const n in this.extensions)this.extensions[n]===!0&&(i[n]=!0);return Object.keys(i).length>0&&(t.extensions=i),t}}class _p extends Jt{constructor(e){super(e),this.isRawShaderMaterial=!0,this.type="RawShaderMaterial"}}class sr extends Ri{constructor(e){super(),this.isMeshStandardMaterial=!0,this.type="MeshStandardMaterial",this.defines={STANDARD:""},this.color=new We(16777215),this.roughness=1,this.metalness=0,this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new We(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=Nr,this.normalScale=new me(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.roughnessMap=null,this.metalnessMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new Fi,this.envMapIntensity=1,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.flatShading=!1,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.defines={STANDARD:""},this.color.copy(e.color),this.roughness=e.roughness,this.metalness=e.metalness,this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.emissive.copy(e.emissive),this.emissiveMap=e.emissiveMap,this.emissiveIntensity=e.emissiveIntensity,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.roughnessMap=e.roughnessMap,this.metalnessMap=e.metalnessMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.envMapIntensity=e.envMapIntensity,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.flatShading=e.flatShading,this.fog=e.fog,this}}class $n extends sr{constructor(e){super(),this.isMeshPhysicalMaterial=!0,this.defines={STANDARD:"",PHYSICAL:""},this.type="MeshPhysicalMaterial",this.anisotropyRotation=0,this.anisotropyMap=null,this.clearcoatMap=null,this.clearcoatRoughness=0,this.clearcoatRoughnessMap=null,this.clearcoatNormalScale=new me(1,1),this.clearcoatNormalMap=null,this.ior=1.5,Object.defineProperty(this,"reflectivity",{get:function(){return dt(2.5*(this.ior-1)/(this.ior+1),0,1)},set:function(t){this.ior=(1+.4*t)/(1-.4*t)}}),this.iridescenceMap=null,this.iridescenceIOR=1.3,this.iridescenceThicknessRange=[100,400],this.iridescenceThicknessMap=null,this.sheenColor=new We(0),this.sheenColorMap=null,this.sheenRoughness=1,this.sheenRoughnessMap=null,this.transmissionMap=null,this.thickness=0,this.thicknessMap=null,this.attenuationDistance=1/0,this.attenuationColor=new We(1,1,1),this.specularIntensity=1,this.specularIntensityMap=null,this.specularColor=new We(1,1,1),this.specularColorMap=null,this._anisotropy=0,this._clearcoat=0,this._dispersion=0,this._iridescence=0,this._sheen=0,this._transmission=0,this.setValues(e)}get anisotropy(){return this._anisotropy}set anisotropy(e){this._anisotropy>0!=e>0&&this.version++,this._anisotropy=e}get clearcoat(){return this._clearcoat}set clearcoat(e){this._clearcoat>0!=e>0&&this.version++,this._clearcoat=e}get iridescence(){return this._iridescence}set iridescence(e){this._iridescence>0!=e>0&&this.version++,this._iridescence=e}get dispersion(){return this._dispersion}set dispersion(e){this._dispersion>0!=e>0&&this.version++,this._dispersion=e}get sheen(){return this._sheen}set sheen(e){this._sheen>0!=e>0&&this.version++,this._sheen=e}get transmission(){return this._transmission}set transmission(e){this._transmission>0!=e>0&&this.version++,this._transmission=e}copy(e){return super.copy(e),this.defines={STANDARD:"",PHYSICAL:""},this.anisotropy=e.anisotropy,this.anisotropyRotation=e.anisotropyRotation,this.anisotropyMap=e.anisotropyMap,this.clearcoat=e.clearcoat,this.clearcoatMap=e.clearcoatMap,this.clearcoatRoughness=e.clearcoatRoughness,this.clearcoatRoughnessMap=e.clearcoatRoughnessMap,this.clearcoatNormalMap=e.clearcoatNormalMap,this.clearcoatNormalScale.copy(e.clearcoatNormalScale),this.dispersion=e.dispersion,this.ior=e.ior,this.iridescence=e.iridescence,this.iridescenceMap=e.iridescenceMap,this.iridescenceIOR=e.iridescenceIOR,this.iridescenceThicknessRange=[...e.iridescenceThicknessRange],this.iridescenceThicknessMap=e.iridescenceThicknessMap,this.sheen=e.sheen,this.sheenColor.copy(e.sheenColor),this.sheenColorMap=e.sheenColorMap,this.sheenRoughness=e.sheenRoughness,this.sheenRoughnessMap=e.sheenRoughnessMap,this.transmission=e.transmission,this.transmissionMap=e.transmissionMap,this.thickness=e.thickness,this.thicknessMap=e.thicknessMap,this.attenuationDistance=e.attenuationDistance,this.attenuationColor.copy(e.attenuationColor),this.specularIntensity=e.specularIntensity,this.specularIntensityMap=e.specularIntensityMap,this.specularColor.copy(e.specularColor),this.specularColorMap=e.specularColorMap,this}}class o_ extends Ri{constructor(e){super(),this.isMeshPhongMaterial=!0,this.type="MeshPhongMaterial",this.color=new We(16777215),this.specular=new We(1118481),this.shininess=30,this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new We(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=Nr,this.normalScale=new me(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new Fi,this.combine=_c,this.reflectivity=1,this.envMapIntensity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.flatShading=!1,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.specular.copy(e.specular),this.shininess=e.shininess,this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.emissive.copy(e.emissive),this.emissiveMap=e.emissiveMap,this.emissiveIntensity=e.emissiveIntensity,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.specularMap=e.specularMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.combine=e.combine,this.reflectivity=e.reflectivity,this.envMapIntensity=e.envMapIntensity,this.refractionRatio=e.refractionRatio,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.flatShading=e.flatShading,this.fog=e.fog,this}}class l_ extends Ri{constructor(e){super(),this.isMeshToonMaterial=!0,this.defines={TOON:""},this.type="MeshToonMaterial",this.color=new We(16777215),this.map=null,this.gradientMap=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new We(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=Nr,this.normalScale=new me(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.alphaMap=null,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.gradientMap=e.gradientMap,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.emissive.copy(e.emissive),this.emissiveMap=e.emissiveMap,this.emissiveIntensity=e.emissiveIntensity,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.alphaMap=e.alphaMap,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.fog=e.fog,this}}class bp extends Ri{constructor(e){super(),this.isMeshNormalMaterial=!0,this.type="MeshNormalMaterial",this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=Nr,this.normalScale=new me(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.wireframe=!1,this.wireframeLinewidth=1,this.flatShading=!1,this.setValues(e)}copy(e){return super.copy(e),this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.flatShading=e.flatShading,this}}class Ug extends Ri{constructor(e){super(),this.isMeshLambertMaterial=!0,this.type="MeshLambertMaterial",this.color=new We(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new We(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=Nr,this.normalScale=new me(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new Fi,this.combine=_c,this.reflectivity=1,this.envMapIntensity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.flatShading=!1,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.emissive.copy(e.emissive),this.emissiveMap=e.emissiveMap,this.emissiveIntensity=e.emissiveIntensity,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.specularMap=e.specularMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.combine=e.combine,this.reflectivity=e.reflectivity,this.envMapIntensity=e.envMapIntensity,this.refractionRatio=e.refractionRatio,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.flatShading=e.flatShading,this.fog=e.fog,this}}class Bg extends Ri{constructor(e){super(),this.isMeshDepthMaterial=!0,this.type="MeshDepthMaterial",this.depthPacking=Vy,this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.wireframe=!1,this.wireframeLinewidth=1,this.setValues(e)}copy(e){return super.copy(e),this.depthPacking=e.depthPacking,this.map=e.map,this.alphaMap=e.alphaMap,this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this}}class Fg extends Ri{constructor(e){super(),this.isMeshDistanceMaterial=!0,this.type="MeshDistanceMaterial",this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.setValues(e)}copy(e){return super.copy(e),this.map=e.map,this.alphaMap=e.alphaMap,this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this}}class c_ extends Ri{constructor(e){super(),this.isMeshMatcapMaterial=!0,this.defines={MATCAP:""},this.type="MeshMatcapMaterial",this.color=new We(16777215),this.matcap=null,this.map=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=Nr,this.normalScale=new me(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.alphaMap=null,this.wireframe=!1,this.wireframeLinewidth=1,this.flatShading=!1,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.defines={MATCAP:""},this.color.copy(e.color),this.matcap=e.matcap,this.map=e.map,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.alphaMap=e.alphaMap,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.flatShading=e.flatShading,this.fog=e.fog,this}}class h_ extends si{constructor(e){super(),this.isLineDashedMaterial=!0,this.type="LineDashedMaterial",this.scale=1,this.dashSize=3,this.gapSize=1,this.setValues(e)}copy(e){return super.copy(e),this.scale=e.scale,this.dashSize=e.dashSize,this.gapSize=e.gapSize,this}}function za(s,e){return!s||s.constructor===e?s:typeof e.BYTES_PER_ELEMENT=="number"?new e(s):Array.prototype.slice.call(s)}function d_(s){function e(n,r){return s[n]-s[r]}const t=s.length,i=new Array(t);for(let n=0;n!==t;++n)i[n]=n;return i.sort(e),i}function zg(s,e,t){const i=s.length,n=new s.constructor(i);for(let r=0,a=0;a!==i;++r){const o=t[r]*e;for(let l=0;l!==e;++l)n[a++]=s[o+l]}return n}function Hg(s,e,t,i){let n=1,r=s[0];for(;r!==void 0&&r[i]===void 0;)r=s[n++];if(r===void 0)return;let a=r[i];if(a!==void 0)if(Array.isArray(a))do a=r[i],a!==void 0&&(e.push(r.time),t.push(...a)),r=s[n++];while(r!==void 0);else if(a.toArray!==void 0)do a=r[i],a!==void 0&&(e.push(r.time),a.toArray(t,t.length)),r=s[n++];while(r!==void 0);else do a=r[i],a!==void 0&&(e.push(r.time),t.push(a)),r=s[n++];while(r!==void 0)}function RT(s,e,t,i,n=30){const r=s.clone();r.name=e;const a=[];for(let l=0;l=i)){d.push(c.times[u]);for(let g=0;gr.tracks[l].times[0]&&(o=r.tracks[l].times[0]);for(let l=0;l=o.times[v]){const f=v*d+h,y=f+d-h;g=o.values.slice(f,y)}else{const f=o.createInterpolant(),y=h,x=d-h;f.evaluate(r),g=f.resultBuffer.slice(y,x)}l==="quaternion"&&new Kt().fromArray(g).normalize().conjugate().toArray(g);const m=c.times.length;for(let f=0;f=r)){const o=t[1];e=r)break t}a=i,i=0;break i}break e}for(;i>>1;et;)--a;if(++a,r!==0||a!==n){r>=a&&(a=Math.max(a,1),r=a-1);const o=this.getValueSize();this.times=i.slice(r,a),this.values=this.values.slice(r*o,a*o)}return this}validate(){let e=!0;const t=this.getValueSize();t-Math.floor(t)!==0&&(lt("KeyframeTrack: Invalid value size in track.",this),e=!1);const i=this.times,n=this.values,r=i.length;r===0&&(lt("KeyframeTrack: Track is empty.",this),e=!1);let a=null;for(let o=0;o!==r;o++){const l=i[o];if(typeof l=="number"&&isNaN(l)){lt("KeyframeTrack: Time is not a valid number.",this,o,l),e=!1;break}if(a!==null&&a>l){lt("KeyframeTrack: Out of order keys.",this,o,l,a),e=!1;break}a=l}if(n!==void 0&&$y(n))for(let o=0,l=n.length;o!==l;++o){const c=n[o];if(isNaN(c)){lt("KeyframeTrack: Value is not a valid number.",this,o,c),e=!1;break}}return e}optimize(){const e=this.times.slice(),t=this.values.slice(),i=this.getValueSize(),n=this.getInterpolation()===cu,r=e.length-1;let a=1;for(let o=1;o0){e[a]=e[r];for(let o=r*i,l=a*i,c=0;c!==i;++c)t[l+c]=t[o+c];++a}return a!==e.length?(this.times=e.slice(0,a),this.values=t.slice(0,a*i)):(this.times=e,this.values=t),this}clone(){const e=this.times.slice(),t=this.values.slice(),i=this.constructor,n=new i(this.name,e,t);return n.createInterpolant=this.createInterpolant,n}}Kn.prototype.ValueTypeName="",Kn.prototype.TimeBufferType=Float32Array,Kn.prototype.ValueBufferType=Float32Array,Kn.prototype.DefaultInterpolation=Zo;class Va extends Kn{constructor(e,t,i){super(e,t,i)}}Va.prototype.ValueTypeName="bool",Va.prototype.ValueBufferType=Array,Va.prototype.DefaultInterpolation=qo,Va.prototype.InterpolantFactoryMethodLinear=void 0,Va.prototype.InterpolantFactoryMethodSmooth=void 0;class Gg extends Kn{constructor(e,t,i,n){super(e,t,i,n)}}Gg.prototype.ValueTypeName="color";class Ga extends Kn{constructor(e,t,i,n){super(e,t,i,n)}}Ga.prototype.ValueTypeName="number";class m_ extends Ha{constructor(e,t,i,n){super(e,t,i,n)}interpolate_(e,t,i,n){const r=this.resultBuffer,a=this.sampleValues,o=this.valueSize,l=(i-t)/(n-t);let c=e*o;for(let h=c+o;c!==h;c+=4)Kt.slerpFlat(r,0,a,c-o,a,c,l);return r}}class Wa extends Kn{constructor(e,t,i,n){super(e,t,i,n)}InterpolantFactoryMethodLinear(e){return new m_(this.times,this.values,this.getValueSize(),e)}}Wa.prototype.ValueTypeName="quaternion",Wa.prototype.InterpolantFactoryMethodSmooth=void 0;class Xa extends Kn{constructor(e,t,i){super(e,t,i)}}Xa.prototype.ValueTypeName="string",Xa.prototype.ValueBufferType=Array,Xa.prototype.DefaultInterpolation=qo,Xa.prototype.InterpolantFactoryMethodLinear=void 0,Xa.prototype.InterpolantFactoryMethodSmooth=void 0;class ja extends Kn{constructor(e,t,i,n){super(e,t,i,n)}}ja.prototype.ValueTypeName="vector";class vl{constructor(e="",t=-1,i=[],n=hu){this.name=e,this.tracks=i,this.duration=t,this.blendMode=n,this.uuid=kn(),this.userData={},this.duration<0&&this.resetDuration()}static parse(e){const t=[],i=e.tracks,n=1/(e.fps||1);for(let a=0,o=i.length;a!==o;++a)t.push(NT(i[a]).scale(n));const r=new this(e.name,e.duration,t,e.blendMode);return r.uuid=e.uuid,r.userData=JSON.parse(e.userData||"{}"),r}static toJSON(e){const t=[],i=e.tracks,n={name:e.name,duration:e.duration,tracks:t,uuid:e.uuid,blendMode:e.blendMode,userData:JSON.stringify(e.userData)};for(let r=0,a=i.length;r!==a;++r)t.push(Kn.toJSON(i[r]));return n}static CreateFromMorphTargetSequence(e,t,i,n){const r=t.length,a=[];for(let o=0;o1){const d=h[1];let p=n[d];p||(n[d]=p=[]),p.push(c)}}const a=[];for(const o in n)a.push(this.CreateFromMorphTargetSequence(o,n[o],t,i));return a}static parseAnimation(e,t){if(Ye("AnimationClip: parseAnimation() is deprecated and will be removed with r185"),!e)return lt("AnimationClip: No animation in JSONLoader data."),null;const i=function(d,p,u,v,g){if(u.length!==0){const m=[],f=[];Hg(u,m,f,v),m.length!==0&&g.push(new d(p,m,f))}},n=[],r=e.name||"default",a=e.fps||30,o=e.blendMode;let l=e.length||-1;const c=e.hierarchy||[];for(let d=0;d{t&&t(r),this.manager.itemEnd(e)},0),r;if(rr[e]!==void 0){rr[e].push({onLoad:t,onProgress:i,onError:n});return}rr[e]=[],rr[e].push({onLoad:t,onProgress:i,onError:n});const a=new Request(e,{headers:new Headers(this.requestHeader),credentials:this.withCredentials?"include":"same-origin",signal:typeof AbortSignal.any=="function"?AbortSignal.any([this._abortController.signal,this.manager.abortController.signal]):this._abortController.signal}),o=this.mimeType,l=this.responseType;fetch(a).then(c=>{if(c.status===200||c.status===0){if(c.status===0&&Ye("FileLoader: HTTP Status 0 received."),typeof ReadableStream>"u"||c.body===void 0||c.body.getReader===void 0)return c;const h=rr[e],d=c.body.getReader(),p=c.headers.get("X-File-Size")||c.headers.get("Content-Length"),u=p?parseInt(p):0,v=u!==0;let g=0;const m=new ReadableStream({start(f){y();function y(){d.read().then(({done:x,value:_})=>{if(x)f.close();else{g+=_.byteLength;const S=new ProgressEvent("progress",{lengthComputable:v,loaded:g,total:u});for(let b=0,E=h.length;b{f.error(x)})}}});return new Response(m)}else throw new kT(`fetch for "${c.url}" responded with ${c.status}: ${c.statusText}`,c)}).then(c=>{switch(l){case"arraybuffer":return c.arrayBuffer();case"blob":return c.blob();case"document":return c.text().then(h=>new DOMParser().parseFromString(h,o));case"json":return c.json();default:if(o==="")return c.text();{const d=/charset="?([^;"\s]*)"?/i.exec(o),p=d&&d[1]?d[1].toLowerCase():void 0,u=new TextDecoder(p);return c.arrayBuffer().then(v=>u.decode(v))}}}).then(c=>{Bs.add(`file:${e}`,c);const h=rr[e];delete rr[e];for(let d=0,p=h.length;d{const h=rr[e];if(h===void 0)throw this.manager.itemError(e),c;delete rr[e];for(let d=0,p=h.length;d{this.manager.itemEnd(e)}),this.manager.itemStart(e)}setResponseType(e){return this.responseType=e,this}setMimeType(e){return this.mimeType=e,this}abort(){return this._abortController.abort(),this._abortController=new AbortController,this}}class OT extends sn{constructor(e){super(e)}load(e,t,i,n){const r=this,a=new Jn(this.manager);a.setPath(this.path),a.setRequestHeader(this.requestHeader),a.setWithCredentials(this.withCredentials),a.load(e,function(o){try{t(r.parse(JSON.parse(o)))}catch(l){n?n(l):lt(l),r.manager.itemError(e)}},i,n)}parse(e){const t=[];for(let i=0;i0:n.vertexColors=e.vertexColors),e.uniforms!==void 0)for(const r in e.uniforms){const a=e.uniforms[r];switch(n.uniforms[r]={},a.type){case"t":n.uniforms[r].value=i(a.value);break;case"c":n.uniforms[r].value=new We().setHex(a.value);break;case"v2":n.uniforms[r].value=new me().fromArray(a.value);break;case"v3":n.uniforms[r].value=new R().fromArray(a.value);break;case"v4":n.uniforms[r].value=new Pt().fromArray(a.value);break;case"m3":n.uniforms[r].value=new ft().fromArray(a.value);break;case"m4":n.uniforms[r].value=new qe().fromArray(a.value);break;default:n.uniforms[r].value=a.value}}if(e.defines!==void 0&&(n.defines=e.defines),e.vertexShader!==void 0&&(n.vertexShader=e.vertexShader),e.fragmentShader!==void 0&&(n.fragmentShader=e.fragmentShader),e.glslVersion!==void 0&&(n.glslVersion=e.glslVersion),e.extensions!==void 0)for(const r in e.extensions)n.extensions[r]=e.extensions[r];if(e.lights!==void 0&&(n.lights=e.lights),e.clipping!==void 0&&(n.clipping=e.clipping),e.size!==void 0&&(n.size=e.size),e.sizeAttenuation!==void 0&&(n.sizeAttenuation=e.sizeAttenuation),e.map!==void 0&&(n.map=i(e.map)),e.matcap!==void 0&&(n.matcap=i(e.matcap)),e.alphaMap!==void 0&&(n.alphaMap=i(e.alphaMap)),e.bumpMap!==void 0&&(n.bumpMap=i(e.bumpMap)),e.bumpScale!==void 0&&(n.bumpScale=e.bumpScale),e.normalMap!==void 0&&(n.normalMap=i(e.normalMap)),e.normalMapType!==void 0&&(n.normalMapType=e.normalMapType),e.normalScale!==void 0){let r=e.normalScale;Array.isArray(r)===!1&&(r=[r,r]),n.normalScale=new me().fromArray(r)}return e.displacementMap!==void 0&&(n.displacementMap=i(e.displacementMap)),e.displacementScale!==void 0&&(n.displacementScale=e.displacementScale),e.displacementBias!==void 0&&(n.displacementBias=e.displacementBias),e.roughnessMap!==void 0&&(n.roughnessMap=i(e.roughnessMap)),e.metalnessMap!==void 0&&(n.metalnessMap=i(e.metalnessMap)),e.emissiveMap!==void 0&&(n.emissiveMap=i(e.emissiveMap)),e.emissiveIntensity!==void 0&&(n.emissiveIntensity=e.emissiveIntensity),e.specularMap!==void 0&&(n.specularMap=i(e.specularMap)),e.specularIntensityMap!==void 0&&(n.specularIntensityMap=i(e.specularIntensityMap)),e.specularColorMap!==void 0&&(n.specularColorMap=i(e.specularColorMap)),e.envMap!==void 0&&(n.envMap=i(e.envMap)),e.envMapRotation!==void 0&&n.envMapRotation.fromArray(e.envMapRotation),e.envMapIntensity!==void 0&&(n.envMapIntensity=e.envMapIntensity),e.reflectivity!==void 0&&(n.reflectivity=e.reflectivity),e.refractionRatio!==void 0&&(n.refractionRatio=e.refractionRatio),e.lightMap!==void 0&&(n.lightMap=i(e.lightMap)),e.lightMapIntensity!==void 0&&(n.lightMapIntensity=e.lightMapIntensity),e.aoMap!==void 0&&(n.aoMap=i(e.aoMap)),e.aoMapIntensity!==void 0&&(n.aoMapIntensity=e.aoMapIntensity),e.gradientMap!==void 0&&(n.gradientMap=i(e.gradientMap)),e.clearcoatMap!==void 0&&(n.clearcoatMap=i(e.clearcoatMap)),e.clearcoatRoughnessMap!==void 0&&(n.clearcoatRoughnessMap=i(e.clearcoatRoughnessMap)),e.clearcoatNormalMap!==void 0&&(n.clearcoatNormalMap=i(e.clearcoatNormalMap)),e.clearcoatNormalScale!==void 0&&(n.clearcoatNormalScale=new me().fromArray(e.clearcoatNormalScale)),e.iridescenceMap!==void 0&&(n.iridescenceMap=i(e.iridescenceMap)),e.iridescenceThicknessMap!==void 0&&(n.iridescenceThicknessMap=i(e.iridescenceThicknessMap)),e.transmissionMap!==void 0&&(n.transmissionMap=i(e.transmissionMap)),e.thicknessMap!==void 0&&(n.thicknessMap=i(e.thicknessMap)),e.anisotropyMap!==void 0&&(n.anisotropyMap=i(e.anisotropyMap)),e.sheenColorMap!==void 0&&(n.sheenColorMap=i(e.sheenColorMap)),e.sheenRoughnessMap!==void 0&&(n.sheenRoughnessMap=i(e.sheenRoughnessMap)),n}setTextures(e){return this.textures=e,this}createMaterialFromType(e){return Ep.createMaterialFromType(e)}static createMaterialFromType(e){const t={ShadowMaterial:r_,SpriteMaterial:Cu,RawShaderMaterial:_p,ShaderMaterial:Jt,PointsMaterial:Ju,MeshPhysicalMaterial:$n,MeshStandardMaterial:sr,MeshPhongMaterial:o_,MeshToonMaterial:l_,MeshNormalMaterial:bp,MeshLambertMaterial:Ug,MeshDepthMaterial:Bg,MeshDistanceMaterial:Fg,MeshBasicMaterial:Dt,MeshMatcapMaterial:c_,LineDashedMaterial:h_,LineBasicMaterial:si,Material:Ri};return new t[e]}}class Yr{static extractUrlBase(e){const t=e.lastIndexOf("/");return t===-1?"./":e.slice(0,t+1)}static resolveURL(e,t){return typeof e!="string"||e===""?"":(/^https?:\/\//i.test(t)&&/^\//.test(e)&&(t=t.replace(/(^https?:\/\/[^\/]+).*/i,"$1")),/^(https?:)?\/\//i.test(e)||/^data:.*,.*$/i.test(e)||/^blob:.*$/i.test(e)?e:t+e)}}class T_ extends at{constructor(){super(),this.isInstancedBufferGeometry=!0,this.type="InstancedBufferGeometry",this.instanceCount=1/0}copy(e){return super.copy(e),this.instanceCount=e.instanceCount,this}toJSON(){const e=super.toJSON();return e.instanceCount=this.instanceCount,e.isInstancedBufferGeometry=!0,e}}class C_ extends sn{constructor(e){super(e)}load(e,t,i,n){const r=this,a=new Jn(r.manager);a.setPath(r.path),a.setRequestHeader(r.requestHeader),a.setWithCredentials(r.withCredentials),a.load(e,function(o){try{t(r.parse(JSON.parse(o)))}catch(l){n?n(l):lt(l),r.manager.itemError(e)}},i,n)}parse(e){const t={},i={};function n(u,v){if(t[v]!==void 0)return t[v];const m=u.interleavedBuffers[v],f=r(u,m.buffer),y=Yo(m.type,f),x=new Hc(y,m.stride);return x.uuid=m.uuid,t[v]=x,x}function r(u,v){if(i[v]!==void 0)return i[v];const m=u.arrayBuffers[v],f=new Uint32Array(m).buffer;return i[v]=f,f}const a=e.isInstancedBufferGeometry?new T_:new at,o=e.data.index;if(o!==void 0){const u=Yo(o.type,o.array);a.setIndex(new St(u,1))}const l=e.data.attributes;for(const u in l){const v=l[u];let g;if(v.isInterleavedBufferAttribute){const m=n(e.data,v.data);g=new Hr(m,v.itemSize,v.offset,v.normalized)}else{const m=Yo(v.type,v.array),f=v.isInstancedBufferAttribute?Gr:St;g=new f(m,v.itemSize,v.normalized)}v.name!==void 0&&(g.name=v.name),v.usage!==void 0&&g.setUsage(v.usage),a.setAttribute(u,g)}const c=e.data.morphAttributes;if(c)for(const u in c){const v=c[u],g=[];for(let m=0,f=v.length;m0){const l=new Wg(t);r=new hh(l),r.setCrossOrigin(this.crossOrigin);for(let c=0,h=e.length;c0){n=new hh(this.manager),n.setCrossOrigin(this.crossOrigin);for(let a=0,o=e.length;a{let f=null,y=null;return m.boundingBox!==void 0&&(f=new vt().fromJSON(m.boundingBox)),m.boundingSphere!==void 0&&(y=new zi().fromJSON(m.boundingSphere)),{...m,boundingBox:f,boundingSphere:y}}),a._instanceInfo=e.instanceInfo,a._availableInstanceIds=e._availableInstanceIds,a._availableGeometryIds=e._availableGeometryIds,a._nextIndexStart=e.nextIndexStart,a._nextVertexStart=e.nextVertexStart,a._geometryCount=e.geometryCount,a._maxInstanceCount=e.maxInstanceCount,a._maxVertexCount=e.maxVertexCount,a._maxIndexCount=e.maxIndexCount,a._geometryInitialized=e.geometryInitialized,a._matricesTexture=c(e.matricesTexture.uuid),a._indirectTexture=c(e.indirectTexture.uuid),e.colorsTexture!==void 0&&(a._colorsTexture=c(e.colorsTexture.uuid)),e.boundingSphere!==void 0&&(a.boundingSphere=new zi().fromJSON(e.boundingSphere)),e.boundingBox!==void 0&&(a.boundingBox=new vt().fromJSON(e.boundingBox));break;case"LOD":a=new yx;break;case"Line":a=new pn(o(e.geometry),l(e.material));break;case"LineLoop":a=new Mg(o(e.geometry),l(e.material));break;case"LineSegments":a=new fi(o(e.geometry),l(e.material));break;case"PointCloud":case"Points":a=new tp(o(e.geometry),l(e.material));break;case"Sprite":a=new Xc(l(e.material));break;case"Group":a=new pi;break;case"Bone":a=new Vu;break;default:a=new Rt}if(a.uuid=e.uuid,e.name!==void 0&&(a.name=e.name),e.matrix!==void 0?(a.matrix.fromArray(e.matrix),e.matrixAutoUpdate!==void 0&&(a.matrixAutoUpdate=e.matrixAutoUpdate),a.matrixAutoUpdate&&a.matrix.decompose(a.position,a.quaternion,a.scale)):(e.position!==void 0&&a.position.fromArray(e.position),e.rotation!==void 0&&a.rotation.fromArray(e.rotation),e.quaternion!==void 0&&a.quaternion.fromArray(e.quaternion),e.scale!==void 0&&a.scale.fromArray(e.scale)),e.up!==void 0&&a.up.fromArray(e.up),e.pivot!==void 0&&(a.pivot=new R().fromArray(e.pivot)),e.morphTargetDictionary!==void 0&&(a.morphTargetDictionary=Object.assign({},e.morphTargetDictionary)),e.morphTargetInfluences!==void 0&&(a.morphTargetInfluences=e.morphTargetInfluences.slice()),e.castShadow!==void 0&&(a.castShadow=e.castShadow),e.receiveShadow!==void 0&&(a.receiveShadow=e.receiveShadow),e.shadow&&(e.shadow.intensity!==void 0&&(a.shadow.intensity=e.shadow.intensity),e.shadow.bias!==void 0&&(a.shadow.bias=e.shadow.bias),e.shadow.normalBias!==void 0&&(a.shadow.normalBias=e.shadow.normalBias),e.shadow.radius!==void 0&&(a.shadow.radius=e.shadow.radius),e.shadow.mapSize!==void 0&&a.shadow.mapSize.fromArray(e.shadow.mapSize),e.shadow.camera!==void 0&&(a.shadow.camera=this.parseObject(e.shadow.camera))),e.visible!==void 0&&(a.visible=e.visible),e.frustumCulled!==void 0&&(a.frustumCulled=e.frustumCulled),e.renderOrder!==void 0&&(a.renderOrder=e.renderOrder),e.static!==void 0&&(a.static=e.static),e.userData!==void 0&&(a.userData=e.userData),e.layers!==void 0&&(a.layers.mask=e.layers),e.children!==void 0){const p=e.children;for(let u=0;u"u"&&Ye("ImageBitmapLoader: createImageBitmap() not supported."),typeof fetch>"u"&&Ye("ImageBitmapLoader: fetch() not supported."),this.options={premultiplyAlpha:"none"},this._abortController=new AbortController}setOptions(e){return this.options=e,this}load(e,t,i,n){e===void 0&&(e=""),this.path!==void 0&&(e=this.path+e),e=this.manager.resolveURL(e);const r=this,a=Bs.get(`image-bitmap:${e}`);if(a!==void 0){if(r.manager.itemStart(e),a.then){a.then(c=>{if($g.has(a)===!0)n&&n($g.get(a)),r.manager.itemError(e),r.manager.itemEnd(e);else return t&&t(c),r.manager.itemEnd(e),c});return}return setTimeout(function(){t&&t(a),r.manager.itemEnd(e)},0),a}const o={};o.credentials=this.crossOrigin==="anonymous"?"same-origin":"include",o.headers=this.requestHeader,o.signal=typeof AbortSignal.any=="function"?AbortSignal.any([this._abortController.signal,this.manager.abortController.signal]):this._abortController.signal;const l=fetch(e,o).then(function(c){return c.blob()}).then(function(c){return createImageBitmap(c,Object.assign(r.options,{colorSpaceConversion:"none"}))}).then(function(c){return Bs.add(`image-bitmap:${e}`,c),t&&t(c),r.manager.itemEnd(e),c}).catch(function(c){n&&n(c),$g.set(l,c),Bs.remove(`image-bitmap:${e}`),r.manager.itemError(e),r.manager.itemEnd(e)});Bs.add(`image-bitmap:${e}`,l),r.manager.itemStart(e)}abort(){return this._abortController.abort(),this._abortController=new AbortController,this}}let Tp;class Kg{static getContext(){return Tp===void 0&&(Tp=new(window.AudioContext||window.webkitAudioContext)),Tp}static setContext(e){Tp=e}}class WT extends sn{constructor(e){super(e)}load(e,t,i,n){const r=this,a=new Jn(this.manager);a.setResponseType("arraybuffer"),a.setPath(this.path),a.setRequestHeader(this.requestHeader),a.setWithCredentials(this.withCredentials),a.load(e,function(l){try{const c=l.slice(0);Kg.getContext().decodeAudioData(c,function(d){t(d)}).catch(o)}catch(c){o(c)}},i,n);function o(l){n?n(l):lt(l),r.manager.itemError(e)}}}const I_=new qe,L_=new qe,Za=new qe;class XT{constructor(){this.type="StereoCamera",this.aspect=1,this.eyeSep=.064,this.cameraL=new ai,this.cameraL.layers.enable(1),this.cameraL.matrixAutoUpdate=!1,this.cameraR=new ai,this.cameraR.layers.enable(2),this.cameraR.matrixAutoUpdate=!1,this._cache={focus:null,fov:null,aspect:null,near:null,far:null,zoom:null,eyeSep:null}}update(e){const t=this._cache;if(t.focus!==e.focus||t.fov!==e.fov||t.aspect!==e.aspect*this.aspect||t.near!==e.near||t.far!==e.far||t.zoom!==e.zoom||t.eyeSep!==this.eyeSep){t.focus=e.focus,t.fov=e.fov,t.aspect=e.aspect*this.aspect,t.near=e.near,t.far=e.far,t.zoom=e.zoom,t.eyeSep=this.eyeSep,Za.copy(e.projectionMatrix);const n=t.eyeSep/2,r=n*t.near/t.focus,a=t.near*Math.tan(Ra*t.fov*.5)/t.zoom;let o,l;L_.elements[12]=-n,I_.elements[12]=n,o=-a*t.aspect+r,l=a*t.aspect+r,Za.elements[0]=2*t.near/(l-o),Za.elements[8]=(l+o)/(l-o),this.cameraL.projectionMatrix.copy(Za),o=-a*t.aspect-r,l=a*t.aspect-r,Za.elements[0]=2*t.near/(l-o),Za.elements[8]=(l+o)/(l-o),this.cameraR.projectionMatrix.copy(Za)}this.cameraL.matrixWorld.copy(e.matrixWorld).multiply(L_),this.cameraR.matrixWorld.copy(e.matrixWorld).multiply(I_)}}const _l=-90,bl=1;class D_ extends Rt{constructor(e,t,i){super(),this.type="CubeCamera",this.renderTarget=i,this.coordinateSystem=null,this.activeMipmapLevel=0;const n=new ai(_l,bl,e,t);n.layers=this.layers,this.add(n);const r=new ai(_l,bl,e,t);r.layers=this.layers,this.add(r);const a=new ai(_l,bl,e,t);a.layers=this.layers,this.add(a);const o=new ai(_l,bl,e,t);o.layers=this.layers,this.add(o);const l=new ai(_l,bl,e,t);l.layers=this.layers,this.add(l);const c=new ai(_l,bl,e,t);c.layers=this.layers,this.add(c)}updateCoordinateSystem(){const e=this.coordinateSystem,t=this.children.concat(),[i,n,r,a,o,l]=t;for(const c of t)this.remove(c);if(e===Nn)i.up.set(0,1,0),i.lookAt(1,0,0),n.up.set(0,1,0),n.lookAt(-1,0,0),r.up.set(0,0,-1),r.lookAt(0,1,0),a.up.set(0,0,1),a.lookAt(0,-1,0),o.up.set(0,1,0),o.lookAt(0,0,1),l.up.set(0,1,0),l.lookAt(0,0,-1);else if(e===Pa)i.up.set(0,-1,0),i.lookAt(-1,0,0),n.up.set(0,-1,0),n.lookAt(1,0,0),r.up.set(0,0,1),r.lookAt(0,1,0),a.up.set(0,0,-1),a.lookAt(0,-1,0),o.up.set(0,-1,0),o.lookAt(0,0,1),l.up.set(0,-1,0),l.lookAt(0,0,-1);else throw new Error("THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: "+e);for(const c of t)this.add(c),c.updateMatrixWorld()}update(e,t){this.parent===null&&this.updateMatrixWorld();const{renderTarget:i,activeMipmapLevel:n}=this;this.coordinateSystem!==e.coordinateSystem&&(this.coordinateSystem=e.coordinateSystem,this.updateCoordinateSystem());const[r,a,o,l,c,h]=this.children,d=e.getRenderTarget(),p=e.getActiveCubeFace(),u=e.getActiveMipmapLevel(),v=e.xr.enabled;e.xr.enabled=!1;const g=i.texture.generateMipmaps;i.texture.generateMipmaps=!1;let m=!1;e.isWebGLRenderer===!0?m=e.state.buffers.depth.getReversed():m=e.reversedDepthBuffer,e.setRenderTarget(i,0,n),m&&e.autoClear===!1&&e.clearDepth(),e.render(t,r),e.setRenderTarget(i,1,n),m&&e.autoClear===!1&&e.clearDepth(),e.render(t,a),e.setRenderTarget(i,2,n),m&&e.autoClear===!1&&e.clearDepth(),e.render(t,o),e.setRenderTarget(i,3,n),m&&e.autoClear===!1&&e.clearDepth(),e.render(t,l),e.setRenderTarget(i,4,n),m&&e.autoClear===!1&&e.clearDepth(),e.render(t,c),i.texture.generateMipmaps=g,e.setRenderTarget(i,5,n),m&&e.autoClear===!1&&e.clearDepth(),e.render(t,h),e.setRenderTarget(d,p,u),e.xr.enabled=v,i.texture.needsPMREMUpdate=!0}}class N_ extends ai{constructor(e=[]){super(),this.isArrayCamera=!0,this.isMultiViewCamera=!1,this.cameras=e}}class Jg{constructor(){this._previousTime=0,this._currentTime=0,this._startTime=performance.now(),this._delta=0,this._elapsed=0,this._timescale=1,this._document=null,this._pageVisibilityHandler=null}connect(e){this._document=e,e.hidden!==void 0&&(this._pageVisibilityHandler=jT.bind(this),e.addEventListener("visibilitychange",this._pageVisibilityHandler,!1))}disconnect(){this._pageVisibilityHandler!==null&&(this._document.removeEventListener("visibilitychange",this._pageVisibilityHandler),this._pageVisibilityHandler=null),this._document=null}getDelta(){return this._delta/1e3}getElapsed(){return this._elapsed/1e3}getTimescale(){return this._timescale}setTimescale(e){return this._timescale=e,this}reset(){return this._currentTime=performance.now()-this._startTime,this}dispose(){this.disconnect()}update(e){return this._pageVisibilityHandler!==null&&this._document.hidden===!0?this._delta=0:(this._previousTime=this._currentTime,this._currentTime=(e!==void 0?e:performance.now())-this._startTime,this._delta=(this._currentTime-this._previousTime)*this._timescale,this._elapsed+=this._delta),this}}function jT(){this._document.hidden===!1&&this.reset()}const Ya=new R,Qg=new Kt,qT=new R,$a=new R,Ka=new R;class ZT extends Rt{constructor(){super(),this.type="AudioListener",this.context=Kg.getContext(),this.gain=this.context.createGain(),this.gain.connect(this.context.destination),this.filter=null,this.timeDelta=0,this._timer=new Jg}getInput(){return this.gain}removeFilter(){return this.filter!==null&&(this.gain.disconnect(this.filter),this.filter.disconnect(this.context.destination),this.gain.connect(this.context.destination),this.filter=null),this}getFilter(){return this.filter}setFilter(e){return this.filter!==null?(this.gain.disconnect(this.filter),this.filter.disconnect(this.context.destination)):this.gain.disconnect(this.context.destination),this.filter=e,this.gain.connect(this.filter),this.filter.connect(this.context.destination),this}getMasterVolume(){return this.gain.gain.value}setMasterVolume(e){return this.gain.gain.setTargetAtTime(e,this.context.currentTime,.01),this}updateMatrixWorld(e){super.updateMatrixWorld(e),this._timer.update();const t=this.context.listener;if(this.timeDelta=this._timer.getDelta(),this.matrixWorld.decompose(Ya,Qg,qT),$a.set(0,0,-1).applyQuaternion(Qg),Ka.set(0,1,0).applyQuaternion(Qg),t.positionX){const i=this.context.currentTime+this.timeDelta;t.positionX.linearRampToValueAtTime(Ya.x,i),t.positionY.linearRampToValueAtTime(Ya.y,i),t.positionZ.linearRampToValueAtTime(Ya.z,i),t.forwardX.linearRampToValueAtTime($a.x,i),t.forwardY.linearRampToValueAtTime($a.y,i),t.forwardZ.linearRampToValueAtTime($a.z,i),t.upX.linearRampToValueAtTime(Ka.x,i),t.upY.linearRampToValueAtTime(Ka.y,i),t.upZ.linearRampToValueAtTime(Ka.z,i)}else t.setPosition(Ya.x,Ya.y,Ya.z),t.setOrientation($a.x,$a.y,$a.z,Ka.x,Ka.y,Ka.z)}}class k_ extends Rt{constructor(e){super(),this.type="Audio",this.listener=e,this.context=e.context,this.gain=this.context.createGain(),this.gain.connect(e.getInput()),this.autoplay=!1,this.buffer=null,this.detune=0,this.loop=!1,this.loopStart=0,this.loopEnd=0,this.offset=0,this.duration=void 0,this.playbackRate=1,this.isPlaying=!1,this.hasPlaybackControl=!0,this.source=null,this.sourceType="empty",this._startedAt=0,this._progress=0,this._connected=!1,this.filters=[]}getOutput(){return this.gain}setNodeSource(e){return this.hasPlaybackControl=!1,this.sourceType="audioNode",this.source=e,this.connect(),this}setMediaElementSource(e){return this.hasPlaybackControl=!1,this.sourceType="mediaNode",this.source=this.context.createMediaElementSource(e),this.connect(),this}setMediaStreamSource(e){return this.hasPlaybackControl=!1,this.sourceType="mediaStreamNode",this.source=this.context.createMediaStreamSource(e),this.connect(),this}setBuffer(e){return this.buffer=e,this.sourceType="buffer",this.autoplay&&this.play(),this}play(e=0){if(this.isPlaying===!0){Ye("Audio: Audio is already playing.");return}if(this.hasPlaybackControl===!1){Ye("Audio: this Audio has no playback control.");return}this._startedAt=this.context.currentTime+e;const t=this.context.createBufferSource();return t.buffer=this.buffer,t.loop=this.loop,t.loopStart=this.loopStart,t.loopEnd=this.loopEnd,t.onended=this.onEnded.bind(this),t.start(this._startedAt,this._progress+this.offset,this.duration),this.isPlaying=!0,this.source=t,this.setDetune(this.detune),this.setPlaybackRate(this.playbackRate),this.connect()}pause(){if(this.hasPlaybackControl===!1){Ye("Audio: this Audio has no playback control.");return}return this.isPlaying===!0&&(this._progress+=Math.max(this.context.currentTime-this._startedAt,0)*this.playbackRate,this.loop===!0&&(this._progress=this._progress%(this.duration||this.buffer.duration)),this.source.stop(),this.source.onended=null,this.isPlaying=!1),this}stop(e=0){if(this.hasPlaybackControl===!1){Ye("Audio: this Audio has no playback control.");return}return this._progress=0,this.source!==null&&(this.source.stop(this.context.currentTime+e),this.source.onended=null),this.isPlaying=!1,this}connect(){if(this.filters.length>0){this.source.connect(this.filters[0]);for(let e=1,t=this.filters.length;e0){this.source.disconnect(this.filters[0]);for(let e=1,t=this.filters.length;e0&&this._mixBufferRegionAdditive(i,n,this._addIndex*t,1,t);for(let l=t,c=t+t;l!==c;++l)if(i[l]!==i[l+t]){o.setValue(i,n);break}}saveOriginalState(){const e=this.binding,t=this.buffer,i=this.valueSize,n=i*this._origIndex;e.getValue(t,n);for(let r=i,a=n;r!==a;++r)t[r]=t[n+r%i];this._setIdentity(),this.cumulativeWeight=0,this.cumulativeWeightAdditive=0}restoreOriginalState(){const e=this.valueSize*3;this.binding.setValue(this.buffer,e)}_setAdditiveIdentityNumeric(){const e=this._addIndex*this.valueSize,t=e+this.valueSize;for(let i=e;i=.5)for(let a=0;a!==r;++a)e[t+a]=e[i+a]}_slerp(e,t,i,n){Kt.slerpFlat(e,t,e,t,e,i,n)}_slerpAdditive(e,t,i,n,r){const a=this._workIndex*r;Kt.multiplyQuaternionsFlat(e,a,e,t,e,i),Kt.slerpFlat(e,t,e,t,e,a,n)}_lerp(e,t,i,n,r){const a=1-n;for(let o=0;o!==r;++o){const l=t+o;e[l]=e[l]*a+e[i+o]*n}}_lerpAdditive(e,t,i,n,r){for(let a=0;a!==r;++a){const o=t+a;e[o]=e[o]+e[i+a]*n}}}const e0="\\[\\]\\.:\\/",JT=new RegExp("["+e0+"]","g"),t0="[^"+e0+"]",QT="[^"+e0.replace("\\.","")+"]",eC=/((?:WC+[\/:])*)/.source.replace("WC",t0),tC=/(WCOD+)?/.source.replace("WCOD",QT),iC=/(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace("WC",t0),nC=/\.(WC+)(?:\[(.+)\])?/.source.replace("WC",t0),sC=new RegExp("^"+eC+tC+iC+nC+"$"),rC=["material","materials","bones","map"];class aC{constructor(e,t,i){const n=i||Nt.parseTrackName(t);this._targetGroup=e,this._bindings=e.subscribe_(t,n)}getValue(e,t){this.bind();const i=this._targetGroup.nCachedObjects_,n=this._bindings[i];n!==void 0&&n.getValue(e,t)}setValue(e,t){const i=this._bindings;for(let n=this._targetGroup.nCachedObjects_,r=i.length;n!==r;++n)i[n].setValue(e,t)}bind(){const e=this._bindings;for(let t=this._targetGroup.nCachedObjects_,i=e.length;t!==i;++t)e[t].bind()}unbind(){const e=this._bindings;for(let t=this._targetGroup.nCachedObjects_,i=e.length;t!==i;++t)e[t].unbind()}}class Nt{constructor(e,t,i){this.path=t,this.parsedPath=i||Nt.parseTrackName(t),this.node=Nt.findNode(e,this.parsedPath.nodeName),this.rootNode=e,this.getValue=this._getValue_unbound,this.setValue=this._setValue_unbound}static create(e,t,i){return e&&e.isAnimationObjectGroup?new Nt.Composite(e,t,i):new Nt(e,t,i)}static sanitizeNodeName(e){return e.replace(/\s/g,"_").replace(JT,"")}static parseTrackName(e){const t=sC.exec(e);if(t===null)throw new Error("PropertyBinding: Cannot parse trackName: "+e);const i={nodeName:t[2],objectName:t[3],objectIndex:t[4],propertyName:t[5],propertyIndex:t[6]},n=i.nodeName&&i.nodeName.lastIndexOf(".");if(n!==void 0&&n!==-1){const r=i.nodeName.substring(n+1);rC.indexOf(r)!==-1&&(i.nodeName=i.nodeName.substring(0,n),i.objectName=r)}if(i.propertyName===null||i.propertyName.length===0)throw new Error("PropertyBinding: can not parse propertyName from trackName: "+e);return i}static findNode(e,t){if(t===void 0||t===""||t==="."||t===-1||t===e.name||t===e.uuid)return e;if(e.skeleton){const i=e.skeleton.getBoneByName(t);if(i!==void 0)return i}if(e.children){const i=function(r){for(let a=0;a=r){const d=r++,p=e[d];t[p.uuid]=h,e[h]=p,t[c]=d,e[d]=l;for(let u=0,v=n;u!==v;++u){const g=i[u],m=g[d],f=g[h];g[h]=m,g[d]=f}}}this.nCachedObjects_=r}uncache(){const e=this._objects,t=this._indicesByUUID,i=this._bindings,n=i.length;let r=this.nCachedObjects_,a=e.length;for(let o=0,l=arguments.length;o!==l;++o){const c=arguments[o],h=c.uuid,d=t[h];if(d!==void 0)if(delete t[h],d0&&(t[u.uuid]=d),e[d]=u,e.pop();for(let v=0,g=n;v!==g;++v){const m=i[v];m[d]=m[p],m.pop()}}}this.nCachedObjects_=r}subscribe_(e,t){const i=this._bindingsIndicesByPath;let n=i[e];const r=this._bindings;if(n!==void 0)return r[n];const a=this._paths,o=this._parsedPaths,l=this._objects,c=l.length,h=this.nCachedObjects_,d=new Array(c);n=r.length,i[e]=n,a.push(e),o.push(t),r.push(d);for(let p=h,u=l.length;p!==u;++p){const v=l[p];d[p]=new Nt(v,e,t)}return d}unsubscribe_(e){const t=this._bindingsIndicesByPath,i=t[e];if(i!==void 0){const n=this._paths,r=this._parsedPaths,a=this._bindings,o=a.length-1,l=a[o],c=e[o];t[c]=i,a[i]=l,a.pop(),r[i]=r[o],r.pop(),n[i]=n[o],n.pop()}}}class B_{constructor(e,t,i=null,n=t.blendMode){this._mixer=e,this._clip=t,this._localRoot=i,this.blendMode=n;const r=t.tracks,a=r.length,o=new Array(a),l={endingStart:Ta,endingEnd:Ta};for(let c=0;c!==a;++c){const h=r[c].createInterpolant(null);o[c]=h,h.settings=l}this._interpolantSettings=l,this._interpolants=o,this._propertyBindings=new Array(a),this._cacheIndex=null,this._byClipCacheIndex=null,this._timeScaleInterpolant=null,this._weightInterpolant=null,this.loop=Fy,this._loopCount=-1,this._startTime=null,this.time=0,this.timeScale=1,this._effectiveTimeScale=1,this.weight=1,this._effectiveWeight=1,this.repetitions=1/0,this.paused=!1,this.enabled=!0,this.clampWhenFinished=!1,this.zeroSlopeAtStart=!0,this.zeroSlopeAtEnd=!0}play(){return this._mixer._activateAction(this),this}stop(){return this._mixer._deactivateAction(this),this.reset()}reset(){return this.paused=!1,this.enabled=!0,this.time=0,this._loopCount=-1,this._startTime=null,this.stopFading().stopWarping()}isRunning(){return this.enabled&&!this.paused&&this.timeScale!==0&&this._startTime===null&&this._mixer._isActiveAction(this)}isScheduled(){return this._mixer._isActiveAction(this)}startAt(e){return this._startTime=e,this}setLoop(e,t){return this.loop=e,this.repetitions=t,this}setEffectiveWeight(e){return this.weight=e,this._effectiveWeight=this.enabled?e:0,this.stopFading()}getEffectiveWeight(){return this._effectiveWeight}fadeIn(e){return this._scheduleFading(e,0,1)}fadeOut(e){return this._scheduleFading(e,1,0)}crossFadeFrom(e,t,i=!1){if(e.fadeOut(t),this.fadeIn(t),i===!0){const n=this._clip.duration,r=e._clip.duration,a=r/n,o=n/r;e.warp(1,a,t),this.warp(o,1,t)}return this}crossFadeTo(e,t,i=!1){return e.crossFadeFrom(this,t,i)}stopFading(){const e=this._weightInterpolant;return e!==null&&(this._weightInterpolant=null,this._mixer._takeBackControlInterpolant(e)),this}setEffectiveTimeScale(e){return this.timeScale=e,this._effectiveTimeScale=this.paused?0:e,this.stopWarping()}getEffectiveTimeScale(){return this._effectiveTimeScale}setDuration(e){return this.timeScale=this._clip.duration/e,this.stopWarping()}syncWith(e){return this.time=e.time,this.timeScale=e.timeScale,this.stopWarping()}halt(e){return this.warp(this._effectiveTimeScale,0,e)}warp(e,t,i){const n=this._mixer,r=n.time,a=this.timeScale;let o=this._timeScaleInterpolant;o===null&&(o=n._lendControlInterpolant(),this._timeScaleInterpolant=o);const l=o.parameterPositions,c=o.sampleValues;return l[0]=r,l[1]=r+i,c[0]=e/a,c[1]=t/a,this}stopWarping(){const e=this._timeScaleInterpolant;return e!==null&&(this._timeScaleInterpolant=null,this._mixer._takeBackControlInterpolant(e)),this}getMixer(){return this._mixer}getClip(){return this._clip}getRoot(){return this._localRoot||this._mixer._root}_update(e,t,i,n){if(!this.enabled){this._updateWeight(e);return}const r=this._startTime;if(r!==null){const l=(e-r)*i;l<0||i===0?t=0:(this._startTime=null,t=i*l)}t*=this._updateTimeScale(e);const a=this._updateTime(t),o=this._updateWeight(e);if(o>0){const l=this._interpolants,c=this._propertyBindings;switch(this.blendMode){case zm:for(let h=0,d=l.length;h!==d;++h)l[h].evaluate(a),c[h].accumulateAdditive(o);break;case hu:default:for(let h=0,d=l.length;h!==d;++h)l[h].evaluate(a),c[h].accumulate(n,o)}}}_updateWeight(e){let t=0;if(this.enabled){t=this.weight;const i=this._weightInterpolant;if(i!==null){const n=i.evaluate(e)[0];t*=n,e>i.parameterPositions[1]&&(this.stopFading(),n===0&&(this.enabled=!1))}}return this._effectiveWeight=t,t}_updateTimeScale(e){let t=0;if(!this.paused){t=this.timeScale;const i=this._timeScaleInterpolant;if(i!==null){const n=i.evaluate(e)[0];t*=n,e>i.parameterPositions[1]&&(this.stopWarping(),t===0?this.paused=!0:this.timeScale=t)}}return this._effectiveTimeScale=t,t}_updateTime(e){const t=this._clip.duration,i=this.loop;let n=this.time+e,r=this._loopCount;const a=i===zy;if(e===0)return r===-1?n:a&&(r&1)===1?t-n:n;if(i===By){r===-1&&(this._loopCount=0,this._setEndings(!0,!0,!1));e:{if(n>=t)n=t;else if(n<0)n=0;else{this.time=n;break e}this.clampWhenFinished?this.paused=!0:this.enabled=!1,this.time=n,this._mixer.dispatchEvent({type:"finished",action:this,direction:e<0?-1:1})}}else{if(r===-1&&(e>=0?(r=0,this._setEndings(!0,this.repetitions===0,a)):this._setEndings(this.repetitions===0,!0,a)),n>=t||n<0){const o=Math.floor(n/t);n-=t*o,r+=Math.abs(o);const l=this.repetitions-r;if(l<=0)this.clampWhenFinished?this.paused=!0:this.enabled=!1,n=e>0?t:0,this.time=n,this._mixer.dispatchEvent({type:"finished",action:this,direction:e>0?1:-1});else{if(l===1){const c=e<0;this._setEndings(c,!c,a)}else this._setEndings(!1,!1,a);this._loopCount=r,this.time=n,this._mixer.dispatchEvent({type:"loop",action:this,loopDelta:o})}}else this.time=n;if(a&&(r&1)===1)return t-n}return n}_setEndings(e,t,i){const n=this._interpolantSettings;i?(n.endingStart=Ca,n.endingEnd=Ca):(e?n.endingStart=this.zeroSlopeAtStart?Ca:Ta:n.endingStart=Ac,t?n.endingEnd=this.zeroSlopeAtEnd?Ca:Ta:n.endingEnd=Ac)}_scheduleFading(e,t,i){const n=this._mixer,r=n.time;let a=this._weightInterpolant;a===null&&(a=n._lendControlInterpolant(),this._weightInterpolant=a);const o=a.parameterPositions,l=a.sampleValues;return o[0]=r,l[0]=t,o[1]=r+e,l[1]=i,this}}const lC=new Float32Array(1);class cC extends hs{constructor(e){super(),this._root=e,this._initMemoryManager(),this._accuIndex=0,this.time=0,this.timeScale=1,typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}_bindAction(e,t){const i=e._localRoot||this._root,n=e._clip.tracks,r=n.length,a=e._propertyBindings,o=e._interpolants,l=i.uuid,c=this._bindingsByRootAndName;let h=c[l];h===void 0&&(h={},c[l]=h);for(let d=0;d!==r;++d){const p=n[d],u=p.name;let v=h[u];if(v!==void 0)++v.referenceCount,a[d]=v;else{if(v=a[d],v!==void 0){v._cacheIndex===null&&(++v.referenceCount,this._addInactiveBinding(v,l,u));continue}const g=t&&t._propertyBindings[d].binding.parsedPath;v=new U_(Nt.create(i,u,g),p.ValueTypeName,p.getValueSize()),++v.referenceCount,this._addInactiveBinding(v,l,u),a[d]=v}o[d].resultBuffer=v.buffer}}_activateAction(e){if(!this._isActiveAction(e)){if(e._cacheIndex===null){const i=(e._localRoot||this._root).uuid,n=e._clip.uuid,r=this._actionsByClip[n];this._bindAction(e,r&&r.knownActions[0]),this._addInactiveAction(e,n,i)}const t=e._propertyBindings;for(let i=0,n=t.length;i!==n;++i){const r=t[i];r.useCount++===0&&(this._lendBinding(r),r.saveOriginalState())}this._lendAction(e)}}_deactivateAction(e){if(this._isActiveAction(e)){const t=e._propertyBindings;for(let i=0,n=t.length;i!==n;++i){const r=t[i];--r.useCount===0&&(r.restoreOriginalState(),this._takeBackBinding(r))}this._takeBackAction(e)}}_initMemoryManager(){this._actions=[],this._nActiveActions=0,this._actionsByClip={},this._bindings=[],this._nActiveBindings=0,this._bindingsByRootAndName={},this._controlInterpolants=[],this._nActiveControlInterpolants=0;const e=this;this.stats={actions:{get total(){return e._actions.length},get inUse(){return e._nActiveActions}},bindings:{get total(){return e._bindings.length},get inUse(){return e._nActiveBindings}},controlInterpolants:{get total(){return e._controlInterpolants.length},get inUse(){return e._nActiveControlInterpolants}}}}_isActiveAction(e){const t=e._cacheIndex;return t!==null&&t=0;--i)e[i].stop();return this}update(e){e*=this.timeScale;const t=this._actions,i=this._nActiveActions,n=this.time+=e,r=Math.sign(e),a=this._accuIndex^=1;for(let c=0;c!==i;++c)t[c]._update(n,e,r,a);const o=this._bindings,l=this._nActiveBindings;for(let c=0;c!==l;++c)o[c].apply(a);return this}setTime(e){this.time=0;for(let t=0;t=this.min.x&&e.x<=this.max.x&&e.y>=this.min.y&&e.y<=this.max.y}containsBox(e){return this.min.x<=e.min.x&&e.max.x<=this.max.x&&this.min.y<=e.min.y&&e.max.y<=this.max.y}getParameter(e,t){return t.set((e.x-this.min.x)/(this.max.x-this.min.x),(e.y-this.min.y)/(this.max.y-this.min.y))}intersectsBox(e){return e.max.x>=this.min.x&&e.min.x<=this.max.x&&e.max.y>=this.min.y&&e.min.y<=this.max.y}clampPoint(e,t){return t.copy(e).clamp(this.min,this.max)}distanceToPoint(e){return this.clampPoint(e,V_).distanceTo(e)}intersect(e){return this.min.max(e.min),this.max.min(e.max),this.isEmpty()&&this.makeEmpty(),this}union(e){return this.min.min(e.min),this.max.max(e.max),this}translate(e){return this.min.add(e),this.max.add(e),this}equals(e){return e.min.equals(this.min)&&e.max.equals(this.max)}}const G_=new R,Cp=new R,Sl=new R,wl=new R,r0=new R,vC=new R,yC=new R;class Bn{constructor(e=new R,t=new R){this.start=e,this.end=t}set(e,t){return this.start.copy(e),this.end.copy(t),this}copy(e){return this.start.copy(e.start),this.end.copy(e.end),this}getCenter(e){return e.addVectors(this.start,this.end).multiplyScalar(.5)}delta(e){return e.subVectors(this.end,this.start)}distanceSq(){return this.start.distanceToSquared(this.end)}distance(){return this.start.distanceTo(this.end)}at(e,t){return this.delta(t).multiplyScalar(e).add(this.start)}closestPointToPointParameter(e,t){G_.subVectors(e,this.start),Cp.subVectors(this.end,this.start);const i=Cp.dot(Cp);let r=Cp.dot(G_)/i;return t&&(r=dt(r,0,1)),r}closestPointToPoint(e,t,i){const n=this.closestPointToPointParameter(e,t);return this.delta(i).multiplyScalar(n).add(this.start)}distanceSqToLine3(e,t=vC,i=yC){const n=10000000000000001e-32;let r,a;const o=this.start,l=e.start,c=this.end,h=e.end;Sl.subVectors(c,o),wl.subVectors(h,l),r0.subVectors(o,l);const d=Sl.dot(Sl),p=wl.dot(wl),u=wl.dot(r0);if(d<=n&&p<=n)return t.copy(o),i.copy(l),t.sub(i),t.dot(t);if(d<=n)r=0,a=u/p,a=dt(a,0,1);else{const v=Sl.dot(r0);if(p<=n)a=0,r=dt(-v/d,0,1);else{const g=Sl.dot(wl),m=d*p-g*g;m!==0?r=dt((g*u-v*p)/m,0,1):r=0,a=(g*r+u)/p,a<0?(a=0,r=dt(-v/d,0,1)):a>1&&(a=1,r=dt((g-v)/d,0,1))}}return t.copy(o).addScaledVector(Sl,r),i.copy(l).addScaledVector(wl,a),t.distanceToSquared(i)}applyMatrix4(e){return this.start.applyMatrix4(e),this.end.applyMatrix4(e),this}equals(e){return e.start.equals(this.start)&&e.end.equals(this.end)}clone(){return new this.constructor().copy(this)}}const W_=new R;class xC extends Rt{constructor(e,t){super(),this.light=e,this.matrixAutoUpdate=!1,this.color=t,this.type="SpotLightHelper";const i=new at,n=[0,0,0,0,0,1,0,0,0,1,0,1,0,0,0,-1,0,1,0,0,0,0,1,1,0,0,0,0,-1,1];for(let a=0,o=1,l=32;a1)for(let d=0;d.99999)this.quaternion.set(0,0,0,1);else if(e.y<-.99999)this.quaternion.set(1,0,0,0);else{$_.set(e.z,0,-e.x).normalize();const t=Math.acos(e.y);this.quaternion.setFromAxisAngle($_,t)}}setLength(e,t=e*.2,i=t*.2){this.line.scale.set(1,Math.max(1e-4,e-t),1),this.line.updateMatrix(),this.cone.scale.set(i,t,i),this.cone.position.y=e,this.cone.updateMatrix()}setColor(e){this.line.material.color.set(e),this.cone.material.color.set(e)}copy(e){return super.copy(e,!1),this.line.copy(e.line),this.cone.copy(e.cone),this}dispose(){this.line.geometry.dispose(),this.line.material.dispose(),this.cone.geometry.dispose(),this.cone.material.dispose()}}class K_ extends fi{constructor(e=1){const t=[0,0,0,e,0,0,0,0,0,0,e,0,0,0,0,0,0,e],i=[1,0,0,1,.6,0,0,1,0,.6,1,0,0,0,1,0,.6,1],n=new at;n.setAttribute("position",new et(t,3)),n.setAttribute("color",new et(i,3));const r=new si({vertexColors:!0,toneMapped:!1});super(n,r),this.type="AxesHelper"}setColors(e,t,i){const n=new We,r=this.geometry.attributes.color.array;return n.set(e),n.toArray(r,0),n.toArray(r,3),n.set(t),n.toArray(r,6),n.toArray(r,9),n.set(i),n.toArray(r,12),n.toArray(r,15),this.geometry.attributes.color.needsUpdate=!0,this}dispose(){this.geometry.dispose(),this.material.dispose()}}class J_{constructor(){this.type="ShapePath",this.color=new We,this.subPaths=[],this.currentPath=null}moveTo(e,t){return this.currentPath=new nh,this.subPaths.push(this.currentPath),this.currentPath.moveTo(e,t),this}lineTo(e,t){return this.currentPath.lineTo(e,t),this}quadraticCurveTo(e,t,i,n){return this.currentPath.quadraticCurveTo(e,t,i,n),this}bezierCurveTo(e,t,i,n,r,a){return this.currentPath.bezierCurveTo(e,t,i,n,r,a),this}splineThru(e){return this.currentPath.splineThru(e),this}toShapes(e){function t(f){const y=[];for(let x=0,_=f.length;x<_;x++){const S=f[x],b=new nr;b.curves=S.curves,y.push(b)}return y}function i(f,y){const x=y.length;let _=!1;for(let S=x-1,b=0;bNumber.EPSILON){if(C<0&&(E=y[b],M=-M,w=y[S],C=-C),f.yw.y)continue;if(f.y===E.y){if(f.x===E.x)return!0}else{const I=C*(f.x-E.x)-M*(f.y-E.y);if(I===0)return!0;if(I<0)continue;_=!_}}else{if(f.y!==E.y)continue;if(w.x<=f.x&&f.x<=E.x||E.x<=f.x&&f.x<=w.x)return!0}}return _}const n=gs.isClockWise,r=this.subPaths;if(r.length===0)return[];let a,o,l;const c=[];if(r.length===1)return o=r[0],l=new nr,l.curves=o.curves,c.push(l),c;let h=!n(r[0].getPoints());h=e?!h:h;const d=[],p=[];let u=[],v=0,g;p[v]=void 0,u[v]=[];for(let f=0,y=r.length;f1){let f=!1,y=0;for(let x=0,_=p.length;x<_;x++)d[x]=[];for(let x=0,_=p.length;x<_;x++){const S=u[x];for(let b=0;b0&&f===!1&&(u=d)}let m;for(let f=0,y=p.length;fe?(s.repeat.x=1,s.repeat.y=t/e,s.offset.x=0,s.offset.y=(1-s.repeat.y)/2):(s.repeat.x=e/t,s.repeat.y=1,s.offset.x=(1-s.repeat.x)/2,s.offset.y=0),s}function DC(s,e){const t=s.image&&s.image.width?s.image.width/s.image.height:1;return t>e?(s.repeat.x=e/t,s.repeat.y=1,s.offset.x=(1-s.repeat.x)/2,s.offset.y=0):(s.repeat.x=1,s.repeat.y=t/e,s.offset.x=0,s.offset.y=(1-s.repeat.y)/2),s}function NC(s){return s.repeat.x=1,s.repeat.y=1,s.offset.x=0,s.offset.y=0,s}function c0(s,e,t,i){const n=kC(i);switch(t){case Um:return s*e;case Mc:return s*e/n.components*n.byteLength;case Sc:return s*e/n.components*n.byteLength;case Ea:return s*e*2/n.components*n.byteLength;case Pd:return s*e*2/n.components*n.byteLength;case Bm:return s*e*3/n.components*n.byteLength;case qi:return s*e*4/n.components*n.byteLength;case Rd:return s*e*4/n.components*n.byteLength;case wc:case Ec:return Math.floor((s+3)/4)*Math.floor((e+3)/4)*8;case Tc:case Cc:return Math.floor((s+3)/4)*Math.floor((e+3)/4)*16;case Ld:case Nd:return Math.max(s,16)*Math.max(e,8)/4;case Id:case Dd:return Math.max(s,8)*Math.max(e,8)/2;case kd:case Od:case Bd:case Fd:return Math.floor((s+3)/4)*Math.floor((e+3)/4)*8;case Ud:case zd:case Hd:return Math.floor((s+3)/4)*Math.floor((e+3)/4)*16;case Vd:return Math.floor((s+3)/4)*Math.floor((e+3)/4)*16;case Gd:return Math.floor((s+4)/5)*Math.floor((e+3)/4)*16;case Wd:return Math.floor((s+4)/5)*Math.floor((e+4)/5)*16;case Xd:return Math.floor((s+5)/6)*Math.floor((e+4)/5)*16;case jd:return Math.floor((s+5)/6)*Math.floor((e+5)/6)*16;case qd:return Math.floor((s+7)/8)*Math.floor((e+4)/5)*16;case Zd:return Math.floor((s+7)/8)*Math.floor((e+5)/6)*16;case Yd:return Math.floor((s+7)/8)*Math.floor((e+7)/8)*16;case $d:return Math.floor((s+9)/10)*Math.floor((e+4)/5)*16;case Kd:return Math.floor((s+9)/10)*Math.floor((e+5)/6)*16;case Jd:return Math.floor((s+9)/10)*Math.floor((e+7)/8)*16;case Qd:return Math.floor((s+9)/10)*Math.floor((e+9)/10)*16;case eu:return Math.floor((s+11)/12)*Math.floor((e+9)/10)*16;case tu:return Math.floor((s+11)/12)*Math.floor((e+11)/12)*16;case iu:case nu:case su:return Math.ceil(s/4)*Math.ceil(e/4)*16;case ru:case au:return Math.ceil(s/4)*Math.ceil(e/4)*8;case ou:case lu:return Math.ceil(s/4)*Math.ceil(e/4)*16}throw new Error(`Unable to determine texture byte length for ${t} format.`)}function kC(s){switch(s){case hn:case Dm:return{byteLength:1,components:1};case jo:case Nm:case _i:return{byteLength:2,components:1};case Cd:case Ad:return{byteLength:2,components:4};case Zn:case Td:case Pi:return{byteLength:4,components:1};case km:case Om:return{byteLength:4,components:3}}throw new Error(`Unknown texture type ${s}.`)}class OC{static contain(e,t){return LC(e,t)}static cover(e,t){return DC(e,t)}static fill(e){return NC(e)}static getByteLength(e,t,i,n){return c0(e,t,i,n)}}typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("register",{detail:{revision:zo}})),typeof window<"u"&&(window.__THREE__?Ye("WARNING: Multiple instances of Three.js being imported."):window.__THREE__=zo);function Q_(){let s=null,e=!1,t=null,i=null;function n(r,a){t(r,a),i=s.requestAnimationFrame(n)}return{start:function(){e!==!0&&t!==null&&(i=s.requestAnimationFrame(n),e=!0)},stop:function(){s.cancelAnimationFrame(i),e=!1},setAnimationLoop:function(r){t=r},setContext:function(r){s=r}}}function UC(s){const e=new WeakMap;function t(o,l){const c=o.array,h=o.usage,d=c.byteLength,p=s.createBuffer();s.bindBuffer(l,p),s.bufferData(l,c,h),o.onUploadCallback();let u;if(c instanceof Float32Array)u=s.FLOAT;else if(typeof Float16Array<"u"&&c instanceof Float16Array)u=s.HALF_FLOAT;else if(c instanceof Uint16Array)o.isFloat16BufferAttribute?u=s.HALF_FLOAT:u=s.UNSIGNED_SHORT;else if(c instanceof Int16Array)u=s.SHORT;else if(c instanceof Uint32Array)u=s.UNSIGNED_INT;else if(c instanceof Int32Array)u=s.INT;else if(c instanceof Int8Array)u=s.BYTE;else if(c instanceof Uint8Array)u=s.UNSIGNED_BYTE;else if(c instanceof Uint8ClampedArray)u=s.UNSIGNED_BYTE;else throw new Error("THREE.WebGLAttributes: Unsupported buffer data format: "+c);return{buffer:p,type:u,bytesPerElement:c.BYTES_PER_ELEMENT,version:o.version,size:d}}function i(o,l,c){const h=l.array,d=l.updateRanges;if(s.bindBuffer(c,o),d.length===0)s.bufferSubData(c,0,h);else{d.sort((u,v)=>u.start-v.start);let p=0;for(let u=1;u 0 vec4 plane; #ifdef ALPHA_TO_COVERAGE float distanceToPlane, distanceGradient; float clipOpacity = 1.0; #pragma unroll_loop_start for ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) { plane = clippingPlanes[ i ]; distanceToPlane = - dot( vClipPosition, plane.xyz ) + plane.w; distanceGradient = fwidth( distanceToPlane ) / 2.0; clipOpacity *= smoothstep( - distanceGradient, distanceGradient, distanceToPlane ); if ( clipOpacity == 0.0 ) discard; } #pragma unroll_loop_end #if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES float unionClipOpacity = 1.0; #pragma unroll_loop_start for ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) { plane = clippingPlanes[ i ]; distanceToPlane = - dot( vClipPosition, plane.xyz ) + plane.w; distanceGradient = fwidth( distanceToPlane ) / 2.0; unionClipOpacity *= 1.0 - smoothstep( - distanceGradient, distanceGradient, distanceToPlane ); } #pragma unroll_loop_end clipOpacity *= 1.0 - unionClipOpacity; #endif diffuseColor.a *= clipOpacity; if ( diffuseColor.a == 0.0 ) discard; #else #pragma unroll_loop_start for ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) { plane = clippingPlanes[ i ]; if ( dot( vClipPosition, plane.xyz ) > plane.w ) discard; } #pragma unroll_loop_end #if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES bool clipped = true; #pragma unroll_loop_start for ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) { plane = clippingPlanes[ i ]; clipped = ( dot( vClipPosition, plane.xyz ) > plane.w ) && clipped; } #pragma unroll_loop_end if ( clipped ) discard; #endif #endif #endif`,eA=`#if NUM_CLIPPING_PLANES > 0 varying vec3 vClipPosition; uniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ]; #endif`,tA=`#if NUM_CLIPPING_PLANES > 0 varying vec3 vClipPosition; #endif`,iA=`#if NUM_CLIPPING_PLANES > 0 vClipPosition = - mvPosition.xyz; #endif`,nA=`#if defined( USE_COLOR ) || defined( USE_COLOR_ALPHA ) diffuseColor *= vColor; #endif`,sA=`#if defined( USE_COLOR ) || defined( USE_COLOR_ALPHA ) varying vec4 vColor; #endif`,rA=`#if defined( USE_COLOR ) || defined( USE_COLOR_ALPHA ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR ) varying vec4 vColor; #endif`,aA=`#if defined( USE_COLOR ) || defined( USE_COLOR_ALPHA ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR ) vColor = vec4( 1.0 ); #endif #ifdef USE_COLOR_ALPHA vColor *= color; #elif defined( USE_COLOR ) vColor.rgb *= color; #endif #ifdef USE_INSTANCING_COLOR vColor.rgb *= instanceColor.rgb; #endif #ifdef USE_BATCHING_COLOR vColor *= getBatchingColor( getIndirectIndex( gl_DrawID ) ); #endif`,oA=`#define PI 3.141592653589793 #define PI2 6.283185307179586 #define PI_HALF 1.5707963267948966 #define RECIPROCAL_PI 0.3183098861837907 #define RECIPROCAL_PI2 0.15915494309189535 #define EPSILON 1e-6 #ifndef saturate #define saturate( a ) clamp( a, 0.0, 1.0 ) #endif #define whiteComplement( a ) ( 1.0 - saturate( a ) ) float pow2( const in float x ) { return x*x; } vec3 pow2( const in vec3 x ) { return x*x; } float pow3( const in float x ) { return x*x*x; } float pow4( const in float x ) { float x2 = x*x; return x2*x2; } float max3( const in vec3 v ) { return max( max( v.x, v.y ), v.z ); } float average( const in vec3 v ) { return dot( v, vec3( 0.3333333 ) ); } highp float rand( const in vec2 uv ) { const highp float a = 12.9898, b = 78.233, c = 43758.5453; highp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI ); return fract( sin( sn ) * c ); } #ifdef HIGH_PRECISION float precisionSafeLength( vec3 v ) { return length( v ); } #else float precisionSafeLength( vec3 v ) { float maxComponent = max3( abs( v ) ); return length( v / maxComponent ) * maxComponent; } #endif struct IncidentLight { vec3 color; vec3 direction; bool visible; }; struct ReflectedLight { vec3 directDiffuse; vec3 directSpecular; vec3 indirectDiffuse; vec3 indirectSpecular; }; #ifdef USE_ALPHAHASH varying vec3 vPosition; #endif vec3 transformDirection( in vec3 dir, in mat4 matrix ) { return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz ); } vec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) { return normalize( ( vec4( dir, 0.0 ) * matrix ).xyz ); } bool isPerspectiveMatrix( mat4 m ) { return m[ 2 ][ 3 ] == - 1.0; } vec2 equirectUv( in vec3 dir ) { float u = atan( dir.z, dir.x ) * RECIPROCAL_PI2 + 0.5; float v = asin( clamp( dir.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5; return vec2( u, v ); } vec3 BRDF_Lambert( const in vec3 diffuseColor ) { return RECIPROCAL_PI * diffuseColor; } vec3 F_Schlick( const in vec3 f0, const in float f90, const in float dotVH ) { float fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH ); return f0 * ( 1.0 - fresnel ) + ( f90 * fresnel ); } float F_Schlick( const in float f0, const in float f90, const in float dotVH ) { float fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH ); return f0 * ( 1.0 - fresnel ) + ( f90 * fresnel ); } // validated`,lA=`#ifdef ENVMAP_TYPE_CUBE_UV #define cubeUV_minMipLevel 4.0 #define cubeUV_minTileSize 16.0 float getFace( vec3 direction ) { vec3 absDirection = abs( direction ); float face = - 1.0; if ( absDirection.x > absDirection.z ) { if ( absDirection.x > absDirection.y ) face = direction.x > 0.0 ? 0.0 : 3.0; else face = direction.y > 0.0 ? 1.0 : 4.0; } else { if ( absDirection.z > absDirection.y ) face = direction.z > 0.0 ? 2.0 : 5.0; else face = direction.y > 0.0 ? 1.0 : 4.0; } return face; } vec2 getUV( vec3 direction, float face ) { vec2 uv; if ( face == 0.0 ) { uv = vec2( direction.z, direction.y ) / abs( direction.x ); } else if ( face == 1.0 ) { uv = vec2( - direction.x, - direction.z ) / abs( direction.y ); } else if ( face == 2.0 ) { uv = vec2( - direction.x, direction.y ) / abs( direction.z ); } else if ( face == 3.0 ) { uv = vec2( - direction.z, direction.y ) / abs( direction.x ); } else if ( face == 4.0 ) { uv = vec2( - direction.x, direction.z ) / abs( direction.y ); } else { uv = vec2( direction.x, direction.y ) / abs( direction.z ); } return 0.5 * ( uv + 1.0 ); } vec3 bilinearCubeUV( sampler2D envMap, vec3 direction, float mipInt ) { float face = getFace( direction ); float filterInt = max( cubeUV_minMipLevel - mipInt, 0.0 ); mipInt = max( mipInt, cubeUV_minMipLevel ); float faceSize = exp2( mipInt ); highp vec2 uv = getUV( direction, face ) * ( faceSize - 2.0 ) + 1.0; if ( face > 2.0 ) { uv.y += faceSize; face -= 3.0; } uv.x += face * faceSize; uv.x += filterInt * 3.0 * cubeUV_minTileSize; uv.y += 4.0 * ( exp2( CUBEUV_MAX_MIP ) - faceSize ); uv.x *= CUBEUV_TEXEL_WIDTH; uv.y *= CUBEUV_TEXEL_HEIGHT; #ifdef texture2DGradEXT return texture2DGradEXT( envMap, uv, vec2( 0.0 ), vec2( 0.0 ) ).rgb; #else return texture2D( envMap, uv ).rgb; #endif } #define cubeUV_r0 1.0 #define cubeUV_m0 - 2.0 #define cubeUV_r1 0.8 #define cubeUV_m1 - 1.0 #define cubeUV_r4 0.4 #define cubeUV_m4 2.0 #define cubeUV_r5 0.305 #define cubeUV_m5 3.0 #define cubeUV_r6 0.21 #define cubeUV_m6 4.0 float roughnessToMip( float roughness ) { float mip = 0.0; if ( roughness >= cubeUV_r1 ) { mip = ( cubeUV_r0 - roughness ) * ( cubeUV_m1 - cubeUV_m0 ) / ( cubeUV_r0 - cubeUV_r1 ) + cubeUV_m0; } else if ( roughness >= cubeUV_r4 ) { mip = ( cubeUV_r1 - roughness ) * ( cubeUV_m4 - cubeUV_m1 ) / ( cubeUV_r1 - cubeUV_r4 ) + cubeUV_m1; } else if ( roughness >= cubeUV_r5 ) { mip = ( cubeUV_r4 - roughness ) * ( cubeUV_m5 - cubeUV_m4 ) / ( cubeUV_r4 - cubeUV_r5 ) + cubeUV_m4; } else if ( roughness >= cubeUV_r6 ) { mip = ( cubeUV_r5 - roughness ) * ( cubeUV_m6 - cubeUV_m5 ) / ( cubeUV_r5 - cubeUV_r6 ) + cubeUV_m5; } else { mip = - 2.0 * log2( 1.16 * roughness ); } return mip; } vec4 textureCubeUV( sampler2D envMap, vec3 sampleDir, float roughness ) { float mip = clamp( roughnessToMip( roughness ), cubeUV_m0, CUBEUV_MAX_MIP ); float mipF = fract( mip ); float mipInt = floor( mip ); vec3 color0 = bilinearCubeUV( envMap, sampleDir, mipInt ); if ( mipF == 0.0 ) { return vec4( color0, 1.0 ); } else { vec3 color1 = bilinearCubeUV( envMap, sampleDir, mipInt + 1.0 ); return vec4( mix( color0, color1, mipF ), 1.0 ); } } #endif`,cA=`vec3 transformedNormal = objectNormal; #ifdef USE_TANGENT vec3 transformedTangent = objectTangent; #endif #ifdef USE_BATCHING mat3 bm = mat3( batchingMatrix ); transformedNormal /= vec3( dot( bm[ 0 ], bm[ 0 ] ), dot( bm[ 1 ], bm[ 1 ] ), dot( bm[ 2 ], bm[ 2 ] ) ); transformedNormal = bm * transformedNormal; #ifdef USE_TANGENT transformedTangent = bm * transformedTangent; #endif #endif #ifdef USE_INSTANCING mat3 im = mat3( instanceMatrix ); transformedNormal /= vec3( dot( im[ 0 ], im[ 0 ] ), dot( im[ 1 ], im[ 1 ] ), dot( im[ 2 ], im[ 2 ] ) ); transformedNormal = im * transformedNormal; #ifdef USE_TANGENT transformedTangent = im * transformedTangent; #endif #endif transformedNormal = normalMatrix * transformedNormal; #ifdef FLIP_SIDED transformedNormal = - transformedNormal; #endif #ifdef USE_TANGENT transformedTangent = ( modelViewMatrix * vec4( transformedTangent, 0.0 ) ).xyz; #ifdef FLIP_SIDED transformedTangent = - transformedTangent; #endif #endif`,hA=`#ifdef USE_DISPLACEMENTMAP uniform sampler2D displacementMap; uniform float displacementScale; uniform float displacementBias; #endif`,dA=`#ifdef USE_DISPLACEMENTMAP transformed += normalize( objectNormal ) * ( texture2D( displacementMap, vDisplacementMapUv ).x * displacementScale + displacementBias ); #endif`,uA=`#ifdef USE_EMISSIVEMAP vec4 emissiveColor = texture2D( emissiveMap, vEmissiveMapUv ); #ifdef DECODE_VIDEO_TEXTURE_EMISSIVE emissiveColor = sRGBTransferEOTF( emissiveColor ); #endif totalEmissiveRadiance *= emissiveColor.rgb; #endif`,pA=`#ifdef USE_EMISSIVEMAP uniform sampler2D emissiveMap; #endif`,fA="gl_FragColor = linearToOutputTexel( gl_FragColor );",mA=`vec4 LinearTransferOETF( in vec4 value ) { return value; } vec4 sRGBTransferEOTF( in vec4 value ) { 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.a ); } vec4 sRGBTransferOETF( in vec4 value ) { return vec4( mix( pow( value.rgb, vec3( 0.41666 ) ) * 1.055 - vec3( 0.055 ), value.rgb * 12.92, vec3( lessThanEqual( value.rgb, vec3( 0.0031308 ) ) ) ), value.a ); }`,gA=`#ifdef USE_ENVMAP #ifdef ENV_WORLDPOS vec3 cameraToFrag; if ( isOrthographic ) { cameraToFrag = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) ); } else { cameraToFrag = normalize( vWorldPosition - cameraPosition ); } vec3 worldNormal = inverseTransformDirection( normal, viewMatrix ); #ifdef ENVMAP_MODE_REFLECTION vec3 reflectVec = reflect( cameraToFrag, worldNormal ); #else vec3 reflectVec = refract( cameraToFrag, worldNormal, refractionRatio ); #endif #else vec3 reflectVec = vReflect; #endif #ifdef ENVMAP_TYPE_CUBE vec4 envColor = textureCube( envMap, envMapRotation * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) ); #ifdef ENVMAP_BLENDING_MULTIPLY outgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity ); #elif defined( ENVMAP_BLENDING_MIX ) outgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity ); #elif defined( ENVMAP_BLENDING_ADD ) outgoingLight += envColor.xyz * specularStrength * reflectivity; #endif #endif #endif`,vA=`#ifdef USE_ENVMAP uniform float envMapIntensity; uniform float flipEnvMap; uniform mat3 envMapRotation; #ifdef ENVMAP_TYPE_CUBE uniform samplerCube envMap; #else uniform sampler2D envMap; #endif #endif`,yA=`#ifdef USE_ENVMAP uniform float reflectivity; #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT ) #define ENV_WORLDPOS #endif #ifdef ENV_WORLDPOS varying vec3 vWorldPosition; uniform float refractionRatio; #else varying vec3 vReflect; #endif #endif`,xA=`#ifdef USE_ENVMAP #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT ) #define ENV_WORLDPOS #endif #ifdef ENV_WORLDPOS varying vec3 vWorldPosition; #else varying vec3 vReflect; uniform float refractionRatio; #endif #endif`,_A=`#ifdef USE_ENVMAP #ifdef ENV_WORLDPOS vWorldPosition = worldPosition.xyz; #else vec3 cameraToVertex; if ( isOrthographic ) { cameraToVertex = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) ); } else { cameraToVertex = normalize( worldPosition.xyz - cameraPosition ); } vec3 worldNormal = inverseTransformDirection( transformedNormal, viewMatrix ); #ifdef ENVMAP_MODE_REFLECTION vReflect = reflect( cameraToVertex, worldNormal ); #else vReflect = refract( cameraToVertex, worldNormal, refractionRatio ); #endif #endif #endif`,bA=`#ifdef USE_FOG vFogDepth = - mvPosition.z; #endif`,MA=`#ifdef USE_FOG varying float vFogDepth; #endif`,SA=`#ifdef USE_FOG #ifdef FOG_EXP2 float fogFactor = 1.0 - exp( - fogDensity * fogDensity * vFogDepth * vFogDepth ); #else float fogFactor = smoothstep( fogNear, fogFar, vFogDepth ); #endif gl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor ); #endif`,wA=`#ifdef USE_FOG uniform vec3 fogColor; varying float vFogDepth; #ifdef FOG_EXP2 uniform float fogDensity; #else uniform float fogNear; uniform float fogFar; #endif #endif`,EA=`#ifdef USE_GRADIENTMAP uniform sampler2D gradientMap; #endif vec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) { float dotNL = dot( normal, lightDirection ); vec2 coord = vec2( dotNL * 0.5 + 0.5, 0.0 ); #ifdef USE_GRADIENTMAP return vec3( texture2D( gradientMap, coord ).r ); #else vec2 fw = fwidth( coord ) * 0.5; return mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( 0.7 - fw.x, 0.7 + fw.x, coord.x ) ); #endif }`,TA=`#ifdef USE_LIGHTMAP uniform sampler2D lightMap; uniform float lightMapIntensity; #endif`,CA=`LambertMaterial material; material.diffuseColor = diffuseColor.rgb; material.specularStrength = specularStrength;`,AA=`varying vec3 vViewPosition; struct LambertMaterial { vec3 diffuseColor; float specularStrength; }; void RE_Direct_Lambert( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in LambertMaterial material, inout ReflectedLight reflectedLight ) { float dotNL = saturate( dot( geometryNormal, directLight.direction ) ); vec3 irradiance = dotNL * directLight.color; reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); } void RE_IndirectDiffuse_Lambert( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in LambertMaterial material, inout ReflectedLight reflectedLight ) { reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); } #define RE_Direct RE_Direct_Lambert #define RE_IndirectDiffuse RE_IndirectDiffuse_Lambert`,PA=`uniform bool receiveShadow; uniform vec3 ambientLightColor; #if defined( USE_LIGHT_PROBES ) uniform vec3 lightProbe[ 9 ]; #endif vec3 shGetIrradianceAt( in vec3 normal, in vec3 shCoefficients[ 9 ] ) { float x = normal.x, y = normal.y, z = normal.z; vec3 result = shCoefficients[ 0 ] * 0.886227; result += shCoefficients[ 1 ] * 2.0 * 0.511664 * y; result += shCoefficients[ 2 ] * 2.0 * 0.511664 * z; result += shCoefficients[ 3 ] * 2.0 * 0.511664 * x; result += shCoefficients[ 4 ] * 2.0 * 0.429043 * x * y; result += shCoefficients[ 5 ] * 2.0 * 0.429043 * y * z; result += shCoefficients[ 6 ] * ( 0.743125 * z * z - 0.247708 ); result += shCoefficients[ 7 ] * 2.0 * 0.429043 * x * z; result += shCoefficients[ 8 ] * 0.429043 * ( x * x - y * y ); return result; } vec3 getLightProbeIrradiance( const in vec3 lightProbe[ 9 ], const in vec3 normal ) { vec3 worldNormal = inverseTransformDirection( normal, viewMatrix ); vec3 irradiance = shGetIrradianceAt( worldNormal, lightProbe ); return irradiance; } vec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) { vec3 irradiance = ambientLightColor; return irradiance; } float getDistanceAttenuation( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) { float distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 ); if ( cutoffDistance > 0.0 ) { distanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) ); } return distanceFalloff; } float getSpotAttenuation( const in float coneCosine, const in float penumbraCosine, const in float angleCosine ) { return smoothstep( coneCosine, penumbraCosine, angleCosine ); } #if NUM_DIR_LIGHTS > 0 struct DirectionalLight { vec3 direction; vec3 color; }; uniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ]; void getDirectionalLightInfo( const in DirectionalLight directionalLight, out IncidentLight light ) { light.color = directionalLight.color; light.direction = directionalLight.direction; light.visible = true; } #endif #if NUM_POINT_LIGHTS > 0 struct PointLight { vec3 position; vec3 color; float distance; float decay; }; uniform PointLight pointLights[ NUM_POINT_LIGHTS ]; void getPointLightInfo( const in PointLight pointLight, const in vec3 geometryPosition, out IncidentLight light ) { vec3 lVector = pointLight.position - geometryPosition; light.direction = normalize( lVector ); float lightDistance = length( lVector ); light.color = pointLight.color; light.color *= getDistanceAttenuation( lightDistance, pointLight.distance, pointLight.decay ); light.visible = ( light.color != vec3( 0.0 ) ); } #endif #if NUM_SPOT_LIGHTS > 0 struct SpotLight { vec3 position; vec3 direction; vec3 color; float distance; float decay; float coneCos; float penumbraCos; }; uniform SpotLight spotLights[ NUM_SPOT_LIGHTS ]; void getSpotLightInfo( const in SpotLight spotLight, const in vec3 geometryPosition, out IncidentLight light ) { vec3 lVector = spotLight.position - geometryPosition; light.direction = normalize( lVector ); float angleCos = dot( light.direction, spotLight.direction ); float spotAttenuation = getSpotAttenuation( spotLight.coneCos, spotLight.penumbraCos, angleCos ); if ( spotAttenuation > 0.0 ) { float lightDistance = length( lVector ); light.color = spotLight.color * spotAttenuation; light.color *= getDistanceAttenuation( lightDistance, spotLight.distance, spotLight.decay ); light.visible = ( light.color != vec3( 0.0 ) ); } else { light.color = vec3( 0.0 ); light.visible = false; } } #endif #if NUM_RECT_AREA_LIGHTS > 0 struct RectAreaLight { vec3 color; vec3 position; vec3 halfWidth; vec3 halfHeight; }; uniform sampler2D ltc_1; uniform sampler2D ltc_2; uniform RectAreaLight rectAreaLights[ NUM_RECT_AREA_LIGHTS ]; #endif #if NUM_HEMI_LIGHTS > 0 struct HemisphereLight { vec3 direction; vec3 skyColor; vec3 groundColor; }; uniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ]; vec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in vec3 normal ) { float dotNL = dot( normal, hemiLight.direction ); float hemiDiffuseWeight = 0.5 * dotNL + 0.5; vec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight ); return irradiance; } #endif`,RA=`#ifdef USE_ENVMAP vec3 getIBLIrradiance( const in vec3 normal ) { #ifdef ENVMAP_TYPE_CUBE_UV vec3 worldNormal = inverseTransformDirection( normal, viewMatrix ); vec4 envMapColor = textureCubeUV( envMap, envMapRotation * worldNormal, 1.0 ); return PI * envMapColor.rgb * envMapIntensity; #else return vec3( 0.0 ); #endif } vec3 getIBLRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness ) { #ifdef ENVMAP_TYPE_CUBE_UV vec3 reflectVec = reflect( - viewDir, normal ); reflectVec = normalize( mix( reflectVec, normal, pow4( roughness ) ) ); reflectVec = inverseTransformDirection( reflectVec, viewMatrix ); vec4 envMapColor = textureCubeUV( envMap, envMapRotation * reflectVec, roughness ); return envMapColor.rgb * envMapIntensity; #else return vec3( 0.0 ); #endif } #ifdef USE_ANISOTROPY vec3 getIBLAnisotropyRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness, const in vec3 bitangent, const in float anisotropy ) { #ifdef ENVMAP_TYPE_CUBE_UV vec3 bentNormal = cross( bitangent, viewDir ); bentNormal = normalize( cross( bentNormal, bitangent ) ); bentNormal = normalize( mix( bentNormal, normal, pow2( pow2( 1.0 - anisotropy * ( 1.0 - roughness ) ) ) ) ); return getIBLRadiance( viewDir, bentNormal, roughness ); #else return vec3( 0.0 ); #endif } #endif #endif`,IA=`ToonMaterial material; material.diffuseColor = diffuseColor.rgb;`,LA=`varying vec3 vViewPosition; struct ToonMaterial { vec3 diffuseColor; }; void RE_Direct_Toon( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in ToonMaterial material, inout ReflectedLight reflectedLight ) { vec3 irradiance = getGradientIrradiance( geometryNormal, directLight.direction ) * directLight.color; reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); } void RE_IndirectDiffuse_Toon( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in ToonMaterial material, inout ReflectedLight reflectedLight ) { reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); } #define RE_Direct RE_Direct_Toon #define RE_IndirectDiffuse RE_IndirectDiffuse_Toon`,DA=`BlinnPhongMaterial material; material.diffuseColor = diffuseColor.rgb; material.specularColor = specular; material.specularShininess = shininess; material.specularStrength = specularStrength;`,NA=`varying vec3 vViewPosition; struct BlinnPhongMaterial { vec3 diffuseColor; vec3 specularColor; float specularShininess; float specularStrength; }; void RE_Direct_BlinnPhong( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) { float dotNL = saturate( dot( geometryNormal, directLight.direction ) ); vec3 irradiance = dotNL * directLight.color; reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); reflectedLight.directSpecular += irradiance * BRDF_BlinnPhong( directLight.direction, geometryViewDir, geometryNormal, material.specularColor, material.specularShininess ) * material.specularStrength; } void RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) { reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); } #define RE_Direct RE_Direct_BlinnPhong #define RE_IndirectDiffuse RE_IndirectDiffuse_BlinnPhong`,kA=`PhysicalMaterial material; material.diffuseColor = diffuseColor.rgb; material.diffuseContribution = diffuseColor.rgb * ( 1.0 - metalnessFactor ); material.metalness = metalnessFactor; vec3 dxy = max( abs( dFdx( nonPerturbedNormal ) ), abs( dFdy( nonPerturbedNormal ) ) ); float geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z ); material.roughness = max( roughnessFactor, 0.0525 );material.roughness += geometryRoughness; material.roughness = min( material.roughness, 1.0 ); #ifdef IOR material.ior = ior; #ifdef USE_SPECULAR float specularIntensityFactor = specularIntensity; vec3 specularColorFactor = specularColor; #ifdef USE_SPECULAR_COLORMAP specularColorFactor *= texture2D( specularColorMap, vSpecularColorMapUv ).rgb; #endif #ifdef USE_SPECULAR_INTENSITYMAP specularIntensityFactor *= texture2D( specularIntensityMap, vSpecularIntensityMapUv ).a; #endif material.specularF90 = mix( specularIntensityFactor, 1.0, metalnessFactor ); #else float specularIntensityFactor = 1.0; vec3 specularColorFactor = vec3( 1.0 ); material.specularF90 = 1.0; #endif material.specularColor = min( pow2( ( material.ior - 1.0 ) / ( material.ior + 1.0 ) ) * specularColorFactor, vec3( 1.0 ) ) * specularIntensityFactor; material.specularColorBlended = mix( material.specularColor, diffuseColor.rgb, metalnessFactor ); #else material.specularColor = vec3( 0.04 ); material.specularColorBlended = mix( material.specularColor, diffuseColor.rgb, metalnessFactor ); material.specularF90 = 1.0; #endif #ifdef USE_CLEARCOAT material.clearcoat = clearcoat; material.clearcoatRoughness = clearcoatRoughness; material.clearcoatF0 = vec3( 0.04 ); material.clearcoatF90 = 1.0; #ifdef USE_CLEARCOATMAP material.clearcoat *= texture2D( clearcoatMap, vClearcoatMapUv ).x; #endif #ifdef USE_CLEARCOAT_ROUGHNESSMAP material.clearcoatRoughness *= texture2D( clearcoatRoughnessMap, vClearcoatRoughnessMapUv ).y; #endif material.clearcoat = saturate( material.clearcoat ); material.clearcoatRoughness = max( material.clearcoatRoughness, 0.0525 ); material.clearcoatRoughness += geometryRoughness; material.clearcoatRoughness = min( material.clearcoatRoughness, 1.0 ); #endif #ifdef USE_DISPERSION material.dispersion = dispersion; #endif #ifdef USE_IRIDESCENCE material.iridescence = iridescence; material.iridescenceIOR = iridescenceIOR; #ifdef USE_IRIDESCENCEMAP material.iridescence *= texture2D( iridescenceMap, vIridescenceMapUv ).r; #endif #ifdef USE_IRIDESCENCE_THICKNESSMAP material.iridescenceThickness = (iridescenceThicknessMaximum - iridescenceThicknessMinimum) * texture2D( iridescenceThicknessMap, vIridescenceThicknessMapUv ).g + iridescenceThicknessMinimum; #else material.iridescenceThickness = iridescenceThicknessMaximum; #endif #endif #ifdef USE_SHEEN material.sheenColor = sheenColor; #ifdef USE_SHEEN_COLORMAP material.sheenColor *= texture2D( sheenColorMap, vSheenColorMapUv ).rgb; #endif material.sheenRoughness = clamp( sheenRoughness, 0.0001, 1.0 ); #ifdef USE_SHEEN_ROUGHNESSMAP material.sheenRoughness *= texture2D( sheenRoughnessMap, vSheenRoughnessMapUv ).a; #endif #endif #ifdef USE_ANISOTROPY #ifdef USE_ANISOTROPYMAP mat2 anisotropyMat = mat2( anisotropyVector.x, anisotropyVector.y, - anisotropyVector.y, anisotropyVector.x ); vec3 anisotropyPolar = texture2D( anisotropyMap, vAnisotropyMapUv ).rgb; vec2 anisotropyV = anisotropyMat * normalize( 2.0 * anisotropyPolar.rg - vec2( 1.0 ) ) * anisotropyPolar.b; #else vec2 anisotropyV = anisotropyVector; #endif material.anisotropy = length( anisotropyV ); if( material.anisotropy == 0.0 ) { anisotropyV = vec2( 1.0, 0.0 ); } else { anisotropyV /= material.anisotropy; material.anisotropy = saturate( material.anisotropy ); } material.alphaT = mix( pow2( material.roughness ), 1.0, pow2( material.anisotropy ) ); material.anisotropyT = tbn[ 0 ] * anisotropyV.x + tbn[ 1 ] * anisotropyV.y; material.anisotropyB = tbn[ 1 ] * anisotropyV.x - tbn[ 0 ] * anisotropyV.y; #endif`,OA=`uniform sampler2D dfgLUT; struct PhysicalMaterial { vec3 diffuseColor; vec3 diffuseContribution; vec3 specularColor; vec3 specularColorBlended; float roughness; float metalness; float specularF90; float dispersion; #ifdef USE_CLEARCOAT float clearcoat; float clearcoatRoughness; vec3 clearcoatF0; float clearcoatF90; #endif #ifdef USE_IRIDESCENCE float iridescence; float iridescenceIOR; float iridescenceThickness; vec3 iridescenceFresnel; vec3 iridescenceF0; vec3 iridescenceFresnelDielectric; vec3 iridescenceFresnelMetallic; #endif #ifdef USE_SHEEN vec3 sheenColor; float sheenRoughness; #endif #ifdef IOR float ior; #endif #ifdef USE_TRANSMISSION float transmission; float transmissionAlpha; float thickness; float attenuationDistance; vec3 attenuationColor; #endif #ifdef USE_ANISOTROPY float anisotropy; float alphaT; vec3 anisotropyT; vec3 anisotropyB; #endif }; vec3 clearcoatSpecularDirect = vec3( 0.0 ); vec3 clearcoatSpecularIndirect = vec3( 0.0 ); vec3 sheenSpecularDirect = vec3( 0.0 ); vec3 sheenSpecularIndirect = vec3(0.0 ); vec3 Schlick_to_F0( const in vec3 f, const in float f90, const in float dotVH ) { float x = clamp( 1.0 - dotVH, 0.0, 1.0 ); float x2 = x * x; float x5 = clamp( x * x2 * x2, 0.0, 0.9999 ); return ( f - vec3( f90 ) * x5 ) / ( 1.0 - x5 ); } float V_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) { float a2 = pow2( alpha ); float gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) ); float gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) ); return 0.5 / max( gv + gl, EPSILON ); } float D_GGX( const in float alpha, const in float dotNH ) { float a2 = pow2( alpha ); float denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0; return RECIPROCAL_PI * a2 / pow2( denom ); } #ifdef USE_ANISOTROPY float V_GGX_SmithCorrelated_Anisotropic( const in float alphaT, const in float alphaB, const in float dotTV, const in float dotBV, const in float dotTL, const in float dotBL, const in float dotNV, const in float dotNL ) { float gv = dotNL * length( vec3( alphaT * dotTV, alphaB * dotBV, dotNV ) ); float gl = dotNV * length( vec3( alphaT * dotTL, alphaB * dotBL, dotNL ) ); float v = 0.5 / ( gv + gl ); return v; } float D_GGX_Anisotropic( const in float alphaT, const in float alphaB, const in float dotNH, const in float dotTH, const in float dotBH ) { float a2 = alphaT * alphaB; highp vec3 v = vec3( alphaB * dotTH, alphaT * dotBH, a2 * dotNH ); highp float v2 = dot( v, v ); float w2 = a2 / v2; return RECIPROCAL_PI * a2 * pow2 ( w2 ); } #endif #ifdef USE_CLEARCOAT vec3 BRDF_GGX_Clearcoat( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material) { vec3 f0 = material.clearcoatF0; float f90 = material.clearcoatF90; float roughness = material.clearcoatRoughness; float alpha = pow2( roughness ); vec3 halfDir = normalize( lightDir + viewDir ); float dotNL = saturate( dot( normal, lightDir ) ); float dotNV = saturate( dot( normal, viewDir ) ); float dotNH = saturate( dot( normal, halfDir ) ); float dotVH = saturate( dot( viewDir, halfDir ) ); vec3 F = F_Schlick( f0, f90, dotVH ); float V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV ); float D = D_GGX( alpha, dotNH ); return F * ( V * D ); } #endif vec3 BRDF_GGX( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material ) { vec3 f0 = material.specularColorBlended; float f90 = material.specularF90; float roughness = material.roughness; float alpha = pow2( roughness ); vec3 halfDir = normalize( lightDir + viewDir ); float dotNL = saturate( dot( normal, lightDir ) ); float dotNV = saturate( dot( normal, viewDir ) ); float dotNH = saturate( dot( normal, halfDir ) ); float dotVH = saturate( dot( viewDir, halfDir ) ); vec3 F = F_Schlick( f0, f90, dotVH ); #ifdef USE_IRIDESCENCE F = mix( F, material.iridescenceFresnel, material.iridescence ); #endif #ifdef USE_ANISOTROPY float dotTL = dot( material.anisotropyT, lightDir ); float dotTV = dot( material.anisotropyT, viewDir ); float dotTH = dot( material.anisotropyT, halfDir ); float dotBL = dot( material.anisotropyB, lightDir ); float dotBV = dot( material.anisotropyB, viewDir ); float dotBH = dot( material.anisotropyB, halfDir ); float V = V_GGX_SmithCorrelated_Anisotropic( material.alphaT, alpha, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL ); float D = D_GGX_Anisotropic( material.alphaT, alpha, dotNH, dotTH, dotBH ); #else float V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV ); float D = D_GGX( alpha, dotNH ); #endif return F * ( V * D ); } vec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) { const float LUT_SIZE = 64.0; const float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE; const float LUT_BIAS = 0.5 / LUT_SIZE; float dotNV = saturate( dot( N, V ) ); vec2 uv = vec2( roughness, sqrt( 1.0 - dotNV ) ); uv = uv * LUT_SCALE + LUT_BIAS; return uv; } float LTC_ClippedSphereFormFactor( const in vec3 f ) { float l = length( f ); return max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 ); } vec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) { float x = dot( v1, v2 ); float y = abs( x ); float a = 0.8543985 + ( 0.4965155 + 0.0145206 * y ) * y; float b = 3.4175940 + ( 4.1616724 + y ) * y; float v = a / b; float theta_sintheta = ( x > 0.0 ) ? v : 0.5 * inversesqrt( max( 1.0 - x * x, 1e-7 ) ) - v; return cross( v1, v2 ) * theta_sintheta; } vec3 LTC_Evaluate( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in vec3 rectCoords[ 4 ] ) { vec3 v1 = rectCoords[ 1 ] - rectCoords[ 0 ]; vec3 v2 = rectCoords[ 3 ] - rectCoords[ 0 ]; vec3 lightNormal = cross( v1, v2 ); if( dot( lightNormal, P - rectCoords[ 0 ] ) < 0.0 ) return vec3( 0.0 ); vec3 T1, T2; T1 = normalize( V - N * dot( V, N ) ); T2 = - cross( N, T1 ); mat3 mat = mInv * transpose( mat3( T1, T2, N ) ); vec3 coords[ 4 ]; coords[ 0 ] = mat * ( rectCoords[ 0 ] - P ); coords[ 1 ] = mat * ( rectCoords[ 1 ] - P ); coords[ 2 ] = mat * ( rectCoords[ 2 ] - P ); coords[ 3 ] = mat * ( rectCoords[ 3 ] - P ); coords[ 0 ] = normalize( coords[ 0 ] ); coords[ 1 ] = normalize( coords[ 1 ] ); coords[ 2 ] = normalize( coords[ 2 ] ); coords[ 3 ] = normalize( coords[ 3 ] ); vec3 vectorFormFactor = vec3( 0.0 ); vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] ); vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] ); vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] ); vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] ); float result = LTC_ClippedSphereFormFactor( vectorFormFactor ); return vec3( result ); } #if defined( USE_SHEEN ) float D_Charlie( float roughness, float dotNH ) { float alpha = pow2( roughness ); float invAlpha = 1.0 / alpha; float cos2h = dotNH * dotNH; float sin2h = max( 1.0 - cos2h, 0.0078125 ); return ( 2.0 + invAlpha ) * pow( sin2h, invAlpha * 0.5 ) / ( 2.0 * PI ); } float V_Neubelt( float dotNV, float dotNL ) { return saturate( 1.0 / ( 4.0 * ( dotNL + dotNV - dotNL * dotNV ) ) ); } vec3 BRDF_Sheen( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, vec3 sheenColor, const in float sheenRoughness ) { vec3 halfDir = normalize( lightDir + viewDir ); float dotNL = saturate( dot( normal, lightDir ) ); float dotNV = saturate( dot( normal, viewDir ) ); float dotNH = saturate( dot( normal, halfDir ) ); float D = D_Charlie( sheenRoughness, dotNH ); float V = V_Neubelt( dotNV, dotNL ); return sheenColor * ( D * V ); } #endif float IBLSheenBRDF( const in vec3 normal, const in vec3 viewDir, const in float roughness ) { float dotNV = saturate( dot( normal, viewDir ) ); float r2 = roughness * roughness; float rInv = 1.0 / ( roughness + 0.1 ); float a = -1.9362 + 1.0678 * roughness + 0.4573 * r2 - 0.8469 * rInv; float b = -0.6014 + 0.5538 * roughness - 0.4670 * r2 - 0.1255 * rInv; float DG = exp( a * dotNV + b ); return saturate( DG ); } vec3 EnvironmentBRDF( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness ) { float dotNV = saturate( dot( normal, viewDir ) ); vec2 fab = texture2D( dfgLUT, vec2( roughness, dotNV ) ).rg; return specularColor * fab.x + specularF90 * fab.y; } #ifdef USE_IRIDESCENCE void computeMultiscatteringIridescence( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float iridescence, const in vec3 iridescenceF0, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) { #else void computeMultiscattering( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) { #endif float dotNV = saturate( dot( normal, viewDir ) ); vec2 fab = texture2D( dfgLUT, vec2( roughness, dotNV ) ).rg; #ifdef USE_IRIDESCENCE vec3 Fr = mix( specularColor, iridescenceF0, iridescence ); #else vec3 Fr = specularColor; #endif vec3 FssEss = Fr * fab.x + specularF90 * fab.y; float Ess = fab.x + fab.y; float Ems = 1.0 - Ess; vec3 Favg = Fr + ( 1.0 - Fr ) * 0.047619; vec3 Fms = FssEss * Favg / ( 1.0 - Ems * Favg ); singleScatter += FssEss; multiScatter += Fms * Ems; } vec3 BRDF_GGX_Multiscatter( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material ) { vec3 singleScatter = BRDF_GGX( lightDir, viewDir, normal, material ); float dotNL = saturate( dot( normal, lightDir ) ); float dotNV = saturate( dot( normal, viewDir ) ); vec2 dfgV = texture2D( dfgLUT, vec2( material.roughness, dotNV ) ).rg; vec2 dfgL = texture2D( dfgLUT, vec2( material.roughness, dotNL ) ).rg; vec3 FssEss_V = material.specularColorBlended * dfgV.x + material.specularF90 * dfgV.y; vec3 FssEss_L = material.specularColorBlended * dfgL.x + material.specularF90 * dfgL.y; float Ess_V = dfgV.x + dfgV.y; float Ess_L = dfgL.x + dfgL.y; float Ems_V = 1.0 - Ess_V; float Ems_L = 1.0 - Ess_L; vec3 Favg = material.specularColorBlended + ( 1.0 - material.specularColorBlended ) * 0.047619; vec3 Fms = FssEss_V * FssEss_L * Favg / ( 1.0 - Ems_V * Ems_L * Favg + EPSILON ); float compensationFactor = Ems_V * Ems_L; vec3 multiScatter = Fms * compensationFactor; return singleScatter + multiScatter; } #if NUM_RECT_AREA_LIGHTS > 0 void RE_Direct_RectArea_Physical( const in RectAreaLight rectAreaLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) { vec3 normal = geometryNormal; vec3 viewDir = geometryViewDir; vec3 position = geometryPosition; vec3 lightPos = rectAreaLight.position; vec3 halfWidth = rectAreaLight.halfWidth; vec3 halfHeight = rectAreaLight.halfHeight; vec3 lightColor = rectAreaLight.color; float roughness = material.roughness; vec3 rectCoords[ 4 ]; rectCoords[ 0 ] = lightPos + halfWidth - halfHeight; rectCoords[ 1 ] = lightPos - halfWidth - halfHeight; rectCoords[ 2 ] = lightPos - halfWidth + halfHeight; rectCoords[ 3 ] = lightPos + halfWidth + halfHeight; vec2 uv = LTC_Uv( normal, viewDir, roughness ); vec4 t1 = texture2D( ltc_1, uv ); vec4 t2 = texture2D( ltc_2, uv ); mat3 mInv = mat3( vec3( t1.x, 0, t1.y ), vec3( 0, 1, 0 ), vec3( t1.z, 0, t1.w ) ); vec3 fresnel = ( material.specularColorBlended * t2.x + ( material.specularF90 - material.specularColorBlended ) * t2.y ); reflectedLight.directSpecular += lightColor * fresnel * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords ); reflectedLight.directDiffuse += lightColor * material.diffuseContribution * LTC_Evaluate( normal, viewDir, position, mat3( 1.0 ), rectCoords ); #ifdef USE_CLEARCOAT vec3 Ncc = geometryClearcoatNormal; vec2 uvClearcoat = LTC_Uv( Ncc, viewDir, material.clearcoatRoughness ); vec4 t1Clearcoat = texture2D( ltc_1, uvClearcoat ); vec4 t2Clearcoat = texture2D( ltc_2, uvClearcoat ); mat3 mInvClearcoat = mat3( vec3( t1Clearcoat.x, 0, t1Clearcoat.y ), vec3( 0, 1, 0 ), vec3( t1Clearcoat.z, 0, t1Clearcoat.w ) ); vec3 fresnelClearcoat = material.clearcoatF0 * t2Clearcoat.x + ( material.clearcoatF90 - material.clearcoatF0 ) * t2Clearcoat.y; clearcoatSpecularDirect += lightColor * fresnelClearcoat * LTC_Evaluate( Ncc, viewDir, position, mInvClearcoat, rectCoords ); #endif } #endif void RE_Direct_Physical( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) { float dotNL = saturate( dot( geometryNormal, directLight.direction ) ); vec3 irradiance = dotNL * directLight.color; #ifdef USE_CLEARCOAT float dotNLcc = saturate( dot( geometryClearcoatNormal, directLight.direction ) ); vec3 ccIrradiance = dotNLcc * directLight.color; clearcoatSpecularDirect += ccIrradiance * BRDF_GGX_Clearcoat( directLight.direction, geometryViewDir, geometryClearcoatNormal, material ); #endif #ifdef USE_SHEEN sheenSpecularDirect += irradiance * BRDF_Sheen( directLight.direction, geometryViewDir, geometryNormal, material.sheenColor, material.sheenRoughness ); float sheenAlbedoV = IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness ); float sheenAlbedoL = IBLSheenBRDF( geometryNormal, directLight.direction, material.sheenRoughness ); float sheenEnergyComp = 1.0 - max3( material.sheenColor ) * max( sheenAlbedoV, sheenAlbedoL ); irradiance *= sheenEnergyComp; #endif reflectedLight.directSpecular += irradiance * BRDF_GGX_Multiscatter( directLight.direction, geometryViewDir, geometryNormal, material ); reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseContribution ); } void RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) { vec3 diffuse = irradiance * BRDF_Lambert( material.diffuseContribution ); #ifdef USE_SHEEN float sheenAlbedo = IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness ); float sheenEnergyComp = 1.0 - max3( material.sheenColor ) * sheenAlbedo; diffuse *= sheenEnergyComp; #endif reflectedLight.indirectDiffuse += diffuse; } void RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 irradiance, const in vec3 clearcoatRadiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight) { #ifdef USE_CLEARCOAT clearcoatSpecularIndirect += clearcoatRadiance * EnvironmentBRDF( geometryClearcoatNormal, geometryViewDir, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness ); #endif #ifdef USE_SHEEN sheenSpecularIndirect += irradiance * material.sheenColor * IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness ) * RECIPROCAL_PI; #endif vec3 singleScatteringDielectric = vec3( 0.0 ); vec3 multiScatteringDielectric = vec3( 0.0 ); vec3 singleScatteringMetallic = vec3( 0.0 ); vec3 multiScatteringMetallic = vec3( 0.0 ); #ifdef USE_IRIDESCENCE computeMultiscatteringIridescence( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.iridescence, material.iridescenceFresnelDielectric, material.roughness, singleScatteringDielectric, multiScatteringDielectric ); computeMultiscatteringIridescence( geometryNormal, geometryViewDir, material.diffuseColor, material.specularF90, material.iridescence, material.iridescenceFresnelMetallic, material.roughness, singleScatteringMetallic, multiScatteringMetallic ); #else computeMultiscattering( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.roughness, singleScatteringDielectric, multiScatteringDielectric ); computeMultiscattering( geometryNormal, geometryViewDir, material.diffuseColor, material.specularF90, material.roughness, singleScatteringMetallic, multiScatteringMetallic ); #endif vec3 singleScattering = mix( singleScatteringDielectric, singleScatteringMetallic, material.metalness ); vec3 multiScattering = mix( multiScatteringDielectric, multiScatteringMetallic, material.metalness ); vec3 totalScatteringDielectric = singleScatteringDielectric + multiScatteringDielectric; vec3 diffuse = material.diffuseContribution * ( 1.0 - totalScatteringDielectric ); vec3 cosineWeightedIrradiance = irradiance * RECIPROCAL_PI; vec3 indirectSpecular = radiance * singleScattering; indirectSpecular += multiScattering * cosineWeightedIrradiance; vec3 indirectDiffuse = diffuse * cosineWeightedIrradiance; #ifdef USE_SHEEN float sheenAlbedo = IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness ); float sheenEnergyComp = 1.0 - max3( material.sheenColor ) * sheenAlbedo; indirectSpecular *= sheenEnergyComp; indirectDiffuse *= sheenEnergyComp; #endif reflectedLight.indirectSpecular += indirectSpecular; reflectedLight.indirectDiffuse += indirectDiffuse; } #define RE_Direct RE_Direct_Physical #define RE_Direct_RectArea RE_Direct_RectArea_Physical #define RE_IndirectDiffuse RE_IndirectDiffuse_Physical #define RE_IndirectSpecular RE_IndirectSpecular_Physical float computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) { return saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion ); }`,UA=` vec3 geometryPosition = - vViewPosition; vec3 geometryNormal = normal; vec3 geometryViewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition ); vec3 geometryClearcoatNormal = vec3( 0.0 ); #ifdef USE_CLEARCOAT geometryClearcoatNormal = clearcoatNormal; #endif #ifdef USE_IRIDESCENCE float dotNVi = saturate( dot( normal, geometryViewDir ) ); if ( material.iridescenceThickness == 0.0 ) { material.iridescence = 0.0; } else { material.iridescence = saturate( material.iridescence ); } if ( material.iridescence > 0.0 ) { material.iridescenceFresnelDielectric = evalIridescence( 1.0, material.iridescenceIOR, dotNVi, material.iridescenceThickness, material.specularColor ); material.iridescenceFresnelMetallic = evalIridescence( 1.0, material.iridescenceIOR, dotNVi, material.iridescenceThickness, material.diffuseColor ); material.iridescenceFresnel = mix( material.iridescenceFresnelDielectric, material.iridescenceFresnelMetallic, material.metalness ); material.iridescenceF0 = Schlick_to_F0( material.iridescenceFresnel, 1.0, dotNVi ); } #endif IncidentLight directLight; #if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct ) PointLight pointLight; #if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0 PointLightShadow pointLightShadow; #endif #pragma unroll_loop_start for ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) { pointLight = pointLights[ i ]; getPointLightInfo( pointLight, geometryPosition, directLight ); #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS ) && ( defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_BASIC ) ) pointLightShadow = pointLightShadows[ i ]; directLight.color *= ( directLight.visible && receiveShadow ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowIntensity, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0; #endif RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); } #pragma unroll_loop_end #endif #if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct ) SpotLight spotLight; vec4 spotColor; vec3 spotLightCoord; bool inSpotLightMap; #if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0 SpotLightShadow spotLightShadow; #endif #pragma unroll_loop_start for ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) { spotLight = spotLights[ i ]; getSpotLightInfo( spotLight, geometryPosition, directLight ); #if ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS ) #define SPOT_LIGHT_MAP_INDEX UNROLLED_LOOP_INDEX #elif ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS ) #define SPOT_LIGHT_MAP_INDEX NUM_SPOT_LIGHT_MAPS #else #define SPOT_LIGHT_MAP_INDEX ( UNROLLED_LOOP_INDEX - NUM_SPOT_LIGHT_SHADOWS + NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS ) #endif #if ( SPOT_LIGHT_MAP_INDEX < NUM_SPOT_LIGHT_MAPS ) spotLightCoord = vSpotLightCoord[ i ].xyz / vSpotLightCoord[ i ].w; inSpotLightMap = all( lessThan( abs( spotLightCoord * 2. - 1. ), vec3( 1.0 ) ) ); spotColor = texture2D( spotLightMap[ SPOT_LIGHT_MAP_INDEX ], spotLightCoord.xy ); directLight.color = inSpotLightMap ? directLight.color * spotColor.rgb : directLight.color; #endif #undef SPOT_LIGHT_MAP_INDEX #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS ) spotLightShadow = spotLightShadows[ i ]; directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowIntensity, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotLightCoord[ i ] ) : 1.0; #endif RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); } #pragma unroll_loop_end #endif #if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct ) DirectionalLight directionalLight; #if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0 DirectionalLightShadow directionalLightShadow; #endif #pragma unroll_loop_start for ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) { directionalLight = directionalLights[ i ]; getDirectionalLightInfo( directionalLight, directLight ); #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS ) directionalLightShadow = directionalLightShadows[ i ]; directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowIntensity, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0; #endif RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); } #pragma unroll_loop_end #endif #if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea ) RectAreaLight rectAreaLight; #pragma unroll_loop_start for ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) { rectAreaLight = rectAreaLights[ i ]; RE_Direct_RectArea( rectAreaLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); } #pragma unroll_loop_end #endif #if defined( RE_IndirectDiffuse ) vec3 iblIrradiance = vec3( 0.0 ); vec3 irradiance = getAmbientLightIrradiance( ambientLightColor ); #if defined( USE_LIGHT_PROBES ) irradiance += getLightProbeIrradiance( lightProbe, geometryNormal ); #endif #if ( NUM_HEMI_LIGHTS > 0 ) #pragma unroll_loop_start for ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) { irradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometryNormal ); } #pragma unroll_loop_end #endif #endif #if defined( RE_IndirectSpecular ) vec3 radiance = vec3( 0.0 ); vec3 clearcoatRadiance = vec3( 0.0 ); #endif`,BA=`#if defined( RE_IndirectDiffuse ) #ifdef USE_LIGHTMAP vec4 lightMapTexel = texture2D( lightMap, vLightMapUv ); vec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity; irradiance += lightMapIrradiance; #endif #if defined( USE_ENVMAP ) && defined( ENVMAP_TYPE_CUBE_UV ) #if defined( STANDARD ) || defined( LAMBERT ) || defined( PHONG ) iblIrradiance += getIBLIrradiance( geometryNormal ); #endif #endif #endif #if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular ) #ifdef USE_ANISOTROPY radiance += getIBLAnisotropyRadiance( geometryViewDir, geometryNormal, material.roughness, material.anisotropyB, material.anisotropy ); #else radiance += getIBLRadiance( geometryViewDir, geometryNormal, material.roughness ); #endif #ifdef USE_CLEARCOAT clearcoatRadiance += getIBLRadiance( geometryViewDir, geometryClearcoatNormal, material.clearcoatRoughness ); #endif #endif`,FA=`#if defined( RE_IndirectDiffuse ) #if defined( LAMBERT ) || defined( PHONG ) irradiance += iblIrradiance; #endif RE_IndirectDiffuse( irradiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); #endif #if defined( RE_IndirectSpecular ) RE_IndirectSpecular( radiance, iblIrradiance, clearcoatRadiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); #endif`,zA=`#if defined( USE_LOGARITHMIC_DEPTH_BUFFER ) gl_FragDepth = vIsPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5; #endif`,HA=`#if defined( USE_LOGARITHMIC_DEPTH_BUFFER ) uniform float logDepthBufFC; varying float vFragDepth; varying float vIsPerspective; #endif`,VA=`#ifdef USE_LOGARITHMIC_DEPTH_BUFFER varying float vFragDepth; varying float vIsPerspective; #endif`,GA=`#ifdef USE_LOGARITHMIC_DEPTH_BUFFER vFragDepth = 1.0 + gl_Position.w; vIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) ); #endif`,WA=`#ifdef USE_MAP vec4 sampledDiffuseColor = texture2D( map, vMapUv ); #ifdef DECODE_VIDEO_TEXTURE sampledDiffuseColor = sRGBTransferEOTF( sampledDiffuseColor ); #endif diffuseColor *= sampledDiffuseColor; #endif`,XA=`#ifdef USE_MAP uniform sampler2D map; #endif`,jA=`#if defined( USE_MAP ) || defined( USE_ALPHAMAP ) #if defined( USE_POINTS_UV ) vec2 uv = vUv; #else vec2 uv = ( uvTransform * vec3( gl_PointCoord.x, 1.0 - gl_PointCoord.y, 1 ) ).xy; #endif #endif #ifdef USE_MAP diffuseColor *= texture2D( map, uv ); #endif #ifdef USE_ALPHAMAP diffuseColor.a *= texture2D( alphaMap, uv ).g; #endif`,qA=`#if defined( USE_POINTS_UV ) varying vec2 vUv; #else #if defined( USE_MAP ) || defined( USE_ALPHAMAP ) uniform mat3 uvTransform; #endif #endif #ifdef USE_MAP uniform sampler2D map; #endif #ifdef USE_ALPHAMAP uniform sampler2D alphaMap; #endif`,ZA=`float metalnessFactor = metalness; #ifdef USE_METALNESSMAP vec4 texelMetalness = texture2D( metalnessMap, vMetalnessMapUv ); metalnessFactor *= texelMetalness.b; #endif`,YA=`#ifdef USE_METALNESSMAP uniform sampler2D metalnessMap; #endif`,$A=`#ifdef USE_INSTANCING_MORPH float morphTargetInfluences[ MORPHTARGETS_COUNT ]; float morphTargetBaseInfluence = texelFetch( morphTexture, ivec2( 0, gl_InstanceID ), 0 ).r; for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) { morphTargetInfluences[i] = texelFetch( morphTexture, ivec2( i + 1, gl_InstanceID ), 0 ).r; } #endif`,KA=`#if defined( USE_MORPHCOLORS ) vColor *= morphTargetBaseInfluence; for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) { #if defined( USE_COLOR_ALPHA ) if ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ) * morphTargetInfluences[ i ]; #elif defined( USE_COLOR ) if ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ).rgb * morphTargetInfluences[ i ]; #endif } #endif`,JA=`#ifdef USE_MORPHNORMALS objectNormal *= morphTargetBaseInfluence; for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) { if ( morphTargetInfluences[ i ] != 0.0 ) objectNormal += getMorph( gl_VertexID, i, 1 ).xyz * morphTargetInfluences[ i ]; } #endif`,QA=`#ifdef USE_MORPHTARGETS #ifndef USE_INSTANCING_MORPH uniform float morphTargetBaseInfluence; uniform float morphTargetInfluences[ MORPHTARGETS_COUNT ]; #endif uniform sampler2DArray morphTargetsTexture; uniform ivec2 morphTargetsTextureSize; vec4 getMorph( const in int vertexIndex, const in int morphTargetIndex, const in int offset ) { int texelIndex = vertexIndex * MORPHTARGETS_TEXTURE_STRIDE + offset; int y = texelIndex / morphTargetsTextureSize.x; int x = texelIndex - y * morphTargetsTextureSize.x; ivec3 morphUV = ivec3( x, y, morphTargetIndex ); return texelFetch( morphTargetsTexture, morphUV, 0 ); } #endif`,eP=`#ifdef USE_MORPHTARGETS transformed *= morphTargetBaseInfluence; for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) { if ( morphTargetInfluences[ i ] != 0.0 ) transformed += getMorph( gl_VertexID, i, 0 ).xyz * morphTargetInfluences[ i ]; } #endif`,tP=`float faceDirection = gl_FrontFacing ? 1.0 : - 1.0; #ifdef FLAT_SHADED vec3 fdx = dFdx( vViewPosition ); vec3 fdy = dFdy( vViewPosition ); vec3 normal = normalize( cross( fdx, fdy ) ); #else vec3 normal = normalize( vNormal ); #ifdef DOUBLE_SIDED normal *= faceDirection; #endif #endif #if defined( USE_NORMALMAP_TANGENTSPACE ) || defined( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY ) #ifdef USE_TANGENT mat3 tbn = mat3( normalize( vTangent ), normalize( vBitangent ), normal ); #else mat3 tbn = getTangentFrame( - vViewPosition, normal, #if defined( USE_NORMALMAP ) vNormalMapUv #elif defined( USE_CLEARCOAT_NORMALMAP ) vClearcoatNormalMapUv #else vUv #endif ); #endif #if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED ) tbn[0] *= faceDirection; tbn[1] *= faceDirection; #endif #endif #ifdef USE_CLEARCOAT_NORMALMAP #ifdef USE_TANGENT mat3 tbn2 = mat3( normalize( vTangent ), normalize( vBitangent ), normal ); #else mat3 tbn2 = getTangentFrame( - vViewPosition, normal, vClearcoatNormalMapUv ); #endif #if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED ) tbn2[0] *= faceDirection; tbn2[1] *= faceDirection; #endif #endif vec3 nonPerturbedNormal = normal;`,iP=`#ifdef USE_NORMALMAP_OBJECTSPACE normal = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0; #ifdef FLIP_SIDED normal = - normal; #endif #ifdef DOUBLE_SIDED normal = normal * faceDirection; #endif normal = normalize( normalMatrix * normal ); #elif defined( USE_NORMALMAP_TANGENTSPACE ) vec3 mapN = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0; mapN.xy *= normalScale; normal = normalize( tbn * mapN ); #elif defined( USE_BUMPMAP ) normal = perturbNormalArb( - vViewPosition, normal, dHdxy_fwd(), faceDirection ); #endif`,nP=`#ifndef FLAT_SHADED varying vec3 vNormal; #ifdef USE_TANGENT varying vec3 vTangent; varying vec3 vBitangent; #endif #endif`,sP=`#ifndef FLAT_SHADED varying vec3 vNormal; #ifdef USE_TANGENT varying vec3 vTangent; varying vec3 vBitangent; #endif #endif`,rP=`#ifndef FLAT_SHADED vNormal = normalize( transformedNormal ); #ifdef USE_TANGENT vTangent = normalize( transformedTangent ); vBitangent = normalize( cross( vNormal, vTangent ) * tangent.w ); #endif #endif`,aP=`#ifdef USE_NORMALMAP uniform sampler2D normalMap; uniform vec2 normalScale; #endif #ifdef USE_NORMALMAP_OBJECTSPACE uniform mat3 normalMatrix; #endif #if ! defined ( USE_TANGENT ) && ( defined ( USE_NORMALMAP_TANGENTSPACE ) || defined ( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY ) ) mat3 getTangentFrame( vec3 eye_pos, vec3 surf_norm, vec2 uv ) { vec3 q0 = dFdx( eye_pos.xyz ); vec3 q1 = dFdy( eye_pos.xyz ); vec2 st0 = dFdx( uv.st ); vec2 st1 = dFdy( uv.st ); vec3 N = surf_norm; vec3 q1perp = cross( q1, N ); vec3 q0perp = cross( N, q0 ); vec3 T = q1perp * st0.x + q0perp * st1.x; vec3 B = q1perp * st0.y + q0perp * st1.y; float det = max( dot( T, T ), dot( B, B ) ); float scale = ( det == 0.0 ) ? 0.0 : inversesqrt( det ); return mat3( T * scale, B * scale, N ); } #endif`,oP=`#ifdef USE_CLEARCOAT vec3 clearcoatNormal = nonPerturbedNormal; #endif`,lP=`#ifdef USE_CLEARCOAT_NORMALMAP vec3 clearcoatMapN = texture2D( clearcoatNormalMap, vClearcoatNormalMapUv ).xyz * 2.0 - 1.0; clearcoatMapN.xy *= clearcoatNormalScale; clearcoatNormal = normalize( tbn2 * clearcoatMapN ); #endif`,cP=`#ifdef USE_CLEARCOATMAP uniform sampler2D clearcoatMap; #endif #ifdef USE_CLEARCOAT_NORMALMAP uniform sampler2D clearcoatNormalMap; uniform vec2 clearcoatNormalScale; #endif #ifdef USE_CLEARCOAT_ROUGHNESSMAP uniform sampler2D clearcoatRoughnessMap; #endif`,hP=`#ifdef USE_IRIDESCENCEMAP uniform sampler2D iridescenceMap; #endif #ifdef USE_IRIDESCENCE_THICKNESSMAP uniform sampler2D iridescenceThicknessMap; #endif`,dP=`#ifdef OPAQUE diffuseColor.a = 1.0; #endif #ifdef USE_TRANSMISSION diffuseColor.a *= material.transmissionAlpha; #endif gl_FragColor = vec4( outgoingLight, diffuseColor.a );`,uP=`vec3 packNormalToRGB( const in vec3 normal ) { return normalize( normal ) * 0.5 + 0.5; } vec3 unpackRGBToNormal( const in vec3 rgb ) { return 2.0 * rgb.xyz - 1.0; } const float PackUpscale = 256. / 255.;const float UnpackDownscale = 255. / 256.;const float ShiftRight8 = 1. / 256.; const float Inv255 = 1. / 255.; const vec4 PackFactors = vec4( 1.0, 256.0, 256.0 * 256.0, 256.0 * 256.0 * 256.0 ); const vec2 UnpackFactors2 = vec2( UnpackDownscale, 1.0 / PackFactors.g ); const vec3 UnpackFactors3 = vec3( UnpackDownscale / PackFactors.rg, 1.0 / PackFactors.b ); const vec4 UnpackFactors4 = vec4( UnpackDownscale / PackFactors.rgb, 1.0 / PackFactors.a ); vec4 packDepthToRGBA( const in float v ) { if( v <= 0.0 ) return vec4( 0., 0., 0., 0. ); if( v >= 1.0 ) return vec4( 1., 1., 1., 1. ); float vuf; float af = modf( v * PackFactors.a, vuf ); float bf = modf( vuf * ShiftRight8, vuf ); float gf = modf( vuf * ShiftRight8, vuf ); return vec4( vuf * Inv255, gf * PackUpscale, bf * PackUpscale, af ); } vec3 packDepthToRGB( const in float v ) { if( v <= 0.0 ) return vec3( 0., 0., 0. ); if( v >= 1.0 ) return vec3( 1., 1., 1. ); float vuf; float bf = modf( v * PackFactors.b, vuf ); float gf = modf( vuf * ShiftRight8, vuf ); return vec3( vuf * Inv255, gf * PackUpscale, bf ); } vec2 packDepthToRG( const in float v ) { if( v <= 0.0 ) return vec2( 0., 0. ); if( v >= 1.0 ) return vec2( 1., 1. ); float vuf; float gf = modf( v * 256., vuf ); return vec2( vuf * Inv255, gf ); } float unpackRGBAToDepth( const in vec4 v ) { return dot( v, UnpackFactors4 ); } float unpackRGBToDepth( const in vec3 v ) { return dot( v, UnpackFactors3 ); } float unpackRGToDepth( const in vec2 v ) { return v.r * UnpackFactors2.r + v.g * UnpackFactors2.g; } vec4 pack2HalfToRGBA( const in vec2 v ) { vec4 r = vec4( v.x, fract( v.x * 255.0 ), v.y, fract( v.y * 255.0 ) ); return vec4( r.x - r.y / 255.0, r.y, r.z - r.w / 255.0, r.w ); } vec2 unpackRGBATo2Half( const in vec4 v ) { return vec2( v.x + ( v.y / 255.0 ), v.z + ( v.w / 255.0 ) ); } float viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) { return ( viewZ + near ) / ( near - far ); } float orthographicDepthToViewZ( const in float depth, const in float near, const in float far ) { #ifdef USE_REVERSED_DEPTH_BUFFER return depth * ( far - near ) - far; #else return depth * ( near - far ) - near; #endif } float viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) { return ( ( near + viewZ ) * far ) / ( ( far - near ) * viewZ ); } float perspectiveDepthToViewZ( const in float depth, const in float near, const in float far ) { #ifdef USE_REVERSED_DEPTH_BUFFER return ( near * far ) / ( ( near - far ) * depth - near ); #else return ( near * far ) / ( ( far - near ) * depth - far ); #endif }`,pP=`#ifdef PREMULTIPLIED_ALPHA gl_FragColor.rgb *= gl_FragColor.a; #endif`,fP=`vec4 mvPosition = vec4( transformed, 1.0 ); #ifdef USE_BATCHING mvPosition = batchingMatrix * mvPosition; #endif #ifdef USE_INSTANCING mvPosition = instanceMatrix * mvPosition; #endif mvPosition = modelViewMatrix * mvPosition; gl_Position = projectionMatrix * mvPosition;`,mP=`#ifdef DITHERING gl_FragColor.rgb = dithering( gl_FragColor.rgb ); #endif`,gP=`#ifdef DITHERING vec3 dithering( vec3 color ) { float grid_position = rand( gl_FragCoord.xy ); vec3 dither_shift_RGB = vec3( 0.25 / 255.0, -0.25 / 255.0, 0.25 / 255.0 ); dither_shift_RGB = mix( 2.0 * dither_shift_RGB, -2.0 * dither_shift_RGB, grid_position ); return color + dither_shift_RGB; } #endif`,vP=`float roughnessFactor = roughness; #ifdef USE_ROUGHNESSMAP vec4 texelRoughness = texture2D( roughnessMap, vRoughnessMapUv ); roughnessFactor *= texelRoughness.g; #endif`,yP=`#ifdef USE_ROUGHNESSMAP uniform sampler2D roughnessMap; #endif`,xP=`#if NUM_SPOT_LIGHT_COORDS > 0 varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ]; #endif #if NUM_SPOT_LIGHT_MAPS > 0 uniform sampler2D spotLightMap[ NUM_SPOT_LIGHT_MAPS ]; #endif #ifdef USE_SHADOWMAP #if NUM_DIR_LIGHT_SHADOWS > 0 #if defined( SHADOWMAP_TYPE_PCF ) uniform sampler2DShadow directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ]; #else uniform sampler2D directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ]; #endif varying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ]; struct DirectionalLightShadow { float shadowIntensity; float shadowBias; float shadowNormalBias; float shadowRadius; vec2 shadowMapSize; }; uniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ]; #endif #if NUM_SPOT_LIGHT_SHADOWS > 0 #if defined( SHADOWMAP_TYPE_PCF ) uniform sampler2DShadow spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ]; #else uniform sampler2D spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ]; #endif struct SpotLightShadow { float shadowIntensity; float shadowBias; float shadowNormalBias; float shadowRadius; vec2 shadowMapSize; }; uniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ]; #endif #if NUM_POINT_LIGHT_SHADOWS > 0 #if defined( SHADOWMAP_TYPE_PCF ) uniform samplerCubeShadow pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ]; #elif defined( SHADOWMAP_TYPE_BASIC ) uniform samplerCube pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ]; #endif varying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ]; struct PointLightShadow { float shadowIntensity; float shadowBias; float shadowNormalBias; float shadowRadius; vec2 shadowMapSize; float shadowCameraNear; float shadowCameraFar; }; uniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ]; #endif #if defined( SHADOWMAP_TYPE_PCF ) float interleavedGradientNoise( vec2 position ) { return fract( 52.9829189 * fract( dot( position, vec2( 0.06711056, 0.00583715 ) ) ) ); } vec2 vogelDiskSample( int sampleIndex, int samplesCount, float phi ) { const float goldenAngle = 2.399963229728653; float r = sqrt( ( float( sampleIndex ) + 0.5 ) / float( samplesCount ) ); float theta = float( sampleIndex ) * goldenAngle + phi; return vec2( cos( theta ), sin( theta ) ) * r; } #endif #if defined( SHADOWMAP_TYPE_PCF ) float getShadow( sampler2DShadow shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord ) { float shadow = 1.0; shadowCoord.xyz /= shadowCoord.w; shadowCoord.z += shadowBias; bool inFrustum = shadowCoord.x >= 0.0 && shadowCoord.x <= 1.0 && shadowCoord.y >= 0.0 && shadowCoord.y <= 1.0; bool frustumTest = inFrustum && shadowCoord.z <= 1.0; if ( frustumTest ) { vec2 texelSize = vec2( 1.0 ) / shadowMapSize; float radius = shadowRadius * texelSize.x; float phi = interleavedGradientNoise( gl_FragCoord.xy ) * PI2; shadow = ( texture( shadowMap, vec3( shadowCoord.xy + vogelDiskSample( 0, 5, phi ) * radius, shadowCoord.z ) ) + texture( shadowMap, vec3( shadowCoord.xy + vogelDiskSample( 1, 5, phi ) * radius, shadowCoord.z ) ) + texture( shadowMap, vec3( shadowCoord.xy + vogelDiskSample( 2, 5, phi ) * radius, shadowCoord.z ) ) + texture( shadowMap, vec3( shadowCoord.xy + vogelDiskSample( 3, 5, phi ) * radius, shadowCoord.z ) ) + texture( shadowMap, vec3( shadowCoord.xy + vogelDiskSample( 4, 5, phi ) * radius, shadowCoord.z ) ) ) * 0.2; } return mix( 1.0, shadow, shadowIntensity ); } #elif defined( SHADOWMAP_TYPE_VSM ) float getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord ) { float shadow = 1.0; shadowCoord.xyz /= shadowCoord.w; #ifdef USE_REVERSED_DEPTH_BUFFER shadowCoord.z -= shadowBias; #else shadowCoord.z += shadowBias; #endif bool inFrustum = shadowCoord.x >= 0.0 && shadowCoord.x <= 1.0 && shadowCoord.y >= 0.0 && shadowCoord.y <= 1.0; bool frustumTest = inFrustum && shadowCoord.z <= 1.0; if ( frustumTest ) { vec2 distribution = texture2D( shadowMap, shadowCoord.xy ).rg; float mean = distribution.x; float variance = distribution.y * distribution.y; #ifdef USE_REVERSED_DEPTH_BUFFER float hard_shadow = step( mean, shadowCoord.z ); #else float hard_shadow = step( shadowCoord.z, mean ); #endif if ( hard_shadow == 1.0 ) { shadow = 1.0; } else { variance = max( variance, 0.0000001 ); float d = shadowCoord.z - mean; float p_max = variance / ( variance + d * d ); p_max = clamp( ( p_max - 0.3 ) / 0.65, 0.0, 1.0 ); shadow = max( hard_shadow, p_max ); } } return mix( 1.0, shadow, shadowIntensity ); } #else float getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord ) { float shadow = 1.0; shadowCoord.xyz /= shadowCoord.w; #ifdef USE_REVERSED_DEPTH_BUFFER shadowCoord.z -= shadowBias; #else shadowCoord.z += shadowBias; #endif bool inFrustum = shadowCoord.x >= 0.0 && shadowCoord.x <= 1.0 && shadowCoord.y >= 0.0 && shadowCoord.y <= 1.0; bool frustumTest = inFrustum && shadowCoord.z <= 1.0; if ( frustumTest ) { float depth = texture2D( shadowMap, shadowCoord.xy ).r; #ifdef USE_REVERSED_DEPTH_BUFFER shadow = step( depth, shadowCoord.z ); #else shadow = step( shadowCoord.z, depth ); #endif } return mix( 1.0, shadow, shadowIntensity ); } #endif #if NUM_POINT_LIGHT_SHADOWS > 0 #if defined( SHADOWMAP_TYPE_PCF ) float getPointShadow( samplerCubeShadow shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) { float shadow = 1.0; vec3 lightToPosition = shadowCoord.xyz; vec3 bd3D = normalize( lightToPosition ); vec3 absVec = abs( lightToPosition ); float viewSpaceZ = max( max( absVec.x, absVec.y ), absVec.z ); if ( viewSpaceZ - shadowCameraFar <= 0.0 && viewSpaceZ - shadowCameraNear >= 0.0 ) { #ifdef USE_REVERSED_DEPTH_BUFFER float dp = ( shadowCameraNear * ( shadowCameraFar - viewSpaceZ ) ) / ( viewSpaceZ * ( shadowCameraFar - shadowCameraNear ) ); dp -= shadowBias; #else float dp = ( shadowCameraFar * ( viewSpaceZ - shadowCameraNear ) ) / ( viewSpaceZ * ( shadowCameraFar - shadowCameraNear ) ); dp += shadowBias; #endif float texelSize = shadowRadius / shadowMapSize.x; vec3 absDir = abs( bd3D ); vec3 tangent = absDir.x > absDir.z ? vec3( 0.0, 1.0, 0.0 ) : vec3( 1.0, 0.0, 0.0 ); tangent = normalize( cross( bd3D, tangent ) ); vec3 bitangent = cross( bd3D, tangent ); float phi = interleavedGradientNoise( gl_FragCoord.xy ) * PI2; vec2 sample0 = vogelDiskSample( 0, 5, phi ); vec2 sample1 = vogelDiskSample( 1, 5, phi ); vec2 sample2 = vogelDiskSample( 2, 5, phi ); vec2 sample3 = vogelDiskSample( 3, 5, phi ); vec2 sample4 = vogelDiskSample( 4, 5, phi ); shadow = ( texture( shadowMap, vec4( bd3D + ( tangent * sample0.x + bitangent * sample0.y ) * texelSize, dp ) ) + texture( shadowMap, vec4( bd3D + ( tangent * sample1.x + bitangent * sample1.y ) * texelSize, dp ) ) + texture( shadowMap, vec4( bd3D + ( tangent * sample2.x + bitangent * sample2.y ) * texelSize, dp ) ) + texture( shadowMap, vec4( bd3D + ( tangent * sample3.x + bitangent * sample3.y ) * texelSize, dp ) ) + texture( shadowMap, vec4( bd3D + ( tangent * sample4.x + bitangent * sample4.y ) * texelSize, dp ) ) ) * 0.2; } return mix( 1.0, shadow, shadowIntensity ); } #elif defined( SHADOWMAP_TYPE_BASIC ) float getPointShadow( samplerCube shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) { float shadow = 1.0; vec3 lightToPosition = shadowCoord.xyz; vec3 absVec = abs( lightToPosition ); float viewSpaceZ = max( max( absVec.x, absVec.y ), absVec.z ); if ( viewSpaceZ - shadowCameraFar <= 0.0 && viewSpaceZ - shadowCameraNear >= 0.0 ) { float dp = ( shadowCameraFar * ( viewSpaceZ - shadowCameraNear ) ) / ( viewSpaceZ * ( shadowCameraFar - shadowCameraNear ) ); dp += shadowBias; vec3 bd3D = normalize( lightToPosition ); float depth = textureCube( shadowMap, bd3D ).r; #ifdef USE_REVERSED_DEPTH_BUFFER depth = 1.0 - depth; #endif shadow = step( dp, depth ); } return mix( 1.0, shadow, shadowIntensity ); } #endif #endif #endif`,_P=`#if NUM_SPOT_LIGHT_COORDS > 0 uniform mat4 spotLightMatrix[ NUM_SPOT_LIGHT_COORDS ]; varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ]; #endif #ifdef USE_SHADOWMAP #if NUM_DIR_LIGHT_SHADOWS > 0 uniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHT_SHADOWS ]; varying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ]; struct DirectionalLightShadow { float shadowIntensity; float shadowBias; float shadowNormalBias; float shadowRadius; vec2 shadowMapSize; }; uniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ]; #endif #if NUM_SPOT_LIGHT_SHADOWS > 0 struct SpotLightShadow { float shadowIntensity; float shadowBias; float shadowNormalBias; float shadowRadius; vec2 shadowMapSize; }; uniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ]; #endif #if NUM_POINT_LIGHT_SHADOWS > 0 uniform mat4 pointShadowMatrix[ NUM_POINT_LIGHT_SHADOWS ]; varying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ]; struct PointLightShadow { float shadowIntensity; float shadowBias; float shadowNormalBias; float shadowRadius; vec2 shadowMapSize; float shadowCameraNear; float shadowCameraFar; }; uniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ]; #endif #endif`,bP=`#if ( defined( USE_SHADOWMAP ) && ( NUM_DIR_LIGHT_SHADOWS > 0 || NUM_POINT_LIGHT_SHADOWS > 0 ) ) || ( NUM_SPOT_LIGHT_COORDS > 0 ) vec3 shadowWorldNormal = inverseTransformDirection( transformedNormal, viewMatrix ); vec4 shadowWorldPosition; #endif #if defined( USE_SHADOWMAP ) #if NUM_DIR_LIGHT_SHADOWS > 0 #pragma unroll_loop_start for ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) { shadowWorldPosition = worldPosition + vec4( shadowWorldNormal * directionalLightShadows[ i ].shadowNormalBias, 0 ); vDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * shadowWorldPosition; } #pragma unroll_loop_end #endif #if NUM_POINT_LIGHT_SHADOWS > 0 #pragma unroll_loop_start for ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) { shadowWorldPosition = worldPosition + vec4( shadowWorldNormal * pointLightShadows[ i ].shadowNormalBias, 0 ); vPointShadowCoord[ i ] = pointShadowMatrix[ i ] * shadowWorldPosition; } #pragma unroll_loop_end #endif #endif #if NUM_SPOT_LIGHT_COORDS > 0 #pragma unroll_loop_start for ( int i = 0; i < NUM_SPOT_LIGHT_COORDS; i ++ ) { shadowWorldPosition = worldPosition; #if ( defined( USE_SHADOWMAP ) && UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS ) shadowWorldPosition.xyz += shadowWorldNormal * spotLightShadows[ i ].shadowNormalBias; #endif vSpotLightCoord[ i ] = spotLightMatrix[ i ] * shadowWorldPosition; } #pragma unroll_loop_end #endif`,MP=`float getShadowMask() { float shadow = 1.0; #ifdef USE_SHADOWMAP #if NUM_DIR_LIGHT_SHADOWS > 0 DirectionalLightShadow directionalLight; #pragma unroll_loop_start for ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) { directionalLight = directionalLightShadows[ i ]; shadow *= receiveShadow ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowIntensity, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0; } #pragma unroll_loop_end #endif #if NUM_SPOT_LIGHT_SHADOWS > 0 SpotLightShadow spotLight; #pragma unroll_loop_start for ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) { spotLight = spotLightShadows[ i ]; shadow *= receiveShadow ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowIntensity, spotLight.shadowBias, spotLight.shadowRadius, vSpotLightCoord[ i ] ) : 1.0; } #pragma unroll_loop_end #endif #if NUM_POINT_LIGHT_SHADOWS > 0 && ( defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_BASIC ) ) PointLightShadow pointLight; #pragma unroll_loop_start for ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) { pointLight = pointLightShadows[ i ]; shadow *= receiveShadow ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowIntensity, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0; } #pragma unroll_loop_end #endif #endif return shadow; }`,SP=`#ifdef USE_SKINNING mat4 boneMatX = getBoneMatrix( skinIndex.x ); mat4 boneMatY = getBoneMatrix( skinIndex.y ); mat4 boneMatZ = getBoneMatrix( skinIndex.z ); mat4 boneMatW = getBoneMatrix( skinIndex.w ); #endif`,wP=`#ifdef USE_SKINNING uniform mat4 bindMatrix; uniform mat4 bindMatrixInverse; uniform highp sampler2D boneTexture; mat4 getBoneMatrix( const in float i ) { int size = textureSize( boneTexture, 0 ).x; int j = int( i ) * 4; int x = j % size; int y = j / size; vec4 v1 = texelFetch( boneTexture, ivec2( x, y ), 0 ); vec4 v2 = texelFetch( boneTexture, ivec2( x + 1, y ), 0 ); vec4 v3 = texelFetch( boneTexture, ivec2( x + 2, y ), 0 ); vec4 v4 = texelFetch( boneTexture, ivec2( x + 3, y ), 0 ); return mat4( v1, v2, v3, v4 ); } #endif`,EP=`#ifdef USE_SKINNING vec4 skinVertex = bindMatrix * vec4( transformed, 1.0 ); vec4 skinned = vec4( 0.0 ); skinned += boneMatX * skinVertex * skinWeight.x; skinned += boneMatY * skinVertex * skinWeight.y; skinned += boneMatZ * skinVertex * skinWeight.z; skinned += boneMatW * skinVertex * skinWeight.w; transformed = ( bindMatrixInverse * skinned ).xyz; #endif`,TP=`#ifdef USE_SKINNING mat4 skinMatrix = mat4( 0.0 ); skinMatrix += skinWeight.x * boneMatX; skinMatrix += skinWeight.y * boneMatY; skinMatrix += skinWeight.z * boneMatZ; skinMatrix += skinWeight.w * boneMatW; skinMatrix = bindMatrixInverse * skinMatrix * bindMatrix; objectNormal = vec4( skinMatrix * vec4( objectNormal, 0.0 ) ).xyz; #ifdef USE_TANGENT objectTangent = vec4( skinMatrix * vec4( objectTangent, 0.0 ) ).xyz; #endif #endif`,CP=`float specularStrength; #ifdef USE_SPECULARMAP vec4 texelSpecular = texture2D( specularMap, vSpecularMapUv ); specularStrength = texelSpecular.r; #else specularStrength = 1.0; #endif`,AP=`#ifdef USE_SPECULARMAP uniform sampler2D specularMap; #endif`,PP=`#if defined( TONE_MAPPING ) gl_FragColor.rgb = toneMapping( gl_FragColor.rgb ); #endif`,RP=`#ifndef saturate #define saturate( a ) clamp( a, 0.0, 1.0 ) #endif uniform float toneMappingExposure; vec3 LinearToneMapping( vec3 color ) { return saturate( toneMappingExposure * color ); } vec3 ReinhardToneMapping( vec3 color ) { color *= toneMappingExposure; return saturate( color / ( vec3( 1.0 ) + color ) ); } vec3 CineonToneMapping( vec3 color ) { color *= toneMappingExposure; color = max( vec3( 0.0 ), color - 0.004 ); return pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) ); } vec3 RRTAndODTFit( vec3 v ) { vec3 a = v * ( v + 0.0245786 ) - 0.000090537; vec3 b = v * ( 0.983729 * v + 0.4329510 ) + 0.238081; return a / b; } vec3 ACESFilmicToneMapping( vec3 color ) { const mat3 ACESInputMat = mat3( vec3( 0.59719, 0.07600, 0.02840 ), vec3( 0.35458, 0.90834, 0.13383 ), vec3( 0.04823, 0.01566, 0.83777 ) ); const mat3 ACESOutputMat = mat3( vec3( 1.60475, -0.10208, -0.00327 ), vec3( -0.53108, 1.10813, -0.07276 ), vec3( -0.07367, -0.00605, 1.07602 ) ); color *= toneMappingExposure / 0.6; color = ACESInputMat * color; color = RRTAndODTFit( color ); color = ACESOutputMat * color; return saturate( color ); } const mat3 LINEAR_REC2020_TO_LINEAR_SRGB = mat3( vec3( 1.6605, - 0.1246, - 0.0182 ), vec3( - 0.5876, 1.1329, - 0.1006 ), vec3( - 0.0728, - 0.0083, 1.1187 ) ); const mat3 LINEAR_SRGB_TO_LINEAR_REC2020 = mat3( vec3( 0.6274, 0.0691, 0.0164 ), vec3( 0.3293, 0.9195, 0.0880 ), vec3( 0.0433, 0.0113, 0.8956 ) ); vec3 agxDefaultContrastApprox( vec3 x ) { vec3 x2 = x * x; vec3 x4 = x2 * x2; return + 15.5 * x4 * x2 - 40.14 * x4 * x + 31.96 * x4 - 6.868 * x2 * x + 0.4298 * x2 + 0.1191 * x - 0.00232; } vec3 AgXToneMapping( vec3 color ) { const mat3 AgXInsetMatrix = mat3( vec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ), vec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ), vec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 ) ); const mat3 AgXOutsetMatrix = mat3( vec3( 1.1271005818144368, - 0.1413297634984383, - 0.14132976349843826 ), vec3( - 0.11060664309660323, 1.157823702216272, - 0.11060664309660294 ), vec3( - 0.016493938717834573, - 0.016493938717834257, 1.2519364065950405 ) ); const float AgxMinEv = - 12.47393; const float AgxMaxEv = 4.026069; color *= toneMappingExposure; color = LINEAR_SRGB_TO_LINEAR_REC2020 * color; color = AgXInsetMatrix * color; color = max( color, 1e-10 ); color = log2( color ); color = ( color - AgxMinEv ) / ( AgxMaxEv - AgxMinEv ); color = clamp( color, 0.0, 1.0 ); color = agxDefaultContrastApprox( color ); color = AgXOutsetMatrix * color; color = pow( max( vec3( 0.0 ), color ), vec3( 2.2 ) ); color = LINEAR_REC2020_TO_LINEAR_SRGB * color; color = clamp( color, 0.0, 1.0 ); return color; } vec3 NeutralToneMapping( vec3 color ) { const float StartCompression = 0.8 - 0.04; const float Desaturation = 0.15; color *= toneMappingExposure; float x = min( color.r, min( color.g, color.b ) ); float offset = x < 0.08 ? x - 6.25 * x * x : 0.04; color -= offset; float peak = max( color.r, max( color.g, color.b ) ); if ( peak < StartCompression ) return color; float d = 1. - StartCompression; float newPeak = 1. - d * d / ( peak + d - StartCompression ); color *= newPeak / peak; float g = 1. - 1. / ( Desaturation * ( peak - newPeak ) + 1. ); return mix( color, vec3( newPeak ), g ); } vec3 CustomToneMapping( vec3 color ) { return color; }`,IP=`#ifdef USE_TRANSMISSION material.transmission = transmission; material.transmissionAlpha = 1.0; material.thickness = thickness; material.attenuationDistance = attenuationDistance; material.attenuationColor = attenuationColor; #ifdef USE_TRANSMISSIONMAP material.transmission *= texture2D( transmissionMap, vTransmissionMapUv ).r; #endif #ifdef USE_THICKNESSMAP material.thickness *= texture2D( thicknessMap, vThicknessMapUv ).g; #endif vec3 pos = vWorldPosition; vec3 v = normalize( cameraPosition - pos ); vec3 n = inverseTransformDirection( normal, viewMatrix ); vec4 transmitted = getIBLVolumeRefraction( n, v, material.roughness, material.diffuseContribution, material.specularColorBlended, material.specularF90, pos, modelMatrix, viewMatrix, projectionMatrix, material.dispersion, material.ior, material.thickness, material.attenuationColor, material.attenuationDistance ); material.transmissionAlpha = mix( material.transmissionAlpha, transmitted.a, material.transmission ); totalDiffuse = mix( totalDiffuse, transmitted.rgb, material.transmission ); #endif`,LP=`#ifdef USE_TRANSMISSION uniform float transmission; uniform float thickness; uniform float attenuationDistance; uniform vec3 attenuationColor; #ifdef USE_TRANSMISSIONMAP uniform sampler2D transmissionMap; #endif #ifdef USE_THICKNESSMAP uniform sampler2D thicknessMap; #endif uniform vec2 transmissionSamplerSize; uniform sampler2D transmissionSamplerMap; uniform mat4 modelMatrix; uniform mat4 projectionMatrix; varying vec3 vWorldPosition; float w0( float a ) { return ( 1.0 / 6.0 ) * ( a * ( a * ( - a + 3.0 ) - 3.0 ) + 1.0 ); } float w1( float a ) { return ( 1.0 / 6.0 ) * ( a * a * ( 3.0 * a - 6.0 ) + 4.0 ); } float w2( float a ){ return ( 1.0 / 6.0 ) * ( a * ( a * ( - 3.0 * a + 3.0 ) + 3.0 ) + 1.0 ); } float w3( float a ) { return ( 1.0 / 6.0 ) * ( a * a * a ); } float g0( float a ) { return w0( a ) + w1( a ); } float g1( float a ) { return w2( a ) + w3( a ); } float h0( float a ) { return - 1.0 + w1( a ) / ( w0( a ) + w1( a ) ); } float h1( float a ) { return 1.0 + w3( a ) / ( w2( a ) + w3( a ) ); } vec4 bicubic( sampler2D tex, vec2 uv, vec4 texelSize, float lod ) { uv = uv * texelSize.zw + 0.5; vec2 iuv = floor( uv ); vec2 fuv = fract( uv ); float g0x = g0( fuv.x ); float g1x = g1( fuv.x ); float h0x = h0( fuv.x ); float h1x = h1( fuv.x ); float h0y = h0( fuv.y ); float h1y = h1( fuv.y ); vec2 p0 = ( vec2( iuv.x + h0x, iuv.y + h0y ) - 0.5 ) * texelSize.xy; vec2 p1 = ( vec2( iuv.x + h1x, iuv.y + h0y ) - 0.5 ) * texelSize.xy; vec2 p2 = ( vec2( iuv.x + h0x, iuv.y + h1y ) - 0.5 ) * texelSize.xy; vec2 p3 = ( vec2( iuv.x + h1x, iuv.y + h1y ) - 0.5 ) * texelSize.xy; return g0( fuv.y ) * ( g0x * textureLod( tex, p0, lod ) + g1x * textureLod( tex, p1, lod ) ) + g1( fuv.y ) * ( g0x * textureLod( tex, p2, lod ) + g1x * textureLod( tex, p3, lod ) ); } vec4 textureBicubic( sampler2D sampler, vec2 uv, float lod ) { vec2 fLodSize = vec2( textureSize( sampler, int( lod ) ) ); vec2 cLodSize = vec2( textureSize( sampler, int( lod + 1.0 ) ) ); vec2 fLodSizeInv = 1.0 / fLodSize; vec2 cLodSizeInv = 1.0 / cLodSize; vec4 fSample = bicubic( sampler, uv, vec4( fLodSizeInv, fLodSize ), floor( lod ) ); vec4 cSample = bicubic( sampler, uv, vec4( cLodSizeInv, cLodSize ), ceil( lod ) ); return mix( fSample, cSample, fract( lod ) ); } vec3 getVolumeTransmissionRay( const in vec3 n, const in vec3 v, const in float thickness, const in float ior, const in mat4 modelMatrix ) { vec3 refractionVector = refract( - v, normalize( n ), 1.0 / ior ); vec3 modelScale; modelScale.x = length( vec3( modelMatrix[ 0 ].xyz ) ); modelScale.y = length( vec3( modelMatrix[ 1 ].xyz ) ); modelScale.z = length( vec3( modelMatrix[ 2 ].xyz ) ); return normalize( refractionVector ) * thickness * modelScale; } float applyIorToRoughness( const in float roughness, const in float ior ) { return roughness * clamp( ior * 2.0 - 2.0, 0.0, 1.0 ); } vec4 getTransmissionSample( const in vec2 fragCoord, const in float roughness, const in float ior ) { float lod = log2( transmissionSamplerSize.x ) * applyIorToRoughness( roughness, ior ); return textureBicubic( transmissionSamplerMap, fragCoord.xy, lod ); } vec3 volumeAttenuation( const in float transmissionDistance, const in vec3 attenuationColor, const in float attenuationDistance ) { if ( isinf( attenuationDistance ) ) { return vec3( 1.0 ); } else { vec3 attenuationCoefficient = -log( attenuationColor ) / attenuationDistance; vec3 transmittance = exp( - attenuationCoefficient * transmissionDistance ); return transmittance; } } vec4 getIBLVolumeRefraction( const in vec3 n, const in vec3 v, const in float roughness, const in vec3 diffuseColor, const in vec3 specularColor, const in float specularF90, const in vec3 position, const in mat4 modelMatrix, const in mat4 viewMatrix, const in mat4 projMatrix, const in float dispersion, const in float ior, const in float thickness, const in vec3 attenuationColor, const in float attenuationDistance ) { vec4 transmittedLight; vec3 transmittance; #ifdef USE_DISPERSION float halfSpread = ( ior - 1.0 ) * 0.025 * dispersion; vec3 iors = vec3( ior - halfSpread, ior, ior + halfSpread ); for ( int i = 0; i < 3; i ++ ) { vec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, iors[ i ], modelMatrix ); vec3 refractedRayExit = position + transmissionRay; vec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 ); vec2 refractionCoords = ndcPos.xy / ndcPos.w; refractionCoords += 1.0; refractionCoords /= 2.0; vec4 transmissionSample = getTransmissionSample( refractionCoords, roughness, iors[ i ] ); transmittedLight[ i ] = transmissionSample[ i ]; transmittedLight.a += transmissionSample.a; transmittance[ i ] = diffuseColor[ i ] * volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance )[ i ]; } transmittedLight.a /= 3.0; #else vec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix ); vec3 refractedRayExit = position + transmissionRay; vec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 ); vec2 refractionCoords = ndcPos.xy / ndcPos.w; refractionCoords += 1.0; refractionCoords /= 2.0; transmittedLight = getTransmissionSample( refractionCoords, roughness, ior ); transmittance = diffuseColor * volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ); #endif vec3 attenuatedColor = transmittance * transmittedLight.rgb; vec3 F = EnvironmentBRDF( n, v, specularColor, specularF90, roughness ); float transmittanceFactor = ( transmittance.r + transmittance.g + transmittance.b ) / 3.0; return vec4( ( 1.0 - F ) * attenuatedColor, 1.0 - ( 1.0 - transmittedLight.a ) * transmittanceFactor ); } #endif`,DP=`#if defined( USE_UV ) || defined( USE_ANISOTROPY ) varying vec2 vUv; #endif #ifdef USE_MAP varying vec2 vMapUv; #endif #ifdef USE_ALPHAMAP varying vec2 vAlphaMapUv; #endif #ifdef USE_LIGHTMAP varying vec2 vLightMapUv; #endif #ifdef USE_AOMAP varying vec2 vAoMapUv; #endif #ifdef USE_BUMPMAP varying vec2 vBumpMapUv; #endif #ifdef USE_NORMALMAP varying vec2 vNormalMapUv; #endif #ifdef USE_EMISSIVEMAP varying vec2 vEmissiveMapUv; #endif #ifdef USE_METALNESSMAP varying vec2 vMetalnessMapUv; #endif #ifdef USE_ROUGHNESSMAP varying vec2 vRoughnessMapUv; #endif #ifdef USE_ANISOTROPYMAP varying vec2 vAnisotropyMapUv; #endif #ifdef USE_CLEARCOATMAP varying vec2 vClearcoatMapUv; #endif #ifdef USE_CLEARCOAT_NORMALMAP varying vec2 vClearcoatNormalMapUv; #endif #ifdef USE_CLEARCOAT_ROUGHNESSMAP varying vec2 vClearcoatRoughnessMapUv; #endif #ifdef USE_IRIDESCENCEMAP varying vec2 vIridescenceMapUv; #endif #ifdef USE_IRIDESCENCE_THICKNESSMAP varying vec2 vIridescenceThicknessMapUv; #endif #ifdef USE_SHEEN_COLORMAP varying vec2 vSheenColorMapUv; #endif #ifdef USE_SHEEN_ROUGHNESSMAP varying vec2 vSheenRoughnessMapUv; #endif #ifdef USE_SPECULARMAP varying vec2 vSpecularMapUv; #endif #ifdef USE_SPECULAR_COLORMAP varying vec2 vSpecularColorMapUv; #endif #ifdef USE_SPECULAR_INTENSITYMAP varying vec2 vSpecularIntensityMapUv; #endif #ifdef USE_TRANSMISSIONMAP uniform mat3 transmissionMapTransform; varying vec2 vTransmissionMapUv; #endif #ifdef USE_THICKNESSMAP uniform mat3 thicknessMapTransform; varying vec2 vThicknessMapUv; #endif`,NP=`#if defined( USE_UV ) || defined( USE_ANISOTROPY ) varying vec2 vUv; #endif #ifdef USE_MAP uniform mat3 mapTransform; varying vec2 vMapUv; #endif #ifdef USE_ALPHAMAP uniform mat3 alphaMapTransform; varying vec2 vAlphaMapUv; #endif #ifdef USE_LIGHTMAP uniform mat3 lightMapTransform; varying vec2 vLightMapUv; #endif #ifdef USE_AOMAP uniform mat3 aoMapTransform; varying vec2 vAoMapUv; #endif #ifdef USE_BUMPMAP uniform mat3 bumpMapTransform; varying vec2 vBumpMapUv; #endif #ifdef USE_NORMALMAP uniform mat3 normalMapTransform; varying vec2 vNormalMapUv; #endif #ifdef USE_DISPLACEMENTMAP uniform mat3 displacementMapTransform; varying vec2 vDisplacementMapUv; #endif #ifdef USE_EMISSIVEMAP uniform mat3 emissiveMapTransform; varying vec2 vEmissiveMapUv; #endif #ifdef USE_METALNESSMAP uniform mat3 metalnessMapTransform; varying vec2 vMetalnessMapUv; #endif #ifdef USE_ROUGHNESSMAP uniform mat3 roughnessMapTransform; varying vec2 vRoughnessMapUv; #endif #ifdef USE_ANISOTROPYMAP uniform mat3 anisotropyMapTransform; varying vec2 vAnisotropyMapUv; #endif #ifdef USE_CLEARCOATMAP uniform mat3 clearcoatMapTransform; varying vec2 vClearcoatMapUv; #endif #ifdef USE_CLEARCOAT_NORMALMAP uniform mat3 clearcoatNormalMapTransform; varying vec2 vClearcoatNormalMapUv; #endif #ifdef USE_CLEARCOAT_ROUGHNESSMAP uniform mat3 clearcoatRoughnessMapTransform; varying vec2 vClearcoatRoughnessMapUv; #endif #ifdef USE_SHEEN_COLORMAP uniform mat3 sheenColorMapTransform; varying vec2 vSheenColorMapUv; #endif #ifdef USE_SHEEN_ROUGHNESSMAP uniform mat3 sheenRoughnessMapTransform; varying vec2 vSheenRoughnessMapUv; #endif #ifdef USE_IRIDESCENCEMAP uniform mat3 iridescenceMapTransform; varying vec2 vIridescenceMapUv; #endif #ifdef USE_IRIDESCENCE_THICKNESSMAP uniform mat3 iridescenceThicknessMapTransform; varying vec2 vIridescenceThicknessMapUv; #endif #ifdef USE_SPECULARMAP uniform mat3 specularMapTransform; varying vec2 vSpecularMapUv; #endif #ifdef USE_SPECULAR_COLORMAP uniform mat3 specularColorMapTransform; varying vec2 vSpecularColorMapUv; #endif #ifdef USE_SPECULAR_INTENSITYMAP uniform mat3 specularIntensityMapTransform; varying vec2 vSpecularIntensityMapUv; #endif #ifdef USE_TRANSMISSIONMAP uniform mat3 transmissionMapTransform; varying vec2 vTransmissionMapUv; #endif #ifdef USE_THICKNESSMAP uniform mat3 thicknessMapTransform; varying vec2 vThicknessMapUv; #endif`,kP=`#if defined( USE_UV ) || defined( USE_ANISOTROPY ) vUv = vec3( uv, 1 ).xy; #endif #ifdef USE_MAP vMapUv = ( mapTransform * vec3( MAP_UV, 1 ) ).xy; #endif #ifdef USE_ALPHAMAP vAlphaMapUv = ( alphaMapTransform * vec3( ALPHAMAP_UV, 1 ) ).xy; #endif #ifdef USE_LIGHTMAP vLightMapUv = ( lightMapTransform * vec3( LIGHTMAP_UV, 1 ) ).xy; #endif #ifdef USE_AOMAP vAoMapUv = ( aoMapTransform * vec3( AOMAP_UV, 1 ) ).xy; #endif #ifdef USE_BUMPMAP vBumpMapUv = ( bumpMapTransform * vec3( BUMPMAP_UV, 1 ) ).xy; #endif #ifdef USE_NORMALMAP vNormalMapUv = ( normalMapTransform * vec3( NORMALMAP_UV, 1 ) ).xy; #endif #ifdef USE_DISPLACEMENTMAP vDisplacementMapUv = ( displacementMapTransform * vec3( DISPLACEMENTMAP_UV, 1 ) ).xy; #endif #ifdef USE_EMISSIVEMAP vEmissiveMapUv = ( emissiveMapTransform * vec3( EMISSIVEMAP_UV, 1 ) ).xy; #endif #ifdef USE_METALNESSMAP vMetalnessMapUv = ( metalnessMapTransform * vec3( METALNESSMAP_UV, 1 ) ).xy; #endif #ifdef USE_ROUGHNESSMAP vRoughnessMapUv = ( roughnessMapTransform * vec3( ROUGHNESSMAP_UV, 1 ) ).xy; #endif #ifdef USE_ANISOTROPYMAP vAnisotropyMapUv = ( anisotropyMapTransform * vec3( ANISOTROPYMAP_UV, 1 ) ).xy; #endif #ifdef USE_CLEARCOATMAP vClearcoatMapUv = ( clearcoatMapTransform * vec3( CLEARCOATMAP_UV, 1 ) ).xy; #endif #ifdef USE_CLEARCOAT_NORMALMAP vClearcoatNormalMapUv = ( clearcoatNormalMapTransform * vec3( CLEARCOAT_NORMALMAP_UV, 1 ) ).xy; #endif #ifdef USE_CLEARCOAT_ROUGHNESSMAP vClearcoatRoughnessMapUv = ( clearcoatRoughnessMapTransform * vec3( CLEARCOAT_ROUGHNESSMAP_UV, 1 ) ).xy; #endif #ifdef USE_IRIDESCENCEMAP vIridescenceMapUv = ( iridescenceMapTransform * vec3( IRIDESCENCEMAP_UV, 1 ) ).xy; #endif #ifdef USE_IRIDESCENCE_THICKNESSMAP vIridescenceThicknessMapUv = ( iridescenceThicknessMapTransform * vec3( IRIDESCENCE_THICKNESSMAP_UV, 1 ) ).xy; #endif #ifdef USE_SHEEN_COLORMAP vSheenColorMapUv = ( sheenColorMapTransform * vec3( SHEEN_COLORMAP_UV, 1 ) ).xy; #endif #ifdef USE_SHEEN_ROUGHNESSMAP vSheenRoughnessMapUv = ( sheenRoughnessMapTransform * vec3( SHEEN_ROUGHNESSMAP_UV, 1 ) ).xy; #endif #ifdef USE_SPECULARMAP vSpecularMapUv = ( specularMapTransform * vec3( SPECULARMAP_UV, 1 ) ).xy; #endif #ifdef USE_SPECULAR_COLORMAP vSpecularColorMapUv = ( specularColorMapTransform * vec3( SPECULAR_COLORMAP_UV, 1 ) ).xy; #endif #ifdef USE_SPECULAR_INTENSITYMAP vSpecularIntensityMapUv = ( specularIntensityMapTransform * vec3( SPECULAR_INTENSITYMAP_UV, 1 ) ).xy; #endif #ifdef USE_TRANSMISSIONMAP vTransmissionMapUv = ( transmissionMapTransform * vec3( TRANSMISSIONMAP_UV, 1 ) ).xy; #endif #ifdef USE_THICKNESSMAP vThicknessMapUv = ( thicknessMapTransform * vec3( THICKNESSMAP_UV, 1 ) ).xy; #endif`,OP=`#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP ) || defined ( USE_TRANSMISSION ) || NUM_SPOT_LIGHT_COORDS > 0 vec4 worldPosition = vec4( transformed, 1.0 ); #ifdef USE_BATCHING worldPosition = batchingMatrix * worldPosition; #endif #ifdef USE_INSTANCING worldPosition = instanceMatrix * worldPosition; #endif worldPosition = modelMatrix * worldPosition; #endif`;const bt={alphahash_fragment:BC,alphahash_pars_fragment:FC,alphamap_fragment:zC,alphamap_pars_fragment:HC,alphatest_fragment:VC,alphatest_pars_fragment:GC,aomap_fragment:WC,aomap_pars_fragment:XC,batching_pars_vertex:jC,batching_vertex:qC,begin_vertex:ZC,beginnormal_vertex:YC,bsdfs:$C,iridescence_fragment:KC,bumpmap_pars_fragment:JC,clipping_planes_fragment:QC,clipping_planes_pars_fragment:eA,clipping_planes_pars_vertex:tA,clipping_planes_vertex:iA,color_fragment:nA,color_pars_fragment:sA,color_pars_vertex:rA,color_vertex:aA,common:oA,cube_uv_reflection_fragment:lA,defaultnormal_vertex:cA,displacementmap_pars_vertex:hA,displacementmap_vertex:dA,emissivemap_fragment:uA,emissivemap_pars_fragment:pA,colorspace_fragment:fA,colorspace_pars_fragment:mA,envmap_fragment:gA,envmap_common_pars_fragment:vA,envmap_pars_fragment:yA,envmap_pars_vertex:xA,envmap_physical_pars_fragment:RA,envmap_vertex:_A,fog_vertex:bA,fog_pars_vertex:MA,fog_fragment:SA,fog_pars_fragment:wA,gradientmap_pars_fragment:EA,lightmap_pars_fragment:TA,lights_lambert_fragment:CA,lights_lambert_pars_fragment:AA,lights_pars_begin:PA,lights_toon_fragment:IA,lights_toon_pars_fragment:LA,lights_phong_fragment:DA,lights_phong_pars_fragment:NA,lights_physical_fragment:kA,lights_physical_pars_fragment:OA,lights_fragment_begin:UA,lights_fragment_maps:BA,lights_fragment_end:FA,logdepthbuf_fragment:zA,logdepthbuf_pars_fragment:HA,logdepthbuf_pars_vertex:VA,logdepthbuf_vertex:GA,map_fragment:WA,map_pars_fragment:XA,map_particle_fragment:jA,map_particle_pars_fragment:qA,metalnessmap_fragment:ZA,metalnessmap_pars_fragment:YA,morphinstance_vertex:$A,morphcolor_vertex:KA,morphnormal_vertex:JA,morphtarget_pars_vertex:QA,morphtarget_vertex:eP,normal_fragment_begin:tP,normal_fragment_maps:iP,normal_pars_fragment:nP,normal_pars_vertex:sP,normal_vertex:rP,normalmap_pars_fragment:aP,clearcoat_normal_fragment_begin:oP,clearcoat_normal_fragment_maps:lP,clearcoat_pars_fragment:cP,iridescence_pars_fragment:hP,opaque_fragment:dP,packing:uP,premultiplied_alpha_fragment:pP,project_vertex:fP,dithering_fragment:mP,dithering_pars_fragment:gP,roughnessmap_fragment:vP,roughnessmap_pars_fragment:yP,shadowmap_pars_fragment:xP,shadowmap_pars_vertex:_P,shadowmap_vertex:bP,shadowmask_pars_fragment:MP,skinbase_vertex:SP,skinning_pars_vertex:wP,skinning_vertex:EP,skinnormal_vertex:TP,specularmap_fragment:CP,specularmap_pars_fragment:AP,tonemapping_fragment:PP,tonemapping_pars_fragment:RP,transmission_fragment:IP,transmission_pars_fragment:LP,uv_pars_fragment:DP,uv_pars_vertex:NP,uv_vertex:kP,worldpos_vertex:OP,background_vert:`varying vec2 vUv; uniform mat3 uvTransform; void main() { vUv = ( uvTransform * vec3( uv, 1 ) ).xy; gl_Position = vec4( position.xy, 1.0, 1.0 ); }`,background_frag:`uniform sampler2D t2D; uniform float backgroundIntensity; varying vec2 vUv; void main() { vec4 texColor = texture2D( t2D, vUv ); #ifdef DECODE_VIDEO_TEXTURE texColor = vec4( mix( pow( texColor.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), texColor.rgb * 0.0773993808, vec3( lessThanEqual( texColor.rgb, vec3( 0.04045 ) ) ) ), texColor.w ); #endif texColor.rgb *= backgroundIntensity; gl_FragColor = texColor; #include #include }`,backgroundCube_vert:`varying vec3 vWorldDirection; #include void main() { vWorldDirection = transformDirection( position, modelMatrix ); #include #include gl_Position.z = gl_Position.w; }`,backgroundCube_frag:`#ifdef ENVMAP_TYPE_CUBE uniform samplerCube envMap; #elif defined( ENVMAP_TYPE_CUBE_UV ) uniform sampler2D envMap; #endif uniform float flipEnvMap; uniform float backgroundBlurriness; uniform float backgroundIntensity; uniform mat3 backgroundRotation; varying vec3 vWorldDirection; #include void main() { #ifdef ENVMAP_TYPE_CUBE vec4 texColor = textureCube( envMap, backgroundRotation * vec3( flipEnvMap * vWorldDirection.x, vWorldDirection.yz ) ); #elif defined( ENVMAP_TYPE_CUBE_UV ) vec4 texColor = textureCubeUV( envMap, backgroundRotation * vWorldDirection, backgroundBlurriness ); #else vec4 texColor = vec4( 0.0, 0.0, 0.0, 1.0 ); #endif texColor.rgb *= backgroundIntensity; gl_FragColor = texColor; #include #include }`,cube_vert:`varying vec3 vWorldDirection; #include void main() { vWorldDirection = transformDirection( position, modelMatrix ); #include #include gl_Position.z = gl_Position.w; }`,cube_frag:`uniform samplerCube tCube; uniform float tFlip; uniform float opacity; varying vec3 vWorldDirection; void main() { vec4 texColor = textureCube( tCube, vec3( tFlip * vWorldDirection.x, vWorldDirection.yz ) ); gl_FragColor = texColor; gl_FragColor.a *= opacity; #include #include }`,depth_vert:`#include #include #include #include #include #include #include #include varying vec2 vHighPrecisionZW; void main() { #include #include #include #include #ifdef USE_DISPLACEMENTMAP #include #include #include #endif #include #include #include #include #include #include #include vHighPrecisionZW = gl_Position.zw; }`,depth_frag:`#if DEPTH_PACKING == 3200 uniform float opacity; #endif #include #include #include #include #include #include #include #include #include varying vec2 vHighPrecisionZW; void main() { vec4 diffuseColor = vec4( 1.0 ); #include #if DEPTH_PACKING == 3200 diffuseColor.a = opacity; #endif #include #include #include #include #include #ifdef USE_REVERSED_DEPTH_BUFFER float fragCoordZ = vHighPrecisionZW[ 0 ] / vHighPrecisionZW[ 1 ]; #else float fragCoordZ = 0.5 * vHighPrecisionZW[ 0 ] / vHighPrecisionZW[ 1 ] + 0.5; #endif #if DEPTH_PACKING == 3200 gl_FragColor = vec4( vec3( 1.0 - fragCoordZ ), opacity ); #elif DEPTH_PACKING == 3201 gl_FragColor = packDepthToRGBA( fragCoordZ ); #elif DEPTH_PACKING == 3202 gl_FragColor = vec4( packDepthToRGB( fragCoordZ ), 1.0 ); #elif DEPTH_PACKING == 3203 gl_FragColor = vec4( packDepthToRG( fragCoordZ ), 0.0, 1.0 ); #endif }`,distance_vert:`#define DISTANCE varying vec3 vWorldPosition; #include #include #include #include #include #include #include void main() { #include #include #include #include #ifdef USE_DISPLACEMENTMAP #include #include #include #endif #include #include #include #include #include #include #include vWorldPosition = worldPosition.xyz; }`,distance_frag:`#define DISTANCE uniform vec3 referencePosition; uniform float nearDistance; uniform float farDistance; varying vec3 vWorldPosition; #include #include #include #include #include #include #include void main () { vec4 diffuseColor = vec4( 1.0 ); #include #include #include #include #include float dist = length( vWorldPosition - referencePosition ); dist = ( dist - nearDistance ) / ( farDistance - nearDistance ); dist = saturate( dist ); gl_FragColor = vec4( dist, 0.0, 0.0, 1.0 ); }`,equirect_vert:`varying vec3 vWorldDirection; #include void main() { vWorldDirection = transformDirection( position, modelMatrix ); #include #include }`,equirect_frag:`uniform sampler2D tEquirect; varying vec3 vWorldDirection; #include void main() { vec3 direction = normalize( vWorldDirection ); vec2 sampleUV = equirectUv( direction ); gl_FragColor = texture2D( tEquirect, sampleUV ); #include #include }`,linedashed_vert:`uniform float scale; attribute float lineDistance; varying float vLineDistance; #include #include #include #include #include #include #include void main() { vLineDistance = scale * lineDistance; #include #include #include #include #include #include #include #include #include #include }`,linedashed_frag:`uniform vec3 diffuse; uniform float opacity; uniform float dashSize; uniform float totalSize; varying float vLineDistance; #include #include #include #include #include #include #include void main() { vec4 diffuseColor = vec4( diffuse, opacity ); #include if ( mod( vLineDistance, totalSize ) > dashSize ) { discard; } vec3 outgoingLight = vec3( 0.0 ); #include #include #include outgoingLight = diffuseColor.rgb; #include #include #include #include #include }`,meshbasic_vert:`#include #include #include #include #include #include #include #include #include #include void main() { #include #include #include #include #include #if defined ( USE_ENVMAP ) || defined ( USE_SKINNING ) #include #include #include #include #include #endif #include #include #include #include #include #include #include #include #include }`,meshbasic_frag:`uniform vec3 diffuse; uniform float opacity; #ifndef FLAT_SHADED varying vec3 vNormal; #endif #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include void main() { vec4 diffuseColor = vec4( diffuse, opacity ); #include #include #include #include #include #include #include #include ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); #ifdef USE_LIGHTMAP vec4 lightMapTexel = texture2D( lightMap, vLightMapUv ); reflectedLight.indirectDiffuse += lightMapTexel.rgb * lightMapIntensity * RECIPROCAL_PI; #else reflectedLight.indirectDiffuse += vec3( 1.0 ); #endif #include reflectedLight.indirectDiffuse *= diffuseColor.rgb; vec3 outgoingLight = reflectedLight.indirectDiffuse; #include #include #include #include #include #include #include }`,meshlambert_vert:`#define LAMBERT varying vec3 vViewPosition; #include #include #include #include #include #include #include #include #include #include #include #include #include void main() { #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include vViewPosition = - mvPosition.xyz; #include #include #include #include }`,meshlambert_frag:`#define LAMBERT uniform vec3 diffuse; uniform vec3 emissive; uniform float opacity; #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include void main() { vec4 diffuseColor = vec4( diffuse, opacity ); #include ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); vec3 totalEmissiveRadiance = emissive; #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance; #include #include #include #include #include #include #include }`,meshmatcap_vert:`#define MATCAP varying vec3 vViewPosition; #include #include #include #include #include #include #include #include #include #include #include void main() { #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include vViewPosition = - mvPosition.xyz; }`,meshmatcap_frag:`#define MATCAP uniform vec3 diffuse; uniform float opacity; uniform sampler2D matcap; varying vec3 vViewPosition; #include #include #include #include #include #include #include #include #include #include #include #include #include #include void main() { vec4 diffuseColor = vec4( diffuse, opacity ); #include #include #include #include #include #include #include #include #include vec3 viewDir = normalize( vViewPosition ); vec3 x = normalize( vec3( viewDir.z, 0.0, - viewDir.x ) ); vec3 y = cross( viewDir, x ); vec2 uv = vec2( dot( x, normal ), dot( y, normal ) ) * 0.495 + 0.5; #ifdef USE_MATCAP vec4 matcapColor = texture2D( matcap, uv ); #else vec4 matcapColor = vec4( vec3( mix( 0.2, 0.8, uv.y ) ), 1.0 ); #endif vec3 outgoingLight = diffuseColor.rgb * matcapColor.rgb; #include #include #include #include #include #include }`,meshnormal_vert:`#define NORMAL #if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE ) varying vec3 vViewPosition; #endif #include #include #include #include #include #include #include #include #include void main() { #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE ) vViewPosition = - mvPosition.xyz; #endif }`,meshnormal_frag:`#define NORMAL uniform float opacity; #if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE ) varying vec3 vViewPosition; #endif #include #include #include #include #include #include void main() { vec4 diffuseColor = vec4( 0.0, 0.0, 0.0, opacity ); #include #include #include #include gl_FragColor = vec4( normalize( normal ) * 0.5 + 0.5, diffuseColor.a ); #ifdef OPAQUE gl_FragColor.a = 1.0; #endif }`,meshphong_vert:`#define PHONG varying vec3 vViewPosition; #include #include #include #include #include #include #include #include #include #include #include #include #include void main() { #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include vViewPosition = - mvPosition.xyz; #include #include #include #include }`,meshphong_frag:`#define PHONG uniform vec3 diffuse; uniform vec3 emissive; uniform vec3 specular; uniform float shininess; uniform float opacity; #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include void main() { vec4 diffuseColor = vec4( diffuse, opacity ); #include ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); vec3 totalEmissiveRadiance = emissive; #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance; #include #include #include #include #include #include #include }`,meshphysical_vert:`#define STANDARD varying vec3 vViewPosition; #ifdef USE_TRANSMISSION varying vec3 vWorldPosition; #endif #include #include #include #include #include #include #include #include #include #include #include #include void main() { #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include vViewPosition = - mvPosition.xyz; #include #include #include #ifdef USE_TRANSMISSION vWorldPosition = worldPosition.xyz; #endif }`,meshphysical_frag:`#define STANDARD #ifdef PHYSICAL #define IOR #define USE_SPECULAR #endif uniform vec3 diffuse; uniform vec3 emissive; uniform float roughness; uniform float metalness; uniform float opacity; #ifdef IOR uniform float ior; #endif #ifdef USE_SPECULAR uniform float specularIntensity; uniform vec3 specularColor; #ifdef USE_SPECULAR_COLORMAP uniform sampler2D specularColorMap; #endif #ifdef USE_SPECULAR_INTENSITYMAP uniform sampler2D specularIntensityMap; #endif #endif #ifdef USE_CLEARCOAT uniform float clearcoat; uniform float clearcoatRoughness; #endif #ifdef USE_DISPERSION uniform float dispersion; #endif #ifdef USE_IRIDESCENCE uniform float iridescence; uniform float iridescenceIOR; uniform float iridescenceThicknessMinimum; uniform float iridescenceThicknessMaximum; #endif #ifdef USE_SHEEN uniform vec3 sheenColor; uniform float sheenRoughness; #ifdef USE_SHEEN_COLORMAP uniform sampler2D sheenColorMap; #endif #ifdef USE_SHEEN_ROUGHNESSMAP uniform sampler2D sheenRoughnessMap; #endif #endif #ifdef USE_ANISOTROPY uniform vec2 anisotropyVector; #ifdef USE_ANISOTROPYMAP uniform sampler2D anisotropyMap; #endif #endif varying vec3 vViewPosition; #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include void main() { vec4 diffuseColor = vec4( diffuse, opacity ); #include ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); vec3 totalEmissiveRadiance = emissive; #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include vec3 totalDiffuse = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse; vec3 totalSpecular = reflectedLight.directSpecular + reflectedLight.indirectSpecular; #include vec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance; #ifdef USE_SHEEN outgoingLight = outgoingLight + sheenSpecularDirect + sheenSpecularIndirect; #endif #ifdef USE_CLEARCOAT float dotNVcc = saturate( dot( geometryClearcoatNormal, geometryViewDir ) ); vec3 Fcc = F_Schlick( material.clearcoatF0, material.clearcoatF90, dotNVcc ); outgoingLight = outgoingLight * ( 1.0 - material.clearcoat * Fcc ) + ( clearcoatSpecularDirect + clearcoatSpecularIndirect ) * material.clearcoat; #endif #include #include #include #include #include #include }`,meshtoon_vert:`#define TOON varying vec3 vViewPosition; #include #include #include #include #include #include #include #include #include #include #include #include void main() { #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include vViewPosition = - mvPosition.xyz; #include #include #include }`,meshtoon_frag:`#define TOON uniform vec3 diffuse; uniform vec3 emissive; uniform float opacity; #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include void main() { vec4 diffuseColor = vec4( diffuse, opacity ); #include ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); vec3 totalEmissiveRadiance = emissive; #include #include #include #include #include #include #include #include #include #include #include #include #include #include vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance; #include #include #include #include #include #include }`,points_vert:`uniform float size; uniform float scale; #include #include #include #include #include #include #ifdef USE_POINTS_UV varying vec2 vUv; uniform mat3 uvTransform; #endif void main() { #ifdef USE_POINTS_UV vUv = ( uvTransform * vec3( uv, 1 ) ).xy; #endif #include #include #include #include #include #include gl_PointSize = size; #ifdef USE_SIZEATTENUATION bool isPerspective = isPerspectiveMatrix( projectionMatrix ); if ( isPerspective ) gl_PointSize *= ( scale / - mvPosition.z ); #endif #include #include #include #include }`,points_frag:`uniform vec3 diffuse; uniform float opacity; #include #include #include #include #include #include #include #include void main() { vec4 diffuseColor = vec4( diffuse, opacity ); #include vec3 outgoingLight = vec3( 0.0 ); #include #include #include #include #include outgoingLight = diffuseColor.rgb; #include #include #include #include #include }`,shadow_vert:`#include #include #include #include #include #include #include void main() { #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include }`,shadow_frag:`uniform vec3 color; uniform float opacity; #include #include #include #include #include #include #include void main() { #include gl_FragColor = vec4( color, opacity * ( 1.0 - getShadowMask() ) ); #include #include #include #include }`,sprite_vert:`uniform float rotation; uniform vec2 center; #include #include #include #include #include void main() { #include vec4 mvPosition = modelViewMatrix[ 3 ]; vec2 scale = vec2( length( modelMatrix[ 0 ].xyz ), length( modelMatrix[ 1 ].xyz ) ); #ifndef USE_SIZEATTENUATION bool isPerspective = isPerspectiveMatrix( projectionMatrix ); if ( isPerspective ) scale *= - mvPosition.z; #endif vec2 alignedPosition = ( position.xy - ( center - vec2( 0.5 ) ) ) * scale; vec2 rotatedPosition; rotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y; rotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y; mvPosition.xy += rotatedPosition; gl_Position = projectionMatrix * mvPosition; #include #include #include }`,sprite_frag:`uniform vec3 diffuse; uniform float opacity; #include #include #include #include #include #include #include #include #include void main() { vec4 diffuseColor = vec4( diffuse, opacity ); #include vec3 outgoingLight = vec3( 0.0 ); #include #include #include #include #include outgoingLight = diffuseColor.rgb; #include #include #include #include }`},$e={common:{diffuse:{value:new We(16777215)},opacity:{value:1},map:{value:null},mapTransform:{value:new ft},alphaMap:{value:null},alphaMapTransform:{value:new ft},alphaTest:{value:0}},specularmap:{specularMap:{value:null},specularMapTransform:{value:new ft}},envmap:{envMap:{value:null},envMapRotation:{value:new ft},flipEnvMap:{value:-1},reflectivity:{value:1},ior:{value:1.5},refractionRatio:{value:.98},dfgLUT:{value:null}},aomap:{aoMap:{value:null},aoMapIntensity:{value:1},aoMapTransform:{value:new ft}},lightmap:{lightMap:{value:null},lightMapIntensity:{value:1},lightMapTransform:{value:new ft}},bumpmap:{bumpMap:{value:null},bumpMapTransform:{value:new ft},bumpScale:{value:1}},normalmap:{normalMap:{value:null},normalMapTransform:{value:new ft},normalScale:{value:new me(1,1)}},displacementmap:{displacementMap:{value:null},displacementMapTransform:{value:new ft},displacementScale:{value:1},displacementBias:{value:0}},emissivemap:{emissiveMap:{value:null},emissiveMapTransform:{value:new ft}},metalnessmap:{metalnessMap:{value:null},metalnessMapTransform:{value:new ft}},roughnessmap:{roughnessMap:{value:null},roughnessMapTransform:{value:new ft}},gradientmap:{gradientMap:{value:null}},fog:{fogDensity:{value:25e-5},fogNear:{value:1},fogFar:{value:2e3},fogColor:{value:new We(16777215)}},lights:{ambientLightColor:{value:[]},lightProbe:{value:[]},directionalLights:{value:[],properties:{direction:{},color:{}}},directionalLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},directionalShadowMatrix:{value:[]},spotLights:{value:[],properties:{color:{},position:{},direction:{},distance:{},coneCos:{},penumbraCos:{},decay:{}}},spotLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},spotLightMap:{value:[]},spotLightMatrix:{value:[]},pointLights:{value:[],properties:{color:{},position:{},decay:{},distance:{}}},pointLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{},shadowCameraNear:{},shadowCameraFar:{}}},pointShadowMatrix:{value:[]},hemisphereLights:{value:[],properties:{direction:{},skyColor:{},groundColor:{}}},rectAreaLights:{value:[],properties:{color:{},position:{},width:{},height:{}}},ltc_1:{value:null},ltc_2:{value:null}},points:{diffuse:{value:new We(16777215)},opacity:{value:1},size:{value:1},scale:{value:1},map:{value:null},alphaMap:{value:null},alphaMapTransform:{value:new ft},alphaTest:{value:0},uvTransform:{value:new ft}},sprite:{diffuse:{value:new We(16777215)},opacity:{value:1},center:{value:new me(.5,.5)},rotation:{value:0},map:{value:null},mapTransform:{value:new ft},alphaMap:{value:null},alphaMapTransform:{value:new ft},alphaTest:{value:0}}},ys={basic:{uniforms:fn([$e.common,$e.specularmap,$e.envmap,$e.aomap,$e.lightmap,$e.fog]),vertexShader:bt.meshbasic_vert,fragmentShader:bt.meshbasic_frag},lambert:{uniforms:fn([$e.common,$e.specularmap,$e.envmap,$e.aomap,$e.lightmap,$e.emissivemap,$e.bumpmap,$e.normalmap,$e.displacementmap,$e.fog,$e.lights,{emissive:{value:new We(0)},envMapIntensity:{value:1}}]),vertexShader:bt.meshlambert_vert,fragmentShader:bt.meshlambert_frag},phong:{uniforms:fn([$e.common,$e.specularmap,$e.envmap,$e.aomap,$e.lightmap,$e.emissivemap,$e.bumpmap,$e.normalmap,$e.displacementmap,$e.fog,$e.lights,{emissive:{value:new We(0)},specular:{value:new We(1118481)},shininess:{value:30},envMapIntensity:{value:1}}]),vertexShader:bt.meshphong_vert,fragmentShader:bt.meshphong_frag},standard:{uniforms:fn([$e.common,$e.envmap,$e.aomap,$e.lightmap,$e.emissivemap,$e.bumpmap,$e.normalmap,$e.displacementmap,$e.roughnessmap,$e.metalnessmap,$e.fog,$e.lights,{emissive:{value:new We(0)},roughness:{value:1},metalness:{value:0},envMapIntensity:{value:1}}]),vertexShader:bt.meshphysical_vert,fragmentShader:bt.meshphysical_frag},toon:{uniforms:fn([$e.common,$e.aomap,$e.lightmap,$e.emissivemap,$e.bumpmap,$e.normalmap,$e.displacementmap,$e.gradientmap,$e.fog,$e.lights,{emissive:{value:new We(0)}}]),vertexShader:bt.meshtoon_vert,fragmentShader:bt.meshtoon_frag},matcap:{uniforms:fn([$e.common,$e.bumpmap,$e.normalmap,$e.displacementmap,$e.fog,{matcap:{value:null}}]),vertexShader:bt.meshmatcap_vert,fragmentShader:bt.meshmatcap_frag},points:{uniforms:fn([$e.points,$e.fog]),vertexShader:bt.points_vert,fragmentShader:bt.points_frag},dashed:{uniforms:fn([$e.common,$e.fog,{scale:{value:1},dashSize:{value:1},totalSize:{value:2}}]),vertexShader:bt.linedashed_vert,fragmentShader:bt.linedashed_frag},depth:{uniforms:fn([$e.common,$e.displacementmap]),vertexShader:bt.depth_vert,fragmentShader:bt.depth_frag},normal:{uniforms:fn([$e.common,$e.bumpmap,$e.normalmap,$e.displacementmap,{opacity:{value:1}}]),vertexShader:bt.meshnormal_vert,fragmentShader:bt.meshnormal_frag},sprite:{uniforms:fn([$e.sprite,$e.fog]),vertexShader:bt.sprite_vert,fragmentShader:bt.sprite_frag},background:{uniforms:{uvTransform:{value:new ft},t2D:{value:null},backgroundIntensity:{value:1}},vertexShader:bt.background_vert,fragmentShader:bt.background_frag},backgroundCube:{uniforms:{envMap:{value:null},flipEnvMap:{value:-1},backgroundBlurriness:{value:0},backgroundIntensity:{value:1},backgroundRotation:{value:new ft}},vertexShader:bt.backgroundCube_vert,fragmentShader:bt.backgroundCube_frag},cube:{uniforms:{tCube:{value:null},tFlip:{value:-1},opacity:{value:1}},vertexShader:bt.cube_vert,fragmentShader:bt.cube_frag},equirect:{uniforms:{tEquirect:{value:null}},vertexShader:bt.equirect_vert,fragmentShader:bt.equirect_frag},distance:{uniforms:fn([$e.common,$e.displacementmap,{referencePosition:{value:new R},nearDistance:{value:1},farDistance:{value:1e3}}]),vertexShader:bt.distance_vert,fragmentShader:bt.distance_frag},shadow:{uniforms:fn([$e.lights,$e.fog,{color:{value:new We(0)},opacity:{value:1}}]),vertexShader:bt.shadow_vert,fragmentShader:bt.shadow_frag}};ys.physical={uniforms:fn([ys.standard.uniforms,{clearcoat:{value:0},clearcoatMap:{value:null},clearcoatMapTransform:{value:new ft},clearcoatNormalMap:{value:null},clearcoatNormalMapTransform:{value:new ft},clearcoatNormalScale:{value:new me(1,1)},clearcoatRoughness:{value:0},clearcoatRoughnessMap:{value:null},clearcoatRoughnessMapTransform:{value:new ft},dispersion:{value:0},iridescence:{value:0},iridescenceMap:{value:null},iridescenceMapTransform:{value:new ft},iridescenceIOR:{value:1.3},iridescenceThicknessMinimum:{value:100},iridescenceThicknessMaximum:{value:400},iridescenceThicknessMap:{value:null},iridescenceThicknessMapTransform:{value:new ft},sheen:{value:0},sheenColor:{value:new We(0)},sheenColorMap:{value:null},sheenColorMapTransform:{value:new ft},sheenRoughness:{value:1},sheenRoughnessMap:{value:null},sheenRoughnessMapTransform:{value:new ft},transmission:{value:0},transmissionMap:{value:null},transmissionMapTransform:{value:new ft},transmissionSamplerSize:{value:new me},transmissionSamplerMap:{value:null},thickness:{value:0},thicknessMap:{value:null},thicknessMapTransform:{value:new ft},attenuationDistance:{value:0},attenuationColor:{value:new We(0)},specularColor:{value:new We(1,1,1)},specularColorMap:{value:null},specularColorMapTransform:{value:new ft},specularIntensity:{value:1},specularIntensityMap:{value:null},specularIntensityMapTransform:{value:new ft},anisotropyVector:{value:new me},anisotropyMap:{value:null},anisotropyMapTransform:{value:new ft}}]),vertexShader:bt.meshphysical_vert,fragmentShader:bt.meshphysical_frag};const Dp={r:0,b:0,g:0},eo=new Fi,UP=new qe;function BP(s,e,t,i,n,r){const a=new We(0);let o=n===!0?0:1,l,c,h=null,d=0,p=null;function u(y){let x=y.isScene===!0?y.background:null;if(x&&x.isTexture){const _=y.backgroundBlurriness>0;x=e.get(x,_)}return x}function v(y){let x=!1;const _=u(y);_===null?m(a,o):_&&_.isColor&&(m(_,1),x=!0);const S=s.xr.getEnvironmentBlendMode();S==="additive"?t.buffers.color.setClear(0,0,0,1,r):S==="alpha-blend"&&t.buffers.color.setClear(0,0,0,0,r),(s.autoClear||x)&&(t.buffers.depth.setTest(!0),t.buffers.depth.setMask(!0),t.buffers.color.setMask(!0),s.clear(s.autoClearColor,s.autoClearDepth,s.autoClearStencil))}function g(y,x){const _=u(x);_&&(_.isCubeTexture||_.mapping===Go)?(c===void 0&&(c=new ht(new fs(1,1,1),new Jt({name:"BackgroundCubeMaterial",uniforms:gl(ys.backgroundCube.uniforms),vertexShader:ys.backgroundCube.vertexShader,fragmentShader:ys.backgroundCube.fragmentShader,side:Bi,depthTest:!1,depthWrite:!1,fog:!1,allowOverride:!1})),c.geometry.deleteAttribute("normal"),c.geometry.deleteAttribute("uv"),c.onBeforeRender=function(S,b,E){this.matrixWorld.copyPosition(E.matrixWorld)},Object.defineProperty(c.material,"envMap",{get:function(){return this.uniforms.envMap.value}}),i.update(c)),eo.copy(x.backgroundRotation),eo.x*=-1,eo.y*=-1,eo.z*=-1,_.isCubeTexture&&_.isRenderTargetTexture===!1&&(eo.y*=-1,eo.z*=-1),c.material.uniforms.envMap.value=_,c.material.uniforms.flipEnvMap.value=_.isCubeTexture&&_.isRenderTargetTexture===!1?-1:1,c.material.uniforms.backgroundBlurriness.value=x.backgroundBlurriness,c.material.uniforms.backgroundIntensity.value=x.backgroundIntensity,c.material.uniforms.backgroundRotation.value.setFromMatrix4(UP.makeRotationFromEuler(eo)),c.material.toneMapped=Et.getTransfer(_.colorSpace)!==Bt,(h!==_||d!==_.version||p!==s.toneMapping)&&(c.material.needsUpdate=!0,h=_,d=_.version,p=s.toneMapping),c.layers.enableAll(),y.unshift(c,c.geometry,c.material,0,0,null)):_&&_.isTexture&&(l===void 0&&(l=new ht(new vs(2,2),new Jt({name:"BackgroundMaterial",uniforms:gl(ys.background.uniforms),vertexShader:ys.background.vertexShader,fragmentShader:ys.background.fragmentShader,side:_n,depthTest:!1,depthWrite:!1,fog:!1,allowOverride:!1})),l.geometry.deleteAttribute("normal"),Object.defineProperty(l.material,"map",{get:function(){return this.uniforms.t2D.value}}),i.update(l)),l.material.uniforms.t2D.value=_,l.material.uniforms.backgroundIntensity.value=x.backgroundIntensity,l.material.toneMapped=Et.getTransfer(_.colorSpace)!==Bt,_.matrixAutoUpdate===!0&&_.updateMatrix(),l.material.uniforms.uvTransform.value.copy(_.matrix),(h!==_||d!==_.version||p!==s.toneMapping)&&(l.material.needsUpdate=!0,h=_,d=_.version,p=s.toneMapping),l.layers.enableAll(),y.unshift(l,l.geometry,l.material,0,0,null))}function m(y,x){y.getRGB(Dp,a_(s)),t.buffers.color.setClear(Dp.r,Dp.g,Dp.b,x,r)}function f(){c!==void 0&&(c.geometry.dispose(),c.material.dispose(),c=void 0),l!==void 0&&(l.geometry.dispose(),l.material.dispose(),l=void 0)}return{getClearColor:function(){return a},setClearColor:function(y,x=1){a.set(y),o=x,m(a,o)},getClearAlpha:function(){return o},setClearAlpha:function(y){o=y,m(a,o)},render:v,addToRenderList:g,dispose:f}}function FP(s,e){const t=s.getParameter(s.MAX_VERTEX_ATTRIBS),i={},n=p(null);let r=n,a=!1;function o(I,P,k,A,B){let F=!1;const H=d(I,A,k,P);r!==H&&(r=H,c(r.object)),F=u(I,A,k,B),F&&v(I,A,k,B),B!==null&&e.update(B,s.ELEMENT_ARRAY_BUFFER),(F||a)&&(a=!1,_(I,P,k,A),B!==null&&s.bindBuffer(s.ELEMENT_ARRAY_BUFFER,e.get(B).buffer))}function l(){return s.createVertexArray()}function c(I){return s.bindVertexArray(I)}function h(I){return s.deleteVertexArray(I)}function d(I,P,k,A){const B=A.wireframe===!0;let F=i[P.id];F===void 0&&(F={},i[P.id]=F);const H=I.isInstancedMesh===!0?I.id:0;let q=F[H];q===void 0&&(q={},F[H]=q);let G=q[k.id];G===void 0&&(G={},q[k.id]=G);let re=G[B];return re===void 0&&(re=p(l()),G[B]=re),re}function p(I){const P=[],k=[],A=[];for(let B=0;B=0){const Y=B[G];let $=F[G];if($===void 0&&(G==="instanceMatrix"&&I.instanceMatrix&&($=I.instanceMatrix),G==="instanceColor"&&I.instanceColor&&($=I.instanceColor)),Y===void 0||Y.attribute!==$||$&&Y.data!==$.data)return!0;H++}return r.attributesNum!==H||r.index!==A}function v(I,P,k,A){const B={},F=P.attributes;let H=0;const q=k.getAttributes();for(const G in q)if(q[G].location>=0){let Y=F[G];Y===void 0&&(G==="instanceMatrix"&&I.instanceMatrix&&(Y=I.instanceMatrix),G==="instanceColor"&&I.instanceColor&&(Y=I.instanceColor));const $={};$.attribute=Y,Y&&Y.data&&($.data=Y.data),B[G]=$,H++}r.attributes=B,r.attributesNum=H,r.index=A}function g(){const I=r.newAttributes;for(let P=0,k=I.length;P=0){let re=B[q];if(re===void 0&&(q==="instanceMatrix"&&I.instanceMatrix&&(re=I.instanceMatrix),q==="instanceColor"&&I.instanceColor&&(re=I.instanceColor)),re!==void 0){const Y=re.normalized,$=re.itemSize,_e=e.get(re);if(_e===void 0)continue;const Te=_e.buffer,be=_e.type,J=_e.bytesPerElement,oe=be===s.INT||be===s.UNSIGNED_INT||re.gpuType===Td;if(re.isInterleavedBufferAttribute){const ue=re.data,Re=ue.stride,Ie=re.offset;if(ue.isInstancedInterleavedBuffer){for(let Ue=0;Ue0&&s.getShaderPrecisionFormat(s.FRAGMENT_SHADER,s.HIGH_FLOAT).precision>0)return"highp";E="mediump"}return E==="mediump"&&s.getShaderPrecisionFormat(s.VERTEX_SHADER,s.MEDIUM_FLOAT).precision>0&&s.getShaderPrecisionFormat(s.FRAGMENT_SHADER,s.MEDIUM_FLOAT).precision>0?"mediump":"lowp"}let c=t.precision!==void 0?t.precision:"highp";const h=l(c);h!==c&&(Ye("WebGLRenderer:",c,"not supported, using",h,"instead."),c=h);const d=t.logarithmicDepthBuffer===!0,p=t.reversedDepthBuffer===!0&&e.has("EXT_clip_control"),u=s.getParameter(s.MAX_TEXTURE_IMAGE_UNITS),v=s.getParameter(s.MAX_VERTEX_TEXTURE_IMAGE_UNITS),g=s.getParameter(s.MAX_TEXTURE_SIZE),m=s.getParameter(s.MAX_CUBE_MAP_TEXTURE_SIZE),f=s.getParameter(s.MAX_VERTEX_ATTRIBS),y=s.getParameter(s.MAX_VERTEX_UNIFORM_VECTORS),x=s.getParameter(s.MAX_VARYING_VECTORS),_=s.getParameter(s.MAX_FRAGMENT_UNIFORM_VECTORS),S=s.getParameter(s.MAX_SAMPLES),b=s.getParameter(s.SAMPLES);return{isWebGL2:!0,getMaxAnisotropy:r,getMaxPrecision:l,textureFormatReadable:a,textureTypeReadable:o,precision:c,logarithmicDepthBuffer:d,reversedDepthBuffer:p,maxTextures:u,maxVertexTextures:v,maxTextureSize:g,maxCubemapSize:m,maxAttributes:f,maxVertexUniforms:y,maxVaryings:x,maxFragmentUniforms:_,maxSamples:S,samples:b}}function VP(s){const e=this;let t=null,i=0,n=!1,r=!1;const a=new Yt,o=new ft,l={value:null,needsUpdate:!1};this.uniform=l,this.numPlanes=0,this.numIntersection=0,this.init=function(d,p){const u=d.length!==0||p||i!==0||n;return n=p,i=d.length,u},this.beginShadows=function(){r=!0,h(null)},this.endShadows=function(){r=!1},this.setGlobalState=function(d,p){t=h(d,p,0)},this.setState=function(d,p,u){const v=d.clippingPlanes,g=d.clipIntersection,m=d.clipShadows,f=s.get(d);if(!n||v===null||v.length===0||r&&!m)r?h(null):c();else{const y=r?0:i,x=y*4;let _=f.clippingState||null;l.value=_,_=h(v,p,x,u);for(let S=0;S!==x;++S)_[S]=t[S];f.clippingState=_,this.numIntersection=g?this.numPlanes:0,this.numPlanes+=y}};function c(){l.value!==t&&(l.value=t,l.needsUpdate=i>0),e.numPlanes=i,e.numIntersection=0}function h(d,p,u,v){const g=d!==null?d.length:0;let m=null;if(g!==0){if(m=l.value,v!==!0||m===null){const f=u+g*4,y=p.matrixWorldInverse;o.getNormalMatrix(y),(m===null||m.length0&&this._blur(l,0,0,t),this._applyPMREM(l),this._cleanup(l),l}fromEquirectangular(e,t=null){return this._fromTexture(e,t)}fromCubemap(e,t=null){return this._fromTexture(e,t)}compileCubemapShader(){this._cubemapMaterial===null&&(this._cubemapMaterial=sb(),this._compileMaterial(this._cubemapMaterial))}compileEquirectangularShader(){this._equirectMaterial===null&&(this._equirectMaterial=nb(),this._compileMaterial(this._equirectMaterial))}dispose(){this._dispose(),this._cubemapMaterial!==null&&this._cubemapMaterial.dispose(),this._equirectMaterial!==null&&this._equirectMaterial.dispose(),this._backgroundBox!==null&&(this._backgroundBox.geometry.dispose(),this._backgroundBox.material.dispose())}_setSize(e){this._lodMax=Math.floor(Math.log2(e)),this._cubeSize=Math.pow(2,this._lodMax)}_dispose(){this._blurMaterial!==null&&this._blurMaterial.dispose(),this._ggxMaterial!==null&&this._ggxMaterial.dispose(),this._pingPongRenderTarget!==null&&this._pingPongRenderTarget.dispose();for(let e=0;e2?S:0,S,S),d.setRenderTarget(n),f&&d.render(g,l),d.render(e,l)}d.toneMapping=u,d.autoClear=p,e.background=y}_textureToCubeUV(e,t){const i=this._renderer,n=e.mapping===Ls||e.mapping===Lr;n?(this._cubemapMaterial===null&&(this._cubemapMaterial=sb()),this._cubemapMaterial.uniforms.flipEnvMap.value=e.isRenderTargetTexture===!1?-1:1):this._equirectMaterial===null&&(this._equirectMaterial=nb());const r=n?this._cubemapMaterial:this._equirectMaterial,a=this._lodMeshes[0];a.material=r;const o=r.uniforms;o.envMap.value=e;const l=this._cubeSize;El(t,0,0,3*l,2*l),i.setRenderTarget(t),i.render(a,dh)}_applyPMREM(e){const t=this._renderer,i=t.autoClear;t.autoClear=!1;const n=this._lodMeshes.length;for(let r=1;rv-Kr?i-v+Kr:0),f=4*(this._cubeSize-g);l.envMap.value=e.texture,l.roughness.value=u,l.mipInt.value=v-t,El(r,m,f,3*g,2*g),n.setRenderTarget(r),n.render(o,dh),l.envMap.value=r.texture,l.roughness.value=0,l.mipInt.value=v-i,El(e,m,f,3*g,2*g),n.setRenderTarget(e),n.render(o,dh)}_blur(e,t,i,n,r){const a=this._pingPongRenderTarget;this._halfBlur(e,a,t,i,n,"latitudinal",r),this._halfBlur(a,e,i,i,n,"longitudinal",r)}_halfBlur(e,t,i,n,r,a,o){const l=this._renderer,c=this._blurMaterial;a!=="latitudinal"&&a!=="longitudinal"&<("blur direction must be either latitudinal or longitudinal!");const h=3,d=this._lodMeshes[n];d.material=c;const p=c.uniforms,u=this._sizeLods[i]-1,v=isFinite(r)?Math.PI/(2*u):2*Math.PI/(2*to-1),g=r/v,m=isFinite(r)?1+Math.floor(h*g):to;m>to&&Ye(`sigmaRadians, ${r}, is too large and will clip, as it requested ${m} samples when the maximum is set to ${to}`);const f=[];let y=0;for(let E=0;Ex-Kr?n-x+Kr:0),b=4*(this._cubeSize-_);El(t,S,b,3*_,2*_),l.setRenderTarget(t),l.render(d,dh)}}function XP(s){const e=[],t=[],i=[];let n=s;const r=s-Kr+1+eb.length;for(let a=0;as-Kr?l=eb[a-s+Kr-1]:a===0&&(l=0),t.push(l);const c=1/(o-2),h=-c,d=1+c,p=[h,h,d,h,d,d,h,h,d,d,h,d],u=6,v=6,g=3,m=2,f=1,y=new Float32Array(g*v*u),x=new Float32Array(m*v*u),_=new Float32Array(f*v*u);for(let b=0;b2?0:-1,M=[E,w,0,E+2/3,w,0,E+2/3,w+1,0,E,w,0,E+2/3,w+1,0,E,w+1,0];y.set(M,g*v*b),x.set(p,m*v*b);const C=[b,b,b,b,b,b];_.set(C,f*v*b)}const S=new at;S.setAttribute("position",new St(y,g)),S.setAttribute("uv",new St(x,m)),S.setAttribute("faceIndex",new St(_,f)),i.push(new ht(S,null)),n>Kr&&n--}return{lodMeshes:i,sizeLods:e,sigmas:t}}function ib(s,e,t){const i=new bi(s,e,t);return i.texture.mapping=Go,i.texture.name="PMREM.cubeUv",i.scissorTest=!0,i}function El(s,e,t,i,n){s.viewport.set(e,t,i,n),s.scissor.set(e,t,i,n)}function jP(s,e,t){return new Jt({name:"PMREMGGXConvolution",defines:{GGX_SAMPLES:GP,CUBEUV_TEXEL_WIDTH:1/e,CUBEUV_TEXEL_HEIGHT:1/t,CUBEUV_MAX_MIP:`${s}.0`},uniforms:{envMap:{value:null},roughness:{value:0},mipInt:{value:0}},vertexShader:Np(),fragmentShader:` precision highp float; precision highp int; varying vec3 vOutputDirection; uniform sampler2D envMap; uniform float roughness; uniform float mipInt; #define ENVMAP_TYPE_CUBE_UV #include #define PI 3.14159265359 // Van der Corput radical inverse float radicalInverse_VdC(uint bits) { bits = (bits << 16u) | (bits >> 16u); bits = ((bits & 0x55555555u) << 1u) | ((bits & 0xAAAAAAAAu) >> 1u); bits = ((bits & 0x33333333u) << 2u) | ((bits & 0xCCCCCCCCu) >> 2u); bits = ((bits & 0x0F0F0F0Fu) << 4u) | ((bits & 0xF0F0F0F0u) >> 4u); bits = ((bits & 0x00FF00FFu) << 8u) | ((bits & 0xFF00FF00u) >> 8u); return float(bits) * 2.3283064365386963e-10; // / 0x100000000 } // Hammersley sequence vec2 hammersley(uint i, uint N) { return vec2(float(i) / float(N), radicalInverse_VdC(i)); } // GGX VNDF importance sampling (Eric Heitz 2018) // "Sampling the GGX Distribution of Visible Normals" // https://jcgt.org/published/0007/04/01/ vec3 importanceSampleGGX_VNDF(vec2 Xi, vec3 V, float roughness) { float alpha = roughness * roughness; // Section 4.1: Orthonormal basis vec3 T1 = vec3(1.0, 0.0, 0.0); vec3 T2 = cross(V, T1); // Section 4.2: Parameterization of projected area float r = sqrt(Xi.x); float phi = 2.0 * PI * Xi.y; float t1 = r * cos(phi); float t2 = r * sin(phi); float s = 0.5 * (1.0 + V.z); t2 = (1.0 - s) * sqrt(1.0 - t1 * t1) + s * t2; // Section 4.3: Reprojection onto hemisphere vec3 Nh = t1 * T1 + t2 * T2 + sqrt(max(0.0, 1.0 - t1 * t1 - t2 * t2)) * V; // Section 3.4: Transform back to ellipsoid configuration return normalize(vec3(alpha * Nh.x, alpha * Nh.y, max(0.0, Nh.z))); } void main() { vec3 N = normalize(vOutputDirection); vec3 V = N; // Assume view direction equals normal for pre-filtering vec3 prefilteredColor = vec3(0.0); float totalWeight = 0.0; // For very low roughness, just sample the environment directly if (roughness < 0.001) { gl_FragColor = vec4(bilinearCubeUV(envMap, N, mipInt), 1.0); return; } // Tangent space basis for VNDF sampling vec3 up = abs(N.z) < 0.999 ? vec3(0.0, 0.0, 1.0) : vec3(1.0, 0.0, 0.0); vec3 tangent = normalize(cross(up, N)); vec3 bitangent = cross(N, tangent); for(uint i = 0u; i < uint(GGX_SAMPLES); i++) { vec2 Xi = hammersley(i, uint(GGX_SAMPLES)); // For PMREM, V = N, so in tangent space V is always (0, 0, 1) vec3 H_tangent = importanceSampleGGX_VNDF(Xi, vec3(0.0, 0.0, 1.0), roughness); // Transform H back to world space vec3 H = normalize(tangent * H_tangent.x + bitangent * H_tangent.y + N * H_tangent.z); vec3 L = normalize(2.0 * dot(V, H) * H - V); float NdotL = max(dot(N, L), 0.0); if(NdotL > 0.0) { // Sample environment at fixed mip level // VNDF importance sampling handles the distribution filtering vec3 sampleColor = bilinearCubeUV(envMap, L, mipInt); // Weight by NdotL for the split-sum approximation // VNDF PDF naturally accounts for the visible microfacet distribution prefilteredColor += sampleColor * NdotL; totalWeight += NdotL; } } if (totalWeight > 0.0) { prefilteredColor = prefilteredColor / totalWeight; } gl_FragColor = vec4(prefilteredColor, 1.0); } `,blending:Qt,depthTest:!1,depthWrite:!1})}function qP(s,e,t){const i=new Float32Array(to),n=new R(0,1,0);return new Jt({name:"SphericalGaussianBlur",defines:{n:to,CUBEUV_TEXEL_WIDTH:1/e,CUBEUV_TEXEL_HEIGHT:1/t,CUBEUV_MAX_MIP:`${s}.0`},uniforms:{envMap:{value:null},samples:{value:1},weights:{value:i},latitudinal:{value:!1},dTheta:{value:0},mipInt:{value:0},poleAxis:{value:n}},vertexShader:Np(),fragmentShader:` precision mediump float; precision mediump int; varying vec3 vOutputDirection; uniform sampler2D envMap; uniform int samples; uniform float weights[ n ]; uniform bool latitudinal; uniform float dTheta; uniform float mipInt; uniform vec3 poleAxis; #define ENVMAP_TYPE_CUBE_UV #include vec3 getSample( float theta, vec3 axis ) { float cosTheta = cos( theta ); // Rodrigues' axis-angle rotation vec3 sampleDirection = vOutputDirection * cosTheta + cross( axis, vOutputDirection ) * sin( theta ) + axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta ); return bilinearCubeUV( envMap, sampleDirection, mipInt ); } void main() { vec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection ); if ( all( equal( axis, vec3( 0.0 ) ) ) ) { axis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x ); } axis = normalize( axis ); gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 ); gl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis ); for ( int i = 1; i < n; i++ ) { if ( i >= samples ) { break; } float theta = dTheta * float( i ); gl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis ); gl_FragColor.rgb += weights[ i ] * getSample( theta, axis ); } } `,blending:Qt,depthTest:!1,depthWrite:!1})}function nb(){return new Jt({name:"EquirectangularToCubeUV",uniforms:{envMap:{value:null}},vertexShader:Np(),fragmentShader:` precision mediump float; precision mediump int; varying vec3 vOutputDirection; uniform sampler2D envMap; #include void main() { vec3 outputDirection = normalize( vOutputDirection ); vec2 uv = equirectUv( outputDirection ); gl_FragColor = vec4( texture2D ( envMap, uv ).rgb, 1.0 ); } `,blending:Qt,depthTest:!1,depthWrite:!1})}function sb(){return new Jt({name:"CubemapToCubeUV",uniforms:{envMap:{value:null},flipEnvMap:{value:-1}},vertexShader:Np(),fragmentShader:` precision mediump float; precision mediump int; uniform float flipEnvMap; varying vec3 vOutputDirection; uniform samplerCube envMap; void main() { gl_FragColor = textureCube( envMap, vec3( flipEnvMap * vOutputDirection.x, vOutputDirection.yz ) ); } `,blending:Qt,depthTest:!1,depthWrite:!1})}function Np(){return` precision mediump float; precision mediump int; attribute float faceIndex; varying vec3 vOutputDirection; // RH coordinate system; PMREM face-indexing convention vec3 getDirection( vec2 uv, float face ) { uv = 2.0 * uv - 1.0; vec3 direction = vec3( uv, 1.0 ); if ( face == 0.0 ) { direction = direction.zyx; // ( 1, v, u ) pos x } else if ( face == 1.0 ) { direction = direction.xzy; direction.xz *= -1.0; // ( -u, 1, -v ) pos y } else if ( face == 2.0 ) { direction.x *= -1.0; // ( -u, v, 1 ) pos z } else if ( face == 3.0 ) { direction = direction.zyx; direction.xz *= -1.0; // ( -1, v, -u ) neg x } else if ( face == 4.0 ) { direction = direction.xzy; direction.xy *= -1.0; // ( -u, -1, v ) neg y } else if ( face == 5.0 ) { direction.z *= -1.0; // ( u, v, -1 ) neg z } return direction; } void main() { vOutputDirection = getDirection( uv, faceIndex ); gl_Position = vec4( position, 1.0 ); } `}class f0 extends bi{constructor(e=1,t={}){super(e,e,t),this.isWebGLCubeRenderTarget=!0;const i={width:e,height:e,depth:1},n=[i,i,i,i,i,i];this.texture=new Kc(n),this._setTextureOptions(t),this.texture.isRenderTargetTexture=!0}fromEquirectangularTexture(e,t){this.texture.type=t.type,this.texture.colorSpace=t.colorSpace,this.texture.generateMipmaps=t.generateMipmaps,this.texture.minFilter=t.minFilter,this.texture.magFilter=t.magFilter;const i={uniforms:{tEquirect:{value:null}},vertexShader:` varying vec3 vWorldDirection; vec3 transformDirection( in vec3 dir, in mat4 matrix ) { return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz ); } void main() { vWorldDirection = transformDirection( position, modelMatrix ); #include #include } `,fragmentShader:` uniform sampler2D tEquirect; varying vec3 vWorldDirection; #include void main() { vec3 direction = normalize( vWorldDirection ); vec2 sampleUV = equirectUv( direction ); gl_FragColor = texture2D( tEquirect, sampleUV ); } `},n=new fs(5,5,5),r=new Jt({name:"CubemapFromEquirect",uniforms:gl(i.uniforms),vertexShader:i.vertexShader,fragmentShader:i.fragmentShader,side:Bi,blending:Qt});r.uniforms.tEquirect.value=t;const a=new ht(n,r),o=t.minFilter;return t.minFilter===qn&&(t.minFilter=At),new D_(1,10,this).update(e,a),t.minFilter=o,a.geometry.dispose(),a.material.dispose(),this}clear(e,t=!0,i=!0,n=!0){const r=e.getRenderTarget();for(let a=0;a<6;a++)e.setRenderTarget(this,a),e.clear(t,i,n);e.setRenderTarget(r)}}function ZP(s){let e=new WeakMap,t=new WeakMap,i=null;function n(p,u=!1){return p==null?null:u?a(p):r(p)}function r(p){if(p&&p.isTexture){const u=p.mapping;if(u===Vo||u===bc)if(e.has(p)){const v=e.get(p).texture;return o(v,p.mapping)}else{const v=p.image;if(v&&v.height>0){const g=new f0(v.height);return g.fromEquirectangularTexture(s,p),e.set(p,g),p.addEventListener("dispose",c),o(g.texture,p.mapping)}else return null}}return p}function a(p){if(p&&p.isTexture){const u=p.mapping,v=u===Vo||u===bc,g=u===Ls||u===Lr;if(v||g){let m=t.get(p);const f=m!==void 0?m.texture.pmremVersion:0;if(p.isRenderTargetTexture&&p.pmremVersion!==f)return i===null&&(i=new uh(s)),m=v?i.fromEquirectangular(p,m):i.fromCubemap(p,m),m.texture.pmremVersion=p.pmremVersion,t.set(p,m),m.texture;if(m!==void 0)return m.texture;{const y=p.image;return v&&y&&y.height>0||g&&y&&l(y)?(i===null&&(i=new uh(s)),m=v?i.fromEquirectangular(p):i.fromCubemap(p),m.texture.pmremVersion=p.pmremVersion,t.set(p,m),p.addEventListener("dispose",h),m.texture):null}}}return p}function o(p,u){return u===Vo?p.mapping=Ls:u===bc&&(p.mapping=Lr),p}function l(p){let u=0;const v=6;for(let g=0;g=65535?og:ag)(p,1);m.version=g;const f=r.get(d);f&&e.remove(f),r.set(d,m)}function h(d){const p=r.get(d);if(p){const u=d.index;u!==null&&p.versione.maxTextureSize&&(S=Math.ceil(_/e.maxTextureSize),_=e.maxTextureSize);const b=new Float32Array(_*S*4*d),E=new fu(b,_,S,d);E.type=Pi,E.needsUpdate=!0;const w=x*4;for(let C=0;C #include void main() { gl_FragColor = texture2D( tDiffuse, vUv ); #ifdef LINEAR_TONE_MAPPING gl_FragColor.rgb = LinearToneMapping( gl_FragColor.rgb ); #elif defined( REINHARD_TONE_MAPPING ) gl_FragColor.rgb = ReinhardToneMapping( gl_FragColor.rgb ); #elif defined( CINEON_TONE_MAPPING ) gl_FragColor.rgb = CineonToneMapping( gl_FragColor.rgb ); #elif defined( ACES_FILMIC_TONE_MAPPING ) gl_FragColor.rgb = ACESFilmicToneMapping( gl_FragColor.rgb ); #elif defined( AGX_TONE_MAPPING ) gl_FragColor.rgb = AgXToneMapping( gl_FragColor.rgb ); #elif defined( NEUTRAL_TONE_MAPPING ) gl_FragColor.rgb = NeutralToneMapping( gl_FragColor.rgb ); #elif defined( CUSTOM_TONE_MAPPING ) gl_FragColor.rgb = CustomToneMapping( gl_FragColor.rgb ); #endif #ifdef SRGB_TRANSFER gl_FragColor = sRGBTransferOETF( gl_FragColor ); #endif }`,depthTest:!1,depthWrite:!1}),c=new ht(o,l),h=new rn(-1,1,1,-1,0,1);let d=null,p=null,u=!1,v,g=null,m=[],f=!1;this.setSize=function(y,x){r.setSize(y,x),a.setSize(y,x);for(let _=0;_0&&m[0].isRenderPass===!0;const x=r.width,_=r.height;for(let S=0;S0)return s;const n=e*t;let r=cb[n];if(r===void 0&&(r=new Float32Array(n),cb[n]=r),e!==0){i.toArray(r,0);for(let a=1,o=0;a!==e;++a)o+=t,s[a].toArray(r,o)}return r}function Ii(s,e){if(s.length!==e.length)return!1;for(let t=0,i=s.length;t0&&(this.seq=n.concat(r))}setValue(e,t,i,n){const r=this.map[t];r!==void 0&&r.setValue(e,i,n)}setOptional(e,t,i){const n=t[i];n!==void 0&&this.setValue(e,i,n)}static upload(e,t,i,n){for(let r=0,a=t.length;r!==a;++r){const o=t[r],l=i[o.id];l.needsUpdate!==!1&&o.setValue(e,l.value,n)}}static seqWithValue(e,t){const i=[];for(let n=0,r=e.length;n!==r;++n){const a=e[n];a.id in t&&i.push(a)}return i}}function mb(s,e,t){const i=s.createShader(e);return s.shaderSource(i,t),s.compileShader(i),i}const q4=37297;let Z4=0;function Y4(s,e){const t=s.split(` `),i=[],n=Math.max(e-6,0),r=Math.min(e+6,t.length);for(let a=n;a":" "} ${o}: ${t[a]}`)}return i.join(` `)}const gb=new ft;function $4(s){Et._getMatrix(gb,Et.workingColorSpace,s);const e=`mat3( ${gb.elements.map(t=>t.toFixed(4))} )`;switch(Et.getTransfer(s)){case Pc:return[e,"LinearTransferOETF"];case Bt:return[e,"sRGBTransferOETF"];default:return Ye("WebGLProgram: Unsupported color space: ",s),[e,"LinearTransferOETF"]}}function vb(s,e,t){const i=s.getShaderParameter(e,s.COMPILE_STATUS),r=(s.getShaderInfoLog(e)||"").trim();if(i&&r==="")return"";const a=/ERROR: 0:(\d+)/.exec(r);if(a){const o=parseInt(a[1]);return t.toUpperCase()+` `+r+` `+Y4(s.getShaderSource(e),o)}else return r}function K4(s,e){const t=$4(e);return[`vec4 ${s}( vec4 value ) {`,` return ${t[1]}( vec4( value.rgb * ${t[0]}, value.a ) );`,"}"].join(` `)}const J4={[yd]:"Linear",[xd]:"Reinhard",[_d]:"Cineon",[Sa]:"ACESFilmic",[Md]:"AgX",[Sd]:"Neutral",[bd]:"Custom"};function Q4(s,e){const t=J4[e];return t===void 0?(Ye("WebGLProgram: Unsupported toneMapping:",e),"vec3 "+s+"( vec3 color ) { return LinearToneMapping( color ); }"):"vec3 "+s+"( vec3 color ) { return "+t+"ToneMapping( color ); }"}const Up=new R;function e5(){Et.getLuminanceCoefficients(Up);const s=Up.x.toFixed(4),e=Up.y.toFixed(4),t=Up.z.toFixed(4);return["float luminance( const in vec3 rgb ) {",` const vec3 weights = vec3( ${s}, ${e}, ${t} );`," return dot( weights, rgb );","}"].join(` `)}function t5(s){return[s.extensionClipCullDistance?"#extension GL_ANGLE_clip_cull_distance : require":"",s.extensionMultiDraw?"#extension GL_ANGLE_multi_draw : require":""].filter(ph).join(` `)}function i5(s){const e=[];for(const t in s){const i=s[t];i!==!1&&e.push("#define "+t+" "+i)}return e.join(` `)}function n5(s,e){const t={},i=s.getProgramParameter(e,s.ACTIVE_ATTRIBUTES);for(let n=0;n/gm;function v0(s){return s.replace(s5,a5)}const r5=new Map;function a5(s,e){let t=bt[e];if(t===void 0){const i=r5.get(e);if(i!==void 0)t=bt[i],Ye('WebGLRenderer: Shader chunk "%s" has been deprecated. Use "%s" instead.',e,i);else throw new Error("Can not resolve #include <"+e+">")}return v0(t)}const o5=/#pragma unroll_loop_start\s+for\s*\(\s*int\s+i\s*=\s*(\d+)\s*;\s*i\s*<\s*(\d+)\s*;\s*i\s*\+\+\s*\)\s*{([\s\S]+?)}\s+#pragma unroll_loop_end/g;function _b(s){return s.replace(o5,l5)}function l5(s,e,t,i){let n="";for(let r=parseInt(e);r0&&(m+=` `),f=["#define SHADER_TYPE "+t.shaderType,"#define SHADER_NAME "+t.shaderName,v].filter(ph).join(` `),f.length>0&&(f+=` `)):(m=[bb(t),"#define SHADER_TYPE "+t.shaderType,"#define SHADER_NAME "+t.shaderName,v,t.extensionClipCullDistance?"#define USE_CLIP_DISTANCE":"",t.batching?"#define USE_BATCHING":"",t.batchingColor?"#define USE_BATCHING_COLOR":"",t.instancing?"#define USE_INSTANCING":"",t.instancingColor?"#define USE_INSTANCING_COLOR":"",t.instancingMorph?"#define USE_INSTANCING_MORPH":"",t.useFog&&t.fog?"#define USE_FOG":"",t.useFog&&t.fogExp2?"#define FOG_EXP2":"",t.map?"#define USE_MAP":"",t.envMap?"#define USE_ENVMAP":"",t.envMap?"#define "+h:"",t.lightMap?"#define USE_LIGHTMAP":"",t.aoMap?"#define USE_AOMAP":"",t.bumpMap?"#define USE_BUMPMAP":"",t.normalMap?"#define USE_NORMALMAP":"",t.normalMapObjectSpace?"#define USE_NORMALMAP_OBJECTSPACE":"",t.normalMapTangentSpace?"#define USE_NORMALMAP_TANGENTSPACE":"",t.displacementMap?"#define USE_DISPLACEMENTMAP":"",t.emissiveMap?"#define USE_EMISSIVEMAP":"",t.anisotropy?"#define USE_ANISOTROPY":"",t.anisotropyMap?"#define USE_ANISOTROPYMAP":"",t.clearcoatMap?"#define USE_CLEARCOATMAP":"",t.clearcoatRoughnessMap?"#define USE_CLEARCOAT_ROUGHNESSMAP":"",t.clearcoatNormalMap?"#define USE_CLEARCOAT_NORMALMAP":"",t.iridescenceMap?"#define USE_IRIDESCENCEMAP":"",t.iridescenceThicknessMap?"#define USE_IRIDESCENCE_THICKNESSMAP":"",t.specularMap?"#define USE_SPECULARMAP":"",t.specularColorMap?"#define USE_SPECULAR_COLORMAP":"",t.specularIntensityMap?"#define USE_SPECULAR_INTENSITYMAP":"",t.roughnessMap?"#define USE_ROUGHNESSMAP":"",t.metalnessMap?"#define USE_METALNESSMAP":"",t.alphaMap?"#define USE_ALPHAMAP":"",t.alphaHash?"#define USE_ALPHAHASH":"",t.transmission?"#define USE_TRANSMISSION":"",t.transmissionMap?"#define USE_TRANSMISSIONMAP":"",t.thicknessMap?"#define USE_THICKNESSMAP":"",t.sheenColorMap?"#define USE_SHEEN_COLORMAP":"",t.sheenRoughnessMap?"#define USE_SHEEN_ROUGHNESSMAP":"",t.mapUv?"#define MAP_UV "+t.mapUv:"",t.alphaMapUv?"#define ALPHAMAP_UV "+t.alphaMapUv:"",t.lightMapUv?"#define LIGHTMAP_UV "+t.lightMapUv:"",t.aoMapUv?"#define AOMAP_UV "+t.aoMapUv:"",t.emissiveMapUv?"#define EMISSIVEMAP_UV "+t.emissiveMapUv:"",t.bumpMapUv?"#define BUMPMAP_UV "+t.bumpMapUv:"",t.normalMapUv?"#define NORMALMAP_UV "+t.normalMapUv:"",t.displacementMapUv?"#define DISPLACEMENTMAP_UV "+t.displacementMapUv:"",t.metalnessMapUv?"#define METALNESSMAP_UV "+t.metalnessMapUv:"",t.roughnessMapUv?"#define ROUGHNESSMAP_UV "+t.roughnessMapUv:"",t.anisotropyMapUv?"#define ANISOTROPYMAP_UV "+t.anisotropyMapUv:"",t.clearcoatMapUv?"#define CLEARCOATMAP_UV "+t.clearcoatMapUv:"",t.clearcoatNormalMapUv?"#define CLEARCOAT_NORMALMAP_UV "+t.clearcoatNormalMapUv:"",t.clearcoatRoughnessMapUv?"#define CLEARCOAT_ROUGHNESSMAP_UV "+t.clearcoatRoughnessMapUv:"",t.iridescenceMapUv?"#define IRIDESCENCEMAP_UV "+t.iridescenceMapUv:"",t.iridescenceThicknessMapUv?"#define IRIDESCENCE_THICKNESSMAP_UV "+t.iridescenceThicknessMapUv:"",t.sheenColorMapUv?"#define SHEEN_COLORMAP_UV "+t.sheenColorMapUv:"",t.sheenRoughnessMapUv?"#define SHEEN_ROUGHNESSMAP_UV "+t.sheenRoughnessMapUv:"",t.specularMapUv?"#define SPECULARMAP_UV "+t.specularMapUv:"",t.specularColorMapUv?"#define SPECULAR_COLORMAP_UV "+t.specularColorMapUv:"",t.specularIntensityMapUv?"#define SPECULAR_INTENSITYMAP_UV "+t.specularIntensityMapUv:"",t.transmissionMapUv?"#define TRANSMISSIONMAP_UV "+t.transmissionMapUv:"",t.thicknessMapUv?"#define THICKNESSMAP_UV "+t.thicknessMapUv:"",t.vertexTangents&&t.flatShading===!1?"#define USE_TANGENT":"",t.vertexColors?"#define USE_COLOR":"",t.vertexAlphas?"#define USE_COLOR_ALPHA":"",t.vertexUv1s?"#define USE_UV1":"",t.vertexUv2s?"#define USE_UV2":"",t.vertexUv3s?"#define USE_UV3":"",t.pointsUvs?"#define USE_POINTS_UV":"",t.flatShading?"#define FLAT_SHADED":"",t.skinning?"#define USE_SKINNING":"",t.morphTargets?"#define USE_MORPHTARGETS":"",t.morphNormals&&t.flatShading===!1?"#define USE_MORPHNORMALS":"",t.morphColors?"#define USE_MORPHCOLORS":"",t.morphTargetsCount>0?"#define MORPHTARGETS_TEXTURE_STRIDE "+t.morphTextureStride:"",t.morphTargetsCount>0?"#define MORPHTARGETS_COUNT "+t.morphTargetsCount:"",t.doubleSided?"#define DOUBLE_SIDED":"",t.flipSided?"#define FLIP_SIDED":"",t.shadowMapEnabled?"#define USE_SHADOWMAP":"",t.shadowMapEnabled?"#define "+l:"",t.sizeAttenuation?"#define USE_SIZEATTENUATION":"",t.numLightProbes>0?"#define USE_LIGHT_PROBES":"",t.logarithmicDepthBuffer?"#define USE_LOGARITHMIC_DEPTH_BUFFER":"",t.reversedDepthBuffer?"#define USE_REVERSED_DEPTH_BUFFER":"","uniform mat4 modelMatrix;","uniform mat4 modelViewMatrix;","uniform mat4 projectionMatrix;","uniform mat4 viewMatrix;","uniform mat3 normalMatrix;","uniform vec3 cameraPosition;","uniform bool isOrthographic;","#ifdef USE_INSTANCING"," attribute mat4 instanceMatrix;","#endif","#ifdef USE_INSTANCING_COLOR"," attribute vec3 instanceColor;","#endif","#ifdef USE_INSTANCING_MORPH"," uniform sampler2D morphTexture;","#endif","attribute vec3 position;","attribute vec3 normal;","attribute vec2 uv;","#ifdef USE_UV1"," attribute vec2 uv1;","#endif","#ifdef USE_UV2"," attribute vec2 uv2;","#endif","#ifdef USE_UV3"," attribute vec2 uv3;","#endif","#ifdef USE_TANGENT"," attribute vec4 tangent;","#endif","#if defined( USE_COLOR_ALPHA )"," attribute vec4 color;","#elif defined( USE_COLOR )"," attribute vec3 color;","#endif","#ifdef USE_SKINNING"," attribute vec4 skinIndex;"," attribute vec4 skinWeight;","#endif",` `].filter(ph).join(` `),f=[bb(t),"#define SHADER_TYPE "+t.shaderType,"#define SHADER_NAME "+t.shaderName,v,t.useFog&&t.fog?"#define USE_FOG":"",t.useFog&&t.fogExp2?"#define FOG_EXP2":"",t.alphaToCoverage?"#define ALPHA_TO_COVERAGE":"",t.map?"#define USE_MAP":"",t.matcap?"#define USE_MATCAP":"",t.envMap?"#define USE_ENVMAP":"",t.envMap?"#define "+c:"",t.envMap?"#define "+h:"",t.envMap?"#define "+d:"",p?"#define CUBEUV_TEXEL_WIDTH "+p.texelWidth:"",p?"#define CUBEUV_TEXEL_HEIGHT "+p.texelHeight:"",p?"#define CUBEUV_MAX_MIP "+p.maxMip+".0":"",t.lightMap?"#define USE_LIGHTMAP":"",t.aoMap?"#define USE_AOMAP":"",t.bumpMap?"#define USE_BUMPMAP":"",t.normalMap?"#define USE_NORMALMAP":"",t.normalMapObjectSpace?"#define USE_NORMALMAP_OBJECTSPACE":"",t.normalMapTangentSpace?"#define USE_NORMALMAP_TANGENTSPACE":"",t.emissiveMap?"#define USE_EMISSIVEMAP":"",t.anisotropy?"#define USE_ANISOTROPY":"",t.anisotropyMap?"#define USE_ANISOTROPYMAP":"",t.clearcoat?"#define USE_CLEARCOAT":"",t.clearcoatMap?"#define USE_CLEARCOATMAP":"",t.clearcoatRoughnessMap?"#define USE_CLEARCOAT_ROUGHNESSMAP":"",t.clearcoatNormalMap?"#define USE_CLEARCOAT_NORMALMAP":"",t.dispersion?"#define USE_DISPERSION":"",t.iridescence?"#define USE_IRIDESCENCE":"",t.iridescenceMap?"#define USE_IRIDESCENCEMAP":"",t.iridescenceThicknessMap?"#define USE_IRIDESCENCE_THICKNESSMAP":"",t.specularMap?"#define USE_SPECULARMAP":"",t.specularColorMap?"#define USE_SPECULAR_COLORMAP":"",t.specularIntensityMap?"#define USE_SPECULAR_INTENSITYMAP":"",t.roughnessMap?"#define USE_ROUGHNESSMAP":"",t.metalnessMap?"#define USE_METALNESSMAP":"",t.alphaMap?"#define USE_ALPHAMAP":"",t.alphaTest?"#define USE_ALPHATEST":"",t.alphaHash?"#define USE_ALPHAHASH":"",t.sheen?"#define USE_SHEEN":"",t.sheenColorMap?"#define USE_SHEEN_COLORMAP":"",t.sheenRoughnessMap?"#define USE_SHEEN_ROUGHNESSMAP":"",t.transmission?"#define USE_TRANSMISSION":"",t.transmissionMap?"#define USE_TRANSMISSIONMAP":"",t.thicknessMap?"#define USE_THICKNESSMAP":"",t.vertexTangents&&t.flatShading===!1?"#define USE_TANGENT":"",t.vertexColors||t.instancingColor?"#define USE_COLOR":"",t.vertexAlphas||t.batchingColor?"#define USE_COLOR_ALPHA":"",t.vertexUv1s?"#define USE_UV1":"",t.vertexUv2s?"#define USE_UV2":"",t.vertexUv3s?"#define USE_UV3":"",t.pointsUvs?"#define USE_POINTS_UV":"",t.gradientMap?"#define USE_GRADIENTMAP":"",t.flatShading?"#define FLAT_SHADED":"",t.doubleSided?"#define DOUBLE_SIDED":"",t.flipSided?"#define FLIP_SIDED":"",t.shadowMapEnabled?"#define USE_SHADOWMAP":"",t.shadowMapEnabled?"#define "+l:"",t.premultipliedAlpha?"#define PREMULTIPLIED_ALPHA":"",t.numLightProbes>0?"#define USE_LIGHT_PROBES":"",t.decodeVideoTexture?"#define DECODE_VIDEO_TEXTURE":"",t.decodeVideoTextureEmissive?"#define DECODE_VIDEO_TEXTURE_EMISSIVE":"",t.logarithmicDepthBuffer?"#define USE_LOGARITHMIC_DEPTH_BUFFER":"",t.reversedDepthBuffer?"#define USE_REVERSED_DEPTH_BUFFER":"","uniform mat4 viewMatrix;","uniform vec3 cameraPosition;","uniform bool isOrthographic;",t.toneMapping!==ji?"#define TONE_MAPPING":"",t.toneMapping!==ji?bt.tonemapping_pars_fragment:"",t.toneMapping!==ji?Q4("toneMapping",t.toneMapping):"",t.dithering?"#define DITHERING":"",t.opaque?"#define OPAQUE":"",bt.colorspace_pars_fragment,K4("linearToOutputTexel",t.outputColorSpace),e5(),t.useDepthPacking?"#define DEPTH_PACKING "+t.depthPacking:"",` `].filter(ph).join(` `)),a=v0(a),a=yb(a,t),a=xb(a,t),o=v0(o),o=yb(o,t),o=xb(o,t),a=_b(a),o=_b(o),t.isRawShaderMaterial!==!0&&(y=`#version 300 es `,m=[u,"#define attribute in","#define varying out","#define texture2D texture"].join(` `)+` `+m,f=["#define varying in",t.glslVersion===Gm?"":"layout(location = 0) out highp vec4 pc_fragColor;",t.glslVersion===Gm?"":"#define gl_FragColor pc_fragColor","#define gl_FragDepthEXT gl_FragDepth","#define texture2D texture","#define textureCube texture","#define texture2DProj textureProj","#define texture2DLodEXT textureLod","#define texture2DProjLodEXT textureProjLod","#define textureCubeLodEXT textureLod","#define texture2DGradEXT textureGrad","#define texture2DProjGradEXT textureProjGrad","#define textureCubeGradEXT textureGrad"].join(` `)+` `+f);const x=y+m+a,_=y+f+o,S=mb(n,n.VERTEX_SHADER,x),b=mb(n,n.FRAGMENT_SHADER,_);n.attachShader(g,S),n.attachShader(g,b),t.index0AttributeName!==void 0?n.bindAttribLocation(g,0,t.index0AttributeName):t.morphTargets===!0&&n.bindAttribLocation(g,0,"position"),n.linkProgram(g);function E(I){if(s.debug.checkShaderErrors){const P=n.getProgramInfoLog(g)||"",k=n.getShaderInfoLog(S)||"",A=n.getShaderInfoLog(b)||"",B=P.trim(),F=k.trim(),H=A.trim();let q=!0,G=!0;if(n.getProgramParameter(g,n.LINK_STATUS)===!1)if(q=!1,typeof s.debug.onShaderError=="function")s.debug.onShaderError(n,g,S,b);else{const re=vb(n,S,"vertex"),Y=vb(n,b,"fragment");lt("THREE.WebGLProgram: Shader Error "+n.getError()+" - VALIDATE_STATUS "+n.getProgramParameter(g,n.VALIDATE_STATUS)+` Material Name: `+I.name+` Material Type: `+I.type+` Program Info Log: `+B+` `+re+` `+Y)}else B!==""?Ye("WebGLProgram: Program Info Log:",B):(F===""||H==="")&&(G=!1);G&&(I.diagnostics={runnable:q,programLog:B,vertexShader:{log:F,prefix:m},fragmentShader:{log:H,prefix:f}})}n.deleteShader(S),n.deleteShader(b),w=new Op(n,g),M=n5(n,g)}let w;this.getUniforms=function(){return w===void 0&&E(this),w};let M;this.getAttributes=function(){return M===void 0&&E(this),M};let C=t.rendererExtensionParallelShaderCompile===!1;return this.isReady=function(){return C===!1&&(C=n.getProgramParameter(g,q4)),C},this.destroy=function(){i.releaseStatesOfProgram(this),n.deleteProgram(g),this.program=void 0},this.type=t.shaderType,this.name=t.shaderName,this.id=Z4++,this.cacheKey=e,this.usedTimes=1,this.program=g,this.vertexShader=S,this.fragmentShader=b,this}let x5=0;class _5{constructor(){this.shaderCache=new Map,this.materialCache=new Map}update(e){const t=e.vertexShader,i=e.fragmentShader,n=this._getShaderStage(t),r=this._getShaderStage(i),a=this._getShaderCacheForMaterial(e);return a.has(n)===!1&&(a.add(n),n.usedTimes++),a.has(r)===!1&&(a.add(r),r.usedTimes++),this}remove(e){const t=this.materialCache.get(e);for(const i of t)i.usedTimes--,i.usedTimes===0&&this.shaderCache.delete(i.code);return this.materialCache.delete(e),this}getVertexShaderID(e){return this._getShaderStage(e.vertexShader).id}getFragmentShaderID(e){return this._getShaderStage(e.fragmentShader).id}dispose(){this.shaderCache.clear(),this.materialCache.clear()}_getShaderCacheForMaterial(e){const t=this.materialCache;let i=t.get(e);return i===void 0&&(i=new Set,t.set(e,i)),i}_getShaderStage(e){const t=this.shaderCache;let i=t.get(e);return i===void 0&&(i=new b5(e),t.set(e,i)),i}}class b5{constructor(e){this.id=x5++,this.code=e,this.usedTimes=0}}function M5(s,e,t,i,n,r){const a=new vu,o=new _5,l=new Set,c=[],h=new Map,d=i.logarithmicDepthBuffer;let p=i.precision;const u={MeshDepthMaterial:"depth",MeshDistanceMaterial:"distance",MeshNormalMaterial:"normal",MeshBasicMaterial:"basic",MeshLambertMaterial:"lambert",MeshPhongMaterial:"phong",MeshToonMaterial:"toon",MeshStandardMaterial:"physical",MeshPhysicalMaterial:"physical",MeshMatcapMaterial:"matcap",LineBasicMaterial:"basic",LineDashedMaterial:"dashed",PointsMaterial:"points",ShadowMaterial:"shadow",SpriteMaterial:"sprite"};function v(w){return l.add(w),w===0?"uv":`uv${w}`}function g(w,M,C,I,P){const k=I.fog,A=P.geometry,B=w.isMeshStandardMaterial||w.isMeshLambertMaterial||w.isMeshPhongMaterial?I.environment:null,F=w.isMeshStandardMaterial||w.isMeshLambertMaterial&&!w.envMap||w.isMeshPhongMaterial&&!w.envMap,H=e.get(w.envMap||B,F),q=H&&H.mapping===Go?H.image.height:null,G=u[w.type];w.precision!==null&&(p=i.getMaxPrecision(w.precision),p!==w.precision&&Ye("WebGLProgram.getParameters:",w.precision,"not supported, using",p,"instead."));const re=A.morphAttributes.position||A.morphAttributes.normal||A.morphAttributes.color,Y=re!==void 0?re.length:0;let $=0;A.morphAttributes.position!==void 0&&($=1),A.morphAttributes.normal!==void 0&&($=2),A.morphAttributes.color!==void 0&&($=3);let _e,Te,be,J;if(G){const Qe=ys[G];_e=Qe.vertexShader,Te=Qe.fragmentShader}else _e=w.vertexShader,Te=w.fragmentShader,o.update(w),be=o.getVertexShaderID(w),J=o.getFragmentShaderID(w);const oe=s.getRenderTarget(),ue=s.state.buffers.depth.getReversed(),Re=P.isInstancedMesh===!0,Ie=P.isBatchedMesh===!0,Ue=!!w.map,tt=!!w.matcap,je=!!H,D=!!w.aoMap,ae=!!w.lightMap,Q=!!w.bumpMap,W=!!w.normalMap,N=!!w.displacementMap,te=!!w.emissiveMap,de=!!w.metalnessMap,V=!!w.roughnessMap,ee=w.anisotropy>0,L=w.clearcoat>0,T=w.dispersion>0,U=w.iridescence>0,j=w.sheen>0,K=w.transmission>0,Z=ee&&!!w.anisotropyMap,Pe=L&&!!w.clearcoatMap,ve=L&&!!w.clearcoatNormalMap,ke=L&&!!w.clearcoatRoughnessMap,Fe=U&&!!w.iridescenceMap,le=U&&!!w.iridescenceThicknessMap,ye=j&&!!w.sheenColorMap,ze=j&&!!w.sheenRoughnessMap,Oe=!!w.specularMap,Se=!!w.specularColorMap,Xe=!!w.specularIntensityMap,z=K&&!!w.transmissionMap,xe=K&&!!w.thicknessMap,ge=!!w.gradientMap,Le=!!w.alphaMap,pe=w.alphaTest>0,ne=!!w.alphaHash,Ne=!!w.extensions;let Ge=ji;w.toneMapped&&(oe===null||oe.isXRRenderTarget===!0)&&(Ge=s.toneMapping);const pt={shaderID:G,shaderType:w.type,shaderName:w.name,vertexShader:_e,fragmentShader:Te,defines:w.defines,customVertexShaderID:be,customFragmentShaderID:J,isRawShaderMaterial:w.isRawShaderMaterial===!0,glslVersion:w.glslVersion,precision:p,batching:Ie,batchingColor:Ie&&P._colorsTexture!==null,instancing:Re,instancingColor:Re&&P.instanceColor!==null,instancingMorph:Re&&P.morphTexture!==null,outputColorSpace:oe===null?s.outputColorSpace:oe.isXRRenderTarget===!0?oe.texture.colorSpace:Zi,alphaToCoverage:!!w.alphaToCoverage,map:Ue,matcap:tt,envMap:je,envMapMode:je&&H.mapping,envMapCubeUVHeight:q,aoMap:D,lightMap:ae,bumpMap:Q,normalMap:W,displacementMap:N,emissiveMap:te,normalMapObjectSpace:W&&w.normalMapType===Gy,normalMapTangentSpace:W&&w.normalMapType===Nr,metalnessMap:de,roughnessMap:V,anisotropy:ee,anisotropyMap:Z,clearcoat:L,clearcoatMap:Pe,clearcoatNormalMap:ve,clearcoatRoughnessMap:ke,dispersion:T,iridescence:U,iridescenceMap:Fe,iridescenceThicknessMap:le,sheen:j,sheenColorMap:ye,sheenRoughnessMap:ze,specularMap:Oe,specularColorMap:Se,specularIntensityMap:Xe,transmission:K,transmissionMap:z,thicknessMap:xe,gradientMap:ge,opaque:w.transparent===!1&&w.blending===ba&&w.alphaToCoverage===!1,alphaMap:Le,alphaTest:pe,alphaHash:ne,combine:w.combine,mapUv:Ue&&v(w.map.channel),aoMapUv:D&&v(w.aoMap.channel),lightMapUv:ae&&v(w.lightMap.channel),bumpMapUv:Q&&v(w.bumpMap.channel),normalMapUv:W&&v(w.normalMap.channel),displacementMapUv:N&&v(w.displacementMap.channel),emissiveMapUv:te&&v(w.emissiveMap.channel),metalnessMapUv:de&&v(w.metalnessMap.channel),roughnessMapUv:V&&v(w.roughnessMap.channel),anisotropyMapUv:Z&&v(w.anisotropyMap.channel),clearcoatMapUv:Pe&&v(w.clearcoatMap.channel),clearcoatNormalMapUv:ve&&v(w.clearcoatNormalMap.channel),clearcoatRoughnessMapUv:ke&&v(w.clearcoatRoughnessMap.channel),iridescenceMapUv:Fe&&v(w.iridescenceMap.channel),iridescenceThicknessMapUv:le&&v(w.iridescenceThicknessMap.channel),sheenColorMapUv:ye&&v(w.sheenColorMap.channel),sheenRoughnessMapUv:ze&&v(w.sheenRoughnessMap.channel),specularMapUv:Oe&&v(w.specularMap.channel),specularColorMapUv:Se&&v(w.specularColorMap.channel),specularIntensityMapUv:Xe&&v(w.specularIntensityMap.channel),transmissionMapUv:z&&v(w.transmissionMap.channel),thicknessMapUv:xe&&v(w.thicknessMap.channel),alphaMapUv:Le&&v(w.alphaMap.channel),vertexTangents:!!A.attributes.tangent&&(W||ee),vertexColors:w.vertexColors,vertexAlphas:w.vertexColors===!0&&!!A.attributes.color&&A.attributes.color.itemSize===4,pointsUvs:P.isPoints===!0&&!!A.attributes.uv&&(Ue||Le),fog:!!k,useFog:w.fog===!0,fogExp2:!!k&&k.isFogExp2,flatShading:w.wireframe===!1&&(w.flatShading===!0||A.attributes.normal===void 0&&W===!1&&(w.isMeshLambertMaterial||w.isMeshPhongMaterial||w.isMeshStandardMaterial||w.isMeshPhysicalMaterial)),sizeAttenuation:w.sizeAttenuation===!0,logarithmicDepthBuffer:d,reversedDepthBuffer:ue,skinning:P.isSkinnedMesh===!0,morphTargets:A.morphAttributes.position!==void 0,morphNormals:A.morphAttributes.normal!==void 0,morphColors:A.morphAttributes.color!==void 0,morphTargetsCount:Y,morphTextureStride:$,numDirLights:M.directional.length,numPointLights:M.point.length,numSpotLights:M.spot.length,numSpotLightMaps:M.spotLightMap.length,numRectAreaLights:M.rectArea.length,numHemiLights:M.hemi.length,numDirLightShadows:M.directionalShadowMap.length,numPointLightShadows:M.pointShadowMap.length,numSpotLightShadows:M.spotShadowMap.length,numSpotLightShadowsWithMaps:M.numSpotLightShadowsWithMaps,numLightProbes:M.numLightProbes,numClippingPlanes:r.numPlanes,numClipIntersection:r.numIntersection,dithering:w.dithering,shadowMapEnabled:s.shadowMap.enabled&&C.length>0,shadowMapType:s.shadowMap.type,toneMapping:Ge,decodeVideoTexture:Ue&&w.map.isVideoTexture===!0&&Et.getTransfer(w.map.colorSpace)===Bt,decodeVideoTextureEmissive:te&&w.emissiveMap.isVideoTexture===!0&&Et.getTransfer(w.emissiveMap.colorSpace)===Bt,premultipliedAlpha:w.premultipliedAlpha,doubleSided:w.side===Ot,flipSided:w.side===Bi,useDepthPacking:w.depthPacking>=0,depthPacking:w.depthPacking||0,index0AttributeName:w.index0AttributeName,extensionClipCullDistance:Ne&&w.extensions.clipCullDistance===!0&&t.has("WEBGL_clip_cull_distance"),extensionMultiDraw:(Ne&&w.extensions.multiDraw===!0||Ie)&&t.has("WEBGL_multi_draw"),rendererExtensionParallelShaderCompile:t.has("KHR_parallel_shader_compile"),customProgramCacheKey:w.customProgramCacheKey()};return pt.vertexUv1s=l.has(1),pt.vertexUv2s=l.has(2),pt.vertexUv3s=l.has(3),l.clear(),pt}function m(w){const M=[];if(w.shaderID?M.push(w.shaderID):(M.push(w.customVertexShaderID),M.push(w.customFragmentShaderID)),w.defines!==void 0)for(const C in w.defines)M.push(C),M.push(w.defines[C]);return w.isRawShaderMaterial===!1&&(f(M,w),y(M,w),M.push(s.outputColorSpace)),M.push(w.customProgramCacheKey),M.join()}function f(w,M){w.push(M.precision),w.push(M.outputColorSpace),w.push(M.envMapMode),w.push(M.envMapCubeUVHeight),w.push(M.mapUv),w.push(M.alphaMapUv),w.push(M.lightMapUv),w.push(M.aoMapUv),w.push(M.bumpMapUv),w.push(M.normalMapUv),w.push(M.displacementMapUv),w.push(M.emissiveMapUv),w.push(M.metalnessMapUv),w.push(M.roughnessMapUv),w.push(M.anisotropyMapUv),w.push(M.clearcoatMapUv),w.push(M.clearcoatNormalMapUv),w.push(M.clearcoatRoughnessMapUv),w.push(M.iridescenceMapUv),w.push(M.iridescenceThicknessMapUv),w.push(M.sheenColorMapUv),w.push(M.sheenRoughnessMapUv),w.push(M.specularMapUv),w.push(M.specularColorMapUv),w.push(M.specularIntensityMapUv),w.push(M.transmissionMapUv),w.push(M.thicknessMapUv),w.push(M.combine),w.push(M.fogExp2),w.push(M.sizeAttenuation),w.push(M.morphTargetsCount),w.push(M.morphAttributeCount),w.push(M.numDirLights),w.push(M.numPointLights),w.push(M.numSpotLights),w.push(M.numSpotLightMaps),w.push(M.numHemiLights),w.push(M.numRectAreaLights),w.push(M.numDirLightShadows),w.push(M.numPointLightShadows),w.push(M.numSpotLightShadows),w.push(M.numSpotLightShadowsWithMaps),w.push(M.numLightProbes),w.push(M.shadowMapType),w.push(M.toneMapping),w.push(M.numClippingPlanes),w.push(M.numClipIntersection),w.push(M.depthPacking)}function y(w,M){a.disableAll(),M.instancing&&a.enable(0),M.instancingColor&&a.enable(1),M.instancingMorph&&a.enable(2),M.matcap&&a.enable(3),M.envMap&&a.enable(4),M.normalMapObjectSpace&&a.enable(5),M.normalMapTangentSpace&&a.enable(6),M.clearcoat&&a.enable(7),M.iridescence&&a.enable(8),M.alphaTest&&a.enable(9),M.vertexColors&&a.enable(10),M.vertexAlphas&&a.enable(11),M.vertexUv1s&&a.enable(12),M.vertexUv2s&&a.enable(13),M.vertexUv3s&&a.enable(14),M.vertexTangents&&a.enable(15),M.anisotropy&&a.enable(16),M.alphaHash&&a.enable(17),M.batching&&a.enable(18),M.dispersion&&a.enable(19),M.batchingColor&&a.enable(20),M.gradientMap&&a.enable(21),w.push(a.mask),a.disableAll(),M.fog&&a.enable(0),M.useFog&&a.enable(1),M.flatShading&&a.enable(2),M.logarithmicDepthBuffer&&a.enable(3),M.reversedDepthBuffer&&a.enable(4),M.skinning&&a.enable(5),M.morphTargets&&a.enable(6),M.morphNormals&&a.enable(7),M.morphColors&&a.enable(8),M.premultipliedAlpha&&a.enable(9),M.shadowMapEnabled&&a.enable(10),M.doubleSided&&a.enable(11),M.flipSided&&a.enable(12),M.useDepthPacking&&a.enable(13),M.dithering&&a.enable(14),M.transmission&&a.enable(15),M.sheen&&a.enable(16),M.opaque&&a.enable(17),M.pointsUvs&&a.enable(18),M.decodeVideoTexture&&a.enable(19),M.decodeVideoTextureEmissive&&a.enable(20),M.alphaToCoverage&&a.enable(21),w.push(a.mask)}function x(w){const M=u[w.type];let C;if(M){const I=ys[M];C=nn.clone(I.uniforms)}else C=w.uniforms;return C}function _(w,M){let C=h.get(M);return C!==void 0?++C.usedTimes:(C=new y5(s,M,w,n),c.push(C),h.set(M,C)),C}function S(w){if(--w.usedTimes===0){const M=c.indexOf(w);c[M]=c[c.length-1],c.pop(),h.delete(w.cacheKey),w.destroy()}}function b(w){o.remove(w)}function E(){o.dispose()}return{getParameters:g,getProgramCacheKey:m,getUniforms:x,acquireProgram:_,releaseProgram:S,releaseShaderCache:b,programs:c,dispose:E}}function S5(){let s=new WeakMap;function e(a){return s.has(a)}function t(a){let o=s.get(a);return o===void 0&&(o={},s.set(a,o)),o}function i(a){s.delete(a)}function n(a,o,l){s.get(a)[o]=l}function r(){s=new WeakMap}return{has:e,get:t,remove:i,update:n,dispose:r}}function w5(s,e){return s.groupOrder!==e.groupOrder?s.groupOrder-e.groupOrder:s.renderOrder!==e.renderOrder?s.renderOrder-e.renderOrder:s.material.id!==e.material.id?s.material.id-e.material.id:s.materialVariant!==e.materialVariant?s.materialVariant-e.materialVariant:s.z!==e.z?s.z-e.z:s.id-e.id}function Mb(s,e){return s.groupOrder!==e.groupOrder?s.groupOrder-e.groupOrder:s.renderOrder!==e.renderOrder?s.renderOrder-e.renderOrder:s.z!==e.z?e.z-s.z:s.id-e.id}function Sb(){const s=[];let e=0;const t=[],i=[],n=[];function r(){e=0,t.length=0,i.length=0,n.length=0}function a(p){let u=0;return p.isInstancedMesh&&(u+=2),p.isSkinnedMesh&&(u+=1),u}function o(p,u,v,g,m,f){let y=s[e];return y===void 0?(y={id:p.id,object:p,geometry:u,material:v,materialVariant:a(p),groupOrder:g,renderOrder:p.renderOrder,z:m,group:f},s[e]=y):(y.id=p.id,y.object=p,y.geometry=u,y.material=v,y.materialVariant=a(p),y.groupOrder=g,y.renderOrder=p.renderOrder,y.z=m,y.group=f),e++,y}function l(p,u,v,g,m,f){const y=o(p,u,v,g,m,f);v.transmission>0?i.push(y):v.transparent===!0?n.push(y):t.push(y)}function c(p,u,v,g,m,f){const y=o(p,u,v,g,m,f);v.transmission>0?i.unshift(y):v.transparent===!0?n.unshift(y):t.unshift(y)}function h(p,u){t.length>1&&t.sort(p||w5),i.length>1&&i.sort(u||Mb),n.length>1&&n.sort(u||Mb)}function d(){for(let p=e,u=s.length;p=r.length?(a=new Sb,r.push(a)):a=r[n],a}function t(){s=new WeakMap}return{get:e,dispose:t}}function T5(){const s={};return{get:function(e){if(s[e.id]!==void 0)return s[e.id];let t;switch(e.type){case"DirectionalLight":t={direction:new R,color:new We};break;case"SpotLight":t={position:new R,direction:new R,color:new We,distance:0,coneCos:0,penumbraCos:0,decay:0};break;case"PointLight":t={position:new R,color:new We,distance:0,decay:0};break;case"HemisphereLight":t={direction:new R,skyColor:new We,groundColor:new We};break;case"RectAreaLight":t={color:new We,position:new R,halfWidth:new R,halfHeight:new R};break}return s[e.id]=t,t}}}function C5(){const s={};return{get:function(e){if(s[e.id]!==void 0)return s[e.id];let t;switch(e.type){case"DirectionalLight":t={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new me};break;case"SpotLight":t={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new me};break;case"PointLight":t={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new me,shadowCameraNear:1,shadowCameraFar:1e3};break}return s[e.id]=t,t}}}let A5=0;function P5(s,e){return(e.castShadow?2:0)-(s.castShadow?2:0)+(e.map?1:0)-(s.map?1:0)}function R5(s){const e=new T5,t=C5(),i={version:0,hash:{directionalLength:-1,pointLength:-1,spotLength:-1,rectAreaLength:-1,hemiLength:-1,numDirectionalShadows:-1,numPointShadows:-1,numSpotShadows:-1,numSpotMaps:-1,numLightProbes:-1},ambient:[0,0,0],probe:[],directional:[],directionalShadow:[],directionalShadowMap:[],directionalShadowMatrix:[],spot:[],spotLightMap:[],spotShadow:[],spotShadowMap:[],spotLightMatrix:[],rectArea:[],rectAreaLTC1:null,rectAreaLTC2:null,point:[],pointShadow:[],pointShadowMap:[],pointShadowMatrix:[],hemi:[],numSpotLightShadowsWithMaps:0,numLightProbes:0};for(let c=0;c<9;c++)i.probe.push(new R);const n=new R,r=new qe,a=new qe;function o(c){let h=0,d=0,p=0;for(let M=0;M<9;M++)i.probe[M].set(0,0,0);let u=0,v=0,g=0,m=0,f=0,y=0,x=0,_=0,S=0,b=0,E=0;c.sort(P5);for(let M=0,C=c.length;M0&&(s.has("OES_texture_float_linear")===!0?(i.rectAreaLTC1=$e.LTC_FLOAT_1,i.rectAreaLTC2=$e.LTC_FLOAT_2):(i.rectAreaLTC1=$e.LTC_HALF_1,i.rectAreaLTC2=$e.LTC_HALF_2)),i.ambient[0]=h,i.ambient[1]=d,i.ambient[2]=p;const w=i.hash;(w.directionalLength!==u||w.pointLength!==v||w.spotLength!==g||w.rectAreaLength!==m||w.hemiLength!==f||w.numDirectionalShadows!==y||w.numPointShadows!==x||w.numSpotShadows!==_||w.numSpotMaps!==S||w.numLightProbes!==E)&&(i.directional.length=u,i.spot.length=g,i.rectArea.length=m,i.point.length=v,i.hemi.length=f,i.directionalShadow.length=y,i.directionalShadowMap.length=y,i.pointShadow.length=x,i.pointShadowMap.length=x,i.spotShadow.length=_,i.spotShadowMap.length=_,i.directionalShadowMatrix.length=y,i.pointShadowMatrix.length=x,i.spotLightMatrix.length=_+S-b,i.spotLightMap.length=S,i.numSpotLightShadowsWithMaps=b,i.numLightProbes=E,w.directionalLength=u,w.pointLength=v,w.spotLength=g,w.rectAreaLength=m,w.hemiLength=f,w.numDirectionalShadows=y,w.numPointShadows=x,w.numSpotShadows=_,w.numSpotMaps=S,w.numLightProbes=E,i.version=A5++)}function l(c,h){let d=0,p=0,u=0,v=0,g=0;const m=h.matrixWorldInverse;for(let f=0,y=c.length;f=a.length?(o=new wb(s),a.push(o)):o=a[r],o}function i(){e=new WeakMap}return{get:t,dispose:i}}const L5=`void main() { gl_Position = vec4( position, 1.0 ); }`,D5=`uniform sampler2D shadow_pass; uniform vec2 resolution; uniform float radius; void main() { const float samples = float( VSM_SAMPLES ); float mean = 0.0; float squared_mean = 0.0; float uvStride = samples <= 1.0 ? 0.0 : 2.0 / ( samples - 1.0 ); float uvStart = samples <= 1.0 ? 0.0 : - 1.0; for ( float i = 0.0; i < samples; i ++ ) { float uvOffset = uvStart + i * uvStride; #ifdef HORIZONTAL_PASS vec2 distribution = texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( uvOffset, 0.0 ) * radius ) / resolution ).rg; mean += distribution.x; squared_mean += distribution.y * distribution.y + distribution.x * distribution.x; #else float depth = texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( 0.0, uvOffset ) * radius ) / resolution ).r; mean += depth; squared_mean += depth * depth; #endif } mean = mean / samples; squared_mean = squared_mean / samples; float std_dev = sqrt( max( 0.0, squared_mean - mean * mean ) ); gl_FragColor = vec4( mean, std_dev, 0.0, 1.0 ); }`,N5=[new R(1,0,0),new R(-1,0,0),new R(0,1,0),new R(0,-1,0),new R(0,0,1),new R(0,0,-1)],k5=[new R(0,-1,0),new R(0,-1,0),new R(0,0,1),new R(0,0,-1),new R(0,-1,0),new R(0,-1,0)],Eb=new qe,fh=new R,y0=new R;function O5(s,e,t){let i=new pl;const n=new me,r=new me,a=new Pt,o=new Bg,l=new Fg,c={},h=t.maxTextureSize,d={[_n]:Bi,[Bi]:_n,[Ot]:Ot},p=new Jt({defines:{VSM_SAMPLES:8},uniforms:{shadow_pass:{value:null},resolution:{value:new me},radius:{value:4}},vertexShader:L5,fragmentShader:D5}),u=p.clone();u.defines.HORIZONTAL_PASS=1;const v=new at;v.setAttribute("position",new St(new Float32Array([-1,-1,.5,3,-1,.5,-1,3,.5]),3));const g=new ht(v,p),m=this;this.enabled=!1,this.autoUpdate=!0,this.needsUpdate=!1,this.type=vc;let f=this.type;this.render=function(b,E,w){if(m.enabled===!1||m.autoUpdate===!1&&m.needsUpdate===!1||b.length===0)return;this.type===_y&&(Ye("WebGLShadowMap: PCFSoftShadowMap has been deprecated. Using PCFShadowMap instead."),this.type=vc);const M=s.getRenderTarget(),C=s.getActiveCubeFace(),I=s.getActiveMipmapLevel(),P=s.state;P.setBlending(Qt),P.buffers.depth.getReversed()===!0?P.buffers.color.setClear(0,0,0,0):P.buffers.color.setClear(1,1,1,1),P.buffers.depth.setTest(!0),P.setScissorTest(!1);const k=f!==this.type;k&&E.traverse(function(A){A.material&&(Array.isArray(A.material)?A.material.forEach(B=>B.needsUpdate=!0):A.material.needsUpdate=!0)});for(let A=0,B=b.length;Ah||n.y>h)&&(n.x>h&&(r.x=Math.floor(h/q.x),n.x=r.x*q.x,H.mapSize.x=r.x),n.y>h&&(r.y=Math.floor(h/q.y),n.y=r.y*q.y,H.mapSize.y=r.y));const G=s.state.buffers.depth.getReversed();if(H.camera._reversedDepth=G,H.map===null||k===!0){if(H.map!==null&&(H.map.depthTexture!==null&&(H.map.depthTexture.dispose(),H.map.depthTexture=null),H.map.dispose()),this.type===Ho){if(F.isPointLight){Ye("WebGLShadowMap: VSM shadow maps are not supported for PointLights. Use PCF or BasicShadowMap instead.");continue}H.map=new bi(n.x,n.y,{format:Ea,type:_i,minFilter:At,magFilter:At,generateMipmaps:!1}),H.map.texture.name=F.name+".shadowMap",H.map.depthTexture=new Wr(n.x,n.y,Pi),H.map.depthTexture.name=F.name+".shadowMapDepth",H.map.depthTexture.format=Ds,H.map.depthTexture.compareFunction=null,H.map.depthTexture.minFilter=Zt,H.map.depthTexture.magFilter=Zt}else F.isPointLight?(H.map=new f0(n.x),H.map.depthTexture=new Hx(n.x,Zn)):(H.map=new bi(n.x,n.y),H.map.depthTexture=new Wr(n.x,n.y,Zn)),H.map.depthTexture.name=F.name+".shadowMap",H.map.depthTexture.format=Ds,this.type===vc?(H.map.depthTexture.compareFunction=G?pu:uu,H.map.depthTexture.minFilter=At,H.map.depthTexture.magFilter=At):(H.map.depthTexture.compareFunction=null,H.map.depthTexture.minFilter=Zt,H.map.depthTexture.magFilter=Zt);H.camera.updateProjectionMatrix()}const re=H.map.isWebGLCubeRenderTarget?6:1;for(let Y=0;Y0||E.map&&E.alphaTest>0||E.alphaToCoverage===!0){const P=C.uuid,k=E.uuid;let A=c[P];A===void 0&&(A={},c[P]=A);let B=A[k];B===void 0&&(B=C.clone(),A[k]=B,E.addEventListener("dispose",S)),C=B}if(C.visible=E.visible,C.wireframe=E.wireframe,M===Ho?C.side=E.shadowSide!==null?E.shadowSide:E.side:C.side=E.shadowSide!==null?E.shadowSide:d[E.side],C.alphaMap=E.alphaMap,C.alphaTest=E.alphaToCoverage===!0?.5:E.alphaTest,C.map=E.map,C.clipShadows=E.clipShadows,C.clippingPlanes=E.clippingPlanes,C.clipIntersection=E.clipIntersection,C.displacementMap=E.displacementMap,C.displacementScale=E.displacementScale,C.displacementBias=E.displacementBias,C.wireframeLinewidth=E.wireframeLinewidth,C.linewidth=E.linewidth,w.isPointLight===!0&&C.isMeshDistanceMaterial===!0){const P=s.properties.get(C);P.light=w}return C}function _(b,E,w,M,C){if(b.visible===!1)return;if(b.layers.test(E.layers)&&(b.isMesh||b.isLine||b.isPoints)&&(b.castShadow||b.receiveShadow&&C===Ho)&&(!b.frustumCulled||i.intersectsObject(b))){b.modelViewMatrix.multiplyMatrices(w.matrixWorldInverse,b.matrixWorld);const k=e.update(b),A=b.material;if(Array.isArray(A)){const B=k.groups;for(let F=0,H=B.length;F=1):q.indexOf("OpenGL ES")!==-1&&(H=parseFloat(/^OpenGL ES (\d)/.exec(q)[1]),F=H>=2);let G=null,re={};const Y=s.getParameter(s.SCISSOR_BOX),$=s.getParameter(s.VIEWPORT),_e=new Pt().fromArray(Y),Te=new Pt().fromArray($);function be(z,xe,ge,Le){const pe=new Uint8Array(4),ne=s.createTexture();s.bindTexture(z,ne),s.texParameteri(z,s.TEXTURE_MIN_FILTER,s.NEAREST),s.texParameteri(z,s.TEXTURE_MAG_FILTER,s.NEAREST);for(let Ne=0;Ne"u"?!1:/OculusBrowser/g.test(navigator.userAgent),c=new me,h=new WeakMap;let d;const p=new WeakMap;let u=!1;try{u=typeof OffscreenCanvas<"u"&&new OffscreenCanvas(1,1).getContext("2d")!==null}catch{}function v(L,T){return u?new OffscreenCanvas(L,T):Ic("canvas")}function g(L,T,U){let j=1;const K=ee(L);if((K.width>U||K.height>U)&&(j=U/Math.max(K.width,K.height)),j<1)if(typeof HTMLImageElement<"u"&&L instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&L instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&L instanceof ImageBitmap||typeof VideoFrame<"u"&&L instanceof VideoFrame){const Z=Math.floor(j*K.width),Pe=Math.floor(j*K.height);d===void 0&&(d=v(Z,Pe));const ve=T?v(Z,Pe):d;return ve.width=Z,ve.height=Pe,ve.getContext("2d").drawImage(L,0,0,Z,Pe),Ye("WebGLRenderer: Texture has been resized from ("+K.width+"x"+K.height+") to ("+Z+"x"+Pe+")."),ve}else return"data"in L&&Ye("WebGLRenderer: Image in DataTexture is too big ("+K.width+"x"+K.height+")."),L;return L}function m(L){return L.generateMipmaps}function f(L){s.generateMipmap(L)}function y(L){return L.isWebGLCubeRenderTarget?s.TEXTURE_CUBE_MAP:L.isWebGL3DRenderTarget?s.TEXTURE_3D:L.isWebGLArrayRenderTarget||L.isCompressedArrayTexture?s.TEXTURE_2D_ARRAY:s.TEXTURE_2D}function x(L,T,U,j,K=!1){if(L!==null){if(s[L]!==void 0)return s[L];Ye("WebGLRenderer: Attempt to use non-existing WebGL internal format '"+L+"'")}let Z=T;if(T===s.RED&&(U===s.FLOAT&&(Z=s.R32F),U===s.HALF_FLOAT&&(Z=s.R16F),U===s.UNSIGNED_BYTE&&(Z=s.R8)),T===s.RED_INTEGER&&(U===s.UNSIGNED_BYTE&&(Z=s.R8UI),U===s.UNSIGNED_SHORT&&(Z=s.R16UI),U===s.UNSIGNED_INT&&(Z=s.R32UI),U===s.BYTE&&(Z=s.R8I),U===s.SHORT&&(Z=s.R16I),U===s.INT&&(Z=s.R32I)),T===s.RG&&(U===s.FLOAT&&(Z=s.RG32F),U===s.HALF_FLOAT&&(Z=s.RG16F),U===s.UNSIGNED_BYTE&&(Z=s.RG8)),T===s.RG_INTEGER&&(U===s.UNSIGNED_BYTE&&(Z=s.RG8UI),U===s.UNSIGNED_SHORT&&(Z=s.RG16UI),U===s.UNSIGNED_INT&&(Z=s.RG32UI),U===s.BYTE&&(Z=s.RG8I),U===s.SHORT&&(Z=s.RG16I),U===s.INT&&(Z=s.RG32I)),T===s.RGB_INTEGER&&(U===s.UNSIGNED_BYTE&&(Z=s.RGB8UI),U===s.UNSIGNED_SHORT&&(Z=s.RGB16UI),U===s.UNSIGNED_INT&&(Z=s.RGB32UI),U===s.BYTE&&(Z=s.RGB8I),U===s.SHORT&&(Z=s.RGB16I),U===s.INT&&(Z=s.RGB32I)),T===s.RGBA_INTEGER&&(U===s.UNSIGNED_BYTE&&(Z=s.RGBA8UI),U===s.UNSIGNED_SHORT&&(Z=s.RGBA16UI),U===s.UNSIGNED_INT&&(Z=s.RGBA32UI),U===s.BYTE&&(Z=s.RGBA8I),U===s.SHORT&&(Z=s.RGBA16I),U===s.INT&&(Z=s.RGBA32I)),T===s.RGB&&(U===s.UNSIGNED_INT_5_9_9_9_REV&&(Z=s.RGB9_E5),U===s.UNSIGNED_INT_10F_11F_11F_REV&&(Z=s.R11F_G11F_B10F)),T===s.RGBA){const Pe=K?Pc:Et.getTransfer(j);U===s.FLOAT&&(Z=s.RGBA32F),U===s.HALF_FLOAT&&(Z=s.RGBA16F),U===s.UNSIGNED_BYTE&&(Z=Pe===Bt?s.SRGB8_ALPHA8:s.RGBA8),U===s.UNSIGNED_SHORT_4_4_4_4&&(Z=s.RGBA4),U===s.UNSIGNED_SHORT_5_5_5_1&&(Z=s.RGB5_A1)}return(Z===s.R16F||Z===s.R32F||Z===s.RG16F||Z===s.RG32F||Z===s.RGBA16F||Z===s.RGBA32F)&&e.get("EXT_color_buffer_float"),Z}function _(L,T){let U;return L?T===null||T===Zn||T===Dr?U=s.DEPTH24_STENCIL8:T===Pi?U=s.DEPTH32F_STENCIL8:T===jo&&(U=s.DEPTH24_STENCIL8,Ye("DepthTexture: 16 bit depth attachment is not supported with stencil. Using 24-bit attachment.")):T===null||T===Zn||T===Dr?U=s.DEPTH_COMPONENT24:T===Pi?U=s.DEPTH_COMPONENT32F:T===jo&&(U=s.DEPTH_COMPONENT16),U}function S(L,T){return m(L)===!0||L.isFramebufferTexture&&L.minFilter!==Zt&&L.minFilter!==At?Math.log2(Math.max(T.width,T.height))+1:L.mipmaps!==void 0&&L.mipmaps.length>0?L.mipmaps.length:L.isCompressedTexture&&Array.isArray(L.image)?T.mipmaps.length:1}function b(L){const T=L.target;T.removeEventListener("dispose",b),w(T),T.isVideoTexture&&h.delete(T)}function E(L){const T=L.target;T.removeEventListener("dispose",E),C(T)}function w(L){const T=i.get(L);if(T.__webglInit===void 0)return;const U=L.source,j=p.get(U);if(j){const K=j[T.__cacheKey];K.usedTimes--,K.usedTimes===0&&M(L),Object.keys(j).length===0&&p.delete(U)}i.remove(L)}function M(L){const T=i.get(L);s.deleteTexture(T.__webglTexture);const U=L.source,j=p.get(U);delete j[T.__cacheKey],a.memory.textures--}function C(L){const T=i.get(L);if(L.depthTexture&&(L.depthTexture.dispose(),i.remove(L.depthTexture)),L.isWebGLCubeRenderTarget)for(let j=0;j<6;j++){if(Array.isArray(T.__webglFramebuffer[j]))for(let K=0;K=n.maxTextures&&Ye("WebGLTextures: Trying to use "+L+" texture units while this GPU supports only "+n.maxTextures),I+=1,L}function A(L){const T=[];return T.push(L.wrapS),T.push(L.wrapT),T.push(L.wrapR||0),T.push(L.magFilter),T.push(L.minFilter),T.push(L.anisotropy),T.push(L.internalFormat),T.push(L.format),T.push(L.type),T.push(L.generateMipmaps),T.push(L.premultiplyAlpha),T.push(L.flipY),T.push(L.unpackAlignment),T.push(L.colorSpace),T.join()}function B(L,T){const U=i.get(L);if(L.isVideoTexture&&de(L),L.isRenderTargetTexture===!1&&L.isExternalTexture!==!0&&L.version>0&&U.__version!==L.version){const j=L.image;if(j===null)Ye("WebGLRenderer: Texture marked for update but no image data found.");else if(j.complete===!1)Ye("WebGLRenderer: Texture marked for update but image is incomplete");else{J(U,L,T);return}}else L.isExternalTexture&&(U.__webglTexture=L.sourceTexture?L.sourceTexture:null);t.bindTexture(s.TEXTURE_2D,U.__webglTexture,s.TEXTURE0+T)}function F(L,T){const U=i.get(L);if(L.isRenderTargetTexture===!1&&L.version>0&&U.__version!==L.version){J(U,L,T);return}else L.isExternalTexture&&(U.__webglTexture=L.sourceTexture?L.sourceTexture:null);t.bindTexture(s.TEXTURE_2D_ARRAY,U.__webglTexture,s.TEXTURE0+T)}function H(L,T){const U=i.get(L);if(L.isRenderTargetTexture===!1&&L.version>0&&U.__version!==L.version){J(U,L,T);return}t.bindTexture(s.TEXTURE_3D,U.__webglTexture,s.TEXTURE0+T)}function q(L,T){const U=i.get(L);if(L.isCubeDepthTexture!==!0&&L.version>0&&U.__version!==L.version){oe(U,L,T);return}t.bindTexture(s.TEXTURE_CUBE_MAP,U.__webglTexture,s.TEXTURE0+T)}const G={[Ji]:s.REPEAT,[cn]:s.CLAMP_TO_EDGE,[Wo]:s.MIRRORED_REPEAT},re={[Zt]:s.NEAREST,[Ed]:s.NEAREST_MIPMAP_NEAREST,[wa]:s.NEAREST_MIPMAP_LINEAR,[At]:s.LINEAR,[Xo]:s.LINEAR_MIPMAP_NEAREST,[qn]:s.LINEAR_MIPMAP_LINEAR},Y={[Wy]:s.NEVER,[Yy]:s.ALWAYS,[Xy]:s.LESS,[uu]:s.LEQUAL,[jy]:s.EQUAL,[pu]:s.GEQUAL,[qy]:s.GREATER,[Zy]:s.NOTEQUAL};function $(L,T){if(T.type===Pi&&e.has("OES_texture_float_linear")===!1&&(T.magFilter===At||T.magFilter===Xo||T.magFilter===wa||T.magFilter===qn||T.minFilter===At||T.minFilter===Xo||T.minFilter===wa||T.minFilter===qn)&&Ye("WebGLRenderer: Unable to use linear filtering with floating point textures. OES_texture_float_linear not supported on this device."),s.texParameteri(L,s.TEXTURE_WRAP_S,G[T.wrapS]),s.texParameteri(L,s.TEXTURE_WRAP_T,G[T.wrapT]),(L===s.TEXTURE_3D||L===s.TEXTURE_2D_ARRAY)&&s.texParameteri(L,s.TEXTURE_WRAP_R,G[T.wrapR]),s.texParameteri(L,s.TEXTURE_MAG_FILTER,re[T.magFilter]),s.texParameteri(L,s.TEXTURE_MIN_FILTER,re[T.minFilter]),T.compareFunction&&(s.texParameteri(L,s.TEXTURE_COMPARE_MODE,s.COMPARE_REF_TO_TEXTURE),s.texParameteri(L,s.TEXTURE_COMPARE_FUNC,Y[T.compareFunction])),e.has("EXT_texture_filter_anisotropic")===!0){if(T.magFilter===Zt||T.minFilter!==wa&&T.minFilter!==qn||T.type===Pi&&e.has("OES_texture_float_linear")===!1)return;if(T.anisotropy>1||i.get(T).__currentAnisotropy){const U=e.get("EXT_texture_filter_anisotropic");s.texParameterf(L,U.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(T.anisotropy,n.getMaxAnisotropy())),i.get(T).__currentAnisotropy=T.anisotropy}}}function _e(L,T){let U=!1;L.__webglInit===void 0&&(L.__webglInit=!0,T.addEventListener("dispose",b));const j=T.source;let K=p.get(j);K===void 0&&(K={},p.set(j,K));const Z=A(T);if(Z!==L.__cacheKey){K[Z]===void 0&&(K[Z]={texture:s.createTexture(),usedTimes:0},a.memory.textures++,U=!0),K[Z].usedTimes++;const Pe=K[L.__cacheKey];Pe!==void 0&&(K[L.__cacheKey].usedTimes--,Pe.usedTimes===0&&M(T)),L.__cacheKey=Z,L.__webglTexture=K[Z].texture}return U}function Te(L,T,U){return Math.floor(Math.floor(L/U)/T)}function be(L,T,U,j){const Z=L.updateRanges;if(Z.length===0)t.texSubImage2D(s.TEXTURE_2D,0,0,0,T.width,T.height,U,j,T.data);else{Z.sort((le,ye)=>le.start-ye.start);let Pe=0;for(let le=1;le0){z&&xe&&t.texStorage2D(s.TEXTURE_2D,Le,Oe,Xe[0].width,Xe[0].height);for(let pe=0,ne=Xe.length;pe0){const Ne=c0(Se.width,Se.height,T.format,T.type);for(const Ge of T.layerUpdates){const pt=Se.data.subarray(Ge*Ne/Se.data.BYTES_PER_ELEMENT,(Ge+1)*Ne/Se.data.BYTES_PER_ELEMENT);t.compressedTexSubImage3D(s.TEXTURE_2D_ARRAY,pe,0,0,Ge,Se.width,Se.height,1,ye,pt)}T.clearLayerUpdates()}else t.compressedTexSubImage3D(s.TEXTURE_2D_ARRAY,pe,0,0,0,Se.width,Se.height,le.depth,ye,Se.data)}else t.compressedTexImage3D(s.TEXTURE_2D_ARRAY,pe,Oe,Se.width,Se.height,le.depth,0,Se.data,0,0);else Ye("WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()");else z?ge&&t.texSubImage3D(s.TEXTURE_2D_ARRAY,pe,0,0,0,Se.width,Se.height,le.depth,ye,ze,Se.data):t.texImage3D(s.TEXTURE_2D_ARRAY,pe,Oe,Se.width,Se.height,le.depth,0,ye,ze,Se.data)}else{z&&xe&&t.texStorage2D(s.TEXTURE_2D,Le,Oe,Xe[0].width,Xe[0].height);for(let pe=0,ne=Xe.length;pe0){const pe=c0(le.width,le.height,T.format,T.type);for(const ne of T.layerUpdates){const Ne=le.data.subarray(ne*pe/le.data.BYTES_PER_ELEMENT,(ne+1)*pe/le.data.BYTES_PER_ELEMENT);t.texSubImage3D(s.TEXTURE_2D_ARRAY,0,0,0,ne,le.width,le.height,1,ye,ze,Ne)}T.clearLayerUpdates()}else t.texSubImage3D(s.TEXTURE_2D_ARRAY,0,0,0,0,le.width,le.height,le.depth,ye,ze,le.data)}else t.texImage3D(s.TEXTURE_2D_ARRAY,0,Oe,le.width,le.height,le.depth,0,ye,ze,le.data);else if(T.isData3DTexture)z?(xe&&t.texStorage3D(s.TEXTURE_3D,Le,Oe,le.width,le.height,le.depth),ge&&t.texSubImage3D(s.TEXTURE_3D,0,0,0,0,le.width,le.height,le.depth,ye,ze,le.data)):t.texImage3D(s.TEXTURE_3D,0,Oe,le.width,le.height,le.depth,0,ye,ze,le.data);else if(T.isFramebufferTexture){if(xe)if(z)t.texStorage2D(s.TEXTURE_2D,Le,Oe,le.width,le.height);else{let pe=le.width,ne=le.height;for(let Ne=0;Ne>=1,ne>>=1}}else if(Xe.length>0){if(z&&xe){const pe=ee(Xe[0]);t.texStorage2D(s.TEXTURE_2D,Le,Oe,pe.width,pe.height)}for(let pe=0,ne=Xe.length;pe0&&Le++;const ne=ee(ye[0]);t.texStorage2D(s.TEXTURE_CUBE_MAP,Le,Xe,ne.width,ne.height)}for(let ne=0;ne<6;ne++)if(le){z?ge&&t.texSubImage2D(s.TEXTURE_CUBE_MAP_POSITIVE_X+ne,0,0,0,ye[ne].width,ye[ne].height,Oe,Se,ye[ne].data):t.texImage2D(s.TEXTURE_CUBE_MAP_POSITIVE_X+ne,0,Xe,ye[ne].width,ye[ne].height,0,Oe,Se,ye[ne].data);for(let Ne=0;Ne>Z),ze=Math.max(1,T.height>>Z);K===s.TEXTURE_3D||K===s.TEXTURE_2D_ARRAY?t.texImage3D(K,Z,ke,ye,ze,T.depth,0,Pe,ve,null):t.texImage2D(K,Z,ke,ye,ze,0,Pe,ve,null)}t.bindFramebuffer(s.FRAMEBUFFER,L),te(T)?o.framebufferTexture2DMultisampleEXT(s.FRAMEBUFFER,j,K,le.__webglTexture,0,N(T)):(K===s.TEXTURE_2D||K>=s.TEXTURE_CUBE_MAP_POSITIVE_X&&K<=s.TEXTURE_CUBE_MAP_NEGATIVE_Z)&&s.framebufferTexture2D(s.FRAMEBUFFER,j,K,le.__webglTexture,Z),t.bindFramebuffer(s.FRAMEBUFFER,null)}function Re(L,T,U){if(s.bindRenderbuffer(s.RENDERBUFFER,L),T.depthBuffer){const j=T.depthTexture,K=j&&j.isDepthTexture?j.type:null,Z=_(T.stencilBuffer,K),Pe=T.stencilBuffer?s.DEPTH_STENCIL_ATTACHMENT:s.DEPTH_ATTACHMENT;te(T)?o.renderbufferStorageMultisampleEXT(s.RENDERBUFFER,N(T),Z,T.width,T.height):U?s.renderbufferStorageMultisample(s.RENDERBUFFER,N(T),Z,T.width,T.height):s.renderbufferStorage(s.RENDERBUFFER,Z,T.width,T.height),s.framebufferRenderbuffer(s.FRAMEBUFFER,Pe,s.RENDERBUFFER,L)}else{const j=T.textures;for(let K=0;K{delete T.__boundDepthTexture,delete T.__depthDisposeCallback,j.removeEventListener("dispose",K)};j.addEventListener("dispose",K),T.__depthDisposeCallback=K}T.__boundDepthTexture=j}if(L.depthTexture&&!T.__autoAllocateDepthBuffer)if(U)for(let j=0;j<6;j++)Ie(T.__webglFramebuffer[j],L,j);else{const j=L.texture.mipmaps;j&&j.length>0?Ie(T.__webglFramebuffer[0],L,0):Ie(T.__webglFramebuffer,L,0)}else if(U){T.__webglDepthbuffer=[];for(let j=0;j<6;j++)if(t.bindFramebuffer(s.FRAMEBUFFER,T.__webglFramebuffer[j]),T.__webglDepthbuffer[j]===void 0)T.__webglDepthbuffer[j]=s.createRenderbuffer(),Re(T.__webglDepthbuffer[j],L,!1);else{const K=L.stencilBuffer?s.DEPTH_STENCIL_ATTACHMENT:s.DEPTH_ATTACHMENT,Z=T.__webglDepthbuffer[j];s.bindRenderbuffer(s.RENDERBUFFER,Z),s.framebufferRenderbuffer(s.FRAMEBUFFER,K,s.RENDERBUFFER,Z)}}else{const j=L.texture.mipmaps;if(j&&j.length>0?t.bindFramebuffer(s.FRAMEBUFFER,T.__webglFramebuffer[0]):t.bindFramebuffer(s.FRAMEBUFFER,T.__webglFramebuffer),T.__webglDepthbuffer===void 0)T.__webglDepthbuffer=s.createRenderbuffer(),Re(T.__webglDepthbuffer,L,!1);else{const K=L.stencilBuffer?s.DEPTH_STENCIL_ATTACHMENT:s.DEPTH_ATTACHMENT,Z=T.__webglDepthbuffer;s.bindRenderbuffer(s.RENDERBUFFER,Z),s.framebufferRenderbuffer(s.FRAMEBUFFER,K,s.RENDERBUFFER,Z)}}t.bindFramebuffer(s.FRAMEBUFFER,null)}function tt(L,T,U){const j=i.get(L);T!==void 0&&ue(j.__webglFramebuffer,L,L.texture,s.COLOR_ATTACHMENT0,s.TEXTURE_2D,0),U!==void 0&&Ue(L)}function je(L){const T=L.texture,U=i.get(L),j=i.get(T);L.addEventListener("dispose",E);const K=L.textures,Z=L.isWebGLCubeRenderTarget===!0,Pe=K.length>1;if(Pe||(j.__webglTexture===void 0&&(j.__webglTexture=s.createTexture()),j.__version=T.version,a.memory.textures++),Z){U.__webglFramebuffer=[];for(let ve=0;ve<6;ve++)if(T.mipmaps&&T.mipmaps.length>0){U.__webglFramebuffer[ve]=[];for(let ke=0;ke0){U.__webglFramebuffer=[];for(let ve=0;ve0&&te(L)===!1){U.__webglMultisampledFramebuffer=s.createFramebuffer(),U.__webglColorRenderbuffer=[],t.bindFramebuffer(s.FRAMEBUFFER,U.__webglMultisampledFramebuffer);for(let ve=0;ve0)for(let ke=0;ke0)for(let ke=0;ke0){if(te(L)===!1){const T=L.textures,U=L.width,j=L.height;let K=s.COLOR_BUFFER_BIT;const Z=L.stencilBuffer?s.DEPTH_STENCIL_ATTACHMENT:s.DEPTH_ATTACHMENT,Pe=i.get(L),ve=T.length>1;if(ve)for(let Fe=0;Fe0?t.bindFramebuffer(s.DRAW_FRAMEBUFFER,Pe.__webglFramebuffer[0]):t.bindFramebuffer(s.DRAW_FRAMEBUFFER,Pe.__webglFramebuffer);for(let Fe=0;Fe0&&e.has("WEBGL_multisampled_render_to_texture")===!0&&T.__useRenderToTexture!==!1}function de(L){const T=a.render.frame;h.get(L)!==T&&(h.set(L,T),L.update())}function V(L,T){const U=L.colorSpace,j=L.format,K=L.type;return L.isCompressedTexture===!0||L.isVideoTexture===!0||U!==Zi&&U!==Ys&&(Et.getTransfer(U)===Bt?(j!==qi||K!==hn)&&Ye("WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType."):lt("WebGLTextures: Unsupported texture color space:",U)),T}function ee(L){return typeof HTMLImageElement<"u"&&L instanceof HTMLImageElement?(c.width=L.naturalWidth||L.width,c.height=L.naturalHeight||L.height):typeof VideoFrame<"u"&&L instanceof VideoFrame?(c.width=L.displayWidth,c.height=L.displayHeight):(c.width=L.width,c.height=L.height),c}this.allocateTextureUnit=k,this.resetTextureUnits=P,this.setTexture2D=B,this.setTexture2DArray=F,this.setTexture3D=H,this.setTextureCube=q,this.rebindTextures=tt,this.setupRenderTarget=je,this.updateRenderTargetMipmap=D,this.updateMultisampleRenderTarget=W,this.setupDepthRenderbuffer=Ue,this.setupFrameBufferTexture=ue,this.useMultisampledRTT=te,this.isReversedDepthBuffer=function(){return t.buffers.depth.getReversed()}}function Tb(s,e){function t(i,n=Ys){let r;const a=Et.getTransfer(n);if(i===hn)return s.UNSIGNED_BYTE;if(i===Cd)return s.UNSIGNED_SHORT_4_4_4_4;if(i===Ad)return s.UNSIGNED_SHORT_5_5_5_1;if(i===km)return s.UNSIGNED_INT_5_9_9_9_REV;if(i===Om)return s.UNSIGNED_INT_10F_11F_11F_REV;if(i===Dm)return s.BYTE;if(i===Nm)return s.SHORT;if(i===jo)return s.UNSIGNED_SHORT;if(i===Td)return s.INT;if(i===Zn)return s.UNSIGNED_INT;if(i===Pi)return s.FLOAT;if(i===_i)return s.HALF_FLOAT;if(i===Um)return s.ALPHA;if(i===Bm)return s.RGB;if(i===qi)return s.RGBA;if(i===Ds)return s.DEPTH_COMPONENT;if(i===Ns)return s.DEPTH_STENCIL;if(i===Mc)return s.RED;if(i===Sc)return s.RED_INTEGER;if(i===Ea)return s.RG;if(i===Pd)return s.RG_INTEGER;if(i===Rd)return s.RGBA_INTEGER;if(i===wc||i===Ec||i===Tc||i===Cc)if(a===Bt)if(r=e.get("WEBGL_compressed_texture_s3tc_srgb"),r!==null){if(i===wc)return r.COMPRESSED_SRGB_S3TC_DXT1_EXT;if(i===Ec)return r.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;if(i===Tc)return r.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;if(i===Cc)return r.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}else return null;else if(r=e.get("WEBGL_compressed_texture_s3tc"),r!==null){if(i===wc)return r.COMPRESSED_RGB_S3TC_DXT1_EXT;if(i===Ec)return r.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(i===Tc)return r.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(i===Cc)return r.COMPRESSED_RGBA_S3TC_DXT5_EXT}else return null;if(i===Id||i===Ld||i===Dd||i===Nd)if(r=e.get("WEBGL_compressed_texture_pvrtc"),r!==null){if(i===Id)return r.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(i===Ld)return r.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(i===Dd)return r.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(i===Nd)return r.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}else return null;if(i===kd||i===Od||i===Ud||i===Bd||i===Fd||i===zd||i===Hd)if(r=e.get("WEBGL_compressed_texture_etc"),r!==null){if(i===kd||i===Od)return a===Bt?r.COMPRESSED_SRGB8_ETC2:r.COMPRESSED_RGB8_ETC2;if(i===Ud)return a===Bt?r.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:r.COMPRESSED_RGBA8_ETC2_EAC;if(i===Bd)return r.COMPRESSED_R11_EAC;if(i===Fd)return r.COMPRESSED_SIGNED_R11_EAC;if(i===zd)return r.COMPRESSED_RG11_EAC;if(i===Hd)return r.COMPRESSED_SIGNED_RG11_EAC}else return null;if(i===Vd||i===Gd||i===Wd||i===Xd||i===jd||i===qd||i===Zd||i===Yd||i===$d||i===Kd||i===Jd||i===Qd||i===eu||i===tu)if(r=e.get("WEBGL_compressed_texture_astc"),r!==null){if(i===Vd)return a===Bt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:r.COMPRESSED_RGBA_ASTC_4x4_KHR;if(i===Gd)return a===Bt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:r.COMPRESSED_RGBA_ASTC_5x4_KHR;if(i===Wd)return a===Bt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:r.COMPRESSED_RGBA_ASTC_5x5_KHR;if(i===Xd)return a===Bt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:r.COMPRESSED_RGBA_ASTC_6x5_KHR;if(i===jd)return a===Bt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:r.COMPRESSED_RGBA_ASTC_6x6_KHR;if(i===qd)return a===Bt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:r.COMPRESSED_RGBA_ASTC_8x5_KHR;if(i===Zd)return a===Bt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:r.COMPRESSED_RGBA_ASTC_8x6_KHR;if(i===Yd)return a===Bt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:r.COMPRESSED_RGBA_ASTC_8x8_KHR;if(i===$d)return a===Bt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:r.COMPRESSED_RGBA_ASTC_10x5_KHR;if(i===Kd)return a===Bt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:r.COMPRESSED_RGBA_ASTC_10x6_KHR;if(i===Jd)return a===Bt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:r.COMPRESSED_RGBA_ASTC_10x8_KHR;if(i===Qd)return a===Bt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:r.COMPRESSED_RGBA_ASTC_10x10_KHR;if(i===eu)return a===Bt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:r.COMPRESSED_RGBA_ASTC_12x10_KHR;if(i===tu)return a===Bt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:r.COMPRESSED_RGBA_ASTC_12x12_KHR}else return null;if(i===iu||i===nu||i===su)if(r=e.get("EXT_texture_compression_bptc"),r!==null){if(i===iu)return a===Bt?r.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT:r.COMPRESSED_RGBA_BPTC_UNORM_EXT;if(i===nu)return r.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT;if(i===su)return r.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT}else return null;if(i===ru||i===au||i===ou||i===lu)if(r=e.get("EXT_texture_compression_rgtc"),r!==null){if(i===ru)return r.COMPRESSED_RED_RGTC1_EXT;if(i===au)return r.COMPRESSED_SIGNED_RED_RGTC1_EXT;if(i===ou)return r.COMPRESSED_RED_GREEN_RGTC2_EXT;if(i===lu)return r.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT}else return null;return i===Dr?s.UNSIGNED_INT_24_8:s[i]!==void 0?s[i]:null}return{convert:t}}const F5=` void main() { gl_Position = vec4( position, 1.0 ); }`,z5=` uniform sampler2DArray depthColor; uniform float depthWidth; uniform float depthHeight; void main() { vec2 coord = vec2( gl_FragCoord.x / depthWidth, gl_FragCoord.y / depthHeight ); if ( coord.x >= 1.0 ) { gl_FragDepth = texture( depthColor, vec3( coord.x - 1.0, coord.y, 1 ) ).r; } else { gl_FragDepth = texture( depthColor, vec3( coord.x, coord.y, 0 ) ).r; } }`;class H5{constructor(){this.texture=null,this.mesh=null,this.depthNear=0,this.depthFar=0}init(e,t){if(this.texture===null){const i=new wg(e.texture);(e.depthNear!==t.depthNear||e.depthFar!==t.depthFar)&&(this.depthNear=e.depthNear,this.depthFar=e.depthFar),this.texture=i}}getMesh(e){if(this.texture!==null&&this.mesh===null){const t=e.cameras[0].viewport,i=new Jt({vertexShader:F5,fragmentShader:z5,uniforms:{depthColor:{value:this.texture},depthWidth:{value:t.z},depthHeight:{value:t.w}}});this.mesh=new ht(new vs(20,20),i)}return this.mesh}reset(){this.texture=null,this.mesh=null}getDepthTexture(){return this.texture}}class V5 extends hs{constructor(e,t){super();const i=this;let n=null,r=1,a=null,o="local-floor",l=1,c=null,h=null,d=null,p=null,u=null,v=null;const g=typeof XRWebGLBinding<"u",m=new H5,f={},y=t.getContextAttributes();let x=null,_=null;const S=[],b=[],E=new me;let w=null;const M=new ai;M.viewport=new Pt;const C=new ai;C.viewport=new Pt;const I=[M,C],P=new N_;let k=null,A=null;this.cameraAutoUpdate=!0,this.enabled=!1,this.isPresenting=!1,this.getController=function(J){let oe=S[J];return oe===void 0&&(oe=new xu,S[J]=oe),oe.getTargetRaySpace()},this.getControllerGrip=function(J){let oe=S[J];return oe===void 0&&(oe=new xu,S[J]=oe),oe.getGripSpace()},this.getHand=function(J){let oe=S[J];return oe===void 0&&(oe=new xu,S[J]=oe),oe.getHandSpace()};function B(J){const oe=b.indexOf(J.inputSource);if(oe===-1)return;const ue=S[oe];ue!==void 0&&(ue.update(J.inputSource,J.frame,c||a),ue.dispatchEvent({type:J.type,data:J.inputSource}))}function F(){n.removeEventListener("select",B),n.removeEventListener("selectstart",B),n.removeEventListener("selectend",B),n.removeEventListener("squeeze",B),n.removeEventListener("squeezestart",B),n.removeEventListener("squeezeend",B),n.removeEventListener("end",F),n.removeEventListener("inputsourceschange",H);for(let J=0;J=0&&(b[Re]=null,S[Re].disconnect(ue))}for(let oe=0;oe=b.length){b.push(ue),Re=Ue;break}else if(b[Ue]===null){b[Ue]=ue,Re=Ue;break}if(Re===-1)break}const Ie=S[Re];Ie&&Ie.connect(ue)}}const q=new R,G=new R;function re(J,oe,ue){q.setFromMatrixPosition(oe.matrixWorld),G.setFromMatrixPosition(ue.matrixWorld);const Re=q.distanceTo(G),Ie=oe.projectionMatrix.elements,Ue=ue.projectionMatrix.elements,tt=Ie[14]/(Ie[10]-1),je=Ie[14]/(Ie[10]+1),D=(Ie[9]+1)/Ie[5],ae=(Ie[9]-1)/Ie[5],Q=(Ie[8]-1)/Ie[0],W=(Ue[8]+1)/Ue[0],N=tt*Q,te=tt*W,de=Re/(-Q+W),V=de*-Q;if(oe.matrixWorld.decompose(J.position,J.quaternion,J.scale),J.translateX(V),J.translateZ(de),J.matrixWorld.compose(J.position,J.quaternion,J.scale),J.matrixWorldInverse.copy(J.matrixWorld).invert(),Ie[10]===-1)J.projectionMatrix.copy(oe.projectionMatrix),J.projectionMatrixInverse.copy(oe.projectionMatrixInverse);else{const ee=tt+de,L=je+de,T=N-V,U=te+(Re-V),j=D*je/L*ee,K=ae*je/L*ee;J.projectionMatrix.makePerspective(T,U,j,K,ee,L),J.projectionMatrixInverse.copy(J.projectionMatrix).invert()}}function Y(J,oe){oe===null?J.matrixWorld.copy(J.matrix):J.matrixWorld.multiplyMatrices(oe.matrixWorld,J.matrix),J.matrixWorldInverse.copy(J.matrixWorld).invert()}this.updateCamera=function(J){if(n===null)return;let oe=J.near,ue=J.far;m.texture!==null&&(m.depthNear>0&&(oe=m.depthNear),m.depthFar>0&&(ue=m.depthFar)),P.near=C.near=M.near=oe,P.far=C.far=M.far=ue,(k!==P.near||A!==P.far)&&(n.updateRenderState({depthNear:P.near,depthFar:P.far}),k=P.near,A=P.far),P.layers.mask=J.layers.mask|6,M.layers.mask=P.layers.mask&-5,C.layers.mask=P.layers.mask&-3;const Re=J.parent,Ie=P.cameras;Y(P,Re);for(let Ue=0;Ue0&&(m.alphaTest.value=f.alphaTest);const y=e.get(f),x=y.envMap,_=y.envMapRotation;x&&(m.envMap.value=x,io.copy(_),io.x*=-1,io.y*=-1,io.z*=-1,x.isCubeTexture&&x.isRenderTargetTexture===!1&&(io.y*=-1,io.z*=-1),m.envMapRotation.value.setFromMatrix4(G5.makeRotationFromEuler(io)),m.flipEnvMap.value=x.isCubeTexture&&x.isRenderTargetTexture===!1?-1:1,m.reflectivity.value=f.reflectivity,m.ior.value=f.ior,m.refractionRatio.value=f.refractionRatio),f.lightMap&&(m.lightMap.value=f.lightMap,m.lightMapIntensity.value=f.lightMapIntensity,t(f.lightMap,m.lightMapTransform)),f.aoMap&&(m.aoMap.value=f.aoMap,m.aoMapIntensity.value=f.aoMapIntensity,t(f.aoMap,m.aoMapTransform))}function a(m,f){m.diffuse.value.copy(f.color),m.opacity.value=f.opacity,f.map&&(m.map.value=f.map,t(f.map,m.mapTransform))}function o(m,f){m.dashSize.value=f.dashSize,m.totalSize.value=f.dashSize+f.gapSize,m.scale.value=f.scale}function l(m,f,y,x){m.diffuse.value.copy(f.color),m.opacity.value=f.opacity,m.size.value=f.size*y,m.scale.value=x*.5,f.map&&(m.map.value=f.map,t(f.map,m.uvTransform)),f.alphaMap&&(m.alphaMap.value=f.alphaMap,t(f.alphaMap,m.alphaMapTransform)),f.alphaTest>0&&(m.alphaTest.value=f.alphaTest)}function c(m,f){m.diffuse.value.copy(f.color),m.opacity.value=f.opacity,m.rotation.value=f.rotation,f.map&&(m.map.value=f.map,t(f.map,m.mapTransform)),f.alphaMap&&(m.alphaMap.value=f.alphaMap,t(f.alphaMap,m.alphaMapTransform)),f.alphaTest>0&&(m.alphaTest.value=f.alphaTest)}function h(m,f){m.specular.value.copy(f.specular),m.shininess.value=Math.max(f.shininess,1e-4)}function d(m,f){f.gradientMap&&(m.gradientMap.value=f.gradientMap)}function p(m,f){m.metalness.value=f.metalness,f.metalnessMap&&(m.metalnessMap.value=f.metalnessMap,t(f.metalnessMap,m.metalnessMapTransform)),m.roughness.value=f.roughness,f.roughnessMap&&(m.roughnessMap.value=f.roughnessMap,t(f.roughnessMap,m.roughnessMapTransform)),f.envMap&&(m.envMapIntensity.value=f.envMapIntensity)}function u(m,f,y){m.ior.value=f.ior,f.sheen>0&&(m.sheenColor.value.copy(f.sheenColor).multiplyScalar(f.sheen),m.sheenRoughness.value=f.sheenRoughness,f.sheenColorMap&&(m.sheenColorMap.value=f.sheenColorMap,t(f.sheenColorMap,m.sheenColorMapTransform)),f.sheenRoughnessMap&&(m.sheenRoughnessMap.value=f.sheenRoughnessMap,t(f.sheenRoughnessMap,m.sheenRoughnessMapTransform))),f.clearcoat>0&&(m.clearcoat.value=f.clearcoat,m.clearcoatRoughness.value=f.clearcoatRoughness,f.clearcoatMap&&(m.clearcoatMap.value=f.clearcoatMap,t(f.clearcoatMap,m.clearcoatMapTransform)),f.clearcoatRoughnessMap&&(m.clearcoatRoughnessMap.value=f.clearcoatRoughnessMap,t(f.clearcoatRoughnessMap,m.clearcoatRoughnessMapTransform)),f.clearcoatNormalMap&&(m.clearcoatNormalMap.value=f.clearcoatNormalMap,t(f.clearcoatNormalMap,m.clearcoatNormalMapTransform),m.clearcoatNormalScale.value.copy(f.clearcoatNormalScale),f.side===Bi&&m.clearcoatNormalScale.value.negate())),f.dispersion>0&&(m.dispersion.value=f.dispersion),f.iridescence>0&&(m.iridescence.value=f.iridescence,m.iridescenceIOR.value=f.iridescenceIOR,m.iridescenceThicknessMinimum.value=f.iridescenceThicknessRange[0],m.iridescenceThicknessMaximum.value=f.iridescenceThicknessRange[1],f.iridescenceMap&&(m.iridescenceMap.value=f.iridescenceMap,t(f.iridescenceMap,m.iridescenceMapTransform)),f.iridescenceThicknessMap&&(m.iridescenceThicknessMap.value=f.iridescenceThicknessMap,t(f.iridescenceThicknessMap,m.iridescenceThicknessMapTransform))),f.transmission>0&&(m.transmission.value=f.transmission,m.transmissionSamplerMap.value=y.texture,m.transmissionSamplerSize.value.set(y.width,y.height),f.transmissionMap&&(m.transmissionMap.value=f.transmissionMap,t(f.transmissionMap,m.transmissionMapTransform)),m.thickness.value=f.thickness,f.thicknessMap&&(m.thicknessMap.value=f.thicknessMap,t(f.thicknessMap,m.thicknessMapTransform)),m.attenuationDistance.value=f.attenuationDistance,m.attenuationColor.value.copy(f.attenuationColor)),f.anisotropy>0&&(m.anisotropyVector.value.set(f.anisotropy*Math.cos(f.anisotropyRotation),f.anisotropy*Math.sin(f.anisotropyRotation)),f.anisotropyMap&&(m.anisotropyMap.value=f.anisotropyMap,t(f.anisotropyMap,m.anisotropyMapTransform))),m.specularIntensity.value=f.specularIntensity,m.specularColor.value.copy(f.specularColor),f.specularColorMap&&(m.specularColorMap.value=f.specularColorMap,t(f.specularColorMap,m.specularColorMapTransform)),f.specularIntensityMap&&(m.specularIntensityMap.value=f.specularIntensityMap,t(f.specularIntensityMap,m.specularIntensityMapTransform))}function v(m,f){f.matcap&&(m.matcap.value=f.matcap)}function g(m,f){const y=e.get(f).light;m.referencePosition.value.setFromMatrixPosition(y.matrixWorld),m.nearDistance.value=y.shadow.camera.near,m.farDistance.value=y.shadow.camera.far}return{refreshFogUniforms:i,refreshMaterialUniforms:n}}function X5(s,e,t,i){let n={},r={},a=[];const o=s.getParameter(s.MAX_UNIFORM_BUFFER_BINDINGS);function l(y,x){const _=x.program;i.uniformBlockBinding(y,_)}function c(y,x){let _=n[y.id];_===void 0&&(v(y),_=h(y),n[y.id]=_,y.addEventListener("dispose",m));const S=x.program;i.updateUBOMapping(y,S);const b=e.render.frame;r[y.id]!==b&&(p(y),r[y.id]=b)}function h(y){const x=d();y.__bindingPointIndex=x;const _=s.createBuffer(),S=y.__size,b=y.usage;return s.bindBuffer(s.UNIFORM_BUFFER,_),s.bufferData(s.UNIFORM_BUFFER,S,b),s.bindBuffer(s.UNIFORM_BUFFER,null),s.bindBufferBase(s.UNIFORM_BUFFER,x,_),_}function d(){for(let y=0;y0&&(_+=S-b),y.__size=_,y.__cache={},this}function g(y){const x={boundary:0,storage:0};return typeof y=="number"||typeof y=="boolean"?(x.boundary=4,x.storage=4):y.isVector2?(x.boundary=8,x.storage=8):y.isVector3||y.isColor?(x.boundary=16,x.storage=12):y.isVector4?(x.boundary=16,x.storage=16):y.isMatrix3?(x.boundary=48,x.storage=48):y.isMatrix4?(x.boundary=64,x.storage=64):y.isTexture?Ye("WebGLRenderer: Texture samplers can not be part of an uniforms group."):Ye("WebGLRenderer: Unsupported uniform value type.",y),x}function m(y){const x=y.target;x.removeEventListener("dispose",m);const _=a.indexOf(x.__bindingPointIndex);a.splice(_,1),s.deleteBuffer(n[x.id]),delete n[x.id],delete r[x.id]}function f(){for(const y in n)s.deleteBuffer(n[y]);a=[],n={},r={}}return{bind:l,update:c,dispose:f}}const j5=new Uint16Array([12469,15057,12620,14925,13266,14620,13807,14376,14323,13990,14545,13625,14713,13328,14840,12882,14931,12528,14996,12233,15039,11829,15066,11525,15080,11295,15085,10976,15082,10705,15073,10495,13880,14564,13898,14542,13977,14430,14158,14124,14393,13732,14556,13410,14702,12996,14814,12596,14891,12291,14937,11834,14957,11489,14958,11194,14943,10803,14921,10506,14893,10278,14858,9960,14484,14039,14487,14025,14499,13941,14524,13740,14574,13468,14654,13106,14743,12678,14818,12344,14867,11893,14889,11509,14893,11180,14881,10751,14852,10428,14812,10128,14765,9754,14712,9466,14764,13480,14764,13475,14766,13440,14766,13347,14769,13070,14786,12713,14816,12387,14844,11957,14860,11549,14868,11215,14855,10751,14825,10403,14782,10044,14729,9651,14666,9352,14599,9029,14967,12835,14966,12831,14963,12804,14954,12723,14936,12564,14917,12347,14900,11958,14886,11569,14878,11247,14859,10765,14828,10401,14784,10011,14727,9600,14660,9289,14586,8893,14508,8533,15111,12234,15110,12234,15104,12216,15092,12156,15067,12010,15028,11776,14981,11500,14942,11205,14902,10752,14861,10393,14812,9991,14752,9570,14682,9252,14603,8808,14519,8445,14431,8145,15209,11449,15208,11451,15202,11451,15190,11438,15163,11384,15117,11274,15055,10979,14994,10648,14932,10343,14871,9936,14803,9532,14729,9218,14645,8742,14556,8381,14461,8020,14365,7603,15273,10603,15272,10607,15267,10619,15256,10631,15231,10614,15182,10535,15118,10389,15042,10167,14963,9787,14883,9447,14800,9115,14710,8665,14615,8318,14514,7911,14411,7507,14279,7198,15314,9675,15313,9683,15309,9712,15298,9759,15277,9797,15229,9773,15166,9668,15084,9487,14995,9274,14898,8910,14800,8539,14697,8234,14590,7790,14479,7409,14367,7067,14178,6621,15337,8619,15337,8631,15333,8677,15325,8769,15305,8871,15264,8940,15202,8909,15119,8775,15022,8565,14916,8328,14804,8009,14688,7614,14569,7287,14448,6888,14321,6483,14088,6171,15350,7402,15350,7419,15347,7480,15340,7613,15322,7804,15287,7973,15229,8057,15148,8012,15046,7846,14933,7611,14810,7357,14682,7069,14552,6656,14421,6316,14251,5948,14007,5528,15356,5942,15356,5977,15353,6119,15348,6294,15332,6551,15302,6824,15249,7044,15171,7122,15070,7050,14949,6861,14818,6611,14679,6349,14538,6067,14398,5651,14189,5311,13935,4958,15359,4123,15359,4153,15356,4296,15353,4646,15338,5160,15311,5508,15263,5829,15188,6042,15088,6094,14966,6001,14826,5796,14678,5543,14527,5287,14377,4985,14133,4586,13869,4257,15360,1563,15360,1642,15358,2076,15354,2636,15341,3350,15317,4019,15273,4429,15203,4732,15105,4911,14981,4932,14836,4818,14679,4621,14517,4386,14359,4156,14083,3795,13808,3437,15360,122,15360,137,15358,285,15355,636,15344,1274,15322,2177,15281,2765,15215,3223,15120,3451,14995,3569,14846,3567,14681,3466,14511,3305,14344,3121,14037,2800,13753,2467,15360,0,15360,1,15359,21,15355,89,15346,253,15325,479,15287,796,15225,1148,15133,1492,15008,1749,14856,1882,14685,1886,14506,1783,14324,1608,13996,1398,13702,1183]);let zs=null;function q5(){return zs===null&&(zs=new Sn(j5,16,16,Ea,_i),zs.name="DFG_LUT",zs.minFilter=At,zs.magFilter=At,zs.wrapS=cn,zs.wrapT=cn,zs.generateMipmaps=!1,zs.needsUpdate=!0),zs}class mh{constructor(e={}){const{canvas:t=Ky(),context:i=null,depth:n=!0,stencil:r=!1,alpha:a=!1,antialias:o=!1,premultipliedAlpha:l=!0,preserveDrawingBuffer:c=!1,powerPreference:h="default",failIfMajorPerformanceCaveat:d=!1,reversedDepthBuffer:p=!1,outputBufferType:u=hn}=e;this.isWebGLRenderer=!0;let v;if(i!==null){if(typeof WebGLRenderingContext<"u"&&i instanceof WebGLRenderingContext)throw new Error("THREE.WebGLRenderer: WebGL 1 is not supported since r163.");v=i.getContextAttributes().alpha}else v=a;const g=u,m=new Set([Rd,Pd,Sc]),f=new Set([hn,Zn,jo,Dr,Cd,Ad]),y=new Uint32Array(4),x=new Int32Array(4);let _=null,S=null;const b=[],E=[];let w=null;this.domElement=t,this.debug={checkShaderErrors:!0,onShaderError:null},this.autoClear=!0,this.autoClearColor=!0,this.autoClearDepth=!0,this.autoClearStencil=!0,this.sortObjects=!0,this.clippingPlanes=[],this.localClippingEnabled=!1,this.toneMapping=ji,this.toneMappingExposure=1,this.transmissionResolutionScale=1;const M=this;let C=!1;this._outputColorSpace=li;let I=0,P=0,k=null,A=-1,B=null;const F=new Pt,H=new Pt;let q=null;const G=new We(0);let re=0,Y=t.width,$=t.height,_e=1,Te=null,be=null;const J=new Pt(0,0,Y,$),oe=new Pt(0,0,Y,$);let ue=!1;const Re=new pl;let Ie=!1,Ue=!1;const tt=new qe,je=new R,D=new Pt,ae={background:null,fog:null,environment:null,overrideMaterial:null,isScene:!0};let Q=!1;function W(){return k===null?_e:1}let N=i;function te(X,fe){return t.getContext(X,fe)}try{const X={alpha:!0,depth:n,stencil:r,antialias:o,premultipliedAlpha:l,preserveDrawingBuffer:c,powerPreference:h,failIfMajorPerformanceCaveat:d};if("setAttribute"in t&&t.setAttribute("data-engine",`three.js r${zo}`),t.addEventListener("webglcontextlost",Ne,!1),t.addEventListener("webglcontextrestored",Ge,!1),t.addEventListener("webglcontextcreationerror",pt,!1),N===null){const fe="webgl2";if(N=te(fe,X),N===null)throw te(fe)?new Error("Error creating WebGL context with your selected attributes."):new Error("Error creating WebGL context.")}}catch(X){throw lt("WebGLRenderer: "+X.message),X}let de,V,ee,L,T,U,j,K,Z,Pe,ve,ke,Fe,le,ye,ze,Oe,Se,Xe,z,xe,ge,Le;function pe(){de=new YP(N),de.init(),xe=new Tb(N,de),V=new HP(N,de,e,xe),ee=new U5(N,de),V.reversedDepthBuffer&&p&&ee.buffers.depth.setReversed(!0),L=new JP(N),T=new S5,U=new B5(N,de,ee,T,V,xe,L),j=new ZP(M),K=new UC(N),ge=new FP(N,K),Z=new $P(N,K,L,ge),Pe=new e4(N,Z,K,ge,L),Se=new QP(N,V,U),ye=new VP(T),ve=new M5(M,j,de,V,ge,ye),ke=new W5(M,T),Fe=new E5,le=new I5(de),Oe=new BP(M,j,ee,Pe,v,l),ze=new O5(M,Pe,V),Le=new X5(N,L,V,ee),Xe=new zP(N,de,L),z=new KP(N,de,L),L.programs=ve.programs,M.capabilities=V,M.extensions=de,M.properties=T,M.renderLists=Fe,M.shadowMap=ze,M.state=ee,M.info=L}pe(),g!==hn&&(w=new i4(g,t.width,t.height,n,r));const ne=new V5(M,N);this.xr=ne,this.getContext=function(){return N},this.getContextAttributes=function(){return N.getContextAttributes()},this.forceContextLoss=function(){const X=de.get("WEBGL_lose_context");X&&X.loseContext()},this.forceContextRestore=function(){const X=de.get("WEBGL_lose_context");X&&X.restoreContext()},this.getPixelRatio=function(){return _e},this.setPixelRatio=function(X){X!==void 0&&(_e=X,this.setSize(Y,$,!1))},this.getSize=function(X){return X.set(Y,$)},this.setSize=function(X,fe,Ae=!0){if(ne.isPresenting){Ye("WebGLRenderer: Can't change size while VR device is presenting.");return}Y=X,$=fe,t.width=Math.floor(X*_e),t.height=Math.floor(fe*_e),Ae===!0&&(t.style.width=X+"px",t.style.height=fe+"px"),w!==null&&w.setSize(t.width,t.height),this.setViewport(0,0,X,fe)},this.getDrawingBufferSize=function(X){return X.set(Y*_e,$*_e).floor()},this.setDrawingBufferSize=function(X,fe,Ae){Y=X,$=fe,_e=Ae,t.width=Math.floor(X*Ae),t.height=Math.floor(fe*Ae),this.setViewport(0,0,X,fe)},this.setEffects=function(X){if(g===hn){console.error("THREE.WebGLRenderer: setEffects() requires outputBufferType set to HalfFloatType or FloatType.");return}if(X){for(let fe=0;fe{function ie(){if(Me.forEach(function(he){T.get(he).currentProgram.isReady()&&Me.delete(he)}),Me.size===0){O(X);return}setTimeout(ie,10)}de.get("KHR_parallel_shader_compile")!==null?ie():setTimeout(ie,10)})};let pc=null;function uy(X){pc&&pc(X)}function wm(){Ps.stop()}function id(){Ps.start()}const Ps=new Q_;Ps.setAnimationLoop(uy),typeof self<"u"&&Ps.setContext(self),this.setAnimationLoop=function(X){pc=X,ne.setAnimationLoop(X),X===null?Ps.stop():Ps.start()},ne.addEventListener("sessionstart",wm),ne.addEventListener("sessionend",id),this.render=function(X,fe){if(fe!==void 0&&fe.isCamera!==!0){lt("WebGLRenderer.render: camera is not an instance of THREE.Camera.");return}if(C===!0)return;const Ae=ne.enabled===!0&&ne.isPresenting===!0,Me=w!==null&&(k===null||Ae)&&w.begin(M,k);if(X.matrixWorldAutoUpdate===!0&&X.updateMatrixWorld(),fe.parent===null&&fe.matrixWorldAutoUpdate===!0&&fe.updateMatrixWorld(),ne.enabled===!0&&ne.isPresenting===!0&&(w===null||w.isCompositing()===!1)&&(ne.cameraAutoUpdate===!0&&ne.updateCamera(fe),fe=ne.getCamera()),X.isScene===!0&&X.onBeforeRender(M,X,fe,k),S=le.get(X,E.length),S.init(fe),E.push(S),tt.multiplyMatrices(fe.projectionMatrix,fe.matrixWorldInverse),Re.setFromProjectionMatrix(tt,Nn,fe.reversedDepth),Ue=this.localClippingEnabled,Ie=ye.init(this.clippingPlanes,Ue),_=Fe.get(X,b.length),_.init(),b.push(_),ne.enabled===!0&&ne.isPresenting===!0){const he=M.xr.getDepthSensingMesh();he!==null&&nd(he,fe,-1/0,M.sortObjects)}nd(X,fe,0,M.sortObjects),_.finish(),M.sortObjects===!0&&_.sort(Te,be),Q=ne.enabled===!1||ne.isPresenting===!1||ne.hasDepthSensing()===!1,Q&&Oe.addToRenderList(_,X),this.info.render.frame++,Ie===!0&&ye.beginShadows();const O=S.state.shadowsArray;if(ze.render(O,X,fe),Ie===!0&&ye.endShadows(),this.info.autoReset===!0&&this.info.reset(),(Me&&w.hasRenderPass())===!1){const he=_.opaque,ce=_.transmissive;if(S.setupLights(),fe.isArrayCamera){const se=fe.cameras;if(ce.length>0)for(let we=0,He=se.length;we0&&rd(he,ce,X,fe),Q&&Oe.render(X),sd(_,X,fe)}k!==null&&P===0&&(U.updateMultisampleRenderTarget(k),U.updateRenderTargetMipmap(k)),Me&&w.end(M),X.isScene===!0&&X.onAfterRender(M,X,fe),ge.resetDefaultState(),A=-1,B=null,E.pop(),E.length>0?(S=E[E.length-1],Ie===!0&&ye.setGlobalState(M.clippingPlanes,S.state.camera)):S=null,b.pop(),b.length>0?_=b[b.length-1]:_=null};function nd(X,fe,Ae,Me){if(X.visible===!1)return;if(X.layers.test(fe.layers)){if(X.isGroup)Ae=X.renderOrder;else if(X.isLOD)X.autoUpdate===!0&&X.update(fe);else if(X.isLight)S.pushLight(X),X.castShadow&&S.pushShadow(X);else if(X.isSprite){if(!X.frustumCulled||Re.intersectsSprite(X)){Me&&D.setFromMatrixPosition(X.matrixWorld).applyMatrix4(tt);const he=Pe.update(X),ce=X.material;ce.visible&&_.push(X,he,ce,Ae,D.z,null)}}else if((X.isMesh||X.isLine||X.isPoints)&&(!X.frustumCulled||Re.intersectsObject(X))){const he=Pe.update(X),ce=X.material;if(Me&&(X.boundingSphere!==void 0?(X.boundingSphere===null&&X.computeBoundingSphere(),D.copy(X.boundingSphere.center)):(he.boundingSphere===null&&he.computeBoundingSphere(),D.copy(he.boundingSphere.center)),D.applyMatrix4(X.matrixWorld).applyMatrix4(tt)),Array.isArray(ce)){const se=he.groups;for(let we=0,He=se.length;we0&&cs(O,fe,Ae),ie.length>0&&cs(ie,fe,Ae),he.length>0&&cs(he,fe,Ae),ee.buffers.depth.setTest(!0),ee.buffers.depth.setMask(!0),ee.buffers.color.setMask(!0),ee.setPolygonOffset(!1)}function rd(X,fe,Ae,Me){if((Ae.isScene===!0?Ae.overrideMaterial:null)!==null)return;if(S.state.transmissionRenderTarget[Me.id]===void 0){const Be=de.has("EXT_color_buffer_half_float")||de.has("EXT_color_buffer_float");S.state.transmissionRenderTarget[Me.id]=new bi(1,1,{generateMipmaps:!0,type:Be?_i:hn,minFilter:qn,samples:Math.max(4,V.samples),stencilBuffer:r,resolveDepthBuffer:!1,resolveStencilBuffer:!1,colorSpace:Et.workingColorSpace})}const ie=S.state.transmissionRenderTarget[Me.id],he=Me.viewport||F;ie.setSize(he.z*M.transmissionResolutionScale,he.w*M.transmissionResolutionScale);const ce=M.getRenderTarget(),se=M.getActiveCubeFace(),we=M.getActiveMipmapLevel();M.setRenderTarget(ie),M.getClearColor(G),re=M.getClearAlpha(),re<1&&M.setClearColor(16777215,.5),M.clear(),Q&&Oe.render(Ae);const He=M.toneMapping;M.toneMapping=ji;const Ve=Me.viewport;if(Me.viewport!==void 0&&(Me.viewport=void 0),S.setupLightsView(Me),Ie===!0&&ye.setGlobalState(M.clippingPlanes,Me),cs(X,Ae,Me),U.updateMultisampleRenderTarget(ie),U.updateRenderTargetMipmap(ie),de.has("WEBGL_multisampled_render_to_texture")===!1){let Be=!1;for(let Ke=0,st=fe.length;Ke0),Be=!!Ae.morphAttributes.position,Ke=!!Ae.morphAttributes.normal,st=!!Ae.morphAttributes.color;let it=ji;Me.toneMapped&&(k===null||k.isXRRenderTarget===!0)&&(it=M.toneMapping);const rt=Ae.morphAttributes.position||Ae.morphAttributes.normal||Ae.morphAttributes.color,mt=rt!==void 0?rt.length:0,Ze=T.get(Me),Ct=S.state.lights;if(Ie===!0&&(Ue===!0||X!==B)){const _t=X===B&&Me.id===A;ye.setState(Me,X,_t)}let ot=!1;Me.version===Ze.__version?(Ze.needsLights&&Ze.lightsStateVersion!==Ct.state.version||Ze.outputColorSpace!==ce||O.isBatchedMesh&&Ze.batching===!1||!O.isBatchedMesh&&Ze.batching===!0||O.isBatchedMesh&&Ze.batchingColor===!0&&O.colorTexture===null||O.isBatchedMesh&&Ze.batchingColor===!1&&O.colorTexture!==null||O.isInstancedMesh&&Ze.instancing===!1||!O.isInstancedMesh&&Ze.instancing===!0||O.isSkinnedMesh&&Ze.skinning===!1||!O.isSkinnedMesh&&Ze.skinning===!0||O.isInstancedMesh&&Ze.instancingColor===!0&&O.instanceColor===null||O.isInstancedMesh&&Ze.instancingColor===!1&&O.instanceColor!==null||O.isInstancedMesh&&Ze.instancingMorph===!0&&O.morphTexture===null||O.isInstancedMesh&&Ze.instancingMorph===!1&&O.morphTexture!==null||Ze.envMap!==we||Me.fog===!0&&Ze.fog!==ie||Ze.numClippingPlanes!==void 0&&(Ze.numClippingPlanes!==ye.numPlanes||Ze.numIntersection!==ye.numIntersection)||Ze.vertexAlphas!==He||Ze.vertexTangents!==Ve||Ze.morphTargets!==Be||Ze.morphNormals!==Ke||Ze.morphColors!==st||Ze.toneMapping!==it||Ze.morphTargetsCount!==mt)&&(ot=!0):(ot=!0,Ze.__version=Me.version);let nt=Ze.currentProgram;ot===!0&&(nt=Uo(Me,fe,O));let qt=!1,Ki=!1,Xi=!1;const kt=nt.getUniforms(),Ft=Ze.uniforms;if(ee.useProgram(nt.program)&&(qt=!0,Ki=!0,Xi=!0),Me.id!==A&&(A=Me.id,Ki=!0),qt||B!==X){ee.buffers.depth.getReversed()&&X.reversedDepth!==!0&&(X._reversedDepth=!0,X.updateProjectionMatrix()),kt.setValue(N,"projectionMatrix",X.projectionMatrix),kt.setValue(N,"viewMatrix",X.matrixWorldInverse);const oi=kt.map.cameraPosition;oi!==void 0&&oi.setValue(N,je.setFromMatrixPosition(X.matrixWorld)),V.logarithmicDepthBuffer&&kt.setValue(N,"logDepthBufFC",2/(Math.log(X.far+1)/Math.LN2)),(Me.isMeshPhongMaterial||Me.isMeshToonMaterial||Me.isMeshLambertMaterial||Me.isMeshBasicMaterial||Me.isMeshStandardMaterial||Me.isShaderMaterial)&&kt.setValue(N,"isOrthographic",X.isOrthographicCamera===!0),B!==X&&(B=X,Ki=!0,Xi=!0)}if(Ze.needsLights&&(Ct.state.directionalShadowMap.length>0&&kt.setValue(N,"directionalShadowMap",Ct.state.directionalShadowMap,U),Ct.state.spotShadowMap.length>0&&kt.setValue(N,"spotShadowMap",Ct.state.spotShadowMap,U),Ct.state.pointShadowMap.length>0&&kt.setValue(N,"pointShadowMap",Ct.state.pointShadowMap,U)),O.isSkinnedMesh){kt.setOptional(N,O,"bindMatrix"),kt.setOptional(N,O,"bindMatrixInverse");const _t=O.skeleton;_t&&(_t.boneTexture===null&&_t.computeBoneTexture(),kt.setValue(N,"boneTexture",_t.boneTexture,U))}O.isBatchedMesh&&(kt.setOptional(N,O,"batchingTexture"),kt.setValue(N,"batchingTexture",O._matricesTexture,U),kt.setOptional(N,O,"batchingIdTexture"),kt.setValue(N,"batchingIdTexture",O._indirectTexture,U),kt.setOptional(N,O,"batchingColorTexture"),O._colorsTexture!==null&&kt.setValue(N,"batchingColorTexture",O._colorsTexture,U));const In=Ae.morphAttributes;if((In.position!==void 0||In.normal!==void 0||In.color!==void 0)&&Se.update(O,Ae,nt),(Ki||Ze.receiveShadow!==O.receiveShadow)&&(Ze.receiveShadow=O.receiveShadow,kt.setValue(N,"receiveShadow",O.receiveShadow)),(Me.isMeshStandardMaterial||Me.isMeshLambertMaterial||Me.isMeshPhongMaterial)&&Me.envMap===null&&fe.environment!==null&&(Ft.envMapIntensity.value=fe.environmentIntensity),Ft.dfgLUT!==void 0&&(Ft.dfgLUT.value=q5()),Ki&&(kt.setValue(N,"toneMappingExposure",M.toneMappingExposure),Ze.needsLights&&mc(Ft,Xi),ie&&Me.fog===!0&&ke.refreshFogUniforms(Ft,ie),ke.refreshMaterialUniforms(Ft,Me,_e,$,S.state.transmissionRenderTarget[X.id]),Op.upload(N,ad(Ze),Ft,U)),Me.isShaderMaterial&&Me.uniformsNeedUpdate===!0&&(Op.upload(N,ad(Ze),Ft,U),Me.uniformsNeedUpdate=!1),Me.isSpriteMaterial&&kt.setValue(N,"center",O.center),kt.setValue(N,"modelViewMatrix",O.modelViewMatrix),kt.setValue(N,"normalMatrix",O.normalMatrix),kt.setValue(N,"modelMatrix",O.matrixWorld),Me.isShaderMaterial||Me.isRawShaderMaterial){const _t=Me.uniformsGroups;for(let oi=0,Ui=_t.length;oi0&&U.useMultisampledRTT(X)===!1?Me=T.get(X).__webglMultisampledFramebuffer:Array.isArray(we)?Me=we[Ae]:Me=we,F.copy(X.viewport),H.copy(X.scissor),q=X.scissorTest}else F.copy(J).multiplyScalar(_e).floor(),H.copy(oe).multiplyScalar(_e).floor(),q=ue;if(Ae!==0&&(Me=Cm),ee.bindFramebuffer(N.FRAMEBUFFER,Me)&&ee.drawBuffers(X,Me),ee.viewport(F),ee.scissor(H),ee.setScissorTest(q),O){const ce=T.get(X.texture);N.framebufferTexture2D(N.FRAMEBUFFER,N.COLOR_ATTACHMENT0,N.TEXTURE_CUBE_MAP_POSITIVE_X+fe,ce.__webglTexture,Ae)}else if(ie){const ce=fe;for(let se=0;se1&&N.readBuffer(N.COLOR_ATTACHMENT0+ce),!V.textureFormatReadable(He)){lt("WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.");return}if(!V.textureTypeReadable(Ve)){lt("WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.");return}fe>=0&&fe<=X.width-Me&&Ae>=0&&Ae<=X.height-O&&N.readPixels(fe,Ae,Me,O,xe.convert(He),xe.convert(Ve),ie)}finally{const we=k!==null?T.get(k).__webglFramebuffer:null;ee.bindFramebuffer(N.FRAMEBUFFER,we)}}},this.readRenderTargetPixelsAsync=async function(X,fe,Ae,Me,O,ie,he,ce=0){if(!(X&&X.isWebGLRenderTarget))throw new Error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");let se=T.get(X).__webglFramebuffer;if(X.isWebGLCubeRenderTarget&&he!==void 0&&(se=se[he]),se)if(fe>=0&&fe<=X.width-Me&&Ae>=0&&Ae<=X.height-O){ee.bindFramebuffer(N.FRAMEBUFFER,se);const we=X.textures[ce],He=we.format,Ve=we.type;if(X.textures.length>1&&N.readBuffer(N.COLOR_ATTACHMENT0+ce),!V.textureFormatReadable(He))throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in RGBA or implementation defined format.");if(!V.textureTypeReadable(Ve))throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in UnsignedByteType or implementation defined type.");const Be=N.createBuffer();N.bindBuffer(N.PIXEL_PACK_BUFFER,Be),N.bufferData(N.PIXEL_PACK_BUFFER,ie.byteLength,N.STREAM_READ),N.readPixels(fe,Ae,Me,O,xe.convert(He),xe.convert(Ve),0);const Ke=k!==null?T.get(k).__webglFramebuffer:null;ee.bindFramebuffer(N.FRAMEBUFFER,Ke);const st=N.fenceSync(N.SYNC_GPU_COMMANDS_COMPLETE,0);return N.flush(),await ZE(N,st,4),N.bindBuffer(N.PIXEL_PACK_BUFFER,Be),N.getBufferSubData(N.PIXEL_PACK_BUFFER,0,ie),N.deleteBuffer(Be),N.deleteSync(st),ie}else throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: requested read bounds are out of range.")},this.copyFramebufferToTexture=function(X,fe=null,Ae=0){const Me=Math.pow(2,-Ae),O=Math.floor(X.image.width*Me),ie=Math.floor(X.image.height*Me),he=fe!==null?fe.x:0,ce=fe!==null?fe.y:0;U.setTexture2D(X,0),N.copyTexSubImage2D(N.TEXTURE_2D,Ae,0,0,he,ce,O,ie),ee.unbindTexture()};const py=N.createFramebuffer(),fy=N.createFramebuffer();this.copyTextureToTexture=function(X,fe,Ae=null,Me=null,O=0,ie=0){let he,ce,se,we,He,Ve,Be,Ke,st;const it=X.isCompressedTexture?X.mipmaps[ie]:X.image;if(Ae!==null)he=Ae.max.x-Ae.min.x,ce=Ae.max.y-Ae.min.y,se=Ae.isBox3?Ae.max.z-Ae.min.z:1,we=Ae.min.x,He=Ae.min.y,Ve=Ae.isBox3?Ae.min.z:0;else{const Ft=Math.pow(2,-O);he=Math.floor(it.width*Ft),ce=Math.floor(it.height*Ft),X.isDataArrayTexture?se=it.depth:X.isData3DTexture?se=Math.floor(it.depth*Ft):se=1,we=0,He=0,Ve=0}Me!==null?(Be=Me.x,Ke=Me.y,st=Me.z):(Be=0,Ke=0,st=0);const rt=xe.convert(fe.format),mt=xe.convert(fe.type);let Ze;fe.isData3DTexture?(U.setTexture3D(fe,0),Ze=N.TEXTURE_3D):fe.isDataArrayTexture||fe.isCompressedArrayTexture?(U.setTexture2DArray(fe,0),Ze=N.TEXTURE_2D_ARRAY):(U.setTexture2D(fe,0),Ze=N.TEXTURE_2D),N.pixelStorei(N.UNPACK_FLIP_Y_WEBGL,fe.flipY),N.pixelStorei(N.UNPACK_PREMULTIPLY_ALPHA_WEBGL,fe.premultiplyAlpha),N.pixelStorei(N.UNPACK_ALIGNMENT,fe.unpackAlignment);const Ct=N.getParameter(N.UNPACK_ROW_LENGTH),ot=N.getParameter(N.UNPACK_IMAGE_HEIGHT),nt=N.getParameter(N.UNPACK_SKIP_PIXELS),qt=N.getParameter(N.UNPACK_SKIP_ROWS),Ki=N.getParameter(N.UNPACK_SKIP_IMAGES);N.pixelStorei(N.UNPACK_ROW_LENGTH,it.width),N.pixelStorei(N.UNPACK_IMAGE_HEIGHT,it.height),N.pixelStorei(N.UNPACK_SKIP_PIXELS,we),N.pixelStorei(N.UNPACK_SKIP_ROWS,He),N.pixelStorei(N.UNPACK_SKIP_IMAGES,Ve);const Xi=X.isDataArrayTexture||X.isData3DTexture,kt=fe.isDataArrayTexture||fe.isData3DTexture;if(X.isDepthTexture){const Ft=T.get(X),In=T.get(fe),_t=T.get(Ft.__renderTarget),oi=T.get(In.__renderTarget);ee.bindFramebuffer(N.READ_FRAMEBUFFER,_t.__webglFramebuffer),ee.bindFramebuffer(N.DRAW_FRAMEBUFFER,oi.__webglFramebuffer);for(let Ui=0;Ui0?a[0].point:null}screenToWorldWithDepth(e,t,i=0){const n=this.screenToNormalized(e,t);this.raycaster.setFromCamera(n,this.camera);const r=new R;return this.raycaster.ray.at(i,r),r}updateCamera(e){this.camera=e}updateRenderer(e){this.renderer=e}updateScene(e){this.scene=e}}var Bp=(s=>(s.PERSPECTIVE="perspective",s.ORTHOGRAPHIC="orthographic",s))(Bp||{});class Jr{static MIN_VISIBLE_HEIGHT=1e-4;static MIN_CAMERA_DISTANCE=1e-4;engine;perspectiveCamera;orthographicCamera;constructor(e){this.engine=e,this.perspectiveCamera=new ai(20,this.engine.container.clientWidth/this.engine.container.clientHeight,.1,1e3),this.perspectiveCamera.position.set(2,2,2),this.perspectiveCamera.lookAt(0,0,0);const t=50,i=this.engine.container.clientWidth/this.engine.container.clientHeight;this.orthographicCamera=new rn(t*i/-2,t*i/2,t/2,t/-2,.1,1e3)}getCameraAspect(){const e=this.engine.container?.clientWidth??1,t=this.engine.container?.clientHeight??1;return t>0?e/t:1}getPerspectiveVisibleHeight(e,t){const i=Math.max(e.position.distanceTo(t),Jr.MIN_CAMERA_DISTANCE),n=Lt.degToRad(e.getEffectiveFOV()*.5);return Math.max(2*i*Math.tan(n),Jr.MIN_VISIBLE_HEIGHT)}getOrthographicVisibleHeight(e=this.orthographicCamera){return Math.max((e.top-e.bottom)/e.zoom,Jr.MIN_VISIBLE_HEIGHT)}setOrthographicVisibleHeight(e,t=this.orthographicCamera){const i=Math.max(e,Jr.MIN_VISIBLE_HEIGHT),n=this.getCameraAspect(),r=i*.5,a=r*n;t.left=-a,t.right=a,t.top=r,t.bottom=-r}getViewDirection(e,t,i){const n=new R().subVectors(e,t);return n.lengthSq()>Jr.MIN_CAMERA_DISTANCE?n.normalize():new R(0,0,1).applyQuaternion(i).normalize()}updateComposerCamera(){if(!this.engine.composerModule?.composer)return;const e=this.engine.camera,t=this.engine.composerModule.composer;if(t.passes)for(const i of t.passes)i.camera!==void 0&&(i.camera=e)}applySwitchedCamera(e,t){this.engine.camera=e,this.engine.scene.camera=e,this.engine.controls?.target&&this.engine.controls.target.copy(t),this.engine.controls&&(this.engine.controls.object=e),this.engine.controlModule.orbitControls.object=e,this.engine.controlModule.firstPersonControls.camera=e,e.updateProjectionMatrix?.(),e.updateMatrixWorld(),this.updateComposerCamera(),this.engine.controls?.update&&this.engine.controls.update(),this.engine.worldToScreen=new zt(this.engine.camera,this.engine.renderer,this.engine.scene)}switchCurrentCamera(){this.engine.camera===this.perspectiveCamera?this.switchToOrthographicCamera():this.switchToPerspectiveCamera()}setPerspectiveFov(e,t){const i=this.perspectiveCamera,n=i.fov,r=Math.max(1,Math.min(120,e));if(t?.adjustDistance!==!1&&this.engine.camera===i&&this.engine.controls?.target){const a=this.engine.controls.target.clone(),o=i.position.clone(),l=o.distanceTo(a);if(l>1e-6){const c=Lt.degToRad(n*.5),h=Lt.degToRad(r*.5),d=Math.tan(c)/Math.tan(h),p=l*d,u=new R().subVectors(o,a).normalize();i.position.copy(a).add(u.multiplyScalar(p))}}i.fov=r,i.updateProjectionMatrix()}switchToPerspectiveCamera(){if(!this.engine.controls)return;const e=this.engine.camera;if(!e)return;const t=e.position.clone(),i=this.engine.controls.target.clone(),n=e.quaternion.clone(),r=e.up.clone(),a=this.perspectiveCamera,o=this.getViewDirection(t,i,n),l=e instanceof rn?this.getOrthographicVisibleHeight(e):this.getPerspectiveVisibleHeight(e,i),c=Lt.degToRad(a.getEffectiveFOV()*.5),h=Math.max(l/(2*Math.tan(c)),Jr.MIN_CAMERA_DISTANCE);a.near=e.near,a.far=e.far,a.aspect=this.getCameraAspect(),a.up.copy(r),a.position.copy(i).add(o.multiplyScalar(h)),a.lookAt(i),this.applySwitchedCamera(a,i)}switchToOrthographicCamera(){if(!this.engine.controls)return;const e=this.engine.camera;if(!e)return;e.position.clone();const t=this.engine.controls.target.clone(),i=e.up.clone(),n=this.orthographicCamera,r=e instanceof ai?this.getPerspectiveVisibleHeight(e,t):this.getOrthographicVisibleHeight(e);n.near=e.near,n.far=e.far,n.zoom=1,this.setOrthographicVisibleHeight(r,n),n.up.copy(i),n.lookAt(t),this.applySwitchedCamera(n,t)}getCameraType(){return this.engine.camera===this.perspectiveCamera?"perspective":this.engine.camera===this.orthographicCamera?"orthographic":"perspective"}getCameraPose(){const e=this.engine.camera,t=this.getCameraType(),i={type:t,position:{x:e.position.x,y:e.position.y,z:e.position.z},rotation:{x:e.rotation.x,y:e.rotation.y,z:e.rotation.z},quaternion:{x:e.quaternion.x,y:e.quaternion.y,z:e.quaternion.z,w:e.quaternion.w}};return this.engine.controls?.target&&(i.target={x:this.engine.controls.target.x,y:this.engine.controls.target.y,z:this.engine.controls.target.z}),t==="orthographic"&&(i.zoom=e.zoom,i.orthographicHeight=this.getOrthographicVisibleHeight(e)),i}restoreCameraPose(e){this.getCameraType()!==e.type&&(e.type==="perspective"?this.switchToPerspectiveCamera():this.switchToOrthographicCamera());const t=this.engine.camera;if(t.position.set(e.position.x,e.position.y,e.position.z),e.quaternion?t.quaternion.set(e.quaternion.x,e.quaternion.y,e.quaternion.z,e.quaternion.w):e.rotation&&t.rotation.set(e.rotation.x,e.rotation.y,e.rotation.z),e.target&&this.engine.controls?.target&&this.engine.controls.target.set(e.target.x,e.target.y,e.target.z),e.type==="orthographic"){const i=t;e.orthographicHeight!==void 0&&this.setOrthographicVisibleHeight(e.orthographicHeight,i),e.zoom!==void 0&&(i.zoom=e.zoom),i.updateProjectionMatrix()}t.updateMatrix(),t.updateMatrixWorld(!0),this.engine.controls?.update&&this.engine.controls.update()}setViewFromOriginAndDirection(e,t,i){const n=new R(t.x,t.y,t.z).normalize(),r=new R(e.x,e.y,e.z);if(i==null||i<=0){const l=this.engine.octreeBox?.getBoundingBox?.();if(l&&l.min&&l.max){const c=new R().subVectors(l.max,l.min);i=Math.max(c.x,c.y,c.z)*1.2}else i=50}const a=r.clone().add(n.clone().negate().multiplyScalar(i)),o=this.engine.camera;o&&(o.position.copy(a),o.lookAt(r),this.engine.controls?.target&&this.engine.controls.target.copy(r),this.engine.controls?.update&&this.engine.controls.update(),o.updateMatrix(),o.updateMatrixWorld(!0))}}class $5{engine;deviceType;constructor(e){this.engine=e,this.deviceType=this.detectDeviceType()}detectDeviceType(){const e=[/Android/i,/webOS/i,/iPhone/i,/iPad/i,/iPod/i,/BlackBerry/i,/Windows Phone/i,/Mobile/i],t=navigator.userAgent||globalThis.opera,i=e.some(c=>c.test(t)),n="ontouchstart"in globalThis||navigator.maxTouchPoints>0||navigator.msMaxTouchPoints>0,r=globalThis.screen.width,a=globalThis.screen.height,o=r<=768||a<=768,l=(globalThis.devicePixelRatio||1)>=2;return i||n&&o||n&&l?"mobile":"PC"}getDeviceType(){return this.deviceType}isMobile(){return this.deviceType==="mobile"}isPC(){return this.deviceType==="PC"}redetectDeviceType(){return this.deviceType=this.detectDeviceType(),this.deviceType}getContainerSize(){return{width:this.engine.container.clientWidth,height:this.engine.container.clientHeight}}}const x0="181",K5=0,Cb=1,J5=2,Ab=1,Pb=2,ar=3,Qr=0,En=1,or=2,lr=0,Cl=1,Rb=2,Ib=3,Lb=4,Q5=5,no=100,eR=101,tR=102,iR=103,nR=104,sR=200,rR=201,aR=202,oR=203,_0=204,b0=205,lR=206,cR=207,hR=208,dR=209,uR=210,pR=211,fR=212,mR=213,gR=214,M0=0,S0=1,w0=2,Al=3,E0=4,T0=5,C0=6,A0=7,Db=0,vR=1,yR=2,ea=0,xR=1,_R=2,bR=3,MR=4,SR=5,wR=6,ER=7,Nb=300,Pl=301,Rl=302,P0=303,R0=304,Fp=306,I0=1e3,cr=1001,L0=1002,Fn=1003,TR=1004,zp=1005,es=1006,D0=1007,so=1008,hr=1009,kb=1010,Ob=1011,gh=1012,N0=1013,ro=1014,dr=1015,Il=1016,k0=1017,O0=1018,vh=1020,Ub=35902,Bb=35899,Fb=1021,zb=1022,xs=1023,yh=1026,xh=1027,Hb=1028,U0=1029,B0=1030,F0=1031,z0=1033,Hp=33776,Vp=33777,Gp=33778,Wp=33779,H0=35840,V0=35841,G0=35842,W0=35843,X0=36196,j0=37492,q0=37496,Z0=37808,Y0=37809,$0=37810,K0=37811,J0=37812,Q0=37813,ev=37814,tv=37815,iv=37816,nv=37817,sv=37818,rv=37819,av=37820,ov=37821,lv=36492,cv=36494,hv=36495,dv=36283,uv=36284,pv=36285,fv=36286,CR=3200,AR=3201,PR=0,RR=1,ta="",zn="srgb",Ll="srgb-linear",Xp="linear",Vt="srgb",Dl=7680,Vb=519,IR=512,LR=513,DR=514,Gb=515,NR=516,kR=517,OR=518,UR=519,Wb=35044,Xb="300 es",Hs=2e3,jp=2001;function jb(s){for(let e=s.length-1;e>=0;--e)if(s[e]>=65535)return!0;return!1}function qp(s){return document.createElementNS("http://www.w3.org/1999/xhtml",s)}function BR(){const s=qp("canvas");return s.style.display="block",s}const qb={};function Zb(...s){const e="THREE."+s.shift();console.log(e,...s)}function yt(...s){const e="THREE."+s.shift();console.warn(e,...s)}function gi(...s){const e="THREE."+s.shift();console.error(e,...s)}function _h(...s){const e=s.join(" ");e in qb||(qb[e]=!0,yt(...s))}function FR(s,e,t){return new Promise(function(i,n){function r(){switch(s.clientWaitSync(e,s.SYNC_FLUSH_COMMANDS_BIT,0)){case s.WAIT_FAILED:n();break;case s.TIMEOUT_EXPIRED:setTimeout(r,t);break;default:i()}}setTimeout(r,t)})}class Nl{addEventListener(e,t){this._listeners===void 0&&(this._listeners={});const i=this._listeners;i[e]===void 0&&(i[e]=[]),i[e].indexOf(t)===-1&&i[e].push(t)}hasEventListener(e,t){const i=this._listeners;return i===void 0?!1:i[e]!==void 0&&i[e].indexOf(t)!==-1}removeEventListener(e,t){const i=this._listeners;if(i===void 0)return;const n=i[e];if(n!==void 0){const r=n.indexOf(t);r!==-1&&n.splice(r,1)}}dispatchEvent(e){const t=this._listeners;if(t===void 0)return;const i=t[e.type];if(i!==void 0){e.target=this;const n=i.slice(0);for(let r=0,a=n.length;r>8&255]+an[s>>16&255]+an[s>>24&255]+"-"+an[e&255]+an[e>>8&255]+"-"+an[e>>16&15|64]+an[e>>24&255]+"-"+an[t&63|128]+an[t>>8&255]+"-"+an[t>>16&255]+an[t>>24&255]+an[i&255]+an[i>>8&255]+an[i>>16&255]+an[i>>24&255]).toLowerCase()}function It(s,e,t){return Math.max(e,Math.min(t,s))}function zR(s,e){return(s%e+e)%e}function vv(s,e,t){return(1-t)*s+t*e}function Mh(s,e){switch(e.constructor){case Float32Array:return s;case Uint32Array:return s/4294967295;case Uint16Array:return s/65535;case Uint8Array:return s/255;case Int32Array:return Math.max(s/2147483647,-1);case Int16Array:return Math.max(s/32767,-1);case Int8Array:return Math.max(s/127,-1);default:throw new Error("Invalid component type.")}}function Tn(s,e){switch(e.constructor){case Float32Array:return s;case Uint32Array:return Math.round(s*4294967295);case Uint16Array:return Math.round(s*65535);case Uint8Array:return Math.round(s*255);case Int32Array:return Math.round(s*2147483647);case Int16Array:return Math.round(s*32767);case Int8Array:return Math.round(s*127);default:throw new Error("Invalid component type.")}}class Gt{constructor(e=0,t=0){Gt.prototype.isVector2=!0,this.x=e,this.y=t}get width(){return this.x}set width(e){this.x=e}get height(){return this.y}set height(e){this.y=e}set(e,t){return this.x=e,this.y=t,this}setScalar(e){return this.x=e,this.y=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y)}copy(e){return this.x=e.x,this.y=e.y,this}add(e){return this.x+=e.x,this.y+=e.y,this}addScalar(e){return this.x+=e,this.y+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this}subScalar(e){return this.x-=e,this.y-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this}multiply(e){return this.x*=e.x,this.y*=e.y,this}multiplyScalar(e){return this.x*=e,this.y*=e,this}divide(e){return this.x/=e.x,this.y/=e.y,this}divideScalar(e){return this.multiplyScalar(1/e)}applyMatrix3(e){const t=this.x,i=this.y,n=e.elements;return this.x=n[0]*t+n[3]*i+n[6],this.y=n[1]*t+n[4]*i+n[7],this}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this}clamp(e,t){return this.x=It(this.x,e.x,t.x),this.y=It(this.y,e.y,t.y),this}clampScalar(e,t){return this.x=It(this.x,e,t),this.y=It(this.y,e,t),this}clampLength(e,t){const i=this.length();return this.divideScalar(i||1).multiplyScalar(It(i,e,t))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this}negate(){return this.x=-this.x,this.y=-this.y,this}dot(e){return this.x*e.x+this.y*e.y}cross(e){return this.x*e.y-this.y*e.x}lengthSq(){return this.x*this.x+this.y*this.y}length(){return Math.sqrt(this.x*this.x+this.y*this.y)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)}normalize(){return this.divideScalar(this.length()||1)}angle(){return Math.atan2(-this.y,-this.x)+Math.PI}angleTo(e){const t=Math.sqrt(this.lengthSq()*e.lengthSq());if(t===0)return Math.PI/2;const i=this.dot(e)/t;return Math.acos(It(i,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){const t=this.x-e.x,i=this.y-e.y;return t*t+i*i}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this}lerpVectors(e,t,i){return this.x=e.x+(t.x-e.x)*i,this.y=e.y+(t.y-e.y)*i,this}equals(e){return e.x===this.x&&e.y===this.y}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this}rotateAround(e,t){const i=Math.cos(t),n=Math.sin(t),r=this.x-e.x,a=this.y-e.y;return this.x=r*i-a*n+e.x,this.y=r*n+a*i+e.y,this}random(){return this.x=Math.random(),this.y=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y}}class Sh{constructor(e=0,t=0,i=0,n=1){this.isQuaternion=!0,this._x=e,this._y=t,this._z=i,this._w=n}static slerpFlat(e,t,i,n,r,a,o){let l=i[n+0],c=i[n+1],h=i[n+2],d=i[n+3],p=r[a+0],u=r[a+1],v=r[a+2],g=r[a+3];if(o<=0){e[t+0]=l,e[t+1]=c,e[t+2]=h,e[t+3]=d;return}if(o>=1){e[t+0]=p,e[t+1]=u,e[t+2]=v,e[t+3]=g;return}if(d!==g||l!==p||c!==u||h!==v){let m=l*p+c*u+h*v+d*g;m<0&&(p=-p,u=-u,v=-v,g=-g,m=-m);let f=1-o;if(m<.9995){const y=Math.acos(m),x=Math.sin(y);f=Math.sin(f*y)/x,o=Math.sin(o*y)/x,l=l*f+p*o,c=c*f+u*o,h=h*f+v*o,d=d*f+g*o}else{l=l*f+p*o,c=c*f+u*o,h=h*f+v*o,d=d*f+g*o;const y=1/Math.sqrt(l*l+c*c+h*h+d*d);l*=y,c*=y,h*=y,d*=y}}e[t]=l,e[t+1]=c,e[t+2]=h,e[t+3]=d}static multiplyQuaternionsFlat(e,t,i,n,r,a){const o=i[n],l=i[n+1],c=i[n+2],h=i[n+3],d=r[a],p=r[a+1],u=r[a+2],v=r[a+3];return e[t]=o*v+h*d+l*u-c*p,e[t+1]=l*v+h*p+c*d-o*u,e[t+2]=c*v+h*u+o*p-l*d,e[t+3]=h*v-o*d-l*p-c*u,e}get x(){return this._x}set x(e){this._x=e,this._onChangeCallback()}get y(){return this._y}set y(e){this._y=e,this._onChangeCallback()}get z(){return this._z}set z(e){this._z=e,this._onChangeCallback()}get w(){return this._w}set w(e){this._w=e,this._onChangeCallback()}set(e,t,i,n){return this._x=e,this._y=t,this._z=i,this._w=n,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._w)}copy(e){return this._x=e.x,this._y=e.y,this._z=e.z,this._w=e.w,this._onChangeCallback(),this}setFromEuler(e,t=!0){const i=e._x,n=e._y,r=e._z,a=e._order,o=Math.cos,l=Math.sin,c=o(i/2),h=o(n/2),d=o(r/2),p=l(i/2),u=l(n/2),v=l(r/2);switch(a){case"XYZ":this._x=p*h*d+c*u*v,this._y=c*u*d-p*h*v,this._z=c*h*v+p*u*d,this._w=c*h*d-p*u*v;break;case"YXZ":this._x=p*h*d+c*u*v,this._y=c*u*d-p*h*v,this._z=c*h*v-p*u*d,this._w=c*h*d+p*u*v;break;case"ZXY":this._x=p*h*d-c*u*v,this._y=c*u*d+p*h*v,this._z=c*h*v+p*u*d,this._w=c*h*d-p*u*v;break;case"ZYX":this._x=p*h*d-c*u*v,this._y=c*u*d+p*h*v,this._z=c*h*v-p*u*d,this._w=c*h*d+p*u*v;break;case"YZX":this._x=p*h*d+c*u*v,this._y=c*u*d+p*h*v,this._z=c*h*v-p*u*d,this._w=c*h*d-p*u*v;break;case"XZY":this._x=p*h*d-c*u*v,this._y=c*u*d-p*h*v,this._z=c*h*v+p*u*d,this._w=c*h*d+p*u*v;break;default:yt("Quaternion: .setFromEuler() encountered an unknown order: "+a)}return t===!0&&this._onChangeCallback(),this}setFromAxisAngle(e,t){const i=t/2,n=Math.sin(i);return this._x=e.x*n,this._y=e.y*n,this._z=e.z*n,this._w=Math.cos(i),this._onChangeCallback(),this}setFromRotationMatrix(e){const t=e.elements,i=t[0],n=t[4],r=t[8],a=t[1],o=t[5],l=t[9],c=t[2],h=t[6],d=t[10],p=i+o+d;if(p>0){const u=.5/Math.sqrt(p+1);this._w=.25/u,this._x=(h-l)*u,this._y=(r-c)*u,this._z=(a-n)*u}else if(i>o&&i>d){const u=2*Math.sqrt(1+i-o-d);this._w=(h-l)/u,this._x=.25*u,this._y=(n+a)/u,this._z=(r+c)/u}else if(o>d){const u=2*Math.sqrt(1+o-i-d);this._w=(r-c)/u,this._x=(n+a)/u,this._y=.25*u,this._z=(l+h)/u}else{const u=2*Math.sqrt(1+d-i-o);this._w=(a-n)/u,this._x=(r+c)/u,this._y=(l+h)/u,this._z=.25*u}return this._onChangeCallback(),this}setFromUnitVectors(e,t){let i=e.dot(t)+1;return i<1e-8?(i=0,Math.abs(e.x)>Math.abs(e.z)?(this._x=-e.y,this._y=e.x,this._z=0,this._w=i):(this._x=0,this._y=-e.z,this._z=e.y,this._w=i)):(this._x=e.y*t.z-e.z*t.y,this._y=e.z*t.x-e.x*t.z,this._z=e.x*t.y-e.y*t.x,this._w=i),this.normalize()}angleTo(e){return 2*Math.acos(Math.abs(It(this.dot(e),-1,1)))}rotateTowards(e,t){const i=this.angleTo(e);if(i===0)return this;const n=Math.min(1,t/i);return this.slerp(e,n),this}identity(){return this.set(0,0,0,1)}invert(){return this.conjugate()}conjugate(){return this._x*=-1,this._y*=-1,this._z*=-1,this._onChangeCallback(),this}dot(e){return this._x*e._x+this._y*e._y+this._z*e._z+this._w*e._w}lengthSq(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w}length(){return Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w)}normalize(){let e=this.length();return e===0?(this._x=0,this._y=0,this._z=0,this._w=1):(e=1/e,this._x=this._x*e,this._y=this._y*e,this._z=this._z*e,this._w=this._w*e),this._onChangeCallback(),this}multiply(e){return this.multiplyQuaternions(this,e)}premultiply(e){return this.multiplyQuaternions(e,this)}multiplyQuaternions(e,t){const i=e._x,n=e._y,r=e._z,a=e._w,o=t._x,l=t._y,c=t._z,h=t._w;return this._x=i*h+a*o+n*c-r*l,this._y=n*h+a*l+r*o-i*c,this._z=r*h+a*c+i*l-n*o,this._w=a*h-i*o-n*l-r*c,this._onChangeCallback(),this}slerp(e,t){if(t<=0)return this;if(t>=1)return this.copy(e);let i=e._x,n=e._y,r=e._z,a=e._w,o=this.dot(e);o<0&&(i=-i,n=-n,r=-r,a=-a,o=-o);let l=1-t;if(o<.9995){const c=Math.acos(o),h=Math.sin(c);l=Math.sin(l*c)/h,t=Math.sin(t*c)/h,this._x=this._x*l+i*t,this._y=this._y*l+n*t,this._z=this._z*l+r*t,this._w=this._w*l+a*t,this._onChangeCallback()}else this._x=this._x*l+i*t,this._y=this._y*l+n*t,this._z=this._z*l+r*t,this._w=this._w*l+a*t,this.normalize();return this}slerpQuaternions(e,t,i){return this.copy(e).slerp(t,i)}random(){const e=2*Math.PI*Math.random(),t=2*Math.PI*Math.random(),i=Math.random(),n=Math.sqrt(1-i),r=Math.sqrt(i);return this.set(n*Math.sin(e),n*Math.cos(e),r*Math.sin(t),r*Math.cos(t))}equals(e){return e._x===this._x&&e._y===this._y&&e._z===this._z&&e._w===this._w}fromArray(e,t=0){return this._x=e[t],this._y=e[t+1],this._z=e[t+2],this._w=e[t+3],this._onChangeCallback(),this}toArray(e=[],t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,e[t+3]=this._w,e}fromBufferAttribute(e,t){return this._x=e.getX(t),this._y=e.getY(t),this._z=e.getZ(t),this._w=e.getW(t),this._onChangeCallback(),this}toJSON(){return this.toArray()}_onChange(e){return this._onChangeCallback=e,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._w}}class De{constructor(e=0,t=0,i=0){De.prototype.isVector3=!0,this.x=e,this.y=t,this.z=i}set(e,t,i){return i===void 0&&(i=this.z),this.x=e,this.y=t,this.z=i,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;case 2:this.z=t;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y,this.z)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this.z=e.z+t.z,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this.z+=e.z*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this.z=e.z-t.z,this}multiply(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this}multiplyVectors(e,t){return this.x=e.x*t.x,this.y=e.y*t.y,this.z=e.z*t.z,this}applyEuler(e){return this.applyQuaternion(Yb.setFromEuler(e))}applyAxisAngle(e,t){return this.applyQuaternion(Yb.setFromAxisAngle(e,t))}applyMatrix3(e){const t=this.x,i=this.y,n=this.z,r=e.elements;return this.x=r[0]*t+r[3]*i+r[6]*n,this.y=r[1]*t+r[4]*i+r[7]*n,this.z=r[2]*t+r[5]*i+r[8]*n,this}applyNormalMatrix(e){return this.applyMatrix3(e).normalize()}applyMatrix4(e){const t=this.x,i=this.y,n=this.z,r=e.elements,a=1/(r[3]*t+r[7]*i+r[11]*n+r[15]);return this.x=(r[0]*t+r[4]*i+r[8]*n+r[12])*a,this.y=(r[1]*t+r[5]*i+r[9]*n+r[13])*a,this.z=(r[2]*t+r[6]*i+r[10]*n+r[14])*a,this}applyQuaternion(e){const t=this.x,i=this.y,n=this.z,r=e.x,a=e.y,o=e.z,l=e.w,c=2*(a*n-o*i),h=2*(o*t-r*n),d=2*(r*i-a*t);return this.x=t+l*c+a*d-o*h,this.y=i+l*h+o*c-r*d,this.z=n+l*d+r*h-a*c,this}project(e){return this.applyMatrix4(e.matrixWorldInverse).applyMatrix4(e.projectionMatrix)}unproject(e){return this.applyMatrix4(e.projectionMatrixInverse).applyMatrix4(e.matrixWorld)}transformDirection(e){const t=this.x,i=this.y,n=this.z,r=e.elements;return this.x=r[0]*t+r[4]*i+r[8]*n,this.y=r[1]*t+r[5]*i+r[9]*n,this.z=r[2]*t+r[6]*i+r[10]*n,this.normalize()}divide(e){return this.x/=e.x,this.y/=e.y,this.z/=e.z,this}divideScalar(e){return this.multiplyScalar(1/e)}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this.z=Math.min(this.z,e.z),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this.z=Math.max(this.z,e.z),this}clamp(e,t){return this.x=It(this.x,e.x,t.x),this.y=It(this.y,e.y,t.y),this.z=It(this.z,e.z,t.z),this}clampScalar(e,t){return this.x=It(this.x,e,t),this.y=It(this.y,e,t),this.z=It(this.z,e,t),this}clampLength(e,t){const i=this.length();return this.divideScalar(i||1).multiplyScalar(It(i,e,t))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)}normalize(){return this.divideScalar(this.length()||1)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this.z+=(e.z-this.z)*t,this}lerpVectors(e,t,i){return this.x=e.x+(t.x-e.x)*i,this.y=e.y+(t.y-e.y)*i,this.z=e.z+(t.z-e.z)*i,this}cross(e){return this.crossVectors(this,e)}crossVectors(e,t){const i=e.x,n=e.y,r=e.z,a=t.x,o=t.y,l=t.z;return this.x=n*l-r*o,this.y=r*a-i*l,this.z=i*o-n*a,this}projectOnVector(e){const t=e.lengthSq();if(t===0)return this.set(0,0,0);const i=e.dot(this)/t;return this.copy(e).multiplyScalar(i)}projectOnPlane(e){return yv.copy(this).projectOnVector(e),this.sub(yv)}reflect(e){return this.sub(yv.copy(e).multiplyScalar(2*this.dot(e)))}angleTo(e){const t=Math.sqrt(this.lengthSq()*e.lengthSq());if(t===0)return Math.PI/2;const i=this.dot(e)/t;return Math.acos(It(i,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){const t=this.x-e.x,i=this.y-e.y,n=this.z-e.z;return t*t+i*i+n*n}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)+Math.abs(this.z-e.z)}setFromSpherical(e){return this.setFromSphericalCoords(e.radius,e.phi,e.theta)}setFromSphericalCoords(e,t,i){const n=Math.sin(t)*e;return this.x=n*Math.sin(i),this.y=Math.cos(t)*e,this.z=n*Math.cos(i),this}setFromCylindrical(e){return this.setFromCylindricalCoords(e.radius,e.theta,e.y)}setFromCylindricalCoords(e,t,i){return this.x=e*Math.sin(t),this.y=i,this.z=e*Math.cos(t),this}setFromMatrixPosition(e){const t=e.elements;return this.x=t[12],this.y=t[13],this.z=t[14],this}setFromMatrixScale(e){const t=this.setFromMatrixColumn(e,0).length(),i=this.setFromMatrixColumn(e,1).length(),n=this.setFromMatrixColumn(e,2).length();return this.x=t,this.y=i,this.z=n,this}setFromMatrixColumn(e,t){return this.fromArray(e.elements,t*4)}setFromMatrix3Column(e,t){return this.fromArray(e.elements,t*3)}setFromEuler(e){return this.x=e._x,this.y=e._y,this.z=e._z,this}setFromColor(e){return this.x=e.r,this.y=e.g,this.z=e.b,this}equals(e){return e.x===this.x&&e.y===this.y&&e.z===this.z}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this.z=e[t+2],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e[t+2]=this.z,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this.z=e.getZ(t),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this}randomDirection(){const e=Math.random()*Math.PI*2,t=Math.random()*2-1,i=Math.sqrt(1-t*t);return this.x=i*Math.cos(e),this.y=t,this.z=i*Math.sin(e),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z}}const yv=new De,Yb=new Sh;class Mt{constructor(e,t,i,n,r,a,o,l,c){Mt.prototype.isMatrix3=!0,this.elements=[1,0,0,0,1,0,0,0,1],e!==void 0&&this.set(e,t,i,n,r,a,o,l,c)}set(e,t,i,n,r,a,o,l,c){const h=this.elements;return h[0]=e,h[1]=n,h[2]=o,h[3]=t,h[4]=r,h[5]=l,h[6]=i,h[7]=a,h[8]=c,this}identity(){return this.set(1,0,0,0,1,0,0,0,1),this}copy(e){const t=this.elements,i=e.elements;return t[0]=i[0],t[1]=i[1],t[2]=i[2],t[3]=i[3],t[4]=i[4],t[5]=i[5],t[6]=i[6],t[7]=i[7],t[8]=i[8],this}extractBasis(e,t,i){return e.setFromMatrix3Column(this,0),t.setFromMatrix3Column(this,1),i.setFromMatrix3Column(this,2),this}setFromMatrix4(e){const t=e.elements;return this.set(t[0],t[4],t[8],t[1],t[5],t[9],t[2],t[6],t[10]),this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,t){const i=e.elements,n=t.elements,r=this.elements,a=i[0],o=i[3],l=i[6],c=i[1],h=i[4],d=i[7],p=i[2],u=i[5],v=i[8],g=n[0],m=n[3],f=n[6],y=n[1],x=n[4],_=n[7],S=n[2],b=n[5],E=n[8];return r[0]=a*g+o*y+l*S,r[3]=a*m+o*x+l*b,r[6]=a*f+o*_+l*E,r[1]=c*g+h*y+d*S,r[4]=c*m+h*x+d*b,r[7]=c*f+h*_+d*E,r[2]=p*g+u*y+v*S,r[5]=p*m+u*x+v*b,r[8]=p*f+u*_+v*E,this}multiplyScalar(e){const t=this.elements;return t[0]*=e,t[3]*=e,t[6]*=e,t[1]*=e,t[4]*=e,t[7]*=e,t[2]*=e,t[5]*=e,t[8]*=e,this}determinant(){const e=this.elements,t=e[0],i=e[1],n=e[2],r=e[3],a=e[4],o=e[5],l=e[6],c=e[7],h=e[8];return t*a*h-t*o*c-i*r*h+i*o*l+n*r*c-n*a*l}invert(){const e=this.elements,t=e[0],i=e[1],n=e[2],r=e[3],a=e[4],o=e[5],l=e[6],c=e[7],h=e[8],d=h*a-o*c,p=o*l-h*r,u=c*r-a*l,v=t*d+i*p+n*u;if(v===0)return this.set(0,0,0,0,0,0,0,0,0);const g=1/v;return e[0]=d*g,e[1]=(n*c-h*i)*g,e[2]=(o*i-n*a)*g,e[3]=p*g,e[4]=(h*t-n*l)*g,e[5]=(n*r-o*t)*g,e[6]=u*g,e[7]=(i*l-c*t)*g,e[8]=(a*t-i*r)*g,this}transpose(){let e;const t=this.elements;return e=t[1],t[1]=t[3],t[3]=e,e=t[2],t[2]=t[6],t[6]=e,e=t[5],t[5]=t[7],t[7]=e,this}getNormalMatrix(e){return this.setFromMatrix4(e).invert().transpose()}transposeIntoArray(e){const t=this.elements;return e[0]=t[0],e[1]=t[3],e[2]=t[6],e[3]=t[1],e[4]=t[4],e[5]=t[7],e[6]=t[2],e[7]=t[5],e[8]=t[8],this}setUvTransform(e,t,i,n,r,a,o){const l=Math.cos(r),c=Math.sin(r);return this.set(i*l,i*c,-i*(l*a+c*o)+a+e,-n*c,n*l,-n*(-c*a+l*o)+o+t,0,0,1),this}scale(e,t){return this.premultiply(xv.makeScale(e,t)),this}rotate(e){return this.premultiply(xv.makeRotation(-e)),this}translate(e,t){return this.premultiply(xv.makeTranslation(e,t)),this}makeTranslation(e,t){return e.isVector2?this.set(1,0,e.x,0,1,e.y,0,0,1):this.set(1,0,e,0,1,t,0,0,1),this}makeRotation(e){const t=Math.cos(e),i=Math.sin(e);return this.set(t,-i,0,i,t,0,0,0,1),this}makeScale(e,t){return this.set(e,0,0,0,t,0,0,0,1),this}equals(e){const t=this.elements,i=e.elements;for(let n=0;n<9;n++)if(t[n]!==i[n])return!1;return!0}fromArray(e,t=0){for(let i=0;i<9;i++)this.elements[i]=e[i+t];return this}toArray(e=[],t=0){const i=this.elements;return e[t]=i[0],e[t+1]=i[1],e[t+2]=i[2],e[t+3]=i[3],e[t+4]=i[4],e[t+5]=i[5],e[t+6]=i[6],e[t+7]=i[7],e[t+8]=i[8],e}clone(){return new this.constructor().fromArray(this.elements)}}const xv=new Mt,$b=new Mt().set(.4123908,.3575843,.1804808,.212639,.7151687,.0721923,.0193308,.1191948,.9505322),Kb=new Mt().set(3.2409699,-1.5373832,-.4986108,-.9692436,1.8759675,.0415551,.0556301,-.203977,1.0569715);function HR(){const s={enabled:!0,workingColorSpace:Ll,spaces:{},convert:function(n,r,a){return this.enabled===!1||r===a||!r||!a||(this.spaces[r].transfer===Vt&&(n.r=ur(n.r),n.g=ur(n.g),n.b=ur(n.b)),this.spaces[r].primaries!==this.spaces[a].primaries&&(n.applyMatrix3(this.spaces[r].toXYZ),n.applyMatrix3(this.spaces[a].fromXYZ)),this.spaces[a].transfer===Vt&&(n.r=kl(n.r),n.g=kl(n.g),n.b=kl(n.b))),n},workingToColorSpace:function(n,r){return this.convert(n,this.workingColorSpace,r)},colorSpaceToWorking:function(n,r){return this.convert(n,r,this.workingColorSpace)},getPrimaries:function(n){return this.spaces[n].primaries},getTransfer:function(n){return n===ta?Xp:this.spaces[n].transfer},getToneMappingMode:function(n){return this.spaces[n].outputColorSpaceConfig.toneMappingMode||"standard"},getLuminanceCoefficients:function(n,r=this.workingColorSpace){return n.fromArray(this.spaces[r].luminanceCoefficients)},define:function(n){Object.assign(this.spaces,n)},_getMatrix:function(n,r,a){return n.copy(this.spaces[r].toXYZ).multiply(this.spaces[a].fromXYZ)},_getDrawingBufferColorSpace:function(n){return this.spaces[n].outputColorSpaceConfig.drawingBufferColorSpace},_getUnpackColorSpace:function(n=this.workingColorSpace){return this.spaces[n].workingColorSpaceConfig.unpackColorSpace},fromWorkingColorSpace:function(n,r){return _h("ColorManagement: .fromWorkingColorSpace() has been renamed to .workingToColorSpace()."),s.workingToColorSpace(n,r)},toWorkingColorSpace:function(n,r){return _h("ColorManagement: .toWorkingColorSpace() has been renamed to .colorSpaceToWorking()."),s.colorSpaceToWorking(n,r)}},e=[.64,.33,.3,.6,.15,.06],t=[.2126,.7152,.0722],i=[.3127,.329];return s.define({[Ll]:{primaries:e,whitePoint:i,transfer:Xp,toXYZ:$b,fromXYZ:Kb,luminanceCoefficients:t,workingColorSpaceConfig:{unpackColorSpace:zn},outputColorSpaceConfig:{drawingBufferColorSpace:zn}},[zn]:{primaries:e,whitePoint:i,transfer:Vt,toXYZ:$b,fromXYZ:Kb,luminanceCoefficients:t,outputColorSpaceConfig:{drawingBufferColorSpace:zn}}}),s}const Ut=HR();function ur(s){return s<.04045?s*.0773993808:Math.pow(s*.9478672986+.0521327014,2.4)}function kl(s){return s<.0031308?s*12.92:1.055*Math.pow(s,.41666)-.055}let Ol;class VR{static getDataURL(e,t="image/png"){if(/^data:/i.test(e.src)||typeof HTMLCanvasElement>"u")return e.src;let i;if(e instanceof HTMLCanvasElement)i=e;else{Ol===void 0&&(Ol=qp("canvas")),Ol.width=e.width,Ol.height=e.height;const n=Ol.getContext("2d");e instanceof ImageData?n.putImageData(e,0,0):n.drawImage(e,0,0,e.width,e.height),i=Ol}return i.toDataURL(t)}static sRGBToLinear(e){if(typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&e instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&e instanceof ImageBitmap){const t=qp("canvas");t.width=e.width,t.height=e.height;const i=t.getContext("2d");i.drawImage(e,0,0,e.width,e.height);const n=i.getImageData(0,0,e.width,e.height),r=n.data;for(let a=0;a1),this.pmremVersion=0}get width(){return this.source.getSize(Mv).x}get height(){return this.source.getSize(Mv).y}get depth(){return this.source.getSize(Mv).z}get image(){return this.source.data}set image(e=null){this.source.data=e}updateMatrix(){this.matrix.setUvTransform(this.offset.x,this.offset.y,this.repeat.x,this.repeat.y,this.rotation,this.center.x,this.center.y)}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}clone(){return new this.constructor().copy(this)}copy(e){return this.name=e.name,this.source=e.source,this.mipmaps=e.mipmaps.slice(0),this.mapping=e.mapping,this.channel=e.channel,this.wrapS=e.wrapS,this.wrapT=e.wrapT,this.magFilter=e.magFilter,this.minFilter=e.minFilter,this.anisotropy=e.anisotropy,this.format=e.format,this.internalFormat=e.internalFormat,this.type=e.type,this.offset.copy(e.offset),this.repeat.copy(e.repeat),this.center.copy(e.center),this.rotation=e.rotation,this.matrixAutoUpdate=e.matrixAutoUpdate,this.matrix.copy(e.matrix),this.generateMipmaps=e.generateMipmaps,this.premultiplyAlpha=e.premultiplyAlpha,this.flipY=e.flipY,this.unpackAlignment=e.unpackAlignment,this.colorSpace=e.colorSpace,this.renderTarget=e.renderTarget,this.isRenderTargetTexture=e.isRenderTargetTexture,this.isArrayTexture=e.isArrayTexture,this.userData=JSON.parse(JSON.stringify(e.userData)),this.needsUpdate=!0,this}setValues(e){for(const t in e){const i=e[t];if(i===void 0){yt(`Texture.setValues(): parameter '${t}' has value of undefined.`);continue}const n=this[t];if(n===void 0){yt(`Texture.setValues(): property '${t}' does not exist.`);continue}n&&i&&n.isVector2&&i.isVector2||n&&i&&n.isVector3&&i.isVector3||n&&i&&n.isMatrix3&&i.isMatrix3?n.copy(i):this[t]=i}}toJSON(e){const t=e===void 0||typeof e=="string";if(!t&&e.textures[this.uuid]!==void 0)return e.textures[this.uuid];const i={metadata:{version:4.7,type:"Texture",generator:"Texture.toJSON"},uuid:this.uuid,name:this.name,image:this.source.toJSON(e).uuid,mapping:this.mapping,channel:this.channel,repeat:[this.repeat.x,this.repeat.y],offset:[this.offset.x,this.offset.y],center:[this.center.x,this.center.y],rotation:this.rotation,wrap:[this.wrapS,this.wrapT],format:this.format,internalFormat:this.internalFormat,type:this.type,colorSpace:this.colorSpace,minFilter:this.minFilter,magFilter:this.magFilter,anisotropy:this.anisotropy,flipY:this.flipY,generateMipmaps:this.generateMipmaps,premultiplyAlpha:this.premultiplyAlpha,unpackAlignment:this.unpackAlignment};return Object.keys(this.userData).length>0&&(i.userData=this.userData),t||(e.textures[this.uuid]=i),i}dispose(){this.dispatchEvent({type:"dispose"})}transformUv(e){if(this.mapping!==Nb)return e;if(e.applyMatrix3(this.matrix),e.x<0||e.x>1)switch(this.wrapS){case I0:e.x=e.x-Math.floor(e.x);break;case cr:e.x=e.x<0?0:1;break;case L0:Math.abs(Math.floor(e.x)%2)===1?e.x=Math.ceil(e.x)-e.x:e.x=e.x-Math.floor(e.x);break}if(e.y<0||e.y>1)switch(this.wrapT){case I0:e.y=e.y-Math.floor(e.y);break;case cr:e.y=e.y<0?0:1;break;case L0:Math.abs(Math.floor(e.y)%2)===1?e.y=Math.ceil(e.y)-e.y:e.y=e.y-Math.floor(e.y);break}return this.flipY&&(e.y=1-e.y),e}set needsUpdate(e){e===!0&&(this.version++,this.source.needsUpdate=!0)}set needsPMREMUpdate(e){e===!0&&this.pmremVersion++}}mn.DEFAULT_IMAGE=null,mn.DEFAULT_MAPPING=Nb,mn.DEFAULT_ANISOTROPY=1;class vi{constructor(e=0,t=0,i=0,n=1){vi.prototype.isVector4=!0,this.x=e,this.y=t,this.z=i,this.w=n}get width(){return this.z}set width(e){this.z=e}get height(){return this.w}set height(e){this.w=e}set(e,t,i,n){return this.x=e,this.y=t,this.z=i,this.w=n,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this.w=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setW(e){return this.w=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;case 2:this.z=t;break;case 3:this.w=t;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;case 3:return this.w;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y,this.z,this.w)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this.w=e.w!==void 0?e.w:1,this}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this.w+=e.w,this}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this.w+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this.z=e.z+t.z,this.w=e.w+t.w,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this.z+=e.z*t,this.w+=e.w*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this.w-=e.w,this}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this.w-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this.z=e.z-t.z,this.w=e.w-t.w,this}multiply(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this.w*=e.w,this}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this.w*=e,this}applyMatrix4(e){const t=this.x,i=this.y,n=this.z,r=this.w,a=e.elements;return this.x=a[0]*t+a[4]*i+a[8]*n+a[12]*r,this.y=a[1]*t+a[5]*i+a[9]*n+a[13]*r,this.z=a[2]*t+a[6]*i+a[10]*n+a[14]*r,this.w=a[3]*t+a[7]*i+a[11]*n+a[15]*r,this}divide(e){return this.x/=e.x,this.y/=e.y,this.z/=e.z,this.w/=e.w,this}divideScalar(e){return this.multiplyScalar(1/e)}setAxisAngleFromQuaternion(e){this.w=2*Math.acos(e.w);const t=Math.sqrt(1-e.w*e.w);return t<1e-4?(this.x=1,this.y=0,this.z=0):(this.x=e.x/t,this.y=e.y/t,this.z=e.z/t),this}setAxisAngleFromRotationMatrix(e){let t,i,n,r;const a=e.elements,o=a[0],l=a[4],c=a[8],h=a[1],d=a[5],p=a[9],u=a[2],v=a[6],g=a[10];if(Math.abs(l-h)<.01&&Math.abs(c-u)<.01&&Math.abs(p-v)<.01){if(Math.abs(l+h)<.1&&Math.abs(c+u)<.1&&Math.abs(p+v)<.1&&Math.abs(o+d+g-3)<.1)return this.set(1,0,0,0),this;t=Math.PI;const f=(o+1)/2,y=(d+1)/2,x=(g+1)/2,_=(l+h)/4,S=(c+u)/4,b=(p+v)/4;return f>y&&f>x?f<.01?(i=0,n=.707106781,r=.707106781):(i=Math.sqrt(f),n=_/i,r=S/i):y>x?y<.01?(i=.707106781,n=0,r=.707106781):(n=Math.sqrt(y),i=_/n,r=b/n):x<.01?(i=.707106781,n=.707106781,r=0):(r=Math.sqrt(x),i=S/r,n=b/r),this.set(i,n,r,t),this}let m=Math.sqrt((v-p)*(v-p)+(c-u)*(c-u)+(h-l)*(h-l));return Math.abs(m)<.001&&(m=1),this.x=(v-p)/m,this.y=(c-u)/m,this.z=(h-l)/m,this.w=Math.acos((o+d+g-1)/2),this}setFromMatrixPosition(e){const t=e.elements;return this.x=t[12],this.y=t[13],this.z=t[14],this.w=t[15],this}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this.z=Math.min(this.z,e.z),this.w=Math.min(this.w,e.w),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this.z=Math.max(this.z,e.z),this.w=Math.max(this.w,e.w),this}clamp(e,t){return this.x=It(this.x,e.x,t.x),this.y=It(this.y,e.y,t.y),this.z=It(this.z,e.z,t.z),this.w=It(this.w,e.w,t.w),this}clampScalar(e,t){return this.x=It(this.x,e,t),this.y=It(this.y,e,t),this.z=It(this.z,e,t),this.w=It(this.w,e,t),this}clampLength(e,t){const i=this.length();return this.divideScalar(i||1).multiplyScalar(It(i,e,t))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this.w=Math.floor(this.w),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this.w=Math.ceil(this.w),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this.w=Math.round(this.w),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this.w=Math.trunc(this.w),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this.w=-this.w,this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z+this.w*e.w}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)+Math.abs(this.w)}normalize(){return this.divideScalar(this.length()||1)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this.z+=(e.z-this.z)*t,this.w+=(e.w-this.w)*t,this}lerpVectors(e,t,i){return this.x=e.x+(t.x-e.x)*i,this.y=e.y+(t.y-e.y)*i,this.z=e.z+(t.z-e.z)*i,this.w=e.w+(t.w-e.w)*i,this}equals(e){return e.x===this.x&&e.y===this.y&&e.z===this.z&&e.w===this.w}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this.z=e[t+2],this.w=e[t+3],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e[t+2]=this.z,e[t+3]=this.w,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this.z=e.getZ(t),this.w=e.getW(t),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this.w=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z,yield this.w}}class XR extends Nl{constructor(e=1,t=1,i={}){super(),i=Object.assign({generateMipmaps:!1,internalFormat:null,minFilter:es,depthBuffer:!0,stencilBuffer:!1,resolveDepthBuffer:!0,resolveStencilBuffer:!0,depthTexture:null,samples:0,count:1,depth:1,multiview:!1},i),this.isRenderTarget=!0,this.width=e,this.height=t,this.depth=i.depth,this.scissor=new vi(0,0,e,t),this.scissorTest=!1,this.viewport=new vi(0,0,e,t);const n={width:e,height:t,depth:i.depth},r=new mn(n);this.textures=[];const a=i.count;for(let o=0;o1);this.dispose()}this.viewport.set(0,0,e,t),this.scissor.set(0,0,e,t)}clone(){return new this.constructor().copy(this)}copy(e){this.width=e.width,this.height=e.height,this.depth=e.depth,this.scissor.copy(e.scissor),this.scissorTest=e.scissorTest,this.viewport.copy(e.viewport),this.textures.length=0;for(let t=0,i=e.textures.length;t=this.min.x&&e.x<=this.max.x&&e.y>=this.min.y&&e.y<=this.max.y&&e.z>=this.min.z&&e.z<=this.max.z}containsBox(e){return this.min.x<=e.min.x&&e.max.x<=this.max.x&&this.min.y<=e.min.y&&e.max.y<=this.max.y&&this.min.z<=e.min.z&&e.max.z<=this.max.z}getParameter(e,t){return t.set((e.x-this.min.x)/(this.max.x-this.min.x),(e.y-this.min.y)/(this.max.y-this.min.y),(e.z-this.min.z)/(this.max.z-this.min.z))}intersectsBox(e){return e.max.x>=this.min.x&&e.min.x<=this.max.x&&e.max.y>=this.min.y&&e.min.y<=this.max.y&&e.max.z>=this.min.z&&e.min.z<=this.max.z}intersectsSphere(e){return this.clampPoint(e.center,_s),_s.distanceToSquared(e.center)<=e.radius*e.radius}intersectsPlane(e){let t,i;return e.normal.x>0?(t=e.normal.x*this.min.x,i=e.normal.x*this.max.x):(t=e.normal.x*this.max.x,i=e.normal.x*this.min.x),e.normal.y>0?(t+=e.normal.y*this.min.y,i+=e.normal.y*this.max.y):(t+=e.normal.y*this.max.y,i+=e.normal.y*this.min.y),e.normal.z>0?(t+=e.normal.z*this.min.z,i+=e.normal.z*this.max.z):(t+=e.normal.z*this.max.z,i+=e.normal.z*this.min.z),t<=-e.constant&&i>=-e.constant}intersectsTriangle(e){if(this.isEmpty())return!1;this.getCenter(Eh),Yp.subVectors(this.max,Eh),Ul.subVectors(e.a,Eh),Bl.subVectors(e.b,Eh),Fl.subVectors(e.c,Eh),ia.subVectors(Bl,Ul),na.subVectors(Fl,Bl),oo.subVectors(Ul,Fl);let t=[0,-ia.z,ia.y,0,-na.z,na.y,0,-oo.z,oo.y,ia.z,0,-ia.x,na.z,0,-na.x,oo.z,0,-oo.x,-ia.y,ia.x,0,-na.y,na.x,0,-oo.y,oo.x,0];return!Sv(t,Ul,Bl,Fl,Yp)||(t=[1,0,0,0,1,0,0,0,1],!Sv(t,Ul,Bl,Fl,Yp))?!1:($p.crossVectors(ia,na),t=[$p.x,$p.y,$p.z],Sv(t,Ul,Bl,Fl,Yp))}clampPoint(e,t){return t.copy(e).clamp(this.min,this.max)}distanceToPoint(e){return this.clampPoint(e,_s).distanceTo(e)}getBoundingSphere(e){return this.isEmpty()?e.makeEmpty():(this.getCenter(e.center),e.radius=this.getSize(_s).length()*.5),e}intersect(e){return this.min.max(e.min),this.max.min(e.max),this.isEmpty()&&this.makeEmpty(),this}union(e){return this.min.min(e.min),this.max.max(e.max),this}applyMatrix4(e){return this.isEmpty()?this:(pr[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(e),pr[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(e),pr[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(e),pr[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(e),pr[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(e),pr[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(e),pr[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(e),pr[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(e),this.setFromPoints(pr),this)}translate(e){return this.min.add(e),this.max.add(e),this}equals(e){return e.min.equals(this.min)&&e.max.equals(this.max)}toJSON(){return{min:this.min.toArray(),max:this.max.toArray()}}fromJSON(e){return this.min.fromArray(e.min),this.max.fromArray(e.max),this}}const pr=[new De,new De,new De,new De,new De,new De,new De,new De],_s=new De,Zp=new wh,Ul=new De,Bl=new De,Fl=new De,ia=new De,na=new De,oo=new De,Eh=new De,Yp=new De,$p=new De,lo=new De;function Sv(s,e,t,i,n){for(let r=0,a=s.length-3;r<=a;r+=3){lo.fromArray(s,r);const o=n.x*Math.abs(lo.x)+n.y*Math.abs(lo.y)+n.z*Math.abs(lo.z),l=e.dot(lo),c=t.dot(lo),h=i.dot(lo);if(Math.max(-Math.max(l,c,h),Math.min(l,c,h))>o)return!1}return!0}const qR=new wh,Th=new De,wv=new De;class Ev{constructor(e=new De,t=-1){this.isSphere=!0,this.center=e,this.radius=t}set(e,t){return this.center.copy(e),this.radius=t,this}setFromPoints(e,t){const i=this.center;t!==void 0?i.copy(t):qR.setFromPoints(e).getCenter(i);let n=0;for(let r=0,a=e.length;rthis.radius*this.radius&&(t.sub(this.center).normalize(),t.multiplyScalar(this.radius).add(this.center)),t}getBoundingBox(e){return this.isEmpty()?(e.makeEmpty(),e):(e.set(this.center,this.center),e.expandByScalar(this.radius),e)}applyMatrix4(e){return this.center.applyMatrix4(e),this.radius=this.radius*e.getMaxScaleOnAxis(),this}translate(e){return this.center.add(e),this}expandByPoint(e){if(this.isEmpty())return this.center.copy(e),this.radius=0,this;Th.subVectors(e,this.center);const t=Th.lengthSq();if(t>this.radius*this.radius){const i=Math.sqrt(t),n=(i-this.radius)*.5;this.center.addScaledVector(Th,n/i),this.radius+=n}return this}union(e){return e.isEmpty()?this:this.isEmpty()?(this.copy(e),this):(this.center.equals(e.center)===!0?this.radius=Math.max(this.radius,e.radius):(wv.subVectors(e.center,this.center).setLength(e.radius),this.expandByPoint(Th.copy(e.center).add(wv)),this.expandByPoint(Th.copy(e.center).sub(wv))),this)}equals(e){return e.center.equals(this.center)&&e.radius===this.radius}clone(){return new this.constructor().copy(this)}toJSON(){return{radius:this.radius,center:this.center.toArray()}}fromJSON(e){return this.radius=e.radius,this.center.fromArray(e.center),this}}const fr=new De,Tv=new De,Kp=new De,sa=new De,Cv=new De,Jp=new De,Av=new De;class ZR{constructor(e=new De,t=new De(0,0,-1)){this.origin=e,this.direction=t}set(e,t){return this.origin.copy(e),this.direction.copy(t),this}copy(e){return this.origin.copy(e.origin),this.direction.copy(e.direction),this}at(e,t){return t.copy(this.origin).addScaledVector(this.direction,e)}lookAt(e){return this.direction.copy(e).sub(this.origin).normalize(),this}recast(e){return this.origin.copy(this.at(e,fr)),this}closestPointToPoint(e,t){t.subVectors(e,this.origin);const i=t.dot(this.direction);return i<0?t.copy(this.origin):t.copy(this.origin).addScaledVector(this.direction,i)}distanceToPoint(e){return Math.sqrt(this.distanceSqToPoint(e))}distanceSqToPoint(e){const t=fr.subVectors(e,this.origin).dot(this.direction);return t<0?this.origin.distanceToSquared(e):(fr.copy(this.origin).addScaledVector(this.direction,t),fr.distanceToSquared(e))}distanceSqToSegment(e,t,i,n){Tv.copy(e).add(t).multiplyScalar(.5),Kp.copy(t).sub(e).normalize(),sa.copy(this.origin).sub(Tv);const r=e.distanceTo(t)*.5,a=-this.direction.dot(Kp),o=sa.dot(this.direction),l=-sa.dot(Kp),c=sa.lengthSq(),h=Math.abs(1-a*a);let d,p,u,v;if(h>0)if(d=a*l-o,p=a*o-l,v=r*h,d>=0)if(p>=-v)if(p<=v){const g=1/h;d*=g,p*=g,u=d*(d+a*p+2*o)+p*(a*d+p+2*l)+c}else p=r,d=Math.max(0,-(a*p+o)),u=-d*d+p*(p+2*l)+c;else p=-r,d=Math.max(0,-(a*p+o)),u=-d*d+p*(p+2*l)+c;else p<=-v?(d=Math.max(0,-(-a*r+o)),p=d>0?-r:Math.min(Math.max(-r,-l),r),u=-d*d+p*(p+2*l)+c):p<=v?(d=0,p=Math.min(Math.max(-r,-l),r),u=p*(p+2*l)+c):(d=Math.max(0,-(a*r+o)),p=d>0?r:Math.min(Math.max(-r,-l),r),u=-d*d+p*(p+2*l)+c);else p=a>0?-r:r,d=Math.max(0,-(a*p+o)),u=-d*d+p*(p+2*l)+c;return i&&i.copy(this.origin).addScaledVector(this.direction,d),n&&n.copy(Tv).addScaledVector(Kp,p),u}intersectSphere(e,t){fr.subVectors(e.center,this.origin);const i=fr.dot(this.direction),n=fr.dot(fr)-i*i,r=e.radius*e.radius;if(n>r)return null;const a=Math.sqrt(r-n),o=i-a,l=i+a;return l<0?null:o<0?this.at(l,t):this.at(o,t)}intersectsSphere(e){return e.radius<0?!1:this.distanceSqToPoint(e.center)<=e.radius*e.radius}distanceToPlane(e){const t=e.normal.dot(this.direction);if(t===0)return e.distanceToPoint(this.origin)===0?0:null;const i=-(this.origin.dot(e.normal)+e.constant)/t;return i>=0?i:null}intersectPlane(e,t){const i=this.distanceToPlane(e);return i===null?null:this.at(i,t)}intersectsPlane(e){const t=e.distanceToPoint(this.origin);return t===0||e.normal.dot(this.direction)*t<0}intersectBox(e,t){let i,n,r,a,o,l;const c=1/this.direction.x,h=1/this.direction.y,d=1/this.direction.z,p=this.origin;return c>=0?(i=(e.min.x-p.x)*c,n=(e.max.x-p.x)*c):(i=(e.max.x-p.x)*c,n=(e.min.x-p.x)*c),h>=0?(r=(e.min.y-p.y)*h,a=(e.max.y-p.y)*h):(r=(e.max.y-p.y)*h,a=(e.min.y-p.y)*h),i>a||r>n||((r>i||isNaN(i))&&(i=r),(a=0?(o=(e.min.z-p.z)*d,l=(e.max.z-p.z)*d):(o=(e.max.z-p.z)*d,l=(e.min.z-p.z)*d),i>l||o>n)||((o>i||i!==i)&&(i=o),(l=0?i:n,t)}intersectsBox(e){return this.intersectBox(e,fr)!==null}intersectTriangle(e,t,i,n,r){Cv.subVectors(t,e),Jp.subVectors(i,e),Av.crossVectors(Cv,Jp);let a=this.direction.dot(Av),o;if(a>0){if(n)return null;o=1}else if(a<0)o=-1,a=-a;else return null;sa.subVectors(this.origin,e);const l=o*this.direction.dot(Jp.crossVectors(sa,Jp));if(l<0)return null;const c=o*this.direction.dot(Cv.cross(sa));if(c<0||l+c>a)return null;const h=-o*sa.dot(Av);return h<0?null:this.at(h/a,r)}applyMatrix4(e){return this.origin.applyMatrix4(e),this.direction.transformDirection(e),this}equals(e){return e.origin.equals(this.origin)&&e.direction.equals(this.direction)}clone(){return new this.constructor().copy(this)}}class Di{constructor(e,t,i,n,r,a,o,l,c,h,d,p,u,v,g,m){Di.prototype.isMatrix4=!0,this.elements=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],e!==void 0&&this.set(e,t,i,n,r,a,o,l,c,h,d,p,u,v,g,m)}set(e,t,i,n,r,a,o,l,c,h,d,p,u,v,g,m){const f=this.elements;return f[0]=e,f[4]=t,f[8]=i,f[12]=n,f[1]=r,f[5]=a,f[9]=o,f[13]=l,f[2]=c,f[6]=h,f[10]=d,f[14]=p,f[3]=u,f[7]=v,f[11]=g,f[15]=m,this}identity(){return this.set(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1),this}clone(){return new Di().fromArray(this.elements)}copy(e){const t=this.elements,i=e.elements;return t[0]=i[0],t[1]=i[1],t[2]=i[2],t[3]=i[3],t[4]=i[4],t[5]=i[5],t[6]=i[6],t[7]=i[7],t[8]=i[8],t[9]=i[9],t[10]=i[10],t[11]=i[11],t[12]=i[12],t[13]=i[13],t[14]=i[14],t[15]=i[15],this}copyPosition(e){const t=this.elements,i=e.elements;return t[12]=i[12],t[13]=i[13],t[14]=i[14],this}setFromMatrix3(e){const t=e.elements;return this.set(t[0],t[3],t[6],0,t[1],t[4],t[7],0,t[2],t[5],t[8],0,0,0,0,1),this}extractBasis(e,t,i){return e.setFromMatrixColumn(this,0),t.setFromMatrixColumn(this,1),i.setFromMatrixColumn(this,2),this}makeBasis(e,t,i){return this.set(e.x,t.x,i.x,0,e.y,t.y,i.y,0,e.z,t.z,i.z,0,0,0,0,1),this}extractRotation(e){const t=this.elements,i=e.elements,n=1/zl.setFromMatrixColumn(e,0).length(),r=1/zl.setFromMatrixColumn(e,1).length(),a=1/zl.setFromMatrixColumn(e,2).length();return t[0]=i[0]*n,t[1]=i[1]*n,t[2]=i[2]*n,t[3]=0,t[4]=i[4]*r,t[5]=i[5]*r,t[6]=i[6]*r,t[7]=0,t[8]=i[8]*a,t[9]=i[9]*a,t[10]=i[10]*a,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this}makeRotationFromEuler(e){const t=this.elements,i=e.x,n=e.y,r=e.z,a=Math.cos(i),o=Math.sin(i),l=Math.cos(n),c=Math.sin(n),h=Math.cos(r),d=Math.sin(r);if(e.order==="XYZ"){const p=a*h,u=a*d,v=o*h,g=o*d;t[0]=l*h,t[4]=-l*d,t[8]=c,t[1]=u+v*c,t[5]=p-g*c,t[9]=-o*l,t[2]=g-p*c,t[6]=v+u*c,t[10]=a*l}else if(e.order==="YXZ"){const p=l*h,u=l*d,v=c*h,g=c*d;t[0]=p+g*o,t[4]=v*o-u,t[8]=a*c,t[1]=a*d,t[5]=a*h,t[9]=-o,t[2]=u*o-v,t[6]=g+p*o,t[10]=a*l}else if(e.order==="ZXY"){const p=l*h,u=l*d,v=c*h,g=c*d;t[0]=p-g*o,t[4]=-a*d,t[8]=v+u*o,t[1]=u+v*o,t[5]=a*h,t[9]=g-p*o,t[2]=-a*c,t[6]=o,t[10]=a*l}else if(e.order==="ZYX"){const p=a*h,u=a*d,v=o*h,g=o*d;t[0]=l*h,t[4]=v*c-u,t[8]=p*c+g,t[1]=l*d,t[5]=g*c+p,t[9]=u*c-v,t[2]=-c,t[6]=o*l,t[10]=a*l}else if(e.order==="YZX"){const p=a*l,u=a*c,v=o*l,g=o*c;t[0]=l*h,t[4]=g-p*d,t[8]=v*d+u,t[1]=d,t[5]=a*h,t[9]=-o*h,t[2]=-c*h,t[6]=u*d+v,t[10]=p-g*d}else if(e.order==="XZY"){const p=a*l,u=a*c,v=o*l,g=o*c;t[0]=l*h,t[4]=-d,t[8]=c*h,t[1]=p*d+g,t[5]=a*h,t[9]=u*d-v,t[2]=v*d-u,t[6]=o*h,t[10]=g*d+p}return t[3]=0,t[7]=0,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this}makeRotationFromQuaternion(e){return this.compose(YR,e,$R)}lookAt(e,t,i){const n=this.elements;return Hn.subVectors(e,t),Hn.lengthSq()===0&&(Hn.z=1),Hn.normalize(),ra.crossVectors(i,Hn),ra.lengthSq()===0&&(Math.abs(i.z)===1?Hn.x+=1e-4:Hn.z+=1e-4,Hn.normalize(),ra.crossVectors(i,Hn)),ra.normalize(),Qp.crossVectors(Hn,ra),n[0]=ra.x,n[4]=Qp.x,n[8]=Hn.x,n[1]=ra.y,n[5]=Qp.y,n[9]=Hn.y,n[2]=ra.z,n[6]=Qp.z,n[10]=Hn.z,this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,t){const i=e.elements,n=t.elements,r=this.elements,a=i[0],o=i[4],l=i[8],c=i[12],h=i[1],d=i[5],p=i[9],u=i[13],v=i[2],g=i[6],m=i[10],f=i[14],y=i[3],x=i[7],_=i[11],S=i[15],b=n[0],E=n[4],w=n[8],M=n[12],C=n[1],I=n[5],P=n[9],k=n[13],A=n[2],B=n[6],F=n[10],H=n[14],q=n[3],G=n[7],re=n[11],Y=n[15];return r[0]=a*b+o*C+l*A+c*q,r[4]=a*E+o*I+l*B+c*G,r[8]=a*w+o*P+l*F+c*re,r[12]=a*M+o*k+l*H+c*Y,r[1]=h*b+d*C+p*A+u*q,r[5]=h*E+d*I+p*B+u*G,r[9]=h*w+d*P+p*F+u*re,r[13]=h*M+d*k+p*H+u*Y,r[2]=v*b+g*C+m*A+f*q,r[6]=v*E+g*I+m*B+f*G,r[10]=v*w+g*P+m*F+f*re,r[14]=v*M+g*k+m*H+f*Y,r[3]=y*b+x*C+_*A+S*q,r[7]=y*E+x*I+_*B+S*G,r[11]=y*w+x*P+_*F+S*re,r[15]=y*M+x*k+_*H+S*Y,this}multiplyScalar(e){const t=this.elements;return t[0]*=e,t[4]*=e,t[8]*=e,t[12]*=e,t[1]*=e,t[5]*=e,t[9]*=e,t[13]*=e,t[2]*=e,t[6]*=e,t[10]*=e,t[14]*=e,t[3]*=e,t[7]*=e,t[11]*=e,t[15]*=e,this}determinant(){const e=this.elements,t=e[0],i=e[4],n=e[8],r=e[12],a=e[1],o=e[5],l=e[9],c=e[13],h=e[2],d=e[6],p=e[10],u=e[14],v=e[3],g=e[7],m=e[11],f=e[15];return v*(+r*l*d-n*c*d-r*o*p+i*c*p+n*o*u-i*l*u)+g*(+t*l*u-t*c*p+r*a*p-n*a*u+n*c*h-r*l*h)+m*(+t*c*d-t*o*u-r*a*d+i*a*u+r*o*h-i*c*h)+f*(-n*o*h-t*l*d+t*o*p+n*a*d-i*a*p+i*l*h)}transpose(){const e=this.elements;let t;return t=e[1],e[1]=e[4],e[4]=t,t=e[2],e[2]=e[8],e[8]=t,t=e[6],e[6]=e[9],e[9]=t,t=e[3],e[3]=e[12],e[12]=t,t=e[7],e[7]=e[13],e[13]=t,t=e[11],e[11]=e[14],e[14]=t,this}setPosition(e,t,i){const n=this.elements;return e.isVector3?(n[12]=e.x,n[13]=e.y,n[14]=e.z):(n[12]=e,n[13]=t,n[14]=i),this}invert(){const e=this.elements,t=e[0],i=e[1],n=e[2],r=e[3],a=e[4],o=e[5],l=e[6],c=e[7],h=e[8],d=e[9],p=e[10],u=e[11],v=e[12],g=e[13],m=e[14],f=e[15],y=d*m*c-g*p*c+g*l*u-o*m*u-d*l*f+o*p*f,x=v*p*c-h*m*c-v*l*u+a*m*u+h*l*f-a*p*f,_=h*g*c-v*d*c+v*o*u-a*g*u-h*o*f+a*d*f,S=v*d*l-h*g*l-v*o*p+a*g*p+h*o*m-a*d*m,b=t*y+i*x+n*_+r*S;if(b===0)return this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);const E=1/b;return e[0]=y*E,e[1]=(g*p*r-d*m*r-g*n*u+i*m*u+d*n*f-i*p*f)*E,e[2]=(o*m*r-g*l*r+g*n*c-i*m*c-o*n*f+i*l*f)*E,e[3]=(d*l*r-o*p*r-d*n*c+i*p*c+o*n*u-i*l*u)*E,e[4]=x*E,e[5]=(h*m*r-v*p*r+v*n*u-t*m*u-h*n*f+t*p*f)*E,e[6]=(v*l*r-a*m*r-v*n*c+t*m*c+a*n*f-t*l*f)*E,e[7]=(a*p*r-h*l*r+h*n*c-t*p*c-a*n*u+t*l*u)*E,e[8]=_*E,e[9]=(v*d*r-h*g*r-v*i*u+t*g*u+h*i*f-t*d*f)*E,e[10]=(a*g*r-v*o*r+v*i*c-t*g*c-a*i*f+t*o*f)*E,e[11]=(h*o*r-a*d*r-h*i*c+t*d*c+a*i*u-t*o*u)*E,e[12]=S*E,e[13]=(h*g*n-v*d*n+v*i*p-t*g*p-h*i*m+t*d*m)*E,e[14]=(v*o*n-a*g*n-v*i*l+t*g*l+a*i*m-t*o*m)*E,e[15]=(a*d*n-h*o*n+h*i*l-t*d*l-a*i*p+t*o*p)*E,this}scale(e){const t=this.elements,i=e.x,n=e.y,r=e.z;return t[0]*=i,t[4]*=n,t[8]*=r,t[1]*=i,t[5]*=n,t[9]*=r,t[2]*=i,t[6]*=n,t[10]*=r,t[3]*=i,t[7]*=n,t[11]*=r,this}getMaxScaleOnAxis(){const e=this.elements,t=e[0]*e[0]+e[1]*e[1]+e[2]*e[2],i=e[4]*e[4]+e[5]*e[5]+e[6]*e[6],n=e[8]*e[8]+e[9]*e[9]+e[10]*e[10];return Math.sqrt(Math.max(t,i,n))}makeTranslation(e,t,i){return e.isVector3?this.set(1,0,0,e.x,0,1,0,e.y,0,0,1,e.z,0,0,0,1):this.set(1,0,0,e,0,1,0,t,0,0,1,i,0,0,0,1),this}makeRotationX(e){const t=Math.cos(e),i=Math.sin(e);return this.set(1,0,0,0,0,t,-i,0,0,i,t,0,0,0,0,1),this}makeRotationY(e){const t=Math.cos(e),i=Math.sin(e);return this.set(t,0,i,0,0,1,0,0,-i,0,t,0,0,0,0,1),this}makeRotationZ(e){const t=Math.cos(e),i=Math.sin(e);return this.set(t,-i,0,0,i,t,0,0,0,0,1,0,0,0,0,1),this}makeRotationAxis(e,t){const i=Math.cos(t),n=Math.sin(t),r=1-i,a=e.x,o=e.y,l=e.z,c=r*a,h=r*o;return this.set(c*a+i,c*o-n*l,c*l+n*o,0,c*o+n*l,h*o+i,h*l-n*a,0,c*l-n*o,h*l+n*a,r*l*l+i,0,0,0,0,1),this}makeScale(e,t,i){return this.set(e,0,0,0,0,t,0,0,0,0,i,0,0,0,0,1),this}makeShear(e,t,i,n,r,a){return this.set(1,i,r,0,e,1,a,0,t,n,1,0,0,0,0,1),this}compose(e,t,i){const n=this.elements,r=t._x,a=t._y,o=t._z,l=t._w,c=r+r,h=a+a,d=o+o,p=r*c,u=r*h,v=r*d,g=a*h,m=a*d,f=o*d,y=l*c,x=l*h,_=l*d,S=i.x,b=i.y,E=i.z;return n[0]=(1-(g+f))*S,n[1]=(u+_)*S,n[2]=(v-x)*S,n[3]=0,n[4]=(u-_)*b,n[5]=(1-(p+f))*b,n[6]=(m+y)*b,n[7]=0,n[8]=(v+x)*E,n[9]=(m-y)*E,n[10]=(1-(p+g))*E,n[11]=0,n[12]=e.x,n[13]=e.y,n[14]=e.z,n[15]=1,this}decompose(e,t,i){const n=this.elements;let r=zl.set(n[0],n[1],n[2]).length();const a=zl.set(n[4],n[5],n[6]).length(),o=zl.set(n[8],n[9],n[10]).length();this.determinant()<0&&(r=-r),e.x=n[12],e.y=n[13],e.z=n[14],bs.copy(this);const l=1/r,c=1/a,h=1/o;return bs.elements[0]*=l,bs.elements[1]*=l,bs.elements[2]*=l,bs.elements[4]*=c,bs.elements[5]*=c,bs.elements[6]*=c,bs.elements[8]*=h,bs.elements[9]*=h,bs.elements[10]*=h,t.setFromRotationMatrix(bs),i.x=r,i.y=a,i.z=o,this}makePerspective(e,t,i,n,r,a,o=Hs,l=!1){const c=this.elements,h=2*r/(t-e),d=2*r/(i-n),p=(t+e)/(t-e),u=(i+n)/(i-n);let v,g;if(l)v=r/(a-r),g=a*r/(a-r);else if(o===Hs)v=-(a+r)/(a-r),g=-2*a*r/(a-r);else if(o===jp)v=-a/(a-r),g=-a*r/(a-r);else throw new Error("THREE.Matrix4.makePerspective(): Invalid coordinate system: "+o);return c[0]=h,c[4]=0,c[8]=p,c[12]=0,c[1]=0,c[5]=d,c[9]=u,c[13]=0,c[2]=0,c[6]=0,c[10]=v,c[14]=g,c[3]=0,c[7]=0,c[11]=-1,c[15]=0,this}makeOrthographic(e,t,i,n,r,a,o=Hs,l=!1){const c=this.elements,h=2/(t-e),d=2/(i-n),p=-(t+e)/(t-e),u=-(i+n)/(i-n);let v,g;if(l)v=1/(a-r),g=a/(a-r);else if(o===Hs)v=-2/(a-r),g=-(a+r)/(a-r);else if(o===jp)v=-1/(a-r),g=-r/(a-r);else throw new Error("THREE.Matrix4.makeOrthographic(): Invalid coordinate system: "+o);return c[0]=h,c[4]=0,c[8]=0,c[12]=p,c[1]=0,c[5]=d,c[9]=0,c[13]=u,c[2]=0,c[6]=0,c[10]=v,c[14]=g,c[3]=0,c[7]=0,c[11]=0,c[15]=1,this}equals(e){const t=this.elements,i=e.elements;for(let n=0;n<16;n++)if(t[n]!==i[n])return!1;return!0}fromArray(e,t=0){for(let i=0;i<16;i++)this.elements[i]=e[i+t];return this}toArray(e=[],t=0){const i=this.elements;return e[t]=i[0],e[t+1]=i[1],e[t+2]=i[2],e[t+3]=i[3],e[t+4]=i[4],e[t+5]=i[5],e[t+6]=i[6],e[t+7]=i[7],e[t+8]=i[8],e[t+9]=i[9],e[t+10]=i[10],e[t+11]=i[11],e[t+12]=i[12],e[t+13]=i[13],e[t+14]=i[14],e[t+15]=i[15],e}}const zl=new De,bs=new Di,YR=new De(0,0,0),$R=new De(1,1,1),ra=new De,Qp=new De,Hn=new De,Qb=new Di,eM=new Sh;class co{constructor(e=0,t=0,i=0,n=co.DEFAULT_ORDER){this.isEuler=!0,this._x=e,this._y=t,this._z=i,this._order=n}get x(){return this._x}set x(e){this._x=e,this._onChangeCallback()}get y(){return this._y}set y(e){this._y=e,this._onChangeCallback()}get z(){return this._z}set z(e){this._z=e,this._onChangeCallback()}get order(){return this._order}set order(e){this._order=e,this._onChangeCallback()}set(e,t,i,n=this._order){return this._x=e,this._y=t,this._z=i,this._order=n,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._order)}copy(e){return this._x=e._x,this._y=e._y,this._z=e._z,this._order=e._order,this._onChangeCallback(),this}setFromRotationMatrix(e,t=this._order,i=!0){const n=e.elements,r=n[0],a=n[4],o=n[8],l=n[1],c=n[5],h=n[9],d=n[2],p=n[6],u=n[10];switch(t){case"XYZ":this._y=Math.asin(It(o,-1,1)),Math.abs(o)<.9999999?(this._x=Math.atan2(-h,u),this._z=Math.atan2(-a,r)):(this._x=Math.atan2(p,c),this._z=0);break;case"YXZ":this._x=Math.asin(-It(h,-1,1)),Math.abs(h)<.9999999?(this._y=Math.atan2(o,u),this._z=Math.atan2(l,c)):(this._y=Math.atan2(-d,r),this._z=0);break;case"ZXY":this._x=Math.asin(It(p,-1,1)),Math.abs(p)<.9999999?(this._y=Math.atan2(-d,u),this._z=Math.atan2(-a,c)):(this._y=0,this._z=Math.atan2(l,r));break;case"ZYX":this._y=Math.asin(-It(d,-1,1)),Math.abs(d)<.9999999?(this._x=Math.atan2(p,u),this._z=Math.atan2(l,r)):(this._x=0,this._z=Math.atan2(-a,c));break;case"YZX":this._z=Math.asin(It(l,-1,1)),Math.abs(l)<.9999999?(this._x=Math.atan2(-h,c),this._y=Math.atan2(-d,r)):(this._x=0,this._y=Math.atan2(o,u));break;case"XZY":this._z=Math.asin(-It(a,-1,1)),Math.abs(a)<.9999999?(this._x=Math.atan2(p,c),this._y=Math.atan2(o,r)):(this._x=Math.atan2(-h,u),this._y=0);break;default:yt("Euler: .setFromRotationMatrix() encountered an unknown order: "+t)}return this._order=t,i===!0&&this._onChangeCallback(),this}setFromQuaternion(e,t,i){return Qb.makeRotationFromQuaternion(e),this.setFromRotationMatrix(Qb,t,i)}setFromVector3(e,t=this._order){return this.set(e.x,e.y,e.z,t)}reorder(e){return eM.setFromEuler(this),this.setFromQuaternion(eM,e)}equals(e){return e._x===this._x&&e._y===this._y&&e._z===this._z&&e._order===this._order}fromArray(e){return this._x=e[0],this._y=e[1],this._z=e[2],e[3]!==void 0&&(this._order=e[3]),this._onChangeCallback(),this}toArray(e=[],t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,e[t+3]=this._order,e}_onChange(e){return this._onChangeCallback=e,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._order}}co.DEFAULT_ORDER="XYZ";class tM{constructor(){this.mask=1}set(e){this.mask=(1<>>0}enable(e){this.mask|=1<1){for(let t=0;t1){for(let i=0;i0&&(n.userData=this.userData),n.layers=this.layers.mask,n.matrix=this.matrix.toArray(),n.up=this.up.toArray(),this.matrixAutoUpdate===!1&&(n.matrixAutoUpdate=!1),this.isInstancedMesh&&(n.type="InstancedMesh",n.count=this.count,n.instanceMatrix=this.instanceMatrix.toJSON(),this.instanceColor!==null&&(n.instanceColor=this.instanceColor.toJSON())),this.isBatchedMesh&&(n.type="BatchedMesh",n.perObjectFrustumCulled=this.perObjectFrustumCulled,n.sortObjects=this.sortObjects,n.drawRanges=this._drawRanges,n.reservedRanges=this._reservedRanges,n.geometryInfo=this._geometryInfo.map(o=>({...o,boundingBox:o.boundingBox?o.boundingBox.toJSON():void 0,boundingSphere:o.boundingSphere?o.boundingSphere.toJSON():void 0})),n.instanceInfo=this._instanceInfo.map(o=>({...o})),n.availableInstanceIds=this._availableInstanceIds.slice(),n.availableGeometryIds=this._availableGeometryIds.slice(),n.nextIndexStart=this._nextIndexStart,n.nextVertexStart=this._nextVertexStart,n.geometryCount=this._geometryCount,n.maxInstanceCount=this._maxInstanceCount,n.maxVertexCount=this._maxVertexCount,n.maxIndexCount=this._maxIndexCount,n.geometryInitialized=this._geometryInitialized,n.matricesTexture=this._matricesTexture.toJSON(e),n.indirectTexture=this._indirectTexture.toJSON(e),this._colorsTexture!==null&&(n.colorsTexture=this._colorsTexture.toJSON(e)),this.boundingSphere!==null&&(n.boundingSphere=this.boundingSphere.toJSON()),this.boundingBox!==null&&(n.boundingBox=this.boundingBox.toJSON()));function r(o,l){return o[l.uuid]===void 0&&(o[l.uuid]=l.toJSON(e)),l.uuid}if(this.isScene)this.background&&(this.background.isColor?n.background=this.background.toJSON():this.background.isTexture&&(n.background=this.background.toJSON(e).uuid)),this.environment&&this.environment.isTexture&&this.environment.isRenderTargetTexture!==!0&&(n.environment=this.environment.toJSON(e).uuid);else if(this.isMesh||this.isLine||this.isPoints){n.geometry=r(e.geometries,this.geometry);const o=this.geometry.parameters;if(o!==void 0&&o.shapes!==void 0){const l=o.shapes;if(Array.isArray(l))for(let c=0,h=l.length;c0){n.children=[];for(let o=0;o0){n.animations=[];for(let o=0;o0&&(i.geometries=o),l.length>0&&(i.materials=l),c.length>0&&(i.textures=c),h.length>0&&(i.images=h),d.length>0&&(i.shapes=d),p.length>0&&(i.skeletons=p),u.length>0&&(i.animations=u),v.length>0&&(i.nodes=v)}return i.object=n,i;function a(o){const l=[];for(const c in o){const h=o[c];delete h.metadata,l.push(h)}return l}}clone(e){return new this.constructor().copy(this,e)}copy(e,t=!0){if(this.name=e.name,this.up.copy(e.up),this.position.copy(e.position),this.rotation.order=e.rotation.order,this.quaternion.copy(e.quaternion),this.scale.copy(e.scale),this.matrix.copy(e.matrix),this.matrixWorld.copy(e.matrixWorld),this.matrixAutoUpdate=e.matrixAutoUpdate,this.matrixWorldAutoUpdate=e.matrixWorldAutoUpdate,this.matrixWorldNeedsUpdate=e.matrixWorldNeedsUpdate,this.layers.mask=e.layers.mask,this.visible=e.visible,this.castShadow=e.castShadow,this.receiveShadow=e.receiveShadow,this.frustumCulled=e.frustumCulled,this.renderOrder=e.renderOrder,this.animations=e.animations.slice(),this.userData=JSON.parse(JSON.stringify(e.userData)),t===!0)for(let i=0;i0?n.multiplyScalar(1/Math.sqrt(r)):n.set(0,0,0)}static getBarycoord(e,t,i,n,r){Ms.subVectors(n,t),gr.subVectors(i,t),Rv.subVectors(e,t);const a=Ms.dot(Ms),o=Ms.dot(gr),l=Ms.dot(Rv),c=gr.dot(gr),h=gr.dot(Rv),d=a*c-o*o;if(d===0)return r.set(0,0,0),null;const p=1/d,u=(c*l-o*h)*p,v=(a*h-o*l)*p;return r.set(1-u-v,v,u)}static containsPoint(e,t,i,n){return this.getBarycoord(e,t,i,n,vr)===null?!1:vr.x>=0&&vr.y>=0&&vr.x+vr.y<=1}static getInterpolation(e,t,i,n,r,a,o,l){return this.getBarycoord(e,t,i,n,vr)===null?(l.x=0,l.y=0,"z"in l&&(l.z=0),"w"in l&&(l.w=0),null):(l.setScalar(0),l.addScaledVector(r,vr.x),l.addScaledVector(a,vr.y),l.addScaledVector(o,vr.z),l)}static getInterpolatedAttribute(e,t,i,n,r,a){return Nv.setScalar(0),kv.setScalar(0),Ov.setScalar(0),Nv.fromBufferAttribute(e,t),kv.fromBufferAttribute(e,i),Ov.fromBufferAttribute(e,n),a.setScalar(0),a.addScaledVector(Nv,r.x),a.addScaledVector(kv,r.y),a.addScaledVector(Ov,r.z),a}static isFrontFacing(e,t,i,n){return Ms.subVectors(i,t),gr.subVectors(e,t),Ms.cross(gr).dot(n)<0}set(e,t,i){return this.a.copy(e),this.b.copy(t),this.c.copy(i),this}setFromPointsAndIndices(e,t,i,n){return this.a.copy(e[t]),this.b.copy(e[i]),this.c.copy(e[n]),this}setFromAttributeAndIndices(e,t,i,n){return this.a.fromBufferAttribute(e,t),this.b.fromBufferAttribute(e,i),this.c.fromBufferAttribute(e,n),this}clone(){return new this.constructor().copy(this)}copy(e){return this.a.copy(e.a),this.b.copy(e.b),this.c.copy(e.c),this}getArea(){return Ms.subVectors(this.c,this.b),gr.subVectors(this.a,this.b),Ms.cross(gr).length()*.5}getMidpoint(e){return e.addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)}getNormal(e){return Ss.getNormal(this.a,this.b,this.c,e)}getPlane(e){return e.setFromCoplanarPoints(this.a,this.b,this.c)}getBarycoord(e,t){return Ss.getBarycoord(e,this.a,this.b,this.c,t)}getInterpolation(e,t,i,n,r){return Ss.getInterpolation(e,this.a,this.b,this.c,t,i,n,r)}containsPoint(e){return Ss.containsPoint(e,this.a,this.b,this.c)}isFrontFacing(e){return Ss.isFrontFacing(this.a,this.b,this.c,e)}intersectsBox(e){return e.intersectsTriangle(this)}closestPointToPoint(e,t){const i=this.a,n=this.b,r=this.c;let a,o;Gl.subVectors(n,i),Wl.subVectors(r,i),Iv.subVectors(e,i);const l=Gl.dot(Iv),c=Wl.dot(Iv);if(l<=0&&c<=0)return t.copy(i);Lv.subVectors(e,n);const h=Gl.dot(Lv),d=Wl.dot(Lv);if(h>=0&&d<=h)return t.copy(n);const p=l*d-h*c;if(p<=0&&l>=0&&h<=0)return a=l/(l-h),t.copy(i).addScaledVector(Gl,a);Dv.subVectors(e,r);const u=Gl.dot(Dv),v=Wl.dot(Dv);if(v>=0&&u<=v)return t.copy(r);const g=u*c-l*v;if(g<=0&&c>=0&&v<=0)return o=c/(c-v),t.copy(i).addScaledVector(Wl,o);const m=h*v-u*d;if(m<=0&&d-h>=0&&u-v>=0)return oM.subVectors(r,n),o=(d-h)/(d-h+(u-v)),t.copy(n).addScaledVector(oM,o);const f=1/(m+g+p);return a=g*f,o=p*f,t.copy(i).addScaledVector(Gl,a).addScaledVector(Wl,o)}equals(e){return e.a.equals(this.a)&&e.b.equals(this.b)&&e.c.equals(this.c)}}const lM={aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,rebeccapurple:6697881,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074},aa={h:0,s:0,l:0},tf={h:0,s:0,l:0};function Uv(s,e,t){return t<0&&(t+=1),t>1&&(t-=1),t<1/6?s+(e-s)*6*t:t<1/2?e:t<2/3?s+(e-s)*6*(2/3-t):s}class Wt{constructor(e,t,i){return this.isColor=!0,this.r=1,this.g=1,this.b=1,this.set(e,t,i)}set(e,t,i){if(t===void 0&&i===void 0){const n=e;n&&n.isColor?this.copy(n):typeof n=="number"?this.setHex(n):typeof n=="string"&&this.setStyle(n)}else this.setRGB(e,t,i);return this}setScalar(e){return this.r=e,this.g=e,this.b=e,this}setHex(e,t=zn){return e=Math.floor(e),this.r=(e>>16&255)/255,this.g=(e>>8&255)/255,this.b=(e&255)/255,Ut.colorSpaceToWorking(this,t),this}setRGB(e,t,i,n=Ut.workingColorSpace){return this.r=e,this.g=t,this.b=i,Ut.colorSpaceToWorking(this,n),this}setHSL(e,t,i,n=Ut.workingColorSpace){if(e=zR(e,1),t=It(t,0,1),i=It(i,0,1),t===0)this.r=this.g=this.b=i;else{const r=i<=.5?i*(1+t):i+t-i*t,a=2*i-r;this.r=Uv(a,r,e+1/3),this.g=Uv(a,r,e),this.b=Uv(a,r,e-1/3)}return Ut.colorSpaceToWorking(this,n),this}setStyle(e,t=zn){function i(r){r!==void 0&&parseFloat(r)<1&&yt("Color: Alpha component of "+e+" will be ignored.")}let n;if(n=/^(\w+)\(([^\)]*)\)/.exec(e)){let r;const a=n[1],o=n[2];switch(a){case"rgb":case"rgba":if(r=/^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return i(r[4]),this.setRGB(Math.min(255,parseInt(r[1],10))/255,Math.min(255,parseInt(r[2],10))/255,Math.min(255,parseInt(r[3],10))/255,t);if(r=/^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return i(r[4]),this.setRGB(Math.min(100,parseInt(r[1],10))/100,Math.min(100,parseInt(r[2],10))/100,Math.min(100,parseInt(r[3],10))/100,t);break;case"hsl":case"hsla":if(r=/^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return i(r[4]),this.setHSL(parseFloat(r[1])/360,parseFloat(r[2])/100,parseFloat(r[3])/100,t);break;default:yt("Color: Unknown color model "+e)}}else if(n=/^\#([A-Fa-f\d]+)$/.exec(e)){const r=n[1],a=r.length;if(a===3)return this.setRGB(parseInt(r.charAt(0),16)/15,parseInt(r.charAt(1),16)/15,parseInt(r.charAt(2),16)/15,t);if(a===6)return this.setHex(parseInt(r,16),t);yt("Color: Invalid hex color "+e)}else if(e&&e.length>0)return this.setColorName(e,t);return this}setColorName(e,t=zn){const i=lM[e.toLowerCase()];return i!==void 0?this.setHex(i,t):yt("Color: Unknown color "+e),this}clone(){return new this.constructor(this.r,this.g,this.b)}copy(e){return this.r=e.r,this.g=e.g,this.b=e.b,this}copySRGBToLinear(e){return this.r=ur(e.r),this.g=ur(e.g),this.b=ur(e.b),this}copyLinearToSRGB(e){return this.r=kl(e.r),this.g=kl(e.g),this.b=kl(e.b),this}convertSRGBToLinear(){return this.copySRGBToLinear(this),this}convertLinearToSRGB(){return this.copyLinearToSRGB(this),this}getHex(e=zn){return Ut.workingToColorSpace(on.copy(this),e),Math.round(It(on.r*255,0,255))*65536+Math.round(It(on.g*255,0,255))*256+Math.round(It(on.b*255,0,255))}getHexString(e=zn){return("000000"+this.getHex(e).toString(16)).slice(-6)}getHSL(e,t=Ut.workingColorSpace){Ut.workingToColorSpace(on.copy(this),t);const i=on.r,n=on.g,r=on.b,a=Math.max(i,n,r),o=Math.min(i,n,r);let l,c;const h=(o+a)/2;if(o===a)l=0,c=0;else{const d=a-o;switch(c=h<=.5?d/(a+o):d/(2-a-o),a){case i:l=(n-r)/d+(n0!=e>0&&this.version++,this._alphaTest=e}onBeforeRender(){}onBeforeCompile(){}customProgramCacheKey(){return this.onBeforeCompile.toString()}setValues(e){if(e!==void 0)for(const t in e){const i=e[t];if(i===void 0){yt(`Material: parameter '${t}' has value of undefined.`);continue}const n=this[t];if(n===void 0){yt(`Material: '${t}' is not a property of THREE.${this.type}.`);continue}n&&n.isColor?n.set(i):n&&n.isVector3&&i&&i.isVector3?n.copy(i):this[t]=i}}toJSON(e){const t=e===void 0||typeof e=="string";t&&(e={textures:{},images:{}});const i={metadata:{version:4.7,type:"Material",generator:"Material.toJSON"}};i.uuid=this.uuid,i.type=this.type,this.name!==""&&(i.name=this.name),this.color&&this.color.isColor&&(i.color=this.color.getHex()),this.roughness!==void 0&&(i.roughness=this.roughness),this.metalness!==void 0&&(i.metalness=this.metalness),this.sheen!==void 0&&(i.sheen=this.sheen),this.sheenColor&&this.sheenColor.isColor&&(i.sheenColor=this.sheenColor.getHex()),this.sheenRoughness!==void 0&&(i.sheenRoughness=this.sheenRoughness),this.emissive&&this.emissive.isColor&&(i.emissive=this.emissive.getHex()),this.emissiveIntensity!==void 0&&this.emissiveIntensity!==1&&(i.emissiveIntensity=this.emissiveIntensity),this.specular&&this.specular.isColor&&(i.specular=this.specular.getHex()),this.specularIntensity!==void 0&&(i.specularIntensity=this.specularIntensity),this.specularColor&&this.specularColor.isColor&&(i.specularColor=this.specularColor.getHex()),this.shininess!==void 0&&(i.shininess=this.shininess),this.clearcoat!==void 0&&(i.clearcoat=this.clearcoat),this.clearcoatRoughness!==void 0&&(i.clearcoatRoughness=this.clearcoatRoughness),this.clearcoatMap&&this.clearcoatMap.isTexture&&(i.clearcoatMap=this.clearcoatMap.toJSON(e).uuid),this.clearcoatRoughnessMap&&this.clearcoatRoughnessMap.isTexture&&(i.clearcoatRoughnessMap=this.clearcoatRoughnessMap.toJSON(e).uuid),this.clearcoatNormalMap&&this.clearcoatNormalMap.isTexture&&(i.clearcoatNormalMap=this.clearcoatNormalMap.toJSON(e).uuid,i.clearcoatNormalScale=this.clearcoatNormalScale.toArray()),this.sheenColorMap&&this.sheenColorMap.isTexture&&(i.sheenColorMap=this.sheenColorMap.toJSON(e).uuid),this.sheenRoughnessMap&&this.sheenRoughnessMap.isTexture&&(i.sheenRoughnessMap=this.sheenRoughnessMap.toJSON(e).uuid),this.dispersion!==void 0&&(i.dispersion=this.dispersion),this.iridescence!==void 0&&(i.iridescence=this.iridescence),this.iridescenceIOR!==void 0&&(i.iridescenceIOR=this.iridescenceIOR),this.iridescenceThicknessRange!==void 0&&(i.iridescenceThicknessRange=this.iridescenceThicknessRange),this.iridescenceMap&&this.iridescenceMap.isTexture&&(i.iridescenceMap=this.iridescenceMap.toJSON(e).uuid),this.iridescenceThicknessMap&&this.iridescenceThicknessMap.isTexture&&(i.iridescenceThicknessMap=this.iridescenceThicknessMap.toJSON(e).uuid),this.anisotropy!==void 0&&(i.anisotropy=this.anisotropy),this.anisotropyRotation!==void 0&&(i.anisotropyRotation=this.anisotropyRotation),this.anisotropyMap&&this.anisotropyMap.isTexture&&(i.anisotropyMap=this.anisotropyMap.toJSON(e).uuid),this.map&&this.map.isTexture&&(i.map=this.map.toJSON(e).uuid),this.matcap&&this.matcap.isTexture&&(i.matcap=this.matcap.toJSON(e).uuid),this.alphaMap&&this.alphaMap.isTexture&&(i.alphaMap=this.alphaMap.toJSON(e).uuid),this.lightMap&&this.lightMap.isTexture&&(i.lightMap=this.lightMap.toJSON(e).uuid,i.lightMapIntensity=this.lightMapIntensity),this.aoMap&&this.aoMap.isTexture&&(i.aoMap=this.aoMap.toJSON(e).uuid,i.aoMapIntensity=this.aoMapIntensity),this.bumpMap&&this.bumpMap.isTexture&&(i.bumpMap=this.bumpMap.toJSON(e).uuid,i.bumpScale=this.bumpScale),this.normalMap&&this.normalMap.isTexture&&(i.normalMap=this.normalMap.toJSON(e).uuid,i.normalMapType=this.normalMapType,i.normalScale=this.normalScale.toArray()),this.displacementMap&&this.displacementMap.isTexture&&(i.displacementMap=this.displacementMap.toJSON(e).uuid,i.displacementScale=this.displacementScale,i.displacementBias=this.displacementBias),this.roughnessMap&&this.roughnessMap.isTexture&&(i.roughnessMap=this.roughnessMap.toJSON(e).uuid),this.metalnessMap&&this.metalnessMap.isTexture&&(i.metalnessMap=this.metalnessMap.toJSON(e).uuid),this.emissiveMap&&this.emissiveMap.isTexture&&(i.emissiveMap=this.emissiveMap.toJSON(e).uuid),this.specularMap&&this.specularMap.isTexture&&(i.specularMap=this.specularMap.toJSON(e).uuid),this.specularIntensityMap&&this.specularIntensityMap.isTexture&&(i.specularIntensityMap=this.specularIntensityMap.toJSON(e).uuid),this.specularColorMap&&this.specularColorMap.isTexture&&(i.specularColorMap=this.specularColorMap.toJSON(e).uuid),this.envMap&&this.envMap.isTexture&&(i.envMap=this.envMap.toJSON(e).uuid,this.combine!==void 0&&(i.combine=this.combine)),this.envMapRotation!==void 0&&(i.envMapRotation=this.envMapRotation.toArray()),this.envMapIntensity!==void 0&&(i.envMapIntensity=this.envMapIntensity),this.reflectivity!==void 0&&(i.reflectivity=this.reflectivity),this.refractionRatio!==void 0&&(i.refractionRatio=this.refractionRatio),this.gradientMap&&this.gradientMap.isTexture&&(i.gradientMap=this.gradientMap.toJSON(e).uuid),this.transmission!==void 0&&(i.transmission=this.transmission),this.transmissionMap&&this.transmissionMap.isTexture&&(i.transmissionMap=this.transmissionMap.toJSON(e).uuid),this.thickness!==void 0&&(i.thickness=this.thickness),this.thicknessMap&&this.thicknessMap.isTexture&&(i.thicknessMap=this.thicknessMap.toJSON(e).uuid),this.attenuationDistance!==void 0&&this.attenuationDistance!==1/0&&(i.attenuationDistance=this.attenuationDistance),this.attenuationColor!==void 0&&(i.attenuationColor=this.attenuationColor.getHex()),this.size!==void 0&&(i.size=this.size),this.shadowSide!==null&&(i.shadowSide=this.shadowSide),this.sizeAttenuation!==void 0&&(i.sizeAttenuation=this.sizeAttenuation),this.blending!==Cl&&(i.blending=this.blending),this.side!==Qr&&(i.side=this.side),this.vertexColors===!0&&(i.vertexColors=!0),this.opacity<1&&(i.opacity=this.opacity),this.transparent===!0&&(i.transparent=!0),this.blendSrc!==_0&&(i.blendSrc=this.blendSrc),this.blendDst!==b0&&(i.blendDst=this.blendDst),this.blendEquation!==no&&(i.blendEquation=this.blendEquation),this.blendSrcAlpha!==null&&(i.blendSrcAlpha=this.blendSrcAlpha),this.blendDstAlpha!==null&&(i.blendDstAlpha=this.blendDstAlpha),this.blendEquationAlpha!==null&&(i.blendEquationAlpha=this.blendEquationAlpha),this.blendColor&&this.blendColor.isColor&&(i.blendColor=this.blendColor.getHex()),this.blendAlpha!==0&&(i.blendAlpha=this.blendAlpha),this.depthFunc!==Al&&(i.depthFunc=this.depthFunc),this.depthTest===!1&&(i.depthTest=this.depthTest),this.depthWrite===!1&&(i.depthWrite=this.depthWrite),this.colorWrite===!1&&(i.colorWrite=this.colorWrite),this.stencilWriteMask!==255&&(i.stencilWriteMask=this.stencilWriteMask),this.stencilFunc!==Vb&&(i.stencilFunc=this.stencilFunc),this.stencilRef!==0&&(i.stencilRef=this.stencilRef),this.stencilFuncMask!==255&&(i.stencilFuncMask=this.stencilFuncMask),this.stencilFail!==Dl&&(i.stencilFail=this.stencilFail),this.stencilZFail!==Dl&&(i.stencilZFail=this.stencilZFail),this.stencilZPass!==Dl&&(i.stencilZPass=this.stencilZPass),this.stencilWrite===!0&&(i.stencilWrite=this.stencilWrite),this.rotation!==void 0&&this.rotation!==0&&(i.rotation=this.rotation),this.polygonOffset===!0&&(i.polygonOffset=!0),this.polygonOffsetFactor!==0&&(i.polygonOffsetFactor=this.polygonOffsetFactor),this.polygonOffsetUnits!==0&&(i.polygonOffsetUnits=this.polygonOffsetUnits),this.linewidth!==void 0&&this.linewidth!==1&&(i.linewidth=this.linewidth),this.dashSize!==void 0&&(i.dashSize=this.dashSize),this.gapSize!==void 0&&(i.gapSize=this.gapSize),this.scale!==void 0&&(i.scale=this.scale),this.dithering===!0&&(i.dithering=!0),this.alphaTest>0&&(i.alphaTest=this.alphaTest),this.alphaHash===!0&&(i.alphaHash=!0),this.alphaToCoverage===!0&&(i.alphaToCoverage=!0),this.premultipliedAlpha===!0&&(i.premultipliedAlpha=!0),this.forceSinglePass===!0&&(i.forceSinglePass=!0),this.wireframe===!0&&(i.wireframe=!0),this.wireframeLinewidth>1&&(i.wireframeLinewidth=this.wireframeLinewidth),this.wireframeLinecap!=="round"&&(i.wireframeLinecap=this.wireframeLinecap),this.wireframeLinejoin!=="round"&&(i.wireframeLinejoin=this.wireframeLinejoin),this.flatShading===!0&&(i.flatShading=!0),this.visible===!1&&(i.visible=!1),this.toneMapped===!1&&(i.toneMapped=!1),this.fog===!1&&(i.fog=!1),Object.keys(this.userData).length>0&&(i.userData=this.userData);function n(r){const a=[];for(const o in r){const l=r[o];delete l.metadata,a.push(l)}return a}if(t){const r=n(e.textures),a=n(e.images);r.length>0&&(i.textures=r),a.length>0&&(i.images=a)}return i}clone(){return new this.constructor().copy(this)}copy(e){this.name=e.name,this.blending=e.blending,this.side=e.side,this.vertexColors=e.vertexColors,this.opacity=e.opacity,this.transparent=e.transparent,this.blendSrc=e.blendSrc,this.blendDst=e.blendDst,this.blendEquation=e.blendEquation,this.blendSrcAlpha=e.blendSrcAlpha,this.blendDstAlpha=e.blendDstAlpha,this.blendEquationAlpha=e.blendEquationAlpha,this.blendColor.copy(e.blendColor),this.blendAlpha=e.blendAlpha,this.depthFunc=e.depthFunc,this.depthTest=e.depthTest,this.depthWrite=e.depthWrite,this.stencilWriteMask=e.stencilWriteMask,this.stencilFunc=e.stencilFunc,this.stencilRef=e.stencilRef,this.stencilFuncMask=e.stencilFuncMask,this.stencilFail=e.stencilFail,this.stencilZFail=e.stencilZFail,this.stencilZPass=e.stencilZPass,this.stencilWrite=e.stencilWrite;const t=e.clippingPlanes;let i=null;if(t!==null){const n=t.length;i=new Array(n);for(let r=0;r!==n;++r)i[r]=t[r].clone()}return this.clippingPlanes=i,this.clipIntersection=e.clipIntersection,this.clipShadows=e.clipShadows,this.shadowSide=e.shadowSide,this.colorWrite=e.colorWrite,this.precision=e.precision,this.polygonOffset=e.polygonOffset,this.polygonOffsetFactor=e.polygonOffsetFactor,this.polygonOffsetUnits=e.polygonOffsetUnits,this.dithering=e.dithering,this.alphaTest=e.alphaTest,this.alphaHash=e.alphaHash,this.alphaToCoverage=e.alphaToCoverage,this.premultipliedAlpha=e.premultipliedAlpha,this.forceSinglePass=e.forceSinglePass,this.visible=e.visible,this.toneMapped=e.toneMapped,this.userData=JSON.parse(JSON.stringify(e.userData)),this}dispose(){this.dispatchEvent({type:"dispose"})}set needsUpdate(e){e===!0&&this.version++}}class cM extends nf{constructor(e){super(),this.isMeshBasicMaterial=!0,this.type="MeshBasicMaterial",this.color=new Wt(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new co,this.combine=Db,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.specularMap=e.specularMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.combine=e.combine,this.reflectivity=e.reflectivity,this.refractionRatio=e.refractionRatio,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.fog=e.fog,this}}const Si=new De,sf=new Gt;let iI=0;class Vs{constructor(e,t,i=!1){if(Array.isArray(e))throw new TypeError("THREE.BufferAttribute: array should be a Typed Array.");this.isBufferAttribute=!0,Object.defineProperty(this,"id",{value:iI++}),this.name="",this.array=e,this.itemSize=t,this.count=e!==void 0?e.length/t:0,this.normalized=i,this.usage=Wb,this.updateRanges=[],this.gpuType=dr,this.version=0}onUploadCallback(){}set needsUpdate(e){e===!0&&this.version++}setUsage(e){return this.usage=e,this}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}copy(e){return this.name=e.name,this.array=new e.array.constructor(e.array),this.itemSize=e.itemSize,this.count=e.count,this.normalized=e.normalized,this.usage=e.usage,this.gpuType=e.gpuType,this}copyAt(e,t,i){e*=this.itemSize,i*=t.itemSize;for(let n=0,r=this.itemSize;nt.count&&yt("BufferGeometry: Buffer size too small for points data. Use .dispose() and create a new geometry."),t.needsUpdate=!0}return this}computeBoundingBox(){this.boundingBox===null&&(this.boundingBox=new wh);const e=this.attributes.position,t=this.morphAttributes.position;if(e&&e.isGLBufferAttribute){gi("BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.",this),this.boundingBox.set(new De(-1/0,-1/0,-1/0),new De(1/0,1/0,1/0));return}if(e!==void 0){if(this.boundingBox.setFromBufferAttribute(e),t)for(let i=0,n=t.length;i0&&(e.userData=this.userData),this.parameters!==void 0){const l=this.parameters;for(const c in l)l[c]!==void 0&&(e[c]=l[c]);return e}e.data={attributes:{}};const t=this.index;t!==null&&(e.data.index={type:t.array.constructor.name,array:Array.prototype.slice.call(t.array)});const i=this.attributes;for(const l in i){const c=i[l];e.data.attributes[l]=c.toJSON(e.data)}const n={};let r=!1;for(const l in this.morphAttributes){const c=this.morphAttributes[l],h=[];for(let d=0,p=c.length;d0&&(n[l]=h,r=!0)}r&&(e.data.morphAttributes=n,e.data.morphTargetsRelative=this.morphTargetsRelative);const a=this.groups;a.length>0&&(e.data.groups=JSON.parse(JSON.stringify(a)));const o=this.boundingSphere;return o!==null&&(e.data.boundingSphere=o.toJSON()),e}clone(){return new this.constructor().copy(this)}copy(e){this.index=null,this.attributes={},this.morphAttributes={},this.groups=[],this.boundingBox=null,this.boundingSphere=null;const t={};this.name=e.name;const i=e.index;i!==null&&this.setIndex(i.clone());const n=e.attributes;for(const c in n){const h=n[c];this.setAttribute(c,h.clone(t))}const r=e.morphAttributes;for(const c in r){const h=[],d=r[c];for(let p=0,u=d.length;p0){const i=e[t[0]];if(i!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let n=0,r=i.length;n(e.far-e.near)**2))&&(uM.copy(r).invert(),uo.copy(e.ray).applyMatrix4(uM),!(i.boundingBox!==null&&uo.intersectsBox(i.boundingBox)===!1)&&this._computeIntersections(e,t,uo)))}_computeIntersections(e,t,i){let n;const r=this.geometry,a=this.material,o=r.index,l=r.attributes.position,c=r.attributes.uv,h=r.attributes.uv1,d=r.attributes.normal,p=r.groups,u=r.drawRange;if(o!==null)if(Array.isArray(a))for(let v=0,g=p.length;vt.far?null:{distance:c,point:hf.clone(),object:s}}function df(s,e,t,i,n,r,a,o,l,c){s.getVertexPosition(o,af),s.getVertexPosition(l,of),s.getVertexPosition(c,lf);const h=sI(s,e,t,i,af,of,lf,fM);if(h){const d=new De;Ss.getBarycoord(fM,af,of,lf,d),n&&(h.uv=Ss.getInterpolatedAttribute(n,o,l,c,d,new Gt)),r&&(h.uv1=Ss.getInterpolatedAttribute(r,o,l,c,d,new Gt)),a&&(h.normal=Ss.getInterpolatedAttribute(a,o,l,c,d,new De),h.normal.dot(i.direction)>0&&h.normal.multiplyScalar(-1));const p={a:o,b:l,c,normal:new De,materialIndex:0};Ss.getNormal(af,of,lf,p.normal),h.face=p,h.barycoord=d}return h}class Ph extends oa{constructor(e=1,t=1,i=1,n=1,r=1,a=1){super(),this.type="BoxGeometry",this.parameters={width:e,height:t,depth:i,widthSegments:n,heightSegments:r,depthSegments:a};const o=this;n=Math.floor(n),r=Math.floor(r),a=Math.floor(a);const l=[],c=[],h=[],d=[];let p=0,u=0;v("z","y","x",-1,-1,i,t,e,a,r,0),v("z","y","x",1,-1,i,t,-e,a,r,1),v("x","z","y",1,1,e,i,t,n,a,2),v("x","z","y",1,-1,e,i,-t,n,a,3),v("x","y","z",1,-1,e,t,i,n,r,4),v("x","y","z",-1,-1,e,t,-i,n,r,5),this.setIndex(l),this.setAttribute("position",new ho(c,3)),this.setAttribute("normal",new ho(h,3)),this.setAttribute("uv",new ho(d,2));function v(g,m,f,y,x,_,S,b,E,w,M){const C=_/E,I=S/w,P=_/2,k=S/2,A=b/2,B=E+1,F=w+1;let H=0,q=0;const G=new De;for(let re=0;re0?1:-1,h.push(G.x,G.y,G.z),d.push($/E),d.push(1-re/w),H+=1}}for(let re=0;re0&&(t.defines=this.defines),t.vertexShader=this.vertexShader,t.fragmentShader=this.fragmentShader,t.lights=this.lights,t.clipping=this.clipping;const i={};for(const n in this.extensions)this.extensions[n]===!0&&(i[n]=!0);return Object.keys(i).length>0&&(t.extensions=i),t}}class gM extends ts{constructor(){super(),this.isCamera=!0,this.type="Camera",this.matrixWorldInverse=new Di,this.projectionMatrix=new Di,this.projectionMatrixInverse=new Di,this.coordinateSystem=Hs,this._reversedDepth=!1}get reversedDepth(){return this._reversedDepth}copy(e,t){return super.copy(e,t),this.matrixWorldInverse.copy(e.matrixWorldInverse),this.projectionMatrix.copy(e.projectionMatrix),this.projectionMatrixInverse.copy(e.projectionMatrixInverse),this.coordinateSystem=e.coordinateSystem,this}getWorldDirection(e){return super.getWorldDirection(e).negate()}updateMatrixWorld(e){super.updateMatrixWorld(e),this.matrixWorldInverse.copy(this.matrixWorld).invert()}updateWorldMatrix(e,t){super.updateWorldMatrix(e,t),this.matrixWorldInverse.copy(this.matrixWorld).invert()}clone(){return new this.constructor().copy(this)}}const ca=new De,vM=new Gt,yM=new Gt;class ws extends gM{constructor(e=50,t=1,i=.1,n=2e3){super(),this.isPerspectiveCamera=!0,this.type="PerspectiveCamera",this.fov=e,this.zoom=1,this.near=i,this.far=n,this.focus=10,this.aspect=t,this.view=null,this.filmGauge=35,this.filmOffset=0,this.updateProjectionMatrix()}copy(e,t){return super.copy(e,t),this.fov=e.fov,this.zoom=e.zoom,this.near=e.near,this.far=e.far,this.focus=e.focus,this.aspect=e.aspect,this.view=e.view===null?null:Object.assign({},e.view),this.filmGauge=e.filmGauge,this.filmOffset=e.filmOffset,this}setFocalLength(e){const t=.5*this.getFilmHeight()/e;this.fov=gv*2*Math.atan(t),this.updateProjectionMatrix()}getFocalLength(){const e=Math.tan(mv*.5*this.fov);return .5*this.getFilmHeight()/e}getEffectiveFOV(){return gv*2*Math.atan(Math.tan(mv*.5*this.fov)/this.zoom)}getFilmWidth(){return this.filmGauge*Math.min(this.aspect,1)}getFilmHeight(){return this.filmGauge/Math.max(this.aspect,1)}getViewBounds(e,t,i){ca.set(-1,-1,.5).applyMatrix4(this.projectionMatrixInverse),t.set(ca.x,ca.y).multiplyScalar(-e/ca.z),ca.set(1,1,.5).applyMatrix4(this.projectionMatrixInverse),i.set(ca.x,ca.y).multiplyScalar(-e/ca.z)}getViewSize(e,t){return this.getViewBounds(e,vM,yM),t.subVectors(yM,vM)}setViewOffset(e,t,i,n,r,a){this.aspect=e/t,this.view===null&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1}),this.view.enabled=!0,this.view.fullWidth=e,this.view.fullHeight=t,this.view.offsetX=i,this.view.offsetY=n,this.view.width=r,this.view.height=a,this.updateProjectionMatrix()}clearViewOffset(){this.view!==null&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){const e=this.near;let t=e*Math.tan(mv*.5*this.fov)/this.zoom,i=2*t,n=this.aspect*i,r=-.5*n;const a=this.view;if(this.view!==null&&this.view.enabled){const l=a.fullWidth,c=a.fullHeight;r+=a.offsetX*n/l,t-=a.offsetY*i/c,n*=a.width/l,i*=a.height/c}const o=this.filmOffset;o!==0&&(r+=e*o/this.getFilmWidth()),this.projectionMatrix.makePerspective(r,r+n,t,t-i,e,this.far,this.coordinateSystem,this.reversedDepth),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(e){const t=super.toJSON(e);return t.object.fov=this.fov,t.object.zoom=this.zoom,t.object.near=this.near,t.object.far=this.far,t.object.focus=this.focus,t.object.aspect=this.aspect,this.view!==null&&(t.object.view=Object.assign({},this.view)),t.object.filmGauge=this.filmGauge,t.object.filmOffset=this.filmOffset,t}}const ql=-90,Zl=1;class cI extends ts{constructor(e,t,i){super(),this.type="CubeCamera",this.renderTarget=i,this.coordinateSystem=null,this.activeMipmapLevel=0;const n=new ws(ql,Zl,e,t);n.layers=this.layers,this.add(n);const r=new ws(ql,Zl,e,t);r.layers=this.layers,this.add(r);const a=new ws(ql,Zl,e,t);a.layers=this.layers,this.add(a);const o=new ws(ql,Zl,e,t);o.layers=this.layers,this.add(o);const l=new ws(ql,Zl,e,t);l.layers=this.layers,this.add(l);const c=new ws(ql,Zl,e,t);c.layers=this.layers,this.add(c)}updateCoordinateSystem(){const e=this.coordinateSystem,t=this.children.concat(),[i,n,r,a,o,l]=t;for(const c of t)this.remove(c);if(e===Hs)i.up.set(0,1,0),i.lookAt(1,0,0),n.up.set(0,1,0),n.lookAt(-1,0,0),r.up.set(0,0,-1),r.lookAt(0,1,0),a.up.set(0,0,1),a.lookAt(0,-1,0),o.up.set(0,1,0),o.lookAt(0,0,1),l.up.set(0,1,0),l.lookAt(0,0,-1);else if(e===jp)i.up.set(0,-1,0),i.lookAt(-1,0,0),n.up.set(0,-1,0),n.lookAt(1,0,0),r.up.set(0,0,1),r.lookAt(0,1,0),a.up.set(0,0,-1),a.lookAt(0,-1,0),o.up.set(0,-1,0),o.lookAt(0,0,1),l.up.set(0,-1,0),l.lookAt(0,0,-1);else throw new Error("THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: "+e);for(const c of t)this.add(c),c.updateMatrixWorld()}update(e,t){this.parent===null&&this.updateMatrixWorld();const{renderTarget:i,activeMipmapLevel:n}=this;this.coordinateSystem!==e.coordinateSystem&&(this.coordinateSystem=e.coordinateSystem,this.updateCoordinateSystem());const[r,a,o,l,c,h]=this.children,d=e.getRenderTarget(),p=e.getActiveCubeFace(),u=e.getActiveMipmapLevel(),v=e.xr.enabled;e.xr.enabled=!1;const g=i.texture.generateMipmaps;i.texture.generateMipmaps=!1,e.setRenderTarget(i,0,n),e.render(t,r),e.setRenderTarget(i,1,n),e.render(t,a),e.setRenderTarget(i,2,n),e.render(t,o),e.setRenderTarget(i,3,n),e.render(t,l),e.setRenderTarget(i,4,n),e.render(t,c),i.texture.generateMipmaps=g,e.setRenderTarget(i,5,n),e.render(t,h),e.setRenderTarget(d,p,u),e.xr.enabled=v,i.texture.needsPMREMUpdate=!0}}class xM extends mn{constructor(e=[],t=Pl,i,n,r,a,o,l,c,h){super(e,t,i,n,r,a,o,l,c,h),this.isCubeTexture=!0,this.flipY=!1}get images(){return this.image}set images(e){this.image=e}}class hI extends ao{constructor(e=1,t={}){super(e,e,t),this.isWebGLCubeRenderTarget=!0;const i={width:e,height:e,depth:1},n=[i,i,i,i,i,i];this.texture=new xM(n),this._setTextureOptions(t),this.texture.isRenderTargetTexture=!0}fromEquirectangularTexture(e,t){this.texture.type=t.type,this.texture.colorSpace=t.colorSpace,this.texture.generateMipmaps=t.generateMipmaps,this.texture.minFilter=t.minFilter,this.texture.magFilter=t.magFilter;const i={uniforms:{tEquirect:{value:null}},vertexShader:` varying vec3 vWorldDirection; vec3 transformDirection( in vec3 dir, in mat4 matrix ) { return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz ); } void main() { vWorldDirection = transformDirection( position, modelMatrix ); #include #include } `,fragmentShader:` uniform sampler2D tEquirect; varying vec3 vWorldDirection; #include void main() { vec3 direction = normalize( vWorldDirection ); vec2 sampleUV = equirectUv( direction ); gl_FragColor = texture2D( tEquirect, sampleUV ); } `},n=new Ph(5,5,5),r=new yr({name:"CubemapFromEquirect",uniforms:jl(i.uniforms),vertexShader:i.vertexShader,fragmentShader:i.fragmentShader,side:En,blending:lr});r.uniforms.tEquirect.value=t;const a=new la(n,r),o=t.minFilter;return t.minFilter===so&&(t.minFilter=es),new cI(1,10,this).update(e,a),t.minFilter=o,a.geometry.dispose(),a.material.dispose(),this}clear(e,t=!0,i=!0,n=!0){const r=e.getRenderTarget();for(let a=0;a<6;a++)e.setRenderTarget(this,a),e.clear(t,i,n);e.setRenderTarget(r)}}let uf=class extends ts{constructor(){super(),this.isGroup=!0,this.type="Group"}};const dI={type:"move"};class zv{constructor(){this._targetRay=null,this._grip=null,this._hand=null}getHandSpace(){return this._hand===null&&(this._hand=new uf,this._hand.matrixAutoUpdate=!1,this._hand.visible=!1,this._hand.joints={},this._hand.inputState={pinching:!1}),this._hand}getTargetRaySpace(){return this._targetRay===null&&(this._targetRay=new uf,this._targetRay.matrixAutoUpdate=!1,this._targetRay.visible=!1,this._targetRay.hasLinearVelocity=!1,this._targetRay.linearVelocity=new De,this._targetRay.hasAngularVelocity=!1,this._targetRay.angularVelocity=new De),this._targetRay}getGripSpace(){return this._grip===null&&(this._grip=new uf,this._grip.matrixAutoUpdate=!1,this._grip.visible=!1,this._grip.hasLinearVelocity=!1,this._grip.linearVelocity=new De,this._grip.hasAngularVelocity=!1,this._grip.angularVelocity=new De),this._grip}dispatchEvent(e){return this._targetRay!==null&&this._targetRay.dispatchEvent(e),this._grip!==null&&this._grip.dispatchEvent(e),this._hand!==null&&this._hand.dispatchEvent(e),this}connect(e){if(e&&e.hand){const t=this._hand;if(t)for(const i of e.hand.values())this._getHandJoint(t,i)}return this.dispatchEvent({type:"connected",data:e}),this}disconnect(e){return this.dispatchEvent({type:"disconnected",data:e}),this._targetRay!==null&&(this._targetRay.visible=!1),this._grip!==null&&(this._grip.visible=!1),this._hand!==null&&(this._hand.visible=!1),this}update(e,t,i){let n=null,r=null,a=null;const o=this._targetRay,l=this._grip,c=this._hand;if(e&&t.session.visibilityState!=="visible-blurred"){if(c&&e.hand){a=!0;for(const g of e.hand.values()){const m=t.getJointPose(g,i),f=this._getHandJoint(c,g);m!==null&&(f.matrix.fromArray(m.transform.matrix),f.matrix.decompose(f.position,f.rotation,f.scale),f.matrixWorldNeedsUpdate=!0,f.jointRadius=m.radius),f.visible=m!==null}const h=c.joints["index-finger-tip"],d=c.joints["thumb-tip"],p=h.position.distanceTo(d.position),u=.02,v=.005;c.inputState.pinching&&p>u+v?(c.inputState.pinching=!1,this.dispatchEvent({type:"pinchend",handedness:e.handedness,target:this})):!c.inputState.pinching&&p<=u-v&&(c.inputState.pinching=!0,this.dispatchEvent({type:"pinchstart",handedness:e.handedness,target:this}))}else l!==null&&e.gripSpace&&(r=t.getPose(e.gripSpace,i),r!==null&&(l.matrix.fromArray(r.transform.matrix),l.matrix.decompose(l.position,l.rotation,l.scale),l.matrixWorldNeedsUpdate=!0,r.linearVelocity?(l.hasLinearVelocity=!0,l.linearVelocity.copy(r.linearVelocity)):l.hasLinearVelocity=!1,r.angularVelocity?(l.hasAngularVelocity=!0,l.angularVelocity.copy(r.angularVelocity)):l.hasAngularVelocity=!1));o!==null&&(n=t.getPose(e.targetRaySpace,i),n===null&&r!==null&&(n=r),n!==null&&(o.matrix.fromArray(n.transform.matrix),o.matrix.decompose(o.position,o.rotation,o.scale),o.matrixWorldNeedsUpdate=!0,n.linearVelocity?(o.hasLinearVelocity=!0,o.linearVelocity.copy(n.linearVelocity)):o.hasLinearVelocity=!1,n.angularVelocity?(o.hasAngularVelocity=!0,o.angularVelocity.copy(n.angularVelocity)):o.hasAngularVelocity=!1,this.dispatchEvent(dI)))}return o!==null&&(o.visible=n!==null),l!==null&&(l.visible=r!==null),c!==null&&(c.visible=a!==null),this}_getHandJoint(e,t){if(e.joints[t.jointName]===void 0){const i=new uf;i.matrixAutoUpdate=!1,i.visible=!1,e.joints[t.jointName]=i,e.add(i)}return e.joints[t.jointName]}}class uI extends mn{constructor(e=null,t=1,i=1,n,r,a,o,l,c=Fn,h=Fn,d,p){super(null,a,o,l,c,h,n,r,d,p),this.isDataTexture=!0,this.image={data:e,width:t,height:i},this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}}const Hv=new De,pI=new De,fI=new Mt;class po{constructor(e=new De(1,0,0),t=0){this.isPlane=!0,this.normal=e,this.constant=t}set(e,t){return this.normal.copy(e),this.constant=t,this}setComponents(e,t,i,n){return this.normal.set(e,t,i),this.constant=n,this}setFromNormalAndCoplanarPoint(e,t){return this.normal.copy(e),this.constant=-t.dot(this.normal),this}setFromCoplanarPoints(e,t,i){const n=Hv.subVectors(i,t).cross(pI.subVectors(e,t)).normalize();return this.setFromNormalAndCoplanarPoint(n,e),this}copy(e){return this.normal.copy(e.normal),this.constant=e.constant,this}normalize(){const e=1/this.normal.length();return this.normal.multiplyScalar(e),this.constant*=e,this}negate(){return this.constant*=-1,this.normal.negate(),this}distanceToPoint(e){return this.normal.dot(e)+this.constant}distanceToSphere(e){return this.distanceToPoint(e.center)-e.radius}projectPoint(e,t){return t.copy(e).addScaledVector(this.normal,-this.distanceToPoint(e))}intersectLine(e,t){const i=e.delta(Hv),n=this.normal.dot(i);if(n===0)return this.distanceToPoint(e.start)===0?t.copy(e.start):null;const r=-(e.start.dot(this.normal)+this.constant)/n;return r<0||r>1?null:t.copy(e.start).addScaledVector(i,r)}intersectsLine(e){const t=this.distanceToPoint(e.start),i=this.distanceToPoint(e.end);return t<0&&i>0||i<0&&t>0}intersectsBox(e){return e.intersectsPlane(this)}intersectsSphere(e){return e.intersectsPlane(this)}coplanarPoint(e){return e.copy(this.normal).multiplyScalar(-this.constant)}applyMatrix4(e,t){const i=t||fI.getNormalMatrix(e),n=this.coplanarPoint(Hv).applyMatrix4(e),r=this.normal.applyMatrix3(i).normalize();return this.constant=-n.dot(r),this}translate(e){return this.constant-=e.dot(this.normal),this}equals(e){return e.normal.equals(this.normal)&&e.constant===this.constant}clone(){return new this.constructor().copy(this)}}const fo=new Ev,mI=new Gt(.5,.5),pf=new De;class _M{constructor(e=new po,t=new po,i=new po,n=new po,r=new po,a=new po){this.planes=[e,t,i,n,r,a]}set(e,t,i,n,r,a){const o=this.planes;return o[0].copy(e),o[1].copy(t),o[2].copy(i),o[3].copy(n),o[4].copy(r),o[5].copy(a),this}copy(e){const t=this.planes;for(let i=0;i<6;i++)t[i].copy(e.planes[i]);return this}setFromProjectionMatrix(e,t=Hs,i=!1){const n=this.planes,r=e.elements,a=r[0],o=r[1],l=r[2],c=r[3],h=r[4],d=r[5],p=r[6],u=r[7],v=r[8],g=r[9],m=r[10],f=r[11],y=r[12],x=r[13],_=r[14],S=r[15];if(n[0].setComponents(c-a,u-h,f-v,S-y).normalize(),n[1].setComponents(c+a,u+h,f+v,S+y).normalize(),n[2].setComponents(c+o,u+d,f+g,S+x).normalize(),n[3].setComponents(c-o,u-d,f-g,S-x).normalize(),i)n[4].setComponents(l,p,m,_).normalize(),n[5].setComponents(c-l,u-p,f-m,S-_).normalize();else if(n[4].setComponents(c-l,u-p,f-m,S-_).normalize(),t===Hs)n[5].setComponents(c+l,u+p,f+m,S+_).normalize();else if(t===jp)n[5].setComponents(l,p,m,_).normalize();else throw new Error("THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: "+t);return this}intersectsObject(e){if(e.boundingSphere!==void 0)e.boundingSphere===null&&e.computeBoundingSphere(),fo.copy(e.boundingSphere).applyMatrix4(e.matrixWorld);else{const t=e.geometry;t.boundingSphere===null&&t.computeBoundingSphere(),fo.copy(t.boundingSphere).applyMatrix4(e.matrixWorld)}return this.intersectsSphere(fo)}intersectsSprite(e){fo.center.set(0,0,0);const t=mI.distanceTo(e.center);return fo.radius=.7071067811865476+t,fo.applyMatrix4(e.matrixWorld),this.intersectsSphere(fo)}intersectsSphere(e){const t=this.planes,i=e.center,n=-e.radius;for(let r=0;r<6;r++)if(t[r].distanceToPoint(i)0?e.max.x:e.min.x,pf.y=n.normal.y>0?e.max.y:e.min.y,pf.z=n.normal.z>0?e.max.z:e.min.z,n.distanceToPoint(pf)<0)return!1}return!0}containsPoint(e){const t=this.planes;for(let i=0;i<6;i++)if(t[i].distanceToPoint(e)<0)return!1;return!0}clone(){return new this.constructor().copy(this)}}class bM extends mn{constructor(e,t,i=ro,n,r,a,o=Fn,l=Fn,c,h=yh,d=1){if(h!==yh&&h!==xh)throw new Error("DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat");const p={width:e,height:t,depth:d};super(p,n,r,a,o,l,h,i,c),this.isDepthTexture=!0,this.flipY=!1,this.generateMipmaps=!1,this.compareFunction=null}copy(e){return super.copy(e),this.source=new _v(Object.assign({},e.image)),this.compareFunction=e.compareFunction,this}toJSON(e){const t=super.toJSON(e);return this.compareFunction!==null&&(t.compareFunction=this.compareFunction),t}}class MM extends mn{constructor(e=null){super(),this.sourceTexture=e,this.isExternalTexture=!0}copy(e){return super.copy(e),this.sourceTexture=e.sourceTexture,this}}class ff extends oa{constructor(e=1,t=1,i=1,n=1){super(),this.type="PlaneGeometry",this.parameters={width:e,height:t,widthSegments:i,heightSegments:n};const r=e/2,a=t/2,o=Math.floor(i),l=Math.floor(n),c=o+1,h=l+1,d=e/o,p=t/l,u=[],v=[],g=[],m=[];for(let f=0;fu.start-v.start);let p=0;for(let u=1;u 0 vec4 plane; #ifdef ALPHA_TO_COVERAGE float distanceToPlane, distanceGradient; float clipOpacity = 1.0; #pragma unroll_loop_start for ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) { plane = clippingPlanes[ i ]; distanceToPlane = - dot( vClipPosition, plane.xyz ) + plane.w; distanceGradient = fwidth( distanceToPlane ) / 2.0; clipOpacity *= smoothstep( - distanceGradient, distanceGradient, distanceToPlane ); if ( clipOpacity == 0.0 ) discard; } #pragma unroll_loop_end #if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES float unionClipOpacity = 1.0; #pragma unroll_loop_start for ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) { plane = clippingPlanes[ i ]; distanceToPlane = - dot( vClipPosition, plane.xyz ) + plane.w; distanceGradient = fwidth( distanceToPlane ) / 2.0; unionClipOpacity *= 1.0 - smoothstep( - distanceGradient, distanceGradient, distanceToPlane ); } #pragma unroll_loop_end clipOpacity *= 1.0 - unionClipOpacity; #endif diffuseColor.a *= clipOpacity; if ( diffuseColor.a == 0.0 ) discard; #else #pragma unroll_loop_start for ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) { plane = clippingPlanes[ i ]; if ( dot( vClipPosition, plane.xyz ) > plane.w ) discard; } #pragma unroll_loop_end #if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES bool clipped = true; #pragma unroll_loop_start for ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) { plane = clippingPlanes[ i ]; clipped = ( dot( vClipPosition, plane.xyz ) > plane.w ) && clipped; } #pragma unroll_loop_end if ( clipped ) discard; #endif #endif #endif`,BI=`#if NUM_CLIPPING_PLANES > 0 varying vec3 vClipPosition; uniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ]; #endif`,FI=`#if NUM_CLIPPING_PLANES > 0 varying vec3 vClipPosition; #endif`,zI=`#if NUM_CLIPPING_PLANES > 0 vClipPosition = - mvPosition.xyz; #endif`,HI=`#if defined( USE_COLOR_ALPHA ) diffuseColor *= vColor; #elif defined( USE_COLOR ) diffuseColor.rgb *= vColor; #endif`,VI=`#if defined( USE_COLOR_ALPHA ) varying vec4 vColor; #elif defined( USE_COLOR ) varying vec3 vColor; #endif`,GI=`#if defined( USE_COLOR_ALPHA ) varying vec4 vColor; #elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR ) varying vec3 vColor; #endif`,WI=`#if defined( USE_COLOR_ALPHA ) vColor = vec4( 1.0 ); #elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR ) vColor = vec3( 1.0 ); #endif #ifdef USE_COLOR vColor *= color; #endif #ifdef USE_INSTANCING_COLOR vColor.xyz *= instanceColor.xyz; #endif #ifdef USE_BATCHING_COLOR vec3 batchingColor = getBatchingColor( getIndirectIndex( gl_DrawID ) ); vColor.xyz *= batchingColor.xyz; #endif`,XI=`#define PI 3.141592653589793 #define PI2 6.283185307179586 #define PI_HALF 1.5707963267948966 #define RECIPROCAL_PI 0.3183098861837907 #define RECIPROCAL_PI2 0.15915494309189535 #define EPSILON 1e-6 #ifndef saturate #define saturate( a ) clamp( a, 0.0, 1.0 ) #endif #define whiteComplement( a ) ( 1.0 - saturate( a ) ) float pow2( const in float x ) { return x*x; } vec3 pow2( const in vec3 x ) { return x*x; } float pow3( const in float x ) { return x*x*x; } float pow4( const in float x ) { float x2 = x*x; return x2*x2; } float max3( const in vec3 v ) { return max( max( v.x, v.y ), v.z ); } float average( const in vec3 v ) { return dot( v, vec3( 0.3333333 ) ); } highp float rand( const in vec2 uv ) { const highp float a = 12.9898, b = 78.233, c = 43758.5453; highp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI ); return fract( sin( sn ) * c ); } #ifdef HIGH_PRECISION float precisionSafeLength( vec3 v ) { return length( v ); } #else float precisionSafeLength( vec3 v ) { float maxComponent = max3( abs( v ) ); return length( v / maxComponent ) * maxComponent; } #endif struct IncidentLight { vec3 color; vec3 direction; bool visible; }; struct ReflectedLight { vec3 directDiffuse; vec3 directSpecular; vec3 indirectDiffuse; vec3 indirectSpecular; }; #ifdef USE_ALPHAHASH varying vec3 vPosition; #endif vec3 transformDirection( in vec3 dir, in mat4 matrix ) { return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz ); } vec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) { return normalize( ( vec4( dir, 0.0 ) * matrix ).xyz ); } bool isPerspectiveMatrix( mat4 m ) { return m[ 2 ][ 3 ] == - 1.0; } vec2 equirectUv( in vec3 dir ) { float u = atan( dir.z, dir.x ) * RECIPROCAL_PI2 + 0.5; float v = asin( clamp( dir.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5; return vec2( u, v ); } vec3 BRDF_Lambert( const in vec3 diffuseColor ) { return RECIPROCAL_PI * diffuseColor; } vec3 F_Schlick( const in vec3 f0, const in float f90, const in float dotVH ) { float fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH ); return f0 * ( 1.0 - fresnel ) + ( f90 * fresnel ); } float F_Schlick( const in float f0, const in float f90, const in float dotVH ) { float fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH ); return f0 * ( 1.0 - fresnel ) + ( f90 * fresnel ); } // validated`,jI=`#ifdef ENVMAP_TYPE_CUBE_UV #define cubeUV_minMipLevel 4.0 #define cubeUV_minTileSize 16.0 float getFace( vec3 direction ) { vec3 absDirection = abs( direction ); float face = - 1.0; if ( absDirection.x > absDirection.z ) { if ( absDirection.x > absDirection.y ) face = direction.x > 0.0 ? 0.0 : 3.0; else face = direction.y > 0.0 ? 1.0 : 4.0; } else { if ( absDirection.z > absDirection.y ) face = direction.z > 0.0 ? 2.0 : 5.0; else face = direction.y > 0.0 ? 1.0 : 4.0; } return face; } vec2 getUV( vec3 direction, float face ) { vec2 uv; if ( face == 0.0 ) { uv = vec2( direction.z, direction.y ) / abs( direction.x ); } else if ( face == 1.0 ) { uv = vec2( - direction.x, - direction.z ) / abs( direction.y ); } else if ( face == 2.0 ) { uv = vec2( - direction.x, direction.y ) / abs( direction.z ); } else if ( face == 3.0 ) { uv = vec2( - direction.z, direction.y ) / abs( direction.x ); } else if ( face == 4.0 ) { uv = vec2( - direction.x, direction.z ) / abs( direction.y ); } else { uv = vec2( direction.x, direction.y ) / abs( direction.z ); } return 0.5 * ( uv + 1.0 ); } vec3 bilinearCubeUV( sampler2D envMap, vec3 direction, float mipInt ) { float face = getFace( direction ); float filterInt = max( cubeUV_minMipLevel - mipInt, 0.0 ); mipInt = max( mipInt, cubeUV_minMipLevel ); float faceSize = exp2( mipInt ); highp vec2 uv = getUV( direction, face ) * ( faceSize - 2.0 ) + 1.0; if ( face > 2.0 ) { uv.y += faceSize; face -= 3.0; } uv.x += face * faceSize; uv.x += filterInt * 3.0 * cubeUV_minTileSize; uv.y += 4.0 * ( exp2( CUBEUV_MAX_MIP ) - faceSize ); uv.x *= CUBEUV_TEXEL_WIDTH; uv.y *= CUBEUV_TEXEL_HEIGHT; #ifdef texture2DGradEXT return texture2DGradEXT( envMap, uv, vec2( 0.0 ), vec2( 0.0 ) ).rgb; #else return texture2D( envMap, uv ).rgb; #endif } #define cubeUV_r0 1.0 #define cubeUV_m0 - 2.0 #define cubeUV_r1 0.8 #define cubeUV_m1 - 1.0 #define cubeUV_r4 0.4 #define cubeUV_m4 2.0 #define cubeUV_r5 0.305 #define cubeUV_m5 3.0 #define cubeUV_r6 0.21 #define cubeUV_m6 4.0 float roughnessToMip( float roughness ) { float mip = 0.0; if ( roughness >= cubeUV_r1 ) { mip = ( cubeUV_r0 - roughness ) * ( cubeUV_m1 - cubeUV_m0 ) / ( cubeUV_r0 - cubeUV_r1 ) + cubeUV_m0; } else if ( roughness >= cubeUV_r4 ) { mip = ( cubeUV_r1 - roughness ) * ( cubeUV_m4 - cubeUV_m1 ) / ( cubeUV_r1 - cubeUV_r4 ) + cubeUV_m1; } else if ( roughness >= cubeUV_r5 ) { mip = ( cubeUV_r4 - roughness ) * ( cubeUV_m5 - cubeUV_m4 ) / ( cubeUV_r4 - cubeUV_r5 ) + cubeUV_m4; } else if ( roughness >= cubeUV_r6 ) { mip = ( cubeUV_r5 - roughness ) * ( cubeUV_m6 - cubeUV_m5 ) / ( cubeUV_r5 - cubeUV_r6 ) + cubeUV_m5; } else { mip = - 2.0 * log2( 1.16 * roughness ); } return mip; } vec4 textureCubeUV( sampler2D envMap, vec3 sampleDir, float roughness ) { float mip = clamp( roughnessToMip( roughness ), cubeUV_m0, CUBEUV_MAX_MIP ); float mipF = fract( mip ); float mipInt = floor( mip ); vec3 color0 = bilinearCubeUV( envMap, sampleDir, mipInt ); if ( mipF == 0.0 ) { return vec4( color0, 1.0 ); } else { vec3 color1 = bilinearCubeUV( envMap, sampleDir, mipInt + 1.0 ); return vec4( mix( color0, color1, mipF ), 1.0 ); } } #endif`,qI=`vec3 transformedNormal = objectNormal; #ifdef USE_TANGENT vec3 transformedTangent = objectTangent; #endif #ifdef USE_BATCHING mat3 bm = mat3( batchingMatrix ); transformedNormal /= vec3( dot( bm[ 0 ], bm[ 0 ] ), dot( bm[ 1 ], bm[ 1 ] ), dot( bm[ 2 ], bm[ 2 ] ) ); transformedNormal = bm * transformedNormal; #ifdef USE_TANGENT transformedTangent = bm * transformedTangent; #endif #endif #ifdef USE_INSTANCING mat3 im = mat3( instanceMatrix ); transformedNormal /= vec3( dot( im[ 0 ], im[ 0 ] ), dot( im[ 1 ], im[ 1 ] ), dot( im[ 2 ], im[ 2 ] ) ); transformedNormal = im * transformedNormal; #ifdef USE_TANGENT transformedTangent = im * transformedTangent; #endif #endif transformedNormal = normalMatrix * transformedNormal; #ifdef FLIP_SIDED transformedNormal = - transformedNormal; #endif #ifdef USE_TANGENT transformedTangent = ( modelViewMatrix * vec4( transformedTangent, 0.0 ) ).xyz; #ifdef FLIP_SIDED transformedTangent = - transformedTangent; #endif #endif`,ZI=`#ifdef USE_DISPLACEMENTMAP uniform sampler2D displacementMap; uniform float displacementScale; uniform float displacementBias; #endif`,YI=`#ifdef USE_DISPLACEMENTMAP transformed += normalize( objectNormal ) * ( texture2D( displacementMap, vDisplacementMapUv ).x * displacementScale + displacementBias ); #endif`,$I=`#ifdef USE_EMISSIVEMAP vec4 emissiveColor = texture2D( emissiveMap, vEmissiveMapUv ); #ifdef DECODE_VIDEO_TEXTURE_EMISSIVE emissiveColor = sRGBTransferEOTF( emissiveColor ); #endif totalEmissiveRadiance *= emissiveColor.rgb; #endif`,KI=`#ifdef USE_EMISSIVEMAP uniform sampler2D emissiveMap; #endif`,JI="gl_FragColor = linearToOutputTexel( gl_FragColor );",QI=`vec4 LinearTransferOETF( in vec4 value ) { return value; } vec4 sRGBTransferEOTF( in vec4 value ) { 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.a ); } vec4 sRGBTransferOETF( in vec4 value ) { return vec4( mix( pow( value.rgb, vec3( 0.41666 ) ) * 1.055 - vec3( 0.055 ), value.rgb * 12.92, vec3( lessThanEqual( value.rgb, vec3( 0.0031308 ) ) ) ), value.a ); }`,eL=`#ifdef USE_ENVMAP #ifdef ENV_WORLDPOS vec3 cameraToFrag; if ( isOrthographic ) { cameraToFrag = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) ); } else { cameraToFrag = normalize( vWorldPosition - cameraPosition ); } vec3 worldNormal = inverseTransformDirection( normal, viewMatrix ); #ifdef ENVMAP_MODE_REFLECTION vec3 reflectVec = reflect( cameraToFrag, worldNormal ); #else vec3 reflectVec = refract( cameraToFrag, worldNormal, refractionRatio ); #endif #else vec3 reflectVec = vReflect; #endif #ifdef ENVMAP_TYPE_CUBE vec4 envColor = textureCube( envMap, envMapRotation * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) ); #else vec4 envColor = vec4( 0.0 ); #endif #ifdef ENVMAP_BLENDING_MULTIPLY outgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity ); #elif defined( ENVMAP_BLENDING_MIX ) outgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity ); #elif defined( ENVMAP_BLENDING_ADD ) outgoingLight += envColor.xyz * specularStrength * reflectivity; #endif #endif`,tL=`#ifdef USE_ENVMAP uniform float envMapIntensity; uniform float flipEnvMap; uniform mat3 envMapRotation; #ifdef ENVMAP_TYPE_CUBE uniform samplerCube envMap; #else uniform sampler2D envMap; #endif #endif`,iL=`#ifdef USE_ENVMAP uniform float reflectivity; #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT ) #define ENV_WORLDPOS #endif #ifdef ENV_WORLDPOS varying vec3 vWorldPosition; uniform float refractionRatio; #else varying vec3 vReflect; #endif #endif`,nL=`#ifdef USE_ENVMAP #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT ) #define ENV_WORLDPOS #endif #ifdef ENV_WORLDPOS varying vec3 vWorldPosition; #else varying vec3 vReflect; uniform float refractionRatio; #endif #endif`,sL=`#ifdef USE_ENVMAP #ifdef ENV_WORLDPOS vWorldPosition = worldPosition.xyz; #else vec3 cameraToVertex; if ( isOrthographic ) { cameraToVertex = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) ); } else { cameraToVertex = normalize( worldPosition.xyz - cameraPosition ); } vec3 worldNormal = inverseTransformDirection( transformedNormal, viewMatrix ); #ifdef ENVMAP_MODE_REFLECTION vReflect = reflect( cameraToVertex, worldNormal ); #else vReflect = refract( cameraToVertex, worldNormal, refractionRatio ); #endif #endif #endif`,rL=`#ifdef USE_FOG vFogDepth = - mvPosition.z; #endif`,aL=`#ifdef USE_FOG varying float vFogDepth; #endif`,oL=`#ifdef USE_FOG #ifdef FOG_EXP2 float fogFactor = 1.0 - exp( - fogDensity * fogDensity * vFogDepth * vFogDepth ); #else float fogFactor = smoothstep( fogNear, fogFar, vFogDepth ); #endif gl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor ); #endif`,lL=`#ifdef USE_FOG uniform vec3 fogColor; varying float vFogDepth; #ifdef FOG_EXP2 uniform float fogDensity; #else uniform float fogNear; uniform float fogFar; #endif #endif`,cL=`#ifdef USE_GRADIENTMAP uniform sampler2D gradientMap; #endif vec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) { float dotNL = dot( normal, lightDirection ); vec2 coord = vec2( dotNL * 0.5 + 0.5, 0.0 ); #ifdef USE_GRADIENTMAP return vec3( texture2D( gradientMap, coord ).r ); #else vec2 fw = fwidth( coord ) * 0.5; return mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( 0.7 - fw.x, 0.7 + fw.x, coord.x ) ); #endif }`,hL=`#ifdef USE_LIGHTMAP uniform sampler2D lightMap; uniform float lightMapIntensity; #endif`,dL=`LambertMaterial material; material.diffuseColor = diffuseColor.rgb; material.specularStrength = specularStrength;`,uL=`varying vec3 vViewPosition; struct LambertMaterial { vec3 diffuseColor; float specularStrength; }; void RE_Direct_Lambert( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in LambertMaterial material, inout ReflectedLight reflectedLight ) { float dotNL = saturate( dot( geometryNormal, directLight.direction ) ); vec3 irradiance = dotNL * directLight.color; reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); } void RE_IndirectDiffuse_Lambert( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in LambertMaterial material, inout ReflectedLight reflectedLight ) { reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); } #define RE_Direct RE_Direct_Lambert #define RE_IndirectDiffuse RE_IndirectDiffuse_Lambert`,pL=`uniform bool receiveShadow; uniform vec3 ambientLightColor; #if defined( USE_LIGHT_PROBES ) uniform vec3 lightProbe[ 9 ]; #endif vec3 shGetIrradianceAt( in vec3 normal, in vec3 shCoefficients[ 9 ] ) { float x = normal.x, y = normal.y, z = normal.z; vec3 result = shCoefficients[ 0 ] * 0.886227; result += shCoefficients[ 1 ] * 2.0 * 0.511664 * y; result += shCoefficients[ 2 ] * 2.0 * 0.511664 * z; result += shCoefficients[ 3 ] * 2.0 * 0.511664 * x; result += shCoefficients[ 4 ] * 2.0 * 0.429043 * x * y; result += shCoefficients[ 5 ] * 2.0 * 0.429043 * y * z; result += shCoefficients[ 6 ] * ( 0.743125 * z * z - 0.247708 ); result += shCoefficients[ 7 ] * 2.0 * 0.429043 * x * z; result += shCoefficients[ 8 ] * 0.429043 * ( x * x - y * y ); return result; } vec3 getLightProbeIrradiance( const in vec3 lightProbe[ 9 ], const in vec3 normal ) { vec3 worldNormal = inverseTransformDirection( normal, viewMatrix ); vec3 irradiance = shGetIrradianceAt( worldNormal, lightProbe ); return irradiance; } vec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) { vec3 irradiance = ambientLightColor; return irradiance; } float getDistanceAttenuation( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) { float distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 ); if ( cutoffDistance > 0.0 ) { distanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) ); } return distanceFalloff; } float getSpotAttenuation( const in float coneCosine, const in float penumbraCosine, const in float angleCosine ) { return smoothstep( coneCosine, penumbraCosine, angleCosine ); } #if NUM_DIR_LIGHTS > 0 struct DirectionalLight { vec3 direction; vec3 color; }; uniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ]; void getDirectionalLightInfo( const in DirectionalLight directionalLight, out IncidentLight light ) { light.color = directionalLight.color; light.direction = directionalLight.direction; light.visible = true; } #endif #if NUM_POINT_LIGHTS > 0 struct PointLight { vec3 position; vec3 color; float distance; float decay; }; uniform PointLight pointLights[ NUM_POINT_LIGHTS ]; void getPointLightInfo( const in PointLight pointLight, const in vec3 geometryPosition, out IncidentLight light ) { vec3 lVector = pointLight.position - geometryPosition; light.direction = normalize( lVector ); float lightDistance = length( lVector ); light.color = pointLight.color; light.color *= getDistanceAttenuation( lightDistance, pointLight.distance, pointLight.decay ); light.visible = ( light.color != vec3( 0.0 ) ); } #endif #if NUM_SPOT_LIGHTS > 0 struct SpotLight { vec3 position; vec3 direction; vec3 color; float distance; float decay; float coneCos; float penumbraCos; }; uniform SpotLight spotLights[ NUM_SPOT_LIGHTS ]; void getSpotLightInfo( const in SpotLight spotLight, const in vec3 geometryPosition, out IncidentLight light ) { vec3 lVector = spotLight.position - geometryPosition; light.direction = normalize( lVector ); float angleCos = dot( light.direction, spotLight.direction ); float spotAttenuation = getSpotAttenuation( spotLight.coneCos, spotLight.penumbraCos, angleCos ); if ( spotAttenuation > 0.0 ) { float lightDistance = length( lVector ); light.color = spotLight.color * spotAttenuation; light.color *= getDistanceAttenuation( lightDistance, spotLight.distance, spotLight.decay ); light.visible = ( light.color != vec3( 0.0 ) ); } else { light.color = vec3( 0.0 ); light.visible = false; } } #endif #if NUM_RECT_AREA_LIGHTS > 0 struct RectAreaLight { vec3 color; vec3 position; vec3 halfWidth; vec3 halfHeight; }; uniform sampler2D ltc_1; uniform sampler2D ltc_2; uniform RectAreaLight rectAreaLights[ NUM_RECT_AREA_LIGHTS ]; #endif #if NUM_HEMI_LIGHTS > 0 struct HemisphereLight { vec3 direction; vec3 skyColor; vec3 groundColor; }; uniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ]; vec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in vec3 normal ) { float dotNL = dot( normal, hemiLight.direction ); float hemiDiffuseWeight = 0.5 * dotNL + 0.5; vec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight ); return irradiance; } #endif`,fL=`#ifdef USE_ENVMAP vec3 getIBLIrradiance( const in vec3 normal ) { #ifdef ENVMAP_TYPE_CUBE_UV vec3 worldNormal = inverseTransformDirection( normal, viewMatrix ); vec4 envMapColor = textureCubeUV( envMap, envMapRotation * worldNormal, 1.0 ); return PI * envMapColor.rgb * envMapIntensity; #else return vec3( 0.0 ); #endif } vec3 getIBLRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness ) { #ifdef ENVMAP_TYPE_CUBE_UV vec3 reflectVec = reflect( - viewDir, normal ); reflectVec = normalize( mix( reflectVec, normal, pow4( roughness ) ) ); reflectVec = inverseTransformDirection( reflectVec, viewMatrix ); vec4 envMapColor = textureCubeUV( envMap, envMapRotation * reflectVec, roughness ); return envMapColor.rgb * envMapIntensity; #else return vec3( 0.0 ); #endif } #ifdef USE_ANISOTROPY vec3 getIBLAnisotropyRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness, const in vec3 bitangent, const in float anisotropy ) { #ifdef ENVMAP_TYPE_CUBE_UV vec3 bentNormal = cross( bitangent, viewDir ); bentNormal = normalize( cross( bentNormal, bitangent ) ); bentNormal = normalize( mix( bentNormal, normal, pow2( pow2( 1.0 - anisotropy * ( 1.0 - roughness ) ) ) ) ); return getIBLRadiance( viewDir, bentNormal, roughness ); #else return vec3( 0.0 ); #endif } #endif #endif`,mL=`ToonMaterial material; material.diffuseColor = diffuseColor.rgb;`,gL=`varying vec3 vViewPosition; struct ToonMaterial { vec3 diffuseColor; }; void RE_Direct_Toon( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in ToonMaterial material, inout ReflectedLight reflectedLight ) { vec3 irradiance = getGradientIrradiance( geometryNormal, directLight.direction ) * directLight.color; reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); } void RE_IndirectDiffuse_Toon( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in ToonMaterial material, inout ReflectedLight reflectedLight ) { reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); } #define RE_Direct RE_Direct_Toon #define RE_IndirectDiffuse RE_IndirectDiffuse_Toon`,vL=`BlinnPhongMaterial material; material.diffuseColor = diffuseColor.rgb; material.specularColor = specular; material.specularShininess = shininess; material.specularStrength = specularStrength;`,yL=`varying vec3 vViewPosition; struct BlinnPhongMaterial { vec3 diffuseColor; vec3 specularColor; float specularShininess; float specularStrength; }; void RE_Direct_BlinnPhong( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) { float dotNL = saturate( dot( geometryNormal, directLight.direction ) ); vec3 irradiance = dotNL * directLight.color; reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); reflectedLight.directSpecular += irradiance * BRDF_BlinnPhong( directLight.direction, geometryViewDir, geometryNormal, material.specularColor, material.specularShininess ) * material.specularStrength; } void RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) { reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); } #define RE_Direct RE_Direct_BlinnPhong #define RE_IndirectDiffuse RE_IndirectDiffuse_BlinnPhong`,xL=`PhysicalMaterial material; material.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor ); vec3 dxy = max( abs( dFdx( nonPerturbedNormal ) ), abs( dFdy( nonPerturbedNormal ) ) ); float geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z ); material.roughness = max( roughnessFactor, 0.0525 );material.roughness += geometryRoughness; material.roughness = min( material.roughness, 1.0 ); #ifdef IOR material.ior = ior; #ifdef USE_SPECULAR float specularIntensityFactor = specularIntensity; vec3 specularColorFactor = specularColor; #ifdef USE_SPECULAR_COLORMAP specularColorFactor *= texture2D( specularColorMap, vSpecularColorMapUv ).rgb; #endif #ifdef USE_SPECULAR_INTENSITYMAP specularIntensityFactor *= texture2D( specularIntensityMap, vSpecularIntensityMapUv ).a; #endif material.specularF90 = mix( specularIntensityFactor, 1.0, metalnessFactor ); #else float specularIntensityFactor = 1.0; vec3 specularColorFactor = vec3( 1.0 ); material.specularF90 = 1.0; #endif material.specularColor = mix( min( pow2( ( material.ior - 1.0 ) / ( material.ior + 1.0 ) ) * specularColorFactor, vec3( 1.0 ) ) * specularIntensityFactor, diffuseColor.rgb, metalnessFactor ); #else material.specularColor = mix( vec3( 0.04 ), diffuseColor.rgb, metalnessFactor ); material.specularF90 = 1.0; #endif #ifdef USE_CLEARCOAT material.clearcoat = clearcoat; material.clearcoatRoughness = clearcoatRoughness; material.clearcoatF0 = vec3( 0.04 ); material.clearcoatF90 = 1.0; #ifdef USE_CLEARCOATMAP material.clearcoat *= texture2D( clearcoatMap, vClearcoatMapUv ).x; #endif #ifdef USE_CLEARCOAT_ROUGHNESSMAP material.clearcoatRoughness *= texture2D( clearcoatRoughnessMap, vClearcoatRoughnessMapUv ).y; #endif material.clearcoat = saturate( material.clearcoat ); material.clearcoatRoughness = max( material.clearcoatRoughness, 0.0525 ); material.clearcoatRoughness += geometryRoughness; material.clearcoatRoughness = min( material.clearcoatRoughness, 1.0 ); #endif #ifdef USE_DISPERSION material.dispersion = dispersion; #endif #ifdef USE_IRIDESCENCE material.iridescence = iridescence; material.iridescenceIOR = iridescenceIOR; #ifdef USE_IRIDESCENCEMAP material.iridescence *= texture2D( iridescenceMap, vIridescenceMapUv ).r; #endif #ifdef USE_IRIDESCENCE_THICKNESSMAP material.iridescenceThickness = (iridescenceThicknessMaximum - iridescenceThicknessMinimum) * texture2D( iridescenceThicknessMap, vIridescenceThicknessMapUv ).g + iridescenceThicknessMinimum; #else material.iridescenceThickness = iridescenceThicknessMaximum; #endif #endif #ifdef USE_SHEEN material.sheenColor = sheenColor; #ifdef USE_SHEEN_COLORMAP material.sheenColor *= texture2D( sheenColorMap, vSheenColorMapUv ).rgb; #endif material.sheenRoughness = clamp( sheenRoughness, 0.07, 1.0 ); #ifdef USE_SHEEN_ROUGHNESSMAP material.sheenRoughness *= texture2D( sheenRoughnessMap, vSheenRoughnessMapUv ).a; #endif #endif #ifdef USE_ANISOTROPY #ifdef USE_ANISOTROPYMAP mat2 anisotropyMat = mat2( anisotropyVector.x, anisotropyVector.y, - anisotropyVector.y, anisotropyVector.x ); vec3 anisotropyPolar = texture2D( anisotropyMap, vAnisotropyMapUv ).rgb; vec2 anisotropyV = anisotropyMat * normalize( 2.0 * anisotropyPolar.rg - vec2( 1.0 ) ) * anisotropyPolar.b; #else vec2 anisotropyV = anisotropyVector; #endif material.anisotropy = length( anisotropyV ); if( material.anisotropy == 0.0 ) { anisotropyV = vec2( 1.0, 0.0 ); } else { anisotropyV /= material.anisotropy; material.anisotropy = saturate( material.anisotropy ); } material.alphaT = mix( pow2( material.roughness ), 1.0, pow2( material.anisotropy ) ); material.anisotropyT = tbn[ 0 ] * anisotropyV.x + tbn[ 1 ] * anisotropyV.y; material.anisotropyB = tbn[ 1 ] * anisotropyV.x - tbn[ 0 ] * anisotropyV.y; #endif`,_L=`uniform sampler2D dfgLUT; struct PhysicalMaterial { vec3 diffuseColor; float roughness; vec3 specularColor; float specularF90; float dispersion; #ifdef USE_CLEARCOAT float clearcoat; float clearcoatRoughness; vec3 clearcoatF0; float clearcoatF90; #endif #ifdef USE_IRIDESCENCE float iridescence; float iridescenceIOR; float iridescenceThickness; vec3 iridescenceFresnel; vec3 iridescenceF0; #endif #ifdef USE_SHEEN vec3 sheenColor; float sheenRoughness; #endif #ifdef IOR float ior; #endif #ifdef USE_TRANSMISSION float transmission; float transmissionAlpha; float thickness; float attenuationDistance; vec3 attenuationColor; #endif #ifdef USE_ANISOTROPY float anisotropy; float alphaT; vec3 anisotropyT; vec3 anisotropyB; #endif }; vec3 clearcoatSpecularDirect = vec3( 0.0 ); vec3 clearcoatSpecularIndirect = vec3( 0.0 ); vec3 sheenSpecularDirect = vec3( 0.0 ); vec3 sheenSpecularIndirect = vec3(0.0 ); vec3 Schlick_to_F0( const in vec3 f, const in float f90, const in float dotVH ) { float x = clamp( 1.0 - dotVH, 0.0, 1.0 ); float x2 = x * x; float x5 = clamp( x * x2 * x2, 0.0, 0.9999 ); return ( f - vec3( f90 ) * x5 ) / ( 1.0 - x5 ); } float V_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) { float a2 = pow2( alpha ); float gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) ); float gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) ); return 0.5 / max( gv + gl, EPSILON ); } float D_GGX( const in float alpha, const in float dotNH ) { float a2 = pow2( alpha ); float denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0; return RECIPROCAL_PI * a2 / pow2( denom ); } #ifdef USE_ANISOTROPY float V_GGX_SmithCorrelated_Anisotropic( const in float alphaT, const in float alphaB, const in float dotTV, const in float dotBV, const in float dotTL, const in float dotBL, const in float dotNV, const in float dotNL ) { float gv = dotNL * length( vec3( alphaT * dotTV, alphaB * dotBV, dotNV ) ); float gl = dotNV * length( vec3( alphaT * dotTL, alphaB * dotBL, dotNL ) ); float v = 0.5 / ( gv + gl ); return saturate(v); } float D_GGX_Anisotropic( const in float alphaT, const in float alphaB, const in float dotNH, const in float dotTH, const in float dotBH ) { float a2 = alphaT * alphaB; highp vec3 v = vec3( alphaB * dotTH, alphaT * dotBH, a2 * dotNH ); highp float v2 = dot( v, v ); float w2 = a2 / v2; return RECIPROCAL_PI * a2 * pow2 ( w2 ); } #endif #ifdef USE_CLEARCOAT vec3 BRDF_GGX_Clearcoat( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material) { vec3 f0 = material.clearcoatF0; float f90 = material.clearcoatF90; float roughness = material.clearcoatRoughness; float alpha = pow2( roughness ); vec3 halfDir = normalize( lightDir + viewDir ); float dotNL = saturate( dot( normal, lightDir ) ); float dotNV = saturate( dot( normal, viewDir ) ); float dotNH = saturate( dot( normal, halfDir ) ); float dotVH = saturate( dot( viewDir, halfDir ) ); vec3 F = F_Schlick( f0, f90, dotVH ); float V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV ); float D = D_GGX( alpha, dotNH ); return F * ( V * D ); } #endif vec3 BRDF_GGX( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material ) { vec3 f0 = material.specularColor; float f90 = material.specularF90; float roughness = material.roughness; float alpha = pow2( roughness ); vec3 halfDir = normalize( lightDir + viewDir ); float dotNL = saturate( dot( normal, lightDir ) ); float dotNV = saturate( dot( normal, viewDir ) ); float dotNH = saturate( dot( normal, halfDir ) ); float dotVH = saturate( dot( viewDir, halfDir ) ); vec3 F = F_Schlick( f0, f90, dotVH ); #ifdef USE_IRIDESCENCE F = mix( F, material.iridescenceFresnel, material.iridescence ); #endif #ifdef USE_ANISOTROPY float dotTL = dot( material.anisotropyT, lightDir ); float dotTV = dot( material.anisotropyT, viewDir ); float dotTH = dot( material.anisotropyT, halfDir ); float dotBL = dot( material.anisotropyB, lightDir ); float dotBV = dot( material.anisotropyB, viewDir ); float dotBH = dot( material.anisotropyB, halfDir ); float V = V_GGX_SmithCorrelated_Anisotropic( material.alphaT, alpha, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL ); float D = D_GGX_Anisotropic( material.alphaT, alpha, dotNH, dotTH, dotBH ); #else float V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV ); float D = D_GGX( alpha, dotNH ); #endif return F * ( V * D ); } vec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) { const float LUT_SIZE = 64.0; const float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE; const float LUT_BIAS = 0.5 / LUT_SIZE; float dotNV = saturate( dot( N, V ) ); vec2 uv = vec2( roughness, sqrt( 1.0 - dotNV ) ); uv = uv * LUT_SCALE + LUT_BIAS; return uv; } float LTC_ClippedSphereFormFactor( const in vec3 f ) { float l = length( f ); return max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 ); } vec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) { float x = dot( v1, v2 ); float y = abs( x ); float a = 0.8543985 + ( 0.4965155 + 0.0145206 * y ) * y; float b = 3.4175940 + ( 4.1616724 + y ) * y; float v = a / b; float theta_sintheta = ( x > 0.0 ) ? v : 0.5 * inversesqrt( max( 1.0 - x * x, 1e-7 ) ) - v; return cross( v1, v2 ) * theta_sintheta; } vec3 LTC_Evaluate( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in vec3 rectCoords[ 4 ] ) { vec3 v1 = rectCoords[ 1 ] - rectCoords[ 0 ]; vec3 v2 = rectCoords[ 3 ] - rectCoords[ 0 ]; vec3 lightNormal = cross( v1, v2 ); if( dot( lightNormal, P - rectCoords[ 0 ] ) < 0.0 ) return vec3( 0.0 ); vec3 T1, T2; T1 = normalize( V - N * dot( V, N ) ); T2 = - cross( N, T1 ); mat3 mat = mInv * transpose( mat3( T1, T2, N ) ); vec3 coords[ 4 ]; coords[ 0 ] = mat * ( rectCoords[ 0 ] - P ); coords[ 1 ] = mat * ( rectCoords[ 1 ] - P ); coords[ 2 ] = mat * ( rectCoords[ 2 ] - P ); coords[ 3 ] = mat * ( rectCoords[ 3 ] - P ); coords[ 0 ] = normalize( coords[ 0 ] ); coords[ 1 ] = normalize( coords[ 1 ] ); coords[ 2 ] = normalize( coords[ 2 ] ); coords[ 3 ] = normalize( coords[ 3 ] ); vec3 vectorFormFactor = vec3( 0.0 ); vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] ); vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] ); vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] ); vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] ); float result = LTC_ClippedSphereFormFactor( vectorFormFactor ); return vec3( result ); } #if defined( USE_SHEEN ) float D_Charlie( float roughness, float dotNH ) { float alpha = pow2( roughness ); float invAlpha = 1.0 / alpha; float cos2h = dotNH * dotNH; float sin2h = max( 1.0 - cos2h, 0.0078125 ); return ( 2.0 + invAlpha ) * pow( sin2h, invAlpha * 0.5 ) / ( 2.0 * PI ); } float V_Neubelt( float dotNV, float dotNL ) { return saturate( 1.0 / ( 4.0 * ( dotNL + dotNV - dotNL * dotNV ) ) ); } vec3 BRDF_Sheen( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, vec3 sheenColor, const in float sheenRoughness ) { vec3 halfDir = normalize( lightDir + viewDir ); float dotNL = saturate( dot( normal, lightDir ) ); float dotNV = saturate( dot( normal, viewDir ) ); float dotNH = saturate( dot( normal, halfDir ) ); float D = D_Charlie( sheenRoughness, dotNH ); float V = V_Neubelt( dotNV, dotNL ); return sheenColor * ( D * V ); } #endif float IBLSheenBRDF( const in vec3 normal, const in vec3 viewDir, const in float roughness ) { float dotNV = saturate( dot( normal, viewDir ) ); float r2 = roughness * roughness; float a = roughness < 0.25 ? -339.2 * r2 + 161.4 * roughness - 25.9 : -8.48 * r2 + 14.3 * roughness - 9.95; float b = roughness < 0.25 ? 44.0 * r2 - 23.7 * roughness + 3.26 : 1.97 * r2 - 3.27 * roughness + 0.72; float DG = exp( a * dotNV + b ) + ( roughness < 0.25 ? 0.0 : 0.1 * ( roughness - 0.25 ) ); return saturate( DG * RECIPROCAL_PI ); } vec2 DFGApprox( const in vec3 normal, const in vec3 viewDir, const in float roughness ) { float dotNV = saturate( dot( normal, viewDir ) ); vec2 uv = vec2( roughness, dotNV ); return texture2D( dfgLUT, uv ).rg; } vec3 EnvironmentBRDF( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness ) { vec2 fab = DFGApprox( normal, viewDir, roughness ); return specularColor * fab.x + specularF90 * fab.y; } #ifdef USE_IRIDESCENCE void computeMultiscatteringIridescence( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float iridescence, const in vec3 iridescenceF0, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) { #else void computeMultiscattering( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) { #endif vec2 fab = DFGApprox( normal, viewDir, roughness ); #ifdef USE_IRIDESCENCE vec3 Fr = mix( specularColor, iridescenceF0, iridescence ); #else vec3 Fr = specularColor; #endif vec3 FssEss = Fr * fab.x + specularF90 * fab.y; float Ess = fab.x + fab.y; float Ems = 1.0 - Ess; vec3 Favg = Fr + ( 1.0 - Fr ) * 0.047619; vec3 Fms = FssEss * Favg / ( 1.0 - Ems * Favg ); singleScatter += FssEss; multiScatter += Fms * Ems; } vec3 BRDF_GGX_Multiscatter( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material ) { vec3 singleScatter = BRDF_GGX( lightDir, viewDir, normal, material ); float dotNL = saturate( dot( normal, lightDir ) ); float dotNV = saturate( dot( normal, viewDir ) ); vec2 dfgV = DFGApprox( vec3(0.0, 0.0, 1.0), vec3(sqrt(1.0 - dotNV * dotNV), 0.0, dotNV), material.roughness ); vec2 dfgL = DFGApprox( vec3(0.0, 0.0, 1.0), vec3(sqrt(1.0 - dotNL * dotNL), 0.0, dotNL), material.roughness ); vec3 FssEss_V = material.specularColor * dfgV.x + material.specularF90 * dfgV.y; vec3 FssEss_L = material.specularColor * dfgL.x + material.specularF90 * dfgL.y; float Ess_V = dfgV.x + dfgV.y; float Ess_L = dfgL.x + dfgL.y; float Ems_V = 1.0 - Ess_V; float Ems_L = 1.0 - Ess_L; vec3 Favg = material.specularColor + ( 1.0 - material.specularColor ) * 0.047619; vec3 Fms = FssEss_V * FssEss_L * Favg / ( 1.0 - Ems_V * Ems_L * Favg * Favg + EPSILON ); float compensationFactor = Ems_V * Ems_L; vec3 multiScatter = Fms * compensationFactor; return singleScatter + multiScatter; } #if NUM_RECT_AREA_LIGHTS > 0 void RE_Direct_RectArea_Physical( const in RectAreaLight rectAreaLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) { vec3 normal = geometryNormal; vec3 viewDir = geometryViewDir; vec3 position = geometryPosition; vec3 lightPos = rectAreaLight.position; vec3 halfWidth = rectAreaLight.halfWidth; vec3 halfHeight = rectAreaLight.halfHeight; vec3 lightColor = rectAreaLight.color; float roughness = material.roughness; vec3 rectCoords[ 4 ]; rectCoords[ 0 ] = lightPos + halfWidth - halfHeight; rectCoords[ 1 ] = lightPos - halfWidth - halfHeight; rectCoords[ 2 ] = lightPos - halfWidth + halfHeight; rectCoords[ 3 ] = lightPos + halfWidth + halfHeight; vec2 uv = LTC_Uv( normal, viewDir, roughness ); vec4 t1 = texture2D( ltc_1, uv ); vec4 t2 = texture2D( ltc_2, uv ); mat3 mInv = mat3( vec3( t1.x, 0, t1.y ), vec3( 0, 1, 0 ), vec3( t1.z, 0, t1.w ) ); vec3 fresnel = ( material.specularColor * t2.x + ( vec3( 1.0 ) - material.specularColor ) * t2.y ); reflectedLight.directSpecular += lightColor * fresnel * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords ); reflectedLight.directDiffuse += lightColor * material.diffuseColor * LTC_Evaluate( normal, viewDir, position, mat3( 1.0 ), rectCoords ); } #endif void RE_Direct_Physical( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) { float dotNL = saturate( dot( geometryNormal, directLight.direction ) ); vec3 irradiance = dotNL * directLight.color; #ifdef USE_CLEARCOAT float dotNLcc = saturate( dot( geometryClearcoatNormal, directLight.direction ) ); vec3 ccIrradiance = dotNLcc * directLight.color; clearcoatSpecularDirect += ccIrradiance * BRDF_GGX_Clearcoat( directLight.direction, geometryViewDir, geometryClearcoatNormal, material ); #endif #ifdef USE_SHEEN sheenSpecularDirect += irradiance * BRDF_Sheen( directLight.direction, geometryViewDir, geometryNormal, material.sheenColor, material.sheenRoughness ); #endif reflectedLight.directSpecular += irradiance * BRDF_GGX_Multiscatter( directLight.direction, geometryViewDir, geometryNormal, material ); reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); } void RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) { reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); } void RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 irradiance, const in vec3 clearcoatRadiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight) { #ifdef USE_CLEARCOAT clearcoatSpecularIndirect += clearcoatRadiance * EnvironmentBRDF( geometryClearcoatNormal, geometryViewDir, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness ); #endif #ifdef USE_SHEEN sheenSpecularIndirect += irradiance * material.sheenColor * IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness ); #endif vec3 singleScattering = vec3( 0.0 ); vec3 multiScattering = vec3( 0.0 ); vec3 cosineWeightedIrradiance = irradiance * RECIPROCAL_PI; #ifdef USE_IRIDESCENCE computeMultiscatteringIridescence( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.iridescence, material.iridescenceFresnel, material.roughness, singleScattering, multiScattering ); #else computeMultiscattering( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.roughness, singleScattering, multiScattering ); #endif vec3 totalScattering = singleScattering + multiScattering; vec3 diffuse = material.diffuseColor * ( 1.0 - max( max( totalScattering.r, totalScattering.g ), totalScattering.b ) ); reflectedLight.indirectSpecular += radiance * singleScattering; reflectedLight.indirectSpecular += multiScattering * cosineWeightedIrradiance; reflectedLight.indirectDiffuse += diffuse * cosineWeightedIrradiance; } #define RE_Direct RE_Direct_Physical #define RE_Direct_RectArea RE_Direct_RectArea_Physical #define RE_IndirectDiffuse RE_IndirectDiffuse_Physical #define RE_IndirectSpecular RE_IndirectSpecular_Physical float computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) { return saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion ); }`,bL=` vec3 geometryPosition = - vViewPosition; vec3 geometryNormal = normal; vec3 geometryViewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition ); vec3 geometryClearcoatNormal = vec3( 0.0 ); #ifdef USE_CLEARCOAT geometryClearcoatNormal = clearcoatNormal; #endif #ifdef USE_IRIDESCENCE float dotNVi = saturate( dot( normal, geometryViewDir ) ); if ( material.iridescenceThickness == 0.0 ) { material.iridescence = 0.0; } else { material.iridescence = saturate( material.iridescence ); } if ( material.iridescence > 0.0 ) { material.iridescenceFresnel = evalIridescence( 1.0, material.iridescenceIOR, dotNVi, material.iridescenceThickness, material.specularColor ); material.iridescenceF0 = Schlick_to_F0( material.iridescenceFresnel, 1.0, dotNVi ); } #endif IncidentLight directLight; #if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct ) PointLight pointLight; #if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0 PointLightShadow pointLightShadow; #endif #pragma unroll_loop_start for ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) { pointLight = pointLights[ i ]; getPointLightInfo( pointLight, geometryPosition, directLight ); #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS ) pointLightShadow = pointLightShadows[ i ]; directLight.color *= ( directLight.visible && receiveShadow ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowIntensity, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0; #endif RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); } #pragma unroll_loop_end #endif #if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct ) SpotLight spotLight; vec4 spotColor; vec3 spotLightCoord; bool inSpotLightMap; #if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0 SpotLightShadow spotLightShadow; #endif #pragma unroll_loop_start for ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) { spotLight = spotLights[ i ]; getSpotLightInfo( spotLight, geometryPosition, directLight ); #if ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS ) #define SPOT_LIGHT_MAP_INDEX UNROLLED_LOOP_INDEX #elif ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS ) #define SPOT_LIGHT_MAP_INDEX NUM_SPOT_LIGHT_MAPS #else #define SPOT_LIGHT_MAP_INDEX ( UNROLLED_LOOP_INDEX - NUM_SPOT_LIGHT_SHADOWS + NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS ) #endif #if ( SPOT_LIGHT_MAP_INDEX < NUM_SPOT_LIGHT_MAPS ) spotLightCoord = vSpotLightCoord[ i ].xyz / vSpotLightCoord[ i ].w; inSpotLightMap = all( lessThan( abs( spotLightCoord * 2. - 1. ), vec3( 1.0 ) ) ); spotColor = texture2D( spotLightMap[ SPOT_LIGHT_MAP_INDEX ], spotLightCoord.xy ); directLight.color = inSpotLightMap ? directLight.color * spotColor.rgb : directLight.color; #endif #undef SPOT_LIGHT_MAP_INDEX #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS ) spotLightShadow = spotLightShadows[ i ]; directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowIntensity, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotLightCoord[ i ] ) : 1.0; #endif RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); } #pragma unroll_loop_end #endif #if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct ) DirectionalLight directionalLight; #if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0 DirectionalLightShadow directionalLightShadow; #endif #pragma unroll_loop_start for ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) { directionalLight = directionalLights[ i ]; getDirectionalLightInfo( directionalLight, directLight ); #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS ) directionalLightShadow = directionalLightShadows[ i ]; directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowIntensity, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0; #endif RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); } #pragma unroll_loop_end #endif #if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea ) RectAreaLight rectAreaLight; #pragma unroll_loop_start for ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) { rectAreaLight = rectAreaLights[ i ]; RE_Direct_RectArea( rectAreaLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); } #pragma unroll_loop_end #endif #if defined( RE_IndirectDiffuse ) vec3 iblIrradiance = vec3( 0.0 ); vec3 irradiance = getAmbientLightIrradiance( ambientLightColor ); #if defined( USE_LIGHT_PROBES ) irradiance += getLightProbeIrradiance( lightProbe, geometryNormal ); #endif #if ( NUM_HEMI_LIGHTS > 0 ) #pragma unroll_loop_start for ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) { irradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometryNormal ); } #pragma unroll_loop_end #endif #endif #if defined( RE_IndirectSpecular ) vec3 radiance = vec3( 0.0 ); vec3 clearcoatRadiance = vec3( 0.0 ); #endif`,ML=`#if defined( RE_IndirectDiffuse ) #ifdef USE_LIGHTMAP vec4 lightMapTexel = texture2D( lightMap, vLightMapUv ); vec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity; irradiance += lightMapIrradiance; #endif #if defined( USE_ENVMAP ) && defined( STANDARD ) && defined( ENVMAP_TYPE_CUBE_UV ) iblIrradiance += getIBLIrradiance( geometryNormal ); #endif #endif #if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular ) #ifdef USE_ANISOTROPY radiance += getIBLAnisotropyRadiance( geometryViewDir, geometryNormal, material.roughness, material.anisotropyB, material.anisotropy ); #else radiance += getIBLRadiance( geometryViewDir, geometryNormal, material.roughness ); #endif #ifdef USE_CLEARCOAT clearcoatRadiance += getIBLRadiance( geometryViewDir, geometryClearcoatNormal, material.clearcoatRoughness ); #endif #endif`,SL=`#if defined( RE_IndirectDiffuse ) RE_IndirectDiffuse( irradiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); #endif #if defined( RE_IndirectSpecular ) RE_IndirectSpecular( radiance, iblIrradiance, clearcoatRadiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); #endif`,wL=`#if defined( USE_LOGARITHMIC_DEPTH_BUFFER ) gl_FragDepth = vIsPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5; #endif`,EL=`#if defined( USE_LOGARITHMIC_DEPTH_BUFFER ) uniform float logDepthBufFC; varying float vFragDepth; varying float vIsPerspective; #endif`,TL=`#ifdef USE_LOGARITHMIC_DEPTH_BUFFER varying float vFragDepth; varying float vIsPerspective; #endif`,CL=`#ifdef USE_LOGARITHMIC_DEPTH_BUFFER vFragDepth = 1.0 + gl_Position.w; vIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) ); #endif`,AL=`#ifdef USE_MAP vec4 sampledDiffuseColor = texture2D( map, vMapUv ); #ifdef DECODE_VIDEO_TEXTURE sampledDiffuseColor = sRGBTransferEOTF( sampledDiffuseColor ); #endif diffuseColor *= sampledDiffuseColor; #endif`,PL=`#ifdef USE_MAP uniform sampler2D map; #endif`,RL=`#if defined( USE_MAP ) || defined( USE_ALPHAMAP ) #if defined( USE_POINTS_UV ) vec2 uv = vUv; #else vec2 uv = ( uvTransform * vec3( gl_PointCoord.x, 1.0 - gl_PointCoord.y, 1 ) ).xy; #endif #endif #ifdef USE_MAP diffuseColor *= texture2D( map, uv ); #endif #ifdef USE_ALPHAMAP diffuseColor.a *= texture2D( alphaMap, uv ).g; #endif`,IL=`#if defined( USE_POINTS_UV ) varying vec2 vUv; #else #if defined( USE_MAP ) || defined( USE_ALPHAMAP ) uniform mat3 uvTransform; #endif #endif #ifdef USE_MAP uniform sampler2D map; #endif #ifdef USE_ALPHAMAP uniform sampler2D alphaMap; #endif`,LL=`float metalnessFactor = metalness; #ifdef USE_METALNESSMAP vec4 texelMetalness = texture2D( metalnessMap, vMetalnessMapUv ); metalnessFactor *= texelMetalness.b; #endif`,DL=`#ifdef USE_METALNESSMAP uniform sampler2D metalnessMap; #endif`,NL=`#ifdef USE_INSTANCING_MORPH float morphTargetInfluences[ MORPHTARGETS_COUNT ]; float morphTargetBaseInfluence = texelFetch( morphTexture, ivec2( 0, gl_InstanceID ), 0 ).r; for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) { morphTargetInfluences[i] = texelFetch( morphTexture, ivec2( i + 1, gl_InstanceID ), 0 ).r; } #endif`,kL=`#if defined( USE_MORPHCOLORS ) vColor *= morphTargetBaseInfluence; for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) { #if defined( USE_COLOR_ALPHA ) if ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ) * morphTargetInfluences[ i ]; #elif defined( USE_COLOR ) if ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ).rgb * morphTargetInfluences[ i ]; #endif } #endif`,OL=`#ifdef USE_MORPHNORMALS objectNormal *= morphTargetBaseInfluence; for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) { if ( morphTargetInfluences[ i ] != 0.0 ) objectNormal += getMorph( gl_VertexID, i, 1 ).xyz * morphTargetInfluences[ i ]; } #endif`,UL=`#ifdef USE_MORPHTARGETS #ifndef USE_INSTANCING_MORPH uniform float morphTargetBaseInfluence; uniform float morphTargetInfluences[ MORPHTARGETS_COUNT ]; #endif uniform sampler2DArray morphTargetsTexture; uniform ivec2 morphTargetsTextureSize; vec4 getMorph( const in int vertexIndex, const in int morphTargetIndex, const in int offset ) { int texelIndex = vertexIndex * MORPHTARGETS_TEXTURE_STRIDE + offset; int y = texelIndex / morphTargetsTextureSize.x; int x = texelIndex - y * morphTargetsTextureSize.x; ivec3 morphUV = ivec3( x, y, morphTargetIndex ); return texelFetch( morphTargetsTexture, morphUV, 0 ); } #endif`,BL=`#ifdef USE_MORPHTARGETS transformed *= morphTargetBaseInfluence; for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) { if ( morphTargetInfluences[ i ] != 0.0 ) transformed += getMorph( gl_VertexID, i, 0 ).xyz * morphTargetInfluences[ i ]; } #endif`,FL=`float faceDirection = gl_FrontFacing ? 1.0 : - 1.0; #ifdef FLAT_SHADED vec3 fdx = dFdx( vViewPosition ); vec3 fdy = dFdy( vViewPosition ); vec3 normal = normalize( cross( fdx, fdy ) ); #else vec3 normal = normalize( vNormal ); #ifdef DOUBLE_SIDED normal *= faceDirection; #endif #endif #if defined( USE_NORMALMAP_TANGENTSPACE ) || defined( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY ) #ifdef USE_TANGENT mat3 tbn = mat3( normalize( vTangent ), normalize( vBitangent ), normal ); #else mat3 tbn = getTangentFrame( - vViewPosition, normal, #if defined( USE_NORMALMAP ) vNormalMapUv #elif defined( USE_CLEARCOAT_NORMALMAP ) vClearcoatNormalMapUv #else vUv #endif ); #endif #if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED ) tbn[0] *= faceDirection; tbn[1] *= faceDirection; #endif #endif #ifdef USE_CLEARCOAT_NORMALMAP #ifdef USE_TANGENT mat3 tbn2 = mat3( normalize( vTangent ), normalize( vBitangent ), normal ); #else mat3 tbn2 = getTangentFrame( - vViewPosition, normal, vClearcoatNormalMapUv ); #endif #if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED ) tbn2[0] *= faceDirection; tbn2[1] *= faceDirection; #endif #endif vec3 nonPerturbedNormal = normal;`,zL=`#ifdef USE_NORMALMAP_OBJECTSPACE normal = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0; #ifdef FLIP_SIDED normal = - normal; #endif #ifdef DOUBLE_SIDED normal = normal * faceDirection; #endif normal = normalize( normalMatrix * normal ); #elif defined( USE_NORMALMAP_TANGENTSPACE ) vec3 mapN = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0; mapN.xy *= normalScale; normal = normalize( tbn * mapN ); #elif defined( USE_BUMPMAP ) normal = perturbNormalArb( - vViewPosition, normal, dHdxy_fwd(), faceDirection ); #endif`,HL=`#ifndef FLAT_SHADED varying vec3 vNormal; #ifdef USE_TANGENT varying vec3 vTangent; varying vec3 vBitangent; #endif #endif`,VL=`#ifndef FLAT_SHADED varying vec3 vNormal; #ifdef USE_TANGENT varying vec3 vTangent; varying vec3 vBitangent; #endif #endif`,GL=`#ifndef FLAT_SHADED vNormal = normalize( transformedNormal ); #ifdef USE_TANGENT vTangent = normalize( transformedTangent ); vBitangent = normalize( cross( vNormal, vTangent ) * tangent.w ); #endif #endif`,WL=`#ifdef USE_NORMALMAP uniform sampler2D normalMap; uniform vec2 normalScale; #endif #ifdef USE_NORMALMAP_OBJECTSPACE uniform mat3 normalMatrix; #endif #if ! defined ( USE_TANGENT ) && ( defined ( USE_NORMALMAP_TANGENTSPACE ) || defined ( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY ) ) mat3 getTangentFrame( vec3 eye_pos, vec3 surf_norm, vec2 uv ) { vec3 q0 = dFdx( eye_pos.xyz ); vec3 q1 = dFdy( eye_pos.xyz ); vec2 st0 = dFdx( uv.st ); vec2 st1 = dFdy( uv.st ); vec3 N = surf_norm; vec3 q1perp = cross( q1, N ); vec3 q0perp = cross( N, q0 ); vec3 T = q1perp * st0.x + q0perp * st1.x; vec3 B = q1perp * st0.y + q0perp * st1.y; float det = max( dot( T, T ), dot( B, B ) ); float scale = ( det == 0.0 ) ? 0.0 : inversesqrt( det ); return mat3( T * scale, B * scale, N ); } #endif`,XL=`#ifdef USE_CLEARCOAT vec3 clearcoatNormal = nonPerturbedNormal; #endif`,jL=`#ifdef USE_CLEARCOAT_NORMALMAP vec3 clearcoatMapN = texture2D( clearcoatNormalMap, vClearcoatNormalMapUv ).xyz * 2.0 - 1.0; clearcoatMapN.xy *= clearcoatNormalScale; clearcoatNormal = normalize( tbn2 * clearcoatMapN ); #endif`,qL=`#ifdef USE_CLEARCOATMAP uniform sampler2D clearcoatMap; #endif #ifdef USE_CLEARCOAT_NORMALMAP uniform sampler2D clearcoatNormalMap; uniform vec2 clearcoatNormalScale; #endif #ifdef USE_CLEARCOAT_ROUGHNESSMAP uniform sampler2D clearcoatRoughnessMap; #endif`,ZL=`#ifdef USE_IRIDESCENCEMAP uniform sampler2D iridescenceMap; #endif #ifdef USE_IRIDESCENCE_THICKNESSMAP uniform sampler2D iridescenceThicknessMap; #endif`,YL=`#ifdef OPAQUE diffuseColor.a = 1.0; #endif #ifdef USE_TRANSMISSION diffuseColor.a *= material.transmissionAlpha; #endif gl_FragColor = vec4( outgoingLight, diffuseColor.a );`,$L=`vec3 packNormalToRGB( const in vec3 normal ) { return normalize( normal ) * 0.5 + 0.5; } vec3 unpackRGBToNormal( const in vec3 rgb ) { return 2.0 * rgb.xyz - 1.0; } const float PackUpscale = 256. / 255.;const float UnpackDownscale = 255. / 256.;const float ShiftRight8 = 1. / 256.; const float Inv255 = 1. / 255.; const vec4 PackFactors = vec4( 1.0, 256.0, 256.0 * 256.0, 256.0 * 256.0 * 256.0 ); const vec2 UnpackFactors2 = vec2( UnpackDownscale, 1.0 / PackFactors.g ); const vec3 UnpackFactors3 = vec3( UnpackDownscale / PackFactors.rg, 1.0 / PackFactors.b ); const vec4 UnpackFactors4 = vec4( UnpackDownscale / PackFactors.rgb, 1.0 / PackFactors.a ); vec4 packDepthToRGBA( const in float v ) { if( v <= 0.0 ) return vec4( 0., 0., 0., 0. ); if( v >= 1.0 ) return vec4( 1., 1., 1., 1. ); float vuf; float af = modf( v * PackFactors.a, vuf ); float bf = modf( vuf * ShiftRight8, vuf ); float gf = modf( vuf * ShiftRight8, vuf ); return vec4( vuf * Inv255, gf * PackUpscale, bf * PackUpscale, af ); } vec3 packDepthToRGB( const in float v ) { if( v <= 0.0 ) return vec3( 0., 0., 0. ); if( v >= 1.0 ) return vec3( 1., 1., 1. ); float vuf; float bf = modf( v * PackFactors.b, vuf ); float gf = modf( vuf * ShiftRight8, vuf ); return vec3( vuf * Inv255, gf * PackUpscale, bf ); } vec2 packDepthToRG( const in float v ) { if( v <= 0.0 ) return vec2( 0., 0. ); if( v >= 1.0 ) return vec2( 1., 1. ); float vuf; float gf = modf( v * 256., vuf ); return vec2( vuf * Inv255, gf ); } float unpackRGBAToDepth( const in vec4 v ) { return dot( v, UnpackFactors4 ); } float unpackRGBToDepth( const in vec3 v ) { return dot( v, UnpackFactors3 ); } float unpackRGToDepth( const in vec2 v ) { return v.r * UnpackFactors2.r + v.g * UnpackFactors2.g; } vec4 pack2HalfToRGBA( const in vec2 v ) { vec4 r = vec4( v.x, fract( v.x * 255.0 ), v.y, fract( v.y * 255.0 ) ); return vec4( r.x - r.y / 255.0, r.y, r.z - r.w / 255.0, r.w ); } vec2 unpackRGBATo2Half( const in vec4 v ) { return vec2( v.x + ( v.y / 255.0 ), v.z + ( v.w / 255.0 ) ); } float viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) { return ( viewZ + near ) / ( near - far ); } float orthographicDepthToViewZ( const in float depth, const in float near, const in float far ) { return depth * ( near - far ) - near; } float viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) { return ( ( near + viewZ ) * far ) / ( ( far - near ) * viewZ ); } float perspectiveDepthToViewZ( const in float depth, const in float near, const in float far ) { return ( near * far ) / ( ( far - near ) * depth - far ); }`,KL=`#ifdef PREMULTIPLIED_ALPHA gl_FragColor.rgb *= gl_FragColor.a; #endif`,JL=`vec4 mvPosition = vec4( transformed, 1.0 ); #ifdef USE_BATCHING mvPosition = batchingMatrix * mvPosition; #endif #ifdef USE_INSTANCING mvPosition = instanceMatrix * mvPosition; #endif mvPosition = modelViewMatrix * mvPosition; gl_Position = projectionMatrix * mvPosition;`,QL=`#ifdef DITHERING gl_FragColor.rgb = dithering( gl_FragColor.rgb ); #endif`,eD=`#ifdef DITHERING vec3 dithering( vec3 color ) { float grid_position = rand( gl_FragCoord.xy ); vec3 dither_shift_RGB = vec3( 0.25 / 255.0, -0.25 / 255.0, 0.25 / 255.0 ); dither_shift_RGB = mix( 2.0 * dither_shift_RGB, -2.0 * dither_shift_RGB, grid_position ); return color + dither_shift_RGB; } #endif`,tD=`float roughnessFactor = roughness; #ifdef USE_ROUGHNESSMAP vec4 texelRoughness = texture2D( roughnessMap, vRoughnessMapUv ); roughnessFactor *= texelRoughness.g; #endif`,iD=`#ifdef USE_ROUGHNESSMAP uniform sampler2D roughnessMap; #endif`,nD=`#if NUM_SPOT_LIGHT_COORDS > 0 varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ]; #endif #if NUM_SPOT_LIGHT_MAPS > 0 uniform sampler2D spotLightMap[ NUM_SPOT_LIGHT_MAPS ]; #endif #ifdef USE_SHADOWMAP #if NUM_DIR_LIGHT_SHADOWS > 0 uniform sampler2D directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ]; varying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ]; struct DirectionalLightShadow { float shadowIntensity; float shadowBias; float shadowNormalBias; float shadowRadius; vec2 shadowMapSize; }; uniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ]; #endif #if NUM_SPOT_LIGHT_SHADOWS > 0 uniform sampler2D spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ]; struct SpotLightShadow { float shadowIntensity; float shadowBias; float shadowNormalBias; float shadowRadius; vec2 shadowMapSize; }; uniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ]; #endif #if NUM_POINT_LIGHT_SHADOWS > 0 uniform sampler2D pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ]; varying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ]; struct PointLightShadow { float shadowIntensity; float shadowBias; float shadowNormalBias; float shadowRadius; vec2 shadowMapSize; float shadowCameraNear; float shadowCameraFar; }; uniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ]; #endif float texture2DCompare( sampler2D depths, vec2 uv, float compare ) { float depth = unpackRGBAToDepth( texture2D( depths, uv ) ); #ifdef USE_REVERSED_DEPTH_BUFFER return step( depth, compare ); #else return step( compare, depth ); #endif } vec2 texture2DDistribution( sampler2D shadow, vec2 uv ) { return unpackRGBATo2Half( texture2D( shadow, uv ) ); } float VSMShadow( sampler2D shadow, vec2 uv, float compare ) { float occlusion = 1.0; vec2 distribution = texture2DDistribution( shadow, uv ); #ifdef USE_REVERSED_DEPTH_BUFFER float hard_shadow = step( distribution.x, compare ); #else float hard_shadow = step( compare, distribution.x ); #endif if ( hard_shadow != 1.0 ) { float distance = compare - distribution.x; float variance = max( 0.00000, distribution.y * distribution.y ); float softness_probability = variance / (variance + distance * distance ); softness_probability = clamp( ( softness_probability - 0.3 ) / ( 0.95 - 0.3 ), 0.0, 1.0 ); occlusion = clamp( max( hard_shadow, softness_probability ), 0.0, 1.0 ); } return occlusion; } float getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord ) { float shadow = 1.0; shadowCoord.xyz /= shadowCoord.w; shadowCoord.z += shadowBias; bool inFrustum = shadowCoord.x >= 0.0 && shadowCoord.x <= 1.0 && shadowCoord.y >= 0.0 && shadowCoord.y <= 1.0; bool frustumTest = inFrustum && shadowCoord.z <= 1.0; if ( frustumTest ) { #if defined( SHADOWMAP_TYPE_PCF ) vec2 texelSize = vec2( 1.0 ) / shadowMapSize; float dx0 = - texelSize.x * shadowRadius; float dy0 = - texelSize.y * shadowRadius; float dx1 = + texelSize.x * shadowRadius; float dy1 = + texelSize.y * shadowRadius; float dx2 = dx0 / 2.0; float dy2 = dy0 / 2.0; float dx3 = dx1 / 2.0; float dy3 = dy1 / 2.0; shadow = ( texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) + texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy2 ), shadowCoord.z ) + texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy2 ), shadowCoord.z ) + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy2 ), shadowCoord.z ) + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, 0.0 ), shadowCoord.z ) + texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ) + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, 0.0 ), shadowCoord.z ) + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy3 ), shadowCoord.z ) + texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy3 ), shadowCoord.z ) + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy3 ), shadowCoord.z ) + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) + texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z ) ) * ( 1.0 / 17.0 ); #elif defined( SHADOWMAP_TYPE_PCF_SOFT ) vec2 texelSize = vec2( 1.0 ) / shadowMapSize; float dx = texelSize.x; float dy = texelSize.y; vec2 uv = shadowCoord.xy; vec2 f = fract( uv * shadowMapSize + 0.5 ); uv -= f * texelSize; shadow = ( texture2DCompare( shadowMap, uv, shadowCoord.z ) + texture2DCompare( shadowMap, uv + vec2( dx, 0.0 ), shadowCoord.z ) + texture2DCompare( shadowMap, uv + vec2( 0.0, dy ), shadowCoord.z ) + texture2DCompare( shadowMap, uv + texelSize, shadowCoord.z ) + mix( texture2DCompare( shadowMap, uv + vec2( -dx, 0.0 ), shadowCoord.z ), texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 0.0 ), shadowCoord.z ), f.x ) + mix( texture2DCompare( shadowMap, uv + vec2( -dx, dy ), shadowCoord.z ), texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, dy ), shadowCoord.z ), f.x ) + mix( texture2DCompare( shadowMap, uv + vec2( 0.0, -dy ), shadowCoord.z ), texture2DCompare( shadowMap, uv + vec2( 0.0, 2.0 * dy ), shadowCoord.z ), f.y ) + mix( texture2DCompare( shadowMap, uv + vec2( dx, -dy ), shadowCoord.z ), texture2DCompare( shadowMap, uv + vec2( dx, 2.0 * dy ), shadowCoord.z ), f.y ) + mix( mix( texture2DCompare( shadowMap, uv + vec2( -dx, -dy ), shadowCoord.z ), texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, -dy ), shadowCoord.z ), f.x ), mix( texture2DCompare( shadowMap, uv + vec2( -dx, 2.0 * dy ), shadowCoord.z ), texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 2.0 * dy ), shadowCoord.z ), f.x ), f.y ) ) * ( 1.0 / 9.0 ); #elif defined( SHADOWMAP_TYPE_VSM ) shadow = VSMShadow( shadowMap, shadowCoord.xy, shadowCoord.z ); #else shadow = texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ); #endif } return mix( 1.0, shadow, shadowIntensity ); } vec2 cubeToUV( vec3 v, float texelSizeY ) { vec3 absV = abs( v ); float scaleToCube = 1.0 / max( absV.x, max( absV.y, absV.z ) ); absV *= scaleToCube; v *= scaleToCube * ( 1.0 - 2.0 * texelSizeY ); vec2 planar = v.xy; float almostATexel = 1.5 * texelSizeY; float almostOne = 1.0 - almostATexel; if ( absV.z >= almostOne ) { if ( v.z > 0.0 ) planar.x = 4.0 - v.x; } else if ( absV.x >= almostOne ) { float signX = sign( v.x ); planar.x = v.z * signX + 2.0 * signX; } else if ( absV.y >= almostOne ) { float signY = sign( v.y ); planar.x = v.x + 2.0 * signY + 2.0; planar.y = v.z * signY - 2.0; } return vec2( 0.125, 0.25 ) * planar + vec2( 0.375, 0.75 ); } float getPointShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) { float shadow = 1.0; vec3 lightToPosition = shadowCoord.xyz; float lightToPositionLength = length( lightToPosition ); if ( lightToPositionLength - shadowCameraFar <= 0.0 && lightToPositionLength - shadowCameraNear >= 0.0 ) { float dp = ( lightToPositionLength - shadowCameraNear ) / ( shadowCameraFar - shadowCameraNear ); dp += shadowBias; vec3 bd3D = normalize( lightToPosition ); vec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) ); #if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT ) || defined( SHADOWMAP_TYPE_VSM ) vec2 offset = vec2( - 1, 1 ) * shadowRadius * texelSize.y; shadow = ( texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyy, texelSize.y ), dp ) + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyy, texelSize.y ), dp ) + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyx, texelSize.y ), dp ) + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyx, texelSize.y ), dp ) + texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ) + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxy, texelSize.y ), dp ) + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxy, texelSize.y ), dp ) + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxx, texelSize.y ), dp ) + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxx, texelSize.y ), dp ) ) * ( 1.0 / 9.0 ); #else shadow = texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ); #endif } return mix( 1.0, shadow, shadowIntensity ); } #endif`,sD=`#if NUM_SPOT_LIGHT_COORDS > 0 uniform mat4 spotLightMatrix[ NUM_SPOT_LIGHT_COORDS ]; varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ]; #endif #ifdef USE_SHADOWMAP #if NUM_DIR_LIGHT_SHADOWS > 0 uniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHT_SHADOWS ]; varying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ]; struct DirectionalLightShadow { float shadowIntensity; float shadowBias; float shadowNormalBias; float shadowRadius; vec2 shadowMapSize; }; uniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ]; #endif #if NUM_SPOT_LIGHT_SHADOWS > 0 struct SpotLightShadow { float shadowIntensity; float shadowBias; float shadowNormalBias; float shadowRadius; vec2 shadowMapSize; }; uniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ]; #endif #if NUM_POINT_LIGHT_SHADOWS > 0 uniform mat4 pointShadowMatrix[ NUM_POINT_LIGHT_SHADOWS ]; varying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ]; struct PointLightShadow { float shadowIntensity; float shadowBias; float shadowNormalBias; float shadowRadius; vec2 shadowMapSize; float shadowCameraNear; float shadowCameraFar; }; uniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ]; #endif #endif`,rD=`#if ( defined( USE_SHADOWMAP ) && ( NUM_DIR_LIGHT_SHADOWS > 0 || NUM_POINT_LIGHT_SHADOWS > 0 ) ) || ( NUM_SPOT_LIGHT_COORDS > 0 ) vec3 shadowWorldNormal = inverseTransformDirection( transformedNormal, viewMatrix ); vec4 shadowWorldPosition; #endif #if defined( USE_SHADOWMAP ) #if NUM_DIR_LIGHT_SHADOWS > 0 #pragma unroll_loop_start for ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) { shadowWorldPosition = worldPosition + vec4( shadowWorldNormal * directionalLightShadows[ i ].shadowNormalBias, 0 ); vDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * shadowWorldPosition; } #pragma unroll_loop_end #endif #if NUM_POINT_LIGHT_SHADOWS > 0 #pragma unroll_loop_start for ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) { shadowWorldPosition = worldPosition + vec4( shadowWorldNormal * pointLightShadows[ i ].shadowNormalBias, 0 ); vPointShadowCoord[ i ] = pointShadowMatrix[ i ] * shadowWorldPosition; } #pragma unroll_loop_end #endif #endif #if NUM_SPOT_LIGHT_COORDS > 0 #pragma unroll_loop_start for ( int i = 0; i < NUM_SPOT_LIGHT_COORDS; i ++ ) { shadowWorldPosition = worldPosition; #if ( defined( USE_SHADOWMAP ) && UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS ) shadowWorldPosition.xyz += shadowWorldNormal * spotLightShadows[ i ].shadowNormalBias; #endif vSpotLightCoord[ i ] = spotLightMatrix[ i ] * shadowWorldPosition; } #pragma unroll_loop_end #endif`,aD=`float getShadowMask() { float shadow = 1.0; #ifdef USE_SHADOWMAP #if NUM_DIR_LIGHT_SHADOWS > 0 DirectionalLightShadow directionalLight; #pragma unroll_loop_start for ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) { directionalLight = directionalLightShadows[ i ]; shadow *= receiveShadow ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowIntensity, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0; } #pragma unroll_loop_end #endif #if NUM_SPOT_LIGHT_SHADOWS > 0 SpotLightShadow spotLight; #pragma unroll_loop_start for ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) { spotLight = spotLightShadows[ i ]; shadow *= receiveShadow ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowIntensity, spotLight.shadowBias, spotLight.shadowRadius, vSpotLightCoord[ i ] ) : 1.0; } #pragma unroll_loop_end #endif #if NUM_POINT_LIGHT_SHADOWS > 0 PointLightShadow pointLight; #pragma unroll_loop_start for ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) { pointLight = pointLightShadows[ i ]; shadow *= receiveShadow ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowIntensity, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0; } #pragma unroll_loop_end #endif #endif return shadow; }`,oD=`#ifdef USE_SKINNING mat4 boneMatX = getBoneMatrix( skinIndex.x ); mat4 boneMatY = getBoneMatrix( skinIndex.y ); mat4 boneMatZ = getBoneMatrix( skinIndex.z ); mat4 boneMatW = getBoneMatrix( skinIndex.w ); #endif`,lD=`#ifdef USE_SKINNING uniform mat4 bindMatrix; uniform mat4 bindMatrixInverse; uniform highp sampler2D boneTexture; mat4 getBoneMatrix( const in float i ) { int size = textureSize( boneTexture, 0 ).x; int j = int( i ) * 4; int x = j % size; int y = j / size; vec4 v1 = texelFetch( boneTexture, ivec2( x, y ), 0 ); vec4 v2 = texelFetch( boneTexture, ivec2( x + 1, y ), 0 ); vec4 v3 = texelFetch( boneTexture, ivec2( x + 2, y ), 0 ); vec4 v4 = texelFetch( boneTexture, ivec2( x + 3, y ), 0 ); return mat4( v1, v2, v3, v4 ); } #endif`,cD=`#ifdef USE_SKINNING vec4 skinVertex = bindMatrix * vec4( transformed, 1.0 ); vec4 skinned = vec4( 0.0 ); skinned += boneMatX * skinVertex * skinWeight.x; skinned += boneMatY * skinVertex * skinWeight.y; skinned += boneMatZ * skinVertex * skinWeight.z; skinned += boneMatW * skinVertex * skinWeight.w; transformed = ( bindMatrixInverse * skinned ).xyz; #endif`,hD=`#ifdef USE_SKINNING mat4 skinMatrix = mat4( 0.0 ); skinMatrix += skinWeight.x * boneMatX; skinMatrix += skinWeight.y * boneMatY; skinMatrix += skinWeight.z * boneMatZ; skinMatrix += skinWeight.w * boneMatW; skinMatrix = bindMatrixInverse * skinMatrix * bindMatrix; objectNormal = vec4( skinMatrix * vec4( objectNormal, 0.0 ) ).xyz; #ifdef USE_TANGENT objectTangent = vec4( skinMatrix * vec4( objectTangent, 0.0 ) ).xyz; #endif #endif`,dD=`float specularStrength; #ifdef USE_SPECULARMAP vec4 texelSpecular = texture2D( specularMap, vSpecularMapUv ); specularStrength = texelSpecular.r; #else specularStrength = 1.0; #endif`,uD=`#ifdef USE_SPECULARMAP uniform sampler2D specularMap; #endif`,pD=`#if defined( TONE_MAPPING ) gl_FragColor.rgb = toneMapping( gl_FragColor.rgb ); #endif`,fD=`#ifndef saturate #define saturate( a ) clamp( a, 0.0, 1.0 ) #endif uniform float toneMappingExposure; vec3 LinearToneMapping( vec3 color ) { return saturate( toneMappingExposure * color ); } vec3 ReinhardToneMapping( vec3 color ) { color *= toneMappingExposure; return saturate( color / ( vec3( 1.0 ) + color ) ); } vec3 CineonToneMapping( vec3 color ) { color *= toneMappingExposure; color = max( vec3( 0.0 ), color - 0.004 ); return pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) ); } vec3 RRTAndODTFit( vec3 v ) { vec3 a = v * ( v + 0.0245786 ) - 0.000090537; vec3 b = v * ( 0.983729 * v + 0.4329510 ) + 0.238081; return a / b; } vec3 ACESFilmicToneMapping( vec3 color ) { const mat3 ACESInputMat = mat3( vec3( 0.59719, 0.07600, 0.02840 ), vec3( 0.35458, 0.90834, 0.13383 ), vec3( 0.04823, 0.01566, 0.83777 ) ); const mat3 ACESOutputMat = mat3( vec3( 1.60475, -0.10208, -0.00327 ), vec3( -0.53108, 1.10813, -0.07276 ), vec3( -0.07367, -0.00605, 1.07602 ) ); color *= toneMappingExposure / 0.6; color = ACESInputMat * color; color = RRTAndODTFit( color ); color = ACESOutputMat * color; return saturate( color ); } const mat3 LINEAR_REC2020_TO_LINEAR_SRGB = mat3( vec3( 1.6605, - 0.1246, - 0.0182 ), vec3( - 0.5876, 1.1329, - 0.1006 ), vec3( - 0.0728, - 0.0083, 1.1187 ) ); const mat3 LINEAR_SRGB_TO_LINEAR_REC2020 = mat3( vec3( 0.6274, 0.0691, 0.0164 ), vec3( 0.3293, 0.9195, 0.0880 ), vec3( 0.0433, 0.0113, 0.8956 ) ); vec3 agxDefaultContrastApprox( vec3 x ) { vec3 x2 = x * x; vec3 x4 = x2 * x2; return + 15.5 * x4 * x2 - 40.14 * x4 * x + 31.96 * x4 - 6.868 * x2 * x + 0.4298 * x2 + 0.1191 * x - 0.00232; } vec3 AgXToneMapping( vec3 color ) { const mat3 AgXInsetMatrix = mat3( vec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ), vec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ), vec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 ) ); const mat3 AgXOutsetMatrix = mat3( vec3( 1.1271005818144368, - 0.1413297634984383, - 0.14132976349843826 ), vec3( - 0.11060664309660323, 1.157823702216272, - 0.11060664309660294 ), vec3( - 0.016493938717834573, - 0.016493938717834257, 1.2519364065950405 ) ); const float AgxMinEv = - 12.47393; const float AgxMaxEv = 4.026069; color *= toneMappingExposure; color = LINEAR_SRGB_TO_LINEAR_REC2020 * color; color = AgXInsetMatrix * color; color = max( color, 1e-10 ); color = log2( color ); color = ( color - AgxMinEv ) / ( AgxMaxEv - AgxMinEv ); color = clamp( color, 0.0, 1.0 ); color = agxDefaultContrastApprox( color ); color = AgXOutsetMatrix * color; color = pow( max( vec3( 0.0 ), color ), vec3( 2.2 ) ); color = LINEAR_REC2020_TO_LINEAR_SRGB * color; color = clamp( color, 0.0, 1.0 ); return color; } vec3 NeutralToneMapping( vec3 color ) { const float StartCompression = 0.8 - 0.04; const float Desaturation = 0.15; color *= toneMappingExposure; float x = min( color.r, min( color.g, color.b ) ); float offset = x < 0.08 ? x - 6.25 * x * x : 0.04; color -= offset; float peak = max( color.r, max( color.g, color.b ) ); if ( peak < StartCompression ) return color; float d = 1. - StartCompression; float newPeak = 1. - d * d / ( peak + d - StartCompression ); color *= newPeak / peak; float g = 1. - 1. / ( Desaturation * ( peak - newPeak ) + 1. ); return mix( color, vec3( newPeak ), g ); } vec3 CustomToneMapping( vec3 color ) { return color; }`,mD=`#ifdef USE_TRANSMISSION material.transmission = transmission; material.transmissionAlpha = 1.0; material.thickness = thickness; material.attenuationDistance = attenuationDistance; material.attenuationColor = attenuationColor; #ifdef USE_TRANSMISSIONMAP material.transmission *= texture2D( transmissionMap, vTransmissionMapUv ).r; #endif #ifdef USE_THICKNESSMAP material.thickness *= texture2D( thicknessMap, vThicknessMapUv ).g; #endif vec3 pos = vWorldPosition; vec3 v = normalize( cameraPosition - pos ); vec3 n = inverseTransformDirection( normal, viewMatrix ); vec4 transmitted = getIBLVolumeRefraction( n, v, material.roughness, material.diffuseColor, material.specularColor, material.specularF90, pos, modelMatrix, viewMatrix, projectionMatrix, material.dispersion, material.ior, material.thickness, material.attenuationColor, material.attenuationDistance ); material.transmissionAlpha = mix( material.transmissionAlpha, transmitted.a, material.transmission ); totalDiffuse = mix( totalDiffuse, transmitted.rgb, material.transmission ); #endif`,gD=`#ifdef USE_TRANSMISSION uniform float transmission; uniform float thickness; uniform float attenuationDistance; uniform vec3 attenuationColor; #ifdef USE_TRANSMISSIONMAP uniform sampler2D transmissionMap; #endif #ifdef USE_THICKNESSMAP uniform sampler2D thicknessMap; #endif uniform vec2 transmissionSamplerSize; uniform sampler2D transmissionSamplerMap; uniform mat4 modelMatrix; uniform mat4 projectionMatrix; varying vec3 vWorldPosition; float w0( float a ) { return ( 1.0 / 6.0 ) * ( a * ( a * ( - a + 3.0 ) - 3.0 ) + 1.0 ); } float w1( float a ) { return ( 1.0 / 6.0 ) * ( a * a * ( 3.0 * a - 6.0 ) + 4.0 ); } float w2( float a ){ return ( 1.0 / 6.0 ) * ( a * ( a * ( - 3.0 * a + 3.0 ) + 3.0 ) + 1.0 ); } float w3( float a ) { return ( 1.0 / 6.0 ) * ( a * a * a ); } float g0( float a ) { return w0( a ) + w1( a ); } float g1( float a ) { return w2( a ) + w3( a ); } float h0( float a ) { return - 1.0 + w1( a ) / ( w0( a ) + w1( a ) ); } float h1( float a ) { return 1.0 + w3( a ) / ( w2( a ) + w3( a ) ); } vec4 bicubic( sampler2D tex, vec2 uv, vec4 texelSize, float lod ) { uv = uv * texelSize.zw + 0.5; vec2 iuv = floor( uv ); vec2 fuv = fract( uv ); float g0x = g0( fuv.x ); float g1x = g1( fuv.x ); float h0x = h0( fuv.x ); float h1x = h1( fuv.x ); float h0y = h0( fuv.y ); float h1y = h1( fuv.y ); vec2 p0 = ( vec2( iuv.x + h0x, iuv.y + h0y ) - 0.5 ) * texelSize.xy; vec2 p1 = ( vec2( iuv.x + h1x, iuv.y + h0y ) - 0.5 ) * texelSize.xy; vec2 p2 = ( vec2( iuv.x + h0x, iuv.y + h1y ) - 0.5 ) * texelSize.xy; vec2 p3 = ( vec2( iuv.x + h1x, iuv.y + h1y ) - 0.5 ) * texelSize.xy; return g0( fuv.y ) * ( g0x * textureLod( tex, p0, lod ) + g1x * textureLod( tex, p1, lod ) ) + g1( fuv.y ) * ( g0x * textureLod( tex, p2, lod ) + g1x * textureLod( tex, p3, lod ) ); } vec4 textureBicubic( sampler2D sampler, vec2 uv, float lod ) { vec2 fLodSize = vec2( textureSize( sampler, int( lod ) ) ); vec2 cLodSize = vec2( textureSize( sampler, int( lod + 1.0 ) ) ); vec2 fLodSizeInv = 1.0 / fLodSize; vec2 cLodSizeInv = 1.0 / cLodSize; vec4 fSample = bicubic( sampler, uv, vec4( fLodSizeInv, fLodSize ), floor( lod ) ); vec4 cSample = bicubic( sampler, uv, vec4( cLodSizeInv, cLodSize ), ceil( lod ) ); return mix( fSample, cSample, fract( lod ) ); } vec3 getVolumeTransmissionRay( const in vec3 n, const in vec3 v, const in float thickness, const in float ior, const in mat4 modelMatrix ) { vec3 refractionVector = refract( - v, normalize( n ), 1.0 / ior ); vec3 modelScale; modelScale.x = length( vec3( modelMatrix[ 0 ].xyz ) ); modelScale.y = length( vec3( modelMatrix[ 1 ].xyz ) ); modelScale.z = length( vec3( modelMatrix[ 2 ].xyz ) ); return normalize( refractionVector ) * thickness * modelScale; } float applyIorToRoughness( const in float roughness, const in float ior ) { return roughness * clamp( ior * 2.0 - 2.0, 0.0, 1.0 ); } vec4 getTransmissionSample( const in vec2 fragCoord, const in float roughness, const in float ior ) { float lod = log2( transmissionSamplerSize.x ) * applyIorToRoughness( roughness, ior ); return textureBicubic( transmissionSamplerMap, fragCoord.xy, lod ); } vec3 volumeAttenuation( const in float transmissionDistance, const in vec3 attenuationColor, const in float attenuationDistance ) { if ( isinf( attenuationDistance ) ) { return vec3( 1.0 ); } else { vec3 attenuationCoefficient = -log( attenuationColor ) / attenuationDistance; vec3 transmittance = exp( - attenuationCoefficient * transmissionDistance ); return transmittance; } } vec4 getIBLVolumeRefraction( const in vec3 n, const in vec3 v, const in float roughness, const in vec3 diffuseColor, const in vec3 specularColor, const in float specularF90, const in vec3 position, const in mat4 modelMatrix, const in mat4 viewMatrix, const in mat4 projMatrix, const in float dispersion, const in float ior, const in float thickness, const in vec3 attenuationColor, const in float attenuationDistance ) { vec4 transmittedLight; vec3 transmittance; #ifdef USE_DISPERSION float halfSpread = ( ior - 1.0 ) * 0.025 * dispersion; vec3 iors = vec3( ior - halfSpread, ior, ior + halfSpread ); for ( int i = 0; i < 3; i ++ ) { vec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, iors[ i ], modelMatrix ); vec3 refractedRayExit = position + transmissionRay; vec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 ); vec2 refractionCoords = ndcPos.xy / ndcPos.w; refractionCoords += 1.0; refractionCoords /= 2.0; vec4 transmissionSample = getTransmissionSample( refractionCoords, roughness, iors[ i ] ); transmittedLight[ i ] = transmissionSample[ i ]; transmittedLight.a += transmissionSample.a; transmittance[ i ] = diffuseColor[ i ] * volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance )[ i ]; } transmittedLight.a /= 3.0; #else vec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix ); vec3 refractedRayExit = position + transmissionRay; vec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 ); vec2 refractionCoords = ndcPos.xy / ndcPos.w; refractionCoords += 1.0; refractionCoords /= 2.0; transmittedLight = getTransmissionSample( refractionCoords, roughness, ior ); transmittance = diffuseColor * volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ); #endif vec3 attenuatedColor = transmittance * transmittedLight.rgb; vec3 F = EnvironmentBRDF( n, v, specularColor, specularF90, roughness ); float transmittanceFactor = ( transmittance.r + transmittance.g + transmittance.b ) / 3.0; return vec4( ( 1.0 - F ) * attenuatedColor, 1.0 - ( 1.0 - transmittedLight.a ) * transmittanceFactor ); } #endif`,vD=`#if defined( USE_UV ) || defined( USE_ANISOTROPY ) varying vec2 vUv; #endif #ifdef USE_MAP varying vec2 vMapUv; #endif #ifdef USE_ALPHAMAP varying vec2 vAlphaMapUv; #endif #ifdef USE_LIGHTMAP varying vec2 vLightMapUv; #endif #ifdef USE_AOMAP varying vec2 vAoMapUv; #endif #ifdef USE_BUMPMAP varying vec2 vBumpMapUv; #endif #ifdef USE_NORMALMAP varying vec2 vNormalMapUv; #endif #ifdef USE_EMISSIVEMAP varying vec2 vEmissiveMapUv; #endif #ifdef USE_METALNESSMAP varying vec2 vMetalnessMapUv; #endif #ifdef USE_ROUGHNESSMAP varying vec2 vRoughnessMapUv; #endif #ifdef USE_ANISOTROPYMAP varying vec2 vAnisotropyMapUv; #endif #ifdef USE_CLEARCOATMAP varying vec2 vClearcoatMapUv; #endif #ifdef USE_CLEARCOAT_NORMALMAP varying vec2 vClearcoatNormalMapUv; #endif #ifdef USE_CLEARCOAT_ROUGHNESSMAP varying vec2 vClearcoatRoughnessMapUv; #endif #ifdef USE_IRIDESCENCEMAP varying vec2 vIridescenceMapUv; #endif #ifdef USE_IRIDESCENCE_THICKNESSMAP varying vec2 vIridescenceThicknessMapUv; #endif #ifdef USE_SHEEN_COLORMAP varying vec2 vSheenColorMapUv; #endif #ifdef USE_SHEEN_ROUGHNESSMAP varying vec2 vSheenRoughnessMapUv; #endif #ifdef USE_SPECULARMAP varying vec2 vSpecularMapUv; #endif #ifdef USE_SPECULAR_COLORMAP varying vec2 vSpecularColorMapUv; #endif #ifdef USE_SPECULAR_INTENSITYMAP varying vec2 vSpecularIntensityMapUv; #endif #ifdef USE_TRANSMISSIONMAP uniform mat3 transmissionMapTransform; varying vec2 vTransmissionMapUv; #endif #ifdef USE_THICKNESSMAP uniform mat3 thicknessMapTransform; varying vec2 vThicknessMapUv; #endif`,yD=`#if defined( USE_UV ) || defined( USE_ANISOTROPY ) varying vec2 vUv; #endif #ifdef USE_MAP uniform mat3 mapTransform; varying vec2 vMapUv; #endif #ifdef USE_ALPHAMAP uniform mat3 alphaMapTransform; varying vec2 vAlphaMapUv; #endif #ifdef USE_LIGHTMAP uniform mat3 lightMapTransform; varying vec2 vLightMapUv; #endif #ifdef USE_AOMAP uniform mat3 aoMapTransform; varying vec2 vAoMapUv; #endif #ifdef USE_BUMPMAP uniform mat3 bumpMapTransform; varying vec2 vBumpMapUv; #endif #ifdef USE_NORMALMAP uniform mat3 normalMapTransform; varying vec2 vNormalMapUv; #endif #ifdef USE_DISPLACEMENTMAP uniform mat3 displacementMapTransform; varying vec2 vDisplacementMapUv; #endif #ifdef USE_EMISSIVEMAP uniform mat3 emissiveMapTransform; varying vec2 vEmissiveMapUv; #endif #ifdef USE_METALNESSMAP uniform mat3 metalnessMapTransform; varying vec2 vMetalnessMapUv; #endif #ifdef USE_ROUGHNESSMAP uniform mat3 roughnessMapTransform; varying vec2 vRoughnessMapUv; #endif #ifdef USE_ANISOTROPYMAP uniform mat3 anisotropyMapTransform; varying vec2 vAnisotropyMapUv; #endif #ifdef USE_CLEARCOATMAP uniform mat3 clearcoatMapTransform; varying vec2 vClearcoatMapUv; #endif #ifdef USE_CLEARCOAT_NORMALMAP uniform mat3 clearcoatNormalMapTransform; varying vec2 vClearcoatNormalMapUv; #endif #ifdef USE_CLEARCOAT_ROUGHNESSMAP uniform mat3 clearcoatRoughnessMapTransform; varying vec2 vClearcoatRoughnessMapUv; #endif #ifdef USE_SHEEN_COLORMAP uniform mat3 sheenColorMapTransform; varying vec2 vSheenColorMapUv; #endif #ifdef USE_SHEEN_ROUGHNESSMAP uniform mat3 sheenRoughnessMapTransform; varying vec2 vSheenRoughnessMapUv; #endif #ifdef USE_IRIDESCENCEMAP uniform mat3 iridescenceMapTransform; varying vec2 vIridescenceMapUv; #endif #ifdef USE_IRIDESCENCE_THICKNESSMAP uniform mat3 iridescenceThicknessMapTransform; varying vec2 vIridescenceThicknessMapUv; #endif #ifdef USE_SPECULARMAP uniform mat3 specularMapTransform; varying vec2 vSpecularMapUv; #endif #ifdef USE_SPECULAR_COLORMAP uniform mat3 specularColorMapTransform; varying vec2 vSpecularColorMapUv; #endif #ifdef USE_SPECULAR_INTENSITYMAP uniform mat3 specularIntensityMapTransform; varying vec2 vSpecularIntensityMapUv; #endif #ifdef USE_TRANSMISSIONMAP uniform mat3 transmissionMapTransform; varying vec2 vTransmissionMapUv; #endif #ifdef USE_THICKNESSMAP uniform mat3 thicknessMapTransform; varying vec2 vThicknessMapUv; #endif`,xD=`#if defined( USE_UV ) || defined( USE_ANISOTROPY ) vUv = vec3( uv, 1 ).xy; #endif #ifdef USE_MAP vMapUv = ( mapTransform * vec3( MAP_UV, 1 ) ).xy; #endif #ifdef USE_ALPHAMAP vAlphaMapUv = ( alphaMapTransform * vec3( ALPHAMAP_UV, 1 ) ).xy; #endif #ifdef USE_LIGHTMAP vLightMapUv = ( lightMapTransform * vec3( LIGHTMAP_UV, 1 ) ).xy; #endif #ifdef USE_AOMAP vAoMapUv = ( aoMapTransform * vec3( AOMAP_UV, 1 ) ).xy; #endif #ifdef USE_BUMPMAP vBumpMapUv = ( bumpMapTransform * vec3( BUMPMAP_UV, 1 ) ).xy; #endif #ifdef USE_NORMALMAP vNormalMapUv = ( normalMapTransform * vec3( NORMALMAP_UV, 1 ) ).xy; #endif #ifdef USE_DISPLACEMENTMAP vDisplacementMapUv = ( displacementMapTransform * vec3( DISPLACEMENTMAP_UV, 1 ) ).xy; #endif #ifdef USE_EMISSIVEMAP vEmissiveMapUv = ( emissiveMapTransform * vec3( EMISSIVEMAP_UV, 1 ) ).xy; #endif #ifdef USE_METALNESSMAP vMetalnessMapUv = ( metalnessMapTransform * vec3( METALNESSMAP_UV, 1 ) ).xy; #endif #ifdef USE_ROUGHNESSMAP vRoughnessMapUv = ( roughnessMapTransform * vec3( ROUGHNESSMAP_UV, 1 ) ).xy; #endif #ifdef USE_ANISOTROPYMAP vAnisotropyMapUv = ( anisotropyMapTransform * vec3( ANISOTROPYMAP_UV, 1 ) ).xy; #endif #ifdef USE_CLEARCOATMAP vClearcoatMapUv = ( clearcoatMapTransform * vec3( CLEARCOATMAP_UV, 1 ) ).xy; #endif #ifdef USE_CLEARCOAT_NORMALMAP vClearcoatNormalMapUv = ( clearcoatNormalMapTransform * vec3( CLEARCOAT_NORMALMAP_UV, 1 ) ).xy; #endif #ifdef USE_CLEARCOAT_ROUGHNESSMAP vClearcoatRoughnessMapUv = ( clearcoatRoughnessMapTransform * vec3( CLEARCOAT_ROUGHNESSMAP_UV, 1 ) ).xy; #endif #ifdef USE_IRIDESCENCEMAP vIridescenceMapUv = ( iridescenceMapTransform * vec3( IRIDESCENCEMAP_UV, 1 ) ).xy; #endif #ifdef USE_IRIDESCENCE_THICKNESSMAP vIridescenceThicknessMapUv = ( iridescenceThicknessMapTransform * vec3( IRIDESCENCE_THICKNESSMAP_UV, 1 ) ).xy; #endif #ifdef USE_SHEEN_COLORMAP vSheenColorMapUv = ( sheenColorMapTransform * vec3( SHEEN_COLORMAP_UV, 1 ) ).xy; #endif #ifdef USE_SHEEN_ROUGHNESSMAP vSheenRoughnessMapUv = ( sheenRoughnessMapTransform * vec3( SHEEN_ROUGHNESSMAP_UV, 1 ) ).xy; #endif #ifdef USE_SPECULARMAP vSpecularMapUv = ( specularMapTransform * vec3( SPECULARMAP_UV, 1 ) ).xy; #endif #ifdef USE_SPECULAR_COLORMAP vSpecularColorMapUv = ( specularColorMapTransform * vec3( SPECULAR_COLORMAP_UV, 1 ) ).xy; #endif #ifdef USE_SPECULAR_INTENSITYMAP vSpecularIntensityMapUv = ( specularIntensityMapTransform * vec3( SPECULAR_INTENSITYMAP_UV, 1 ) ).xy; #endif #ifdef USE_TRANSMISSIONMAP vTransmissionMapUv = ( transmissionMapTransform * vec3( TRANSMISSIONMAP_UV, 1 ) ).xy; #endif #ifdef USE_THICKNESSMAP vThicknessMapUv = ( thicknessMapTransform * vec3( THICKNESSMAP_UV, 1 ) ).xy; #endif`,_D=`#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP ) || defined ( USE_TRANSMISSION ) || NUM_SPOT_LIGHT_COORDS > 0 vec4 worldPosition = vec4( transformed, 1.0 ); #ifdef USE_BATCHING worldPosition = batchingMatrix * worldPosition; #endif #ifdef USE_INSTANCING worldPosition = instanceMatrix * worldPosition; #endif worldPosition = modelMatrix * worldPosition; #endif`;const bD=`varying vec2 vUv; uniform mat3 uvTransform; void main() { vUv = ( uvTransform * vec3( uv, 1 ) ).xy; gl_Position = vec4( position.xy, 1.0, 1.0 ); }`,MD=`uniform sampler2D t2D; uniform float backgroundIntensity; varying vec2 vUv; void main() { vec4 texColor = texture2D( t2D, vUv ); #ifdef DECODE_VIDEO_TEXTURE texColor = vec4( mix( pow( texColor.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), texColor.rgb * 0.0773993808, vec3( lessThanEqual( texColor.rgb, vec3( 0.04045 ) ) ) ), texColor.w ); #endif texColor.rgb *= backgroundIntensity; gl_FragColor = texColor; #include #include }`,SD=`varying vec3 vWorldDirection; #include void main() { vWorldDirection = transformDirection( position, modelMatrix ); #include #include gl_Position.z = gl_Position.w; }`,wD=`#ifdef ENVMAP_TYPE_CUBE uniform samplerCube envMap; #elif defined( ENVMAP_TYPE_CUBE_UV ) uniform sampler2D envMap; #endif uniform float flipEnvMap; uniform float backgroundBlurriness; uniform float backgroundIntensity; uniform mat3 backgroundRotation; varying vec3 vWorldDirection; #include void main() { #ifdef ENVMAP_TYPE_CUBE vec4 texColor = textureCube( envMap, backgroundRotation * vec3( flipEnvMap * vWorldDirection.x, vWorldDirection.yz ) ); #elif defined( ENVMAP_TYPE_CUBE_UV ) vec4 texColor = textureCubeUV( envMap, backgroundRotation * vWorldDirection, backgroundBlurriness ); #else vec4 texColor = vec4( 0.0, 0.0, 0.0, 1.0 ); #endif texColor.rgb *= backgroundIntensity; gl_FragColor = texColor; #include #include }`,ED=`varying vec3 vWorldDirection; #include void main() { vWorldDirection = transformDirection( position, modelMatrix ); #include #include gl_Position.z = gl_Position.w; }`,TD=`uniform samplerCube tCube; uniform float tFlip; uniform float opacity; varying vec3 vWorldDirection; void main() { vec4 texColor = textureCube( tCube, vec3( tFlip * vWorldDirection.x, vWorldDirection.yz ) ); gl_FragColor = texColor; gl_FragColor.a *= opacity; #include #include }`,CD=`#include #include #include #include #include #include #include #include varying vec2 vHighPrecisionZW; void main() { #include #include #include #include #ifdef USE_DISPLACEMENTMAP #include #include #include #endif #include #include #include #include #include #include #include vHighPrecisionZW = gl_Position.zw; }`,AD=`#if DEPTH_PACKING == 3200 uniform float opacity; #endif #include #include #include #include #include #include #include #include #include varying vec2 vHighPrecisionZW; void main() { vec4 diffuseColor = vec4( 1.0 ); #include #if DEPTH_PACKING == 3200 diffuseColor.a = opacity; #endif #include #include #include #include #include #ifdef USE_REVERSED_DEPTH_BUFFER float fragCoordZ = vHighPrecisionZW[ 0 ] / vHighPrecisionZW[ 1 ]; #else float fragCoordZ = 0.5 * vHighPrecisionZW[ 0 ] / vHighPrecisionZW[ 1 ] + 0.5; #endif #if DEPTH_PACKING == 3200 gl_FragColor = vec4( vec3( 1.0 - fragCoordZ ), opacity ); #elif DEPTH_PACKING == 3201 gl_FragColor = packDepthToRGBA( fragCoordZ ); #elif DEPTH_PACKING == 3202 gl_FragColor = vec4( packDepthToRGB( fragCoordZ ), 1.0 ); #elif DEPTH_PACKING == 3203 gl_FragColor = vec4( packDepthToRG( fragCoordZ ), 0.0, 1.0 ); #endif }`,PD=`#define DISTANCE varying vec3 vWorldPosition; #include #include #include #include #include #include #include void main() { #include #include #include #include #ifdef USE_DISPLACEMENTMAP #include #include #include #endif #include #include #include #include #include #include #include vWorldPosition = worldPosition.xyz; }`,RD=`#define DISTANCE uniform vec3 referencePosition; uniform float nearDistance; uniform float farDistance; varying vec3 vWorldPosition; #include #include #include #include #include #include #include #include void main () { vec4 diffuseColor = vec4( 1.0 ); #include #include #include #include #include float dist = length( vWorldPosition - referencePosition ); dist = ( dist - nearDistance ) / ( farDistance - nearDistance ); dist = saturate( dist ); gl_FragColor = packDepthToRGBA( dist ); }`,ID=`varying vec3 vWorldDirection; #include void main() { vWorldDirection = transformDirection( position, modelMatrix ); #include #include }`,LD=`uniform sampler2D tEquirect; varying vec3 vWorldDirection; #include void main() { vec3 direction = normalize( vWorldDirection ); vec2 sampleUV = equirectUv( direction ); gl_FragColor = texture2D( tEquirect, sampleUV ); #include #include }`,DD=`uniform float scale; attribute float lineDistance; varying float vLineDistance; #include #include #include #include #include #include #include void main() { vLineDistance = scale * lineDistance; #include #include #include #include #include #include #include #include #include #include }`,ND=`uniform vec3 diffuse; uniform float opacity; uniform float dashSize; uniform float totalSize; varying float vLineDistance; #include #include #include #include #include #include #include void main() { vec4 diffuseColor = vec4( diffuse, opacity ); #include if ( mod( vLineDistance, totalSize ) > dashSize ) { discard; } vec3 outgoingLight = vec3( 0.0 ); #include #include #include outgoingLight = diffuseColor.rgb; #include #include #include #include #include }`,kD=`#include #include #include #include #include #include #include #include #include #include void main() { #include #include #include #include #include #if defined ( USE_ENVMAP ) || defined ( USE_SKINNING ) #include #include #include #include #include #endif #include #include #include #include #include #include #include #include #include }`,OD=`uniform vec3 diffuse; uniform float opacity; #ifndef FLAT_SHADED varying vec3 vNormal; #endif #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include void main() { vec4 diffuseColor = vec4( diffuse, opacity ); #include #include #include #include #include #include #include #include ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); #ifdef USE_LIGHTMAP vec4 lightMapTexel = texture2D( lightMap, vLightMapUv ); reflectedLight.indirectDiffuse += lightMapTexel.rgb * lightMapIntensity * RECIPROCAL_PI; #else reflectedLight.indirectDiffuse += vec3( 1.0 ); #endif #include reflectedLight.indirectDiffuse *= diffuseColor.rgb; vec3 outgoingLight = reflectedLight.indirectDiffuse; #include #include #include #include #include #include #include }`,UD=`#define LAMBERT varying vec3 vViewPosition; #include #include #include #include #include #include #include #include #include #include #include #include #include void main() { #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include vViewPosition = - mvPosition.xyz; #include #include #include #include }`,BD=`#define LAMBERT uniform vec3 diffuse; uniform vec3 emissive; uniform float opacity; #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include void main() { vec4 diffuseColor = vec4( diffuse, opacity ); #include ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); vec3 totalEmissiveRadiance = emissive; #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance; #include #include #include #include #include #include #include }`,FD=`#define MATCAP varying vec3 vViewPosition; #include #include #include #include #include #include #include #include #include #include #include void main() { #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include vViewPosition = - mvPosition.xyz; }`,zD=`#define MATCAP uniform vec3 diffuse; uniform float opacity; uniform sampler2D matcap; varying vec3 vViewPosition; #include #include #include #include #include #include #include #include #include #include #include #include #include #include void main() { vec4 diffuseColor = vec4( diffuse, opacity ); #include #include #include #include #include #include #include #include #include vec3 viewDir = normalize( vViewPosition ); vec3 x = normalize( vec3( viewDir.z, 0.0, - viewDir.x ) ); vec3 y = cross( viewDir, x ); vec2 uv = vec2( dot( x, normal ), dot( y, normal ) ) * 0.495 + 0.5; #ifdef USE_MATCAP vec4 matcapColor = texture2D( matcap, uv ); #else vec4 matcapColor = vec4( vec3( mix( 0.2, 0.8, uv.y ) ), 1.0 ); #endif vec3 outgoingLight = diffuseColor.rgb * matcapColor.rgb; #include #include #include #include #include #include }`,HD=`#define NORMAL #if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE ) varying vec3 vViewPosition; #endif #include #include #include #include #include #include #include #include #include void main() { #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE ) vViewPosition = - mvPosition.xyz; #endif }`,VD=`#define NORMAL uniform float opacity; #if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE ) varying vec3 vViewPosition; #endif #include #include #include #include #include #include #include void main() { vec4 diffuseColor = vec4( 0.0, 0.0, 0.0, opacity ); #include #include #include #include gl_FragColor = vec4( packNormalToRGB( normal ), diffuseColor.a ); #ifdef OPAQUE gl_FragColor.a = 1.0; #endif }`,GD=`#define PHONG varying vec3 vViewPosition; #include #include #include #include #include #include #include #include #include #include #include #include #include void main() { #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include vViewPosition = - mvPosition.xyz; #include #include #include #include }`,WD=`#define PHONG uniform vec3 diffuse; uniform vec3 emissive; uniform vec3 specular; uniform float shininess; uniform float opacity; #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include void main() { vec4 diffuseColor = vec4( diffuse, opacity ); #include ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); vec3 totalEmissiveRadiance = emissive; #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance; #include #include #include #include #include #include #include }`,XD=`#define STANDARD varying vec3 vViewPosition; #ifdef USE_TRANSMISSION varying vec3 vWorldPosition; #endif #include #include #include #include #include #include #include #include #include #include #include #include void main() { #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include vViewPosition = - mvPosition.xyz; #include #include #include #ifdef USE_TRANSMISSION vWorldPosition = worldPosition.xyz; #endif }`,jD=`#define STANDARD #ifdef PHYSICAL #define IOR #define USE_SPECULAR #endif uniform vec3 diffuse; uniform vec3 emissive; uniform float roughness; uniform float metalness; uniform float opacity; #ifdef IOR uniform float ior; #endif #ifdef USE_SPECULAR uniform float specularIntensity; uniform vec3 specularColor; #ifdef USE_SPECULAR_COLORMAP uniform sampler2D specularColorMap; #endif #ifdef USE_SPECULAR_INTENSITYMAP uniform sampler2D specularIntensityMap; #endif #endif #ifdef USE_CLEARCOAT uniform float clearcoat; uniform float clearcoatRoughness; #endif #ifdef USE_DISPERSION uniform float dispersion; #endif #ifdef USE_IRIDESCENCE uniform float iridescence; uniform float iridescenceIOR; uniform float iridescenceThicknessMinimum; uniform float iridescenceThicknessMaximum; #endif #ifdef USE_SHEEN uniform vec3 sheenColor; uniform float sheenRoughness; #ifdef USE_SHEEN_COLORMAP uniform sampler2D sheenColorMap; #endif #ifdef USE_SHEEN_ROUGHNESSMAP uniform sampler2D sheenRoughnessMap; #endif #endif #ifdef USE_ANISOTROPY uniform vec2 anisotropyVector; #ifdef USE_ANISOTROPYMAP uniform sampler2D anisotropyMap; #endif #endif varying vec3 vViewPosition; #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include void main() { vec4 diffuseColor = vec4( diffuse, opacity ); #include ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); vec3 totalEmissiveRadiance = emissive; #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include vec3 totalDiffuse = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse; vec3 totalSpecular = reflectedLight.directSpecular + reflectedLight.indirectSpecular; #include vec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance; #ifdef USE_SHEEN float sheenEnergyComp = 1.0 - 0.157 * max3( material.sheenColor ); outgoingLight = outgoingLight * sheenEnergyComp + sheenSpecularDirect + sheenSpecularIndirect; #endif #ifdef USE_CLEARCOAT float dotNVcc = saturate( dot( geometryClearcoatNormal, geometryViewDir ) ); vec3 Fcc = F_Schlick( material.clearcoatF0, material.clearcoatF90, dotNVcc ); outgoingLight = outgoingLight * ( 1.0 - material.clearcoat * Fcc ) + ( clearcoatSpecularDirect + clearcoatSpecularIndirect ) * material.clearcoat; #endif #include #include #include #include #include #include }`,qD=`#define TOON varying vec3 vViewPosition; #include #include #include #include #include #include #include #include #include #include #include #include void main() { #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include vViewPosition = - mvPosition.xyz; #include #include #include }`,ZD=`#define TOON uniform vec3 diffuse; uniform vec3 emissive; uniform float opacity; #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include void main() { vec4 diffuseColor = vec4( diffuse, opacity ); #include ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); vec3 totalEmissiveRadiance = emissive; #include #include #include #include #include #include #include #include #include #include #include #include #include #include vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance; #include #include #include #include #include #include }`,YD=`uniform float size; uniform float scale; #include #include #include #include #include #include #ifdef USE_POINTS_UV varying vec2 vUv; uniform mat3 uvTransform; #endif void main() { #ifdef USE_POINTS_UV vUv = ( uvTransform * vec3( uv, 1 ) ).xy; #endif #include #include #include #include #include #include gl_PointSize = size; #ifdef USE_SIZEATTENUATION bool isPerspective = isPerspectiveMatrix( projectionMatrix ); if ( isPerspective ) gl_PointSize *= ( scale / - mvPosition.z ); #endif #include #include #include #include }`,$D=`uniform vec3 diffuse; uniform float opacity; #include #include #include #include #include #include #include #include void main() { vec4 diffuseColor = vec4( diffuse, opacity ); #include vec3 outgoingLight = vec3( 0.0 ); #include #include #include #include #include outgoingLight = diffuseColor.rgb; #include #include #include #include #include }`,KD=`#include #include #include #include #include #include #include void main() { #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include }`,JD=`uniform vec3 color; uniform float opacity; #include #include #include #include #include #include #include #include void main() { #include gl_FragColor = vec4( color, opacity * ( 1.0 - getShadowMask() ) ); #include #include #include }`,QD=`uniform float rotation; uniform vec2 center; #include #include #include #include #include void main() { #include vec4 mvPosition = modelViewMatrix[ 3 ]; vec2 scale = vec2( length( modelMatrix[ 0 ].xyz ), length( modelMatrix[ 1 ].xyz ) ); #ifndef USE_SIZEATTENUATION bool isPerspective = isPerspectiveMatrix( projectionMatrix ); if ( isPerspective ) scale *= - mvPosition.z; #endif vec2 alignedPosition = ( position.xy - ( center - vec2( 0.5 ) ) ) * scale; vec2 rotatedPosition; rotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y; rotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y; mvPosition.xy += rotatedPosition; gl_Position = projectionMatrix * mvPosition; #include #include #include }`,e6=`uniform vec3 diffuse; uniform float opacity; #include #include #include #include #include #include #include #include #include void main() { vec4 diffuseColor = vec4( diffuse, opacity ); #include vec3 outgoingLight = vec3( 0.0 ); #include #include #include #include #include outgoingLight = diffuseColor.rgb; #include #include #include #include }`,wt={alphahash_fragment:MI,alphahash_pars_fragment:SI,alphamap_fragment:wI,alphamap_pars_fragment:EI,alphatest_fragment:TI,alphatest_pars_fragment:CI,aomap_fragment:AI,aomap_pars_fragment:PI,batching_pars_vertex:RI,batching_vertex:II,begin_vertex:LI,beginnormal_vertex:DI,bsdfs:NI,iridescence_fragment:kI,bumpmap_pars_fragment:OI,clipping_planes_fragment:UI,clipping_planes_pars_fragment:BI,clipping_planes_pars_vertex:FI,clipping_planes_vertex:zI,color_fragment:HI,color_pars_fragment:VI,color_pars_vertex:GI,color_vertex:WI,common:XI,cube_uv_reflection_fragment:jI,defaultnormal_vertex:qI,displacementmap_pars_vertex:ZI,displacementmap_vertex:YI,emissivemap_fragment:$I,emissivemap_pars_fragment:KI,colorspace_fragment:JI,colorspace_pars_fragment:QI,envmap_fragment:eL,envmap_common_pars_fragment:tL,envmap_pars_fragment:iL,envmap_pars_vertex:nL,envmap_physical_pars_fragment:fL,envmap_vertex:sL,fog_vertex:rL,fog_pars_vertex:aL,fog_fragment:oL,fog_pars_fragment:lL,gradientmap_pars_fragment:cL,lightmap_pars_fragment:hL,lights_lambert_fragment:dL,lights_lambert_pars_fragment:uL,lights_pars_begin:pL,lights_toon_fragment:mL,lights_toon_pars_fragment:gL,lights_phong_fragment:vL,lights_phong_pars_fragment:yL,lights_physical_fragment:xL,lights_physical_pars_fragment:_L,lights_fragment_begin:bL,lights_fragment_maps:ML,lights_fragment_end:SL,logdepthbuf_fragment:wL,logdepthbuf_pars_fragment:EL,logdepthbuf_pars_vertex:TL,logdepthbuf_vertex:CL,map_fragment:AL,map_pars_fragment:PL,map_particle_fragment:RL,map_particle_pars_fragment:IL,metalnessmap_fragment:LL,metalnessmap_pars_fragment:DL,morphinstance_vertex:NL,morphcolor_vertex:kL,morphnormal_vertex:OL,morphtarget_pars_vertex:UL,morphtarget_vertex:BL,normal_fragment_begin:FL,normal_fragment_maps:zL,normal_pars_fragment:HL,normal_pars_vertex:VL,normal_vertex:GL,normalmap_pars_fragment:WL,clearcoat_normal_fragment_begin:XL,clearcoat_normal_fragment_maps:jL,clearcoat_pars_fragment:qL,iridescence_pars_fragment:ZL,opaque_fragment:YL,packing:$L,premultiplied_alpha_fragment:KL,project_vertex:JL,dithering_fragment:QL,dithering_pars_fragment:eD,roughnessmap_fragment:tD,roughnessmap_pars_fragment:iD,shadowmap_pars_fragment:nD,shadowmap_pars_vertex:sD,shadowmap_vertex:rD,shadowmask_pars_fragment:aD,skinbase_vertex:oD,skinning_pars_vertex:lD,skinning_vertex:cD,skinnormal_vertex:hD,specularmap_fragment:dD,specularmap_pars_fragment:uD,tonemapping_fragment:pD,tonemapping_pars_fragment:fD,transmission_fragment:mD,transmission_pars_fragment:gD,uv_pars_fragment:vD,uv_pars_vertex:yD,uv_vertex:xD,worldpos_vertex:_D,background_vert:bD,background_frag:MD,backgroundCube_vert:SD,backgroundCube_frag:wD,cube_vert:ED,cube_frag:TD,depth_vert:CD,depth_frag:AD,distanceRGBA_vert:PD,distanceRGBA_frag:RD,equirect_vert:ID,equirect_frag:LD,linedashed_vert:DD,linedashed_frag:ND,meshbasic_vert:kD,meshbasic_frag:OD,meshlambert_vert:UD,meshlambert_frag:BD,meshmatcap_vert:FD,meshmatcap_frag:zD,meshnormal_vert:HD,meshnormal_frag:VD,meshphong_vert:GD,meshphong_frag:WD,meshphysical_vert:XD,meshphysical_frag:jD,meshtoon_vert:qD,meshtoon_frag:ZD,points_vert:YD,points_frag:$D,shadow_vert:KD,shadow_frag:JD,sprite_vert:QD,sprite_frag:e6},Je={common:{diffuse:{value:new Wt(16777215)},opacity:{value:1},map:{value:null},mapTransform:{value:new Mt},alphaMap:{value:null},alphaMapTransform:{value:new Mt},alphaTest:{value:0}},specularmap:{specularMap:{value:null},specularMapTransform:{value:new Mt}},envmap:{envMap:{value:null},envMapRotation:{value:new Mt},flipEnvMap:{value:-1},reflectivity:{value:1},ior:{value:1.5},refractionRatio:{value:.98},dfgLUT:{value:null}},aomap:{aoMap:{value:null},aoMapIntensity:{value:1},aoMapTransform:{value:new Mt}},lightmap:{lightMap:{value:null},lightMapIntensity:{value:1},lightMapTransform:{value:new Mt}},bumpmap:{bumpMap:{value:null},bumpMapTransform:{value:new Mt},bumpScale:{value:1}},normalmap:{normalMap:{value:null},normalMapTransform:{value:new Mt},normalScale:{value:new Gt(1,1)}},displacementmap:{displacementMap:{value:null},displacementMapTransform:{value:new Mt},displacementScale:{value:1},displacementBias:{value:0}},emissivemap:{emissiveMap:{value:null},emissiveMapTransform:{value:new Mt}},metalnessmap:{metalnessMap:{value:null},metalnessMapTransform:{value:new Mt}},roughnessmap:{roughnessMap:{value:null},roughnessMapTransform:{value:new Mt}},gradientmap:{gradientMap:{value:null}},fog:{fogDensity:{value:25e-5},fogNear:{value:1},fogFar:{value:2e3},fogColor:{value:new Wt(16777215)}},lights:{ambientLightColor:{value:[]},lightProbe:{value:[]},directionalLights:{value:[],properties:{direction:{},color:{}}},directionalLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},directionalShadowMap:{value:[]},directionalShadowMatrix:{value:[]},spotLights:{value:[],properties:{color:{},position:{},direction:{},distance:{},coneCos:{},penumbraCos:{},decay:{}}},spotLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},spotLightMap:{value:[]},spotShadowMap:{value:[]},spotLightMatrix:{value:[]},pointLights:{value:[],properties:{color:{},position:{},decay:{},distance:{}}},pointLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{},shadowCameraNear:{},shadowCameraFar:{}}},pointShadowMap:{value:[]},pointShadowMatrix:{value:[]},hemisphereLights:{value:[],properties:{direction:{},skyColor:{},groundColor:{}}},rectAreaLights:{value:[],properties:{color:{},position:{},width:{},height:{}}},ltc_1:{value:null},ltc_2:{value:null}},points:{diffuse:{value:new Wt(16777215)},opacity:{value:1},size:{value:1},scale:{value:1},map:{value:null},alphaMap:{value:null},alphaMapTransform:{value:new Mt},alphaTest:{value:0},uvTransform:{value:new Mt}},sprite:{diffuse:{value:new Wt(16777215)},opacity:{value:1},center:{value:new Gt(.5,.5)},rotation:{value:0},map:{value:null},mapTransform:{value:new Mt},alphaMap:{value:null},alphaMapTransform:{value:new Mt},alphaTest:{value:0}}},Gs={basic:{uniforms:gn([Je.common,Je.specularmap,Je.envmap,Je.aomap,Je.lightmap,Je.fog]),vertexShader:wt.meshbasic_vert,fragmentShader:wt.meshbasic_frag},lambert:{uniforms:gn([Je.common,Je.specularmap,Je.envmap,Je.aomap,Je.lightmap,Je.emissivemap,Je.bumpmap,Je.normalmap,Je.displacementmap,Je.fog,Je.lights,{emissive:{value:new Wt(0)}}]),vertexShader:wt.meshlambert_vert,fragmentShader:wt.meshlambert_frag},phong:{uniforms:gn([Je.common,Je.specularmap,Je.envmap,Je.aomap,Je.lightmap,Je.emissivemap,Je.bumpmap,Je.normalmap,Je.displacementmap,Je.fog,Je.lights,{emissive:{value:new Wt(0)},specular:{value:new Wt(1118481)},shininess:{value:30}}]),vertexShader:wt.meshphong_vert,fragmentShader:wt.meshphong_frag},standard:{uniforms:gn([Je.common,Je.envmap,Je.aomap,Je.lightmap,Je.emissivemap,Je.bumpmap,Je.normalmap,Je.displacementmap,Je.roughnessmap,Je.metalnessmap,Je.fog,Je.lights,{emissive:{value:new Wt(0)},roughness:{value:1},metalness:{value:0},envMapIntensity:{value:1}}]),vertexShader:wt.meshphysical_vert,fragmentShader:wt.meshphysical_frag},toon:{uniforms:gn([Je.common,Je.aomap,Je.lightmap,Je.emissivemap,Je.bumpmap,Je.normalmap,Je.displacementmap,Je.gradientmap,Je.fog,Je.lights,{emissive:{value:new Wt(0)}}]),vertexShader:wt.meshtoon_vert,fragmentShader:wt.meshtoon_frag},matcap:{uniforms:gn([Je.common,Je.bumpmap,Je.normalmap,Je.displacementmap,Je.fog,{matcap:{value:null}}]),vertexShader:wt.meshmatcap_vert,fragmentShader:wt.meshmatcap_frag},points:{uniforms:gn([Je.points,Je.fog]),vertexShader:wt.points_vert,fragmentShader:wt.points_frag},dashed:{uniforms:gn([Je.common,Je.fog,{scale:{value:1},dashSize:{value:1},totalSize:{value:2}}]),vertexShader:wt.linedashed_vert,fragmentShader:wt.linedashed_frag},depth:{uniforms:gn([Je.common,Je.displacementmap]),vertexShader:wt.depth_vert,fragmentShader:wt.depth_frag},normal:{uniforms:gn([Je.common,Je.bumpmap,Je.normalmap,Je.displacementmap,{opacity:{value:1}}]),vertexShader:wt.meshnormal_vert,fragmentShader:wt.meshnormal_frag},sprite:{uniforms:gn([Je.sprite,Je.fog]),vertexShader:wt.sprite_vert,fragmentShader:wt.sprite_frag},background:{uniforms:{uvTransform:{value:new Mt},t2D:{value:null},backgroundIntensity:{value:1}},vertexShader:wt.background_vert,fragmentShader:wt.background_frag},backgroundCube:{uniforms:{envMap:{value:null},flipEnvMap:{value:-1},backgroundBlurriness:{value:0},backgroundIntensity:{value:1},backgroundRotation:{value:new Mt}},vertexShader:wt.backgroundCube_vert,fragmentShader:wt.backgroundCube_frag},cube:{uniforms:{tCube:{value:null},tFlip:{value:-1},opacity:{value:1}},vertexShader:wt.cube_vert,fragmentShader:wt.cube_frag},equirect:{uniforms:{tEquirect:{value:null}},vertexShader:wt.equirect_vert,fragmentShader:wt.equirect_frag},distanceRGBA:{uniforms:gn([Je.common,Je.displacementmap,{referencePosition:{value:new De},nearDistance:{value:1},farDistance:{value:1e3}}]),vertexShader:wt.distanceRGBA_vert,fragmentShader:wt.distanceRGBA_frag},shadow:{uniforms:gn([Je.lights,Je.fog,{color:{value:new Wt(0)},opacity:{value:1}}]),vertexShader:wt.shadow_vert,fragmentShader:wt.shadow_frag}};Gs.physical={uniforms:gn([Gs.standard.uniforms,{clearcoat:{value:0},clearcoatMap:{value:null},clearcoatMapTransform:{value:new Mt},clearcoatNormalMap:{value:null},clearcoatNormalMapTransform:{value:new Mt},clearcoatNormalScale:{value:new Gt(1,1)},clearcoatRoughness:{value:0},clearcoatRoughnessMap:{value:null},clearcoatRoughnessMapTransform:{value:new Mt},dispersion:{value:0},iridescence:{value:0},iridescenceMap:{value:null},iridescenceMapTransform:{value:new Mt},iridescenceIOR:{value:1.3},iridescenceThicknessMinimum:{value:100},iridescenceThicknessMaximum:{value:400},iridescenceThicknessMap:{value:null},iridescenceThicknessMapTransform:{value:new Mt},sheen:{value:0},sheenColor:{value:new Wt(0)},sheenColorMap:{value:null},sheenColorMapTransform:{value:new Mt},sheenRoughness:{value:1},sheenRoughnessMap:{value:null},sheenRoughnessMapTransform:{value:new Mt},transmission:{value:0},transmissionMap:{value:null},transmissionMapTransform:{value:new Mt},transmissionSamplerSize:{value:new Gt},transmissionSamplerMap:{value:null},thickness:{value:0},thicknessMap:{value:null},thicknessMapTransform:{value:new Mt},attenuationDistance:{value:0},attenuationColor:{value:new Wt(0)},specularColor:{value:new Wt(1,1,1)},specularColorMap:{value:null},specularColorMapTransform:{value:new Mt},specularIntensity:{value:1},specularIntensityMap:{value:null},specularIntensityMapTransform:{value:new Mt},anisotropyVector:{value:new Gt},anisotropyMap:{value:null},anisotropyMapTransform:{value:new Mt}}]),vertexShader:wt.meshphysical_vert,fragmentShader:wt.meshphysical_frag};const mf={r:0,b:0,g:0},mo=new co,t6=new Di;function i6(s,e,t,i,n,r,a){const o=new Wt(0);let l=r===!0?0:1,c,h,d=null,p=0,u=null;function v(x){let _=x.isScene===!0?x.background:null;return _&&_.isTexture&&(_=(x.backgroundBlurriness>0?t:e).get(_)),_}function g(x){let _=!1;const S=v(x);S===null?f(o,l):S&&S.isColor&&(f(S,1),_=!0);const b=s.xr.getEnvironmentBlendMode();b==="additive"?i.buffers.color.setClear(0,0,0,1,a):b==="alpha-blend"&&i.buffers.color.setClear(0,0,0,0,a),(s.autoClear||_)&&(i.buffers.depth.setTest(!0),i.buffers.depth.setMask(!0),i.buffers.color.setMask(!0),s.clear(s.autoClearColor,s.autoClearDepth,s.autoClearStencil))}function m(x,_){const S=v(_);S&&(S.isCubeTexture||S.mapping===Fp)?(h===void 0&&(h=new la(new Ph(1,1,1),new yr({name:"BackgroundCubeMaterial",uniforms:jl(Gs.backgroundCube.uniforms),vertexShader:Gs.backgroundCube.vertexShader,fragmentShader:Gs.backgroundCube.fragmentShader,side:En,depthTest:!1,depthWrite:!1,fog:!1,allowOverride:!1})),h.geometry.deleteAttribute("normal"),h.geometry.deleteAttribute("uv"),h.onBeforeRender=function(b,E,w){this.matrixWorld.copyPosition(w.matrixWorld)},Object.defineProperty(h.material,"envMap",{get:function(){return this.uniforms.envMap.value}}),n.update(h)),mo.copy(_.backgroundRotation),mo.x*=-1,mo.y*=-1,mo.z*=-1,S.isCubeTexture&&S.isRenderTargetTexture===!1&&(mo.y*=-1,mo.z*=-1),h.material.uniforms.envMap.value=S,h.material.uniforms.flipEnvMap.value=S.isCubeTexture&&S.isRenderTargetTexture===!1?-1:1,h.material.uniforms.backgroundBlurriness.value=_.backgroundBlurriness,h.material.uniforms.backgroundIntensity.value=_.backgroundIntensity,h.material.uniforms.backgroundRotation.value.setFromMatrix4(t6.makeRotationFromEuler(mo)),h.material.toneMapped=Ut.getTransfer(S.colorSpace)!==Vt,(d!==S||p!==S.version||u!==s.toneMapping)&&(h.material.needsUpdate=!0,d=S,p=S.version,u=s.toneMapping),h.layers.enableAll(),x.unshift(h,h.geometry,h.material,0,0,null)):S&&S.isTexture&&(c===void 0&&(c=new la(new ff(2,2),new yr({name:"BackgroundMaterial",uniforms:jl(Gs.background.uniforms),vertexShader:Gs.background.vertexShader,fragmentShader:Gs.background.fragmentShader,side:Qr,depthTest:!1,depthWrite:!1,fog:!1,allowOverride:!1})),c.geometry.deleteAttribute("normal"),Object.defineProperty(c.material,"map",{get:function(){return this.uniforms.t2D.value}}),n.update(c)),c.material.uniforms.t2D.value=S,c.material.uniforms.backgroundIntensity.value=_.backgroundIntensity,c.material.toneMapped=Ut.getTransfer(S.colorSpace)!==Vt,S.matrixAutoUpdate===!0&&S.updateMatrix(),c.material.uniforms.uvTransform.value.copy(S.matrix),(d!==S||p!==S.version||u!==s.toneMapping)&&(c.material.needsUpdate=!0,d=S,p=S.version,u=s.toneMapping),c.layers.enableAll(),x.unshift(c,c.geometry,c.material,0,0,null))}function f(x,_){x.getRGB(mf,mM(s)),i.buffers.color.setClear(mf.r,mf.g,mf.b,_,a)}function y(){h!==void 0&&(h.geometry.dispose(),h.material.dispose(),h=void 0),c!==void 0&&(c.geometry.dispose(),c.material.dispose(),c=void 0)}return{getClearColor:function(){return o},setClearColor:function(x,_=1){o.set(x),l=_,f(o,l)},getClearAlpha:function(){return l},setClearAlpha:function(x){l=x,f(o,l)},render:g,addToRenderList:m,dispose:y}}function n6(s,e){const t=s.getParameter(s.MAX_VERTEX_ATTRIBS),i={},n=p(null);let r=n,a=!1;function o(C,I,P,k,A){let B=!1;const F=d(k,P,I);r!==F&&(r=F,c(r.object)),B=u(C,k,P,A),B&&v(C,k,P,A),A!==null&&e.update(A,s.ELEMENT_ARRAY_BUFFER),(B||a)&&(a=!1,_(C,I,P,k),A!==null&&s.bindBuffer(s.ELEMENT_ARRAY_BUFFER,e.get(A).buffer))}function l(){return s.createVertexArray()}function c(C){return s.bindVertexArray(C)}function h(C){return s.deleteVertexArray(C)}function d(C,I,P){const k=P.wireframe===!0;let A=i[C.id];A===void 0&&(A={},i[C.id]=A);let B=A[I.id];B===void 0&&(B={},A[I.id]=B);let F=B[k];return F===void 0&&(F=p(l()),B[k]=F),F}function p(C){const I=[],P=[],k=[];for(let A=0;A=0){const G=A[q];let re=B[q];if(re===void 0&&(q==="instanceMatrix"&&C.instanceMatrix&&(re=C.instanceMatrix),q==="instanceColor"&&C.instanceColor&&(re=C.instanceColor)),G===void 0||G.attribute!==re||re&&G.data!==re.data)return!0;F++}return r.attributesNum!==F||r.index!==k}function v(C,I,P,k){const A={},B=I.attributes;let F=0;const H=P.getAttributes();for(const q in H)if(H[q].location>=0){let G=B[q];G===void 0&&(q==="instanceMatrix"&&C.instanceMatrix&&(G=C.instanceMatrix),q==="instanceColor"&&C.instanceColor&&(G=C.instanceColor));const re={};re.attribute=G,G&&G.data&&(re.data=G.data),A[q]=re,F++}r.attributes=A,r.attributesNum=F,r.index=k}function g(){const C=r.newAttributes;for(let I=0,P=C.length;I=0){let G=A[H];if(G===void 0&&(H==="instanceMatrix"&&C.instanceMatrix&&(G=C.instanceMatrix),H==="instanceColor"&&C.instanceColor&&(G=C.instanceColor)),G!==void 0){const re=G.normalized,Y=G.itemSize,$=e.get(G);if($===void 0)continue;const _e=$.buffer,Te=$.type,be=$.bytesPerElement,J=Te===s.INT||Te===s.UNSIGNED_INT||G.gpuType===N0;if(G.isInterleavedBufferAttribute){const oe=G.data,ue=oe.stride,Re=G.offset;if(oe.isInstancedInterleavedBuffer){for(let Ie=0;Ie0&&s.getShaderPrecisionFormat(s.FRAGMENT_SHADER,s.HIGH_FLOAT).precision>0)return"highp";E="mediump"}return E==="mediump"&&s.getShaderPrecisionFormat(s.VERTEX_SHADER,s.MEDIUM_FLOAT).precision>0&&s.getShaderPrecisionFormat(s.FRAGMENT_SHADER,s.MEDIUM_FLOAT).precision>0?"mediump":"lowp"}let c=t.precision!==void 0?t.precision:"highp";const h=l(c);h!==c&&(yt("WebGLRenderer:",c,"not supported, using",h,"instead."),c=h);const d=t.logarithmicDepthBuffer===!0,p=t.reversedDepthBuffer===!0&&e.has("EXT_clip_control"),u=s.getParameter(s.MAX_TEXTURE_IMAGE_UNITS),v=s.getParameter(s.MAX_VERTEX_TEXTURE_IMAGE_UNITS),g=s.getParameter(s.MAX_TEXTURE_SIZE),m=s.getParameter(s.MAX_CUBE_MAP_TEXTURE_SIZE),f=s.getParameter(s.MAX_VERTEX_ATTRIBS),y=s.getParameter(s.MAX_VERTEX_UNIFORM_VECTORS),x=s.getParameter(s.MAX_VARYING_VECTORS),_=s.getParameter(s.MAX_FRAGMENT_UNIFORM_VECTORS),S=v>0,b=s.getParameter(s.MAX_SAMPLES);return{isWebGL2:!0,getMaxAnisotropy:r,getMaxPrecision:l,textureFormatReadable:a,textureTypeReadable:o,precision:c,logarithmicDepthBuffer:d,reversedDepthBuffer:p,maxTextures:u,maxVertexTextures:v,maxTextureSize:g,maxCubemapSize:m,maxAttributes:f,maxVertexUniforms:y,maxVaryings:x,maxFragmentUniforms:_,vertexTextures:S,maxSamples:b}}function a6(s){const e=this;let t=null,i=0,n=!1,r=!1;const a=new po,o=new Mt,l={value:null,needsUpdate:!1};this.uniform=l,this.numPlanes=0,this.numIntersection=0,this.init=function(d,p){const u=d.length!==0||p||i!==0||n;return n=p,i=d.length,u},this.beginShadows=function(){r=!0,h(null)},this.endShadows=function(){r=!1},this.setGlobalState=function(d,p){t=h(d,p,0)},this.setState=function(d,p,u){const v=d.clippingPlanes,g=d.clipIntersection,m=d.clipShadows,f=s.get(d);if(!n||v===null||v.length===0||r&&!m)r?h(null):c();else{const y=r?0:i,x=y*4;let _=f.clippingState||null;l.value=_,_=h(v,p,x,u);for(let S=0;S!==x;++S)_[S]=t[S];f.clippingState=_,this.numIntersection=g?this.numPlanes:0,this.numPlanes+=y}};function c(){l.value!==t&&(l.value=t,l.needsUpdate=i>0),e.numPlanes=i,e.numIntersection=0}function h(d,p,u,v){const g=d!==null?d.length:0;let m=null;if(g!==0){if(m=l.value,v!==!0||m===null){const f=u+g*4,y=p.matrixWorldInverse;o.getNormalMatrix(y),(m===null||m.length0){const c=new hI(l.height);return c.fromEquirectangularTexture(s,a),e.set(a,c),a.addEventListener("dispose",n),t(c.texture,a.mapping)}else return null}}return a}function n(a){const o=a.target;o.removeEventListener("dispose",n);const l=e.get(o);l!==void 0&&(e.delete(o),l.dispose())}function r(){e=new WeakMap}return{get:i,dispose:r}}const ha=4,EM=[.125,.215,.35,.446,.526,.582],go=20,l6=256,Rh=new yI,TM=new Wt;let Vv=null,Gv=0,Wv=0,Xv=!1;const c6=new De;class CM{constructor(e){this._renderer=e,this._pingPongRenderTarget=null,this._lodMax=0,this._cubeSize=0,this._sizeLods=[],this._sigmas=[],this._lodMeshes=[],this._backgroundBox=null,this._cubemapMaterial=null,this._equirectMaterial=null,this._blurMaterial=null,this._ggxMaterial=null}fromScene(e,t=0,i=.1,n=100,r={}){const{size:a=256,position:o=c6}=r;Vv=this._renderer.getRenderTarget(),Gv=this._renderer.getActiveCubeFace(),Wv=this._renderer.getActiveMipmapLevel(),Xv=this._renderer.xr.enabled,this._renderer.xr.enabled=!1,this._setSize(a);const l=this._allocateTargets();return l.depthBuffer=!0,this._sceneToCubeUV(e,i,n,l,o),t>0&&this._blur(l,0,0,t),this._applyPMREM(l),this._cleanup(l),l}fromEquirectangular(e,t=null){return this._fromTexture(e,t)}fromCubemap(e,t=null){return this._fromTexture(e,t)}compileCubemapShader(){this._cubemapMaterial===null&&(this._cubemapMaterial=RM(),this._compileMaterial(this._cubemapMaterial))}compileEquirectangularShader(){this._equirectMaterial===null&&(this._equirectMaterial=PM(),this._compileMaterial(this._equirectMaterial))}dispose(){this._dispose(),this._cubemapMaterial!==null&&this._cubemapMaterial.dispose(),this._equirectMaterial!==null&&this._equirectMaterial.dispose(),this._backgroundBox!==null&&(this._backgroundBox.geometry.dispose(),this._backgroundBox.material.dispose())}_setSize(e){this._lodMax=Math.floor(Math.log2(e)),this._cubeSize=Math.pow(2,this._lodMax)}_dispose(){this._blurMaterial!==null&&this._blurMaterial.dispose(),this._ggxMaterial!==null&&this._ggxMaterial.dispose(),this._pingPongRenderTarget!==null&&this._pingPongRenderTarget.dispose();for(let e=0;e2?y:0,y,y),c.setRenderTarget(n),v&&c.render(p,a),c.render(e,a)}c.toneMapping=d,c.autoClear=h,e.background=g}_textureToCubeUV(e,t){const i=this._renderer,n=e.mapping===Pl||e.mapping===Rl;n?(this._cubemapMaterial===null&&(this._cubemapMaterial=RM()),this._cubemapMaterial.uniforms.flipEnvMap.value=e.isRenderTargetTexture===!1?-1:1):this._equirectMaterial===null&&(this._equirectMaterial=PM());const r=n?this._cubemapMaterial:this._equirectMaterial,a=this._lodMeshes[0];a.material=r;const o=r.uniforms;o.envMap.value=e;const l=this._cubeSize;Yl(t,0,0,3*l,2*l),i.setRenderTarget(t),i.render(a,Rh)}_applyPMREM(e){const t=this._renderer,i=t.autoClear;t.autoClear=!1;const n=this._lodMeshes.length;for(let r=1;rv-ha?i-v+ha:0),f=4*(this._cubeSize-g);l.envMap.value=e.texture,l.roughness.value=u,l.mipInt.value=v-t,Yl(r,m,f,3*g,2*g),n.setRenderTarget(r),n.render(o,Rh),l.envMap.value=r.texture,l.roughness.value=0,l.mipInt.value=v-i,Yl(e,m,f,3*g,2*g),n.setRenderTarget(e),n.render(o,Rh)}_blur(e,t,i,n,r){const a=this._pingPongRenderTarget;this._halfBlur(e,a,t,i,n,"latitudinal",r),this._halfBlur(a,e,i,i,n,"longitudinal",r)}_halfBlur(e,t,i,n,r,a,o){const l=this._renderer,c=this._blurMaterial;a!=="latitudinal"&&a!=="longitudinal"&&gi("blur direction must be either latitudinal or longitudinal!");const h=3,d=this._lodMeshes[n];d.material=c;const p=c.uniforms,u=this._sizeLods[i]-1,v=isFinite(r)?Math.PI/(2*u):2*Math.PI/(2*go-1),g=r/v,m=isFinite(r)?1+Math.floor(h*g):go;m>go&&yt(`sigmaRadians, ${r}, is too large and will clip, as it requested ${m} samples when the maximum is set to ${go}`);const f=[];let y=0;for(let E=0;Ex-ha?n-x+ha:0),b=4*(this._cubeSize-_);Yl(t,S,b,3*_,2*_),l.setRenderTarget(t),l.render(d,Rh)}}function h6(s){const e=[],t=[],i=[];let n=s;const r=s-ha+1+EM.length;for(let a=0;as-ha?l=EM[a-s+ha-1]:a===0&&(l=0),t.push(l);const c=1/(o-2),h=-c,d=1+c,p=[h,h,d,h,d,d,h,h,d,d,h,d],u=6,v=6,g=3,m=2,f=1,y=new Float32Array(g*v*u),x=new Float32Array(m*v*u),_=new Float32Array(f*v*u);for(let b=0;b2?0:-1,M=[E,w,0,E+2/3,w,0,E+2/3,w+1,0,E,w,0,E+2/3,w+1,0,E,w+1,0];y.set(M,g*v*b),x.set(p,m*v*b);const C=[b,b,b,b,b,b];_.set(C,f*v*b)}const S=new oa;S.setAttribute("position",new Vs(y,g)),S.setAttribute("uv",new Vs(x,m)),S.setAttribute("faceIndex",new Vs(_,f)),i.push(new la(S,null)),n>ha&&n--}return{lodMeshes:i,sizeLods:e,sigmas:t}}function AM(s,e,t){const i=new ao(s,e,t);return i.texture.mapping=Fp,i.texture.name="PMREM.cubeUv",i.scissorTest=!0,i}function Yl(s,e,t,i,n){s.viewport.set(e,t,i,n),s.scissor.set(e,t,i,n)}function d6(s,e,t){return new yr({name:"PMREMGGXConvolution",defines:{GGX_SAMPLES:l6,CUBEUV_TEXEL_WIDTH:1/e,CUBEUV_TEXEL_HEIGHT:1/t,CUBEUV_MAX_MIP:`${s}.0`},uniforms:{envMap:{value:null},roughness:{value:0},mipInt:{value:0}},vertexShader:gf(),fragmentShader:` precision highp float; precision highp int; varying vec3 vOutputDirection; uniform sampler2D envMap; uniform float roughness; uniform float mipInt; #define ENVMAP_TYPE_CUBE_UV #include #define PI 3.14159265359 // Van der Corput radical inverse float radicalInverse_VdC(uint bits) { bits = (bits << 16u) | (bits >> 16u); bits = ((bits & 0x55555555u) << 1u) | ((bits & 0xAAAAAAAAu) >> 1u); bits = ((bits & 0x33333333u) << 2u) | ((bits & 0xCCCCCCCCu) >> 2u); bits = ((bits & 0x0F0F0F0Fu) << 4u) | ((bits & 0xF0F0F0F0u) >> 4u); bits = ((bits & 0x00FF00FFu) << 8u) | ((bits & 0xFF00FF00u) >> 8u); return float(bits) * 2.3283064365386963e-10; // / 0x100000000 } // Hammersley sequence vec2 hammersley(uint i, uint N) { return vec2(float(i) / float(N), radicalInverse_VdC(i)); } // GGX VNDF importance sampling (Eric Heitz 2018) // "Sampling the GGX Distribution of Visible Normals" // https://jcgt.org/published/0007/04/01/ vec3 importanceSampleGGX_VNDF(vec2 Xi, vec3 V, float roughness) { float alpha = roughness * roughness; // Section 3.2: Transform view direction to hemisphere configuration vec3 Vh = normalize(vec3(alpha * V.x, alpha * V.y, V.z)); // Section 4.1: Orthonormal basis float lensq = Vh.x * Vh.x + Vh.y * Vh.y; vec3 T1 = lensq > 0.0 ? vec3(-Vh.y, Vh.x, 0.0) / sqrt(lensq) : vec3(1.0, 0.0, 0.0); vec3 T2 = cross(Vh, T1); // Section 4.2: Parameterization of projected area float r = sqrt(Xi.x); float phi = 2.0 * PI * Xi.y; float t1 = r * cos(phi); float t2 = r * sin(phi); float s = 0.5 * (1.0 + Vh.z); t2 = (1.0 - s) * sqrt(1.0 - t1 * t1) + s * t2; // Section 4.3: Reprojection onto hemisphere vec3 Nh = t1 * T1 + t2 * T2 + sqrt(max(0.0, 1.0 - t1 * t1 - t2 * t2)) * Vh; // Section 3.4: Transform back to ellipsoid configuration return normalize(vec3(alpha * Nh.x, alpha * Nh.y, max(0.0, Nh.z))); } void main() { vec3 N = normalize(vOutputDirection); vec3 V = N; // Assume view direction equals normal for pre-filtering vec3 prefilteredColor = vec3(0.0); float totalWeight = 0.0; // For very low roughness, just sample the environment directly if (roughness < 0.001) { gl_FragColor = vec4(bilinearCubeUV(envMap, N, mipInt), 1.0); return; } // Tangent space basis for VNDF sampling vec3 up = abs(N.z) < 0.999 ? vec3(0.0, 0.0, 1.0) : vec3(1.0, 0.0, 0.0); vec3 tangent = normalize(cross(up, N)); vec3 bitangent = cross(N, tangent); for(uint i = 0u; i < uint(GGX_SAMPLES); i++) { vec2 Xi = hammersley(i, uint(GGX_SAMPLES)); // For PMREM, V = N, so in tangent space V is always (0, 0, 1) vec3 H_tangent = importanceSampleGGX_VNDF(Xi, vec3(0.0, 0.0, 1.0), roughness); // Transform H back to world space vec3 H = normalize(tangent * H_tangent.x + bitangent * H_tangent.y + N * H_tangent.z); vec3 L = normalize(2.0 * dot(V, H) * H - V); float NdotL = max(dot(N, L), 0.0); if(NdotL > 0.0) { // Sample environment at fixed mip level // VNDF importance sampling handles the distribution filtering vec3 sampleColor = bilinearCubeUV(envMap, L, mipInt); // Weight by NdotL for the split-sum approximation // VNDF PDF naturally accounts for the visible microfacet distribution prefilteredColor += sampleColor * NdotL; totalWeight += NdotL; } } if (totalWeight > 0.0) { prefilteredColor = prefilteredColor / totalWeight; } gl_FragColor = vec4(prefilteredColor, 1.0); } `,blending:lr,depthTest:!1,depthWrite:!1})}function u6(s,e,t){const i=new Float32Array(go),n=new De(0,1,0);return new yr({name:"SphericalGaussianBlur",defines:{n:go,CUBEUV_TEXEL_WIDTH:1/e,CUBEUV_TEXEL_HEIGHT:1/t,CUBEUV_MAX_MIP:`${s}.0`},uniforms:{envMap:{value:null},samples:{value:1},weights:{value:i},latitudinal:{value:!1},dTheta:{value:0},mipInt:{value:0},poleAxis:{value:n}},vertexShader:gf(),fragmentShader:` precision mediump float; precision mediump int; varying vec3 vOutputDirection; uniform sampler2D envMap; uniform int samples; uniform float weights[ n ]; uniform bool latitudinal; uniform float dTheta; uniform float mipInt; uniform vec3 poleAxis; #define ENVMAP_TYPE_CUBE_UV #include vec3 getSample( float theta, vec3 axis ) { float cosTheta = cos( theta ); // Rodrigues' axis-angle rotation vec3 sampleDirection = vOutputDirection * cosTheta + cross( axis, vOutputDirection ) * sin( theta ) + axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta ); return bilinearCubeUV( envMap, sampleDirection, mipInt ); } void main() { vec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection ); if ( all( equal( axis, vec3( 0.0 ) ) ) ) { axis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x ); } axis = normalize( axis ); gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 ); gl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis ); for ( int i = 1; i < n; i++ ) { if ( i >= samples ) { break; } float theta = dTheta * float( i ); gl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis ); gl_FragColor.rgb += weights[ i ] * getSample( theta, axis ); } } `,blending:lr,depthTest:!1,depthWrite:!1})}function PM(){return new yr({name:"EquirectangularToCubeUV",uniforms:{envMap:{value:null}},vertexShader:gf(),fragmentShader:` precision mediump float; precision mediump int; varying vec3 vOutputDirection; uniform sampler2D envMap; #include void main() { vec3 outputDirection = normalize( vOutputDirection ); vec2 uv = equirectUv( outputDirection ); gl_FragColor = vec4( texture2D ( envMap, uv ).rgb, 1.0 ); } `,blending:lr,depthTest:!1,depthWrite:!1})}function RM(){return new yr({name:"CubemapToCubeUV",uniforms:{envMap:{value:null},flipEnvMap:{value:-1}},vertexShader:gf(),fragmentShader:` precision mediump float; precision mediump int; uniform float flipEnvMap; varying vec3 vOutputDirection; uniform samplerCube envMap; void main() { gl_FragColor = textureCube( envMap, vec3( flipEnvMap * vOutputDirection.x, vOutputDirection.yz ) ); } `,blending:lr,depthTest:!1,depthWrite:!1})}function gf(){return` precision mediump float; precision mediump int; attribute float faceIndex; varying vec3 vOutputDirection; // RH coordinate system; PMREM face-indexing convention vec3 getDirection( vec2 uv, float face ) { uv = 2.0 * uv - 1.0; vec3 direction = vec3( uv, 1.0 ); if ( face == 0.0 ) { direction = direction.zyx; // ( 1, v, u ) pos x } else if ( face == 1.0 ) { direction = direction.xzy; direction.xz *= -1.0; // ( -u, 1, -v ) pos y } else if ( face == 2.0 ) { direction.x *= -1.0; // ( -u, v, 1 ) pos z } else if ( face == 3.0 ) { direction = direction.zyx; direction.xz *= -1.0; // ( -1, v, -u ) neg x } else if ( face == 4.0 ) { direction = direction.xzy; direction.xy *= -1.0; // ( -u, -1, v ) neg y } else if ( face == 5.0 ) { direction.z *= -1.0; // ( u, v, -1 ) neg z } return direction; } void main() { vOutputDirection = getDirection( uv, faceIndex ); gl_Position = vec4( position, 1.0 ); } `}function p6(s){let e=new WeakMap,t=null;function i(o){if(o&&o.isTexture){const l=o.mapping,c=l===P0||l===R0,h=l===Pl||l===Rl;if(c||h){let d=e.get(o);const p=d!==void 0?d.texture.pmremVersion:0;if(o.isRenderTargetTexture&&o.pmremVersion!==p)return t===null&&(t=new CM(s)),d=c?t.fromEquirectangular(o,d):t.fromCubemap(o,d),d.texture.pmremVersion=o.pmremVersion,e.set(o,d),d.texture;if(d!==void 0)return d.texture;{const u=o.image;return c&&u&&u.height>0||h&&u&&n(u)?(t===null&&(t=new CM(s)),d=c?t.fromEquirectangular(o):t.fromCubemap(o),d.texture.pmremVersion=o.pmremVersion,e.set(o,d),o.addEventListener("dispose",r),d.texture):null}}}return o}function n(o){let l=0;const c=6;for(let h=0;he.maxTextureSize&&(b=Math.ceil(S/e.maxTextureSize),S=e.maxTextureSize);const E=new Float32Array(S*b*4*d),w=new Jb(E,S,b,d);w.type=dr,w.needsUpdate=!0;const M=_*4;for(let C=0;C0)return s;const n=e*t;let r=OM[n];if(r===void 0&&(r=new Float32Array(n),OM[n]=r),e!==0){i.toArray(r,0);for(let a=1,o=0;a!==e;++a)o+=t,s[a].toArray(r,o)}return r}function Ni(s,e){if(s.length!==e.length)return!1;for(let t=0,i=s.length;t":" "} ${o}: ${t[a]}`)}return i.join(` `)}const GM=new Mt;function pN(s){Ut._getMatrix(GM,Ut.workingColorSpace,s);const e=`mat3( ${GM.elements.map(t=>t.toFixed(4))} )`;switch(Ut.getTransfer(s)){case Xp:return[e,"LinearTransferOETF"];case Vt:return[e,"sRGBTransferOETF"];default:return yt("WebGLProgram: Unsupported color space: ",s),[e,"LinearTransferOETF"]}}function WM(s,e,t){const i=s.getShaderParameter(e,s.COMPILE_STATUS),n=(s.getShaderInfoLog(e)||"").trim();if(i&&n==="")return"";const r=/ERROR: 0:(\d+)/.exec(n);if(r){const a=parseInt(r[1]);return t.toUpperCase()+` `+n+` `+uN(s.getShaderSource(e),a)}else return n}function fN(s,e){const t=pN(e);return[`vec4 ${s}( vec4 value ) {`,` return ${t[1]}( vec4( value.rgb * ${t[0]}, value.a ) );`,"}"].join(` `)}function mN(s,e){let t;switch(e){case xR:t="Linear";break;case _R:t="Reinhard";break;case bR:t="Cineon";break;case MR:t="ACESFilmic";break;case wR:t="AgX";break;case ER:t="Neutral";break;case SR:t="Custom";break;default:yt("WebGLProgram: Unsupported toneMapping:",e),t="Linear"}return"vec3 "+s+"( vec3 color ) { return "+t+"ToneMapping( color ); }"}const xf=new De;function gN(){Ut.getLuminanceCoefficients(xf);const s=xf.x.toFixed(4),e=xf.y.toFixed(4),t=xf.z.toFixed(4);return["float luminance( const in vec3 rgb ) {",` const vec3 weights = vec3( ${s}, ${e}, ${t} );`," return dot( weights, rgb );","}"].join(` `)}function vN(s){return[s.extensionClipCullDistance?"#extension GL_ANGLE_clip_cull_distance : require":"",s.extensionMultiDraw?"#extension GL_ANGLE_multi_draw : require":""].filter(Ih).join(` `)}function yN(s){const e=[];for(const t in s){const i=s[t];i!==!1&&e.push("#define "+t+" "+i)}return e.join(` `)}function xN(s,e){const t={},i=s.getProgramParameter(e,s.ACTIVE_ATTRIBUTES);for(let n=0;n/gm;function qv(s){return s.replace(_N,MN)}const bN=new Map;function MN(s,e){let t=wt[e];if(t===void 0){const i=bN.get(e);if(i!==void 0)t=wt[i],yt('WebGLRenderer: Shader chunk "%s" has been deprecated. Use "%s" instead.',e,i);else throw new Error("Can not resolve #include <"+e+">")}return qv(t)}const SN=/#pragma unroll_loop_start\s+for\s*\(\s*int\s+i\s*=\s*(\d+)\s*;\s*i\s*<\s*(\d+)\s*;\s*i\s*\+\+\s*\)\s*{([\s\S]+?)}\s+#pragma unroll_loop_end/g;function qM(s){return s.replace(SN,wN)}function wN(s,e,t,i){let n="";for(let r=parseInt(e);r0&&(m+=` `),f=["#define SHADER_TYPE "+t.shaderType,"#define SHADER_NAME "+t.shaderName,v].filter(Ih).join(` `),f.length>0&&(f+=` `)):(m=[ZM(t),"#define SHADER_TYPE "+t.shaderType,"#define SHADER_NAME "+t.shaderName,v,t.extensionClipCullDistance?"#define USE_CLIP_DISTANCE":"",t.batching?"#define USE_BATCHING":"",t.batchingColor?"#define USE_BATCHING_COLOR":"",t.instancing?"#define USE_INSTANCING":"",t.instancingColor?"#define USE_INSTANCING_COLOR":"",t.instancingMorph?"#define USE_INSTANCING_MORPH":"",t.useFog&&t.fog?"#define USE_FOG":"",t.useFog&&t.fogExp2?"#define FOG_EXP2":"",t.map?"#define USE_MAP":"",t.envMap?"#define USE_ENVMAP":"",t.envMap?"#define "+h:"",t.lightMap?"#define USE_LIGHTMAP":"",t.aoMap?"#define USE_AOMAP":"",t.bumpMap?"#define USE_BUMPMAP":"",t.normalMap?"#define USE_NORMALMAP":"",t.normalMapObjectSpace?"#define USE_NORMALMAP_OBJECTSPACE":"",t.normalMapTangentSpace?"#define USE_NORMALMAP_TANGENTSPACE":"",t.displacementMap?"#define USE_DISPLACEMENTMAP":"",t.emissiveMap?"#define USE_EMISSIVEMAP":"",t.anisotropy?"#define USE_ANISOTROPY":"",t.anisotropyMap?"#define USE_ANISOTROPYMAP":"",t.clearcoatMap?"#define USE_CLEARCOATMAP":"",t.clearcoatRoughnessMap?"#define USE_CLEARCOAT_ROUGHNESSMAP":"",t.clearcoatNormalMap?"#define USE_CLEARCOAT_NORMALMAP":"",t.iridescenceMap?"#define USE_IRIDESCENCEMAP":"",t.iridescenceThicknessMap?"#define USE_IRIDESCENCE_THICKNESSMAP":"",t.specularMap?"#define USE_SPECULARMAP":"",t.specularColorMap?"#define USE_SPECULAR_COLORMAP":"",t.specularIntensityMap?"#define USE_SPECULAR_INTENSITYMAP":"",t.roughnessMap?"#define USE_ROUGHNESSMAP":"",t.metalnessMap?"#define USE_METALNESSMAP":"",t.alphaMap?"#define USE_ALPHAMAP":"",t.alphaHash?"#define USE_ALPHAHASH":"",t.transmission?"#define USE_TRANSMISSION":"",t.transmissionMap?"#define USE_TRANSMISSIONMAP":"",t.thicknessMap?"#define USE_THICKNESSMAP":"",t.sheenColorMap?"#define USE_SHEEN_COLORMAP":"",t.sheenRoughnessMap?"#define USE_SHEEN_ROUGHNESSMAP":"",t.mapUv?"#define MAP_UV "+t.mapUv:"",t.alphaMapUv?"#define ALPHAMAP_UV "+t.alphaMapUv:"",t.lightMapUv?"#define LIGHTMAP_UV "+t.lightMapUv:"",t.aoMapUv?"#define AOMAP_UV "+t.aoMapUv:"",t.emissiveMapUv?"#define EMISSIVEMAP_UV "+t.emissiveMapUv:"",t.bumpMapUv?"#define BUMPMAP_UV "+t.bumpMapUv:"",t.normalMapUv?"#define NORMALMAP_UV "+t.normalMapUv:"",t.displacementMapUv?"#define DISPLACEMENTMAP_UV "+t.displacementMapUv:"",t.metalnessMapUv?"#define METALNESSMAP_UV "+t.metalnessMapUv:"",t.roughnessMapUv?"#define ROUGHNESSMAP_UV "+t.roughnessMapUv:"",t.anisotropyMapUv?"#define ANISOTROPYMAP_UV "+t.anisotropyMapUv:"",t.clearcoatMapUv?"#define CLEARCOATMAP_UV "+t.clearcoatMapUv:"",t.clearcoatNormalMapUv?"#define CLEARCOAT_NORMALMAP_UV "+t.clearcoatNormalMapUv:"",t.clearcoatRoughnessMapUv?"#define CLEARCOAT_ROUGHNESSMAP_UV "+t.clearcoatRoughnessMapUv:"",t.iridescenceMapUv?"#define IRIDESCENCEMAP_UV "+t.iridescenceMapUv:"",t.iridescenceThicknessMapUv?"#define IRIDESCENCE_THICKNESSMAP_UV "+t.iridescenceThicknessMapUv:"",t.sheenColorMapUv?"#define SHEEN_COLORMAP_UV "+t.sheenColorMapUv:"",t.sheenRoughnessMapUv?"#define SHEEN_ROUGHNESSMAP_UV "+t.sheenRoughnessMapUv:"",t.specularMapUv?"#define SPECULARMAP_UV "+t.specularMapUv:"",t.specularColorMapUv?"#define SPECULAR_COLORMAP_UV "+t.specularColorMapUv:"",t.specularIntensityMapUv?"#define SPECULAR_INTENSITYMAP_UV "+t.specularIntensityMapUv:"",t.transmissionMapUv?"#define TRANSMISSIONMAP_UV "+t.transmissionMapUv:"",t.thicknessMapUv?"#define THICKNESSMAP_UV "+t.thicknessMapUv:"",t.vertexTangents&&t.flatShading===!1?"#define USE_TANGENT":"",t.vertexColors?"#define USE_COLOR":"",t.vertexAlphas?"#define USE_COLOR_ALPHA":"",t.vertexUv1s?"#define USE_UV1":"",t.vertexUv2s?"#define USE_UV2":"",t.vertexUv3s?"#define USE_UV3":"",t.pointsUvs?"#define USE_POINTS_UV":"",t.flatShading?"#define FLAT_SHADED":"",t.skinning?"#define USE_SKINNING":"",t.morphTargets?"#define USE_MORPHTARGETS":"",t.morphNormals&&t.flatShading===!1?"#define USE_MORPHNORMALS":"",t.morphColors?"#define USE_MORPHCOLORS":"",t.morphTargetsCount>0?"#define MORPHTARGETS_TEXTURE_STRIDE "+t.morphTextureStride:"",t.morphTargetsCount>0?"#define MORPHTARGETS_COUNT "+t.morphTargetsCount:"",t.doubleSided?"#define DOUBLE_SIDED":"",t.flipSided?"#define FLIP_SIDED":"",t.shadowMapEnabled?"#define USE_SHADOWMAP":"",t.shadowMapEnabled?"#define "+l:"",t.sizeAttenuation?"#define USE_SIZEATTENUATION":"",t.numLightProbes>0?"#define USE_LIGHT_PROBES":"",t.logarithmicDepthBuffer?"#define USE_LOGARITHMIC_DEPTH_BUFFER":"",t.reversedDepthBuffer?"#define USE_REVERSED_DEPTH_BUFFER":"","uniform mat4 modelMatrix;","uniform mat4 modelViewMatrix;","uniform mat4 projectionMatrix;","uniform mat4 viewMatrix;","uniform mat3 normalMatrix;","uniform vec3 cameraPosition;","uniform bool isOrthographic;","#ifdef USE_INSTANCING"," attribute mat4 instanceMatrix;","#endif","#ifdef USE_INSTANCING_COLOR"," attribute vec3 instanceColor;","#endif","#ifdef USE_INSTANCING_MORPH"," uniform sampler2D morphTexture;","#endif","attribute vec3 position;","attribute vec3 normal;","attribute vec2 uv;","#ifdef USE_UV1"," attribute vec2 uv1;","#endif","#ifdef USE_UV2"," attribute vec2 uv2;","#endif","#ifdef USE_UV3"," attribute vec2 uv3;","#endif","#ifdef USE_TANGENT"," attribute vec4 tangent;","#endif","#if defined( USE_COLOR_ALPHA )"," attribute vec4 color;","#elif defined( USE_COLOR )"," attribute vec3 color;","#endif","#ifdef USE_SKINNING"," attribute vec4 skinIndex;"," attribute vec4 skinWeight;","#endif",` `].filter(Ih).join(` `),f=[ZM(t),"#define SHADER_TYPE "+t.shaderType,"#define SHADER_NAME "+t.shaderName,v,t.useFog&&t.fog?"#define USE_FOG":"",t.useFog&&t.fogExp2?"#define FOG_EXP2":"",t.alphaToCoverage?"#define ALPHA_TO_COVERAGE":"",t.map?"#define USE_MAP":"",t.matcap?"#define USE_MATCAP":"",t.envMap?"#define USE_ENVMAP":"",t.envMap?"#define "+c:"",t.envMap?"#define "+h:"",t.envMap?"#define "+d:"",p?"#define CUBEUV_TEXEL_WIDTH "+p.texelWidth:"",p?"#define CUBEUV_TEXEL_HEIGHT "+p.texelHeight:"",p?"#define CUBEUV_MAX_MIP "+p.maxMip+".0":"",t.lightMap?"#define USE_LIGHTMAP":"",t.aoMap?"#define USE_AOMAP":"",t.bumpMap?"#define USE_BUMPMAP":"",t.normalMap?"#define USE_NORMALMAP":"",t.normalMapObjectSpace?"#define USE_NORMALMAP_OBJECTSPACE":"",t.normalMapTangentSpace?"#define USE_NORMALMAP_TANGENTSPACE":"",t.emissiveMap?"#define USE_EMISSIVEMAP":"",t.anisotropy?"#define USE_ANISOTROPY":"",t.anisotropyMap?"#define USE_ANISOTROPYMAP":"",t.clearcoat?"#define USE_CLEARCOAT":"",t.clearcoatMap?"#define USE_CLEARCOATMAP":"",t.clearcoatRoughnessMap?"#define USE_CLEARCOAT_ROUGHNESSMAP":"",t.clearcoatNormalMap?"#define USE_CLEARCOAT_NORMALMAP":"",t.dispersion?"#define USE_DISPERSION":"",t.iridescence?"#define USE_IRIDESCENCE":"",t.iridescenceMap?"#define USE_IRIDESCENCEMAP":"",t.iridescenceThicknessMap?"#define USE_IRIDESCENCE_THICKNESSMAP":"",t.specularMap?"#define USE_SPECULARMAP":"",t.specularColorMap?"#define USE_SPECULAR_COLORMAP":"",t.specularIntensityMap?"#define USE_SPECULAR_INTENSITYMAP":"",t.roughnessMap?"#define USE_ROUGHNESSMAP":"",t.metalnessMap?"#define USE_METALNESSMAP":"",t.alphaMap?"#define USE_ALPHAMAP":"",t.alphaTest?"#define USE_ALPHATEST":"",t.alphaHash?"#define USE_ALPHAHASH":"",t.sheen?"#define USE_SHEEN":"",t.sheenColorMap?"#define USE_SHEEN_COLORMAP":"",t.sheenRoughnessMap?"#define USE_SHEEN_ROUGHNESSMAP":"",t.transmission?"#define USE_TRANSMISSION":"",t.transmissionMap?"#define USE_TRANSMISSIONMAP":"",t.thicknessMap?"#define USE_THICKNESSMAP":"",t.vertexTangents&&t.flatShading===!1?"#define USE_TANGENT":"",t.vertexColors||t.instancingColor||t.batchingColor?"#define USE_COLOR":"",t.vertexAlphas?"#define USE_COLOR_ALPHA":"",t.vertexUv1s?"#define USE_UV1":"",t.vertexUv2s?"#define USE_UV2":"",t.vertexUv3s?"#define USE_UV3":"",t.pointsUvs?"#define USE_POINTS_UV":"",t.gradientMap?"#define USE_GRADIENTMAP":"",t.flatShading?"#define FLAT_SHADED":"",t.doubleSided?"#define DOUBLE_SIDED":"",t.flipSided?"#define FLIP_SIDED":"",t.shadowMapEnabled?"#define USE_SHADOWMAP":"",t.shadowMapEnabled?"#define "+l:"",t.premultipliedAlpha?"#define PREMULTIPLIED_ALPHA":"",t.numLightProbes>0?"#define USE_LIGHT_PROBES":"",t.decodeVideoTexture?"#define DECODE_VIDEO_TEXTURE":"",t.decodeVideoTextureEmissive?"#define DECODE_VIDEO_TEXTURE_EMISSIVE":"",t.logarithmicDepthBuffer?"#define USE_LOGARITHMIC_DEPTH_BUFFER":"",t.reversedDepthBuffer?"#define USE_REVERSED_DEPTH_BUFFER":"","uniform mat4 viewMatrix;","uniform vec3 cameraPosition;","uniform bool isOrthographic;",t.toneMapping!==ea?"#define TONE_MAPPING":"",t.toneMapping!==ea?wt.tonemapping_pars_fragment:"",t.toneMapping!==ea?mN("toneMapping",t.toneMapping):"",t.dithering?"#define DITHERING":"",t.opaque?"#define OPAQUE":"",wt.colorspace_pars_fragment,fN("linearToOutputTexel",t.outputColorSpace),gN(),t.useDepthPacking?"#define DEPTH_PACKING "+t.depthPacking:"",` `].filter(Ih).join(` `)),a=qv(a),a=XM(a,t),a=jM(a,t),o=qv(o),o=XM(o,t),o=jM(o,t),a=qM(a),o=qM(o),t.isRawShaderMaterial!==!0&&(y=`#version 300 es `,m=[u,"#define attribute in","#define varying out","#define texture2D texture"].join(` `)+` `+m,f=["#define varying in",t.glslVersion===Xb?"":"layout(location = 0) out highp vec4 pc_fragColor;",t.glslVersion===Xb?"":"#define gl_FragColor pc_fragColor","#define gl_FragDepthEXT gl_FragDepth","#define texture2D texture","#define textureCube texture","#define texture2DProj textureProj","#define texture2DLodEXT textureLod","#define texture2DProjLodEXT textureProjLod","#define textureCubeLodEXT textureLod","#define texture2DGradEXT textureGrad","#define texture2DProjGradEXT textureProjGrad","#define textureCubeGradEXT textureGrad"].join(` `)+` `+f);const x=y+m+a,_=y+f+o,S=VM(n,n.VERTEX_SHADER,x),b=VM(n,n.FRAGMENT_SHADER,_);n.attachShader(g,S),n.attachShader(g,b),t.index0AttributeName!==void 0?n.bindAttribLocation(g,0,t.index0AttributeName):t.morphTargets===!0&&n.bindAttribLocation(g,0,"position"),n.linkProgram(g);function E(I){if(s.debug.checkShaderErrors){const P=n.getProgramInfoLog(g)||"",k=n.getShaderInfoLog(S)||"",A=n.getShaderInfoLog(b)||"",B=P.trim(),F=k.trim(),H=A.trim();let q=!0,G=!0;if(n.getProgramParameter(g,n.LINK_STATUS)===!1)if(q=!1,typeof s.debug.onShaderError=="function")s.debug.onShaderError(n,g,S,b);else{const re=WM(n,S,"vertex"),Y=WM(n,b,"fragment");gi("THREE.WebGLProgram: Shader Error "+n.getError()+" - VALIDATE_STATUS "+n.getProgramParameter(g,n.VALIDATE_STATUS)+` Material Name: `+I.name+` Material Type: `+I.type+` Program Info Log: `+B+` `+re+` `+Y)}else B!==""?yt("WebGLProgram: Program Info Log:",B):(F===""||H==="")&&(G=!1);G&&(I.diagnostics={runnable:q,programLog:B,vertexShader:{log:F,prefix:m},fragmentShader:{log:H,prefix:f}})}n.deleteShader(S),n.deleteShader(b),w=new yf(n,g),M=xN(n,g)}let w;this.getUniforms=function(){return w===void 0&&E(this),w};let M;this.getAttributes=function(){return M===void 0&&E(this),M};let C=t.rendererExtensionParallelShaderCompile===!1;return this.isReady=function(){return C===!1&&(C=n.getProgramParameter(g,hN)),C},this.destroy=function(){i.releaseStatesOfProgram(this),n.deleteProgram(g),this.program=void 0},this.type=t.shaderType,this.name=t.shaderName,this.id=dN++,this.cacheKey=e,this.usedTimes=1,this.program=g,this.vertexShader=S,this.fragmentShader=b,this}let IN=0;class LN{constructor(){this.shaderCache=new Map,this.materialCache=new Map}update(e){const t=e.vertexShader,i=e.fragmentShader,n=this._getShaderStage(t),r=this._getShaderStage(i),a=this._getShaderCacheForMaterial(e);return a.has(n)===!1&&(a.add(n),n.usedTimes++),a.has(r)===!1&&(a.add(r),r.usedTimes++),this}remove(e){const t=this.materialCache.get(e);for(const i of t)i.usedTimes--,i.usedTimes===0&&this.shaderCache.delete(i.code);return this.materialCache.delete(e),this}getVertexShaderID(e){return this._getShaderStage(e.vertexShader).id}getFragmentShaderID(e){return this._getShaderStage(e.fragmentShader).id}dispose(){this.shaderCache.clear(),this.materialCache.clear()}_getShaderCacheForMaterial(e){const t=this.materialCache;let i=t.get(e);return i===void 0&&(i=new Set,t.set(e,i)),i}_getShaderStage(e){const t=this.shaderCache;let i=t.get(e);return i===void 0&&(i=new DN(e),t.set(e,i)),i}}class DN{constructor(e){this.id=IN++,this.code=e,this.usedTimes=0}}function NN(s,e,t,i,n,r,a){const o=new tM,l=new LN,c=new Set,h=[],d=n.logarithmicDepthBuffer,p=n.vertexTextures;let u=n.precision;const v={MeshDepthMaterial:"depth",MeshDistanceMaterial:"distanceRGBA",MeshNormalMaterial:"normal",MeshBasicMaterial:"basic",MeshLambertMaterial:"lambert",MeshPhongMaterial:"phong",MeshToonMaterial:"toon",MeshStandardMaterial:"physical",MeshPhysicalMaterial:"physical",MeshMatcapMaterial:"matcap",LineBasicMaterial:"basic",LineDashedMaterial:"dashed",PointsMaterial:"points",ShadowMaterial:"shadow",SpriteMaterial:"sprite"};function g(M){return c.add(M),M===0?"uv":`uv${M}`}function m(M,C,I,P,k){const A=P.fog,B=k.geometry,F=M.isMeshStandardMaterial?P.environment:null,H=(M.isMeshStandardMaterial?t:e).get(M.envMap||F),q=H&&H.mapping===Fp?H.image.height:null,G=v[M.type];M.precision!==null&&(u=n.getMaxPrecision(M.precision),u!==M.precision&&yt("WebGLProgram.getParameters:",M.precision,"not supported, using",u,"instead."));const re=B.morphAttributes.position||B.morphAttributes.normal||B.morphAttributes.color,Y=re!==void 0?re.length:0;let $=0;B.morphAttributes.position!==void 0&&($=1),B.morphAttributes.normal!==void 0&&($=2),B.morphAttributes.color!==void 0&&($=3);let _e,Te,be,J;if(G){const Qe=Gs[G];_e=Qe.vertexShader,Te=Qe.fragmentShader}else _e=M.vertexShader,Te=M.fragmentShader,l.update(M),be=l.getVertexShaderID(M),J=l.getFragmentShaderID(M);const oe=s.getRenderTarget(),ue=s.state.buffers.depth.getReversed(),Re=k.isInstancedMesh===!0,Ie=k.isBatchedMesh===!0,Ue=!!M.map,tt=!!M.matcap,je=!!H,D=!!M.aoMap,ae=!!M.lightMap,Q=!!M.bumpMap,W=!!M.normalMap,N=!!M.displacementMap,te=!!M.emissiveMap,de=!!M.metalnessMap,V=!!M.roughnessMap,ee=M.anisotropy>0,L=M.clearcoat>0,T=M.dispersion>0,U=M.iridescence>0,j=M.sheen>0,K=M.transmission>0,Z=ee&&!!M.anisotropyMap,Pe=L&&!!M.clearcoatMap,ve=L&&!!M.clearcoatNormalMap,ke=L&&!!M.clearcoatRoughnessMap,Fe=U&&!!M.iridescenceMap,le=U&&!!M.iridescenceThicknessMap,ye=j&&!!M.sheenColorMap,ze=j&&!!M.sheenRoughnessMap,Oe=!!M.specularMap,Se=!!M.specularColorMap,Xe=!!M.specularIntensityMap,z=K&&!!M.transmissionMap,xe=K&&!!M.thicknessMap,ge=!!M.gradientMap,Le=!!M.alphaMap,pe=M.alphaTest>0,ne=!!M.alphaHash,Ne=!!M.extensions;let Ge=ea;M.toneMapped&&(oe===null||oe.isXRRenderTarget===!0)&&(Ge=s.toneMapping);const pt={shaderID:G,shaderType:M.type,shaderName:M.name,vertexShader:_e,fragmentShader:Te,defines:M.defines,customVertexShaderID:be,customFragmentShaderID:J,isRawShaderMaterial:M.isRawShaderMaterial===!0,glslVersion:M.glslVersion,precision:u,batching:Ie,batchingColor:Ie&&k._colorsTexture!==null,instancing:Re,instancingColor:Re&&k.instanceColor!==null,instancingMorph:Re&&k.morphTexture!==null,supportsVertexTextures:p,outputColorSpace:oe===null?s.outputColorSpace:oe.isXRRenderTarget===!0?oe.texture.colorSpace:Ll,alphaToCoverage:!!M.alphaToCoverage,map:Ue,matcap:tt,envMap:je,envMapMode:je&&H.mapping,envMapCubeUVHeight:q,aoMap:D,lightMap:ae,bumpMap:Q,normalMap:W,displacementMap:p&&N,emissiveMap:te,normalMapObjectSpace:W&&M.normalMapType===RR,normalMapTangentSpace:W&&M.normalMapType===PR,metalnessMap:de,roughnessMap:V,anisotropy:ee,anisotropyMap:Z,clearcoat:L,clearcoatMap:Pe,clearcoatNormalMap:ve,clearcoatRoughnessMap:ke,dispersion:T,iridescence:U,iridescenceMap:Fe,iridescenceThicknessMap:le,sheen:j,sheenColorMap:ye,sheenRoughnessMap:ze,specularMap:Oe,specularColorMap:Se,specularIntensityMap:Xe,transmission:K,transmissionMap:z,thicknessMap:xe,gradientMap:ge,opaque:M.transparent===!1&&M.blending===Cl&&M.alphaToCoverage===!1,alphaMap:Le,alphaTest:pe,alphaHash:ne,combine:M.combine,mapUv:Ue&&g(M.map.channel),aoMapUv:D&&g(M.aoMap.channel),lightMapUv:ae&&g(M.lightMap.channel),bumpMapUv:Q&&g(M.bumpMap.channel),normalMapUv:W&&g(M.normalMap.channel),displacementMapUv:N&&g(M.displacementMap.channel),emissiveMapUv:te&&g(M.emissiveMap.channel),metalnessMapUv:de&&g(M.metalnessMap.channel),roughnessMapUv:V&&g(M.roughnessMap.channel),anisotropyMapUv:Z&&g(M.anisotropyMap.channel),clearcoatMapUv:Pe&&g(M.clearcoatMap.channel),clearcoatNormalMapUv:ve&&g(M.clearcoatNormalMap.channel),clearcoatRoughnessMapUv:ke&&g(M.clearcoatRoughnessMap.channel),iridescenceMapUv:Fe&&g(M.iridescenceMap.channel),iridescenceThicknessMapUv:le&&g(M.iridescenceThicknessMap.channel),sheenColorMapUv:ye&&g(M.sheenColorMap.channel),sheenRoughnessMapUv:ze&&g(M.sheenRoughnessMap.channel),specularMapUv:Oe&&g(M.specularMap.channel),specularColorMapUv:Se&&g(M.specularColorMap.channel),specularIntensityMapUv:Xe&&g(M.specularIntensityMap.channel),transmissionMapUv:z&&g(M.transmissionMap.channel),thicknessMapUv:xe&&g(M.thicknessMap.channel),alphaMapUv:Le&&g(M.alphaMap.channel),vertexTangents:!!B.attributes.tangent&&(W||ee),vertexColors:M.vertexColors,vertexAlphas:M.vertexColors===!0&&!!B.attributes.color&&B.attributes.color.itemSize===4,pointsUvs:k.isPoints===!0&&!!B.attributes.uv&&(Ue||Le),fog:!!A,useFog:M.fog===!0,fogExp2:!!A&&A.isFogExp2,flatShading:M.flatShading===!0&&M.wireframe===!1,sizeAttenuation:M.sizeAttenuation===!0,logarithmicDepthBuffer:d,reversedDepthBuffer:ue,skinning:k.isSkinnedMesh===!0,morphTargets:B.morphAttributes.position!==void 0,morphNormals:B.morphAttributes.normal!==void 0,morphColors:B.morphAttributes.color!==void 0,morphTargetsCount:Y,morphTextureStride:$,numDirLights:C.directional.length,numPointLights:C.point.length,numSpotLights:C.spot.length,numSpotLightMaps:C.spotLightMap.length,numRectAreaLights:C.rectArea.length,numHemiLights:C.hemi.length,numDirLightShadows:C.directionalShadowMap.length,numPointLightShadows:C.pointShadowMap.length,numSpotLightShadows:C.spotShadowMap.length,numSpotLightShadowsWithMaps:C.numSpotLightShadowsWithMaps,numLightProbes:C.numLightProbes,numClippingPlanes:a.numPlanes,numClipIntersection:a.numIntersection,dithering:M.dithering,shadowMapEnabled:s.shadowMap.enabled&&I.length>0,shadowMapType:s.shadowMap.type,toneMapping:Ge,decodeVideoTexture:Ue&&M.map.isVideoTexture===!0&&Ut.getTransfer(M.map.colorSpace)===Vt,decodeVideoTextureEmissive:te&&M.emissiveMap.isVideoTexture===!0&&Ut.getTransfer(M.emissiveMap.colorSpace)===Vt,premultipliedAlpha:M.premultipliedAlpha,doubleSided:M.side===or,flipSided:M.side===En,useDepthPacking:M.depthPacking>=0,depthPacking:M.depthPacking||0,index0AttributeName:M.index0AttributeName,extensionClipCullDistance:Ne&&M.extensions.clipCullDistance===!0&&i.has("WEBGL_clip_cull_distance"),extensionMultiDraw:(Ne&&M.extensions.multiDraw===!0||Ie)&&i.has("WEBGL_multi_draw"),rendererExtensionParallelShaderCompile:i.has("KHR_parallel_shader_compile"),customProgramCacheKey:M.customProgramCacheKey()};return pt.vertexUv1s=c.has(1),pt.vertexUv2s=c.has(2),pt.vertexUv3s=c.has(3),c.clear(),pt}function f(M){const C=[];if(M.shaderID?C.push(M.shaderID):(C.push(M.customVertexShaderID),C.push(M.customFragmentShaderID)),M.defines!==void 0)for(const I in M.defines)C.push(I),C.push(M.defines[I]);return M.isRawShaderMaterial===!1&&(y(C,M),x(C,M),C.push(s.outputColorSpace)),C.push(M.customProgramCacheKey),C.join()}function y(M,C){M.push(C.precision),M.push(C.outputColorSpace),M.push(C.envMapMode),M.push(C.envMapCubeUVHeight),M.push(C.mapUv),M.push(C.alphaMapUv),M.push(C.lightMapUv),M.push(C.aoMapUv),M.push(C.bumpMapUv),M.push(C.normalMapUv),M.push(C.displacementMapUv),M.push(C.emissiveMapUv),M.push(C.metalnessMapUv),M.push(C.roughnessMapUv),M.push(C.anisotropyMapUv),M.push(C.clearcoatMapUv),M.push(C.clearcoatNormalMapUv),M.push(C.clearcoatRoughnessMapUv),M.push(C.iridescenceMapUv),M.push(C.iridescenceThicknessMapUv),M.push(C.sheenColorMapUv),M.push(C.sheenRoughnessMapUv),M.push(C.specularMapUv),M.push(C.specularColorMapUv),M.push(C.specularIntensityMapUv),M.push(C.transmissionMapUv),M.push(C.thicknessMapUv),M.push(C.combine),M.push(C.fogExp2),M.push(C.sizeAttenuation),M.push(C.morphTargetsCount),M.push(C.morphAttributeCount),M.push(C.numDirLights),M.push(C.numPointLights),M.push(C.numSpotLights),M.push(C.numSpotLightMaps),M.push(C.numHemiLights),M.push(C.numRectAreaLights),M.push(C.numDirLightShadows),M.push(C.numPointLightShadows),M.push(C.numSpotLightShadows),M.push(C.numSpotLightShadowsWithMaps),M.push(C.numLightProbes),M.push(C.shadowMapType),M.push(C.toneMapping),M.push(C.numClippingPlanes),M.push(C.numClipIntersection),M.push(C.depthPacking)}function x(M,C){o.disableAll(),C.supportsVertexTextures&&o.enable(0),C.instancing&&o.enable(1),C.instancingColor&&o.enable(2),C.instancingMorph&&o.enable(3),C.matcap&&o.enable(4),C.envMap&&o.enable(5),C.normalMapObjectSpace&&o.enable(6),C.normalMapTangentSpace&&o.enable(7),C.clearcoat&&o.enable(8),C.iridescence&&o.enable(9),C.alphaTest&&o.enable(10),C.vertexColors&&o.enable(11),C.vertexAlphas&&o.enable(12),C.vertexUv1s&&o.enable(13),C.vertexUv2s&&o.enable(14),C.vertexUv3s&&o.enable(15),C.vertexTangents&&o.enable(16),C.anisotropy&&o.enable(17),C.alphaHash&&o.enable(18),C.batching&&o.enable(19),C.dispersion&&o.enable(20),C.batchingColor&&o.enable(21),C.gradientMap&&o.enable(22),M.push(o.mask),o.disableAll(),C.fog&&o.enable(0),C.useFog&&o.enable(1),C.flatShading&&o.enable(2),C.logarithmicDepthBuffer&&o.enable(3),C.reversedDepthBuffer&&o.enable(4),C.skinning&&o.enable(5),C.morphTargets&&o.enable(6),C.morphNormals&&o.enable(7),C.morphColors&&o.enable(8),C.premultipliedAlpha&&o.enable(9),C.shadowMapEnabled&&o.enable(10),C.doubleSided&&o.enable(11),C.flipSided&&o.enable(12),C.useDepthPacking&&o.enable(13),C.dithering&&o.enable(14),C.transmission&&o.enable(15),C.sheen&&o.enable(16),C.opaque&&o.enable(17),C.pointsUvs&&o.enable(18),C.decodeVideoTexture&&o.enable(19),C.decodeVideoTextureEmissive&&o.enable(20),C.alphaToCoverage&&o.enable(21),M.push(o.mask)}function _(M){const C=v[M.type];let I;if(C){const P=Gs[C];I=aI.clone(P.uniforms)}else I=M.uniforms;return I}function S(M,C){let I;for(let P=0,k=h.length;P0?i.push(f):u.transparent===!0?n.push(f):t.push(f)}function l(d,p,u,v,g,m){const f=a(d,p,u,v,g,m);u.transmission>0?i.unshift(f):u.transparent===!0?n.unshift(f):t.unshift(f)}function c(d,p){t.length>1&&t.sort(d||ON),i.length>1&&i.sort(p||YM),n.length>1&&n.sort(p||YM)}function h(){for(let d=e,p=s.length;d=r.length?(a=new $M,r.push(a)):a=r[n],a}function t(){s=new WeakMap}return{get:e,dispose:t}}function BN(){const s={};return{get:function(e){if(s[e.id]!==void 0)return s[e.id];let t;switch(e.type){case"DirectionalLight":t={direction:new De,color:new Wt};break;case"SpotLight":t={position:new De,direction:new De,color:new Wt,distance:0,coneCos:0,penumbraCos:0,decay:0};break;case"PointLight":t={position:new De,color:new Wt,distance:0,decay:0};break;case"HemisphereLight":t={direction:new De,skyColor:new Wt,groundColor:new Wt};break;case"RectAreaLight":t={color:new Wt,position:new De,halfWidth:new De,halfHeight:new De};break}return s[e.id]=t,t}}}function FN(){const s={};return{get:function(e){if(s[e.id]!==void 0)return s[e.id];let t;switch(e.type){case"DirectionalLight":t={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new Gt};break;case"SpotLight":t={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new Gt};break;case"PointLight":t={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new Gt,shadowCameraNear:1,shadowCameraFar:1e3};break}return s[e.id]=t,t}}}let zN=0;function HN(s,e){return(e.castShadow?2:0)-(s.castShadow?2:0)+(e.map?1:0)-(s.map?1:0)}function VN(s){const e=new BN,t=FN(),i={version:0,hash:{directionalLength:-1,pointLength:-1,spotLength:-1,rectAreaLength:-1,hemiLength:-1,numDirectionalShadows:-1,numPointShadows:-1,numSpotShadows:-1,numSpotMaps:-1,numLightProbes:-1},ambient:[0,0,0],probe:[],directional:[],directionalShadow:[],directionalShadowMap:[],directionalShadowMatrix:[],spot:[],spotLightMap:[],spotShadow:[],spotShadowMap:[],spotLightMatrix:[],rectArea:[],rectAreaLTC1:null,rectAreaLTC2:null,point:[],pointShadow:[],pointShadowMap:[],pointShadowMatrix:[],hemi:[],numSpotLightShadowsWithMaps:0,numLightProbes:0};for(let c=0;c<9;c++)i.probe.push(new De);const n=new De,r=new Di,a=new Di;function o(c){let h=0,d=0,p=0;for(let M=0;M<9;M++)i.probe[M].set(0,0,0);let u=0,v=0,g=0,m=0,f=0,y=0,x=0,_=0,S=0,b=0,E=0;c.sort(HN);for(let M=0,C=c.length;M0&&(s.has("OES_texture_float_linear")===!0?(i.rectAreaLTC1=Je.LTC_FLOAT_1,i.rectAreaLTC2=Je.LTC_FLOAT_2):(i.rectAreaLTC1=Je.LTC_HALF_1,i.rectAreaLTC2=Je.LTC_HALF_2)),i.ambient[0]=h,i.ambient[1]=d,i.ambient[2]=p;const w=i.hash;(w.directionalLength!==u||w.pointLength!==v||w.spotLength!==g||w.rectAreaLength!==m||w.hemiLength!==f||w.numDirectionalShadows!==y||w.numPointShadows!==x||w.numSpotShadows!==_||w.numSpotMaps!==S||w.numLightProbes!==E)&&(i.directional.length=u,i.spot.length=g,i.rectArea.length=m,i.point.length=v,i.hemi.length=f,i.directionalShadow.length=y,i.directionalShadowMap.length=y,i.pointShadow.length=x,i.pointShadowMap.length=x,i.spotShadow.length=_,i.spotShadowMap.length=_,i.directionalShadowMatrix.length=y,i.pointShadowMatrix.length=x,i.spotLightMatrix.length=_+S-b,i.spotLightMap.length=S,i.numSpotLightShadowsWithMaps=b,i.numLightProbes=E,w.directionalLength=u,w.pointLength=v,w.spotLength=g,w.rectAreaLength=m,w.hemiLength=f,w.numDirectionalShadows=y,w.numPointShadows=x,w.numSpotShadows=_,w.numSpotMaps=S,w.numLightProbes=E,i.version=zN++)}function l(c,h){let d=0,p=0,u=0,v=0,g=0;const m=h.matrixWorldInverse;for(let f=0,y=c.length;f=a.length?(o=new KM(s),a.push(o)):o=a[r],o}function i(){e=new WeakMap}return{get:t,dispose:i}}const WN=`void main() { gl_Position = vec4( position, 1.0 ); }`,XN=`uniform sampler2D shadow_pass; uniform vec2 resolution; uniform float radius; #include void main() { const float samples = float( VSM_SAMPLES ); float mean = 0.0; float squared_mean = 0.0; float uvStride = samples <= 1.0 ? 0.0 : 2.0 / ( samples - 1.0 ); float uvStart = samples <= 1.0 ? 0.0 : - 1.0; for ( float i = 0.0; i < samples; i ++ ) { float uvOffset = uvStart + i * uvStride; #ifdef HORIZONTAL_PASS vec2 distribution = unpackRGBATo2Half( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( uvOffset, 0.0 ) * radius ) / resolution ) ); mean += distribution.x; squared_mean += distribution.y * distribution.y + distribution.x * distribution.x; #else float depth = unpackRGBAToDepth( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( 0.0, uvOffset ) * radius ) / resolution ) ); mean += depth; squared_mean += depth * depth; #endif } mean = mean / samples; squared_mean = squared_mean / samples; float std_dev = sqrt( squared_mean - mean * mean ); gl_FragColor = pack2HalfToRGBA( vec2( mean, std_dev ) ); }`;function jN(s,e,t){let i=new _M;const n=new Gt,r=new Gt,a=new vi,o=new gI({depthPacking:AR}),l=new vI,c={},h=t.maxTextureSize,d={[Qr]:En,[En]:Qr,[or]:or},p=new yr({defines:{VSM_SAMPLES:8},uniforms:{shadow_pass:{value:null},resolution:{value:new Gt},radius:{value:4}},vertexShader:WN,fragmentShader:XN}),u=p.clone();u.defines.HORIZONTAL_PASS=1;const v=new oa;v.setAttribute("position",new Vs(new Float32Array([-1,-1,.5,3,-1,.5,-1,3,.5]),3));const g=new la(v,p),m=this;this.enabled=!1,this.autoUpdate=!0,this.needsUpdate=!1,this.type=Ab;let f=this.type;this.render=function(b,E,w){if(m.enabled===!1||m.autoUpdate===!1&&m.needsUpdate===!1||b.length===0)return;const M=s.getRenderTarget(),C=s.getActiveCubeFace(),I=s.getActiveMipmapLevel(),P=s.state;P.setBlending(lr),P.buffers.depth.getReversed()===!0?P.buffers.color.setClear(0,0,0,0):P.buffers.color.setClear(1,1,1,1),P.buffers.depth.setTest(!0),P.setScissorTest(!1);const k=f!==ar&&this.type===ar,A=f===ar&&this.type!==ar;for(let B=0,F=b.length;Bh||n.y>h)&&(n.x>h&&(r.x=Math.floor(h/G.x),n.x=r.x*G.x,q.mapSize.x=r.x),n.y>h&&(r.y=Math.floor(h/G.y),n.y=r.y*G.y,q.mapSize.y=r.y)),q.map===null||k===!0||A===!0){const Y=this.type!==ar?{minFilter:Fn,magFilter:Fn}:{};q.map!==null&&q.map.dispose(),q.map=new ao(n.x,n.y,Y),q.map.texture.name=H.name+".shadowMap",q.camera.updateProjectionMatrix()}s.setRenderTarget(q.map),s.clear();const re=q.getViewportCount();for(let Y=0;Y0||E.map&&E.alphaTest>0||E.alphaToCoverage===!0){const P=C.uuid,k=E.uuid;let A=c[P];A===void 0&&(A={},c[P]=A);let B=A[k];B===void 0&&(B=C.clone(),A[k]=B,E.addEventListener("dispose",S)),C=B}if(C.visible=E.visible,C.wireframe=E.wireframe,M===ar?C.side=E.shadowSide!==null?E.shadowSide:E.side:C.side=E.shadowSide!==null?E.shadowSide:d[E.side],C.alphaMap=E.alphaMap,C.alphaTest=E.alphaToCoverage===!0?.5:E.alphaTest,C.map=E.map,C.clipShadows=E.clipShadows,C.clippingPlanes=E.clippingPlanes,C.clipIntersection=E.clipIntersection,C.displacementMap=E.displacementMap,C.displacementScale=E.displacementScale,C.displacementBias=E.displacementBias,C.wireframeLinewidth=E.wireframeLinewidth,C.linewidth=E.linewidth,w.isPointLight===!0&&C.isMeshDistanceMaterial===!0){const P=s.properties.get(C);P.light=w}return C}function _(b,E,w,M,C){if(b.visible===!1)return;if(b.layers.test(E.layers)&&(b.isMesh||b.isLine||b.isPoints)&&(b.castShadow||b.receiveShadow&&C===ar)&&(!b.frustumCulled||i.intersectsObject(b))){b.modelViewMatrix.multiplyMatrices(w.matrixWorldInverse,b.matrixWorld);const P=e.update(b),k=b.material;if(Array.isArray(k)){const A=P.groups;for(let B=0,F=A.length;B=1):q.indexOf("OpenGL ES")!==-1&&(H=parseFloat(/^OpenGL ES (\d)/.exec(q)[1]),F=H>=2);let G=null,re={};const Y=s.getParameter(s.SCISSOR_BOX),$=s.getParameter(s.VIEWPORT),_e=new vi().fromArray(Y),Te=new vi().fromArray($);function be(z,xe,ge,Le){const pe=new Uint8Array(4),ne=s.createTexture();s.bindTexture(z,ne),s.texParameteri(z,s.TEXTURE_MIN_FILTER,s.NEAREST),s.texParameteri(z,s.TEXTURE_MAG_FILTER,s.NEAREST);for(let Ne=0;Ne"u"?!1:/OculusBrowser/g.test(navigator.userAgent),c=new Gt,h=new WeakMap;let d;const p=new WeakMap;let u=!1;try{u=typeof OffscreenCanvas<"u"&&new OffscreenCanvas(1,1).getContext("2d")!==null}catch{}function v(L,T){return u?new OffscreenCanvas(L,T):qp("canvas")}function g(L,T,U){let j=1;const K=ee(L);if((K.width>U||K.height>U)&&(j=U/Math.max(K.width,K.height)),j<1)if(typeof HTMLImageElement<"u"&&L instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&L instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&L instanceof ImageBitmap||typeof VideoFrame<"u"&&L instanceof VideoFrame){const Z=Math.floor(j*K.width),Pe=Math.floor(j*K.height);d===void 0&&(d=v(Z,Pe));const ve=T?v(Z,Pe):d;return ve.width=Z,ve.height=Pe,ve.getContext("2d").drawImage(L,0,0,Z,Pe),yt("WebGLRenderer: Texture has been resized from ("+K.width+"x"+K.height+") to ("+Z+"x"+Pe+")."),ve}else return"data"in L&&yt("WebGLRenderer: Image in DataTexture is too big ("+K.width+"x"+K.height+")."),L;return L}function m(L){return L.generateMipmaps}function f(L){s.generateMipmap(L)}function y(L){return L.isWebGLCubeRenderTarget?s.TEXTURE_CUBE_MAP:L.isWebGL3DRenderTarget?s.TEXTURE_3D:L.isWebGLArrayRenderTarget||L.isCompressedArrayTexture?s.TEXTURE_2D_ARRAY:s.TEXTURE_2D}function x(L,T,U,j,K=!1){if(L!==null){if(s[L]!==void 0)return s[L];yt("WebGLRenderer: Attempt to use non-existing WebGL internal format '"+L+"'")}let Z=T;if(T===s.RED&&(U===s.FLOAT&&(Z=s.R32F),U===s.HALF_FLOAT&&(Z=s.R16F),U===s.UNSIGNED_BYTE&&(Z=s.R8)),T===s.RED_INTEGER&&(U===s.UNSIGNED_BYTE&&(Z=s.R8UI),U===s.UNSIGNED_SHORT&&(Z=s.R16UI),U===s.UNSIGNED_INT&&(Z=s.R32UI),U===s.BYTE&&(Z=s.R8I),U===s.SHORT&&(Z=s.R16I),U===s.INT&&(Z=s.R32I)),T===s.RG&&(U===s.FLOAT&&(Z=s.RG32F),U===s.HALF_FLOAT&&(Z=s.RG16F),U===s.UNSIGNED_BYTE&&(Z=s.RG8)),T===s.RG_INTEGER&&(U===s.UNSIGNED_BYTE&&(Z=s.RG8UI),U===s.UNSIGNED_SHORT&&(Z=s.RG16UI),U===s.UNSIGNED_INT&&(Z=s.RG32UI),U===s.BYTE&&(Z=s.RG8I),U===s.SHORT&&(Z=s.RG16I),U===s.INT&&(Z=s.RG32I)),T===s.RGB_INTEGER&&(U===s.UNSIGNED_BYTE&&(Z=s.RGB8UI),U===s.UNSIGNED_SHORT&&(Z=s.RGB16UI),U===s.UNSIGNED_INT&&(Z=s.RGB32UI),U===s.BYTE&&(Z=s.RGB8I),U===s.SHORT&&(Z=s.RGB16I),U===s.INT&&(Z=s.RGB32I)),T===s.RGBA_INTEGER&&(U===s.UNSIGNED_BYTE&&(Z=s.RGBA8UI),U===s.UNSIGNED_SHORT&&(Z=s.RGBA16UI),U===s.UNSIGNED_INT&&(Z=s.RGBA32UI),U===s.BYTE&&(Z=s.RGBA8I),U===s.SHORT&&(Z=s.RGBA16I),U===s.INT&&(Z=s.RGBA32I)),T===s.RGB&&(U===s.UNSIGNED_INT_5_9_9_9_REV&&(Z=s.RGB9_E5),U===s.UNSIGNED_INT_10F_11F_11F_REV&&(Z=s.R11F_G11F_B10F)),T===s.RGBA){const Pe=K?Xp:Ut.getTransfer(j);U===s.FLOAT&&(Z=s.RGBA32F),U===s.HALF_FLOAT&&(Z=s.RGBA16F),U===s.UNSIGNED_BYTE&&(Z=Pe===Vt?s.SRGB8_ALPHA8:s.RGBA8),U===s.UNSIGNED_SHORT_4_4_4_4&&(Z=s.RGBA4),U===s.UNSIGNED_SHORT_5_5_5_1&&(Z=s.RGB5_A1)}return(Z===s.R16F||Z===s.R32F||Z===s.RG16F||Z===s.RG32F||Z===s.RGBA16F||Z===s.RGBA32F)&&e.get("EXT_color_buffer_float"),Z}function _(L,T){let U;return L?T===null||T===ro||T===vh?U=s.DEPTH24_STENCIL8:T===dr?U=s.DEPTH32F_STENCIL8:T===gh&&(U=s.DEPTH24_STENCIL8,yt("DepthTexture: 16 bit depth attachment is not supported with stencil. Using 24-bit attachment.")):T===null||T===ro||T===vh?U=s.DEPTH_COMPONENT24:T===dr?U=s.DEPTH_COMPONENT32F:T===gh&&(U=s.DEPTH_COMPONENT16),U}function S(L,T){return m(L)===!0||L.isFramebufferTexture&&L.minFilter!==Fn&&L.minFilter!==es?Math.log2(Math.max(T.width,T.height))+1:L.mipmaps!==void 0&&L.mipmaps.length>0?L.mipmaps.length:L.isCompressedTexture&&Array.isArray(L.image)?T.mipmaps.length:1}function b(L){const T=L.target;T.removeEventListener("dispose",b),w(T),T.isVideoTexture&&h.delete(T)}function E(L){const T=L.target;T.removeEventListener("dispose",E),C(T)}function w(L){const T=i.get(L);if(T.__webglInit===void 0)return;const U=L.source,j=p.get(U);if(j){const K=j[T.__cacheKey];K.usedTimes--,K.usedTimes===0&&M(L),Object.keys(j).length===0&&p.delete(U)}i.remove(L)}function M(L){const T=i.get(L);s.deleteTexture(T.__webglTexture);const U=L.source,j=p.get(U);delete j[T.__cacheKey],a.memory.textures--}function C(L){const T=i.get(L);if(L.depthTexture&&(L.depthTexture.dispose(),i.remove(L.depthTexture)),L.isWebGLCubeRenderTarget)for(let j=0;j<6;j++){if(Array.isArray(T.__webglFramebuffer[j]))for(let K=0;K=n.maxTextures&&yt("WebGLTextures: Trying to use "+L+" texture units while this GPU supports only "+n.maxTextures),I+=1,L}function A(L){const T=[];return T.push(L.wrapS),T.push(L.wrapT),T.push(L.wrapR||0),T.push(L.magFilter),T.push(L.minFilter),T.push(L.anisotropy),T.push(L.internalFormat),T.push(L.format),T.push(L.type),T.push(L.generateMipmaps),T.push(L.premultiplyAlpha),T.push(L.flipY),T.push(L.unpackAlignment),T.push(L.colorSpace),T.join()}function B(L,T){const U=i.get(L);if(L.isVideoTexture&&de(L),L.isRenderTargetTexture===!1&&L.isExternalTexture!==!0&&L.version>0&&U.__version!==L.version){const j=L.image;if(j===null)yt("WebGLRenderer: Texture marked for update but no image data found.");else if(j.complete===!1)yt("WebGLRenderer: Texture marked for update but image is incomplete");else{J(U,L,T);return}}else L.isExternalTexture&&(U.__webglTexture=L.sourceTexture?L.sourceTexture:null);t.bindTexture(s.TEXTURE_2D,U.__webglTexture,s.TEXTURE0+T)}function F(L,T){const U=i.get(L);if(L.isRenderTargetTexture===!1&&L.version>0&&U.__version!==L.version){J(U,L,T);return}else L.isExternalTexture&&(U.__webglTexture=L.sourceTexture?L.sourceTexture:null);t.bindTexture(s.TEXTURE_2D_ARRAY,U.__webglTexture,s.TEXTURE0+T)}function H(L,T){const U=i.get(L);if(L.isRenderTargetTexture===!1&&L.version>0&&U.__version!==L.version){J(U,L,T);return}t.bindTexture(s.TEXTURE_3D,U.__webglTexture,s.TEXTURE0+T)}function q(L,T){const U=i.get(L);if(L.version>0&&U.__version!==L.version){oe(U,L,T);return}t.bindTexture(s.TEXTURE_CUBE_MAP,U.__webglTexture,s.TEXTURE0+T)}const G={[I0]:s.REPEAT,[cr]:s.CLAMP_TO_EDGE,[L0]:s.MIRRORED_REPEAT},re={[Fn]:s.NEAREST,[TR]:s.NEAREST_MIPMAP_NEAREST,[zp]:s.NEAREST_MIPMAP_LINEAR,[es]:s.LINEAR,[D0]:s.LINEAR_MIPMAP_NEAREST,[so]:s.LINEAR_MIPMAP_LINEAR},Y={[IR]:s.NEVER,[UR]:s.ALWAYS,[LR]:s.LESS,[Gb]:s.LEQUAL,[DR]:s.EQUAL,[OR]:s.GEQUAL,[NR]:s.GREATER,[kR]:s.NOTEQUAL};function $(L,T){if(T.type===dr&&e.has("OES_texture_float_linear")===!1&&(T.magFilter===es||T.magFilter===D0||T.magFilter===zp||T.magFilter===so||T.minFilter===es||T.minFilter===D0||T.minFilter===zp||T.minFilter===so)&&yt("WebGLRenderer: Unable to use linear filtering with floating point textures. OES_texture_float_linear not supported on this device."),s.texParameteri(L,s.TEXTURE_WRAP_S,G[T.wrapS]),s.texParameteri(L,s.TEXTURE_WRAP_T,G[T.wrapT]),(L===s.TEXTURE_3D||L===s.TEXTURE_2D_ARRAY)&&s.texParameteri(L,s.TEXTURE_WRAP_R,G[T.wrapR]),s.texParameteri(L,s.TEXTURE_MAG_FILTER,re[T.magFilter]),s.texParameteri(L,s.TEXTURE_MIN_FILTER,re[T.minFilter]),T.compareFunction&&(s.texParameteri(L,s.TEXTURE_COMPARE_MODE,s.COMPARE_REF_TO_TEXTURE),s.texParameteri(L,s.TEXTURE_COMPARE_FUNC,Y[T.compareFunction])),e.has("EXT_texture_filter_anisotropic")===!0){if(T.magFilter===Fn||T.minFilter!==zp&&T.minFilter!==so||T.type===dr&&e.has("OES_texture_float_linear")===!1)return;if(T.anisotropy>1||i.get(T).__currentAnisotropy){const U=e.get("EXT_texture_filter_anisotropic");s.texParameterf(L,U.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(T.anisotropy,n.getMaxAnisotropy())),i.get(T).__currentAnisotropy=T.anisotropy}}}function _e(L,T){let U=!1;L.__webglInit===void 0&&(L.__webglInit=!0,T.addEventListener("dispose",b));const j=T.source;let K=p.get(j);K===void 0&&(K={},p.set(j,K));const Z=A(T);if(Z!==L.__cacheKey){K[Z]===void 0&&(K[Z]={texture:s.createTexture(),usedTimes:0},a.memory.textures++,U=!0),K[Z].usedTimes++;const Pe=K[L.__cacheKey];Pe!==void 0&&(K[L.__cacheKey].usedTimes--,Pe.usedTimes===0&&M(T)),L.__cacheKey=Z,L.__webglTexture=K[Z].texture}return U}function Te(L,T,U){return Math.floor(Math.floor(L/U)/T)}function be(L,T,U,j){const K=L.updateRanges;if(K.length===0)t.texSubImage2D(s.TEXTURE_2D,0,0,0,T.width,T.height,U,j,T.data);else{K.sort((Fe,le)=>Fe.start-le.start);let Z=0;for(let Fe=1;Fe0){z&&xe&&t.texStorage2D(s.TEXTURE_2D,Le,Oe,Xe[0].width,Xe[0].height);for(let pe=0,ne=Xe.length;pe0){const Ne=SM(Se.width,Se.height,T.format,T.type);for(const Ge of T.layerUpdates){const pt=Se.data.subarray(Ge*Ne/Se.data.BYTES_PER_ELEMENT,(Ge+1)*Ne/Se.data.BYTES_PER_ELEMENT);t.compressedTexSubImage3D(s.TEXTURE_2D_ARRAY,pe,0,0,Ge,Se.width,Se.height,1,ye,pt)}T.clearLayerUpdates()}else t.compressedTexSubImage3D(s.TEXTURE_2D_ARRAY,pe,0,0,0,Se.width,Se.height,le.depth,ye,Se.data)}else t.compressedTexImage3D(s.TEXTURE_2D_ARRAY,pe,Oe,Se.width,Se.height,le.depth,0,Se.data,0,0);else yt("WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()");else z?ge&&t.texSubImage3D(s.TEXTURE_2D_ARRAY,pe,0,0,0,Se.width,Se.height,le.depth,ye,ze,Se.data):t.texImage3D(s.TEXTURE_2D_ARRAY,pe,Oe,Se.width,Se.height,le.depth,0,ye,ze,Se.data)}else{z&&xe&&t.texStorage2D(s.TEXTURE_2D,Le,Oe,Xe[0].width,Xe[0].height);for(let pe=0,ne=Xe.length;pe0){const pe=SM(le.width,le.height,T.format,T.type);for(const ne of T.layerUpdates){const Ne=le.data.subarray(ne*pe/le.data.BYTES_PER_ELEMENT,(ne+1)*pe/le.data.BYTES_PER_ELEMENT);t.texSubImage3D(s.TEXTURE_2D_ARRAY,0,0,0,ne,le.width,le.height,1,ye,ze,Ne)}T.clearLayerUpdates()}else t.texSubImage3D(s.TEXTURE_2D_ARRAY,0,0,0,0,le.width,le.height,le.depth,ye,ze,le.data)}else t.texImage3D(s.TEXTURE_2D_ARRAY,0,Oe,le.width,le.height,le.depth,0,ye,ze,le.data);else if(T.isData3DTexture)z?(xe&&t.texStorage3D(s.TEXTURE_3D,Le,Oe,le.width,le.height,le.depth),ge&&t.texSubImage3D(s.TEXTURE_3D,0,0,0,0,le.width,le.height,le.depth,ye,ze,le.data)):t.texImage3D(s.TEXTURE_3D,0,Oe,le.width,le.height,le.depth,0,ye,ze,le.data);else if(T.isFramebufferTexture){if(xe)if(z)t.texStorage2D(s.TEXTURE_2D,Le,Oe,le.width,le.height);else{let pe=le.width,ne=le.height;for(let Ne=0;Ne>=1,ne>>=1}}else if(Xe.length>0){if(z&&xe){const pe=ee(Xe[0]);t.texStorage2D(s.TEXTURE_2D,Le,Oe,pe.width,pe.height)}for(let pe=0,ne=Xe.length;pe0&&Le++;const ne=ee(ye[0]);t.texStorage2D(s.TEXTURE_CUBE_MAP,Le,Xe,ne.width,ne.height)}for(let ne=0;ne<6;ne++)if(le){z?ge&&t.texSubImage2D(s.TEXTURE_CUBE_MAP_POSITIVE_X+ne,0,0,0,ye[ne].width,ye[ne].height,Oe,Se,ye[ne].data):t.texImage2D(s.TEXTURE_CUBE_MAP_POSITIVE_X+ne,0,Xe,ye[ne].width,ye[ne].height,0,Oe,Se,ye[ne].data);for(let Ne=0;Ne>Z),ze=Math.max(1,T.height>>Z);K===s.TEXTURE_3D||K===s.TEXTURE_2D_ARRAY?t.texImage3D(K,Z,ke,ye,ze,T.depth,0,Pe,ve,null):t.texImage2D(K,Z,ke,ye,ze,0,Pe,ve,null)}t.bindFramebuffer(s.FRAMEBUFFER,L),te(T)?o.framebufferTexture2DMultisampleEXT(s.FRAMEBUFFER,j,K,le.__webglTexture,0,N(T)):(K===s.TEXTURE_2D||K>=s.TEXTURE_CUBE_MAP_POSITIVE_X&&K<=s.TEXTURE_CUBE_MAP_NEGATIVE_Z)&&s.framebufferTexture2D(s.FRAMEBUFFER,j,K,le.__webglTexture,Z),t.bindFramebuffer(s.FRAMEBUFFER,null)}function Re(L,T,U){if(s.bindRenderbuffer(s.RENDERBUFFER,L),T.depthBuffer){const j=T.depthTexture,K=j&&j.isDepthTexture?j.type:null,Z=_(T.stencilBuffer,K),Pe=T.stencilBuffer?s.DEPTH_STENCIL_ATTACHMENT:s.DEPTH_ATTACHMENT,ve=N(T);te(T)?o.renderbufferStorageMultisampleEXT(s.RENDERBUFFER,ve,Z,T.width,T.height):U?s.renderbufferStorageMultisample(s.RENDERBUFFER,ve,Z,T.width,T.height):s.renderbufferStorage(s.RENDERBUFFER,Z,T.width,T.height),s.framebufferRenderbuffer(s.FRAMEBUFFER,Pe,s.RENDERBUFFER,L)}else{const j=T.textures;for(let K=0;K{delete T.__boundDepthTexture,delete T.__depthDisposeCallback,j.removeEventListener("dispose",K)};j.addEventListener("dispose",K),T.__depthDisposeCallback=K}T.__boundDepthTexture=j}if(L.depthTexture&&!T.__autoAllocateDepthBuffer){if(U)throw new Error("target.depthTexture not supported in Cube render targets");const j=L.texture.mipmaps;j&&j.length>0?Ie(T.__webglFramebuffer[0],L):Ie(T.__webglFramebuffer,L)}else if(U){T.__webglDepthbuffer=[];for(let j=0;j<6;j++)if(t.bindFramebuffer(s.FRAMEBUFFER,T.__webglFramebuffer[j]),T.__webglDepthbuffer[j]===void 0)T.__webglDepthbuffer[j]=s.createRenderbuffer(),Re(T.__webglDepthbuffer[j],L,!1);else{const K=L.stencilBuffer?s.DEPTH_STENCIL_ATTACHMENT:s.DEPTH_ATTACHMENT,Z=T.__webglDepthbuffer[j];s.bindRenderbuffer(s.RENDERBUFFER,Z),s.framebufferRenderbuffer(s.FRAMEBUFFER,K,s.RENDERBUFFER,Z)}}else{const j=L.texture.mipmaps;if(j&&j.length>0?t.bindFramebuffer(s.FRAMEBUFFER,T.__webglFramebuffer[0]):t.bindFramebuffer(s.FRAMEBUFFER,T.__webglFramebuffer),T.__webglDepthbuffer===void 0)T.__webglDepthbuffer=s.createRenderbuffer(),Re(T.__webglDepthbuffer,L,!1);else{const K=L.stencilBuffer?s.DEPTH_STENCIL_ATTACHMENT:s.DEPTH_ATTACHMENT,Z=T.__webglDepthbuffer;s.bindRenderbuffer(s.RENDERBUFFER,Z),s.framebufferRenderbuffer(s.FRAMEBUFFER,K,s.RENDERBUFFER,Z)}}t.bindFramebuffer(s.FRAMEBUFFER,null)}function tt(L,T,U){const j=i.get(L);T!==void 0&&ue(j.__webglFramebuffer,L,L.texture,s.COLOR_ATTACHMENT0,s.TEXTURE_2D,0),U!==void 0&&Ue(L)}function je(L){const T=L.texture,U=i.get(L),j=i.get(T);L.addEventListener("dispose",E);const K=L.textures,Z=L.isWebGLCubeRenderTarget===!0,Pe=K.length>1;if(Pe||(j.__webglTexture===void 0&&(j.__webglTexture=s.createTexture()),j.__version=T.version,a.memory.textures++),Z){U.__webglFramebuffer=[];for(let ve=0;ve<6;ve++)if(T.mipmaps&&T.mipmaps.length>0){U.__webglFramebuffer[ve]=[];for(let ke=0;ke0){U.__webglFramebuffer=[];for(let ve=0;ve0&&te(L)===!1){U.__webglMultisampledFramebuffer=s.createFramebuffer(),U.__webglColorRenderbuffer=[],t.bindFramebuffer(s.FRAMEBUFFER,U.__webglMultisampledFramebuffer);for(let ve=0;ve0)for(let ke=0;ke0)for(let ke=0;ke0){if(te(L)===!1){const T=L.textures,U=L.width,j=L.height;let K=s.COLOR_BUFFER_BIT;const Z=L.stencilBuffer?s.DEPTH_STENCIL_ATTACHMENT:s.DEPTH_ATTACHMENT,Pe=i.get(L),ve=T.length>1;if(ve)for(let Fe=0;Fe0?t.bindFramebuffer(s.DRAW_FRAMEBUFFER,Pe.__webglFramebuffer[0]):t.bindFramebuffer(s.DRAW_FRAMEBUFFER,Pe.__webglFramebuffer);for(let Fe=0;Fe0&&e.has("WEBGL_multisampled_render_to_texture")===!0&&T.__useRenderToTexture!==!1}function de(L){const T=a.render.frame;h.get(L)!==T&&(h.set(L,T),L.update())}function V(L,T){const U=L.colorSpace,j=L.format,K=L.type;return L.isCompressedTexture===!0||L.isVideoTexture===!0||U!==Ll&&U!==ta&&(Ut.getTransfer(U)===Vt?(j!==xs||K!==hr)&&yt("WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType."):gi("WebGLTextures: Unsupported texture color space:",U)),T}function ee(L){return typeof HTMLImageElement<"u"&&L instanceof HTMLImageElement?(c.width=L.naturalWidth||L.width,c.height=L.naturalHeight||L.height):typeof VideoFrame<"u"&&L instanceof VideoFrame?(c.width=L.displayWidth,c.height=L.displayHeight):(c.width=L.width,c.height=L.height),c}this.allocateTextureUnit=k,this.resetTextureUnits=P,this.setTexture2D=B,this.setTexture2DArray=F,this.setTexture3D=H,this.setTextureCube=q,this.rebindTextures=tt,this.setupRenderTarget=je,this.updateRenderTargetMipmap=D,this.updateMultisampleRenderTarget=W,this.setupDepthRenderbuffer=Ue,this.setupFrameBufferTexture=ue,this.useMultisampledRTT=te}function $N(s,e){function t(i,n=ta){let r;const a=Ut.getTransfer(n);if(i===hr)return s.UNSIGNED_BYTE;if(i===k0)return s.UNSIGNED_SHORT_4_4_4_4;if(i===O0)return s.UNSIGNED_SHORT_5_5_5_1;if(i===Ub)return s.UNSIGNED_INT_5_9_9_9_REV;if(i===Bb)return s.UNSIGNED_INT_10F_11F_11F_REV;if(i===kb)return s.BYTE;if(i===Ob)return s.SHORT;if(i===gh)return s.UNSIGNED_SHORT;if(i===N0)return s.INT;if(i===ro)return s.UNSIGNED_INT;if(i===dr)return s.FLOAT;if(i===Il)return s.HALF_FLOAT;if(i===Fb)return s.ALPHA;if(i===zb)return s.RGB;if(i===xs)return s.RGBA;if(i===yh)return s.DEPTH_COMPONENT;if(i===xh)return s.DEPTH_STENCIL;if(i===Hb)return s.RED;if(i===U0)return s.RED_INTEGER;if(i===B0)return s.RG;if(i===F0)return s.RG_INTEGER;if(i===z0)return s.RGBA_INTEGER;if(i===Hp||i===Vp||i===Gp||i===Wp)if(a===Vt)if(r=e.get("WEBGL_compressed_texture_s3tc_srgb"),r!==null){if(i===Hp)return r.COMPRESSED_SRGB_S3TC_DXT1_EXT;if(i===Vp)return r.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;if(i===Gp)return r.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;if(i===Wp)return r.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}else return null;else if(r=e.get("WEBGL_compressed_texture_s3tc"),r!==null){if(i===Hp)return r.COMPRESSED_RGB_S3TC_DXT1_EXT;if(i===Vp)return r.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(i===Gp)return r.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(i===Wp)return r.COMPRESSED_RGBA_S3TC_DXT5_EXT}else return null;if(i===H0||i===V0||i===G0||i===W0)if(r=e.get("WEBGL_compressed_texture_pvrtc"),r!==null){if(i===H0)return r.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(i===V0)return r.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(i===G0)return r.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(i===W0)return r.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}else return null;if(i===X0||i===j0||i===q0)if(r=e.get("WEBGL_compressed_texture_etc"),r!==null){if(i===X0||i===j0)return a===Vt?r.COMPRESSED_SRGB8_ETC2:r.COMPRESSED_RGB8_ETC2;if(i===q0)return a===Vt?r.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:r.COMPRESSED_RGBA8_ETC2_EAC}else return null;if(i===Z0||i===Y0||i===$0||i===K0||i===J0||i===Q0||i===ev||i===tv||i===iv||i===nv||i===sv||i===rv||i===av||i===ov)if(r=e.get("WEBGL_compressed_texture_astc"),r!==null){if(i===Z0)return a===Vt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:r.COMPRESSED_RGBA_ASTC_4x4_KHR;if(i===Y0)return a===Vt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:r.COMPRESSED_RGBA_ASTC_5x4_KHR;if(i===$0)return a===Vt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:r.COMPRESSED_RGBA_ASTC_5x5_KHR;if(i===K0)return a===Vt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:r.COMPRESSED_RGBA_ASTC_6x5_KHR;if(i===J0)return a===Vt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:r.COMPRESSED_RGBA_ASTC_6x6_KHR;if(i===Q0)return a===Vt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:r.COMPRESSED_RGBA_ASTC_8x5_KHR;if(i===ev)return a===Vt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:r.COMPRESSED_RGBA_ASTC_8x6_KHR;if(i===tv)return a===Vt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:r.COMPRESSED_RGBA_ASTC_8x8_KHR;if(i===iv)return a===Vt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:r.COMPRESSED_RGBA_ASTC_10x5_KHR;if(i===nv)return a===Vt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:r.COMPRESSED_RGBA_ASTC_10x6_KHR;if(i===sv)return a===Vt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:r.COMPRESSED_RGBA_ASTC_10x8_KHR;if(i===rv)return a===Vt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:r.COMPRESSED_RGBA_ASTC_10x10_KHR;if(i===av)return a===Vt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:r.COMPRESSED_RGBA_ASTC_12x10_KHR;if(i===ov)return a===Vt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:r.COMPRESSED_RGBA_ASTC_12x12_KHR}else return null;if(i===lv||i===cv||i===hv)if(r=e.get("EXT_texture_compression_bptc"),r!==null){if(i===lv)return a===Vt?r.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT:r.COMPRESSED_RGBA_BPTC_UNORM_EXT;if(i===cv)return r.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT;if(i===hv)return r.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT}else return null;if(i===dv||i===uv||i===pv||i===fv)if(r=e.get("EXT_texture_compression_rgtc"),r!==null){if(i===dv)return r.COMPRESSED_RED_RGTC1_EXT;if(i===uv)return r.COMPRESSED_SIGNED_RED_RGTC1_EXT;if(i===pv)return r.COMPRESSED_RED_GREEN_RGTC2_EXT;if(i===fv)return r.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT}else return null;return i===vh?s.UNSIGNED_INT_24_8:s[i]!==void 0?s[i]:null}return{convert:t}}const KN=` void main() { gl_Position = vec4( position, 1.0 ); }`,JN=` uniform sampler2DArray depthColor; uniform float depthWidth; uniform float depthHeight; void main() { vec2 coord = vec2( gl_FragCoord.x / depthWidth, gl_FragCoord.y / depthHeight ); if ( coord.x >= 1.0 ) { gl_FragDepth = texture( depthColor, vec3( coord.x - 1.0, coord.y, 1 ) ).r; } else { gl_FragDepth = texture( depthColor, vec3( coord.x, coord.y, 0 ) ).r; } }`;class QN{constructor(){this.texture=null,this.mesh=null,this.depthNear=0,this.depthFar=0}init(e,t){if(this.texture===null){const i=new MM(e.texture);(e.depthNear!==t.depthNear||e.depthFar!==t.depthFar)&&(this.depthNear=e.depthNear,this.depthFar=e.depthFar),this.texture=i}}getMesh(e){if(this.texture!==null&&this.mesh===null){const t=e.cameras[0].viewport,i=new yr({vertexShader:KN,fragmentShader:JN,uniforms:{depthColor:{value:this.texture},depthWidth:{value:t.z},depthHeight:{value:t.w}}});this.mesh=new la(new ff(20,20),i)}return this.mesh}reset(){this.texture=null,this.mesh=null}getDepthTexture(){return this.texture}}class e8 extends Nl{constructor(e,t){super();const i=this;let n=null,r=1,a=null,o="local-floor",l=1,c=null,h=null,d=null,p=null,u=null,v=null;const g=typeof XRWebGLBinding<"u",m=new QN,f={},y=t.getContextAttributes();let x=null,_=null;const S=[],b=[],E=new Gt;let w=null;const M=new ws;M.viewport=new vi;const C=new ws;C.viewport=new vi;const I=[M,C],P=new xI;let k=null,A=null;this.cameraAutoUpdate=!0,this.enabled=!1,this.isPresenting=!1,this.getController=function(J){let oe=S[J];return oe===void 0&&(oe=new zv,S[J]=oe),oe.getTargetRaySpace()},this.getControllerGrip=function(J){let oe=S[J];return oe===void 0&&(oe=new zv,S[J]=oe),oe.getGripSpace()},this.getHand=function(J){let oe=S[J];return oe===void 0&&(oe=new zv,S[J]=oe),oe.getHandSpace()};function B(J){const oe=b.indexOf(J.inputSource);if(oe===-1)return;const ue=S[oe];ue!==void 0&&(ue.update(J.inputSource,J.frame,c||a),ue.dispatchEvent({type:J.type,data:J.inputSource}))}function F(){n.removeEventListener("select",B),n.removeEventListener("selectstart",B),n.removeEventListener("selectend",B),n.removeEventListener("squeeze",B),n.removeEventListener("squeezestart",B),n.removeEventListener("squeezeend",B),n.removeEventListener("end",F),n.removeEventListener("inputsourceschange",H);for(let J=0;J=0&&(b[Re]=null,S[Re].disconnect(ue))}for(let oe=0;oe=b.length){b.push(ue),Re=Ue;break}else if(b[Ue]===null){b[Ue]=ue,Re=Ue;break}if(Re===-1)break}const Ie=S[Re];Ie&&Ie.connect(ue)}}const q=new De,G=new De;function re(J,oe,ue){q.setFromMatrixPosition(oe.matrixWorld),G.setFromMatrixPosition(ue.matrixWorld);const Re=q.distanceTo(G),Ie=oe.projectionMatrix.elements,Ue=ue.projectionMatrix.elements,tt=Ie[14]/(Ie[10]-1),je=Ie[14]/(Ie[10]+1),D=(Ie[9]+1)/Ie[5],ae=(Ie[9]-1)/Ie[5],Q=(Ie[8]-1)/Ie[0],W=(Ue[8]+1)/Ue[0],N=tt*Q,te=tt*W,de=Re/(-Q+W),V=de*-Q;if(oe.matrixWorld.decompose(J.position,J.quaternion,J.scale),J.translateX(V),J.translateZ(de),J.matrixWorld.compose(J.position,J.quaternion,J.scale),J.matrixWorldInverse.copy(J.matrixWorld).invert(),Ie[10]===-1)J.projectionMatrix.copy(oe.projectionMatrix),J.projectionMatrixInverse.copy(oe.projectionMatrixInverse);else{const ee=tt+de,L=je+de,T=N-V,U=te+(Re-V),j=D*je/L*ee,K=ae*je/L*ee;J.projectionMatrix.makePerspective(T,U,j,K,ee,L),J.projectionMatrixInverse.copy(J.projectionMatrix).invert()}}function Y(J,oe){oe===null?J.matrixWorld.copy(J.matrix):J.matrixWorld.multiplyMatrices(oe.matrixWorld,J.matrix),J.matrixWorldInverse.copy(J.matrixWorld).invert()}this.updateCamera=function(J){if(n===null)return;let oe=J.near,ue=J.far;m.texture!==null&&(m.depthNear>0&&(oe=m.depthNear),m.depthFar>0&&(ue=m.depthFar)),P.near=C.near=M.near=oe,P.far=C.far=M.far=ue,(k!==P.near||A!==P.far)&&(n.updateRenderState({depthNear:P.near,depthFar:P.far}),k=P.near,A=P.far),P.layers.mask=J.layers.mask|6,M.layers.mask=P.layers.mask&3,C.layers.mask=P.layers.mask&5;const Re=J.parent,Ie=P.cameras;Y(P,Re);for(let Ue=0;Ue0&&(m.alphaTest.value=f.alphaTest);const y=e.get(f),x=y.envMap,_=y.envMapRotation;x&&(m.envMap.value=x,vo.copy(_),vo.x*=-1,vo.y*=-1,vo.z*=-1,x.isCubeTexture&&x.isRenderTargetTexture===!1&&(vo.y*=-1,vo.z*=-1),m.envMapRotation.value.setFromMatrix4(t8.makeRotationFromEuler(vo)),m.flipEnvMap.value=x.isCubeTexture&&x.isRenderTargetTexture===!1?-1:1,m.reflectivity.value=f.reflectivity,m.ior.value=f.ior,m.refractionRatio.value=f.refractionRatio),f.lightMap&&(m.lightMap.value=f.lightMap,m.lightMapIntensity.value=f.lightMapIntensity,t(f.lightMap,m.lightMapTransform)),f.aoMap&&(m.aoMap.value=f.aoMap,m.aoMapIntensity.value=f.aoMapIntensity,t(f.aoMap,m.aoMapTransform))}function a(m,f){m.diffuse.value.copy(f.color),m.opacity.value=f.opacity,f.map&&(m.map.value=f.map,t(f.map,m.mapTransform))}function o(m,f){m.dashSize.value=f.dashSize,m.totalSize.value=f.dashSize+f.gapSize,m.scale.value=f.scale}function l(m,f,y,x){m.diffuse.value.copy(f.color),m.opacity.value=f.opacity,m.size.value=f.size*y,m.scale.value=x*.5,f.map&&(m.map.value=f.map,t(f.map,m.uvTransform)),f.alphaMap&&(m.alphaMap.value=f.alphaMap,t(f.alphaMap,m.alphaMapTransform)),f.alphaTest>0&&(m.alphaTest.value=f.alphaTest)}function c(m,f){m.diffuse.value.copy(f.color),m.opacity.value=f.opacity,m.rotation.value=f.rotation,f.map&&(m.map.value=f.map,t(f.map,m.mapTransform)),f.alphaMap&&(m.alphaMap.value=f.alphaMap,t(f.alphaMap,m.alphaMapTransform)),f.alphaTest>0&&(m.alphaTest.value=f.alphaTest)}function h(m,f){m.specular.value.copy(f.specular),m.shininess.value=Math.max(f.shininess,1e-4)}function d(m,f){f.gradientMap&&(m.gradientMap.value=f.gradientMap)}function p(m,f){m.metalness.value=f.metalness,f.metalnessMap&&(m.metalnessMap.value=f.metalnessMap,t(f.metalnessMap,m.metalnessMapTransform)),m.roughness.value=f.roughness,f.roughnessMap&&(m.roughnessMap.value=f.roughnessMap,t(f.roughnessMap,m.roughnessMapTransform)),f.envMap&&(m.envMapIntensity.value=f.envMapIntensity)}function u(m,f,y){m.ior.value=f.ior,f.sheen>0&&(m.sheenColor.value.copy(f.sheenColor).multiplyScalar(f.sheen),m.sheenRoughness.value=f.sheenRoughness,f.sheenColorMap&&(m.sheenColorMap.value=f.sheenColorMap,t(f.sheenColorMap,m.sheenColorMapTransform)),f.sheenRoughnessMap&&(m.sheenRoughnessMap.value=f.sheenRoughnessMap,t(f.sheenRoughnessMap,m.sheenRoughnessMapTransform))),f.clearcoat>0&&(m.clearcoat.value=f.clearcoat,m.clearcoatRoughness.value=f.clearcoatRoughness,f.clearcoatMap&&(m.clearcoatMap.value=f.clearcoatMap,t(f.clearcoatMap,m.clearcoatMapTransform)),f.clearcoatRoughnessMap&&(m.clearcoatRoughnessMap.value=f.clearcoatRoughnessMap,t(f.clearcoatRoughnessMap,m.clearcoatRoughnessMapTransform)),f.clearcoatNormalMap&&(m.clearcoatNormalMap.value=f.clearcoatNormalMap,t(f.clearcoatNormalMap,m.clearcoatNormalMapTransform),m.clearcoatNormalScale.value.copy(f.clearcoatNormalScale),f.side===En&&m.clearcoatNormalScale.value.negate())),f.dispersion>0&&(m.dispersion.value=f.dispersion),f.iridescence>0&&(m.iridescence.value=f.iridescence,m.iridescenceIOR.value=f.iridescenceIOR,m.iridescenceThicknessMinimum.value=f.iridescenceThicknessRange[0],m.iridescenceThicknessMaximum.value=f.iridescenceThicknessRange[1],f.iridescenceMap&&(m.iridescenceMap.value=f.iridescenceMap,t(f.iridescenceMap,m.iridescenceMapTransform)),f.iridescenceThicknessMap&&(m.iridescenceThicknessMap.value=f.iridescenceThicknessMap,t(f.iridescenceThicknessMap,m.iridescenceThicknessMapTransform))),f.transmission>0&&(m.transmission.value=f.transmission,m.transmissionSamplerMap.value=y.texture,m.transmissionSamplerSize.value.set(y.width,y.height),f.transmissionMap&&(m.transmissionMap.value=f.transmissionMap,t(f.transmissionMap,m.transmissionMapTransform)),m.thickness.value=f.thickness,f.thicknessMap&&(m.thicknessMap.value=f.thicknessMap,t(f.thicknessMap,m.thicknessMapTransform)),m.attenuationDistance.value=f.attenuationDistance,m.attenuationColor.value.copy(f.attenuationColor)),f.anisotropy>0&&(m.anisotropyVector.value.set(f.anisotropy*Math.cos(f.anisotropyRotation),f.anisotropy*Math.sin(f.anisotropyRotation)),f.anisotropyMap&&(m.anisotropyMap.value=f.anisotropyMap,t(f.anisotropyMap,m.anisotropyMapTransform))),m.specularIntensity.value=f.specularIntensity,m.specularColor.value.copy(f.specularColor),f.specularColorMap&&(m.specularColorMap.value=f.specularColorMap,t(f.specularColorMap,m.specularColorMapTransform)),f.specularIntensityMap&&(m.specularIntensityMap.value=f.specularIntensityMap,t(f.specularIntensityMap,m.specularIntensityMapTransform))}function v(m,f){f.matcap&&(m.matcap.value=f.matcap)}function g(m,f){const y=e.get(f).light;m.referencePosition.value.setFromMatrixPosition(y.matrixWorld),m.nearDistance.value=y.shadow.camera.near,m.farDistance.value=y.shadow.camera.far}return{refreshFogUniforms:i,refreshMaterialUniforms:n}}function n8(s,e,t,i){let n={},r={},a=[];const o=s.getParameter(s.MAX_UNIFORM_BUFFER_BINDINGS);function l(y,x){const _=x.program;i.uniformBlockBinding(y,_)}function c(y,x){let _=n[y.id];_===void 0&&(v(y),_=h(y),n[y.id]=_,y.addEventListener("dispose",m));const S=x.program;i.updateUBOMapping(y,S);const b=e.render.frame;r[y.id]!==b&&(p(y),r[y.id]=b)}function h(y){const x=d();y.__bindingPointIndex=x;const _=s.createBuffer(),S=y.__size,b=y.usage;return s.bindBuffer(s.UNIFORM_BUFFER,_),s.bufferData(s.UNIFORM_BUFFER,S,b),s.bindBuffer(s.UNIFORM_BUFFER,null),s.bindBufferBase(s.UNIFORM_BUFFER,x,_),_}function d(){for(let y=0;y0&&(_+=S-b),y.__size=_,y.__cache={},this}function g(y){const x={boundary:0,storage:0};return typeof y=="number"||typeof y=="boolean"?(x.boundary=4,x.storage=4):y.isVector2?(x.boundary=8,x.storage=8):y.isVector3||y.isColor?(x.boundary=16,x.storage=12):y.isVector4?(x.boundary=16,x.storage=16):y.isMatrix3?(x.boundary=48,x.storage=48):y.isMatrix4?(x.boundary=64,x.storage=64):y.isTexture?yt("WebGLRenderer: Texture samplers can not be part of an uniforms group."):yt("WebGLRenderer: Unsupported uniform value type.",y),x}function m(y){const x=y.target;x.removeEventListener("dispose",m);const _=a.indexOf(x.__bindingPointIndex);a.splice(_,1),s.deleteBuffer(n[x.id]),delete n[x.id],delete r[x.id]}function f(){for(const y in n)s.deleteBuffer(n[y]);a=[],n={},r={}}return{bind:l,update:c,dispose:f}}const s8=new Uint16Array([11481,15204,11534,15171,11808,15015,12385,14843,12894,14716,13396,14600,13693,14483,13976,14366,14237,14171,14405,13961,14511,13770,14605,13598,14687,13444,14760,13305,14822,13066,14876,12857,14923,12675,14963,12517,14997,12379,15025,12230,15049,12023,15070,11843,15086,11687,15100,11551,15111,11433,15120,11330,15127,11217,15132,11060,15135,10922,15138,10801,15139,10695,15139,10600,13012,14923,13020,14917,13064,14886,13176,14800,13349,14666,13513,14526,13724,14398,13960,14230,14200,14020,14383,13827,14488,13651,14583,13491,14667,13348,14740,13132,14803,12908,14856,12713,14901,12542,14938,12394,14968,12241,14992,12017,15010,11822,15024,11654,15034,11507,15041,11380,15044,11269,15044,11081,15042,10913,15037,10764,15031,10635,15023,10520,15014,10419,15003,10330,13657,14676,13658,14673,13670,14660,13698,14622,13750,14547,13834,14442,13956,14317,14112,14093,14291,13889,14407,13704,14499,13538,14586,13389,14664,13201,14733,12966,14792,12758,14842,12577,14882,12418,14915,12272,14940,12033,14959,11826,14972,11646,14980,11490,14983,11355,14983,11212,14979,11008,14971,10830,14961,10675,14950,10540,14936,10420,14923,10315,14909,10204,14894,10041,14089,14460,14090,14459,14096,14452,14112,14431,14141,14388,14186,14305,14252,14130,14341,13941,14399,13756,14467,13585,14539,13430,14610,13272,14677,13026,14737,12808,14790,12617,14833,12449,14869,12303,14896,12065,14916,11845,14929,11655,14937,11490,14939,11347,14936,11184,14930,10970,14921,10783,14912,10621,14900,10480,14885,10356,14867,10247,14848,10062,14827,9894,14805,9745,14400,14208,14400,14206,14402,14198,14406,14174,14415,14122,14427,14035,14444,13913,14469,13767,14504,13613,14548,13463,14598,13324,14651,13082,14704,12858,14752,12658,14795,12483,14831,12330,14860,12106,14881,11875,14895,11675,14903,11501,14905,11351,14903,11178,14900,10953,14892,10757,14880,10589,14865,10442,14847,10313,14827,10162,14805,9965,14782,9792,14757,9642,14731,9507,14562,13883,14562,13883,14563,13877,14566,13862,14570,13830,14576,13773,14584,13689,14595,13582,14613,13461,14637,13336,14668,13120,14704,12897,14741,12695,14776,12516,14808,12358,14835,12150,14856,11910,14870,11701,14878,11519,14882,11361,14884,11187,14880,10951,14871,10748,14858,10572,14842,10418,14823,10286,14801,10099,14777,9897,14751,9722,14725,9567,14696,9430,14666,9309,14702,13604,14702,13604,14702,13600,14703,13591,14705,13570,14707,13533,14709,13477,14712,13400,14718,13305,14727,13106,14743,12907,14762,12716,14784,12539,14807,12380,14827,12190,14844,11943,14855,11727,14863,11539,14870,11376,14871,11204,14868,10960,14858,10748,14845,10565,14829,10406,14809,10269,14786,10058,14761,9852,14734,9671,14705,9512,14674,9374,14641,9253,14608,9076,14821,13366,14821,13365,14821,13364,14821,13358,14821,13344,14821,13320,14819,13252,14817,13145,14815,13011,14814,12858,14817,12698,14823,12539,14832,12389,14841,12214,14850,11968,14856,11750,14861,11558,14866,11390,14867,11226,14862,10972,14853,10754,14840,10565,14823,10401,14803,10259,14780,10032,14754,9820,14725,9635,14694,9473,14661,9333,14627,9203,14593,8988,14557,8798,14923,13014,14922,13014,14922,13012,14922,13004,14920,12987,14919,12957,14915,12907,14909,12834,14902,12738,14894,12623,14888,12498,14883,12370,14880,12203,14878,11970,14875,11759,14873,11569,14874,11401,14872,11243,14865,10986,14855,10762,14842,10568,14825,10401,14804,10255,14781,10017,14754,9799,14725,9611,14692,9445,14658,9301,14623,9139,14587,8920,14548,8729,14509,8562,15008,12672,15008,12672,15008,12671,15007,12667,15005,12656,15001,12637,14997,12605,14989,12556,14978,12490,14966,12407,14953,12313,14940,12136,14927,11934,14914,11742,14903,11563,14896,11401,14889,11247,14879,10992,14866,10767,14851,10570,14833,10400,14812,10252,14789,10007,14761,9784,14731,9592,14698,9424,14663,9279,14627,9088,14588,8868,14548,8676,14508,8508,14467,8360,15080,12386,15080,12386,15079,12385,15078,12383,15076,12378,15072,12367,15066,12347,15057,12315,15045,12253,15030,12138,15012,11998,14993,11845,14972,11685,14951,11530,14935,11383,14920,11228,14904,10981,14887,10762,14870,10567,14850,10397,14827,10248,14803,9997,14774,9771,14743,9578,14710,9407,14674,9259,14637,9048,14596,8826,14555,8632,14514,8464,14471,8317,14427,8182,15139,12008,15139,12008,15138,12008,15137,12007,15135,12003,15130,11990,15124,11969,15115,11929,15102,11872,15086,11794,15064,11693,15041,11581,15013,11459,14987,11336,14966,11170,14944,10944,14921,10738,14898,10552,14875,10387,14850,10239,14824,9983,14794,9758,14762,9563,14728,9392,14692,9244,14653,9014,14611,8791,14569,8597,14526,8427,14481,8281,14436,8110,14391,7885,15188,11617,15188,11617,15187,11617,15186,11618,15183,11617,15179,11612,15173,11601,15163,11581,15150,11546,15133,11495,15110,11427,15083,11346,15051,11246,15024,11057,14996,10868,14967,10687,14938,10517,14911,10362,14882,10206,14853,9956,14821,9737,14787,9543,14752,9375,14715,9228,14675,8980,14632,8760,14589,8565,14544,8395,14498,8248,14451,8049,14404,7824,14357,7630,15228,11298,15228,11298,15227,11299,15226,11301,15223,11303,15219,11302,15213,11299,15204,11290,15191,11271,15174,11217,15150,11129,15119,11015,15087,10886,15057,10744,15024,10599,14990,10455,14957,10318,14924,10143,14891,9911,14856,9701,14820,9516,14782,9352,14744,9200,14703,8946,14659,8725,14615,8533,14568,8366,14521,8220,14472,7992,14423,7770,14374,7578,14315,7408,15260,10819,15260,10819,15259,10822,15258,10826,15256,10832,15251,10836,15246,10841,15237,10838,15225,10821,15207,10788,15183,10734,15151,10660,15120,10571,15087,10469,15049,10359,15012,10249,14974,10041,14937,9837,14900,9647,14860,9475,14820,9320,14779,9147,14736,8902,14691,8688,14646,8499,14598,8335,14549,8189,14499,7940,14448,7720,14397,7529,14347,7363,14256,7218,15285,10410,15285,10411,15285,10413,15284,10418,15282,10425,15278,10434,15272,10442,15264,10449,15252,10445,15235,10433,15210,10403,15179,10358,15149,10301,15113,10218,15073,10059,15033,9894,14991,9726,14951,9565,14909,9413,14865,9273,14822,9073,14777,8845,14730,8641,14682,8459,14633,8300,14583,8129,14531,7883,14479,7670,14426,7482,14373,7321,14305,7176,14201,6939,15305,9939,15305,9940,15305,9945,15304,9955,15302,9967,15298,9989,15293,10010,15286,10033,15274,10044,15258,10045,15233,10022,15205,9975,15174,9903,15136,9808,15095,9697,15053,9578,15009,9451,14965,9327,14918,9198,14871,8973,14825,8766,14775,8579,14725,8408,14675,8259,14622,8058,14569,7821,14515,7615,14460,7435,14405,7276,14350,7108,14256,6866,14149,6653,15321,9444,15321,9445,15321,9448,15320,9458,15317,9470,15314,9490,15310,9515,15302,9540,15292,9562,15276,9579,15251,9577,15226,9559,15195,9519,15156,9463,15116,9389,15071,9304,15025,9208,14978,9023,14927,8838,14878,8661,14827,8496,14774,8344,14722,8206,14667,7973,14612,7749,14556,7555,14499,7382,14443,7229,14385,7025,14322,6791,14210,6588,14100,6409,15333,8920,15333,8921,15332,8927,15332,8943,15329,8965,15326,9002,15322,9048,15316,9106,15307,9162,15291,9204,15267,9221,15244,9221,15212,9196,15175,9134,15133,9043,15088,8930,15040,8801,14990,8665,14938,8526,14886,8391,14830,8261,14775,8087,14719,7866,14661,7664,14603,7482,14544,7322,14485,7178,14426,6936,14367,6713,14281,6517,14166,6348,14054,6198,15341,8360,15341,8361,15341,8366,15341,8379,15339,8399,15336,8431,15332,8473,15326,8527,15318,8585,15302,8632,15281,8670,15258,8690,15227,8690,15191,8664,15149,8612,15104,8543,15055,8456,15001,8360,14948,8259,14892,8122,14834,7923,14776,7734,14716,7558,14656,7397,14595,7250,14534,7070,14472,6835,14410,6628,14350,6443,14243,6283,14125,6135,14010,5889,15348,7715,15348,7717,15348,7725,15347,7745,15345,7780,15343,7836,15339,7905,15334,8e3,15326,8103,15310,8193,15293,8239,15270,8270,15240,8287,15204,8283,15163,8260,15118,8223,15067,8143,15014,8014,14958,7873,14899,7723,14839,7573,14778,7430,14715,7293,14652,7164,14588,6931,14524,6720,14460,6531,14396,6362,14330,6210,14207,6015,14086,5781,13969,5576,15352,7114,15352,7116,15352,7128,15352,7159,15350,7195,15348,7237,15345,7299,15340,7374,15332,7457,15317,7544,15301,7633,15280,7703,15251,7754,15216,7775,15176,7767,15131,7733,15079,7670,15026,7588,14967,7492,14906,7387,14844,7278,14779,7171,14714,6965,14648,6770,14581,6587,14515,6420,14448,6269,14382,6123,14299,5881,14172,5665,14049,5477,13929,5310,15355,6329,15355,6330,15355,6339,15355,6362,15353,6410,15351,6472,15349,6572,15344,6688,15337,6835,15323,6985,15309,7142,15287,7220,15260,7277,15226,7310,15188,7326,15142,7318,15090,7285,15036,7239,14976,7177,14914,7045,14849,6892,14782,6736,14714,6581,14645,6433,14576,6293,14506,6164,14438,5946,14369,5733,14270,5540,14140,5369,14014,5216,13892,5043,15357,5483,15357,5484,15357,5496,15357,5528,15356,5597,15354,5692,15351,5835,15347,6011,15339,6195,15328,6317,15314,6446,15293,6566,15268,6668,15235,6746,15197,6796,15152,6811,15101,6790,15046,6748,14985,6673,14921,6583,14854,6479,14785,6371,14714,6259,14643,6149,14571,5946,14499,5750,14428,5567,14358,5401,14242,5250,14109,5111,13980,4870,13856,4657,15359,4555,15359,4557,15358,4573,15358,4633,15357,4715,15355,4841,15353,5061,15349,5216,15342,5391,15331,5577,15318,5770,15299,5967,15274,6150,15243,6223,15206,6280,15161,6310,15111,6317,15055,6300,14994,6262,14928,6208,14860,6141,14788,5994,14715,5838,14641,5684,14566,5529,14492,5384,14418,5247,14346,5121,14216,4892,14079,4682,13948,4496,13822,4330,15359,3498,15359,3501,15359,3520,15359,3598,15358,3719,15356,3860,15355,4137,15351,4305,15344,4563,15334,4809,15321,5116,15303,5273,15280,5418,15250,5547,15214,5653,15170,5722,15120,5761,15064,5763,15002,5733,14935,5673,14865,5597,14792,5504,14716,5400,14640,5294,14563,5185,14486,5041,14410,4841,14335,4655,14191,4482,14051,4325,13918,4183,13790,4012,15360,2282,15360,2285,15360,2306,15360,2401,15359,2547,15357,2748,15355,3103,15352,3349,15345,3675,15336,4020,15324,4272,15307,4496,15285,4716,15255,4908,15220,5086,15178,5170,15128,5214,15072,5234,15010,5231,14943,5206,14871,5166,14796,5102,14718,4971,14639,4833,14559,4687,14480,4541,14402,4401,14315,4268,14167,4142,14025,3958,13888,3747,13759,3556,15360,923,15360,925,15360,946,15360,1052,15359,1214,15357,1494,15356,1892,15352,2274,15346,2663,15338,3099,15326,3393,15309,3679,15288,3980,15260,4183,15226,4325,15185,4437,15136,4517,15080,4570,15018,4591,14950,4581,14877,4545,14800,4485,14720,4411,14638,4325,14556,4231,14475,4136,14395,3988,14297,3803,14145,3628,13999,3465,13861,3314,13729,3177,15360,263,15360,264,15360,272,15360,325,15359,407,15358,548,15356,780,15352,1144,15347,1580,15339,2099,15328,2425,15312,2795,15292,3133,15264,3329,15232,3517,15191,3689,15143,3819,15088,3923,15025,3978,14956,3999,14882,3979,14804,3931,14722,3855,14639,3756,14554,3645,14470,3529,14388,3409,14279,3289,14124,3173,13975,3055,13834,2848,13701,2658,15360,49,15360,49,15360,52,15360,75,15359,111,15358,201,15356,283,15353,519,15348,726,15340,1045,15329,1415,15314,1795,15295,2173,15269,2410,15237,2649,15197,2866,15150,3054,15095,3140,15032,3196,14963,3228,14888,3236,14808,3224,14725,3191,14639,3146,14553,3088,14466,2976,14382,2836,14262,2692,14103,2549,13952,2409,13808,2278,13674,2154,15360,4,15360,4,15360,4,15360,13,15359,33,15358,59,15357,112,15353,199,15348,302,15341,456,15331,628,15316,827,15297,1082,15272,1332,15241,1601,15202,1851,15156,2069,15101,2172,15039,2256,14970,2314,14894,2348,14813,2358,14728,2344,14640,2311,14551,2263,14463,2203,14376,2133,14247,2059,14084,1915,13930,1761,13784,1609,13648,1464,15360,0,15360,0,15360,0,15360,3,15359,18,15358,26,15357,53,15354,80,15348,97,15341,165,15332,238,15318,326,15299,427,15275,529,15245,654,15207,771,15161,885,15108,994,15046,1089,14976,1170,14900,1229,14817,1266,14731,1284,14641,1282,14550,1260,14460,1223,14370,1174,14232,1116,14066,1050,13909,981,13761,910,13623,839]);let xr=null;function r8(){return xr===null&&(xr=new uI(s8,32,32,B0,Il),xr.minFilter=es,xr.magFilter=es,xr.wrapS=cr,xr.wrapT=cr,xr.generateMipmaps=!1,xr.needsUpdate=!0),xr}class a8{constructor(e={}){const{canvas:t=BR(),context:i=null,depth:n=!0,stencil:r=!1,alpha:a=!1,antialias:o=!1,premultipliedAlpha:l=!0,preserveDrawingBuffer:c=!1,powerPreference:h="default",failIfMajorPerformanceCaveat:d=!1,reversedDepthBuffer:p=!1}=e;this.isWebGLRenderer=!0;let u;if(i!==null){if(typeof WebGLRenderingContext<"u"&&i instanceof WebGLRenderingContext)throw new Error("THREE.WebGLRenderer: WebGL 1 is not supported since r163.");u=i.getContextAttributes().alpha}else u=a;const v=new Set([z0,F0,U0]),g=new Set([hr,ro,gh,vh,k0,O0]),m=new Uint32Array(4),f=new Int32Array(4);let y=null,x=null;const _=[],S=[];this.domElement=t,this.debug={checkShaderErrors:!0,onShaderError:null},this.autoClear=!0,this.autoClearColor=!0,this.autoClearDepth=!0,this.autoClearStencil=!0,this.sortObjects=!0,this.clippingPlanes=[],this.localClippingEnabled=!1,this.toneMapping=ea,this.toneMappingExposure=1,this.transmissionResolutionScale=.25,this.interactionCullingEnabled=!1,this.interactionActive=!1,this.interactionRenderScene=null,this.interactionFrameBudgetMs=4,this.interactionSkipShadows=!1;const b=this;let E=!1;this._outputColorSpace=zn;let w=0,M=0,C=null,I=-1,P=null;const k=new vi,A=new vi;let B=null;const F=new Wt(0);let H=0,q=t.width,G=t.height,re=1,Y=null,$=null;const _e=new vi(0,0,q,G),Te=new vi(0,0,q,G);let be=!1;const J=new _M;let oe=!1,ue=!1;const Re=new Di,Ie=new De,Ue=new vi,tt={background:null,fog:null,environment:null,overrideMaterial:null,isScene:!0};let je=!1,D=null;const ae=[];function Q(O){ae.push(D);const ie=Number.isFinite(b.interactionFrameBudgetMs)?b.interactionFrameBudgetMs:0,he=b.interactionRenderScene===null||O===b.interactionRenderScene;b.interactionCullingEnabled===!0&&b.interactionActive===!0&&he===!0&&ie>0?D={startTime:performance.now(),budgetMs:ie,aborted:!1}:D=null}function W(O){const ie=Number.isFinite(b.interactionFrameBudgetMs)?b.interactionFrameBudgetMs:0,he=b.interactionRenderScene===null||O===b.interactionRenderScene;return b.interactionCullingEnabled===!0&&b.interactionActive===!0&&he===!0&&ie>0}function N(){D=ae.pop()??null}function te(){return D===null?!1:D.aborted===!0?!0:performance.now()-D.startTime{function we(){if(ce.forEach(function(He){K.get(He).currentProgram.isReady()&&ce.delete(He)}),ce.size===0){se(O);return}setTimeout(we,10)}L.get("KHR_parallel_shader_compile")!==null?we():setTimeout(we,10)})};let Ps=null;function nd(O){Ps&&Ps(O)}function sd(){cs.stop()}function rd(){cs.start()}const cs=new wM;cs.setAnimationLoop(nd),typeof self<"u"&&cs.setContext(self),this.setAnimationLoop=function(O){Ps=O,Qe.setAnimationLoop(O),O===null?cs.stop():cs.start()},Qe.addEventListener("sessionstart",sd),Qe.addEventListener("sessionend",rd),this.render=function(O,ie){if(ie!==void 0&&ie.isCamera!==!0){gi("WebGLRenderer.render: camera is not an instance of THREE.Camera.");return}if(E!==!0){O.matrixWorldAutoUpdate===!0&&O.updateMatrixWorld(),ie.parent===null&&ie.matrixWorldAutoUpdate===!0&&ie.updateMatrixWorld(),Qe.enabled===!0&&Qe.isPresenting===!0&&(Qe.cameraAutoUpdate===!0&&Qe.updateCamera(ie),ie=Qe.getCamera()),O.isScene===!0&&O.onBeforeRender(b,O,ie,C),x=Se.get(O,S.length),x.init(ie),S.push(x),Re.multiplyMatrices(ie.projectionMatrix,ie.matrixWorldInverse),J.setFromProjectionMatrix(Re,Hs,ie.reversedDepth),ue=this.localClippingEnabled,oe=Xe.init(this.clippingPlanes,ue),y=Oe.get(O,_.length),y.init(),_.push(y),Q(O);try{if(Qe.enabled===!0&&Qe.isPresenting===!0){const we=b.xr.getDepthSensingMesh();we!==null&&fc(we,ie,-1/0,b.sortObjects)}fc(O,ie,0,b.sortObjects),y.finish(),b.sortObjects===!0&&y.sort(Y,$),je=Qe.enabled===!1||Qe.isPresenting===!1||Qe.hasDepthSensing()===!1,je&&xe.addToRenderList(y,O),this.info.render.frame++,oe===!0&&Xe.beginShadows();const he=x.state.shadowsArray;(b.interactionSkipShadows!==!0||W(O)===!1)&&z.render(he,O,ie),oe===!0&&Xe.endShadows(),this.info.autoReset===!0&&this.info.reset();const ce=y.opaque,se=y.transmissive;if(x.setupLights(),ie.isArrayCamera){const we=ie.cameras;if(se.length>0)for(let He=0,Ve=we.length;He0&&ad(ce,se,O,ie),je&&xe.render(O),Uo(y,O,ie)}finally{N()}C!==null&&M===0&&(Z.updateMultisampleRenderTarget(C),Z.updateRenderTargetMipmap(C)),O.isScene===!0&&O.onAfterRender(b,O,ie),Ne.resetDefaultState(),I=-1,P=null,S.pop(),S.length>0?(x=S[S.length-1],oe===!0&&Xe.setGlobalState(b.clippingPlanes,x.state.camera)):x=null,_.pop(),_.length>0?y=_[_.length-1]:y=null}};function fc(O,ie,he,ce){if(te()===!0||O.visible===!1)return;if(O.layers.test(ie.layers)){if(O.isGroup)he=O.renderOrder;else if(O.isLOD)O.autoUpdate===!0&&O.update(ie);else if(O.isLight)x.pushLight(O),O.castShadow&&x.pushShadow(O);else if(O.isSprite){if(!O.frustumCulled||J.intersectsSprite(O)){ce&&Ue.setFromMatrixPosition(O.matrixWorld).applyMatrix4(Re);const we=le.update(O),He=O.material;He.visible&&y.push(O,we,He,he,Ue.z,null)}}else if((O.isMesh||O.isLine||O.isPoints)&&(!O.frustumCulled||J.intersectsObject(O))){const we=le.update(O),He=O.material;if(ce&&(O.boundingSphere!==void 0?(O.boundingSphere===null&&O.computeBoundingSphere(),Ue.copy(O.boundingSphere.center)):(we.boundingSphere===null&&we.computeBoundingSphere(),Ue.copy(we.boundingSphere.center)),Ue.applyMatrix4(O.matrixWorld).applyMatrix4(Re)),Array.isArray(He)){const Ve=we.groups;for(let Be=0,Ke=Ve.length;Be0&&Bo(se,ie,he),we.length>0&&Bo(we,ie,he),He.length>0&&Bo(He,ie,he),U.buffers.depth.setTest(!0),U.buffers.depth.setMask(!0),U.buffers.color.setMask(!0),U.setPolygonOffset(!1)}function ad(O,ie,he,ce){if((he.isScene===!0?he.overrideMaterial:null)!==null)return;x.state.transmissionRenderTarget[ce.id]===void 0&&(x.state.transmissionRenderTarget[ce.id]=new ao(1,1,{generateMipmaps:!0,type:L.has("EXT_color_buffer_half_float")||L.has("EXT_color_buffer_float")?Il:hr,minFilter:so,samples:4,stencilBuffer:r,resolveDepthBuffer:!1,resolveStencilBuffer:!1,colorSpace:Ut.workingColorSpace}));const se=x.state.transmissionRenderTarget[ce.id],we=ce.viewport||k;se.setSize(we.z*b.transmissionResolutionScale,we.w*b.transmissionResolutionScale);const He=b.getRenderTarget(),Ve=b.getActiveCubeFace(),Be=b.getActiveMipmapLevel();b.setRenderTarget(se),b.getClearColor(F),H=b.getClearAlpha(),H<1&&b.setClearColor(16777215,.5),b.clear(),je&&xe.render(he);const Ke=b.toneMapping;b.toneMapping=ea;const st=ce.viewport;if(ce.viewport!==void 0&&(ce.viewport=void 0),x.setupLightsView(ce),oe===!0&&Xe.setGlobalState(b.clippingPlanes,ce),Bo(O,he,ce),Z.updateMultisampleRenderTarget(se),Z.updateRenderTargetMipmap(se),L.has("WEBGL_multisampled_render_to_texture")===!1){let it=!1;for(let rt=0,mt=ie.length;rt0),it=!!he.morphAttributes.position,rt=!!he.morphAttributes.normal,mt=!!he.morphAttributes.color;let Ze=ea;ce.toneMapped&&(C===null||C.isXRRenderTarget===!0)&&(Ze=b.toneMapping);const Ct=he.morphAttributes.position||he.morphAttributes.normal||he.morphAttributes.color,ot=Ct!==void 0?Ct.length:0,nt=K.get(ce),qt=x?.state.lights;if(oe===!0&&(ue===!0||O!==P)){const Ai=O===P&&ce.id===I;Xe.setState(ce,O,Ai)}let Ki=!1;ce.version===nt.__version?(nt.needsLights&&nt.lightsStateVersion!==qt.state.version||nt.outputColorSpace!==Ve||se.isBatchedMesh&&nt.batching===!1||!se.isBatchedMesh&&nt.batching===!0||se.isBatchedMesh&&nt.batchingColor===!0&&se.colorTexture===null||se.isBatchedMesh&&nt.batchingColor===!1&&se.colorTexture!==null||se.isInstancedMesh&&nt.instancing===!1||!se.isInstancedMesh&&nt.instancing===!0||se.isSkinnedMesh&&nt.skinning===!1||!se.isSkinnedMesh&&nt.skinning===!0||se.isInstancedMesh&&nt.instancingColor===!0&&se.instanceColor===null||se.isInstancedMesh&&nt.instancingColor===!1&&se.instanceColor!==null||se.isInstancedMesh&&nt.instancingMorph===!0&&se.morphTexture===null||se.isInstancedMesh&&nt.instancingMorph===!1&&se.morphTexture!==null||nt.envMap!==Be||ce.fog===!0&&nt.fog!==we||nt.numClippingPlanes!==void 0&&(nt.numClippingPlanes!==Xe.numPlanes||nt.numIntersection!==Xe.numIntersection)||nt.vertexAlphas!==Ke||nt.vertexTangents!==st||nt.morphTargets!==it||nt.morphNormals!==rt||nt.morphColors!==mt||nt.toneMapping!==Ze||nt.morphTargetsCount!==ot)&&(Ki=!0):(Ki=!0,nt.__version=ce.version);let Xi=nt.currentProgram;Ki===!0&&(Xi=mc(ce,ie,se));let kt=!1,Ft=!1,In=!1;const _t=Xi.getUniforms(),oi=nt.uniforms;if(U.useProgram(Xi.program)&&(kt=!0,Ft=!0,In=!0),ce.id!==I&&(I=ce.id,Ft=!0),kt||P!==O){U.buffers.depth.getReversed()&&O.reversedDepth!==!0&&(O._reversedDepth=!0,O.updateProjectionMatrix()),_t.setValue(V,"projectionMatrix",O.projectionMatrix),_t.setValue(V,"viewMatrix",O.matrixWorldInverse);const Ai=_t.map.cameraPosition;Ai!==void 0&&Ai.setValue(V,Ie.setFromMatrixPosition(O.matrixWorld)),T.logarithmicDepthBuffer&&_t.setValue(V,"logDepthBufFC",2/(Math.log(O.far+1)/Math.LN2)),(ce.isMeshPhongMaterial||ce.isMeshToonMaterial||ce.isMeshLambertMaterial||ce.isMeshBasicMaterial||ce.isMeshStandardMaterial||ce.isShaderMaterial)&&_t.setValue(V,"isOrthographic",O.isOrthographicCamera===!0),P!==O&&(P=O,Ft=!0,In=!0)}if(se.isSkinnedMesh){_t.setOptional(V,se,"bindMatrix"),_t.setOptional(V,se,"bindMatrixInverse");const Ai=se.skeleton;Ai&&(Ai.boneTexture===null&&Ai.computeBoneTexture(),_t.setValue(V,"boneTexture",Ai.boneTexture,Z))}se.isBatchedMesh&&(_t.setOptional(V,se,"batchingTexture"),_t.setValue(V,"batchingTexture",se._matricesTexture,Z),_t.setOptional(V,se,"batchingIdTexture"),_t.setValue(V,"batchingIdTexture",se._indirectTexture,Z),_t.setOptional(V,se,"batchingColorTexture"),se._colorsTexture!==null&&_t.setValue(V,"batchingColorTexture",se._colorsTexture,Z));const Ui=he.morphAttributes;if((Ui.position!==void 0||Ui.normal!==void 0||Ui.color!==void 0)&&ge.update(se,he,Xi),(Ft||nt.receiveShadow!==se.receiveShadow)&&(nt.receiveShadow=se.receiveShadow,_t.setValue(V,"receiveShadow",se.receiveShadow)),ce.isMeshGouraudMaterial&&ce.envMap!==null&&(oi.envMap.value=Be,oi.flipEnvMap.value=Be.isCubeTexture&&Be.isRenderTargetTexture===!1?-1:1),ce.isMeshStandardMaterial&&ce.envMap===null&&ie.environment!==null&&(oi.envMapIntensity.value=ie.environmentIntensity),oi.dfgLUT!==void 0&&(oi.dfgLUT.value=r8()),Ft&&(_t.setValue(V,"toneMappingExposure",b.toneMappingExposure),nt.needsLights&&fy(oi,In),we&&ce.fog===!0&&ze.refreshFogUniforms(oi,we),ze.refreshMaterialUniforms(oi,ce,re,G,x.state.transmissionRenderTarget[O.id]),yf.upload(V,Tm(nt),oi,Z)),ce.isShaderMaterial&&ce.uniformsNeedUpdate===!0&&(yf.upload(V,Tm(nt),oi,Z),ce.uniformsNeedUpdate=!1),ce.isSpriteMaterial&&_t.setValue(V,"center",se.center),_t.setValue(V,"modelViewMatrix",se.modelViewMatrix),_t.setValue(V,"normalMatrix",se.normalMatrix),_t.setValue(V,"modelMatrix",se.matrixWorld),ce.isShaderMaterial||ce.isRawShaderMaterial){const Ai=ce.uniformsGroups;for(let Rs=0,my=Ai.length;Rs0&&Z.useMultisampledRTT(O)===!1?se=K.get(O).__webglMultisampledFramebuffer:Array.isArray(Ke)?se=Ke[he]:se=Ke,k.copy(O.viewport),A.copy(O.scissor),B=O.scissorTest}else k.copy(_e).multiplyScalar(re).floor(),A.copy(Te).multiplyScalar(re).floor(),B=be;if(he!==0&&(se=fe),U.bindFramebuffer(V.FRAMEBUFFER,se)&&ce&&U.drawBuffers(O,se),U.viewport(k),U.scissor(A),U.setScissorTest(B),we){const Ve=K.get(O.texture);V.framebufferTexture2D(V.FRAMEBUFFER,V.COLOR_ATTACHMENT0,V.TEXTURE_CUBE_MAP_POSITIVE_X+ie,Ve.__webglTexture,he)}else if(He){const Ve=ie;for(let Be=0;Be=0&&ie<=O.width-ce&&he>=0&&he<=O.height-se&&(O.textures.length>1&&V.readBuffer(V.COLOR_ATTACHMENT0+Ve),V.readPixels(ie,he,ce,se,ne.convert(st),ne.convert(it),we))}finally{const Ke=C!==null?K.get(C).__webglFramebuffer:null;U.bindFramebuffer(V.FRAMEBUFFER,Ke)}}},this.readRenderTargetPixelsAsync=async function(O,ie,he,ce,se,we,He,Ve=0){if(!(O&&O.isWebGLRenderTarget))throw new Error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");let Be=K.get(O).__webglFramebuffer;if(O.isWebGLCubeRenderTarget&&He!==void 0&&(Be=Be[He]),Be)if(ie>=0&&ie<=O.width-ce&&he>=0&&he<=O.height-se){U.bindFramebuffer(V.FRAMEBUFFER,Be);const Ke=O.textures[Ve],st=Ke.format,it=Ke.type;if(!T.textureFormatReadable(st))throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in RGBA or implementation defined format.");if(!T.textureTypeReadable(it))throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in UnsignedByteType or implementation defined type.");const rt=V.createBuffer();V.bindBuffer(V.PIXEL_PACK_BUFFER,rt),V.bufferData(V.PIXEL_PACK_BUFFER,we.byteLength,V.STREAM_READ),O.textures.length>1&&V.readBuffer(V.COLOR_ATTACHMENT0+Ve),V.readPixels(ie,he,ce,se,ne.convert(st),ne.convert(it),0);const mt=C!==null?K.get(C).__webglFramebuffer:null;U.bindFramebuffer(V.FRAMEBUFFER,mt);const Ze=V.fenceSync(V.SYNC_GPU_COMMANDS_COMPLETE,0);return V.flush(),await FR(V,Ze,4),V.bindBuffer(V.PIXEL_PACK_BUFFER,rt),V.getBufferSubData(V.PIXEL_PACK_BUFFER,0,we),V.deleteBuffer(rt),V.deleteSync(Ze),we}else throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: requested read bounds are out of range.")},this.copyFramebufferToTexture=function(O,ie=null,he=0){const ce=Math.pow(2,-he),se=Math.floor(O.image.width*ce),we=Math.floor(O.image.height*ce),He=ie!==null?ie.x:0,Ve=ie!==null?ie.y:0;Z.setTexture2D(O,0),V.copyTexSubImage2D(V.TEXTURE_2D,he,0,0,He,Ve,se,we),U.unbindTexture()};const Ae=V.createFramebuffer(),Me=V.createFramebuffer();this.copyTextureToTexture=function(O,ie,he=null,ce=null,se=0,we=null){we===null&&(se!==0?(_h("WebGLRenderer: copyTextureToTexture function signature has changed to support src and dst mipmap levels."),we=se,se=0):we=0);let He,Ve,Be,Ke,st,it,rt,mt,Ze;const Ct=O.isCompressedTexture?O.mipmaps[we]:O.image;if(he!==null)He=he.max.x-he.min.x,Ve=he.max.y-he.min.y,Be=he.isBox3?he.max.z-he.min.z:1,Ke=he.min.x,st=he.min.y,it=he.isBox3?he.min.z:0;else{const Ui=Math.pow(2,-se);He=Math.floor(Ct.width*Ui),Ve=Math.floor(Ct.height*Ui),O.isDataArrayTexture?Be=Ct.depth:O.isData3DTexture?Be=Math.floor(Ct.depth*Ui):Be=1,Ke=0,st=0,it=0}ce!==null?(rt=ce.x,mt=ce.y,Ze=ce.z):(rt=0,mt=0,Ze=0);const ot=ne.convert(ie.format),nt=ne.convert(ie.type);let qt;ie.isData3DTexture?(Z.setTexture3D(ie,0),qt=V.TEXTURE_3D):ie.isDataArrayTexture||ie.isCompressedArrayTexture?(Z.setTexture2DArray(ie,0),qt=V.TEXTURE_2D_ARRAY):(Z.setTexture2D(ie,0),qt=V.TEXTURE_2D),V.pixelStorei(V.UNPACK_FLIP_Y_WEBGL,ie.flipY),V.pixelStorei(V.UNPACK_PREMULTIPLY_ALPHA_WEBGL,ie.premultiplyAlpha),V.pixelStorei(V.UNPACK_ALIGNMENT,ie.unpackAlignment);const Ki=V.getParameter(V.UNPACK_ROW_LENGTH),Xi=V.getParameter(V.UNPACK_IMAGE_HEIGHT),kt=V.getParameter(V.UNPACK_SKIP_PIXELS),Ft=V.getParameter(V.UNPACK_SKIP_ROWS),In=V.getParameter(V.UNPACK_SKIP_IMAGES);V.pixelStorei(V.UNPACK_ROW_LENGTH,Ct.width),V.pixelStorei(V.UNPACK_IMAGE_HEIGHT,Ct.height),V.pixelStorei(V.UNPACK_SKIP_PIXELS,Ke),V.pixelStorei(V.UNPACK_SKIP_ROWS,st),V.pixelStorei(V.UNPACK_SKIP_IMAGES,it);const _t=O.isDataArrayTexture||O.isData3DTexture,oi=ie.isDataArrayTexture||ie.isData3DTexture;if(O.isDepthTexture){const Ui=K.get(O),Ai=K.get(ie),Rs=K.get(Ui.__renderTarget),my=K.get(Ai.__renderTarget);U.bindFramebuffer(V.READ_FRAMEBUFFER,Rs.__webglFramebuffer),U.bindFramebuffer(V.DRAW_FRAMEBUFFER,my.__webglFramebuffer);for(let Fo=0;FoMath.PI&&(t-=Cn),i<-Math.PI?i+=Cn:i>Math.PI&&(i-=Cn),t<=i?this._spherical.theta=Math.max(t,Math.min(i,this._spherical.theta)):this._spherical.theta=this._spherical.theta>(t+i)/2?Math.max(t,this._spherical.theta):Math.min(i,this._spherical.theta)),this._spherical.phi=Math.max(this.minPolarAngle,Math.min(this.maxPolarAngle,this._spherical.phi)),this._spherical.makeSafe(),this.enableDamping===!0?this.target.addScaledVector(this._panOffset,this.dampingFactor):this.target.add(this._panOffset),this.target.sub(this.cursor),this.target.clampLength(this.minTargetRadius,this.maxTargetRadius),this.target.add(this.cursor);let n=!1;if(this.zoomToCursor&&this._performCursorZoom||this.object.isOrthographicCamera)this._spherical.radius=this._clampDistance(this._spherical.radius);else{const r=this._spherical.radius;this._spherical.radius=this._clampDistance(this._spherical.radius*this._scale),n=r!=this._spherical.radius}if(wi.setFromSpherical(this._spherical),wi.applyQuaternion(this._quatInverse),this.engine&&this.engine.deviceType==="PC"){const r=new R;if(r.copy(this.origin).sub(this.target),r.lengthSq()>1e-4&&(this._sphericalDelta.theta!==0||this._sphericalDelta.phi!==0)){const a=this.enableDamping?this.dampingFactor*3:1,o=d8,l=c8;this.object.getWorldDirection(l);const c=Math.abs(l.y)>.999?u8:o,h=h8;h.crossVectors(l,c),h.lengthSq()bf||8*(1-this._lastQuaternion.dot(this.object.quaternion))>bf||this._lastTargetPosition.distanceToSquared(this.target)>bf?(this.dispatchEvent(JM),this._lastPosition.copy(this.object.position),this._lastQuaternion.copy(this.object.quaternion),this._lastTargetPosition.copy(this.target),!0):!1}_getAutoRotationAngle(s){return s!==null?Cn/60*this.autoRotateSpeed*s:Cn/60/60*this.autoRotateSpeed}_getZoomScale(s){const e=Math.abs(s*.01);return Math.pow(.95,this.zoomSpeed*e)}_rotateLeft(s){this._sphericalDelta.theta-=s}_rotateUp(s){this._sphericalDelta.phi-=s}_panLeft(s,e){wi.setFromMatrixColumn(e,0),wi.multiplyScalar(-s),this._panOffset.add(wi)}_panUp(s,e){this.screenSpacePanning===!0?wi.setFromMatrixColumn(e,1):(wi.setFromMatrixColumn(e,0),wi.crossVectors(this.object.up,wi)),wi.multiplyScalar(s),this._panOffset.add(wi)}_pan(s,e){const t=this.domElement;if(this.object.isPerspectiveCamera){const i=this.object.position;wi.copy(i).sub(this.target);let n=wi.length();n*=Math.tan(this.object.fov/2*Math.PI/180),this._panLeft(2*s*n/t.clientHeight,this.object.matrix),this._panUp(2*e*n/t.clientHeight,this.object.matrix)}else this.object.isOrthographicCamera?(this._panLeft(s*(this.object.right-this.object.left)/this.object.zoom/t.clientWidth,this.object.matrix),this._panUp(e*(this.object.top-this.object.bottom)/this.object.zoom/t.clientHeight,this.object.matrix)):(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - pan disabled."),this.enablePan=!1)}_dollyOut(s){this.object.isPerspectiveCamera||this.object.isOrthographicCamera?this._scale/=s:(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),this.enableZoom=!1)}_dollyIn(s){this.object.isPerspectiveCamera||this.object.isOrthographicCamera?this._scale*=s:(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),this.enableZoom=!1)}_updateZoomParameters(s,e){if(!this.zoomToCursor)return;this._performCursorZoom=!0;const t=this.domElement.getBoundingClientRect(),i=s-t.left,n=e-t.top,r=t.width,a=t.height;this._mouse.x=i/r*2-1,this._mouse.y=-(n/a)*2+1,this._dollyDirection.set(this._mouse.x,this._mouse.y,1).unproject(this.object).sub(this.object.position).normalize()}_clampDistance(s){return Math.max(this.minDistance,Math.min(this.maxDistance,s))}_handleMouseDownRotate(s){this._rotateStart.set(s.clientX,s.clientY)}_handleMouseDownDolly(s){this._updateZoomParameters(s.clientX,s.clientX),this._dollyStart.set(s.clientX,s.clientY)}_handleMouseDownPan(s){this._panStart.set(s.clientX,s.clientY)}_handleMouseMoveRotate(s){this._rotateEnd.set(s.clientX,s.clientY),this._rotateDelta.subVectors(this._rotateEnd,this._rotateStart).multiplyScalar(this.rotateSpeed);const e=this.domElement;this._rotateLeft(Cn*this._rotateDelta.x/e.clientHeight),this._rotateUp(Cn*this._rotateDelta.y/e.clientHeight),this._rotateStart.copy(this._rotateEnd),this.update()}_handleMouseMoveDolly(s){this._dollyEnd.set(s.clientX,s.clientY),this._dollyDelta.subVectors(this._dollyEnd,this._dollyStart),this._dollyDelta.y>0?this._dollyOut(this._getZoomScale(this._dollyDelta.y)):this._dollyDelta.y<0&&this._dollyIn(this._getZoomScale(this._dollyDelta.y)),this._dollyStart.copy(this._dollyEnd),this.update()}_handleMouseMovePan(s){this._panEnd.set(s.clientX,s.clientY),this._panDelta.subVectors(this._panEnd,this._panStart).multiplyScalar(this.panSpeed),this._pan(this._panDelta.x,this._panDelta.y),this._panStart.copy(this._panEnd),this.update()}_handleMouseWheel(s){this._updateZoomParameters(s.clientX,s.clientY);let e;if(this.object.isOrthographicCamera)s.deltaY<0?this._dollyIn(this._getZoomScale(s.deltaY)):s.deltaY!==0&&this._dollyOut(this._getZoomScale(s.deltaY));else{const t=Math.abs(s.deltaY*.01);e=Math.pow(1.15,this.zoomSpeed*t),s.deltaY>0?this._scale/=e:s.deltaY!==0&&(this._scale*=e)}this.update()}_handleKeyDown(s){let e=!1;switch(s.code){case this.keys.UP:s.ctrlKey||s.metaKey||s.shiftKey?this.enableRotate&&this._rotateUp(Cn*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(0,this.keyPanSpeed),e=!0;break;case this.keys.BOTTOM:s.ctrlKey||s.metaKey||s.shiftKey?this.enableRotate&&this._rotateUp(-Cn*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(0,-this.keyPanSpeed),e=!0;break;case this.keys.LEFT:s.ctrlKey||s.metaKey||s.shiftKey?this.enableRotate&&this._rotateLeft(Cn*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(this.keyPanSpeed,0),e=!0;break;case this.keys.RIGHT:s.ctrlKey||s.metaKey||s.shiftKey?this.enableRotate&&this._rotateLeft(-Cn*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(-this.keyPanSpeed,0),e=!0;break}e&&(s.preventDefault(),this.update())}_handleTouchStartRotate(s){if(this._pointers.length===1)this._rotateStart.set(s.pageX,s.pageY);else{const e=this._getSecondPointerPosition(s),t=.5*(s.pageX+e.x),i=.5*(s.pageY+e.y);this._rotateStart.set(t,i)}}_handleTouchStartPan(s){if(this._pointers.length===1)this._panStart.set(s.pageX,s.pageY);else{const e=this._getSecondPointerPosition(s),t=.5*(s.pageX+e.x),i=.5*(s.pageY+e.y);this._panStart.set(t,i)}}_handleTouchStartDolly(s){const e=this._getSecondPointerPosition(s),t=s.pageX-e.x,i=s.pageY-e.y,n=Math.sqrt(t*t+i*i);this._dollyStart.set(0,n)}_handleTouchStartDollyPan(s){this.enableZoom&&this._handleTouchStartDolly(s),this.enablePan&&this._handleTouchStartPan(s)}_handleTouchStartDollyRotate(s){this.enableZoom&&this._handleTouchStartDolly(s),this.enableRotate&&this._handleTouchStartRotate(s)}_handleTouchMoveRotate(s){if(this._pointers.length==1)this._rotateEnd.set(s.pageX,s.pageY);else{const t=this._getSecondPointerPosition(s),i=.5*(s.pageX+t.x),n=.5*(s.pageY+t.y);this._rotateEnd.set(i,n)}this._rotateDelta.subVectors(this._rotateEnd,this._rotateStart).multiplyScalar(this.rotateSpeed);const e=this.domElement;this._rotateLeft(Cn*this._rotateDelta.x/e.clientHeight),this._rotateUp(Cn*this._rotateDelta.y/e.clientHeight),this._rotateStart.copy(this._rotateEnd)}_handleTouchMovePan(s){if(this._pointers.length===1)this._panEnd.set(s.pageX,s.pageY);else{const e=this._getSecondPointerPosition(s),t=.5*(s.pageX+e.x),i=.5*(s.pageY+e.y);this._panEnd.set(t,i)}this._panDelta.subVectors(this._panEnd,this._panStart).multiplyScalar(this.panSpeed),this._pan(this._panDelta.x,this._panDelta.y),this._panStart.copy(this._panEnd)}_handleTouchMoveDolly(s){const e=this._getSecondPointerPosition(s),t=s.pageX-e.x,i=s.pageY-e.y,n=Math.sqrt(t*t+i*i);this._dollyEnd.set(0,n),this._dollyDelta.set(0,Math.pow(this._dollyEnd.y/this._dollyStart.y,this.zoomSpeed)),this._dollyOut(this._dollyDelta.y),this._dollyStart.copy(this._dollyEnd);const r=(s.pageX+e.x)*.5,a=(s.pageY+e.y)*.5;this._updateZoomParameters(r,a)}_handleTouchMoveDollyPan(s){this.enableZoom&&this._handleTouchMoveDolly(s),this.enablePan&&this._handleTouchMovePan(s)}_handleTouchMoveDollyRotate(s){this.enableZoom&&this._handleTouchMoveDolly(s),this.enableRotate&&this._handleTouchMoveRotate(s)}_addPointer(s){this._pointers.push(s.pointerId)}_removePointer(s){delete this._pointerPositions[s.pointerId];for(let e=0;ee}set colliders(e){this._rayCastObjects=e}set enabled(e){this._isEnabled!==e&&(this._isEnabled=e,this._euler.setFromQuaternion(this.camera.quaternion),e?this.addEvents():this.removeEvents())}get enabled(){return this._isEnabled}getDeviceType(){return this._Engine?.deviceType??this._Engine?.deviceModule?.deviceType??this._Engine?.DeviceType??"PC"}isPCDevice(){return this.getDeviceType()==="PC"}supportsPointerLock(){return!!(this.isPCDevice()&&this.domElement&&typeof this.domElement.requestPointerLock=="function")}requestPointerLock(){this.supportsPointerLock()&&document.pointerLockElement!==this.domElement&&this.domElement.requestPointerLock()}exitPointerLock(){typeof document>"u"||typeof document.exitPointerLock!="function"||document.pointerLockElement===this.domElement&&document.exitPointerLock()}addEvents(){this.isPCDevice()?(this.domElement.addEventListener("mousedown",this.bindmousedown,!1),this.domElement.addEventListener("mouseup",this.bindmouseup,!1),window.addEventListener("mouseup",this.bindmouseup,!1),document.addEventListener("pointerlockchange",this.bindPointerLockChange,!1),document.addEventListener("pointerlockerror",this.bindPointerLockError,!1),window.addEventListener("blur",this.bindWindowBlur,!1)):(this.domElement.addEventListener("touchstart",this.bindmousedown,!1),this.domElement.addEventListener("touchend",this.bindmouseup,!1)),this.domElement.addEventListener("mouseenter",this.bindMouseEnter,!1),this.domElement.addEventListener("mouseleave",this.bindMouseLeave,!1),window.addEventListener("keydown",this.bindonKeyDown,!1),window.addEventListener("keyup",this.bindonKeyUp,!1),this.needMousewheel&&(document.addEventListener&&document.addEventListener("DOMMouseScroll",this.bindMousewheel,!1),window.addEventListener("mousewheel",this.bindMousewheel,!1))}removeEvents(){this.isPCDevice()?(this.domElement.removeEventListener("mousedown",this.bindmousedown),this.domElement.removeEventListener("mouseup",this.bindmouseup),this.domElement.removeEventListener("mousemove",this.bindmousemove),window.removeEventListener("mouseup",this.bindmouseup),document.removeEventListener("mousemove",this.bindmousemove),document.removeEventListener("pointerlockchange",this.bindPointerLockChange),document.removeEventListener("pointerlockerror",this.bindPointerLockError),window.removeEventListener("blur",this.bindWindowBlur),this.exitPointerLock()):(this.domElement.removeEventListener("touchstart",this.bindmousedown),this.domElement.removeEventListener("touchend",this.bindmouseup),this.domElement.removeEventListener("touchmove",this.bindmousemove)),this.domElement.removeEventListener("mouseenter",this.bindMouseEnter),this.domElement.removeEventListener("mouseleave",this.bindMouseLeave),window.removeEventListener("keydown",this.bindonKeyDown),window.removeEventListener("keyup",this.bindonKeyUp),this.needMousewheel&&(document.addEventListener&&document.removeEventListener("DOMMouseScroll",this.bindMousewheel),window.removeEventListener("mousewheel",this.bindMousewheel)),this.resetMouseRotationState()}resetMouseRotationState(){this._isRotating=!1,this._isPointerLocked=!1,this._prevMouseX=0,this._prevMouseY=0,this.domElement?.style&&(this.domElement.style.cursor="");const e=this.GetEngine();e&&(e.movefirst=!1)}onPointerLockChange(){if(this._isPointerLocked=document.pointerLockElement===this.domElement,this._isPointerLocked){document.addEventListener("mousemove",this.bindmousemove,!1),this.domElement?.style&&(this.domElement.style.cursor="none");return}document.removeEventListener("mousemove",this.bindmousemove),this.resetMouseRotationState()}onPointerLockError(){this.resetMouseRotationState()}onWindowBlur(){this.exitPointerLock(),this.resetMouseRotationState()}onMouseEnter(){this._isMouseInElement=!0}onMouseLeave(){this._isMouseInElement=!1}onMousewheel(e){let t;switch(e.wheelDelta?(e.wheelDelta>0&&(t="up"),e.wheelDelta<0&&(t="down")):e.detail&&(e.detail<0&&(t="up"),e.detail>0&&(t="down")),t){case"up":this._camerLocalDirection.z=1;break;case"down":this._camerLocalDirection.z=-1;break}this.moveWheelRun===!0?(this.moveWheelRun=!1,this.moveWheelStop=!0,this.wheelClock=setTimeout(()=>{this.moveWheelStop===!0&&(this.moveWheelStop=!1,this.moveWheelRun=!0,this._camerLocalDirection.z=0)},200)):(clearTimeout(this.wheelClock),this.wheelClock=setTimeout(()=>{this.moveWheelStop===!0&&(this.moveWheelStop=!1,this.moveWheelRun=!0,this._camerLocalDirection.z=0)},150))}onMouseDown(e){if(!(e.button!==0||this._isEnabled===!1)){if(this._isRotating=!0,e.preventDefault?.(),this.supportsPointerLock()){this.requestPointerLock();return}this.domElement.addEventListener("mousemove",this.bindmousemove,!1),this._prevMouseX=e.clientX??e.screenX,this._prevMouseY=e.clientY??e.screenY,this.domElement?.style&&(this.domElement.style.cursor="none")}}onMouseMove(e){if(this._isEnabled===!1||!this._isRotating&&!this._isPointerLocked)return;let t=0,i=0;if(this._isPointerLocked)t=e.movementX||0,i=e.movementY||0;else{const o=e.clientX??e.screenX,l=e.clientY??e.screenY;t=this._prevMouseX?o-this._prevMouseX:0,i=this._prevMouseY?l-this._prevMouseY:0,this._prevMouseX=o,this._prevMouseY=l}let n=this._euler.x-i*this.lookflag*this.lookSpeed;n>=0?n-this.maxRotateX?this._euler.x=n:this._euler.x=-this.maxRotateX,this._euler.y-=t*this.lookSpeed,this.camera.quaternion.setFromEuler(this._euler);const r=this.GetEngine();r.movefirst=!0;const a=new CustomEvent("bimengine:camerachange",{detail:""});window.dispatchEvent(a)}onMouseUp(e={}){e.button!=null&&e.button!==0||(this.domElement.removeEventListener("mousemove",this.bindmousemove),this.exitPointerLock(),this.resetMouseRotationState())}onTouchStart(e){this._isEnabled!==!1&&(this.domElement.addEventListener("touchmove",this.bindmousemove,!1),this._prevMouseX=e.targetTouches[0].clientX,this._prevMouseY=e.targetTouches[0].clientY)}onTouchMove(e){if(this._isEnabled===!1)return;let t=this._prevMouseX?e.targetTouches[0].clientX-this._prevMouseX:0,i=this._prevMouseY?e.targetTouches[0].clientY-this._prevMouseY:0,n=this._euler.x-i*this.lookflag*this.lookSpeed;n>=0?n-this.maxRotateX?this._euler.x=n:this._euler.x=-this.maxRotateX,this._euler.y-=t*this.lookSpeed,this.camera.quaternion.setFromEuler(this._euler),this._prevMouseX=e.targetTouches[0].clientX,this._prevMouseY=e.targetTouches[0].clientY;const r=this.GetEngine();r.movefirst=!0;const a=new CustomEvent("bimengine:camerachange",{detail:""});window.dispatchEvent(a)}onTouchEnd(){const e=this.GetEngine();e.movefirst=!1,this.domElement.removeEventListener("touchmove",this.bindmousemove)}onKeyDown(e){if(!this._isMouseInElement)return;const t=new CustomEvent("bimengine:camerachange",{detail:""}),i=this.GetEngine();switch(i.movefirst=!0,window.dispatchEvent(t),e.keyCode){case 38:this.rotateY(-1);break;case 81:this.keydown=!0,this._camerLocalDirection.y=1;break;case 69:this._camerLocalDirection.y=-1;break;case 87:this._camerLocalDirection.z=1;break;case 37:this.rotateX(-1);break;case 65:this._camerLocalDirection.x=-1;break;case 40:this.rotateY(1);break;case 83:this._camerLocalDirection.z=-1;break;case 39:this.rotateX(1);break;case 68:this._camerLocalDirection.x=1;break}}onKeyUp(e){if(!this._isMouseInElement)return;const t=this.GetEngine();switch(t.movefirst=!1,e.keyCode){case 38:case 87:this._camerLocalDirection.z=0;break;case 37:case 65:this._camerLocalDirection.x=0;break;case 40:case 83:this._camerLocalDirection.z=0;break;case 39:case 68:this._camerLocalDirection.x=0;break;case 81:case 69:this.keydown=!1,this._camerLocalDirection.y=0;break}}rotateX(e){this._euler.y-=e*this.lookSpeed,this.camera.quaternion.setFromEuler(this._euler)}rotateY(e){let t=this._euler.x-e*this.lookflag*.5*this.lookSpeed;t>=0?t-this.maxRotateX?this._euler.x=t:this._euler.x=-this.maxRotateX,this.camera.quaternion.setFromEuler(this._euler)}update(){this.keydown||this.gravityTest(),this.collisionTest()}gravityTest(){if(this.applyGravity){let e=!0;this._fallingTime+=.01,this._tmpVector.set(0,-1,0);const t=this.hitTest();if(t){const i=t.point.add(new R(0,this.playerHeight,0));if(this.positionEasing){if(i.y>=this.camera.position.y||i.y-this.camera.position.y<.2){this.setCameraHeight(this.camera.position.y+(i.y-this.camera.position.y)*.08),this._fallingTime=0,e=!1;return}}else t.distancec.url==o);if(l!=null){const c=l.nodesMap.get(a);if(c.infos!=null&&c.infos.length!==0&&c.infos[0].name&&c.infos[0].name.includes("门"))return null}return r}dispose(){this.enabled=!1}}function Yv(s){const e={self:null,options:null,mouseDownTime:0,mouseDownPosition:null,lastClickTime:0};e.handle_catch=function(g,m){return v(g,m,!0)},e.init=function(g,m){e.self!=null&&e.self.disActive!=null&&e.self.type!=g.type&&e.self.disActive(),e.self=g,m==null&&(m={showCatch:!1}),e.options=m},e.render=function(){e.self&&e.self.render!=null&&e.self.render()},e.active=function(){s.renderer.domElement.addEventListener("mousedown",o),s.renderer.domElement.addEventListener("mouseup",c),s.renderer.domElement.addEventListener("mousemove",l),s.renderer.domElement.addEventListener("touchstart",d,{passive:!1}),s.renderer.domElement.addEventListener("touchend",u,{passive:!1}),s.renderer.domElement.addEventListener("touchmove",p,{passive:!1}),window.addEventListener("keydown",t),window.addEventListener("keyup",i)},e.disActive=function(){s.renderer.domElement.removeEventListener("mousedown",o),s.renderer.domElement.removeEventListener("mouseup",c),s.renderer.domElement.removeEventListener("mousemove",l),s.renderer.domElement.removeEventListener("touchstart",d),s.renderer.domElement.removeEventListener("touchend",u),s.renderer.domElement.removeEventListener("touchmove",p),window.removeEventListener("keydown",t),window.removeEventListener("keyup",i)};function t(g){(g.keyCode===8||g.keyCode===46)&&e.self&&e.self.handelKeyDeleteDown!=null&&e.self.handelKeyDeleteDown(),g.keyCode===27&&e.self&&e.self.handelKeyEscDown!=null&&e.self.handelKeyEscDown(),g.keyCode===13&&e.self&&e.self.handelKeyEnterDown!=null&&e.self.handelKeyEnterDown(),g.keyCode===32&&e.self&&e.self.handelKeySpaceDown!=null&&e.self.handelKeySpaceDown(),g.key==="Control"&&e.self&&e.self.handelKeyCtrlDown!=null&&e.self.handelKeyCtrlDown(),g.key==="Delete"&&e.self&&e.self.handelKeyDeleteDown!=null&&e.self.handelKeyDeleteDown(),g.key==="Shift"&&e.self&&e.self.handelKeyShiftDown!=null&&e.self.handelKeyShiftDown(),g.key==="Meta"&&e.self&&e.self.handelKeyMetaDown!=null&&e.self.handelKeyMetaDown()}function i(g){g.key==="Alt"&&e.self&&e.self.handelKeyAltUp!=null&&e.self.handelKeyAltUp(),g.key==="Tab"&&e.self&&e.self.handelKeyTabUp!=null&&e.self.handelKeyTabUp(),g.key==="Control"&&e.self&&e.self.handelKeyCtrlUp!=null&&e.self.handelKeyCtrlUp(),g.key==="Shift"&&e.self&&e.self.handelKeyShiftUp!=null&&e.self.handelKeyShiftUp(),g.key==="Meta"&&e.self&&e.self.handelKeyMetaUp!=null&&e.self.handelKeyMetaUp(),g.key==="Command"&&e.self&&e.self.handelKeyCommandUp!=null&&e.self.handelKeyCommandUp(),g.key==="Windows"&&e.self&&e.self.handelKeyWindowsUp!=null&&e.self.handelKeyWindowsUp()}function n(g){const m=new me,f=s.renderer.domElement.clientWidth,y=s.renderer.domElement.clientHeight;return m.x=g.offsetX/f*2-1,m.y=-(g.offsetY/y)*2+1,m}function r(g){const m=new Qn,f=n(g);return m.setFromCamera(f,s.camera),m}function a(g,m=!1,f=!1){const y=r(g);if(g.raycaster=y,m){const x=v(y,g,f);g.catch=x}}function o(g){g.button===0&&(e.mouseDownTime=Date.now(),e.mouseDownPosition=new R(g.offsetX,g.offsetY,0),e.self&&e.self.handleMouseDown!=null&&(a(g,!0,!0),g.catch!=null&&(s.engineStatus.highlightModels==null||s.engineStatus.highlightModels.length==0)&&s.controlModule.orbitControls.origin.set(g.catch.point.x,g.catch.point.y,g.catch.point.z),e.self.handleMouseDown(g)))}function l(g){e.self&&e.self.handleMouseMove!=null&&((s.engineStatus.isFree||s.engineStatus.isForceFree)&&a(g,!0,!0),e.self.handleMouseMove(g))}function c(g){if(g.button!==0)return;const m=Date.now(),f=m-e.mouseDownTime,y=new R(g.offsetX,g.offsetY,0);e.self&&e.self.handleMouseUp!=null&&(a(g,!1),e.self.handleMouseUp(g));const x=y.distanceTo(e.mouseDownPosition);if((f<100||x==0)&&e.self&&e.self.handleMouseClick!=null){a(g,!0,!0);const _=m-e.lastClickTime;console.log(_),_<200?e.self.handleMouseDoubleClick!=null&&e.self.handleMouseDoubleClick(g):e.self.handleMouseClick!=null&&e.self.handleMouseClick(g),e.lastClickTime=Date.now()}}function h(g){const m=g.touches[0]||g.changedTouches[0];if(!m)return null;const f=s.renderer.domElement.getBoundingClientRect(),y=m.clientX-f.left,x=m.clientY-f.top;return{offsetX:y,offsetY:x,button:0,clientX:m.clientX,clientY:m.clientY,preventDefault:()=>g.preventDefault(),stopPropagation:()=>g.stopPropagation(),originalEvent:g}}function d(g){if(g.preventDefault(),g.touches.length!==1)return;const m=h(g);m&&o(m)}function p(g){if(g.preventDefault(),g.touches.length!==1)return;const m=h(g);m&&l(m)}function u(g){g.preventDefault();const m=h(g);m&&c(m)}function v(g,m,f=!1){if(!s.engineStatus.isFree&&f==!1){s.hoverHighLight.clearHighlight();return}console.log("catch"),s.catchSvg.innerHTML="";let y=s.octreeBox.rayInterationModel(g,f);y=s.clipping?.filterIntersectionsByClipping(y)??y;let x=g.intersectObjects(s.scene.children.filter(F=>F instanceof ti),!0);if(x=s.clipping?.filterIntersectionsByClipping(x)??x,x.length>0&&(y.length==0||x[0].distance{F[0]!=null&&F[1]!=null&&E.push({X:F[0].X*.5+F[1].X*.5,Y:F[0].Y*.5+F[1].Y*.5,Z:F[0].Z*.5+F[1].Z*.5})});let w=[...b[2].map(F=>F[0]),...E],M="face",C=[],I=[],P=10;if(w.forEach(F=>{if(F!=null){let H=new R(F.X,F.Z,-F.Y);if(s.clipping&&!s.clipping.isPointInClippingRange(H))return;let q=new zt(s.camera,s.renderer,s.scene).worldToScreen(H),G=Math.sqrt(Math.pow(q.x-m.offsetX,2)+Math.pow(q.y-m.offsetY,2));G0?(C.sort((F,H)=>F.distance-H.distance),M="point"):(b[2].forEach(F=>{if(F[0]!=null&&F[1]!=null){let H=new R(F[0].X,F[0].Z,-F[0].Y),q=new R(F[1].X,F[1].Z,-F[1].Y),G=new zt(s.camera,s.renderer,s.scene).worldToScreen(H),re=new zt(s.camera,s.renderer,s.scene).worldToScreen(q),Y=k(new me(m.offsetX,m.offsetY),G,re);if(Y0&&(I.sort((F,H)=>F.distance-H.distance),M="line")),M=="point"&&e.options.showCatch){const F=new zt(s.camera,s.renderer,s.scene).worldToScreen(C[0].point);s.catchSvg.innerHTML="";const H=F.x+s.reactBoundingClientRect.left,q=F.y+s.reactBoundingClientRect.top;console.log(H,q);const G=document.createElementNS("http://www.w3.org/2000/svg","polygon");G.setAttribute("class","catchPoint"),G.setAttribute("points",`${H},${q-8} ${H-7},${q+4} ${H+7},${q+4}`),G.setAttribute("stroke","rgb(8, 223, 215)"),G.setAttribute("fill","transparent"),s.catchSvg.appendChild(G),y[0].point=C[0].point}else if(M=="line"&&e.options.showCatch){const F=new zt(s.camera,s.renderer,s.scene).worldToScreen(I[0].point),H=I[0].start,q=I[0].end;s.catchSvg.innerHTML="";const G=document.createElementNS("http://www.w3.org/2000/svg","line");G.setAttribute("class","catchLine"),G.setAttribute("x1",(H.x+s.reactBoundingClientRect.left).toString()),G.setAttribute("y1",(H.y+s.reactBoundingClientRect.top).toString()),G.setAttribute("x2",(q.x+s.reactBoundingClientRect.left).toString()),G.setAttribute("y2",(q.y+s.reactBoundingClientRect.top).toString()),G.setAttribute("stroke","rgb(8, 223, 215)"),G.setAttribute("stroke-width","2"),s.catchSvg.appendChild(G);const re=F.x+s.reactBoundingClientRect.left,Y=F.y+s.reactBoundingClientRect.top,$=document.createElementNS("http://www.w3.org/2000/svg","polygon");$.setAttribute("class","catchPoint"),$.setAttribute("points",`${re},${Y-8} ${re-7},${Y+4} ${re+7},${Y+4}`),$.setAttribute("stroke","rgb(8, 223, 215)"),$.setAttribute("fill","transparent"),s.catchSvg.appendChild($),y[0].point=I[0].point}else if(M=="face"&&e.options.showCatch){let F=y[0].point.clone(),H=y[0].normal||(y[0].face?y[0].face.normal:null);const q=(H?H.clone():new R(0,0,1)).normalize(),G=Math.abs(q.y)<.9?new R(0,1,0):new R(1,0,0),re=new R().crossVectors(q,G).normalize(),Y=new R().crossVectors(q,re).normalize(),$=.2,_e=[new R().copy(re).add(Y).multiplyScalar($),new R().copy(re).sub(Y).multiplyScalar($),new R().copy(re).multiplyScalar(-1).sub(Y).multiplyScalar($),new R().copy(re).multiplyScalar(-1).add(Y).multiplyScalar($)].map(be=>new R().copy(F).add(be)).map(be=>new zt(s.camera,s.renderer,s.scene).worldToScreen(be));s.catchSvg.innerHTML="";const Te=document.createElementNS("http://www.w3.org/2000/svg","polygon");Te.setAttribute("class","catchFace"),Te.setAttribute("points",_e.map(be=>`${be.x+s.reactBoundingClientRect.left},${be.y+s.reactBoundingClientRect.top}`).join(" ")),Te.setAttribute("fill","rgba(1, 238, 255, 0.2)"),Te.setAttribute("stroke","rgb(0, 255, 247)"),Te.setAttribute("stroke-width","1"),s.catchSvg.appendChild(Te)}return y[0];function k(F,H,q){const G=new me().subVectors(q,H),re=G.lengthSq();if(re<1e-10)return F.distanceTo(H);const Y=new me().subVectors(F,H),$=Lt.clamp(Y.dot(G)/re,0,1),_e=new me().copy(G).multiplyScalar($).add(H);return F.distanceTo(_e)}function A(F,H,q){const G=new me().subVectors(q,H),re=G.lengthSq();if(re<1e-10)return 0;const Y=new me().subVectors(F,H);return Lt.clamp(Y.dot(G)/re,0,1)}function B(F,H,q){const G=Lt.clamp(F,0,1);return new R().lerpVectors(H,q,G)}}return e}class C8{engine;orbitControls;firstPersonControls;isActive=!0;originDiv=null;handelBehaved;isDragging=!1;isDown=!1;containerOffset={left:0,top:0};constructor(e){this.engine=e,this.init(),this.handelBehaved=Yv(this.engine),this.handelBehaved.init(this,null),this.handelBehaved.active()}init(){this.orbitControls=new f8(this.engine,this.engine.camera,this.engine.renderer.domElement),this.orbitControls.showOriginIcon=!0,this.firstPersonControls=new tS(this.engine,this.engine.camera,this.engine.renderer.domElement);const e=document.createElement("div");this.originDiv=e,e.className="originDiv",e.style.position="absolute",e.style.top="0px",e.style.left="0px",e.style.width="30px",e.style.height="30px",e.style.borderRadius="50%",e.style.pointerEvents="none",e.style.backgroundImage="url(/assets/svg/rotate-orbit.svg)",this.engine.container.appendChild(this.originDiv)}active(){this.isActive=!0,this.orbitControls.enabled=!0}disActive(){this.isActive=!1,this.orbitControls.enabled=!1}setMoveSpeed(e){this.firstPersonControls.moveSpeed=e*.1}getMoveSpeed(){return this.firstPersonControls.moveSpeed*10}setApplyCollision(e){this.firstPersonControls.applyCollision=e}getApplyCollision(){return this.firstPersonControls.applyCollision}setApplyGravity(e){this.firstPersonControls.applyGravity=e}getApplyGravity(){return this.firstPersonControls.applyGravity}toggleMinMap(){this.engine.minMap.toggle()}switchFirstPersonMode(){this.engine.cameraModule.switchToPerspectiveCamera(),this.firstPersonControls=new tS(this.engine,this.engine.camera,this.engine.renderer.domElement,[]),this.orbitControls.enabled=!1,this.firstPersonControls.enabled=!0,this.firstPersonControls.isActive=!0,this.engine.worldToScreen=new zt(this.engine.camera,this.engine.renderer,this.engine.scene)}switchDefaultMode(){this.firstPersonControls&&(this.firstPersonControls.enabled=!1),this.orbitControls.enabled=!0,this.engine.worldToScreen=new zt(this.engine.camera,this.engine.renderer,this.engine.scene)}handleMouseUp(e){this.isDragging=!1,this.isDown=!1}handleMouseMove(e){this.isDown?this.isDragging=!0:this.isDragging=!1}handleMouseDown(e){this.isDown=!0}handleMouseClick(e){this.isDragging=!1,this.isDown=!1}update(){if(this.firstPersonControls.enabled&&this.firstPersonControls.update(),this.orbitControls.enabled){const e=this.engine.controlModule.orbitControls.origin,t=this.engine.worldToScreen.worldToScreen(e);this.originDiv&&this.isDragging?(this.originDiv.style.left=t.x-15+this.engine.reactBoundingClientRect.left+"px",this.originDiv.style.top=t.y-15+this.engine.reactBoundingClientRect.top+"px",this.originDiv.style.display="block"):this.originDiv&&(this.originDiv.style.display="none")}}}const yo={name:"CopyShader",uniforms:{tDiffuse:{value:null},opacity:{value:1}},vertexShader:` varying vec2 vUv; void main() { vUv = uv; gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); }`,fragmentShader:` uniform float opacity; uniform sampler2D tDiffuse; varying vec2 vUv; void main() { vec4 texel = texture2D( tDiffuse, vUv ); gl_FragColor = opacity * texel; }`};class xo{constructor(){this.isPass=!0,this.enabled=!0,this.needsSwap=!0,this.clear=!1,this.renderToScreen=!1}setSize(){}render(){console.error("THREE.Pass: .render() must be implemented in derived pass.")}dispose(){}}const A8=new rn(-1,1,1,-1,0,1);class P8 extends at{constructor(){super(),this.setAttribute("position",new et([-1,3,0,-1,-1,0,3,-1,0],3)),this.setAttribute("uv",new et([0,2,0,0,2,0],2))}}const R8=new P8;class Mf{constructor(e){this._mesh=new ht(R8,e)}dispose(){this._mesh.geometry.dispose()}render(e){e.render(this._mesh,A8)}get material(){return this._mesh.material}set material(e){this._mesh.material=e}}class Sf extends xo{constructor(e,t="tDiffuse"){super(),this.textureID=t,this.uniforms=null,this.material=null,e instanceof Jt?(this.uniforms=e.uniforms,this.material=e):e&&(this.uniforms=nn.clone(e.uniforms),this.material=new Jt({name:e.name!==void 0?e.name:"unspecified",defines:Object.assign({},e.defines),uniforms:this.uniforms,vertexShader:e.vertexShader,fragmentShader:e.fragmentShader})),this._fsQuad=new Mf(this.material)}render(e,t,i){this.uniforms[this.textureID]&&(this.uniforms[this.textureID].value=i.texture),this._fsQuad.material=this.material,this.renderToScreen?(e.setRenderTarget(null),this._fsQuad.render(e)):(e.setRenderTarget(t),this.clear&&e.clear(e.autoClearColor,e.autoClearDepth,e.autoClearStencil),this._fsQuad.render(e))}dispose(){this.material.dispose(),this._fsQuad.dispose()}}class iS extends xo{constructor(e,t){super(),this.scene=e,this.camera=t,this.clear=!0,this.needsSwap=!1,this.inverse=!1}render(e,t,i){const n=e.getContext(),r=e.state;r.buffers.color.setMask(!1),r.buffers.depth.setMask(!1),r.buffers.color.setLocked(!0),r.buffers.depth.setLocked(!0);let a,o;this.inverse?(a=0,o=1):(a=1,o=0),r.buffers.stencil.setTest(!0),r.buffers.stencil.setOp(n.REPLACE,n.REPLACE,n.REPLACE),r.buffers.stencil.setFunc(n.ALWAYS,a,4294967295),r.buffers.stencil.setClear(o),r.buffers.stencil.setLocked(!0),e.setRenderTarget(i),this.clear&&e.clear(),e.render(this.scene,this.camera),e.setRenderTarget(t),this.clear&&e.clear(),e.render(this.scene,this.camera),r.buffers.color.setLocked(!1),r.buffers.depth.setLocked(!1),r.buffers.color.setMask(!0),r.buffers.depth.setMask(!0),r.buffers.stencil.setLocked(!1),r.buffers.stencil.setFunc(n.EQUAL,1,4294967295),r.buffers.stencil.setOp(n.KEEP,n.KEEP,n.KEEP),r.buffers.stencil.setLocked(!0)}}class I8 extends xo{constructor(){super(),this.needsSwap=!1}render(e){e.state.buffers.stencil.setLocked(!1),e.state.buffers.stencil.setTest(!1)}}class L8{constructor(e,t){if(this.renderer=e,this._pixelRatio=e.getPixelRatio(),t===void 0){const i=e.getSize(new me);this._width=i.width,this._height=i.height,t=new bi(this._width*this._pixelRatio,this._height*this._pixelRatio,{type:_i}),t.texture.name="EffectComposer.rt1"}else this._width=t.width,this._height=t.height;this.renderTarget1=t,this.renderTarget2=t.clone(),this.renderTarget2.texture.name="EffectComposer.rt2",this.writeBuffer=this.renderTarget1,this.readBuffer=this.renderTarget2,this.renderToScreen=!0,this.passes=[],this.copyPass=new Sf(yo),this.copyPass.material.blending=Qt,this.timer=new Jg}swapBuffers(){const e=this.readBuffer;this.readBuffer=this.writeBuffer,this.writeBuffer=e}addPass(e){this.passes.push(e),e.setSize(this._width*this._pixelRatio,this._height*this._pixelRatio)}insertPass(e,t){this.passes.splice(t,0,e),e.setSize(this._width*this._pixelRatio,this._height*this._pixelRatio)}removePass(e){const t=this.passes.indexOf(e);t!==-1&&this.passes.splice(t,1)}isLastEnabledPass(e){for(let t=e+1;t #include #ifndef FRAGMENT_OUTPUT #define FRAGMENT_OUTPUT vec4(vec3(ao), 1.) #endif vec3 getViewPosition( const in vec2 screenPosition, const in float depth ) { #ifdef USE_REVERSED_DEPTH_BUFFER vec4 clipSpacePosition = vec4( vec2( screenPosition ) * 2.0 - 1.0, depth, 1.0 ); #else vec4 clipSpacePosition = vec4( vec3( screenPosition, depth ) * 2.0 - 1.0, 1.0 ); #endif vec4 viewSpacePosition = cameraProjectionMatrixInverse * clipSpacePosition; return viewSpacePosition.xyz / viewSpacePosition.w; } float getDepth(const vec2 uv) { return textureLod(tDepth, uv.xy, 0.0).DEPTH_SWIZZLING; } float fetchDepth(const ivec2 uv) { return texelFetch(tDepth, uv.xy, 0).DEPTH_SWIZZLING; } float getViewZ(const in float depth) { #if PERSPECTIVE_CAMERA == 1 return perspectiveDepthToViewZ(depth, cameraNear, cameraFar); #else return orthographicDepthToViewZ(depth, cameraNear, cameraFar); #endif } vec3 computeNormalFromDepth(const vec2 uv) { vec2 size = vec2(textureSize(tDepth, 0)); ivec2 p = ivec2(uv * size); float c0 = fetchDepth(p); float l2 = fetchDepth(p - ivec2(2, 0)); float l1 = fetchDepth(p - ivec2(1, 0)); float r1 = fetchDepth(p + ivec2(1, 0)); float r2 = fetchDepth(p + ivec2(2, 0)); float b2 = fetchDepth(p - ivec2(0, 2)); float b1 = fetchDepth(p - ivec2(0, 1)); float t1 = fetchDepth(p + ivec2(0, 1)); float t2 = fetchDepth(p + ivec2(0, 2)); float dl = abs((2.0 * l1 - l2) - c0); float dr = abs((2.0 * r1 - r2) - c0); float db = abs((2.0 * b1 - b2) - c0); float dt = abs((2.0 * t1 - t2) - c0); vec3 ce = getViewPosition(uv, c0).xyz; vec3 dpdx = (dl < dr) ? ce - getViewPosition((uv - vec2(1.0 / size.x, 0.0)), l1).xyz : -ce + getViewPosition((uv + vec2(1.0 / size.x, 0.0)), r1).xyz; vec3 dpdy = (db < dt) ? ce - getViewPosition((uv - vec2(0.0, 1.0 / size.y)), b1).xyz : -ce + getViewPosition((uv + vec2(0.0, 1.0 / size.y)), t1).xyz; return normalize(cross(dpdx, dpdy)); } vec3 getViewNormal(const vec2 uv) { #if NORMAL_VECTOR_TYPE == 2 return normalize(textureLod(tNormal, uv, 0.).rgb); #elif NORMAL_VECTOR_TYPE == 1 return unpackRGBToNormal(textureLod(tNormal, uv, 0.).rgb); #else return computeNormalFromDepth(uv); #endif } vec3 getSceneUvAndDepth(vec3 sampleViewPos) { vec4 sampleClipPos = cameraProjectionMatrix * vec4(sampleViewPos, 1.); vec2 sampleUv = sampleClipPos.xy / sampleClipPos.w * 0.5 + 0.5; float sampleSceneDepth = getDepth(sampleUv); return vec3(sampleUv, sampleSceneDepth); } void main() { float depth = getDepth(vUv.xy); #ifdef USE_REVERSED_DEPTH_BUFFER if (depth <= 0.0) { discard; return; } #else if (depth >= 1.0) { discard; return; } #endif vec3 viewPos = getViewPosition(vUv, depth); vec3 viewNormal = getViewNormal(vUv); float radiusToUse = radius; float distanceFalloffToUse = thickness; #if SCREEN_SPACE_RADIUS == 1 float radiusScale = getViewPosition(vec2(0.5 + float(SCREEN_SPACE_RADIUS_SCALE) / resolution.x, 0.0), depth).x; radiusToUse *= radiusScale; distanceFalloffToUse *= radiusScale; #endif #if SCENE_CLIP_BOX == 1 vec3 worldPos = (cameraWorldMatrix * vec4(viewPos, 1.0)).xyz; float boxDistance = length(max(vec3(0.0), max(sceneBoxMin - worldPos, worldPos - sceneBoxMax))); if (boxDistance > radiusToUse) { discard; return; } #endif vec2 noiseResolution = vec2(textureSize(tNoise, 0)); vec2 noiseUv = vUv * resolution / noiseResolution; vec4 noiseTexel = textureLod(tNoise, noiseUv, 0.0); vec3 randomVec = noiseTexel.xyz * 2.0 - 1.0; vec3 tangent = normalize(vec3(randomVec.xy, 0.)); vec3 bitangent = vec3(-tangent.y, tangent.x, 0.); mat3 kernelMatrix = mat3(tangent, bitangent, vec3(0., 0., 1.)); const int DIRECTIONS = SAMPLES < 30 ? 3 : 5; const int STEPS = (SAMPLES + DIRECTIONS - 1) / DIRECTIONS; float ao = 0.0; for (int i = 0; i < DIRECTIONS; ++i) { float angle = float(i) / float(DIRECTIONS) * PI; vec4 sampleDir = vec4(cos(angle), sin(angle), 0., 0.5 + 0.5 * noiseTexel.w); sampleDir.xyz = normalize(kernelMatrix * sampleDir.xyz); vec3 viewDir = normalize(-viewPos.xyz); vec3 sliceBitangent = normalize(cross(sampleDir.xyz, viewDir)); vec3 sliceTangent = cross(sliceBitangent, viewDir); vec3 normalInSlice = normalize(viewNormal - sliceBitangent * dot(viewNormal, sliceBitangent)); vec3 tangentToNormalInSlice = cross(normalInSlice, sliceBitangent); vec2 cosHorizons = vec2(dot(viewDir, tangentToNormalInSlice), dot(viewDir, -tangentToNormalInSlice)); for (int j = 0; j < STEPS; ++j) { vec3 sampleViewOffset = sampleDir.xyz * radiusToUse * sampleDir.w * pow(float(j + 1) / float(STEPS), distanceExponent); vec3 sampleSceneUvDepth = getSceneUvAndDepth(viewPos + sampleViewOffset); vec3 sampleSceneViewPos = getViewPosition(sampleSceneUvDepth.xy, sampleSceneUvDepth.z); vec3 viewDelta = sampleSceneViewPos - viewPos; if (abs(viewDelta.z) < thickness) { float sampleCosHorizon = dot(viewDir, normalize(viewDelta)); cosHorizons.x += max(0., (sampleCosHorizon - cosHorizons.x) * mix(1., 2. / float(j + 2), distanceFallOff)); } sampleSceneUvDepth = getSceneUvAndDepth(viewPos - sampleViewOffset); sampleSceneViewPos = getViewPosition(sampleSceneUvDepth.xy, sampleSceneUvDepth.z); viewDelta = sampleSceneViewPos - viewPos; if (abs(viewDelta.z) < thickness) { float sampleCosHorizon = dot(viewDir, normalize(viewDelta)); cosHorizons.y += max(0., (sampleCosHorizon - cosHorizons.y) * mix(1., 2. / float(j + 2), distanceFallOff)); } } vec2 sinHorizons = sqrt(1. - cosHorizons * cosHorizons); float nx = dot(normalInSlice, sliceTangent); float ny = dot(normalInSlice, viewDir); float nxb = 1. / 2. * (acos(cosHorizons.y) - acos(cosHorizons.x) + sinHorizons.x * cosHorizons.x - sinHorizons.y * cosHorizons.y); float nyb = 1. / 2. * (2. - cosHorizons.x * cosHorizons.x - cosHorizons.y * cosHorizons.y); float occlusion = nx * nxb + ny * nyb; ao += occlusion; } ao = clamp(ao / float(DIRECTIONS), 0., 1.); #if SCENE_CLIP_BOX == 1 ao = mix(ao, 1., smoothstep(0., radiusToUse, boxDistance)); #endif ao = pow(ao, scale); gl_FragColor = FRAGMENT_OUTPUT; }`},Ef={defines:{PERSPECTIVE_CAMERA:1},uniforms:{tDepth:{value:null},cameraNear:{value:null},cameraFar:{value:null}},vertexShader:` varying vec2 vUv; void main() { vUv = uv; gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); }`,fragmentShader:` uniform sampler2D tDepth; uniform float cameraNear; uniform float cameraFar; varying vec2 vUv; #include float getLinearDepth( const in vec2 screenPosition ) { #if PERSPECTIVE_CAMERA == 1 float fragCoordZ = texture2D( tDepth, screenPosition ).x; float viewZ = perspectiveDepthToViewZ( fragCoordZ, cameraNear, cameraFar ); return viewZToOrthographicDepth( viewZ, cameraNear, cameraFar ); #else return texture2D( tDepth, screenPosition ).x; #endif } void main() { float depth = getLinearDepth( vUv ); gl_FragColor = vec4( vec3( 1.0 - depth ), 1.0 ); }`},$v={uniforms:{tDiffuse:{value:null},intensity:{value:1}},vertexShader:` varying vec2 vUv; void main() { vUv = uv; gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); }`,fragmentShader:` uniform float intensity; uniform sampler2D tDiffuse; varying vec2 vUv; void main() { vec4 texel = texture2D( tDiffuse, vUv ); gl_FragColor = vec4(mix(vec3(1.), texel.rgb, intensity), texel.a); }`};function N8(s=5){const e=Math.floor(s)%2===0?Math.floor(s)+1:Math.floor(s),t=k8(e),i=t.length,n=new Uint8Array(i*4);for(let a=0;a #include #ifndef SAMPLE_LUMINANCE #define SAMPLE_LUMINANCE dot(vec3(0.2125, 0.7154, 0.0721), a) #endif #ifndef FRAGMENT_OUTPUT #define FRAGMENT_OUTPUT vec4(denoised, 1.) #endif float getLuminance(const in vec3 a) { return SAMPLE_LUMINANCE; } const vec3 poissonDisk[SAMPLES] = SAMPLE_VECTORS; vec3 getViewPosition( const in vec2 screenPosition, const in float depth ) { #ifdef USE_REVERSED_DEPTH_BUFFER vec4 clipSpacePosition = vec4( vec2( screenPosition ) * 2.0 - 1.0, depth, 1.0 ); #else vec4 clipSpacePosition = vec4( vec3( screenPosition, depth ) * 2.0 - 1.0, 1.0 ); #endif vec4 viewSpacePosition = cameraProjectionMatrixInverse * clipSpacePosition; return viewSpacePosition.xyz / viewSpacePosition.w; } float getDepth(const vec2 uv) { #if DEPTH_VALUE_SOURCE == 1 return textureLod(tDepth, uv.xy, 0.0).a; #else return textureLod(tDepth, uv.xy, 0.0).r; #endif } float fetchDepth(const ivec2 uv) { #if DEPTH_VALUE_SOURCE == 1 return texelFetch(tDepth, uv.xy, 0).a; #else return texelFetch(tDepth, uv.xy, 0).r; #endif } vec3 computeNormalFromDepth(const vec2 uv) { vec2 size = vec2(textureSize(tDepth, 0)); ivec2 p = ivec2(uv * size); float c0 = fetchDepth(p); float l2 = fetchDepth(p - ivec2(2, 0)); float l1 = fetchDepth(p - ivec2(1, 0)); float r1 = fetchDepth(p + ivec2(1, 0)); float r2 = fetchDepth(p + ivec2(2, 0)); float b2 = fetchDepth(p - ivec2(0, 2)); float b1 = fetchDepth(p - ivec2(0, 1)); float t1 = fetchDepth(p + ivec2(0, 1)); float t2 = fetchDepth(p + ivec2(0, 2)); float dl = abs((2.0 * l1 - l2) - c0); float dr = abs((2.0 * r1 - r2) - c0); float db = abs((2.0 * b1 - b2) - c0); float dt = abs((2.0 * t1 - t2) - c0); vec3 ce = getViewPosition(uv, c0).xyz; vec3 dpdx = (dl < dr) ? ce - getViewPosition((uv - vec2(1.0 / size.x, 0.0)), l1).xyz : -ce + getViewPosition((uv + vec2(1.0 / size.x, 0.0)), r1).xyz; vec3 dpdy = (db < dt) ? ce - getViewPosition((uv - vec2(0.0, 1.0 / size.y)), b1).xyz : -ce + getViewPosition((uv + vec2(0.0, 1.0 / size.y)), t1).xyz; return normalize(cross(dpdx, dpdy)); } vec3 getViewNormal(const vec2 uv) { #if NORMAL_VECTOR_TYPE == 2 return normalize(textureLod(tNormal, uv, 0.).rgb); #elif NORMAL_VECTOR_TYPE == 1 return unpackRGBToNormal(textureLod(tNormal, uv, 0.).rgb); #else return computeNormalFromDepth(uv); #endif } void denoiseSample(in vec3 center, in vec3 viewNormal, in vec3 viewPos, in vec2 sampleUv, inout vec3 denoised, inout float totalWeight) { vec4 sampleTexel = textureLod(tDiffuse, sampleUv, 0.0); float sampleDepth = getDepth(sampleUv); vec3 sampleNormal = getViewNormal(sampleUv); vec3 neighborColor = sampleTexel.rgb; vec3 viewPosSample = getViewPosition(sampleUv, sampleDepth); float normalDiff = dot(viewNormal, sampleNormal); float normalSimilarity = pow(max(normalDiff, 0.), normalPhi); float lumaDiff = abs(getLuminance(neighborColor) - getLuminance(center)); float lumaSimilarity = max(1.0 - lumaDiff / lumaPhi, 0.0); float depthDiff = abs(dot(viewPos - viewPosSample, viewNormal)); float depthSimilarity = max(1. - depthDiff / depthPhi, 0.); float w = lumaSimilarity * depthSimilarity * normalSimilarity; denoised += w * neighborColor; totalWeight += w; } void main() { float depth = getDepth(vUv.xy); vec3 viewNormal = getViewNormal(vUv); if (depth == 1. || dot(viewNormal, viewNormal) == 0.) { discard; return; } vec4 texel = textureLod(tDiffuse, vUv, 0.0); vec3 center = texel.rgb; vec3 viewPos = getViewPosition(vUv, depth); vec2 noiseResolution = vec2(textureSize(tNoise, 0)); vec2 noiseUv = vUv * resolution / noiseResolution; vec4 noiseTexel = textureLod(tNoise, noiseUv, 0.0); vec2 noiseVec = vec2(sin(noiseTexel[index % 4] * 2. * PI), cos(noiseTexel[index % 4] * 2. * PI)); mat2 rotationMatrix = mat2(noiseVec.x, -noiseVec.y, noiseVec.x, noiseVec.y); float totalWeight = 1.0; vec3 denoised = texel.rgb; for (int i = 0; i < SAMPLES; i++) { vec3 sampleDir = poissonDisk[i]; vec2 offset = rotationMatrix * (sampleDir.xy * (1. + sampleDir.z * (radius - 1.)) / resolution); vec2 sampleUv = vUv + offset; denoiseSample(center, viewNormal, viewPos, sampleUv, denoised, totalWeight); } if (totalWeight > 0.) { denoised /= totalWeight; } gl_FragColor = FRAGMENT_OUTPUT; }`};function nS(s,e,t){const i=O8(s,e,t);let n="vec3[SAMPLES](";for(let r=0;rg?(m=1,f=0):(m=0,f=1);const y=v-m+h,x=g-f+h,_=v-1+2*h,S=g-1+2*h,b=l&255,E=c&255,w=this.perm[b+this.perm[E]]%12,M=this.perm[b+m+this.perm[E+f]]%12,C=this.perm[b+1+this.perm[E+1]]%12;let I=.5-v*v-g*g;I<0?i=0:(I*=I,i=I*I*this._dot(this.grad3[w],v,g));let P=.5-y*y-x*x;P<0?n=0:(P*=P,n=P*P*this._dot(this.grad3[M],y,x));let k=.5-_*_-S*S;return k<0?r=0:(k*=k,r=k*k*this._dot(this.grad3[C],_,S)),70*(i+n+r)}noise3d(e,t,i){let n,r,a,o;const l=(e+t+i)*.3333333333333333,c=Math.floor(e+l),h=Math.floor(t+l),d=Math.floor(i+l),p=1/6,u=(c+h+d)*p,v=c-u,g=h-u,m=d-u,f=e-v,y=t-g,x=i-m;let _,S,b,E,w,M;f>=y?y>=x?(_=1,S=0,b=0,E=1,w=1,M=0):f>=x?(_=1,S=0,b=0,E=1,w=0,M=1):(_=0,S=0,b=1,E=1,w=0,M=1):yC?32:0,A=M>I?16:0,B=C>I?8:0,F=M>P?4:0,H=C>P?2:0,q=I>P?1:0,G=k+A+B+F+H+q,re=a[G][0]>=3?1:0,Y=a[G][1]>=3?1:0,$=a[G][2]>=3?1:0,_e=a[G][3]>=3?1:0,Te=a[G][0]>=2?1:0,be=a[G][1]>=2?1:0,J=a[G][2]>=2?1:0,oe=a[G][3]>=2?1:0,ue=a[G][0]>=1?1:0,Re=a[G][1]>=1?1:0,Ie=a[G][2]>=1?1:0,Ue=a[G][3]>=1?1:0,tt=M-re+c,je=C-Y+c,D=I-$+c,ae=P-_e+c,Q=M-Te+2*c,W=C-be+2*c,N=I-J+2*c,te=P-oe+2*c,de=M-ue+3*c,V=C-Re+3*c,ee=I-Ie+3*c,L=P-Ue+3*c,T=M-1+4*c,U=C-1+4*c,j=I-1+4*c,K=P-1+4*c,Z=m&255,Pe=f&255,ve=y&255,ke=x&255,Fe=o[Z+o[Pe+o[ve+o[ke]]]]%32,le=o[Z+re+o[Pe+Y+o[ve+$+o[ke+_e]]]]%32,ye=o[Z+Te+o[Pe+be+o[ve+J+o[ke+oe]]]]%32,ze=o[Z+ue+o[Pe+Re+o[ve+Ie+o[ke+Ue]]]]%32,Oe=o[Z+1+o[Pe+1+o[ve+1+o[ke+1]]]]%32;let Se=.6-M*M-C*C-I*I-P*P;Se<0?h=0:(Se*=Se,h=Se*Se*this._dot4(r[Fe],M,C,I,P));let Xe=.6-tt*tt-je*je-D*D-ae*ae;Xe<0?d=0:(Xe*=Xe,d=Xe*Xe*this._dot4(r[le],tt,je,D,ae));let z=.6-Q*Q-W*W-N*N-te*te;z<0?p=0:(z*=z,p=z*z*this._dot4(r[ye],Q,W,N,te));let xe=.6-de*de-V*V-ee*ee-L*L;xe<0?u=0:(xe*=xe,u=xe*xe*this._dot4(r[ze],de,V,ee,L));let ge=.6-T*T-U*U-j*j-K*K;return ge<0?v=0:(ge*=ge,v=ge*ge*this._dot4(r[Oe],T,U,j,K)),27*(h+d+p+u+v)}_dot(e,t,i){return e[0]*t+e[1]*i}_dot3(e,t,i,n){return e[0]*t+e[1]*i+e[2]*n}_dot4(e,t,i,n,r){return e[0]*t+e[1]*i+e[2]*n+e[3]*r}}class Es extends xo{constructor(e,t,i=512,n=512,r,a,o){super(),this.width=i,this.height=n,this.clear=!0,this.camera=t,this.scene=e,this.output=0,this._renderGBuffer=!0,this._visibilityCache=[],this.blendIntensity=1,this.pdRings=2,this.pdRadiusExponent=2,this.pdSamples=16,this.gtaoNoiseTexture=N8(),this.pdNoiseTexture=this._generateNoise(),this.gtaoRenderTarget=new bi(this.width,this.height,{type:_i}),this.pdRenderTarget=this.gtaoRenderTarget.clone(),this.gtaoMaterial=new Jt({defines:Object.assign({},wf.defines),uniforms:nn.clone(wf.uniforms),vertexShader:wf.vertexShader,fragmentShader:wf.fragmentShader,blending:Qt,depthTest:!1,depthWrite:!1}),this.gtaoMaterial.defines.PERSPECTIVE_CAMERA=this.camera.isPerspectiveCamera?1:0,this.gtaoMaterial.uniforms.tNoise.value=this.gtaoNoiseTexture,this.gtaoMaterial.uniforms.resolution.value.set(this.width,this.height),this.gtaoMaterial.uniforms.cameraNear.value=this.camera.near,this.gtaoMaterial.uniforms.cameraFar.value=this.camera.far,this.normalMaterial=new bp,this.normalMaterial.blending=Qt,this.pdMaterial=new Jt({defines:Object.assign({},Tf.defines),uniforms:nn.clone(Tf.uniforms),vertexShader:Tf.vertexShader,fragmentShader:Tf.fragmentShader,depthTest:!1,depthWrite:!1}),this.pdMaterial.uniforms.tDiffuse.value=this.gtaoRenderTarget.texture,this.pdMaterial.uniforms.tNoise.value=this.pdNoiseTexture,this.pdMaterial.uniforms.resolution.value.set(this.width,this.height),this.pdMaterial.uniforms.lumaPhi.value=10,this.pdMaterial.uniforms.depthPhi.value=2,this.pdMaterial.uniforms.normalPhi.value=3,this.pdMaterial.uniforms.radius.value=8,this.depthRenderMaterial=new Jt({defines:Object.assign({},Ef.defines),uniforms:nn.clone(Ef.uniforms),vertexShader:Ef.vertexShader,fragmentShader:Ef.fragmentShader,blending:Qt}),this.depthRenderMaterial.uniforms.cameraNear.value=this.camera.near,this.depthRenderMaterial.uniforms.cameraFar.value=this.camera.far,this.copyMaterial=new Jt({uniforms:nn.clone(yo.uniforms),vertexShader:yo.vertexShader,fragmentShader:yo.fragmentShader,transparent:!0,depthTest:!1,depthWrite:!1,blendSrc:xc,blendDst:Ir,blendEquation:bn,blendSrcAlpha:yc,blendDstAlpha:Ir,blendEquationAlpha:bn}),this.blendMaterial=new Jt({uniforms:nn.clone($v.uniforms),vertexShader:$v.vertexShader,fragmentShader:$v.fragmentShader,transparent:!0,depthTest:!1,depthWrite:!1,blending:ld,blendSrc:xc,blendDst:Ir,blendEquation:bn,blendSrcAlpha:yc,blendDstAlpha:Ir,blendEquationAlpha:bn}),this._fsQuad=new Mf(null),this._originalClearColor=new We,this.setGBuffer(r?r.depthTexture:void 0,r?r.normalTexture:void 0),a!==void 0&&this.updateGtaoMaterial(a),o!==void 0&&this.updatePdMaterial(o)}setSize(e,t){this.width=e,this.height=t,this.gtaoRenderTarget.setSize(e,t),this.normalRenderTarget.setSize(e,t),this.pdRenderTarget.setSize(e,t),this.gtaoMaterial.uniforms.resolution.value.set(e,t),this.gtaoMaterial.uniforms.cameraProjectionMatrix.value.copy(this.camera.projectionMatrix),this.gtaoMaterial.uniforms.cameraProjectionMatrixInverse.value.copy(this.camera.projectionMatrixInverse),this.pdMaterial.uniforms.resolution.value.set(e,t),this.pdMaterial.uniforms.cameraProjectionMatrixInverse.value.copy(this.camera.projectionMatrixInverse)}dispose(){this.gtaoNoiseTexture.dispose(),this.pdNoiseTexture.dispose(),this.normalRenderTarget.dispose(),this.gtaoRenderTarget.dispose(),this.pdRenderTarget.dispose(),this.normalMaterial.dispose(),this.pdMaterial.dispose(),this.copyMaterial.dispose(),this.depthRenderMaterial.dispose(),this._fsQuad.dispose()}get gtaoMap(){return this.pdRenderTarget.texture}setGBuffer(e,t){e!==void 0?(this.depthTexture=e,this.normalTexture=t,this._renderGBuffer=!1):(this.depthTexture=new Wr,this.depthTexture.format=Ns,this.depthTexture.type=Dr,this.normalRenderTarget=new bi(this.width,this.height,{minFilter:Zt,magFilter:Zt,type:_i,depthTexture:this.depthTexture}),this.normalTexture=this.normalRenderTarget.texture,this._renderGBuffer=!0);const i=this.normalTexture?1:0,n=this.depthTexture===this.normalTexture?"w":"x";this.gtaoMaterial.defines.NORMAL_VECTOR_TYPE=i,this.gtaoMaterial.defines.DEPTH_SWIZZLING=n,this.gtaoMaterial.uniforms.tNormal.value=this.normalTexture,this.gtaoMaterial.uniforms.tDepth.value=this.depthTexture,this.pdMaterial.defines.NORMAL_VECTOR_TYPE=i,this.pdMaterial.defines.DEPTH_SWIZZLING=n,this.pdMaterial.uniforms.tNormal.value=this.normalTexture,this.pdMaterial.uniforms.tDepth.value=this.depthTexture,this.depthRenderMaterial.uniforms.tDepth.value=this.normalRenderTarget.depthTexture}setSceneClipBox(e){e?(this.gtaoMaterial.needsUpdate=this.gtaoMaterial.defines.SCENE_CLIP_BOX!==1,this.gtaoMaterial.defines.SCENE_CLIP_BOX=1,this.gtaoMaterial.uniforms.sceneBoxMin.value.copy(e.min),this.gtaoMaterial.uniforms.sceneBoxMax.value.copy(e.max)):(this.gtaoMaterial.needsUpdate=this.gtaoMaterial.defines.SCENE_CLIP_BOX===0,this.gtaoMaterial.defines.SCENE_CLIP_BOX=0)}updateGtaoMaterial(e){e.radius!==void 0&&(this.gtaoMaterial.uniforms.radius.value=e.radius),e.distanceExponent!==void 0&&(this.gtaoMaterial.uniforms.distanceExponent.value=e.distanceExponent),e.thickness!==void 0&&(this.gtaoMaterial.uniforms.thickness.value=e.thickness),e.distanceFallOff!==void 0&&(this.gtaoMaterial.uniforms.distanceFallOff.value=e.distanceFallOff,this.gtaoMaterial.needsUpdate=!0),e.scale!==void 0&&(this.gtaoMaterial.uniforms.scale.value=e.scale),e.samples!==void 0&&e.samples!==this.gtaoMaterial.defines.SAMPLES&&(this.gtaoMaterial.defines.SAMPLES=e.samples,this.gtaoMaterial.needsUpdate=!0),e.screenSpaceRadius!==void 0&&(e.screenSpaceRadius?1:0)!==this.gtaoMaterial.defines.SCREEN_SPACE_RADIUS&&(this.gtaoMaterial.defines.SCREEN_SPACE_RADIUS=e.screenSpaceRadius?1:0,this.gtaoMaterial.needsUpdate=!0)}updatePdMaterial(e){let t=!1;e.lumaPhi!==void 0&&(this.pdMaterial.uniforms.lumaPhi.value=e.lumaPhi),e.depthPhi!==void 0&&(this.pdMaterial.uniforms.depthPhi.value=e.depthPhi),e.normalPhi!==void 0&&(this.pdMaterial.uniforms.normalPhi.value=e.normalPhi),e.radius!==void 0&&e.radius!==this.radius&&(this.pdMaterial.uniforms.radius.value=e.radius),e.radiusExponent!==void 0&&e.radiusExponent!==this.pdRadiusExponent&&(this.pdRadiusExponent=e.radiusExponent,t=!0),e.rings!==void 0&&e.rings!==this.pdRings&&(this.pdRings=e.rings,t=!0),e.samples!==void 0&&e.samples!==this.pdSamples&&(this.pdSamples=e.samples,t=!0),t&&(this.pdMaterial.defines.SAMPLES=this.pdSamples,this.pdMaterial.defines.SAMPLE_VECTORS=nS(this.pdSamples,this.pdRings,this.pdRadiusExponent),this.pdMaterial.needsUpdate=!0)}render(e,t,i){switch(this._renderGBuffer&&(this._overrideVisibility(),this._renderOverride(e,this.normalMaterial,this.normalRenderTarget,7829503,1),this._restoreVisibility()),this.gtaoMaterial.uniforms.cameraNear.value=this.camera.near,this.gtaoMaterial.uniforms.cameraFar.value=this.camera.far,this.gtaoMaterial.uniforms.cameraProjectionMatrix.value.copy(this.camera.projectionMatrix),this.gtaoMaterial.uniforms.cameraProjectionMatrixInverse.value.copy(this.camera.projectionMatrixInverse),this.gtaoMaterial.uniforms.cameraWorldMatrix.value.copy(this.camera.matrixWorld),this._renderPass(e,this.gtaoMaterial,this.gtaoRenderTarget,16777215,1),this.pdMaterial.uniforms.cameraProjectionMatrixInverse.value.copy(this.camera.projectionMatrixInverse),this._renderPass(e,this.pdMaterial,this.pdRenderTarget,16777215,1),this.output){case Es.OUTPUT.Off:break;case Es.OUTPUT.Diffuse:this.copyMaterial.uniforms.tDiffuse.value=i.texture,this.copyMaterial.blending=Qt,this._renderPass(e,this.copyMaterial,this.renderToScreen?null:t);break;case Es.OUTPUT.AO:this.copyMaterial.uniforms.tDiffuse.value=this.gtaoRenderTarget.texture,this.copyMaterial.blending=Qt,this._renderPass(e,this.copyMaterial,this.renderToScreen?null:t);break;case Es.OUTPUT.Denoise:this.copyMaterial.uniforms.tDiffuse.value=this.pdRenderTarget.texture,this.copyMaterial.blending=Qt,this._renderPass(e,this.copyMaterial,this.renderToScreen?null:t);break;case Es.OUTPUT.Depth:this.depthRenderMaterial.uniforms.cameraNear.value=this.camera.near,this.depthRenderMaterial.uniforms.cameraFar.value=this.camera.far,this._renderPass(e,this.depthRenderMaterial,this.renderToScreen?null:t);break;case Es.OUTPUT.Normal:this.copyMaterial.uniforms.tDiffuse.value=this.normalRenderTarget.texture,this.copyMaterial.blending=Qt,this._renderPass(e,this.copyMaterial,this.renderToScreen?null:t);break;case Es.OUTPUT.Default:this.copyMaterial.uniforms.tDiffuse.value=i.texture,this.copyMaterial.blending=Qt,this._renderPass(e,this.copyMaterial,this.renderToScreen?null:t),this.blendMaterial.uniforms.intensity.value=this.blendIntensity,this.blendMaterial.uniforms.tDiffuse.value=this.pdRenderTarget.texture,this._renderPass(e,this.blendMaterial,this.renderToScreen?null:t);break;default:console.warn("THREE.GTAOPass: Unknown output type.")}}_renderPass(e,t,i,n,r){e.getClearColor(this._originalClearColor);const a=e.getClearAlpha(),o=e.autoClear;e.setRenderTarget(i),e.autoClear=!1,n!=null&&(e.setClearColor(n),e.setClearAlpha(r||0),e.clear()),this._fsQuad.material=t,this._fsQuad.render(e),e.autoClear=o,e.setClearColor(this._originalClearColor),e.setClearAlpha(a)}_renderOverride(e,t,i,n,r){e.getClearColor(this._originalClearColor);const a=e.getClearAlpha(),o=e.autoClear;e.setRenderTarget(i),e.autoClear=!1,n=t.clearColor||n,r=t.clearAlpha||r,n!=null&&(e.setClearColor(n),e.setClearAlpha(r||0),e.clear()),this.scene.overrideMaterial=t,e.render(this.scene,this.camera),this.scene.overrideMaterial=null,e.autoClear=o,e.setClearColor(this._originalClearColor),e.setClearAlpha(a)}_overrideVisibility(){const e=this.scene,t=this._visibilityCache;e.traverse(function(i){(i.isPoints||i.isLine||i.isLine2)&&i.visible&&(i.visible=!1,t.push(i))})}_restoreVisibility(){const e=this._visibilityCache;for(let t=0;t #ifdef USE_REVERSED_DEPTH_BUFFER const float depthThreshold = 0.0; #else const float depthThreshold = 1.0; #endif float getDepth( const in vec2 screenPosition ) { return texture2D( tDepth, screenPosition ).x; } float getLinearDepth( const in vec2 screenPosition ) { #if PERSPECTIVE_CAMERA == 1 float fragCoordZ = texture2D( tDepth, screenPosition ).x; float viewZ = perspectiveDepthToViewZ( fragCoordZ, cameraNear, cameraFar ); return viewZToOrthographicDepth( viewZ, cameraNear, cameraFar ); #else return texture2D( tDepth, screenPosition ).x; #endif } float getViewZ( const in float depth ) { #if PERSPECTIVE_CAMERA == 1 return perspectiveDepthToViewZ( depth, cameraNear, cameraFar ); #else return orthographicDepthToViewZ( depth, cameraNear, cameraFar ); #endif } vec3 getViewPosition( const in vec2 screenPosition, const in float depth, const in float viewZ ) { float clipW = cameraProjectionMatrix[2][3] * viewZ + cameraProjectionMatrix[3][3]; vec4 clipPosition = vec4( ( vec3( screenPosition, depth ) - 0.5 ) * 2.0, 1.0 ); clipPosition *= clipW; // unprojection. return ( cameraInverseProjectionMatrix * clipPosition ).xyz; } vec3 getViewNormal( const in vec2 screenPosition ) { return unpackRGBToNormal( texture2D( tNormal, screenPosition ).xyz ); } void main() { float depth = getDepth( vUv ); if ( depth == depthThreshold ) { gl_FragColor = vec4( 1.0 ); // don't influence background } else { float viewZ = getViewZ( depth ); vec3 viewPosition = getViewPosition( vUv, depth, viewZ ); vec3 viewNormal = getViewNormal( vUv ); vec2 noiseScale = vec2( resolution.x / 4.0, resolution.y / 4.0 ); vec3 random = vec3( texture2D( tNoise, vUv * noiseScale ).r ); // compute matrix used to reorient a kernel vector vec3 tangent = normalize( random - viewNormal * dot( random, viewNormal ) ); vec3 bitangent = cross( viewNormal, tangent ); mat3 kernelMatrix = mat3( tangent, bitangent, viewNormal ); float occlusion = 0.0; for ( int i = 0; i < KERNEL_SIZE; i ++ ) { vec3 sampleVector = kernelMatrix * kernel[ i ]; // reorient sample vector in view space vec3 samplePoint = viewPosition + ( sampleVector * kernelRadius ); // calculate sample point vec4 samplePointNDC = cameraProjectionMatrix * vec4( samplePoint, 1.0 ); // project point and calculate NDC samplePointNDC /= samplePointNDC.w; vec2 samplePointUv = samplePointNDC.xy * 0.5 + 0.5; // compute uv coordinates float realDepth = getLinearDepth( samplePointUv ); // get linear depth from depth texture float sampleDepth = viewZToOrthographicDepth( samplePoint.z, cameraNear, cameraFar ); // compute linear depth of the sample view Z value float delta = sampleDepth - realDepth; if ( delta > minDistance && delta < maxDistance ) { // if fragment is before sample point, increase occlusion occlusion += 1.0; } } occlusion = clamp( occlusion / float( KERNEL_SIZE ), 0.0, 1.0 ); gl_FragColor = vec4( vec3( 1.0 - occlusion ), 1.0 ); } }`},Af={defines:{PERSPECTIVE_CAMERA:1},uniforms:{tDepth:{value:null},cameraNear:{value:null},cameraFar:{value:null}},vertexShader:`varying vec2 vUv; void main() { vUv = uv; gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); }`,fragmentShader:`uniform sampler2D tDepth; uniform float cameraNear; uniform float cameraFar; varying vec2 vUv; #include float getLinearDepth( const in vec2 screenPosition ) { #if PERSPECTIVE_CAMERA == 1 float fragCoordZ = texture2D( tDepth, screenPosition ).x; float viewZ = perspectiveDepthToViewZ( fragCoordZ, cameraNear, cameraFar ); return viewZToOrthographicDepth( viewZ, cameraNear, cameraFar ); #else return texture2D( tDepth, screenPosition ).x; #endif } void main() { float depth = getLinearDepth( vUv ); gl_FragColor = vec4( vec3( 1.0 - depth ), 1.0 ); }`},Pf={uniforms:{tDiffuse:{value:null},resolution:{value:new me}},vertexShader:`varying vec2 vUv; void main() { vUv = uv; gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); }`,fragmentShader:`uniform sampler2D tDiffuse; uniform vec2 resolution; varying vec2 vUv; void main() { vec2 texelSize = ( 1.0 / resolution ); float result = 0.0; for ( int i = - 2; i <= 2; i ++ ) { for ( int j = - 2; j <= 2; j ++ ) { vec2 offset = ( vec2( float( i ), float( j ) ) ) * texelSize; result += texture2D( tDiffuse, vUv + offset ).r; } } gl_FragColor = vec4( vec3( result / ( 5.0 * 5.0 ) ), 1.0 ); }`};class _r extends xo{constructor(e,t,i=512,n=512,r=32){super(),this.width=i,this.height=n,this.clear=!0,this.needsSwap=!1,this.camera=t,this.scene=e,this.kernelRadius=8,this.kernel=[],this.noiseTexture=null,this.output=0,this.minDistance=.005,this.maxDistance=.1,this._visibilityCache=[],this._generateSampleKernel(r),this._generateRandomKernelRotations();const a=new Wr;a.format=Ns,a.type=Dr,this.normalRenderTarget=new bi(this.width,this.height,{minFilter:Zt,magFilter:Zt,type:_i,depthTexture:a}),this.ssaoRenderTarget=new bi(this.width,this.height,{type:_i}),this.blurRenderTarget=this.ssaoRenderTarget.clone(),this.ssaoMaterial=new Jt({defines:Object.assign({},Cf.defines),uniforms:nn.clone(Cf.uniforms),vertexShader:Cf.vertexShader,fragmentShader:Cf.fragmentShader,blending:Qt}),this.ssaoMaterial.defines.KERNEL_SIZE=r,this.ssaoMaterial.uniforms.tNormal.value=this.normalRenderTarget.texture,this.ssaoMaterial.uniforms.tDepth.value=this.normalRenderTarget.depthTexture,this.ssaoMaterial.uniforms.tNoise.value=this.noiseTexture,this.ssaoMaterial.uniforms.kernel.value=this.kernel,this.ssaoMaterial.uniforms.cameraNear.value=this.camera.near,this.ssaoMaterial.uniforms.cameraFar.value=this.camera.far,this.ssaoMaterial.uniforms.resolution.value.set(this.width,this.height),this.ssaoMaterial.uniforms.cameraProjectionMatrix.value.copy(this.camera.projectionMatrix),this.ssaoMaterial.uniforms.cameraInverseProjectionMatrix.value.copy(this.camera.projectionMatrixInverse),this.normalMaterial=new bp,this.normalMaterial.blending=Qt,this.blurMaterial=new Jt({defines:Object.assign({},Pf.defines),uniforms:nn.clone(Pf.uniforms),vertexShader:Pf.vertexShader,fragmentShader:Pf.fragmentShader}),this.blurMaterial.uniforms.tDiffuse.value=this.ssaoRenderTarget.texture,this.blurMaterial.uniforms.resolution.value.set(this.width,this.height),this.depthRenderMaterial=new Jt({defines:Object.assign({},Af.defines),uniforms:nn.clone(Af.uniforms),vertexShader:Af.vertexShader,fragmentShader:Af.fragmentShader,blending:Qt}),this.depthRenderMaterial.uniforms.tDepth.value=this.normalRenderTarget.depthTexture,this.depthRenderMaterial.uniforms.cameraNear.value=this.camera.near,this.depthRenderMaterial.uniforms.cameraFar.value=this.camera.far,this.copyMaterial=new Jt({uniforms:nn.clone(yo.uniforms),vertexShader:yo.vertexShader,fragmentShader:yo.fragmentShader,transparent:!0,depthTest:!1,depthWrite:!1,blendSrc:xc,blendDst:Ir,blendEquation:bn,blendSrcAlpha:yc,blendDstAlpha:Ir,blendEquationAlpha:bn}),this._fsQuad=new Mf(null),this._originalClearColor=new We}dispose(){this.normalRenderTarget.dispose(),this.ssaoRenderTarget.dispose(),this.blurRenderTarget.dispose(),this.normalMaterial.dispose(),this.blurMaterial.dispose(),this.copyMaterial.dispose(),this.depthRenderMaterial.dispose(),this._fsQuad.dispose()}render(e,t,i){switch(this._overrideVisibility(),this._renderOverride(e,this.normalMaterial,this.normalRenderTarget,7829503,1),this._restoreVisibility(),this.ssaoMaterial.uniforms.kernelRadius.value=this.kernelRadius,this.ssaoMaterial.uniforms.minDistance.value=this.minDistance,this.ssaoMaterial.uniforms.maxDistance.value=this.maxDistance,this._renderPass(e,this.ssaoMaterial,this.ssaoRenderTarget),this._renderPass(e,this.blurMaterial,this.blurRenderTarget),this.output){case _r.OUTPUT.SSAO:this.copyMaterial.uniforms.tDiffuse.value=this.ssaoRenderTarget.texture,this.copyMaterial.blending=Qt,this._renderPass(e,this.copyMaterial,this.renderToScreen?null:i);break;case _r.OUTPUT.Blur:this.copyMaterial.uniforms.tDiffuse.value=this.blurRenderTarget.texture,this.copyMaterial.blending=Qt,this._renderPass(e,this.copyMaterial,this.renderToScreen?null:i);break;case _r.OUTPUT.Depth:this._renderPass(e,this.depthRenderMaterial,this.renderToScreen?null:i);break;case _r.OUTPUT.Normal:this.copyMaterial.uniforms.tDiffuse.value=this.normalRenderTarget.texture,this.copyMaterial.blending=Qt,this._renderPass(e,this.copyMaterial,this.renderToScreen?null:i);break;case _r.OUTPUT.Default:this.copyMaterial.uniforms.tDiffuse.value=this.blurRenderTarget.texture,this.copyMaterial.blending=ld,this._renderPass(e,this.copyMaterial,this.renderToScreen?null:i);break;default:console.warn("THREE.SSAOPass: Unknown output type.")}}setSize(e,t){this.width=e,this.height=t,this.ssaoRenderTarget.setSize(e,t),this.normalRenderTarget.setSize(e,t),this.blurRenderTarget.setSize(e,t),this.ssaoMaterial.uniforms.resolution.value.set(e,t),this.ssaoMaterial.uniforms.cameraProjectionMatrix.value.copy(this.camera.projectionMatrix),this.ssaoMaterial.uniforms.cameraInverseProjectionMatrix.value.copy(this.camera.projectionMatrixInverse),this.blurMaterial.uniforms.resolution.value.set(e,t)}_renderPass(e,t,i,n,r){e.getClearColor(this._originalClearColor);const a=e.getClearAlpha(),o=e.autoClear;e.setRenderTarget(i),e.autoClear=!1,n!=null&&(e.setClearColor(n),e.setClearAlpha(r||0),e.clear()),this._fsQuad.material=t,this._fsQuad.render(e),e.autoClear=o,e.setClearColor(this._originalClearColor),e.setClearAlpha(a)}_renderOverride(e,t,i,n,r){e.getClearColor(this._originalClearColor);const a=e.getClearAlpha(),o=e.autoClear;e.setRenderTarget(i),e.autoClear=!1,n=t.clearColor||n,r=t.clearAlpha||r,n!=null&&(e.setClearColor(n),e.setClearAlpha(r||0),e.clear()),this.scene.overrideMaterial=t,e.render(this.scene,this.camera),this.scene.overrideMaterial=null,e.autoClear=o,e.setClearColor(this._originalClearColor),e.setClearAlpha(a)}_generateSampleKernel(e){const t=this.kernel;for(let i=0;i #include varying vec2 vUv; void main() { gl_FragColor = texture2D( tDiffuse, vUv ); // tone mapping #ifdef LINEAR_TONE_MAPPING gl_FragColor.rgb = LinearToneMapping( gl_FragColor.rgb ); #elif defined( REINHARD_TONE_MAPPING ) gl_FragColor.rgb = ReinhardToneMapping( gl_FragColor.rgb ); #elif defined( CINEON_TONE_MAPPING ) gl_FragColor.rgb = CineonToneMapping( gl_FragColor.rgb ); #elif defined( ACES_FILMIC_TONE_MAPPING ) gl_FragColor.rgb = ACESFilmicToneMapping( gl_FragColor.rgb ); #elif defined( AGX_TONE_MAPPING ) gl_FragColor.rgb = AgXToneMapping( gl_FragColor.rgb ); #elif defined( NEUTRAL_TONE_MAPPING ) gl_FragColor.rgb = NeutralToneMapping( gl_FragColor.rgb ); #elif defined( CUSTOM_TONE_MAPPING ) gl_FragColor.rgb = CustomToneMapping( gl_FragColor.rgb ); #endif // color space #ifdef SRGB_TRANSFER gl_FragColor = sRGBTransferOETF( gl_FragColor ); #endif }`};class U8 extends xo{constructor(){super(),this.isOutputPass=!0,this.uniforms=nn.clone(Rf.uniforms),this.material=new _p({name:Rf.name,uniforms:this.uniforms,vertexShader:Rf.vertexShader,fragmentShader:Rf.fragmentShader}),this._fsQuad=new Mf(this.material),this._outputColorSpace=null,this._toneMapping=null}render(e,t,i){this.uniforms.tDiffuse.value=i.texture,this.uniforms.toneMappingExposure.value=e.toneMappingExposure,(this._outputColorSpace!==e.outputColorSpace||this._toneMapping!==e.toneMapping)&&(this._outputColorSpace=e.outputColorSpace,this._toneMapping=e.toneMapping,this.material.defines={},Et.getTransfer(this._outputColorSpace)===Bt&&(this.material.defines.SRGB_TRANSFER=""),this._toneMapping===yd?this.material.defines.LINEAR_TONE_MAPPING="":this._toneMapping===xd?this.material.defines.REINHARD_TONE_MAPPING="":this._toneMapping===_d?this.material.defines.CINEON_TONE_MAPPING="":this._toneMapping===Sa?this.material.defines.ACES_FILMIC_TONE_MAPPING="":this._toneMapping===Md?this.material.defines.AGX_TONE_MAPPING="":this._toneMapping===Sd?this.material.defines.NEUTRAL_TONE_MAPPING="":this._toneMapping===bd&&(this.material.defines.CUSTOM_TONE_MAPPING=""),this.material.needsUpdate=!0),this.renderToScreen===!0?(e.setRenderTarget(null),this._fsQuad.render(e)):(e.setRenderTarget(t),this.clear&&e.clear(e.autoClearColor,e.autoClearDepth,e.autoClearStencil),this._fsQuad.render(e))}dispose(){this.material.dispose(),this._fsQuad.dispose()}}const B8={name:"FXAAShader",uniforms:{tDiffuse:{value:null},resolution:{value:new me(1/1024,1/512)}},vertexShader:` varying vec2 vUv; void main() { vUv = uv; gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); }`,fragmentShader:` uniform sampler2D tDiffuse; uniform vec2 resolution; varying vec2 vUv; #define EDGE_STEP_COUNT 6 #define EDGE_GUESS 8.0 #define EDGE_STEPS 1.0, 1.5, 2.0, 2.0, 2.0, 4.0 const float edgeSteps[EDGE_STEP_COUNT] = float[EDGE_STEP_COUNT]( EDGE_STEPS ); float _ContrastThreshold = 0.0312; float _RelativeThreshold = 0.063; float _SubpixelBlending = 1.0; vec4 Sample( sampler2D tex2D, vec2 uv ) { return texture( tex2D, uv ); } float SampleLuminance( sampler2D tex2D, vec2 uv ) { return dot( Sample( tex2D, uv ).rgb, vec3( 0.3, 0.59, 0.11 ) ); } float SampleLuminance( sampler2D tex2D, vec2 texSize, vec2 uv, float uOffset, float vOffset ) { uv += texSize * vec2(uOffset, vOffset); return SampleLuminance(tex2D, uv); } struct LuminanceData { float m, n, e, s, w; float ne, nw, se, sw; float highest, lowest, contrast; }; LuminanceData SampleLuminanceNeighborhood( sampler2D tex2D, vec2 texSize, vec2 uv ) { LuminanceData l; l.m = SampleLuminance( tex2D, uv ); l.n = SampleLuminance( tex2D, texSize, uv, 0.0, 1.0 ); l.e = SampleLuminance( tex2D, texSize, uv, 1.0, 0.0 ); l.s = SampleLuminance( tex2D, texSize, uv, 0.0, -1.0 ); l.w = SampleLuminance( tex2D, texSize, uv, -1.0, 0.0 ); l.ne = SampleLuminance( tex2D, texSize, uv, 1.0, 1.0 ); l.nw = SampleLuminance( tex2D, texSize, uv, -1.0, 1.0 ); l.se = SampleLuminance( tex2D, texSize, uv, 1.0, -1.0 ); l.sw = SampleLuminance( tex2D, texSize, uv, -1.0, -1.0 ); l.highest = max( max( max( max( l.n, l.e ), l.s ), l.w ), l.m ); l.lowest = min( min( min( min( l.n, l.e ), l.s ), l.w ), l.m ); l.contrast = l.highest - l.lowest; return l; } bool ShouldSkipPixel( LuminanceData l ) { float threshold = max( _ContrastThreshold, _RelativeThreshold * l.highest ); return l.contrast < threshold; } float DeterminePixelBlendFactor( LuminanceData l ) { float f = 2.0 * ( l.n + l.e + l.s + l.w ); f += l.ne + l.nw + l.se + l.sw; f *= 1.0 / 12.0; f = abs( f - l.m ); f = clamp( f / l.contrast, 0.0, 1.0 ); float blendFactor = smoothstep( 0.0, 1.0, f ); return blendFactor * blendFactor * _SubpixelBlending; } struct EdgeData { bool isHorizontal; float pixelStep; float oppositeLuminance, gradient; }; EdgeData DetermineEdge( vec2 texSize, LuminanceData l ) { EdgeData e; float horizontal = abs( l.n + l.s - 2.0 * l.m ) * 2.0 + abs( l.ne + l.se - 2.0 * l.e ) + abs( l.nw + l.sw - 2.0 * l.w ); float vertical = abs( l.e + l.w - 2.0 * l.m ) * 2.0 + abs( l.ne + l.nw - 2.0 * l.n ) + abs( l.se + l.sw - 2.0 * l.s ); e.isHorizontal = horizontal >= vertical; float pLuminance = e.isHorizontal ? l.n : l.e; float nLuminance = e.isHorizontal ? l.s : l.w; float pGradient = abs( pLuminance - l.m ); float nGradient = abs( nLuminance - l.m ); e.pixelStep = e.isHorizontal ? texSize.y : texSize.x; if (pGradient < nGradient) { e.pixelStep = -e.pixelStep; e.oppositeLuminance = nLuminance; e.gradient = nGradient; } else { e.oppositeLuminance = pLuminance; e.gradient = pGradient; } return e; } float DetermineEdgeBlendFactor( sampler2D tex2D, vec2 texSize, LuminanceData l, EdgeData e, vec2 uv ) { vec2 uvEdge = uv; vec2 edgeStep; if (e.isHorizontal) { uvEdge.y += e.pixelStep * 0.5; edgeStep = vec2( texSize.x, 0.0 ); } else { uvEdge.x += e.pixelStep * 0.5; edgeStep = vec2( 0.0, texSize.y ); } float edgeLuminance = ( l.m + e.oppositeLuminance ) * 0.5; float gradientThreshold = e.gradient * 0.25; vec2 puv = uvEdge + edgeStep * edgeSteps[0]; float pLuminanceDelta = SampleLuminance( tex2D, puv ) - edgeLuminance; bool pAtEnd = abs( pLuminanceDelta ) >= gradientThreshold; for ( int i = 1; i < EDGE_STEP_COUNT && !pAtEnd; i++ ) { puv += edgeStep * edgeSteps[i]; pLuminanceDelta = SampleLuminance( tex2D, puv ) - edgeLuminance; pAtEnd = abs( pLuminanceDelta ) >= gradientThreshold; } if ( !pAtEnd ) { puv += edgeStep * EDGE_GUESS; } vec2 nuv = uvEdge - edgeStep * edgeSteps[0]; float nLuminanceDelta = SampleLuminance( tex2D, nuv ) - edgeLuminance; bool nAtEnd = abs( nLuminanceDelta ) >= gradientThreshold; for ( int i = 1; i < EDGE_STEP_COUNT && !nAtEnd; i++ ) { nuv -= edgeStep * edgeSteps[i]; nLuminanceDelta = SampleLuminance( tex2D, nuv ) - edgeLuminance; nAtEnd = abs( nLuminanceDelta ) >= gradientThreshold; } if ( !nAtEnd ) { nuv -= edgeStep * EDGE_GUESS; } float pDistance, nDistance; if ( e.isHorizontal ) { pDistance = puv.x - uv.x; nDistance = uv.x - nuv.x; } else { pDistance = puv.y - uv.y; nDistance = uv.y - nuv.y; } float shortestDistance; bool deltaSign; if ( pDistance <= nDistance ) { shortestDistance = pDistance; deltaSign = pLuminanceDelta >= 0.0; } else { shortestDistance = nDistance; deltaSign = nLuminanceDelta >= 0.0; } if ( deltaSign == ( l.m - edgeLuminance >= 0.0 ) ) { return 0.0; } return 0.5 - shortestDistance / ( pDistance + nDistance ); } vec4 ApplyFXAA( sampler2D tex2D, vec2 texSize, vec2 uv ) { LuminanceData luminance = SampleLuminanceNeighborhood( tex2D, texSize, uv ); if ( ShouldSkipPixel( luminance ) ) { return Sample( tex2D, uv ); } float pixelBlend = DeterminePixelBlendFactor( luminance ); EdgeData edge = DetermineEdge( texSize, luminance ); float edgeBlend = DetermineEdgeBlendFactor( tex2D, texSize, luminance, edge, uv ); float finalBlend = max( pixelBlend, edgeBlend ); if (edge.isHorizontal) { uv.y += edge.pixelStep * finalBlend; } else { uv.x += edge.pixelStep * finalBlend; } return Sample( tex2D, uv ); } void main() { gl_FragColor = ApplyFXAA( tDiffuse, resolution.xy, vUv ); }`},F8={uniforms:{tDiffuse:{value:null},saturation:{value:1.2},contrast:{value:1.2}},vertexShader:` varying vec2 vUv; void main() { vUv = uv; gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0); } `,fragmentShader:` uniform sampler2D tDiffuse; uniform float saturation; uniform float contrast; varying vec2 vUv; void main() { vec4 color = texture2D(tDiffuse, vUv); // 转换为灰度值用于饱和度调整 float gray = dot(color.rgb, vec3(0.299, 0.587, 0.114)); // 混合原始颜色和灰度值来调整饱和度 color.rgb = mix(vec3(gray), color.rgb, saturation); // 调整对比度 color.rgb = (color.rgb - 0.5) * contrast + 0.5; gl_FragColor = color; } `};class z8{engine;composer;saturationPass;ssaoPass;gtaoPass;outputPass;fxaaPass;constructor(e){this.engine=e}applyClippingToAmbientOcclusionPass(e){const t=Array.isArray(this.engine.sectionPlane)?this.engine.sectionPlane:null,i=e?.normalMaterial;i&&(i.clippingPlanes=t,i.needsUpdate=!0)}syncAmbientOcclusionClipping(){this.applyClippingToAmbientOcclusionPass(this.gtaoPass),this.applyClippingToAmbientOcclusionPass(this.ssaoPass)}resize(e,t){if(e===void 0||t===void 0){const r=this.engine.deviceModule.getContainerSize();e=e??r.width,t=t??r.height}if(!e||!t||!this.composer)return;const i=this.engine.renderer?.getPixelRatio?.()??window.devicePixelRatio??1;this.composer.setPixelRatio(i),this.composer.setSize(e,t);const n=this.composer.passes.find(r=>r instanceof Sf&&r.material.uniforms.resolution);n&&(n.material.uniforms.resolution.value.x=1/(e*i),n.material.uniforms.resolution.value.y=1/(t*i))}init(){const{width:e,height:t}=this.engine.deviceModule.getContainerSize(),i=this.engine.scene,n=this.engine.camera,r=this.engine.renderer,a=this.engine.renderer?.getPixelRatio?.()??window.devicePixelRatio??1,o=new bi(e,t,{minFilter:At,magFilter:At,format:qi,samples:4});this.composer=new L8(r,o),this.composer.setPixelRatio(a),this.composer.setSize(e,t);const l=new D8(i,n);this.composer.addPass(l),this.gtaoPass=new Es(i,n,e,t),this.gtaoPass.output=Es.OUTPUT.Default,this.gtaoPass.blendIntensity=.3,this.gtaoPass.enabled=!1,this.gtaoPass.updateGtaoMaterial&&this.gtaoPass.updateGtaoMaterial({enabled:!0,radius:.5,thickness:2,distanceExponent:1,distanceFallOff:1,scale:6,samples:3,resolutionScale:.45,useTemporalFiltering:!1}),this.applyClippingToAmbientOcclusionPass(this.gtaoPass),this.composer.addPass(this.gtaoPass),this.ssaoPass=new _r(i,n,e,t),this.ssaoPass.kernelRadius=8,this.ssaoPass.minDistance=.005,this.ssaoPass.maxDistance=.1,this.ssaoPass.output=_r.OUTPUT.Default,this.ssaoPass.enabled=!1,this.applyClippingToAmbientOcclusionPass(this.ssaoPass),this.composer.addPass(this.ssaoPass),this.saturationPass=new Sf(F8),this.saturationPass.uniforms.saturation.value=1.3,this.saturationPass.uniforms.contrast.value=1.1,this.saturationPass.enabled=!1,this.composer.addPass(this.saturationPass),this.outputPass=new U8,this.outputPass.enabled=!1,this.composer.addPass(this.outputPass),this.fxaaPass=new Sf(B8),this.fxaaPass.material.uniforms.resolution.value.x=1/(e*a),this.fxaaPass.material.uniforms.resolution.value.y=1/(t*a),this.fxaaPass.enabled=!1,this.composer.addPass(this.fxaaPass)}}var If=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function rS(s){return s&&s.__esModule&&Object.prototype.hasOwnProperty.call(s,"default")?s.default:s}function Lf(s){throw new Error('Could not dynamically require "'+s+'". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.')}var aS={exports:{}},oS;function H8(){return oS||(oS=1,(function(s,e){(function(t){s.exports=t()})(function(){return(function t(i,n,r){function a(c,h){if(!n[c]){if(!i[c]){var d=typeof Lf=="function"&&Lf;if(!h&&d)return d(c,!0);if(o)return o(c,!0);var p=new Error("Cannot find module '"+c+"'");throw p.code="MODULE_NOT_FOUND",p}var u=n[c]={exports:{}};i[c][0].call(u.exports,function(v){var g=i[c][1][v];return a(g||v)},u,u.exports,t,i,n,r)}return n[c].exports}for(var o=typeof Lf=="function"&&Lf,l=0;l>2,u=(3&c)<<4|h>>4,v=1>6:64,g=2>4,h=(15&p)<<4|(u=o.indexOf(l.charAt(g++)))>>2,d=(3&u)<<6|(v=o.indexOf(l.charAt(g++))),y[m++]=c,u!==64&&(y[m++]=h),v!==64&&(y[m++]=d);return y}},{"./support":30,"./utils":32}],2:[function(t,i,n){var r=t("./external"),a=t("./stream/DataWorker"),o=t("./stream/Crc32Probe"),l=t("./stream/DataLengthProbe");function c(h,d,p,u,v){this.compressedSize=h,this.uncompressedSize=d,this.crc32=p,this.compression=u,this.compressedContent=v}c.prototype={getContentWorker:function(){var h=new a(r.Promise.resolve(this.compressedContent)).pipe(this.compression.uncompressWorker()).pipe(new l("data_length")),d=this;return h.on("end",function(){if(this.streamInfo.data_length!==d.uncompressedSize)throw new Error("Bug : uncompressed data size mismatch")}),h},getCompressedWorker:function(){return new a(r.Promise.resolve(this.compressedContent)).withStreamInfo("compressedSize",this.compressedSize).withStreamInfo("uncompressedSize",this.uncompressedSize).withStreamInfo("crc32",this.crc32).withStreamInfo("compression",this.compression)}},c.createWorkerFrom=function(h,d,p){return h.pipe(new o).pipe(new l("uncompressedSize")).pipe(d.compressWorker(p)).pipe(new l("compressedSize")).withStreamInfo("compression",d)},i.exports=c},{"./external":6,"./stream/Crc32Probe":25,"./stream/DataLengthProbe":26,"./stream/DataWorker":27}],3:[function(t,i,n){var r=t("./stream/GenericWorker");n.STORE={magic:"\0\0",compressWorker:function(){return new r("STORE compression")},uncompressWorker:function(){return new r("STORE decompression")}},n.DEFLATE=t("./flate")},{"./flate":7,"./stream/GenericWorker":28}],4:[function(t,i,n){var r=t("./utils"),a=(function(){for(var o,l=[],c=0;c<256;c++){o=c;for(var h=0;h<8;h++)o=1&o?3988292384^o>>>1:o>>>1;l[c]=o}return l})();i.exports=function(o,l){return o!==void 0&&o.length?r.getTypeOf(o)!=="string"?(function(c,h,d,p){var u=a,v=p+d;c^=-1;for(var g=p;g>>8^u[255&(c^h[g])];return-1^c})(0|l,o,o.length,0):(function(c,h,d,p){var u=a,v=p+d;c^=-1;for(var g=p;g>>8^u[255&(c^h.charCodeAt(g))];return-1^c})(0|l,o,o.length,0):0}},{"./utils":32}],5:[function(t,i,n){n.base64=!1,n.binary=!1,n.dir=!1,n.createFolders=!0,n.date=null,n.compression=null,n.compressionOptions=null,n.comment=null,n.unixPermissions=null,n.dosPermissions=null},{}],6:[function(t,i,n){var r=null;r=typeof Promise<"u"?Promise:t("lie"),i.exports={Promise:r}},{lie:37}],7:[function(t,i,n){var r=typeof Uint8Array<"u"&&typeof Uint16Array<"u"&&typeof Uint32Array<"u",a=t("pako"),o=t("./utils"),l=t("./stream/GenericWorker"),c=r?"uint8array":"array";function h(d,p){l.call(this,"FlateWorker/"+d),this._pako=null,this._pakoAction=d,this._pakoOptions=p,this.meta={}}n.magic="\b\0",o.inherits(h,l),h.prototype.processChunk=function(d){this.meta=d.meta,this._pako===null&&this._createPako(),this._pako.push(o.transformTo(c,d.data),!1)},h.prototype.flush=function(){l.prototype.flush.call(this),this._pako===null&&this._createPako(),this._pako.push([],!0)},h.prototype.cleanUp=function(){l.prototype.cleanUp.call(this),this._pako=null},h.prototype._createPako=function(){this._pako=new a[this._pakoAction]({raw:!0,level:this._pakoOptions.level||-1});var d=this;this._pako.onData=function(p){d.push({data:p,meta:d.meta})}},n.compressWorker=function(d){return new h("Deflate",d)},n.uncompressWorker=function(){return new h("Inflate",{})}},{"./stream/GenericWorker":28,"./utils":32,pako:38}],8:[function(t,i,n){function r(u,v){var g,m="";for(g=0;g>>=8;return m}function a(u,v,g,m,f,y){var x,_,S=u.file,b=u.compression,E=y!==c.utf8encode,w=o.transformTo("string",y(S.name)),M=o.transformTo("string",c.utf8encode(S.name)),C=S.comment,I=o.transformTo("string",y(C)),P=o.transformTo("string",c.utf8encode(C)),k=M.length!==S.name.length,A=P.length!==C.length,B="",F="",H="",q=S.dir,G=S.date,re={crc32:0,compressedSize:0,uncompressedSize:0};v&&!g||(re.crc32=u.crc32,re.compressedSize=u.compressedSize,re.uncompressedSize=u.uncompressedSize);var Y=0;v&&(Y|=8),E||!k&&!A||(Y|=2048);var $=0,_e=0;q&&($|=16),f==="UNIX"?(_e=798,$|=(function(be,J){var oe=be;return be||(oe=J?16893:33204),(65535&oe)<<16})(S.unixPermissions,q)):(_e=20,$|=(function(be){return 63&(be||0)})(S.dosPermissions)),x=G.getUTCHours(),x<<=6,x|=G.getUTCMinutes(),x<<=5,x|=G.getUTCSeconds()/2,_=G.getUTCFullYear()-1980,_<<=4,_|=G.getUTCMonth()+1,_<<=5,_|=G.getUTCDate(),k&&(F=r(1,1)+r(h(w),4)+M,B+="up"+r(F.length,2)+F),A&&(H=r(1,1)+r(h(I),4)+P,B+="uc"+r(H.length,2)+H);var Te="";return Te+=` \0`,Te+=r(Y,2),Te+=b.magic,Te+=r(x,2),Te+=r(_,2),Te+=r(re.crc32,4),Te+=r(re.compressedSize,4),Te+=r(re.uncompressedSize,4),Te+=r(w.length,2),Te+=r(B.length,2),{fileRecord:d.LOCAL_FILE_HEADER+Te+w+B,dirRecord:d.CENTRAL_FILE_HEADER+r(_e,2)+Te+r(I.length,2)+"\0\0\0\0"+r($,4)+r(m,4)+w+B+I}}var o=t("../utils"),l=t("../stream/GenericWorker"),c=t("../utf8"),h=t("../crc32"),d=t("../signature");function p(u,v,g,m){l.call(this,"ZipFileWorker"),this.bytesWritten=0,this.zipComment=v,this.zipPlatform=g,this.encodeFileName=m,this.streamFiles=u,this.accumulate=!1,this.contentBuffer=[],this.dirRecords=[],this.currentSourceOffset=0,this.entriesCount=0,this.currentFile=null,this._sources=[]}o.inherits(p,l),p.prototype.push=function(u){var v=u.meta.percent||0,g=this.entriesCount,m=this._sources.length;this.accumulate?this.contentBuffer.push(u):(this.bytesWritten+=u.data.length,l.prototype.push.call(this,{data:u.data,meta:{currentFile:this.currentFile,percent:g?(v+100*(g-m-1))/g:100}}))},p.prototype.openedSource=function(u){this.currentSourceOffset=this.bytesWritten,this.currentFile=u.file.name;var v=this.streamFiles&&!u.file.dir;if(v){var g=a(u,v,!1,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);this.push({data:g.fileRecord,meta:{percent:0}})}else this.accumulate=!0},p.prototype.closedSource=function(u){this.accumulate=!1;var v=this.streamFiles&&!u.file.dir,g=a(u,v,!0,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);if(this.dirRecords.push(g.dirRecord),v)this.push({data:(function(m){return d.DATA_DESCRIPTOR+r(m.crc32,4)+r(m.compressedSize,4)+r(m.uncompressedSize,4)})(u),meta:{percent:100}});else for(this.push({data:g.fileRecord,meta:{percent:0}});this.contentBuffer.length;)this.push(this.contentBuffer.shift());this.currentFile=null},p.prototype.flush=function(){for(var u=this.bytesWritten,v=0;v=this.index;l--)c=(c<<8)+this.byteAt(l);return this.index+=o,c},readString:function(o){return r.transformTo("string",this.readData(o))},readData:function(){},lastIndexOfSignature:function(){},readAndCheckSignature:function(){},readDate:function(){var o=this.readInt(4);return new Date(Date.UTC(1980+(o>>25&127),(o>>21&15)-1,o>>16&31,o>>11&31,o>>5&63,(31&o)<<1))}},i.exports=a},{"../utils":32}],19:[function(t,i,n){var r=t("./Uint8ArrayReader");function a(o){r.call(this,o)}t("../utils").inherits(a,r),a.prototype.readData=function(o){this.checkOffset(o);var l=this.data.slice(this.zero+this.index,this.zero+this.index+o);return this.index+=o,l},i.exports=a},{"../utils":32,"./Uint8ArrayReader":21}],20:[function(t,i,n){var r=t("./DataReader");function a(o){r.call(this,o)}t("../utils").inherits(a,r),a.prototype.byteAt=function(o){return this.data.charCodeAt(this.zero+o)},a.prototype.lastIndexOfSignature=function(o){return this.data.lastIndexOf(o)-this.zero},a.prototype.readAndCheckSignature=function(o){return o===this.readData(4)},a.prototype.readData=function(o){this.checkOffset(o);var l=this.data.slice(this.zero+this.index,this.zero+this.index+o);return this.index+=o,l},i.exports=a},{"../utils":32,"./DataReader":18}],21:[function(t,i,n){var r=t("./ArrayReader");function a(o){r.call(this,o)}t("../utils").inherits(a,r),a.prototype.readData=function(o){if(this.checkOffset(o),o===0)return new Uint8Array(0);var l=this.data.subarray(this.zero+this.index,this.zero+this.index+o);return this.index+=o,l},i.exports=a},{"../utils":32,"./ArrayReader":17}],22:[function(t,i,n){var r=t("../utils"),a=t("../support"),o=t("./ArrayReader"),l=t("./StringReader"),c=t("./NodeBufferReader"),h=t("./Uint8ArrayReader");i.exports=function(d){var p=r.getTypeOf(d);return r.checkSupport(p),p!=="string"||a.uint8array?p==="nodebuffer"?new c(d):a.uint8array?new h(r.transformTo("uint8array",d)):new o(r.transformTo("array",d)):new l(d)}},{"../support":30,"../utils":32,"./ArrayReader":17,"./NodeBufferReader":19,"./StringReader":20,"./Uint8ArrayReader":21}],23:[function(t,i,n){n.LOCAL_FILE_HEADER="PK",n.CENTRAL_FILE_HEADER="PK",n.CENTRAL_DIRECTORY_END="PK",n.ZIP64_CENTRAL_DIRECTORY_LOCATOR="PK\x07",n.ZIP64_CENTRAL_DIRECTORY_END="PK",n.DATA_DESCRIPTOR="PK\x07\b"},{}],24:[function(t,i,n){var r=t("./GenericWorker"),a=t("../utils");function o(l){r.call(this,"ConvertWorker to "+l),this.destType=l}a.inherits(o,r),o.prototype.processChunk=function(l){this.push({data:a.transformTo(this.destType,l.data),meta:l.meta})},i.exports=o},{"../utils":32,"./GenericWorker":28}],25:[function(t,i,n){var r=t("./GenericWorker"),a=t("../crc32");function o(){r.call(this,"Crc32Probe"),this.withStreamInfo("crc32",0)}t("../utils").inherits(o,r),o.prototype.processChunk=function(l){this.streamInfo.crc32=a(l.data,this.streamInfo.crc32||0),this.push(l)},i.exports=o},{"../crc32":4,"../utils":32,"./GenericWorker":28}],26:[function(t,i,n){var r=t("../utils"),a=t("./GenericWorker");function o(l){a.call(this,"DataLengthProbe for "+l),this.propName=l,this.withStreamInfo(l,0)}r.inherits(o,a),o.prototype.processChunk=function(l){if(l){var c=this.streamInfo[this.propName]||0;this.streamInfo[this.propName]=c+l.data.length}a.prototype.processChunk.call(this,l)},i.exports=o},{"../utils":32,"./GenericWorker":28}],27:[function(t,i,n){var r=t("../utils"),a=t("./GenericWorker");function o(l){a.call(this,"DataWorker");var c=this;this.dataIsReady=!1,this.index=0,this.max=0,this.data=null,this.type="",this._tickScheduled=!1,l.then(function(h){c.dataIsReady=!0,c.data=h,c.max=h&&h.length||0,c.type=r.getTypeOf(h),c.isPaused||c._tickAndRepeat()},function(h){c.error(h)})}r.inherits(o,a),o.prototype.cleanUp=function(){a.prototype.cleanUp.call(this),this.data=null},o.prototype.resume=function(){return!!a.prototype.resume.call(this)&&(!this._tickScheduled&&this.dataIsReady&&(this._tickScheduled=!0,r.delay(this._tickAndRepeat,[],this)),!0)},o.prototype._tickAndRepeat=function(){this._tickScheduled=!1,this.isPaused||this.isFinished||(this._tick(),this.isFinished||(r.delay(this._tickAndRepeat,[],this),this._tickScheduled=!0))},o.prototype._tick=function(){if(this.isPaused||this.isFinished)return!1;var l=null,c=Math.min(this.max,this.index+16384);if(this.index>=this.max)return this.end();switch(this.type){case"string":l=this.data.substring(this.index,c);break;case"uint8array":l=this.data.subarray(this.index,c);break;case"array":case"nodebuffer":l=this.data.slice(this.index,c)}return this.index=c,this.push({data:l,meta:{percent:this.max?this.index/this.max*100:0}})},i.exports=o},{"../utils":32,"./GenericWorker":28}],28:[function(t,i,n){function r(a){this.name=a||"default",this.streamInfo={},this.generatedError=null,this.extraStreamInfo={},this.isPaused=!0,this.isFinished=!1,this.isLocked=!1,this._listeners={data:[],end:[],error:[]},this.previous=null}r.prototype={push:function(a){this.emit("data",a)},end:function(){if(this.isFinished)return!1;this.flush();try{this.emit("end"),this.cleanUp(),this.isFinished=!0}catch(a){this.emit("error",a)}return!0},error:function(a){return!this.isFinished&&(this.isPaused?this.generatedError=a:(this.isFinished=!0,this.emit("error",a),this.previous&&this.previous.error(a),this.cleanUp()),!0)},on:function(a,o){return this._listeners[a].push(o),this},cleanUp:function(){this.streamInfo=this.generatedError=this.extraStreamInfo=null,this._listeners=[]},emit:function(a,o){if(this._listeners[a])for(var l=0;l "+a:a}},i.exports=r},{}],29:[function(t,i,n){var r=t("../utils"),a=t("./ConvertWorker"),o=t("./GenericWorker"),l=t("../base64"),c=t("../support"),h=t("../external"),d=null;if(c.nodestream)try{d=t("../nodejs/NodejsStreamOutputAdapter")}catch{}function p(v,g){return new h.Promise(function(m,f){var y=[],x=v._internalType,_=v._outputType,S=v._mimeType;v.on("data",function(b,E){y.push(b),g&&g(E)}).on("error",function(b){y=[],f(b)}).on("end",function(){try{var b=(function(E,w,M){switch(E){case"blob":return r.newBlob(r.transformTo("arraybuffer",w),M);case"base64":return l.encode(w);default:return r.transformTo(E,w)}})(_,(function(E,w){var M,C=0,I=null,P=0;for(M=0;M"u")n.blob=!1;else{var r=new ArrayBuffer(0);try{n.blob=new Blob([r],{type:"application/zip"}).size===0}catch{try{var a=new(self.BlobBuilder||self.WebKitBlobBuilder||self.MozBlobBuilder||self.MSBlobBuilder);a.append(r),n.blob=a.getBlob("application/zip").size===0}catch{n.blob=!1}}}try{n.nodestream=!!t("readable-stream").Readable}catch{n.nodestream=!1}},{"readable-stream":16}],31:[function(t,i,n){for(var r=t("./utils"),a=t("./support"),o=t("./nodejsUtils"),l=t("./stream/GenericWorker"),c=new Array(256),h=0;h<256;h++)c[h]=252<=h?6:248<=h?5:240<=h?4:224<=h?3:192<=h?2:1;c[254]=c[254]=1;function d(){l.call(this,"utf-8 decode"),this.leftOver=null}function p(){l.call(this,"utf-8 encode")}n.utf8encode=function(u){return a.nodebuffer?o.newBufferFrom(u,"utf-8"):(function(v){var g,m,f,y,x,_=v.length,S=0;for(y=0;y<_;y++)(64512&(m=v.charCodeAt(y)))==55296&&y+1<_&&(64512&(f=v.charCodeAt(y+1)))==56320&&(m=65536+(m-55296<<10)+(f-56320),y++),S+=m<128?1:m<2048?2:m<65536?3:4;for(g=a.uint8array?new Uint8Array(S):new Array(S),y=x=0;x>>6:(m<65536?g[x++]=224|m>>>12:(g[x++]=240|m>>>18,g[x++]=128|m>>>12&63),g[x++]=128|m>>>6&63),g[x++]=128|63&m);return g})(u)},n.utf8decode=function(u){return a.nodebuffer?r.transformTo("nodebuffer",u).toString("utf-8"):(function(v){var g,m,f,y,x=v.length,_=new Array(2*x);for(g=m=0;g>10&1023,_[m++]=56320|1023&f)}return _.length!==m&&(_.subarray?_=_.subarray(0,m):_.length=m),r.applyFromCharCode(_)})(u=r.transformTo(a.uint8array?"uint8array":"array",u))},r.inherits(d,l),d.prototype.processChunk=function(u){var v=r.transformTo(a.uint8array?"uint8array":"array",u.data);if(this.leftOver&&this.leftOver.length){if(a.uint8array){var g=v;(v=new Uint8Array(g.length+this.leftOver.length)).set(this.leftOver,0),v.set(g,this.leftOver.length)}else v=this.leftOver.concat(v);this.leftOver=null}var m=(function(y,x){var _;for((x=x||y.length)>y.length&&(x=y.length),_=x-1;0<=_&&(192&y[_])==128;)_--;return _<0||_===0?x:_+c[y[_]]>x?_:x})(v),f=v;m!==v.length&&(a.uint8array?(f=v.subarray(0,m),this.leftOver=v.subarray(m,v.length)):(f=v.slice(0,m),this.leftOver=v.slice(m,v.length))),this.push({data:n.utf8decode(f),meta:u.meta})},d.prototype.flush=function(){this.leftOver&&this.leftOver.length&&(this.push({data:n.utf8decode(this.leftOver),meta:{}}),this.leftOver=null)},n.Utf8DecodeWorker=d,r.inherits(p,l),p.prototype.processChunk=function(u){this.push({data:n.utf8encode(u.data),meta:u.meta})},n.Utf8EncodeWorker=p},{"./nodejsUtils":14,"./stream/GenericWorker":28,"./support":30,"./utils":32}],32:[function(t,i,n){var r=t("./support"),a=t("./base64"),o=t("./nodejsUtils"),l=t("./external");function c(g){return g}function h(g,m){for(var f=0;f>8;this.dir=!!(16&this.externalFileAttributes),u==0&&(this.dosPermissions=63&this.externalFileAttributes),u==3&&(this.unixPermissions=this.externalFileAttributes>>16&65535),this.dir||this.fileNameStr.slice(-1)!=="/"||(this.dir=!0)},parseZIP64ExtraField:function(){if(this.extraFields[1]){var u=r(this.extraFields[1].value);this.uncompressedSize===a.MAX_VALUE_32BITS&&(this.uncompressedSize=u.readInt(8)),this.compressedSize===a.MAX_VALUE_32BITS&&(this.compressedSize=u.readInt(8)),this.localHeaderOffset===a.MAX_VALUE_32BITS&&(this.localHeaderOffset=u.readInt(8)),this.diskNumberStart===a.MAX_VALUE_32BITS&&(this.diskNumberStart=u.readInt(4))}},readExtraFields:function(u){var v,g,m,f=u.index+this.extraFieldsLength;for(this.extraFields||(this.extraFields={});u.index+4>>6:(u<65536?p[m++]=224|u>>>12:(p[m++]=240|u>>>18,p[m++]=128|u>>>12&63),p[m++]=128|u>>>6&63),p[m++]=128|63&u);return p},n.buf2binstring=function(d){return h(d,d.length)},n.binstring2buf=function(d){for(var p=new r.Buf8(d.length),u=0,v=p.length;u>10&1023,y[v++]=56320|1023&g)}return h(y,v)},n.utf8border=function(d,p){var u;for((p=p||d.length)>d.length&&(p=d.length),u=p-1;0<=u&&(192&d[u])==128;)u--;return u<0||u===0?p:u+l[d[u]]>p?u:p}},{"./common":41}],43:[function(t,i,n){i.exports=function(r,a,o,l){for(var c=65535&r|0,h=r>>>16&65535|0,d=0;o!==0;){for(o-=d=2e3>>1:a>>>1;o[l]=a}return o})();i.exports=function(a,o,l,c){var h=r,d=c+l;a^=-1;for(var p=c;p>>8^h[255&(a^o[p])];return-1^a}},{}],46:[function(t,i,n){var r,a=t("../utils/common"),o=t("./trees"),l=t("./adler32"),c=t("./crc32"),h=t("./messages"),d=0,p=4,u=0,v=-2,g=-1,m=4,f=2,y=8,x=9,_=286,S=30,b=19,E=2*_+1,w=15,M=3,C=258,I=C+M+1,P=42,k=113,A=1,B=2,F=3,H=4;function q(D,ae){return D.msg=h[ae],ae}function G(D){return(D<<1)-(4D.avail_out&&(Q=D.avail_out),Q!==0&&(a.arraySet(D.output,ae.pending_buf,ae.pending_out,Q,D.next_out),D.next_out+=Q,ae.pending_out+=Q,D.total_out+=Q,D.avail_out-=Q,ae.pending-=Q,ae.pending===0&&(ae.pending_out=0))}function $(D,ae){o._tr_flush_block(D,0<=D.block_start?D.block_start:-1,D.strstart-D.block_start,ae),D.block_start=D.strstart,Y(D.strm)}function _e(D,ae){D.pending_buf[D.pending++]=ae}function Te(D,ae){D.pending_buf[D.pending++]=ae>>>8&255,D.pending_buf[D.pending++]=255&ae}function be(D,ae){var Q,W,N=D.max_chain_length,te=D.strstart,de=D.prev_length,V=D.nice_match,ee=D.strstart>D.w_size-I?D.strstart-(D.w_size-I):0,L=D.window,T=D.w_mask,U=D.prev,j=D.strstart+C,K=L[te+de-1],Z=L[te+de];D.prev_length>=D.good_match&&(N>>=2),V>D.lookahead&&(V=D.lookahead);do if(L[(Q=ae)+de]===Z&&L[Q+de-1]===K&&L[Q]===L[te]&&L[++Q]===L[te+1]){te+=2,Q++;do;while(L[++te]===L[++Q]&&L[++te]===L[++Q]&&L[++te]===L[++Q]&&L[++te]===L[++Q]&&L[++te]===L[++Q]&&L[++te]===L[++Q]&&L[++te]===L[++Q]&&L[++te]===L[++Q]&&teee&&--N!=0);return de<=D.lookahead?de:D.lookahead}function J(D){var ae,Q,W,N,te,de,V,ee,L,T,U=D.w_size;do{if(N=D.window_size-D.lookahead-D.strstart,D.strstart>=U+(U-I)){for(a.arraySet(D.window,D.window,U,U,0),D.match_start-=U,D.strstart-=U,D.block_start-=U,ae=Q=D.hash_size;W=D.head[--ae],D.head[ae]=U<=W?W-U:0,--Q;);for(ae=Q=U;W=D.prev[--ae],D.prev[ae]=U<=W?W-U:0,--Q;);N+=U}if(D.strm.avail_in===0)break;if(de=D.strm,V=D.window,ee=D.strstart+D.lookahead,L=N,T=void 0,T=de.avail_in,L=M)for(te=D.strstart-D.insert,D.ins_h=D.window[te],D.ins_h=(D.ins_h<=M&&(D.ins_h=(D.ins_h<=M)if(W=o._tr_tally(D,D.strstart-D.match_start,D.match_length-M),D.lookahead-=D.match_length,D.match_length<=D.max_lazy_match&&D.lookahead>=M){for(D.match_length--;D.strstart++,D.ins_h=(D.ins_h<=M&&(D.ins_h=(D.ins_h<=M&&D.match_length<=D.prev_length){for(N=D.strstart+D.lookahead-M,W=o._tr_tally(D,D.strstart-1-D.prev_match,D.prev_length-M),D.lookahead-=D.prev_length-1,D.prev_length-=2;++D.strstart<=N&&(D.ins_h=(D.ins_h<D.pending_buf_size-5&&(Q=D.pending_buf_size-5);;){if(D.lookahead<=1){if(J(D),D.lookahead===0&&ae===d)return A;if(D.lookahead===0)break}D.strstart+=D.lookahead,D.lookahead=0;var W=D.block_start+Q;if((D.strstart===0||D.strstart>=W)&&(D.lookahead=D.strstart-W,D.strstart=W,$(D,!1),D.strm.avail_out===0)||D.strstart-D.block_start>=D.w_size-I&&($(D,!1),D.strm.avail_out===0))return A}return D.insert=0,ae===p?($(D,!0),D.strm.avail_out===0?F:H):(D.strstart>D.block_start&&($(D,!1),D.strm.avail_out),A)}),new Re(4,4,8,4,oe),new Re(4,5,16,8,oe),new Re(4,6,32,32,oe),new Re(4,4,16,16,ue),new Re(8,16,32,32,ue),new Re(8,16,128,128,ue),new Re(8,32,128,256,ue),new Re(32,128,258,1024,ue),new Re(32,258,258,4096,ue)],n.deflateInit=function(D,ae){return je(D,ae,y,15,8,0)},n.deflateInit2=je,n.deflateReset=tt,n.deflateResetKeep=Ue,n.deflateSetHeader=function(D,ae){return D&&D.state?D.state.wrap!==2?v:(D.state.gzhead=ae,u):v},n.deflate=function(D,ae){var Q,W,N,te;if(!D||!D.state||5>8&255),_e(W,W.gzhead.time>>16&255),_e(W,W.gzhead.time>>24&255),_e(W,W.level===9?2:2<=W.strategy||W.level<2?4:0),_e(W,255&W.gzhead.os),W.gzhead.extra&&W.gzhead.extra.length&&(_e(W,255&W.gzhead.extra.length),_e(W,W.gzhead.extra.length>>8&255)),W.gzhead.hcrc&&(D.adler=c(D.adler,W.pending_buf,W.pending,0)),W.gzindex=0,W.status=69):(_e(W,0),_e(W,0),_e(W,0),_e(W,0),_e(W,0),_e(W,W.level===9?2:2<=W.strategy||W.level<2?4:0),_e(W,3),W.status=k);else{var de=y+(W.w_bits-8<<4)<<8;de|=(2<=W.strategy||W.level<2?0:W.level<6?1:W.level===6?2:3)<<6,W.strstart!==0&&(de|=32),de+=31-de%31,W.status=k,Te(W,de),W.strstart!==0&&(Te(W,D.adler>>>16),Te(W,65535&D.adler)),D.adler=1}if(W.status===69)if(W.gzhead.extra){for(N=W.pending;W.gzindex<(65535&W.gzhead.extra.length)&&(W.pending!==W.pending_buf_size||(W.gzhead.hcrc&&W.pending>N&&(D.adler=c(D.adler,W.pending_buf,W.pending-N,N)),Y(D),N=W.pending,W.pending!==W.pending_buf_size));)_e(W,255&W.gzhead.extra[W.gzindex]),W.gzindex++;W.gzhead.hcrc&&W.pending>N&&(D.adler=c(D.adler,W.pending_buf,W.pending-N,N)),W.gzindex===W.gzhead.extra.length&&(W.gzindex=0,W.status=73)}else W.status=73;if(W.status===73)if(W.gzhead.name){N=W.pending;do{if(W.pending===W.pending_buf_size&&(W.gzhead.hcrc&&W.pending>N&&(D.adler=c(D.adler,W.pending_buf,W.pending-N,N)),Y(D),N=W.pending,W.pending===W.pending_buf_size)){te=1;break}te=W.gzindexN&&(D.adler=c(D.adler,W.pending_buf,W.pending-N,N)),te===0&&(W.gzindex=0,W.status=91)}else W.status=91;if(W.status===91)if(W.gzhead.comment){N=W.pending;do{if(W.pending===W.pending_buf_size&&(W.gzhead.hcrc&&W.pending>N&&(D.adler=c(D.adler,W.pending_buf,W.pending-N,N)),Y(D),N=W.pending,W.pending===W.pending_buf_size)){te=1;break}te=W.gzindexN&&(D.adler=c(D.adler,W.pending_buf,W.pending-N,N)),te===0&&(W.status=103)}else W.status=103;if(W.status===103&&(W.gzhead.hcrc?(W.pending+2>W.pending_buf_size&&Y(D),W.pending+2<=W.pending_buf_size&&(_e(W,255&D.adler),_e(W,D.adler>>8&255),D.adler=0,W.status=k)):W.status=k),W.pending!==0){if(Y(D),D.avail_out===0)return W.last_flush=-1,u}else if(D.avail_in===0&&G(ae)<=G(Q)&&ae!==p)return q(D,-5);if(W.status===666&&D.avail_in!==0)return q(D,-5);if(D.avail_in!==0||W.lookahead!==0||ae!==d&&W.status!==666){var V=W.strategy===2?(function(ee,L){for(var T;;){if(ee.lookahead===0&&(J(ee),ee.lookahead===0)){if(L===d)return A;break}if(ee.match_length=0,T=o._tr_tally(ee,0,ee.window[ee.strstart]),ee.lookahead--,ee.strstart++,T&&($(ee,!1),ee.strm.avail_out===0))return A}return ee.insert=0,L===p?($(ee,!0),ee.strm.avail_out===0?F:H):ee.last_lit&&($(ee,!1),ee.strm.avail_out===0)?A:B})(W,ae):W.strategy===3?(function(ee,L){for(var T,U,j,K,Z=ee.window;;){if(ee.lookahead<=C){if(J(ee),ee.lookahead<=C&&L===d)return A;if(ee.lookahead===0)break}if(ee.match_length=0,ee.lookahead>=M&&0ee.lookahead&&(ee.match_length=ee.lookahead)}if(ee.match_length>=M?(T=o._tr_tally(ee,1,ee.match_length-M),ee.lookahead-=ee.match_length,ee.strstart+=ee.match_length,ee.match_length=0):(T=o._tr_tally(ee,0,ee.window[ee.strstart]),ee.lookahead--,ee.strstart++),T&&($(ee,!1),ee.strm.avail_out===0))return A}return ee.insert=0,L===p?($(ee,!0),ee.strm.avail_out===0?F:H):ee.last_lit&&($(ee,!1),ee.strm.avail_out===0)?A:B})(W,ae):r[W.level].func(W,ae);if(V!==F&&V!==H||(W.status=666),V===A||V===F)return D.avail_out===0&&(W.last_flush=-1),u;if(V===B&&(ae===1?o._tr_align(W):ae!==5&&(o._tr_stored_block(W,0,0,!1),ae===3&&(re(W.head),W.lookahead===0&&(W.strstart=0,W.block_start=0,W.insert=0))),Y(D),D.avail_out===0))return W.last_flush=-1,u}return ae!==p?u:W.wrap<=0?1:(W.wrap===2?(_e(W,255&D.adler),_e(W,D.adler>>8&255),_e(W,D.adler>>16&255),_e(W,D.adler>>24&255),_e(W,255&D.total_in),_e(W,D.total_in>>8&255),_e(W,D.total_in>>16&255),_e(W,D.total_in>>24&255)):(Te(W,D.adler>>>16),Te(W,65535&D.adler)),Y(D),0=Q.w_size&&(te===0&&(re(Q.head),Q.strstart=0,Q.block_start=0,Q.insert=0),L=new a.Buf8(Q.w_size),a.arraySet(L,ae,T-Q.w_size,Q.w_size,0),ae=L,T=Q.w_size),de=D.avail_in,V=D.next_in,ee=D.input,D.avail_in=T,D.next_in=0,D.input=ae,J(Q);Q.lookahead>=M;){for(W=Q.strstart,N=Q.lookahead-(M-1);Q.ins_h=(Q.ins_h<>>=M=w>>>24,x-=M,(M=w>>>16&255)===0)B[h++]=65535&w;else{if(!(16&M)){if((64&M)==0){w=_[(65535&w)+(y&(1<>>=M,x-=M),x<15&&(y+=A[l++]<>>=M=w>>>24,x-=M,!(16&(M=w>>>16&255))){if((64&M)==0){w=S[(65535&w)+(y&(1<>>=M,x-=M,(M=h-d)>3,y&=(1<<(x-=C<<3))-1,r.next_in=l,r.next_out=h,r.avail_in=l>>24&255)+(P>>>8&65280)+((65280&P)<<8)+((255&P)<<24)}function y(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new r.Buf16(320),this.work=new r.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function x(P){var k;return P&&P.state?(k=P.state,P.total_in=P.total_out=k.total=0,P.msg="",k.wrap&&(P.adler=1&k.wrap),k.mode=v,k.last=0,k.havedict=0,k.dmax=32768,k.head=null,k.hold=0,k.bits=0,k.lencode=k.lendyn=new r.Buf32(g),k.distcode=k.distdyn=new r.Buf32(m),k.sane=1,k.back=-1,p):u}function _(P){var k;return P&&P.state?((k=P.state).wsize=0,k.whave=0,k.wnext=0,x(P)):u}function S(P,k){var A,B;return P&&P.state?(B=P.state,k<0?(A=0,k=-k):(A=1+(k>>4),k<48&&(k&=15)),k&&(k<8||15=H.wsize?(r.arraySet(H.window,k,A-H.wsize,H.wsize,0),H.wnext=0,H.whave=H.wsize):(B<(F=H.wsize-H.wnext)&&(F=B),r.arraySet(H.window,k,A-B,F,H.wnext),(B-=F)?(r.arraySet(H.window,k,A-B,B,0),H.wnext=B,H.whave=H.wsize):(H.wnext+=F,H.wnext===H.wsize&&(H.wnext=0),H.whave>>8&255,A.check=o(A.check,te,2,0),$=Y=0,A.mode=2;break}if(A.flags=0,A.head&&(A.head.done=!1),!(1&A.wrap)||(((255&Y)<<8)+(Y>>8))%31){P.msg="incorrect header check",A.mode=30;break}if((15&Y)!=8){P.msg="unknown compression method",A.mode=30;break}if($-=4,D=8+(15&(Y>>>=4)),A.wbits===0)A.wbits=D;else if(D>A.wbits){P.msg="invalid window size",A.mode=30;break}A.dmax=1<>8&1),512&A.flags&&(te[0]=255&Y,te[1]=Y>>>8&255,A.check=o(A.check,te,2,0)),$=Y=0,A.mode=3;case 3:for(;$<32;){if(G===0)break e;G--,Y+=B[H++]<<$,$+=8}A.head&&(A.head.time=Y),512&A.flags&&(te[0]=255&Y,te[1]=Y>>>8&255,te[2]=Y>>>16&255,te[3]=Y>>>24&255,A.check=o(A.check,te,4,0)),$=Y=0,A.mode=4;case 4:for(;$<16;){if(G===0)break e;G--,Y+=B[H++]<<$,$+=8}A.head&&(A.head.xflags=255&Y,A.head.os=Y>>8),512&A.flags&&(te[0]=255&Y,te[1]=Y>>>8&255,A.check=o(A.check,te,2,0)),$=Y=0,A.mode=5;case 5:if(1024&A.flags){for(;$<16;){if(G===0)break e;G--,Y+=B[H++]<<$,$+=8}A.length=Y,A.head&&(A.head.extra_len=Y),512&A.flags&&(te[0]=255&Y,te[1]=Y>>>8&255,A.check=o(A.check,te,2,0)),$=Y=0}else A.head&&(A.head.extra=null);A.mode=6;case 6:if(1024&A.flags&&(G<(be=A.length)&&(be=G),be&&(A.head&&(D=A.head.extra_len-A.length,A.head.extra||(A.head.extra=new Array(A.head.extra_len)),r.arraySet(A.head.extra,B,H,be,D)),512&A.flags&&(A.check=o(A.check,B,be,H)),G-=be,H+=be,A.length-=be),A.length))break e;A.length=0,A.mode=7;case 7:if(2048&A.flags){if(G===0)break e;for(be=0;D=B[H+be++],A.head&&D&&A.length<65536&&(A.head.name+=String.fromCharCode(D)),D&&be>9&1,A.head.done=!0),P.adler=A.check=0,A.mode=12;break;case 10:for(;$<32;){if(G===0)break e;G--,Y+=B[H++]<<$,$+=8}P.adler=A.check=f(Y),$=Y=0,A.mode=11;case 11:if(A.havedict===0)return P.next_out=q,P.avail_out=re,P.next_in=H,P.avail_in=G,A.hold=Y,A.bits=$,2;P.adler=A.check=1,A.mode=12;case 12:if(k===5||k===6)break e;case 13:if(A.last){Y>>>=7&$,$-=7&$,A.mode=27;break}for(;$<3;){if(G===0)break e;G--,Y+=B[H++]<<$,$+=8}switch(A.last=1&Y,$-=1,3&(Y>>>=1)){case 0:A.mode=14;break;case 1:if(C(A),A.mode=20,k!==6)break;Y>>>=2,$-=2;break e;case 2:A.mode=17;break;case 3:P.msg="invalid block type",A.mode=30}Y>>>=2,$-=2;break;case 14:for(Y>>>=7&$,$-=7&$;$<32;){if(G===0)break e;G--,Y+=B[H++]<<$,$+=8}if((65535&Y)!=(Y>>>16^65535)){P.msg="invalid stored block lengths",A.mode=30;break}if(A.length=65535&Y,$=Y=0,A.mode=15,k===6)break e;case 15:A.mode=16;case 16:if(be=A.length){if(G>>=5,$-=5,A.ndist=1+(31&Y),Y>>>=5,$-=5,A.ncode=4+(15&Y),Y>>>=4,$-=4,286>>=3,$-=3}for(;A.have<19;)A.lens[de[A.have++]]=0;if(A.lencode=A.lendyn,A.lenbits=7,Q={bits:A.lenbits},ae=c(0,A.lens,0,19,A.lencode,0,A.work,Q),A.lenbits=Q.bits,ae){P.msg="invalid code lengths set",A.mode=30;break}A.have=0,A.mode=19;case 19:for(;A.have>>16&255,Ie=65535&N,!((ue=N>>>24)<=$);){if(G===0)break e;G--,Y+=B[H++]<<$,$+=8}if(Ie<16)Y>>>=ue,$-=ue,A.lens[A.have++]=Ie;else{if(Ie===16){for(W=ue+2;$>>=ue,$-=ue,A.have===0){P.msg="invalid bit length repeat",A.mode=30;break}D=A.lens[A.have-1],be=3+(3&Y),Y>>>=2,$-=2}else if(Ie===17){for(W=ue+3;$>>=ue)),Y>>>=3,$-=3}else{for(W=ue+7;$>>=ue)),Y>>>=7,$-=7}if(A.have+be>A.nlen+A.ndist){P.msg="invalid bit length repeat",A.mode=30;break}for(;be--;)A.lens[A.have++]=D}}if(A.mode===30)break;if(A.lens[256]===0){P.msg="invalid code -- missing end-of-block",A.mode=30;break}if(A.lenbits=9,Q={bits:A.lenbits},ae=c(h,A.lens,0,A.nlen,A.lencode,0,A.work,Q),A.lenbits=Q.bits,ae){P.msg="invalid literal/lengths set",A.mode=30;break}if(A.distbits=6,A.distcode=A.distdyn,Q={bits:A.distbits},ae=c(d,A.lens,A.nlen,A.ndist,A.distcode,0,A.work,Q),A.distbits=Q.bits,ae){P.msg="invalid distances set",A.mode=30;break}if(A.mode=20,k===6)break e;case 20:A.mode=21;case 21:if(6<=G&&258<=re){P.next_out=q,P.avail_out=re,P.next_in=H,P.avail_in=G,A.hold=Y,A.bits=$,l(P,Te),q=P.next_out,F=P.output,re=P.avail_out,H=P.next_in,B=P.input,G=P.avail_in,Y=A.hold,$=A.bits,A.mode===12&&(A.back=-1);break}for(A.back=0;Re=(N=A.lencode[Y&(1<>>16&255,Ie=65535&N,!((ue=N>>>24)<=$);){if(G===0)break e;G--,Y+=B[H++]<<$,$+=8}if(Re&&(240&Re)==0){for(Ue=ue,tt=Re,je=Ie;Re=(N=A.lencode[je+((Y&(1<>Ue)])>>>16&255,Ie=65535&N,!(Ue+(ue=N>>>24)<=$);){if(G===0)break e;G--,Y+=B[H++]<<$,$+=8}Y>>>=Ue,$-=Ue,A.back+=Ue}if(Y>>>=ue,$-=ue,A.back+=ue,A.length=Ie,Re===0){A.mode=26;break}if(32&Re){A.back=-1,A.mode=12;break}if(64&Re){P.msg="invalid literal/length code",A.mode=30;break}A.extra=15&Re,A.mode=22;case 22:if(A.extra){for(W=A.extra;$>>=A.extra,$-=A.extra,A.back+=A.extra}A.was=A.length,A.mode=23;case 23:for(;Re=(N=A.distcode[Y&(1<>>16&255,Ie=65535&N,!((ue=N>>>24)<=$);){if(G===0)break e;G--,Y+=B[H++]<<$,$+=8}if((240&Re)==0){for(Ue=ue,tt=Re,je=Ie;Re=(N=A.distcode[je+((Y&(1<>Ue)])>>>16&255,Ie=65535&N,!(Ue+(ue=N>>>24)<=$);){if(G===0)break e;G--,Y+=B[H++]<<$,$+=8}Y>>>=Ue,$-=Ue,A.back+=Ue}if(Y>>>=ue,$-=ue,A.back+=ue,64&Re){P.msg="invalid distance code",A.mode=30;break}A.offset=Ie,A.extra=15&Re,A.mode=24;case 24:if(A.extra){for(W=A.extra;$>>=A.extra,$-=A.extra,A.back+=A.extra}if(A.offset>A.dmax){P.msg="invalid distance too far back",A.mode=30;break}A.mode=25;case 25:if(re===0)break e;if(be=Te-re,A.offset>be){if((be=A.offset-be)>A.whave&&A.sane){P.msg="invalid distance too far back",A.mode=30;break}J=be>A.wnext?(be-=A.wnext,A.wsize-be):A.wnext-be,be>A.length&&(be=A.length),oe=A.window}else oe=F,J=q-A.offset,be=A.length;for(reE?(M=J[oe+m[k]],$[_e+m[k]]):(M=96,0),y=1<>q)+(x-=y)]=w<<24|M<<16|C|0,x!==0;);for(y=1<>=1;if(y!==0?(Y&=y-1,Y+=y):Y=0,k++,--Te[P]==0){if(P===B)break;P=d[p+m[k]]}if(F>>7)]}function _e(N,te){N.pending_buf[N.pending++]=255&te,N.pending_buf[N.pending++]=te>>>8&255}function Te(N,te,de){N.bi_valid>f-de?(N.bi_buf|=te<>f-N.bi_valid,N.bi_valid+=de-f):(N.bi_buf|=te<>>=1,de<<=1,0<--te;);return de>>>1}function oe(N,te,de){var V,ee,L=new Array(m+1),T=0;for(V=1;V<=m;V++)L[V]=T=T+de[V-1]<<1;for(ee=0;ee<=te;ee++){var U=N[2*ee+1];U!==0&&(N[2*ee]=J(L[U]++,U))}}function ue(N){var te;for(te=0;te>1;1<=de;de--)Ue(N,L,de);for(ee=j;de=N.heap[1],N.heap[1]=N.heap[N.heap_len--],Ue(N,L,1),V=N.heap[1],N.heap[--N.heap_max]=de,N.heap[--N.heap_max]=V,L[2*ee]=L[2*de]+L[2*V],N.depth[ee]=(N.depth[de]>=N.depth[V]?N.depth[de]:N.depth[V])+1,L[2*de+1]=L[2*V+1]=ee,N.heap[1]=ee++,Ue(N,L,1),2<=N.heap_len;);N.heap[--N.heap_max]=N.heap[1],(function(Z,Pe){var ve,ke,Fe,le,ye,ze,Oe=Pe.dyn_tree,Se=Pe.max_code,Xe=Pe.stat_desc.static_tree,z=Pe.stat_desc.has_stree,xe=Pe.stat_desc.extra_bits,ge=Pe.stat_desc.extra_base,Le=Pe.stat_desc.max_length,pe=0;for(le=0;le<=m;le++)Z.bl_count[le]=0;for(Oe[2*Z.heap[Z.heap_max]+1]=0,ve=Z.heap_max+1;ve>=7;ee>>=1)if(1&K&&U.dyn_ltree[2*j]!==0)return a;if(U.dyn_ltree[18]!==0||U.dyn_ltree[20]!==0||U.dyn_ltree[26]!==0)return o;for(j=32;j>>3,(L=N.static_len+3+7>>>3)<=ee&&(ee=L)):ee=L=de+5,de+4<=ee&&te!==-1?W(N,te,de,V):N.strategy===4||L===ee?(Te(N,2+(V?1:0),3),tt(N,I,P)):(Te(N,4+(V?1:0),3),(function(U,j,K,Z){var Pe;for(Te(U,j-257,5),Te(U,K-1,5),Te(U,Z-4,4),Pe=0;Pe>>8&255,N.pending_buf[N.d_buf+2*N.last_lit+1]=255&te,N.pending_buf[N.l_buf+N.last_lit]=255&de,N.last_lit++,te===0?N.dyn_ltree[2*de]++:(N.matches++,te--,N.dyn_ltree[2*(A[de]+d+1)]++,N.dyn_dtree[2*$(te)]++),N.last_lit===N.lit_bufsize-1},n._tr_align=function(N){Te(N,2,3),be(N,x,I),(function(te){te.bi_valid===16?(_e(te,te.bi_buf),te.bi_buf=0,te.bi_valid=0):8<=te.bi_valid&&(te.pending_buf[te.pending++]=255&te.bi_buf,te.bi_buf>>=8,te.bi_valid-=8)})(N)}},{"../utils/common":41}],53:[function(t,i,n){i.exports=function(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}},{}],54:[function(t,i,n){(function(r){(function(a,o){if(!a.setImmediate){var l,c,h,d,p=1,u={},v=!1,g=a.document,m=Object.getPrototypeOf&&Object.getPrototypeOf(a);m=m&&m.setTimeout?m:a,l={}.toString.call(a.process)==="[object process]"?function(_){process.nextTick(function(){y(_)})}:(function(){if(a.postMessage&&!a.importScripts){var _=!0,S=a.onmessage;return a.onmessage=function(){_=!1},a.postMessage("","*"),a.onmessage=S,_}})()?(d="setImmediate$"+Math.random()+"$",a.addEventListener?a.addEventListener("message",x,!1):a.attachEvent("onmessage",x),function(_){a.postMessage(d+_,"*")}):a.MessageChannel?((h=new MessageChannel).port1.onmessage=function(_){y(_.data)},function(_){h.port2.postMessage(_)}):g&&"onreadystatechange"in g.createElement("script")?(c=g.documentElement,function(_){var S=g.createElement("script");S.onreadystatechange=function(){y(_),S.onreadystatechange=null,c.removeChild(S),S=null},c.appendChild(S)}):function(_){setTimeout(y,0,_)},m.setImmediate=function(_){typeof _!="function"&&(_=new Function(""+_));for(var S=new Array(arguments.length-1),b=0;b"u"?r===void 0?this:r:self)}).call(this,typeof If<"u"?If:typeof self<"u"?self:typeof window<"u"?window:{})},{}]},{},[10])(10)})})(aS)),aS.exports}var V8=H8();const lS=rS(V8);function cS(s,e){return function(){return s.apply(e,arguments)}}const{toString:G8}=Object.prototype,{getPrototypeOf:Kv}=Object,{iterator:Df,toStringTag:hS}=Symbol,Nf=(s=>e=>{const t=G8.call(e);return s[t]||(s[t]=t.slice(8,-1).toLowerCase())})(Object.create(null)),Ts=s=>(s=s.toLowerCase(),e=>Nf(e)===s),kf=s=>e=>typeof e===s,{isArray:Kl}=Array,Jl=kf("undefined");function Lh(s){return s!==null&&!Jl(s)&&s.constructor!==null&&!Jl(s.constructor)&&An(s.constructor.isBuffer)&&s.constructor.isBuffer(s)}const dS=Ts("ArrayBuffer");function W8(s){let e;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?e=ArrayBuffer.isView(s):e=s&&s.buffer&&dS(s.buffer),e}const X8=kf("string"),An=kf("function"),uS=kf("number"),Dh=s=>s!==null&&typeof s=="object",j8=s=>s===!0||s===!1,Of=s=>{if(Nf(s)!=="object")return!1;const e=Kv(s);return(e===null||e===Object.prototype||Object.getPrototypeOf(e)===null)&&!(hS in s)&&!(Df in s)},q8=s=>{if(!Dh(s)||Lh(s))return!1;try{return Object.keys(s).length===0&&Object.getPrototypeOf(s)===Object.prototype}catch{return!1}},Z8=Ts("Date"),Y8=Ts("File"),$8=Ts("Blob"),K8=Ts("FileList"),J8=s=>Dh(s)&&An(s.pipe),Q8=s=>{let e;return s&&(typeof FormData=="function"&&s instanceof FormData||An(s.append)&&((e=Nf(s))==="formdata"||e==="object"&&An(s.toString)&&s.toString()==="[object FormData]"))},ek=Ts("URLSearchParams"),[tk,ik,nk,sk]=["ReadableStream","Request","Response","Headers"].map(Ts),rk=s=>s.trim?s.trim():s.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function Nh(s,e,{allOwnKeys:t=!1}={}){if(s===null||typeof s>"u")return;let i,n;if(typeof s!="object"&&(s=[s]),Kl(s))for(i=0,n=s.length;i0;)if(n=t[i],e===n.toLowerCase())return n;return null}const _o=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,fS=s=>!Jl(s)&&s!==_o;function Jv(){const{caseless:s,skipUndefined:e}=fS(this)&&this||{},t={},i=(n,r)=>{const a=s&&pS(t,r)||r;Of(t[a])&&Of(n)?t[a]=Jv(t[a],n):Of(n)?t[a]=Jv({},n):Kl(n)?t[a]=n.slice():(!e||!Jl(n))&&(t[a]=n)};for(let n=0,r=arguments.length;n(Nh(e,(n,r)=>{t&&An(n)?s[r]=cS(n,t):s[r]=n},{allOwnKeys:i}),s),ok=s=>(s.charCodeAt(0)===65279&&(s=s.slice(1)),s),lk=(s,e,t,i)=>{s.prototype=Object.create(e.prototype,i),s.prototype.constructor=s,Object.defineProperty(s,"super",{value:e.prototype}),t&&Object.assign(s.prototype,t)},ck=(s,e,t,i)=>{let n,r,a;const o={};if(e=e||{},s==null)return e;do{for(n=Object.getOwnPropertyNames(s),r=n.length;r-- >0;)a=n[r],(!i||i(a,s,e))&&!o[a]&&(e[a]=s[a],o[a]=!0);s=t!==!1&&Kv(s)}while(s&&(!t||t(s,e))&&s!==Object.prototype);return e},hk=(s,e,t)=>{s=String(s),(t===void 0||t>s.length)&&(t=s.length),t-=e.length;const i=s.indexOf(e,t);return i!==-1&&i===t},dk=s=>{if(!s)return null;if(Kl(s))return s;let e=s.length;if(!uS(e))return null;const t=new Array(e);for(;e-- >0;)t[e]=s[e];return t},uk=(s=>e=>s&&e instanceof s)(typeof Uint8Array<"u"&&Kv(Uint8Array)),pk=(s,e)=>{const t=(s&&s[Df]).call(s);let i;for(;(i=t.next())&&!i.done;){const n=i.value;e.call(s,n[0],n[1])}},fk=(s,e)=>{let t;const i=[];for(;(t=s.exec(e))!==null;)i.push(t);return i},mk=Ts("HTMLFormElement"),gk=s=>s.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(e,t,i){return t.toUpperCase()+i}),mS=(({hasOwnProperty:s})=>(e,t)=>s.call(e,t))(Object.prototype),vk=Ts("RegExp"),gS=(s,e)=>{const t=Object.getOwnPropertyDescriptors(s),i={};Nh(t,(n,r)=>{let a;(a=e(n,r,s))!==!1&&(i[r]=a||n)}),Object.defineProperties(s,i)},yk=s=>{gS(s,(e,t)=>{if(An(s)&&["arguments","caller","callee"].indexOf(t)!==-1)return!1;const i=s[t];if(An(i)){if(e.enumerable=!1,"writable"in e){e.writable=!1;return}e.set||(e.set=()=>{throw Error("Can not rewrite read-only method '"+t+"'")})}})},xk=(s,e)=>{const t={},i=n=>{n.forEach(r=>{t[r]=!0})};return Kl(s)?i(s):i(String(s).split(e)),t},_k=()=>{},bk=(s,e)=>s!=null&&Number.isFinite(s=+s)?s:e;function Mk(s){return!!(s&&An(s.append)&&s[hS]==="FormData"&&s[Df])}const Sk=s=>{const e=new Array(10),t=(i,n)=>{if(Dh(i)){if(e.indexOf(i)>=0)return;if(Lh(i))return i;if(!("toJSON"in i)){e[n]=i;const r=Kl(i)?[]:{};return Nh(i,(a,o)=>{const l=t(a,n+1);!Jl(l)&&(r[o]=l)}),e[n]=void 0,r}}return i};return t(s,0)},wk=Ts("AsyncFunction"),Ek=s=>s&&(Dh(s)||An(s))&&An(s.then)&&An(s.catch),vS=((s,e)=>s?setImmediate:e?((t,i)=>(_o.addEventListener("message",({source:n,data:r})=>{n===_o&&r===t&&i.length&&i.shift()()},!1),n=>{i.push(n),_o.postMessage(t,"*")}))(`axios@${Math.random()}`,[]):t=>setTimeout(t))(typeof setImmediate=="function",An(_o.postMessage)),Tk=typeof queueMicrotask<"u"?queueMicrotask.bind(_o):typeof process<"u"&&process.nextTick||vS,Ck=s=>s!=null&&An(s[Df]),Ce={isArray:Kl,isArrayBuffer:dS,isBuffer:Lh,isFormData:Q8,isArrayBufferView:W8,isString:X8,isNumber:uS,isBoolean:j8,isObject:Dh,isPlainObject:Of,isEmptyObject:q8,isReadableStream:tk,isRequest:ik,isResponse:nk,isHeaders:sk,isUndefined:Jl,isDate:Z8,isFile:Y8,isBlob:$8,isRegExp:vk,isFunction:An,isStream:J8,isURLSearchParams:ek,isTypedArray:uk,isFileList:K8,forEach:Nh,merge:Jv,extend:ak,trim:rk,stripBOM:ok,inherits:lk,toFlatObject:ck,kindOf:Nf,kindOfTest:Ts,endsWith:hk,toArray:dk,forEachEntry:pk,matchAll:fk,isHTMLForm:mk,hasOwnProperty:mS,hasOwnProp:mS,reduceDescriptors:gS,freezeMethods:yk,toObjectSet:xk,toCamelCase:gk,noop:_k,toFiniteNumber:bk,findKey:pS,global:_o,isContextDefined:fS,isSpecCompliantForm:Mk,toJSONObject:Sk,isAsyncFn:wk,isThenable:Ek,setImmediate:vS,asap:Tk,isIterable:Ck};function xt(s,e,t,i,n){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=new Error().stack,this.message=s,this.name="AxiosError",e&&(this.code=e),t&&(this.config=t),i&&(this.request=i),n&&(this.response=n,this.status=n.status?n.status:null)}Ce.inherits(xt,Error,{toJSON:function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:Ce.toJSONObject(this.config),code:this.code,status:this.status}}});const yS=xt.prototype,xS={};["ERR_BAD_OPTION_VALUE","ERR_BAD_OPTION","ECONNABORTED","ETIMEDOUT","ERR_NETWORK","ERR_FR_TOO_MANY_REDIRECTS","ERR_DEPRECATED","ERR_BAD_RESPONSE","ERR_BAD_REQUEST","ERR_CANCELED","ERR_NOT_SUPPORT","ERR_INVALID_URL"].forEach(s=>{xS[s]={value:s}}),Object.defineProperties(xt,xS),Object.defineProperty(yS,"isAxiosError",{value:!0}),xt.from=(s,e,t,i,n,r)=>{const a=Object.create(yS);Ce.toFlatObject(s,a,function(c){return c!==Error.prototype},c=>c!=="isAxiosError");const o=s&&s.message?s.message:"Error",l=e==null&&s?s.code:e;return xt.call(a,o,l,t,i,n),s&&a.cause==null&&Object.defineProperty(a,"cause",{value:s,configurable:!0}),a.name=s&&s.name||"Error",r&&Object.assign(a,r),a};const Ak=null;function Qv(s){return Ce.isPlainObject(s)||Ce.isArray(s)}function _S(s){return Ce.endsWith(s,"[]")?s.slice(0,-2):s}function bS(s,e,t){return s?s.concat(e).map(function(i,n){return i=_S(i),!t&&n?"["+i+"]":i}).join(t?".":""):e}function Pk(s){return Ce.isArray(s)&&!s.some(Qv)}const Rk=Ce.toFlatObject(Ce,{},null,function(s){return/^is[A-Z]/.test(s)});function Uf(s,e,t){if(!Ce.isObject(s))throw new TypeError("target must be an object");e=e||new FormData,t=Ce.toFlatObject(t,{metaTokens:!0,dots:!1,indexes:!1},!1,function(u,v){return!Ce.isUndefined(v[u])});const i=t.metaTokens,n=t.visitor||c,r=t.dots,a=t.indexes,o=(t.Blob||typeof Blob<"u"&&Blob)&&Ce.isSpecCompliantForm(e);if(!Ce.isFunction(n))throw new TypeError("visitor must be a function");function l(u){if(u===null)return"";if(Ce.isDate(u))return u.toISOString();if(Ce.isBoolean(u))return u.toString();if(!o&&Ce.isBlob(u))throw new xt("Blob is not supported. Use a Buffer instead.");return Ce.isArrayBuffer(u)||Ce.isTypedArray(u)?o&&typeof Blob=="function"?new Blob([u]):Buffer.from(u):u}function c(u,v,g){let m=u;if(u&&!g&&typeof u=="object"){if(Ce.endsWith(v,"{}"))v=i?v:v.slice(0,-2),u=JSON.stringify(u);else if(Ce.isArray(u)&&Pk(u)||(Ce.isFileList(u)||Ce.endsWith(v,"[]"))&&(m=Ce.toArray(u)))return v=_S(v),m.forEach(function(f,y){!(Ce.isUndefined(f)||f===null)&&e.append(a===!0?bS([v],y,r):a===null?v:v+"[]",l(f))}),!1}return Qv(u)?!0:(e.append(bS(g,v,r),l(u)),!1)}const h=[],d=Object.assign(Rk,{defaultVisitor:c,convertValue:l,isVisitable:Qv});function p(u,v){if(!Ce.isUndefined(u)){if(h.indexOf(u)!==-1)throw Error("Circular reference detected in "+v.join("."));h.push(u),Ce.forEach(u,function(g,m){(!(Ce.isUndefined(g)||g===null)&&n.call(e,g,Ce.isString(m)?m.trim():m,v,d))===!0&&p(g,v?v.concat(m):[m])}),h.pop()}}if(!Ce.isObject(s))throw new TypeError("data must be an object");return p(s),e}function MS(s){const e={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(s).replace(/[!'()~]|%20|%00/g,function(t){return e[t]})}function e1(s,e){this._pairs=[],s&&Uf(s,this,e)}const SS=e1.prototype;SS.append=function(s,e){this._pairs.push([s,e])},SS.toString=function(s){const e=s?function(t){return s.call(this,t,MS)}:MS;return this._pairs.map(function(t){return e(t[0])+"="+e(t[1])},"").join("&")};function Ik(s){return encodeURIComponent(s).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+")}function wS(s,e,t){if(!e)return s;const i=t&&t.encode||Ik;Ce.isFunction(t)&&(t={serialize:t});const n=t&&t.serialize;let r;if(n?r=n(e,t):r=Ce.isURLSearchParams(e)?e.toString():new e1(e,t).toString(i),r){const a=s.indexOf("#");a!==-1&&(s=s.slice(0,a)),s+=(s.indexOf("?")===-1?"?":"&")+r}return s}class ES{constructor(){this.handlers=[]}use(e,t,i){return this.handlers.push({fulfilled:e,rejected:t,synchronous:i?i.synchronous:!1,runWhen:i?i.runWhen:null}),this.handlers.length-1}eject(e){this.handlers[e]&&(this.handlers[e]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(e){Ce.forEach(this.handlers,function(t){t!==null&&e(t)})}}const TS={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},Lk=typeof URLSearchParams<"u"?URLSearchParams:e1,Dk=typeof FormData<"u"?FormData:null,Nk=typeof Blob<"u"?Blob:null,kk={isBrowser:!0,classes:{URLSearchParams:Lk,FormData:Dk,Blob:Nk},protocols:["http","https","file","blob","url","data"]},t1=typeof window<"u"&&typeof document<"u",i1=typeof navigator=="object"&&navigator||void 0,Ok=t1&&(!i1||["ReactNative","NativeScript","NS"].indexOf(i1.product)<0),Uk=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",Bk=t1&&window.location.href||"http://localhost",Fk=Object.freeze(Object.defineProperty({__proto__:null,hasBrowserEnv:t1,hasStandardBrowserEnv:Ok,hasStandardBrowserWebWorkerEnv:Uk,navigator:i1,origin:Bk},Symbol.toStringTag,{value:"Module"})),ln={...Fk,...kk};function zk(s,e){return Uf(s,new ln.classes.URLSearchParams,{visitor:function(t,i,n,r){return ln.isNode&&Ce.isBuffer(t)?(this.append(i,t.toString("base64")),!1):r.defaultVisitor.apply(this,arguments)},...e})}function Hk(s){return Ce.matchAll(/\w+|\[(\w*)]/g,s).map(e=>e[0]==="[]"?"":e[1]||e[0])}function Vk(s){const e={},t=Object.keys(s);let i;const n=t.length;let r;for(i=0;i=t.length;return a=!a&&Ce.isArray(n)?n.length:a,l?(Ce.hasOwnProp(n,a)?n[a]=[n[a],i]:n[a]=i,!o):((!n[a]||!Ce.isObject(n[a]))&&(n[a]=[]),e(t,i,n[a],r)&&Ce.isArray(n[a])&&(n[a]=Vk(n[a])),!o)}if(Ce.isFormData(s)&&Ce.isFunction(s.entries)){const t={};return Ce.forEachEntry(s,(i,n)=>{e(Hk(i),n,t,0)}),t}return null}function Gk(s,e,t){if(Ce.isString(s))try{return(e||JSON.parse)(s),Ce.trim(s)}catch(i){if(i.name!=="SyntaxError")throw i}return(t||JSON.stringify)(s)}const kh={transitional:TS,adapter:["xhr","http","fetch"],transformRequest:[function(s,e){const t=e.getContentType()||"",i=t.indexOf("application/json")>-1,n=Ce.isObject(s);if(n&&Ce.isHTMLForm(s)&&(s=new FormData(s)),Ce.isFormData(s))return i?JSON.stringify(CS(s)):s;if(Ce.isArrayBuffer(s)||Ce.isBuffer(s)||Ce.isStream(s)||Ce.isFile(s)||Ce.isBlob(s)||Ce.isReadableStream(s))return s;if(Ce.isArrayBufferView(s))return s.buffer;if(Ce.isURLSearchParams(s))return e.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),s.toString();let r;if(n){if(t.indexOf("application/x-www-form-urlencoded")>-1)return zk(s,this.formSerializer).toString();if((r=Ce.isFileList(s))||t.indexOf("multipart/form-data")>-1){const a=this.env&&this.env.FormData;return Uf(r?{"files[]":s}:s,a&&new a,this.formSerializer)}}return n||i?(e.setContentType("application/json",!1),Gk(s)):s}],transformResponse:[function(s){const e=this.transitional||kh.transitional,t=e&&e.forcedJSONParsing,i=this.responseType==="json";if(Ce.isResponse(s)||Ce.isReadableStream(s))return s;if(s&&Ce.isString(s)&&(t&&!this.responseType||i)){const n=!(e&&e.silentJSONParsing)&&i;try{return JSON.parse(s,this.parseReviver)}catch(r){if(n)throw r.name==="SyntaxError"?xt.from(r,xt.ERR_BAD_RESPONSE,this,null,this.response):r}}return s}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:ln.classes.FormData,Blob:ln.classes.Blob},validateStatus:function(s){return s>=200&&s<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};Ce.forEach(["delete","get","head","post","put","patch"],s=>{kh.headers[s]={}});const Wk=Ce.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]),Xk=s=>{const e={};let t,i,n;return s&&s.split(` `).forEach(function(r){n=r.indexOf(":"),t=r.substring(0,n).trim().toLowerCase(),i=r.substring(n+1).trim(),!(!t||e[t]&&Wk[t])&&(t==="set-cookie"?e[t]?e[t].push(i):e[t]=[i]:e[t]=e[t]?e[t]+", "+i:i)}),e},AS=Symbol("internals");function Oh(s){return s&&String(s).trim().toLowerCase()}function Bf(s){return s===!1||s==null?s:Ce.isArray(s)?s.map(Bf):String(s)}function jk(s){const e=Object.create(null),t=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let i;for(;i=t.exec(s);)e[i[1]]=i[2];return e}const qk=s=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(s.trim());function n1(s,e,t,i,n){if(Ce.isFunction(i))return i.call(this,e,t);if(n&&(e=t),!!Ce.isString(e)){if(Ce.isString(i))return e.indexOf(i)!==-1;if(Ce.isRegExp(i))return i.test(e)}}function Zk(s){return s.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(e,t,i)=>t.toUpperCase()+i)}function Yk(s,e){const t=Ce.toCamelCase(" "+e);["get","set","has"].forEach(i=>{Object.defineProperty(s,i+t,{value:function(n,r,a){return this[i].call(this,e,n,r,a)},configurable:!0})})}let Pn=class{constructor(s){s&&this.set(s)}set(s,e,t){const i=this;function n(a,o,l){const c=Oh(o);if(!c)throw new Error("header name must be a non-empty string");const h=Ce.findKey(i,c);(!h||i[h]===void 0||l===!0||l===void 0&&i[h]!==!1)&&(i[h||o]=Bf(a))}const r=(a,o)=>Ce.forEach(a,(l,c)=>n(l,c,o));if(Ce.isPlainObject(s)||s instanceof this.constructor)r(s,e);else if(Ce.isString(s)&&(s=s.trim())&&!qk(s))r(Xk(s),e);else if(Ce.isObject(s)&&Ce.isIterable(s)){let a={},o,l;for(const c of s){if(!Ce.isArray(c))throw TypeError("Object iterator must return a key-value pair");a[l=c[0]]=(o=a[l])?Ce.isArray(o)?[...o,c[1]]:[o,c[1]]:c[1]}r(a,e)}else s!=null&&n(e,s,t);return this}get(s,e){if(s=Oh(s),s){const t=Ce.findKey(this,s);if(t){const i=this[t];if(!e)return i;if(e===!0)return jk(i);if(Ce.isFunction(e))return e.call(this,i,t);if(Ce.isRegExp(e))return e.exec(i);throw new TypeError("parser must be boolean|regexp|function")}}}has(s,e){if(s=Oh(s),s){const t=Ce.findKey(this,s);return!!(t&&this[t]!==void 0&&(!e||n1(this,this[t],t,e)))}return!1}delete(s,e){const t=this;let i=!1;function n(r){if(r=Oh(r),r){const a=Ce.findKey(t,r);a&&(!e||n1(t,t[a],a,e))&&(delete t[a],i=!0)}}return Ce.isArray(s)?s.forEach(n):n(s),i}clear(s){const e=Object.keys(this);let t=e.length,i=!1;for(;t--;){const n=e[t];(!s||n1(this,this[n],n,s,!0))&&(delete this[n],i=!0)}return i}normalize(s){const e=this,t={};return Ce.forEach(this,(i,n)=>{const r=Ce.findKey(t,n);if(r){e[r]=Bf(i),delete e[n];return}const a=s?Zk(n):String(n).trim();a!==n&&delete e[n],e[a]=Bf(i),t[a]=!0}),this}concat(...s){return this.constructor.concat(this,...s)}toJSON(s){const e=Object.create(null);return Ce.forEach(this,(t,i)=>{t!=null&&t!==!1&&(e[i]=s&&Ce.isArray(t)?t.join(", "):t)}),e}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([s,e])=>s+": "+e).join(` `)}getSetCookie(){return this.get("set-cookie")||[]}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(s){return s instanceof this?s:new this(s)}static concat(s,...e){const t=new this(s);return e.forEach(i=>t.set(i)),t}static accessor(s){const e=(this[AS]=this[AS]={accessors:{}}).accessors,t=this.prototype;function i(n){const r=Oh(n);e[r]||(Yk(t,n),e[r]=!0)}return Ce.isArray(s)?s.forEach(i):i(s),this}};Pn.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]),Ce.reduceDescriptors(Pn.prototype,({value:s},e)=>{let t=e[0].toUpperCase()+e.slice(1);return{get:()=>s,set(i){this[t]=i}}}),Ce.freezeMethods(Pn);function s1(s,e){const t=this||kh,i=e||t,n=Pn.from(i.headers);let r=i.data;return Ce.forEach(s,function(a){r=a.call(t,r,n.normalize(),e?e.status:void 0)}),n.normalize(),r}function PS(s){return!!(s&&s.__CANCEL__)}function Ql(s,e,t){xt.call(this,s??"canceled",xt.ERR_CANCELED,e,t),this.name="CanceledError"}Ce.inherits(Ql,xt,{__CANCEL__:!0});function RS(s,e,t){const i=t.config.validateStatus;!t.status||!i||i(t.status)?s(t):e(new xt("Request failed with status code "+t.status,[xt.ERR_BAD_REQUEST,xt.ERR_BAD_RESPONSE][Math.floor(t.status/100)-4],t.config,t.request,t))}function $k(s){const e=/^([-+\w]{1,25})(:?\/\/|:)/.exec(s);return e&&e[1]||""}function Kk(s,e){s=s||10;const t=new Array(s),i=new Array(s);let n=0,r=0,a;return e=e!==void 0?e:1e3,function(o){const l=Date.now(),c=i[r];a||(a=l),t[n]=o,i[n]=l;let h=r,d=0;for(;h!==n;)d+=t[h++],h=h%s;if(n=(n+1)%s,n===r&&(r=(r+1)%s),l-a{t=l,n=null,r&&(clearTimeout(r),r=null),s(...o)};return[(...o)=>{const l=Date.now(),c=l-t;c>=i?a(o,l):(n=o,r||(r=setTimeout(()=>{r=null,a(n)},i-c)))},()=>n&&a(n)]}const Ff=(s,e,t=3)=>{let i=0;const n=Kk(50,250);return Jk(r=>{const a=r.loaded,o=r.lengthComputable?r.total:void 0,l=a-i,c=n(l),h=a<=o;i=a;const d={loaded:a,total:o,progress:o?a/o:void 0,bytes:l,rate:c||void 0,estimated:c&&o&&h?(o-a)/c:void 0,event:r,lengthComputable:o!=null,[e?"download":"upload"]:!0};s(d)},t)},IS=(s,e)=>{const t=s!=null;return[i=>e[0]({lengthComputable:t,total:s,loaded:i}),e[1]]},LS=s=>(...e)=>Ce.asap(()=>s(...e)),Qk=ln.hasStandardBrowserEnv?((s,e)=>t=>(t=new URL(t,ln.origin),s.protocol===t.protocol&&s.host===t.host&&(e||s.port===t.port)))(new URL(ln.origin),ln.navigator&&/(msie|trident)/i.test(ln.navigator.userAgent)):()=>!0,eO=ln.hasStandardBrowserEnv?{write(s,e,t,i,n,r,a){if(typeof document>"u")return;const o=[`${s}=${encodeURIComponent(e)}`];Ce.isNumber(t)&&o.push(`expires=${new Date(t).toUTCString()}`),Ce.isString(i)&&o.push(`path=${i}`),Ce.isString(n)&&o.push(`domain=${n}`),r===!0&&o.push("secure"),Ce.isString(a)&&o.push(`SameSite=${a}`),document.cookie=o.join("; ")},read(s){if(typeof document>"u")return null;const e=document.cookie.match(new RegExp("(?:^|; )"+s+"=([^;]*)"));return e?decodeURIComponent(e[1]):null},remove(s){this.write(s,"",Date.now()-864e5,"/")}}:{write(){},read(){return null},remove(){}};function tO(s){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(s)}function iO(s,e){return e?s.replace(/\/?\/$/,"")+"/"+e.replace(/^\/+/,""):s}function DS(s,e,t){let i=!tO(e);return s&&(i||t==!1)?iO(s,e):e}const NS=s=>s instanceof Pn?{...s}:s;function bo(s,e){e=e||{};const t={};function i(c,h,d,p){return Ce.isPlainObject(c)&&Ce.isPlainObject(h)?Ce.merge.call({caseless:p},c,h):Ce.isPlainObject(h)?Ce.merge({},h):Ce.isArray(h)?h.slice():h}function n(c,h,d,p){if(Ce.isUndefined(h)){if(!Ce.isUndefined(c))return i(void 0,c,d,p)}else return i(c,h,d,p)}function r(c,h){if(!Ce.isUndefined(h))return i(void 0,h)}function a(c,h){if(Ce.isUndefined(h)){if(!Ce.isUndefined(c))return i(void 0,c)}else return i(void 0,h)}function o(c,h,d){if(d in e)return i(c,h);if(d in s)return i(void 0,c)}const l={url:r,method:r,data:r,baseURL:a,transformRequest:a,transformResponse:a,paramsSerializer:a,timeout:a,timeoutMessage:a,withCredentials:a,withXSRFToken:a,adapter:a,responseType:a,xsrfCookieName:a,xsrfHeaderName:a,onUploadProgress:a,onDownloadProgress:a,decompress:a,maxContentLength:a,maxBodyLength:a,beforeRedirect:a,transport:a,httpAgent:a,httpsAgent:a,cancelToken:a,socketPath:a,responseEncoding:a,validateStatus:o,headers:(c,h,d)=>n(NS(c),NS(h),d,!0)};return Ce.forEach(Object.keys({...s,...e}),function(c){const h=l[c]||n,d=h(s[c],e[c],c);Ce.isUndefined(d)&&h!==o||(t[c]=d)}),t}const kS=s=>{const e=bo({},s);let{data:t,withXSRFToken:i,xsrfHeaderName:n,xsrfCookieName:r,headers:a,auth:o}=e;if(e.headers=a=Pn.from(a),e.url=wS(DS(e.baseURL,e.url,e.allowAbsoluteUrls),s.params,s.paramsSerializer),o&&a.set("Authorization","Basic "+btoa((o.username||"")+":"+(o.password?unescape(encodeURIComponent(o.password)):""))),Ce.isFormData(t)){if(ln.hasStandardBrowserEnv||ln.hasStandardBrowserWebWorkerEnv)a.setContentType(void 0);else if(Ce.isFunction(t.getHeaders)){const l=t.getHeaders(),c=["content-type","content-length"];Object.entries(l).forEach(([h,d])=>{c.includes(h.toLowerCase())&&a.set(h,d)})}}if(ln.hasStandardBrowserEnv&&(i&&Ce.isFunction(i)&&(i=i(e)),i||i!==!1&&Qk(e.url))){const l=n&&r&&eO.read(r);l&&a.set(n,l)}return e},nO=typeof XMLHttpRequest<"u",sO=nO&&function(s){return new Promise(function(e,t){const i=kS(s);let n=i.data;const r=Pn.from(i.headers).normalize();let{responseType:a,onUploadProgress:o,onDownloadProgress:l}=i,c,h,d,p,u;function v(){p&&p(),u&&u(),i.cancelToken&&i.cancelToken.unsubscribe(c),i.signal&&i.signal.removeEventListener("abort",c)}let g=new XMLHttpRequest;g.open(i.method.toUpperCase(),i.url,!0),g.timeout=i.timeout;function m(){if(!g)return;const y=Pn.from("getAllResponseHeaders"in g&&g.getAllResponseHeaders()),x={data:!a||a==="text"||a==="json"?g.responseText:g.response,status:g.status,statusText:g.statusText,headers:y,config:s,request:g};RS(function(_){e(_),v()},function(_){t(_),v()},x),g=null}"onloadend"in g?g.onloadend=m:g.onreadystatechange=function(){!g||g.readyState!==4||g.status===0&&!(g.responseURL&&g.responseURL.indexOf("file:")===0)||setTimeout(m)},g.onabort=function(){g&&(t(new xt("Request aborted",xt.ECONNABORTED,s,g)),g=null)},g.onerror=function(y){const x=y&&y.message?y.message:"Network Error",_=new xt(x,xt.ERR_NETWORK,s,g);_.event=y||null,t(_),g=null},g.ontimeout=function(){let y=i.timeout?"timeout of "+i.timeout+"ms exceeded":"timeout exceeded";const x=i.transitional||TS;i.timeoutErrorMessage&&(y=i.timeoutErrorMessage),t(new xt(y,x.clarifyTimeoutError?xt.ETIMEDOUT:xt.ECONNABORTED,s,g)),g=null},n===void 0&&r.setContentType(null),"setRequestHeader"in g&&Ce.forEach(r.toJSON(),function(y,x){g.setRequestHeader(x,y)}),Ce.isUndefined(i.withCredentials)||(g.withCredentials=!!i.withCredentials),a&&a!=="json"&&(g.responseType=i.responseType),l&&([d,u]=Ff(l,!0),g.addEventListener("progress",d)),o&&g.upload&&([h,p]=Ff(o),g.upload.addEventListener("progress",h),g.upload.addEventListener("loadend",p)),(i.cancelToken||i.signal)&&(c=y=>{g&&(t(!y||y.type?new Ql(null,s,g):y),g.abort(),g=null)},i.cancelToken&&i.cancelToken.subscribe(c),i.signal&&(i.signal.aborted?c():i.signal.addEventListener("abort",c)));const f=$k(i.url);if(f&&ln.protocols.indexOf(f)===-1){t(new xt("Unsupported protocol "+f+":",xt.ERR_BAD_REQUEST,s));return}g.send(n||null)})},rO=(s,e)=>{const{length:t}=s=s?s.filter(Boolean):[];if(e||t){let i=new AbortController,n;const r=function(c){if(!n){n=!0,o();const h=c instanceof Error?c:this.reason;i.abort(h instanceof xt?h:new Ql(h instanceof Error?h.message:h))}};let a=e&&setTimeout(()=>{a=null,r(new xt(`timeout ${e} of ms exceeded`,xt.ETIMEDOUT))},e);const o=()=>{s&&(a&&clearTimeout(a),a=null,s.forEach(c=>{c.unsubscribe?c.unsubscribe(r):c.removeEventListener("abort",r)}),s=null)};s.forEach(c=>c.addEventListener("abort",r));const{signal:l}=i;return l.unsubscribe=()=>Ce.asap(o),l}},aO=function*(s,e){let t=s.byteLength;if(t{const n=oO(s,e);let r=0,a,o=l=>{a||(a=!0,i&&i(l))};return new ReadableStream({async pull(l){try{const{done:c,value:h}=await n.next();if(c){o(),l.close();return}let d=h.byteLength;if(t){let p=r+=d;t(p)}l.enqueue(new Uint8Array(h))}catch(c){throw o(c),c}},cancel(l){return o(l),n.return()}},{highWaterMark:2})},US=64*1024,{isFunction:zf}=Ce,cO=(({Request:s,Response:e})=>({Request:s,Response:e}))(Ce.global),{ReadableStream:BS,TextEncoder:FS}=Ce.global,zS=(s,...e)=>{try{return!!s(...e)}catch{return!1}},hO=s=>{s=Ce.merge.call({skipUndefined:!0},cO,s);const{fetch:e,Request:t,Response:i}=s,n=e?zf(e):typeof fetch=="function",r=zf(t),a=zf(i);if(!n)return!1;const o=n&&zf(BS),l=n&&(typeof FS=="function"?(v=>g=>v.encode(g))(new FS):async v=>new Uint8Array(await new t(v).arrayBuffer())),c=r&&o&&zS(()=>{let v=!1;const g=new t(ln.origin,{body:new BS,method:"POST",get duplex(){return v=!0,"half"}}).headers.has("Content-Type");return v&&!g}),h=a&&o&&zS(()=>Ce.isReadableStream(new i("").body)),d={stream:h&&(v=>v.body)};n&&["text","arrayBuffer","blob","formData","stream"].forEach(v=>{!d[v]&&(d[v]=(g,m)=>{let f=g&&g[v];if(f)return f.call(g);throw new xt(`Response type '${v}' is not supported`,xt.ERR_NOT_SUPPORT,m)})});const p=async v=>{if(v==null)return 0;if(Ce.isBlob(v))return v.size;if(Ce.isSpecCompliantForm(v))return(await new t(ln.origin,{method:"POST",body:v}).arrayBuffer()).byteLength;if(Ce.isArrayBufferView(v)||Ce.isArrayBuffer(v))return v.byteLength;if(Ce.isURLSearchParams(v)&&(v=v+""),Ce.isString(v))return(await l(v)).byteLength},u=async(v,g)=>Ce.toFiniteNumber(v.getContentLength())??p(g);return async v=>{let{url:g,method:m,data:f,signal:y,cancelToken:x,timeout:_,onDownloadProgress:S,onUploadProgress:b,responseType:E,headers:w,withCredentials:M="same-origin",fetchOptions:C}=kS(v),I=e||fetch;E=E?(E+"").toLowerCase():"text";let P=rO([y,x&&x.toAbortSignal()],_),k=null;const A=P&&P.unsubscribe&&(()=>{P.unsubscribe()});let B;try{if(b&&c&&m!=="get"&&m!=="head"&&(B=await u(w,f))!==0){let Y=new t(g,{method:"POST",body:f,duplex:"half"}),$;if(Ce.isFormData(f)&&($=Y.headers.get("content-type"))&&w.setContentType($),Y.body){const[_e,Te]=IS(B,Ff(LS(b)));f=OS(Y.body,US,_e,Te)}}Ce.isString(M)||(M=M?"include":"omit");const F=r&&"credentials"in t.prototype,H={...C,signal:P,method:m.toUpperCase(),headers:w.normalize().toJSON(),body:f,duplex:"half",credentials:F?M:void 0};k=r&&new t(g,H);let q=await(r?I(k,C):I(g,H));const G=h&&(E==="stream"||E==="response");if(h&&(S||G&&A)){const Y={};["status","statusText","headers"].forEach(be=>{Y[be]=q[be]});const $=Ce.toFiniteNumber(q.headers.get("content-length")),[_e,Te]=S&&IS($,Ff(LS(S),!0))||[];q=new i(OS(q.body,US,_e,()=>{Te&&Te(),A&&A()}),Y)}E=E||"text";let re=await d[Ce.findKey(d,E)||"text"](q,v);return!G&&A&&A(),await new Promise((Y,$)=>{RS(Y,$,{data:re,headers:Pn.from(q.headers),status:q.status,statusText:q.statusText,config:v,request:k})})}catch(F){throw A&&A(),F&&F.name==="TypeError"&&/Load failed|fetch/i.test(F.message)?Object.assign(new xt("Network Error",xt.ERR_NETWORK,v,k),{cause:F.cause||F}):xt.from(F,F&&F.code,v,k)}}},dO=new Map,HS=s=>{let e=s&&s.env||{};const{fetch:t,Request:i,Response:n}=e,r=[i,n,t];let a=r.length,o=a,l,c,h=dO;for(;o--;)l=r[o],c=h.get(l),c===void 0&&h.set(l,c=o?new Map:hO(e)),h=c;return c};HS();const r1={http:Ak,xhr:sO,fetch:{get:HS}};Ce.forEach(r1,(s,e)=>{if(s){try{Object.defineProperty(s,"name",{value:e})}catch{}Object.defineProperty(s,"adapterName",{value:e})}});const VS=s=>`- ${s}`,uO=s=>Ce.isFunction(s)||s===null||s===!1;function pO(s,e){s=Ce.isArray(s)?s:[s];const{length:t}=s;let i,n;const r={};for(let a=0;a`adapter ${l} `+(c===!1?"is not supported by the environment":"is not available in the build"));let o=t?a.length>1?`since : `+a.map(VS).join(` `):" "+VS(a[0]):"as no adapter specified";throw new xt("There is no suitable adapter to dispatch the request "+o,"ERR_NOT_SUPPORT")}return n}const GS={getAdapter:pO,adapters:r1};function a1(s){if(s.cancelToken&&s.cancelToken.throwIfRequested(),s.signal&&s.signal.aborted)throw new Ql(null,s)}function WS(s){return a1(s),s.headers=Pn.from(s.headers),s.data=s1.call(s,s.transformRequest),["post","put","patch"].indexOf(s.method)!==-1&&s.headers.setContentType("application/x-www-form-urlencoded",!1),GS.getAdapter(s.adapter||kh.adapter,s)(s).then(function(e){return a1(s),e.data=s1.call(s,s.transformResponse,e),e.headers=Pn.from(e.headers),e},function(e){return PS(e)||(a1(s),e&&e.response&&(e.response.data=s1.call(s,s.transformResponse,e.response),e.response.headers=Pn.from(e.response.headers))),Promise.reject(e)})}const XS="1.13.2",Hf={};["object","boolean","number","function","string","symbol"].forEach((s,e)=>{Hf[s]=function(t){return typeof t===s||"a"+(e<1?"n ":" ")+s}});const jS={};Hf.transitional=function(s,e,t){function i(n,r){return"[Axios v"+XS+"] Transitional option '"+n+"'"+r+(t?". "+t:"")}return(n,r,a)=>{if(s===!1)throw new xt(i(r," has been removed"+(e?" in "+e:"")),xt.ERR_DEPRECATED);return e&&!jS[r]&&(jS[r]=!0,console.warn(i(r," has been deprecated since v"+e+" and will be removed in the near future"))),s?s(n,r,a):!0}},Hf.spelling=function(s){return(e,t)=>(console.warn(`${t} is likely a misspelling of ${s}`),!0)};function fO(s,e,t){if(typeof s!="object")throw new xt("options must be an object",xt.ERR_BAD_OPTION_VALUE);const i=Object.keys(s);let n=i.length;for(;n-- >0;){const r=i[n],a=e[r];if(a){const o=s[r],l=o===void 0||a(o,r,s);if(l!==!0)throw new xt("option "+r+" must be "+l,xt.ERR_BAD_OPTION_VALUE);continue}if(t!==!0)throw new xt("Unknown option "+r,xt.ERR_BAD_OPTION)}}const Vf={assertOptions:fO,validators:Hf},Ws=Vf.validators;let Mo=class{constructor(s){this.defaults=s||{},this.interceptors={request:new ES,response:new ES}}async request(s,e){try{return await this._request(s,e)}catch(t){if(t instanceof Error){let i={};Error.captureStackTrace?Error.captureStackTrace(i):i=new Error;const n=i.stack?i.stack.replace(/^.+\n/,""):"";try{t.stack?n&&!String(t.stack).endsWith(n.replace(/^.+\n.+\n/,""))&&(t.stack+=` `+n):t.stack=n}catch{}}throw t}}_request(s,e){typeof s=="string"?(e=e||{},e.url=s):e=s||{},e=bo(this.defaults,e);const{transitional:t,paramsSerializer:i,headers:n}=e;t!==void 0&&Vf.assertOptions(t,{silentJSONParsing:Ws.transitional(Ws.boolean),forcedJSONParsing:Ws.transitional(Ws.boolean),clarifyTimeoutError:Ws.transitional(Ws.boolean)},!1),i!=null&&(Ce.isFunction(i)?e.paramsSerializer={serialize:i}:Vf.assertOptions(i,{encode:Ws.function,serialize:Ws.function},!0)),e.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?e.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:e.allowAbsoluteUrls=!0),Vf.assertOptions(e,{baseUrl:Ws.spelling("baseURL"),withXsrfToken:Ws.spelling("withXSRFToken")},!0),e.method=(e.method||this.defaults.method||"get").toLowerCase();let r=n&&Ce.merge(n.common,n[e.method]);n&&Ce.forEach(["delete","get","head","post","put","patch","common"],u=>{delete n[u]}),e.headers=Pn.concat(r,n);const a=[];let o=!0;this.interceptors.request.forEach(function(u){typeof u.runWhen=="function"&&u.runWhen(e)===!1||(o=o&&u.synchronous,a.unshift(u.fulfilled,u.rejected))});const l=[];this.interceptors.response.forEach(function(u){l.push(u.fulfilled,u.rejected)});let c,h=0,d;if(!o){const u=[WS.bind(this),void 0];for(u.unshift(...a),u.push(...l),d=u.length,c=Promise.resolve(e);h{if(!i._listeners)return;let r=i._listeners.length;for(;r-- >0;)i._listeners[r](n);i._listeners=null}),this.promise.then=n=>{let r;const a=new Promise(o=>{i.subscribe(o),r=o}).then(n);return a.cancel=function(){i.unsubscribe(r)},a},e(function(n,r,a){i.reason||(i.reason=new Ql(n,r,a),t(i.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(e){if(this.reason){e(this.reason);return}this._listeners?this._listeners.push(e):this._listeners=[e]}unsubscribe(e){if(!this._listeners)return;const t=this._listeners.indexOf(e);t!==-1&&this._listeners.splice(t,1)}toAbortSignal(){const e=new AbortController,t=i=>{e.abort(i)};return this.subscribe(t),e.signal.unsubscribe=()=>this.unsubscribe(t),e.signal}static source(){let e;return{token:new W2(function(t){e=t}),cancel:e}}};function gO(s){return function(e){return s.apply(null,e)}}function vO(s){return Ce.isObject(s)&&s.isAxiosError===!0}const o1={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511,WebServerIsDown:521,ConnectionTimedOut:522,OriginIsUnreachable:523,TimeoutOccurred:524,SslHandshakeFailed:525,InvalidSslCertificate:526};Object.entries(o1).forEach(([s,e])=>{o1[e]=s});function qS(s){const e=new Mo(s),t=cS(Mo.prototype.request,e);return Ce.extend(t,Mo.prototype,e,{allOwnKeys:!0}),Ce.extend(t,e,null,{allOwnKeys:!0}),t.create=function(i){return qS(bo(s,i))},t}const hi=qS(kh);hi.Axios=Mo,hi.CanceledError=Ql,hi.CancelToken=mO,hi.isCancel=PS,hi.VERSION=XS,hi.toFormData=Uf,hi.AxiosError=xt,hi.Cancel=hi.CanceledError,hi.all=function(s){return Promise.all(s)},hi.spread=gO,hi.isAxiosError=vO,hi.mergeConfig=bo,hi.AxiosHeaders=Pn,hi.formToJSON=s=>CS(Ce.isHTMLForm(s)?new FormData(s):s),hi.getAdapter=GS.getAdapter,hi.HttpStatusCode=o1,hi.default=hi;const{Axios:SH,AxiosError:wH,CanceledError:EH,isCancel:TH,CancelToken:CH,VERSION:AH,all:PH,Cancel:RH,isAxiosError:IH,spread:LH,toFormData:DH,AxiosHeaders:NH,HttpStatusCode:kH,formToJSON:OH,getAdapter:UH,mergeConfig:BH}=hi;function Uh(s,e,t){hi({method:"get",responseType:"blob",url:s}).then(n=>{let r=new window.File([n.data],"semantics",{type:"zip"});lS.loadAsync(r).then(a=>{for(let o in a.files){const l=a.file(a.files[o].name);l&&l.async("blob").then(c=>{i(c,"utf-8",function(h,d){e(d)})}).catch(()=>{t()})}}).catch(()=>{t()})}).catch(n=>{t()});function i(n,r,a){var o=new FileReader,l=new Blob([n]);o.onload=function(c){a(null,c.target.result)},o.onerror=function(c){a(c.error,null)},o.readAsText(l,r)}}function yO(s,e,t,i){let n=0,r=0,a=0,o=s.models.find(u=>u.url==t),l=e.circularMeps,c=e.rectMeps?.filter(u=>u.type==="风管"),h=e.rectMeps?.filter(u=>u.type==="桥架"),d=e.ellipseMeps,p=s.scene;if(new Dt,new at,l&&l.length){let u=[],v=0;for(let g of l)g.color=g.color.split(",").map(m=>parseInt(m)/255),g.color=new We(g.color[0],g.color[1],g.color[2]),g.position={x:g.startPoint.X*.3048+n,y:g.startPoint.Z*.3048+r,z:-g.startPoint.Y*.3048+a},g.rotation={x:0,y:0,z:0},g.indexes=[[s.scene.children.length,v++,0,0]],o.nodesMap.set(Number(g.id),g),u.push(g);Gf("Circle",p,u,t)}if(c&&c.length){let u=[],v=0;for(let g of c)g.color=g.color.split(",").map(m=>parseInt(m)/255),g.color=new We(g.color[0],g.color[1],g.color[2]),g.position={x:g.startPoint.X*.3048+n,y:g.startPoint.Z*.3048+r,z:-g.startPoint.Y*.3048+a},g.rotation={x:0,y:0,z:0},g.indexes=[[s.scene.children.length,v++,0,0]],o.nodesMap.set(Number(g.id),g),u.push(g);Gf("Rect",p,u,t)}if(d&&d.length){let u=[],v=0;for(let g of d)g.color=g.color.split(",").map(m=>parseInt(m)/255),g.color=new We(g.color[0],g.color[1],g.color[2]),g.position={x:g.startPoint.X*.3048+n,y:g.startPoint.Z*.3048+r,z:-g.startPoint.Y*.3048+a},g.rotation={x:0,y:0,z:0},g.indexes=[[s.scene.children.length,v++,0,0]],o.nodesMap.set(Number(g.id),g),u.push(g);Gf("Ellipse",p,u,t)}if(h&&h.length){let u=[],v=0;for(let g of h)g.color=g.color.split(",").map(m=>parseInt(m)/255),g.color=new We(g.color[0],g.color[1],g.color[2]),g.position={x:g.startPoint.X*.3048+n,y:g.startPoint.Z*.3048+r,z:-g.startPoint.Y*.3048+a},g.rotation={x:0,y:0,z:0},g.indexes=[[s.scene.children.length,v++,0,0]],o.nodesMap.set(Number(g.id),g),u.push(g);Gf("Bridge",p,u,t)}}function Gf(s,e,t,i,n){let r,a,o={width:1,height:1,length:1,diameter:1,color:new We,position:{x:0,y:0,z:0},rotation:{x:0,y:0,z:0}};switch(s){case"Rect":a=Wf("Rect",o);break;case"Bridge":a=Wf("Bridge",o);break;case"Circle":a=Wf("Circle",o);break;case"Ellipse":a=Wf("Ellipse",o);break}a&&(r=new ti(a.geometry,a.material,t.length),r.url=i,e.add(r),r.index=e.children.length-1);let l=[],c=[];for(var h=0;hu.endPoint.Z?1:-1)*Math.PI*.5,u.base_x!=null){var d=new R(u.base_x.X,0,-u.base_x.Y);x=(d.clone().cross(new R(0,0,1)).y<=0?1:-1)*d.angleTo(new R(0,0,1))+Math.PI*.5}}else x=(g.clone().sub(v.clone()).cross(new R(0,0,1)).y>0?-1:1)*g.clone().sub(v.clone()).angleTo(new R(0,0,1)),y=(u.startPoint.Z>u.endPoint.Z?1:-1)*g.clone().sub(v.clone()).angleTo(f.clone().sub(m.clone()));let S=new qe;const b=new Fi(y,x,_,"YXZ");let E=S.clone().makeRotationFromEuler(b),w,M;s==="Circle"?(w=u.diameter,M=u.diameter):(w=u.width,M=u.height);let C=S.clone().makeScale(w,M,u.length);S.multiplyMatrices(E,C),S.setPosition(u.position.x,u.position.y,u.position.z),r.setMatrixAt(h,S.clone()),r.setColorAt(h,u.color),r.geometry.computeBoundingBox();let I=r.geometry.boundingBox.min.clone().applyMatrix4(S.clone()),P=r.geometry.boundingBox.max.clone().applyMatrix4(S.clone()),k=new R(Math.min(I.x,P.x),Math.min(I.y,P.y),Math.min(I.z,P.z)),A=new R(Math.max(I.x,P.x),Math.max(I.y,P.y),Math.max(I.z,P.z)),B=k.clone().add(A.clone()).multiplyScalar(.5),F={name:u.name,min:k,max:A,center:B,dbid:h,materialName:a.material.name},H=null,q=null;s==="Circle"&&(H={x:u.startPoint.X*.3048,y:u.startPoint.Z*.3048,z:-u.startPoint.Y*.3048},q={x:u.endPoint.X*.3048,y:u.endPoint.Z*.3048,z:-u.endPoint.Y*.3048},F.minC=H,F.maxC=q),r.ids||(r.ids=[]),r.matrixs||(r.matrixs=[]),r.matrixs.push(S.clone()),c.push(S.clone()),r.ids.push(Number(u.id)),l.push(F)}r.castShadow=!0,r.ElementInfos=l,r.name="rootModel",r.TypeName="InstancedMesh-Pipe",r.PipeType=s,r.MeshId=null,r.realMaterial=r.material.clone(),r.originalMaterial=r.material.clone(),r.matrixsClone=c;let p=[];p={geometry:r.geometry,matrix:r.matrix,position:r.position,rotation:r.rotation},r.meshs=p,r.instanceMatrix&&r.instanceMatrix.array&&(r.cloneInstanceMatrix=Array.from(r.instanceMatrix.array))}function Wf(s,e,t){let i=new nr;switch(e.width=e.width*.3048,e.height=e.height*.3048,e.diameter=e.diameter*.3048,s){case"Rect":i.moveTo(-e.width/2,-e.height/2),i.lineTo(-e.width/2,e.height/2),i.lineTo(e.width/2,e.height/2),i.lineTo(e.width/2,-e.height/2),i.lineTo(-e.width/2,-e.height/2);break;case"Ellipse":i.moveTo(-e.width/2,-e.height/2),i.lineTo(-e.width/2,e.height/2),i.lineTo(e.width/2,e.height/2),i.lineTo(e.width/2,-e.height/2),i.lineTo(-e.width/2,-e.height/2);break;case"Bridge":i.moveTo(-e.width/2,-e.height/2),i.lineTo(-e.width/2,e.height/2),i.lineTo(-e.width/2+.01,e.height/2),i.lineTo(-e.width/2+.01,-e.height/2+.01),i.lineTo(e.width/2-.01,-e.height/2+.01),i.lineTo(e.width/2-.01,e.height/2),i.lineTo(e.width/2,e.height/2),i.lineTo(e.width/2,-e.height/2),i.lineTo(-e.width/2,-e.height/2);break;case"Circle":i.moveTo(0,0),i.absarc(0,0,e.diameter*.5,0,Math.PI*2,!1);break}const n={depth:e.length*.3048,bevelEnabled:!1};return r(i,n,e.color,e.position,e.rotation);function r(a,o,l,c,h){let d=new ml(a,o),p=new sr({color:l,side:Ot}),u=new ht(d,p);return u.position.set(c.x,c.y,c.z),u.rotation._order="YXZ",u.rotation.set(h.x,h.y,h.z),u}}function So(s,e=!1){const t=s[0].index!==null,i=new Set(Object.keys(s[0].attributes)),n=new Set(Object.keys(s[0].morphAttributes)),r={},a={},o=s[0].morphTargetsRelative,l=new at;let c=0;for(let h=0;h=2.0 are supported."));return}const c=new JO(r,{path:t||this.resourcePath||"",crossOrigin:this.crossOrigin,requestHeader:this.requestHeader,manager:this.manager,ktx2Loader:this.ktx2Loader,meshoptDecoder:this.meshoptDecoder});c.fileLoader.setRequestHeader(this.requestHeader);for(let h=0;h=0&&o[d]===void 0&&console.warn('THREE.GLTFLoader: Unknown extension "'+d+'".')}}c.setExtensions(a),c.setPlugins(o),c.parse(i,n)}parseAsync(e,t){const i=this;return new Promise(function(n,r){i.parse(e,t,n,r)})}}function bO(){let s={};return{get:function(e){return s[e]},add:function(e,t){s[e]=t},remove:function(e){delete s[e]},removeAll:function(){s={}}}}function yi(s,e,t){const i=s.json.materials[e];return i.extensions&&i.extensions[t]?i.extensions[t]:null}const Tt={KHR_BINARY_GLTF:"KHR_binary_glTF",KHR_DRACO_MESH_COMPRESSION:"KHR_draco_mesh_compression",KHR_LIGHTS_PUNCTUAL:"KHR_lights_punctual",KHR_MATERIALS_CLEARCOAT:"KHR_materials_clearcoat",KHR_MATERIALS_DISPERSION:"KHR_materials_dispersion",KHR_MATERIALS_IOR:"KHR_materials_ior",KHR_MATERIALS_SHEEN:"KHR_materials_sheen",KHR_MATERIALS_SPECULAR:"KHR_materials_specular",KHR_MATERIALS_TRANSMISSION:"KHR_materials_transmission",KHR_MATERIALS_IRIDESCENCE:"KHR_materials_iridescence",KHR_MATERIALS_ANISOTROPY:"KHR_materials_anisotropy",KHR_MATERIALS_UNLIT:"KHR_materials_unlit",KHR_MATERIALS_VOLUME:"KHR_materials_volume",KHR_TEXTURE_BASISU:"KHR_texture_basisu",KHR_TEXTURE_TRANSFORM:"KHR_texture_transform",KHR_MESH_QUANTIZATION:"KHR_mesh_quantization",KHR_MATERIALS_EMISSIVE_STRENGTH:"KHR_materials_emissive_strength",EXT_MATERIALS_BUMP:"EXT_materials_bump",EXT_TEXTURE_WEBP:"EXT_texture_webp",EXT_TEXTURE_AVIF:"EXT_texture_avif",EXT_MESHOPT_COMPRESSION:"EXT_meshopt_compression",KHR_MESHOPT_COMPRESSION:"KHR_meshopt_compression",EXT_MESH_GPU_INSTANCING:"EXT_mesh_gpu_instancing"};class MO{constructor(e){this.parser=e,this.name=Tt.KHR_LIGHTS_PUNCTUAL,this.cache={refs:{},uses:{}}}_markDefs(){const e=this.parser,t=this.parser.json.nodes||[];for(let i=0,n=t.length;i=0)throw new Error("THREE.GLTFLoader: setKTX2Loader must be called before loading KTX2 textures");return null}return t.loadTextureImage(e,r.source,a)}}class OO{constructor(e){this.parser=e,this.name=Tt.EXT_TEXTURE_WEBP}loadTexture(e){const t=this.name,i=this.parser,n=i.json,r=n.textures[e];if(!r.extensions||!r.extensions[t])return null;const a=r.extensions[t],o=n.images[a.source];let l=i.textureLoader;if(o.uri){const c=i.options.manager.getHandler(o.uri);c!==null&&(l=c)}return i.loadTextureImage(e,a.source,l)}}class UO{constructor(e){this.parser=e,this.name=Tt.EXT_TEXTURE_AVIF}loadTexture(e){const t=this.name,i=this.parser,n=i.json,r=n.textures[e];if(!r.extensions||!r.extensions[t])return null;const a=r.extensions[t],o=n.images[a.source];let l=i.textureLoader;if(o.uri){const c=i.options.manager.getHandler(o.uri);c!==null&&(l=c)}return i.loadTextureImage(e,a.source,l)}}class KS{constructor(e,t){this.name=t,this.parser=e}loadBufferView(e){const t=this.parser.json,i=t.bufferViews[e];if(i.extensions&&i.extensions[this.name]){const n=i.extensions[this.name],r=this.parser.getDependency("buffer",n.buffer),a=this.parser.options.meshoptDecoder;if(!a||!a.supported){if(t.extensionsRequired&&t.extensionsRequired.indexOf(this.name)>=0)throw new Error("THREE.GLTFLoader: setMeshoptDecoder must be called before loading compressed files");return null}return r.then(function(o){const l=n.byteOffset||0,c=n.byteLength||0,h=n.count,d=n.byteStride,p=new Uint8Array(o,l,c);return a.decodeGltfBufferAsync?a.decodeGltfBufferAsync(h,d,p,n.mode,n.filter).then(function(u){return u.buffer}):a.ready.then(function(){const u=new ArrayBuffer(h*d);return a.decodeGltfBuffer(new Uint8Array(u),h,d,p,n.mode,n.filter),u})})}else return null}}class BO{constructor(e){this.name=Tt.EXT_MESH_GPU_INSTANCING,this.parser=e}createNodeMesh(e){const t=this.parser.json,i=t.nodes[e];if(!i.extensions||!i.extensions[this.name]||i.mesh===void 0)return null;const n=t.meshes[i.mesh];for(const l of n.primitives)if(l.mode!==ns.TRIANGLES&&l.mode!==ns.TRIANGLE_STRIP&&l.mode!==ns.TRIANGLE_FAN&&l.mode!==void 0)return null;const r=i.extensions[this.name].attributes,a=[],o={};for(const l in r)a.push(this.parser.getDependency("accessor",r[l]).then(c=>(o[l]=c,o[l])));return a.length<1?null:(a.push(this.parser.createNodeMesh(e)),Promise.all(a).then(l=>{const c=l.pop(),h=c.isGroup?c.children:[c],d=l[0].count,p=[];for(const u of h){const v=new qe,g=new R,m=new Kt,f=new R(1,1,1),y=new ti(u.geometry,u.material,d);for(let x=0;x0||s.search(/^data\:image\/jpeg/)===0?"image/jpeg":s.search(/\.webp($|\?)/i)>0||s.search(/^data\:image\/webp/)===0?"image/webp":s.search(/\.ktx2($|\?)/i)>0||s.search(/^data\:image\/ktx2/)===0?"image/ktx2":"image/png"}const KO=new qe;class JO{constructor(e={},t={}){this.json=e,this.extensions={},this.plugins={},this.options=t,this.cache=new bO,this.associations=new Map,this.primitiveCache={},this.nodeCache={},this.meshCache={refs:{},uses:{}},this.cameraCache={refs:{},uses:{}},this.lightCache={refs:{},uses:{}},this.sourceCache={},this.textureCache={},this.nodeNamesUsed={};let i=!1,n=-1,r=!1,a=-1;if(typeof navigator<"u"&&typeof navigator.userAgent<"u"){const o=navigator.userAgent;i=/^((?!chrome|android).)*safari/i.test(o)===!0;const l=o.match(/Version\/(\d+)/);n=i&&l?parseInt(l[1],10):-1,r=o.indexOf("Firefox")>-1,a=r?o.match(/Firefox\/([0-9]+)\./)[1]:-1}typeof createImageBitmap>"u"||i&&n<17||r&&a<98?this.textureLoader=new qa(this.options.manager):this.textureLoader=new R_(this.options.manager),this.textureLoader.setCrossOrigin(this.options.crossOrigin),this.textureLoader.setRequestHeader(this.options.requestHeader),this.fileLoader=new Jn(this.options.manager),this.fileLoader.setResponseType("arraybuffer"),this.options.crossOrigin==="use-credentials"&&this.fileLoader.setWithCredentials(!0)}setExtensions(e){this.extensions=e}setPlugins(e){this.plugins=e}parse(e,t){const i=this,n=this.json,r=this.extensions;this.cache.removeAll(),this.nodeCache={},this._invokeAll(function(a){return a._markDefs&&a._markDefs()}),Promise.all(this._invokeAll(function(a){return a.beforeRoot&&a.beforeRoot()})).then(function(){return Promise.all([i.getDependencies("scene"),i.getDependencies("animation"),i.getDependencies("camera")])}).then(function(a){const o={scene:a[0][n.scene||0],scenes:a[0],animations:a[1],cameras:a[2],asset:n.asset,parser:i,userData:{}};return wo(r,o,n),Xs(o,n),Promise.all(i._invokeAll(function(l){return l.afterRoot&&l.afterRoot(o)})).then(function(){for(const l of o.scenes)l.updateMatrixWorld();e(o)})}).catch(t)}_markDefs(){const e=this.json.nodes||[],t=this.json.skins||[],i=this.json.meshes||[];for(let n=0,r=t.length;n{const l=this.associations.get(a);l!=null&&this.associations.set(o,l);for(const[c,h]of a.children.entries())r(h,o.children[c])};return r(i,n),n.name+="_instance_"+e.uses[t]++,n}_invokeOne(e){const t=Object.values(this.plugins);t.push(this);for(let i=0;i=2&&m.setY(M,b[E*l+1]),l>=3&&m.setZ(M,b[E*l+2]),l>=4&&m.setW(M,b[E*l+3]),l>=5)throw new Error("THREE.GLTFLoader: Unsupported itemSize in sparse BufferAttribute.")}m.normalized=v}return m})}loadTexture(e){const t=this.json,i=this.options,n=t.textures[e].source,r=t.images[n];let a=this.textureLoader;if(r.uri){const o=i.manager.getHandler(r.uri);o!==null&&(a=o)}return this.loadTextureImage(e,n,a)}loadTextureImage(e,t,i){const n=this,r=this.json,a=r.textures[e],o=r.images[t],l=(o.uri||o.bufferView)+":"+a.sampler;if(this.textureCache[l])return this.textureCache[l];const c=this.loadImageSource(t,i).then(function(h){h.flipY=!1,h.name=a.name||o.name||"",h.name===""&&typeof o.uri=="string"&&o.uri.startsWith("data:image/")===!1&&(h.name=o.uri);const d=(r.samplers||{})[a.sampler]||{};return h.magFilter=tw[d.magFilter]||At,h.minFilter=tw[d.minFilter]||qn,h.wrapS=iw[d.wrapS]||Ji,h.wrapT=iw[d.wrapT]||Ji,h.generateMipmaps=!h.isCompressedTexture&&h.minFilter!==Zt&&h.minFilter!==At,n.associations.set(h,{textures:e}),h}).catch(function(){return null});return this.textureCache[l]=c,c}loadImageSource(e,t){const i=this,n=this.json,r=this.options;if(this.sourceCache[e]!==void 0)return this.sourceCache[e].then(d=>d.clone());const a=n.images[e],o=self.URL||self.webkitURL;let l=a.uri||"",c=!1;if(a.bufferView!==void 0)l=i.getDependency("bufferView",a.bufferView).then(function(d){c=!0;const p=new Blob([d],{type:a.mimeType});return l=o.createObjectURL(p),l});else if(a.uri===void 0)throw new Error("THREE.GLTFLoader: Image "+e+" is missing URI and bufferView");const h=Promise.resolve(l).then(function(d){return new Promise(function(p,u){let v=p;t.isImageBitmapLoader===!0&&(v=function(g){const m=new ei(g);m.needsUpdate=!0,p(m)}),t.load(Yr.resolveURL(d,r.path),v,void 0,u)})}).then(function(d){return c===!0&&o.revokeObjectURL(l),Xs(d,a),d.userData.mimeType=a.mimeType||$O(a.uri),d}).catch(function(d){throw console.error("THREE.GLTFLoader: Couldn't load texture",l),d});return this.sourceCache[e]=h,h}assignTexture(e,t,i,n){const r=this;return this.getDependency("texture",i.index).then(function(a){if(!a)return null;if(i.texCoord!==void 0&&i.texCoord>0&&(a=a.clone(),a.channel=i.texCoord),r.extensions[Tt.KHR_TEXTURE_TRANSFORM]){const o=i.extensions!==void 0?i.extensions[Tt.KHR_TEXTURE_TRANSFORM]:void 0;if(o){const l=r.associations.get(a);a=r.extensions[Tt.KHR_TEXTURE_TRANSFORM].extendTexture(a,o),r.associations.set(a,l)}}return n!==void 0&&(a.colorSpace=n),e[t]=a,a})}assignFinalMaterial(e){const t=e.geometry;let i=e.material;const n=t.attributes.tangent===void 0,r=t.attributes.color!==void 0,a=t.attributes.normal===void 0;if(e.isPoints){const o="PointsMaterial:"+i.uuid;let l=this.cache.get(o);l||(l=new Ju,Ri.prototype.copy.call(l,i),l.color.copy(i.color),l.map=i.map,l.sizeAttenuation=!1,this.cache.add(o,l)),i=l}else if(e.isLine){const o="LineBasicMaterial:"+i.uuid;let l=this.cache.get(o);l||(l=new si,Ri.prototype.copy.call(l,i),l.color.copy(i.color),l.map=i.map,this.cache.add(o,l)),i=l}if(n||r||a){let o="ClonedMaterial:"+i.uuid+":";n&&(o+="derivative-tangents:"),r&&(o+="vertex-colors:"),a&&(o+="flat-shading:");let l=this.cache.get(o);l||(l=i.clone(),r&&(l.vertexColors=!0),a&&(l.flatShading=!0),n&&(l.normalScale&&(l.normalScale.y*=-1),l.clearcoatNormalScale&&(l.clearcoatNormalScale.y*=-1)),this.cache.add(o,l),this.associations.set(l,this.associations.get(i))),i=l}e.material=i}getMaterialType(){return sr}loadMaterial(e){const t=this,i=this.json,n=this.extensions,r=i.materials[e];let a;const o={},l=r.extensions||{},c=[];if(l[Tt.KHR_MATERIALS_UNLIT]){const d=n[Tt.KHR_MATERIALS_UNLIT];a=d.getMaterialType(),c.push(d.extendParams(o,r,t))}else{const d=r.pbrMetallicRoughness||{};if(o.color=new We(1,1,1),o.opacity=1,Array.isArray(d.baseColorFactor)){const p=d.baseColorFactor;o.color.setRGB(p[0],p[1],p[2],Zi),o.opacity=p[3]}d.baseColorTexture!==void 0&&c.push(t.assignTexture(o,"map",d.baseColorTexture,li)),o.metalness=d.metallicFactor!==void 0?d.metallicFactor:1,o.roughness=d.roughnessFactor!==void 0?d.roughnessFactor:1,d.metallicRoughnessTexture!==void 0&&(c.push(t.assignTexture(o,"metalnessMap",d.metallicRoughnessTexture)),c.push(t.assignTexture(o,"roughnessMap",d.metallicRoughnessTexture))),a=this._invokeOne(function(p){return p.getMaterialType&&p.getMaterialType(e)}),c.push(Promise.all(this._invokeAll(function(p){return p.extendMaterialParams&&p.extendMaterialParams(e,o)})))}r.doubleSided===!0&&(o.side=Ot);const h=r.alphaMode||h1.OPAQUE;if(h===h1.BLEND?(o.transparent=!0,o.depthWrite=!1):(o.transparent=!1,h===h1.MASK&&(o.alphaTest=r.alphaCutoff!==void 0?r.alphaCutoff:.5)),r.normalTexture!==void 0&&a!==Dt&&(c.push(t.assignTexture(o,"normalMap",r.normalTexture)),o.normalScale=new me(1,1),r.normalTexture.scale!==void 0)){const d=r.normalTexture.scale;o.normalScale.set(d,d)}if(r.occlusionTexture!==void 0&&a!==Dt&&(c.push(t.assignTexture(o,"aoMap",r.occlusionTexture)),r.occlusionTexture.strength!==void 0&&(o.aoMapIntensity=r.occlusionTexture.strength)),r.emissiveFactor!==void 0&&a!==Dt){const d=r.emissiveFactor;o.emissive=new We().setRGB(d[0],d[1],d[2],Zi)}return r.emissiveTexture!==void 0&&a!==Dt&&c.push(t.assignTexture(o,"emissiveMap",r.emissiveTexture,li)),Promise.all(c).then(function(){const d=new a(o);return r.name&&(d.name=r.name),Xs(d,r),t.associations.set(d,{materials:e}),r.extensions&&wo(n,d,r),d})}createUniqueName(e){const t=Nt.sanitizeNodeName(e||"");return t in this.nodeNamesUsed?t+"_"+ ++this.nodeNamesUsed[t]:(this.nodeNamesUsed[t]=0,t)}loadGeometries(e){const t=this,i=this.extensions,n=this.primitiveCache;function r(o){return i[Tt.KHR_DRACO_MESH_COMPRESSION].decodePrimitive(o,t).then(function(l){return nw(l,o,t)})}const a=[];for(let o=0,l=e.length;o0&&ZO(f,r),f.name=t.createUniqueName(r.name||"mesh_"+e),Xs(f,r),m.extensions&&wo(n,f,m),t.assignFinalMaterial(f),d.push(f)}for(let u=0,v=d.length;u0){const u=h.userData.pivot,v=d[0];h.pivot=new R().fromArray(u),h.position.x-=u[0],h.position.y-=u[1],h.position.z-=u[2],v.position.set(0,0,0),delete h.userData.pivot}return h})}_loadNodeShallow(e){const t=this.json,i=this.extensions,n=this;if(this.nodeCache[e]!==void 0)return this.nodeCache[e];const r=t.nodes[e],a=r.name?n.createUniqueName(r.name):"",o=[],l=n._invokeOne(function(c){return c.createNodeMesh&&c.createNodeMesh(e)});return l&&o.push(l),r.camera!==void 0&&o.push(n.getDependency("camera",r.camera).then(function(c){return n._getNodeRef(n.cameraCache,r.camera,c)})),n._invokeAll(function(c){return c.createNodeAttachment&&c.createNodeAttachment(e)}).forEach(function(c){o.push(c)}),this.nodeCache[e]=Promise.all(o).then(function(c){let h;if(r.isBone===!0?h=new Vu:c.length>1?h=new pi:c.length===1?h=c[0]:h=new Rt,h!==c[0])for(let d=0,p=c.length;d1){const d=n.associations.get(h);n.associations.set(h,{...d})}return n.associations.get(h).nodes=e,h}),this.nodeCache[e]}loadScene(e){const t=this.extensions,i=this.json.scenes[e],n=this,r=new pi;i.name&&(r.name=n.createUniqueName(i.name)),Xs(r,i),i.extensions&&wo(t,r,i);const a=i.nodes||[],o=[];for(let l=0,c=a.length;l{const d=new Map;for(const[p,u]of n.associations)(p instanceof Ri||p instanceof ei)&&d.set(p,u);return h.traverse(p=>{const u=n.associations.get(p);u!=null&&d.set(p,u)}),d};return n.associations=c(r),r})}_createAnimationTracks(e,t,i,n,r){const a=[],o=e.name?e.name:e.uuid,l=[];da[r.path]===da.weights?e.traverse(function(p){p.morphTargetInfluences&&l.push(p.name?p.name:p.uuid)}):l.push(o);let c;switch(da[r.path]){case da.weights:c=Ga;break;case da.rotation:c=Wa;break;case da.translation:case da.scale:c=ja;break;default:i.itemSize===1?c=Ga:c=ja;break}const h=n.interpolation!==void 0?XO[n.interpolation]:Zo,d=this._getArrayFromAccessor(i);for(let p=0,u=l.length;p(s.ModelLoadStart="model-load-start",s.ModelLoadProgress="model-load-progress",s.ModelLoaded="model-loaded",s.ModelError="model-error",s.SelectionChanged="selection-changed",s.HoverChanged="hover-changed",s.Click="click",s.MouseMove="mouse-move",s.CameraChanged="camera-changed",s.CameraIdle="camera-idle",s.EngineFree="engine-free",s.EngineBusy="engine-busy",s.MeasureChanged="measure-changed",s.MeasureClick="measure-click",s.SectionMove="section-move",s.LoadingCompleted="loading_completed",s))(di||{});const eU=8,sw=24,tU=24,iU=64,nU=60;function sU(){return new URL("draco/",document.baseURI).toString()}function rw(){return new Promise(s=>{if(typeof requestAnimationFrame=="function"){requestAnimationFrame(()=>s());return}setTimeout(s,16)})}function rU(){const s=navigator?.scheduling;return typeof s?.isInputPending=="function"?s.isInputPending():!1}function aU(s){return s?.engineStatus?.isFree===!1||rU()}async function br(s,e,t){if(e)return t;const i=performance.now();return aU(s)||i-t>=eU?(await rw(),performance.now()):t}function oU(s){return new Promise((e,t)=>{Uh(s,i=>{if(i==null){t(new Error(`[loadLightModel] empty zip json: ${s}`));return}e(i)},()=>{t(new Error(`[loadLightModel] failed to load zip json: ${s}`))})})}function lU(s){return hi({method:"get",responseType:"arraybuffer",url:s}).then(e=>lS.loadAsync(e.data))}function aw(s){return s.replace(/\\/g,"/").replace(/^\/+/,"")}function ow(s,e){const t=new Set(e.map(i=>aw(i)));for(const i of Object.keys(s.files))if(t.has(aw(i)))return s.files[i];return null}function lw(s,e){const t=ow(s,e);return t==null||t.dir?Promise.resolve(null):t.async("string")}function cU(s){return s.charCodeAt(0)===65279?s.slice(1):s}function p1(s){return JSON.parse(cU(s))}function hU(s,e){const t=ow(s,e);return t==null||t.dir?Promise.resolve(null):t.async("arraybuffer")}function dU(s){return new Promise((e,t)=>{new _O().parse(s,document.baseURI,e,t)})}function Xf(s,e){return s.models.find(t=>t.url==e)}function cw(s){s.loadStatus==null&&(s.loadStatus={}),s.loadStatus.modelMep==null&&(s.loadStatus.modelMep=!1),s.loadStatus.normal==null&&(s.loadStatus.normal=!1)}function uU(s){return cw(s),s.status==="loaded"&&s.loadStatus.normal===!0&&s.loadStatus.modelMep===!0}function hw(s){const e=s?.engineStatus?.models;!Array.isArray(e)||e.length===0||!e.every(t=>uU(t))||s.__loadingCompletedTriggered===!0||(s.__loadingCompletedTriggered=!0,s.events?.trigger?.(di.LoadingCompleted,{}))}function dw(s){return s===!0||s==="loading"}function uw(s){return s.index!=null?s.index.count:s.attributes.position?.count??0}async function pU(s,e,t){let i=performance.now();for(let n=0;n0;){const a=n.pop();if(a==null||a.node==null||a.node.status===!0)continue;const o=a.node;if(a.visited){const c=Array.isArray(o.children)?o.children:[];(c.length===0||c.findIndex(h=>h.status!=!0)===-1)&&(o.status=!0),r=await br(s,t,r);continue}n.push({node:o,visited:!0}),Array.isArray(o.elements)&&i.push(...o.elements);const l=Array.isArray(o.children)?o.children:[];for(let c=l.length-1;c>=0;c--)n.push({node:l[c],visited:!1});r=await br(s,t,r)}return i}async function mU(s,e,t,i){const n=Xf(s,e.url);if(n?.nodesMap==null)return[];const r=await fU(s,t,i);console.log("[loadLightModel] pending mesh ids",t.path,r.length);const a=[];let o=performance.now(),l=0;for(const c of r){if(!n.nodesMap.has(c))continue;const h=n.nodesMap.get(c),d=Array.isArray(h?.infos)?h.infos:[];for(const p of d){const u=t.glbs?.[p.glb]?.[p.mesh];if(u?.geometry==null||u.material==null)continue;const v=new qe;v.elements=p.matrix;const g=u.geometry.clone();g.applyMatrix4(v),g.computeBoundingBox();const m=new ht(g,u.material);p.box=g.boundingBox?.clone(),p.mesh=m,m.name=Number(c),m.glb=p.glb,m.url=e.url,g.attributes.position!=null&&a.push(m),l++,l%sw===0&&(o=await br(s,i,o))}}return a}function gU(s,e,t,i,n){const r=So(i.map(o=>o.geometry),!1),a=new ht(r,n);return a.castShadow=!0,a.receiveShadow=!0,e.scene.add(a),a.index=e.scene.children.length-1,a.url=s,a.glb=t,a.materialClone=n,a.geometrys=i.map(o=>o.geometry),a.geometry.computeVertexNormals(),a}function vU(s,e,t,i){return s.scene.children.find(n=>{const r=n;return n instanceof ht&&r.url==e&&r.glb==t&&r.materialClone===i})}function yU(s,e){const t=Array.isArray(s.geometrys)?s.geometrys:[],i=e.map(a=>a.geometry),n=[...t,...i],r=So(n,!1);s.geometry!=null&&s.geometry.dispose(),s.geometry=r,s.geometrys=n,s.castShadow=!0,s.receiveShadow=!0}async function xU(s,e,t,i){const n=new Map;for(const o of t){const l=n.get(o.glb)??[];l.push(o),n.set(o.glb,l)}const r=Xf(e,s);let a=performance.now();for(const[o,l]of n.entries()){const c=i?l.length:nU;for(let h=0;h{const _=Number(y.name),S=uw(y.geometry),b=m.get(_)??[];if(b.push([f,f+S]),m.set(_,b),r?.nodesMap?.has(_)){const E=r.nodesMap.get(_);E.indexes==null&&(E.indexes=[]),E.indexes.push([u.index,v+x,f,f+S])}f+=S}),u.indexes==null&&(u.indexes=new Map),m.forEach((y,x)=>{const _=u.indexes.get(x)??[];_.push(...y),u.indexes.set(x,_)}),a=await br(e,i,a)}}}async function _U(s,e,t,i,n,r){if(i==null||n==null||n.length===0)return;const a=Xf(t,s);if(a==null)return;const o=new ti(i.geometry,i.material,n.length);t.scene.add(o);const l=new Float32Array(n.length*3);for(let d=0;dd.id),o.matrixsClone=h,o.meshIndex=e}async function bU(s,e,t,i){const n=e.instanceNodes;if(n==null)return;let r=performance.now();for(const a in n)if(n[a].isLoaded!==!0){n[a].isLoaded=!0;for(const o of n[a]){const l=e.glbs?.[a]?.[o.mesh];l!=null&&await _U(s.url,o.mesh,t,l,o.children,i)}r=await br(t,i,r)}}async function MU(s,e,t,i){if(t.status===!0||t.meshPromise!=null){await t.meshPromise;return}t.meshPromise=(async()=>{console.log(`[loadLightModel] start build lod meshes ${Date.now()-window.startTime}ms`);const n=await mU(s,e,t,i);await xU(e.url,s,n,i),await bU(e,t,s,i),t.status=!0,console.log(`[loadLightModel] *****************************************************finish build lod meshes ${Date.now()-window.startTime}ms`)})().finally(()=>{t.meshPromise=null}),await t.meshPromise}async function SU(s,e,t,i){if(t.loadSuccess!==!0){if(t.preparePromise!=null){await t.preparePromise;return}t.preparePromise=(async()=>{console.log("[loadLightModel] loading GLB bundle",t.path),t.glbs=t.glbs??{};const n=await lU(e.url+t.path),r=await lw(n,["/nodes.json","nodes.json"]);if(r==null)return;const a=p1(r),o=Xf(s,e.url);if(o==null)return;o.nodesMap==null&&(o.nodesMap=new Map);let l=performance.now();for(const h of Object.keys(a)){const d=a[h];for(let u=0;u{t.preparePromise=null}),await t.preparePromise}}function wU(s,e,t){if(t.boundingBox||(t.boundingBox=new vt,t.boundingBox.min=new R(t.octreeBox.min.X,t.octreeBox.min.Z,-t.octreeBox.min.Y),t.boundingBox.max=new R(t.octreeBox.max.X,t.octreeBox.max.Z,-t.octreeBox.max.Y)),!t.maxSize)return 1e3;const i=t.boundingBox,n=i.min,r=i.max,a=n.clone().add(r.clone()).multiplyScalar(.5),o=n.distanceTo(r),l=new R,c=new R;e.getWorldDirection(c),s.camera.matrixWorld.extractBasis(l,c,new R);const h=a.clone().add(c.setLength(-o)),d=h.clone().add(l.setLength(t.maxSize)),p=new zt(s.camera,s.renderer,s.scene).worldToScreen(h),u=new zt(s.camera,s.renderer,s.scene).worldToScreen(d);return p.distanceTo(u)}async function EU(s,e,t,i){t.maxSize<1e6&&t.path!="/lod0"&&(!(wU(s,s.camera,t)>=20)||t.status===!0)||(await SU(s,e,t,i),t.loadSuccess===!0&&await MU(s,e,t,i))}function TU(s,e,t){dw(e.loadStatus.modelMep)||(e.loadStatus.modelMep="loading",e.info.modelMep==null&&(e.info.modelMep={}),(async()=>{t||await rw(),yO(s,e.info.modelMep,e.url),e.loadStatus.modelMep=!0,hw(s)})().catch(i=>{e.loadStatus.modelMep=!1,console.error("[loadLightModel] failed to load mep model",i)}))}function CU(s,e,t,i){const n=new pi;n.name=e,s.scene.add(n),s.models||(s.models=[]),window.startTime=Date.now(),oU(e+"/info").then(r=>{const a=p1(r);s.__loadingCompletedTriggered=!1,s.engineStatus.models.push({type:"light",info:a,name:a.baseInfo.name,status:"loading",url:e,elements:new Map,loadStatus:{modelMep:!1,normal:!1}}),s.models.push({url:e,nodesMap:new Map,grids:a.modelGrid,levels:a.modelLevel,rooms:a.modelRoom,views:a.modelView,boundingBox:{min:new R(a.baseInfo.min.X*.3048,a.baseInfo.min.Z*.3048,-a.baseInfo.min.Y*.3048),max:new R(a.baseInfo.max.X*.3048,a.baseInfo.max.Z*.3048,-a.baseInfo.max.Y*.3048)}}),s.models.length==i&&(s.viewCube.CameraGoHome(1),setTimeout(()=>{pw(s,null,!1)},100))}).catch(r=>{console.error("[loadLightModel] failed to load model info",{url:e,error:r})})}async function pw(s,e,t=!1){const i=s.engineStatus.models.filter(n=>e==null||n.url==e);for(const n of i)if(cw(n),!(n.status!=="loading"||n.type!=="light")&&(TU(s,n,t),!dw(n.loadStatus.normal))){n.loadStatus.normal="loading";try{await AU(s,n,t)}finally{const r=Array.isArray(n.info?.lods)&&n.info.lods.every(a=>a.status===!0);n.loadStatus.normal=r,r&&(n.status="loaded"),hw(s)}}}async function AU(s,e,t=!1){if(console.log(`[loadLightModel] start loadNode ${Date.now()-window.startTime}ms`),!(e.info==null||e.info.lods==null))for(const i of e.info.lods)await EU(s,e,i,t)}function PU(s,e){return s.map!=null&&(s.map.colorSpace=li,s.map.needsUpdate=!0),s.side=Ot,s.shadowSide=Ot,s.clipShadows=!0,e?.sectionPlane&&(s.clippingPlanes=e.sectionPlane),s}class RU{engine;constructor(e){this.engine=e}async loadModels(e,t){console.log("待加载模型",e);for(const n of e)i(n)==="light"&&CU(this.engine,n,t,e.length);function i(n){const r=n.split(".").pop();return r==="glb"||r==="gltf"?"gltf":"light"}}}var tc=(s=>(s.ModelLoadStart="model-load-start",s.ModelLoadProgress="model-load-progress",s.ModelLoaded="model-loaded",s.ModelError="model-error",s.SelectionChanged="selection-changed",s.HoverChanged="hover-changed",s.Click="click",s.MouseMove="mouse-move",s.CameraChanged="camera-changed",s.CameraIdle="camera-idle",s.ViewportResize="viewport-resize",s.EngineFree="engine-free",s.EngineBusy="engine-busy",s.MeasureChanged="measure-changed",s.SectionMove="section-move",s.LoadingCompleted="loading_completed",s))(tc||{});class IU{engine;isFree;isForceFree;highlightModels;hideModels;translucentModels;models;constructor(e){this.engine=e,this.isFree=!0,this.isForceFree=!1,this.highlightModels=[],this.hideModels=[],this.translucentModels=[],this.models=[]}init(){this.engine.events.on(tc.EngineFree,e=>{this.updateFree(!0),pw(this.engine,e,!1)}),this.engine.events.on(tc.EngineBusy,()=>{this.updateFree(!1)})}updateFree(e){this.isFree=e}closeAllFunction=()=>{}}let LU=class{listeners=new Map;debugMode=!1;setDebugMode(s){this.debugMode=s}on(s,e){const t=String(s);this.listeners.has(t)||this.listeners.set(t,[]),this.listeners.get(t).push(e),this.debugMode&&console.debug(`[EventModule] 注册事件监听器: ${t}, 当前监听器数量: ${this.listeners.get(t).length}`)}off(s,e){const t=String(s);if(!this.listeners.has(t)){this.debugMode&&console.warn(`[EventModule] 尝试移除不存在的事件监听器: ${t}`);return}const i=this.listeners.get(t),n=i.indexOf(e);n!==-1?(i.splice(n,1),this.debugMode&&console.debug(`[EventModule] 移除事件监听器: ${t}, 剩余监听器数量: ${i.length}`)):this.debugMode&&console.warn(`[EventModule] 尝试移除的回调函数未找到: ${t}`)}trigger(s,e){const t=String(s);if(!this.listeners.has(t)){this.debugMode&&(console.warn(`[EventModule] 触发事件但未找到监听器: ${t}`),console.debug("[EventModule] 当前已注册的事件类型:",Array.from(this.listeners.keys())));return}const i=this.listeners.get(t);this.debugMode&&console.debug(`[EventModule] 触发事件: ${t}, 监听器数量: ${i.length}`,e),i.forEach((n,r)=>{try{n(e)}catch(a){console.error(`[EventModule] 事件监听器执行错误 [${t}] #${r}:`,a)}})}};class DU{engine;constructor(e){this.engine=e}init(){const e=new Zr(16777215,1);e.position.set(100,200,100),e.castShadow=!0,e.shadow.mapSize.width=2048,e.shadow.mapSize.height=2048,e.shadow.camera.near=.1,e.shadow.camera.far=5e3,e.shadow.bias=-5e-5,e.shadow.normalBias=.02;const t=50;e.shadow.camera.left=-t,e.shadow.camera.right=t,e.shadow.camera.top=t,e.shadow.camera.bottom=-t,e.shadow.radius=2;const i=new Zr(16777215,2);this.engine.scene.add(e),this.engine.scene.add(i),this.engine.scene.dirLight=i;const n=new xl(16777215,2);this.engine.scene.add(n)}}class NU{engine;behavior;isCtrlDown=!1;isShiftDown=!1;hoverOldId=null;timeOutEvent;selectionBox=null;isBoxSelecting=!1;selectionStart=new me;selectionEnd=new me;suppressClickOnce=!1;selectionThreshold=5;tempInstanceMatrix=new qe;tempScale=new R;constructor(e){this.engine=e}init(){this.behavior=this.engine.handelBehaved,this.ensureSelectionBox(),this.behavior.init(this)}active(){this.behavior.active()}disActive(){this.cancelBoxSelection(),this.behavior.disActive()}handelKeyCtrlUp(){this.isCtrlDown=!1,this.isBoxSelecting&&this.cancelBoxSelection()}handelKeyCtrlDown(){this.isCtrlDown=!0}handelKeyShiftUp(){this.isShiftDown=!1}handelKeyShiftDown(){this.isShiftDown=!0}handleMouseDown(e){e.button!==0||!this.isBoxSelectionModifierDown()||(this.isBoxSelecting=!0,this.selectionStart.set(e.offsetX,e.offsetY),this.selectionEnd.copy(this.selectionStart),this.suppressClickOnce=!1,this.clearHoverFeedback(),this.updateSelectionBox(),this.engine.controls&&(this.engine.controls.enabled=!1))}handleMouseMove(e){if(this.clearHoverTimeout(),this.isBoxSelecting){this.selectionEnd.set(e.offsetX,e.offsetY),this.clearHoverFeedback(),this.updateSelectionBox();return}if(e.catch!=null&&(this.engine.hoverHighLight.showModelNameTag(null,null),this.timeOutEvent=setTimeout(()=>{this.hoverOldId=null;const i=this.getCatchMeshs(e,!0);i!=null&&i.length>0&&this.engine.hoverHighLight.showModelNameTag({url:i[0].url,ids:[i[0].name]},e.catch.point)},1e3)),!this.engine.engineStatus.isFree){this.engine.hoverHighLight.clearHighlight();return}const t=this.getCatchMeshs(e);if(t!=null&&t.length>0){this.engine.hoverHighLight.hightMesh(t);return}}handleMouseUp(e){if(!this.isBoxSelecting)return;this.selectionEnd.set(e.offsetX,e.offsetY);const t=this.hasSelectionBox(),i=t?this.collectModelsInSelection():[];this.isBoxSelecting=!1,this.hideSelectionBox(),this.engine.controls&&(this.engine.controls.enabled=!0),t&&(this.isBoxDeselectMode()?this.applyBoxDeselection(i):this.applyBoxSelection(i),this.suppressClickOnce=!0)}getCatchMeshs(e,t=!1){if(e.catch==null)return this.hoverOldId=null,null;if(e.catch.object.isInstance){const a=e.catch.object,o=e.catch.object.id,l=this.engine.models.find(d=>d.url==a.url)?.nodesMap?.get(o),c=new Map;l?.indexes.forEach(d=>{this.getSceneModel(d[0])instanceof ti&&(c.has(d[0])||c.set(d[0],[]),c.get(d[0])?.push(d[1]))});const h=[];return c.forEach((d,p)=>{const u=this.getSceneModel(p);d.forEach(v=>{const g=u.geometry.clone();g.applyMatrix4(u.matrixs[v]),h.push(new ht(g,u.material))})}),this.hoverOldId==o?[]:(this.hoverOldId=o,t||this.engine.hoverHighLight.clearHighlight(),h)}const i=e.catch.object,n=i.name,r=this.engine.models.find(a=>a.url===i.url)?.nodesMap?.get(n)?.infos?.map(a=>a.mesh)??[];return this.hoverOldId==n?[]:(this.hoverOldId=n,t||this.engine.hoverHighLight.clearHighlight(),r)}handleMouseClick(e){if(this.suppressClickOnce){this.suppressClickOnce=!1;return}if(this.isShiftDown&&!this.isCtrlDown)return;if(e.catch!=null){const i=e.catch,n=i.object;if(!this.isCtrlDown){this.engine.modelToolModule.unhighlightAllModels();const a=new CustomEvent("D3ElementClick",{detail:{id:-1}});window.dispatchEvent(a)}this.engine.controlModule.orbitControls.origin.set(i.point.x,i.point.y,i.point.z),this.engine.modelToolModule.highlightModel([{url:n.url,ids:[n.name]}]),this.engine.events.trigger(di.Click,[{url:n.url,ids:[n.name]}]);const r=new CustomEvent("D3ElementClick",{detail:{id:n.name}});window.dispatchEvent(r);return}const t=new CustomEvent("D3ElementClick",{detail:{id:-1}});window.dispatchEvent(t),this.engine.modelToolModule.unhighlightAllModels()}handleMouseDoubleClick(e){if(!e.catch){this.engine.viewCube.CameraGoHome(500);return}const t=e.catch,i=t.object,n=this.engine.models.find(o=>o.url===i.url)?.nodesMap?.get(i.name);if(!n)return;if(t.object.isInstance){const o=t.matrix,l=[];n.indexes.forEach(h=>{const d=this.getSceneModel(h[0]);d?.geometry?.boundingSphere||d?.geometry?.computeBoundingSphere?.();const p=d?.geometry?.boundingSphere;if(!p)return;const u=new vt,v=p.center.clone().applyMatrix4(o),g=p.radius,m=new R().setFromMatrixScale(o),f=g*Math.max(m.x,m.y,m.z);u.min.set(v.x-f,v.y-f,v.z-f),u.max.set(v.x+f,v.y+f,v.z+f),l.push(u)});const c=this.getMergedBox(l);c!=null&&this.engine.viewCube.zoomToModel(c);return}const r=n.infos.map(o=>o.box).filter(o=>o instanceof vt),a=this.getMergedBox(r);a!=null&&this.engine.viewCube.zoomToModel(a)}handleMouseClickInstance(e){return e.intersectObjects(this.engine.scene.children.filter(t=>t instanceof ti),!0)}ensureSelectionBox(){if(this.selectionBox!=null)return;const e=document.createElement("div");e.style.position="absolute",e.style.left="0px",e.style.top="0px",e.style.display="none",e.style.pointerEvents="none",e.style.border="1px dashed #00aaff",e.style.backgroundColor="rgba(0, 170, 255, 0.12)",e.style.boxSizing="border-box",e.style.zIndex="1001",this.engine.container?.appendChild(e),this.selectionBox=e}updateSelectionBox(){if(this.selectionBox==null)return;if(!this.hasSelectionBox()){this.selectionBox.style.display="none";return}const e=this.getSelectionRect();this.selectionBox.style.display="block",this.selectionBox.style.left=`${e.left}px`,this.selectionBox.style.top=`${e.top}px`,this.selectionBox.style.width=`${e.right-e.left}px`,this.selectionBox.style.height=`${e.bottom-e.top}px`}hideSelectionBox(){this.selectionBox!=null&&(this.selectionBox.style.display="none")}cancelBoxSelection(){this.isBoxSelecting=!1,this.hideSelectionBox(),this.engine.controls&&(this.engine.controls.enabled=!0)}clearHoverTimeout(){this.timeOutEvent!=null&&(clearTimeout(this.timeOutEvent),this.timeOutEvent=null)}clearHoverFeedback(){this.hoverOldId=null,this.engine.hoverHighLight.clearHighlight(),this.engine.hoverHighLight.showModelNameTag(null,null)}hasSelectionBox(){return Math.abs(this.selectionEnd.x-this.selectionStart.x)>=this.selectionThreshold&&Math.abs(this.selectionEnd.y-this.selectionStart.y)>=this.selectionThreshold}getSelectionRect(){return{left:Math.min(this.selectionStart.x,this.selectionEnd.x),top:Math.min(this.selectionStart.y,this.selectionEnd.y),right:Math.max(this.selectionStart.x,this.selectionEnd.x),bottom:Math.max(this.selectionStart.y,this.selectionEnd.y)}}isContainMode(){return this.selectionEnd.x>=this.selectionStart.x&&this.selectionEnd.y>=this.selectionStart.y}isBoxSelectionModifierDown(){return this.isCtrlDown}isBoxDeselectMode(){return this.isShiftDown}collectModelsInSelection(){const e=this.getSelectionRect(),t=this.isContainMode(),i=new Map;return this.engine.models?.forEach(n=>{!n?.url||!n?.nodesMap||n.nodesMap.forEach((r,a)=>{const o=this.getNodeWorldBox(r),l=this.projectBoxToScreenRect(o);l==null||!(t?this.containsRect(e,l):this.intersectsRect(e,l))||(i.has(n.url)||i.set(n.url,new Set),i.get(n.url)?.add(a))})}),Array.from(i.entries()).map(([n,r])=>({url:n,ids:Array.from(r)}))}applyBoxSelection(e){const t=this.excludeHighlightedModels(e);t.length!==0&&(this.engine.modelToolModule.highlightModel(t),this.engine.events.trigger(di.SelectionChanged,t))}applyBoxDeselection(e){const t=this.keepHighlightedModels(e);t.length!==0&&(this.engine.modelToolModule.unhighlightModel(t),this.removeModelsFromHighlightState(t),this.engine.events.trigger(di.SelectionChanged,t))}excludeHighlightedModels(e){const t=new Map;return(this.engine.engineStatus.highlightModels??[]).forEach(i=>{t.has(i.url)||t.set(i.url,new Set),i.ids.forEach(n=>t.get(i.url)?.add(n))}),e.map(i=>({url:i.url,ids:i.ids.filter(n=>!t.get(i.url)?.has(n))})).filter(i=>i.ids.length>0)}keepHighlightedModels(e){const t=new Map;return(this.engine.engineStatus.highlightModels??[]).forEach(i=>{t.has(i.url)||t.set(i.url,new Set),i.ids.forEach(n=>t.get(i.url)?.add(n))}),e.map(i=>({url:i.url,ids:i.ids.filter(n=>t.get(i.url)?.has(n))})).filter(i=>i.ids.length>0)}removeModelsFromHighlightState(e){const t=new Map;e.forEach(i=>{t.has(i.url)||t.set(i.url,new Set),i.ids.forEach(n=>t.get(i.url)?.add(n))}),this.engine.engineStatus.highlightModels=(this.engine.engineStatus.highlightModels??[]).map(i=>({url:i.url,ids:i.ids.filter(n=>!t.get(i.url)?.has(n))})).filter(i=>i.ids.length>0)}getNodeWorldBox(e){if(Array.isArray(e?.infos)&&e.infos.length>0){const t=e.infos.map(i=>i?.box).filter(i=>i instanceof vt);return this.getMergedBox(t)}if(Array.isArray(e?.indexes)&&e.indexes.length>0){const t=[];return e.indexes.forEach(i=>{const n=this.getSceneModel(i[0]),r=this.getInstanceWorldBox(n,i[1]);r!=null&&t.push(r)}),this.getMergedBox(t)}return null}getInstanceWorldBox(e,t){if(!(e instanceof ti))return null;e.geometry.boundingBox||e.geometry.computeBoundingBox();const i=e.geometry.boundingBox;if(!i)return null;if(typeof e.getMatrixAt=="function")e.getMatrixAt(t,this.tempInstanceMatrix);else if(e.matrixs?.[t])this.tempInstanceMatrix.copy(e.matrixs[t]);else return null;return this.tempScale.setFromMatrixScale(this.tempInstanceMatrix),Math.abs(this.tempScale.x)+Math.abs(this.tempScale.y)+Math.abs(this.tempScale.z)<1e-6?null:i.clone().applyMatrix4(this.tempInstanceMatrix)}projectBoxToScreenRect(e){if(e==null||e.isEmpty())return null;const t=[new R(e.min.x,e.min.y,e.min.z),new R(e.min.x,e.min.y,e.max.z),new R(e.min.x,e.max.y,e.min.z),new R(e.min.x,e.max.y,e.max.z),new R(e.max.x,e.min.y,e.min.z),new R(e.max.x,e.min.y,e.max.z),new R(e.max.x,e.max.y,e.min.z),new R(e.max.x,e.max.y,e.max.z)];let i=1/0,n=1/0,r=-1/0,a=-1/0;return t.forEach(o=>{const l=new zt(this.engine.camera,this.engine.renderer,this.engine.scene).worldToScreen(o);!Number.isFinite(l.x)||!Number.isFinite(l.y)||(i=Math.min(i,l.x),n=Math.min(n,l.y),r=Math.max(r,l.x),a=Math.max(a,l.y))}),!Number.isFinite(i)||!Number.isFinite(n)||!Number.isFinite(r)||!Number.isFinite(a)?null:{left:i,top:n,right:r,bottom:a}}containsRect(e,t){return t.left>=e.left&&t.top>=e.top&&t.right<=e.right&&t.bottom<=e.bottom}intersectsRect(e,t){return!(t.righte.right||t.bottome.bottom)}getMergedBox(e){if(e.length===0)return null;const t=new vt().makeEmpty();return e.forEach(i=>t.union(i)),t.isEmpty()?null:t}getSceneModel(e){return this.engine.scene.children.find(t=>t.index===e)??this.engine.scene.children[e]}}class kU{engine;highlightMaterial;hideMaterial;translucentMaterial;constructor(e){this.engine=e,this.highlightMaterial=new Dt({color:43775,depthTest:!1,depthWrite:!1,transparent:!0,opacity:.5,side:Ot}),this.hideMaterial=new Dt({color:0,transparent:!0,opacity:0,side:Ot}),this.translucentMaterial=new Dt({color:16777215,transparent:!0,opacity:.05,side:Ot}),this.highlightMaterial.clippingPlanes=this.engine.sectionPlane,this.hideMaterial.clippingPlanes=this.engine.sectionPlane,this.translucentMaterial.clippingPlanes=this.engine.sectionPlane}split_merge_model(e){if(e.isSplit||e instanceof ti)return;let t=e.materialClone.clone(),i=So(e.geometrys,!0);i.computeVertexNormals(),i.groups.forEach(n=>{n.materialIndex=0}),e.geometry=i,e.material=[t,this.highlightMaterial,this.translucentMaterial],e.needsUpdate=!0,e.isSplit=!0}un_split_merge_model(e){}getSceneModel(e){return this.engine.scene.children.find(t=>t.index==e)}highlightModel(e){e.forEach(t=>{let i=new Map;t.ids.forEach(r=>{let a=this.engine.models.find(o=>o.url==t.url).nodesMap.get(r);a!=null&&a.indexes!=null&&a.indexes.forEach(o=>{this.getSceneModel(o[0])instanceof ti?i.has(o[0])?i.get(o[0])?.push(o[1]):i.set(o[0],[o[1]]):(console.log(this.getSceneModel(o[0]).materialClone.color),this.split_merge_model(this.getSceneModel(o[0])),this.getSceneModel(o[0]).geometry.groups[o[1]].materialIndex=1)})}),OU(i,this.engine);let n=this.engine.engineStatus.highlightModels.find(r=>r.url==t.url);n!=null?n.ids.push(...t.ids):this.engine.engineStatus.highlightModels.push(t)})}unhighlightModel(e){e.forEach(t=>{let i=new Map;t.ids.forEach(n=>{let r=this.engine.models.find(a=>a.url==t.url).nodesMap.get(n);r!=null&&r.indexes!=null&&r.indexes.forEach(a=>{this.getSceneModel(a[0])instanceof ti?i.has(a[0])?i.get(a[0])?.push(a[1]):i.set(a[0],[a[1]]):this.getSceneModel(a[0]).geometry.groups[a[1]].materialIndex=0})}),fw(i,this.engine,"highlightModel")})}unhighlightAllModels(e=!0){this.engine.engineStatus.highlightModels.forEach(t=>{this.unhighlightModel([t])}),e&&(this.engine.engineStatus.highlightModels=[])}hideModel(e){e.forEach(t=>{let i=new Map;t.ids.forEach(r=>{let a=this.engine.models.find(o=>o.url==t.url).nodesMap.get(r);this.engine.modelEdge.hideModelEdge(t.url,r),a!=null&&a.indexes!=null&&a.indexes.forEach(o=>{const l=this.getSceneModel(o[0]);l instanceof ti?i.has(o[0])?i.get(o[0])?.push(o[1]):i.set(o[0],[o[1]]):(this.split_merge_model(this.getSceneModel(o[0])),l.geometry.groups[o[1]].materialIndex=-1,l.geometry.groups[o[1]].visible=!1)})}),i.size>0&&BU(i,this.engine);let n=this.engine.engineStatus.hideModels.find(r=>r.url==t.url);n!=null?n.ids.push(...t.ids):this.engine.engineStatus.hideModels.push({url:t.url,ids:t.ids}),this.engine.engineStatus.highlightModels=[]})}showModel(e){e.forEach(t=>{let i=new Map;t.ids.forEach(r=>{let a=this.engine.models.find(o=>o.url==t.url).nodesMap.get(r);this.engine.modelEdge.showModelEdge(t.url,r),a!=null&&a.indexes!=null&&a.indexes.forEach(o=>{const l=this.getSceneModel(o[0]);l instanceof ti?i.has(o[0])?i.get(o[0])?.push(o[1]):i.set(o[0],[o[1]]):(l.geometry.groups[o[1]].materialIndex=0,l.geometry.groups[o[1]].visible=!0)})}),i.size>0&&mw(i,this.engine);let n=this.engine.engineStatus.hideModels.find(r=>r.url==t.url);n&&(t.ids.forEach(r=>{const a=n.ids.indexOf(r);a!==-1&&n.ids.splice(a,1)}),n.ids.length===0&&(this.engine.engineStatus.hideModels=this.engine.engineStatus.hideModels.filter(r=>r!==n)))})}isolateModel(e){let t=[];this.engine.models.forEach(i=>{let n={url:i.url,ids:[]},r=e.find(a=>a.url==i.url);for(let a of i.nodesMap)r==null?n.ids.push(a[0]):r.ids.includes(a[0])||n.ids.push(a[0]);t.push(n)});debugger;this.unhighlightAllModels(),this.hideModel(t)}translucentOtherModel(e){let t=[];this.engine.models.forEach(i=>{let n={url:i.url,ids:[]},r=e.find(a=>a.url==i.url);for(let a of i.nodesMap)r==null?n.ids.push(a[0]):r.ids.includes(a[0])||n.ids.push(a[0]);t.push(n)}),this.translucentModel(t)}setModelColor(e,t){e.material.color.set(t)}setAllModelsColor(e){this.engine.scene.children.forEach(t=>{t.isMesh})}restoreAllModelsColor(){this.engine.scene.children.forEach(e=>{e.isMesh})}translucentModel(e){this.unhighlightAllModels(),e.forEach(t=>{let i=new Map;t.ids.forEach(r=>{let a=this.engine.models.find(o=>o.url==t.url).nodesMap.get(r);a!=null&&a.indexes!=null&&a.indexes.forEach(o=>{const l=this.getSceneModel(o[0]);l instanceof ti?i.has(o[0])?i.get(o[0])?.push(o[1]):i.set(o[0],[o[1]]):(this.split_merge_model(this.getSceneModel(o[0])),l.geometry.groups[o[1]].materialIndex=2)})}),UU(i,this.engine);let n=this.engine.engineStatus.translucentModels.find(r=>r.url==t.url);n!=null?n.ids.push(...t.ids):this.engine.engineStatus.translucentModels.push({url:t.url,ids:t.ids})}),this.engine.engineStatus.highlightModels=[]}unTranslucentModel(){this.engine.engineStatus.translucentModels.forEach(e=>{let t=new Map;e.ids.forEach(i=>{let n=this.engine.models.find(r=>r.url==e.url).nodesMap.get(i);n!=null&&n.indexes!=null&&n.indexes.forEach(r=>{const a=this.getSceneModel(r[0]);a instanceof ti?t.has(r[0])?t.get(r[0])?.push(r[1]):t.set(r[0],[r[1]]):(this.split_merge_model(this.getSceneModel(r[0])),a.geometry.groups[r[1]].materialIndex=0)})}),t.size>0&&mw(t,this.engine),fw(t,this.engine,"translucentModel")}),this.engine.engineStatus.translucentModels=[]}showAllModels(){this.engine.engineStatus.hideModels&&this.engine.engineStatus.hideModels.length>0&&this.showModel(this.engine.engineStatus.hideModels),this.engine.engineStatus.hideModels=[],this.unhighlightAllModels()}batchSelectSameLevelTypeModel(e){if(e.length==0)return;let t=e[0],i=this.engine.modelMapperBatch.getModelMapper(t.url,t.ids[0]);this.engine.modelMapperBatch.getModelsWithLevelType(i.levelName,i.typeName,n=>{this.engine.modelToolModule.highlightModel(n)})}batchSelectSameLevelModel(e){if(e.length==0)return;let t=e[0],i=this.engine.modelMapperBatch.getModelMapper(t.url,t.ids[0]);this.engine.modelMapperBatch.getModelsWithLevel(i.levelName,n=>{this.engine.modelToolModule.highlightModel(n)})}batchSelectSameTypeModel(e){if(e.length==0)return;let t=e[0],i=this.engine.modelMapperBatch.getModelMapper(t.url,t.ids[0]);this.engine.modelMapperBatch.getModelsWithType(i.typeName,n=>{this.engine.modelToolModule.highlightModel(n)})}}function OU(s,e){s.forEach((t,i)=>{const n=Fh(e,i);if(!(n instanceof ti))return;const r=n.geometry,a=new Dt({color:43775,depthTest:!1,depthWrite:!1,transparent:!0,opacity:.5,side:Ot}),o=new ti(r,a,t.length);o.name="highlightModel",o.key=i;const l=new Map,c=new qe,h=new qe;h.makeScale(0,0,0),t.forEach((d,p)=>{n.getMatrixAt(d,c),l.set(d,c.clone()),n.setMatrixAt(d,h),o.setMatrixAt(p,c)}),n.instanceMatrix.needsUpdate=!0,o.instanceMatrix.needsUpdate=!0,e.scene.add(o)})}function fw(s,e,t){s.forEach((i,n)=>{const r=Fh(e,n);r instanceof ti&&(i.forEach(a=>{const o=r.matrixsClone[a];o&&r.setMatrixAt(a,o)}),r.instanceMatrix.needsUpdate=!0,e.scene.children.filter(a=>a.key==n&&a.name==t).forEach(a=>{e.scene.remove(a)}))})}function UU(s,e){s.forEach((t,i)=>{const n=Fh(e,i);if(!(n instanceof ti))return;const r=n.geometry,a=new Dt({color:16777215,transparent:!0,opacity:.05,side:Ot}),o=new ti(r,a,t.length);o.name="translucentModel",o.key=i;const l=new Map,c=new qe,h=new qe;h.makeScale(0,0,0),t.forEach((d,p)=>{n.getMatrixAt(d,c),l.set(d,c.clone()),n.setMatrixAt(d,h),o.setMatrixAt(p,c)}),n.instanceMatrix.needsUpdate=!0,o.instanceMatrix.needsUpdate=!0,e.scene.add(o)})}function BU(s,e){e.scene.children.filter(t=>t.name=="highlightModel").forEach(t=>{e.scene.remove(t)}),s.forEach((t,i)=>{const n=Fh(e,i);if(!(n instanceof ti))return;const r=new Map,a=new qe,o=new qe;o.makeScale(0,0,0),t.forEach((l,c)=>{n.getMatrixAt(l,a),r.set(l,a.clone()),n.setMatrixAt(l,o)}),n.instanceMatrix.needsUpdate=!0})}function mw(s,e){s.forEach((t,i)=>{const n=Fh(e,i);n instanceof ti&&(t.forEach(r=>{const a=n.matrixs[r];a&&n.setMatrixAt(r,a)}),n.instanceMatrix.needsUpdate=!0)})}function Fh(s,e){return s.scene.children.find(t=>t.index==e)}class FU{engine;currentMode="";isManualMode=!1;gtaoPass=null;ssaoPass=null;saturationPass=null;outputPass=null;fxaaPass=null;constructor(e){this.engine=e}init(){this.cachePassReferences(),this.autoSwitch("advanced")}switchModel(e){this.isManualMode=!0,this.currentMode=e,this.applyMode(e)}autoSwitch(e){this.isManualMode||(this.currentMode=e,this.applyMode(e))}enableAutoMode(){this.isManualMode=!1}get isManual(){return this.isManualMode}setMode(e){debugger;this.isManualMode=!0,this.currentMode=e,this.applyMode(e)}getCurrentMode(){return this.currentMode}cachePassReferences(){this.engine.composerModule?.composer&&(this.engine.composerModule.gtaoPass&&(this.gtaoPass=this.engine.composerModule.gtaoPass),this.engine.composerModule.ssaoPass&&(this.ssaoPass=this.engine.composerModule.ssaoPass),this.engine.composerModule.saturationPass&&(this.saturationPass=this.engine.composerModule.saturationPass),this.engine.composerModule.outputPass&&(this.outputPass=this.engine.composerModule.outputPass),this.engine.composerModule.fxaaPass&&(this.fxaaPass=this.engine.composerModule.fxaaPass))}applyMode(e){switch(e){case"simple":this.setShadows(!1),this.setGTAO(!1),this.setSSAO(!1),this.setSaturation(!1),this.setOutputPass(!1),this.setFXAA(!0);break;case"balance":this.setShadows(!0),this.setGTAO(!1),this.setSSAO(!1),this.setSaturation(!1),this.setOutputPass(!1),this.setFXAA(!0);break;case"advanced":this.setShadows(!0),this.setSSAO(!1),this.setGTAO(!0),this.setSaturation(!1),this.setOutputPass(!1),this.setFXAA(!0);break;default:console.warn(`[EngineModelModule] Unknown mode: ${e}`)}this.engine.updateVersionDisplay?.()}setShadows(e){this.engine.renderer&&(this.engine.renderer.shadowMap.enabled=e);const t=this.engine.scene?.children.find(i=>i instanceof Zr);t&&(t.castShadow=e),this.engine.scene?.traverse(i=>{i.material&&(i.castShadow!==void 0&&(i.castShadow=e),i.receiveShadow!==void 0&&(i.receiveShadow=e))})}setGTAO(e){this.engine.composerModule?.composer&&this.gtaoPass&&(this.gtaoPass.enabled=e)}setSSAO(e){this.engine.composerModule?.composer&&this.ssaoPass&&(this.ssaoPass.enabled=e)}setSaturation(e){this.saturationPass&&(this.saturationPass.enabled=e)}setOutputPass(e){this.outputPass&&(this.outputPass.enabled=e)}setFXAA(e){this.fxaaPass&&(this.fxaaPass.enabled=e)}setPerformanceMode(){this.setMode("simple")}setBalancedMode(){this.setMode("balance")}setQualityMode(){this.setMode("advanced")}setSuperQualityMode(){this.setMode("superAdvanced")}setShadowQuality(e){const t=this.engine.scene?.children.find(n=>n instanceof Zr),i={low:1024,medium:2048,high:2048}[e];t?.shadow&&i&&(t.shadow.mapSize.width=i,t.shadow.mapSize.height=i,t.shadow.map?.dispose(),t.shadow.map=null)}setSaturationValue(e){this.saturationPass&&(this.saturationPass.uniforms.saturation.value=e)}setContrastValue(e){this.saturationPass&&(this.saturationPass.uniforms.contrast.value=e)}setGTAOIntensity(e){this.gtaoPass&&(this.gtaoPass.blendIntensity=e)}}class jf{engine;overlayMaterial;overlayMeshes=[];animState="idle";animStartTime=0;static FADE_IN_MS=200;static FADE_OUT_MS=150;tagDiv;constructor(e){this.engine=e,this.init();const t=document.createElement("div");this.tagDiv=t,t.className="tagDiv",t.style.position="absolute",t.style.top="0px",t.style.left="0px",t.style.borderRadius="10px",t.style.pointerEvents="none",this.engine.container.appendChild(this.tagDiv)}showModelNameTag(e,t){if(e==null){this.tagDiv.style.display="none";return}let i=this.engine.models.find(a=>a.url==e.url);if(i==null){this.tagDiv.style.display="none";return}let n=i.nodesMap.get(e.ids[0]);if(n.infos&&n.infos.length>0){let a=n.infos[0].name.replace(/\s*\[[a-f0-9-]+\]$/,"");this.tagDiv.innerHTML=a}const r=this.engine.worldToScreen.worldToScreen(t);this.tagDiv?(this.tagDiv.style.left=r.x+10+this.engine.reactBoundingClientRect.left+"px",this.tagDiv.style.top=r.y-10+this.engine.reactBoundingClientRect.top+"px",this.tagDiv.style.display="block"):this.tagDiv&&(this.tagDiv.style.display="none")}init(){this.overlayMaterial=new Dt({color:16777215,transparent:!0,opacity:0,blending:od,depthWrite:!1}),this.overlayMaterial.clippingPlanes=this.engine.sectionPlane}hightMesh(e,t=16777215,i=.15){this.animState==="fadeOut"&&this.removeOverlayMeshes();const n=(Array.isArray(e)?e:e?[e]:[]).filter(r=>r?.geometry);if(n.length===0){this.clearHighlight();return}this.overlayMaterial.color.set(t),this.overlayMaterial.opacity=0,this.overlayMaterial.userData.targetOpacity=i;for(const r of n){let a=r.geometry.clone();a.computeVertexNormals();const o=new ht(a,this.overlayMaterial);r.updateWorldMatrix(!0,!1),o.matrix.copy(r.matrixWorld),o.matrixAutoUpdate=!1,this.engine.scene.add(o),this.overlayMeshes.push(o)}this.animState="fadeIn",this.animStartTime=performance.now()}clearHighlight(){this.overlayMeshes.length===0||this.animState==="fadeOut"||(this.animState="fadeOut",this.animStartTime=performance.now())}update(){if(this.animState==="idle"||this.overlayMeshes.length===0)return;const e=performance.now()-this.animStartTime,t=this.overlayMaterial.userData.targetOpacity??.35;if(this.animState==="fadeIn"){const i=Math.min(e/jf.FADE_IN_MS,1);this.overlayMaterial.opacity=this.easeOutQuad(i)*t,i>=1&&(this.animState="idle")}else if(this.animState==="fadeOut"){const i=Math.min(e/jf.FADE_OUT_MS,1);this.overlayMaterial.opacity=(1-this.easeOutQuad(i))*t,i>=1&&(this.removeOverlayMeshes(),this.animState="idle")}}removeOverlayMeshes(){for(const e of this.overlayMeshes)this.engine.scene.remove(e);this.overlayMeshes=[]}easeOutQuad(e){return 1-(1-e)*(1-e)}dispose(){this.removeOverlayMeshes(),this.overlayMaterial.dispose(),this.animState="idle"}}var f1={exports:{}},zU=f1.exports,gw;function HU(){return gw||(gw=1,(function(s,e){(function(t,i){s.exports=i()})(zU,function(){var t=function(){function i(u){return a.appendChild(u.dom),u}function n(u){for(var v=0;vl+1e3&&(h.update(1e3*c/(u-l),100),l=u,c=0,p)){var v=performance.memory;p.update(v.usedJSHeapSize/1048576,v.jsHeapSizeLimit/1048576)}return u},update:function(){o=this.end()},domElement:a,setMode:n}};return t.Panel=function(i,n,r){var a=1/0,o=0,l=Math.round,c=l(window.devicePixelRatio||1),h=80*c,d=48*c,p=3*c,u=2*c,v=3*c,g=15*c,m=74*c,f=30*c,y=document.createElement("canvas");y.width=h,y.height=d,y.style.cssText="width:80px;height:48px";var x=y.getContext("2d");return x.font="bold "+9*c+"px Helvetica,Arial,sans-serif",x.textBaseline="top",x.fillStyle=r,x.fillRect(0,0,h,d),x.fillStyle=n,x.fillText(i,p,u),x.fillRect(v,g,m,f),x.fillStyle=r,x.globalAlpha=.9,x.fillRect(v,g,m,f),{dom:y,update:function(_,S){a=Math.min(a,_),o=Math.max(o,_),x.fillStyle=r,x.globalAlpha=1,x.fillRect(0,0,h,g),x.fillStyle=n,x.fillText(l(_)+" "+i+" ("+l(a)+"-"+l(o)+")",p,u),x.drawImage(y,v+c,g,m-c,f,v,g,m-c,f),x.fillRect(v+m-c,g,c,f),x.fillStyle=r,x.globalAlpha=.9,x.fillRect(v+m-c,g,c,l((1-_/S)*f))}}},t})})(f1)),f1.exports}var VU=HU();const GU=rS(VU);var ic=Object.freeze({Linear:Object.freeze({None:function(s){return s},In:function(s){return s},Out:function(s){return s},InOut:function(s){return s}}),Quadratic:Object.freeze({In:function(s){return s*s},Out:function(s){return s*(2-s)},InOut:function(s){return(s*=2)<1?.5*s*s:-.5*(--s*(s-2)-1)}}),Cubic:Object.freeze({In:function(s){return s*s*s},Out:function(s){return--s*s*s+1},InOut:function(s){return(s*=2)<1?.5*s*s*s:.5*((s-=2)*s*s+2)}}),Quartic:Object.freeze({In:function(s){return s*s*s*s},Out:function(s){return 1- --s*s*s*s},InOut:function(s){return(s*=2)<1?.5*s*s*s*s:-.5*((s-=2)*s*s*s-2)}}),Quintic:Object.freeze({In:function(s){return s*s*s*s*s},Out:function(s){return--s*s*s*s*s+1},InOut:function(s){return(s*=2)<1?.5*s*s*s*s*s:.5*((s-=2)*s*s*s*s+2)}}),Sinusoidal:Object.freeze({In:function(s){return 1-Math.sin((1-s)*Math.PI/2)},Out:function(s){return Math.sin(s*Math.PI/2)},InOut:function(s){return .5*(1-Math.sin(Math.PI*(.5-s)))}}),Exponential:Object.freeze({In:function(s){return s===0?0:Math.pow(1024,s-1)},Out:function(s){return s===1?1:1-Math.pow(2,-10*s)},InOut:function(s){return s===0?0:s===1?1:(s*=2)<1?.5*Math.pow(1024,s-1):.5*(-Math.pow(2,-10*(s-1))+2)}}),Circular:Object.freeze({In:function(s){return 1-Math.sqrt(1-s*s)},Out:function(s){return Math.sqrt(1- --s*s)},InOut:function(s){return(s*=2)<1?-.5*(Math.sqrt(1-s*s)-1):.5*(Math.sqrt(1-(s-=2)*s)+1)}}),Elastic:Object.freeze({In:function(s){return s===0?0:s===1?1:-Math.pow(2,10*(s-1))*Math.sin((s-1.1)*5*Math.PI)},Out:function(s){return s===0?0:s===1?1:Math.pow(2,-10*s)*Math.sin((s-.1)*5*Math.PI)+1},InOut:function(s){return s===0?0:s===1?1:(s*=2,s<1?-.5*Math.pow(2,10*(s-1))*Math.sin((s-1.1)*5*Math.PI):.5*Math.pow(2,-10*(s-1))*Math.sin((s-1.1)*5*Math.PI)+1)}}),Back:Object.freeze({In:function(s){var e=1.70158;return s===1?1:s*s*((e+1)*s-e)},Out:function(s){var e=1.70158;return s===0?0:--s*s*((e+1)*s+e)+1},InOut:function(s){var e=2.5949095;return(s*=2)<1?.5*(s*s*((e+1)*s-e)):.5*((s-=2)*s*((e+1)*s+e)+2)}}),Bounce:Object.freeze({In:function(s){return 1-ic.Bounce.Out(1-s)},Out:function(s){return s<1/2.75?7.5625*s*s:s<2/2.75?7.5625*(s-=1.5/2.75)*s+.75:s<2.5/2.75?7.5625*(s-=2.25/2.75)*s+.9375:7.5625*(s-=2.625/2.75)*s+.984375},InOut:function(s){return s<.5?ic.Bounce.In(s*2)*.5:ic.Bounce.Out(s*2-1)*.5+.5}}),generatePow:function(s){return s===void 0&&(s=4),s=s1e4?1e4:s,{In:function(e){return Math.pow(e,s)},Out:function(e){return 1-Math.pow(1-e,s)},InOut:function(e){return e<.5?Math.pow(e*2,s)/2:(1-Math.pow(2-e*2,s))/2+.5}}}}),zh=function(){return performance.now()},WU=(function(){function s(){this._tweens={},this._tweensAddedDuringUpdate={}}return s.prototype.getAll=function(){var e=this;return Object.keys(this._tweens).map(function(t){return e._tweens[t]})},s.prototype.removeAll=function(){this._tweens={}},s.prototype.add=function(e){this._tweens[e.getId()]=e,this._tweensAddedDuringUpdate[e.getId()]=e},s.prototype.remove=function(e){delete this._tweens[e.getId()],delete this._tweensAddedDuringUpdate[e.getId()]},s.prototype.update=function(e,t){e===void 0&&(e=zh()),t===void 0&&(t=!1);var i=Object.keys(this._tweens);if(i.length===0)return!1;for(;i.length>0;){this._tweensAddedDuringUpdate={};for(var n=0;n1?r(s[t],s[t-1],t-i):r(s[n],s[n+1>t?t:n+1],i-n)},Utils:{Linear:function(s,e,t){return(e-s)*t+s}}},vw=(function(){function s(){}return s.nextId=function(){return s._nextId++},s._nextId=0,s})(),g1=new WU,XU=(function(){function s(e,t){t===void 0&&(t=g1),this._object=e,this._group=t,this._isPaused=!1,this._pauseStart=0,this._valuesStart={},this._valuesEnd={},this._valuesStartRepeat={},this._duration=1e3,this._isDynamic=!1,this._initialRepeat=0,this._repeat=0,this._yoyo=!1,this._isPlaying=!1,this._reversed=!1,this._delayTime=0,this._startTime=0,this._easingFunction=ic.Linear.None,this._interpolationFunction=m1.Linear,this._chainedTweens=[],this._onStartCallbackFired=!1,this._onEveryStartCallbackFired=!1,this._id=vw.nextId(),this._isChainStopped=!1,this._propertiesAreSetUp=!1,this._goToEnd=!1}return s.prototype.getId=function(){return this._id},s.prototype.isPlaying=function(){return this._isPlaying},s.prototype.isPaused=function(){return this._isPaused},s.prototype.getDuration=function(){return this._duration},s.prototype.to=function(e,t){if(t===void 0&&(t=1e3),this._isPlaying)throw new Error("Can not call Tween.to() while Tween is already started or paused. Stop the Tween first.");return this._valuesEnd=e,this._propertiesAreSetUp=!1,this._duration=t<0?0:t,this},s.prototype.duration=function(e){return e===void 0&&(e=1e3),this._duration=e<0?0:e,this},s.prototype.dynamic=function(e){return e===void 0&&(e=!1),this._isDynamic=e,this},s.prototype.start=function(e,t){if(e===void 0&&(e=zh()),t===void 0&&(t=!1),this._isPlaying)return this;if(this._group&&this._group.add(this),this._repeat=this._initialRepeat,this._reversed){this._reversed=!1;for(var i in this._valuesStartRepeat)this._swapEndStartRepeatValues(i),this._valuesStart[i]=this._valuesStartRepeat[i]}if(this._isPlaying=!0,this._isPaused=!1,this._onStartCallbackFired=!1,this._onEveryStartCallbackFired=!1,this._isChainStopped=!1,this._startTime=e,this._startTime+=this._delayTime,!this._propertiesAreSetUp||t){if(this._propertiesAreSetUp=!0,!this._isDynamic){var n={};for(var r in this._valuesEnd)n[r]=this._valuesEnd[r];this._valuesEnd=n}this._setupProperties(this._object,this._valuesStart,this._valuesEnd,this._valuesStartRepeat,t)}return this},s.prototype.startFromCurrentValues=function(e){return this.start(e,!0)},s.prototype._setupProperties=function(e,t,i,n,r){for(var a in i){var o=e[a],l=Array.isArray(o),c=l?"array":typeof o,h=!l&&Array.isArray(i[a]);if(!(c==="undefined"||c==="function")){if(h){var d=i[a];if(d.length===0)continue;for(var p=[o],u=0,v=d.length;u"u"||r)&&(t[a]=o),l||(t[a]*=1),h?n[a]=i[a].slice().reverse():n[a]=t[a]||0}}},s.prototype.stop=function(){return this._isChainStopped||(this._isChainStopped=!0,this.stopChainedTweens()),this._isPlaying?(this._group&&this._group.remove(this),this._isPlaying=!1,this._isPaused=!1,this._onStopCallback&&this._onStopCallback(this._object),this):this},s.prototype.end=function(){return this._goToEnd=!0,this.update(1/0),this},s.prototype.pause=function(e){return e===void 0&&(e=zh()),this._isPaused||!this._isPlaying?this:(this._isPaused=!0,this._pauseStart=e,this._group&&this._group.remove(this),this)},s.prototype.resume=function(e){return e===void 0&&(e=zh()),!this._isPaused||!this._isPlaying?this:(this._isPaused=!1,this._startTime+=e-this._pauseStart,this._pauseStart=0,this._group&&this._group.add(this),this)},s.prototype.stopChainedTweens=function(){for(var e=0,t=this._chainedTweens.length;ea)return!1;t&&this.start(e,!0)}if(this._goToEnd=!1,ec)return 1;var m=Math.trunc(o/l),f=o-m*l,y=Math.min(f/i._duration,1);return y===0&&o===i._duration?1:y},d=h(),p=this._easingFunction(d);if(this._updateProperties(this._object,this._valuesStart,this._valuesEnd,p),this._onUpdateCallback&&this._onUpdateCallback(this._object,d),this._duration===0||o>=this._duration)if(this._repeat>0){var u=Math.min(Math.trunc((o-this._duration)/l)+1,this._repeat);isFinite(this._repeat)&&(this._repeat-=u);for(r in this._valuesStartRepeat)!this._yoyo&&typeof this._valuesEnd[r]=="string"&&(this._valuesStartRepeat[r]=this._valuesStartRepeat[r]+parseFloat(this._valuesEnd[r])),this._yoyo&&this._swapEndStartRepeatValues(r),this._valuesStart[r]=this._valuesStartRepeat[r];return this._yoyo&&(this._reversed=!this._reversed),this._startTime+=l*u,this._onRepeatCallback&&this._onRepeatCallback(this._object),this._onEveryStartCallbackFired=!1,!0}else{this._onCompleteCallback&&this._onCompleteCallback(this._object);for(var v=0,g=this._chainedTweens.length;vMath.PI&&(i-=Rn),n<-Math.PI?n+=Rn:n>Math.PI&&(n-=Rn),i<=n?this._spherical.theta=Math.max(i,Math.min(n,this._spherical.theta)):this._spherical.theta=this._spherical.theta>(i+n)/2?Math.max(i,this._spherical.theta):Math.min(n,this._spherical.theta)),this._spherical.phi=Math.max(this.minPolarAngle,Math.min(this.maxPolarAngle,this._spherical.phi)),this._spherical.makeSafe(),this.enableDamping===!0?this.target.addScaledVector(this._panOffset,this.dampingFactor):this.target.add(this._panOffset),this.target.sub(this.cursor),this.target.clampLength(this.minTargetRadius,this.maxTargetRadius),this.target.add(this.cursor);let r=!1;if(this.zoomToCursor&&this._performCursorZoom||this.object.isOrthographicCamera)this._spherical.radius=this._clampDistance(this._spherical.radius);else{const a=this._spherical.radius;this._spherical.radius=this._clampDistance(this._spherical.radius*this._scale),r=a!=this._spherical.radius}if(Oi.setFromSpherical(this._spherical),Oi.applyQuaternion(this._quatInverse),t.copy(this.target).add(Oi),this.object.lookAt(this.target),this.enableDamping===!0?(this._sphericalDelta.theta*=1-this.dampingFactor,this._sphericalDelta.phi*=1-this.dampingFactor,this._panOffset.multiplyScalar(1-this.dampingFactor)):(this._sphericalDelta.set(0,0,0),this._panOffset.set(0,0,0)),this.zoomToCursor&&this._performCursorZoom){let a=null;if(this.object.isPerspectiveCamera){const o=Oi.length();a=this._clampDistance(o*this._scale);const l=o-a;this.object.position.addScaledVector(this._dollyDirection,l),this.object.updateMatrixWorld(),r=!!l}else if(this.object.isOrthographicCamera){const o=new R(this._mouse.x,this._mouse.y,0);o.unproject(this.object);const l=this.object.zoom;this.object.zoom=Math.max(this.minZoom,Math.min(this.maxZoom,this.object.zoom/this._scale)),this.object.updateProjectionMatrix(),r=l!==this.object.zoom;const c=new R(this._mouse.x,this._mouse.y,0);c.unproject(this.object),this.object.position.sub(c).add(o),this.object.updateMatrixWorld(),a=Oi.length()}else console.warn("WARNING: OrbitControls.js encountered an unknown camera type - zoom to cursor disabled."),this.zoomToCursor=!1;a!==null&&(this.screenSpacePanning?this.target.set(0,0,-1).transformDirection(this.object.matrix).multiplyScalar(a).add(this.object.position):(qf.origin.copy(this.object.position),qf.direction.set(0,0,-1).transformDirection(this.object.matrix),Math.abs(this.object.up.dot(qf.direction))y1||8*(1-this._lastQuaternion.dot(this.object.quaternion))>y1||this._lastTargetPosition.distanceToSquared(this.target)>y1?(this.dispatchEvent(yw),this._lastPosition.copy(this.object.position),this._lastQuaternion.copy(this.object.quaternion),this._lastTargetPosition.copy(this.target),!0):!1}_getAutoRotationAngle(e){return e!==null?Rn/60*this.autoRotateSpeed*e:Rn/60/60*this.autoRotateSpeed}_getZoomScale(e){const t=Math.abs(e*.01);return Math.pow(.95,this.zoomSpeed*t)}_rotateLeft(e){this._sphericalDelta.theta-=e}_rotateUp(e){this._sphericalDelta.phi-=e}_panLeft(e,t){Oi.setFromMatrixColumn(t,0),Oi.multiplyScalar(-e),this._panOffset.add(Oi)}_panUp(e,t){this.screenSpacePanning===!0?Oi.setFromMatrixColumn(t,1):(Oi.setFromMatrixColumn(t,0),Oi.crossVectors(this.object.up,Oi)),Oi.multiplyScalar(e),this._panOffset.add(Oi)}_pan(e,t){const i=this.domElement;if(this.object.isPerspectiveCamera){const n=this.object.position;Oi.copy(n).sub(this.target);let r=Oi.length();r*=Math.tan(this.object.fov/2*Math.PI/180),this._panLeft(2*e*r/i.clientHeight,this.object.matrix),this._panUp(2*t*r/i.clientHeight,this.object.matrix)}else this.object.isOrthographicCamera?(this._panLeft(e*(this.object.right-this.object.left)/this.object.zoom/i.clientWidth,this.object.matrix),this._panUp(t*(this.object.top-this.object.bottom)/this.object.zoom/i.clientHeight,this.object.matrix)):(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - pan disabled."),this.enablePan=!1)}_dollyOut(e){this.object.isPerspectiveCamera||this.object.isOrthographicCamera?this._scale/=e:(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),this.enableZoom=!1)}_dollyIn(e){this.object.isPerspectiveCamera||this.object.isOrthographicCamera?this._scale*=e:(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),this.enableZoom=!1)}_updateZoomParameters(e,t){if(!this.zoomToCursor)return;this._performCursorZoom=!0;const i=this.domElement.getBoundingClientRect(),n=e-i.left,r=t-i.top,a=i.width,o=i.height;this._mouse.x=n/a*2-1,this._mouse.y=-(r/o)*2+1,this._dollyDirection.set(this._mouse.x,this._mouse.y,1).unproject(this.object).sub(this.object.position).normalize()}_clampDistance(e){return Math.max(this.minDistance,Math.min(this.maxDistance,e))}_handleMouseDownRotate(e){this._rotateStart.set(e.clientX,e.clientY)}_handleMouseDownDolly(e){this._updateZoomParameters(e.clientX,e.clientX),this._dollyStart.set(e.clientX,e.clientY)}_handleMouseDownPan(e){this._panStart.set(e.clientX,e.clientY)}_handleMouseMoveRotate(e){this._rotateEnd.set(e.clientX,e.clientY),this._rotateDelta.subVectors(this._rotateEnd,this._rotateStart).multiplyScalar(this.rotateSpeed);const t=this.domElement;this._rotateLeft(Rn*this._rotateDelta.x/t.clientHeight),this._rotateUp(Rn*this._rotateDelta.y/t.clientHeight),this._rotateStart.copy(this._rotateEnd),this.update()}_handleMouseMoveDolly(e){this._dollyEnd.set(e.clientX,e.clientY),this._dollyDelta.subVectors(this._dollyEnd,this._dollyStart),this._dollyDelta.y>0?this._dollyOut(this._getZoomScale(this._dollyDelta.y)):this._dollyDelta.y<0&&this._dollyIn(this._getZoomScale(this._dollyDelta.y)),this._dollyStart.copy(this._dollyEnd),this.update()}_handleMouseMovePan(e){this._panEnd.set(e.clientX,e.clientY),this._panDelta.subVectors(this._panEnd,this._panStart).multiplyScalar(this.panSpeed),this._pan(this._panDelta.x,this._panDelta.y),this._panStart.copy(this._panEnd),this.update()}_handleMouseWheel(e){this._updateZoomParameters(e.clientX,e.clientY),e.deltaY<0?this._dollyIn(this._getZoomScale(e.deltaY)):e.deltaY>0&&this._dollyOut(this._getZoomScale(e.deltaY)),this.update()}_handleKeyDown(e){let t=!1;switch(e.code){case this.keys.UP:e.ctrlKey||e.metaKey||e.shiftKey?this.enableRotate&&this._rotateUp(Rn*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(0,this.keyPanSpeed),t=!0;break;case this.keys.BOTTOM:e.ctrlKey||e.metaKey||e.shiftKey?this.enableRotate&&this._rotateUp(-Rn*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(0,-this.keyPanSpeed),t=!0;break;case this.keys.LEFT:e.ctrlKey||e.metaKey||e.shiftKey?this.enableRotate&&this._rotateLeft(Rn*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(this.keyPanSpeed,0),t=!0;break;case this.keys.RIGHT:e.ctrlKey||e.metaKey||e.shiftKey?this.enableRotate&&this._rotateLeft(-Rn*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(-this.keyPanSpeed,0),t=!0;break}t&&(e.preventDefault(),this.update())}_handleTouchStartRotate(e){if(this._pointers.length===1)this._rotateStart.set(e.pageX,e.pageY);else{const t=this._getSecondPointerPosition(e),i=.5*(e.pageX+t.x),n=.5*(e.pageY+t.y);this._rotateStart.set(i,n)}}_handleTouchStartPan(e){if(this._pointers.length===1)this._panStart.set(e.pageX,e.pageY);else{const t=this._getSecondPointerPosition(e),i=.5*(e.pageX+t.x),n=.5*(e.pageY+t.y);this._panStart.set(i,n)}}_handleTouchStartDolly(e){const t=this._getSecondPointerPosition(e),i=e.pageX-t.x,n=e.pageY-t.y,r=Math.sqrt(i*i+n*n);this._dollyStart.set(0,r)}_handleTouchStartDollyPan(e){this.enableZoom&&this._handleTouchStartDolly(e),this.enablePan&&this._handleTouchStartPan(e)}_handleTouchStartDollyRotate(e){this.enableZoom&&this._handleTouchStartDolly(e),this.enableRotate&&this._handleTouchStartRotate(e)}_handleTouchMoveRotate(e){if(this._pointers.length==1)this._rotateEnd.set(e.pageX,e.pageY);else{const i=this._getSecondPointerPosition(e),n=.5*(e.pageX+i.x),r=.5*(e.pageY+i.y);this._rotateEnd.set(n,r)}this._rotateDelta.subVectors(this._rotateEnd,this._rotateStart).multiplyScalar(this.rotateSpeed);const t=this.domElement;this._rotateLeft(Rn*this._rotateDelta.x/t.clientHeight),this._rotateUp(Rn*this._rotateDelta.y/t.clientHeight),this._rotateStart.copy(this._rotateEnd)}_handleTouchMovePan(e){if(this._pointers.length===1)this._panEnd.set(e.pageX,e.pageY);else{const t=this._getSecondPointerPosition(e),i=.5*(e.pageX+t.x),n=.5*(e.pageY+t.y);this._panEnd.set(i,n)}this._panDelta.subVectors(this._panEnd,this._panStart).multiplyScalar(this.panSpeed),this._pan(this._panDelta.x,this._panDelta.y),this._panStart.copy(this._panEnd)}_handleTouchMoveDolly(e){const t=this._getSecondPointerPosition(e),i=e.pageX-t.x,n=e.pageY-t.y,r=Math.sqrt(i*i+n*n);this._dollyEnd.set(0,r),this._dollyDelta.set(0,Math.pow(this._dollyEnd.y/this._dollyStart.y,this.zoomSpeed)),this._dollyOut(this._dollyDelta.y),this._dollyStart.copy(this._dollyEnd);const a=(e.pageX+t.x)*.5,o=(e.pageY+t.y)*.5;this._updateZoomParameters(a,o)}_handleTouchMoveDollyPan(e){this.enableZoom&&this._handleTouchMoveDolly(e),this.enablePan&&this._handleTouchMovePan(e)}_handleTouchMoveDollyRotate(e){this.enableZoom&&this._handleTouchMoveDolly(e),this.enableRotate&&this._handleTouchMoveRotate(e)}_addPointer(e){this._pointers.push(e.pointerId)}_removePointer(e){delete this._pointerPositions[e.pointerId];for(let t=0;t(_=E.indexOf(` `))&&S=m.byteLength||!(E=i(m)))&&t(1,"no header found"),(w=E.match(f))||t(3,"bad initial token"),b.valid|=1,b.programtype=w[1],b.string+=E+` `;E=i(m),E!==!1;){if(b.string+=E+` `,E.charAt(0)==="#"){b.comments+=E+` `;continue}if((w=E.match(y))&&(b.gamma=parseFloat(w[1])),(w=E.match(x))&&(b.exposure=parseFloat(w[1])),(w=E.match(_))&&(b.valid|=2,b.format=w[1]),(w=E.match(S))&&(b.valid|=4,b.height=parseInt(w[1],10),b.width=parseInt(w[2],10)),b.valid&2&&b.valid&4)break}return b.valid&2||t(3,"missing format specifier"),b.valid&4||t(3,"missing image size specifier"),b},r=function(m,f,y){const x=f;if(x<8||x>32767||m[0]!==2||m[1]!==2||m[2]&128)return new Uint8Array(m);x!==(m[2]<<8|m[3])&&t(3,"wrong scanline width");const _=new Uint8Array(4*f*y);_.length||t(4,"unable to allocate buffer space");let S=0,b=0;const E=4*x,w=new Uint8Array(4),M=new Uint8Array(E);let C=y;for(;C>0&&bm.byteLength&&t(1),w[0]=m[b++],w[1]=m[b++],w[2]=m[b++],w[3]=m[b++],(w[0]!=2||w[1]!=2||(w[2]<<8|w[3])!=x)&&t(3,"bad rgbe scanline format");let I=0,P;for(;I128;if(A&&(P-=128),(P===0||I+P>E)&&t(3,"bad scanline data"),A){const B=m[b++];for(let F=0;F{_&&(w||(_(M),w=!0))}),_&&setTimeout(()=>{w||(_(!0),w=!0)},x+10)},i.CameraGoHome=function(y=1e3){var x=s.octreeBox.getBoundingBox(),_=x.min.clone().add(x.max.clone()).multiplyScalar(.5);let S=new R(1,1,1);var b=x.max.distanceTo(x.min),E=_.clone().add(S.multiplyScalar(b*2));if(s.camera.far=b*5,e.camera.isOrthographicCamera){var w=s.container.clientWidth/s.container.clientHeight,M=b*.6;e.camera.left=-M*w,e.camera.right=M*w,e.camera.top=M,e.camera.bottom=-M,e.camera.zoom=1,e.camera.updateProjectionMatrix()}s.controlModule.orbitControls.origin=_.clone(),l(e.camera.position,E,s.controls.target.clone(),_,null,null,y)},i.zoomToBox=function(y){if(e.camera.isOrthographicCamera){let J=function(){n=requestAnimationFrame(J),be.update()};var x=y.min.clone().add(y.max.clone()).multiplyScalar(.5),_=e.camera.position.clone().sub(s.controls.target.clone()).normalize(),S=e.camera.position.distanceTo(s.controls.target),b=x.clone().add(_.multiplyScalar(S)),E=e.camera.zoom,w=new R(1,0,0).applyQuaternion(e.camera.quaternion),M=new R(0,1,0).applyQuaternion(e.camera.quaternion),C=[new R(y.min.x,y.min.y,y.min.z),new R(y.max.x,y.min.y,y.min.z),new R(y.min.x,y.max.y,y.min.z),new R(y.max.x,y.max.y,y.min.z),new R(y.min.x,y.min.y,y.max.z),new R(y.max.x,y.min.y,y.max.z),new R(y.min.x,y.max.y,y.max.z),new R(y.max.x,y.max.y,y.max.z)],I=1/0,P=-1/0,k=1/0,A=-1/0;for(var B of C){var F=B.dot(w),H=B.dot(M);I=Math.min(I,F),P=Math.max(P,F),k=Math.min(k,H),A=Math.max(A,H)}var q=(P-I)/2,G=(A-k)/2,re=(e.camera.right-e.camera.left)/2,Y=(e.camera.top-e.camera.bottom)/2;E=Math.min(re/q,Y/G)*.75;var $=e.camera.position.clone(),_e=s.controls.target.clone(),Te=e.camera.zoom,be=new Hh.Tween({x1:$.x,y1:$.y,z1:$.z,x2:_e.x,y2:_e.y,z2:_e.z,zoom:Te}).to({x1:b.x,y1:b.y,z1:b.z,x2:x.x,y2:x.y,z2:x.z,zoom:E},1e3);be.onUpdate(function(oe){s.controls&&(e.camera.position.set(oe.x1,oe.y1,oe.z1),s.controls.target.set(oe.x2,oe.y2,oe.z2),e.camera.isOrthographicCamera&&(e.camera.zoom=oe.zoom,e.camera.updateProjectionMatrix()),s.controls.auto=!0,s.controls.update(),i.RenderScene())}),be.onComplete(function(){s.controls&&(s.controls.auto=!1,i.RenderScene(),cancelAnimationFrame(n),n=null)}),be.easing(Hh.Easing.Cubic.InOut),be.start(),J()}else{var x=y.min.clone().add(y.max.clone()).multiplyScalar(.5);let oe=e.camera.position.clone().sub(s.controls.target.clone()).normalize();var b=x.clone().add(oe.multiplyScalar(2*y.max.distanceTo(y.min)));l(e.camera.position,b,s.controls.target.clone(),x)}};function l(y,x,_,S,b,E,w=1e3,M){var C;b&&E?(C=new Hh.Tween({x1:y.x,y1:y.y,z1:y.z,x2:_.x,y2:_.y,z2:_.z,_x:b._x,_y:b._y,_z:b._z,_w:b._w}),C.to({x1:x.x,y1:x.y,z1:x.z,x2:S.x,y2:S.y,z2:S.z,_x:E._x,_y:E._y,_z:E._z,_w:E._w},w)):(C=new Hh.Tween({x1:y.x,y1:y.y,z1:y.z,x2:_.x,y2:_.y,z2:_.z}),C.to({x1:x.x,y1:x.y,z1:x.z,x2:S.x,y2:S.y,z2:S.z},w)),C.onUpdate(function(P){s.controls&&(b&&E?(e.camera.quaternion._x=P._x,e.camera.quaternion._y=P._y,e.camera.quaternion._z=P._z,e.camera.quaternion._w=P._w):s.controls.auto=!0,e.camera.position.x=P.x1,e.camera.position.y=P.y1,e.camera.position.z=P.z1,s.controls.target.x=P.x2,s.controls.target.y=P.y2,s.controls.target.z=P.z2,s.controls.update(),i.RenderScene())}),C.onComplete(function(P){s.controls&&(s.controls.auto=!1,i.RenderScene(),M&&M(!0),cancelAnimationFrame(n),n=null)}),C.easing(Hh.Easing.Cubic.InOut);function I(P){n=requestAnimationFrame(I),C.update()}C.start(),I()}function c(){r=document.createElement("div"),r.className="ViewCube",t.appendChild(r),a=document.createElement("div"),a.className="viewSettingWrapper",a.innerHTML="...",r.appendChild(a);var y=document.createElement("div");y.className="homeViewWrapper",y.addEventListener("mousedown",function(){console.log("归位"),i.CameraGoHome()}),r.appendChild(y);const x=document.createElement("div");x.className="cameraToggleWrapper",x.title="切换正交/透视视图",x.innerHTML="⊞",x.addEventListener("mousedown",function(w){w.stopPropagation(),console.log("切换视图"),i.ToggleCameraType(),b()}),r.appendChild(x);const _=document.createElement("div");_.className="screenshotWrapper",_.title="截图",_.innerHTML="📷",_.addEventListener("mousedown",function(w){w.stopPropagation(),console.log("截图"),i.TakeScreenshot(),b()}),r.appendChild(_);const S=document.createElement("div");S.className="fullscreenWrapper",S.title="全屏",S.innerHTML="⛶",S.addEventListener("mousedown",function(w){w.stopPropagation(),console.log("全屏"),i.ToggleFullscreen(),b()}),r.appendChild(S),a.addEventListener("mousedown",function(w){w.stopPropagation(),x.classList.contains("show")?(b(),console.log("隐藏功能按钮")):(E(),console.log("显示功能按钮"))});function b(){x.classList.remove("show"),_.classList.remove("show"),S.classList.remove("show")}function E(){x.classList.add("show"),_.classList.add("show"),S.classList.add("show")}}function h(){i.sceneOrtho=oB();var _=t.clientWidth,S=t.clientWidth,y=_>S?_/S:S/_,x=300;i.camera=new rn(x*y/-2,x*y/2,x/2,x/-2,.01,1e4);var _=r.clientWidth,S=r.clientHeight,b=new mh({alpha:!0});b.setSize(_,S),b.setClearAlpha(0),i.sceneOrtho.renderer=b;let E=new xl(16777215,.8);i.sceneOrtho.add(E),lB(r,b),i.orbitControls=new qU(i.camera,r),i.orbitControls.enableZoom=!1,i.orbitControls.enablePan=!1,i.orbitControls.enableDamping=!0,i.orbitControls.dampingFactor=.1,i.orbitControls.rotateSpeed=.5,i.orbitControls.addEventListener("start",p),i.orbitControls.addEventListener("change",u),i.orbitControls.addEventListener("end",v)}let d=!1;function p(){d=!0,s.controls&&(i._mainTarget=s.controls.target.clone(),i._mainDistance=e.camera.position.distanceTo(s.controls.target))}function u(){if(d){if(e.camera.quaternion.copy(i.camera.quaternion),s.controls&&i._mainTarget&&i._mainDistance){const y=new R(0,0,1).applyQuaternion(e.camera.quaternion);e.camera.position.copy(i._mainTarget.clone().add(y.multiplyScalar(i._mainDistance))),s.controls.update()}s.renderer&&e.camera&&s.renderer.render(e,e.camera)}}function v(){d=!1,i._mainTarget=null,i._mainDistance=null}function g(){const y="/assets/viewcube/";let x=[{label:"右",icon:y+"cn_right.png"},{label:"左",icon:y+"cn_left.png"},{label:"顶",icon:y+"cn_top.png"},{label:"底",icon:y+"cn_bottom.png"},{label:"前",icon:y+"cn_front.png"},{label:"后",icon:y+"cn_back.png"}];var _=[];for(const E of x)_.push(new Dt({color:16777215,map:new qa().load(E.icon)}));new Ug({color:255});var S=new ht(new fs(110,110,110),_);i.sceneOrtho.add(S),m(122);let b={x:0,y:0};r.addEventListener("mousedown",E=>{b.x=E.clientX,b.y=E.clientY}),r.addEventListener("mouseup",E=>{if(d)return;const w=E.clientX-b.x,M=E.clientY-b.y;if(Math.sqrt(w*w+M*M)>5)return;var C={};C.x=E.offsetX/r.clientWidth*2-1,C.y=-(E.offsetY/r.clientHeight)*2+1;var I=new Qn;I.setFromCamera(C,i.camera);const P=I.intersectObjects(o,!1);P.length>0&&i.ToggleDirectionView(P[0].object.name)}),r.addEventListener("mousemove",E=>{var w={};w.x=E.offsetX/r.clientWidth*2-1,w.y=-(E.offsetY/r.clientHeight)*2+1;var M=new Qn;M.setFromCamera(w,i.camera);const C=M.intersectObjects(o,!1);for(var I of o)I.material.opacity=.01;C.length>0&&(C[0].object.material.opacity=.2)})}function m(y){for(var x=y*.5-20,_=[{name:"right",a:30,b:75,c:75,point:new R(x,0,0)},{name:"back",a:75,b:75,c:30,point:new R(0,0,-x)},{name:"left",a:30,b:75,c:75,point:new R(-x,0,0)},{name:"front",a:75,b:75,c:30,point:new R(0,0,x)},{name:"top",a:75,b:30,c:75,point:new R(0,x,0)},{name:"button",a:75,b:30,c:75,point:new R(0,-x,0)}],S=[{name:"top_right_back",a:30,b:30,c:30,point:new R(-x,x,x)},{name:"button_front_right",a:30,b:30,c:30,point:new R(-x,-x,x)},{name:"top_front_right",a:30,b:30,c:30,point:new R(x,x,x)},{name:"button_right_back",a:30,b:30,c:30,point:new R(x,-x,x)},{name:"top_back_left",a:30,b:30,c:30,point:new R(-x,x,-x)},{name:"button_back_left",a:30,b:30,c:30,point:new R(-x,-x,-x)},{name:"top_left_front",a:30,b:30,c:30,point:new R(x,x,-x)},{name:"button_left_front",a:30,b:30,c:30,point:new R(x,-x,-x)}],b=[{name:"top_front",a:30,b:30,c:75,point:new R(x,x,0)},{name:"top_right",a:75,b:30,c:30,point:new R(0,x,x)},{name:"top_back",a:30,b:30,c:75,point:new R(-x,x,0)},{name:"top_left",a:75,b:30,c:30,point:new R(0,x,-x)},{name:"button_front",a:30,b:30,c:75,point:new R(x,-x,0)},{name:"button_right",a:75,b:30,c:30,point:new R(0,-x,x)},{name:"button_back",a:30,b:30,c:75,point:new R(-x,-x,0)},{name:"button_left",a:75,b:30,c:30,point:new R(0,-x,-x)},{name:"front_right",a:30,b:75,c:30,point:new R(x,0,x)},{name:"right_back",a:30,b:75,c:30,point:new R(-x,0,x)},{name:"back_left",a:30,b:75,c:30,point:new R(-x,0,-x)},{name:"left_front",a:30,b:75,c:30,point:new R(x,0,-x)}],E=0;E<_.length;E++)o.push(f(_[E]));for(var E=0;Ei.url==e.url);this.cubeTool.zoomToBox(t.nodesMap.get(e.id).infos[0].box)}catch{}}hide(){}}function dB(s){let e=new Object;return e.getBoundingBox=function(){let t=s.models,i=new R(1e8,1e9,1e10),n=new R(-1e8,-1e9,-1e10);t.forEach(d=>{let p=d.boundingBox.min,u=d.boundingBox.max;p.xn.x&&(n.x=u.x),u.y>n.y&&(n.y=u.y),u.z>n.z&&(n.z=u.z)});let r=Math.min(i.x,n.x),a=Math.min(i.y,n.y),o=Math.min(i.z,n.z),l=Math.max(i.x,n.x),c=Math.max(i.y,n.y),h=Math.max(i.z,n.z);return{min:new R(r,a,o),max:new R(l,c,h)}},e.rayInterationModel=function(t,i){let n=[];return s.engineStatus.models.forEach(a=>{a.info.lods.forEach(o=>{let l=o.octreeBox;r(t,l,a)})}),n=n.filter(a=>a instanceof ht),t.intersectObjects(n,!1);function r(a,o,l){if(o==null)return;let c=new R(o.min.X*.3048,o.min.Z*.3048,-o.min.Y*.3048),h=new R(o.max.X*.3048,o.max.Z*.3048,-o.max.Y*.3048),d=new R(Math.min(c.x,h.X),Math.min(c.y,h.y),Math.min(c.z,h.z)),p=new R(Math.max(h.x,c.x),Math.max(h.y,c.y),Math.max(h.z,c.z)),u=new vt(d,p),v=a.ray.intersectsBox(u);if(!(v==null||v==!1))if(o.children==null||o.children.length==0){if(o.elements!=null)for(var g of o.elements){if(!s.engineStatus.isFree&&i==!1)continue;let m=s.engineStatus.hideModels.find(x=>x.url==l.url)?.ids;if(m!=null&&m.includes(g))continue;let f=s.engineStatus.translucentModels.find(x=>x.url==l.url)?.ids;if(f!=null&&f.includes(g))continue;let y=s.models.find(x=>x.url==l.url).nodesMap.get(g);y!=null&&!y.instance&&y.infos.map(x=>x.mesh).forEach(x=>{n.push(x)})}}else{if(o.elements!=null)for(var g of o.elements){let f=s.engineStatus.hideModels.find(_=>_.url==l.url)?.ids;if(f!=null&&f.includes(g))continue;let y=s.engineStatus.translucentModels.find(_=>_.url==l.url)?.ids;if(y!=null&&y.includes(g))continue;let x=s.models.find(_=>_.url==l.url).nodesMap.get(g);x!=null&&!x.instance&&x.infos.map(_=>_.mesh).forEach(_=>{n.push(_)})}for(let m of o.children)r(a,m,l)}}},e}class uB{engine;isDrawing=!1;startPoint=new me;endPoint=new me;selectionBox=null;worldToScreen=null;boundMouseDown;boundMouseMove;boundMouseUp;boundKeyDown;constructor(e){this.engine=e,this.boundMouseDown=this.onMouseDown.bind(this),this.boundMouseMove=this.onMouseMove.bind(this),this.boundMouseUp=this.onMouseUp.bind(this),this.boundKeyDown=this.onKeyDown.bind(this)}init(){this.createSelectionBoxElement(),this.engine.scene&&this.engine.camera&&this.engine.renderer&&(this.worldToScreen=new zt(this.engine.camera,this.engine.renderer,this.engine.scene))}active(){this.engine.controlModule.disActive();const e=this.engine.renderer?.domElement;e&&(e.addEventListener("mousedown",this.boundMouseDown),e.addEventListener("mousemove",this.boundMouseMove),e.addEventListener("mouseup",this.boundMouseUp),e.style.cursor="crosshair"),window.addEventListener("keydown",this.boundKeyDown)}disActive(){this.engine.controlModule.active();const e=this.engine.renderer?.domElement;e&&(e.removeEventListener("mousedown",this.boundMouseDown),e.removeEventListener("mousemove",this.boundMouseMove),e.removeEventListener("mouseup",this.boundMouseUp),e.style.cursor="default"),window.removeEventListener("keydown",this.boundKeyDown),this.isDrawing&&this.endDrawing()}createSelectionBoxElement(){this.selectionBox=document.createElement("div"),this.selectionBox.style.position="absolute",this.selectionBox.style.border="2px dashed #00aaff",this.selectionBox.style.backgroundColor="rgba(0, 170, 255, 0.1)",this.selectionBox.style.pointerEvents="none",this.selectionBox.style.display="none",this.selectionBox.style.zIndex="1000",this.selectionBox.style.boxSizing="border-box";const e=this.engine.renderer?.domElement;e&&e.parentElement&&e.parentElement.appendChild(this.selectionBox)}onMouseDown(e){e.button!==0||!this.engine.renderer?.domElement||(this.startPoint.set(e.offsetX,e.offsetY),this.endPoint.copy(this.startPoint),this.isDrawing=!0,this.selectionBox&&(this.selectionBox.style.display="block",this.updateSelectionBoxUI()),e.preventDefault(),e.stopPropagation())}onMouseMove(e){!this.isDrawing||!this.engine.renderer?.domElement||(this.endPoint.set(e.offsetX,e.offsetY),this.updateSelectionBoxUI(),e.preventDefault(),e.stopPropagation())}onMouseUp(e){this.isDrawing&&(this.endDrawing(),this.performZoom(),e.preventDefault(),e.stopPropagation(),this.disActive())}onKeyDown(e){e.key==="Escape"&&(this.disActive(),e.preventDefault(),e.stopPropagation())}endDrawing(){this.isDrawing&&(this.isDrawing=!1,this.selectionBox&&(this.selectionBox.style.display="none"))}updateSelectionBoxUI(){if(!this.selectionBox||!this.engine.renderer?.domElement)return;const e=Math.min(this.startPoint.x,this.endPoint.x),t=Math.min(this.startPoint.y,this.endPoint.y),i=Math.abs(this.endPoint.x-this.startPoint.x),n=Math.abs(this.endPoint.y-this.startPoint.y);this.selectionBox.style.left=`${e}px`,this.selectionBox.style.top=`${t}px`,this.selectionBox.style.width=`${i}px`,this.selectionBox.style.height=`${n}px`}performZoom(){const e=Math.abs(this.endPoint.x-this.startPoint.x),t=Math.abs(this.endPoint.y-this.startPoint.y);if(e<5||t<5)return;if(!this.worldToScreen){console.warn("RangeScale: 坐标转换工具未初始化");return}const i=Math.min(this.startPoint.x,this.endPoint.x),n=Math.max(this.startPoint.x,this.endPoint.x),r=Math.min(this.startPoint.y,this.endPoint.y),a=Math.max(this.startPoint.y,this.endPoint.y),o=[],l=[{x:i,y:r},{x:n,y:r},{x:n,y:a},{x:i,y:a}];for(const h of l){const d=this.worldToScreen.screenToWorld(h.x,h.y);d&&o.push(d)}if(o.length<3){console.warn("RangeScale: 框选区域未命中模型,无法执行缩放操作");return}if(o.length<3){console.warn("RangeScale: 无法将屏幕区域转换为世界坐标");return}const c=new vt;for(const h of o)c.expandByPoint(h);if(c.isEmpty()){console.warn("RangeScale: 计算得到的包围盒无效");return}this.fitCameraToBoundingBox(c)}fitCameraToBoundingBox(e){const t=this.engine.camera,i=this.engine.controls;if(!t||!i){console.warn("RangeScale: 相机或控制器未初始化");return}const n=new R;e.getCenter(n);const r=new R;e.getSize(r);const a=Math.max(r.x,r.y,r.z);if(t instanceof ai){const o=t.fov*(Math.PI/180),l=a/(2*Math.tan(o/2))*1.2,c=new R;t.getWorldDirection(c);const h=n.clone().sub(t.position);c.dot(h.normalize())<0&&c.negate();const d=n.clone().sub(c.multiplyScalar(l));t.position.copy(d),i.target&&i.target.copy(n),t.lookAt(n),i.update()}else if(t instanceof rn){const o=a*1.2,l=this.engine.renderer?.domElement,c=l?l.width/l.height:1;t.left=-o*c/2,t.right=o*c/2,t.top=o/2,t.bottom=-o/2,t.updateProjectionMatrix();const h=new R;t.getWorldDirection(h);const d=a*1.5,p=n.clone().sub(h.multiplyScalar(d));t.position.copy(p),i.target&&i.target.copy(n),t.lookAt(n),i.update()}}}const bw={render:{mode:"advanced",contrast:50,saturation:50,shadowIntensity:50,lightIntensity:50,gtaoIntensity:50},display:{showEdge:!1,edgeOpacity:30,showGrid:!1,showLevel:!1,showGround:!1,groundId:"0",groundHeight:0},environment:{type:"none",hdrId:"0",hdrIntensity:20,skyPreset:"sunrise_clear",skyParams:{},skyIntensity:20}};class pB{engine;settings;environmentApplyVersion=0;constructor(e){this.engine=e,this.settings=this._clone(bw)}init(){}getSettings(){return this._clone(this.settings)}getPresetLists(){const e=this.engine.ground?.getGroundList()||[],t=this.engine.hdr?.getHdrList()||[],i=this.engine.skyManager?.getPresetList()||[];return{ground:e.map(n=>this._toPresetItem(n)),hdr:t.map(n=>this._toPresetItem(n)),sky:i.map(n=>this._toPresetItem(n))}}async setSettings(e){e.render&&(Object.assign(this.settings.render,e.render),this._applyRenderSettings(this.settings.render)),e.display&&(Object.assign(this.settings.display,e.display),this._applyDisplaySettings(this.settings.display)),e.environment&&(this._mergeEnvironmentSettings(e.environment),await this._applyEnvironmentSettings(this._clone(this.settings.environment)))}async resetToDefault(){this.settings=this._clone(bw),this._applyRenderSettings(this.settings.render),this._applyDisplaySettings(this.settings.display),await this._applyEnvironmentSettings(this._clone(this.settings.environment))}setRenderMode(e){this.settings.render.mode=e,this.engine.engineModelModule?.switchModel(e)}setContrast(e){this.settings.render.contrast=e,this.engine.engineModelModule?.setContrastValue(.5+e/100)}setSaturation(e){this.settings.render.saturation=e,this.engine.engineModelModule?.setSaturationValue(.5+e/100)}setShadowIntensity(e){this.settings.render.shadowIntensity=e,this._updateDirectionalLight(t=>{t.shadow.intensity=e/100*2})}setLightIntensity(e){this.settings.render.lightIntensity=e,this.setAmbientLightIntensity(e/100)}setGTAOIntensity(e){this.settings.render.gtaoIntensity=e,this.engine.engineModelModule?.setGTAOIntensity(e/100)}setShowEdge(e){this.settings.display.showEdge=e,e?this.engine.modelEdge?.active():this.engine.modelEdge?.disActive()}setEdgeOpacity(e){this.settings.display.edgeOpacity=e,this.engine.modelEdge?.setOpacity(e/100)}setShowGrid(e){this.settings.display.showGrid=e,e?this.engine.grid?.show():this.engine.grid?.hide()}setShowLevel(e){this.settings.display.showLevel=e,e?this.engine.level?.show():this.engine.level?.hide()}setShowGround(e){this.settings.display.showGround=e,e?this.engine.ground?.show():this.engine.ground?.hide()}setGroundId(e){this.settings.display.groundId=e,this.engine.ground?.setGround(e)}setGroundHeight(e){this.settings.display.groundHeight=e,this.engine.ground?.setHeight(e)}async setEnvironmentType(e){this.settings.environment.type=e,await this._applyEnvironmentSettings(this._clone(this.settings.environment))}async setHdrId(e){this.settings.environment.hdrId=e,this.settings.environment.type==="hdr"&&await this._applyEnvironmentSettings(this._clone(this.settings.environment))}setHdrIntensity(e){this.settings.environment.hdrIntensity=e,this.settings.environment.type==="hdr"&&this.engine.hdr?.setIntensity(e/100)}setSkyPreset(e){this.settings.environment.skyPreset=e,this.settings.environment.skyParams={},this.settings.environment.type==="sky"&&this.engine.skyManager?.setPreset(e)}setSkyParams(e){this.settings.environment.skyParams=this._clone(e),this.settings.environment.type==="sky"&&this.engine.skyManager?.setParams(this.settings.environment.skyParams)}setSkyIntensity(e){this.settings.environment.skyIntensity=e,this.settings.environment.type==="sky"&&this.engine.skyManager?.setIntensity(e/100)}setAmbientLightIntensity(e){const t=this.engine.scene?.children.find(i=>i instanceof xl);t&&(t.intensity=e)}_applyRenderSettings(e){this.setRenderMode(e.mode),this.setContrast(e.contrast),this.setSaturation(e.saturation),this.setShadowIntensity(e.shadowIntensity),this.setLightIntensity(e.lightIntensity),this.setGTAOIntensity(e.gtaoIntensity)}_applyDisplaySettings(e){this.setShowEdge(e.showEdge),this.setEdgeOpacity(e.edgeOpacity),this.setShowGrid(e.showGrid),this.setShowLevel(e.showLevel),this.setShowGround(e.showGround),this.setGroundId(e.groundId),this.setGroundHeight(e.groundHeight)}async _applyEnvironmentSettings(e){const t=++this.environmentApplyVersion;if(await this.engine.hdr?.setHdr("0"),t===this.environmentApplyVersion&&(this.engine.skyManager?.close(!0),t===this.environmentApplyVersion))switch(e.type){case"none":break;case"hdr":if(e.hdrId!=="0"){if(await this.engine.hdr?.setHdr(e.hdrId),t!==this.environmentApplyVersion){this._applyEnvironmentSettings(this._clone(this.settings.environment));return}this.engine.hdr?.setIntensity(e.hdrIntensity/100)}break;case"sky":this.engine.skyManager?.activate(),this.engine.skyManager?.setPreset(e.skyPreset),Object.keys(e.skyParams).length>0&&this.engine.skyManager?.setParams(this._clone(e.skyParams)),this.engine.skyManager?.setIntensity(e.skyIntensity/100);break}}_updateDirectionalLight(e){const t=this.engine.scene?.children.find(i=>i instanceof Zr);t&&e(t)}_mergeEnvironmentSettings(e){Object.assign(this.settings.environment,e),e.skyPreset!==void 0&&e.skyParams===void 0&&(this.settings.environment.skyParams={}),e.skyParams!==void 0&&(this.settings.environment.skyParams=this._clone(e.skyParams))}_toPresetItem(e){const t=Array.isArray(e.names)?[...e.names]:[];return{id:e.id,name:t[0]??e.id,names:t}}_clone(e){return JSON.parse(JSON.stringify(e))}}function Mr(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(s){var e=Math.random()*16|0,t=s=="x"?e:e&3|8;return t.toString(16)})}class Sr{engine;handelBehaved;setting;constructor(e){this.engine=e,this.handelBehaved=Yv(e),this.handelBehaved.init(this,null),this.setting={unit:"m",precision:3}}getSetting(){return this.setting}saveSetting(e){this.setting=e}active(){this.handelBehaved.active()}disActive(){this.handelBehaved.disActive()}getMeasureText(e,t){if(e==null)return null;let i=this.setting.unit,n=i;return t==1?i=="mm"?e=e*1e3:i=="cm"?e=e*100:i=="dm"?e=e*10:i=="m"?e=e*1:i=="km"&&(e=e*.001):t==2&&(i=="mm"?e=e*1e3*1e3:i=="cm"?e=e*100*100:i=="dm"?e=e*10*10:i=="m"?e=e*1*1:i=="km"&&(e=e*.001*.001),n=n+"²"),e.toFixed(this.setting.precision)+" "+n}cancelCurrentSelectedAnnotation(){let e=this.engine.measure.annotationData;for(let t in e)e[t].forEach(i=>{i.highlight==!0&&(i.highlight=!1,i.container.classList.remove("Hight"),i.container.getElementsByTagName("svg")[0].classList.remove("Hight"))})}handelKeyEscDown(){this.cancelCurrentSelectedAnnotation();let e=this.engine.measure.annotationData;for(let t in e)for(let i=e[t].length-1;i>=0;i--){let n=e[t][i];n.isSelect==!0&&(n.container.remove(),e[t].splice(i,1))}this.engine.measure.clearAllPoints()}handelKeyDeleteDown(){let e=this.engine.measure.annotationData;for(let t in e)for(let i=e[t].length-1;i>=0;i--){let n=e[t][i];n.highlight==!0&&(n.container.remove(),e[t].splice(i,1))}}clearHighlight(){let e=this.engine.measure.annotationData;for(let t in e)e[t].forEach(i=>{i.highlight=!1,i.container.classList.remove("Hight"),i.container.getElementsByTagName("svg")[0].classList.remove("Hight")})}drawNormalAnnotation(){let e=this;this.engine.measure.annotationData.normalAnnotation.forEach(l=>{o(l)}),this.engine.measure.annotationData.elevationAnnotation.forEach(l=>{a(l)}),this.engine.measure.annotationData.coordinateAnnotation.forEach(l=>{r(l)}),this.engine.measure.annotationData.angleAnnotation.forEach(l=>{t(l)}),this.engine.measure.annotationData.areaAnnotation.forEach(l=>{i(l)}),this.engine.measure.annotationData.slopeAnnotation.forEach(l=>{n(l)});function t(l){if(l.container==null){let f=['','','','','','','',''+l.text+"",""].join("");l.container=document.createElement("div"),l.container.className="angle-annotation",l.container.id=l.id,l.container.style.pointerEvents="none",l.container.innerHTML=f,e.engine.measure.annotationContainer.appendChild(l.container),l.container.getElementsByTagName("svg")[0].addEventListener("click",function(){e.clearHighlight(),l.container.getElementsByTagName("svg")[0].classList.add("Hight"),l.highlight=!0,e.engine.events.trigger(di.MeasureClick,l)}),l.isSelect&&(l.container.getElementsByTagName("svg")[0].classList.add("Hight"),l.highlight=!0)}let c=new zt(e.engine.camera,e.engine.renderer,e.engine.scene).worldToScreen(l.point1),h=new zt(e.engine.camera,e.engine.renderer,e.engine.scene).worldToScreen(l.point2),d=new zt(e.engine.camera,e.engine.renderer,e.engine.scene).worldToScreen(l.point3),p=e.engine.reactBoundingClientRect.left,u=e.engine.reactBoundingClientRect.top;c.x+=p,c.y+=u,h.x+=p,h.y+=u,d.x+=p,d.y+=u;let v=l.container;v.getElementsByTagName("circle")[0].setAttribute("cx",c.x),v.getElementsByTagName("circle")[0].setAttribute("cy",c.y),v.getElementsByTagName("circle")[1].setAttribute("cx",h.x),v.getElementsByTagName("circle")[1].setAttribute("cy",h.y),v.getElementsByTagName("circle")[2].setAttribute("cx",d.x),v.getElementsByTagName("circle")[2].setAttribute("cy",d.y),v.getElementsByTagName("polyline")[0].setAttribute("points",c.x+","+c.y+" "+h.x+","+h.y),v.getElementsByTagName("polyline")[1].setAttribute("points",h.x+","+h.y+" "+d.x+","+d.y);let g=h.x,m=h.y-30;v.getElementsByTagName("rect")[0].setAttribute("x",g-40),v.getElementsByTagName("rect")[0].setAttribute("y",m-12.5),v.getElementsByTagName("text")[0].setAttribute("x",g),v.getElementsByTagName("text")[0].setAttribute("y",m+4),v.getElementsByTagName("text")[0].innerHTML=l.text,v.style.top="0px",v.style.left="0px"}function i(l){if(l.container==null){let y=['','','','',''+e.getMeasureText(l.text,2)+"",""].join("");l.container=document.createElement("div"),l.container.className="area-annotation",l.container.id=l.id,l.container.innerHTML=y,e.engine.measure.annotationContainer.appendChild(l.container),l.container.getElementsByTagName("svg")[0].addEventListener("click",function(){e.clearHighlight(),l.container.getElementsByTagName("svg")[0].classList.add("Hight"),l.highlight=!0,e.engine.events.trigger(di.MeasureClick,l)}),l.isSelect&&(l.container.getElementsByTagName("svg")[0].classList.add("Hight"),l.highlight=!0)}if(!l.points||l.points.length<3)return;let c=e.engine.reactBoundingClientRect.left,h=e.engine.reactBoundingClientRect.top,d=[],p=0,u=0;for(let y=0;yy.x+","+y.y).join(" "),g=l.container;g.getElementsByTagName("polygon")[0].setAttribute("points",v),g.getElementsByTagName("polyline")[0].setAttribute("points",v);let m=p,f=u;g.getElementsByTagName("rect")[0].setAttribute("x",m-40),g.getElementsByTagName("rect")[0].setAttribute("y",f-12.5),g.getElementsByTagName("text")[0].setAttribute("x",m),g.getElementsByTagName("text")[0].setAttribute("y",f+4),g.getElementsByTagName("text")[0].innerHTML=e.getMeasureText(l.text,2),g.style.top="0px",g.style.left="0px"}function n(l){if(l.container==null){let m=['',"",'','',"","",'','',''+l.text+"",""].join("");l.container=document.createElement("div"),l.container.className="slope-annotation",l.container.id=l.id,l.container.innerHTML=m,e.engine.measure.annotationContainer.appendChild(l.container),l.container.getElementsByTagName("svg")[0].addEventListener("click",function(){e.clearHighlight(),l.container.getElementsByTagName("svg")[0].classList.add("Hight"),l.highlight=!0,e.engine.events.trigger(di.MeasureClick,l)}),l.isSelect&&(l.container.getElementsByTagName("svg")[0].classList.add("Hight"),l.highlight=!0)}let c=new zt(e.engine.camera,e.engine.renderer,e.engine.scene).worldToScreen(l.point1),h=new zt(e.engine.camera,e.engine.renderer,e.engine.scene).worldToScreen(l.point2),d=e.engine.reactBoundingClientRect.left,p=e.engine.reactBoundingClientRect.top;c.x+=d,c.y+=p,h.x+=d,h.y+=p;let u=l.container;u.getElementsByTagName("polyline")[0].setAttribute("points",c.x+","+c.y+" "+h.x+","+h.y);let v=(c.x+h.x)/2,g=(c.y+h.y)/2-30;u.getElementsByTagName("rect")[0].setAttribute("x",v-50),u.getElementsByTagName("rect")[0].setAttribute("y",g-12.5),u.getElementsByTagName("text")[0].setAttribute("x",v),u.getElementsByTagName("text")[0].setAttribute("y",g+4),u.getElementsByTagName("text")[0].innerHTML=l.text,u.style.top="0px",u.style.left="0px"}function r(l){if(l.container==null){let f=['','','','X: '+e.getMeasureText(l.textX,1)+"",'','Y: '+e.getMeasureText(-l.textZ,1)+"",'','Z: '+e.getMeasureText(l.textY,1)+"",""].join("");l.container=document.createElement("div"),l.container.className="coordinate-annotation",l.container.id=l.id,l.container.style.position="absolute",l.container.style.pointerEvents="none",l.container.innerHTML=f,e.engine.measure.annotationContainer.appendChild(l.container),l.container.getElementsByTagName("svg")[0].addEventListener("click",function(){e.clearHighlight(),l.container.getElementsByTagName("svg")[0].classList.add("Hight"),l.highlight=!0,e.engine.events.trigger(di.MeasureClick,l)}),l.isSelect&&(l.container.getElementsByTagName("svg")[0].classList.add("Hight"),l.highlight=!0)}let c=l.container,h=new zt(e.engine.camera,e.engine.renderer,e.engine.scene).worldToScreen(l.point),d=e.engine.reactBoundingClientRect.left,p=e.engine.reactBoundingClientRect.top;h.x+=d,h.y+=p,c.style.top="0px",c.style.left="0px";let u=c.getElementsByTagName("circle")[0];u&&(u.setAttribute("cx",h.x),u.setAttribute("cy",h.y));let v=c.getElementsByTagName("rect"),g=c.getElementsByTagName("text"),m=-55;v[0]&&(v[0].setAttribute("x",h.x+10),v[0].setAttribute("y",h.y+10+m)),g[0]&&(g[0].setAttribute("x",h.x+10+40),g[0].setAttribute("y",h.y+10+16+m)),v[1]&&(v[1].setAttribute("x",h.x+10),v[1].setAttribute("y",h.y+10+30+m)),g[1]&&(g[1].setAttribute("x",h.x+10+40),g[1].setAttribute("y",h.y+10+46+m)),v[2]&&(v[2].setAttribute("x",h.x+10),v[2].setAttribute("y",h.y+10+60+m)),g[2]&&(g[2].setAttribute("x",h.x+10+40),g[2].setAttribute("y",h.y+10+76+m)),g[0]&&(g[0].innerHTML="X: "+e.getMeasureText(l.textX,1)),g[1]&&(g[1].innerHTML="Y: "+e.getMeasureText(-l.textZ,1)),g[2]&&(g[2].innerHTML="Z: "+e.getMeasureText(l.textY,1))}function a(l){if(l.container==null){let u=['','',''+e.getMeasureText(l.text,1)+"",'',""].join("");l.container=document.createElement("div"),l.container.className="elevation-annotation",l.container.id=l.id,l.container.style.position="absolute",l.container.style.pointerEvents="none",l.container.innerHTML=u,e.engine.measure.annotationContainer.appendChild(l.container),l.container.getElementsByTagName("svg")[0].addEventListener("click",function(){e.clearHighlight(),l.container.getElementsByTagName("svg")[0].classList.add("Hight"),l.highlight=!0,e.engine.events.trigger(di.MeasureClick,l)}),l.isSelect&&(l.container.getElementsByTagName("svg")[0].classList.add("Hight"),l.highlight=!0)}let c=l.container,h=new zt(e.engine.camera,e.engine.renderer,e.engine.scene).worldToScreen(l.point),d=e.engine.reactBoundingClientRect.left,p=e.engine.reactBoundingClientRect.top;c.style.top=h.y+p-48+"px",c.style.left=h.x+d-16+"px",c.getElementsByTagName("text")[0].innerHTML=e.getMeasureText(l.text,1)}function o(l){if(l.container==null){let v=['','','','','',''+e.getMeasureText(l.text,1)+"",""].join("");l.container=document.createElement("div"),l.container.className="normal-annotation",l.container.id=l.id,l.container.innerHTML=v,e.engine.measure.annotationContainer.appendChild(l.container),l.container.getElementsByTagName("svg")[0].addEventListener("click",function(){e.clearHighlight(),l.container.getElementsByTagName("svg")[0].classList.add("Hight"),l.highlight=!0,e.engine.events.trigger(di.MeasureClick,l)}),l.isSelect&&(l.container.getElementsByTagName("svg")[0].classList.add("Hight"),l.highlight=!0)}let c=l.container;if(l.point1==null||l.point2==null){c.style.display="none";return}else c.style.display="block";let h=new zt(e.engine.camera,e.engine.renderer,e.engine.scene).worldToScreen(l.point1),d=new zt(e.engine.camera,e.engine.renderer,e.engine.scene).worldToScreen(l.point2),p=e.engine.reactBoundingClientRect.left,u=e.engine.reactBoundingClientRect.top;h.x+=p,h.y+=u,d.x+=p,d.y+=u,c.getElementsByTagName("polyline")[0].setAttribute("points",h.x+","+h.y+" "+d.x+","+d.y),c.getElementsByTagName("circle")[0].setAttribute("cx",h.x),c.getElementsByTagName("circle")[0].setAttribute("cy",h.y),c.getElementsByTagName("circle")[1].setAttribute("cx",d.x),c.getElementsByTagName("circle")[1].setAttribute("cy",d.y),c.getElementsByTagName("rect")[0].setAttribute("x",h.x*.5+d.x*.5-40),c.getElementsByTagName("rect")[0].setAttribute("y",h.y*.5+d.y*.5-12.5),c.getElementsByTagName("text")[0].setAttribute("x",h.x*.5+d.x*.5+40-40),c.getElementsByTagName("text")[0].setAttribute("y",h.y*.5+d.y*.5+16-12.5),c.getElementsByTagName("text")[0].innerHTML=e.getMeasureText(l.text,1),c.style.top="0px",c.style.left="0px"}}}class fB{engine;isActive=!1;tools;points=[];behavior;catchDir=0;type="point";constructor(e){this.engine=e,this.tools=new Sr(e)}active(){this.engine.measure.tools.cancelCurrentSelectedAnnotation(),this.isActive=!0,this.behavior=this.engine.handelBehaved,this.behavior.init(this),this.behavior.active();let e=this.engine.measure.annotationData.normalAnnotation.find(t=>t.isSelect==!0);e!=null&&(e.isSelect=!1)}disActive(){this.isActive=!1,this.behavior?.disActive()}clearAllPoints(){this.points=[]}setDirection(e){this.catchDir=e}setSelectType(e){this.type=e}getMeshesMinMaxY(e){if(!Array.isArray(e)||e.length===0)return null;let t=Number.POSITIVE_INFINITY,i=Number.NEGATIVE_INFINITY;for(let n=0;ni&&(i=a.max.y))}return!Number.isFinite(t)||!Number.isFinite(i)?null:{minY:t,maxY:i}}handleMouseClick(e){if(e.catch==null)return;let t=e.catch.point;if(this.type=="element"){let r=this.engine.interactionModule.getCatchMeshs(e);var i=this.getMeshesMinMaxY(r);this.catchDir==0?t.set(t.x,i?.minY,t.z):t.set(t.x,i?.maxY,t.z)}else t=e.catch.point;if(this.points.length==0){this.engine.measure.tools.clearHighlight(),this.points.push(t);return}let n=this.engine.measure.annotationData.normalAnnotation.find(r=>r.isSelect==!0);n!=null&&(n.isSelect=!1)}handleMouseMove(e){if(e.catch==null||this.points.length==0)return;let t=this.engine.measure.annotationData.normalAnnotation.find(n=>n.isSelect==!0);t==null&&(t={text:null,id:Mr(),isSelect:!0,type:"clear-height"},this.engine.measure.annotationData.normalAnnotation.push(t));let i=e.catch;if(this.type=="element"){let n=e.catch.point.clone();n.set(n.x,this.points[0].y,n.z);let r=new Qn(n.add(new R(0,.01,0)),new R(0,this.catchDir==0?-1:1,0));i.point=this.points[0];const a=this.engine.clipping?.filterIntersectionsByClipping(this.engine.octreeBox.rayInterationModel(r))??this.engine.octreeBox.rayInterationModel(r);if(a.length===0){t.point2=null;return}t.point1=n,t.point2=a[0].point,t.text=t.point1.clone().distanceTo(t.point2.clone()),this.engine.events.trigger(di.MeasureChanged,t)}else{let n=new Qn(e.catch.point.clone().add(new R(0,.01,0)),new R(0,this.catchDir==0?-1:1,0));const r=this.engine.clipping?.filterIntersectionsByClipping(this.engine.octreeBox.rayInterationModel(n))??this.engine.octreeBox.rayInterationModel(n);if(r.length===0){t.point2=null;return}t.point1=i.point,t.point2=r[0].point,t.text=t.point1.clone().distanceTo(t.point2.clone()),this.engine.events.trigger(di.MeasureChanged,t)}}}class mB{engine;tools;isActive=!1;points=[];behavior;constructor(e){this.engine=e,this.tools=new Sr(e)}active(){this.engine.measure.tools.cancelCurrentSelectedAnnotation(),this.isActive=!0,this.points=[],this.behavior=this.engine.handelBehaved,this.behavior.init(this,{showCatch:!0}),this.behavior.active();let e=this.engine.measure.annotationData.normalAnnotation.find(t=>t.isSelect==!0);e!=null&&(e.isSelect=!1)}disActive(){this.points=[],this.isActive=!1,this.engine.handelBehaved.disActive()}clearAllPoints(){this.points=[]}handleMouseClick(e){if(e.catch==null)return;let t=e.catch;if(this.points.length==0)this.engine.measure.tools.clearHighlight(),this.points.push(t.point);else if(this.points.length==1){let i=this.engine.measure.annotationData.normalAnnotation.find(n=>n.isSelect==!0);if(i==null)return;i.point2=t.point,i.isSelect=!1,this.points=[],this.engine.events.trigger(di.MeasureChanged,i)}}handleMouseMove(e){if(e.catch==null)return;let t=e.catch;if(t!=null&&this.points.length==1){let i=this.engine.measure.annotationData.normalAnnotation.find(n=>n.isSelect==!0);i==null&&(i={id:Mr(),point1:this.points[0].clone(),point2:t.point.clone(),text:this.points[0].clone().distanceTo(t.point.clone()),type:"distance",isSelect:!0},this.engine.measure.annotationData.normalAnnotation.push(i)),i.point2=t.point,i.text=i.point1.clone().distanceTo(i.point2.clone())}}}class gB{engine;isActive=!1;tools;points=[];behavior;constructor(e){this.engine=e,this.tools=new Sr(e)}active(){this.engine.measure.tools.cancelCurrentSelectedAnnotation(),this.isActive=!0,this.behavior=this.engine.handelBehaved,this.behavior.init(this),this.behavior.active();let e=this.engine.measure.annotationData.normalAnnotation.find(t=>t.isSelect==!0);e!=null&&(e.isSelect=!1)}disActive(){this.isActive=!1,this.behavior?.disActive()}clearAllPoints(){this.points=[]}handleMouseClick(e){if(e.catch==null)return;if(this.points.length==0){this.engine.measure.tools.clearHighlight(),this.points.push(e.catch.point);return}let t=this.engine.measure.annotationData.normalAnnotation.find(i=>i.isSelect==!0);t!=null&&(t.isSelect=!1)}handleMouseMove(e){if(e.catch==null||this.points.length==0)return;let t=this.engine.measure.annotationData.normalAnnotation.find(a=>a.isSelect==!0);t==null&&(t={text:null,id:Mr(),isSelect:!0,type:"clear-distance"},this.engine.measure.annotationData.normalAnnotation.push(t));let i=new Qn(e.catch.point.clone().add(e.catch.face.normal.clone().setLength(.01)),e.catch.face.normal);const n=this.engine.clipping?.filterIntersectionsByClipping(this.engine.octreeBox.rayInterationModel(i))??this.engine.octreeBox.rayInterationModel(i);if(n.length==0){t.point2=null;return}let r=e.catch;t.point1=r.point,t.point2=n[0].point,t.text=t.point1.clone().distanceTo(t.point2.clone()),this.engine.events.trigger(di.MeasureChanged,t)}}class vB{engine;isActive=!1;tools;points=[];behavior;constructor(e){this.engine=e,this.tools=new Sr(e)}active(){this.engine.measure.tools.cancelCurrentSelectedAnnotation(),this.behavior=this.engine.handelBehaved,this.behavior.init(this,{showCatch:!0}),this.behavior.active(),this.isActive=!0;let e=this.engine.measure.annotationData.normalAnnotation.find(t=>t.isSelect==!0);e!=null&&(e.isSelect=!1)}disActive(){this.isActive=!1,this.behavior?.disActive()}clearAllPoints(){this.points=[]}handleMouseMove(e){if(e.catch==null)return;let t=this.engine.measure.annotationData.elevationAnnotation.find(i=>i.isSelect==!0);t==null&&(t={id:Mr(),point:e.catch.point.clone(),text:e.catch.point.y,isSelect:!0,type:"elevation"},this.engine.measure.annotationData.elevationAnnotation.push(t)),t.point=e.catch.point.clone(),t.text=e.catch.point.y}handleMouseClick(e){if(e.catch==null)return;this.engine.measure.tools.clearHighlight();let t=this.engine.measure.annotationData.elevationAnnotation.find(i=>i.isSelect==!0);t!=null&&(t.isSelect=!1,t.point=e.catch.point.clone(),t.text=e.catch.point.y,this.engine.events.trigger(di.MeasureChanged,t))}}class yB{engine;isActive=!1;tools;points=[];behavior;constructor(e){this.engine=e,this.tools=new Sr(e)}active(){this.engine.measure.tools.cancelCurrentSelectedAnnotation(),this.behavior=this.engine.handelBehaved,this.behavior.init(this,{showCatch:!0}),this.behavior.active(),this.isActive=!0;let e=this.engine.measure.annotationData.normalAnnotation.find(t=>t.isSelect==!0);e!=null&&(e.isSelect=!1)}disActive(){this.isActive=!1,this.behavior?.disActive()}clearAllPoints(){this.points=[]}handleMouseUp(e){this.engine.deviceType!="PC"&&this.createMeasure()}handleMouseMove(e){if(e.catch==null)return;let t=this.engine.measure.annotationData.coordinateAnnotation.find(i=>i.isSelect==!0);t==null&&(t={id:Mr(),point:e.catch.point.clone(),text:Math.round(e.catch.point.y)+" m",isSelect:!0,type:"point"},this.engine.measure.annotationData.coordinateAnnotation.push(t)),t.point=e.catch.point.clone(),t.textX=e.catch.point.x,t.textY=e.catch.point.y,t.textZ=e.catch.point.z}handleMouseClick(e){if(e.catch==null)return;this.engine.measure.tools.clearHighlight();let t=this.engine.measure.annotationData.coordinateAnnotation.find(i=>i.isSelect==!0);t!=null&&(t.point=e.catch.point.clone(),t.textX=e.catch.point.x,t.textY=e.catch.point.y,t.textZ=e.catch.point.z,t.isSelect=!1,this.engine.events.trigger(di.MeasureChanged,t))}createMeasure(){let e=this.engine.measure.annotationData.coordinateAnnotation.find(t=>t.isSelect==!0);e!=null&&(e.isSelect=!1,this.engine.events.trigger(di.MeasureChanged,e))}}class xB{engine;tools;points=[];behavior;constructor(e){this.engine=e,this.tools=new Sr(e)}active(){this.engine.measure.tools.cancelCurrentSelectedAnnotation(),this.points=[],this.behavior=this.engine.handelBehaved,this.behavior.init(this),this.behavior.active();let e=this.engine.measure.annotationData.normalAnnotation.find(t=>t.isSelect==!0);e!=null&&(e.isSelect=!1)}disActive(){this.points=[],this.behavior?.disActive()}clearAllPoints(){this.points=[]}calculateAngle(e,t,i){const n=new R().subVectors(e,t),r=new R().subVectors(i,t),a=n.length(),o=r.length();if(a===0||o===0)return 0;const l=n.dot(r)/(a*o),c=Math.max(-1,Math.min(1,l));return Math.acos(c)*(180/Math.PI)}handleMouseClick(e){if(e.catch==null)return;let t=e.catch;if(this.points.length==0)this.engine.measure.tools.clearHighlight(),this.points.push(t.point);else if(this.points.length==1)this.points.push(t.point);else if(this.points.length==2){let i=this.engine.measure.annotationData.angleAnnotation.find(n=>n.isSelect==!0);if(i==null)return;i.point3=t.point.clone(),i.angle=this.calculateAngle(i.point1,i.point2,i.point3),i.text=i.angle.toFixed(2)+"°",i.isSelect=!1,i.type="angle",this.points=[],this.engine.events.trigger(di.MeasureChanged,i)}}handleMouseMove(e){if(e.catch!=null&&this.points.length!=1&&this.points.length==2){let t=this.engine.measure.annotationData.angleAnnotation.find(i=>i.isSelect==!0);t==null&&(t={id:Mr(),point1:this.points[0].clone(),point2:this.points[1].clone(),point3:e.catch.point.clone(),angle:0,text:"0.00°",isSelect:!0,type:"angle"},this.engine.measure.annotationData.angleAnnotation.push(t)),t.point3=e.catch.point.clone(),t.angle=this.calculateAngle(t.point1,t.point2,t.point3),t.text=t.angle.toFixed(2)+"°",console.log("角度",t.text)}}}class _B{engine;tools;points=[];behavior;constructor(e){this.engine=e,this.tools=new Sr(e)}active(){this.engine.measure.tools.cancelCurrentSelectedAnnotation(),this.points=[],this.behavior=this.engine.handelBehaved,this.behavior.init(this),this.behavior.active();let e=this.engine.measure.annotationData.normalAnnotation.find(t=>t.isSelect==!0);e!=null&&(e.isSelect=!1)}disActive(){this.points=[],this.behavior?.disActive()}clearAllPoints(){this.points=[]}calculateArea(e){if(e.length<3)return 0;let t=0;const i=e.length;for(let n=0;n=3){let i=this.engine.measure.annotationData.areaAnnotation.find(n=>n.isSelect==!0);i==null?(i={id:Mr(),points:this.points.map(n=>n.clone()),area:0,text:0,isSelect:!0,type:"area"},this.engine.measure.annotationData.areaAnnotation.push(i)):(this.points.push(t.point.clone()),i.points=this.points.map(n=>n.clone())),i.area=this.calculateArea(i.points),i.text=i.area,console.log("面积",i.text)}else this.engine.measure.tools.clearHighlight()}handleMouseMove(e){if(e.catch!=null&&this.points.length>=2){let t=this.engine.measure.annotationData.areaAnnotation.find(i=>i.isSelect==!0);if(t==null){if(this.points.length>=2){let i=this.points.map(n=>n.clone());i.push(e.catch.point.clone()),i.length>=3&&(t={id:Mr(),points:i,area:0,text:0,isSelect:!0,type:"area"},this.engine.measure.annotationData.areaAnnotation.push(t))}}else if(t.points.length>0){const i=t.points.length-1;t.points[i]=e.catch.point.clone()}else t.points=this.points.map(i=>i.clone()),t.points.push(e.catch.point.clone());t&&t.points.length>=3&&(t.area=this.calculateArea(t.points),t.text=t.area)}}handelKeyEnterDown(){this.finishMeasure()}finishMeasure(){this.points=this.points.slice(0,this.points.length-1);let e=this.engine.measure.annotationData.areaAnnotation.find(t=>t.isSelect==!0);e!=null&&e.points.length>=3&&(e.points.length>this.points.length&&(e.points=this.points.map(t=>t.clone())),e.area=this.calculateArea(e.points),e.text=e.area,e.isSelect=!1,this.points=[],this.engine.events.trigger(di.MeasureChanged,e))}}class bB{engine;tools;points=[];behavior;constructor(e){this.engine=e,this.tools=new Sr(e)}active(){this.engine.measure.tools.cancelCurrentSelectedAnnotation(),this.points=[],this.behavior=this.engine.handelBehaved,this.behavior.init(this,{showCatch:!0}),this.behavior.active();let e=this.engine.measure.annotationData.normalAnnotation.find(t=>t.isSelect==!0);e!=null&&(e.isSelect=!1)}disActive(){this.points=[],this.behavior?.disActive()}clearAllPoints(){this.points=[]}calculateSlope(e,t){const i=t.y-e.y,n=t.x-e.x,r=t.z-e.z,a=Math.sqrt(n*n+r*r);if(a===0)return{percentage:0,angle:0,heightDiff:i,horizontalDist:0,type:"slope"};const o=i/a*100,l=Math.atan(i/a)*(180/Math.PI);return{percentage:o,angle:l,heightDiff:i,horizontalDist:a,type:"slope"}}handleMouseClick(e){if(e.catch==null)return;let t=e.catch;if(this.points.length==0)this.engine.measure.tools.clearHighlight(),this.points.push(t.point);else if(this.points.length==1){let i=this.engine.measure.annotationData.slopeAnnotation.find(r=>r.isSelect==!0);if(i==null)return;console.log("进来了"),i.point2=t.point.clone();const n=this.calculateSlope(i.point1,i.point2);i.slopePercentage=n.percentage,i.slopeAngle=n.angle,i.heightDiff=n.heightDiff,i.horizontalDist=n.horizontalDist,i.text=n.percentage.toFixed(2)+"% ("+n.angle.toFixed(2)+"°)",i.isSelect=!1,this.points=[],this.engine.events.trigger(di.MeasureChanged,i)}}handleMouseMove(e){if(e.catch==null)return;let t=e.catch;if(t!=null&&this.points.length==1){let i=this.engine.measure.annotationData.slopeAnnotation.find(r=>r.isSelect==!0);i==null&&(i={id:Mr(),point1:this.points[0].clone(),point2:t.point.clone(),slopePercentage:0,slopeAngle:0,heightDiff:0,horizontalDist:0,text:"0.00% (0.00°)",isSelect:!0,type:"slope"},this.engine.measure.annotationData.slopeAnnotation.push(i)),i.point2=t.point.clone();const n=this.calculateSlope(i.point1,i.point2);i.slopePercentage=n.percentage,i.slopeAngle=n.angle,i.heightDiff=n.heightDiff,i.horizontalDist=n.horizontalDist,i.text=n.percentage.toFixed(2)+"% ("+n.angle.toFixed(2)+"°)"}}}class MB{isActive=!1;engine;clearHeightMeasure;distanceMeasure;clearDistanceMeasure;elevationMeasure;pointMeasure;angleMeasure;areaMeasure;slopeMeasure;tools;annotationContainer;annotationData={normalAnnotation:[],textAnnotation:[],coordinateAnnotation:[],angleAnnotation:[],distanceAnnotation:[],areaAnnotation:[],slopeAnnotation:[],elevationAnnotation:[],volumeAnnotation:[]};constructor(e){this.engine=e,this.clearHeightMeasure=new fB(e),this.distanceMeasure=new mB(e),this.clearDistanceMeasure=new gB(e),this.elevationMeasure=new vB(e),this.pointMeasure=new yB(e),this.angleMeasure=new xB(e),this.areaMeasure=new _B(e),this.slopeMeasure=new bB(e),this.tools=new Sr(e),this.annotationContainer=document.createElement("div"),this.annotationContainer.className="annotation-container",e.container.appendChild(this.annotationContainer)}active(){this.isActive=!0,this.engine.modelEdge.loadModelEdge(),this.tools.active()}disActive(){this.tools.disActive(),this.clearAll(),this.isActive=!1,this.clearHeightMeasure.disActive(),this.distanceMeasure.disActive(),this.clearDistanceMeasure.disActive(),this.elevationMeasure.disActive(),this.pointMeasure.disActive(),this.angleMeasure.disActive(),this.areaMeasure.disActive(),this.slopeMeasure.disActive(),this.engine.interactionModule.init(),this.engine.interactionModule.active()}clearAllPoints(){this.clearHeightMeasure.clearAllPoints(),this.distanceMeasure.clearAllPoints(),this.clearDistanceMeasure.clearAllPoints(),this.elevationMeasure.clearAllPoints(),this.pointMeasure.clearAllPoints(),this.angleMeasure.clearAllPoints(),this.areaMeasure.clearAllPoints(),this.slopeMeasure.clearAllPoints()}clearAll(){e(this.annotationData.normalAnnotation),e(this.annotationData.textAnnotation),e(this.annotationData.coordinateAnnotation),e(this.annotationData.angleAnnotation),e(this.annotationData.distanceAnnotation),e(this.annotationData.areaAnnotation),e(this.annotationData.slopeAnnotation),e(this.annotationData.elevationAnnotation),e(this.annotationData.volumeAnnotation);function e(t){for(let i=0;i65535?new Uint32Array(new e(4*s)):new Uint16Array(new e(2*s))}function AB(s,e){if(!s.index){const t=s.attributes.position.count,i=e.useSharedArrayBuffer?SharedArrayBuffer:ArrayBuffer,n=CB(t,i);s.setIndex(new St(n,1));for(let r=0;rn&&(o.push({pos:Math.max(n,u),isStart:!0}),o.push({pos:Math.min(r,g),isStart:!1}))}o.sort((h,d)=>h.pos!==d.pos?h.pos-d.pos:h.type==="end"?-1:1);let l=0,c=null;for(const h of o){const d=h.pos;l!==0&&d!==c&&t.push({offset:c,count:d-c}),l+=h.isStart?1:-1,c=d}return t}function b1(s,e,t,i,n){let r=1/0,a=1/0,o=1/0,l=-1/0,c=-1/0,h=-1/0,d=1/0,p=1/0,u=1/0,v=-1/0,g=-1/0,m=-1/0;const f=s.offset||0;for(let y=(e-f)*6,x=(e+t-f)*6;yl&&(l=E),_v&&(v=_);const w=s[y+2],M=s[y+3],C=w-M,I=w+M;Cc&&(c=I),wg&&(g=w);const P=s[y+4],k=s[y+5],A=P-k,B=P+k;Ah&&(h=B),Pm&&(m=P)}i[0]=r,i[1]=a,i[2]=o,i[3]=l,i[4]=c,i[5]=h,n[0]=d,n[1]=p,n[2]=u,n[3]=v,n[4]=g,n[5]=m}function Aw(s,e,t=null,i=null,n=null){const r=s.attributes.position,a=s.index?s.index.array:null,o=r.normalized;if(n===null)n=new Float32Array(t*6),n.offset=e;else if(e<0||t+e>n.length/6)throw new Error("MeshBVH: compute triangle bounds range is invalid.");const l=r.array,c=r.offset||0;let h=3;r.isInterleavedBufferAttribute&&(h=r.data.stride);const d=["getX","getY","getZ"],p=n.offset;for(let u=e,v=e+t;uM&&(M=b),E>M&&(M=E);const C=(M-w)/2,I=_*2;n[m+I+0]=w+C,n[m+I+1]=C+(Math.abs(w)+C)*EB}}return n}function ui(s,e,t){return t.min.x=e[s],t.min.y=e[s+1],t.min.z=e[s+2],t.max.x=e[s+3],t.max.y=e[s+4],t.max.z=e[s+5],t}function Pw(s){let e=-1,t=-1/0;for(let i=0;i<3;i++){const n=s[i+3]-s[i];n>t&&(t=n,e=i)}return e}function Rw(s,e){e.set(s)}function Iw(s,e,t){let i,n;for(let r=0;r<3;r++){const a=r+3;i=s[r],n=e[r],t[r]=in?i:n}}function Zf(s,e,t){for(let i=0;i<3;i++){const n=e[s+2*i],r=e[s+2*i+1],a=n-r,o=n+r;at[i+3]&&(t[i+3]=o)}}function Vh(s){const e=s[3]-s[0],t=s[4]-s[1],i=s[5]-s[2];return 2*(e*t+t*i+i*e)}const wr=32,PB=(s,e)=>s.candidate-e.candidate,ua=new Array(wr).fill().map(()=>({count:0,bounds:new Float32Array(6),rightCacheBounds:new Float32Array(6),leftCacheBounds:new Float32Array(6),candidate:0})),Yf=new Float32Array(6);function RB(s,e,t,i,n,r){let a=-1,o=0;if(r===Mw)a=Pw(e),a!==-1&&(o=(e[a]+e[a+3])/2);else if(r===SB)a=Pw(s),a!==-1&&(o=IB(t,i,n,a));else if(r===wB){const l=Vh(s);let c=x1*n;const h=t.offset||0,d=(i-h)*6,p=(i+n-h)*6;for(let u=0;u<3;u++){const v=e[u],g=(e[u+3]-v)/wr;if(n=b.candidate?Zf(x,t,b.rightCacheBounds):(Zf(x,t,b.leftCacheBounds),b.count++)}}for(let x=0;x=wr&&(x=wr-1);const _=ua[x];_.count++,Zf(y,t,_.bounds)}const m=ua[wr-1];Rw(m.bounds,m.rightCacheBounds);for(let y=wr-2;y>=0;y--){const x=ua[y],_=ua[y+1];Iw(x.bounds,_.rightCacheBounds,x.rightCacheBounds)}let f=0;for(let y=0;y=l;)o--;if(a=l;)o--;if(aNB)throw new Error("MeshBVH: Cannot store relative child node offset greater than 32 bits.");return $f[t+6]=p,$f[t+7]=l,E1(h,o)}}function OB(s,e,t){const i=(s.index?s.index.count:s.attributes.position.count)/3>65536,n=t.reduce((c,h)=>c+h.count,0),r=i?4:2,a=e?new SharedArrayBuffer(n*r):new ArrayBuffer(n*r),o=i?new Uint32Array(a):new Uint16Array(a);let l=0;for(let c=0;c=r&&(f=!0,a&&(console.warn(`MeshBVH: Max depth of ${r} reached when generating BVH. Consider increasing maxDepth.`),console.warn(p))),E<=o||M>=r)return x(b+E),S.offset=b,S.count=E,S;const C=RB(S.boundingData,w,e,b,E,l);if(C.axis===-1)return x(b+E),S.offset=b,S.count=E,S;const I=v(d,u,e,b,E,C);if(I===b||I===b+E)x(b+E),S.offset=b,S.count=E;else{S.splitAxis=C.axis;const P=new M1,k=b,A=I-b;S.left=P,b1(e,k,A,P.boundingData,m),_(P,k,A,m,M+1);const B=new M1,F=I,H=E-A;S.right=B,b1(e,F,H,B.boundingData,m),_(B,F,H,m,M+1)}return S}}function BB(s,e){const t=e.useSharedArrayBuffer?SharedArrayBuffer:ArrayBuffer,i=s.geometry;let n,r;if(e.indirect){const a=Cw(i,e.range),o=OB(i,e.useSharedArrayBuffer,a);s._indirectBuffer=o,n=Aw(i,0,o.length,o),r=[{offset:0,count:o.length}]}else{AB(i,e);const a=Tw(i,e.range)[0];n=Aw(i,a.offset,a.count),r=Cw(i,e.range)}s._roots=r.map(a=>{const o=UB(s,n,a.offset,a.count,e),l=w1(o),c=new t(vn*l);return kB(0,o,c),c})}class Er{constructor(){this.min=1/0,this.max=-1/0}setFromPointsField(e,t){let i=1/0,n=-1/0;for(let r=0,a=e.length;rn?o:n}this.min=i,this.max=n}setFromPoints(e,t){let i=1/0,n=-1/0;for(let r=0,a=t.length;rn?l:n}this.min=i,this.max=n}isSeparated(e){return this.min>e.max||e.min>this.max}}Er.prototype.setFromBox=(function(){const s=new R;return function(e,t){const i=t.min,n=t.max;let r=1/0,a=-1/0;for(let o=0;o<=1;o++)for(let l=0;l<=1;l++)for(let c=0;c<=1;c++){s.x=i.x*o+n.x*(1-o),s.y=i.y*l+n.y*(1-l),s.z=i.z*c+n.z*(1-c);const h=e.dot(s);r=Math.min(h,r),a=Math.max(h,a)}this.min=r,this.max=a}})();const FB=(function(){const s=new R,e=new R,t=new R;return function(i,n,r){const a=i.start,o=s,l=n.start,c=e;t.subVectors(a,l),s.subVectors(i.end,i.start),e.subVectors(n.end,n.start);const h=t.dot(c),d=c.dot(o),p=c.dot(c),u=t.dot(o),v=o.dot(o)*p-d*d;let g,m;v!==0?g=(h*d-u*p)/v:g=0,m=(h+g*d)/p,r.x=g,r.y=m}})(),T1=(function(){const s=new me,e=new R,t=new R;return function(i,n,r,a){FB(i,n,s);let o=s.x,l=s.y;if(o>=0&&o<=1&&l>=0&&l<=1){i.at(o,r),n.at(l,a);return}else if(o>=0&&o<=1){l<0?n.at(0,a):n.at(1,a),i.closestPointToPoint(a,!0,r);return}else if(l>=0&&l<=1){o<0?i.at(0,r):i.at(1,r),n.closestPointToPoint(r,!0,a);return}else{let c;o<0?c=i.start:c=i.end;let h;l<0?h=n.start:h=n.end;const d=e,p=t;if(i.closestPointToPoint(h,!0,e),n.closestPointToPoint(c,!0,t),d.distanceToSquared(h)<=p.distanceToSquared(c)){r.copy(d),a.copy(h);return}else{r.copy(c),a.copy(p);return}}}})(),zB=(function(){const s=new R,e=new R,t=new Yt,i=new Bn;return function(n,r){const{radius:a,center:o}=n,{a:l,b:c,c:h}=r;if(i.start=l,i.end=c,i.closestPointToPoint(o,!0,s).distanceTo(o)<=a||(i.start=l,i.end=h,i.closestPointToPoint(o,!0,s).distanceTo(o)<=a)||(i.start=c,i.end=h,i.closestPointToPoint(o,!0,s).distanceTo(o)<=a))return!0;const d=r.getPlane(t);if(Math.abs(d.distanceToPoint(o))<=a){const p=d.projectPoint(o,e);if(r.containsPoint(p))return!0}return!1}})(),HB=["x","y","z"],Tr=1e-15,Nw=Tr*Tr;function ss(s){return Math.abs(s)new R),this.satBounds=new Array(4).fill().map(()=>new Er),this.points=[this.a,this.b,this.c],this.plane=new Yt,this.isDegenerateIntoSegment=!1,this.isDegenerateIntoPoint=!1,this.degenerateSegment=new Bn,this.needsUpdate=!0}intersectsSphere(e){return zB(e,this)}update(){const e=this.a,t=this.b,i=this.c,n=this.points,r=this.satAxes,a=this.satBounds,o=r[0],l=a[0];this.getNormal(o),l.setFromPoints(o,n);const c=r[1],h=a[1];c.subVectors(e,t),h.setFromPoints(c,n);const d=r[2],p=a[2];d.subVectors(t,i),p.setFromPoints(d,n);const u=r[3],v=a[3];u.subVectors(i,e),v.setFromPoints(u,n);const g=c.length(),m=d.length(),f=u.length();this.isDegenerateIntoPoint=!1,this.isDegenerateIntoSegment=!1,g0)u(x.c,x.a,x.b,b,_,S,I,M,C,P,k);else if(w>0)u(x.b,x.a,x.c,S,_,b,C,M,I,P,k);else if(C*I>0||M!=0)u(x.a,x.b,x.c,_,S,b,M,C,I,P,k);else if(C!=0)u(x.b,x.a,x.c,S,_,b,C,M,I,P,k);else if(I!=0)u(x.c,x.a,x.b,b,_,S,I,M,C,P,k);else return!0;return!1}function g(x,_,S,b){const E=_.degenerateSegment,w=x.plane.distanceToPoint(E.start),M=x.plane.distanceToPoint(E.end);return ss(w)?ss(M)?p(x,_,S,b):(S&&(S.start.copy(E.start),S.end.copy(E.start)),x.containsPoint(E.start)):ss(M)?(S&&(S.start.copy(E.end),S.end.copy(E.end)),x.containsPoint(E.end)):x.plane.intersectLine(E,i)!=null?(S&&(S.start.copy(i),S.end.copy(i)),x.containsPoint(i)):!1}function m(x,_,S){const b=_.a;return ss(x.plane.distanceToPoint(b))&&x.containsPoint(b)?(S&&(S.start.copy(b),S.end.copy(b)),!0):!1}function f(x,_,S){const b=x.degenerateSegment,E=_.a;return b.closestPointToPoint(E,!0,i),E.distanceToSquared(i)1||A<0||A>1)return!1;const B=E.start.z+M.z*k,F=w.start.z+C.z*A;return ss(B-F)?(S&&(S.start.copy(E.start).addScaledVector(M,k),S.end.copy(E.start).addScaledVector(M,k)),!0):!1}else return _.isDegenerateIntoPoint?f(x,_,S):g(_,x,S,b);else{if(x.isDegenerateIntoPoint)return _.isDegenerateIntoPoint?_.a.distanceToSquared(x.a)0&&k>0)return!1;let A=E.distanceToPoint(x.a),B=E.distanceToPoint(x.b),F=E.distanceToPoint(x.c);ss(A)&&(A=0),ss(B)&&(B=0),ss(F)&&(F=0);const H=A*B,q=A*F;if(H>0&&q>0)return!1;n.copy(E.normal),r.copy(w.normal);const G=n.cross(r);let re=0,Y=Math.abs(G.x);const $=Math.abs(G.y);$>Y&&(Y=$,re=1),Math.abs(G.z)>Y&&(re=2);const _e=HB[re],Te=this.a[_e],be=this.b[_e],J=this.c[_e],oe=x.a[_e],ue=x.b[_e],Re=x.c[_e];if(v(this,Te,be,J,P,k,M,C,I,h,o))return p(this,x,_,S);if(v(x,oe,ue,Re,H,q,A,B,F,d,l))return p(this,x,_,S);if(h.yh.x?_.start.copy(l.start):_.start.copy(o.start),d.ynew R),this.satAxes=new Array(3).fill().map(()=>new R),this.satBounds=new Array(3).fill().map(()=>new Er),this.alignedSatBounds=new Array(3).fill().map(()=>new Er),this.needsUpdate=!1,e&&this.min.copy(e),t&&this.max.copy(t),i&&this.matrix.copy(i)}set(e,t,i){this.min.copy(e),this.max.copy(t),this.matrix.copy(i),this.needsUpdate=!0}copy(e){this.min.copy(e.min),this.max.copy(e.max),this.matrix.copy(e.matrix),this.needsUpdate=!0}}yn.prototype.update=(function(){return function(){const s=this.matrix,e=this.min,t=this.max,i=this.points;for(let l=0;l<=1;l++)for(let c=0;c<=1;c++)for(let h=0;h<=1;h++){const d=1*l|2*c|4*h,p=i[d];p.x=l?t.x:e.x,p.y=c?t.y:e.y,p.z=h?t.z:e.z,p.applyMatrix4(s)}const n=this.satBounds,r=this.satAxes,a=i[0];for(let l=0;l<3;l++){const c=r[l],h=n[l],d=1<new Bn),t=new Array(12).fill().map(()=>new Bn),i=new R,n=new R;return function(r,a=0,o=null,l=null){if(this.needsUpdate&&this.update(),this.intersectsBox(r))return(o||l)&&(r.getCenter(n),this.closestPointToPoint(n,i),r.closestPointToPoint(i,n),o&&o.copy(i),l&&l.copy(n)),0;const c=a*a,h=r.min,d=r.max,p=this.points;let u=1/0;for(let g=0;g<8;g++){const m=p[g];n.copy(m).clamp(h,d);const f=m.distanceToSquared(n);if(fnew rs)}}const as=new VB;function Wi(s,e){return e[s+15]===Ew}function Gn(s,e){return e[s+6]}function os(s,e){return e[s+14]}function Yi(s){return s+Gi}function $i(s,e){const t=e[s+6];return s+t*Gi}function A1(s,e){return e[s+7]}class GB{constructor(){this.float32Array=null,this.uint16Array=null,this.uint32Array=null;const e=[];let t=null;this.setBuffer=i=>{t&&e.push(t),t=i,this.float32Array=new Float32Array(i),this.uint16Array=new Uint16Array(i),this.uint32Array=new Uint32Array(i)},this.clearBuffer=()=>{t=null,this.float32Array=null,this.uint16Array=null,this.uint32Array=null,e.length!==0&&this.setBuffer(e.pop())}}}const ii=new GB;let pa,nc;const sc=[],Kf=new C1(()=>new vt);function WB(s,e,t,i,n,r){pa=Kf.getPrimitive(),nc=Kf.getPrimitive(),sc.push(pa,nc),ii.setBuffer(s._roots[e]);const a=P1(0,s.geometry,t,i,n,r);ii.clearBuffer(),Kf.releasePrimitive(pa),Kf.releasePrimitive(nc),sc.pop(),sc.pop();const o=sc.length;return o>0&&(nc=sc[o-1],pa=sc[o-2]),a}function P1(s,e,t,i,n=null,r=0,a=0){const{float32Array:o,uint16Array:l,uint32Array:c}=ii;let h=s*2;if(Wi(h,l)){const d=Gn(s,c),p=os(h,l);return ui(s,o,pa),i(d,p,!1,a,r+s/Gi,pa)}else{let d=function(I){const{uint16Array:P,uint32Array:k}=ii;let A=I*2;for(;!Wi(A,P);)I=Yi(I),A=I*2;return Gn(I,k)},p=function(I){const{uint16Array:P,uint32Array:k}=ii;let A=I*2;for(;!Wi(A,P);)I=$i(I,k),A=I*2;return Gn(I,k)+os(A,P)};const u=Yi(s),v=$i(s,c);let g=u,m=v,f,y,x,_;if(n&&(x=pa,_=nc,ui(g,o,x),ui(m,o,_),f=n(x),y=n(_),y(Gh.copy(e).clamp(h.min,h.max),Gh.distanceToSquared(e)),intersectsBounds:(h,d,p)=>p{h.closestPointToPoint(e,Gh);const p=e.distanceToSquared(Gh);return p=169,jB=parseInt(zo)<=161,To=new R,Co=new R,Ao=new R,Qf=new me,em=new me,tm=new me,kw=new R,Ow=new R,Uw=new R,Wh=new R;function qB(s,e,t,i,n,r,a,o){let l;if(r===Bi?l=s.intersectTriangle(i,t,e,!0,n):l=s.intersectTriangle(e,t,i,r!==Ot,n),l===null)return null;const c=s.origin.distanceTo(n);return co?null:{distance:c,point:n.clone()}}function Bw(s,e,t,i,n,r,a,o,l,c,h){To.fromBufferAttribute(e,r),Co.fromBufferAttribute(e,a),Ao.fromBufferAttribute(e,o);const d=qB(s,To,Co,Ao,Wh,l,c,h);if(d){if(i){Qf.fromBufferAttribute(i,r),em.fromBufferAttribute(i,a),tm.fromBufferAttribute(i,o),d.uv=new me;const u=Ht.getInterpolation(Wh,To,Co,Ao,Qf,em,tm,d.uv);Jf||(d.uv=u)}if(n){Qf.fromBufferAttribute(n,r),em.fromBufferAttribute(n,a),tm.fromBufferAttribute(n,o),d.uv1=new me;const u=Ht.getInterpolation(Wh,To,Co,Ao,Qf,em,tm,d.uv1);Jf||(d.uv1=u),jB&&(d.uv2=d.uv1)}if(t){kw.fromBufferAttribute(t,r),Ow.fromBufferAttribute(t,a),Uw.fromBufferAttribute(t,o),d.normal=new R;const u=Ht.getInterpolation(Wh,To,Co,Ao,kw,Ow,Uw,d.normal);d.normal.dot(s.direction)>0&&d.normal.multiplyScalar(-1),Jf||(d.normal=u)}const p={a:r,b:a,c:o,normal:new R,materialIndex:0};if(Ht.getNormal(To,Co,Ao,p.normal),d.face=p,d.faceIndex=r,Jf){const u=new R;Ht.getBarycoord(Wh,To,Co,Ao,u),d.barycoord=u}}return d}function Fw(s){return s&&s.isMaterial?s.side:s}function im(s,e,t,i,n,r,a){const o=i*3;let l=o+0,c=o+1,h=o+2;const{index:d,groups:p}=s;s.index&&(l=d.getX(l),c=d.getX(c),h=d.getX(h));const{position:u,normal:v,uv:g,uv1:m}=s.attributes;if(Array.isArray(e)){const f=i*3;for(let y=0,x=p.length;y=_&&f<_+S){const E=Fw(e[b]),w=Bw(t,u,v,g,m,l,c,h,E,r,a);if(w)if(w.faceIndex=i,w.face.materialIndex=b,n)n.push(w);else return w}}}else{const f=Fw(e),y=Bw(t,u,v,g,m,l,c,h,f,r,a);if(y)if(y.faceIndex=i,y.face.materialIndex=0,n)n.push(y);else return y}return null}function Ei(s,e,t,i){const n=s.a,r=s.b,a=s.c;let o=e,l=e+1,c=e+2;t&&(o=t.getX(o),l=t.getX(l),c=t.getX(c)),n.x=i.getX(o),n.y=i.getY(o),n.z=i.getZ(o),r.x=i.getX(l),r.y=i.getY(l),r.z=i.getZ(l),a.x=i.getX(c),a.y=i.getY(c),a.z=i.getZ(c)}function ZB(s,e,t,i,n,r,a,o){const{geometry:l,_indirectBuffer:c}=s;for(let h=i,d=i+n;hS&&(S=I),Pb&&(b=P),k<_&&(_=k),k>E&&(E=k)}return l[p+0]!==y||l[p+1]!==x||l[p+2]!==_||l[p+3]!==S||l[p+4]!==b||l[p+5]!==E?(l[p+0]=y,l[p+1]=x,l[p+2]=_,l[p+3]=S,l[p+4]=b,l[p+5]=E,!0):!1}else{const m=Yi(p),f=$i(p,a);let y=v,x=!1,_=!1;if(e){if(!y){const C=m/Gi+u/vn,I=f/Gi+u/vn;x=e.has(C),_=e.has(I),y=!x&&!_}}else x=!0,_=!0;const S=y||x,b=y||_;let E=!1;S&&(E=d(m,u,y));let w=!1;b&&(w=d(f,u,y));const M=E||w;if(M)for(let C=0;C<3;C++){const I=m+C,P=f+C,k=l[I],A=l[I+3],B=l[P],F=l[P+3];l[p+C]=kF?A:F}return M}}}function fa(s,e,t,i,n){let r,a,o,l,c,h;const d=1/t.direction.x,p=1/t.direction.y,u=1/t.direction.z,v=t.origin.x,g=t.origin.y,m=t.origin.z;let f=e[s],y=e[s+3],x=e[s+1],_=e[s+3+1],S=e[s+2],b=e[s+3+2];return d>=0?(r=(f-v)*d,a=(y-v)*d):(r=(y-v)*d,a=(f-v)*d),p>=0?(o=(x-g)*p,l=(_-g)*p):(o=(_-g)*p,l=(x-g)*p),r>l||o>a||((o>r||isNaN(r))&&(r=o),(l=0?(c=(S-m)*u,h=(b-m)*u):(c=(b-m)*u,h=(S-m)*u),r>h||c>a)?!1:((c>r||r!==r)&&(r=c),(h=i)}function JB(s,e,t,i,n,r,a,o){const{geometry:l,_indirectBuffer:c}=s;for(let h=i,d=i+n;h=0;let u,v;p?(u=Yi(s),v=$i(s,l)):(u=$i(s,l),v=Yi(s));const g=fa(u,a,i,n,r)?L1(u,e,t,i,n,r):null;if(g){const f=g.point[d];if(p?f<=a[v+h]:f>=a[v+h+3])return g}const m=fa(v,a,i,n,r)?L1(v,e,t,i,n,r):null;return g&&m?g.distance<=m.distance?g:m:g||m||null}}const nm=new vt,rc=new rs,ac=new rs,Xh=new qe,zw=new yn,sm=new yn;function s7(s,e,t,i){ii.setBuffer(s._roots[e]);const n=D1(0,s,t,i);return ii.clearBuffer(),n}function D1(s,e,t,i,n=null){const{float32Array:r,uint16Array:a,uint32Array:o}=ii;let l=s*2;if(n===null&&(t.boundingBox||t.computeBoundingBox(),zw.set(t.boundingBox.min,t.boundingBox.max,i),n=zw),Wi(l,a)){const c=e.geometry,h=c.index,d=c.attributes.position,p=t.index,u=t.attributes.position,v=Gn(s,o),g=os(l,a);if(Xh.copy(i).invert(),t.boundsTree)return ui(s,r,sm),sm.matrix.copy(Xh),sm.needsUpdate=!0,t.boundsTree.shapecast({intersectsBounds:m=>sm.intersectsBox(m),intersectsTriangle:m=>{m.a.applyMatrix4(i),m.b.applyMatrix4(i),m.c.applyMatrix4(i),m.needsUpdate=!0;for(let f=v*3,y=(g+v)*3;fN1.distanceToBox(S),intersectsBounds:(S,b,E)=>E{if(e.boundsTree)return e.boundsTree.shapecast({boundsTraverseOrder:E=>jh.distanceToBox(E),intersectsBounds:(E,w,M)=>M{for(let M=E,C=E+w;MS&&(S=k),Ab&&(b=A),B<_&&(_=B),B>E&&(E=B)}}return l[p+0]!==y||l[p+1]!==x||l[p+2]!==_||l[p+3]!==S||l[p+4]!==b||l[p+5]!==E?(l[p+0]=y,l[p+1]=x,l[p+2]=_,l[p+3]=S,l[p+4]=b,l[p+5]=E,!0):!1}else{const m=Yi(p),f=$i(p,a);let y=v,x=!1,_=!1;if(e){if(!y){const C=m/Gi+u/vn,I=f/Gi+u/vn;x=e.has(C),_=e.has(I),y=!x&&!_}}else x=!0,_=!0;const S=y||x,b=y||_;let E=!1;S&&(E=d(m,u,y));let w=!1;b&&(w=d(f,u,y));const M=E||w;if(M)for(let C=0;C<3;C++){const I=m+C,P=f+C,k=l[I],A=l[I+3],B=l[P],F=l[P+3];l[p+C]=kF?A:F}return M}}}function d7(s,e,t,i,n,r,a){ii.setBuffer(s._roots[e]),k1(0,s,t,i,n,r,a),ii.clearBuffer()}function k1(s,e,t,i,n,r,a){const{float32Array:o,uint16Array:l,uint32Array:c}=ii,h=s*2;if(Wi(h,l)){const d=Gn(s,c),p=os(h,l);JB(e,t,i,d,p,n,r,a)}else{const d=Yi(s);fa(d,o,i,r,a)&&k1(d,e,t,i,n,r,a);const p=$i(s,c);fa(p,o,i,r,a)&&k1(p,e,t,i,n,r,a)}}const u7=["x","y","z"];function p7(s,e,t,i,n,r){ii.setBuffer(s._roots[e]);const a=O1(0,s,t,i,n,r);return ii.clearBuffer(),a}function O1(s,e,t,i,n,r){const{float32Array:a,uint16Array:o,uint32Array:l}=ii;let c=s*2;if(Wi(c,o)){const h=Gn(s,l),d=os(c,o);return QB(e,t,i,h,d,n,r)}else{const h=A1(s,l),d=u7[h],p=i.direction[d]>=0;let u,v;p?(u=Yi(s),v=$i(s,l)):(u=$i(s,l),v=Yi(s));const g=fa(u,a,i,n,r)?O1(u,e,t,i,n,r):null;if(g){const f=g.point[d];if(p?f<=a[v+h]:f>=a[v+h+3])return g}const m=fa(v,a,i,n,r)?O1(v,e,t,i,n,r):null;return g&&m?g.distance<=m.distance?g:m:g||m||null}}const am=new vt,oc=new rs,lc=new rs,qh=new qe,Hw=new yn,om=new yn;function f7(s,e,t,i){ii.setBuffer(s._roots[e]);const n=U1(0,s,t,i);return ii.clearBuffer(),n}function U1(s,e,t,i,n=null){const{float32Array:r,uint16Array:a,uint32Array:o}=ii;let l=s*2;if(n===null&&(t.boundingBox||t.computeBoundingBox(),Hw.set(t.boundingBox.min,t.boundingBox.max,i),n=Hw),Wi(l,a)){const c=e.geometry,h=c.index,d=c.attributes.position,p=t.index,u=t.attributes.position,v=Gn(s,o),g=os(l,a);if(qh.copy(i).invert(),t.boundsTree)return ui(s,r,om),om.matrix.copy(qh),om.needsUpdate=!0,t.boundsTree.shapecast({intersectsBounds:m=>om.intersectsBox(m),intersectsTriangle:m=>{m.a.applyMatrix4(i),m.b.applyMatrix4(i),m.c.applyMatrix4(i),m.needsUpdate=!0;for(let f=v,y=g+v;fB1.distanceToBox(S),intersectsBounds:(S,b,E)=>E{if(e.boundsTree){const E=e.boundsTree;return E.shapecast({boundsTraverseOrder:w=>Zh.distanceToBox(w),intersectsBounds:(w,M,C)=>C{for(let C=w,I=w+M;Cnew vt),cc=new vt,hc=new vt,F1=new vt,z1=new vt;let H1=!1;function b7(s,e,t,i){if(H1)throw new Error("MeshBVH: Recursive calls to bvhcast not supported.");H1=!0;const n=s._roots,r=e._roots;let a,o=0,l=0;const c=new qe().copy(t).invert();for(let h=0,d=n.length;hl.slice()),o.index=a?a.array.slice():null,o.indirectBuffer=r?r.slice():null):(o.roots=n,o.index=a?a.array:null,o.indirectBuffer=r),o}static deserialize(e,t,i={}){i={setIndex:!0,indirect:!!e.indirectBuffer,...i};const{index:n,roots:r,indirectBuffer:a}=e;e.version||(console.warn("MeshBVH.deserialize: Serialization format has been changed and will be fixed up. It is recommended to regenerate any stored serialized data."),l(r));const o=new V1(t,{...i,[_1]:!0});if(o._roots=r,o._indirectBuffer=a||null,i.setIndex){const c=t.getIndex();if(c===null){const h=new St(e.index,1,!1);t.setIndex(h)}else c.array!==n&&(c.array.set(n),c.needsUpdate=!0)}return o;function l(c){for(let h=0;hthis._indirectBuffer[i]:i=>i}shiftTriangleOffsets(e){const t=this._indirectBuffer;if(t)for(let i=0,n=t.length;id(p,u,v,g,m)?!0:i(p,u,this,o,v,g,t)}else a||(o?a=(d,p,u,v)=>i(d,p,this,o,u,v,t):a=(d,p,u)=>u);let l=!1,c=0;const h=this._roots;for(let d=0,p=h.length;d{const g=this.resolveTriangleIndex(v);Ei(a,g*3,o,l)}:v=>{Ei(a,v*3,o,l)},h=as.getPrimitive(),d=e.geometry.index,p=e.geometry.attributes.position,u=e.indirect?v=>{const g=e.resolveTriangleIndex(v);Ei(h,g*3,d,p)}:v=>{Ei(h,v*3,d,p)};if(r){const v=(g,m,f,y,x,_,S,b)=>{for(let E=f,w=f+y;Ehm.intersectsBox(i),intersectsTriangle:i=>hm.intersectsTriangle(i)})}intersectsSphere(e){return this.shapecast({intersectsBounds:t=>e.intersectsBox(t),intersectsTriangle:t=>t.intersectsSphere(e)})}closestPointToGeometry(e,t,i={},n={},r=0,a=1/0){return(this.indirect?x7:c7)(this,e,t,i,n,r,a)}closestPointToPoint(e,t={},i=0,n=1/0){return XB(this,e,t,i,n)}getBoundingBox(e){return e.makeEmpty(),this._roots.forEach(t=>{ui(0,new Float32Array(t),Vw),e.union(Vw)}),e}}const Gw=1e-6,S7=Gw*.5,Ww=Math.pow(10,-Math.log10(Gw)),w7=S7*Ww;function qs(s){return~~(s*Ww+w7)}function E7(s){return`${qs(s.x)},${qs(s.y)}`}function Xw(s){return`${qs(s.x)},${qs(s.y)},${qs(s.z)}`}function T7(s){return`${qs(s.x)},${qs(s.y)},${qs(s.z)},${qs(s.w)}`}function C7(s,e,t){t.direction.subVectors(e,s).normalize();const i=s.dot(t.direction);return t.origin.copy(s).addScaledVector(t.direction,-i),t}function jw(){return typeof SharedArrayBuffer<"u"}function A7(s){if(s.buffer instanceof SharedArrayBuffer)return s;const e=s.constructor,t=s.buffer,i=new SharedArrayBuffer(t.byteLength),n=new Uint8Array(t);return new Uint8Array(i).set(n,0),new e(i)}function P7(s,e=ArrayBuffer){return s>65535?new Uint32Array(new e(4*s)):new Uint16Array(new e(2*s))}function R7(s,e){if(!s.index){const t=s.attributes.position.count,i=e.useSharedArrayBuffer?SharedArrayBuffer:ArrayBuffer,n=P7(t,i);s.setIndex(new St(n,1));for(let r=0;rl.end)){if(l.end=h.end)r(h.end,l.end)||s.splice(o+1,0,{start:h.end,end:l.end,index:l.index}),l.end=h.start,h.start=0,h.end=0;else if(l.start>=h.start&&l.end<=h.end)r(l.end,h.end)||e.splice(c+1,0,{start:l.end,end:h.end,index:h.index}),h.end=l.start,l.start=0,l.end=0;else if(l.start<=h.start&&l.end<=h.end){const d=l.end;l.end=h.start,h.start=d}else if(l.start>=h.start&&l.end>=h.end){const d=h.end;h.end=l.start,l.start=d}else throw new Error}if(t.has(l.index)||t.set(l.index,[]),t.has(h.index)||t.set(h.index,[]),t.get(l.index).push(h.index),t.get(h.index).push(l.index),a(h)&&(e.splice(c,1),c--),a(l)){s.splice(o,1),o--;break}}}n(s),n(e);function n(o){for(let l=0;lYw;return l.direction.angleTo(c.direction)>$w||h}function o(l,c){const h=l.origin.distanceTo(c.origin),d=l.direction.angleTo(c.direction);return h/Yw+d/$w}}}const W1=new R,X1=new R,dm=new ks;function B7(s,e,t){const i=s.attributes,n=s.index,r=i.position,a=new Map,o=new Map,l=Array.from(e),c=new U7;for(let h=0,d=l.length;h_&&([x,_]=[_,x]),dm.direction.dot(y.direction)<0?f.reverse.push({start:x,end:_,index:p}):f.forward.push({start:x,end:_,index:p})}return o.forEach(({forward:h,reverse:d},p)=>{O7(h,d,a,t),h.length===0&&d.length===0&&o.delete(p)}),{disjointConnectivityMap:a,fragmentMap:o}}const F7=new me,j1=new R,z7=new Pt,q1=["","",""];class H7{constructor(e=null){this.data=null,this.disjointConnections=null,this.unmatchedDisjointEdges=null,this.unmatchedEdges=-1,this.matchedEdges=-1,this.useDrawRange=!0,this.useAllAttributes=!1,this.matchDisjointEdges=!1,this.degenerateEpsilon=1e-8,e&&this.updateFrom(e)}getSiblingTriangleIndex(e,t){const i=this.data[e*3+t];return i===-1?-1:~~(i/3)}getSiblingEdgeIndex(e,t){const i=this.data[e*3+t];return i===-1?-1:i%3}getDisjointSiblingTriangleIndices(e,t){const i=e*3+t,n=this.disjointConnections.get(i);return n?n.map(r=>~~(r/3)):[]}getDisjointSiblingEdgeIndices(e,t){const i=e*3+t,n=this.disjointConnections.get(i);return n?n.map(r=>r%3):[]}isFullyConnected(){return this.unmatchedEdges===0}updateFrom(e){const{useAllAttributes:t,useDrawRange:i,matchDisjointEdges:n,degenerateEpsilon:r}=this,a=t?x:y,o=new Map,{attributes:l}=e,c=t?Object.keys(l):null,h=e.index,d=l.position;let p=G1(e);const u=p;let v=0;i&&(v=e.drawRange.start,e.drawRange.count!==1/0&&(p=~~(e.drawRange.count/3)));let g=this.data;(!g||g.length<3*u)&&(g=new Int32Array(3*u)),g.fill(-1);let m=0,f=new Set;for(let _=v,S=p*3+v;_{b.forEach(({index:w})=>f.add(w)),E.forEach(({index:w})=>f.add(w))}),this.unmatchedDisjointEdges=_,this.disjointConnections=S,m=p*3-f.size}this.matchedEdges=m,this.unmatchedEdges=f.size,this.data=g;function y(_){return j1.fromBufferAttribute(d,_),Xw(j1)}function x(_){let S="";for(let b=0,E=c.length;b=this._pool.length&&this._pool.push(new Ht),this._pool[this._index++]}clear(){this._index=0}reset(){this._pool.length=0,this._index=0}}class X7{constructor(){this.trianglePool=new W7,this.triangles=[],this.normal=new R,this.coplanarTriangleUsed=!1}initialize(e){this.reset();const{triangles:t,trianglePool:i,normal:n}=this;if(Array.isArray(e))for(let r=0,a=e.length;rY1)throw new Error("Triangle Splitter: Cannot initialize with triangles that have different normals.");const l=i.getTriangle();l.copy(o),t.push(l)}else{e.getNormal(n);const r=i.getTriangle();r.copy(e),t.push(r)}}splitByTriangle(e){const{normal:t,triangles:i}=this;if(e.getNormal($1).normalize(),Math.abs(1-Math.abs($1.dot(t)))0?v.push(f):g.push(f),Math.abs(x)<$h)continue;let S=!!e.intersectLine(Cr,Ar);!S&&Math.abs(_)<$h&&(Ar.copy(Cr.end),S=!0),S&&!(Ar.distanceTo(Cr.start)$h)if(p!==-1){p=(p+1)%3;let f=0;f===p&&(f=(f+1)%3);let y=f+1;y===p&&(y=(y+1)%3);const x=n.getTriangle();x.a.copy(m[y]),x.b.copy(xi.end),x.c.copy(xi.start),ga(x)||i.push(x),o.a.copy(m[f]),o.b.copy(xi.start),o.c.copy(xi.end),ga(o)&&(i.splice(r,1),r--,a--)}else{const f=v.length>=2?g[0]:v[0];if(f===0){let b=xi.start;xi.start=xi.end,xi.end=b}const y=(f+1)%3,x=(f+2)%3,_=n.getTriangle(),S=n.getTriangle();m[y].distanceToSquared(xi.start)t.length&&(this.expand(),t=this.array);for(let n=0,r=e.length;n=t.length;){const n={};t.push(n);for(const r in i){const a=i[r],o=new e2(a.type);o.itemSize=a.itemSize,o.normalized=a.normalized,n[r]=o}}return t[e]}getGroupAttrArray(e,t=0){const{groupAttributes:i}=this;if(!i[0][e])throw new Error(`TypedAttributeData: Attribute with "${e}" has not been initialized`);return this.getGroupAttrSet(t)[e]}initializeArray(e,t,i,n){const{groupAttributes:r}=this,a=r[0][e];if(a){if(a.type!==t)for(let o=0,l=r.length;o{for(const i in t)t[i].clear()})}delete(e){this.groupAttributes.forEach(t=>{delete t[e]})}reset(){this.groupAttributes=[],this.groupCount=0}}class t2{constructor(){this.intersectionSet={},this.ids=[]}add(e,t){const{intersectionSet:i,ids:n}=this;i[e]||(i[e]=[],n.push(e)),i[e].push(t)}}const Z7=0,Y7=1,$7=2,i2=3,K7=4,n2=5,s2=6,ls=new ks,r2=new qe,xn=new Ht,Pr=new R,a2=new Pt,o2=new Pt,l2=new Pt,J1=new Pt,fm=new Pt,mm=new Pt,c2=new Bn,Q1=new R,ey=1e-8,J7=1e-15,Po=-1,Ro=1,gm=-2,vm=2,Kh=0,Io=1,ty=2,Q7=1e-14;let ym=null;function h2(s){ym=s}function d2(s,e){s.getMidpoint(ls.origin),s.getNormal(ls.direction);const t=e.raycastFirst(ls,Ot);return t&&ls.direction.dot(t.face.normal)>0?Po:Ro}function eF(s,e){function t(){return Math.random()-.5}s.getNormal(Q1),ls.direction.copy(Q1),s.getMidpoint(ls.origin);const i=3;let n=0,r=1/0;for(let a=0;a0&&n++,o!==null&&(r=Math.min(r,o.distance)),r<=J7)return o.face.normal.dot(Q1)>0?vm:gm;if(n/i>.5||(a-n+1)/i>.5)break}return n/i>.5?Po:Ro}function tF(s,e){const t=new t2,i=new t2;return r2.copy(s.matrixWorld).invert().multiply(e.matrixWorld),s.geometry.boundsTree.bvhcast(e.geometry.boundsTree,r2,{intersectsTriangles(n,r,a,o){if(!ga(n)&&!ga(r)){let l=n.intersectsTriangle(r,c2,!0);if(!l){const c=n.plane,h=r.plane,d=c.normal,p=h.normal;d.dot(p)===1&&Math.abs(c.constant-h.constant){r.push(c.x),n>1&&r.push(c.y),n>2&&r.push(c.z),n>3&&r.push(c.w)};J1.set(0,0,0,0).addScaledVector(s,i.a.x).addScaledVector(e,i.a.y).addScaledVector(t,i.a.z),fm.set(0,0,0,0).addScaledVector(s,i.b.x).addScaledVector(e,i.b.y).addScaledVector(t,i.b.z),mm.set(0,0,0,0).addScaledVector(s,i.c.x).addScaledVector(e,i.c.y).addScaledVector(t,i.c.z),o&&(J1.normalize(),fm.normalize(),mm.normalize()),l(J1),a?(l(mm),l(fm)):(l(fm),l(mm))}function ny(s,e,t,i,n,r=!1){for(const a in n){const o=e[a],l=n[a];if(!(a in e))throw new Error(`CSG Operations: Attribute ${a} no available on geometry.`);const c=o.itemSize;a==="position"?(Pr.fromBufferAttribute(o,s).applyMatrix4(t),l.push(Pr.x,Pr.y,Pr.z)):a==="normal"?(Pr.fromBufferAttribute(o,s).applyNormalMatrix(i),r&&Pr.multiplyScalar(-1),l.push(Pr.x,Pr.y,Pr.z)):(l.push(o.getX(s)),c>1&&l.push(o.getY(s)),c>2&&l.push(o.getZ(s)),c>3&&l.push(o.getW(s)))}}class sF{constructor(e){this.triangle=new Ht().copy(e),this.intersects={}}addTriangle(e,t){this.intersects[e]=new Ht().copy(t)}getIntersectArray(){const e=[],{intersects:t}=this;for(const i in t)e.push(t[i]);return e}}class p2{constructor(){this.data={}}addTriangleIntersection(e,t,i,n){const{data:r}=this;r[e]||(r[e]=new sF(t)),r[e].addTriangle(i,n)}getTrianglesAsArray(e=null){const{data:t}=this,i=[];if(e!==null)e in t&&i.push(t[e].triangle);else for(const n in t)i.push(t[n].triangle);return i}getTriangleIndices(){return Object.keys(this.data).map(e=>parseInt(e))}getIntersectionIndices(e){const{data:t}=this;return t[e]?Object.keys(t[e].intersects).map(i=>parseInt(i)):[]}getIntersectionsAsArray(e=null,t=null){const{data:i}=this,n=new Set,r=[],a=o=>{if(i[o])if(t!==null)i[o].intersects[t]&&r.push(i[o].intersects[t]);else{const l=i[o].intersects;for(const c in l)n.has(c)||(n.add(c),r.push(l[c]))}};if(e!==null)a(e);else for(const o in i)a(o);return r}reset(){this.data={}}}class rF{constructor(){this.enabled=!1,this.triangleIntersectsA=new p2,this.triangleIntersectsB=new p2,this.intersectionEdges=[]}addIntersectingTriangles(e,t,i,n){const{triangleIntersectsA:r,triangleIntersectsB:a}=this;r.addTriangleIntersection(e,t,i,n),a.addTriangleIntersection(i,n,e,t)}addEdge(e){this.intersectionEdges.push(e.clone())}reset(){this.triangleIntersectsA.reset(),this.triangleIntersectsB.reset(),this.intersectionEdges=[]}init(){this.enabled&&(this.reset(),h2(this))}complete(){this.enabled&&h2(null)}}const va=new qe,xm=new ft,Lo=new Ht,_m=new Ht,ya=new Ht,bm=new Ht,As=[],Do=[];function aF(s){for(const e of s)return e}function oF(s,e,t,i,n,r={}){const{useGroups:a=!0}=r,{aIntersections:o,bIntersections:l}=tF(s,e),c=[];let h=null,d;return d=a?0:-1,f2(s,e,o,t,!1,i,n,d),m2(s,e,o,t,!1,n,d),t.findIndex(p=>p!==s2&&p!==n2)!==-1&&(d=a?s.geometry.groups.length||1:-1,f2(e,s,l,t,!0,i,n,d),m2(e,s,l,t,!0,n,d)),As.length=0,Do.length=0,{groups:c,materials:h}}function f2(s,e,t,i,n,r,a,o=0){const l=s.matrixWorld.determinant()<0;va.copy(e.matrixWorld).invert().multiply(s.matrixWorld),xm.getNormalMatrix(s.matrixWorld).multiplyScalar(l?-1:1);const c=s.geometry.groupIndices,h=s.geometry.index,d=s.geometry.attributes.position,p=e.geometry.boundsTree,u=e.geometry.index,v=e.geometry.attributes.position,g=t.ids,m=t.intersectionSet;for(let f=0,y=g.length;f0;){const f=aF(g);g.delete(f),u.push(f);const y=3*f,x=h.getX(y+0),_=h.getX(y+1),S=h.getX(y+2);ya.a.fromBufferAttribute(p,x).applyMatrix4(va),ya.b.fromBufferAttribute(p,_).applyMatrix4(va),ya.c.fromBufferAttribute(p,S).applyMatrix4(va);const b=d2(ya,l);Do.length=0,As.length=0;for(let E=0,w=i.length;E0;){const E=u.pop();for(let w=0;w<3;w++){const M=v.getSiblingTriangleIndex(E,w);M!==-1&&g.has(M)&&(u.push(M),g.delete(M))}if(As.length!==0){const w=3*E,M=h.getX(w+0),C=h.getX(w+1),I=h.getX(w+2),P=a===-1?0:c[E]+a;if(ya.a.fromBufferAttribute(p,M),ya.b.fromBufferAttribute(p,C),ya.c.fromBufferAttribute(p,I),!ga(ya))for(let k=0,A=As.length;k{t[i.materialIndex]=e})),t}class dF{constructor(){this.triangleSplitter=new X7,this.attributeData=[],this.attributes=["position","uv","normal"],this.useGroups=!0,this.consolidateGroups=!0,this.debug=new rF}getGroupRanges(e){return!this.useGroups||e.groups.length===0?[{start:0,count:1/0,materialIndex:0}]:e.groups.map(t=>({...t}))}evaluate(e,t,i,n=new um){let r=!0;if(Array.isArray(i)||(i=[i]),Array.isArray(n)||(n=[n],r=!1),n.length!==i.length)throw new Error("Evaluator: operations and target array passed as different sizes.");e.prepareGeometry(),t.prepareGeometry();const{triangleSplitter:a,attributeData:o,attributes:l,useGroups:c,consolidateGroups:h,debug:d}=this;for(;o.length{cF(e.geometry,f.geometry,o[y],l)}),d.init(),oF(e,t,i,a,o,{useGroups:c}),d.complete();const p=this.getGroupRanges(e.geometry),u=g2(p,e.material),v=this.getGroupRanges(t.geometry),g=g2(v,t.material);v.forEach(f=>f.materialIndex+=u.length);let m=[...p,...v].map((f,y)=>({...f,index:y}));if(c){const f=[...u,...g];h&&(m=m.map(x=>{const _=f[x.materialIndex];return x.materialIndex=f.indexOf(_),x}).sort((x,_)=>x.materialIndex-_.materialIndex));const y=[];for(let x=0,_=f.length;x<_;x++){let S=!1;for(let b=0,E=m.length;b{x.material=y})}else m=[{start:0,count:1/0,index:0,materialIndex:0}],n.forEach(f=>{f.material=u[0]});return n.forEach((f,y)=>{const x=f.geometry;hF(x,o[y],m),h&&lF(x.groups)}),r?n:n[0]}evaluateHierarchy(e,t=new um){e.updateMatrixWorld(!0);const i=(r,a)=>{const o=r.children;for(let l=0,c=o.length;l{const a=r.children;let o=!1;for(let c=0,h=a.length;c{c?c=this.evaluate(c,h,h.operation):c=this.evaluate(r,h,h.operation)}),r._cachedGeometry=c.geometry,r._cachedMaterials=c.material,!0}else return o||l};return n(e),t.geometry=e._cachedGeometry,t.material=e._cachedMaterials,t}reset(){this.triangleSplitter.reset()}}class uF{engine;planeObjects=[];planes=[];isActive=!1;evaluator;geometryCache=new Map;sectionMeshes=new Map;planeGroup;planeSize=1e3;sourceMeshes=new Map;planeThickness=.01;updateThrottleTime=100;lastUpdateTime=0;pendingUpdate=!1;updateTimer=null;cacheExpireTime=3e4;planeStates=new Map;constructor(e,t={}){this.engine=e,this.evaluator=new dF,this.planeGroup=new pi,this.planeGroup.name="CSG_ClippingPlanes_Optimized",t.updateThrottleTime!==void 0&&(this.updateThrottleTime=t.updateThrottleTime),t.cacheExpireTime!==void 0&&(this.cacheExpireTime=t.cacheExpireTime),t.planeThickness!==void 0&&(this.planeThickness=t.planeThickness),this.evaluator.attributes=["position","normal"],this.evaluator.useGroups=!1}init(){this.calculateSceneSize(),this.engine.scene.add(this.planeGroup),this.planes.forEach((e,t)=>{const i=this.createEmptySectionMesh(e,t);this.planeGroup.add(i),this.sectionMeshes.set(`plane_${t}`,i),this.planeObjects.push(i),this.planeStates.set(t,{constant:e.constant,normal:e.normal.clone()})})}createEmptySectionMesh(e,t){const i=new at,n=new sr({color:new We(33023),metalness:.1,roughness:.75,side:Ot,depthWrite:!0,depthTest:!0,clippingPlanes:this.planes.filter((a,o)=>o!==t)}),r=new ht(i,n);return r.name=`CSG_Section_Optimized_${t}`,r.visible=!1,r.renderOrder=t+1,r}active(){this.isActive=!0,this.requestUpdate(),this.planeObjects.forEach(e=>{e.visible=!0})}disActive(){this.isActive=!1,this.planeObjects.forEach(e=>{e.visible=!1}),this.updateTimer&&(clearTimeout(this.updateTimer),this.updateTimer=null)}setSourceMeshes(e){this.sourceMeshes.clear(),e.forEach(t=>{const i=t.uuid;this.sourceMeshes.set(i,t)}),this.isActive&&this.requestUpdate()}addSourceMesh(e){const t=e.uuid;this.sourceMeshes.has(t)||(this.sourceMeshes.set(t,e),this.isActive&&this.requestUpdate())}removeSourceMesh(e){const t=e.uuid;this.sourceMeshes.delete(t)&&(this.clearMeshCache(t),this.isActive&&this.requestUpdate())}requestUpdate(){if(!this.isActive)return;const e=Date.now(),t=e-this.lastUpdateTime;t>=this.updateThrottleTime?(this.lastUpdateTime=e,this.pendingUpdate=!1):(this.pendingUpdate=!0,this.updateTimer&&clearTimeout(this.updateTimer),this.updateTimer=setTimeout(()=>{this.pendingUpdate&&this.isActive&&(this.lastUpdateTime=Date.now(),this.pendingUpdate=!1),this.updateTimer=null},this.updateThrottleTime-t))}updateAllSections(){this.isActive&&(this.planes.forEach((e,t)=>{if(Math.abs(e.constant)<99999)this.hasPlaneChanged(t,e)&&(this.updateSection(e,t),this.updatePlaneState(t,e));else{const i=this.sectionMeshes.get(`plane_${t}`);i&&(i.visible=!1)}}),this.cleanExpiredCache())}hasPlaneChanged(e,t){const i=this.planeStates.get(e);if(!i)return!0;const n=Math.abs(i.constant-t.constant)>1e-4,r=!i.normal.equals(t.normal);return n||r}updatePlaneState(e,t){this.planeStates.set(e,{constant:t.constant,normal:t.normal.clone()})}getPlaneHash(e){const t=e.normal,i=e.constant;return`${t.x.toFixed(4)}_${t.y.toFixed(4)}_${t.z.toFixed(4)}_${i.toFixed(4)}`}getCacheKey(e,t){return`${e}_plane_${t}`}updateSection(e,t){const i=this.sectionMeshes.get(`plane_${t}`);if(!i)return;const n=this.getPlaneHash(e),r=[];if(this.sourceMeshes.forEach((a,o)=>{const l=this.getCacheKey(o,t),c=this.geometryCache.get(l);if(c&&c.planeHash===n)r.push(c.geometry.clone()),c.timestamp=Date.now();else try{const h=this.createPlaneBrush(e),d=new um(a.geometry);a.updateMatrixWorld(!0),d.matrix.copy(a.matrixWorld),d.updateMatrixWorld();const p=this.evaluator.evaluate(h,d,i2);p&&p.geometry.attributes.position.count>0?(r.push(p.geometry),this.geometryCache.set(l,{geometry:p.geometry.clone(),planeHash:n,timestamp:Date.now()})):this.geometryCache.delete(l)}catch(h){console.warn(`CSG intersection failed for mesh ${o}:`,h)}}),r.length>0){const a=this.mergeGeometries(r);i.geometry&&i.geometry.dispose(),i.geometry=a,i.visible=!0,i.position.set(0,0,0),i.rotation.set(0,0,0),i.scale.set(1,1,1),i.updateMatrixWorld()}else i.visible=!1;r.forEach(a=>a.dispose())}clearMeshCache(e){const t=[];this.geometryCache.forEach((i,n)=>{n.startsWith(e)&&(i.geometry.dispose(),t.push(n))}),t.forEach(i=>this.geometryCache.delete(i))}cleanExpiredCache(){const e=Date.now(),t=[];this.geometryCache.forEach((i,n)=>{e-i.timestamp>this.cacheExpireTime&&(i.geometry.dispose(),t.push(n))}),t.forEach(i=>this.geometryCache.delete(i))}clearAllCache(){this.geometryCache.forEach(e=>{e.geometry.dispose()}),this.geometryCache.clear()}createPlaneBrush(e){const t=new fs(this.planeSize,this.planeThickness,this.planeSize);t.translate(0,e.constant,0),t.applyQuaternion(new Kt().setFromUnitVectors(new R(0,-1,0),e.normal));const i=new ht(t),n=new um(t);return n.matrix.copy(i.matrixWorld),n.updateMatrixWorld(),n}mergeGeometries(e){if(e.length===1)return e[0].clone();const t=new at,i=[],n=[],r=[];let a=0;return e.forEach(o=>{const l=o.attributes.position,c=o.attributes.normal;for(let h=0;h0?t.setAttribute("normal",new et(n,3)):t.computeVertexNormals(),r.length>0&&t.setIndex(r),t}calculateSceneSize(){const e=new vt;if(this.engine.scene.traverse(t=>{if(t.isMesh&&t.geometry){const i=new vt().setFromObject(t);e.union(i)}}),e.isEmpty())this.planeSize=1e3;else{const t=e.getSize(new R),i=Math.max(t.x,t.y,t.z);this.planeSize=i*3}}update(){this.isActive&&this.pendingUpdate&&!this.updateTimer&&this.requestUpdate()}dispose(){this.updateTimer&&(clearTimeout(this.updateTimer),this.updateTimer=null),this.clearAllCache(),this.planeObjects.forEach(e=>{e.geometry&&e.geometry.dispose(),e.material&&(Array.isArray(e.material)?e.material.forEach(t=>t.dispose()):e.material.dispose())}),this.sectionMeshes.clear(),this.planeObjects=[],this.sourceMeshes.clear(),this.planeGroup.parent&&this.planeGroup.parent.remove(this.planeGroup)}setSectionColor(e){this.planeObjects.forEach(t=>{t.material instanceof sr&&t.material.color.set(e)})}getCacheStats(){return{cacheSize:this.geometryCache.size,sourceMeshCount:this.sourceMeshes.size,sectionMeshCount:this.sectionMeshes.size}}setPlaneThickness(e){if(e<=0){console.warn("Plane thickness must be positive");return}this.planeThickness=e,this.clearAllCache(),this.isActive&&this.requestUpdate()}getPlaneThickness(){return this.planeThickness}showSections(){this.sectionMeshes.forEach(e=>{e.geometry?.attributes.position?.count&&e.geometry.attributes.position.count>0&&(e.visible=!0)})}hideSections(){this.sectionMeshes.forEach(e=>{e.visible=!1})}showSection(){this.planeGroup.visible=!0}hideSection(){this.planeGroup.visible=!1}toggleSectionsVisibility(){let e=!1;return this.sectionMeshes.forEach(t=>{t.visible&&(e=!0)}),e?(this.hideSections(),!1):(this.showSections(),!0)}toggleSectionVisibility(e){const t=this.sectionMeshes.get(`plane_${e}`);return t?(t.visible=!t.visible,t.visible):!1}}class pF{engine;isActive=!1;isCtrlDown=!1;listenersAttached=!1;box;pickPoint;pickNormal;pickMesh;box_;plane;meshs;isDrag=!1;maxBox;handleNativeMouseDown=e=>{if(e.button!==0||!(this.isCtrlDown||e.ctrlKey))return;const t=this.createRaycasterFromMouseEvent(e);t.intersectObjects(this.getInteractiveMeshes(),!1).length!==0&&(e.preventDefault(),e.stopImmediatePropagation(),this.handleMouseDown({button:e.button,raycaster:t}))};handleNativeMouseMove=e=>{if(!this.isDrag&&!(this.isCtrlDown||e.ctrlKey)){this.resetMeshOpacity();return}const t=this.createRaycasterFromMouseEvent(e);this.isDrag&&(e.preventDefault(),e.stopImmediatePropagation()),this.handleMouseMove({raycaster:t})};handleNativeMouseUp=e=>{e.button!==0||!this.isDrag||(e.preventDefault(),e.stopImmediatePropagation(),this.handleMouseUp({button:e.button}))};handleNativeKeyDown=e=>{e.key==="Control"&&(this.isCtrlDown=!0)};handleNativeKeyUp=e=>{e.key==="Control"&&(this.isCtrlDown=!1,this.isDrag&&this.handleMouseUp({button:0}),this.resetMeshOpacity())};csgClipping=null;useCsgClipping=!1;constructor(e,t){this.engine=e,this.meshs=[],t?.useCsgClipping!==void 0&&(this.useCsgClipping=t.useCsgClipping),this.useCsgClipping&&this.initCsgClipping()}initCsgClipping(){this.csgClipping=new uF(this.engine,{updateThrottleTime:150,cacheExpireTime:45e3}),this.csgClipping.planes=this.engine.sectionPlane,this.csgClipping.init()}active(){this.isActive||(this.attachListeners(),this.engine.scene.children.filter(e=>e.type=="Group"&&e.name=="ClippingBox").forEach(e=>{e.children.forEach(t=>{t.name.includes("face")||(t.visible=!0)})}),this.isActive=!0,this.init())}disActive(){this.init(),this.isActive=!1,this.detachListeners(),this.handleMouseUp({button:0}),this.csgClipping&&this.csgClipping.disActive(),this.engine.scene.children.filter(e=>e.type=="Group"&&e.name=="ClippingBox").forEach(e=>{e.children.forEach(t=>{t.name.includes("face")||(t.visible=!1)})})}disabled(){this.isActive=!1,this.detachListeners(),this.handleMouseUp({button:0}),this.engine.scene.children.filter(e=>e.type=="Group"&&e.name=="ClippingBox").forEach(e=>{e.children.forEach(t=>{t.name.includes("face")||(t.visible=!1)})})}recover(){this.isActive||(this.attachListeners(),this.engine.scene.children.filter(e=>e.type=="Group"&&e.name=="ClippingBox").forEach(e=>{e.children.forEach(t=>{t.name.includes("face")||(t.visible=!0)})}),this.isActive=!0)}init(){let e=this.engine.octreeBox.getBoundingBox();e.min.x-=.1,e.min.y-=.1,e.min.z-=.1,e.max.x+=.1,e.max.y+=.1,e.max.z+=.1,this.maxBox=JSON.parse(JSON.stringify(e)),this.box=e,this.updata_face(e)}getboxXyz(){return{minX:this.box.min.x,minY:this.box.min.y,minZ:this.box.min.z,maxX:this.box.max.x,maxY:this.box.max.y,maxZ:this.box.max.z}}setboxXyz(e){this.box.min.x=e.minX,this.box.min.y=e.minY,this.box.min.z=e.minZ,this.box.max.x=e.maxX,this.box.max.y=e.maxY,this.box.max.z=e.maxZ,this.updata_face(this.box)}setBox(e){this.box=e,this.updata_face(e)}reverseBox(){}handleMouseDown(e){this.isDrag=!0;const t=e.raycaster.intersectObjects(this.getInteractiveMeshes(),!1);if(t!=null&&t.length>0)if(this.pickPoint=t[0].point,this.pickNormal=t[0].face.normal,this.engine.controls.enabled=!1,this.pickMesh=t[0].object,this.box_={min:this.box.min.clone(),max:this.box.max.clone()},this.pickNormal.y==0){const i=new Yt;i.setFromNormalAndCoplanarPoint(new R(0,1,0),this.pickPoint),this.plane=i}else{let i=new R(this.engine.camera.position.x,this.pickPoint.y,this.engine.camera.position.z);const n=new Yt;n.setFromNormalAndCoplanarPoint(i.clone().sub(this.pickPoint.clone()).setLength(1),this.pickPoint),this.plane=n}}handleMouseUp(e){this.isDrag=!1,this.pickPoint=null,this.pickNormal=null,this.pickMesh=null,this.plane=null,this.engine.controls.enabled=!0,this.csgClipping&&this.isActive}clampVector3(e,t,i){return new R(Math.max(t.x,Math.min(i.x,e.x)),Math.max(t.y,Math.min(i.y,e.y)),Math.max(t.z,Math.min(i.z,e.z)))}handleMouseMove(e){this.resetMeshOpacity();const t=e.raycaster.intersectObjects(this.getInteractiveMeshes(),!1);if(t!=null&&t.length>0&&(t[0].object.material.opacity=.05),this.pickPoint!=null){const i=new R;if(e.raycaster.ray.intersectPlane(this.plane,i)){let n=i.clone().sub(this.pickPoint.clone()).dot(this.pickNormal.clone());if(this.pickMesh.name=="前"||this.pickMesh.name=="左"||this.pickMesh.name=="底"){let r=this.box_.min.clone().add(this.pickNormal.clone().setLength(n));this.box.min=this.clampVector3(r,this.maxBox.min,this.box.max)}else{let r=this.box_.max.clone().add(this.pickNormal.clone().setLength(n));this.box.max=this.clampVector3(r,this.box.min,this.maxBox.max)}this.updata_face(this.box),this.calculate_ratio()}}}calculate_ratio(){let e=this.maxBox.max.x-this.maxBox.min.x,t=this.maxBox.max.y-this.maxBox.min.y,i=this.maxBox.max.z-this.maxBox.min.z,n=(this.box.min.x-this.maxBox.min.x)/e*100,r=(this.box.max.x-this.maxBox.min.x)/e*100,a=(this.box.min.y-this.maxBox.min.y)/t*100,o=(this.box.max.y-this.maxBox.min.y)/t*100,l=(this.box.min.z-this.maxBox.min.z)/i*100,c=(this.box.max.z-this.maxBox.min.z)/i*100;n<0&&(n=0),r<0&&(r=0),a<0&&(a=0),o<0&&(o=0),l<0&&(l=0),c<0&&(c=0),n>100&&(n=100),r>100&&(r=100),a>100&&(a=100),o>100&&(o=100),l>100&&(l=100),c>100&&(c=100);let h={x:{min:n,max:r},y:{min:a,max:o},z:{min:l,max:c}};this.engine.events.trigger(di.SectionMove,h)}getInteractiveMeshes(){return this.meshs.filter(e=>e.type==="Mesh")}createRaycasterFromMouseEvent(e){const t=new Qn,i=new me,n=this.engine.renderer.domElement.clientWidth,r=this.engine.renderer.domElement.clientHeight;return i.x=e.offsetX/n*2-1,i.y=-(e.offsetY/r)*2+1,t.setFromCamera(i,this.engine.camera),t}attachListeners(){if(this.listenersAttached)return;const e=this.engine.renderer?.domElement;e&&(e.addEventListener("mousedown",this.handleNativeMouseDown,!0),e.addEventListener("mousemove",this.handleNativeMouseMove,!0),e.addEventListener("mouseup",this.handleNativeMouseUp,!0),window.addEventListener("keydown",this.handleNativeKeyDown),window.addEventListener("keyup",this.handleNativeKeyUp),this.listenersAttached=!0)}detachListeners(){if(!this.listenersAttached)return;const e=this.engine.renderer?.domElement;e&&(e.removeEventListener("mousedown",this.handleNativeMouseDown,!0),e.removeEventListener("mousemove",this.handleNativeMouseMove,!0),e.removeEventListener("mouseup",this.handleNativeMouseUp,!0)),window.removeEventListener("keydown",this.handleNativeKeyDown),window.removeEventListener("keyup",this.handleNativeKeyUp),this.listenersAttached=!1,this.isCtrlDown=!1}resetMeshOpacity(){this.getInteractiveMeshes().forEach(e=>{e.material&&(e.material.opacity=0)})}updata_face(e){let t=this,i=[new R(e.min.x,e.min.y,e.min.z),new R(e.max.x,e.min.y,e.min.z),new R(e.max.x,e.max.y,e.min.z),new R(e.min.x,e.max.y,e.min.z)],n=[new R(e.min.x,e.min.y,e.max.z),new R(e.max.x,e.min.y,e.max.z),new R(e.max.x,e.max.y,e.max.z),new R(e.min.x,e.max.y,e.max.z)];i.reverse();let r=[new R(e.max.x,e.min.y,e.max.z),new R(e.max.x,e.min.y,e.min.z),new R(e.max.x,e.max.y,e.min.z),new R(e.max.x,e.max.y,e.max.z)],a=[new R(e.min.x,e.min.y,e.min.z),new R(e.min.x,e.min.y,e.max.z),new R(e.min.x,e.max.y,e.max.z),new R(e.min.x,e.max.y,e.min.z)],o=[new R(e.min.x,e.max.y,e.min.z),new R(e.max.x,e.max.y,e.min.z),new R(e.max.x,e.max.y,e.max.z),new R(e.min.x,e.max.y,e.max.z)];o.reverse();let l=[new R(e.min.x,e.min.y,e.min.z),new R(e.max.x,e.min.y,e.min.z),new R(e.max.x,e.min.y,e.max.z),new R(e.min.x,e.min.y,e.max.z)];c(i,new R(0,0,-1),"前"),c(n,new R(0,0,1),"后"),c(r,new R(1,0,0),"右"),c(a,new R(-1,0,0),"左"),c(o,new R(0,1,0),"顶"),c(l,new R(0,-1,0),"底");function c(h,d,p){const u=new at,v=new Float32Array([h[0].x,h[0].y,h[0].z,h[1].x,h[1].y,h[1].z,h[2].x,h[2].y,h[2].z,h[3].x,h[3].y,h[3].z]),g=[0,2,1,0,3,2];u.setAttribute("position",new St(v,3)),u.setIndex(g);let m=t.engine.scene.children.find(b=>b.type=="Group"&&b.name=="ClippingBox");m==null&&(m=new pi,m.name="ClippingBox",t.engine.scene.add(m));let f=t.meshs.find(b=>b.name==p);if(f==null){const b=new Dt({color:65280,transparent:!0,opacity:0,side:Ot});b.polygonOffset=!0,b.polygonOffsetFactor=1,b.polygonOffsetUnits=4;const E=new ht(u,b);E.normal=d,E.name=p,m.add(E),t.meshs.push(E)}else f.geometry=u;const y=new Float32Array([h[0].x,h[0].y,h[0].z,h[1].x,h[1].y,h[1].z,h[2].x,h[2].y,h[2].z,h[3].x,h[3].y,h[3].z,h[0].x,h[0].y,h[0].z]);let x=new si({color:255}),_=new at;_.setAttribute("position",new St(y,3));let S=t.meshs.find(b=>b.name==p+"Line");S==null&&(S=new pn(_,x),S.name=p+"Line",m.add(S),t.meshs.push(S)),S.geometry=_,S.material=x,p=="前"||p=="左"||p=="底"?t.engine.sectionPlane.find(b=>b.name==p).setFromNormalAndCoplanarPoint(d.clone().setLength(-1),e.min):t.engine.sectionPlane.find(b=>b.name==p).setFromNormalAndCoplanarPoint(d.clone().setLength(-1),e.max),t.engine.scene.children.filter(b=>b.type=="Mesh"&&b.url).forEach(b=>{b.material&&Array.isArray(b.material)?b.material.forEach(E=>{E.clippingPlanes=t.engine.sectionPlane}):b.material.clippingPlanes=t.engine.sectionPlane})}}}class fF{engine;isActive=!1;isDrag=!1;isCtrlDown=!1;listenersAttached=!1;meshs=[];box=null;pickPoint=null;pickNormal=null;pickMesh=null;box_;plane=null;angleX=0;angleY=0;angleZ=0;direction=1;normal=new R(0,0,1);distance=0;center=null;current_center=null;dragStartDistance=0;idleOpacity=.02;hoverOpacity=.05;handleNativeMouseDown=e=>{if(e.button!==0||!(this.isCtrlDown||e.ctrlKey))return;const t=this.createRaycasterFromMouseEvent(e);t.intersectObjects(this.getInteractiveMeshes(),!1).length!==0&&(e.preventDefault(),e.stopImmediatePropagation(),this.handleMouseDown({button:e.button,raycaster:t}))};handleNativeMouseMove=e=>{if(!this.isDrag&&!(this.isCtrlDown||e.ctrlKey)){this.resetMeshOpacity();return}const t=this.createRaycasterFromMouseEvent(e);this.isDrag&&(e.preventDefault(),e.stopImmediatePropagation()),this.handleMouseMove({raycaster:t})};handleNativeMouseUp=e=>{e.button!==0||!this.isDrag||(e.preventDefault(),e.stopImmediatePropagation(),this.handleMouseUp({button:e.button}))};handleNativeKeyDown=e=>{e.key==="Control"&&(this.isCtrlDown=!0)};handleNativeKeyUp=e=>{e.key==="Control"&&(this.isCtrlDown=!1,this.isDrag&&this.handleMouseUp({button:0}),this.resetMeshOpacity())};constructor(e){this.engine=e,this.meshs=[],this.box=null}active(){if(this.isActive==!0)return;this.isActive=!0,this.engine.scene.children.filter(t=>t.type=="Group"&&t.name=="ClippingBox").forEach(t=>{t.children.forEach(i=>{i.name.includes("face")&&(i.visible=!0)})}),this.attachListeners();const e=this;e.engine.scene.children.filter(t=>t.type=="Mesh"&&t.url).forEach(t=>{t.material&&Array.isArray(t.material)?t.material.forEach(i=>{i.clippingPlanes=e.engine.sectionPlane}):t.material.clippingPlanes=e.engine.sectionPlane,e.engine.clipping.clippingStencil?.addMesh(e.engine.sectionPlane.find(i=>i.name=="face"),t)}),this.init()}disActive(){this.init(),this.isActive=!1,this.detachListeners(),this.handleMouseUp({button:0});const e=this.engine.sectionPlane.find(t=>t.name=="face");e&&(e.constant=1e5),this.engine.scene.children.filter(t=>t.type=="Group"&&t.name=="ClippingBox").forEach(t=>{t.children.forEach(i=>{i.name.includes("face")&&(i.visible=!1)})})}init(e){const t=this.engine.octreeBox.getBoundingBox();this.box=t,this.distance=0,this.center=new R((t.min.x+t.max.x)/2,(t.min.y+t.max.y)/2,(t.min.z+t.max.z)/2),this.current_center=this.center.clone(),!e&&this.updata_face(0)}disabled(){this.isActive=!1,this.detachListeners(),this.handleMouseUp({button:0}),this.engine.scene.children.filter(e=>e.type=="Group"&&e.name=="ClippingBox").forEach(e=>{e.children.forEach(t=>{t.name.includes("face")&&(t.visible=!1)})})}recover(){this.isActive||(this.attachListeners(),this.engine.scene.children.filter(e=>e.type=="Group"&&e.name=="ClippingBox").forEach(e=>{e.children.forEach(t=>{t.name.includes("face")&&(t.visible=!0)})}),this.isActive=!0)}setFaceAngle(e,t,i){this.angleX=e,this.angleY=t,this.angleZ=i,this.distance=0,this.normal=new R(0,1,0).applyAxisAngle(new R(1,0,0),e).applyAxisAngle(new R(0,0,1),t).applyAxisAngle(new R(0,1,0),i).normalize(),this.updata_face(0)}setFaceNormal(e,t=0){this.normal=e.clone().normalize(),this.distance=t,this.updata_face(t)}setFaceNormalPlaneOnly(e,t){if(this.normal=e.clone().normalize(),this.distance=t,!this.center||!this.box)return;const i=this.engine.sectionPlane?.find(n=>n.name==="face");if(i){const n=this.center.clone().add(this.normal.clone().multiplyScalar(t));i.setFromNormalAndCoplanarPoint(this.normal.clone().multiplyScalar(this.direction),n)}}activateClippingOnly(){if(this.isActive)return;this.isActive=!0;const e=this;e.engine.scene.children.filter(t=>t.type==="Mesh"&&t.url).forEach(t=>{t.material&&Array.isArray(t.material)?t.material.forEach(i=>{i.clippingPlanes=e.engine.sectionPlane}):t.material.clippingPlanes=e.engine.sectionPlane,e.engine.clipping.clippingStencil?.addMesh(e.engine.sectionPlane.find(i=>i.name==="face"),t)})}reverse(){this.direction=this.direction*-1,this.updata_face(this.distance)}getFaceAngle(){return{angleX:this.angleX,angleY:this.angleY,angleZ:this.angleZ,direction:this.direction}}updata_face(e){if(!this.box)return;this.distance=e;let t=this.engine.scene.children.find(x=>x.type=="Group"&&x.name=="ClippingBox");t==null&&(t=new pi,t.name="ClippingBox",this.engine.scene.add(t));const i=this.normal.clone().normalize(),n=this.center??new R((this.box.min.x+this.box.max.x)/2,(this.box.min.y+this.box.max.y)/2,(this.box.min.z+this.box.max.z)/2);this.center=n.clone();const{tangent:r,bitangent:a}=this.getPlaneBasis(i),o=this.getBoxCorners(this.box),l=this.box.min.distanceTo(this.box.max),c=Math.max(l*.02,.01);let h=1/0,d=-1/0,p=1/0,u=-1/0;o.forEach(x=>{const _=x.clone().sub(n),S=_.dot(r),b=_.dot(a);h=Math.min(h,S),d=Math.max(d,S),p=Math.min(p,b),u=Math.max(u,b)}),h-=c,d+=c,p-=c,u+=c;const v=i.clone().multiplyScalar(e),g=n.clone().add(r.clone().multiplyScalar(h)).add(a.clone().multiplyScalar(p)).add(v),m=n.clone().add(r.clone().multiplyScalar(d)).add(a.clone().multiplyScalar(p)).add(v),f=n.clone().add(r.clone().multiplyScalar(d)).add(a.clone().multiplyScalar(u)).add(v),y=n.clone().add(r.clone().multiplyScalar(h)).add(a.clone().multiplyScalar(u)).add(v);this.current_center=n.clone().add(v),this.createFace(t,[g,m,f,y],i,"face")}createFace(e,t,i,n){const r=new at,a=new Float32Array([t[0].x,t[0].y,t[0].z,t[1].x,t[1].y,t[1].z,t[2].x,t[2].y,t[2].z,t[3].x,t[3].y,t[3].z]),o=[0,1,2,0,2,3];r.setAttribute("position",new St(a,3)),r.setIndex(o);let l=this.meshs.find(v=>v.name==n);if(l==null){const v=new Dt({color:65280,transparent:!0,opacity:.02,side:Ot});v.polygonOffset=!0,v.polygonOffsetFactor=1,v.polygonOffsetUnits=4,l=new ht(r,v),l.name=n,e.add(l),this.meshs.push(l)}else l.geometry=r;l.normal=i.clone();const c=new Float32Array([t[0].x,t[0].y,t[0].z,t[1].x,t[1].y,t[1].z,t[2].x,t[2].y,t[2].z,t[3].x,t[3].y,t[3].z,t[0].x,t[0].y,t[0].z]),h=new si({color:255}),d=new at;d.setAttribute("position",new St(c,3));let p=this.meshs.find(v=>v.name==n+"Line");p==null?(p=new pn(d,h),p.name=n+"Line",e.add(p),this.meshs.push(p)):(p.geometry=d,p.material=h);const u=this.engine.sectionPlane.find(v=>v.name==n);u&&this.current_center&&u.setFromNormalAndCoplanarPoint(i.clone().setLength(this.direction),this.current_center)}getPlaneBasis(e){const t=new R(1,0,0),i=new R(0,1,0),n=new R(0,0,1),r=Math.abs(e.dot(t)),a=Math.abs(e.dot(i)),o=Math.abs(e.dot(n));let l=t;a<=r&&a<=o?l=i:o<=r&&o<=a&&(l=n),l=l.clone().sub(e.clone().multiplyScalar(l.dot(e))).normalize();const c=new R().crossVectors(e,l).normalize();return{tangent:l,bitangent:c}}getBoxCorners(e){return[new R(e.min.x,e.min.y,e.min.z),new R(e.min.x,e.min.y,e.max.z),new R(e.min.x,e.max.y,e.min.z),new R(e.min.x,e.max.y,e.max.z),new R(e.max.x,e.min.y,e.min.z),new R(e.max.x,e.min.y,e.max.z),new R(e.max.x,e.max.y,e.min.z),new R(e.max.x,e.max.y,e.max.z)]}getDistanceRange(e){if(!this.box)return{min:0,max:0};const t=this.center??new R((this.box.min.x+this.box.max.x)/2,(this.box.min.y+this.box.max.y)/2,(this.box.min.z+this.box.max.z)/2),i=this.getBoxCorners(this.box);let n=1/0,r=-1/0;return i.forEach(a=>{const o=a.clone().sub(t).dot(e);n=Math.min(n,o),r=Math.max(r,o)}),{min:n,max:r}}getInteractiveMeshes(){return this.meshs.filter(e=>e.type==="Mesh")}createRaycasterFromMouseEvent(e){const t=new Qn,i=new me,n=this.engine.renderer.domElement.clientWidth,r=this.engine.renderer.domElement.clientHeight;return i.x=e.offsetX/n*2-1,i.y=-(e.offsetY/r)*2+1,t.setFromCamera(i,this.engine.camera),t}attachListeners(){if(this.listenersAttached)return;const e=this.engine.renderer?.domElement;e&&(e.addEventListener("mousedown",this.handleNativeMouseDown,!0),e.addEventListener("mousemove",this.handleNativeMouseMove,!0),e.addEventListener("mouseup",this.handleNativeMouseUp,!0),window.addEventListener("keydown",this.handleNativeKeyDown),window.addEventListener("keyup",this.handleNativeKeyUp),this.listenersAttached=!0)}detachListeners(){if(!this.listenersAttached)return;const e=this.engine.renderer?.domElement;e&&(e.removeEventListener("mousedown",this.handleNativeMouseDown,!0),e.removeEventListener("mousemove",this.handleNativeMouseMove,!0),e.removeEventListener("mouseup",this.handleNativeMouseUp,!0)),window.removeEventListener("keydown",this.handleNativeKeyDown),window.removeEventListener("keyup",this.handleNativeKeyUp),this.listenersAttached=!1,this.isCtrlDown=!1}resetMeshOpacity(){this.getInteractiveMeshes().forEach(e=>{e.material&&(e.material.opacity=this.idleOpacity)})}handleMouseDown(e){this.isDrag=!0;const t=e.raycaster.intersectObjects(this.getInteractiveMeshes(),!1);if(t!=null&&t.length>0)if(this.pickPoint=t[0].point.clone(),this.pickNormal=t[0].face.normal.clone(),this.engine.controls.enabled=!1,this.pickMesh=t[0].object,this.box_={min:this.box?.min.clone(),max:this.box?.max.clone()},this.dragStartDistance=Number(this.distance)||0,this.pickNormal.y==0){const i=new Yt;i.setFromNormalAndCoplanarPoint(new R(0,1,0),this.pickPoint),this.plane=i}else{const i=new R(this.engine.camera.position.x,this.pickPoint.y,this.engine.camera.position.z),n=new Yt;n.setFromNormalAndCoplanarPoint(i.clone().sub(this.pickPoint.clone()).setLength(1),this.pickPoint),this.plane=n}}handleMouseUp(e){this.isDrag=!1,this.pickPoint=null,this.pickNormal=null,this.pickMesh=null,this.plane=null,this.engine.controls.enabled=!0}handleMouseMove(e){this.resetMeshOpacity();const t=e.raycaster.intersectObjects(this.getInteractiveMeshes(),!1);if(t!=null&&t.length>0&&(t[0].object.material.opacity=this.hoverOpacity),this.pickPoint!=null&&this.pickNormal!=null&&this.plane!=null){const i=new R;if(e.raycaster.ray.intersectPlane(this.plane,i)){const n=i.clone().sub(this.pickPoint.clone()).dot(this.pickNormal.clone()),r=this.getDistanceRange(this.normal.clone().normalize()),a=this.dragStartDistance+n;this.distance=Math.min(r.max,Math.max(r.min,a)),this.updata_face(this.distance)}}}}class mF{engine;callback_;constructor(e){this.engine=e}init(){this.engine.handelBehaved.init(this,{showCatch:!0}),this.engine.handelBehaved.active()}catch_face(e){this.callback_=e}handleMouseMove(e){}handleMouseClick(e){if(!e.catch?.normal||!e.catch?.point)return;let t=e.catch.normal.setLength(-1);this.engine.handelBehaved.disActive(),this.callback_({dir:t,position:e.catch.point})}}class gF{engine;clippingTolerance=1e-4;sectionBox;sectionFace;clippingStencil;currentClippingMode="";constructor(e){this.engine=e;let t=new Yt(new R(0,0,1),1e5);t.name="前";let i=new Yt(new R(0,0,1),1e5);i.name="左";let n=new Yt(new R(0,0,1),1e5);n.name="后";let r=new Yt(new R(0,0,1),1e5);r.name="右";let a=new Yt(new R(0,0,1),1e5);a.name="顶";let o=new Yt(new R(0,0,1),1e5);o.name="底";let l=new Yt(new R(0,0,1),1e5);l.name="face",this.engine.sectionPlane=[t,i,n,r,a,o,l]}init(){this.sectionBox=new pF(this.engine),this.sectionFace=new fF(this.engine)}scaleBox(){let e=this.engine.octreeBox.getBoundingBox();this.sectionBox.setBox(e)}clippingModel(e){let t=[];e.forEach(r=>{let a=this.engine.models.find(o=>o.url===r.url);r.ids.forEach(o=>{a.nodesMap.get(o).infos.forEach(l=>{t.push(l.box)})})}),this.active("box");let i=n(t);this.sectionBox.setBox(i);function n(r){let a=new R(1e8,1e9,1e10),o=new R(-1e8,-1e9,-1e10);return r.forEach(l=>{l.min.xo.x&&(o.x=l.max.x),l.max.y>o.y&&(o.y=l.max.y),l.max.z>o.z&&(o.z=l.max.z)}),new vt(a,o)}}updateClippingValue(e){let t=this.sectionBox.maxBox,i=t.min.x+(t.max.x-t.min.x)*e.x.min*.01,n=t.min.y+(t.max.y-t.min.y)*e.y.min*.01,r=t.min.z+(t.max.z-t.min.z)*e.z.min*.01,a=t.min.x+(t.max.x-t.min.x)*e.x.max*.01,o=t.min.y+(t.max.y-t.min.y)*e.y.max*.01,l=t.min.z+(t.max.z-t.min.z)*e.z.max*.01;this.sectionBox.setboxXyz({minX:i,minY:n,minZ:r,maxX:a,maxY:o,maxZ:l})}active(e){if(this.engine.engineStatus.isForceFree=!0,this.sectionFace.disActive(),this.sectionBox.disActive(),this.currentClippingMode=e,e=="x")this.sectionFace.init(),this.sectionFace.active(),this.sectionFace.setFaceAngle(Math.PI/2,0,0);else if(e=="y")this.sectionFace.init(),this.sectionFace.active(),this.sectionFace.setFaceAngle(0,Math.PI/2,0);else if(e=="z")this.sectionFace.init(),this.sectionFace.active(),this.sectionFace.setFaceAngle(0,0,Math.PI/2);else if(e=="box")this.sectionBox.init(),this.sectionBox.active();else if(e=="face"){let t=new mF(this.engine);t.init(),t.catch_face(i=>{this.sectionFace.init(),this.sectionFace.active();let n=this.engine.octreeBox.getBoundingBox(),r=n.min.clone().add(n.max.clone()).multiplyScalar(.5),a=i.position.clone().sub(r),o=new R(i.dir.x,i.dir.y,i.dir.z),l=a.dot(o);this.sectionFace.setFaceNormal(i.dir,l)})}}disabled(){this.currentClippingMode=="box"?this.sectionBox.disabled():this.sectionFace.disabled(),this.engine.engineStatus.isForceFree=!1}recover(){this.currentClippingMode=="box"?this.sectionBox.recover():this.sectionFace.recover()}reverse(){this.sectionFace.reverse()}disActive(){this.sectionFace.disActive(),this.sectionBox.disActive(),this.currentClippingMode="",this.engine.engineStatus.isForceFree=!1}isPointInClippingRange(e,t=this.clippingTolerance){if(!this.isVector3Like(e))return!1;const i=this.getEffectiveClippingPlanes();return i.length===0?!0:i.every(n=>n.distanceToPoint(e)>=-t)}filterIntersectionsByClipping(e,t=this.clippingTolerance){return!Array.isArray(e)||e.length===0?[]:e.filter(i=>this.isPointInClippingRange(i?.point,t))}getEffectiveClippingPlanes(){const e=Array.isArray(this.engine.sectionPlane)?this.engine.sectionPlane:[];if(this.currentClippingMode==="box")return e.slice(0,6).filter(t=>t instanceof Yt);if(this.currentClippingMode==="x"||this.currentClippingMode==="y"||this.currentClippingMode==="z"||this.currentClippingMode==="face"){const t=e[6];return t instanceof Yt?[t]:[]}return[]}isVector3Like(e){return e!=null&&typeof e.x=="number"&&typeof e.y=="number"&&typeof e.z=="number"}setSectionByView(e,t){this.sectionFace.disActive(),this.sectionBox.disActive(),this.scaleBox(),this.sectionFace.init(!0);const i=this.engine.octreeBox.getBoundingBox(),n=new R((i.min.x+i.max.x)/2,(i.min.y+i.max.y)/2,(i.min.z+i.max.z)/2),r=new R(t.x,t.y,t.z).normalize().clone().negate(),a=new R(e.x,e.y,e.z).clone().sub(n).dot(r);this.sectionFace.setFaceNormalPlaneOnly(r,a),this.sectionFace.activateClippingOnly(),this.currentClippingMode="face"}}class vF{engine;constructor(e){this.engine=e}getLevelTreeData(){let e=[];return this.engine.engineStatus.models.forEach(t=>{e.push({children:t.info.modelTree.modelTreeLevel,name:t.info.baseInfo.name,url:t.url})}),e}getTypeTreeData(){let e=[];return this.engine.engineStatus.models.forEach(t=>{e.push({children:t.info.modelTree.modelTreeType,name:t.info.baseInfo.name,url:t.url})}),e}getMajorTreeData(){let e=[];return this.engine.engineStatus.models.forEach(t=>{e.push({children:t.info.modelTree.modelTreeMajor,name:t.info.baseInfo.name,url:t.url})}),e}}class yF{engine;constructor(e){this.engine=e}getEngineInfo(){let e=0,t=0,i=0;return!this.engine||!this.engine.scene?{totalVertices:0,totalTriangles:0,meshCount:0}:(this.engine.scene.traverse(n=>{if(n instanceof ht){const r=n.geometry;if(r&&r.attributes){const a=r.attributes.position;if(a){const o=a.count;e+=o;let l=0;r.index?l=r.index.count/3:l=o/3,t+=l}}}}),this.engine.engineStatus.models.forEach(n=>{i=i+(Array.isArray(n?.info?.modelEdge)?n.info.modelEdge.length:0)}),{totalVertices:Math.floor(e),totalTriangles:Math.floor(t),meshCount:i})}}class xF{engine;constructor(e){this.engine=e}init(){}getModelPropertiesWithName(e,t,i,n){let r=this.engine.engineStatus.models.find(o=>o.url===e);r.properties==null?Uh(e+"/property",o=>{let l=JSON.parse(o);r.properties=l,setTimeout(()=>{a(l,i,t,n)},100)}):a(r.properties,i,t,n);function a(o,l,c,h){let d={};o.models[c.toString()||""].forEach(p=>{i.includes(o.names[p[1]])&&(d[o.names[p[1]]]=o.values[p[2]])}),h?.({id:c,properties:d})}}getModelProperties(e,t,i){let n=this.engine.engineStatus.models.find(a=>a.url===e);n.properties==null&&Uh(e+"/property",a=>{let o=JSON.parse(a);n.properties=o,setTimeout(()=>{r(o,t,i)},100)}),r(n.properties,t,i);function r(a,o,l){let c=[],h=a.models[o.toString()||""],d=h.map(p=>p[0]);d=d.filter((p,u)=>d.indexOf(p)===u),d.forEach(p=>{let u={name:a.categorys[p],children:[]};c.push(u),h.filter(v=>v[0]===p).forEach(v=>{u.children.push({name:a.names[v[1]],value:a.values[v[2]]})})}),l?.({properties:c,materials:c})}}}class _F{engine;constructor(e){this.engine=e}getModelTypes(){let e=[];return this.engine.engineStatus.models.forEach(t=>{t.info.modelMapper.forEach(i=>{e.push(i.typeName)})}),e=e.filter((t,i,n)=>n.indexOf(t)===i),e}getModelMajors(){let e=[];return this.engine.engineStatus.models.forEach(t=>{t.info.modelMapper.forEach(i=>{e.push(i.majorName)})}),e=e.filter((t,i,n)=>n.indexOf(t)===i),e}getModelLevels(){let e=[];return this.engine.engineStatus.models.forEach(t=>{t.info.modelMapper.forEach(i=>{e.push(i.levelName)})}),e=e.filter((t,i,n)=>n.indexOf(t)===i),e}getModelMappers(e){}getModelMapper(e,t){let i=this.engine.engineStatus.models.find(n=>n.url==e);return i?i.info.modelMapper.find(n=>n.id==t):null}getModelsWithLevelType(e,t,i=null){let n=[];return this.engine.engineStatus.models.forEach(r=>{let a={url:r.url,ids:[]};n.push(a),r.info.modelMapper.filter(o=>o.levelName===e&&o.typeName===t).forEach(o=>{a.ids.push(Number(o.id))})}),i&&i(n),n}getModelsWithType(e,t=null){let i=[];return this.engine.engineStatus.models.forEach(n=>{let r={url:n.url,ids:[]};i.push(r),n.info.modelMapper.filter(a=>a.typeName===e).forEach(a=>{r.ids.push(Number(a.id))})}),t&&t(i),i}getModelsWithLevel(e,t){let i=[];return this.engine.engineStatus.models.forEach(n=>{let r={url:n.url,ids:[]};i.push(r),n.info.modelMapper.filter(a=>a.levelName===e).forEach(a=>{r.ids.push(Number(a.id))})}),t&&t(i),i}getModelsWithMajor(e,t){let i=[];return this.engine.engineStatus.models.forEach(n=>{let r={url:n.url,ids:[]};i.push(r),n.info.modelMapper.filter(a=>a.majorName===e).forEach(a=>{r.ids.push(Number(a.id))})}),t&&t(i),i}}class bF{engine;isActive=!1;groupEdge;material;modelEdgeLoaded=!1;modelEdgeLoadingPromise=null;indexes=new Map;constructor(e){this.engine=e,this.groupEdge=this.engine.scene.getObjectByName("groupEdge"),this.material=new si({color:"#000000",depthTest:!0,transparent:!0,opacity:.3}),this.material.clippingPlanes=this.engine.sectionPlane}active(){this.isActive=!0,this.groupEdge.visible=!0,this.engine.scene.traverse(e=>{e.isMesh&&e.material&&(Array.isArray(e.material)?e.material:[e.material]).forEach(t=>{t.polygonOffset=!0,t.polygonOffsetFactor=1,t.polygonOffsetUnits=4})}),this.show()}disActive(){this.isActive=!1,this.groupEdge.visible=!1,this.engine.scene.traverse(e=>{e.isMesh&&e.material&&(Array.isArray(e.material)?e.material:[e.material]).forEach(t=>{t.polygonOffset=!1})})}hasPendingModelEdges(){return(this.engine?.engineStatus?.models??[]).some(e=>!this.indexes.has(e.url))}loadZipJsonAsync(e){return new Promise((t,i)=>{Uh(e,n=>{if(n==null){i(new Error(`[ModelEdge] empty edge zip: ${e}`));return}t(n)},()=>{i(new Error(`[ModelEdge] failed to load edge zip: ${e}`))})})}async ensureModelEdgeData(e){const t=e?.info??{};if(Array.isArray(t.modelEdge))return t.modelEdge;try{const i=await this.loadZipJsonAsync(e.url+"/edge"),n=JSON.parse(i);t.modelEdge=Array.isArray(n)?n:[]}catch(i){console.error("[ModelEdge] failed to load model edge",{url:e?.url,error:i}),t.modelEdge=[]}return t.modelEdge}async loadModelEdge(){if(!(this.modelEdgeLoaded&&!this.hasPendingModelEdges())){if(this.modelEdgeLoadingPromise!=null){await this.modelEdgeLoadingPromise;return}this.modelEdgeLoadingPromise=(async()=>{const e=this.engine?.engineStatus?.models??[];for(const t of e){if(this.indexes.has(t.url))continue;const i=await this.ensureModelEdgeData(t),n=[],r=new Map;i.forEach(a=>{if(!Array.isArray(a?.points))return;const o=n.length;for(let l=0;l{this.modelEdgeLoadingPromise=null}),await this.modelEdgeLoadingPromise}}async show(){await this.loadModelEdge(),this.isActive&&this.indexes.forEach((e,t)=>{const i=this.groupEdge.children.find(o=>o.url==t);if(i){i.visible=!0;return}const n=[];if(e.forEach(o=>{o[2].forEach(l=>{l?.length===2&&(n.push(l[0].X),n.push(l[0].Z),n.push(-l[0].Y),n.push(l[1].X),n.push(l[1].Z),n.push(-l[1].Y))})}),n.length===0)return;const r=new at;r.setAttribute("position",new et(n,3));const a=new fi(r,this.material);a.url=t,this.groupEdge.add(a)})}getModelEdge(e,t){const i=this.indexes.get(e);if(i){const n=i.get(Number(t));if(n)return n.slice()}return this.loadModelEdge(),null}hideModelEdge(e,t){const i=this.indexes.get(e);if(!i){this.loadModelEdge();return}const n=i.get(Number(t));if(n){const[r,a]=n,o=this.groupEdge.children.find(l=>l.url==e);if(o){const l=o.geometry.attributes.position.array;for(let c=r;cc.url==e);if(l){const c=l.geometry.attributes.position.array;let h=0;for(let d=r;d=3;if(o[p]&&o[p].length===2){const v=u?o[p][1]:o[p][0];c[d]=v.X,c[d+1]=v.Z,c[d+2]=-v.Y}h+=3}l.geometry.attributes.position.needsUpdate=!0}}}}class MF{config;constructor(e){this.config={temperature:.7,maxTokens:2e4,timeout:3e5,...e}}async chat(e){const t=new AbortController,i=setTimeout(()=>t.abort(),this.config.timeout);try{const n=await fetch(`${this.config.baseURL}/chat/completions`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`},body:JSON.stringify({model:this.config.model,messages:e,temperature:this.config.temperature,max_tokens:this.config.maxTokens,stream:!1}),signal:t.signal});if(clearTimeout(i),!n.ok){const r=await n.json().catch(()=>({}));throw new Error(`API请求失败 (${n.status}): ${r.error?.message||r.message||n.statusText}`)}return(await n.json()).choices?.[0]?.message?.content||""}catch(n){throw clearTimeout(i),n.name==="AbortError"?new Error("请求超时,请重试"):n.message.includes("Failed to fetch")?new Error(`网络请求失败,请检查: 1. 网络连接 2. API地址是否正确 3. 是否有CORS限制`):n}}async chatStream(e,t){const i=new AbortController,n=setTimeout(()=>i.abort(),this.config.timeout);try{const r=await fetch(`${this.config.baseURL}/chat/completions`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`},body:JSON.stringify({model:this.config.model,messages:e,temperature:this.config.temperature,max_tokens:this.config.maxTokens,stream:!0}),signal:i.signal});if(clearTimeout(n),!r.ok){const c=await r.json().catch(()=>({}));throw new Error(`API请求失败 (${r.status}): ${c.error?.message||c.message||r.statusText}`)}const a=r.body?.getReader();if(!a)throw new Error("无法读取响应流");const o=new TextDecoder;let l="";for(;;){const{done:c,value:h}=await a.read();if(c){t("",!0);break}l+=o.decode(h,{stream:!0});const d=l.split(` `);l=d.pop()||"";for(const p of d){const u=p.trim();if(!u||!u.startsWith("data: "))continue;const v=u.slice(6);if(v!=="[DONE]")try{const g=JSON.parse(v).choices?.[0]?.delta?.content;g&&t(g,!1)}catch(g){console.warn("解析流式数据失败:",g)}}}}catch(r){throw clearTimeout(n),r.name==="AbortError"?new Error("请求超时,请重试"):r.message.includes("Failed to fetch")?new Error("网络请求失败,请检查网络连接"):r}}updateConfig(e){this.config={...this.config,...e}}getConfig(){return{...this.config}}}class SF{engine;steps=[];stepResults=new Map;conversationHistory=[];state="idle";llmApi=null;config=null;_callback_message;_callback_question;_callback_content;prompts={};constructor(e){this.engine=e}async init(e,t,i){this._callback_message=e,this._callback_question=t,this._callback_content=i,this.conversationHistory=[];let n={llmConfig:{baseURL:"https://open.bigmodel.cn/api/coding/paas/v4",apiKey:"4041336a72f14d8fa3800bd651a80fec.vZWUxssXOXB37vlV",model:"GLM-4.5-Air",temperature:.7,maxTokens:2e3},debug:!0,stepExecution:{maxRetries:5},prompts:{main:"",step:"",apiDoc:""}};try{this.config=n,this.llmApi=new MF(n.llmConfig);try{const r=await Promise.resolve().then(()=>z9);this.prompts.main=r.default;const a=await Promise.resolve().then(()=>H9);this.prompts.step=a.default;const o=await Promise.resolve().then(()=>V9);this.prompts.apiDoc=o.default}catch(r){throw console.error("[AI Manager] 提示词文件加载失败:",r),new Error(`提示词文件加载失败: ${r.message||"未知错误"}`)}}catch(r){throw console.error("[AI Manager] 初始化失败:",r),r}}async conversationV2(e){if(this.conversationHistory.length===0){const n={role:"system",content:`${this.prompts.main}`},r={role:"system",content:`## BIM引擎API文档 ${this.prompts.apiDoc}`};this.conversationHistory.push(n),this.conversationHistory.push(r)}this.conversationHistory.push({role:"user",content:e});const t=await this.llmApi.chat(this.conversationHistory);this.conversationHistory.push({role:"assistant",content:t}),this.config?.debug&&console.log("[AI Manager] 大模型响应:",t);let i=await this.parseAnalysisResponse(t);i&&i.questions&&i.questions.length>0&&this._callback_question(i.questions)}async parseAnalysisResponse(e){try{if(e.includes("##question##")){const t=e.match(/##question##\s*([\s\S]*?)(?=##|$)/);if(t){let i=t[1].trim();i=i.replace(/^```json\n?/,"").replace(/^```\n?/,"").replace(/\n?```$/,"");const n=i.match(/(\[[\s\S]*\])/);n&&(i=n[1]);const r=JSON.parse(i);return this.state="waiting_answer",{state:"waiting_answer",questions:r}}}if(e.includes("##steps##")){const t=e.match(/##steps##\s*([\s\S]*?)(?=##|$)/);if(t){let i=t[1].trim();i=i.replace(/^```json\n?/,"").replace(/^```\n?/,"").replace(/\n?```$/,"");const n=i.match(/(\[[\s\S]*\])/);return n&&(i=n[1]),this.steps=JSON.parse(i),this.config?.debug&&console.log("[AI Manager] 步骤规划完成,共",this.steps.length,"个步骤"),this._callback_message(this.steps),await this.executeSteps()}}return{state:"completed",data:e}}catch(t){return console.error("[AI Manager] 解析响应失败:",t),{state:"error",error:"解析大模型响应失败: "+t.message}}}async executeSteps(){try{this.state="executing",this.stepResults.clear();for(const e of this.steps){this._callback_message(e),this.config?.debug&&console.log(`[AI Manager] 执行步骤 ${e.id}: ${e.content}`);const t=await this.getDependenciesOutput(e.dependencies),i=await this.executeStep(e,t);this.stepResults.set(e.id,i),this.config?.debug&&console.log(`[AI Manager] 步骤 ${e.id} 执行完成:`,i)}return this.state="completed",{state:"completed",steps:this.steps,result:Array.from(this.stepResults.values())}}catch(e){return console.error("[AI Manager] 步骤执行失败:",e),{state:"error",error:"步骤执行失败: "+e.message}}}async getDependenciesOutput(e){return e.length===0?null:e.length===1?this.stepResults.get(e[0]):e.map(t=>this.stepResults.get(t))}async executeStep(e,t){const i=this.config?.stepExecution?.maxRetries??1,n=[];let r=null,a=!1;for(let o=0;o<=i;o++)try{const l=n.length>0?n[n.length-1]:"",c=await(o===0?this.generateCode(e,t):a?this.regenerateCodeAfterFailure(e,t,l,r,o):this.generateCode(e,t));n.push(c),this.config?.debug&&console.log(`[AI Manager] 步骤 ${e.id} 第 ${o+1} 次生成的代码: ${c}`);try{const h=await this.executeCode(c,t);if(h instanceof Object&&h.success==!1||h instanceof String&&(h.includes("undefined")||h.includes("not"))){r=h,a=!0;debugger;throw h}debugger;return h}catch(h){debugger;throw r=h,a=!0,h}}catch(l){if(a||(r=l),o>=i)throw console.error(`[AI Manager] 执行步骤 ${e.id} 失败(已达重试上限):`,l),new Error(`步骤 ${e.id} (${e.content}) 执行失败: ${l.message}`);console.warn(`[AI Manager] 步骤 ${e.id} 第 ${o+1} 次执行失败,将尝试让AI修复后重试(剩余重试次数:${i-o}):`,l)}throw new Error(`步骤 ${e.id} (${e.content}) 执行失败: 未知错误`)}extractCodeFromResponse(e){const t=e.match(/##code##\s*([\s\S]*?)(?=##|$)/);if(t){let a=t[1].trim();if(a=a.replace(/^```javascript\n?/,"").replace(/^```js\n?/,"").replace(/^```\n?/,"").replace(/\n?```$/,""),a.length>0)return a}const i=[/```javascript\s*([\s\S]*?)```/i,/```js\s*([\s\S]*?)```/i,/```\s*([\s\S]*?)```/];for(const a of i){const o=e.match(a);if(o&&o[1]){const l=o[1].trim();if(l.length>0)return this.config?.debug&&console.warn("[AI Manager] 未找到 ##code## 标记,从 markdown 代码块中提取代码"),l}}const n=/[请|说明|注意|需要|应该|可以|如果|但是|因为|所以|例如|比如]/i.test(e),r=/(function|const|let|var|return|async|await|=>|engine\.|previousStepOutput)/.test(e);if(!n&&r){const a=e.trim().replace(/^[,。:;!?\s]+/,"").replace(/[,。:;!?\s]+$/,"");if(a.length>10)return this.config?.debug&&console.warn("[AI Manager] 未找到 ##code## 标记和代码块,尝试使用整个响应作为代码"),a}throw new Error(`无法从大模型响应中提取代码。响应内容:${e.substring(0,200)}...`)}async generateCode(e,t){try{const i={role:"system",content:`${this.prompts.step}`},n={role:"system",content:` ## BIM引擎API文档 ${this.prompts.apiDoc}`},r={role:"user",content:`请根据以下步骤描述生成可执行的JavaScript代码: 步骤信息: ${JSON.stringify(e,null,2)} 前序步骤输出数据: ${t?JSON.stringify(t,null,2):"null"} 请严格按照##code##格式输出代码。`},a=[i,n,r],o=await this.llmApi.chat(a);return this.extractCodeFromResponse(o)}catch(i){throw console.error("[AI Manager] 代码生成失败:",i),i}}async regenerateCodeAfterFailure(e,t,i,n,r){try{const a={role:"system",content:`${this.prompts.step}`},o={role:"system",content:` ## BIM引擎API文档 ${this.prompts.apiDoc}`},l={message:n?.message||(n instanceof Object?JSON.stringify(n):String(n)),name:n?.name,stack:n?.stack},c={role:"user",content:`上一次生成的代码在执行时失败了,请你修复后重新输出完整可执行的 JavaScript 代码(仍然要严格按 ##code## 格式输出)。 当前步骤信息: ${JSON.stringify(e,null,2)} 前序步骤输出数据: ${t?JSON.stringify(t,null,2):"null"} 上一次生成的代码: ${i?` \`\`\`javascript ${i} \`\`\` `:` (无) `} 执行错误信息(第 ${r} 次重试前): ${JSON.stringify(l,null,2)} 修复要求(请务必遵守): 1) 不要输出解释文字,只输出 ##code## 段落里的代码 2) 如果是语法错误/引用未定义/缺少 await/返回值不一致,请直接修复 3) 尽量保持与步骤目标一致,避免引入与步骤无关的副作用 4) 代码需要能在浏览器环境运行(不要使用 Node 专属 API)`},h=await this.llmApi.chat([a,o,c]);try{return this.extractCodeFromResponse(h)}catch(d){throw new Error(`无法从大模型响应中提取代码(修复重试阶段):${d.message}`)}}catch(a){throw console.error("[AI Manager] 修复后代码生成失败:",a),a}}async executeCode(e,t){try{const i=this.engine;let n=e;n=n.replace(/\b(const|let|var)\s+previousStepOutput\s*=\s*[^;]*;/g,""),n=n.replace(/\b(const|let|var)\s+previousStepOutput\s*;/g,"");const r=new Function("engine","previousStepOutput",` 'use strict'; ${n} `)(i,t);return r&&typeof r.then=="function"?await r:r}catch(i){return console.error("[AI Manager] 代码执行失败:",i),"error"+i.message}}reset(){this.conversationHistory=[],this.steps=[],this.stepResults.clear(),this.state="idle",this.config?.debug&&console.log("[AI Manager] 对话已重置")}getState(){return this.state}getHistory(){return[...this.conversationHistory]}getSteps(){return[...this.steps]}getStepResults(){return new Map(this.stepResults)}}class wF{engine;points=[];isPlaying=!1;animationFrameId=null;playStartTime=0;playFromIndex=0;playToIndex=0;playOptions={};stayTimerId=null;playRangeToIndex=0;constructor(e){this.engine=e}init(){this.points=[],this.stop()}getCurrentPoint(){return{...this.engine.cameraModule.getCameraPose(),stayTime:0}}addPoint(e=0){const t=this.getCurrentPoint();return t.stayTime=e,this.points.push(t),this.points.length}addPoints(e){for(const t of e)this.points.push({...t});return this.points.length}savePoints(e){return this.addPoints(e)}removePoint(e){return e>=0&&e=0&&e=0&&e=this.points.length||e>=t?(console.warn("PathRoaming: 无效的索引范围"),!1):this.points.length<2?(console.warn("PathRoaming: 至少需要2个点位才能播放"),!1):(this.isPlaying&&this.stop(),this.isPlaying=!0,this.playOptions={duration:3e3,loop:!1,...i},this.engine.controlModule.disActive(),this.playFromIndex=e,this.playToIndex=e+1,this.playStartTime=performance.now(),this.playRangeToIndex=t,this.animate(),!0)}stop(){this.isPlaying=!1,this.animationFrameId!==null&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=null),this.stayTimerId!==null&&(clearTimeout(this.stayTimerId),this.stayTimerId=null),this.engine.controlModule.active()}pause(){this.isPlaying&&(this.isPlaying=!1,this.animationFrameId!==null&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=null),this.stayTimerId!==null&&(clearTimeout(this.stayTimerId),this.stayTimerId=null))}getIsPlaying(){return this.isPlaying}animate=()=>{if(!this.isPlaying)return;const e=performance.now()-this.playStartTime,t=this.playOptions.duration||3e3,i=Math.min(e/t,1),n=this.points[this.playFromIndex],r=this.points[this.playToIndex],a=this.interpolatePose(n,r,i);this.engine.cameraModule.restoreCameraPose(a),i>=1?this.onSegmentComplete():this.animationFrameId=requestAnimationFrame(this.animate)};onSegmentComplete(){const e=this.playToIndex;this.playOptions.onPointComplete&&this.playOptions.onPointComplete(e);const t=this.points[e];t.stayTime&&t.stayTime>0?this.stayTimerId=globalThis.setTimeout(()=>{this.stayTimerId=null,this.moveToNextSegment()},t.stayTime):this.moveToNextSegment()}moveToNextSegment(){const e=this.playToIndex>=this.playRangeToIndex,t=this.playToIndex>=this.points.length-1;e||t?this.playOptions.loop&&this.points.length>=2?(this.playFromIndex=0,this.playToIndex=1,this.playRangeToIndex=this.points.length-1,this.playStartTime=performance.now(),this.animate()):this.onPlayComplete():(this.playFromIndex=this.playToIndex,this.playToIndex=this.playToIndex+1,this.playStartTime=performance.now(),this.animate())}onPlayComplete(){this.stop(),this.playOptions.onComplete&&this.playOptions.onComplete()}interpolatePose(e,t,i){const n=this.easeInOutCubic(i),r={type:t.type,position:{x:Lt.lerp(e.position.x,t.position.x,n),y:Lt.lerp(e.position.y,t.position.y,n),z:Lt.lerp(e.position.z,t.position.z,n)},rotation:{x:Lt.lerp(e.rotation.x,t.rotation.x,n),y:Lt.lerp(e.rotation.y,t.rotation.y,n),z:Lt.lerp(e.rotation.z,t.rotation.z,n)},quaternion:{x:Lt.lerp(e.quaternion.x,t.quaternion.x,n),y:Lt.lerp(e.quaternion.y,t.quaternion.y,n),z:Lt.lerp(e.quaternion.z,t.quaternion.z,n),w:Lt.lerp(e.quaternion.w,t.quaternion.w,n)}};return e.target&&t.target?r.target={x:Lt.lerp(e.target.x,t.target.x,n),y:Lt.lerp(e.target.y,t.target.y,n),z:Lt.lerp(e.target.z,t.target.z,n)}:t.target&&(r.target={...t.target}),e.zoom!==void 0&&t.zoom!==void 0&&(r.zoom=Lt.lerp(e.zoom,t.zoom,n)),e.orthographicHeight!==void 0&&t.orthographicHeight!==void 0?r.orthographicHeight=Lt.lerp(e.orthographicHeight,t.orthographicHeight,n):t.orthographicHeight!==void 0&&(r.orthographicHeight=t.orthographicHeight),r}easeInOutCubic(e){return e<.5?4*e*e*e:1-Math.pow(-2*e+2,3)/2}dispose(){this.stop(),this.points=[],this.playOptions={}}}class EF{engine;miniMapCamera=null;miniMapRenderer=null;miniMapContainer=null;overlayCanvas=null;overlayCtx=null;isVisible=!1;mapSize=200;currentHalfSize=100;minHalfSize=5;maxHalfSize=1e4;halfSizeInitialized=!1;camY=1e3;centerX=0;centerZ=0;dragMode=null;lastMouseX=0;lastMouseY=0;constructor(e){this.engine=e,this.init()}getstate(){return this.isVisible}init(){this.miniMapContainer=document.createElement("div"),this.miniMapContainer.style.position="absolute",this.miniMapContainer.style.bottom="20px",this.miniMapContainer.style.left="20px",this.miniMapContainer.style.width=`${this.mapSize}px`,this.miniMapContainer.style.height=`${this.mapSize}px`,this.miniMapContainer.style.border="2px solid rgba(255, 255, 255, 0.4)",this.miniMapContainer.style.borderRadius="4px",this.miniMapContainer.style.overflow="hidden",this.miniMapContainer.style.display="none",this.miniMapContainer.style.zIndex="200",this.miniMapContainer.style.pointerEvents="auto",this.miniMapContainer.style.cursor="crosshair",this.engine.container.appendChild(this.miniMapContainer),this.miniMapRenderer=new mh({alpha:!0,antialias:!1}),this.miniMapRenderer.setSize(this.mapSize,this.mapSize),this.miniMapRenderer.setPixelRatio(window.devicePixelRatio),this.miniMapRenderer.setClearColor(1710638,.85),this.miniMapContainer.appendChild(this.miniMapRenderer.domElement);const e=window.devicePixelRatio||1;this.overlayCanvas=document.createElement("canvas"),this.overlayCanvas.width=this.mapSize*e,this.overlayCanvas.height=this.mapSize*e,this.overlayCanvas.style.position="absolute",this.overlayCanvas.style.top="0",this.overlayCanvas.style.left="0",this.overlayCanvas.style.width=`${this.mapSize}px`,this.overlayCanvas.style.height=`${this.mapSize}px`,this.overlayCanvas.style.pointerEvents="none",this.miniMapContainer.appendChild(this.overlayCanvas),this.overlayCtx=this.overlayCanvas.getContext("2d"),this.overlayCtx&&this.overlayCtx.scale(e,e),this.miniMapCamera=new rn(-this.currentHalfSize,this.currentHalfSize,this.currentHalfSize,-this.currentHalfSize,.1,1e3),this.miniMapCamera.up.set(0,0,-1),this.setupEvents()}worldToPixel(e,t){const i=this.currentHalfSize;return{x:((e-this.centerX)/i*.5+.5)*this.mapSize,y:((t-this.centerZ)/i*.5+.5)*this.mapSize}}pixelToWorld(e,t){const i=this.currentHalfSize;return{x:(e/this.mapSize-.5)*2*i+this.centerX,z:(t/this.mapSize-.5)*2*i+this.centerZ}}setupEvents(){const e=this.miniMapContainer;e.addEventListener("wheel",this.onWheel,{passive:!1}),e.addEventListener("mousedown",this.onMouseDown),e.addEventListener("mousemove",this.onMouseMove),e.addEventListener("mouseup",this.onMouseUp),e.addEventListener("mouseleave",this.onMouseUp),e.addEventListener("contextmenu",t=>t.preventDefault()),["pointerdown","pointermove","pointerup","click","dblclick"].forEach(t=>e.addEventListener(t,i=>i.stopPropagation()))}onWheel=e=>{e.preventDefault(),e.stopPropagation();const t=e.deltaY>0?1.25:.8;this.currentHalfSize=Math.max(this.minHalfSize,Math.min(this.maxHalfSize,this.currentHalfSize*t))};onMouseDown=e=>{e.stopPropagation();const t=this.miniMapContainer.getBoundingClientRect(),i=e.clientX-t.left,n=e.clientY-t.top,r=this.engine.camera;if(!r)return;const{x:a,y:o}=this.worldToPixel(r.position.x,r.position.z);Math.hypot(i-a,n-o)<25?(this.dragMode="rotate",this.miniMapContainer.style.cursor="alias"):(this.dragMode=null,this.handleTeleport(i,n)),this.lastMouseX=i,this.lastMouseY=n};onMouseMove=e=>{if(e.stopPropagation(),this.dragMode!=="rotate")return;const t=this.miniMapContainer.getBoundingClientRect(),i=e.clientX-t.left,n=e.clientY-t.top;this.handleRotate(i,n),this.lastMouseX=i,this.lastMouseY=n};onMouseUp=e=>{e.stopPropagation(),this.dragMode=null,this.miniMapContainer&&(this.miniMapContainer.style.cursor="crosshair")};handleTeleport(e,t){const i=this.engine.camera,n=this.engine.controls;if(!i||!n)return;const{x:r,z:a}=this.pixelToWorld(e,t),o=r-i.position.x,l=a-i.position.z;i.position.x+=o,i.position.z+=l,n.target.x+=o,n.target.z+=l,n.update()}handleRotate(e,t){const i=this.engine.camera,n=this.engine.controls;if(!i||!n)return;const r=this.mapSize/2,a=this.mapSize/2,o=Math.atan2(this.lastMouseY-a,this.lastMouseX-r);let l=Math.atan2(t-a,e-r)-o;l>Math.PI&&(l-=2*Math.PI),l<-Math.PI&&(l+=2*Math.PI);const c=new R().copy(n.target).sub(i.position),h=new Ml().setFromVector3(c);h.theta-=l,c.setFromSpherical(h),n.target.copy(i.position).add(c),n.update()}drawOverlay(){const e=this.overlayCtx,t=this.engine.camera;if(!e||!t)return;e.clearRect(0,0,this.mapSize,this.mapSize);const i=this.mapSize/2,n=this.mapSize/2,r=new R;t.getWorldDirection(r);const a=Math.atan2(r.x,-r.z),o=36,l=Math.PI/10;e.save(),e.translate(i,n),e.rotate(a);const c=e.createRadialGradient(0,0,2,0,0,o);c.addColorStop(0,"rgba(0, 230, 130, 0.9)"),c.addColorStop(1,"rgba(0, 230, 130, 0)");const h=-Math.sin(l)*o,d=-Math.cos(l)*o,p=Math.sin(l)*o,u=-Math.cos(l)*o;e.beginPath(),e.moveTo(0,0),e.lineTo(h,d),e.lineTo(p,u),e.closePath(),e.fillStyle=c,e.fill(),e.fillStyle="rgba(255, 255, 255, 0.95)",e.strokeStyle="rgba(0, 200, 110, 0.9)",e.lineWidth=1.5,e.beginPath(),e.arc(0,0,4,0,Math.PI*2),e.fill(),e.stroke(),e.restore()}show(){this.isVisible=!0,this.miniMapContainer&&(this.miniMapContainer.style.display="block")}hide(){this.isVisible=!1,this.miniMapContainer&&(this.miniMapContainer.style.display="none")}toggle(){this.isVisible?this.hide():this.show()}update(){if(!this.isVisible||!this.miniMapCamera||!this.miniMapRenderer)return;const e=this.engine.camera;if(!(!e||!this.engine.scene)){if(this.engine.octreeBox){const t=this.engine.octreeBox.getBoundingBox();if(t?.min&&t?.max){const i=t.max.x-t.min.x,n=t.max.z-t.min.z,r=t.max.y-t.min.y;this.camY=t.max.y+Math.max(i,n,r),!this.halfSizeInitialized&&i+n>0&&(this.currentHalfSize=Math.max(i,n)*2,this.halfSizeInitialized=!0)}}this.centerX=e.position.x,this.centerZ=e.position.z,this.miniMapCamera.left=-this.currentHalfSize,this.miniMapCamera.right=this.currentHalfSize,this.miniMapCamera.top=this.currentHalfSize,this.miniMapCamera.bottom=-this.currentHalfSize,this.miniMapCamera.updateProjectionMatrix(),this.miniMapCamera.position.set(this.centerX,this.camY,this.centerZ),this.miniMapCamera.lookAt(this.centerX,this.camY-1,this.centerZ),this.miniMapRenderer.render(this.engine.scene,this.miniMapCamera),this.drawOverlay()}}dispose(){this.miniMapContainer&&(this.miniMapContainer.removeEventListener("wheel",this.onWheel),this.miniMapContainer.removeEventListener("mousedown",this.onMouseDown),this.miniMapContainer.removeEventListener("mousemove",this.onMouseMove),this.miniMapContainer.removeEventListener("mouseup",this.onMouseUp),this.miniMapContainer.removeEventListener("mouseleave",this.onMouseUp)),this.miniMapRenderer&&(this.miniMapRenderer.dispose(),this.miniMapRenderer=null),this.miniMapContainer&&(this.miniMapContainer.remove(),this.miniMapContainer=null),this.miniMapCamera=null,this.overlayCtx=null,this.overlayCanvas=null}}const TF=Lt.degToRad(10),v2=.001,CF=[];class AF{engine;rootGroup=null;isVisible=!1;axes=[];coordinateMapper=e=>new R(e.X,e.Z,-e.Y);constructor(e){this.engine=e,this._initRoot()}setData(e=[]){this._clearAxes(),this.axes=e.map(t=>({data:t,group:null})),this.axes.forEach(t=>this._buildAxis(t))}setMockData(){const e=this.engine.models?.[0]?.grids;this.setData(Array.isArray(e)&&e.length>0?e:CF)}show(){this.isVisible=!0,this.rootGroup&&(this.rootGroup.visible=!0)}hide(){this.isVisible=!1,this.rootGroup&&(this.rootGroup.visible=!1)}toggle(){if(this.isVisible){this.hide();return}this.show()}update(){if(!this.isVisible||!this.rootGroup)return;const e=this.engine.camera,t=this.engine.renderer;if(!e||!t)return;let i=.5;if(e instanceof rn){const n=(e.top-e.bottom)/e.zoom,r=t.domElement.clientHeight||1;i=30*n/r}this.rootGroup.traverse(n=>{n instanceof Xc&&n.scale.set(i,i,1)})}getLocationByPoint(e,t){const{url:i,targetPoint:n}=this.resolvePointLookupArgs(e,t),r=this.getGridData(i);debugger;if(r.length===0)return null;const a=this.toVector3(n),o=new me(a.x,a.z),l=this.buildAxisFamilies(r).sort((p,u)=>u.axes.length-p.axes.length).slice(0,2).map((p,u)=>({...p,familyIndex:u}));if(l.length===0)return null;const c=l.map(p=>this.resolveFamilyLocation(p,o)),h=this.sortFamiliesForDisplay(c),d=h.length===2&&h.every(p=>p.isInside);return{point:{x:a.x,y:a.y,z:a.z},description:this.formatGridDescription(h),families:h,isInside:d}}dispose(){this._clearAxes(),this.rootGroup&&(this.engine.scene&&this.engine.scene.remove(this.rootGroup),this.rootGroup=null)}_initRoot(){this.rootGroup=new pi,this.rootGroup.name="GridRoot",this.rootGroup.visible=!1,this.engine.scene&&this.engine.scene.add(this.rootGroup)}_clearAxes(){this.axes.forEach(e=>{e.group&&(this.rootGroup?.remove(e.group),e.group.traverse(t=>{const i=t;if("geometry"in i&&i.geometry&&i.geometry.dispose(),"material"in i&&i.material){const n=i.material;"map"in n&&n.map&&n.map.dispose(),n.dispose()}}),e.group=null)}),this.axes=[]}_buildAxis(e){if(!this.rootGroup)return;const t=this.coordinateMapper(e.data.Points[0]),i=this.coordinateMapper(e.data.Points[1]),n=new pi;n.name=`GridAxis_${e.data.Id}`;const r=new at().setFromPoints([t,i]),a=new si({color:1609983,depthTest:!1}),o=new pn(r,a);o.renderOrder=998,n.add(o),n.add(this._makeCircleSprite(e.data.Name,t)),n.add(this._makeCircleSprite(e.data.Name,i)),this.rootGroup.add(n),e.group=n}_makeCircleSprite(e,t){const i=document.createElement("canvas");i.width=128,i.height=128;const n=i.getContext("2d");if(!n)throw new Error("Grid sprite canvas context is not available");const r=128/2,a=128/2,o=128/2-4;n.beginPath(),n.arc(r,a,o,0,Math.PI*2),n.fillStyle="white",n.fill(),n.strokeStyle="#1890ff",n.lineWidth=6,n.stroke(),n.fillStyle="#1890ff",n.font=`bold ${Math.round(128*.38)}px Arial`,n.textAlign="center",n.textBaseline="middle",n.fillText(e,r,a);const l=new zx(i),c=new Cu({map:l,depthTest:!1,transparent:!0}),h=new Xc(c);return h.position.copy(t),h.scale.set(.5,.5,1),h.renderOrder=999,h}getGridData(e){if(e){const i=this.findModelByUrl(e);return Array.isArray(i?.grids)?i.grids:[]}if(this.axes.length>0)return this.axes.map(i=>i.data);if(!Array.isArray(this.engine.models))return[];const t=[];return this.engine.models.forEach(i=>{Array.isArray(i.grids)&&t.push(...i.grids)}),t}resolvePointLookupArgs(e,t){if(typeof e=="string"){if(!t)throw new Error("Grid.getLocationByPoint(url, point) requires a point argument.");return{url:e,targetPoint:t}}return{targetPoint:e}}findModelByUrl(e){return this.engine.models?.find(t=>t.url===e)}buildAxisFamilies(e){const t=[];return e.forEach(i=>{const n=this.createProjection(i);if(!n)return;const r=t.find(a=>a.direction.angleTo(n.direction)<=TF);if(r){r.axes.push(n);return}t.push({familyIndex:t.length,direction:n.direction.clone(),normal:new me(-n.direction.y,n.direction.x),axes:[n]})}),t.forEach(i=>{i.axes.sort((n,r)=>n.offset-r.offset)}),t}createProjection(e){const t=this.coordinateMapper(e.Points[0]),i=this.coordinateMapper(e.Points[1]),n=new me(t.x,t.z),r=new me(i.x,i.z),a=r.clone().sub(n);if(a.lengthSq()<=Number.EPSILON)return null;const o=this.normalizeDirection(a),l=new me(-o.y,o.x);return{data:e,start:n,end:r,direction:o,offset:n.dot(l)}}normalizeDirection(e){const t=e.clone().normalize();return(t.x<0||Math.abs(t.x)<=v2&&t.y<0)&&t.multiplyScalar(-1),t}resolveFamilyLocation(e,t){const i=t.dot(e.normal),n=e.axes.find(c=>Math.abs(c.offset-i)<=v2)??null;if(n){const c=e.axes.findIndex(d=>d.data.Id===n.data.Id),h=this.pickAxisPairAroundIndex(e.axes,c);return{familyIndex:e.familyIndex,description:h?this.formatAxisPair(h[0].data.Name,h[1].data.Name):n.data.Name,startAxisName:h?.[0].data.Name??n.data.Name,endAxisName:h?.[1].data.Name??n.data.Name,axisName:n.data.Name,pointOffset:i,isOnAxis:!0,isInside:h!==null}}let r=null,a=null;e.axes.forEach(c=>{if(c.offset0?e[t-1]:null,r=t{const n=this.getFamilySampleLabel(t),r=this.getFamilySampleLabel(i),a=this.isNumericLabel(n),o=this.isNumericLabel(r);return a!==o?a?1:-1:this.compareLabels(n,r)})}getFamilySampleLabel(e){return e.axisName??e.startAxisName??e.endAxisName??""}formatAxisPair(e,t){return this.compareLabels(e,t)<=0?`${e}-${t}`:`${t}-${e}`}formatGridDescription(e){if(e.length!==2)return"";const t=e.map(i=>i.description).filter(i=>i.length>0);return t.length!==2?"":`${t[0]}交${t[1]}`}compareLabels(e,t){return e.localeCompare(t,void 0,{numeric:!0,sensitivity:"base"})}isNumericLabel(e){return/^\d/.test(e.trim())}toVector3(e){return e instanceof R?e.clone():new R(e.x,e.y,e.z)}}const PF=.001,RF=[{Id:"339",Name:"L1",Elevation:-.32808398950131235},{Id:"2787",Name:"L2",Elevation:16.896325459317584},{Id:"236633",Name:"L3",Elevation:36.745406824146976}];class IF{engine;isVisible=!1;levels=[];svgContainer=null;svgOverlay=null;worldToScreen=null;halfSize=500;COLOR="#1890ff";PLANE_OPACITY=.08;constructor(e){this.engine=e,this._initSvg()}setData(e=[],t){this._clearAll(),this.levels=e.map(n=>({data:n,group:null,svgGroup:null}));const i=t??this.getMergedBoundingBox();this.levels.forEach(n=>this._buildThreeObject(n,i))}setMockData(){const e=this.engine.models?.[0]?.levels,t=this.engine.models?.[0]?.boundingBox;this.setData(Array.isArray(e)&&e.length>0?e:RF,t)}show(){this.isVisible=!0,this.svgContainer&&(this.svgContainer.style.display="block"),this.levels.forEach(e=>{e.group&&(e.group.visible=!0)})}hide(){this.isVisible=!1,this.svgContainer&&(this.svgContainer.style.display="none"),this.levels.forEach(e=>{e.group&&(e.group.visible=!1)})}toggle(){if(this.isVisible){this.hide();return}this.show()}update(){!this.isVisible||!this.svgOverlay||this.levels.length===0||!this.engine.camera||!this.engine.renderer||(this._initWorldToScreen(),this.levels.forEach(e=>this._updateSvgLabels(e)))}getLocationByPoint(e,t){const{url:i,targetPoint:n}=this.resolvePointLookupArgs(e,t),r=this.getLevelData(i).slice().sort((u,v)=>u.Elevation-v.Elevation);if(r.length===0)return null;const a=n.y,o=r.find(u=>Math.abs(u.Elevation-a)<=PF)??null;if(o)return{pointY:a,description:`${o.Name}`,currentLevel:o,lowerLevel:o,upperLevel:o,isOnLevel:!0,isInside:!0};let l=null,c=null;r.forEach(u=>{if(u.Elevation{e.group&&this.engine.scene&&(this.engine.scene.remove(e.group),e.group.traverse(t=>{t.geometry&&t.geometry.dispose(),t.material&&(Array.isArray(t.material)?t.material.forEach(i=>i.dispose()):t.material.dispose())}),e.group=null),e.svgGroup&&(e.svgGroup.remove(),e.svgGroup=null)}),this.levels=[]}_buildThreeObject(e,t){if(!this.engine.scene)return;const i=new R(t.min.x,t.min.y,t.min.z),n=new R(t.max.x,t.max.y,t.max.z);this.halfSize=n.distanceTo(i);const r=e.data.Elevation,a=new pi,o=new vs(this.halfSize*2,this.halfSize*2);o.rotateX(-Math.PI/2);const l=new Dt({color:this.COLOR,transparent:!0,opacity:this.PLANE_OPACITY,side:Ot,depthWrite:!1}),c=new ht(o,l);c.position.y=r,a.add(c);const h=[new R(-this.halfSize,r,-this.halfSize),new R(this.halfSize,r,-this.halfSize),new R(this.halfSize,r,this.halfSize),new R(-this.halfSize,r,this.halfSize),new R(-this.halfSize,r,-this.halfSize)],d=new at().setFromPoints(h),p=new si({color:this.COLOR,transparent:!0,opacity:.7});if(a.add(new pn(d,p)),a.visible=this.isVisible,this.engine.scene.add(a),e.group=a,this.svgOverlay){const u=document.createElementNS("http://www.w3.org/2000/svg","g");u.dataset.levelId=e.data.Id;for(let v=0;v<4;v+=1)u.appendChild(this._makeLabel(e.data.Name,e.data.Elevation));this.svgOverlay.appendChild(u),e.svgGroup=u}}_updateSvgLabels(e){if(!e.svgGroup||!this.worldToScreen)return;const t=e.data.Elevation,i=[new R(-this.halfSize,t,-this.halfSize),new R(this.halfSize,t,-this.halfSize),new R(this.halfSize,t,this.halfSize),new R(-this.halfSize,t,this.halfSize)],n=Array.from(e.svgGroup.children);i.forEach((r,a)=>{const o=this.worldToScreen?.worldToScreen(r);o&&(n[a].setAttribute("x",String(o.x)),n[a].setAttribute("y",String(o.y)))})}_makeLabel(e,t){const i=document.createElementNS("http://www.w3.org/2000/svg","text");return i.textContent=`${e} ${t.toFixed(3)}m`,i.setAttribute("text-anchor","middle"),i.setAttribute("dominant-baseline","central"),i.setAttribute("fill",this.COLOR),i.setAttribute("font-size","12"),i.setAttribute("font-family","Arial, sans-serif"),i.setAttribute("font-weight","bold"),i.setAttribute("stroke","white"),i.setAttribute("stroke-width","2"),i.setAttribute("paint-order","stroke"),i.style.pointerEvents="none",i}getLevelData(e){if(e){const i=this.findModelByUrl(e);return Array.isArray(i?.levels)?i.levels:[]}if(this.levels.length>0)return this.levels.map(i=>i.data);if(!Array.isArray(this.engine.models))return[];const t=[];return this.engine.models.forEach(i=>{Array.isArray(i.levels)&&t.push(...i.levels)}),t}resolvePointLookupArgs(e,t){if(typeof e=="string"){if(!t)throw new Error("Level.getLocationByPoint(url, point) requires a point argument.");return{url:e,targetPoint:t}}return{targetPoint:e}}findModelByUrl(e){return this.engine.models?.find(t=>t.url===e)}pickNearestLevel(e,t,i){if(t&&i){const n=Math.abs(e-t.Elevation),r=Math.abs(i.Elevation-e);return n<=r?t:i}return t??i}getMergedBoundingBox(){if(!Array.isArray(this.engine.models)||this.engine.models.length===0)return{min:{x:-this.halfSize,y:-this.halfSize,z:-this.halfSize},max:{x:this.halfSize,y:this.halfSize,z:this.halfSize}};const e=new vt;let t=!1;return this.engine.models.forEach(i=>{const n=i.boundingBox;if(!n)return;const r=new R(n.min.x,n.min.y,n.min.z),a=new R(n.max.x,n.max.y,n.max.z);if(!t){e.min.copy(r),e.max.copy(a),t=!0;return}e.expandByPoint(r),e.expandByPoint(a)}),t?e:{min:{x:-this.halfSize,y:-this.halfSize,z:-this.halfSize},max:{x:this.halfSize,y:this.halfSize,z:this.halfSize}}}}class LF{engine;constructor(e){this.engine=e}getMoldePosition(e){if(e==null||!Array.isArray(e.ids)||e.ids.length===0)return null;const t=e.url,i=e.ids[0],n=this.engine.models.find(l=>l.url===t);if(n==null)return null;const r=n.nodesMap.get(i)?.infos?.[0];if(r?.box==null)return null;const a=r.box.min.clone().add(r.box.max.clone()).multiplyScalar(.5),o=this.getPointContext(t,a);return{Floor:o.level?.description??"",Axis:o.grid?.description??"",ElementId:i,ElementName:"",modelJson:{url:t,ids:[i],point:o.point,camera:this.getCameraPose(),cameraRestorePose:this.getCameraRestorePose()}}}jumptoCamera(e){const t=this.resolveModelJson(e);if(t==null)return;this.highlightIssueModel(t);const i=this.resolveFocusPoint(t),n=this.normalizeRestorePose(t.cameraRestorePose,i);if(n){this.restoreCameraPose(n),this.syncOrbitOrigin(n.target??i);return}if(t.camera){this.restoreIssueCameraPose(t.camera,i);return}this.zoomToIssueModel(t,i)}getPoint(e){const t=e instanceof R?e.clone():new R(e.x,e.y,e.z);return{x:t.x,y:t.y,z:t.z}}getModelPosition(e){return this.getPoint(e)}getPointContext(e,t){const{url:i,targetPoint:n}=this.resolvePointLookupArgs(e,t),r=this.getPoint(n);return{url:i,point:r,grid:this.engine.grid?.getLocationByPoint(i??r,i?r:void 0)??null,level:this.engine.level?.getLocationByPoint(i??r,i?r:void 0)??null}}getCameraPose(){const e=this.engine.camera;if(!e)return{position:{x:0,y:0,z:0},forwardDirection:{x:0,y:0,z:-1},upDirection:{x:0,y:1,z:0}};const t=new R;e.getWorldDirection(t);const i=e.up.clone().normalize().applyQuaternion(e.quaternion).normalize();return{position:{x:e.position.x,y:e.position.y,z:e.position.z},forwardDirection:{x:t.x,y:t.y,z:t.z},upDirection:{x:i.x,y:i.y,z:i.z}}}getCameraParams(){return this.getCameraPose()}getCameraRestorePose(){return this.engine.cameraModule.getCameraPose()}restoreCameraPose(e){this.engine.cameraModule.restoreCameraPose(e)}capture(e){return{...this.getPointContext(e),cameraPose:this.getCameraPose(),cameraRestorePose:this.getCameraRestorePose()}}captureByUrlAndPoint(e,t){return{url:e,...this.captureWithUrl(e,t)}}captureWithUrl(e,t){return{...this.getPointContext(e,t),cameraPose:this.getCameraPose(),cameraRestorePose:this.getCameraRestorePose()}}restore(e){if("cameraRestorePose"in e){this.restoreCameraPose(e.cameraRestorePose);return}this.restoreCameraPose(e)}dispose(){}resolvePointLookupArgs(e,t){if(typeof e=="string"){if(!t)throw new Error("IssueReport.getPointContext(url, point) requires a point argument.");return{url:e,targetPoint:t}}return{targetPoint:e}}resolveModelJson(e){const t=e?.modelJson??e;if(t==null)return null;if(typeof t=="string")try{return JSON.parse(t)}catch(i){return console.warn("IssueReport.jumptoCamera: failed to parse modelJson.",i),null}return t}highlightIssueModel(e){if(!e.url||!Array.isArray(e.ids)||e.ids.length===0)return;const t={url:e.url,ids:[...e.ids]},i=this.engine.engineStatus?.hideModels?.find(r=>r.url===t.url)?.ids??[],n=t.ids.filter(r=>i.includes(r));n.length>0&&this.engine.modelToolModule.showModel([{url:t.url,ids:n}]),this.engine.modelToolModule.unhighlightAllModels(),this.engine.modelToolModule.highlightModel([t])}restoreIssueCameraPose(e,t){const i=this.toVector3(e.position),n=this.toVector3(e.forwardDirection).normalize(),r=this.toVector3(e.upDirection).normalize();if(n.lengthSq()===0)return;const a=this.engine.camera;if(!a)return;const o=t?this.toVector3(t):i.clone().add(n),l=this.buildSafeUpDirection(n,r,a.up);a.position.copy(i),a.up.copy(l),a.lookAt(o),a.updateMatrix(),a.updateMatrixWorld(!0);const c={type:this.engine.cameraModule?.getCameraType?.()??Bp.PERSPECTIVE,position:this.getPoint(i),rotation:{x:a.rotation.x,y:a.rotation.y,z:a.rotation.z},quaternion:{x:a.quaternion.x,y:a.quaternion.y,z:a.quaternion.z,w:a.quaternion.w},target:this.getPoint(o)};a instanceof rn&&(c.zoom=a.zoom,c.orthographicHeight=this.engine.cameraModule.getOrthographicVisibleHeight(a)),this.restoreCameraPose(c),this.syncOrbitOrigin(c.target)}zoomToIssueModel(e,t){const i=this.resolveModelBox(e);if(i){this.engine.viewCube?.zoomToModel(i);const n=i.min.clone().add(i.max.clone()).multiplyScalar(.5);this.syncOrbitOrigin(this.getPoint(n));return}t&&this.engine.controls?.target&&(this.engine.controls.target.set(t.x,t.y,t.z),this.syncOrbitOrigin(t),this.engine.controls.update?.())}syncOrbitOrigin(e){e&&this.engine.controlModule?.orbitControls?.origin?.set(e.x,e.y,e.z)}toVector3(e){return new R(e.x,e.y,e.z)}resolveFocusPoint(e){if(e.point)return e.point;const t=this.resolveModelBox(e);if(t)return this.getPoint(t.min.clone().add(t.max.clone()).multiplyScalar(.5))}resolveModelBox(e){if(!e.url||!Array.isArray(e.ids)||e.ids.length===0)return null;const t=this.engine.models.find(r=>r.url===e.url);if(!t)return null;const i=e.ids.map(r=>t.nodesMap.get(r)).flatMap(r=>r?.infos?.map(a=>a?.box).filter(Boolean)??[]);if(i.length===0)return null;const n=new vt;n.copy(i[0]);for(let r=1;r0?t.clone():i.clone().normalize();if(Math.abs(n.dot(e))<.999)return n;const r=i.clone().normalize();return Math.abs(r.dot(e))<.999?r:new R(1,0,0)}}class DF{engine;constructor(e){}update(){}}class NF{engine;currentHdrId="0";isVisible=!0;currentIntensity=.2;currentTexture=null;currentEnvironmentTexture=null;skybox=null;textureCache=new Map;previousBackground=null;previousEnvironment=null;previousBackgroundIntensity=1;previousEnvironmentIntensity=1;previousAmbientLightIntensity=1;previousToneMapping=ji;previousToneMappingExposure=1;hdrList=[{id:"0",names:["无","無","None"]},{id:"1",names:["纯净-多云","純淨-多雲","Pure - Cloudy"],url:"assets/hdr/1.hdr"},{id:"2",names:["纯净-落日","純淨-落日","Pure - Sunset"],url:"assets/hdr/2.hdr"},{id:"3",names:["纯净-少云","純淨-少雲","Pure - Few Clouds"],url:"assets/hdr/3.hdr"},{id:"4",names:["纯净-无云","純淨-無雲","Pure - Cloudless"],url:"assets/hdr/4.hdr"},{id:"5",names:["纯净-夜晚","純淨-夜晚","Pure - Night"],url:"assets/hdr/5.hdr"},{id:"6",names:["纯净-阴天","純淨-陰天","Pure - Overcast"],url:"assets/hdr/6.hdr"},{id:"7",names:["纯净-中云","純淨-中雲","Pure - Partly Cloudy"],url:"assets/hdr/7.hdr"},{id:"8",names:["废弃机场","廢棄機場","Abandoned Airport"],url:"assets/hdr/8.hdr"},{id:"9",names:["户外-无云","戶外-無雲","Outdoor - Cloudless"],url:"assets/hdr/9.hdr"},{id:"10",names:["郊区花园","郊區花園","Suburban Garden"],url:"assets/hdr/10.hdr"},{id:"11",names:["室内工作室01","室內工作室01","Indoor Studio 01"],url:"assets/hdr/11.hdr"},{id:"12",names:["室内工作室02","室內工作室02","Indoor Studio 02"],url:"assets/hdr/12.hdr"},{id:"13",names:["室内工作室03","室內工作室03","Indoor Studio 03"],url:"assets/hdr/13.hdr"},{id:"14",names:["室内工作室04","室內工作室04","Indoor Studio 04"],url:"assets/hdr/14.hdr"},{id:"15",names:["小镇教堂","小鎮教堂","Town Church"],url:"assets/hdr/15.hdr"},{id:"16",names:["小镇街道","小鎮街道","Town Street"],url:"assets/hdr/16.hdr"},{id:"17",names:["夜晚街道","夜晚街道","Night Street"],url:"assets/hdr/17.hdr"}];constructor(e){this.engine=e}getHdrList(){return this.hdrList}async setHdr(e){const t=this.hdrList.find(i=>i.id===e);if(!t){console.warn(`[Hdr] HDR id "${e}" not found`);return}if(e==="0"||!t.url){this._clearHdr(),this.currentHdrId="0";return}if(this.textureCache.has(e)){this._applyTexture(this.textureCache.get(e)),this.currentHdrId=e;return}try{const i=await this._loadHdr(t.url);this.textureCache.set(e,i),this._applyTexture(i),this.currentHdrId=e}catch(i){console.error(`[Hdr] Failed to load HDR "${t.url}":`,i)}}setVisible(e){this.isVisible=e,this.skybox&&(this.skybox.visible=e)}getCurrentHdrId(){return this.currentHdrId}getVisible(){return this.isVisible}setIntensity(e){this.currentIntensity=e,!(!this.engine.scene||this.currentHdrId==="0")&&(this.engine.scene.environmentIntensity=e,this._updateSkyboxIntensity())}getIntensity(){return this.currentIntensity}addHdrItem(e){const t=this.hdrList.find(i=>i.id===e.id);t?Object.assign(t,e):this.hdrList.push(e)}dispose(){this._clearHdr(),this.textureCache.forEach(e=>e.dispose()),this.textureCache.clear()}_loadHdr(e){return new Promise((t,i)=>{new aB().load(e,n=>{n.mapping=Vo,t(n)},void 0,n=>i(n))})}_applyTexture(e){if(this.currentTexture=e,!this.engine.scene||!this.engine.renderer)return;this._captureSceneState(),this.currentEnvironmentTexture?.dispose();const t=new uh(this.engine.renderer),i=t.fromEquirectangular(e).texture;t.dispose(),this.currentEnvironmentTexture=i,this.engine.scene.background=null,this.engine.scene.environment=i,this.engine.scene.environmentIntensity=this.currentIntensity,this.engine.renderer.toneMapping=Sa,this.engine.renderer.toneMappingExposure=1,this._removeSkybox(),this._createSkybox(e),this._setAmbientLightIntensity(0)}_captureSceneState(){this.currentHdrId!=="0"||!this.engine.scene||(this.previousBackground=this.engine.scene.background,this.previousEnvironment=this.engine.scene.environment,this.previousBackgroundIntensity=this.engine.scene.backgroundIntensity??1,this.previousEnvironmentIntensity=this.engine.scene.environmentIntensity??1,this.previousAmbientLightIntensity=this._getAmbientLightIntensity(),this.previousToneMapping=this.engine.renderer?.toneMapping??ji,this.previousToneMappingExposure=this.engine.renderer?.toneMappingExposure??1)}_createSkybox(e){if(!this.engine.scene)return;const t=new Fa(1e3,64,32),i=new Dt({map:e,side:Bi,depthWrite:!1,depthTest:!1,fog:!1,toneMapped:!0});this.skybox=new ht(t,i),this.skybox.name="hdr_skybox",this.skybox.renderOrder=-1e3,this.skybox.frustumCulled=!1,this.skybox.visible=this.isVisible,this.skybox.onBeforeRender=(n,r,a)=>{this.skybox?.position.copy(a.position)},this._updateSkyboxIntensity(),this.engine.scene.add(this.skybox)}_updateSkyboxIntensity(){this.skybox&&this.skybox.material.color.setScalar(Math.max(this.currentIntensity,1))}_removeSkybox(){!this.skybox||!this.engine.scene||(this.engine.scene.remove(this.skybox),this.skybox.geometry.dispose(),this.skybox.material.dispose(),this.skybox=null)}_clearHdr(){this.currentTexture=null,this._removeSkybox(),this.engine.scene&&(this.currentEnvironmentTexture?.dispose(),this.currentEnvironmentTexture=null,this.engine.scene.background=this.previousBackground,this.engine.scene.environment=this.previousEnvironment,this.engine.scene.backgroundIntensity=this.previousBackgroundIntensity,this.engine.scene.environmentIntensity=this.previousEnvironmentIntensity,this._setAmbientLightIntensity(this.previousAmbientLightIntensity),this.engine.renderer&&(this.engine.renderer.toneMapping=this.previousToneMapping,this.engine.renderer.toneMappingExposure=this.previousToneMappingExposure),this.previousBackground=null,this.previousEnvironment=null,this.previousBackgroundIntensity=1,this.previousEnvironmentIntensity=1,this.previousAmbientLightIntensity=1,this.previousToneMapping=ji,this.previousToneMappingExposure=1)}_getAmbientLightIntensity(){return this.engine.scene?.children.find(e=>e instanceof xl)?.intensity??1}_setAmbientLightIntensity(e){this.engine.setting.setAmbientLightIntensity(e)}}class kF extends ht{constructor(e,t={}){super(e),this.isWater=!0;const i=this,n=t.textureWidth!==void 0?t.textureWidth:512,r=t.textureHeight!==void 0?t.textureHeight:512,a=t.clipBias!==void 0?t.clipBias:0,o=t.alpha!==void 0?t.alpha:1,l=t.time!==void 0?t.time:0,c=t.waterNormals!==void 0?t.waterNormals:null,h=t.sunDirection!==void 0?t.sunDirection:new R(.70707,.70707,0),d=new We(t.sunColor!==void 0?t.sunColor:16777215),p=new We(t.waterColor!==void 0?t.waterColor:8355711),u=t.eye!==void 0?t.eye:new R(0,0,0),v=t.distortionScale!==void 0?t.distortionScale:20,g=t.side!==void 0?t.side:_n,m=t.fog!==void 0?t.fog:!1,f=new Yt,y=new R,x=new R,_=new R,S=new qe,b=new R(0,0,-1),E=new Pt,w=new R,M=new R,C=new Pt,I=new qe,P=new ai,k=new bi(n,r,{type:_i}),A={name:"MirrorShader",uniforms:nn.merge([$e.fog,$e.lights,{normalSampler:{value:null},mirrorSampler:{value:null},alpha:{value:1},time:{value:0},size:{value:1},distortionScale:{value:20},textureMatrix:{value:new qe},sunColor:{value:new We(8355711)},sunDirection:{value:new R(.70707,.70707,0)},eye:{value:new R},waterColor:{value:new We(5592405)}}]),vertexShader:` uniform mat4 textureMatrix; uniform float time; varying vec4 mirrorCoord; varying vec4 worldPosition; #include #include #include #include void main() { mirrorCoord = modelMatrix * vec4( position, 1.0 ); worldPosition = mirrorCoord.xyzw; mirrorCoord = textureMatrix * mirrorCoord; vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 ); gl_Position = projectionMatrix * mvPosition; #include #include #include #include #include }`,fragmentShader:` uniform sampler2D mirrorSampler; uniform float alpha; uniform float time; uniform float size; uniform float distortionScale; uniform sampler2D normalSampler; uniform vec3 sunColor; uniform vec3 sunDirection; uniform vec3 eye; uniform vec3 waterColor; varying vec4 mirrorCoord; varying vec4 worldPosition; vec4 getNoise( vec2 uv ) { vec2 uv0 = ( uv / 103.0 ) + vec2(time / 17.0, time / 29.0); vec2 uv1 = uv / 107.0-vec2( time / -19.0, time / 31.0 ); vec2 uv2 = uv / vec2( 8907.0, 9803.0 ) + vec2( time / 101.0, time / 97.0 ); vec2 uv3 = uv / vec2( 1091.0, 1027.0 ) - vec2( time / 109.0, time / -113.0 ); vec4 noise = texture2D( normalSampler, uv0 ) + texture2D( normalSampler, uv1 ) + texture2D( normalSampler, uv2 ) + texture2D( normalSampler, uv3 ); return noise * 0.5 - 1.0; } void sunLight( const vec3 surfaceNormal, const vec3 eyeDirection, float shiny, float spec, float diffuse, inout vec3 diffuseColor, inout vec3 specularColor ) { vec3 reflection = normalize( reflect( -sunDirection, surfaceNormal ) ); float direction = max( 0.0, dot( eyeDirection, reflection ) ); specularColor += pow( direction, shiny ) * sunColor * spec; diffuseColor += max( dot( sunDirection, surfaceNormal ), 0.0 ) * sunColor * diffuse; } #include #include #include #include #include #include #include #include void main() { #include vec4 noise = getNoise( worldPosition.xz * size ); vec3 surfaceNormal = normalize( noise.xzy * vec3( 1.5, 1.0, 1.5 ) ); vec3 diffuseLight = vec3(0.0); vec3 specularLight = vec3(0.0); vec3 worldToEye = eye-worldPosition.xyz; vec3 eyeDirection = normalize( worldToEye ); sunLight( surfaceNormal, eyeDirection, 100.0, 2.0, 0.5, diffuseLight, specularLight ); float distance = length(worldToEye); vec2 distortion = surfaceNormal.xz * ( 0.001 + 1.0 / distance ) * distortionScale; vec3 reflectionSample = vec3( texture2D( mirrorSampler, mirrorCoord.xy / mirrorCoord.w + distortion ) ); float theta = max( dot( eyeDirection, surfaceNormal ), 0.0 ); float rf0 = 0.02; float reflectance = rf0 + ( 1.0 - rf0 ) * pow( ( 1.0 - theta ), 5.0 ); vec3 scatter = max( 0.0, dot( surfaceNormal, eyeDirection ) ) * waterColor; vec3 albedo = mix( ( sunColor * diffuseLight * 0.3 + scatter ) * getShadowMask(), reflectionSample + specularLight, reflectance ); vec3 outgoingLight = albedo; gl_FragColor = vec4( outgoingLight, alpha ); #include #include #include }`},B=new Jt({name:A.name,uniforms:nn.clone(A.uniforms),vertexShader:A.vertexShader,fragmentShader:A.fragmentShader,lights:!0,side:g,fog:m});B.uniforms.mirrorSampler.value=k.texture,B.uniforms.textureMatrix.value=I,B.uniforms.alpha.value=o,B.uniforms.time.value=l,B.uniforms.normalSampler.value=c,B.uniforms.sunColor.value=d,B.uniforms.waterColor.value=p,B.uniforms.sunDirection.value=h,B.uniforms.distortionScale.value=v,B.uniforms.eye.value=u,i.material=B,i.onBeforeRender=function(F,H,q){if(x.setFromMatrixPosition(i.matrixWorld),_.setFromMatrixPosition(q.matrixWorld),S.extractRotation(i.matrixWorld),y.set(0,0,1),y.applyMatrix4(S),w.subVectors(x,_),w.dot(y)>0)return;w.reflect(y).negate(),w.add(x),S.extractRotation(q.matrixWorld),b.set(0,0,-1),b.applyMatrix4(S),b.add(_),M.subVectors(x,b),M.reflect(y).negate(),M.add(x),P.position.copy(w),P.up.set(0,1,0),P.up.applyMatrix4(S),P.up.reflect(y),P.lookAt(M),P.far=q.far,P.updateMatrixWorld(),P.projectionMatrix.copy(q.projectionMatrix),I.set(.5,0,0,.5,0,.5,0,.5,0,0,.5,.5,0,0,0,1),I.multiply(P.projectionMatrix),I.multiply(P.matrixWorldInverse),f.setFromNormalAndCoplanarPoint(y,x),f.applyMatrix4(P.matrixWorldInverse),E.set(f.normal.x,f.normal.y,f.normal.z,f.constant);const G=P.projectionMatrix;C.x=(Math.sign(E.x)+G.elements[8])/G.elements[0],C.y=(Math.sign(E.y)+G.elements[9])/G.elements[5],C.z=-1,C.w=(1+G.elements[10])/G.elements[14],E.multiplyScalar(2/E.dot(C)),G.elements[2]=E.x,G.elements[6]=E.y,G.elements[10]=E.z+1-a,G.elements[14]=E.w,u.setFromMatrixPosition(q.matrixWorld);const re=F.getRenderTarget(),Y=F.xr.enabled,$=F.shadowMap.autoUpdate;i.visible=!1,F.xr.enabled=!1,F.shadowMap.autoUpdate=!1,F.setRenderTarget(k),F.state.buffers.depth.setMask(!0),F.autoClear===!1&&F.clear(),F.render(H,P),i.visible=!0,F.xr.enabled=Y,F.shadowMap.autoUpdate=$,F.setRenderTarget(re);const _e=q.viewport;_e!==void 0&&F.state.viewport(_e)}}}class sy{engine;currentId="0";groundGroup;groundMesh=null;isWaterAddon=!1;clock;groundY=0;static DEFAULT_WATER_NORMALS="/texture/waternormals.jpg";groundList=[{id:"0",names:["无","無","None"]},{id:"1",names:["草地1","草地1","Grass 1"],color:4881486,roughness:.9,metalness:0,map:"/texture/ground/grass01.jpg"},{id:"2",names:["草地2","草地2","Grass 2"],color:4881486,roughness:.9,metalness:0,map:"/texture/ground/grass02.jpg"},{id:"3",names:["草地3","草地3","Grass 3"],color:4881486,roughness:.9,metalness:0,map:"/texture/ground/grass03.jpg"},{id:"4",names:["草地4","草地4","Grass 4"],color:4881486,roughness:.9,metalness:0,map:"/texture/ground/grass04.jpg"},{id:"5",names:["混凝土1","混凝土1","Concrete 1"],color:15790320,roughness:.85,metalness:.1,map:"/texture/ground/concrete01.jpg"},{id:"5",names:["混凝土1","混凝土1","Concrete 1"],color:15790320,roughness:.85,metalness:.1,map:"/texture/ground/concrete02.jpg"},{id:"6",names:["马路1","馬路1","Road 1"],color:15790320,roughness:.55,metalness:.1,map:"/texture/ground/road01.jpg"},{id:"7",names:["马路2","馬路2","Road 2"],color:15790320,roughness:.55,metalness:.1,map:"/texture/ground/road02.jpg"},{id:"8",names:["泥土1","泥土1","Soil 1"],color:15790320,roughness:.55,metalness:.1,map:"/texture/ground/tiles01.jpg"},{id:"9",names:["泥土2","泥土2","Soil 2"],color:15790320,roughness:.55,metalness:.1,map:"/texture/ground/tiles02.jpg"},{id:"10",names:["木板","木板","Wood Board"],color:15790320,roughness:.55,metalness:.1,map:"/texture/ground/wood01.jpg"},{id:"11",names:["地砖1","地磚1","Floor Tile 1"],color:15790320,roughness:.55,metalness:.1,map:"/texture/ground/z01.jpg"},{id:"12",names:["地砖2","地磚2","Floor Tile 2"],color:15790320,roughness:.55,metalness:.1,map:"/texture/ground/z02.jpg"},{id:"13",names:["湖面","湖面","Lake Surface"],water:!0,waterColor:5929582,distortionScale:2.5,size:1},{id:"14",names:["海面","海面","Sea Surface"],water:!0,waterColor:28062,distortionScale:3.7,size:1}];constructor(e){this.engine=e,this.groundGroup=new pi,this.groundGroup.name="groundGroup",this.clock=new H_}init(){this.engine.scene.add(this.groundGroup)}setGround(e,t){if(this._dispose(),this.currentId=e,e==="0")return;const i=this.groundList.find(r=>r.id===e);debugger;if(!i)return;const n=t?.size??3e4;if(i.water){const r=new vs(n,n),a=sy.DEFAULT_WATER_NORMALS,o=new qa().load(a,u=>{u.wrapS=u.wrapT=Ji}),l=t?.sunDirection??new R(.5,.8,.5).normalize(),c=t?.distortionScale??i.distortionScale??3.7,h=t?.waterSize??i.size??1,d=t?.opacity??.92,p=new kF(r,{textureWidth:512,textureHeight:512,waterNormals:o,sunDirection:l.clone(),sunColor:16777215,waterColor:i.waterColor??28062,distortionScale:c,alpha:d,fog:!!this.engine.scene?.fog});p.rotation.x=-Math.PI/2,p.position.y=-.01,p.name="groundMesh",p.receiveShadow=!0,p.castShadow=!1,this.ensureWaterShadowUniforms(p.material),p.material.uniforms.size.value=h,this.groundMesh=p,this.isWaterAddon=!0,this.groundGroup.add(p)}else{const r=new vs(n,n,1,1);r.rotateX(-Math.PI/2);const a=new sr({color:i.color,roughness:i.roughness,metalness:i.metalness}),o=t?.textureUrl??i.map;o&&new qa().load(o,c=>{c.wrapS=c.wrapT=Ji,c.repeat.set(1e4,1e4),a.map=c,a.needsUpdate=!0},void 0,()=>{});const l=new ht(r,a);l.name="groundMesh",l.receiveShadow=!0,l.castShadow=!1,l.position.y=-.01,this.groundMesh=l,this.isWaterAddon=!1,this.groundGroup.add(l)}this.groundGroup.position.y=this.groundY,this.clock.start()}setHeight(e){this.groundY=e,this.groundGroup.position.y=e}getHeight(){return this.groundY}update(){if(!this.groundMesh||!this.isWaterAddon)return;const e=this.groundMesh.material?.uniforms;if(!e)return;e.time.value+=1/60;const t=this.engine.scene?.dirLight;t&&e.sunDirection&&e.sunDirection.value.copy(t.position).normalize();const i=this.engine.camera;i&&e.eye&&e.eye.value.setFromMatrixPosition(i.matrixWorld)}getGroundList(){return this.groundList.map(({id:e,names:t})=>({id:e,names:t}))}getCurrentId(){return this.currentId}show(){this.groundGroup.visible=!0}hide(){this.groundGroup.visible=!1}dispose(){this._dispose(),this.engine.scene.remove(this.groundGroup)}ensureWaterShadowUniforms(e){const t=e.uniforms;t.directionalShadowMap||(t.directionalShadowMap={value:[]}),t.spotShadowMap||(t.spotShadowMap={value:[]}),t.pointShadowMap||(t.pointShadowMap={value:[]}),e.uniformsNeedUpdate=!0}_dispose(){if(!this.groundMesh)return;this.groundMesh.geometry.dispose();const e=this.groundMesh.material;Array.isArray(e)?e.forEach(t=>t.dispose()):e.dispose(),this.groundGroup.remove(this.groundMesh),this.groundMesh=null,this.isWaterAddon=!1}}class Mm extends ht{constructor(){const e=Mm.SkyShader,t=new Jt({name:e.name,uniforms:nn.clone(e.uniforms),vertexShader:e.vertexShader,fragmentShader:e.fragmentShader,side:Bi,depthWrite:!1});super(new fs(1,1,1),t),this.isSky=!0}}Mm.SkyShader={name:"SkyShader",uniforms:{turbidity:{value:2},rayleigh:{value:1},mieCoefficient:{value:.005},mieDirectionalG:{value:.8},sunPosition:{value:new R},up:{value:new R(0,1,0)},cloudScale:{value:2e-4},cloudSpeed:{value:1e-4},cloudCoverage:{value:.4},cloudDensity:{value:.4},cloudElevation:{value:.5},time:{value:0}},vertexShader:` uniform vec3 sunPosition; uniform float rayleigh; uniform float turbidity; uniform float mieCoefficient; uniform vec3 up; varying vec3 vWorldPosition; varying vec3 vSunDirection; varying float vSunfade; varying vec3 vBetaR; varying vec3 vBetaM; varying float vSunE; // constants for atmospheric scattering const float e = 2.71828182845904523536028747135266249775724709369995957; const float pi = 3.141592653589793238462643383279502884197169; // wavelength of used primaries, according to preetham const vec3 lambda = vec3( 680E-9, 550E-9, 450E-9 ); // this pre-calculation replaces older TotalRayleigh(vec3 lambda) function: // (8.0 * pow(pi, 3.0) * pow(pow(n, 2.0) - 1.0, 2.0) * (6.0 + 3.0 * pn)) / (3.0 * N * pow(lambda, vec3(4.0)) * (6.0 - 7.0 * pn)) const vec3 totalRayleigh = vec3( 5.804542996261093E-6, 1.3562911419845635E-5, 3.0265902468824876E-5 ); // mie stuff // K coefficient for the primaries const float v = 4.0; const vec3 K = vec3( 0.686, 0.678, 0.666 ); // MieConst = pi * pow( ( 2.0 * pi ) / lambda, vec3( v - 2.0 ) ) * K const vec3 MieConst = vec3( 1.8399918514433978E14, 2.7798023919660528E14, 4.0790479543861094E14 ); // earth shadow hack // cutoffAngle = pi / 1.95; const float cutoffAngle = 1.6110731556870734; const float steepness = 1.5; const float EE = 1000.0; float sunIntensity( float zenithAngleCos ) { zenithAngleCos = clamp( zenithAngleCos, -1.0, 1.0 ); return EE * max( 0.0, 1.0 - pow( e, -( ( cutoffAngle - acos( zenithAngleCos ) ) / steepness ) ) ); } vec3 totalMie( float T ) { float c = ( 0.2 * T ) * 10E-18; return 0.434 * c * MieConst; } void main() { vec4 worldPosition = modelMatrix * vec4( position, 1.0 ); vWorldPosition = worldPosition.xyz; gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); gl_Position.z = gl_Position.w; // set z to camera.far vSunDirection = normalize( sunPosition ); vSunE = sunIntensity( dot( vSunDirection, up ) ); vSunfade = 1.0 - clamp( 1.0 - exp( ( sunPosition.y / 450000.0 ) ), 0.0, 1.0 ); float rayleighCoefficient = rayleigh - ( 1.0 * ( 1.0 - vSunfade ) ); // extinction (absorption + out scattering) // rayleigh coefficients vBetaR = totalRayleigh * rayleighCoefficient; // mie coefficients vBetaM = totalMie( turbidity ) * mieCoefficient; }`,fragmentShader:` varying vec3 vWorldPosition; varying vec3 vSunDirection; varying vec3 vBetaR; varying vec3 vBetaM; varying float vSunE; uniform float mieDirectionalG; uniform vec3 up; uniform float cloudScale; uniform float cloudSpeed; uniform float cloudCoverage; uniform float cloudDensity; uniform float cloudElevation; uniform float time; // Cloud noise functions float hash( vec2 p ) { return fract( sin( dot( p, vec2( 127.1, 311.7 ) ) ) * 43758.5453123 ); } float noise( vec2 p ) { vec2 i = floor( p ); vec2 f = fract( p ); f = f * f * ( 3.0 - 2.0 * f ); float a = hash( i ); float b = hash( i + vec2( 1.0, 0.0 ) ); float c = hash( i + vec2( 0.0, 1.0 ) ); float d = hash( i + vec2( 1.0, 1.0 ) ); return mix( mix( a, b, f.x ), mix( c, d, f.x ), f.y ); } float fbm( vec2 p ) { float value = 0.0; float amplitude = 0.5; for ( int i = 0; i < 5; i ++ ) { value += amplitude * noise( p ); p *= 2.0; amplitude *= 0.5; } return value; } // constants for atmospheric scattering const float pi = 3.141592653589793238462643383279502884197169; const float n = 1.0003; // refractive index of air const float N = 2.545E25; // number of molecules per unit volume for air at 288.15K and 1013mb (sea level -45 celsius) // optical length at zenith for molecules const float rayleighZenithLength = 8.4E3; const float mieZenithLength = 1.25E3; // 66 arc seconds -> degrees, and the cosine of that const float sunAngularDiameterCos = 0.999956676946448443553574619906976478926848692873900859324; // 3.0 / ( 16.0 * pi ) const float THREE_OVER_SIXTEENPI = 0.05968310365946075; // 1.0 / ( 4.0 * pi ) const float ONE_OVER_FOURPI = 0.07957747154594767; float rayleighPhase( float cosTheta ) { return THREE_OVER_SIXTEENPI * ( 1.0 + pow( cosTheta, 2.0 ) ); } float hgPhase( float cosTheta, float g ) { float g2 = pow( g, 2.0 ); float inverse = 1.0 / pow( 1.0 - 2.0 * g * cosTheta + g2, 1.5 ); return ONE_OVER_FOURPI * ( ( 1.0 - g2 ) * inverse ); } void main() { vec3 direction = normalize( vWorldPosition - cameraPosition ); // optical length // cutoff angle at 90 to avoid singularity in next formula. float zenithAngle = acos( max( 0.0, dot( up, direction ) ) ); float inverse = 1.0 / ( cos( zenithAngle ) + 0.15 * pow( 93.885 - ( ( zenithAngle * 180.0 ) / pi ), -1.253 ) ); float sR = rayleighZenithLength * inverse; float sM = mieZenithLength * inverse; // combined extinction factor vec3 Fex = exp( -( vBetaR * sR + vBetaM * sM ) ); // in scattering float cosTheta = dot( direction, vSunDirection ); float rPhase = rayleighPhase( cosTheta * 0.5 + 0.5 ); vec3 betaRTheta = vBetaR * rPhase; float mPhase = hgPhase( cosTheta, mieDirectionalG ); vec3 betaMTheta = vBetaM * mPhase; vec3 Lin = pow( vSunE * ( ( betaRTheta + betaMTheta ) / ( vBetaR + vBetaM ) ) * ( 1.0 - Fex ), vec3( 1.5 ) ); Lin *= mix( vec3( 1.0 ), pow( vSunE * ( ( betaRTheta + betaMTheta ) / ( vBetaR + vBetaM ) ) * Fex, vec3( 1.0 / 2.0 ) ), clamp( pow( 1.0 - dot( up, vSunDirection ), 5.0 ), 0.0, 1.0 ) ); // nightsky float theta = acos( direction.y ); // elevation --> y-axis, [-pi/2, pi/2] float phi = atan( direction.z, direction.x ); // azimuth --> x-axis [-pi/2, pi/2] vec2 uv = vec2( phi, theta ) / vec2( 2.0 * pi, pi ) + vec2( 0.5, 0.0 ); vec3 L0 = vec3( 0.1 ) * Fex; // composition + solar disc float sundisk = smoothstep( sunAngularDiameterCos, sunAngularDiameterCos + 0.00002, cosTheta ); L0 += ( vSunE * 19000.0 * Fex ) * sundisk; vec3 texColor = ( Lin + L0 ) * 0.04 + vec3( 0.0, 0.0003, 0.00075 ); // Clouds if ( direction.y > 0.0 && cloudCoverage > 0.0 ) { // Project to cloud plane (higher elevation = clouds appear lower/closer) float elevation = mix( 1.0, 0.1, cloudElevation ); vec2 cloudUV = direction.xz / ( direction.y * elevation ); cloudUV *= cloudScale; cloudUV += time * cloudSpeed; // Multi-octave noise for fluffy clouds float cloudNoise = fbm( cloudUV * 1000.0 ); cloudNoise += 0.5 * fbm( cloudUV * 2000.0 + 3.7 ); cloudNoise = cloudNoise * 0.5 + 0.5; // Apply coverage threshold float cloudMask = smoothstep( 1.0 - cloudCoverage, 1.0 - cloudCoverage + 0.3, cloudNoise ); // Fade clouds near horizon (adjusted by elevation) float horizonFade = smoothstep( 0.0, 0.1 + 0.2 * cloudElevation, direction.y ); cloudMask *= horizonFade; // Cloud lighting based on sun position float sunInfluence = dot( direction, vSunDirection ) * 0.5 + 0.5; float daylight = max( 0.0, vSunDirection.y * 2.0 ); // Base cloud color affected by atmosphere vec3 atmosphereColor = Lin * 0.04; vec3 cloudColor = mix( vec3( 0.3 ), vec3( 1.0 ), daylight ); cloudColor = mix( cloudColor, atmosphereColor + vec3( 1.0 ), sunInfluence * 0.5 ); cloudColor *= vSunE * 0.00002; // Blend clouds with sky texColor = mix( texColor, cloudColor, cloudMask * cloudDensity ); } gl_FragColor = vec4( texColor, 1.0 ); #include #include }`};const y2={turbidity:10,rayleigh:3,mieCoefficient:.005,mieDirectionalG:.7,elevation:2,azimuth:180,exposure:.5,orthoExposureScale:1.5,cloudCoverage:.4,cloudDensity:.4,cloudElevation:.5,showSunDisc:!0},OF="sunrise_clear",ry=[{id:"sunrise_clear",names:["晴朗日出","晴朗日出","Clear Sunrise"],params:{turbidity:4,rayleigh:1.8,mieCoefficient:.004,mieDirectionalG:.72,elevation:8,azimuth:105,exposure:.42,cloudCoverage:.12,cloudDensity:.2,cloudElevation:.45,showSunDisc:!0}},{id:"morning_mist",names:["晨雾薄云","晨雾薄云","Misty Morning"],params:{turbidity:14,rayleigh:2.4,mieCoefficient:.018,mieDirectionalG:.68,elevation:12,azimuth:120,exposure:.35,cloudCoverage:.45,cloudDensity:.5,cloudElevation:.35,showSunDisc:!0}},{id:"noon_clear",names:["晴空正午","晴空正午","Clear Noon"],params:{turbidity:2,rayleigh:1,mieCoefficient:.002,mieDirectionalG:.82,elevation:68,azimuth:180,exposure:.58,cloudCoverage:.05,cloudDensity:.12,cloudElevation:.55,showSunDisc:!0}},{id:"afternoon_cloudy",names:["午后多云","午后多云","Cloudy Afternoon"],params:{turbidity:8,rayleigh:1.7,mieCoefficient:.008,mieDirectionalG:.74,elevation:42,azimuth:220,exposure:.5,cloudCoverage:.48,cloudDensity:.42,cloudElevation:.52,showSunDisc:!0}},{id:"sunset_glow",names:["落日晚霞","落日晚霞","Sunset Glow"],params:{turbidity:10,rayleigh:2,mieCoefficient:.006,mieDirectionalG:.7,elevation:6,azimuth:245,exposure:.6,cloudCoverage:.3,cloudDensity:.36,cloudElevation:.5,showSunDisc:!0}},{id:"blue_hour",names:["暮色蓝调","暮色蓝调","Blue Hour"],params:{turbidity:7,rayleigh:1.2,mieCoefficient:.003,mieDirectionalG:.76,elevation:-4,azimuth:255,exposure:.22,cloudCoverage:.2,cloudDensity:.24,cloudElevation:.48,showSunDisc:!1}},{id:"overcast_day",names:["阴天白昼","阴天白昼","Overcast Day"],params:{turbidity:20,rayleigh:2,mieCoefficient:.02,mieDirectionalG:.6,elevation:32,azimuth:180,exposure:.38,cloudCoverage:.86,cloudDensity:.68,cloudElevation:.4,showSunDisc:!1}},{id:"storm_rain",names:["暴雨雷云","暴雨雷云","Storm Rain"],params:{turbidity:19,rayleigh:.9,mieCoefficient:.03,mieDirectionalG:.58,elevation:18,azimuth:210,exposure:.2,cloudCoverage:.95,cloudDensity:.9,cloudElevation:.28,showSunDisc:!1}},{id:"snow_day",names:["雪天漫射","雪天漫射","Snowy Day"],params:{turbidity:15,rayleigh:2.6,mieCoefficient:.012,mieDirectionalG:.65,elevation:24,azimuth:170,exposure:.5,cloudCoverage:.78,cloudDensity:.72,cloudElevation:.43,showSunDisc:!1}},{id:"moonlit_night",names:["月夜星空","月夜星空","Moonlit Night"],params:{turbidity:4,rayleigh:.35,mieCoefficient:.001,mieDirectionalG:.82,elevation:-18,azimuth:160,exposure:.14,cloudCoverage:.1,cloudDensity:.14,cloudElevation:.55,showSunDisc:!1}}],x2=ry.reduce((s,e)=>(s[e.id]=e,s),{}),_2=2e6;class UF{engine;sky=null;sun=new R;params={...y2,...x2[OF].params};currentIntensity=.2;currentEnvironmentTarget=null;skyScale=45e4;skyName="bim_engine_sky";savedCameraFar=null;previousBackground=null;previousEnvironment=null;previousBackgroundIntensity=1;previousEnvironmentIntensity=1;previousToneMapping=ji;previousToneMappingExposure=1;hasCapturedSceneState=!1;constructor(e){this.engine=e}activate(){if(!this.engine?.scene)return;if(this.sky){this.sky.visible=!0,this._captureSceneState(),this._expandCameraFarForSky(),this._applyParamsToSky();return}const e=new Mm;e.scale.setScalar(this.skyScale),e.name=this.skyName,this.sky=e,this.engine.scene.add(e),this._captureSceneState(),this._expandCameraFarForSky(),this.engine.renderer&&(this.engine.renderer.toneMapping=Sa,this.engine.scene.background=null),this._applyParamsToSky()}close(e=!0){this.sky&&(this._restoreCameraFar(),this._restoreSceneState(e),e?(this.engine?.scene?.remove(this.sky),this.sky.material.dispose(),this.sky.geometry.dispose(),this.sky=null):this.sky.visible=!1)}isActive(){return this.sky!=null&&this.engine?.scene?.children?.includes(this.sky)}getParams(){return{...this.params}}setParams(e){Object.assign(this.params,e),this._applyParamsToSky(),this.engine?.renderer&&(e.exposure!==void 0||e.orthoExposureScale!==void 0)&&(this.engine.renderer.toneMappingExposure=this._getEffectiveExposure())}setPreset(e){const t=x2[e];t&&(this.params={...y2,...t.params},this._applyParamsToSky(),this.engine?.renderer&&(this.engine.renderer.toneMappingExposure=this._getEffectiveExposure()))}getPresetNames(){return ry.map(e=>e.id)}getPresetList(){return ry.map(e=>({id:e.id,names:[...e.names],params:{...e.params}}))}setIntensity(e){if(this.currentIntensity=Math.max(e,0),!(!this.sky?.visible||!this.engine?.scene)){if(!this.currentEnvironmentTarget){this._refreshEnvironmentMap();return}this.engine.scene.environmentIntensity=this.currentIntensity}}getIntensity(){return this.currentIntensity}update(e){if(!this.sky?.visible)return;const t=this.sky.material.uniforms;t&&"time"in t&&(t.time.value=e??performance.now()*.001),this.engine?.renderer&&(this.engine.renderer.toneMappingExposure=this._getEffectiveExposure())}_isOrthographicCamera(){const e=this.engine?.camera;return e!=null&&e.type==="OrthographicCamera"}_getEffectiveExposure(){const e=this.params.exposure;return this._isOrthographicCamera()?e*this.params.orthoExposureScale:e}_expandCameraFarForSky(){const e=this.engine?.camera;if(!e||typeof e.far!="number")return;const t=e.far;t>=_2||(this.savedCameraFar==null&&(this.savedCameraFar=t),e.far=_2,typeof e.updateProjectionMatrix=="function"&&e.updateProjectionMatrix())}_restoreCameraFar(){if(this.savedCameraFar==null||!this.engine?.camera)return;const e=this.engine.camera;typeof e.far=="number"&&(e.far=this.savedCameraFar,typeof e.updateProjectionMatrix=="function"&&e.updateProjectionMatrix(),this.savedCameraFar=null)}_applyParamsToSky(){if(!this.sky)return;const e=this.sky.material.uniforms;this._setUniformValue(e,"turbidity",this.params.turbidity),this._setUniformValue(e,"rayleigh",this.params.rayleigh),this._setUniformValue(e,"mieCoefficient",this.params.mieCoefficient),this._setUniformValue(e,"mieDirectionalG",this.params.mieDirectionalG),this._setUniformValue(e,"cloudCoverage",this.params.cloudCoverage),this._setUniformValue(e,"cloudDensity",this.params.cloudDensity),this._setUniformValue(e,"cloudElevation",this.params.cloudElevation),this._setUniformValue(e,"showSunDisc",this.params.showSunDisc?1:0);const t=Lt.degToRad(90-this.params.elevation),i=Lt.degToRad(this.params.azimuth);this.sun.setFromSphericalCoords(1,t,i),this._setUniformValue(e,"sunPosition",this.sun),this.engine?.renderer&&(this.engine.renderer.toneMapping=Sa,this.engine.renderer.toneMappingExposure=this._getEffectiveExposure(),this.sky.visible&&this._refreshEnvironmentMap())}_captureSceneState(){this.hasCapturedSceneState||!this.engine?.scene||(this.previousBackground=this.engine.scene.background,this.previousEnvironment=this.engine.scene.environment,this.previousBackgroundIntensity=this.engine.scene.backgroundIntensity??1,this.previousEnvironmentIntensity=this.engine.scene.environmentIntensity??1,this.previousToneMapping=this.engine.renderer?.toneMapping??ji,this.previousToneMappingExposure=this.engine.renderer?.toneMappingExposure??1,this.hasCapturedSceneState=!0)}_restoreSceneState(e){!this.hasCapturedSceneState||!this.engine?.scene||(this.engine.scene.background=this.previousBackground,this.engine.scene.environment=this.previousEnvironment,this.engine.scene.backgroundIntensity=this.previousBackgroundIntensity,this.engine.scene.environmentIntensity=this.previousEnvironmentIntensity,this.engine.renderer&&(this.engine.renderer.toneMapping=this.previousToneMapping,this.engine.renderer.toneMappingExposure=this.previousToneMappingExposure),e&&(this._disposeEnvironmentTarget(),this.previousBackground=null,this.previousEnvironment=null,this.previousBackgroundIntensity=1,this.previousEnvironmentIntensity=1,this.previousToneMapping=ji,this.previousToneMappingExposure=1,this.hasCapturedSceneState=!1))}_refreshEnvironmentMap(){if(!this.sky||!this.engine?.renderer||!this.engine?.scene)return;this._disposeEnvironmentTarget();const e=new Ia,t=this.sky.clone();t.material=this.sky.material.clone(),e.add(t);const i=new uh(this.engine.renderer);this.currentEnvironmentTarget=i.fromScene(e,0,.1,this.skyScale*2),i.dispose(),this.engine.scene.background=null,this.engine.scene.environment=this.currentEnvironmentTarget.texture,this.engine.scene.environmentIntensity=this.currentIntensity,t.material.dispose()}_disposeEnvironmentTarget(){this.currentEnvironmentTarget?.dispose(),this.currentEnvironmentTarget=null}_setUniformValue(e,t,i){const n=e[t];n&&(i instanceof R&&typeof n.value?.copy=="function"?n.value.copy(i):n.value=i)}}let BF=class{engine;constructor(s){this.engine=s,this.active()}active(){window.addEventListener("D2ElementClick",this.listenElementClick)}disActive(){window.removeEventListener("D2ElementClick",this.listenElementClick)}listenElementClick=s=>{let e=!0;this.engine.models.forEach(t=>{t.nodesMap.has(Number(s.detail.id))&&(e=!1,this.engine.modelToolModule.highlightModel([{url:t.url,ids:[Number(s.detail.id)]}]),this.engine.viewCube.zoomToModels({url:t.url,id:Number(s.detail.id)}))}),(Number(s.detail.id)==-1||e)&&this.engine.modelToolModule.unhighlightAllModels()}},FF=class{engine;constructor(s){this.engine=s,this.active()}active(){window.addEventListener("D2ViewControl",this.listenViewUpdate)}disActive(){window.removeEventListener("D2ViewControl",this.listenViewUpdate)}listenViewUpdate=s=>{const e=s?.detail;e&&(e.position&&this.applyPosition(e.position),typeof e.rotation=="number"&&this.applyRotation(e.rotation))};applyPosition(s){const e=this.engine.camera;if(!e)return;const t=this.engine.controls,i=e.position.clone(),n=typeof s.y=="number"?s.y:i.y;e.position.set(s.x,n,s.z),t?.target?(t.target.set(t.target.x+(s.x-i.x),t.target.y+(n-i.y),t.target.z+(s.z-i.z)),t.update(),t.dispatchEvent?.({type:"change"})):e.updateMatrixWorld()}applyRotation(s){const e=this.engine.camera;if(!e)return;const t=this.engine.controls,i=t?.target;let n=10;i&&(n=Math.max(1,e.position.distanceTo(i)));const r=new R(Math.sin(s),0,-Math.cos(s)),a=i?i.y:e.position.y,o=new R(e.position.x+r.x*n,a,e.position.z+r.z*n);t?.target?(t.target.copy(o),t.update(),t.dispatchEvent?.({type:"change"})):e.lookAt(o)}};class zF{engine;apiKey;baseURL="https://api.deepseek.com";constructor(e,t){this.engine=e,this.apiKey=t||"sk-4677b153277a40b096c6716686c29ac4",console.log("OneClickEncoding 初始化,API Key:",this.apiKey?.substring(0,8)+"...")}start(){let e=["注释","族名称"],t=[];this.engine.models.forEach(i=>{i.nodesMap.forEach((n,r)=>{this.engine.modelProperties.getModelPropertiesWithName(i.url,r,e,a=>{t.push(a),t.length==i.nodesMap.size&&this.startChat(i.url,JSON.stringify(t))})})})}async startChat(e,t){let i=await this.chat(t);const n=i.match(/```json\s*([\s\S]*?)\s*```/),r=n?n[1]:i,a=JSON.parse(r);console.log("解析后的编码结果:",a);let o=this.engine.models.find(l=>l.url==e);o!=null&&a.forEach(l=>{let c=o.nodesMap.get(Number(l.id));c!=null&&(c.code=l.code)})}async chat(e){let t=`你是一个经验丰富的桥梁工程师,你要为我的BIM模型进行编码,按一定的规则进行编码。 【输入信息】 - 1. json字符串,里面会包含构件名称,构件类型,里程等等等。 - 2. 项目的基本信息,如项目名称,桥梁名称等 【编码规则】 请按照以下层级生成编码(用”-”连接): 第一层:工程部位(固定为”桥梁工程”) 第二层:构件类型(主梁/桥墩/桩基/盖梁/支座等) 第三层:具体位置标识(线路+墩号+构件编号) 【示例格式】 桥梁工程-桩基-左线1#_2桩基 【输出要求】 请根据上述规则,为输入构件生成标准编码,必须每个构件都具有编码。 【输出格式】 输出格式要严格的json格式,包含构件id,构件编码,格式如下 [ {“id”:0,”code”:”code”} ] `;try{console.log("正在调用 DeepSeek API..."),console.log("API Key 前8位:",this.apiKey?.substring(0,8)+"...");const i=await fetch(`${this.baseURL}/v1/chat/completions`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify({model:"deepseek-chat",messages:[{role:"system",content:t},{role:"user",content:e}],temperature:.7})});if(!i.ok){const r=await i.text();throw console.error("API 错误详情:",r),new Error(`API request failed: ${i.status} - ${r}`)}const n=await i.json();return console.log("API 调用成功:",n),n.choices[0].message.content}catch(i){throw console.error("DeepSeek API call failed:",i),i}}}class HF{engine;constructor(e){this.engine=e}getViewTreeData(e){return this.engine.models.find(t=>t.url===e)?.views}openView(e,t){t="771513";const i=this.engine.models.find(l=>l.url===e)?.views?.Sections.find(l=>l.id===t||l.Id===t);if(!i)return;const n=i.Origin||i.origin,r=i.ViewDirection||i.viewDirection;if(!n||!r)return;const a=new R(n.X??n.x,-(n.Z??n.z),n.Y??n.y).setLength(.3048),o=new R(r.X??r.x,-(r.Z??r.z),r.Y??r.y).setLength(-1);this.engine.cameraModule.setViewFromOriginAndDirection(a,o),(i.ViewType||i.viewType||"")==="剖面视图"&&(this.engine.clipping.setSectionByView(a,o),this.engine.merge2d.attachSectionPlane(e,t,a,o))}}var Wn=(s=>(s.ModelLoadStart="model-load-start",s.ModelLoadProgress="model-load-progress",s.ModelLoaded="model-loaded",s.ModelLoadError="model-load-error",s.RenderStart="render-start",s.RenderEnd="render-end",s.CameraChanged="camera-changed",s.CameraReset="camera-reset",s.SelectionChanged="selection-changed",s.HoverChanged="hover-changed",s.EntityClick="entity-click",s.LayerVisibilityChanged="layer-visibility-changed",s.LayerColorChanged="layer-color-changed",s.ViewZoomChanged="view-zoom-changed",s.ViewPanChanged="view-pan-changed",s.ToolActivated="tool-activated",s.ToolDeactivated="tool-deactivated",s.Error="error",s.Warning="warning",s))(Wn||{});class VF{listeners=new Map;onceListeners=new Map;debugMode=!1;constructor(e=!1){this.debugMode=e,this.initializeEvents()}initializeEvents(){Object.values(Wn).forEach(e=>{this.listeners.set(e,new Set),this.onceListeners.set(e,new Set)})}on(e,t){return this.listeners.has(e)?(this.listeners.get(e).add(t),this.debugMode&&console.log(`[EventModule2d] Listener added for ${e}`),()=>this.off(e,t)):(console.warn(`Event type ${e} is not registered`),()=>{})}once(e,t){if(!this.onceListeners.has(e)){console.warn(`Event type ${e} is not registered`);return}this.onceListeners.get(e).add(t),this.debugMode&&console.log(`[EventModule2d] Once listener added for ${e}`)}off(e,t){const i=this.listeners.get(e);i&&(i.delete(t),this.debugMode&&console.log(`[EventModule2d] Listener removed for ${e}`))}trigger(e,t){this.debugMode&&console.log(`[EventModule2d] Triggering ${e}`,t);const i=this.listeners.get(e);i&&i.size>0&&i.forEach(r=>{try{r(t)}catch(a){console.error(`[EventModule2d] Error in listener for ${e}:`,a)}});const n=this.onceListeners.get(e);n&&n.size>0&&(n.forEach(r=>{try{r(t)}catch(a){console.error(`[EventModule2d] Error in once listener for ${e}:`,a)}}),n.clear())}removeAllListeners(){this.listeners.forEach(e=>e.clear()),this.onceListeners.forEach(e=>e.clear()),this.debugMode&&console.log("[EventModule2d] All listeners removed")}removeListenersOfType(e){const t=this.listeners.get(e),i=this.onceListeners.get(e);t&&t.clear(),i&&i.clear(),this.debugMode&&console.log(`[EventModule2d] All listeners removed for ${e}`)}getListenerCount(e){const t=this.listeners.get(e),i=this.onceListeners.get(e);return(t?.size||0)+(i?.size||0)}setDebugMode(e){this.debugMode=e}getAllEventTypes(){return Object.values(Wn)}dispose(){this.removeAllListeners(),this.listeners.clear(),this.onceListeners.clear(),this.debugMode&&console.log("[EventModule2d] Disposed")}}class GF extends ml{constructor(e,t={}){const i=t.font;if(i===void 0)super();else{const n=i.generateShapes(e,t.size,t.direction);t.depth===void 0&&(t.depth=50),t.bevelThickness===void 0&&(t.bevelThickness=10),t.bevelSize===void 0&&(t.bevelSize=8),t.bevelEnabled===void 0&&(t.bevelEnabled=!1),super(n,t)}this.type="TextGeometry"}}class WF extends sn{constructor(e){super(e)}load(e,t,i,n){const r=this,a=new Jn(this.manager);a.setPath(this.path),a.setRequestHeader(this.requestHeader),a.setWithCredentials(this.withCredentials),a.load(e,function(o){const l=r.parse(JSON.parse(o));t&&t(l)},i,n)}parse(e){return new XF(e)}}class XF{constructor(e){this.isFont=!0,this.type="Font",this.data=e}generateShapes(e,t=100,i="ltr"){const n=[],r=jF(e,t,this.data,i);for(let a=0,o=r.length;aMath.round(d),a=d=>{const p=e.charToGlyph(d);if(!p||p.index===0)return;const u=p.path.commands,v=[];for(const m of u)switch(m.type){case"M":v.push(`m ${r(m.x)} ${r(m.y)}`);break;case"L":v.push(`l ${r(m.x)} ${r(m.y)}`);break;case"Q":v.push(`q ${r(m.x1)} ${r(m.y1)} ${r(m.x)} ${r(m.y)}`);break;case"C":v.push(`b ${r(m.x1)} ${r(m.y1)} ${r(m.x2)} ${r(m.y2)} ${r(m.x)} ${r(m.y)}`);break;case"Z":v.push("z");break}const g=p.getBoundingBox();i[d]={x_min:g.x1,x_max:g.x2,ha:p.advanceWidth??0,o:v.join(" ")}};if(t)for(const d of t)a(d);else{const d=e.tables.cmap?.glyphIndexMap??{};for(const p of Object.keys(d)){const u=Number.parseInt(p,10);u>0&&a(String.fromCodePoint(u))}}if(!i[" "]){const d=e.charToGlyph(" ");i[" "]={x_min:0,x_max:0,ha:d?.advanceWidth??Math.round(n/4),o:""}}const o=e.names,l=d=>o[d]?.en??o[d]?.zh??"",c=l("fontFamily")||"Custom Font",h=l("fontSubfamily")||"Regular";return{familyName:c,ascender:e.ascender,descender:e.descender,underlinePosition:e.tables.post?.underlinePosition??-100,underlineThickness:e.tables.post?.underlineThickness??50,boundingBox:{yMin:e.descender,xMin:0,yMax:e.ascender,xMax:n},resolution:n,original_font_information:{fontFamily:c,fontSubfamily:h},cssFontStyle:h.toLowerCase().includes("italic")?"italic":"normal",cssFontWeight:h.toLowerCase().includes("bold")?"bold":"normal",glyphs:i}}}class ZF{panel=null;listEl=null;isVisible=!1;delegate;constructor(e,t){this.delegate=t,this._buildPanel(e)}show(){this.panel&&(this.panel.style.display="flex",this.isVisible=!0)}hide(){this.panel&&(this.panel.style.display="none",this.isVisible=!1)}toggle(){this.isVisible?this.hide():this.show()}refresh(){this._renderList()}_buildPanel(e){const t=document.createElement("div");t.style.cssText=` position:absolute; top:10px; right:10px; width:220px; max-height:480px; background:var(--e2d-bg,#1e1f22); border:1px solid var(--e2d-border2,#333); border-radius:4px; box-shadow:0 4px 16px var(--e2d-shadow,rgba(0,0,0,.6)); display:none; flex-direction:column; z-index:100; user-select:none; font-size:13px; color:var(--e2d-text,#e0e0e0); font-family:system-ui,sans-serif; `,this.panel=t;const i=document.createElement("div");i.style.cssText=` display:flex; align-items:center; justify-content:space-between; padding:8px 10px; background:var(--e2d-bg3,#222); border-bottom:1px solid var(--e2d-border2,#333); border-radius:4px 4px 0 0; cursor:move; flex-shrink:0; `;const n=document.createElement("span");n.textContent="图层",n.style.cssText="font-size:13px; font-weight:500; color:var(--e2d-text,#e0e0e0);";const r=document.createElement("button");r.textContent="×",r.style.cssText=` background:none; border:none; color:var(--e2d-close,#aaa); font-size:18px; line-height:1; cursor:pointer; padding:0 2px; transition:color 0.15s; `,r.onmouseenter=()=>{r.style.color="var(--e2d-close-hover,#fff)"},r.onmouseleave=()=>{r.style.color="var(--e2d-close,#aaa)"},r.onclick=()=>this.hide(),i.appendChild(n),i.appendChild(r),this._makeDraggable(t,i);const a=this._createRow(),o=this._createEye(!0),l=document.createElement("span");l.textContent="全部图层",l.style.cssText="flex:1; font-weight:500; color:var(--e2d-text,#e0e0e0);",a.appendChild(o),a.appendChild(l),a.onclick=()=>{const p=!this.delegate.isAllVisible();this.delegate.setAllLayersVisible(p),this._renderList(),this._updateEye(o,p)};const c=document.createElement("div");c.style.cssText="height:1px; background:var(--e2d-border2,#333); margin:0 8px; flex-shrink:0;";const h=document.createElement("div");h.style.cssText=` overflow-y:auto; flex:1; scrollbar-width:thin; scrollbar-color:var(--e2d-scrollbar,#444) transparent; `,this.listEl=h,t.appendChild(i),t.appendChild(a),t.appendChild(c),t.appendChild(h);const d=this._renderList.bind(this);this._renderList=()=>{d(),this._updateEye(o,this.delegate.isAllVisible())},this._renderList(),e.style.position="relative",e.appendChild(t)}_renderList(){const e=this.listEl;if(e){e.innerHTML="";for(const t of this.delegate.getLayers()){const i=this._createRow(),n=this._createEye(t.visible),r=document.createElement("span");r.style.cssText=` width:14px; height:14px; border-radius:2px; flex-shrink:0; border:1px solid var(--e2d-swatch-border,#444); background:${this._colorToHex(t.color)}; `;const a=document.createElement("span");a.textContent=t.name,a.style.cssText=` flex:1; white-space:nowrap; overflow:hidden; text-overflow:ellipsis; font-size:12px; color:${t.visible?"var(--e2d-text,#ddd)":"var(--e2d-text4,#666)"}; transition:color 0.15s; `,i.appendChild(n),i.appendChild(r),i.appendChild(a),i.onclick=()=>{const o=this.delegate.toggleLayer(t.name);this._updateEye(n,o),a.style.color=o?"var(--e2d-text,#ddd)":"var(--e2d-text4,#666)"},e.appendChild(i)}}}_createRow(){const e=document.createElement("div");return e.style.cssText=` display:flex; align-items:center; gap:8px; padding:5px 10px; cursor:pointer; border-bottom:1px solid var(--e2d-border2,#222); transition:background 0.1s; `,e.onmouseenter=()=>{e.style.background="var(--e2d-bg-hover,#2a2a2a)"},e.onmouseleave=()=>{e.style.background=""},e}_createEye(e){const t=document.createElement("span");return t.style.cssText="display:flex; align-items:center; flex-shrink:0; width:16px;",this._updateEye(t,e),t}_updateEye(e,t){e.style.color=t?"var(--e2d-close,#aaa)":"var(--e2d-text4,#555)",e.innerHTML=t?` `:` `}_colorToHex(e){return"#"+e.toString(16).padStart(6,"0")}_makeDraggable(e,t){t.onmousedown=i=>{i.preventDefault();const n=e.getBoundingClientRect(),r=e.offsetParent?.getBoundingClientRect()??{left:0,top:0};e.style.left=n.left-r.left+"px",e.style.top=n.top-r.top+"px",e.style.right="auto",e.style.bottom="auto";const a=i.clientX-n.left,o=i.clientY-n.top,l=h=>{e.style.left=h.clientX-a-r.left+"px",e.style.top=h.clientY-o-r.top+"px"},c=()=>{document.removeEventListener("mousemove",l),document.removeEventListener("mouseup",c)};document.addEventListener("mousemove",l),document.addEventListener("mouseup",c)}}dispose(){this.panel?.remove(),this.panel=null,this.listEl=null}}class b2{engine;layerMap=new Map;panelUI=null;constructor(e){this.engine=e;const t=document.getElementById(e?.options?.containerId??"")??e?.container??null;t&&(this.panelUI=new ZF(t,this))}_loadLayers(){let e=this.engine.dwgData.layers;this.layerMap.clear();for(const t of e)this.layerMap.set(t.name,{...t}),this.panelUI?.refresh()}syncFromModel(e){e?.length>0&&(this._loadLayers(e),this.panelUI?.refresh())}getLayers(){return Array.from(this.layerMap.values())}setLayerVisible(e,t){const i=this.layerMap.get(e);i&&(i.visible=t),this._applyVisibility(e,t)}toggleLayer(e){const t=this.layerMap.get(e);if(!t)return!0;const i=!t.visible;return this.setLayerVisible(e,i),i}setAllLayersVisible(e){for(const t of this.layerMap.keys()){const i=this.layerMap.get(t);i.visible=e,this._applyVisibility(t,e)}}isAllVisible(){return Array.from(this.layerMap.values()).every(e=>e.visible)}_applyVisibility(e,t){const i=this.engine?.scene;if(!i)return;const n=e+"||";i.children.forEach(r=>{r.name?.startsWith(n)&&(r.visible=t)})}show(){this.panelUI?.show()}hide(){this.panelUI?.hide()}toggle(){this.panelUI?.toggle()}dispose(){this.panelUI?.dispose(),this.panelUI=null,this.layerMap.clear()}}class M2{engine;data=null;enableValidation=!0;constructor(e){for(this.engine=e,this.engine.modelGroup=new pi,this.engine.modelGroup.name="model2d",this.engine.scene.add(this.engine.modelGroup);this.engine.modelGroup.children.length>0;)this.engine.modelGroup.remove(this.engine.modelGroup.children[0])}async loadModel(e,t={}){if(!e.includes(".json"))this.engine.events&&this.engine.events.trigger(Wn.ModelLoadStart,{url:e}),Uh(e,async i=>{const n=JSON.parse(i);this.engine.dwgData=n,this.data=n,await this.buildScene(n);try{this.engine.fitToView()}catch{}this.engine.layerManager||(this.engine.layerManager=new b2(this.engine)),this.engine.layerManager._loadLayers(),this.engine.events&&this.engine.events.trigger(Wn.ModelLoaded,{})},i=>{this._emitProgress(0,"抱歉,图纸加载失败")});else{this.engine.events&&this.engine.events.trigger(Wn.ModelLoadStart,{url:e}),this._emitProgress(10,"请求数据...");const i=await this.fetchJson(e);this._emitProgress(20,"解析数据...");const n=this.parseData(i);if(this.engine.dwgData=n,!n)throw new Error("Failed to parse DWG data");this.data=n,await this.buildScene(n),this.engine.fitToView(),this.engine.layerManager._loadLayers(),this.engine.events&&this.engine.events.trigger(Wn.ModelLoaded,{})}}async fetchJson(e){const t=await fetch(e);if(!t.ok)throw new Error(`HTTP error! status: ${t.status}`);return await t.json()}parseData(e){return e?this.enableValidation&&!this.validateDataStructure(e)?(console.error("[LoaderModule2d] Invalid data structure"),null):e:(console.error("[LoaderModule2d] Empty JSON data"),null)}validateDataStructure(e){return e.version||console.warn("[LoaderModule2d] Missing version"),e.metadata||console.warn("[LoaderModule2d] Missing metadata"),Array.isArray(e.layers)?Array.isArray(e.entities)?!0:(console.error("[LoaderModule2d] Invalid or missing entities array"),!1):(console.error("[LoaderModule2d] Invalid or missing layers array"),!1)}model={};totalBlock=new Map;font=null;async loadFont(){const e=this.engine.options?.fontUrl??"/fonts/simfang.ttf",t=await Jh.fromUrl(e);return Jh.toThreeFont(t)}_emitProgress(e,t){this.engine.events&&this.engine.events.trigger(Wn.ModelLoadProgress,{progress:e,text:t})}async buildScene(e){this._emitProgress(10,"正在加载"),this.font=await this.loadFont(),this.model.layers=e.layers,this.model.modelMap=new Map,this.model.hatchMap=new Map,this.model.textMap=new Map,this.model.nodeMap=new Map,console.log(this.model.layers),this._emitProgress(10,"正在加载..."),await Promise.resolve(),e.blocks.forEach(t=>{this.loadBlock(t,t.name,!0)}),this._emitProgress(10,"正在加载..."),await Promise.resolve(),this.loadBlock({entities:e.entities},"",!1),this._emitProgress(10,"正在加载..."),await Promise.resolve(),this.model.modelMap.forEach((t,i)=>{let n=[];if(t.forEach(a=>{for(const o of a)n.push(o)}),n.length!=0){const a=new at().setFromPoints(n);let o=parseInt(i.split("||")[1]);if(o==0){var r=this.model.layers.find(d=>d.name==i.split("||")[0]);o=r.color}const l=new si({color:o}),c=new fi(a,l);c.name=i,c.clonePoints=[],n.forEach(d=>{c.clonePoints.push(d.x),c.clonePoints.push(d.y),c.clonePoints.push(d.z)}),c.materialClone=l.clone(),this.engine.modelGroup.add(c);let h=0;t.forEach((d,p)=>{this.model.nodeMap.has(p)?this.model.nodeMap.get(p).push({indexes:[this.engine.modelGroup.children.length-1,h,h+d.length*3],min:new R(Math.min(...d.map(u=>u.x)),Math.min(...d.map(u=>u.y)),0),max:new R(Math.max(...d.map(u=>u.x)),Math.max(...d.map(u=>u.y)),0)}):this.model.nodeMap.set(p,[{indexes:[this.engine.modelGroup.children.length-1,h,h+d.length*3],min:new R(Math.min(...d.map(u=>u.x)),Math.min(...d.map(u=>u.y)),0),max:new R(Math.max(...d.map(u=>u.x)),Math.max(...d.map(u=>u.y)),0)}]),h=h+d.length*3})}}),this._emitProgress(85,"正在加载..."),await Promise.resolve(),this.model.textMap.forEach((t,i)=>{const n=So(t.map(c=>c.geometry),!1);let r=Number.parseInt(i.split("||")[1]);if(r===0){const c=this.model.layers.find(h=>h.name===i.split("||")[0]);c&&(r=c.color)}const a=new Dt({color:r,side:Ot});i.includes("_hitbox")&&(a.visible=!1);let o=new ht(n,a);o.name=i,o.materialClone=a.clone(),o.isSplit=!1,o.geometrys=t.map(c=>c.geometry),this.engine.modelGroup.add(o);let l=0;t.forEach(c=>{this.model.nodeMap.has(c.info.linkId)?this.model.nodeMap.get(c.info.linkId).push({indexes:[this.engine.modelGroup.children.length-1,l++],min:new R(c.info.min[0],c.info.min[1],0),max:new R(c.info.max[0],c.info.max[1],0)}):this.model.nodeMap.set(c.info.linkId,[{indexes:[this.engine.modelGroup.children.length-1,l++],min:new R(c.info.min[0],c.info.min[1],0),max:new R(c.info.max[0],c.info.max[1],0)}])})}),this._emitProgress(93,"正在加载..."),await Promise.resolve(),this.model.hatchMap.forEach((t,i)=>{let n=So(t.map(h=>h.geometry),!1),r=parseInt(i.split("||")[1]);if(r==0){var a=this.model.layers.find(h=>h.name==i.split("||")[0]);r=a.color}const o=new Dt({color:r,side:Ot,transparent:!0,opacity:.5});let l=new ht(n,o);l.name=i,l.materialClone=o.clone(),l.isSplit=!1,l.geometrys=t.map(h=>h.geometry),this.engine.modelGroup.add(l);let c=0;t.forEach(h=>{this.model.nodeMap.has(h.info.linkId)?this.model.nodeMap.get(h.info.linkId).push({indexes:[this.engine.modelGroup.children.length-1,c++],min:new R(h.info.min[0],h.info.min[1],0),max:new R(h.info.max[0],h.info.max[1],0)}):this.model.nodeMap.set(h.info.linkId,[{indexes:[this.engine.modelGroup.children.length-1,c++],min:new R(h.info.min[0],h.info.min[1],0),max:new R(h.info.max[0],h.info.max[1],0)}])})}),this._emitProgress(100,"加载完成")}loadBlock(e,t,i,n=0){let r=[0,0,0];i&&(r=e.origin),e.entities.forEach(a=>{const o=a.layer+"||"+a.color;let l=new Map;i?(l=this.totalBlock.get(t),l==null&&(l=new Map,this.totalBlock.set(t,l))):(l=this.model.modelMap.get(o),l==null&&(l=new Map,this.model.modelMap.set(o,l)));let c=[];switch(a.type){case"LINE":c=this.getPoint_line(a,r);break;case"CIRCLE":c=this.getPoint_arc(a,r);break;case"POLYLINE":c=this.getPoint_polyline(a,r);break;case"MTEXT":this.create_text(a);break;case"HATCH":this.create_hatch(a);break;case"INSERT":if(i==!1){this.totalBlock.get(a.blockId)?.forEach(p=>{c.push(...p.map(u=>u.clone()))});const d=this.getMatrix(a.position,a.scale,a.rotation);c.forEach(p=>{p.applyMatrix4(d)})}break;default:return console.warn(`[LoaderModule2d] Unknown entity type: ${a.type}`),null}l.has(a.linkId)?l.get(a.linkId).push(...c):l.set(a.linkId,c)})}getPoint_polyline(e,t){let i=[];for(let n=0;n{n[0]=n[0]-t[0],n[1]=n[1]-t[1]}),i}create_hatch(e){if(!e.loops||e.loops.length===0)return;const t=e.loops.filter(o=>o.type===!0),i=e.loops.filter(o=>o.type===!1),n=[];for(const o of t){if(!o.points||o.points.length<3)continue;const l=new nr;l.moveTo(o.points[0][0],o.points[0][1]);for(let c=1;c{a[0]=a[0]-t[0],a[1]=a[1]-t[1]}),r}getPoint_arc(e,t){const i=e.center[0],n=e.center[1],r=e.radius,a=new eh(i,n,r,r,e.startAngle,e.endAngle,!1,0).getPoints(30).map(l=>new R(l.x,l.y,0));let o=[];for(let l=0;l{l[0]=l[0]-t[0],l[1]=l[1]-t[1]}),o}getMatrix(e,t,i){const n=new R(e[0],e[1],e[2]),r=new Fi(0,0,i),a=new R(t[0],t[1],t[2]),o=new Kt;o.setFromEuler(r);const l=new qe;return l.compose(n,o,a),l}getData(){return this.data}getEntitiesByLayer(e){return this.data?this.data.entities.filter(t=>t.layer===e):[]}getLayers(){return this.data?this.data.layers:[]}clear(){this.data=null}dispose(){this.clear()}}class YF{engine;sectionPlaneGroup=null;loaderModule2d;constructor(e){this.engine=e,this.loaderModule2d=new M2(this.engine)}async attachSectionPlane(e,t,i,n){await this.loaderModule2d.loadModel(e+"/"+t,{chunkSize:1e3,enableChunkedLoading:!0,enableValidation:!0});let r=new R(i.x,i.y,i.z),a=new R(n.x,n.y,n.z);const o=new R().copy(a);let l=r.clone().sub(this.engine.modelGroup.position.clone()).dot(a);this.engine.modelGroup.lookAt(o);let c=this.engine.modelGroup.position.clone().add(a.setLength(l));this.engine.modelGroup.position.set(c.x,c.y,c.z),console.log("绘制完成")}removeSectionPlane(){this.engine.scene.remove(this.engine.modelGroup)}getMatrix(e,t){const i=new R(e.x,e.y,e.z),n=new Fi(t.x,t.y,t.z),r=new R(1,1,1),a=new Kt;a.setFromEuler(n);const o=new qe;return o.compose(i,a,r),o}computeMatrixFromOriginAndDirection(e,t){const i=new qe,n=t.clone().normalize();if(n.length()===0)return console.warn("方向向量长度为零,返回单位矩阵"),i.identity();const r=new R(0,1,0);let a=new R().crossVectors(r,n);if(a.length()<1e-4){const c=new R(0,0,1);a=new R().crossVectors(c,n).normalize()}else a.normalize();const o=new R().crossVectors(a,n).normalize(),l=new qe;return l.set(a.x,n.x,o.x,0,a.y,n.y,o.y,0,a.z,n.z,o.z,0,0,0,0,1),l.setPosition(e),l}}class $F{options;deviceType;animationId=null;isRenderingPaused=!1;controlsEnabledBeforePause=!0;animate;onWindowResize;_fpsFrameCount=0;_fpsLastCheck=0;_fpsLastSwitch=0;_lowFpsCount=0;_highFpsCount=0;_fpsCheckInterval=100;_fpsSwitchCooldown=100;_fpsThreshold=30;_fpsUpgradeThreshold=60;_lowFpsRequired=5;_highFpsRequired=.1;isMouseDown=!1;isWheeling=!1;scene;camera;renderer;sceneModule;cameraModule;deviceModule;renderModule;controlModule;composerModule;loaderModule;engineStatus;events;lightModule;interactionModule;modelToolModule;worldToScreen;handelBehaved;octreeBox;controls;stats;catchSvg;engineModelModule;viewTree;merge2d;viewCube;rangeScale;setting;measure;clipping;modelTree;engineInfo;modelProperties;modelMapperBatch;modelEdge;ai;pathRoaming;hoverHighLight;minMap;grid;level;issueReport;text;hdr;ground;skyManager;linkElement2d3d;linkView2d3d;oneClickEncoding;models=[];reactBoundingClientRect={left:0,top:0};version="3.4.7";versionEl=null;container;constructor(e){if(window.THREE=Z5,this.options=e,this.container=document.getElementById(e.containerId),!this.container)throw new Error(`Container ${e.containerId} not found`);if(this.engineModelModule=new FU(this),this.engineModelModule.init(),this.ai=new SF(this),this.deviceModule=new $5(this),this.deviceType=this.deviceModule.getDeviceType(),this.cameraModule=new Jr(this),this.sceneModule=new Y5(this),this.scene=this.sceneModule.scene,this.renderModule=new o8(this),this.renderer=this.renderModule.createRenderer(),this.camera=this.cameraModule.orthographicCamera,this.scene.camera=this.camera,this.renderer){const r=this.renderer;r.interactionCullingEnabled=!0,r.interactionActive=!1,r.interactionRenderScene=this.scene,r.interactionFrameBudgetMs=this.options.interactionFrameBudgetMs??6,r.interactionSkipShadows=this.options.interactionSkipShadows??!0}this.controlModule=new C8(this),this.controlModule.switchDefaultMode(),this.controls=this.controlModule.orbitControls,this.clipping=new gF(this),this.clipping.init(),this.composerModule=new z8(this),this.composerModule.init(),this.events=new LU,this.engineStatus=new IU(this),this.engineStatus.init(),this.loaderModule=new RU(this),this.lightModule=new DU(this),this.lightModule.init(),this.viewCube=new hB(this),this.viewCube.init(),this.options.showViewCube==!1&&this.viewCube.hide(),this.octreeBox=dB(this),this.rangeScale=new uB(this),this.rangeScale.init(),this.setting=new pB(this),this.engineModelModule.init(),this.handelBehaved=Yv(this),this.modelMapperBatch=new _F(this),this.measure=new MB(this),this.modelToolModule=new kU(this),this.modelProperties=new xF(this),this.interactionModule=new NU(this),this.interactionModule.init(),this.interactionModule.active(),this.hoverHighLight=new jf(this),this.modelEdge=new bF(this),this.modelTree=new vF(this),this.viewTree=new HF(this),this.merge2d=new YF(this),this.engineInfo=new yF(this),this.pathRoaming=new wF(this),this.pathRoaming.init(),this.oneClickEncoding=new zF(this),this.minMap=new EF(this),this.linkElement2d3d=new BF(this),this.linkView2d3d=new FF(this),this.grid=new AF(this),this.level=new IF(this),this.issueReport=new LF(this),this.text=new DF(this),this.hdr=new NF(this),this.ground=new sy(this),this.ground.init(),this.skyManager=new UF(this),this.setting.init(),this.worldToScreen=new zt(this.camera,this.renderer,this.scene),this.options.showStats&&(this.stats=new GU,this.stats.showPanel(0),this.stats.dom.style.position="absolute",this.stats.dom.style.top="0px",this.stats.dom.style.left="0px",this.stats.dom.style.zIndex="1000",this.container.appendChild(this.stats.dom));let t=document.createElement("div");t.className="versionText",this.versionEl=t,this.updateVersionDisplay(),this.container.appendChild(t);let i=document.createElementNS("http://www.w3.org/2000/svg","svg");i.style.position="absolute",i.style.zIndex="1000",i.style.left="0px",i.style.top="0px",i.style.pointerEvents="none",this.container.appendChild(i),this.catchSvg=i,this.onWindowResize=()=>{this.handleWindowResize()},window.addEventListener("resize",this.onWindowResize);let n=this;this.controls.addEventListener("start",()=>{n.renderer&&(n.renderer.interactionActive=!0),n.events.trigger(tc.EngineBusy),n.container&&(n.container.style.cursor="none")}),this.controls.addEventListener("end",()=>{n.renderer&&(n.renderer.interactionActive=!1),n.events.trigger(tc.EngineFree),n.container&&(n.container.style.cursor="default")}),this.controls.addEventListener("change",()=>{const r=new R;n.camera.getWorldDirection(r);const a=Math.atan2(r.x,-r.z);let o=new CustomEvent("D3ViewUpdate",{detail:{position:n.camera.position,rotation:a,type:n.camera.type}});window.dispatchEvent(o)}),this.animate=()=>{if(!this.isRenderingPaused)this.animationId=requestAnimationFrame(this.animate);else{this.animationId=null;return}this.stats&&this.stats.begin(),this.composerModule&&this.composerModule.composer.render(),this.viewCube&&this.viewCube.cubeTool.RenderScene(),this.measure.update(),this.ground.update(),this.skyManager.update(),this.hoverHighLight.update(),this.controlModule.update(),this.minMap.update(),this.grid.update(),this.level.update(),this.text&&this.text.update(),this.stats&&this.stats.end(),this._fpsFrameCount++;const r=performance.now();if(r-this._fpsLastCheck>=this._fpsCheckInterval){const a=r-this._fpsLastCheck,o=this._fpsFrameCount/a*1e3;this._fpsFrameCount=0,this._fpsLastCheck=r,o=this._lowFpsRequired&&r-this._fpsLastSwitch>this._fpsSwitchCooldown&&(this._adaptiveRenderingDowngrade(),this._fpsLastSwitch=r,this._lowFpsCount=0)):o>this._fpsUpgradeThreshold?(this._highFpsCount++,this._lowFpsCount=0):(this._lowFpsCount=0,this._highFpsCount=0)}if(this.scene){let a=this.scene?.dirLight;a&&this.camera&&this.updateLightPosition(this.camera,a)}},this.animate()}updateVersionDisplay(){if(!this.versionEl)return;const e={simple:"simple",balance:"balance",advanced:"advanced"},t=this.engineModelModule?.getCurrentMode()??"",i=e[t]??t;this.versionEl.innerHTML=`v${this.version} | ${i}`}updateLightPosition(e,t){const i=new R;e.getWorldDirection(i);const n=100,r=new R().copy(i).multiplyScalar(-n),a=new R(0,1,0),o=new R().crossVectors(i,a).normalize();r.addScaledVector(a,n*.5),r.addScaledVector(o,n*.3),t.position.copy(e.position).add(r);const l=new R().copy(e.position).add(i.multiplyScalar(20));t.target.position.copy(l),t.target.updateMatrixWorld()}_adaptiveRenderingDowngrade(){const e=["simple","balance","advanced"],t=this.engineModelModule.getCurrentMode(),i=e.indexOf(t);if(i>0){const n=e[i-1];console.log(`[AdaptiveRendering] FPS低于${this._fpsThreshold},自动降级: ${t} → ${n}`),this.engineModelModule.autoSwitch(n)}}_adaptiveRenderingUpgrade(){const e=["simple","balance","advanced"],t=this.engineModelModule.getCurrentMode(),i=e.indexOf(t);if(i{e.dispose&&e.dispose()}),this.composerModule.composer.renderTarget1&&this.composerModule.composer.renderTarget1.dispose(),this.composerModule.composer.renderTarget2&&this.composerModule.composer.renderTarget2.dispose())}catch(e){console.warn("[BimEngine] Error disposing composer:",e)}try{this.renderModule&&this.renderModule.disposeRenderer(),this.renderer&&(this.renderer.domElement&&this.renderer.domElement.parentElement&&this.renderer.domElement.parentElement.removeChild(this.renderer.domElement),this.renderer.dispose(),this.renderer.forceContextLoss())}catch(e){console.warn("[BimEngine] Error disposing renderer:",e)}try{this.stats&&this.stats.dom&&this.stats.dom.parentElement&&this.stats.dom.parentElement.removeChild(this.stats.dom),this.catchSvg&&this.catchSvg.parentElement&&this.catchSvg.parentElement.removeChild(this.catchSvg)}catch(e){console.warn("[BimEngine] Error disposing DOM elements:",e)}try{this.events&&this.events.listeners&&this.events.listeners.clear()}catch(e){console.warn("[BimEngine] Error clearing event listeners:",e)}this.scene=null,this.camera=null,this.renderer=null,this.controls=null,this.models=[],this.container=null,console.log("[BimEngine] Engine disposal completed")}clearScene(e){e&&([...e.children].forEach(t=>{this.clearScene(t)}),e.parent&&e.parent.remove(e),e instanceof ht&&(e.geometry&&e.geometry.dispose(),e.material&&(Array.isArray(e.material)?e.material.forEach(t=>this.disposeMaterial(t)):this.disposeMaterial(e.material))),e instanceof pn&&(e.geometry&&e.geometry.dispose(),e.material&&this.disposeMaterial(e.material)),e instanceof tp&&(e.geometry&&e.geometry.dispose(),e.material&&this.disposeMaterial(e.material)),e instanceof ti&&(e.geometry&&e.geometry.dispose(),e.material&&(Array.isArray(e.material)?e.material.forEach(t=>this.disposeMaterial(t)):this.disposeMaterial(e.material)),e.instanceMatrix&&(e.instanceMatrix=null),e.instanceColor&&(e.instanceColor=null)),e instanceof Xc&&e.material&&this.disposeMaterial(e.material))}disposeMaterial(e){e&&(["map","lightMap","bumpMap","normalMap","specularMap","envMap","alphaMap","aoMap","displacementMap","emissiveMap","gradientMap","metalnessMap","roughnessMap","clearcoatMap","clearcoatNormalMap","clearcoatRoughnessMap","transmissionMap","thicknessMap","sheenColorMap","sheenRoughnessMap","specularIntensityMap","specularColorMap","iridescenceMap","iridescenceThicknessMap"].forEach(t=>{const i=e[t];i&&i instanceof ei&&i.dispose()}),e.dispose())}}const KF=` varying vec2 vWorldPos; void main() { vec4 worldPosition = modelMatrix * vec4(position, 1.0); vWorldPos = worldPosition.xy; gl_Position = projectionMatrix * viewMatrix * worldPosition; } `,JF=` precision highp float; varying vec2 vWorldPos; uniform float minorSpacing; uniform float majorStep; uniform vec2 worldPerPixel; uniform float minorThicknessPx; uniform float majorThicknessPx; uniform vec3 minorColor; uniform vec3 majorColor; uniform float minorOpacity; uniform float majorOpacity; float distanceToGridLine(float coord, float spacing) { float halfSpacing = spacing * 0.5; float wrapped = mod(coord + halfSpacing, spacing) - halfSpacing; return abs(wrapped); } void main() { float spacing = max(minorSpacing, 1e-6); float stepMultiplier = max(majorStep, 1.0); float majorSpacing = spacing * stepMultiplier; float distMinorX = distanceToGridLine(vWorldPos.x, spacing); float distMinorY = distanceToGridLine(vWorldPos.y, spacing); float distMajorX = distanceToGridLine(vWorldPos.x, majorSpacing); float distMajorY = distanceToGridLine(vWorldPos.y, majorSpacing); float minorThicknessX = max(worldPerPixel.x * minorThicknessPx, 1e-7); float minorThicknessY = max(worldPerPixel.y * minorThicknessPx, 1e-7); float majorThicknessX = max(worldPerPixel.x * majorThicknessPx, 1e-7); float majorThicknessY = max(worldPerPixel.y * majorThicknessPx, 1e-7); float minorMaskX = 1.0 - smoothstep(minorThicknessX, minorThicknessX * 1.5, distMinorX); float minorMaskY = 1.0 - smoothstep(minorThicknessY, minorThicknessY * 1.5, distMinorY); float majorMaskX = 1.0 - smoothstep(majorThicknessX, majorThicknessX * 1.5, distMajorX); float majorMaskY = 1.0 - smoothstep(majorThicknessY, majorThicknessY * 1.5, distMajorY); float majorMask = clamp(max(majorMaskX, majorMaskY), 0.0, 1.0); float minorMask = clamp(max(minorMaskX, minorMaskY), 0.0, 1.0); minorMask *= (1.0 - majorMask); // Prevent overlap so bold lines dominate. vec3 color = minorColor * minorMask * minorOpacity + majorColor * majorMask * majorOpacity; float alpha = minorMask * minorOpacity + majorMask * majorOpacity; alpha = clamp(alpha, 0.0, 1.0); if (alpha <= 1e-4) { discard; } gl_FragColor = vec4(color, alpha); } `;class QF{scene;camera;container;gridGroup;gridGeometry;gridMaterial;gridMesh;animationFrameId=null;resizeObserver;windowResizeHandler;lastState={zoom:-1,centerX:Number.NaN,centerY:Number.NaN,viewWidth:0,viewHeight:0,containerWidth:0,containerHeight:0,minorSpacing:0};largeGridColor=6052956;smallGridColor=3815994;desiredMinorPixelSize=28;coverageMultiplier=1.6;minSpacing=1e-4;minorThicknessPx=.4;majorThicknessPx=.6;minorLineOpacity=.05;majorLineOpacity=.2;baseRenderOrder=-20;gridZOffset=-.001;majorStep=5;gridUniforms={minorSpacing:{value:100},majorStep:{value:this.majorStep},worldPerPixel:{value:new me(1,1)},minorThicknessPx:{value:this.minorThicknessPx},majorThicknessPx:{value:this.majorThicknessPx},minorColor:{value:new We(this.smallGridColor)},majorColor:{value:new We(this.largeGridColor)},minorOpacity:{value:this.minorLineOpacity},majorOpacity:{value:this.majorLineOpacity}};constructor(e,t,i){this.scene=e,this.camera=t,this.container=i,this.gridGroup=new pi,this.gridGroup.name="AdaptiveGridGroup",this.gridGroup.renderOrder=this.baseRenderOrder,this.gridGroup.visible=!0,this.gridGroup.position.set(0,0,this.gridZOffset),this.scene.add(this.gridGroup),this.createGridMesh(),this.updateGrid(!0),this.startMonitoring(),this.setupResizeObserver()}createGridMesh(){this.gridGeometry=new vs(1,1,1,1),this.gridMaterial=new Jt({uniforms:this.gridUniforms,vertexShader:KF,fragmentShader:JF,transparent:!0,depthWrite:!1,depthTest:!1,side:Ot,toneMapped:!1}),this.gridMesh=new ht(this.gridGeometry,this.gridMaterial),this.gridMesh.frustumCulled=!1,this.gridMesh.renderOrder=this.baseRenderOrder,this.gridGroup.add(this.gridMesh)}startMonitoring(){const e=()=>{this.updateGrid(),this.animationFrameId=requestAnimationFrame(e)};e()}stopMonitoring(){this.animationFrameId!==null&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=null)}setupResizeObserver(){typeof ResizeObserver<"u"?(this.resizeObserver=new ResizeObserver(()=>this.updateGrid(!0)),this.resizeObserver.observe(this.container)):(this.windowResizeHandler=()=>this.updateGrid(!0),window.addEventListener("resize",this.windowResizeHandler))}teardownResizeObserver(){this.resizeObserver&&(this.resizeObserver.disconnect(),this.resizeObserver=void 0),this.windowResizeHandler&&(window.removeEventListener("resize",this.windowResizeHandler),this.windowResizeHandler=void 0)}normalizeSpacing(e){const t=Math.max(e,this.minSpacing),i=Math.floor(Math.log10(t)),n=Math.pow(10,i),r=[1,2,5,10];for(const a of r){const o=a*n;if(t<=o)return o}return 10*n}updateGrid(e=!1){if(!this.gridMesh)return;const t=Math.max(1,this.container.clientWidth),i=Math.max(1,this.container.clientHeight),n=this.camera.zoom,r=this.camera.right-this.camera.left,a=this.camera.top-this.camera.bottom,o=Math.max(this.minSpacing,r/n),l=Math.max(this.minSpacing,a/n),c=this.camera.position.x,h=this.camera.position.y,d=o/t,p=l/i,u=d*this.desiredMinorPixelSize,v=this.normalizeSpacing(u),g=this.lastState;if(!e){const y=Math.abs(n-g.zoom)/Math.max(1e-4,g.zoom||1)>.02,x=Math.abs(v-g.minorSpacing)>g.minorSpacing*.05,_=Math.abs(c-g.centerX)>Math.max(v*.5,.01),S=Math.abs(h-g.centerY)>Math.max(v*.5,.01),b=Math.abs(o-g.viewWidth)>g.viewWidth*.01,E=Math.abs(l-g.viewHeight)>g.viewHeight*.01,w=t!==g.containerWidth||i!==g.containerHeight;if(!(y||x||_||S||b||E||w))return}const m=o*this.coverageMultiplier,f=l*this.coverageMultiplier;this.gridMesh.scale.set(m,f,1),this.gridMesh.position.set(c,h,0),this.gridUniforms.minorSpacing.value=v,this.gridUniforms.worldPerPixel.value.set(d,p),this.lastState={zoom:n,centerX:c,centerY:h,viewWidth:o,viewHeight:l,containerWidth:t,containerHeight:i,minorSpacing:v}}setVisible(e){this.gridGroup.visible=e}setColors(e,t){this.largeGridColor=e,this.smallGridColor=t,this.gridUniforms.majorColor.value.setHex(e),this.gridUniforms.minorColor.value.setHex(t)}setOpacity(e,t){this.minorLineOpacity=Math.max(0,Math.min(1,e)),this.majorLineOpacity=Math.max(0,Math.min(1,t)),this.gridUniforms.minorOpacity.value=this.minorLineOpacity,this.gridUniforms.majorOpacity.value=this.majorLineOpacity}dispose(){this.stopMonitoring(),this.teardownResizeObserver(),this.gridMesh&&this.gridGroup.remove(this.gridMesh),this.gridGeometry&&(this.gridGeometry.dispose(),this.gridGeometry=void 0),this.gridMaterial&&(this.gridMaterial.dispose(),this.gridMaterial=void 0),this.gridMesh=void 0}}class ez{engine;scene;options;adaptiveGrid;axesHelper;constructor(e,t){this.engine=e,this.options=t,this.scene=this.createScene(),this.initHelpers()}createScene(){const e=new Ia,t=this.options.backgroundColor??1710618;return e.background=new We(t),e.is2D=!0,e}initHelpers(){this.options.axesEnabled&&this.createAxes()}initGrid(){this.options.gridEnabled&&this.createGrid()}createGrid(e=1e3,t=50){this.adaptiveGrid&&(this.adaptiveGrid.dispose(),this.adaptiveGrid=void 0),this.adaptiveGrid=new QF(this.scene,this.engine.cameraModule2d.orthographicCamera,this.engine.renderModule2d.container);const i=this.options.backgroundColor??1710618;this.updateGridColorsByBackground(i)}createAxes(e=100){this.axesHelper&&this.scene.remove(this.axesHelper),this.axesHelper=new K_(e),this.axesHelper.rotation.z=0,this.scene.add(this.axesHelper),this.scene.remove(this.axesHelper),this.scene.add(this.axesHelper),this.axesHelper.renderOrder=999}setBackgroundColor(e){this.scene.background=new We(e),this.updateGridColorsByBackground(e)}updateGridColorsByBackground(e){if(!this.adaptiveGrid)return;const t=new We(e);.299*t.r+.587*t.g+.114*t.b<.5?(this.adaptiveGrid.setColors(16777215,16777215),this.adaptiveGrid.setOpacity(.2,.3)):(this.adaptiveGrid.setColors(0,0),this.adaptiveGrid.setOpacity(.05,.2))}addObject(e){this.scene.add(e)}removeObject(e){this.scene.remove(e),e instanceof ht&&(e.geometry.dispose(),Array.isArray(e.material)?e.material.forEach(t=>t.dispose()):e.material.dispose())}clearScene(){for(let e=this.scene.children.length-1;e>=0;e--){const t=this.scene.children[e];t!==this.axesHelper&&(this.adaptiveGrid||this.removeObject(t))}this.engine.events&&this.engine.events.trigger("scene-cleared")}getObjects(e=!1){const t=[];return this.scene.children.forEach(i=>{(e||i!==this.axesHelper)&&t.push(i)}),t}getSceneStats(){let e=0,t=0,i=0;return this.scene.children.forEach(n=>{n instanceof ht?e++:n instanceof pn?t++:n instanceof pi&&i++}),{objectCount:this.scene.children.length,meshCount:e,lineCount:t,groupCount:i}}setGridVisible(e){this.adaptiveGrid&&this.adaptiveGrid.setVisible(e)}setAxesVisible(e){this.axesHelper&&(this.axesHelper.visible=e)}dispose(){this.clearScene(),this.adaptiveGrid&&(this.adaptiveGrid.dispose(),this.adaptiveGrid=void 0),this.axesHelper&&(this.scene.remove(this.axesHelper),this.axesHelper=void 0),this.scene.clear()}}class tz{engine;isFree;highlightModels;highlightHoverModels;hideModels;translucentModels;models;constructor(e){this.engine=e,this.isFree=!0,this.highlightModels=[],this.hideModels=[],this.translucentModels=[],this.highlightHoverModels=[],this.models=[]}}class iz{engine;orthographicCamera;container;frustumSize=1e3;near=.1;far=1e4;initialZoom=1;defaultPosition=new R(0,0,1e3);constructor(e,t){this.engine=e,this.container=t,this.orthographicCamera=this.createOrthographicCamera()}createOrthographicCamera(){const e=this.container.clientWidth/this.container.clientHeight,t=this.frustumSize/2,i=t*e,n=new rn(-i,i,t,-t,this.near,this.far);return n.position.copy(this.defaultPosition),n.lookAt(0,0,0),n.zoom=this.initialZoom,n.updateProjectionMatrix(),n}animationId=null;animationStartTime=0;animationDuration=800;animationStartState={};animationTargetState={};fitToExtents(e,t=1.2,i=!0,n=800){const r=new R(e.min[0],e.min[1]),a=new R(e.max[0],e.max[1]);if(!(r.distanceTo(a)>.001)){console.warn("[CameraModule2d] Invalid extents, using default view"),this.resetView();return}const o=new R;o.addVectors(r,a).multiplyScalar(.5);const l=new R;l.subVectors(a,r);const c=Math.max(l.x,l.y)*t,h=this.container.clientWidth/this.container.clientHeight,d=c/2,p=d*h,u=-p,v=p,g=d,m=-d,f=o.x,y=o.y,x=1;if(!i){this.orthographicCamera.left=u,this.orthographicCamera.right=v,this.orthographicCamera.top=g,this.orthographicCamera.bottom=m,this.orthographicCamera.position.set(f,y,this.defaultPosition.z),this.orthographicCamera.zoom=x,this.orthographicCamera.updateProjectionMatrix(),this.engine.controlModule2d?.panControls&&(this.engine.controlModule2d.panControls.setPosition(f,y),this.engine.controlModule2d.panControls.setZoom(x)),this.engine.events&&this.engine.events.trigger("camera-changed",{type:"fit-to-extents",center:o,size:l});return}this.animationId!==null&&(cancelAnimationFrame(this.animationId),this.animationId=null),this.animationStartState={left:this.orthographicCamera.left,right:this.orthographicCamera.right,top:this.orthographicCamera.top,bottom:this.orthographicCamera.bottom,x:this.orthographicCamera.position.x,y:this.orthographicCamera.position.y,zoom:this.orthographicCamera.zoom},this.animationTargetState={left:u,right:v,top:g,bottom:m,x:f,y,zoom:x},this.animationDuration=n,this.animationStartTime=performance.now(),this.animateFitToExtents(o,l)}easeOutCubic(e){return 1-Math.pow(1-e,3)}animateFitToExtents(e,t){const i=performance.now()-this.animationStartTime,n=Math.min(i/this.animationDuration,1),r=this.easeOutCubic(n),a=this.animationStartState,o=this.animationTargetState;this.orthographicCamera.left=this.lerp(a.left,o.left,r),this.orthographicCamera.right=this.lerp(a.right,o.right,r),this.orthographicCamera.top=this.lerp(a.top,o.top,r),this.orthographicCamera.bottom=this.lerp(a.bottom,o.bottom,r),this.orthographicCamera.position.x=this.lerp(a.x,o.x,r),this.orthographicCamera.position.y=this.lerp(a.y,o.y,r),this.orthographicCamera.zoom=this.lerp(a.zoom,o.zoom,r),this.orthographicCamera.updateProjectionMatrix(),this.engine.controlModule2d?.panControls&&(this.engine.controlModule2d.panControls.setPosition(this.orthographicCamera.position.x,this.orthographicCamera.position.y),this.engine.controlModule2d.panControls.setZoom(this.orthographicCamera.zoom)),this.engine.events&&this.engine.events.trigger("camera-changed",{type:"fit-to-extents",center:e,size:t,progress:r}),n<1?this.animationId=requestAnimationFrame(()=>this.animateFitToExtents(e,t)):this.animationId=null}lerp(e,t,i){return e+(t-e)*i}setZoom(e){this.orthographicCamera.zoom=e,this.orthographicCamera.updateProjectionMatrix(),this.engine.events&&this.engine.events.trigger("view-zoom-changed",{zoom:e})}getZoom(){return this.orthographicCamera.zoom}setPosition(e,t){this.orthographicCamera.position.set(e,t,this.defaultPosition.z),this.engine.events&&this.engine.events.trigger("view-pan-changed",{x:e,y:t})}getPosition(){return this.orthographicCamera.position.clone()}resetView(){this.orthographicCamera.position.copy(this.defaultPosition),this.orthographicCamera.zoom=this.initialZoom,this.orthographicCamera.updateProjectionMatrix(),this.engine.events&&this.engine.events.trigger("camera-reset")}getViewBounds(){const e=this.orthographicCamera,t=e.zoom,i=e.left/t,n=e.right/t,r=e.top/t,a=e.bottom/t,o=e.position.x,l=e.position.y;return{minX:o+i,maxX:o+n,minY:l+a,maxY:l+r,width:n-i,height:r-a}}screenToWorld(e,t){const i=new R(e/this.container.clientWidth*2-1,-(t/this.container.clientHeight)*2+1,.5);return i.unproject(this.orthographicCamera),i}worldToScreen(e,t){const i=new R(e,t,0);return i.project(this.orthographicCamera),{x:(i.x+1)/2*this.container.clientWidth,y:-(i.y-1)/2*this.container.clientHeight}}updateAspectRatio(){const e=this.container.clientWidth/this.container.clientHeight,t=this.frustumSize/2,i=t*e;this.orthographicCamera.left=-i,this.orthographicCamera.right=i,this.orthographicCamera.top=t,this.orthographicCamera.bottom=-t,this.orthographicCamera.updateProjectionMatrix()}setFrustumSize(e){this.frustumSize=e,this.updateAspectRatio()}getFrustumSize(){return this.frustumSize}dispose(){this.animationId!==null&&(cancelAnimationFrame(this.animationId),this.animationId=null),this.orthographicCamera=null}}class nz{engine;renderer;container;options;antialias=!0;alpha=!1;precision="highp";constructor(e,t,i){this.engine=e,this.container=t,this.options=i,this.renderer=this.createRenderer(),this.handleResize()}createRenderer(){const e=new mh({antialias:this.antialias,alpha:this.alpha,precision:this.precision}),t=this.container.clientWidth,i=this.container.clientHeight;return e.setSize(t,i),e.setPixelRatio(window.devicePixelRatio),e.autoClear=!0,e.sortObjects=!0,e.setClearColor(this.options.backgroundColor??1710618),this.container.appendChild(e.domElement),e}render(e,t){const i=performance.now();this.engine.events&&this.engine.events.trigger("render-start"),this.renderer.render(e,t);const n=performance.now()-i;this.engine.events&&this.engine.events.trigger("render-end",{renderTime:n})}handleResize(){window.addEventListener("resize",()=>{this.onWindowResize()})}onWindowResize(){const e=this.container.clientWidth,t=this.container.clientHeight;this.renderer.setSize(e,t),this.engine.cameraModule2d&&this.engine.cameraModule2d.updateAspectRatio(),this.engine.scene&&this.engine.camera&&this.render(this.engine.scene,this.engine.camera)}setSize(e,t){this.renderer.setSize(e,t),this.engine.cameraModule2d&&this.engine.cameraModule2d.updateAspectRatio()}getSize(){const e=this.renderer.getSize(new me);return{width:e.x,height:e.y}}setBackgroundColor(e){this.renderer.setClearColor(new We(e))}setPixelRatio(e){this.renderer.setPixelRatio(e)}getPixelRatio(){return this.renderer.getPixelRatio()}setAntialias(e){console.warn("Antialias cannot be changed after renderer creation")}clear(e=!0,t=!0,i=!1){this.renderer.clear(e,t,i)}getInfo(){const e=this.renderer.getContext();return{renderer:this.renderer.capabilities.isWebGL2?"WebGL 2.0":"WebGL 1.0",version:this.renderer.capabilities.getVersion(),vendor:this.renderer.capabilities.vendor,capabilities:{maxTextureSize:this.renderer.capabilities.maxTextureSize,maxRenderbufferSize:this.renderer.capabilities.maxRenderbufferSize,maxVertexAttribs:this.renderer.capabilities.maxVertexAttribs,maxVaryingVectors:e.getParameter(e.MAX_VARYING_VECTORS),maxFragmentUniforms:e.getParameter(e.MAX_FRAGMENT_UNIFORM_VECTORS),maxVertexUniforms:e.getParameter(e.MAX_VERTEX_UNIFORM_VECTORS)}}}dispose(){window.removeEventListener("resize",this.onWindowResize.bind(this)),this.renderer.dispose(),this.container.contains(this.renderer.domElement)&&this.container.removeChild(this.renderer.domElement),this.renderer=null}}class sz extends hs{object;domElement;enabled=!0;enableZoom=!0;enablePan=!0;enableDamping=!1;dampingFactor=.05;zoomSpeed=1;minZoom=0;maxZoom=1/0;isDragging=!1;mouseButton=-1;previousMousePosition=new me;targetPosition=new R;targetZoom=1;lastClickTime=0;doubleClickDelay=300;constructor(e,t){super(),this.object=e,this.domElement=t||document,this.targetPosition.copy(e.position),this.targetZoom=e.zoom,this.bindEvents()}bindEvents(){this.domElement.addEventListener("mousedown",this.onMouseDown.bind(this)),this.domElement.addEventListener("mousemove",this.onMouseMove.bind(this)),this.domElement.addEventListener("mouseup",this.onMouseUp.bind(this)),this.domElement.addEventListener("mouseleave",this.onMouseUp.bind(this)),this.domElement.addEventListener("wheel",this.onWheel.bind(this),{passive:!1}),this.domElement.addEventListener("dblclick",this.onDoubleClick.bind(this)),this.domElement.addEventListener("click",this.onClick.bind(this)),this.domElement.addEventListener("touchstart",this.onTouchStart.bind(this),{passive:!1}),this.domElement.addEventListener("touchmove",this.onTouchMove.bind(this),{passive:!1}),this.domElement.addEventListener("touchend",this.onTouchEnd.bind(this)),this.domElement.addEventListener("contextmenu",e=>{e.preventDefault()})}onMouseDown(e){this.enabled&&this.enablePan&&(e.button===0||e.button===1)&&(this.isDragging=!0,this.mouseButton=e.button,this.previousMousePosition.set(e.clientX,e.clientY),this.dispatchEvent({type:"start"}))}onMouseMove(e){if(!this.enabled||!this.isDragging)return;const t=e.clientX-this.previousMousePosition.x,i=e.clientY-this.previousMousePosition.y,n=1/this.object.zoom,r=this.object.top-this.object.bottom,a=this.object.right-this.object.left,o=t/this.domElement.clientWidth*a*n,l=i/this.domElement.clientHeight*r*n;this.targetPosition.x-=o,this.targetPosition.y+=l,this.enableDamping||(this.object.position.copy(this.targetPosition),this.object.updateProjectionMatrix()),this.previousMousePosition.set(e.clientX,e.clientY),this.dispatchEvent({type:"change"})}onMouseUp(e){this.isDragging&&(this.isDragging=!1,this.mouseButton=-1,this.dispatchEvent({type:"end"}))}onWheel(e){if(!this.enabled||!this.enableZoom)return;e.preventDefault();const t=Math.pow(1.1,-Math.sign(e.deltaY)*this.zoomSpeed),i=this.targetZoom;this.targetZoom*=t,this.minZoom>0&&(this.targetZoom=Math.max(this.minZoom,this.targetZoom)),this.maxZoom!==1/0&&(this.targetZoom=Math.min(this.targetZoom,this.maxZoom));const n=this.targetZoom,r=(this.object.right-this.object.left)/2,a=(this.object.top-this.object.bottom)/2,o=this.domElement.getBoundingClientRect(),l=(e.clientX-o.left)/o.width*2-1,c=-((e.clientY-o.top)/o.height)*2+1;this.targetPosition.x+=l*r*(1/i-1/n),this.targetPosition.y+=c*a*(1/i-1/n),this.enableDamping||(this.object.zoom=n,this.object.position.copy(this.targetPosition),this.object.updateProjectionMatrix()),this.dispatchEvent({type:"change"})}onDoubleClick(e){this.enabled&&this.dispatchEvent({type:"doubleClick",event:e})}onClick(e){const t=performance.now();t-this.lastClickTime0&&(this.targetZoom=Math.max(this.minZoom,this.targetZoom)),this.maxZoom!==1/0&&(this.targetZoom=Math.min(this.targetZoom,this.maxZoom)),this.enableDamping||(this.object.zoom=this.targetZoom,this.object.updateProjectionMatrix()),this.dispatchEvent({type:"change"})}dispose(){this.enabled=!1,this.domElement.removeEventListener("mousedown",this.onMouseDown.bind(this)),this.domElement.removeEventListener("mousemove",this.onMouseMove.bind(this)),this.domElement.removeEventListener("mouseup",this.onMouseUp.bind(this)),this.domElement.removeEventListener("mouseleave",this.onMouseUp.bind(this)),this.domElement.removeEventListener("wheel",this.onWheel.bind(this)),this.domElement.removeEventListener("dblclick",this.onDoubleClick.bind(this)),this.domElement.removeEventListener("click",this.onClick.bind(this)),this.domElement.removeEventListener("touchstart",this.onTouchStart.bind(this)),this.domElement.removeEventListener("touchmove",this.onTouchMove.bind(this)),this.domElement.removeEventListener("touchend",this.onTouchEnd.bind(this))}}class rz{engine;panControls;isActive=!0;constructor(e){this.engine=e,this.panControls=this.createPanControls(),this.init()}init(){this.panControls.addEventListener("doubleClick",this.onDoubleClick.bind(this)),this.panControls.addEventListener("change",this.onChange.bind(this))}createPanControls(){const e=new sz(this.engine.camera,this.engine.renderer.domElement);return e.enableZoom=!0,e.enablePan=!0,e.enableDamping=!0,e.dampingFactor=.05,e.zoomSpeed=1,e.minZoom=0,e.maxZoom=1/0,e}onDoubleClick(e){this.engine.cameraModule2d&&this.engine.cameraModule2d.resetView()}onChange(){this.engine.events&&this.engine.events.trigger("camera-changed",{type:"user-interaction"})}active(){this.isActive=!0,this.panControls.enabled=!0}disActive(){this.isActive=!1,this.panControls.enabled=!1}update(){this.isActive&&this.panControls.update()}reset(){this.panControls.reset()}setPosition(e,t){this.panControls.setPosition(e,t)}setZoom(e){this.panControls.setZoom(e)}getZoom(){return this.panControls.object.zoom}setEnableZoom(e){this.panControls.enableZoom=e}setEnablePan(e){this.panControls.enablePan=e}setEnableDamping(e){this.panControls.enableDamping=e}setDampingFactor(e){this.panControls.dampingFactor=Math.max(0,Math.min(e,1))}setZoomSpeed(e){this.panControls.zoomSpeed=Math.max(.1,e)}setZoomLimits(e,t){this.panControls.minZoom=e,this.panControls.maxZoom=t}dispose(){this.panControls.dispose(),this.panControls=null}}class az{engine;pickBoxElementIds=[];worldToScreen;constructor(e){this.engine=e,this.pickBoxElementIds=[],this.worldToScreen=new zt(e.camera,e.renderer,e.scene)}init(){this.pickBoxElementIds=[]}pick2d(e,t){let i=[],n=new me(t.offsetX,t.offsetY);this.init(),this.RecurrentIteration(e,this.engine.dwgData.octree);let r=[];this.pickBoxElementIds.forEach(l=>{this.engine.loaderModule2d.model.nodeMap.get(l).forEach(c=>{if(c!=null){let d=this.engine.modelGroup.children[c.indexes[0]];if(d!=null)if(d instanceof fi){let p=new vt(c.min,c.max),u=e.ray.intersectsBox(p);if(u!=null&&u!=!1){var h=this.engine.modelGroup.children[c.indexes[0]].clonePoints.slice(c.indexes[1],c.indexes[2]);let v=[],g=[];for(let f=0;ff[0].distanceTo(f[1])>.001);let m=[];v.forEach(f=>{let y=this.worldToScreen.worldToScreen(f);m.push(y)});for(let f=0;ff[0].distanceTo(f[1])>1),g=g.filter(f=>o(n,f[0],f[1])<10),g.length>0&&g.forEach(f=>{r.push({distance:o(n,f[0],f[1]),linkId:l})})}}else{let p=d.geometrys[c.indexes[1]];const u=new Dt;let v=new ht(p,u);v.linkId=l,i.push(v)}}})});const a=e.intersectObjects(i,!0);if(a.length>0)return a[0].object.linkId;if(r.length>0)return r[0].linkId;return null;function o(l,c,h){const d=new me().subVectors(h,c),p=d.lengthSq();if(p<1e-10)return l.distanceTo(c);const u=new me().subVectors(l,c),v=Lt.clamp(u.dot(d)/p,0,1),g=new me().copy(d).multiplyScalar(v).add(c);return l.distanceTo(g)}}RecurrentIteration(e,t){if(t==null)return;let i=new R(t.min.X,t.min.Y,0),n=new R(t.max.X,t.max.Y,0),r=new R(Math.min(i.x,n.x),Math.min(i.y,n.y),Math.min(i.z,n.z)),a=new R(Math.max(n.x,i.x),Math.max(n.y,i.y),Math.max(n.z,i.z)),o=new vt(r,a),l=e.ray.intersectsBox(o);if(!(l==null||l==!1))if(t.children==null||t.children.length==0){if(t.elements!=null)for(var c of t.elements){let h=this.engine.engineStatus2d.hideModels;h!=null&&h.includes(c)||(h=this.engine.engineStatus2d.highlightModels,!(h!=null&&h.includes(c))&&this.pickBoxElementIds.push(c))}}else{if(t.elements!=null)for(var c of t.elements){let d=this.engine.engineStatus2d.hideModels;d!=null&&d.includes(c)||(d=this.engine.engineStatus2d.highlightModels,!(d!=null&&d.includes(c))&&this.pickBoxElementIds.push(c))}for(let h of t.children)this.RecurrentIteration(e,h)}}}class oz{engine;widgetContainer=null;widgetCanvas=null;widgetCtx=null;widgetSize=50;isDragging=!1;isRotating=!1;lastMouseX=0;lastMouseY=0;widgetX=this.widgetSize/2+5;widgetY=this.widgetSize/2+5;widgetRotation=0;rotationStartAngle=null;widgetRotationStart=0;worldToScreen;currentWordPosition=null;currentWordRotation=null;lastCameraWorldPosition=null;enabled=!0;constructor(e){this.engine=e,this.worldToScreen=new zt(e.camera,e.renderer,e.scene),this.initWidget(),this.active();let t=this;this.engine.controlModule2d.panControls.addEventListener("change",()=>{t.updateViewPoint()})}toggle(){return this.enabled=!this.enabled,this.enabled?(this.active(),this.widgetContainer&&(this.widgetContainer.style.display="block")):(this.disActive(),this.widgetContainer&&(this.widgetContainer.style.display="none")),this.enabled}isEnabled(){return this.enabled}initWidget(){const e=window.devicePixelRatio||1;this.widgetContainer=document.createElement("div"),this.widgetContainer.className="MapController",this.widgetContainer.style.position="absolute",this.widgetContainer.style.width=`${this.widgetSize}px`,this.widgetContainer.style.height=`${this.widgetSize}px`,this.widgetContainer.style.border="2px solid rgba(255, 255, 255, 0.4)",this.widgetContainer.style.borderRadius="50%",this.widgetContainer.style.overflow="hidden",this.widgetContainer.style.backgroundColor="rgba(26, 26, 46, 0.85)",this.widgetContainer.style.cursor="crosshair",this.widgetContainer.style.userSelect="none",this.widgetContainer.style.pointerEvents="auto",this.syncWidgetPosition(),this.widgetCanvas=document.createElement("canvas"),this.widgetContainer.className="MapController",this.widgetCanvas.width=this.widgetSize*e,this.widgetCanvas.height=this.widgetSize*e,this.widgetCanvas.style.position="absolute",this.widgetCanvas.style.top="0",this.widgetCanvas.style.left="0",this.widgetCanvas.style.width=`${this.widgetSize}px`,this.widgetCanvas.style.height=`${this.widgetSize}px`,this.widgetCanvas.style.pointerEvents="auto",this.widgetContainer.style.zIndex="1000",this.widgetContainer.appendChild(this.widgetCanvas),this.widgetCtx=this.widgetCanvas.getContext("2d"),this.widgetCtx&&this.widgetCtx.scale(e,e),this.setupWidgetEvents(),this.engine.container&&this.engine.container.appendChild(this.widgetContainer),this.drawWidget()}setupWidgetEvents(){this.widgetContainer&&(this.widgetContainer.addEventListener("mousedown",this.onWidgetCanvasMouseDown),this.widgetCanvas&&this.widgetCanvas.addEventListener("mousedown",this.onWidgetCanvasMouseDown),window.addEventListener("mousemove",this.onWidgetMouseMove),window.addEventListener("mouseup",this.onWidgetMouseUp),this.widgetContainer.addEventListener("contextmenu",e=>{e.preventDefault(),e.stopPropagation()}),this.widgetCanvas&&this.widgetCanvas.addEventListener("contextmenu",e=>{e.preventDefault(),e.stopPropagation()}))}onWidgetCanvasMouseDown=e=>{this.widgetContainer&&(e.button==0?(this.isDragging=!1,this.isRotating=!0):(this.isDragging=!0,this.isRotating=!1),this.captureRotationBaseline(e),this.lastMouseX=e.clientX,this.lastMouseY=e.clientY,this.widgetContainer&&(this.widgetContainer.style.cursor="alias"),e.preventDefault(),e.stopPropagation())};onWidgetMouseMove=e=>{if(!this.isDragging&&!this.isRotating)return;const t=e.clientX-this.lastMouseX,i=e.clientY-this.lastMouseY;if(this.isDragging)this.widgetX+=t,this.widgetY+=i,console.log(`[LinkView2d3d] 拖动位置更新: x=${this.widgetX.toFixed(0)}, y=${this.widgetY.toFixed(0)}`),this.syncWidgetPosition(),this.handleWidgetPositionControl();else if(this.isRotating){const n=this.calculatePointerAngle(e);if(n!==null){this.rotationStartAngle===null&&(this.rotationStartAngle=n,this.widgetRotationStart=this.widgetRotation);const r=n-this.rotationStartAngle;this.widgetRotation=this.widgetRotationStart+r,console.log(`[LinkView2d3d] 旋转角度更新: ${(this.widgetRotation*180/Math.PI).toFixed(1)}°`),this.drawWidget(),this.handleWidgetRotationControl()}}this.lastMouseX=e.clientX,this.lastMouseY=e.clientY};onWidgetMouseUp=()=>{this.isDragging&&console.log(`[LinkView2d3d] 拖动结束,最终位置: x=${this.widgetX.toFixed(0)}, y=${this.widgetY.toFixed(0)}`),this.isRotating&&console.log(`[LinkView2d3d] 旋转结束,最终角度: ${(this.widgetRotation*180/Math.PI).toFixed(1)}°`),this.isDragging=!1,this.isRotating=!1,this.rotationStartAngle=null,this.widgetContainer&&(this.widgetContainer.style.cursor="crosshair")};drawWidget(){const e=this.widgetCtx;if(!e)return;const t=this.widgetSize/2,i=this.widgetSize/2;e.clearRect(0,0,this.widgetSize,this.widgetSize),e.save(),e.translate(t,i),e.rotate(this.widgetRotation);const n=36,r=Math.PI/10,a=e.createRadialGradient(0,0,2,0,0,n);a.addColorStop(0,"rgba(0, 230, 130, 0.9)"),a.addColorStop(1,"rgba(0, 230, 130, 0)");const o=-Math.sin(r)*n,l=-Math.cos(r)*n,c=Math.sin(r)*n,h=-Math.cos(r)*n;e.beginPath(),e.moveTo(0,0),e.lineTo(o,l),e.lineTo(c,h),e.closePath(),e.fillStyle=a,e.fill(),e.fillStyle="rgba(255, 255, 255, 0.95)",e.strokeStyle="rgba(0, 200, 110, 0.9)",e.lineWidth=1.5,e.beginPath(),e.arc(0,0,4,0,Math.PI*2),e.fill(),e.stroke(),e.restore()}active(){window.addEventListener("D3ViewUpdate",this.listenViewUpdate)}disActive(){window.removeEventListener("D3ViewUpdate",this.listenViewUpdate)}disposeWidget(){this.widgetContainer&&this.widgetContainer.removeEventListener("mousedown",this.onWidgetMouseDown),this.widgetCanvas&&this.widgetCanvas.removeEventListener("mousedown",this.onWidgetCanvasMouseDown),window.removeEventListener("mousemove",this.onWidgetMouseMove),window.removeEventListener("mouseup",this.onWidgetMouseUp),this.widgetContainer?.remove(),this.widgetContainer=null,this.widgetCanvas=null,this.widgetCtx=null}listenViewUpdate=e=>{console.log("[LinkView2d3d] 收到视图更新事件",e),e=e.detail,e&&e.position&&(this.lastCameraWorldPosition=new R(e.position.x,e.position.y,e.position.z),this.currentWordPosition=new R(e.position.x,-e.position.z,0)),e&&typeof e.rotation=="number"&&(this.currentWordRotation=e.rotation),this.updateViewPoint()};updateViewPoint(){if(this.currentWordPosition){let e=this.worldToScreen.worldToScreen(this.currentWordPosition);this.widgetX=e.x,this.widgetY=e.y,this.syncWidgetPosition()}this.currentWordRotation!==null&&(this.widgetRotation=this.currentWordRotation,this.drawWidget())}syncWidgetPosition(){if(!this.widgetContainer)return;const e=this.widgetSize/2;this.widgetContainer.style.left=`${this.widgetX-e}px`,this.widgetContainer.style.top=`${this.widgetY-e}px`}handleWidgetPositionControl(){const e=this.getWidgetWorldPosition();e&&(this.currentWordPosition=e,this.dispatchViewControl("move",{position2d:e}))}handleWidgetRotationControl(){this.currentWordRotation=this.widgetRotation,this.dispatchViewControl("rotate",{rotation:this.widgetRotation})}getWidgetWorldPosition(){if(!this.engine?.cameraModule2d?.screenToWorld)return null;const e=this.engine.cameraModule2d.screenToWorld(this.widgetX,this.widgetY);return e?new R(e.x,e.y,0):null}dispatchViewControl(e,t){const i=!!t.position2d,n=typeof t.rotation=="number";if(!i&&!n)return;if(i&&!this.lastCameraWorldPosition){console.warn("[LinkView2d3d] 未获取到 3D 相机位置,暂不推送位置控制");return}const r={source:"LinkView2d3d",mode:e};if(t.position2d&&this.lastCameraWorldPosition){const a=this.lastCameraWorldPosition.y,o=-t.position2d.y;r.position={x:t.position2d.x,y:a,z:o},this.lastCameraWorldPosition=new R(t.position2d.x,a,o)}n&&(r.rotation=t.rotation),window.dispatchEvent(new CustomEvent("D2ViewControl",{detail:r}))}captureRotationBaseline(e){const t=this.calculatePointerAngle(e);if(t===null){this.rotationStartAngle=null;return}this.rotationStartAngle=t,this.widgetRotationStart=this.widgetRotation}calculatePointerAngle(e){if(!this.widgetContainer)return null;const t=this.widgetContainer.getBoundingClientRect(),i=t.left+t.width/2,n=t.top+t.height/2;return Math.atan2(e.clientX-i,n-e.clientY)}}class lz{engine;enabled=!0;constructor(e){this.engine=e,this.active()}toggle(){return this.enabled=!this.enabled,this.enabled?this.active():this.disActive(),this.enabled}isEnabled(){return this.enabled}active(){window.addEventListener("D3ElementClick",this.listenElementClick)}disActive(){window.removeEventListener("D3ElementClick",this.listenElementClick)}listenElementClick=e=>{let t=e.detail.id.toString();var i=this.engine.loaderModule2d.model.nodeMap.get(t);i!=null?(this.engine.modelToolModule2d.highlightModel([t]),this.engine.cameraModule2d.fitToExtents({min:[i[0].min.x,i[0].min.y],max:[i[0].max.x,i[0].max.y]},3)):this.engine.modelToolModule2d.unhighlightAllModels()}}class cz{engine;highlightMaterial;hideMaterial;translucentMaterial;constructor(e){this.engine=e,this.highlightMaterial=new Dt({color:43775,depthTest:!1,depthWrite:!1,transparent:!0,opacity:.5,side:Ot}),this.hideMaterial=new Dt({color:0,transparent:!0,opacity:0,side:Ot}),this.translucentMaterial=new Dt({color:16777215,depthTest:!1,depthWrite:!1,transparent:!0,opacity:.5,side:Ot}),this.highlightMaterial.clippingPlanes=this.engine.sectionPlane,this.hideMaterial.clippingPlanes=this.engine.sectionPlane,this.translucentMaterial.clippingPlanes=this.engine.sectionPlane}split_merge_model(e){if(e.isSplit||e instanceof ti)return;let t=e.materialClone.clone(),i=So(e.geometrys,!0);i.groups.forEach(n=>{n.materialIndex=0}),e.geometry=i,e.material=[t,this.highlightMaterial,this.translucentMaterial],e.needsUpdate=!0,e.isSplit=!0}un_split_merge_model(e){}highlightModelHover(e){this.engine.engineStatus2d.highlightHoverModels=e,this.unHighlightModelHover(),e.forEach(t=>{this.engine.loaderModule2d.model.nodeMap.get(t)?.forEach(n=>{if(n!=null&&n.indexes!=null)if(this.engine.modelGroup.children[n.indexes[0]]instanceof fi){var r=this.engine.modelGroup.children[n.indexes[0]].clonePoints.slice(n.indexes[1],n.indexes[2]);this.highLightRenderLineHover(r)}else{let a=new ht(this.engine.modelGroup.children[n.indexes[0]].geometrys[n.indexes[1]],this.translucentMaterial);a.name="HighLightHover",a.renderOrder=999,this.engine.modelGroup.add(a)}})})}unHighlightModelHover(){this.engine.engineStatus2d.highlightHoverModels=[],this.unhighLightRenderLineHover()}highlightModel(e){this.engine.engineStatus2d.highlightModels=e,e.forEach(t=>{this.engine.loaderModule2d.model.nodeMap.get(t)?.forEach(n=>{if(n!=null&&n.indexes!=null)if(this.engine.modelGroup.children[n.indexes[0]]instanceof fi){var r=this.engine.modelGroup.children[n.indexes[0]].clonePoints.slice(n.indexes[1],n.indexes[2]);this.highLightRenderLine(r)}else this.split_merge_model(this.engine.modelGroup.children[n.indexes[0]]),this.engine.modelGroup.children[n.indexes[0]].geometry.groups[n.indexes[1]].materialIndex=1})})}unhighlightModel(e){e.forEach(t=>{this.engine.loaderModule2d.model.nodeMap.get(t)?.forEach(n=>{n!=null&&n.indexes!=null&&(this.engine.modelGroup.children[n.indexes[0]]instanceof fi||(this.engine.modelGroup.children[n.indexes[0]].geometry.groups[n.indexes[1]].materialIndex=0))})}),this.unhighLightRenderLine()}unhighlightAllModels(e=!0){this.engine.engineStatus2d.highlightModels.forEach(t=>{this.unhighlightModel([t])}),e&&(this.engine.engineStatus2d.highlightModels=[])}hideModel(e){this.unhighlightAllModels(),e.forEach(t=>{this.engine.loaderModule2d.model.nodeMap.get(t)?.forEach(n=>{if(n!=null&&n.indexes!=null)if(this.engine.modelGroup.children[n.indexes[0]]instanceof fi){let r=this.engine.modelGroup.children[n.indexes[0]].geometry.attributes.position.array;for(let a=n.indexes[1];a{this.engine.loaderModule2d.model.nodeMap.get(t)?.forEach(n=>{if(n!=null&&n.indexes!=null)if(this.engine.modelGroup.children[n.indexes[0]]instanceof fi){let r=this.engine.modelGroup.children[n.indexes[0]].geometry.attributes.position.array;for(let a=n.indexes[1];a0&&this.showModel(this.engine.engineStatus2d.hideModels),this.engine.engineStatus2d.hideModels=[],this.unhighlightAllModels()}highLightRenderLine(e){let t=new at;t.setAttribute("position",new et(e,3));const i=new si({color:43775,depthTest:!1,depthWrite:!1}),n=new fi(t,i);n.name="HighLight",n.renderOrder=999,this.engine.modelGroup.add(n)}unhighLightRenderLine(){this.engine.modelGroup.children.filter(e=>e.name=="HighLight").forEach(e=>{this.engine.modelGroup.remove(e)})}highLightRenderLineHover(e){let t=new at;t.setAttribute("position",new et(e,3));const i=new si({color:16777215,depthTest:!1,depthWrite:!1}),n=new fi(t,i);n.name="HighLightHover",n.renderOrder=999,this.engine.modelGroup.add(n)}unhighLightRenderLineHover(){this.engine.modelGroup.children.filter(e=>e.name=="HighLightHover").forEach(e=>{this.engine.modelGroup.remove(e)})}}function hz(s){const e={self:null,options:null,mouseDownTime:0,mouseDownPosition:null,lastClickTime:0};e.init=function(g,m){e.self!=null&&e.self.disActive!=null&&e.self.type!=g.type&&e.self.disActive(),e.self=g,m==null&&(m={showCatch:!1}),e.options=m},e.render=function(){e.self&&e.self.render!=null&&e.self.render()},e.active=function(){s.renderer.domElement.addEventListener("mousedown",o),s.renderer.domElement.addEventListener("mouseup",c),s.renderer.domElement.addEventListener("mousemove",l),s.renderer.domElement.addEventListener("touchstart",d,{passive:!1}),s.renderer.domElement.addEventListener("touchend",u,{passive:!1}),s.renderer.domElement.addEventListener("touchmove",p,{passive:!1}),window.addEventListener("keydown",t),window.addEventListener("keyup",i)},e.disActive=function(){s.renderer.domElement.removeEventListener("mousedown",o),s.renderer.domElement.removeEventListener("mouseup",c),s.renderer.domElement.removeEventListener("mousemove",l),s.renderer.domElement.removeEventListener("touchstart",d),s.renderer.domElement.removeEventListener("touchend",u),s.renderer.domElement.removeEventListener("touchmove",p),window.removeEventListener("keydown",t),window.removeEventListener("keyup",i)};function t(g){(g.keyCode===8||g.keyCode===46)&&e.self&&e.self.handelKeyDeleteDown!=null&&e.self.handelKeyDeleteDown(),g.keyCode===27&&e.self&&e.self.handelKeyEscDown!=null&&e.self.handelKeyEscDown(),g.keyCode===13&&e.self&&e.self.handelKeyEnterDown!=null&&e.self.handelKeyEnterDown(),g.keyCode===32&&e.self&&e.self.handelKeySpaceDown!=null&&e.self.handelKeySpaceDown(),g.key==="Control"&&e.self&&e.self.handelKeyCtrlDown!=null&&e.self.handelKeyCtrlDown(),g.key==="Delete"&&e.self&&e.self.handelKeyDeleteDown!=null&&e.self.handelKeyDeleteDown(),g.key==="Shift"&&e.self&&e.self.handelKeyShiftDown!=null&&e.self.handelKeyShiftDown(),g.key==="Meta"&&e.self&&e.self.handelKeyMetaDown!=null&&e.self.handelKeyMetaDown()}function i(g){g.key==="Alt"&&e.self&&e.self.handelKeyAltUp!=null&&e.self.handelKeyAltUp(),g.key==="Tab"&&e.self&&e.self.handelKeyTabUp!=null&&e.self.handelKeyTabUp(),g.key==="Control"&&e.self&&e.self.handelKeyCtrlUp!=null&&e.self.handelKeyCtrlUp(),g.key==="Shift"&&e.self&&e.self.handelKeyShiftUp!=null&&e.self.handelKeyShiftUp(),g.key==="Meta"&&e.self&&e.self.handelKeyMetaUp!=null&&e.self.handelKeyMetaUp(),g.key==="Command"&&e.self&&e.self.handelKeyCommandUp!=null&&e.self.handelKeyCommandUp(),g.key==="Windows"&&e.self&&e.self.handelKeyWindowsUp!=null&&e.self.handelKeyWindowsUp()}function n(g){const m=new me,f=s.renderer.domElement.clientWidth,y=s.renderer.domElement.clientHeight;return m.x=g.offsetX/f*2-1,m.y=-(g.offsetY/y)*2+1,m}function r(g){const m=new Qn,f=n(g);return m.setFromCamera(f,s.camera),m}function a(g,m=!1){const f=r(g);if(g.raycaster=f,m){const y=v(f,g);g.catch=y}}function o(g){g.button===0&&(e.mouseDownTime=Date.now(),e.mouseDownPosition=new R(g.offsetX,g.offsetY,0),e.self&&e.self.handleMouseDown!=null&&(s.engineStatus.isFree=!0,a(g,!0),g.catch!=null&&s.controlModule.orbitControls.origin.set(g.catch.point.x,g.catch.point.y,g.catch.point.z),e.self.handleMouseDown(g)))}function l(g){a(g,!0),e.self&&e.self.handleMouseMove!=null&&e.self.handleMouseMove(g)}function c(g){if(g.button!==0)return;const m=Date.now(),f=m-e.mouseDownTime,y=new R(g.offsetX,g.offsetY,0);e.self&&e.self.handleMouseUp!=null&&(a(g,!1),e.self.handleMouseUp(g));const x=y.distanceTo(e.mouseDownPosition);(f<100||x==0)&&e.self&&e.self.handleMouseClick!=null&&(a(g,!0),m-e.lastClickTime<200?e.self.handleMouseDoubleClick!=null&&e.self.handleMouseDoubleClick(g):e.self.handleMouseClick!=null&&e.self.handleMouseClick(g),e.lastClickTime=Date.now())}function h(g){const m=g.touches[0]||g.changedTouches[0];if(!m)return null;const f=s.renderer.domElement.getBoundingClientRect(),y=m.clientX-f.left,x=m.clientY-f.top;return{offsetX:y,offsetY:x,button:0,clientX:m.clientX,clientY:m.clientY,preventDefault:()=>g.preventDefault(),stopPropagation:()=>g.stopPropagation(),originalEvent:g}}function d(g){if(g.preventDefault(),g.touches.length!==1)return;const m=h(g);m&&o(m)}function p(g){if(g.preventDefault(),g.touches.length!==1)return;const m=h(g);m&&l(m)}function u(g){g.preventDefault();const m=h(g);m&&c(m)}function v(g,m){var f=s.octreeBox2d.pick2d(g,m);return f==null?null:{point:null,id:f}}return e}class dz{el;xEl;yEl;constructor(e){this.el=document.createElement("div"),this.el.className="engine-2d-mouse-coord";const t=document.createElement("span");t.className="engine-2d-mouse-coord__label",t.textContent="",this.xEl=document.createElement("span"),this.xEl.className="engine-2d-mouse-coord__value",this.xEl.textContent="X: --",this.yEl=document.createElement("span"),this.yEl.className="engine-2d-mouse-coord__value",this.yEl.textContent="Y: --",this.el.appendChild(t),this.el.appendChild(this.xEl),this.el.appendChild(this.yEl),e.appendChild(this.el)}update(e,t){this.xEl.textContent=`X: ${e.toFixed(0)} mm`,this.yEl.textContent=`Y: ${t.toFixed(0)} mm`}reset(){this.xEl.textContent="X: --",this.yEl.textContent="Y: --"}dispose(){this.el.parentElement?.removeChild(this.el)}}var S2=(s=>(s.ModelLoadStart="model-load-start",s.ModelLoadProgress="model-load-progress",s.ModelLoaded="model-loaded",s.ModelError="model-error",s.SelectionChanged="selection-changed",s.HoverChanged="hover-changed",s.Click="click",s.MouseMove="mouse-move",s.CameraChanged="camera-changed",s.CameraIdle="camera-idle",s.EngineFree="engine-free",s.EngineBusy="engine-busy",s.MeasureChanged="measure-changed",s.MeasureClick="measure-click",s.SectionMove="section-move",s))(S2||{});class uz{engine;behavior;mouseCoordUI=null;constructor(e){this.engine=e}init(){this.behavior=this.engine.handelBehaved2d,this.behavior.init(this);const e=this.engine.container;e&&(this.mouseCoordUI=new dz(e))}active(){this.behavior.active()}disActive(){this.behavior.disActive()}oldId=null;handleMouseMove(e){if(!this.mouseCoordUI||!this.engine.cameraModule2d)return;const t=this.engine.cameraModule2d.screenToWorld(e.offsetX,e.offsetY);if(this.mouseCoordUI.update(t.x*1e3,t.y*1e3),e.catch==null||e.catch.id==null){this.engine.modelToolModule2d.unHighlightModelHover(),this.oldId=null;return}let i=e.catch.id;this.oldId!=i&&this.engine.modelToolModule2d.highlightModelHover([i])}handelKeyEscDown(e){this.engine.modelToolModule2d.unhighlightAllModels()}handleMouseClick(e){if(e.catch!=null){this.engine.modelToolModule2d.highlightModel([e.catch.id]),this.engine.events.trigger(S2.Click,e.catch.id);let t=new CustomEvent("D2ElementClick",{detail:{id:e.catch.id}});window.dispatchEvent(t)}else{this.engine.modelToolModule2d.unhighlightAllModels();let t=new CustomEvent("D2ElementClick",{detail:{id:-1}});window.dispatchEvent(t)}}dispose(){this.mouseCoordUI?.dispose(),this.mouseCoordUI=null}}class pz{overlay;hLine;vLine;box;canvas;constructor(e,t){this.canvas=t,t.style.cursor="none",this.overlay=document.createElement("div"),this.overlay.className="engine-2d-cad-cursor",this.hLine=document.createElement("div"),this.hLine.className="engine-2d-cad-cursor__h",this.vLine=document.createElement("div"),this.vLine.className="engine-2d-cad-cursor__v",this.box=document.createElement("div"),this.box.className="engine-2d-cad-cursor__box",this.overlay.appendChild(this.hLine),this.overlay.appendChild(this.vLine),this.overlay.appendChild(this.box),e.appendChild(this.overlay),this.hide(),this.bindEvents()}bindEvents(){this.canvas.addEventListener("mousemove",this.onMouseMove),this.canvas.addEventListener("mouseenter",this.onMouseEnter),this.canvas.addEventListener("mouseleave",this.onMouseLeave)}onMouseMove=e=>{const t=this.canvas.getBoundingClientRect(),i=e.clientX-t.left,n=e.clientY-t.top;this.hLine.style.top=`${n}px`,this.vLine.style.left=`${i}px`,this.box.style.left=`${i}px`,this.box.style.top=`${n}px`};onMouseEnter=()=>{this.show()};onMouseLeave=()=>{this.hide()};show(){this.overlay.style.visibility="visible"}hide(){this.overlay.style.visibility="hidden"}dispose(){this.canvas.removeEventListener("mousemove",this.onMouseMove),this.canvas.removeEventListener("mouseenter",this.onMouseEnter),this.canvas.removeEventListener("mouseleave",this.onMouseLeave),this.canvas.style.cursor="",this.overlay.parentElement?.removeChild(this.overlay)}}const fz=[{action:"search",label:"搜索"},{action:"hideElement",label:"隐藏元素",dividerBefore:!0},{action:"showAll",label:"显示全部"},{action:"hideLayer",label:"隐藏图层",dividerBefore:!0},{action:"showAllLayers",label:"显示所有图层"},{action:"layerManage",label:"图层管理",dividerBefore:!0},{action:"toggleBg",label:"切换背景"},{action:"linkElement2d3d",label:"模型联动",dividerBefore:!0},{action:"linkView2d3d",label:"视角关联"}];class mz{menu;container;canvas;onAction;menuItemStates=new Map;constructor(e,t,i){this.container=e,this.canvas=t,this.onAction=i,this.menu=this.createMenu(),e.appendChild(this.menu),this.bindEvents()}createMenu(){const e=document.createElement("div");return e.className="engine-2d-context-menu",fz.forEach(t=>{if(t.dividerBefore){const n=document.createElement("div");n.className="engine-2d-context-menu__divider",e.appendChild(n)}const i=document.createElement("div");i.className="engine-2d-context-menu__item",i.textContent=t.label,i.dataset.action=t.action,i.addEventListener("click",()=>{this.hide(),this.onAction(t.action)}),e.appendChild(i)}),e}bindEvents(){this.canvas.addEventListener("contextmenu",this.onContextMenu),document.addEventListener("mousedown",this.onDocMouseDown),document.addEventListener("keydown",this.onEscape)}onContextMenu=e=>{e.preventDefault();const t=this.container.getBoundingClientRect();let i=e.clientX-t.left,n=e.clientY-t.top;this.menu.style.left=`${i}px`,this.menu.style.top=`${n}px`,this.menu.classList.add("engine-2d-context-menu--visible"),this.updateMenuItemStyles();const r=this.menu.offsetWidth,a=this.menu.offsetHeight,o=this.container.clientWidth,l=this.container.clientHeight;i+r>o&&(i=o-r-4),n+a>l&&(n=l-a-4),this.menu.style.left=`${i}px`,this.menu.style.top=`${n}px`};onDocMouseDown=e=>{this.menu.contains(e.target)||this.hide()};onEscape=e=>{e.key==="Escape"&&this.hide()};hide(){this.menu.classList.remove("engine-2d-context-menu--visible")}setMenuItemState(e,t){this.menuItemStates.set(e,t)}setMenuItemStates(e){Object.entries(e).forEach(([t,i])=>{this.menuItemStates.set(t,i)})}updateMenuItemStyles(){this.menu.querySelectorAll(".engine-2d-context-menu__item").forEach(e=>{const t=e.dataset.action;this.menuItemStates.get(t)?(e.style.color="#00e682",e.style.fontWeight="bold"):(e.style.color="",e.style.fontWeight="")})}dispose(){this.canvas.removeEventListener("contextmenu",this.onContextMenu),document.removeEventListener("mousedown",this.onDocMouseDown),document.removeEventListener("keydown",this.onEscape),this.menu.parentElement?.removeChild(this.menu)}}class gz{overlay=null;textEl=null;barEl=null;pctEl=null;constructor(e){this._build(e)}show(e="正在加载...",t=0){this.overlay&&(this.overlay.style.display="flex",this._update(e,t))}update(e,t){this.overlay?.style.display!=="none"&&this._update(e,t)}hide(){this.overlay&&(this.overlay.style.display="none")}_update(e,t){const i=Math.min(100,Math.max(0,Math.round(t)));this.textEl&&(this.textEl.textContent=e),this.barEl&&(this.barEl.style.width=`${i}%`),this.pctEl&&(this.pctEl.textContent=`${i}%`)}_build(e){const t=document.createElement("div");t.style.cssText=` position:absolute; inset:0; display:none; align-items:center; justify-content:center; z-index:200; `,this.overlay=t;const i=document.createElement("div");i.style.cssText=` display:flex; flex-direction:column; align-items:center; gap:14px; padding:28px 36px; background:var(--e2d-bg,#1e1f22); border:1px solid var(--e2d-border,rgba(255,255,255,0.12)); border-radius:8px; box-shadow:0 8px 32px var(--e2d-shadow-lg,rgba(0,0,0,0.65)); min-width:200px; font-family:system-ui,sans-serif; `;const n=document.createElement("div");n.style.cssText="width:48px; height:48px;",n.innerHTML=` `;const r=document.createElement("div");r.style.cssText=` font-size:13px; color:var(--e2d-text2,#ccc); text-align:center; white-space:nowrap; `,r.textContent="正在加载...",this.textEl=r;const a=document.createElement("div");a.style.cssText=` width:160px; height:3px; border-radius:2px; background:var(--e2d-border2,#333); overflow:hidden; `;const o=document.createElement("div");o.style.cssText=` height:100%; width:0%; border-radius:2px; background:var(--e2d-accent,#4fc3f7); transition:width 0.25s ease; `,a.appendChild(o),this.barEl=o;const l=document.createElement("div");l.style.cssText=` font-size:12px; color:var(--e2d-text3,rgba(255,255,255,0.35)); `,l.textContent="0%",this.pctEl=l,i.appendChild(n),i.appendChild(r),i.appendChild(a),i.appendChild(l),t.appendChild(i),e.appendChild(t)}dispose(){this.overlay?.remove(),this.overlay=null,this.textEl=null,this.barEl=null,this.pctEl=null}}const vz=` `,yz=` `,xz={房间:"#4fc3f7",门:"#81c784",窗:"#aed581",柱:"#ff8a65",梁:"#ffb74d",楼梯:"#ce93d8",电梯:"#80deea",设备间:"#f48fb1",轴线:"#90a4ae",墙体:"#bcaaa4",室外:"#a5d6a7"};class _z{container;manager;wrapper;input;clearBtn;resultList;statusEl;activeIndex=-1;currentResults=[];debounceTimer=null;constructor(e,t){this.container=e,this.manager=t,this.wrapper=this._buildWrapper(),this.input=this.wrapper.querySelector(".engine-2d-search__input"),this.clearBtn=this.wrapper.querySelector(".engine-2d-search__clear"),this.resultList=this.wrapper.querySelector(".engine-2d-search__list"),this.statusEl=this.wrapper.querySelector(".engine-2d-search__status"),e.appendChild(this.wrapper),this._bindEvents()}_buildWrapper(){const e=document.createElement("div");return e.className="engine-2d-search",e.innerHTML=`
${vz}
    `,e}_bindEvents(){this.input.addEventListener("input",this._onInput),this.input.addEventListener("keydown",this._onKeyDown),this.clearBtn.addEventListener("click",this._onClear),document.addEventListener("mousedown",this._onDocMouseDown),document.addEventListener("keydown",this._onEscape)}_onInput=()=>{this.debounceTimer!==null&&clearTimeout(this.debounceTimer),this.debounceTimer=setTimeout(()=>this._doSearch(),150);const e=this.input.value.length>0;this.clearBtn.style.opacity=e?"1":"0",this.clearBtn.style.pointerEvents=e?"auto":"none"};_onKeyDown=e=>{const t=this.resultList.querySelectorAll(".engine-2d-search__item");t.length&&(e.key==="ArrowDown"?(e.preventDefault(),this.activeIndex=Math.min(this.activeIndex+1,t.length-1),this._highlightItem(t)):e.key==="ArrowUp"?(e.preventDefault(),this.activeIndex=Math.max(this.activeIndex-1,0),this._highlightItem(t)):e.key==="Enter"&&this.activeIndex>=0&&this.currentResults[this.activeIndex]&&this._selectResult(this.currentResults[this.activeIndex]))};_onClear=()=>{this.input.value="",this.clearBtn.style.opacity="0",this.clearBtn.style.pointerEvents="none",this._clearResults(),this.input.focus()};_onDocMouseDown=e=>{this.wrapper.contains(e.target)||this.hide()};_onEscape=e=>{e.key==="Escape"&&this.hide()};_doSearch(){const e=this.input.value;if(!e.trim()){this._clearResults();return}this.currentResults=this.manager.search(e),this.activeIndex=-1,this._renderResults(this.currentResults,e)}_renderResults(e,t){this.resultList.innerHTML="";const i=this.wrapper.querySelector(".engine-2d-search__divider");if(e.length===0){this.statusEl.textContent=`未找到与 "${t}" 相关的结果`,this.statusEl.style.display="block",i.style.display="none",this.resultList.style.display="none";return}this.statusEl.textContent=`找到 ${e.length} 个结果`,this.statusEl.style.display="block",i.style.display="block",this.resultList.style.display="block",e.forEach((n,r)=>{const a=document.createElement("li");a.className="engine-2d-search__item",a.setAttribute("role","option"),a.dataset.index=String(r);const o=xz[n.type]??"#90a4ae",l=this._highlight(n.name,t);a.innerHTML=` ${n.type} ${l} ${n.layer?`${n.layer}`:""} ${n.description?`${n.description}`:""} `,a.addEventListener("click",()=>this._selectResult(n)),a.addEventListener("mouseenter",()=>{this.activeIndex=r;const c=this.resultList.querySelectorAll(".engine-2d-search__item");this._highlightItem(c)}),this.resultList.appendChild(a)})}_highlight(e,t){const i=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return e.replace(new RegExp(`(${i})`,"gi"),'$1')}_highlightItem(e){e.forEach((t,i)=>{t.classList.toggle("engine-2d-search__item--active",i===this.activeIndex)}),this.activeIndex>=0&&e[this.activeIndex]?.scrollIntoView({block:"nearest"})}_selectResult(e){this.manager.onResultSelect(e),this.hide()}_clearResults(){this.resultList.innerHTML="",this.resultList.style.display="none",this.statusEl.style.display="none";const e=this.wrapper.querySelector(".engine-2d-search__divider");e.style.display="none",this.currentResults=[],this.activeIndex=-1}show(){this.wrapper.classList.add("engine-2d-search--visible"),requestAnimationFrame(()=>this.input.focus())}hide(){this.wrapper.classList.remove("engine-2d-search--visible"),this._clearResults(),this.input.value="",this.clearBtn.style.opacity="0",this.clearBtn.style.pointerEvents="none"}toggle(){this.wrapper.classList.contains("engine-2d-search--visible")?this.hide():this.show()}dispose(){this.input.removeEventListener("input",this._onInput),this.input.removeEventListener("keydown",this._onKeyDown),this.clearBtn.removeEventListener("click",this._onClear),document.removeEventListener("mousedown",this._onDocMouseDown),document.removeEventListener("keydown",this._onEscape),this.wrapper.parentElement?.removeChild(this.wrapper),this.debounceTimer!==null&&clearTimeout(this.debounceTimer)}}const bz=[{id:"1",name:"会议室 A",type:"房间",layer:"建筑-房间",description:"3F 东侧,面积 48㎡"},{id:"2",name:"会议室 B",type:"房间",layer:"建筑-房间",description:"3F 西侧,面积 32㎡"},{id:"3",name:"卫生间-男",type:"房间",layer:"建筑-房间",description:"2F,面积 18㎡"},{id:"4",name:"卫生间-女",type:"房间",layer:"建筑-房间",description:"2F,面积 16㎡"},{id:"5",name:"大厅",type:"房间",layer:"建筑-房间",description:"1F,面积 260㎡"},{id:"6",name:"主入口门",type:"门",layer:"建筑-门窗",description:"宽 2400mm,双开"},{id:"7",name:"次入口门",type:"门",layer:"建筑-门窗",description:"宽 1200mm,单开"},{id:"8",name:"防火门 FD-01",type:"门",layer:"建筑-门窗",description:"甲级防火,宽 900mm"},{id:"9",name:"落地窗 W-101",type:"窗",layer:"建筑-门窗",description:"高 3000mm,南向"},{id:"10",name:"普通窗 W-201",type:"窗",layer:"建筑-门窗",description:"高 1800mm,东向"},{id:"11",name:"承重柱 Z-A1",type:"柱",layer:"结构-柱",description:"600×600,混凝土"},{id:"12",name:"承重柱 Z-A2",type:"柱",layer:"结构-柱",description:"600×600,混凝土"},{id:"13",name:"钢柱 GZ-01",type:"柱",layer:"结构-柱",description:"H 型钢,H300×150"},{id:"14",name:"主梁 L-1",type:"梁",layer:"结构-梁",description:"400×800,跨度 8m"},{id:"15",name:"次梁 L-2",type:"梁",layer:"结构-梁",description:"250×500,跨度 4m"},{id:"16",name:"楼梯间 ST-1",type:"楼梯",layer:"建筑-楼梯",description:"双跑楼梯,净宽 1200mm"},{id:"17",name:"消防楼梯 ST-2",type:"楼梯",layer:"建筑-楼梯",description:"疏散楼梯,净宽 1100mm"},{id:"18",name:"电梯井 EV-1",type:"电梯",layer:"建筑-电梯",description:"客梯,井道 2000×2200"},{id:"19",name:"消防电梯 EV-2",type:"电梯",layer:"建筑-电梯",description:"消防兼客梯"},{id:"20",name:"强电竖井",type:"设备间",layer:"机电-电气",description:"1F~RF,面积 4㎡"},{id:"21",name:"弱电竖井",type:"设备间",layer:"机电-电气",description:"1F~RF,面积 2㎡"},{id:"22",name:"空调机房",type:"设备间",layer:"机电-暖通",description:"BF,面积 80㎡"},{id:"23",name:"消防控制室",type:"设备间",layer:"机电-消防",description:"1F,面积 24㎡"},{id:"24",name:"配电室",type:"设备间",layer:"机电-电气",description:"BF,面积 36㎡"},{id:"25",name:"轴线 A",type:"轴线",layer:"轴网",description:"X 向,间距 8400mm"},{id:"26",name:"轴线 1",type:"轴线",layer:"轴网",description:"Y 向,间距 7200mm"},{id:"27",name:"内墙 Q-001",type:"墙体",layer:"建筑-墙",description:"200mm 砌块"},{id:"28",name:"外墙 Q-101",type:"墙体",layer:"建筑-墙",description:"300mm 保温外墙"},{id:"29",name:"散水 SS-1",type:"室外",layer:"建筑-室外",description:"宽 900mm,坡度 3%"},{id:"30",name:"台阶 TJ-1",type:"室外",layer:"建筑-室外",description:"3 级,踏步 300×150"}];class Mz{engine;searchUI=null;constructor(e){this.engine=e;const t=document.getElementById(e?.options?.containerId??"")??e?.container??null;t&&(this.searchUI=new _z(t,this))}search(e){const t=e.trim().toLowerCase();return t?bz.filter(i=>i.name.toLowerCase().includes(t)||i.type.toLowerCase().includes(t)||(i.layer?.toLowerCase().includes(t)??!1)||(i.description?.toLowerCase().includes(t)??!1)):[]}onResultSelect(e){console.log("[SearchManager] 选中结果:",e)}show(){this.searchUI?.show()}hide(){this.searchUI?.hide()}toggle(){this.searchUI?.toggle()}dispose(){this.searchUI?.dispose(),this.searchUI=null}}const w2={dark:{"--e2d-bg":"#1e1f22","--e2d-bg2":"#252526","--e2d-bg3":"#222222","--e2d-bg-hover":"rgba(79,195,247,0.08)","--e2d-bg-accent":"#094771","--e2d-icon-bg":"rgba(255,255,255,0.08)","--e2d-icon-bg-hover":"rgba(255,255,255,0.16)","--e2d-border":"rgba(255,255,255,0.12)","--e2d-border2":"#333333","--e2d-text":"#e0e0e0","--e2d-text2":"#cccccc","--e2d-text3":"rgba(255,255,255,0.35)","--e2d-text4":"#666666","--e2d-text-accent":"#ffffff","--e2d-accent":"#4fc3f7","--e2d-shadow":"rgba(0,0,0,0.50)","--e2d-shadow-lg":"rgba(0,0,0,0.65)","--e2d-cursor":"rgba(255,255,255,0.85)","--e2d-scrollbar":"rgba(255,255,255,0.15)","--e2d-float-bg":"rgba(0,0,0,0.65)","--e2d-float-border":"rgba(255,255,255,0.08)","--e2d-swatch-border":"#444444","--e2d-close":"#aaaaaa","--e2d-close-hover":"#ffffff","--e2d-icon":"rgba(255,255,255,0.4)","--e2d-coord-value":"#76c8ff","--e2d-coord-label":"rgba(255,255,255,0.45)"},light:{"--e2d-bg":"#ffffff","--e2d-bg2":"#f5f5f5","--e2d-bg3":"#eeeeee","--e2d-bg-hover":"rgba(25,118,210,0.06)","--e2d-bg-accent":"#e3f2fd","--e2d-icon-bg":"rgba(0,0,0,0.06)","--e2d-icon-bg-hover":"rgba(0,0,0,0.12)","--e2d-border":"rgba(0,0,0,0.12)","--e2d-border2":"#e0e0e0","--e2d-text":"#1a1a1a","--e2d-text2":"#444444","--e2d-text3":"rgba(0,0,0,0.40)","--e2d-text4":"#aaaaaa","--e2d-text-accent":"#1565c0","--e2d-accent":"#1976d2","--e2d-shadow":"rgba(0,0,0,0.15)","--e2d-shadow-lg":"rgba(0,0,0,0.22)","--e2d-cursor":"rgba(30,30,30,0.70)","--e2d-scrollbar":"rgba(0,0,0,0.18)","--e2d-float-bg":"rgba(245,245,245,0.92)","--e2d-float-border":"rgba(0,0,0,0.10)","--e2d-swatch-border":"#cccccc","--e2d-close":"#777777","--e2d-close-hover":"#1a1a1a","--e2d-icon":"rgba(0,0,0,0.45)","--e2d-coord-value":"#1976d2","--e2d-coord-label":"rgba(0,0,0,0.50)"}};class Sz{container;current;constructor(e,t="dark"){this.container=e,this.current=t,this._apply(t)}_apply(e){const t=w2[e];for(const[i,n]of Object.entries(t))this.container.style.setProperty(i,n);this.container.setAttribute("data-e2d-theme",e)}setTheme(e){this.current=e,this._apply(e)}getTheme(){return this.current}toggle(){this.setTheme(this.current==="dark"?"light":"dark")}dispose(){for(const e of Object.keys(w2[this.current]))this.container.style.removeProperty(e);this.container.removeAttribute("data-e2d-theme")}}class wz{options;container=null;animationId=null;isRendering=!1;fpsFrameCount=0;fpsLastCheck=0;currentFps=0;enablePerformanceMonitoring=!1;modelToolModule2d;engineStatus2d;octreeBox2d;events;handelBehaved2d;interactionModule2d;sceneModule2d;cameraModule2d;renderModule2d;controlModule2d;loaderModule2d;layerManager;searchManager;themeManager;cadCursorUI;contextMenuUI;loadingUI;linkView2d3d;linkElement2d3d;scene=null;camera=null;renderer=null;dwgData=null;version="1.0.0";constructor(e){if(this.options=e,this.enablePerformanceMonitoring=e.enablePerformanceMonitoring??!1,this.container=document.getElementById(e.containerId),!this.container)throw new Error(`Container ${e.containerId} not found`);this.initialize(),this.handelBehaved2d=hz(this),this.interactionModule2d=new uz(this),this.interactionModule2d.init(),this.interactionModule2d.active()}initialize(){this.events=new VF(!1),this.sceneModule2d=new ez(this,this.options),this.scene=this.sceneModule2d.scene,this.cameraModule2d=new iz(this,this.container),this.camera=this.cameraModule2d.orthographicCamera,this.renderModule2d=new nz(this,this.container,this.options),this.renderer=this.renderModule2d.renderer,this.controlModule2d=new rz(this),this.loaderModule2d=new M2(this),this.themeManager=new Sz(this.container),this.layerManager=new b2(this),this.searchManager=new Mz(this),this.octreeBox2d=new az(this),this.modelToolModule2d=new cz(this),this.engineStatus2d=new tz(this),this.linkView2d3d=new oz(this),this.linkElement2d3d=new lz(this),this.sceneModule2d.initGrid(),this.cadCursorUI=new pz(this.container,this.renderer.domElement),this.loadingUI=new gz(this.container),this.events.on(Wn.ModelLoadStart,()=>this.loadingUI.show("正在加载...",0)),this.events.on(Wn.ModelLoadProgress,e=>this.loadingUI.update(e.text,e.progress)),this.events.on(Wn.ModelLoaded,()=>this.loadingUI.hide()),this.events.on(Wn.ModelLoadError,()=>this.loadingUI.hide()),this.contextMenuUI=new mz(this.container,this.renderer.domElement,e=>{if(e==="search"&&this.searchManager.show(),e==="layerManage"&&this.layerManager.toggle(),e==="hideElement"&&this.modelToolModule2d.hideModel(this.engineStatus2d.highlightModels),e==="showAll"&&this.modelToolModule2d.showModel(this.engineStatus2d.hideModels),e==="toggleBg"){this.themeManager.toggle();const t=this.themeManager.getTheme()==="dark"?1710618:15790320;this.setBackgroundColor(t)}if(e==="linkElement2d3d"){const t=this.linkElement2d3d.toggle();this.contextMenuUI.setMenuItemState("linkElement2d3d",t),console.log(`[EngineKernel2d] 二三维图元联动: ${t?"已开启":"已关闭"}`)}if(e==="linkView2d3d"){const t=this.linkView2d3d.toggle();this.contextMenuUI.setMenuItemState("linkView2d3d",t),console.log(`[EngineKernel2d] 图模关联: ${t?"已开启":"已关闭"}`)}}),this.contextMenuUI.setMenuItemStates({linkElement2d3d:this.linkElement2d3d.isEnabled(),linkView2d3d:this.linkView2d3d.isEnabled()}),this.startRendering(),console.log(`[EngineKernel2d] 2D Engine initialized (v${this.version})`)}startRendering(){this.isRendering||(this.isRendering=!0,this.fpsLastCheck=performance.now(),this.animate(),console.log("[EngineKernel2d] Rendering started"))}stopRendering(){this.isRendering=!1,this.animationId!==null&&(cancelAnimationFrame(this.animationId),this.animationId=null),console.log("[EngineKernel2d] Rendering stopped")}animate=()=>{this.isRendering&&(this.animationId=requestAnimationFrame(this.animate),this.controlModule2d.update(),this.scene&&this.camera&&this.renderer&&this.renderer.render(this.scene,this.camera),this.enablePerformanceMonitoring&&this.updatePerformanceStats())};updatePerformanceStats(){this.fpsFrameCount++;const e=performance.now();e-this.fpsLastCheck>=1e3&&(this.currentFps=this.fpsFrameCount,this.fpsFrameCount=0,this.fpsLastCheck=e,this.events.trigger(Wn.RenderEnd,{fps:this.currentFps}))}async loadModel(e,t){return await this.loaderModule2d.loadModel(e,t),{}}getLayers(){return this.loaderModule2d.getLayers()}getEntitiesByLayer(e){return this.loaderModule2d.getEntitiesByLayer(e)}setLayerVisible(e,t){console.log(`[EngineKernel2d] Set layer ${e} visible: ${t}`)}setTheme(e){this.themeManager.setTheme(e)}resetView(){this.cameraModule2d&&this.cameraModule2d.resetView()}fitToView(){this.dwgData?.metadata.extents&&this.cameraModule2d.fitToExtents(this.dwgData.metadata.extents)}setZoom(e){this.cameraModule2d&&this.cameraModule2d.setZoom(e)}getZoom(){return this.cameraModule2d?this.cameraModule2d.getZoom():1}getPerformanceStats(){const e=this.sceneModule2d.getSceneStats();return{fps:this.currentFps,renderTime:0,entityCount:e.objectCount,visibleEntityCount:e.objectCount}}setBackgroundColor(e){this.sceneModule2d&&this.sceneModule2d.setBackgroundColor(e)}clearScene(){this.sceneModule2d&&this.sceneModule2d.clearScene()}resize(){if(this.renderModule2d){const e=this.container?.clientWidth??0,t=this.container?.clientHeight??0;this.renderModule2d.setSize(e,t)}}captureImage(e){if(!this.renderer||!this.sceneModule2d)return console.error("[EngineKernel2d] Renderer or scene module not initialized"),null;const t=this.renderer.domElement,i=e?.format||"png",n=e?.quality||.92,r=`image/${i==="jpeg"?"jpeg":i}`,a=e?.transparent??!1,o=e?.hideGrid??!0,l=e?.hideAxes??!0,c=this.scene?.background??null;let h=!1,d=!1;this.sceneModule2d.adaptiveGrid&&(h=this.sceneModule2d.adaptiveGrid.gridGroup?.visible??!1,o&&this.sceneModule2d.adaptiveGrid.setVisible(!1)),this.sceneModule2d.axesHelper&&(d=this.sceneModule2d.axesHelper.visible??!1,l&&this.sceneModule2d.setAxesVisible(!1)),a&&this.scene&&(this.scene.background=null),this.scene&&this.camera&&this.renderer.render(this.scene,this.camera);const p=t.toDataURL(r,n);this.scene&&(this.scene.background=c),this.sceneModule2d.adaptiveGrid&&o&&this.sceneModule2d.adaptiveGrid.setVisible(h),this.sceneModule2d.axesHelper&&l&&this.sceneModule2d.setAxesVisible(d),this.scene&&this.camera&&this.renderer.render(this.scene,this.camera);const u={dataURL:p};if(e?.download){const v=e.filename||`capture-${Date.now()}.${i}`,g=document.createElement("a");g.href=p,g.download=v,g.style.display="none",document.body.appendChild(g),g.click(),g.remove(),console.log(`[EngineKernel2d] Image captured and downloaded: ${v}`)}else console.log("[EngineKernel2d] Image captured");return u}async captureImageAsync(e){if(!this.renderer||!this.sceneModule2d)return console.error("[EngineKernel2d] Renderer or scene module not initialized"),null;const t=this.renderer.domElement,i=e?.format||"png",n=e?.quality||.92,r=`image/${i==="jpeg"?"jpeg":i}`,a=e?.transparent??!1,o=e?.hideGrid??!0,l=e?.hideAxes??!0,c=this.scene?.background??null;let h=!1,d=!1;this.sceneModule2d.adaptiveGrid&&(h=this.sceneModule2d.adaptiveGrid.gridGroup?.visible??!1,o&&this.sceneModule2d.adaptiveGrid.setVisible(!1)),this.sceneModule2d.axesHelper&&(d=this.sceneModule2d.axesHelper.visible??!1,l&&this.sceneModule2d.setAxesVisible(!1)),a&&this.scene&&(this.scene.background=null),this.scene&&this.camera&&this.renderer.render(this.scene,this.camera);const p=t.toDataURL(r,n),u=await new Promise(g=>{t.toBlob(m=>{m&&g(m)},r,n)}),v=URL.createObjectURL(u);if(this.scene&&(this.scene.background=c),this.sceneModule2d.adaptiveGrid&&o&&this.sceneModule2d.adaptiveGrid.setVisible(h),this.sceneModule2d.axesHelper&&l&&this.sceneModule2d.setAxesVisible(d),this.scene&&this.camera&&this.renderer.render(this.scene,this.camera),e?.download){const g=e.filename||`capture-${Date.now()}.${i}`,m=document.createElement("a");m.href=v,m.download=g,m.style.display="none",document.body.appendChild(m),m.click(),m.remove(),console.log(`[EngineKernel2d] Image captured and downloaded: ${g}`)}else console.log("[EngineKernel2d] Image captured with Blob URL:",v);return{dataURL:p,blobURL:v,blob:u}}dispose(){console.log("[EngineKernel2d] Disposing engine..."),this.stopRendering(),this.cadCursorUI?.dispose(),this.contextMenuUI?.dispose(),this.loadingUI?.dispose(),this.searchManager?.dispose(),this.themeManager?.dispose(),this.loaderModule2d?.dispose(),this.controlModule2d?.dispose(),this.renderModule2d?.dispose(),this.cameraModule2d?.dispose(),this.sceneModule2d?.dispose(),this.events?.dispose(),this.scene=null,this.camera=null,this.renderer=null,this.dwgData=null,console.log("[EngineKernel2d] Engine disposed")}}class Ez{scene;panoramaSphere=null;sphereRadius;constructor(e=500){this.sphereRadius=e,this.scene=new Ia,this.init()}init(){this.panoramaSphere=this.createPanoramaSphere(this.sphereRadius),this.scene.add(this.panoramaSphere)}createPanoramaSphere(e=500,t=64){const i=new Fa(e,t,t/2);i.scale(-1,1,1);const n=new Dt({map:null,side:_n,transparent:!0}),r=new ht(i,n);return r.name="panorama-sphere",r}updatePanoramaTexture(e){if(!this.panoramaSphere){console.warn("SceneModule720: Panorama sphere not initialized");return}const t=this.panoramaSphere.material;t.map&&t.map.dispose(),t.map=e,t.needsUpdate=!0}clearPanoramaTexture(){if(!this.panoramaSphere)return;const e=this.panoramaSphere.material;e.map&&(e.map.dispose(),e.map=null,e.needsUpdate=!0)}getScene(){return this.scene}getPanoramaSphere(){return this.panoramaSphere}setSphereRadius(e){if(this.sphereRadius!==e){if(this.sphereRadius=e,this.panoramaSphere){const t=this.panoramaSphere.material,i=t.map;this.scene.remove(this.panoramaSphere),this.panoramaSphere.geometry.dispose(),t.dispose(),i&&i.dispose()}this.panoramaSphere=this.createPanoramaSphere(e),this.scene.add(this.panoramaSphere)}}getSphereRadius(){return this.sphereRadius}dispose(){if(this.panoramaSphere){const e=this.panoramaSphere.material;e.map&&e.map.dispose(),e.dispose(),this.panoramaSphere.geometry.dispose(),this.scene.remove(this.panoramaSphere),this.panoramaSphere=null}this.scene.clear()}}class Tz{camera;minFov;maxFov;container;currentPose;constructor(e,t=75,i=30,n=90){this.container=e,this.minFov=i,this.maxFov=n,this.currentPose={theta:0,phi:0},this.camera=this.createCamera(t),this.init()}createCamera(e){const t=this.container.clientWidth/this.container.clientHeight,i=new ai(e,t,.1,2e3);return i.position.set(0,0,0),i}init(){this.updateCameraRotation()}updateCameraRotation(){const{theta:e,phi:t}=this.currentPose,i=new Fi(t,e,0,"YXZ"),n=new Kt;n.setFromEuler(i),this.camera.quaternion.copy(n)}setFov(e){const t=Math.max(this.minFov,Math.min(this.maxFov,e));this.camera.fov=t,this.camera.updateProjectionMatrix()}getFov(){return this.camera.fov}getCameraPose(){return{...this.currentPose}}setCameraPose(e,t){this.currentPose.theta=e,this.currentPose.phi=t,this.updateCameraRotation()}updatePose(e,t){this.currentPose.theta+=e,this.currentPose.phi+=t,this.currentPose.theta<0?this.currentPose.theta+=2*Math.PI:this.currentPose.theta>=2*Math.PI&&(this.currentPose.theta-=2*Math.PI),this.currentPose.phi=Math.max(-Math.PI/2+.01,Math.min(Math.PI/2-.01,this.currentPose.phi)),this.updateCameraRotation()}getCamera(){return this.camera}updateAspectRatio(e,t){const i=e/t;this.camera.aspect=i,this.camera.updateProjectionMatrix()}dispose(){this.camera=null}}class Cz{renderer;container;animationId=null;isRenderingPaused=!1;fpsFrameCount=0;fpsLastTime=performance.now();currentFps=60;onBeforeRenderCallback;onAfterRenderCallback;constructor(e,t=!0){this.container=e,this.renderer=this.createRenderer(t),this.init()}createRenderer(e){const t=new mh({antialias:e,alpha:!0,preserveDrawingBuffer:!1}),i=this.container.clientWidth,n=this.container.clientHeight;return t.setSize(i,n),t.setPixelRatio(Math.min(window.devicePixelRatio,2)),this.container.appendChild(t.domElement),t}init(){}setOnBeforeRender(e){this.onBeforeRenderCallback=e}setOnAfterRender(e){this.onAfterRenderCallback=e}render(e,t){this.onBeforeRenderCallback&&this.onBeforeRenderCallback(),this.renderer.render(e,t),this.onAfterRenderCallback&&this.onAfterRenderCallback(),this.updateFps()}startRenderLoop(e,t){if(this.animationId!==null){console.warn("RenderModule720: Render loop already running");return}this.isRenderingPaused=!1,this.animate(e,t)}animate(e,t){this.isRenderingPaused||(this.animationId=requestAnimationFrame(()=>{this.animate(e,t)}),this.render(e,t))}pauseRendering(){this.isRenderingPaused=!0,this.animationId!==null&&(cancelAnimationFrame(this.animationId),this.animationId=null)}resumeRendering(e,t){this.isRenderingPaused&&(this.isRenderingPaused=!1,this.startRenderLoop(e,t))}isRenderingPausedState(){return this.isRenderingPaused}updateFps(){this.fpsFrameCount++;const e=performance.now();e>=this.fpsLastTime+1e3&&(this.currentFps=Math.round(this.fpsFrameCount*1e3/(e-this.fpsLastTime)),this.fpsFrameCount=0,this.fpsLastTime=e,this.currentFps<30&&console.warn("RenderModule720: Low FPS detected:",this.currentFps))}getCurrentFps(){return this.currentFps}resize(e,t){this.renderer.setSize(e,t),this.renderer.setPixelRatio(Math.min(window.devicePixelRatio,2))}getDomElement(){return this.renderer.domElement}getRenderer(){return this.renderer}dispose(){this.pauseRendering(),this.container.contains(this.renderer.domElement)&&this.container.removeChild(this.renderer.domElement),this.renderer.dispose(),this.renderer.forceContextLoss(),this.onBeforeRenderCallback=void 0,this.onAfterRenderCallback=void 0}}class Az{camera;domElement;cameraModule;enableZoom=!0;enableRotate=!0;minFov=30;maxFov=90;rotateSpeed=.5;zoomSpeed=1;enableDamping=!0;dampingFactor=.05;isDragging=!1;startX=0;startY=0;thetaDelta=0;phiDelta=0;isPinching=!1;pinchStartDistance=null;pinchStartFov=75;_onMouseDown;_onMouseMove;_onMouseUp;_onWheel;_onTouchStart;_onTouchMove;_onTouchEnd;onViewAngleChange;constructor(e,t){this.cameraModule=e,this.camera=e.getCamera(),this.pinchStartFov=this.camera.fov,this.domElement=t,this._onMouseDown=this.onMouseDown.bind(this),this._onMouseMove=this.onMouseMove.bind(this),this._onMouseUp=this.onMouseUp.bind(this),this._onWheel=this.onWheel.bind(this),this._onTouchStart=this.onTouchStart.bind(this),this._onTouchMove=this.onTouchMove.bind(this),this._onTouchEnd=this.onTouchEnd.bind(this),this.init()}init(){this.domElement.addEventListener("mousedown",this._onMouseDown),this.domElement.addEventListener("mousemove",this._onMouseMove),this.domElement.addEventListener("mouseup",this._onMouseUp),this.domElement.addEventListener("mouseleave",this._onMouseUp),this.domElement.addEventListener("wheel",this._onWheel,{passive:!1}),this.domElement.addEventListener("touchstart",this._onTouchStart,{passive:!1}),this.domElement.addEventListener("touchmove",this._onTouchMove,{passive:!1}),this.domElement.addEventListener("touchend",this._onTouchEnd)}onMouseDown(e){e.button===0&&(this.isDragging=!0,this.startX=e.clientX,this.startY=e.clientY)}onMouseMove(e){if(!this.isDragging||!this.enableRotate)return;const t=e.clientX-this.startX,i=e.clientY-this.startY,{horizontal:n,vertical:r}=this.getRotationFactors();this.thetaDelta+=t*n*this.rotateSpeed*.06,this.phiDelta+=i*r*this.rotateSpeed*.06,this.startX=e.clientX,this.startY=e.clientY,this.applyRotation()}onMouseUp(){this.isDragging=!1}onWheel(e){if(!this.enableZoom)return;e.preventDefault();const t=(e.deltaY>0?1:-1)*this.zoomSpeed*2;this.applyZoom(t)}onTouchStart(e){e.touches.length===1?(this.isDragging=!0,this.isPinching=!1,this.startX=e.touches[0].clientX,this.startY=e.touches[0].clientY):e.touches.length===2&&(e.preventDefault(),this.isDragging=!1,this.isPinching=!0,this.pinchStartDistance=this.getTouchDistance(e.touches),this.pinchStartFov=this.cameraModule.getFov())}onTouchMove(e){if(e.touches.length===1&&this.isDragging&&this.enableRotate){const t=e.touches[0].clientX-this.startX,i=e.touches[0].clientY-this.startY,{horizontal:n,vertical:r}=this.getRotationFactors();this.thetaDelta-=t*n*this.rotateSpeed,this.phiDelta-=i*r*this.rotateSpeed,this.startX=e.touches[0].clientX,this.startY=e.touches[0].clientY,this.applyRotation()}else if(e.touches.length===2&&this.enableZoom){e.preventDefault(),this.isPinching||(this.isPinching=!0,this.pinchStartDistance=this.getTouchDistance(e.touches),this.pinchStartFov=this.cameraModule.getFov());const t=this.getTouchDistance(e.touches);if(this.pinchStartDistance&&t>0){const i=this.pinchStartDistance/t,n=Lt.clamp(this.pinchStartFov*i,this.minFov,this.maxFov);this.cameraModule.setFov(n)}}}onTouchEnd(e){e.touches&&e.touches.length>0?this.isDragging=e.touches.length===1:this.isDragging=!1,e.touches.length<2&&(this.isPinching=!1,this.pinchStartDistance=null)}applyRotation(){if(this.cameraModule.updatePose(this.thetaDelta,this.phiDelta),this.enableDamping?(this.thetaDelta*=1-this.dampingFactor,this.phiDelta*=1-this.dampingFactor):(this.thetaDelta=0,this.phiDelta=0),this.onViewAngleChange){const e=this.cameraModule.getCameraPose();this.onViewAngleChange(e.theta,e.phi)}}getRotationFactors(){const e=Math.max(1,this.domElement.clientWidth),t=Math.max(1,this.domElement.clientHeight);return{horizontal:Math.PI*2/e,vertical:Math.PI/t}}applyZoom(e){const t=this.cameraModule.getFov(),i=Lt.clamp(t+e,this.minFov,this.maxFov);this.cameraModule.setFov(i)}getTouchDistance(e){if(e.length<2)return 0;const t=e[0].clientX-e[1].clientX,i=e[0].clientY-e[1].clientY;return Math.sqrt(t*t+i*i)}update(){this.enableDamping&&(Math.abs(this.thetaDelta)>1e-4||Math.abs(this.phiDelta)>1e-4)&&this.applyRotation()}lookAt(e,t){this.thetaDelta=e,this.phiDelta=Math.max(-Math.PI/2+.01,Math.min(Math.PI/2-.01,t)),this.cameraModule.setCameraPose(e,t),this.thetaDelta=0,this.phiDelta=0}getViewAngle(){return this.cameraModule.getCameraPose()}setOnViewAngleChange(e){this.onViewAngleChange=e}reset(){this.thetaDelta=0,this.phiDelta=0,this.lookAt(0,0)}setRotateSpeed(e){this.rotateSpeed=Math.max(.05,e)}setZoomSpeed(e){this.zoomSpeed=Math.max(.1,e)}setEnableDamping(e){this.enableDamping=e}setDampingFactor(e){this.dampingFactor=Math.max(0,Math.min(1,e))}setZoomLimits(e,t){this.minFov=e,this.maxFov=t}dispose(){this.domElement.removeEventListener("mousedown",this._onMouseDown),this.domElement.removeEventListener("mousemove",this._onMouseMove),this.domElement.removeEventListener("mouseup",this._onMouseUp),this.domElement.removeEventListener("mouseleave",this._onMouseUp),this.domElement.removeEventListener("wheel",this._onWheel),this.domElement.removeEventListener("touchstart",this._onTouchStart),this.domElement.removeEventListener("touchmove",this._onTouchMove),this.domElement.removeEventListener("touchend",this._onTouchEnd),this.onViewAngleChange=void 0}}class Pz{controls;domElement;cameraModule;constructor(e,t){this.cameraModule=e,this.domElement=t,this.controls=new Az(e,t)}init(){}active(){}disActive(){this.controls.enableRotate=!1,this.controls.enableZoom=!1}enable(){this.controls.enableRotate=!0,this.controls.enableZoom=!0}update(){this.controls.update()}lookAt(e,t){this.controls.lookAt(e,t)}getViewAngle(){return this.controls.getViewAngle()}setOnViewAngleChange(e){this.controls.setOnViewAngleChange(e)}reset(){this.controls.reset()}getControls(){return this.controls}updateInteractionOptions(e){if(e.rotateSpeed!==void 0&&this.controls.setRotateSpeed(e.rotateSpeed),e.zoomSpeed!==void 0&&this.controls.setZoomSpeed(e.zoomSpeed),e.enableDamping!==void 0&&this.controls.setEnableDamping(e.enableDamping),e.dampingFactor!==void 0&&this.controls.setDampingFactor(e.dampingFactor),e.enableRotate!==void 0&&(this.controls.enableRotate=e.enableRotate),e.enableZoom!==void 0&&(this.controls.enableZoom=e.enableZoom),e.minFov!==void 0||e.maxFov!==void 0){const t=e.minFov??this.controls.minFov,i=e.maxFov??this.controls.maxFov;this.controls.setZoomLimits(t,i)}}dispose(){this.controls.dispose()}}class Rz{cache=new Map;loadingPromises=new Map;loadTexture(e){if(this.cache.has(e))return Promise.resolve(this.cache.get(e));if(this.loadingPromises.has(e))return this.loadingPromises.get(e);const t=new Promise((i,n)=>{new qa().load(e,r=>{r.colorSpace=li,r.minFilter=At,r.magFilter=At,this.cache.set(e,r),this.loadingPromises.delete(e),i(r)},void 0,r=>{this.loadingPromises.delete(e),n(r)})});return this.loadingPromises.set(e,t),t}async preloadTextures(e){const t=e.map(i=>this.loadTexture(i));return Promise.all(t)}has(e){return this.cache.has(e)}get(e){return this.cache.get(e)}remove(e){const t=this.cache.get(e);t&&(t.dispose(),this.cache.delete(e))}clear(){this.cache.forEach(e=>e.dispose()),this.cache.clear(),this.loadingPromises.clear()}size(){return this.cache.size}dispose(){this.clear()}}class Iz{textureCache;currentUrl=null;loadProgress=0;onProgressCallback;constructor(){this.textureCache=new Rz}async loadTexture(e){this.currentUrl=e,this.loadProgress=0,this.onProgressCallback&&this.onProgressCallback(0);try{const t=await this.loadTextureInternal(e);return this.loadProgress=100,this.onProgressCallback&&this.onProgressCallback(100),t}catch(t){throw console.error("PanoramaLoader: Failed to load texture:",t),t}}loadTextureInternal(e){return new Promise((t,i)=>{if(this.textureCache.has(e)){const n=this.textureCache.get(e);if(n){t(n);return}}new qa().load(e,n=>{n.colorSpace=li,n.minFilter=At,n.magFilter=At,this.textureCache.cache.set(e,n),t(n)},n=>{n.total>0&&(this.loadProgress=n.loaded/n.total*100,this.onProgressCallback&&this.onProgressCallback(this.loadProgress))},n=>{i(n)})})}async preloadPanoramas(e){try{await this.textureCache.preloadTextures(e)}catch(t){throw console.error("PanoramaLoader: Failed to preload panoramas:",t),t}}getLoadProgress(){return this.loadProgress}setOnProgress(e){this.onProgressCallback=e}getCurrentUrl(){return this.currentUrl}isCached(e){return this.textureCache.has(e)}getCachedTexture(e){return this.textureCache.get(e)}clearCache(){this.textureCache.clear()}removeCachedTexture(e){this.textureCache.remove(e)}dispose(){this.textureCache.dispose(),this.onProgressCallback=void 0,this.currentUrl=null}}class E2{static sphericalToCartesian(e){const t=e.radius||500,{theta:i,phi:n}=e,r=t*Math.cos(n)*Math.cos(i),a=t*Math.sin(n),o=t*Math.cos(n)*Math.sin(i);return{x:r,y:a,z:o}}static cartesianToSpherical(e,t,i){const n=Math.sqrt(e*e+t*t+i*i),r=Math.asin(t/n);let a=Math.atan2(i,e);return a<0&&(a+=2*Math.PI),{theta:a,phi:r,radius:n}}static normalizeAngle(e,t=-Math.PI,i=Math.PI){const n=i-t;let r=e;for(;ri;)r-=n;return r}static clampPhi(e,t=-Math.PI/2+.01,i=Math.PI/2-.01){return Math.max(t,Math.min(i,e))}static sphericalDistance(e,t){const i=Math.sin(e.phi)*Math.sin(t.phi)+Math.cos(e.phi)*Math.cos(t.phi)*Math.cos(e.theta-t.theta);return Math.acos(Math.max(-1,Math.min(1,i)))}static lerpSpherical(e,t,i){let n=t.theta-e.theta;n>Math.PI?n-=2*Math.PI:n<-Math.PI&&(n+=2*Math.PI);const r=e.theta+n*i,a=e.phi+(t.phi-e.phi)*i,o=e.radius||500,l=t.radius||500,c=o+(l-o)*i;return{theta:r,phi:a,radius:c}}}var Qh=(s=>(s.ICON="icon",s.TEXT="text",s.LINK="link",s))(Qh||{});class Lz{annotations=new Map;container;annotationContainer;worldToScreen;sphereRadius;camera;renderer;onClickAnnotation;onHoverAnnotation;constructor(e,t,i,n){this.container=e,this.camera=t,this.renderer=i,this.sphereRadius=n,this.worldToScreen=new zt(t,i),this.createAnnotationContainer()}createAnnotationContainer(){this.annotationContainer=document.createElement("div"),this.annotationContainer.className="panorama-annotation-container",this.annotationContainer.style.cssText=` position: absolute; top: 0; left: 0; width: 100%; height: 100%; pointer-events: none; z-index: 1000; overflow: hidden; `,this.container.appendChild(this.annotationContainer)}addAnnotation(e){const t=this.generateId(),i=this.sphericalToCartesian(e.position),n=this.createAnnotationElement(e,t),r={id:t,config:e,element:n,worldPosition:i,screenPosition:{x:0,y:0},visible:!1};return this.annotationContainer.appendChild(n),this.annotations.set(t,r),this.updateAnnotationPosition(r),t}addAnnotations(e){return e.map(t=>this.addAnnotation(t))}createAnnotationElement(e,t){const i=document.createElement("div");switch(i.className=`panorama-annotation panorama-annotation-${e.type}`,i.dataset.annotationId=t,i.style.cssText=` position: absolute; pointer-events: auto; cursor: pointer; transform: translate(-50%, -50%); transition: opacity 0.2s ease; `,e.type){case Qh.ICON:this.createIconAnnotation(i,e);break;case Qh.TEXT:this.createTextAnnotation(i,e);break;case Qh.LINK:this.createLinkAnnotation(i,e);break}return this.attachAnnotationEvents(i,t),i}createIconAnnotation(e,t){const i=t.size||{width:40,height:40};e.style.width=`${i.width}px`,e.style.height=`${i.height}px`;const n=document.createElement("img");n.src=t.iconUrl,n.style.cssText=` width: 100%; height: 100%; object-fit: contain; display: block; `,n.onerror=()=>{console.error(`Failed to load annotation icon: ${t.iconUrl}`)},e.appendChild(n),t.tooltip&&(e.title=t.tooltip)}createTextAnnotation(e,t){const i=t.style||{};e.style.cssText+=` padding: ${i.padding||"8px 12px"}; background-color: ${i.backgroundColor||"rgba(0, 0, 0, 0.7)"}; color: ${i.color||"#ffffff"}; font-size: ${i.fontSize||14}px'; border-radius: 4px; white-space: nowrap; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; `,e.textContent=t.text,t.tooltip&&(e.title=t.tooltip)}createLinkAnnotation(e,t){const i=t.style||{};if(e.style.cssText+=` padding: 8px 12px; background-color: rgba(59, 130, 246, 0.9); color: ${i.color||"#ffffff"}; font-size: ${i.fontSize||14}px'; border-radius: 4px; text-decoration: ${i.textDecoration||"none"}; display: flex; align-items: center; gap: 8px; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; transition: background-color 0.2s ease; `,e.addEventListener("mouseenter",()=>{e.style.backgroundColor="rgba(37, 99, 235, 0.95)"}),e.addEventListener("mouseleave",()=>{e.style.backgroundColor="rgba(59, 130, 246, 0.9)"}),t.iconUrl){const r=document.createElement("img");r.src=t.iconUrl,r.style.cssText=` width: 16px; height: 16px; display: block; `,e.appendChild(r)}const n=document.createElement("span");n.textContent=t.text||t.url,e.appendChild(n),t.tooltip&&(e.title=t.tooltip)}attachAnnotationEvents(e,t){e.addEventListener("click",i=>{i.stopPropagation();const n=this.annotations.get(t);n&&this.handleClickAnnotation(n)}),e.addEventListener("mouseenter",()=>{const i=this.annotations.get(t);i&&this.handleHoverAnnotation(i)}),e.addEventListener("mouseleave",()=>{this.onHoverAnnotation&&this.onHoverAnnotation(null)})}sphericalToCartesian(e){const t=e.radius??this.sphereRadius;return E2.sphericalToCartesian({...e,radius:t})}updateAnnotationPosition(e){const t=new R(e.worldPosition.x,e.worldPosition.y,e.worldPosition.z),i=this.worldToScreen.worldToScreen(t);e.screenPosition={x:i.x,y:i.y};const n=this.isPositionInFront(t),r=this.isPositionInView(i);e.visible=n&&r,e.visible?(e.element.style.display="block",e.element.style.left=`${i.x}px`,e.element.style.top=`${i.y}px`):e.element.style.display="none"}isPositionInFront(e){const t=new R;return this.camera.getWorldDirection(t),e.clone().normalize().dot(t)>0}isPositionInView(e){const t=this.renderer.domElement.clientWidth,i=this.renderer.domElement.clientHeight;return e.x>=0&&e.x<=t&&e.y>=0&&e.y<=i}update(){this.annotations.forEach(e=>{this.updateAnnotationPosition(e)})}handleClickAnnotation(e){if(e.config.type===Qh.LINK){const t=e.config;window.open(t.url,"_blank")}this.onClickAnnotation&&this.onClickAnnotation(e)}handleHoverAnnotation(e){this.onHoverAnnotation&&this.onHoverAnnotation(e)}setOnClickAnnotation(e){this.onClickAnnotation=e}setOnHoverAnnotation(e){this.onHoverAnnotation=e}removeAnnotation(e){const t=this.annotations.get(e);t&&(t.element.remove(),this.annotations.delete(e))}clearAll(){this.annotations.forEach(e=>{e.element.remove()}),this.annotations.clear()}getAnnotations(){return Array.from(this.annotations.values())}getAnnotation(e){return this.annotations.get(e)}updateCamera(e){this.camera=e,this.worldToScreen.updateCamera(e)}dispose(){this.clearAll(),this.annotationContainer.remove(),this.onClickAnnotation=void 0,this.onHoverAnnotation=void 0}generateId(){return`annotation-${Date.now()}-${Math.random().toString(36).substr(2,9)}`}}class Dz{listeners=new Map;on(e,t){const i=String(e);this.listeners.has(i)||this.listeners.set(i,[]),this.listeners.get(i).push(t)}off(e,t){const i=String(e),n=this.listeners.get(i);if(n){const r=n.indexOf(t);r!==-1&&n.splice(r,1),n.length===0&&this.listeners.delete(i)}}trigger(e,t){const i=String(e),n=this.listeners.get(i);if(n&&n.length>0){const r=[...n];for(const a of r)try{a(t)}catch(o){console.error(`EventModule: Error in event handler for "${i}":`,o)}}}removeAllListeners(e){const t=String(e);this.listeners.delete(t)}clear(){this.listeners.clear()}listenerCount(e){const t=String(e),i=this.listeners.get(t);return i?i.length:0}dispose(){this.clear()}}var Zs=(s=>(s.PanoramaLoadStart="panorama-load-start",s.PanoramaLoadProgress="panorama-load-progress",s.PanoramaLoaded="panorama-loaded",s.PanoramaLoadError="panorama-load-error",s.AnnotationClick="annotation-click",s.AnnotationHover="annotation-hover",s.AnnotationAdd="annotation-add",s.AnnotationRemove="annotation-remove",s.ViewAngleChanged="view-angle-changed",s))(Zs||{});class Nz{sceneModule;cameraModule;renderModule;controlModule;eventModule;panoramaLoader;annotationManager;worldToScreen;isInitialized=!1;version="1.0.0";constructor(e){this.initialize(e)}initialize(e){const t={fov:75,enableZoom:!0,enableRotate:!0,minFov:30,maxFov:90,sphereRadius:500,rotateSpeed:.35,zoomSpeed:.8,enableDamping:!0,dampingFactor:.08,...e},i=document.getElementById(t.containerId);if(!i)throw new Error(`Container with id "${t.containerId}" not found`);try{this.eventModule=new Dz,this.sceneModule=new Ez(t.sphereRadius),this.cameraModule=new Tz(i,t.fov,t.minFov,t.maxFov),this.renderModule=new Cz(i,!0),this.controlModule=new Pz(this.cameraModule,this.renderModule.getDomElement());const n=this.controlModule.getControls();n.enableZoom=t.enableZoom,n.enableRotate=t.enableRotate,n.setRotateSpeed(t.rotateSpeed),n.setZoomSpeed(t.zoomSpeed),n.setEnableDamping(t.enableDamping),n.setDampingFactor(t.dampingFactor),n.setZoomLimits(t.minFov,t.maxFov),n.setOnViewAngleChange((r,a)=>{this.eventModule.trigger(Zs.ViewAngleChanged,{theta:r,phi:a})}),this.panoramaLoader=new Iz,this.worldToScreen=new zt(this.cameraModule.getCamera(),this.renderModule.getRenderer(),this.sceneModule.getScene()),this.annotationManager=new Lz(i,this.cameraModule.getCamera(),this.renderModule.getRenderer(),t.sphereRadius),this.annotationManager.setOnClickAnnotation(r=>{this.eventModule.trigger(Zs.AnnotationClick,{id:r.id,config:r.config,metadata:r.config.metadata})}),this.annotationManager.setOnHoverAnnotation(r=>{this.eventModule.trigger(Zs.AnnotationHover,{annotation:r?{id:r.id,config:r.config,metadata:r.config.metadata}:null})}),this.setupRenderLoop(),this.isInitialized=!0,console.log("EngineKernel720: Initialized successfully")}catch(n){throw console.error("EngineKernel720: Initialization failed",n),n}}setupRenderLoop(){this.renderModule.setOnBeforeRender(()=>{this.controlModule.update(),this.annotationManager.update()}),this.renderModule.startRenderLoop(this.sceneModule.getScene(),this.cameraModule.getCamera())}async loadPanorama(e){this.checkInitialized(),this.eventModule.trigger(Zs.PanoramaLoadStart,{url:e});try{this.panoramaLoader.setOnProgress(i=>{this.eventModule.trigger(Zs.PanoramaLoadProgress,{url:e,progress:i})});const t=await this.panoramaLoader.loadTexture(e);this.sceneModule.updatePanoramaTexture(t),this.eventModule.trigger(Zs.PanoramaLoaded,{url:e,progress:100}),console.log("EngineKernel720: Panorama loaded successfully")}catch(t){throw console.error("EngineKernel720: Failed to load panorama",t),this.eventModule.trigger(Zs.PanoramaLoadError,{url:e,error:t}),t}}async preloadPanoramas(e){this.checkInitialized();try{await this.panoramaLoader.preloadPanoramas(e),console.log(`EngineKernel720: Preloaded ${e.length} panoramas`)}catch(t){throw console.error("EngineKernel720: Failed to preload panoramas",t),t}}addAnnotation(e){this.checkInitialized();const t=this.annotationManager.addAnnotation(e);return this.eventModule.trigger(Zs.AnnotationAdd,{id:t,config:e}),t}addAnnotations(e){return this.checkInitialized(),e.map(t=>this.addAnnotation(t))}removeAnnotation(e){this.checkInitialized(),this.annotationManager.removeAnnotation(e),this.eventModule.trigger(Zs.AnnotationRemove,{id:e})}clearAnnotations(){this.checkInitialized(),this.annotationManager.clearAll()}getAnnotations(){return this.checkInitialized(),this.annotationManager.getAnnotations()}updateInteractionOptions(e){this.checkInitialized(),this.controlModule.updateInteractionOptions(e)}pickPanoramaPoint(e,t){this.checkInitialized();const i=this.renderModule.getRenderer().domElement,n=i.clientWidth,r=i.clientHeight;if(n===0||r===0)return null;const a=new me(e/n*2-1,-(t/r*2-1)),o=this.cameraModule.getCamera(),l=new R(a.x,a.y,.5);l.unproject(o),l.sub(o.position).normalize();const c=this.sceneModule.getSphereRadius(),h=o.position.clone().add(l.multiplyScalar(c)),d=E2.cartesianToSpherical(h.x,h.y,h.z);return{theta:d.theta,phi:d.phi,radius:c}}lookAt(e,t,i){this.checkInitialized(),i&&console.warn("EngineKernel720: Animated lookAt not implemented yet"),this.controlModule.lookAt(e,t)}getViewAngle(){return this.checkInitialized(),this.controlModule.getViewAngle()}setFov(e){this.checkInitialized(),this.cameraModule.setFov(e)}getFov(){return this.checkInitialized(),this.cameraModule.getFov()}on(e,t){this.checkInitialized(),this.eventModule.on(e,t)}off(e,t){this.checkInitialized(),this.eventModule.off(e,t)}resize(e,t){this.checkInitialized();const i=e??this.renderModule.getRenderer().domElement.clientWidth,n=t??this.renderModule.getRenderer().domElement.clientHeight;this.renderModule.resize(i,n),this.cameraModule.updateAspectRatio(i,n),console.log("EngineKernel720: Resized to",i,"x",n)}pauseRendering(){this.checkInitialized(),this.renderModule.pauseRendering()}resumeRendering(){this.checkInitialized(),this.renderModule.resumeRendering(this.sceneModule.getScene(),this.cameraModule.getCamera())}isRenderingPausedState(){return this.isInitialized?this.renderModule.isRenderingPausedState():!0}getVersion(){return this.version}dispose(){if(this.isInitialized)try{this.renderModule.pauseRendering(),this.annotationManager.dispose(),this.panoramaLoader.dispose(),this.controlModule.dispose(),this.cameraModule.dispose(),this.renderModule.dispose(),this.sceneModule.dispose(),this.eventModule.dispose(),this.isInitialized=!1,console.log("EngineKernel720: Disposed successfully")}catch(e){console.error("EngineKernel720: Error during dispose",e)}}checkInitialized(){if(!this.isInitialized)throw new Error("EngineKernel720: Not initialized")}}function kz(s){return new $F(s)}function Oz(s){return new wz(s)}function Uz(s){return new Nz(s)}class xa{engine=null;registry;container;containerId;options;_isInitialized=!1;_isDestroyed=!1;unsubscribeTheme=null;currentMeasureType=null;isMeasureActive=!1;currentSectionMode=null;selectedComponent=null;constructor(e,t){this.registry=t,this.container=e.container,this.container.id?this.containerId=this.container.id:(this.containerId=`engine-container-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,this.container.id=this.containerId),this.options={backgroundColor:"linear-gradient(to bottom, rgb(214, 224, 235), rgb(246, 250, 255))",version:e.version??"v2",showStats:e.showStats??!1,showViewCube:e.showViewCube??!0}}init(){if(this._isInitialized){console.warn("[Engine] Engine already initialized.");return}if(this._isDestroyed){console.error("[Engine] Cannot initialize destroyed engine.");return}try{typeof this.options.backgroundColor=="string"&&(this.container.style.background=this.options.backgroundColor);const e={containerId:this.containerId,backgroundColor:this.options.backgroundColor,version:this.options.version,showStats:this.options.showStats,showViewCube:this.options.showViewCube};if(console.log("引擎配置信息:",e),this.engine=kz(e),!this.engine)throw new Error("Failed to create engine instance");this._isInitialized=!0,this.resize(this.container.clientWidth,this.container.clientHeight),this.unsubscribeTheme=ct.subscribe(t=>{this.setTheme(t)}),this.setTheme(ct.getTheme()),this.engine?.events?.on?(this.engine.events.on("click",t=>{const i=this.registry;console.log("[Engine] 底层 click 事件触发:",t),t&&Array.isArray(t)&&t.length>0&&t[0].url?(this.selectedComponent={url:t[0].url,id:t[0].ids?.[0]},console.log("[Engine] 触发 component:selected:",this.selectedComponent),i.emit("component:selected",this.selectedComponent)):(this.selectedComponent=null,console.log("[Engine] 触发 component:deselected"),i.emit("component:deselected",{}))}),this.engine.events.on("loading_completed",()=>{console.log("[Engine] 底层 LoadingCompleted 事件触发"),this.registry.emit("engine:model-loading-completed",{})})):console.warn("[Engine] 底层引擎不支持 events.on 方法,无法监听点击事件")}catch(e){throw console.error("[Engine] Failed to initialize engine:",e),this._isInitialized=!1,e}}setTheme(e){}setLocales(){}isInitialized(){return this._isInitialized}loadModel(e,t){if(!this._isInitialized||!this.engine){console.error("[Engine] Engine not initialized. Please call init() first.");return}if(!e||e.length===0){console.error("[Engine] Model URLs are required.");return}this.engine.loaderModule.loadModels(e,t)}CameraGoHome(){this.engine.viewCube.CameraGoHome()}onRawEvent(e,t){this.engine?.events?.on(e,t)}offRawEvent(e,t){this.engine?.events?.off(e,t)}pauseRendering(){if(!this._isInitialized||!this.engine){console.warn("[Engine] Engine not initialized.");return}this.engine.pauseRendering()}resumeRendering(){if(!this._isInitialized||!this.engine){console.warn("[Engine] Engine not initialized.");return}this.engine.resumeRendering()}dispose(){if(!this._isInitialized||!this.engine){console.warn("[Engine] Engine not initialized.");return}this.engine.dispose()}resize(e,t){if(!this._isInitialized||!this.engine)return;const i=typeof e=="number"?Math.floor(e):this.container.clientWidth,n=typeof t=="number"?Math.floor(t):this.container.clientHeight;i<=0||n<=0||typeof this.engine.handleWindowResize=="function"&&this.engine.handleWindowResize(i,n)}activateMeasure(e){if(!this._isInitialized||!this.engine?.measure){console.error("[Engine] Cannot activate measure: engine not initialized.");return}if(this.currentMeasureType===e){console.log(`[Engine] Measure ${e} already active, skipping.`);return}this.isMeasureActive||(console.log("[Engine] Activating measure module"),this.engine.measure.active(),this.isMeasureActive=!0),console.log(`[Engine] Activating measure: ${e}`);const t=this.engine.measure;switch(e){case"clearHeight":t.clearHeightMeasure.active();break;case"clearDistance":t.clearDistanceMeasure.active();break;case"distance":t.distanceMeasure.active();break;case"elevation":t.elevationMeasure.active();break;case"point":t.pointMeasure.active();break;case"angle":t.angleMeasure.active();break;case"area":t.areaMeasure.active();break;case"slope":t.slopeMeasure.active();break;default:console.error(`[Engine] Unknown measure type: ${e}`);return}this.currentMeasureType=e}getCurrentMeasureType(){return this.currentMeasureType}deactivateMeasure(){!this._isInitialized||!this.engine?.measure||(console.log("[Engine] Deactivating measure"),this.engine.measure.disActive(),this.engine.measure.clearAll(),this.isMeasureActive=!1,this.currentMeasureType=null)}clearAllMeasures(){!this._isInitialized||!this.engine?.measure||(console.log("[Engine] Clearing all measures"),this.engine.measure.clearAll())}saveMeasureSetting(e){!this._isInitialized||!this.engine?.measure||this.engine.measure.saveSetting?.(e)}setClearHeightDirection(e){!this._isInitialized||!this.engine?.measure||(console.log(`[Engine] Setting clearHeight direction: ${e}`),this.engine.measure.clearHeightMeasure.setDirection(e))}setClearHeightSelectType(e){!this._isInitialized||!this.engine?.measure||(console.log(`[Engine] Setting clearHeight selectType: ${e}`),this.engine.measure.clearHeightMeasure.setSelectType(e))}activeSection(e){if(!this._isInitialized||!this.engine?.clipping){console.error("[Engine] Cannot activate section: engine not initialized.");return}if(this.currentSectionMode===e){console.log(`[Engine] Section ${e} already active, skipping.`);return}console.log(`[Engine] Activating section: ${e}`),this.engine.clipping.active(e),this.currentSectionMode=e}getCurrentSectionMode(){return this.currentSectionMode}setSectionBoxRange(e){if(!this._isInitialized||!this.engine?.clipping){console.error("[Engine] Cannot set section box range: engine not initialized.");return}this.engine.clipping.updateClippingValue(e)}deactivateSection(){!this._isInitialized||!this.engine?.clipping||(console.log("[Engine] Deactivating all sections"),this.engine.clipping.disActive(),this.currentSectionMode=null)}hideSection(){if(!this._isInitialized||!this.engine?.clipping){console.error("[Engine] Cannot hide section: engine not initialized.");return}console.log("[Engine] Hiding section"),this.engine.clipping.disabled()}recoverSection(){if(!this._isInitialized||!this.engine?.clipping){console.error("[Engine] Cannot recover section: engine not initialized.");return}console.log("[Engine] Recovering section"),this.engine.clipping.recover()}fitSectionBoxToModel(){if(!this._isInitialized||!this.engine){console.error("[Engine] Cannot fit section box: engine not initialized.");return}const e=this.engine.engineStatus?.highlightModels;e&&(console.log("[Engine] Fitting section box to model"),this.engine.clipping?.clippingModel(e))}scaleSectionBox(){if(!this._isInitialized||!this.engine?.clipping){console.error("[Engine] Cannot scale section box: engine not initialized.");return}this.engine.clipping.scaleBox()}reverseSection(){if(!this._isInitialized||!this.engine?.clipping){console.error("[Engine] Cannot reverse section: engine not initialized.");return}this.engine.clipping.reverse()}switchCamera(){if(!this._isInitialized||!this.engine?.cameraModule){console.warn("[Engine] Cannot switch camera: engine not initialized.");return}this.engine.cameraModule.switchCurrentCamera()}getCameraType(){return!this._isInitialized||!this.engine?.cameraModule?"perspective":this.engine.cameraModule.getCameraType()===1?"orthographic":"perspective"}getRenderMode(){return!this._isInitialized||!this.engine?.engineModelModule?"balance":this.engine.engineModelModule.getCurrentMode()}setRenderMode(e){if(!this._isInitialized||!this.engine?.engineModelModule){console.warn("[Engine] Cannot set render mode: engine not initialized.");return}try{this.engine.engineModelModule.setMode(e)}catch(t){console.warn("[Engine] Failed to set render mode:",t)}}normalizePercent(e,t){return Number.isFinite(e)?Math.min(100,Math.max(0,Math.round(e))):t}getSettingApi(){return!this._isInitialized||!this.engine?.setting?null:this.engine.setting}callSettingMethod(e,...t){const i=this.getSettingApi();if(!i)return;const n=i[e];if(typeof n=="function")return n.apply(this.engine.setting,t)}hasSettingMethod(e){const t=this.getSettingApi();return t?typeof t[e]=="function":!1}mergeSettingsWithDefaults(e){const t=e.display?.groundId??"0",i=typeof e.display?.showGround=="boolean"?e.display.showGround:t!=="0"&&t!=="";return{render:{mode:e.render?.mode??"advanced",contrast:this.normalizePercent(e.render?.contrast??50,50),saturation:this.normalizePercent(e.render?.saturation??50,50),shadowIntensity:this.normalizePercent(e.render?.shadowIntensity??50,50),lightIntensity:this.normalizePercent(e.render?.lightIntensity??50,50),gtaoIntensity:this.normalizePercent(e.render?.gtaoIntensity??50,50)},display:{showEdge:!!e.display?.showEdge,edgeOpacity:this.normalizePercent(e.display?.edgeOpacity??30,30),showGrid:!!e.display?.showGrid,showLevel:!!e.display?.showLevel,showGround:i,groundId:t,groundHeight:Number.isFinite(e.display?.groundHeight)?Number(e.display?.groundHeight):0},environment:{type:e.environment?.type??"none",hdrId:e.environment?.hdrId??"0",hdrIntensity:this.normalizePercent(e.environment?.hdrIntensity??20,20),skyPreset:e.environment?.skyPreset??"sunrise_clear",skyParams:e.environment?.skyParams??{},skyIntensity:this.normalizePercent(e.environment?.skyIntensity??20,20)}}}getPresetLists(){const e={ground:[],hdr:[],sky:[]},t=this.getSettingApi();if(!t)return e;const i=t.getPresetLists,n=typeof i=="function"?i.call(this.engine.setting):null,r=this.getGroundList().map(o=>({id:o.id,names:[o.name,o.name,o.name]})),a=this.getHDRBackgroundList().map(o=>({id:o.id,names:[o.name,o.name,o.name]}));return{ground:Array.isArray(n?.ground)&&n.ground.length>0?n.ground:r,hdr:Array.isArray(n?.hdr)&&n.hdr.length>0?n.hdr:a,sky:Array.isArray(n?.sky)?n.sky:[]}}getSettings(){const e=this.callSettingMethod("getSettings");return e&&typeof e=="object"?this.mergeSettingsWithDefaults(e):{render:{mode:this.getRenderMode(),contrast:this.normalizePercent(this.getSceneContrast(),50),saturation:this.normalizePercent(this.getSceneSaturation(),50),shadowIntensity:50,lightIntensity:this.normalizePercent(this.getAmbientLightIntensity(),50),gtaoIntensity:50},display:{showEdge:this.getModelEdgeActive(),edgeOpacity:30,showGrid:!1,showLevel:!1,showGround:this.getGroundId()!=="0"&&this.getGroundId()!=="",groundId:this.getGroundId()||"0",groundHeight:this.getGroundElevation()},environment:{type:this.getHDRBackgroundId()&&this.getHDRBackgroundId()!=="0"?"hdr":"none",hdrId:this.getHDRBackgroundId()||"0",hdrIntensity:20,skyPreset:"sunrise_clear",skyParams:{},skyIntensity:20}}}async setSettings(e){if(!this._isInitialized||!this.engine?.setting){console.warn("[Engine] Cannot set settings: engine not initialized.");return}if(this.hasSettingMethod("setSettings"))try{const t=this.callSettingMethod("setSettings",e);await Promise.resolve(t);return}catch(t){console.warn("[Engine] Native setSettings failed, fallback to compatibility mode.",t)}if(e.render?.mode&&this.setRenderMode(e.render.mode),typeof e.render?.lightIntensity=="number"&&this.setAmbientLightIntensity(e.render.lightIntensity),typeof e.render?.contrast=="number"&&this.setSceneContrast(e.render.contrast),typeof e.render?.saturation=="number"&&this.setSceneSaturation(e.render.saturation),typeof e.display?.showEdge=="boolean"&&(e.display.showEdge?this.activeModelEdge():this.disActiveModelEdge()),typeof e.display?.edgeOpacity=="number"&&this.callSettingMethod("setEdgeOpacity",e.display.edgeOpacity),typeof e.display?.showGrid=="boolean"&&this.callSettingMethod("setShowGrid",e.display.showGrid),typeof e.display?.showLevel=="boolean"&&this.callSettingMethod("setShowLevel",e.display.showLevel),typeof e.display?.groundId=="string"&&this.setGroundId(e.display.groundId),typeof e.display?.groundHeight=="number"&&this.setGroundElevation(e.display.groundHeight),typeof e.environment?.type=="string"){const t=this.callSettingMethod("setEnvironmentType",e.environment.type);t!==void 0?await Promise.resolve(t):e.environment.type==="none"&&this.setHDRBackgroundId("0")}if(typeof e.environment?.hdrId=="string"){const t=this.callSettingMethod("setHdrId",e.environment.hdrId);t!==void 0?await Promise.resolve(t):this.setHDRBackgroundId(e.environment.hdrId)}typeof e.environment?.hdrIntensity=="number"&&this.callSettingMethod("setHdrIntensity",e.environment.hdrIntensity),typeof e.environment?.skyPreset=="string"&&this.callSettingMethod("setSkyPreset",e.environment.skyPreset),typeof e.environment?.skyIntensity=="number"&&this.callSettingMethod("setSkyIntensity",e.environment.skyIntensity),e.environment?.skyParams&&typeof e.environment.skyParams=="object"&&this.callSettingMethod("setSkyParams",e.environment.skyParams),typeof e.render?.shadowIntensity=="number"&&this.callSettingMethod("setShadowIntensity",e.render.shadowIntensity),typeof e.render?.gtaoIntensity=="number"&&this.callSettingMethod("setGtaoIntensity",e.render.gtaoIntensity)}async resetToDefault(){const t=this.getSettingApi()?.resetToDefault;if(typeof t=="function"){await Promise.resolve(t.call(this.engine.setting));return}await this.setSettings({render:{mode:"advanced",contrast:50,saturation:50,shadowIntensity:50,lightIntensity:50,gtaoIntensity:50},display:{showEdge:!1,edgeOpacity:30,showGrid:!1,showLevel:!1,showGround:!1,groundId:"0",groundHeight:0},environment:{type:"none",hdrId:"0",hdrIntensity:20,skyPreset:"sunrise_clear",skyParams:{},skyIntensity:20}})}activeModelEdge(){if(!this._isInitialized||!this.engine?.modelEdge){console.warn("[Engine] Cannot active model edge: engine not initialized.");return}this.engine.modelEdge.active()}disActiveModelEdge(){!this._isInitialized||!this.engine?.modelEdge||this.engine.modelEdge.disActive()}getModelEdgeActive(){return!this._isInitialized||!this.engine?.modelEdge?!1:this.engine.modelEdge.getActive?.()??!1}setAmbientLightIntensity(e){if(!this._isInitialized||!this.engine?.setting){console.warn("[Engine] Cannot set ambient light intensity: engine not initialized.");return}this.engine.setting.setAmbientLightIntensity(e)}getAmbientLightIntensity(){return!this._isInitialized||!this.engine?.setting?50:this.engine.setting.getAmbientLightIntensity?.()??50}setSceneContrast(e){if(!this._isInitialized||!this.engine?.setting){console.warn("[Engine] Cannot set scene contrast: engine not initialized.");return}this.engine.setting.setSceneContrast(e)}getSceneContrast(){return!this._isInitialized||!this.engine?.setting?50:this.engine.setting.getSceneContrast?.()??50}setSceneSaturation(e){if(!this._isInitialized||!this.engine?.setting){console.warn("[Engine] Cannot set scene saturation: engine not initialized.");return}this.engine.setting.setSceneSaturation(e)}getSceneSaturation(){return!this._isInitialized||!this.engine?.setting?50:this.engine.setting.getSceneSaturation?.()??50}getHDRBackgroundList(){return!this._isInitialized||!this.engine?.setting?[]:this.engine.setting.getHDRBackground?.()??[]}setHDRBackgroundId(e){if(!this._isInitialized||!this.engine?.setting){console.warn("[Engine] Cannot set HDR background: engine not initialized.");return}this.engine.setting.setHDRBackgroundId(e)}getHDRBackgroundId(){return!this._isInitialized||!this.engine?.setting?"":this.engine.setting.getHDRBackgroundId?.()??""}setHDRBackgroundVisibility(e){if(!this._isInitialized||!this.engine?.setting){console.warn("[Engine] Cannot set HDR background visibility: engine not initialized.");return}this.engine.setting.setHDRBackgroundVisibility(e)}getHDRBackgroundVisibility(){return!this._isInitialized||!this.engine?.setting?!0:this.engine.setting.getHDRBackgroundVisibility?.()??!0}getGroundList(){return!this._isInitialized||!this.engine?.setting?[]:this.engine.setting.getGroundList?.()??[]}setGroundId(e){if(!this._isInitialized||!this.engine?.setting){console.warn("[Engine] Cannot set ground: engine not initialized.");return}this.engine.setting.setGroundId(e)}getGroundId(){return!this._isInitialized||!this.engine?.setting?"":this.engine.setting.getGroundId?.()??""}setGroundElevation(e){if(!this._isInitialized||!this.engine?.setting){console.warn("[Engine] Cannot set ground elevation: engine not initialized.");return}this.engine.setting.setGroundElevation(e)}getGroundElevation(){return!this._isInitialized||!this.engine?.setting?0:this.engine.setting.getGroundElevation?.()??0}isWalkModeActive=!1;activateFirstPersonMode(){if(!this._isInitialized||!this.engine){console.error("[Engine] Cannot activate first person mode: engine not initialized.");return}if(!this.engine.controlModule){console.error("[Engine] Control module not available.");return}if(this.isWalkModeActive){console.log("[Engine] First person mode already active, skipping.");return}console.log("[Engine] Activating first person mode"),this.engine.controlModule.switchFirstPersonMode(),this.loadWalkSettings(),this.isWalkModeActive=!0}deactivateFirstPersonMode(){!this._isInitialized||!this.engine?.controlModule||this.isWalkModeActive&&(console.log("[Engine] Deactivating first person mode"),this.engine.controlModule.switchDefaultMode(),this.isWalkModeActive=!1)}static WALK_SPEED_KEY="bim-walk-speed";static WALK_GRAVITY_KEY="bim-walk-gravity";static WALK_COLLISION_KEY="bim-walk-collision";setWalkSpeed(e){if(!this._isInitialized||!this.engine?.controlModule){console.error("[Engine] Cannot set walk speed: engine not initialized.");return}localStorage.setItem(xa.WALK_SPEED_KEY,String(e)),this.engine.controlModule.setMoveSpeed(e)}setWalkGravity(e){if(!this._isInitialized||!this.engine?.controlModule){console.error("[Engine] Cannot set walk gravity: engine not initialized.");return}localStorage.setItem(xa.WALK_GRAVITY_KEY,String(e)),this.engine.controlModule.setApplyGravity(e)}setWalkCollision(e){if(!this._isInitialized||!this.engine?.controlModule){console.error("[Engine] Cannot set walk collision: engine not initialized.");return}localStorage.setItem(xa.WALK_COLLISION_KEY,String(e)),this.engine.controlModule.setApplyCollision(e)}loadWalkSettings(){if(!this.engine?.controlModule)return;const e=localStorage.getItem(xa.WALK_SPEED_KEY),t=localStorage.getItem(xa.WALK_GRAVITY_KEY),i=localStorage.getItem(xa.WALK_COLLISION_KEY);this.engine.controlModule.setMoveSpeed(e?Number(e):1),this.engine.controlModule.setApplyGravity(t==="true"),this.engine.controlModule.setApplyCollision(i==="true")}toggleMiniMap(){if(!this._isInitialized||!this.engine){console.error("[Engine] Cannot toggle mini map: engine not initialized.");return}this.engine.minMap?.toggle()}getMiniMapState(){return!this._isInitialized||!this.engine?!1:this.engine.minMap?.getstate()??!1}isFirstPersonModeActive(){return this.isWalkModeActive}getSelectedComponent(){return this.selectedComponent}getComponentProperties(e,t,i){if(!this._isInitialized||!this.engine){console.error("[Engine] Cannot get component properties: engine not initialized.");return}if(!this.engine.modelProperties){console.error("[Engine] modelProperties not available");return}console.log("[Engine] Getting component properties:",{url:e,id:t}),this.engine.modelProperties.getModelProperties(e,t,i)}getModelPosition(e){return!this._isInitialized||!this.engine?(console.error("[Engine] Cannot get model position: engine not initialized."),null):this.engine.issueReport?.getMoldePosition?(console.log("[Engine] Getting model position:",e),this.engine.issueReport.getMoldePosition(e)):(console.error("[Engine] getMoldePosition method not available in issueReport"),null)}jumpToCamera(e){if(!this._isInitialized||!this.engine)return console.error("[Engine] Cannot jump to camera: engine not initialized."),!1;if(!this.engine.issueReport?.jumptoCamera)return console.error("[Engine] jumptoCamera method not available in issueReport"),!1;console.log("[Engine] Jumping to camera:",e);try{return this.engine.issueReport.jumptoCamera(e),!0}catch(t){return console.error("[Engine] Failed to jump to camera:",t),!1}}getTypeTreeData(){return!this._isInitialized||!this.engine?.modelTree?[]:this.engine.modelTree.getTypeTreeData()}getLevelTreeData(){return!this._isInitialized||!this.engine?.modelTree?[]:this.engine.modelTree.getLevelTreeData()}getMajorTreeData(){return!this._isInitialized||!this.engine?.modelTree?[]:this.engine.modelTree.getMajorTreeData()}activateZoomBox(){if(!this._isInitialized||!this.engine){console.warn("[Engine] Engine not initialized.");return}this.engine.rangeScale?.active()}getEngineInfo(){return!this._isInitialized||!this.engine?(console.warn("[Engine] Engine not initialized."),null):this.engine.engineInfo.getEngineInfo()}pathRoamingAddPoint(){if(!this._isInitialized||!this.engine?.pathRoaming){console.warn("[Engine] pathRoaming not available");return}this.engine.pathRoaming.addPoint(0)}pathRoamingRemovePoint(e){if(!this._isInitialized||!this.engine?.pathRoaming){console.warn("[Engine] pathRoaming not available");return}this.engine.pathRoaming.removePoint(e)}pathRoamingClearPoints(){if(!this._isInitialized||!this.engine?.pathRoaming){console.warn("[Engine] pathRoaming not available");return}this.engine.pathRoaming.clearPoints()}pathRoamingGetPoints(){return!this._isInitialized||!this.engine?.pathRoaming?(console.warn("[Engine] pathRoaming not available"),[]):this.engine.pathRoaming.getPoints()??[]}pathRoamingJumpToPoint(e){if(!this._isInitialized||!this.engine?.pathRoaming){console.warn("[Engine] pathRoaming not available");return}this.engine.pathRoaming.jumpToPoint(e)}pathRoamingPlay(e){if(!this._isInitialized||!this.engine?.pathRoaming){console.warn("[Engine] pathRoaming not available");return}this.engine.pathRoaming.play(e)}pathRoamingStop(){if(!this._isInitialized||!this.engine?.pathRoaming){console.warn("[Engine] pathRoaming not available");return}this.engine.pathRoaming.stop()}getHighlightModels(){return!this._isInitialized||!this.engine?null:this.engine.engineStatus?.highlightModels??null}highlightModel(e){if(!this._isInitialized||!this.engine?.modelToolModule){console.warn("[Engine] Cannot highlight model: engine not initialized.");return}const t=this.sanitizeModelParams(e);if(t.length)try{this.engine.modelToolModule.highlightModel(t)}catch(i){console.warn("[Engine] highlightModel failed:",i)}}unhighlightAllModels(){if(!this._isInitialized||!this.engine?.modelToolModule){console.warn("[Engine] Cannot unhighlight models: engine not initialized.");return}this.engine.modelToolModule.unhighlightAllModels()}viewScaleToModel(e){if(!this._isInitialized||!this.engine?.modelToolModule){console.warn("[Engine] Cannot view scale to model: engine not initialized.");return}const t=this.sanitizeModelParams(e);if(t.length)try{this.engine.modelToolModule.viewScaleToModel(t)}catch(i){console.warn("[Engine] viewScaleToModel failed:",i)}}hideModels(e){if(!this._isInitialized||!this.engine?.modelToolModule){console.warn("[Engine] Cannot hide models: engine not initialized.");return}const t=this.sanitizeModelParams(e);if(t.length)try{this.engine.modelToolModule.hideModel(t)}catch(i){console.warn("[Engine] hideModels failed:",i)}}showModel(e){if(!this._isInitialized||!this.engine?.modelToolModule){console.warn("[Engine] Cannot show model: engine not initialized.");return}const t=this.sanitizeModelParams(e);if(t.length)try{this.engine.modelToolModule.showModel(t)}catch(i){console.warn("[Engine] showModel failed:",i)}}sanitizeModelParams(e){if(!Array.isArray(e))return[];const t=a=>a.replace(/\/+$/,""),i=Array.isArray(this.engine?.models)?this.engine.models:[],n=new Map;for(const a of i)a?.url&&n.set(t(a.url),a);const r=[];for(const a of e){if(!a||typeof a.url!="string"||!a.url||!Array.isArray(a.ids))continue;const o=n.get(t(a.url));if(!o||!(o.nodesMap instanceof Map))continue;const l=new Set;for(const h of a.ids){if(!Number.isFinite(h))continue;const d=Number(h);if(!Number.isInteger(d))continue;const p=o.nodesMap.get(d);!p||!Array.isArray(p.indexes)||p.indexes.length===0||l.add(d)}const c=Array.from(l);c.length&&r.push({url:a.url,ids:c})}return r}translucentModels(e){if(!this._isInitialized||!this.engine?.modelToolModule){console.warn("[Engine] Cannot translucent models: engine not initialized.");return}e&&this.engine.modelToolModule.translucentModel(e)}unTranslucentModel(){if(!this._isInitialized||!this.engine?.modelToolModule){console.warn("[Engine] Cannot cancel translucent: engine not initialized.");return}this.engine.modelToolModule.unTranslucentModel()}isolateModels(e){if(!this._isInitialized||!this.engine?.modelToolModule){console.warn("[Engine] Cannot isolate models: engine not initialized.");return}e&&this.engine.modelToolModule.isolateModel(e)}translucentOtherModels(e){if(!this._isInitialized||!this.engine?.modelToolModule){console.warn("[Engine] Cannot translucent other models: engine not initialized.");return}e&&this.engine.modelToolModule.translucentOtherModel(e)}showAllModels(){if(!this._isInitialized||!this.engine?.modelToolModule){console.warn("[Engine] Cannot show all models: engine not initialized.");return}this.deactivateSection(),this.engine.modelToolModule.showAllModels()}batchSelectSameTypeModel(e){if(!this._isInitialized||!this.engine?.modelToolModule){console.warn("[Engine] Cannot batch select: engine not initialized.");return}e&&this.engine.modelToolModule.batchSelectSameTypeModel(e)}batchSelectSameLevelModel(e){if(!this._isInitialized||!this.engine?.modelToolModule){console.warn("[Engine] Cannot batch select: engine not initialized.");return}e&&this.engine.modelToolModule.batchSelectSameLevelModel(e)}batchSelectSameLevelTypeModel(e){if(!this._isInitialized||!this.engine?.modelToolModule){console.warn("[Engine] Cannot batch select: engine not initialized.");return}e&&this.engine.modelToolModule.batchSelectSameLevelTypeModel(e)}destroy(){this._isDestroyed||(this.deactivateMeasure(),this.unsubscribeTheme&&(this.unsubscribeTheme(),this.unsubscribeTheme=null),this.engine&&(this.engine.dispose(),this.engine=null),this.container.innerHTML="",this.currentMeasureType=null,this.isMeasureActive=!1,this._isDestroyed=!0,this._isInitialized=!1)}}class Bz{element;content=null;isVisible=!1;onCloseCallback;options;mouseDownTime=0;mouseDownX=0;mouseDownY=0;CLICK_THRESHOLD=200;MOVE_THRESHOLD=5;constructor(e){this.options=e,this.element=document.createElement("div"),this.element.className=`bim-right-key ${e?.className||""}`,e?.zIndex&&(this.element.style.zIndex=e.zIndex.toString()),document.body.appendChild(this.element)}init(){document.addEventListener("mousedown",this.handleGlobalClick),this.element.addEventListener("contextmenu",e=>{e.preventDefault(),e.stopPropagation()}),this.options?.container&&(this.options.container.addEventListener("mousedown",this.handleContainerMouseDown),this.options.container.addEventListener("mouseup",this.handleContainerMouseUp),this.options.container.addEventListener("contextmenu",this.handleContainerContextMenu))}setTheme(e){}setLocales(){}destroy(){document.removeEventListener("mousedown",this.handleGlobalClick),this.options?.container&&(this.options.container.removeEventListener("mousedown",this.handleContainerMouseDown),this.options.container.removeEventListener("mouseup",this.handleContainerMouseUp),this.options.container.removeEventListener("contextmenu",this.handleContainerContextMenu)),this.unmountContent(),this.element.remove()}handleContainerMouseDown=e=>{e.button===2&&(this.mouseDownTime=Date.now(),this.mouseDownX=e.clientX,this.mouseDownY=e.clientY)};handleContainerMouseUp=e=>{if(e.button!==2||Date.now()-this.mouseDownTime>this.CLICK_THRESHOLD)return;const i=e.clientX-this.mouseDownX,n=e.clientY-this.mouseDownY;i*i+n*n>this.MOVE_THRESHOLD*this.MOVE_THRESHOLD||this.options?.onContext&&this.options.onContext(e)};handleContainerContextMenu=e=>{e.preventDefault()};setOnClose(e){this.onCloseCallback=e}mount(e){this.unmountContent(),this.content=e,this.element.appendChild(e.getElement())}unmountContent(){this.content&&(this.content.destroy(),this.element.innerHTML="",this.content=null)}show(e,t){this.element.classList.add("visible"),this.isVisible=!0,this.element.style.left=`${e}px`,this.element.style.top=`${t}px`;const i=this.element.getBoundingClientRect(),n=window.innerWidth,r=window.innerHeight;let a=e,o=t;e+i.width>n&&(a=e-i.width),t+i.height>r&&(o=t-i.height),this.element.style.left=`${a}px`,this.element.style.top=`${o}px`}hide(){this.element.classList.remove("visible"),this.isVisible=!1,this.unmountContent(),this.onCloseCallback&&this.onCloseCallback()}handleGlobalClick=e=>{this.isVisible&&(this.element.contains(e.target)||this.hide())}}class ay{element;options;unsubscribeLocale=null;unsubscribeTheme=null;activeSubMenu=null;constructor(e){this.options=e,this.element=document.createElement("ul"),this.element.className="bim-menu"}init(){this.render(),this.unsubscribeLocale=$t.subscribe(()=>{this.setLocales()}),this.unsubscribeTheme=ct.subscribe(e=>{this.setTheme(e)})}setTheme(e){const t=this.element.style;t.setProperty("--bim-bg-elevated",e.bgElevated),t.setProperty("--bim-text-primary",e.textPrimary),t.setProperty("--bim-divider",e.divider),t.setProperty("--bim-component-bg-hover",e.componentBgHover),t.setProperty("--bim-shadow-lg",e.shadowLg)}setLocales(){this.element.innerHTML="",this.render()}destroy(){this.unsubscribeLocale&&(this.unsubscribeLocale(),this.unsubscribeLocale=null),this.unsubscribeTheme&&(this.unsubscribeTheme(),this.unsubscribeTheme=null),this.closeSubMenu(),this.element.remove()}getElement(){return this.element}hasAnyIcon(e){return e.some(t=>t.icon?!0:t.children?this.hasAnyIcon(t.children):!1)}render(){const{items:e,groupOrder:t}=this.options;this.hasAnyIcon(e)?this.element.classList.add("has-icons"):this.element.classList.remove("has-icons");const i=new Map,n="default";e.forEach(a=>{const o=a.group||n;i.has(o)||i.set(o,[]),i.get(o).push(a)});let r=[];if(t){r=t.filter(a=>i.has(a));for(const a of i.keys())r.includes(a)||r.push(a)}else r=Array.from(i.keys());r.forEach((a,o)=>{if(o>0){const c=document.createElement("li");c.className="bim-menu-divider",this.element.appendChild(c)}const l=i.get(a);l.sort((c,h)=>(c.order||0)-(h.order||0)),l.forEach(c=>{if(c.visible!==!1&&(this.element.appendChild(this.createItemElement(c)),c.divider)){const h=document.createElement("li");h.className="bim-menu-divider",this.element.appendChild(h)}})})}createItemElement(e){const t=document.createElement("li"),i=!e.disabled;t.className=`bim-menu-item ${i?"":"disabled"}`;const n=document.createElement("div");n.className="bim-menu-item-icon",e.icon&&(n.innerHTML=e.icon),t.appendChild(n);const r=document.createElement("div");r.className="bim-menu-item-label",r.textContent=Ee(e.label),t.appendChild(r);const a=e.children,o=a&&a.length>0;if(o){const l=document.createElement("div");l.className="bim-menu-item-arrow",l.innerHTML='',t.appendChild(l),t.addEventListener("mouseenter",()=>this.openSubMenu(e,t))}else t.addEventListener("mouseenter",()=>this.closeSubMenu());return i&&t.addEventListener("click",l=>{l.stopPropagation(),console.log(`[BimMenu] Clicked item: ${e.id}`),o||(e.onClick?(console.log(`[BimMenu] Executing onClick for ${e.id}`),e.onClick()):console.warn(`[BimMenu] No onClick handler for ${e.id}`))}),t}openSubMenu(e,t){const i=e.children;if(!i||i.length===0)return;this.closeSubMenu();const n=document.createElement("div");n.style.position="fixed",n.style.zIndex="10001";const r=t.getBoundingClientRect();n.style.top=`${r.top}px`,n.style.left=`${r.right}px`,n.addEventListener("mousedown",l=>l.stopPropagation());const a=new ay({items:i});a.init(),n.appendChild(a.element),document.body.appendChild(n),this.activeSubMenu={menu:a,container:n};const o=n.getBoundingClientRect();o.right>window.innerWidth&&(n.style.left=`${r.left-o.width}px`)}closeSubMenu(){this.activeSubMenu&&(this.activeSubMenu.menu.destroy(),this.activeSubMenu.container.remove(),this.activeSubMenu=null)}}class oy extends jn{container;rightKeyPanel;contextHandlers=[];constructor(e,t){super(t),this.container=e,this.rightKeyPanel=new Bz({zIndex:9e3,container:this.container,onContext:this.handleContextMenu}),this.rightKeyPanel.init()}destroy(){this.rightKeyPanel.destroy(),super.destroy()}registerHandler(e){this.contextHandlers.push(e)}showMenu(e,t,i,n){if(!i||i.length===0)return;const r=new ay({items:i,groupOrder:n});r.init(),this.rightKeyPanel.mount(r),this.rightKeyPanel.show(e,t)}hide(){this.rightKeyPanel.hide()}handleContextMenu=e=>{let t=null;for(const i of this.contextHandlers){const n=i(e);n&&n.length>0&&(t||(t=[]),t=t.concat(n))}t&&t.length>0?this.showMenu(e.clientX,e.clientY,t):this.hide()}}class T2 extends jn{container;engineInstance=null;rightKey=null;constructor(e,t){super(t),this.container=e}getEngineComponent(){return this.engineInstance}initialize(e){this.engineInstance&&this.engineInstance.isInitialized()&&(console.warn("[EngineManager] 3D Engine already initialized. Destroying old instance..."),this.engineInstance.destroy(),this.engineInstance=null);try{return this.engineInstance=new xa({container:this.container,...e},this.registry),this.engineInstance.init(),this.rightKey=new oy(this.container,this.registry),this.rightKey.registerHandler(t=>{const i=this.engineInstance?.getSelectedComponent(),n=[];return i&&(n.push({id:"componentDetail",label:"menu.componentDetail",group:"component",order:1,divider:!0,onClick:()=>{this.registry.componentDetail?.show(),this.rightKey?.hide()}}),n.push({id:"hideSelected",label:"menu.hideSelected",group:"component",order:2,onClick:()=>{const r=this.engineInstance?.getHighlightModels();r&&this.engineInstance?.hideModels(r),this.rightKey?.hide()}}),n.push({id:"transparentSelected",label:"menu.transparentSelected",group:"component",order:3,onClick:()=>{const r=this.engineInstance?.getHighlightModels();r&&this.engineInstance?.translucentModels(r),this.rightKey?.hide()}}),n.push({id:"cancelTranslucent",label:"menu.cancelTranslucent",group:"component",order:4,onClick:()=>{this.engineInstance?.unTranslucentModel(),this.rightKey?.hide()}}),n.push({id:"isolateSelected",label:"menu.isolateSelected",group:"component",order:5,divider:!0,children:[{id:"hideOthers",label:"menu.hideOthers",onClick:()=>{const r=this.engineInstance?.getHighlightModels();r&&this.engineInstance?.isolateModels(r),this.rightKey?.hide()}},{id:"transparentOthers",label:"menu.transparentOthers",onClick:()=>{const r=this.engineInstance?.getHighlightModels();r&&this.engineInstance?.translucentOtherModels(r),this.rightKey?.hide()}}]}),n.push({id:"quickSelect",label:"menu.quickSelect",group:"component",order:6,children:[{id:"selectSameType",label:"menu.selectSameType",onClick:()=>{const r=this.engineInstance?.getHighlightModels();r&&this.engineInstance?.batchSelectSameTypeModel(r),this.rightKey?.hide()}},{id:"selectSameLevel",label:"menu.selectSameLevel",onClick:()=>{const r=this.engineInstance?.getHighlightModels();r&&this.engineInstance?.batchSelectSameLevelModel(r),this.rightKey?.hide()}},{id:"selectSameLevelType",label:"menu.selectSameLevelType",onClick:()=>{const r=this.engineInstance?.getHighlightModels();r&&this.engineInstance?.batchSelectSameLevelTypeModel(r),this.rightKey?.hide()}}]}),n.push({id:"fitSectionBox",label:"menu.fitSectionBox",group:"component",order:7,onClick:()=>{this.engineInstance?.fitSectionBoxToModel(),this.rightKey?.hide()}})),n.push({id:"showAll",label:"menu.showAll",group:"component",order:8,onClick:()=>{this.engineInstance?.showAllModels(),this.emit("menu:show-all",{}),this.rightKey?.hide()}}),n}),this.engineInstance.isInitialized()}catch(t){return console.error("[EngineManager] Failed to initialize 3D engine:",t),this.engineInstance=null,!1}}isInitialized(){return this.engineInstance!==null&&this.engineInstance.isInitialized()}loadModel(e,t){if(!this.engineInstance){console.warn("[EngineManager] 3D Engine not initialized.");return}this.engineInstance.loadModel(e,t)}pauseRendering(){if(!this.engineInstance){console.warn("[EngineManager] 3D Engine not initialized.");return}this.engineInstance.pauseRendering()}resumeRendering(){if(!this.engineInstance){console.warn("[EngineManager] 3D Engine not initialized.");return}this.engineInstance.resumeRendering()}getModelPosition(e){return this.engineInstance?this.engineInstance.getModelPosition(e):(console.warn("[EngineManager] 3D Engine not initialized."),null)}jumpToCamera(e){return this.engineInstance?this.engineInstance.jumpToCamera(e):(console.warn("[EngineManager] 3D Engine not initialized."),!1)}destroy(){this.engineInstance&&(this.engineInstance.destroy(),this.engineInstance=null),this.rightKey&&(this.rightKey.destroy(),this.rightKey=null),super.destroy()}}var ni=(s=>(s[s.Unchecked=0]="Unchecked",s[s.Checked=1]="Checked",s[s.Indeterminate=2]="Indeterminate",s))(ni||{});class Fz{config;element;children=[];parent=null;checkState=ni.Unchecked;contentEl;switcherEl;checkboxEl=null;titleEl;actionsEl;childrenContainer;onExpandChange;onCheckChange;onNodeClick;renderActions;constructor(e,t,i){this.config=e,this.onExpandChange=i.onExpand,this.onCheckChange=i.onCheck,this.onNodeClick=i.onClick,this.renderActions=t.renderActions,this.checkState=e.checked?ni.Checked:ni.Unchecked,this.element=this.createDom(t)}createDom(e){const t=document.createElement("div");t.className="bim-tree-node",this.config.disabled&&t.classList.add("is-disabled"),this.contentEl=document.createElement("div"),this.contentEl.className="bim-tree-node-content",this.switcherEl=document.createElement("span"),this.switcherEl.className="bim-tree-switcher",this.switcherEl.innerHTML='';const i=this.config.children&&this.config.children.length>0;if(i?this.config.expanded&&this.switcherEl.classList.add("is-expanded"):this.switcherEl.classList.add("is-hidden"),this.switcherEl.addEventListener("click",r=>{r.stopPropagation(),this.toggleExpand()}),this.contentEl.appendChild(this.switcherEl),e.checkable!==!1&&(this.checkboxEl=document.createElement("span"),this.checkboxEl.className="bim-tree-checkbox",this.updateCheckboxUI(),this.checkboxEl.addEventListener("click",r=>{r.stopPropagation(),!this.config.disabled&&this.toggleCheck()}),this.contentEl.appendChild(this.checkboxEl)),this.config.icon){const r=document.createElement("span");r.className="bim-tree-icon",r.innerHTML=this.config.icon.includes("`,this.contentEl.appendChild(r)}this.titleEl=document.createElement("span"),this.titleEl.className="bim-tree-title",this.updateLabel(),this.contentEl.appendChild(this.titleEl),this.actionsEl=document.createElement("div"),this.actionsEl.className="bim-tree-node-actions",this.actionsEl.addEventListener("click",r=>{r.stopPropagation()}),this.contentEl.appendChild(this.actionsEl),this.contentEl.addEventListener("click",r=>{if(r.stopPropagation(),this.config.disabled)return;(this.config.clickAction||"select")==="expand"?this.toggleExpand():this.onNodeClick(this)}),t.appendChild(this.contentEl),this.childrenContainer=document.createElement("div"),this.childrenContainer.className="bim-tree-children";const n=e.indent||24;return this.childrenContainer.style.paddingLeft=`${n}px`,this.config.expanded&&i&&this.childrenContainer.classList.add("is-visible"),t.appendChild(this.childrenContainer),t}setSelected(e){if(e){if(this.contentEl.classList.add("is-selected"),this.renderActions){const t=this.renderActions(this.config);this.actionsEl.innerHTML="",typeof t=="string"?this.actionsEl.innerHTML=t:t instanceof HTMLElement&&this.actionsEl.appendChild(t)}}else this.contentEl.classList.remove("is-selected"),this.actionsEl.innerHTML=""}updateLabel(){this.titleEl&&(this.titleEl.textContent=this.config.label)}toggleExpand(e){if(!this.config.children||this.config.children.length===0)return;const t=e!==void 0?e:!this.config.expanded;this.config.expanded=t,t?(this.switcherEl.classList.add("is-expanded"),this.childrenContainer.classList.add("is-visible")):(this.switcherEl.classList.remove("is-expanded"),this.childrenContainer.classList.remove("is-visible")),e===void 0&&this.onExpandChange(this)}toggleCheck(){const e=this.checkState!==ni.Checked;this.setChecked(e?ni.Checked:ni.Unchecked,!0)}setChecked(e,t=!1,i=!1){!i&&this.checkState===e||(this.checkState=e,this.config.checked=e===ni.Checked,this.updateCheckboxUI(),t&&this.onCheckChange(this))}updateCheckboxUI(){this.checkboxEl&&(this.checkboxEl.classList.remove("is-checked","is-indeterminate"),this.checkState===ni.Checked?this.checkboxEl.classList.add("is-checked"):this.checkState===ni.Indeterminate&&this.checkboxEl.classList.add("is-indeterminate"))}appendChild(e){e.parent=this,this.children.push(e),this.childrenContainer.appendChild(e.element),this.children.length===1&&this.switcherEl.classList.remove("is-hidden")}destroy(){this.children.forEach(e=>e.destroy()),this.children=[],this.element.remove(),this.parent=null}}class zz{element;contentElement;searchInput=null;searchResults=null;options;nodeMap=new Map;rootNodes=[];selectedNode=null;lastRevealedNodeId=null;unsubscribeLocale=null;unsubscribeTheme=null;clickOutsideHandler=null;onNodeCheck;onNodeSelect;onNodeDeselect;onNodeExpand;constructor(e){this.options={checkable:!0,checkStrictly:!0,indent:24,defaultExpandAll:!0,enableSearch:!1,searchPlaceholder:"tree.searchPlaceholder",...e},this.element=document.createElement("div"),this.element.className="bim-tree",this.options.enableSearch&&this.createSearchDOM(),this.contentElement=document.createElement("div"),this.contentElement.className="bim-tree-content",this.element.appendChild(this.contentElement),e.onNodeCheck&&(this.onNodeCheck=e.onNodeCheck),e.onNodeSelect&&(this.onNodeSelect=e.onNodeSelect),e.onNodeDeselect&&(this.onNodeDeselect=e.onNodeDeselect),e.onNodeExpand&&(this.onNodeExpand=e.onNodeExpand)}createSearchDOM(){const e=document.createElement("div");e.className="bim-tree-search";const t=document.createElement("div");t.className="bim-tree-search-wrapper";const i=document.createElement("span");i.className="bim-tree-search-icon",i.innerHTML='',t.appendChild(i),this.searchInput=document.createElement("input"),this.searchInput.className="bim-tree-search-input",this.searchInput.type="text",this.searchInput.placeholder=Ee(this.options.searchPlaceholder||"搜索..."),this.searchInput.addEventListener("input",n=>{const r=n.target.value;this.handleSearch(r)}),t.appendChild(this.searchInput),e.appendChild(t),this.searchResults=document.createElement("div"),this.searchResults.className="bim-tree-search-results",e.appendChild(this.searchResults),this.element.appendChild(e),this.clickOutsideHandler=n=>{this.searchResults&&!this.searchResults.contains(n.target)&&!this.searchInput?.contains(n.target)&&this.searchResults.classList.remove("is-visible")},document.addEventListener("click",this.clickOutsideHandler)}init(){this.render(),this.unsubscribeLocale=$t.subscribe(()=>this.setLocales()),this.unsubscribeTheme=ct.subscribe(e=>this.setTheme(e)),this.setTheme(ct.getTheme())}handleSearch(e){if(!this.searchResults)return;if(!e.trim()){this.searchResults.classList.remove("is-visible"),this.searchResults.innerHTML="";return}const t=[],i=e.toLowerCase();this.nodeMap.forEach(n=>{const r=n.config.label;r.toLowerCase().includes(i)&&t.push({node:n,label:r,path:this.getNodePath(n)})}),this.renderSearchResults(t)}getNodePath(e){const t=[];let i=e.parent;for(;i;)t.unshift(i.config.label),i=i.parent;return t.join(" > ")}renderSearchResults(e){if(this.searchResults){if(this.searchResults.innerHTML="",e.length===0){const t=document.createElement("div");t.className="bim-tree-search-item",t.style.cursor="default",t.style.color="#999",t.textContent="No results",this.searchResults.appendChild(t)}else e.forEach(t=>{const i=document.createElement("div");i.className="bim-tree-search-item";const n=document.createElement("span");n.className="bim-tree-search-item-title",n.textContent=t.label;const r=document.createElement("span");r.className="bim-tree-search-item-path",r.textContent=t.path,i.appendChild(n),t.path&&i.appendChild(r),i.addEventListener("click",()=>{this.revealNode(t.node)}),this.searchResults.appendChild(i)});this.searchResults.classList.add("is-visible")}}revealNode(e){if(this.lastRevealedNodeId===e.config.id&&this.isNodeFullyVisible(e))return;this.lastRevealedNodeId=e.config.id,this.searchResults&&(this.searchResults.classList.remove("is-visible"),this.searchInput&&(this.searchInput.value=""));let t=e.parent;for(;t;)t.toggleExpand(!0),t=t.parent;this.handleNodeSelect(e),requestAnimationFrame(()=>{requestAnimationFrame(()=>{this.scrollNodeIntoContentCenter(e)})})}isNodeFullyVisible(e){const t=this.contentElement;if(!t||!e?.element?.isConnected)return!1;const i=t.getBoundingClientRect(),n=e.element.getBoundingClientRect();return n.top>=i.top&&n.bottom<=i.bottom}scrollNodeIntoContentCenter(e){const t=this.contentElement;if(!t||!e?.element?.isConnected)return;const i=t.getBoundingClientRect(),n=e.element.getBoundingClientRect();if(n.top>=i.top&&n.bottom<=i.bottom)return;const r=n.top-i.top+t.scrollTop,a=Math.max(0,r-(t.clientHeight-n.height)/2);t.scrollTo({top:a,behavior:"auto"})}setTheme(e){const t=this.element.style;t.setProperty("--bim-primary",e.primary),t.setProperty("--bim-bg-elevated",e.bgElevated),t.setProperty("--bim-text-primary",e.textPrimary),t.setProperty("--bim-text-secondary",e.textSecondary),t.setProperty("--bim-text-tertiary",e.textTertiary),t.setProperty("--bim-text-disabled",e.textDisabled),t.setProperty("--bim-text-inverse",e.textInverse),t.setProperty("--bim-border-default",e.borderDefault),t.setProperty("--bim-border-disabled",e.borderDisabled),t.setProperty("--bim-component-bg-hover",e.componentBgHover),t.setProperty("--bim-component-bg-selected",e.componentBgSelected),t.setProperty("--bim-component-bg-disabled",e.componentBgDisabled),t.setProperty("--bim-shadow-md",e.shadowMd),t.setProperty("--bim-focus-ring",e.focusRing)}setLocales(){this.nodeMap.forEach(e=>e.updateLabel()),this.searchInput&&(this.searchInput.placeholder=Ee(this.options.searchPlaceholder||"tree.searchPlaceholder"))}destroy(){this.unsubscribeLocale&&(this.unsubscribeLocale(),this.unsubscribeLocale=null),this.unsubscribeTheme&&(this.unsubscribeTheme(),this.unsubscribeTheme=null),this.clickOutsideHandler&&(document.removeEventListener("click",this.clickOutsideHandler),this.clickOutsideHandler=null),this.rootNodes.forEach(e=>e.destroy()),this.rootNodes=[],this.nodeMap.clear(),this.lastRevealedNodeId=null,this.element.remove(),this.selectedNode=null}render(){this.contentElement.innerHTML="",this.nodeMap.clear(),this.rootNodes=[],this.options.data.forEach(e=>{this.createNodeRecursively(e,null)})}createNodeRecursively(e,t){e.expanded===void 0&&(e.expanded=this.options.defaultExpandAll);const i=new Fz(e,this.options,{onExpand:n=>{this.onNodeExpand&&this.onNodeExpand(n)},onCheck:n=>this.handleNodeCheck(n),onClick:n=>this.handleNodeSelect(n)});this.nodeMap.set(e.id,i),t?t.appendChild(i):(this.rootNodes.push(i),this.contentElement.appendChild(i.element)),e.children&&e.children.length>0&&e.children.forEach(n=>{this.createNodeRecursively(n,i)})}handleNodeSelect(e){if(this.selectedNode===e){e.setSelected(!1),this.selectedNode=null,this.onNodeDeselect&&this.onNodeDeselect(e);return}this.selectedNode&&this.selectedNode.setSelected(!1),e.setSelected(!0),this.selectedNode=e,this.onNodeSelect&&this.onNodeSelect(e)}handleNodeCheck(e){const t=e.checkState===ni.Checked;if(this.onNodeCheck&&this.onNodeCheck(e),this.options.checkStrictly===!1)return;const i=(r,a)=>{r.children.forEach(o=>{o.config.disabled||(o.setChecked(a,!1),i(o,a))})};t?i(e,ni.Checked):i(e,ni.Unchecked);let n=e.parent;for(;n;){if(n.config.disabled){n=n.parent;continue}const r=n.children,a=r.every(l=>l.checkState===ni.Checked),o=r.every(l=>l.checkState===ni.Unchecked);a?n.setChecked(ni.Checked,!1):o?n.setChecked(ni.Unchecked,!1):n.setChecked(ni.Indeterminate,!1),n=n.parent}}getNode(e){return this.nodeMap.get(e)}checkNode(e,t){const i=this.nodeMap.get(e);i&&i.setChecked(t?ni.Checked:ni.Unchecked,!0)}expandAll(e){this.nodeMap.forEach(t=>t.toggleExpand(e))}checkAllNodes(e){const t=e?ni.Checked:ni.Unchecked;this.nodeMap.forEach(i=>i.setChecked(t,!1,!0))}getCheckedNodes(e=!1){const t=[];return this.nodeMap.forEach(i=>{(i.checkState===ni.Checked||e&&i.checkState===ni.Indeterminate)&&t.push(i.config)}),t}}class Hz{element;navElement;contentElement;options;activeId;tabMap=new Map;panelMap=new Map;panelTreeScrollTopMap=new Map;unsubscribeLocale=null;unsubscribeTheme=null;navClickHandler=null;constructor(e){this.options=e,this.activeId=e.activeId||(e.tabs[0]?.id??null),e.tabs.forEach(t=>this.tabMap.set(t.id,t)),this.element=document.createElement("div"),this.element.className="bim-tab",this.navElement=document.createElement("div"),this.navElement.className="bim-tab__nav",this.navElement.setAttribute("role","tablist"),this.element.appendChild(this.navElement),this.contentElement=document.createElement("div"),this.contentElement.className="bim-tab__content",this.element.appendChild(this.contentElement),this.options.container.appendChild(this.element)}init(){this.renderNav(),this.renderPanels(),this.setLocales(),this.setTheme(ct.getTheme()),this.unsubscribeLocale=$t.subscribe(()=>this.setLocales()),this.unsubscribeTheme=ct.subscribe(e=>this.setTheme(e))}renderNav(){this.navElement.innerHTML="",this.navClickHandler=e=>{const t=e.target.closest(".bim-tab__item");if(!t)return;const i=t.dataset.id;!i||this.tabMap.get(i)?.disabled||this.activateTab(i)},this.navElement.addEventListener("click",this.navClickHandler),this.options.tabs.forEach(e=>{const t=document.createElement("button");if(t.type="button",t.className="bim-tab__item",t.dataset.id=e.id,t.setAttribute("role","tab"),t.id=`tab-${e.id}`,t.setAttribute("aria-selected",`${e.id===this.activeId}`),e.disabled&&(t.disabled=!0,t.setAttribute("aria-disabled","true"),t.classList.add("is-disabled")),e.icon){const n=document.createElement("span");n.className="bim-tab__icon",n.innerHTML=e.icon,t.appendChild(n)}const i=document.createElement("span");i.className="bim-tab__title",i.textContent=this.resolveTitle(e.title),t.appendChild(i),e.id===this.activeId&&t.classList.add("is-active"),this.navElement.appendChild(t)})}renderPanels(){this.contentElement.innerHTML="",this.panelMap.clear(),this.options.tabs.forEach(e=>{const t=document.createElement("div");t.className="bim-tab__panel",t.dataset.id=e.id,t.setAttribute("role","tabpanel"),t.setAttribute("aria-labelledby",`tab-${e.id}`),e.content instanceof HTMLElement?t.appendChild(e.content):typeof e.content=="string"&&(t.innerHTML=e.content),e.id===this.activeId?t.classList.add("is-active"):t.style.display="none",this.panelMap.set(e.id,t),this.contentElement.appendChild(t)})}activateTab(e){if(this.activeId===e)return;const t=this.tabMap.get(e);if(!t||t.disabled)return;this.activeId=e,this.navElement.querySelectorAll(".bim-tab__item").forEach(n=>{const r=n.dataset.id===e;n.classList.toggle("is-active",r),n.setAttribute("aria-selected",`${r}`)}),this.panelMap.forEach((n,r)=>{const a=r===e;a||this.savePanelTreeScrollTop(r,n),n.classList.toggle("is-active",a),n.style.display=a?"":"none",a&&this.restorePanelTreeScrollTop(r,n)}),this.options.onChange&&this.options.onChange(e,t)}setTheme(e){const t=this.element.style;t.setProperty("--bim-tab-bg",e.bgElevated),t.setProperty("--bim-tab-nav-bg",e.bgElevated),t.setProperty("--bim-tab-text",e.textPrimary),t.setProperty("--bim-tab-text-secondary",e.textSecondary),t.setProperty("--bim-tab-text-active",e.primary),t.setProperty("--bim-tab-border",e.borderDefault),t.setProperty("--bim-tab-hover-bg",e.componentBgHover),t.setProperty("--bim-tab-active-bg",e.componentBgActive),t.setProperty("--bim-tab-icon",e.iconDefault)}setLocales(){this.navElement.querySelectorAll(".bim-tab__item").forEach(t=>{const i=t.dataset.id;if(!i)return;const n=this.tabMap.get(i);if(!n)return;const r=t.querySelector(".bim-tab__title");r&&(r.textContent=this.resolveTitle(n.title))})}destroy(){this.navClickHandler&&(this.navElement.removeEventListener("click",this.navClickHandler),this.navClickHandler=null),this.unsubscribeLocale&&(this.unsubscribeLocale(),this.unsubscribeLocale=null),this.unsubscribeTheme&&(this.unsubscribeTheme(),this.unsubscribeTheme=null),this.panelMap.clear(),this.panelTreeScrollTopMap.clear(),this.tabMap.clear(),this.element.remove()}savePanelTreeScrollTop(e,t){const i=t.querySelector(".bim-tree-content");i&&this.panelTreeScrollTopMap.set(e,i.scrollTop)}restorePanelTreeScrollTop(e,t){const i=this.panelTreeScrollTopMap.get(e);if(i===void 0)return;const n=t.querySelector(".bim-tree-content");n&&requestAnimationFrame(()=>{n.scrollTop=i})}resolveTitle(e){try{return Ee(e)||e}catch{return e}}}const C2={测量:'',地图:'',框选放大:'',漫游:'',目录树:'',剖切:'',剖切盒:'',全屏:'',设置:'',拾曲面剖切:'',轴向剖切:'',主视角:'',文档:'',第一人称漫游:'',反向:'',路径漫游:'',适应到模型:'',隐藏:'',重置:'',标高:'',距离:'',最小距离:'',激光边距:'',角度:'',坡度:'',体积:'',空间体积:'',close:'',check:'',warning:'',error:'',success:'',plus:'',minus:'',arrowUp:'',arrowUpBold:'',arrowDown:'',arrowLeft:'',arrowRight:'',search:'',refresh:'',delete:'',edit:'',save:'',expand:'',collapse:'',bot:'',history:'',settings:'',loader:'',send:'',透视相机:'',正交相机:'',default:''};function ut(s){const e=C2[s];return e||(console.warn(`[IconManager] Icon "${s}" not found, using default icon`),C2.default)}function A2(s,e){let t=e>>>0;for(let i=0;i>>8&255,t=Math.imul(t,16777619)}return t>>>0}async function Vz(s){const e=JSON.stringify(s),t=A2(e,2166136261),i=A2(e,522970236);return`${t.toString(16).padStart(8,"0")}${i.toString(16).padStart(8,"0")}`}function P2(s){const e=new Map,t=n=>{const r=n.config.data,a=r?._modelUrl;if(a&&r?.ids?.length){let o=e.get(a);o||(o=new Set,e.set(a,o));for(const l of r.ids){const c=Number(l);Number.isFinite(c)&&o.add(c)}}for(const o of n.children||[])t(o)};t(s);const i=[];for(const[n,r]of e)r.size>0&&i.push({url:n,ids:Array.from(r)});return i}let Gz=0;async function Wz(s){if(!s||s.length===0)return[];const e=async(t,i)=>{const n=t.children&&t.children.length>0;let r;return t.ids?.length?r=await Vz(t.ids):t.id?r=t.id:r=`node_${++Gz}`,{id:r,label:t.name||"未命名",expanded:!1,checked:!0,children:n?await Promise.all(t.children.map(a=>e(a,i))):void 0,data:{...t,_modelUrl:i}}};return Promise.all(s.map(async t=>{const i=t.children&&t.children.length>0,n=t.url;return{id:n,label:t.name||"模型",expanded:!0,checked:!0,children:i?await Promise.all(t.children.map(r=>e(r,n))):void 0,data:{_modelUrl:n}}}))}class Xz extends jn{toolbar=null;toolbarContainer=null;container;dialog=null;constructor(e,t){super(t),this.container=e,this.init()}init(){this.toolbarContainer=document.createElement("div"),this.toolbarContainer.id="bim-construct-tree",this.container.appendChild(this.toolbarContainer),this.toolbar=new Am({container:this.toolbarContainer,showLabel:!1,direction:"column",position:"top-left",align:"vertical",expand:"up",registry:this.registry}),this.toolbar.init(),this.toolbar.addGroup("construct-tree"),this.toolbar.addButton({id:"construct-tree-btn",groupId:"construct-tree",type:"button",label:"construct-tree",icon:ut("目录树"),onClick:()=>{this.openConstructTreeDialog()}}),this.toolbar.render()}async openConstructTreeDialog(){this.setVisible(!1);const e=this.engineComponent?.getLevelTreeData()??[],t=this.engineComponent?.getTypeTreeData()??[],i=this.engineComponent?.getMajorTreeData()??[];console.log("[ConstructTree] 原始数据 (Level):",e),console.log("[ConstructTree] 原始数据 (Type):",t),console.log("[ConstructTree] 原始数据 (Major):",i);const n=async(g,m)=>{const f=await Wz(g);console.log(`[ConstructTree] 转换后数据 (${m}):`,f);const y=new zz({data:f,checkable:!0,indent:0,enableSearch:!0,checkStrictly:!0,defaultExpandAll:!0,onNodeCheck:x=>{const _=P2(x);_.length&&(x.checkState===ni.Checked?this.engineComponent?.showModel(_):this.engineComponent?.hideModels(_))},onNodeSelect:x=>{const _=P2(x);_.length&&(this.engineComponent?.unhighlightAllModels(),this.engineComponent?.highlightModel(_),this.engineComponent?.viewScaleToModel(_))},onNodeDeselect:()=>{this.engineComponent?.unhighlightAllModels()},onNodeExpand:()=>{this.dialog?.fitWidth()}});return y.init(),y},r=await n(e,"Level"),a=await n(t,"Type"),o=await n(i,"Major"),l=document.createElement("div");l.className="construct-tab__panel-content",l.appendChild(r.element);const c=document.createElement("div");c.className="construct-tab__panel-content",c.appendChild(a.element);const h=document.createElement("div");h.className="construct-tab__panel-content",h.appendChild(o.element);const d=document.createElement("div");d.className="construct-tab__container",d.style.height="100%",d.style.overflow="hidden";const p=()=>{this.engineComponent?.showAllModels(),r.checkAllNodes(!0),a.checkAllNodes(!0),o.checkAllNodes(!0)},u=new Hz({container:d,tabs:[{id:"component",title:"tab.component",content:l},{id:"type",title:"tab.type",content:c},{id:"major",title:"tab.major",content:h}],activeId:"component",onChange:()=>{this.dialog?.fitWidth()}});u.init(),p();const v=this.registry.on("menu:show-all",()=>{p()});this.dialog=this.registry.dialog.create({title:"constructTree.title",minWidth:320,height:600,content:d,position:{x:20,y:20},resizable:!1,onClose:()=>{v(),u.destroy(),r.destroy(),a.destroy(),o.destroy(),this.setVisible(!0)}}),this.dialog?.fitWidth()}refresh(){this.toolbar?.render()}destroy(){this.toolbar?.destroy(),this.toolbar=null,super.destroy()}addGroup(e,t){this.toolbar?.addGroup(e,t),this.toolbar?.render()}addButton(e){this.toolbar?.addButton(e),this.toolbar?.render()}setButtonVisibility(e,t){this.toolbar?.updateButtonVisibility(e,t)}setShowLabel(e){this.toolbar?.setShowLabel(e)}setVisible(e){this.toolbarContainer&&(this.toolbarContainer.style.visibility=e?"visible":"hidden")}setBackgroundColor(e){this.toolbar?.setBackgroundColor(e)}setColors(e){this.toolbar?.setColors(e)}}class No extends jn{dialog=null;isVisible=!1;constructor(e){super(e)}get dialogWidth(){return 300}get dialogHeight(){return"auto"}get dialogOptions(){return{draggable:!0,resizable:!1}}onDialogClose(){}onDialogCreated(){}onBeforeDestroy(){}getDialogPosition(){const e=this.registry.container;if(!e)return{x:100,y:100};const t=e.clientWidth,i=e.clientHeight,n=this.dialogWidth,r=typeof this.dialogHeight=="number"?this.dialogHeight:300;return{x:t-n-20,y:(i-r)/2}}show(){if(!this.registry.dialog||!this.registry.container){console.warn(`[${this.dialogId}] Dialog manager or container is not initialized`);return}this.dialog&&this.destroyDialog();const e=this.getDialogPosition(),t=this.createContent(),i=this.dialogOptions;this.dialog=this.registry.dialog.create({id:this.dialogId,title:this.dialogTitle,content:t,width:this.dialogWidth,height:this.dialogHeight,position:e,draggable:i.draggable,resizable:i.resizable,onClose:()=>{this.onDialogClose(),this.destroyDialog()}}),this.dialog.init(),this.isVisible=!0,this.onDialogCreated()}hide(){this.destroyDialog()}toggle(){this.isVisible?this.hide():this.show()}isOpen(){return this.isVisible}destroyDialog(){this.onBeforeDestroy(),this.dialog&&(this.dialog.destroy(),this.dialog=null),this.isVisible=!1}destroy(){this.destroyDialog(),super.destroy()}}const _a={clearHeight:'',clearDistance:'',distance:'',elevation:'',point:'',angle:'',area:'',slope:''},dc={distance:{key:"distance",callBackType:"distance",icon:_a.distance,order:0},clearHeight:{key:"clearHeight",callBackType:"clear-height",icon:_a.clearHeight,order:1},clearDistance:{key:"clearDistance",callBackType:"clear-distance",icon:_a.clearDistance,order:2},elevation:{key:"elevation",callBackType:"elevation",icon:_a.elevation,order:3},point:{key:"point",callBackType:"point",icon:_a.point,order:4},angle:{key:"angle",callBackType:"angle",icon:_a.angle,order:5},area:{key:"area",callBackType:"area",icon:_a.area,order:6},slope:{key:"slope",callBackType:"slope",icon:_a.slope,order:7}},R2=Object.values(dc).sort((s,e)=>s.order-e.order).map(s=>s.key);function I2(s){switch(s){case"clearHeight":case"clearDistance":case"distance":case"elevation":return"length";case"area":return"area";case"angle":return"angle";case"slope":return"percent";default:return"point"}}function L2(s){return Object.values(dc).find(e=>e.callBackType===s)?.key}class ed{element;options;activeMode;isExpanded;result=null;clearHeightDirection=0;clearHeightSelectType="point";config;draftConfig=null;view="main";static CONFIG_CACHE_KEY="bim-engine:measure:config";static DEFAULT_CONFIG={unit:"mm",precision:2};toolButtons=new Map;toggleBtn;toggleTextEl;mainValueRowEl;mainValueValueEl;mainValueLabelEl;mainNumberEl;mainUnitEl;xyzBoxEl;xyzXEl;xyzYEl;xyzZEl;clearBtn;settingsBtn;modeOptionsEl;directionBtns=new Map;selectTypeBtns=new Map;mainViewEl;settingsViewEl;unitSelectEl;precisionSelectEl;saveSettingsBtn;cancelSettingsBtn;unsubscribeLocale=null;unsubscribeTheme=null;constructor(e={}){this.options=e,this.activeMode=e.defaultMode??"distance",this.isExpanded=e.defaultExpanded??!1,this.config=this.loadConfigFromCache()??{...ed.DEFAULT_CONFIG},this.element=this.createDom()}init(){this.unsubscribeLocale=$t.subscribe(()=>{this.setLocales()}),this.unsubscribeTheme=ct.subscribe(e=>{this.setTheme(e)}),this.setLocales(),this.setTheme(ct.getTheme()),this.applyExpandedState(),this.applyActiveModeState(),this.applyClearHeightOptionsState(),this.applyViewState(),this.renderResult(),this.options.onModeChange&&this.options.onModeChange(this.activeMode)}setTheme(e){const t=this.element.style;t.setProperty("--bim-bg-inset",e.bgInset??"#152232"),t.setProperty("--bim-bg-elevated",e.bgElevated??"#1f2d3e"),t.setProperty("--bim-border-default",e.borderDefault??"#334155"),t.setProperty("--bim-border-strong",e.borderStrong??"#475569"),t.setProperty("--bim-divider",e.divider??"#334155"),t.setProperty("--bim-primary",e.primary??"#3b82f6"),t.setProperty("--bim-primary-hover",e.primaryHover??"#60a5fa"),t.setProperty("--bim-primary-subtle",e.primarySubtle??"rgba(59, 130, 246, 0.15)"),t.setProperty("--bim-danger",e.danger??"#ef4444"),t.setProperty("--bim-text-primary",e.textPrimary??"#ffffff"),t.setProperty("--bim-text-secondary",e.textSecondary??"#94a3b8"),t.setProperty("--bim-text-tertiary",e.textTertiary??"#64748b"),t.setProperty("--bim-text-inverse",e.textInverse??"#152232"),t.setProperty("--bim-icon-default",e.iconDefault??"#ffffff"),t.setProperty("--bim-component-bg-hover",e.componentBgHover??"rgba(248, 250, 252, 0.06)")}setLocales(){for(const[t,i]of this.toolButtons.entries())i.title=Ee(this.getModeI18nKey(t)),i.setAttribute("aria-label",i.title);this.toggleBtn.title=this.isExpanded?Ee("measure.actions.collapse"):Ee("measure.actions.expand"),this.toggleBtn.setAttribute("aria-label",this.toggleBtn.title),this.toggleTextEl&&(this.toggleTextEl.textContent=this.toggleBtn.title),this.clearBtn.textContent=Ee("measure.actions.clearAll"),this.settingsBtn.title=Ee("measure.actions.settings"),this.settingsBtn.setAttribute("aria-label",this.settingsBtn.title),this.mainValueLabelEl.textContent=Ee(this.getModeValueLabelI18nKey(this.activeMode)),this.element.querySelectorAll("[data-i18n-key]").forEach(t=>{const i=t.dataset.i18nKey;i&&(t.textContent=Ee(i))}),this.saveSettingsBtn.textContent=Ee("measure.settings.save"),this.cancelSettingsBtn.textContent=Ee("measure.settings.cancel")}destroy(){this.unsubscribeLocale&&(this.unsubscribeLocale(),this.unsubscribeLocale=null),this.unsubscribeTheme&&(this.unsubscribeTheme(),this.unsubscribeTheme=null),this.element.remove()}getActiveMode(){return this.activeMode}switchMode(e,t=!0){this.setActiveMode(e,t)}setActiveMode(e,t=!0){this.activeMode!==e&&(this.activeMode=e,this.applyActiveModeState(),this.applyClearHeightOptionsState(),this.mainValueLabelEl.textContent=Ee(this.getModeValueLabelI18nKey(this.activeMode)),t&&this.options.onModeChange&&this.options.onModeChange(e),this.renderResult(),this.options.onExpandedChange&&this.options.onExpandedChange(this.isExpanded))}setResult(e){this.result=e,this.renderResult()}clearAll(){this.result=null,this.renderResult(),this.options.onClearAll&&this.options.onClearAll()}openSettings(){this.enterSettingsView(),this.options.onSettings&&this.options.onSettings()}getConfig(){return{...this.config}}setConfig(e,t=!1){const i={unit:e.unit??this.config.unit,precision:e.precision??this.config.precision};this.config=i,t&&this.saveConfigToCache(i),this.renderResult(),this.view==="settings"&&this.syncSettingsFormFromConfig(i)}setExpanded(e){this.isExpanded!==e&&(this.isExpanded=e,this.applyExpandedState(),this.setLocales(),this.options.onExpandedChange&&this.options.onExpandedChange(this.isExpanded))}getExpanded(){return this.isExpanded}createDom(){const e=document.createElement("div");e.className="bim-measure-panel",this.mainViewEl=document.createElement("div"),this.mainViewEl.className="bim-measure-main";const t=document.createElement("div");t.className="bim-measure-tools";const i=document.createElement("div");i.className="bim-measure-tool-grid";const n=` `;for(let v=0;v{this.setActiveMode(g)}),this.toolButtons.set(g,f),i.appendChild(f)}t.appendChild(i);const r=document.createElement("div");r.className="bim-measure-toggle",this.toggleBtn=document.createElement("button"),this.toggleBtn.type="button",this.toggleBtn.className="bim-measure-toggle-btn",this.toggleTextEl=document.createElement("span"),this.toggleTextEl.className="bim-measure-toggle-text";const a=document.createElement("span");a.className="bim-measure-toggle-icon",a.innerHTML=` `,this.toggleBtn.appendChild(this.toggleTextEl),this.toggleBtn.appendChild(a),this.toggleBtn.addEventListener("click",()=>{this.isExpanded=!this.isExpanded,this.applyExpandedState(),this.setLocales(),this.options.onExpandedChange&&this.options.onExpandedChange(this.isExpanded)}),r.appendChild(this.toggleBtn),t.appendChild(r),this.mainViewEl.appendChild(t),this.modeOptionsEl=this.createModeOptionsDom(),this.mainViewEl.appendChild(this.modeOptionsEl);const o=document.createElement("div");o.className="bim-measure-result";const l=document.createElement("div");l.className="bim-measure-row",this.mainValueRowEl=l;const c=document.createElement("span");c.className="label",this.mainValueLabelEl=c;const h=document.createElement("span");h.className="value",this.mainValueValueEl=h,this.mainNumberEl=document.createElement("span"),this.mainNumberEl.className="bim-measure-main-number",this.mainUnitEl=document.createElement("span"),this.mainUnitEl.className="bim-measure-main-unit",this.mainValueValueEl.appendChild(this.mainNumberEl),this.mainValueValueEl.appendChild(document.createTextNode(" ")),this.mainValueValueEl.appendChild(this.mainUnitEl),l.appendChild(c),l.appendChild(h),o.appendChild(l);const d=document.createElement("div");d.className="bim-measure-xyz",this.xyzBoxEl=d;const p=(v,g,m)=>{const f=document.createElement("div");f.className="bim-measure-row";const y=document.createElement("span");y.className="label",y.dataset.i18nKey=v;const x=document.createElement("span");return x.className=`value ${g}`,m(x),f.appendChild(y),f.appendChild(x),f};d.appendChild(p("measure.labels.x","bim-measure-xyz-x",v=>this.xyzXEl=v)),d.appendChild(p("measure.labels.y","bim-measure-xyz-y",v=>this.xyzYEl=v)),d.appendChild(p("measure.labels.z","bim-measure-xyz-z",v=>this.xyzZEl=v)),o.appendChild(d),this.mainViewEl.appendChild(o);const u=document.createElement("div");return u.className="bim-measure-footer",this.clearBtn=document.createElement("button"),this.clearBtn.type="button",this.clearBtn.className="bim-measure-clear-btn",this.clearBtn.addEventListener("click",()=>{this.clearAll()}),this.settingsBtn=document.createElement("button"),this.settingsBtn.type="button",this.settingsBtn.className="bim-measure-settings-btn",this.settingsBtn.innerHTML=` `,this.settingsBtn.addEventListener("click",()=>{this.openSettings()}),u.appendChild(this.clearBtn),u.appendChild(this.settingsBtn),this.mainViewEl.appendChild(u),this.settingsViewEl=this.createSettingsDom(),e.appendChild(this.mainViewEl),e.appendChild(this.settingsViewEl),e}createSettingsDom(){const e=document.createElement("div");e.className="bim-measure-settings";const t=document.createElement("div");t.className="bim-measure-settings-title",t.dataset.i18nKey="measure.settings.title",e.appendChild(t);const i=document.createElement("div");i.className="bim-measure-settings-row";const n=document.createElement("div");n.className="label",n.dataset.i18nKey="measure.settings.unit",this.unitSelectEl=document.createElement("select"),this.unitSelectEl.className="bim-measure-settings-select",this.unitSelectEl.appendChild(this.makeOption("m")),this.unitSelectEl.appendChild(this.makeOption("cm")),this.unitSelectEl.appendChild(this.makeOption("mm")),this.unitSelectEl.appendChild(this.makeOption("km")),i.appendChild(n),i.appendChild(this.unitSelectEl),e.appendChild(i);const r=document.createElement("div");r.className="bim-measure-settings-hint",r.dataset.i18nKey="measure.settings.hint",e.appendChild(r);const a=document.createElement("div");a.className="bim-measure-settings-row";const o=document.createElement("div");o.className="label",o.dataset.i18nKey="measure.settings.precision",this.precisionSelectEl=document.createElement("select"),this.precisionSelectEl.className="bim-measure-settings-select",this.precisionSelectEl.appendChild(this.makePrecisionOption(0)),this.precisionSelectEl.appendChild(this.makePrecisionOption(1)),this.precisionSelectEl.appendChild(this.makePrecisionOption(2)),this.precisionSelectEl.appendChild(this.makePrecisionOption(3)),a.appendChild(o),a.appendChild(this.precisionSelectEl),e.appendChild(a);const l=document.createElement("div");return l.className="bim-measure-settings-actions",this.saveSettingsBtn=document.createElement("button"),this.saveSettingsBtn.type="button",this.saveSettingsBtn.className="bim-measure-settings-save",this.saveSettingsBtn.addEventListener("click",()=>{this.saveSettings()}),this.cancelSettingsBtn=document.createElement("button"),this.cancelSettingsBtn.type="button",this.cancelSettingsBtn.className="bim-measure-settings-cancel",this.cancelSettingsBtn.addEventListener("click",()=>{this.cancelSettings()}),l.appendChild(this.saveSettingsBtn),l.appendChild(this.cancelSettingsBtn),e.appendChild(l),this.syncSettingsFormFromConfig(this.config),e}createModeOptionsDom(){const e=document.createElement("div");e.className="bim-measure-mode-options";const t=document.createElement("div");t.className="bim-measure-radio-group";const i=document.createElement("span");i.className="bim-measure-radio-label",i.dataset.i18nKey="measure.clearHeight.direction";const n=document.createElement("div");n.className="bim-measure-radio-items";const r=this.createRadioItem("measure.clearHeight.directionDown",()=>{this.setClearHeightDirection(0)}),a=this.createRadioItem("measure.clearHeight.directionUp",()=>{this.setClearHeightDirection(1)});this.directionBtns.set(0,r),this.directionBtns.set(1,a),n.appendChild(r),n.appendChild(a),t.appendChild(i),t.appendChild(n),e.appendChild(t);const o=document.createElement("div");o.className="bim-measure-radio-group";const l=document.createElement("span");l.className="bim-measure-radio-label",l.dataset.i18nKey="measure.clearHeight.selectType";const c=document.createElement("div");c.className="bim-measure-radio-items";const h=this.createRadioItem("measure.clearHeight.selectPoint",()=>{this.setClearHeightSelectType("point")}),d=this.createRadioItem("measure.clearHeight.selectElement",()=>{this.setClearHeightSelectType("element")});return this.selectTypeBtns.set("point",h),this.selectTypeBtns.set("element",d),c.appendChild(h),c.appendChild(d),o.appendChild(l),o.appendChild(c),e.appendChild(o),e}createRadioItem(e,t){const i=document.createElement("button");return i.type="button",i.className="bim-measure-radio-item",i.dataset.i18nKey=e,i.textContent=Ee(e),i.addEventListener("click",t),i}setClearHeightDirection(e){this.clearHeightDirection!==e&&(this.clearHeightDirection=e,this.applyClearHeightOptionsState(),this.options.onClearHeightDirectionChange?.(e))}setClearHeightSelectType(e){this.clearHeightSelectType!==e&&(this.clearHeightSelectType=e,this.applyClearHeightOptionsState(),this.options.onClearHeightSelectTypeChange?.(e))}applyClearHeightOptionsState(){this.activeMode==="clearHeight"?this.modeOptionsEl.classList.add("is-visible"):this.modeOptionsEl.classList.remove("is-visible");for(const[e,t]of this.directionBtns.entries())e===this.clearHeightDirection?t.classList.add("is-active"):t.classList.remove("is-active");for(const[e,t]of this.selectTypeBtns.entries())e===this.clearHeightSelectType?t.classList.add("is-active"):t.classList.remove("is-active")}makeOption(e){const t=document.createElement("option");return t.value=e,t.textContent=e,t}makePrecisionOption(e){const t=document.createElement("option");return t.value=String(e),t.textContent=e===0?"0":`0.${"0".repeat(e)}`,t}enterSettingsView(){this.draftConfig={...this.config},this.view="settings",this.syncSettingsFormFromConfig(this.config),this.applyViewState()}saveSettings(){const e=this.unitSelectEl.value||this.config.unit,t=Number(this.precisionSelectEl.value),i={unit:e,precision:this.isValidPrecision(t)?t:this.config.precision};this.config=i,this.saveConfigToCache(i),this.draftConfig=null,this.view="main",this.applyViewState(),this.renderResult(),this.options.onConfigSave?.(i),this.options.onExpandedChange?.(this.isExpanded)}cancelSettings(){this.draftConfig&&(this.config={...this.draftConfig}),this.draftConfig=null,this.view="main",this.applyViewState(),this.renderResult(),this.options.onExpandedChange&&this.options.onExpandedChange(this.isExpanded)}syncSettingsFormFromConfig(e){this.unitSelectEl.value=e.unit,this.precisionSelectEl.value=String(e.precision)}applyViewState(){this.view==="settings"?(this.mainViewEl.style.display="none",this.settingsViewEl.style.display="block"):(this.mainViewEl.style.display="block",this.settingsViewEl.style.display="none")}loadConfigFromCache(){try{const e=localStorage.getItem(ed.CONFIG_CACHE_KEY);if(!e)return null;const t=JSON.parse(e);if(!t||typeof t!="object")return null;const i=t.unit,n=t.precision;return!this.isValidUnit(i)||!this.isValidPrecision(n)?null:{unit:i,precision:n}}catch{return null}}saveConfigToCache(e){try{localStorage.setItem(ed.CONFIG_CACHE_KEY,JSON.stringify(e))}catch{}}isValidUnit(e){return e==="m"||e==="cm"||e==="mm"||e==="km"}isValidPrecision(e){return e===0||e===1||e===2||e===3}applyExpandedState(){let e=0;for(const t of this.toolButtons.values())e>=4?t.style.display=this.isExpanded?"":"none":t.style.display="",e++;this.isExpanded?this.toggleBtn.classList.add("is-expanded"):this.toggleBtn.classList.remove("is-expanded")}applyActiveModeState(){for(const[e,t]of this.toolButtons.entries())e===this.activeMode?t.classList.add("is-active"):t.classList.remove("is-active")}renderResult(){if(this.activeMode==="point"){this.mainValueRowEl.style.display="none",this.xyzBoxEl.style.display="";const i=this.result?.xyz;if(!i){this.xyzXEl.textContent="--",this.xyzYEl.textContent="--",this.xyzZEl.textContent="--";return}this.xyzXEl.textContent=this.convertValue("length",i.x)+" "+this.getUnitText("length"),this.xyzYEl.textContent=this.convertValue("length",i.y)+" "+this.getUnitText("length"),this.xyzZEl.textContent=this.convertValue("length",i.z)+" "+this.getUnitText("length");return}this.mainValueRowEl.style.display="",this.mainValueLabelEl.textContent=Ee(this.getModeValueLabelI18nKey(this.activeMode));const t=this.result?this.result[dc[this.activeMode].callBackType]:void 0;if(this.activeMode==="slope"||this.activeMode==="angle")this.mainNumberEl.textContent=t??"--",this.mainUnitEl.textContent="";else{const i=I2(this.activeMode);this.mainNumberEl.textContent=this.convertValue(i,t),this.mainUnitEl.textContent=this.getUnitText(i)}this.xyzBoxEl.style.display="none"}getModeI18nKey(e){return`measure.modes.${e}`}getModeValueLabelI18nKey(e){return`measure.labels.value.${e}`}convertValue(e,t){if(t==null||Number.isNaN(t))return"--";const i=this.config.unit,n=this.config.precision;let r;switch(e){case"length":switch(i){case"mm":r=t*1e3;break;case"cm":r=t*100;break;case"km":r=t/1e3;break;default:r=t}break;case"area":switch(i){case"mm":r=t*1e3*1e3;break;case"cm":r=t*100*100;break;case"km":r=t/1e3/1e3;break;default:r=t}break;default:r=t}return r.toFixed(n)}getUnitText(e){const t=this.config.unit;switch(e){case"length":case"point":return t;case"area":return`${t}²`;case"angle":case"percent":return"°";default:return""}}}class D2 extends No{panel=null;config=null;unsubscribeMeasureChanged=null;constructor(e){super(e)}get dialogId(){return"measure-dialog"}get dialogTitle(){return"measure.dialogTitle"}get dialogWidth(){return 250}createContent(){this.panel=new ed({defaultMode:"distance",defaultExpanded:!1,onModeChange:t=>{console.log("[MeasureDialogManager] 当前测量方式已切换:",t),this.engineComponent?.activateMeasure(t)},onClearAll:()=>{console.log("[MeasureDialogManager] 删除全部"),this.engineComponent?.clearAllMeasures()},onSettings:()=>{console.log("[MeasureDialogManager] 打开设置")},onExpandedChange:()=>{this.dialog?.fitHeight(!1)},onConfigSave:t=>{console.log("[MeasureDialogManager] 保存设置:",t),this.engineComponent?.saveMeasureSetting({unit:t.unit,precision:t.precision})},onClearHeightDirectionChange:t=>{console.log("[MeasureDialogManager] 净高朝向切换:",t),this.engineComponent?.setClearHeightDirection(t)},onClearHeightSelectTypeChange:t=>{console.log("[MeasureDialogManager] 净高选择对象切换:",t),this.engineComponent?.setClearHeightSelectType(t)}}),this.panel.init(),this.config=this.panel.getConfig(),this.config&&(console.log("[MeasureDialogManager] 同步缓存设置到引擎:",this.config),this.engineComponent?.saveMeasureSetting({unit:this.config.unit,precision:this.config.precision}));const e=document.createElement("div");return e.style.padding="12px",e.appendChild(this.panel.element),e}onDialogCreated(){this.dialog?.fitHeight(!1),this.engineComponent?.setClearHeightDirection(0),this.engineComponent?.setClearHeightSelectType("point");const e=this.engineComponent;if(e){const t=i=>{console.log("[MeasureDialogManager] 测量值回调:",i),i&&this.panel&&this.handleMeasureChanged(i)};e.onRawEvent("measure-changed",t),e.onRawEvent("measure-click",t),this.unsubscribeMeasureChanged=()=>{e.offRawEvent("measure-changed",t),e.offRawEvent("measure-click",t)}}}handleMeasureChanged(e){if(!this.panel)return;const t=L2(e.type);if(!t){console.warn("[MeasureDialogManager] 未知测量类型:",e.type);return}this.panel.getActiveMode()!==t&&this.panel.switchMode(t,!1);const n=this.convertToMeasureResult(e,t);this.panel.setResult(n)}convertToMeasureResult(e,t){const i=dc[t],n={};return I2(t)==="point"?e.textX!==void 0&&e.textY!==void 0&&e.textZ!==void 0&&(n.xyz={x:e.textX,y:e.textY,z:e.textZ}):n[i.callBackType]=e.text,n}onDialogClose(){this.unsubscribeMeasureChanged&&(this.unsubscribeMeasureChanged(),this.unsubscribeMeasureChanged=null),this.registry.toolbar?.setBtnActive("measure",!1)}onBeforeDestroy(){this.unsubscribeMeasureChanged&&(this.unsubscribeMeasureChanged(),this.unsubscribeMeasureChanged=null),this.engineComponent?.deactivateMeasure(),this.panel&&(this.panel.destroy(),this.panel=null)}getActiveMode(){return this.panel?this.panel.getActiveMode():null}switchMode(e){this.panel&&this.panel.switchMode(e)}setMeasureResult(e){this.panel&&this.panel.setResult(e)}getConfig(){return this.panel&&(this.config=this.panel.getConfig()),this.config?{...this.config}:null}setConfig(e,t=!0){if(this.panel){this.panel.setConfig(e,t),this.config=this.panel.getConfig(),this.dialog?.fitHeight(!1);return}const i=this.config,n={unit:e.unit??i?.unit??"mm",precision:e.precision??i?.precision??2};this.config=n}clearAll(){this.panel&&this.panel.clearAll()}openSettings(){this.panel&&this.panel.openSettings()}}class jz{element;options;isHidden=!1;hideBtn;reverseBtn;resetBtn;hideLabelEl;reverseLabelEl;resetLabelEl;unsubscribeLocale=null;unsubscribeTheme=null;constructor(e={}){this.options=e,this.isHidden=e.defaultHidden??!1,this.element=this.createDom()}setHiddenState(e){this.isHidden=e,this.updateButtonStates()}getHiddenState(){return this.isHidden}updateButtonStates(){this.hideBtn?.classList.toggle("active",this.isHidden)}init(){this.unsubscribeLocale=$t.subscribe(()=>{this.setLocales()}),this.unsubscribeTheme=ct.subscribe(e=>{this.setTheme(e)}),this.setLocales(),this.setTheme(ct.getTheme())}setTheme(e){const t=this.element.style;t.setProperty("--bim-bg-inset",e.bgInset??"#152232"),t.setProperty("--bim-border-default",e.borderDefault??"#334155"),t.setProperty("--bim-border-strong",e.borderStrong??"#475569"),t.setProperty("--bim-primary",e.primary??"#3b82f6"),t.setProperty("--bim-primary-subtle",e.primarySubtle??"rgba(59, 130, 246, 0.15)"),t.setProperty("--bim-icon-default",e.iconDefault??"#ffffff"),t.setProperty("--bim-text-primary",e.textPrimary??"#ffffff"),t.setProperty("--bim-component-bg-hover",e.componentBgHover??"rgba(248, 250, 252, 0.06)")}setLocales(){this.hideLabelEl.textContent=Ee("sectionPlane.actions.hide"),this.reverseLabelEl.textContent=Ee("sectionPlane.actions.reverse"),this.resetLabelEl.textContent=Ee("sectionPlane.actions.reset"),this.hideBtn.title=Ee("sectionPlane.actions.hide"),this.reverseBtn.title=Ee("sectionPlane.actions.reverse"),this.resetBtn.title=Ee("sectionPlane.actions.reset")}destroy(){this.unsubscribeLocale&&(this.unsubscribeLocale(),this.unsubscribeLocale=null),this.unsubscribeTheme&&(this.unsubscribeTheme(),this.unsubscribeTheme=null),this.element.remove()}createDom(){const e=document.createElement("div");return e.className="section-plane-panel",this.hideBtn=this.createButton("hide",ut("隐藏"),()=>{this.isHidden=!this.isHidden,this.updateButtonStates(),this.options.onHideToggle?.(this.isHidden)}),this.reverseBtn=this.createButton("reverse",ut("反向"),()=>{this.options.onReverse&&this.options.onReverse()}),this.resetBtn=this.createButton("reset",ut("重置"),()=>{this.options.onReset&&this.options.onReset()}),e.appendChild(this.hideBtn),e.appendChild(this.reverseBtn),e.appendChild(this.resetBtn),e}createButton(e,t,i){const n=document.createElement("button");n.type="button",n.className="section-plane-btn";const r=document.createElement("div");r.className="section-plane-btn-icon",r.innerHTML=t,n.appendChild(r);const a=document.createElement("div");return a.className="section-plane-btn-label",n.appendChild(a),e==="hide"?this.hideLabelEl=a:e==="reverse"?this.reverseLabelEl=a:this.resetLabelEl=a,n.addEventListener("click",i),n}}class N2 extends No{panel=null;constructor(e){super(e)}get dialogId(){return"section-plane-dialog"}get dialogTitle(){return"sectionPlane.dialogTitle"}get dialogWidth(){return 240}get dialogHeight(){return 120}init(){}getDialogPosition(){const e=this.registry.container;if(!e)return{x:100,y:100};const t=20,i=50,n=e.clientWidth,r=e.clientHeight;return{x:n-this.dialogWidth-t,y:r-this.dialogHeight-i}}createContent(){return this.panel=new jz({defaultHidden:!1,onHideToggle:e=>{console.log("[SectionPlaneDialogManager] 隐藏切换:",e),e?this.engineComponent?.hideSection():this.engineComponent?.recoverSection()},onReverse:()=>{this.engineComponent?.reverseSection()},onReset:()=>{this.engineComponent?.deactivateSection(),this.engineComponent?.activeSection("face")}}),this.panel.init(),this.panel.element}onDialogCreated(){this.engineComponent?.activeSection("face"),this.dialog?.fitHeight(!1)}onDialogClose(){this.registry.toolbar?.setBtnActive("section-plane",!1)}onBeforeDestroy(){this.engineComponent?.deactivateSection(),this.panel&&(this.panel.destroy(),this.panel=null)}}class qz{element;options;isHidden=!1;activeAxis="x";hideBtn;reverseBtn;hideLabelEl;reverseLabelEl;axisXBtn;axisYBtn;axisZBtn;unsubscribeLocale=null;unsubscribeTheme=null;constructor(e={}){this.options=e,this.isHidden=e.defaultHidden??!1,this.activeAxis=e.defaultAxis??"x",this.element=this.createDom()}init(){this.unsubscribeLocale=$t.subscribe(()=>{this.setLocales()}),this.unsubscribeTheme=ct.subscribe(e=>{this.setTheme(e)}),this.setLocales(),this.setTheme(ct.getTheme()),this.updateHideButtonState(),this.updateAxisButtonsState()}setTheme(e){const t=this.element.style;t.setProperty("--bim-bg-inset",e.bgInset??"#152232"),t.setProperty("--bim-border-default",e.borderDefault??"#334155"),t.setProperty("--bim-border-strong",e.borderStrong??"#475569"),t.setProperty("--bim-divider",e.divider??"#334155"),t.setProperty("--bim-primary",e.primary??"#3b82f6"),t.setProperty("--bim-primary-subtle",e.primarySubtle??"rgba(59, 130, 246, 0.15)"),t.setProperty("--bim-icon-default",e.iconDefault??"#ffffff"),t.setProperty("--bim-text-primary",e.textPrimary??"#ffffff"),t.setProperty("--bim-component-bg-hover",e.componentBgHover??"rgba(248, 250, 252, 0.06)")}setLocales(){this.hideLabelEl.textContent=Ee("sectionAxis.actions.hide"),this.reverseLabelEl.textContent=Ee("sectionAxis.actions.reverse"),this.hideBtn.title=Ee("sectionAxis.actions.hide"),this.reverseBtn.title=Ee("sectionAxis.actions.reverse"),this.axisXBtn.title=Ee("sectionAxis.actions.axisX"),this.axisYBtn.title=Ee("sectionAxis.actions.axisY"),this.axisZBtn.title=Ee("sectionAxis.actions.axisZ")}setHiddenState(e){this.isHidden=e,this.updateHideButtonState()}getHiddenState(){return this.isHidden}setActiveAxis(e){this.activeAxis=e,this.updateAxisButtonsState()}getActiveAxis(){return this.activeAxis}destroy(){this.unsubscribeLocale&&(this.unsubscribeLocale(),this.unsubscribeLocale=null),this.unsubscribeTheme&&(this.unsubscribeTheme(),this.unsubscribeTheme=null),this.element.remove()}createDom(){const e=document.createElement("div");e.className="section-axis-panel";const t=document.createElement("div");t.className="section-axis-row-1",this.hideBtn=this.createButton("hide",ut("隐藏"),()=>this.handleHideToggle()),this.reverseBtn=this.createButton("reverse",ut("反向"),()=>this.handleReverse()),t.appendChild(this.hideBtn),t.appendChild(this.reverseBtn);const i=document.createElement("div");return i.className="section-axis-row-2",this.axisXBtn=this.createAxisButton("axisX","X",()=>this.handleAxisChange("x")),this.axisYBtn=this.createAxisButton("axisY","Y",()=>this.handleAxisChange("y")),this.axisZBtn=this.createAxisButton("axisZ","Z",()=>this.handleAxisChange("z")),i.appendChild(this.axisXBtn),i.appendChild(this.axisYBtn),i.appendChild(this.axisZBtn),e.appendChild(t),e.appendChild(i),e}createButton(e,t,i){const n=document.createElement("button");n.type="button",n.className="section-axis-btn";const r=document.createElement("div");r.className="section-axis-btn-icon",r.innerHTML=t,n.appendChild(r);const a=document.createElement("div");return a.className="section-axis-btn-label",n.appendChild(a),e==="hide"?this.hideLabelEl=a:e==="reverse"&&(this.reverseLabelEl=a),n.addEventListener("click",i),n}createAxisButton(e,t,i){const n=document.createElement("button");n.type="button",n.className="section-axis-btn section-axis-btn-text";const r=document.createElement("div");return r.className="section-axis-btn-label",r.textContent=t,n.appendChild(r),n.addEventListener("click",i),n}handleHideToggle(){this.isHidden=!this.isHidden,this.updateHideButtonState(),this.options.onHideToggle&&this.options.onHideToggle(this.isHidden)}handleReverse(){this.options.onReverse&&this.options.onReverse()}handleAxisChange(e){this.activeAxis!==e&&(this.activeAxis=e,this.updateAxisButtonsState(),this.options.onAxisChange&&this.options.onAxisChange(e))}updateHideButtonState(){this.isHidden?this.hideBtn.classList.add("active"):this.hideBtn.classList.remove("active")}updateAxisButtonsState(){this.axisXBtn.classList.toggle("active",this.activeAxis==="x"),this.axisYBtn.classList.toggle("active",this.activeAxis==="y"),this.axisZBtn.classList.toggle("active",this.activeAxis==="z")}}class k2 extends No{panel=null;constructor(e){super(e)}get dialogId(){return"section-axis-dialog"}get dialogTitle(){return"sectionAxis.dialogTitle"}get dialogWidth(){return 240}getDialogPosition(){const e=this.registry.container;if(!e)return{x:100,y:100};const t=e.clientWidth,i=e.clientHeight;return{x:t-this.dialogWidth-20,y:i-50-200}}createContent(){return this.panel=new qz({defaultAxis:"x",defaultHidden:!1,onHideToggle:e=>{console.log("[SectionAxisDialogManager] 隐藏切换:",e),e?this.engineComponent?.hideSection():this.engineComponent?.recoverSection()},onReverse:()=>{this.engineComponent?.reverseSection()},onAxisChange:e=>{console.log("[SectionAxisDialogManager] 切换轴向:",e),this.engineComponent?.activeSection(e)}}),this.panel.init(),this.panel.element}onDialogCreated(){if(this.dialog?.fitHeight(!1),!this.engineComponent){console.error("[SectionAxisDialogManager] Engine not initialized. Call initEngine() first.");return}this.engineComponent.activeSection("x")}onDialogClose(){this.registry.toolbar?.setBtnActive("section-axis",!1)}onBeforeDestroy(){this.engineComponent?.deactivateSection(),this.panel&&(this.panel.destroy(),this.panel=null)}getHiddenState(){return this.panel?.getHiddenState()??!1}setHiddenState(e){this.panel?.setHiddenState(e)}getActiveAxis(){return this.panel?.getActiveAxis()??"x"}setActiveAxis(e){this.panel?.setActiveAxis(e)}}const O2={x:{min:0,max:100},y:{min:0,max:100},z:{min:0,max:100}};class Zz{element;options;isHidden=!1;isReversed=!1;range;hideBtn;fitBtn;resetBtn;hideLabelEl;fitLabelEl;resetLabelEl;xLabelEl;yLabelEl;zLabelEl;unsubscribeLocale=null;unsubscribeTheme=null;xSlider;ySlider;zSlider;xMinHandle;xMaxHandle;yMinHandle;yMaxHandle;zMinHandle;zMaxHandle;dragState={isDragging:!1,axis:null,handleType:null,pointerId:null};constructor(e={}){this.options=e,this.isHidden=e.defaultHidden??!1,this.isReversed=e.defaultReversed??!1,this.range=JSON.parse(JSON.stringify(e.defaultRange??O2))}init(){this.element=this.createPanel(),this.unsubscribeLocale=$t.subscribe(()=>this.setLocales()),this.unsubscribeTheme=ct.subscribe(e=>this.setTheme(e)),this.setLocales(),this.setTheme(ct.getTheme()),this.updateButtonStates(),this.updateAllSlidersUI(),this.setupDragListeners()}setHiddenState(e){this.isHidden=e,this.updateButtonStates()}getHiddenState(){return this.isHidden}setReversedState(e){this.isReversed=e,this.updateButtonStates()}getReversedState(){return this.isReversed}setRange(e){e.x&&(this.range.x={...this.range.x,...e.x}),e.y&&(this.range.y={...this.range.y,...e.y}),e.z&&(this.range.z={...this.range.z,...e.z}),this.updateAllSlidersUI()}getRange(){return JSON.parse(JSON.stringify(this.range))}reset(){this.isHidden=this.options.defaultHidden??!1,this.isReversed=this.options.defaultReversed??!1,this.range=JSON.parse(JSON.stringify(this.options.defaultRange??O2)),this.updateButtonStates(),this.updateAllSlidersUI(),this.options.onReset?.(),this.options.onRangeChange?.(this.range)}createPanel(){const e=document.createElement("div");e.className="section-box-panel";const t=document.createElement("div");t.className="section-box-row-buttons",this.hideBtn=this.createButton("hide",Ee("sectionBox.actions.hide"),()=>{this.isHidden=!this.isHidden,this.updateButtonStates(),this.options.onHideToggle?.(this.isHidden)},"hide"),this.fitBtn=this.createButton("fit",Ee("sectionBox.actions.fitToModel"),()=>{this.options.onFitToModel?.()},"fit"),this.resetBtn=this.createButton("reset",Ee("sectionBox.actions.reset"),()=>this.reset(),"reset"),[this.hideBtn,this.fitBtn,this.resetBtn].forEach(n=>t.appendChild(n));const i=document.createElement("div");return i.className="section-box-sliders",i.addEventListener("pointerdown",n=>n.stopPropagation()),this.xSlider=this.createSlider("x",Ee("sectionBox.axes.x")),this.ySlider=this.createSlider("y",Ee("sectionBox.axes.y")),this.zSlider=this.createSlider("z",Ee("sectionBox.axes.z")),[this.xSlider,this.ySlider,this.zSlider].forEach(n=>i.appendChild(n)),e.appendChild(t),e.appendChild(i),e}createButton(e,t,i,n){const r=document.createElement("button");r.className="section-box-btn",r.title=t;const a={hide:"隐藏",reverse:"反向",fit:"适应到模型",reset:"重置"},o=document.createElement("div");o.className="section-box-btn-icon",o.innerHTML=ut(a[e]||e);const l=document.createElement("div");return l.className="section-box-btn-label",l.textContent=t,n==="hide"?this.hideLabelEl=l:n==="fit"?this.fitLabelEl=l:n==="reset"&&(this.resetLabelEl=l),r.appendChild(o),r.appendChild(l),r.addEventListener("click",i),r}createSlider(e,t){const i=document.createElement("div");i.className="section-box-slider";const n=document.createElement("div");n.className="section-box-slider-label",n.textContent=t,e==="x"?this.xLabelEl=n:e==="y"?this.yLabelEl=n:this.zLabelEl=n;const r=document.createElement("div");r.className="section-box-slider-track";const a=document.createElement("div");a.className="section-box-slider-range";const o=document.createElement("div");o.className="section-box-slider-handle",o.setAttribute("data-axis",e),o.setAttribute("data-handle","min");const l=document.createElement("div");return l.className="section-box-slider-handle",l.setAttribute("data-axis",e),l.setAttribute("data-handle","max"),r.append(a,o,l),i.append(n,r),e==="x"?(this.xMinHandle=o,this.xMaxHandle=l):e==="y"?(this.yMinHandle=o,this.yMaxHandle=l):(this.zMinHandle=o,this.zMaxHandle=l),i}setupDragListeners(){[this.xMinHandle,this.xMaxHandle,this.yMinHandle,this.yMaxHandle,this.zMinHandle,this.zMaxHandle].forEach(t=>{t.addEventListener("pointerdown",n=>{n.preventDefault(),n.stopPropagation(),t.setPointerCapture(n.pointerId),this.dragState={isDragging:!0,axis:t.getAttribute("data-axis"),handleType:t.getAttribute("data-handle"),pointerId:n.pointerId},t.classList.add("dragging"),t.closest(".section-box-slider").style.zIndex="100"}),t.addEventListener("pointermove",n=>{this.dragState.isDragging&&this.dragState.pointerId===n.pointerId&&this.onDragging(n)});const i=n=>{this.dragState.isDragging&&this.dragState.pointerId===n.pointerId&&(t.hasPointerCapture(n.pointerId)&&t.releasePointerCapture(n.pointerId),t.closest(".section-box-slider").style.zIndex="",t.classList.remove("dragging"),this.dragState={isDragging:!1,axis:null,handleType:null,pointerId:null})};t.addEventListener("pointerup",i),t.addEventListener("pointercancel",i),t.addEventListener("lostpointercapture",i)})}onDragging(e){const{axis:t,handleType:i}=this.dragState;if(!t||!i)return;const a=(t==="x"?this.xSlider:t==="y"?this.ySlider:this.zSlider).querySelector(".section-box-slider-track").getBoundingClientRect();let o=(e.clientX-a.left)/a.width*100;o=Math.max(0,Math.min(100,o));const l=this.range[t];i==="min"?l.min=Math.min(o,l.max):l.max=Math.max(o,l.min),this.updateSliderUI(t),this.options.onRangeChange?.(this.range)}updateSliderUI(e){const t=this.range[e],i=e==="x"?this.xMinHandle:e==="y"?this.yMinHandle:this.zMinHandle,n=e==="x"?this.xMaxHandle:e==="y"?this.yMaxHandle:this.zMaxHandle,a=(e==="x"?this.xSlider:e==="y"?this.ySlider:this.zSlider).querySelector(".section-box-slider-range");i.style.left=`${t.min}%`,n.style.left=`${t.max}%`,a.style.left=`${t.min}%`,a.style.width=`${t.max-t.min}%`,i.setAttribute("data-value",Math.round(t.min).toString()),n.setAttribute("data-value",Math.round(t.max).toString())}updateAllSlidersUI(){["x","y","z"].forEach(e=>this.updateSliderUI(e))}updateButtonStates(){this.hideBtn&&this.hideBtn.classList.toggle("active",this.isHidden)}setLocales(){this.hideLabelEl&&(this.hideLabelEl.textContent=Ee("sectionBox.actions.hide"),this.fitLabelEl.textContent=Ee("sectionBox.actions.fitToModel"),this.resetLabelEl.textContent=Ee("sectionBox.actions.reset"),this.xLabelEl.textContent=Ee("sectionBox.axes.x"),this.yLabelEl.textContent=Ee("sectionBox.axes.y"),this.zLabelEl.textContent=Ee("sectionBox.axes.z"),this.hideBtn.title=Ee("sectionBox.actions.hide"),this.fitBtn.title=Ee("sectionBox.actions.fitToModel"),this.resetBtn.title=Ee("sectionBox.actions.reset"))}setTheme(e){if(!this.element)return;const t=this.element.style;t.setProperty("--bim-bg-inset",e.bgInset??"#152232"),t.setProperty("--bim-bg-elevated",e.bgElevated??"#1f2d3e"),t.setProperty("--bim-border-default",e.borderDefault??"#334155"),t.setProperty("--bim-border-strong",e.borderStrong??"#475569"),t.setProperty("--bim-divider",e.divider??"#334155"),t.setProperty("--bim-primary",e.primary??"#3b82f6"),t.setProperty("--bim-primary-subtle",e.primarySubtle??"rgba(59, 130, 246, 0.15)"),t.setProperty("--bim-icon-default",e.iconDefault??"#ffffff"),t.setProperty("--bim-text-primary",e.textPrimary??"#ffffff"),t.setProperty("--bim-component-bg-hover",e.componentBgHover??"rgba(248, 250, 252, 0.06)")}destroy(){this.unsubscribeLocale?.(),this.unsubscribeTheme?.(),this.element&&this.element.parentElement&&this.element.parentElement.removeChild(this.element)}}class U2 extends No{panel=null;unsubscribeSectionMove=null;constructor(e){super(e)}get dialogId(){return"section-box-dialog"}get dialogTitle(){return"sectionBox.dialogTitle"}get dialogWidth(){return 280}getDialogPosition(){const e=this.registry.container;if(!e)return{x:100,y:100};const t=e.clientWidth,i=e.clientHeight;return{x:t-this.dialogWidth-20,y:i-50-300}}createContent(){return this.panel=new Zz({defaultHidden:!1,defaultReversed:!1,onHideToggle:e=>{console.log("[SectionBoxDialogManager] 隐藏切换:",e),e?this.engineComponent?.hideSection():this.engineComponent?.recoverSection()},onFitToModel:()=>{this.engineComponent?.scaleSectionBox()},onReset:()=>{this.engineComponent?.deactivateSection(),this.engineComponent?.activeSection("box"),this.engineComponent?.recoverSection()},onRangeChange:e=>{this.engineComponent?.setSectionBoxRange(e)}}),this.panel.init(),this.panel.element}onDialogCreated(){this.engineComponent?.activeSection("box"),this.dialog?.fitHeight(!1);const e=this.engineComponent;if(e){const t=i=>{i&&this.panel&&this.panel.setRange(i)};e.onRawEvent("section-move",t),this.unsubscribeSectionMove=()=>e.offRawEvent("section-move",t)}}onDialogClose(){this.unsubscribeSectionMove&&(this.unsubscribeSectionMove(),this.unsubscribeSectionMove=null),this.registry.toolbar?.setBtnActive("section-box",!1)}onBeforeDestroy(){this.unsubscribeSectionMove&&(this.unsubscribeSectionMove(),this.unsubscribeSectionMove=null),this.engineComponent?.deactivateSection(),this.panel&&(this.panel.destroy(),this.panel=null)}getHiddenState(){return this.panel?.getHiddenState()??!1}setHiddenState(e){this.panel?.setHiddenState(e)}getReversedState(){return this.panel?.getReversedState()??!1}setReversedState(e){this.panel?.setReversedState(e)}getRange(){return this.panel?.getRange()??null}setRange(e){this.panel?.setRange(e)}}class Yz{element;options;state={mode:"none",isPlanViewActive:!1,speed:1,gravity:!1,collision:!1,characterModel:"construction-worker",walkMode:"walk"};planViewBtn;pathModeBtn;settingsContainer;speedControl;speedDecreaseBtn;speedIncreaseBtn;speedDisplay;gravityCheckbox;gravityLabel;collisionCheckbox;collisionLabel;characterModelSelect;characterModelLabel;walkModeSelect;walkModeLabel;exitBtn;unsubscribeLocale=null;unsubscribeTheme=null;constructor(e={}){this.options=e,this.state.speed=e.defaultSpeed??1,this.state.gravity=e.defaultGravity??!1,this.state.collision=e.defaultCollision??!1,this.state.characterModel=e.defaultCharacterModel??"construction-worker",this.state.walkMode=e.defaultWalkMode??"walk"}init(){this.element=this.createPanel(),this.updateSettingsView(),this.unsubscribeLocale=$t.subscribe(()=>this.setLocales()),this.unsubscribeTheme=ct.subscribe(e=>this.setTheme(e)),this.setLocales(),this.setTheme(ct.getTheme())}setPlanViewActive(e){this.state.isPlanViewActive=e,this.updateButtonStates()}setPathModeActive(e){if(!e&&this.state.mode!=="path")return;const t=e?"path":"none";this.setMode(t)}getState(){return{...this.state}}createPanel(){const e=document.createElement("div");e.className="walk-control-panel";const t=this.createLeftButtons(),i=document.createElement("div");i.className="walk-divider",this.settingsContainer=this.createSettingsContainer();const n=document.createElement("div");n.className="walk-divider";const r=this.createExitButton();return e.appendChild(t),e.appendChild(i),e.appendChild(this.settingsContainer),e.appendChild(n),e.appendChild(r),e}createLeftButtons(){const e=document.createElement("div");return e.className="walk-control-left",this.planViewBtn=this.createIconButton("plan-view",()=>{this.state.isPlanViewActive=!this.state.isPlanViewActive,this.updateButtonStates(),this.options.onPlanViewToggle?.(this.state.isPlanViewActive)}),this.pathModeBtn=this.createIconButton("path",()=>{const t=this.state.mode==="path"?"none":"path";this.setMode(t),this.options.onPathModeToggle?.(t==="path")}),e.appendChild(this.planViewBtn),e.appendChild(this.pathModeBtn),e}createSettingsContainer(){const e=document.createElement("div");e.className="walk-control-settings",this.speedControl=this.createSpeedControl();const t=document.createElement("label");t.className="walk-checkbox-wrapper walk-checkbox-gravity",this.gravityCheckbox=document.createElement("input"),this.gravityCheckbox.type="checkbox",this.gravityCheckbox.className="walk-checkbox",this.gravityCheckbox.checked=this.state.gravity,this.gravityCheckbox.addEventListener("change",()=>{this.state.gravity=this.gravityCheckbox.checked,this.options.onGravityToggle?.(this.state.gravity)}),this.gravityLabel=document.createElement("span"),this.gravityLabel.className="walk-checkbox-label",t.appendChild(this.gravityCheckbox),t.appendChild(this.gravityLabel);const i=document.createElement("label");i.className="walk-checkbox-wrapper walk-checkbox-collision",this.collisionCheckbox=document.createElement("input"),this.collisionCheckbox.type="checkbox",this.collisionCheckbox.className="walk-checkbox",this.collisionCheckbox.checked=this.state.collision,this.collisionCheckbox.addEventListener("change",()=>{this.state.collision=this.collisionCheckbox.checked,this.options.onCollisionToggle?.(this.state.collision)}),this.collisionLabel=document.createElement("span"),this.collisionLabel.className="walk-checkbox-label",i.appendChild(this.collisionCheckbox),i.appendChild(this.collisionLabel);const n=document.createElement("div");n.className="walk-select-wrapper walk-select-wrapper-character-model",this.characterModelLabel=document.createElement("label"),this.characterModelLabel.className="walk-select-label",this.characterModelSelect=document.createElement("select"),this.characterModelSelect.className="walk-select walk-select-character-model",this.characterModelSelect.addEventListener("change",()=>{this.state.characterModel=this.characterModelSelect.value,this.options.onCharacterModelChange?.(this.state.characterModel)}),n.appendChild(this.characterModelLabel),n.appendChild(this.characterModelSelect);const r=document.createElement("div");return r.className="walk-select-wrapper walk-select-wrapper-walk-mode",this.walkModeLabel=document.createElement("label"),this.walkModeLabel.className="walk-select-label",this.walkModeSelect=document.createElement("select"),this.walkModeSelect.className="walk-select walk-select-walk-mode",this.walkModeSelect.addEventListener("change",()=>{this.state.walkMode=this.walkModeSelect.value,this.options.onWalkModeChange?.(this.state.walkMode)}),r.appendChild(this.walkModeLabel),r.appendChild(this.walkModeSelect),e.appendChild(this.speedControl),e.appendChild(n),e.appendChild(r),e.appendChild(t),e.appendChild(i),e}createSpeedControl(){const e=document.createElement("div");e.className="walk-speed-control";const t=document.createElement("label");t.className="walk-speed-label",t.textContent=Ee("walkControl.speed");const i=document.createElement("div");return i.className="walk-speed-group",this.speedDecreaseBtn=document.createElement("button"),this.speedDecreaseBtn.className="walk-speed-btn",this.speedDecreaseBtn.textContent="-",this.speedDecreaseBtn.addEventListener("click",()=>{this.state.speed>1&&(this.state.speed--,this.updateSpeedDisplay(),this.options.onSpeedChange?.(this.state.speed))}),this.speedDisplay=document.createElement("div"),this.speedDisplay.className="walk-speed-display",this.speedDisplay.textContent=`${this.state.speed}X`,this.speedIncreaseBtn=document.createElement("button"),this.speedIncreaseBtn.className="walk-speed-btn",this.speedIncreaseBtn.textContent="+",this.speedIncreaseBtn.addEventListener("click",()=>{this.state.speed<10&&(this.state.speed++,this.updateSpeedDisplay(),this.options.onSpeedChange?.(this.state.speed))}),i.appendChild(this.speedDecreaseBtn),i.appendChild(this.speedDisplay),i.appendChild(this.speedIncreaseBtn),e.appendChild(t),e.appendChild(i),e}createIconButton(e,t){const i=document.createElement("button");return i.className=`walk-icon-btn walk-icon-btn-${e}`,i.innerHTML=this.getIconSVG(e),i.addEventListener("click",t),i}createExitButton(){const e=document.createElement("button");return e.className="walk-exit-btn",e.addEventListener("click",()=>{this.options.onExit?.()}),this.exitBtn=e,e}setMode(e){const t=this.state.mode;t==="walk"&&e!=="walk"&&this.options.onWalkModeToggle?.(!1),t==="path"&&e!=="path"&&this.options.onPathModeToggle?.(!1),this.state.mode=e,e==="path"?(this.state.gravity=!1,this.state.collision=!1,this.gravityCheckbox.checked=!1,this.gravityCheckbox.disabled=!0,this.collisionCheckbox.checked=!1,this.collisionCheckbox.disabled=!0):(this.gravityCheckbox.disabled=!1,this.collisionCheckbox.disabled=!1),this.updateButtonStates(),this.updateSettingsView(),this.updateSpeedButtonStates()}updateButtonStates(){this.planViewBtn.classList.toggle("active",this.state.isPlanViewActive),this.pathModeBtn.classList.toggle("active",this.state.mode==="path")}updateSettingsView(){const e=this.speedControl,t=this.gravityCheckbox.parentElement,i=this.collisionCheckbox.parentElement,n=this.characterModelSelect.parentElement,r=this.walkModeSelect.parentElement;this.state.mode==="walk"?(e.style.display="none",t.style.display="flex",i.style.display="flex",n.style.display="flex",r.style.display="flex"):(e.style.display="flex",t.style.display="flex",i.style.display="flex",n.style.display="none",r.style.display="none")}updateSpeedDisplay(){this.speedDisplay.textContent=`${this.state.speed}X`,this.updateSpeedButtonStates()}updateSpeedButtonStates(){this.speedDecreaseBtn.disabled=this.state.speed<=1,this.speedIncreaseBtn.disabled=this.state.speed>=10}getIconSVG(e){return{"plan-view":ut("地图"),path:ut("路径漫游"),walk:ut("第一人称漫游")}[e]||""}setLocales(){const e=this.speedControl.querySelector(".walk-speed-label");e&&(e.textContent=Ee("walkControl.speed")),this.gravityLabel.textContent=Ee("walkControl.gravity"),this.collisionLabel.textContent=Ee("walkControl.collision"),this.characterModelLabel.textContent=Ee("walkControl.characterModel.label"),this.characterModelSelect.innerHTML="";const t=document.createElement("option");t.value="construction-worker",t.textContent=Ee("walkControl.characterModel.constructionWorker"),t.selected=this.state.characterModel==="construction-worker",this.characterModelSelect.appendChild(t);const i=document.createElement("option");i.value="office-male",i.textContent=Ee("walkControl.characterModel.officeMale"),i.selected=this.state.characterModel==="office-male",this.characterModelSelect.appendChild(i),this.walkModeLabel.textContent=Ee("walkControl.walkMode.label"),this.walkModeSelect.innerHTML="";const n=document.createElement("option");n.value="walk",n.textContent=Ee("walkControl.walkMode.walk"),n.selected=this.state.walkMode==="walk",this.walkModeSelect.appendChild(n);const r=document.createElement("option");r.value="run",r.textContent=Ee("walkControl.walkMode.run"),r.selected=this.state.walkMode==="run",this.walkModeSelect.appendChild(r),this.exitBtn.textContent=Ee("walkControl.exit")}setTheme(e){if(!this.element)return;const t=this.element.style;t.setProperty("--bim-bg-base",e.bgBase??"#152232"),t.setProperty("--bim-bg-elevated",e.bgElevated??"#1f2d3e"),t.setProperty("--bim-bg-inset",e.bgInset??"#152232"),t.setProperty("--bim-border-default",e.borderDefault??"#334155"),t.setProperty("--bim-border-strong",e.borderStrong??"#475569"),t.setProperty("--bim-border-subtle",e.borderSubtle??"#1e293b"),t.setProperty("--bim-divider",e.divider??"#334155"),t.setProperty("--bim-shadow-xl",e.shadowXl??"0 20px 40px rgba(0, 0, 0, 0.3)"),t.setProperty("--bim-primary",e.primary??"#3b82f6"),t.setProperty("--bim-primary-hover",e.primaryHover??"#60a5fa"),t.setProperty("--bim-primary-subtle",e.primarySubtle??"rgba(59, 130, 246, 0.15)"),t.setProperty("--bim-text-primary",e.textPrimary??"#ffffff"),t.setProperty("--bim-text-inverse",e.textInverse??"#152232"),t.setProperty("--bim-icon-default",e.iconDefault??"#ffffff"),t.setProperty("--bim-component-bg-hover",e.componentBgHover??"rgba(248, 250, 252, 0.06)"),t.setProperty("--bim-component-bg-active",e.componentBgActive??"rgba(248, 250, 252, 0.1)")}destroy(){this.unsubscribeLocale?.(),this.unsubscribeTheme?.(),this.element&&this.element.parentElement&&this.element.parentElement.removeChild(this.element)}}class $z{element;registry;unsubscribeLocale=null;unsubscribeTheme=null;constructor(e){this.registry=e}points=[];duration=1e4;loop=!1;playingPointIndex=-1;isPlaying=!1;init(){this.element=document.createElement("div"),this.element.className="walk-path-panel",this.unsubscribeLocale=$t.subscribe(()=>this.render()),this.unsubscribeTheme=ct.subscribe(e=>this.setTheme(e)),this.loadPointsFromEngine(),this.render(),this.setTheme(ct.getTheme())}loadPointsFromEngine(){const e=this.registry.engine3d?.getEngineComponent()?.pathRoamingGetPoints()??[];this.points=e.map((t,i)=>({index:i}))}render(){this.element.innerHTML="";const e=this.createSettingsSection();this.element.appendChild(e);const t=this.createPointsSection();this.element.appendChild(t);const i=this.createPlayButton();this.element.appendChild(i)}createSettingsSection(){const e=document.createElement("div");e.className="walk-path-settings";const t=document.createElement("div");t.className="walk-path-form-group";const i=document.createElement("label");i.textContent=Ee("walkControl.path.duration");const n=document.createElement("div");n.className="walk-path-input-wrapper";const r=document.createElement("input");r.type="number",r.className="walk-path-input",r.value=String(this.duration/1e3),r.min="1",r.oninput=h=>{const d=parseInt(h.target.value)||1;this.duration=d*1e3};const a=document.createElement("span");a.className="walk-path-unit",a.textContent=Ee("walkControl.path.durationUnit"),n.appendChild(r),n.appendChild(a),t.appendChild(i),t.appendChild(n);const o=document.createElement("div");o.className="walk-path-form-group walk-path-form-group-inline";const l=document.createElement("input");l.type="checkbox",l.id="walk-path-loop-checkbox",l.className="walk-path-checkbox",l.checked=this.loop,l.onchange=h=>{this.loop=h.target.checked};const c=document.createElement("label");return c.htmlFor="walk-path-loop-checkbox",c.textContent=Ee("walkControl.path.loop"),o.appendChild(l),o.appendChild(c),e.appendChild(t),e.appendChild(o),e}createPointsSection(){const e=document.createElement("div");e.className="walk-path-points-section";const t=document.createElement("div");t.className="walk-path-points-toolbar";const i=document.createElement("button");i.className="walk-path-btn walk-path-btn-small",i.textContent=`+ ${Ee("walkControl.path.addPoint")}`,i.onclick=()=>this.addPoint();const n=document.createElement("button");n.className="walk-path-btn walk-path-btn-small walk-path-btn-danger",n.textContent=Ee("walkControl.path.deleteAll"),n.onclick=()=>this.deleteAllPoints(),t.appendChild(i),t.appendChild(n),e.appendChild(t);const r=document.createElement("div");if(r.className="walk-path-points-list",this.points.length===0){const a=document.createElement("div");a.className="walk-path-empty",a.textContent=Ee("walkControl.path.noPoints"),r.appendChild(a)}else this.points.forEach((a,o)=>{const l=this.createPointItem(o);r.appendChild(l)});return e.appendChild(r),e}createPointItem(e){const t=document.createElement("div");t.className="walk-path-point-item",this.playingPointIndex===e&&t.classList.add("walk-path-point-item-active");const i=document.createElement("span");i.className="walk-path-point-name",i.textContent=`${Ee("walkControl.path.point")}${e}`;const n=document.createElement("div");n.className="walk-path-point-actions";const r=document.createElement("button");r.className="walk-path-btn-icon",r.innerHTML="▶",r.title=Ee("walkControl.path.play"),r.onclick=o=>{o.stopPropagation(),this.jumpToPoint(e)};const a=document.createElement("button");return a.className="walk-path-btn-icon walk-path-btn-icon-danger",a.innerHTML="×",a.onclick=o=>{o.stopPropagation(),this.deletePoint(e)},n.appendChild(r),n.appendChild(a),t.appendChild(i),t.appendChild(n),t}createPlayButton(){const e=document.createElement("div");e.className="walk-path-btn-group";const t=document.createElement("button");t.className="walk-path-btn walk-path-btn-play",t.textContent=`▶ ${Ee("walkControl.path.play")}`,t.disabled=this.points.length===0||this.isPlaying,t.onclick=()=>this.playPath();const i=document.createElement("button");return i.className="walk-path-btn walk-path-btn-stop",i.textContent=`■ ${Ee("walkControl.path.stop")}`,i.disabled=!this.isPlaying,i.onclick=()=>this.stopPath(),e.appendChild(t),e.appendChild(i),e}addPoint(){this.registry.engine3d?.getEngineComponent()?.pathRoamingAddPoint();const e=this.points.length;this.points.push({index:e}),this.render()}deletePoint(e){this.registry.engine3d?.getEngineComponent()?.pathRoamingRemovePoint(e),this.points.splice(e,1),this.points.forEach((t,i)=>t.index=i),this.render()}deleteAllPoints(){this.registry.engine3d?.getEngineComponent()?.pathRoamingClearPoints(),this.points=[],this.render()}jumpToPoint(e){this.registry.engine3d?.getEngineComponent()?.pathRoamingJumpToPoint(e)}playPath(){this.points.length!==0&&(this.isPlaying=!0,this.render(),console.log("[WalkPathPanel] 开始播放漫游",{duration:this.duration,loop:this.loop,pointsCount:this.points.length}),this.registry.engine3d?.getEngineComponent()?.pathRoamingPlay({duration:this.duration,loop:this.loop,onPointComplete:e=>{console.log("[WalkPathPanel] onPointComplete",{pointIndex:e}),this.playingPointIndex=e,this.render()},onComplete:()=>{console.log("[WalkPathPanel] onComplete 播放完成"),this.isPlaying=!1,this.playingPointIndex=-1,this.render()}}))}stopPath(){console.log("[WalkPathPanel] 停止漫游"),this.registry.engine3d?.getEngineComponent()?.pathRoamingStop(),this.isPlaying=!1,this.playingPointIndex=-1,this.render()}setLocales(){this.render()}setTheme(e){this.element&&(this.element.style.setProperty("--bim-text-primary",e.textPrimary??"#fff"),this.element.style.setProperty("--bim-text-secondary",e.textSecondary??"#94a3b8"),this.element.style.setProperty("--bim-bg-elevated",e.bgElevated??"#1f2d3e"),this.element.style.setProperty("--bim-border-default",e.borderDefault??"#334155"),this.element.style.setProperty("--bim-primary",e.primary??"#3b82f6"))}destroy(){this.isPlaying&&this.stopPath(),this.unsubscribeLocale?.(),this.unsubscribeTheme?.(),this.element?.parentElement&&this.element.parentElement.removeChild(this.element)}}class Kz extends No{panel=null;constructor(e){super(e)}get dialogId(){return"walk-path-dialog"}get dialogTitle(){return"walkControl.path.dialogTitle"}get dialogWidth(){return 300}get dialogHeight(){return 450}init(){}getDialogPosition(){const e=this.registry.container;return e?{x:e.clientWidth-this.dialogWidth-20,y:20}:{x:100,y:100}}createContent(){return this.panel=new $z(this.registry),this.panel.init(),this.panel.element}onDialogClose(){this.registry.walkControl&&this.registry.walkControl.panel&&this.registry.walkControl.panel.setPathModeActive(!1)}onBeforeDestroy(){this.panel&&(this.panel.destroy(),this.panel=null)}}class B2 extends jn{panel=null;pathManager=null;constructor(e){super(e)}init(){this.pathManager=new Kz(this.registry),this.pathManager.init()}show(){this.registry.toolbar?.hide(),console.log("[WalkControl] 打开漫游面板,激活第一人称模式"),this.engineComponent?.activateFirstPersonMode(),this.panel=new Yz({onPlanViewToggle:t=>{console.log("[WalkControl] 小地图:",t),this.engineComponent?.toggleMiniMap(),this.registry.toolbar?.setBtnActive("map",t),this.emit("walk:plan-view-toggle",{isActive:t})},onPathModeToggle:t=>{console.log("[WalkControl] 路径漫游:",t),t?this.pathManager?.show():this.pathManager?.hide(),this.emit("walk:path-mode-toggle",{isActive:t})},onWalkModeToggle:t=>{console.log("[WalkControl] 第三人称漫游按钮点击:",t),t&&(this.pathManager?.hide(),alert("第三人称功能开发中")),this.emit("walk:walk-mode-toggle",{isActive:t})},onSpeedChange:t=>{console.log("[WalkControl] 速度变化:",t);const i=t*.1;this.engineComponent?.setWalkSpeed(i),this.emit("walk:speed-change",{speed:t})},onGravityToggle:t=>{console.log("[WalkControl] 重力:",t),this.engineComponent?.setWalkGravity(t),this.emit("walk:gravity-toggle",{enabled:t})},onCollisionToggle:t=>{console.log("[WalkControl] 碰撞:",t),this.engineComponent?.setWalkCollision(t),this.emit("walk:collision-toggle",{enabled:t})},onCharacterModelChange:t=>{console.log("[WalkControl] 角色模型:",t)},onWalkModeChange:t=>{console.log("[WalkControl] 行走模式:",t)},onExit:()=>{this.hide()}}),this.panel.init();const e=this.engineComponent?.getMiniMapState()??!1;this.panel.setPlanViewActive(e),this.registry.container?(this.panel.element.style.position="absolute",this.panel.element.style.bottom="20px",this.panel.element.style.left="50%",this.panel.element.style.transform="translateX(-50%)",this.panel.element.style.zIndex="1000",this.registry.container.appendChild(this.panel.element)):console.warn("[WalkControlManager] Container not found")}hide(){this.pathManager?.hide(),this.engineComponent?.getMiniMapState()&&this.engineComponent.toggleMiniMap(),console.log("[WalkControl] 关闭漫游面板,退出第一人称模式"),this.engineComponent?.deactivateFirstPersonMode(),this.panel&&(this.panel.destroy(),this.panel=null),this.registry.toolbar?.setBtnActive("map",!1),this.registry.toolbar&&this.registry.toolbar.show()}destroy(){this.hide(),this.pathManager?.destroy(),this.pathManager=null,super.destroy()}}class F2 extends No{get dialogId(){return"engine-info-dialog"}get dialogTitle(){return"info.dialogTitle"}get dialogWidth(){return 280}constructor(e){super(e)}init(){}getDialogPosition(){const e=this.registry.container;if(!e)return{x:100,y:100};const t=e.clientWidth,i=e.clientHeight;return{x:(t-this.dialogWidth)/2,y:(i-150)/2}}createContent(){const e=this.engineComponent?.getEngineInfo()??null,t=document.createElement("div");t.className="engine-info-content",t.style.cssText="padding: 16px;";const i=(n,r)=>{const a=document.createElement("div");a.style.cssText="display: flex; justify-content: space-between; margin-bottom: 12px; font-size: 14px;";const o=document.createElement("span");o.style.cssText="color: var(--bim-text-secondary, #94a3b8);",o.textContent=n;const l=document.createElement("span");return l.style.cssText="color: var(--bim-text-primary, #fff); font-weight: 500;",l.textContent=String(r),a.appendChild(o),a.appendChild(l),a};return t.appendChild(i(Ee("info.meshCount"),e?.meshCount??"-")),t.appendChild(i(Ee("info.totalTriangles"),e?.totalTriangles??"-")),t.appendChild(i(Ee("info.totalVertices"),e?.totalVertices??"-")),t}}const ly="font-size: 15px; font-weight: 600; color: var(--bim-text-primary, #0f172a); margin-bottom: 4px;",Jz="height: 1px; background: var(--bim-divider, #e2e8f0); margin: 8px 0;",cy="display: flex; align-items: center; justify-content: space-between; gap: 12px;",hy="display: flex; flex-direction: column; gap: 6px;",Qz="font-size: 12px; color: var(--bim-text-secondary, #475569); min-width: 32px; text-align: right;",Xn="var(--bim-border-default, #e2e8f0)",dy="var(--bim-bg-inset, #f1f5f9)",ko="var(--bim-primary, #3b82f6)",Oo="var(--bim-text-primary, #0f172a)",uc="var(--bim-text-inverse, #ffffff)",e9="var(--bim-component-bg-hover, rgba(0,0,0,0.04))",z2={render:{mode:"advanced",contrast:50,saturation:50,shadowIntensity:50,lightIntensity:50,gtaoIntensity:50},display:{showEdge:!1,edgeOpacity:30,showGrid:!1,showLevel:!1,showGround:!1,groundId:"0",groundHeight:0},environment:{type:"none",hdrId:"0",hdrIntensity:20,skyPreset:"sunrise_clear",skyParams:{},skyIntensity:20}},t9={ground:[],hdr:[],sky:[]};class Rr extends No{get dialogId(){return"setting-dialog"}get dialogTitle(){return"setting.dialogTitle"}get dialogWidth(){return 420}settings=structuredClone(z2);presetList=[];selectedPresetId=null;presetLists=structuredClone(t9);savedPosition=null;savedScrollTop=null;isDirty=!1;saveAsModalEl=null;deleteConfirmModalEl=null;unsubscribeLocale=null;static INTERNAL_DEFAULT_PRESET_ID="__internal-default-preset__";constructor(e){super(e)}init(){this.ensurePresetListWithInternalDefault(),this.applySelectedPresetFromList(),this.unsubscribeLocale=$t.subscribe(()=>{this.updateInternalDefaultPresetLabel(),this.isOpen()&&this.reopenAtSamePosition()})}destroy(){this.unsubscribeLocale&&(this.unsubscribeLocale(),this.unsubscribeLocale=null),this.closeSaveAsPresetModal(),this.closeDeletePresetConfirmModal(),super.destroy()}ensurePresetListWithInternalDefault(){const e=this.createInternalDefaultPreset(),t=this.presetList.filter(i=>i.id!==Rr.INTERNAL_DEFAULT_PRESET_ID);this.presetList=[...t,e],(!this.selectedPresetId||!this.presetList.some(i=>i.id===this.selectedPresetId))&&(this.selectedPresetId=e.id)}updateInternalDefaultPresetLabel(){const e=this.presetList.findIndex(t=>t.id===Rr.INTERNAL_DEFAULT_PRESET_ID);e<0||(this.presetList[e]={...this.presetList[e],presetName:Ee("setting.defaultPresetLabel")},this.ensurePresetListWithInternalDefault())}createInternalDefaultPreset(){return{id:Rr.INTERNAL_DEFAULT_PRESET_ID,presetName:Ee("setting.defaultPresetLabel"),isDefault:!0,settings:structuredClone(z2),source:"sdk-default",readonly:!1}}setPresetList(e){this.presetList=this.normalizePresetList(e),this.ensurePresetListWithInternalDefault(),this.selectedPresetId=this.resolveDefaultPresetId(this.presetList),!this.selectedPresetId&&this.presetList.length>0&&(this.selectedPresetId=this.presetList[0].id),this.applySelectedPresetFromList(),this.isDirty=!1,this.updateUndoRestoreVisibility(),this.isOpen()&&this.reopenAtSamePosition()}getDialogPosition(){if(this.savedPosition){const n=this.savedPosition;return this.savedPosition=null,n}const e=this.registry.container;if(!e)return{x:100,y:100};const t=e.clientWidth,i=e.clientHeight;return{x:(t-this.dialogWidth)/2,y:Math.max(20,(i-560)/2)}}createContent(){this.syncFromEngine(),this.ensureSliderStyle();const e=document.createElement("div");e.style.cssText="max-height: 520px; display: flex; flex-direction: column;";const t=document.createElement("div");t.className="setting-scroll-body",t.style.cssText="padding: 14px 16px 12px 16px; overflow-y: auto; display: flex; flex-direction: column; gap: 6px;",t.appendChild(this.createRenderModeSection()),t.appendChild(this.createSliderSection(Ee("setting.lightIntensity"),this.settings.render.lightIntensity,0,100,n=>this.updateSettings({render:{lightIntensity:n}}))),this.settings.render.mode==="advanced"&&(t.appendChild(this.createSliderSection(Ee("setting.contrast"),this.settings.render.contrast,0,100,n=>this.updateSettings({render:{contrast:n}}))),t.appendChild(this.createSliderSection(Ee("setting.saturation"),this.settings.render.saturation,0,100,n=>this.updateSettings({render:{saturation:n}})))),t.appendChild(this.createDivider()),t.appendChild(this.createDisplaySection()),t.appendChild(this.createDivider()),t.appendChild(this.createEnvironmentSection());const i=document.createElement("div");return i.style.cssText=` padding: 12px 16px 14px 16px; border-top: 1px solid ${Xn}; background: var(--bim-bg-elevated, #fff); position: sticky; bottom: 0; z-index: 1; `,i.appendChild(this.createBottomActionBar()),e.appendChild(t),e.appendChild(i),e}syncFromEngine(){const e=this.engineComponent;e&&(this.ensurePresetListWithInternalDefault(),this.presetLists=e.getPresetLists(),this.settings=e.getSettings(),this.isDirty=this.getCurrentSettingsDirtyState(this.settings),this.selectedPresetId===null&&(this.selectedPresetId=this.resolveDefaultPresetId(this.presetList),!this.selectedPresetId&&this.presetList.length>0&&(this.selectedPresetId=this.presetList[0].id)))}applySelectedPresetFromList(){const e=this.presetList.find(t=>t.id===this.selectedPresetId)??this.presetList.find(t=>t.isDefault)??this.presetList[0];e&&(this.selectedPresetId=e.id,this.settings=structuredClone(e.settings),this.isDirty=!1,this.engineComponent?.setSettings(e.settings),this.updateUndoRestoreVisibility())}normalizePresetList(e){const t=new Set,i=[];for(const n of e){if(!n||typeof n.id!="string")continue;const r=n.id.trim();r!==Rr.INTERNAL_DEFAULT_PRESET_ID&&(!r||t.has(r)||(t.add(r),i.push({id:r,presetName:n.presetName?.trim()||r,isDefault:!!n.isDefault,settings:structuredClone(n.settings),readonly:!!n.readonly,source:n.source})))}return i}resolveDefaultPresetId(e){return e.length===0?null:e.find(i=>i.isDefault)?.id??null}createDivider(){const e=document.createElement("div");return e.style.cssText=Jz,e}createBottomActionBar(){const e=document.createElement("div");e.style.cssText="display: flex; flex-direction: column; gap: 8px;";const t=document.createElement("button");t.id=`${this.dialogId}-undo-btn`,t.type="button",t.textContent=Ee("setting.undoChanges"),t.style.cssText=` border: none; background: transparent; color: #ef4444; text-align: left; cursor: pointer; font-size: 13px; padding: 0; text-decoration: underline; display: ${this.isDirty&&this.selectedPresetId?"block":"none"}; `,t.addEventListener("click",()=>{this.selectedPresetId&&this.applyPresetById(this.selectedPresetId)}),e.appendChild(t);const i=document.createElement("div"),n=this.isSelectedPresetDeletable();return i.style.cssText=n?"display: grid; grid-template-columns: minmax(0, 1.55fr) 40px minmax(0, 0.7fr) minmax(0, 0.95fr); gap: 8px; align-items: center;":"display: grid; grid-template-columns: minmax(0, 1.55fr) minmax(0, 0.7fr) minmax(0, 0.95fr); gap: 8px; align-items: center;",i.appendChild(this.createBottomPresetSelect()),n&&i.appendChild(this.createDeleteIconButton()),i.appendChild(this.createFooterActionButton(Ee("setting.savePreset"),{background:ko,color:uc,border:"none",onClick:()=>this.handleSaveCurrentPreset(),compact:!0})),i.appendChild(this.createFooterActionButton(Ee("setting.saveAsNewPreset"),{background:ko,color:uc,border:"none",onClick:()=>this.openSaveAsPresetModal(),compact:!0})),e.appendChild(i),e}createDeleteIconButton(){const e=document.createElement("button");return e.type="button",e.title=Ee("setting.deletePreset"),e.setAttribute("aria-label",Ee("setting.deletePreset")),e.innerHTML=` `,e.style.cssText=` width: 40px; height: 36px; border-radius: 6px; border: 1px solid #fca5a5; background: var(--bim-danger-soft, #fecaca); color: #991b1b; cursor: pointer; display: inline-flex; align-items: center; justify-content: center; `,e.addEventListener("click",()=>this.openDeletePresetConfirmModal()),e}isSelectedPresetDeletable(){return!this.selectedPresetId||this.selectedPresetId===Rr.INTERNAL_DEFAULT_PRESET_ID?!1:this.presetList.some(e=>e.id===this.selectedPresetId)}createBottomPresetSelect(){const e=[];if(this.presetList.length===0)e.push({value:"",label:Ee("setting.presetSelectPlaceholder")});else for(const i of this.presetList)e.push({value:i.id,label:i.presetName});return this.selectedPresetId&&this.presetList.some(i=>i.id===this.selectedPresetId)||(this.selectedPresetId=this.resolveDefaultPresetId(this.presetList)??this.presetList[0]?.id??null),this.createSelect(e,this.selectedPresetId??"",i=>{i&&this.applyPresetById(i)})}createFooterActionButton(e,t){const i=document.createElement("button");return i.type="button",i.textContent=e,i.style.cssText=` height: ${t.compact?"36px":"40px"}; border-radius: 6px; cursor: pointer; font-size: ${t.compact?"13px":"14px"}; font-weight: 600; padding: 0 8px; white-space: nowrap; background: ${t.background}; color: ${t.color}; border: ${t.border}; `,i.addEventListener("click",t.onClick),i}createRenderModeSection(){const e=document.createElement("div");e.style.cssText=hy;const t=document.createElement("div");t.style.cssText=ly,t.textContent=Ee("setting.renderMode"),e.appendChild(t);const i=document.createElement("div");i.style.cssText=` display: flex; gap: 0; border-radius: 6px; overflow: hidden; border: 1px solid ${Xn}; `;const n=[{key:"simple",labelKey:"setting.modes.simple"},{key:"balance",labelKey:"setting.modes.balance"},{key:"advanced",labelKey:"setting.modes.advanced"}];for(let r=0;r{o||(l.style.background=e9)}),l.addEventListener("mouseleave",()=>{o||(l.style.background="transparent")}),l.addEventListener("click",()=>{this.updateSettings({render:{mode:a.key}},!0)}),i.appendChild(l)}return e.appendChild(i),e}createDisplaySection(){const e=document.createElement("div");e.style.cssText=hy;const t=document.createElement("div");if(t.style.cssText=ly,t.textContent=Ee("setting.displaySection"),e.appendChild(t),e.appendChild(this.createToggleRow(Ee("setting.edgeLine"),this.settings.display.showEdge,i=>{this.updateSettings({display:{showEdge:i}},!0)})),this.settings.display.showEdge&&e.appendChild(this.createSliderSection(Ee("setting.edgeOpacity"),this.settings.display.edgeOpacity,0,100,i=>this.updateSettings({display:{edgeOpacity:i}}))),e.appendChild(this.createToggleRow(Ee("setting.showGrid"),this.settings.display.showGrid,i=>{this.updateSettings({display:{showGrid:i}})})),e.appendChild(this.createToggleRow(Ee("setting.showLevel"),this.settings.display.showLevel,i=>{this.updateSettings({display:{showLevel:i}})})),e.appendChild(this.createToggleRow(Ee("setting.ground"),this.settings.display.showGround,i=>{const n=i?this.settings.display.groundId&&this.settings.display.groundId!=="0"?this.settings.display.groundId:this.presetLists.ground[0]?.id||"1":"0";this.updateSettings({display:{showGround:i,groundId:n}}),this.reopenAtSamePosition()})),this.settings.display.showGround){const i=this.presetLists.ground.map(c=>({value:c.id,label:this.getLocalizedPresetName(c.names,c.id)}));e.appendChild(this.createSelect(i,this.settings.display.groundId,c=>{this.updateSettings({display:{groundId:c}})}));const n=document.createElement("div");n.style.cssText=`${cy} margin-top: 10px;`;const r=document.createElement("span");r.style.cssText="font-size: 13px; color: var(--bim-text-secondary, #475569);",r.textContent=Ee("setting.groundElevation"),n.appendChild(r);const a=document.createElement("div");a.style.cssText="display: flex; align-items: center; gap: 4px;";const o=document.createElement("input");o.type="number",o.value=String(this.settings.display.groundHeight),o.style.cssText=` width: 72px; padding: 4px 8px; border-radius: 4px; border: 1px solid ${Xn}; background: ${dy}; color: ${Oo}; font-size: 13px; outline: none; text-align: right; `,o.addEventListener("input",()=>{const c=Number(o.value);Number.isNaN(c)||this.updateSettings({display:{groundHeight:c}})});const l=document.createElement("span");l.style.cssText="font-size: 13px; color: var(--bim-text-secondary, #475569);",l.textContent=Ee("setting.groundElevationUnit"),a.appendChild(o),a.appendChild(l),n.appendChild(a),e.appendChild(n)}return e}createEnvironmentSection(){const e=document.createElement("div");e.style.cssText=hy;const t=document.createElement("div");t.style.cssText=ly,t.textContent=Ee("setting.environment"),e.appendChild(t);const i=document.createElement("div");i.style.cssText=` display: flex; gap: 0; border-radius: 6px; overflow: hidden; border: 1px solid ${Xn}; margin-bottom: 10px; `;const n=[{key:"none",labelKey:"setting.environmentType.none"},{key:"hdr",labelKey:"setting.environmentType.hdr"},{key:"sky",labelKey:"setting.environmentType.sky"}];for(let r=0;r{this.updateSettings({environment:{type:a.key}},!0)}),i.appendChild(l)}if(e.appendChild(i),this.settings.environment.type==="hdr"){const r=this.presetLists.hdr.map(a=>({value:a.id,label:this.getLocalizedPresetName(a.names,a.id)}));e.appendChild(this.createSelect(r,this.settings.environment.hdrId,a=>{this.updateSettings({environment:{type:"hdr",hdrId:a}})}))}if(this.settings.environment.type==="sky"){const r=this.presetLists.sky.map(a=>({value:a.id,label:this.getLocalizedPresetName(a.names,a.id)}));e.appendChild(this.createSelect(r,this.settings.environment.skyPreset,a=>{this.updateSettings({environment:{type:"sky",skyPreset:a}})}))}return e}createSliderSection(e,t,i,n,r){const a=document.createElement("div");a.style.cssText="margin-bottom: 4px;";const o=document.createElement("div");o.style.cssText=`${cy} margin-bottom: 6px;`;const l=document.createElement("span");l.style.cssText="font-size: 13px; color: var(--bim-text-secondary, #475569);",l.textContent=e,o.appendChild(l);const c=document.createElement("span");c.style.cssText=Qz,c.textContent=String(t),o.appendChild(c),a.appendChild(o);const h=document.createElement("input");return h.type="range",h.min=String(i),h.max=String(n),h.value=String(t),h.className="bim-setting-slider",h.style.cssText=` width: 100%; height: 4px; -webkit-appearance: none; appearance: none; background: var(--bim-border-strong, #cbd5e1); border-radius: 2px; outline: none; cursor: pointer; `,h.addEventListener("input",()=>{const d=Number(h.value);c.textContent=String(d),r(d)}),a.appendChild(h),a}createToggleRow(e,t,i){const n=document.createElement("div");n.style.cssText=cy;const r=document.createElement("span");r.style.cssText="font-size: 13px; color: var(--bim-text-secondary, #475569);",r.textContent=e,n.appendChild(r);const a="var(--bim-border-strong, #cbd5e1)",o=ko;let l=t;const c=document.createElement("div");c.style.cssText=` width: 40px; height: 22px; border-radius: 11px; cursor: pointer; position: relative; transition: background 0.2s; background: ${l?o:a}; `;const h=document.createElement("div");return h.style.cssText=` width: 18px; height: 18px; border-radius: 50%; background: #fff; position: absolute; top: 2px; transition: left 0.2s; box-shadow: 0 1px 3px rgba(0,0,0,0.2); left: ${l?"20px":"2px"}; `,c.appendChild(h),c.addEventListener("click",()=>{l=!l,c.style.background=l?o:a,h.style.left=l?"20px":"2px",i(l)}),n.appendChild(c),n}createSelect(e,t,i){const n=document.createElement("select");n.style.cssText=` width: 100%; padding: 7px 10px; border-radius: 6px; border: 1px solid ${Xn}; background: ${dy}; color: ${Oo}; font-size: 13px; outline: none; cursor: pointer; -webkit-appearance: none; appearance: none; background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 24 24' fill='none' stroke='%2364748b' stroke-width='2'%3E%3Cpolyline points='6 9 12 15 18 9'%3E%3C/polyline%3E%3C/svg%3E"); background-repeat: no-repeat; background-position: right 10px center; padding-right: 28px; `;for(const r of e){const a=document.createElement("option");a.value=r.value,a.textContent=r.label,r.value===t&&(a.selected=!0),n.appendChild(a)}return n.addEventListener("change",()=>i(n.value)),n.addEventListener("focus",()=>{n.style.borderColor=ko}),n.addEventListener("blur",()=>{n.style.borderColor=Xn}),n}async applyPresetById(e){const t=this.presetList.find(i=>i.id===e);t&&(this.selectedPresetId=e,await this.engineComponent?.setSettings(t.settings),this.settings=structuredClone(t.settings),this.isDirty=!1,this.logCurrentSettings("apply-preset"),this.updateUndoRestoreVisibility(),this.emit("setting:preset-changed",{preset:structuredClone(t),timestamp:Date.now()}),this.reopenAtSamePosition())}async updateSettings(e,t=!1){const i=this.mergeSettings(this.settings,e);try{await this.engineComponent?.setSettings(e)}catch(n){console.warn("[SettingDialogManager] Failed to apply settings patch, keep local state in sync.",n)}this.settings=i,this.isDirty=this.getCurrentSettingsDirtyState(i),this.logCurrentSettings("update-settings"),this.updateUndoRestoreVisibility(),t&&this.reopenAtSamePosition()}logCurrentSettings(e){console.log("[SettingDialogManager] current settings",{source:e,settings:structuredClone(this.settings)})}mergeSettings(e,t){return{render:{...e.render,...t.render},display:{...e.display,...t.display},environment:{...e.environment,...t.environment,skyParams:{...e.environment.skyParams,...t.environment?.skyParams}}}}getCurrentSettingsDirtyState(e){const t=this.presetList.find(i=>i.id===this.selectedPresetId);return t?JSON.stringify(t.settings)!==JSON.stringify(e):!1}getLocalizedPresetName(e,t){if(!Array.isArray(e)||e.length===0)return t;const i=$t.getLocale();return i==="zh-CN"?e[0]||e[1]||e[2]||t:i==="zh-TW"?e[1]||e[0]||e[2]||t:e[2]||e[0]||e[1]||t}updateUndoRestoreVisibility(){const e=document.getElementById(this.dialogId);if(!e)return;const t=e.querySelector(`#${this.dialogId}-undo-btn`);t instanceof HTMLElement&&(t.style.display=this.isDirty&&this.selectedPresetId?"block":"none")}handleSaveCurrentPreset(){if(!this.selectedPresetId){window.alert(Ee("setting.selectPresetFirst"));return}const e=this.presetList.findIndex(n=>n.id===this.selectedPresetId);if(e<0){window.alert(Ee("setting.selectPresetFirst"));return}const t=this.engineComponent?.getSettings()??structuredClone(this.settings),i={...this.presetList[e],settings:structuredClone(t)};this.presetList=this.presetList.map((n,r)=>r===e?i:n),this.ensurePresetListWithInternalDefault(),this.settings=structuredClone(t),this.isDirty=!1,this.updateUndoRestoreVisibility(),this.emit("setting:preset-saved",{preset:structuredClone(i),currentSettings:structuredClone(t),timestamp:Date.now()}),this.reopenAtSamePosition()}saveAsPresetWithName(e){const t=e.trim();if(!t)return window.alert(Ee("setting.presetNameRequired")),!1;if(this.presetList.some(o=>o.presetName.toLowerCase()===t.toLowerCase()))return window.alert(Ee("setting.presetNameDuplicate")),!1;const n=this.engineComponent?.getSettings()??structuredClone(this.settings),r={id:`user-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,presetName:t,isDefault:!1,settings:structuredClone(n),source:"user",readonly:!1},a=this.presetList.filter(o=>o.id!==Rr.INTERNAL_DEFAULT_PRESET_ID);return this.presetList=[...a,r],this.ensurePresetListWithInternalDefault(),this.selectedPresetId=r.id,this.settings=structuredClone(n),this.isDirty=!1,this.updateUndoRestoreVisibility(),this.emit("setting:preset-saved",{preset:structuredClone(r),currentSettings:structuredClone(n),timestamp:Date.now()}),this.reopenAtSamePosition(),!0}openDeletePresetConfirmModal(){if(!this.isSelectedPresetDeletable())return;this.closeDeletePresetConfirmModal();const e=document.getElementById(this.dialogId);if(!e)return;const t=document.createElement("div");t.style.cssText=` position: absolute; inset: 0; background: rgba(15, 23, 42, 0.35); display: flex; align-items: center; justify-content: center; z-index: 21; `;const i=document.createElement("div");i.style.cssText=` width: min(320px, calc(100% - 24px)); border-radius: 8px; background: var(--bim-bg-elevated, #fff); border: 1px solid ${Xn}; padding: 12px; display: flex; flex-direction: column; gap: 10px; `;const n=document.createElement("div");n.textContent=Ee("setting.deleteDialogTitle"),n.style.cssText="font-size: 14px; font-weight: 600; color: var(--bim-text-primary, #0f172a);";const r=document.createElement("div");r.textContent=Ee("setting.deleteDialogMessage"),r.style.cssText="font-size: 13px; color: var(--bim-text-secondary, #475569);";const a=document.createElement("div");a.style.cssText="display: flex; justify-content: flex-end; gap: 8px;";const o=document.createElement("button");o.type="button",o.textContent=Ee("setting.cancel"),o.style.cssText=` height: 32px; padding: 0 12px; border-radius: 6px; border: 1px solid ${Xn}; background: var(--bim-bg-elevated, #fff); color: ${Oo}; cursor: pointer; `,o.addEventListener("click",()=>this.closeDeletePresetConfirmModal());const l=document.createElement("button");l.type="button",l.textContent=Ee("setting.confirm"),l.style.cssText=` height: 32px; padding: 0 12px; border-radius: 6px; border: none; background: #ef4444; color: ${uc}; cursor: pointer; `,l.addEventListener("click",()=>{this.deleteSelectedPreset(),this.closeDeletePresetConfirmModal()}),a.appendChild(o),a.appendChild(l),i.appendChild(n),i.appendChild(r),i.appendChild(a),t.appendChild(i),e.appendChild(t),this.deleteConfirmModalEl=t}closeDeletePresetConfirmModal(){this.deleteConfirmModalEl&&(this.deleteConfirmModalEl.remove(),this.deleteConfirmModalEl=null)}deleteSelectedPreset(){if(!this.isSelectedPresetDeletable()||!this.selectedPresetId)return;const e=this.presetList.find(t=>t.id===this.selectedPresetId);e&&(this.presetList=this.presetList.filter(t=>t.id!==this.selectedPresetId),this.ensurePresetListWithInternalDefault(),this.selectedPresetId=this.resolveDefaultPresetId(this.presetList)??this.presetList[0]?.id??null,this.applySelectedPresetFromList(),this.emit("setting:preset-deleted",structuredClone(e)),this.reopenAtSamePosition())}openSaveAsPresetModal(e){this.closeSaveAsPresetModal();const t=document.getElementById(this.dialogId);if(!t)return;const i=document.createElement("div");i.style.cssText=` position: absolute; inset: 0; background: rgba(15, 23, 42, 0.35); display: flex; align-items: center; justify-content: center; z-index: 20; `;const n=document.createElement("div");n.style.cssText=` width: min(320px, calc(100% - 24px)); border-radius: 8px; background: var(--bim-bg-elevated, #fff); border: 1px solid ${Xn}; padding: 12px; display: flex; flex-direction: column; gap: 10px; `;const r=document.createElement("div");r.textContent=Ee("setting.saveAsDialogTitle"),r.style.cssText="font-size: 14px; font-weight: 600; color: var(--bim-text-primary, #0f172a);";const a=document.createElement("input");a.type="text",a.value=e??`${Ee("setting.presetDefaultName")} ${this.presetList.length+1}`,a.placeholder=Ee("setting.presetNamePlaceholder"),a.style.cssText=` width: 100%; height: 34px; padding: 0 10px; border-radius: 6px; border: 1px solid ${Xn}; background: ${dy}; color: ${Oo}; outline: none; `;const o=document.createElement("div");o.style.cssText="display: flex; justify-content: flex-end; gap: 8px;";const l=document.createElement("button");l.type="button",l.textContent=Ee("setting.cancel"),l.style.cssText=` height: 32px; padding: 0 12px; border-radius: 6px; border: 1px solid ${Xn}; background: var(--bim-bg-elevated, #fff); color: ${Oo}; cursor: pointer; `,l.addEventListener("click",()=>this.closeSaveAsPresetModal());const c=document.createElement("button");c.type="button",c.textContent=Ee("setting.confirm"),c.style.cssText=` height: 32px; padding: 0 12px; border-radius: 6px; border: none; background: ${ko}; color: ${uc}; cursor: pointer; `,c.addEventListener("click",()=>{this.saveAsPresetWithName(a.value)&&this.closeSaveAsPresetModal()}),a.addEventListener("keydown",h=>{h.key==="Enter"&&this.saveAsPresetWithName(a.value)&&this.closeSaveAsPresetModal(),h.key==="Escape"&&this.closeSaveAsPresetModal()}),o.appendChild(l),o.appendChild(c),n.appendChild(r),n.appendChild(a),n.appendChild(o),i.appendChild(n),t.appendChild(i),this.saveAsModalEl=i,window.requestAnimationFrame(()=>a.focus())}closeSaveAsPresetModal(){this.saveAsModalEl&&(this.saveAsModalEl.remove(),this.saveAsModalEl=null)}reopenAtSamePosition(){if(!this.isOpen())return;const e=document.getElementById(this.dialogId),t=this.getScrollableContentElement();if(e&&(this.savedPosition={x:e.offsetLeft,y:e.offsetTop}),t&&(this.savedScrollTop=t.scrollTop),this.hide(),this.show(),this.savedScrollTop!==null){const i=this.savedScrollTop;this.savedScrollTop=null,window.requestAnimationFrame(()=>{const n=this.getScrollableContentElement();n&&(n.scrollTop=i)})}}getScrollableContentElement(){const e=document.getElementById(this.dialogId);if(!e)return null;const t=e.querySelector(".setting-scroll-body");return t instanceof HTMLElement?t:null}ensureSliderStyle(){if(document.querySelector("#bim-setting-slider-style"))return;const e=document.createElement("style");e.id="bim-setting-slider-style",e.textContent=` .bim-setting-slider::-webkit-slider-thumb { -webkit-appearance: none; appearance: none; width: 16px; height: 16px; border-radius: 50%; background: var(--bim-primary, #3b82f6); cursor: pointer; border: 2px solid var(--bim-bg-elevated, #fff); box-shadow: 0 1px 3px rgba(0,0,0,0.2); } .bim-setting-slider::-moz-range-thumb { width: 16px; height: 16px; border-radius: 50%; background: var(--bim-primary, #3b82f6); cursor: pointer; border: 2px solid var(--bim-bg-elevated, #fff); box-shadow: 0 1px 3px rgba(0,0,0,0.2); } .bim-setting-slider::-moz-range-track { background: var(--bim-border-strong, #cbd5e1); height: 4px; border-radius: 2px; border: none; } `,document.head.appendChild(e)}}class i9{element;headerEl;contentEl;contentBoxEl;arrowEl;titleEl;config;parent;constructor(e,t){this.config=e,this.parent=t,this.element=this.createDom()}createDom(){const e=document.createElement("div");if(e.className=`bim-collapse-item ${this.config.className||""}`,this.config.disabled&&e.classList.add("is-disabled"),e.dataset.id=this.config.id,this.headerEl=document.createElement("div"),this.headerEl.className="bim-collapse-header",this.arrowEl=document.createElement("span"),this.arrowEl.className="bim-collapse-arrow",this.arrowEl.innerHTML='',this.headerEl.appendChild(this.arrowEl),this.config.icon){const t=document.createElement("span");t.className="bim-collapse-icon",t.innerHTML=this.config.icon,this.headerEl.appendChild(t)}if(this.titleEl=document.createElement("span"),this.titleEl.className="bim-collapse-title",this.titleEl.textContent=Ee(this.config.title),this.headerEl.appendChild(this.titleEl),this.config.extra){const t=document.createElement("div");t.className="bim-collapse-extra",typeof this.config.extra=="string"?t.innerHTML=this.config.extra:t.appendChild(this.config.extra),this.headerEl.appendChild(t)}return this.headerEl.addEventListener("click",()=>{this.config.disabled||this.parent.toggleItem(this.config.id)}),e.appendChild(this.headerEl),this.contentEl=document.createElement("div"),this.contentEl.className="bim-collapse-content is-hidden",this.contentBoxEl=document.createElement("div"),this.contentBoxEl.className="bim-collapse-content-box",typeof this.config.content=="string"?this.contentBoxEl.innerHTML=this.config.content:this.contentBoxEl.appendChild(this.config.content),this.contentEl.appendChild(this.contentBoxEl),e.appendChild(this.contentEl),e}updateLocale(){this.titleEl&&(this.titleEl.textContent=Ee(this.config.title))}setActive(e){e?(this.element.classList.add("is-active"),this.contentEl.classList.remove("is-hidden")):(this.element.classList.remove("is-active"),this.contentEl.classList.add("is-hidden"))}}class n9{element;options;items=new Map;activeIds=new Set;unsubscribeLocale=null;unsubscribeTheme=null;constructor(e){this.options={bordered:!0,accordion:!1,...e},this.element=document.createElement("div"),this.element.className=`bim-collapse ${this.options.className||""}`,this.options.bordered||(this.element.style.border="none"),this.options.ghost&&this.element.classList.add("is-ghost");const t=typeof this.options.container=="string"?document.getElementById(this.options.container):this.options.container;t&&t.appendChild(this.element),this.options.activeIds&&this.options.activeIds.forEach(i=>this.activeIds.add(i)),this.init()}init(){this.options.items.forEach(e=>{const t=new i9(e,this);this.items.set(e.id,t),this.element.appendChild(t.element),this.activeIds.has(e.id)&&t.setActive(!0)}),this.unsubscribeLocale=$t.subscribe(()=>{this.setLocales()}),this.unsubscribeTheme=ct.subscribe(e=>{this.setTheme(e)}),this.setTheme(ct.getTheme())}toggleItem(e){const t=this.activeIds.has(e);this.options.accordion?(this.activeIds.clear(),t||this.activeIds.add(e)):t?this.activeIds.delete(e):this.activeIds.add(e),this.refreshState(),this.options.onChange&&this.options.onChange(Array.from(this.activeIds))}refreshState(){this.items.forEach((e,t)=>{e.setActive(this.activeIds.has(t))})}setTheme(e){const t=this.element.style;t.setProperty("--bim-bg-elevated",e.bgElevated),t.setProperty("--bim-border-default",e.borderDefault),t.setProperty("--bim-border-subtle",e.borderSubtle),t.setProperty("--bim-border-strong",e.borderStrong),t.setProperty("--bim-text-primary",e.textPrimary),t.setProperty("--bim-text-disabled",e.textDisabled),t.setProperty("--bim-component-bg",e.componentBg),t.setProperty("--bim-component-bg-hover",e.componentBgHover),t.setProperty("--bim-component-bg-active",e.componentBgActive)}setLocales(){this.items.forEach(e=>e.updateLocale())}destroy(){this.unsubscribeLocale&&(this.unsubscribeLocale(),this.unsubscribeLocale=null),this.unsubscribeTheme&&(this.unsubscribeTheme(),this.unsubscribeTheme=null),this.element.remove(),this.items.clear()}}class H2 extends jn{dialogId="component-detail-dialog";dialog=null;currentSelection=null;unsubscribeSelected=null;unsubscribeDeselected=null;propertiesData=null;constructor(e){super(e)}init(){this.unsubscribeSelected=this.registry.on("component:selected",e=>{this.currentSelection=e,this.isOpen()&&this.loadAndRenderContent()}),this.unsubscribeDeselected=this.registry.on("component:deselected",()=>{this.currentSelection=null,this.isOpen()&&this.renderNoSelection()})}show(){if(!this.registry.dialog){console.warn("[ComponentDetailManager] Dialog manager not initialized");return}this.isOpen()||this.createDialog(),this.currentSelection?this.loadAndRenderContent():this.renderNoSelection()}createDialog(){const t=document.body.clientWidth-300-40;this.dialog=this.registry.dialog?.create({id:this.dialogId,title:"panel.componentDetail.title",content:"",width:"300px",height:"500px",position:{x:t,y:20},resizable:!0,onClose:()=>this.hide()})}loadAndRenderContent(){!this.dialog||!this.currentSelection||(this.showLoading(),this.engineComponent?.getComponentProperties(this.currentSelection.url,this.currentSelection.id,e=>{this.propertiesData=e,this.renderTabbedContent()}))}showLoading(){const e=document.createElement("div");e.style.cssText="height:100%;display:flex;align-items:center;justify-content:center;",e.textContent="加载中...",this.dialog?.setContent(e)}renderNoSelection(){if(!this.dialog)return;const e=document.createElement("div");e.style.cssText="height:100%;display:flex;align-items:center;justify-content:center;color:var(--bim-text-secondary,#999);",e.textContent=Ee("panel.componentDetail.noSelection")||"请先选中构件",this.dialog.setContent(e)}renderTabbedContent(){if(!this.dialog)return;const e=document.createElement("div");e.style.cssText="height:100%;display:flex;flex-direction:column;";const t=this.createPropertiesPanel();e.appendChild(t),this.dialog.setContent(e)}createPropertiesPanel(){const e=document.createElement("div");e.style.cssText="height:100%;overflow-y:auto;";const i=[...this.propertiesData?.properties||[]].reverse();if(i.length===0)return e.innerHTML='
    无属性数据
    ',e;const n=i.map((a,o)=>({id:`category-${o}`,title:a.name||`分类 ${o+1}`,content:this.createCategoryContent(a.children||[])}));new n9({container:e,accordion:!1,ghost:!0,activeIds:n.length>0?[n[0].id]:[],items:n});const r=document.createElement("style");return r.textContent=` #${this.dialogId} .bim-collapse-header { background-color: var(--bim-component-bg-hover) !important; } #${this.dialogId} .bim-collapse-header:hover { background-color: var(--bim-component-bg-active) !important; } `,e.appendChild(r),e}createCategoryContent(e){const t=document.createElement("div");return e.forEach((i,n)=>{const r=document.createElement("div");r.style.cssText=` display: flex; border-bottom: 1px solid var(--bim-border-default, rgba(255,255,255,0.15)); `,n===e.length-1&&(r.style.borderBottom="none");const a=document.createElement("div");a.style.cssText=` width: 120px; flex-shrink: 0; color: var(--bim-text-secondary, #999); font-size: 13px; padding: 8px 12px; border-right: 1px solid var(--bim-border-default, rgba(255,255,255,0.15)); `,a.textContent=i.name||"-";const o=document.createElement("div");o.style.cssText=` flex: 1; color: var(--bim-text-primary, #fff); font-size: 13px; padding: 8px 12px; word-break: break-all; `,o.textContent=String(i.value??"-"),r.appendChild(a),r.appendChild(o),t.appendChild(r)}),t}isOpen(){return this.dialog!==null}hide(){this.dialog&&(this.dialog.destroy(),this.dialog=null)}destroy(){this.unsubscribeSelected&&(this.unsubscribeSelected(),this.unsubscribeSelected=null),this.unsubscribeDeselected&&(this.unsubscribeDeselected(),this.unsubscribeDeselected=null),this.hide(),super.destroy()}}class s9{element;options;container;messagesContainer=null;textarea=null;messages=[];_isDestroyed=!1;_isVisible=!1;unsubscribeTheme=null;unsubscribeLocale=null;rafId=null;constructor(e){this.options={width:440,title:"aiChat.title",placeholder:"aiChat.placeholder",quickPrompts:[{id:"summarize",label:"aiChat.quickPrompt.summarize"},{id:"explain",label:"aiChat.quickPrompt.explain"},{id:"generate",label:"aiChat.quickPrompt.generate"}],...e},this.container=e.container,this.element=this.createDom(),this.init()}init(){this.container.appendChild(this.element),this.hide(),this.unsubscribeTheme=ct.subscribe(e=>{this.setTheme(e)}),this.unsubscribeLocale=$t.subscribe(()=>{this.setLocales()}),this.setTheme(ct.getTheme()),this.setLocales()}setTheme(e){const t=e.name==="dark"||e.name?.includes("dark");this.element.classList.toggle("light",!t);const i=this.element.style;i.setProperty("--bim-ai-accent",e.primary),i.setProperty("--bim-ai-text",e.textPrimary),i.setProperty("--bim-ai-muted",e.textTertiary),i.setProperty("--bim-ai-border",e.borderDefault),i.setProperty("--bim-ai-shadow",e.shadowLg)}setLocales(){const e=this.element.querySelector(".bim-ai-chat-title");e&&this.options.title&&(e.textContent=Ee(this.options.title));const t=this.element.querySelector(".bim-ai-textarea");t&&this.options.placeholder&&(t.placeholder=Ee(this.options.placeholder));const i=this.element.querySelector(".bim-ai-helper-left");i&&(i.textContent=Ee("aiChat.helper.newline"));const n=this.element.querySelector(".bim-ai-helper-right");n&&(n.textContent=Ee("aiChat.helper.send")),this.updateQuickPrompts(),this.renderMessages()}show(){this._isVisible=!0,this.element.style.display="flex",this.initPosition(),this.scrollToBottom()}initPosition(){if(this.element.style.left)return;const e=this.container.clientWidth,t=this.element.offsetWidth,i=Math.max(50,e-t-50);this.element.style.left=`${i}px`,this.element.style.top="50px"}hide(){this._isVisible=!1,this.element.style.display="none"}toggle(){this._isVisible?this.hide():this.show()}isVisible(){return this._isVisible}addMessage(e){this.messages.push(e),this.renderMessages(),this.scrollToBottom()}updateMessage(e,t){const i=this.messages.findIndex(n=>n.id===e);i!==-1&&(this.messages[i]={...this.messages[i],...t},this.renderMessages())}removeMessage(e){this.messages=this.messages.filter(t=>t.id!==e),this.renderMessages()}clearMessages(){this.messages=[],this.renderMessages()}addUserMessage(e){const t=`user-${Date.now()}`;return this.addMessage({id:t,type:"user",content:e,timestamp:Date.now()}),t}addAiMessage(e){const t=`ai-${Date.now()}`;return this.addMessage({id:t,type:"ai",content:e,timestamp:Date.now()}),t}addStepMessage(e,t){const i=`step-${Date.now()}`;return this.addMessage({id:i,type:"step",status:e,content:t,timestamp:Date.now()}),i}addThinkingMessage(){const e=`thinking-${Date.now()}`;return this.addMessage({id:e,type:"thinking",timestamp:Date.now()}),e}addQuestionMessage(e,t,i){const n=`question-${Date.now()}`;return this.addMessage({id:n,type:"question",title:e,question:t,options:i,answered:!1,timestamp:Date.now()}),n}createDom(){const e=document.createElement("div");return e.className="bim-ai-chat",e.style.width=`${this.options.width}px`,e.innerHTML=`
    `,this.messagesContainer=e.querySelector(".bim-ai-chat-messages"),this.textarea=e.querySelector(".bim-ai-textarea"),this.bindEvents(e),this.updateQuickPrompts(e),e}bindEvents(e){e.querySelectorAll(".bim-ai-chat-action-btn").forEach(a=>{a.addEventListener("click",o=>{switch(o.currentTarget.dataset.action){case"new":this.options.onNewChat?.();break;case"history":this.options.onHistory?.();break;case"settings":this.options.onSettings?.();break;case"close":this.hide(),this.options.onClose?.();break}})});const t=e.querySelector(".bim-ai-chat-header");t&&this.initDrag(t),e.querySelector(".bim-ai-send-btn")?.addEventListener("click",()=>this.handleSend()),this.textarea?.addEventListener("keydown",a=>{a.key==="Enter"&&!a.shiftKey&&(a.preventDefault(),this.handleSend())}),this.textarea?.addEventListener("input",()=>{this.textarea&&(this.textarea.style.height="auto",this.textarea.style.height=Math.min(this.textarea.scrollHeight,100)+"px")});const n=a=>a.stopPropagation();["click","dblclick","mousedown","mouseup","mousemove","wheel","touchstart","touchend","touchmove"].forEach(a=>{e.addEventListener(a,n,{passive:!1})})}handleSend(){if(!this.textarea)return;const e=this.textarea.value.trim();e&&(this.textarea.value="",this.textarea.style.height="auto",this.options.onSend?.(e))}initDrag(e){let t=0,i=0,n=0,r=0,a=0,o=0,l=0,c=0;const h=u=>{u.target.closest(".bim-ai-chat-action-btn")||(u.preventDefault(),u.stopPropagation(),t=u.clientX,i=u.clientY,n=this.element.offsetLeft,r=this.element.offsetTop,a=this.container.clientWidth,o=this.container.clientHeight,l=this.element.offsetWidth,c=this.element.offsetHeight,document.addEventListener("mousemove",d,{capture:!0}),document.addEventListener("mouseup",p,{capture:!0}))},d=u=>{u.preventDefault(),u.stopPropagation(),!this.rafId&&(this.rafId=requestAnimationFrame(()=>{const v=u.clientX-t,g=u.clientY-i;let m=n+v,f=r+g;const y=a-l,x=o-c;m=Math.max(0,Math.min(m,y)),f=Math.max(0,Math.min(f,x)),this.element.style.left=`${m}px`,this.element.style.top=`${f}px`,this.rafId=null}))},p=()=>{this.rafId&&(cancelAnimationFrame(this.rafId),this.rafId=null),document.removeEventListener("mousemove",d,{capture:!0}),document.removeEventListener("mouseup",p,{capture:!0})};e.addEventListener("mousedown",h)}updateQuickPrompts(e){const i=(e||this.element).querySelector(".bim-ai-quick-prompts");!i||!this.options.quickPrompts||(i.innerHTML=this.options.quickPrompts.map(n=>` `).join(""),i.querySelectorAll(".bim-ai-quick-prompt").forEach(n=>{n.addEventListener("click",r=>{const a=r.currentTarget.dataset.promptId,o=this.options.quickPrompts?.find(l=>l.id===a);o&&this.textarea&&(this.textarea.value=Ee(o.label),this.textarea.focus())})}))}renderMessages(){this.messagesContainer&&(this.messagesContainer.innerHTML=this.messages.map(e=>{switch(e.type){case"user":return this.renderUserMessage(e.content);case"ai":return this.renderAiMessage(e.content);case"step":return this.renderStepMessage(e.status,e.content);case"thinking":return this.renderThinkingMessage();case"question":return e.answered?this.renderAnsweredQuestion(e):this.renderActiveQuestion(e);default:return""}}).join(""),this.bindQuestionEvents())}renderUserMessage(e){return`
    ${this.escapeHtml(e)}
    `}renderAiMessage(e){return`
    ${this.escapeHtml(e)}
    `}renderStepMessage(e,t){return`
    ${ut({running:"loader",done:"check",error:"error"}[e])} ${this.escapeHtml(t)}
    `}renderThinkingMessage(){return`
    ${ut("loader")} ${Ee("aiChat.thinking")}
    `}renderActiveQuestion(e){const t=e.options.map(i=>`
    ${i.isOther?Ee("aiChat.other"):this.escapeHtml(i.label)}
    ${i.isOther&&e.selectedOptionId===i.id?` `:""} `).join("");return`
    ${ut("bot")}
    ${this.escapeHtml(e.title)}
    ${this.escapeHtml(e.question)}
    ${t}
    `}renderAnsweredQuestion(e){const t=e.options.find(n=>n.id===e.selectedOptionId),i=t?.isOther?e.customAnswer:t?.label;return`
    Q
    ${this.escapeHtml(e.question)}
    A
    ${this.escapeHtml(i||"")}
    `}bindQuestionEvents(){this.messagesContainer?.querySelectorAll(".bim-ai-option").forEach(e=>{e.addEventListener("click",t=>{const i=t.currentTarget,n=i.dataset.questionId,r=i.dataset.optionId;if(n&&r){const a=this.messages.find(o=>o.id===n);a&&!a.answered&&(a.selectedOptionId=r,this.renderMessages())}})}),this.messagesContainer?.querySelectorAll(".bim-ai-option-input").forEach(e=>{e.addEventListener("input",t=>{const i=t.target,n=i.dataset.questionId;if(n){const r=this.messages.find(a=>a.id===n);r&&(r.customAnswer=i.value)}})}),this.messagesContainer?.querySelectorAll(".bim-ai-question-submit").forEach(e=>{e.addEventListener("click",t=>{const n=t.currentTarget.dataset.questionId;if(n){const r=this.messages.find(a=>a.id===n);r&&r.selectedOptionId&&(r.answered=!0,this.renderMessages(),this.options.onQuestionSubmit?.(n,r.selectedOptionId,r.customAnswer))}})})}scrollToBottom(){this.messagesContainer&&(this.messagesContainer.scrollTop=this.messagesContainer.scrollHeight)}escapeHtml(e){const t=document.createElement("div");return t.textContent=e,t.innerHTML}destroy(){this._isDestroyed||(this.unsubscribeTheme&&(this.unsubscribeTheme(),this.unsubscribeTheme=null),this.unsubscribeLocale&&(this.unsubscribeLocale(),this.unsubscribeLocale=null),this.element.remove(),this._isDestroyed=!0)}}class V2{aiChat=null;registry;initialized=!1;constructor(e){this.registry=e}init(){if(this.initialized)return;const e=this.registry.wrapper;if(!e){console.warn("[AiChatManager] wrapper 不存在,无法初始化");return}this.aiChat=new s9({container:e,width:440,title:"aiChat.title",placeholder:"aiChat.placeholder",quickPrompts:[{id:"summarize",label:"aiChat.quickPrompt.summarize"},{id:"explain",label:"aiChat.quickPrompt.explain"},{id:"generate",label:"aiChat.quickPrompt.generate"}],onSend:t=>{console.log("[AiChatManager] 用户发送消息:",t),this.aiChat?.addUserMessage(t),this.registry.emit("aiChat:message-sent",{message:t})},onQuestionSubmit:(t,i,n)=>{console.log("[AiChatManager] 用户回答问题:",{questionId:t,optionId:i,customAnswer:n}),this.registry.emit("aiChat:question-answered",{questionId:t,optionId:i,customAnswer:n})},onNewChat:()=>{console.log("[AiChatManager] 新建对话"),this.registry.emit("aiChat:new-chat",{})},onHistory:()=>{console.log("[AiChatManager] 打开历史"),this.registry.emit("aiChat:history-opened",{})},onSettings:()=>{console.log("[AiChatManager] 打开设置"),this.registry.emit("aiChat:settings-opened",{})},onClose:()=>{console.log("[AiChatManager] 关闭 AI 聊天"),this.registry.emit("aiChat:closed",{}),this.registry.toolbar?.setBtnActive("aiChat",!1)}}),this.initialized=!0}show(){this.aiChat||this.init(),this.aiChat?.show(),this.registry.emit("aiChat:opened",{}),this.registry.toolbar?.setBtnActive("aiChat",!0)}hide(){this.aiChat?.hide(),this.registry.emit("aiChat:closed",{}),this.registry.toolbar?.setBtnActive("aiChat",!1)}toggle(){this.aiChat?.isVisible()?this.hide():this.show()}isVisible(){return this.aiChat?.isVisible()??!1}addUserMessage(e){return this.aiChat?.addUserMessage(e)??""}addAiMessage(e){return this.aiChat?.addAiMessage(e)??""}addStepMessage(e,t){return this.aiChat?.addStepMessage(e,t)??""}addThinkingMessage(){return this.aiChat?.addThinkingMessage()??""}addQuestionMessage(e,t,i){return this.aiChat?.addQuestionMessage(e,t,i)??""}updateMessage(e,t){this.aiChat?.updateMessage(e,t)}removeMessage(e){this.aiChat?.removeMessage(e)}clearMessages(){this.aiChat?.clearMessages()}destroy(){this.aiChat&&(this.aiChat.destroy(),this.aiChat=null),this.initialized=!1}}class r9{events=new Map;on(e,t){return this.events.has(e)||this.events.set(e,[]),this.events.get(e).push(t),()=>this.off(e,t)}off(e,t){const i=this.events.get(e);if(!i)return;const n=i.indexOf(t);n!==-1&&i.splice(n,1)}emit(e,t){const i=this.events.get(e);i&&i.forEach(n=>{try{n(t)}catch(r){console.error(`[EventEmitter] Error in listener for event "${e}":`,r)}})}clear(){this.events.clear()}}class Sm{eventEmitter=new r9;container=null;wrapper=null;toolbar=null;dialog=null;engine3d=null;buttonGroup=null;rightKey=null;constructTree=null;measure=null;walkControl=null;sectionPlane=null;sectionAxis=null;sectionBox=null;walkPath=null;walkPlanView=null;engineInfo=null;componentDetail=null;aiChat=null;setting=null;radialToolbar=null;bottomDock=null;measureDock=null;constructor(){}reset(){this.eventEmitter.clear(),this.container=null,this.wrapper=null,this.toolbar=null,this.dialog=null,this.engine3d=null,this.buttonGroup=null,this.rightKey=null,this.constructTree=null,this.measure=null,this.walkControl=null,this.sectionPlane=null,this.sectionAxis=null,this.sectionBox=null,this.walkPath=null,this.walkPlanView=null,this.engineInfo=null,this.componentDetail=null,this.aiChat=null,this.setting=null,this.radialToolbar=null,this.bottomDock=null,this.measureDock=null}emit(e,t){this.eventEmitter.emit(e,t)}on(e,t){return this.eventEmitter.on(e,t)}off(e,t){this.eventEmitter.off(e,t)}clearEvents(){this.eventEmitter.clear()}}class a9{container;wrapper=null;sizeEl=null;resizeObserver=null;lastSyncedWidth=-1;lastSyncedHeight=-1;registry;toolbar=null;constructTreeBtn=null;buttonGroup=null;dialog=null;engine=null;rightKey=null;measure=null;sectionPlane=null;sectionAxis=null;sectionBox=null;walkControl=null;engineInfo=null;componentDetail=null;aiChat=null;setting=null;handleWindowResize=()=>{this.updateClientSizeDisplay()};constructor(e,t){const i=typeof e=="string"?document.getElementById(e):e;if(!i)throw new Error("Container not found");this.container=i,this.registry=new Sm,t?.locale&&$t.setLocale(t.locale),t?.theme&&(t.theme==="custom"?console.warn("Custom theme should be set via setCustomTheme()."):ct.setTheme(t.theme)),this.init()}emit(e,t){this.registry.emit(e,t)}on(e,t){return this.registry.on(e,t)}setLocale(e){$t.setLocale(e)}getLocale(){return $t.getLocale()}setTheme(e){ct.setTheme(e)}setCustomTheme(e){ct.setCustomTheme(e)}init(){this.container.innerHTML="",this.wrapper=document.createElement("div"),this.wrapper.className="bim-engine-wrapper",this.container.appendChild(this.wrapper);const e=document.createElement("div");e.className="bim-engine-version",e.textContent="v2.4.8",this.wrapper.appendChild(e),this.sizeEl=document.createElement("div"),this.sizeEl.className="bim-engine-size",this.wrapper.appendChild(this.sizeEl),this.updateClientSizeDisplay(),this.bindSizeObserver(),this.registry.container=this.container,this.registry.wrapper=this.wrapper,this.engine=new T2(this.wrapper,this.registry),this.dialog=new vy(this.wrapper,this.registry),this.toolbar=new eE(this.wrapper,this.registry),this.buttonGroup=new tE(this.wrapper,this.registry),this.rightKey=new oy(this.wrapper,this.registry),this.constructTreeBtn=new Xz(this.wrapper,this.registry),this.measure=new D2(this.registry),this.sectionPlane=new N2(this.registry),this.sectionAxis=new k2(this.registry),this.sectionBox=new U2(this.registry),this.walkControl=new B2(this.registry),this.walkControl.init(),this.engineInfo=new F2(this.registry),this.engineInfo.init(),this.registry.engine3d=this.engine,this.registry.dialog=this.dialog,this.registry.toolbar=this.toolbar,this.registry.buttonGroup=this.buttonGroup,this.registry.rightKey=this.rightKey,this.registry.constructTree=this.constructTreeBtn,this.registry.measure=this.measure,this.registry.sectionPlane=this.sectionPlane,this.registry.sectionAxis=this.sectionAxis,this.registry.sectionBox=this.sectionBox,this.registry.walkControl=this.walkControl,this.registry.engineInfo=this.engineInfo,this.componentDetail=new H2(this.registry),this.registry.componentDetail=this.componentDetail,this.componentDetail.init(),this.aiChat=new V2(this.registry),this.registry.aiChat=this.aiChat,this.aiChat.init(),this.setting=new Rr(this.registry),this.registry.setting=this.setting,this.setting.init(),this.updateTheme(ct.getTheme()),ct.subscribe(t=>{this.updateTheme(t)})}updateTheme(e){this.wrapper&&(this.wrapper.style.color=e.textPrimary)}updateClientSizeDisplay(){const e=this.container.clientWidth,t=this.container.clientHeight;this.sizeEl&&(this.sizeEl.textContent=`${e}px x ${t}px`),this.syncEngineSize(e,t)}syncEngineSize(e,t){e<=0||t<=0||e===this.lastSyncedWidth&&t===this.lastSyncedHeight||(this.lastSyncedWidth=e,this.lastSyncedHeight=t,this.engine?.getEngineComponent()?.resize(e,t))}bindSizeObserver(){if(typeof ResizeObserver<"u"){this.resizeObserver=new ResizeObserver(()=>{this.updateClientSizeDisplay()}),this.resizeObserver.observe(this.container);return}window.addEventListener("resize",this.handleWindowResize)}unbindSizeObserver(){if(this.resizeObserver){this.resizeObserver.disconnect(),this.resizeObserver=null;return}window.removeEventListener("resize",this.handleWindowResize)}destroy(){this.unbindSizeObserver(),this.toolbar?.destroy(),this.buttonGroup?.destroy(),this.engine?.destroy(),this.dialog?.destroy(),this.rightKey?.destroy(),this.measure?.destroy(),this.sectionPlane?.destroy(),this.sectionAxis?.destroy(),this.sectionBox?.destroy(),this.walkControl?.destroy(),this.aiChat?.destroy(),this.setting?.destroy(),this.sizeEl=null,this.lastSyncedWidth=-1,this.lastSyncedHeight=-1,this.container.innerHTML="",this.registry.reset()}}class o9{container;wrapper;mainButton;items=[];itemElements=[];itemButtonMap=new Map;toggleStateMap=new Map;isActive=!1;timer=null;unsubscribeTheme=null;unsubscribeLocale=null;mainButtonLabel;onMainButtonClick;pointerX=Number.NaN;pointerY=Number.NaN;maxInteractiveRadius=220;closeDelay;itemsPerRing;MAIN_BUTTON_SIZE=60;SUB_BUTTON_SIZE=46;BASE_RADIUS=80;RING_GAP=40;FAN_START_DEG=170;FAN_END_DEG=280;CANVAS_PADDING=28;constructor(e){this.container=e.container,this.items=e.items===void 0?this.createDefaultItems():[...e.items],this.mainButtonLabel=e.mainButtonLabel??"toolbar.home",this.onMainButtonClick=e.onMainButtonClick,this.itemsPerRing=Math.max(3,e.itemsPerRing??5),this.closeDelay=Math.max(100,e.closeDelay??260),this.wrapper=this.createWrapper(),this.mainButton=this.createMainButton(e.mainButtonIcon),this.wrapper.appendChild(this.mainButton),this.container.appendChild(this.wrapper),this.renderItems(),this.updateLayoutMetrics(),this.bindEvents(),this.setTheme(ct.getTheme()),this.updateLocales(),this.unsubscribeTheme=ct.subscribe(t=>{this.setTheme(t)}),this.unsubscribeLocale=$t.subscribe(()=>{this.updateLocales()})}createDefaultItems(){return[{id:"zoom",label:"toolbar.zoomBox",icon:ut("框选放大")},{id:"measure",label:"toolbar.measure",icon:ut("测量")},{id:"section",label:"toolbar.section",icon:ut("剖切")},{id:"walk",label:"toolbar.walk",icon:ut("漫游")},{id:"setting",label:"toolbar.setting",icon:ut("设置")}]}createWrapper(){const e=document.createElement("div");return e.className="radial-toolbar-wrapper",e}createMainButton(e){const t=document.createElement("button");return t.className="radial-main-btn",t.type="button",t.innerHTML=e??ut("主视角"),t}bindEvents(){this.mainButton.addEventListener("mouseenter",this.handlePointerEnter),this.mainButton.addEventListener("mouseleave",this.handlePointerLeave),this.mainButton.addEventListener("click",this.handleMainButtonClick),document.addEventListener("click",this.handleDocumentClick),document.addEventListener("mousemove",this.handleDocumentMouseMove),document.addEventListener("mouseleave",this.handleDocumentMouseLeave),document.addEventListener("visibilitychange",this.handleVisibilityChange),window.addEventListener("blur",this.handleWindowBlur)}handleDocumentMouseMove=e=>{this.pointerX=e.clientX,this.pointerY=e.clientY};handleDocumentMouseLeave=()=>{this.pointerX=Number.NaN,this.pointerY=Number.NaN,this.collapse()};handleVisibilityChange=()=>{document.hidden&&(this.pointerX=Number.NaN,this.pointerY=Number.NaN,this.collapse())};handleWindowBlur=()=>{this.pointerX=Number.NaN,this.pointerY=Number.NaN,this.collapse()};handlePointerEnter=()=>{this.timer&&(clearTimeout(this.timer),this.timer=null),this.expand()};handlePointerLeave=e=>{const t=e.relatedTarget;t instanceof Node&&this.wrapper.contains(t)||this.scheduleCollapse()};handleMainButtonClick=e=>{if(e.stopPropagation(),this.onMainButtonClick){this.onMainButtonClick();return}if(this.isActive){this.collapse();return}this.expand()};handleDocumentClick=e=>{const t=e.target;t instanceof Node&&(this.wrapper.contains(t)||this.collapse())};renderItems(){this.itemElements.forEach(e=>e.remove()),this.itemElements=[],this.itemButtonMap.clear(),this.toggleStateMap.clear(),this.items.forEach((e,t)=>{this.toggleStateMap.set(e.id,!!e.isActive);const i=this.createSubButton(e,t);this.wrapper.insertBefore(i,this.mainButton),this.itemElements.push(i),this.itemButtonMap.set(e.id,i)}),this.updateItemPositions()}createSubButton(e,t){const i=document.createElement("button");i.className="radial-sub-btn",i.type="button",i.dataset.index=String(t),this.applyItemActiveClass(i,e);const n=document.createElement("span");return n.className="radial-sub-btn-icon",e.icon?n.innerHTML=e.icon:n.textContent=this.getFallbackLabel(e.label),i.appendChild(n),i.addEventListener("mouseenter",this.handlePointerEnter),i.addEventListener("mouseleave",this.handlePointerLeave),i.addEventListener("click",r=>{if(r.stopPropagation(),e.isToggle){const o=!(this.toggleStateMap.get(e.id)??!1);this.toggleStateMap.set(e.id,o),e.isActive=o,this.applyItemActiveClass(i,e),e.onToggle?.(o,e),this.collapse();return}e.onClick?.(e),this.collapse()}),i}updateItemPositions(){const e=this.itemElements.length,t=this.FAN_END_DEG-this.FAN_START_DEG;this.itemElements.forEach((i,n)=>{const r=Math.floor(n/this.itemsPerRing),a=r*this.itemsPerRing,o=Math.min(this.itemsPerRing,e-a),l=n-a,c=o===1?.5:l/(o-1),d=(this.FAN_START_DEG+t*c)*Math.PI/180,p=this.getBaseRadius(o)+r*this.RING_GAP,u=Math.cos(d)*p,v=Math.sin(d)*p,g=(l+r*.5)*.045,m=(o-1-l+r*.4)*.032;i.style.setProperty("--rt-x",`${u.toFixed(2)}px`),i.style.setProperty("--rt-y",`${v.toFixed(2)}px`),i.style.setProperty("--rt-open-delay",`${g.toFixed(3)}s`),i.style.setProperty("--rt-close-delay",`${m.toFixed(3)}s`)})}updateLayoutMetrics(){const e=this.items.length,t=Math.max(1,Math.ceil(e/this.itemsPerRing)),i=Math.max(1,Math.min(e,this.itemsPerRing)),n=this.getBaseRadius(i)+(t-1)*this.RING_GAP,r=Math.ceil(n+this.MAIN_BUTTON_SIZE+this.SUB_BUTTON_SIZE+this.CANVAS_PADDING*2);this.maxInteractiveRadius=n+this.SUB_BUTTON_SIZE*.7,this.wrapper.style.width=`${r}px`,this.wrapper.style.height=`${r}px`,this.wrapper.style.setProperty("--rt-main-size",`${this.MAIN_BUTTON_SIZE}px`),this.wrapper.style.setProperty("--rt-sub-size",`${this.SUB_BUTTON_SIZE}px`),this.wrapper.style.setProperty("--rt-main-offset",`${(this.MAIN_BUTTON_SIZE-this.SUB_BUTTON_SIZE)/2}px`)}getBaseRadius(e){return this.BASE_RADIUS}scheduleCollapse(){this.timer&&clearTimeout(this.timer),this.timer=window.setTimeout(()=>{if(this.timer=null,this.isPointerInsideToolbar()){this.isActive&&this.scheduleCollapse();return}this.collapse()},this.closeDelay)}isPointerInsideToolbar(){return this.mainButton.matches(":hover")||this.itemElements.some(e=>e.matches(":hover"))?!0:this.isPointerInsideFanRegion()}isPointerInsideFanRegion(){if(!Number.isFinite(this.pointerX)||!Number.isFinite(this.pointerY))return!1;const e=this.mainButton.getBoundingClientRect(),t=e.left+e.width/2,i=e.top+e.height/2,n=this.pointerX-t,r=this.pointerY-i,a=Math.hypot(n,r);if(a<=this.MAIN_BUTTON_SIZE/2)return!0;if(a>this.maxInteractiveRadius)return!1;let o=Math.atan2(r,n)*180/Math.PI;return o<0&&(o+=360),this.FAN_START_DEG<=this.FAN_END_DEG?o>=this.FAN_START_DEG&&o<=this.FAN_END_DEG:o>=this.FAN_START_DEG||o<=this.FAN_END_DEG}expand(){this.isActive||this.items.length===0||(this.isActive=!0,this.wrapper.classList.add("is-active"))}collapse(){this.isActive&&(this.isActive=!1,this.wrapper.classList.remove("is-active"))}updateLocales(){const e=Ee(this.mainButtonLabel);this.mainButton.title=e,this.mainButton.setAttribute("aria-label",e),this.itemElements.forEach((t,i)=>{const n=this.items[i];if(!n)return;const r=Ee(n.label);if(t.title=r,t.setAttribute("aria-label",r),this.applyItemActiveClass(t,n),!n.icon){const a=t.querySelector(".radial-sub-btn-icon");a&&(a.textContent=this.getFallbackLabel(n.label))}})}applyItemActiveClass(e,t){if(!t.isToggle){e.classList.remove("is-active"),e.dataset.active="false";return}const i=this.toggleStateMap.get(t.id)??!!t.isActive;e.classList.toggle("is-active",i),e.dataset.active=i?"true":"false"}getFallbackLabel(e){const t=Ee(e).trim();return t?t.charAt(0).toUpperCase():"?"}setTheme(e){this.wrapper.classList.remove("theme-light","theme-dark"),this.wrapper.classList.add(`theme-${e.name}`);const t=this.wrapper.style;t.setProperty("--bim-primary",e.primary),t.setProperty("--bim-primary-hover",e.primaryHover),t.setProperty("--bim-primary-active",e.primaryActive),t.setProperty("--bim-text-inverse",e.textInverse),t.setProperty("--bim-icon-inverse",e.iconInverse),t.setProperty("--bim-shadow-glow",e.shadowGlow);const i=e.name==="dark";t.setProperty("--rt-main-bg",i?"rgba(55, 68, 86, 0.92)":e.floatingBtnBg),t.setProperty("--rt-main-bg-hover",i?"rgba(66, 82, 104, 0.96)":e.floatingBtnBgHover),t.setProperty("--rt-main-border",i?"rgba(117, 133, 154, 0.56)":e.floatingBtnBorder),t.setProperty("--rt-main-shadow",i?"0 2px 8px rgba(15, 23, 42, 0.32), 0 4px 12px rgba(15, 23, 42, 0.24)":e.floatingBtnShadow),t.setProperty("--rt-main-shadow-hover",i?"0 4px 12px rgba(15, 23, 42, 0.38), 0 6px 20px rgba(15, 23, 42, 0.3)":e.floatingBtnShadowHover),t.setProperty("--rt-main-icon",i?"#e2e8f0":e.floatingIconColor),t.setProperty("--rt-main-icon-hover",i?"#f8fafc":e.floatingIconColorHover),t.setProperty("--rt-sub-bg",i?"rgba(55, 68, 86, 0.92)":e.floatingBtnBg),t.setProperty("--rt-sub-bg-hover",i?"rgba(66, 82, 104, 0.96)":e.floatingBtnBgHover),t.setProperty("--rt-sub-border",i?"rgba(117, 133, 154, 0.56)":e.floatingBtnBorder),t.setProperty("--rt-sub-shadow",i?"0 2px 8px rgba(15, 23, 42, 0.32), 0 4px 12px rgba(15, 23, 42, 0.24)":e.floatingBtnShadow),t.setProperty("--rt-sub-shadow-hover",i?"0 4px 12px rgba(15, 23, 42, 0.38), 0 6px 20px rgba(15, 23, 42, 0.3)":e.floatingBtnShadowHover),t.setProperty("--rt-sub-icon",i?"#e2e8f0":e.floatingIconColor),t.setProperty("--rt-sub-icon-hover",i?"#f8fafc":e.floatingIconColorHover)}setItemActive(e,t){const i=this.items.find(r=>r.id===e);if(!i||!i.isToggle)return;i.isActive=t,this.toggleStateMap.set(e,t);const n=this.itemButtonMap.get(e);n&&this.applyItemActiveClass(n,i)}init(){}setLocales(){this.updateLocales()}destroy(){this.timer&&(clearTimeout(this.timer),this.timer=null),this.unsubscribeTheme&&(this.unsubscribeTheme(),this.unsubscribeTheme=null),this.unsubscribeLocale&&(this.unsubscribeLocale(),this.unsubscribeLocale=null),document.removeEventListener("click",this.handleDocumentClick),document.removeEventListener("mousemove",this.handleDocumentMouseMove),document.removeEventListener("mouseleave",this.handleDocumentMouseLeave),document.removeEventListener("visibilitychange",this.handleVisibilityChange),window.removeEventListener("blur",this.handleWindowBlur),this.mainButton.removeEventListener("mouseenter",this.handlePointerEnter),this.mainButton.removeEventListener("mouseleave",this.handlePointerLeave),this.mainButton.removeEventListener("click",this.handleMainButtonClick),this.itemElements.forEach(e=>{e.removeEventListener("mouseenter",this.handlePointerEnter),e.removeEventListener("mouseleave",this.handlePointerLeave)}),this.wrapper.parentNode&&this.wrapper.parentNode.removeChild(this.wrapper)}}const l9=s=>({id:"measure",label:"toolbar.measure",icon:ut("测量"),isToggle:!0,isActive:s.bottomDock?.isOpen("measure")??!1,onToggle:e=>{const t=s.bottomDock;if(!t){console.warn("[RadialToolbar] bottom dock not initialized: measure");return}e?t.open("measure"):t.close("measure"),console.log(`[RadialToolbar] 测量${e?"已打开":"已关闭"}`)}}),c9=s=>({id:"section",label:"toolbar.section",icon:ut("剖切"),isToggle:!0,isActive:s.bottomDock?.isOpen("section")??!1,onToggle:e=>{const t=s.bottomDock;if(!t){console.warn("[RadialToolbar] bottom dock not initialized: section");return}e?t.open("section"):t.close("section"),console.log(`[RadialToolbar] 剖切${e?"已打开":"已关闭"}`)}}),h9=s=>({id:"setting",label:"toolbar.setting",icon:ut("设置"),onClick:()=>{s.setting?.toggle(),console.log(`[RadialToolbar] 设置${s.setting?.isOpen()?"已打开":"已关闭"}`)}}),d9=s=>({id:"walk",label:"toolbar.walk",icon:ut("漫游"),isToggle:!0,isActive:s.bottomDock?.isOpen("walk")??!1,onToggle:e=>{const t=s.bottomDock;if(!t){console.warn("[RadialToolbar] bottom dock not initialized: walk");return}e?t.open("walk"):t.close("walk"),console.log(`[RadialToolbar] 漫游${e?"已打开":"已关闭"}`)}});class u9 extends jn{toolbar=null;unsubscribeDockState=null;constructor(e,t,i){super(t),this.toolbar=new o9({container:e,items:i?.items??this.createDefaultItems(),itemsPerRing:i?.itemsPerRing??4,mainButtonIcon:ut("主视角"),mainButtonLabel:"toolbar.home",onMainButtonClick:()=>{console.log("[RadialToolbar] main: home"),this.registry.engine3d?.getEngineComponent()?.CameraGoHome()}}),this.toolbar.setTheme(ct.getTheme()),this.unsubscribeDockState=this.registry.bottomDock?.onStateChange(({id:n,open:r})=>{this.toolbar?.setItemActive(n,r)})??null,this.syncInitialToggleStates()}createDefaultItems(){return[h9(this.registry),l9(this.registry),c9(this.registry),d9(this.registry)]}syncInitialToggleStates(){const e=this.registry.bottomDock;!e||!this.toolbar||(this.toolbar.setItemActive("measure",e.isOpen("measure")),this.toolbar.setItemActive("section",e.isOpen("section")),this.toolbar.setItemActive("walk",e.isOpen("walk")))}destroy(){this.unsubscribeDockState&&(this.unsubscribeDockState(),this.unsubscribeDockState=null),this.toolbar?.destroy(),this.toolbar=null,super.destroy()}}class p9{container;root;panelGap=10;panelMap=new Map;panelOrder=[];resizeObserver;handleWindowResize=()=>{this.reflow()};constructor(e){this.container=e,this.root=document.createElement("div"),this.root.className="bottom-dock-stack",this.container.appendChild(this.root),this.resizeObserver=typeof ResizeObserver<"u"?new ResizeObserver(()=>{this.reflow()}):null,this.resizeObserver||window.addEventListener("resize",this.handleWindowResize)}setTheme(e){const t=this.root.style;t.setProperty("--bd-bg",e.floatingBtnBg),t.setProperty("--bd-border",e.floatingBtnBorder),t.setProperty("--bd-shadow",e.floatingBtnShadow),t.setProperty("--bd-close-color",e.floatingIconColor),t.setProperty("--bd-close-color-hover",e.floatingIconColorHover),t.setProperty("--bd-close-bg-hover",e.floatingBtnBgHover),t.setProperty("--bd-close-border-hover",e.floatingBtnBorder),t.setProperty("--bd-body-bg",e.floatingBtnBg),t.setProperty("--bd-placeholder-border",e.borderSubtle),t.setProperty("--bd-placeholder-text",e.textSecondary)}hasPanel(e){return this.panelMap.has(e)}addPanel(e){const t=this.panelMap.get(e.id);if(t&&t.leaving){t.leaving=!1,t.element.classList.remove("is-leaving"),t.removeTimer&&(clearTimeout(t.removeTimer),t.removeTimer=null),t.bodyElement.replaceChildren(e.content),this.panelOrder.includes(e.id)||this.panelOrder.push(e.id),this.reflow();return}if(t)return;const i=document.createElement("section");i.className="bottom-dock-panel is-entering",i.dataset.panelId=e.id;let n=null;e.closable!==!1&&(n=document.createElement("button"),n.className="bottom-dock-panel-close",n.type="button",n.setAttribute("aria-label","close-panel"),n.textContent="×",n.addEventListener("click",a=>{a.stopPropagation(),e.onClose(e.id)}),i.appendChild(n));const r=document.createElement("div");r.className="bottom-dock-panel-body",r.appendChild(e.content),i.appendChild(r),this.root.appendChild(i),this.panelOrder.push(e.id),this.panelMap.set(e.id,{id:e.id,element:i,bodyElement:r,closeButton:n,leaving:!1,removeTimer:null}),this.resizeObserver?.observe(i),this.reflow(),requestAnimationFrame(()=>{i.classList.remove("is-entering")})}removePanel(e){const t=this.panelMap.get(e);if(!t||t.leaving)return;t.leaving=!0,t.element.classList.add("is-leaving");const i=this.panelOrder.indexOf(e);i>=0&&this.panelOrder.splice(i,1),this.reflow(),t.removeTimer=window.setTimeout(()=>{this.resizeObserver?.unobserve(t.element),t.element.remove(),this.panelMap.delete(e),t.removeTimer=null},220)}createPlaceholderContent(e){const t=document.createElement("div");return t.className="bottom-dock-placeholder",t.textContent=e,t}destroy(){this.resizeObserver?.disconnect(),window.removeEventListener("resize",this.handleWindowResize),this.panelMap.clear(),this.panelOrder.length=0,this.root.remove()}reflow(){let e=0,t=0;this.panelOrder.forEach(r=>{const a=this.panelMap.get(r);a&&(a.element.style.transform=`translateX(-50%) translateY(-${e}px)`,e+=a.element.offsetHeight+this.panelGap,t=Math.max(t,a.element.offsetWidth))});const i=this.panelOrder.length,n=i>0?e-this.panelGap:0;this.root.style.height=`${n}px`,this.root.style.width=i>0?`${t}px`:"0px"}}class f9 extends jn{stack;definitions=new Map;openStates=new Map;listeners=new Set;unsubscribeTheme=null;constructor(e,t){super(t),this.stack=new p9(e),this.stack.setTheme(ct.getTheme()),this.unsubscribeTheme=ct.subscribe(i=>{this.stack.setTheme(i)}),this.registerDefaultPanels()}register(e){this.definitions.set(e.id,e),this.openStates.has(e.id)||this.openStates.set(e.id,!1)}unregister(e){this.isOpen(e)&&this.close(e),this.definitions.delete(e),this.openStates.delete(e)}toggle(e){if(this.isOpen(e)){this.close(e);return}this.open(e)}open(e){const t=this.definitions.get(e);if(!t){console.warn(`[BottomDock] Unknown panel id: ${e}`);return}if(this.isOpen(e))return;const i=t.createContent?t.createContent():this.stack.createPlaceholderContent(`${t.title} 面板内容占位`);this.stack.addPanel({id:e,content:i,closable:t.closable!==!1,onClose:()=>{this.close(e)}}),this.openStates.set(e,!0),this.emitState({id:e,open:!0})}close(e){this.isOpen(e)&&(this.stack.removePanel(e),this.openStates.set(e,!1),this.emitState({id:e,open:!1}))}isOpen(e){return this.openStates.get(e)??!1}createPlaceholderContent(e){return this.stack.createPlaceholderContent(e)}onStateChange(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}destroy(){this.unsubscribeTheme&&(this.unsubscribeTheme(),this.unsubscribeTheme=null),this.listeners.clear(),this.definitions.clear(),this.openStates.clear(),this.stack.destroy(),super.destroy()}emitState(e){this.listeners.forEach(t=>{t(e)})}registerDefaultPanels(){this.register({id:"measure",title:"测量",createContent:()=>{const e=this.registry.measureDock?.getPanelElement();return e||this.stack.createPlaceholderContent("测量面板占位")}}),this.register({id:"section",title:"剖切",createContent:()=>this.stack.createPlaceholderContent("剖切面板占位")}),this.register({id:"walk",title:"漫游",createContent:()=>this.stack.createPlaceholderContent("漫游面板占位")})}}const m9=["distance","clearHeight","clearDistance","elevation"],g9=["point","angle","area","slope"],G2="bim-engine:measure:config",v9={unit:"mm",precision:2};class y9{element;options;modeButtons=new Map;clearBtn;expandBtn;settingsBtn;secondaryRow;clearHeightOptions;clearHeightDirectionLabel;clearHeightSelectTypeLabel;directionButtons=new Map;selectTypeButtons=new Map;mainView;settingsView;settingsUnitLabel;settingsPrecisionLabel;settingsUnitSelect;settingsPrecisionSelect;settingsSaveBtn;settingsBackBtn;activeMode;isExpanded;clearHeightDirection;clearHeightSelectType;view="main";config;lockedWidthPx=null;constructor(e={}){this.options=e,this.activeMode=e.defaultMode??"distance",this.isExpanded=e.defaultExpanded??!1,this.clearHeightDirection=e.defaultClearHeightDirection??1,this.clearHeightSelectType=e.defaultClearHeightSelectType??"point",this.config=this.loadConfigFromCache()??{...v9};const{root:t,clearBtn:i,expandBtn:n,settingsBtn:r,secondaryRow:a,clearHeightOptions:o,clearHeightDirectionLabel:l,clearHeightSelectTypeLabel:c,mainView:h,settingsView:d,settingsUnitLabel:p,settingsPrecisionLabel:u,settingsUnitSelect:v,settingsPrecisionSelect:g,settingsSaveBtn:m,settingsBackBtn:f}=this.createDom();this.element=t,this.clearBtn=i,this.expandBtn=n,this.settingsBtn=r,this.secondaryRow=a,this.clearHeightOptions=o,this.clearHeightDirectionLabel=l,this.clearHeightSelectTypeLabel=c,this.mainView=h,this.settingsView=d,this.settingsUnitLabel=p,this.settingsPrecisionLabel=u,this.settingsUnitSelect=v,this.settingsPrecisionSelect=g,this.settingsSaveBtn=m,this.settingsBackBtn=f}init(){this.setLocales(),this.syncSettingsFormFromConfig(),this.applyExpandedState(),this.applyClearHeightOptionsState(),this.applyViewState(),this.syncActiveMode(this.activeMode)}setTheme(e){const t=this.element.style;t.setProperty("--bim-text-primary",e.textPrimary),t.setProperty("--bim-text-secondary",e.textSecondary),t.setProperty("--bim-text-tertiary",e.textTertiary),t.setProperty("--bim-border-default",e.borderDefault),t.setProperty("--bim-border-strong",e.borderStrong),t.setProperty("--bim-bg-inset",e.bgInset),t.setProperty("--bim-bg-elevated",e.bgElevated),t.setProperty("--bim-primary",e.primary),t.setProperty("--bim-primary-subtle",e.primarySubtle),t.setProperty("--bim-danger",e.danger),t.setProperty("--bim-component-bg-hover",e.componentBgHover)}setLocales(){for(const[n,r]of this.modeButtons.entries()){const a=Ee(`measure.modes.${n}`);r.dataset.tooltip=a,r.setAttribute("aria-label",a)}const e=Ee("measure.actions.clearAll");this.clearBtn.dataset.tooltip=e,this.clearBtn.setAttribute("aria-label",e);const t=this.isExpanded?Ee("measure.actions.collapse"):Ee("measure.actions.expand");delete this.expandBtn.dataset.tooltip,this.expandBtn.setAttribute("aria-label",t);const i=Ee("measure.actions.settings");this.settingsBtn.dataset.tooltip=i,this.settingsBtn.setAttribute("aria-label",i),this.clearHeightDirectionLabel.textContent=Ee("measure.clearHeight.direction"),this.clearHeightSelectTypeLabel.textContent=Ee("measure.clearHeight.selectType"),this.directionButtons.get(0).textContent=Ee("measure.clearHeight.directionDown"),this.directionButtons.get(1).textContent=Ee("measure.clearHeight.directionUp"),this.selectTypeButtons.get("point").textContent=Ee("measure.clearHeight.selectPoint"),this.selectTypeButtons.get("element").textContent=Ee("measure.clearHeight.selectElement"),this.settingsUnitLabel.textContent=Ee("measure.settings.unit"),this.settingsPrecisionLabel.textContent=Ee("measure.settings.precision"),this.settingsSaveBtn.textContent=Ee("measure.settings.save"),this.settingsBackBtn.textContent=Ee("measure.settings.cancel")}switchMode(e,t=!0){this.activeMode=e,this.syncActiveMode(e),this.applyClearHeightOptionsState(),this.closeSettingsView(),t&&this.options.onModeChange?.(e),e==="clearHeight"&&(this.options.onClearHeightDirectionChange?.(this.clearHeightDirection),this.options.onClearHeightSelectTypeChange?.(this.clearHeightSelectType))}destroy(){this.element.remove()}getConfig(){return{...this.config}}createDom(){const e=document.createElement("div");e.className="measure-dock-panel";const t=document.createElement("div");t.className="measure-dock-panel-main";const i=document.createElement("div");i.className="measure-dock-clearheight-options";const n=document.createElement("div");n.className="measure-dock-clearheight-group";const r=document.createElement("span");r.className="measure-dock-clearheight-label";const a=document.createElement("div");a.className="measure-dock-clearheight-buttons";const o=this.createClearHeightOptionButton(()=>{this.setClearHeightDirection(0)}),l=this.createClearHeightOptionButton(()=>{this.setClearHeightDirection(1)});this.directionButtons.set(0,o),this.directionButtons.set(1,l),a.appendChild(o),a.appendChild(l),n.appendChild(r),n.appendChild(a);const c=document.createElement("div");c.className="measure-dock-clearheight-group";const h=document.createElement("span");h.className="measure-dock-clearheight-label";const d=document.createElement("div");d.className="measure-dock-clearheight-buttons";const p=this.createClearHeightOptionButton(()=>{this.setClearHeightSelectType("point")}),u=this.createClearHeightOptionButton(()=>{this.setClearHeightSelectType("element")});this.selectTypeButtons.set("point",p),this.selectTypeButtons.set("element",u),d.appendChild(p),d.appendChild(u),c.appendChild(h),c.appendChild(d),i.appendChild(n),i.appendChild(c);const v=document.createElement("div");v.className="measure-dock-panel-top";const g=document.createElement("div");g.className="measure-dock-panel-mode-zone";const m=document.createElement("div");m.className="measure-dock-panel-mode-row",m9.forEach(k=>{m.appendChild(this.createModeButton(k))});const f=document.createElement("div");f.className="measure-dock-panel-mode-row measure-dock-panel-mode-row-secondary",g9.forEach(k=>{f.appendChild(this.createModeButton(k))});const y=this.createIconButton("measure-dock-panel-action-clear",ut("delete"));y.addEventListener("click",()=>{this.options.onClearAll?.()});const x=this.createIconButton("measure-dock-panel-action-settings",ut("settings"));x.addEventListener("click",()=>{this.openSettingsView(),this.options.onSettings?.()}),m.appendChild(y),f.appendChild(x),g.appendChild(m),g.appendChild(f);const _=document.createElement("div");_.className="measure-dock-panel-actions";const S=this.createIconButton("measure-dock-panel-action-expand",ut("expand"));S.addEventListener("click",()=>{this.isExpanded=!this.isExpanded,this.applyExpandedState(),this.setLocales()}),_.appendChild(S),v.appendChild(g),v.appendChild(_),t.appendChild(i),t.appendChild(v);const{settingsView:b,settingsUnitLabel:E,settingsPrecisionLabel:w,settingsUnitSelect:M,settingsPrecisionSelect:C,settingsSaveBtn:I,settingsBackBtn:P}=this.createSettingsView();return e.appendChild(t),e.appendChild(b),{root:e,clearBtn:y,expandBtn:S,settingsBtn:x,secondaryRow:f,clearHeightOptions:i,clearHeightDirectionLabel:r,clearHeightSelectTypeLabel:h,mainView:t,settingsView:b,settingsUnitLabel:E,settingsPrecisionLabel:w,settingsUnitSelect:M,settingsPrecisionSelect:C,settingsSaveBtn:I,settingsBackBtn:P}}createSettingsView(){const e=document.createElement("div");e.className="measure-dock-panel-settings";const t=document.createElement("div");t.className="measure-dock-settings-row";const i=document.createElement("span");i.className="measure-dock-settings-label";const n=document.createElement("select");n.className="measure-dock-settings-select",["m","cm","mm","km"].forEach(d=>{const p=document.createElement("option");p.value=d,p.textContent=d,n.appendChild(p)}),t.appendChild(i),t.appendChild(n);const r=document.createElement("div");r.className="measure-dock-settings-row";const a=document.createElement("span");a.className="measure-dock-settings-label";const o=document.createElement("select");o.className="measure-dock-settings-select",[0,1,2,3].forEach(d=>{const p=document.createElement("option");p.value=String(d),p.textContent=d===0?"0":`0.${"0".repeat(d)}`,o.appendChild(p)}),r.appendChild(a),r.appendChild(o);const l=document.createElement("div");l.className="measure-dock-settings-actions";const c=document.createElement("button");c.type="button",c.className="measure-dock-settings-btn is-save",c.addEventListener("click",()=>{this.saveSettings()});const h=document.createElement("button");return h.type="button",h.className="measure-dock-settings-btn is-back",h.addEventListener("click",()=>{this.closeSettingsView()}),l.appendChild(c),l.appendChild(h),e.appendChild(t),e.appendChild(r),e.appendChild(l),{settingsView:e,settingsUnitLabel:i,settingsPrecisionLabel:a,settingsUnitSelect:n,settingsPrecisionSelect:o,settingsSaveBtn:c,settingsBackBtn:h}}createClearHeightOptionButton(e){const t=document.createElement("button");return t.type="button",t.className="measure-dock-clearheight-btn",t.addEventListener("click",e),t}createModeButton(e){const t=document.createElement("button");return t.type="button",t.className="measure-dock-panel-mode-btn",t.dataset.mode=e,t.innerHTML=`${dc[e].icon}`,t.addEventListener("click",()=>{this.switchMode(e)}),this.modeButtons.set(e,t),t}createIconButton(e,t){const i=document.createElement("button");return i.type="button",i.className=`measure-dock-panel-action-btn ${e}`,i.innerHTML=t,i}applyExpandedState(){this.secondaryRow.style.display=this.isExpanded?"grid":"none",this.expandBtn.classList.toggle("is-expanded",this.isExpanded),this.expandBtn.classList.toggle("is-collapsed",!this.isExpanded)}openSettingsView(){this.lockPanelWidth(),this.view="settings",this.syncSettingsFormFromConfig(),this.applyViewState()}closeSettingsView(){this.view==="settings"&&(this.view="main",this.unlockPanelWidth(),this.applyViewState())}saveSettings(){const e=this.settingsUnitSelect.value,t=Number(this.settingsPrecisionSelect.value);!this.isValidUnit(e)||!this.isValidPrecision(t)||(this.config={unit:e,precision:t},this.saveConfigToCache(this.config),this.options.onConfigSave?.(this.getConfig()),this.view="main",this.unlockPanelWidth(),this.applyViewState())}lockPanelWidth(){const e=this.element.getBoundingClientRect().width;e<=0||(this.lockedWidthPx=Math.ceil(e),this.element.style.width=`${this.lockedWidthPx}px`)}unlockPanelWidth(){this.lockedWidthPx=null,this.element.style.removeProperty("width")}syncSettingsFormFromConfig(){this.settingsUnitSelect.value=this.config.unit,this.settingsPrecisionSelect.value=String(this.config.precision)}applyViewState(){const e=this.view==="main";this.mainView.style.display=e?"block":"none",this.settingsView.style.display=e?"none":"flex"}applyClearHeightOptionsState(){this.clearHeightOptions.classList.remove("is-visible");for(const[e,t]of this.directionButtons.entries())t.classList.toggle("is-active",e===this.clearHeightDirection);for(const[e,t]of this.selectTypeButtons.entries())t.classList.toggle("is-active",e===this.clearHeightSelectType)}setClearHeightDirection(e){this.clearHeightDirection!==e&&(this.clearHeightDirection=e,this.applyClearHeightOptionsState(),this.options.onClearHeightDirectionChange?.(e))}setClearHeightSelectType(e){this.clearHeightSelectType!==e&&(this.clearHeightSelectType=e,this.applyClearHeightOptionsState(),this.options.onClearHeightSelectTypeChange?.(e))}loadConfigFromCache(){try{const e=localStorage.getItem(G2);if(!e)return null;const t=JSON.parse(e);return!t||typeof t!="object"||!this.isValidUnit(t.unit)||!this.isValidPrecision(t.precision)?null:{unit:t.unit,precision:t.precision}}catch{return null}}saveConfigToCache(e){try{localStorage.setItem(G2,JSON.stringify(e))}catch{return}}isValidUnit(e){return e==="m"||e==="cm"||e==="mm"||e==="km"}isValidPrecision(e){return e===0||e===1||e===2||e===3}syncActiveMode(e){for(const[t,i]of this.modeButtons.entries())i.classList.toggle("is-active",t===e)}}class x9 extends jn{panel=null;unsubscribeTheme=null;unsubscribeLocale=null;unsubscribeDockState=null;unsubscribeMeasureEvents=null;constructor(e){super(e)}init(){this.unsubscribeTheme||(this.unsubscribeTheme=ct.subscribe(()=>{this.applyPresentation()})),this.unsubscribeLocale||(this.unsubscribeLocale=$t.subscribe(()=>{this.applyPresentation()})),this.unsubscribeDockState||(this.unsubscribeDockState=this.registry.bottomDock?.onStateChange(e=>{if(e.id!=="measure"||e.open){e.id==="measure"&&e.open&&this.ensureMeasureEventSubscription();return}this.engineComponent?.deactivateMeasure()})??null),this.ensureMeasureEventSubscription()}destroy(){this.unsubscribeTheme&&(this.unsubscribeTheme(),this.unsubscribeTheme=null),this.unsubscribeLocale&&(this.unsubscribeLocale(),this.unsubscribeLocale=null),this.unsubscribeDockState&&(this.unsubscribeDockState(),this.unsubscribeDockState=null),this.unsubscribeMeasureEvents&&(this.unsubscribeMeasureEvents(),this.unsubscribeMeasureEvents=null),this.panel?.destroy(),this.panel=null,super.destroy()}getPanelElement(){if(this.ensureMeasureEventSubscription(),this.panel)this.panel.switchMode("distance");else{this.panel=new y9({defaultMode:"distance",defaultExpanded:!1,defaultClearHeightDirection:1,defaultClearHeightSelectType:"point",onModeChange:t=>{this.engineComponent?.activateMeasure(t)},onClearAll:()=>{this.engineComponent?.clearAllMeasures()},onConfigSave:t=>{this.engineComponent?.saveMeasureSetting({unit:t.unit,precision:t.precision})},onClearHeightDirectionChange:t=>{this.engineComponent?.setClearHeightDirection(t)},onClearHeightSelectTypeChange:t=>{this.engineComponent?.setClearHeightSelectType(t)}}),this.panel.init(),this.panel.switchMode("distance"),this.engineComponent?.setClearHeightDirection(1),this.engineComponent?.setClearHeightSelectType("point");const e=this.panel.getConfig();this.engineComponent?.saveMeasureSetting({unit:e.unit,precision:e.precision})}return this.applyPresentation(),this.panel.element}ensureMeasureEventSubscription(){if(this.unsubscribeMeasureEvents)return;const e=this.engineComponent;if(!e){console.warn("[MeasureDockManager] skip callback binding: engine component not ready yet");return}const t=n=>{this.handleMeasureCallback("measure-changed",n)},i=n=>{this.handleMeasureCallback("measure-click",n)};e.onRawEvent("measure-changed",t),e.onRawEvent("measure-click",i),this.unsubscribeMeasureEvents=()=>{e.offRawEvent("measure-changed",t),e.offRawEvent("measure-click",i)},console.log("[MeasureDockManager] raw event callbacks bound")}applyPresentation(){this.panel&&(this.panel.setTheme(ct.getTheme()),this.panel.setLocales())}handleMeasureCallback(e,t){const i=this.registry.bottomDock?.isOpen("measure")??!1,n=L2(t.type);if(console.log("[MeasureDockManager] callback received",{event:e,type:t.type,mode:n,dockOpen:i,hasPanel:!!this.panel}),!i){console.log("[MeasureDockManager] skip mode switch: measure dock is closed");return}if(!n||!this.panel){console.log("[MeasureDockManager] skip mode switch: invalid mode or panel not ready");return}this.panel.switchMode(n,!1),this.engineComponent?.activateMeasure(n),console.log("[MeasureDockManager] switched mode by callback",{event:e,mode:n})}}class _9{container;wrapper=null;sizeEl=null;resizeObserver=null;lastSyncedWidth=-1;lastSyncedHeight=-1;unsubscribeTheme=null;registry;dialog=null;engine=null;rightKey=null;radialToolbar=null;bottomDock=null;measureDock=null;measure=null;sectionPlane=null;sectionAxis=null;sectionBox=null;walkControl=null;engineInfo=null;componentDetail=null;aiChat=null;setting=null;handleWindowResize=()=>{this.updateClientSizeDisplay()};constructor(e,t){const i=typeof e=="string"?document.getElementById(e):e;if(!i)throw new Error("Container not found");this.container=i,this.registry=new Sm,t?.locale&&$t.setLocale(t.locale),t?.theme&&(t.theme==="custom"?console.warn("Custom theme should be set via setCustomTheme()."):ct.setTheme(t.theme)),this.init()}emit(e,t){this.registry.emit(e,t)}on(e,t){return this.registry.on(e,t)}setLocale(e){$t.setLocale(e)}getLocale(){return $t.getLocale()}setTheme(e){ct.setTheme(e)}setCustomTheme(e){ct.setCustomTheme(e)}init(){this.container.innerHTML="",this.wrapper=document.createElement("div"),this.wrapper.className="bim-engine-wrapper",this.container.appendChild(this.wrapper);const e=document.createElement("div");e.className="bim-engine-version",e.textContent="v2.4.8",this.wrapper.appendChild(e),this.sizeEl=document.createElement("div"),this.sizeEl.className="bim-engine-size",this.wrapper.appendChild(this.sizeEl),this.updateClientSizeDisplay(),this.bindSizeObserver(),this.registry.container=this.container,this.registry.wrapper=this.wrapper,this.engine=new T2(this.wrapper,this.registry),this.dialog=new vy(this.wrapper,this.registry),this.rightKey=new oy(this.wrapper,this.registry),this.bottomDock=new f9(this.wrapper,this.registry),this.registry.bottomDock=this.bottomDock,this.registry.engine3d=this.engine,this.registry.dialog=this.dialog,this.registry.rightKey=this.rightKey,this.measureDock=new x9(this.registry),this.registry.measureDock=this.measureDock,this.measureDock.init(),this.radialToolbar=new u9(this.wrapper,this.registry),this.measure=new D2(this.registry),this.sectionPlane=new N2(this.registry),this.sectionAxis=new k2(this.registry),this.sectionBox=new U2(this.registry),this.walkControl=new B2(this.registry),this.walkControl.init(),this.engineInfo=new F2(this.registry),this.engineInfo.init(),this.registry.radialToolbar=this.radialToolbar,this.registry.measure=this.measure,this.registry.sectionPlane=this.sectionPlane,this.registry.sectionAxis=this.sectionAxis,this.registry.sectionBox=this.sectionBox,this.registry.walkControl=this.walkControl,this.registry.engineInfo=this.engineInfo,this.componentDetail=new H2(this.registry),this.registry.componentDetail=this.componentDetail,this.componentDetail.init(),this.aiChat=new V2(this.registry),this.registry.aiChat=this.aiChat,this.aiChat.init(),this.setting=new Rr(this.registry),this.registry.setting=this.setting,this.setting.init(),this.updateTheme(ct.getTheme()),this.unsubscribeTheme=ct.subscribe(t=>{this.updateTheme(t)})}updateTheme(e){this.wrapper&&(this.wrapper.style.color=e.textPrimary)}updateClientSizeDisplay(){const e=this.container.clientWidth,t=this.container.clientHeight;this.sizeEl&&(this.sizeEl.textContent=`${e}px x ${t}px`),this.syncEngineSize(e,t)}syncEngineSize(e,t){e<=0||t<=0||e===this.lastSyncedWidth&&t===this.lastSyncedHeight||(this.lastSyncedWidth=e,this.lastSyncedHeight=t,this.engine?.getEngineComponent()?.resize(e,t))}bindSizeObserver(){if(typeof ResizeObserver<"u"){this.resizeObserver=new ResizeObserver(()=>{this.updateClientSizeDisplay()}),this.resizeObserver.observe(this.container);return}window.addEventListener("resize",this.handleWindowResize)}unbindSizeObserver(){if(this.resizeObserver){this.resizeObserver.disconnect(),this.resizeObserver=null;return}window.removeEventListener("resize",this.handleWindowResize)}destroy(){this.unbindSizeObserver(),this.unsubscribeTheme&&(this.unsubscribeTheme(),this.unsubscribeTheme=null),this.radialToolbar?.destroy(),this.measureDock?.destroy(),this.bottomDock?.destroy(),this.engine?.destroy(),this.dialog?.destroy(),this.rightKey?.destroy(),this.measure?.destroy(),this.sectionPlane?.destroy(),this.sectionAxis?.destroy(),this.sectionBox?.destroy(),this.walkControl?.destroy(),this.aiChat?.destroy(),this.setting?.destroy(),this.sizeEl=null,this.lastSyncedWidth=-1,this.lastSyncedHeight=-1,this.container.innerHTML="",this.registry.reset()}}class b9{engine=null;registry;container;containerId;options;_isInitialized=!1;_isDestroyed=!1;unsubscribeTheme=null;constructor(e,t){this.registry=t,this.container=e.container,this.container.id?this.containerId=this.container.id:(this.containerId=`engine2d-container-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,this.container.id=this.containerId),this.options={backgroundColor:e.backgroundColor??1710618,gridEnabled:e.gridEnabled??!0,axesEnabled:e.axesEnabled??!0,selectionColor:e.selectionColor,highlightColor:e.highlightColor,enablePerformanceMonitoring:e.enablePerformanceMonitoring??!0}}init(){if(this._isInitialized){console.warn("[Engine2d] Engine already initialized.");return}if(this._isDestroyed){console.error("[Engine2d] Cannot initialize destroyed engine.");return}try{const e={containerId:this.containerId,backgroundColor:this.options.backgroundColor,gridEnabled:this.options.gridEnabled,axesEnabled:this.options.axesEnabled};if(this.options.selectionColor!==void 0&&(e.selectionColor=this.options.selectionColor),this.options.highlightColor!==void 0&&(e.highlightColor=this.options.highlightColor),this.options.enablePerformanceMonitoring!==void 0&&(e.enablePerformanceMonitoring=this.options.enablePerformanceMonitoring),console.log("[Engine2d] 引擎配置信息:",e),this.engine=Oz(e),!this.engine)throw new Error("Failed to create 2D engine instance");this._isInitialized=!0,this.unsubscribeTheme=ct.subscribe(t=>{this.setTheme(t)}),this.setTheme(ct.getTheme()),this.engine.events&&(this.engine.events.on("entity-click",t=>{console.log("[Engine2d] 实体点击:",t),this.registry.emit("engine2d:entity-clicked",{data:t})}),this.engine.events.on("layer-visibility-changed",t=>{console.log("[Engine2d] 图层可见性变更:",t),this.registry.emit("engine2d:layer-changed",{data:t})}))}catch(e){throw console.error("[Engine2d] Failed to initialize 2D engine:",e),this._isInitialized=!1,e}}setTheme(e){}setLocales(){}isInitialized(){return this._isInitialized}async loadDrawing(e,t){if(!this._isInitialized||!this.engine){console.error("[Engine2d] Engine not initialized. Please call init() first.");return}if(!e){console.error("[Engine2d] Drawing URL is required.");return}try{console.log("[Engine2d] 开始加载图纸:",e),await this.engine.loadModel(e,t),console.log("[Engine2d] 图纸加载完成:",e),this.registry.emit("engine2d:drawing-loaded",{url:e})}catch(i){throw console.error("[Engine2d] 图纸加载失败:",i),i}}getLayers(){if(!this._isInitialized||!this.engine)return[];try{return this.engine.getLayers?.()??[]}catch(e){return console.warn("[Engine2d] Failed to get layers:",e),[]}}setLayerVisible(e,t){if(!this._isInitialized||!this.engine){console.warn("[Engine2d] Engine not initialized.");return}try{this.engine.setLayerVisible?.(e,t)}catch(i){console.warn("[Engine2d] Failed to set layer visibility:",i)}}resetView(){if(!(!this._isInitialized||!this.engine))try{this.engine.resetView?.()}catch(e){console.warn("[Engine2d] Failed to reset view:",e)}}fitToView(){if(!(!this._isInitialized||!this.engine))try{this.engine.fitToView?.()}catch(e){console.warn("[Engine2d] Failed to fit to view:",e)}}setZoom(e){!this._isInitialized||!this.engine||this.engine.setZoom?.(e)}getZoom(){return!this._isInitialized||!this.engine?1:this.engine.getZoom?.()??1}setBackgroundColor(e){!this._isInitialized||!this.engine||this.engine.setBackgroundColor?.(e)}clearScene(){!this._isInitialized||!this.engine||this.engine.clearScene?.()}resize(){!this._isInitialized||!this.engine||this.engine.resize?.()}onRawEvent(e,t){this.engine?.events?.on(e,t)}offRawEvent(e,t){this.engine?.events?.off(e,t)}destroy(){if(!this._isDestroyed){if(this.unsubscribeTheme&&(this.unsubscribeTheme(),this.unsubscribeTheme=null),this.engine){try{this.engine.dispose?.()}catch(e){console.warn("[Engine2d] Error during dispose:",e)}this.engine=null}this.container.innerHTML="",this._isDestroyed=!0,this._isInitialized=!1}}}class M9{container;registry;engineComponent=null;constructor(e,t){const i=typeof e=="string"?document.getElementById(e):e;if(!i)throw new Error("Container not found");this.container=i,this.registry=new Sm,t?.locale&&$t.setLocale(t.locale),t?.theme&&t.theme!=="custom"&&ct.setTheme(t.theme),this.engineComponent=new b9({container:this.container,backgroundColor:t?.backgroundColor,gridEnabled:t?.gridEnabled,axesEnabled:t?.axesEnabled,selectionColor:t?.selectionColor,highlightColor:t?.highlightColor,enablePerformanceMonitoring:t?.enablePerformanceMonitoring},this.registry),this.engineComponent.init()}async loadDrawing(e,t){return this.engineComponent?.loadDrawing(e,t)}getLayers(){return this.engineComponent?.getLayers()??[]}setLayerVisible(e,t){this.engineComponent?.setLayerVisible(e,t)}resetView(){this.engineComponent?.resetView()}fitToView(){this.engineComponent?.fitToView()}setZoom(e){this.engineComponent?.setZoom(e)}getZoom(){return this.engineComponent?.getZoom()??1}setTheme(e){ct.setTheme(e)}on(e,t){return this.registry.on(e,t)}off(e,t){this.registry.off(e,t)}onRawEvent(e,t){this.engineComponent?.onRawEvent(e,t)}offRawEvent(e,t){this.engineComponent?.offRawEvent(e,t)}destroy(){this.engineComponent?.destroy(),this.engineComponent=null,this.registry.reset()}}class S9{engine=null;registry;container;containerId;options;_isInitialized=!1;_isDestroyed=!1;unsubscribeTheme=null;constructor(e,t){this.registry=t,this.container=e.container,this.container.id?this.containerId=this.container.id:(this.containerId=`engine720-container-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,this.container.id=this.containerId),this.options={fov:e.fov??75,enableZoom:e.enableZoom??!0,enableRotate:e.enableRotate??!0,sphereRadius:e.sphereRadius??500,rotateSpeed:e.rotateSpeed,zoomSpeed:e.zoomSpeed,enableDamping:e.enableDamping,dampingFactor:e.dampingFactor,minFov:e.minFov,maxFov:e.maxFov}}init(){if(this._isInitialized){console.warn("[Engine720] Engine already initialized.");return}if(this._isDestroyed){console.error("[Engine720] Cannot initialize destroyed engine.");return}try{const e={containerId:this.containerId,fov:this.options.fov,enableZoom:this.options.enableZoom,enableRotate:this.options.enableRotate,sphereRadius:this.options.sphereRadius};if(this.options.rotateSpeed!==void 0&&(e.rotateSpeed=this.options.rotateSpeed),this.options.zoomSpeed!==void 0&&(e.zoomSpeed=this.options.zoomSpeed),this.options.enableDamping!==void 0&&(e.enableDamping=this.options.enableDamping),this.options.dampingFactor!==void 0&&(e.dampingFactor=this.options.dampingFactor),this.options.minFov!==void 0&&(e.minFov=this.options.minFov),this.options.maxFov!==void 0&&(e.maxFov=this.options.maxFov),console.log("[Engine720] 引擎配置信息:",e),this.engine=Uz(e),!this.engine)throw new Error("Failed to create 720 engine instance");this._isInitialized=!0,this.unsubscribeTheme=ct.subscribe(t=>{this.setTheme(t)}),this.setTheme(ct.getTheme()),this.engine.events&&(this.engine.events.on("panorama-loaded",t=>{console.log("[Engine720] 全景加载完成:",t),this.registry.emit("engine720:panorama-loaded",{data:t})}),this.engine.events.on("panorama-load-error",t=>{console.error("[Engine720] 全景加载失败:",t),this.registry.emit("engine720:load-error",{data:t})}),this.engine.events.on("annotation-click",t=>{console.log("[Engine720] 标注点击:",t),this.registry.emit("engine720:annotation-click",{data:t})}),this.engine.events.on("view-angle-changed",t=>{this.registry.emit("engine720:view-changed",{data:t})}))}catch(e){throw console.error("[Engine720] Failed to initialize 720 engine:",e),this._isInitialized=!1,e}}setTheme(e){!this._isInitialized||this.engine}setLocales(){}isInitialized(){return this._isInitialized}async loadPanorama(e,t){if(!this._isInitialized||!this.engine){console.error("[Engine720] Engine not initialized. Please call init() first.");return}if(!e){console.error("[Engine720] Panorama URL is required.");return}try{console.log("[Engine720] 开始加载全景图:",e),await this.engine.loadPanorama(e),console.log("[Engine720] 全景图加载完成:",e)}catch(i){throw console.error("[Engine720] 全景图加载失败:",i),i}}async preloadPanoramas(e){if(!(!this._isInitialized||!this.engine))try{await this.engine.preloadPanoramas?.(e)}catch(t){console.warn("[Engine720] Failed to preload panoramas:",t)}}setFov(e){!this._isInitialized||!this.engine||this.engine.setFov?.(e)}getFov(){return!this._isInitialized||!this.engine?75:this.engine.getFov?.()??75}lookAt(e,t,i){!this._isInitialized||!this.engine||this.engine.lookAt?.(e,t,i)}resetView(){if(!(!this._isInitialized||!this.engine))try{this.engine.lookAt?.(0,0,!0),this.engine.setFov?.(75)}catch(e){console.warn("[Engine720] Failed to reset view:",e)}}pauseRendering(){!this._isInitialized||!this.engine||this.engine.pauseRendering?.()}resumeRendering(){!this._isInitialized||!this.engine||this.engine.resumeRendering?.()}resize(e,t){!this._isInitialized||!this.engine||this.engine.resize?.(e,t)}onRawEvent(e,t){this.engine?.events?.on(e,t)}offRawEvent(e,t){this.engine?.events?.off(e,t)}destroy(){if(!this._isDestroyed){if(this.unsubscribeTheme&&(this.unsubscribeTheme(),this.unsubscribeTheme=null),this.engine){try{this.engine.dispose?.()}catch(e){console.warn("[Engine720] Error during dispose:",e)}this.engine=null}this.container.innerHTML="",this._isDestroyed=!0,this._isInitialized=!1}}}class w9{container;registry;engineComponent=null;constructor(e,t){const i=typeof e=="string"?document.getElementById(e):e;if(!i)throw new Error("Container not found");this.container=i,this.registry=new Sm,t?.locale&&$t.setLocale(t.locale),t?.theme&&t.theme!=="custom"&&ct.setTheme(t.theme),this.engineComponent=new S9({container:this.container,fov:t?.fov,enableZoom:t?.enableZoom,enableRotate:t?.enableRotate,sphereRadius:t?.sphereRadius,rotateSpeed:t?.rotateSpeed,zoomSpeed:t?.zoomSpeed,enableDamping:t?.enableDamping,dampingFactor:t?.dampingFactor,minFov:t?.minFov,maxFov:t?.maxFov},this.registry),this.engineComponent.init()}async loadPanorama(e,t){return this.engineComponent?.loadPanorama(e,t)}async preloadPanoramas(e){return this.engineComponent?.preloadPanoramas(e)}setFov(e){this.engineComponent?.setFov(e)}getFov(){return this.engineComponent?.getFov()??75}lookAt(e,t,i){this.engineComponent?.lookAt(e,t,i)}resetView(){this.engineComponent?.resetView()}setTheme(e){ct.setTheme(e)}on(e,t){return this.registry.on(e,t)}off(e,t){this.registry.off(e,t)}onRawEvent(e,t){this.engineComponent?.onRawEvent(e,t)}offRawEvent(e,t){this.engineComponent?.offRawEvent(e,t)}destroy(){this.engineComponent?.destroy(),this.engineComponent=null,this.registry.reset()}}const E9=Object.freeze(Object.defineProperty({__proto__:null,createHomeButton:s=>({id:"home",groupId:"group-1",type:"button",label:"toolbar.home",icon:ut("主视角"),keepActive:!1,onClick:e=>{console.log("首页按钮被点击:",e.id),s.engine3d?.getEngineComponent()?.CameraGoHome()}})},Symbol.toStringTag,{value:"Module"})),T9=Object.freeze(Object.defineProperty({__proto__:null,createZoomBoxButton:s=>({id:"zoom-box",groupId:"group-1",keepActive:!1,type:"button",label:"toolbar.zoomBox",icon:ut("框选放大"),onClick:()=>{s.engine3d?.getEngineComponent()?.activateZoomBox()}})},Symbol.toStringTag,{value:"Module"})),C9=Object.freeze(Object.defineProperty({__proto__:null,createWalkMenuButton:s=>({id:"walk",groupId:"group-1",type:"button",label:"toolbar.walk",align:"vertical",icon:ut("漫游"),onClick:()=>{console.log("漫游按钮被点击"),s.walkControl?.show()}})},Symbol.toStringTag,{value:"Module"})),A9=Object.freeze(Object.defineProperty({__proto__:null,createMapButton:s=>({id:"map",groupId:"group-1",type:"button",label:"toolbar.map",align:"vertical",keepActive:!0,icon:ut("地图"),onClick:()=>{s.engine3d?.getEngineComponent()?.toggleMiniMap();const e=s.engine3d?.getEngineComponent()?.getMiniMapState()??!1;s.walkControl?.panel?.setPlanViewActive(e)}})},Symbol.toStringTag,{value:"Module"})),P9=Object.freeze(Object.defineProperty({__proto__:null,createPropertyButton:s=>({id:"property",groupId:"group-1",type:"button",label:"toolbar.property",align:"vertical",icon:ut("文档"),onClick:()=>{console.log("构件详情按钮被点击"),s.componentDetail?.show()}})},Symbol.toStringTag,{value:"Module"})),R9=Object.freeze(Object.defineProperty({__proto__:null,createSettingButton:s=>({id:"setting",groupId:"group-2",type:"button",label:"toolbar.setting",icon:ut("设置"),keepActive:!1,onClick:e=>{s?.setting?.toggle()}})},Symbol.toStringTag,{value:"Module"})),I9=Object.freeze(Object.defineProperty({__proto__:null,createInfoButton:s=>({id:"info",groupId:"group-2",type:"button",label:"toolbar.info",icon:ut("信息"),keepActive:!1,onClick:()=>{s.engineInfo?.show()}})},Symbol.toStringTag,{value:"Module"})),L9=Object.freeze(Object.defineProperty({__proto__:null,createFullscreenButton:s=>({id:"fullscreen",groupId:"group-2",type:"button",label:"toolbar.fullscreen",align:"vertical",icon:ut("全屏"),onClick:async()=>{console.log("全屏按钮被点击"),window.self!==window.top&&console.warn('检测到在 Iframe 中运行,请确保父级 iframe 标签拥有 allow="fullscreen" 属性');try{const t=document,n=!!(t.fullscreenElement||t.webkitFullscreenElement||t.mozFullScreenElement||t.msFullscreenElement);console.log("当前是否全屏:",n);const a=document.querySelector(".bim-engine-container")||document.body,o=a;if(n){console.log("准备退出全屏...");const l=t.exitFullscreen||t.webkitExitFullscreen||t.mozCancelFullScreen||t.msExitFullscreen;l&&(await l.call(t),console.log("退出全屏请求已发送"))}else{console.log("准备进入全屏..."),(a.style.backgroundColor===""||a.style.backgroundColor==="transparent")&&(a.style.backgroundColor="#ffffff");const l=o.requestFullscreen||o.webkitRequestFullscreen||o.mozRequestFullScreen||o.msRequestFullscreen;l?(await l.call(o,{navigationUI:"hide"}),console.log("全屏请求已发送")):(console.warn("当前浏览器不支持全屏 API"),alert("当前浏览器不支持全屏功能"))}}catch(t){console.error("全屏操作失败:",t),t&&t.message&&t.message.includes("denied")&&console.error('全屏请求被拒绝。如果是 Iframe,请检查 allow="fullscreen"。如果是自动触发,请确保由用户点击触发。')}}})},Symbol.toStringTag,{value:"Module"})),D9=Object.freeze(Object.defineProperty({__proto__:null,createMeasureButton:s=>({id:"measure",groupId:"group-1",type:"button",label:"toolbar.measure",icon:ut("测量"),keepActive:!0,onClick:e=>{e.isActive?s.measure?.show():s.measure?.destroy()}})},Symbol.toStringTag,{value:"Module"})),N9=Object.freeze(Object.defineProperty({__proto__:null,createSectionMenuButton:s=>({id:"section",groupId:"group-1",type:"menu",label:"toolbar.section",align:"vertical",icon:ut("剖切"),keepActive:!0,onClick:e=>{console.log("剖切按钮被点击:",e.id)}})},Symbol.toStringTag,{value:"Module"})),k9=Object.freeze(Object.defineProperty({__proto__:null,createSectionPlaneButton:s=>({id:"section-plane",groupId:"group-1",parentId:"section",type:"button",keepActive:!0,exclusive:!0,align:"vertical",label:"toolbar.sectionPlane",icon:ut("拾曲面剖切"),onClick:e=>{console.log("拾取面剖切被点击:",e.id,"激活状态:",e.isActive),e.isActive?s.sectionPlane?.show():s.sectionPlane?.hide()}})},Symbol.toStringTag,{value:"Module"})),O9=Object.freeze(Object.defineProperty({__proto__:null,createSectionAxisButton:s=>({id:"section-axis",groupId:"group-1",parentId:"section",type:"button",keepActive:!0,exclusive:!0,align:"vertical",label:"toolbar.sectionAxis",icon:ut("轴向剖切"),onClick:e=>{e.isActive?s.sectionAxis?.show():s.sectionAxis?.destroy()}})},Symbol.toStringTag,{value:"Module"})),U9=Object.freeze(Object.defineProperty({__proto__:null,createSectionBoxButton:s=>({id:"section-box",groupId:"group-1",parentId:"section",type:"button",keepActive:!0,exclusive:!0,align:"vertical",label:"toolbar.sectionBox",icon:ut("剖切盒"),onClick:e=>{console.log("剖切盒被点击:",e.id,"激活状态:",e.isActive),e.isActive?s.sectionBox?.show():s.sectionBox?.hide()}})},Symbol.toStringTag,{value:"Module"})),B9=Object.freeze(Object.defineProperty({__proto__:null,createAiChatButton:s=>(s.on("aiChat:opened",()=>{s.toolbar?.setBtnActive("aiChat",!0)}),s.on("aiChat:closed",()=>{s.toolbar?.setBtnActive("aiChat",!1)}),{id:"aiChat",groupId:"group-2",type:"button",label:"aiChat.title",align:"vertical",keepActive:!0,icon:ut("bot"),onClick:()=>{s.aiChat?.toggle()}})},Symbol.toStringTag,{value:"Module"})),F9=Object.freeze(Object.defineProperty({__proto__:null,createCameraSwitchButton:s=>({id:"camera-switch",groupId:"group-1",type:"button",label:"toolbar.cameraSwitch",icon:ut("透视相机"),keepActive:!1,onClick:()=>{const e=s.engine3d?.getEngineComponent();if(!e)return;e.switchCamera();const t=e.getCameraType(),i=ut(t==="orthographic"?"正交相机":"透视相机");s.toolbar?.updateButtonIcon("camera-switch",i)}})},Symbol.toStringTag,{value:"Module"})),z9=Object.freeze(Object.defineProperty({__proto__:null,default:`# BIM引擎AI助手 - 需求分析与步骤规划专家\r \r ## 角色定位\r \r 你是一位资深的**AI+BIM轻量化引擎架构专家**,具备以下核心能力:\r \r 1. **深度理解BIM引擎架构**:精通BIM引擎的模块化设计、API体系、数据结构和交互模式\r 2. **需求分析能力**:能够准确理解用户意图,识别模糊需求,提出精准的澄清问题\r 3. **任务分解能力**:将复杂需求拆解为可执行的、原子化的操作步骤\r 4. **技术决策能力**:根据需求特点选择最优的API组合和实现路径\r \r 你的职责是通过分析用户需求,生成结构化的执行步骤,指导代码生成模块完成BIM引擎的功能实现。\r \r ## 工作流程\r \r 如果存在疑问,你就不能输出最终的步骤,只有当你把所有的疑问清楚后,你才可以输出步骤,如果存在疑问,你要以bim模型为载体,不能问一下和bim模型不想干的问题,尽量没有或减少问题\r \r ### 阶段一:需求理解与分析\r \r 当接收到用户需求时,你需要:\r \r 1. **深度分析需求**:\r - 理解用户的核心目标\r - 识别涉及到的BIM引擎模块(场景、相机、模型、测量、剖切等)\r - 分析数据流向和依赖关系\r - 评估需求的复杂度和可行性\r \r 2. **识别模糊点**:\r - 检查需求中是否存在歧义、缺失信息或边界条件不明确的情况\r - 判断是否需要用户澄清才能继续\r \r 3. **决策是否需要提问**:\r - **仅在必要时提问**:如果需求足够清晰,直接进入步骤规划阶段\r - **避免过度提问**:不要为了提问而提问,不要询问可以从上下文推断的信息\r - **精准提问**:每个问题都应该针对关键决策点,影响后续实现路径\r \r ### 阶段二:需求澄清(如需要)\r \r 如果需要用户澄清,请按照以下格式输出:\r \r **输出格式**:\r \`\`\`\r ##question## \r json内容\r \`\`\`\r \r **JSON格式规范**:\r \`\`\`json\r [\r {\r "id": 0,\r "question": "您是否需要设置所有的构件?",\r "answers": [\r "A. 是的,设置所有构件",\r "B. 只设置1F层的构件",\r "C. 根据特定条件筛选构件"\r ]\r },\r {\r "id": 1,\r "question": "颜色设置的优先级是什么?",\r "answers": [\r "A. 按构件类型设置",\r "B. 按楼层设置",\r "C. 按自定义属性设置"\r ]\r }\r ]\r \`\`\`\r \r **提问原则**:\r - 每个问题必须针对一个明确的决策点\r - 答案选项应该互斥且覆盖主要场景\r - 问题数量控制在3个以内,优先询问最关键的问题\r - 问题描述清晰、具体,避免模糊表述\r - 不要强行提问,尽量减少或不提问题\r ### 阶段三:步骤规划\r \r 当需求清晰后,你需要将用户意图拆解为一系列可执行的步骤。\r \r **输出格式**:\r \`\`\`\r ##steps## \r json内容\r \r \`\`\`\r \r **JSON格式规范**:\r \`\`\`json\r [\r {\r "id": 0,\r "content": "获取所有桩基模型",\r "description": "通过modelTree模块遍历模型树,筛选出类型为'桩基'的所有构件,返回构件ID数组和构件对象数组",\r "output": "{\\"modelIds\\": [\\"id1\\", \\"id2\\", ...], \\"models\\": [modelObject1, modelObject2, ...]}",\r "dependencies": [],\r "apiModules": ["modelTree", "dataModule"]\r },\r {\r "id": 1,\r "content": "设置桩基模型颜色为红色",\r "description": "使用modelMapperBatch模块的批量设置方法,将上一步获取的所有桩基模型的颜色属性设置为红色(RGB: 255, 0, 0)",\r "output": "{\\"success\\": true, \\"count\\": 10, \\"failedIds\\": []}",\r "dependencies": [0],\r "apiModules": ["modelMapperBatch"]\r }\r ]\r \`\`\`\r \r **字段说明**:\r - \`id\`: 步骤唯一标识符,从0开始递增\r - \`content\`: 步骤的简短描述(一句话概括)\r - \`description\`: 步骤的详细功能说明,包括:\r - 具体要做什么\r - 使用哪些API模块\r - 如何处理数据\r - 可能的边界情况\r - \`output\`: 步骤输出的数据格式说明(JSON Schema格式),用于:\r - 指导代码生成模块返回正确的数据结构\r - 确保步骤间的数据传递正确\r - \`dependencies\`: 依赖的步骤ID数组,表示此步骤需要等待哪些步骤完成\r - \`apiModules\`: 此步骤涉及到的BIM引擎模块名称数组(如:modelTree, cameraModule, measure等)\r \r **步骤规划原则**:\r 1. **原子化**:每个步骤应该只完成一个明确的功能点\r 2. **可执行**:每个步骤都应该能够独立生成可执行的代码\r 3. **依赖清晰**:明确标注步骤间的依赖关系,确保执行顺序正确\r 4. **数据流转**:每个步骤的输出格式要明确,便于后续步骤使用\r 5. **模块化**:合理利用BIM引擎的模块化设计,选择最合适的API\r 6. **错误处理**:在关键步骤中考虑异常情况的处理\r \r ## 硬性要求\r \r ### 1. 输出格式规范\r - **必须严格遵循**上述JSON格式,字段名称和类型不能改变\r - JSON必须是有效的、可解析的格式\r - 步骤ID必须连续且从0开始\r - 依赖关系必须正确,不能出现循环依赖\r \r ### 2. 需求理解要求\r - **深度理解**:不能停留在表面理解,要理解用户的真实意图和业务场景\r - **上下文感知**:结合BIM引擎的特性,理解每个需求在BIM场景下的实际意义\r - **技术可行性**:确保规划的步骤在BIM引擎API能力范围内\r \r ### 3. 步骤质量要求\r - **完整性**:步骤应该覆盖用户需求的所有方面,不能遗漏关键环节\r - **准确性**:步骤描述要准确,不能有歧义或错误\r - **可执行性**:每个步骤都应该能够生成可执行的代码\r - **效率性**:优先选择高效的API组合,避免不必要的中间步骤\r \r ### 4. 错误预防\r - 检查步骤间的数据格式是否匹配\r - 确保依赖关系正确,避免执行顺序错误\r - 验证API模块名称是否正确\r - 考虑边界情况和异常处理\r \r ### 5. 代码生成友好\r - 步骤描述要足够详细,让代码生成模块能够准确理解意图\r - 输出格式说明要具体,使用JSON Schema或示例数据\r - 明确标注使用的API模块,便于代码生成时快速定位\r \r ## 最佳实践\r \r 1. **先理解后规划**:充分理解需求后再开始规划步骤,避免返工\r 2. **模块优先**:优先使用BIM引擎提供的功能模块,而不是底层API\r 3. **数据驱动**:明确每个步骤的输入输出,确保数据流清晰\r 4. **可扩展性**:考虑未来可能的扩展需求,设计灵活的步骤结构\r 5. **用户友好**:步骤描述要清晰易懂,便于用户理解整个执行流程\r \r \r ''`},Symbol.toStringTag,{value:"Module"})),H9=Object.freeze(Object.defineProperty({__proto__:null,default:`# BIM引擎AI助手 - 代码生成专家\r \r ## 角色定位\r \r 你是一位资深的**BIM引擎代码生成专家**,具备以下核心能力:\r \r 1. **BIM引擎API精通**:深度掌握BIM引擎的所有模块API、方法签名、参数类型和返回值\r 2. **代码生成能力**:能够根据步骤描述,生成高质量、可执行、符合规范的JavaScript代码\r 3. **上下文理解**:能够理解步骤间的数据流转,正确处理前序步骤的输出结果\r 4. **错误处理能力**:具备完善的异常处理和边界情况处理能力\r 5. **代码质量意识**:生成的代码应该具备良好的可读性、可维护性和性能\r \r 你的职责是根据步骤规划模块提供的步骤描述,生成可直接在BIM引擎环境中执行的JavaScript代码片段。\r \r ## 工作流程\r \r ### 阶段一:理解步骤要求\r \r 当接收到步骤执行请求时,你需要:\r \r 1. **解析步骤信息**:\r - 理解步骤的\`content\`(简短描述)和\`description\`(详细说明)\r - 识别步骤涉及到的BIM引擎模块(\`apiModules\`字段)\r - 理解步骤的依赖关系(\`dependencies\`字段)\r - 明确步骤的预期输出格式(\`output\`字段)\r \r 2. **分析上下文数据**:\r - 如果有前序步骤的输出结果,分析其数据结构\r - 理解当前步骤需要使用的输入数据\r - 验证数据格式是否匹配步骤要求\r \r 3. **确定实现方案**:\r - 根据步骤描述,选择最合适的BIM引擎API\r - 设计数据转换和处理逻辑\r - 规划错误处理策略\r \r ### 阶段二:生成代码\r \r 根据步骤要求生成可执行的JavaScript代码。\r \r **输出格式**:\r \`\`\`\r ##code##\r [可执行的JavaScript代码]\r \`\`\`\r \r **代码生成规范**:\r \r 1. **代码结构**:\r - 代码必须是一个完整的、可执行的JavaScript代码片段\r - 可以是函数、立即执行函数(IIFE)或代码块\r - 代码应该能够直接运行,不需要额外的包装\r \r 2. **引擎实例访问**:\r - 假设BIM引擎实例通过变量\`engine\`访问(全局作用域)\r - 通过\`engine.moduleName\`访问各个功能模块\r - 例如:\`engine.modelTree\`、\`engine.cameraModule\`、\`engine.measure\`等\r \r 3. **数据输入处理**:\r - 如果步骤有依赖,使用前序步骤的输出数据\r - 假设前序步骤的输出数据存储在变量\`previousStepOutput\`中(如果是第一步,则为\`null\`)\r - 需要根据\`output\`字段的格式说明,正确解析和使用输入数据\r \r 4. **API调用规范**:\r - 严格按照BIM引擎API文档使用API\r - 参数类型和数量必须正确\r - 处理API的返回值和可能的异常\r \r 5. **数据输出规范**:\r - 代码执行后,必须返回符合步骤\`output\`字段要求的数据格式\r - 使用\`return\`语句返回结果\r - 返回的数据必须是可序列化的(JSON格式)\r \r 6. **错误处理**:\r - 必须包含完善的错误处理逻辑\r - 使用try-catch捕获可能的异常\r - 对于关键操作,添加参数验证\r - 错误信息要清晰,便于调试\r \r 7. **代码质量要求**:\r - 代码要有清晰的注释,说明关键逻辑\r - 变量命名要有意义,符合JavaScript命名规范\r - 避免使用过于复杂的嵌套结构\r - 优先使用可读性高的写法,而不是过于"高级"的技巧\r \r ## 硬性要求\r \r ### 1. 代码格式要求\r - **单一代码块**:输出必须且只能包含一个JavaScript代码片段\r - **可执行性**:代码必须能够直接执行,不需要额外的依赖或配置\r - **完整性**:代码必须完整,不能有语法错误或未定义的变量\r \r ### 2. 数据格式要求\r - **输入解析**:正确解析和使用前序步骤的输出数据\r - **输出格式**:严格按照步骤\`output\`字段的格式要求返回数据\r - **类型安全**:确保数据类型正确,必要时进行类型转换\r \r ### 3. API使用要求\r - **准确性**:API调用必须准确,参数必须正确\r - **模块识别**:正确识别和使用BIM引擎的各个模块\r - **方法调用**:使用正确的方法名和参数签名\r \r ### 4. 错误处理要求\r - **异常捕获**:所有可能抛出异常的操作都要有try-catch保护\r - **参数验证**:对关键参数进行验证,避免无效输入\r - **错误信息**:错误信息要清晰,包含足够的上下文信息\r - **优雅降级**:在可能的情况下,提供降级方案\r \r ### 5. 代码质量要求\r - **可读性**:代码结构清晰,逻辑易懂\r - **注释完整**:关键逻辑要有注释说明\r - **命名规范**:变量和函数命名要有意义\r - **性能考虑**:避免不必要的循环和计算\r \r ## 代码生成示例\r \r ### 示例1:获取模型数据\r \r **步骤描述**:\r \`\`\`json\r {\r "id": 0,\r "content": "获取所有桩基模型",\r "description": "通过modelTree模块遍历模型树,筛选出类型为'桩基'的所有构件",\r "output": "{\\"modelIds\\": [\\"id1\\", \\"id2\\"], \\"models\\": [modelObject1, modelObject2]}",\r "dependencies": [],\r "apiModules": ["modelTree"]\r }\r \`\`\`\r \r **生成代码**:\r \`\`\`javascript\r // 获取所有桩基模型\r try {\r // 获取模型树模块\r const modelTree = engine.modelTree;\r if (!modelTree) {\r throw new Error('模型树模块未初始化');\r }\r \r // 获取所有模型\r const allModels = modelTree.getAllModels();\r if (!allModels || allModels.length === 0) {\r return {\r modelIds: [],\r models: []\r };\r }\r \r // 筛选桩基模型\r const pileModels = [];\r const pileModelIds = [];\r \r for (let i = 0; i < allModels.length; i++) {\r const model = allModels[i];\r // 根据模型属性判断是否为桩基\r const modelType = model.getProperty('类型') || model.getProperty('category');\r if (modelType && (modelType.includes('桩基') || modelType.includes('Pile'))) {\r pileModels.push(model);\r pileModelIds.push(model.id || model.uuid);\r }\r }\r \r // 返回结果\r return {\r modelIds: pileModelIds,\r models: pileModels\r };\r } catch (error) {\r console.error('获取桩基模型失败:', error);\r return {\r modelIds: [],\r models: [],\r error: error.message\r };\r }\r \`\`\`\r \r ### 示例2:使用前序步骤的输出\r \r **步骤描述**:\r \`\`\`json\r {\r "id": 1,\r "content": "设置桩基模型颜色为红色",\r "description": "使用modelMapperBatch模块批量设置上一步获取的桩基模型颜色",\r "output": "{\\"success\\": true, \\"count\\": 10}",\r "dependencies": [0],\r "apiModules": ["modelMapperBatch"]\r }\r \`\`\`\r \r **生成代码**:\r \`\`\`javascript\r // 设置桩基模型颜色为红色\r try {\r // 获取前序步骤的输出数据\r if (!previousStepOutput || !previousStepOutput.modelIds) {\r throw new Error('前序步骤输出数据无效,缺少modelIds字段');\r }\r \r const modelIds = previousStepOutput.modelIds;\r if (modelIds.length === 0) {\r return {\r success: true,\r count: 0,\r message: '没有需要设置的模型'\r };\r }\r \r // 获取批量映射模块\r const modelMapperBatch = engine.modelMapperBatch;\r if (!modelMapperBatch) {\r throw new Error('批量映射模块未初始化');\r }\r \r // 设置颜色为红色 (RGB: 255, 0, 0)\r const redColor = { r: 255, g: 0, b: 0 };\r \r // 批量设置模型颜色\r const result = modelMapperBatch.setModelColor(modelIds, redColor);\r \r return {\r success: result.success !== false,\r count: result.count || modelIds.length,\r failedIds: result.failedIds || []\r };\r } catch (error) {\r console.error('设置模型颜色失败:', error);\r return {\r success: false,\r count: 0,\r error: error.message\r };\r }\r \`\`\`\r \r ## 最佳实践\r \r 1. **充分理解步骤**:仔细阅读步骤描述,确保理解每个细节\r 2. **查阅API文档**:不确定的API用法,参考BIM引擎API文档\r 3. **数据验证优先**:在处理数据前,先验证数据的有效性\r 4. **错误处理完善**:考虑各种可能的异常情况\r 5. **代码可读性**:优先保证代码的可读性,而不是追求"高级"写法\r 6. **注释清晰**:关键逻辑要有注释,但不要过度注释\r 7. **性能考虑**:对于大量数据的处理,考虑性能优化\r 8. **测试友好**:生成的代码应该便于测试和调试 `},Symbol.toStringTag,{value:"Module"})),V9=Object.freeze(Object.defineProperty({__proto__:null,default:`# BIM Engine SDK API 文档 本文档为 BIM Engine SDK 的完整 API 参考,适合大模型阅读和理解引擎的功能结构。 ## 目录 1. [核心引擎类](#1-核心引擎类) 2. [基础模块](#2-基础模块) 3. [功能管理器](#3-功能管理器) 4. [状态管理](#4-状态管理) --- ## 1. 核心引擎类 ### EngineKernelV2 引擎核心组件,负责整合和管理所有模块。 **文件路径**: \`src/core/v2/EngineKernel.ts\` #### 构造函数 \`\`\`typescript constructor(options: any) \`\`\` **参数**: - \`options.containerId\`: string - 容器元素的 ID **功能**: - 初始化所有基础模块(场景、相机、渲染器、控制器等) - 初始化所有功能管理器(测量、剖切、模型树等) - 设置渲染循环 - 添加性能监视器 #### 公共属性 \`\`\`typescript // 基础对象 public scene: THREE.Scene | null // 三维场景 public camera: THREE.Camera | null // 当前使用的相机 public renderer: THREE.WebGLRenderer | null // 渲染器 public controls: any // 控制器(轨道控制或第一人称) // 基础模块 public sceneModule: SceneModule // 场景模块 public cameraModule: CameraModule // 相机模块 public deviceModule: DeviceModule // 设备模块 public renderModule: RenderModule // 渲染模块 public controlModule: ControlModule // 控制模块 public composerModule: ComposerModule // 合成器模块 public loaderModule: LoaderModule // 加载器模块 public lightModule: LightModule // 光照模块 public interactionModule: InteractionModule // 交互模块 public modelToolModule: ModelToolModule // 模型工具模块 // 功能管理器 public viewCube: ViewCube // 视图立方体 public rangeScale: RangeScale // 范围缩放 public setting: Setting // 设置 public measure: Measure // 测量 public clipping: Clipping // 剖切 public modelTree: ModelTree // 模型树 public engineInfo: EngineInfo // 引擎信息统计 public modelProperties: ModelProperties // 模型属性 public modelMapperBatch: ModelMapperBatch // 模型批量映射 public modelEdge: ModelEdge // 模型边线 // 状态管理 public engineStatus: EngineStatus // 引擎状态 public events: EventModule // 事件模块 // 业务数据 public models: any[] // 已加载的模型数组 public reactBoundingClientRect: { left: number; top: number } // 容器的边界矩形 \`\`\` #### 公共方法 ##### pauseRendering() \`\`\`typescript public pauseRendering(): void \`\`\` **功能**: 暂停渲染循环 - 停止动画帧请求 - 禁用控制器 - 用于性能优化或后台运行 ##### resumeRendering() \`\`\`typescript public resumeRendering(): void \`\`\` **功能**: 恢复渲染循环 - 重新启动动画帧请求 - 恢复控制器状态 ##### isRenderingPausedState() \`\`\`typescript public isRenderingPausedState(): boolean \`\`\` **功能**: 检查渲染是否暂停 **返回值**: boolean - true 表示已暂停 ##### dispose() \`\`\`typescript public dispose(): void \`\`\` **功能**: 销毁引擎,释放所有资源 - 停止渲染循环 - 清理所有模块 - 释放几何体、材质、纹理 - 移除 DOM 元素 - 清理事件监听器 **注意**: 调用此方法后引擎不可再使用 --- ## 2. 基础模块 ### 2.1 SceneModule - 场景模块 **文件路径**: \`src/core/v2/modules/sceneModule.ts\` #### 公共属性 \`\`\`typescript public scene: THREE.Scene | null // 三维场景对象 \`\`\` **功能**: - 创建并管理 THREE.Scene - 初始化边线组(groupEdge)用于存储模型边线 --- ### 2.2 CameraModule - 相机模块 **文件路径**: \`src/core/v2/modules/cameraModule.ts\` #### 公共属性 \`\`\`typescript public perspectiveCamera: THREE.PerspectiveCamera // 透视相机 public orthographicCamera: THREE.OrthographicCamera // 正交相机 \`\`\` #### 公共方法 ##### switchCurrentCamera() \`\`\`typescript public switchCurrentCamera(): void \`\`\` **功能**: 切换当前相机类型(透视 ↔ 正交) ##### switchToPerspectiveCamera() \`\`\`typescript public switchToPerspectiveCamera(): void \`\`\` **功能**: 切换到透视相机 - 保持当前位置和目标点 - 更新控制器 - 重新初始化合成器 ##### switchToOrthographicCamera() \`\`\`typescript public switchToOrthographicCamera(): void \`\`\` **功能**: 切换到正交相机 - 保持当前位置和目标点 - 更新控制器 - 重新初始化合成器 ##### getCameraType() \`\`\`typescript public getCameraType(): CameraType \`\`\` **功能**: 获取当前相机类型 **返回值**: - \`CameraType.PERSPECTIVE\` - 透视相机 - \`CameraType.ORTHOGRAPHIC\` - 正交相机 ##### getCameraPose() \`\`\`typescript public getCameraPose(): ICameraPose \`\`\` **功能**: 获取当前相机姿态(位置、旋转、目标点、缩放等) **返回值**: ICameraPose 对象 \`\`\`typescript interface ICameraPose { type: CameraType; position: { x: number; y: number; z: number }; rotation: { x: number; y: number; z: number }; quaternion: { x: number; y: number; z: number; w: number }; target?: { x: number; y: number; z: number }; zoom?: number; } \`\`\` ##### restoreCameraPose() \`\`\`typescript public restoreCameraPose(pose: ICameraPose): void \`\`\` **功能**: 通过相机姿态还原相机位置 - 自动切换相机类型 - 恢复位置、旋转、目标点 - 恢复正交相机的缩放值 **参数**: - \`pose\`: ICameraPose - 相机姿态对象 --- ### 2.3 DeviceModule - 设备模块 **文件路径**: \`src/core/v2/modules/deviceModule.ts\` #### 公共属性 \`\`\`typescript public deviceType: string // 设备类型(默认 'PC') \`\`\` #### 公共方法 ##### getDeviceType() \`\`\`typescript public getDeviceType(): string \`\`\` **功能**: 获取设备类型 **返回值**: 'PC' 或其他设备标识 ##### getContainerSize() \`\`\`typescript public getContainerSize(): { width: number; height: number } \`\`\` **功能**: 获取容器尺寸 **返回值**: 容器的宽度和高度 --- ### 2.4 RenderModule - 渲染模块 **文件路径**: \`src/core/v2/modules/renderModule.ts\` #### 公共属性 \`\`\`typescript public renderer: THREE.WebGLRenderer | null // WebGL 渲染器 \`\`\` #### 公共方法 ##### createRenderer() \`\`\`typescript public createRenderer(): THREE.WebGLRenderer \`\`\` **功能**: 创建并配置 WebGL 渲染器 - 启用抗锯齿 - 启用阴影映射(PCFSoftShadowMap) - 启用本地裁剪(用于剖切平面) - 配置色彩空间和色调映射 **返回值**: 配置好的渲染器实例 ##### disposeRenderer() \`\`\`typescript public disposeRenderer(): void \`\`\` **功能**: 释放渲染器资源 --- ### 2.5 ControlModule - 控制模块 **文件路径**: \`src/core/v2/modules/controlModule.ts\` #### 公共属性 \`\`\`typescript public orbitControls: any // 轨道控制器 public firstPersonControls: any // 第一人称控制器 public isActive: boolean // 控制器是否激活 \`\`\` #### 公共方法 ##### init() \`\`\`typescript public init(): void \`\`\` **功能**: 初始化控制器 - 创建轨道控制器和第一人称控制器 - 创建旋转中心指示器 UI ##### active() \`\`\`typescript public active(): void \`\`\` **功能**: 激活控制器 ##### disActive() \`\`\`typescript public disActive(): void \`\`\` **功能**: 禁用控制器 ##### switchFirstPersonMode() \`\`\`typescript public switchFirstPersonMode(): void \`\`\` **功能**: 切换到第一人称漫游模式 - 禁用轨道控制器 - 启用第一人称控制器 ##### switchDefaultMode() \`\`\`typescript public switchDefaultMode(): void \`\`\` **功能**: 切换到默认模式(轨道控制) - 禁用第一人称控制器 - 启用轨道控制器 ##### update() \`\`\`typescript public update(): void \`\`\` **功能**: 更新控制器状态 - 更新旋转中心指示器位置 - 在渲染循环中调用 --- ### 2.6 ComposerModule - 合成器模块 **文件路径**: \`src/core/v2/modules/composerModule.ts\` #### 公共属性 \`\`\`typescript public composer: any // 效果合成器 \`\`\` #### 公共方法 ##### init() \`\`\`typescript public init(): void \`\`\` **功能**: 初始化后处理管线 - RenderPass - 基础渲染 - GTAOPass - 环境光遮蔽(默认禁用) - UnrealBloomPass - 辉光效果(默认禁用) - SaturationPass - 饱和度和对比度调整 - OutputPass - 色调映射和颜色校正 - FXAAPass - 抗锯齿 ##### resize() \`\`\`typescript public resize(): void \`\`\` **功能**: 调整合成器大小 - 更新所有 pass 的分辨率 - 更新 FXAA 的分辨率参数 --- ### 2.7 LoaderModule - 加载器模块 **文件路径**: \`src/core/v2/modules/loaderModule.ts\` #### 公共方法 ##### loadModels() \`\`\`typescript async loadModels(urls: string[], options?: LoadModelOptions): Promise \`\`\` **功能**: 加载多个模型 - 支持轻量化模型格式 - 支持 GLTF/GLB 格式 - 异步加载 **参数**: - \`urls\`: string[] - 模型 URL 数组 - \`options\`: LoadModelOptions - 加载选项(可选) --- ### 2.8 EventModule - 事件模块 **文件路径**: \`src/core/v2/modules/eventModule.ts\` #### 公共方法 ##### on() \`\`\`typescript on(event: EventType, callback: (data: T) => void): void \`\`\` **功能**: 注册事件监听器 **参数**: - \`event\`: EventType - 事件类型 - \`callback\`: 回调函数 ##### off() \`\`\`typescript off(event: EventType, callback: (data: T) => void): void \`\`\` **功能**: 移除事件监听器 **参数**: - \`event\`: EventType - 事件类型 - \`callback\`: 要移除的回调函数 ##### trigger() \`\`\`typescript trigger(event: EventType, data?: any): void \`\`\` **功能**: 触发事件 **参数**: - \`event\`: EventType - 事件类型 - \`data\`: 传递给监听器的数据 **常用事件类型**: - \`EventType.Click\` - 点击事件 - \`EventType.ViewportResize\` - 视口大小改变 - \`EventType.EngineFree\` - 引擎空闲 - \`EventType.EngineBusy\` - 引擎繁忙 --- ### 2.9 LightModule - 光照模块 **文件路径**: \`src/core/v2/modules/lightModule.ts\` #### 公共方法 ##### init() \`\`\`typescript public init(): void \`\`\` **功能**: 初始化场景基本光照 - 添加定向光(DirectionalLight) - 强度: 2 - 位置: (10, 20, 10) - 阴影贴图: 4096x4096(高质量) - 添加环境光(AmbientLight) - 强度: 1 --- ### 2.10 InteractionModule - 交互模块 **文件路径**: \`src/core/v2/modules/interactionModule.ts\` #### 公共方法 ##### init() \`\`\`typescript public init(): void \`\`\` **功能**: 初始化交互行为处理器 ##### active() \`\`\`typescript public active(): void \`\`\` **功能**: 激活交互功能 ##### disActive() \`\`\`typescript public disActive(): void \`\`\` **功能**: 禁用交互功能 ##### handleMouseClick() \`\`\`typescript public handleMouseClick(event: any): void \`\`\` **功能**: 处理鼠标单击事件 - 射线检测点击的模型 - 高亮选中的模型 - 设置旋转中心 - 支持 Ctrl 多选 ##### handleMouseDoubleClick() \`\`\`typescript public handleMouseDoubleClick(event: any): void \`\`\` **功能**: 处理鼠标双击事件 - 双击模型后缩放到该模型 - 计算模型包围盒并调整相机视角 ##### handleMouseClickInstance() \`\`\`typescript public handleMouseClickInstance(raycaster: any): any \`\`\` **功能**: 判断点击实例化网格节点 **参数**: - \`raycaster\`: 射线投射器 **返回值**: 相交结果数组 --- ### 2.11 ModelToolModule - 模型工具模块 **文件路径**: \`src/core/v2/modules/modelToolModule.ts\` #### 公共方法 ##### highlightModel() \`\`\`typescript public highlightModel(models: any): void \`\`\` **功能**: 设置模型高亮显示 **参数**: - \`models\`: 模型数组,格式: \`[{url: string, ids: string[]}]\` ##### unhighlightModel() \`\`\`typescript public unhighlightModel(models: any): void \`\`\` **功能**: 取消模型高亮 **参数**: - \`models\`: 模型数组 ##### unhighlightAllModels() \`\`\`typescript public unhighlightAllModels(): void \`\`\` **功能**: 取消所有模型高亮 ##### hideModel() \`\`\`typescript public hideModel(models: any): void \`\`\` **功能**: 隐藏模型 **参数**: - \`models\`: 模型数组,格式: \`[{url: string, ids: string[]}]\` ##### showModel() \`\`\`typescript public showModel(models: any): void \`\`\` **功能**: 显示模型 **参数**: - \`models\`: 模型数组 ##### isolateModel() \`\`\`typescript public isolateModel(models: any): void \`\`\` **功能**: 隔离模型(只显示指定模型,隐藏其他) **参数**: - \`models\`: 要显示的模型数组 ##### showAllModels() \`\`\`typescript public showAllModels(): void \`\`\` **功能**: 显示所有模型 ##### getModelsBox() \`\`\`typescript public getModelsBox(models: any): THREE.Box3 \`\`\` **功能**: 获取模型的包围盒 **参数**: - \`models\`: 模型数组 **返回值**: THREE.Box3 包围盒对象 --- ## 3. 功能管理器 ### 3.1 ViewCube - 视图立方体 **文件路径**: \`src/core/v2/managers/viewCube/index.ts\` #### 公共属性 \`\`\`typescript public cubeTool: any // 视图立方体工具 \`\`\` #### 公共方法 ##### init() \`\`\`typescript public init(): void \`\`\` **功能**: 初始化视图立方体 - 创建 3D 小立方体辅助视图 - 支持六个面和边角视图切换 ##### CameraGoHome() \`\`\`typescript public CameraGoHome(): void \`\`\` **功能**: 相机回归正位(默认视角) ##### zoomToModel() \`\`\`typescript public zoomToModel(box: THREE.Box3): void \`\`\` **功能**: 缩放到指定模型包围盒 **参数**: - \`box\`: THREE.Box3 - 目标包围盒 --- ### 3.2 RangeScale - 范围缩放工具 **文件路径**: \`src/core/v2/managers/rangeScale/index.ts\` #### 公共方法 ##### init() \`\`\`typescript public init(): void \`\`\` **功能**: 初始化范围缩放工具 - 创建绘制框 UI 元素 - 初始化坐标转换工具 ##### active() \`\`\`typescript public active(): void \`\`\` **功能**: 激活范围缩放工具 - 禁用控制器 - 启用框选功能 - 鼠标变为十字光标 **使用方式**: 1. 激活工具 2. 鼠标拖拽绘制矩形区域 3. 松开鼠标自动缩放到该区域 4. 按 ESC 键退出 ##### disActive() \`\`\`typescript public disActive(): void \`\`\` **功能**: 停用范围缩放工具 - 恢复控制器 - 移除事件监听 --- ### 3.3 Setting - 设置管理器 **文件路径**: \`src/core/v2/managers/setting/index.ts\` #### 公共方法 ##### setStatsVisible() \`\`\`typescript public setStatsVisible(visible: boolean): void \`\`\` **功能**: 显示/隐藏性能监视器 **参数**: - \`visible\`: true 显示,false 隐藏 ##### setAmbientLightIntensity() \`\`\`typescript public setAmbientLightIntensity(intensity: number): void \`\`\` **功能**: 设置环境光照强度 **参数**: - \`intensity\`: 光照强度,范围 0-5 ##### setAmbientLightColor() \`\`\`typescript public setAmbientLightColor(color: number | string): void \`\`\` **功能**: 设置环境光照颜色 **参数**: - \`color\`: 颜色(0xffffff 或 '#ffffff') ##### setDirectionalLightIntensity() \`\`\`typescript public setDirectionalLightIntensity(intensity: number): void \`\`\` **功能**: 设置定向光源强度 **参数**: - \`intensity\`: 光照强度,范围 0-5 ##### setDirectionalLightColor() \`\`\`typescript public setDirectionalLightColor(color: number | string): void \`\`\` **功能**: 设置定向光源颜色 **参数**: - \`color\`: 颜色 ##### setShadowQuality() \`\`\`typescript public setShadowQuality(quality: 'low' | 'medium' | 'high' | 'ultra'): void \`\`\` **功能**: 设置阴影精细度 **参数**: - \`quality\`: 质量等级 - 'low': 1024 - 'medium': 2048 - 'high': 4096 - 'ultra': 8192 ##### setDirectionalLightShadow() \`\`\`typescript public setDirectionalLightShadow(enabled: boolean): void \`\`\` **功能**: 开启/关闭定向光阴影 **参数**: - \`enabled\`: true 开启,false 关闭 ##### setGTAOEnabled() \`\`\`typescript public setGTAOEnabled(enabled: boolean): void \`\`\` **功能**: 开启/关闭 GTAO 环境光遮蔽 **参数**: - \`enabled\`: true 开启,false 关闭 ##### setSceneSaturation() \`\`\`typescript public setSceneSaturation(saturation: number): void \`\`\` **功能**: 设置场景饱和度 **参数**: - \`saturation\`: 饱和度值,1.0 为正常,推荐范围 0.5-2.0 ##### setSceneContrast() \`\`\`typescript public setSceneContrast(contrast: number): void \`\`\` **功能**: 设置场景对比度 **参数**: - \`contrast\`: 对比度值,1.0 为正常,推荐范围 0.5-2.0 ##### setGroundEnabled() \`\`\`typescript public setGroundEnabled(enabled: boolean, options?: { size?: number; color?: number | string; opacity?: number; }): void \`\`\` **功能**: 开启/关闭地面 **参数**: - \`enabled\`: true 开启,false 关闭 - \`options\`: 地面配置选项 - \`size\`: 地面大小(默认 100) - \`color\`: 地面颜色(默认 0x808080) - \`opacity\`: 透明度(默认 0.3) ##### setHDRBackground() \`\`\`typescript public setHDRBackground(hdrTexture: THREE.Texture | null): void \`\`\` **功能**: 设置 HDR 背景 **参数**: - \`hdrTexture\`: HDR 环境贴图,null 则移除 --- ### 3.4 Measure - 测量工具 **文件路径**: \`src/core/v2/managers/measure/index.ts\` #### 公共方法 ##### active() \`\`\`typescript public active(): void \`\`\` **功能**: 激活测量工具 ##### disActive() \`\`\`typescript public disActive(): void \`\`\` **功能**: 停用测量工具 - 清除所有测量 - 恢复点选功能 ##### clearAllPoints() \`\`\`typescript public clearAllPoints(): void \`\`\` **功能**: 清空所有测量点 ##### clearAll() \`\`\`typescript public clearAll(): void \`\`\` **功能**: 清除所有测量标注 ##### update() \`\`\`typescript update(): void \`\`\` **功能**: 更新测量标注 - 在渲染循环中调用 - 更新屏幕坐标 **测量类型**: - 距离测量(DistanceMeasure) - 净高测量(ClearHeightMeasure) - 净距测量(ClearDistanceMeasure) - 标高测量(ElevationMeasure) - 点测量(PointMeasure) - 角度测量(AngleMeasure) - 面积测量(AreaMeasure) - 坡度测量(SlopeMeasure) --- ### 3.5 Clipping - 剖切管理器 **文件路径**: \`src/core/v2/managers/clipping/index.ts\` #### 公共属性 \`\`\`typescript public sectionPlaneX: any // X 轴剖切平面 public sectionPlaneY: any // Y 轴剖切平面 public sectionPlaneZ: any // Z 轴剖切平面 public sectionBox: any // 剖切盒 \`\`\` #### 公共方法 ##### init() \`\`\`typescript public init(): void \`\`\` **功能**: 初始化剖切管理器 - 创建 6 个剖切平面(前、后、左、右、顶、底) - 初始化 X/Y/Z 轴剖切工具 - 初始化剖切盒工具 ##### disActive() \`\`\`typescript public disActive(): void \`\`\` **功能**: 停用所有剖切工具 --- ### 3.6 ModelTree - 模型树 **文件路径**: \`src/core/v2/managers/modelTree/index.ts\` #### 公共方法 ##### getTreeData() \`\`\`typescript public getTreeData(): any[] \`\`\` **功能**: 获取模型树数据 **返回值**: 模型树数组 \`\`\`typescript [{ name: string, // 模型名称 children: any[] // 模型层级树 }] \`\`\` --- ### 3.7 EngineInfo - 引擎信息统计 **文件路径**: \`src/core/v2/managers/engineInfo/index.ts\` #### 公共方法 ##### getEngineInfo() \`\`\`typescript public getEngineInfo(): { totalVertices: number; totalTriangles: number; meshCount: number; } \`\`\` **功能**: 获取引擎统计信息 - 统计所有网格的顶点数 - 统计所有网格的三角面数 - 统计网格数量 **返回值**: - \`totalVertices\`: 总顶点数 - \`totalTriangles\`: 总三角面数 - \`meshCount\`: 网格数量 --- ### 3.8 ModelProperties - 模型属性 **文件路径**: \`src/core/v2/managers/modelProperties/index.ts\` #### 公共方法 ##### getModelProperties() \`\`\`typescript public getModelProperties(url: string, id: string, callback: (properties: any) => void): void \`\`\` **功能**: 查询构件属性 - 异步加载属性数据(如果未加载) - 从压缩的 JSON 中解析属性 **参数**: - \`url\`: 模型 URL - \`id\`: 构件 ID - \`callback\`: 回调函数,接收属性对象 **返回值格式**: \`\`\`typescript { properties: [{ name: string, // 分类名称 children: [{ name: string, // 属性名 value: any // 属性值 }] }], materials: [] } \`\`\` --- ### 3.9 ModelMapperBatch - 模型批量映射 **文件路径**: \`src/core/v2/managers/modelMapperBatch/index.ts\` #### 公共方法 ##### getModelTypes() \`\`\`typescript public getModelTypes(): any[] \`\`\` **功能**: 获取模型中所有的构件类型 ##### getModelMajors() \`\`\`typescript public getModelMajors(): any[] \`\`\` **功能**: 获取模型中所有的专业 ##### getModelLevels() \`\`\`typescript public getModelLevels(): any[] \`\`\` **功能**: 获取模型中所有的楼层 ##### getModelMapper() \`\`\`typescript public getModelMapper(url: string, id: number): any \`\`\` **功能**: 获取指定构件的映射信息 **参数**: - \`url\`: 模型 URL - \`id\`: 构件 ID **返回值**: Mapper 对象(包含类型、专业、楼层等信息) ##### getModelSWithType() \`\`\`typescript public getModelSWithType(type: string, callback: any): any[] \`\`\` **功能**: 获取同类型的所有构件 **参数**: - \`type\`: 构件类型名称 - \`callback\`: 回调函数 **返回值**: \`[{url: string, ids: number[]}]\` ##### getModelSWithLevel() \`\`\`typescript public getModelSWithLevel(level: string, callback: any): any[] \`\`\` **功能**: 获取同楼层的所有构件 **参数**: - \`level\`: 楼层名称 - \`callback\`: 回调函数 **返回值**: \`[{url: string, ids: number[]}]\` ##### getModelsWithMajor() \`\`\`typescript public getModelsWithMajor(major: string, callback: any): any[] \`\`\` **功能**: 获取同专业的所有构件 **参数**: - \`major\`: 专业名称 - \`callback\`: 回调函数 **返回值**: \`[{url: string, ids: number[]}]\` --- ### 3.10 ModelEdge - 模型边线管理器 **文件路径**: \`src/core/v2/managers/modelEdge/index.ts\` #### 公共方法 ##### active() \`\`\`typescript public active(): void \`\`\` **功能**: 启动边线显示 - 显示所有模型的边线 - 用于技术制图风格渲染 ##### disActive() \`\`\`typescript public disActive(): void \`\`\` **功能**: 关闭边线显示 ##### getModelEdge() \`\`\`typescript public getModelEdge(url: string, id: Number): any \`\`\` **功能**: 获取指定模型的边线数据 **参数**: - \`url\`: 模型 URL - \`id\`: 构件 ID **返回值**: 边线数据 \`[startIndex, endIndex, points]\` ##### hideModelEdge() \`\`\`typescript public hideModelEdge(url: string, id: Number): void \`\`\` **功能**: 隐藏指定构件的边线 **参数**: - \`url\`: 模型 URL - \`id\`: 构件 ID ##### showModelEdge() \`\`\`typescript public showModelEdge(url: string, id: Number): void \`\`\` **功能**: 显示指定构件的边线 **参数**: - \`url\`: 模型 URL - \`id\`: 构件 ID --- ## 4. 状态管理 ### 4.1 EngineStatus - 引擎状态 **文件路径**: \`src/core/v2/status/engineStatus.ts\` #### 公共属性 \`\`\`typescript public isFree: boolean // 引擎是否空闲 public highlightModels: any[] // 高亮的模型数组 public hideModels: any[] // 隐藏的模型数组 public models: any[] // 已加载的模型数组 \`\`\` #### 公共方法 ##### init() \`\`\`typescript public init(): void \`\`\` **功能**: 初始化引擎状态监听 - 监听 \`EventType.EngineFree\` 事件 - 监听 \`EventType.EngineBusy\` 事件 ##### updateFree() \`\`\`typescript public updateFree(status: boolean): void \`\`\` **功能**: 更新引擎空闲状态 **参数**: - \`status\`: true 表示空闲,false 表示繁忙 ##### closeAllFunction() \`\`\`typescript public closeAllFunction(): void \`\`\` **功能**: 关闭所有功能 --- ### 4.2 HandelBehaved - 行为处理器 **文件路径**: \`src/core/v2/status/handelBehaved.ts\` 这是一个工厂函数,返回行为处理器对象。 #### 公共方法 ##### init() \`\`\`typescript init(self: any, options: any): void \`\`\` **功能**: 初始化行为处理器 **参数**: - \`self\`: 当前激活的行为对象 - \`options\`: 行为配置选项 - \`showCatch\`: boolean - 是否显示捕捉点 ##### active() \`\`\`typescript active(): void \`\`\` **功能**: 开启事务(激活事件监听) - 监听鼠标事件(mousedown, mouseup, mousemove) - 监听键盘事件(keydown, keyup) ##### disActive() \`\`\`typescript disActive(): void \`\`\` **功能**: 关闭事务(禁用事件监听) **支持的键盘事件**: - Delete / Backspace - 删除 - Escape - 取消 - Enter - 确认 - Space - 空格 - Ctrl / Control - 控制键 - Shift - 切换键 - Alt - 辅助键 - Meta / Command - 命令键 **支持的鼠标事件**: - handleMouseDown - 鼠标按下 - handleMouseMove - 鼠标移动 - handleMouseUp - 鼠标弹起 - handleMouseClick - 鼠标单击 - handleMouseDoubleClick - 鼠标双击 **捕捉功能**: - 点捕捉(距离 < 5 像素) - 线捕捉(距离 < 5 像素) - 面捕捉(默认) --- ## 使用示例 ### 初始化引擎 \`\`\`typescript import { EngineKernelV2 } from './src/core/v2/EngineKernel'; const engine = new EngineKernelV2({ containerId: 'canvas-container', antialias: true }); \`\`\` ### 加载模型 \`\`\`typescript await engine.loaderModule.loadModels([ 'https://example.com/model1.light', 'https://example.com/model2.light' ]); \`\`\` ### 高亮模型 \`\`\`typescript engine.modelToolModule.highlightModel([ { url: 'model1.light', ids: ['wall-001', 'wall-002'] } ]); \`\`\` ### 切换相机 \`\`\`typescript // 切换到正交相机 engine.cameraModule.switchToOrthographicCamera(); // 或切换当前相机类型 engine.cameraModule.switchCurrentCamera(); \`\`\` ### 保存和恢复相机姿态 \`\`\`typescript // 保存当前相机姿态 const pose = engine.cameraModule.getCameraPose(); // 恢复相机姿态 engine.cameraModule.restoreCameraPose(pose); \`\`\` ### 设置光照和渲染质量 \`\`\`typescript // 设置环境光强度 engine.setting.setAmbientLightIntensity(1.5); // 设置阴影质量 engine.setting.setShadowQuality('ultra'); // 开启 GTAO engine.setting.setGTAOEnabled(true); // 调整饱和度和对比度 engine.setting.setSceneSaturation(1.3); engine.setting.setSceneContrast(1.1); \`\`\` ### 获取模型属性 \`\`\`typescript engine.modelProperties.getModelProperties('model.light', 'wall-001', (data) => { console.log('属性:', data.properties); }); \`\`\` ### 按类型筛选构件 \`\`\`typescript engine.modelMapperBatch.getModelSWithType('墙', (models) => { // 高亮所有墙体 engine.modelToolModule.highlightModel(models); }); \`\`\` ### 监听事件 \`\`\`typescript // 监听点击事件 engine.events.on(EventType.Click, (hit) => { console.log('点击了:', hit.object.name); }); // 监听视口大小改变 engine.events.on(EventType.ViewportResize, ({ width, height }) => { console.log('视口大小:', width, height); }); \`\`\` ### 暂停和恢复渲染 \`\`\`typescript // 暂停渲染(节省性能) engine.pauseRendering(); // 恢复渲染 engine.resumeRendering(); // 检查渲染状态 if (engine.isRenderingPausedState()) { console.log('渲染已暂停'); } \`\`\` ### 销毁引擎 \`\`\`typescript // 释放所有资源 engine.dispose(); \`\`\` --- ## 总结 BIM Engine SDK 提供了完整的 3D BIM 模型渲染和交互能力,主要特性包括: - **完整的相机系统**: 支持透视和正交相机,可保存和恢复相机姿态 - **强大的模型操作**: 高亮、隐藏、隔离、批量筛选 - **丰富的测量工具**: 距离、净高、净距、标高、角度、面积、坡度 - **灵活的剖切功能**: 支持 X/Y/Z 轴剖切和剖切盒 - **可配置的渲染质量**: 阴影、环境光遮蔽、饱和度、对比度 - **事件驱动架构**: 支持自定义事件监听和触发 - **性能优化**: 支持暂停/恢复渲染,八叉树加速 - **完善的资源管理**: 自动释放几何体、材质、纹理等资源 适用场景: - BIM 模型在线浏览 - 建筑设计审查 - 施工模拟 - 运维管理 - AI 辅助设计 `},Symbol.toStringTag,{value:"Module"}));Is.BimEngine=a9,Is.BimEngine2d=M9,Is.BimEngine720=w9,Is.CusBimEngine=_9,Object.defineProperty(Is,Symbol.toStringTag,{value:"Module"})})); //# sourceMappingURL=iflow-engine.umd.js.map