(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-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: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}.catchPoint{pointer-events:none;fill:#00f;stroke:#fff;stroke-width:1}.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}.measureBack{cursor:pointer;pointer-events:auto;fill:orange;top:-50px;rx:5;ry:5}.measureLabel{position:absolute;fill:#fff;font-size:14px;font-family:Arial,sans-serif;pointer-events:none}.measurePointer{fill:orange}.Hight{stroke:#fff;stroke-width:2}.allow-select{pointer-events:auto}.disallow-select{pointer-events:none}.angle-annotation{position:absolute;pointer-events:auto}.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-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)}')),document.head.appendChild(e)}}catch(i){console.error("vite-plugin-css-injected-by-js",i)}})(); (function(Ns,zr){typeof exports=="object"&&typeof module<"u"?zr(exports):typeof define=="function"&&define.amd?define(["exports"],zr):(Ns=typeof globalThis<"u"?globalThis:Ns||self,zr(Ns.IflowEngine={}))})(this,(function(Ns){"use strict";const zr={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:"剖切盒"},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:"取消"}},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:"设置",renderMode:"渲染模式",modes:{simple:"性能模式",balance:"平衡模式",advanced:"效果模式"}}},Qg={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"},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"}},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",renderMode:"Render Mode",modes:{simple:"Performance",balance:"Balanced",advanced:"Quality"}}};class e0{currentLocale="zh-CN";messages={"zh-CN":zr,"en-US":Qg};listeners=[];constructor(){}getLocale(){return this.currentLocale}setLocale(e){this.currentLocale!==e&&(this.currentLocale=e,this.notifyListeners())}t(e){if(!e)return"";const t=e.split(".");let n=this.messages[this.currentLocale];for(const i of t)if(n&&typeof n=="object"&&i in n)n=n[i];else return e;return n}subscribe(e){return this.listeners.push(e),()=>{this.listeners=this.listeners.filter(t=>t!==e)}}notifyListeners(){this.listeners.forEach(e=>e(this.currentLocale))}}const Yt=new e0,xe=s=>Yt.t(s),sd={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"}}},t0={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 n0{currentTheme=sd;listeners=[];constructor(){}getTheme(){return this.currentTheme}setTheme(e){e==="light"?this.applyTheme(sd):this.applyTheme(t0)}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 ot=new n0;class zl{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(i=>{e[i]&&this.customColors.add(i)}),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=i=>{i.stopPropagation()};["click","dblclick","contextmenu","wheel","mousedown","mouseup","mousemove","touchstart","touchend","touchmove","pointerdown","pointerup","pointermove","pointerenter","pointerleave","pointerover","pointerout"].forEach(i=>{e.addEventListener(i,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 n="20px";switch(e){case"top-left":t.top=n,t.left=n;break;case"top-center":t.top=n,t.left="50%",t.transform="translateX(-50%)";break;case"top-right":t.top=n,t.right=n;break;case"bottom-left":t.bottom=n,t.left=n;break;case"bottom-center":t.bottom=n,t.left="50%",t.transform="translateX(-50%)";break;case"bottom-right":t.bottom=n,t.right=n;break;case"left-center":t.left=n,t.top="50%",t.transform="translateY(-50%)";break;case"right-center":t.right=n,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(n=>{const i=n.style;this.options.iconColor&&i.setProperty("--bim-icon-color",this.options.iconColor),this.options.iconActiveColor&&i.setProperty("--bim-icon-active-color",this.options.iconActiveColor),this.options.textColor&&i.setProperty("--bim-btn-text-color",this.options.textColor),this.options.textActiveColor&&i.setProperty("--bim-btn-text-active-color",this.options.textActiveColor),this.options.btnBackgroundColor&&i.setProperty("--bim-btn-bg",this.options.btnBackgroundColor),this.options.btnHoverColor&&i.setProperty("--bim-btn-hover-bg",this.options.btnHoverColor),this.options.btnActiveColor&&i.setProperty("--bim-btn-active-bg",this.options.btnActiveColor)})}setPrimaryColor(e){this.container.style.setProperty("--bim-primary-color",e),document.querySelectorAll(".opt-btn-dropdown").forEach(n=>{n.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(([n,i])=>{const r=n;this.customColors.has(r)||(this.options[r]=i)}),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(n=>{const i=n.style;i.setProperty("--bim-primary",e.primary),i.setProperty("--bim-bg-overlay",e.bgOverlay),i.setProperty("--bim-border-default",e.borderDefault),i.setProperty("--bim-text-primary",e.textPrimary),i.setProperty("--bim-text-inverse",e.textInverse),i.setProperty("--bim-shadow-lg",e.shadowLg),i.setProperty("--bim-floating-btn-bg",e.floatingBtnBg),i.setProperty("--bim-floating-btn-bg-hover",e.floatingBtnBgHover),i.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=Yt.subscribe(()=>{this.setLocales()}),this.unsubscribeTheme=ot.subscribe(e=>{this.setTheme(e)})}setLocales(){this.render()}addGroup(e,t){if(this.groups.some(i=>i.id===e))return;const n={id:e,buttons:[]};if(t){const i=this.groups.findIndex(r=>r.id===t);i!==-1?this.groups.splice(i,0,n):this.groups.push(n)}else this.groups.push(n)}addButton(e){const{groupId:t,parentId:n}=e,i=this.groups.find(o=>o.id===t);if(!i)return;const r={...e,children:e.children||[]};if(n){const o=this.findButton(i.buttons,n);o&&(o.children||(o.children=[]),o.children.push(r))}else i.buttons.push(r)}findButton(e,t){for(const n of e){if(n.id===t)return n;if(n.children){const i=this.findButton(n.children,t);if(i)return i}}}render(){this.container.innerHTML="",this.btnRefs.clear(),this.groups.forEach((e,t)=>{const n=this.renderGroup(e,t,this.groups.length);this.container.appendChild(n)})}renderGroup(e,t,n){const i=document.createElement("div");return i.className="bim-btn-group-section",t{if(this.isVisible(r.id)){const o=this.renderButton(r);i.appendChild(o)}}),i}renderButton(e){const t=document.createElement("div");t.className="opt-btn-wrapper";const n=document.createElement("div");n.className="opt-btn",e.isActive&&this.activeBtnIds.add(e.id),(e.align||this.options.align||"vertical")==="horizontal"?n.classList.add("align-horizontal"):n.classList.add("align-vertical"),this.activeBtnIds.has(e.id)&&n.classList.add("active"),e.disabled&&n.classList.add("disabled"),this.options.showLabel&&e.label||(n.classList.add("no-label"),e.label&&(n.title=xe(e.label)));const o=e.iconSize||32,a=e.minWidth||50;n.style.minWidth=`${a}px`;const l=document.createElement("div");l.className="opt-btn-icon",l.style.width=`${o}px`,l.style.height=`${o}px`,l.innerHTML=this.getIcon(e.icon),n.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=xe(e.label),c.appendChild(h)}return c.hasChildNodes()&&n.appendChild(c),n.addEventListener("click",()=>this.handleClick(e)),n.addEventListener("mouseenter",()=>this.handleMouseEnter(e,n)),n.addEventListener("mouseleave",()=>this.handleMouseLeave()),this.btnRefs.set(e.id,n),t.appendChild(n),t}setBtnActive(e,t){const n=this.findButtonById(e);if(!n)return;const i=t!==void 0?t:!this.activeBtnIds.has(e);i?this.activeBtnIds.add(e):this.activeBtnIds.delete(e),n.isActive=i,this.updateButtonState(e)}handleClick(e){if(!e.disabled&&(!e.children||e.children.length===0)){if(e.keepActive){const n=!this.activeBtnIds.has(e.id);this.setBtnActive(e.id,n),n&&e.exclusive&&e.groupId&&this.deactivateExclusiveSiblings(e)}this.closeDropdown(),e.onClick&&e.onClick(e)}}deactivateExclusiveSiblings(e){const t=this.groups.find(n=>n.id===e.groupId);if(t){if(e.parentId){const i=this.findButton(t.buttons,e.parentId)?.children||[];for(const r of i)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 n of t.buttons)n.id!==e.id&&n.groupId===e.groupId&&(n.parentId||this.activeBtnIds.has(n.id)&&(this.setBtnActive(n.id,!1),n.onClick&&n.onClick(n)))}}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 n=document.createElement("div");n.className="opt-btn-dropdown",this.options.backgroundColor&&n.style.setProperty("--bim-toolbar-bg",this.options.backgroundColor);const i=n.style;this.options.iconColor&&i.setProperty("--bim-icon-color",this.options.iconColor),this.options.iconActiveColor&&i.setProperty("--bim-icon-active-color",this.options.iconActiveColor),this.options.textColor&&i.setProperty("--bim-btn-text-color",this.options.textColor),this.options.textActiveColor&&i.setProperty("--bim-btn-text-active-color",this.options.textActiveColor),this.options.btnBackgroundColor&&i.setProperty("--bim-btn-bg",this.options.btnBackgroundColor),this.options.btnHoverColor&&i.setProperty("--bim-btn-hover-bg",this.options.btnHoverColor),this.options.btnActiveColor&&i.setProperty("--bim-btn-active-bg",this.options.btnActiveColor);const r=t.getBoundingClientRect(),o=this.options.expand||"down";this.options.direction==="row"?n.style.flexDirection="column":n.style.flexDirection="row",this.options.type&&this.options.type!=="default"&&n.classList.add(`type-${this.options.type}`);const a=ot.getTheme();n.classList.add(`theme-${a.name}`),i.setProperty("--bim-primary",a.primary),i.setProperty("--bim-bg-overlay",a.bgOverlay),i.setProperty("--bim-border-default",a.borderDefault),i.setProperty("--bim-text-primary",a.textPrimary),i.setProperty("--bim-text-inverse",a.textInverse),i.setProperty("--bim-shadow-lg",a.shadowLg),i.setProperty("--bim-floating-btn-bg",a.floatingBtnBg),i.setProperty("--bim-floating-btn-bg-hover",a.floatingBtnBgHover),i.setProperty("--bim-floating-icon-color",a.floatingIconColor),document.body.appendChild(n),this.setupEventInterception(n),e.children.forEach(c=>{if(this.isVisible(c.id)){const h=this.renderDropdownItem(c);n.appendChild(h)}});const l=n.getBoundingClientRect();o==="up"?(n.style.bottom=window.innerHeight-r.top+8+"px",n.style.left=r.left+(r.width-l.width)/2+"px"):o==="down"?(n.style.top=r.bottom+8+"px",n.style.left=r.left+(r.width-l.width)/2+"px"):o==="right"?(n.style.top=r.top+(r.height-l.height)/2+"px",n.style.left=r.right+8+"px"):o==="left"&&(n.style.top=r.top+(r.height-l.height)/2+"px",n.style.right=window.innerWidth-r.left+8+"px"),n.addEventListener("mouseenter",()=>{this.hoverTimeout&&clearTimeout(this.hoverTimeout)}),n.addEventListener("mouseleave",()=>this.handleMouseLeave()),this.dropdownElement=n}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 i=e.iconSize||32,r=e.minWidth;r&&(t.style.minWidth=`${r}px`);const o=document.createElement("div");if(o.className="opt-btn-icon",o.style.width=`${i}px`,o.style.height=`${i}px`,o.innerHTML=this.getIcon(e.icon),t.appendChild(o),this.options.showLabel&&e.label){const a=document.createElement("span");a.className="opt-btn-dropdown-label",a.textContent=xe(e.label),t.appendChild(a)}else e.label&&(t.title=xe(e.label));return t.addEventListener("click",a=>{a.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}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 n=this.findButtonById(t);if(!n)return;this.options.showLabel&&n.label?(e.classList.remove("no-label"),e.removeAttribute("title")):(e.classList.add("no-label"),n.label&&(e.title=xe(n.label)))})}findButtonById(e){for(const t of this.groups){const n=this.findButton(t.buttons,e);if(n)return n}}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 i0 extends zl{async init(){await super.init();const e=this.options.registry,{createHomeButton:t}=await Promise.resolve().then(()=>xT),{createZoomBoxButton:n}=await Promise.resolve().then(()=>vT),{createWalkMenuButton:i}=await Promise.resolve().then(()=>bT),{createMapButton:r}=await Promise.resolve().then(()=>yT),{createPropertyButton:o}=await Promise.resolve().then(()=>_T),{createSettingButton:a}=await Promise.resolve().then(()=>MT),{createInfoButton:l}=await Promise.resolve().then(()=>wT),{createFullscreenButton:c}=await Promise.resolve().then(()=>ST),{createMeasureButton:h}=await Promise.resolve().then(()=>ET),{createSectionMenuButton:u}=await Promise.resolve().then(()=>TT),{createSectionPlaneButton:f}=await Promise.resolve().then(()=>CT),{createSectionAxisButton:d}=await Promise.resolve().then(()=>AT),{createSectionBoxButton:m}=await Promise.resolve().then(()=>PT),{createAiChatButton:p}=await Promise.resolve().then(()=>RT);this.addGroup("group-1"),this.addButton(t(e)),this.addButton(n(e)),this.addButton(h(e)),this.addButton(u(e)),this.addButton(f(e)),this.addButton(d(e)),this.addButton(m(e)),this.addButton(i(e)),this.addButton(r(e)),this.addButton(o(e)),this.addGroup("group-2"),this.addButton(p(e)),this.addButton(a(e)),this.addButton(l(e)),this.addButton(c(e)),this.render()}}class pi{registry;subscriptions=[];constructor(e){this.registry=e}subscribe(e,t){const n=this.registry.on(e,t);this.subscriptions.push(n)}emit(e,t){this.registry.emit(e,t)}destroy(){this.subscriptions.forEach(e=>e()),this.subscriptions=[]}}class s0 extends pi{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 i0({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)}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 r0 extends pi{groups=new Map;container;constructor(e,t){super(t),this.container=e}create(e,t){const n=new zl({container:this.container,registry:this.registry,...t});return n.init(),this.groups.set(e,n),n}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 o0{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=ot.subscribe(e=>{this.setTheme(e)}),this.unsubscribeLocale=Yt.subscribe(()=>{this.setLocales()}))}setLocales(){if(this.options.title){const e=this.header.querySelector(".bim-dialog-title");e&&(e.textContent=xe(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 n=document.createElement("div");n.className="bim-dialog-header",this.options.draggable&&n.classList.add("draggable");const i=document.createElement("span");i.className="bim-dialog-title",i.textContent=this.options.title?xe(this.options.title):"";const r=document.createElement("span");r.className="bim-dialog-close",r.innerHTML="×",r.onclick=()=>{this.close()},n.appendChild(i),n.appendChild(r);const o=document.createElement("div");if(o.className="bim-dialog-content",typeof this.options.content=="string"?o.innerHTML=this.options.content:this.options.content instanceof HTMLElement&&o.appendChild(this.options.content),e.appendChild(n),e.appendChild(o),this.options.resizable){const c=document.createElement("div");c.className="bim-dialog-resize-handle",e.appendChild(c)}const a=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,a,{passive:!1})}),e}setSize(e,t,n){t!==void 0&&(t==="auto"||t==="fit-content"?e.style.width=t:e.style.width=typeof t=="number"?`${t}px`:t),n!==void 0&&(n==="auto"||n==="fit-content"?e.style.height=n:e.style.height=typeof n=="number"?`${n}px`:n)}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,n=this.options.minHeight??100,i=this.container.clientHeight||0;let r=Math.max(n,t);i>0&&(r=Math.min(r,i)),this.element.style.height=`${r}px`,e?this.initPosition():this.clampToContainer()}clampToContainer(){const e=this.container.clientWidth,t=this.container.clientHeight,n=this.element.offsetWidth,i=this.element.offsetHeight,r=this.options.bottomOffset??70,o=this.element.offsetLeft,a=this.element.offsetTop,l=Math.max(0,e-n),c=Math.max(0,t-i-r),h=Math.max(0,Math.min(o,l)),u=Math.max(0,Math.min(a,c));this.element.style.left=`${h}px`,this.element.style.top=`${u}px`}initPosition(){const e=this.options.position,t=this.element.getBoundingClientRect(),n=this.options.bottomOffset??70;let i=0,r=0;const o=this.container.clientWidth,a=this.container.clientHeight,l=t.width,c=t.height;if(typeof e=="object"&&"x"in e)i=e.x,r=e.y;else switch(e){case"center":i=(o-l)/2,r=(a-c)/2;break;case"top-left":i=0,r=0;break;case"top-center":i=(o-l)/2,r=0;break;case"top-right":i=o-l,r=0;break;case"left-center":i=0,r=(a-c)/2;break;case"right-center":i=o-l,r=(a-c)/2;break;case"bottom-left":i=0,r=a-c-n;break;case"bottom-center":i=(o-l)/2,r=a-c-n;break;case"bottom-right":i=o-l,r=a-c-n;break;default:i=(o-l)/2,r=(a-c)/2}i=Math.max(0,Math.min(i,o-l)),r=Math.max(0,Math.min(r,a-c-n)),this.element.style.left=`${i}px`,this.element.style.top=`${r}px`}initDrag(){let e=0,t=0,n=0,i=0,r=0,o=0,a=0,l=0,c=0;const h=d=>{d.preventDefault(),d.stopPropagation(),e=d.clientX,t=d.clientY,n=this.element.offsetLeft,i=this.element.offsetTop,r=this.container.clientWidth,o=this.container.clientHeight,a=this.element.offsetWidth,l=this.element.offsetHeight,c=this.options.bottomOffset??70,document.addEventListener("mousemove",u,{capture:!0}),document.addEventListener("mouseup",f,{capture:!0})},u=d=>{d.preventDefault(),d.stopPropagation(),!this.rafId&&(this.rafId=requestAnimationFrame(()=>{const m=d.clientX-e,p=d.clientY-t;let x=n+m,g=i+p;const b=r-a,v=o-l-c;x=Math.max(0,Math.min(x,b)),g=Math.max(0,Math.min(g,v)),this.element.style.left=`${x}px`,this.element.style.top=`${g}px`,this.rafId=null}))},f=()=>{this.rafId&&(cancelAnimationFrame(this.rafId),this.rafId=null),document.removeEventListener("mousemove",u,{capture:!0}),document.removeEventListener("mouseup",f,{capture:!0})};this.header.addEventListener("mousedown",h)}initResize(){const e=this.element.querySelector(".bim-dialog-resize-handle");if(!e)return;let t=0,n=0,i=0,r=0;const o=c=>{c.preventDefault(),c.stopPropagation(),t=c.clientX,n=c.clientY,i=this.element.offsetWidth,r=this.element.offsetHeight,document.addEventListener("mousemove",a,{capture:!0}),document.addEventListener("mouseup",l,{capture:!0})},a=c=>{c.preventDefault(),c.stopPropagation(),!this.rafId&&(this.rafId=requestAnimationFrame(()=>{const h=c.clientX-t,u=c.clientY-n,f=Math.max(this.options.minWidth||100,i+h),d=Math.max(this.options.minHeight||50,r+u);this.element.style.width=`${f}px`,this.element.style.height=`${d}px`,this.rafId=null}))},l=()=>{this.rafId&&(cancelAnimationFrame(this.rafId),this.rafId=null),document.removeEventListener("mousemove",a,{capture:!0}),document.removeEventListener("mouseup",l,{capture:!0})};e.addEventListener("mousedown",o)}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 a0 extends pi{container;activeDialogs=[];constructor(e,t){super(t),this.container=e}create(e){const t=new o0({container:this.container,...e,onClose:()=>{this.activeDialogs=this.activeDialogs.filter(n=>n!==t),e.onClose&&e.onClose()}});return t.setTheme(ot.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 Hr="181",ks={ROTATE:0,DOLLY:1,PAN:2},Us={ROTATE:0,PAN:1,DOLLY_PAN:2,DOLLY_ROTATE:3},l0=0,rd=1,c0=2,od=1,ad=2,mi=3,Pn=0,ln=1,St=2,Wt=0,Os=1,Hl=2,ld=3,cd=4,hd=5,Gn=100,h0=101,u0=102,d0=103,f0=104,Vr=200,p0=201,m0=202,g0=203,Vl=204,Gl=205,Wl=206,x0=207,Xl=208,v0=209,b0=210,y0=211,_0=212,M0=213,w0=214,jl=0,ql=1,Zl=2,Fs=3,Yl=4,$l=5,Kl=6,Jl=7,Ql=0,S0=1,E0=2,ki=0,ud=1,dd=2,fd=3,pd=4,md=5,gd=6,xd=7,vd="attached",T0="detached",bd=300,zs=301,Hs=302,ec=303,tc=304,Go=306,ni=1e3,ii=1001,Wo=1002,$t=1003,yd=1004,Gr=1005,Kt=1006,Xo=1007,gi=1008,Wn=1009,_d=1010,Md=1011,Wr=1012,nc=1013,rs=1014,Xn=1015,xi=1016,ic=1017,sc=1018,Vs=1020,wd=35902,Sd=35899,Ed=1021,Td=1022,mn=1023,Xr=1026,Gs=1027,rc=1028,oc=1029,ac=1030,lc=1031,cc=1033,jo=33776,qo=33777,Zo=33778,Yo=33779,hc=35840,uc=35841,dc=35842,fc=35843,pc=36196,mc=37492,gc=37496,xc=37808,vc=37809,bc=37810,yc=37811,_c=37812,Mc=37813,wc=37814,Sc=37815,Ec=37816,Tc=37817,Cc=37818,Ac=37819,Pc=37820,Rc=37821,Lc=36492,Ic=36494,Dc=36495,Bc=36283,Nc=36284,kc=36285,Uc=36286,jr=2300,qr=2301,Oc=2302,Cd=2400,Ad=2401,Pd=2402,C0=2500,A0=0,Rd=1,Fc=2,P0=3200,R0=3201,$o=0,L0=1,Ui="",At="srgb",tn="srgb-linear",Ko="linear",lt="srgb",Ws=7680,Ld=519,I0=512,D0=513,B0=514,Id=515,N0=516,k0=517,U0=518,O0=519,zc=35044,Dd="300 es",si=2e3,Jo=2001;function Bd(s){for(let e=s.length-1;e>=0;--e)if(s[e]>=65535)return!0;return!1}function Zr(s){return document.createElementNS("http://www.w3.org/1999/xhtml",s)}function F0(){const s=Zr("canvas");return s.style.display="block",s}const Nd={};function Qo(...s){const e="THREE."+s.shift();console.log(e,...s)}function ze(...s){const e="THREE."+s.shift();console.warn(e,...s)}function Qe(...s){const e="THREE."+s.shift();console.error(e,...s)}function Yr(...s){const e=s.join(" ");e in Nd||(Nd[e]=!0,ze(...s))}function z0(s,e,t){return new Promise(function(n,i){function r(){switch(s.clientWaitSync(e,s.SYNC_FLUSH_COMMANDS_BIT,0)){case s.WAIT_FAILED:i();break;case s.TIMEOUT_EXPIRED:setTimeout(r,t);break;default:n()}}setTimeout(r,t)})}class os{addEventListener(e,t){this._listeners===void 0&&(this._listeners={});const n=this._listeners;n[e]===void 0&&(n[e]=[]),n[e].indexOf(t)===-1&&n[e].push(t)}hasEventListener(e,t){const n=this._listeners;return n===void 0?!1:n[e]!==void 0&&n[e].indexOf(t)!==-1}removeEventListener(e,t){const n=this._listeners;if(n===void 0)return;const i=n[e];if(i!==void 0){const r=i.indexOf(t);r!==-1&&i.splice(r,1)}}dispatchEvent(e){const t=this._listeners;if(t===void 0)return;const n=t[e.type];if(n!==void 0){e.target=this;const i=n.slice(0);for(let r=0,o=i.length;r>8&255]+nn[s>>16&255]+nn[s>>24&255]+"-"+nn[e&255]+nn[e>>8&255]+"-"+nn[e>>16&15|64]+nn[e>>24&255]+"-"+nn[t&63|128]+nn[t>>8&255]+"-"+nn[t>>16&255]+nn[t>>24&255]+nn[n&255]+nn[n>>8&255]+nn[n>>16&255]+nn[n>>24&255]).toLowerCase()}function qe(s,e,t){return Math.max(e,Math.min(t,s))}function Hc(s,e){return(s%e+e)%e}function H0(s,e,t,n,i){return n+(s-e)*(i-n)/(t-e)}function V0(s,e,t){return s!==e?(t-s)/(e-s):0}function Kr(s,e,t){return(1-t)*s+t*e}function G0(s,e,t,n){return Kr(s,e,1-Math.exp(-t*n))}function W0(s,e=1){return e-Math.abs(Hc(s,e*2)-e)}function X0(s,e,t){return s<=e?0:s>=t?1:(s=(s-e)/(t-e),s*s*(3-2*s))}function j0(s,e,t){return s<=e?0:s>=t?1:(s=(s-e)/(t-e),s*s*s*(s*(s*6-15)+10))}function q0(s,e){return s+Math.floor(Math.random()*(e-s+1))}function Z0(s,e){return s+Math.random()*(e-s)}function Y0(s){return s*(.5-Math.random())}function $0(s){s!==void 0&&(kd=s);let e=kd+=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 K0(s){return s*$r}function J0(s){return s*Xs}function Q0(s){return(s&s-1)===0&&s!==0}function ex(s){return Math.pow(2,Math.ceil(Math.log(s)/Math.LN2))}function tx(s){return Math.pow(2,Math.floor(Math.log(s)/Math.LN2))}function nx(s,e,t,n,i){const r=Math.cos,o=Math.sin,a=r(t/2),l=o(t/2),c=r((e+n)/2),h=o((e+n)/2),u=r((e-n)/2),f=o((e-n)/2),d=r((n-e)/2),m=o((n-e)/2);switch(i){case"XYX":s.set(a*h,l*u,l*f,a*c);break;case"YZY":s.set(l*f,a*h,l*u,a*c);break;case"ZXZ":s.set(l*u,l*f,a*h,a*c);break;case"XZX":s.set(a*h,l*m,l*d,a*c);break;case"YXY":s.set(l*d,a*h,l*m,a*c);break;case"ZYZ":s.set(l*m,l*d,a*h,a*c);break;default:ze("MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: "+i)}}function jn(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 ct(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 Ot={DEG2RAD:$r,RAD2DEG:Xs,generateUUID:Rn,clamp:qe,euclideanModulo:Hc,mapLinear:H0,inverseLerp:V0,lerp:Kr,damp:G0,pingpong:W0,smoothstep:X0,smootherstep:j0,randInt:q0,randFloat:Z0,randFloatSpread:Y0,seededRandom:$0,degToRad:K0,radToDeg:J0,isPowerOfTwo:Q0,ceilPowerOfTwo:ex,floorPowerOfTwo:tx,setQuaternionFromProperEuler:nx,normalize:ct,denormalize:jn};class ue{constructor(e=0,t=0){ue.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,n=this.y,i=e.elements;return this.x=i[0]*t+i[3]*n+i[6],this.y=i[1]*t+i[4]*n+i[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=qe(this.x,e.x,t.x),this.y=qe(this.y,e.y,t.y),this}clampScalar(e,t){return this.x=qe(this.x,e,t),this.y=qe(this.y,e,t),this}clampLength(e,t){const n=this.length();return this.divideScalar(n||1).multiplyScalar(qe(n,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 n=this.dot(e)/t;return Math.acos(qe(n,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){const t=this.x-e.x,n=this.y-e.y;return t*t+n*n}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,n){return this.x=e.x+(t.x-e.x)*n,this.y=e.y+(t.y-e.y)*n,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 n=Math.cos(t),i=Math.sin(t),r=this.x-e.x,o=this.y-e.y;return this.x=r*n-o*i+e.x,this.y=r*i+o*n+e.y,this}random(){return this.x=Math.random(),this.y=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y}}class Ln{constructor(e=0,t=0,n=0,i=1){this.isQuaternion=!0,this._x=e,this._y=t,this._z=n,this._w=i}static slerpFlat(e,t,n,i,r,o,a){let l=n[i+0],c=n[i+1],h=n[i+2],u=n[i+3],f=r[o+0],d=r[o+1],m=r[o+2],p=r[o+3];if(a<=0){e[t+0]=l,e[t+1]=c,e[t+2]=h,e[t+3]=u;return}if(a>=1){e[t+0]=f,e[t+1]=d,e[t+2]=m,e[t+3]=p;return}if(u!==p||l!==f||c!==d||h!==m){let x=l*f+c*d+h*m+u*p;x<0&&(f=-f,d=-d,m=-m,p=-p,x=-x);let g=1-a;if(x<.9995){const b=Math.acos(x),v=Math.sin(b);g=Math.sin(g*b)/v,a=Math.sin(a*b)/v,l=l*g+f*a,c=c*g+d*a,h=h*g+m*a,u=u*g+p*a}else{l=l*g+f*a,c=c*g+d*a,h=h*g+m*a,u=u*g+p*a;const b=1/Math.sqrt(l*l+c*c+h*h+u*u);l*=b,c*=b,h*=b,u*=b}}e[t]=l,e[t+1]=c,e[t+2]=h,e[t+3]=u}static multiplyQuaternionsFlat(e,t,n,i,r,o){const a=n[i],l=n[i+1],c=n[i+2],h=n[i+3],u=r[o],f=r[o+1],d=r[o+2],m=r[o+3];return e[t]=a*m+h*u+l*d-c*f,e[t+1]=l*m+h*f+c*u-a*d,e[t+2]=c*m+h*d+a*f-l*u,e[t+3]=h*m-a*u-l*f-c*d,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,n,i){return this._x=e,this._y=t,this._z=n,this._w=i,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 n=e._x,i=e._y,r=e._z,o=e._order,a=Math.cos,l=Math.sin,c=a(n/2),h=a(i/2),u=a(r/2),f=l(n/2),d=l(i/2),m=l(r/2);switch(o){case"XYZ":this._x=f*h*u+c*d*m,this._y=c*d*u-f*h*m,this._z=c*h*m+f*d*u,this._w=c*h*u-f*d*m;break;case"YXZ":this._x=f*h*u+c*d*m,this._y=c*d*u-f*h*m,this._z=c*h*m-f*d*u,this._w=c*h*u+f*d*m;break;case"ZXY":this._x=f*h*u-c*d*m,this._y=c*d*u+f*h*m,this._z=c*h*m+f*d*u,this._w=c*h*u-f*d*m;break;case"ZYX":this._x=f*h*u-c*d*m,this._y=c*d*u+f*h*m,this._z=c*h*m-f*d*u,this._w=c*h*u+f*d*m;break;case"YZX":this._x=f*h*u+c*d*m,this._y=c*d*u+f*h*m,this._z=c*h*m-f*d*u,this._w=c*h*u-f*d*m;break;case"XZY":this._x=f*h*u-c*d*m,this._y=c*d*u-f*h*m,this._z=c*h*m+f*d*u,this._w=c*h*u+f*d*m;break;default:ze("Quaternion: .setFromEuler() encountered an unknown order: "+o)}return t===!0&&this._onChangeCallback(),this}setFromAxisAngle(e,t){const n=t/2,i=Math.sin(n);return this._x=e.x*i,this._y=e.y*i,this._z=e.z*i,this._w=Math.cos(n),this._onChangeCallback(),this}setFromRotationMatrix(e){const t=e.elements,n=t[0],i=t[4],r=t[8],o=t[1],a=t[5],l=t[9],c=t[2],h=t[6],u=t[10],f=n+a+u;if(f>0){const d=.5/Math.sqrt(f+1);this._w=.25/d,this._x=(h-l)*d,this._y=(r-c)*d,this._z=(o-i)*d}else if(n>a&&n>u){const d=2*Math.sqrt(1+n-a-u);this._w=(h-l)/d,this._x=.25*d,this._y=(i+o)/d,this._z=(r+c)/d}else if(a>u){const d=2*Math.sqrt(1+a-n-u);this._w=(r-c)/d,this._x=(i+o)/d,this._y=.25*d,this._z=(l+h)/d}else{const d=2*Math.sqrt(1+u-n-a);this._w=(o-i)/d,this._x=(r+c)/d,this._y=(l+h)/d,this._z=.25*d}return this._onChangeCallback(),this}setFromUnitVectors(e,t){let n=e.dot(t)+1;return n<1e-8?(n=0,Math.abs(e.x)>Math.abs(e.z)?(this._x=-e.y,this._y=e.x,this._z=0,this._w=n):(this._x=0,this._y=-e.z,this._z=e.y,this._w=n)):(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=n),this.normalize()}angleTo(e){return 2*Math.acos(Math.abs(qe(this.dot(e),-1,1)))}rotateTowards(e,t){const n=this.angleTo(e);if(n===0)return this;const i=Math.min(1,t/n);return this.slerp(e,i),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 n=e._x,i=e._y,r=e._z,o=e._w,a=t._x,l=t._y,c=t._z,h=t._w;return this._x=n*h+o*a+i*c-r*l,this._y=i*h+o*l+r*a-n*c,this._z=r*h+o*c+n*l-i*a,this._w=o*h-n*a-i*l-r*c,this._onChangeCallback(),this}slerp(e,t){if(t<=0)return this;if(t>=1)return this.copy(e);let n=e._x,i=e._y,r=e._z,o=e._w,a=this.dot(e);a<0&&(n=-n,i=-i,r=-r,o=-o,a=-a);let l=1-t;if(a<.9995){const c=Math.acos(a),h=Math.sin(c);l=Math.sin(l*c)/h,t=Math.sin(t*c)/h,this._x=this._x*l+n*t,this._y=this._y*l+i*t,this._z=this._z*l+r*t,this._w=this._w*l+o*t,this._onChangeCallback()}else this._x=this._x*l+n*t,this._y=this._y*l+i*t,this._z=this._z*l+r*t,this._w=this._w*l+o*t,this.normalize();return this}slerpQuaternions(e,t,n){return this.copy(e).slerp(t,n)}random(){const e=2*Math.PI*Math.random(),t=2*Math.PI*Math.random(),n=Math.random(),i=Math.sqrt(1-n),r=Math.sqrt(n);return this.set(i*Math.sin(e),i*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,n=0){R.prototype.isVector3=!0,this.x=e,this.y=t,this.z=n}set(e,t,n){return n===void 0&&(n=this.z),this.x=e,this.y=t,this.z=n,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(Ud.setFromEuler(e))}applyAxisAngle(e,t){return this.applyQuaternion(Ud.setFromAxisAngle(e,t))}applyMatrix3(e){const t=this.x,n=this.y,i=this.z,r=e.elements;return this.x=r[0]*t+r[3]*n+r[6]*i,this.y=r[1]*t+r[4]*n+r[7]*i,this.z=r[2]*t+r[5]*n+r[8]*i,this}applyNormalMatrix(e){return this.applyMatrix3(e).normalize()}applyMatrix4(e){const t=this.x,n=this.y,i=this.z,r=e.elements,o=1/(r[3]*t+r[7]*n+r[11]*i+r[15]);return this.x=(r[0]*t+r[4]*n+r[8]*i+r[12])*o,this.y=(r[1]*t+r[5]*n+r[9]*i+r[13])*o,this.z=(r[2]*t+r[6]*n+r[10]*i+r[14])*o,this}applyQuaternion(e){const t=this.x,n=this.y,i=this.z,r=e.x,o=e.y,a=e.z,l=e.w,c=2*(o*i-a*n),h=2*(a*t-r*i),u=2*(r*n-o*t);return this.x=t+l*c+o*u-a*h,this.y=n+l*h+a*c-r*u,this.z=i+l*u+r*h-o*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,n=this.y,i=this.z,r=e.elements;return this.x=r[0]*t+r[4]*n+r[8]*i,this.y=r[1]*t+r[5]*n+r[9]*i,this.z=r[2]*t+r[6]*n+r[10]*i,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=qe(this.x,e.x,t.x),this.y=qe(this.y,e.y,t.y),this.z=qe(this.z,e.z,t.z),this}clampScalar(e,t){return this.x=qe(this.x,e,t),this.y=qe(this.y,e,t),this.z=qe(this.z,e,t),this}clampLength(e,t){const n=this.length();return this.divideScalar(n||1).multiplyScalar(qe(n,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,n){return this.x=e.x+(t.x-e.x)*n,this.y=e.y+(t.y-e.y)*n,this.z=e.z+(t.z-e.z)*n,this}cross(e){return this.crossVectors(this,e)}crossVectors(e,t){const n=e.x,i=e.y,r=e.z,o=t.x,a=t.y,l=t.z;return this.x=i*l-r*a,this.y=r*o-n*l,this.z=n*a-i*o,this}projectOnVector(e){const t=e.lengthSq();if(t===0)return this.set(0,0,0);const n=e.dot(this)/t;return this.copy(e).multiplyScalar(n)}projectOnPlane(e){return Vc.copy(this).projectOnVector(e),this.sub(Vc)}reflect(e){return this.sub(Vc.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 n=this.dot(e)/t;return Math.acos(qe(n,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){const t=this.x-e.x,n=this.y-e.y,i=this.z-e.z;return t*t+n*n+i*i}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,n){const i=Math.sin(t)*e;return this.x=i*Math.sin(n),this.y=Math.cos(t)*e,this.z=i*Math.cos(n),this}setFromCylindrical(e){return this.setFromCylindricalCoords(e.radius,e.theta,e.y)}setFromCylindricalCoords(e,t,n){return this.x=e*Math.sin(t),this.y=n,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(),n=this.setFromMatrixColumn(e,1).length(),i=this.setFromMatrixColumn(e,2).length();return this.x=t,this.y=n,this.z=i,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,n=Math.sqrt(1-t*t);return this.x=n*Math.cos(e),this.y=t,this.z=n*Math.sin(e),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z}}const Vc=new R,Ud=new Ln;class $e{constructor(e,t,n,i,r,o,a,l,c){$e.prototype.isMatrix3=!0,this.elements=[1,0,0,0,1,0,0,0,1],e!==void 0&&this.set(e,t,n,i,r,o,a,l,c)}set(e,t,n,i,r,o,a,l,c){const h=this.elements;return h[0]=e,h[1]=i,h[2]=a,h[3]=t,h[4]=r,h[5]=l,h[6]=n,h[7]=o,h[8]=c,this}identity(){return this.set(1,0,0,0,1,0,0,0,1),this}copy(e){const t=this.elements,n=e.elements;return t[0]=n[0],t[1]=n[1],t[2]=n[2],t[3]=n[3],t[4]=n[4],t[5]=n[5],t[6]=n[6],t[7]=n[7],t[8]=n[8],this}extractBasis(e,t,n){return e.setFromMatrix3Column(this,0),t.setFromMatrix3Column(this,1),n.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 n=e.elements,i=t.elements,r=this.elements,o=n[0],a=n[3],l=n[6],c=n[1],h=n[4],u=n[7],f=n[2],d=n[5],m=n[8],p=i[0],x=i[3],g=i[6],b=i[1],v=i[4],y=i[7],M=i[2],E=i[5],C=i[8];return r[0]=o*p+a*b+l*M,r[3]=o*x+a*v+l*E,r[6]=o*g+a*y+l*C,r[1]=c*p+h*b+u*M,r[4]=c*x+h*v+u*E,r[7]=c*g+h*y+u*C,r[2]=f*p+d*b+m*M,r[5]=f*x+d*v+m*E,r[8]=f*g+d*y+m*C,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],n=e[1],i=e[2],r=e[3],o=e[4],a=e[5],l=e[6],c=e[7],h=e[8];return t*o*h-t*a*c-n*r*h+n*a*l+i*r*c-i*o*l}invert(){const e=this.elements,t=e[0],n=e[1],i=e[2],r=e[3],o=e[4],a=e[5],l=e[6],c=e[7],h=e[8],u=h*o-a*c,f=a*l-h*r,d=c*r-o*l,m=t*u+n*f+i*d;if(m===0)return this.set(0,0,0,0,0,0,0,0,0);const p=1/m;return e[0]=u*p,e[1]=(i*c-h*n)*p,e[2]=(a*n-i*o)*p,e[3]=f*p,e[4]=(h*t-i*l)*p,e[5]=(i*r-a*t)*p,e[6]=d*p,e[7]=(n*l-c*t)*p,e[8]=(o*t-n*r)*p,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,n,i,r,o,a){const l=Math.cos(r),c=Math.sin(r);return this.set(n*l,n*c,-n*(l*o+c*a)+o+e,-i*c,i*l,-i*(-c*o+l*a)+a+t,0,0,1),this}scale(e,t){return this.premultiply(Gc.makeScale(e,t)),this}rotate(e){return this.premultiply(Gc.makeRotation(-e)),this}translate(e,t){return this.premultiply(Gc.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),n=Math.sin(e);return this.set(t,-n,0,n,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,n=e.elements;for(let i=0;i<9;i++)if(t[i]!==n[i])return!1;return!0}fromArray(e,t=0){for(let n=0;n<9;n++)this.elements[n]=e[n+t];return this}toArray(e=[],t=0){const n=this.elements;return e[t]=n[0],e[t+1]=n[1],e[t+2]=n[2],e[t+3]=n[3],e[t+4]=n[4],e[t+5]=n[5],e[t+6]=n[6],e[t+7]=n[7],e[t+8]=n[8],e}clone(){return new this.constructor().fromArray(this.elements)}}const Gc=new $e,Od=new $e().set(.4123908,.3575843,.1804808,.212639,.7151687,.0721923,.0193308,.1191948,.9505322),Fd=new $e().set(3.2409699,-1.5373832,-.4986108,-.9692436,1.8759675,.0415551,.0556301,-.203977,1.0569715);function ix(){const s={enabled:!0,workingColorSpace:tn,spaces:{},convert:function(i,r,o){return this.enabled===!1||r===o||!r||!o||(this.spaces[r].transfer===lt&&(i.r=vi(i.r),i.g=vi(i.g),i.b=vi(i.b)),this.spaces[r].primaries!==this.spaces[o].primaries&&(i.applyMatrix3(this.spaces[r].toXYZ),i.applyMatrix3(this.spaces[o].fromXYZ)),this.spaces[o].transfer===lt&&(i.r=js(i.r),i.g=js(i.g),i.b=js(i.b))),i},workingToColorSpace:function(i,r){return this.convert(i,this.workingColorSpace,r)},colorSpaceToWorking:function(i,r){return this.convert(i,r,this.workingColorSpace)},getPrimaries:function(i){return this.spaces[i].primaries},getTransfer:function(i){return i===Ui?Ko:this.spaces[i].transfer},getToneMappingMode:function(i){return this.spaces[i].outputColorSpaceConfig.toneMappingMode||"standard"},getLuminanceCoefficients:function(i,r=this.workingColorSpace){return i.fromArray(this.spaces[r].luminanceCoefficients)},define:function(i){Object.assign(this.spaces,i)},_getMatrix:function(i,r,o){return i.copy(this.spaces[r].toXYZ).multiply(this.spaces[o].fromXYZ)},_getDrawingBufferColorSpace:function(i){return this.spaces[i].outputColorSpaceConfig.drawingBufferColorSpace},_getUnpackColorSpace:function(i=this.workingColorSpace){return this.spaces[i].workingColorSpaceConfig.unpackColorSpace},fromWorkingColorSpace:function(i,r){return Yr("ColorManagement: .fromWorkingColorSpace() has been renamed to .workingToColorSpace()."),s.workingToColorSpace(i,r)},toWorkingColorSpace:function(i,r){return Yr("ColorManagement: .toWorkingColorSpace() has been renamed to .colorSpaceToWorking()."),s.colorSpaceToWorking(i,r)}},e=[.64,.33,.3,.6,.15,.06],t=[.2126,.7152,.0722],n=[.3127,.329];return s.define({[tn]:{primaries:e,whitePoint:n,transfer:Ko,toXYZ:Od,fromXYZ:Fd,luminanceCoefficients:t,workingColorSpaceConfig:{unpackColorSpace:At},outputColorSpaceConfig:{drawingBufferColorSpace:At}},[At]:{primaries:e,whitePoint:n,transfer:lt,toXYZ:Od,fromXYZ:Fd,luminanceCoefficients:t,outputColorSpaceConfig:{drawingBufferColorSpace:At}}}),s}const it=ix();function vi(s){return s<.04045?s*.0773993808:Math.pow(s*.9478672986+.0521327014,2.4)}function js(s){return s<.0031308?s*12.92:1.055*Math.pow(s,.41666)-.055}let qs;class sx{static getDataURL(e,t="image/png"){if(/^data:/i.test(e.src)||typeof HTMLCanvasElement>"u")return e.src;let n;if(e instanceof HTMLCanvasElement)n=e;else{qs===void 0&&(qs=Zr("canvas")),qs.width=e.width,qs.height=e.height;const i=qs.getContext("2d");e instanceof ImageData?i.putImageData(e,0,0):i.drawImage(e,0,0,e.width,e.height),n=qs}return n.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=Zr("canvas");t.width=e.width,t.height=e.height;const n=t.getContext("2d");n.drawImage(e,0,0,e.width,e.height);const i=n.getImageData(0,0,e.width,e.height),r=i.data;for(let o=0;o1),this.pmremVersion=0}get width(){return this.source.getSize(jc).x}get height(){return this.source.getSize(jc).y}get depth(){return this.source.getSize(jc).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 n=e[t];if(n===void 0){ze(`Texture.setValues(): parameter '${t}' has value of undefined.`);continue}const i=this[t];if(i===void 0){ze(`Texture.setValues(): property '${t}' does not exist.`);continue}i&&n&&i.isVector2&&n.isVector2||i&&n&&i.isVector3&&n.isVector3||i&&n&&i.isMatrix3&&n.isMatrix3?i.copy(n):this[t]=n}}toJSON(e){const t=e===void 0||typeof e=="string";if(!t&&e.textures[this.uuid]!==void 0)return e.textures[this.uuid];const n={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&&(n.userData=this.userData),t||(e.textures[this.uuid]=n),n}dispose(){this.dispatchEvent({type:"dispose"})}transformUv(e){if(this.mapping!==bd)return e;if(e.applyMatrix3(this.matrix),e.x<0||e.x>1)switch(this.wrapS){case ni:e.x=e.x-Math.floor(e.x);break;case ii: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 ni:e.y=e.y-Math.floor(e.y);break;case ii: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++}}Ft.DEFAULT_IMAGE=null,Ft.DEFAULT_MAPPING=bd,Ft.DEFAULT_ANISOTROPY=1;class tt{constructor(e=0,t=0,n=0,i=1){tt.prototype.isVector4=!0,this.x=e,this.y=t,this.z=n,this.w=i}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,n,i){return this.x=e,this.y=t,this.z=n,this.w=i,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,n=this.y,i=this.z,r=this.w,o=e.elements;return this.x=o[0]*t+o[4]*n+o[8]*i+o[12]*r,this.y=o[1]*t+o[5]*n+o[9]*i+o[13]*r,this.z=o[2]*t+o[6]*n+o[10]*i+o[14]*r,this.w=o[3]*t+o[7]*n+o[11]*i+o[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,n,i,r;const l=e.elements,c=l[0],h=l[4],u=l[8],f=l[1],d=l[5],m=l[9],p=l[2],x=l[6],g=l[10];if(Math.abs(h-f)<.01&&Math.abs(u-p)<.01&&Math.abs(m-x)<.01){if(Math.abs(h+f)<.1&&Math.abs(u+p)<.1&&Math.abs(m+x)<.1&&Math.abs(c+d+g-3)<.1)return this.set(1,0,0,0),this;t=Math.PI;const v=(c+1)/2,y=(d+1)/2,M=(g+1)/2,E=(h+f)/4,C=(u+p)/4,P=(m+x)/4;return v>y&&v>M?v<.01?(n=0,i=.707106781,r=.707106781):(n=Math.sqrt(v),i=E/n,r=C/n):y>M?y<.01?(n=.707106781,i=0,r=.707106781):(i=Math.sqrt(y),n=E/i,r=P/i):M<.01?(n=.707106781,i=.707106781,r=0):(r=Math.sqrt(M),n=C/r,i=P/r),this.set(n,i,r,t),this}let b=Math.sqrt((x-m)*(x-m)+(u-p)*(u-p)+(f-h)*(f-h));return Math.abs(b)<.001&&(b=1),this.x=(x-m)/b,this.y=(u-p)/b,this.z=(f-h)/b,this.w=Math.acos((c+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=qe(this.x,e.x,t.x),this.y=qe(this.y,e.y,t.y),this.z=qe(this.z,e.z,t.z),this.w=qe(this.w,e.w,t.w),this}clampScalar(e,t){return this.x=qe(this.x,e,t),this.y=qe(this.y,e,t),this.z=qe(this.z,e,t),this.w=qe(this.w,e,t),this}clampLength(e,t){const n=this.length();return this.divideScalar(n||1).multiplyScalar(qe(n,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,n){return this.x=e.x+(t.x-e.x)*n,this.y=e.y+(t.y-e.y)*n,this.z=e.z+(t.z-e.z)*n,this.w=e.w+(t.w-e.w)*n,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 ax extends os{constructor(e=1,t=1,n={}){super(),n=Object.assign({generateMipmaps:!1,internalFormat:null,minFilter:Kt,depthBuffer:!0,stencilBuffer:!1,resolveDepthBuffer:!0,resolveStencilBuffer:!0,depthTexture:null,samples:0,count:1,depth:1,multiview:!1},n),this.isRenderTarget=!0,this.width=e,this.height=t,this.depth=n.depth,this.scissor=new tt(0,0,e,t),this.scissorTest=!1,this.viewport=new tt(0,0,e,t);const i={width:e,height:t,depth:n.depth},r=new Ft(i);this.textures=[];const o=n.count;for(let a=0;a1);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,n=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,Zn),Zn.distanceToSquared(e.center)<=e.radius*e.radius}intersectsPlane(e){let t,n;return e.normal.x>0?(t=e.normal.x*this.min.x,n=e.normal.x*this.max.x):(t=e.normal.x*this.max.x,n=e.normal.x*this.min.x),e.normal.y>0?(t+=e.normal.y*this.min.y,n+=e.normal.y*this.max.y):(t+=e.normal.y*this.max.y,n+=e.normal.y*this.min.y),e.normal.z>0?(t+=e.normal.z*this.min.z,n+=e.normal.z*this.max.z):(t+=e.normal.z*this.max.z,n+=e.normal.z*this.min.z),t<=-e.constant&&n>=-e.constant}intersectsTriangle(e){if(this.isEmpty())return!1;this.getCenter(Jr),ta.subVectors(this.max,Jr),Zs.subVectors(e.a,Jr),Ys.subVectors(e.b,Jr),$s.subVectors(e.c,Jr),Oi.subVectors(Ys,Zs),Fi.subVectors($s,Ys),as.subVectors(Zs,$s);let t=[0,-Oi.z,Oi.y,0,-Fi.z,Fi.y,0,-as.z,as.y,Oi.z,0,-Oi.x,Fi.z,0,-Fi.x,as.z,0,-as.x,-Oi.y,Oi.x,0,-Fi.y,Fi.x,0,-as.y,as.x,0];return!qc(t,Zs,Ys,$s,ta)||(t=[1,0,0,0,1,0,0,0,1],!qc(t,Zs,Ys,$s,ta))?!1:(na.crossVectors(Oi,Fi),t=[na.x,na.y,na.z],qc(t,Zs,Ys,$s,ta))}clampPoint(e,t){return t.copy(e).clamp(this.min,this.max)}distanceToPoint(e){return this.clampPoint(e,Zn).distanceTo(e)}getBoundingSphere(e){return this.isEmpty()?e.makeEmpty():(this.getCenter(e.center),e.radius=this.getSize(Zn).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:(bi[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(e),bi[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(e),bi[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(e),bi[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(e),bi[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(e),bi[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(e),bi[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(e),bi[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(e),this.setFromPoints(bi),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 bi=[new R,new R,new R,new R,new R,new R,new R,new R],Zn=new R,ea=new gt,Zs=new R,Ys=new R,$s=new R,Oi=new R,Fi=new R,as=new R,Jr=new R,ta=new R,na=new R,ls=new R;function qc(s,e,t,n,i){for(let r=0,o=s.length-3;r<=o;r+=3){ls.fromArray(s,r);const a=i.x*Math.abs(ls.x)+i.y*Math.abs(ls.y)+i.z*Math.abs(ls.z),l=e.dot(ls),c=t.dot(ls),h=n.dot(ls);if(Math.max(-Math.max(l,c,h),Math.min(l,c,h))>a)return!1}return!0}const cx=new gt,Qr=new R,Zc=new R;class ri{constructor(e=new R,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 n=this.center;t!==void 0?n.copy(t):cx.setFromPoints(e).getCenter(n);let i=0;for(let r=0,o=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;Qr.subVectors(e,this.center);const t=Qr.lengthSq();if(t>this.radius*this.radius){const n=Math.sqrt(t),i=(n-this.radius)*.5;this.center.addScaledVector(Qr,i/n),this.radius+=i}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):(Zc.subVectors(e.center,this.center).setLength(e.radius),this.expandByPoint(Qr.copy(e.center).add(Zc)),this.expandByPoint(Qr.copy(e.center).sub(Zc))),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 yi=new R,Yc=new R,ia=new R,zi=new R,$c=new R,sa=new R,Kc=new R;class Hi{constructor(e=new R,t=new R(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,yi)),this}closestPointToPoint(e,t){t.subVectors(e,this.origin);const n=t.dot(this.direction);return n<0?t.copy(this.origin):t.copy(this.origin).addScaledVector(this.direction,n)}distanceToPoint(e){return Math.sqrt(this.distanceSqToPoint(e))}distanceSqToPoint(e){const t=yi.subVectors(e,this.origin).dot(this.direction);return t<0?this.origin.distanceToSquared(e):(yi.copy(this.origin).addScaledVector(this.direction,t),yi.distanceToSquared(e))}distanceSqToSegment(e,t,n,i){Yc.copy(e).add(t).multiplyScalar(.5),ia.copy(t).sub(e).normalize(),zi.copy(this.origin).sub(Yc);const r=e.distanceTo(t)*.5,o=-this.direction.dot(ia),a=zi.dot(this.direction),l=-zi.dot(ia),c=zi.lengthSq(),h=Math.abs(1-o*o);let u,f,d,m;if(h>0)if(u=o*l-a,f=o*a-l,m=r*h,u>=0)if(f>=-m)if(f<=m){const p=1/h;u*=p,f*=p,d=u*(u+o*f+2*a)+f*(o*u+f+2*l)+c}else f=r,u=Math.max(0,-(o*f+a)),d=-u*u+f*(f+2*l)+c;else f=-r,u=Math.max(0,-(o*f+a)),d=-u*u+f*(f+2*l)+c;else f<=-m?(u=Math.max(0,-(-o*r+a)),f=u>0?-r:Math.min(Math.max(-r,-l),r),d=-u*u+f*(f+2*l)+c):f<=m?(u=0,f=Math.min(Math.max(-r,-l),r),d=f*(f+2*l)+c):(u=Math.max(0,-(o*r+a)),f=u>0?r:Math.min(Math.max(-r,-l),r),d=-u*u+f*(f+2*l)+c);else f=o>0?-r:r,u=Math.max(0,-(o*f+a)),d=-u*u+f*(f+2*l)+c;return n&&n.copy(this.origin).addScaledVector(this.direction,u),i&&i.copy(Yc).addScaledVector(ia,f),d}intersectSphere(e,t){yi.subVectors(e.center,this.origin);const n=yi.dot(this.direction),i=yi.dot(yi)-n*n,r=e.radius*e.radius;if(i>r)return null;const o=Math.sqrt(r-i),a=n-o,l=n+o;return l<0?null:a<0?this.at(l,t):this.at(a,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 n=-(this.origin.dot(e.normal)+e.constant)/t;return n>=0?n:null}intersectPlane(e,t){const n=this.distanceToPlane(e);return n===null?null:this.at(n,t)}intersectsPlane(e){const t=e.distanceToPoint(this.origin);return t===0||e.normal.dot(this.direction)*t<0}intersectBox(e,t){let n,i,r,o,a,l;const c=1/this.direction.x,h=1/this.direction.y,u=1/this.direction.z,f=this.origin;return c>=0?(n=(e.min.x-f.x)*c,i=(e.max.x-f.x)*c):(n=(e.max.x-f.x)*c,i=(e.min.x-f.x)*c),h>=0?(r=(e.min.y-f.y)*h,o=(e.max.y-f.y)*h):(r=(e.max.y-f.y)*h,o=(e.min.y-f.y)*h),n>o||r>i||((r>n||isNaN(n))&&(n=r),(o=0?(a=(e.min.z-f.z)*u,l=(e.max.z-f.z)*u):(a=(e.max.z-f.z)*u,l=(e.min.z-f.z)*u),n>l||a>i)||((a>n||n!==n)&&(n=a),(l=0?n:i,t)}intersectsBox(e){return this.intersectBox(e,yi)!==null}intersectTriangle(e,t,n,i,r){$c.subVectors(t,e),sa.subVectors(n,e),Kc.crossVectors($c,sa);let o=this.direction.dot(Kc),a;if(o>0){if(i)return null;a=1}else if(o<0)a=-1,o=-o;else return null;zi.subVectors(this.origin,e);const l=a*this.direction.dot(sa.crossVectors(zi,sa));if(l<0)return null;const c=a*this.direction.dot($c.cross(zi));if(c<0||l+c>o)return null;const h=-a*zi.dot(Kc);return h<0?null:this.at(h/o,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 De{constructor(e,t,n,i,r,o,a,l,c,h,u,f,d,m,p,x){De.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,n,i,r,o,a,l,c,h,u,f,d,m,p,x)}set(e,t,n,i,r,o,a,l,c,h,u,f,d,m,p,x){const g=this.elements;return g[0]=e,g[4]=t,g[8]=n,g[12]=i,g[1]=r,g[5]=o,g[9]=a,g[13]=l,g[2]=c,g[6]=h,g[10]=u,g[14]=f,g[3]=d,g[7]=m,g[11]=p,g[15]=x,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 De().fromArray(this.elements)}copy(e){const t=this.elements,n=e.elements;return t[0]=n[0],t[1]=n[1],t[2]=n[2],t[3]=n[3],t[4]=n[4],t[5]=n[5],t[6]=n[6],t[7]=n[7],t[8]=n[8],t[9]=n[9],t[10]=n[10],t[11]=n[11],t[12]=n[12],t[13]=n[13],t[14]=n[14],t[15]=n[15],this}copyPosition(e){const t=this.elements,n=e.elements;return t[12]=n[12],t[13]=n[13],t[14]=n[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,n){return e.setFromMatrixColumn(this,0),t.setFromMatrixColumn(this,1),n.setFromMatrixColumn(this,2),this}makeBasis(e,t,n){return this.set(e.x,t.x,n.x,0,e.y,t.y,n.y,0,e.z,t.z,n.z,0,0,0,0,1),this}extractRotation(e){const t=this.elements,n=e.elements,i=1/Ks.setFromMatrixColumn(e,0).length(),r=1/Ks.setFromMatrixColumn(e,1).length(),o=1/Ks.setFromMatrixColumn(e,2).length();return t[0]=n[0]*i,t[1]=n[1]*i,t[2]=n[2]*i,t[3]=0,t[4]=n[4]*r,t[5]=n[5]*r,t[6]=n[6]*r,t[7]=0,t[8]=n[8]*o,t[9]=n[9]*o,t[10]=n[10]*o,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this}makeRotationFromEuler(e){const t=this.elements,n=e.x,i=e.y,r=e.z,o=Math.cos(n),a=Math.sin(n),l=Math.cos(i),c=Math.sin(i),h=Math.cos(r),u=Math.sin(r);if(e.order==="XYZ"){const f=o*h,d=o*u,m=a*h,p=a*u;t[0]=l*h,t[4]=-l*u,t[8]=c,t[1]=d+m*c,t[5]=f-p*c,t[9]=-a*l,t[2]=p-f*c,t[6]=m+d*c,t[10]=o*l}else if(e.order==="YXZ"){const f=l*h,d=l*u,m=c*h,p=c*u;t[0]=f+p*a,t[4]=m*a-d,t[8]=o*c,t[1]=o*u,t[5]=o*h,t[9]=-a,t[2]=d*a-m,t[6]=p+f*a,t[10]=o*l}else if(e.order==="ZXY"){const f=l*h,d=l*u,m=c*h,p=c*u;t[0]=f-p*a,t[4]=-o*u,t[8]=m+d*a,t[1]=d+m*a,t[5]=o*h,t[9]=p-f*a,t[2]=-o*c,t[6]=a,t[10]=o*l}else if(e.order==="ZYX"){const f=o*h,d=o*u,m=a*h,p=a*u;t[0]=l*h,t[4]=m*c-d,t[8]=f*c+p,t[1]=l*u,t[5]=p*c+f,t[9]=d*c-m,t[2]=-c,t[6]=a*l,t[10]=o*l}else if(e.order==="YZX"){const f=o*l,d=o*c,m=a*l,p=a*c;t[0]=l*h,t[4]=p-f*u,t[8]=m*u+d,t[1]=u,t[5]=o*h,t[9]=-a*h,t[2]=-c*h,t[6]=d*u+m,t[10]=f-p*u}else if(e.order==="XZY"){const f=o*l,d=o*c,m=a*l,p=a*c;t[0]=l*h,t[4]=-u,t[8]=c*h,t[1]=f*u+p,t[5]=o*h,t[9]=d*u-m,t[2]=m*u-d,t[6]=a*h,t[10]=p*u+f}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(hx,e,ux)}lookAt(e,t,n){const i=this.elements;return Mn.subVectors(e,t),Mn.lengthSq()===0&&(Mn.z=1),Mn.normalize(),Vi.crossVectors(n,Mn),Vi.lengthSq()===0&&(Math.abs(n.z)===1?Mn.x+=1e-4:Mn.z+=1e-4,Mn.normalize(),Vi.crossVectors(n,Mn)),Vi.normalize(),ra.crossVectors(Mn,Vi),i[0]=Vi.x,i[4]=ra.x,i[8]=Mn.x,i[1]=Vi.y,i[5]=ra.y,i[9]=Mn.y,i[2]=Vi.z,i[6]=ra.z,i[10]=Mn.z,this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,t){const n=e.elements,i=t.elements,r=this.elements,o=n[0],a=n[4],l=n[8],c=n[12],h=n[1],u=n[5],f=n[9],d=n[13],m=n[2],p=n[6],x=n[10],g=n[14],b=n[3],v=n[7],y=n[11],M=n[15],E=i[0],C=i[4],P=i[8],_=i[12],S=i[1],I=i[5],A=i[9],B=i[13],w=i[2],F=i[6],W=i[10],X=i[14],$=i[3],Z=i[7],ie=i[11],j=i[15];return r[0]=o*E+a*S+l*w+c*$,r[4]=o*C+a*I+l*F+c*Z,r[8]=o*P+a*A+l*W+c*ie,r[12]=o*_+a*B+l*X+c*j,r[1]=h*E+u*S+f*w+d*$,r[5]=h*C+u*I+f*F+d*Z,r[9]=h*P+u*A+f*W+d*ie,r[13]=h*_+u*B+f*X+d*j,r[2]=m*E+p*S+x*w+g*$,r[6]=m*C+p*I+x*F+g*Z,r[10]=m*P+p*A+x*W+g*ie,r[14]=m*_+p*B+x*X+g*j,r[3]=b*E+v*S+y*w+M*$,r[7]=b*C+v*I+y*F+M*Z,r[11]=b*P+v*A+y*W+M*ie,r[15]=b*_+v*B+y*X+M*j,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],n=e[4],i=e[8],r=e[12],o=e[1],a=e[5],l=e[9],c=e[13],h=e[2],u=e[6],f=e[10],d=e[14],m=e[3],p=e[7],x=e[11],g=e[15];return m*(+r*l*u-i*c*u-r*a*f+n*c*f+i*a*d-n*l*d)+p*(+t*l*d-t*c*f+r*o*f-i*o*d+i*c*h-r*l*h)+x*(+t*c*u-t*a*d-r*o*u+n*o*d+r*a*h-n*c*h)+g*(-i*a*h-t*l*u+t*a*f+i*o*u-n*o*f+n*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,n){const i=this.elements;return e.isVector3?(i[12]=e.x,i[13]=e.y,i[14]=e.z):(i[12]=e,i[13]=t,i[14]=n),this}invert(){const e=this.elements,t=e[0],n=e[1],i=e[2],r=e[3],o=e[4],a=e[5],l=e[6],c=e[7],h=e[8],u=e[9],f=e[10],d=e[11],m=e[12],p=e[13],x=e[14],g=e[15],b=u*x*c-p*f*c+p*l*d-a*x*d-u*l*g+a*f*g,v=m*f*c-h*x*c-m*l*d+o*x*d+h*l*g-o*f*g,y=h*p*c-m*u*c+m*a*d-o*p*d-h*a*g+o*u*g,M=m*u*l-h*p*l-m*a*f+o*p*f+h*a*x-o*u*x,E=t*b+n*v+i*y+r*M;if(E===0)return this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);const C=1/E;return e[0]=b*C,e[1]=(p*f*r-u*x*r-p*i*d+n*x*d+u*i*g-n*f*g)*C,e[2]=(a*x*r-p*l*r+p*i*c-n*x*c-a*i*g+n*l*g)*C,e[3]=(u*l*r-a*f*r-u*i*c+n*f*c+a*i*d-n*l*d)*C,e[4]=v*C,e[5]=(h*x*r-m*f*r+m*i*d-t*x*d-h*i*g+t*f*g)*C,e[6]=(m*l*r-o*x*r-m*i*c+t*x*c+o*i*g-t*l*g)*C,e[7]=(o*f*r-h*l*r+h*i*c-t*f*c-o*i*d+t*l*d)*C,e[8]=y*C,e[9]=(m*u*r-h*p*r-m*n*d+t*p*d+h*n*g-t*u*g)*C,e[10]=(o*p*r-m*a*r+m*n*c-t*p*c-o*n*g+t*a*g)*C,e[11]=(h*a*r-o*u*r-h*n*c+t*u*c+o*n*d-t*a*d)*C,e[12]=M*C,e[13]=(h*p*i-m*u*i+m*n*f-t*p*f-h*n*x+t*u*x)*C,e[14]=(m*a*i-o*p*i-m*n*l+t*p*l+o*n*x-t*a*x)*C,e[15]=(o*u*i-h*a*i+h*n*l-t*u*l-o*n*f+t*a*f)*C,this}scale(e){const t=this.elements,n=e.x,i=e.y,r=e.z;return t[0]*=n,t[4]*=i,t[8]*=r,t[1]*=n,t[5]*=i,t[9]*=r,t[2]*=n,t[6]*=i,t[10]*=r,t[3]*=n,t[7]*=i,t[11]*=r,this}getMaxScaleOnAxis(){const e=this.elements,t=e[0]*e[0]+e[1]*e[1]+e[2]*e[2],n=e[4]*e[4]+e[5]*e[5]+e[6]*e[6],i=e[8]*e[8]+e[9]*e[9]+e[10]*e[10];return Math.sqrt(Math.max(t,n,i))}makeTranslation(e,t,n){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,n,0,0,0,1),this}makeRotationX(e){const t=Math.cos(e),n=Math.sin(e);return this.set(1,0,0,0,0,t,-n,0,0,n,t,0,0,0,0,1),this}makeRotationY(e){const t=Math.cos(e),n=Math.sin(e);return this.set(t,0,n,0,0,1,0,0,-n,0,t,0,0,0,0,1),this}makeRotationZ(e){const t=Math.cos(e),n=Math.sin(e);return this.set(t,-n,0,0,n,t,0,0,0,0,1,0,0,0,0,1),this}makeRotationAxis(e,t){const n=Math.cos(t),i=Math.sin(t),r=1-n,o=e.x,a=e.y,l=e.z,c=r*o,h=r*a;return this.set(c*o+n,c*a-i*l,c*l+i*a,0,c*a+i*l,h*a+n,h*l-i*o,0,c*l-i*a,h*l+i*o,r*l*l+n,0,0,0,0,1),this}makeScale(e,t,n){return this.set(e,0,0,0,0,t,0,0,0,0,n,0,0,0,0,1),this}makeShear(e,t,n,i,r,o){return this.set(1,n,r,0,e,1,o,0,t,i,1,0,0,0,0,1),this}compose(e,t,n){const i=this.elements,r=t._x,o=t._y,a=t._z,l=t._w,c=r+r,h=o+o,u=a+a,f=r*c,d=r*h,m=r*u,p=o*h,x=o*u,g=a*u,b=l*c,v=l*h,y=l*u,M=n.x,E=n.y,C=n.z;return i[0]=(1-(p+g))*M,i[1]=(d+y)*M,i[2]=(m-v)*M,i[3]=0,i[4]=(d-y)*E,i[5]=(1-(f+g))*E,i[6]=(x+b)*E,i[7]=0,i[8]=(m+v)*C,i[9]=(x-b)*C,i[10]=(1-(f+p))*C,i[11]=0,i[12]=e.x,i[13]=e.y,i[14]=e.z,i[15]=1,this}decompose(e,t,n){const i=this.elements;let r=Ks.set(i[0],i[1],i[2]).length();const o=Ks.set(i[4],i[5],i[6]).length(),a=Ks.set(i[8],i[9],i[10]).length();this.determinant()<0&&(r=-r),e.x=i[12],e.y=i[13],e.z=i[14],Yn.copy(this);const c=1/r,h=1/o,u=1/a;return Yn.elements[0]*=c,Yn.elements[1]*=c,Yn.elements[2]*=c,Yn.elements[4]*=h,Yn.elements[5]*=h,Yn.elements[6]*=h,Yn.elements[8]*=u,Yn.elements[9]*=u,Yn.elements[10]*=u,t.setFromRotationMatrix(Yn),n.x=r,n.y=o,n.z=a,this}makePerspective(e,t,n,i,r,o,a=si,l=!1){const c=this.elements,h=2*r/(t-e),u=2*r/(n-i),f=(t+e)/(t-e),d=(n+i)/(n-i);let m,p;if(l)m=r/(o-r),p=o*r/(o-r);else if(a===si)m=-(o+r)/(o-r),p=-2*o*r/(o-r);else if(a===Jo)m=-o/(o-r),p=-o*r/(o-r);else throw new Error("THREE.Matrix4.makePerspective(): Invalid coordinate system: "+a);return c[0]=h,c[4]=0,c[8]=f,c[12]=0,c[1]=0,c[5]=u,c[9]=d,c[13]=0,c[2]=0,c[6]=0,c[10]=m,c[14]=p,c[3]=0,c[7]=0,c[11]=-1,c[15]=0,this}makeOrthographic(e,t,n,i,r,o,a=si,l=!1){const c=this.elements,h=2/(t-e),u=2/(n-i),f=-(t+e)/(t-e),d=-(n+i)/(n-i);let m,p;if(l)m=1/(o-r),p=o/(o-r);else if(a===si)m=-2/(o-r),p=-(o+r)/(o-r);else if(a===Jo)m=-1/(o-r),p=-r/(o-r);else throw new Error("THREE.Matrix4.makeOrthographic(): Invalid coordinate system: "+a);return c[0]=h,c[4]=0,c[8]=0,c[12]=f,c[1]=0,c[5]=u,c[9]=0,c[13]=d,c[2]=0,c[6]=0,c[10]=m,c[14]=p,c[3]=0,c[7]=0,c[11]=0,c[15]=1,this}equals(e){const t=this.elements,n=e.elements;for(let i=0;i<16;i++)if(t[i]!==n[i])return!1;return!0}fromArray(e,t=0){for(let n=0;n<16;n++)this.elements[n]=e[n+t];return this}toArray(e=[],t=0){const n=this.elements;return e[t]=n[0],e[t+1]=n[1],e[t+2]=n[2],e[t+3]=n[3],e[t+4]=n[4],e[t+5]=n[5],e[t+6]=n[6],e[t+7]=n[7],e[t+8]=n[8],e[t+9]=n[9],e[t+10]=n[10],e[t+11]=n[11],e[t+12]=n[12],e[t+13]=n[13],e[t+14]=n[14],e[t+15]=n[15],e}}const Ks=new R,Yn=new De,hx=new R(0,0,0),ux=new R(1,1,1),Vi=new R,ra=new R,Mn=new R,Hd=new De,Vd=new Ln;class wn{constructor(e=0,t=0,n=0,i=wn.DEFAULT_ORDER){this.isEuler=!0,this._x=e,this._y=t,this._z=n,this._order=i}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,n,i=this._order){return this._x=e,this._y=t,this._z=n,this._order=i,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,n=!0){const i=e.elements,r=i[0],o=i[4],a=i[8],l=i[1],c=i[5],h=i[9],u=i[2],f=i[6],d=i[10];switch(t){case"XYZ":this._y=Math.asin(qe(a,-1,1)),Math.abs(a)<.9999999?(this._x=Math.atan2(-h,d),this._z=Math.atan2(-o,r)):(this._x=Math.atan2(f,c),this._z=0);break;case"YXZ":this._x=Math.asin(-qe(h,-1,1)),Math.abs(h)<.9999999?(this._y=Math.atan2(a,d),this._z=Math.atan2(l,c)):(this._y=Math.atan2(-u,r),this._z=0);break;case"ZXY":this._x=Math.asin(qe(f,-1,1)),Math.abs(f)<.9999999?(this._y=Math.atan2(-u,d),this._z=Math.atan2(-o,c)):(this._y=0,this._z=Math.atan2(l,r));break;case"ZYX":this._y=Math.asin(-qe(u,-1,1)),Math.abs(u)<.9999999?(this._x=Math.atan2(f,d),this._z=Math.atan2(l,r)):(this._x=0,this._z=Math.atan2(-o,c));break;case"YZX":this._z=Math.asin(qe(l,-1,1)),Math.abs(l)<.9999999?(this._x=Math.atan2(-h,c),this._y=Math.atan2(-u,r)):(this._x=0,this._y=Math.atan2(a,d));break;case"XZY":this._z=Math.asin(-qe(o,-1,1)),Math.abs(o)<.9999999?(this._x=Math.atan2(f,c),this._y=Math.atan2(a,r)):(this._x=Math.atan2(-h,d),this._y=0);break;default:ze("Euler: .setFromRotationMatrix() encountered an unknown order: "+t)}return this._order=t,n===!0&&this._onChangeCallback(),this}setFromQuaternion(e,t,n){return Hd.makeRotationFromQuaternion(e),this.setFromRotationMatrix(Hd,t,n)}setFromVector3(e,t=this._order){return this.set(e.x,e.y,e.z,t)}reorder(e){return Vd.setFromEuler(this),this.setFromQuaternion(Vd,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}}wn.DEFAULT_ORDER="XYZ";class Jc{constructor(){this.mask=1}set(e){this.mask=(1<>>0}enable(e){this.mask|=1<1){for(let t=0;t1){for(let n=0;n0&&(i.userData=this.userData),i.layers=this.layers.mask,i.matrix=this.matrix.toArray(),i.up=this.up.toArray(),this.matrixAutoUpdate===!1&&(i.matrixAutoUpdate=!1),this.isInstancedMesh&&(i.type="InstancedMesh",i.count=this.count,i.instanceMatrix=this.instanceMatrix.toJSON(),this.instanceColor!==null&&(i.instanceColor=this.instanceColor.toJSON())),this.isBatchedMesh&&(i.type="BatchedMesh",i.perObjectFrustumCulled=this.perObjectFrustumCulled,i.sortObjects=this.sortObjects,i.drawRanges=this._drawRanges,i.reservedRanges=this._reservedRanges,i.geometryInfo=this._geometryInfo.map(a=>({...a,boundingBox:a.boundingBox?a.boundingBox.toJSON():void 0,boundingSphere:a.boundingSphere?a.boundingSphere.toJSON():void 0})),i.instanceInfo=this._instanceInfo.map(a=>({...a})),i.availableInstanceIds=this._availableInstanceIds.slice(),i.availableGeometryIds=this._availableGeometryIds.slice(),i.nextIndexStart=this._nextIndexStart,i.nextVertexStart=this._nextVertexStart,i.geometryCount=this._geometryCount,i.maxInstanceCount=this._maxInstanceCount,i.maxVertexCount=this._maxVertexCount,i.maxIndexCount=this._maxIndexCount,i.geometryInitialized=this._geometryInitialized,i.matricesTexture=this._matricesTexture.toJSON(e),i.indirectTexture=this._indirectTexture.toJSON(e),this._colorsTexture!==null&&(i.colorsTexture=this._colorsTexture.toJSON(e)),this.boundingSphere!==null&&(i.boundingSphere=this.boundingSphere.toJSON()),this.boundingBox!==null&&(i.boundingBox=this.boundingBox.toJSON()));function r(a,l){return a[l.uuid]===void 0&&(a[l.uuid]=l.toJSON(e)),l.uuid}if(this.isScene)this.background&&(this.background.isColor?i.background=this.background.toJSON():this.background.isTexture&&(i.background=this.background.toJSON(e).uuid)),this.environment&&this.environment.isTexture&&this.environment.isRenderTargetTexture!==!0&&(i.environment=this.environment.toJSON(e).uuid);else if(this.isMesh||this.isLine||this.isPoints){i.geometry=r(e.geometries,this.geometry);const a=this.geometry.parameters;if(a!==void 0&&a.shapes!==void 0){const l=a.shapes;if(Array.isArray(l))for(let c=0,h=l.length;c0){i.children=[];for(let a=0;a0){i.animations=[];for(let a=0;a0&&(n.geometries=a),l.length>0&&(n.materials=l),c.length>0&&(n.textures=c),h.length>0&&(n.images=h),u.length>0&&(n.shapes=u),f.length>0&&(n.skeletons=f),d.length>0&&(n.animations=d),m.length>0&&(n.nodes=m)}return n.object=i,n;function o(a){const l=[];for(const c in a){const h=a[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 n=0;n0?i.multiplyScalar(1/Math.sqrt(r)):i.set(0,0,0)}static getBarycoord(e,t,n,i,r){$n.subVectors(i,t),Mi.subVectors(n,t),eh.subVectors(e,t);const o=$n.dot($n),a=$n.dot(Mi),l=$n.dot(eh),c=Mi.dot(Mi),h=Mi.dot(eh),u=o*c-a*a;if(u===0)return r.set(0,0,0),null;const f=1/u,d=(c*l-a*h)*f,m=(o*h-a*l)*f;return r.set(1-d-m,m,d)}static containsPoint(e,t,n,i){return this.getBarycoord(e,t,n,i,wi)===null?!1:wi.x>=0&&wi.y>=0&&wi.x+wi.y<=1}static getInterpolation(e,t,n,i,r,o,a,l){return this.getBarycoord(e,t,n,i,wi)===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,wi.x),l.addScaledVector(o,wi.y),l.addScaledVector(a,wi.z),l)}static getInterpolatedAttribute(e,t,n,i,r,o){return sh.setScalar(0),rh.setScalar(0),oh.setScalar(0),sh.fromBufferAttribute(e,t),rh.fromBufferAttribute(e,n),oh.fromBufferAttribute(e,i),o.setScalar(0),o.addScaledVector(sh,r.x),o.addScaledVector(rh,r.y),o.addScaledVector(oh,r.z),o}static isFrontFacing(e,t,n,i){return $n.subVectors(n,t),Mi.subVectors(e,t),$n.cross(Mi).dot(i)<0}set(e,t,n){return this.a.copy(e),this.b.copy(t),this.c.copy(n),this}setFromPointsAndIndices(e,t,n,i){return this.a.copy(e[t]),this.b.copy(e[n]),this.c.copy(e[i]),this}setFromAttributeAndIndices(e,t,n,i){return this.a.fromBufferAttribute(e,t),this.b.fromBufferAttribute(e,n),this.c.fromBufferAttribute(e,i),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 $n.subVectors(this.c,this.b),Mi.subVectors(this.a,this.b),$n.cross(Mi).length()*.5}getMidpoint(e){return e.addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)}getNormal(e){return xt.getNormal(this.a,this.b,this.c,e)}getPlane(e){return e.setFromCoplanarPoints(this.a,this.b,this.c)}getBarycoord(e,t){return xt.getBarycoord(e,this.a,this.b,this.c,t)}getInterpolation(e,t,n,i,r){return xt.getInterpolation(e,this.a,this.b,this.c,t,n,i,r)}containsPoint(e){return xt.containsPoint(e,this.a,this.b,this.c)}isFrontFacing(e){return xt.isFrontFacing(this.a,this.b,this.c,e)}intersectsBox(e){return e.intersectsTriangle(this)}closestPointToPoint(e,t){const n=this.a,i=this.b,r=this.c;let o,a;er.subVectors(i,n),tr.subVectors(r,n),th.subVectors(e,n);const l=er.dot(th),c=tr.dot(th);if(l<=0&&c<=0)return t.copy(n);nh.subVectors(e,i);const h=er.dot(nh),u=tr.dot(nh);if(h>=0&&u<=h)return t.copy(i);const f=l*u-h*c;if(f<=0&&l>=0&&h<=0)return o=l/(l-h),t.copy(n).addScaledVector(er,o);ih.subVectors(e,r);const d=er.dot(ih),m=tr.dot(ih);if(m>=0&&d<=m)return t.copy(r);const p=d*c-l*m;if(p<=0&&c>=0&&m<=0)return a=c/(c-m),t.copy(n).addScaledVector(tr,a);const x=h*m-d*u;if(x<=0&&u-h>=0&&d-m>=0)return Zd.subVectors(r,i),a=(u-h)/(u-h+(d-m)),t.copy(i).addScaledVector(Zd,a);const g=1/(x+p+f);return o=p*g,a=f*g,t.copy(n).addScaledVector(er,o).addScaledVector(tr,a)}equals(e){return e.a.equals(this.a)&&e.b.equals(this.b)&&e.c.equals(this.c)}}const Yd={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},Gi={h:0,s:0,l:0},aa={h:0,s:0,l:0};function ah(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 He{constructor(e,t,n){return this.isColor=!0,this.r=1,this.g=1,this.b=1,this.set(e,t,n)}set(e,t,n){if(t===void 0&&n===void 0){const i=e;i&&i.isColor?this.copy(i):typeof i=="number"?this.setHex(i):typeof i=="string"&&this.setStyle(i)}else this.setRGB(e,t,n);return this}setScalar(e){return this.r=e,this.g=e,this.b=e,this}setHex(e,t=At){return e=Math.floor(e),this.r=(e>>16&255)/255,this.g=(e>>8&255)/255,this.b=(e&255)/255,it.colorSpaceToWorking(this,t),this}setRGB(e,t,n,i=it.workingColorSpace){return this.r=e,this.g=t,this.b=n,it.colorSpaceToWorking(this,i),this}setHSL(e,t,n,i=it.workingColorSpace){if(e=Hc(e,1),t=qe(t,0,1),n=qe(n,0,1),t===0)this.r=this.g=this.b=n;else{const r=n<=.5?n*(1+t):n+t-n*t,o=2*n-r;this.r=ah(o,r,e+1/3),this.g=ah(o,r,e),this.b=ah(o,r,e-1/3)}return it.colorSpaceToWorking(this,i),this}setStyle(e,t=At){function n(r){r!==void 0&&parseFloat(r)<1&&ze("Color: Alpha component of "+e+" will be ignored.")}let i;if(i=/^(\w+)\(([^\)]*)\)/.exec(e)){let r;const o=i[1],a=i[2];switch(o){case"rgb":case"rgba":if(r=/^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(a))return n(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(a))return n(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(a))return n(r[4]),this.setHSL(parseFloat(r[1])/360,parseFloat(r[2])/100,parseFloat(r[3])/100,t);break;default:ze("Color: Unknown color model "+e)}}else if(i=/^\#([A-Fa-f\d]+)$/.exec(e)){const r=i[1],o=r.length;if(o===3)return this.setRGB(parseInt(r.charAt(0),16)/15,parseInt(r.charAt(1),16)/15,parseInt(r.charAt(2),16)/15,t);if(o===6)return this.setHex(parseInt(r,16),t);ze("Color: Invalid hex color "+e)}else if(e&&e.length>0)return this.setColorName(e,t);return this}setColorName(e,t=At){const n=Yd[e.toLowerCase()];return n!==void 0?this.setHex(n,t):ze("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=vi(e.r),this.g=vi(e.g),this.b=vi(e.b),this}copyLinearToSRGB(e){return this.r=js(e.r),this.g=js(e.g),this.b=js(e.b),this}convertSRGBToLinear(){return this.copySRGBToLinear(this),this}convertLinearToSRGB(){return this.copyLinearToSRGB(this),this}getHex(e=At){return it.workingToColorSpace(sn.copy(this),e),Math.round(qe(sn.r*255,0,255))*65536+Math.round(qe(sn.g*255,0,255))*256+Math.round(qe(sn.b*255,0,255))}getHexString(e=At){return("000000"+this.getHex(e).toString(16)).slice(-6)}getHSL(e,t=it.workingColorSpace){it.workingToColorSpace(sn.copy(this),t);const n=sn.r,i=sn.g,r=sn.b,o=Math.max(n,i,r),a=Math.min(n,i,r);let l,c;const h=(a+o)/2;if(a===o)l=0,c=0;else{const u=o-a;switch(c=h<=.5?u/(o+a):u/(2-o-a),o){case n:l=(i-r)/u+(i0!=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 n=e[t];if(n===void 0){ze(`Material: parameter '${t}' has value of undefined.`);continue}const i=this[t];if(i===void 0){ze(`Material: '${t}' is not a property of THREE.${this.type}.`);continue}i&&i.isColor?i.set(n):i&&i.isVector3&&n&&n.isVector3?i.copy(n):this[t]=n}}toJSON(e){const t=e===void 0||typeof e=="string";t&&(e={textures:{},images:{}});const n={metadata:{version:4.7,type:"Material",generator:"Material.toJSON"}};n.uuid=this.uuid,n.type=this.type,this.name!==""&&(n.name=this.name),this.color&&this.color.isColor&&(n.color=this.color.getHex()),this.roughness!==void 0&&(n.roughness=this.roughness),this.metalness!==void 0&&(n.metalness=this.metalness),this.sheen!==void 0&&(n.sheen=this.sheen),this.sheenColor&&this.sheenColor.isColor&&(n.sheenColor=this.sheenColor.getHex()),this.sheenRoughness!==void 0&&(n.sheenRoughness=this.sheenRoughness),this.emissive&&this.emissive.isColor&&(n.emissive=this.emissive.getHex()),this.emissiveIntensity!==void 0&&this.emissiveIntensity!==1&&(n.emissiveIntensity=this.emissiveIntensity),this.specular&&this.specular.isColor&&(n.specular=this.specular.getHex()),this.specularIntensity!==void 0&&(n.specularIntensity=this.specularIntensity),this.specularColor&&this.specularColor.isColor&&(n.specularColor=this.specularColor.getHex()),this.shininess!==void 0&&(n.shininess=this.shininess),this.clearcoat!==void 0&&(n.clearcoat=this.clearcoat),this.clearcoatRoughness!==void 0&&(n.clearcoatRoughness=this.clearcoatRoughness),this.clearcoatMap&&this.clearcoatMap.isTexture&&(n.clearcoatMap=this.clearcoatMap.toJSON(e).uuid),this.clearcoatRoughnessMap&&this.clearcoatRoughnessMap.isTexture&&(n.clearcoatRoughnessMap=this.clearcoatRoughnessMap.toJSON(e).uuid),this.clearcoatNormalMap&&this.clearcoatNormalMap.isTexture&&(n.clearcoatNormalMap=this.clearcoatNormalMap.toJSON(e).uuid,n.clearcoatNormalScale=this.clearcoatNormalScale.toArray()),this.sheenColorMap&&this.sheenColorMap.isTexture&&(n.sheenColorMap=this.sheenColorMap.toJSON(e).uuid),this.sheenRoughnessMap&&this.sheenRoughnessMap.isTexture&&(n.sheenRoughnessMap=this.sheenRoughnessMap.toJSON(e).uuid),this.dispersion!==void 0&&(n.dispersion=this.dispersion),this.iridescence!==void 0&&(n.iridescence=this.iridescence),this.iridescenceIOR!==void 0&&(n.iridescenceIOR=this.iridescenceIOR),this.iridescenceThicknessRange!==void 0&&(n.iridescenceThicknessRange=this.iridescenceThicknessRange),this.iridescenceMap&&this.iridescenceMap.isTexture&&(n.iridescenceMap=this.iridescenceMap.toJSON(e).uuid),this.iridescenceThicknessMap&&this.iridescenceThicknessMap.isTexture&&(n.iridescenceThicknessMap=this.iridescenceThicknessMap.toJSON(e).uuid),this.anisotropy!==void 0&&(n.anisotropy=this.anisotropy),this.anisotropyRotation!==void 0&&(n.anisotropyRotation=this.anisotropyRotation),this.anisotropyMap&&this.anisotropyMap.isTexture&&(n.anisotropyMap=this.anisotropyMap.toJSON(e).uuid),this.map&&this.map.isTexture&&(n.map=this.map.toJSON(e).uuid),this.matcap&&this.matcap.isTexture&&(n.matcap=this.matcap.toJSON(e).uuid),this.alphaMap&&this.alphaMap.isTexture&&(n.alphaMap=this.alphaMap.toJSON(e).uuid),this.lightMap&&this.lightMap.isTexture&&(n.lightMap=this.lightMap.toJSON(e).uuid,n.lightMapIntensity=this.lightMapIntensity),this.aoMap&&this.aoMap.isTexture&&(n.aoMap=this.aoMap.toJSON(e).uuid,n.aoMapIntensity=this.aoMapIntensity),this.bumpMap&&this.bumpMap.isTexture&&(n.bumpMap=this.bumpMap.toJSON(e).uuid,n.bumpScale=this.bumpScale),this.normalMap&&this.normalMap.isTexture&&(n.normalMap=this.normalMap.toJSON(e).uuid,n.normalMapType=this.normalMapType,n.normalScale=this.normalScale.toArray()),this.displacementMap&&this.displacementMap.isTexture&&(n.displacementMap=this.displacementMap.toJSON(e).uuid,n.displacementScale=this.displacementScale,n.displacementBias=this.displacementBias),this.roughnessMap&&this.roughnessMap.isTexture&&(n.roughnessMap=this.roughnessMap.toJSON(e).uuid),this.metalnessMap&&this.metalnessMap.isTexture&&(n.metalnessMap=this.metalnessMap.toJSON(e).uuid),this.emissiveMap&&this.emissiveMap.isTexture&&(n.emissiveMap=this.emissiveMap.toJSON(e).uuid),this.specularMap&&this.specularMap.isTexture&&(n.specularMap=this.specularMap.toJSON(e).uuid),this.specularIntensityMap&&this.specularIntensityMap.isTexture&&(n.specularIntensityMap=this.specularIntensityMap.toJSON(e).uuid),this.specularColorMap&&this.specularColorMap.isTexture&&(n.specularColorMap=this.specularColorMap.toJSON(e).uuid),this.envMap&&this.envMap.isTexture&&(n.envMap=this.envMap.toJSON(e).uuid,this.combine!==void 0&&(n.combine=this.combine)),this.envMapRotation!==void 0&&(n.envMapRotation=this.envMapRotation.toArray()),this.envMapIntensity!==void 0&&(n.envMapIntensity=this.envMapIntensity),this.reflectivity!==void 0&&(n.reflectivity=this.reflectivity),this.refractionRatio!==void 0&&(n.refractionRatio=this.refractionRatio),this.gradientMap&&this.gradientMap.isTexture&&(n.gradientMap=this.gradientMap.toJSON(e).uuid),this.transmission!==void 0&&(n.transmission=this.transmission),this.transmissionMap&&this.transmissionMap.isTexture&&(n.transmissionMap=this.transmissionMap.toJSON(e).uuid),this.thickness!==void 0&&(n.thickness=this.thickness),this.thicknessMap&&this.thicknessMap.isTexture&&(n.thicknessMap=this.thicknessMap.toJSON(e).uuid),this.attenuationDistance!==void 0&&this.attenuationDistance!==1/0&&(n.attenuationDistance=this.attenuationDistance),this.attenuationColor!==void 0&&(n.attenuationColor=this.attenuationColor.getHex()),this.size!==void 0&&(n.size=this.size),this.shadowSide!==null&&(n.shadowSide=this.shadowSide),this.sizeAttenuation!==void 0&&(n.sizeAttenuation=this.sizeAttenuation),this.blending!==Os&&(n.blending=this.blending),this.side!==Pn&&(n.side=this.side),this.vertexColors===!0&&(n.vertexColors=!0),this.opacity<1&&(n.opacity=this.opacity),this.transparent===!0&&(n.transparent=!0),this.blendSrc!==Vl&&(n.blendSrc=this.blendSrc),this.blendDst!==Gl&&(n.blendDst=this.blendDst),this.blendEquation!==Gn&&(n.blendEquation=this.blendEquation),this.blendSrcAlpha!==null&&(n.blendSrcAlpha=this.blendSrcAlpha),this.blendDstAlpha!==null&&(n.blendDstAlpha=this.blendDstAlpha),this.blendEquationAlpha!==null&&(n.blendEquationAlpha=this.blendEquationAlpha),this.blendColor&&this.blendColor.isColor&&(n.blendColor=this.blendColor.getHex()),this.blendAlpha!==0&&(n.blendAlpha=this.blendAlpha),this.depthFunc!==Fs&&(n.depthFunc=this.depthFunc),this.depthTest===!1&&(n.depthTest=this.depthTest),this.depthWrite===!1&&(n.depthWrite=this.depthWrite),this.colorWrite===!1&&(n.colorWrite=this.colorWrite),this.stencilWriteMask!==255&&(n.stencilWriteMask=this.stencilWriteMask),this.stencilFunc!==Ld&&(n.stencilFunc=this.stencilFunc),this.stencilRef!==0&&(n.stencilRef=this.stencilRef),this.stencilFuncMask!==255&&(n.stencilFuncMask=this.stencilFuncMask),this.stencilFail!==Ws&&(n.stencilFail=this.stencilFail),this.stencilZFail!==Ws&&(n.stencilZFail=this.stencilZFail),this.stencilZPass!==Ws&&(n.stencilZPass=this.stencilZPass),this.stencilWrite===!0&&(n.stencilWrite=this.stencilWrite),this.rotation!==void 0&&this.rotation!==0&&(n.rotation=this.rotation),this.polygonOffset===!0&&(n.polygonOffset=!0),this.polygonOffsetFactor!==0&&(n.polygonOffsetFactor=this.polygonOffsetFactor),this.polygonOffsetUnits!==0&&(n.polygonOffsetUnits=this.polygonOffsetUnits),this.linewidth!==void 0&&this.linewidth!==1&&(n.linewidth=this.linewidth),this.dashSize!==void 0&&(n.dashSize=this.dashSize),this.gapSize!==void 0&&(n.gapSize=this.gapSize),this.scale!==void 0&&(n.scale=this.scale),this.dithering===!0&&(n.dithering=!0),this.alphaTest>0&&(n.alphaTest=this.alphaTest),this.alphaHash===!0&&(n.alphaHash=!0),this.alphaToCoverage===!0&&(n.alphaToCoverage=!0),this.premultipliedAlpha===!0&&(n.premultipliedAlpha=!0),this.forceSinglePass===!0&&(n.forceSinglePass=!0),this.wireframe===!0&&(n.wireframe=!0),this.wireframeLinewidth>1&&(n.wireframeLinewidth=this.wireframeLinewidth),this.wireframeLinecap!=="round"&&(n.wireframeLinecap=this.wireframeLinecap),this.wireframeLinejoin!=="round"&&(n.wireframeLinejoin=this.wireframeLinejoin),this.flatShading===!0&&(n.flatShading=!0),this.visible===!1&&(n.visible=!1),this.toneMapped===!1&&(n.toneMapped=!1),this.fog===!1&&(n.fog=!1),Object.keys(this.userData).length>0&&(n.userData=this.userData);function i(r){const o=[];for(const a in r){const l=r[a];delete l.metadata,o.push(l)}return o}if(t){const r=i(e.textures),o=i(e.images);r.length>0&&(n.textures=r),o.length>0&&(n.images=o)}return n}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 n=null;if(t!==null){const i=t.length;n=new Array(i);for(let r=0;r!==i;++r)n[r]=t[r].clone()}return this.clippingPlanes=n,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 Xt extends Sn{constructor(e){super(),this.isMeshBasicMaterial=!0,this.type="MeshBasicMaterial",this.color=new He(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 wn,this.combine=Ql,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 Nt=new R,la=new ue;let xx=0;class vt{constructor(e,t,n=!1){if(Array.isArray(e))throw new TypeError("THREE.BufferAttribute: array should be a Typed Array.");this.isBufferAttribute=!0,Object.defineProperty(this,"id",{value:xx++}),this.name="",this.array=e,this.itemSize=t,this.count=e!==void 0?e.length/t:0,this.normalized=n,this.usage=zc,this.updateRanges=[],this.gpuType=Xn,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,n){e*=this.itemSize,n*=t.itemSize;for(let i=0,r=this.itemSize;it.count&&ze("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 gt);const e=this.attributes.position,t=this.morphAttributes.position;if(e&&e.isGLBufferAttribute){Qe("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 n=0,i=t.length;n0&&(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 n=this.attributes;for(const l in n){const c=n[l];e.data.attributes[l]=c.toJSON(e.data)}const i={};let r=!1;for(const l in this.morphAttributes){const c=this.morphAttributes[l],h=[];for(let u=0,f=c.length;u0&&(i[l]=h,r=!0)}r&&(e.data.morphAttributes=i,e.data.morphTargetsRelative=this.morphTargetsRelative);const o=this.groups;o.length>0&&(e.data.groups=JSON.parse(JSON.stringify(o)));const a=this.boundingSphere;return a!==null&&(e.data.boundingSphere=a.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 n=e.index;n!==null&&this.setIndex(n.clone());const i=e.attributes;for(const c in i){const h=i[c];this.setAttribute(c,h.clone(t))}const r=e.morphAttributes;for(const c in r){const h=[],u=r[c];for(let f=0,d=u.length;f0){const i=t[n[0]];if(i!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let r=0,o=i.length;r(e.far-e.near)**2))&&(Jd.copy(r).invert(),cs.copy(e.ray).applyMatrix4(Jd),!(n.boundingBox!==null&&cs.intersectsBox(n.boundingBox)===!1)&&this._computeIntersections(e,t,cs)))}_computeIntersections(e,t,n){let i;const r=this.geometry,o=this.material,a=r.index,l=r.attributes.position,c=r.attributes.uv,h=r.attributes.uv1,u=r.attributes.normal,f=r.groups,d=r.drawRange;if(a!==null)if(Array.isArray(o))for(let m=0,p=f.length;mt.far?null:{distance:c,point:pa.clone(),object:s}}function ma(s,e,t,n,i,r,o,a,l,c){s.getVertexPosition(a,ha),s.getVertexPosition(l,ua),s.getVertexPosition(c,da);const h=bx(s,e,t,n,ha,ua,da,ef);if(h){const u=new R;xt.getBarycoord(ef,ha,ua,da,u),i&&(h.uv=xt.getInterpolatedAttribute(i,a,l,c,u,new ue)),r&&(h.uv1=xt.getInterpolatedAttribute(r,a,l,c,u,new ue)),o&&(h.normal=xt.getInterpolatedAttribute(o,a,l,c,u,new R),h.normal.dot(n.direction)>0&&h.normal.multiplyScalar(-1));const f={a,b:l,c,normal:new R,materialIndex:0};xt.getNormal(ha,ua,da,f.normal),h.face=f,h.barycoord=u}return h}class Wi extends bt{constructor(e=1,t=1,n=1,i=1,r=1,o=1){super(),this.type="BoxGeometry",this.parameters={width:e,height:t,depth:n,widthSegments:i,heightSegments:r,depthSegments:o};const a=this;i=Math.floor(i),r=Math.floor(r),o=Math.floor(o);const l=[],c=[],h=[],u=[];let f=0,d=0;m("z","y","x",-1,-1,n,t,e,o,r,0),m("z","y","x",1,-1,n,t,-e,o,r,1),m("x","z","y",1,1,e,n,t,i,o,2),m("x","z","y",1,-1,e,n,-t,i,o,3),m("x","y","z",1,-1,e,t,n,i,r,4),m("x","y","z",-1,-1,e,t,-n,i,r,5),this.setIndex(l),this.setAttribute("position",new rn(c,3)),this.setAttribute("normal",new rn(h,3)),this.setAttribute("uv",new rn(u,2));function m(p,x,g,b,v,y,M,E,C,P,_){const S=y/C,I=M/P,A=y/2,B=M/2,w=E/2,F=C+1,W=P+1;let X=0,$=0;const Z=new R;for(let ie=0;ie0?1:-1,h.push(Z.x,Z.y,Z.z),u.push(Y/C),u.push(1-ie/P),X+=1}}for(let ie=0;ie0&&(t.defines=this.defines),t.vertexShader=this.vertexShader,t.fragmentShader=this.fragmentShader,t.lights=this.lights,t.clipping=this.clipping;const n={};for(const i in this.extensions)this.extensions[i]===!0&&(n[i]=!0);return Object.keys(n).length>0&&(t.extensions=n),t}}class nf extends wt{constructor(){super(),this.isCamera=!0,this.type="Camera",this.matrixWorldInverse=new De,this.projectionMatrix=new De,this.projectionMatrixInverse=new De,this.coordinateSystem=si,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 ji=new R,sf=new ue,rf=new ue;class on extends nf{constructor(e=50,t=1,n=.1,i=2e3){super(),this.isPerspectiveCamera=!0,this.type="PerspectiveCamera",this.fov=e,this.zoom=1,this.near=n,this.far=i,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=Xs*2*Math.atan(t),this.updateProjectionMatrix()}getFocalLength(){const e=Math.tan($r*.5*this.fov);return .5*this.getFilmHeight()/e}getEffectiveFOV(){return Xs*2*Math.atan(Math.tan($r*.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,n){ji.set(-1,-1,.5).applyMatrix4(this.projectionMatrixInverse),t.set(ji.x,ji.y).multiplyScalar(-e/ji.z),ji.set(1,1,.5).applyMatrix4(this.projectionMatrixInverse),n.set(ji.x,ji.y).multiplyScalar(-e/ji.z)}getViewSize(e,t){return this.getViewBounds(e,sf,rf),t.subVectors(rf,sf)}setViewOffset(e,t,n,i,r,o){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=n,this.view.offsetY=i,this.view.width=r,this.view.height=o,this.updateProjectionMatrix()}clearViewOffset(){this.view!==null&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){const e=this.near;let t=e*Math.tan($r*.5*this.fov)/this.zoom,n=2*t,i=this.aspect*n,r=-.5*i;const o=this.view;if(this.view!==null&&this.view.enabled){const l=o.fullWidth,c=o.fullHeight;r+=o.offsetX*i/l,t-=o.offsetY*n/c,i*=o.width/l,n*=o.height/c}const a=this.filmOffset;a!==0&&(r+=e*a/this.getFilmWidth()),this.projectionMatrix.makePerspective(r,r+i,t,t-n,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 sr=-90,rr=1;class wx extends wt{constructor(e,t,n){super(),this.type="CubeCamera",this.renderTarget=n,this.coordinateSystem=null,this.activeMipmapLevel=0;const i=new on(sr,rr,e,t);i.layers=this.layers,this.add(i);const r=new on(sr,rr,e,t);r.layers=this.layers,this.add(r);const o=new on(sr,rr,e,t);o.layers=this.layers,this.add(o);const a=new on(sr,rr,e,t);a.layers=this.layers,this.add(a);const l=new on(sr,rr,e,t);l.layers=this.layers,this.add(l);const c=new on(sr,rr,e,t);c.layers=this.layers,this.add(c)}updateCoordinateSystem(){const e=this.coordinateSystem,t=this.children.concat(),[n,i,r,o,a,l]=t;for(const c of t)this.remove(c);if(e===si)n.up.set(0,1,0),n.lookAt(1,0,0),i.up.set(0,1,0),i.lookAt(-1,0,0),r.up.set(0,0,-1),r.lookAt(0,1,0),o.up.set(0,0,1),o.lookAt(0,-1,0),a.up.set(0,1,0),a.lookAt(0,0,1),l.up.set(0,1,0),l.lookAt(0,0,-1);else if(e===Jo)n.up.set(0,-1,0),n.lookAt(-1,0,0),i.up.set(0,-1,0),i.lookAt(1,0,0),r.up.set(0,0,1),r.lookAt(0,1,0),o.up.set(0,0,-1),o.lookAt(0,-1,0),a.up.set(0,-1,0),a.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:n,activeMipmapLevel:i}=this;this.coordinateSystem!==e.coordinateSystem&&(this.coordinateSystem=e.coordinateSystem,this.updateCoordinateSystem());const[r,o,a,l,c,h]=this.children,u=e.getRenderTarget(),f=e.getActiveCubeFace(),d=e.getActiveMipmapLevel(),m=e.xr.enabled;e.xr.enabled=!1;const p=n.texture.generateMipmaps;n.texture.generateMipmaps=!1,e.setRenderTarget(n,0,i),e.render(t,r),e.setRenderTarget(n,1,i),e.render(t,o),e.setRenderTarget(n,2,i),e.render(t,a),e.setRenderTarget(n,3,i),e.render(t,l),e.setRenderTarget(n,4,i),e.render(t,c),n.texture.generateMipmaps=p,e.setRenderTarget(n,5,i),e.render(t,h),e.setRenderTarget(u,f,d),e.xr.enabled=m,n.texture.needsPMREMUpdate=!0}}class of extends Ft{constructor(e=[],t=zs,n,i,r,o,a,l,c,h){super(e,t,n,i,r,o,a,l,c,h),this.isCubeTexture=!0,this.flipY=!1}get images(){return this.image}set images(e){this.image=e}}class Sx extends qn{constructor(e=1,t={}){super(e,e,t),this.isWebGLCubeRenderTarget=!0;const n={width:e,height:e,depth:1},i=[n,n,n,n,n,n];this.texture=new of(i),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 n={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 ); } `},i=new Wi(5,5,5),r=new Jt({name:"CubemapFromEquirect",uniforms:ir(n.uniforms),vertexShader:n.vertexShader,fragmentShader:n.fragmentShader,side:ln,blending:Wt});r.uniforms.tEquirect.value=t;const o=new ht(i,r),a=t.minFilter;return t.minFilter===gi&&(t.minFilter=Kt),new wx(1,10,this).update(e,o),t.minFilter=a,o.geometry.dispose(),o.material.dispose(),this}clear(e,t=!0,n=!0,i=!0){const r=e.getRenderTarget();for(let o=0;o<6;o++)e.setRenderTarget(this,o),e.clear(t,n,i);e.setRenderTarget(r)}}class Dn extends wt{constructor(){super(),this.isGroup=!0,this.type="Group"}}const Ex={type:"move"};class hh{constructor(){this._targetRay=null,this._grip=null,this._hand=null}getHandSpace(){return this._hand===null&&(this._hand=new Dn,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 Dn,this._targetRay.matrixAutoUpdate=!1,this._targetRay.visible=!1,this._targetRay.hasLinearVelocity=!1,this._targetRay.linearVelocity=new R,this._targetRay.hasAngularVelocity=!1,this._targetRay.angularVelocity=new R),this._targetRay}getGripSpace(){return this._grip===null&&(this._grip=new Dn,this._grip.matrixAutoUpdate=!1,this._grip.visible=!1,this._grip.hasLinearVelocity=!1,this._grip.linearVelocity=new R,this._grip.hasAngularVelocity=!1,this._grip.angularVelocity=new R),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 n of e.hand.values())this._getHandJoint(t,n)}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,n){let i=null,r=null,o=null;const a=this._targetRay,l=this._grip,c=this._hand;if(e&&t.session.visibilityState!=="visible-blurred"){if(c&&e.hand){o=!0;for(const p of e.hand.values()){const x=t.getJointPose(p,n),g=this._getHandJoint(c,p);x!==null&&(g.matrix.fromArray(x.transform.matrix),g.matrix.decompose(g.position,g.rotation,g.scale),g.matrixWorldNeedsUpdate=!0,g.jointRadius=x.radius),g.visible=x!==null}const h=c.joints["index-finger-tip"],u=c.joints["thumb-tip"],f=h.position.distanceTo(u.position),d=.02,m=.005;c.inputState.pinching&&f>d+m?(c.inputState.pinching=!1,this.dispatchEvent({type:"pinchend",handedness:e.handedness,target:this})):!c.inputState.pinching&&f<=d-m&&(c.inputState.pinching=!0,this.dispatchEvent({type:"pinchstart",handedness:e.handedness,target:this}))}else l!==null&&e.gripSpace&&(r=t.getPose(e.gripSpace,n),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));a!==null&&(i=t.getPose(e.targetRaySpace,n),i===null&&r!==null&&(i=r),i!==null&&(a.matrix.fromArray(i.transform.matrix),a.matrix.decompose(a.position,a.rotation,a.scale),a.matrixWorldNeedsUpdate=!0,i.linearVelocity?(a.hasLinearVelocity=!0,a.linearVelocity.copy(i.linearVelocity)):a.hasLinearVelocity=!1,i.angularVelocity?(a.hasAngularVelocity=!0,a.angularVelocity.copy(i.angularVelocity)):a.hasAngularVelocity=!1,this.dispatchEvent(Ex)))}return a!==null&&(a.visible=i!==null),l!==null&&(l.visible=r!==null),c!==null&&(c.visible=o!==null),this}_getHandJoint(e,t){if(e.joints[t.jointName]===void 0){const n=new Dn;n.matrixAutoUpdate=!1,n.visible=!1,e.joints[t.jointName]=n,e.add(n)}return e.joints[t.jointName]}}class af extends wt{constructor(){super(),this.isScene=!0,this.type="Scene",this.background=null,this.environment=null,this.fog=null,this.backgroundBlurriness=0,this.backgroundIntensity=1,this.backgroundRotation=new wn,this.environmentIntensity=1,this.environmentRotation=new wn,this.overrideMaterial=null,typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}copy(e,t){return super.copy(e,t),e.background!==null&&(this.background=e.background.clone()),e.environment!==null&&(this.environment=e.environment.clone()),e.fog!==null&&(this.fog=e.fog.clone()),this.backgroundBlurriness=e.backgroundBlurriness,this.backgroundIntensity=e.backgroundIntensity,this.backgroundRotation.copy(e.backgroundRotation),this.environmentIntensity=e.environmentIntensity,this.environmentRotation.copy(e.environmentRotation),e.overrideMaterial!==null&&(this.overrideMaterial=e.overrideMaterial.clone()),this.matrixAutoUpdate=e.matrixAutoUpdate,this}toJSON(e){const t=super.toJSON(e);return this.fog!==null&&(t.object.fog=this.fog.toJSON()),this.backgroundBlurriness>0&&(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}}class uh{constructor(e,t){this.isInterleavedBuffer=!0,this.array=e,this.stride=t,this.count=e!==void 0?e.length/t:0,this.usage=zc,this.updateRanges=[],this.version=0,this.uuid=Rn()}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.array=new e.array.constructor(e.array),this.count=e.count,this.stride=e.stride,this.usage=e.usage,this}copyAt(e,t,n){e*=this.stride,n*=t.stride;for(let i=0,r=this.stride;ie.far||t.push({distance:l,point:no.clone(),uv:xt.getInterpolation(no,ga,so,xa,cf,dh,hf,new ue),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 va(s,e,t,n,i,r){hr.subVectors(s,t).addScalar(.5).multiply(n),i!==void 0?(io.x=r*hr.x-i*hr.y,io.y=i*hr.x+r*hr.y):io.copy(hr),s.copy(e),s.x+=io.x,s.y+=io.y,s.applyMatrix4(lf)}const uf=new R,df=new tt,ff=new tt,Ax=new R,pf=new De,ba=new R,fh=new ri,mf=new De,ph=new Hi;class Px extends ht{constructor(e,t){super(e,t),this.isSkinnedMesh=!0,this.type="SkinnedMesh",this.bindMode=vd,this.bindMatrix=new De,this.bindMatrixInverse=new De,this.boundingBox=null,this.boundingSphere=null}computeBoundingBox(){const e=this.geometry;this.boundingBox===null&&(this.boundingBox=new gt),this.boundingBox.makeEmpty();const t=e.getAttribute("position");for(let n=0;n1?null:t.copy(e.start).addScaledVector(n,r)}intersectsLine(e){const t=this.distanceToPoint(e.start),n=this.distanceToPoint(e.end);return t<0&&n>0||n<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 n=t||Dx.getNormalMatrix(e),i=this.coplanarPoint(gh).applyMatrix4(e),r=this.normal.applyMatrix3(n).normalize();return this.constant=-i.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 hs=new ri,Bx=new ue(.5,.5),Ma=new R;class xh{constructor(e=new Pt,t=new Pt,n=new Pt,i=new Pt,r=new Pt,o=new Pt){this.planes=[e,t,n,i,r,o]}set(e,t,n,i,r,o){const a=this.planes;return a[0].copy(e),a[1].copy(t),a[2].copy(n),a[3].copy(i),a[4].copy(r),a[5].copy(o),this}copy(e){const t=this.planes;for(let n=0;n<6;n++)t[n].copy(e.planes[n]);return this}setFromProjectionMatrix(e,t=si,n=!1){const i=this.planes,r=e.elements,o=r[0],a=r[1],l=r[2],c=r[3],h=r[4],u=r[5],f=r[6],d=r[7],m=r[8],p=r[9],x=r[10],g=r[11],b=r[12],v=r[13],y=r[14],M=r[15];if(i[0].setComponents(c-o,d-h,g-m,M-b).normalize(),i[1].setComponents(c+o,d+h,g+m,M+b).normalize(),i[2].setComponents(c+a,d+u,g+p,M+v).normalize(),i[3].setComponents(c-a,d-u,g-p,M-v).normalize(),n)i[4].setComponents(l,f,x,y).normalize(),i[5].setComponents(c-l,d-f,g-x,M-y).normalize();else if(i[4].setComponents(c-l,d-f,g-x,M-y).normalize(),t===si)i[5].setComponents(c+l,d+f,g+x,M+y).normalize();else if(t===Jo)i[5].setComponents(l,f,x,y).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(),hs.copy(e.boundingSphere).applyMatrix4(e.matrixWorld);else{const t=e.geometry;t.boundingSphere===null&&t.computeBoundingSphere(),hs.copy(t.boundingSphere).applyMatrix4(e.matrixWorld)}return this.intersectsSphere(hs)}intersectsSprite(e){hs.center.set(0,0,0);const t=Bx.distanceTo(e.center);return hs.radius=.7071067811865476+t,hs.applyMatrix4(e.matrixWorld),this.intersectsSphere(hs)}intersectsSphere(e){const t=this.planes,n=e.center,i=-e.radius;for(let r=0;r<6;r++)if(t[r].distanceToPoint(n)0?e.max.x:e.min.x,Ma.y=i.normal.y>0?e.max.y:e.min.y,Ma.z=i.normal.z>0?e.max.z:e.min.z,i.distanceToPoint(Ma)<0)return!1}return!0}containsPoint(e){const t=this.planes;for(let n=0;n<6;n++)if(t[n].distanceToPoint(e)<0)return!1;return!0}clone(){return new this.constructor().copy(this)}}class lo extends Sn{constructor(e){super(),this.isLineBasicMaterial=!0,this.type="LineBasicMaterial",this.color=new He(16777215),this.map=null,this.linewidth=1,this.linecap="round",this.linejoin="round",this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.linewidth=e.linewidth,this.linecap=e.linecap,this.linejoin=e.linejoin,this.fog=e.fog,this}}const wa=new R,Sa=new R,yf=new De,co=new Hi,Ea=new ri,vh=new R,_f=new R;class dr extends wt{constructor(e=new bt,t=new lo){super(),this.isLine=!0,this.type="Line",this.geometry=e,this.material=t,this.morphTargetDictionary=void 0,this.morphTargetInfluences=void 0,this.updateMorphTargets()}copy(e,t){return super.copy(e,t),this.material=Array.isArray(e.material)?e.material.slice():e.material,this.geometry=e.geometry,this}computeLineDistances(){const e=this.geometry;if(e.index===null){const t=e.attributes.position,n=[0];for(let i=1,r=t.count;i0){const i=t[n[0]];if(i!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let r=0,o=i.length;rn)return;vh.applyMatrix4(s.matrixWorld);const c=e.ray.origin.distanceTo(vh);if(!(ce.far))return{distance:c,point:_f.clone().applyMatrix4(s.matrixWorld),index:o,face:null,faceIndex:null,barycoord:null,object:s}}const Mf=new R,wf=new R;class Sf extends dr{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,n=[];for(let i=0,r=t.count;i0){const i=t[n[0]];if(i!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let r=0,o=i.length;ri.far)return;r.push({distance:c,distanceToRay:Math.sqrt(a),point:l,index:e,face:null,faceIndex:null,barycoord:null,object:o})}}class yh extends Ft{constructor(e,t,n=rs,i,r,o,a=$t,l=$t,c,h=Xr,u=1){if(h!==Xr&&h!==Gs)throw new Error("DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat");const f={width:e,height:t,depth:u};super(f,i,r,o,a,l,h,n,c),this.isDepthTexture=!0,this.flipY=!1,this.generateMipmaps=!1,this.compareFunction=null}copy(e){return super.copy(e),this.source=new Wc(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 Pf extends Ft{constructor(e=null){super(),this.sourceTexture=e,this.isExternalTexture=!0}copy(e){return super.copy(e),this.sourceTexture=e.sourceTexture,this}}class oi{constructor(){this.type="Curve",this.arcLengthDivisions=200,this.needsUpdate=!1,this.cacheArcLengths=null}getPoint(){ze("Curve: .getPoint() not implemented.")}getPointAt(e,t){const n=this.getUtoTmapping(e);return this.getPoint(n,t)}getPoints(e=5){const t=[];for(let n=0;n<=e;n++)t.push(this.getPoint(n/e));return t}getSpacedPoints(e=5){const t=[];for(let n=0;n<=e;n++)t.push(this.getPointAt(n/e));return t}getLength(){const e=this.getLengths();return e[e.length-1]}getLengths(e=this.arcLengthDivisions){if(this.cacheArcLengths&&this.cacheArcLengths.length===e+1&&!this.needsUpdate)return this.cacheArcLengths;this.needsUpdate=!1;const t=[];let n,i=this.getPoint(0),r=0;t.push(0);for(let o=1;o<=e;o++)n=this.getPoint(o/e),r+=n.distanceTo(i),t.push(r),i=n;return this.cacheArcLengths=t,t}updateArcLengths(){this.needsUpdate=!0,this.getLengths()}getUtoTmapping(e,t=null){const n=this.getLengths();let i=0;const r=n.length;let o;t?o=t:o=e*n[r-1];let a=0,l=r-1,c;for(;a<=l;)if(i=Math.floor(a+(l-a)/2),c=n[i]-o,c<0)a=i+1;else if(c>0)l=i-1;else{l=i;break}if(i=l,n[i]===o)return i/(r-1);const h=n[i],f=n[i+1]-h,d=(o-h)/f;return(i+d)/(r-1)}getTangent(e,t){let i=e-1e-4,r=e+1e-4;i<0&&(i=0),r>1&&(r=1);const o=this.getPoint(i),a=this.getPoint(r),l=t||(o.isVector2?new ue:new R);return l.copy(a).sub(o).normalize(),l}getTangentAt(e,t){const n=this.getUtoTmapping(e);return this.getTangent(n,t)}computeFrenetFrames(e,t=!1){const n=new R,i=[],r=[],o=[],a=new R,l=new De;for(let d=0;d<=e;d++){const m=d/e;i[d]=this.getTangentAt(m,new R)}r[0]=new R,o[0]=new R;let c=Number.MAX_VALUE;const h=Math.abs(i[0].x),u=Math.abs(i[0].y),f=Math.abs(i[0].z);h<=c&&(c=h,n.set(1,0,0)),u<=c&&(c=u,n.set(0,1,0)),f<=c&&n.set(0,0,1),a.crossVectors(i[0],n).normalize(),r[0].crossVectors(i[0],a),o[0].crossVectors(i[0],r[0]);for(let d=1;d<=e;d++){if(r[d]=r[d-1].clone(),o[d]=o[d-1].clone(),a.crossVectors(i[d-1],i[d]),a.length()>Number.EPSILON){a.normalize();const m=Math.acos(qe(i[d-1].dot(i[d]),-1,1));r[d].applyMatrix4(l.makeRotationAxis(a,m))}o[d].crossVectors(i[d],r[d])}if(t===!0){let d=Math.acos(qe(r[0].dot(r[e]),-1,1));d/=e,i[0].dot(a.crossVectors(r[0],r[e]))>0&&(d=-d);for(let m=1;m<=e;m++)r[m].applyMatrix4(l.makeRotationAxis(i[m],d*m)),o[m].crossVectors(i[m],r[m])}return{tangents:i,normals:r,binormals:o}}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 _h extends oi{constructor(e=0,t=0,n=1,i=1,r=0,o=Math.PI*2,a=!1,l=0){super(),this.isEllipseCurve=!0,this.type="EllipseCurve",this.aX=e,this.aY=t,this.xRadius=n,this.yRadius=i,this.aStartAngle=r,this.aEndAngle=o,this.aClockwise=a,this.aRotation=l}getPoint(e,t=new ue){const n=t,i=Math.PI*2;let r=this.aEndAngle-this.aStartAngle;const o=Math.abs(r)i;)r-=i;r0?0:(Math.floor(Math.abs(a)/r)+1)*r:l===0&&a===r-1&&(a=r-2,l=1);let c,h;this.closed||a>0?c=i[(a-1)%r]:(Pa.subVectors(i[0],i[1]).add(i[0]),c=Pa);const u=i[a%r],f=i[(a+1)%r];if(this.closed||a+2i.length-2?i.length-1:o+1],u=i[o>i.length-3?i.length-1:o+2];return n.set(Rf(a,l.x,c.x,h.x,u.x),Rf(a,l.y,c.y,h.y,u.y)),n}copy(e){super.copy(e),this.points=[];for(let t=0,n=e.points.length;t=n){const o=i[r]-n,a=this.curves[r],l=a.getLength(),c=l===0?0:1-o/l;return a.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 n=0,i=this.curves.length;n1&&!t[t.length-1].equals(t[0])&&t.push(t[0]),t}copy(e){super.copy(e),this.curves=[];for(let t=0,n=e.curves.length;t0){const u=c.getPoint(0);u.equals(this.currentPoint)||this.lineTo(u.x,u.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 kf extends Nf{constructor(e){super(e),this.uuid=Rn(),this.type="Shape",this.holes=[]}getPointsHoles(e){const t=[];for(let n=0,i=this.holes.length;n80*t){a=s[0],l=s[1];let h=a,u=l;for(let f=t;fh&&(h=d),m>u&&(u=m)}c=Math.max(h-a,u-l),c=c!==0?32767/c:0}return fo(r,o,t,a,l,c,0),o}function Uf(s,e,t,n,i){let r;if(i===uv(s,e,t,n)>0)for(let o=e;o=e;o-=n)r=Hf(o/n|0,s[o],s[o+1],r);return r&&fr(r,r.next)&&(go(r),r=r.next),r}function us(s,e){if(!s)return s;e||(e=s);let t=s,n;do if(n=!1,!t.steiner&&(fr(t,t.next)||Et(t.prev,t,t.next)===0)){if(go(t),t=e=t.prev,t===t.next)break;n=!0}else t=t.next;while(n||t!==e);return e}function fo(s,e,t,n,i,r,o){if(!s)return;!o&&r&&rv(s,n,i,r);let a=s;for(;s.prev!==s.next;){const l=s.prev,c=s.next;if(r?Kx(s,n,i,r):$x(s)){e.push(l.i,s.i,c.i),go(s),s=c.next,a=c.next;continue}if(s=c,s===a){o?o===1?(s=Jx(us(s),e),fo(s,e,t,n,i,r,2)):o===2&&Qx(s,e,t,n,i,r):fo(us(s),e,t,n,i,r,1);break}}}function $x(s){const e=s.prev,t=s,n=s.next;if(Et(e,t,n)>=0)return!1;const i=e.x,r=t.x,o=n.x,a=e.y,l=t.y,c=n.y,h=Math.min(i,r,o),u=Math.min(a,l,c),f=Math.max(i,r,o),d=Math.max(a,l,c);let m=n.next;for(;m!==e;){if(m.x>=h&&m.x<=f&&m.y>=u&&m.y<=d&&po(i,a,r,l,o,c,m.x,m.y)&&Et(m.prev,m,m.next)>=0)return!1;m=m.next}return!0}function Kx(s,e,t,n){const i=s.prev,r=s,o=s.next;if(Et(i,r,o)>=0)return!1;const a=i.x,l=r.x,c=o.x,h=i.y,u=r.y,f=o.y,d=Math.min(a,l,c),m=Math.min(h,u,f),p=Math.max(a,l,c),x=Math.max(h,u,f),g=Ch(d,m,e,t,n),b=Ch(p,x,e,t,n);let v=s.prevZ,y=s.nextZ;for(;v&&v.z>=g&&y&&y.z<=b;){if(v.x>=d&&v.x<=p&&v.y>=m&&v.y<=x&&v!==i&&v!==o&&po(a,h,l,u,c,f,v.x,v.y)&&Et(v.prev,v,v.next)>=0||(v=v.prevZ,y.x>=d&&y.x<=p&&y.y>=m&&y.y<=x&&y!==i&&y!==o&&po(a,h,l,u,c,f,y.x,y.y)&&Et(y.prev,y,y.next)>=0))return!1;y=y.nextZ}for(;v&&v.z>=g;){if(v.x>=d&&v.x<=p&&v.y>=m&&v.y<=x&&v!==i&&v!==o&&po(a,h,l,u,c,f,v.x,v.y)&&Et(v.prev,v,v.next)>=0)return!1;v=v.prevZ}for(;y&&y.z<=b;){if(y.x>=d&&y.x<=p&&y.y>=m&&y.y<=x&&y!==i&&y!==o&&po(a,h,l,u,c,f,y.x,y.y)&&Et(y.prev,y,y.next)>=0)return!1;y=y.nextZ}return!0}function Jx(s,e){let t=s;do{const n=t.prev,i=t.next.next;!fr(n,i)&&Ff(n,t,t.next,i)&&mo(n,i)&&mo(i,n)&&(e.push(n.i,t.i,i.i),go(t),go(t.next),t=s=i),t=t.next}while(t!==s);return us(t)}function Qx(s,e,t,n,i,r){let o=s;do{let a=o.next.next;for(;a!==o.prev;){if(o.i!==a.i&&lv(o,a)){let l=zf(o,a);o=us(o,o.next),l=us(l,l.next),fo(o,e,t,n,i,r,0),fo(l,e,t,n,i,r,0);return}a=a.next}o=o.next}while(o!==s)}function ev(s,e,t,n){const i=[];for(let r=0,o=e.length;r=t.next.y&&t.next.y!==t.y){const u=t.x+(i-t.y)*(t.next.x-t.x)/(t.next.y-t.y);if(u<=n&&u>r&&(r=u,o=t.x=t.x&&t.x>=l&&n!==t.x&&Of(io.x||t.x===o.x&&sv(o,t)))&&(o=t,h=u)}t=t.next}while(t!==a);return o}function sv(s,e){return Et(s.prev,s,e.prev)<0&&Et(e.next,s,s.next)<0}function rv(s,e,t,n){let i=s;do i.z===0&&(i.z=Ch(i.x,i.y,e,t,n)),i.prevZ=i.prev,i.nextZ=i.next,i=i.next;while(i!==s);i.prevZ.nextZ=null,i.prevZ=null,ov(i)}function ov(s){let e,t=1;do{let n=s,i;s=null;let r=null;for(e=0;n;){e++;let o=n,a=0;for(let c=0;c0||l>0&&o;)a!==0&&(l===0||!o||n.z<=o.z)?(i=n,n=n.nextZ,a--):(i=o,o=o.nextZ,l--),r?r.nextZ=i:s=i,i.prevZ=r,r=i;n=o}r.nextZ=null,t*=2}while(e>1);return s}function Ch(s,e,t,n,i){return s=(s-t)*i|0,e=(e-n)*i|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 av(s){let e=s,t=s;do(e.x=(s-o)*(r-a)&&(s-o)*(n-a)>=(t-o)*(e-a)&&(t-o)*(r-a)>=(i-o)*(n-a)}function po(s,e,t,n,i,r,o,a){return!(s===o&&e===a)&&Of(s,e,t,n,i,r,o,a)}function lv(s,e){return s.next.i!==e.i&&s.prev.i!==e.i&&!cv(s,e)&&(mo(s,e)&&mo(e,s)&&hv(s,e)&&(Et(s.prev,s,e.prev)||Et(s,e.prev,e))||fr(s,e)&&Et(s.prev,s,s.next)>0&&Et(e.prev,e,e.next)>0)}function Et(s,e,t){return(e.y-s.y)*(t.x-e.x)-(e.x-s.x)*(t.y-e.y)}function fr(s,e){return s.x===e.x&&s.y===e.y}function Ff(s,e,t,n){const i=La(Et(s,e,t)),r=La(Et(s,e,n)),o=La(Et(t,n,s)),a=La(Et(t,n,e));return!!(i!==r&&o!==a||i===0&&Ra(s,t,e)||r===0&&Ra(s,n,e)||o===0&&Ra(t,s,n)||a===0&&Ra(t,e,n))}function Ra(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 La(s){return s>0?1:s<0?-1:0}function cv(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&&Ff(t,t.next,s,e))return!0;t=t.next}while(t!==s);return!1}function mo(s,e){return Et(s.prev,s,s.next)<0?Et(s,e,s.next)>=0&&Et(s,s.prev,e)>=0:Et(s,e,s.prev)<0||Et(s,s.next,e)<0}function hv(s,e){let t=s,n=!1;const i=(s.x+e.x)/2,r=(s.y+e.y)/2;do t.y>r!=t.next.y>r&&t.next.y!==t.y&&i<(t.next.x-t.x)*(r-t.y)/(t.next.y-t.y)+t.x&&(n=!n),t=t.next;while(t!==s);return n}function zf(s,e){const t=Ah(s.i,s.x,s.y),n=Ah(e.i,e.x,e.y),i=s.next,r=e.prev;return s.next=e,e.prev=s,t.next=i,i.prev=t,n.next=t,t.prev=n,r.next=n,n.prev=r,n}function Hf(s,e,t,n){const i=Ah(s,e,t);return n?(i.next=n.next,i.prev=n,n.next.prev=i,n.next=i):(i.prev=i,i.next=i),i}function go(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 Ah(s,e,t){return{i:s,x:e,y:t,prev:null,next:null,z:0,prevZ:null,nextZ:null,steiner:!1}}function uv(s,e,t,n){let i=0;for(let r=e,o=t-n;r2&&s[e-1].equals(s[0])&&s.pop()}function Gf(s,e){for(let t=0;tNumber.EPSILON){const K=Math.sqrt(L),le=Math.sqrt(G*G+N*N),te=D.x-J/K,Ce=D.y+ee/K,ye=V.x-N/le,Re=V.y+G/le,Ie=((ye-te)*N-(Re-Ce)*G)/(ee*N-J*G);U=te+ee*Ie-T.x,k=Ce+J*Ie-T.y;const he=U*U+k*k;if(he<=2)return new ue(U,k);z=Math.sqrt(he/2)}else{let K=!1;ee>Number.EPSILON?G>Number.EPSILON&&(K=!0):ee<-Number.EPSILON?G<-Number.EPSILON&&(K=!0):Math.sign(J)===Math.sign(N)&&(K=!0),K?(U=-J,k=ee,z=Math.sqrt(L)):(U=ee,k=J,z=Math.sqrt(L/2))}return new ue(U/z,k/z)}const Z=[];for(let T=0,D=F.length,V=D-1,U=T+1;T=0;T--){const D=T/x,V=d*Math.cos(D*Math.PI/2),U=m*Math.sin(D*Math.PI/2)+p;for(let k=0,z=F.length;k=0;){const U=V;let k=V-1;k<0&&(k=T.length-1);for(let z=0,ee=h+x*2;z0!=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 gv extends Sn{constructor(e){super(),this.isMeshNormalMaterial=!0,this.type="MeshNormalMaterial",this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=$o,this.normalScale=new ue(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 xv extends Sn{constructor(e){super(),this.isMeshLambertMaterial=!0,this.type="MeshLambertMaterial",this.color=new He(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new He(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=$o,this.normalScale=new ue(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new wn,this.combine=Ql,this.reflectivity=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.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 vv extends Sn{constructor(e){super(),this.isMeshDepthMaterial=!0,this.type="MeshDepthMaterial",this.depthPacking=P0,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 bv extends Sn{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}}function Ia(s,e){return!s||s.constructor===e?s:typeof e.BYTES_PER_ELEMENT=="number"?new e(s):Array.prototype.slice.call(s)}function yv(s){return ArrayBuffer.isView(s)&&!(s instanceof DataView)}function _v(s){function e(i,r){return s[i]-s[r]}const t=s.length,n=new Array(t);for(let i=0;i!==t;++i)n[i]=i;return n.sort(e),n}function Wf(s,e,t){const n=s.length,i=new s.constructor(n);for(let r=0,o=0;o!==n;++r){const a=t[r]*e;for(let l=0;l!==e;++l)i[o++]=s[a+l]}return i}function Xf(s,e,t,n){let i=1,r=s[0];for(;r!==void 0&&r[n]===void 0;)r=s[i++];if(r===void 0)return;let o=r[n];if(o!==void 0)if(Array.isArray(o))do o=r[n],o!==void 0&&(e.push(r.time),t.push(...o)),r=s[i++];while(r!==void 0);else if(o.toArray!==void 0)do o=r[n],o!==void 0&&(e.push(r.time),o.toArray(t,t.length)),r=s[i++];while(r!==void 0);else do o=r[n],o!==void 0&&(e.push(r.time),t.push(o)),r=s[i++];while(r!==void 0)}class vo{constructor(e,t,n,i){this.parameterPositions=e,this._cachedIndex=0,this.resultBuffer=i!==void 0?i:new t.constructor(n),this.sampleValues=t,this.valueSize=n,this.settings=null,this.DefaultSettings_={}}evaluate(e){const t=this.parameterPositions;let n=this._cachedIndex,i=t[n],r=t[n-1];e:{t:{let o;n:{i:if(!(e=r)){const a=t[1];e=r)break t}o=n,n=0;break n}break e}for(;n>>1;et;)--o;if(++o,r!==0||o!==i){r>=o&&(o=Math.max(o,1),r=o-1);const a=this.getValueSize();this.times=n.slice(r,o),this.values=this.values.slice(r*a,o*a)}return this}validate(){let e=!0;const t=this.getValueSize();t-Math.floor(t)!==0&&(Qe("KeyframeTrack: Invalid value size in track.",this),e=!1);const n=this.times,i=this.values,r=n.length;r===0&&(Qe("KeyframeTrack: Track is empty.",this),e=!1);let o=null;for(let a=0;a!==r;a++){const l=n[a];if(typeof l=="number"&&isNaN(l)){Qe("KeyframeTrack: Time is not a valid number.",this,a,l),e=!1;break}if(o!==null&&o>l){Qe("KeyframeTrack: Out of order keys.",this,a,l,o),e=!1;break}o=l}if(i!==void 0&&yv(i))for(let a=0,l=i.length;a!==l;++a){const c=i[a];if(isNaN(c)){Qe("KeyframeTrack: Value is not a valid number.",this,a,c),e=!1;break}}return e}optimize(){const e=this.times.slice(),t=this.values.slice(),n=this.getValueSize(),i=this.getInterpolation()===Oc,r=e.length-1;let o=1;for(let a=1;a0){e[o]=e[r];for(let a=r*n,l=o*n,c=0;c!==n;++c)t[l+c]=t[a+c];++o}return o!==e.length?(this.times=e.slice(0,o),this.values=t.slice(0,o*n)):(this.times=e,this.values=t),this}clone(){const e=this.times.slice(),t=this.values.slice(),n=this.constructor,i=new n(this.name,e,t);return i.createInterpolant=this.createInterpolant,i}}Kn.prototype.ValueTypeName="",Kn.prototype.TimeBufferType=Float32Array,Kn.prototype.ValueBufferType=Float32Array,Kn.prototype.DefaultInterpolation=qr;class mr extends Kn{constructor(e,t,n){super(e,t,n)}}mr.prototype.ValueTypeName="bool",mr.prototype.ValueBufferType=Array,mr.prototype.DefaultInterpolation=jr,mr.prototype.InterpolantFactoryMethodLinear=void 0,mr.prototype.InterpolantFactoryMethodSmooth=void 0;class jf extends Kn{constructor(e,t,n,i){super(e,t,n,i)}}jf.prototype.ValueTypeName="color";class gr extends Kn{constructor(e,t,n,i){super(e,t,n,i)}}gr.prototype.ValueTypeName="number";class Ev extends vo{constructor(e,t,n,i){super(e,t,n,i)}interpolate_(e,t,n,i){const r=this.resultBuffer,o=this.sampleValues,a=this.valueSize,l=(n-t)/(i-t);let c=e*a;for(let h=c+a;c!==h;c+=4)Ln.slerpFlat(r,0,o,c-a,o,c,l);return r}}class xr extends Kn{constructor(e,t,n,i){super(e,t,n,i)}InterpolantFactoryMethodLinear(e){return new Ev(this.times,this.values,this.getValueSize(),e)}}xr.prototype.ValueTypeName="quaternion",xr.prototype.InterpolantFactoryMethodSmooth=void 0;class vr extends Kn{constructor(e,t,n){super(e,t,n)}}vr.prototype.ValueTypeName="string",vr.prototype.ValueBufferType=Array,vr.prototype.DefaultInterpolation=jr,vr.prototype.InterpolantFactoryMethodLinear=void 0,vr.prototype.InterpolantFactoryMethodSmooth=void 0;class br extends Kn{constructor(e,t,n,i){super(e,t,n,i)}}br.prototype.ValueTypeName="vector";class Tv{constructor(e="",t=-1,n=[],i=C0){this.name=e,this.tracks=n,this.duration=t,this.blendMode=i,this.uuid=Rn(),this.userData={},this.duration<0&&this.resetDuration()}static parse(e){const t=[],n=e.tracks,i=1/(e.fps||1);for(let o=0,a=n.length;o!==a;++o)t.push(Av(n[o]).scale(i));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=[],n=e.tracks,i={name:e.name,duration:e.duration,tracks:t,uuid:e.uuid,blendMode:e.blendMode,userData:JSON.stringify(e.userData)};for(let r=0,o=n.length;r!==o;++r)t.push(Kn.toJSON(n[r]));return i}static CreateFromMorphTargetSequence(e,t,n,i){const r=t.length,o=[];for(let a=0;a1){const u=h[1];let f=i[u];f||(i[u]=f=[]),f.push(c)}}const o=[];for(const a in i)o.push(this.CreateFromMorphTargetSequence(a,i[a],t,n));return o}static parseAnimation(e,t){if(ze("AnimationClip: parseAnimation() is deprecated and will be removed with r185"),!e)return Qe("AnimationClip: No animation in JSONLoader data."),null;const n=function(u,f,d,m,p){if(d.length!==0){const x=[],g=[];Xf(d,x,g,m),x.length!==0&&p.push(new u(f,x,g))}},i=[],r=e.name||"default",o=e.fps||30,a=e.blendMode;let l=e.length||-1;const c=e.hierarchy||[];for(let u=0;u{t&&t(r),this.manager.itemEnd(e)},0),r;if(Ei[e]!==void 0){Ei[e].push({onLoad:t,onProgress:n,onError:i});return}Ei[e]=[],Ei[e].push({onLoad:t,onProgress:n,onError:i});const o=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}),a=this.mimeType,l=this.responseType;fetch(o).then(c=>{if(c.status===200||c.status===0){if(c.status===0&&ze("FileLoader: HTTP Status 0 received."),typeof ReadableStream>"u"||c.body===void 0||c.body.getReader===void 0)return c;const h=Ei[e],u=c.body.getReader(),f=c.headers.get("X-File-Size")||c.headers.get("Content-Length"),d=f?parseInt(f):0,m=d!==0;let p=0;const x=new ReadableStream({start(g){b();function b(){u.read().then(({done:v,value:y})=>{if(v)g.close();else{p+=y.byteLength;const M=new ProgressEvent("progress",{lengthComputable:m,loaded:p,total:d});for(let E=0,C=h.length;E{g.error(v)})}}});return new Response(x)}else throw new Lv(`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,a));case"json":return c.json();default:if(a==="")return c.text();{const u=/charset="?([^;"\s]*)"?/i.exec(a),f=u&&u[1]?u[1].toLowerCase():void 0,d=new TextDecoder(f);return c.arrayBuffer().then(m=>d.decode(m))}}}).then(c=>{Si.add(`file:${e}`,c);const h=Ei[e];delete Ei[e];for(let u=0,f=h.length;u{const h=Ei[e];if(h===void 0)throw this.manager.itemError(e),c;delete Ei[e];for(let u=0,f=h.length;u{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}}const yr=new WeakMap;class Iv extends fs{constructor(e){super(e)}load(e,t,n,i){this.path!==void 0&&(e=this.path+e),e=this.manager.resolveURL(e);const r=this,o=Si.get(`image:${e}`);if(o!==void 0){if(o.complete===!0)r.manager.itemStart(e),setTimeout(function(){t&&t(o),r.manager.itemEnd(e)},0);else{let u=yr.get(o);u===void 0&&(u=[],yr.set(o,u)),u.push({onLoad:t,onError:i})}return o}const a=Zr("img");function l(){h(),t&&t(this);const u=yr.get(this)||[];for(let f=0;f"u"&&ze("ImageBitmapLoader: createImageBitmap() not supported."),typeof fetch>"u"&&ze("ImageBitmapLoader: fetch() not supported."),this.options={premultiplyAlpha:"none"},this._abortController=new AbortController}setOptions(e){return this.options=e,this}load(e,t,n,i){e===void 0&&(e=""),this.path!==void 0&&(e=this.path+e),e=this.manager.resolveURL(e);const r=this,o=Si.get(`image-bitmap:${e}`);if(o!==void 0){if(r.manager.itemStart(e),o.then){o.then(c=>{if(Dh.has(o)===!0)i&&i(Dh.get(o)),r.manager.itemError(e),r.manager.itemEnd(e);else return t&&t(c),r.manager.itemEnd(e),c});return}return setTimeout(function(){t&&t(o),r.manager.itemEnd(e)},0),o}const a={};a.credentials=this.crossOrigin==="anonymous"?"same-origin":"include",a.headers=this.requestHeader,a.signal=typeof AbortSignal.any=="function"?AbortSignal.any([this._abortController.signal,this.manager.abortController.signal]):this._abortController.signal;const l=fetch(e,a).then(function(c){return c.blob()}).then(function(c){return createImageBitmap(c,Object.assign(r.options,{colorSpaceConversion:"none"}))}).then(function(c){return Si.add(`image-bitmap:${e}`,c),t&&t(c),r.manager.itemEnd(e),c}).catch(function(c){i&&i(c),Dh.set(l,c),Si.remove(`image-bitmap:${e}`),r.manager.itemError(e),r.manager.itemEnd(e)});Si.add(`image-bitmap:${e}`,l),r.manager.itemStart(e)}abort(){return this._abortController.abort(),this._abortController=new AbortController,this}}class Fv extends on{constructor(e=[]){super(),this.isArrayCamera=!0,this.isMultiViewCamera=!1,this.cameras=e}}class zv{constructor(e=!0){this.autoStart=e,this.startTime=0,this.oldTime=0,this.elapsedTime=0,this.running=!1}start(){this.startTime=performance.now(),this.oldTime=this.startTime,this.elapsedTime=0,this.running=!0}stop(){this.getElapsedTime(),this.running=!1,this.autoStart=!1}getElapsedTime(){return this.getDelta(),this.elapsedTime}getDelta(){let e=0;if(this.autoStart&&!this.running)return this.start(),0;if(this.running){const t=performance.now();e=(t-this.oldTime)/1e3,this.oldTime=t,this.elapsedTime+=e}return e}}const Bh="\\[\\]\\.:\\/",Hv=new RegExp("["+Bh+"]","g"),Nh="[^"+Bh+"]",Vv="[^"+Bh.replace("\\.","")+"]",Gv=/((?:WC+[\/:])*)/.source.replace("WC",Nh),Wv=/(WCOD+)?/.source.replace("WCOD",Vv),Xv=/(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace("WC",Nh),jv=/\.(WC+)(?:\[(.+)\])?/.source.replace("WC",Nh),qv=new RegExp("^"+Gv+Wv+Xv+jv+"$"),Zv=["material","materials","bones","map"];class Yv{constructor(e,t,n){const i=n||ut.parseTrackName(t);this._targetGroup=e,this._bindings=e.subscribe_(t,i)}getValue(e,t){this.bind();const n=this._targetGroup.nCachedObjects_,i=this._bindings[n];i!==void 0&&i.getValue(e,t)}setValue(e,t){const n=this._bindings;for(let i=this._targetGroup.nCachedObjects_,r=n.length;i!==r;++i)n[i].setValue(e,t)}bind(){const e=this._bindings;for(let t=this._targetGroup.nCachedObjects_,n=e.length;t!==n;++t)e[t].bind()}unbind(){const e=this._bindings;for(let t=this._targetGroup.nCachedObjects_,n=e.length;t!==n;++t)e[t].unbind()}}class ut{constructor(e,t,n){this.path=t,this.parsedPath=n||ut.parseTrackName(t),this.node=ut.findNode(e,this.parsedPath.nodeName),this.rootNode=e,this.getValue=this._getValue_unbound,this.setValue=this._setValue_unbound}static create(e,t,n){return e&&e.isAnimationObjectGroup?new ut.Composite(e,t,n):new ut(e,t,n)}static sanitizeNodeName(e){return e.replace(/\s/g,"_").replace(Hv,"")}static parseTrackName(e){const t=qv.exec(e);if(t===null)throw new Error("PropertyBinding: Cannot parse trackName: "+e);const n={nodeName:t[2],objectName:t[3],objectIndex:t[4],propertyName:t[5],propertyIndex:t[6]},i=n.nodeName&&n.nodeName.lastIndexOf(".");if(i!==void 0&&i!==-1){const r=n.nodeName.substring(i+1);Zv.indexOf(r)!==-1&&(n.nodeName=n.nodeName.substring(0,i),n.objectName=r)}if(n.propertyName===null||n.propertyName.length===0)throw new Error("PropertyBinding: can not parse propertyName from trackName: "+e);return n}static findNode(e,t){if(t===void 0||t===""||t==="."||t===-1||t===e.name||t===e.uuid)return e;if(e.skeleton){const n=e.skeleton.getBoneByName(t);if(n!==void 0)return n}if(e.children){const n=function(r){for(let o=0;o1&&(o=1,r=qe((p-m)/u,0,1))}}return t.copy(a).add(_r.multiplyScalar(r)),n.copy(l).add(Mr.multiplyScalar(o)),t.sub(n),t.dot(t)}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)}}class Jv extends os{constructor(e,t=null){super(),this.object=e,this.domElement=t,this.enabled=!0,this.state=-1,this.keys={},this.mouseButtons={LEFT:null,MIDDLE:null,RIGHT:null},this.touches={ONE:null,TWO:null}}connect(e){if(e===void 0){ze("Controls: connect() now requires an element.");return}this.domElement!==null&&this.disconnect(),this.domElement=e}disconnect(){}dispose(){}update(){}}function tp(s,e,t,n){const i=Qv(n);switch(t){case Ed:return s*e;case rc:return s*e/i.components*i.byteLength;case oc:return s*e/i.components*i.byteLength;case ac:return s*e*2/i.components*i.byteLength;case lc:return s*e*2/i.components*i.byteLength;case Td:return s*e*3/i.components*i.byteLength;case mn:return s*e*4/i.components*i.byteLength;case cc:return s*e*4/i.components*i.byteLength;case jo:case qo:return Math.floor((s+3)/4)*Math.floor((e+3)/4)*8;case Zo:case Yo:return Math.floor((s+3)/4)*Math.floor((e+3)/4)*16;case uc:case fc:return Math.max(s,16)*Math.max(e,8)/4;case hc:case dc:return Math.max(s,8)*Math.max(e,8)/2;case pc:case mc:return Math.floor((s+3)/4)*Math.floor((e+3)/4)*8;case gc:return Math.floor((s+3)/4)*Math.floor((e+3)/4)*16;case xc:return Math.floor((s+3)/4)*Math.floor((e+3)/4)*16;case vc:return Math.floor((s+4)/5)*Math.floor((e+3)/4)*16;case bc:return Math.floor((s+4)/5)*Math.floor((e+4)/5)*16;case yc:return Math.floor((s+5)/6)*Math.floor((e+4)/5)*16;case _c:return Math.floor((s+5)/6)*Math.floor((e+5)/6)*16;case Mc:return Math.floor((s+7)/8)*Math.floor((e+4)/5)*16;case wc:return Math.floor((s+7)/8)*Math.floor((e+5)/6)*16;case Sc:return Math.floor((s+7)/8)*Math.floor((e+7)/8)*16;case Ec:return Math.floor((s+9)/10)*Math.floor((e+4)/5)*16;case Tc:return Math.floor((s+9)/10)*Math.floor((e+5)/6)*16;case Cc:return Math.floor((s+9)/10)*Math.floor((e+7)/8)*16;case Ac:return Math.floor((s+9)/10)*Math.floor((e+9)/10)*16;case Pc:return Math.floor((s+11)/12)*Math.floor((e+9)/10)*16;case Rc:return Math.floor((s+11)/12)*Math.floor((e+11)/12)*16;case Lc:case Ic:case Dc:return Math.ceil(s/4)*Math.ceil(e/4)*16;case Bc:case Nc:return Math.ceil(s/4)*Math.ceil(e/4)*8;case kc:case Uc:return Math.ceil(s/4)*Math.ceil(e/4)*16}throw new Error(`Unable to determine texture byte length for ${t} format.`)}function Qv(s){switch(s){case Wn:case _d:return{byteLength:1,components:1};case Wr:case Md:case xi:return{byteLength:2,components:1};case ic:case sc:return{byteLength:2,components:4};case rs:case nc:case Xn:return{byteLength:4,components:1};case wd:case Sd:return{byteLength:4,components:3}}throw new Error(`Unknown texture type ${s}.`)}typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("register",{detail:{revision:Hr}})),typeof window<"u"&&(window.__THREE__?ze("WARNING: Multiple instances of Three.js being imported."):window.__THREE__=Hr);function np(){let s=null,e=!1,t=null,n=null;function i(r,o){t(r,o),n=s.requestAnimationFrame(i)}return{start:function(){e!==!0&&t!==null&&(n=s.requestAnimationFrame(i),e=!0)},stop:function(){s.cancelAnimationFrame(n),e=!1},setAnimationLoop:function(r){t=r},setContext:function(r){s=r}}}function e1(s){const e=new WeakMap;function t(a,l){const c=a.array,h=a.usage,u=c.byteLength,f=s.createBuffer();s.bindBuffer(l,f),s.bufferData(l,c,h),a.onUploadCallback();let d;if(c instanceof Float32Array)d=s.FLOAT;else if(typeof Float16Array<"u"&&c instanceof Float16Array)d=s.HALF_FLOAT;else if(c instanceof Uint16Array)a.isFloat16BufferAttribute?d=s.HALF_FLOAT:d=s.UNSIGNED_SHORT;else if(c instanceof Int16Array)d=s.SHORT;else if(c instanceof Uint32Array)d=s.UNSIGNED_INT;else if(c instanceof Int32Array)d=s.INT;else if(c instanceof Int8Array)d=s.BYTE;else if(c instanceof Uint8Array)d=s.UNSIGNED_BYTE;else if(c instanceof Uint8ClampedArray)d=s.UNSIGNED_BYTE;else throw new Error("THREE.WebGLAttributes: Unsupported buffer data format: "+c);return{buffer:f,type:d,bytesPerElement:c.BYTES_PER_ELEMENT,version:a.version,size:u}}function n(a,l,c){const h=l.array,u=l.updateRanges;if(s.bindBuffer(c,a),u.length===0)s.bufferSubData(c,0,h);else{u.sort((d,m)=>d.start-m.start);let f=0;for(let d=1;d 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`,x1=`#if NUM_CLIPPING_PLANES > 0 varying vec3 vClipPosition; uniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ]; #endif`,v1=`#if NUM_CLIPPING_PLANES > 0 varying vec3 vClipPosition; #endif`,b1=`#if NUM_CLIPPING_PLANES > 0 vClipPosition = - mvPosition.xyz; #endif`,y1=`#if defined( USE_COLOR_ALPHA ) diffuseColor *= vColor; #elif defined( USE_COLOR ) diffuseColor.rgb *= vColor; #endif`,_1=`#if defined( USE_COLOR_ALPHA ) varying vec4 vColor; #elif defined( USE_COLOR ) varying vec3 vColor; #endif`,M1=`#if defined( USE_COLOR_ALPHA ) varying vec4 vColor; #elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR ) varying vec3 vColor; #endif`,w1=`#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`,S1=`#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`,E1=`#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`,T1=`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`,C1=`#ifdef USE_DISPLACEMENTMAP uniform sampler2D displacementMap; uniform float displacementScale; uniform float displacementBias; #endif`,A1=`#ifdef USE_DISPLACEMENTMAP transformed += normalize( objectNormal ) * ( texture2D( displacementMap, vDisplacementMapUv ).x * displacementScale + displacementBias ); #endif`,P1=`#ifdef USE_EMISSIVEMAP vec4 emissiveColor = texture2D( emissiveMap, vEmissiveMapUv ); #ifdef DECODE_VIDEO_TEXTURE_EMISSIVE emissiveColor = sRGBTransferEOTF( emissiveColor ); #endif totalEmissiveRadiance *= emissiveColor.rgb; #endif`,R1=`#ifdef USE_EMISSIVEMAP uniform sampler2D emissiveMap; #endif`,L1="gl_FragColor = linearToOutputTexel( gl_FragColor );",I1=`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 ); }`,D1=`#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`,B1=`#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`,N1=`#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`,k1=`#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`,U1=`#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`,O1=`#ifdef USE_FOG vFogDepth = - mvPosition.z; #endif`,F1=`#ifdef USE_FOG varying float vFogDepth; #endif`,z1=`#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`,H1=`#ifdef USE_FOG uniform vec3 fogColor; varying float vFogDepth; #ifdef FOG_EXP2 uniform float fogDensity; #else uniform float fogNear; uniform float fogFar; #endif #endif`,V1=`#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 }`,G1=`#ifdef USE_LIGHTMAP uniform sampler2D lightMap; uniform float lightMapIntensity; #endif`,W1=`LambertMaterial material; material.diffuseColor = diffuseColor.rgb; material.specularStrength = specularStrength;`,X1=`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`,j1=`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`,q1=`#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`,Z1=`ToonMaterial material; material.diffuseColor = diffuseColor.rgb;`,Y1=`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`,$1=`BlinnPhongMaterial material; material.diffuseColor = diffuseColor.rgb; material.specularColor = specular; material.specularShininess = shininess; material.specularStrength = specularStrength;`,K1=`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`,J1=`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`,Q1=`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 ); }`,eb=` 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`,tb=`#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`,nb=`#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`,ib=`#if defined( USE_LOGARITHMIC_DEPTH_BUFFER ) gl_FragDepth = vIsPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5; #endif`,sb=`#if defined( USE_LOGARITHMIC_DEPTH_BUFFER ) uniform float logDepthBufFC; varying float vFragDepth; varying float vIsPerspective; #endif`,rb=`#ifdef USE_LOGARITHMIC_DEPTH_BUFFER varying float vFragDepth; varying float vIsPerspective; #endif`,ob=`#ifdef USE_LOGARITHMIC_DEPTH_BUFFER vFragDepth = 1.0 + gl_Position.w; vIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) ); #endif`,ab=`#ifdef USE_MAP vec4 sampledDiffuseColor = texture2D( map, vMapUv ); #ifdef DECODE_VIDEO_TEXTURE sampledDiffuseColor = sRGBTransferEOTF( sampledDiffuseColor ); #endif diffuseColor *= sampledDiffuseColor; #endif`,lb=`#ifdef USE_MAP uniform sampler2D map; #endif`,cb=`#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`,hb=`#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`,ub=`float metalnessFactor = metalness; #ifdef USE_METALNESSMAP vec4 texelMetalness = texture2D( metalnessMap, vMetalnessMapUv ); metalnessFactor *= texelMetalness.b; #endif`,db=`#ifdef USE_METALNESSMAP uniform sampler2D metalnessMap; #endif`,fb=`#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`,pb=`#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`,mb=`#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`,gb=`#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`,xb=`#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`,vb=`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;`,bb=`#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`,yb=`#ifndef FLAT_SHADED varying vec3 vNormal; #ifdef USE_TANGENT varying vec3 vTangent; varying vec3 vBitangent; #endif #endif`,_b=`#ifndef FLAT_SHADED varying vec3 vNormal; #ifdef USE_TANGENT varying vec3 vTangent; varying vec3 vBitangent; #endif #endif`,Mb=`#ifndef FLAT_SHADED vNormal = normalize( transformedNormal ); #ifdef USE_TANGENT vTangent = normalize( transformedTangent ); vBitangent = normalize( cross( vNormal, vTangent ) * tangent.w ); #endif #endif`,wb=`#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`,Sb=`#ifdef USE_CLEARCOAT vec3 clearcoatNormal = nonPerturbedNormal; #endif`,Eb=`#ifdef USE_CLEARCOAT_NORMALMAP vec3 clearcoatMapN = texture2D( clearcoatNormalMap, vClearcoatNormalMapUv ).xyz * 2.0 - 1.0; clearcoatMapN.xy *= clearcoatNormalScale; clearcoatNormal = normalize( tbn2 * clearcoatMapN ); #endif`,Tb=`#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`,Cb=`#ifdef USE_IRIDESCENCEMAP uniform sampler2D iridescenceMap; #endif #ifdef USE_IRIDESCENCE_THICKNESSMAP uniform sampler2D iridescenceThicknessMap; #endif`,Ab=`#ifdef OPAQUE diffuseColor.a = 1.0; #endif #ifdef USE_TRANSMISSION diffuseColor.a *= material.transmissionAlpha; #endif gl_FragColor = vec4( outgoingLight, diffuseColor.a );`,Pb=`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 ); }`,Rb=`#ifdef PREMULTIPLIED_ALPHA gl_FragColor.rgb *= gl_FragColor.a; #endif`,Lb=`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;`,Ib=`#ifdef DITHERING gl_FragColor.rgb = dithering( gl_FragColor.rgb ); #endif`,Db=`#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`,Bb=`float roughnessFactor = roughness; #ifdef USE_ROUGHNESSMAP vec4 texelRoughness = texture2D( roughnessMap, vRoughnessMapUv ); roughnessFactor *= texelRoughness.g; #endif`,Nb=`#ifdef USE_ROUGHNESSMAP uniform sampler2D roughnessMap; #endif`,kb=`#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`,Ub=`#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`,Ob=`#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`,Fb=`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; }`,zb=`#ifdef USE_SKINNING mat4 boneMatX = getBoneMatrix( skinIndex.x ); mat4 boneMatY = getBoneMatrix( skinIndex.y ); mat4 boneMatZ = getBoneMatrix( skinIndex.z ); mat4 boneMatW = getBoneMatrix( skinIndex.w ); #endif`,Hb=`#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`,Vb=`#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`,Gb=`#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`,Wb=`float specularStrength; #ifdef USE_SPECULARMAP vec4 texelSpecular = texture2D( specularMap, vSpecularMapUv ); specularStrength = texelSpecular.r; #else specularStrength = 1.0; #endif`,Xb=`#ifdef USE_SPECULARMAP uniform sampler2D specularMap; #endif`,jb=`#if defined( TONE_MAPPING ) gl_FragColor.rgb = toneMapping( gl_FragColor.rgb ); #endif`,qb=`#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; }`,Zb=`#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`,Yb=`#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`,$b=`#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`,Kb=`#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`,Jb=`#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`,Qb=`#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 et={alphahash_fragment:t1,alphahash_pars_fragment:n1,alphamap_fragment:i1,alphamap_pars_fragment:s1,alphatest_fragment:r1,alphatest_pars_fragment:o1,aomap_fragment:a1,aomap_pars_fragment:l1,batching_pars_vertex:c1,batching_vertex:h1,begin_vertex:u1,beginnormal_vertex:d1,bsdfs:f1,iridescence_fragment:p1,bumpmap_pars_fragment:m1,clipping_planes_fragment:g1,clipping_planes_pars_fragment:x1,clipping_planes_pars_vertex:v1,clipping_planes_vertex:b1,color_fragment:y1,color_pars_fragment:_1,color_pars_vertex:M1,color_vertex:w1,common:S1,cube_uv_reflection_fragment:E1,defaultnormal_vertex:T1,displacementmap_pars_vertex:C1,displacementmap_vertex:A1,emissivemap_fragment:P1,emissivemap_pars_fragment:R1,colorspace_fragment:L1,colorspace_pars_fragment:I1,envmap_fragment:D1,envmap_common_pars_fragment:B1,envmap_pars_fragment:N1,envmap_pars_vertex:k1,envmap_physical_pars_fragment:q1,envmap_vertex:U1,fog_vertex:O1,fog_pars_vertex:F1,fog_fragment:z1,fog_pars_fragment:H1,gradientmap_pars_fragment:V1,lightmap_pars_fragment:G1,lights_lambert_fragment:W1,lights_lambert_pars_fragment:X1,lights_pars_begin:j1,lights_toon_fragment:Z1,lights_toon_pars_fragment:Y1,lights_phong_fragment:$1,lights_phong_pars_fragment:K1,lights_physical_fragment:J1,lights_physical_pars_fragment:Q1,lights_fragment_begin:eb,lights_fragment_maps:tb,lights_fragment_end:nb,logdepthbuf_fragment:ib,logdepthbuf_pars_fragment:sb,logdepthbuf_pars_vertex:rb,logdepthbuf_vertex:ob,map_fragment:ab,map_pars_fragment:lb,map_particle_fragment:cb,map_particle_pars_fragment:hb,metalnessmap_fragment:ub,metalnessmap_pars_fragment:db,morphinstance_vertex:fb,morphcolor_vertex:pb,morphnormal_vertex:mb,morphtarget_pars_vertex:gb,morphtarget_vertex:xb,normal_fragment_begin:vb,normal_fragment_maps:bb,normal_pars_fragment:yb,normal_pars_vertex:_b,normal_vertex:Mb,normalmap_pars_fragment:wb,clearcoat_normal_fragment_begin:Sb,clearcoat_normal_fragment_maps:Eb,clearcoat_pars_fragment:Tb,iridescence_pars_fragment:Cb,opaque_fragment:Ab,packing:Pb,premultiplied_alpha_fragment:Rb,project_vertex:Lb,dithering_fragment:Ib,dithering_pars_fragment:Db,roughnessmap_fragment:Bb,roughnessmap_pars_fragment:Nb,shadowmap_pars_fragment:kb,shadowmap_pars_vertex:Ub,shadowmap_vertex:Ob,shadowmask_pars_fragment:Fb,skinbase_vertex:zb,skinning_pars_vertex:Hb,skinning_vertex:Vb,skinnormal_vertex:Gb,specularmap_fragment:Wb,specularmap_pars_fragment:Xb,tonemapping_fragment:jb,tonemapping_pars_fragment:qb,transmission_fragment:Zb,transmission_pars_fragment:Yb,uv_pars_fragment:$b,uv_pars_vertex:Kb,uv_vertex:Jb,worldpos_vertex:Qb,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 }`,distanceRGBA_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; }`,distanceRGBA_frag:`#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 ); }`,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 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 #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 }`,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 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 #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 }`,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 #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 #include void main() { #include gl_FragColor = vec4( color, opacity * ( 1.0 - getShadowMask() ) ); #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 }`},Pe={common:{diffuse:{value:new He(16777215)},opacity:{value:1},map:{value:null},mapTransform:{value:new $e},alphaMap:{value:null},alphaMapTransform:{value:new $e},alphaTest:{value:0}},specularmap:{specularMap:{value:null},specularMapTransform:{value:new $e}},envmap:{envMap:{value:null},envMapRotation:{value:new $e},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 $e}},lightmap:{lightMap:{value:null},lightMapIntensity:{value:1},lightMapTransform:{value:new $e}},bumpmap:{bumpMap:{value:null},bumpMapTransform:{value:new $e},bumpScale:{value:1}},normalmap:{normalMap:{value:null},normalMapTransform:{value:new $e},normalScale:{value:new ue(1,1)}},displacementmap:{displacementMap:{value:null},displacementMapTransform:{value:new $e},displacementScale:{value:1},displacementBias:{value:0}},emissivemap:{emissiveMap:{value:null},emissiveMapTransform:{value:new $e}},metalnessmap:{metalnessMap:{value:null},metalnessMapTransform:{value:new $e}},roughnessmap:{roughnessMap:{value:null},roughnessMapTransform:{value:new $e}},gradientmap:{gradientMap:{value:null}},fog:{fogDensity:{value:25e-5},fogNear:{value:1},fogFar:{value:2e3},fogColor:{value:new He(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 He(16777215)},opacity:{value:1},size:{value:1},scale:{value:1},map:{value:null},alphaMap:{value:null},alphaMapTransform:{value:new $e},alphaTest:{value:0},uvTransform:{value:new $e}},sprite:{diffuse:{value:new He(16777215)},opacity:{value:1},center:{value:new ue(.5,.5)},rotation:{value:0},map:{value:null},mapTransform:{value:new $e},alphaMap:{value:null},alphaMapTransform:{value:new $e},alphaTest:{value:0}}},li={basic:{uniforms:cn([Pe.common,Pe.specularmap,Pe.envmap,Pe.aomap,Pe.lightmap,Pe.fog]),vertexShader:et.meshbasic_vert,fragmentShader:et.meshbasic_frag},lambert:{uniforms:cn([Pe.common,Pe.specularmap,Pe.envmap,Pe.aomap,Pe.lightmap,Pe.emissivemap,Pe.bumpmap,Pe.normalmap,Pe.displacementmap,Pe.fog,Pe.lights,{emissive:{value:new He(0)}}]),vertexShader:et.meshlambert_vert,fragmentShader:et.meshlambert_frag},phong:{uniforms:cn([Pe.common,Pe.specularmap,Pe.envmap,Pe.aomap,Pe.lightmap,Pe.emissivemap,Pe.bumpmap,Pe.normalmap,Pe.displacementmap,Pe.fog,Pe.lights,{emissive:{value:new He(0)},specular:{value:new He(1118481)},shininess:{value:30}}]),vertexShader:et.meshphong_vert,fragmentShader:et.meshphong_frag},standard:{uniforms:cn([Pe.common,Pe.envmap,Pe.aomap,Pe.lightmap,Pe.emissivemap,Pe.bumpmap,Pe.normalmap,Pe.displacementmap,Pe.roughnessmap,Pe.metalnessmap,Pe.fog,Pe.lights,{emissive:{value:new He(0)},roughness:{value:1},metalness:{value:0},envMapIntensity:{value:1}}]),vertexShader:et.meshphysical_vert,fragmentShader:et.meshphysical_frag},toon:{uniforms:cn([Pe.common,Pe.aomap,Pe.lightmap,Pe.emissivemap,Pe.bumpmap,Pe.normalmap,Pe.displacementmap,Pe.gradientmap,Pe.fog,Pe.lights,{emissive:{value:new He(0)}}]),vertexShader:et.meshtoon_vert,fragmentShader:et.meshtoon_frag},matcap:{uniforms:cn([Pe.common,Pe.bumpmap,Pe.normalmap,Pe.displacementmap,Pe.fog,{matcap:{value:null}}]),vertexShader:et.meshmatcap_vert,fragmentShader:et.meshmatcap_frag},points:{uniforms:cn([Pe.points,Pe.fog]),vertexShader:et.points_vert,fragmentShader:et.points_frag},dashed:{uniforms:cn([Pe.common,Pe.fog,{scale:{value:1},dashSize:{value:1},totalSize:{value:2}}]),vertexShader:et.linedashed_vert,fragmentShader:et.linedashed_frag},depth:{uniforms:cn([Pe.common,Pe.displacementmap]),vertexShader:et.depth_vert,fragmentShader:et.depth_frag},normal:{uniforms:cn([Pe.common,Pe.bumpmap,Pe.normalmap,Pe.displacementmap,{opacity:{value:1}}]),vertexShader:et.meshnormal_vert,fragmentShader:et.meshnormal_frag},sprite:{uniforms:cn([Pe.sprite,Pe.fog]),vertexShader:et.sprite_vert,fragmentShader:et.sprite_frag},background:{uniforms:{uvTransform:{value:new $e},t2D:{value:null},backgroundIntensity:{value:1}},vertexShader:et.background_vert,fragmentShader:et.background_frag},backgroundCube:{uniforms:{envMap:{value:null},flipEnvMap:{value:-1},backgroundBlurriness:{value:0},backgroundIntensity:{value:1},backgroundRotation:{value:new $e}},vertexShader:et.backgroundCube_vert,fragmentShader:et.backgroundCube_frag},cube:{uniforms:{tCube:{value:null},tFlip:{value:-1},opacity:{value:1}},vertexShader:et.cube_vert,fragmentShader:et.cube_frag},equirect:{uniforms:{tEquirect:{value:null}},vertexShader:et.equirect_vert,fragmentShader:et.equirect_frag},distanceRGBA:{uniforms:cn([Pe.common,Pe.displacementmap,{referencePosition:{value:new R},nearDistance:{value:1},farDistance:{value:1e3}}]),vertexShader:et.distanceRGBA_vert,fragmentShader:et.distanceRGBA_frag},shadow:{uniforms:cn([Pe.lights,Pe.fog,{color:{value:new He(0)},opacity:{value:1}}]),vertexShader:et.shadow_vert,fragmentShader:et.shadow_frag}};li.physical={uniforms:cn([li.standard.uniforms,{clearcoat:{value:0},clearcoatMap:{value:null},clearcoatMapTransform:{value:new $e},clearcoatNormalMap:{value:null},clearcoatNormalMapTransform:{value:new $e},clearcoatNormalScale:{value:new ue(1,1)},clearcoatRoughness:{value:0},clearcoatRoughnessMap:{value:null},clearcoatRoughnessMapTransform:{value:new $e},dispersion:{value:0},iridescence:{value:0},iridescenceMap:{value:null},iridescenceMapTransform:{value:new $e},iridescenceIOR:{value:1.3},iridescenceThicknessMinimum:{value:100},iridescenceThicknessMaximum:{value:400},iridescenceThicknessMap:{value:null},iridescenceThicknessMapTransform:{value:new $e},sheen:{value:0},sheenColor:{value:new He(0)},sheenColorMap:{value:null},sheenColorMapTransform:{value:new $e},sheenRoughness:{value:1},sheenRoughnessMap:{value:null},sheenRoughnessMapTransform:{value:new $e},transmission:{value:0},transmissionMap:{value:null},transmissionMapTransform:{value:new $e},transmissionSamplerSize:{value:new ue},transmissionSamplerMap:{value:null},thickness:{value:0},thicknessMap:{value:null},thicknessMapTransform:{value:new $e},attenuationDistance:{value:0},attenuationColor:{value:new He(0)},specularColor:{value:new He(1,1,1)},specularColorMap:{value:null},specularColorMapTransform:{value:new $e},specularIntensity:{value:1},specularIntensityMap:{value:null},specularIntensityMapTransform:{value:new $e},anisotropyVector:{value:new ue},anisotropyMap:{value:null},anisotropyMapTransform:{value:new $e}}]),vertexShader:et.meshphysical_vert,fragmentShader:et.meshphysical_frag};const Ua={r:0,b:0,g:0},gs=new wn,ey=new De;function ty(s,e,t,n,i,r,o){const a=new He(0);let l=r===!0?0:1,c,h,u=null,f=0,d=null;function m(v){let y=v.isScene===!0?v.background:null;return y&&y.isTexture&&(y=(v.backgroundBlurriness>0?t:e).get(y)),y}function p(v){let y=!1;const M=m(v);M===null?g(a,l):M&&M.isColor&&(g(M,1),y=!0);const E=s.xr.getEnvironmentBlendMode();E==="additive"?n.buffers.color.setClear(0,0,0,1,o):E==="alpha-blend"&&n.buffers.color.setClear(0,0,0,0,o),(s.autoClear||y)&&(n.buffers.depth.setTest(!0),n.buffers.depth.setMask(!0),n.buffers.color.setMask(!0),s.clear(s.autoClearColor,s.autoClearDepth,s.autoClearStencil))}function x(v,y){const M=m(y);M&&(M.isCubeTexture||M.mapping===Go)?(h===void 0&&(h=new ht(new Wi(1,1,1),new Jt({name:"BackgroundCubeMaterial",uniforms:ir(li.backgroundCube.uniforms),vertexShader:li.backgroundCube.vertexShader,fragmentShader:li.backgroundCube.fragmentShader,side:ln,depthTest:!1,depthWrite:!1,fog:!1,allowOverride:!1})),h.geometry.deleteAttribute("normal"),h.geometry.deleteAttribute("uv"),h.onBeforeRender=function(E,C,P){this.matrixWorld.copyPosition(P.matrixWorld)},Object.defineProperty(h.material,"envMap",{get:function(){return this.uniforms.envMap.value}}),i.update(h)),gs.copy(y.backgroundRotation),gs.x*=-1,gs.y*=-1,gs.z*=-1,M.isCubeTexture&&M.isRenderTargetTexture===!1&&(gs.y*=-1,gs.z*=-1),h.material.uniforms.envMap.value=M,h.material.uniforms.flipEnvMap.value=M.isCubeTexture&&M.isRenderTargetTexture===!1?-1:1,h.material.uniforms.backgroundBlurriness.value=y.backgroundBlurriness,h.material.uniforms.backgroundIntensity.value=y.backgroundIntensity,h.material.uniforms.backgroundRotation.value.setFromMatrix4(ey.makeRotationFromEuler(gs)),h.material.toneMapped=it.getTransfer(M.colorSpace)!==lt,(u!==M||f!==M.version||d!==s.toneMapping)&&(h.material.needsUpdate=!0,u=M,f=M.version,d=s.toneMapping),h.layers.enableAll(),v.unshift(h,h.geometry,h.material,0,0,null)):M&&M.isTexture&&(c===void 0&&(c=new ht(new xo(2,2),new Jt({name:"BackgroundMaterial",uniforms:ir(li.background.uniforms),vertexShader:li.background.vertexShader,fragmentShader:li.background.fragmentShader,side:Pn,depthTest:!1,depthWrite:!1,fog:!1,allowOverride:!1})),c.geometry.deleteAttribute("normal"),Object.defineProperty(c.material,"map",{get:function(){return this.uniforms.t2D.value}}),i.update(c)),c.material.uniforms.t2D.value=M,c.material.uniforms.backgroundIntensity.value=y.backgroundIntensity,c.material.toneMapped=it.getTransfer(M.colorSpace)!==lt,M.matrixAutoUpdate===!0&&M.updateMatrix(),c.material.uniforms.uvTransform.value.copy(M.matrix),(u!==M||f!==M.version||d!==s.toneMapping)&&(c.material.needsUpdate=!0,u=M,f=M.version,d=s.toneMapping),c.layers.enableAll(),v.unshift(c,c.geometry,c.material,0,0,null))}function g(v,y){v.getRGB(Ua,tf(s)),n.buffers.color.setClear(Ua.r,Ua.g,Ua.b,y,o)}function b(){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 a},setClearColor:function(v,y=1){a.set(v),l=y,g(a,l)},getClearAlpha:function(){return l},setClearAlpha:function(v){l=v,g(a,l)},render:p,addToRenderList:x,dispose:b}}function ny(s,e){const t=s.getParameter(s.MAX_VERTEX_ATTRIBS),n={},i=f(null);let r=i,o=!1;function a(S,I,A,B,w){let F=!1;const W=u(B,A,I);r!==W&&(r=W,c(r.object)),F=d(S,B,A,w),F&&m(S,B,A,w),w!==null&&e.update(w,s.ELEMENT_ARRAY_BUFFER),(F||o)&&(o=!1,y(S,I,A,B),w!==null&&s.bindBuffer(s.ELEMENT_ARRAY_BUFFER,e.get(w).buffer))}function l(){return s.createVertexArray()}function c(S){return s.bindVertexArray(S)}function h(S){return s.deleteVertexArray(S)}function u(S,I,A){const B=A.wireframe===!0;let w=n[S.id];w===void 0&&(w={},n[S.id]=w);let F=w[I.id];F===void 0&&(F={},w[I.id]=F);let W=F[B];return W===void 0&&(W=f(l()),F[B]=W),W}function f(S){const I=[],A=[],B=[];for(let w=0;w=0){const ie=w[$];let j=F[$];if(j===void 0&&($==="instanceMatrix"&&S.instanceMatrix&&(j=S.instanceMatrix),$==="instanceColor"&&S.instanceColor&&(j=S.instanceColor)),ie===void 0||ie.attribute!==j||j&&ie.data!==j.data)return!0;W++}return r.attributesNum!==W||r.index!==B}function m(S,I,A,B){const w={},F=I.attributes;let W=0;const X=A.getAttributes();for(const $ in X)if(X[$].location>=0){let ie=F[$];ie===void 0&&($==="instanceMatrix"&&S.instanceMatrix&&(ie=S.instanceMatrix),$==="instanceColor"&&S.instanceColor&&(ie=S.instanceColor));const j={};j.attribute=ie,ie&&ie.data&&(j.data=ie.data),w[$]=j,W++}r.attributes=w,r.attributesNum=W,r.index=B}function p(){const S=r.newAttributes;for(let I=0,A=S.length;I=0){let Z=w[X];if(Z===void 0&&(X==="instanceMatrix"&&S.instanceMatrix&&(Z=S.instanceMatrix),X==="instanceColor"&&S.instanceColor&&(Z=S.instanceColor)),Z!==void 0){const ie=Z.normalized,j=Z.itemSize,Y=e.get(Z);if(Y===void 0)continue;const ge=Y.buffer,pe=Y.type,de=Y.bytesPerElement,se=pe===s.INT||pe===s.UNSIGNED_INT||Z.gpuType===nc;if(Z.isInterleavedBufferAttribute){const ce=Z.data,fe=ce.stride,be=Z.offset;if(ce.isInstancedInterleavedBuffer){for(let Se=0;Se<$.locationSize;Se++)g($.location+Se,ce.meshPerAttribute);S.isInstancedMesh!==!0&&B._maxInstanceCount===void 0&&(B._maxInstanceCount=ce.meshPerAttribute*ce.count)}else for(let Se=0;Se<$.locationSize;Se++)x($.location+Se);s.bindBuffer(s.ARRAY_BUFFER,ge);for(let Se=0;Se<$.locationSize;Se++)v($.location+Se,j/$.locationSize,pe,ie,fe*de,(be+j/$.locationSize*Se)*de,se)}else{if(Z.isInstancedBufferAttribute){for(let ce=0;ce<$.locationSize;ce++)g($.location+ce,Z.meshPerAttribute);S.isInstancedMesh!==!0&&B._maxInstanceCount===void 0&&(B._maxInstanceCount=Z.meshPerAttribute*Z.count)}else for(let ce=0;ce<$.locationSize;ce++)x($.location+ce);s.bindBuffer(s.ARRAY_BUFFER,ge);for(let ce=0;ce<$.locationSize;ce++)v($.location+ce,j/$.locationSize,pe,ie,j*de,j/$.locationSize*ce*de,se)}}else if(W!==void 0){const ie=W[X];if(ie!==void 0)switch(ie.length){case 2:s.vertexAttrib2fv($.location,ie);break;case 3:s.vertexAttrib3fv($.location,ie);break;case 4:s.vertexAttrib4fv($.location,ie);break;default:s.vertexAttrib1fv($.location,ie)}}}}b()}function M(){P();for(const S in n){const I=n[S];for(const A in I){const B=I[A];for(const w in B)h(B[w].object),delete B[w];delete I[A]}delete n[S]}}function E(S){if(n[S.id]===void 0)return;const I=n[S.id];for(const A in I){const B=I[A];for(const w in B)h(B[w].object),delete B[w];delete I[A]}delete n[S.id]}function C(S){for(const I in n){const A=n[I];if(A[S.id]===void 0)continue;const B=A[S.id];for(const w in B)h(B[w].object),delete B[w];delete A[S.id]}}function P(){_(),o=!0,r!==i&&(r=i,c(r.object))}function _(){i.geometry=null,i.program=null,i.wireframe=!1}return{setup:a,reset:P,resetDefaultState:_,dispose:M,releaseStatesOfGeometry:E,releaseStatesOfProgram:C,initAttributes:p,enableAttribute:x,disableUnusedAttributes:b}}function iy(s,e,t){let n;function i(c){n=c}function r(c,h){s.drawArrays(n,c,h),t.update(h,n,1)}function o(c,h,u){u!==0&&(s.drawArraysInstanced(n,c,h,u),t.update(h,n,u))}function a(c,h,u){if(u===0)return;e.get("WEBGL_multi_draw").multiDrawArraysWEBGL(n,c,0,h,0,u);let d=0;for(let m=0;m0&&s.getShaderPrecisionFormat(s.FRAGMENT_SHADER,s.HIGH_FLOAT).precision>0)return"highp";C="mediump"}return C==="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&&(ze("WebGLRenderer:",c,"not supported, using",h,"instead."),c=h);const u=t.logarithmicDepthBuffer===!0,f=t.reversedDepthBuffer===!0&&e.has("EXT_clip_control"),d=s.getParameter(s.MAX_TEXTURE_IMAGE_UNITS),m=s.getParameter(s.MAX_VERTEX_TEXTURE_IMAGE_UNITS),p=s.getParameter(s.MAX_TEXTURE_SIZE),x=s.getParameter(s.MAX_CUBE_MAP_TEXTURE_SIZE),g=s.getParameter(s.MAX_VERTEX_ATTRIBS),b=s.getParameter(s.MAX_VERTEX_UNIFORM_VECTORS),v=s.getParameter(s.MAX_VARYING_VECTORS),y=s.getParameter(s.MAX_FRAGMENT_UNIFORM_VECTORS),M=m>0,E=s.getParameter(s.MAX_SAMPLES);return{isWebGL2:!0,getMaxAnisotropy:r,getMaxPrecision:l,textureFormatReadable:o,textureTypeReadable:a,precision:c,logarithmicDepthBuffer:u,reversedDepthBuffer:f,maxTextures:d,maxVertexTextures:m,maxTextureSize:p,maxCubemapSize:x,maxAttributes:g,maxVertexUniforms:b,maxVaryings:v,maxFragmentUniforms:y,vertexTextures:M,maxSamples:E}}function ry(s){const e=this;let t=null,n=0,i=!1,r=!1;const o=new Pt,a=new $e,l={value:null,needsUpdate:!1};this.uniform=l,this.numPlanes=0,this.numIntersection=0,this.init=function(u,f){const d=u.length!==0||f||n!==0||i;return i=f,n=u.length,d},this.beginShadows=function(){r=!0,h(null)},this.endShadows=function(){r=!1},this.setGlobalState=function(u,f){t=h(u,f,0)},this.setState=function(u,f,d){const m=u.clippingPlanes,p=u.clipIntersection,x=u.clipShadows,g=s.get(u);if(!i||m===null||m.length===0||r&&!x)r?h(null):c();else{const b=r?0:n,v=b*4;let y=g.clippingState||null;l.value=y,y=h(m,f,v,d);for(let M=0;M!==v;++M)y[M]=t[M];g.clippingState=y,this.numIntersection=p?this.numPlanes:0,this.numPlanes+=b}};function c(){l.value!==t&&(l.value=t,l.needsUpdate=n>0),e.numPlanes=n,e.numIntersection=0}function h(u,f,d,m){const p=u!==null?u.length:0;let x=null;if(p!==0){if(x=l.value,m!==!0||x===null){const g=d+p*4,b=f.matrixWorldInverse;a.getNormalMatrix(b),(x===null||x.length0){const c=new Sx(l.height);return c.fromEquirectangularTexture(s,o),e.set(o,c),o.addEventListener("dispose",i),t(c.texture,o.mapping)}else return null}}return o}function i(o){const a=o.target;a.removeEventListener("dispose",i);const l=e.get(a);l!==void 0&&(e.delete(a),l.dispose())}function r(){e=new WeakMap}return{get:n,dispose:r}}const qi=4,ip=[.125,.215,.35,.446,.526,.582],xs=20,ay=256,_o=new ps,sp=new He;let Oh=null,Fh=0,zh=0,Hh=!1;const ly=new R;class rp{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,n=.1,i=100,r={}){const{size:o=256,position:a=ly}=r;Oh=this._renderer.getRenderTarget(),Fh=this._renderer.getActiveCubeFace(),zh=this._renderer.getActiveMipmapLevel(),Hh=this._renderer.xr.enabled,this._renderer.xr.enabled=!1,this._setSize(o);const l=this._allocateTargets();return l.depthBuffer=!0,this._sceneToCubeUV(e,n,i,l,a),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=lp(),this._compileMaterial(this._cubemapMaterial))}compileEquirectangularShader(){this._equirectMaterial===null&&(this._equirectMaterial=ap(),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?M:0,M,M),u.setRenderTarget(i),g&&u.render(p,l),u.render(e,l)}u.toneMapping=d,u.autoClear=f,e.background=b}_textureToCubeUV(e,t){const n=this._renderer,i=e.mapping===zs||e.mapping===Hs;i?(this._cubemapMaterial===null&&(this._cubemapMaterial=lp()),this._cubemapMaterial.uniforms.flipEnvMap.value=e.isRenderTargetTexture===!1?-1:1):this._equirectMaterial===null&&(this._equirectMaterial=ap());const r=i?this._cubemapMaterial:this._equirectMaterial,o=this._lodMeshes[0];o.material=r;const a=r.uniforms;a.envMap.value=e;const l=this._cubeSize;wr(t,0,0,3*l,2*l),n.setRenderTarget(t),n.render(o,_o)}_applyPMREM(e){const t=this._renderer,n=t.autoClear;t.autoClear=!1;const i=this._lodMeshes.length;for(let r=1;rm-qi?n-m+qi:0),g=4*(this._cubeSize-p);l.envMap.value=e.texture,l.roughness.value=d,l.mipInt.value=m-t,wr(r,x,g,3*p,2*p),i.setRenderTarget(r),i.render(a,_o),l.envMap.value=r.texture,l.roughness.value=0,l.mipInt.value=m-n,wr(e,x,g,3*p,2*p),i.setRenderTarget(e),i.render(a,_o)}_blur(e,t,n,i,r){const o=this._pingPongRenderTarget;this._halfBlur(e,o,t,n,i,"latitudinal",r),this._halfBlur(o,e,n,n,i,"longitudinal",r)}_halfBlur(e,t,n,i,r,o,a){const l=this._renderer,c=this._blurMaterial;o!=="latitudinal"&&o!=="longitudinal"&&Qe("blur direction must be either latitudinal or longitudinal!");const h=3,u=this._lodMeshes[i];u.material=c;const f=c.uniforms,d=this._sizeLods[n]-1,m=isFinite(r)?Math.PI/(2*d):2*Math.PI/(2*xs-1),p=r/m,x=isFinite(r)?1+Math.floor(h*p):xs;x>xs&&ze(`sigmaRadians, ${r}, is too large and will clip, as it requested ${x} samples when the maximum is set to ${xs}`);const g=[];let b=0;for(let C=0;Cv-qi?i-v+qi:0),E=4*(this._cubeSize-y);wr(t,M,E,3*y,2*y),l.setRenderTarget(t),l.render(u,_o)}}function cy(s){const e=[],t=[],n=[];let i=s;const r=s-qi+1+ip.length;for(let o=0;os-qi?l=ip[o-s+qi-1]:o===0&&(l=0),t.push(l);const c=1/(a-2),h=-c,u=1+c,f=[h,h,u,h,u,u,h,h,u,u,h,u],d=6,m=6,p=3,x=2,g=1,b=new Float32Array(p*m*d),v=new Float32Array(x*m*d),y=new Float32Array(g*m*d);for(let E=0;E2?0:-1,_=[C,P,0,C+2/3,P,0,C+2/3,P+1,0,C,P,0,C+2/3,P+1,0,C,P+1,0];b.set(_,p*m*E),v.set(f,x*m*E);const S=[E,E,E,E,E,E];y.set(S,g*m*E)}const M=new bt;M.setAttribute("position",new vt(b,p)),M.setAttribute("uv",new vt(v,x)),M.setAttribute("faceIndex",new vt(y,g)),n.push(new ht(M,null)),i>qi&&i--}return{lodMeshes:n,sizeLods:e,sigmas:t}}function op(s,e,t){const n=new qn(s,e,t);return n.texture.mapping=Go,n.texture.name="PMREM.cubeUv",n.scissorTest=!0,n}function wr(s,e,t,n,i){s.viewport.set(e,t,n,i),s.scissor.set(e,t,n,i)}function hy(s,e,t){return new Jt({name:"PMREMGGXConvolution",defines:{GGX_SAMPLES:ay,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:Oa(),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:Wt,depthTest:!1,depthWrite:!1})}function uy(s,e,t){const n=new Float32Array(xs),i=new R(0,1,0);return new Jt({name:"SphericalGaussianBlur",defines:{n:xs,CUBEUV_TEXEL_WIDTH:1/e,CUBEUV_TEXEL_HEIGHT:1/t,CUBEUV_MAX_MIP:`${s}.0`},uniforms:{envMap:{value:null},samples:{value:1},weights:{value:n},latitudinal:{value:!1},dTheta:{value:0},mipInt:{value:0},poleAxis:{value:i}},vertexShader:Oa(),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:Wt,depthTest:!1,depthWrite:!1})}function ap(){return new Jt({name:"EquirectangularToCubeUV",uniforms:{envMap:{value:null}},vertexShader:Oa(),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:Wt,depthTest:!1,depthWrite:!1})}function lp(){return new Jt({name:"CubemapToCubeUV",uniforms:{envMap:{value:null},flipEnvMap:{value:-1}},vertexShader:Oa(),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:Wt,depthTest:!1,depthWrite:!1})}function Oa(){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 dy(s){let e=new WeakMap,t=null;function n(a){if(a&&a.isTexture){const l=a.mapping,c=l===ec||l===tc,h=l===zs||l===Hs;if(c||h){let u=e.get(a);const f=u!==void 0?u.texture.pmremVersion:0;if(a.isRenderTargetTexture&&a.pmremVersion!==f)return t===null&&(t=new rp(s)),u=c?t.fromEquirectangular(a,u):t.fromCubemap(a,u),u.texture.pmremVersion=a.pmremVersion,e.set(a,u),u.texture;if(u!==void 0)return u.texture;{const d=a.image;return c&&d&&d.height>0||h&&d&&i(d)?(t===null&&(t=new rp(s)),u=c?t.fromEquirectangular(a):t.fromCubemap(a),u.texture.pmremVersion=a.pmremVersion,e.set(a,u),a.addEventListener("dispose",r),u.texture):null}}}return a}function i(a){let l=0;const c=6;for(let h=0;he.maxTextureSize&&(M=Math.ceil(y/e.maxTextureSize),y=e.maxTextureSize);const E=new Float32Array(y*M*4*u),C=new zd(E,y,M,u);C.type=Xn,C.needsUpdate=!0;const P=v*4;for(let S=0;S0)return s;const i=e*t;let r=pp[i];if(r===void 0&&(r=new Float32Array(i),pp[i]=r),e!==0){n.toArray(r,0);for(let o=1,a=0;o!==e;++o)a+=t,s[o].toArray(r,a)}return r}function zt(s,e){if(s.length!==e.length)return!1;for(let t=0,n=s.length;t":" "} ${a}: ${t[o]}`)}return n.join(` `)}const _p=new $e;function d_(s){it._getMatrix(_p,it.workingColorSpace,s);const e=`mat3( ${_p.elements.map(t=>t.toFixed(4))} )`;switch(it.getTransfer(s)){case Ko:return[e,"LinearTransferOETF"];case lt:return[e,"sRGBTransferOETF"];default:return ze("WebGLProgram: Unsupported color space: ",s),[e,"LinearTransferOETF"]}}function Mp(s,e,t){const n=s.getShaderParameter(e,s.COMPILE_STATUS),r=(s.getShaderInfoLog(e)||"").trim();if(n&&r==="")return"";const o=/ERROR: 0:(\d+)/.exec(r);if(o){const a=parseInt(o[1]);return t.toUpperCase()+` `+r+` `+u_(s.getShaderSource(e),a)}else return r}function f_(s,e){const t=d_(e);return[`vec4 ${s}( vec4 value ) {`,` return ${t[1]}( vec4( value.rgb * ${t[0]}, value.a ) );`,"}"].join(` `)}function p_(s,e){let t;switch(e){case ud:t="Linear";break;case dd:t="Reinhard";break;case fd:t="Cineon";break;case pd:t="ACESFilmic";break;case gd:t="AgX";break;case xd:t="Neutral";break;case md:t="Custom";break;default:ze("WebGLProgram: Unsupported toneMapping:",e),t="Linear"}return"vec3 "+s+"( vec3 color ) { return "+t+"ToneMapping( color ); }"}const Ha=new R;function m_(){it.getLuminanceCoefficients(Ha);const s=Ha.x.toFixed(4),e=Ha.y.toFixed(4),t=Ha.z.toFixed(4);return["float luminance( const in vec3 rgb ) {",` const vec3 weights = vec3( ${s}, ${e}, ${t} );`," return dot( weights, rgb );","}"].join(` `)}function g_(s){return[s.extensionClipCullDistance?"#extension GL_ANGLE_clip_cull_distance : require":"",s.extensionMultiDraw?"#extension GL_ANGLE_multi_draw : require":""].filter(Mo).join(` `)}function x_(s){const e=[];for(const t in s){const n=s[t];n!==!1&&e.push("#define "+t+" "+n)}return e.join(` `)}function v_(s,e){const t={},n=s.getProgramParameter(e,s.ACTIVE_ATTRIBUTES);for(let i=0;i/gm;function Gh(s){return s.replace(b_,__)}const y_=new Map;function __(s,e){let t=et[e];if(t===void 0){const n=y_.get(e);if(n!==void 0)t=et[n],ze('WebGLRenderer: Shader chunk "%s" has been deprecated. Use "%s" instead.',e,n);else throw new Error("Can not resolve #include <"+e+">")}return Gh(t)}const M_=/#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 Ep(s){return s.replace(M_,w_)}function w_(s,e,t,n){let i="";for(let r=parseInt(e);r0&&(x+=` `),g=["#define SHADER_TYPE "+t.shaderType,"#define SHADER_NAME "+t.shaderName,m].filter(Mo).join(` `),g.length>0&&(g+=` `)):(x=[Tp(t),"#define SHADER_TYPE "+t.shaderType,"#define SHADER_NAME "+t.shaderName,m,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(Mo).join(` `),g=[Tp(t),"#define SHADER_TYPE "+t.shaderType,"#define SHADER_NAME "+t.shaderName,m,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 "+u:"",f?"#define CUBEUV_TEXEL_WIDTH "+f.texelWidth:"",f?"#define CUBEUV_TEXEL_HEIGHT "+f.texelHeight:"",f?"#define CUBEUV_MAX_MIP "+f.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!==ki?"#define TONE_MAPPING":"",t.toneMapping!==ki?et.tonemapping_pars_fragment:"",t.toneMapping!==ki?p_("toneMapping",t.toneMapping):"",t.dithering?"#define DITHERING":"",t.opaque?"#define OPAQUE":"",et.colorspace_pars_fragment,f_("linearToOutputTexel",t.outputColorSpace),m_(),t.useDepthPacking?"#define DEPTH_PACKING "+t.depthPacking:"",` `].filter(Mo).join(` `)),o=Gh(o),o=wp(o,t),o=Sp(o,t),a=Gh(a),a=wp(a,t),a=Sp(a,t),o=Ep(o),a=Ep(a),t.isRawShaderMaterial!==!0&&(b=`#version 300 es `,x=[d,"#define attribute in","#define varying out","#define texture2D texture"].join(` `)+` `+x,g=["#define varying in",t.glslVersion===Dd?"":"layout(location = 0) out highp vec4 pc_fragColor;",t.glslVersion===Dd?"":"#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(` `)+` `+g);const v=b+x+o,y=b+g+a,M=yp(i,i.VERTEX_SHADER,v),E=yp(i,i.FRAGMENT_SHADER,y);i.attachShader(p,M),i.attachShader(p,E),t.index0AttributeName!==void 0?i.bindAttribLocation(p,0,t.index0AttributeName):t.morphTargets===!0&&i.bindAttribLocation(p,0,"position"),i.linkProgram(p);function C(I){if(s.debug.checkShaderErrors){const A=i.getProgramInfoLog(p)||"",B=i.getShaderInfoLog(M)||"",w=i.getShaderInfoLog(E)||"",F=A.trim(),W=B.trim(),X=w.trim();let $=!0,Z=!0;if(i.getProgramParameter(p,i.LINK_STATUS)===!1)if($=!1,typeof s.debug.onShaderError=="function")s.debug.onShaderError(i,p,M,E);else{const ie=Mp(i,M,"vertex"),j=Mp(i,E,"fragment");Qe("THREE.WebGLProgram: Shader Error "+i.getError()+" - VALIDATE_STATUS "+i.getProgramParameter(p,i.VALIDATE_STATUS)+` Material Name: `+I.name+` Material Type: `+I.type+` Program Info Log: `+F+` `+ie+` `+j)}else F!==""?ze("WebGLProgram: Program Info Log:",F):(W===""||X==="")&&(Z=!1);Z&&(I.diagnostics={runnable:$,programLog:F,vertexShader:{log:W,prefix:x},fragmentShader:{log:X,prefix:g}})}i.deleteShader(M),i.deleteShader(E),P=new za(i,p),_=v_(i,p)}let P;this.getUniforms=function(){return P===void 0&&C(this),P};let _;this.getAttributes=function(){return _===void 0&&C(this),_};let S=t.rendererExtensionParallelShaderCompile===!1;return this.isReady=function(){return S===!1&&(S=i.getProgramParameter(p,c_)),S},this.destroy=function(){n.releaseStatesOfProgram(this),i.deleteProgram(p),this.program=void 0},this.type=t.shaderType,this.name=t.shaderName,this.id=h_++,this.cacheKey=e,this.usedTimes=1,this.program=p,this.vertexShader=M,this.fragmentShader=E,this}let R_=0;class L_{constructor(){this.shaderCache=new Map,this.materialCache=new Map}update(e){const t=e.vertexShader,n=e.fragmentShader,i=this._getShaderStage(t),r=this._getShaderStage(n),o=this._getShaderCacheForMaterial(e);return o.has(i)===!1&&(o.add(i),i.usedTimes++),o.has(r)===!1&&(o.add(r),r.usedTimes++),this}remove(e){const t=this.materialCache.get(e);for(const n of t)n.usedTimes--,n.usedTimes===0&&this.shaderCache.delete(n.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 n=t.get(e);return n===void 0&&(n=new Set,t.set(e,n)),n}_getShaderStage(e){const t=this.shaderCache;let n=t.get(e);return n===void 0&&(n=new I_(e),t.set(e,n)),n}}class I_{constructor(e){this.id=R_++,this.code=e,this.usedTimes=0}}function D_(s,e,t,n,i,r,o){const a=new Jc,l=new L_,c=new Set,h=[],u=i.logarithmicDepthBuffer,f=i.vertexTextures;let d=i.precision;const m={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 p(_){return c.add(_),_===0?"uv":`uv${_}`}function x(_,S,I,A,B){const w=A.fog,F=B.geometry,W=_.isMeshStandardMaterial?A.environment:null,X=(_.isMeshStandardMaterial?t:e).get(_.envMap||W),$=X&&X.mapping===Go?X.image.height:null,Z=m[_.type];_.precision!==null&&(d=i.getMaxPrecision(_.precision),d!==_.precision&&ze("WebGLProgram.getParameters:",_.precision,"not supported, using",d,"instead."));const ie=F.morphAttributes.position||F.morphAttributes.normal||F.morphAttributes.color,j=ie!==void 0?ie.length:0;let Y=0;F.morphAttributes.position!==void 0&&(Y=1),F.morphAttributes.normal!==void 0&&(Y=2),F.morphAttributes.color!==void 0&&(Y=3);let ge,pe,de,se;if(Z){const ft=li[Z];ge=ft.vertexShader,pe=ft.fragmentShader}else ge=_.vertexShader,pe=_.fragmentShader,l.update(_),de=l.getVertexShaderID(_),se=l.getFragmentShaderID(_);const ce=s.getRenderTarget(),fe=s.state.buffers.depth.getReversed(),be=B.isInstancedMesh===!0,Se=B.isBatchedMesh===!0,Ne=!!_.map,Je=!!_.matcap,ke=!!X,T=!!_.aoMap,D=!!_.lightMap,V=!!_.bumpMap,U=!!_.normalMap,k=!!_.displacementMap,z=!!_.emissiveMap,ee=!!_.metalnessMap,J=!!_.roughnessMap,G=_.anisotropy>0,N=_.clearcoat>0,L=_.dispersion>0,H=_.iridescence>0,K=_.sheen>0,le=_.transmission>0,te=G&&!!_.anisotropyMap,Ce=N&&!!_.clearcoatMap,ye=N&&!!_.clearcoatNormalMap,Re=N&&!!_.clearcoatRoughnessMap,Ie=H&&!!_.iridescenceMap,he=H&&!!_.iridescenceThicknessMap,_e=K&&!!_.sheenColorMap,Ve=K&&!!_.sheenRoughnessMap,Ue=!!_.specularMap,Ae=!!_.specularColorMap,Ge=!!_.specularIntensityMap,q=le&&!!_.transmissionMap,Te=le&&!!_.thicknessMap,Me=!!_.gradientMap,we=!!_.alphaMap,ve=_.alphaTest>0,me=!!_.alphaHash,Oe=!!_.extensions;let Ye=ki;_.toneMapped&&(ce===null||ce.isXRRenderTarget===!0)&&(Ye=s.toneMapping);const Mt={shaderID:Z,shaderType:_.type,shaderName:_.name,vertexShader:ge,fragmentShader:pe,defines:_.defines,customVertexShaderID:de,customFragmentShaderID:se,isRawShaderMaterial:_.isRawShaderMaterial===!0,glslVersion:_.glslVersion,precision:d,batching:Se,batchingColor:Se&&B._colorsTexture!==null,instancing:be,instancingColor:be&&B.instanceColor!==null,instancingMorph:be&&B.morphTexture!==null,supportsVertexTextures:f,outputColorSpace:ce===null?s.outputColorSpace:ce.isXRRenderTarget===!0?ce.texture.colorSpace:tn,alphaToCoverage:!!_.alphaToCoverage,map:Ne,matcap:Je,envMap:ke,envMapMode:ke&&X.mapping,envMapCubeUVHeight:$,aoMap:T,lightMap:D,bumpMap:V,normalMap:U,displacementMap:f&&k,emissiveMap:z,normalMapObjectSpace:U&&_.normalMapType===L0,normalMapTangentSpace:U&&_.normalMapType===$o,metalnessMap:ee,roughnessMap:J,anisotropy:G,anisotropyMap:te,clearcoat:N,clearcoatMap:Ce,clearcoatNormalMap:ye,clearcoatRoughnessMap:Re,dispersion:L,iridescence:H,iridescenceMap:Ie,iridescenceThicknessMap:he,sheen:K,sheenColorMap:_e,sheenRoughnessMap:Ve,specularMap:Ue,specularColorMap:Ae,specularIntensityMap:Ge,transmission:le,transmissionMap:q,thicknessMap:Te,gradientMap:Me,opaque:_.transparent===!1&&_.blending===Os&&_.alphaToCoverage===!1,alphaMap:we,alphaTest:ve,alphaHash:me,combine:_.combine,mapUv:Ne&&p(_.map.channel),aoMapUv:T&&p(_.aoMap.channel),lightMapUv:D&&p(_.lightMap.channel),bumpMapUv:V&&p(_.bumpMap.channel),normalMapUv:U&&p(_.normalMap.channel),displacementMapUv:k&&p(_.displacementMap.channel),emissiveMapUv:z&&p(_.emissiveMap.channel),metalnessMapUv:ee&&p(_.metalnessMap.channel),roughnessMapUv:J&&p(_.roughnessMap.channel),anisotropyMapUv:te&&p(_.anisotropyMap.channel),clearcoatMapUv:Ce&&p(_.clearcoatMap.channel),clearcoatNormalMapUv:ye&&p(_.clearcoatNormalMap.channel),clearcoatRoughnessMapUv:Re&&p(_.clearcoatRoughnessMap.channel),iridescenceMapUv:Ie&&p(_.iridescenceMap.channel),iridescenceThicknessMapUv:he&&p(_.iridescenceThicknessMap.channel),sheenColorMapUv:_e&&p(_.sheenColorMap.channel),sheenRoughnessMapUv:Ve&&p(_.sheenRoughnessMap.channel),specularMapUv:Ue&&p(_.specularMap.channel),specularColorMapUv:Ae&&p(_.specularColorMap.channel),specularIntensityMapUv:Ge&&p(_.specularIntensityMap.channel),transmissionMapUv:q&&p(_.transmissionMap.channel),thicknessMapUv:Te&&p(_.thicknessMap.channel),alphaMapUv:we&&p(_.alphaMap.channel),vertexTangents:!!F.attributes.tangent&&(U||G),vertexColors:_.vertexColors,vertexAlphas:_.vertexColors===!0&&!!F.attributes.color&&F.attributes.color.itemSize===4,pointsUvs:B.isPoints===!0&&!!F.attributes.uv&&(Ne||we),fog:!!w,useFog:_.fog===!0,fogExp2:!!w&&w.isFogExp2,flatShading:_.flatShading===!0&&_.wireframe===!1,sizeAttenuation:_.sizeAttenuation===!0,logarithmicDepthBuffer:u,reversedDepthBuffer:fe,skinning:B.isSkinnedMesh===!0,morphTargets:F.morphAttributes.position!==void 0,morphNormals:F.morphAttributes.normal!==void 0,morphColors:F.morphAttributes.color!==void 0,morphTargetsCount:j,morphTextureStride:Y,numDirLights:S.directional.length,numPointLights:S.point.length,numSpotLights:S.spot.length,numSpotLightMaps:S.spotLightMap.length,numRectAreaLights:S.rectArea.length,numHemiLights:S.hemi.length,numDirLightShadows:S.directionalShadowMap.length,numPointLightShadows:S.pointShadowMap.length,numSpotLightShadows:S.spotShadowMap.length,numSpotLightShadowsWithMaps:S.numSpotLightShadowsWithMaps,numLightProbes:S.numLightProbes,numClippingPlanes:o.numPlanes,numClipIntersection:o.numIntersection,dithering:_.dithering,shadowMapEnabled:s.shadowMap.enabled&&I.length>0,shadowMapType:s.shadowMap.type,toneMapping:Ye,decodeVideoTexture:Ne&&_.map.isVideoTexture===!0&&it.getTransfer(_.map.colorSpace)===lt,decodeVideoTextureEmissive:z&&_.emissiveMap.isVideoTexture===!0&&it.getTransfer(_.emissiveMap.colorSpace)===lt,premultipliedAlpha:_.premultipliedAlpha,doubleSided:_.side===St,flipSided:_.side===ln,useDepthPacking:_.depthPacking>=0,depthPacking:_.depthPacking||0,index0AttributeName:_.index0AttributeName,extensionClipCullDistance:Oe&&_.extensions.clipCullDistance===!0&&n.has("WEBGL_clip_cull_distance"),extensionMultiDraw:(Oe&&_.extensions.multiDraw===!0||Se)&&n.has("WEBGL_multi_draw"),rendererExtensionParallelShaderCompile:n.has("KHR_parallel_shader_compile"),customProgramCacheKey:_.customProgramCacheKey()};return Mt.vertexUv1s=c.has(1),Mt.vertexUv2s=c.has(2),Mt.vertexUv3s=c.has(3),c.clear(),Mt}function g(_){const S=[];if(_.shaderID?S.push(_.shaderID):(S.push(_.customVertexShaderID),S.push(_.customFragmentShaderID)),_.defines!==void 0)for(const I in _.defines)S.push(I),S.push(_.defines[I]);return _.isRawShaderMaterial===!1&&(b(S,_),v(S,_),S.push(s.outputColorSpace)),S.push(_.customProgramCacheKey),S.join()}function b(_,S){_.push(S.precision),_.push(S.outputColorSpace),_.push(S.envMapMode),_.push(S.envMapCubeUVHeight),_.push(S.mapUv),_.push(S.alphaMapUv),_.push(S.lightMapUv),_.push(S.aoMapUv),_.push(S.bumpMapUv),_.push(S.normalMapUv),_.push(S.displacementMapUv),_.push(S.emissiveMapUv),_.push(S.metalnessMapUv),_.push(S.roughnessMapUv),_.push(S.anisotropyMapUv),_.push(S.clearcoatMapUv),_.push(S.clearcoatNormalMapUv),_.push(S.clearcoatRoughnessMapUv),_.push(S.iridescenceMapUv),_.push(S.iridescenceThicknessMapUv),_.push(S.sheenColorMapUv),_.push(S.sheenRoughnessMapUv),_.push(S.specularMapUv),_.push(S.specularColorMapUv),_.push(S.specularIntensityMapUv),_.push(S.transmissionMapUv),_.push(S.thicknessMapUv),_.push(S.combine),_.push(S.fogExp2),_.push(S.sizeAttenuation),_.push(S.morphTargetsCount),_.push(S.morphAttributeCount),_.push(S.numDirLights),_.push(S.numPointLights),_.push(S.numSpotLights),_.push(S.numSpotLightMaps),_.push(S.numHemiLights),_.push(S.numRectAreaLights),_.push(S.numDirLightShadows),_.push(S.numPointLightShadows),_.push(S.numSpotLightShadows),_.push(S.numSpotLightShadowsWithMaps),_.push(S.numLightProbes),_.push(S.shadowMapType),_.push(S.toneMapping),_.push(S.numClippingPlanes),_.push(S.numClipIntersection),_.push(S.depthPacking)}function v(_,S){a.disableAll(),S.supportsVertexTextures&&a.enable(0),S.instancing&&a.enable(1),S.instancingColor&&a.enable(2),S.instancingMorph&&a.enable(3),S.matcap&&a.enable(4),S.envMap&&a.enable(5),S.normalMapObjectSpace&&a.enable(6),S.normalMapTangentSpace&&a.enable(7),S.clearcoat&&a.enable(8),S.iridescence&&a.enable(9),S.alphaTest&&a.enable(10),S.vertexColors&&a.enable(11),S.vertexAlphas&&a.enable(12),S.vertexUv1s&&a.enable(13),S.vertexUv2s&&a.enable(14),S.vertexUv3s&&a.enable(15),S.vertexTangents&&a.enable(16),S.anisotropy&&a.enable(17),S.alphaHash&&a.enable(18),S.batching&&a.enable(19),S.dispersion&&a.enable(20),S.batchingColor&&a.enable(21),S.gradientMap&&a.enable(22),_.push(a.mask),a.disableAll(),S.fog&&a.enable(0),S.useFog&&a.enable(1),S.flatShading&&a.enable(2),S.logarithmicDepthBuffer&&a.enable(3),S.reversedDepthBuffer&&a.enable(4),S.skinning&&a.enable(5),S.morphTargets&&a.enable(6),S.morphNormals&&a.enable(7),S.morphColors&&a.enable(8),S.premultipliedAlpha&&a.enable(9),S.shadowMapEnabled&&a.enable(10),S.doubleSided&&a.enable(11),S.flipSided&&a.enable(12),S.useDepthPacking&&a.enable(13),S.dithering&&a.enable(14),S.transmission&&a.enable(15),S.sheen&&a.enable(16),S.opaque&&a.enable(17),S.pointsUvs&&a.enable(18),S.decodeVideoTexture&&a.enable(19),S.decodeVideoTextureEmissive&&a.enable(20),S.alphaToCoverage&&a.enable(21),_.push(a.mask)}function y(_){const S=m[_.type];let I;if(S){const A=li[S];I=Xi.clone(A.uniforms)}else I=_.uniforms;return I}function M(_,S){let I;for(let A=0,B=h.length;A0?n.push(g):d.transparent===!0?i.push(g):t.push(g)}function l(u,f,d,m,p,x){const g=o(u,f,d,m,p,x);d.transmission>0?n.unshift(g):d.transparent===!0?i.unshift(g):t.unshift(g)}function c(u,f){t.length>1&&t.sort(u||N_),n.length>1&&n.sort(f||Cp),i.length>1&&i.sort(f||Cp)}function h(){for(let u=e,f=s.length;u=r.length?(o=new Ap,r.push(o)):o=r[i],o}function t(){s=new WeakMap}return{get:e,dispose:t}}function U_(){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 He};break;case"SpotLight":t={position:new R,direction:new R,color:new He,distance:0,coneCos:0,penumbraCos:0,decay:0};break;case"PointLight":t={position:new R,color:new He,distance:0,decay:0};break;case"HemisphereLight":t={direction:new R,skyColor:new He,groundColor:new He};break;case"RectAreaLight":t={color:new He,position:new R,halfWidth:new R,halfHeight:new R};break}return s[e.id]=t,t}}}function O_(){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 ue};break;case"SpotLight":t={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new ue};break;case"PointLight":t={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new ue,shadowCameraNear:1,shadowCameraFar:1e3};break}return s[e.id]=t,t}}}let F_=0;function z_(s,e){return(e.castShadow?2:0)-(s.castShadow?2:0)+(e.map?1:0)-(s.map?1:0)}function H_(s){const e=new U_,t=O_(),n={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++)n.probe.push(new R);const i=new R,r=new De,o=new De;function a(c){let h=0,u=0,f=0;for(let _=0;_<9;_++)n.probe[_].set(0,0,0);let d=0,m=0,p=0,x=0,g=0,b=0,v=0,y=0,M=0,E=0,C=0;c.sort(z_);for(let _=0,S=c.length;_0&&(s.has("OES_texture_float_linear")===!0?(n.rectAreaLTC1=Pe.LTC_FLOAT_1,n.rectAreaLTC2=Pe.LTC_FLOAT_2):(n.rectAreaLTC1=Pe.LTC_HALF_1,n.rectAreaLTC2=Pe.LTC_HALF_2)),n.ambient[0]=h,n.ambient[1]=u,n.ambient[2]=f;const P=n.hash;(P.directionalLength!==d||P.pointLength!==m||P.spotLength!==p||P.rectAreaLength!==x||P.hemiLength!==g||P.numDirectionalShadows!==b||P.numPointShadows!==v||P.numSpotShadows!==y||P.numSpotMaps!==M||P.numLightProbes!==C)&&(n.directional.length=d,n.spot.length=p,n.rectArea.length=x,n.point.length=m,n.hemi.length=g,n.directionalShadow.length=b,n.directionalShadowMap.length=b,n.pointShadow.length=v,n.pointShadowMap.length=v,n.spotShadow.length=y,n.spotShadowMap.length=y,n.directionalShadowMatrix.length=b,n.pointShadowMatrix.length=v,n.spotLightMatrix.length=y+M-E,n.spotLightMap.length=M,n.numSpotLightShadowsWithMaps=E,n.numLightProbes=C,P.directionalLength=d,P.pointLength=m,P.spotLength=p,P.rectAreaLength=x,P.hemiLength=g,P.numDirectionalShadows=b,P.numPointShadows=v,P.numSpotShadows=y,P.numSpotMaps=M,P.numLightProbes=C,n.version=F_++)}function l(c,h){let u=0,f=0,d=0,m=0,p=0;const x=h.matrixWorldInverse;for(let g=0,b=c.length;g=o.length?(a=new Pp(s),o.push(a)):a=o[r],a}function n(){e=new WeakMap}return{get:t,dispose:n}}const G_=`void main() { gl_Position = vec4( position, 1.0 ); }`,W_=`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 X_(s,e,t){let n=new xh;const i=new ue,r=new ue,o=new tt,a=new vv({depthPacking:R0}),l=new bv,c={},h=t.maxTextureSize,u={[Pn]:ln,[ln]:Pn,[St]:St},f=new Jt({defines:{VSM_SAMPLES:8},uniforms:{shadow_pass:{value:null},resolution:{value:new ue},radius:{value:4}},vertexShader:G_,fragmentShader:W_}),d=f.clone();d.defines.HORIZONTAL_PASS=1;const m=new bt;m.setAttribute("position",new vt(new Float32Array([-1,-1,.5,3,-1,.5,-1,3,.5]),3));const p=new ht(m,f),x=this;this.enabled=!1,this.autoUpdate=!0,this.needsUpdate=!1,this.type=od;let g=this.type;this.render=function(E,C,P){if(x.enabled===!1||x.autoUpdate===!1&&x.needsUpdate===!1||E.length===0)return;const _=s.getRenderTarget(),S=s.getActiveCubeFace(),I=s.getActiveMipmapLevel(),A=s.state;A.setBlending(Wt),A.buffers.depth.getReversed()===!0?A.buffers.color.setClear(0,0,0,0):A.buffers.color.setClear(1,1,1,1),A.buffers.depth.setTest(!0),A.setScissorTest(!1);const B=g!==mi&&this.type===mi,w=g===mi&&this.type!==mi;for(let F=0,W=E.length;Fh||i.y>h)&&(i.x>h&&(r.x=Math.floor(h/Z.x),i.x=r.x*Z.x,$.mapSize.x=r.x),i.y>h&&(r.y=Math.floor(h/Z.y),i.y=r.y*Z.y,$.mapSize.y=r.y)),$.map===null||B===!0||w===!0){const j=this.type!==mi?{minFilter:$t,magFilter:$t}:{};$.map!==null&&$.map.dispose(),$.map=new qn(i.x,i.y,j),$.map.texture.name=X.name+".shadowMap",$.camera.updateProjectionMatrix()}s.setRenderTarget($.map),s.clear();const ie=$.getViewportCount();for(let j=0;j0||C.map&&C.alphaTest>0||C.alphaToCoverage===!0){const A=S.uuid,B=C.uuid;let w=c[A];w===void 0&&(w={},c[A]=w);let F=w[B];F===void 0&&(F=S.clone(),w[B]=F,C.addEventListener("dispose",M)),S=F}if(S.visible=C.visible,S.wireframe=C.wireframe,_===mi?S.side=C.shadowSide!==null?C.shadowSide:C.side:S.side=C.shadowSide!==null?C.shadowSide:u[C.side],S.alphaMap=C.alphaMap,S.alphaTest=C.alphaToCoverage===!0?.5:C.alphaTest,S.map=C.map,S.clipShadows=C.clipShadows,S.clippingPlanes=C.clippingPlanes,S.clipIntersection=C.clipIntersection,S.displacementMap=C.displacementMap,S.displacementScale=C.displacementScale,S.displacementBias=C.displacementBias,S.wireframeLinewidth=C.wireframeLinewidth,S.linewidth=C.linewidth,P.isPointLight===!0&&S.isMeshDistanceMaterial===!0){const A=s.properties.get(S);A.light=P}return S}function y(E,C,P,_,S){if(E.visible===!1)return;if(E.layers.test(C.layers)&&(E.isMesh||E.isLine||E.isPoints)&&(E.castShadow||E.receiveShadow&&S===mi)&&(!E.frustumCulled||n.intersectsObject(E))){E.modelViewMatrix.multiplyMatrices(P.matrixWorldInverse,E.matrixWorld);const B=e.update(E),w=E.material;if(Array.isArray(w)){const F=B.groups;for(let W=0,X=F.length;W=1):$.indexOf("OpenGL ES")!==-1&&(X=parseFloat(/^OpenGL ES (\d)/.exec($)[1]),W=X>=2);let Z=null,ie={};const j=s.getParameter(s.SCISSOR_BOX),Y=s.getParameter(s.VIEWPORT),ge=new tt().fromArray(j),pe=new tt().fromArray(Y);function de(q,Te,Me,we){const ve=new Uint8Array(4),me=s.createTexture();s.bindTexture(q,me),s.texParameteri(q,s.TEXTURE_MIN_FILTER,s.NEAREST),s.texParameteri(q,s.TEXTURE_MAG_FILTER,s.NEAREST);for(let Oe=0;Oe"u"?!1:/OculusBrowser/g.test(navigator.userAgent),c=new ue,h=new WeakMap;let u;const f=new WeakMap;let d=!1;try{d=typeof OffscreenCanvas<"u"&&new OffscreenCanvas(1,1).getContext("2d")!==null}catch{}function m(N,L){return d?new OffscreenCanvas(N,L):Zr("canvas")}function p(N,L,H){let K=1;const le=G(N);if((le.width>H||le.height>H)&&(K=H/Math.max(le.width,le.height)),K<1)if(typeof HTMLImageElement<"u"&&N instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&N instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&N instanceof ImageBitmap||typeof VideoFrame<"u"&&N instanceof VideoFrame){const te=Math.floor(K*le.width),Ce=Math.floor(K*le.height);u===void 0&&(u=m(te,Ce));const ye=L?m(te,Ce):u;return ye.width=te,ye.height=Ce,ye.getContext("2d").drawImage(N,0,0,te,Ce),ze("WebGLRenderer: Texture has been resized from ("+le.width+"x"+le.height+") to ("+te+"x"+Ce+")."),ye}else return"data"in N&&ze("WebGLRenderer: Image in DataTexture is too big ("+le.width+"x"+le.height+")."),N;return N}function x(N){return N.generateMipmaps}function g(N){s.generateMipmap(N)}function b(N){return N.isWebGLCubeRenderTarget?s.TEXTURE_CUBE_MAP:N.isWebGL3DRenderTarget?s.TEXTURE_3D:N.isWebGLArrayRenderTarget||N.isCompressedArrayTexture?s.TEXTURE_2D_ARRAY:s.TEXTURE_2D}function v(N,L,H,K,le=!1){if(N!==null){if(s[N]!==void 0)return s[N];ze("WebGLRenderer: Attempt to use non-existing WebGL internal format '"+N+"'")}let te=L;if(L===s.RED&&(H===s.FLOAT&&(te=s.R32F),H===s.HALF_FLOAT&&(te=s.R16F),H===s.UNSIGNED_BYTE&&(te=s.R8)),L===s.RED_INTEGER&&(H===s.UNSIGNED_BYTE&&(te=s.R8UI),H===s.UNSIGNED_SHORT&&(te=s.R16UI),H===s.UNSIGNED_INT&&(te=s.R32UI),H===s.BYTE&&(te=s.R8I),H===s.SHORT&&(te=s.R16I),H===s.INT&&(te=s.R32I)),L===s.RG&&(H===s.FLOAT&&(te=s.RG32F),H===s.HALF_FLOAT&&(te=s.RG16F),H===s.UNSIGNED_BYTE&&(te=s.RG8)),L===s.RG_INTEGER&&(H===s.UNSIGNED_BYTE&&(te=s.RG8UI),H===s.UNSIGNED_SHORT&&(te=s.RG16UI),H===s.UNSIGNED_INT&&(te=s.RG32UI),H===s.BYTE&&(te=s.RG8I),H===s.SHORT&&(te=s.RG16I),H===s.INT&&(te=s.RG32I)),L===s.RGB_INTEGER&&(H===s.UNSIGNED_BYTE&&(te=s.RGB8UI),H===s.UNSIGNED_SHORT&&(te=s.RGB16UI),H===s.UNSIGNED_INT&&(te=s.RGB32UI),H===s.BYTE&&(te=s.RGB8I),H===s.SHORT&&(te=s.RGB16I),H===s.INT&&(te=s.RGB32I)),L===s.RGBA_INTEGER&&(H===s.UNSIGNED_BYTE&&(te=s.RGBA8UI),H===s.UNSIGNED_SHORT&&(te=s.RGBA16UI),H===s.UNSIGNED_INT&&(te=s.RGBA32UI),H===s.BYTE&&(te=s.RGBA8I),H===s.SHORT&&(te=s.RGBA16I),H===s.INT&&(te=s.RGBA32I)),L===s.RGB&&(H===s.UNSIGNED_INT_5_9_9_9_REV&&(te=s.RGB9_E5),H===s.UNSIGNED_INT_10F_11F_11F_REV&&(te=s.R11F_G11F_B10F)),L===s.RGBA){const Ce=le?Ko:it.getTransfer(K);H===s.FLOAT&&(te=s.RGBA32F),H===s.HALF_FLOAT&&(te=s.RGBA16F),H===s.UNSIGNED_BYTE&&(te=Ce===lt?s.SRGB8_ALPHA8:s.RGBA8),H===s.UNSIGNED_SHORT_4_4_4_4&&(te=s.RGBA4),H===s.UNSIGNED_SHORT_5_5_5_1&&(te=s.RGB5_A1)}return(te===s.R16F||te===s.R32F||te===s.RG16F||te===s.RG32F||te===s.RGBA16F||te===s.RGBA32F)&&e.get("EXT_color_buffer_float"),te}function y(N,L){let H;return N?L===null||L===rs||L===Vs?H=s.DEPTH24_STENCIL8:L===Xn?H=s.DEPTH32F_STENCIL8:L===Wr&&(H=s.DEPTH24_STENCIL8,ze("DepthTexture: 16 bit depth attachment is not supported with stencil. Using 24-bit attachment.")):L===null||L===rs||L===Vs?H=s.DEPTH_COMPONENT24:L===Xn?H=s.DEPTH_COMPONENT32F:L===Wr&&(H=s.DEPTH_COMPONENT16),H}function M(N,L){return x(N)===!0||N.isFramebufferTexture&&N.minFilter!==$t&&N.minFilter!==Kt?Math.log2(Math.max(L.width,L.height))+1:N.mipmaps!==void 0&&N.mipmaps.length>0?N.mipmaps.length:N.isCompressedTexture&&Array.isArray(N.image)?L.mipmaps.length:1}function E(N){const L=N.target;L.removeEventListener("dispose",E),P(L),L.isVideoTexture&&h.delete(L)}function C(N){const L=N.target;L.removeEventListener("dispose",C),S(L)}function P(N){const L=n.get(N);if(L.__webglInit===void 0)return;const H=N.source,K=f.get(H);if(K){const le=K[L.__cacheKey];le.usedTimes--,le.usedTimes===0&&_(N),Object.keys(K).length===0&&f.delete(H)}n.remove(N)}function _(N){const L=n.get(N);s.deleteTexture(L.__webglTexture);const H=N.source,K=f.get(H);delete K[L.__cacheKey],o.memory.textures--}function S(N){const L=n.get(N);if(N.depthTexture&&(N.depthTexture.dispose(),n.remove(N.depthTexture)),N.isWebGLCubeRenderTarget)for(let K=0;K<6;K++){if(Array.isArray(L.__webglFramebuffer[K]))for(let le=0;le=i.maxTextures&&ze("WebGLTextures: Trying to use "+N+" texture units while this GPU supports only "+i.maxTextures),I+=1,N}function w(N){const L=[];return L.push(N.wrapS),L.push(N.wrapT),L.push(N.wrapR||0),L.push(N.magFilter),L.push(N.minFilter),L.push(N.anisotropy),L.push(N.internalFormat),L.push(N.format),L.push(N.type),L.push(N.generateMipmaps),L.push(N.premultiplyAlpha),L.push(N.flipY),L.push(N.unpackAlignment),L.push(N.colorSpace),L.join()}function F(N,L){const H=n.get(N);if(N.isVideoTexture&&ee(N),N.isRenderTargetTexture===!1&&N.isExternalTexture!==!0&&N.version>0&&H.__version!==N.version){const K=N.image;if(K===null)ze("WebGLRenderer: Texture marked for update but no image data found.");else if(K.complete===!1)ze("WebGLRenderer: Texture marked for update but image is incomplete");else{se(H,N,L);return}}else N.isExternalTexture&&(H.__webglTexture=N.sourceTexture?N.sourceTexture:null);t.bindTexture(s.TEXTURE_2D,H.__webglTexture,s.TEXTURE0+L)}function W(N,L){const H=n.get(N);if(N.isRenderTargetTexture===!1&&N.version>0&&H.__version!==N.version){se(H,N,L);return}else N.isExternalTexture&&(H.__webglTexture=N.sourceTexture?N.sourceTexture:null);t.bindTexture(s.TEXTURE_2D_ARRAY,H.__webglTexture,s.TEXTURE0+L)}function X(N,L){const H=n.get(N);if(N.isRenderTargetTexture===!1&&N.version>0&&H.__version!==N.version){se(H,N,L);return}t.bindTexture(s.TEXTURE_3D,H.__webglTexture,s.TEXTURE0+L)}function $(N,L){const H=n.get(N);if(N.version>0&&H.__version!==N.version){ce(H,N,L);return}t.bindTexture(s.TEXTURE_CUBE_MAP,H.__webglTexture,s.TEXTURE0+L)}const Z={[ni]:s.REPEAT,[ii]:s.CLAMP_TO_EDGE,[Wo]:s.MIRRORED_REPEAT},ie={[$t]:s.NEAREST,[yd]:s.NEAREST_MIPMAP_NEAREST,[Gr]:s.NEAREST_MIPMAP_LINEAR,[Kt]:s.LINEAR,[Xo]:s.LINEAR_MIPMAP_NEAREST,[gi]:s.LINEAR_MIPMAP_LINEAR},j={[I0]:s.NEVER,[O0]:s.ALWAYS,[D0]:s.LESS,[Id]:s.LEQUAL,[B0]:s.EQUAL,[U0]:s.GEQUAL,[N0]:s.GREATER,[k0]:s.NOTEQUAL};function Y(N,L){if(L.type===Xn&&e.has("OES_texture_float_linear")===!1&&(L.magFilter===Kt||L.magFilter===Xo||L.magFilter===Gr||L.magFilter===gi||L.minFilter===Kt||L.minFilter===Xo||L.minFilter===Gr||L.minFilter===gi)&&ze("WebGLRenderer: Unable to use linear filtering with floating point textures. OES_texture_float_linear not supported on this device."),s.texParameteri(N,s.TEXTURE_WRAP_S,Z[L.wrapS]),s.texParameteri(N,s.TEXTURE_WRAP_T,Z[L.wrapT]),(N===s.TEXTURE_3D||N===s.TEXTURE_2D_ARRAY)&&s.texParameteri(N,s.TEXTURE_WRAP_R,Z[L.wrapR]),s.texParameteri(N,s.TEXTURE_MAG_FILTER,ie[L.magFilter]),s.texParameteri(N,s.TEXTURE_MIN_FILTER,ie[L.minFilter]),L.compareFunction&&(s.texParameteri(N,s.TEXTURE_COMPARE_MODE,s.COMPARE_REF_TO_TEXTURE),s.texParameteri(N,s.TEXTURE_COMPARE_FUNC,j[L.compareFunction])),e.has("EXT_texture_filter_anisotropic")===!0){if(L.magFilter===$t||L.minFilter!==Gr&&L.minFilter!==gi||L.type===Xn&&e.has("OES_texture_float_linear")===!1)return;if(L.anisotropy>1||n.get(L).__currentAnisotropy){const H=e.get("EXT_texture_filter_anisotropic");s.texParameterf(N,H.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(L.anisotropy,i.getMaxAnisotropy())),n.get(L).__currentAnisotropy=L.anisotropy}}}function ge(N,L){let H=!1;N.__webglInit===void 0&&(N.__webglInit=!0,L.addEventListener("dispose",E));const K=L.source;let le=f.get(K);le===void 0&&(le={},f.set(K,le));const te=w(L);if(te!==N.__cacheKey){le[te]===void 0&&(le[te]={texture:s.createTexture(),usedTimes:0},o.memory.textures++,H=!0),le[te].usedTimes++;const Ce=le[N.__cacheKey];Ce!==void 0&&(le[N.__cacheKey].usedTimes--,Ce.usedTimes===0&&_(L)),N.__cacheKey=te,N.__webglTexture=le[te].texture}return H}function pe(N,L,H){return Math.floor(Math.floor(N/H)/L)}function de(N,L,H,K){const te=N.updateRanges;if(te.length===0)t.texSubImage2D(s.TEXTURE_2D,0,0,0,L.width,L.height,H,K,L.data);else{te.sort((he,_e)=>he.start-_e.start);let Ce=0;for(let he=1;he0){q&&Te&&t.texStorage2D(s.TEXTURE_2D,we,Ue,Ge[0].width,Ge[0].height);for(let ve=0,me=Ge.length;ve0){const Oe=tp(Ae.width,Ae.height,L.format,L.type);for(const Ye of L.layerUpdates){const Mt=Ae.data.subarray(Ye*Oe/Ae.data.BYTES_PER_ELEMENT,(Ye+1)*Oe/Ae.data.BYTES_PER_ELEMENT);t.compressedTexSubImage3D(s.TEXTURE_2D_ARRAY,ve,0,0,Ye,Ae.width,Ae.height,1,_e,Mt)}L.clearLayerUpdates()}else t.compressedTexSubImage3D(s.TEXTURE_2D_ARRAY,ve,0,0,0,Ae.width,Ae.height,he.depth,_e,Ae.data)}else t.compressedTexImage3D(s.TEXTURE_2D_ARRAY,ve,Ue,Ae.width,Ae.height,he.depth,0,Ae.data,0,0);else ze("WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()");else q?Me&&t.texSubImage3D(s.TEXTURE_2D_ARRAY,ve,0,0,0,Ae.width,Ae.height,he.depth,_e,Ve,Ae.data):t.texImage3D(s.TEXTURE_2D_ARRAY,ve,Ue,Ae.width,Ae.height,he.depth,0,_e,Ve,Ae.data)}else{q&&Te&&t.texStorage2D(s.TEXTURE_2D,we,Ue,Ge[0].width,Ge[0].height);for(let ve=0,me=Ge.length;ve0){const ve=tp(he.width,he.height,L.format,L.type);for(const me of L.layerUpdates){const Oe=he.data.subarray(me*ve/he.data.BYTES_PER_ELEMENT,(me+1)*ve/he.data.BYTES_PER_ELEMENT);t.texSubImage3D(s.TEXTURE_2D_ARRAY,0,0,0,me,he.width,he.height,1,_e,Ve,Oe)}L.clearLayerUpdates()}else t.texSubImage3D(s.TEXTURE_2D_ARRAY,0,0,0,0,he.width,he.height,he.depth,_e,Ve,he.data)}else t.texImage3D(s.TEXTURE_2D_ARRAY,0,Ue,he.width,he.height,he.depth,0,_e,Ve,he.data);else if(L.isData3DTexture)q?(Te&&t.texStorage3D(s.TEXTURE_3D,we,Ue,he.width,he.height,he.depth),Me&&t.texSubImage3D(s.TEXTURE_3D,0,0,0,0,he.width,he.height,he.depth,_e,Ve,he.data)):t.texImage3D(s.TEXTURE_3D,0,Ue,he.width,he.height,he.depth,0,_e,Ve,he.data);else if(L.isFramebufferTexture){if(Te)if(q)t.texStorage2D(s.TEXTURE_2D,we,Ue,he.width,he.height);else{let ve=he.width,me=he.height;for(let Oe=0;Oe>=1,me>>=1}}else if(Ge.length>0){if(q&&Te){const ve=G(Ge[0]);t.texStorage2D(s.TEXTURE_2D,we,Ue,ve.width,ve.height)}for(let ve=0,me=Ge.length;ve0&&we++;const me=G(_e[0]);t.texStorage2D(s.TEXTURE_CUBE_MAP,we,Ge,me.width,me.height)}for(let me=0;me<6;me++)if(he){q?Me&&t.texSubImage2D(s.TEXTURE_CUBE_MAP_POSITIVE_X+me,0,0,0,_e[me].width,_e[me].height,Ue,Ae,_e[me].data):t.texImage2D(s.TEXTURE_CUBE_MAP_POSITIVE_X+me,0,Ge,_e[me].width,_e[me].height,0,Ue,Ae,_e[me].data);for(let Oe=0;Oe>te),Ve=Math.max(1,L.height>>te);le===s.TEXTURE_3D||le===s.TEXTURE_2D_ARRAY?t.texImage3D(le,te,Re,_e,Ve,L.depth,0,Ce,ye,null):t.texImage2D(le,te,Re,_e,Ve,0,Ce,ye,null)}t.bindFramebuffer(s.FRAMEBUFFER,N),z(L)?a.framebufferTexture2DMultisampleEXT(s.FRAMEBUFFER,K,le,he.__webglTexture,0,k(L)):(le===s.TEXTURE_2D||le>=s.TEXTURE_CUBE_MAP_POSITIVE_X&&le<=s.TEXTURE_CUBE_MAP_NEGATIVE_Z)&&s.framebufferTexture2D(s.FRAMEBUFFER,K,le,he.__webglTexture,te),t.bindFramebuffer(s.FRAMEBUFFER,null)}function be(N,L,H){if(s.bindRenderbuffer(s.RENDERBUFFER,N),L.depthBuffer){const K=L.depthTexture,le=K&&K.isDepthTexture?K.type:null,te=y(L.stencilBuffer,le),Ce=L.stencilBuffer?s.DEPTH_STENCIL_ATTACHMENT:s.DEPTH_ATTACHMENT,ye=k(L);z(L)?a.renderbufferStorageMultisampleEXT(s.RENDERBUFFER,ye,te,L.width,L.height):H?s.renderbufferStorageMultisample(s.RENDERBUFFER,ye,te,L.width,L.height):s.renderbufferStorage(s.RENDERBUFFER,te,L.width,L.height),s.framebufferRenderbuffer(s.FRAMEBUFFER,Ce,s.RENDERBUFFER,N)}else{const K=L.textures;for(let le=0;le{delete L.__boundDepthTexture,delete L.__depthDisposeCallback,K.removeEventListener("dispose",le)};K.addEventListener("dispose",le),L.__depthDisposeCallback=le}L.__boundDepthTexture=K}if(N.depthTexture&&!L.__autoAllocateDepthBuffer){if(H)throw new Error("target.depthTexture not supported in Cube render targets");const K=N.texture.mipmaps;K&&K.length>0?Se(L.__webglFramebuffer[0],N):Se(L.__webglFramebuffer,N)}else if(H){L.__webglDepthbuffer=[];for(let K=0;K<6;K++)if(t.bindFramebuffer(s.FRAMEBUFFER,L.__webglFramebuffer[K]),L.__webglDepthbuffer[K]===void 0)L.__webglDepthbuffer[K]=s.createRenderbuffer(),be(L.__webglDepthbuffer[K],N,!1);else{const le=N.stencilBuffer?s.DEPTH_STENCIL_ATTACHMENT:s.DEPTH_ATTACHMENT,te=L.__webglDepthbuffer[K];s.bindRenderbuffer(s.RENDERBUFFER,te),s.framebufferRenderbuffer(s.FRAMEBUFFER,le,s.RENDERBUFFER,te)}}else{const K=N.texture.mipmaps;if(K&&K.length>0?t.bindFramebuffer(s.FRAMEBUFFER,L.__webglFramebuffer[0]):t.bindFramebuffer(s.FRAMEBUFFER,L.__webglFramebuffer),L.__webglDepthbuffer===void 0)L.__webglDepthbuffer=s.createRenderbuffer(),be(L.__webglDepthbuffer,N,!1);else{const le=N.stencilBuffer?s.DEPTH_STENCIL_ATTACHMENT:s.DEPTH_ATTACHMENT,te=L.__webglDepthbuffer;s.bindRenderbuffer(s.RENDERBUFFER,te),s.framebufferRenderbuffer(s.FRAMEBUFFER,le,s.RENDERBUFFER,te)}}t.bindFramebuffer(s.FRAMEBUFFER,null)}function Je(N,L,H){const K=n.get(N);L!==void 0&&fe(K.__webglFramebuffer,N,N.texture,s.COLOR_ATTACHMENT0,s.TEXTURE_2D,0),H!==void 0&&Ne(N)}function ke(N){const L=N.texture,H=n.get(N),K=n.get(L);N.addEventListener("dispose",C);const le=N.textures,te=N.isWebGLCubeRenderTarget===!0,Ce=le.length>1;if(Ce||(K.__webglTexture===void 0&&(K.__webglTexture=s.createTexture()),K.__version=L.version,o.memory.textures++),te){H.__webglFramebuffer=[];for(let ye=0;ye<6;ye++)if(L.mipmaps&&L.mipmaps.length>0){H.__webglFramebuffer[ye]=[];for(let Re=0;Re0){H.__webglFramebuffer=[];for(let ye=0;ye0&&z(N)===!1){H.__webglMultisampledFramebuffer=s.createFramebuffer(),H.__webglColorRenderbuffer=[],t.bindFramebuffer(s.FRAMEBUFFER,H.__webglMultisampledFramebuffer);for(let ye=0;ye0)for(let Re=0;Re0)for(let Re=0;Re0){if(z(N)===!1){const L=N.textures,H=N.width,K=N.height;let le=s.COLOR_BUFFER_BIT;const te=N.stencilBuffer?s.DEPTH_STENCIL_ATTACHMENT:s.DEPTH_ATTACHMENT,Ce=n.get(N),ye=L.length>1;if(ye)for(let Ie=0;Ie0?t.bindFramebuffer(s.DRAW_FRAMEBUFFER,Ce.__webglFramebuffer[0]):t.bindFramebuffer(s.DRAW_FRAMEBUFFER,Ce.__webglFramebuffer);for(let Ie=0;Ie0&&e.has("WEBGL_multisampled_render_to_texture")===!0&&L.__useRenderToTexture!==!1}function ee(N){const L=o.render.frame;h.get(N)!==L&&(h.set(N,L),N.update())}function J(N,L){const H=N.colorSpace,K=N.format,le=N.type;return N.isCompressedTexture===!0||N.isVideoTexture===!0||H!==tn&&H!==Ui&&(it.getTransfer(H)===lt?(K!==mn||le!==Wn)&&ze("WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType."):Qe("WebGLTextures: Unsupported texture color space:",H)),L}function G(N){return typeof HTMLImageElement<"u"&&N instanceof HTMLImageElement?(c.width=N.naturalWidth||N.width,c.height=N.naturalHeight||N.height):typeof VideoFrame<"u"&&N instanceof VideoFrame?(c.width=N.displayWidth,c.height=N.displayHeight):(c.width=N.width,c.height=N.height),c}this.allocateTextureUnit=B,this.resetTextureUnits=A,this.setTexture2D=F,this.setTexture2DArray=W,this.setTexture3D=X,this.setTextureCube=$,this.rebindTextures=Je,this.setupRenderTarget=ke,this.updateRenderTargetMipmap=T,this.updateMultisampleRenderTarget=U,this.setupDepthRenderbuffer=Ne,this.setupFrameBufferTexture=fe,this.useMultisampledRTT=z}function Y_(s,e){function t(n,i=Ui){let r;const o=it.getTransfer(i);if(n===Wn)return s.UNSIGNED_BYTE;if(n===ic)return s.UNSIGNED_SHORT_4_4_4_4;if(n===sc)return s.UNSIGNED_SHORT_5_5_5_1;if(n===wd)return s.UNSIGNED_INT_5_9_9_9_REV;if(n===Sd)return s.UNSIGNED_INT_10F_11F_11F_REV;if(n===_d)return s.BYTE;if(n===Md)return s.SHORT;if(n===Wr)return s.UNSIGNED_SHORT;if(n===nc)return s.INT;if(n===rs)return s.UNSIGNED_INT;if(n===Xn)return s.FLOAT;if(n===xi)return s.HALF_FLOAT;if(n===Ed)return s.ALPHA;if(n===Td)return s.RGB;if(n===mn)return s.RGBA;if(n===Xr)return s.DEPTH_COMPONENT;if(n===Gs)return s.DEPTH_STENCIL;if(n===rc)return s.RED;if(n===oc)return s.RED_INTEGER;if(n===ac)return s.RG;if(n===lc)return s.RG_INTEGER;if(n===cc)return s.RGBA_INTEGER;if(n===jo||n===qo||n===Zo||n===Yo)if(o===lt)if(r=e.get("WEBGL_compressed_texture_s3tc_srgb"),r!==null){if(n===jo)return r.COMPRESSED_SRGB_S3TC_DXT1_EXT;if(n===qo)return r.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;if(n===Zo)return r.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;if(n===Yo)return r.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}else return null;else if(r=e.get("WEBGL_compressed_texture_s3tc"),r!==null){if(n===jo)return r.COMPRESSED_RGB_S3TC_DXT1_EXT;if(n===qo)return r.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(n===Zo)return r.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(n===Yo)return r.COMPRESSED_RGBA_S3TC_DXT5_EXT}else return null;if(n===hc||n===uc||n===dc||n===fc)if(r=e.get("WEBGL_compressed_texture_pvrtc"),r!==null){if(n===hc)return r.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(n===uc)return r.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(n===dc)return r.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(n===fc)return r.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}else return null;if(n===pc||n===mc||n===gc)if(r=e.get("WEBGL_compressed_texture_etc"),r!==null){if(n===pc||n===mc)return o===lt?r.COMPRESSED_SRGB8_ETC2:r.COMPRESSED_RGB8_ETC2;if(n===gc)return o===lt?r.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:r.COMPRESSED_RGBA8_ETC2_EAC}else return null;if(n===xc||n===vc||n===bc||n===yc||n===_c||n===Mc||n===wc||n===Sc||n===Ec||n===Tc||n===Cc||n===Ac||n===Pc||n===Rc)if(r=e.get("WEBGL_compressed_texture_astc"),r!==null){if(n===xc)return o===lt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:r.COMPRESSED_RGBA_ASTC_4x4_KHR;if(n===vc)return o===lt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:r.COMPRESSED_RGBA_ASTC_5x4_KHR;if(n===bc)return o===lt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:r.COMPRESSED_RGBA_ASTC_5x5_KHR;if(n===yc)return o===lt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:r.COMPRESSED_RGBA_ASTC_6x5_KHR;if(n===_c)return o===lt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:r.COMPRESSED_RGBA_ASTC_6x6_KHR;if(n===Mc)return o===lt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:r.COMPRESSED_RGBA_ASTC_8x5_KHR;if(n===wc)return o===lt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:r.COMPRESSED_RGBA_ASTC_8x6_KHR;if(n===Sc)return o===lt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:r.COMPRESSED_RGBA_ASTC_8x8_KHR;if(n===Ec)return o===lt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:r.COMPRESSED_RGBA_ASTC_10x5_KHR;if(n===Tc)return o===lt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:r.COMPRESSED_RGBA_ASTC_10x6_KHR;if(n===Cc)return o===lt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:r.COMPRESSED_RGBA_ASTC_10x8_KHR;if(n===Ac)return o===lt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:r.COMPRESSED_RGBA_ASTC_10x10_KHR;if(n===Pc)return o===lt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:r.COMPRESSED_RGBA_ASTC_12x10_KHR;if(n===Rc)return o===lt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:r.COMPRESSED_RGBA_ASTC_12x12_KHR}else return null;if(n===Lc||n===Ic||n===Dc)if(r=e.get("EXT_texture_compression_bptc"),r!==null){if(n===Lc)return o===lt?r.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT:r.COMPRESSED_RGBA_BPTC_UNORM_EXT;if(n===Ic)return r.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT;if(n===Dc)return r.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT}else return null;if(n===Bc||n===Nc||n===kc||n===Uc)if(r=e.get("EXT_texture_compression_rgtc"),r!==null){if(n===Bc)return r.COMPRESSED_RED_RGTC1_EXT;if(n===Nc)return r.COMPRESSED_SIGNED_RED_RGTC1_EXT;if(n===kc)return r.COMPRESSED_RED_GREEN_RGTC2_EXT;if(n===Uc)return r.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT}else return null;return n===Vs?s.UNSIGNED_INT_24_8:s[n]!==void 0?s[n]:null}return{convert:t}}const $_=` void main() { gl_Position = vec4( position, 1.0 ); }`,K_=` 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 J_{constructor(){this.texture=null,this.mesh=null,this.depthNear=0,this.depthFar=0}init(e,t){if(this.texture===null){const n=new Pf(e.texture);(e.depthNear!==t.depthNear||e.depthFar!==t.depthFar)&&(this.depthNear=e.depthNear,this.depthFar=e.depthFar),this.texture=n}}getMesh(e){if(this.texture!==null&&this.mesh===null){const t=e.cameras[0].viewport,n=new Jt({vertexShader:$_,fragmentShader:K_,uniforms:{depthColor:{value:this.texture},depthWidth:{value:t.z},depthHeight:{value:t.w}}});this.mesh=new ht(new xo(20,20),n)}return this.mesh}reset(){this.texture=null,this.mesh=null}getDepthTexture(){return this.texture}}class Q_ extends os{constructor(e,t){super();const n=this;let i=null,r=1,o=null,a="local-floor",l=1,c=null,h=null,u=null,f=null,d=null,m=null;const p=typeof XRWebGLBinding<"u",x=new J_,g={},b=t.getContextAttributes();let v=null,y=null;const M=[],E=[],C=new ue;let P=null;const _=new on;_.viewport=new tt;const S=new on;S.viewport=new tt;const I=[_,S],A=new Fv;let B=null,w=null;this.cameraAutoUpdate=!0,this.enabled=!1,this.isPresenting=!1,this.getController=function(se){let ce=M[se];return ce===void 0&&(ce=new hh,M[se]=ce),ce.getTargetRaySpace()},this.getControllerGrip=function(se){let ce=M[se];return ce===void 0&&(ce=new hh,M[se]=ce),ce.getGripSpace()},this.getHand=function(se){let ce=M[se];return ce===void 0&&(ce=new hh,M[se]=ce),ce.getHandSpace()};function F(se){const ce=E.indexOf(se.inputSource);if(ce===-1)return;const fe=M[ce];fe!==void 0&&(fe.update(se.inputSource,se.frame,c||o),fe.dispatchEvent({type:se.type,data:se.inputSource}))}function W(){i.removeEventListener("select",F),i.removeEventListener("selectstart",F),i.removeEventListener("selectend",F),i.removeEventListener("squeeze",F),i.removeEventListener("squeezestart",F),i.removeEventListener("squeezeend",F),i.removeEventListener("end",W),i.removeEventListener("inputsourceschange",X);for(let se=0;se=0&&(E[be]=null,M[be].disconnect(fe))}for(let ce=0;ce=E.length){E.push(fe),be=Ne;break}else if(E[Ne]===null){E[Ne]=fe,be=Ne;break}if(be===-1)break}const Se=M[be];Se&&Se.connect(fe)}}const $=new R,Z=new R;function ie(se,ce,fe){$.setFromMatrixPosition(ce.matrixWorld),Z.setFromMatrixPosition(fe.matrixWorld);const be=$.distanceTo(Z),Se=ce.projectionMatrix.elements,Ne=fe.projectionMatrix.elements,Je=Se[14]/(Se[10]-1),ke=Se[14]/(Se[10]+1),T=(Se[9]+1)/Se[5],D=(Se[9]-1)/Se[5],V=(Se[8]-1)/Se[0],U=(Ne[8]+1)/Ne[0],k=Je*V,z=Je*U,ee=be/(-V+U),J=ee*-V;if(ce.matrixWorld.decompose(se.position,se.quaternion,se.scale),se.translateX(J),se.translateZ(ee),se.matrixWorld.compose(se.position,se.quaternion,se.scale),se.matrixWorldInverse.copy(se.matrixWorld).invert(),Se[10]===-1)se.projectionMatrix.copy(ce.projectionMatrix),se.projectionMatrixInverse.copy(ce.projectionMatrixInverse);else{const G=Je+ee,N=ke+ee,L=k-J,H=z+(be-J),K=T*ke/N*G,le=D*ke/N*G;se.projectionMatrix.makePerspective(L,H,K,le,G,N),se.projectionMatrixInverse.copy(se.projectionMatrix).invert()}}function j(se,ce){ce===null?se.matrixWorld.copy(se.matrix):se.matrixWorld.multiplyMatrices(ce.matrixWorld,se.matrix),se.matrixWorldInverse.copy(se.matrixWorld).invert()}this.updateCamera=function(se){if(i===null)return;let ce=se.near,fe=se.far;x.texture!==null&&(x.depthNear>0&&(ce=x.depthNear),x.depthFar>0&&(fe=x.depthFar)),A.near=S.near=_.near=ce,A.far=S.far=_.far=fe,(B!==A.near||w!==A.far)&&(i.updateRenderState({depthNear:A.near,depthFar:A.far}),B=A.near,w=A.far),A.layers.mask=se.layers.mask|6,_.layers.mask=A.layers.mask&3,S.layers.mask=A.layers.mask&5;const be=se.parent,Se=A.cameras;j(A,be);for(let Ne=0;Ne0&&(x.alphaTest.value=g.alphaTest);const b=e.get(g),v=b.envMap,y=b.envMapRotation;v&&(x.envMap.value=v,vs.copy(y),vs.x*=-1,vs.y*=-1,vs.z*=-1,v.isCubeTexture&&v.isRenderTargetTexture===!1&&(vs.y*=-1,vs.z*=-1),x.envMapRotation.value.setFromMatrix4(e2.makeRotationFromEuler(vs)),x.flipEnvMap.value=v.isCubeTexture&&v.isRenderTargetTexture===!1?-1:1,x.reflectivity.value=g.reflectivity,x.ior.value=g.ior,x.refractionRatio.value=g.refractionRatio),g.lightMap&&(x.lightMap.value=g.lightMap,x.lightMapIntensity.value=g.lightMapIntensity,t(g.lightMap,x.lightMapTransform)),g.aoMap&&(x.aoMap.value=g.aoMap,x.aoMapIntensity.value=g.aoMapIntensity,t(g.aoMap,x.aoMapTransform))}function o(x,g){x.diffuse.value.copy(g.color),x.opacity.value=g.opacity,g.map&&(x.map.value=g.map,t(g.map,x.mapTransform))}function a(x,g){x.dashSize.value=g.dashSize,x.totalSize.value=g.dashSize+g.gapSize,x.scale.value=g.scale}function l(x,g,b,v){x.diffuse.value.copy(g.color),x.opacity.value=g.opacity,x.size.value=g.size*b,x.scale.value=v*.5,g.map&&(x.map.value=g.map,t(g.map,x.uvTransform)),g.alphaMap&&(x.alphaMap.value=g.alphaMap,t(g.alphaMap,x.alphaMapTransform)),g.alphaTest>0&&(x.alphaTest.value=g.alphaTest)}function c(x,g){x.diffuse.value.copy(g.color),x.opacity.value=g.opacity,x.rotation.value=g.rotation,g.map&&(x.map.value=g.map,t(g.map,x.mapTransform)),g.alphaMap&&(x.alphaMap.value=g.alphaMap,t(g.alphaMap,x.alphaMapTransform)),g.alphaTest>0&&(x.alphaTest.value=g.alphaTest)}function h(x,g){x.specular.value.copy(g.specular),x.shininess.value=Math.max(g.shininess,1e-4)}function u(x,g){g.gradientMap&&(x.gradientMap.value=g.gradientMap)}function f(x,g){x.metalness.value=g.metalness,g.metalnessMap&&(x.metalnessMap.value=g.metalnessMap,t(g.metalnessMap,x.metalnessMapTransform)),x.roughness.value=g.roughness,g.roughnessMap&&(x.roughnessMap.value=g.roughnessMap,t(g.roughnessMap,x.roughnessMapTransform)),g.envMap&&(x.envMapIntensity.value=g.envMapIntensity)}function d(x,g,b){x.ior.value=g.ior,g.sheen>0&&(x.sheenColor.value.copy(g.sheenColor).multiplyScalar(g.sheen),x.sheenRoughness.value=g.sheenRoughness,g.sheenColorMap&&(x.sheenColorMap.value=g.sheenColorMap,t(g.sheenColorMap,x.sheenColorMapTransform)),g.sheenRoughnessMap&&(x.sheenRoughnessMap.value=g.sheenRoughnessMap,t(g.sheenRoughnessMap,x.sheenRoughnessMapTransform))),g.clearcoat>0&&(x.clearcoat.value=g.clearcoat,x.clearcoatRoughness.value=g.clearcoatRoughness,g.clearcoatMap&&(x.clearcoatMap.value=g.clearcoatMap,t(g.clearcoatMap,x.clearcoatMapTransform)),g.clearcoatRoughnessMap&&(x.clearcoatRoughnessMap.value=g.clearcoatRoughnessMap,t(g.clearcoatRoughnessMap,x.clearcoatRoughnessMapTransform)),g.clearcoatNormalMap&&(x.clearcoatNormalMap.value=g.clearcoatNormalMap,t(g.clearcoatNormalMap,x.clearcoatNormalMapTransform),x.clearcoatNormalScale.value.copy(g.clearcoatNormalScale),g.side===ln&&x.clearcoatNormalScale.value.negate())),g.dispersion>0&&(x.dispersion.value=g.dispersion),g.iridescence>0&&(x.iridescence.value=g.iridescence,x.iridescenceIOR.value=g.iridescenceIOR,x.iridescenceThicknessMinimum.value=g.iridescenceThicknessRange[0],x.iridescenceThicknessMaximum.value=g.iridescenceThicknessRange[1],g.iridescenceMap&&(x.iridescenceMap.value=g.iridescenceMap,t(g.iridescenceMap,x.iridescenceMapTransform)),g.iridescenceThicknessMap&&(x.iridescenceThicknessMap.value=g.iridescenceThicknessMap,t(g.iridescenceThicknessMap,x.iridescenceThicknessMapTransform))),g.transmission>0&&(x.transmission.value=g.transmission,x.transmissionSamplerMap.value=b.texture,x.transmissionSamplerSize.value.set(b.width,b.height),g.transmissionMap&&(x.transmissionMap.value=g.transmissionMap,t(g.transmissionMap,x.transmissionMapTransform)),x.thickness.value=g.thickness,g.thicknessMap&&(x.thicknessMap.value=g.thicknessMap,t(g.thicknessMap,x.thicknessMapTransform)),x.attenuationDistance.value=g.attenuationDistance,x.attenuationColor.value.copy(g.attenuationColor)),g.anisotropy>0&&(x.anisotropyVector.value.set(g.anisotropy*Math.cos(g.anisotropyRotation),g.anisotropy*Math.sin(g.anisotropyRotation)),g.anisotropyMap&&(x.anisotropyMap.value=g.anisotropyMap,t(g.anisotropyMap,x.anisotropyMapTransform))),x.specularIntensity.value=g.specularIntensity,x.specularColor.value.copy(g.specularColor),g.specularColorMap&&(x.specularColorMap.value=g.specularColorMap,t(g.specularColorMap,x.specularColorMapTransform)),g.specularIntensityMap&&(x.specularIntensityMap.value=g.specularIntensityMap,t(g.specularIntensityMap,x.specularIntensityMapTransform))}function m(x,g){g.matcap&&(x.matcap.value=g.matcap)}function p(x,g){const b=e.get(g).light;x.referencePosition.value.setFromMatrixPosition(b.matrixWorld),x.nearDistance.value=b.shadow.camera.near,x.farDistance.value=b.shadow.camera.far}return{refreshFogUniforms:n,refreshMaterialUniforms:i}}function n2(s,e,t,n){let i={},r={},o=[];const a=s.getParameter(s.MAX_UNIFORM_BUFFER_BINDINGS);function l(b,v){const y=v.program;n.uniformBlockBinding(b,y)}function c(b,v){let y=i[b.id];y===void 0&&(m(b),y=h(b),i[b.id]=y,b.addEventListener("dispose",x));const M=v.program;n.updateUBOMapping(b,M);const E=e.render.frame;r[b.id]!==E&&(f(b),r[b.id]=E)}function h(b){const v=u();b.__bindingPointIndex=v;const y=s.createBuffer(),M=b.__size,E=b.usage;return s.bindBuffer(s.UNIFORM_BUFFER,y),s.bufferData(s.UNIFORM_BUFFER,M,E),s.bindBuffer(s.UNIFORM_BUFFER,null),s.bindBufferBase(s.UNIFORM_BUFFER,v,y),y}function u(){for(let b=0;b0&&(y+=M-E),b.__size=y,b.__cache={},this}function p(b){const v={boundary:0,storage:0};return typeof b=="number"||typeof b=="boolean"?(v.boundary=4,v.storage=4):b.isVector2?(v.boundary=8,v.storage=8):b.isVector3||b.isColor?(v.boundary=16,v.storage=12):b.isVector4?(v.boundary=16,v.storage=16):b.isMatrix3?(v.boundary=48,v.storage=48):b.isMatrix4?(v.boundary=64,v.storage=64):b.isTexture?ze("WebGLRenderer: Texture samplers can not be part of an uniforms group."):ze("WebGLRenderer: Unsupported uniform value type.",b),v}function x(b){const v=b.target;v.removeEventListener("dispose",x);const y=o.indexOf(v.__bindingPointIndex);o.splice(y,1),s.deleteBuffer(i[v.id]),delete i[v.id],delete r[v.id]}function g(){for(const b in i)s.deleteBuffer(i[b]);o=[],i={},r={}}return{bind:l,update:c,dispose:g}}const i2=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 Ci=null;function s2(){return Ci===null&&(Ci=new ro(i2,32,32,ac,xi),Ci.minFilter=Kt,Ci.magFilter=Kt,Ci.wrapS=ii,Ci.wrapT=ii,Ci.generateMipmaps=!1,Ci.needsUpdate=!0),Ci}class Rp{constructor(e={}){const{canvas:t=F0(),context:n=null,depth:i=!0,stencil:r=!1,alpha:o=!1,antialias:a=!1,premultipliedAlpha:l=!0,preserveDrawingBuffer:c=!1,powerPreference:h="default",failIfMajorPerformanceCaveat:u=!1,reversedDepthBuffer:f=!1}=e;this.isWebGLRenderer=!0;let d;if(n!==null){if(typeof WebGLRenderingContext<"u"&&n instanceof WebGLRenderingContext)throw new Error("THREE.WebGLRenderer: WebGL 1 is not supported since r163.");d=n.getContextAttributes().alpha}else d=o;const m=new Set([cc,lc,oc]),p=new Set([Wn,rs,Wr,Vs,ic,sc]),x=new Uint32Array(4),g=new Int32Array(4);let b=null,v=null;const y=[],M=[];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=ki,this.toneMappingExposure=1,this.transmissionResolutionScale=1;const E=this;let C=!1;this._outputColorSpace=At;let P=0,_=0,S=null,I=-1,A=null;const B=new tt,w=new tt;let F=null;const W=new He(0);let X=0,$=t.width,Z=t.height,ie=1,j=null,Y=null;const ge=new tt(0,0,$,Z),pe=new tt(0,0,$,Z);let de=!1;const se=new xh;let ce=!1,fe=!1;const be=new De,Se=new R,Ne=new tt,Je={background:null,fog:null,environment:null,overrideMaterial:null,isScene:!0};let ke=!1;function T(){return S===null?ie:1}let D=n;function V(O,Q){return t.getContext(O,Q)}try{const O={alpha:!0,depth:i,stencil:r,antialias:a,premultipliedAlpha:l,preserveDrawingBuffer:c,powerPreference:h,failIfMajorPerformanceCaveat:u};if("setAttribute"in t&&t.setAttribute("data-engine",`three.js r${Hr}`),t.addEventListener("webglcontextlost",ve,!1),t.addEventListener("webglcontextrestored",me,!1),t.addEventListener("webglcontextcreationerror",Oe,!1),D===null){const Q="webgl2";if(D=V(Q,O),D===null)throw V(Q)?new Error("Error creating WebGL context with your selected attributes."):new Error("Error creating WebGL context.")}}catch(O){throw O("WebGLRenderer: "+O.message),O}let U,k,z,ee,J,G,N,L,H,K,le,te,Ce,ye,Re,Ie,he,_e,Ve,Ue,Ae,Ge,q,Te;function Me(){U=new fy(D),U.init(),Ge=new Y_(D,U),k=new sy(D,U,e,Ge),z=new q_(D,U),k.reversedDepthBuffer&&f&&z.buffers.depth.setReversed(!0),ee=new gy(D),J=new B_,G=new Z_(D,U,z,J,k,Ge,ee),N=new oy(E),L=new dy(E),H=new e1(D),q=new ny(D,H),K=new py(D,H,ee,q),le=new vy(D,K,H,ee),Ve=new xy(D,k,G),Ie=new ry(J),te=new D_(E,N,L,U,k,q,Ie),Ce=new t2(E,J),ye=new k_,Re=new V_(U),_e=new ty(E,N,L,z,le,d,l),he=new X_(E,le,k),Te=new n2(D,ee,k,z),Ue=new iy(D,U,ee),Ae=new my(D,U,ee),ee.programs=te.programs,E.capabilities=k,E.extensions=U,E.properties=J,E.renderLists=ye,E.shadowMap=he,E.state=z,E.info=ee}Me();const we=new Q_(E,D);this.xr=we,this.getContext=function(){return D},this.getContextAttributes=function(){return D.getContextAttributes()},this.forceContextLoss=function(){const O=U.get("WEBGL_lose_context");O&&O.loseContext()},this.forceContextRestore=function(){const O=U.get("WEBGL_lose_context");O&&O.restoreContext()},this.getPixelRatio=function(){return ie},this.setPixelRatio=function(O){O!==void 0&&(ie=O,this.setSize($,Z,!1))},this.getSize=function(O){return O.set($,Z)},this.setSize=function(O,Q,oe=!0){if(we.isPresenting){ze("WebGLRenderer: Can't change size while VR device is presenting.");return}$=O,Z=Q,t.width=Math.floor(O*ie),t.height=Math.floor(Q*ie),oe===!0&&(t.style.width=O+"px",t.style.height=Q+"px"),this.setViewport(0,0,O,Q)},this.getDrawingBufferSize=function(O){return O.set($*ie,Z*ie).floor()},this.setDrawingBufferSize=function(O,Q,oe){$=O,Z=Q,ie=oe,t.width=Math.floor(O*oe),t.height=Math.floor(Q*oe),this.setViewport(0,0,O,Q)},this.getCurrentViewport=function(O){return O.copy(B)},this.getViewport=function(O){return O.copy(ge)},this.setViewport=function(O,Q,oe,ae){O.isVector4?ge.set(O.x,O.y,O.z,O.w):ge.set(O,Q,oe,ae),z.viewport(B.copy(ge).multiplyScalar(ie).round())},this.getScissor=function(O){return O.copy(pe)},this.setScissor=function(O,Q,oe,ae){O.isVector4?pe.set(O.x,O.y,O.z,O.w):pe.set(O,Q,oe,ae),z.scissor(w.copy(pe).multiplyScalar(ie).round())},this.getScissorTest=function(){return de},this.setScissorTest=function(O){z.setScissorTest(de=O)},this.setOpaqueSort=function(O){j=O},this.setTransparentSort=function(O){Y=O},this.getClearColor=function(O){return O.copy(_e.getClearColor())},this.setClearColor=function(){_e.setClearColor(...arguments)},this.getClearAlpha=function(){return _e.getClearAlpha()},this.setClearAlpha=function(){_e.setClearAlpha(...arguments)},this.clear=function(O=!0,Q=!0,oe=!0){let ae=0;if(O){let ne=!1;if(S!==null){const Ee=S.texture.format;ne=m.has(Ee)}if(ne){const Ee=S.texture.type,Le=p.has(Ee),Fe=_e.getClearColor(),Be=_e.getClearAlpha(),je=Fe.r,Ze=Fe.g,We=Fe.b;Le?(x[0]=je,x[1]=Ze,x[2]=We,x[3]=Be,D.clearBufferuiv(D.COLOR,0,x)):(g[0]=je,g[1]=Ze,g[2]=We,g[3]=Be,D.clearBufferiv(D.COLOR,0,g))}else ae|=D.COLOR_BUFFER_BIT}Q&&(ae|=D.DEPTH_BUFFER_BIT),oe&&(ae|=D.STENCIL_BUFFER_BIT,this.state.buffers.stencil.setMask(4294967295)),D.clear(ae)},this.clearColor=function(){this.clear(!0,!1,!1)},this.clearDepth=function(){this.clear(!1,!0,!1)},this.clearStencil=function(){this.clear(!1,!1,!0)},this.dispose=function(){t.removeEventListener("webglcontextlost",ve,!1),t.removeEventListener("webglcontextrestored",me,!1),t.removeEventListener("webglcontextcreationerror",Oe,!1),_e.dispose(),ye.dispose(),Re.dispose(),J.dispose(),N.dispose(),L.dispose(),le.dispose(),q.dispose(),Te.dispose(),te.dispose(),we.dispose(),we.removeEventListener("sessionstart",Xg),we.removeEventListener("sessionend",jg),Ds.stop()};function ve(O){O.preventDefault(),Qo("WebGLRenderer: Context Lost."),C=!0}function me(){Qo("WebGLRenderer: Context Restored."),C=!1;const O=ee.autoReset,Q=he.enabled,oe=he.autoUpdate,ae=he.needsUpdate,ne=he.type;Me(),ee.autoReset=O,he.enabled=Q,he.autoUpdate=oe,he.needsUpdate=ae,he.type=ne}function Oe(O){Qe("WebGLRenderer: A WebGL context could not be created. Reason: ",O.statusMessage)}function Ye(O){const Q=O.target;Q.removeEventListener("dispose",Ye),Mt(Q)}function Mt(O){ft(O),J.remove(O)}function ft(O){const Q=J.get(O).programs;Q!==void 0&&(Q.forEach(function(oe){te.releaseProgram(oe)}),O.isShaderMaterial&&te.releaseShaderCache(O))}this.renderBufferDirect=function(O,Q,oe,ae,ne,Ee){Q===null&&(Q=Je);const Le=ne.isMesh&&ne.matrixWorld.determinant()<0,Fe=NT(O,Q,oe,ae,ne);z.setMaterial(ae,Le);let Be=oe.index,je=1;if(ae.wireframe===!0){if(Be=K.getWireframeAttribute(oe),Be===void 0)return;je=2}const Ze=oe.drawRange,We=oe.attributes.position;let st=Ze.start*je,pt=(Ze.start+Ze.count)*je;Ee!==null&&(st=Math.max(st,Ee.start*je),pt=Math.min(pt,(Ee.start+Ee.count)*je)),Be!==null?(st=Math.max(st,0),pt=Math.min(pt,Be.count)):We!=null&&(st=Math.max(st,0),pt=Math.min(pt,We.count));const It=pt-st;if(It<0||It===1/0)return;q.setup(ne,ae,Fe,oe,Be);let Dt,mt=Ue;if(Be!==null&&(Dt=H.get(Be),mt=Ae,mt.setIndex(Dt)),ne.isMesh)ae.wireframe===!0?(z.setLineWidth(ae.wireframeLinewidth*T()),mt.setMode(D.LINES)):mt.setMode(D.TRIANGLES);else if(ne.isLine){let Xe=ae.linewidth;Xe===void 0&&(Xe=1),z.setLineWidth(Xe*T()),ne.isLineSegments?mt.setMode(D.LINES):ne.isLineLoop?mt.setMode(D.LINE_LOOP):mt.setMode(D.LINE_STRIP)}else ne.isPoints?mt.setMode(D.POINTS):ne.isSprite&&mt.setMode(D.TRIANGLES);if(ne.isBatchedMesh)if(ne._multiDrawInstances!==null)Yr("WebGLRenderer: renderMultiDrawInstances has been deprecated and will be removed in r184. Append to renderMultiDraw arguments and use indirection."),mt.renderMultiDrawInstances(ne._multiDrawStarts,ne._multiDrawCounts,ne._multiDrawCount,ne._multiDrawInstances);else if(U.get("WEBGL_multi_draw"))mt.renderMultiDraw(ne._multiDrawStarts,ne._multiDrawCounts,ne._multiDrawCount);else{const Xe=ne._multiDrawStarts,Tt=ne._multiDrawCounts,at=ne._multiDrawCount,Cn=Be?H.get(Be).bytesPerElement:1,Fr=J.get(ae).currentProgram.getUniforms();for(let An=0;An{function Ee(){if(ae.forEach(function(Le){J.get(Le).currentProgram.isReady()&&ae.delete(Le)}),ae.size===0){ne(O);return}setTimeout(Ee,10)}U.get("KHR_parallel_shader_compile")!==null?Ee():setTimeout(Ee,10)})};let ti=null;function BT(O){ti&&ti(O)}function Xg(){Ds.stop()}function jg(){Ds.start()}const Ds=new np;Ds.setAnimationLoop(BT),typeof self<"u"&&Ds.setContext(self),this.setAnimationLoop=function(O){ti=O,we.setAnimationLoop(O),O===null?Ds.stop():Ds.start()},we.addEventListener("sessionstart",Xg),we.addEventListener("sessionend",jg),this.render=function(O,Q){if(Q!==void 0&&Q.isCamera!==!0){Qe("WebGLRenderer.render: camera is not an instance of THREE.Camera.");return}if(C===!0)return;if(O.matrixWorldAutoUpdate===!0&&O.updateMatrixWorld(),Q.parent===null&&Q.matrixWorldAutoUpdate===!0&&Q.updateMatrixWorld(),we.enabled===!0&&we.isPresenting===!0&&(we.cameraAutoUpdate===!0&&we.updateCamera(Q),Q=we.getCamera()),O.isScene===!0&&O.onBeforeRender(E,O,Q,S),v=Re.get(O,M.length),v.init(Q),M.push(v),be.multiplyMatrices(Q.projectionMatrix,Q.matrixWorldInverse),se.setFromProjectionMatrix(be,si,Q.reversedDepth),fe=this.localClippingEnabled,ce=Ie.init(this.clippingPlanes,fe),b=ye.get(O,y.length),b.init(),y.push(b),we.enabled===!0&&we.isPresenting===!0){const Ee=E.xr.getDepthSensingMesh();Ee!==null&&nd(Ee,Q,-1/0,E.sortObjects)}nd(O,Q,0,E.sortObjects),b.finish(),E.sortObjects===!0&&b.sort(j,Y),ke=we.enabled===!1||we.isPresenting===!1||we.hasDepthSensing()===!1,ke&&_e.addToRenderList(b,O),this.info.render.frame++,ce===!0&&Ie.beginShadows();const oe=v.state.shadowsArray;he.render(oe,O,Q),ce===!0&&Ie.endShadows(),this.info.autoReset===!0&&this.info.reset();const ae=b.opaque,ne=b.transmissive;if(v.setupLights(),Q.isArrayCamera){const Ee=Q.cameras;if(ne.length>0)for(let Le=0,Fe=Ee.length;Le0&&Zg(ae,ne,O,Q),ke&&_e.render(O),qg(b,O,Q);S!==null&&_===0&&(G.updateMultisampleRenderTarget(S),G.updateRenderTargetMipmap(S)),O.isScene===!0&&O.onAfterRender(E,O,Q),q.resetDefaultState(),I=-1,A=null,M.pop(),M.length>0?(v=M[M.length-1],ce===!0&&Ie.setGlobalState(E.clippingPlanes,v.state.camera)):v=null,y.pop(),y.length>0?b=y[y.length-1]:b=null};function nd(O,Q,oe,ae){if(O.visible===!1)return;if(O.layers.test(Q.layers)){if(O.isGroup)oe=O.renderOrder;else if(O.isLOD)O.autoUpdate===!0&&O.update(Q);else if(O.isLight)v.pushLight(O),O.castShadow&&v.pushShadow(O);else if(O.isSprite){if(!O.frustumCulled||se.intersectsSprite(O)){ae&&Ne.setFromMatrixPosition(O.matrixWorld).applyMatrix4(be);const Le=le.update(O),Fe=O.material;Fe.visible&&b.push(O,Le,Fe,oe,Ne.z,null)}}else if((O.isMesh||O.isLine||O.isPoints)&&(!O.frustumCulled||se.intersectsObject(O))){const Le=le.update(O),Fe=O.material;if(ae&&(O.boundingSphere!==void 0?(O.boundingSphere===null&&O.computeBoundingSphere(),Ne.copy(O.boundingSphere.center)):(Le.boundingSphere===null&&Le.computeBoundingSphere(),Ne.copy(Le.boundingSphere.center)),Ne.applyMatrix4(O.matrixWorld).applyMatrix4(be)),Array.isArray(Fe)){const Be=Le.groups;for(let je=0,Ze=Be.length;je0&&Ol(ne,Q,oe),Ee.length>0&&Ol(Ee,Q,oe),Le.length>0&&Ol(Le,Q,oe),z.buffers.depth.setTest(!0),z.buffers.depth.setMask(!0),z.buffers.color.setMask(!0),z.setPolygonOffset(!1)}function Zg(O,Q,oe,ae){if((oe.isScene===!0?oe.overrideMaterial:null)!==null)return;v.state.transmissionRenderTarget[ae.id]===void 0&&(v.state.transmissionRenderTarget[ae.id]=new qn(1,1,{generateMipmaps:!0,type:U.has("EXT_color_buffer_half_float")||U.has("EXT_color_buffer_float")?xi:Wn,minFilter:gi,samples:4,stencilBuffer:r,resolveDepthBuffer:!1,resolveStencilBuffer:!1,colorSpace:it.workingColorSpace}));const Ee=v.state.transmissionRenderTarget[ae.id],Le=ae.viewport||B;Ee.setSize(Le.z*E.transmissionResolutionScale,Le.w*E.transmissionResolutionScale);const Fe=E.getRenderTarget(),Be=E.getActiveCubeFace(),je=E.getActiveMipmapLevel();E.setRenderTarget(Ee),E.getClearColor(W),X=E.getClearAlpha(),X<1&&E.setClearColor(16777215,.5),E.clear(),ke&&_e.render(oe);const Ze=E.toneMapping;E.toneMapping=ki;const We=ae.viewport;if(ae.viewport!==void 0&&(ae.viewport=void 0),v.setupLightsView(ae),ce===!0&&Ie.setGlobalState(E.clippingPlanes,ae),Ol(O,oe,ae),G.updateMultisampleRenderTarget(Ee),G.updateRenderTargetMipmap(Ee),U.has("WEBGL_multisampled_render_to_texture")===!1){let st=!1;for(let pt=0,It=Q.length;pt0),We=!!oe.morphAttributes.position,st=!!oe.morphAttributes.normal,pt=!!oe.morphAttributes.color;let It=ki;ae.toneMapped&&(S===null||S.isXRRenderTarget===!0)&&(It=E.toneMapping);const Dt=oe.morphAttributes.position||oe.morphAttributes.normal||oe.morphAttributes.color,mt=Dt!==void 0?Dt.length:0,Xe=J.get(ae),Tt=v.state.lights;if(ce===!0&&(fe===!0||O!==A)){const pn=O===A&&ae.id===I;Ie.setState(ae,O,pn)}let at=!1;ae.version===Xe.__version?(Xe.needsLights&&Xe.lightsStateVersion!==Tt.state.version||Xe.outputColorSpace!==Fe||ne.isBatchedMesh&&Xe.batching===!1||!ne.isBatchedMesh&&Xe.batching===!0||ne.isBatchedMesh&&Xe.batchingColor===!0&&ne.colorTexture===null||ne.isBatchedMesh&&Xe.batchingColor===!1&&ne.colorTexture!==null||ne.isInstancedMesh&&Xe.instancing===!1||!ne.isInstancedMesh&&Xe.instancing===!0||ne.isSkinnedMesh&&Xe.skinning===!1||!ne.isSkinnedMesh&&Xe.skinning===!0||ne.isInstancedMesh&&Xe.instancingColor===!0&&ne.instanceColor===null||ne.isInstancedMesh&&Xe.instancingColor===!1&&ne.instanceColor!==null||ne.isInstancedMesh&&Xe.instancingMorph===!0&&ne.morphTexture===null||ne.isInstancedMesh&&Xe.instancingMorph===!1&&ne.morphTexture!==null||Xe.envMap!==Be||ae.fog===!0&&Xe.fog!==Ee||Xe.numClippingPlanes!==void 0&&(Xe.numClippingPlanes!==Ie.numPlanes||Xe.numIntersection!==Ie.numIntersection)||Xe.vertexAlphas!==je||Xe.vertexTangents!==Ze||Xe.morphTargets!==We||Xe.morphNormals!==st||Xe.morphColors!==pt||Xe.toneMapping!==It||Xe.morphTargetsCount!==mt)&&(at=!0):(at=!0,Xe.__version=ae.version);let Cn=Xe.currentProgram;at===!0&&(Cn=Fl(ae,Q,ne));let Fr=!1,An=!1,Vo=!1;const Ct=Cn.getUniforms(),yn=Xe.uniforms;if(z.useProgram(Cn.program)&&(Fr=!0,An=!0,Vo=!0),ae.id!==I&&(I=ae.id,An=!0),Fr||A!==O){z.buffers.depth.getReversed()&&O.reversedDepth!==!0&&(O._reversedDepth=!0,O.updateProjectionMatrix()),Ct.setValue(D,"projectionMatrix",O.projectionMatrix),Ct.setValue(D,"viewMatrix",O.matrixWorldInverse);const _n=Ct.map.cameraPosition;_n!==void 0&&_n.setValue(D,Se.setFromMatrixPosition(O.matrixWorld)),k.logarithmicDepthBuffer&&Ct.setValue(D,"logDepthBufFC",2/(Math.log(O.far+1)/Math.LN2)),(ae.isMeshPhongMaterial||ae.isMeshToonMaterial||ae.isMeshLambertMaterial||ae.isMeshBasicMaterial||ae.isMeshStandardMaterial||ae.isShaderMaterial)&&Ct.setValue(D,"isOrthographic",O.isOrthographicCamera===!0),A!==O&&(A=O,An=!0,Vo=!0)}if(ne.isSkinnedMesh){Ct.setOptional(D,ne,"bindMatrix"),Ct.setOptional(D,ne,"bindMatrixInverse");const pn=ne.skeleton;pn&&(pn.boneTexture===null&&pn.computeBoneTexture(),Ct.setValue(D,"boneTexture",pn.boneTexture,G))}ne.isBatchedMesh&&(Ct.setOptional(D,ne,"batchingTexture"),Ct.setValue(D,"batchingTexture",ne._matricesTexture,G),Ct.setOptional(D,ne,"batchingIdTexture"),Ct.setValue(D,"batchingIdTexture",ne._indirectTexture,G),Ct.setOptional(D,ne,"batchingColorTexture"),ne._colorsTexture!==null&&Ct.setValue(D,"batchingColorTexture",ne._colorsTexture,G));const Vn=oe.morphAttributes;if((Vn.position!==void 0||Vn.normal!==void 0||Vn.color!==void 0)&&Ve.update(ne,oe,Cn),(An||Xe.receiveShadow!==ne.receiveShadow)&&(Xe.receiveShadow=ne.receiveShadow,Ct.setValue(D,"receiveShadow",ne.receiveShadow)),ae.isMeshGouraudMaterial&&ae.envMap!==null&&(yn.envMap.value=Be,yn.flipEnvMap.value=Be.isCubeTexture&&Be.isRenderTargetTexture===!1?-1:1),ae.isMeshStandardMaterial&&ae.envMap===null&&Q.environment!==null&&(yn.envMapIntensity.value=Q.environmentIntensity),yn.dfgLUT!==void 0&&(yn.dfgLUT.value=s2()),An&&(Ct.setValue(D,"toneMappingExposure",E.toneMappingExposure),Xe.needsLights&&kT(yn,Vo),Ee&&ae.fog===!0&&Ce.refreshFogUniforms(yn,Ee),Ce.refreshMaterialUniforms(yn,ae,ie,Z,v.state.transmissionRenderTarget[O.id]),za.upload(D,$g(Xe),yn,G)),ae.isShaderMaterial&&ae.uniformsNeedUpdate===!0&&(za.upload(D,$g(Xe),yn,G),ae.uniformsNeedUpdate=!1),ae.isSpriteMaterial&&Ct.setValue(D,"center",ne.center),Ct.setValue(D,"modelViewMatrix",ne.modelViewMatrix),Ct.setValue(D,"normalMatrix",ne.normalMatrix),Ct.setValue(D,"modelMatrix",ne.matrixWorld),ae.isShaderMaterial||ae.isRawShaderMaterial){const pn=ae.uniformsGroups;for(let _n=0,id=pn.length;_n0&&G.useMultisampledRTT(O)===!1?ne=J.get(O).__webglMultisampledFramebuffer:Array.isArray(Ze)?ne=Ze[oe]:ne=Ze,B.copy(O.viewport),w.copy(O.scissor),F=O.scissorTest}else B.copy(ge).multiplyScalar(ie).floor(),w.copy(pe).multiplyScalar(ie).floor(),F=de;if(oe!==0&&(ne=OT),z.bindFramebuffer(D.FRAMEBUFFER,ne)&&ae&&z.drawBuffers(O,ne),z.viewport(B),z.scissor(w),z.setScissorTest(F),Ee){const Be=J.get(O.texture);D.framebufferTexture2D(D.FRAMEBUFFER,D.COLOR_ATTACHMENT0,D.TEXTURE_CUBE_MAP_POSITIVE_X+Q,Be.__webglTexture,oe)}else if(Le){const Be=Q;for(let je=0;je=0&&Q<=O.width-ae&&oe>=0&&oe<=O.height-ne&&(O.textures.length>1&&D.readBuffer(D.COLOR_ATTACHMENT0+Fe),D.readPixels(Q,oe,ae,ne,Ge.convert(Ze),Ge.convert(We),Ee))}finally{const je=S!==null?J.get(S).__webglFramebuffer:null;z.bindFramebuffer(D.FRAMEBUFFER,je)}}},this.readRenderTargetPixelsAsync=async function(O,Q,oe,ae,ne,Ee,Le,Fe=0){if(!(O&&O.isWebGLRenderTarget))throw new Error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");let Be=J.get(O).__webglFramebuffer;if(O.isWebGLCubeRenderTarget&&Le!==void 0&&(Be=Be[Le]),Be)if(Q>=0&&Q<=O.width-ae&&oe>=0&&oe<=O.height-ne){z.bindFramebuffer(D.FRAMEBUFFER,Be);const je=O.textures[Fe],Ze=je.format,We=je.type;if(!k.textureFormatReadable(Ze))throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in RGBA or implementation defined format.");if(!k.textureTypeReadable(We))throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in UnsignedByteType or implementation defined type.");const st=D.createBuffer();D.bindBuffer(D.PIXEL_PACK_BUFFER,st),D.bufferData(D.PIXEL_PACK_BUFFER,Ee.byteLength,D.STREAM_READ),O.textures.length>1&&D.readBuffer(D.COLOR_ATTACHMENT0+Fe),D.readPixels(Q,oe,ae,ne,Ge.convert(Ze),Ge.convert(We),0);const pt=S!==null?J.get(S).__webglFramebuffer:null;z.bindFramebuffer(D.FRAMEBUFFER,pt);const It=D.fenceSync(D.SYNC_GPU_COMMANDS_COMPLETE,0);return D.flush(),await z0(D,It,4),D.bindBuffer(D.PIXEL_PACK_BUFFER,st),D.getBufferSubData(D.PIXEL_PACK_BUFFER,0,Ee),D.deleteBuffer(st),D.deleteSync(It),Ee}else throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: requested read bounds are out of range.")},this.copyFramebufferToTexture=function(O,Q=null,oe=0){const ae=Math.pow(2,-oe),ne=Math.floor(O.image.width*ae),Ee=Math.floor(O.image.height*ae),Le=Q!==null?Q.x:0,Fe=Q!==null?Q.y:0;G.setTexture2D(O,0),D.copyTexSubImage2D(D.TEXTURE_2D,oe,0,0,Le,Fe,ne,Ee),z.unbindTexture()};const FT=D.createFramebuffer(),zT=D.createFramebuffer();this.copyTextureToTexture=function(O,Q,oe=null,ae=null,ne=0,Ee=null){Ee===null&&(ne!==0?(Yr("WebGLRenderer: copyTextureToTexture function signature has changed to support src and dst mipmap levels."),Ee=ne,ne=0):Ee=0);let Le,Fe,Be,je,Ze,We,st,pt,It;const Dt=O.isCompressedTexture?O.mipmaps[Ee]:O.image;if(oe!==null)Le=oe.max.x-oe.min.x,Fe=oe.max.y-oe.min.y,Be=oe.isBox3?oe.max.z-oe.min.z:1,je=oe.min.x,Ze=oe.min.y,We=oe.isBox3?oe.min.z:0;else{const Vn=Math.pow(2,-ne);Le=Math.floor(Dt.width*Vn),Fe=Math.floor(Dt.height*Vn),O.isDataArrayTexture?Be=Dt.depth:O.isData3DTexture?Be=Math.floor(Dt.depth*Vn):Be=1,je=0,Ze=0,We=0}ae!==null?(st=ae.x,pt=ae.y,It=ae.z):(st=0,pt=0,It=0);const mt=Ge.convert(Q.format),Xe=Ge.convert(Q.type);let Tt;Q.isData3DTexture?(G.setTexture3D(Q,0),Tt=D.TEXTURE_3D):Q.isDataArrayTexture||Q.isCompressedArrayTexture?(G.setTexture2DArray(Q,0),Tt=D.TEXTURE_2D_ARRAY):(G.setTexture2D(Q,0),Tt=D.TEXTURE_2D),D.pixelStorei(D.UNPACK_FLIP_Y_WEBGL,Q.flipY),D.pixelStorei(D.UNPACK_PREMULTIPLY_ALPHA_WEBGL,Q.premultiplyAlpha),D.pixelStorei(D.UNPACK_ALIGNMENT,Q.unpackAlignment);const at=D.getParameter(D.UNPACK_ROW_LENGTH),Cn=D.getParameter(D.UNPACK_IMAGE_HEIGHT),Fr=D.getParameter(D.UNPACK_SKIP_PIXELS),An=D.getParameter(D.UNPACK_SKIP_ROWS),Vo=D.getParameter(D.UNPACK_SKIP_IMAGES);D.pixelStorei(D.UNPACK_ROW_LENGTH,Dt.width),D.pixelStorei(D.UNPACK_IMAGE_HEIGHT,Dt.height),D.pixelStorei(D.UNPACK_SKIP_PIXELS,je),D.pixelStorei(D.UNPACK_SKIP_ROWS,Ze),D.pixelStorei(D.UNPACK_SKIP_IMAGES,We);const Ct=O.isDataArrayTexture||O.isData3DTexture,yn=Q.isDataArrayTexture||Q.isData3DTexture;if(O.isDepthTexture){const Vn=J.get(O),pn=J.get(Q),_n=J.get(Vn.__renderTarget),id=J.get(pn.__renderTarget);z.bindFramebuffer(D.READ_FRAMEBUFFER,_n.__webglFramebuffer),z.bindFramebuffer(D.DRAW_FRAMEBUFFER,id.__webglFramebuffer);for(let Bs=0;BsMath.PI&&(n-=gn),i<-Math.PI?i+=gn:i>Math.PI&&(i-=gn),n<=i?this._spherical.theta=Math.max(n,Math.min(i,this._spherical.theta)):this._spherical.theta=this._spherical.theta>(n+i)/2?Math.max(n,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 r=!1;if(this.zoomToCursor&&this._performCursorZoom||this.object.isOrthographicCamera)this._spherical.radius=this._clampDistance(this._spherical.radius);else{const o=this._spherical.radius;this._spherical.radius=this._clampDistance(this._spherical.radius*this._scale),r=o!=this._spherical.radius}if(Vt.setFromSpherical(this._spherical),Vt.applyQuaternion(this._quatInverse),t.copy(this.target).add(Vt),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 o=null;if(this.object.isPerspectiveCamera){const a=Vt.length();o=this._clampDistance(a*this._scale);const l=a-o;this.object.position.addScaledVector(this._dollyDirection,l),this.object.updateMatrixWorld(),r=!!l}else if(this.object.isOrthographicCamera){const a=new R(this._mouse.x,this._mouse.y,0);a.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(a),this.object.updateMatrixWorld(),o=Vt.length()}else console.warn("WARNING: OrbitControls.js encountered an unknown camera type - zoom to cursor disabled."),this.zoomToCursor=!1;o!==null&&(this.screenSpacePanning?this.target.set(0,0,-1).transformDirection(this.object.matrix).multiplyScalar(o).add(this.object.position):(Va.origin.copy(this.object.position),Va.direction.set(0,0,-1).transformDirection(this.object.matrix),Math.abs(this.object.up.dot(Va.direction))Xh||8*(1-this._lastQuaternion.dot(this.object.quaternion))>Xh||this._lastTargetPosition.distanceToSquared(this.target)>Xh?(this.dispatchEvent(Lp),this._lastPosition.copy(this.object.position),this._lastQuaternion.copy(this.object.quaternion),this._lastTargetPosition.copy(this.target),!0):!1}_getAutoRotationAngle(e){return e!==null?gn/60*this.autoRotateSpeed*e:gn/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){Vt.setFromMatrixColumn(t,0),Vt.multiplyScalar(-e),this._panOffset.add(Vt)}_panUp(e,t){this.screenSpacePanning===!0?Vt.setFromMatrixColumn(t,1):(Vt.setFromMatrixColumn(t,0),Vt.crossVectors(this.object.up,Vt)),Vt.multiplyScalar(e),this._panOffset.add(Vt)}_pan(e,t){const n=this.domElement;if(this.object.isPerspectiveCamera){const i=this.object.position;Vt.copy(i).sub(this.target);let r=Vt.length();r*=Math.tan(this.object.fov/2*Math.PI/180),this._panLeft(2*e*r/n.clientHeight,this.object.matrix),this._panUp(2*t*r/n.clientHeight,this.object.matrix)}else this.object.isOrthographicCamera?(this._panLeft(e*(this.object.right-this.object.left)/this.object.zoom/n.clientWidth,this.object.matrix),this._panUp(t*(this.object.top-this.object.bottom)/this.object.zoom/n.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 n=this.domElement.getBoundingClientRect(),i=e-n.left,r=t-n.top,o=n.width,a=n.height;this._mouse.x=i/o*2-1,this._mouse.y=-(r/a)*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(gn*this._rotateDelta.x/t.clientHeight),this._rotateUp(gn*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(gn*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(-gn*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(gn*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(-gn*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),n=.5*(e.pageX+t.x),i=.5*(e.pageY+t.y);this._rotateStart.set(n,i)}}_handleTouchStartPan(e){if(this._pointers.length===1)this._panStart.set(e.pageX,e.pageY);else{const t=this._getSecondPointerPosition(e),n=.5*(e.pageX+t.x),i=.5*(e.pageY+t.y);this._panStart.set(n,i)}}_handleTouchStartDolly(e){const t=this._getSecondPointerPosition(e),n=e.pageX-t.x,i=e.pageY-t.y,r=Math.sqrt(n*n+i*i);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 n=this._getSecondPointerPosition(e),i=.5*(e.pageX+n.x),r=.5*(e.pageY+n.y);this._rotateEnd.set(i,r)}this._rotateDelta.subVectors(this._rotateEnd,this._rotateStart).multiplyScalar(this.rotateSpeed);const t=this.domElement;this._rotateLeft(gn*this._rotateDelta.x/t.clientHeight),this._rotateUp(gn*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),n=.5*(e.pageX+t.x),i=.5*(e.pageY+t.y);this._panEnd.set(n,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(e){const t=this._getSecondPointerPosition(e),n=e.pageX-t.x,i=e.pageY-t.y,r=Math.sqrt(n*n+i*i);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 o=(e.pageX+t.x)*.5,a=(e.pageY+t.y)*.5;this._updateZoomParameters(o,a)}_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;te}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}addEvents(){const e=this._Engine?.DeviceType,t=e==="PC"||!e;console.log("[FirstPersonCameraControl] addEvents - DeviceType:",e,"isPC:",t),t?(console.log("[FirstPersonCameraControl] 添加鼠标事件监听器 - mousedown, mouseup"),this.domElement.addEventListener("mousedown",this.bindmousedown,!1),this.domElement.addEventListener("mouseup",this.bindmouseup,!1)):(console.log("[FirstPersonCameraControl] 添加触摸事件监听器"),this.domElement.addEventListener("touchstart",this.bindmousedown,!1),this.domElement.addEventListener("touchend",this.bindmouseup,!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._Engine&&this._Engine.DeviceType!=="PC"?(this.domElement.removeEventListener("touchstart",this.bindmousedown),this.domElement.removeEventListener("touchend",this.bindmouseup),this.domElement.removeEventListener("touchmove",this.bindmousemove)):(this.domElement.removeEventListener("mousedown",this.bindmousedown),this.domElement.removeEventListener("mouseup",this.bindmouseup),this.domElement.removeEventListener("mousemove",this.bindmousemove)),window.removeEventListener("keydown",this.bindonKeyDown),window.removeEventListener("keyup",this.bindonKeyUp),this.needMousewheel&&(document.addEventListener&&document.removeEventListener("DOMMouseScroll",this.bindMousewheel),window.removeEventListener("mousewheel",this.bindMousewheel))}onMousewheel(e){debugger;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){console.log("[FirstPersonCameraControl] onMouseDown 被调用",e),this.domElement.addEventListener("mousemove",this.bindmousemove,!1),this._prevMouseX=e.screenX,this._prevMouseY=e.screenY}onMouseMove(e){if(this._isEnabled==!1)return;let t=this._prevMouseX?e.screenX-this._prevMouseX:0,n=this._prevMouseY?e.screenY-this._prevMouseY:0,i=this._euler.x-n*this.lookflag*this.lookSpeed;i>=0?i-this.maxRotateX?this._euler.x=i:this._euler.x=-this.maxRotateX,this._euler.y-=t*this.lookSpeed,this.camera.quaternion.setFromEuler(this._euler),this._prevMouseX=e.screenX,this._prevMouseY=e.screenY;let r=this.GetEngine();r.movefirst=!0;var o=new CustomEvent("bimengine:camerachange",{detail:""});window.dispatchEvent(o)}onMouseUp(e){let t=this.GetEngine();t.movefirst=!1,this.domElement.removeEventListener("mousemove",this.bindmousemove)}onTouchStart(e){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,n=this._prevMouseY?e.targetTouches[0].clientY-this._prevMouseY:0,i=this._euler.x-n*this.lookflag*this.lookSpeed;i>=0?i-this.maxRotateX?this._euler.x=i: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;let r=this.GetEngine();r.movefirst=!0;var o=new CustomEvent("bimengine:camerachange",{detail:""});window.dispatchEvent(o)}onTouchEnd(e){let t=this.GetEngine();t.movefirst=!1,this.domElement.removeEventListener("touchmove",this.bindmousemove)}onKeyDown(e){var t=new CustomEvent("bimengine:camerachange",{detail:""});let n=this.GetEngine();switch(n.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){let 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 n=t.point.add(new R(0,this.playerHeight,0));if(this.positionEasing){if(n.y>=this.camera.position.y||n.y-this.camera.position.y<.2){this.setCameraHeight(this.camera.position.y+(n.y-this.camera.position.y)*.08),this._fallingTime=0,e=!1;return}}else t.distanceP[0]).forEach(P=>{let _=new R(P.X,P.Z,-P.Y),S=s.worldToScreen.worldToScreen(_),I=Math.sqrt(Math.pow(S.x-f.offsetX,2)+Math.pow(S.y-f.offsetY,2));I0?(b.sort((P,_)=>P.distance-_.distance),g="point"):(x[2].forEach(P=>{let _=new R(P[0].X,P[0].Z,-P[0].Y),S=new R(P[1].X,P[1].Z,-P[1].Y),I=s.worldToScreen.worldToScreen(_),A=s.worldToScreen.worldToScreen(S),B=M(new ue(f.offsetX,f.offsetY),I,A);if(B0&&(v.sort((P,_)=>P.distance-_.distance),g="line")),g=="point"&&e.options.showCatch){const P=s.worldToScreen.worldToScreen(b[0].point);console.log("捕捉点屏幕坐标:",P.x,P.y),console.log("Canvas尺寸:",s.renderer.domElement.width,s.renderer.domElement.height),console.log("SVG尺寸:",s.catchSvg.clientWidth,s.catchSvg.clientHeight),s.catchSvg.innerHTML="";const _=document.createElementNS("http://www.w3.org/2000/svg","circle");_.setAttribute("class","catchPoint"),_.setAttribute("cx",(P.x+s.reactBoundingClientRect.left).toString()),_.setAttribute("cy",(P.y+s.reactBoundingClientRect.top).toString()),_.setAttribute("r","5"),_.setAttribute("fill","rgb(0, 255, 247)"),s.catchSvg.appendChild(_)}else if(g=="line"&&e.options.showCatch){const P=s.worldToScreen.worldToScreen(v[0].point),_=v[0].start,S=v[0].end;console.log("捕捉点屏幕坐标:",P.x,P.y),console.log("Canvas尺寸:",s.renderer.domElement.width,s.renderer.domElement.height),console.log("SVG尺寸:",s.catchSvg.clientWidth,s.catchSvg.clientHeight),s.catchSvg.innerHTML="";const I=document.createElementNS("http://www.w3.org/2000/svg","line");I.setAttribute("class","catchLine"),I.setAttribute("x1",(_.x+s.reactBoundingClientRect.left).toString()),I.setAttribute("y1",(_.y+s.reactBoundingClientRect.top).toString()),I.setAttribute("x2",(S.x+s.reactBoundingClientRect.left).toString()),I.setAttribute("y2",(S.y+s.reactBoundingClientRect.top).toString()),I.setAttribute("stroke","rgb(0, 255, 247)"),I.setAttribute("stroke-width","2"),s.catchSvg.appendChild(I)}else if(g=="face"&&e.options.showCatch){let P=d[0].point.clone(),_=d[0].normal||(d[0].face?d[0].face.normal:null);const S=(_?_.clone():new R(0,0,1)).normalize(),I=Math.abs(S.y)<.9?new R(0,1,0):new R(1,0,0),A=new R().crossVectors(S,I).normalize(),B=new R().crossVectors(S,A).normalize(),w=.05,F=[new R().copy(A).add(B).multiplyScalar(w),new R().copy(A).sub(B).multiplyScalar(w),new R().copy(A).multiplyScalar(-1).sub(B).multiplyScalar(w),new R().copy(A).multiplyScalar(-1).add(B).multiplyScalar(w)].map(X=>new R().copy(P).add(X)).map(X=>s.worldToScreen.worldToScreen(X));s.catchSvg.innerHTML="";const W=document.createElementNS("http://www.w3.org/2000/svg","polygon");W.setAttribute("class","catchFace"),W.setAttribute("points",F.map(X=>`${X.x+s.reactBoundingClientRect.left},${X.y+s.reactBoundingClientRect.top}`).join(" ")),W.setAttribute("fill","rgba(1, 238, 255, 0.2)"),W.setAttribute("stroke","rgb(0, 255, 247)"),W.setAttribute("stroke-width","1"),s.catchSvg.appendChild(W)}return d[0];function M(P,_,S){const I=new ue().subVectors(S,_),A=I.lengthSq();if(A<1e-10)return P.distanceTo(_);const B=new ue().subVectors(P,_),w=Ot.clamp(B.dot(I)/A,0,1),F=new ue().copy(I).multiplyScalar(w).add(_);return P.distanceTo(F)}function E(P,_,S){const I=new ue().subVectors(S,_),A=I.lengthSq();if(A<1e-10)return 0;const B=new ue().subVectors(P,_);return Ot.clamp(B.dot(I)/A,0,1)}function C(P,_,S){const I=Ot.clamp(P,0,1);return new R().lerpVectors(_,S,I)}}return e}class w2{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=jh(this.engine),this.handelBehaved.init(this,null),this.handelBehaved.active()}init(){this.orbitControls=new h2(this.engine,this.engine.camera,this.engine.renderer.domElement),this.orbitControls.showOriginIcon=!0,this.firstPersonControls=new Bp(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}getMoveSpeed(){return this.firstPersonControls.moveSpeed}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 Bp(this.engine,this.engine.camera,this.engine.renderer.domElement,[]),this.orbitControls.enabled=!1,this.firstPersonControls.enabled=!0,this.firstPersonControls.isActive=!0}switchDefaultMode(){this.firstPersonControls&&(this.firstPersonControls.enabled=!1,this.engine.cameraModule.switchToOrthographicCamera()),this.orbitControls.enabled=!0}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 Ga={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 Er{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 S2=new ps(-1,1,1,-1,0,1);class E2 extends bt{constructor(){super(),this.setAttribute("position",new rn([-1,3,0,-1,-1,0,3,-1,0],3)),this.setAttribute("uv",new rn([0,2,0,0,2,0],2))}}const T2=new E2;class qh{constructor(e){this._mesh=new ht(T2,e)}dispose(){this._mesh.geometry.dispose()}render(e){e.render(this._mesh,S2)}get material(){return this._mesh.material}set material(e){this._mesh.material=e}}class Wa extends Er{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=Xi.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 qh(this.material)}render(e,t,n){this.uniforms[this.textureID]&&(this.uniforms[this.textureID].value=n.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 Np extends Er{constructor(e,t){super(),this.scene=e,this.camera=t,this.clear=!0,this.needsSwap=!1,this.inverse=!1}render(e,t,n){const i=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 o,a;this.inverse?(o=0,a=1):(o=1,a=0),r.buffers.stencil.setTest(!0),r.buffers.stencil.setOp(i.REPLACE,i.REPLACE,i.REPLACE),r.buffers.stencil.setFunc(i.ALWAYS,o,4294967295),r.buffers.stencil.setClear(a),r.buffers.stencil.setLocked(!0),e.setRenderTarget(n),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(i.EQUAL,1,4294967295),r.buffers.stencil.setOp(i.KEEP,i.KEEP,i.KEEP),r.buffers.stencil.setLocked(!0)}}class C2 extends Er{constructor(){super(),this.needsSwap=!1}render(e){e.state.buffers.stencil.setLocked(!1),e.state.buffers.stencil.setTest(!1)}}class A2{constructor(e,t){if(this.renderer=e,this._pixelRatio=e.getPixelRatio(),t===void 0){const n=e.getSize(new ue);this._width=n.width,this._height=n.height,t=new qn(this._width*this._pixelRatio,this._height*this._pixelRatio,{type:xi}),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 Wa(Ga),this.copyPass.material.blending=Wt,this.clock=new zv}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) { vec4 clipSpacePosition = vec4(vec3(screenPosition, depth) * 2.0 - 1.0, 1.0); 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); if (depth >= 1.0) { discard; return; } 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; }`},ja={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 ); }`},Zh={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 R2(s=5){const e=Math.floor(s)%2===0?Math.floor(s)+1:Math.floor(s),t=L2(e),n=t.length,i=new Uint8Array(n*4);for(let o=0;o #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) { vec4 clipSpacePosition = vec4(vec3(screenPosition, depth) * 2.0 - 1.0, 1.0); 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 kp(s,e,t){const n=I2(s,e,t);let i="vec3[SAMPLES](";for(let r=0;rp?(x=1,g=0):(x=0,g=1);const b=m-x+h,v=p-g+h,y=m-1+2*h,M=p-1+2*h,E=l&255,C=c&255,P=this.perm[E+this.perm[C]]%12,_=this.perm[E+x+this.perm[C+g]]%12,S=this.perm[E+1+this.perm[C+1]]%12;let I=.5-m*m-p*p;I<0?n=0:(I*=I,n=I*I*this._dot(this.grad3[P],m,p));let A=.5-b*b-v*v;A<0?i=0:(A*=A,i=A*A*this._dot(this.grad3[_],b,v));let B=.5-y*y-M*M;return B<0?r=0:(B*=B,r=B*B*this._dot(this.grad3[S],y,M)),70*(n+i+r)}noise3d(e,t,n){let i,r,o,a;const l=(e+t+n)*.3333333333333333,c=Math.floor(e+l),h=Math.floor(t+l),u=Math.floor(n+l),f=1/6,d=(c+h+u)*f,m=c-d,p=h-d,x=u-d,g=e-m,b=t-p,v=n-x;let y,M,E,C,P,_;g>=b?b>=v?(y=1,M=0,E=0,C=1,P=1,_=0):g>=v?(y=1,M=0,E=0,C=1,P=0,_=1):(y=0,M=0,E=1,C=1,P=0,_=1):bS?32:0,w=_>I?16:0,F=S>I?8:0,W=_>A?4:0,X=S>A?2:0,$=I>A?1:0,Z=B+w+F+W+X+$,ie=o[Z][0]>=3?1:0,j=o[Z][1]>=3?1:0,Y=o[Z][2]>=3?1:0,ge=o[Z][3]>=3?1:0,pe=o[Z][0]>=2?1:0,de=o[Z][1]>=2?1:0,se=o[Z][2]>=2?1:0,ce=o[Z][3]>=2?1:0,fe=o[Z][0]>=1?1:0,be=o[Z][1]>=1?1:0,Se=o[Z][2]>=1?1:0,Ne=o[Z][3]>=1?1:0,Je=_-ie+c,ke=S-j+c,T=I-Y+c,D=A-ge+c,V=_-pe+2*c,U=S-de+2*c,k=I-se+2*c,z=A-ce+2*c,ee=_-fe+3*c,J=S-be+3*c,G=I-Se+3*c,N=A-Ne+3*c,L=_-1+4*c,H=S-1+4*c,K=I-1+4*c,le=A-1+4*c,te=x&255,Ce=g&255,ye=b&255,Re=v&255,Ie=a[te+a[Ce+a[ye+a[Re]]]]%32,he=a[te+ie+a[Ce+j+a[ye+Y+a[Re+ge]]]]%32,_e=a[te+pe+a[Ce+de+a[ye+se+a[Re+ce]]]]%32,Ve=a[te+fe+a[Ce+be+a[ye+Se+a[Re+Ne]]]]%32,Ue=a[te+1+a[Ce+1+a[ye+1+a[Re+1]]]]%32;let Ae=.6-_*_-S*S-I*I-A*A;Ae<0?h=0:(Ae*=Ae,h=Ae*Ae*this._dot4(r[Ie],_,S,I,A));let Ge=.6-Je*Je-ke*ke-T*T-D*D;Ge<0?u=0:(Ge*=Ge,u=Ge*Ge*this._dot4(r[he],Je,ke,T,D));let q=.6-V*V-U*U-k*k-z*z;q<0?f=0:(q*=q,f=q*q*this._dot4(r[_e],V,U,k,z));let Te=.6-ee*ee-J*J-G*G-N*N;Te<0?d=0:(Te*=Te,d=Te*Te*this._dot4(r[Ve],ee,J,G,N));let Me=.6-L*L-H*H-K*K-le*le;return Me<0?m=0:(Me*=Me,m=Me*Me*this._dot4(r[Ue],L,H,K,le)),27*(h+u+f+d+m)}_dot(e,t,n){return e[0]*t+e[1]*n}_dot3(e,t,n,i){return e[0]*t+e[1]*n+e[2]*i}_dot4(e,t,n,i,r){return e[0]*t+e[1]*n+e[2]*i+e[3]*r}}class xn extends Er{constructor(e,t,n=512,i=512,r,o,a){super(),this.width=n,this.height=i,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=R2(),this.pdNoiseTexture=this._generateNoise(),this.gtaoRenderTarget=new qn(this.width,this.height,{type:xi}),this.pdRenderTarget=this.gtaoRenderTarget.clone(),this.gtaoMaterial=new Jt({defines:Object.assign({},Xa.defines),uniforms:Xi.clone(Xa.uniforms),vertexShader:Xa.vertexShader,fragmentShader:Xa.fragmentShader,blending:Wt,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 gv,this.normalMaterial.blending=Wt,this.pdMaterial=new Jt({defines:Object.assign({},qa.defines),uniforms:Xi.clone(qa.uniforms),vertexShader:qa.vertexShader,fragmentShader:qa.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({},ja.defines),uniforms:Xi.clone(ja.uniforms),vertexShader:ja.vertexShader,fragmentShader:ja.fragmentShader,blending:Wt}),this.depthRenderMaterial.uniforms.cameraNear.value=this.camera.near,this.depthRenderMaterial.uniforms.cameraFar.value=this.camera.far,this.copyMaterial=new Jt({uniforms:Xi.clone(Ga.uniforms),vertexShader:Ga.vertexShader,fragmentShader:Ga.fragmentShader,transparent:!0,depthTest:!1,depthWrite:!1,blendSrc:Xl,blendDst:Vr,blendEquation:Gn,blendSrcAlpha:Wl,blendDstAlpha:Vr,blendEquationAlpha:Gn}),this.blendMaterial=new Jt({uniforms:Xi.clone(Zh.uniforms),vertexShader:Zh.vertexShader,fragmentShader:Zh.fragmentShader,transparent:!0,depthTest:!1,depthWrite:!1,blending:hd,blendSrc:Xl,blendDst:Vr,blendEquation:Gn,blendSrcAlpha:Wl,blendDstAlpha:Vr,blendEquationAlpha:Gn}),this._fsQuad=new qh(null),this._originalClearColor=new He,this.setGBuffer(r?r.depthTexture:void 0,r?r.normalTexture:void 0),o!==void 0&&this.updateGtaoMaterial(o),a!==void 0&&this.updatePdMaterial(a)}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 yh,this.depthTexture.format=Gs,this.depthTexture.type=Vs,this.normalRenderTarget=new qn(this.width,this.height,{minFilter:$t,magFilter:$t,type:xi,depthTexture:this.depthTexture}),this.normalTexture=this.normalRenderTarget.texture,this._renderGBuffer=!0);const n=this.normalTexture?1:0,i=this.depthTexture===this.normalTexture?"w":"x";this.gtaoMaterial.defines.NORMAL_VECTOR_TYPE=n,this.gtaoMaterial.defines.DEPTH_SWIZZLING=i,this.gtaoMaterial.uniforms.tNormal.value=this.normalTexture,this.gtaoMaterial.uniforms.tDepth.value=this.depthTexture,this.pdMaterial.defines.NORMAL_VECTOR_TYPE=n,this.pdMaterial.defines.DEPTH_SWIZZLING=i,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=kp(this.pdSamples,this.pdRings,this.pdRadiusExponent),this.pdMaterial.needsUpdate=!0)}render(e,t,n){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 xn.OUTPUT.Off:break;case xn.OUTPUT.Diffuse:this.copyMaterial.uniforms.tDiffuse.value=n.texture,this.copyMaterial.blending=Wt,this._renderPass(e,this.copyMaterial,this.renderToScreen?null:t);break;case xn.OUTPUT.AO:this.copyMaterial.uniforms.tDiffuse.value=this.gtaoRenderTarget.texture,this.copyMaterial.blending=Wt,this._renderPass(e,this.copyMaterial,this.renderToScreen?null:t);break;case xn.OUTPUT.Denoise:this.copyMaterial.uniforms.tDiffuse.value=this.pdRenderTarget.texture,this.copyMaterial.blending=Wt,this._renderPass(e,this.copyMaterial,this.renderToScreen?null:t);break;case xn.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 xn.OUTPUT.Normal:this.copyMaterial.uniforms.tDiffuse.value=this.normalRenderTarget.texture,this.copyMaterial.blending=Wt,this._renderPass(e,this.copyMaterial,this.renderToScreen?null:t);break;case xn.OUTPUT.Default:this.copyMaterial.uniforms.tDiffuse.value=n.texture,this.copyMaterial.blending=Wt,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,n,i,r){e.getClearColor(this._originalClearColor);const o=e.getClearAlpha(),a=e.autoClear;e.setRenderTarget(n),e.autoClear=!1,i!=null&&(e.setClearColor(i),e.setClearAlpha(r||0),e.clear()),this._fsQuad.material=t,this._fsQuad.render(e),e.autoClear=a,e.setClearColor(this._originalClearColor),e.setClearAlpha(o)}_renderOverride(e,t,n,i,r){e.getClearColor(this._originalClearColor);const o=e.getClearAlpha(),a=e.autoClear;e.setRenderTarget(n),e.autoClear=!1,i=t.clearColor||i,r=t.clearAlpha||r,i!=null&&(e.setClearColor(i),e.setClearAlpha(r||0),e.clear()),this.scene.overrideMaterial=t,e.render(this.scene,this.camera),this.scene.overrideMaterial=null,e.autoClear=a,e.setClearColor(this._originalClearColor),e.setClearAlpha(o)}_overrideVisibility(){const e=this.scene,t=this._visibilityCache;e.traverse(function(n){(n.isPoints||n.isLine||n.isLine2)&&n.visible&&(n.visible=!1,t.push(n))})}_restoreVisibility(){const e=this._visibilityCache;for(let t=0;t #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 B2 extends Er{constructor(){super(),this.uniforms=Xi.clone(Za.uniforms),this.material=new mv({name:Za.name,uniforms:this.uniforms,vertexShader:Za.vertexShader,fragmentShader:Za.fragmentShader}),this._fsQuad=new qh(this.material),this._outputColorSpace=null,this._toneMapping=null}render(e,t,n){this.uniforms.tDiffuse.value=n.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={},it.getTransfer(this._outputColorSpace)===lt&&(this.material.defines.SRGB_TRANSFER=""),this._toneMapping===ud?this.material.defines.LINEAR_TONE_MAPPING="":this._toneMapping===dd?this.material.defines.REINHARD_TONE_MAPPING="":this._toneMapping===fd?this.material.defines.CINEON_TONE_MAPPING="":this._toneMapping===pd?this.material.defines.ACES_FILMIC_TONE_MAPPING="":this._toneMapping===gd?this.material.defines.AGX_TONE_MAPPING="":this._toneMapping===xd?this.material.defines.NEUTRAL_TONE_MAPPING="":this._toneMapping===md&&(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 N2={name:"FXAAShader",uniforms:{tDiffuse:{value:null},resolution:{value:new ue(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 ); }`},k2={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 U2{engine;composer;saturationPass;constructor(e){this.engine=e}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 n=this.engine.renderer?.getPixelRatio?.()??window.devicePixelRatio??1;this.composer.setPixelRatio(n),this.composer.setSize(e,t);const i=this.composer.passes.find(r=>r instanceof Wa&&r.material.uniforms.resolution);i&&(i.material.uniforms.resolution.value.x=1/(e*n),i.material.uniforms.resolution.value.y=1/(t*n))}init(){const{width:e,height:t}=this.engine.deviceModule.getContainerSize(),n=this.engine.scene,i=this.engine.camera,r=this.engine.renderer,o=this.engine.renderer?.getPixelRatio?.()??window.devicePixelRatio??1,a=new qn(e,t,{minFilter:Kt,magFilter:Kt,format:mn,samples:4});this.composer=new A2(r,a),this.composer.setPixelRatio(o),this.composer.setSize(e,t);const l=new P2(n,i);this.composer.addPass(l);const c=new xn(n,i,e,t);c.output=xn.OUTPUT.Default,c.blendIntensity=.5,c.enabled=!1,c.updateGtaoMaterial&&c.updateGtaoMaterial({radius:1,distanceExponent:1,thickness:1,scale:1,distanceFallOff:1,screenSpaceRadius:!0}),this.composer.addPass(c),this.saturationPass=new Wa(k2),this.saturationPass.uniforms.saturation.value=1.3,this.saturationPass.uniforms.contrast.value=1.1,this.saturationPass.enabled=!1,this.composer.addPass(this.saturationPass);const h=new B2;h.enabled=!1,this.composer.addPass(h);const u=new Wa(N2);u.material.uniforms.resolution.value.x=1/(e*o),u.material.uniforms.resolution.value.y=1/(t*o),u.enabled=!1,this.composer.addPass(u)}}var Ya=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Up(s){return s&&s.__esModule&&Object.prototype.hasOwnProperty.call(s,"default")?s.default:s}function $a(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 Op={exports:{}},Fp;function O2(){return Fp||(Fp=1,(function(s,e){(function(t){s.exports=t()})(function(){return(function t(n,i,r){function o(c,h){if(!i[c]){if(!n[c]){var u=typeof $a=="function"&&$a;if(!h&&u)return u(c,!0);if(a)return a(c,!0);var f=new Error("Cannot find module '"+c+"'");throw f.code="MODULE_NOT_FOUND",f}var d=i[c]={exports:{}};n[c][0].call(d.exports,function(m){var p=n[c][1][m];return o(p||m)},d,d.exports,t,n,i,r)}return i[c].exports}for(var a=typeof $a=="function"&&$a,l=0;l>2,d=(3&c)<<4|h>>4,m=1>6:64,p=2>4,h=(15&f)<<4|(d=a.indexOf(l.charAt(p++)))>>2,u=(3&d)<<6|(m=a.indexOf(l.charAt(p++))),b[x++]=c,d!==64&&(b[x++]=h),m!==64&&(b[x++]=u);return b}},{"./support":30,"./utils":32}],2:[function(t,n,i){var r=t("./external"),o=t("./stream/DataWorker"),a=t("./stream/Crc32Probe"),l=t("./stream/DataLengthProbe");function c(h,u,f,d,m){this.compressedSize=h,this.uncompressedSize=u,this.crc32=f,this.compression=d,this.compressedContent=m}c.prototype={getContentWorker:function(){var h=new o(r.Promise.resolve(this.compressedContent)).pipe(this.compression.uncompressWorker()).pipe(new l("data_length")),u=this;return h.on("end",function(){if(this.streamInfo.data_length!==u.uncompressedSize)throw new Error("Bug : uncompressed data size mismatch")}),h},getCompressedWorker:function(){return new o(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,u,f){return h.pipe(new a).pipe(new l("uncompressedSize")).pipe(u.compressWorker(f)).pipe(new l("compressedSize")).withStreamInfo("compression",u)},n.exports=c},{"./external":6,"./stream/Crc32Probe":25,"./stream/DataLengthProbe":26,"./stream/DataWorker":27}],3:[function(t,n,i){var r=t("./stream/GenericWorker");i.STORE={magic:"\0\0",compressWorker:function(){return new r("STORE compression")},uncompressWorker:function(){return new r("STORE decompression")}},i.DEFLATE=t("./flate")},{"./flate":7,"./stream/GenericWorker":28}],4:[function(t,n,i){var r=t("./utils"),o=(function(){for(var a,l=[],c=0;c<256;c++){a=c;for(var h=0;h<8;h++)a=1&a?3988292384^a>>>1:a>>>1;l[c]=a}return l})();n.exports=function(a,l){return a!==void 0&&a.length?r.getTypeOf(a)!=="string"?(function(c,h,u,f){var d=o,m=f+u;c^=-1;for(var p=f;p>>8^d[255&(c^h[p])];return-1^c})(0|l,a,a.length,0):(function(c,h,u,f){var d=o,m=f+u;c^=-1;for(var p=f;p>>8^d[255&(c^h.charCodeAt(p))];return-1^c})(0|l,a,a.length,0):0}},{"./utils":32}],5:[function(t,n,i){i.base64=!1,i.binary=!1,i.dir=!1,i.createFolders=!0,i.date=null,i.compression=null,i.compressionOptions=null,i.comment=null,i.unixPermissions=null,i.dosPermissions=null},{}],6:[function(t,n,i){var r=null;r=typeof Promise<"u"?Promise:t("lie"),n.exports={Promise:r}},{lie:37}],7:[function(t,n,i){var r=typeof Uint8Array<"u"&&typeof Uint16Array<"u"&&typeof Uint32Array<"u",o=t("pako"),a=t("./utils"),l=t("./stream/GenericWorker"),c=r?"uint8array":"array";function h(u,f){l.call(this,"FlateWorker/"+u),this._pako=null,this._pakoAction=u,this._pakoOptions=f,this.meta={}}i.magic="\b\0",a.inherits(h,l),h.prototype.processChunk=function(u){this.meta=u.meta,this._pako===null&&this._createPako(),this._pako.push(a.transformTo(c,u.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 o[this._pakoAction]({raw:!0,level:this._pakoOptions.level||-1});var u=this;this._pako.onData=function(f){u.push({data:f,meta:u.meta})}},i.compressWorker=function(u){return new h("Deflate",u)},i.uncompressWorker=function(){return new h("Inflate",{})}},{"./stream/GenericWorker":28,"./utils":32,pako:38}],8:[function(t,n,i){function r(d,m){var p,x="";for(p=0;p>>=8;return x}function o(d,m,p,x,g,b){var v,y,M=d.file,E=d.compression,C=b!==c.utf8encode,P=a.transformTo("string",b(M.name)),_=a.transformTo("string",c.utf8encode(M.name)),S=M.comment,I=a.transformTo("string",b(S)),A=a.transformTo("string",c.utf8encode(S)),B=_.length!==M.name.length,w=A.length!==S.length,F="",W="",X="",$=M.dir,Z=M.date,ie={crc32:0,compressedSize:0,uncompressedSize:0};m&&!p||(ie.crc32=d.crc32,ie.compressedSize=d.compressedSize,ie.uncompressedSize=d.uncompressedSize);var j=0;m&&(j|=8),C||!B&&!w||(j|=2048);var Y=0,ge=0;$&&(Y|=16),g==="UNIX"?(ge=798,Y|=(function(de,se){var ce=de;return de||(ce=se?16893:33204),(65535&ce)<<16})(M.unixPermissions,$)):(ge=20,Y|=(function(de){return 63&(de||0)})(M.dosPermissions)),v=Z.getUTCHours(),v<<=6,v|=Z.getUTCMinutes(),v<<=5,v|=Z.getUTCSeconds()/2,y=Z.getUTCFullYear()-1980,y<<=4,y|=Z.getUTCMonth()+1,y<<=5,y|=Z.getUTCDate(),B&&(W=r(1,1)+r(h(P),4)+_,F+="up"+r(W.length,2)+W),w&&(X=r(1,1)+r(h(I),4)+A,F+="uc"+r(X.length,2)+X);var pe="";return pe+=` \0`,pe+=r(j,2),pe+=E.magic,pe+=r(v,2),pe+=r(y,2),pe+=r(ie.crc32,4),pe+=r(ie.compressedSize,4),pe+=r(ie.uncompressedSize,4),pe+=r(P.length,2),pe+=r(F.length,2),{fileRecord:u.LOCAL_FILE_HEADER+pe+P+F,dirRecord:u.CENTRAL_FILE_HEADER+r(ge,2)+pe+r(I.length,2)+"\0\0\0\0"+r(Y,4)+r(x,4)+P+F+I}}var a=t("../utils"),l=t("../stream/GenericWorker"),c=t("../utf8"),h=t("../crc32"),u=t("../signature");function f(d,m,p,x){l.call(this,"ZipFileWorker"),this.bytesWritten=0,this.zipComment=m,this.zipPlatform=p,this.encodeFileName=x,this.streamFiles=d,this.accumulate=!1,this.contentBuffer=[],this.dirRecords=[],this.currentSourceOffset=0,this.entriesCount=0,this.currentFile=null,this._sources=[]}a.inherits(f,l),f.prototype.push=function(d){var m=d.meta.percent||0,p=this.entriesCount,x=this._sources.length;this.accumulate?this.contentBuffer.push(d):(this.bytesWritten+=d.data.length,l.prototype.push.call(this,{data:d.data,meta:{currentFile:this.currentFile,percent:p?(m+100*(p-x-1))/p:100}}))},f.prototype.openedSource=function(d){this.currentSourceOffset=this.bytesWritten,this.currentFile=d.file.name;var m=this.streamFiles&&!d.file.dir;if(m){var p=o(d,m,!1,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);this.push({data:p.fileRecord,meta:{percent:0}})}else this.accumulate=!0},f.prototype.closedSource=function(d){this.accumulate=!1;var m=this.streamFiles&&!d.file.dir,p=o(d,m,!0,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);if(this.dirRecords.push(p.dirRecord),m)this.push({data:(function(x){return u.DATA_DESCRIPTOR+r(x.crc32,4)+r(x.compressedSize,4)+r(x.uncompressedSize,4)})(d),meta:{percent:100}});else for(this.push({data:p.fileRecord,meta:{percent:0}});this.contentBuffer.length;)this.push(this.contentBuffer.shift());this.currentFile=null},f.prototype.flush=function(){for(var d=this.bytesWritten,m=0;m=this.index;l--)c=(c<<8)+this.byteAt(l);return this.index+=a,c},readString:function(a){return r.transformTo("string",this.readData(a))},readData:function(){},lastIndexOfSignature:function(){},readAndCheckSignature:function(){},readDate:function(){var a=this.readInt(4);return new Date(Date.UTC(1980+(a>>25&127),(a>>21&15)-1,a>>16&31,a>>11&31,a>>5&63,(31&a)<<1))}},n.exports=o},{"../utils":32}],19:[function(t,n,i){var r=t("./Uint8ArrayReader");function o(a){r.call(this,a)}t("../utils").inherits(o,r),o.prototype.readData=function(a){this.checkOffset(a);var l=this.data.slice(this.zero+this.index,this.zero+this.index+a);return this.index+=a,l},n.exports=o},{"../utils":32,"./Uint8ArrayReader":21}],20:[function(t,n,i){var r=t("./DataReader");function o(a){r.call(this,a)}t("../utils").inherits(o,r),o.prototype.byteAt=function(a){return this.data.charCodeAt(this.zero+a)},o.prototype.lastIndexOfSignature=function(a){return this.data.lastIndexOf(a)-this.zero},o.prototype.readAndCheckSignature=function(a){return a===this.readData(4)},o.prototype.readData=function(a){this.checkOffset(a);var l=this.data.slice(this.zero+this.index,this.zero+this.index+a);return this.index+=a,l},n.exports=o},{"../utils":32,"./DataReader":18}],21:[function(t,n,i){var r=t("./ArrayReader");function o(a){r.call(this,a)}t("../utils").inherits(o,r),o.prototype.readData=function(a){if(this.checkOffset(a),a===0)return new Uint8Array(0);var l=this.data.subarray(this.zero+this.index,this.zero+this.index+a);return this.index+=a,l},n.exports=o},{"../utils":32,"./ArrayReader":17}],22:[function(t,n,i){var r=t("../utils"),o=t("../support"),a=t("./ArrayReader"),l=t("./StringReader"),c=t("./NodeBufferReader"),h=t("./Uint8ArrayReader");n.exports=function(u){var f=r.getTypeOf(u);return r.checkSupport(f),f!=="string"||o.uint8array?f==="nodebuffer"?new c(u):o.uint8array?new h(r.transformTo("uint8array",u)):new a(r.transformTo("array",u)):new l(u)}},{"../support":30,"../utils":32,"./ArrayReader":17,"./NodeBufferReader":19,"./StringReader":20,"./Uint8ArrayReader":21}],23:[function(t,n,i){i.LOCAL_FILE_HEADER="PK",i.CENTRAL_FILE_HEADER="PK",i.CENTRAL_DIRECTORY_END="PK",i.ZIP64_CENTRAL_DIRECTORY_LOCATOR="PK\x07",i.ZIP64_CENTRAL_DIRECTORY_END="PK",i.DATA_DESCRIPTOR="PK\x07\b"},{}],24:[function(t,n,i){var r=t("./GenericWorker"),o=t("../utils");function a(l){r.call(this,"ConvertWorker to "+l),this.destType=l}o.inherits(a,r),a.prototype.processChunk=function(l){this.push({data:o.transformTo(this.destType,l.data),meta:l.meta})},n.exports=a},{"../utils":32,"./GenericWorker":28}],25:[function(t,n,i){var r=t("./GenericWorker"),o=t("../crc32");function a(){r.call(this,"Crc32Probe"),this.withStreamInfo("crc32",0)}t("../utils").inherits(a,r),a.prototype.processChunk=function(l){this.streamInfo.crc32=o(l.data,this.streamInfo.crc32||0),this.push(l)},n.exports=a},{"../crc32":4,"../utils":32,"./GenericWorker":28}],26:[function(t,n,i){var r=t("../utils"),o=t("./GenericWorker");function a(l){o.call(this,"DataLengthProbe for "+l),this.propName=l,this.withStreamInfo(l,0)}r.inherits(a,o),a.prototype.processChunk=function(l){if(l){var c=this.streamInfo[this.propName]||0;this.streamInfo[this.propName]=c+l.data.length}o.prototype.processChunk.call(this,l)},n.exports=a},{"../utils":32,"./GenericWorker":28}],27:[function(t,n,i){var r=t("../utils"),o=t("./GenericWorker");function a(l){o.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(a,o),a.prototype.cleanUp=function(){o.prototype.cleanUp.call(this),this.data=null},a.prototype.resume=function(){return!!o.prototype.resume.call(this)&&(!this._tickScheduled&&this.dataIsReady&&(this._tickScheduled=!0,r.delay(this._tickAndRepeat,[],this)),!0)},a.prototype._tickAndRepeat=function(){this._tickScheduled=!1,this.isPaused||this.isFinished||(this._tick(),this.isFinished||(r.delay(this._tickAndRepeat,[],this),this._tickScheduled=!0))},a.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}})},n.exports=a},{"../utils":32,"./GenericWorker":28}],28:[function(t,n,i){function r(o){this.name=o||"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(o){this.emit("data",o)},end:function(){if(this.isFinished)return!1;this.flush();try{this.emit("end"),this.cleanUp(),this.isFinished=!0}catch(o){this.emit("error",o)}return!0},error:function(o){return!this.isFinished&&(this.isPaused?this.generatedError=o:(this.isFinished=!0,this.emit("error",o),this.previous&&this.previous.error(o),this.cleanUp()),!0)},on:function(o,a){return this._listeners[o].push(a),this},cleanUp:function(){this.streamInfo=this.generatedError=this.extraStreamInfo=null,this._listeners=[]},emit:function(o,a){if(this._listeners[o])for(var l=0;l "+o:o}},n.exports=r},{}],29:[function(t,n,i){var r=t("../utils"),o=t("./ConvertWorker"),a=t("./GenericWorker"),l=t("../base64"),c=t("../support"),h=t("../external"),u=null;if(c.nodestream)try{u=t("../nodejs/NodejsStreamOutputAdapter")}catch{}function f(m,p){return new h.Promise(function(x,g){var b=[],v=m._internalType,y=m._outputType,M=m._mimeType;m.on("data",function(E,C){b.push(E),p&&p(C)}).on("error",function(E){b=[],g(E)}).on("end",function(){try{var E=(function(C,P,_){switch(C){case"blob":return r.newBlob(r.transformTo("arraybuffer",P),_);case"base64":return l.encode(P);default:return r.transformTo(C,P)}})(y,(function(C,P){var _,S=0,I=null,A=0;for(_=0;_"u")i.blob=!1;else{var r=new ArrayBuffer(0);try{i.blob=new Blob([r],{type:"application/zip"}).size===0}catch{try{var o=new(self.BlobBuilder||self.WebKitBlobBuilder||self.MozBlobBuilder||self.MSBlobBuilder);o.append(r),i.blob=o.getBlob("application/zip").size===0}catch{i.blob=!1}}}try{i.nodestream=!!t("readable-stream").Readable}catch{i.nodestream=!1}},{"readable-stream":16}],31:[function(t,n,i){for(var r=t("./utils"),o=t("./support"),a=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 u(){l.call(this,"utf-8 decode"),this.leftOver=null}function f(){l.call(this,"utf-8 encode")}i.utf8encode=function(d){return o.nodebuffer?a.newBufferFrom(d,"utf-8"):(function(m){var p,x,g,b,v,y=m.length,M=0;for(b=0;b>>6:(x<65536?p[v++]=224|x>>>12:(p[v++]=240|x>>>18,p[v++]=128|x>>>12&63),p[v++]=128|x>>>6&63),p[v++]=128|63&x);return p})(d)},i.utf8decode=function(d){return o.nodebuffer?r.transformTo("nodebuffer",d).toString("utf-8"):(function(m){var p,x,g,b,v=m.length,y=new Array(2*v);for(p=x=0;p>10&1023,y[x++]=56320|1023&g)}return y.length!==x&&(y.subarray?y=y.subarray(0,x):y.length=x),r.applyFromCharCode(y)})(d=r.transformTo(o.uint8array?"uint8array":"array",d))},r.inherits(u,l),u.prototype.processChunk=function(d){var m=r.transformTo(o.uint8array?"uint8array":"array",d.data);if(this.leftOver&&this.leftOver.length){if(o.uint8array){var p=m;(m=new Uint8Array(p.length+this.leftOver.length)).set(this.leftOver,0),m.set(p,this.leftOver.length)}else m=this.leftOver.concat(m);this.leftOver=null}var x=(function(b,v){var y;for((v=v||b.length)>b.length&&(v=b.length),y=v-1;0<=y&&(192&b[y])==128;)y--;return y<0||y===0?v:y+c[b[y]]>v?y:v})(m),g=m;x!==m.length&&(o.uint8array?(g=m.subarray(0,x),this.leftOver=m.subarray(x,m.length)):(g=m.slice(0,x),this.leftOver=m.slice(x,m.length))),this.push({data:i.utf8decode(g),meta:d.meta})},u.prototype.flush=function(){this.leftOver&&this.leftOver.length&&(this.push({data:i.utf8decode(this.leftOver),meta:{}}),this.leftOver=null)},i.Utf8DecodeWorker=u,r.inherits(f,l),f.prototype.processChunk=function(d){this.push({data:i.utf8encode(d.data),meta:d.meta})},i.Utf8EncodeWorker=f},{"./nodejsUtils":14,"./stream/GenericWorker":28,"./support":30,"./utils":32}],32:[function(t,n,i){var r=t("./support"),o=t("./base64"),a=t("./nodejsUtils"),l=t("./external");function c(p){return p}function h(p,x){for(var g=0;g>8;this.dir=!!(16&this.externalFileAttributes),d==0&&(this.dosPermissions=63&this.externalFileAttributes),d==3&&(this.unixPermissions=this.externalFileAttributes>>16&65535),this.dir||this.fileNameStr.slice(-1)!=="/"||(this.dir=!0)},parseZIP64ExtraField:function(){if(this.extraFields[1]){var d=r(this.extraFields[1].value);this.uncompressedSize===o.MAX_VALUE_32BITS&&(this.uncompressedSize=d.readInt(8)),this.compressedSize===o.MAX_VALUE_32BITS&&(this.compressedSize=d.readInt(8)),this.localHeaderOffset===o.MAX_VALUE_32BITS&&(this.localHeaderOffset=d.readInt(8)),this.diskNumberStart===o.MAX_VALUE_32BITS&&(this.diskNumberStart=d.readInt(4))}},readExtraFields:function(d){var m,p,x,g=d.index+this.extraFieldsLength;for(this.extraFields||(this.extraFields={});d.index+4>>6:(d<65536?f[x++]=224|d>>>12:(f[x++]=240|d>>>18,f[x++]=128|d>>>12&63),f[x++]=128|d>>>6&63),f[x++]=128|63&d);return f},i.buf2binstring=function(u){return h(u,u.length)},i.binstring2buf=function(u){for(var f=new r.Buf8(u.length),d=0,m=f.length;d>10&1023,b[m++]=56320|1023&p)}return h(b,m)},i.utf8border=function(u,f){var d;for((f=f||u.length)>u.length&&(f=u.length),d=f-1;0<=d&&(192&u[d])==128;)d--;return d<0||d===0?f:d+l[u[d]]>f?d:f}},{"./common":41}],43:[function(t,n,i){n.exports=function(r,o,a,l){for(var c=65535&r|0,h=r>>>16&65535|0,u=0;a!==0;){for(a-=u=2e3>>1:o>>>1;a[l]=o}return a})();n.exports=function(o,a,l,c){var h=r,u=c+l;o^=-1;for(var f=c;f>>8^h[255&(o^a[f])];return-1^o}},{}],46:[function(t,n,i){var r,o=t("../utils/common"),a=t("./trees"),l=t("./adler32"),c=t("./crc32"),h=t("./messages"),u=0,f=4,d=0,m=-2,p=-1,x=4,g=2,b=8,v=9,y=286,M=30,E=19,C=2*y+1,P=15,_=3,S=258,I=S+_+1,A=42,B=113,w=1,F=2,W=3,X=4;function $(T,D){return T.msg=h[D],D}function Z(T){return(T<<1)-(4T.avail_out&&(V=T.avail_out),V!==0&&(o.arraySet(T.output,D.pending_buf,D.pending_out,V,T.next_out),T.next_out+=V,D.pending_out+=V,T.total_out+=V,T.avail_out-=V,D.pending-=V,D.pending===0&&(D.pending_out=0))}function Y(T,D){a._tr_flush_block(T,0<=T.block_start?T.block_start:-1,T.strstart-T.block_start,D),T.block_start=T.strstart,j(T.strm)}function ge(T,D){T.pending_buf[T.pending++]=D}function pe(T,D){T.pending_buf[T.pending++]=D>>>8&255,T.pending_buf[T.pending++]=255&D}function de(T,D){var V,U,k=T.max_chain_length,z=T.strstart,ee=T.prev_length,J=T.nice_match,G=T.strstart>T.w_size-I?T.strstart-(T.w_size-I):0,N=T.window,L=T.w_mask,H=T.prev,K=T.strstart+S,le=N[z+ee-1],te=N[z+ee];T.prev_length>=T.good_match&&(k>>=2),J>T.lookahead&&(J=T.lookahead);do if(N[(V=D)+ee]===te&&N[V+ee-1]===le&&N[V]===N[z]&&N[++V]===N[z+1]){z+=2,V++;do;while(N[++z]===N[++V]&&N[++z]===N[++V]&&N[++z]===N[++V]&&N[++z]===N[++V]&&N[++z]===N[++V]&&N[++z]===N[++V]&&N[++z]===N[++V]&&N[++z]===N[++V]&&zG&&--k!=0);return ee<=T.lookahead?ee:T.lookahead}function se(T){var D,V,U,k,z,ee,J,G,N,L,H=T.w_size;do{if(k=T.window_size-T.lookahead-T.strstart,T.strstart>=H+(H-I)){for(o.arraySet(T.window,T.window,H,H,0),T.match_start-=H,T.strstart-=H,T.block_start-=H,D=V=T.hash_size;U=T.head[--D],T.head[D]=H<=U?U-H:0,--V;);for(D=V=H;U=T.prev[--D],T.prev[D]=H<=U?U-H:0,--V;);k+=H}if(T.strm.avail_in===0)break;if(ee=T.strm,J=T.window,G=T.strstart+T.lookahead,N=k,L=void 0,L=ee.avail_in,N=_)for(z=T.strstart-T.insert,T.ins_h=T.window[z],T.ins_h=(T.ins_h<=_&&(T.ins_h=(T.ins_h<=_)if(U=a._tr_tally(T,T.strstart-T.match_start,T.match_length-_),T.lookahead-=T.match_length,T.match_length<=T.max_lazy_match&&T.lookahead>=_){for(T.match_length--;T.strstart++,T.ins_h=(T.ins_h<=_&&(T.ins_h=(T.ins_h<=_&&T.match_length<=T.prev_length){for(k=T.strstart+T.lookahead-_,U=a._tr_tally(T,T.strstart-1-T.prev_match,T.prev_length-_),T.lookahead-=T.prev_length-1,T.prev_length-=2;++T.strstart<=k&&(T.ins_h=(T.ins_h<T.pending_buf_size-5&&(V=T.pending_buf_size-5);;){if(T.lookahead<=1){if(se(T),T.lookahead===0&&D===u)return w;if(T.lookahead===0)break}T.strstart+=T.lookahead,T.lookahead=0;var U=T.block_start+V;if((T.strstart===0||T.strstart>=U)&&(T.lookahead=T.strstart-U,T.strstart=U,Y(T,!1),T.strm.avail_out===0)||T.strstart-T.block_start>=T.w_size-I&&(Y(T,!1),T.strm.avail_out===0))return w}return T.insert=0,D===f?(Y(T,!0),T.strm.avail_out===0?W:X):(T.strstart>T.block_start&&(Y(T,!1),T.strm.avail_out),w)}),new be(4,4,8,4,ce),new be(4,5,16,8,ce),new be(4,6,32,32,ce),new be(4,4,16,16,fe),new be(8,16,32,32,fe),new be(8,16,128,128,fe),new be(8,32,128,256,fe),new be(32,128,258,1024,fe),new be(32,258,258,4096,fe)],i.deflateInit=function(T,D){return ke(T,D,b,15,8,0)},i.deflateInit2=ke,i.deflateReset=Je,i.deflateResetKeep=Ne,i.deflateSetHeader=function(T,D){return T&&T.state?T.state.wrap!==2?m:(T.state.gzhead=D,d):m},i.deflate=function(T,D){var V,U,k,z;if(!T||!T.state||5>8&255),ge(U,U.gzhead.time>>16&255),ge(U,U.gzhead.time>>24&255),ge(U,U.level===9?2:2<=U.strategy||U.level<2?4:0),ge(U,255&U.gzhead.os),U.gzhead.extra&&U.gzhead.extra.length&&(ge(U,255&U.gzhead.extra.length),ge(U,U.gzhead.extra.length>>8&255)),U.gzhead.hcrc&&(T.adler=c(T.adler,U.pending_buf,U.pending,0)),U.gzindex=0,U.status=69):(ge(U,0),ge(U,0),ge(U,0),ge(U,0),ge(U,0),ge(U,U.level===9?2:2<=U.strategy||U.level<2?4:0),ge(U,3),U.status=B);else{var ee=b+(U.w_bits-8<<4)<<8;ee|=(2<=U.strategy||U.level<2?0:U.level<6?1:U.level===6?2:3)<<6,U.strstart!==0&&(ee|=32),ee+=31-ee%31,U.status=B,pe(U,ee),U.strstart!==0&&(pe(U,T.adler>>>16),pe(U,65535&T.adler)),T.adler=1}if(U.status===69)if(U.gzhead.extra){for(k=U.pending;U.gzindex<(65535&U.gzhead.extra.length)&&(U.pending!==U.pending_buf_size||(U.gzhead.hcrc&&U.pending>k&&(T.adler=c(T.adler,U.pending_buf,U.pending-k,k)),j(T),k=U.pending,U.pending!==U.pending_buf_size));)ge(U,255&U.gzhead.extra[U.gzindex]),U.gzindex++;U.gzhead.hcrc&&U.pending>k&&(T.adler=c(T.adler,U.pending_buf,U.pending-k,k)),U.gzindex===U.gzhead.extra.length&&(U.gzindex=0,U.status=73)}else U.status=73;if(U.status===73)if(U.gzhead.name){k=U.pending;do{if(U.pending===U.pending_buf_size&&(U.gzhead.hcrc&&U.pending>k&&(T.adler=c(T.adler,U.pending_buf,U.pending-k,k)),j(T),k=U.pending,U.pending===U.pending_buf_size)){z=1;break}z=U.gzindexk&&(T.adler=c(T.adler,U.pending_buf,U.pending-k,k)),z===0&&(U.gzindex=0,U.status=91)}else U.status=91;if(U.status===91)if(U.gzhead.comment){k=U.pending;do{if(U.pending===U.pending_buf_size&&(U.gzhead.hcrc&&U.pending>k&&(T.adler=c(T.adler,U.pending_buf,U.pending-k,k)),j(T),k=U.pending,U.pending===U.pending_buf_size)){z=1;break}z=U.gzindexk&&(T.adler=c(T.adler,U.pending_buf,U.pending-k,k)),z===0&&(U.status=103)}else U.status=103;if(U.status===103&&(U.gzhead.hcrc?(U.pending+2>U.pending_buf_size&&j(T),U.pending+2<=U.pending_buf_size&&(ge(U,255&T.adler),ge(U,T.adler>>8&255),T.adler=0,U.status=B)):U.status=B),U.pending!==0){if(j(T),T.avail_out===0)return U.last_flush=-1,d}else if(T.avail_in===0&&Z(D)<=Z(V)&&D!==f)return $(T,-5);if(U.status===666&&T.avail_in!==0)return $(T,-5);if(T.avail_in!==0||U.lookahead!==0||D!==u&&U.status!==666){var J=U.strategy===2?(function(G,N){for(var L;;){if(G.lookahead===0&&(se(G),G.lookahead===0)){if(N===u)return w;break}if(G.match_length=0,L=a._tr_tally(G,0,G.window[G.strstart]),G.lookahead--,G.strstart++,L&&(Y(G,!1),G.strm.avail_out===0))return w}return G.insert=0,N===f?(Y(G,!0),G.strm.avail_out===0?W:X):G.last_lit&&(Y(G,!1),G.strm.avail_out===0)?w:F})(U,D):U.strategy===3?(function(G,N){for(var L,H,K,le,te=G.window;;){if(G.lookahead<=S){if(se(G),G.lookahead<=S&&N===u)return w;if(G.lookahead===0)break}if(G.match_length=0,G.lookahead>=_&&0G.lookahead&&(G.match_length=G.lookahead)}if(G.match_length>=_?(L=a._tr_tally(G,1,G.match_length-_),G.lookahead-=G.match_length,G.strstart+=G.match_length,G.match_length=0):(L=a._tr_tally(G,0,G.window[G.strstart]),G.lookahead--,G.strstart++),L&&(Y(G,!1),G.strm.avail_out===0))return w}return G.insert=0,N===f?(Y(G,!0),G.strm.avail_out===0?W:X):G.last_lit&&(Y(G,!1),G.strm.avail_out===0)?w:F})(U,D):r[U.level].func(U,D);if(J!==W&&J!==X||(U.status=666),J===w||J===W)return T.avail_out===0&&(U.last_flush=-1),d;if(J===F&&(D===1?a._tr_align(U):D!==5&&(a._tr_stored_block(U,0,0,!1),D===3&&(ie(U.head),U.lookahead===0&&(U.strstart=0,U.block_start=0,U.insert=0))),j(T),T.avail_out===0))return U.last_flush=-1,d}return D!==f?d:U.wrap<=0?1:(U.wrap===2?(ge(U,255&T.adler),ge(U,T.adler>>8&255),ge(U,T.adler>>16&255),ge(U,T.adler>>24&255),ge(U,255&T.total_in),ge(U,T.total_in>>8&255),ge(U,T.total_in>>16&255),ge(U,T.total_in>>24&255)):(pe(U,T.adler>>>16),pe(U,65535&T.adler)),j(T),0=V.w_size&&(z===0&&(ie(V.head),V.strstart=0,V.block_start=0,V.insert=0),N=new o.Buf8(V.w_size),o.arraySet(N,D,L-V.w_size,V.w_size,0),D=N,L=V.w_size),ee=T.avail_in,J=T.next_in,G=T.input,T.avail_in=L,T.next_in=0,T.input=D,se(V);V.lookahead>=_;){for(U=V.strstart,k=V.lookahead-(_-1);V.ins_h=(V.ins_h<>>=_=P>>>24,v-=_,(_=P>>>16&255)===0)F[h++]=65535&P;else{if(!(16&_)){if((64&_)==0){P=y[(65535&P)+(b&(1<<_)-1)];continue t}if(32&_){a.mode=12;break e}r.msg="invalid literal/length code",a.mode=30;break e}S=65535&P,(_&=15)&&(v<_&&(b+=w[l++]<>>=_,v-=_),v<15&&(b+=w[l++]<>>=_=P>>>24,v-=_,!(16&(_=P>>>16&255))){if((64&_)==0){P=M[(65535&P)+(b&(1<<_)-1)];continue n}r.msg="invalid distance code",a.mode=30;break e}if(I=65535&P,v<(_&=15)&&(b+=w[l++]<>>=_,v-=_,(_=h-u)>3,b&=(1<<(v-=S<<3))-1,r.next_in=l,r.next_out=h,r.avail_in=l>>24&255)+(A>>>8&65280)+((65280&A)<<8)+((255&A)<<24)}function b(){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 v(A){var B;return A&&A.state?(B=A.state,A.total_in=A.total_out=B.total=0,A.msg="",B.wrap&&(A.adler=1&B.wrap),B.mode=m,B.last=0,B.havedict=0,B.dmax=32768,B.head=null,B.hold=0,B.bits=0,B.lencode=B.lendyn=new r.Buf32(p),B.distcode=B.distdyn=new r.Buf32(x),B.sane=1,B.back=-1,f):d}function y(A){var B;return A&&A.state?((B=A.state).wsize=0,B.whave=0,B.wnext=0,v(A)):d}function M(A,B){var w,F;return A&&A.state?(F=A.state,B<0?(w=0,B=-B):(w=1+(B>>4),B<48&&(B&=15)),B&&(B<8||15=X.wsize?(r.arraySet(X.window,B,w-X.wsize,X.wsize,0),X.wnext=0,X.whave=X.wsize):(F<(W=X.wsize-X.wnext)&&(W=F),r.arraySet(X.window,B,w-F,W,X.wnext),(F-=W)?(r.arraySet(X.window,B,w-F,F,0),X.wnext=F,X.whave=X.wsize):(X.wnext+=W,X.wnext===X.wsize&&(X.wnext=0),X.whave>>8&255,w.check=a(w.check,z,2,0),Y=j=0,w.mode=2;break}if(w.flags=0,w.head&&(w.head.done=!1),!(1&w.wrap)||(((255&j)<<8)+(j>>8))%31){A.msg="incorrect header check",w.mode=30;break}if((15&j)!=8){A.msg="unknown compression method",w.mode=30;break}if(Y-=4,T=8+(15&(j>>>=4)),w.wbits===0)w.wbits=T;else if(T>w.wbits){A.msg="invalid window size",w.mode=30;break}w.dmax=1<>8&1),512&w.flags&&(z[0]=255&j,z[1]=j>>>8&255,w.check=a(w.check,z,2,0)),Y=j=0,w.mode=3;case 3:for(;Y<32;){if(Z===0)break e;Z--,j+=F[X++]<>>8&255,z[2]=j>>>16&255,z[3]=j>>>24&255,w.check=a(w.check,z,4,0)),Y=j=0,w.mode=4;case 4:for(;Y<16;){if(Z===0)break e;Z--,j+=F[X++]<>8),512&w.flags&&(z[0]=255&j,z[1]=j>>>8&255,w.check=a(w.check,z,2,0)),Y=j=0,w.mode=5;case 5:if(1024&w.flags){for(;Y<16;){if(Z===0)break e;Z--,j+=F[X++]<>>8&255,w.check=a(w.check,z,2,0)),Y=j=0}else w.head&&(w.head.extra=null);w.mode=6;case 6:if(1024&w.flags&&(Z<(de=w.length)&&(de=Z),de&&(w.head&&(T=w.head.extra_len-w.length,w.head.extra||(w.head.extra=new Array(w.head.extra_len)),r.arraySet(w.head.extra,F,X,de,T)),512&w.flags&&(w.check=a(w.check,F,de,X)),Z-=de,X+=de,w.length-=de),w.length))break e;w.length=0,w.mode=7;case 7:if(2048&w.flags){if(Z===0)break e;for(de=0;T=F[X+de++],w.head&&T&&w.length<65536&&(w.head.name+=String.fromCharCode(T)),T&&de>9&1,w.head.done=!0),A.adler=w.check=0,w.mode=12;break;case 10:for(;Y<32;){if(Z===0)break e;Z--,j+=F[X++]<>>=7&Y,Y-=7&Y,w.mode=27;break}for(;Y<3;){if(Z===0)break e;Z--,j+=F[X++]<>>=1)){case 0:w.mode=14;break;case 1:if(S(w),w.mode=20,B!==6)break;j>>>=2,Y-=2;break e;case 2:w.mode=17;break;case 3:A.msg="invalid block type",w.mode=30}j>>>=2,Y-=2;break;case 14:for(j>>>=7&Y,Y-=7&Y;Y<32;){if(Z===0)break e;Z--,j+=F[X++]<>>16^65535)){A.msg="invalid stored block lengths",w.mode=30;break}if(w.length=65535&j,Y=j=0,w.mode=15,B===6)break e;case 15:w.mode=16;case 16:if(de=w.length){if(Z>>=5,Y-=5,w.ndist=1+(31&j),j>>>=5,Y-=5,w.ncode=4+(15&j),j>>>=4,Y-=4,286>>=3,Y-=3}for(;w.have<19;)w.lens[ee[w.have++]]=0;if(w.lencode=w.lendyn,w.lenbits=7,V={bits:w.lenbits},D=c(0,w.lens,0,19,w.lencode,0,w.work,V),w.lenbits=V.bits,D){A.msg="invalid code lengths set",w.mode=30;break}w.have=0,w.mode=19;case 19:for(;w.have>>16&255,Se=65535&k,!((fe=k>>>24)<=Y);){if(Z===0)break e;Z--,j+=F[X++]<>>=fe,Y-=fe,w.lens[w.have++]=Se;else{if(Se===16){for(U=fe+2;Y>>=fe,Y-=fe,w.have===0){A.msg="invalid bit length repeat",w.mode=30;break}T=w.lens[w.have-1],de=3+(3&j),j>>>=2,Y-=2}else if(Se===17){for(U=fe+3;Y>>=fe)),j>>>=3,Y-=3}else{for(U=fe+7;Y>>=fe)),j>>>=7,Y-=7}if(w.have+de>w.nlen+w.ndist){A.msg="invalid bit length repeat",w.mode=30;break}for(;de--;)w.lens[w.have++]=T}}if(w.mode===30)break;if(w.lens[256]===0){A.msg="invalid code -- missing end-of-block",w.mode=30;break}if(w.lenbits=9,V={bits:w.lenbits},D=c(h,w.lens,0,w.nlen,w.lencode,0,w.work,V),w.lenbits=V.bits,D){A.msg="invalid literal/lengths set",w.mode=30;break}if(w.distbits=6,w.distcode=w.distdyn,V={bits:w.distbits},D=c(u,w.lens,w.nlen,w.ndist,w.distcode,0,w.work,V),w.distbits=V.bits,D){A.msg="invalid distances set",w.mode=30;break}if(w.mode=20,B===6)break e;case 20:w.mode=21;case 21:if(6<=Z&&258<=ie){A.next_out=$,A.avail_out=ie,A.next_in=X,A.avail_in=Z,w.hold=j,w.bits=Y,l(A,pe),$=A.next_out,W=A.output,ie=A.avail_out,X=A.next_in,F=A.input,Z=A.avail_in,j=w.hold,Y=w.bits,w.mode===12&&(w.back=-1);break}for(w.back=0;be=(k=w.lencode[j&(1<>>16&255,Se=65535&k,!((fe=k>>>24)<=Y);){if(Z===0)break e;Z--,j+=F[X++]<>Ne)])>>>16&255,Se=65535&k,!(Ne+(fe=k>>>24)<=Y);){if(Z===0)break e;Z--,j+=F[X++]<>>=Ne,Y-=Ne,w.back+=Ne}if(j>>>=fe,Y-=fe,w.back+=fe,w.length=Se,be===0){w.mode=26;break}if(32&be){w.back=-1,w.mode=12;break}if(64&be){A.msg="invalid literal/length code",w.mode=30;break}w.extra=15&be,w.mode=22;case 22:if(w.extra){for(U=w.extra;Y>>=w.extra,Y-=w.extra,w.back+=w.extra}w.was=w.length,w.mode=23;case 23:for(;be=(k=w.distcode[j&(1<>>16&255,Se=65535&k,!((fe=k>>>24)<=Y);){if(Z===0)break e;Z--,j+=F[X++]<>Ne)])>>>16&255,Se=65535&k,!(Ne+(fe=k>>>24)<=Y);){if(Z===0)break e;Z--,j+=F[X++]<>>=Ne,Y-=Ne,w.back+=Ne}if(j>>>=fe,Y-=fe,w.back+=fe,64&be){A.msg="invalid distance code",w.mode=30;break}w.offset=Se,w.extra=15&be,w.mode=24;case 24:if(w.extra){for(U=w.extra;Y>>=w.extra,Y-=w.extra,w.back+=w.extra}if(w.offset>w.dmax){A.msg="invalid distance too far back",w.mode=30;break}w.mode=25;case 25:if(ie===0)break e;if(de=pe-ie,w.offset>de){if((de=w.offset-de)>w.whave&&w.sane){A.msg="invalid distance too far back",w.mode=30;break}se=de>w.wnext?(de-=w.wnext,w.wsize-de):w.wnext-de,de>w.length&&(de=w.length),ce=w.window}else ce=W,se=$-w.offset,de=w.length;for(ieC?(_=se[ce+x[B]],Y[ge+x[B]]):(_=96,0),b=1<>$)+(v-=b)]=P<<24|_<<16|S|0,v!==0;);for(b=1<>=1;if(b!==0?(j&=b-1,j+=b):j=0,B++,--pe[A]==0){if(A===F)break;A=u[f+x[B]]}if(W>>7)]}function ge(k,z){k.pending_buf[k.pending++]=255&z,k.pending_buf[k.pending++]=z>>>8&255}function pe(k,z,ee){k.bi_valid>g-ee?(k.bi_buf|=z<>g-k.bi_valid,k.bi_valid+=ee-g):(k.bi_buf|=z<>>=1,ee<<=1,0<--z;);return ee>>>1}function ce(k,z,ee){var J,G,N=new Array(x+1),L=0;for(J=1;J<=x;J++)N[J]=L=L+ee[J-1]<<1;for(G=0;G<=z;G++){var H=k[2*G+1];H!==0&&(k[2*G]=se(N[H]++,H))}}function fe(k){var z;for(z=0;z>1;1<=ee;ee--)Ne(k,N,ee);for(G=K;ee=k.heap[1],k.heap[1]=k.heap[k.heap_len--],Ne(k,N,1),J=k.heap[1],k.heap[--k.heap_max]=ee,k.heap[--k.heap_max]=J,N[2*G]=N[2*ee]+N[2*J],k.depth[G]=(k.depth[ee]>=k.depth[J]?k.depth[ee]:k.depth[J])+1,N[2*ee+1]=N[2*J+1]=G,k.heap[1]=G++,Ne(k,N,1),2<=k.heap_len;);k.heap[--k.heap_max]=k.heap[1],(function(te,Ce){var ye,Re,Ie,he,_e,Ve,Ue=Ce.dyn_tree,Ae=Ce.max_code,Ge=Ce.stat_desc.static_tree,q=Ce.stat_desc.has_stree,Te=Ce.stat_desc.extra_bits,Me=Ce.stat_desc.extra_base,we=Ce.stat_desc.max_length,ve=0;for(he=0;he<=x;he++)te.bl_count[he]=0;for(Ue[2*te.heap[te.heap_max]+1]=0,ye=te.heap_max+1;ye>=7;G>>=1)if(1&le&&H.dyn_ltree[2*K]!==0)return o;if(H.dyn_ltree[18]!==0||H.dyn_ltree[20]!==0||H.dyn_ltree[26]!==0)return a;for(K=32;K>>3,(N=k.static_len+3+7>>>3)<=G&&(G=N)):G=N=ee+5,ee+4<=G&&z!==-1?U(k,z,ee,J):k.strategy===4||N===G?(pe(k,2+(J?1:0),3),Je(k,I,A)):(pe(k,4+(J?1:0),3),(function(H,K,le,te){var Ce;for(pe(H,K-257,5),pe(H,le-1,5),pe(H,te-4,4),Ce=0;Ce>>8&255,k.pending_buf[k.d_buf+2*k.last_lit+1]=255&z,k.pending_buf[k.l_buf+k.last_lit]=255&ee,k.last_lit++,z===0?k.dyn_ltree[2*ee]++:(k.matches++,z--,k.dyn_ltree[2*(w[ee]+u+1)]++,k.dyn_dtree[2*Y(z)]++),k.last_lit===k.lit_bufsize-1},i._tr_align=function(k){pe(k,2,3),de(k,v,I),(function(z){z.bi_valid===16?(ge(z,z.bi_buf),z.bi_buf=0,z.bi_valid=0):8<=z.bi_valid&&(z.pending_buf[z.pending++]=255&z.bi_buf,z.bi_buf>>=8,z.bi_valid-=8)})(k)}},{"../utils/common":41}],53:[function(t,n,i){n.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,n,i){(function(r){(function(o,a){if(!o.setImmediate){var l,c,h,u,f=1,d={},m=!1,p=o.document,x=Object.getPrototypeOf&&Object.getPrototypeOf(o);x=x&&x.setTimeout?x:o,l={}.toString.call(o.process)==="[object process]"?function(y){process.nextTick(function(){b(y)})}:(function(){if(o.postMessage&&!o.importScripts){var y=!0,M=o.onmessage;return o.onmessage=function(){y=!1},o.postMessage("","*"),o.onmessage=M,y}})()?(u="setImmediate$"+Math.random()+"$",o.addEventListener?o.addEventListener("message",v,!1):o.attachEvent("onmessage",v),function(y){o.postMessage(u+y,"*")}):o.MessageChannel?((h=new MessageChannel).port1.onmessage=function(y){b(y.data)},function(y){h.port2.postMessage(y)}):p&&"onreadystatechange"in p.createElement("script")?(c=p.documentElement,function(y){var M=p.createElement("script");M.onreadystatechange=function(){b(y),M.onreadystatechange=null,c.removeChild(M),M=null},c.appendChild(M)}):function(y){setTimeout(b,0,y)},x.setImmediate=function(y){typeof y!="function"&&(y=new Function(""+y));for(var M=new Array(arguments.length-1),E=0;E"u"?r===void 0?this:r:self)}).call(this,typeof Ya<"u"?Ya:typeof self<"u"?self:typeof window<"u"?window:{})},{}]},{},[10])(10)})})(Op)),Op.exports}var F2=O2();const zp=Up(F2);function Hp(s,e){return function(){return s.apply(e,arguments)}}const{toString:z2}=Object.prototype,{getPrototypeOf:Yh}=Object,{iterator:Ka,toStringTag:Vp}=Symbol,Ja=(s=>e=>{const t=z2.call(e);return s[t]||(s[t]=t.slice(8,-1).toLowerCase())})(Object.create(null)),Jn=s=>(s=s.toLowerCase(),e=>Ja(e)===s),Qa=s=>e=>typeof e===s,{isArray:Tr}=Array,Cr=Qa("undefined");function wo(s){return s!==null&&!Cr(s)&&s.constructor!==null&&!Cr(s.constructor)&&vn(s.constructor.isBuffer)&&s.constructor.isBuffer(s)}const Gp=Jn("ArrayBuffer");function H2(s){let e;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?e=ArrayBuffer.isView(s):e=s&&s.buffer&&Gp(s.buffer),e}const V2=Qa("string"),vn=Qa("function"),Wp=Qa("number"),So=s=>s!==null&&typeof s=="object",G2=s=>s===!0||s===!1,el=s=>{if(Ja(s)!=="object")return!1;const e=Yh(s);return(e===null||e===Object.prototype||Object.getPrototypeOf(e)===null)&&!(Vp in s)&&!(Ka in s)},W2=s=>{if(!So(s)||wo(s))return!1;try{return Object.keys(s).length===0&&Object.getPrototypeOf(s)===Object.prototype}catch{return!1}},X2=Jn("Date"),j2=Jn("File"),q2=Jn("Blob"),Z2=Jn("FileList"),Y2=s=>So(s)&&vn(s.pipe),$2=s=>{let e;return s&&(typeof FormData=="function"&&s instanceof FormData||vn(s.append)&&((e=Ja(s))==="formdata"||e==="object"&&vn(s.toString)&&s.toString()==="[object FormData]"))},K2=Jn("URLSearchParams"),[J2,Q2,eM,tM]=["ReadableStream","Request","Response","Headers"].map(Jn),nM=s=>s.trim?s.trim():s.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function Eo(s,e,{allOwnKeys:t=!1}={}){if(s===null||typeof s>"u")return;let n,i;if(typeof s!="object"&&(s=[s]),Tr(s))for(n=0,i=s.length;n0;)if(i=t[n],e===i.toLowerCase())return i;return null}const bs=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,jp=s=>!Cr(s)&&s!==bs;function $h(){const{caseless:s,skipUndefined:e}=jp(this)&&this||{},t={},n=(i,r)=>{const o=s&&Xp(t,r)||r;el(t[o])&&el(i)?t[o]=$h(t[o],i):el(i)?t[o]=$h({},i):Tr(i)?t[o]=i.slice():(!e||!Cr(i))&&(t[o]=i)};for(let i=0,r=arguments.length;i(Eo(e,(i,r)=>{t&&vn(i)?s[r]=Hp(i,t):s[r]=i},{allOwnKeys:n}),s),sM=s=>(s.charCodeAt(0)===65279&&(s=s.slice(1)),s),rM=(s,e,t,n)=>{s.prototype=Object.create(e.prototype,n),s.prototype.constructor=s,Object.defineProperty(s,"super",{value:e.prototype}),t&&Object.assign(s.prototype,t)},oM=(s,e,t,n)=>{let i,r,o;const a={};if(e=e||{},s==null)return e;do{for(i=Object.getOwnPropertyNames(s),r=i.length;r-- >0;)o=i[r],(!n||n(o,s,e))&&!a[o]&&(e[o]=s[o],a[o]=!0);s=t!==!1&&Yh(s)}while(s&&(!t||t(s,e))&&s!==Object.prototype);return e},aM=(s,e,t)=>{s=String(s),(t===void 0||t>s.length)&&(t=s.length),t-=e.length;const n=s.indexOf(e,t);return n!==-1&&n===t},lM=s=>{if(!s)return null;if(Tr(s))return s;let e=s.length;if(!Wp(e))return null;const t=new Array(e);for(;e-- >0;)t[e]=s[e];return t},cM=(s=>e=>s&&e instanceof s)(typeof Uint8Array<"u"&&Yh(Uint8Array)),hM=(s,e)=>{const t=(s&&s[Ka]).call(s);let n;for(;(n=t.next())&&!n.done;){const i=n.value;e.call(s,i[0],i[1])}},uM=(s,e)=>{let t;const n=[];for(;(t=s.exec(e))!==null;)n.push(t);return n},dM=Jn("HTMLFormElement"),fM=s=>s.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(e,t,n){return t.toUpperCase()+n}),qp=(({hasOwnProperty:s})=>(e,t)=>s.call(e,t))(Object.prototype),pM=Jn("RegExp"),Zp=(s,e)=>{const t=Object.getOwnPropertyDescriptors(s),n={};Eo(t,(i,r)=>{let o;(o=e(i,r,s))!==!1&&(n[r]=o||i)}),Object.defineProperties(s,n)},mM=s=>{Zp(s,(e,t)=>{if(vn(s)&&["arguments","caller","callee"].indexOf(t)!==-1)return!1;const n=s[t];if(vn(n)){if(e.enumerable=!1,"writable"in e){e.writable=!1;return}e.set||(e.set=()=>{throw Error("Can not rewrite read-only method '"+t+"'")})}})},gM=(s,e)=>{const t={},n=i=>{i.forEach(r=>{t[r]=!0})};return Tr(s)?n(s):n(String(s).split(e)),t},xM=()=>{},vM=(s,e)=>s!=null&&Number.isFinite(s=+s)?s:e;function bM(s){return!!(s&&vn(s.append)&&s[Vp]==="FormData"&&s[Ka])}const yM=s=>{const e=new Array(10),t=(n,i)=>{if(So(n)){if(e.indexOf(n)>=0)return;if(wo(n))return n;if(!("toJSON"in n)){e[i]=n;const r=Tr(n)?[]:{};return Eo(n,(o,a)=>{const l=t(o,i+1);!Cr(l)&&(r[a]=l)}),e[i]=void 0,r}}return n};return t(s,0)},_M=Jn("AsyncFunction"),MM=s=>s&&(So(s)||vn(s))&&vn(s.then)&&vn(s.catch),Yp=((s,e)=>s?setImmediate:e?((t,n)=>(bs.addEventListener("message",({source:i,data:r})=>{i===bs&&r===t&&n.length&&n.shift()()},!1),i=>{n.push(i),bs.postMessage(t,"*")}))(`axios@${Math.random()}`,[]):t=>setTimeout(t))(typeof setImmediate=="function",vn(bs.postMessage)),wM=typeof queueMicrotask<"u"?queueMicrotask.bind(bs):typeof process<"u"&&process.nextTick||Yp,SM=s=>s!=null&&vn(s[Ka]),re={isArray:Tr,isArrayBuffer:Gp,isBuffer:wo,isFormData:$2,isArrayBufferView:H2,isString:V2,isNumber:Wp,isBoolean:G2,isObject:So,isPlainObject:el,isEmptyObject:W2,isReadableStream:J2,isRequest:Q2,isResponse:eM,isHeaders:tM,isUndefined:Cr,isDate:X2,isFile:j2,isBlob:q2,isRegExp:pM,isFunction:vn,isStream:Y2,isURLSearchParams:K2,isTypedArray:cM,isFileList:Z2,forEach:Eo,merge:$h,extend:iM,trim:nM,stripBOM:sM,inherits:rM,toFlatObject:oM,kindOf:Ja,kindOfTest:Jn,endsWith:aM,toArray:lM,forEachEntry:hM,matchAll:uM,isHTMLForm:dM,hasOwnProperty:qp,hasOwnProp:qp,reduceDescriptors:Zp,freezeMethods:mM,toObjectSet:gM,toCamelCase:fM,noop:xM,toFiniteNumber:vM,findKey:Xp,global:bs,isContextDefined:jp,isSpecCompliantForm:bM,toJSONObject:yM,isAsyncFn:_M,isThenable:MM,setImmediate:Yp,asap:wM,isIterable:SM};function Ke(s,e,t,n,i){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),n&&(this.request=n),i&&(this.response=i,this.status=i.status?i.status:null)}re.inherits(Ke,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:re.toJSONObject(this.config),code:this.code,status:this.status}}});const $p=Ke.prototype,Kp={};["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=>{Kp[s]={value:s}}),Object.defineProperties(Ke,Kp),Object.defineProperty($p,"isAxiosError",{value:!0}),Ke.from=(s,e,t,n,i,r)=>{const o=Object.create($p);re.toFlatObject(s,o,function(c){return c!==Error.prototype},c=>c!=="isAxiosError");const a=s&&s.message?s.message:"Error",l=e==null&&s?s.code:e;return Ke.call(o,a,l,t,n,i),s&&o.cause==null&&Object.defineProperty(o,"cause",{value:s,configurable:!0}),o.name=s&&s.name||"Error",r&&Object.assign(o,r),o};const EM=null;function Kh(s){return re.isPlainObject(s)||re.isArray(s)}function Jp(s){return re.endsWith(s,"[]")?s.slice(0,-2):s}function Qp(s,e,t){return s?s.concat(e).map(function(n,i){return n=Jp(n),!t&&i?"["+n+"]":n}).join(t?".":""):e}function TM(s){return re.isArray(s)&&!s.some(Kh)}const CM=re.toFlatObject(re,{},null,function(s){return/^is[A-Z]/.test(s)});function tl(s,e,t){if(!re.isObject(s))throw new TypeError("target must be an object");e=e||new FormData,t=re.toFlatObject(t,{metaTokens:!0,dots:!1,indexes:!1},!1,function(d,m){return!re.isUndefined(m[d])});const n=t.metaTokens,i=t.visitor||c,r=t.dots,o=t.indexes,a=(t.Blob||typeof Blob<"u"&&Blob)&&re.isSpecCompliantForm(e);if(!re.isFunction(i))throw new TypeError("visitor must be a function");function l(d){if(d===null)return"";if(re.isDate(d))return d.toISOString();if(re.isBoolean(d))return d.toString();if(!a&&re.isBlob(d))throw new Ke("Blob is not supported. Use a Buffer instead.");return re.isArrayBuffer(d)||re.isTypedArray(d)?a&&typeof Blob=="function"?new Blob([d]):Buffer.from(d):d}function c(d,m,p){let x=d;if(d&&!p&&typeof d=="object"){if(re.endsWith(m,"{}"))m=n?m:m.slice(0,-2),d=JSON.stringify(d);else if(re.isArray(d)&&TM(d)||(re.isFileList(d)||re.endsWith(m,"[]"))&&(x=re.toArray(d)))return m=Jp(m),x.forEach(function(g,b){!(re.isUndefined(g)||g===null)&&e.append(o===!0?Qp([m],b,r):o===null?m:m+"[]",l(g))}),!1}return Kh(d)?!0:(e.append(Qp(p,m,r),l(d)),!1)}const h=[],u=Object.assign(CM,{defaultVisitor:c,convertValue:l,isVisitable:Kh});function f(d,m){if(!re.isUndefined(d)){if(h.indexOf(d)!==-1)throw Error("Circular reference detected in "+m.join("."));h.push(d),re.forEach(d,function(p,x){(!(re.isUndefined(p)||p===null)&&i.call(e,p,re.isString(x)?x.trim():x,m,u))===!0&&f(p,m?m.concat(x):[x])}),h.pop()}}if(!re.isObject(s))throw new TypeError("data must be an object");return f(s),e}function em(s){const e={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(s).replace(/[!'()~]|%20|%00/g,function(t){return e[t]})}function Jh(s,e){this._pairs=[],s&&tl(s,this,e)}const tm=Jh.prototype;tm.append=function(s,e){this._pairs.push([s,e])},tm.toString=function(s){const e=s?function(t){return s.call(this,t,em)}:em;return this._pairs.map(function(t){return e(t[0])+"="+e(t[1])},"").join("&")};function AM(s){return encodeURIComponent(s).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+")}function nm(s,e,t){if(!e)return s;const n=t&&t.encode||AM;re.isFunction(t)&&(t={serialize:t});const i=t&&t.serialize;let r;if(i?r=i(e,t):r=re.isURLSearchParams(e)?e.toString():new Jh(e,t).toString(n),r){const o=s.indexOf("#");o!==-1&&(s=s.slice(0,o)),s+=(s.indexOf("?")===-1?"?":"&")+r}return s}class im{constructor(){this.handlers=[]}use(e,t,n){return this.handlers.push({fulfilled:e,rejected:t,synchronous:n?n.synchronous:!1,runWhen:n?n.runWhen:null}),this.handlers.length-1}eject(e){this.handlers[e]&&(this.handlers[e]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(e){re.forEach(this.handlers,function(t){t!==null&&e(t)})}}const sm={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},PM=typeof URLSearchParams<"u"?URLSearchParams:Jh,RM=typeof FormData<"u"?FormData:null,LM=typeof Blob<"u"?Blob:null,IM={isBrowser:!0,classes:{URLSearchParams:PM,FormData:RM,Blob:LM},protocols:["http","https","file","blob","url","data"]},Qh=typeof window<"u"&&typeof document<"u",eu=typeof navigator=="object"&&navigator||void 0,DM=Qh&&(!eu||["ReactNative","NativeScript","NS"].indexOf(eu.product)<0),BM=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",NM=Qh&&window.location.href||"http://localhost",kM=Object.freeze(Object.defineProperty({__proto__:null,hasBrowserEnv:Qh,hasStandardBrowserEnv:DM,hasStandardBrowserWebWorkerEnv:BM,navigator:eu,origin:NM},Symbol.toStringTag,{value:"Module"})),an={...kM,...IM};function UM(s,e){return tl(s,new an.classes.URLSearchParams,{visitor:function(t,n,i,r){return an.isNode&&re.isBuffer(t)?(this.append(n,t.toString("base64")),!1):r.defaultVisitor.apply(this,arguments)},...e})}function OM(s){return re.matchAll(/\w+|\[(\w*)]/g,s).map(e=>e[0]==="[]"?"":e[1]||e[0])}function FM(s){const e={},t=Object.keys(s);let n;const i=t.length;let r;for(n=0;n=t.length;return o=!o&&re.isArray(i)?i.length:o,l?(re.hasOwnProp(i,o)?i[o]=[i[o],n]:i[o]=n,!a):((!i[o]||!re.isObject(i[o]))&&(i[o]=[]),e(t,n,i[o],r)&&re.isArray(i[o])&&(i[o]=FM(i[o])),!a)}if(re.isFormData(s)&&re.isFunction(s.entries)){const t={};return re.forEachEntry(s,(n,i)=>{e(OM(n),i,t,0)}),t}return null}function zM(s,e,t){if(re.isString(s))try{return(e||JSON.parse)(s),re.trim(s)}catch(n){if(n.name!=="SyntaxError")throw n}return(t||JSON.stringify)(s)}const To={transitional:sm,adapter:["xhr","http","fetch"],transformRequest:[function(s,e){const t=e.getContentType()||"",n=t.indexOf("application/json")>-1,i=re.isObject(s);if(i&&re.isHTMLForm(s)&&(s=new FormData(s)),re.isFormData(s))return n?JSON.stringify(rm(s)):s;if(re.isArrayBuffer(s)||re.isBuffer(s)||re.isStream(s)||re.isFile(s)||re.isBlob(s)||re.isReadableStream(s))return s;if(re.isArrayBufferView(s))return s.buffer;if(re.isURLSearchParams(s))return e.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),s.toString();let r;if(i){if(t.indexOf("application/x-www-form-urlencoded")>-1)return UM(s,this.formSerializer).toString();if((r=re.isFileList(s))||t.indexOf("multipart/form-data")>-1){const o=this.env&&this.env.FormData;return tl(r?{"files[]":s}:s,o&&new o,this.formSerializer)}}return i||n?(e.setContentType("application/json",!1),zM(s)):s}],transformResponse:[function(s){const e=this.transitional||To.transitional,t=e&&e.forcedJSONParsing,n=this.responseType==="json";if(re.isResponse(s)||re.isReadableStream(s))return s;if(s&&re.isString(s)&&(t&&!this.responseType||n)){const i=!(e&&e.silentJSONParsing)&&n;try{return JSON.parse(s,this.parseReviver)}catch(r){if(i)throw r.name==="SyntaxError"?Ke.from(r,Ke.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:an.classes.FormData,Blob:an.classes.Blob},validateStatus:function(s){return s>=200&&s<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};re.forEach(["delete","get","head","post","put","patch"],s=>{To.headers[s]={}});const HM=re.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"]),VM=s=>{const e={};let t,n,i;return s&&s.split(` `).forEach(function(r){i=r.indexOf(":"),t=r.substring(0,i).trim().toLowerCase(),n=r.substring(i+1).trim(),!(!t||e[t]&&HM[t])&&(t==="set-cookie"?e[t]?e[t].push(n):e[t]=[n]:e[t]=e[t]?e[t]+", "+n:n)}),e},om=Symbol("internals");function Co(s){return s&&String(s).trim().toLowerCase()}function nl(s){return s===!1||s==null?s:re.isArray(s)?s.map(nl):String(s)}function GM(s){const e=Object.create(null),t=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let n;for(;n=t.exec(s);)e[n[1]]=n[2];return e}const WM=s=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(s.trim());function tu(s,e,t,n,i){if(re.isFunction(n))return n.call(this,e,t);if(i&&(e=t),!!re.isString(e)){if(re.isString(n))return e.indexOf(n)!==-1;if(re.isRegExp(n))return n.test(e)}}function XM(s){return s.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(e,t,n)=>t.toUpperCase()+n)}function jM(s,e){const t=re.toCamelCase(" "+e);["get","set","has"].forEach(n=>{Object.defineProperty(s,n+t,{value:function(i,r,o){return this[n].call(this,e,i,r,o)},configurable:!0})})}let bn=class{constructor(s){s&&this.set(s)}set(s,e,t){const n=this;function i(o,a,l){const c=Co(a);if(!c)throw new Error("header name must be a non-empty string");const h=re.findKey(n,c);(!h||n[h]===void 0||l===!0||l===void 0&&n[h]!==!1)&&(n[h||a]=nl(o))}const r=(o,a)=>re.forEach(o,(l,c)=>i(l,c,a));if(re.isPlainObject(s)||s instanceof this.constructor)r(s,e);else if(re.isString(s)&&(s=s.trim())&&!WM(s))r(VM(s),e);else if(re.isObject(s)&&re.isIterable(s)){let o={},a,l;for(const c of s){if(!re.isArray(c))throw TypeError("Object iterator must return a key-value pair");o[l=c[0]]=(a=o[l])?re.isArray(a)?[...a,c[1]]:[a,c[1]]:c[1]}r(o,e)}else s!=null&&i(e,s,t);return this}get(s,e){if(s=Co(s),s){const t=re.findKey(this,s);if(t){const n=this[t];if(!e)return n;if(e===!0)return GM(n);if(re.isFunction(e))return e.call(this,n,t);if(re.isRegExp(e))return e.exec(n);throw new TypeError("parser must be boolean|regexp|function")}}}has(s,e){if(s=Co(s),s){const t=re.findKey(this,s);return!!(t&&this[t]!==void 0&&(!e||tu(this,this[t],t,e)))}return!1}delete(s,e){const t=this;let n=!1;function i(r){if(r=Co(r),r){const o=re.findKey(t,r);o&&(!e||tu(t,t[o],o,e))&&(delete t[o],n=!0)}}return re.isArray(s)?s.forEach(i):i(s),n}clear(s){const e=Object.keys(this);let t=e.length,n=!1;for(;t--;){const i=e[t];(!s||tu(this,this[i],i,s,!0))&&(delete this[i],n=!0)}return n}normalize(s){const e=this,t={};return re.forEach(this,(n,i)=>{const r=re.findKey(t,i);if(r){e[r]=nl(n),delete e[i];return}const o=s?XM(i):String(i).trim();o!==i&&delete e[i],e[o]=nl(n),t[o]=!0}),this}concat(...s){return this.constructor.concat(this,...s)}toJSON(s){const e=Object.create(null);return re.forEach(this,(t,n)=>{t!=null&&t!==!1&&(e[n]=s&&re.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(n=>t.set(n)),t}static accessor(s){const e=(this[om]=this[om]={accessors:{}}).accessors,t=this.prototype;function n(i){const r=Co(i);e[r]||(jM(t,i),e[r]=!0)}return re.isArray(s)?s.forEach(n):n(s),this}};bn.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]),re.reduceDescriptors(bn.prototype,({value:s},e)=>{let t=e[0].toUpperCase()+e.slice(1);return{get:()=>s,set(n){this[t]=n}}}),re.freezeMethods(bn);function nu(s,e){const t=this||To,n=e||t,i=bn.from(n.headers);let r=n.data;return re.forEach(s,function(o){r=o.call(t,r,i.normalize(),e?e.status:void 0)}),i.normalize(),r}function am(s){return!!(s&&s.__CANCEL__)}function Ar(s,e,t){Ke.call(this,s??"canceled",Ke.ERR_CANCELED,e,t),this.name="CanceledError"}re.inherits(Ar,Ke,{__CANCEL__:!0});function lm(s,e,t){const n=t.config.validateStatus;!t.status||!n||n(t.status)?s(t):e(new Ke("Request failed with status code "+t.status,[Ke.ERR_BAD_REQUEST,Ke.ERR_BAD_RESPONSE][Math.floor(t.status/100)-4],t.config,t.request,t))}function qM(s){const e=/^([-+\w]{1,25})(:?\/\/|:)/.exec(s);return e&&e[1]||""}function ZM(s,e){s=s||10;const t=new Array(s),n=new Array(s);let i=0,r=0,o;return e=e!==void 0?e:1e3,function(a){const l=Date.now(),c=n[r];o||(o=l),t[i]=a,n[i]=l;let h=r,u=0;for(;h!==i;)u+=t[h++],h=h%s;if(i=(i+1)%s,i===r&&(r=(r+1)%s),l-o{t=l,i=null,r&&(clearTimeout(r),r=null),s(...a)};return[(...a)=>{const l=Date.now(),c=l-t;c>=n?o(a,l):(i=a,r||(r=setTimeout(()=>{r=null,o(i)},n-c)))},()=>i&&o(i)]}const il=(s,e,t=3)=>{let n=0;const i=ZM(50,250);return YM(r=>{const o=r.loaded,a=r.lengthComputable?r.total:void 0,l=o-n,c=i(l),h=o<=a;n=o;const u={loaded:o,total:a,progress:a?o/a:void 0,bytes:l,rate:c||void 0,estimated:c&&a&&h?(a-o)/c:void 0,event:r,lengthComputable:a!=null,[e?"download":"upload"]:!0};s(u)},t)},cm=(s,e)=>{const t=s!=null;return[n=>e[0]({lengthComputable:t,total:s,loaded:n}),e[1]]},hm=s=>(...e)=>re.asap(()=>s(...e)),$M=an.hasStandardBrowserEnv?((s,e)=>t=>(t=new URL(t,an.origin),s.protocol===t.protocol&&s.host===t.host&&(e||s.port===t.port)))(new URL(an.origin),an.navigator&&/(msie|trident)/i.test(an.navigator.userAgent)):()=>!0,KM=an.hasStandardBrowserEnv?{write(s,e,t,n,i,r,o){if(typeof document>"u")return;const a=[`${s}=${encodeURIComponent(e)}`];re.isNumber(t)&&a.push(`expires=${new Date(t).toUTCString()}`),re.isString(n)&&a.push(`path=${n}`),re.isString(i)&&a.push(`domain=${i}`),r===!0&&a.push("secure"),re.isString(o)&&a.push(`SameSite=${o}`),document.cookie=a.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 JM(s){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(s)}function QM(s,e){return e?s.replace(/\/?\/$/,"")+"/"+e.replace(/^\/+/,""):s}function um(s,e,t){let n=!JM(e);return s&&(n||t==!1)?QM(s,e):e}const dm=s=>s instanceof bn?{...s}:s;function ys(s,e){e=e||{};const t={};function n(c,h,u,f){return re.isPlainObject(c)&&re.isPlainObject(h)?re.merge.call({caseless:f},c,h):re.isPlainObject(h)?re.merge({},h):re.isArray(h)?h.slice():h}function i(c,h,u,f){if(re.isUndefined(h)){if(!re.isUndefined(c))return n(void 0,c,u,f)}else return n(c,h,u,f)}function r(c,h){if(!re.isUndefined(h))return n(void 0,h)}function o(c,h){if(re.isUndefined(h)){if(!re.isUndefined(c))return n(void 0,c)}else return n(void 0,h)}function a(c,h,u){if(u in e)return n(c,h);if(u in s)return n(void 0,c)}const l={url:r,method:r,data:r,baseURL:o,transformRequest:o,transformResponse:o,paramsSerializer:o,timeout:o,timeoutMessage:o,withCredentials:o,withXSRFToken:o,adapter:o,responseType:o,xsrfCookieName:o,xsrfHeaderName:o,onUploadProgress:o,onDownloadProgress:o,decompress:o,maxContentLength:o,maxBodyLength:o,beforeRedirect:o,transport:o,httpAgent:o,httpsAgent:o,cancelToken:o,socketPath:o,responseEncoding:o,validateStatus:a,headers:(c,h,u)=>i(dm(c),dm(h),u,!0)};return re.forEach(Object.keys({...s,...e}),function(c){const h=l[c]||i,u=h(s[c],e[c],c);re.isUndefined(u)&&h!==a||(t[c]=u)}),t}const fm=s=>{const e=ys({},s);let{data:t,withXSRFToken:n,xsrfHeaderName:i,xsrfCookieName:r,headers:o,auth:a}=e;if(e.headers=o=bn.from(o),e.url=nm(um(e.baseURL,e.url,e.allowAbsoluteUrls),s.params,s.paramsSerializer),a&&o.set("Authorization","Basic "+btoa((a.username||"")+":"+(a.password?unescape(encodeURIComponent(a.password)):""))),re.isFormData(t)){if(an.hasStandardBrowserEnv||an.hasStandardBrowserWebWorkerEnv)o.setContentType(void 0);else if(re.isFunction(t.getHeaders)){const l=t.getHeaders(),c=["content-type","content-length"];Object.entries(l).forEach(([h,u])=>{c.includes(h.toLowerCase())&&o.set(h,u)})}}if(an.hasStandardBrowserEnv&&(n&&re.isFunction(n)&&(n=n(e)),n||n!==!1&&$M(e.url))){const l=i&&r&&KM.read(r);l&&o.set(i,l)}return e},ew=typeof XMLHttpRequest<"u",tw=ew&&function(s){return new Promise(function(e,t){const n=fm(s);let i=n.data;const r=bn.from(n.headers).normalize();let{responseType:o,onUploadProgress:a,onDownloadProgress:l}=n,c,h,u,f,d;function m(){f&&f(),d&&d(),n.cancelToken&&n.cancelToken.unsubscribe(c),n.signal&&n.signal.removeEventListener("abort",c)}let p=new XMLHttpRequest;p.open(n.method.toUpperCase(),n.url,!0),p.timeout=n.timeout;function x(){if(!p)return;const b=bn.from("getAllResponseHeaders"in p&&p.getAllResponseHeaders()),v={data:!o||o==="text"||o==="json"?p.responseText:p.response,status:p.status,statusText:p.statusText,headers:b,config:s,request:p};lm(function(y){e(y),m()},function(y){t(y),m()},v),p=null}"onloadend"in p?p.onloadend=x:p.onreadystatechange=function(){!p||p.readyState!==4||p.status===0&&!(p.responseURL&&p.responseURL.indexOf("file:")===0)||setTimeout(x)},p.onabort=function(){p&&(t(new Ke("Request aborted",Ke.ECONNABORTED,s,p)),p=null)},p.onerror=function(b){const v=b&&b.message?b.message:"Network Error",y=new Ke(v,Ke.ERR_NETWORK,s,p);y.event=b||null,t(y),p=null},p.ontimeout=function(){let b=n.timeout?"timeout of "+n.timeout+"ms exceeded":"timeout exceeded";const v=n.transitional||sm;n.timeoutErrorMessage&&(b=n.timeoutErrorMessage),t(new Ke(b,v.clarifyTimeoutError?Ke.ETIMEDOUT:Ke.ECONNABORTED,s,p)),p=null},i===void 0&&r.setContentType(null),"setRequestHeader"in p&&re.forEach(r.toJSON(),function(b,v){p.setRequestHeader(v,b)}),re.isUndefined(n.withCredentials)||(p.withCredentials=!!n.withCredentials),o&&o!=="json"&&(p.responseType=n.responseType),l&&([u,d]=il(l,!0),p.addEventListener("progress",u)),a&&p.upload&&([h,f]=il(a),p.upload.addEventListener("progress",h),p.upload.addEventListener("loadend",f)),(n.cancelToken||n.signal)&&(c=b=>{p&&(t(!b||b.type?new Ar(null,s,p):b),p.abort(),p=null)},n.cancelToken&&n.cancelToken.subscribe(c),n.signal&&(n.signal.aborted?c():n.signal.addEventListener("abort",c)));const g=qM(n.url);if(g&&an.protocols.indexOf(g)===-1){t(new Ke("Unsupported protocol "+g+":",Ke.ERR_BAD_REQUEST,s));return}p.send(i||null)})},nw=(s,e)=>{const{length:t}=s=s?s.filter(Boolean):[];if(e||t){let n=new AbortController,i;const r=function(c){if(!i){i=!0,a();const h=c instanceof Error?c:this.reason;n.abort(h instanceof Ke?h:new Ar(h instanceof Error?h.message:h))}};let o=e&&setTimeout(()=>{o=null,r(new Ke(`timeout ${e} of ms exceeded`,Ke.ETIMEDOUT))},e);const a=()=>{s&&(o&&clearTimeout(o),o=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}=n;return l.unsubscribe=()=>re.asap(a),l}},iw=function*(s,e){let t=s.byteLength;if(t{const i=sw(s,e);let r=0,o,a=l=>{o||(o=!0,n&&n(l))};return new ReadableStream({async pull(l){try{const{done:c,value:h}=await i.next();if(c){a(),l.close();return}let u=h.byteLength;if(t){let f=r+=u;t(f)}l.enqueue(new Uint8Array(h))}catch(c){throw a(c),c}},cancel(l){return a(l),i.return()}},{highWaterMark:2})},mm=64*1024,{isFunction:sl}=re,ow=(({Request:s,Response:e})=>({Request:s,Response:e}))(re.global),{ReadableStream:gm,TextEncoder:xm}=re.global,vm=(s,...e)=>{try{return!!s(...e)}catch{return!1}},aw=s=>{s=re.merge.call({skipUndefined:!0},ow,s);const{fetch:e,Request:t,Response:n}=s,i=e?sl(e):typeof fetch=="function",r=sl(t),o=sl(n);if(!i)return!1;const a=i&&sl(gm),l=i&&(typeof xm=="function"?(m=>p=>m.encode(p))(new xm):async m=>new Uint8Array(await new t(m).arrayBuffer())),c=r&&a&&vm(()=>{let m=!1;const p=new t(an.origin,{body:new gm,method:"POST",get duplex(){return m=!0,"half"}}).headers.has("Content-Type");return m&&!p}),h=o&&a&&vm(()=>re.isReadableStream(new n("").body)),u={stream:h&&(m=>m.body)};i&&["text","arrayBuffer","blob","formData","stream"].forEach(m=>{!u[m]&&(u[m]=(p,x)=>{let g=p&&p[m];if(g)return g.call(p);throw new Ke(`Response type '${m}' is not supported`,Ke.ERR_NOT_SUPPORT,x)})});const f=async m=>{if(m==null)return 0;if(re.isBlob(m))return m.size;if(re.isSpecCompliantForm(m))return(await new t(an.origin,{method:"POST",body:m}).arrayBuffer()).byteLength;if(re.isArrayBufferView(m)||re.isArrayBuffer(m))return m.byteLength;if(re.isURLSearchParams(m)&&(m=m+""),re.isString(m))return(await l(m)).byteLength},d=async(m,p)=>re.toFiniteNumber(m.getContentLength())??f(p);return async m=>{let{url:p,method:x,data:g,signal:b,cancelToken:v,timeout:y,onDownloadProgress:M,onUploadProgress:E,responseType:C,headers:P,withCredentials:_="same-origin",fetchOptions:S}=fm(m),I=e||fetch;C=C?(C+"").toLowerCase():"text";let A=nw([b,v&&v.toAbortSignal()],y),B=null;const w=A&&A.unsubscribe&&(()=>{A.unsubscribe()});let F;try{if(E&&c&&x!=="get"&&x!=="head"&&(F=await d(P,g))!==0){let j=new t(p,{method:"POST",body:g,duplex:"half"}),Y;if(re.isFormData(g)&&(Y=j.headers.get("content-type"))&&P.setContentType(Y),j.body){const[ge,pe]=cm(F,il(hm(E)));g=pm(j.body,mm,ge,pe)}}re.isString(_)||(_=_?"include":"omit");const W=r&&"credentials"in t.prototype,X={...S,signal:A,method:x.toUpperCase(),headers:P.normalize().toJSON(),body:g,duplex:"half",credentials:W?_:void 0};B=r&&new t(p,X);let $=await(r?I(B,S):I(p,X));const Z=h&&(C==="stream"||C==="response");if(h&&(M||Z&&w)){const j={};["status","statusText","headers"].forEach(de=>{j[de]=$[de]});const Y=re.toFiniteNumber($.headers.get("content-length")),[ge,pe]=M&&cm(Y,il(hm(M),!0))||[];$=new n(pm($.body,mm,ge,()=>{pe&&pe(),w&&w()}),j)}C=C||"text";let ie=await u[re.findKey(u,C)||"text"]($,m);return!Z&&w&&w(),await new Promise((j,Y)=>{lm(j,Y,{data:ie,headers:bn.from($.headers),status:$.status,statusText:$.statusText,config:m,request:B})})}catch(W){throw w&&w(),W&&W.name==="TypeError"&&/Load failed|fetch/i.test(W.message)?Object.assign(new Ke("Network Error",Ke.ERR_NETWORK,m,B),{cause:W.cause||W}):Ke.from(W,W&&W.code,m,B)}}},lw=new Map,bm=s=>{let e=s&&s.env||{};const{fetch:t,Request:n,Response:i}=e,r=[n,i,t];let o=r.length,a=o,l,c,h=lw;for(;a--;)l=r[a],c=h.get(l),c===void 0&&h.set(l,c=a?new Map:aw(e)),h=c;return c};bm();const iu={http:EM,xhr:tw,fetch:{get:bm}};re.forEach(iu,(s,e)=>{if(s){try{Object.defineProperty(s,"name",{value:e})}catch{}Object.defineProperty(s,"adapterName",{value:e})}});const ym=s=>`- ${s}`,cw=s=>re.isFunction(s)||s===null||s===!1;function hw(s,e){s=re.isArray(s)?s:[s];const{length:t}=s;let n,i;const r={};for(let o=0;o`adapter ${l} `+(c===!1?"is not supported by the environment":"is not available in the build"));let a=t?o.length>1?`since : `+o.map(ym).join(` `):" "+ym(o[0]):"as no adapter specified";throw new Ke("There is no suitable adapter to dispatch the request "+a,"ERR_NOT_SUPPORT")}return i}const _m={getAdapter:hw,adapters:iu};function su(s){if(s.cancelToken&&s.cancelToken.throwIfRequested(),s.signal&&s.signal.aborted)throw new Ar(null,s)}function Mm(s){return su(s),s.headers=bn.from(s.headers),s.data=nu.call(s,s.transformRequest),["post","put","patch"].indexOf(s.method)!==-1&&s.headers.setContentType("application/x-www-form-urlencoded",!1),_m.getAdapter(s.adapter||To.adapter,s)(s).then(function(e){return su(s),e.data=nu.call(s,s.transformResponse,e),e.headers=bn.from(e.headers),e},function(e){return am(e)||(su(s),e&&e.response&&(e.response.data=nu.call(s,s.transformResponse,e.response),e.response.headers=bn.from(e.response.headers))),Promise.reject(e)})}const wm="1.13.2",rl={};["object","boolean","number","function","string","symbol"].forEach((s,e)=>{rl[s]=function(t){return typeof t===s||"a"+(e<1?"n ":" ")+s}});const Sm={};rl.transitional=function(s,e,t){function n(i,r){return"[Axios v"+wm+"] Transitional option '"+i+"'"+r+(t?". "+t:"")}return(i,r,o)=>{if(s===!1)throw new Ke(n(r," has been removed"+(e?" in "+e:"")),Ke.ERR_DEPRECATED);return e&&!Sm[r]&&(Sm[r]=!0,console.warn(n(r," has been deprecated since v"+e+" and will be removed in the near future"))),s?s(i,r,o):!0}},rl.spelling=function(s){return(e,t)=>(console.warn(`${t} is likely a misspelling of ${s}`),!0)};function uw(s,e,t){if(typeof s!="object")throw new Ke("options must be an object",Ke.ERR_BAD_OPTION_VALUE);const n=Object.keys(s);let i=n.length;for(;i-- >0;){const r=n[i],o=e[r];if(o){const a=s[r],l=a===void 0||o(a,r,s);if(l!==!0)throw new Ke("option "+r+" must be "+l,Ke.ERR_BAD_OPTION_VALUE);continue}if(t!==!0)throw new Ke("Unknown option "+r,Ke.ERR_BAD_OPTION)}}const ol={assertOptions:uw,validators:rl},ci=ol.validators;let _s=class{constructor(s){this.defaults=s||{},this.interceptors={request:new im,response:new im}}async request(s,e){try{return await this._request(s,e)}catch(t){if(t instanceof Error){let n={};Error.captureStackTrace?Error.captureStackTrace(n):n=new Error;const i=n.stack?n.stack.replace(/^.+\n/,""):"";try{t.stack?i&&!String(t.stack).endsWith(i.replace(/^.+\n.+\n/,""))&&(t.stack+=` `+i):t.stack=i}catch{}}throw t}}_request(s,e){typeof s=="string"?(e=e||{},e.url=s):e=s||{},e=ys(this.defaults,e);const{transitional:t,paramsSerializer:n,headers:i}=e;t!==void 0&&ol.assertOptions(t,{silentJSONParsing:ci.transitional(ci.boolean),forcedJSONParsing:ci.transitional(ci.boolean),clarifyTimeoutError:ci.transitional(ci.boolean)},!1),n!=null&&(re.isFunction(n)?e.paramsSerializer={serialize:n}:ol.assertOptions(n,{encode:ci.function,serialize:ci.function},!0)),e.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?e.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:e.allowAbsoluteUrls=!0),ol.assertOptions(e,{baseUrl:ci.spelling("baseURL"),withXsrfToken:ci.spelling("withXSRFToken")},!0),e.method=(e.method||this.defaults.method||"get").toLowerCase();let r=i&&re.merge(i.common,i[e.method]);i&&re.forEach(["delete","get","head","post","put","patch","common"],d=>{delete i[d]}),e.headers=bn.concat(r,i);const o=[];let a=!0;this.interceptors.request.forEach(function(d){typeof d.runWhen=="function"&&d.runWhen(e)===!1||(a=a&&d.synchronous,o.unshift(d.fulfilled,d.rejected))});const l=[];this.interceptors.response.forEach(function(d){l.push(d.fulfilled,d.rejected)});let c,h=0,u;if(!a){const d=[Mm.bind(this),void 0];for(d.unshift(...o),d.push(...l),u=d.length,c=Promise.resolve(e);h{if(!n._listeners)return;let r=n._listeners.length;for(;r-- >0;)n._listeners[r](i);n._listeners=null}),this.promise.then=i=>{let r;const o=new Promise(a=>{n.subscribe(a),r=a}).then(i);return o.cancel=function(){n.unsubscribe(r)},o},e(function(i,r,o){n.reason||(n.reason=new Ar(i,r,o),t(n.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=n=>{e.abort(n)};return this.subscribe(t),e.signal.unsubscribe=()=>this.unsubscribe(t),e.signal}static source(){let e;return{token:new Jg(function(t){e=t}),cancel:e}}};function fw(s){return function(e){return s.apply(null,e)}}function pw(s){return re.isObject(s)&&s.isAxiosError===!0}const ru={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(ru).forEach(([s,e])=>{ru[e]=s});function Em(s){const e=new _s(s),t=Hp(_s.prototype.request,e);return re.extend(t,_s.prototype,e,{allOwnKeys:!0}),re.extend(t,e,null,{allOwnKeys:!0}),t.create=function(n){return Em(ys(s,n))},t}const Rt=Em(To);Rt.Axios=_s,Rt.CanceledError=Ar,Rt.CancelToken=dw,Rt.isCancel=am,Rt.VERSION=wm,Rt.toFormData=tl,Rt.AxiosError=Ke,Rt.Cancel=Rt.CanceledError,Rt.all=function(s){return Promise.all(s)},Rt.spread=fw,Rt.isAxiosError=pw,Rt.mergeConfig=ys,Rt.AxiosHeaders=bn,Rt.formToJSON=s=>rm(re.isHTMLForm(s)?new FormData(s):s),Rt.getAdapter=_m.getAdapter,Rt.HttpStatusCode=ru,Rt.default=Rt;const{Axios:_C,AxiosError:MC,CanceledError:wC,isCancel:SC,CancelToken:EC,VERSION:TC,all:CC,Cancel:AC,isAxiosError:PC,spread:RC,toFormData:LC,AxiosHeaders:IC,HttpStatusCode:DC,formToJSON:BC,getAdapter:NC,mergeConfig:kC}=Rt;function Tm(s,e){var t;if(window.XMLHttpRequest?t=new XMLHttpRequest:window.ActiveXObject?t=new window.ActiveXObject:alert("请升级至最新版本的浏览器"),t!=null){let n=s;t.open("GET",n,!0),t.send(null),t.onreadystatechange=function(){t.readyState==4&&t.status==200&&(t.responseText.includes("",0)&&t.responseText.includes("",0)&&t.responseText.includes("",0)?e(null):e(t.responseText))},t.onloadend=function(){t.readyState==4&&t.status==404&&t.status==502&&e(null)}}}function mw(s,e){Rt({method:"get",responseType:"blob",url:s}).then(t=>{let n=new window.File([t.data],"zipFolder",{type:"zip"});zp.loadAsync(n).then(i=>{const r=new Map,o=[];for(let a in i.files){if(i.files[a].dir)continue;const l=i.file(i.files[a].name);if(l){const c=l.async("blob").then(h=>{const u=URL.createObjectURL(h);r.set("/"+i.files[a].name.replace("\\","/"),u)});o.push(c)}}Promise.all(o).then(()=>{e(r)}).catch(a=>{console.error("解压zip文件失败:",a),e(new Map)})}).catch(i=>{console.error("加载zip文件失败:",i),e(new Map)})}).catch(t=>{console.error("下载zip文件失败:",t),e(new Map)})}function Cm(s,e){Rt({method:"get",responseType:"blob",url:s}).then(n=>{let i=new window.File([n.data],"semantics",{type:"zip"});zp.loadAsync(i).then(r=>{for(let o in r.files)r.file(r.files[o].name).async("blob").then(a=>{t(a,"utf-8",function(l,c){e(c)})})})});function t(n,i,r){var o=new FileReader,a=new Blob([n]);o.onload=function(l){r(null,l.target.result)},o.onerror=function(l){r(l.error,null)},o.readAsText(a,i)}}const ou=new WeakMap;class gw extends fs{constructor(e){super(e),this.decoderPath="",this.decoderConfig={},this.decoderBinary=null,this.decoderPending=null,this.workerLimit=4,this.workerPool=[],this.workerNextTaskID=1,this.workerSourceURL="",this.defaultAttributeIDs={position:"POSITION",normal:"NORMAL",color:"COLOR",uv:"TEX_COORD"},this.defaultAttributeTypes={position:"Float32Array",normal:"Float32Array",color:"Float32Array",uv:"Float32Array"}}setDecoderPath(e){return this.decoderPath=e,this}setDecoderConfig(e){return this.decoderConfig=e,this}setWorkerLimit(e){return this.workerLimit=e,this}load(e,t,n,i){const r=new Da(this.manager);r.setPath(this.path),r.setResponseType("arraybuffer"),r.setRequestHeader(this.requestHeader),r.setWithCredentials(this.withCredentials),r.load(e,o=>{this.parse(o,t,i)},n,i)}parse(e,t,n=()=>{}){this.decodeDracoFile(e,t,null,null,At,n).catch(n)}decodeDracoFile(e,t,n,i,r=tn,o=()=>{}){const a={attributeIDs:n||this.defaultAttributeIDs,attributeTypes:i||this.defaultAttributeTypes,useUniqueIDs:!!n,vertexColorSpace:r};return this.decodeGeometry(e,a).then(t).catch(o)}decodeGeometry(e,t){const n=JSON.stringify(t);if(ou.has(e)){const l=ou.get(e);if(l.key===n)return l.promise;if(e.byteLength===0)throw new Error("THREE.DRACOLoader: Unable to re-decode a buffer with different settings. Buffer has already been transferred.")}let i;const r=this.workerNextTaskID++,o=e.byteLength,a=this._getWorker(r,o).then(l=>(i=l,new Promise((c,h)=>{i._callbacks[r]={resolve:c,reject:h},i.postMessage({type:"decode",id:r,taskConfig:t,buffer:e},[e])}))).then(l=>this._createGeometry(l.geometry));return a.catch(()=>!0).then(()=>{i&&r&&this._releaseTask(i,r)}),ou.set(e,{key:n,promise:a}),a}_createGeometry(e){const t=new bt;e.index&&t.setIndex(new vt(e.index.array,1));for(let n=0;n{n.load(e,i,void 0,r)})}preload(){return this._initDecoder(),this}_initDecoder(){if(this.decoderPending)return this.decoderPending;const e=typeof WebAssembly!="object"||this.decoderConfig.type==="js",t=[];return e?t.push(this._loadLibrary("draco_decoder.js","text")):(t.push(this._loadLibrary("draco_wasm_wrapper.js","text")),t.push(this._loadLibrary("draco_decoder.wasm","arraybuffer"))),this.decoderPending=Promise.all(t).then(n=>{const i=n[0];e||(this.decoderConfig.wasmBinary=n[1]);const r=xw.toString(),o=["/* draco decoder */",i,"","/* worker */",r.substring(r.indexOf("{")+1,r.lastIndexOf("}"))].join(` `);this.workerSourceURL=URL.createObjectURL(new Blob([o]))}),this.decoderPending}_getWorker(e,t){return this._initDecoder().then(()=>{if(this.workerPool.lengthr._taskLoad?-1:1});const n=this.workerPool[this.workerPool.length-1];return n._taskCosts[e]=t,n._taskLoad+=t,n})}_releaseTask(e,t){e._taskLoad-=e._taskCosts[t],delete e._callbacks[t],delete e._taskCosts[t]}debug(){console.log("Task load: ",this.workerPool.map(e=>e._taskLoad))}dispose(){for(let e=0;e{const u=h.draco,f=new u.Decoder;try{const d=t(u,f,new Int8Array(l),c),m=d.attributes.map(p=>p.array.buffer);d.index&&m.push(d.index.array.buffer),self.postMessage({type:"decode",id:a.id,geometry:d},m)}catch(d){console.error(d),self.postMessage({type:"error",id:a.id,error:d.message})}finally{u.destroy(f)}});break}};function t(o,a,l,c){const h=c.attributeIDs,u=c.attributeTypes;let f,d;const m=a.GetEncodedGeometryType(l);if(m===o.TRIANGULAR_MESH)f=new o.Mesh,d=a.DecodeArrayToMesh(l,l.byteLength,f);else if(m===o.POINT_CLOUD)f=new o.PointCloud,d=a.DecodeArrayToPointCloud(l,l.byteLength,f);else throw new Error("THREE.DRACOLoader: Unexpected geometry type.");if(!d.ok()||f.ptr===0)throw new Error("THREE.DRACOLoader: Decoding failed: "+d.error_msg());const p={index:null,attributes:[]};for(const x in h){const g=self[u[x]];let b,v;if(c.useUniqueIDs)v=h[x],b=a.GetAttributeByUniqueId(f,v);else{if(v=a.GetAttributeId(f,o[h[x]]),v===-1)continue;b=a.GetAttribute(f,v)}const y=i(o,a,f,x,g,b);x==="color"&&(y.vertexColorSpace=c.vertexColorSpace),p.attributes.push(y)}return m===o.TRIANGULAR_MESH&&(p.index=n(o,a,f)),o.destroy(f),p}function n(o,a,l){const c=l.num_faces()*3,h=c*4,u=o._malloc(h);a.GetTrianglesUInt32Array(l,h,u);const f=new Uint32Array(o.HEAPF32.buffer,u,c).slice();return o._free(u),{array:f,itemSize:1}}function i(o,a,l,c,h,u){const f=l.num_points(),d=u.num_components(),m=r(o,h),p=d*h.BYTES_PER_ELEMENT,x=Math.ceil(p/4)*4,g=x/h.BYTES_PER_ELEMENT,b=f*p,v=f*x,y=o._malloc(b);a.GetAttributeDataArrayForAllPoints(l,u,m,b,y);const M=new h(o.HEAPF32.buffer,y,b/h.BYTES_PER_ELEMENT);let E;if(p===x)E=M.slice();else{E=new h(v/h.BYTES_PER_ELEMENT);let C=0;for(let P=0,_=M.length;P<_;P++){for(let S=0;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))(Zi||{});function vw(s,e,t,n){let i=0,r=0,o=0,a=s.models.find(d=>d.url==t),l=e.circularMeps,c=e.rectMeps.filter(d=>d.type==="风管"),h=e.rectMeps.filter(d=>d.type==="桥架"),u=e.ellipseMeps,f=s.scene;if(new Xt,new bt,l&&l.length){let d=[],m=0;for(let p of l)p.color=p.color.split(",").map(x=>parseInt(x)/255),p.color=new He(p.color[0],p.color[1],p.color[2]),p.position={x:p.startPoint.X*.3048+i,y:p.startPoint.Z*.3048+r,z:-p.startPoint.Y*.3048+o},p.rotation={x:0,y:0,z:0},p.indexes=[[s.scene.children.length,m++,0,0]],a.nodesMap.set(Number(p.id),p),d.push(p);al("Circle",f,d,t)}if(c&&c.length){let d=[],m=0;for(let p of c)p.color=p.color.split(",").map(x=>parseInt(x)/255),p.color=new He(p.color[0],p.color[1],p.color[2]),p.position={x:p.startPoint.X*.3048+i,y:p.startPoint.Z*.3048+r,z:-p.startPoint.Y*.3048+o},p.rotation={x:0,y:0,z:0},p.indexes=[[s.scene.children.length,m++,0,0]],a.nodesMap.set(Number(p.id),p),d.push(p);al("Rect",f,d,t)}if(u&&u.length){let d=[],m=0;for(let p of u)p.color=p.color.split(",").map(x=>parseInt(x)/255),p.color=new He(p.color[0],p.color[1],p.color[2]),p.position={x:p.startPoint.X*.3048+i,y:p.startPoint.Z*.3048+r,z:-p.startPoint.Y*.3048+o},p.rotation={x:0,y:0,z:0},p.indexes=[[s.scene.children.length,m++,0,0]],a.nodesMap.set(Number(p.id),p),d.push(p);al("Ellipse",f,d,t)}if(h&&h.length){let d=[],m=0;for(let p of h)p.color=p.color.split(",").map(x=>parseInt(x)/255),p.color=new He(p.color[0],p.color[1],p.color[2]),p.position={x:p.startPoint.X*.3048+i,y:p.startPoint.Z*.3048+r,z:-p.startPoint.Y*.3048+o},p.rotation={x:0,y:0,z:0},p.indexes=[[s.scene.children.length,m++,0,0]],a.nodesMap.set(Number(p.id),p),d.push(p);al("Bridge",f,d,t)}}function al(s,e,t,n,i){let r,o,a={width:1,height:1,length:1,diameter:1,color:new He,position:{x:0,y:0,z:0},rotation:{x:0,y:0,z:0}};switch(s){case"Rect":o=ll("Rect",a);break;case"Bridge":o=ll("Bridge",a);break;case"Circle":o=ll("Circle",a);break;case"Ellipse":o=ll("Ellipse",a);break}o&&(r=new kt(o.geometry,o.material,t.length),r.url=n,e.add(r));let l=[];for(var c=0;cf.endPoint.Z?1:-1)*Math.PI*.5,f.base_x!=null){var h=new R(f.base_x.X,0,-f.base_x.Y);b=(h.clone().cross(new R(0,0,1)).y<=0?1:-1)*h.angleTo(new R(0,0,1))+Math.PI*.5}}else b=(m.clone().sub(d.clone()).cross(new R(0,0,1)).y>0?-1:1)*m.clone().sub(d.clone()).angleTo(new R(0,0,1)),g=(f.startPoint.Z>f.endPoint.Z?1:-1)*m.clone().sub(d.clone()).angleTo(x.clone().sub(p.clone()));let y=new De;const M=new wn(g,b,v,"YXZ");let E=y.clone().makeRotationFromEuler(M),C,P;s==="Circle"?(C=f.diameter,P=f.diameter):(C=f.width,P=f.height);let _=y.clone().makeScale(C,P,f.length);y.multiplyMatrices(E,_),y.setPosition(f.position.x,f.position.y,f.position.z),r.setMatrixAt(c,y.clone()),r.setColorAt(c,f.color),r.geometry.computeBoundingBox();let S=r.geometry.boundingBox.min.clone().applyMatrix4(y.clone()),I=r.geometry.boundingBox.max.clone().applyMatrix4(y.clone()),A=new R(Math.min(S.x,I.x),Math.min(S.y,I.y),Math.min(S.z,I.z)),B=new R(Math.max(S.x,I.x),Math.max(S.y,I.y),Math.max(S.z,I.z)),w=A.clone().add(B.clone()).multiplyScalar(.5),F={name:f.name,min:A,max:B,center:w,dbid:c,materialName:o.material.name},W=null,X=null;s==="Circle"&&(W={x:f.startPoint.X*.3048,y:f.startPoint.Z*.3048,z:-f.startPoint.Y*.3048},X={x:f.endPoint.X*.3048,y:f.endPoint.Z*.3048,z:-f.endPoint.Y*.3048},F.minC=W,F.maxC=X),r.ids||(r.ids=[]),r.matrixs||(r.matrixs=[]),r.matrixs.push(y.clone()),r.ids.push(Number(f.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();let u=[];u={geometry:r.geometry,matrix:r.matrix,position:r.position,rotation:r.rotation},r.meshs=u,r.instanceMatrix&&r.instanceMatrix.array&&(r.cloneInstanceMatrix=Array.from(r.instanceMatrix.array))}function ll(s,e,t){let n=new kf;switch(e.width=e.width*.3048,e.height=e.height*.3048,e.diameter=e.diameter*.3048,s){case"Rect":n.moveTo(-e.width/2,-e.height/2),n.lineTo(-e.width/2,e.height/2),n.lineTo(e.width/2,e.height/2),n.lineTo(e.width/2,-e.height/2),n.lineTo(-e.width/2,-e.height/2);break;case"Ellipse":n.moveTo(-e.width/2,-e.height/2),n.lineTo(-e.width/2,e.height/2),n.lineTo(e.width/2,e.height/2),n.lineTo(e.width/2,-e.height/2),n.lineTo(-e.width/2,-e.height/2);break;case"Bridge":n.moveTo(-e.width/2,-e.height/2),n.lineTo(-e.width/2,e.height/2),n.lineTo(-e.width/2+.01,e.height/2),n.lineTo(-e.width/2+.01,-e.height/2+.01),n.lineTo(e.width/2-.01,-e.height/2+.01),n.lineTo(e.width/2-.01,e.height/2),n.lineTo(e.width/2,e.height/2),n.lineTo(e.width/2,-e.height/2),n.lineTo(-e.width/2,-e.height/2);break;case"Circle":n.moveTo(0,0),n.absarc(0,0,e.diameter*.5,0,Math.PI*2,!1);break}const i={depth:e.length*.3048,bevelEnabled:!1};return r(n,i,e.color,e.position,e.rotation);function r(o,a,l,c,h){let u=new Ph(o,a),f=new ds({color:l,side:St}),d=new ht(u,f);return d.position.set(c.x,c.y,c.z),d.rotation._order="YXZ",d.rotation.set(h.x,h.y,h.z),d}}function Am(s,e=!1){const t=s[0].index!==null,n=new Set(Object.keys(s[0].attributes)),i=new Set(Object.keys(s[0].morphAttributes)),r={},o={},a=s[0].morphTargetsRelative,l=new bt;let c=0;for(let h=0;h=2.0 are supported."));return}const c=new Jw(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&&a[u]===void 0&&console.warn('THREE.GLTFLoader: Unknown extension "'+u+'".')}}c.setExtensions(o),c.setPlugins(a),c.parse(n,i)}parseAsync(e,t){const n=this;return new Promise(function(i,r){n.parse(e,t,i,r)})}}function yw(){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={}}}}const nt={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",EXT_MESH_GPU_INSTANCING:"EXT_mesh_gpu_instancing"};class _w{constructor(e){this.parser=e,this.name=nt.KHR_LIGHTS_PUNCTUAL,this.cache={refs:{},uses:{}}}_markDefs(){const e=this.parser,t=this.parser.json.nodes||[];for(let n=0,i=t.length;n=0)throw new Error("THREE.GLTFLoader: setKTX2Loader must be called before loading KTX2 textures");return null}return t.loadTextureImage(e,r.source,o)}}class Nw{constructor(e){this.parser=e,this.name=nt.EXT_TEXTURE_WEBP}loadTexture(e){const t=this.name,n=this.parser,i=n.json,r=i.textures[e];if(!r.extensions||!r.extensions[t])return null;const o=r.extensions[t],a=i.images[o.source];let l=n.textureLoader;if(a.uri){const c=n.options.manager.getHandler(a.uri);c!==null&&(l=c)}return n.loadTextureImage(e,o.source,l)}}class kw{constructor(e){this.parser=e,this.name=nt.EXT_TEXTURE_AVIF}loadTexture(e){const t=this.name,n=this.parser,i=n.json,r=i.textures[e];if(!r.extensions||!r.extensions[t])return null;const o=r.extensions[t],a=i.images[o.source];let l=n.textureLoader;if(a.uri){const c=n.options.manager.getHandler(a.uri);c!==null&&(l=c)}return n.loadTextureImage(e,o.source,l)}}class Uw{constructor(e){this.name=nt.EXT_MESHOPT_COMPRESSION,this.parser=e}loadBufferView(e){const t=this.parser.json,n=t.bufferViews[e];if(n.extensions&&n.extensions[this.name]){const i=n.extensions[this.name],r=this.parser.getDependency("buffer",i.buffer),o=this.parser.options.meshoptDecoder;if(!o||!o.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(a){const l=i.byteOffset||0,c=i.byteLength||0,h=i.count,u=i.byteStride,f=new Uint8Array(a,l,c);return o.decodeGltfBufferAsync?o.decodeGltfBufferAsync(h,u,f,i.mode,i.filter).then(function(d){return d.buffer}):o.ready.then(function(){const d=new ArrayBuffer(h*u);return o.decodeGltfBuffer(new Uint8Array(d),h,u,f,i.mode,i.filter),d})})}else return null}}class Ow{constructor(e){this.name=nt.EXT_MESH_GPU_INSTANCING,this.parser=e}createNodeMesh(e){const t=this.parser.json,n=t.nodes[e];if(!n.extensions||!n.extensions[this.name]||n.mesh===void 0)return null;const i=t.meshes[n.mesh];for(const l of i.primitives)if(l.mode!==Nn.TRIANGLES&&l.mode!==Nn.TRIANGLE_STRIP&&l.mode!==Nn.TRIANGLE_FAN&&l.mode!==void 0)return null;const r=n.extensions[this.name].attributes,o=[],a={};for(const l in r)o.push(this.parser.getDependency("accessor",r[l]).then(c=>(a[l]=c,a[l])));return o.length<1?null:(o.push(this.parser.createNodeMesh(e)),Promise.all(o).then(l=>{const c=l.pop(),h=c.isGroup?c.children:[c],u=l[0].count,f=[];for(const d of h){const m=new De,p=new R,x=new Ln,g=new R(1,1,1),b=new kt(d.geometry,d.material,u);for(let v=0;v0||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 Kw=new De;class Jw{constructor(e={},t={}){this.json=e,this.extensions={},this.plugins={},this.options=t,this.cache=new yw,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 n=!1,i=-1,r=!1,o=-1;if(typeof navigator<"u"){const a=navigator.userAgent;n=/^((?!chrome|android).)*safari/i.test(a)===!0;const l=a.match(/Version\/(\d+)/);i=n&&l?parseInt(l[1],10):-1,r=a.indexOf("Firefox")>-1,o=r?a.match(/Firefox\/([0-9]+)\./)[1]:-1}typeof createImageBitmap>"u"||n&&i<17||r&&o<98?this.textureLoader=new qf(this.options.manager):this.textureLoader=new Ov(this.options.manager),this.textureLoader.setCrossOrigin(this.options.crossOrigin),this.textureLoader.setRequestHeader(this.options.requestHeader),this.fileLoader=new Da(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 n=this,i=this.json,r=this.extensions;this.cache.removeAll(),this.nodeCache={},this._invokeAll(function(o){return o._markDefs&&o._markDefs()}),Promise.all(this._invokeAll(function(o){return o.beforeRoot&&o.beforeRoot()})).then(function(){return Promise.all([n.getDependencies("scene"),n.getDependencies("animation"),n.getDependencies("camera")])}).then(function(o){const a={scene:o[0][i.scene||0],scenes:o[0],animations:o[1],cameras:o[2],asset:i.asset,parser:n,userData:{}};return Ms(r,a,i),hi(a,i),Promise.all(n._invokeAll(function(l){return l.afterRoot&&l.afterRoot(a)})).then(function(){for(const l of a.scenes)l.updateMatrixWorld();e(a)})}).catch(t)}_markDefs(){const e=this.json.nodes||[],t=this.json.skins||[],n=this.json.meshes||[];for(let i=0,r=t.length;i{const l=this.associations.get(o);l!=null&&this.associations.set(a,l);for(const[c,h]of o.children.entries())r(h,a.children[c])};return r(n,i),i.name+="_instance_"+e.uses[t]++,i}_invokeOne(e){const t=Object.values(this.plugins);t.push(this);for(let n=0;n=2&&x.setY(_,E[C*l+1]),l>=3&&x.setZ(_,E[C*l+2]),l>=4&&x.setW(_,E[C*l+3]),l>=5)throw new Error("THREE.GLTFLoader: Unsupported itemSize in sparse BufferAttribute.")}x.normalized=m}return x})}loadTexture(e){const t=this.json,n=this.options,i=t.textures[e].source,r=t.images[i];let o=this.textureLoader;if(r.uri){const a=n.manager.getHandler(r.uri);a!==null&&(o=a)}return this.loadTextureImage(e,i,o)}loadTextureImage(e,t,n){const i=this,r=this.json,o=r.textures[e],a=r.images[t],l=(a.uri||a.bufferView)+":"+o.sampler;if(this.textureCache[l])return this.textureCache[l];const c=this.loadImageSource(t,n).then(function(h){h.flipY=!1,h.name=o.name||a.name||"",h.name===""&&typeof a.uri=="string"&&a.uri.startsWith("data:image/")===!1&&(h.name=a.uri);const u=(r.samplers||{})[o.sampler]||{};return h.magFilter=Bm[u.magFilter]||Kt,h.minFilter=Bm[u.minFilter]||gi,h.wrapS=Nm[u.wrapS]||ni,h.wrapT=Nm[u.wrapT]||ni,h.generateMipmaps=!h.isCompressedTexture&&h.minFilter!==$t&&h.minFilter!==Kt,i.associations.set(h,{textures:e}),h}).catch(function(){return null});return this.textureCache[l]=c,c}loadImageSource(e,t){const n=this,i=this.json,r=this.options;if(this.sourceCache[e]!==void 0)return this.sourceCache[e].then(u=>u.clone());const o=i.images[e],a=self.URL||self.webkitURL;let l=o.uri||"",c=!1;if(o.bufferView!==void 0)l=n.getDependency("bufferView",o.bufferView).then(function(u){c=!0;const f=new Blob([u],{type:o.mimeType});return l=a.createObjectURL(f),l});else if(o.uri===void 0)throw new Error("THREE.GLTFLoader: Image "+e+" is missing URI and bufferView");const h=Promise.resolve(l).then(function(u){return new Promise(function(f,d){let m=f;t.isImageBitmapLoader===!0&&(m=function(p){const x=new Ft(p);x.needsUpdate=!0,f(x)}),t.load(yo.resolveURL(u,r.path),m,void 0,d)})}).then(function(u){return c===!0&&a.revokeObjectURL(l),hi(u,o),u.userData.mimeType=o.mimeType||$w(o.uri),u}).catch(function(u){throw console.error("THREE.GLTFLoader: Couldn't load texture",l),u});return this.sourceCache[e]=h,h}assignTexture(e,t,n,i){const r=this;return this.getDependency("texture",n.index).then(function(o){if(!o)return null;if(n.texCoord!==void 0&&n.texCoord>0&&(o=o.clone(),o.channel=n.texCoord),r.extensions[nt.KHR_TEXTURE_TRANSFORM]){const a=n.extensions!==void 0?n.extensions[nt.KHR_TEXTURE_TRANSFORM]:void 0;if(a){const l=r.associations.get(o);o=r.extensions[nt.KHR_TEXTURE_TRANSFORM].extendTexture(o,a),r.associations.set(o,l)}}return i!==void 0&&(o.colorSpace=i),e[t]=o,o})}assignFinalMaterial(e){const t=e.geometry;let n=e.material;const i=t.attributes.tangent===void 0,r=t.attributes.color!==void 0,o=t.attributes.normal===void 0;if(e.isPoints){const a="PointsMaterial:"+n.uuid;let l=this.cache.get(a);l||(l=new Ef,Sn.prototype.copy.call(l,n),l.color.copy(n.color),l.map=n.map,l.sizeAttenuation=!1,this.cache.add(a,l)),n=l}else if(e.isLine){const a="LineBasicMaterial:"+n.uuid;let l=this.cache.get(a);l||(l=new lo,Sn.prototype.copy.call(l,n),l.color.copy(n.color),l.map=n.map,this.cache.add(a,l)),n=l}if(i||r||o){let a="ClonedMaterial:"+n.uuid+":";i&&(a+="derivative-tangents:"),r&&(a+="vertex-colors:"),o&&(a+="flat-shading:");let l=this.cache.get(a);l||(l=n.clone(),r&&(l.vertexColors=!0),o&&(l.flatShading=!0),i&&(l.normalScale&&(l.normalScale.y*=-1),l.clearcoatNormalScale&&(l.clearcoatNormalScale.y*=-1)),this.cache.add(a,l),this.associations.set(l,this.associations.get(n))),n=l}e.material=n}getMaterialType(){return ds}loadMaterial(e){const t=this,n=this.json,i=this.extensions,r=n.materials[e];let o;const a={},l=r.extensions||{},c=[];if(l[nt.KHR_MATERIALS_UNLIT]){const u=i[nt.KHR_MATERIALS_UNLIT];o=u.getMaterialType(),c.push(u.extendParams(a,r,t))}else{const u=r.pbrMetallicRoughness||{};if(a.color=new He(1,1,1),a.opacity=1,Array.isArray(u.baseColorFactor)){const f=u.baseColorFactor;a.color.setRGB(f[0],f[1],f[2],tn),a.opacity=f[3]}u.baseColorTexture!==void 0&&c.push(t.assignTexture(a,"map",u.baseColorTexture,At)),a.metalness=u.metallicFactor!==void 0?u.metallicFactor:1,a.roughness=u.roughnessFactor!==void 0?u.roughnessFactor:1,u.metallicRoughnessTexture!==void 0&&(c.push(t.assignTexture(a,"metalnessMap",u.metallicRoughnessTexture)),c.push(t.assignTexture(a,"roughnessMap",u.metallicRoughnessTexture))),o=this._invokeOne(function(f){return f.getMaterialType&&f.getMaterialType(e)}),c.push(Promise.all(this._invokeAll(function(f){return f.extendMaterialParams&&f.extendMaterialParams(e,a)})))}r.doubleSided===!0&&(a.side=St);const h=r.alphaMode||cu.OPAQUE;if(h===cu.BLEND?(a.transparent=!0,a.depthWrite=!1):(a.transparent=!1,h===cu.MASK&&(a.alphaTest=r.alphaCutoff!==void 0?r.alphaCutoff:.5)),r.normalTexture!==void 0&&o!==Xt&&(c.push(t.assignTexture(a,"normalMap",r.normalTexture)),a.normalScale=new ue(1,1),r.normalTexture.scale!==void 0)){const u=r.normalTexture.scale;a.normalScale.set(u,u)}if(r.occlusionTexture!==void 0&&o!==Xt&&(c.push(t.assignTexture(a,"aoMap",r.occlusionTexture)),r.occlusionTexture.strength!==void 0&&(a.aoMapIntensity=r.occlusionTexture.strength)),r.emissiveFactor!==void 0&&o!==Xt){const u=r.emissiveFactor;a.emissive=new He().setRGB(u[0],u[1],u[2],tn)}return r.emissiveTexture!==void 0&&o!==Xt&&c.push(t.assignTexture(a,"emissiveMap",r.emissiveTexture,At)),Promise.all(c).then(function(){const u=new o(a);return r.name&&(u.name=r.name),hi(u,r),t.associations.set(u,{materials:e}),r.extensions&&Ms(i,u,r),u})}createUniqueName(e){const t=ut.sanitizeNodeName(e||"");return t in this.nodeNamesUsed?t+"_"+ ++this.nodeNamesUsed[t]:(this.nodeNamesUsed[t]=0,t)}loadGeometries(e){const t=this,n=this.extensions,i=this.primitiveCache;function r(a){return n[nt.KHR_DRACO_MESH_COMPRESSION].decodePrimitive(a,t).then(function(l){return km(l,a,t)})}const o=[];for(let a=0,l=e.length;a0&&Zw(g,r),g.name=t.createUniqueName(r.name||"mesh_"+e),hi(g,r),x.extensions&&Ms(i,g,x),t.assignFinalMaterial(g),u.push(g)}for(let d=0,m=u.length;d1?h=new Dn:c.length===1?h=c[0]:h=new wt,h!==c[0])for(let u=0,f=c.length;u1){const u=i.associations.get(h);i.associations.set(h,{...u})}return i.associations.get(h).nodes=e,h}),this.nodeCache[e]}loadScene(e){const t=this.extensions,n=this.json.scenes[e],i=this,r=new Dn;n.name&&(r.name=i.createUniqueName(n.name)),hi(r,n),n.extensions&&Ms(t,r,n);const o=n.nodes||[],a=[];for(let l=0,c=o.length;l{const u=new Map;for(const[f,d]of i.associations)(f instanceof Sn||f instanceof Ft)&&u.set(f,d);return h.traverse(f=>{const d=i.associations.get(f);d!=null&&u.set(f,d)}),u};return i.associations=c(r),r})}_createAnimationTracks(e,t,n,i,r){const o=[],a=e.name?e.name:e.uuid,l=[];Yi[r.path]===Yi.weights?e.traverse(function(f){f.morphTargetInfluences&&l.push(f.name?f.name:f.uuid)}):l.push(a);let c;switch(Yi[r.path]){case Yi.weights:c=gr;break;case Yi.rotation:c=xr;break;case Yi.translation:case Yi.scale:c=br;break;default:switch(n.itemSize){case 1:c=gr;break;case 2:case 3:default:c=br;break}break}const h=i.interpolation!==void 0?Xw[i.interpolation]:qr,u=this._getArrayFromAccessor(n);for(let f=0,d=l.length;f{let r=JSON.parse(i);s.engineStatus.models.push({type:"light",info:r,name:r.baseInfo.name,status:"loading",url:e,elements:new Map}),s.models==null&&(s.models=[]),s.models.push({url:e,nodesMap:new Map,boundingBox:{min:new R(r.baseInfo.min.X*.3048,r.baseInfo.min.Z*.3048,-r.baseInfo.min.Y*.3048),max:new R(r.baseInfo.max.X*.3048,r.baseInfo.max.Z*.3048,-r.baseInfo.max.Y*.3048)}}),s.events.trigger(Zi.EngineFree,null)})}function t3(s){s.engineStatus.models.forEach(e=>{e.loadStatus==null&&(e.loadStatus={mep:!1,instance:!1,normal:!1}),e.status==="loading"&&e.type==="light"&&(e.loadStatus.modelMep!=!0&&(e.loadStatus.modelMep=!0,vw(s,e.info.modelMep,e.url)),e.loadStatus.normal!=!0&&n3(s,e))})}function n3(s,e){if(s.camera.position,e.size,e.info==null||e.info.lods==null)return;e.info.lods.forEach(n=>{if(n.status!=!0)if(n.glbs==null)console.log("加载GLB............."),n.glbs={},mw(e.url+n.path,i=>{Tm(i.get("/nodes.json"),r=>{let o=JSON.parse(r);s.models.find(c=>c.url==e.url).nodesMap==null&&(s.models.find(c=>c.url==e.url).nodesMap=new Map);let a=s.models.find(c=>c.url==e.url).nodesMap,l=0;for(let c in o){o[c].forEach(f=>{f.glb=c,a.has(f.id)==!1?a.set(f.id,{infos:[f]}):a.get(f.id).infos.push(f)});let h=new bw;const u=new gw;u.setDecoderPath("/draco/"),u.preload(),h.setDRACOLoader(u),h.load(i.get(c+".glb"),f=>{n.glbs[c]=f.scene.children,l++,l==Object.keys(o).length&&s.engineStatus.isFree&&(s.events.trigger(Zi.EngineFree,null),s.viewCube.CameraGoHome())})}Tm(i.get("/instances.json"),c=>{let h=JSON.parse(c);s.models.find(u=>u.url==e.url).instanceNodes=h})})});else{console.log("加载模型.............");let i=t(e,n,n.octreeBox),r=[],o=s.models.find(l=>l.url==e.url);i.forEach(l=>{o.nodesMap.has(l)&&o.nodesMap.get(l).infos.forEach(c=>{let h=n.glbs[c.glb][c.mesh];if(h!=null&&h.geometry!=null&&h.material!=null){let u=new De;u.elements=c.matrix;let f=new ht(h.geometry.clone().applyMatrix4(u),h.material),d=new gt().setFromObject(f);c.box=d,c.mesh=f,f.name=l,f.glb=c.glb,f.url=e.url,h.geometry.attributes.position!=null&&r.push(f)}})}),console.log("加载模型数量",r.length),i3(e.url,s,r);let a=o.instanceNodes;for(let l in a)(a[l].isLoaded==null||a[l].isLoaded==!1)&&(a[l].isLoaded=!0,a[l].forEach(c=>{let h=n.glbs[l][c.mesh];s3(e.url,c.mesh,s,h,c.children)}))}});function t(n,i,r){let o=[];if(r.status!=!0){if(!s.engineStatus.isFree)return o;let a=new R(r.min.X,r.min.Z,-r.min.Y),l=new R(r.max.X,r.max.Z,-r.max.Y);l.distanceTo(a);let c=s.camera.position,h=new R(a.x+l.x/2,a.y+l.y/2,a.z+l.z/2);c.distanceTo(h),r.elements.forEach(u=>{o.push(u)}),r.children.forEach(u=>{o.push(...t(n,i,u))}),r.children.findIndex(u=>u.status!=!0)==-1&&(r.status=!0),r.children.length==0&&(r.status=!0)}return o}}function i3(s,e,t){let n=[];t.forEach(i=>{n.findIndex(o=>o.glb==i.glb)==-1?n.push({glb:i.glb,meshes:[i],currentIndex:i.geometry.index.count,indexes:new Map}):(n.find(o=>o.glb==i.glb).meshes.push(i),n.find(o=>o.glb==i.glb).currentIndex+=i.geometry.index.count);let r=n.find(o=>o.glb==i.glb);r.indexes.set(Number(i.name),[r.currentIndex-i.geometry.index.count,r.currentIndex])}),n.forEach(i=>{let r=e.scene.children.find(o=>o instanceof ht&&o.url==s&&o.glb==i.glb);if(r!=null)r.castShadow=!0,r.receiveShadow=!0;else{let o=new bt,a=r3(i.meshes[0].material);o=Am(i.meshes.map(h=>h.geometry),!1);let l=new ht(o,a);l.castShadow=!0,l.receiveShadow=!0,e.scene.add(l),l.index=e.scene.children.length-1,l.url=s,l.glb=i.glb,l.indexes=i.indexes,l.materialClone=a,l.geometrys=i.meshes.map(h=>h.geometry);let c=e.models.find(h=>h.url==s);if(c!=null){let h=0;i.indexes.forEach(u=>{c.nodesMap.get(Number(i.meshes[h].name)).indexes==null&&(c.nodesMap.get(Number(i.meshes[h].name)).indexes=[]),c.nodesMap.get(Number(i.meshes[h].name)).indexes.push([l.index,h++,u[0],u[1]])})}}})}function s3(s,e,t,n,i){if(n==null)return;let r=new kt(n.geometry,n.material,i.length);t.scene.add(r);const o=new Float32Array(i.length*3);for(let a=0;ah.url==s).nodesMap.has(l.id)?(t.models.find(h=>h.url==s).nodesMap.get(l.id).indexes==null&&(t.models.find(h=>h.url==s).nodesMap.get(l.id).indexes=[]),t.models.find(h=>h.url==s).nodesMap.get(l.id).indexes.push([t.scene.children.length-1,a,0,0])):t.models.find(h=>h.url==s).nodesMap.set(l.id,{instance:!0,info:l,indexes:[[t.scene.children.length-1,a,0,0]]})}r.index=t.scene.children.length-1,r.materialClone=n.material,r.url=s,r.glb=n.glb,r.ids=i.map(a=>a.id)}function r3(s){return s.map!=null&&(s.map.colorSpace=At,s.map.needsUpdate=!0),s.shadowSide=Pn,s.side=s.side,s}class o3{engine;constructor(e){this.engine=e}async loadModels(e,t){for(const i of e)n(i)==="light"&&e3(this.engine,i);function n(i){const r=i.split(".").pop();return r==="glb"||r==="gltf"?"gltf":"light"}}}class a3{engine;isFree;highlightModels;hideModels;translucentModels;models;constructor(e){this.engine=e,this.isFree=!0,this.highlightModels=[],this.hideModels=[],this.translucentModels=[],this.models=[]}init(){this.engine.events.on(Zi.EngineFree,()=>{this.updateFree(!0),console.log("引擎空闲"),t3(this.engine)}),this.engine.events.on(Zi.EngineBusy,()=>{this.updateFree(!1),console.log("引擎繁忙")})}updateFree(e){this.isFree=e}closeAllFunction=()=>{}}class l3{listeners=new Map;debugMode=!1;setDebugMode(e){this.debugMode=e}on(e,t){const n=String(e);this.listeners.has(n)||this.listeners.set(n,[]),this.listeners.get(n).push(t),this.debugMode&&console.debug(`[EventModule] 注册事件监听器: ${n}, 当前监听器数量: ${this.listeners.get(n).length}`)}off(e,t){const n=String(e);if(!this.listeners.has(n)){this.debugMode&&console.warn(`[EventModule] 尝试移除不存在的事件监听器: ${n}`);return}const i=this.listeners.get(n),r=i.indexOf(t);r!==-1?(i.splice(r,1),this.debugMode&&console.debug(`[EventModule] 移除事件监听器: ${n}, 剩余监听器数量: ${i.length}`)):this.debugMode&&console.warn(`[EventModule] 尝试移除的回调函数未找到: ${n}`)}trigger(e,t){const n=String(e);if(!this.listeners.has(n)){this.debugMode&&(console.warn(`[EventModule] 触发事件但未找到监听器: ${n}`),console.debug("[EventModule] 当前已注册的事件类型:",Array.from(this.listeners.keys())));return}const i=this.listeners.get(n);this.debugMode&&console.debug(`[EventModule] 触发事件: ${n}, 监听器数量: ${i.length}`,t),i.forEach((r,o)=>{try{r(t)}catch(a){console.error(`[EventModule] 事件监听器执行错误 [${n}] #${o}:`,a)}})}}class c3{engine;constructor(e){this.engine=e}init(){const e=new Ti(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 n=new Ti(16777215,2);this.engine.scene.add(e),this.engine.scene.add(n),this.engine.scene.dirLight=n;const i=new Na(16777215,1);this.engine.scene.add(i)}}var Gt=(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))(Gt||{});class h3{engine;behavior;isCtrlDown=!1;highlightedInstances=[];highlightColor=new He(43775);constructor(e){this.engine=e}init(){this.behavior=this.engine.handelBehaved,this.behavior.init(this)}active(){this.behavior.active()}disActive(){this.behavior.disActive()}handelKeyCtrlUp(){this.isCtrlDown=!1}handelKeyCtrlDown(){this.isCtrlDown=!0}hoverOldId=null;handleMouseMove(e){if(!this.engine.engineStatus.isFree){this.engine.hoverHighLight.clearHighlight();return}let t=this.handleMouseClickInstance(e.raycaster);if(t.length>0&&(e.catch==null||t[0].distancel.url==n.url).nodesMap.get(i),o=new Map;r?.indexes.forEach(l=>{this.engine.scene.children[l[0]]instanceof kt&&(o.has(l[0])?o.get(l[0])?.push(l[1]):o.set(l[0],[l[1]]))});let a=[];if(o.forEach((l,c)=>{let h=this.engine.scene.children[c];l.forEach(u=>{let f=h.geometry.clone();f.applyMatrix4(n.matrixs[u]),a.push(new ht(f,h.material))})}),this.hoverOldId==i)return;this.hoverOldId=i,this.engine.hoverHighLight.clearHighlight(),this.engine.hoverHighLight.hightMesh(a)}else if(e.catch!=null&&(t.length==0||t[0].distance>e.catch.distance)){const n=e.catch;n.object,this.engine.events.trigger(Gt.Click,n);let i=n.object,r=i.name,o=this.engine.models.find(a=>a.url===i.url).nodesMap.get(r).infos.map(a=>a.mesh);if(this.hoverOldId==r)return;this.hoverOldId=r,this.engine.hoverHighLight.clearHighlight(),this.engine.hoverHighLight.hightMesh(o)}else this.engine.hoverHighLight.clearHighlight()}handleMouseClick(e){let t=this.handleMouseClickInstance(e.raycaster);if(t.length>0&&(e.catch==null||t[0].distancee.catch.distance)){const n=e.catch;n.object,this.engine.events.trigger(Gt.Click,n);let i=n.object;this.isCtrlDown||this.engine.modelToolModule.unhighlightAllModels(),console.log([{url:i.url,ids:[i.name]}]),this.engine.controlModule.orbitControls.origin.set(n.point.x,n.point.y,n.point.z),this.engine.modelToolModule.highlightModel([{url:i.url,ids:[i.name]}])}e.catch==null&&t.length==0&&this.engine.modelToolModule.unhighlightAllModels()}handleMouseDoubleClick(e){if(e.catch){const n=e.catch;n.object,this.engine.events.trigger(Gt.Click,n);let i=n.object,r=this.engine.models.find(a=>a.url===i.url).nodesMap.get(i.name).infos.map(a=>a.box),o=t(r);this.engine.viewCube.zoomToModel(o)}function t(n){let i=new R(1e8,1e9,1e10),r=new R(-1e8,-1e9,-1e10);return n.forEach(o=>{o.min.xr.x&&(r.x=o.max.x),o.max.y>r.y&&(r.y=o.max.y),o.max.z>r.z&&(r.z=o.max.z)}),new gt(i,r)}}handleMouseClickInstance(e){return e.intersectObjects(this.engine.scene.children.filter(t=>t instanceof kt),!0)}}class u3{engine;highlightMaterial;hideMaterial;translucentMaterial;cloneModels=new Map;clonetranslucentModels=new Map;constructor(e){this.engine=e,this.highlightMaterial=new Xt({color:43775,depthTest:!1,depthWrite:!1,transparent:!0,opacity:.5,side:St}),this.hideMaterial=new Xt({color:0,transparent:!0,opacity:0,side:St}),this.translucentMaterial=new Xt({color:16777215,transparent:!0,opacity:.05,side:St}),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 kt)return;let t=e.materialClone.clone(),n=Am(e.geometrys,!0);n.groups.forEach(i=>{i.materialIndex=0}),e.geometry=n,e.material=[t,this.highlightMaterial,this.translucentMaterial],e.needsUpdate=!0,e.isSplit=!0}un_split_merge_model(e){}highlightModel(e){e.forEach(t=>{let n=new Map;t.ids.forEach(i=>{this.engine.models.find(o=>o.url==t.url).nodesMap.get(i)?.indexes.forEach(o=>{this.engine.scene.children[o[0]]instanceof kt?n.has(o[0])?n.get(o[0])?.push(o[1]):n.set(o[0],[o[1]]):(console.log(this.engine.scene.children[o[0]].materialClone.color),this.split_merge_model(this.engine.scene.children[o[0]]),this.engine.scene.children[o[0]].geometry.groups[o[1]].materialIndex=1)})}),d3(n,this.engine,this.cloneModels),this.engine.engineStatus.highlightModels.push(t)})}unhighlightModel(e){e.forEach(t=>{let n=new Map;t.ids.forEach(i=>{this.engine.models.find(o=>o.url==t.url).nodesMap.get(i)?.indexes.forEach(o=>{this.engine.scene.children[o[0]]instanceof kt?n.has(o[0])?n.get(o[0])?.push(o[1]):n.set(o[0],[o[1]]):this.engine.scene.children[o[0]].geometry.groups[o[1]].materialIndex=0})}),Um(n,this.engine,this.cloneModels)})}unhighlightAllModels(e=!0){this.engine.engineStatus.highlightModels.forEach(t=>{this.unhighlightModel([t])}),e&&(this.engine.engineStatus.highlightModels=[])}hideModel(e){e.forEach(t=>{let n=new Map;t.ids.forEach(r=>{let o=this.engine.models.find(a=>a.url==t.url).nodesMap.get(r);this.engine.modelEdge.hideModelEdge(t.url,r),o.indexes.forEach(a=>{const l=this.engine.scene.children[a[0]];l instanceof kt?n.has(a[0])?n.get(a[0])?.push(a[1]):n.set(a[0],[a[1]]):(this.split_merge_model(this.engine.scene.children[a[0]]),l.geometry.groups[a[1]].materialIndex=-1,l.geometry.groups[a[1]].visible=!1)})}),n.size>0&&p3(n,this.engine,this.cloneModels);let i=this.engine.engineStatus.hideModels.find(r=>r.url==t.url);i!=null?i.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 n=new Map;t.ids.forEach(r=>{let o=this.engine.models.find(a=>a.url==t.url).nodesMap.get(r);this.engine.modelEdge.showModelEdge(t.url,r),o.indexes.forEach(a=>{const l=this.engine.scene.children[a[0]];l instanceof kt?n.has(a[0])?n.get(a[0])?.push(a[1]):n.set(a[0],[a[1]]):(l.geometry.groups[a[1]].materialIndex=0,l.geometry.groups[a[1]].visible=!0)})}),n.size>0&&Om(n,this.engine);let i=this.engine.engineStatus.hideModels.find(r=>r.url==t.url);i&&(t.ids.forEach(r=>{const o=i.ids.indexOf(r);o!==-1&&i.ids.splice(o,1)}),i.ids.length===0&&(this.engine.engineStatus.hideModels=this.engine.engineStatus.hideModels.filter(r=>r!==i)))})}isolateModel(e){let t=[];this.engine.models.forEach(n=>{let i={url:n.url,ids:[]},r=e.find(o=>o.url==n.url);for(let o of n.nodesMap)r==null?i.ids.push(o[0]):r.ids.includes(o[0])||i.ids.push(o[0]);t.push(i)}),this.unhighlightAllModels(),this.hideModel(t)}translucentOtherModel(e){let t=[];this.engine.models.forEach(n=>{let i={url:n.url,ids:[]},r=e.find(o=>o.url==n.url);for(let o of n.nodesMap)r==null?i.ids.push(o[0]):r.ids.includes(o[0])||i.ids.push(o[0]);t.push(i)}),this.unhighlightAllModels(),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.unhighlightModel(e),e.forEach(t=>{let n=new Map;t.ids.forEach(r=>{let o=this.engine.models.find(a=>a.url==t.url).nodesMap.get(r);o&&o.indexes.forEach(a=>{const l=this.engine.scene.children[a[0]];l instanceof kt?n.has(a[0])?n.get(a[0])?.push(a[1]):n.set(a[0],[a[1]]):(this.split_merge_model(this.engine.scene.children[a[0]]),l.geometry.groups[a[1]].materialIndex=2)})}),f3(n,this.engine,this.clonetranslucentModels);let i=this.engine.engineStatus.translucentModels.find(r=>r.url==t.url);i!=null?i.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(n=>{let i=this.engine.models.find(r=>r.url==e.url).nodesMap.get(n);i&&i.indexes.forEach(r=>{const o=this.engine.scene.children[r[0]];o instanceof kt?t.has(r[0])?t.get(r[0])?.push(r[1]):t.set(r[0],[r[1]]):(this.split_merge_model(this.engine.scene.children[r[0]]),o.geometry.groups[r[1]].materialIndex=0)})}),t.size>0&&Om(t,this.engine),Um(t,this.engine,this.clonetranslucentModels)}),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],n=this.engine.modelMapperBatch.getModelMapper(t.url,t.ids[0]);this.engine.modelMapperBatch.getModelsWithLevelType(n.levelName,n.typeName,i=>{this.engine.modelToolModule.highlightModel(i)})}batchSelectSameLevelModel(e){if(e.length==0)return;let t=e[0],n=this.engine.modelMapperBatch.getModelMapper(t.url,t.ids[0]);this.engine.modelMapperBatch.getModelsWithLevel(n.levelName,i=>{this.engine.modelToolModule.highlightModel(i)})}batchSelectSameTypeModel(e){if(e.length==0)return;let t=e[0],n=this.engine.modelMapperBatch.getModelMapper(t.url,t.ids[0]);this.engine.modelMapperBatch.getModelsWithType(n.typeName,i=>{this.engine.modelToolModule.highlightModel(i)})}}function d3(s,e,t){s.forEach((n,i)=>{const r=e.scene.children[i];if(!(r instanceof kt))return;const o=r.geometry,a=new Xt({color:43775,depthTest:!1,depthWrite:!1,transparent:!0,opacity:.5,side:St}),l=new kt(o,a,n.length);l.name="highlightModel";const c=new Map,h=new De,u=new De;u.makeScale(0,0,0),n.forEach((f,d)=>{r.getMatrixAt(f,h),c.set(f,h.clone()),r.setMatrixAt(f,u),l.setMatrixAt(d,h)}),r.instanceMatrix.needsUpdate=!0,l.instanceMatrix.needsUpdate=!0,e.scene.add(l),t.set(i,{cloneModel:l,originalMatrices:c})})}function Um(s,e,t){s.forEach((n,i)=>{const r=t.get(i);if(!r)return;const o=e.scene.children[i];o instanceof kt&&(n.forEach(a=>{const l=r.originalMatrices.get(a);l&&o.setMatrixAt(a,l)}),o.instanceMatrix.needsUpdate=!0,r.cloneModel.parent&&r.cloneModel.parent.remove(r.cloneModel),r.cloneModel.geometry,r.cloneModel.material&&(Array.isArray(r.cloneModel.material)?r.cloneModel.material.forEach(a=>a.dispose()):r.cloneModel.material.dispose()),t.delete(i))})}function f3(s,e,t){s.forEach((n,i)=>{const r=e.scene.children[i];if(!(r instanceof kt))return;const o=r.geometry,a=new Xt({color:16777215,transparent:!0,opacity:.05,side:St}),l=new kt(o,a,n.length);l.name="translucentModel";const c=new Map,h=new De,u=new De;u.makeScale(0,0,0),n.forEach((f,d)=>{r.getMatrixAt(f,h),c.set(f,h.clone()),r.setMatrixAt(f,u),l.setMatrixAt(d,h)}),r.instanceMatrix.needsUpdate=!0,l.instanceMatrix.needsUpdate=!0,e.scene.add(l),t.set(i,{cloneModel:l,originalMatrices:c})})}function p3(s,e,t){e.scene.children.forEach(n=>{n.name=="highlightModel"&&n.parent.remove(n)}),s.forEach((n,i)=>{const r=e.scene.children[i];if(!(r instanceof kt))return;const o=new Map,a=new De,l=new De;l.makeScale(0,0,0),n.forEach((c,h)=>{r.getMatrixAt(c,a),o.set(c,a.clone()),r.setMatrixAt(c,l)}),r.instanceMatrix.needsUpdate=!0,t.set(i,{cloneModel:null,originalMatrices:o})})}function Om(s,e){s.forEach((t,n)=>{const i=e.scene.children[n];i instanceof kt&&(t.forEach(r=>{const o=i.matrixs[r];o&&i.setMatrixAt(r,o)}),i.instanceMatrix.needsUpdate=!0)})}class kn{constructor(e,t,n){this.camera=e,this.renderer=t,this.scene=n,this.raycaster=new ms}raycaster;worldToScreenNormalized(e){const t=e.clone();return t.project(this.camera),new ue(t.x,t.y)}worldToScreen(e){const t=this.worldToScreenNormalized(e),n=this.renderer.domElement.width,i=this.renderer.domElement.height,r=(t.x+1)*n/2,o=(1-t.y)*i/2;return new ue(r,o)}screenToNormalized(e,t){const n=this.renderer.domElement.clientWidth,i=this.renderer.domElement.clientHeight,r=e/n*2-1,o=-(t/i*2-1);return new ue(r,o)}screenToWorld(e,t,n){if(!this.scene&&!n)return console.warn("WorldToScreen: 需要提供 scene 或 objects 参数才能进行屏幕坐标转世界坐标"),null;const i=this.screenToNormalized(e,t);this.raycaster.setFromCamera(i,this.camera);const r=n||this.scene.children,o=this.raycaster.intersectObjects(r,!0);return o.length>0?o[0].point:null}screenToWorldWithDepth(e,t,n=0){const i=this.screenToNormalized(e,t);this.raycaster.setFromCamera(i,this.camera);const r=new R;return this.raycaster.ray.at(n,r),r}updateCamera(e){this.camera=e}updateRenderer(e){this.renderer=e}updateScene(e){this.scene=e}}class m3{engine;currentMode="balance";gtaoPass=null;saturationPass=null;outputPass=null;fxaaPass=null;constructor(e){this.engine=e}init(){this.cachePassReferences(),this.setMode("balance")}setMode(e){this.currentMode=e,this.switchModel(e)}getCurrentMode(){return this.currentMode}cachePassReferences(){if(!this.engine.composerModule?.composer)return;const e=this.engine.composerModule.composer.passes;for(const t of e)t.constructor.name==="_GTAOPass"?this.gtaoPass=t:t.constructor.name==="ShaderPass"?t.material.uniforms.saturation?this.saturationPass=t:t.material.uniforms.resolution&&(this.fxaaPass=t):t.constructor.name==="OutputPass"&&(this.outputPass=t);this.engine.composerModule.saturationPass&&(this.saturationPass=this.engine.composerModule.saturationPass)}switchModel(e){switch(e){case"simple":this.setShadows(!1),this.setGTAO(!1),this.setSaturation(!1),this.setOutputPass(!1),this.setFXAA(!1);break;case"balance":this.setShadows(!0),this.setGTAO(!1),this.setSaturation(!1),this.setOutputPass(!1),this.setFXAA(!1);break;case"advanced":this.setShadows(!0),this.setGTAO(!0),this.setSaturation(!0),this.setOutputPass(!0),this.setFXAA(!0);break;default:console.warn(`[EngineModelModule] Unknown mode: ${e}`)}}setShadows(e){this.engine.renderer&&(this.engine.renderer.shadowMap.enabled=e);const t=this.engine.scene?.children.find(n=>n instanceof Ti);t&&(t.castShadow=e),this.engine.scene?.traverse(n=>{n.material&&(n.castShadow!==void 0&&(n.castShadow=e),n.receiveShadow!==void 0&&(n.receiveShadow=e))})}setGTAO(e){this.engine.composerModule?.composer&&(e?this.gtaoPass.enabled=!0:this.gtaoPass&&(this.gtaoPass.enabled=!1))}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")}setShadowQuality(e){const t=this.engine.scene?.children.find(i=>i instanceof Ti),n={low:1024,medium:2048,high:4096}[e];t?.shadow&&n&&(t.shadow.mapSize.width=n,t.shadow.mapSize.height=n,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 cl{engine;overlayMaterial;overlayMeshes=[];animState="idle";animStartTime=0;static FADE_IN_MS=200;static FADE_OUT_MS=150;constructor(e){this.engine=e,this.init()}init(){this.overlayMaterial=new Xt({color:16777215,transparent:!0,opacity:0,blending:Hl,depthWrite:!1})}hightMesh(e,t=16777215,n=.15){this.animState==="fadeOut"&&this.removeOverlayMeshes();const i=(Array.isArray(e)?e:e?[e]:[]).filter(r=>r?.geometry);if(i.length===0){this.clearHighlight();return}this.overlayMaterial.color.set(t),this.overlayMaterial.opacity=0,this.overlayMaterial.userData.targetOpacity=n;for(const r of i){const o=new ht(r.geometry,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 n=Math.min(e/cl.FADE_IN_MS,1);this.overlayMaterial.opacity=this.easeOutQuad(n)*t,n>=1&&(this.animState="idle")}else if(this.animState==="fadeOut"){const n=Math.min(e/cl.FADE_OUT_MS,1);this.overlayMaterial.opacity=(1-this.easeOutQuad(n))*t,n>=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 du={exports:{}},g3=du.exports,Fm;function x3(){return Fm||(Fm=1,(function(s,e){(function(t,n){s.exports=n()})(g3,function(){var t=function(){function n(d){return o.appendChild(d.dom),d}function i(d){for(var m=0;ml+1e3&&(h.update(1e3*c/(d-l),100),l=d,c=0,f)){var m=performance.memory;f.update(m.usedJSHeapSize/1048576,m.jsHeapSizeLimit/1048576)}return d},update:function(){a=this.end()},domElement:o,setMode:i}};return t.Panel=function(n,i,r){var o=1/0,a=0,l=Math.round,c=l(window.devicePixelRatio||1),h=80*c,u=48*c,f=3*c,d=2*c,m=3*c,p=15*c,x=74*c,g=30*c,b=document.createElement("canvas");b.width=h,b.height=u,b.style.cssText="width:80px;height:48px";var v=b.getContext("2d");return v.font="bold "+9*c+"px Helvetica,Arial,sans-serif",v.textBaseline="top",v.fillStyle=r,v.fillRect(0,0,h,u),v.fillStyle=i,v.fillText(n,f,d),v.fillRect(m,p,x,g),v.fillStyle=r,v.globalAlpha=.9,v.fillRect(m,p,x,g),{dom:b,update:function(y,M){o=Math.min(o,y),a=Math.max(a,y),v.fillStyle=r,v.globalAlpha=1,v.fillRect(0,0,h,p),v.fillStyle=i,v.fillText(l(y)+" "+n+" ("+l(o)+"-"+l(a)+")",f,d),v.drawImage(b,m+c,p,x-c,g,m,p,x-c,g),v.fillRect(m+x-c,p,c,g),v.fillStyle=r,v.globalAlpha=.9,v.fillRect(m+x-c,p,c,l((1-y/M)*g))}}},t})})(du)),du.exports}var v3=x3();const b3=Up(v3);var Rr=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-Rr.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?Rr.Bounce.In(s*2)*.5:Rr.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}}}}),Po=function(){return performance.now()},y3=(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=Po()),t===void 0&&(t=!1);var n=Object.keys(this._tweens);if(n.length===0)return!1;for(;n.length>0;){this._tweensAddedDuringUpdate={};for(var i=0;i1?r(s[t],s[t-1],t-n):r(s[i],s[i+1>t?t:i+1],n-i)},Utils:{Linear:function(s,e,t){return(e-s)*t+s}}},zm=(function(){function s(){}return s.nextId=function(){return s._nextId++},s._nextId=0,s})(),pu=new y3,_3=(function(){function s(e,t){t===void 0&&(t=pu),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=Rr.Linear.None,this._interpolationFunction=fu.Linear,this._chainedTweens=[],this._onStartCallbackFired=!1,this._onEveryStartCallbackFired=!1,this._id=zm.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=Po()),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 n in this._valuesStartRepeat)this._swapEndStartRepeatValues(n),this._valuesStart[n]=this._valuesStartRepeat[n]}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 i={};for(var r in this._valuesEnd)i[r]=this._valuesEnd[r];this._valuesEnd=i}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,n,i,r){for(var o in n){var a=e[o],l=Array.isArray(a),c=l?"array":typeof a,h=!l&&Array.isArray(n[o]);if(!(c==="undefined"||c==="function")){if(h){var u=n[o];if(u.length===0)continue;for(var f=[a],d=0,m=u.length;d"u"||r)&&(t[o]=a),l||(t[o]*=1),h?i[o]=n[o].slice().reverse():i[o]=t[o]||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=Po()),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=Po()),!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;eo)return!1;t&&this.start(e,!0)}if(this._goToEnd=!1,ec)return 1;var x=Math.trunc(a/l),g=a-x*l,b=Math.min(g/n._duration,1);return b===0&&a===n._duration?1:b},u=h(),f=this._easingFunction(u);if(this._updateProperties(this._object,this._valuesStart,this._valuesEnd,f),this._onUpdateCallback&&this._onUpdateCallback(this._object,u),this._duration===0||a>=this._duration)if(this._repeat>0){var d=Math.min(Math.trunc((a-this._duration)/l)+1,this._repeat);isFinite(this._repeat)&&(this._repeat-=d);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*d,this._onRepeatCallback&&this._onRepeatCallback(this._object),this._onEveryStartCallbackFired=!1,!0}else{this._onCompleteCallback&&this._onCompleteCallback(this._object);for(var m=0,p=this._chainedTweens.length;m{x&&(y||(x(M),y=!0))}),x&&setTimeout(()=>{y||(x(!0),y=!0)},p+10)},n.CameraGoHome=function(){var m=s.octreeBox.getBoundingBox(),p=m.min.clone().add(m.max.clone()).multiplyScalar(.5);let x=new R(1,1,1);var g=m.max.distanceTo(m.min),b=p.clone().add(x.multiplyScalar(g));if(e.camera.isOrthographicCamera){var v=s.container.clientWidth/s.container.clientHeight,y=g*.6;e.camera.left=-y*v,e.camera.right=y*v,e.camera.top=y,e.camera.bottom=-y,e.camera.zoom=1,e.camera.updateProjectionMatrix()}l(e.camera.position,b,s.controls.target.clone(),p)},n.zoomToBox=function(m){var p=m.min.clone().add(m.max.clone()).multiplyScalar(.5);let x=e.camera.position.clone().sub(s.controls.target.clone()).normalize();var g=p.clone().add(x.multiplyScalar(1*m.max.distanceTo(m.min)));l(e.camera.position,g,s.controls.target.clone(),p)};function l(m,p,x,g,b,v,y=1e3,M){var E;b&&v?(E=new mu.Tween({x1:m.x,y1:m.y,z1:m.z,x2:x.x,y2:x.y,z2:x.z,_x:b._x,_y:b._y,_z:b._z,_w:b._w}),E.to({x1:p.x,y1:p.y,z1:p.z,x2:g.x,y2:g.y,z2:g.z,_x:v._x,_y:v._y,_z:v._z,_w:v._w},y)):(E=new mu.Tween({x1:m.x,y1:m.y,z1:m.z,x2:x.x,y2:x.y,z2:x.z}),E.to({x1:p.x,y1:p.y,z1:p.z,x2:g.x,y2:g.y,z2:g.z},y)),E.onUpdate(function(P){s.controls&&(b&&v?(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(),n.RenderScene())}),E.onComplete(function(P){s.controls&&(s.controls.auto=!1,n.RenderScene(),M&&M(!0),cancelAnimationFrame(i),i=null)}),E.easing(mu.Easing.Cubic.InOut);function C(P){i=requestAnimationFrame(C),E.update()}E.start(),C()}function c(){r=document.createElement("div"),r.className="ViewCube",t.appendChild(r),o=document.createElement("div"),o.className="viewSettingWrapper",o.innerHTML="...",r.appendChild(o);var m=document.createElement("div");m.className="homeViewWrapper",m.addEventListener("mousedown",function(){console.log("归位"),n.CameraGoHome()}),r.appendChild(m);const p=document.createElement("div");p.className="cameraToggleWrapper",p.title="切换正交/透视视图",p.innerHTML="⊞",p.addEventListener("mousedown",function(y){y.stopPropagation(),console.log("切换视图"),n.ToggleCameraType(),b()}),r.appendChild(p);const x=document.createElement("div");x.className="screenshotWrapper",x.title="截图",x.innerHTML="📷",x.addEventListener("mousedown",function(y){y.stopPropagation(),console.log("截图"),n.TakeScreenshot(),b()}),r.appendChild(x);const g=document.createElement("div");g.className="fullscreenWrapper",g.title="全屏",g.innerHTML="⛶",g.addEventListener("mousedown",function(y){y.stopPropagation(),console.log("全屏"),n.ToggleFullscreen(),b()}),r.appendChild(g),o.addEventListener("mousedown",function(y){y.stopPropagation(),p.classList.contains("show")?(b(),console.log("隐藏功能按钮")):(v(),console.log("显示功能按钮"))});function b(){p.classList.remove("show"),x.classList.remove("show"),g.classList.remove("show")}function v(){p.classList.add("show"),x.classList.add("show"),g.classList.add("show")}}function h(){n.sceneOrtho=M3();var x=t.clientWidth,g=t.clientWidth,m=x>g?x/g:g/x,p=300;n.camera=new ps(p*m/-2,p*m/2,p/2,p/-2,.01,1e4);var x=r.clientWidth,g=r.clientHeight,b=new Rp({alpha:!0});b.setSize(x,g),b.setClearAlpha(0),n.sceneOrtho.renderer=b;let v=new Na(16777215,.8);n.sceneOrtho.add(v),w3(r,b)}function u(){const m="/assets/viewcube/";let p=[{label:"右",icon:m+"cn_right.png"},{label:"左",icon:m+"cn_left.png"},{label:"顶",icon:m+"cn_top.png"},{label:"底",icon:m+"cn_bottom.png"},{label:"前",icon:m+"cn_front.png"},{label:"后",icon:m+"cn_back.png"}];var x=[];for(const b of p)x.push(new Xt({color:16777215,map:new qf().load(b.icon)}));new xv({color:255});var g=new ht(new Wi(110,110,110),x);n.sceneOrtho.add(g),f(122),r.addEventListener("mousedown",b=>{var v={};v.x=b.offsetX/r.clientWidth*2-1,v.y=-(b.offsetY/r.clientHeight)*2+1;var y=new ms;y.setFromCamera(v,n.camera);const M=y.intersectObjects(a,!1);M.length>0&&n.ToggleDirectionView(M[0].object.name)}),r.addEventListener("mousemove",b=>{var v={};v.x=b.offsetX/r.clientWidth*2-1,v.y=-(b.offsetY/r.clientHeight)*2+1;var y=new ms;y.setFromCamera(v,n.camera);const M=y.intersectObjects(a,!1);for(var E of a)E.material.opacity=.01;M.length>0&&(M[0].object.material.opacity=.2)})}function f(m){for(var p=m*.5-20,x=[{name:"right",a:30,b:75,c:75,point:new R(p,0,0)},{name:"back",a:75,b:75,c:30,point:new R(0,0,-p)},{name:"left",a:30,b:75,c:75,point:new R(-p,0,0)},{name:"front",a:75,b:75,c:30,point:new R(0,0,p)},{name:"top",a:75,b:30,c:75,point:new R(0,p,0)},{name:"button",a:75,b:30,c:75,point:new R(0,-p,0)}],g=[{name:"top_right_back",a:30,b:30,c:30,point:new R(-p,p,p)},{name:"button_front_right",a:30,b:30,c:30,point:new R(-p,-p,p)},{name:"top_front_right",a:30,b:30,c:30,point:new R(p,p,p)},{name:"button_right_back",a:30,b:30,c:30,point:new R(p,-p,p)},{name:"top_back_left",a:30,b:30,c:30,point:new R(-p,p,-p)},{name:"button_back_left",a:30,b:30,c:30,point:new R(-p,-p,-p)},{name:"top_left_front",a:30,b:30,c:30,point:new R(p,p,-p)},{name:"button_left_front",a:30,b:30,c:30,point:new R(p,-p,-p)}],b=[{name:"top_front",a:30,b:30,c:75,point:new R(p,p,0)},{name:"top_right",a:75,b:30,c:30,point:new R(0,p,p)},{name:"top_back",a:30,b:30,c:75,point:new R(-p,p,0)},{name:"top_left",a:75,b:30,c:30,point:new R(0,p,-p)},{name:"button_front",a:30,b:30,c:75,point:new R(p,-p,0)},{name:"button_right",a:75,b:30,c:30,point:new R(0,-p,p)},{name:"button_back",a:30,b:30,c:75,point:new R(-p,-p,0)},{name:"button_left",a:75,b:30,c:30,point:new R(0,-p,-p)},{name:"front_right",a:30,b:75,c:30,point:new R(p,0,p)},{name:"right_back",a:30,b:75,c:30,point:new R(-p,0,p)},{name:"back_left",a:30,b:75,c:30,point:new R(-p,0,-p)},{name:"left_front",a:30,b:75,c:30,point:new R(p,0,-p)}],v=0;v{let f=u.boundingBox.min,d=u.boundingBox.max;f.xi.x&&(i.x=d.x),d.y>i.y&&(i.y=d.y),d.z>i.z&&(i.z=d.z)});let r=Math.min(n.x,i.x),o=Math.min(n.y,i.y),a=Math.min(n.z,i.z),l=Math.max(n.x,i.x),c=Math.max(n.y,i.y),h=Math.max(n.z,i.z);return{min:new R(r,o,a),max:new R(l,c,h)}},e.rayInterationModel=function(t){let n=[];return s.engineStatus.models.forEach(r=>{r.info.lods.forEach(o=>{let a=o.octreeBox;i(t,a,r)})}),t.intersectObjects(n,!1);function i(r,o,a){if(o==null)return;let l=new R(o.min.X*.3048,o.min.Z*.3048,-o.min.Y*.3048),c=new R(o.max.X*.3048,o.max.Z*.3048,-o.max.Y*.3048),h=new R(Math.min(l.x,c.X),Math.min(l.y,c.y),Math.min(l.z,c.z)),u=new R(Math.max(c.x,l.x),Math.max(c.y,l.y),Math.max(c.z,l.z)),f=new gt(h,u),d=r.ray.intersectsBox(f);if(!(d==null||d==!1))if(o.children==null||o.children.length==0){if(o.elements!=null)for(var m of o.elements){let p=s.engineStatus.hideModels.find(b=>b.url==a.url)?.ids;if(p!=null&&p.includes(m))continue;let x=s.engineStatus.translucentModels.find(b=>b.url==a.url)?.ids;if(x!=null&&x.includes(m))continue;let g=s.models.find(b=>b.url==a.url).nodesMap.get(m);g!=null&&!g.instance&&g.infos.map(b=>b.mesh).forEach(b=>{n.push(b)})}}else{if(o.elements!=null)for(var m of o.elements){let x=s.engineStatus.hideModels.find(v=>v.url==a.url)?.ids;if(x!=null&&x.includes(m))continue;let g=s.engineStatus.translucentModels.find(v=>v.url==a.url)?.ids;if(g!=null&&g.includes(m))continue;let b=s.models.find(v=>v.url==a.url).nodesMap.get(m);b!=null&&!b.instance&&b.infos.map(v=>v.mesh).forEach(v=>{n.push(v)})}for(let p of o.children)i(r,p,a)}}},e}class C3{engine;isDrawing=!1;startPoint=new ue;endPoint=new ue;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 kn(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),n=Math.abs(this.endPoint.x-this.startPoint.x),i=Math.abs(this.endPoint.y-this.startPoint.y);this.selectionBox.style.left=`${e}px`,this.selectionBox.style.top=`${t}px`,this.selectionBox.style.width=`${n}px`,this.selectionBox.style.height=`${i}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 n=Math.min(this.startPoint.x,this.endPoint.x),i=Math.max(this.startPoint.x,this.endPoint.x),r=Math.min(this.startPoint.y,this.endPoint.y),o=Math.max(this.startPoint.y,this.endPoint.y),a=[],l=[{x:n,y:r},{x:i,y:r},{x:i,y:o},{x:n,y:o}];for(const h of l){const u=this.worldToScreen.screenToWorld(h.x,h.y);u&&a.push(u)}if(a.length<3){console.warn("RangeScale: 框选区域未命中模型,无法执行缩放操作");return}if(a.length<3){console.warn("RangeScale: 无法将屏幕区域转换为世界坐标");return}const c=new gt;for(const h of a)c.expandByPoint(h);if(c.isEmpty()){console.warn("RangeScale: 计算得到的包围盒无效");return}this.fitCameraToBoundingBox(c)}fitCameraToBoundingBox(e){const t=this.engine.camera,n=this.engine.controls;if(!t||!n){console.warn("RangeScale: 相机或控制器未初始化");return}const i=new R;e.getCenter(i);const r=new R;e.getSize(r);const o=Math.max(r.x,r.y,r.z);if(t instanceof on){const a=t.fov*(Math.PI/180),l=o/(2*Math.tan(a/2))*1.2,c=new R;t.getWorldDirection(c);const h=i.clone().sub(t.position);c.dot(h.normalize())<0&&c.negate();const u=i.clone().sub(c.multiplyScalar(l));t.position.copy(u),n.target&&n.target.copy(i),t.lookAt(i),n.update()}else if(t instanceof ps){const a=o*1.2,l=this.engine.renderer?.domElement,c=l?l.width/l.height:1;t.left=-a*c/2,t.right=a*c/2,t.top=a/2,t.bottom=-a/2,t.updateProjectionMatrix();const h=new R;t.getWorldDirection(h);const u=o*1.5,f=i.clone().sub(h.multiplyScalar(u));t.position.copy(f),n.target&&n.target.copy(i),t.lookAt(i),n.update()}}}class A3{engine;ground=null;constructor(e){this.engine=e}init(){}setStatsVisible(e){this.engine.stats?.dom&&(this.engine.stats.dom.style.display=e?"block":"none")}setAmbientLightIntensity(e){const t=this.engine.scene.children.find(n=>n instanceof Na);t&&(t.intensity=e)}setAmbientLightColor(e){const t=this.engine.scene.children.find(n=>n instanceof Na);t&&t.color.set(e)}setDirectionalLightIntensity(e){const t=this.engine.scene.children.find(n=>n instanceof Ti);t&&(t.intensity=e)}setDirectionalLightColor(e){const t=this.engine.scene.children.find(n=>n instanceof Ti);t&&t.color.set(e)}setShadowQuality(e){const t=this.engine.scene.children.find(n=>n instanceof Ti);if(t?.shadow){const n={low:1024,medium:2048,high:4096,ultra:8192}[e];t.shadow.mapSize.width=n,t.shadow.mapSize.height=n,t.shadow.map?.dispose(),t.shadow.map=null}}setDirectionalLightShadow(e){const t=this.engine.scene.children.find(n=>n instanceof Ti);t&&(t.castShadow=e),this.engine.renderer&&(this.engine.renderer.shadowMap.enabled=e)}setGTAOEnabled(e){if(!this.engine.composerModule?.composer){console.warn("Composer not initialized");return}const t=this.engine.composerModule.composer,n=t.passes.find(i=>i instanceof xn);if(e)if(n)n.enabled=!0;else{const{width:i,height:r}=this.engine.deviceModule.getContainerSize(),o=new xn(this.engine.scene,this.engine.camera,i,r);o.output=xn.OUTPUT.Default,o.blendIntensity=.5,o.updateGtaoMaterial&&o.updateGtaoMaterial({radius:1,distanceExponent:1,thickness:1,scale:1,distanceFallOff:1,screenSpaceRadius:!0});const a=t.passes.findIndex(l=>l.constructor.name==="RenderPass");t.passes.splice(a+1,0,o)}else n&&(n.enabled=!1)}setSceneSaturation(e){if(!this.engine.composerModule?.saturationPass){console.warn("Saturation pass not initialized");return}this.engine.composerModule.saturationPass.uniforms.saturation.value=e}setSceneContrast(e){if(!this.engine.composerModule?.saturationPass){console.warn("Saturation pass not initialized");return}this.engine.composerModule.saturationPass.uniforms.contrast.value=e}setGroundEnabled(e,t){if(e)if(this.ground)this.ground.visible=!0;else{const n=t?.size??100,i=t?.color??8421504,r=t?.opacity??.3,o=new xo(n,n),a=new ds({color:i,transparent:!0,opacity:r,side:St});this.ground=new ht(o,a),this.ground.rotation.x=-Math.PI/2,this.ground.position.y=0,this.ground.receiveShadow=!0,this.ground.name="ground",this.engine.scene.add(this.ground)}else this.ground&&(this.ground.visible=!1)}setHDRBackground(e){e?(this.engine.scene.background=e,this.engine.scene.environment=e):(this.engine.scene.background=null,this.engine.scene.environment=null)}}function Ai(){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 Pi{engine;handelBehaved;setting;constructor(e){this.engine=e,this.handelBehaved=jh(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 n=this.setting.unit,i=n;return t==1?n=="mm"?e=e*1e3:n=="cm"?e=e*100:n=="dm"?e=e*10:n=="m"?e=e*1:n=="km"&&(e=e*.001):t==2&&(n=="mm"?e=e*1e3*1e3:n=="cm"?e=e*100*100:n=="dm"?e=e*10*10:n=="m"?e=e*1*1:n=="km"&&(e=e*.001*.001),i=i+"²"),e.toFixed(this.setting.precision)+" "+i}cancelCurrentSelectedAnnotation(){let e=this.engine.measure.annotationData;for(let t in e)e[t].forEach(n=>{n.highlight==!0&&(n.highlight=!1,n.container.classList.remove("Hight"),n.container.getElementsByTagName("svg")[0].classList.remove("Hight"))})}handelKeyEscDown(){this.cancelCurrentSelectedAnnotation();let e=this.engine.measure.annotationData;for(let t in e)for(let n=e[t].length-1;n>=0;n--){let i=e[t][n];i.isSelect==!0&&(i.container.remove(),e[t].splice(n,1))}this.engine.measure.clearAllPoints()}handelKeyDeleteDown(){let e=this.engine.measure.annotationData;for(let t in e)for(let n=e[t].length-1;n>=0;n--){let i=e[t][n];i.highlight==!0&&(i.container.remove(),e[t].splice(n,1))}}clearHighlight(){let e=this.engine.measure.annotationData;for(let t in e)e[t].forEach(n=>{n.highlight=!1,n.container.classList.remove("Hight"),n.container.getElementsByTagName("svg")[0].classList.remove("Hight")})}drawNormalAnnotation(){let e=this;this.engine.measure.annotationData.normalAnnotation.forEach(l=>{a(l)}),this.engine.measure.annotationData.elevationAnnotation.forEach(l=>{o(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=>{n(l)}),this.engine.measure.annotationData.slopeAnnotation.forEach(l=>{i(l)});function t(l){if(l.container==null){let g=['','','','','','','',''+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=g,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(Gt.MeasureClick,l)})}let c=new kn(e.engine.camera,e.engine.renderer,e.engine.scene).worldToScreen(l.point1),h=new kn(e.engine.camera,e.engine.renderer,e.engine.scene).worldToScreen(l.point2),u=new kn(e.engine.camera,e.engine.renderer,e.engine.scene).worldToScreen(l.point3),f=e.engine.reactBoundingClientRect.left,d=e.engine.reactBoundingClientRect.top;c.x+=f,c.y+=d,h.x+=f,h.y+=d,u.x+=f,u.y+=d;let m=l.container;m.getElementsByTagName("circle")[0].setAttribute("cx",c.x),m.getElementsByTagName("circle")[0].setAttribute("cy",c.y),m.getElementsByTagName("circle")[1].setAttribute("cx",h.x),m.getElementsByTagName("circle")[1].setAttribute("cy",h.y),m.getElementsByTagName("circle")[2].setAttribute("cx",u.x),m.getElementsByTagName("circle")[2].setAttribute("cy",u.y),m.getElementsByTagName("polyline")[0].setAttribute("points",c.x+","+c.y+" "+h.x+","+h.y),m.getElementsByTagName("polyline")[1].setAttribute("points",h.x+","+h.y+" "+u.x+","+u.y);let p=h.x,x=h.y-30;m.getElementsByTagName("rect")[0].setAttribute("x",p-40),m.getElementsByTagName("rect")[0].setAttribute("y",x-12.5),m.getElementsByTagName("text")[0].setAttribute("x",p),m.getElementsByTagName("text")[0].setAttribute("y",x+4),m.getElementsByTagName("text")[0].innerHTML=l.text,m.style.top="0px",m.style.left="0px"}function n(l){if(l.container==null){let b=['','','','',''+e.getMeasureText(l.text,2)+"",""].join("");l.container=document.createElement("div"),l.container.className="area-annotation",l.container.id=l.id,l.container.innerHTML=b,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(Gt.MeasureClick,l)})}if(!l.points||l.points.length<3)return;let c=e.engine.reactBoundingClientRect.left,h=e.engine.reactBoundingClientRect.top,u=[],f=0,d=0;for(let b=0;bb.x+","+b.y).join(" "),p=l.container;p.getElementsByTagName("polygon")[0].setAttribute("points",m),p.getElementsByTagName("polyline")[0].setAttribute("points",m);let x=f,g=d;p.getElementsByTagName("rect")[0].setAttribute("x",x-40),p.getElementsByTagName("rect")[0].setAttribute("y",g-12.5),p.getElementsByTagName("text")[0].setAttribute("x",x),p.getElementsByTagName("text")[0].setAttribute("y",g+4),p.getElementsByTagName("text")[0].innerHTML=e.getMeasureText(l.text,2),p.style.top="0px",p.style.left="0px"}function i(l){if(l.container==null){let x=['',"",'','',"","",'','',''+l.text+"",""].join("");l.container=document.createElement("div"),l.container.className="slope-annotation",l.container.id=l.id,l.container.innerHTML=x,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(Gt.MeasureClick,l)})}let c=new kn(e.engine.camera,e.engine.renderer,e.engine.scene).worldToScreen(l.point1),h=new kn(e.engine.camera,e.engine.renderer,e.engine.scene).worldToScreen(l.point2),u=e.engine.reactBoundingClientRect.left,f=e.engine.reactBoundingClientRect.top;c.x+=u,c.y+=f,h.x+=u,h.y+=f;let d=l.container;d.getElementsByTagName("polyline")[0].setAttribute("points",c.x+","+c.y+" "+h.x+","+h.y);let m=(c.x+h.x)/2,p=(c.y+h.y)/2-30;d.getElementsByTagName("rect")[0].setAttribute("x",m-50),d.getElementsByTagName("rect")[0].setAttribute("y",p-12.5),d.getElementsByTagName("text")[0].setAttribute("x",m),d.getElementsByTagName("text")[0].setAttribute("y",p+4),d.getElementsByTagName("text")[0].innerHTML=l.text,d.style.top="0px",d.style.left="0px"}function r(l){if(l.container==null){let g=['','','','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=g,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(Gt.MeasureClick,l)})}let c=l.container,h=new kn(e.engine.camera,e.engine.renderer,e.engine.scene).worldToScreen(l.point),u=e.engine.reactBoundingClientRect.left,f=e.engine.reactBoundingClientRect.top;h.x+=u,h.y+=f,c.style.top="0px",c.style.left="0px";let d=c.getElementsByTagName("circle")[0];d&&(d.setAttribute("cx",h.x),d.setAttribute("cy",h.y));let m=c.getElementsByTagName("rect"),p=c.getElementsByTagName("text"),x=-55;m[0]&&(m[0].setAttribute("x",h.x+10),m[0].setAttribute("y",h.y+10+x)),p[0]&&(p[0].setAttribute("x",h.x+10+40),p[0].setAttribute("y",h.y+10+16+x)),m[1]&&(m[1].setAttribute("x",h.x+10),m[1].setAttribute("y",h.y+10+30+x)),p[1]&&(p[1].setAttribute("x",h.x+10+40),p[1].setAttribute("y",h.y+10+46+x)),m[2]&&(m[2].setAttribute("x",h.x+10),m[2].setAttribute("y",h.y+10+60+x)),p[2]&&(p[2].setAttribute("x",h.x+10+40),p[2].setAttribute("y",h.y+10+76+x)),p[0]&&(p[0].innerHTML="X: "+e.getMeasureText(l.textX,1)),p[1]&&(p[1].innerHTML="Y: "+e.getMeasureText(-l.textZ,1)),p[2]&&(p[2].innerHTML="Z: "+e.getMeasureText(l.textY,1))}function o(l){if(l.container==null){let d=['','',''+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=d,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(Gt.MeasureClick,l)})}let c=l.container,h=new kn(e.engine.camera,e.engine.renderer,e.engine.scene).worldToScreen(l.point),u=e.engine.reactBoundingClientRect.left,f=e.engine.reactBoundingClientRect.top;c.style.top=h.y+f-48+"px",c.style.left=h.x+u-16+"px",c.getElementsByTagName("text")[0].innerHTML=e.getMeasureText(l.text,1)}function a(l){if(l.container==null){let m=['','','','','',''+e.getMeasureText(l.text,1)+"",""].join("");l.container=document.createElement("div"),l.container.className="normal-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(Gt.MeasureClick,l)})}let c=l.container;if(l.point1==null||l.point2==null){c.style.display="none";return}else c.style.display="block";let h=new kn(e.engine.camera,e.engine.renderer,e.engine.scene).worldToScreen(l.point1),u=new kn(e.engine.camera,e.engine.renderer,e.engine.scene).worldToScreen(l.point2),f=e.engine.reactBoundingClientRect.left,d=e.engine.reactBoundingClientRect.top;h.x+=f,h.y+=d,u.x+=f,u.y+=d,c.getElementsByTagName("polyline")[0].setAttribute("points",h.x+","+h.y+" "+u.x+","+u.y),c.getElementsByTagName("circle")[0].setAttribute("cx",h.x),c.getElementsByTagName("circle")[0].setAttribute("cy",h.y),c.getElementsByTagName("circle")[1].setAttribute("cx",u.x),c.getElementsByTagName("circle")[1].setAttribute("cy",u.y),c.getElementsByTagName("rect")[0].setAttribute("x",h.x*.5+u.x*.5-40),c.getElementsByTagName("rect")[0].setAttribute("y",h.y*.5+u.y*.5-12.5),c.getElementsByTagName("text")[0].setAttribute("x",h.x*.5+u.x*.5+40-40),c.getElementsByTagName("text")[0].setAttribute("y",h.y*.5+u.y*.5+16-12.5),c.getElementsByTagName("text")[0].innerHTML=e.getMeasureText(l.text,1),c.style.top="0px",c.style.left="0px"}}}class P3{engine;isActive=!1;tools;points=[];behavior;constructor(e){this.engine=e,this.tools=new Pi(e)}active(){this.engine.measure.tools.cancelCurrentSelectedAnnotation(),this.isActive=!0,this.behavior=this.engine.handelBehaved,this.behavior.init(this),this.behavior.active()}disActive(){this.isActive=!1,this.behavior?.disActive()}clearAllPoints(){this.points=[]}handleMouseClick(e){if(e.catch==null)return;if(this.points.length==0){this.points.push(e.catch.point);return}let t=this.engine.measure.annotationData.normalAnnotation.find(n=>n.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(o=>o.isSelect==!0);t==null&&(t={text:null,id:Ai(),isSelect:!0,type:"clear-height"},this.engine.measure.annotationData.normalAnnotation.push(t));let n=new ms(e.catch.point.clone().add(new R(0,.01,0)),new R(0,1,0));const i=this.engine.octreeBox.rayInterationModel(n);if(i.length===0){t.point2=null;return}let r=e.catch;t.point1=r.point,t.point2=i[0].point,t.text=t.point1.clone().distanceTo(t.point2.clone()),this.engine.events.trigger(Gt.MeasureChanged,t)}}class R3{engine;tools;isActive=!1;points=[];behavior;constructor(e){this.engine=e,this.tools=new Pi(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()}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.points.push(t.point);else if(this.points.length==1){let n=this.engine.measure.annotationData.normalAnnotation.find(i=>i.isSelect==!0);if(n==null)return;n.point2=t.point,n.isSelect=!1,this.points=[],this.engine.events.trigger(Gt.MeasureChanged,n)}}handleMouseMove(e){if(e.catch==null)return;let t=e.catch;if(t!=null&&this.points.length==1){let n=this.engine.measure.annotationData.normalAnnotation.find(i=>i.isSelect==!0);n==null&&(n={id:Ai(),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(n)),n.point2=t.point,n.text=n.point1.clone().distanceTo(n.point2.clone())}}}class L3{engine;isActive=!1;tools;points=[];behavior;constructor(e){this.engine=e,this.tools=new Pi(e)}active(){this.engine.measure.tools.cancelCurrentSelectedAnnotation(),this.isActive=!0,this.behavior=this.engine.handelBehaved,this.behavior.init(this),this.behavior.active()}disActive(){this.isActive=!1,this.behavior?.disActive()}clearAllPoints(){this.points=[]}handleMouseClick(e){if(e.catch==null)return;if(this.points.length==0){this.points.push(e.catch.point);return}let t=this.engine.measure.annotationData.normalAnnotation.find(n=>n.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(o=>o.isSelect==!0);t==null&&(t={text:null,id:Ai(),isSelect:!0,type:"clear-distance"},this.engine.measure.annotationData.normalAnnotation.push(t));let n=new ms(e.catch.point.clone().add(e.catch.normal.clone().setLength(.01)),e.catch.normal);const i=this.engine.octreeBox.rayInterationModel(n);if(i.length==0){t.point2=null;return}let r=e.catch;t.point1=r.point,t.point2=i[0].point,t.text=t.point1.clone().distanceTo(t.point2.clone()),this.engine.events.trigger(Gt.MeasureChanged,t)}}class I3{engine;isActive=!1;tools;points=[];behavior;constructor(e){this.engine=e,this.tools=new Pi(e)}active(){this.engine.measure.tools.cancelCurrentSelectedAnnotation(),this.behavior=this.engine.handelBehaved,this.behavior.init(this),this.behavior.active(),this.isActive=!0}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(n=>n.isSelect==!0);t==null&&(t={id:Ai(),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;let t=this.engine.measure.annotationData.elevationAnnotation.find(n=>n.isSelect==!0);t!=null&&(t.isSelect=!1,t.point=e.catch.point.clone(),t.text=e.catch.point.y,this.engine.events.trigger(Gt.MeasureChanged,t))}}class D3{engine;isActive=!1;tools;points=[];behavior;constructor(e){this.engine=e,this.tools=new Pi(e)}active(){this.engine.measure.tools.cancelCurrentSelectedAnnotation(),this.behavior=this.engine.handelBehaved,this.behavior.init(this),this.behavior.active(),this.isActive=!0}disActive(){this.isActive=!1,this.behavior?.disActive()}clearAllPoints(){this.points=[]}handleMouseMove(e){if(e.catch==null)return;let t=this.engine.measure.annotationData.coordinateAnnotation.find(n=>n.isSelect==!0);t==null&&(t={id:Ai(),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;let t=this.engine.measure.annotationData.coordinateAnnotation.find(n=>n.isSelect==!0);t!=null&&(t.isSelect=!1,t.point=e.catch.point.clone(),t.textX=e.catch.point.x,t.textY=e.catch.point.y,t.textZ=e.catch.point.z,this.engine.events.trigger(Gt.MeasureChanged,t))}}class B3{engine;tools;points=[];behavior;constructor(e){this.engine=e,this.tools=new Pi(e)}active(){this.engine.measure.tools.cancelCurrentSelectedAnnotation(),this.points=[],this.behavior=this.engine.handelBehaved,this.behavior.init(this),this.behavior.active()}disActive(){this.points=[],this.behavior?.disActive()}clearAllPoints(){this.points=[]}calculateAngle(e,t,n){const i=new R().subVectors(e,t),r=new R().subVectors(n,t),o=i.length(),a=r.length();if(o===0||a===0)return 0;const l=i.dot(r)/(o*a),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.points.push(t.point);else if(this.points.length==1)this.points.push(t.point);else if(this.points.length==2){let n=this.engine.measure.annotationData.angleAnnotation.find(i=>i.isSelect==!0);if(n==null)return;n.point3=t.point.clone(),n.angle=this.calculateAngle(n.point1,n.point2,n.point3),n.text=n.angle.toFixed(2)+"°",n.isSelect=!1,n.type="angle",this.points=[],this.engine.events.trigger(Gt.MeasureChanged,n)}}handleMouseMove(e){if(e.catch!=null&&this.points.length!=1&&this.points.length==2){let t=this.engine.measure.annotationData.angleAnnotation.find(n=>n.isSelect==!0);t==null&&(t={id:Ai(),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 N3{engine;tools;points=[];behavior;constructor(e){this.engine=e,this.tools=new Pi(e)}active(){this.engine.measure.tools.cancelCurrentSelectedAnnotation(),this.points=[],this.behavior=this.engine.handelBehaved,this.behavior.init(this),this.behavior.active()}disActive(){this.points=[],this.behavior?.disActive()}clearAllPoints(){this.points=[]}calculateArea(e){if(e.length<3)return 0;let t=0;const n=e.length;for(let i=0;i=3){let n=this.engine.measure.annotationData.areaAnnotation.find(i=>i.isSelect==!0);n==null?(n={id:Ai(),points:this.points.map(i=>i.clone()),area:0,text:0,isSelect:!0,type:"area"},this.engine.measure.annotationData.areaAnnotation.push(n)):(this.points.push(t.point.clone()),n.points=this.points.map(i=>i.clone())),n.area=this.calculateArea(n.points),n.text=n.area,console.log("面积",n.text)}}handleMouseMove(e){if(e.catch!=null&&this.points.length>=2){let t=this.engine.measure.annotationData.areaAnnotation.find(n=>n.isSelect==!0);if(t==null){if(this.points.length>=2){let n=this.points.map(i=>i.clone());n.push(e.catch.point.clone()),n.length>=3&&(t={id:Ai(),points:n,area:0,text:0,isSelect:!0,type:"area"},this.engine.measure.annotationData.areaAnnotation.push(t))}}else if(t.points.length>0){const n=t.points.length-1;t.points[n]=e.catch.point.clone()}else t.points=this.points.map(n=>n.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(Gt.MeasureChanged,e))}}class k3{engine;tools;points=[];behavior;constructor(e){this.engine=e,this.tools=new Pi(e)}active(){this.engine.measure.tools.cancelCurrentSelectedAnnotation(),this.points=[],this.behavior=this.engine.handelBehaved,this.behavior.init(this),this.behavior.active()}disActive(){this.points=[],this.behavior?.disActive()}clearAllPoints(){this.points=[]}calculateSlope(e,t){const n=t.y-e.y,i=t.x-e.x,r=t.z-e.z,o=Math.sqrt(i*i+r*r);if(o===0)return{percentage:0,angle:0,heightDiff:n,horizontalDist:0,type:"slope"};const a=n/o*100,l=Math.atan(n/o)*(180/Math.PI);return{percentage:a,angle:l,heightDiff:n,horizontalDist:o,type:"slope"}}handleMouseClick(e){if(e.catch==null)return;let t=e.catch;if(this.points.length==0)this.points.push(t.point);else if(this.points.length==1){let n=this.engine.measure.annotationData.slopeAnnotation.find(r=>r.isSelect==!0);if(n==null)return;console.log("进来了"),n.point2=t.point.clone();const i=this.calculateSlope(n.point1,n.point2);n.slopePercentage=i.percentage,n.slopeAngle=i.angle,n.heightDiff=i.heightDiff,n.horizontalDist=i.horizontalDist,n.text=i.percentage.toFixed(2)+"% ("+i.angle.toFixed(2)+"°)",n.isSelect=!1,this.points=[],this.engine.events.trigger(Gt.MeasureChanged,n)}}handleMouseMove(e){if(e.catch==null)return;let t=e.catch;if(t!=null&&this.points.length==1){let n=this.engine.measure.annotationData.slopeAnnotation.find(r=>r.isSelect==!0);n==null&&(n={id:Ai(),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(n)),n.point2=t.point.clone();const i=this.calculateSlope(n.point1,n.point2);n.slopePercentage=i.percentage,n.slopeAngle=i.angle,n.heightDiff=i.heightDiff,n.horizontalDist=i.horizontalDist,n.text=i.percentage.toFixed(2)+"% ("+i.angle.toFixed(2)+"°)"}}}class U3{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 P3(e),this.distanceMeasure=new R3(e),this.clearDistanceMeasure=new L3(e),this.elevationMeasure=new I3(e),this.pointMeasure=new D3(e),this.angleMeasure=new B3(e),this.areaMeasure=new N3(e),this.slopeMeasure=new k3(e),this.tools=new Pi(e),this.annotationContainer=document.createElement("div"),this.annotationContainer.className="annotation-container",e.container.appendChild(this.annotationContainer)}active(){this.isActive=!0,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 n=0;n65535?new Uint32Array(new e(4*s)):new Uint16Array(new e(2*s))}function G3(s,e){if(!s.index){const t=s.attributes.position.count,n=e.useSharedArrayBuffer?SharedArrayBuffer:ArrayBuffer,i=V3(t,n);s.setIndex(new vt(i,1));for(let r=0;ri&&(a.push({pos:Math.max(i,d),isStart:!0}),a.push({pos:Math.min(r,p),isStart:!1}))}a.sort((h,u)=>h.pos!==u.pos?h.pos-u.pos:h.type==="end"?-1:1);let l=0,c=null;for(const h of a){const u=h.pos;l!==0&&u!==c&&t.push({offset:c,count:u-c}),l+=h.isStart?1:-1,c=u}return t}function vu(s,e,t,n,i){let r=1/0,o=1/0,a=1/0,l=-1/0,c=-1/0,h=-1/0,u=1/0,f=1/0,d=1/0,m=-1/0,p=-1/0,x=-1/0;const g=s.offset||0;for(let b=(e-g)*6,v=(e+t-g)*6;bl&&(l=C),ym&&(m=y);const P=s[b+2],_=s[b+3],S=P-_,I=P+_;Sc&&(c=I),Pp&&(p=P);const A=s[b+4],B=s[b+5],w=A-B,F=A+B;wh&&(h=F),Ax&&(x=A)}n[0]=r,n[1]=o,n[2]=a,n[3]=l,n[4]=c,n[5]=h,i[0]=u,i[1]=f,i[2]=d,i[3]=m,i[4]=p,i[5]=x}function qm(s,e,t=null,n=null,i=null){const r=s.attributes.position,o=s.index?s.index.array:null,a=r.normalized;if(i===null)i=new Float32Array(t*6),i.offset=e;else if(e<0||t+e>i.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 u=["getX","getY","getZ"],f=i.offset;for(let d=e,m=e+t;d_&&(_=E),C>_&&(_=C);const S=(_-P)/2,I=y*2;i[x+I+0]=P+S,i[x+I+1]=S+(Math.abs(P)+S)*z3}}return i}function Lt(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 Zm(s){let e=-1,t=-1/0;for(let n=0;n<3;n++){const i=s[n+3]-s[n];i>t&&(t=i,e=n)}return e}function Ym(s,e){e.set(s)}function $m(s,e,t){let n,i;for(let r=0;r<3;r++){const o=r+3;n=s[r],i=e[r],t[r]=ni?n:i}}function hl(s,e,t){for(let n=0;n<3;n++){const i=e[s+2*n],r=e[s+2*n+1],o=i-r,a=i+r;ot[n+3]&&(t[n+3]=a)}}function Ro(s){const e=s[3]-s[0],t=s[4]-s[1],n=s[5]-s[2];return 2*(e*t+t*n+n*e)}const Ri=32,W3=(s,e)=>s.candidate-e.candidate,$i=new Array(Ri).fill().map(()=>({count:0,bounds:new Float32Array(6),rightCacheBounds:new Float32Array(6),leftCacheBounds:new Float32Array(6),candidate:0})),ul=new Float32Array(6);function X3(s,e,t,n,i,r){let o=-1,a=0;if(r===Hm)o=Zm(e),o!==-1&&(a=(e[o]+e[o+3])/2);else if(r===O3)o=Zm(s),o!==-1&&(a=j3(t,n,i,o));else if(r===F3){const l=Ro(s);let c=gu*i;const h=t.offset||0,u=(n-h)*6,f=(n+i-h)*6;for(let d=0;d<3;d++){const m=e[d],p=(e[d+3]-m)/Ri;if(i=E.candidate?hl(v,t,E.rightCacheBounds):(hl(v,t,E.leftCacheBounds),E.count++)}}for(let v=0;v=Ri&&(v=Ri-1);const y=$i[v];y.count++,hl(b,t,y.bounds)}const x=$i[Ri-1];Ym(x.bounds,x.rightCacheBounds);for(let b=Ri-2;b>=0;b--){const v=$i[b],y=$i[b+1];$m(v.bounds,y.rightCacheBounds,v.rightCacheBounds)}let g=0;for(let b=0;b=l;)a--;if(o=l;)a--;if(oY3)throw new Error("MeshBVH: Cannot store relative child node offset greater than 32 bits.");return dl[t+6]=f,dl[t+7]=l,Mu(h,a)}}function K3(s,e,t){const n=(s.index?s.index.count:s.attributes.position.count)/3>65536,i=t.reduce((c,h)=>c+h.count,0),r=n?4:2,o=e?new SharedArrayBuffer(i*r):new ArrayBuffer(i*r),a=n?new Uint32Array(o):new Uint16Array(o);let l=0;for(let c=0;c=r&&(g=!0,o&&(console.warn(`MeshBVH: Max depth of ${r} reached when generating BVH. Consider increasing maxDepth.`),console.warn(f))),C<=a||_>=r)return v(E+C),M.offset=E,M.count=C,M;const S=X3(M.boundingData,P,e,E,C,l);if(S.axis===-1)return v(E+C),M.offset=E,M.count=C,M;const I=m(u,d,e,E,C,S);if(I===E||I===E+C)v(E+C),M.offset=E,M.count=C;else{M.splitAxis=S.axis;const A=new bu,B=E,w=I-E;M.left=A,vu(e,B,w,A.boundingData,x),y(A,B,w,x,_+1);const F=new bu,W=I,X=C-w;M.right=F,vu(e,W,X,F.boundingData,x),y(F,W,X,x,_+1)}return M}}function Q3(s,e){const t=e.useSharedArrayBuffer?SharedArrayBuffer:ArrayBuffer,n=s.geometry;let i,r;if(e.indirect){const o=jm(n,e.range),a=K3(n,e.useSharedArrayBuffer,o);s._indirectBuffer=a,i=qm(n,0,a.length,a),r=[{offset:0,count:a.length}]}else{G3(n,e);const o=Xm(n,e.range)[0];i=qm(n,o.offset,o.count),r=jm(n,e.range)}s._roots=r.map(o=>{const a=J3(s,i,o.offset,o.count,e),l=_u(a),c=new t(un*l);return $3(0,a,c),c})}class Li{constructor(){this.min=1/0,this.max=-1/0}setFromPointsField(e,t){let n=1/0,i=-1/0;for(let r=0,o=e.length;ri?a:i}this.min=n,this.max=i}setFromPoints(e,t){let n=1/0,i=-1/0;for(let r=0,o=t.length;ri?l:i}this.min=n,this.max=i}isSeparated(e){return this.min>e.max||e.min>this.max}}Li.prototype.setFromBox=(function(){const s=new R;return function(e,t){const n=t.min,i=t.max;let r=1/0,o=-1/0;for(let a=0;a<=1;a++)for(let l=0;l<=1;l++)for(let c=0;c<=1;c++){s.x=n.x*a+i.x*(1-a),s.y=n.y*l+i.y*(1-l),s.z=n.z*c+i.z*(1-c);const h=e.dot(s);r=Math.min(h,r),o=Math.max(h,o)}this.min=r,this.max=o}})();const eS=(function(){const s=new R,e=new R,t=new R;return function(n,i,r){const o=n.start,a=s,l=i.start,c=e;t.subVectors(o,l),s.subVectors(n.end,n.start),e.subVectors(i.end,i.start);const h=t.dot(c),u=c.dot(a),f=c.dot(c),d=t.dot(a),m=a.dot(a)*f-u*u;let p,x;m!==0?p=(h*u-d*f)/m:p=0,x=(h+p*u)/f,r.x=p,r.y=x}})(),wu=(function(){const s=new ue,e=new R,t=new R;return function(n,i,r,o){eS(n,i,s);let a=s.x,l=s.y;if(a>=0&&a<=1&&l>=0&&l<=1){n.at(a,r),i.at(l,o);return}else if(a>=0&&a<=1){l<0?i.at(0,o):i.at(1,o),n.closestPointToPoint(o,!0,r);return}else if(l>=0&&l<=1){a<0?n.at(0,r):n.at(1,r),i.closestPointToPoint(r,!0,o);return}else{let c;a<0?c=n.start:c=n.end;let h;l<0?h=i.start:h=i.end;const u=e,f=t;if(n.closestPointToPoint(h,!0,e),i.closestPointToPoint(c,!0,t),u.distanceToSquared(h)<=f.distanceToSquared(c)){r.copy(u),o.copy(h);return}else{r.copy(c),o.copy(f);return}}}})(),tS=(function(){const s=new R,e=new R,t=new Pt,n=new Bn;return function(i,r){const{radius:o,center:a}=i,{a:l,b:c,c:h}=r;if(n.start=l,n.end=c,n.closestPointToPoint(a,!0,s).distanceTo(a)<=o||(n.start=l,n.end=h,n.closestPointToPoint(a,!0,s).distanceTo(a)<=o)||(n.start=c,n.end=h,n.closestPointToPoint(a,!0,s).distanceTo(a)<=o))return!0;const u=r.getPlane(t);if(Math.abs(u.distanceToPoint(a))<=o){const f=u.projectPoint(a,e);if(r.containsPoint(f))return!0}return!1}})(),nS=["x","y","z"],Ii=1e-15,Qm=Ii*Ii;function Un(s){return Math.abs(s)new R),this.satBounds=new Array(4).fill().map(()=>new Li),this.points=[this.a,this.b,this.c],this.plane=new Pt,this.isDegenerateIntoSegment=!1,this.isDegenerateIntoPoint=!1,this.degenerateSegment=new Bn,this.needsUpdate=!0}intersectsSphere(e){return tS(e,this)}update(){const e=this.a,t=this.b,n=this.c,i=this.points,r=this.satAxes,o=this.satBounds,a=r[0],l=o[0];this.getNormal(a),l.setFromPoints(a,i);const c=r[1],h=o[1];c.subVectors(e,t),h.setFromPoints(c,i);const u=r[2],f=o[2];u.subVectors(t,n),f.setFromPoints(u,i);const d=r[3],m=o[3];d.subVectors(n,e),m.setFromPoints(d,i);const p=c.length(),x=u.length(),g=d.length();this.isDegenerateIntoPoint=!1,this.isDegenerateIntoSegment=!1,p0)d(v.c,v.a,v.b,E,y,M,I,_,S,A,B);else if(P>0)d(v.b,v.a,v.c,M,y,E,S,_,I,A,B);else if(S*I>0||_!=0)d(v.a,v.b,v.c,y,M,E,_,S,I,A,B);else if(S!=0)d(v.b,v.a,v.c,M,y,E,S,_,I,A,B);else if(I!=0)d(v.c,v.a,v.b,E,y,M,I,_,S,A,B);else return!0;return!1}function p(v,y,M,E){const C=y.degenerateSegment,P=v.plane.distanceToPoint(C.start),_=v.plane.distanceToPoint(C.end);return Un(P)?Un(_)?f(v,y,M,E):(M&&(M.start.copy(C.start),M.end.copy(C.start)),v.containsPoint(C.start)):Un(_)?(M&&(M.start.copy(C.end),M.end.copy(C.end)),v.containsPoint(C.end)):v.plane.intersectLine(C,n)!=null?(M&&(M.start.copy(n),M.end.copy(n)),v.containsPoint(n)):!1}function x(v,y,M){const E=y.a;return Un(v.plane.distanceToPoint(E))&&v.containsPoint(E)?(M&&(M.start.copy(E),M.end.copy(E)),!0):!1}function g(v,y,M){const E=v.degenerateSegment,C=y.a;return E.closestPointToPoint(C,!0,n),C.distanceToSquared(n)1||w<0||w>1)return!1;const F=C.start.z+_.z*B,W=P.start.z+S.z*w;return Un(F-W)?(M&&(M.start.copy(C.start).addScaledVector(_,B),M.end.copy(C.start).addScaledVector(_,B)),!0):!1}else return y.isDegenerateIntoPoint?g(v,y,M):p(y,v,M,E);else{if(v.isDegenerateIntoPoint)return y.isDegenerateIntoPoint?y.a.distanceToSquared(v.a)0&&B>0)return!1;let w=C.distanceToPoint(v.a),F=C.distanceToPoint(v.b),W=C.distanceToPoint(v.c);Un(w)&&(w=0),Un(F)&&(F=0),Un(W)&&(W=0);const X=w*F,$=w*W;if(X>0&&$>0)return!1;i.copy(C.normal),r.copy(P.normal);const Z=i.cross(r);let ie=0,j=Math.abs(Z.x);const Y=Math.abs(Z.y);Y>j&&(j=Y,ie=1),Math.abs(Z.z)>j&&(ie=2);const ge=nS[ie],pe=this.a[ge],de=this.b[ge],se=this.c[ge],ce=v.a[ge],fe=v.b[ge],be=v.c[ge];if(m(this,pe,de,se,A,B,_,S,I,h,a))return f(this,v,y,M);if(m(v,ce,fe,be,X,$,w,F,W,u,l))return f(this,v,y,M);if(h.yh.x?y.start.copy(l.start):y.start.copy(a.start),u.ynew R),this.satAxes=new Array(3).fill().map(()=>new R),this.satBounds=new Array(3).fill().map(()=>new Li),this.alignedSatBounds=new Array(3).fill().map(()=>new Li),this.needsUpdate=!1,e&&this.min.copy(e),t&&this.max.copy(t),n&&this.matrix.copy(n)}set(e,t,n){this.min.copy(e),this.max.copy(t),this.matrix.copy(n),this.needsUpdate=!0}copy(e){this.min.copy(e.min),this.max.copy(e.max),this.matrix.copy(e.matrix),this.needsUpdate=!0}}dn.prototype.update=(function(){return function(){const s=this.matrix,e=this.min,t=this.max,n=this.points;for(let l=0;l<=1;l++)for(let c=0;c<=1;c++)for(let h=0;h<=1;h++){const u=1*l|2*c|4*h,f=n[u];f.x=l?t.x:e.x,f.y=c?t.y:e.y,f.z=h?t.z:e.z,f.applyMatrix4(s)}const i=this.satBounds,r=this.satAxes,o=n[0];for(let l=0;l<3;l++){const c=r[l],h=i[l],u=1<new Bn),t=new Array(12).fill().map(()=>new Bn),n=new R,i=new R;return function(r,o=0,a=null,l=null){if(this.needsUpdate&&this.update(),this.intersectsBox(r))return(a||l)&&(r.getCenter(i),this.closestPointToPoint(i,n),r.closestPointToPoint(n,i),a&&a.copy(n),l&&l.copy(i)),0;const c=o*o,h=r.min,u=r.max,f=this.points;let d=1/0;for(let p=0;p<8;p++){const x=f[p];i.copy(x).clamp(h,u);const g=x.distanceToSquared(i);if(gnew On)}}const Fn=new iS;function Zt(s,e){return e[s+15]===Wm}function Tn(s,e){return e[s+6]}function zn(s,e){return e[s+14]}function Qt(s){return s+qt}function en(s,e){const t=e[s+6];return s+t*qt}function Eu(s,e){return e[s+7]}class sS{constructor(){this.float32Array=null,this.uint16Array=null,this.uint32Array=null;const e=[];let t=null;this.setBuffer=n=>{t&&e.push(t),t=n,this.float32Array=new Float32Array(n),this.uint16Array=new Uint16Array(n),this.uint32Array=new Uint32Array(n)},this.clearBuffer=()=>{t=null,this.float32Array=null,this.uint16Array=null,this.uint32Array=null,e.length!==0&&this.setBuffer(e.pop())}}}const yt=new sS;let Ki,Lr;const Ir=[],fl=new Su(()=>new gt);function rS(s,e,t,n,i,r){Ki=fl.getPrimitive(),Lr=fl.getPrimitive(),Ir.push(Ki,Lr),yt.setBuffer(s._roots[e]);const o=Tu(0,s.geometry,t,n,i,r);yt.clearBuffer(),fl.releasePrimitive(Ki),fl.releasePrimitive(Lr),Ir.pop(),Ir.pop();const a=Ir.length;return a>0&&(Lr=Ir[a-1],Ki=Ir[a-2]),o}function Tu(s,e,t,n,i=null,r=0,o=0){const{float32Array:a,uint16Array:l,uint32Array:c}=yt;let h=s*2;if(Zt(h,l)){const u=Tn(s,c),f=zn(h,l);return Lt(s,a,Ki),n(u,f,!1,o,r+s/qt,Ki)}else{let u=function(I){const{uint16Array:A,uint32Array:B}=yt;let w=I*2;for(;!Zt(w,A);)I=Qt(I),w=I*2;return Tn(I,B)},f=function(I){const{uint16Array:A,uint32Array:B}=yt;let w=I*2;for(;!Zt(w,A);)I=en(I,B),w=I*2;return Tn(I,B)+zn(w,A)};const d=Qt(s),m=en(s,c);let p=d,x=m,g,b,v,y;if(i&&(v=Ki,y=Lr,Lt(p,a,v),Lt(x,a,y),g=i(v),b=i(y),b(Lo.copy(e).clamp(h.min,h.max),Lo.distanceToSquared(e)),intersectsBounds:(h,u,f)=>f{h.closestPointToPoint(e,Lo);const f=e.distanceToSquared(Lo);return f=169,aS=parseInt(Hr)<=161,Ss=new R,Es=new R,Ts=new R,ml=new ue,gl=new ue,xl=new ue,eg=new R,tg=new R,ng=new R,Io=new R;function lS(s,e,t,n,i,r,o,a){let l;if(r===ln?l=s.intersectTriangle(n,t,e,!0,i):l=s.intersectTriangle(e,t,n,r!==St,i),l===null)return null;const c=s.origin.distanceTo(i);return ca?null:{distance:c,point:i.clone()}}function ig(s,e,t,n,i,r,o,a,l,c,h){Ss.fromBufferAttribute(e,r),Es.fromBufferAttribute(e,o),Ts.fromBufferAttribute(e,a);const u=lS(s,Ss,Es,Ts,Io,l,c,h);if(u){if(n){ml.fromBufferAttribute(n,r),gl.fromBufferAttribute(n,o),xl.fromBufferAttribute(n,a),u.uv=new ue;const d=xt.getInterpolation(Io,Ss,Es,Ts,ml,gl,xl,u.uv);pl||(u.uv=d)}if(i){ml.fromBufferAttribute(i,r),gl.fromBufferAttribute(i,o),xl.fromBufferAttribute(i,a),u.uv1=new ue;const d=xt.getInterpolation(Io,Ss,Es,Ts,ml,gl,xl,u.uv1);pl||(u.uv1=d),aS&&(u.uv2=u.uv1)}if(t){eg.fromBufferAttribute(t,r),tg.fromBufferAttribute(t,o),ng.fromBufferAttribute(t,a),u.normal=new R;const d=xt.getInterpolation(Io,Ss,Es,Ts,eg,tg,ng,u.normal);u.normal.dot(s.direction)>0&&u.normal.multiplyScalar(-1),pl||(u.normal=d)}const f={a:r,b:o,c:a,normal:new R,materialIndex:0};if(xt.getNormal(Ss,Es,Ts,f.normal),u.face=f,u.faceIndex=r,pl){const d=new R;xt.getBarycoord(Io,Ss,Es,Ts,d),u.barycoord=d}}return u}function sg(s){return s&&s.isMaterial?s.side:s}function vl(s,e,t,n,i,r,o){const a=n*3;let l=a+0,c=a+1,h=a+2;const{index:u,groups:f}=s;s.index&&(l=u.getX(l),c=u.getX(c),h=u.getX(h));const{position:d,normal:m,uv:p,uv1:x}=s.attributes;if(Array.isArray(e)){const g=n*3;for(let b=0,v=f.length;b=y&&gM&&(M=I),AE&&(E=A),BC&&(C=B)}return l[f+0]!==b||l[f+1]!==v||l[f+2]!==y||l[f+3]!==M||l[f+4]!==E||l[f+5]!==C?(l[f+0]=b,l[f+1]=v,l[f+2]=y,l[f+3]=M,l[f+4]=E,l[f+5]=C,!0):!1}else{const x=Qt(f),g=en(f,o);let b=m,v=!1,y=!1;if(e){if(!b){const S=x/qt+d/un,I=g/qt+d/un;v=e.has(S),y=e.has(I),b=!v&&!y}}else v=!0,y=!0;const M=b||v,E=b||y;let C=!1;M&&(C=u(x,d,b));let P=!1;E&&(P=u(g,d,b));const _=C||P;if(_)for(let S=0;S<3;S++){const I=x+S,A=g+S,B=l[I],w=l[I+3],F=l[A],W=l[A+3];l[f+S]=BW?w:W}return _}}}function Ji(s,e,t,n,i){let r,o,a,l,c,h;const u=1/t.direction.x,f=1/t.direction.y,d=1/t.direction.z,m=t.origin.x,p=t.origin.y,x=t.origin.z;let g=e[s],b=e[s+3],v=e[s+1],y=e[s+3+1],M=e[s+2],E=e[s+3+2];return u>=0?(r=(g-m)*u,o=(b-m)*u):(r=(b-m)*u,o=(g-m)*u),f>=0?(a=(v-p)*f,l=(y-p)*f):(a=(y-p)*f,l=(v-p)*f),r>l||a>o||((a>r||isNaN(r))&&(r=a),(l=0?(c=(M-x)*d,h=(E-x)*d):(c=(E-x)*d,h=(M-x)*d),r>h||c>o)?!1:((c>r||r!==r)&&(r=c),(h=n)}function fS(s,e,t,n,i,r,o,a){const{geometry:l,_indirectBuffer:c}=s;for(let h=n,u=n+i;h=0;let d,m;f?(d=Qt(s),m=en(s,l)):(d=en(s,l),m=Qt(s));const p=Ji(d,o,n,i,r)?Pu(d,e,t,n,i,r):null;if(p){const g=p.point[u];if(f?g<=o[m+h]:g>=o[m+h+3])return p}const x=Ji(m,o,n,i,r)?Pu(m,e,t,n,i,r):null;return p&&x?p.distance<=x.distance?p:x:p||x||null}}const bl=new gt,Dr=new On,Br=new On,Do=new De,rg=new dn,yl=new dn;function bS(s,e,t,n){yt.setBuffer(s._roots[e]);const i=Ru(0,s,t,n);return yt.clearBuffer(),i}function Ru(s,e,t,n,i=null){const{float32Array:r,uint16Array:o,uint32Array:a}=yt;let l=s*2;if(i===null&&(t.boundingBox||t.computeBoundingBox(),rg.set(t.boundingBox.min,t.boundingBox.max,n),i=rg),Zt(l,o)){const c=e.geometry,h=c.index,u=c.attributes.position,f=t.index,d=t.attributes.position,m=Tn(s,a),p=zn(l,o);if(Do.copy(n).invert(),t.boundsTree)return Lt(s,r,yl),yl.matrix.copy(Do),yl.needsUpdate=!0,t.boundsTree.shapecast({intersectsBounds:x=>yl.intersectsBox(x),intersectsTriangle:x=>{x.a.applyMatrix4(n),x.b.applyMatrix4(n),x.c.applyMatrix4(n),x.needsUpdate=!0;for(let g=m*3,b=(p+m)*3;gLu.distanceToBox(M),intersectsBounds:(M,E,C)=>C{if(e.boundsTree)return e.boundsTree.shapecast({boundsTraverseOrder:C=>Bo.distanceToBox(C),intersectsBounds:(C,P,_)=>_{for(let _=C,S=C+P;_M&&(M=B),wE&&(E=w),FC&&(C=F)}}return l[f+0]!==b||l[f+1]!==v||l[f+2]!==y||l[f+3]!==M||l[f+4]!==E||l[f+5]!==C?(l[f+0]=b,l[f+1]=v,l[f+2]=y,l[f+3]=M,l[f+4]=E,l[f+5]=C,!0):!1}else{const x=Qt(f),g=en(f,o);let b=m,v=!1,y=!1;if(e){if(!b){const S=x/qt+d/un,I=g/qt+d/un;v=e.has(S),y=e.has(I),b=!v&&!y}}else v=!0,y=!0;const M=b||v,E=b||y;let C=!1;M&&(C=u(x,d,b));let P=!1;E&&(P=u(g,d,b));const _=C||P;if(_)for(let S=0;S<3;S++){const I=x+S,A=g+S,B=l[I],w=l[I+3],F=l[A],W=l[A+3];l[f+S]=BW?w:W}return _}}}function TS(s,e,t,n,i,r,o){yt.setBuffer(s._roots[e]),Iu(0,s,t,n,i,r,o),yt.clearBuffer()}function Iu(s,e,t,n,i,r,o){const{float32Array:a,uint16Array:l,uint32Array:c}=yt,h=s*2;if(Zt(h,l)){const u=Tn(s,c),f=zn(h,l);fS(e,t,n,u,f,i,r,o)}else{const u=Qt(s);Ji(u,a,n,r,o)&&Iu(u,e,t,n,i,r,o);const f=en(s,c);Ji(f,a,n,r,o)&&Iu(f,e,t,n,i,r,o)}}const CS=["x","y","z"];function AS(s,e,t,n,i,r){yt.setBuffer(s._roots[e]);const o=Du(0,s,t,n,i,r);return yt.clearBuffer(),o}function Du(s,e,t,n,i,r){const{float32Array:o,uint16Array:a,uint32Array:l}=yt;let c=s*2;if(Zt(c,a)){const h=Tn(s,l),u=zn(c,a);return pS(e,t,n,h,u,i,r)}else{const h=Eu(s,l),u=CS[h],f=n.direction[u]>=0;let d,m;f?(d=Qt(s),m=en(s,l)):(d=en(s,l),m=Qt(s));const p=Ji(d,o,n,i,r)?Du(d,e,t,n,i,r):null;if(p){const g=p.point[u];if(f?g<=o[m+h]:g>=o[m+h+3])return p}const x=Ji(m,o,n,i,r)?Du(m,e,t,n,i,r):null;return p&&x?p.distance<=x.distance?p:x:p||x||null}}const Ml=new gt,Nr=new On,kr=new On,No=new De,og=new dn,wl=new dn;function PS(s,e,t,n){yt.setBuffer(s._roots[e]);const i=Bu(0,s,t,n);return yt.clearBuffer(),i}function Bu(s,e,t,n,i=null){const{float32Array:r,uint16Array:o,uint32Array:a}=yt;let l=s*2;if(i===null&&(t.boundingBox||t.computeBoundingBox(),og.set(t.boundingBox.min,t.boundingBox.max,n),i=og),Zt(l,o)){const c=e.geometry,h=c.index,u=c.attributes.position,f=t.index,d=t.attributes.position,m=Tn(s,a),p=zn(l,o);if(No.copy(n).invert(),t.boundsTree)return Lt(s,r,wl),wl.matrix.copy(No),wl.needsUpdate=!0,t.boundsTree.shapecast({intersectsBounds:x=>wl.intersectsBox(x),intersectsTriangle:x=>{x.a.applyMatrix4(n),x.b.applyMatrix4(n),x.c.applyMatrix4(n),x.needsUpdate=!0;for(let g=m,b=p+m;gNu.distanceToBox(M),intersectsBounds:(M,E,C)=>C{if(e.boundsTree){const C=e.boundsTree;return C.shapecast({boundsTraverseOrder:P=>ko.distanceToBox(P),intersectsBounds:(P,_,S)=>S{for(let S=P,I=P+_;Snew gt),Ur=new gt,Or=new gt,ku=new gt,Uu=new gt;let Ou=!1;function kS(s,e,t,n){if(Ou)throw new Error("MeshBVH: Recursive calls to bvhcast not supported.");Ou=!0;const i=s._roots,r=e._roots;let o,a=0,l=0;const c=new De().copy(t).invert();for(let h=0,u=i.length;hl.slice()),a.index=o?o.array.slice():null,a.indirectBuffer=r?r.slice():null):(a.roots=i,a.index=o?o.array:null,a.indirectBuffer=r),a}static deserialize(e,t,n={}){n={setIndex:!0,indirect:!!e.indirectBuffer,...n};const{index:i,roots:r,indirectBuffer:o}=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 a=new Fu(t,{...n,[xu]:!0});if(a._roots=r,a._indirectBuffer=o||null,n.setIndex){const c=t.getIndex();if(c===null){const h=new vt(e.index,1,!1);t.setIndex(h)}else c.array!==i&&(c.array.set(i),c.needsUpdate=!0)}return a;function l(c){for(let h=0;hthis._indirectBuffer[n]:n=>n}shiftTriangleOffsets(e){const t=this._indirectBuffer;if(t)for(let n=0,i=t.length;nu(f,d,m,p,x)?!0:n(f,d,this,a,m,p,t)}else o||(a?o=(u,f,d,m)=>n(u,f,this,a,d,m,t):o=(u,f,d)=>d);let l=!1,c=0;const h=this._roots;for(let u=0,f=h.length;u{const p=this.resolveTriangleIndex(m);Ut(o,p*3,a,l)}:m=>{Ut(o,m*3,a,l)},h=Fn.getPrimitive(),u=e.geometry.index,f=e.geometry.attributes.position,d=e.indirect?m=>{const p=e.resolveTriangleIndex(m);Ut(h,p*3,u,f)}:m=>{Ut(h,m*3,u,f)};if(r){const m=(p,x,g,b,v,y,M,E)=>{for(let C=g,P=g+b;CTl.intersectsBox(n),intersectsTriangle:n=>Tl.intersectsTriangle(n)})}intersectsSphere(e){return this.shapecast({intersectsBounds:t=>e.intersectsBox(t),intersectsTriangle:t=>t.intersectsSphere(e)})}closestPointToGeometry(e,t,n={},i={},r=0,o=1/0){return(this.indirect?BS:SS)(this,e,t,n,i,r,o)}closestPointToPoint(e,t={},n=0,i=1/0){return oS(this,e,t,n,i)}getBoundingBox(e){return e.makeEmpty(),this._roots.forEach(t=>{Lt(0,new Float32Array(t),ag),e.union(ag)}),e}}const lg=1e-6,OS=lg*.5,cg=Math.pow(10,-Math.log10(lg)),FS=OS*cg;function di(s){return~~(s*cg+FS)}function zS(s){return`${di(s.x)},${di(s.y)}`}function hg(s){return`${di(s.x)},${di(s.y)},${di(s.z)}`}function HS(s){return`${di(s.x)},${di(s.y)},${di(s.z)},${di(s.w)}`}function VS(s,e,t){t.direction.subVectors(e,s).normalize();const n=s.dot(t.direction);return t.origin.copy(s).addScaledVector(t.direction,-n),t}function ug(){return typeof SharedArrayBuffer<"u"}function GS(s){if(s.buffer instanceof SharedArrayBuffer)return s;const e=s.constructor,t=s.buffer,n=new SharedArrayBuffer(t.byteLength),i=new Uint8Array(t);return new Uint8Array(n).set(i,0),new e(n)}function WS(s,e=ArrayBuffer){return s>65535?new Uint32Array(new e(4*s)):new Uint16Array(new e(2*s))}function XS(s,e){if(!s.index){const t=s.attributes.position.count,n=e.useSharedArrayBuffer?SharedArrayBuffer:ArrayBuffer,i=WS(t,n);s.setIndex(new vt(i,1));for(let r=0;rl.end)){if(l.end=h.end)r(h.end,l.end)||s.splice(a+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 u=l.end;l.end=h.start,h.start=u}else if(l.start>=h.start&&l.end>=h.end){const u=h.end;h.end=l.start,l.start=u}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),o(h)&&(e.splice(c,1),c--),o(l)){s.splice(a,1),a--;break}}}i(s),i(e);function i(a){for(let l=0;lpg;return l.direction.angleTo(c.direction)>mg||h}function a(l,c){const h=l.origin.distanceTo(c.origin),u=l.direction.angleTo(c.direction);return h/pg+u/mg}}}const Hu=new R,Vu=new R,Cl=new Hi;function QS(s,e,t){const n=s.attributes,i=s.index,r=n.position,o=new Map,a=new Map,l=Array.from(e),c=new JS;for(let h=0,u=l.length;hy&&([v,y]=[y,v]),Cl.direction.dot(b.direction)<0?g.reverse.push({start:v,end:y,index:f}):g.forward.push({start:v,end:y,index:f})}return a.forEach(({forward:h,reverse:u},f)=>{KS(h,u,o,t),h.length===0&&u.length===0&&a.delete(f)}),{disjointConnectivityMap:o,fragmentMap:a}}const eE=new ue,Gu=new R,tE=new tt,Wu=["","",""];class nE{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 n=this.data[e*3+t];return n===-1?-1:~~(n/3)}getSiblingEdgeIndex(e,t){const n=this.data[e*3+t];return n===-1?-1:n%3}getDisjointSiblingTriangleIndices(e,t){const n=e*3+t,i=this.disjointConnections.get(n);return i?i.map(r=>~~(r/3)):[]}getDisjointSiblingEdgeIndices(e,t){const n=e*3+t,i=this.disjointConnections.get(n);return i?i.map(r=>r%3):[]}isFullyConnected(){return this.unmatchedEdges===0}updateFrom(e){const{useAllAttributes:t,useDrawRange:n,matchDisjointEdges:i,degenerateEpsilon:r}=this,o=t?v:b,a=new Map,{attributes:l}=e,c=t?Object.keys(l):null,h=e.index,u=l.position;let f=zu(e);const d=f;let m=0;n&&(m=e.drawRange.start,e.drawRange.count!==1/0&&(f=~~(e.drawRange.count/3)));let p=this.data;(!p||p.length<3*d)&&(p=new Int32Array(3*d)),p.fill(-1);let x=0,g=new Set;for(let y=m,M=f*3+m;y{E.forEach(({index:P})=>g.add(P)),C.forEach(({index:P})=>g.add(P))}),this.unmatchedDisjointEdges=y,this.disjointConnections=M,x=f*3-g.size}this.matchedEdges=x,this.unmatchedEdges=g.size,this.data=p;function b(y){return Gu.fromBufferAttribute(u,y),hg(Gu)}function v(y){let M="";for(let E=0,C=c.length;E=this._pool.length&&this._pool.push(new xt),this._pool[this._index++]}clear(){this._index=0}reset(){this._pool.length=0,this._index=0}}class oE{constructor(){this.trianglePool=new rE,this.triangles=[],this.normal=new R,this.coplanarTriangleUsed=!1}initialize(e){this.reset();const{triangles:t,trianglePool:n,normal:i}=this;if(Array.isArray(e))for(let r=0,o=e.length;rju)throw new Error("Triangle Splitter: Cannot initialize with triangles that have different normals.");const l=n.getTriangle();l.copy(a),t.push(l)}else{e.getNormal(i);const r=n.getTriangle();r.copy(e),t.push(r)}}splitByTriangle(e){const{normal:t,triangles:n}=this;if(e.getNormal(qu).normalize(),Math.abs(1-Math.abs(qu.dot(t)))0?m.push(g):p.push(g),Math.abs(v)Oo)if(f!==-1){f=(f+1)%3;let g=0;g===f&&(g=(g+1)%3);let b=g+1;b===f&&(b=(b+1)%3);const v=i.getTriangle();v.a.copy(x[b]),v.b.copy(Bt.end),v.c.copy(Bt.start),es(v)||n.push(v),a.a.copy(x[g]),a.b.copy(Bt.start),a.c.copy(Bt.end),es(a)&&(n.splice(r,1),r--,o--)}else{const g=m.length>=2?p[0]:m[0];if(g===0){let E=Bt.start;Bt.start=Bt.end,Bt.end=E}const b=(g+1)%3,v=(g+2)%3,y=i.getTriangle(),M=i.getTriangle();x[b].distanceToSquared(Bt.start)t.length&&(this.expand(),t=this.array);for(let i=0,r=e.length;i=t.length;){const i={};t.push(i);for(const r in n){const o=n[r],a=new bg(o.type);a.itemSize=o.itemSize,a.normalized=o.normalized,i[r]=a}}return t[e]}getGroupAttrArray(e,t=0){const{groupAttributes:n}=this;if(!n[0][e])throw new Error(`TypedAttributeData: Attribute with "${e}" has not been initialized`);return this.getGroupAttrSet(t)[e]}initializeArray(e,t,n,i){const{groupAttributes:r}=this,o=r[0][e];if(o){if(o.type!==t)for(let a=0,l=r.length;a{for(const n in t)t[n].clear()})}delete(e){this.groupAttributes.forEach(t=>{delete t[e]})}reset(){this.groupAttributes=[],this.groupCount=0}}class yg{constructor(){this.intersectionSet={},this.ids=[]}add(e,t){const{intersectionSet:n,ids:i}=this;n[e]||(n[e]=[],i.push(e)),n[e].push(t)}}const cE=0,hE=1,uE=2,_g=3,dE=4,Mg=5,wg=6,Hn=new Hi,Sg=new De,fn=new xt,Ni=new R,Eg=new tt,Tg=new tt,Cg=new tt,Yu=new tt,Rl=new tt,Ll=new tt,Ag=new Bn,$u=new R,Ku=1e-8,fE=1e-15,Cs=-1,As=1,Il=-2,Dl=2,Fo=0,Ps=1,Ju=2,pE=1e-14;let Bl=null;function Pg(s){Bl=s}function Rg(s,e){s.getMidpoint(Hn.origin),s.getNormal(Hn.direction);const t=e.raycastFirst(Hn,St);return t&&Hn.direction.dot(t.face.normal)>0?Cs:As}function mE(s,e){function t(){return Math.random()-.5}s.getNormal($u),Hn.direction.copy($u),s.getMidpoint(Hn.origin);const n=3;let i=0,r=1/0;for(let o=0;o0&&i++,a!==null&&(r=Math.min(r,a.distance)),r<=fE)return a.face.normal.dot($u)>0?Dl:Il;if(i/n>.5||(o-i+1)/n>.5)break}return i/n>.5?Cs:As}function gE(s,e){const t=new yg,n=new yg;return Sg.copy(s.matrixWorld).invert().multiply(e.matrixWorld),s.geometry.boundsTree.bvhcast(e.geometry.boundsTree,Sg,{intersectsTriangles(i,r,o,a){if(!es(i)&&!es(r)){let l=i.intersectsTriangle(r,Ag,!0);if(!l){const c=i.plane,h=r.plane,u=c.normal,f=h.normal;u.dot(f)===1&&Math.abs(c.constant-h.constant){r.push(c.x),i>1&&r.push(c.y),i>2&&r.push(c.z),i>3&&r.push(c.w)};Yu.set(0,0,0,0).addScaledVector(s,n.a.x).addScaledVector(e,n.a.y).addScaledVector(t,n.a.z),Rl.set(0,0,0,0).addScaledVector(s,n.b.x).addScaledVector(e,n.b.y).addScaledVector(t,n.b.z),Ll.set(0,0,0,0).addScaledVector(s,n.c.x).addScaledVector(e,n.c.y).addScaledVector(t,n.c.z),a&&(Yu.normalize(),Rl.normalize(),Ll.normalize()),l(Yu),o?(l(Ll),l(Rl)):(l(Rl),l(Ll))}function ed(s,e,t,n,i,r=!1){for(const o in i){const a=e[o],l=i[o];if(!(o in e))throw new Error(`CSG Operations: Attribute ${o} no available on geometry.`);const c=a.itemSize;o==="position"?(Ni.fromBufferAttribute(a,s).applyMatrix4(t),l.push(Ni.x,Ni.y,Ni.z)):o==="normal"?(Ni.fromBufferAttribute(a,s).applyNormalMatrix(n),r&&Ni.multiplyScalar(-1),l.push(Ni.x,Ni.y,Ni.z)):(l.push(a.getX(s)),c>1&&l.push(a.getY(s)),c>2&&l.push(a.getZ(s)),c>3&&l.push(a.getW(s)))}}class bE{constructor(e){this.triangle=new xt().copy(e),this.intersects={}}addTriangle(e,t){this.intersects[e]=new xt().copy(t)}getIntersectArray(){const e=[],{intersects:t}=this;for(const n in t)e.push(t[n]);return e}}class Ig{constructor(){this.data={}}addTriangleIntersection(e,t,n,i){const{data:r}=this;r[e]||(r[e]=new bE(t)),r[e].addTriangle(n,i)}getTrianglesAsArray(e=null){const{data:t}=this,n=[];if(e!==null)e in t&&n.push(t[e].triangle);else for(const i in t)n.push(t[i].triangle);return n}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(n=>parseInt(n)):[]}getIntersectionsAsArray(e=null,t=null){const{data:n}=this,i=new Set,r=[],o=a=>{if(n[a])if(t!==null)n[a].intersects[t]&&r.push(n[a].intersects[t]);else{const l=n[a].intersects;for(const c in l)i.has(c)||(i.add(c),r.push(l[c]))}};if(e!==null)o(e);else for(const a in n)o(a);return r}reset(){this.data={}}}class yE{constructor(){this.enabled=!1,this.triangleIntersectsA=new Ig,this.triangleIntersectsB=new Ig,this.intersectionEdges=[]}addIntersectingTriangles(e,t,n,i){const{triangleIntersectsA:r,triangleIntersectsB:o}=this;r.addTriangleIntersection(e,t,n,i),o.addTriangleIntersection(n,i,e,t)}addEdge(e){this.intersectionEdges.push(e.clone())}reset(){this.triangleIntersectsA.reset(),this.triangleIntersectsB.reset(),this.intersectionEdges=[]}init(){this.enabled&&(this.reset(),Pg(this))}complete(){this.enabled&&Pg(null)}}const ts=new De,Nl=new $e,Rs=new xt,kl=new xt,ns=new xt,Ul=new xt,ei=[],Ls=[];function _E(s){for(const e of s)return e}function ME(s,e,t,n,i,r={}){const{useGroups:o=!0}=r,{aIntersections:a,bIntersections:l}=gE(s,e),c=[];let h=null,u;return u=o?0:-1,Dg(s,e,a,t,!1,n,i,u),Bg(s,e,a,t,!1,i,u),t.findIndex(f=>f!==wg&&f!==Mg)!==-1&&(u=o?s.geometry.groups.length||1:-1,Dg(e,s,l,t,!0,n,i,u),Bg(e,s,l,t,!0,i,u)),ei.length=0,Ls.length=0,{groups:c,materials:h}}function Dg(s,e,t,n,i,r,o,a=0){const l=s.matrixWorld.determinant()<0;ts.copy(e.matrixWorld).invert().multiply(s.matrixWorld),Nl.getNormalMatrix(s.matrixWorld).multiplyScalar(l?-1:1);const c=s.geometry.groupIndices,h=s.geometry.index,u=s.geometry.attributes.position,f=e.geometry.boundsTree,d=e.geometry.index,m=e.geometry.attributes.position,p=t.ids,x=t.intersectionSet;for(let g=0,b=p.length;g0;){const g=_E(p);p.delete(g),d.push(g);const b=3*g,v=h.getX(b+0),y=h.getX(b+1),M=h.getX(b+2);ns.a.fromBufferAttribute(f,v).applyMatrix4(ts),ns.b.fromBufferAttribute(f,y).applyMatrix4(ts),ns.c.fromBufferAttribute(f,M).applyMatrix4(ts);const E=Rg(ns,l);Ls.length=0,ei.length=0;for(let C=0,P=n.length;C0;){const C=d.pop();for(let P=0;P<3;P++){const _=m.getSiblingTriangleIndex(C,P);_!==-1&&p.has(_)&&(d.push(_),p.delete(_))}if(ei.length!==0){const P=3*C,_=h.getX(P+0),S=h.getX(P+1),I=h.getX(P+2),A=o===-1?0:c[C]+o;if(ns.a.fromBufferAttribute(f,_),ns.b.fromBufferAttribute(f,S),ns.c.fromBufferAttribute(f,I),!es(ns))for(let B=0,w=ei.length;B{t[n.materialIndex]=e})),t}class TE{constructor(){this.triangleSplitter=new oE,this.attributeData=[],this.attributes=["position","uv","normal"],this.useGroups=!0,this.consolidateGroups=!0,this.debug=new yE}getGroupRanges(e){return!this.useGroups||e.groups.length===0?[{start:0,count:1/0,materialIndex:0}]:e.groups.map(t=>({...t}))}evaluate(e,t,n,i=new Al){let r=!0;if(Array.isArray(n)||(n=[n]),Array.isArray(i)||(i=[i],r=!1),i.length!==n.length)throw new Error("Evaluator: operations and target array passed as different sizes.");e.prepareGeometry(),t.prepareGeometry();const{triangleSplitter:o,attributeData:a,attributes:l,useGroups:c,consolidateGroups:h,debug:u}=this;for(;a.length{SE(e.geometry,g.geometry,a[b],l)}),u.init(),ME(e,t,n,o,a,{useGroups:c}),u.complete();const f=this.getGroupRanges(e.geometry),d=Ng(f,e.material),m=this.getGroupRanges(t.geometry),p=Ng(m,t.material);m.forEach(g=>g.materialIndex+=d.length);let x=[...f,...m].map((g,b)=>({...g,index:b}));if(c){const g=[...d,...p];h&&(x=x.map(v=>{const y=g[v.materialIndex];return v.materialIndex=g.indexOf(y),v}).sort((v,y)=>v.materialIndex-y.materialIndex));const b=[];for(let v=0,y=g.length;v{v.material=b})}else x=[{start:0,count:1/0,index:0,materialIndex:0}],i.forEach(g=>{g.material=d[0]});return i.forEach((g,b)=>{const v=g.geometry;EE(v,a[b],x),h&&wE(v.groups)}),r?i:i[0]}evaluateHierarchy(e,t=new Al){e.updateMatrixWorld(!0);const n=(r,o)=>{const a=r.children;for(let l=0,c=a.length;l{const o=r.children;let a=!1;for(let c=0,h=o.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 a||l};return i(e),t.geometry=e._cachedGeometry,t.material=e._cachedMaterials,t}reset(){this.triangleSplitter.reset()}}class CE{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 TE,this.planeGroup=new Dn,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 n=this.createEmptySectionMesh(e,t);this.planeGroup.add(n),this.sectionMeshes.set(`plane_${t}`,n),this.planeObjects.push(n),this.planeStates.set(t,{constant:e.constant,normal:e.normal.clone()})})}createEmptySectionMesh(e,t){const n=new bt,i=new ds({color:new He(33023),metalness:.1,roughness:.75,side:St,depthWrite:!0,depthTest:!0,clippingPlanes:this.planes.filter((o,a)=>a!==t)}),r=new ht(n,i);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 n=t.uuid;this.sourceMeshes.set(n,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 n=this.sectionMeshes.get(`plane_${t}`);n&&(n.visible=!1)}}),this.cleanExpiredCache())}hasPlaneChanged(e,t){const n=this.planeStates.get(e);if(!n)return!0;const i=Math.abs(n.constant-t.constant)>1e-4,r=!n.normal.equals(t.normal);return i||r}updatePlaneState(e,t){this.planeStates.set(e,{constant:t.constant,normal:t.normal.clone()})}getPlaneHash(e){const t=e.normal,n=e.constant;return`${t.x.toFixed(4)}_${t.y.toFixed(4)}_${t.z.toFixed(4)}_${n.toFixed(4)}`}getCacheKey(e,t){return`${e}_plane_${t}`}updateSection(e,t){const n=this.sectionMeshes.get(`plane_${t}`);if(!n)return;const i=this.getPlaneHash(e),r=[];if(this.sourceMeshes.forEach((o,a)=>{const l=this.getCacheKey(a,t),c=this.geometryCache.get(l);if(c&&c.planeHash===i)r.push(c.geometry.clone()),c.timestamp=Date.now();else try{const h=this.createPlaneBrush(e),u=new Al(o.geometry);o.updateMatrixWorld(!0),u.matrix.copy(o.matrixWorld),u.updateMatrixWorld();const f=this.evaluator.evaluate(h,u,_g);f&&f.geometry.attributes.position.count>0?(r.push(f.geometry),this.geometryCache.set(l,{geometry:f.geometry.clone(),planeHash:i,timestamp:Date.now()})):this.geometryCache.delete(l)}catch(h){console.warn(`CSG intersection failed for mesh ${a}:`,h)}}),r.length>0){const o=this.mergeGeometries(r);n.geometry&&n.geometry.dispose(),n.geometry=o,n.visible=!0,n.position.set(0,0,0),n.rotation.set(0,0,0),n.scale.set(1,1,1),n.updateMatrixWorld()}else n.visible=!1;r.forEach(o=>o.dispose())}clearMeshCache(e){const t=[];this.geometryCache.forEach((n,i)=>{i.startsWith(e)&&(n.geometry.dispose(),t.push(i))}),t.forEach(n=>this.geometryCache.delete(n))}cleanExpiredCache(){const e=Date.now(),t=[];this.geometryCache.forEach((n,i)=>{e-n.timestamp>this.cacheExpireTime&&(n.geometry.dispose(),t.push(i))}),t.forEach(n=>this.geometryCache.delete(n))}clearAllCache(){this.geometryCache.forEach(e=>{e.geometry.dispose()}),this.geometryCache.clear()}createPlaneBrush(e){const t=new Wi(this.planeSize,this.planeThickness,this.planeSize);t.translate(0,e.constant,0),t.applyQuaternion(new Ln().setFromUnitVectors(new R(0,-1,0),e.normal));const n=new ht(t),i=new Al(t);return i.matrix.copy(n.matrixWorld),i.updateMatrixWorld(),i}mergeGeometries(e){if(e.length===1)return e[0].clone();const t=new bt,n=[],i=[],r=[];let o=0;return e.forEach(a=>{const l=a.attributes.position,c=a.attributes.normal;for(let h=0;h0?t.setAttribute("normal",new rn(i,3)):t.computeVertexNormals(),r.length>0&&t.setIndex(r),t}calculateSceneSize(){const e=new gt;if(this.engine.scene.traverse(t=>{if(t.isMesh&&t.geometry){const n=new gt().setFromObject(t);e.union(n)}}),e.isEmpty())this.planeSize=1e3;else{const t=e.getSize(new R),n=Math.max(t.x,t.y,t.z);this.planeSize=n*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 ds&&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 AE{engine;isActive=!1;box;pickPoint;pickNormal;pickMesh;box_;plane;meshs;isDrag=!1;maxBox;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 CE(this.engine,{updateThrottleTime:150,cacheExpireTime:45e3}),this.csgClipping.planes=this.engine.sectionPlane,this.csgClipping.init()}active(){this.isActive||(this.engine.handelBehaved.init(this),this.engine.handelBehaved.active(),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.engine.handelBehaved.disActive(),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)})}),this.engine.interactionModule.init(),this.engine.interactionModule.active()}disabled(){this.isActive=!1,this.engine.handelBehaved.disActive(),this.engine.interactionModule.init(),this.engine.interactionModule.active(),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.engine.handelBehaved.init(this),this.engine.handelBehaved.active(),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();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.meshs,!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 n=new Pt;n.setFromNormalAndCoplanarPoint(new R(0,1,0),this.pickPoint),this.plane=n}else{let n=new R(this.engine.camera.position.x,this.pickPoint.y,this.engine.camera.position.z);const i=new Pt;i.setFromNormalAndCoplanarPoint(n.clone().sub(this.pickPoint.clone()).setLength(1),this.pickPoint),this.plane=i}}handleMouseUp(e){this.isDrag=!1,this.pickPoint=null,this.pickNormal=null,this.pickMesh=null,this.engine.controls.enabled=!0,this.csgClipping&&this.isActive}handleMouseMove(e){this.meshs.forEach(n=>{n.material.opacity=0});const t=e.raycaster.intersectObjects(this.meshs,!1);if(t!=null&&t.length>0&&(t[0].object.material.opacity=.05),this.pickPoint!=null){const n=new R;if(e.raycaster.ray.intersectPlane(this.plane,n)){let i=n.clone().sub(this.pickPoint.clone()).dot(this.pickNormal.clone());this.pickMesh.name=="前"||this.pickMesh.name=="左"||this.pickMesh.name=="底"?this.box.min=this.box_.min.clone().add(this.pickNormal.clone().setLength(i)):this.box.max=this.box_.max.clone().add(this.pickNormal.clone().setLength(i)),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,n=this.maxBox.max.z-this.maxBox.min.z,i=(this.box.min.x-this.maxBox.min.x)/e*100,r=(this.box.max.x-this.maxBox.min.x)/e*100,o=(this.box.min.y-this.maxBox.min.y)/t*100,a=(this.box.max.y-this.maxBox.min.y)/t*100,l=(this.box.min.z-this.maxBox.min.z)/n*100,c=(this.box.max.z-this.maxBox.min.z)/n*100;i<0&&(i=0),r<0&&(r=0),o<0&&(o=0),a<0&&(a=0),l<0&&(l=0),c<0&&(c=0),i>100&&(i=100),r>100&&(r=100),o>100&&(o=100),a>100&&(a=100),l>100&&(l=100),c>100&&(c=100);let h={x:{min:i,max:r},y:{min:o,max:a},z:{min:l,max:c}};this.engine.events.trigger(Gt.SectionMove,h)}updata_face(e){let t=this,n=[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)],i=[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)],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)],o=[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)],a=[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)],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(n,new R(0,0,-1),"前"),c(i,new R(0,0,1),"后"),c(r,new R(1,0,0),"右"),c(o,new R(-1,0,0),"左"),c(a,new R(0,1,0),"顶"),c(l,new R(0,-1,0),"底");function c(h,u,f){const d=new bt,m=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]),p=[0,1,2,0,2,3];d.setAttribute("position",new vt(m,3)),d.setIndex(p);let x=t.engine.scene.children.find(E=>E.type=="Group"&&E.name=="ClippingBox");x==null&&(x=new Dn,x.name="ClippingBox",t.engine.scene.add(x));let g=t.meshs.find(E=>E.name==f);if(g==null){const E=new Xt({color:65280,transparent:!0,opacity:0,side:St}),C=new ht(d,E);C.normal=u,C.name=f,x.add(C),t.meshs.push(C)}else g.geometry=d;const b=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 v=new lo({color:255}),y=new bt;y.setAttribute("position",new vt(b,3));let M=t.meshs.find(E=>E.name==f+"Line");M==null&&(M=new dr(y,v),M.name=f+"Line",x.add(M),t.meshs.push(M)),M.geometry=y,M.material=v,f=="前"||f=="左"||f=="底"?t.engine.sectionPlane.find(E=>E.name==f).setFromNormalAndCoplanarPoint(u.clone().setLength(-1),e.min):t.engine.sectionPlane.find(E=>E.name==f).setFromNormalAndCoplanarPoint(u.clone().setLength(-1),e.max),t.engine.scene.children.filter(E=>E.type=="Mesh"&&E.url).forEach(E=>{E.material&&Array.isArray(E.material)?E.material.forEach(C=>{C.clippingPlanes=t.engine.sectionPlane}):E.material.clippingPlanes=t.engine.sectionPlane})}}}class PE{engine;isActive=!1;isDrag=!1;meshs=[];box;pickPoint;pickNormal;pickMesh;box_;plane;angleX=0;angleY=0;angleZ=0;direction=1;normal=new R(0,0,1);distance=0;center=null;current_center=null;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(n=>{n.name.includes("face")&&(n.visible=!0)})}),this.engine.handelBehaved.init(this),this.engine.handelBehaved.active();let e=this;e.engine.scene.children.filter(t=>t.type=="Mesh"&&t.url).forEach(t=>{t.material&&Array.isArray(t.material)?t.material.forEach(n=>{n.clippingPlanes=e.engine.sectionPlane}):t.material.clippingPlanes=e.engine.sectionPlane,e.engine.clipping.clippingStencil?.addMesh(e.engine.sectionPlane.find(n=>n.name=="face"),t)}),this.init()}disActive(){this.init(),this.isActive=!1,this.engine.handelBehaved.disActive();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(n=>{n.name.includes("face")&&(n.visible=!1)})})}init(){let e=this.engine.octreeBox.getBoundingBox();this.box=e,this.updata_face(0)}disabled(){this.isActive=!1,this.engine.handelBehaved.disActive(),this.engine.interactionModule.init(),this.engine.interactionModule.active(),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.engine.handelBehaved.init(this),this.engine.handelBehaved.active(),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,n){this.angleX=e,this.angleY=t,this.angleZ=n,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),n),this.normal.normalize(),this.updata_face(0)}setFaceNormal(e,t=0){this.normal=e,this.distance=t,this.updata_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){let t=this,n=t.engine.scene.children.find(P=>P.type=="Group"&&P.name=="ClippingBox");n==null&&(n=new Dn,n.name="ClippingBox",t.engine.scene.add(n));let i=new R(1,0,0),r=new R(0,1,0),o=new R(0,0,1),a,l,c=this.normal.clone().normalize(),h=Math.abs(c.dot(i)),u=Math.abs(c.dot(r)),f=Math.abs(c.dot(o));h<=u&&h<=f?a=i:u<=h&&u<=f?a=r:a=o,a=a.clone().sub(c.clone().multiplyScalar(a.dot(c))).normalize(),l=new R().crossVectors(c,a).normalize();let d=null;this.center==null?(d=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=d.clone()):d=this.center.clone();let m=this.box.max.x-this.box.min.x,p=this.box.max.y-this.box.min.y,x=this.box.max.z-this.box.min.z,g=Math.max(Math.abs(a.x)*m,Math.abs(a.y)*p,Math.abs(a.z)*x),b=Math.max(Math.abs(l.x)*m,Math.abs(l.y)*p,Math.abs(l.z)*x),v=d.clone().add(a.clone().multiplyScalar(-g/2)).add(l.clone().multiplyScalar(-b/2)),y=d.clone().add(a.clone().multiplyScalar(g/2)).add(l.clone().multiplyScalar(-b/2)),M=d.clone().add(a.clone().multiplyScalar(g/2)).add(l.clone().multiplyScalar(b/2)),E=d.clone().add(a.clone().multiplyScalar(-g/2)).add(l.clone().multiplyScalar(b/2));v.add(c.clone().multiplyScalar(e)),y.add(c.clone().multiplyScalar(e)),M.add(c.clone().multiplyScalar(e)),E.add(c.clone().multiplyScalar(e)),this.current_center=d.clone().add(c.clone().multiplyScalar(e)),C([v,y,M,E],c,"face");function C(P,_,S){const I=new bt,A=new Float32Array([P[0].x,P[0].y,P[0].z,P[1].x,P[1].y,P[1].z,P[2].x,P[2].y,P[2].z,P[3].x,P[3].y,P[3].z]),B=[0,1,2,0,2,3];I.setAttribute("position",new vt(A,3)),I.setIndex(B);let w=t.meshs.find(Z=>Z.name==S);if(w==null){const Z=new Xt({color:65280,transparent:!0,opacity:.02,side:St}),ie=new ht(I,Z);ie.normal=_,ie.name=S,n.add(ie),t.meshs.push(ie)}else w.geometry=I;const F=new Float32Array([P[0].x,P[0].y,P[0].z,P[1].x,P[1].y,P[1].z,P[2].x,P[2].y,P[2].z,P[3].x,P[3].y,P[3].z,P[0].x,P[0].y,P[0].z]);let W=new lo({color:255}),X=new bt;X.setAttribute("position",new vt(F,3));let $=t.meshs.find(Z=>Z.name==S+"Line");$==null&&($=new dr(X,W),$.name=S+"Line",n.add($),t.meshs.push($)),$.geometry=X,$.material=W,t.engine.sectionPlane.find(Z=>Z.name==S).setFromNormalAndCoplanarPoint(_.clone().setLength(t.direction),P[0])}}handleMouseDown(e){this.isDrag=!0;const t=e.raycaster.intersectObjects(this.meshs,!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.center=this.current_center.clone(),this.pickNormal.y==0){const n=new Pt;n.setFromNormalAndCoplanarPoint(new R(0,1,0),this.pickPoint),this.plane=n}else{let n=new R(this.engine.camera.position.x,this.pickPoint.y,this.engine.camera.position.z);const i=new Pt;i.setFromNormalAndCoplanarPoint(n.clone().sub(this.pickPoint.clone()).setLength(1),this.pickPoint),this.plane=i}}handleMouseUp(e){this.isDrag=!1,this.pickPoint=null,this.pickNormal=null,this.pickMesh=null,this.engine.controls.enabled=!0}handleMouseMove(e){this.meshs.forEach(n=>{n.material.opacity=0});const t=e.raycaster.intersectObjects(this.meshs,!1);if(t!=null&&t.length>0&&(t[0].object.material.opacity=.05),this.pickPoint!=null){const n=new R;if(e.raycaster.ray.intersectPlane(this.plane,n)){let i=n.clone().sub(this.pickPoint.clone()).dot(this.pickNormal.clone());this.distance=i,this.updata_face(this.distance)}}}}class RE{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){let t=e.catch.normal;this.engine.handelBehaved.disActive(),this.callback_({dir:t,position:e.catch.point})}}class LE{engine;sectionBox;sectionFace;clippingStencil;currentClippingMode="";constructor(e){this.engine=e;let t=new Pt(new R(0,0,1),1e5);t.name="前";let n=new Pt(new R(0,0,1),1e5);n.name="左";let i=new Pt(new R(0,0,1),1e5);i.name="后";let r=new Pt(new R(0,0,1),1e5);r.name="右";let o=new Pt(new R(0,0,1),1e5);o.name="顶";let a=new Pt(new R(0,0,1),1e5);a.name="底";let l=new Pt(new R(0,0,1),1e5);l.name="face",this.engine.sectionPlane=[t,n,i,r,o,a,l]}init(){this.sectionBox=new AE(this.engine),this.sectionFace=new PE(this.engine)}scaleBox(){let e=this.engine.octreeBox.getBoundingBox();this.sectionBox.setBox(e)}clippingModel(e){let t=[];e.forEach(r=>{let o=this.engine.models.find(a=>a.url===r.url);r.ids.forEach(a=>{o.nodesMap.get(a).infos.forEach(l=>{t.push(l.box)})})}),this.active("box");let n=i(t);this.sectionBox.setBox(n);function i(r){let o=new R(1e8,1e9,1e10),a=new R(-1e8,-1e9,-1e10);return r.forEach(l=>{l.min.xa.x&&(a.x=l.max.x),l.max.y>a.y&&(a.y=l.max.y),l.max.z>a.z&&(a.z=l.max.z)}),new gt(o,a)}}updateClippingValue(e){let t=this.sectionBox.maxBox,n=t.min.x+(t.max.x-t.min.x)*e.x.min*.01,i=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,o=t.min.x+(t.max.x-t.min.x)*e.x.max*.01,a=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:n,minY:i,minZ:r,maxX:o,maxY:a,maxZ:l})}active(e){if(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 RE(this.engine);t.init(),t.catch_face(n=>{this.sectionFace.init(),this.sectionFace.active();let i=this.engine.octreeBox.getBoundingBox(),r=n.position.clone().sub(i.min.clone().add(i.max.clone()).setLength(.5)),o=new R(n.dir.x,n.dir.y,n.dir.z),a=r.dot(o);this.sectionFace.setFaceNormal(n.dir,a)})}}disabled(){this.currentClippingMode=="box"?this.sectionBox.disabled():this.sectionFace.disabled()}recover(){this.currentClippingMode=="box"?this.sectionBox.recover():this.sectionFace.recover()}reverse(){this.sectionFace.reverse()}disActive(){this.sectionFace.disActive(),this.sectionBox.disActive(),this.currentClippingMode=""}}class IE{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 DE{engine;constructor(e){this.engine=e}getEngineInfo(){let e=0,t=0,n=0;return!this.engine||!this.engine.scene?{totalVertices:0,totalTriangles:0,meshCount:0}:(this.engine.scene.traverse(i=>{if(i instanceof ht){const r=i.geometry;if(r&&r.attributes){const o=r.attributes.position;if(o){const a=o.count;e+=a;let l=0;r.index?l=r.index.count/3:l=a/3,t+=l}}}}),this.engine.engineStatus.models.forEach(i=>{n=n+i.info.modelEdge.length}),{totalVertices:Math.floor(e),totalTriangles:Math.floor(t),meshCount:n})}}class BE{engine;constructor(e){this.engine=e}init(){}getModelProperties(e,t,n){let i=this.engine.engineStatus.models.find(o=>o.url===e);i.properties==null&&Cm(e+"/property",o=>{let a=JSON.parse(o);i.properties=a,setTimeout(()=>{r(a,t,n)},100)}),r(i.properties,t,n);function r(o,a,l){let c=[],h=o.models[a.toString()||""],u=h.map(f=>f[0]);u=u.filter((f,d)=>u.indexOf(f)===d),u.forEach(f=>{let d={name:o.categorys[f],children:[]};c.push(d),h.filter(m=>m[0]===f).forEach(m=>{d.children.push({name:o.names[m[1]],value:o.values[m[2]]})})}),l?.({properties:c,materials:c})}}}class NE{engine;constructor(e){this.engine=e}getModelTypes(){let e=[];return this.engine.engineStatus.models.forEach(t=>{t.info.modelMapper.forEach(n=>{e.push(n.typeName)})}),e=e.filter((t,n,i)=>i.indexOf(t)===n),e}getModelMajors(){let e=[];return this.engine.engineStatus.models.forEach(t=>{t.info.modelMapper.forEach(n=>{e.push(n.majorName)})}),e=e.filter((t,n,i)=>i.indexOf(t)===n),e}getModelLevels(){let e=[];return this.engine.engineStatus.models.forEach(t=>{t.info.modelMapper.forEach(n=>{e.push(n.levelName)})}),e=e.filter((t,n,i)=>i.indexOf(t)===n),e}getModelMappers(e){}getModelMapper(e,t){let n=this.engine.engineStatus.models.find(i=>i.url==e);return n?n.info.modelMapper.find(i=>i.id==t):null}getModelsWithLevelType(e,t,n=null){let i=[];return this.engine.engineStatus.models.forEach(r=>{let o={url:r.url,ids:[]};i.push(o),r.info.modelMapper.filter(a=>a.levelName===e&&a.typeName===t).forEach(a=>{o.ids.push(Number(a.id))})}),n&&n(i),i}getModelsWithType(e,t=null){let n=[];return this.engine.engineStatus.models.forEach(i=>{let r={url:i.url,ids:[]};n.push(r),i.info.modelMapper.filter(o=>o.typeName===e).forEach(o=>{r.ids.push(Number(o.id))})}),t&&t(n),n}getModelsWithLevel(e,t){let n=[];return this.engine.engineStatus.models.forEach(i=>{let r={url:i.url,ids:[]};n.push(r),i.info.modelMapper.filter(o=>o.levelName===e).forEach(o=>{r.ids.push(Number(o.id))})}),t&&t(n),n}getModelsWithMajor(e,t){let n=[];return this.engine.engineStatus.models.forEach(i=>{let r={url:i.url,ids:[]};n.push(r),i.info.modelMapper.filter(o=>o.majorName===e).forEach(o=>{r.ids.push(Number(o.id))})}),t&&t(n),n}}class kE{engine;isActive=!1;groupEdge;material;indexes=new Map;constructor(e){this.engine=e,this.groupEdge=this.engine.scene.getObjectByName("groupEdge"),this.material=new lo({color:"#000000",depthTest:!0})}active(){this.isActive=!0,this.groupEdge.visible=!0,this.show()}disActive(){this.isActive=!1,this.groupEdge.visible=!1}show(){this.engine.engineStatus.models.forEach(e=>{if(!this.groupEdge.children.find(t=>t.url==e.url)){let t=e.info,n=[],i=new Map;t.modelEdge.forEach(a=>{let l=n.length;for(let c=0;cc.url==e);if(l){let c=l.geometry.attributes.position.array;for(let h=r;hc.url==e);if(l){let c=l.geometry.attributes.position.array,h=0;for(let u=r;u=3;if(a[f]&&a[f].length===2){const m=d?a[f][1]:a[f][0];c[u]=m.X,c[u+1]=m.Z,c[u+2]=-m.Y}h+=3}l.geometry.attributes.position.needsUpdate=!0}}}}}class UE{config;constructor(e){this.config={temperature:.7,maxTokens:2e4,timeout:3e5,...e}}async chat(e){const t=new AbortController,n=setTimeout(()=>t.abort(),this.config.timeout);try{const i=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(n),!i.ok){const r=await i.json().catch(()=>({}));throw new Error(`API请求失败 (${i.status}): ${r.error?.message||r.message||i.statusText}`)}return(await i.json()).choices?.[0]?.message?.content||""}catch(i){throw clearTimeout(n),i.name==="AbortError"?new Error("请求超时,请重试"):i.message.includes("Failed to fetch")?new Error(`网络请求失败,请检查: 1. 网络连接 2. API地址是否正确 3. 是否有CORS限制`):i}}async chatStream(e,t){const n=new AbortController,i=setTimeout(()=>n.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:n.signal});if(clearTimeout(i),!r.ok){const c=await r.json().catch(()=>({}));throw new Error(`API请求失败 (${r.status}): ${c.error?.message||c.message||r.statusText}`)}const o=r.body?.getReader();if(!o)throw new Error("无法读取响应流");const a=new TextDecoder;let l="";for(;;){const{done:c,value:h}=await o.read();if(c){t("",!0);break}l+=a.decode(h,{stream:!0});const u=l.split(` `);l=u.pop()||"";for(const f of u){const d=f.trim();if(!d||!d.startsWith("data: "))continue;const m=d.slice(6);if(m!=="[DONE]")try{const p=JSON.parse(m).choices?.[0]?.delta?.content;p&&t(p,!1)}catch(p){console.warn("解析流式数据失败:",p)}}}}catch(r){throw clearTimeout(i),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 OE{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,n){this._callback_message=e,this._callback_question=t,this._callback_content=n,this.conversationHistory=[];let i={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=i,this.llmApi=new UE(i.llmConfig);try{const r=await Promise.resolve().then(()=>LT);this.prompts.main=r.default;const o=await Promise.resolve().then(()=>IT);this.prompts.step=o.default;const a=await Promise.resolve().then(()=>DT);this.prompts.apiDoc=a.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 i={role:"system",content:`${this.prompts.main}`},r={role:"system",content:`## BIM引擎API文档 ${this.prompts.apiDoc}`};this.conversationHistory.push(i),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 n=await this.parseAnalysisResponse(t);n&&n.questions&&n.questions.length>0&&this._callback_question(n.questions)}async parseAnalysisResponse(e){try{if(e.includes("##question##")){const t=e.match(/##question##\s*([\s\S]*?)(?=##|$)/);if(t){let n=t[1].trim();n=n.replace(/^```json\n?/,"").replace(/^```\n?/,"").replace(/\n?```$/,"");const i=n.match(/(\[[\s\S]*\])/);i&&(n=i[1]);const r=JSON.parse(n);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 n=t[1].trim();n=n.replace(/^```json\n?/,"").replace(/^```\n?/,"").replace(/\n?```$/,"");const i=n.match(/(\[[\s\S]*\])/);return i&&(n=i[1]),this.steps=JSON.parse(n),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),n=await this.executeStep(e,t);this.stepResults.set(e.id,n),this.config?.debug&&console.log(`[AI Manager] 步骤 ${e.id} 执行完成:`,n)}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 n=this.config?.stepExecution?.maxRetries??1,i=[];let r=null,o=!1;for(let a=0;a<=n;a++)try{const l=i.length>0?i[i.length-1]:"",c=await(a===0?this.generateCode(e,t):o?this.regenerateCodeAfterFailure(e,t,l,r,a):this.generateCode(e,t));i.push(c),this.config?.debug&&console.log(`[AI Manager] 步骤 ${e.id} 第 ${a+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,o=!0;debugger;throw h}debugger;return h}catch(h){debugger;throw r=h,o=!0,h}}catch(l){if(o||(r=l),a>=n)throw console.error(`[AI Manager] 执行步骤 ${e.id} 失败(已达重试上限):`,l),new Error(`步骤 ${e.id} (${e.content}) 执行失败: ${l.message}`);console.warn(`[AI Manager] 步骤 ${e.id} 第 ${a+1} 次执行失败,将尝试让AI修复后重试(剩余重试次数:${n-a}):`,l)}throw new Error(`步骤 ${e.id} (${e.content}) 执行失败: 未知错误`)}extractCodeFromResponse(e){const t=e.match(/##code##\s*([\s\S]*?)(?=##|$)/);if(t){let o=t[1].trim();if(o=o.replace(/^```javascript\n?/,"").replace(/^```js\n?/,"").replace(/^```\n?/,"").replace(/\n?```$/,""),o.length>0)return o}const n=[/```javascript\s*([\s\S]*?)```/i,/```js\s*([\s\S]*?)```/i,/```\s*([\s\S]*?)```/];for(const o of n){const a=e.match(o);if(a&&a[1]){const l=a[1].trim();if(l.length>0)return this.config?.debug&&console.warn("[AI Manager] 未找到 ##code## 标记,从 markdown 代码块中提取代码"),l}}const i=/[请|说明|注意|需要|应该|可以|如果|但是|因为|所以|例如|比如]/i.test(e),r=/(function|const|let|var|return|async|await|=>|engine\.|previousStepOutput)/.test(e);if(!i&&r){const o=e.trim().replace(/^[,。:;!?\s]+/,"").replace(/[,。:;!?\s]+$/,"");if(o.length>10)return this.config?.debug&&console.warn("[AI Manager] 未找到 ##code## 标记和代码块,尝试使用整个响应作为代码"),o}throw new Error(`无法从大模型响应中提取代码。响应内容:${e.substring(0,200)}...`)}async generateCode(e,t){try{const n={role:"system",content:`${this.prompts.step}`},i={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##格式输出代码。`},o=[n,i,r],a=await this.llmApi.chat(o);return this.extractCodeFromResponse(a)}catch(n){throw console.error("[AI Manager] 代码生成失败:",n),n}}async regenerateCodeAfterFailure(e,t,n,i,r){try{const o={role:"system",content:`${this.prompts.step}`},a={role:"system",content:` ## BIM引擎API文档 ${this.prompts.apiDoc}`},l={message:i?.message||(i instanceof Object?JSON.stringify(i):String(i)),name:i?.name,stack:i?.stack},c={role:"user",content:`上一次生成的代码在执行时失败了,请你修复后重新输出完整可执行的 JavaScript 代码(仍然要严格按 ##code## 格式输出)。 当前步骤信息: ${JSON.stringify(e,null,2)} 前序步骤输出数据: ${t?JSON.stringify(t,null,2):"null"} 上一次生成的代码: ${n?` \`\`\`javascript ${n} \`\`\` `:` (无) `} 执行错误信息(第 ${r} 次重试前): ${JSON.stringify(l,null,2)} 修复要求(请务必遵守): 1) 不要输出解释文字,只输出 ##code## 段落里的代码 2) 如果是语法错误/引用未定义/缺少 await/返回值不一致,请直接修复 3) 尽量保持与步骤目标一致,避免引入与步骤无关的副作用 4) 代码需要能在浏览器环境运行(不要使用 Node 专属 API)`},h=await this.llmApi.chat([o,a,c]);try{return this.extractCodeFromResponse(h)}catch(u){throw new Error(`无法从大模型响应中提取代码(修复重试阶段):${u.message}`)}}catch(o){throw console.error("[AI Manager] 修复后代码生成失败:",o),o}}async executeCode(e,t){try{const n=this.engine;let i=e;i=i.replace(/\b(const|let|var)\s+previousStepOutput\s*=\s*[^;]*;/g,""),i=i.replace(/\b(const|let|var)\s+previousStepOutput\s*;/g,"");const r=new Function("engine","previousStepOutput",` 'use strict'; ${i} `)(n,t);return r&&typeof r.then=="function"?await r:r}catch(n){return console.error("[AI Manager] 代码执行失败:",n),"error"+n.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 FE{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,...n},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,n=Math.min(e/t,1),i=this.points[this.playFromIndex],r=this.points[this.playToIndex],o=this.interpolatePose(i,r,n);this.engine.cameraModule.restoreCameraPose(o),n>=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,n){const i=this.easeInOutCubic(n),r={type:t.type,position:{x:Ot.lerp(e.position.x,t.position.x,i),y:Ot.lerp(e.position.y,t.position.y,i),z:Ot.lerp(e.position.z,t.position.z,i)},rotation:{x:Ot.lerp(e.rotation.x,t.rotation.x,i),y:Ot.lerp(e.rotation.y,t.rotation.y,i),z:Ot.lerp(e.rotation.z,t.rotation.z,i)},quaternion:{x:Ot.lerp(e.quaternion.x,t.quaternion.x,i),y:Ot.lerp(e.quaternion.y,t.quaternion.y,i),z:Ot.lerp(e.quaternion.z,t.quaternion.z,i),w:Ot.lerp(e.quaternion.w,t.quaternion.w,i)}};return e.target&&t.target?r.target={x:Ot.lerp(e.target.x,t.target.x,i),y:Ot.lerp(e.target.y,t.target.y,i),z:Ot.lerp(e.target.z,t.target.z,i)}:t.target&&(r.target={...t.target}),e.zoom!==void 0&&t.zoom!==void 0&&(r.zoom=Ot.lerp(e.zoom,t.zoom,i)),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 zE{options;DeviceType;animationId=null;isRenderingPaused=!1;controlsEnabledBeforePause=!0;animate;onWindowResize;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;viewCube;rangeScale;setting;measure;clipping;modelTree;engineInfo;modelProperties;modelMapperBatch;modelEdge;ai;pathRoaming;hoverHighLight;models=[];reactBoundingClientRect={left:0,top:0};version="2.0.0";container;constructor(e){if(this.options=e,this.container=document.getElementById(e.containerId),!this.container)throw new Error(`Container ${e.containerId} not found`);this.engineModelModule=new m3(this),this.engineModelModule.init(),this.ai=new OE(this),this.deviceModule=new a2(this),this.DeviceType=this.deviceModule.getDeviceType(),this.cameraModule=new o2(this),this.sceneModule=new r2(this),this.scene=this.sceneModule.scene,this.renderModule=new l2(this),this.renderer=this.renderModule.createRenderer(),this.camera=this.cameraModule.orthographicCamera,this.scene.camera=this.camera,this.controlModule=new w2(this),this.controlModule.switchDefaultMode(),this.controls=this.controlModule.orbitControls,this.composerModule=new U2(this),this.composerModule.init(),this.events=new l3,this.engineStatus=new a3(this),this.engineStatus.init(),this.loaderModule=new o3(this),this.lightModule=new c3(this),this.lightModule.init(),this.viewCube=new E3(this),this.viewCube.init(),this.options.showViewCube==!1&&this.viewCube.hide(),this.octreeBox=T3(this),this.rangeScale=new C3(this),this.rangeScale.init(),this.clipping=new LE(this),this.clipping.init(),this.setting=new A3(this),this.setting.init(),this.engineModelModule.init(),this.handelBehaved=jh(this),this.modelMapperBatch=new NE(this),this.measure=new U3(this),this.modelToolModule=new u3(this),this.modelProperties=new BE(this),this.interactionModule=new h3(this),this.interactionModule.init(),this.interactionModule.active(),this.hoverHighLight=new cl(this),this.modelEdge=new kE(this),this.modelTree=new IE(this),this.engineInfo=new DE(this),this.pathRoaming=new FE(this),this.pathRoaming.init(),this.worldToScreen=new kn(this.camera,this.renderer,this.scene),this.options.showStats&&(this.stats=new b3,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",t.innerHTML=`v${this.version}`,this.container.appendChild(t);let n=document.createElementNS("http://www.w3.org/2000/svg","svg");n.style.position="absolute",n.style.width="100%",n.style.height="100%",n.style.zIndex="1000",n.style.left="0px",n.style.top="0px",n.style.pointerEvents="none";const i=this.renderer?.domElement.width||1920,r=this.renderer?.domElement.height||1080;n.setAttribute("viewBox",`0 0 ${i} ${r}`),n.setAttribute("preserveAspectRatio","none"),this.container.appendChild(n),this.catchSvg=n,this.onWindowResize=()=>{this.handleWindowResize()},window.addEventListener("resize",this.onWindowResize);let o=this;this.controls.addEventListener("start",()=>{o.events.trigger(Zi.EngineBusy)}),this.controls.addEventListener("end",()=>{o.events.trigger(Zi.EngineFree)}),this.controls.addEventListener("change",()=>{}),this.animate=()=>{if(!this.isRenderingPaused)this.animationId=requestAnimationFrame(this.animate);else{this.animationId=null;return}if(this.stats&&this.stats.begin(),this.composerModule&&this.composerModule.composer.render(),this.viewCube&&this.viewCube.cubeTool.RenderScene(),this.measure.update(),this.hoverHighLight.update(),this.controlModule.update(),this.stats&&this.stats.end(),this.scene){let a=this.scene?.dirLight;a&&this.camera&&this.updateLightPosition(this.camera,a)}},this.animate()}updateLightPosition(e,t){const n=new R;e.getWorldDirection(n);const i=new R().copy(n).multiplyScalar(-100);t.position.copy(e.position).add(i);const r=new R().copy(e.position).add(n.multiplyScalar(20));t.target.position.copy(r),t.target.updateMatrixWorld()}pauseRendering(){if(this.isRenderingPaused){console.warn("[BimEngine] Rendering is already paused");return}this.isRenderingPaused=!0,this.controls&&(this.controlsEnabledBeforePause=this.controls.enabled,this.controls.enabled=!1)}resumeRendering(){if(!this.isRenderingPaused){console.warn("[BimEngine] Rendering is not paused");return}this.isRenderingPaused=!1,this.controls&&(this.controls.enabled=this.controlsEnabledBeforePause),this.animationId===null&&this.animate()}isRenderingPausedState(){return this.isRenderingPaused}handleWindowResize(e,t){if(!this.container||!this.renderer||!this.camera)return;if(e===void 0||t===void 0){const i=this.deviceModule.getContainerSize();e=e??i.width,t=t??i.height}if(!e||!t)return;this.renderer.setPixelRatio(window.devicePixelRatio),this.renderer.setSize(e,t);const n=e/t;if(this.camera===this.cameraModule.perspectiveCamera)this.cameraModule.perspectiveCamera.aspect=n,this.cameraModule.perspectiveCamera.updateProjectionMatrix(),this.camera=this.cameraModule.perspectiveCamera;else if(this.camera===this.cameraModule.orthographicCamera){const i=this.cameraModule.orthographicCamera,r=50,o=this.container.clientWidth/this.container.clientHeight;i.left=r*o/-2,i.right=r*o/2,i.top=r/2,i.bottom=r/-2,i.updateProjectionMatrix()}if(this.catchSvg){const i=this.renderer.domElement.width,r=this.renderer.domElement.height;this.catchSvg.setAttribute("viewBox",`0 0 ${i} ${r}`)}this.events&&this.events.trigger(Zi.ViewportResize,{width:e,height:t})}dispose(){console.log("[BimEngine] Starting engine disposal..."),this.animationId!==null&&(cancelAnimationFrame(this.animationId),this.animationId=null),this.isRenderingPaused=!0,this.onWindowResize&&window.removeEventListener("resize",this.onWindowResize);try{this.measure&&(this.measure.disActive(),this.measure.clearAll(),this.measure.annotationContainer&&this.measure.annotationContainer.remove()),this.clipping&&this.clipping.disActive(),this.interactionModule&&this.interactionModule.disActive(),this.viewCube&&this.viewCube.cubeTool&&typeof this.viewCube.cubeTool.dispose=="function"&&this.viewCube.cubeTool.dispose()}catch(e){console.warn("[BimEngine] Error disposing managers:",e)}try{this.controlModule&&(this.controlModule.originDiv&&this.controlModule.originDiv.remove(),this.controlModule.orbitControls&&typeof this.controlModule.orbitControls.dispose=="function"&&this.controlModule.orbitControls.dispose(),this.controlModule.firstPersonControls&&typeof this.controlModule.firstPersonControls.dispose=="function"&&this.controlModule.firstPersonControls.dispose())}catch(e){console.warn("[BimEngine] Error disposing controls:",e)}this.scene&&this.clearScene(this.scene);try{this.composerModule&&this.composerModule.composer&&(this.composerModule.composer.passes&&this.composerModule.composer.passes.forEach(e=>{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 dr&&(e.geometry&&e.geometry.dispose(),e.material&&this.disposeMaterial(e.material)),e instanceof Cf&&(e.geometry&&e.geometry.dispose(),e.material&&this.disposeMaterial(e.material)),e instanceof kt&&(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 Cx&&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 n=e[t];n&&n instanceof Ft&&n.dispose()}),e.dispose())}}function HE(s){return new zE(s)}class is{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=HE(e),!this.engine)throw new Error("Failed to create engine instance");this._isInitialized=!0,this.unsubscribeTheme=ot.subscribe(t=>{this.setTheme(t)}),this.setTheme(ot.getTheme()),this.engine.events.on("click",t=>{const n=this.registry;t&&t.object?(this.selectedComponent={url:t.object.url,id:t.object.name},console.log("[Engine] 构件选中:",this.selectedComponent),n.emit("component:selected",this.selectedComponent)):(this.selectedComponent=null,console.log("[Engine] 取消选中"),n.emit("component:deselected",{}))})}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()}getEngine(){return this.engine}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(){!this._isInitialized||this.engine}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)}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()}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)}}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(is.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(is.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(is.WALK_COLLISION_KEY,String(e)),this.engine.controlModule.setApplyCollision(e)}loadWalkSettings(){if(!this.engine?.controlModule)return;const e=localStorage.getItem(is.WALK_SPEED_KEY),t=localStorage.getItem(is.WALK_GRAVITY_KEY),n=localStorage.getItem(is.WALK_COLLISION_KEY);this.engine.controlModule.setMoveSpeed(e?Number(e):1),this.engine.controlModule.setApplyGravity(t==="true"),this.engine.controlModule.setApplyCollision(n==="true")}toggleMiniMap(){if(!this._isInitialized||!this.engine?.controlModule){console.error("[Engine] Cannot toggle mini map: engine not initialized.");return}this.engine.controlModule.toggleMinMap()}isFirstPersonModeActive(){return this.isWalkModeActive}getSelectedComponent(){return this.selectedComponent}getComponentProperties(e,t,n){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,n)}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(n){console.warn("[Engine] highlightModel failed:",n)}}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(n){console.warn("[Engine] viewScaleToModel failed:",n)}}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(n){console.warn("[Engine] hideModels failed:",n)}}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(n){console.warn("[Engine] showModel failed:",n)}}sanitizeModelParams(e){if(!Array.isArray(e))return[];const t=o=>o.replace(/\/+$/,""),n=Array.isArray(this.engine?.models)?this.engine.models:[],i=new Map;for(const o of n)o?.url&&i.set(t(o.url),o);const r=[];for(const o of e){if(!o||typeof o.url!="string"||!o.url||!Array.isArray(o.ids))continue;const a=i.get(t(o.url));if(!a||!(a.nodesMap instanceof Map))continue;const l=new Set;for(const h of o.ids){if(!Number.isFinite(h))continue;const u=Number(h);if(!Number.isInteger(u))continue;const f=a.nodesMap.get(u);!f||!Array.isArray(f.indexes)||f.indexes.length===0||l.add(u)}const c=Array.from(l);c.length&&r.push({url:o.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 VE{element;content=null;isVisible=!1;onCloseCallback;options;mouseDownTime=0;CLICK_THRESHOLD=200;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())};handleContainerMouseUp=e=>{e.button!==2||Date.now()-this.mouseDownTime>this.CLICK_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 n=this.element.getBoundingClientRect(),i=window.innerWidth,r=window.innerHeight;let o=e,a=t;e+n.width>i&&(o=e-n.width),t+n.height>r&&(a=t-n.height),this.element.style.left=`${o}px`,this.element.style.top=`${a}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 td{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=Yt.subscribe(()=>{this.setLocales()}),this.unsubscribeTheme=ot.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 n=new Map,i="default";e.forEach(o=>{const a=o.group||i;n.has(a)||n.set(a,[]),n.get(a).push(o)});let r=[];if(t){r=t.filter(o=>n.has(o));for(const o of n.keys())r.includes(o)||r.push(o)}else r=Array.from(n.keys());r.forEach((o,a)=>{if(a>0){const c=document.createElement("li");c.className="bim-menu-divider",this.element.appendChild(c)}const l=n.get(o);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"),n=!e.disabled;t.className=`bim-menu-item ${n?"":"disabled"}`;const i=document.createElement("div");i.className="bim-menu-item-icon",e.icon&&(i.innerHTML=e.icon),t.appendChild(i);const r=document.createElement("div");r.className="bim-menu-item-label",r.textContent=xe(e.label),t.appendChild(r);const o=e.children,a=o&&o.length>0;if(a){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 n&&t.addEventListener("click",l=>{l.stopPropagation(),console.log(`[BimMenu] Clicked item: ${e.id}`),a||(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 n=e.children;if(!n||n.length===0)return;this.closeSubMenu();const i=document.createElement("div");i.style.position="fixed",i.style.zIndex="10001";const r=t.getBoundingClientRect();i.style.top=`${r.top}px`,i.style.left=`${r.right}px`,i.addEventListener("mousedown",l=>l.stopPropagation());const o=new td({items:n});o.init(),i.appendChild(o.element),document.body.appendChild(i),this.activeSubMenu={menu:o,container:i};const a=i.getBoundingClientRect();a.right>window.innerWidth&&(i.style.left=`${r.left-a.width}px`)}closeSubMenu(){this.activeSubMenu&&(this.activeSubMenu.menu.destroy(),this.activeSubMenu.container.remove(),this.activeSubMenu=null)}}class kg extends pi{container;rightKeyPanel;contextHandlers=[];constructor(e,t){super(t),this.container=e,this.rightKeyPanel=new VE({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,n,i){if(!n||n.length===0)return;const r=new td({items:n,groupOrder:i});r.init(),this.rightKeyPanel.mount(r),this.rightKeyPanel.show(e,t)}hide(){this.rightKeyPanel.hide()}handleContextMenu=e=>{let t=null;for(const n of this.contextHandlers){const i=n(e);i&&i.length>0&&(t||(t=[]),t=t.concat(i))}t&&t.length>0?this.showMenu(e.clientX,e.clientY,t):this.hide()}}class GE extends pi{container;engineInstance=null;rightKey=null;constructor(e,t){super(t),this.container=e}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 is({container:this.container,...e},this.registry),this.engineInstance.init(),this.rightKey=new kg(this.container,this.registry),this.rightKey.registerHandler(t=>{const n=this.getSelectedComponent(),i=[];return n&&(i.push({id:"componentDetail",label:"menu.componentDetail",group:"component",order:1,divider:!0,onClick:()=>{this.registry.componentDetail?.show(),this.rightKey?.hide()}}),i.push({id:"hideSelected",label:"menu.hideSelected",group:"component",order:2,onClick:()=>{const r=this.getHighlightModels();r&&this.hideModels(r),this.rightKey?.hide()}}),i.push({id:"transparentSelected",label:"menu.transparentSelected",group:"component",order:3,onClick:()=>{const r=this.getHighlightModels();r&&this.translucentModels(r),this.rightKey?.hide()}}),i.push({id:"cancelTranslucent",label:"menu.cancelTranslucent",group:"component",order:4,onClick:()=>{this.unTranslucentModel(),this.rightKey?.hide()}}),i.push({id:"isolateSelected",label:"menu.isolateSelected",group:"component",order:5,divider:!0,children:[{id:"hideOthers",label:"menu.hideOthers",onClick:()=>{const r=this.getHighlightModels();r&&this.isolateModels(r),this.rightKey?.hide()}},{id:"transparentOthers",label:"menu.transparentOthers",onClick:()=>{const r=this.getHighlightModels();r&&this.translucentOtherModels(r),this.rightKey?.hide()}}]}),i.push({id:"quickSelect",label:"menu.quickSelect",group:"component",order:6,children:[{id:"selectSameType",label:"menu.selectSameType",onClick:()=>{const r=this.getHighlightModels();r&&this.batchSelectSameTypeModel(r),this.rightKey?.hide()}},{id:"selectSameLevel",label:"menu.selectSameLevel",onClick:()=>{const r=this.getHighlightModels();r&&this.batchSelectSameLevelModel(r),this.rightKey?.hide()}},{id:"selectSameLevelType",label:"menu.selectSameLevelType",onClick:()=>{const r=this.getHighlightModels();r&&this.batchSelectSameLevelTypeModel(r),this.rightKey?.hide()}}]}),i.push({id:"fitSectionBox",label:"menu.fitSectionBox",group:"component",order:7,onClick:()=>{this.fitSectionBoxToModel(),this.rightKey?.hide()}})),i.push({id:"showAll",label:"menu.showAll",group:"component",order:8,onClick:()=>{this.showAllModels(),this.emit("menu:show-all",{}),this.rightKey?.hide()}}),i}),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)}getEngine(){return this.engineInstance?this.engineInstance.getEngine():(console.warn("[EngineManager] 3D Engine not initialized."),null)}CameraGoHome(){if(!this.engineInstance){console.warn("[EngineManager] 3D Engine not initialized.");return}this.engineInstance.CameraGoHome()}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()}activateMeasure(e){if(!this.engineInstance){console.warn("[EngineManager] 3D Engine not initialized.");return}this.engineInstance.activateMeasure(e)}deactivateMeasure(){this.engineInstance&&this.engineInstance.deactivateMeasure()}getCurrentMeasureType(){return this.engineInstance?this.engineInstance.getCurrentMeasureType():null}clearAllMeasures(){this.engineInstance&&this.engineInstance.clearAllMeasures()}saveMeasureSetting(e){this.engineInstance&&this.engineInstance.saveMeasureSetting(e)}activeSection(e){if(!this.engineInstance){console.warn("[EngineManager] 3D Engine not initialized.");return}this.engineInstance.activeSection(e)}getCurrentSectionMode(){return this.engineInstance?this.engineInstance.getCurrentSectionMode():null}deactivateSection(){this.engineInstance&&this.engineInstance.deactivateSection()}setSectionBoxRange(e){if(!this.engineInstance){console.warn("[EngineManager] 3D Engine not initialized.");return}this.engineInstance.setSectionBoxRange(e)}hideSection(){this.engineInstance&&this.engineInstance.hideSection()}recoverSection(){this.engineInstance&&this.engineInstance.recoverSection()}fitSectionBoxToModel(){this.engineInstance&&this.engineInstance.fitSectionBoxToModel()}scaleSectionBox(){this.engineInstance&&this.engineInstance.scaleSectionBox()}reverseSection(){this.engineInstance&&this.engineInstance.reverseSection()}activateZoomBox(){if(!this.engineInstance){console.warn("[EngineManager] 3D Engine not initialized.");return}this.engineInstance.activateZoomBox()}activateFirstPersonMode(){if(!this.engineInstance){console.warn("[EngineManager] 3D Engine not initialized.");return}this.engineInstance.activateFirstPersonMode()}deactivateFirstPersonMode(){this.engineInstance&&this.engineInstance.deactivateFirstPersonMode()}setWalkSpeed(e){this.engineInstance?.setWalkSpeed(e)}setWalkGravity(e){this.engineInstance?.setWalkGravity(e)}setWalkCollision(e){this.engineInstance?.setWalkCollision(e)}toggleMiniMap(){this.engineInstance?.toggleMiniMap()}isFirstPersonModeActive(){return this.engineInstance?.isFirstPersonModeActive()??!1}getSelectedComponent(){return this.engineInstance?.getSelectedComponent()??null}getComponentProperties(e,t,n){this.engineInstance?.getComponentProperties(e,t,n)}getTypeTreeData(){return this.engineInstance?.getTypeTreeData()??[]}getLevelTreeData(){return this.engineInstance?.getLevelTreeData()??[]}getMajorTreeData(){return this.engineInstance?.getMajorTreeData()??[]}getEngineInfo(){return this.engineInstance?.getEngineInfo()??null}pathRoamingAddPoint(){this.engineInstance?.pathRoamingAddPoint()}pathRoamingRemovePoint(e){this.engineInstance?.pathRoamingRemovePoint(e)}pathRoamingClearPoints(){this.engineInstance?.pathRoamingClearPoints()}pathRoamingGetPoints(){return this.engineInstance?.pathRoamingGetPoints()??[]}pathRoamingJumpToPoint(e){this.engineInstance?.pathRoamingJumpToPoint(e)}pathRoamingPlay(e){this.engineInstance?.pathRoamingPlay(e)}pathRoamingStop(){this.engineInstance?.pathRoamingStop()}getHighlightModels(){return this.engineInstance?.getHighlightModels()??null}highlightModel(e){this.engineInstance?.highlightModel(e)}unhighlightAllModels(){this.engineInstance?.unhighlightAllModels()}viewScaleToModel(e){this.engineInstance?.viewScaleToModel(e)}hideModels(e){this.engineInstance?.hideModels(e)}showModel(e){this.engineInstance?.showModel(e)}translucentModels(e){this.engineInstance?.translucentModels(e)}unTranslucentModel(){this.engineInstance?.unTranslucentModel()}isolateModels(e){this.engineInstance?.isolateModels(e)}translucentOtherModels(e){this.engineInstance?.translucentOtherModels(e)}showAllModels(){this.engineInstance?.showAllModels()}batchSelectSameTypeModel(e){this.engineInstance?.batchSelectSameTypeModel(e)}batchSelectSameLevelModel(e){this.engineInstance?.batchSelectSameLevelModel(e)}batchSelectSameLevelTypeModel(e){this.engineInstance?.batchSelectSameLevelTypeModel(e)}getRenderMode(){return this.engineInstance?.getRenderMode()??"balance"}setRenderMode(e){this.engineInstance?.setRenderMode(e)}destroy(){this.engineInstance&&(this.engineInstance.destroy(),this.engineInstance=null),this.rightKey&&(this.rightKey.destroy(),this.rightKey=null),super.destroy()}}var _t=(s=>(s[s.Unchecked=0]="Unchecked",s[s.Checked=1]="Checked",s[s.Indeterminate=2]="Indeterminate",s))(_t||{});class WE{config;element;children=[];parent=null;checkState=_t.Unchecked;contentEl;switcherEl;checkboxEl=null;titleEl;actionsEl;childrenContainer;onExpandChange;onCheckChange;onNodeClick;renderActions;constructor(e,t,n){this.config=e,this.onExpandChange=n.onExpand,this.onCheckChange=n.onCheck,this.onNodeClick=n.onClick,this.renderActions=t.renderActions,this.checkState=e.checked?_t.Checked:_t.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 n=this.config.children&&this.config.children.length>0;if(n?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 i=e.indent||24;return this.childrenContainer.style.paddingLeft=`${i}px`,this.config.expanded&&n&&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!==_t.Checked;this.setChecked(e?_t.Checked:_t.Unchecked,!0)}setChecked(e,t=!1,n=!1){!n&&this.checkState===e||(this.checkState=e,this.config.checked=e===_t.Checked,this.updateCheckboxUI(),t&&this.onCheckChange(this))}updateCheckboxUI(){this.checkboxEl&&(this.checkboxEl.classList.remove("is-checked","is-indeterminate"),this.checkState===_t.Checked?this.checkboxEl.classList.add("is-checked"):this.checkState===_t.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 XE{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 n=document.createElement("span");n.className="bim-tree-search-icon",n.innerHTML='',t.appendChild(n),this.searchInput=document.createElement("input"),this.searchInput.className="bim-tree-search-input",this.searchInput.type="text",this.searchInput.placeholder=xe(this.options.searchPlaceholder||"搜索..."),this.searchInput.addEventListener("input",i=>{const r=i.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=i=>{this.searchResults&&!this.searchResults.contains(i.target)&&!this.searchInput?.contains(i.target)&&this.searchResults.classList.remove("is-visible")},document.addEventListener("click",this.clickOutsideHandler)}init(){this.render(),this.unsubscribeLocale=Yt.subscribe(()=>this.setLocales()),this.unsubscribeTheme=ot.subscribe(e=>this.setTheme(e)),this.setTheme(ot.getTheme())}handleSearch(e){if(!this.searchResults)return;if(!e.trim()){this.searchResults.classList.remove("is-visible"),this.searchResults.innerHTML="";return}const t=[],n=e.toLowerCase();this.nodeMap.forEach(i=>{const r=i.config.label;r.toLowerCase().includes(n)&&t.push({node:i,label:r,path:this.getNodePath(i)})}),this.renderSearchResults(t)}getNodePath(e){const t=[];let n=e.parent;for(;n;)t.unshift(n.config.label),n=n.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 n=document.createElement("div");n.className="bim-tree-search-item";const i=document.createElement("span");i.className="bim-tree-search-item-title",i.textContent=t.label;const r=document.createElement("span");r.className="bim-tree-search-item-path",r.textContent=t.path,n.appendChild(i),t.path&&n.appendChild(r),n.addEventListener("click",()=>{this.revealNode(t.node)}),this.searchResults.appendChild(n)});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 n=t.getBoundingClientRect(),i=e.element.getBoundingClientRect();return i.top>=n.top&&i.bottom<=n.bottom}scrollNodeIntoContentCenter(e){const t=this.contentElement;if(!t||!e?.element?.isConnected)return;const n=t.getBoundingClientRect(),i=e.element.getBoundingClientRect();if(i.top>=n.top&&i.bottom<=n.bottom)return;const r=i.top-n.top+t.scrollTop,o=Math.max(0,r-(t.clientHeight-i.height)/2);t.scrollTo({top:o,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=xe(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 n=new WE(e,this.options,{onExpand:i=>{this.onNodeExpand&&this.onNodeExpand(i)},onCheck:i=>this.handleNodeCheck(i),onClick:i=>this.handleNodeSelect(i)});this.nodeMap.set(e.id,n),t?t.appendChild(n):(this.rootNodes.push(n),this.contentElement.appendChild(n.element)),e.children&&e.children.length>0&&e.children.forEach(i=>{this.createNodeRecursively(i,n)})}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===_t.Checked;if(this.onNodeCheck&&this.onNodeCheck(e),this.options.checkStrictly===!1)return;const n=(r,o)=>{r.children.forEach(a=>{a.config.disabled||(a.setChecked(o,!1),n(a,o))})};t?n(e,_t.Checked):n(e,_t.Unchecked);let i=e.parent;for(;i;){if(i.config.disabled){i=i.parent;continue}const r=i.children,o=r.every(l=>l.checkState===_t.Checked),a=r.every(l=>l.checkState===_t.Unchecked);o?i.setChecked(_t.Checked,!1):a?i.setChecked(_t.Unchecked,!1):i.setChecked(_t.Indeterminate,!1),i=i.parent}}getNode(e){return this.nodeMap.get(e)}checkNode(e,t){const n=this.nodeMap.get(e);n&&n.setChecked(t?_t.Checked:_t.Unchecked,!0)}expandAll(e){this.nodeMap.forEach(t=>t.toggleExpand(e))}checkAllNodes(e){const t=e?_t.Checked:_t.Unchecked;this.nodeMap.forEach(n=>n.setChecked(t,!1,!0))}getCheckedNodes(e=!1){const t=[];return this.nodeMap.forEach(n=>{(n.checkState===_t.Checked||e&&n.checkState===_t.Indeterminate)&&t.push(n.config)}),t}}class Ug{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(ot.getTheme()),this.unsubscribeLocale=Yt.subscribe(()=>this.setLocales()),this.unsubscribeTheme=ot.subscribe(e=>this.setTheme(e))}renderNav(){this.navElement.innerHTML="",this.navClickHandler=e=>{const t=e.target.closest(".bim-tab__item");if(!t)return;const n=t.dataset.id;!n||this.tabMap.get(n)?.disabled||this.activateTab(n)},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 i=document.createElement("span");i.className="bim-tab__icon",i.innerHTML=e.icon,t.appendChild(i)}const n=document.createElement("span");n.className="bim-tab__title",n.textContent=this.resolveTitle(e.title),t.appendChild(n),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(i=>{const r=i.dataset.id===e;i.classList.toggle("is-active",r),i.setAttribute("aria-selected",`${r}`)}),this.panelMap.forEach((i,r)=>{const o=r===e;o||this.savePanelTreeScrollTop(r,i),i.classList.toggle("is-active",o),i.style.display=o?"":"none",o&&this.restorePanelTreeScrollTop(r,i)}),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 n=t.dataset.id;if(!n)return;const i=this.tabMap.get(n);if(!i)return;const r=t.querySelector(".bim-tab__title");r&&(r.textContent=this.resolveTitle(i.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 n=t.querySelector(".bim-tree-content");n&&this.panelTreeScrollTopMap.set(e,n.scrollTop)}restorePanelTreeScrollTop(e,t){const n=this.panelTreeScrollTopMap.get(e);if(n===void 0)return;const i=t.querySelector(".bim-tree-content");i&&requestAnimationFrame(()=>{i.scrollTop=n})}resolveTitle(e){try{return xe(e)||e}catch{return e}}}const Og={测量:'',地图:'',框选放大:'',漫游:'',目录树:'',剖切:'',剖切盒:'',全屏:'',设置:'',拾曲面剖切:'',轴向剖切:'',主视角:'',文档:'',第一人称漫游:'',反向:'',路径漫游:'',适应到模型:'',隐藏:'',重置:'',标高:'',距离:'',最小距离:'',激光边距:'',角度:'',坡度:'',体积:'',空间体积:'',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 rt(s){const e=Og[s];return e||(console.warn(`[IconManager] Icon "${s}" not found, using default icon`),Og.default)}function Fg(s,e){let t=e>>>0;for(let n=0;n>>8&255,t=Math.imul(t,16777619)}return t>>>0}async function jE(s){const e=JSON.stringify(s),t=Fg(e,2166136261),n=Fg(e,522970236);return`${t.toString(16).padStart(8,"0")}${n.toString(16).padStart(8,"0")}`}function zg(s){const e=new Map,t=i=>{const r=i.config.data,o=r?._modelUrl;if(o&&r?.ids?.length){let a=e.get(o);a||(a=new Set,e.set(o,a));for(const l of r.ids){const c=Number(l);Number.isFinite(c)&&a.add(c)}}for(const a of i.children||[])t(a)};t(s);const n=[];for(const[i,r]of e)r.size>0&&n.push({url:i,ids:Array.from(r)});return n}let qE=0;async function ZE(s){if(!s||s.length===0)return[];const e=async(t,n)=>{const i=t.children&&t.children.length>0;let r;return t.ids?.length?r=await jE(t.ids):t.id?r=t.id:r=`node_${++qE}`,{id:r,label:t.name||"未命名",expanded:!1,checked:!0,children:i?await Promise.all(t.children.map(o=>e(o,n))):void 0,data:{...t,_modelUrl:n}}};return Promise.all(s.map(async t=>{const n=t.children&&t.children.length>0,i=t.url;return{id:i,label:t.name||"模型",expanded:!0,checked:!0,children:n?await Promise.all(t.children.map(r=>e(r,i))):void 0,data:{_modelUrl:i}}}))}class YE extends pi{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 zl({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:rt("目录树"),onClick:()=>{this.openConstructTreeDialog()}}),this.toolbar.render()}async openConstructTreeDialog(){this.setVisible(!1);const e=this.registry.engine3d?.getLevelTreeData()??[],t=this.registry.engine3d?.getTypeTreeData()??[],n=this.registry.engine3d?.getMajorTreeData()??[];console.log("[ConstructTree] 原始数据 (Level):",e),console.log("[ConstructTree] 原始数据 (Type):",t),console.log("[ConstructTree] 原始数据 (Major):",n);const i=async(p,x)=>{const g=await ZE(p);console.log(`[ConstructTree] 转换后数据 (${x}):`,g);const b=new XE({data:g,checkable:!0,indent:0,enableSearch:!0,checkStrictly:!0,defaultExpandAll:!0,onNodeCheck:v=>{const y=zg(v);y.length&&(v.checkState===_t.Checked?this.registry.engine3d?.showModel(y):this.registry.engine3d?.hideModels(y))},onNodeSelect:v=>{const y=zg(v);y.length&&(this.registry.engine3d?.unhighlightAllModels(),this.registry.engine3d?.highlightModel(y),this.registry.engine3d?.viewScaleToModel(y))},onNodeDeselect:()=>{this.registry.engine3d?.unhighlightAllModels()},onNodeExpand:()=>{this.dialog?.fitWidth()}});return b.init(),b},r=await i(e,"Level"),o=await i(t,"Type"),a=await i(n,"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(o.element);const h=document.createElement("div");h.className="construct-tab__panel-content",h.appendChild(a.element);const u=document.createElement("div");u.className="construct-tab__container",u.style.height="100%",u.style.overflow="hidden";const f=()=>{this.registry.engine3d?.showAllModels(),r.checkAllNodes(!0),o.checkAllNodes(!0),a.checkAllNodes(!0)},d=new Ug({container:u,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()}});d.init(),f();const m=this.registry.on("menu:show-all",()=>{f()});this.dialog=this.registry.dialog.create({title:"constructTree.title",minWidth:320,height:600,content:u,position:{x:20,y:20},resizable:!1,onClose:()=>{m(),d.destroy(),r.destroy(),o.destroy(),a.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 Is extends pi{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,n=e.clientHeight,i=this.dialogWidth,r=typeof this.dialogHeight=="number"?this.dialogHeight:300;return{x:t-i-20,y:(n-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(),n=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:n.draggable,resizable:n.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 ss={clearHeight:'',clearDistance:'',distance:'',elevation:'',point:'',angle:'',area:'',slope:''},zo={distance:{key:"distance",callBackType:"distance",icon:ss.distance,order:0},clearHeight:{key:"clearHeight",callBackType:"clear-height",icon:ss.clearHeight,order:1},clearDistance:{key:"clearDistance",callBackType:"clear-distance",icon:ss.clearDistance,order:2},elevation:{key:"elevation",callBackType:"elevation",icon:ss.elevation,order:3},point:{key:"point",callBackType:"point",icon:ss.point,order:4},angle:{key:"angle",callBackType:"angle",icon:ss.angle,order:5},area:{key:"area",callBackType:"area",icon:ss.area,order:6},slope:{key:"slope",callBackType:"slope",icon:ss.slope,order:7}},Hg=Object.values(zo).sort((s,e)=>s.order-e.order).map(s=>s.key);function Vg(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";case"point":default:return"point"}}function $E(s){return Object.values(zo).find(e=>e.callBackType===s)?.key}class Ho{element;options;activeMode;isExpanded;result=null;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;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()??{...Ho.DEFAULT_CONFIG},this.element=this.createDom()}init(){this.unsubscribeLocale=Yt.subscribe(()=>{this.setLocales()}),this.unsubscribeTheme=ot.subscribe(e=>{this.setTheme(e)}),this.setLocales(),this.setTheme(ot.getTheme()),this.applyExpandedState(),this.applyActiveModeState(),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,n]of this.toolButtons.entries())n.title=xe(this.getModeI18nKey(t)),n.setAttribute("aria-label",n.title);this.toggleBtn.title=this.isExpanded?xe("measure.actions.collapse"):xe("measure.actions.expand"),this.toggleBtn.setAttribute("aria-label",this.toggleBtn.title),this.toggleTextEl&&(this.toggleTextEl.textContent=this.toggleBtn.title),this.clearBtn.textContent=xe("measure.actions.clearAll"),this.settingsBtn.title=xe("measure.actions.settings"),this.settingsBtn.setAttribute("aria-label",this.settingsBtn.title),this.mainValueLabelEl.textContent=xe(this.getModeValueLabelI18nKey(this.activeMode)),this.element.querySelectorAll("[data-i18n-key]").forEach(t=>{const n=t.dataset.i18nKey;n&&(t.textContent=xe(n))}),this.saveSettingsBtn.textContent=xe("measure.settings.save"),this.cancelSettingsBtn.textContent=xe("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.mainValueLabelEl.textContent=xe(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 n={unit:e.unit??this.config.unit,precision:e.precision??this.config.precision};this.config=n,t&&this.saveConfigToCache(n),this.renderResult(),this.view==="settings"&&this.syncSettingsFormFromConfig(n)}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 n=document.createElement("div");n.className="bim-measure-tool-grid";const i=` `;for(let m=0;m{this.setActiveMode(p)}),this.toolButtons.set(p,g),n.appendChild(g)}t.appendChild(n);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 o=document.createElement("span");o.className="bim-measure-toggle-icon",o.innerHTML=` `,this.toggleBtn.appendChild(this.toggleTextEl),this.toggleBtn.appendChild(o),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);const a=document.createElement("div");a.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),a.appendChild(l);const u=document.createElement("div");u.className="bim-measure-xyz",this.xyzBoxEl=u;const f=(m,p,x)=>{const g=document.createElement("div");g.className="bim-measure-row";const b=document.createElement("span");b.className="label",b.dataset.i18nKey=m;const v=document.createElement("span");return v.className=`value ${p}`,x(v),g.appendChild(b),g.appendChild(v),g};u.appendChild(f("measure.labels.x","bim-measure-xyz-x",m=>this.xyzXEl=m)),u.appendChild(f("measure.labels.y","bim-measure-xyz-y",m=>this.xyzYEl=m)),u.appendChild(f("measure.labels.z","bim-measure-xyz-z",m=>this.xyzZEl=m)),a.appendChild(u),this.mainViewEl.appendChild(a);const d=document.createElement("div");return d.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()}),d.appendChild(this.clearBtn),d.appendChild(this.settingsBtn),this.mainViewEl.appendChild(d),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 n=document.createElement("div");n.className="bim-measure-settings-row";const i=document.createElement("div");i.className="label",i.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")),n.appendChild(i),n.appendChild(this.unitSelectEl),e.appendChild(n);const r=document.createElement("div");r.className="bim-measure-settings-hint",r.dataset.i18nKey="measure.settings.hint",e.appendChild(r);const o=document.createElement("div");o.className="bim-measure-settings-row";const a=document.createElement("div");a.className="label",a.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)),o.appendChild(a),o.appendChild(this.precisionSelectEl),e.appendChild(o);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}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),n={unit:e,precision:this.isValidPrecision(t)?t:this.config.precision};this.config=n,this.saveConfigToCache(n),this.draftConfig=null,this.view="main",this.applyViewState(),this.renderResult(),this.options.onConfigSave?.(n),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(Ho.CONFIG_CACHE_KEY);if(!e)return null;const t=JSON.parse(e);if(!t||typeof t!="object")return null;const n=t.unit,i=t.precision;return!this.isValidUnit(n)||!this.isValidPrecision(i)?null:{unit:n,precision:i}}catch{return null}}saveConfigToCache(e){try{localStorage.setItem(Ho.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 n=this.result?.xyz;if(!n){this.xyzXEl.textContent="--",this.xyzYEl.textContent="--",this.xyzZEl.textContent="--";return}this.xyzXEl.textContent=this.convertValue("length",n.x)+" "+this.getUnitText("length"),this.xyzYEl.textContent=this.convertValue("length",n.y)+" "+this.getUnitText("length"),this.xyzZEl.textContent=this.convertValue("length",n.z)+" "+this.getUnitText("length");return}this.mainValueRowEl.style.display="",this.mainValueLabelEl.textContent=xe(this.getModeValueLabelI18nKey(this.activeMode));const t=this.result?this.result[zo[this.activeMode].callBackType]:void 0;if(this.activeMode==="slope"||this.activeMode==="angle")this.mainNumberEl.textContent=t??"--",this.mainUnitEl.textContent="";else{const n=Vg(this.activeMode);this.mainNumberEl.textContent=this.convertValue(n,t),this.mainUnitEl.textContent=this.getUnitText(n)}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 n=this.config.unit,i=this.config.precision;let r;switch(e){case"length":switch(n){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(n){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;case"angle":case"percent":case"point":default:r=t}return r.toFixed(i)}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 KE extends Is{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 Ho({defaultMode:"distance",defaultExpanded:!1,onModeChange:t=>{console.log("[MeasureDialogManager] 当前测量方式已切换:",t),this.registry.engine3d?.activateMeasure(t)},onClearAll:()=>{console.log("[MeasureDialogManager] 删除全部"),this.registry.engine3d?.clearAllMeasures()},onSettings:()=>{console.log("[MeasureDialogManager] 打开设置")},onExpandedChange:()=>{this.dialog?.fitHeight(!1)},onConfigSave:t=>{console.log("[MeasureDialogManager] 保存设置:",t),this.registry.engine3d?.saveMeasureSetting({unit:t.unit,precision:t.precision})}}),this.panel.init(),this.config=this.panel.getConfig(),this.config&&(console.log("[MeasureDialogManager] 同步缓存设置到引擎:",this.config),this.registry.engine3d?.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);const e=this.registry.engine3d?.getEngine();if(e?.events){const t=n=>{console.log("[MeasureDialogManager] 测量值回调:",n),n&&this.panel&&this.handleMeasureChanged(n)};e.events.on("measure-changed",t),e.events.on("measure-click",t),this.unsubscribeMeasureChanged=()=>{e.events.off("measure-changed",t),e.events.on("measure-click",t)}}}handleMeasureChanged(e){if(!this.panel)return;const t=$E(e.type);if(!t){console.warn("[MeasureDialogManager] 未知测量类型:",e.type);return}this.panel.getActiveMode()!==t&&this.panel.switchMode(t,!1);const i=this.convertToMeasureResult(e,t);this.panel.setResult(i)}convertToMeasureResult(e,t){const n=zo[t],i={};return Vg(t)==="point"?e.textX!==void 0&&e.textY!==void 0&&e.textZ!==void 0&&(i.xyz={x:e.textX,y:e.textY,z:e.textZ}):i[n.callBackType]=e.text,i}onDialogClose(){this.unsubscribeMeasureChanged&&(this.unsubscribeMeasureChanged(),this.unsubscribeMeasureChanged=null),this.registry.toolbar?.setBtnActive("measure",!1)}onBeforeDestroy(){this.unsubscribeMeasureChanged&&(this.unsubscribeMeasureChanged(),this.unsubscribeMeasureChanged=null),this.registry.engine3d&&this.registry.engine3d.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 n=this.config,i={unit:e.unit??n?.unit??"mm",precision:e.precision??n?.precision??2};this.config=i}clearAll(){this.panel&&this.panel.clearAll()}openSettings(){this.panel&&this.panel.openSettings()}}class JE{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=Yt.subscribe(()=>{this.setLocales()}),this.unsubscribeTheme=ot.subscribe(e=>{this.setTheme(e)}),this.setLocales(),this.setTheme(ot.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=xe("sectionPlane.actions.hide"),this.reverseLabelEl.textContent=xe("sectionPlane.actions.reverse"),this.resetLabelEl.textContent=xe("sectionPlane.actions.reset"),this.hideBtn.title=xe("sectionPlane.actions.hide"),this.reverseBtn.title=xe("sectionPlane.actions.reverse"),this.resetBtn.title=xe("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",rt("隐藏"),()=>{this.isHidden=!this.isHidden,this.updateButtonStates(),this.options.onHideToggle?.(this.isHidden)}),this.reverseBtn=this.createButton("reverse",rt("反向"),()=>{this.options.onReverse&&this.options.onReverse()}),this.resetBtn=this.createButton("reset",rt("重置"),()=>{this.options.onReset&&this.options.onReset()}),e.appendChild(this.hideBtn),e.appendChild(this.reverseBtn),e.appendChild(this.resetBtn),e}createButton(e,t,n){const i=document.createElement("button");i.type="button",i.className="section-plane-btn";const r=document.createElement("div");r.className="section-plane-btn-icon",r.innerHTML=t,i.appendChild(r);const o=document.createElement("div");return o.className="section-plane-btn-label",i.appendChild(o),e==="hide"?this.hideLabelEl=o:e==="reverse"?this.reverseLabelEl=o:this.resetLabelEl=o,i.addEventListener("click",n),i}}class QE extends Is{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,n=50,i=e.clientWidth,r=e.clientHeight;return{x:i-this.dialogWidth-t,y:r-this.dialogHeight-n}}createContent(){return this.panel=new JE({defaultHidden:!1,onHideToggle:e=>{console.log("[SectionPlaneDialogManager] 隐藏切换:",e),e?this.registry.engine3d?.hideSection():this.registry.engine3d?.recoverSection()},onReverse:()=>{console.log("[SectionPlaneDialogManager] 反向 (not supported in new API)")},onReset:()=>{console.log("[SectionPlaneDialogManager] 重置 (not supported in new API)")}}),this.panel.init(),this.panel.element}onDialogCreated(){this.registry.engine3d?.activeSection("face"),this.dialog?.fitHeight(!1)}onDialogClose(){this.registry.toolbar?.setBtnActive("section-plane",!1)}onBeforeDestroy(){this.registry.engine3d?.deactivateSection(),this.panel&&(this.panel.destroy(),this.panel=null)}}class eT{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=Yt.subscribe(()=>{this.setLocales()}),this.unsubscribeTheme=ot.subscribe(e=>{this.setTheme(e)}),this.setLocales(),this.setTheme(ot.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=xe("sectionAxis.actions.hide"),this.reverseLabelEl.textContent=xe("sectionAxis.actions.reverse"),this.hideBtn.title=xe("sectionAxis.actions.hide"),this.reverseBtn.title=xe("sectionAxis.actions.reverse"),this.axisXBtn.title=xe("sectionAxis.actions.axisX"),this.axisYBtn.title=xe("sectionAxis.actions.axisY"),this.axisZBtn.title=xe("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",rt("隐藏"),()=>this.handleHideToggle()),this.reverseBtn=this.createButton("reverse",rt("反向"),()=>this.handleReverse()),t.appendChild(this.hideBtn),t.appendChild(this.reverseBtn);const n=document.createElement("div");return n.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")),n.appendChild(this.axisXBtn),n.appendChild(this.axisYBtn),n.appendChild(this.axisZBtn),e.appendChild(t),e.appendChild(n),e}createButton(e,t,n){const i=document.createElement("button");i.type="button",i.className="section-axis-btn";const r=document.createElement("div");r.className="section-axis-btn-icon",r.innerHTML=t,i.appendChild(r);const o=document.createElement("div");return o.className="section-axis-btn-label",i.appendChild(o),e==="hide"?this.hideLabelEl=o:e==="reverse"&&(this.reverseLabelEl=o),i.addEventListener("click",n),i}createAxisButton(e,t,n){const i=document.createElement("button");i.type="button",i.className="section-axis-btn section-axis-btn-text";const r=document.createElement("div");return r.className="section-axis-btn-label",r.textContent=t,i.appendChild(r),i.addEventListener("click",n),i}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 tT extends Is{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,n=e.clientHeight;return{x:t-this.dialogWidth-20,y:n-50-200}}createContent(){return this.panel=new eT({defaultAxis:"x",defaultHidden:!1,onHideToggle:e=>{console.log("[SectionAxisDialogManager] 隐藏切换:",e),e?this.registry.engine3d?.hideSection():this.registry.engine3d?.recoverSection()},onReverse:()=>{console.log("[SectionAxisDialogManager] 反向剖切(暂不支持)")},onAxisChange:e=>{console.log("[SectionAxisDialogManager] 切换轴向:",e),this.registry.engine3d?.activeSection(e)}}),this.panel.init(),this.panel.element}onDialogCreated(){if(this.dialog?.fitHeight(!1),!this.registry.engine3d){console.error("[SectionAxisDialogManager] Engine not initialized. Call initEngine() first.");return}this.registry.engine3d.activeSection("x")}onDialogClose(){this.registry.toolbar?.setBtnActive("section-axis",!1)}onBeforeDestroy(){this.registry.engine3d?.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 Gg={x:{min:0,max:100},y:{min:0,max:100},z:{min:0,max:100}};class nT{element;options;isHidden=!1;isReversed=!1;range;hideBtn;reverseBtn;fitBtn;resetBtn;hideLabelEl;reverseLabelEl;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??Gg))}init(){this.element=this.createPanel(),this.unsubscribeLocale=Yt.subscribe(()=>this.setLocales()),this.unsubscribeTheme=ot.subscribe(e=>this.setTheme(e)),this.setLocales(),this.setTheme(ot.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??Gg)),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",xe("sectionBox.actions.hide"),()=>{this.isHidden=!this.isHidden,this.updateButtonStates(),this.options.onHideToggle?.(this.isHidden)},"hide"),this.reverseBtn=this.createButton("reverse",xe("sectionBox.actions.reverse"),()=>{this.isReversed=!this.isReversed,this.updateButtonStates(),this.options.onReverseToggle?.(this.isReversed)},"reverse"),this.fitBtn=this.createButton("fit",xe("sectionBox.actions.fitToModel"),()=>{this.options.onFitToModel?.()},"fit"),this.resetBtn=this.createButton("reset",xe("sectionBox.actions.reset"),()=>this.reset(),"reset"),[this.hideBtn,this.reverseBtn,this.fitBtn,this.resetBtn].forEach(i=>t.appendChild(i));const n=document.createElement("div");return n.className="section-box-sliders",n.addEventListener("pointerdown",i=>i.stopPropagation()),this.xSlider=this.createSlider("x",xe("sectionBox.axes.x")),this.ySlider=this.createSlider("y",xe("sectionBox.axes.y")),this.zSlider=this.createSlider("z",xe("sectionBox.axes.z")),[this.xSlider,this.ySlider,this.zSlider].forEach(i=>n.appendChild(i)),e.appendChild(t),e.appendChild(n),e}createButton(e,t,n,i){const r=document.createElement("button");r.className="section-box-btn",r.title=t;const o={hide:"隐藏",reverse:"反向",fit:"适应到模型",reset:"重置"},a=document.createElement("div");a.className="section-box-btn-icon",a.innerHTML=rt(o[e]||e);const l=document.createElement("div");return l.className="section-box-btn-label",l.textContent=t,i==="hide"?this.hideLabelEl=l:i==="reverse"?this.reverseLabelEl=l:i==="fit"?this.fitLabelEl=l:i==="reset"&&(this.resetLabelEl=l),r.appendChild(a),r.appendChild(l),r.addEventListener("click",n),r}createSlider(e,t){const n=document.createElement("div");n.className="section-box-slider";const i=document.createElement("div");i.className="section-box-slider-label",i.textContent=t,e==="x"?this.xLabelEl=i:e==="y"?this.yLabelEl=i:this.zLabelEl=i;const r=document.createElement("div");r.className="section-box-slider-track";const o=document.createElement("div");o.className="section-box-slider-range";const a=document.createElement("div");a.className="section-box-slider-handle",a.setAttribute("data-axis",e),a.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(o,a,l),n.append(i,r),e==="x"?(this.xMinHandle=a,this.xMaxHandle=l):e==="y"?(this.yMinHandle=a,this.yMaxHandle=l):(this.zMinHandle=a,this.zMaxHandle=l),n}setupDragListeners(){[this.xMinHandle,this.xMaxHandle,this.yMinHandle,this.yMaxHandle,this.zMinHandle,this.zMaxHandle].forEach(t=>{t.addEventListener("pointerdown",i=>{i.preventDefault(),i.stopPropagation(),t.setPointerCapture(i.pointerId),this.dragState={isDragging:!0,axis:t.getAttribute("data-axis"),handleType:t.getAttribute("data-handle"),pointerId:i.pointerId},t.classList.add("dragging"),t.closest(".section-box-slider").style.zIndex="100"}),t.addEventListener("pointermove",i=>{this.dragState.isDragging&&this.dragState.pointerId===i.pointerId&&this.onDragging(i)});const n=i=>{this.dragState.isDragging&&this.dragState.pointerId===i.pointerId&&(t.hasPointerCapture(i.pointerId)&&t.releasePointerCapture(i.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",n),t.addEventListener("pointercancel",n),t.addEventListener("lostpointercapture",n)})}onDragging(e){const{axis:t,handleType:n}=this.dragState;if(!t||!n)return;const o=(t==="x"?this.xSlider:t==="y"?this.ySlider:this.zSlider).querySelector(".section-box-slider-track").getBoundingClientRect();let a=(e.clientX-o.left)/o.width*100;a=Math.max(0,Math.min(100,a));const l=this.range[t];n==="min"?l.min=Math.min(a,l.max):l.max=Math.max(a,l.min),this.updateSliderUI(t),this.options.onRangeChange?.(this.range)}updateSliderUI(e){const t=this.range[e],n=e==="x"?this.xMinHandle:e==="y"?this.yMinHandle:this.zMinHandle,i=e==="x"?this.xMaxHandle:e==="y"?this.yMaxHandle:this.zMaxHandle,o=(e==="x"?this.xSlider:e==="y"?this.ySlider:this.zSlider).querySelector(".section-box-slider-range");n.style.left=`${t.min}%`,i.style.left=`${t.max}%`,o.style.left=`${t.min}%`,o.style.width=`${t.max-t.min}%`,n.setAttribute("data-value",Math.round(t.min).toString()),i.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),this.reverseBtn&&this.reverseBtn.classList.toggle("active",this.isReversed)}setLocales(){this.hideLabelEl&&(this.hideLabelEl.textContent=xe("sectionBox.actions.hide"),this.reverseLabelEl.textContent=xe("sectionBox.actions.reverse"),this.fitLabelEl.textContent=xe("sectionBox.actions.fitToModel"),this.resetLabelEl.textContent=xe("sectionBox.actions.reset"),this.xLabelEl.textContent=xe("sectionBox.axes.x"),this.yLabelEl.textContent=xe("sectionBox.axes.y"),this.zLabelEl.textContent=xe("sectionBox.axes.z"),this.hideBtn.title=xe("sectionBox.actions.hide"),this.reverseBtn.title=xe("sectionBox.actions.reverse"),this.fitBtn.title=xe("sectionBox.actions.fitToModel"),this.resetBtn.title=xe("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 iT extends Is{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,n=e.clientHeight;return{x:t-this.dialogWidth-20,y:n-50-300}}createContent(){return this.panel=new nT({defaultHidden:!1,defaultReversed:!1,onHideToggle:e=>{console.log("[SectionBoxDialogManager] 隐藏切换:",e),e?this.registry.engine3d?.hideSection():this.registry.engine3d?.recoverSection()},onReverseToggle:e=>{console.log("[SectionBoxDialogManager] 反向切换:",e),this.registry.engine3d?.reverseSection()},onFitToModel:()=>{this.registry.engine3d?.scaleSectionBox()},onReset:()=>{this.registry.engine3d?.deactivateSection(),this.registry.engine3d?.activeSection("box"),this.registry.engine3d?.recoverSection()},onRangeChange:e=>{this.registry.engine3d?.setSectionBoxRange(e)}}),this.panel.init(),this.panel.element}onDialogCreated(){this.registry.engine3d?.activeSection("box"),this.dialog?.fitHeight(!1);const e=this.registry.engine3d?.getEngine();if(e?.events){const t=n=>{n&&this.panel&&this.panel.setRange(n)};e.events.on("section-move",t),this.unsubscribeSectionMove=()=>e.events.off("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.registry.engine3d?.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 sT{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=Yt.subscribe(()=>this.setLocales()),this.unsubscribeTheme=ot.subscribe(e=>this.setTheme(e)),this.setLocales(),this.setTheme(ot.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(),n=document.createElement("div");n.className="walk-divider",this.settingsContainer=this.createSettingsContainer();const i=document.createElement("div");i.className="walk-divider";const r=this.createExitButton();return e.appendChild(t),e.appendChild(n),e.appendChild(this.settingsContainer),e.appendChild(i),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 n=document.createElement("label");n.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",n.appendChild(this.collisionCheckbox),n.appendChild(this.collisionLabel);const i=document.createElement("div");i.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)}),i.appendChild(this.characterModelLabel),i.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(i),e.appendChild(r),e.appendChild(t),e.appendChild(n),e}createSpeedControl(){const e=document.createElement("div");e.className="walk-speed-control";const t=document.createElement("label");t.className="walk-speed-label",t.textContent=xe("walkControl.speed");const n=document.createElement("div");return n.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))}),n.appendChild(this.speedDecreaseBtn),n.appendChild(this.speedDisplay),n.appendChild(this.speedIncreaseBtn),e.appendChild(t),e.appendChild(n),e}createIconButton(e,t){const n=document.createElement("button");return n.className=`walk-icon-btn walk-icon-btn-${e}`,n.innerHTML=this.getIconSVG(e),n.addEventListener("click",t),n}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,n=this.collisionCheckbox.parentElement,i=this.characterModelSelect.parentElement,r=this.walkModeSelect.parentElement;this.state.mode==="walk"?(e.style.display="none",t.style.display="flex",n.style.display="flex",i.style.display="flex",r.style.display="flex"):(e.style.display="flex",t.style.display="flex",n.style.display="flex",i.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":rt("地图"),path:rt("路径漫游"),walk:rt("第一人称漫游")}[e]||""}setLocales(){const e=this.speedControl.querySelector(".walk-speed-label");e&&(e.textContent=xe("walkControl.speed")),this.gravityLabel.textContent=xe("walkControl.gravity"),this.collisionLabel.textContent=xe("walkControl.collision"),this.characterModelLabel.textContent=xe("walkControl.characterModel.label"),this.characterModelSelect.innerHTML="";const t=document.createElement("option");t.value="construction-worker",t.textContent=xe("walkControl.characterModel.constructionWorker"),t.selected=this.state.characterModel==="construction-worker",this.characterModelSelect.appendChild(t);const n=document.createElement("option");n.value="office-male",n.textContent=xe("walkControl.characterModel.officeMale"),n.selected=this.state.characterModel==="office-male",this.characterModelSelect.appendChild(n),this.walkModeLabel.textContent=xe("walkControl.walkMode.label"),this.walkModeSelect.innerHTML="";const i=document.createElement("option");i.value="walk",i.textContent=xe("walkControl.walkMode.walk"),i.selected=this.state.walkMode==="walk",this.walkModeSelect.appendChild(i);const r=document.createElement("option");r.value="run",r.textContent=xe("walkControl.walkMode.run"),r.selected=this.state.walkMode==="run",this.walkModeSelect.appendChild(r),this.exitBtn.textContent=xe("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 rT{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=Yt.subscribe(()=>this.render()),this.unsubscribeTheme=ot.subscribe(e=>this.setTheme(e)),this.loadPointsFromEngine(),this.render(),this.setTheme(ot.getTheme())}loadPointsFromEngine(){const e=this.registry.engine3d?.pathRoamingGetPoints()??[];this.points=e.map((t,n)=>({index:n}))}render(){this.element.innerHTML="";const e=this.createSettingsSection();this.element.appendChild(e);const t=this.createPointsSection();this.element.appendChild(t);const n=this.createPlayButton();this.element.appendChild(n)}createSettingsSection(){const e=document.createElement("div");e.className="walk-path-settings";const t=document.createElement("div");t.className="walk-path-form-group";const n=document.createElement("label");n.textContent=xe("walkControl.path.duration");const i=document.createElement("div");i.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 u=parseInt(h.target.value)||1;this.duration=u*1e3};const o=document.createElement("span");o.className="walk-path-unit",o.textContent=xe("walkControl.path.durationUnit"),i.appendChild(r),i.appendChild(o),t.appendChild(n),t.appendChild(i);const a=document.createElement("div");a.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=xe("walkControl.path.loop"),a.appendChild(l),a.appendChild(c),e.appendChild(t),e.appendChild(a),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 n=document.createElement("button");n.className="walk-path-btn walk-path-btn-small",n.textContent=`+ ${xe("walkControl.path.addPoint")}`,n.onclick=()=>this.addPoint();const i=document.createElement("button");i.className="walk-path-btn walk-path-btn-small walk-path-btn-danger",i.textContent=xe("walkControl.path.deleteAll"),i.onclick=()=>this.deleteAllPoints(),t.appendChild(n),t.appendChild(i),e.appendChild(t);const r=document.createElement("div");if(r.className="walk-path-points-list",this.points.length===0){const o=document.createElement("div");o.className="walk-path-empty",o.textContent=xe("walkControl.path.noPoints"),r.appendChild(o)}else this.points.forEach((o,a)=>{const l=this.createPointItem(a);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 n=document.createElement("span");n.className="walk-path-point-name",n.textContent=`${xe("walkControl.path.point")}${e}`;const i=document.createElement("div");i.className="walk-path-point-actions";const r=document.createElement("button");r.className="walk-path-btn-icon",r.innerHTML="▶",r.title=xe("walkControl.path.play"),r.onclick=a=>{a.stopPropagation(),this.jumpToPoint(e)};const o=document.createElement("button");return o.className="walk-path-btn-icon walk-path-btn-icon-danger",o.innerHTML="×",o.onclick=a=>{a.stopPropagation(),this.deletePoint(e)},i.appendChild(r),i.appendChild(o),t.appendChild(n),t.appendChild(i),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=`▶ ${xe("walkControl.path.play")}`,t.disabled=this.points.length===0||this.isPlaying,t.onclick=()=>this.playPath();const n=document.createElement("button");return n.className="walk-path-btn walk-path-btn-stop",n.textContent=`■ ${xe("walkControl.path.stop")}`,n.disabled=!this.isPlaying,n.onclick=()=>this.stopPath(),e.appendChild(t),e.appendChild(n),e}addPoint(){this.registry.engine3d?.pathRoamingAddPoint();const e=this.points.length;this.points.push({index:e}),this.render()}deletePoint(e){this.registry.engine3d?.pathRoamingRemovePoint(e),this.points.splice(e,1),this.points.forEach((t,n)=>t.index=n),this.render()}deleteAllPoints(){this.registry.engine3d?.pathRoamingClearPoints(),this.points=[],this.render()}jumpToPoint(e){this.registry.engine3d?.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?.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?.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 oT extends Is{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 rT(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 aT extends pi{panel=null;pathManager=null;constructor(e){super(e)}init(){this.pathManager=new oT(this.registry),this.pathManager.init()}show(){if(!this.registry.toolbar){console.warn("Toolbar not initialized");return}this.registry.toolbar.hide(),console.log("[WalkControl] 打开漫游面板,激活第一人称模式"),this.registry.engine3d?.activateFirstPersonMode(),this.panel=new sT({onPlanViewToggle:e=>{console.log("[WalkControl] 小地图:",e),this.registry.engine3d?.toggleMiniMap(),this.emit("walk:plan-view-toggle",{isActive:e})},onPathModeToggle:e=>{console.log("[WalkControl] 路径漫游:",e),e?this.pathManager?.show():this.pathManager?.hide(),this.emit("walk:path-mode-toggle",{isActive:e})},onWalkModeToggle:e=>{console.log("[WalkControl] 第三人称漫游按钮点击:",e),e&&(this.pathManager?.hide(),alert("第三人称功能开发中")),this.emit("walk:walk-mode-toggle",{isActive:e})},onSpeedChange:e=>{console.log("[WalkControl] 速度变化:",e);const t=e*.1;this.registry.engine3d?.setWalkSpeed(t),this.emit("walk:speed-change",{speed:e})},onGravityToggle:e=>{console.log("[WalkControl] 重力:",e),this.registry.engine3d?.setWalkGravity(e),this.emit("walk:gravity-toggle",{enabled:e})},onCollisionToggle:e=>{console.log("[WalkControl] 碰撞:",e),this.registry.engine3d?.setWalkCollision(e),this.emit("walk:collision-toggle",{enabled:e})},onCharacterModelChange:e=>{console.log("[WalkControl] 角色模型:",e)},onWalkModeChange:e=>{console.log("[WalkControl] 行走模式:",e)},onExit:()=>{this.hide()}}),this.panel.init(),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(),console.log("[WalkControl] 关闭漫游面板,退出第一人称模式"),this.registry.engine3d?.deactivateFirstPersonMode(),this.panel&&(this.panel.destroy(),this.panel=null),this.registry.toolbar&&this.registry.toolbar.show()}destroy(){this.hide(),this.pathManager?.destroy(),this.pathManager=null,super.destroy()}}class lT extends Is{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,n=e.clientHeight;return{x:(t-this.dialogWidth)/2,y:(n-150)/2}}createContent(){const e=this.registry.engine3d?.getEngineInfo()??null,t=document.createElement("div");t.className="engine-info-content",t.style.cssText="padding: 16px;";const n=(i,r)=>{const o=document.createElement("div");o.style.cssText="display: flex; justify-content: space-between; margin-bottom: 12px; font-size: 14px;";const a=document.createElement("span");a.style.cssText="color: var(--bim-text-secondary, #94a3b8);",a.textContent=i;const l=document.createElement("span");return l.style.cssText="color: var(--bim-text-primary, #fff); font-weight: 500;",l.textContent=String(r),o.appendChild(a),o.appendChild(l),o};return t.appendChild(n(xe("info.meshCount"),e?.meshCount??"-")),t.appendChild(n(xe("info.totalTriangles"),e?.totalTriangles??"-")),t.appendChild(n(xe("info.totalVertices"),e?.totalVertices??"-")),t}}class cT extends Is{get dialogId(){return"setting-dialog"}get dialogTitle(){return"setting.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,n=e.clientHeight;return{x:(t-this.dialogWidth)/2,y:(n-200)/2}}createContent(){const e=this.registry.engine3d?.getRenderMode()??"balance",t=document.createElement("div");t.style.cssText="padding: 16px;";const n=document.createElement("div");n.style.cssText="font-size: 13px; color: var(--bim-text-secondary, #94a3b8); margin-bottom: 12px;",n.textContent=xe("setting.renderMode"),t.appendChild(n);const i=[{key:"simple",labelKey:"setting.modes.simple"},{key:"balance",labelKey:"setting.modes.balance"},{key:"advanced",labelKey:"setting.modes.advanced"}],r=document.createElement("div");r.style.cssText="display: flex; flex-direction: column; gap: 4px;";for(const o of i){const a=document.createElement("div");a.style.cssText=` display: flex; align-items: center; gap: 10px; padding: 10px 12px; border-radius: 6px; cursor: pointer; transition: background 0.15s; background: ${o.key===e?"var(--bim-primary, #3b82f6)":"transparent"}; color: ${o.key===e?"var(--bim-text-inverse, #fff)":"var(--bim-text-primary, #fff)"}; `;const l=document.createElement("div");if(l.style.cssText=` width: 16px; height: 16px; border-radius: 50%; flex-shrink: 0; border: 2px solid ${o.key===e?"var(--bim-text-inverse, #fff)":"var(--bim-text-tertiary, #64748b)"}; display: flex; align-items: center; justify-content: center; `,o.key===e){const h=document.createElement("div");h.style.cssText="width: 8px; height: 8px; border-radius: 50%; background: var(--bim-text-inverse, #fff);",l.appendChild(h)}const c=document.createElement("span");c.style.cssText="font-size: 14px; font-weight: 500;",c.textContent=xe(o.labelKey),a.appendChild(l),a.appendChild(c),a.addEventListener("mouseenter",()=>{o.key!==e&&(a.style.background="var(--bim-floating-btn-bg, rgba(255,255,255,0.08))")}),a.addEventListener("mouseleave",()=>{o.key!==e&&(a.style.background="transparent")}),a.addEventListener("click",()=>{this.registry.engine3d?.setRenderMode(o.key),this.hide(),this.show()}),r.appendChild(a)}return t.appendChild(r),t}}class hT{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=xe(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=xe(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 Wg{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(n=>this.activeIds.add(n)),this.init()}init(){this.options.items.forEach(e=>{const t=new hT(e,this);this.items.set(e.id,t),this.element.appendChild(t.element),this.activeIds.has(e.id)&&t.setActive(!0)}),this.unsubscribeLocale=Yt.subscribe(()=>{this.setLocales()}),this.unsubscribeTheme=ot.subscribe(e=>{this.setTheme(e)}),this.setTheme(ot.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 uT extends pi{dialogId="component-detail-dialog";dialog=null;currentSelection=null;unsubscribeSelected=null;unsubscribeDeselected=null;tabInstance=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.registry.engine3d?.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=xe("panel.componentDetail.noSelection")||"请先选中构件",this.dialog.setContent(e)}renderTabbedContent(){if(!this.dialog)return;this.tabInstance&&(this.tabInstance.destroy(),this.tabInstance=null);const e=document.createElement("div");e.style.cssText="height:100%;display:flex;flex-direction:column;";const t=this.createPropertiesPanel(),n=this.createMaterialsPanel();this.tabInstance=new Ug({container:e,activeId:"properties",tabs:[{id:"properties",title:"panel.property.tab.props",content:t},{id:"materials",title:"panel.property.tab.material",content:n}]}),this.tabInstance.init(),this.dialog.setContent(e)}createPropertiesPanel(){const e=document.createElement("div");e.style.cssText="height:100%;overflow-y:auto;";const t=this.propertiesData?.properties||[];if(t.length===0)return e.innerHTML='
无属性数据
',e;const n=t.map((r,o)=>({id:`category-${o}`,title:r.name||`分类 ${o+1}`,content:this.createCategoryContent(r.children||[])}));new Wg({container:e,accordion:!1,ghost:!0,activeIds:n.length>0?[n[0].id]:[],items:n});const i=document.createElement("style");return i.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(i),e}createMaterialsPanel(){const e=document.createElement("div");e.style.cssText="height:100%;overflow-y:auto;";const t=this.propertiesData?.materials||[];if(t.length===0)return e.innerHTML='
无材质数据
',e;const n=t.map((r,o)=>({id:`material-${o}`,title:r.name||`材质 ${o+1}`,content:this.createCategoryContent(r.children||r.properties||[])}));new Wg({container:e,accordion:!1,ghost:!0,activeIds:n.length>0?[n[0].id]:[],items:n});const i=document.createElement("style");return i.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(i),e}createCategoryContent(e){const t=document.createElement("div");return e.forEach((n,i)=>{const r=document.createElement("div");r.style.cssText=` display: flex; border-bottom: 1px solid var(--bim-border-default, rgba(255,255,255,0.15)); `,i===e.length-1&&(r.style.borderBottom="none");const o=document.createElement("div");o.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)); `,o.textContent=n.name||"-";const a=document.createElement("div");a.style.cssText=` flex: 1; color: var(--bim-text-primary, #fff); font-size: 13px; padding: 8px 12px; word-break: break-all; `,a.textContent=String(n.value??"-"),r.appendChild(o),r.appendChild(a),t.appendChild(r)}),t}isOpen(){return this.dialog!==null}hide(){this.tabInstance&&(this.tabInstance.destroy(),this.tabInstance=null),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 dT{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=ot.subscribe(e=>{this.setTheme(e)}),this.unsubscribeLocale=Yt.subscribe(()=>{this.setLocales()}),this.setTheme(ot.getTheme()),this.setLocales()}setTheme(e){const t=e.name==="dark"||e.name?.includes("dark");this.element.classList.toggle("light",!t);const n=this.element.style;n.setProperty("--bim-ai-accent",e.primary),n.setProperty("--bim-ai-text",e.textPrimary),n.setProperty("--bim-ai-muted",e.textTertiary),n.setProperty("--bim-ai-border",e.borderDefault),n.setProperty("--bim-ai-shadow",e.shadowLg)}setLocales(){const e=this.element.querySelector(".bim-ai-chat-title");e&&this.options.title&&(e.textContent=xe(this.options.title));const t=this.element.querySelector(".bim-ai-textarea");t&&this.options.placeholder&&(t.placeholder=xe(this.options.placeholder));const n=this.element.querySelector(".bim-ai-helper-left");n&&(n.textContent=xe("aiChat.helper.newline"));const i=this.element.querySelector(".bim-ai-helper-right");i&&(i.textContent=xe("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,n=Math.max(50,e-t-50);this.element.style.left=`${n}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 n=this.messages.findIndex(i=>i.id===e);n!==-1&&(this.messages[n]={...this.messages[n],...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 n=`step-${Date.now()}`;return this.addMessage({id:n,type:"step",status:e,content:t,timestamp:Date.now()}),n}addThinkingMessage(){const e=`thinking-${Date.now()}`;return this.addMessage({id:e,type:"thinking",timestamp:Date.now()}),e}addQuestionMessage(e,t,n){const i=`question-${Date.now()}`;return this.addMessage({id:i,type:"question",title:e,question:t,options:n,answered:!1,timestamp:Date.now()}),i}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(o=>{o.addEventListener("click",a=>{switch(a.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",o=>{o.key==="Enter"&&!o.shiftKey&&(o.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 i=o=>o.stopPropagation();["click","dblclick","mousedown","mouseup","mousemove","wheel","touchstart","touchend","touchmove"].forEach(o=>{e.addEventListener(o,i,{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,n=0,i=0,r=0,o=0,a=0,l=0,c=0;const h=d=>{d.target.closest(".bim-ai-chat-action-btn")||(d.preventDefault(),d.stopPropagation(),t=d.clientX,n=d.clientY,i=this.element.offsetLeft,r=this.element.offsetTop,o=this.container.clientWidth,a=this.container.clientHeight,l=this.element.offsetWidth,c=this.element.offsetHeight,document.addEventListener("mousemove",u,{capture:!0}),document.addEventListener("mouseup",f,{capture:!0}))},u=d=>{d.preventDefault(),d.stopPropagation(),!this.rafId&&(this.rafId=requestAnimationFrame(()=>{const m=d.clientX-t,p=d.clientY-n;let x=i+m,g=r+p;const b=o-l,v=a-c;x=Math.max(0,Math.min(x,b)),g=Math.max(0,Math.min(g,v)),this.element.style.left=`${x}px`,this.element.style.top=`${g}px`,this.rafId=null}))},f=()=>{this.rafId&&(cancelAnimationFrame(this.rafId),this.rafId=null),document.removeEventListener("mousemove",u,{capture:!0}),document.removeEventListener("mouseup",f,{capture:!0})};e.addEventListener("mousedown",h)}updateQuickPrompts(e){const n=(e||this.element).querySelector(".bim-ai-quick-prompts");!n||!this.options.quickPrompts||(n.innerHTML=this.options.quickPrompts.map(i=>` `).join(""),n.querySelectorAll(".bim-ai-quick-prompt").forEach(i=>{i.addEventListener("click",r=>{const o=r.currentTarget.dataset.promptId,a=this.options.quickPrompts?.find(l=>l.id===o);a&&this.textarea&&(this.textarea.value=xe(a.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`
${rt({running:"loader",done:"check",error:"error"}[e])} ${this.escapeHtml(t)}
`}renderThinkingMessage(){return`
${rt("loader")} ${xe("aiChat.thinking")}
`}renderActiveQuestion(e){const t=e.options.map(n=>`
${n.isOther?xe("aiChat.other"):this.escapeHtml(n.label)}
${n.isOther&&e.selectedOptionId===n.id?` `:""} `).join("");return`
${rt("bot")}
${this.escapeHtml(e.title)}
${this.escapeHtml(e.question)}
${t}
`}renderAnsweredQuestion(e){const t=e.options.find(i=>i.id===e.selectedOptionId),n=t?.isOther?e.customAnswer:t?.label;return`
Q
${this.escapeHtml(e.question)}
A
${this.escapeHtml(n||"")}
`}bindQuestionEvents(){this.messagesContainer?.querySelectorAll(".bim-ai-option").forEach(e=>{e.addEventListener("click",t=>{const n=t.currentTarget,i=n.dataset.questionId,r=n.dataset.optionId;if(i&&r){const o=this.messages.find(a=>a.id===i);o&&!o.answered&&(o.selectedOptionId=r,this.renderMessages())}})}),this.messagesContainer?.querySelectorAll(".bim-ai-option-input").forEach(e=>{e.addEventListener("input",t=>{const n=t.target,i=n.dataset.questionId;if(i){const r=this.messages.find(o=>o.id===i);r&&(r.customAnswer=n.value)}})}),this.messagesContainer?.querySelectorAll(".bim-ai-question-submit").forEach(e=>{e.addEventListener("click",t=>{const i=t.currentTarget.dataset.questionId;if(i){const r=this.messages.find(o=>o.id===i);r&&r.selectedOptionId&&(r.answered=!0,this.renderMessages(),this.options.onQuestionSubmit?.(i,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 fT{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 dT({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,n,i)=>{console.log("[AiChatManager] 用户回答问题:",{questionId:t,optionId:n,customAnswer:i}),this.registry.emit("aiChat:question-answered",{questionId:t,optionId:n,customAnswer:i})},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,n){return this.aiChat?.addQuestionMessage(e,t,n)??""}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 pT{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 n=this.events.get(e);if(!n)return;const i=n.indexOf(t);i!==-1&&n.splice(i,1)}emit(e,t){const n=this.events.get(e);n&&n.forEach(i=>{try{i(t)}catch(r){console.error(`[EventEmitter] Error in listener for event "${e}":`,r)}})}clear(){this.events.clear()}}class mT{eventEmitter=new pT;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;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}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 gT{container;wrapper=null;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;constructor(e,t){const n=typeof e=="string"?document.getElementById(e):e;if(!n)throw new Error("Container not found");this.container=n,this.registry=new mT,t?.locale&&Yt.setLocale(t.locale),t?.theme&&(t.theme==="custom"?console.warn("Custom theme should be set via setCustomTheme()."):ot.setTheme(t.theme)),this.init()}emit(e,t){this.registry.emit(e,t)}on(e,t){return this.registry.on(e,t)}setLocale(e){Yt.setLocale(e)}getLocale(){return Yt.getLocale()}setTheme(e){ot.setTheme(e)}setCustomTheme(e){ot.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="v1.1.8",this.wrapper.appendChild(e),this.registry.container=this.container,this.registry.wrapper=this.wrapper,this.engine=new GE(this.wrapper,this.registry),this.dialog=new a0(this.wrapper,this.registry),this.toolbar=new s0(this.wrapper,this.registry),this.buttonGroup=new r0(this.wrapper,this.registry),this.rightKey=new kg(this.wrapper,this.registry),this.constructTreeBtn=new YE(this.wrapper,this.registry),this.measure=new KE(this.registry),this.sectionPlane=new QE(this.registry),this.sectionAxis=new tT(this.registry),this.sectionBox=new iT(this.registry),this.walkControl=new aT(this.registry),this.walkControl.init(),this.engineInfo=new lT(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 uT(this.registry),this.registry.componentDetail=this.componentDetail,this.componentDetail.init(),this.aiChat=new fT(this.registry),this.registry.aiChat=this.aiChat,this.aiChat.init(),this.setting=new cT(this.registry),this.registry.setting=this.setting,this.setting.init(),this.updateTheme(ot.getTheme()),ot.subscribe(t=>{this.updateTheme(t)})}updateTheme(e){this.wrapper&&(this.wrapper.style.color=e.textPrimary)}destroy(){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.container.innerHTML="",this.registry.reset()}}const xT=Object.freeze(Object.defineProperty({__proto__:null,createHomeButton:s=>({id:"home",groupId:"group-1",type:"button",label:"toolbar.home",icon:rt("主视角"),keepActive:!1,onClick:e=>{console.log("首页按钮被点击:",e.id),s.engine3d?.CameraGoHome()}})},Symbol.toStringTag,{value:"Module"})),vT=Object.freeze(Object.defineProperty({__proto__:null,createZoomBoxButton:s=>({id:"zoom-box",groupId:"group-1",keepActive:!1,type:"button",label:"toolbar.zoomBox",icon:rt("框选放大"),onClick:()=>{s.engine3d?.activateZoomBox()}})},Symbol.toStringTag,{value:"Module"})),bT=Object.freeze(Object.defineProperty({__proto__:null,createWalkMenuButton:s=>({id:"walk",groupId:"group-1",type:"button",label:"toolbar.walk",align:"vertical",icon:rt("漫游"),onClick:()=>{console.log("漫游按钮被点击"),s.walkControl?.show()}})},Symbol.toStringTag,{value:"Module"})),yT=Object.freeze(Object.defineProperty({__proto__:null,createMapButton:s=>({id:"map",groupId:"group-1",type:"button",label:"toolbar.map",align:"vertical",keepActive:!0,icon:rt("地图"),onClick:()=>{s.engine3d?.toggleMiniMap()}})},Symbol.toStringTag,{value:"Module"})),_T=Object.freeze(Object.defineProperty({__proto__:null,createPropertyButton:s=>({id:"property",groupId:"group-1",type:"button",label:"toolbar.property",align:"vertical",icon:rt("文档"),onClick:()=>{console.log("构件详情按钮被点击"),s.componentDetail?.show()}})},Symbol.toStringTag,{value:"Module"})),MT=Object.freeze(Object.defineProperty({__proto__:null,createSettingButton:s=>({id:"setting",groupId:"group-2",type:"button",label:"toolbar.setting",icon:rt("设置"),keepActive:!1,onClick:e=>{s?.setting?.toggle()}})},Symbol.toStringTag,{value:"Module"})),wT=Object.freeze(Object.defineProperty({__proto__:null,createInfoButton:s=>({id:"info",groupId:"group-2",type:"button",label:"toolbar.info",icon:rt("信息"),keepActive:!1,onClick:()=>{s.engineInfo?.show()}})},Symbol.toStringTag,{value:"Module"})),ST=Object.freeze(Object.defineProperty({__proto__:null,createFullscreenButton:s=>({id:"fullscreen",groupId:"group-2",type:"button",label:"toolbar.fullscreen",align:"vertical",icon:rt("全屏"),onClick:async()=>{console.log("全屏按钮被点击"),window.self!==window.top&&console.warn('检测到在 Iframe 中运行,请确保父级 iframe 标签拥有 allow="fullscreen" 属性');try{const t=document,i=!!(t.fullscreenElement||t.webkitFullscreenElement||t.mozFullScreenElement||t.msFullscreenElement);console.log("当前是否全屏:",i);const o=document.querySelector(".bim-engine-container")||document.body,a=o;if(i){console.log("准备退出全屏...");const l=t.exitFullscreen||t.webkitExitFullscreen||t.mozCancelFullScreen||t.msExitFullscreen;l&&(await l.call(t),console.log("退出全屏请求已发送"))}else{console.log("准备进入全屏..."),(o.style.backgroundColor===""||o.style.backgroundColor==="transparent")&&(o.style.backgroundColor="#ffffff");const l=a.requestFullscreen||a.webkitRequestFullscreen||a.mozRequestFullScreen||a.msRequestFullscreen;l?(await l.call(a,{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"})),ET=Object.freeze(Object.defineProperty({__proto__:null,createMeasureButton:s=>({id:"measure",groupId:"group-1",type:"button",label:"toolbar.measure",icon:rt("测量"),keepActive:!0,onClick:e=>{e.isActive?s.measure?.show():s.measure?.destroy()}})},Symbol.toStringTag,{value:"Module"})),TT=Object.freeze(Object.defineProperty({__proto__:null,createSectionMenuButton:s=>({id:"section",groupId:"group-1",type:"menu",label:"toolbar.section",align:"vertical",icon:rt("剖切"),keepActive:!0,onClick:e=>{console.log("剖切按钮被点击:",e.id)}})},Symbol.toStringTag,{value:"Module"})),CT=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:rt("拾曲面剖切"),onClick:e=>{console.log("拾取面剖切被点击:",e.id,"激活状态:",e.isActive),e.isActive?s.sectionPlane?.show():s.sectionPlane?.hide()}})},Symbol.toStringTag,{value:"Module"})),AT=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:rt("轴向剖切"),onClick:e=>{e.isActive?s.sectionAxis?.show():s.sectionAxis?.destroy()}})},Symbol.toStringTag,{value:"Module"})),PT=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:rt("剖切盒"),onClick:e=>{console.log("剖切盒被点击:",e.id,"激活状态:",e.isActive),e.isActive?s.sectionBox?.show():s.sectionBox?.hide()}})},Symbol.toStringTag,{value:"Module"})),RT=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:rt("bot"),onClick:()=>{s.aiChat?.toggle()}})},Symbol.toStringTag,{value:"Module"})),LT=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"})),IT=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"})),DT=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"}));Ns.BimEngine=gT,Object.defineProperty(Ns,Symbol.toStringTag,{value:"Module"})})); //# sourceMappingURL=iflow-engine.umd.js.map