rayzee 8.6.0 → 8.6.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -53
- package/dist/{DLSSNeural-BhBCBgKf.js → NeuralRetouch-CYOJ21Wn.js} +31 -31
- package/dist/{DLSSSuperRes-BCA7F_k5.js → NeuralSuperRes-Dc6jRYke.js} +23 -23
- package/dist/{ToneMapGPU-BzcLheoR.js → ToneMapGPU-BVE852iN.js} +2 -2
- package/dist/rayzee.es.js +49 -39
- package/dist/rayzee.umd.js +5 -5
- package/package.json +1 -1
- package/src/AssetConfig.js +6 -5
- package/src/Passes/OIDNDenoiser.js +13 -5
- package/src/index.js +3 -3
- package/src/managers/DenoisingManager.js +60 -44
- package/src/{dlss/DLSSNeural.js → neural/NeuralRetouch.js} +42 -41
- package/src/{dlss/DLSSSuperRes.js → neural/NeuralSuperRes.js} +27 -26
package/dist/rayzee.umd.js
CHANGED
|
@@ -112,7 +112,7 @@
|
|
|
112
112
|
return seed;
|
|
113
113
|
|
|
114
114
|
}
|
|
115
|
-
`,[ne,z]),ye={ALWAYS:`always`,PER_CYCLE:`per_cycle`,PER_TILE:`per_tile`,CONDITIONAL:`conditional`},V=class{constructor(e,t={}){this.name=e,this.enabled=t.enabled!==!1,this.executionMode=t.executionMode||ye.ALWAYS,this.context=null,this.eventBus=null}initialize(e,t){this.context=e,this.eventBus=t,this.setupEventListeners()}setupEventListeners(){}shouldExecuteThisFrame(e){if(!this.enabled)return!1;let t=e.getState(`renderMode`)||0,n=e.getState(`tileRenderingComplete`);switch(this.executionMode){case ye.ALWAYS:return!0;case ye.PER_CYCLE:return t===0?!0:n===!0;case ye.PER_TILE:return!0;case ye.CONDITIONAL:return this.shouldExecute(e);default:return this.warn(`Unknown execution mode: ${this.executionMode}`),!0}}shouldExecute(e){return!0}render(e,t){throw Error(`render() must be implemented in ${this.name}`)}reset(){}setSize(e,t){}dispose(){}emit(e,t){this.eventBus&&this.eventBus.emit(e,t)}on(e,t){this.eventBus&&this.eventBus.on(e,t)}once(e,t){this.eventBus&&this.eventBus.once(e,t)}off(e,t){this.eventBus&&this.eventBus.off(e,t)}enable(){this.enabled||(this.enabled=!0,this.emit(`stage:enabled`,{stage:this.name}))}disable(){this.enabled&&(this.enabled=!1,this.emit(`stage:disabled`,{stage:this.name}))}toggle(){this.enabled?this.disable():this.enable()}isEnabled(){return this.enabled}log(...e){console.log(`[${this.name}]`,...e)}warn(...e){console.warn(`[${this.name}]`,...e)}error(...e){console.error(`[${this.name}]`,...e)}},be=class{constructor(e,t,n={}){this.renderer=e,this.material=t,this.interactionModeEnabled=n.enabled===void 0?!0:n.enabled,this.interactionDelay=n.delay||100,this.interactionMode=!1,this.interactionTimeout=null,this.originalValues={},this.appliedValues={},this.wasAccumulationEnabled=!0,this.interactionQualitySettings={enableAccumulation:!1,...n.qualitySettings},this.onEnterCallback=n.onEnter||null,this.onExitCallback=n.onExit||null,this.onResetCallback=n.onReset||null}enterInteractionMode(){this.interactionModeEnabled&&(this.interactionMode?clearTimeout(this.interactionTimeout):(this.interactionMode=!0,this.originalValues={},this.appliedValues={},this.material.uniforms.enableAccumulation&&(this.wasAccumulationEnabled=this.material.uniforms.enableAccumulation.value),Object.keys(this.interactionQualitySettings).forEach(e=>{e===`pixelRatio`?(this.originalValues.dpr=this.renderer.getPixelRatio(),this.renderer.setPixelRatio(this.interactionQualitySettings.pixelRatio)):e===`enableAccumulation`||this.material.uniforms[e]&&(this.originalValues[e]=this.material.uniforms[e].value,this.material.uniforms[e].value=this._resolveQualityValue(e,this.interactionQualitySettings[e]),this.appliedValues[e]=this.material.uniforms[e].value)}),this.material.uniforms.enableAccumulation&&(this.originalValues.enableAccumulation=this.material.uniforms.enableAccumulation.value,this.material.uniforms.enableAccumulation.value=!1),this.material.uniforms.cameraIsMoving&&(this.originalValues.cameraIsMoving=this.material.uniforms.cameraIsMoving.value,this.material.uniforms.cameraIsMoving.value=!0),this.onEnterCallback&&this.onEnterCallback()),this.interactionTimeout=setTimeout(()=>{this.exitInteractionMode()},this.interactionDelay))}exitInteractionMode(){this.interactionMode&&(Object.keys(this.originalValues).forEach(e=>{if(e===`dpr`)this.renderer.setPixelRatio(this.originalValues.dpr);else if(this.material.uniforms[e]){let t=this.appliedValues[e];(t===void 0||this.material.uniforms[e].value===t)&&(this.material.uniforms[e].value=this.originalValues[e])}}),this.interactionMode=!1,this.originalValues={},this.appliedValues={},this.onExitCallback&&this.onExitCallback(),this.onResetCallback&&this.onResetCallback())}updateInteractionMode(e){e&&this.enterInteractionMode()}setInteractionModeEnabled(e){this.interactionModeEnabled=e,!e&&this.interactionMode&&(clearTimeout(this.interactionTimeout),this.exitInteractionMode())}updateQualitySettings(e){Object.assign(this.interactionQualitySettings,e),this.interactionMode&&Object.keys(e).forEach(t=>{t===`pixelRatio`?this.renderer.setPixelRatio(e.pixelRatio):this.material.uniforms[t]&&(this.material.uniforms[t].value=this._resolveQualityValue(t,e[t]),this.appliedValues[t]=this.material.uniforms[t].value)})}_resolveQualityValue(e,t){return typeof t==`function`?t(this.originalValues[e]??this.material.uniforms[e].value):t}setInteractionDelay(e){this.interactionDelay=e}getState(){return{interactionMode:this.interactionMode,interactionModeEnabled:this.interactionModeEnabled,interactionDelay:this.interactionDelay,hasTimeout:this.interactionTimeout!==null,qualitySettings:{...this.interactionQualitySettings},originalValues:{...this.originalValues},wasAccumulationEnabled:this.wasAccumulationEnabled}}forceExitInteractionMode(){this.interactionTimeout&&=(clearTimeout(this.interactionTimeout),null),this.exitInteractionMode()}isInInteractionMode(){return this.interactionMode}setCallbacks(e){e.onEnter&&(this.onEnterCallback=e.onEnter),e.onExit&&(this.onExitCallback=e.onExit),e.onReset&&(this.onResetCallback=e.onReset)}static createQualityPreset(e){let t={"ultra-low":{maxBounceCount:1,pixelRatio:.125,enableAccumulation:!1},low:{maxBounceCount:1,pixelRatio:.25,enableAccumulation:!1},medium:{maxBounceCount:2,pixelRatio:.5,enableAccumulation:!1},high:{maxBounceCount:3,pixelRatio:.75,enableAccumulation:!0}};return t[e]||t.low}dispose(){this.interactionTimeout&&=(clearTimeout(this.interactionTimeout),null),this.interactionMode&&this.forceExitInteractionMode(),this.onEnterCallback=null,this.onExitCallback=null,this.onResetCallback=null}},H,xe=y((()=>{H={RENDER_COMPLETE:`engine:renderComplete`,RENDER_RESET:`engine:renderReset`,FRAME:`engine:frame`,DENOISING_START:`engine:denoisingStart`,DENOISING_END:`engine:denoisingEnd`,UPSCALING_START:`engine:upscalingStart`,UPSCALING_PROGRESS:`engine:upscalingProgress`,UPSCALING_END:`engine:upscalingEnd`,LOADING_UPDATE:`engine:loadingUpdate`,LOADING_RESET:`engine:loadingReset`,STATS_UPDATE:`engine:statsUpdate`,OBJECT_SELECTED:`engine:objectSelected`,OBJECT_DESELECTED:`engine:objectDeselected`,OBJECT_DOUBLE_CLICKED:`engine:objectDoubleClicked`,SELECT_MODE_CHANGED:`engine:selectModeChanged`,OBJECT_TRANSFORM_START:`engine:objectTransformStart`,OBJECT_TRANSFORM_END:`engine:objectTransformEnd`,TRANSFORM_MODE_CHANGED:`engine:transformModeChanged`,AUTO_FOCUS_UPDATED:`engine:autoFocusUpdated`,AUTO_EXPOSURE_UPDATED:`engine:autoExposureUpdated`,AF_POINT_PLACED:`engine:afPointPlaced`,SETTING_CHANGED:`engine:settingChanged`,ANIMATION_STARTED:`engine:animationStarted`,ANIMATION_PAUSED:`engine:animationPaused`,ANIMATION_STOPPED:`engine:animationStopped`,ANIMATION_FINISHED:`engine:animationFinished`,VIDEO_RENDER_PROGRESS:`engine:videoRenderProgress`,VIDEO_RENDER_COMPLETE:`engine:videoRenderComplete`,DISPOSE:`engine:dispose`,DEVICE_LOST:`engine:deviceLost`,ISSUE:`engine:issue`,SCENE_METADATA_APPLIED:`engine:sceneMetadataApplied`}}));xe();var Se=null;function Ce(e){Se=e}var we=()=>Se?.({type:H.LOADING_RESET}),U=e=>{Se?.({type:H.LOADING_UPDATE,...e})},Te=e=>{Se?.({type:H.STATS_UPDATE,...e})};function Ee(e){return e.frameCount||0}function De(e){if(Array.isArray(e))e.forEach(e=>{e.userData&&e.userData.isFallback||(Oe(e),e.dispose())});else{if(e.userData&&e.userData.isFallback)return;Oe(e),e.dispose()}}function Oe(e){e&&[`alphaMap`,`aoMap`,`bumpMap`,`clearcoatMap`,`clearcoatNormalMap`,`clearcoatRoughnessMap`,`displacementMap`,`emissiveMap`,`envMap`,`gradientMap`,`lightMap`,`map`,`metalnessMap`,`normalMap`,`roughnessMap`,`specularMap`,`sheenColorMap`,`sheenRoughnessMap`,`specularIntensityMap`,`specularColorMap`,`thicknessMap`,`transmissionMap`].forEach(t=>{e[t]&&(e[t].dispose(),e[t]=null)})}function ke({material:e,geometry:t,children:n}){if(e&&De(e),t&&t.dispose(),n.length>0)for(let e of n)ke(e)}function Ae(e){if(!e)return;e._canvasTarget&&e._onCanvasTargetResize&&e._canvasTarget.removeEventListener(`resize`,e._onCanvasTargetResize);let t=e.dispose();return e._canvasTarget=null,t}function je(e,t=[]){if(e&&!(t.includes(e.name)||e.isScene)){if(e.isMaterial){De(e);return}for(;e.children.length>0;)for(let t of e.children)je(t);ke(e),e.removeFromParent(),e.clear()}}function Me(e){e?.traverse(e=>{e.geometry?.userData?.__rayzeeOwned&&e.geometry.dispose()})}function Ne(e,t){return t}function Pe(e,t=!1){return t?1:1/(e+1)}function Fe(){let e=0,t=0,n=0,r=0;return{start(){e=performance.now()},end(){t=performance.now();let i=t-e;return r+=i,n++,i},getAverageFrameTime(){return n>0?r/n:0},getFPS(){let e=this.getAverageFrameTime();return e>0?1e3/e:0},reset(){n=0,r=0}}}var Ie=Object.freeze({viewer:Object.freeze({areaLightIntensityScale:.1,environmentRotation:0,toneMapping:6,saturation:1}),physical:Object.freeze({areaLightIntensityScale:1,environmentRotation:0,toneMapping:6,saturation:1})});function Le(e=`viewer`){let t=Ie[e];if(!t)throw Error(`unknown render profile "${e}" — expected one of ${Object.keys(Ie).join(`, `)}`);return t}var W={resolution:512,canvasWidth:512,canvasHeight:512,maxTextureSize:4096,toneMapping:Ie.viewer.toneMapping,exposure:1,saturation:Ie.viewer.saturation,enableEnvironment:!0,showBackground:!0,transparentBackground:!1,environmentIntensity:1,backgroundIntensity:1,backgroundColor:`#000000`,backgroundBlurriness:0,backgroundBlurSamples:8,environmentRotation:Ie.viewer.environmentRotation,groundProjectionEnabled:!1,groundProjectionRadius:100,groundProjectionHeight:15,groundProjectionLevel:0,enableGroundCatcher:!1,groundCatcherHeight:0,globalIlluminationIntensity:1,environmentMode:`hdri`,gradientZenithColor:`#0077BE`,gradientHorizonColor:`#87CEEB`,gradientGroundColor:`#654321`,solidSkyColor:`#87CEEB`,skySunAzimuth:90,skySunElevation:20,skySunIntensity:15,skyRayleighDensity:.9,skyTurbidity:.8,skyMieAnisotropy:.76,skyPreset:`clearMorning`,cameraProjection:`perspective`,panoramaLonRange:[-180,180],panoramaLatRange:[-90,90],panoramaLevelHorizon:!0,enableDOF:!1,fov:55,focusDistance:.8,aperture:5.6,focalLength:50,apertureScale:1,anamorphicRatio:1,autoFocusMode:`auto`,afScreenPoint:{x:.5,y:.5},afSmoothingFactor:.15,enablePathTracer:!0,enableAccumulation:!0,pauseRendering:!1,maxSamples:60,bounces:3,transmissiveBounces:5,maxSubsurfaceSteps:8,maxTransparentBounces:32,useAdaptiveSampling:!0,noiseThreshold:.1,adaptiveMinSamples:8,adaptiveStopFraction:.9,usePixelFreeze:!0,pixelFreezeThreshold:.02,pixelFreezeStability:8,convergenceOverlay:!1,samplingTechnique:2,enableEmissiveTriangleSampling:!1,emissiveBoost:1,fireflyThreshold:3,shadowTerminatorOffset:.1,wavefrontSortMaterials:!0,renderLimitMode:`frames`,renderTimeLimit:30,renderMode:0,enableAlphaShadows:!1,tilesHelper:!0,showLightHelper:!1,directionalLightIntensity:0,directionalLightColor:`#ffffff`,directionalLightPosition:[1,1,1],directionalLightAngle:0,filterStrength:1,edgeAtrousIterations:5,edgePhiLuminance:4,edgePhiNormal:64,edgePhiDepth:.1,enableOIDN:!1,oidnQuality:`fast`,continuousDenoise:!1,continuousDenoiseInterval:8,enableUpscaler:!1,upscalerScale:2,upscalerQuality:`fast`,upscalerHdr:!0,debugMode:0,debugThreshold:100,debugModel:0,enableBloom:!1,bloomStrength:.2,bloomRadius:.15,bloomThreshold:.85,interactionModeEnabled:!0,interactionRenderScale:.5,debugVisScale:100,denoiserStrategy:`none`,enableASVGF:!1,asvgfTemporalAlpha:.1,asvgfAtrousIterations:8,asvgfPhiColor:10,asvgfPhiNormal:128,asvgfPhiDepth:1,asvgfVarianceBoost:1,asvgfMaxAccumFrames:32,asvgfGradientStrength:1,asvgfGradientSigmaScale:2,asvgfGradientNoiseFloor:0,asvgfDebugMode:0,asvgfQualityPreset:`medium`,showAsvgfHeatmap:!1,nrdQualityPreset:`medium`,nrdDebugMode:0,autoExposure:!1,autoExposureKeyValue:.18,autoExposureMinExposure:.1,autoExposureMaxExposure:20,autoExposureAdaptSpeedBright:3,autoExposureAdaptSpeedDark:.5},Re=6e4,ze=3,Be=.1,Ve=.01,He=4096,G=2048;function Ue(e){return G=Math.max(256,Math.min(He,Math.floor(e)||256)),G}var We={low:{temporalAlpha:.1,gradientStrength:.8,gradientSigmaScale:2.5,gradientNoiseFloor:.05,atrousIterations:3,phiColor:1,phiNormal:64,phiDepth:.1,phiLuminance:6,maxAccumFrames:16,varianceBoost:.5},medium:{temporalAlpha:.03,gradientStrength:1,gradientSigmaScale:2.5,gradientNoiseFloor:.05,atrousIterations:4,phiColor:.5,phiNormal:128,phiDepth:.05,phiLuminance:4,maxAccumFrames:64,varianceBoost:1},high:{temporalAlpha:0,gradientStrength:1,gradientSigmaScale:2.5,gradientNoiseFloor:.05,atrousIterations:6,phiColor:.3,phiNormal:256,phiDepth:.02,phiLuminance:2,maxAccumFrames:128,varianceBoost:1.5}},Ge={maxAccumulatedFrameNum:30,maxFastAccumulatedFrameNum:6,maxStabilizedFrameNum:63,historyFixFrameNum:3,historyFixBasePixelStride:14,prepassBlurRadius:30,minBlurRadius:1,maxBlurRadius:30,lobeAngleFraction:.15,roughnessFraction:.15,planeDistanceSensitivity:.02,minHitDistanceWeight:.1,fastHistoryClampingSigmaScale:2,fireflySuppressorMinRelativeScale:2,enableAntiFirefly:!0,antilagLuminanceSigmaScale:2,antilagLuminanceSensitivity:3,disocclusionThreshold:.01,convergenceS:1,convergenceB:.2,convergenceP:.8,lobeVolumePercent:.1,handoverFrames:0},Ke=[`maxAccumulatedFrameNum`,`maxFastAccumulatedFrameNum`,`maxStabilizedFrameNum`,`historyFixFrameNum`,`prepassBlurRadius`,`maxBlurRadius`,`enableAntiFirefly`],qe={low:{maxAccumulatedFrameNum:16,maxFastAccumulatedFrameNum:4,maxStabilizedFrameNum:16,historyFixFrameNum:2,prepassBlurRadius:0,maxBlurRadius:20,enableAntiFirefly:!1},medium:{},high:{maxAccumulatedFrameNum:45,maxFastAccumulatedFrameNum:8,historyFixFrameNum:4,prepassBlurRadius:40,maxBlurRadius:40}},Je={fov:{min:10,max:90,default:W.fov},focusDistance:{min:.3,max:100,default:W.focusDistance},aperture:{options:[1.4,2,2.8,4,5.6,8,11,16],default:W.aperture},focalLength:{min:0,max:200,default:W.focalLength}},Ye={clearMorning:{name:`Clear Morning`,sunAzimuth:90,sunElevation:20,sunIntensity:15,rayleighDensity:.9,turbidity:.8},clearNoon:{name:`Clear Noon`,sunAzimuth:0,sunElevation:75,sunIntensity:20,rayleighDensity:1,turbidity:.3},overcast:{name:`Overcast`,sunAzimuth:0,sunElevation:45,sunIntensity:6,rayleighDensity:.6,turbidity:4},goldenHour:{name:`Golden Hour`,sunAzimuth:270,sunElevation:10,sunIntensity:19,rayleighDensity:.8,turbidity:1.2},sunset:{name:`Sunset`,sunAzimuth:270,sunElevation:2,sunIntensity:18,rayleighDensity:.7,turbidity:2},dusk:{name:`Dusk`,sunAzimuth:270,sunElevation:-8,sunIntensity:8,rayleighDensity:.5,turbidity:1.5}},Xe={portrait:{name:`Portrait`,description:`Shallow depth of field, background blur`,fov:45,focusDistance:1.5,aperture:1.4,focalLength:135,apertureScale:1.5},landscape:{name:`Landscape`,description:`Maximum depth of field, everything in focus`,fov:65,focusDistance:10,aperture:16,focalLength:24,apertureScale:.5},macro:{name:`Macro`,description:`Extreme close-up with thin focus plane`,fov:40,focusDistance:.3,aperture:2,focalLength:100,apertureScale:2},product:{name:`Product`,description:`Sharp detail with subtle background separation`,fov:50,focusDistance:.8,aperture:2.8,focalLength:85,apertureScale:1},architectural:{name:`Architectural`,description:`Wide view with deep focus`,fov:75,focusDistance:5,aperture:11,focalLength:16,apertureScale:.5},cinematic:{name:`Cinematic`,description:`Dramatic depth separation with anamorphic bokeh`,fov:35,focusDistance:3,aperture:1.4,focalLength:200,apertureScale:1.8,anamorphicRatio:1.5}},Ze={MANUAL:`manual`,AUTO:`auto`},Qe={SMOOTHING_FACTOR:.15,RESET_THRESHOLD:.05,FALLBACK_DISTANCE:10,SNAP_THRESHOLD:.5},$e={FLOATS_PER_TRIANGLE:20,POSITION_A_OFFSET:0,POSITION_B_OFFSET:4,POSITION_C_OFFSET:8,NORMAL_A_PACKED_OFFSET:3,NORMAL_B_PACKED_OFFSET:7,NORMAL_C_PACKED_OFFSET:11,UV_AB_OFFSET:12,UV_C_OFFSET:16,MATERIAL_FLAGS_OFFSET:18,MESH_INDEX_OFFSET:19},et=16777215;function tt(e){return!e||!((e.transmission||0)===0&&(!(e.transparent|0)||(e.opacity??1)>=1))?0:e.alphaMode|0?2:1}function K(e,t){return(e&et|(t?.side??0)<<24|tt(t)<<26)>>>0}function nt(e,t,n){let r=Math.sqrt(e*e+t*t+n*n);r>0?(e/=r,t/=r,n/=r):(e=0,t=0,n=1);let i=Math.abs(e)+Math.abs(t)+Math.abs(n),a=e/i,o=t/i;if(n<0){let e=a,t=o;a=(1-Math.abs(t))*(e>=0?1:-1),o=(1-Math.abs(e))*(t>=0?1:-1)}let s=Math.round(Math.min(1,Math.max(-1,a))*32767)&65535;return((Math.round(Math.min(1,Math.max(-1,o))*32767)&65535)<<16|s)>>>0}var q={SLOTS_PER_MATERIAL:33,FLOATS_PER_MATERIAL:132,IOR:0,TRANSMISSION:1,THICKNESS:2,EMISSIVE_INTENSITY:3,ATTENUATION_COLOR:4,ATTENUATION_DISTANCE:7,OPACITY:8,SIDE:9,TRANSPARENT:10,ALPHA_TEST:11,ALPHA_MODE:12,DEPTH_WRITE:13,NORMAL_SCALE:14,COLOR:16,METALNESS:19,EMISSIVE:20,ROUGHNESS:23,ALBEDO_MAP_INDEX:24,NORMAL_MAP_INDEX:25,ROUGHNESS_MAP_INDEX:26,METALNESS_MAP_INDEX:27,EMISSIVE_MAP_INDEX:28,BUMP_MAP_INDEX:29,CLEARCOAT:30,CLEARCOAT_ROUGHNESS:31,DISPERSION:32,VISIBLE:33,SHEEN:34,SHEEN_ROUGHNESS:35,SHEEN_COLOR:36,SPECULAR_INTENSITY:40,SPECULAR_COLOR:41,IRIDESCENCE:44,IRIDESCENCE_IOR:45,IRIDESCENCE_THICKNESS_RANGE:46,BUMP_SCALE:48,DISPLACEMENT_SCALE:49,DISPLACEMENT_MAP_INDEX:50,ALBEDO_TRANSFORM:52,NORMAL_TRANSFORM:60,ROUGHNESS_TRANSFORM:68,METALNESS_TRANSFORM:76,EMISSIVE_TRANSFORM:84,BUMP_TRANSFORM:92,DISPLACEMENT_TRANSFORM:100,SUBSURFACE_COLOR:108,SUBSURFACE:111,SUBSURFACE_RADIUS:112,SUBSURFACE_RADIUS_SCALE:115,SUBSURFACE_ANISOTROPY:116,ANISOTROPY:117,ANISOTROPY_ROTATION:118,ANISOTROPY_MAP_INDEX:119,TRANSMISSION_MAP_INDEX:120,CLEARCOAT_MAP_INDEX:121,CLEARCOAT_ROUGHNESS_MAP_INDEX:122,SHEEN_COLOR_MAP_INDEX:123,SHEEN_ROUGHNESS_MAP_INDEX:124,IRIDESCENCE_MAP_INDEX:125,IRIDESCENCE_THICKNESS_MAP_INDEX:126,SPECULAR_INTENSITY_MAP_INDEX:127,SPECULAR_COLOR_MAP_INDEX:128,SLOT:{IOR_TRANSMISSION:0,ATTENUATION:1,OPACITY_ALPHA:2,ALPHA_MODE:3,COLOR_METALNESS:4,EMISSIVE_ROUGHNESS:5,MAP_INDICES_A:6,MAP_INDICES_B:7,DISPERSION_SHEEN:8,SHEEN_COLOR:9,SPECULAR:10,IRIDESCENCE:11,BUMP_DISPLACEMENT:12,ALBEDO_TRANSFORM_A:13,ALBEDO_TRANSFORM_B:14,NORMAL_TRANSFORM_A:15,NORMAL_TRANSFORM_B:16,ROUGHNESS_TRANSFORM_A:17,ROUGHNESS_TRANSFORM_B:18,METALNESS_TRANSFORM_A:19,METALNESS_TRANSFORM_B:20,EMISSIVE_TRANSFORM_A:21,EMISSIVE_TRANSFORM_B:22,BUMP_TRANSFORM_A:23,BUMP_TRANSFORM_B:24,DISPLACEMENT_TRANSFORM_A:25,DISPLACEMENT_TRANSFORM_B:26,SUBSURFACE_A:27,SUBSURFACE_B:28,SUBSURFACE_C:29,EXT_MAP_INDICES_A:30,EXT_MAP_INDICES_B:31,EXT_MAP_INDICES_C:32}},rt=e=>Number.isFinite(e)&&e>0?e:0,J=it({color:[1,1,1],emissive:[0,0,0],emissiveIntensity:1,roughness:1,metalness:0,ior:1.5,opacity:1,transmission:0,thickness:0,attenuationColor:[1,1,1],attenuationDistance:1/0,dispersion:0,sheen:0,sheenRoughness:1,sheenColor:[0,0,0],specularIntensity:1,specularColor:[1,1,1],clearcoat:0,clearcoatRoughness:0,iridescence:0,iridescenceIOR:1.3,iridescenceThicknessRange:[100,400],normalScale:[1,1],bumpScale:1,displacementScale:1,transparent:0,alphaTest:0,alphaMode:0,side:0,depthWrite:1,subsurface:0,subsurfaceColor:[1,1,1],subsurfaceRadius:[1,.2,.1],subsurfaceRadiusScale:1,subsurfaceAnisotropy:0,anisotropy:0,anisotropyRotation:0});function it(e){for(let t of Object.values(e))typeof t==`object`&&Object.freeze(t);return Object.freeze(e)}var at=1073741824,ot=1073741824,st=1073741823,ct={TRIANGLE_LEAF:1073741824,BLAS_POINTER_LEAF:1073741825,FRONTIER:1073741826};function lt(e){return new Uint32Array(e.buffer,e.byteOffset,e.length)}function ut(e,t){if(e>=1073741824)throw RangeError(`${t} is ${e.toLocaleString()}, at or past the BVH index limit of ${at.toLocaleString()}. Node indices are stored as u32 bit patterns and the leaf tags occupy everything above that.`);return e}var dt={PIXELS_PER_MATERIAL:30,RGBA_COMPONENTS:4,VEC4_PER_TRIANGLE:8,VEC4_PER_BVH_NODE:4,FLOATS_PER_VEC4:4,MIN_TEXTURE_WIDTH:4,MAX_CONCURRENT_WORKERS:Math.min(typeof navigator<`u`&&navigator.hardwareConcurrency||4,6),BUFFER_POOL_SIZE:20,CANVAS_POOL_SIZE:12,CACHE_SIZE_LIMIT:50,MAX_TEXTURE_SIZE:8192,DEFAULT_MAX_TEXTURE_SIZE:4096,MAX_TEXTURES_LIMIT:4*256,MATERIAL_BUCKET_COUNT:4,BUCKET_LAYER_STRIDE:256},ft=64;function pt(e,t){let n=Math.ceil(Math.max(1,e)/ft)*ft;return Math.min(t,Math.max(dt.MIN_TEXTURE_WIDTH,n))}function mt(e){let t=0,n=0,r=0;for(let i of e)t=Math.max(t,i.width),n=Math.max(n,i.height),r+=i.count;return{units:e,width:t,height:n,count:r}}function ht(e,t){return pt(e.width,t)*e.height*e.count*4}function gt(e,t){return e.reduce((e,n)=>e+ht(n,t),0)}function _t(e,t,n){let r=e.slice();for(;r.length>t;){let e=null;for(let t=0;t<r.length;t++)for(let i=t+1;i<r.length;i++){let a=mt(r[t].units.concat(r[i].units)),o=ht(a,n)-ht(r[t],n)-ht(r[i],n);(!e||o<e.delta)&&(e={i:t,j:i,delta:o,fused:a})}r=r.filter((t,n)=>n!==e.i&&n!==e.j).concat([e.fused])}return r}function vt(e,t,n){let r=[];for(let e=t-1;e>=0;e--)r.push(Math.max(dt.MIN_TEXTURE_WIDTH,Math.round(n/2**e)));let i=r.map(()=>[]);for(let t of e){let e=2**Math.ceil(Math.log2(Math.max(t.width,t.height))),n=r.findIndex(t=>e<=t);n<0&&(n=r.length-1),i[n].push(t)}return i.filter(e=>e.length).map(mt)}function yt(e,t){let n=e;for(let e=0;e<8;e++){let e=!1;for(let r of n.flatMap(e=>e.units)){let i=n.findIndex(e=>e.units.includes(r));if(!(i<0))for(let a=0;a<n.length;a++){if(a===i)continue;let o=[];for(let e=0;e<n.length;e++)if(e===i){let t=n[e].units.filter(e=>e!==r);t.length&&o.push(mt(t))}else e===a?o.push(mt(n[e].units.concat([r]))):o.push(n[e]);if(gt(o,t)<gt(n,t)){n=o,e=!0;break}}}if(!e)break}return n}function bt(e,t,n=dt.MATERIAL_BUCKET_COUNT){let r=new Map;for(let{width:n,height:i}of e){let e=Math.min(t,Math.max(1,n||1)),a=Math.min(t,Math.max(1,i||1)),o=`${e}x${a}`,s=r.get(o);s?s.count++:r.set(o,{width:e,height:a,count:1})}let i=[...r.values()],a=i.map(e=>mt([e]));if(a.length>n){let e=vt(i,n,t),r=_t(a,n,t);a=gt(e,t)<gt(r,t)?e:r,a=yt(a,t)}return a.map(e=>({width:pt(e.width,t),height:e.height})).sort((e,t)=>e.width*e.height-t.width*t.height)}function xt(e,t,n){let r=Math.max(1,e||1),i=Math.max(1,t||1);for(let e=0;e<n.length;e++)if(n[e].width>=r&&n[e].height>=i)return e;return Math.max(0,n.length-1)}function St(e,t){return e*dt.BUCKET_LAYER_STRIDE+t}var Ct=[0,0,1,1,0,0,0,1],wt={maxSamples:30,bounces:20,transmissiveBounces:24,maxSubsurfaceSteps:64,renderMode:1,enableAlphaShadows:!0,enableOIDN:!0,oidnQuality:`high`,interactionModeEnabled:!1,useAdaptiveSampling:!0,noiseThreshold:.02,adaptiveStopFraction:.94,usePixelFreeze:!0},Tt={maxSamples:W.maxSamples,bounces:W.bounces,renderMode:W.renderMode,enableAlphaShadows:W.enableAlphaShadows,transmissiveBounces:12,maxSubsurfaceSteps:W.maxSubsurfaceSteps,enableOIDN:!0,oidnQuality:`fast`,interactionModeEnabled:!0,useAdaptiveSampling:!0,noiseThreshold:.1,usePixelFreeze:!0};function Et(e){return{maxSamples:e.maxSamples,maxBounces:e.bounces,transmissiveBounces:e.transmissiveBounces,maxSubsurfaceSteps:e.maxSubsurfaceSteps,enableAlphaShadows:e.enableAlphaShadows??!1,useAdaptiveSampling:e.useAdaptiveSampling??!1,noiseThreshold:e.noiseThreshold??W.noiseThreshold,adaptiveStopFraction:e.adaptiveStopFraction??W.adaptiveStopFraction,adaptiveMinSamples:e.adaptiveMinSamples??W.adaptiveMinSamples,usePixelFreeze:e.usePixelFreeze??!1,pixelFreezeThreshold:e.pixelFreezeThreshold??W.pixelFreezeThreshold,pixelFreezeStability:e.pixelFreezeStability??W.pixelFreezeStability,interactionModeEnabled:e.interactionModeEnabled??W.interactionModeEnabled}}var Dt={MAX_BUFFER_MEMORY:1024*1024*1024,MAX_TEXTURE_MEMORY:2048*1024*1024,CLEANUP_THRESHOLD:.8,CHUNK_SIZE_THRESHOLD:64*1024*1024,STREAM_BATCH_SIZE:4};function Ot(e){try{return globalThis.localStorage?.getItem(e)??null}catch{return null}}function kt(e,t){try{t===null?globalThis.localStorage?.removeItem(e):globalThis.localStorage?.setItem(e,t)}catch{}}function At(){if(Ut!==null)return Ut;let e=globalThis.__RAYZEE_LOG_LEVEL__;return e!==void 0&&e in Lt?(Ut=Lt[e],Ut):(Ut=Lt[Ot(zt)]??Lt[Rt],Ut)}function jt(){if(Wt!==null)return Wt;let e=globalThis.__RAYZEE_LOG_NS__??Ot(Bt);return Wt=e?String(e).split(`,`).map(e=>e.trim()).filter(Boolean):[],Wt}function Mt(e,t){if(t<Lt.debug)return!0;let n=jt();return n.length===0||n.some(t=>e===t||e.startsWith(`${t}:`))}function Nt(e,t,n){if(e>At()||!Mt(t,e))return;let r=e===Lt.error?console.error:e===Lt.warn?console.warn:console.log,i=`[${t}]`;typeof n[0]==`string`?r(`%c${i}%c ${n[0]}`,Vt,Ht,...n.slice(1)):r(`%c${i}`,Vt,...n)}function Pt(e){return{namespace:e,error:(...t)=>Nt(Lt.error,e,t),warn:(...t)=>Nt(Lt.warn,e,t),info:(...t)=>Nt(Lt.info,e,t),debug:(...t)=>Nt(Lt.debug,e,t),isEnabled:e=>Gt.isEnabled(e),summary(t,n=[]){let r=n.filter(Boolean);if(r.length===0||!console.groupCollapsed){Nt(Lt.info,e,[t]),r.forEach(t=>Nt(Lt.debug,e,[t]));return}Lt.info>At()||((At()>=Lt.debug&&console.group?console.group:console.groupCollapsed)(`%c[${e}]%c ${t}`,Vt,Ht),r.forEach(e=>console.log(e)),console.groupEnd())}}}function Ft(e,t,...n){Kt.has(t)||(Kt.add(t),e.warn(...n))}function It(){return Gt.getLevel()}var Lt,Rt,zt,Bt,Vt,Ht,Ut,Wt,Y,Gt,Kt,qt=y((()=>{Lt={silent:0,error:1,warn:2,info:3,debug:4},Rt=`info`,zt=`rayzeeLogLevel`,Bt=`rayzeeLogNamespaces`,Vt=`color:#7c8494`,Ht=`color:inherit`,Ut=null,Wt=null,Y={n:e=>Number(e).toLocaleString(`en-US`),ms:e=>e<10?`${Number(e).toFixed(1)} ms`:`${Math.round(e)} ms`,mb:e=>{let t=e/(1024*1024);return t<10?`${t.toFixed(1)} MB`:`${Math.round(t)} MB`},px:(e,t)=>`${e}×${t}`,count:(e,t,n=`${t}s`)=>`${Y.n(e)} ${Number(e)===1?t:n}`,list:e=>e.filter(Boolean).join(` · `)},Gt={levels:Lt,setLevel(e){return e in Lt?(globalThis.__RAYZEE_LOG_LEVEL__=e,Ut=Lt[e],kt(zt,e===Rt?null:e),e):(console.warn(`[log] unknown level '${e}' — expected one of ${Object.keys(Lt).join(`, `)}`),this.getLevel())},getLevel(){let e=At();return Object.keys(Lt).find(t=>Lt[t]===e)},isEnabled(e){return(Lt[e]??Lt.debug)<=At()},only(...e){let t=e.flat().filter(Boolean);return Wt=t,globalThis.__RAYZEE_LOG_NS__=t.join(`,`),kt(Bt,t.length?t.join(`,`):null),t.length&&this.setLevel(`debug`),t},refresh(){return Ut=null,Wt=null,this.getLevel()}},Kt=new Set}));qt();var Jt=Pt(`gpu`);function Yt(e=r.FloatType,n=r.LinearFilter){let i=new t.StorageTexture(G,G);return i.type=e,i.format=r.RGBAFormat,i.minFilter=n,i.magFilter=n,i}var Xt=()=>Yt(),Zt=class{constructor(e,t){this.writeColor=null,this.writeNormalDepth=null,this.writeAlbedo=null,this.readTarget=null,this.currentTarget=0,this.renderWidth=0,this.renderHeight=0,this._srcRegion=new r.Box2(new r.Vector2(0,0),new r.Vector2(0,0)),e>0&&t>0&&this.create(e,t)}create(e,n){this.dispose(),this.renderWidth=e,this.renderHeight=n,this.writeColor=Xt(),this.writeNormalDepth=Xt(),this.writeAlbedo=Xt(),this.readTarget=new t.RenderTarget(e,n,{type:r.FloatType,format:r.RGBAFormat,minFilter:r.NearestFilter,magFilter:r.NearestFilter,depthBuffer:!1,stencilBuffer:!1,count:3}),this.readTarget.textures[0].name=`gColor`,this.readTarget.textures[1].name=`gNormalDepth`,this.readTarget.textures[2].name=`gAlbedo`,Jt.debug(`storage texture pool ${Y.px(e,n)} — 3 write StorageTextures + 1 MRT RenderTarget`)}ensureSize(e,t){return this.writeColor?this.renderWidth!==e||this.renderHeight!==t?(this.setSize(e,t),!0):!1:(this.create(e,t),!0)}getReadTextures(){return{color:this.readTarget.textures[0],normalDepth:this.readTarget.textures[1],albedo:this.readTarget.textures[2]}}getWriteTextures(){return{color:this.writeColor,normalDepth:this.writeNormalDepth,albedo:this.writeAlbedo}}copyToReadTargets(e,t=!0){this._srcRegion.max.set(this.renderWidth,this.renderHeight),e.copyTextureToTexture(this.writeColor,this.readTarget.textures[0],this._srcRegion),t&&(e.copyTextureToTexture(this.writeNormalDepth,this.readTarget.textures[1],this._srcRegion),e.copyTextureToTexture(this.writeAlbedo,this.readTarget.textures[2],this._srcRegion))}clear(e){if(!this.readTarget||!e)return;let t=e.getRenderTarget();e.setRenderTarget(this.readTarget),e.clear(!0,!1,!1),e.setRenderTarget(t)}swap(){this.currentTarget=1-this.currentTarget}setSize(e,t){if(this.renderWidth=e,this.renderHeight=t,this.readTarget){this.readTarget.setSize(e,t);for(let e of this.readTarget.textures)e.needsUpdate=!0}}dispose(){this.writeColor?.dispose(),this.writeNormalDepth?.dispose(),this.writeAlbedo?.dispose(),this.readTarget?.dispose(),this.writeColor=null,this.writeNormalDepth=null,this.writeAlbedo=null,this.readTarget=null}},Qt={cameraViewMatrix:`ptCameraViewMatrix`,cameraProjectionMatrix:`ptCameraProjectionMatrix`},$t=class{constructor(e=1920,t=1080){this._uniforms=new Map,this._booleans=new Set,this._arrayWarned=new Set,this._lightBuffers={},this._initUniforms(e,t),this._nameAll()}get(e){return this._uniforms.get(e)}set(e,t){let n=this._uniforms.get(e);if(!n){console.warn(`UniformManager: Unknown uniform "${e}"`);return}Array.isArray(t)&&t.length===1&&(this._booleans.has(e)||typeof n.value==`number`)&&(this._arrayWarned.has(e)||(this._arrayWarned.add(e),console.warn(`UniformManager: "${e}" was set to [${t[0]}] but expects a scalar — unwrapping. Fix the caller; a slider handler is probably forwarding its array value unchanged.`)),t=t[0]),this._booleans.has(e)?n.value=+!!t:typeof t==`object`&&t&&typeof n.value?.copy==`function`?n.value.copy(t):n.value=t}has(e){return this._uniforms.has(e)}keys(){return this._uniforms.keys()}getLightBufferNodes(){return this._lightBuffers}updateMany(e){let t=!1;for(let[n,r]of Object.entries(e)){let e=this._uniforms.get(n);e&&e.value!==r&&(e.value=r,t=!0)}return t}_initUniforms(e,t){let i=(e,t,r)=>{let i=(0,n.uniform)(t,r);return this._uniforms.set(e,i),i},a=(e,t)=>(this._booleans.add(e),i(e,+!!t,`int`));i(`frame`,0,`uint`),i(`seedFrame`,0,`uint`),i(`maxBounces`,W.bounces,`int`),i(`maxSamples`,W.maxSamples,`int`),i(`transmissiveBounces`,W.transmissiveBounces,`int`),i(`maxSubsurfaceSteps`,W.maxSubsurfaceSteps,`int`),i(`maxTransparentBounces`,W.maxTransparentBounces,`int`),i(`visMode`,W.debugMode,`int`),i(`debugVisScale`,W.debugVisScale,`float`),a(`useAdaptiveSampling`,W.useAdaptiveSampling),i(`noiseThreshold`,W.noiseThreshold,`float`),i(`adaptiveMinSamples`,W.adaptiveMinSamples,`int`),i(`adaptiveStopFraction`,W.adaptiveStopFraction,`float`),a(`usePixelFreeze`,W.usePixelFreeze),i(`pixelFreezeThreshold`,W.pixelFreezeThreshold,`float`),i(`pixelFreezeStability`,W.pixelFreezeStability,`int`),a(`convergenceOverlay`,W.convergenceOverlay),a(`enableAccumulation`,!0),i(`accumulationAlpha`,0,`float`),a(`cameraIsMoving`,!1),a(`hasPreviousAccumulated`,!1),i(`auxAccumulationAlpha`,1,`float`),a(`hasPreviousAux`,!1),i(`environmentIntensity`,W.environmentIntensity,`float`),i(`backgroundIntensity`,W.backgroundIntensity,`float`),i(`backgroundColor`,new r.Color(0,0,0),`color`),i(`backgroundBlurriness`,W.backgroundBlurriness,`float`),i(`backgroundBlurSamples`,W.backgroundBlurSamples,`int`),a(`showBackground`,W.showBackground),a(`transparentBackground`,W.transparentBackground),a(`enableEnvironment`,W.enableEnvironment),i(`environmentMatrix`,new r.Matrix4,`mat4`),i(`envTotalSum`,0,`float`),i(`envCompensationDelta`,0,`float`),i(`envResolution`,new r.Vector2(1,1),`vec2`),a(`groundProjectionEnabled`,W.groundProjectionEnabled),i(`groundProjectionRadius`,W.groundProjectionRadius,`float`),i(`groundProjectionHeight`,W.groundProjectionHeight,`float`),i(`groundProjectionLevel`,W.groundProjectionLevel,`float`),a(`enableGroundCatcher`,W.enableGroundCatcher),i(`groundCatcherHeight`,W.groundCatcherHeight,`float`),i(`sunDirection`,new r.Vector3(0,1,0),`vec3`),i(`sunAngularSize`,.0087,`float`),a(`hasSun`,!1),i(`globalIlluminationIntensity`,W.globalIlluminationIntensity,`float`),i(`exposure`,W.exposure,`float`),i(`numDirectionalLights`,0,`int`),i(`numAreaLights`,0,`int`),i(`numPointLights`,0,`int`),i(`numSpotLights`,0,`int`),this._lightBuffers={directional:(0,n.uniformArray)(new Float32Array(192),`float`),area:(0,n.uniformArray)(new Float32Array(256),`float`),point:(0,n.uniformArray)(new Float32Array(144),`float`),spot:(0,n.uniformArray)(new Float32Array(320),`float`)},i(`cameraWorldMatrix`,new r.Matrix4,`mat4`),i(`cameraProjectionMatrixInverse`,new r.Matrix4,`mat4`),i(`cameraViewMatrix`,new r.Matrix4,`mat4`),i(`cameraProjectionMatrix`,new r.Matrix4,`mat4`);let o=([e,t])=>new r.Vector2(e,t).multiplyScalar(r.MathUtils.DEG2RAD);i(`cameraProjection`,+(W.cameraProjection===`equirectangular`),`int`),i(`panoLonRange`,o(W.panoramaLonRange),`vec2`),i(`panoLatRange`,o(W.panoramaLatRange),`vec2`),a(`panoLevelHorizon`,W.panoramaLevelHorizon),a(`enableDOF`,W.enableDOF),i(`focusDistance`,W.focusDistance,`float`),i(`focalLength`,W.focalLength,`float`),i(`aperture`,W.aperture,`float`),i(`apertureScale`,1,`float`),i(`anamorphicRatio`,W.anamorphicRatio??1,`float`),i(`sceneScale`,1,`float`),this._uniforms.set(`samplingTechnique`,N),N.value=W.samplingTechnique,i(`fireflyThreshold`,W.fireflyThreshold,`float`),i(`shadowTerminatorOffset`,W.shadowTerminatorOffset,`float`),a(`enableEmissiveTriangleSampling`,W.enableEmissiveTriangleSampling),i(`emissiveBoost`,W.emissiveBoost,`float`),i(`emissiveTriangleCount`,0,`int`),i(`emissiveTotalPower`,0,`float`),i(`lightBVHNodeCount`,0,`int`),i(`emissiveVec4Offset`,0,`int`),i(`reverseMapVec4Offset`,0,`int`),i(`renderMode`,W.renderMode,`int`),a(`enableAlphaShadows`,W.enableAlphaShadows),i(`resolution`,new r.Vector2(e,t),`vec2`)}_nameAll(){for(let[e,t]of this._uniforms)t.name=Qt[e]||e}dispose(){this._disposed||(this._disposed=!0,this._uniforms.clear(),this._booleans.clear(),this._arrayWarned.clear(),this._lightBuffers={})}},en=[1,0,0,0,1,0,0,0],tn=[[`mapMatrix`,q.ALBEDO_TRANSFORM],[`normalMapMatrices`,q.NORMAL_TRANSFORM],[`roughnessMapMatrices`,q.ROUGHNESS_TRANSFORM],[`metalnessMapMatrices`,q.METALNESS_TRANSFORM],[`emissiveMapMatrices`,q.EMISSIVE_TRANSFORM],[`bumpMapMatrices`,q.BUMP_TRANSFORM],[`displacementMapMatrices`,q.DISPLACEMENT_TRANSFORM]];Object.freeze([q.VISIBLE,q.SHEEN_COLOR+3,q.DISPLACEMENT_MAP_INDEX+1,q.SPECULAR_COLOR_MAP_INDEX+1,q.SPECULAR_COLOR_MAP_INDEX+2,q.SPECULAR_COLOR_MAP_INDEX+3]);var nn=Object.freeze(new Set([`metalness`,`roughness`,`transmission`,`opacity`,`clearcoat`,`clearcoatRoughness`,`sheen`,`sheenRoughness`,`specularIntensity`,`iridescence`,`subsurface`,`anisotropy`])),rn=e=>Math.min(Math.max(e,0),1);function an(e,t){let n=typeof e==`boolean`?+e:e;return Number.isFinite(n)?n:t}function on(e){return Number.isInteger(e)?e:-1}function sn(e,t,n,r){let i=n?.r??n?.[0]??n?.x,a=n?.g??n?.[1]??n?.y,o=n?.b??n?.[2]??n?.z;e[t]=an(i,r[0]),e[t+1]=an(a,r[1]),e[t+2]=an(o,r[2])}function cn(e,t,n){let r=(n,r,i)=>{e[t+n]=an(r,i)},i=(n,r,i)=>{e[t+n]=rn(an(r,i))};r(q.IOR,n.ior,J.ior),i(q.TRANSMISSION,n.transmission,J.transmission),r(q.THICKNESS,n.thickness,J.thickness),r(q.EMISSIVE_INTENSITY,n.emissiveIntensity,J.emissiveIntensity),sn(e,t+q.ATTENUATION_COLOR,n.attenuationColor,J.attenuationColor),e[t+q.ATTENUATION_DISTANCE]=rt(n.attenuationDistance??J.attenuationDistance),i(q.OPACITY,n.opacity,J.opacity),r(q.SIDE,n.side,J.side),r(q.TRANSPARENT,n.transparent,J.transparent),r(q.ALPHA_TEST,n.alphaTest,J.alphaTest),r(q.ALPHA_MODE,n.alphaMode,J.alphaMode),r(q.DEPTH_WRITE,n.depthWrite,J.depthWrite);let a=n.normalScale,o=typeof a==`number`?a:void 0;r(q.NORMAL_SCALE,o??a?.x??a?.[0],J.normalScale[0]),r(q.NORMAL_SCALE+1,o??a?.y??a?.[1],J.normalScale[1]),sn(e,t+q.COLOR,n.color,J.color),i(q.METALNESS,n.metalness,J.metalness),sn(e,t+q.EMISSIVE,n.emissive,J.emissive),i(q.ROUGHNESS,n.roughness,J.roughness),e[t+q.ALBEDO_MAP_INDEX]=on(n.map),e[t+q.NORMAL_MAP_INDEX]=on(n.normalMap),e[t+q.ROUGHNESS_MAP_INDEX]=on(n.roughnessMap),e[t+q.METALNESS_MAP_INDEX]=on(n.metalnessMap),e[t+q.EMISSIVE_MAP_INDEX]=on(n.emissiveMap),e[t+q.BUMP_MAP_INDEX]=on(n.bumpMap),i(q.CLEARCOAT,n.clearcoat,J.clearcoat),i(q.CLEARCOAT_ROUGHNESS,n.clearcoatRoughness,J.clearcoatRoughness),r(q.DISPERSION,n.dispersion,J.dispersion),i(q.SHEEN,n.sheen,J.sheen),i(q.SHEEN_ROUGHNESS,n.sheenRoughness,J.sheenRoughness),sn(e,t+q.SHEEN_COLOR,n.sheenColor,J.sheenColor),i(q.SPECULAR_INTENSITY,n.specularIntensity,J.specularIntensity),sn(e,t+q.SPECULAR_COLOR,n.specularColor,J.specularColor),i(q.IRIDESCENCE,n.iridescence,J.iridescence),r(q.IRIDESCENCE_IOR,n.iridescenceIOR,J.iridescenceIOR),r(q.IRIDESCENCE_THICKNESS_RANGE,n.iridescenceThicknessRange?.[0],J.iridescenceThicknessRange[0]),r(q.IRIDESCENCE_THICKNESS_RANGE+1,n.iridescenceThicknessRange?.[1],J.iridescenceThicknessRange[1]),r(q.BUMP_SCALE,n.bumpScale,J.bumpScale),r(q.DISPLACEMENT_SCALE,n.displacementScale,J.displacementScale),e[t+q.DISPLACEMENT_MAP_INDEX]=on(n.displacementMap);for(let[r,i]of tn){let a=n[r];for(let n=0;n<8;n++)e[t+i+n]=an(a?.[n],en[n])}sn(e,t+q.SUBSURFACE_COLOR,n.subsurfaceColor,J.subsurfaceColor),i(q.SUBSURFACE,n.subsurface,J.subsurface),sn(e,t+q.SUBSURFACE_RADIUS,n.subsurfaceRadius,J.subsurfaceRadius),r(q.SUBSURFACE_RADIUS_SCALE,n.subsurfaceRadiusScale,J.subsurfaceRadiusScale),r(q.SUBSURFACE_ANISOTROPY,n.subsurfaceAnisotropy,J.subsurfaceAnisotropy),i(q.ANISOTROPY,n.anisotropy,J.anisotropy),r(q.ANISOTROPY_ROTATION,n.anisotropyRotation,J.anisotropyRotation),e[t+q.ANISOTROPY_MAP_INDEX]=on(n.anisotropyMap),e[t+q.TRANSMISSION_MAP_INDEX]=on(n.transmissionMap),e[t+q.CLEARCOAT_MAP_INDEX]=on(n.clearcoatMap),e[t+q.CLEARCOAT_ROUGHNESS_MAP_INDEX]=on(n.clearcoatRoughnessMap),e[t+q.SHEEN_COLOR_MAP_INDEX]=on(n.sheenColorMap),e[t+q.SHEEN_ROUGHNESS_MAP_INDEX]=on(n.sheenRoughnessMap),e[t+q.IRIDESCENCE_MAP_INDEX]=on(n.iridescenceMap),e[t+q.IRIDESCENCE_THICKNESS_MAP_INDEX]=on(n.iridescenceThicknessMap),e[t+q.SPECULAR_INTENSITY_MAP_INDEX]=on(n.specularIntensityMap),e[t+q.SPECULAR_COLOR_MAP_INDEX]=on(n.specularColorMap),e[t+q.VISIBLE]=1,e[t+q.SHEEN_COLOR+3]=1,e[t+q.DISPLACEMENT_MAP_INDEX+1]=0,e[t+q.SPECULAR_COLOR_MAP_INDEX+1]=0,e[t+q.SPECULAR_COLOR_MAP_INDEX+2]=0,e[t+q.SPECULAR_COLOR_MAP_INDEX+3]=0}var ln=Object.freeze({ADAPTER_SOFTWARE:`adapter.software`,ASSET_UNREACHABLE:`asset.unreachable`,ASSET_AMBIGUOUS_ENTRY:`asset.ambiguous_entry`,ASSET_ARCHIVE_TOO_LARGE:`asset.archive_too_large`,ASSET_ENTRY_TOO_LARGE:`asset.entry_too_large`,TEXTURE_BUILD_FAILED:`texture.build_failed`,TEXTURE_PROCESSING_FALLBACK:`texture.processing_fallback`,TEXTURE_LIMIT_EXCEEDED:`texture.limit_exceeded`,ENVIRONMENT_LOAD_FAILED:`environment.load_failed`,SETTING_UNKNOWN_KEY:`setting.unknown_key`,RENDER_SIZE_DECLINED:`render.size_declined`,STAGE_RENDER_FAILED:`stage.render_failed`,RENDER_RESERVE_CAPPED:`render.reserve_capped`,SCENE_MEMORY_BUDGET:`scene.memory_budget`,EMISSIVE_INSTANCES_COLLAPSED:`emissive.instances_collapsed`,REFIT_SHARED_GEOMETRY:`refit.shared_geometry`,VIEW_TRANSFORM_DISPLAY_MISMATCH:`viewTransform.display_mismatch`,VIEW_TRANSFORM_BAKE_FAILED:`viewTransform.bake_failed`,COLOR_CONFIG_LOAD_FAILED:`color.config_load_failed`}),un=Object.freeze({ERROR:`error`,WARNING:`warning`}),dn=class extends Error{constructor(e){super(`[${e.code}] ${e.message}`),this.name=`EngineIssueError`,this.code=e.code,this.detail=e.detail}},fn=class{constructor({strict:e=!1,onIssue:t=null}={}){this.strict=e===!0,this._onIssue=t,this._entries=[]}record(e,t,n={},r=un.ERROR){let i=Object.freeze({code:e,message:t,detail:n,severity:r,at:Date.now()});if(this._entries.push(i),this._onIssue?.(i),this.strict&&r===un.ERROR)throw new dn(i);return i}warn(e,t,n){return this.record(e,t,n,un.WARNING)}get list(){return this._entries.slice()}get errors(){return this._entries.filter(e=>e.severity===un.ERROR)}clear(){this._entries.length=0}detach(){this._onIssue=null,this.strict=!1}},pn=64*1024*1024,mn=typeof SharedArrayBuffer<`u`,hn=null;function gn(e){hn=e}function _n(e,t,n){let r=n?new e(new SharedArrayBuffer(t*e.BYTES_PER_ELEMENT)):new e(t);return hn&&r.byteLength>0&&hn(r.byteLength,n),r}var vn=class e{constructor(e,t,n,r=pn,i=!1){let a=t*n.BYTES_PER_ELEMENT,o=Math.max(1,Math.floor(r/a));this.recordCount=e,this.lanesPerRecord=t,this.LaneType=n,this.recordsPerChunk=e<=o?Math.max(e,1):o,this.shared=i,this.chunks=[];let s=e;for(;s>0;){let e=Math.min(s,this.recordsPerChunk);this.chunks.push(_n(n,e*t,i)),s-=e}this.chunks.length===0&&this.chunks.push(_n(n,0,i))}static adopt(t,n,r,i){let a=Object.create(e.prototype);return a.recordCount=n,a.lanesPerRecord=r,a.LaneType=t[0]?.constructor??null,a.recordsPerChunk=i,a.chunks=t,a.shared=typeof SharedArrayBuffer<`u`&&t[0]?.buffer instanceof SharedArrayBuffer,a}static lazy(t,n,r,i=pn,a=!1){let o=Math.max(1,Math.floor(i/(n*r.BYTES_PER_ELEMENT))),s=Object.create(e.prototype);return s.recordCount=t,s.lanesPerRecord=n,s.LaneType=r,s.recordsPerChunk=t<=o?Math.max(t,1):o,s.shared=a,s.chunks=Array(Math.max(1,Math.ceil(t/s.recordsPerChunk))),s._views=[],s}_materialize(e){if(this._owner)return this._owner._materialize(e),this.chunks[e];let t=e*this.recordsPerChunk,n=Math.min(this.recordsPerChunk,this.recordCount-t)*this.lanesPerRecord,r=this.chunks[e]=_n(this.LaneType,n,this.shared);for(let t of this._views)t.chunks[e]=new t.LaneType(r.buffer,r.byteOffset,r.byteLength/t.LaneType.BYTES_PER_ELEMENT);return r}materializeAll(){for(let e=0;e<this.chunks.length;e++)this.chunks[e]||this._materialize(e);return this}get chunkCount(){return this.chunks.length}get single(){return this.chunks.length===1?this.chunks[0]:null}get byteLength(){let e=0;for(let t of this.chunks)t&&(e+=t.byteLength);return e}chunkFor(e){let t=e/this.recordsPerChunk|0;return this.chunks[t]??this._materialize(t)}baseOf(e){return e%this.recordsPerChunk*this.lanesPerRecord}isContiguous(e,t){return t<=0?!0:(e/this.recordsPerChunk|0)==((e+t-1)/this.recordsPerChunk|0)}slice(e,t){let n=this.baseOf(e),r=t*this.lanesPerRecord;if(this.isContiguous(e,t))return this.chunkFor(e).subarray(n,n+r);let i=new this.LaneType(r);return this.readRecords(e,t,i),i}readRecords(e,t,n){let r=0;for(;r<t;){let i=e+r,a=this.chunkFor(i),o=this.baseOf(i),s=this.recordsPerChunk-i%this.recordsPerChunk,c=Math.min(s,t-r);n.set(a.subarray(o,o+c*this.lanesPerRecord),r*this.lanesPerRecord),r+=c}return n}setRecords(e,t){let n=t.length/this.lanesPerRecord,r=0;for(;r<n;){let i=e+r,a=this.chunkFor(i),o=this.baseOf(i),s=this.recordsPerChunk-i%this.recordsPerChunk,c=Math.min(s,n-r);a.set(t.subarray(r*this.lanesPerRecord,(r+c)*this.lanesPerRecord),o),r+=c}}copyOf(e,t){return this.readRecords(e,t,new this.LaneType(t*this.lanesPerRecord))}trimTo(t){let n=Math.max(1,Math.ceil(t/this.recordsPerChunk)),r=this.chunks.slice(0,n),i=(t-(n-1)*this.recordsPerChunk)*this.lanesPerRecord,a=r[n-1];return a.length>i&&(r[n-1]=a.subarray(0,Math.max(0,i))),e.adopt(r,t,this.lanesPerRecord,this.recordsPerChunk)}viewAs(t){let n=e=>new t(e.buffer,e.byteOffset,e.byteLength/t.BYTES_PER_ELEMENT),r=e.adopt(this.chunks.map(e=>e?n(e):void 0),this.recordCount,this.lanesPerRecord,this.recordsPerChunk);return r.LaneType=t,this._views&&(r._owner=this,this._views.push(r)),r}};qt();var yn=Pt(`geometry`),bn=dt.MAX_TEXTURES_LIMIT,xn=new Set([`color`,`emissive`,`attenuationColor`,`sheenColor`,`specularColor`,`subsurfaceColor`]),Sn=Object.freeze({MATERIAL:`material`,MAPPED:`mapped`,DEFAULT:`default`,HOST:`host`}),Cn=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];function wn(e){for(let t=0;t<16;t++)if(e[t]!==Cn[t])return!1;return!0}function Tn(e){return{map:e.map,normalMap:e.normalMap,bumpMap:e.bumpMap,roughnessMap:e.roughnessMap,metalnessMap:e.metalnessMap,emissiveMap:e.emissiveMap??(e.isMeshBasicMaterial?e.map:void 0),displacementMap:e.displacementMap,anisotropyMap:e.anisotropyMap,clearcoatMap:e.clearcoatMap,clearcoatRoughnessMap:e.clearcoatRoughnessMap,transmissionMap:e.transmissionMap,sheenColorMap:e.sheenColorMap,sheenRoughnessMap:e.sheenRoughnessMap,specularIntensityMap:e.specularIntensityMap,specularColorMap:e.specularColorMap,iridescenceMap:e.iridescenceMap,iridescenceThicknessMap:e.iridescenceThicknessMap}}function En(e){if(e.userData?.gltfExtensions?.KHR_materials_unlit?.alphaMode){let t=e.userData.gltfExtensions.KHR_materials_unlit.alphaMode;return t===`BLEND`?2:+(t===`MASK`)}return e.alphaTest>0?1:e.transparent&&e.opacity<1||e.map&&e.map.format===r.RGBAFormat&&e.transparent?2:0}function Dn(e){let t=0,n=new Set,r=e=>{let i=e.isMesh&&e.material?e.geometry:null;if(i&&!n.has(i.uuid)){n.add(i.uuid);for(let e in i.attributes)t+=i.attributes[e].array?.byteLength??0;t+=i.index?.array?.byteLength??0}if(e.children)for(let t of e.children)r(t)};return r(e),t}function On(e,t){let n=e.x,r=e.y,i=e.z;e.x=t[0]*n+t[4]*r+t[8]*i+t[12],e.y=t[1]*n+t[5]*r+t[9]*i+t[13],e.z=t[2]*n+t[6]*r+t[10]*i+t[14]}function kn(e,t){let n=e.x,r=e.y,i=e.z;e.x=t[0]*n+t[3]*r+t[6]*i,e.y=t[1]*n+t[4]*r+t[7]*i,e.z=t[2]*n+t[5]*r+t[8]*i}var An=1<<21;function jn(e){return!!(e.isSkinnedMesh||Object.keys(e.geometry?.morphAttributes??{}).length)}function Mn(e){return e[0]*(e[5]*e[10]-e[9]*e[6])-e[4]*(e[1]*e[10]-e[9]*e[2])+e[8]*(e[1]*e[6]-e[5]*e[2])}var Nn=class{constructor({issues:e=null}={}){this._issues=e,this._droppedTextures=0,this._vectorPool={vec3:Array(9).fill().map(()=>new r.Vector3),vec2:[,,,,,,].fill().map(()=>new r.Vector2)},this._geometryRanges=new Map,this.expandedTriangleCount=0,this._allocatePlacements(0),this._matrixPool={mat3:new r.Matrix3,mat4:new r.Matrix4},this.resetArrays(),this.triangleCount=0,this.currentTriangleIndex=0}_getVec3(e=0){return this._vectorPool.vec3[e%this._vectorPool.vec3.length]}_getVec2(e=0){return this._vectorPool.vec2[e%this._vectorPool.vec2.length]}extract(e){this.resetArrays();let t=this._countTriangles(e);return this._triangleCapacity=Math.max(1024,t),this._allocateTriangles(this._triangleCapacity),this.currentTriangleIndex=0,this._allocatePlacements(this._countPlacements(e)),this._geometryUses=this._countGeometryUses(e),this.bakeInverse=new Map,this.traverseObject(e),this._shareInstanceMatrices(),this._compressAttributes(e),this.logStats(),this.getExtractedData()}surveyScene(e){let t=0,n=e=>{if(e.isMesh&&e.geometry&&e.material&&t++,e.children)for(let t of e.children)n(t)};return n(e),{triangles:this._countTriangles(e),placements:this._countPlacements(e),meshes:t,geometryBytes:Dn(e)}}_countGeometryUses(e){let t=new Map;return e.traverse(e=>{if(!e.isMesh||!e.geometry||!e.material)return;let n=`${e.geometry.uuid}|${e.material.uuid}`;t.set(n,(t.get(n)??0)+1)}),t}_countPlacements(e){let t=0;if(e.isMesh&&e.geometry&&e.material&&(t+=e.isInstancedMesh&&e.instanceMatrix?e.count??e.instanceMatrix.array.length/16:1),e.children)for(let n of e.children)t+=this._countPlacements(n);return t}_allocatePlacements(e){this.instanceCount=0,this.instanceCapacity=e,this.instanceSource=new Int32Array(e),this.instanceMatrices=new Float32Array(e*16),this._shareable=[],this._compressed=new Set}_compressAttributes(e){let t=this._compressed,n=(e,t)=>{if(!e.userData?.__rayzeeExternal){t(e);for(let r of e.children)n(r,t)}};n(e,e=>{let n=e.geometry;if(!(!e.isMesh||!n||t.has(n.uuid))){t.add(n.uuid);for(let e of[`normal`,`tangent`,`color`]){let t=n.getAttribute(e);if(!t||t.normalized||!(t.array instanceof Float32Array)||n.morphAttributes?.[e]?.length)continue;let i=t.array,a=!0;for(let e=0;e<i.length;e++){let t=i[e];if(!(t>=-1.0001&&t<=1.0001)){a=!1;break}}if(!a)continue;let o=new Int16Array(i.length);for(let e=0;e<i.length;e++)o[e]=Math.round(Math.max(-1,Math.min(1,i[e]))*32767);n.setAttribute(e,new r.BufferAttribute(o,t.itemSize,!0))}}})}_shareInstanceMatrices(){for(let{mesh:e,start:t,count:n}of this._shareable){let r=e.instanceMatrix;!r||r.array.length!==n*16||(r.array=this.instanceMatrices.subarray(t*16,(t+n)*16))}this._shareable=[]}_countTriangles(e){let t=0;if(e.isMesh&&e.geometry&&e.material){let n=e.geometry.index,r=e.geometry.attributes.position;n?t+=Math.ceil(n.count/3):r&&(t+=Math.ceil(r.count/3))}if(e.children)for(let n of e.children)t+=this._countTriangles(n);return t}_ensureCapacity(e){if(e<=this._triangleCapacity)return;let t=this.triangles,n=this.currentTriangleIndex;this._allocateTriangles(e);for(let e=0;e<n;e++)this.triangles.chunkFor(e).set(t.chunkFor(e).subarray(t.baseOf(e),t.baseOf(e)+t.lanesPerRecord),this.triangles.baseOf(e));this._triangleCapacity=e}_allocateTriangles(e){this.triangles=new vn(e,$e.FLOATS_PER_TRIANGLE,Uint32Array,void 0,mn),this.triangleFloatChunks=this.triangles.viewAs(Float32Array),this.triangleData=this.triangles.single,this.triangleFloats=this.triangleFloatChunks.single}traverseObject(e){if(e.isMesh?this.processMesh(e):e.isDirectionalLight?this.directionalLights.push(e):e.isCamera&&this.cameras.push(e),e.children)for(let t of e.children)this.traverseObject(t)}processMesh(e){if(!e.geometry||!e.material){console.warn(`Skipping mesh with missing geometry or material:`,e);return}let t=this.processMaterial(e.material);e.userData.materialIndex=t;let n=this.meshes.length;this.meshes.push(e),e.userData.meshIndex=n;let r=`${e.geometry.uuid}|${t}`,i=jn(e),a=!this._emissiveMaterial(t)&&!i,o=a?this._geometryRanges.get(r):null;if(o){let t={start:o.start,count:o.count,expandedStart:this.expandedTriangleCount,sharedFrom:o.meshIndex};this.expandedTriangleCount+=o.count,this.meshTriangleRanges.push(t),this._recordPlacements(e,n);return}let s=this.currentTriangleIndex,c=e.isInstancedMesh&&!i&&this._emissiveMaterial(t)&&this._canExpand(e),l=c||!e.isInstancedMesh&&!i&&(this._geometryUses.get(`${e.geometry.uuid}|${e.material?.uuid}`)===1||this._emissiveMaterial(t));this.extractGeometry(e,t,n,l,c);let u={start:s,count:this.currentTriangleIndex-s,expandedStart:this.expandedTriangleCount};this.expandedTriangleCount+=u.count,this.meshTriangleRanges.push(u),u.count>0&&!l&&a&&this._geometryRanges.set(r,{...u,meshIndex:n}),this._recordPlacements(e,n,l,c)}_recordPlacements(e,t,n=!1,r=!1){let i=e.matrixWorld.elements,a=this.instanceMatrices,o=this.instanceSource;if(!e.isInstancedMesh||!e.instanceMatrix||r){let r=this._nextPlacement();if(o[r]=t,n){for(let e=0;e<16;e++)a[r*16+e]=+(e%5==0);this.bakeInverse.set(t,Float32Array.from(this._matrixPool.mat4.copy(e.matrixWorld).invert().elements))}else for(let e=0;e<16;e++)a[r*16+e]=i[e];return}let s=e.instanceMatrix.array,c=e.count??s.length/16,l=wn(i);l&&s.length===c*16&&this._shareable.push({mesh:e,start:this.instanceCount,count:c});for(let e=0;e<c;e++){let n=e*16,r=this._nextPlacement(),c=r*16;if(o[r]=t,l){for(let e=0;e<16;e++)a[c+e]=s[n+e];continue}for(let e=0;e<4;e++)for(let t=0;t<4;t++)a[c+e*4+t]=i[t]*s[n+e*4]+i[4+t]*s[n+e*4+1]+i[8+t]*s[n+e*4+2]+i[12+t]*s[n+e*4+3]}}_nextPlacement(){if(this.instanceCount>=this.instanceCapacity){let e=Math.max(16,this.instanceCapacity*2),t=new Int32Array(e),n=new Float32Array(e*16);t.set(this.instanceSource),n.set(this.instanceMatrices),this.instanceSource=t,this.instanceMatrices=n,this.instanceCapacity=e}return this.instanceCount++}_canExpand(e){let t=e.geometry,n=(t.index?t.index.count:t.attributes.position.count)/3,r=e.count??(e.instanceMatrix?.array.length??0)/16;return n*r<=An?!0:(this._issues?.record(ln.EMISSIVE_INSTANCES_COLLAPSED,`"${e.name||`instanced mesh`}" would need ${Math.round(n*r).toLocaleString()} triangles to light every instance; lighting the first one only`,{instances:r,trianglesPerInstance:n,limit:An}),!1)}_emissiveMaterial(e){let t=this.materials[e];if(!t||!(t.emissiveIntensity>0))return!1;let n=t.emissive;return!!n&&(n.r>0||n.g>0||n.b>0)}processMaterial(e){let t=this._materialUuidMap.get(e.uuid)??-1;if(t===-1){e.depthWrite===!1&&(e.depthWrite=!0,Ft(yn,`depthWrite`,`material had depthWrite disabled — enabled for rastered rendering`));let n=this.createMaterialObject(e);this.materials.push(n),t=this.materials.length-1,this._materialUuidMap.set(e.uuid,t)}return t}getMaterialType(e){return e.isMeshPhysicalMaterial?`physical`:e.isMeshStandardMaterial?`standard`:e.isMeshPhongMaterial?`phong`:e.isMeshLambertMaterial?`lambert`:e.isMeshBasicMaterial?`basic`:e.isMeshToonMaterial?`toon`:`unknown`}getPhysicalDefaults(){let e={};for(let[t,n]of Object.entries(J))e[t]=xn.has(t)?new r.Color().fromArray(n):Array.isArray(n)?[...n]:n;return e.normalScale={x:J.normalScale[0],y:J.normalScale[1]},e}mapLegacyMaterialToPhysical(e,t){let n={};switch(t){case`basic`:n.emissive=e.color.clone(),n.emissiveIntensity=1,n.color=new r.Color(0),n.roughness=1,n.metalness=0,n.specularIntensity=0;break;case`lambert`:n.roughness=1,n.metalness=0,n.specularIntensity=0;break;case`phong`:{let t=e.shininess||30;n.roughness=Math.sqrt(2/(t+2)),n.metalness=0}if(e.specular){let t=e.specular,i=t.r*.299+t.g*.587+t.b*.114,a=Math.max(t.r,t.g,t.b);n.specularIntensity=Math.min(i*2,1),n.specularColor=a>0?t.clone().multiplyScalar(1/a):new r.Color(1,1,1)}break;case`toon`:n.roughness=.9,n.metalness=0;break;case`standard`:case`physical`:break}return n}createMaterialObject(e){let t=this.getPhysicalDefaults(),n=this.getMaterialType(e),r=this.mapLegacyMaterialToPhysical(e,n),i=Tn(e),a={},o=n=>r[n]===void 0?e[n]!==void 0&&e[n]!==null?(a[n]=Sn.MATERIAL,e[n]):(a[n]=Sn.DEFAULT,t[n]):(a[n]=Sn.MAPPED,r[n]);for(let e of[`transparent`,`alphaMode`,`side`,`depthWrite`])a[e]=Sn.MATERIAL;return{uuid:e.uuid,color:o(`color`),emissive:o(`emissive`),emissiveIntensity:o(`emissiveIntensity`),roughness:Math.max(.02,o(`roughness`)),metalness:o(`metalness`),ior:o(`ior`),opacity:o(`opacity`),transmission:o(`transmission`),thickness:o(`thickness`),attenuationColor:o(`attenuationColor`),attenuationDistance:o(`attenuationDistance`),dispersion:o(`dispersion`),sheen:o(`sheen`),sheenRoughness:o(`sheenRoughness`),sheenColor:o(`sheenColor`),clearcoat:o(`clearcoat`),clearcoatRoughness:o(`clearcoatRoughness`),iridescence:o(`iridescence`),iridescenceIOR:o(`iridescenceIOR`),iridescenceThicknessRange:o(`iridescenceThicknessRange`),subsurface:o(`subsurface`),subsurfaceColor:o(`subsurfaceColor`),subsurfaceRadius:o(`subsurfaceRadius`),subsurfaceRadiusScale:o(`subsurfaceRadiusScale`),subsurfaceAnisotropy:o(`subsurfaceAnisotropy`),anisotropy:o(`anisotropy`),anisotropyRotation:o(`anisotropyRotation`),specularIntensity:o(`specularIntensity`),specularColor:o(`specularColor`),normalScale:o(`normalScale`),bumpScale:o(`bumpScale`),displacementScale:o(`displacementScale`),transparent:+!!e.transparent,alphaTest:o(`alphaTest`),alphaMode:En(e),side:this.getMaterialSide(e),depthWrite:e.depthWrite??!0?1:0,map:this.processTexture(i.map,this.maps),normalMap:this.processTexture(i.normalMap,this.normalMaps),bumpMap:this.processTexture(i.bumpMap,this.bumpMaps),roughnessMap:this.processTexture(i.roughnessMap,this.roughnessMaps),metalnessMap:this.processTexture(i.metalnessMap,this.metalnessMaps),emissiveMap:this.processTexture(i.emissiveMap,this.emissiveMaps),displacementMap:this.processTexture(i.displacementMap,this.displacementMaps),anisotropyMap:this.processTexture(i.anisotropyMap,this.anisotropyMaps),clearcoatMap:this.processTexture(i.clearcoatMap,this.clearcoatMaps),clearcoatRoughnessMap:this.processTexture(i.clearcoatRoughnessMap,this.clearcoatRoughnessMaps),transmissionMap:this.processTexture(i.transmissionMap,this.transmissionMaps),thicknessMap:this.processTexture(e.thicknessMap,[]),sheenColorMap:this.processTexture(i.sheenColorMap,this.sheenColorMaps),sheenRoughnessMap:this.processTexture(i.sheenRoughnessMap,this.sheenRoughnessMaps),specularIntensityMap:this.processTexture(i.specularIntensityMap,this.specularIntensityMaps),specularColorMap:this.processTexture(i.specularColorMap,this.specularColorMaps),iridescenceMap:this.processTexture(i.iridescenceMap,this.iridescenceMaps),iridescenceThicknessMap:this.processTexture(i.iridescenceThicknessMap,this.iridescenceThicknessMaps),mapMatrix:this.getTextureMatrix(i.map),normalMapMatrices:this.getTextureMatrix(i.normalMap),bumpMapMatrices:this.getTextureMatrix(i.bumpMap),roughnessMapMatrices:this.getTextureMatrix(i.roughnessMap),metalnessMapMatrices:this.getTextureMatrix(i.metalnessMap),emissiveMapMatrices:this.getTextureMatrix(i.emissiveMap),displacementMapMatrices:this.getTextureMatrix(i.displacementMap),sources:a,originalType:n}}getTextureMatrix(e){return e?(e.matrixAutoUpdate&&e.updateMatrix(),e.matrix.elements):new r.Matrix3().elements}getMaterialSide(e){if(e.transmission>0)return 2;switch(e.side){case r.FrontSide:return 0;case r.BackSide:return 1;case r.DoubleSide:return 2;default:return 0}}processTexture(e,t){if(!e)return-1;let n=this._textureIndexCache.get(t);n||(n=new Map,this._textureIndexCache.set(t,n));let r=e.source.uuid,i=n.get(r);if(i!==void 0)return i;if(t.length<bn){t.push(e);let i=t.length-1;return n.set(r,i),i}return this._droppedTextures++,this._droppedTextures===1&&this._issues?.record(ln.TEXTURE_LIMIT_EXCEEDED,`scene needs more than ${bn} distinct textures for one map type; the rest render untextured`,{limit:bn,firstDropped:e.name||e.source?.uuid}),-1}extractGeometry(e,t,n,i=!1,a=!1){e.updateMatrix(),e.updateMatrixWorld();let o=e.geometry;o.attributes.normal||o.computeVertexNormals();let s=o.attributes.position,c=o.attributes.normal,l=o.attributes.uv,u=o.index?o.index.array:null,d=u?u.length/3:s.count/3;if(a){let i=e.count??e.instanceMatrix.array.length/16,a=this._matrixPool.mat4,o=new r.Matrix4;for(let f=0;f<i;f++){a.fromArray(e.instanceMatrix.array,f*16),o.multiplyMatrices(e.matrixWorld,a);let i=new r.Matrix3().getNormalMatrix(o);this.extractTrianglesInBatch(s,c,l,u,d,t,n,o,i,Mn(o.elements)<0)}return}let f=i?this._matrixPool.mat4.copy(e.matrixWorld):null,p=i?this._matrixPool.mat3.getNormalMatrix(e.matrixWorld):null,m=i&&Mn(f.elements)<0;this.extractTrianglesInBatch(s,c,l,u,d,t,n,f,p,m)}extractTrianglesInBatch(e,t,n,r,i,a,o,s=null,c=null,l=!1){for(;this.materialTriangleCounts.length<=a;)this.materialTriangleCounts.push(0);this.materialTriangleCounts[a]+=i;let u=this._getVec3(0),d=this._getVec3(1),f=this._getVec3(2),p=this._getVec3(3),m=this._getVec3(4),h=this._getVec3(5),g=this._getVec2(0),_=this._getVec2(1),v=this._getVec2(2);this._ensureCapacity(this.currentTriangleIndex+i);let y=s?.elements,b=c?.elements;for(let c=0;c<i;c++){let i=c*3,x=r?r[i+0]:i+0,S=l?2:1,C=l?1:2,w=r?r[i+S]:i+S,T=r?r[i+C]:i+C;this.getVertex(e,x,u),this.getVertex(e,w,d),this.getVertex(e,T,f),this.getVertex(t,x,p),this.getVertex(t,w,m),this.getVertex(t,T,h),n?(this.getVertex(n,x,g),this.getVertex(n,w,_),this.getVertex(n,T,v)):(g.set(0,0),_.set(0,0),v.set(0,0)),s&&(On(u,y),On(d,y),On(f,y),kn(p,b),kn(m,b),kn(h,b)),p.normalize(),m.normalize(),h.normalize(),this.packTriangleDataTextureFormat(this.currentTriangleIndex,u,d,f,p,m,h,g,_,v,a,o),this.currentTriangleIndex++}}packTriangleDataTextureFormat(e,t,n,r,i,a,o,s,c,l,u,d){let f=$e,p=this.triangles.baseOf(e),m=this.triangleFloatChunks.chunkFor(e),h=this.triangles.chunkFor(e);m[p+f.POSITION_A_OFFSET+0]=t.x,m[p+f.POSITION_A_OFFSET+1]=t.y,m[p+f.POSITION_A_OFFSET+2]=t.z,h[p+f.NORMAL_A_PACKED_OFFSET]=nt(i.x,i.y,i.z),m[p+f.POSITION_B_OFFSET+0]=n.x,m[p+f.POSITION_B_OFFSET+1]=n.y,m[p+f.POSITION_B_OFFSET+2]=n.z,h[p+f.NORMAL_B_PACKED_OFFSET]=nt(a.x,a.y,a.z),m[p+f.POSITION_C_OFFSET+0]=r.x,m[p+f.POSITION_C_OFFSET+1]=r.y,m[p+f.POSITION_C_OFFSET+2]=r.z,h[p+f.NORMAL_C_PACKED_OFFSET]=nt(o.x,o.y,o.z),m[p+f.UV_AB_OFFSET+0]=s.x,m[p+f.UV_AB_OFFSET+1]=s.y,m[p+f.UV_AB_OFFSET+2]=c.x,m[p+f.UV_AB_OFFSET+3]=c.y,m[p+f.UV_C_OFFSET+0]=l.x,m[p+f.UV_C_OFFSET+1]=l.y,h[p+f.MATERIAL_FLAGS_OFFSET]=K(u,this.materials[u]),h[p+f.MESH_INDEX_OFFSET]=d}getTriangleData(){return this.triangles?this.triangles.trimTo(this.currentTriangleIndex):null}getTriangleCount(){return this.currentTriangleIndex}getVertex(e,t,n){return e.itemSize===2?(n.x=e.getX(t),n.y=e.getY(t)):e.itemSize>=3&&(n.x=e.getX(t),n.y=e.getY(t),n.z=e.getZ(t)),n}logStats(){let e=this.currentTriangleIndex*$e.FLOATS_PER_TRIANGLE*4;yn.debug(Y.list([`${Y.count(this.currentTriangleIndex,`tri`)} (${Y.mb(e)})`,Y.count(this.materials.length,`material`),Y.count(this.maps.length,`map`)]))}extractMaterialsOnly(e){return this.resetArrays(),this._traverseMaterialsOnly(e),this.getExtractedData()}_traverseMaterialsOnly(e){if(e.isMesh&&e.geometry&&e.material){let t=this.processMaterial(e.material);e.userData.materialIndex=t;let n=this.meshes.length;this.meshes.push(e),e.userData.meshIndex=n}else e.isDirectionalLight?this.directionalLights.push(e):e.isCamera&&this.cameras.push(e);if(e.children)for(let t of e.children)this._traverseMaterialsOnly(t)}resetArrays(){this._droppedTextures=0,this.triangles=null,this.triangleData=null,this.triangleFloatChunks=null,this.triangleFloats=null,this.triangleCount=0,this.currentTriangleIndex=0,this.materials=[],this.materialTriangleCounts=[],this.meshes=[],this.meshTriangleRanges=[],this._geometryRanges=new Map,this.expandedTriangleCount=0,this._allocatePlacements(0),this.maps=[],this.normalMaps=[],this.bumpMaps=[],this.metalnessMaps=[],this.emissiveMaps=[],this.roughnessMaps=[],this.displacementMaps=[],this.anisotropyMaps=[],this.transmissionMaps=[],this.clearcoatMaps=[],this.clearcoatRoughnessMaps=[],this.sheenColorMaps=[],this.sheenRoughnessMaps=[],this.iridescenceMaps=[],this.iridescenceThicknessMaps=[],this.specularIntensityMaps=[],this.specularColorMaps=[],this.directionalLights=[],this.cameras=[],this._materialUuidMap=new Map,this._textureIndexCache=new WeakMap}getExtractedData(){return{triangleData:this.getTriangleData(),triangleCount:this.getTriangleCount(),materials:this.materials,materialTriangleCounts:this.materialTriangleCounts,meshes:this.meshes,meshTriangleRanges:this.meshTriangleRanges,expandedTriangleCount:this.expandedTriangleCount,instanceSource:this.instanceSource.subarray(0,this.instanceCount),instanceMatrices:this.instanceMatrices.subarray(0,this.instanceCount*16),instanceCount:this.instanceCount,bakeInverse:this.bakeInverse,maps:this.maps,normalMaps:this.normalMaps,bumpMaps:this.bumpMaps,metalnessMaps:this.metalnessMaps,emissiveMaps:this.emissiveMaps,roughnessMaps:this.roughnessMaps,displacementMaps:this.displacementMaps,anisotropyMaps:this.anisotropyMaps,transmissionMaps:this.transmissionMaps,clearcoatMaps:this.clearcoatMaps,clearcoatRoughnessMaps:this.clearcoatRoughnessMaps,sheenColorMaps:this.sheenColorMaps,sheenRoughnessMaps:this.sheenRoughnessMaps,iridescenceMaps:this.iridescenceMaps,iridescenceThicknessMaps:this.iridescenceThicknessMaps,specularIntensityMaps:this.specularIntensityMaps,specularColorMaps:this.specularColorMaps,directionalLights:this.directionalLights,cameras:this.cameras}}},Pn=null,Fn=null;function In(e,t=null){Pn=e,Fn=e?t:null}function Ln(){return Pn}function Rn(){return Fn}function zn(e){if(!Pn)return!1;let t=e[0],n=e[1],r=e[2];return e[0]=Pn[0]*t+Pn[1]*n+Pn[2]*r,e[1]=Pn[3]*t+Pn[4]*n+Pn[5]*r,e[2]=Pn[6]*t+Pn[7]*n+Pn[8]*r,!0}function Bn(e,t,n){if(!Pn||n.length===0)return 0;let r=0;for(let i=0;i+t<=e.length;i+=t)for(let t of n){let n=i+t,a=e[n],o=e[n+1],s=e[n+2];e[n]=Pn[0]*a+Pn[1]*o+Pn[2]*s,e[n+1]=Pn[3]*a+Pn[4]*o+Pn[5]*s,e[n+2]=Pn[6]*a+Pn[7]*o+Pn[8]*s,r++}return r}qt();var Vn=new WeakSet,Hn=Pt(`material`),Un=q.SLOTS_PER_MATERIAL,Wn=$e.MATERIAL_FLAGS_OFFSET,Gn=new Set([`transmission`,`transparent`,`opacity`,`alphaMode`]),Kn=[[`map`,!0],[`emissiveMap`,!0],[`sheenColorMap`,!0],[`specularColorMap`,!0],[`normalMap`,!1],[`bumpMap`,!1],[`roughnessMap`,!1],[`metalnessMap`,!1],[`displacementMap`,!1],[`anisotropyMap`,!1],[`transmissionMap`,!1],[`clearcoatMap`,!1],[`clearcoatRoughnessMap`,!1],[`sheenRoughnessMap`,!1],[`iridescenceMap`,!1],[`iridescenceThicknessMap`,!1],[`specularIntensityMap`,!1]],qn={ior:q.IOR,transmission:q.TRANSMISSION,thickness:q.THICKNESS,emissiveIntensity:q.EMISSIVE_INTENSITY,attenuationDistance:q.ATTENUATION_DISTANCE,opacity:q.OPACITY,alphaTest:q.ALPHA_TEST,metalness:q.METALNESS,roughness:q.ROUGHNESS,clearcoat:q.CLEARCOAT,clearcoatRoughness:q.CLEARCOAT_ROUGHNESS,dispersion:q.DISPERSION,sheen:q.SHEEN,sheenRoughness:q.SHEEN_ROUGHNESS,specularIntensity:q.SPECULAR_INTENSITY,iridescence:q.IRIDESCENCE,iridescenceIOR:q.IRIDESCENCE_IOR,subsurface:q.SUBSURFACE,subsurfaceRadiusScale:q.SUBSURFACE_RADIUS_SCALE,subsurfaceAnisotropy:q.SUBSURFACE_ANISOTROPY,anisotropy:q.ANISOTROPY,anisotropyRotation:q.ANISOTROPY_ROTATION},Jn=class e{constructor(e){this.sdfs=e,this.materialStorageAttr=null,this.materialStorageNode=null,this.materialCount=0,this.srgbBuckets=null,this.linearBuckets=null,this._srgbTexPacked=null,this._linearTexPacked=null,this.callbacks={},this._sources=[],this._hostSet=[]}static COLOR_OFFSETS=[q.COLOR,q.EMISSIVE,q.ATTENUATION_COLOR,q.SHEEN_COLOR,q.SPECULAR_COLOR,q.SUBSURFACE_COLOR].filter(e=>Number.isInteger(e));_convertColorsToWorkingSpace(t){if(Vn.has(t))return;Vn.add(t);let n=Bn(t,q.FLOATS_PER_MATERIAL,e.COLOR_OFFSETS);n&&Hn.debug(`converted ${n} material colour(s) into ${Rn()}`)}_writeColor(e,t,n,r,i){let a=[n,r,i];zn(a)&&([n,r,i]=a),e[t]=n,e[t+1]=r,e[t+2]=i}setMaterialData(e,r=[]){if(!e)return;this._convertColorsToWorkingSpace(e);let i=e.length/4;this.materialStorageNode?(this.materialStorageAttr=new t.StorageInstancedBufferAttribute(e,4),this.materialStorageNode.value=this.materialStorageAttr,this.materialStorageNode.bufferCount=i):(this.materialStorageAttr=new t.StorageInstancedBufferAttribute(e,4),this.materialStorageNode=(0,n.storage)(this.materialStorageAttr,`vec4`,i).toReadOnly()),this.materialCount=Math.floor(i/Un),this._sources=[...r],this._hostSet=[],Hn.debug(`${Y.n(this.materialCount)} materials (storage buffer)`)}getStorageAttr(){return this.materialStorageAttr}getStorageNode(){return this.materialStorageNode}setMaterialTextures(e){e.srgbBuckets&&(this.srgbBuckets=e.srgbBuckets),e.linearBuckets&&(this.linearBuckets=e.linearBuckets)}setTexturePackMaps(e,t){this._srgbTexPacked=e||null,this._linearTexPacked=t||null}getPackedTextureIndex(e,t){if(!e)return-1;let n=e.source?.uuid??e.uuid,r=(t?this._srgbTexPacked:this._linearTexPacked)?.get(n);return r===void 0?-1:r}loadTexturesFromSdfs(){this.srgbBuckets=this.sdfs.srgbBucketTextures,this.linearBuckets=this.sdfs.linearBucketTextures,this.setTexturePackMaps(this.sdfs._srgbTexPacked,this.sdfs._linearTexPacked)}getTextureArrays(){return{srgbBuckets:this.srgbBuckets,linearBuckets:this.linearBuckets}}getMaterialProperty(e,t){let n=this.materialStorageAttr?.array;if(!n)return;let r=qn[t];if(r===void 0)return;let i=e*q.FLOATS_PER_MATERIAL+r;return i<n.length?n[i]:void 0}getMaterialPropertySource(e,t){return this._hostSet[e]?.has(t)?Sn.HOST:this._sources[e]?.[t]}updateMaterialProperty(e,t,n){if(!this.materialStorageAttr){Hn.warn(`material storage buffer not available`);return}let r=this.materialStorageAttr.array,i=e*q.FLOATS_PER_MATERIAL;switch(nn.has(t)&&typeof n==`number`&&(n=rn(n)),t){case`color`:n.r===void 0?Array.isArray(n)&&this._writeColor(r,i+q.COLOR,n[0],n[1],n[2]):this._writeColor(r,i+q.COLOR,n.r,n.g,n.b);break;case`metalness`:r[i+q.METALNESS]=n;break;case`emissive`:n.r===void 0?Array.isArray(n)&&this._writeColor(r,i+q.EMISSIVE,n[0],n[1],n[2]):this._writeColor(r,i+q.EMISSIVE,n.r,n.g,n.b);break;case`roughness`:r[i+q.ROUGHNESS]=n;break;case`ior`:r[i+q.IOR]=n;break;case`transmission`:r[i+q.TRANSMISSION]=n;break;case`thickness`:r[i+q.THICKNESS]=n;break;case`emissiveIntensity`:r[i+q.EMISSIVE_INTENSITY]=n;break;case`attenuationColor`:n.r===void 0?Array.isArray(n)&&this._writeColor(r,i+q.ATTENUATION_COLOR,n[0],n[1],n[2]):this._writeColor(r,i+q.ATTENUATION_COLOR,n.r,n.g,n.b);break;case`attenuationDistance`:r[i+q.ATTENUATION_DISTANCE]=rt(n);break;case`dispersion`:r[i+q.DISPERSION]=n;break;case`sheen`:r[i+q.SHEEN]=n;break;case`sheenRoughness`:r[i+q.SHEEN_ROUGHNESS]=n;break;case`sheenColor`:n.r===void 0?Array.isArray(n)&&this._writeColor(r,i+q.SHEEN_COLOR,n[0],n[1],n[2]):this._writeColor(r,i+q.SHEEN_COLOR,n.r,n.g,n.b);break;case`specularIntensity`:r[i+q.SPECULAR_INTENSITY]=n;break;case`specularColor`:n.r===void 0?Array.isArray(n)&&this._writeColor(r,i+q.SPECULAR_COLOR,n[0],n[1],n[2]):this._writeColor(r,i+q.SPECULAR_COLOR,n.r,n.g,n.b);break;case`iridescence`:r[i+q.IRIDESCENCE]=n;break;case`iridescenceIOR`:r[i+q.IRIDESCENCE_IOR]=n;break;case`iridescenceThicknessRange`:Array.isArray(n)&&(r[i+q.IRIDESCENCE_THICKNESS_RANGE]=n[0],r[i+q.IRIDESCENCE_THICKNESS_RANGE+1]=n[1]);break;case`clearcoat`:r[i+q.CLEARCOAT]=n;break;case`clearcoatRoughness`:r[i+q.CLEARCOAT_ROUGHNESS]=n;break;case`opacity`:r[i+q.OPACITY]=n;break;case`side`:r[i+q.SIDE]=n,this._patchTriangleSideForMaterial(e,n);break;case`transparent`:r[i+q.TRANSPARENT]=n;break;case`alphaTest`:r[i+q.ALPHA_TEST]=n;break;case`alphaMode`:r[i+q.ALPHA_MODE]=n;break;case`depthWrite`:r[i+q.DEPTH_WRITE]=n;break;case`normalScale`:n.x===void 0?typeof n==`number`&&(r[i+q.NORMAL_SCALE]=n,r[i+q.NORMAL_SCALE+1]=n):(r[i+q.NORMAL_SCALE]=n.x,r[i+q.NORMAL_SCALE+1]=n.y);break;case`bumpScale`:r[i+q.BUMP_SCALE]=n;break;case`displacementScale`:r[i+q.DISPLACEMENT_SCALE]=n;break;case`subsurface`:r[i+q.SUBSURFACE]=n;break;case`subsurfaceRadiusScale`:r[i+q.SUBSURFACE_RADIUS_SCALE]=n;break;case`subsurfaceAnisotropy`:r[i+q.SUBSURFACE_ANISOTROPY]=n;break;case`anisotropy`:r[i+q.ANISOTROPY]=n;break;case`anisotropyRotation`:r[i+q.ANISOTROPY_ROTATION]=n;break;case`subsurfaceColor`:n.r===void 0?Array.isArray(n)&&this._writeColor(r,i+q.SUBSURFACE_COLOR,n[0],n[1],n[2]):this._writeColor(r,i+q.SUBSURFACE_COLOR,n.r,n.g,n.b);break;case`subsurfaceRadius`:Array.isArray(n)?(r[i+q.SUBSURFACE_RADIUS]=n[0],r[i+q.SUBSURFACE_RADIUS+1]=n[1],r[i+q.SUBSURFACE_RADIUS+2]=n[2]):n.x!==void 0&&(r[i+q.SUBSURFACE_RADIUS]=n.x,r[i+q.SUBSURFACE_RADIUS+1]=n.y,r[i+q.SUBSURFACE_RADIUS+2]=n.z);break;default:Hn.warn(`unknown material property: ${t}`);return}this.materialStorageAttr.needsUpdate=!0,(this._hostSet[e]??=new Set).add(t),Gn.has(t)&&this._recomputeOpaqueBlockerForMaterial(e),this._notifyReset()}updateMaterialDataFromObject(t,n){if(!this.materialStorageAttr){Hn.warn(`material storage buffer not available`);return}let r=this.materialStorageAttr.array,i=t*q.FLOATS_PER_MATERIAL;cn(r,i,n);for(let t of e.COLOR_OFFSETS)this._writeColor(r,i+t,r[i+t],r[i+t+1],r[i+t+2]);this._sources[t]=n.sources,this._hostSet[t]=void 0,this._patchTriangleSideForMaterial(t,r[i+q.SIDE]),this._recomputeOpaqueBlockerForMaterial(t),this.materialStorageAttr.needsUpdate=!0,this._notifyReset()}updateMaterial(e,t){let n=this.sdfs.geometryExtractor.createMaterialObject(t);if(this._srgbTexPacked||this._linearTexPacked){let e=Tn(t);for(let[t,r]of Kn)n[t]=this.getPackedTextureIndex(e[t],r)}this.updateMaterialDataFromObject(e,n)}updateTextureTransform(e,t,n){if(!this.materialStorageAttr){Hn.warn(`material storage buffer not available`);return}let r=this.materialStorageAttr.array,i=e*q.FLOATS_PER_MATERIAL,a={map:q.ALBEDO_TRANSFORM,normalMap:q.NORMAL_TRANSFORM,roughnessMap:q.ROUGHNESS_TRANSFORM,metalnessMap:q.METALNESS_TRANSFORM,emissiveMap:q.EMISSIVE_TRANSFORM,bumpMap:q.BUMP_TRANSFORM,displacementMap:q.DISPLACEMENT_TRANSFORM}[t];if(a===void 0){Hn.warn(`unknown texture name for transform update: ${t}`);return}for(let e=0;e<8;e++)i+a+e<r.length&&(r[i+a+e]=n[e]);this.materialStorageAttr.needsUpdate=!0,this._notifyReset()}_notifyReset(){this.callbacks.onReset&&this.callbacks.onReset()}_recomputeOpaqueBlockerForMaterial(e){let t=this.materialStorageAttr?.array;if(!t)return;let n=e*q.FLOATS_PER_MATERIAL,r=tt({alphaMode:t[n+q.ALPHA_MODE],transparent:t[n+q.TRANSPARENT],transmission:t[n+q.TRANSMISSION],opacity:t[n+q.OPACITY]});this._patchTriangleFlagForMaterial(e,26,2,r)}_patchTriangleFlagForMaterial(e,t,n,r){let i=this.callbacks.getTriangleData?.(),a=i?.records,o=a?null:i?.array,s=i?.count|0;if(!o&&!a||s===0)return;let c=$e.FLOATS_PER_TRIANGLE,l=(1<<n)-1<<t>>>0,u=(r<<t&l)>>>0,d=0;for(let t=0;t<s;t++){let n=a?a.chunkFor(t):o,r=a?a.baseOf(t):t*c;(n[r+Wn]&16777215)===e&&(n[r+Wn]=(n[r+Wn]&~l|u)>>>0,d++)}d>0&&this.callbacks.onTriangleDataChanged&&this.callbacks.onTriangleDataChanged()}_patchTriangleSideForMaterial(e,t){this._patchTriangleFlagForMaterial(e,24,2,t)}dispose(){this.materialStorageAttr=null,this.materialStorageNode=null,this.materialCount=0,this.srgbBuckets=null,this.linearBuckets=null,this._srgbTexPacked=null,this._linearTexPacked=null,this._sources=[],this._hostSet=[]}},Yn=`function e(e,t,n,r){let i=n,a=n+r-1;for(;i<a;){let n=i+a>>1;e[n]<t?i=n+1:a=n}return i-n}function t(t,n,r){let i=n*r,a=new Float32Array(i),o=0;for(let e=0;e<r;e++){let i=Math.sin(Math.PI*(e+.5)/r);for(let r=0;r<n;r++){let s=e*n+r,c=t[4*s],l=t[4*s+1],u=t[4*s+2],d=(.2126*c+.7152*l+.0722*u)*i;a[s]=d,o+=d}}let s=o/i,c=0;for(let e=0;e<i;e++)a[e]=Math.max(0,a[e]-s),c+=a[e];let l=c>0,u=l?c:o,d=l?s:0;if(!l)for(let e=0;e<r;e++){let i=Math.sin(Math.PI*(e+.5)/r);for(let r=0;r<n;r++){let o=e*n+r,s=t[4*o],c=t[4*o+1],l=t[4*o+2];a[o]=(.2126*s+.7152*c+.0722*l)*i}}let f=new Float32Array(i),p=new Float32Array(r),m=0;for(let e=0;e<r;e++){let t=0;for(let r=0;r<n;r++){let i=e*n+r;t+=a[i],f[i]=t}if(t!==0)for(let r=e*n,i=e*n+n;r<i;r++)f[r]/=t;m+=t,p[e]=m}if(m!==0)for(let e=0,t=p.length;e<t;e++)p[e]/=m;let h=new Float32Array(r);for(let t=0;t<r;t++)h[t]=(e(p,(t+1)/r,0,r)+.5)/r;let g=new Float32Array(n*r);for(let t=0;t<r;t++)for(let r=0;r<n;r++){let i=t*n+r;g[i]=(e(f,(r+1)/n,t*n,n)+.5)/n}return{marginalData:h,conditionalData:g,totalSum:u,compensationDelta:d}}self.onmessage=function(e){let{floatData:n,width:r,height:i}=e.data;try{let e=t(n,r,i);self.postMessage({marginalData:e.marginalData,conditionalData:e.conditionalData,totalSum:e.totalSum,compensationDelta:e.compensationDelta,width:r,height:i},[e.marginalData.buffer,e.conditionalData.buffer])}catch(e){self.postMessage({error:e.message})}};`,Xn=typeof self<`u`&&self.Blob&&new Blob([`URL.revokeObjectURL(import.meta.url);`,Yn],{type:`text/javascript;charset=utf-8`});function Zn(e){let t;try{if(t=Xn&&(self.URL||self.webkitURL).createObjectURL(Xn),!t)throw``;let n=new Worker(t,{type:`module`,name:e?.name});return n.addEventListener(`error`,()=>{(self.URL||self.webkitURL).revokeObjectURL(t)}),n}catch{return new Worker(`data:text/javascript;charset=utf-8,`+encodeURIComponent(Yn),{type:`module`,name:e?.name})}}function Qn(e,t,n=0,r=e.length){let i=n,a=n+r-1;for(;i<a;){let n=i+a>>1;e[n]<t?i=n+1:a=n}return i-n}function $n(e,t,n){return .2126*e+.7152*t+.0722*n}function er(e){return e<=.04045?e/12.92:((e+.055)/1.055)**2.4}function tr(e){let{width:t,height:n}=e.image,i=e.image.data,a=!1;if(!i){let r=new OffscreenCanvas(t,n).getContext(`2d`);r.drawImage(e.image,0,0,t,n),i=r.getImageData(0,0,t,n).data,a=!0}let o;if(e.type===r.FloatType&&i instanceof Float32Array)o=new Float32Array(i);else if(e.type===r.HalfFloatType){o=new Float32Array(i.length);for(let e=0,t=i.length;e<t;e++)o[e]=r.DataUtils.fromHalfFloat(i[e])}else{let e;e=i instanceof Int8Array||i instanceof Int16Array||i instanceof Int32Array?2**(8*i.BYTES_PER_ELEMENT-1)-1:2**(8*i.BYTES_PER_ELEMENT)-1,o=new Float32Array(i.length);for(let t=0,n=i.length;t<n;t++)o[t]=i[t]/e}if(!a&&e.colorSpace===r.SRGBColorSpace&&(a=!0),a)for(let e=0,t=o.length;e<t;e+=4)o[e]=er(o[e]),o[e+1]=er(o[e+1]),o[e+2]=er(o[e+2]);if(e.flipY){let e=new Float32Array(o.length);for(let r=0;r<n;r++){let i=n-r-1,a=r*t*4,s=i*t*4;e.set(o.subarray(a,a+t*4),s)}o=e}return{floatData:o,width:t,height:n}}var nr=class e{constructor(){this.marginalData=new Float32Array([0,1]),this.conditionalData=new Float32Array([0,0,1,1]),this.totalSum=0,this.compensationDelta=0,this.width=0,this.height=0,this._worker=null}dispose(){this.marginalData=null,this.conditionalData=null,this._worker&&=(this._worker.terminate(),null)}updateFrom(t){let{floatData:n,width:r,height:i}=tr(t),a=e.computeCDF(n,r,i);this.marginalData=a.marginalData,this.conditionalData=a.conditionalData,this.totalSum=a.totalSum,this.compensationDelta=a.compensationDelta,this.width=r,this.height=i}async updateFromAsync(e){let{floatData:t,width:n,height:r}=tr(e);this._worker=new Zn;try{let e=await new Promise((e,i)=>{this._worker.onmessage=t=>{t.data.error?i(Error(t.data.error)):e(t.data)},this._worker.onerror=i,this._worker.postMessage({floatData:t,width:n,height:r},[t.buffer])});this.marginalData=e.marginalData,this.conditionalData=e.conditionalData,this.totalSum=e.totalSum,this.compensationDelta=e.compensationDelta,this.width=e.width,this.height=e.height}finally{this._worker&&=(this._worker.terminate(),null)}}static computeCDF(e,t,n){let r=t*n,i=new Float32Array(r),a=0;for(let r=0;r<n;r++){let o=Math.sin(Math.PI*(r+.5)/n);for(let n=0;n<t;n++){let s=r*t+n,c=$n(e[4*s],e[4*s+1],e[4*s+2])*o;i[s]=c,a+=c}}let o=a/r,s=0;for(let e=0;e<r;e++)i[e]=Math.max(0,i[e]-o),s+=i[e];let c=s>0,l=c?s:a,u=c?o:0;if(!c)for(let r=0;r<n;r++){let a=Math.sin(Math.PI*(r+.5)/n);for(let n=0;n<t;n++){let o=r*t+n;i[o]=$n(e[4*o],e[4*o+1],e[4*o+2])*a}}let d=new Float32Array(r),f=new Float32Array(n),p=0;for(let e=0;e<n;e++){let n=0;for(let r=0;r<t;r++){let a=e*t+r;n+=i[a],d[a]=n}if(n!==0)for(let r=e*t,i=e*t+t;r<i;r++)d[r]/=n;p+=n,f[e]=p}if(p!==0)for(let e=0,t=f.length;e<t;e++)f[e]/=p;let m=new Float32Array(n),h=new Float32Array(r);for(let e=0;e<n;e++)m[e]=(Qn(f,(e+1)/n)+.5)/n;for(let e=0;e<n;e++)for(let n=0;n<t;n++){let r=e*t+n;h[r]=(Qn(d,(n+1)/t,e*t,t)+.5)/t}return{marginalData:m,conditionalData:h,totalSum:l,compensationDelta:u}}},rr=Math.PI,ir=Math.PI*2,ar=Math.E,or=[5804542996261093e-21,13562911419845635e-21,30265902468824876e-21],sr=[183999185144339.78,277980239196605.28,407904795438610.94],cr=1.6110731556870734,lr=1.5,ur=1e3,dr=8400,fr=1250,pr=.9999566769464484,mr=.05968310365946075,hr=.07957747154594767;function gr(e){return ur*Math.max(0,1-ar**+(-(cr-Math.acos(Math.max(-1,Math.min(1,e))))/lr))}function _r(e){let t=.2*e*1e-17;return[.434*t*sr[0],.434*t*sr[1],.434*t*sr[2]]}function vr(e){return mr*(1+e**2)}function yr(e,t){let n=t*t;return hr*((1-n)/(1-2*t*e+n)**1.5)}function br(e,t){return e[0]*t[0]+e[1]*t[1]+e[2]*t[2]}function xr(e){let t=Math.sqrt(e[0]*e[0]+e[1]*e[1]+e[2]*e[2]);return t===0?[0,0,0]:[e[0]/t,e[1]/t,e[2]/t]}function Sr(e,t,n,r,i,a,o,s){let c=(1-t)*rr,l=(e-.5)*ir,u=Math.sin(c),d=xr([u*Math.sin(l),Math.cos(c),u*Math.cos(l)]),f=xr(n),p=gr(f[1])*r,m=i-1*(1-(1-Math.max(0,Math.min(1,1-Math.exp(f[1]/45e4))))),h=[or[0]*m,or[1]*m,or[2]*m],g=_r(s),_=[g[0]*a,g[1]*a,g[2]*a],v=Math.acos(Math.max(0,d[1])),y=Math.cos(v)+.15*(93.885-180/rr*v)**-1.253,b=dr/y,x=fr/y,S=[Math.exp(-(h[0]*b+_[0]*x)),Math.exp(-(h[1]*b+_[1]*x)),Math.exp(-(h[2]*b+_[2]*x))],C=br(d,f),w=vr(C*.5+.5),T=[h[0]*w,h[1]*w,h[2]*w],E=yr(C,o),D=[_[0]*E,_[1]*E,_[2]*E],O=[T[0]+D[0],T[1]+D[1],T[2]+D[2]],k=[h[0]+_[0],h[1]+_[1],h[2]+_[2]],A=[(p*(O[0]/k[0])*(1-S[0]))**1.5,(p*(O[1]/k[1])*(1-S[1]))**1.5,(p*(O[2]/k[2])*(1-S[2]))**1.5],j=Math.max(0,Math.min(1,1-(1-f[1])**5)),M=[Math.sqrt(p*(O[0]/k[0])*S[0]),Math.sqrt(p*(O[1]/k[1])*S[1]),Math.sqrt(p*(O[2]/k[2])*S[2])],N=1-j;for(let e=0;e<3;e++){let t=1*(1-N)+M[e]*N;A[e]*=t}let P=[.1*S[0],.1*S[1],.1*S[2]],F=Cr(pr,pr+2e-5,C);for(let e=0;e<3;e++)P[e]+=p*19e3*S[e]*F;let I=65504;return[Math.min((A[0]+P[0])*.04,I),Math.min((A[1]+P[1])*.04+3e-4,I),Math.min((A[2]+P[2])*.04+75e-5,I),1]}function Cr(e,t,n){let r=Math.max(0,Math.min(1,(n-e)/(t-e)));return r*r*(3-2*r)}var wr=class{constructor(e=512,t=256){this.width=e,this.height=t,this.lastRenderTime=0,this._pixels=new Float32Array(e*t*4),this._texture=new r.DataTexture(this._pixels,e,t,r.RGBAFormat,r.FloatType),this._texture.mapping=r.EquirectangularReflectionMapping,this._texture.colorSpace=r.LinearSRGBColorSpace,this._texture.minFilter=r.LinearFilter,this._texture.magFilter=r.LinearFilter,this._texture.wrapS=r.RepeatWrapping,this._texture.wrapT=r.ClampToEdgeWrapping,this._texture.generateMipmaps=!1}render(e){let t=performance.now(),n=[e.sunDirection.x,e.sunDirection.y,e.sunDirection.z],r=e.sunIntensity||1,i=e.rayleighDensity||2,a=e.mieDensity||.005,o=e.mieAnisotropy||.8,s=e.turbidity||2,{width:c,height:l}=this,u=this._pixels;for(let e=0;e<l;e++){let t=(e+.5)/l;for(let l=0;l<c;l++){let d=Sr((l+.5)/c,t,n,r,i,a,o,s),f=(e*c+l)*4;u[f]=d[0],u[f+1]=d[1],u[f+2]=d[2],u[f+3]=d[3]}}return this._texture.needsUpdate=!0,delete this._texture.userData?.__rayzeeColorSpace,this.lastRenderTime=performance.now()-t,this._texture}setResolution(e,t){this.width===e&&this.height===t||(this.width=e,this.height=t,this._pixels=new Float32Array(e*t*4),this._texture.dispose(),this._texture=new r.DataTexture(this._pixels,e,t,r.RGBAFormat,r.FloatType),this._texture.mapping=r.EquirectangularReflectionMapping,this._texture.colorSpace=r.LinearSRGBColorSpace,this._texture.minFilter=r.LinearFilter,this._texture.magFilter=r.LinearFilter,this._texture.wrapS=r.RepeatWrapping,this._texture.wrapT=r.ClampToEdgeWrapping,this._texture.generateMipmaps=!1)}getLastRenderTime(){return this.lastRenderTime}dispose(){this._texture.dispose()}},Tr=class{constructor(e=512,t=256){this.width=e,this.height=t,this.lastRenderTime=0,this._pixels=new Float32Array(e*t*4),this._texture=new r.DataTexture(this._pixels,e,t,r.RGBAFormat,r.FloatType),this._texture.mapping=r.EquirectangularReflectionMapping,this._texture.colorSpace=r.LinearSRGBColorSpace,this._texture.minFilter=r.LinearFilter,this._texture.magFilter=r.LinearFilter,this._texture.wrapS=r.RepeatWrapping,this._texture.wrapT=r.ClampToEdgeWrapping,this._texture.generateMipmaps=!1}renderGradient(e){let t=performance.now(),{width:n,height:r}=this,i=this._pixels,a=e.zenithColor.r,o=e.zenithColor.g,s=e.zenithColor.b,c=e.horizonColor.r,l=e.horizonColor.g,u=e.horizonColor.b,d=e.groundColor.r,f=e.groundColor.g,p=e.groundColor.b;for(let e=0;e<r;e++){let t=(e+.5)/r,m,h,g;if(t>.5){let e=(t-.5)*2;m=c+(a-c)*e,h=l+(o-l)*e,g=u+(s-u)*e}else{let e=t*2;m=d+(c-d)*e,h=f+(l-f)*e,g=p+(u-p)*e}for(let t=0;t<n;t++){let r=(e*n+t)*4;i[r]=m,i[r+1]=h,i[r+2]=g,i[r+3]=1}}return this._texture.needsUpdate=!0,delete this._texture.userData?.__rayzeeColorSpace,this.lastRenderTime=performance.now()-t,this._texture}renderSolid(e){let t=performance.now(),{width:n,height:r}=this,i=this._pixels,a=e.color.r,o=e.color.g,s=e.color.b;for(let e=0;e<r;e++)for(let t=0;t<n;t++){let r=(e*n+t)*4;i[r]=a,i[r+1]=o,i[r+2]=s,i[r+3]=1}return this._texture.needsUpdate=!0,delete this._texture.userData?.__rayzeeColorSpace,this.lastRenderTime=performance.now()-t,this._texture}setResolution(e,t){this.width===e&&this.height===t||(this.width=e,this.height=t,this._pixels=new Float32Array(e*t*4),this._texture.dispose(),this._texture=new r.DataTexture(this._pixels,e,t,r.RGBAFormat,r.FloatType),this._texture.mapping=r.EquirectangularReflectionMapping,this._texture.colorSpace=r.LinearSRGBColorSpace,this._texture.minFilter=r.LinearFilter,this._texture.magFilter=r.LinearFilter,this._texture.wrapS=r.RepeatWrapping,this._texture.wrapT=r.ClampToEdgeWrapping,this._texture.generateMipmaps=!1)}getLastRenderTime(){return this.lastRenderTime}dispose(){this._texture.dispose()}};function Er(e){let t=String(e??``);return/(hdr|pq|hlg|2100|st2084)/i.test(t)?null:/^display\s*p3\b/i.test(t)?`display-p3`:/^(srgb|rec\.?\s*1886|bt\.?\s*1886|gamma\s*2\.2\s*rec\.?\s*709)\b(?!.*(p3|2020))/i.test(t)?`srgb`:null}function Dr(e){e&&Object.assign(kr,e)}function Or(){return{...kr}}var kr,Ar=y((()=>{kr={stbnScalarAtlas:`https://assets.rayzee.atulmourya.com/noise/stbn_scalar_atlas.png`,stbnVec2Atlas:`https://assets.rayzee.atulmourya.com/noise/stbn_vec2_atlas.png`,ortRuntimeUrl:`https://cdn.jsdelivr.net/npm/onnxruntime-web@1.24.3/dist/ort.webgpu.bundle.min.mjs`,ortWasmPaths:`https://cdn.jsdelivr.net/npm/onnxruntime-web@1.24.3/dist/`,dracoDecoderPath:`https://www.gstatic.com/draco/v1/decoders/`,ktx2TranscoderPath:`https://cdn.jsdelivr.net/npm/three@0.183.2/examples/jsm/libs/basis/`,oidnWeightsBaseUrl:`https://assets.rayzee.atulmourya.com/oidn/denoiser-0.0.11/`,ocioRuntimeFactory:null,ocioRuntimeUrl:null,ocioWasmUrl:null,upscalerModelBaseUrl:`https://huggingface.co/notaneimu/onnx-image-models/resolve/main/`,dlssRuntimeUrl:`/dlss/dlss-runtime.js`,dlssAssetBaseUrl:`https://pub-6e048ff014374f11bef33d76b6c2b5ef.r2.dev/v1`,cacheNamespace:`rayzee`}}));Ar(),qt();var jr=Pt(`ocio`);function Mr(e){let t=String(e);/\[OpenColorIO Error\]/.test(t)?jr.error(t):/\[OpenColorIO Warning\]/.test(t)?jr.warn(t):jr.debug(t)}var Nr=null,Pr=null,Fr=null,Ir=null,Lr=null;async function Rr(){let{ocioRuntimeFactory:e,ocioRuntimeUrl:t}=Or();if(typeof e==`function`)return await e();if(typeof t==`string`&&t)return await import(t);throw Error(`OpenColorIO runtime not configured. Call configureAssets({ ocioRuntimeFactory: () => import('@bb-studio/ocio') }) before loading a config.`)}async function zr(){return Pr||(Nr||=(async()=>{let e=await Rr();if(typeof e.createOcioRuntime!=`function`)throw Error(`OCIO module has no createOcioRuntime() — wrong package or version`);let{ocioWasmUrl:t}=Or();return Pr=await e.createOcioRuntime({...t?{wasmUrl:t}:{},moduleOptions:{print:Mr,printErr:Mr}}),Pr})().catch(e=>{throw Nr=null,e}),await Nr)}async function Br(){return(await zr()).ocio.listBuiltinConfigs()}async function Vr({builtin:e,text:t,files:n=[],configPath:r=`config.ocio`,id:i}={}){let a=await zr();if(e)Fr=a.loadBuiltinConfig(e),Ir=e,Lr=qr(a,e);else{let e=n.map(e=>({relativePath:e.relativePath??e.path??e.name,data:e.data instanceof Uint8Array?e.data:new Uint8Array(e.data)}));if(t!==void 0&&e.unshift({relativePath:r,data:new TextEncoder().encode(t)}),!e.some(e=>e.relativePath===r))throw Error(`config package has no "${r}" — pass configPath to name the .ocio file`);Fr=a.loadConfigPackage({configRelativePath:r,files:e},i?{id:i}:void 0),Ir=i??Fr.id;let o=e.find(e=>e.relativePath===r);Lr=o?new TextDecoder().decode(o.data):null}return Kr()}function Hr(){Fr=null,Ir=null,Lr=null}function Ur(){return Fr!==null}function Wr(){return Fr?Pr:null}function Gr(){return Fr}function Kr(){if(!Fr)return null;let e=Object.fromEntries(Fr.roles.map(e=>[e.name,e.colorSpace]));return{id:Ir,name:Lr?.match(/^name:\s*(\S.*?)\s*$/m)?.[1]??null,ocioVersion:Fr.ocioVersion,version:Fr.version,roles:e,sceneLinear:e.scene_linear??null,colorPicking:e.color_picking??e.texture_paint??null,texturePaint:e.texture_paint??e.color_picking??null,data:e.data??null,compositingLog:e.compositing_log??e.color_timing??null,colorSpaces:Fr.colorSpaces.map(e=>({name:e.name,family:e.family,categories:e.categories??[],encoding:e.encoding,isData:e.isData,aliases:e.aliases,description:e.description})),displays:Fr.displays.slice(),defaultDisplay:Fr.defaultDisplay,views:Object.fromEntries(Object.entries(Fr.viewsByDisplay).map(([e,t])=>[e,t.map(e=>({name:e.name,transform:e.transform,colorSpace:e.colorSpace,looks:e.looks,description:e.description}))])),defaultViews:{...Fr.defaultViewsByDisplay},looks:Fr.looks.map(e=>({name:e.name,processSpace:e.processSpace,description:e.description,forward:e.hasForwardTransform,inverse:e.hasInverseTransform})),namedTransforms:Fr.namedTransforms.map(e=>e.name),fileRules:Fr.fileRules.map(e=>({index:e.index,name:e.name,colorSpace:e.colorSpace,pattern:e.pattern,extension:e.extension,regex:e.regex})),contextVariables:Jr()}}function qr(e,t){try{return e.ocio.getBuiltinConfigYaml(t)}catch{return null}}function Jr(){if(!Lr)return[];let e=new Map,t=Lr.split(/\r?\n/),n=t.findIndex(e=>/^environment:\s*(\{\s*\})?\s*$/.test(e));if(n>=0&&!/\{\s*\}/.test(t[n]))for(let r=n+1;r<t.length;r++){let n=t[r];if(/^\S/.test(n))break;let i=n.match(/^\s+([A-Za-z_][A-Za-z0-9_]*)\s*:\s*(.*?)\s*$/);i&&e.set(i[1],{name:i[1],default:i[2].replace(/^["']|["']$/g,``)||null,declared:!0})}for(let t of Lr.matchAll(/\$\{?([A-Za-z_][A-Za-z0-9_]*)\}?/g))e.has(t[1])||e.set(t[1],{name:t[1],default:null,declared:!1});return[...e.values()].sort((e,t)=>e.name.localeCompare(t.name))}function Yr(){Hr(),Pr?.dispose?.(),Pr=null,Nr=null}var Xr=1<<20,Zr=new Map,Qr=new Map,$r=4096,ei=new Map;function ti(e,t,n){return`${e}\u0000${t}\u0000${n?JSON.stringify(n):``}`}function ni(){for(let e of Zr.values())e.dispose?.();Zr.clear(),Qr.clear(),ei.clear()}function ri(e,t,{context:n=null}={}){if(!Wr()||e===t)return null;let r=ti(e,t,n),i=Zr.get(r);if(i!==void 0)return i;try{i=si().createColorSpaceProcessor(e,t,n?{context:n}:void 0),i.isNoOp&&(i.dispose(),i=null)}catch(n){throw Error(`no OCIO transform from "${e}" to "${t}": ${n.message}`)}return Zr.set(r,i),i}var ii=null,ai=null,oi=!1;function si(){let e=Wr();if(!e)throw Error(`no OCIO config loaded`);if(e.config)return e.config;let t=Gr();if(ii&&ai===t.id)return ii;if(oi&&ii?.dispose?.(),!t.id?.startsWith(`ocio://`))throw Error(`OCIO runtime exposes no Config handle for this config`);return ii=e.ocio.createBuiltinConfig(t.id),oi=!0,ai=t.id,ii}function ci(){oi&&ii?.dispose?.(),ii=null,ai=null,oi=!1,ni()}function li(e,t,n,{context:r=null}={}){let i=Wr();if(!i||t===n)return[e[0],e[1],e[2]];let a=`${ti(t,n,r)}\u0000${e[0]},${e[1]},${e[2]}`,o=Qr.get(a);if(o)return o.slice();let s=i.transformRgb(t,n,[e[0],e[1],e[2]],r?{context:r}:void 0);return Qr.size>=$r&&Qr.clear(),Qr.set(a,s),s.slice()}function ui(e,t,n,{context:r=null}={}){if(e.length%4!=0)throw Error(`convertPixelsF32 wants 4 floats per pixel`);let i=ri(t,n,{context:r});if(!i)return e;let a=e.length/4;if(a<=Xr)return i.applyRGBAF32(e),e;for(let t=0;t<a;t+=Xr){let n=Math.min(Xr,a-t);i.applyRGBAF32(e.subarray(t*4,(t+n)*4))}return e}var di=.055;function fi(e){return e<=.04045?e/12.92:((e+di)/(1+di))**2.4}function pi(e){return e<=0?0:e<=.0031308?12.92*e:(1+di)*e**(1/2.4)-di}var mi=new Float32Array(256);for(let e=0;e<256;e++)mi[e]=fi(e/255);var hi=new Float32Array(256);for(let e=0;e<256;e++)hi[e]=e/255;function gi(e){return e===`srgb`?mi:hi}function _i(e,t,n,{context:r=null,inputEncoding:i=`raw`,outputEncoding:a=`srgb`}={}){if(e.length%4!=0)throw Error(`convertEncodedRGBA8 wants 4 bytes per pixel`);let o=ri(t,n,{context:r});if(!o)return e;let s=e.length/4,c=gi(i),l=a===`srgb`?bi:xi,u=new Float32Array(Math.min(Xr,s)*4);for(let t=0;t<s;t+=Xr){let n=Math.min(Xr,s-t),r=n*4===u.length?u:u.subarray(0,n*4);for(let i=0;i<n;i++){let n=(t+i)*4,a=i*4;r[a]=c[e[n]],r[a+1]=c[e[n+1]],r[a+2]=c[e[n+2]],r[a+3]=1}o.applyRGBAF32(r);for(let i=0;i<n;i++){let n=(t+i)*4,a=i*4;e[n]=l(r[a]),e[n+1]=l(r[a+1]),e[n+2]=l(r[a+2])}}return e}var vi=65536,yi=new Uint8Array(vi+1);for(let e=0;e<=vi;e++){let t=e/vi;yi[e]=Math.round(pi(t*t)*255)}function bi(e){return e>0?e>=1?255:yi[Math.sqrt(e)*vi+.5|0]:0}function xi(e){return e>0?e>=1?255:e*255+.5|0:0}function Si(e,t,n=`srgb`){if(!t)return e;let r=gi(n),i=n===`srgb`?bi:xi,[a,o,s,c,l,u,d,f,p]=t;for(let t=0;t<e.length;t+=4){let n=r[e[t]],m=r[e[t+1]],h=r[e[t+2]];e[t]=i(a*n+o*m+s*h),e[t+1]=i(c*n+l*m+u*h),e[t+2]=i(d*n+f*m+p*h)}return e}function Ci(e,t,{context:n=null,tolerance:r=1e-4}={}){if(!Wr())return null;if(e===t)return[1,0,0,0,1,0,0,0,1];let i=ti(e,t,n);if(ei.has(i))return ei.get(i);let a=ri(e,t,{context:n});if(!a)return ei.set(i,[1,0,0,0,1,0,0,0,1]),ei.get(i);let o=e=>{let t=new Float32Array([e[0],e[1],e[2],1]);return a.applyRGBAF32(t),[t[0],t[1],t[2]]},s=[o([1,0,0]),o([0,1,0]),o([0,0,1])],c=[s[0][0],s[1][0],s[2][0],s[0][1],s[1][1],s[2][1],s[0][2],s[1][2],s[2][2]],l=e=>[c[0]*e[0]+c[1]*e[1]+c[2]*e[2],c[3]*e[0]+c[4]*e[1]+c[5]*e[2],c[6]*e[0]+c[7]*e[1]+c[8]*e[2]],u=[[.18,.18,.18],[.5,.25,.75],[2,.1,.4],[.02,.9,.3],[8,4,1],[.001,.002,.004]],d=!0;for(let e of u){let t=o(e),n=l(e),i=Math.max(.001,Math.abs(n[0]),Math.abs(n[1]),Math.abs(n[2]));for(let e=0;e<3;e++)Math.abs(t[e]-n[e])>r*i&&(d=!1);if(!d)break}let f=d?c:null;return ei.set(i,f),f}function wi(e){let t=Gr();if(!t)return!1;let n=t.colorSpaces.find(t=>t.name===e||t.aliases?.includes(e));return n?n.isData:!1}function Ti(e){let t=Gr();return!t||!e?!1:t.colorSpaces.some(t=>t.name===e||t.aliases?.includes(e))}function Ei(e,t,n,r,i){i[0]=Ni(e),i[1]=Ni(t),i[2]=Ni(n)}function Di(e,t,n,r,i){i[0]=Ni(e*r),i[1]=Ni(t*r),i[2]=Ni(n*r)}function Oi(e,t,n,r,i){e*=r,t*=r,n*=r,i[0]=Ni(e/(e+1)),i[1]=Ni(t/(t+1)),i[2]=Ni(n/(n+1))}function ki(e,t,n,r,i){e=Math.max(e*r-.004,0),t=Math.max(t*r-.004,0),n=Math.max(n*r-.004,0);let a=e=>(e*(6.2*e+.5)/(e*(6.2*e+1.7)+.06))**2.2;i[0]=a(e),i[1]=a(t),i[2]=a(n)}function Ai(e,t,n,r,i){e=e*r/.6,t=t*r/.6,n=n*r/.6;let a=.59719*e+.35458*t+.04823*n,o=.076*e+.90834*t+.01566*n,s=.0284*e+.13383*t+.83777*n,c=e=>(e*(e+.0245786)-90537e-9)/(e*(.983729*e+.432951)+.238081);a=c(a),o=c(o),s=c(s),i[0]=Ni(1.60475*a-.53108*o-.07367*s),i[1]=Ni(-.10208*a+1.10813*o-.00605*s),i[2]=Ni(-.00327*a-.07276*o+1.07602*s)}function ji(e,t,n,r,i){e*=r,t*=r,n*=r;let a=.6274*e+.3293*t+.0433*n,o=.0691*e+.9195*t+.0113*n,s=.0164*e+.088*t+.8956*n,c=.856627153315983*a+.0951212405381588*o+.0482516061458583*s,l=.137318972929847*a+.761241990602591*o+.101439036467562*s,u=.11189821299995*a+.0767994186031903*o+.811302368396859*s,d=-12.47393,f=4.026069-d;c=Ni((Math.log2(Math.max(c,1e-10))-d)/f),l=Ni((Math.log2(Math.max(l,1e-10))-d)/f),u=Ni((Math.log2(Math.max(u,1e-10))-d)/f);let p=e=>{let t=e*e,n=t*t;return 15.5*n*t-40.14*n*e+31.96*n-6.868*t*e+.4298*t+.1191*e-.00232};c=p(c),l=p(l),u=p(u);let m=1.1271005818144368*c-.11060664309660323*l-.016493938717834573*u,h=-.1413297634984383*c+1.157823702216272*l-.016493938717834257*u,g=-.14132976349843826*c-.11060664309660294*l+1.2519364065950405*u;m=Math.max(0,m)**2.2,h=Math.max(0,h)**2.2,g=Math.max(0,g)**2.2,i[0]=Ni(1.6605*m-.5876*h-.0728*g),i[1]=Ni(-.1246*m+1.1329*h-.0083*g),i[2]=Ni(-.0182*m-.1006*h+1.1187*g)}function Mi(e,t,n,r,i){let a=.76;e*=r,t*=r,n*=r;let o=Math.min(e,Math.min(t,n)),s=o<.08?o-6.25*o*o:.04;e-=s,t-=s,n-=s;let c=Math.max(e,Math.max(t,n));if(c<a){i[0]=e,i[1]=t,i[2]=n;return}let l=1-a,u=1-l*l/(c+l-a),d=u/c;e*=d,t*=d,n*=d;let f=1-1/(.15*(c-u)+1);i[0]=e+(u-e)*f,i[1]=t+(u-t)*f,i[2]=n+(u-n)*f}var Ni,Pi,Fi,Ii,Li,Ri,zi,Bi=y((()=>{Ni=e=>Math.min(Math.max(e,0),1),Pi=`
|
|
115
|
+
`,[ne,z]),ye={ALWAYS:`always`,PER_CYCLE:`per_cycle`,PER_TILE:`per_tile`,CONDITIONAL:`conditional`},V=class{constructor(e,t={}){this.name=e,this.enabled=t.enabled!==!1,this.executionMode=t.executionMode||ye.ALWAYS,this.context=null,this.eventBus=null}initialize(e,t){this.context=e,this.eventBus=t,this.setupEventListeners()}setupEventListeners(){}shouldExecuteThisFrame(e){if(!this.enabled)return!1;let t=e.getState(`renderMode`)||0,n=e.getState(`tileRenderingComplete`);switch(this.executionMode){case ye.ALWAYS:return!0;case ye.PER_CYCLE:return t===0?!0:n===!0;case ye.PER_TILE:return!0;case ye.CONDITIONAL:return this.shouldExecute(e);default:return this.warn(`Unknown execution mode: ${this.executionMode}`),!0}}shouldExecute(e){return!0}render(e,t){throw Error(`render() must be implemented in ${this.name}`)}reset(){}setSize(e,t){}dispose(){}emit(e,t){this.eventBus&&this.eventBus.emit(e,t)}on(e,t){this.eventBus&&this.eventBus.on(e,t)}once(e,t){this.eventBus&&this.eventBus.once(e,t)}off(e,t){this.eventBus&&this.eventBus.off(e,t)}enable(){this.enabled||(this.enabled=!0,this.emit(`stage:enabled`,{stage:this.name}))}disable(){this.enabled&&(this.enabled=!1,this.emit(`stage:disabled`,{stage:this.name}))}toggle(){this.enabled?this.disable():this.enable()}isEnabled(){return this.enabled}log(...e){console.log(`[${this.name}]`,...e)}warn(...e){console.warn(`[${this.name}]`,...e)}error(...e){console.error(`[${this.name}]`,...e)}},be=class{constructor(e,t,n={}){this.renderer=e,this.material=t,this.interactionModeEnabled=n.enabled===void 0?!0:n.enabled,this.interactionDelay=n.delay||100,this.interactionMode=!1,this.interactionTimeout=null,this.originalValues={},this.appliedValues={},this.wasAccumulationEnabled=!0,this.interactionQualitySettings={enableAccumulation:!1,...n.qualitySettings},this.onEnterCallback=n.onEnter||null,this.onExitCallback=n.onExit||null,this.onResetCallback=n.onReset||null}enterInteractionMode(){this.interactionModeEnabled&&(this.interactionMode?clearTimeout(this.interactionTimeout):(this.interactionMode=!0,this.originalValues={},this.appliedValues={},this.material.uniforms.enableAccumulation&&(this.wasAccumulationEnabled=this.material.uniforms.enableAccumulation.value),Object.keys(this.interactionQualitySettings).forEach(e=>{e===`pixelRatio`?(this.originalValues.dpr=this.renderer.getPixelRatio(),this.renderer.setPixelRatio(this.interactionQualitySettings.pixelRatio)):e===`enableAccumulation`||this.material.uniforms[e]&&(this.originalValues[e]=this.material.uniforms[e].value,this.material.uniforms[e].value=this._resolveQualityValue(e,this.interactionQualitySettings[e]),this.appliedValues[e]=this.material.uniforms[e].value)}),this.material.uniforms.enableAccumulation&&(this.originalValues.enableAccumulation=this.material.uniforms.enableAccumulation.value,this.material.uniforms.enableAccumulation.value=!1),this.material.uniforms.cameraIsMoving&&(this.originalValues.cameraIsMoving=this.material.uniforms.cameraIsMoving.value,this.material.uniforms.cameraIsMoving.value=!0),this.onEnterCallback&&this.onEnterCallback()),this.interactionTimeout=setTimeout(()=>{this.exitInteractionMode()},this.interactionDelay))}exitInteractionMode(){this.interactionMode&&(Object.keys(this.originalValues).forEach(e=>{if(e===`dpr`)this.renderer.setPixelRatio(this.originalValues.dpr);else if(this.material.uniforms[e]){let t=this.appliedValues[e];(t===void 0||this.material.uniforms[e].value===t)&&(this.material.uniforms[e].value=this.originalValues[e])}}),this.interactionMode=!1,this.originalValues={},this.appliedValues={},this.onExitCallback&&this.onExitCallback(),this.onResetCallback&&this.onResetCallback())}updateInteractionMode(e){e&&this.enterInteractionMode()}setInteractionModeEnabled(e){this.interactionModeEnabled=e,!e&&this.interactionMode&&(clearTimeout(this.interactionTimeout),this.exitInteractionMode())}updateQualitySettings(e){Object.assign(this.interactionQualitySettings,e),this.interactionMode&&Object.keys(e).forEach(t=>{t===`pixelRatio`?this.renderer.setPixelRatio(e.pixelRatio):this.material.uniforms[t]&&(this.material.uniforms[t].value=this._resolveQualityValue(t,e[t]),this.appliedValues[t]=this.material.uniforms[t].value)})}_resolveQualityValue(e,t){return typeof t==`function`?t(this.originalValues[e]??this.material.uniforms[e].value):t}setInteractionDelay(e){this.interactionDelay=e}getState(){return{interactionMode:this.interactionMode,interactionModeEnabled:this.interactionModeEnabled,interactionDelay:this.interactionDelay,hasTimeout:this.interactionTimeout!==null,qualitySettings:{...this.interactionQualitySettings},originalValues:{...this.originalValues},wasAccumulationEnabled:this.wasAccumulationEnabled}}forceExitInteractionMode(){this.interactionTimeout&&=(clearTimeout(this.interactionTimeout),null),this.exitInteractionMode()}isInInteractionMode(){return this.interactionMode}setCallbacks(e){e.onEnter&&(this.onEnterCallback=e.onEnter),e.onExit&&(this.onExitCallback=e.onExit),e.onReset&&(this.onResetCallback=e.onReset)}static createQualityPreset(e){let t={"ultra-low":{maxBounceCount:1,pixelRatio:.125,enableAccumulation:!1},low:{maxBounceCount:1,pixelRatio:.25,enableAccumulation:!1},medium:{maxBounceCount:2,pixelRatio:.5,enableAccumulation:!1},high:{maxBounceCount:3,pixelRatio:.75,enableAccumulation:!0}};return t[e]||t.low}dispose(){this.interactionTimeout&&=(clearTimeout(this.interactionTimeout),null),this.interactionMode&&this.forceExitInteractionMode(),this.onEnterCallback=null,this.onExitCallback=null,this.onResetCallback=null}},H,xe=y((()=>{H={RENDER_COMPLETE:`engine:renderComplete`,RENDER_RESET:`engine:renderReset`,FRAME:`engine:frame`,DENOISING_START:`engine:denoisingStart`,DENOISING_END:`engine:denoisingEnd`,UPSCALING_START:`engine:upscalingStart`,UPSCALING_PROGRESS:`engine:upscalingProgress`,UPSCALING_END:`engine:upscalingEnd`,LOADING_UPDATE:`engine:loadingUpdate`,LOADING_RESET:`engine:loadingReset`,STATS_UPDATE:`engine:statsUpdate`,OBJECT_SELECTED:`engine:objectSelected`,OBJECT_DESELECTED:`engine:objectDeselected`,OBJECT_DOUBLE_CLICKED:`engine:objectDoubleClicked`,SELECT_MODE_CHANGED:`engine:selectModeChanged`,OBJECT_TRANSFORM_START:`engine:objectTransformStart`,OBJECT_TRANSFORM_END:`engine:objectTransformEnd`,TRANSFORM_MODE_CHANGED:`engine:transformModeChanged`,AUTO_FOCUS_UPDATED:`engine:autoFocusUpdated`,AUTO_EXPOSURE_UPDATED:`engine:autoExposureUpdated`,AF_POINT_PLACED:`engine:afPointPlaced`,SETTING_CHANGED:`engine:settingChanged`,ANIMATION_STARTED:`engine:animationStarted`,ANIMATION_PAUSED:`engine:animationPaused`,ANIMATION_STOPPED:`engine:animationStopped`,ANIMATION_FINISHED:`engine:animationFinished`,VIDEO_RENDER_PROGRESS:`engine:videoRenderProgress`,VIDEO_RENDER_COMPLETE:`engine:videoRenderComplete`,DISPOSE:`engine:dispose`,DEVICE_LOST:`engine:deviceLost`,ISSUE:`engine:issue`,SCENE_METADATA_APPLIED:`engine:sceneMetadataApplied`}}));xe();var Se=null;function Ce(e){Se=e}var we=()=>Se?.({type:H.LOADING_RESET}),U=e=>{Se?.({type:H.LOADING_UPDATE,...e})},Te=e=>{Se?.({type:H.STATS_UPDATE,...e})};function Ee(e){return e.frameCount||0}function De(e){if(Array.isArray(e))e.forEach(e=>{e.userData&&e.userData.isFallback||(Oe(e),e.dispose())});else{if(e.userData&&e.userData.isFallback)return;Oe(e),e.dispose()}}function Oe(e){e&&[`alphaMap`,`aoMap`,`bumpMap`,`clearcoatMap`,`clearcoatNormalMap`,`clearcoatRoughnessMap`,`displacementMap`,`emissiveMap`,`envMap`,`gradientMap`,`lightMap`,`map`,`metalnessMap`,`normalMap`,`roughnessMap`,`specularMap`,`sheenColorMap`,`sheenRoughnessMap`,`specularIntensityMap`,`specularColorMap`,`thicknessMap`,`transmissionMap`].forEach(t=>{e[t]&&(e[t].dispose(),e[t]=null)})}function ke({material:e,geometry:t,children:n}){if(e&&De(e),t&&t.dispose(),n.length>0)for(let e of n)ke(e)}function Ae(e){if(!e)return;e._canvasTarget&&e._onCanvasTargetResize&&e._canvasTarget.removeEventListener(`resize`,e._onCanvasTargetResize);let t=e.dispose();return e._canvasTarget=null,t}function je(e,t=[]){if(e&&!(t.includes(e.name)||e.isScene)){if(e.isMaterial){De(e);return}for(;e.children.length>0;)for(let t of e.children)je(t);ke(e),e.removeFromParent(),e.clear()}}function Me(e){e?.traverse(e=>{e.geometry?.userData?.__rayzeeOwned&&e.geometry.dispose()})}function Ne(e,t){return t}function Pe(e,t=!1){return t?1:1/(e+1)}function Fe(){let e=0,t=0,n=0,r=0;return{start(){e=performance.now()},end(){t=performance.now();let i=t-e;return r+=i,n++,i},getAverageFrameTime(){return n>0?r/n:0},getFPS(){let e=this.getAverageFrameTime();return e>0?1e3/e:0},reset(){n=0,r=0}}}var Ie=Object.freeze({viewer:Object.freeze({areaLightIntensityScale:.1,environmentRotation:0,toneMapping:6,saturation:1}),physical:Object.freeze({areaLightIntensityScale:1,environmentRotation:0,toneMapping:6,saturation:1})});function Le(e=`viewer`){let t=Ie[e];if(!t)throw Error(`unknown render profile "${e}" — expected one of ${Object.keys(Ie).join(`, `)}`);return t}var W={resolution:512,canvasWidth:512,canvasHeight:512,maxTextureSize:4096,toneMapping:Ie.viewer.toneMapping,exposure:1,saturation:Ie.viewer.saturation,enableEnvironment:!0,showBackground:!0,transparentBackground:!1,environmentIntensity:1,backgroundIntensity:1,backgroundColor:`#000000`,backgroundBlurriness:0,backgroundBlurSamples:8,environmentRotation:Ie.viewer.environmentRotation,groundProjectionEnabled:!1,groundProjectionRadius:100,groundProjectionHeight:15,groundProjectionLevel:0,enableGroundCatcher:!1,groundCatcherHeight:0,globalIlluminationIntensity:1,environmentMode:`hdri`,gradientZenithColor:`#0077BE`,gradientHorizonColor:`#87CEEB`,gradientGroundColor:`#654321`,solidSkyColor:`#87CEEB`,skySunAzimuth:90,skySunElevation:20,skySunIntensity:15,skyRayleighDensity:.9,skyTurbidity:.8,skyMieAnisotropy:.76,skyPreset:`clearMorning`,cameraProjection:`perspective`,panoramaLonRange:[-180,180],panoramaLatRange:[-90,90],panoramaLevelHorizon:!0,enableDOF:!1,fov:55,focusDistance:.8,aperture:5.6,focalLength:50,apertureScale:1,anamorphicRatio:1,autoFocusMode:`auto`,afScreenPoint:{x:.5,y:.5},afSmoothingFactor:.15,enablePathTracer:!0,enableAccumulation:!0,pauseRendering:!1,maxSamples:60,bounces:3,transmissiveBounces:5,maxSubsurfaceSteps:8,maxTransparentBounces:32,useAdaptiveSampling:!0,noiseThreshold:.1,adaptiveMinSamples:8,adaptiveStopFraction:.9,usePixelFreeze:!0,pixelFreezeThreshold:.02,pixelFreezeStability:8,convergenceOverlay:!1,samplingTechnique:2,enableEmissiveTriangleSampling:!1,emissiveBoost:1,fireflyThreshold:3,shadowTerminatorOffset:.1,wavefrontSortMaterials:!0,renderLimitMode:`frames`,renderTimeLimit:30,renderMode:0,enableAlphaShadows:!1,tilesHelper:!0,showLightHelper:!1,directionalLightIntensity:0,directionalLightColor:`#ffffff`,directionalLightPosition:[1,1,1],directionalLightAngle:0,filterStrength:1,edgeAtrousIterations:5,edgePhiLuminance:4,edgePhiNormal:64,edgePhiDepth:.1,enableOIDN:!1,oidnQuality:`fast`,continuousDenoise:!1,continuousDenoiseInterval:8,enableUpscaler:!1,upscalerScale:2,upscalerQuality:`fast`,upscalerHdr:!0,debugMode:0,debugThreshold:100,debugModel:0,enableBloom:!1,bloomStrength:.2,bloomRadius:.15,bloomThreshold:.85,interactionModeEnabled:!0,interactionRenderScale:.5,debugVisScale:100,denoiserStrategy:`none`,enableASVGF:!1,asvgfTemporalAlpha:.1,asvgfAtrousIterations:8,asvgfPhiColor:10,asvgfPhiNormal:128,asvgfPhiDepth:1,asvgfVarianceBoost:1,asvgfMaxAccumFrames:32,asvgfGradientStrength:1,asvgfGradientSigmaScale:2,asvgfGradientNoiseFloor:0,asvgfDebugMode:0,asvgfQualityPreset:`medium`,showAsvgfHeatmap:!1,nrdQualityPreset:`medium`,nrdDebugMode:0,autoExposure:!1,autoExposureKeyValue:.18,autoExposureMinExposure:.1,autoExposureMaxExposure:20,autoExposureAdaptSpeedBright:3,autoExposureAdaptSpeedDark:.5},Re=6e4,ze=3,Be=.1,Ve=.01,He=4096,G=2048;function Ue(e){return G=Math.max(256,Math.min(He,Math.floor(e)||256)),G}var We={low:{temporalAlpha:.1,gradientStrength:.8,gradientSigmaScale:2.5,gradientNoiseFloor:.05,atrousIterations:3,phiColor:1,phiNormal:64,phiDepth:.1,phiLuminance:6,maxAccumFrames:16,varianceBoost:.5},medium:{temporalAlpha:.03,gradientStrength:1,gradientSigmaScale:2.5,gradientNoiseFloor:.05,atrousIterations:4,phiColor:.5,phiNormal:128,phiDepth:.05,phiLuminance:4,maxAccumFrames:64,varianceBoost:1},high:{temporalAlpha:0,gradientStrength:1,gradientSigmaScale:2.5,gradientNoiseFloor:.05,atrousIterations:6,phiColor:.3,phiNormal:256,phiDepth:.02,phiLuminance:2,maxAccumFrames:128,varianceBoost:1.5}},Ge={maxAccumulatedFrameNum:30,maxFastAccumulatedFrameNum:6,maxStabilizedFrameNum:63,historyFixFrameNum:3,historyFixBasePixelStride:14,prepassBlurRadius:30,minBlurRadius:1,maxBlurRadius:30,lobeAngleFraction:.15,roughnessFraction:.15,planeDistanceSensitivity:.02,minHitDistanceWeight:.1,fastHistoryClampingSigmaScale:2,fireflySuppressorMinRelativeScale:2,enableAntiFirefly:!0,antilagLuminanceSigmaScale:2,antilagLuminanceSensitivity:3,disocclusionThreshold:.01,convergenceS:1,convergenceB:.2,convergenceP:.8,lobeVolumePercent:.1,handoverFrames:0},Ke=[`maxAccumulatedFrameNum`,`maxFastAccumulatedFrameNum`,`maxStabilizedFrameNum`,`historyFixFrameNum`,`prepassBlurRadius`,`maxBlurRadius`,`enableAntiFirefly`],qe={low:{maxAccumulatedFrameNum:16,maxFastAccumulatedFrameNum:4,maxStabilizedFrameNum:16,historyFixFrameNum:2,prepassBlurRadius:0,maxBlurRadius:20,enableAntiFirefly:!1},medium:{},high:{maxAccumulatedFrameNum:45,maxFastAccumulatedFrameNum:8,historyFixFrameNum:4,prepassBlurRadius:40,maxBlurRadius:40}},Je={fov:{min:10,max:90,default:W.fov},focusDistance:{min:.3,max:100,default:W.focusDistance},aperture:{options:[1.4,2,2.8,4,5.6,8,11,16],default:W.aperture},focalLength:{min:0,max:200,default:W.focalLength}},Ye={clearMorning:{name:`Clear Morning`,sunAzimuth:90,sunElevation:20,sunIntensity:15,rayleighDensity:.9,turbidity:.8},clearNoon:{name:`Clear Noon`,sunAzimuth:0,sunElevation:75,sunIntensity:20,rayleighDensity:1,turbidity:.3},overcast:{name:`Overcast`,sunAzimuth:0,sunElevation:45,sunIntensity:6,rayleighDensity:.6,turbidity:4},goldenHour:{name:`Golden Hour`,sunAzimuth:270,sunElevation:10,sunIntensity:19,rayleighDensity:.8,turbidity:1.2},sunset:{name:`Sunset`,sunAzimuth:270,sunElevation:2,sunIntensity:18,rayleighDensity:.7,turbidity:2},dusk:{name:`Dusk`,sunAzimuth:270,sunElevation:-8,sunIntensity:8,rayleighDensity:.5,turbidity:1.5}},Xe={portrait:{name:`Portrait`,description:`Shallow depth of field, background blur`,fov:45,focusDistance:1.5,aperture:1.4,focalLength:135,apertureScale:1.5},landscape:{name:`Landscape`,description:`Maximum depth of field, everything in focus`,fov:65,focusDistance:10,aperture:16,focalLength:24,apertureScale:.5},macro:{name:`Macro`,description:`Extreme close-up with thin focus plane`,fov:40,focusDistance:.3,aperture:2,focalLength:100,apertureScale:2},product:{name:`Product`,description:`Sharp detail with subtle background separation`,fov:50,focusDistance:.8,aperture:2.8,focalLength:85,apertureScale:1},architectural:{name:`Architectural`,description:`Wide view with deep focus`,fov:75,focusDistance:5,aperture:11,focalLength:16,apertureScale:.5},cinematic:{name:`Cinematic`,description:`Dramatic depth separation with anamorphic bokeh`,fov:35,focusDistance:3,aperture:1.4,focalLength:200,apertureScale:1.8,anamorphicRatio:1.5}},Ze={MANUAL:`manual`,AUTO:`auto`},Qe={SMOOTHING_FACTOR:.15,RESET_THRESHOLD:.05,FALLBACK_DISTANCE:10,SNAP_THRESHOLD:.5},$e={FLOATS_PER_TRIANGLE:20,POSITION_A_OFFSET:0,POSITION_B_OFFSET:4,POSITION_C_OFFSET:8,NORMAL_A_PACKED_OFFSET:3,NORMAL_B_PACKED_OFFSET:7,NORMAL_C_PACKED_OFFSET:11,UV_AB_OFFSET:12,UV_C_OFFSET:16,MATERIAL_FLAGS_OFFSET:18,MESH_INDEX_OFFSET:19},et=16777215;function tt(e){return!e||!((e.transmission||0)===0&&(!(e.transparent|0)||(e.opacity??1)>=1))?0:e.alphaMode|0?2:1}function K(e,t){return(e&et|(t?.side??0)<<24|tt(t)<<26)>>>0}function nt(e,t,n){let r=Math.sqrt(e*e+t*t+n*n);r>0?(e/=r,t/=r,n/=r):(e=0,t=0,n=1);let i=Math.abs(e)+Math.abs(t)+Math.abs(n),a=e/i,o=t/i;if(n<0){let e=a,t=o;a=(1-Math.abs(t))*(e>=0?1:-1),o=(1-Math.abs(e))*(t>=0?1:-1)}let s=Math.round(Math.min(1,Math.max(-1,a))*32767)&65535;return((Math.round(Math.min(1,Math.max(-1,o))*32767)&65535)<<16|s)>>>0}var q={SLOTS_PER_MATERIAL:33,FLOATS_PER_MATERIAL:132,IOR:0,TRANSMISSION:1,THICKNESS:2,EMISSIVE_INTENSITY:3,ATTENUATION_COLOR:4,ATTENUATION_DISTANCE:7,OPACITY:8,SIDE:9,TRANSPARENT:10,ALPHA_TEST:11,ALPHA_MODE:12,DEPTH_WRITE:13,NORMAL_SCALE:14,COLOR:16,METALNESS:19,EMISSIVE:20,ROUGHNESS:23,ALBEDO_MAP_INDEX:24,NORMAL_MAP_INDEX:25,ROUGHNESS_MAP_INDEX:26,METALNESS_MAP_INDEX:27,EMISSIVE_MAP_INDEX:28,BUMP_MAP_INDEX:29,CLEARCOAT:30,CLEARCOAT_ROUGHNESS:31,DISPERSION:32,VISIBLE:33,SHEEN:34,SHEEN_ROUGHNESS:35,SHEEN_COLOR:36,SPECULAR_INTENSITY:40,SPECULAR_COLOR:41,IRIDESCENCE:44,IRIDESCENCE_IOR:45,IRIDESCENCE_THICKNESS_RANGE:46,BUMP_SCALE:48,DISPLACEMENT_SCALE:49,DISPLACEMENT_MAP_INDEX:50,ALBEDO_TRANSFORM:52,NORMAL_TRANSFORM:60,ROUGHNESS_TRANSFORM:68,METALNESS_TRANSFORM:76,EMISSIVE_TRANSFORM:84,BUMP_TRANSFORM:92,DISPLACEMENT_TRANSFORM:100,SUBSURFACE_COLOR:108,SUBSURFACE:111,SUBSURFACE_RADIUS:112,SUBSURFACE_RADIUS_SCALE:115,SUBSURFACE_ANISOTROPY:116,ANISOTROPY:117,ANISOTROPY_ROTATION:118,ANISOTROPY_MAP_INDEX:119,TRANSMISSION_MAP_INDEX:120,CLEARCOAT_MAP_INDEX:121,CLEARCOAT_ROUGHNESS_MAP_INDEX:122,SHEEN_COLOR_MAP_INDEX:123,SHEEN_ROUGHNESS_MAP_INDEX:124,IRIDESCENCE_MAP_INDEX:125,IRIDESCENCE_THICKNESS_MAP_INDEX:126,SPECULAR_INTENSITY_MAP_INDEX:127,SPECULAR_COLOR_MAP_INDEX:128,SLOT:{IOR_TRANSMISSION:0,ATTENUATION:1,OPACITY_ALPHA:2,ALPHA_MODE:3,COLOR_METALNESS:4,EMISSIVE_ROUGHNESS:5,MAP_INDICES_A:6,MAP_INDICES_B:7,DISPERSION_SHEEN:8,SHEEN_COLOR:9,SPECULAR:10,IRIDESCENCE:11,BUMP_DISPLACEMENT:12,ALBEDO_TRANSFORM_A:13,ALBEDO_TRANSFORM_B:14,NORMAL_TRANSFORM_A:15,NORMAL_TRANSFORM_B:16,ROUGHNESS_TRANSFORM_A:17,ROUGHNESS_TRANSFORM_B:18,METALNESS_TRANSFORM_A:19,METALNESS_TRANSFORM_B:20,EMISSIVE_TRANSFORM_A:21,EMISSIVE_TRANSFORM_B:22,BUMP_TRANSFORM_A:23,BUMP_TRANSFORM_B:24,DISPLACEMENT_TRANSFORM_A:25,DISPLACEMENT_TRANSFORM_B:26,SUBSURFACE_A:27,SUBSURFACE_B:28,SUBSURFACE_C:29,EXT_MAP_INDICES_A:30,EXT_MAP_INDICES_B:31,EXT_MAP_INDICES_C:32}},rt=e=>Number.isFinite(e)&&e>0?e:0,J=it({color:[1,1,1],emissive:[0,0,0],emissiveIntensity:1,roughness:1,metalness:0,ior:1.5,opacity:1,transmission:0,thickness:0,attenuationColor:[1,1,1],attenuationDistance:1/0,dispersion:0,sheen:0,sheenRoughness:1,sheenColor:[0,0,0],specularIntensity:1,specularColor:[1,1,1],clearcoat:0,clearcoatRoughness:0,iridescence:0,iridescenceIOR:1.3,iridescenceThicknessRange:[100,400],normalScale:[1,1],bumpScale:1,displacementScale:1,transparent:0,alphaTest:0,alphaMode:0,side:0,depthWrite:1,subsurface:0,subsurfaceColor:[1,1,1],subsurfaceRadius:[1,.2,.1],subsurfaceRadiusScale:1,subsurfaceAnisotropy:0,anisotropy:0,anisotropyRotation:0});function it(e){for(let t of Object.values(e))typeof t==`object`&&Object.freeze(t);return Object.freeze(e)}var at=1073741824,ot=1073741824,st=1073741823,ct={TRIANGLE_LEAF:1073741824,BLAS_POINTER_LEAF:1073741825,FRONTIER:1073741826};function lt(e){return new Uint32Array(e.buffer,e.byteOffset,e.length)}function ut(e,t){if(e>=1073741824)throw RangeError(`${t} is ${e.toLocaleString()}, at or past the BVH index limit of ${at.toLocaleString()}. Node indices are stored as u32 bit patterns and the leaf tags occupy everything above that.`);return e}var dt={PIXELS_PER_MATERIAL:30,RGBA_COMPONENTS:4,VEC4_PER_TRIANGLE:8,VEC4_PER_BVH_NODE:4,FLOATS_PER_VEC4:4,MIN_TEXTURE_WIDTH:4,MAX_CONCURRENT_WORKERS:Math.min(typeof navigator<`u`&&navigator.hardwareConcurrency||4,6),BUFFER_POOL_SIZE:20,CANVAS_POOL_SIZE:12,CACHE_SIZE_LIMIT:50,MAX_TEXTURE_SIZE:8192,DEFAULT_MAX_TEXTURE_SIZE:4096,MAX_TEXTURES_LIMIT:4*256,MATERIAL_BUCKET_COUNT:4,BUCKET_LAYER_STRIDE:256},ft=64;function pt(e,t){let n=Math.ceil(Math.max(1,e)/ft)*ft;return Math.min(t,Math.max(dt.MIN_TEXTURE_WIDTH,n))}function mt(e){let t=0,n=0,r=0;for(let i of e)t=Math.max(t,i.width),n=Math.max(n,i.height),r+=i.count;return{units:e,width:t,height:n,count:r}}function ht(e,t){return pt(e.width,t)*e.height*e.count*4}function gt(e,t){return e.reduce((e,n)=>e+ht(n,t),0)}function _t(e,t,n){let r=e.slice();for(;r.length>t;){let e=null;for(let t=0;t<r.length;t++)for(let i=t+1;i<r.length;i++){let a=mt(r[t].units.concat(r[i].units)),o=ht(a,n)-ht(r[t],n)-ht(r[i],n);(!e||o<e.delta)&&(e={i:t,j:i,delta:o,fused:a})}r=r.filter((t,n)=>n!==e.i&&n!==e.j).concat([e.fused])}return r}function vt(e,t,n){let r=[];for(let e=t-1;e>=0;e--)r.push(Math.max(dt.MIN_TEXTURE_WIDTH,Math.round(n/2**e)));let i=r.map(()=>[]);for(let t of e){let e=2**Math.ceil(Math.log2(Math.max(t.width,t.height))),n=r.findIndex(t=>e<=t);n<0&&(n=r.length-1),i[n].push(t)}return i.filter(e=>e.length).map(mt)}function yt(e,t){let n=e;for(let e=0;e<8;e++){let e=!1;for(let r of n.flatMap(e=>e.units)){let i=n.findIndex(e=>e.units.includes(r));if(!(i<0))for(let a=0;a<n.length;a++){if(a===i)continue;let o=[];for(let e=0;e<n.length;e++)if(e===i){let t=n[e].units.filter(e=>e!==r);t.length&&o.push(mt(t))}else e===a?o.push(mt(n[e].units.concat([r]))):o.push(n[e]);if(gt(o,t)<gt(n,t)){n=o,e=!0;break}}}if(!e)break}return n}function bt(e,t,n=dt.MATERIAL_BUCKET_COUNT){let r=new Map;for(let{width:n,height:i}of e){let e=Math.min(t,Math.max(1,n||1)),a=Math.min(t,Math.max(1,i||1)),o=`${e}x${a}`,s=r.get(o);s?s.count++:r.set(o,{width:e,height:a,count:1})}let i=[...r.values()],a=i.map(e=>mt([e]));if(a.length>n){let e=vt(i,n,t),r=_t(a,n,t);a=gt(e,t)<gt(r,t)?e:r,a=yt(a,t)}return a.map(e=>({width:pt(e.width,t),height:e.height})).sort((e,t)=>e.width*e.height-t.width*t.height)}function xt(e,t,n){let r=Math.max(1,e||1),i=Math.max(1,t||1);for(let e=0;e<n.length;e++)if(n[e].width>=r&&n[e].height>=i)return e;return Math.max(0,n.length-1)}function St(e,t){return e*dt.BUCKET_LAYER_STRIDE+t}var Ct=[0,0,1,1,0,0,0,1],wt={maxSamples:30,bounces:20,transmissiveBounces:24,maxSubsurfaceSteps:64,renderMode:1,enableAlphaShadows:!0,enableOIDN:!0,oidnQuality:`high`,interactionModeEnabled:!1,useAdaptiveSampling:!0,noiseThreshold:.02,adaptiveStopFraction:.94,usePixelFreeze:!0},Tt={maxSamples:W.maxSamples,bounces:W.bounces,renderMode:W.renderMode,enableAlphaShadows:W.enableAlphaShadows,transmissiveBounces:12,maxSubsurfaceSteps:W.maxSubsurfaceSteps,enableOIDN:!0,oidnQuality:`fast`,interactionModeEnabled:!0,useAdaptiveSampling:!0,noiseThreshold:.1,usePixelFreeze:!0};function Et(e){return{maxSamples:e.maxSamples,maxBounces:e.bounces,transmissiveBounces:e.transmissiveBounces,maxSubsurfaceSteps:e.maxSubsurfaceSteps,enableAlphaShadows:e.enableAlphaShadows??!1,useAdaptiveSampling:e.useAdaptiveSampling??!1,noiseThreshold:e.noiseThreshold??W.noiseThreshold,adaptiveStopFraction:e.adaptiveStopFraction??W.adaptiveStopFraction,adaptiveMinSamples:e.adaptiveMinSamples??W.adaptiveMinSamples,usePixelFreeze:e.usePixelFreeze??!1,pixelFreezeThreshold:e.pixelFreezeThreshold??W.pixelFreezeThreshold,pixelFreezeStability:e.pixelFreezeStability??W.pixelFreezeStability,interactionModeEnabled:e.interactionModeEnabled??W.interactionModeEnabled}}var Dt={MAX_BUFFER_MEMORY:1024*1024*1024,MAX_TEXTURE_MEMORY:2048*1024*1024,CLEANUP_THRESHOLD:.8,CHUNK_SIZE_THRESHOLD:64*1024*1024,STREAM_BATCH_SIZE:4};function Ot(e){try{return globalThis.localStorage?.getItem(e)??null}catch{return null}}function kt(e,t){try{t===null?globalThis.localStorage?.removeItem(e):globalThis.localStorage?.setItem(e,t)}catch{}}function At(){if(Ut!==null)return Ut;let e=globalThis.__RAYZEE_LOG_LEVEL__;return e!==void 0&&e in Lt?(Ut=Lt[e],Ut):(Ut=Lt[Ot(zt)]??Lt[Rt],Ut)}function jt(){if(Wt!==null)return Wt;let e=globalThis.__RAYZEE_LOG_NS__??Ot(Bt);return Wt=e?String(e).split(`,`).map(e=>e.trim()).filter(Boolean):[],Wt}function Mt(e,t){if(t<Lt.debug)return!0;let n=jt();return n.length===0||n.some(t=>e===t||e.startsWith(`${t}:`))}function Nt(e,t,n){if(e>At()||!Mt(t,e))return;let r=e===Lt.error?console.error:e===Lt.warn?console.warn:console.log,i=`[${t}]`;typeof n[0]==`string`?r(`%c${i}%c ${n[0]}`,Vt,Ht,...n.slice(1)):r(`%c${i}`,Vt,...n)}function Pt(e){return{namespace:e,error:(...t)=>Nt(Lt.error,e,t),warn:(...t)=>Nt(Lt.warn,e,t),info:(...t)=>Nt(Lt.info,e,t),debug:(...t)=>Nt(Lt.debug,e,t),isEnabled:e=>Gt.isEnabled(e),summary(t,n=[]){let r=n.filter(Boolean);if(r.length===0||!console.groupCollapsed){Nt(Lt.info,e,[t]),r.forEach(t=>Nt(Lt.debug,e,[t]));return}Lt.info>At()||((At()>=Lt.debug&&console.group?console.group:console.groupCollapsed)(`%c[${e}]%c ${t}`,Vt,Ht),r.forEach(e=>console.log(e)),console.groupEnd())}}}function Ft(e,t,...n){Kt.has(t)||(Kt.add(t),e.warn(...n))}function It(){return Gt.getLevel()}var Lt,Rt,zt,Bt,Vt,Ht,Ut,Wt,Y,Gt,Kt,qt=y((()=>{Lt={silent:0,error:1,warn:2,info:3,debug:4},Rt=`info`,zt=`rayzeeLogLevel`,Bt=`rayzeeLogNamespaces`,Vt=`color:#7c8494`,Ht=`color:inherit`,Ut=null,Wt=null,Y={n:e=>Number(e).toLocaleString(`en-US`),ms:e=>e<10?`${Number(e).toFixed(1)} ms`:`${Math.round(e)} ms`,mb:e=>{let t=e/(1024*1024);return t<10?`${t.toFixed(1)} MB`:`${Math.round(t)} MB`},px:(e,t)=>`${e}×${t}`,count:(e,t,n=`${t}s`)=>`${Y.n(e)} ${Number(e)===1?t:n}`,list:e=>e.filter(Boolean).join(` · `)},Gt={levels:Lt,setLevel(e){return e in Lt?(globalThis.__RAYZEE_LOG_LEVEL__=e,Ut=Lt[e],kt(zt,e===Rt?null:e),e):(console.warn(`[log] unknown level '${e}' — expected one of ${Object.keys(Lt).join(`, `)}`),this.getLevel())},getLevel(){let e=At();return Object.keys(Lt).find(t=>Lt[t]===e)},isEnabled(e){return(Lt[e]??Lt.debug)<=At()},only(...e){let t=e.flat().filter(Boolean);return Wt=t,globalThis.__RAYZEE_LOG_NS__=t.join(`,`),kt(Bt,t.length?t.join(`,`):null),t.length&&this.setLevel(`debug`),t},refresh(){return Ut=null,Wt=null,this.getLevel()}},Kt=new Set}));qt();var Jt=Pt(`gpu`);function Yt(e=r.FloatType,n=r.LinearFilter){let i=new t.StorageTexture(G,G);return i.type=e,i.format=r.RGBAFormat,i.minFilter=n,i.magFilter=n,i}var Xt=()=>Yt(),Zt=class{constructor(e,t){this.writeColor=null,this.writeNormalDepth=null,this.writeAlbedo=null,this.readTarget=null,this.currentTarget=0,this.renderWidth=0,this.renderHeight=0,this._srcRegion=new r.Box2(new r.Vector2(0,0),new r.Vector2(0,0)),e>0&&t>0&&this.create(e,t)}create(e,n){this.dispose(),this.renderWidth=e,this.renderHeight=n,this.writeColor=Xt(),this.writeNormalDepth=Xt(),this.writeAlbedo=Xt(),this.readTarget=new t.RenderTarget(e,n,{type:r.FloatType,format:r.RGBAFormat,minFilter:r.NearestFilter,magFilter:r.NearestFilter,depthBuffer:!1,stencilBuffer:!1,count:3}),this.readTarget.textures[0].name=`gColor`,this.readTarget.textures[1].name=`gNormalDepth`,this.readTarget.textures[2].name=`gAlbedo`,Jt.debug(`storage texture pool ${Y.px(e,n)} — 3 write StorageTextures + 1 MRT RenderTarget`)}ensureSize(e,t){return this.writeColor?this.renderWidth!==e||this.renderHeight!==t?(this.setSize(e,t),!0):!1:(this.create(e,t),!0)}getReadTextures(){return{color:this.readTarget.textures[0],normalDepth:this.readTarget.textures[1],albedo:this.readTarget.textures[2]}}getWriteTextures(){return{color:this.writeColor,normalDepth:this.writeNormalDepth,albedo:this.writeAlbedo}}copyToReadTargets(e,t=!0){this._srcRegion.max.set(this.renderWidth,this.renderHeight),e.copyTextureToTexture(this.writeColor,this.readTarget.textures[0],this._srcRegion),t&&(e.copyTextureToTexture(this.writeNormalDepth,this.readTarget.textures[1],this._srcRegion),e.copyTextureToTexture(this.writeAlbedo,this.readTarget.textures[2],this._srcRegion))}clear(e){if(!this.readTarget||!e)return;let t=e.getRenderTarget();e.setRenderTarget(this.readTarget),e.clear(!0,!1,!1),e.setRenderTarget(t)}swap(){this.currentTarget=1-this.currentTarget}setSize(e,t){if(this.renderWidth=e,this.renderHeight=t,this.readTarget){this.readTarget.setSize(e,t);for(let e of this.readTarget.textures)e.needsUpdate=!0}}dispose(){this.writeColor?.dispose(),this.writeNormalDepth?.dispose(),this.writeAlbedo?.dispose(),this.readTarget?.dispose(),this.writeColor=null,this.writeNormalDepth=null,this.writeAlbedo=null,this.readTarget=null}},Qt={cameraViewMatrix:`ptCameraViewMatrix`,cameraProjectionMatrix:`ptCameraProjectionMatrix`},$t=class{constructor(e=1920,t=1080){this._uniforms=new Map,this._booleans=new Set,this._arrayWarned=new Set,this._lightBuffers={},this._initUniforms(e,t),this._nameAll()}get(e){return this._uniforms.get(e)}set(e,t){let n=this._uniforms.get(e);if(!n){console.warn(`UniformManager: Unknown uniform "${e}"`);return}Array.isArray(t)&&t.length===1&&(this._booleans.has(e)||typeof n.value==`number`)&&(this._arrayWarned.has(e)||(this._arrayWarned.add(e),console.warn(`UniformManager: "${e}" was set to [${t[0]}] but expects a scalar — unwrapping. Fix the caller; a slider handler is probably forwarding its array value unchanged.`)),t=t[0]),this._booleans.has(e)?n.value=+!!t:typeof t==`object`&&t&&typeof n.value?.copy==`function`?n.value.copy(t):n.value=t}has(e){return this._uniforms.has(e)}keys(){return this._uniforms.keys()}getLightBufferNodes(){return this._lightBuffers}updateMany(e){let t=!1;for(let[n,r]of Object.entries(e)){let e=this._uniforms.get(n);e&&e.value!==r&&(e.value=r,t=!0)}return t}_initUniforms(e,t){let i=(e,t,r)=>{let i=(0,n.uniform)(t,r);return this._uniforms.set(e,i),i},a=(e,t)=>(this._booleans.add(e),i(e,+!!t,`int`));i(`frame`,0,`uint`),i(`seedFrame`,0,`uint`),i(`maxBounces`,W.bounces,`int`),i(`maxSamples`,W.maxSamples,`int`),i(`transmissiveBounces`,W.transmissiveBounces,`int`),i(`maxSubsurfaceSteps`,W.maxSubsurfaceSteps,`int`),i(`maxTransparentBounces`,W.maxTransparentBounces,`int`),i(`visMode`,W.debugMode,`int`),i(`debugVisScale`,W.debugVisScale,`float`),a(`useAdaptiveSampling`,W.useAdaptiveSampling),i(`noiseThreshold`,W.noiseThreshold,`float`),i(`adaptiveMinSamples`,W.adaptiveMinSamples,`int`),i(`adaptiveStopFraction`,W.adaptiveStopFraction,`float`),a(`usePixelFreeze`,W.usePixelFreeze),i(`pixelFreezeThreshold`,W.pixelFreezeThreshold,`float`),i(`pixelFreezeStability`,W.pixelFreezeStability,`int`),a(`convergenceOverlay`,W.convergenceOverlay),a(`enableAccumulation`,!0),i(`accumulationAlpha`,0,`float`),a(`cameraIsMoving`,!1),a(`hasPreviousAccumulated`,!1),i(`auxAccumulationAlpha`,1,`float`),a(`hasPreviousAux`,!1),i(`environmentIntensity`,W.environmentIntensity,`float`),i(`backgroundIntensity`,W.backgroundIntensity,`float`),i(`backgroundColor`,new r.Color(0,0,0),`color`),i(`backgroundBlurriness`,W.backgroundBlurriness,`float`),i(`backgroundBlurSamples`,W.backgroundBlurSamples,`int`),a(`showBackground`,W.showBackground),a(`transparentBackground`,W.transparentBackground),a(`enableEnvironment`,W.enableEnvironment),i(`environmentMatrix`,new r.Matrix4,`mat4`),i(`envTotalSum`,0,`float`),i(`envCompensationDelta`,0,`float`),i(`envResolution`,new r.Vector2(1,1),`vec2`),a(`groundProjectionEnabled`,W.groundProjectionEnabled),i(`groundProjectionRadius`,W.groundProjectionRadius,`float`),i(`groundProjectionHeight`,W.groundProjectionHeight,`float`),i(`groundProjectionLevel`,W.groundProjectionLevel,`float`),a(`enableGroundCatcher`,W.enableGroundCatcher),i(`groundCatcherHeight`,W.groundCatcherHeight,`float`),i(`sunDirection`,new r.Vector3(0,1,0),`vec3`),i(`sunAngularSize`,.0087,`float`),a(`hasSun`,!1),i(`globalIlluminationIntensity`,W.globalIlluminationIntensity,`float`),i(`exposure`,W.exposure,`float`),i(`numDirectionalLights`,0,`int`),i(`numAreaLights`,0,`int`),i(`numPointLights`,0,`int`),i(`numSpotLights`,0,`int`),this._lightBuffers={directional:(0,n.uniformArray)(new Float32Array(192),`float`),area:(0,n.uniformArray)(new Float32Array(256),`float`),point:(0,n.uniformArray)(new Float32Array(144),`float`),spot:(0,n.uniformArray)(new Float32Array(320),`float`)},i(`cameraWorldMatrix`,new r.Matrix4,`mat4`),i(`cameraProjectionMatrixInverse`,new r.Matrix4,`mat4`),i(`cameraViewMatrix`,new r.Matrix4,`mat4`),i(`cameraProjectionMatrix`,new r.Matrix4,`mat4`);let o=([e,t])=>new r.Vector2(e,t).multiplyScalar(r.MathUtils.DEG2RAD);i(`cameraProjection`,+(W.cameraProjection===`equirectangular`),`int`),i(`panoLonRange`,o(W.panoramaLonRange),`vec2`),i(`panoLatRange`,o(W.panoramaLatRange),`vec2`),a(`panoLevelHorizon`,W.panoramaLevelHorizon),a(`enableDOF`,W.enableDOF),i(`focusDistance`,W.focusDistance,`float`),i(`focalLength`,W.focalLength,`float`),i(`aperture`,W.aperture,`float`),i(`apertureScale`,1,`float`),i(`anamorphicRatio`,W.anamorphicRatio??1,`float`),i(`sceneScale`,1,`float`),this._uniforms.set(`samplingTechnique`,N),N.value=W.samplingTechnique,i(`fireflyThreshold`,W.fireflyThreshold,`float`),i(`shadowTerminatorOffset`,W.shadowTerminatorOffset,`float`),a(`enableEmissiveTriangleSampling`,W.enableEmissiveTriangleSampling),i(`emissiveBoost`,W.emissiveBoost,`float`),i(`emissiveTriangleCount`,0,`int`),i(`emissiveTotalPower`,0,`float`),i(`lightBVHNodeCount`,0,`int`),i(`emissiveVec4Offset`,0,`int`),i(`reverseMapVec4Offset`,0,`int`),i(`renderMode`,W.renderMode,`int`),a(`enableAlphaShadows`,W.enableAlphaShadows),i(`resolution`,new r.Vector2(e,t),`vec2`)}_nameAll(){for(let[e,t]of this._uniforms)t.name=Qt[e]||e}dispose(){this._disposed||(this._disposed=!0,this._uniforms.clear(),this._booleans.clear(),this._arrayWarned.clear(),this._lightBuffers={})}},en=[1,0,0,0,1,0,0,0],tn=[[`mapMatrix`,q.ALBEDO_TRANSFORM],[`normalMapMatrices`,q.NORMAL_TRANSFORM],[`roughnessMapMatrices`,q.ROUGHNESS_TRANSFORM],[`metalnessMapMatrices`,q.METALNESS_TRANSFORM],[`emissiveMapMatrices`,q.EMISSIVE_TRANSFORM],[`bumpMapMatrices`,q.BUMP_TRANSFORM],[`displacementMapMatrices`,q.DISPLACEMENT_TRANSFORM]];Object.freeze([q.VISIBLE,q.SHEEN_COLOR+3,q.DISPLACEMENT_MAP_INDEX+1,q.SPECULAR_COLOR_MAP_INDEX+1,q.SPECULAR_COLOR_MAP_INDEX+2,q.SPECULAR_COLOR_MAP_INDEX+3]);var nn=Object.freeze(new Set([`metalness`,`roughness`,`transmission`,`opacity`,`clearcoat`,`clearcoatRoughness`,`sheen`,`sheenRoughness`,`specularIntensity`,`iridescence`,`subsurface`,`anisotropy`])),rn=e=>Math.min(Math.max(e,0),1);function an(e,t){let n=typeof e==`boolean`?+e:e;return Number.isFinite(n)?n:t}function on(e){return Number.isInteger(e)?e:-1}function sn(e,t,n,r){let i=n?.r??n?.[0]??n?.x,a=n?.g??n?.[1]??n?.y,o=n?.b??n?.[2]??n?.z;e[t]=an(i,r[0]),e[t+1]=an(a,r[1]),e[t+2]=an(o,r[2])}function cn(e,t,n){let r=(n,r,i)=>{e[t+n]=an(r,i)},i=(n,r,i)=>{e[t+n]=rn(an(r,i))};r(q.IOR,n.ior,J.ior),i(q.TRANSMISSION,n.transmission,J.transmission),r(q.THICKNESS,n.thickness,J.thickness),r(q.EMISSIVE_INTENSITY,n.emissiveIntensity,J.emissiveIntensity),sn(e,t+q.ATTENUATION_COLOR,n.attenuationColor,J.attenuationColor),e[t+q.ATTENUATION_DISTANCE]=rt(n.attenuationDistance??J.attenuationDistance),i(q.OPACITY,n.opacity,J.opacity),r(q.SIDE,n.side,J.side),r(q.TRANSPARENT,n.transparent,J.transparent),r(q.ALPHA_TEST,n.alphaTest,J.alphaTest),r(q.ALPHA_MODE,n.alphaMode,J.alphaMode),r(q.DEPTH_WRITE,n.depthWrite,J.depthWrite);let a=n.normalScale,o=typeof a==`number`?a:void 0;r(q.NORMAL_SCALE,o??a?.x??a?.[0],J.normalScale[0]),r(q.NORMAL_SCALE+1,o??a?.y??a?.[1],J.normalScale[1]),sn(e,t+q.COLOR,n.color,J.color),i(q.METALNESS,n.metalness,J.metalness),sn(e,t+q.EMISSIVE,n.emissive,J.emissive),i(q.ROUGHNESS,n.roughness,J.roughness),e[t+q.ALBEDO_MAP_INDEX]=on(n.map),e[t+q.NORMAL_MAP_INDEX]=on(n.normalMap),e[t+q.ROUGHNESS_MAP_INDEX]=on(n.roughnessMap),e[t+q.METALNESS_MAP_INDEX]=on(n.metalnessMap),e[t+q.EMISSIVE_MAP_INDEX]=on(n.emissiveMap),e[t+q.BUMP_MAP_INDEX]=on(n.bumpMap),i(q.CLEARCOAT,n.clearcoat,J.clearcoat),i(q.CLEARCOAT_ROUGHNESS,n.clearcoatRoughness,J.clearcoatRoughness),r(q.DISPERSION,n.dispersion,J.dispersion),i(q.SHEEN,n.sheen,J.sheen),i(q.SHEEN_ROUGHNESS,n.sheenRoughness,J.sheenRoughness),sn(e,t+q.SHEEN_COLOR,n.sheenColor,J.sheenColor),i(q.SPECULAR_INTENSITY,n.specularIntensity,J.specularIntensity),sn(e,t+q.SPECULAR_COLOR,n.specularColor,J.specularColor),i(q.IRIDESCENCE,n.iridescence,J.iridescence),r(q.IRIDESCENCE_IOR,n.iridescenceIOR,J.iridescenceIOR),r(q.IRIDESCENCE_THICKNESS_RANGE,n.iridescenceThicknessRange?.[0],J.iridescenceThicknessRange[0]),r(q.IRIDESCENCE_THICKNESS_RANGE+1,n.iridescenceThicknessRange?.[1],J.iridescenceThicknessRange[1]),r(q.BUMP_SCALE,n.bumpScale,J.bumpScale),r(q.DISPLACEMENT_SCALE,n.displacementScale,J.displacementScale),e[t+q.DISPLACEMENT_MAP_INDEX]=on(n.displacementMap);for(let[r,i]of tn){let a=n[r];for(let n=0;n<8;n++)e[t+i+n]=an(a?.[n],en[n])}sn(e,t+q.SUBSURFACE_COLOR,n.subsurfaceColor,J.subsurfaceColor),i(q.SUBSURFACE,n.subsurface,J.subsurface),sn(e,t+q.SUBSURFACE_RADIUS,n.subsurfaceRadius,J.subsurfaceRadius),r(q.SUBSURFACE_RADIUS_SCALE,n.subsurfaceRadiusScale,J.subsurfaceRadiusScale),r(q.SUBSURFACE_ANISOTROPY,n.subsurfaceAnisotropy,J.subsurfaceAnisotropy),i(q.ANISOTROPY,n.anisotropy,J.anisotropy),r(q.ANISOTROPY_ROTATION,n.anisotropyRotation,J.anisotropyRotation),e[t+q.ANISOTROPY_MAP_INDEX]=on(n.anisotropyMap),e[t+q.TRANSMISSION_MAP_INDEX]=on(n.transmissionMap),e[t+q.CLEARCOAT_MAP_INDEX]=on(n.clearcoatMap),e[t+q.CLEARCOAT_ROUGHNESS_MAP_INDEX]=on(n.clearcoatRoughnessMap),e[t+q.SHEEN_COLOR_MAP_INDEX]=on(n.sheenColorMap),e[t+q.SHEEN_ROUGHNESS_MAP_INDEX]=on(n.sheenRoughnessMap),e[t+q.IRIDESCENCE_MAP_INDEX]=on(n.iridescenceMap),e[t+q.IRIDESCENCE_THICKNESS_MAP_INDEX]=on(n.iridescenceThicknessMap),e[t+q.SPECULAR_INTENSITY_MAP_INDEX]=on(n.specularIntensityMap),e[t+q.SPECULAR_COLOR_MAP_INDEX]=on(n.specularColorMap),e[t+q.VISIBLE]=1,e[t+q.SHEEN_COLOR+3]=1,e[t+q.DISPLACEMENT_MAP_INDEX+1]=0,e[t+q.SPECULAR_COLOR_MAP_INDEX+1]=0,e[t+q.SPECULAR_COLOR_MAP_INDEX+2]=0,e[t+q.SPECULAR_COLOR_MAP_INDEX+3]=0}var ln=Object.freeze({ADAPTER_SOFTWARE:`adapter.software`,ASSET_UNREACHABLE:`asset.unreachable`,ASSET_AMBIGUOUS_ENTRY:`asset.ambiguous_entry`,ASSET_ARCHIVE_TOO_LARGE:`asset.archive_too_large`,ASSET_ENTRY_TOO_LARGE:`asset.entry_too_large`,TEXTURE_BUILD_FAILED:`texture.build_failed`,TEXTURE_PROCESSING_FALLBACK:`texture.processing_fallback`,TEXTURE_LIMIT_EXCEEDED:`texture.limit_exceeded`,ENVIRONMENT_LOAD_FAILED:`environment.load_failed`,SETTING_UNKNOWN_KEY:`setting.unknown_key`,RENDER_SIZE_DECLINED:`render.size_declined`,STAGE_RENDER_FAILED:`stage.render_failed`,RENDER_RESERVE_CAPPED:`render.reserve_capped`,SCENE_MEMORY_BUDGET:`scene.memory_budget`,EMISSIVE_INSTANCES_COLLAPSED:`emissive.instances_collapsed`,REFIT_SHARED_GEOMETRY:`refit.shared_geometry`,VIEW_TRANSFORM_DISPLAY_MISMATCH:`viewTransform.display_mismatch`,VIEW_TRANSFORM_BAKE_FAILED:`viewTransform.bake_failed`,COLOR_CONFIG_LOAD_FAILED:`color.config_load_failed`}),un=Object.freeze({ERROR:`error`,WARNING:`warning`}),dn=class extends Error{constructor(e){super(`[${e.code}] ${e.message}`),this.name=`EngineIssueError`,this.code=e.code,this.detail=e.detail}},fn=class{constructor({strict:e=!1,onIssue:t=null}={}){this.strict=e===!0,this._onIssue=t,this._entries=[]}record(e,t,n={},r=un.ERROR){let i=Object.freeze({code:e,message:t,detail:n,severity:r,at:Date.now()});if(this._entries.push(i),this._onIssue?.(i),this.strict&&r===un.ERROR)throw new dn(i);return i}warn(e,t,n){return this.record(e,t,n,un.WARNING)}get list(){return this._entries.slice()}get errors(){return this._entries.filter(e=>e.severity===un.ERROR)}clear(){this._entries.length=0}detach(){this._onIssue=null,this.strict=!1}},pn=64*1024*1024,mn=typeof SharedArrayBuffer<`u`,hn=null;function gn(e){hn=e}function _n(e,t,n){let r=n?new e(new SharedArrayBuffer(t*e.BYTES_PER_ELEMENT)):new e(t);return hn&&r.byteLength>0&&hn(r.byteLength,n),r}var vn=class e{constructor(e,t,n,r=pn,i=!1){let a=t*n.BYTES_PER_ELEMENT,o=Math.max(1,Math.floor(r/a));this.recordCount=e,this.lanesPerRecord=t,this.LaneType=n,this.recordsPerChunk=e<=o?Math.max(e,1):o,this.shared=i,this.chunks=[];let s=e;for(;s>0;){let e=Math.min(s,this.recordsPerChunk);this.chunks.push(_n(n,e*t,i)),s-=e}this.chunks.length===0&&this.chunks.push(_n(n,0,i))}static adopt(t,n,r,i){let a=Object.create(e.prototype);return a.recordCount=n,a.lanesPerRecord=r,a.LaneType=t[0]?.constructor??null,a.recordsPerChunk=i,a.chunks=t,a.shared=typeof SharedArrayBuffer<`u`&&t[0]?.buffer instanceof SharedArrayBuffer,a}static lazy(t,n,r,i=pn,a=!1){let o=Math.max(1,Math.floor(i/(n*r.BYTES_PER_ELEMENT))),s=Object.create(e.prototype);return s.recordCount=t,s.lanesPerRecord=n,s.LaneType=r,s.recordsPerChunk=t<=o?Math.max(t,1):o,s.shared=a,s.chunks=Array(Math.max(1,Math.ceil(t/s.recordsPerChunk))),s._views=[],s}_materialize(e){if(this._owner)return this._owner._materialize(e),this.chunks[e];let t=e*this.recordsPerChunk,n=Math.min(this.recordsPerChunk,this.recordCount-t)*this.lanesPerRecord,r=this.chunks[e]=_n(this.LaneType,n,this.shared);for(let t of this._views)t.chunks[e]=new t.LaneType(r.buffer,r.byteOffset,r.byteLength/t.LaneType.BYTES_PER_ELEMENT);return r}materializeAll(){for(let e=0;e<this.chunks.length;e++)this.chunks[e]||this._materialize(e);return this}get chunkCount(){return this.chunks.length}get single(){return this.chunks.length===1?this.chunks[0]:null}get byteLength(){let e=0;for(let t of this.chunks)t&&(e+=t.byteLength);return e}chunkFor(e){let t=e/this.recordsPerChunk|0;return this.chunks[t]??this._materialize(t)}baseOf(e){return e%this.recordsPerChunk*this.lanesPerRecord}isContiguous(e,t){return t<=0?!0:(e/this.recordsPerChunk|0)==((e+t-1)/this.recordsPerChunk|0)}slice(e,t){let n=this.baseOf(e),r=t*this.lanesPerRecord;if(this.isContiguous(e,t))return this.chunkFor(e).subarray(n,n+r);let i=new this.LaneType(r);return this.readRecords(e,t,i),i}readRecords(e,t,n){let r=0;for(;r<t;){let i=e+r,a=this.chunkFor(i),o=this.baseOf(i),s=this.recordsPerChunk-i%this.recordsPerChunk,c=Math.min(s,t-r);n.set(a.subarray(o,o+c*this.lanesPerRecord),r*this.lanesPerRecord),r+=c}return n}setRecords(e,t){let n=t.length/this.lanesPerRecord,r=0;for(;r<n;){let i=e+r,a=this.chunkFor(i),o=this.baseOf(i),s=this.recordsPerChunk-i%this.recordsPerChunk,c=Math.min(s,n-r);a.set(t.subarray(r*this.lanesPerRecord,(r+c)*this.lanesPerRecord),o),r+=c}}copyOf(e,t){return this.readRecords(e,t,new this.LaneType(t*this.lanesPerRecord))}trimTo(t){let n=Math.max(1,Math.ceil(t/this.recordsPerChunk)),r=this.chunks.slice(0,n),i=(t-(n-1)*this.recordsPerChunk)*this.lanesPerRecord,a=r[n-1];return a.length>i&&(r[n-1]=a.subarray(0,Math.max(0,i))),e.adopt(r,t,this.lanesPerRecord,this.recordsPerChunk)}viewAs(t){let n=e=>new t(e.buffer,e.byteOffset,e.byteLength/t.BYTES_PER_ELEMENT),r=e.adopt(this.chunks.map(e=>e?n(e):void 0),this.recordCount,this.lanesPerRecord,this.recordsPerChunk);return r.LaneType=t,this._views&&(r._owner=this,this._views.push(r)),r}};qt();var yn=Pt(`geometry`),bn=dt.MAX_TEXTURES_LIMIT,xn=new Set([`color`,`emissive`,`attenuationColor`,`sheenColor`,`specularColor`,`subsurfaceColor`]),Sn=Object.freeze({MATERIAL:`material`,MAPPED:`mapped`,DEFAULT:`default`,HOST:`host`}),Cn=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];function wn(e){for(let t=0;t<16;t++)if(e[t]!==Cn[t])return!1;return!0}function Tn(e){return{map:e.map,normalMap:e.normalMap,bumpMap:e.bumpMap,roughnessMap:e.roughnessMap,metalnessMap:e.metalnessMap,emissiveMap:e.emissiveMap??(e.isMeshBasicMaterial?e.map:void 0),displacementMap:e.displacementMap,anisotropyMap:e.anisotropyMap,clearcoatMap:e.clearcoatMap,clearcoatRoughnessMap:e.clearcoatRoughnessMap,transmissionMap:e.transmissionMap,sheenColorMap:e.sheenColorMap,sheenRoughnessMap:e.sheenRoughnessMap,specularIntensityMap:e.specularIntensityMap,specularColorMap:e.specularColorMap,iridescenceMap:e.iridescenceMap,iridescenceThicknessMap:e.iridescenceThicknessMap}}function En(e){if(e.userData?.gltfExtensions?.KHR_materials_unlit?.alphaMode){let t=e.userData.gltfExtensions.KHR_materials_unlit.alphaMode;return t===`BLEND`?2:+(t===`MASK`)}return e.alphaTest>0?1:e.transparent&&e.opacity<1||e.map&&e.map.format===r.RGBAFormat&&e.transparent?2:0}function Dn(e){let t=0,n=new Set,r=e=>{let i=e.isMesh&&e.material?e.geometry:null;if(i&&!n.has(i.uuid)){n.add(i.uuid);for(let e in i.attributes)t+=i.attributes[e].array?.byteLength??0;t+=i.index?.array?.byteLength??0}if(e.children)for(let t of e.children)r(t)};return r(e),t}function On(e,t){let n=e.x,r=e.y,i=e.z;e.x=t[0]*n+t[4]*r+t[8]*i+t[12],e.y=t[1]*n+t[5]*r+t[9]*i+t[13],e.z=t[2]*n+t[6]*r+t[10]*i+t[14]}function kn(e,t){let n=e.x,r=e.y,i=e.z;e.x=t[0]*n+t[3]*r+t[6]*i,e.y=t[1]*n+t[4]*r+t[7]*i,e.z=t[2]*n+t[5]*r+t[8]*i}var An=1<<21;function jn(e){return!!(e.isSkinnedMesh||Object.keys(e.geometry?.morphAttributes??{}).length)}function Mn(e){return e[0]*(e[5]*e[10]-e[9]*e[6])-e[4]*(e[1]*e[10]-e[9]*e[2])+e[8]*(e[1]*e[6]-e[5]*e[2])}var Nn=class{constructor({issues:e=null}={}){this._issues=e,this._droppedTextures=0,this._vectorPool={vec3:Array(9).fill().map(()=>new r.Vector3),vec2:[,,,,,,].fill().map(()=>new r.Vector2)},this._geometryRanges=new Map,this.expandedTriangleCount=0,this._allocatePlacements(0),this._matrixPool={mat3:new r.Matrix3,mat4:new r.Matrix4},this.resetArrays(),this.triangleCount=0,this.currentTriangleIndex=0}_getVec3(e=0){return this._vectorPool.vec3[e%this._vectorPool.vec3.length]}_getVec2(e=0){return this._vectorPool.vec2[e%this._vectorPool.vec2.length]}extract(e){this.resetArrays();let t=this._countTriangles(e);return this._triangleCapacity=Math.max(1024,t),this._allocateTriangles(this._triangleCapacity),this.currentTriangleIndex=0,this._allocatePlacements(this._countPlacements(e)),this._geometryUses=this._countGeometryUses(e),this.bakeInverse=new Map,this.traverseObject(e),this._shareInstanceMatrices(),this._compressAttributes(e),this.logStats(),this.getExtractedData()}surveyScene(e){let t=0,n=e=>{if(e.isMesh&&e.geometry&&e.material&&t++,e.children)for(let t of e.children)n(t)};return n(e),{triangles:this._countTriangles(e),placements:this._countPlacements(e),meshes:t,geometryBytes:Dn(e)}}_countGeometryUses(e){let t=new Map;return e.traverse(e=>{if(!e.isMesh||!e.geometry||!e.material)return;let n=`${e.geometry.uuid}|${e.material.uuid}`;t.set(n,(t.get(n)??0)+1)}),t}_countPlacements(e){let t=0;if(e.isMesh&&e.geometry&&e.material&&(t+=e.isInstancedMesh&&e.instanceMatrix?e.count??e.instanceMatrix.array.length/16:1),e.children)for(let n of e.children)t+=this._countPlacements(n);return t}_allocatePlacements(e){this.instanceCount=0,this.instanceCapacity=e,this.instanceSource=new Int32Array(e),this.instanceMatrices=new Float32Array(e*16),this._shareable=[],this._compressed=new Set}_compressAttributes(e){let t=this._compressed,n=(e,t)=>{if(!e.userData?.__rayzeeExternal){t(e);for(let r of e.children)n(r,t)}};n(e,e=>{let n=e.geometry;if(!(!e.isMesh||!n||t.has(n.uuid))){t.add(n.uuid);for(let e of[`normal`,`tangent`,`color`]){let t=n.getAttribute(e);if(!t||t.normalized||!(t.array instanceof Float32Array)||n.morphAttributes?.[e]?.length)continue;let i=t.array,a=!0;for(let e=0;e<i.length;e++){let t=i[e];if(!(t>=-1.0001&&t<=1.0001)){a=!1;break}}if(!a)continue;let o=new Int16Array(i.length);for(let e=0;e<i.length;e++)o[e]=Math.round(Math.max(-1,Math.min(1,i[e]))*32767);n.setAttribute(e,new r.BufferAttribute(o,t.itemSize,!0))}}})}_shareInstanceMatrices(){for(let{mesh:e,start:t,count:n}of this._shareable){let r=e.instanceMatrix;!r||r.array.length!==n*16||(r.array=this.instanceMatrices.subarray(t*16,(t+n)*16))}this._shareable=[]}_countTriangles(e){let t=0;if(e.isMesh&&e.geometry&&e.material){let n=e.geometry.index,r=e.geometry.attributes.position;n?t+=Math.ceil(n.count/3):r&&(t+=Math.ceil(r.count/3))}if(e.children)for(let n of e.children)t+=this._countTriangles(n);return t}_ensureCapacity(e){if(e<=this._triangleCapacity)return;let t=this.triangles,n=this.currentTriangleIndex;this._allocateTriangles(e);for(let e=0;e<n;e++)this.triangles.chunkFor(e).set(t.chunkFor(e).subarray(t.baseOf(e),t.baseOf(e)+t.lanesPerRecord),this.triangles.baseOf(e));this._triangleCapacity=e}_allocateTriangles(e){this.triangles=new vn(e,$e.FLOATS_PER_TRIANGLE,Uint32Array,void 0,mn),this.triangleFloatChunks=this.triangles.viewAs(Float32Array),this.triangleData=this.triangles.single,this.triangleFloats=this.triangleFloatChunks.single}traverseObject(e){if(e.isMesh?this.processMesh(e):e.isDirectionalLight?this.directionalLights.push(e):e.isCamera&&this.cameras.push(e),e.children)for(let t of e.children)this.traverseObject(t)}processMesh(e){if(!e.geometry||!e.material){console.warn(`Skipping mesh with missing geometry or material:`,e);return}let t=this.processMaterial(e.material);e.userData.materialIndex=t;let n=this.meshes.length;this.meshes.push(e),e.userData.meshIndex=n;let r=`${e.geometry.uuid}|${t}`,i=jn(e),a=!this._emissiveMaterial(t)&&!i,o=a?this._geometryRanges.get(r):null;if(o){let t={start:o.start,count:o.count,expandedStart:this.expandedTriangleCount,sharedFrom:o.meshIndex};this.expandedTriangleCount+=o.count,this.meshTriangleRanges.push(t),this._recordPlacements(e,n);return}let s=this.currentTriangleIndex,c=e.isInstancedMesh&&!i&&this._emissiveMaterial(t)&&this._canExpand(e),l=c||!e.isInstancedMesh&&!i&&(this._geometryUses.get(`${e.geometry.uuid}|${e.material?.uuid}`)===1||this._emissiveMaterial(t));this.extractGeometry(e,t,n,l,c);let u={start:s,count:this.currentTriangleIndex-s,expandedStart:this.expandedTriangleCount};this.expandedTriangleCount+=u.count,this.meshTriangleRanges.push(u),u.count>0&&!l&&a&&this._geometryRanges.set(r,{...u,meshIndex:n}),this._recordPlacements(e,n,l,c)}_recordPlacements(e,t,n=!1,r=!1){let i=e.matrixWorld.elements,a=this.instanceMatrices,o=this.instanceSource;if(!e.isInstancedMesh||!e.instanceMatrix||r){let r=this._nextPlacement();if(o[r]=t,n){for(let e=0;e<16;e++)a[r*16+e]=+(e%5==0);this.bakeInverse.set(t,Float32Array.from(this._matrixPool.mat4.copy(e.matrixWorld).invert().elements))}else for(let e=0;e<16;e++)a[r*16+e]=i[e];return}let s=e.instanceMatrix.array,c=e.count??s.length/16,l=wn(i);l&&s.length===c*16&&this._shareable.push({mesh:e,start:this.instanceCount,count:c});for(let e=0;e<c;e++){let n=e*16,r=this._nextPlacement(),c=r*16;if(o[r]=t,l){for(let e=0;e<16;e++)a[c+e]=s[n+e];continue}for(let e=0;e<4;e++)for(let t=0;t<4;t++)a[c+e*4+t]=i[t]*s[n+e*4]+i[4+t]*s[n+e*4+1]+i[8+t]*s[n+e*4+2]+i[12+t]*s[n+e*4+3]}}_nextPlacement(){if(this.instanceCount>=this.instanceCapacity){let e=Math.max(16,this.instanceCapacity*2),t=new Int32Array(e),n=new Float32Array(e*16);t.set(this.instanceSource),n.set(this.instanceMatrices),this.instanceSource=t,this.instanceMatrices=n,this.instanceCapacity=e}return this.instanceCount++}_canExpand(e){let t=e.geometry,n=(t.index?t.index.count:t.attributes.position.count)/3,r=e.count??(e.instanceMatrix?.array.length??0)/16;return n*r<=An?!0:(this._issues?.record(ln.EMISSIVE_INSTANCES_COLLAPSED,`"${e.name||`instanced mesh`}" would need ${Math.round(n*r).toLocaleString()} triangles to light every instance; lighting the first one only`,{instances:r,trianglesPerInstance:n,limit:An}),!1)}_emissiveMaterial(e){let t=this.materials[e];if(!t||!(t.emissiveIntensity>0))return!1;let n=t.emissive;return!!n&&(n.r>0||n.g>0||n.b>0)}processMaterial(e){let t=this._materialUuidMap.get(e.uuid)??-1;if(t===-1){e.depthWrite===!1&&(e.depthWrite=!0,Ft(yn,`depthWrite`,`material had depthWrite disabled — enabled for rastered rendering`));let n=this.createMaterialObject(e);this.materials.push(n),t=this.materials.length-1,this._materialUuidMap.set(e.uuid,t)}return t}getMaterialType(e){return e.isMeshPhysicalMaterial?`physical`:e.isMeshStandardMaterial?`standard`:e.isMeshPhongMaterial?`phong`:e.isMeshLambertMaterial?`lambert`:e.isMeshBasicMaterial?`basic`:e.isMeshToonMaterial?`toon`:`unknown`}getPhysicalDefaults(){let e={};for(let[t,n]of Object.entries(J))e[t]=xn.has(t)?new r.Color().fromArray(n):Array.isArray(n)?[...n]:n;return e.normalScale={x:J.normalScale[0],y:J.normalScale[1]},e}mapLegacyMaterialToPhysical(e,t){let n={};switch(t){case`basic`:n.emissive=e.color.clone(),n.emissiveIntensity=1,n.color=new r.Color(0),n.roughness=1,n.metalness=0,n.specularIntensity=0;break;case`lambert`:n.roughness=1,n.metalness=0,n.specularIntensity=0;break;case`phong`:{let t=e.shininess||30;n.roughness=Math.sqrt(2/(t+2)),n.metalness=0}if(e.specular){let t=e.specular,i=t.r*.299+t.g*.587+t.b*.114,a=Math.max(t.r,t.g,t.b);n.specularIntensity=Math.min(i*2,1),n.specularColor=a>0?t.clone().multiplyScalar(1/a):new r.Color(1,1,1)}break;case`toon`:n.roughness=.9,n.metalness=0;break;case`standard`:case`physical`:break}return n}createMaterialObject(e){let t=this.getPhysicalDefaults(),n=this.getMaterialType(e),r=this.mapLegacyMaterialToPhysical(e,n),i=Tn(e),a={},o=n=>r[n]===void 0?e[n]!==void 0&&e[n]!==null?(a[n]=Sn.MATERIAL,e[n]):(a[n]=Sn.DEFAULT,t[n]):(a[n]=Sn.MAPPED,r[n]);for(let e of[`transparent`,`alphaMode`,`side`,`depthWrite`])a[e]=Sn.MATERIAL;return{uuid:e.uuid,color:o(`color`),emissive:o(`emissive`),emissiveIntensity:o(`emissiveIntensity`),roughness:Math.max(.02,o(`roughness`)),metalness:o(`metalness`),ior:o(`ior`),opacity:o(`opacity`),transmission:o(`transmission`),thickness:o(`thickness`),attenuationColor:o(`attenuationColor`),attenuationDistance:o(`attenuationDistance`),dispersion:o(`dispersion`),sheen:o(`sheen`),sheenRoughness:o(`sheenRoughness`),sheenColor:o(`sheenColor`),clearcoat:o(`clearcoat`),clearcoatRoughness:o(`clearcoatRoughness`),iridescence:o(`iridescence`),iridescenceIOR:o(`iridescenceIOR`),iridescenceThicknessRange:o(`iridescenceThicknessRange`),subsurface:o(`subsurface`),subsurfaceColor:o(`subsurfaceColor`),subsurfaceRadius:o(`subsurfaceRadius`),subsurfaceRadiusScale:o(`subsurfaceRadiusScale`),subsurfaceAnisotropy:o(`subsurfaceAnisotropy`),anisotropy:o(`anisotropy`),anisotropyRotation:o(`anisotropyRotation`),specularIntensity:o(`specularIntensity`),specularColor:o(`specularColor`),normalScale:o(`normalScale`),bumpScale:o(`bumpScale`),displacementScale:o(`displacementScale`),transparent:+!!e.transparent,alphaTest:o(`alphaTest`),alphaMode:En(e),side:this.getMaterialSide(e),depthWrite:e.depthWrite??!0?1:0,map:this.processTexture(i.map,this.maps),normalMap:this.processTexture(i.normalMap,this.normalMaps),bumpMap:this.processTexture(i.bumpMap,this.bumpMaps),roughnessMap:this.processTexture(i.roughnessMap,this.roughnessMaps),metalnessMap:this.processTexture(i.metalnessMap,this.metalnessMaps),emissiveMap:this.processTexture(i.emissiveMap,this.emissiveMaps),displacementMap:this.processTexture(i.displacementMap,this.displacementMaps),anisotropyMap:this.processTexture(i.anisotropyMap,this.anisotropyMaps),clearcoatMap:this.processTexture(i.clearcoatMap,this.clearcoatMaps),clearcoatRoughnessMap:this.processTexture(i.clearcoatRoughnessMap,this.clearcoatRoughnessMaps),transmissionMap:this.processTexture(i.transmissionMap,this.transmissionMaps),thicknessMap:this.processTexture(e.thicknessMap,[]),sheenColorMap:this.processTexture(i.sheenColorMap,this.sheenColorMaps),sheenRoughnessMap:this.processTexture(i.sheenRoughnessMap,this.sheenRoughnessMaps),specularIntensityMap:this.processTexture(i.specularIntensityMap,this.specularIntensityMaps),specularColorMap:this.processTexture(i.specularColorMap,this.specularColorMaps),iridescenceMap:this.processTexture(i.iridescenceMap,this.iridescenceMaps),iridescenceThicknessMap:this.processTexture(i.iridescenceThicknessMap,this.iridescenceThicknessMaps),mapMatrix:this.getTextureMatrix(i.map),normalMapMatrices:this.getTextureMatrix(i.normalMap),bumpMapMatrices:this.getTextureMatrix(i.bumpMap),roughnessMapMatrices:this.getTextureMatrix(i.roughnessMap),metalnessMapMatrices:this.getTextureMatrix(i.metalnessMap),emissiveMapMatrices:this.getTextureMatrix(i.emissiveMap),displacementMapMatrices:this.getTextureMatrix(i.displacementMap),sources:a,originalType:n}}getTextureMatrix(e){return e?(e.matrixAutoUpdate&&e.updateMatrix(),e.matrix.elements):new r.Matrix3().elements}getMaterialSide(e){if(e.transmission>0)return 2;switch(e.side){case r.FrontSide:return 0;case r.BackSide:return 1;case r.DoubleSide:return 2;default:return 0}}processTexture(e,t){if(!e)return-1;let n=this._textureIndexCache.get(t);n||(n=new Map,this._textureIndexCache.set(t,n));let r=e.source.uuid,i=n.get(r);if(i!==void 0)return i;if(t.length<bn){t.push(e);let i=t.length-1;return n.set(r,i),i}return this._droppedTextures++,this._droppedTextures===1&&this._issues?.record(ln.TEXTURE_LIMIT_EXCEEDED,`scene needs more than ${bn} distinct textures for one map type; the rest render untextured`,{limit:bn,firstDropped:e.name||e.source?.uuid}),-1}extractGeometry(e,t,n,i=!1,a=!1){e.updateMatrix(),e.updateMatrixWorld();let o=e.geometry;o.attributes.normal||o.computeVertexNormals();let s=o.attributes.position,c=o.attributes.normal,l=o.attributes.uv,u=o.index?o.index.array:null,d=u?u.length/3:s.count/3;if(a){let i=e.count??e.instanceMatrix.array.length/16,a=this._matrixPool.mat4,o=new r.Matrix4;for(let f=0;f<i;f++){a.fromArray(e.instanceMatrix.array,f*16),o.multiplyMatrices(e.matrixWorld,a);let i=new r.Matrix3().getNormalMatrix(o);this.extractTrianglesInBatch(s,c,l,u,d,t,n,o,i,Mn(o.elements)<0)}return}let f=i?this._matrixPool.mat4.copy(e.matrixWorld):null,p=i?this._matrixPool.mat3.getNormalMatrix(e.matrixWorld):null,m=i&&Mn(f.elements)<0;this.extractTrianglesInBatch(s,c,l,u,d,t,n,f,p,m)}extractTrianglesInBatch(e,t,n,r,i,a,o,s=null,c=null,l=!1){for(;this.materialTriangleCounts.length<=a;)this.materialTriangleCounts.push(0);this.materialTriangleCounts[a]+=i;let u=this._getVec3(0),d=this._getVec3(1),f=this._getVec3(2),p=this._getVec3(3),m=this._getVec3(4),h=this._getVec3(5),g=this._getVec2(0),_=this._getVec2(1),v=this._getVec2(2);this._ensureCapacity(this.currentTriangleIndex+i);let y=s?.elements,b=c?.elements;for(let c=0;c<i;c++){let i=c*3,x=r?r[i+0]:i+0,S=l?2:1,C=l?1:2,w=r?r[i+S]:i+S,T=r?r[i+C]:i+C;this.getVertex(e,x,u),this.getVertex(e,w,d),this.getVertex(e,T,f),this.getVertex(t,x,p),this.getVertex(t,w,m),this.getVertex(t,T,h),n?(this.getVertex(n,x,g),this.getVertex(n,w,_),this.getVertex(n,T,v)):(g.set(0,0),_.set(0,0),v.set(0,0)),s&&(On(u,y),On(d,y),On(f,y),kn(p,b),kn(m,b),kn(h,b)),p.normalize(),m.normalize(),h.normalize(),this.packTriangleDataTextureFormat(this.currentTriangleIndex,u,d,f,p,m,h,g,_,v,a,o),this.currentTriangleIndex++}}packTriangleDataTextureFormat(e,t,n,r,i,a,o,s,c,l,u,d){let f=$e,p=this.triangles.baseOf(e),m=this.triangleFloatChunks.chunkFor(e),h=this.triangles.chunkFor(e);m[p+f.POSITION_A_OFFSET+0]=t.x,m[p+f.POSITION_A_OFFSET+1]=t.y,m[p+f.POSITION_A_OFFSET+2]=t.z,h[p+f.NORMAL_A_PACKED_OFFSET]=nt(i.x,i.y,i.z),m[p+f.POSITION_B_OFFSET+0]=n.x,m[p+f.POSITION_B_OFFSET+1]=n.y,m[p+f.POSITION_B_OFFSET+2]=n.z,h[p+f.NORMAL_B_PACKED_OFFSET]=nt(a.x,a.y,a.z),m[p+f.POSITION_C_OFFSET+0]=r.x,m[p+f.POSITION_C_OFFSET+1]=r.y,m[p+f.POSITION_C_OFFSET+2]=r.z,h[p+f.NORMAL_C_PACKED_OFFSET]=nt(o.x,o.y,o.z),m[p+f.UV_AB_OFFSET+0]=s.x,m[p+f.UV_AB_OFFSET+1]=s.y,m[p+f.UV_AB_OFFSET+2]=c.x,m[p+f.UV_AB_OFFSET+3]=c.y,m[p+f.UV_C_OFFSET+0]=l.x,m[p+f.UV_C_OFFSET+1]=l.y,h[p+f.MATERIAL_FLAGS_OFFSET]=K(u,this.materials[u]),h[p+f.MESH_INDEX_OFFSET]=d}getTriangleData(){return this.triangles?this.triangles.trimTo(this.currentTriangleIndex):null}getTriangleCount(){return this.currentTriangleIndex}getVertex(e,t,n){return e.itemSize===2?(n.x=e.getX(t),n.y=e.getY(t)):e.itemSize>=3&&(n.x=e.getX(t),n.y=e.getY(t),n.z=e.getZ(t)),n}logStats(){let e=this.currentTriangleIndex*$e.FLOATS_PER_TRIANGLE*4;yn.debug(Y.list([`${Y.count(this.currentTriangleIndex,`tri`)} (${Y.mb(e)})`,Y.count(this.materials.length,`material`),Y.count(this.maps.length,`map`)]))}extractMaterialsOnly(e){return this.resetArrays(),this._traverseMaterialsOnly(e),this.getExtractedData()}_traverseMaterialsOnly(e){if(e.isMesh&&e.geometry&&e.material){let t=this.processMaterial(e.material);e.userData.materialIndex=t;let n=this.meshes.length;this.meshes.push(e),e.userData.meshIndex=n}else e.isDirectionalLight?this.directionalLights.push(e):e.isCamera&&this.cameras.push(e);if(e.children)for(let t of e.children)this._traverseMaterialsOnly(t)}resetArrays(){this._droppedTextures=0,this.triangles=null,this.triangleData=null,this.triangleFloatChunks=null,this.triangleFloats=null,this.triangleCount=0,this.currentTriangleIndex=0,this.materials=[],this.materialTriangleCounts=[],this.meshes=[],this.meshTriangleRanges=[],this._geometryRanges=new Map,this.expandedTriangleCount=0,this._allocatePlacements(0),this.maps=[],this.normalMaps=[],this.bumpMaps=[],this.metalnessMaps=[],this.emissiveMaps=[],this.roughnessMaps=[],this.displacementMaps=[],this.anisotropyMaps=[],this.transmissionMaps=[],this.clearcoatMaps=[],this.clearcoatRoughnessMaps=[],this.sheenColorMaps=[],this.sheenRoughnessMaps=[],this.iridescenceMaps=[],this.iridescenceThicknessMaps=[],this.specularIntensityMaps=[],this.specularColorMaps=[],this.directionalLights=[],this.cameras=[],this._materialUuidMap=new Map,this._textureIndexCache=new WeakMap}getExtractedData(){return{triangleData:this.getTriangleData(),triangleCount:this.getTriangleCount(),materials:this.materials,materialTriangleCounts:this.materialTriangleCounts,meshes:this.meshes,meshTriangleRanges:this.meshTriangleRanges,expandedTriangleCount:this.expandedTriangleCount,instanceSource:this.instanceSource.subarray(0,this.instanceCount),instanceMatrices:this.instanceMatrices.subarray(0,this.instanceCount*16),instanceCount:this.instanceCount,bakeInverse:this.bakeInverse,maps:this.maps,normalMaps:this.normalMaps,bumpMaps:this.bumpMaps,metalnessMaps:this.metalnessMaps,emissiveMaps:this.emissiveMaps,roughnessMaps:this.roughnessMaps,displacementMaps:this.displacementMaps,anisotropyMaps:this.anisotropyMaps,transmissionMaps:this.transmissionMaps,clearcoatMaps:this.clearcoatMaps,clearcoatRoughnessMaps:this.clearcoatRoughnessMaps,sheenColorMaps:this.sheenColorMaps,sheenRoughnessMaps:this.sheenRoughnessMaps,iridescenceMaps:this.iridescenceMaps,iridescenceThicknessMaps:this.iridescenceThicknessMaps,specularIntensityMaps:this.specularIntensityMaps,specularColorMaps:this.specularColorMaps,directionalLights:this.directionalLights,cameras:this.cameras}}},Pn=null,Fn=null;function In(e,t=null){Pn=e,Fn=e?t:null}function Ln(){return Pn}function Rn(){return Fn}function zn(e){if(!Pn)return!1;let t=e[0],n=e[1],r=e[2];return e[0]=Pn[0]*t+Pn[1]*n+Pn[2]*r,e[1]=Pn[3]*t+Pn[4]*n+Pn[5]*r,e[2]=Pn[6]*t+Pn[7]*n+Pn[8]*r,!0}function Bn(e,t,n){if(!Pn||n.length===0)return 0;let r=0;for(let i=0;i+t<=e.length;i+=t)for(let t of n){let n=i+t,a=e[n],o=e[n+1],s=e[n+2];e[n]=Pn[0]*a+Pn[1]*o+Pn[2]*s,e[n+1]=Pn[3]*a+Pn[4]*o+Pn[5]*s,e[n+2]=Pn[6]*a+Pn[7]*o+Pn[8]*s,r++}return r}qt();var Vn=new WeakSet,Hn=Pt(`material`),Un=q.SLOTS_PER_MATERIAL,Wn=$e.MATERIAL_FLAGS_OFFSET,Gn=new Set([`transmission`,`transparent`,`opacity`,`alphaMode`]),Kn=[[`map`,!0],[`emissiveMap`,!0],[`sheenColorMap`,!0],[`specularColorMap`,!0],[`normalMap`,!1],[`bumpMap`,!1],[`roughnessMap`,!1],[`metalnessMap`,!1],[`displacementMap`,!1],[`anisotropyMap`,!1],[`transmissionMap`,!1],[`clearcoatMap`,!1],[`clearcoatRoughnessMap`,!1],[`sheenRoughnessMap`,!1],[`iridescenceMap`,!1],[`iridescenceThicknessMap`,!1],[`specularIntensityMap`,!1]],qn={ior:q.IOR,transmission:q.TRANSMISSION,thickness:q.THICKNESS,emissiveIntensity:q.EMISSIVE_INTENSITY,attenuationDistance:q.ATTENUATION_DISTANCE,opacity:q.OPACITY,alphaTest:q.ALPHA_TEST,metalness:q.METALNESS,roughness:q.ROUGHNESS,clearcoat:q.CLEARCOAT,clearcoatRoughness:q.CLEARCOAT_ROUGHNESS,dispersion:q.DISPERSION,sheen:q.SHEEN,sheenRoughness:q.SHEEN_ROUGHNESS,specularIntensity:q.SPECULAR_INTENSITY,iridescence:q.IRIDESCENCE,iridescenceIOR:q.IRIDESCENCE_IOR,subsurface:q.SUBSURFACE,subsurfaceRadiusScale:q.SUBSURFACE_RADIUS_SCALE,subsurfaceAnisotropy:q.SUBSURFACE_ANISOTROPY,anisotropy:q.ANISOTROPY,anisotropyRotation:q.ANISOTROPY_ROTATION},Jn=class e{constructor(e){this.sdfs=e,this.materialStorageAttr=null,this.materialStorageNode=null,this.materialCount=0,this.srgbBuckets=null,this.linearBuckets=null,this._srgbTexPacked=null,this._linearTexPacked=null,this.callbacks={},this._sources=[],this._hostSet=[]}static COLOR_OFFSETS=[q.COLOR,q.EMISSIVE,q.ATTENUATION_COLOR,q.SHEEN_COLOR,q.SPECULAR_COLOR,q.SUBSURFACE_COLOR].filter(e=>Number.isInteger(e));_convertColorsToWorkingSpace(t){if(Vn.has(t))return;Vn.add(t);let n=Bn(t,q.FLOATS_PER_MATERIAL,e.COLOR_OFFSETS);n&&Hn.debug(`converted ${n} material colour(s) into ${Rn()}`)}_writeColor(e,t,n,r,i){let a=[n,r,i];zn(a)&&([n,r,i]=a),e[t]=n,e[t+1]=r,e[t+2]=i}setMaterialData(e,r=[]){if(!e)return;this._convertColorsToWorkingSpace(e);let i=e.length/4;this.materialStorageNode?(this.materialStorageAttr=new t.StorageInstancedBufferAttribute(e,4),this.materialStorageNode.value=this.materialStorageAttr,this.materialStorageNode.bufferCount=i):(this.materialStorageAttr=new t.StorageInstancedBufferAttribute(e,4),this.materialStorageNode=(0,n.storage)(this.materialStorageAttr,`vec4`,i).toReadOnly()),this.materialCount=Math.floor(i/Un),this._sources=[...r],this._hostSet=[],Hn.debug(`${Y.n(this.materialCount)} materials (storage buffer)`)}getStorageAttr(){return this.materialStorageAttr}getStorageNode(){return this.materialStorageNode}setMaterialTextures(e){e.srgbBuckets&&(this.srgbBuckets=e.srgbBuckets),e.linearBuckets&&(this.linearBuckets=e.linearBuckets)}setTexturePackMaps(e,t){this._srgbTexPacked=e||null,this._linearTexPacked=t||null}getPackedTextureIndex(e,t){if(!e)return-1;let n=e.source?.uuid??e.uuid,r=(t?this._srgbTexPacked:this._linearTexPacked)?.get(n);return r===void 0?-1:r}loadTexturesFromSdfs(){this.srgbBuckets=this.sdfs.srgbBucketTextures,this.linearBuckets=this.sdfs.linearBucketTextures,this.setTexturePackMaps(this.sdfs._srgbTexPacked,this.sdfs._linearTexPacked)}getTextureArrays(){return{srgbBuckets:this.srgbBuckets,linearBuckets:this.linearBuckets}}getMaterialProperty(e,t){let n=this.materialStorageAttr?.array;if(!n)return;let r=qn[t];if(r===void 0)return;let i=e*q.FLOATS_PER_MATERIAL+r;return i<n.length?n[i]:void 0}getMaterialPropertySource(e,t){return this._hostSet[e]?.has(t)?Sn.HOST:this._sources[e]?.[t]}updateMaterialProperty(e,t,n){if(!this.materialStorageAttr){Hn.warn(`material storage buffer not available`);return}let r=this.materialStorageAttr.array,i=e*q.FLOATS_PER_MATERIAL;switch(nn.has(t)&&typeof n==`number`&&(n=rn(n)),t){case`color`:n.r===void 0?Array.isArray(n)&&this._writeColor(r,i+q.COLOR,n[0],n[1],n[2]):this._writeColor(r,i+q.COLOR,n.r,n.g,n.b);break;case`metalness`:r[i+q.METALNESS]=n;break;case`emissive`:n.r===void 0?Array.isArray(n)&&this._writeColor(r,i+q.EMISSIVE,n[0],n[1],n[2]):this._writeColor(r,i+q.EMISSIVE,n.r,n.g,n.b);break;case`roughness`:r[i+q.ROUGHNESS]=n;break;case`ior`:r[i+q.IOR]=n;break;case`transmission`:r[i+q.TRANSMISSION]=n;break;case`thickness`:r[i+q.THICKNESS]=n;break;case`emissiveIntensity`:r[i+q.EMISSIVE_INTENSITY]=n;break;case`attenuationColor`:n.r===void 0?Array.isArray(n)&&this._writeColor(r,i+q.ATTENUATION_COLOR,n[0],n[1],n[2]):this._writeColor(r,i+q.ATTENUATION_COLOR,n.r,n.g,n.b);break;case`attenuationDistance`:r[i+q.ATTENUATION_DISTANCE]=rt(n);break;case`dispersion`:r[i+q.DISPERSION]=n;break;case`sheen`:r[i+q.SHEEN]=n;break;case`sheenRoughness`:r[i+q.SHEEN_ROUGHNESS]=n;break;case`sheenColor`:n.r===void 0?Array.isArray(n)&&this._writeColor(r,i+q.SHEEN_COLOR,n[0],n[1],n[2]):this._writeColor(r,i+q.SHEEN_COLOR,n.r,n.g,n.b);break;case`specularIntensity`:r[i+q.SPECULAR_INTENSITY]=n;break;case`specularColor`:n.r===void 0?Array.isArray(n)&&this._writeColor(r,i+q.SPECULAR_COLOR,n[0],n[1],n[2]):this._writeColor(r,i+q.SPECULAR_COLOR,n.r,n.g,n.b);break;case`iridescence`:r[i+q.IRIDESCENCE]=n;break;case`iridescenceIOR`:r[i+q.IRIDESCENCE_IOR]=n;break;case`iridescenceThicknessRange`:Array.isArray(n)&&(r[i+q.IRIDESCENCE_THICKNESS_RANGE]=n[0],r[i+q.IRIDESCENCE_THICKNESS_RANGE+1]=n[1]);break;case`clearcoat`:r[i+q.CLEARCOAT]=n;break;case`clearcoatRoughness`:r[i+q.CLEARCOAT_ROUGHNESS]=n;break;case`opacity`:r[i+q.OPACITY]=n;break;case`side`:r[i+q.SIDE]=n,this._patchTriangleSideForMaterial(e,n);break;case`transparent`:r[i+q.TRANSPARENT]=n;break;case`alphaTest`:r[i+q.ALPHA_TEST]=n;break;case`alphaMode`:r[i+q.ALPHA_MODE]=n;break;case`depthWrite`:r[i+q.DEPTH_WRITE]=n;break;case`normalScale`:n.x===void 0?typeof n==`number`&&(r[i+q.NORMAL_SCALE]=n,r[i+q.NORMAL_SCALE+1]=n):(r[i+q.NORMAL_SCALE]=n.x,r[i+q.NORMAL_SCALE+1]=n.y);break;case`bumpScale`:r[i+q.BUMP_SCALE]=n;break;case`displacementScale`:r[i+q.DISPLACEMENT_SCALE]=n;break;case`subsurface`:r[i+q.SUBSURFACE]=n;break;case`subsurfaceRadiusScale`:r[i+q.SUBSURFACE_RADIUS_SCALE]=n;break;case`subsurfaceAnisotropy`:r[i+q.SUBSURFACE_ANISOTROPY]=n;break;case`anisotropy`:r[i+q.ANISOTROPY]=n;break;case`anisotropyRotation`:r[i+q.ANISOTROPY_ROTATION]=n;break;case`subsurfaceColor`:n.r===void 0?Array.isArray(n)&&this._writeColor(r,i+q.SUBSURFACE_COLOR,n[0],n[1],n[2]):this._writeColor(r,i+q.SUBSURFACE_COLOR,n.r,n.g,n.b);break;case`subsurfaceRadius`:Array.isArray(n)?(r[i+q.SUBSURFACE_RADIUS]=n[0],r[i+q.SUBSURFACE_RADIUS+1]=n[1],r[i+q.SUBSURFACE_RADIUS+2]=n[2]):n.x!==void 0&&(r[i+q.SUBSURFACE_RADIUS]=n.x,r[i+q.SUBSURFACE_RADIUS+1]=n.y,r[i+q.SUBSURFACE_RADIUS+2]=n.z);break;default:Hn.warn(`unknown material property: ${t}`);return}this.materialStorageAttr.needsUpdate=!0,(this._hostSet[e]??=new Set).add(t),Gn.has(t)&&this._recomputeOpaqueBlockerForMaterial(e),this._notifyReset()}updateMaterialDataFromObject(t,n){if(!this.materialStorageAttr){Hn.warn(`material storage buffer not available`);return}let r=this.materialStorageAttr.array,i=t*q.FLOATS_PER_MATERIAL;cn(r,i,n);for(let t of e.COLOR_OFFSETS)this._writeColor(r,i+t,r[i+t],r[i+t+1],r[i+t+2]);this._sources[t]=n.sources,this._hostSet[t]=void 0,this._patchTriangleSideForMaterial(t,r[i+q.SIDE]),this._recomputeOpaqueBlockerForMaterial(t),this.materialStorageAttr.needsUpdate=!0,this._notifyReset()}updateMaterial(e,t){let n=this.sdfs.geometryExtractor.createMaterialObject(t);if(this._srgbTexPacked||this._linearTexPacked){let e=Tn(t);for(let[t,r]of Kn)n[t]=this.getPackedTextureIndex(e[t],r)}this.updateMaterialDataFromObject(e,n)}updateTextureTransform(e,t,n){if(!this.materialStorageAttr){Hn.warn(`material storage buffer not available`);return}let r=this.materialStorageAttr.array,i=e*q.FLOATS_PER_MATERIAL,a={map:q.ALBEDO_TRANSFORM,normalMap:q.NORMAL_TRANSFORM,roughnessMap:q.ROUGHNESS_TRANSFORM,metalnessMap:q.METALNESS_TRANSFORM,emissiveMap:q.EMISSIVE_TRANSFORM,bumpMap:q.BUMP_TRANSFORM,displacementMap:q.DISPLACEMENT_TRANSFORM}[t];if(a===void 0){Hn.warn(`unknown texture name for transform update: ${t}`);return}for(let e=0;e<8;e++)i+a+e<r.length&&(r[i+a+e]=n[e]);this.materialStorageAttr.needsUpdate=!0,this._notifyReset()}_notifyReset(){this.callbacks.onReset&&this.callbacks.onReset()}_recomputeOpaqueBlockerForMaterial(e){let t=this.materialStorageAttr?.array;if(!t)return;let n=e*q.FLOATS_PER_MATERIAL,r=tt({alphaMode:t[n+q.ALPHA_MODE],transparent:t[n+q.TRANSPARENT],transmission:t[n+q.TRANSMISSION],opacity:t[n+q.OPACITY]});this._patchTriangleFlagForMaterial(e,26,2,r)}_patchTriangleFlagForMaterial(e,t,n,r){let i=this.callbacks.getTriangleData?.(),a=i?.records,o=a?null:i?.array,s=i?.count|0;if(!o&&!a||s===0)return;let c=$e.FLOATS_PER_TRIANGLE,l=(1<<n)-1<<t>>>0,u=(r<<t&l)>>>0,d=0;for(let t=0;t<s;t++){let n=a?a.chunkFor(t):o,r=a?a.baseOf(t):t*c;(n[r+Wn]&16777215)===e&&(n[r+Wn]=(n[r+Wn]&~l|u)>>>0,d++)}d>0&&this.callbacks.onTriangleDataChanged&&this.callbacks.onTriangleDataChanged()}_patchTriangleSideForMaterial(e,t){this._patchTriangleFlagForMaterial(e,24,2,t)}dispose(){this.materialStorageAttr=null,this.materialStorageNode=null,this.materialCount=0,this.srgbBuckets=null,this.linearBuckets=null,this._srgbTexPacked=null,this._linearTexPacked=null,this._sources=[],this._hostSet=[]}},Yn=`function e(e,t,n,r){let i=n,a=n+r-1;for(;i<a;){let n=i+a>>1;e[n]<t?i=n+1:a=n}return i-n}function t(t,n,r){let i=n*r,a=new Float32Array(i),o=0;for(let e=0;e<r;e++){let i=Math.sin(Math.PI*(e+.5)/r);for(let r=0;r<n;r++){let s=e*n+r,c=t[4*s],l=t[4*s+1],u=t[4*s+2],d=(.2126*c+.7152*l+.0722*u)*i;a[s]=d,o+=d}}let s=o/i,c=0;for(let e=0;e<i;e++)a[e]=Math.max(0,a[e]-s),c+=a[e];let l=c>0,u=l?c:o,d=l?s:0;if(!l)for(let e=0;e<r;e++){let i=Math.sin(Math.PI*(e+.5)/r);for(let r=0;r<n;r++){let o=e*n+r,s=t[4*o],c=t[4*o+1],l=t[4*o+2];a[o]=(.2126*s+.7152*c+.0722*l)*i}}let f=new Float32Array(i),p=new Float32Array(r),m=0;for(let e=0;e<r;e++){let t=0;for(let r=0;r<n;r++){let i=e*n+r;t+=a[i],f[i]=t}if(t!==0)for(let r=e*n,i=e*n+n;r<i;r++)f[r]/=t;m+=t,p[e]=m}if(m!==0)for(let e=0,t=p.length;e<t;e++)p[e]/=m;let h=new Float32Array(r);for(let t=0;t<r;t++)h[t]=(e(p,(t+1)/r,0,r)+.5)/r;let g=new Float32Array(n*r);for(let t=0;t<r;t++)for(let r=0;r<n;r++){let i=t*n+r;g[i]=(e(f,(r+1)/n,t*n,n)+.5)/n}return{marginalData:h,conditionalData:g,totalSum:u,compensationDelta:d}}self.onmessage=function(e){let{floatData:n,width:r,height:i}=e.data;try{let e=t(n,r,i);self.postMessage({marginalData:e.marginalData,conditionalData:e.conditionalData,totalSum:e.totalSum,compensationDelta:e.compensationDelta,width:r,height:i},[e.marginalData.buffer,e.conditionalData.buffer])}catch(e){self.postMessage({error:e.message})}};`,Xn=typeof self<`u`&&self.Blob&&new Blob([`URL.revokeObjectURL(import.meta.url);`,Yn],{type:`text/javascript;charset=utf-8`});function Zn(e){let t;try{if(t=Xn&&(self.URL||self.webkitURL).createObjectURL(Xn),!t)throw``;let n=new Worker(t,{type:`module`,name:e?.name});return n.addEventListener(`error`,()=>{(self.URL||self.webkitURL).revokeObjectURL(t)}),n}catch{return new Worker(`data:text/javascript;charset=utf-8,`+encodeURIComponent(Yn),{type:`module`,name:e?.name})}}function Qn(e,t,n=0,r=e.length){let i=n,a=n+r-1;for(;i<a;){let n=i+a>>1;e[n]<t?i=n+1:a=n}return i-n}function $n(e,t,n){return .2126*e+.7152*t+.0722*n}function er(e){return e<=.04045?e/12.92:((e+.055)/1.055)**2.4}function tr(e){let{width:t,height:n}=e.image,i=e.image.data,a=!1;if(!i){let r=new OffscreenCanvas(t,n).getContext(`2d`);r.drawImage(e.image,0,0,t,n),i=r.getImageData(0,0,t,n).data,a=!0}let o;if(e.type===r.FloatType&&i instanceof Float32Array)o=new Float32Array(i);else if(e.type===r.HalfFloatType){o=new Float32Array(i.length);for(let e=0,t=i.length;e<t;e++)o[e]=r.DataUtils.fromHalfFloat(i[e])}else{let e;e=i instanceof Int8Array||i instanceof Int16Array||i instanceof Int32Array?2**(8*i.BYTES_PER_ELEMENT-1)-1:2**(8*i.BYTES_PER_ELEMENT)-1,o=new Float32Array(i.length);for(let t=0,n=i.length;t<n;t++)o[t]=i[t]/e}if(!a&&e.colorSpace===r.SRGBColorSpace&&(a=!0),a)for(let e=0,t=o.length;e<t;e+=4)o[e]=er(o[e]),o[e+1]=er(o[e+1]),o[e+2]=er(o[e+2]);if(e.flipY){let e=new Float32Array(o.length);for(let r=0;r<n;r++){let i=n-r-1,a=r*t*4,s=i*t*4;e.set(o.subarray(a,a+t*4),s)}o=e}return{floatData:o,width:t,height:n}}var nr=class e{constructor(){this.marginalData=new Float32Array([0,1]),this.conditionalData=new Float32Array([0,0,1,1]),this.totalSum=0,this.compensationDelta=0,this.width=0,this.height=0,this._worker=null}dispose(){this.marginalData=null,this.conditionalData=null,this._worker&&=(this._worker.terminate(),null)}updateFrom(t){let{floatData:n,width:r,height:i}=tr(t),a=e.computeCDF(n,r,i);this.marginalData=a.marginalData,this.conditionalData=a.conditionalData,this.totalSum=a.totalSum,this.compensationDelta=a.compensationDelta,this.width=r,this.height=i}async updateFromAsync(e){let{floatData:t,width:n,height:r}=tr(e);this._worker=new Zn;try{let e=await new Promise((e,i)=>{this._worker.onmessage=t=>{t.data.error?i(Error(t.data.error)):e(t.data)},this._worker.onerror=i,this._worker.postMessage({floatData:t,width:n,height:r},[t.buffer])});this.marginalData=e.marginalData,this.conditionalData=e.conditionalData,this.totalSum=e.totalSum,this.compensationDelta=e.compensationDelta,this.width=e.width,this.height=e.height}finally{this._worker&&=(this._worker.terminate(),null)}}static computeCDF(e,t,n){let r=t*n,i=new Float32Array(r),a=0;for(let r=0;r<n;r++){let o=Math.sin(Math.PI*(r+.5)/n);for(let n=0;n<t;n++){let s=r*t+n,c=$n(e[4*s],e[4*s+1],e[4*s+2])*o;i[s]=c,a+=c}}let o=a/r,s=0;for(let e=0;e<r;e++)i[e]=Math.max(0,i[e]-o),s+=i[e];let c=s>0,l=c?s:a,u=c?o:0;if(!c)for(let r=0;r<n;r++){let a=Math.sin(Math.PI*(r+.5)/n);for(let n=0;n<t;n++){let o=r*t+n;i[o]=$n(e[4*o],e[4*o+1],e[4*o+2])*a}}let d=new Float32Array(r),f=new Float32Array(n),p=0;for(let e=0;e<n;e++){let n=0;for(let r=0;r<t;r++){let a=e*t+r;n+=i[a],d[a]=n}if(n!==0)for(let r=e*t,i=e*t+t;r<i;r++)d[r]/=n;p+=n,f[e]=p}if(p!==0)for(let e=0,t=f.length;e<t;e++)f[e]/=p;let m=new Float32Array(n),h=new Float32Array(r);for(let e=0;e<n;e++)m[e]=(Qn(f,(e+1)/n)+.5)/n;for(let e=0;e<n;e++)for(let n=0;n<t;n++){let r=e*t+n;h[r]=(Qn(d,(n+1)/t,e*t,t)+.5)/t}return{marginalData:m,conditionalData:h,totalSum:l,compensationDelta:u}}},rr=Math.PI,ir=Math.PI*2,ar=Math.E,or=[5804542996261093e-21,13562911419845635e-21,30265902468824876e-21],sr=[183999185144339.78,277980239196605.28,407904795438610.94],cr=1.6110731556870734,lr=1.5,ur=1e3,dr=8400,fr=1250,pr=.9999566769464484,mr=.05968310365946075,hr=.07957747154594767;function gr(e){return ur*Math.max(0,1-ar**+(-(cr-Math.acos(Math.max(-1,Math.min(1,e))))/lr))}function _r(e){let t=.2*e*1e-17;return[.434*t*sr[0],.434*t*sr[1],.434*t*sr[2]]}function vr(e){return mr*(1+e**2)}function yr(e,t){let n=t*t;return hr*((1-n)/(1-2*t*e+n)**1.5)}function br(e,t){return e[0]*t[0]+e[1]*t[1]+e[2]*t[2]}function xr(e){let t=Math.sqrt(e[0]*e[0]+e[1]*e[1]+e[2]*e[2]);return t===0?[0,0,0]:[e[0]/t,e[1]/t,e[2]/t]}function Sr(e,t,n,r,i,a,o,s){let c=(1-t)*rr,l=(e-.5)*ir,u=Math.sin(c),d=xr([u*Math.sin(l),Math.cos(c),u*Math.cos(l)]),f=xr(n),p=gr(f[1])*r,m=i-1*(1-(1-Math.max(0,Math.min(1,1-Math.exp(f[1]/45e4))))),h=[or[0]*m,or[1]*m,or[2]*m],g=_r(s),_=[g[0]*a,g[1]*a,g[2]*a],v=Math.acos(Math.max(0,d[1])),y=Math.cos(v)+.15*(93.885-180/rr*v)**-1.253,b=dr/y,x=fr/y,S=[Math.exp(-(h[0]*b+_[0]*x)),Math.exp(-(h[1]*b+_[1]*x)),Math.exp(-(h[2]*b+_[2]*x))],C=br(d,f),w=vr(C*.5+.5),T=[h[0]*w,h[1]*w,h[2]*w],E=yr(C,o),D=[_[0]*E,_[1]*E,_[2]*E],O=[T[0]+D[0],T[1]+D[1],T[2]+D[2]],k=[h[0]+_[0],h[1]+_[1],h[2]+_[2]],A=[(p*(O[0]/k[0])*(1-S[0]))**1.5,(p*(O[1]/k[1])*(1-S[1]))**1.5,(p*(O[2]/k[2])*(1-S[2]))**1.5],j=Math.max(0,Math.min(1,1-(1-f[1])**5)),M=[Math.sqrt(p*(O[0]/k[0])*S[0]),Math.sqrt(p*(O[1]/k[1])*S[1]),Math.sqrt(p*(O[2]/k[2])*S[2])],N=1-j;for(let e=0;e<3;e++){let t=1*(1-N)+M[e]*N;A[e]*=t}let P=[.1*S[0],.1*S[1],.1*S[2]],F=Cr(pr,pr+2e-5,C);for(let e=0;e<3;e++)P[e]+=p*19e3*S[e]*F;let I=65504;return[Math.min((A[0]+P[0])*.04,I),Math.min((A[1]+P[1])*.04+3e-4,I),Math.min((A[2]+P[2])*.04+75e-5,I),1]}function Cr(e,t,n){let r=Math.max(0,Math.min(1,(n-e)/(t-e)));return r*r*(3-2*r)}var wr=class{constructor(e=512,t=256){this.width=e,this.height=t,this.lastRenderTime=0,this._pixels=new Float32Array(e*t*4),this._texture=new r.DataTexture(this._pixels,e,t,r.RGBAFormat,r.FloatType),this._texture.mapping=r.EquirectangularReflectionMapping,this._texture.colorSpace=r.LinearSRGBColorSpace,this._texture.minFilter=r.LinearFilter,this._texture.magFilter=r.LinearFilter,this._texture.wrapS=r.RepeatWrapping,this._texture.wrapT=r.ClampToEdgeWrapping,this._texture.generateMipmaps=!1}render(e){let t=performance.now(),n=[e.sunDirection.x,e.sunDirection.y,e.sunDirection.z],r=e.sunIntensity||1,i=e.rayleighDensity||2,a=e.mieDensity||.005,o=e.mieAnisotropy||.8,s=e.turbidity||2,{width:c,height:l}=this,u=this._pixels;for(let e=0;e<l;e++){let t=(e+.5)/l;for(let l=0;l<c;l++){let d=Sr((l+.5)/c,t,n,r,i,a,o,s),f=(e*c+l)*4;u[f]=d[0],u[f+1]=d[1],u[f+2]=d[2],u[f+3]=d[3]}}return this._texture.needsUpdate=!0,delete this._texture.userData?.__rayzeeColorSpace,this.lastRenderTime=performance.now()-t,this._texture}setResolution(e,t){this.width===e&&this.height===t||(this.width=e,this.height=t,this._pixels=new Float32Array(e*t*4),this._texture.dispose(),this._texture=new r.DataTexture(this._pixels,e,t,r.RGBAFormat,r.FloatType),this._texture.mapping=r.EquirectangularReflectionMapping,this._texture.colorSpace=r.LinearSRGBColorSpace,this._texture.minFilter=r.LinearFilter,this._texture.magFilter=r.LinearFilter,this._texture.wrapS=r.RepeatWrapping,this._texture.wrapT=r.ClampToEdgeWrapping,this._texture.generateMipmaps=!1)}getLastRenderTime(){return this.lastRenderTime}dispose(){this._texture.dispose()}},Tr=class{constructor(e=512,t=256){this.width=e,this.height=t,this.lastRenderTime=0,this._pixels=new Float32Array(e*t*4),this._texture=new r.DataTexture(this._pixels,e,t,r.RGBAFormat,r.FloatType),this._texture.mapping=r.EquirectangularReflectionMapping,this._texture.colorSpace=r.LinearSRGBColorSpace,this._texture.minFilter=r.LinearFilter,this._texture.magFilter=r.LinearFilter,this._texture.wrapS=r.RepeatWrapping,this._texture.wrapT=r.ClampToEdgeWrapping,this._texture.generateMipmaps=!1}renderGradient(e){let t=performance.now(),{width:n,height:r}=this,i=this._pixels,a=e.zenithColor.r,o=e.zenithColor.g,s=e.zenithColor.b,c=e.horizonColor.r,l=e.horizonColor.g,u=e.horizonColor.b,d=e.groundColor.r,f=e.groundColor.g,p=e.groundColor.b;for(let e=0;e<r;e++){let t=(e+.5)/r,m,h,g;if(t>.5){let e=(t-.5)*2;m=c+(a-c)*e,h=l+(o-l)*e,g=u+(s-u)*e}else{let e=t*2;m=d+(c-d)*e,h=f+(l-f)*e,g=p+(u-p)*e}for(let t=0;t<n;t++){let r=(e*n+t)*4;i[r]=m,i[r+1]=h,i[r+2]=g,i[r+3]=1}}return this._texture.needsUpdate=!0,delete this._texture.userData?.__rayzeeColorSpace,this.lastRenderTime=performance.now()-t,this._texture}renderSolid(e){let t=performance.now(),{width:n,height:r}=this,i=this._pixels,a=e.color.r,o=e.color.g,s=e.color.b;for(let e=0;e<r;e++)for(let t=0;t<n;t++){let r=(e*n+t)*4;i[r]=a,i[r+1]=o,i[r+2]=s,i[r+3]=1}return this._texture.needsUpdate=!0,delete this._texture.userData?.__rayzeeColorSpace,this.lastRenderTime=performance.now()-t,this._texture}setResolution(e,t){this.width===e&&this.height===t||(this.width=e,this.height=t,this._pixels=new Float32Array(e*t*4),this._texture.dispose(),this._texture=new r.DataTexture(this._pixels,e,t,r.RGBAFormat,r.FloatType),this._texture.mapping=r.EquirectangularReflectionMapping,this._texture.colorSpace=r.LinearSRGBColorSpace,this._texture.minFilter=r.LinearFilter,this._texture.magFilter=r.LinearFilter,this._texture.wrapS=r.RepeatWrapping,this._texture.wrapT=r.ClampToEdgeWrapping,this._texture.generateMipmaps=!1)}getLastRenderTime(){return this.lastRenderTime}dispose(){this._texture.dispose()}};function Er(e){let t=String(e??``);return/(hdr|pq|hlg|2100|st2084)/i.test(t)?null:/^display\s*p3\b/i.test(t)?`display-p3`:/^(srgb|rec\.?\s*1886|bt\.?\s*1886|gamma\s*2\.2\s*rec\.?\s*709)\b(?!.*(p3|2020))/i.test(t)?`srgb`:null}function Dr(e){e&&Object.assign(kr,e)}function Or(){return{...kr}}var kr,Ar=y((()=>{kr={stbnScalarAtlas:`https://assets.rayzee.atulmourya.com/noise/stbn_scalar_atlas.png`,stbnVec2Atlas:`https://assets.rayzee.atulmourya.com/noise/stbn_vec2_atlas.png`,ortRuntimeUrl:`https://cdn.jsdelivr.net/npm/onnxruntime-web@1.24.3/dist/ort.webgpu.bundle.min.mjs`,ortWasmPaths:`https://cdn.jsdelivr.net/npm/onnxruntime-web@1.24.3/dist/`,dracoDecoderPath:`https://www.gstatic.com/draco/v1/decoders/`,ktx2TranscoderPath:`https://cdn.jsdelivr.net/npm/three@0.183.2/examples/jsm/libs/basis/`,oidnWeightsBaseUrl:`https://assets.rayzee.atulmourya.com/oidn/denoiser-0.0.11/`,ocioRuntimeFactory:null,ocioRuntimeUrl:null,ocioWasmUrl:null,upscalerModelBaseUrl:`https://huggingface.co/notaneimu/onnx-image-models/resolve/main/`,neuralRuntimeUrl:`/neural/neural-runtime.js`,neuralAssetBaseUrl:null,cacheNamespace:`rayzee`}}));Ar(),qt();var jr=Pt(`ocio`);function Mr(e){let t=String(e);/\[OpenColorIO Error\]/.test(t)?jr.error(t):/\[OpenColorIO Warning\]/.test(t)?jr.warn(t):jr.debug(t)}var Nr=null,Pr=null,Fr=null,Ir=null,Lr=null;async function Rr(){let{ocioRuntimeFactory:e,ocioRuntimeUrl:t}=Or();if(typeof e==`function`)return await e();if(typeof t==`string`&&t)return await import(t);throw Error(`OpenColorIO runtime not configured. Call configureAssets({ ocioRuntimeFactory: () => import('@bb-studio/ocio') }) before loading a config.`)}async function zr(){return Pr||(Nr||=(async()=>{let e=await Rr();if(typeof e.createOcioRuntime!=`function`)throw Error(`OCIO module has no createOcioRuntime() — wrong package or version`);let{ocioWasmUrl:t}=Or();return Pr=await e.createOcioRuntime({...t?{wasmUrl:t}:{},moduleOptions:{print:Mr,printErr:Mr}}),Pr})().catch(e=>{throw Nr=null,e}),await Nr)}async function Br(){return(await zr()).ocio.listBuiltinConfigs()}async function Vr({builtin:e,text:t,files:n=[],configPath:r=`config.ocio`,id:i}={}){let a=await zr();if(e)Fr=a.loadBuiltinConfig(e),Ir=e,Lr=qr(a,e);else{let e=n.map(e=>({relativePath:e.relativePath??e.path??e.name,data:e.data instanceof Uint8Array?e.data:new Uint8Array(e.data)}));if(t!==void 0&&e.unshift({relativePath:r,data:new TextEncoder().encode(t)}),!e.some(e=>e.relativePath===r))throw Error(`config package has no "${r}" — pass configPath to name the .ocio file`);Fr=a.loadConfigPackage({configRelativePath:r,files:e},i?{id:i}:void 0),Ir=i??Fr.id;let o=e.find(e=>e.relativePath===r);Lr=o?new TextDecoder().decode(o.data):null}return Kr()}function Hr(){Fr=null,Ir=null,Lr=null}function Ur(){return Fr!==null}function Wr(){return Fr?Pr:null}function Gr(){return Fr}function Kr(){if(!Fr)return null;let e=Object.fromEntries(Fr.roles.map(e=>[e.name,e.colorSpace]));return{id:Ir,name:Lr?.match(/^name:\s*(\S.*?)\s*$/m)?.[1]??null,ocioVersion:Fr.ocioVersion,version:Fr.version,roles:e,sceneLinear:e.scene_linear??null,colorPicking:e.color_picking??e.texture_paint??null,texturePaint:e.texture_paint??e.color_picking??null,data:e.data??null,compositingLog:e.compositing_log??e.color_timing??null,colorSpaces:Fr.colorSpaces.map(e=>({name:e.name,family:e.family,categories:e.categories??[],encoding:e.encoding,isData:e.isData,aliases:e.aliases,description:e.description})),displays:Fr.displays.slice(),defaultDisplay:Fr.defaultDisplay,views:Object.fromEntries(Object.entries(Fr.viewsByDisplay).map(([e,t])=>[e,t.map(e=>({name:e.name,transform:e.transform,colorSpace:e.colorSpace,looks:e.looks,description:e.description}))])),defaultViews:{...Fr.defaultViewsByDisplay},looks:Fr.looks.map(e=>({name:e.name,processSpace:e.processSpace,description:e.description,forward:e.hasForwardTransform,inverse:e.hasInverseTransform})),namedTransforms:Fr.namedTransforms.map(e=>e.name),fileRules:Fr.fileRules.map(e=>({index:e.index,name:e.name,colorSpace:e.colorSpace,pattern:e.pattern,extension:e.extension,regex:e.regex})),contextVariables:Jr()}}function qr(e,t){try{return e.ocio.getBuiltinConfigYaml(t)}catch{return null}}function Jr(){if(!Lr)return[];let e=new Map,t=Lr.split(/\r?\n/),n=t.findIndex(e=>/^environment:\s*(\{\s*\})?\s*$/.test(e));if(n>=0&&!/\{\s*\}/.test(t[n]))for(let r=n+1;r<t.length;r++){let n=t[r];if(/^\S/.test(n))break;let i=n.match(/^\s+([A-Za-z_][A-Za-z0-9_]*)\s*:\s*(.*?)\s*$/);i&&e.set(i[1],{name:i[1],default:i[2].replace(/^["']|["']$/g,``)||null,declared:!0})}for(let t of Lr.matchAll(/\$\{?([A-Za-z_][A-Za-z0-9_]*)\}?/g))e.has(t[1])||e.set(t[1],{name:t[1],default:null,declared:!1});return[...e.values()].sort((e,t)=>e.name.localeCompare(t.name))}function Yr(){Hr(),Pr?.dispose?.(),Pr=null,Nr=null}var Xr=1<<20,Zr=new Map,Qr=new Map,$r=4096,ei=new Map;function ti(e,t,n){return`${e}\u0000${t}\u0000${n?JSON.stringify(n):``}`}function ni(){for(let e of Zr.values())e.dispose?.();Zr.clear(),Qr.clear(),ei.clear()}function ri(e,t,{context:n=null}={}){if(!Wr()||e===t)return null;let r=ti(e,t,n),i=Zr.get(r);if(i!==void 0)return i;try{i=si().createColorSpaceProcessor(e,t,n?{context:n}:void 0),i.isNoOp&&(i.dispose(),i=null)}catch(n){throw Error(`no OCIO transform from "${e}" to "${t}": ${n.message}`)}return Zr.set(r,i),i}var ii=null,ai=null,oi=!1;function si(){let e=Wr();if(!e)throw Error(`no OCIO config loaded`);if(e.config)return e.config;let t=Gr();if(ii&&ai===t.id)return ii;if(oi&&ii?.dispose?.(),!t.id?.startsWith(`ocio://`))throw Error(`OCIO runtime exposes no Config handle for this config`);return ii=e.ocio.createBuiltinConfig(t.id),oi=!0,ai=t.id,ii}function ci(){oi&&ii?.dispose?.(),ii=null,ai=null,oi=!1,ni()}function li(e,t,n,{context:r=null}={}){let i=Wr();if(!i||t===n)return[e[0],e[1],e[2]];let a=`${ti(t,n,r)}\u0000${e[0]},${e[1]},${e[2]}`,o=Qr.get(a);if(o)return o.slice();let s=i.transformRgb(t,n,[e[0],e[1],e[2]],r?{context:r}:void 0);return Qr.size>=$r&&Qr.clear(),Qr.set(a,s),s.slice()}function ui(e,t,n,{context:r=null}={}){if(e.length%4!=0)throw Error(`convertPixelsF32 wants 4 floats per pixel`);let i=ri(t,n,{context:r});if(!i)return e;let a=e.length/4;if(a<=Xr)return i.applyRGBAF32(e),e;for(let t=0;t<a;t+=Xr){let n=Math.min(Xr,a-t);i.applyRGBAF32(e.subarray(t*4,(t+n)*4))}return e}var di=.055;function fi(e){return e<=.04045?e/12.92:((e+di)/(1+di))**2.4}function pi(e){return e<=0?0:e<=.0031308?12.92*e:(1+di)*e**(1/2.4)-di}var mi=new Float32Array(256);for(let e=0;e<256;e++)mi[e]=fi(e/255);var hi=new Float32Array(256);for(let e=0;e<256;e++)hi[e]=e/255;function gi(e){return e===`srgb`?mi:hi}function _i(e,t,n,{context:r=null,inputEncoding:i=`raw`,outputEncoding:a=`srgb`}={}){if(e.length%4!=0)throw Error(`convertEncodedRGBA8 wants 4 bytes per pixel`);let o=ri(t,n,{context:r});if(!o)return e;let s=e.length/4,c=gi(i),l=a===`srgb`?bi:xi,u=new Float32Array(Math.min(Xr,s)*4);for(let t=0;t<s;t+=Xr){let n=Math.min(Xr,s-t),r=n*4===u.length?u:u.subarray(0,n*4);for(let i=0;i<n;i++){let n=(t+i)*4,a=i*4;r[a]=c[e[n]],r[a+1]=c[e[n+1]],r[a+2]=c[e[n+2]],r[a+3]=1}o.applyRGBAF32(r);for(let i=0;i<n;i++){let n=(t+i)*4,a=i*4;e[n]=l(r[a]),e[n+1]=l(r[a+1]),e[n+2]=l(r[a+2])}}return e}var vi=65536,yi=new Uint8Array(vi+1);for(let e=0;e<=vi;e++){let t=e/vi;yi[e]=Math.round(pi(t*t)*255)}function bi(e){return e>0?e>=1?255:yi[Math.sqrt(e)*vi+.5|0]:0}function xi(e){return e>0?e>=1?255:e*255+.5|0:0}function Si(e,t,n=`srgb`){if(!t)return e;let r=gi(n),i=n===`srgb`?bi:xi,[a,o,s,c,l,u,d,f,p]=t;for(let t=0;t<e.length;t+=4){let n=r[e[t]],m=r[e[t+1]],h=r[e[t+2]];e[t]=i(a*n+o*m+s*h),e[t+1]=i(c*n+l*m+u*h),e[t+2]=i(d*n+f*m+p*h)}return e}function Ci(e,t,{context:n=null,tolerance:r=1e-4}={}){if(!Wr())return null;if(e===t)return[1,0,0,0,1,0,0,0,1];let i=ti(e,t,n);if(ei.has(i))return ei.get(i);let a=ri(e,t,{context:n});if(!a)return ei.set(i,[1,0,0,0,1,0,0,0,1]),ei.get(i);let o=e=>{let t=new Float32Array([e[0],e[1],e[2],1]);return a.applyRGBAF32(t),[t[0],t[1],t[2]]},s=[o([1,0,0]),o([0,1,0]),o([0,0,1])],c=[s[0][0],s[1][0],s[2][0],s[0][1],s[1][1],s[2][1],s[0][2],s[1][2],s[2][2]],l=e=>[c[0]*e[0]+c[1]*e[1]+c[2]*e[2],c[3]*e[0]+c[4]*e[1]+c[5]*e[2],c[6]*e[0]+c[7]*e[1]+c[8]*e[2]],u=[[.18,.18,.18],[.5,.25,.75],[2,.1,.4],[.02,.9,.3],[8,4,1],[.001,.002,.004]],d=!0;for(let e of u){let t=o(e),n=l(e),i=Math.max(.001,Math.abs(n[0]),Math.abs(n[1]),Math.abs(n[2]));for(let e=0;e<3;e++)Math.abs(t[e]-n[e])>r*i&&(d=!1);if(!d)break}let f=d?c:null;return ei.set(i,f),f}function wi(e){let t=Gr();if(!t)return!1;let n=t.colorSpaces.find(t=>t.name===e||t.aliases?.includes(e));return n?n.isData:!1}function Ti(e){let t=Gr();return!t||!e?!1:t.colorSpaces.some(t=>t.name===e||t.aliases?.includes(e))}function Ei(e,t,n,r,i){i[0]=Ni(e),i[1]=Ni(t),i[2]=Ni(n)}function Di(e,t,n,r,i){i[0]=Ni(e*r),i[1]=Ni(t*r),i[2]=Ni(n*r)}function Oi(e,t,n,r,i){e*=r,t*=r,n*=r,i[0]=Ni(e/(e+1)),i[1]=Ni(t/(t+1)),i[2]=Ni(n/(n+1))}function ki(e,t,n,r,i){e=Math.max(e*r-.004,0),t=Math.max(t*r-.004,0),n=Math.max(n*r-.004,0);let a=e=>(e*(6.2*e+.5)/(e*(6.2*e+1.7)+.06))**2.2;i[0]=a(e),i[1]=a(t),i[2]=a(n)}function Ai(e,t,n,r,i){e=e*r/.6,t=t*r/.6,n=n*r/.6;let a=.59719*e+.35458*t+.04823*n,o=.076*e+.90834*t+.01566*n,s=.0284*e+.13383*t+.83777*n,c=e=>(e*(e+.0245786)-90537e-9)/(e*(.983729*e+.432951)+.238081);a=c(a),o=c(o),s=c(s),i[0]=Ni(1.60475*a-.53108*o-.07367*s),i[1]=Ni(-.10208*a+1.10813*o-.00605*s),i[2]=Ni(-.00327*a-.07276*o+1.07602*s)}function ji(e,t,n,r,i){e*=r,t*=r,n*=r;let a=.6274*e+.3293*t+.0433*n,o=.0691*e+.9195*t+.0113*n,s=.0164*e+.088*t+.8956*n,c=.856627153315983*a+.0951212405381588*o+.0482516061458583*s,l=.137318972929847*a+.761241990602591*o+.101439036467562*s,u=.11189821299995*a+.0767994186031903*o+.811302368396859*s,d=-12.47393,f=4.026069-d;c=Ni((Math.log2(Math.max(c,1e-10))-d)/f),l=Ni((Math.log2(Math.max(l,1e-10))-d)/f),u=Ni((Math.log2(Math.max(u,1e-10))-d)/f);let p=e=>{let t=e*e,n=t*t;return 15.5*n*t-40.14*n*e+31.96*n-6.868*t*e+.4298*t+.1191*e-.00232};c=p(c),l=p(l),u=p(u);let m=1.1271005818144368*c-.11060664309660323*l-.016493938717834573*u,h=-.1413297634984383*c+1.157823702216272*l-.016493938717834257*u,g=-.14132976349843826*c-.11060664309660294*l+1.2519364065950405*u;m=Math.max(0,m)**2.2,h=Math.max(0,h)**2.2,g=Math.max(0,g)**2.2,i[0]=Ni(1.6605*m-.5876*h-.0728*g),i[1]=Ni(-.1246*m+1.1329*h-.0083*g),i[2]=Ni(-.0182*m-.1006*h+1.1187*g)}function Mi(e,t,n,r,i){let a=.76;e*=r,t*=r,n*=r;let o=Math.min(e,Math.min(t,n)),s=o<.08?o-6.25*o*o:.04;e-=s,t-=s,n-=s;let c=Math.max(e,Math.max(t,n));if(c<a){i[0]=e,i[1]=t,i[2]=n;return}let l=1-a,u=1-l*l/(c+l-a),d=u/c;e*=d,t*=d,n*=d;let f=1-1/(.15*(c-u)+1);i[0]=e+(u-e)*f,i[1]=t+(u-t)*f,i[2]=n+(u-n)*f}var Ni,Pi,Fi,Ii,Li,Ri,zi,Bi=y((()=>{Ni=e=>Math.min(Math.max(e,0),1),Pi=`
|
|
116
116
|
fn tm_reinhard( c: vec3<f32> ) -> vec3<f32> {
|
|
117
117
|
return clamp( c / ( c + vec3<f32>( 1.0 ) ), vec3<f32>( 0.0 ), vec3<f32>( 1.0 ) );
|
|
118
118
|
}
|
|
@@ -1072,7 +1072,7 @@ fn main( @builtin(global_invocation_id) gid: vec3<u32> ) {
|
|
|
1072
1072
|
// survives the denoise.
|
|
1073
1073
|
textureStore( dst, vec2<u32>( px, py ), vec4<f32>( src[ si ].xyz / scaleBuf[ 0 ], inColor[ si ].w ) );
|
|
1074
1074
|
}
|
|
1075
|
-
`,Fy=class extends r.EventDispatcher{constructor(e,t={}){if(super(),!e)throw Error(`OIDNDenoiser requires a renderer`);this.renderer=e,this._renderWidth=e.domElement.width,this._renderHeight=e.domElement.height,this.backendParamsGetter=t.backendParams||null,this.getGPUTextures=t.getGPUTextures||null,this.gpuDevice=null,this._gpuInputBuffers={color:null,albedo:null,normal:null},this._gpuInputBufferSize={width:0,height:0},this._gpuInputPadBuffer=null,this._gpuInputPaddedRowBytes=0,this._lumReducePipeline=null,this._lumFinalizePipeline=null,this._lumLayout=null,this._lumBindGroup=null,this._lumPartials=null,this._lumParams=null,this._inputScaleBuffer=null,this._colorScalePipeline=null,this._colorScaleBindGroup=null,this._unpackPipeline=null,this._outGPUTexture=null,this._outTexture=null,this._outTexSize={width:0,height:0},this.config={...wy.DEFAULT_OPTIONS,...t},this.enabled=this.config.enableOIDN,this.quality=this.config.oidnQuality,this.maxTileSize=this.config.tileSize,this._activeTileSize=0,this.state={isDenoising:!1,isLoading:!1,abortController:null},this._tilesWritten=0,this._runId=0,this._hasOutput=!1,this.lastDenoiseMs=0,this.currentTZAUrl=null,this.unet=null,this._pendingStart=!1,this._pendingStartContinuous=!1,this._reloadPending=!1,this._initialize().catch(e=>{by.error(`init failed:`,e),this.dispatchEvent({type:`error`,error:e})})}async _initialize(){try{await this._setupUNetDenoiser()}catch(e){throw Error(`Initialization failed: ${e.message}`)}}expectsCleanAux(e=this.quality){let{QUALITY_MODELS:t}=wy;return(t[e]||t.balance).cleanAux}getRuntimeInfo(){return this.unet?.getRuntimeInfo?.()??null}profileNextDenoise(){return this.unet?.profileNextExecution?.()??!1}async getLastDenoiseProfile(){return await this.unet?.getLastExecutionProfile?.()??null}_resolveTileSize(){let e=Math.max(this._renderWidth,this._renderHeight);if(!e)return this.maxTileSize;let t=Math.ceil(e/xy)*xy;return t<=this.maxTileSize?t:Math.max(xy,Math.floor(this.maxTileSize/xy)*xy)}async _setupUNetDenoiser(){if(this.state.isLoading){this._reloadPending=!0;return}do{this._reloadPending=!1,this.state.isLoading=!0;try{await this._loadUNetWeights()}catch(e){by.error(`UNet weights failed to load:`,e),this.dispatchEvent({type:`error`,error:Error(`Denoiser loading failed: ${e.message}`)})}finally{this.state.isLoading=!1}}while(this._reloadPending);if(this._pendingStart&&this.unet&&this.enabled){let e=this._pendingStartContinuous;this._pendingStart=!1,this._pendingStartContinuous=!1,this.start({continuous:e})}}async _loadUNetWeights(){let e=this._generateTzaUrl(),t=this._resolveTileSize();if(this.currentTZAUrl===e&&this._activeTileSize===t&&this.unet)return;this.dispatchEvent({type:`loading`,message:`Loading UNet denoiser...`}),this.unet&&=(this.unet.dispose(),null);let n;if(this.backendParamsGetter){let e=this.backendParamsGetter();this.gpuDevice=e?.device??null,n=e?.device?e:void 0}this.unet=await(await Cy())(e,n,{aux:!0,hdr:!0,maxTileSize:t,dynamicTile:!1}),this.currentTZAUrl=e,this._activeTileSize=t,this.dispatchEvent({type:`loaded`}),by.debug(`UNet weights loaded:`,e)}_generateTzaUrl(){let{oidnWeightsBaseUrl:e}=Or(),{QUALITY_MODELS:t}=wy;return`${e}${(t[this.quality]||t.balance).model}.tza`}async updateConfiguration(e){Object.keys(e).some(t=>this.config[t]!==e[t])&&(Object.assign(this.config,e),this.quality=this.config.oidnQuality,this.maxTileSize=this.config.tileSize,await this._setupUNetDenoiser())}async updateQuality(e){if(!Object.prototype.hasOwnProperty.call(wy.QUALITY_MODELS,e))throw Error(`Invalid quality setting: ${e}. Must be one of: ${Object.keys(wy.QUALITY_MODELS).join(`, `)}`);await this.updateConfiguration({oidnQuality:e})}async start({continuous:e=!1}={}){if(!this.enabled||this.state.isDenoising)return!1;if(this.unet&&!this.state.isLoading&&this._activeTileSize!==this._resolveTileSize()&&await this._setupUNetDenoiser(),this.state.isLoading)return this._pendingStartContinuous=this._pendingStart?this._pendingStartContinuous&&e:e,this._pendingStart=!0,!1;this.dispatchEvent({type:`start`,continuous:e});let t=performance.now(),n=await this.execute(e);return n&&(this.renderer?.resetState?.(),this.lastDenoiseMs=performance.now()-t,by.debug(`denoise complete in ${Y.ms(this.lastDenoiseMs)} · quality ${this.quality}`)),n}async execute(e=!1){if(!this.enabled||!this.unet)return!1;let t=++this._runId;this.state.abortController=new AbortController,this.state.isDenoising=!0;try{return await this._executeUNetGPU(e)!==!1}catch(e){return e.name===`AbortError`?by.debug(`denoise aborted`):by.error(`denoise error:`,e),!1}finally{this._runId===t&&(this.state.isDenoising=!1,this.state.abortController=null),this.dispatchEvent({type:`end`,continuous:e})}}async _executeUNetGPU(e=!1){let t=this._renderWidth,n=this._renderHeight;if(!this.getGPUTextures)return by.warn(`GPU mode enabled but getGPUTextures not provided`),!1;let r=this.getGPUTextures();if(!r?.color)return by.warn(`GPU textures not ready yet`),!1;let i=this.gpuDevice;if(!i)return by.warn(`gpuDevice not available`),!1;this._ensureGPUInputBuffers(t,n);let a=i.createCommandEncoder({label:`oidn-tex-to-buf`}),o=t*16,s=this._gpuInputPaddedRowBytes,c=s>o,l=this._gpuInputPadBuffer,u=(e,r)=>{if(!c)a.copyTextureToBuffer({texture:e,mipLevel:0},{buffer:r,offset:0,bytesPerRow:o,rowsPerImage:n},{width:t,height:n,depthOrArrayLayers:1});else{a.copyTextureToBuffer({texture:e,mipLevel:0},{buffer:l,offset:0,bytesPerRow:s,rowsPerImage:n},{width:t,height:n,depthOrArrayLayers:1});for(let e=0;e<n;e++)a.copyBufferToBuffer(l,e*s,r,e*o,o)}};u(r.color,this._gpuInputBuffers.color),u(r.albedo,this._gpuInputBuffers.albedo),u(r.normal,this._gpuInputBuffers.normal),i.queue.submit([a.finish()]),this._computeInputScale(i,t*n),this._applyColorScale(i,t*n);let d={color:{data:this._gpuInputBuffers.color,width:t,height:n},albedo:{data:this._gpuInputBuffers.albedo,width:t,height:n},normal:{data:this._gpuInputBuffers.normal,width:t,height:n}};return this._executeWithAbortGPU(d,e)}_ensureGPUInputBuffers(e,t){let{width:n,height:r}=this._gpuInputBufferSize;if(n===e&&r===t&&this._gpuInputBuffers.color)return;this._destroyGPUInputBuffers();let i=this.gpuDevice,a=e*t*16,o=GPUBufferUsage.COPY_DST|GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC;this._gpuInputBuffers.color=i.createBuffer({label:`oidn-in-color`,size:a,usage:o}),this._gpuInputBuffers.albedo=i.createBuffer({label:`oidn-in-albedo`,size:a,usage:o}),this._gpuInputBuffers.normal=i.createBuffer({label:`oidn-in-normal`,size:a,usage:o}),this._gpuInputBufferSize={width:e,height:t};let s=e*16,c=Math.ceil(s/256)*256;c===s?this._gpuInputPaddedRowBytes=s:(this._gpuInputPadBuffer=i.createBuffer({label:`oidn-in-pad`,size:c*t,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.COPY_SRC}),this._gpuInputPaddedRowBytes=c)}_destroyGPUInputBuffers(){this._gpuInputBuffers.color?.destroy(),this._gpuInputBuffers.albedo?.destroy(),this._gpuInputBuffers.normal?.destroy(),this._gpuInputPadBuffer?.destroy(),this._colorScaleBindGroup=null,this._lumBindGroup=null,this._lumPartials?.destroy(),this._lumPartials=null,this._lumParams?.destroy(),this._lumParams=null,this._inputScaleBuffer?.destroy(),this._inputScaleBuffer=null,this._gpuInputBuffers={color:null,albedo:null,normal:null},this._gpuInputPadBuffer=null,this._gpuInputPaddedRowBytes=0,this._gpuInputBufferSize={width:0,height:0}}_ensureScalePipelines(e){let t=this._gpuInputBuffers.color;if(!e||!t)return!1;if(!this._lumLayout){this._lumLayout=e.createBindGroupLayout({label:`oidn-autoexposure`,entries:[{binding:0,visibility:GPUShaderStage.COMPUTE,buffer:{type:`read-only-storage`}},{binding:1,visibility:GPUShaderStage.COMPUTE,buffer:{type:`storage`}},{binding:2,visibility:GPUShaderStage.COMPUTE,buffer:{type:`uniform`}},{binding:3,visibility:GPUShaderStage.COMPUTE,buffer:{type:`storage`}}]});let t=e.createShaderModule({label:`oidn-autoexposure`,code:Oy}),n=e.createPipelineLayout({bindGroupLayouts:[this._lumLayout]});this._lumReducePipeline=e.createComputePipeline({label:`oidn-autoexposure-reduce`,layout:n,compute:{module:t,entryPoint:`reduce`}}),this._lumFinalizePipeline=e.createComputePipeline({label:`oidn-autoexposure-finalize`,layout:n,compute:{module:t,entryPoint:`finalize`}})}return this._colorScalePipeline||=e.createComputePipeline({label:`oidn-color-scale`,layout:`auto`,compute:{module:e.createShaderModule({label:`oidn-color-scale`,code:ky}),entryPoint:`main`}}),this._unpackPipeline||=e.createComputePipeline({label:`oidn-output-unpack`,layout:`auto`,compute:{module:e.createShaderModule({label:`oidn-output-unpack`,code:Py}),entryPoint:`main`}}),this._inputScaleBuffer||(this._inputScaleBuffer=e.createBuffer({label:`oidn-input-scale`,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST|GPUBufferUsage.COPY_SRC,size:4}),this._lumPartials=e.createBuffer({label:`oidn-autoexposure-partials`,size:Dy*4,usage:GPUBufferUsage.STORAGE}),this._lumParams=e.createBuffer({label:`oidn-autoexposure-params`,size:16,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST})),this._lumBindGroup||=e.createBindGroup({label:`oidn-autoexposure`,layout:this._lumLayout,entries:[{binding:0,resource:{buffer:t}},{binding:1,resource:{buffer:this._lumPartials}},{binding:2,resource:{buffer:this._lumParams}},{binding:3,resource:{buffer:this._inputScaleBuffer}}]}),this._colorScaleBindGroup||=e.createBindGroup({label:`oidn-color-scale`,layout:this._colorScalePipeline.getBindGroupLayout(0),entries:[{binding:0,resource:{buffer:t}},{binding:1,resource:{buffer:this._inputScaleBuffer}}]}),!0}_computeInputScale(e,t){if(!this._ensureScalePipelines(e))return;if(globalThis.__OIDN_NO_INPUT_SCALE){e.queue.writeBuffer(this._inputScaleBuffer,0,new Float32Array([1]));return}e.queue.writeBuffer(this._lumParams,0,new Uint32Array([t,0,0,0]));let n=e.createCommandEncoder({label:`oidn-autoexposure`}),r=n.beginComputePass({label:`oidn-autoexposure-reduce`});r.setPipeline(this._lumReducePipeline),r.setBindGroup(0,this._lumBindGroup),r.dispatchWorkgroups(Dy,1,1),r.end();let i=n.beginComputePass({label:`oidn-autoexposure-finalize`});i.setPipeline(this._lumFinalizePipeline),i.setBindGroup(0,this._lumBindGroup),i.dispatchWorkgroups(1,1,1),i.end(),e.queue.submit([n.finish()])}_applyColorScale(e,t){if(!this._ensureScalePipelines(e))return;let n=Math.ceil(t/Ay),r=Math.min(n,jy),i=Math.ceil(n/r),a=e.createCommandEncoder({label:`oidn-color-scale`}),o=a.beginComputePass({label:`oidn-color-scale`});o.setPipeline(this._colorScalePipeline),o.setBindGroup(0,this._colorScaleBindGroup),o.dispatchWorkgroups(r,i,1),o.end(),e.queue.submit([a.finish()])}get outputTexture(){return this._outTexture}_ensureOutputTexture(e,n,i){if(this._outGPUTexture&&this._outTexSize.width===n&&this._outTexSize.height===i)return;this._releaseOutputTexture(),this._outGPUTexture=e.createTexture({label:`oidn-output`,size:{width:n,height:i,depthOrArrayLayers:1},format:`rgba16float`,usage:GPUTextureUsage.STORAGE_BINDING|GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_SRC});let a=new t.ExternalTexture(this._outGPUTexture);a.name=`oidn:output`,a.image={width:n,height:i,depth:1},a.type=r.HalfFloatType,a.format=r.RGBAFormat,a.colorSpace=r.NoColorSpace,a.minFilter=r.NearestFilter,a.magFilter=r.NearestFilter,a.wrapS=r.ClampToEdgeWrapping,a.wrapT=r.ClampToEdgeWrapping,a.generateMipmaps=!1,a.flipY=!1,this._outTexture=a,this._outTexSize={width:n,height:i}}_releaseOutputTexture(){this._outTexture?.dispose(),this._outGPUTexture?.destroy(),this._outTexture=null,this._outGPUTexture=null,this._outTexSize={width:0,height:0}}_unpackToTexture(e,t,n){let r=this.gpuDevice;if(!r||!this._ensureScalePipelines(r))return;let{x:i,y:a,width:o,height:s}=n;if(this._ensureOutputTexture(r,this._renderWidth,this._renderHeight),!this._outGPUTexture)return;let c=r.createBuffer({label:`oidn-unpack-params`,size:Ny,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST});try{r.queue.writeBuffer(c,0,new Uint32Array([t,i,a,o,s,0,0,0]));let n=r.createBindGroup({label:`oidn-output-unpack`,layout:this._unpackPipeline.getBindGroupLayout(0),entries:[{binding:0,resource:{buffer:e}},{binding:1,resource:{buffer:c}},{binding:2,resource:{buffer:this._inputScaleBuffer}},{binding:3,resource:{buffer:this._gpuInputBuffers.color}},{binding:4,resource:this._outGPUTexture.createView()}]}),l=r.createCommandEncoder({label:`oidn-output-unpack`}),u=l.beginComputePass({label:`oidn-output-unpack`});u.setPipeline(this._unpackPipeline),u.setBindGroup(0,n),u.dispatchWorkgroups(Math.ceil(o/My),Math.ceil(s/My),1),u.end(),r.queue.submit([l.finish()]),this._hasOutput=!0}finally{c.destroy()}}_executeWithAbortGPU(e,t=!1){return new Promise((n,r)=>{if(this.state.abortController?.signal.aborted){r(new DOMException(`Aborted`,`AbortError`));return}let i=null;this._tilesWritten=0;let a=()=>{i&&=(i(),null),r(new DOMException(`Aborted`,`AbortError`))};this.state.abortController.signal.addEventListener(`abort`,a,{once:!0}),i=this.unet.tileExecute({...e,done:async e=>{this.state.abortController.signal.removeEventListener(`abort`,a),i=null;try{this._tilesWritten===0&&this._displayGPUOutput(e),n()}catch(e){r(e)}},progress:(e,n,r)=>{if(!e?.data||!r)return;let i=e.width,a=e.height,o=Math.min(r.width,i-r.x),s=Math.min(r.height,a-r.y);if(o<=0||s<=0)return;let c={x:r.x,y:r.y,width:o,height:s};this._unpackToTexture(e.data,i,c),this._tilesWritten++,this.dispatchEvent({type:`tileProgress`,tile:c,imageWidth:i,imageHeight:a,continuous:t})}})})}_displayGPUOutput({data:e,width:t,height:n}){if(!this.gpuDevice){by.error(`gpuDevice not available for the output picture`);return}this._unpackToTexture(e,t,{x:0,y:0,width:t,height:n})}abort(){this._pendingStart=!1,this._pendingStartContinuous=!1,!(!this.enabled||!this.state.isDenoising)&&(this.state.abortController?.abort(),this.state.isDenoising=!1,by.debug(`denoise aborted`))}get hasOutput(){return this._hasOutput}invalidateOutput(){this._hasOutput=!1}setSize(e,t){if(e<=0||t<=0)throw Error(`Invalid dimensions: ${e}x${t}`);this._renderWidth=e,this._renderHeight=t,this._hasOutput=!1,this.lastDenoiseMs=0,this._setupUNetDenoiser().catch(e=>{by.error(`reinitialize after size change failed:`,e)})}dispose(){this.abort(),this.unet?.dispose(),this._destroyGPUInputBuffers(),this._releaseOutputTexture(),this._colorScalePipeline=null,this._lumReducePipeline=null,this._lumFinalizePipeline=null,this._lumLayout=null,this._unpackPipeline=null,this.unet=null,this.state.abortController=null,this.removeAllListeners?.(),by.debug(`disposed`)}},Iy='let e={ortRuntimeUrl:`https://cdn.jsdelivr.net/npm/onnxruntime-web@1.24.3/dist/ort.webgpu.bundle.min.mjs`,ortWasmPaths:`https://cdn.jsdelivr.net/npm/onnxruntime-web@1.24.3/dist/`,cacheNamespace:`rayzee`},t=null;async function n(){return t||(t=await import(e.ortRuntimeUrl),t.env.wasm.wasmPaths=e.ortWasmPaths,t.env.logLevel=`error`,t)}function r(){return`${e.cacheNamespace}:ai-upscaler-models`}const i=`models`;let a=null,o=null;function s(){return new Promise((e,t)=>{let n=indexedDB.open(r(),1);n.onupgradeneeded=()=>n.result.createObjectStore(i),n.onsuccess=()=>e(n.result),n.onerror=()=>t(n.error)})}async function c(e){try{let t=await s();return await new Promise((n,r)=>{let a=t.transaction(i,`readonly`).objectStore(i).get(e);a.onsuccess=()=>n(a.result||null),a.onerror=()=>r(a.error)})}catch{return null}}async function l(e,t){try{let n=await s();await new Promise((r,a)=>{let o=n.transaction(i,`readwrite`);o.objectStore(i).put(t,e),o.oncomplete=()=>r(),o.onerror=()=>a(o.error)})}catch{}}async function u(e){let t=await c(e);if(t)return console.log(`AI Upscaler Worker: model loaded from cache (${(t.byteLength/1024/1024).toFixed(1)}MB)`),t;let n=await fetch(e);if(!n.ok)throw Error(`Failed to fetch model: ${n.status}`);let r=await n.arrayBuffer();return l(e,r.slice(0)),r}async function d(e,t){if(a&&o===e){self.postMessage({type:`loaded`,backend:`webgpu`});return}a&&=(await a.release(),null);let[r,i]=await Promise.all([u(e),n()]);a=await i.InferenceSession.create(r,t),o=e;let s=512;try{let e=await navigator.gpu?.requestAdapter(),t=await e?.requestAdapterInfo?.()||e?.info,n=/apple|swiftshader|llvmpipe/i.test(t?.vendor||``)||/apple|swiftshader/i.test(t?.architecture||``),r=t?.device?.toLowerCase?.()?.includes(`integrated`)||/intel.*iris|intel.*uhd|intel.*hd|amd.*vega|radeon.*graphics/i.test(t?.description||``);s=n?128:r?256:512,console.log(`AI Upscaler Worker: GPU="${t?.description||t?.device||`unknown`}", tileSize=${s}`)}catch{}let c=(r.byteLength/1024/1024).toFixed(1);console.log(`AI Upscaler Worker: model loaded (${c}MB), backend: webgpu`),self.postMessage({type:`loaded`,backend:`webgpu`,tileSize:s})}async function f(e,t,r,i){let o=await n(),s=a.inputNames[0],c=a.outputNames[0],l=new o.Tensor(`float32`,e,[1,3,r,t]),u=(await a.run({[s]:l}))[c].data;self.postMessage({type:`inferred`,outputData:u,id:i},[u.buffer])}self.onmessage=async t=>{let{type:n}=t.data;try{n===`load`?(t.data.ortRuntimeUrl&&(e.ortRuntimeUrl=t.data.ortRuntimeUrl),t.data.ortWasmPaths&&(e.ortWasmPaths=t.data.ortWasmPaths),t.data.cacheNamespace&&(e.cacheNamespace=t.data.cacheNamespace),await d(t.data.url,t.data.sessionOptions)):n===`infer`?await f(t.data.tileData,t.data.width,t.data.height,t.data.id):n===`dispose`&&a&&(await a.release(),a=null,o=null)}catch(e){self.postMessage({type:`error`,message:e.message,id:t.data?.id})}};',Ly=typeof self<`u`&&self.Blob&&new Blob([`URL.revokeObjectURL(import.meta.url);`,Iy],{type:`text/javascript;charset=utf-8`});function Ry(e){let t;try{if(t=Ly&&(self.URL||self.webkitURL).createObjectURL(Ly),!t)throw``;let n=new Worker(t,{type:`module`,name:e?.name});return n.addEventListener(`error`,()=>{(self.URL||self.webkitURL).revokeObjectURL(t)}),n}catch{return new Worker(`data:text/javascript;charset=utf-8,`+encodeURIComponent(Iy),{type:`module`,name:e?.name})}}Ar();var zy=e=>sd(e)?(e=>e>1?1:e<0?0:e):(e=>e**+cd),By={fast:{2:`2x-spanx2-ch48.onnx`,4:`4xNomos8k_span_otf_strong_fp32_opset17.onnx`},balanced:{2:`2xNomosUni_compact_otf_medium.onnx`,4:`RealESRGAN_x4plus.onnx`},quality:{2:`2x-realesrgan-x2plus.onnx`,4:`4xNomos2_hq_mosr_fp32.onnx`}};function Vy(){let{upscalerModelBaseUrl:e}=Or(),t={};for(let n in By){t[n]={};for(let r in By[n])t[n][r]=e+By[n][r]}return t}var Hy={get QUALITY_PRESETS(){return Vy()},TILE_SIZE:512,TILE_OVERLAP:16,SESSION_OPTIONS:{executionProviders:[{name:`webgpu`,preferredLayout:`NCHW`}],graphOptimizationLevel:`all`}},Uy=class extends r.EventDispatcher{constructor(e,t,n={}){if(super(),!e||!t)throw Error(`AIUpscaler requires output canvas and renderer`);this.renderer=t,this.input=t.domElement,this.output=e,this.getSourceCanvas=n.getSourceCanvas||null,this.getGPUTextures=n.getGPUTextures||null,this.getExposure=n.getExposure||(()=>1),this.getToneMapping=n.getToneMapping||(()=>r.ACESFilmicToneMapping),this.getSaturation=n.getSaturation||(()=>1),this.enabled=!1,this.hdr=!1,this.scaleFactor=n.scaleFactor||2,this.quality=n.quality||`fast`,this.refreshInput=n.refreshInput||null,this.tileSize=n.tileSize||Hy.TILE_SIZE,this._tileSizeOverride=!!n.tileSize,this.state={isUpscaling:!1,isLoading:!1,abortController:null},this._worker=null,this._currentModelUrl=null,this._tileId=0,this._pendingWorkerHandlers=new Set,this._upscaledAlpha=null,this._upscaledAlphaWidth=0,this._backupCanvas=null,this._baseWidth=e.width,this._baseHeight=e.height,this._hdrStagingBuffer=null,this._hdrStagingWidth=0,this._hdrStagingHeight=0}async _ensureSession(){let e=Hy.QUALITY_PRESETS[this.quality];if(!e)throw Error(`Unknown quality preset: ${this.quality}`);let t=e[this.scaleFactor];if(!t)throw Error(`No model for ${this.quality}/${this.scaleFactor}x`);if(!(this._worker&&this._currentModelUrl===t)){this.state.isLoading=!0,this.dispatchEvent({type:`loading`,message:`Loading ${this.scaleFactor}x upscale model...`});try{this._worker||=new Ry,await new Promise((e,n)=>{let r=t=>{t.data.type===`loaded`?(this._worker.removeEventListener(`message`,r),t.data.tileSize&&!this._tileSizeOverride&&(this.tileSize=t.data.tileSize),console.log(`AI Upscaler: ${this.scaleFactor}x model loaded, backend: ${t.data.backend}, tileSize: ${this.tileSize}`),e()):t.data.type===`error`&&(this._worker.removeEventListener(`message`,r),n(Error(t.data.message)))},{ortRuntimeUrl:i,ortWasmPaths:a,cacheNamespace:o}=Or();this._worker.addEventListener(`message`,r),this._worker.postMessage({type:`load`,url:t,sessionOptions:Hy.SESSION_OPTIONS,ortRuntimeUrl:i,ortWasmPaths:a,cacheNamespace:o})}),this._currentModelUrl=t,this.dispatchEvent({type:`loaded`})}catch(e){throw console.error(`AI Upscaler: Failed to load model:`,e),this.dispatchEvent({type:`error`,error:e}),e}finally{this.state.isLoading=!1}}}async start(){if(!this.enabled||this.state.isUpscaling||this.state.isLoading)return!1;this.dispatchEvent({type:`start`});let e=performance.now(),t=await this.execute();if(t){this.renderer?.resetState?.();let t=performance.now()-e;console.log(`AI Upscaler: ${this.scaleFactor}x upscale completed in ${t.toFixed(1)}ms`)}return t}_revealOutput(){this.output.style.display=`block`,this.input.style.opacity=`0`}async execute(){if(!this.enabled)return!1;this.state.abortController=new AbortController,this.state.isUpscaling=!0,this.hdr&&this.getGPUTextures?this._capturedSource=await this._captureSourceHDR():this._capturedSource=this._captureSource(),this._createBackup(this._capturedSource);let e=this._capturedSource.width*this.scaleFactor,t=this._capturedSource.height*this.scaleFactor;this.output.width=e,this.output.height=t;let n=this.output.getContext(`2d`,{willReadFrequently:!0,alpha:!0});n.imageSmoothingEnabled=!0,n.imageSmoothingQuality=`high`,n.drawImage(this._backupCanvas,0,0,e,t),this._revealOutput();try{return await this._ensureSession(),await this._runUpscale(),this.dispatchEvent({type:`resolution_changed`,width:this.output.width,height:this.output.height}),!0}catch(e){return e.name===`AbortError`?console.log(`AI Upscaler: Upscaling was aborted`):(console.error(`AI Upscaler: Upscaling error:`,e),this.dispatchEvent({type:`error`,error:e}),this._restoreBackup(),this.input.style.opacity=`1`,this.dispatchEvent({type:`resolution_changed`,width:this._baseWidth,height:this._baseHeight})),!1}finally{this._capturedSource=null,this._upscaledAlpha=null,this._backupCanvas=null,this.state.isUpscaling&&(this.state.isUpscaling=!1,this.state.abortController=null,this.dispatchEvent({type:`end`}))}}abort(){this.state.isUpscaling&&(this.state.abortController?.abort(),this._cleanupPendingWorkerHandlers(),this.input.style.opacity=`1`,this._restoreBackup(),this.dispatchEvent({type:`resolution_changed`,width:this._baseWidth,height:this._baseHeight}),this.state.isUpscaling=!1,this.dispatchEvent({type:`end`}),console.log(`AI Upscaler: Aborted`))}async _runUpscale(){let e=this.state.abortController.signal,t=this._capturedSource;this._capturedSource=null;let{width:n,height:i}=t,a=this.scaleFactor,o=this.output.getContext(`2d`,{willReadFrequently:!0,alpha:!0});this._cacheUpscaledAlpha(t,n*a,i*a),t.isHDR&&(this._hdrToneMapFn=ad.get(this.getToneMapping())||ad.get(r.ACESFilmicToneMapping),this._hdrEncode=zy(this.getToneMapping()),this._hdrExposure=ud(this.getExposure(),this.getToneMapping()),this._hdrSaturation=this.getSaturation(),this._tmOut=new Float32Array(3));let s=Hy.TILE_OVERLAP,c=this.tileSize,l=c-s*2,u=Math.ceil(n/l),d=Math.ceil(i/l),f=u*d,p=0;for(let r=0;r<d;r++)for(let s=0;s<u;s++){if(e.aborted)throw new DOMException(`Aborted`,`AbortError`);let u=Math.min(s*l,Math.max(0,n-c)),d=Math.min(r*l,Math.max(0,i-c)),m=Math.min(c,n-u),h=Math.min(c,i-d),g=this._extractTile(t,u,d,m,h),_=await this._inferTile(g,m,h),v=u*a,y=d*a,b=m*a,x=h*a,S=this._tensorToImageData(_,b,x,v,y);o.putImageData(S,v,y),p++,this.dispatchEvent({type:`progress`,progress:p/f,tile:{x:s,y:r,total:f,completed:p}}),this.dispatchEvent({type:`tileProgress`,tile:{x:v,y,width:b,height:x},imageWidth:n*a,imageHeight:i*a})}}_captureSource(){let e=this.getSourceCanvas?this.getSourceCanvas():null;if(e&&e!==this.output){this.refreshInput?.();let t=document.createElement(`canvas`);t.width=e.width,t.height=e.height;let n=t.getContext(`2d`);return n.drawImage(e,0,0),n.getImageData(0,0,t.width,t.height)}return this.output.getContext(`2d`,{willReadFrequently:!0}).getImageData(0,0,this.output.width,this.output.height)}async _captureSourceHDR(){let e=this.getGPUTextures();if(!e?.color)throw Error(`No GPU color texture available for HDR capture`);let t=this.renderer.backend.device,n=e.color,r=n.width,i=n.height,a=Math.ceil(r*16/256)*256,o=a*i;(this._hdrStagingWidth!==r||this._hdrStagingHeight!==i)&&(this._hdrStagingBuffer?.destroy(),this._hdrStagingBuffer=t.createBuffer({label:`aiupscaler-hdr-readback`,size:o,usage:GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST}),this._hdrStagingWidth=r,this._hdrStagingHeight=i);let s=this._hdrStagingBuffer,c=t.createCommandEncoder();c.copyTextureToBuffer({texture:n},{buffer:s,bytesPerRow:a,rowsPerImage:i},{width:r,height:i,depthOrArrayLayers:1}),t.queue.submit([c.finish()]),await s.mapAsync(GPUMapMode.READ);let l=new Float32Array(s.getMappedRange()),u=r*4,d=a/4,f=new Float32Array(r*i*4);for(let e=0;e<i;e++){let t=e*d,n=e*u;f.set(l.subarray(t,t+u),n)}return s.unmap(),{data:f,width:r,height:i,isHDR:!0}}_extractTile(e,t,n,r,i){let{data:a,width:o}=e,s=e.isHDR,c=r*i,l=new Float32Array(3*c);for(let e=0;e<i;e++)for(let i=0;i<r;i++){let u=((n+e)*o+(t+i))*4,d=e*r+i;if(s){let e=this._hdrToneMapFn,t=this._hdrExposure,n=this._hdrSaturation,r=a[u]*t,i=a[u+1]*t,o=a[u+2]*t;n!==1&&(this._tmOut[0]=r,this._tmOut[1]=i,this._tmOut[2]=o,md(this._tmOut,n),r=this._tmOut[0],i=this._tmOut[1],o=this._tmOut[2]),e(r,i,o,1,this._tmOut);let s=this._hdrEncode;l[d]=s(this._tmOut[0]),l[c+d]=s(this._tmOut[1]),l[2*c+d]=s(this._tmOut[2])}else l[d]=a[u]/255,l[c+d]=a[u+1]/255,l[2*c+d]=a[u+2]/255}return l}async _inferTile(e,t,n){let r=++this._tileId;return new Promise((i,a)=>{let o=e=>{e.data.id===r&&(this._worker.removeEventListener(`message`,o),this._pendingWorkerHandlers.delete(o),e.data.type===`inferred`?i(e.data.outputData):e.data.type===`error`&&a(Error(e.data.message)))};this._pendingWorkerHandlers.add(o),this._worker.addEventListener(`message`,o),this._worker.postMessage({type:`infer`,tileData:e,width:t,height:n,id:r},[e.buffer])})}_tensorToImageData(e,t,n,r,i){let a=new ImageData(t,n),o=a.data,s=t*n,c=this._upscaledAlpha,l=this._upscaledAlphaWidth;for(let n=0;n<s;n++)if(o[n*4]=Math.min(255,Math.max(0,e[n]*255+.5))|0,o[n*4+1]=Math.min(255,Math.max(0,e[s+n]*255+.5))|0,o[n*4+2]=Math.min(255,Math.max(0,e[2*s+n]*255+.5))|0,c){let e=n/t|0,a=n%t;o[n*4+3]=c[(i+e)*l+(r+a)]}else o[n*4+3]=255;return a}_cacheUpscaledAlpha(e,t,n){let{data:r,width:i,height:a}=e,o=e.isHDR,s=o?1:255,c=!1;for(let e=3;e<r.length;e+=4)if(r[e]<s){c=!0;break}if(!c){this._upscaledAlpha=null,this._upscaledAlphaWidth=0;return}let l=document.createElement(`canvas`);l.width=i,l.height=a;let u=l.getContext(`2d`),d=u.createImageData(i,a);for(let e=0,t=i*a;e<t;e++){let t=o?Math.min(Math.max(r[e*4+3]*255,0),255)|0:r[e*4+3];d.data[e*4]=t,d.data[e*4+1]=t,d.data[e*4+2]=t,d.data[e*4+3]=255}u.putImageData(d,0,0);let f=document.createElement(`canvas`);f.width=t,f.height=n;let p=f.getContext(`2d`);p.imageSmoothingEnabled=!0,p.imageSmoothingQuality=`high`,p.drawImage(l,0,0,t,n);let m=p.getImageData(0,0,t,n).data,h=new Uint8Array(t*n);for(let e=0,r=t*n;e<r;e++)h[e]=m[e*4];this._upscaledAlpha=h,this._upscaledAlphaWidth=t}_createBackup(e){this._backupCanvas=document.createElement(`canvas`),this._backupCanvas.width=e.width,this._backupCanvas.height=e.height;let t=this._backupCanvas.getContext(`2d`);if(e.isHDR){let{data:n,width:i,height:a}=e,o=t.createImageData(i,a),s=o.data,c=ad.get(this.getToneMapping())||ad.get(r.ACESFilmicToneMapping),l=ud(this.getExposure(),this.getToneMapping()),u=zy(this.getToneMapping()),d=this.getSaturation(),f=new Float32Array(3);for(let e=0,t=i*a;e<t;e++){let t=e*4,r=n[t]*l,i=n[t+1]*l,a=n[t+2]*l;d!==1&&(f[0]=r,f[1]=i,f[2]=a,md(f,d),r=f[0],i=f[1],a=f[2]),c(r,i,a,1,f),s[t]=u(f[0])*255+.5|0,s[t+1]=u(f[1])*255+.5|0,s[t+2]=u(f[2])*255+.5|0,s[t+3]=255}t.putImageData(o,0,0)}else t.putImageData(e,0,0)}_restoreBackup(){this._backupCanvas&&=(this.output.width=this._backupCanvas.width,this.output.height=this._backupCanvas.height,this.output.getContext(`2d`).drawImage(this._backupCanvas,0,0),null)}toggleHDR(e){this.hdr=!!e}setQuality(e){if(!Hy.QUALITY_PRESETS[e]){console.warn(`AIUpscaler: Invalid quality "${e}", must be fast/balanced/quality`);return}this.quality=e}setScaleFactor(e){if(e=Number(e),e!==2&&e!==4){console.warn(`AIUpscaler: Invalid scale factor ${e}, must be 2 or 4`);return}this.scaleFactor=e}setBaseSize(e,t){this._baseWidth=e,this._baseHeight=t}_cleanupPendingWorkerHandlers(){if(this._worker)for(let e of this._pendingWorkerHandlers)this._worker.removeEventListener(`message`,e);this._pendingWorkerHandlers.clear()}async dispose(){this.abort(),this._cleanupPendingWorkerHandlers(),this._worker&&=(this._worker.postMessage({type:`dispose`}),this._worker.terminate(),null),this._currentModelUrl=null,this._backupCanvas=null,this._upscaledAlpha=null,this.state.abortController=null,this._hdrStagingBuffer?.destroy(),this._hdrStagingBuffer=null,this._hdrStagingWidth=0,this._hdrStagingHeight=0,console.log(`AIUpscaler disposed`)}};function Wy(){let{wgsl:e,bindings:t}=Qi({group:Gy,firstBinding:Ky});return{wgsl:e,bindings:t,version:Hi()}}var Gy,Ky,qy,Jy,Yy,Xy=y((()=>{ca(),Gy=0,Ky=3,Wy().wgsl,qy=e=>`
|
|
1075
|
+
`,Fy=class extends r.EventDispatcher{constructor(e,t={}){if(super(),!e)throw Error(`OIDNDenoiser requires a renderer`);this.renderer=e,this._renderWidth=e.domElement.width,this._renderHeight=e.domElement.height,this.backendParamsGetter=t.backendParams||null,this.getGPUTextures=t.getGPUTextures||null,this.gpuDevice=null,this._gpuInputBuffers={color:null,albedo:null,normal:null},this._gpuInputBufferSize={width:0,height:0},this._gpuInputPadBuffer=null,this._gpuInputPaddedRowBytes=0,this._lumReducePipeline=null,this._lumFinalizePipeline=null,this._lumLayout=null,this._lumBindGroup=null,this._lumPartials=null,this._lumParams=null,this._inputScaleBuffer=null,this._colorScalePipeline=null,this._colorScaleBindGroup=null,this._unpackPipeline=null,this._outGPUTexture=null,this._outTexture=null,this._outTexSize={width:0,height:0},this.config={...wy.DEFAULT_OPTIONS,...t},this.enabled=this.config.enableOIDN,this.quality=this.config.oidnQuality,this.maxTileSize=this.config.tileSize,this._activeTileSize=0,this.state={isDenoising:!1,isLoading:!1,abortController:null},this._tilesWritten=0,this._runId=0,this._hasOutput=!1,this.lastDenoiseMs=0,this.currentTZAUrl=null,this.unet=null,this._pendingStart=!1,this._pendingStartContinuous=!1,this._reloadPending=!1,this._initialize().catch(e=>{by.error(`init failed:`,e),this.dispatchEvent({type:`error`,error:e})})}async _initialize(){try{await this._setupUNetDenoiser()}catch(e){throw Error(`Initialization failed: ${e.message}`)}}expectsCleanAux(e=this.quality){let{QUALITY_MODELS:t}=wy;return(t[e]||t.balance).cleanAux}getRuntimeInfo(){return this.unet?.getRuntimeInfo?.()??null}profileNextDenoise(){return this.unet?.profileNextExecution?.()??!1}async getLastDenoiseProfile(){return await this.unet?.getLastExecutionProfile?.()??null}_resolveTileSize(){let e=Math.max(this._renderWidth,this._renderHeight);if(!e)return this.maxTileSize;let t=Math.ceil(e/xy)*xy;return t<=this.maxTileSize?t:Math.max(xy,Math.floor(this.maxTileSize/xy)*xy)}async _setupUNetDenoiser(){if(this.state.isLoading){this._reloadPending=!0;return}do{this._reloadPending=!1,this.state.isLoading=!0;try{await this._loadUNetWeights()}catch(e){by.error(`UNet weights failed to load:`,e),this.dispatchEvent({type:`error`,error:Error(`Denoiser loading failed: ${e.message}`)})}finally{this.state.isLoading=!1}}while(this._reloadPending);if(this._pendingStart&&this.unet&&this.enabled){let e=this._pendingStartContinuous;this._pendingStart=!1,this._pendingStartContinuous=!1,this.start({continuous:e})}}async _loadUNetWeights(){let e=this._generateTzaUrl(),t=this._resolveTileSize();if(this.currentTZAUrl===e&&this._activeTileSize===t&&this.unet)return;this.dispatchEvent({type:`loading`,message:`Loading UNet denoiser...`}),this.unet&&=(this.unet.dispose(),null);let n;if(this.backendParamsGetter){let e=this.backendParamsGetter();this.gpuDevice=e?.device??null,n=e?.device?e:void 0}this.unet=await(await Cy())(e,n,{aux:!0,hdr:!0,maxTileSize:t,dynamicTile:!1}),this.currentTZAUrl=e,this._activeTileSize=t,this.dispatchEvent({type:`loaded`}),by.debug(`UNet weights loaded:`,e)}_generateTzaUrl(){let{oidnWeightsBaseUrl:e}=Or(),{QUALITY_MODELS:t}=wy;return`${e}${(t[this.quality]||t.balance).model}.tza`}async updateConfiguration(e){Object.keys(e).some(t=>this.config[t]!==e[t])&&(Object.assign(this.config,e),this.quality=this.config.oidnQuality,this.maxTileSize=this.config.tileSize,await this._setupUNetDenoiser())}async updateQuality(e){if(!Object.prototype.hasOwnProperty.call(wy.QUALITY_MODELS,e))throw Error(`Invalid quality setting: ${e}. Must be one of: ${Object.keys(wy.QUALITY_MODELS).join(`, `)}`);await this.updateConfiguration({oidnQuality:e})}async start({continuous:e=!1}={}){if(!this.enabled||this.state.isDenoising)return!1;if(this.unet&&!this.state.isLoading&&this._activeTileSize!==this._resolveTileSize()&&await this._setupUNetDenoiser(),this.state.isLoading)return this._pendingStartContinuous=this._pendingStart?this._pendingStartContinuous&&e:e,this._pendingStart=!0,!1;this.dispatchEvent({type:`start`,continuous:e});let t=performance.now(),n=await this.execute(e);return n&&(this.renderer?.resetState?.(),this.lastDenoiseMs=performance.now()-t,by.debug(`denoise complete in ${Y.ms(this.lastDenoiseMs)} · quality ${this.quality}`)),n}async execute(e=!1){if(!this.enabled||!this.unet)return!1;let t=++this._runId;this.state.abortController=new AbortController,this.state.isDenoising=!0;try{return await this._executeUNetGPU(e)!==!1}catch(e){return e.name===`AbortError`?by.debug(`denoise aborted`):by.error(`denoise error:`,e),!1}finally{this._runId===t&&(this.state.isDenoising=!1,this.state.abortController=null),this.dispatchEvent({type:`end`,continuous:e})}}async _executeUNetGPU(e=!1){let t=this._renderWidth,n=this._renderHeight;if(!this.getGPUTextures)return by.warn(`GPU mode enabled but getGPUTextures not provided`),!1;let r=this.getGPUTextures();if(!r?.color)return by.warn(`GPU textures not ready yet`),!1;let i=this.gpuDevice;if(!i)return by.warn(`gpuDevice not available`),!1;this._ensureGPUInputBuffers(t,n);let a=i.createCommandEncoder({label:`oidn-tex-to-buf`}),o=t*16,s=this._gpuInputPaddedRowBytes,c=s>o,l=this._gpuInputPadBuffer,u=(e,r)=>{if(!c)a.copyTextureToBuffer({texture:e,mipLevel:0},{buffer:r,offset:0,bytesPerRow:o,rowsPerImage:n},{width:t,height:n,depthOrArrayLayers:1});else{a.copyTextureToBuffer({texture:e,mipLevel:0},{buffer:l,offset:0,bytesPerRow:s,rowsPerImage:n},{width:t,height:n,depthOrArrayLayers:1});for(let e=0;e<n;e++)a.copyBufferToBuffer(l,e*s,r,e*o,o)}};u(r.color,this._gpuInputBuffers.color),u(r.albedo,this._gpuInputBuffers.albedo),u(r.normal,this._gpuInputBuffers.normal),i.queue.submit([a.finish()]),this._computeInputScale(i,t*n),this._applyColorScale(i,t*n),!e&&!this._hasOutput&&this._unpackToTexture(this._gpuInputBuffers.color,t,{x:0,y:0,width:t,height:n},!1);let d={color:{data:this._gpuInputBuffers.color,width:t,height:n},albedo:{data:this._gpuInputBuffers.albedo,width:t,height:n},normal:{data:this._gpuInputBuffers.normal,width:t,height:n}};return this._executeWithAbortGPU(d,e)}_ensureGPUInputBuffers(e,t){let{width:n,height:r}=this._gpuInputBufferSize;if(n===e&&r===t&&this._gpuInputBuffers.color)return;this._destroyGPUInputBuffers();let i=this.gpuDevice,a=e*t*16,o=GPUBufferUsage.COPY_DST|GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC;this._gpuInputBuffers.color=i.createBuffer({label:`oidn-in-color`,size:a,usage:o}),this._gpuInputBuffers.albedo=i.createBuffer({label:`oidn-in-albedo`,size:a,usage:o}),this._gpuInputBuffers.normal=i.createBuffer({label:`oidn-in-normal`,size:a,usage:o}),this._gpuInputBufferSize={width:e,height:t};let s=e*16,c=Math.ceil(s/256)*256;c===s?this._gpuInputPaddedRowBytes=s:(this._gpuInputPadBuffer=i.createBuffer({label:`oidn-in-pad`,size:c*t,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.COPY_SRC}),this._gpuInputPaddedRowBytes=c)}_destroyGPUInputBuffers(){this._gpuInputBuffers.color?.destroy(),this._gpuInputBuffers.albedo?.destroy(),this._gpuInputBuffers.normal?.destroy(),this._gpuInputPadBuffer?.destroy(),this._colorScaleBindGroup=null,this._lumBindGroup=null,this._lumPartials?.destroy(),this._lumPartials=null,this._lumParams?.destroy(),this._lumParams=null,this._inputScaleBuffer?.destroy(),this._inputScaleBuffer=null,this._gpuInputBuffers={color:null,albedo:null,normal:null},this._gpuInputPadBuffer=null,this._gpuInputPaddedRowBytes=0,this._gpuInputBufferSize={width:0,height:0}}_ensureScalePipelines(e){let t=this._gpuInputBuffers.color;if(!e||!t)return!1;if(!this._lumLayout){this._lumLayout=e.createBindGroupLayout({label:`oidn-autoexposure`,entries:[{binding:0,visibility:GPUShaderStage.COMPUTE,buffer:{type:`read-only-storage`}},{binding:1,visibility:GPUShaderStage.COMPUTE,buffer:{type:`storage`}},{binding:2,visibility:GPUShaderStage.COMPUTE,buffer:{type:`uniform`}},{binding:3,visibility:GPUShaderStage.COMPUTE,buffer:{type:`storage`}}]});let t=e.createShaderModule({label:`oidn-autoexposure`,code:Oy}),n=e.createPipelineLayout({bindGroupLayouts:[this._lumLayout]});this._lumReducePipeline=e.createComputePipeline({label:`oidn-autoexposure-reduce`,layout:n,compute:{module:t,entryPoint:`reduce`}}),this._lumFinalizePipeline=e.createComputePipeline({label:`oidn-autoexposure-finalize`,layout:n,compute:{module:t,entryPoint:`finalize`}})}return this._colorScalePipeline||=e.createComputePipeline({label:`oidn-color-scale`,layout:`auto`,compute:{module:e.createShaderModule({label:`oidn-color-scale`,code:ky}),entryPoint:`main`}}),this._unpackPipeline||=e.createComputePipeline({label:`oidn-output-unpack`,layout:`auto`,compute:{module:e.createShaderModule({label:`oidn-output-unpack`,code:Py}),entryPoint:`main`}}),this._inputScaleBuffer||(this._inputScaleBuffer=e.createBuffer({label:`oidn-input-scale`,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST|GPUBufferUsage.COPY_SRC,size:4}),this._lumPartials=e.createBuffer({label:`oidn-autoexposure-partials`,size:Dy*4,usage:GPUBufferUsage.STORAGE}),this._lumParams=e.createBuffer({label:`oidn-autoexposure-params`,size:16,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST})),this._lumBindGroup||=e.createBindGroup({label:`oidn-autoexposure`,layout:this._lumLayout,entries:[{binding:0,resource:{buffer:t}},{binding:1,resource:{buffer:this._lumPartials}},{binding:2,resource:{buffer:this._lumParams}},{binding:3,resource:{buffer:this._inputScaleBuffer}}]}),this._colorScaleBindGroup||=e.createBindGroup({label:`oidn-color-scale`,layout:this._colorScalePipeline.getBindGroupLayout(0),entries:[{binding:0,resource:{buffer:t}},{binding:1,resource:{buffer:this._inputScaleBuffer}}]}),!0}_computeInputScale(e,t){if(!this._ensureScalePipelines(e))return;if(globalThis.__OIDN_NO_INPUT_SCALE){e.queue.writeBuffer(this._inputScaleBuffer,0,new Float32Array([1]));return}e.queue.writeBuffer(this._lumParams,0,new Uint32Array([t,0,0,0]));let n=e.createCommandEncoder({label:`oidn-autoexposure`}),r=n.beginComputePass({label:`oidn-autoexposure-reduce`});r.setPipeline(this._lumReducePipeline),r.setBindGroup(0,this._lumBindGroup),r.dispatchWorkgroups(Dy,1,1),r.end();let i=n.beginComputePass({label:`oidn-autoexposure-finalize`});i.setPipeline(this._lumFinalizePipeline),i.setBindGroup(0,this._lumBindGroup),i.dispatchWorkgroups(1,1,1),i.end(),e.queue.submit([n.finish()])}_applyColorScale(e,t){if(!this._ensureScalePipelines(e))return;let n=Math.ceil(t/Ay),r=Math.min(n,jy),i=Math.ceil(n/r),a=e.createCommandEncoder({label:`oidn-color-scale`}),o=a.beginComputePass({label:`oidn-color-scale`});o.setPipeline(this._colorScalePipeline),o.setBindGroup(0,this._colorScaleBindGroup),o.dispatchWorkgroups(r,i,1),o.end(),e.queue.submit([a.finish()])}get outputTexture(){return this._outTexture}_ensureOutputTexture(e,n,i){if(this._outGPUTexture&&this._outTexSize.width===n&&this._outTexSize.height===i)return;this._releaseOutputTexture(),this._outGPUTexture=e.createTexture({label:`oidn-output`,size:{width:n,height:i,depthOrArrayLayers:1},format:`rgba16float`,usage:GPUTextureUsage.STORAGE_BINDING|GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_SRC});let a=new t.ExternalTexture(this._outGPUTexture);a.name=`oidn:output`,a.image={width:n,height:i,depth:1},a.type=r.HalfFloatType,a.format=r.RGBAFormat,a.colorSpace=r.NoColorSpace,a.minFilter=r.NearestFilter,a.magFilter=r.NearestFilter,a.wrapS=r.ClampToEdgeWrapping,a.wrapT=r.ClampToEdgeWrapping,a.generateMipmaps=!1,a.flipY=!1,this._outTexture=a,this._outTexSize={width:n,height:i}}_releaseOutputTexture(){this._outTexture?.dispose(),this._outGPUTexture?.destroy(),this._outTexture=null,this._outGPUTexture=null,this._outTexSize={width:0,height:0}}_unpackToTexture(e,t,n,r=!0){let i=this.gpuDevice;if(!i||!this._ensureScalePipelines(i))return;let{x:a,y:o,width:s,height:c}=n;if(this._ensureOutputTexture(i,this._renderWidth,this._renderHeight),!this._outGPUTexture)return;let l=i.createBuffer({label:`oidn-unpack-params`,size:Ny,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST});try{i.queue.writeBuffer(l,0,new Uint32Array([t,a,o,s,c,0,0,0]));let n=i.createBindGroup({label:`oidn-output-unpack`,layout:this._unpackPipeline.getBindGroupLayout(0),entries:[{binding:0,resource:{buffer:e}},{binding:1,resource:{buffer:l}},{binding:2,resource:{buffer:this._inputScaleBuffer}},{binding:3,resource:{buffer:this._gpuInputBuffers.color}},{binding:4,resource:this._outGPUTexture.createView()}]}),u=i.createCommandEncoder({label:`oidn-output-unpack`}),d=u.beginComputePass({label:`oidn-output-unpack`});d.setPipeline(this._unpackPipeline),d.setBindGroup(0,n),d.dispatchWorkgroups(Math.ceil(s/My),Math.ceil(c/My),1),d.end(),i.queue.submit([u.finish()]),r&&(this._hasOutput=!0)}finally{l.destroy()}}_executeWithAbortGPU(e,t=!1){return new Promise((n,r)=>{if(this.state.abortController?.signal.aborted){r(new DOMException(`Aborted`,`AbortError`));return}let i=null;this._tilesWritten=0;let a=()=>{i&&=(i(),null),r(new DOMException(`Aborted`,`AbortError`))};this.state.abortController.signal.addEventListener(`abort`,a,{once:!0}),i=this.unet.tileExecute({...e,done:async e=>{this.state.abortController.signal.removeEventListener(`abort`,a),i=null;try{this._tilesWritten===0&&this._displayGPUOutput(e),n()}catch(e){r(e)}},progress:(e,n,r)=>{if(!e?.data||!r)return;let i=e.width,a=e.height,o=Math.min(r.width,i-r.x),s=Math.min(r.height,a-r.y);if(o<=0||s<=0)return;let c={x:r.x,y:r.y,width:o,height:s};this._unpackToTexture(e.data,i,c),this._tilesWritten++,this.dispatchEvent({type:`tileProgress`,tile:c,imageWidth:i,imageHeight:a,continuous:t})}})})}_displayGPUOutput({data:e,width:t,height:n}){if(!this.gpuDevice){by.error(`gpuDevice not available for the output picture`);return}this._unpackToTexture(e,t,{x:0,y:0,width:t,height:n})}abort(){this._pendingStart=!1,this._pendingStartContinuous=!1,!(!this.enabled||!this.state.isDenoising)&&(this.state.abortController?.abort(),this.state.isDenoising=!1,by.debug(`denoise aborted`))}get hasOutput(){return this._hasOutput}invalidateOutput(){this._hasOutput=!1}setSize(e,t){if(e<=0||t<=0)throw Error(`Invalid dimensions: ${e}x${t}`);this._renderWidth=e,this._renderHeight=t,this._hasOutput=!1,this.lastDenoiseMs=0,this._setupUNetDenoiser().catch(e=>{by.error(`reinitialize after size change failed:`,e)})}dispose(){this.abort(),this.unet?.dispose(),this._destroyGPUInputBuffers(),this._releaseOutputTexture(),this._colorScalePipeline=null,this._lumReducePipeline=null,this._lumFinalizePipeline=null,this._lumLayout=null,this._unpackPipeline=null,this.unet=null,this.state.abortController=null,this.removeAllListeners?.(),by.debug(`disposed`)}},Iy='let e={ortRuntimeUrl:`https://cdn.jsdelivr.net/npm/onnxruntime-web@1.24.3/dist/ort.webgpu.bundle.min.mjs`,ortWasmPaths:`https://cdn.jsdelivr.net/npm/onnxruntime-web@1.24.3/dist/`,cacheNamespace:`rayzee`},t=null;async function n(){return t||(t=await import(e.ortRuntimeUrl),t.env.wasm.wasmPaths=e.ortWasmPaths,t.env.logLevel=`error`,t)}function r(){return`${e.cacheNamespace}:ai-upscaler-models`}const i=`models`;let a=null,o=null;function s(){return new Promise((e,t)=>{let n=indexedDB.open(r(),1);n.onupgradeneeded=()=>n.result.createObjectStore(i),n.onsuccess=()=>e(n.result),n.onerror=()=>t(n.error)})}async function c(e){try{let t=await s();return await new Promise((n,r)=>{let a=t.transaction(i,`readonly`).objectStore(i).get(e);a.onsuccess=()=>n(a.result||null),a.onerror=()=>r(a.error)})}catch{return null}}async function l(e,t){try{let n=await s();await new Promise((r,a)=>{let o=n.transaction(i,`readwrite`);o.objectStore(i).put(t,e),o.oncomplete=()=>r(),o.onerror=()=>a(o.error)})}catch{}}async function u(e){let t=await c(e);if(t)return console.log(`AI Upscaler Worker: model loaded from cache (${(t.byteLength/1024/1024).toFixed(1)}MB)`),t;let n=await fetch(e);if(!n.ok)throw Error(`Failed to fetch model: ${n.status}`);let r=await n.arrayBuffer();return l(e,r.slice(0)),r}async function d(e,t){if(a&&o===e){self.postMessage({type:`loaded`,backend:`webgpu`});return}a&&=(await a.release(),null);let[r,i]=await Promise.all([u(e),n()]);a=await i.InferenceSession.create(r,t),o=e;let s=512;try{let e=await navigator.gpu?.requestAdapter(),t=await e?.requestAdapterInfo?.()||e?.info,n=/apple|swiftshader|llvmpipe/i.test(t?.vendor||``)||/apple|swiftshader/i.test(t?.architecture||``),r=t?.device?.toLowerCase?.()?.includes(`integrated`)||/intel.*iris|intel.*uhd|intel.*hd|amd.*vega|radeon.*graphics/i.test(t?.description||``);s=n?128:r?256:512,console.log(`AI Upscaler Worker: GPU="${t?.description||t?.device||`unknown`}", tileSize=${s}`)}catch{}let c=(r.byteLength/1024/1024).toFixed(1);console.log(`AI Upscaler Worker: model loaded (${c}MB), backend: webgpu`),self.postMessage({type:`loaded`,backend:`webgpu`,tileSize:s})}async function f(e,t,r,i){let o=await n(),s=a.inputNames[0],c=a.outputNames[0],l=new o.Tensor(`float32`,e,[1,3,r,t]),u=(await a.run({[s]:l}))[c].data;self.postMessage({type:`inferred`,outputData:u,id:i},[u.buffer])}self.onmessage=async t=>{let{type:n}=t.data;try{n===`load`?(t.data.ortRuntimeUrl&&(e.ortRuntimeUrl=t.data.ortRuntimeUrl),t.data.ortWasmPaths&&(e.ortWasmPaths=t.data.ortWasmPaths),t.data.cacheNamespace&&(e.cacheNamespace=t.data.cacheNamespace),await d(t.data.url,t.data.sessionOptions)):n===`infer`?await f(t.data.tileData,t.data.width,t.data.height,t.data.id):n===`dispose`&&a&&(await a.release(),a=null,o=null)}catch(e){self.postMessage({type:`error`,message:e.message,id:t.data?.id})}};',Ly=typeof self<`u`&&self.Blob&&new Blob([`URL.revokeObjectURL(import.meta.url);`,Iy],{type:`text/javascript;charset=utf-8`});function Ry(e){let t;try{if(t=Ly&&(self.URL||self.webkitURL).createObjectURL(Ly),!t)throw``;let n=new Worker(t,{type:`module`,name:e?.name});return n.addEventListener(`error`,()=>{(self.URL||self.webkitURL).revokeObjectURL(t)}),n}catch{return new Worker(`data:text/javascript;charset=utf-8,`+encodeURIComponent(Iy),{type:`module`,name:e?.name})}}Ar();var zy=e=>sd(e)?(e=>e>1?1:e<0?0:e):(e=>e**+cd),By={fast:{2:`2x-spanx2-ch48.onnx`,4:`4xNomos8k_span_otf_strong_fp32_opset17.onnx`},balanced:{2:`2xNomosUni_compact_otf_medium.onnx`,4:`RealESRGAN_x4plus.onnx`},quality:{2:`2x-realesrgan-x2plus.onnx`,4:`4xNomos2_hq_mosr_fp32.onnx`}};function Vy(){let{upscalerModelBaseUrl:e}=Or(),t={};for(let n in By){t[n]={};for(let r in By[n])t[n][r]=e+By[n][r]}return t}var Hy={get QUALITY_PRESETS(){return Vy()},TILE_SIZE:512,TILE_OVERLAP:16,SESSION_OPTIONS:{executionProviders:[{name:`webgpu`,preferredLayout:`NCHW`}],graphOptimizationLevel:`all`}},Uy=class extends r.EventDispatcher{constructor(e,t,n={}){if(super(),!e||!t)throw Error(`AIUpscaler requires output canvas and renderer`);this.renderer=t,this.input=t.domElement,this.output=e,this.getSourceCanvas=n.getSourceCanvas||null,this.getGPUTextures=n.getGPUTextures||null,this.getExposure=n.getExposure||(()=>1),this.getToneMapping=n.getToneMapping||(()=>r.ACESFilmicToneMapping),this.getSaturation=n.getSaturation||(()=>1),this.enabled=!1,this.hdr=!1,this.scaleFactor=n.scaleFactor||2,this.quality=n.quality||`fast`,this.refreshInput=n.refreshInput||null,this.tileSize=n.tileSize||Hy.TILE_SIZE,this._tileSizeOverride=!!n.tileSize,this.state={isUpscaling:!1,isLoading:!1,abortController:null},this._worker=null,this._currentModelUrl=null,this._tileId=0,this._pendingWorkerHandlers=new Set,this._upscaledAlpha=null,this._upscaledAlphaWidth=0,this._backupCanvas=null,this._baseWidth=e.width,this._baseHeight=e.height,this._hdrStagingBuffer=null,this._hdrStagingWidth=0,this._hdrStagingHeight=0}async _ensureSession(){let e=Hy.QUALITY_PRESETS[this.quality];if(!e)throw Error(`Unknown quality preset: ${this.quality}`);let t=e[this.scaleFactor];if(!t)throw Error(`No model for ${this.quality}/${this.scaleFactor}x`);if(!(this._worker&&this._currentModelUrl===t)){this.state.isLoading=!0,this.dispatchEvent({type:`loading`,message:`Loading ${this.scaleFactor}x upscale model...`});try{this._worker||=new Ry,await new Promise((e,n)=>{let r=t=>{t.data.type===`loaded`?(this._worker.removeEventListener(`message`,r),t.data.tileSize&&!this._tileSizeOverride&&(this.tileSize=t.data.tileSize),console.log(`AI Upscaler: ${this.scaleFactor}x model loaded, backend: ${t.data.backend}, tileSize: ${this.tileSize}`),e()):t.data.type===`error`&&(this._worker.removeEventListener(`message`,r),n(Error(t.data.message)))},{ortRuntimeUrl:i,ortWasmPaths:a,cacheNamespace:o}=Or();this._worker.addEventListener(`message`,r),this._worker.postMessage({type:`load`,url:t,sessionOptions:Hy.SESSION_OPTIONS,ortRuntimeUrl:i,ortWasmPaths:a,cacheNamespace:o})}),this._currentModelUrl=t,this.dispatchEvent({type:`loaded`})}catch(e){throw console.error(`AI Upscaler: Failed to load model:`,e),this.dispatchEvent({type:`error`,error:e}),e}finally{this.state.isLoading=!1}}}async start(){if(!this.enabled||this.state.isUpscaling||this.state.isLoading)return!1;this.dispatchEvent({type:`start`});let e=performance.now(),t=await this.execute();if(t){this.renderer?.resetState?.();let t=performance.now()-e;console.log(`AI Upscaler: ${this.scaleFactor}x upscale completed in ${t.toFixed(1)}ms`)}return t}_revealOutput(){this.output.style.display=`block`,this.input.style.opacity=`0`}async execute(){if(!this.enabled)return!1;this.state.abortController=new AbortController,this.state.isUpscaling=!0,this.hdr&&this.getGPUTextures?this._capturedSource=await this._captureSourceHDR():this._capturedSource=this._captureSource(),this._createBackup(this._capturedSource);let e=this._capturedSource.width*this.scaleFactor,t=this._capturedSource.height*this.scaleFactor;this.output.width=e,this.output.height=t;let n=this.output.getContext(`2d`,{willReadFrequently:!0,alpha:!0});n.imageSmoothingEnabled=!0,n.imageSmoothingQuality=`high`,n.drawImage(this._backupCanvas,0,0,e,t),this._revealOutput();try{return await this._ensureSession(),await this._runUpscale(),this.dispatchEvent({type:`resolution_changed`,width:this.output.width,height:this.output.height}),!0}catch(e){return e.name===`AbortError`?console.log(`AI Upscaler: Upscaling was aborted`):(console.error(`AI Upscaler: Upscaling error:`,e),this.dispatchEvent({type:`error`,error:e}),this._restoreBackup(),this.input.style.opacity=`1`,this.dispatchEvent({type:`resolution_changed`,width:this._baseWidth,height:this._baseHeight})),!1}finally{this._capturedSource=null,this._upscaledAlpha=null,this._backupCanvas=null,this.state.isUpscaling&&(this.state.isUpscaling=!1,this.state.abortController=null,this.dispatchEvent({type:`end`}))}}abort(){this.state.isUpscaling&&(this.state.abortController?.abort(),this._cleanupPendingWorkerHandlers(),this.input.style.opacity=`1`,this._restoreBackup(),this.dispatchEvent({type:`resolution_changed`,width:this._baseWidth,height:this._baseHeight}),this.state.isUpscaling=!1,this.dispatchEvent({type:`end`}),console.log(`AI Upscaler: Aborted`))}async _runUpscale(){let e=this.state.abortController.signal,t=this._capturedSource;this._capturedSource=null;let{width:n,height:i}=t,a=this.scaleFactor,o=this.output.getContext(`2d`,{willReadFrequently:!0,alpha:!0});this._cacheUpscaledAlpha(t,n*a,i*a),t.isHDR&&(this._hdrToneMapFn=ad.get(this.getToneMapping())||ad.get(r.ACESFilmicToneMapping),this._hdrEncode=zy(this.getToneMapping()),this._hdrExposure=ud(this.getExposure(),this.getToneMapping()),this._hdrSaturation=this.getSaturation(),this._tmOut=new Float32Array(3));let s=Hy.TILE_OVERLAP,c=this.tileSize,l=c-s*2,u=Math.ceil(n/l),d=Math.ceil(i/l),f=u*d,p=0;for(let r=0;r<d;r++)for(let s=0;s<u;s++){if(e.aborted)throw new DOMException(`Aborted`,`AbortError`);let u=Math.min(s*l,Math.max(0,n-c)),d=Math.min(r*l,Math.max(0,i-c)),m=Math.min(c,n-u),h=Math.min(c,i-d),g=this._extractTile(t,u,d,m,h),_=await this._inferTile(g,m,h),v=u*a,y=d*a,b=m*a,x=h*a,S=this._tensorToImageData(_,b,x,v,y);o.putImageData(S,v,y),p++,this.dispatchEvent({type:`progress`,progress:p/f,tile:{x:s,y:r,total:f,completed:p}}),this.dispatchEvent({type:`tileProgress`,tile:{x:v,y,width:b,height:x},imageWidth:n*a,imageHeight:i*a})}}_captureSource(){let e=this.getSourceCanvas?this.getSourceCanvas():null;if(e&&e!==this.output){this.refreshInput?.();let t=document.createElement(`canvas`);t.width=e.width,t.height=e.height;let n=t.getContext(`2d`);return n.drawImage(e,0,0),n.getImageData(0,0,t.width,t.height)}return this.output.getContext(`2d`,{willReadFrequently:!0}).getImageData(0,0,this.output.width,this.output.height)}async _captureSourceHDR(){let e=this.getGPUTextures();if(!e?.color)throw Error(`No GPU color texture available for HDR capture`);let t=this.renderer.backend.device,n=e.color,r=n.width,i=n.height,a=Math.ceil(r*16/256)*256,o=a*i;(this._hdrStagingWidth!==r||this._hdrStagingHeight!==i)&&(this._hdrStagingBuffer?.destroy(),this._hdrStagingBuffer=t.createBuffer({label:`aiupscaler-hdr-readback`,size:o,usage:GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST}),this._hdrStagingWidth=r,this._hdrStagingHeight=i);let s=this._hdrStagingBuffer,c=t.createCommandEncoder();c.copyTextureToBuffer({texture:n},{buffer:s,bytesPerRow:a,rowsPerImage:i},{width:r,height:i,depthOrArrayLayers:1}),t.queue.submit([c.finish()]),await s.mapAsync(GPUMapMode.READ);let l=new Float32Array(s.getMappedRange()),u=r*4,d=a/4,f=new Float32Array(r*i*4);for(let e=0;e<i;e++){let t=e*d,n=e*u;f.set(l.subarray(t,t+u),n)}return s.unmap(),{data:f,width:r,height:i,isHDR:!0}}_extractTile(e,t,n,r,i){let{data:a,width:o}=e,s=e.isHDR,c=r*i,l=new Float32Array(3*c);for(let e=0;e<i;e++)for(let i=0;i<r;i++){let u=((n+e)*o+(t+i))*4,d=e*r+i;if(s){let e=this._hdrToneMapFn,t=this._hdrExposure,n=this._hdrSaturation,r=a[u]*t,i=a[u+1]*t,o=a[u+2]*t;n!==1&&(this._tmOut[0]=r,this._tmOut[1]=i,this._tmOut[2]=o,md(this._tmOut,n),r=this._tmOut[0],i=this._tmOut[1],o=this._tmOut[2]),e(r,i,o,1,this._tmOut);let s=this._hdrEncode;l[d]=s(this._tmOut[0]),l[c+d]=s(this._tmOut[1]),l[2*c+d]=s(this._tmOut[2])}else l[d]=a[u]/255,l[c+d]=a[u+1]/255,l[2*c+d]=a[u+2]/255}return l}async _inferTile(e,t,n){let r=++this._tileId;return new Promise((i,a)=>{let o=e=>{e.data.id===r&&(this._worker.removeEventListener(`message`,o),this._pendingWorkerHandlers.delete(o),e.data.type===`inferred`?i(e.data.outputData):e.data.type===`error`&&a(Error(e.data.message)))};this._pendingWorkerHandlers.add(o),this._worker.addEventListener(`message`,o),this._worker.postMessage({type:`infer`,tileData:e,width:t,height:n,id:r},[e.buffer])})}_tensorToImageData(e,t,n,r,i){let a=new ImageData(t,n),o=a.data,s=t*n,c=this._upscaledAlpha,l=this._upscaledAlphaWidth;for(let n=0;n<s;n++)if(o[n*4]=Math.min(255,Math.max(0,e[n]*255+.5))|0,o[n*4+1]=Math.min(255,Math.max(0,e[s+n]*255+.5))|0,o[n*4+2]=Math.min(255,Math.max(0,e[2*s+n]*255+.5))|0,c){let e=n/t|0,a=n%t;o[n*4+3]=c[(i+e)*l+(r+a)]}else o[n*4+3]=255;return a}_cacheUpscaledAlpha(e,t,n){let{data:r,width:i,height:a}=e,o=e.isHDR,s=o?1:255,c=!1;for(let e=3;e<r.length;e+=4)if(r[e]<s){c=!0;break}if(!c){this._upscaledAlpha=null,this._upscaledAlphaWidth=0;return}let l=document.createElement(`canvas`);l.width=i,l.height=a;let u=l.getContext(`2d`),d=u.createImageData(i,a);for(let e=0,t=i*a;e<t;e++){let t=o?Math.min(Math.max(r[e*4+3]*255,0),255)|0:r[e*4+3];d.data[e*4]=t,d.data[e*4+1]=t,d.data[e*4+2]=t,d.data[e*4+3]=255}u.putImageData(d,0,0);let f=document.createElement(`canvas`);f.width=t,f.height=n;let p=f.getContext(`2d`);p.imageSmoothingEnabled=!0,p.imageSmoothingQuality=`high`,p.drawImage(l,0,0,t,n);let m=p.getImageData(0,0,t,n).data,h=new Uint8Array(t*n);for(let e=0,r=t*n;e<r;e++)h[e]=m[e*4];this._upscaledAlpha=h,this._upscaledAlphaWidth=t}_createBackup(e){this._backupCanvas=document.createElement(`canvas`),this._backupCanvas.width=e.width,this._backupCanvas.height=e.height;let t=this._backupCanvas.getContext(`2d`);if(e.isHDR){let{data:n,width:i,height:a}=e,o=t.createImageData(i,a),s=o.data,c=ad.get(this.getToneMapping())||ad.get(r.ACESFilmicToneMapping),l=ud(this.getExposure(),this.getToneMapping()),u=zy(this.getToneMapping()),d=this.getSaturation(),f=new Float32Array(3);for(let e=0,t=i*a;e<t;e++){let t=e*4,r=n[t]*l,i=n[t+1]*l,a=n[t+2]*l;d!==1&&(f[0]=r,f[1]=i,f[2]=a,md(f,d),r=f[0],i=f[1],a=f[2]),c(r,i,a,1,f),s[t]=u(f[0])*255+.5|0,s[t+1]=u(f[1])*255+.5|0,s[t+2]=u(f[2])*255+.5|0,s[t+3]=255}t.putImageData(o,0,0)}else t.putImageData(e,0,0)}_restoreBackup(){this._backupCanvas&&=(this.output.width=this._backupCanvas.width,this.output.height=this._backupCanvas.height,this.output.getContext(`2d`).drawImage(this._backupCanvas,0,0),null)}toggleHDR(e){this.hdr=!!e}setQuality(e){if(!Hy.QUALITY_PRESETS[e]){console.warn(`AIUpscaler: Invalid quality "${e}", must be fast/balanced/quality`);return}this.quality=e}setScaleFactor(e){if(e=Number(e),e!==2&&e!==4){console.warn(`AIUpscaler: Invalid scale factor ${e}, must be 2 or 4`);return}this.scaleFactor=e}setBaseSize(e,t){this._baseWidth=e,this._baseHeight=t}_cleanupPendingWorkerHandlers(){if(this._worker)for(let e of this._pendingWorkerHandlers)this._worker.removeEventListener(`message`,e);this._pendingWorkerHandlers.clear()}async dispose(){this.abort(),this._cleanupPendingWorkerHandlers(),this._worker&&=(this._worker.postMessage({type:`dispose`}),this._worker.terminate(),null),this._currentModelUrl=null,this._backupCanvas=null,this._upscaledAlpha=null,this.state.abortController=null,this._hdrStagingBuffer?.destroy(),this._hdrStagingBuffer=null,this._hdrStagingWidth=0,this._hdrStagingHeight=0,console.log(`AIUpscaler disposed`)}};function Wy(){let{wgsl:e,bindings:t}=Qi({group:Gy,firstBinding:Ky});return{wgsl:e,bindings:t,version:Hi()}}var Gy,Ky,qy,Jy,Yy,Xy=y((()=>{ca(),Gy=0,Ky=3,Wy().wgsl,qy=e=>`
|
|
1076
1076
|
struct Params {
|
|
1077
1077
|
width: u32,
|
|
1078
1078
|
height: u32,
|
|
@@ -1103,7 +1103,7 @@ fn main( @builtin(global_invocation_id) gid: vec3<u32> ) {
|
|
|
1103
1103
|
let b8 = rayzee_to_u8( rayzee_encode( mapped, params.mode ) );
|
|
1104
1104
|
dst[ gid.y * params.width + gid.x ] = b8.x | ( b8.y << 8u ) | ( b8.z << 16u ) | ( 255u << 24u );
|
|
1105
1105
|
}
|
|
1106
|
-
`,Jy=32,Yy=class{constructor(e,t=`rayzee:tonemap`){this.device=e,this.label=t,this.width=0,this.height=0,this._pipeline=null,this._storage=null,this._map=null,this._params=null,this._paramData=new ArrayBuffer(Jy),this._paramU32=new Uint32Array(this._paramData),this._paramF32=new Float32Array(this._paramData),this._shaderVersion=-1,this._bindings=[],this._tables=new Map,this.disposed=!1}_ensurePipeline(){let{wgsl:e,bindings:t,version:n}=Wy();this._pipeline&&this._shaderVersion===n||(this._bindings=t,this._shaderVersion=n,this._pipeline=this.device.createComputePipeline({label:this.label,layout:`auto`,compute:{module:this.device.createShaderModule({label:this.label,code:qy(e)}),entryPoint:`main`}}))}_ensureTables(){let e=new Set;for(let{index:t,transform:n}of this._bindings){let{data:r,size:i}=n.table;e.add(t);let a=this._tables.get(t);if(a&&a.data===r)continue;a?.texture.destroy();let o=this.device.createTexture({label:`${this.label}-${n.wgslConst}`,size:[i,i,i],dimension:`3d`,format:`rgba16float`,usage:GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_DST});this.device.queue.writeTexture({texture:o},r,{bytesPerRow:i*8,rowsPerImage:i},[i,i,i]),this._tables.set(t,{texture:o,data:r,view:o.createView()})}for(let[t,n]of this._tables)e.has(t)||(n.texture.destroy(),this._tables.delete(t))}ensureSize(e,t){if(this._ensurePipeline(),this._ensureTables(),this.width===e&&this.height===t&&this._storage)return;this._releaseBuffers();let n=e*t*4;this._storage=this.device.createBuffer({label:`${this.label}-out`,size:n,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC}),this._map=this.device.createBuffer({label:`${this.label}-map`,size:n,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ}),this._params=this.device.createBuffer({label:`${this.label}-params`,size:Jy,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),this.width=e,this.height=t}async toRGBA8(e,{exposure:t=1,toneMapping:n=0,saturation:r=1,flipY:i=!1}={}){if(this.disposed)throw Error(`PackedToneMapper: disposed`);if(!this._storage)throw Error(`PackedToneMapper: call ensureSize() first`);this._ensurePipeline(),this._ensureTables();let{width:a,height:o}=this;this._paramU32[0]=a,this._paramU32[1]=o,this._paramU32[2]=n>>>0,this._paramU32[3]=+!!i,this._paramF32[4]=t,this._paramF32[5]=r,this.device.queue.writeBuffer(this._params,0,this._paramData);let s=[...this._tables.entries()].map(([e,t])=>({binding:e,resource:t.view})),c=this.device.createBindGroup({layout:this._pipeline.getBindGroupLayout(0),entries:[...s,{binding:0,resource:{buffer:e,size:a*o*8}},{binding:1,resource:{buffer:this._storage}},{binding:2,resource:{buffer:this._params}}]}),l=this.device.createCommandEncoder({label:this.label}),u=l.beginComputePass();u.setPipeline(this._pipeline),u.setBindGroup(0,c),u.dispatchWorkgroups(Math.ceil(a/8),Math.ceil(o/8)),u.end(),l.copyBufferToBuffer(this._storage,0,this._map,0,a*o*4),this.device.queue.submit([l.finish()]),await this._map.mapAsync(GPUMapMode.READ);let d=new Uint8ClampedArray(this._map.getMappedRange().slice(0));return this._map.unmap(),d}_releaseBuffers(){this._storage?.destroy(),this._map?.destroy(),this._params?.destroy(),this._storage=null,this._map=null,this._params=null}dispose(){if(!this.disposed){this.disposed=!0,this._releaseBuffers();for(let e of this._tables.values())e.texture.destroy();this._tables.clear(),this._pipeline=null}}}})),Zy=b({
|
|
1106
|
+
`,Jy=32,Yy=class{constructor(e,t=`rayzee:tonemap`){this.device=e,this.label=t,this.width=0,this.height=0,this._pipeline=null,this._storage=null,this._map=null,this._params=null,this._paramData=new ArrayBuffer(Jy),this._paramU32=new Uint32Array(this._paramData),this._paramF32=new Float32Array(this._paramData),this._shaderVersion=-1,this._bindings=[],this._tables=new Map,this.disposed=!1}_ensurePipeline(){let{wgsl:e,bindings:t,version:n}=Wy();this._pipeline&&this._shaderVersion===n||(this._bindings=t,this._shaderVersion=n,this._pipeline=this.device.createComputePipeline({label:this.label,layout:`auto`,compute:{module:this.device.createShaderModule({label:this.label,code:qy(e)}),entryPoint:`main`}}))}_ensureTables(){let e=new Set;for(let{index:t,transform:n}of this._bindings){let{data:r,size:i}=n.table;e.add(t);let a=this._tables.get(t);if(a&&a.data===r)continue;a?.texture.destroy();let o=this.device.createTexture({label:`${this.label}-${n.wgslConst}`,size:[i,i,i],dimension:`3d`,format:`rgba16float`,usage:GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_DST});this.device.queue.writeTexture({texture:o},r,{bytesPerRow:i*8,rowsPerImage:i},[i,i,i]),this._tables.set(t,{texture:o,data:r,view:o.createView()})}for(let[t,n]of this._tables)e.has(t)||(n.texture.destroy(),this._tables.delete(t))}ensureSize(e,t){if(this._ensurePipeline(),this._ensureTables(),this.width===e&&this.height===t&&this._storage)return;this._releaseBuffers();let n=e*t*4;this._storage=this.device.createBuffer({label:`${this.label}-out`,size:n,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC}),this._map=this.device.createBuffer({label:`${this.label}-map`,size:n,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ}),this._params=this.device.createBuffer({label:`${this.label}-params`,size:Jy,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),this.width=e,this.height=t}async toRGBA8(e,{exposure:t=1,toneMapping:n=0,saturation:r=1,flipY:i=!1}={}){if(this.disposed)throw Error(`PackedToneMapper: disposed`);if(!this._storage)throw Error(`PackedToneMapper: call ensureSize() first`);this._ensurePipeline(),this._ensureTables();let{width:a,height:o}=this;this._paramU32[0]=a,this._paramU32[1]=o,this._paramU32[2]=n>>>0,this._paramU32[3]=+!!i,this._paramF32[4]=t,this._paramF32[5]=r,this.device.queue.writeBuffer(this._params,0,this._paramData);let s=[...this._tables.entries()].map(([e,t])=>({binding:e,resource:t.view})),c=this.device.createBindGroup({layout:this._pipeline.getBindGroupLayout(0),entries:[...s,{binding:0,resource:{buffer:e,size:a*o*8}},{binding:1,resource:{buffer:this._storage}},{binding:2,resource:{buffer:this._params}}]}),l=this.device.createCommandEncoder({label:this.label}),u=l.beginComputePass();u.setPipeline(this._pipeline),u.setBindGroup(0,c),u.dispatchWorkgroups(Math.ceil(a/8),Math.ceil(o/8)),u.end(),l.copyBufferToBuffer(this._storage,0,this._map,0,a*o*4),this.device.queue.submit([l.finish()]),await this._map.mapAsync(GPUMapMode.READ);let d=new Uint8ClampedArray(this._map.getMappedRange().slice(0));return this._map.unmap(),d}_releaseBuffers(){this._storage?.destroy(),this._map?.destroy(),this._params?.destroy(),this._storage=null,this._map=null,this._params=null}dispose(){if(!this.disposed){this.disposed=!0,this._releaseBuffers();for(let e of this._tables.values())e.texture.destroy();this._tables.clear(),this._pipeline=null}}}})),Zy=b({NeuralSuperRes:()=>fb,SR_MAX_INPUT:()=>cb,SR_SCALE:()=>2,presentRGBA8:()=>ab,readDenoisedHalf:()=>tb,releaseDenoisedReader:()=>eb,renderUpscaled:()=>rb});function Qy(){if(lb)return lb;let{neuralRuntimeUrl:e,neuralAssetBaseUrl:t}=Or();return t?(globalThis.__NEURAL_ASSET_BASE__=t,lb=new Promise((t,n)=>{if(globalThis.NeuralRuntime?.getNativeSR)return t(globalThis.NeuralRuntime.getNativeSR());let r=document.createElement(`script`);r.src=e,r.onload=()=>{let e=globalThis.NeuralRuntime?.getNativeSR;if(!e)return n(Error(`Neural runtime loaded but exposed no super-resolution entry`));t(e())},r.onerror=()=>n(Error(`Failed to load the neural runtime from ${e}`)),document.head.appendChild(r)}),lb):Promise.reject(Error(`No neural model location: set neuralAssetBaseUrl with configureAssets()`))}function $y(e,t,n){if(db&&(db.device!==e||db.width!==t||db.height!==n)&&eb(),db)return db;let r=t*n*8;return db={device:e,width:t,height:n,storage:e.createBuffer({label:`rayzee:neural-sr-pack`,size:r,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC}),map:e.createBuffer({label:`rayzee:neural-sr-pack-map`,size:r,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ}),pipeline:e.createComputePipeline({label:`rayzee:neural-sr-pack`,layout:`auto`,compute:{module:e.createShaderModule({label:`rayzee:neural-sr-pack`,code:ub}),entryPoint:`main`}})},db}function eb(){db?.storage.destroy(),db?.map.destroy(),db=null}async function tb(e){let t=e?._outGPUTexture;if(!t)throw Error(`NeuralSuperRes: no denoised frame — enable OIDN and finish a render first`);let n=e.gpuDevice,{width:r,height:i}=e._outTexSize,a=$y(n,r,i),o=n.createBindGroup({layout:a.pipeline.getBindGroupLayout(0),entries:[{binding:0,resource:t.createView()},{binding:1,resource:{buffer:a.storage}}]}),s=n.createCommandEncoder({label:`rayzee:neural-sr-pack`}),c=s.beginComputePass();c.setPipeline(a.pipeline),c.setBindGroup(0,o),c.dispatchWorkgroups(Math.ceil(r/8),Math.ceil(i/8)),c.end(),s.copyBufferToBuffer(a.storage,0,a.map,0,r*i*8),n.queue.submit([s.finish()]),await a.map.mapAsync(GPUMapMode.READ);let l=new Uint16Array(a.map.getMappedRange().slice(0));return a.map.unmap(),{half:l,width:r,height:i}}function nb(e,t,n){return new Promise((r,i)=>{let a=!1,o=(t,n)=>{a||(a=!0,e.removeEventListener(H.DENOISING_END,c),clearInterval(l),clearTimeout(u),t?r():i(n))},s=!1,c=()=>{(e.stages?.pathTracer?.frameCount??0)>=t&&(s=!0)};e.addEventListener(H.DENOISING_END,c);let l=setInterval(()=>{s&&o(!0)},200),u=setTimeout(()=>o(!1,Error(`NeuralSuperRes: timed out waiting for the render to finish`)),n)})}async function rb(e,{outputWidth:t,outputHeight:n,samples:r=64,upscaler:i=null,timeoutMs:a=6e5,present:o=!0,onProgress:s=()=>{}}={}){if(t%2||n%2)throw Error(`renderUpscaled: output must be divisible by 2, got ${t}x${n}`);let c=t/2,l=n/2,u=e.stages?.pathTracer,d={width:u?.width,height:u?.height,maxSamples:e.settings?.get?.(`maxSamples`),finalDenoise:e.denoisingManager?.finalDenoise,paused:e.pauseRendering},f=!i,p=i,m={};try{if(!p){let e=performance.now();s(`Loading the super-resolution model`),p=await fb.create({width:c,height:l,onProgress:s}),m.load=performance.now()-e}else if(p.inputWidth!==c||p.inputHeight!==l)throw Error(`renderUpscaled: upscaler is ${p.inputWidth}x${p.inputHeight}, need ${c}x${l}`);let i=performance.now();s(`Tracing ${c}x${l} at ${r} spp`),e.pauseRendering=!1,e.setCanvasSize(c,l),await new Promise(e=>setTimeout(e,300)),e.denoisingManager.applyOIDNEnabled(!0),e.settings.set(`maxSamples`,r);let u=nb(e,r,a);e.reset(),await u,e.pauseRendering=!0,m.render=performance.now()-i,s(`Reading the denoised frame`);let d=performance.now(),f=await tb(e.denoisingManager?.denoiser);m.read=performance.now()-d,s(`Upscaling to ${t}x${n}`);let h={exposure:e.renderer.toneMappingExposure,toneMapping:e.renderer.toneMapping,saturation:e.settings.get(`saturation`)??1},{rgba8:g,width:_,height:v,ms:y,toneMs:b}=await p.upscaleToRGBA8(f,h);return m.upscale=y,m.tonemap=b,o&&ib(e.denoisingManager?.upscalerCanvas,g,_,v),{rgba8:g,width:_,height:v,timings:m,upscaler:p}}catch(e){throw f&&p?.dispose(),e}finally{d.width&&d.height&&e.setCanvasSize(d.width,d.height),d.maxSamples!==void 0&&e.settings?.set?.(`maxSamples`,d.maxSamples),d.finalDenoise!==void 0&&e.denoisingManager?.applyOIDNEnabled(d.finalDenoise),e.pauseRendering=d.paused}}function ib(e,t,n,r){return e?(e.width=n,e.height=r,e.getContext(`2d`).putImageData(new ImageData(new Uint8ClampedArray(t.buffer??t),n,r),0,0),e.style.display=`block`,!0):!1}function ab(e,t,n,r){return ib(e,t,n,r)}var ob,sb,cb,lb,ub,db,fb,pb=y((()=>{xe(),qt(),Xy(),Ar(),ob=2,sb=Pt(`neural`),cb=2048,lb=null,ub=`
|
|
1107
1107
|
@group(0) @binding(0) var src: texture_2d<f32>;
|
|
1108
1108
|
@group(0) @binding(1) var<storage, read_write> dst: array<u32>;
|
|
1109
1109
|
|
|
@@ -1116,7 +1116,7 @@ fn main( @builtin(global_invocation_id) gid: vec3<u32> ) {
|
|
|
1116
1116
|
dst[ a ] = pack2x16float( c.rg );
|
|
1117
1117
|
dst[ a + 1u ] = pack2x16float( vec2<f32>( c.b, 1.0 ) );
|
|
1118
1118
|
}
|
|
1119
|
-
`,db=null,fb=class e{constructor(e,t){this.sr=e,this.canvas=t,this.slot=0,this._color=null,this._depth=null,this._motion=null,this._toneMapper=null,this.disposed=!1}get geometry(){return this.sr.geometry}get inputWidth(){return this.sr.geometry.width}get inputHeight(){return this.sr.geometry.height}get outputWidth(){return this.sr.geometry.outputWidth}get outputHeight(){return this.sr.geometry.outputHeight}static async create({width:t,height:n,onProgress:r=()=>{}}={}){if(!Number.isInteger(t)||!Number.isInteger(n)||t<1||n<1)throw Error(`
|
|
1119
|
+
`,db=null,fb=class e{constructor(e,t){this.sr=e,this.canvas=t,this.slot=0,this._color=null,this._depth=null,this._motion=null,this._toneMapper=null,this.disposed=!1}get geometry(){return this.sr.geometry}get inputWidth(){return this.sr.geometry.width}get inputHeight(){return this.sr.geometry.height}get outputWidth(){return this.sr.geometry.outputWidth}get outputHeight(){return this.sr.geometry.outputHeight}static async create({width:t,height:n,onProgress:r=()=>{}}={}){if(!Number.isInteger(t)||!Number.isInteger(n)||t<1||n<1)throw Error(`NeuralSuperRes.create: width and height must be positive integers`);if(t>2048||n>2048)throw Error(`NeuralSuperRes.create: input capped at ${cb}px per side (${cb*2}px output), got ${t}x${n}. Above that the runtime's history plane exceeds maxTextureDimension2D and it fails later with an unrelated bind-group error.`);let i=await Qy(),a=document.createElement(`canvas`);a.style.cssText=`position:fixed;left:-10000px;top:0;pointer-events:none`,document.body.appendChild(a);let o;try{o=await i.create(a,{width:t,height:n,onProgress:r,timestamps:!0,nrSettings:null})}catch(e){throw a.remove(),e}let s=new e(o,a);return s._allocate(),s}_allocate(){let e=this.inputWidth,t=this.inputHeight;this._color=new Uint16Array(e*t*4),this._depth=new Float32Array(e*t),this._motion=new Uint16Array(e*t*2)}async _run(e){if(this.disposed)throw Error(`NeuralSuperRes: disposed`);let t=this.inputWidth,n=this.inputHeight;if(e.width!==t||e.height!==n)throw Error(`NeuralSuperRes: expected a ${t}x${n} source, got ${e.width}x${e.height}`);let r=this._color;if(!e.half||e.half.length!==r.length)throw Error(`NeuralSuperRes: expected ${r.length} packed halfs from readDenoisedHalf, got ${e.half?.length}`);r.set(e.half),this._depth.fill(.5),this._motion.fill(0);let i=performance.now(),a=await this.sr.render(this.slot,{color:r,depth:this._depth,motion:this._motion,reset:!0,jitter:[0,0]});return await this.sr.device.queue.onSubmittedWorkDone(),{result:a,ms:performance.now()-i}}async upscaleToRGBA8(e,t={}){let{result:n,ms:r}=await this._run(e),{outputWidth:i,outputHeight:a}=this.geometry;this._toneMapper??=new Yy(this.sr.device,`rayzee:neural-sr-tonemap`),this._toneMapper.ensureSize(i,a);let o=performance.now();return{rgba8:await this._toneMapper.toRGBA8(n.hdr.buffer??n.hdr,{exposure:t.exposure??1,toneMapping:t.toneMapping??0,saturation:t.saturation??1,flipY:!0}),width:i,height:a,ms:r,toneMs:performance.now()-o}}dispose(){if(!this.disposed){this.disposed=!0,this._toneMapper?.dispose(),this._toneMapper=null,this.canvas.remove();try{this.sr.destroy()}catch(e){sb.warn(`super resolution teardown:`,e)}}}}})),mb=b({NeuralRetouch:()=>Tb,RETOUCH_COLOR_STRENGTH:()=>0,RETOUCH_DEFAULTS:()=>vb,RETOUCH_MAX_PIXELS:()=>bb,RETOUCH_RANGES:()=>xb,enhanceFrame:()=>_b});function hb(e={}){let{colorStrength:t=0,...n}=e;return{runtime:{...vb,...n},colorStrength:t}}function gb(){if(Sb)return Sb;let{neuralRuntimeUrl:e,neuralAssetBaseUrl:t}=Or();return t?(globalThis.__NEURAL_ASSET_BASE__=t,Sb=new Promise((t,n)=>{if(globalThis.NeuralRuntime?.getSrNrChain)return t(globalThis.NeuralRuntime.getSrNrChain());let r=document.createElement(`script`);r.src=e,r.onload=()=>{let e=globalThis.NeuralRuntime?.getSrNrChain;if(!e)return n(Error(`Neural runtime loaded but exposed no retouch entry`));t(e())},r.onerror=()=>n(Error(`Failed to load the neural runtime from ${e}`)),document.head.appendChild(r)}),Sb):Promise.reject(Error(`No neural model location: set neuralAssetBaseUrl with configureAssets()`))}async function _b({source:e,settings:t={},instance:n=null,exposure:r=1,tone:i=null,onProgress:a=()=>{}}){let o=n;o&&(o.width!==e.width||o.height!==e.height)&&(o.dispose(),o=null),o||=await Tb.create({width:e.width,height:e.height,settings:t,onProgress:a});let{runtime:s,colorStrength:c}=hb(t),l=o.staging;if(!e.half||e.half.length!==l.length)throw Error(`NeuralRetouch: expected ${l.length} packed halfs, got ${e.half?.length}`);l.set(e.half),o.device.queue.writeBuffer(o.source,0,l),o.chain.pipeline.paperWhite=1/Math.min(Math.max(r,1/Eb),Eb),o.chain.pipeline.colorStrength=c;let u=performance.now(),d=o.device.createCommandEncoder({label:`rayzee:retouch`});await o.chain.encode(d,o.slot,{buffer:o.source},s,()=>{},{reset:!0}),o.device.queue.submit([d.finish()]),await o.device.queue.onSubmittedWorkDone();let f=i?await o.readOutputToned(i):await o.readOutputHDR();return{instance:o,...f,ms:performance.now()-u}}var vb,yb,bb,xb,Sb,Cb,wb,Tb,Eb,Db=y((()=>{Xy(),qt(),Ar(),vb=Object.freeze({enabled:!0,intensity:1,localTone:1,localStructure:1,skinStructure:-1,autoMask:!0,style:0,preset:0,uiCorrection:!1}),yb=Pt(`neural`),bb=2048*2048,xb=Object.freeze({intensity:[0,1],localTone:[0,2],localStructure:[0,2],skinStructure:[-1,2],style:[0,2],preset:[0,3]}),Sb=null,Cb=`
|
|
1120
1120
|
@group(0) @binding(0) var src: texture_2d<f32>;
|
|
1121
1121
|
@group(0) @binding(1) var<storage, read_write> dst: array<u32>;
|
|
1122
1122
|
|
|
@@ -1143,4 +1143,4 @@ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
|
|
|
1143
1143
|
dst[a] = pack2x16float(c.rg);
|
|
1144
1144
|
dst[a + 1u] = pack2x16float(vec2<f32>(c.b, 1.0));
|
|
1145
1145
|
}
|
|
1146
|
-
`,Tb=class e{constructor(e,t){this.chain=e,this.canvas=t,this.slot=0,this.source=null,this.staging=null,this._readbackPipeline=null,this._readbackStorage=null,this._readbackMap=null,this._hdrPipeline=null,this._hdrStorage=null,this._hdrMap=null,this._toneMapper=null,this.disposed=!1}get device(){return this.chain.device}get width(){return this.chain.pipeline.geometry.validWidth}get height(){return this.chain.pipeline.geometry.validHeight}static async create({width:t,height:n,canvas:r=null,settings:i={},onProgress:a=()=>{}}){if(!Number.isInteger(t)||!Number.isInteger(n)||t<1||n<1)throw Error(`DLSSNeural.create: width and height must be positive integers`);if(t*n>4194304)throw Error(`DLSSNeural.create: ${t}x${n} is ${(t*n/1e6).toFixed(1)} MP, above the ${(bb/1e6).toFixed(1)} MP this pass survives. Past it the run takes minutes and then loses every GPU device in the page.`);let o=r??document.createElement(`canvas`);r||(o.style.cssText=`position:fixed;left:-10000px;top:0;pointer-events:none`);let s=new e(await(await gb()).create(o,t,n,a,hb(i).runtime),o);return s._allocate(),s}_allocate(){let{validWidth:e,validHeight:t}=this.chain.pipeline.geometry;this.source=this.device.createBuffer({label:`rayzee:dlss-nr-source`,size:e*t*8,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST}),this.staging=new Uint16Array(e*t*4);let n=e*t*4;this._readbackStorage=this.device.createBuffer({label:`rayzee:dlss-nr-readback`,size:n,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC}),this._readbackMap=this.device.createBuffer({label:`rayzee:dlss-nr-readback-map`,size:n,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ}),this._readbackPipeline=this.device.createComputePipeline({label:`rayzee:dlss-nr-readback`,layout:`auto`,compute:{module:this.device.createShaderModule({code:Cb}),entryPoint:`main`}});let r=e*t*8;this._hdrStorage=this.device.createBuffer({label:`rayzee:dlss-nr-hdr`,size:r,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC}),this._hdrMap=this.device.createBuffer({label:`rayzee:dlss-nr-hdr-map`,size:r,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ}),this._hdrPipeline=this.device.createComputePipeline({label:`rayzee:dlss-nr-hdr`,layout:`auto`,compute:{module:this.device.createShaderModule({code:wb}),entryPoint:`main`}})}async _packHDR(e,t,n=!1){let r=this.chain.pipeline.slots[this.slot]?.hdrOutput;if(!r)throw Error(`DLSSNeural: the runtime has no scene-referred output. Either no frame has been produced yet, or dlss-runtime.js was re-vendored without the patch described in its PATCHES.md.`);let i=this.device.createBindGroup({layout:this._hdrPipeline.getBindGroupLayout(0),entries:[{binding:0,resource:r.createView()},{binding:1,resource:{buffer:this._hdrStorage}}]}),a=this.device.createCommandEncoder({label:`rayzee:dlss-nr-hdr`}),o=a.beginComputePass();o.setPipeline(this._hdrPipeline),o.setBindGroup(0,i),o.dispatchWorkgroups(Math.ceil(e/8),Math.ceil(t/8)),o.end(),n&&a.copyBufferToBuffer(this._hdrStorage,0,this._hdrMap,0,e*t*8),this.device.queue.submit([a.finish()])}async readOutputHDR(){let{validWidth:e,validHeight:t}=this.chain.pipeline.geometry;await this._packHDR(e,t,!0),await this._hdrMap.mapAsync(GPUMapMode.READ);let n=new Uint16Array(this._hdrMap.getMappedRange().slice(0));return this._hdrMap.unmap(),{half:n,width:e,height:t}}async readOutputToned(e){let{validWidth:t,validHeight:n}=this.chain.pipeline.geometry;return await this._packHDR(t,n),this._toneMapper??=new Yy(this.device,`rayzee:dlss-nr-tonemap`),this._toneMapper.ensureSize(t,n),{rgba8:await this._toneMapper.toRGBA8(this._hdrStorage,{exposure:e.exposure??1,toneMapping:e.toneMapping??0,saturation:e.saturation??1}),width:t,height:n}}async readOutput(){let{validWidth:e,validHeight:t}=this.chain.pipeline.geometry,n=this.chain.pipeline.slots[this.slot]?.output;if(!n)throw Error(`DLSSNeural.readOutput: the pass has not produced a frame yet`);let r=this.device.createBindGroup({layout:this._readbackPipeline.getBindGroupLayout(0),entries:[{binding:0,resource:n.createView()},{binding:1,resource:{buffer:this._readbackStorage}}]}),i=this.device.createCommandEncoder({label:`rayzee:dlss-nr-readback`}),a=i.beginComputePass();a.setPipeline(this._readbackPipeline),a.setBindGroup(0,r),a.dispatchWorkgroups(Math.ceil(e/8),Math.ceil(t/8)),a.end(),i.copyBufferToBuffer(this._readbackStorage,0,this._readbackMap,0,e*t*4),this.device.queue.submit([i.finish()]),await this._readbackMap.mapAsync(GPUMapMode.READ);let o=new Uint8ClampedArray(this._readbackMap.getMappedRange().slice(0));return this._readbackMap.unmap(),o}dispose(){if(!this.disposed){this.disposed=!0,this.source?.destroy(),this._readbackStorage?.destroy(),this._readbackMap?.destroy(),this._hdrStorage?.destroy(),this._hdrMap?.destroy(),this._toneMapper?.dispose();try{this.chain.destroy()}catch(e){yb.warn(`retouch teardown:`,e)}}}},Eb=20}));xe(),qt();var Ob=Pt(`dlss`),kb=120,Ab=2,jb=1,Mb=0,Nb=300,Pb=5,Fb=3,Ib=3,Lb=class extends r.EventDispatcher{constructor({renderer:e,mainCanvas:t,stages:n,pipeline:r,getExposure:i,getSaturation:a}){super(),this.renderer=e,this.mainCanvas=t,this.upscalerCanvas=this._createUpscalerCanvas(t),this.pipeline=r,this._stages=n,this._getExposure=i,this._getSaturation=a,this.denoiser=null,this.upscaler=null,this.upscalerBackend=`esrgan`,this._dlssUpscaler=null,this.neuralRendering=!1,this.neuralRenderingSettings={},this._dlssNeural=null,this._dlssModule=null,this._neuralPostBusy=!1,this._finalQuality=W.oidnQuality,this.finalDenoise=W.enableOIDN,this.continuousDenoise=W.continuousDenoise,this.continuousDenoiseInterval=W.continuousDenoiseInterval,this._lastCadenceAt=-1/0,this._lastCadenceSamples=0,this._failedRefreshes=0,this._cadenceSuspended=!1,this._movingDenoiseMs=[],this._movingHopeless=!1,this._holdWhileMoving=null,this._onReset=null,this._onPostProcessRefresh=null,this._onDisplayRefresh=null,this._lastRenderWidth=0,this._lastRenderHeight=0,this._pendingStartUpscaler=null,this._pendingCloseDenoise=null,this._denoiserStartHandler=null,this._denoiserEndHandler=null,this._upscalerResChangedHandler=null,this._upscalerStartHandler=null,this._upscalerProgressHandler=null,this._upscalerEndHandler=null}_createUpscalerCanvas(e){let t=e.parentNode;if(!t)return null;let n=document.createElement(`canvas`);return n.width=e.width,n.height=e.height,n.style.position=`absolute`,n.style.inset=`0`,n.style.width=`100%`,n.style.height=`100%`,n.style.display=`none`,t.insertBefore(n,e),n}setRenderSize(e,t){this._lastRenderWidth=e,this._lastRenderHeight=t,this._cadenceDowngraded=!1,this._holdWhileMoving=null,this._movingDenoiseMs.length=0,this._movingHopeless=!1,this.denoiser?.abort(),this._unpublishOutput(),this.denoiser?.setSize(e,t),this.upscalerCanvas&&(this.upscalerCanvas.width!==e||this.upscalerCanvas.height!==t)&&(this.upscalerCanvas.width=e,this.upscalerCanvas.height=t),this.upscaler?.setBaseSize(e,t)}restoreBaseResolution(){return!this.upscalerCanvas||!this._lastRenderWidth||!this._lastRenderHeight||!(this.upscalerCanvas.width!==this._lastRenderWidth||this.upscalerCanvas.height!==this._lastRenderHeight)?!1:(this.upscalerCanvas.width=this._lastRenderWidth,this.upscalerCanvas.height=this._lastRenderHeight,!0)}setupDenoiser(){if(!this.upscalerCanvas)return;let e=this._stages.pathTracer;this.denoiser=new Fy(this.renderer,{...W,backendParams:()=>({device:this.renderer.backend.device,adapterInfo:null}),getGPUTextures:()=>{if(!e?.storageTextures?.readTarget)return null;let t=e.storageTextures.getReadTextures(),{backend:n}=this.renderer;return{color:n.get(t.color).texture,normal:n.get(t.normalDepth).texture,albedo:n.get(t.albedo).texture}}}),this._syncOIDNInUse(),this._denoiserStartHandler=e=>this.dispatchEvent({type:H.DENOISING_START,continuous:!!e.continuous}),this._denoiserEndHandler=e=>{this.denoiser?.hasOutput&&this._publishOutput(),this.dispatchEvent({type:H.DENOISING_END,continuous:!!e.continuous})},this.denoiser.addEventListener(`start`,this._denoiserStartHandler),this.denoiser.addEventListener(`end`,this._denoiserEndHandler)}setupUpscaler(){if(!this.upscalerCanvas)return;let e=this._stages.pathTracer;this.upscaler=new Uy(this.upscalerCanvas,this.renderer,{scaleFactor:W.upscalerScale||2,quality:W.upscalerQuality||`fast`,getSourceCanvas:()=>this.renderer.domElement,refreshInput:()=>{let e=this.pipeline?.context;this._stages.compositor&&e&&this._stages.compositor.render(e)},getGPUTextures:()=>{if(!e?.storageTextures?.readTarget)return null;let t=e.storageTextures.getReadTextures();return{color:this.renderer.backend.get(t.color).texture}},getExposure:()=>this._getEffectiveExposure(),getToneMapping:()=>this._getToneMapping(),getSaturation:()=>this._getSaturation()}),this.upscaler.enabled=W.enableUpscaler||!1,this._upscalerResChangedHandler=e=>this.dispatchEvent({type:`resolution_changed`,width:e.width,height:e.height}),this._upscalerStartHandler=()=>this.dispatchEvent({type:H.UPSCALING_START}),this._upscalerProgressHandler=e=>this.dispatchEvent({type:H.UPSCALING_PROGRESS,progress:e.progress}),this._upscalerEndHandler=()=>this.dispatchEvent({type:H.UPSCALING_END}),this.upscaler.addEventListener(`resolution_changed`,this._upscalerResChangedHandler),this.upscaler.addEventListener(`start`,this._upscalerStartHandler),this.upscaler.addEventListener(`progress`,this._upscalerProgressHandler),this.upscaler.addEventListener(`end`,this._upscalerEndHandler)}get denoiserStrategy(){return this.continuousDenoise?`oidn`:this._stages.asvgf?.enabled?`asvgf`:this._stages.nrd?.enabled?`nrd`:this._stages.edgeFilter?.enabled?`edgeaware`:`none`}setDenoiserStrategy(e,t){let n=this._stages;switch(n.asvgf&&(n.asvgf.enabled=!1),n.nrd&&(n.nrd.enabled=!1),n.variance&&(n.variance.enabled=!1),n.bilateralFilter&&(n.bilateralFilter.enabled=!1),n.edgeFilter&&n.edgeFilter.setFilteringEnabled(!1),this._clearDenoiserTextures(),this.setContinuousDenoise(e===`oidn`),e){case`asvgf`:n.asvgf.enabled=!0,n.variance&&(n.variance.enabled=!0),n.bilateralFilter&&(n.bilateralFilter.enabled=!0),n.asvgf.setTemporalEnabled?.(!0),this._applyASVGFPreset(t||`medium`);break;case`nrd`:n.nrd&&(n.nrd.enabled=!0,n.nrd.resetHistory?.(),this._applyNRDPreset(t||`medium`));break;case`edgeaware`:n.variance&&(n.variance.enabled=!0),n.edgeFilter&&n.edgeFilter.setFilteringEnabled(!0);break}this._syncGBufferStages()}setASVGFEnabled(e,t){let n=this._stages;n.asvgf&&(n.asvgf.enabled=e),n.variance&&(n.variance.enabled=e),n.bilateralFilter&&(n.bilateralFilter.enabled=e),e&&(n.nrd&&(n.nrd.enabled=!1),n.asvgf?.setTemporalEnabled?.(!0),this._applyASVGFPreset(t||`medium`)),n.edgeFilter&&n.edgeFilter.setFilteringEnabled(!e),this._syncGBufferStages()}applyASVGFPreset(e){this._applyASVGFPreset(e)}setAutoExposureEnabled(e,t){let n=this._stages;n.autoExposure&&(n.autoExposure.enabled=e,!e&&this.renderer&&(this.renderer.toneMappingExposure=t))}get requiresMotionVectors(){return!!(this._stages.asvgf?.enabled||this._stages.nrd?.enabled)}_syncGBufferStages(){let e=this._stages,t=e.normalDepth,n=e.motionVector,r=this.requiresMotionVectors,i=r||!!(e.edgeFilter?.enabled||e.bilateralFilter?.enabled);t&&(i&&!t.enabled&&t.reset(),t.enabled=i),n&&(r&&!n.enabled&&(n.matricesInitialized=!1,n.isFirstFrame=!0,n.frameCount=0),n.enabled=r),e.pathTracer?.setAuxGBufferEnabled?.(i||!!this.denoiser?.enabled),e.pathTracer?.setCleanAuxNormal?.(!!this.denoiser?.enabled&&!!this.denoiser?.expectsCleanAux(this._finalQuality));for(let r of[e.asvgf,e.nrd,e.variance,e.bilateralFilter,e.edgeFilter,t,n])r&&!r.enabled&&r.releaseGPUMemory?.()}_cleanupCompletionListener(){this.denoiser&&(this._pendingStartUpscaler&&this.denoiser.removeEventListener(`end`,this._pendingStartUpscaler),this._pendingCloseDenoise&&this.denoiser.removeEventListener(`end`,this._pendingCloseDenoise)),this._pendingStartUpscaler=null,this._pendingCloseDenoise=null}get holdsWhileMoving(){if(!this._stages.pathTracer?.viewIsChanging||!this.continuousDenoise||this._cadenceSuspended||!this.denoiser?.enabled||this._movingHopeless)return!1;let e=this.movingCostMs,t=this._movingDenoiseMs.length;e>Nb*Fb&&(this._movingHopeless=!0);let n=!this._movingHopeless&&(t<2||e<=Nb);return this._holdWhileMoving=(this._holdWhileMoving===null||this._holdWhileMoving)&&n,this._holdWhileMoving}skipsTrace(){return this.holdsWhileMoving&&!!this.denoiser?.state.isDenoising}get movingCostMs(){return this._movingDenoiseMs.length?Math.min(...this._movingDenoiseMs):0}_publishOutput(){let e=this.pipeline?.context,t=this.denoiser?.outputTexture;e&&t&&e.setTexture(`oidn:output`,t)}_unpublishOutput(){this.pipeline?.context?.removeTexture(`oidn:output`),this.denoiser?.invalidateOutput()}_checkHeldFrameHealthy(){!this.denoiser?.hasOutput||this._failedRefreshes<Ib||this._unpublishOutput()}tickContinuousDenoise(e){let t=this.denoiser;if(!this.continuousDenoise||this._cadenceSuspended||!t)return!1;this._checkHeldFrameHealthy();let n=!!this._stages.pathTracer?.viewIsChanging;if(!n)this._holdWhileMoving=null,this._movingDenoiseMs.length=0;else if(!this.holdsWhileMoving)return!1;if(t.state.isDenoising||t.state.isLoading||!n&&e<=this._lastCadenceSamples)return!1;let r=performance.now(),i=n?Mb:this._lastCadenceSamples===0?jb:Ab,a=Math.max(this.continuousDenoiseInterval,t.lastDenoiseMs*i);if(r-this._lastCadenceAt<a)return!1;this._lastCadenceAt=r,this._lastCadenceSamples=e,t.lastDenoiseMs>kb&&(this._cadenceDowngraded=!0);let o=this._cadenceDowngraded?this.previewQuality():this._finalQuality;return t.quality!==o&&t.updateQuality(o),t.start({continuous:!0}).then(e=>{this._failedRefreshes=e?0:this._failedRefreshes+1,!(!e||!n)&&(this._movingDenoiseMs.push(t.lastDenoiseMs),this._movingDenoiseMs.length>Pb&&this._movingDenoiseMs.shift())}),!0}previewQuality(){return this.denoiser?.expectsCleanAux(this._finalQuality)?`fast-clean`:`fast`}setCadenceSuspended(e){this._cadenceSuspended=!!e,this._cadenceSuspended&&(this.denoiser?.abort(),this._unpublishOutput())}setContinuousDenoise(e){this.continuousDenoise=!!e,this._syncOIDNInUse(),this._lastCadenceAt=-1/0,this._resetCadence()}_useFinalQuality(){let e=this.denoiser;e&&e.quality!==this._finalQuality&&e.updateQuality(this._finalQuality)}_resetCadence(){this._lastCadenceSamples=0}setUpscalerBackend(e){let t=e===`dlss`?`dlss`:`esrgan`;t!==this.upscalerBackend&&(this.upscalerBackend=t,this._restoreRenderDisplay(),t!==`dlss`&&this._releaseDLSSUpscaler())}_restoreRenderDisplay(){let e=this.upscalerCanvas&&this.upscalerCanvas.style.display!==`none`;return this.upscalerCanvas&&(this.upscalerCanvas.style.display=`none`),this.mainCanvas&&(this.mainCanvas.style.opacity=`1`),e&&this._lastRenderWidth&&this._lastRenderHeight&&this.dispatchEvent({type:`resolution_changed`,width:this._lastRenderWidth,height:this._lastRenderHeight}),!!e}_releaseDLSSUpscaler(){this._dlssUpscaler?.dispose(),this._dlssUpscaler=null,this._dlssModule?.releaseDenoisedReader()}setNeuralRendering(e,t=null){this.neuralRendering=!!e,t&&(this.neuralRenderingSettings={...this.neuralRenderingSettings,...t}),this.neuralRendering||(this._releaseDLSSNeural(),this._restoreRenderDisplay())}_releaseDLSSNeural(){this._dlssNeural?.dispose(),this._dlssNeural=null}async _runNeuralPost(e){let t=this.upscaler?.enabled&&this.upscalerBackend===`dlss`,n=this.neuralRendering;if(!(!t&&!n)&&!this._neuralPostBusy){if(!this.upscalerCanvas){Ob.warn(`neural pass skipped: the engine has no overlay canvas to present on`);return}if(!this.pipeline?.context?.getTexture(`oidn:output`)){Ob.warn(`neural pass skipped: no denoised picture — it needs OIDN`);return}this._neuralPostBusy=!0,this.dispatchEvent({type:H.UPSCALING_START});try{let r=await Promise.resolve().then(()=>(pb(),Zy));this._dlssModule=r;let i=n?await Promise.resolve().then(()=>(Db(),mb)):null,a=this.denoiser?._outTexSize,o=(a?.width??0)*(a?.height??0),s=n&&o<=i.DLSS_NR_MAX_PIXELS;if(n&&!s&&(Ob.warn(`Neural rendering skipped: the render is ${(o/1e6).toFixed(1)} MP, above the ${(i.DLSS_NR_MAX_PIXELS/1e6).toFixed(1)} MP the pass survives.`+(t?` The upscale still ran.`:``)),this._releaseDLSSNeural()),!t&&!s)return;let c={exposure:this._getEffectiveExposure(),toneMapping:this._getToneMapping(),saturation:this._getSaturation?.()??1},l=await r.readDenoisedHalf(this.denoiser);t&&(this._dlssUpscaler&&(this._dlssUpscaler.inputWidth!==l.width||this._dlssUpscaler.inputHeight!==l.height)&&this._releaseDLSSUpscaler(),this._dlssUpscaler||=await r.DLSSSuperRes.create({width:l.width,height:l.height}));let u=l;if(s){let e=await i.enhanceFrame({source:u,settings:this.neuralRenderingSettings,instance:this._dlssNeural,exposure:c.exposure,tone:t?null:c});this._dlssNeural=e.instance,u=e}if(t&&(u=await this._dlssUpscaler.upscaleToRGBA8(u,c)),!e()){this.dropDisplay();return}if(r.presentRGBA8(this.upscalerCanvas,u.rgba8,u.width,u.height),!e()){this.dropDisplay();return}this.mainCanvas&&(this.mainCanvas.style.opacity=`0`),this.dispatchEvent({type:`resolution_changed`,width:u.width,height:u.height})}catch(e){Ob.warn(`neural pass failed`,e)}finally{this._neuralPostBusy=!1,this.dispatchEvent({type:H.UPSCALING_END})}}}onRenderComplete({isStillComplete:e,context:t}){this._cleanupCompletionListener();let n=this.finalDenoise?`final`:this.continuousDenoise?`refresh`:null,r=()=>{if(this.denoiser?.removeEventListener(`end`,r),this._pendingStartUpscaler=null,e()){if(n&&this._onDisplayRefresh?.(),this.neuralRendering||this.upscaler?.enabled&&this.upscalerBackend===`dlss`){this._runNeuralPost(e);return}this.upscaler?.enabled&&this.upscaler.start()}};if(!n){r();return}let i=()=>{e()&&(this._pendingStartUpscaler=r,this.denoiser.addEventListener(`end`,r),n===`final`?(this._useFinalQuality(),this.denoiser.start()):this.denoiser.start({continuous:!0}))};if(this._resetCadence(),this.denoiser.state.isDenoising){let e=()=>{this.denoiser?.removeEventListener(`end`,e),this._pendingCloseDenoise===e&&(this._pendingCloseDenoise=null),i()};this._pendingCloseDenoise=e,this.denoiser.addEventListener(`end`,e)}else i()}abort(e,{keepDisplay:t=!1}={}){this._cleanupCompletionListener(),this._restoreRenderDisplay(),e&&e!==this.mainCanvas&&(e.style.opacity=`1`),this.upscaler&&this.upscaler.abort();let n=!!this._stages.pathTracer?.viewIsChanging,r=t&&this.continuousDenoise&&!this._cadenceSuspended&&!!this.denoiser?.hasOutput&&(!n||this.holdsWhileMoving);this.denoiser&&!r&&(this.denoiser.enabled&&this.denoiser.abort(),this._unpublishOutput()),this._resetCadence()}dropDisplay(){this._unpublishOutput(),this._restoreRenderDisplay()}dispose(){this._cleanupCompletionListener(),this._releaseDLSSUpscaler(),this._releaseDLSSNeural(),this._unpublishOutput(),this.denoiser&&=(this._denoiserStartHandler&&this.denoiser.removeEventListener(`start`,this._denoiserStartHandler),this._denoiserEndHandler&&this.denoiser.removeEventListener(`end`,this._denoiserEndHandler),this.denoiser.dispose(),null),this.upscaler&&(this._upscalerResChangedHandler&&this.upscaler.removeEventListener(`resolution_changed`,this._upscalerResChangedHandler),this._upscalerStartHandler&&this.upscaler.removeEventListener(`start`,this._upscalerStartHandler),this._upscalerProgressHandler&&this.upscaler.removeEventListener(`progress`,this._upscalerProgressHandler),this._upscalerEndHandler&&this.upscaler.removeEventListener(`end`,this._upscalerEndHandler),this.upscaler.dispose(),this.upscaler=null,this.upscalerBackend=`esrgan`,this._dlssUpscaler=null),this._denoiserStartHandler=null,this._denoiserEndHandler=null,this._upscalerResChangedHandler=null,this._upscalerStartHandler=null,this._upscalerProgressHandler=null,this._upscalerEndHandler=null,this._onReset=null,this._onPostProcessRefresh=null,this._onDisplayRefresh=null,this.upscalerCanvas?.parentNode&&(this.upscalerCanvas.parentNode.removeChild(this.upscalerCanvas),this.upscalerCanvas=null)}setOverlayManager(e){this._overlayManager=e}setResetCallback(e){this._onReset=e}setPostProcessRefreshCallback(e){this._onPostProcessRefresh=e}setDisplayRefreshCallback(e){this._onDisplayRefresh=e}setSettings(e){this._settings=e}setASVGFParams(e){this._stages.asvgf?.updateParameters(e)}toggleASVGFHeatmap(e){this._stages.asvgf?.setHeatmapEnabled?.(e)}configureASVGFForMode(e){this._stages.asvgf&&(this._stages.asvgf.enabled=e.enabled,this._stages.variance&&(this._stages.variance.enabled=e.enabled),this._stages.bilateralFilter&&(this._stages.bilateralFilter.enabled=e.enabled),e.enabled&&this._stages.asvgf.updateParameters(e),this._syncGBufferStages())}setEdgeAwareParams(e){this._stages.edgeFilter?.updateUniforms(e)}setAutoExposureParams(e){this._stages.autoExposure?.updateParameters(e)}applyOIDNEnabled(e){this.finalDenoise=!!e,this._syncOIDNInUse()}get oidnQuality(){return this._finalQuality}setOIDNEnabled(e){this.applyOIDNEnabled(e),this._syncGBufferStages(),this._onPostProcessRefresh?.()}_syncOIDNInUse(){this.denoiser&&(this.denoiser.enabled=this.finalDenoise||this.continuousDenoise)}applyOIDNQuality(e){this._finalQuality=e,this._cadenceDowngraded=!1,this.denoiser?.updateQuality(e)}setOIDNQuality(e){this.applyOIDNQuality(e),this._syncGBufferStages(),this._onPostProcessRefresh?.()}setTileHelperEnabled(e){this._setTileHelper(e)}setUpscalerEnabled(e){this.upscaler&&(this.upscaler.enabled=e),e||this._restoreRenderDisplay()}setUpscalerScaleFactor(e){this.upscaler?.setScaleFactor(e)}setUpscalerQuality(e){this.upscaler?.setQuality(e)}setAutoExposure(e){this.setAutoExposureEnabled(e,this._getExposure()),this._onReset?.()}setStrategy(e,t){this.setDenoiserStrategy(e,t),this._onReset?.()}setNRDParams(e){this._stages.nrd?.updateParameters(e)}applyNRDPreset(e){this._applyNRDPreset(e)}setNRDDebugMode(e){this._stages.nrd?.updateParameters({debugMode:e})}_setTileHelper(e){let t=this._overlayManager?.getHelper(`tiles`);t&&(t.enabled=e,e||t.hide())}_getEffectiveExposure(){return this._stages.autoExposure?.enabled?this.renderer.toneMappingExposure:this._getExposure()}_getToneMapping(){return this.renderer.toneMapping}_clearDenoiserTextures(){let e=this.pipeline?.context;e&&[`asvgf:output`,`asvgf:demodulated`,`asvgf:gradient`,`variance:output`,`bilateralFiltering:output`,`edgeFiltering:output`,`nrd:output`,`oidn:output`].forEach(t=>e.removeTexture(t))}_applyNRDPreset(e){let t=qe[e];if(!t)return;let n={};for(let e of Ke)n[e]=Ge[e];this._stages.nrd?.updateParameters({...n,...t})}_applyASVGFPreset(e){let t=We[e];t&&(this._stages.asvgf?.updateParameters(t),this._stages.bilateralFilter?.updateParameters(t),this._stages.variance&&t.varianceBoost!==void 0&&(this._stages.variance.varianceBoost.value=t.varianceBoost))}},Rb=class{constructor(){this.layer=`hud`,this.visible=!1,this._tileBounds=null,this._imageWidth=1,this._imageHeight=1,this.enabled=!0,this._borderColor=`rgba(255, 0, 0, 0.6)`,this._borderWidthRatio=1/540,this._borderWidthMin=1.5,this._borderWidthMax=4}setActiveTile(e){this._tileBounds=e}setRenderSize(e,t){this._imageWidth=e,this._imageHeight=t}render(e,t,n){if(!this._tileBounds)return;let r=this._tileBounds,i=t/this._imageWidth,a=n/this._imageHeight,o=r.x*i,s=r.y*a,c=r.width*i,l=r.height*a,u=Math.min(this._borderWidthMax,Math.max(this._borderWidthMin,Math.min(t,n)*this._borderWidthRatio));e.strokeStyle=this._borderColor,e.lineWidth=u,e.strokeRect(o,s,c,l)}show(){this.enabled&&(this.visible=!0)}hide(){this.visible=!1,this._tileBounds=null}dispose(){this.visible=!1}},zb=class{constructor(e,i){this.layer=`scene`,this._enabled=!0,this._outlineNode=(0,g.outline)(e,i,{selectedObjects:[],edgeThickness:(0,n.uniform)(1),edgeGlow:(0,n.uniform)(0)});let a=(0,n.uniform)(3),o=(0,n.uniform)(new r.Color(16777215)),s=(0,n.uniform)(new r.Color(1640965)),{visibleEdge:c,hiddenEdge:l}=this._outlineNode,u=c.mul(o).add(l.mul(s)).mul(a),d=u.r.max(u.g).max(u.b).clamp(0,1);this._material=new t.MeshBasicNodeMaterial,this._material.colorNode=(0,n.vec4)(u,d),this._material.transparent=!0,this._material.blending=r.CustomBlending,this._material.blendEquation=r.AddEquation,this._material.blendSrc=r.OneFactor,this._material.blendDst=r.OneFactor,this._material.blendEquationAlpha=r.AddEquation,this._material.blendSrcAlpha=r.OneFactor,this._material.blendDstAlpha=r.OneFactor,this._material.toneMapped=!1,this._material.depthTest=!1,this._material.depthWrite=!1,this._quad=new t.QuadMesh(this._material)}setSelectedObjects(e){this._outlineNode.selectedObjects=e}get visible(){return this._enabled&&this._outlineNode.selectedObjects.length>0}render(e){if(!this.visible)return;let t=e.autoClear;e.autoClear=!1,e.setRenderTarget(null),this._quad.render(e),e.autoClear=t}show(){this._enabled=!0}hide(){this._enabled=!1}dispose(){this._enabled=!1,this._outlineNode?.dispose(),this._material?.dispose(),this._quad=null}};function Bb(e=!1){let t=document.createElement(`canvas`);return t.style.cssText=`position:absolute;top:0;left:0;width:100%;height:100%;pointer-events:none;`+(e?`display:none;`:``),t}function Vb(e,t=1/0){let n=e?.getBoundingClientRect();if(!n||n.width===0||n.height===0)return null;let r=Math.min(window.devicePixelRatio||1,2),i=Math.round(n.width*r),a=Math.round(n.height*r),o=t/Math.max(i,a);return o<1&&(i=Math.max(1,Math.round(i*o)),a=Math.max(1,Math.round(a*o))),{width:i,height:a}}var Hb=4096,Ub=class{constructor(){this.canvas=Bb(!0),this._visible=!1,this.renderer=null,this._sizeSource=null}async init({device:e,sizeSource:n}){this._sizeSource=n;let i=e.onuncapturederror,a=new t.WebGPURenderer({canvas:this.canvas,device:e,alpha:!0,antialias:(window.devicePixelRatio||1)<2});return await a.init(),e.onuncapturederror=i,a.outputColorSpace=r.SRGBColorSpace,a.setPixelRatio(1),a.setClearColor(0,0),a.autoClear=!1,this.renderer=a,this.syncSize(),this}get isVisible(){return this._visible}syncSize(){if(!this.renderer)return;let e=Vb(this._sizeSource,Hb);!e||e.width===this.canvas.width&&e.height===this.canvas.height||this.renderer.setSize(e.width,e.height,!1)}begin(){this.renderer&&(this.renderer.setRenderTarget(null),this.renderer.clear())}setVisible(e){this._visible!==e&&(this._visible=e,this.canvas.style.display=e?``:`none`)}dispose(){Ae(this.renderer),this.renderer=null,this.canvas.parentElement?.removeChild(this.canvas)}};qt();var Wb=Pt(`overlay`),Gb=(e,t)=>e.visible&&e.layer===t&&e.render,Kb=class{constructor(e){this.camera=e,this._helpers=new Map,this._hudCanvas=Bb(),this._hudCtx=this._hudCanvas.getContext(`2d`),this._helperScene=null,this._viewOverlay=null}async initViewRenderer({device:e,sizeSource:t}){if(!(!e||!t))try{this._viewOverlay=await new Ub().init({device:e,sizeSource:t})}catch(e){Wb.error(`overlay surface unavailable — light gizmos, transform gizmo and outlines are disabled`,e),this._viewOverlay=null}}setHelperScene(e){this._helperScene=e}getHUDCanvas(){return this._hudCanvas}mount(e){if(!e)return;let t=this._viewOverlay?.canvas;t&&t.parentElement!==e&&e.appendChild(t),this._hudCanvas.parentElement!==e&&e.appendChild(this._hudCanvas)}setupDefaultHelpers({helperScene:e,meshScene:t,pipeline:n,denoisingManager:r,app:i,renderWidth:a,renderHeight:o}){this.setHelperScene(e);let s=new Rb;this.register(`tiles`,s),s.setRenderSize(a||1,o||1),i.addEventListener(`resolution_changed`,e=>{s.setRenderSize(e.width,e.height)}),n.eventBus.on(`pipeline:reset`,()=>s.hide()),this._wireDenoiserTileEvents(s,r);let c=new zb(t,this.camera);this.register(`outline`,c)}_wireDenoiserTileEvents(e,t){let n=[t?.denoiser,t?.upscaler];for(let t of n)t&&(t.addEventListener(`tileProgress`,t=>{t.continuous||t.tile&&(e.setRenderSize(t.imageWidth,t.imageHeight),e.setActiveTile(t.tile),e.show(),this.refreshHUD())}),t.addEventListener(`end`,()=>{e.hide(),this.refreshHUD()}))}register(e,t){this._helpers.has(e)&&(Wb.warn(`helper "${e}" already registered — replacing.`),this._helpers.get(e).dispose?.()),this._helpers.set(e,t)}unregister(e){let t=this._helpers.get(e);t&&(t.dispose?.(),this._helpers.delete(e))}show(e){this._helpers.get(e)?.show()}hide(e){this._helpers.get(e)?.hide()}toggle(e){let t=this._helpers.get(e);t&&(t.visible?t.hide():t.show())}getHelper(e){return this._helpers.get(e)??null}isVisible(e){return this._helpers.get(e)?.visible??!1}showAll(){for(let e of this._helpers.values())e.show()}hideAll(){for(let e of this._helpers.values())e.hide()}render(){let e=this._viewOverlay;if(e){let t=this._hasVisibleSceneOverlay();(t||e.isVisible)&&(e.syncSize(),e.begin(),t&&this._renderSceneLayer(e.renderer),e.setVisible(t))}this.refreshHUD()}_renderSceneLayer(e){this._helperScene?.render(e,this.camera);for(let t of this._helpers.values())Gb(t,`scene`)&&t.render(e,this.camera)}_hasVisibleSceneOverlay(){if(this._helperScene?.isDrawing)return!0;for(let e of this._helpers.values())if(Gb(e,`scene`))return!0;return!1}refreshHUD(){let e=this._hudCanvas,t=this._hudCtx,n=!1;for(let e of this._helpers.values())if(Gb(e,`hud`)){n=!0;break}if(!n){e.style.display!==`none`&&(e.style.display=`none`);return}e.style.display!==``&&(e.style.display=``);let r=e.clientWidth,i=e.clientHeight,a=r>0&&i>0?Vb(e):null;if(a){(e.width!==a.width||e.height!==a.height)&&(e.width=a.width,e.height=a.height),t.clearRect(0,0,a.width,a.height),t.save(),t.scale(a.width/r,a.height/i);for(let e of this._helpers.values())Gb(e,`hud`)&&e.render(t,r,i);t.restore(),e.style.display!==``&&(e.style.display=``)}}dispose(){for(let e of this._helpers.values())e.dispose?.();this._helpers.clear(),this._viewOverlay?.dispose(),this._viewOverlay=null,this._hudCanvas.parentElement&&this._hudCanvas.parentElement.removeChild(this._hudCanvas)}};xe();var qb=class extends r.EventDispatcher{constructor(){super(),this.mixer=null,this.timer=new r.Timer,this.actions=[],this.isPlaying=!1,this._scene=null,this._mixerRoot=null,this._meshes=null,this._meshTriRanges=null,this._meshPositions=null,this._tempVec=new r.Vector3,this._skinnedCache=null,this._clipsCache=null,this._savedTimeScale=1,this.onFinished=null,this.wakeCallback=null}init(e,t,n,i){if(this.dispose(),!i||i.length===0)return;this._scene=e,this._mixerRoot=t,this._meshes=n,this.mixer=new r.AnimationMixer(t);let a=i.map(e=>this.mixer.clipAction(e)),o=(e,t)=>e.name===t||e.getObjectByName(t)!==void 0;!a.some(e=>e.getClip().tracks.some(e=>{let n=e.name.split(`.`)[0];return o(t,n)}))&&t!==e&&(console.log(`[AnimationManager] Tracks did not resolve from model root, retrying with scene root`),this.mixer=new r.AnimationMixer(e),this._mixerRoot=e,a=i.map(e=>this.mixer.clipAction(e))),this.actions=a,this.mixer.addEventListener(`finished`,()=>{this.isPlaying=!1,this.timer.reset(),this.onFinished&&this.onFinished()}),this._meshTriRanges=[],this._skinnedCache=[];let s=0;for(let e of n){let t=e.geometry,n=t.attributes.position,r=t.index?t.index.array:null,i=r?r.length/3:n.count/3,a=n.count;this._meshTriRanges.push({start:s,count:i,uniqueVerts:a,indices:r}),s+=i}this._skinnedCache=[],this._meshPositions=[];let c=n.filter(e=>e.isSkinnedMesh).length;console.debug(`[AnimationManager] Init: ${i.length} clips, ${n.length} meshes (${c} skinned), ${s} triangles`)}play(e=0){if(!(!this.mixer||this.actions.length===0)){if(this.mixer.stopAllAction(),e===-1)for(let e of this.actions)e.play();else e>=0&&e<this.actions.length&&this.actions[e].play();this.timer.reset(),this.isPlaying=!0,this.wakeCallback?.(),this.dispatchEvent({type:H.ANIMATION_STARTED})}}pause(){this.mixer&&(this.mixer.timeScale=0,this.timer.reset(),this.isPlaying=!1,this.dispatchEvent({type:H.ANIMATION_PAUSED}))}resume(){this.mixer&&(this.mixer.timeScale=this._savedTimeScale||1,this.timer.reset(),this.isPlaying=!0,this.wakeCallback?.(),this.dispatchEvent({type:H.ANIMATION_STARTED}))}stop(){this.mixer&&(this.mixer.stopAllAction(),this.mixer.timeScale=this._savedTimeScale||1,this.timer.reset(),this.isPlaying=!1,this.dispatchEvent({type:H.ANIMATION_STOPPED}))}setSpeed(e){this._savedTimeScale=e,this.mixer&&this.isPlaying&&(this.mixer.timeScale=e)}setLoop(e){let t=e?r.LoopRepeat:r.LoopOnce;for(let n of this.actions)n.setLoop(t),n.clampWhenFinished=!e}seekTo(e,t=0){if(!this.mixer||this.actions.length===0)return null;if(this.mixer.stopAllAction(),t===-1)for(let e of this.actions)e.play();else t>=0&&t<this.actions.length&&this.actions[t].play();this.mixer.setTime(e);for(let e of this.actions)e.isRunning()&&(e.paused=!0);return this._poseReader()}get currentTime(){return this.mixer?.time||0}update(){if(!this.isPlaying||!this.mixer)return null;this.timer.update();let e=this.timer.getDelta();return this.mixer.update(e),this._poseReader()}_scratch(e,t,n){let r=e[t];return r&&r.length===n?r:e[t]=new Float32Array(n)}_poseReader(){return this._mixerRoot.updateMatrixWorld(!0),e=>this._computeMeshPositions(e)}_computeMeshPositions(e){let t=this._tempVec,n=this._meshes[e],{count:r,uniqueVerts:i,indices:a}=this._meshTriRanges[e],o=this._scratch(this._skinnedCache,e,i*3),s=this._scratch(this._meshPositions,e,r*9),c=n.matrixWorld;for(let e=0;e<i;e++)n.getVertexPosition(e,t),t.applyMatrix4(c),o[e*3]=t.x,o[e*3+1]=t.y,o[e*3+2]=t.z;if(a)for(let e=0;e<r;e++){let t=e*3,n=a[t]*3,r=a[t+1]*3,i=a[t+2]*3,c=e*9;s[c]=o[n],s[c+1]=o[n+1],s[c+2]=o[n+2],s[c+3]=o[r],s[c+4]=o[r+1],s[c+5]=o[r+2],s[c+6]=o[i],s[c+7]=o[i+1],s[c+8]=o[i+2]}else for(let e=0;e<r;e++){let t=e*3*3,n=(e*3+1)*3,r=(e*3+2)*3,i=e*9;s[i]=o[t],s[i+1]=o[t+1],s[i+2]=o[t+2],s[i+3]=o[n],s[i+4]=o[n+1],s[i+5]=o[n+2],s[i+6]=o[r],s[i+7]=o[r+1],s[i+8]=o[r+2]}return s}get hasAnimations(){return this.actions.length>0}get clips(){return this._clipsCache||=this.actions.map((e,t)=>{let n=e.getClip();return{index:t,name:n.name||`Clip ${t}`,duration:n.duration}}),this._clipsCache}dispose(){this.mixer&&=(this.mixer.stopAllAction(),this.mixer.uncacheRoot(this._mixerRoot),null),this.actions=[],this.isPlaying=!1,this.timer.reset(),this._scene=null,this._mixerRoot=null,this._meshes=null,this._meshTriRanges=null,this._meshPositions=null,this._skinnedCache=null,this._clipsCache=null}};xe();var Jb=new r.Vector3(0,0,-1),Yb=class{constructor({camera:e,canvas:t,orbitControls:n,app:i}){this._app=i,this._orbitControls=n,this._camera=e,this._controls=new _.TransformControls(e,t),this._gizmoScene=new r.Scene,this._gizmoScene.add(this._controls.getHelper()),this._attached=null,this._isDragging=!1,this._meshes=null,this._refitInFlight=!1,this._baselineComputed=!1,this._tempForward=new r.Vector3,this._lightTargetDistance=null,this._lastLightPosition=null,this._onDraggingChanged=this._onDraggingChanged.bind(this),this._onObjectChange=this._onObjectChange.bind(this),this._controls.addEventListener(`dragging-changed`,this._onDraggingChanged),this._controls.addEventListener(`objectChange`,this._onObjectChange)}setMeshData(e){this._meshes=e}attach(e){if(this._attached!==e&&(this._controls.attach(e),this._attached=e,this._lightTargetDistance=null,this._lastLightPosition=null,e.isLight&&e.target)){let t=e.target.position.clone().sub(e.position),n=t.length();n>1e-4?(e.quaternion.setFromUnitVectors(Jb,t.normalize()),this._lightTargetDistance=n):this._lightTargetDistance=1,this._lastLightPosition=e.position.clone()}}detach(){this._attached&&(this._controls.detach(),this._attached=null,this._lightTargetDistance=null,this._lastLightPosition=null)}setMode(e){this._controls.setMode(e),this._app?.dispatchEvent({type:H.TRANSFORM_MODE_CHANGED,mode:e}),this._app?.refreshFrame()}setSpace(e){this._controls.setSpace(e),this._app?.refreshFrame()}get isDragging(){return this._isDragging}get attachedObject(){return this._attached}get controls(){return this._controls}render(e){if(!this._attached)return;let t=e.autoClear;e.autoClear=!1,e.clearDepth(),e.setRenderTarget(null),e.render(this._gizmoScene,this._camera),e.autoClear=t}_onDraggingChanged(e){this._isDragging=e.value,this._orbitControls&&(this._orbitControls.enabled=!e.value),e.value?this._app.dispatchEvent({type:H.OBJECT_TRANSFORM_START}):(this._attached?.isLight?this._finalizeLightTransform():this._recomputeAndRefit(),this._app.dispatchEvent({type:H.OBJECT_TRANSFORM_END}))}_onObjectChange(){this._app.needsReset=!0,this._app.wake(),this._attached?.isLight&&this._syncLightDuringDrag()}_syncLightDuringDrag(){let e=this._attached;if(e.target){let t=this._controls.mode;if(t===`translate`&&this._lastLightPosition){let t=this._tempForward.copy(e.position).sub(this._lastLightPosition);e.target.position.add(t),e.target.updateMatrixWorld(!0)}else if(t===`rotate`&&this._lightTargetDistance!=null){let t=this._tempForward.set(0,0,-1).applyQuaternion(e.quaternion);e.target.position.copy(e.position).addScaledVector(t,this._lightTargetDistance),e.target.updateMatrixWorld(!0)}this._lastLightPosition.copy(e.position)}this._app.lightManager?.updateLights()}_finalizeLightTransform(){let e=this._attached;e.isRectAreaLight&&(e.scale.x!==1||e.scale.y!==1)&&(e.width*=e.scale.x,e.height*=e.scale.y,e.scale.set(1,1,1)),this._app.lightManager?.updateLights()}_recomputeAndRefit(){if(!this._meshes||this._refitInFlight||!this._attached)return;this._attached.updateMatrixWorld(!0);let e=this._findAffectedMeshIndices(this._attached);if(e.length!==0){this._refitInFlight=!0;try{this._app.updateMeshTransforms(e)}catch(e){console.error(`Transform refit error:`,e)}finally{this._refitInFlight=!1}}}_findAffectedMeshIndices(e){let t=[];for(let n=0;n<this._meshes.length;n++){let r=this._meshes[n];(r===e||this._isDescendantOf(r,e))&&t.push(n)}return t}_isDescendantOf(e,t){let n=e.parent;for(;n;){if(n===t)return!0;n=n.parent}return!1}dispose(){this._controls.removeEventListener(`dragging-changed`,this._onDraggingChanged),this._controls.removeEventListener(`objectChange`,this._onObjectChange),this.detach(),this._gizmoScene.remove(this._controls.getHelper()),this._controls.dispose(),this._meshes=null,this._baselineComputed=!1,this._tempForward=null,this._lightTargetDistance=null,this._lastLightPosition=null,this._app=null,this._orbitControls=null,this._camera=null,this._controls=null,this._gizmoScene=null}},Xb=class{constructor(e){this.layer=`scene`,this._transformManager=e,this._enabled=!0}get visible(){return this._enabled&&this._transformManager.attachedObject!==null}render(e){this._transformManager.render(e)}show(){this._enabled=!0}hide(){this._enabled=!1}dispose(){this._enabled=!1}};qt(),xe(),ca();var Zb=new WeakMap,Qb=Pt(`engine`);function $b(e,t){e.lost.then(e=>{t.app&&t.app._handleDeviceLost(e)})}var ex=/swiftshader|llvmpipe|lavapipe|basic render|microsoft basic|warp/i;function tx(e){let t=e.info??{},n=`${t.vendor??``} ${t.architecture??``} ${t.device??``} ${t.description??``}`;return{vendor:t.vendor??``,architecture:t.architecture??``,device:t.device??``,description:t.description??``,isSoftware:t.isFallbackAdapter===!0||e.isFallbackAdapter===!0||ex.test(n)}}var nx=class extends r.EventDispatcher{constructor(e,t={}){super();try{Zb.get(e)?.dispose()}catch(e){Qb.warn(`prior canvas owner dispose failed`,e)}Zb.set(e,this),this.canvas=e,this._autoResize=t.autoResize!==!1,this._maxSceneBytes=t.maxSceneBytes,this._container=t.container||null,this._applySceneMetadataEnabled=t.applySceneMetadata!==!1,this._applyingSceneMetadata=!1,this._profile=Le(t.profile),this._issues=new fn({strict:t.strict===!0,onIssue:e=>this.dispatchEvent({type:H.ISSUE,issue:e})}),this.color=new mo({issues:this._issues}),co(this.color),this.settings=new jg({...W,environmentRotation:this._profile.environmentRotation,saturation:this._profile.saturation},{issues:this._issues}),this.renderer=null,this.scene=null,this.meshScene=null,this._sceneHelpers=null,this.assetLoader=null,this._sdf=null,this._animRefitInFlight=!1,this._maxTextureSize=W.maxTextureSize,this.pipeline=null,this._pendingReservedRenderSize=null,this.stages={},this.cameraManager=null,this.lightManager=null,this.goboManager=null,this.iesManager=null,this.denoisingManager=null,this.overlayManager=null,this.interactionManager=null,this.transformManager=null,this.animationManager=new qb,this.environmentManager=null,this.isInitialized=!1,this.pauseRendering=!1,this._pathTracerEnabled=!0,this._rasterPrecompile=null,this.animationManagerId=null,this.needsReset=!1,this._loadingInProgress=!1,this._needsDisplayRefresh=!1,this._paused=!1,this._emissiveSamplingUserSet=!1,this.completion=new Tg,this._resizeDebounceTimer=null,this._displayWidth=0,this._displayHeight=0,this._renderScale=1,this._pendingRenderScale=null,this._trackedListeners=[],this._disposed=!1,this._deviceLost=!1,this._gpuDevice=null,this._deviceLostHolder=null,this._deterministic=!1,this._dispatchPinned=!1,this._deterministicRestore=null,this.adapterInfo=null}_addTrackedListener(e,t,n){e&&(e.addEventListener(t,n),this._trackedListeners.push({target:e,type:t,handler:n}))}_removeTrackedListeners(){for(let{target:e,type:t,handler:n}of this._trackedListeners)try{e.removeEventListener(t,n)}catch(e){Qb.warn(`failed to remove listener`,t,e)}this._trackedListeners.length=0}async init(){return await this._initRenderer(),this._applyPendingReservedRenderSize(),this._initCameraManager(),this._initScenes(),this._initAssetPipeline(),this._initPipeline(),await this._initManagers(),this._wireEvents(),this.stages.pathTracer.setTriangleData(new Float32Array(32),0),this.stages.pathTracer.setBVHData(new Float32Array(16)),this.stages.pathTracer.materialData.setMaterialData(new Float32Array(16)),this.stages.pathTracer.setupMaterial(),this.isInitialized=!0,Qb.debug(`WebGPU path tracer app initialized`),this}animate(){if(this._deviceLost)return;if(this.animationManagerId=requestAnimationFrame(()=>this.animate()),this._loadingInProgress||this._sdf?.isProcessing){this.dispatchEvent({type:H.FRAME});return}if(this.cameraManager.controls&&this.cameraManager.controls.update(),this._applyPendingRenderScale(),this.animationManager?.isPlaying&&!this._animRefitInFlight){let e=this.animationManager.update();e&&(this._animRefitInFlight=!0,this.refitBVH(e).catch(e=>Qb.error(`animation refit error:`,e)).finally(()=>{this._animRefitInFlight=!1}))}let e=this.needsReset;if(this.needsReset&&=(this.stages.pathTracer?.noteViewChanged(),this.reset(!0),!1),this.cameraManager.camera.updateMatrixWorld(),!this.pathTracerEnabled){this.renderer.render(this.meshScene,this.cameraManager.camera),this._renderHelperOverlay();return}if(!this.pauseRendering){if(this.cameraManager.updateAutoFocus(),this.stages.pathTracer?.isReady){if(this.stages.pathTracer.isComplete&&this.completion.renderCompleteDispatched){this._needsDisplayRefresh&&(this._needsDisplayRefresh=!1,this.stages.compositor.render(this.pipeline.context),this._renderHelperOverlay()),this.stopAnimation();return}if(this.denoisingManager?.skipsTrace()){e&&this.stages.pathTracer.enterInteractionMode(),this._renderHelperOverlay(),this.dispatchEvent({type:H.FRAME});return}this.pipeline.render(),this.stages.pathTracer.isComplete||(this.completion.updateTime(),this.denoisingManager?.tickContinuousDenoise(this.stages.pathTracer.frameCount)),this._ensureVRAMWiring();let t=this.stages.pathTracer?.vramTracker,n=this.stages.pathTracer?.frameCount??0;if(t&&(n<=1||n%30==0)&&t.measure(),Te({timeElapsed:this.completion.timeElapsed,samples:Ee(this.stages.pathTracer),memoryUsed:t?.current??0,memoryPeak:t?.peak??0}),this.completion.isTimeLimitReached(this.stages.pathTracer,this.settings.get(`renderLimitMode`),this.settings.get(`renderTimeLimit`))&&(this.stages.pathTracer.isComplete=!0),this.stages.pathTracer.isComplete&&this.completion.markComplete()){this.denoisingManager.onRenderComplete({isStillComplete:()=>this.completion.renderCompleteDispatched,context:this.pipeline?.context});let e={samples:this.stages.pathTracer.frameCount,timeElapsed:this.completion.timeElapsed,budgetOverrun:this.completion.budgetOverrun,reason:this.completion.stopCondition(this.stages.pathTracer)??`samples`};this.dispatchEvent({type:`RenderComplete`,...e}),this.dispatchEvent({type:H.RENDER_COMPLETE,...e})}}this._renderHelperOverlay(),this.dispatchEvent({type:H.FRAME})}}stopAnimation(){this.animationManagerId&&=(cancelAnimationFrame(this.animationManagerId),null)}_handleDeviceLost(e){this._deviceLost||(this._deviceLost=!0,Qb.error(`WebGPU device lost (${e?.reason||`unknown`}): ${e?.message||``}`),this.stopAnimation(),this.dispatchEvent({type:H.DEVICE_LOST,reason:e?.reason,message:e?.message}))}wake(){this._deviceLost||!this.animationManagerId&&this.isInitialized&&!this._paused&&this.animate()}pause(){this._paused=!0,this.stopAnimation()}resume(){this._paused=!1,this.animationManagerId||this.animate()}reset(e=!1){this.pipeline&&(this.pipeline.reset(),e||(this.pipeline.eventBus.emit(`asvgf:reset`),this.pipeline.eventBus.emit(`denoiser:reset`))),this._abortPostProcess({keepDisplay:!0}),this.completion.reset(),this.wake(),this.dispatchEvent({type:`RenderReset`}),this.dispatchEvent({type:H.RENDER_RESET})}dispose(){if(!this._disposed){if(this._disposed=!0,this.dispatchEvent({type:H.DISPOSE}),this.stopAnimation(),clearTimeout(this._resizeDebounceTimer),this._resizeDebounceTimer=null,this._removeTrackedListeners(),Ce(null),this._issues.detach(),this.color?.dispose(),this.color=null,this._textureReadback?.dispose(),this._textureReadback=null,this.interactionManager?.deselect?.(),this.transformManager?.detach?.(),this.animationManager?.dispose(),this.transformManager?.dispose(),this.overlayManager?.dispose(),this.lightManager?.dispose(),this.goboManager?.dispose(),this.iesManager?.dispose(),this.denoisingManager?.dispose(),this.interactionManager?.dispose(),this.cameraManager?.dispose(),this.pipeline?.dispose(),this._sdf?.dispose(),this._sdf=null,this.assetLoader?.dispose(),this.assetLoader=null,this.meshScene){this.meshScene.environment?.dispose(),this.meshScene.environment=null;for(let e of[...this.meshScene.children])je(e);this.meshScene.clear(),this.meshScene=null}this._sceneHelpers?.clear(),this._sceneHelpers=null,this.scene?.clear(),this.scene=null;try{let e=(0,n.texture)().value,t=(0,n.cubeTexture)().value;e?._listeners?.dispose&&(e._listeners.dispose.length=0),t?._listeners?.dispose&&(t._listeners.dispose.length=0)}catch(e){Qb.warn(`failed to clear TSL texture singleton listeners`,e)}this.canvas&&Zb.get(this.canvas)===this&&Zb.delete(this.canvas),this._gpuDevice&&=(this._gpuDevice.onuncapturederror=null,null),this._deviceLostHolder&&=(this._deviceLostHolder.app=null,null),Ae(this.renderer),this.renderer=null,this.stages={},this.isInitialized=!1}}unloadScene(){if(this.isInitialized){if(this._loadingInProgress)throw Error(`PathTracerApp.unloadScene: cannot unload while a load is in progress`);this._disposed||(this.animationManager?.dispose(),this._animRefitInFlight=!1,this.interactionManager?.deselect(),this.transformManager?.detach?.(),this.assetLoader?.releaseTargetModel(),this.lightManager?.clearLights?.(),this.stages.pathTracer&&(this.stages.pathTracer.setTriangleData(new Float32Array(32),0),this.stages.pathTracer.setBVHData(new Float32Array(16)),this.stages.pathTracer.materialData.setMaterialData(new Float32Array(16)),this.stages.pathTracer.setEmissiveTriangleData?.(new Float32Array,0,0),this.stages.pathTracer.setupMaterial()),this.denoisingManager?.dropDisplay(),this.reset(),this.dispatchEvent({type:`SceneUnloaded`}))}}async loadModel(e){await this._loadWithSceneRebuild(()=>this.assetLoader.loadModel(e),{type:`ModelLoaded`,url:e})}async loadObject3D(e,t=`object3d`){await this._loadWithSceneRebuild(()=>this.assetLoader.loadObject3D(e,t),{type:`Object3DLoaded`,name:t})}_busyError(e){let t=Error(`${e}: another load is already in progress`);return t.code=`LOAD_IN_PROGRESS`,t}async loadEnvironment(e){if(this._loadingInProgress)throw this._busyError(`PathTracerApp.loadEnvironment`);this._loadingInProgress=!0;try{await this.assetLoader.loadEnvironment(e);let t=this.meshScene.environment;t&&this.stages.pathTracer&&await this.stages.pathTracer.environment.setEnvironmentMap(t),this.pipeline?.eventBus.emit(`autoexposure:resetHistory`),this.reset(),this.dispatchEvent({type:`EnvironmentLoaded`,url:e})}finally{this._loadingInProgress=!1}}async inspectArchive(e){return await this.assetLoader.inspectArchive(e)}async loadFile(e,t={}){let n=this.assetLoader?.getFileFormat(e?.name||``);if(!n)throw Error(`Unsupported file format: ${e?.name}`);if(n.type!==`environment`&&n.type!==`image`){await this._loadWithSceneRebuild(()=>this.assetLoader.loadAssetFromFile(e,t),{type:`ModelLoaded`,filename:e.name});return}if(this._loadingInProgress)throw this._busyError(`PathTracerApp.loadFile`);this._loadingInProgress=!0;try{await this.assetLoader.loadAssetFromFile(e);let t=this.meshScene.environment;t&&this.stages.pathTracer&&await this.stages.pathTracer.environment.applyHDRI(t),this.pipeline?.eventBus.emit(`autoexposure:resetHistory`),this.reset(),this.dispatchEvent({type:`EnvironmentLoaded`,filename:e.name})}finally{this._loadingInProgress=!1}}async loadExampleModels(e,t){await this._loadWithSceneRebuild(()=>this.assetLoader.loadExampleModels(e,t),{type:`ModelLoaded`,index:e})}cancelLoad(){this._loadingInProgress&&this.assetLoader?.cancelActiveLoad()}async setMaxTextureSize(e,{reprocess:t=!0}={}){let n=this._maxTextureSize;if(this._maxTextureSize=this._sdf?.setMaxTextureSize(e)??e,typeof this.stages?.pathTracer?.sdfs?.setMaxTextureSize==`function`&&this.stages.pathTracer.sdfs.setMaxTextureSize(this._maxTextureSize),t&&this._maxTextureSize!==n&&this._sdf?.triangles&&!this._loadingInProgress){this._loadingInProgress=!0;try{await this.loadSceneData(),this.reset(),this.dispatchEvent({type:`TexturesReprocessed`,maxTextureSize:this._maxTextureSize})}finally{this._loadingInProgress=!1}}}async _loadWithSceneRebuild(e,t){if(this._loadingInProgress)throw this._busyError(`PathTracerApp`);this._loadingInProgress=!0;try{await e(),this._emissiveSamplingUserSet=!1,this._clearAppendedModels(),this._syncControlsAfterLoad(),await this.loadSceneData({pendingEnvironment:this._beginSceneMetadataEnvironment()}),this.pipeline?.eventBus.emit(`autoexposure:resetHistory`),this.denoisingManager?.dropDisplay(),this.reset(),this.cameraManager.currentCameraIndex=0,this.dispatchEvent(t),this._dispatchCamerasUpdated()}catch(e){throw(!e||e.code!==`LOAD_IN_PROGRESS`)&&this._discardFailedLoad(),e}finally{this._loadingInProgress=!1}}_discardFailedLoad(){try{this._clearAppendedModels(),this.assetLoader?.releaseTargetModel(),this.denoisingManager?.dropDisplay(),this.reset()}catch(e){console.warn(`PathTracerApp: could not clear the scene after a failed load`,e)}}get sceneMetadata(){return this.assetLoader?.sceneMetadata??null}_beginSceneMetadataEnvironment(){let e=this.sceneMetadata?.environment;return!this._applySceneMetadataEnabled||!e?.sourceFile||!this.stages.pathTracer?null:(this.stages.pathTracer.environment.beginHDRI(),this._applyingSceneMetadata=!0,this.assetLoader.loadEnvironment(e.sourceFile).catch(t=>(this._issues.record(ln.ENVIRONMENT_LOAD_FAILED,`authored environment "${e.sourceFile}" failed to load — lighting falls back to the previous environment`,{sourceFile:e.sourceFile,cause:String(t?.message??t)}),null)).finally(()=>{this._applyingSceneMetadata=!1}))}_applySceneMetadataSettings(e){let t=this.sceneMetadata,n=t?.environment;if(!n)return;let r={enableEnvironment:!0,showBackground:!0,transparentBackground:!1};n.intensity!==void 0&&(r.environmentIntensity=n.intensity,r.backgroundIntensity=n.intensity),n.rotation!==void 0&&(r.environmentRotation=n.rotation),this.settings.setMany(r,{reset:!1,source:kg.SCENE_METADATA}),this.scene&&(this.scene.background=e),this.dispatchEvent({type:H.SCENE_METADATA_APPLIED,metadata:t,environment:{...n}})}async loadSceneData({pendingEnvironment:e=null}={}){this._preserveSelectionOnRebuild||this.interactionManager?.deselect(),this.animationManager.dispose(),this._animRefitInFlight=!1,this._tagPrimarySceneObject();let t=new jd(``,{namespace:`scene`,level:`info`}),n=this.meshScene.environment,r=null;if(e?(t.start(`Environment fetch + CDF (concurrent)`),r=e.then(async e=>{e&&(await this.stages.pathTracer.environment.applyHDRI(e),this._applySceneMetadataSettings(e))}).catch(e=>this._issues.record(ln.ENVIRONMENT_LOAD_FAILED,`authored environment failed to install — the scene is lit by whatever was already loaded`,{cause:String(e?.message??e)})).finally(()=>t.end(`Environment fetch + CDF (concurrent)`))):n?.image?.data&&(t.start(`Environment CDF build (worker)`),this.stages.pathTracer.scene.environment=n,r=this.stages.pathTracer.environment.buildEnvironmentCDF().then(()=>{t.end(`Environment CDF build (worker)`),this._applySceneMetadataEnabled&&this._applySceneMetadataSettings(n)})),t.start(`BVH build (SceneProcessor)`),this._sdf.setMaxTextureSize(this._maxTextureSize),await this._sdf.buildBVH(this.meshScene),t.end(`BVH build (SceneProcessor)`),U({status:`Transferring data to GPU...`,progress:86}),await new Promise(e=>setTimeout(e,0)),t.start(`GPU data transfer`),!this._sdf.uploadToPathTracer(this.stages.pathTracer,this.lightManager,this.meshScene,this.meshScene.environment))return!1;this.stages.pathTracer._meshRefs=this.stages.pathTracer._collectMeshRefs(this.meshScene),this.stages.pathTracer.setMeshVisibilityData(this.stages.pathTracer._meshRefs),this._refreshEmissiveForVisibility(),t.end(`GPU data transfer`),U({status:`Compiling shaders...`,progress:90}),await new Promise(e=>setTimeout(e,0)),t.start(`Material setup (TSL compile)`),this.stages.pathTracer.setupMaterial(),t.end(`Material setup (TSL compile)`),this._rasterPrecompile=null,this._pathTracerEnabled||(t.start(`Pipeline precompile`),await this.precompileRaster(),t.end(`Pipeline precompile`)),r&&(U({status:`Finalizing environment map...`,progress:95}),await r,this.stages.pathTracer.environment.applyCDFResults());let i=this.getSceneMinY();if(this.settings.set(`groundProjectionLevel`,i,{reset:!1}),this.settings.set(`groundCatcherHeight`,i,{reset:!1}),!this._emissiveSamplingUserSet){let e=(this._sdf?.emissiveTriangleBuilder?.emissiveTriangles?.length??this._sdf?.emissiveTriangleCount??0)>0;this.settings.set(`enableEmissiveTriangleSampling`,e,{reset:!1})}return t.start(`Apply settings`),this.settings.applyAll(),this.stages.compositor.setTransparentBackground(this.settings.get(`transparentBackground`)),t.end(`Apply settings`),t.print(this._sceneSummaryParts()),we(),this._initAnimationAndTransforms(),this.dispatchEvent({type:`SceneRebuild`}),!0}_sceneSummaryParts(){let e=this.stages.pathTracer,t=this._sdf?.instanceTable?.setCount??0,n=this._sdf?.geometryExtractor?.maps?.length??0;return[Y.count(e.triangleCount,`tri`),t?Y.count(t,`mesh`,`meshes`):null,Y.count(e.materialData.materialCount,`material`),n?Y.count(n,`map`):null,Y.count(e.bvhNodeCount,`BVH node`)]}_tagPrimarySceneObject(){let e=this.sceneModel;e&&(e.userData.__rayzeeSceneObject=!0)}_clearAppendedModels(){let e=this.meshScene;if(!e)return;let t=this.assetLoader?.floorPlane,n=this.sceneModel;for(let r of[...e.children])r===t||r===n||r.userData?.__rayzeeSceneObject&&this.assetLoader.removeModelRoot(r)}async _finishRebuildNoReframe(e){await this.loadSceneData(),this._recalibrateControlLimits(),this.pipeline?.eventBus.emit(`autoexposure:resetHistory`),this.reset(),e&&this.dispatchEvent(e)}async addModel(e,{name:t}={}){if(this._loadingInProgress)throw Error(`PathTracerApp.addModel: another load is already in progress`);this._loadingInProgress=!0,this._preserveSelectionOnRebuild=!0;try{let{root:n}=await this.assetLoader.appendModel(e);return n.userData.__rayzeeSceneObject=!0,t&&(n.userData.__rayzeeName=t),await this._finishRebuildNoReframe({type:`ModelAdded`,url:e,id:n.uuid}),n.uuid}finally{this._preserveSelectionOnRebuild=!1,this._loadingInProgress=!1}}async addModelFromObject3D(e,{name:t}={}){if(this._loadingInProgress)throw Error(`PathTracerApp.addModelFromObject3D: another load is already in progress`);this._loadingInProgress=!0,this._preserveSelectionOnRebuild=!0;try{let{root:n}=this.assetLoader.appendObject3D(e,t||`object3d`);return n.userData.__rayzeeSceneObject=!0,t&&(n.userData.__rayzeeName=t),await this._finishRebuildNoReframe({type:`ModelAdded`,id:n.uuid}),n.uuid}finally{this._preserveSelectionOnRebuild=!1,this._loadingInProgress=!1}}async removeSceneObject(e){if(!this.meshScene)return!1;let t=this.assetLoader?.floorPlane;if(t&&t.uuid===e)return!1;let n=this.getSceneObject(e);if(!n)return!1;if(this._loadingInProgress)throw Error(`PathTracerApp.removeSceneObject: another load is already in progress`);this._loadingInProgress=!0;try{return this.interactionManager?.deselect(),this.transformManager?.detach?.(),n===this.sceneModel?this.assetLoader.releaseTargetModel():this.assetLoader.removeModelRoot(n),await this._finishRebuildNoReframe({type:`SceneObjectRemoved`,id:e}),!0}finally{this._loadingInProgress=!1}}setSceneObjectVisibility(e,t){return this.setMeshVisibilityByUuid(e,t)}get currentCameraIndex(){return this.cameraManager?.currentCameraIndex??0}addCamera({name:e}={}){let t=this.cameraManager.addCameraFromView(e);return this.cameraManager.switchCamera(t),this._dispatchCamerasUpdated(),t}removeCamera(e){let t=this.cameraManager.removeCamera(e);return t&&this._dispatchCamerasUpdated(),t}_dispatchCamerasUpdated(){this.dispatchEvent({type:`CamerasUpdated`,cameras:this.cameraManager.cameras,cameraNames:this.cameraManager.getCameraNames()})}get sceneMeshes(){return this._sdf?.meshes??[]}get sceneModel(){return this.assetLoader?.targetModel??null}getSceneObject(e){let t=this.meshScene?.children.find(t=>t.uuid===e);return t?.userData?.__rayzeeSceneObject?t:null}async refitBVH(e,t){let n=await this._sdf.refitBVH(e,t);return this.stages.pathTracer.updateTriangleData(this._sdf.triangles),this.stages.pathTracer.updateBVHData(this._sdf.bvh),this.reset(),n}refitBLASes(e,t,n){let r=this._sdf.refitBLASes(e,t,n),{triRanges:i,bvhRanges:a}=this._sdf.computeBLASDirtyRanges(e);return this.stages.pathTracer.updateBufferRanges(i,a),this.reset(),this._sdf.scheduleBackgroundRebuild(e,e=>{let t=this._sdf.computeBLASDirtyRanges([e]);this.stages.pathTracer.updateBufferRanges(t.triRanges,t.bvhRanges),this.reset()}),r}updateMeshTransforms(e){let t=this._sdf.updateMeshTransforms(e);return this.stages.pathTracer.updateBufferRanges([],[this._sdf.computeTLASDirtyRange()]),this.reset(),t}setReservedRenderResolution(e,{allowLower:t=!1}={}){let n=t?e:Math.max(e,G);if(!this.renderer)return this._pendingReservedRenderSize={requestedPx:e,allowLower:t},Math.max(256,Math.min(He,Math.floor(n)||256));let r=this.renderer.backend?.device?.limits?.maxStorageBufferBindingSize||128*1024*1024,i=(typeof navigator<`u`&&navigator.deviceMemory||4)>=8&&r>=1024*1024*1024?He:2048,a=Ue(Math.min(n,i));if((this.stages?.pathTracer?.storageTextures?.writeColor?.image?.width??a)!==a){let e=this.pauseRendering;this.pauseRendering=!0;try{let e=this.renderer.domElement;(e.width>a||e.height>a)&&this.renderer.setSize(Math.min(e.width,a),Math.min(e.height,a),!1);for(let e of Object.values(this.stages))e?.reallocateReservedStorage?.()}finally{this.pauseRendering=e}this.reset(),this.dispatchEvent({type:`reserved_render_size_changed`,size:a})}return a}_applyPendingReservedRenderSize(){let e=this._pendingReservedRenderSize;if(!e)return;this._pendingReservedRenderSize=null;let t=this.setReservedRenderResolution(e.requestedPx,{allowLower:e.allowLower});t<e.requestedPx&&this._issues.warn(ln.RENDER_RESERVE_CAPPED,`reserved render size ${Y.n(e.requestedPx)}px was capped to ${Y.n(t)}px by this device's limits — renders above ${Y.n(t)}px will be declined`,{requested:e.requestedPx,applied:t}),this.dispatchEvent({type:`reserved_render_size_changed`,size:t})}getReservedRenderResolution(){return G}_isRenderSizeSupported(e,t){return e>G||t>G?(this._issues.record(ln.RENDER_SIZE_DECLINED,`render resolution ${e}×${t} exceeds the ${G}px storage reserve — resize ignored, so output stays at the previous size. Raise it with setReservedRenderResolution( ${Math.max(e,t)} ) before init().`,{width:e,height:t,reserve:G}),!1):!0}onResize(){let e=this.canvas.clientWidth,t=this.canvas.clientHeight;if(e===0||t===0||!this._isRenderSizeSupported(e,t))return;this.renderer.setPixelRatio(1),this._setDisplaySize(e,t);let n=this.denoisingManager?._lastRenderWidth??0,r=this.denoisingManager?._lastRenderHeight??0;e===n&&t===r||(clearTimeout(this._resizeDebounceTimer),this._resizeDebounceTimer=setTimeout(()=>{this._applyRenderResize(e,t)},300))}_applyRenderResize(e,t){this._isRenderSizeSupported(e,t)&&(this.pipeline?.setSize(this._scaled(e),this._scaled(t)),this.denoisingManager?.setRenderSize(e,t),this.needsReset=!0,this.dispatchEvent({type:`resolution_changed`,width:e,height:t}))}setCanvasSize(e,t){return e===0||t===0||!this._isRenderSizeSupported(e,t)?null:(this.renderer.setPixelRatio(1),this._setDisplaySize(e,t),clearTimeout(this._resizeDebounceTimer),this._applyRenderResize(e,t),{width:e,height:t})}_scaled(e){return Math.max(1,Math.round(e*this._renderScale))}_setDisplaySize(e,t){this._displayWidth=e,this._displayHeight=t,this.renderer.setSize(this._scaled(e),this._scaled(t),!1),this.cameraManager.camera.aspect=e/t,this.cameraManager.camera.updateProjectionMatrix()}_interactionRenderScale(){if(this.denoisingManager?.continuousDenoise)return 1;let e=Number(this.settings.get(`interactionRenderScale`));return e>0?Math.min(1,Math.max(.125,e)):1}_requestRenderScale(e){this._pendingRenderScale=e}_applyPendingRenderScale(){this._pendingRenderScale!==null&&this._applyRenderScale(this._pendingRenderScale)}_applyRenderScale(e){this._pendingRenderScale=null,!(this._disposed||e===this._renderScale)&&(this._renderScale=e,!(!this._displayWidth||!this._displayHeight)&&(this._setDisplaySize(this._displayWidth,this._displayHeight),this.pipeline?.setSize(this._scaled(this._displayWidth),this._scaled(this._displayHeight)),this.pipeline?.eventBus.emit(`asvgf:reset`),this.pipeline?.eventBus.emit(`denoiser:reset`),this.needsReset=!0))}configureForMode(e,t={}){let n=e===`production`,r=n?wt:Tt;this.denoisingManager?.setCadenceSuspended(n),this.cameraManager.controls.enabled=!n,this.settings.setMany(Et(r),{silent:!0,source:kg.MODE_PRESET}),this.stages.pathTracer?.setUniform(`renderMode`,parseInt(r.renderMode)),this.stages.pathTracer?.updateCompletionThreshold?.();let i=this.denoisingManager?.denoiser;if(i&&(i.abort(),this.denoisingManager.applyOIDNEnabled(r.enableOIDN),this.denoisingManager.applyOIDNQuality(r.oidnQuality)),this.denoisingManager?._syncGBufferStages?.(),this.denoisingManager?.upscaler?.abort(),t.canvasWidth&&t.canvasHeight&&(this.setReservedRenderResolution(Math.max(t.canvasWidth,t.canvasHeight)),this.setCanvasSize(t.canvasWidth,t.canvasHeight)),this.needsReset=!1,this.pauseRendering=!1,n){let e=this.stages.pathTracer?.vramTracker;e&&(e.measure(),e.resetPeak())}this.reset()}refreshFrame(){this._needsDisplayRefresh=!0,this.wake()}_abortPostProcess({keepDisplay:e=!1}={}){if(this.denoisingManager?.abort(this.canvas,{keepDisplay:e}),this.denoisingManager?.restoreBaseResolution()){let e=this.denoisingManager._lastRenderWidth,t=this.denoisingManager._lastRenderHeight;this.dispatchEvent({type:`resolution_changed`,width:e,height:t})}}requestPostProcessRefresh(){!this.stages.pathTracer?.isReady||this._deviceLost||(this._abortPostProcess(),this.completion.renderCompleteDispatched=!1,this.wake())}setDeterministicMode(e=!0,{pinDispatch:t=!0}={}){let n=this.stages.pathTracer;if(!n)return!1;if(e)this._deterministicRestore||={settings:{useAdaptiveSampling:this.settings.get(`useAdaptiveSampling`),usePixelFreeze:this.settings.get(`usePixelFreeze`),interactionModeEnabled:this.settings.get(`interactionModeEnabled`),renderLimitMode:this.settings.get(`renderLimitMode`),renderTimeLimit:this.settings.get(`renderTimeLimit`)},bounceEarlyExit:n._bounceEarlyExitThreshold,dynamicDispatch:n._useDynamicDispatch,autoFocusMode:this.cameraManager?.autoFocusMode,autoExposure:this.stages.autoExposure?.enabled,continuousDenoise:this.denoisingManager?.continuousDenoise},this.settings.setMany({useAdaptiveSampling:!1,usePixelFreeze:!1,interactionModeEnabled:!1,renderLimitMode:`frames`,renderTimeLimit:0},{silent:!0}),t?(n._bounceEarlyExitThreshold=-1,n._useDynamicDispatch=!1):(n._bounceEarlyExitThreshold=this._deterministicRestore.bounceEarlyExit,n._useDynamicDispatch=this._deterministicRestore.dynamicDispatch),this.cameraManager?.setAutoFocusMode(`manual`),this.stages.autoExposure&&(this.stages.autoExposure.enabled=!1),this.denoisingManager?.setContinuousDenoise(!1),n._pinSeedToFrame=!0,this._deterministic=!0,this._dispatchPinned=t;else if(this._deterministicRestore){let e=this._deterministicRestore;this.settings.setMany(e.settings,{silent:!0}),n._bounceEarlyExitThreshold=e.bounceEarlyExit,n._useDynamicDispatch=e.dynamicDispatch,e.autoFocusMode!==void 0&&this.cameraManager?.setAutoFocusMode(e.autoFocusMode),this.stages.autoExposure&&e.autoExposure!==void 0&&(this.stages.autoExposure.enabled=e.autoExposure),e.continuousDenoise!==void 0&&this.denoisingManager?.setContinuousDenoise(e.continuousDenoise),n._pinSeedToFrame=!1,this._deterministicRestore=null,this._deterministic=!1,this._dispatchPinned=!1}return this.reset(),this.stopAnimation(),this._deterministic}get issues(){return this._issues.list}get issueErrors(){return this._issues.errors}clearIssues(){this._issues.clear()}get isDeterministic(){return this._deterministic&&this._dispatchPinned}async renderFrames(e,{reset:t=!0,yieldEvery:n=8,onProgress:r,allowEarlyRetire:i=!1}={}){let a=this.stages.pathTracer;if(!a)throw Error(`renderFrames: app is not initialized`);if(!(e>0))throw Error(`renderFrames: count must be positive, got ${e}`);await a.blueNoiseReady;let o=(t?0:a.frameCount)+e;this.settings.get(`maxSamples`)<o&&this.settings.set(`maxSamples`,o,{silent:!0,reset:!1}),t&&this.reset(),this.stopAnimation();let s=e+64,c=0,l=!1;for(;a.frameCount<o&&c<s;){if(this._deviceLost)throw Error(`renderFrames: WebGPU device lost`);if(!a.isReady)throw Error(`renderFrames: path tracer stage is not ready`);if(this.pipeline.render(),c++,a.isComplete&&a.frameCount<o){l=!0;break}r?.(a.frameCount),n>0&&c%n===0&&await new Promise(e=>setTimeout(e,0))}if(a.frameCount<o&&!(l&&i)){let e=l?"adaptive sampling retired the frame at the convergence threshold — pass `allowEarlyRetire: true`, or disable it with setDeterministicMode()":`something retired the render (maxSamples, a stray reset, or a canvas resize)`;throw Error(`renderFrames: stopped at ${a.frameCount}/${o} samples after ${c} passes — ${e}`)}return a.frameCount}async renderToBuffer({colorSpace:e=`srgb`,preserveAlpha:t=!1,source:n=`accumulation`}={}){let r=e!==`linear`&&e!==`srgb`;if(r&&!this.color?.hasConfig)throw Error(`renderToBuffer: colorSpace must be 'linear' or 'srgb' without a colour config loaded, got "${e}"`);let i=this.stages?.pathTracer,a=i?.storageTextures?.readTarget;if(!a)throw Error(`renderToBuffer: no render target — call init() and render at least one sample`);let{width:o,height:s}=i,c=n===`display`?await this._readDisplaySource(a,o,s):await this.renderer.readRenderTargetPixelsAsync(a,0,0,o,s,0);if(e===`linear`)return{data:c,width:o,height:s,colorSpace:e,workingSpace:this.color?.workingSpace??null};if(r){let{rgba:t,colorSpace:n}=this.color.exportPixels(c,e);return{data:t,width:o,height:s,colorSpace:n}}return{data:hd(c,{exposure:this.renderer.toneMappingExposure,toneMapping:this.renderer.toneMapping,saturation:this.settings.get(`saturation`)??1,preserveAlpha:t}),width:o,height:s,colorSpace:e}}enableGPUTiming(e=!0){let t=this.renderer?.backend;return!t||e&&t.hasFeature?.(`timestamp-query`)!==!0?!1:(t.trackTimestamp=e,t.trackTimestamp===e)}profileNextDenoise(){return this.denoisingManager?.denoiser?.profileNextDenoise()??!1}async getDenoiseProfile(){let e=this.denoisingManager?.denoiser;return e?{profile:await e.getLastDenoiseProfile(),runtime:e.getRuntimeInfo()}:null}async getGPUTimings(){let e=this.renderer;if(!e?.backend?.trackTimestamp)return null;await e.resolveTimestampsAsync(`compute`),await e.resolveTimestampsAsync(`render`);let t=e.info.compute.timestamp||0,n=e.info.render.timestamp||0;return{compute:t,render:n,total:t+n}}async getKernelGPUTimings(){let e=this.renderer;if(!e?.backend?.trackTimestamp)return null;await e.resolveTimestampsAsync(`compute`);let t=e.backend.timestampQueryPool?.compute?.timestamps;if(!t||t.size===0)return null;let n=new Map,r=this.stages?.pathTracer?._kernelManager?.kernels;if(r)for(let[e,t]of r)n.set(t.id,e);let i=[],a=-1;for(let[e,n]of t){let t=e.split(`:`);if(t.length!==4)continue;let r=Number(t[3].slice(1));Number.isFinite(r)&&(i.push({nodeId:Number(t[2]),f:r,ms:n}),r>a&&(a=r))}let o={},s=0,c=0;for(let e of i){if(e.f!==a)continue;s+=e.ms;let t=n.get(e.nodeId);t===void 0?c+=e.ms:o[t]=(o[t]??0)+e.ms}return{kernels:o,total:s,unattributed:c,frame:a}}getCanvas(){if(!this.renderer?.domElement)return null;let e=this.denoisingManager?.upscalerCanvas;return e&&e.style.display!==`none`?e:(this.stages.compositor&&this.pipeline?.context&&this.stages.compositor.render(this.pipeline.context),this.renderer.domElement)}screenshot({type:e=`image/png`,quality:t}={}){let n=this.getCanvas();return n?new Promise(r=>n.toBlob(r,e,t)):Promise.resolve(null)}getStatistics(){try{return this._sdf?.getStatistics?.()??null}catch{return null}}get pathTracerEnabled(){return this._pathTracerEnabled}set pathTracerEnabled(e){this._pathTracerEnabled=e,e||this.precompileRaster()}precompileRaster(){return!this.renderer||!this.meshScene?Promise.resolve():(this._rasterPrecompile??=this.renderer.compileAsync(this.meshScene,this.cameraManager.camera).catch(e=>Qb.warn(`raster fallback precompile failed`,e)),this._rasterPrecompile)}get isLoading(){return this._loadingInProgress}isComplete(){return this.stages.pathTracer?.isComplete??!1}getFrameCount(){return this.stages.pathTracer?.frameCount||0}getConvergenceStats(){return this.stages.pathTracer?.getConvergenceStats?.()??null}get vram(){return this.stages.pathTracer?.vramTracker??null}getMemoryInfo(){return this.stages.pathTracer?.vramTracker?.measure()??{current:0,peak:0,byCategory:{}}}getHostMemoryInfo(){let e=this._sdf;return e?.memory?{preflight:e.memoryPreflight,...e.memory.report}:null}_ensureVRAMWiring(){if(this._vramWired)return;let e=this.stages.pathTracer?.vramTracker;if(!e)return;e.register(`stages`,()=>this._collectStageTextures());let t=()=>e.measure();this._addTrackedListener(this,`SceneRebuild`,t),this._addTrackedListener(this,`EnvironmentLoaded`,t),this._addTrackedListener(this,`resolution_changed`,t),this._vramWired=!0}_collectStageTextures(){let e=[],t=this.stages||{},n=t.pathTracer;for(let r in t){let i=t[r];if(!(!i||i===n||typeof i!=`object`))for(let t in i){let n=i[t];n&&(n.isTexture||n.isRenderTarget)&&e.push(n)}}return e}getSceneMinY(){if(!this.meshScene)return 0;let e=new r.Box3().setFromObject(this.meshScene);return Number.isFinite(e.min.y)?e.min.y:0}getMaterialProperty(e,t){return this.stages.pathTracer?.materialData.getMaterialProperty(e,t)}getMaterialPropertySource(e,t){return this.stages.pathTracer?.materialData.getMaterialPropertySource(e,t)}setMaterialProperty(e,t,n){this.stages.pathTracer?.materialData.updateMaterialProperty(e,t,n),[`emissive`,`emissiveIntensity`].includes(t)&&this._sdf&&this._uploadEmissivePayload(this._sdf.updateMaterialEmissive(e,t,n)),this.reset()}_uploadEmissivePayload(e){!e||!this.stages.pathTracer||(this.stages.pathTracer.setEmissiveTriangleData(e.rawData,e.emissiveCount,e.totalPower,e.bitTrailMap),e.lightBVHNodeData&&this.stages.pathTracer.setLightBVHData(e.lightBVHNodeData,e.lightBVHNodeCount))}_refreshEmissiveForVisibility(){let e=this._sdf?.instanceTable;if(!e)return;let t=new Set;for(let n=0;n<e.count;n++)e.isSet[n]&&!e.visible[n]&&t.add(n);this._uploadEmissivePayload(this._sdf.rebuildEmissiveForVisibility(t))}setEmissiveTriangleSampling(e){this._emissiveSamplingUserSet=!0,this.settings.set(`enableEmissiveTriangleSampling`,e)}hasEmissiveGeometry(){return(this._sdf?.emissiveTriangleBuilder?.emissiveTriangles?.length??this._sdf?.emissiveTriangleCount??0)>0}setMeshVisibility(e,t){this.stages.pathTracer?.updateMeshVisibility(e,t),this._refreshEmissiveForVisibility(),this.reset()}updateAllMeshVisibility(){this.stages.pathTracer?.updateAllMeshVisibility(),this._refreshEmissiveForVisibility(),this.reset()}getScene(){return this.meshScene||this.scene}setMeshVisibilityByUuid(e,t){let n=this.getScene()?.getObjectByProperty(`uuid`,e);if(!n)return null;let r=typeof t==`function`?!!t(n.visible):!!t;return n.visible=r,this.updateAllMeshVisibility(),r}setTextureTransform(e,t,n){this.stages.pathTracer?.materialData.updateTextureTransform(e,t,n),this.reset()}async _readDisplaySource(e,t,n){let r=this.pipeline?.context,i=r&&this.stages.compositor?.resolveLightTexture(r);return!i||i===e.texture?await this.renderer.readRenderTargetPixelsAsync(e,0,0,t,n,0):(this._textureReadback??=new Eg(this.renderer),await this._textureReadback.read(i,t,n))}async setTextureColorSpace(e,n){if(!e?.isTexture)throw Error(`setTextureColorSpace wants a three.js texture`);let r=e.userData??={};r.__rayzeeOriginalColorSpace===void 0&&(r.__rayzeeOriginalColorSpace=e.colorSpace);let i=r.__rayzeeOriginalColorSpace;if(delete r.ocioColorSpace,delete r.__rayzeeColorSpaceChoice,n==null)e.colorSpace=i,delete r.__rayzeeOriginalColorSpace;else if(n===`srgb`||n===`linear`)e.colorSpace=n===`srgb`?t.SRGBColorSpace:t.LinearSRGBColorSpace,r.__rayzeeColorSpaceChoice=n;else{if(!this.color?.hasConfig)throw Error(`"${n}" needs a colour config loaded`);r.ocioColorSpace=n,e.colorSpace=t.SRGBColorSpace}e.needsUpdate=!0,this.stages.pathTracer?.sdfs&&await this.rebuildMaterials()}async loadColorConfig(e={}){await this._leaveColorWorkingSpace();let t=Wi(this.renderer?.toneMapping),n=await this.color.loadConfig(e);return this.color.workingSpaceAdopted&&await this.applyColorWorkingSpace(),(!(t?.source===`ocio`&&Wi(this.renderer?.toneMapping)===t)||this.color.workingSpaceAdopted)&&this.reset(),n}async unloadColorConfig(){await this._leaveColorWorkingSpace(),this.color.unloadConfig(),this.reset()}async _leaveColorWorkingSpace(){this.color?.workingSpaceAdopted&&(this.color.setWorkingSpace(null),await this.applyColorWorkingSpace())}async applyColorWorkingSpace(){let e=this.environmentManager?.getEnvironmentTexture?.(),t=!1;if(e&&this.color?.hasConfig)try{t=this.color.convertTexturePixels(e)}catch(e){Qb.warn(`environment colour conversion failed: ${e.message}`)}this.stages.pathTracer?.sdfs&&(await this.rebuildMaterials(),this._uploadEmissivePayload(this._sdf?.rebuildEmissiveColors?.()??null)),t&&await this.environmentManager?.buildEnvironmentCDF?.(),this.reset()}async rebuildMaterials(e){await this.stages.pathTracer?.rebuildMaterials(e||this.meshScene),this.reset()}async _initRenderer(){if(Ce(e=>this.dispatchEvent(e)),!navigator.gpu)throw Error(`WebGPU is not supported in this browser`);let e=await navigator.gpu.requestAdapter({powerPreference:`high-performance`});if(!e)throw Error(`Failed to get WebGPU adapter`);this.adapterInfo=tx(e),this.adapterInfo.isSoftware&&(this._issues.warn(ln.ADAPTER_SOFTWARE,`software GPU adapter "${this.adapterInfo.description||this.adapterInfo.vendor}" — renders are correct but orders of magnitude slower than hardware`,{...this.adapterInfo}),Qb.warn(`software GPU adapter — check app.adapterInfo.isSoftware. ${this.adapterInfo.description}`));let n=e.limits,r={maxColorAttachmentBytesPerSample:128};for(let e of[`maxBufferSize`,`maxStorageBufferBindingSize`,`maxSampledTexturesPerShaderStage`,`maxStorageTexturesPerShaderStage`,`maxTextureArrayLayers`,`maxTextureDimension2D`,`maxComputeInvocationsPerWorkgroup`,`maxComputeWorkgroupStorageSize`,`maxComputeWorkgroupSizeX`,`maxComputeWorkgroupSizeY`,`maxComputeWorkgroupSizeZ`]){let t=n[e];t!==void 0&&(r[e]=t)}if(r.maxStorageBuffersPerShaderStage=Math.min(n.maxStorageBuffersPerShaderStage,10),this.renderer=new t.WebGPURenderer({canvas:this.canvas,alpha:!0,powerPreference:`high-performance`,requiredLimits:r}),await this.renderer.init(),!this.renderer.backend?.isWebGPUBackend)throw Error(`WebGPU backend unavailable — three.js fell back to WebGL2, which cannot run the path tracer's compute kernels. Check GPU process flags and driver support.`);let a=this.renderer.backend?.device;a?.lost&&(this._gpuDevice=a,this._deviceLostHolder={app:this},$b(a,this._deviceLostHolder),a.onuncapturederror=e=>Qb.error(`WebGPU uncaptured error:`,e.error)),t.RectAreaLightNode.setLTC(i.RectAreaLightTexturesLib.init()),this.renderer.outputColorSpace=t.SRGBColorSpace,this.renderer.toneMapping=this._profile.toneMapping,this.renderer.toneMappingExposure=1,this.renderer.setPixelRatio(1),this.color.attachRenderer(this.renderer)}_initCameraManager(){this.cameraManager=new ay(this.canvas)}_initScenes(){this.scene=new r.Scene,this.meshScene=new r.Scene,this._sceneHelpers=new M}_initAssetPipeline(){this._sdf=new Bd({issues:this._issues,...this._maxSceneBytes===void 0?{}:{maxSceneBytes:this._maxSceneBytes}}),this.assetLoader=new ry(this.meshScene,this.cameraManager.camera,this.cameraManager.controls,{issues:this._issues,profile:this._profile}),this.assetLoader.setRenderer(this.renderer),this.assetLoader.createFloorPlane(),this._addTrackedListener(this.cameraManager.controls,`change`,()=>{this.needsReset=!0,this.stages.pathTracer?.enterInteractionMode(),this.wake()})}_initPipeline(){this._createStages();let{clientWidth:e,clientHeight:t}=this.canvas;this.pipeline=new Cg(this.renderer,e||1,t||1,{issues:this._issues}),this.pipeline.addStage(this.stages.pathTracer),this.pipeline.addStage(this.stages.normalDepth),this.pipeline.addStage(this.stages.motionVector),this.pipeline.addStage(this.stages.nrd),this.pipeline.addStage(this.stages.asvgf),this.pipeline.addStage(this.stages.variance),this.pipeline.addStage(this.stages.bilateralFilter),this.pipeline.addStage(this.stages.edgeFilter),this.pipeline.addStage(this.stages.autoExposure),this.pipeline.addStage(this.stages.compositor);let n=this.canvas.clientWidth||1,r=this.canvas.clientHeight||1;this._displayWidth=n,this._displayHeight=r,this.pipeline.setSize(n,r),this.pipeline.eventBus.on(`pathtracer:interactionStart`,()=>this._requestRenderScale(this._interactionRenderScale())),this.pipeline.eventBus.on(`pathtracer:interactionEnd`,()=>this._applyRenderScale(1))}async _initManagers(){this.interactionManager=new Dg({scene:this.meshScene,camera:this.cameraManager.camera,canvas:this.canvas,assetLoader:this.assetLoader,pathTracer:null,floorPlane:this.assetLoader.floorPlane}),this.interactionManager.wireAppEvents(this),this.cameraManager.setInteractionManager(this.interactionManager),this.lightManager=new oy(this.scene,this._sceneHelpers,this.stages.pathTracer,{onReset:()=>this.reset()}),this.goboManager=new sy(this.stages.pathTracer,{onReset:()=>this.reset()}),this.iesManager=new vy(this.stages.pathTracer,{onReset:()=>this.reset()}),this._setupDenoisingManager(),await this._setupOverlayManager(),this.transformManager=new Yb({camera:this.cameraManager.camera,canvas:this.canvas,orbitControls:this.cameraManager.controls,app:this}),this.overlayManager.register(`transform`,new Xb(this.transformManager)),this.interactionManager.setDependencies({overlayManager:this.overlayManager,transformManager:this.transformManager,appDispatch:e=>this.dispatchEvent(e),orbitControls:this.cameraManager.controls,helperScene:this._sceneHelpers.scene}),this.denoisingManager.setOverlayManager(this.overlayManager),this.denoisingManager.setResetCallback(()=>this.reset()),this.denoisingManager.setPostProcessRefreshCallback(()=>this.requestPostProcessRefresh()),this.denoisingManager.setDisplayRefreshCallback(()=>this.refreshFrame()),this.denoisingManager.setSettings(this.settings),this.environmentManager=this.stages.pathTracer.environment,this.environmentManager.callbacks.onAutoExposureReset=()=>this.pipeline.eventBus.emit(`autoexposure:resetHistory`)}_wireEvents(){this._addTrackedListener(this.cameraManager,`CameraSwitched`,e=>this.dispatchEvent(e)),this._addTrackedListener(this.cameraManager,H.AUTO_FOCUS_UPDATED,e=>this.dispatchEvent(e)),this._forwardEvents(this.denoisingManager,[H.DENOISING_START,H.DENOISING_END,H.UPSCALING_START,H.UPSCALING_PROGRESS,H.UPSCALING_END,`resolution_changed`]),this._setupAutoExposureListener(),this.animationManager.wakeCallback=()=>this.wake(),this._forwardEvents(this.animationManager,[H.ANIMATION_STARTED,H.ANIMATION_PAUSED,H.ANIMATION_STOPPED]),this._addTrackedListener(this.animationManager,H.ANIMATION_PAUSED,()=>{this._animRefitInFlight=!1}),this._addTrackedListener(this.animationManager,H.ANIMATION_STOPPED,()=>{this._animRefitInFlight=!1}),this.cameraManager.initCallbacks({onResize:()=>this.onResize(),onReset:()=>this.reset(),getSettings:e=>this.settings.get(e),applySettings:e=>this.settings.setMany(e,{silent:!0,reset:!1})}),this.cameraManager.initAutoFocus({meshScene:this.meshScene,assetLoader:this.assetLoader,floorPlane:this.assetLoader.floorPlane,pathTracer:this.stages.pathTracer,settings:this.settings,softReset:()=>this.reset(!0),hardReset:()=>this.reset()}),this.settings.bind({stages:this.stages,renderer:this.renderer,resetCallback:()=>this.reset(),reconcileCompletion:()=>this._reconcileCompletion(),denoisingManager:this.denoisingManager,cameraManager:this.cameraManager,onInteractionRenderScale:()=>{this.stages.pathTracer?.interactionMode&&this._requestRenderScale(this._interactionRenderScale())}}),this.renderer.toneMappingExposure=this.settings.get(`exposure`)??1,this.onResize(),this.resizeHandler=()=>this.onResize(),this._autoResize&&this._addTrackedListener(window,`resize`,this.resizeHandler),this._onAssetLoaded=async e=>{if(!this._loadingInProgress&&!(this._applyingSceneMetadata&&e.texture)){if(e.model)this._clearAppendedModels(),await this.loadSceneData({pendingEnvironment:this._beginSceneMetadataEnvironment()});else if(e.texture){let e=this.meshScene.environment;e&&this.stages.pathTracer&&await this.stages.pathTracer.environment.setEnvironmentMap(e),we()}this.pauseRendering=!1,this.reset()}},this._addTrackedListener(this.assetLoader,`load`,this._onAssetLoaded),this._addTrackedListener(this.assetLoader,`modelProcessed`,e=>{let t=[this.cameraManager.camera,...e.cameras||[]];this.cameraManager.setCameras(t),this.interactionManager&&(this.interactionManager.floorPlane=this.assetLoader.floorPlane)})}_initAnimationAndTransforms(){let e=this.assetLoader?.animations||[];if(e.length>0){let t=this.sceneModel||this.meshScene;this.animationManager.init(this.meshScene,t,this._sdf.meshes,e),this.animationManager.onFinished=()=>{this._animRefitInFlight=!1,this.dispatchEvent({type:H.ANIMATION_FINISHED})}}this.transformManager?.setMeshData(this._sdf.meshes)}_createStages(){this.stages.pathTracer=new nh(this.renderer,this.scene,this.cameraManager.camera),this.stages.normalDepth=new rh(this.renderer,{pathTracer:this.stages.pathTracer}),this.stages.motionVector=new ih(this.renderer,this.cameraManager.camera,{pathTracer:this.stages.pathTracer}),this.stages.asvgf=new sh(this.renderer,{enabled:!1}),this.stages.nrd=new Gh(this.renderer,{enabled:!1,pathTracer:this.stages.pathTracer}),this.stages.variance=new Jh(this.renderer,{enabled:!1}),this.stages.bilateralFilter=new Xh(this.renderer,{enabled:!1}),this.stages.edgeFilter=new ng(this.renderer,{enabled:!1}),this.stages.autoExposure=new lg(this.renderer,{enabled:W.autoExposure??!1}),this.stages.compositor=new ug(this.renderer,{saturation:this.settings.get(`saturation`)??W.saturation,pathTracer:this.stages.pathTracer})}_setupDenoisingManager(){this.denoisingManager=new Lb({renderer:this.renderer,mainCanvas:this.canvas,stages:{pathTracer:this.stages.pathTracer,normalDepth:this.stages.normalDepth,motionVector:this.stages.motionVector,asvgf:this.stages.asvgf,nrd:this.stages.nrd,variance:this.stages.variance,bilateralFilter:this.stages.bilateralFilter,edgeFilter:this.stages.edgeFilter,autoExposure:this.stages.autoExposure,compositor:this.stages.compositor},pipeline:this.pipeline,getExposure:()=>this.settings.get(`exposure`)??1,getSaturation:()=>this.settings.get(`saturation`)??1}),this.denoisingManager.setupDenoiser(),this.denoisingManager.setupUpscaler(),this.denoisingManager._syncGBufferStages();let e=this.canvas.clientWidth||1,t=this.canvas.clientHeight||1;this.denoisingManager.setRenderSize(e,t)}_reconcileCompletion(){let e=this.stages.pathTracer;if(!e)return;let t=this.completion.isLimitReached(e,this.settings.get(`renderLimitMode`),this.settings.get(`renderTimeLimit`));t&&!e.isComplete?e.isComplete=!0:!t&&e.isComplete&&(e.isComplete=!1,this.completion.resumeFromPause(),this.denoisingManager?.abort(this.canvas),this.dispatchEvent({type:H.RENDER_RESET}),this.wake())}_setupAutoExposureListener(){this.stages.autoExposure&&this.stages.autoExposure.on(`autoexposure:updated`,e=>{this.dispatchEvent({type:H.AUTO_EXPOSURE_UPDATED,exposure:e.exposure,luminance:e.luminance})})}_renderHelperOverlay(){this.scene.updateMatrixWorld(),this.overlayManager?.render()}async _setupOverlayManager(){this.overlayManager=new Kb(this.cameraManager.camera),this.overlayManager.setupDefaultHelpers({helperScene:this._sceneHelpers,meshScene:this.meshScene,pipeline:this.pipeline,denoisingManager:this.denoisingManager,app:this,renderWidth:this.denoisingManager?._lastRenderWidth||this.canvas.clientWidth||1,renderHeight:this.denoisingManager?._lastRenderHeight||this.canvas.clientHeight||1}),await this.overlayManager.initViewRenderer({device:this.renderer.backend?.device,sizeSource:this.canvas}),this._container=this._container||this.canvas.parentNode||null,this.overlayManager.mount(this._container)}_syncControlsAfterLoad(){this.cameraManager.controls.saveState(),this.cameraManager.controls.update()}_recalibrateControlLimits(){if(!this.meshScene||!this.cameraManager)return;let e=new r.Box3,t=new r.Box3;for(let n of this.meshScene.children)n.userData?.__rayzeeSceneObject&&(t.setFromObject(n),t.isEmpty()||e.union(t));if(e.isEmpty())return;let n=Math.max(e.max.x-e.min.x,e.max.y-e.min.y,e.max.z-e.min.z);if(!Number.isFinite(n)||n<=0)return;let{camera:i,controls:a}=this.cameraManager,o=i.fov*(Math.PI/180),s=Math.abs(n/Math.sin(o/2)/2);this.cameraManager.currentCameraIndex===0&&(i.near=n/100,i.far=n*100,i.updateProjectionMatrix());let c=i.position.distanceTo(a.target);a.minDistance=Math.min(n/1e3,c),a.maxDistance=Math.max(s*10,c*1.1),a.update()}_forwardEvents(e,t){if(e)for(let n of t)this._addTrackedListener(e,n,e=>this.dispatchEvent(e))}};async function rx(e){let t=await ax(e);try{return await ix(t,e)}finally{t.dispose()}}async function ix(e,{samples:t=64,colorSpace:n=`srgb`,allowEarlyRetire:r=!1,onProgress:i=void 0}={}){let a=await e.renderFrames(t,{onProgress:i,allowEarlyRetire:r});return{...await e.renderToBuffer({colorSpace:n}),samples:a,retiredBy:a<t?`converged`:`count`,issues:e.issues,adapter:e.adapterInfo}}async function ax({canvas:e,model:t=null,width:n=1920,height:r=1080,strict:i=!0,profile:a=`physical`,deterministic:o=!0,settings:s=null}={}){if(!e)throw Error(`openHeadless: a canvas is required`);let c=new nx(e,{autoResize:!1,strict:i,profile:a});try{return c.setReservedRenderResolution(Math.max(n,r)),await c.init(),c.setCanvasSize(n,r),t&&await c.loadModel(t),s&&c.settings.setMany(s,{silent:!0}),o&&c.setDeterministicMode(!0),c}catch(e){throw c.dispose(),e}}xe();var ox=class{constructor(e){this._app=e,this._cancelled=!1,this._rendering=!1}async renderAnimation(e={}){let{clipIndex:t=0,fps:n=30,speed:r=1,samplesPerFrame:i=wt.maxSamples,enableOIDN:a=!0,onFrame:o,onProgress:s,onComplete:c}=e,l=this._app;if(!l.animationManager?.hasAnimations){console.warn(`VideoRenderManager: No animation clips available`),c?.(!1);return}let u=l.animationManager.clips[t];if(!u){console.warn(`VideoRenderManager: Invalid clip index ${t}`),c?.(!1);return}let d=u.duration/(r||1),f=e.totalFrames||Math.ceil(d*n),p=1/n;this._cancelled=!1,this._rendering=!0;let m=this._saveState();l.stopAnimation(),l.configureForMode(`production`),l.settings.setMany({maxSamples:i},{silent:!0}),l.stages.pathTracer?.updateCompletionThreshold?.(),l.cameraManager.controls&&(l.cameraManager.controls.enabled=!1);try{for(let e=0;e<f&&!this._cancelled;e++){let n=e*p*r,i=l.animationManager.seekTo(n,t);if(i?await l.refitBVH(i):l.reset(),l.stopAnimation(),await this._accumulateFrame(l),this._cancelled||(a&&l.denoisingManager?.finalDenoise&&await this._waitForDenoise(l),this._cancelled))break;let c=l.getCanvas();if(c&&o){let t=await createImageBitmap(c);await o(t,e,f),t.close()}let u={frame:e+1,totalFrames:f,percent:(e+1)/f*100};s?.(u),l.dispatchEvent({type:H.VIDEO_RENDER_PROGRESS,...u})}}catch(e){console.error(`VideoRenderManager: Render error:`,e),this._cancelled=!0}finally{this._restoreState(m),this._rendering=!1;let e=!this._cancelled;c?.(e),l.dispatchEvent({type:H.VIDEO_RENDER_COMPLETE,success:e})}}cancel(){this._cancelled=!0}get isRendering(){return this._rendering}async _accumulateFrame(e){let t=e.stages.pathTracer;if(t?.isReady)for(;!t.isComplete&&!this._cancelled;)e.cameraManager.camera.updateMatrixWorld(),e.pipeline.render(),t.frameCount%4==0&&(Te({samples:Ee(t)}),await new Promise(e=>setTimeout(e,0)))}_waitForDenoise(e){return new Promise(t=>{let n,r=()=>{e.removeEventListener(H.DENOISING_END,i),clearTimeout(n)},i=()=>{r(),t()};n=setTimeout(()=>{console.warn(`VideoRenderManager: Denoise timed out, skipping`),r(),t()},3e4),e.addEventListener(H.DENOISING_END,i),e.denoisingManager.onRenderComplete({isStillComplete:()=>!this._cancelled,context:e.pipeline?.context})})}_saveState(){let e=this._app,t=e.settings.getEffective();return{settings:Object.keys(Et(wt)).map(e=>[e,t[e]]),renderMode:e.stages.pathTracer?.renderMode?.value,controlsEnabled:e.cameraManager.controls?.enabled,oidnEnabled:e.denoisingManager?.finalDenoise,oidnQuality:e.denoisingManager?.oidnQuality,wasPlaying:e.animationManager?.isPlaying,pauseRendering:e.pauseRendering}}_restoreState(e){let t=this._app;for(let[n,r]of e.settings)r&&t.settings.set(n,r.value,{silent:!0,reset:!1,source:r.source});t.stages.pathTracer&&e.renderMode!==void 0&&t.stages.pathTracer?.setUniform(`renderMode`,parseInt(e.renderMode)),t.stages.pathTracer?.updateCompletionThreshold?.(),t.cameraManager.controls&&(t.cameraManager.controls.enabled=e.controlsEnabled??!0),t.denoisingManager?.denoiser&&(t.denoisingManager.applyOIDNEnabled(e.oidnEnabled??!1),e.oidnQuality&&t.denoisingManager.applyOIDNQuality(e.oidnQuality)),t.pauseRendering=e.pauseRendering??!1,t.denoisingManager?.setCadenceSuspended(!1),t.animationManager?.stop(),t.reset(),t.wake()}};xe(),Ar(),qt(),pb(),Db(),ca(),e.AF_DEFAULTS=Qe,e.ASVGF_QUALITY_PRESETS=We,e.AUTO_FOCUS_MODES=Ze,e.AnimationManager=qb,e.BVH_LEAF_MARKERS=ct,e.CAMERA_PRESETS=Xe,e.CAMERA_RANGES=Je,e.CameraManager=ay,e.ColorManagement=mo,e.DEFAULT_LUT_SIZE=Ca,e.DEFAULT_MAX_EV=Sa,e.DEFAULT_MIN_EV=xa,e.DEFAULT_TEXTURE_MATRIX=Ct,e.DEFAULT_WORKING_SPACE=ao,e.DLSS_NR_DEFAULTS=vb,e.DLSS_NR_MAX_PIXELS=bb,e.DLSS_NR_RANGES=xb,e.DenoisingManager=Lb,e.ENGINE_DEFAULTS=W,e.EngineEvents=H,e.EngineIssueError=dn,e.GoboManager=sy,e.IESManager=vy,e.INTERACTIVE_RENDER_CONFIG=Tt,e.ISSUE_CODES=ln,e.ISSUE_SEVERITY=un,e.InteractionManager=Dg,e.IssueLog=fn,e.LOG_LEVELS=Lt,e.LightManager=oy,e.Logger=Gt,e.MATERIAL_DEFAULTS=J,e.MATERIAL_VALUE_SOURCE=Sn,e.MAX_RESERVABLE_RENDER_SIZE=He,e.MAX_SCENE_BYTES=Yu,e.MAX_TABLE_TRANSFORMS=ta,e.MEMORY_CONSTANTS=Dt,e.MemoryLedger=ed,e.NRD_DEFAULTS=Ge,e.NRD_HIT_DIST_A=ze,e.NRD_HIT_DIST_B=Be,e.NRD_PRESET_KEYS=Ke,e.NRD_QUALITY_PRESETS=qe,e.OCIO_VIEW_BASE=ea,e.OverlayManager=Kb,e.PRODUCTION_RENDER_CONFIG=wt,e.PathTracerApp=nx,e.PipelineContext=dg,e.RENDER_PROFILES=Ie,e.RenderPipeline=Cg,e.RenderSettings=jg,e.RenderStage=V,e.SAFE_SCENE_BYTES=Ju,e.SETTING_SOURCE=kg,e.SKY_PRESETS=Ye,e.SR_MAX_INPUT=cb,e.SR_SCALE=ob,e.StageExecutionMode=ye,e.TEXTURE_CONSTANTS=dt,e.TRIANGLE_DATA_LAYOUT=$e,e.TransformManager=Yb,e.VIEW_TRANSFORMS=oa,e.VRAMTracker=tp,e.VideoRenderManager=ox,e.addAllOcioViews=Pa,e.addOcioView=Na,e.addViewTransform=Ji,e.applyMatrixRGBA8=Si,e.bakeLut=fa,e.bufferBytes=$f,e.buildOcioView=Aa,e.buildToneMapWGSL=Qi,e.canvasColorSpaceFor=lo,e.captureHeadless=ix,e.clearBindingAuditFindings=vg,e.clearInputOverrides=Ya,e.configureAssets=Dr,e.convertColor=li,e.convertEncodedRGBA8=_i,e.convertPixelsF32=ui,e.createLogger=Pt,e.deriveAlphaMode=En,e.describeAdapter=tx,e.displayCanvasFit=Er,e.estimateSceneBytes=Qu,e.extractMatrix=Ci,e.extractSceneMetadata=Jv,e.findNativeLinearSpace=po,e.fmt=Y,e.getActiveColorManagement=so,e.getAssetConfig=Or,e.getBindingAuditFindings=_g,e.getRegistryVersion=Hi,e.getRenderProfile=Le,e.getViewTransform=Wi,e.hasColorSpace=Ti,e.isColorManaged=ho,e.isDataSpace=wi,e.isDataTexture=to,e.linearToSrgb=pi,e.listFileRules=Qa,e.listInputOverrides=Xa,e.listViewTransforms=Gi,e.makeCpuSampler=va,e.measureBakeError=ba,e.onRegistryChange=Ui,e.openHeadless=ax,e.parseSceneMetadata=qv,e.probeAddressSpace=$u,e.removeViewTransform=Yi,e.renderHeadless=rx,e.renderUpscaled=rb,e.resolveInputSpace=eo,e.setActiveColorManagement=co,e.setBindingAudit=gg,e.setInputOverride=Ja,e.srgbToLinear=fi,e.textureBytes=ep,e.textureInputSpace=io});
|
|
1146
|
+
`,Tb=class e{constructor(e,t){this.chain=e,this.canvas=t,this.slot=0,this.source=null,this.staging=null,this._readbackPipeline=null,this._readbackStorage=null,this._readbackMap=null,this._hdrPipeline=null,this._hdrStorage=null,this._hdrMap=null,this._toneMapper=null,this.disposed=!1}get device(){return this.chain.device}get width(){return this.chain.pipeline.geometry.validWidth}get height(){return this.chain.pipeline.geometry.validHeight}static async create({width:t,height:n,canvas:r=null,settings:i={},onProgress:a=()=>{}}){if(!Number.isInteger(t)||!Number.isInteger(n)||t<1||n<1)throw Error(`NeuralRetouch.create: width and height must be positive integers`);if(t*n>4194304)throw Error(`NeuralRetouch.create: ${t}x${n} is ${(t*n/1e6).toFixed(1)} MP, above the ${(bb/1e6).toFixed(1)} MP this pass survives. Past it the run takes minutes and then loses every GPU device in the page.`);let o=r??document.createElement(`canvas`);r||(o.style.cssText=`position:fixed;left:-10000px;top:0;pointer-events:none`);let s=new e(await(await gb()).create(o,t,n,a,hb(i).runtime),o);return s._allocate(),s}_allocate(){let{validWidth:e,validHeight:t}=this.chain.pipeline.geometry;this.source=this.device.createBuffer({label:`rayzee:retouch-source`,size:e*t*8,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST}),this.staging=new Uint16Array(e*t*4);let n=e*t*4;this._readbackStorage=this.device.createBuffer({label:`rayzee:retouch-readback`,size:n,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC}),this._readbackMap=this.device.createBuffer({label:`rayzee:retouch-readback-map`,size:n,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ}),this._readbackPipeline=this.device.createComputePipeline({label:`rayzee:retouch-readback`,layout:`auto`,compute:{module:this.device.createShaderModule({code:Cb}),entryPoint:`main`}});let r=e*t*8;this._hdrStorage=this.device.createBuffer({label:`rayzee:retouch-hdr`,size:r,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC}),this._hdrMap=this.device.createBuffer({label:`rayzee:retouch-hdr-map`,size:r,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ}),this._hdrPipeline=this.device.createComputePipeline({label:`rayzee:retouch-hdr`,layout:`auto`,compute:{module:this.device.createShaderModule({code:wb}),entryPoint:`main`}})}async _packHDR(e,t,n=!1){let r=this.chain.pipeline.slots[this.slot]?.hdrOutput;if(!r)throw Error("NeuralRetouch: the runtime has no scene-referred output. Either no frame has been produced yet, or neural-runtime.js was re-vendored without its `rayzee-patch` edits.");let i=this.device.createBindGroup({layout:this._hdrPipeline.getBindGroupLayout(0),entries:[{binding:0,resource:r.createView()},{binding:1,resource:{buffer:this._hdrStorage}}]}),a=this.device.createCommandEncoder({label:`rayzee:retouch-hdr`}),o=a.beginComputePass();o.setPipeline(this._hdrPipeline),o.setBindGroup(0,i),o.dispatchWorkgroups(Math.ceil(e/8),Math.ceil(t/8)),o.end(),n&&a.copyBufferToBuffer(this._hdrStorage,0,this._hdrMap,0,e*t*8),this.device.queue.submit([a.finish()])}async readOutputHDR(){let{validWidth:e,validHeight:t}=this.chain.pipeline.geometry;await this._packHDR(e,t,!0),await this._hdrMap.mapAsync(GPUMapMode.READ);let n=new Uint16Array(this._hdrMap.getMappedRange().slice(0));return this._hdrMap.unmap(),{half:n,width:e,height:t}}async readOutputToned(e){let{validWidth:t,validHeight:n}=this.chain.pipeline.geometry;return await this._packHDR(t,n),this._toneMapper??=new Yy(this.device,`rayzee:retouch-tonemap`),this._toneMapper.ensureSize(t,n),{rgba8:await this._toneMapper.toRGBA8(this._hdrStorage,{exposure:e.exposure??1,toneMapping:e.toneMapping??0,saturation:e.saturation??1}),width:t,height:n}}async readOutput(){let{validWidth:e,validHeight:t}=this.chain.pipeline.geometry,n=this.chain.pipeline.slots[this.slot]?.output;if(!n)throw Error(`NeuralRetouch.readOutput: the pass has not produced a frame yet`);let r=this.device.createBindGroup({layout:this._readbackPipeline.getBindGroupLayout(0),entries:[{binding:0,resource:n.createView()},{binding:1,resource:{buffer:this._readbackStorage}}]}),i=this.device.createCommandEncoder({label:`rayzee:retouch-readback`}),a=i.beginComputePass();a.setPipeline(this._readbackPipeline),a.setBindGroup(0,r),a.dispatchWorkgroups(Math.ceil(e/8),Math.ceil(t/8)),a.end(),i.copyBufferToBuffer(this._readbackStorage,0,this._readbackMap,0,e*t*4),this.device.queue.submit([i.finish()]),await this._readbackMap.mapAsync(GPUMapMode.READ);let o=new Uint8ClampedArray(this._readbackMap.getMappedRange().slice(0));return this._readbackMap.unmap(),o}dispose(){if(!this.disposed){this.disposed=!0,this.source?.destroy(),this._readbackStorage?.destroy(),this._readbackMap?.destroy(),this._hdrStorage?.destroy(),this._hdrMap?.destroy(),this._toneMapper?.dispose();try{this.chain.destroy()}catch(e){yb.warn(`retouch teardown:`,e)}}}},Eb=20}));xe(),qt();var Ob=Pt(`neural`),kb=120,Ab=2,jb=1,Mb=0,Nb=300,Pb=5,Fb=3,Ib=3,Lb=class extends r.EventDispatcher{constructor({renderer:e,mainCanvas:t,stages:n,pipeline:r,getExposure:i,getSaturation:a}){super(),this.renderer=e,this.mainCanvas=t,this.upscalerCanvas=this._createUpscalerCanvas(t),this.pipeline=r,this._stages=n,this._getExposure=i,this._getSaturation=a,this.denoiser=null,this.upscaler=null,this.upscalerBackend=`esrgan`,this._neuralUpscaler=null,this.neuralRendering=!1,this.neuralRenderingSettings={},this._retouch=null,this._superResModule=null,this._neuralPostBusy=!1,this._finalQuality=W.oidnQuality,this.finalDenoise=W.enableOIDN,this.continuousDenoise=W.continuousDenoise,this.continuousDenoiseInterval=W.continuousDenoiseInterval,this._lastCadenceAt=-1/0,this._lastCadenceSamples=0,this._failedRefreshes=0,this._cadenceSuspended=!1,this._movingDenoiseMs=[],this._movingHopeless=!1,this._holdWhileMoving=null,this._onReset=null,this._onPostProcessRefresh=null,this._onDisplayRefresh=null,this._lastRenderWidth=0,this._lastRenderHeight=0,this._pendingStartUpscaler=null,this._pendingCloseDenoise=null,this._denoiserStartHandler=null,this._denoiserEndHandler=null,this._denoiserTileHandler=null,this._upscalerResChangedHandler=null,this._upscalerStartHandler=null,this._upscalerProgressHandler=null,this._upscalerEndHandler=null}_createUpscalerCanvas(e){let t=e.parentNode;if(!t)return null;let n=document.createElement(`canvas`);return n.width=e.width,n.height=e.height,n.style.position=`absolute`,n.style.inset=`0`,n.style.width=`100%`,n.style.height=`100%`,n.style.display=`none`,t.insertBefore(n,e),n}setRenderSize(e,t){this._lastRenderWidth=e,this._lastRenderHeight=t,this._cadenceDowngraded=!1,this._holdWhileMoving=null,this._movingDenoiseMs.length=0,this._movingHopeless=!1,this.denoiser?.abort(),this._unpublishOutput(),this.denoiser?.setSize(e,t),this.upscalerCanvas&&(this.upscalerCanvas.width!==e||this.upscalerCanvas.height!==t)&&(this.upscalerCanvas.width=e,this.upscalerCanvas.height=t),this.upscaler?.setBaseSize(e,t)}restoreBaseResolution(){return!this.upscalerCanvas||!this._lastRenderWidth||!this._lastRenderHeight||!(this.upscalerCanvas.width!==this._lastRenderWidth||this.upscalerCanvas.height!==this._lastRenderHeight)?!1:(this.upscalerCanvas.width=this._lastRenderWidth,this.upscalerCanvas.height=this._lastRenderHeight,!0)}setupDenoiser(){if(!this.upscalerCanvas)return;let e=this._stages.pathTracer;this.denoiser=new Fy(this.renderer,{...W,backendParams:()=>({device:this.renderer.backend.device,adapterInfo:null}),getGPUTextures:()=>{if(!e?.storageTextures?.readTarget)return null;let t=e.storageTextures.getReadTextures(),{backend:n}=this.renderer;return{color:n.get(t.color).texture,normal:n.get(t.normalDepth).texture,albedo:n.get(t.albedo).texture}}}),this._syncOIDNInUse(),this._denoiserStartHandler=e=>this.dispatchEvent({type:H.DENOISING_START,continuous:!!e.continuous}),this._denoiserEndHandler=e=>{this.denoiser?.hasOutput&&this._publishOutput(),this.dispatchEvent({type:H.DENOISING_END,continuous:!!e.continuous})},this._denoiserTileHandler=e=>{if(e.continuous)return;this._publishOutput();let t=this.pipeline?.context;this._stages.compositor&&t&&this._stages.compositor.render(t)},this.denoiser.addEventListener(`start`,this._denoiserStartHandler),this.denoiser.addEventListener(`end`,this._denoiserEndHandler),this.denoiser.addEventListener(`tileProgress`,this._denoiserTileHandler)}setupUpscaler(){if(!this.upscalerCanvas)return;let e=this._stages.pathTracer;this.upscaler=new Uy(this.upscalerCanvas,this.renderer,{scaleFactor:W.upscalerScale||2,quality:W.upscalerQuality||`fast`,getSourceCanvas:()=>this.renderer.domElement,refreshInput:()=>{let e=this.pipeline?.context;this._stages.compositor&&e&&this._stages.compositor.render(e)},getGPUTextures:()=>{if(!e?.storageTextures?.readTarget)return null;let t=e.storageTextures.getReadTextures();return{color:this.renderer.backend.get(t.color).texture}},getExposure:()=>this._getEffectiveExposure(),getToneMapping:()=>this._getToneMapping(),getSaturation:()=>this._getSaturation()}),this.upscaler.enabled=W.enableUpscaler||!1,this._upscalerResChangedHandler=e=>this.dispatchEvent({type:`resolution_changed`,width:e.width,height:e.height}),this._upscalerStartHandler=()=>this.dispatchEvent({type:H.UPSCALING_START}),this._upscalerProgressHandler=e=>this.dispatchEvent({type:H.UPSCALING_PROGRESS,progress:e.progress}),this._upscalerEndHandler=()=>this.dispatchEvent({type:H.UPSCALING_END}),this.upscaler.addEventListener(`resolution_changed`,this._upscalerResChangedHandler),this.upscaler.addEventListener(`start`,this._upscalerStartHandler),this.upscaler.addEventListener(`progress`,this._upscalerProgressHandler),this.upscaler.addEventListener(`end`,this._upscalerEndHandler)}get denoiserStrategy(){return this.continuousDenoise?`oidn`:this._stages.asvgf?.enabled?`asvgf`:this._stages.nrd?.enabled?`nrd`:this._stages.edgeFilter?.enabled?`edgeaware`:`none`}setDenoiserStrategy(e,t){let n=this._stages;switch(n.asvgf&&(n.asvgf.enabled=!1),n.nrd&&(n.nrd.enabled=!1),n.variance&&(n.variance.enabled=!1),n.bilateralFilter&&(n.bilateralFilter.enabled=!1),n.edgeFilter&&n.edgeFilter.setFilteringEnabled(!1),this._clearDenoiserTextures(),this.setContinuousDenoise(e===`oidn`),e){case`asvgf`:n.asvgf.enabled=!0,n.variance&&(n.variance.enabled=!0),n.bilateralFilter&&(n.bilateralFilter.enabled=!0),n.asvgf.setTemporalEnabled?.(!0),this._applyASVGFPreset(t||`medium`);break;case`nrd`:n.nrd&&(n.nrd.enabled=!0,n.nrd.resetHistory?.(),this._applyNRDPreset(t||`medium`));break;case`edgeaware`:n.variance&&(n.variance.enabled=!0),n.edgeFilter&&n.edgeFilter.setFilteringEnabled(!0);break}this._syncGBufferStages()}setASVGFEnabled(e,t){let n=this._stages;n.asvgf&&(n.asvgf.enabled=e),n.variance&&(n.variance.enabled=e),n.bilateralFilter&&(n.bilateralFilter.enabled=e),e&&(n.nrd&&(n.nrd.enabled=!1),n.asvgf?.setTemporalEnabled?.(!0),this._applyASVGFPreset(t||`medium`)),n.edgeFilter&&n.edgeFilter.setFilteringEnabled(!e),this._syncGBufferStages()}applyASVGFPreset(e){this._applyASVGFPreset(e)}setAutoExposureEnabled(e,t){let n=this._stages;n.autoExposure&&(n.autoExposure.enabled=e,!e&&this.renderer&&(this.renderer.toneMappingExposure=t))}get requiresMotionVectors(){return!!(this._stages.asvgf?.enabled||this._stages.nrd?.enabled)}_syncGBufferStages(){let e=this._stages,t=e.normalDepth,n=e.motionVector,r=this.requiresMotionVectors,i=r||!!(e.edgeFilter?.enabled||e.bilateralFilter?.enabled);t&&(i&&!t.enabled&&t.reset(),t.enabled=i),n&&(r&&!n.enabled&&(n.matricesInitialized=!1,n.isFirstFrame=!0,n.frameCount=0),n.enabled=r),e.pathTracer?.setAuxGBufferEnabled?.(i||!!this.denoiser?.enabled),e.pathTracer?.setCleanAuxNormal?.(!!this.denoiser?.enabled&&!!this.denoiser?.expectsCleanAux(this._finalQuality));for(let r of[e.asvgf,e.nrd,e.variance,e.bilateralFilter,e.edgeFilter,t,n])r&&!r.enabled&&r.releaseGPUMemory?.()}_cleanupCompletionListener(){this.denoiser&&(this._pendingStartUpscaler&&this.denoiser.removeEventListener(`end`,this._pendingStartUpscaler),this._pendingCloseDenoise&&this.denoiser.removeEventListener(`end`,this._pendingCloseDenoise)),this._pendingStartUpscaler=null,this._pendingCloseDenoise=null}get holdsWhileMoving(){if(!this._stages.pathTracer?.viewIsChanging||!this.continuousDenoise||this._cadenceSuspended||!this.denoiser?.enabled||this._movingHopeless)return!1;let e=this.movingCostMs,t=this._movingDenoiseMs.length;e>Nb*Fb&&(this._movingHopeless=!0);let n=!this._movingHopeless&&(t<2||e<=Nb);return this._holdWhileMoving=(this._holdWhileMoving===null||this._holdWhileMoving)&&n,this._holdWhileMoving}skipsTrace(){return this.holdsWhileMoving&&!!this.denoiser?.state.isDenoising}get movingCostMs(){return this._movingDenoiseMs.length?Math.min(...this._movingDenoiseMs):0}_publishOutput(){let e=this.pipeline?.context,t=this.denoiser?.outputTexture;e&&t&&e.setTexture(`oidn:output`,t)}_unpublishOutput(){this.pipeline?.context?.removeTexture(`oidn:output`),this.denoiser?.invalidateOutput()}_checkHeldFrameHealthy(){!this.denoiser?.hasOutput||this._failedRefreshes<Ib||this._unpublishOutput()}tickContinuousDenoise(e){let t=this.denoiser;if(!this.continuousDenoise||this._cadenceSuspended||!t)return!1;this._checkHeldFrameHealthy();let n=!!this._stages.pathTracer?.viewIsChanging;if(!n)this._holdWhileMoving=null,this._movingDenoiseMs.length=0;else if(!this.holdsWhileMoving)return!1;if(t.state.isDenoising||t.state.isLoading||!n&&e<=this._lastCadenceSamples)return!1;let r=performance.now(),i=n?Mb:this._lastCadenceSamples===0?jb:Ab,a=Math.max(this.continuousDenoiseInterval,t.lastDenoiseMs*i);if(r-this._lastCadenceAt<a)return!1;this._lastCadenceAt=r,this._lastCadenceSamples=e,t.lastDenoiseMs>kb&&(this._cadenceDowngraded=!0);let o=this._cadenceDowngraded?this.previewQuality():this._finalQuality;return t.quality!==o&&t.updateQuality(o),t.start({continuous:!0}).then(e=>{this._failedRefreshes=e?0:this._failedRefreshes+1,!(!e||!n)&&(this._movingDenoiseMs.push(t.lastDenoiseMs),this._movingDenoiseMs.length>Pb&&this._movingDenoiseMs.shift())}),!0}previewQuality(){return this.denoiser?.expectsCleanAux(this._finalQuality)?`fast-clean`:`fast`}setCadenceSuspended(e){this._cadenceSuspended=!!e,this._cadenceSuspended&&(this.denoiser?.abort(),this._unpublishOutput())}setContinuousDenoise(e){this.continuousDenoise=!!e,this._syncOIDNInUse(),this._lastCadenceAt=-1/0,this._resetCadence()}_useFinalQuality(){let e=this.denoiser;e&&e.quality!==this._finalQuality&&e.updateQuality(this._finalQuality)}_resetCadence(){this._lastCadenceSamples=0}setUpscalerBackend(e){let t=e===`neural`?`neural`:`esrgan`;t!==this.upscalerBackend&&(this.upscalerBackend=t,this._restoreRenderDisplay(),t!==`neural`&&this._releaseNeuralUpscaler())}_restoreRenderDisplay(){let e=this.upscalerCanvas&&this.upscalerCanvas.style.display!==`none`;return this.upscalerCanvas&&(this.upscalerCanvas.style.display=`none`),this.mainCanvas&&(this.mainCanvas.style.opacity=`1`),e&&this._lastRenderWidth&&this._lastRenderHeight&&this.dispatchEvent({type:`resolution_changed`,width:this._lastRenderWidth,height:this._lastRenderHeight}),!!e}_releaseNeuralUpscaler(){this._neuralUpscaler?.dispose(),this._neuralUpscaler=null,this._superResModule?.releaseDenoisedReader()}setNeuralRendering(e,t=null){this.neuralRendering=!!e,t&&(this.neuralRenderingSettings={...this.neuralRenderingSettings,...t}),this.neuralRendering||(this._releaseNeuralRetouch(),this._restoreRenderDisplay())}_releaseNeuralRetouch(){this._retouch?.dispose(),this._retouch=null}async _runNeuralPost(e){let t=this.upscaler?.enabled&&this.upscalerBackend===`neural`,n=this.neuralRendering;if(!(!t&&!n)&&!this._neuralPostBusy){if(!this.upscalerCanvas){Ob.warn(`neural pass skipped: the engine has no overlay canvas to present on`);return}if(!this.pipeline?.context?.getTexture(`oidn:output`)){Ob.warn(`neural pass skipped: no denoised picture — it needs OIDN`);return}this._neuralPostBusy=!0,this.dispatchEvent({type:H.UPSCALING_START});try{let r=await Promise.resolve().then(()=>(pb(),Zy));this._superResModule=r;let i=n?await Promise.resolve().then(()=>(Db(),mb)):null,a=this.denoiser?._outTexSize,o=(a?.width??0)*(a?.height??0),s=n&&o<=i.RETOUCH_MAX_PIXELS;if(n&&!s&&(Ob.warn(`Neural rendering skipped: the render is ${(o/1e6).toFixed(1)} MP, above the ${(i.RETOUCH_MAX_PIXELS/1e6).toFixed(1)} MP the pass survives.`+(t?` The upscale still ran.`:``)),this._releaseNeuralRetouch()),!t&&!s)return;let c={exposure:this._getEffectiveExposure(),toneMapping:this._getToneMapping(),saturation:this._getSaturation?.()??1},l=await r.readDenoisedHalf(this.denoiser);t&&(this._neuralUpscaler&&(this._neuralUpscaler.inputWidth!==l.width||this._neuralUpscaler.inputHeight!==l.height)&&this._releaseNeuralUpscaler(),this._neuralUpscaler||=await r.NeuralSuperRes.create({width:l.width,height:l.height}));let u=l;if(s){let e=await i.enhanceFrame({source:u,settings:this.neuralRenderingSettings,instance:this._retouch,exposure:c.exposure,tone:t?null:c});this._retouch=e.instance,u=e}if(t&&(u=await this._neuralUpscaler.upscaleToRGBA8(u,c)),!e()){this.dropDisplay();return}if(r.presentRGBA8(this.upscalerCanvas,u.rgba8,u.width,u.height),!e()){this.dropDisplay();return}this.mainCanvas&&(this.mainCanvas.style.opacity=`0`),this.dispatchEvent({type:`resolution_changed`,width:u.width,height:u.height})}catch(e){Ob.warn(`neural pass failed`,e)}finally{this._neuralPostBusy=!1,this.dispatchEvent({type:H.UPSCALING_END})}}}onRenderComplete({isStillComplete:e,context:t}){this._cleanupCompletionListener();let n=this.finalDenoise?`final`:this.continuousDenoise?`refresh`:null,r=()=>{if(this.denoiser?.removeEventListener(`end`,r),this._pendingStartUpscaler=null,e()){if(n&&this._onDisplayRefresh?.(),this.neuralRendering||this.upscaler?.enabled&&this.upscalerBackend===`neural`){this._runNeuralPost(e);return}this.upscaler?.enabled&&this.upscaler.start()}};if(!n){r();return}let i=()=>{e()&&(this._pendingStartUpscaler=r,this.denoiser.addEventListener(`end`,r),n===`final`?(this._useFinalQuality(),this.denoiser.start()):this.denoiser.start({continuous:!0}))};if(this._resetCadence(),this.denoiser.state.isDenoising){let e=()=>{this.denoiser?.removeEventListener(`end`,e),this._pendingCloseDenoise===e&&(this._pendingCloseDenoise=null),i()};this._pendingCloseDenoise=e,this.denoiser.addEventListener(`end`,e)}else i()}abort(e,{keepDisplay:t=!1}={}){this._cleanupCompletionListener(),this._restoreRenderDisplay(),e&&e!==this.mainCanvas&&(e.style.opacity=`1`),this.upscaler&&this.upscaler.abort();let n=!!this._stages.pathTracer?.viewIsChanging,r=t&&this.continuousDenoise&&!this._cadenceSuspended&&!!this.denoiser?.hasOutput&&(!n||this.holdsWhileMoving);this.denoiser&&!r&&(this.denoiser.enabled&&this.denoiser.abort(),this._unpublishOutput()),this._resetCadence()}dropDisplay(){this._unpublishOutput(),this._restoreRenderDisplay()}dispose(){this._cleanupCompletionListener(),this._releaseNeuralUpscaler(),this._releaseNeuralRetouch(),this._unpublishOutput(),this.denoiser&&=(this._denoiserStartHandler&&this.denoiser.removeEventListener(`start`,this._denoiserStartHandler),this._denoiserEndHandler&&this.denoiser.removeEventListener(`end`,this._denoiserEndHandler),this._denoiserTileHandler&&this.denoiser.removeEventListener(`tileProgress`,this._denoiserTileHandler),this.denoiser.dispose(),null),this.upscaler&&(this._upscalerResChangedHandler&&this.upscaler.removeEventListener(`resolution_changed`,this._upscalerResChangedHandler),this._upscalerStartHandler&&this.upscaler.removeEventListener(`start`,this._upscalerStartHandler),this._upscalerProgressHandler&&this.upscaler.removeEventListener(`progress`,this._upscalerProgressHandler),this._upscalerEndHandler&&this.upscaler.removeEventListener(`end`,this._upscalerEndHandler),this.upscaler.dispose(),this.upscaler=null,this.upscalerBackend=`esrgan`,this._neuralUpscaler=null),this._denoiserStartHandler=null,this._denoiserEndHandler=null,this._denoiserTileHandler=null,this._upscalerResChangedHandler=null,this._upscalerStartHandler=null,this._upscalerProgressHandler=null,this._upscalerEndHandler=null,this._onReset=null,this._onPostProcessRefresh=null,this._onDisplayRefresh=null,this.upscalerCanvas?.parentNode&&(this.upscalerCanvas.parentNode.removeChild(this.upscalerCanvas),this.upscalerCanvas=null)}setOverlayManager(e){this._overlayManager=e}setResetCallback(e){this._onReset=e}setPostProcessRefreshCallback(e){this._onPostProcessRefresh=e}setDisplayRefreshCallback(e){this._onDisplayRefresh=e}setSettings(e){this._settings=e}setASVGFParams(e){this._stages.asvgf?.updateParameters(e)}toggleASVGFHeatmap(e){this._stages.asvgf?.setHeatmapEnabled?.(e)}configureASVGFForMode(e){this._stages.asvgf&&(this._stages.asvgf.enabled=e.enabled,this._stages.variance&&(this._stages.variance.enabled=e.enabled),this._stages.bilateralFilter&&(this._stages.bilateralFilter.enabled=e.enabled),e.enabled&&this._stages.asvgf.updateParameters(e),this._syncGBufferStages())}setEdgeAwareParams(e){this._stages.edgeFilter?.updateUniforms(e)}setAutoExposureParams(e){this._stages.autoExposure?.updateParameters(e)}applyOIDNEnabled(e){this.finalDenoise=!!e,this._syncOIDNInUse()}get oidnQuality(){return this._finalQuality}setOIDNEnabled(e){this.applyOIDNEnabled(e),this._syncGBufferStages(),this._onPostProcessRefresh?.()}_syncOIDNInUse(){this.denoiser&&(this.denoiser.enabled=this.finalDenoise||this.continuousDenoise)}applyOIDNQuality(e){this._finalQuality=e,this._cadenceDowngraded=!1,this.denoiser?.updateQuality(e)}setOIDNQuality(e){this.applyOIDNQuality(e),this._syncGBufferStages(),this._onPostProcessRefresh?.()}setTileHelperEnabled(e){this._setTileHelper(e)}setUpscalerEnabled(e){this.upscaler&&(this.upscaler.enabled=e),e||this._restoreRenderDisplay()}setUpscalerScaleFactor(e){this.upscaler?.setScaleFactor(e)}setUpscalerQuality(e){this.upscaler?.setQuality(e)}setAutoExposure(e){this.setAutoExposureEnabled(e,this._getExposure()),this._onReset?.()}setStrategy(e,t){this.setDenoiserStrategy(e,t),this._onReset?.()}setNRDParams(e){this._stages.nrd?.updateParameters(e)}applyNRDPreset(e){this._applyNRDPreset(e)}setNRDDebugMode(e){this._stages.nrd?.updateParameters({debugMode:e})}_setTileHelper(e){let t=this._overlayManager?.getHelper(`tiles`);t&&(t.enabled=e,e||t.hide())}_getEffectiveExposure(){return this._stages.autoExposure?.enabled?this.renderer.toneMappingExposure:this._getExposure()}_getToneMapping(){return this.renderer.toneMapping}_clearDenoiserTextures(){let e=this.pipeline?.context;e&&[`asvgf:output`,`asvgf:demodulated`,`asvgf:gradient`,`variance:output`,`bilateralFiltering:output`,`edgeFiltering:output`,`nrd:output`,`oidn:output`].forEach(t=>e.removeTexture(t))}_applyNRDPreset(e){let t=qe[e];if(!t)return;let n={};for(let e of Ke)n[e]=Ge[e];this._stages.nrd?.updateParameters({...n,...t})}_applyASVGFPreset(e){let t=We[e];t&&(this._stages.asvgf?.updateParameters(t),this._stages.bilateralFilter?.updateParameters(t),this._stages.variance&&t.varianceBoost!==void 0&&(this._stages.variance.varianceBoost.value=t.varianceBoost))}},Rb=class{constructor(){this.layer=`hud`,this.visible=!1,this._tileBounds=null,this._imageWidth=1,this._imageHeight=1,this.enabled=!0,this._borderColor=`rgba(255, 0, 0, 0.6)`,this._borderWidthRatio=1/540,this._borderWidthMin=1.5,this._borderWidthMax=4}setActiveTile(e){this._tileBounds=e}setRenderSize(e,t){this._imageWidth=e,this._imageHeight=t}render(e,t,n){if(!this._tileBounds)return;let r=this._tileBounds,i=t/this._imageWidth,a=n/this._imageHeight,o=r.x*i,s=r.y*a,c=r.width*i,l=r.height*a,u=Math.min(this._borderWidthMax,Math.max(this._borderWidthMin,Math.min(t,n)*this._borderWidthRatio));e.strokeStyle=this._borderColor,e.lineWidth=u,e.strokeRect(o,s,c,l)}show(){this.enabled&&(this.visible=!0)}hide(){this.visible=!1,this._tileBounds=null}dispose(){this.visible=!1}},zb=class{constructor(e,i){this.layer=`scene`,this._enabled=!0,this._outlineNode=(0,g.outline)(e,i,{selectedObjects:[],edgeThickness:(0,n.uniform)(1),edgeGlow:(0,n.uniform)(0)});let a=(0,n.uniform)(3),o=(0,n.uniform)(new r.Color(16777215)),s=(0,n.uniform)(new r.Color(1640965)),{visibleEdge:c,hiddenEdge:l}=this._outlineNode,u=c.mul(o).add(l.mul(s)).mul(a),d=u.r.max(u.g).max(u.b).clamp(0,1);this._material=new t.MeshBasicNodeMaterial,this._material.colorNode=(0,n.vec4)(u,d),this._material.transparent=!0,this._material.blending=r.CustomBlending,this._material.blendEquation=r.AddEquation,this._material.blendSrc=r.OneFactor,this._material.blendDst=r.OneFactor,this._material.blendEquationAlpha=r.AddEquation,this._material.blendSrcAlpha=r.OneFactor,this._material.blendDstAlpha=r.OneFactor,this._material.toneMapped=!1,this._material.depthTest=!1,this._material.depthWrite=!1,this._quad=new t.QuadMesh(this._material)}setSelectedObjects(e){this._outlineNode.selectedObjects=e}get visible(){return this._enabled&&this._outlineNode.selectedObjects.length>0}render(e){if(!this.visible)return;let t=e.autoClear;e.autoClear=!1,e.setRenderTarget(null),this._quad.render(e),e.autoClear=t}show(){this._enabled=!0}hide(){this._enabled=!1}dispose(){this._enabled=!1,this._outlineNode?.dispose(),this._material?.dispose(),this._quad=null}};function Bb(e=!1){let t=document.createElement(`canvas`);return t.style.cssText=`position:absolute;top:0;left:0;width:100%;height:100%;pointer-events:none;`+(e?`display:none;`:``),t}function Vb(e,t=1/0){let n=e?.getBoundingClientRect();if(!n||n.width===0||n.height===0)return null;let r=Math.min(window.devicePixelRatio||1,2),i=Math.round(n.width*r),a=Math.round(n.height*r),o=t/Math.max(i,a);return o<1&&(i=Math.max(1,Math.round(i*o)),a=Math.max(1,Math.round(a*o))),{width:i,height:a}}var Hb=4096,Ub=class{constructor(){this.canvas=Bb(!0),this._visible=!1,this.renderer=null,this._sizeSource=null}async init({device:e,sizeSource:n}){this._sizeSource=n;let i=e.onuncapturederror,a=new t.WebGPURenderer({canvas:this.canvas,device:e,alpha:!0,antialias:(window.devicePixelRatio||1)<2});return await a.init(),e.onuncapturederror=i,a.outputColorSpace=r.SRGBColorSpace,a.setPixelRatio(1),a.setClearColor(0,0),a.autoClear=!1,this.renderer=a,this.syncSize(),this}get isVisible(){return this._visible}syncSize(){if(!this.renderer)return;let e=Vb(this._sizeSource,Hb);!e||e.width===this.canvas.width&&e.height===this.canvas.height||this.renderer.setSize(e.width,e.height,!1)}begin(){this.renderer&&(this.renderer.setRenderTarget(null),this.renderer.clear())}setVisible(e){this._visible!==e&&(this._visible=e,this.canvas.style.display=e?``:`none`)}dispose(){Ae(this.renderer),this.renderer=null,this.canvas.parentElement?.removeChild(this.canvas)}};qt();var Wb=Pt(`overlay`),Gb=(e,t)=>e.visible&&e.layer===t&&e.render,Kb=class{constructor(e){this.camera=e,this._helpers=new Map,this._hudCanvas=Bb(),this._hudCtx=this._hudCanvas.getContext(`2d`),this._helperScene=null,this._viewOverlay=null}async initViewRenderer({device:e,sizeSource:t}){if(!(!e||!t))try{this._viewOverlay=await new Ub().init({device:e,sizeSource:t})}catch(e){Wb.error(`overlay surface unavailable — light gizmos, transform gizmo and outlines are disabled`,e),this._viewOverlay=null}}setHelperScene(e){this._helperScene=e}getHUDCanvas(){return this._hudCanvas}mount(e){if(!e)return;let t=this._viewOverlay?.canvas;t&&t.parentElement!==e&&e.appendChild(t),this._hudCanvas.parentElement!==e&&e.appendChild(this._hudCanvas)}setupDefaultHelpers({helperScene:e,meshScene:t,pipeline:n,denoisingManager:r,app:i,renderWidth:a,renderHeight:o}){this.setHelperScene(e);let s=new Rb;this.register(`tiles`,s),s.setRenderSize(a||1,o||1),i.addEventListener(`resolution_changed`,e=>{s.setRenderSize(e.width,e.height)}),n.eventBus.on(`pipeline:reset`,()=>s.hide()),this._wireDenoiserTileEvents(s,r);let c=new zb(t,this.camera);this.register(`outline`,c)}_wireDenoiserTileEvents(e,t){let n=[t?.denoiser,t?.upscaler];for(let t of n)t&&(t.addEventListener(`tileProgress`,t=>{t.continuous||t.tile&&(e.setRenderSize(t.imageWidth,t.imageHeight),e.setActiveTile(t.tile),e.show(),this.refreshHUD())}),t.addEventListener(`end`,()=>{e.hide(),this.refreshHUD()}))}register(e,t){this._helpers.has(e)&&(Wb.warn(`helper "${e}" already registered — replacing.`),this._helpers.get(e).dispose?.()),this._helpers.set(e,t)}unregister(e){let t=this._helpers.get(e);t&&(t.dispose?.(),this._helpers.delete(e))}show(e){this._helpers.get(e)?.show()}hide(e){this._helpers.get(e)?.hide()}toggle(e){let t=this._helpers.get(e);t&&(t.visible?t.hide():t.show())}getHelper(e){return this._helpers.get(e)??null}isVisible(e){return this._helpers.get(e)?.visible??!1}showAll(){for(let e of this._helpers.values())e.show()}hideAll(){for(let e of this._helpers.values())e.hide()}render(){let e=this._viewOverlay;if(e){let t=this._hasVisibleSceneOverlay();(t||e.isVisible)&&(e.syncSize(),e.begin(),t&&this._renderSceneLayer(e.renderer),e.setVisible(t))}this.refreshHUD()}_renderSceneLayer(e){this._helperScene?.render(e,this.camera);for(let t of this._helpers.values())Gb(t,`scene`)&&t.render(e,this.camera)}_hasVisibleSceneOverlay(){if(this._helperScene?.isDrawing)return!0;for(let e of this._helpers.values())if(Gb(e,`scene`))return!0;return!1}refreshHUD(){let e=this._hudCanvas,t=this._hudCtx,n=!1;for(let e of this._helpers.values())if(Gb(e,`hud`)){n=!0;break}if(!n){e.style.display!==`none`&&(e.style.display=`none`);return}e.style.display!==``&&(e.style.display=``);let r=e.clientWidth,i=e.clientHeight,a=r>0&&i>0?Vb(e):null;if(a){(e.width!==a.width||e.height!==a.height)&&(e.width=a.width,e.height=a.height),t.clearRect(0,0,a.width,a.height),t.save(),t.scale(a.width/r,a.height/i);for(let e of this._helpers.values())Gb(e,`hud`)&&e.render(t,r,i);t.restore(),e.style.display!==``&&(e.style.display=``)}}dispose(){for(let e of this._helpers.values())e.dispose?.();this._helpers.clear(),this._viewOverlay?.dispose(),this._viewOverlay=null,this._hudCanvas.parentElement&&this._hudCanvas.parentElement.removeChild(this._hudCanvas)}};xe();var qb=class extends r.EventDispatcher{constructor(){super(),this.mixer=null,this.timer=new r.Timer,this.actions=[],this.isPlaying=!1,this._scene=null,this._mixerRoot=null,this._meshes=null,this._meshTriRanges=null,this._meshPositions=null,this._tempVec=new r.Vector3,this._skinnedCache=null,this._clipsCache=null,this._savedTimeScale=1,this.onFinished=null,this.wakeCallback=null}init(e,t,n,i){if(this.dispose(),!i||i.length===0)return;this._scene=e,this._mixerRoot=t,this._meshes=n,this.mixer=new r.AnimationMixer(t);let a=i.map(e=>this.mixer.clipAction(e)),o=(e,t)=>e.name===t||e.getObjectByName(t)!==void 0;!a.some(e=>e.getClip().tracks.some(e=>{let n=e.name.split(`.`)[0];return o(t,n)}))&&t!==e&&(console.log(`[AnimationManager] Tracks did not resolve from model root, retrying with scene root`),this.mixer=new r.AnimationMixer(e),this._mixerRoot=e,a=i.map(e=>this.mixer.clipAction(e))),this.actions=a,this.mixer.addEventListener(`finished`,()=>{this.isPlaying=!1,this.timer.reset(),this.onFinished&&this.onFinished()}),this._meshTriRanges=[],this._skinnedCache=[];let s=0;for(let e of n){let t=e.geometry,n=t.attributes.position,r=t.index?t.index.array:null,i=r?r.length/3:n.count/3,a=n.count;this._meshTriRanges.push({start:s,count:i,uniqueVerts:a,indices:r}),s+=i}this._skinnedCache=[],this._meshPositions=[];let c=n.filter(e=>e.isSkinnedMesh).length;console.debug(`[AnimationManager] Init: ${i.length} clips, ${n.length} meshes (${c} skinned), ${s} triangles`)}play(e=0){if(!(!this.mixer||this.actions.length===0)){if(this.mixer.stopAllAction(),e===-1)for(let e of this.actions)e.play();else e>=0&&e<this.actions.length&&this.actions[e].play();this.timer.reset(),this.isPlaying=!0,this.wakeCallback?.(),this.dispatchEvent({type:H.ANIMATION_STARTED})}}pause(){this.mixer&&(this.mixer.timeScale=0,this.timer.reset(),this.isPlaying=!1,this.dispatchEvent({type:H.ANIMATION_PAUSED}))}resume(){this.mixer&&(this.mixer.timeScale=this._savedTimeScale||1,this.timer.reset(),this.isPlaying=!0,this.wakeCallback?.(),this.dispatchEvent({type:H.ANIMATION_STARTED}))}stop(){this.mixer&&(this.mixer.stopAllAction(),this.mixer.timeScale=this._savedTimeScale||1,this.timer.reset(),this.isPlaying=!1,this.dispatchEvent({type:H.ANIMATION_STOPPED}))}setSpeed(e){this._savedTimeScale=e,this.mixer&&this.isPlaying&&(this.mixer.timeScale=e)}setLoop(e){let t=e?r.LoopRepeat:r.LoopOnce;for(let n of this.actions)n.setLoop(t),n.clampWhenFinished=!e}seekTo(e,t=0){if(!this.mixer||this.actions.length===0)return null;if(this.mixer.stopAllAction(),t===-1)for(let e of this.actions)e.play();else t>=0&&t<this.actions.length&&this.actions[t].play();this.mixer.setTime(e);for(let e of this.actions)e.isRunning()&&(e.paused=!0);return this._poseReader()}get currentTime(){return this.mixer?.time||0}update(){if(!this.isPlaying||!this.mixer)return null;this.timer.update();let e=this.timer.getDelta();return this.mixer.update(e),this._poseReader()}_scratch(e,t,n){let r=e[t];return r&&r.length===n?r:e[t]=new Float32Array(n)}_poseReader(){return this._mixerRoot.updateMatrixWorld(!0),e=>this._computeMeshPositions(e)}_computeMeshPositions(e){let t=this._tempVec,n=this._meshes[e],{count:r,uniqueVerts:i,indices:a}=this._meshTriRanges[e],o=this._scratch(this._skinnedCache,e,i*3),s=this._scratch(this._meshPositions,e,r*9),c=n.matrixWorld;for(let e=0;e<i;e++)n.getVertexPosition(e,t),t.applyMatrix4(c),o[e*3]=t.x,o[e*3+1]=t.y,o[e*3+2]=t.z;if(a)for(let e=0;e<r;e++){let t=e*3,n=a[t]*3,r=a[t+1]*3,i=a[t+2]*3,c=e*9;s[c]=o[n],s[c+1]=o[n+1],s[c+2]=o[n+2],s[c+3]=o[r],s[c+4]=o[r+1],s[c+5]=o[r+2],s[c+6]=o[i],s[c+7]=o[i+1],s[c+8]=o[i+2]}else for(let e=0;e<r;e++){let t=e*3*3,n=(e*3+1)*3,r=(e*3+2)*3,i=e*9;s[i]=o[t],s[i+1]=o[t+1],s[i+2]=o[t+2],s[i+3]=o[n],s[i+4]=o[n+1],s[i+5]=o[n+2],s[i+6]=o[r],s[i+7]=o[r+1],s[i+8]=o[r+2]}return s}get hasAnimations(){return this.actions.length>0}get clips(){return this._clipsCache||=this.actions.map((e,t)=>{let n=e.getClip();return{index:t,name:n.name||`Clip ${t}`,duration:n.duration}}),this._clipsCache}dispose(){this.mixer&&=(this.mixer.stopAllAction(),this.mixer.uncacheRoot(this._mixerRoot),null),this.actions=[],this.isPlaying=!1,this.timer.reset(),this._scene=null,this._mixerRoot=null,this._meshes=null,this._meshTriRanges=null,this._meshPositions=null,this._skinnedCache=null,this._clipsCache=null}};xe();var Jb=new r.Vector3(0,0,-1),Yb=class{constructor({camera:e,canvas:t,orbitControls:n,app:i}){this._app=i,this._orbitControls=n,this._camera=e,this._controls=new _.TransformControls(e,t),this._gizmoScene=new r.Scene,this._gizmoScene.add(this._controls.getHelper()),this._attached=null,this._isDragging=!1,this._meshes=null,this._refitInFlight=!1,this._baselineComputed=!1,this._tempForward=new r.Vector3,this._lightTargetDistance=null,this._lastLightPosition=null,this._onDraggingChanged=this._onDraggingChanged.bind(this),this._onObjectChange=this._onObjectChange.bind(this),this._controls.addEventListener(`dragging-changed`,this._onDraggingChanged),this._controls.addEventListener(`objectChange`,this._onObjectChange)}setMeshData(e){this._meshes=e}attach(e){if(this._attached!==e&&(this._controls.attach(e),this._attached=e,this._lightTargetDistance=null,this._lastLightPosition=null,e.isLight&&e.target)){let t=e.target.position.clone().sub(e.position),n=t.length();n>1e-4?(e.quaternion.setFromUnitVectors(Jb,t.normalize()),this._lightTargetDistance=n):this._lightTargetDistance=1,this._lastLightPosition=e.position.clone()}}detach(){this._attached&&(this._controls.detach(),this._attached=null,this._lightTargetDistance=null,this._lastLightPosition=null)}setMode(e){this._controls.setMode(e),this._app?.dispatchEvent({type:H.TRANSFORM_MODE_CHANGED,mode:e}),this._app?.refreshFrame()}setSpace(e){this._controls.setSpace(e),this._app?.refreshFrame()}get isDragging(){return this._isDragging}get attachedObject(){return this._attached}get controls(){return this._controls}render(e){if(!this._attached)return;let t=e.autoClear;e.autoClear=!1,e.clearDepth(),e.setRenderTarget(null),e.render(this._gizmoScene,this._camera),e.autoClear=t}_onDraggingChanged(e){this._isDragging=e.value,this._orbitControls&&(this._orbitControls.enabled=!e.value),e.value?this._app.dispatchEvent({type:H.OBJECT_TRANSFORM_START}):(this._attached?.isLight?this._finalizeLightTransform():this._recomputeAndRefit(),this._app.dispatchEvent({type:H.OBJECT_TRANSFORM_END}))}_onObjectChange(){this._app.needsReset=!0,this._app.wake(),this._attached?.isLight&&this._syncLightDuringDrag()}_syncLightDuringDrag(){let e=this._attached;if(e.target){let t=this._controls.mode;if(t===`translate`&&this._lastLightPosition){let t=this._tempForward.copy(e.position).sub(this._lastLightPosition);e.target.position.add(t),e.target.updateMatrixWorld(!0)}else if(t===`rotate`&&this._lightTargetDistance!=null){let t=this._tempForward.set(0,0,-1).applyQuaternion(e.quaternion);e.target.position.copy(e.position).addScaledVector(t,this._lightTargetDistance),e.target.updateMatrixWorld(!0)}this._lastLightPosition.copy(e.position)}this._app.lightManager?.updateLights()}_finalizeLightTransform(){let e=this._attached;e.isRectAreaLight&&(e.scale.x!==1||e.scale.y!==1)&&(e.width*=e.scale.x,e.height*=e.scale.y,e.scale.set(1,1,1)),this._app.lightManager?.updateLights()}_recomputeAndRefit(){if(!this._meshes||this._refitInFlight||!this._attached)return;this._attached.updateMatrixWorld(!0);let e=this._findAffectedMeshIndices(this._attached);if(e.length!==0){this._refitInFlight=!0;try{this._app.updateMeshTransforms(e)}catch(e){console.error(`Transform refit error:`,e)}finally{this._refitInFlight=!1}}}_findAffectedMeshIndices(e){let t=[];for(let n=0;n<this._meshes.length;n++){let r=this._meshes[n];(r===e||this._isDescendantOf(r,e))&&t.push(n)}return t}_isDescendantOf(e,t){let n=e.parent;for(;n;){if(n===t)return!0;n=n.parent}return!1}dispose(){this._controls.removeEventListener(`dragging-changed`,this._onDraggingChanged),this._controls.removeEventListener(`objectChange`,this._onObjectChange),this.detach(),this._gizmoScene.remove(this._controls.getHelper()),this._controls.dispose(),this._meshes=null,this._baselineComputed=!1,this._tempForward=null,this._lightTargetDistance=null,this._lastLightPosition=null,this._app=null,this._orbitControls=null,this._camera=null,this._controls=null,this._gizmoScene=null}},Xb=class{constructor(e){this.layer=`scene`,this._transformManager=e,this._enabled=!0}get visible(){return this._enabled&&this._transformManager.attachedObject!==null}render(e){this._transformManager.render(e)}show(){this._enabled=!0}hide(){this._enabled=!1}dispose(){this._enabled=!1}};qt(),xe(),ca();var Zb=new WeakMap,Qb=Pt(`engine`);function $b(e,t){e.lost.then(e=>{t.app&&t.app._handleDeviceLost(e)})}var ex=/swiftshader|llvmpipe|lavapipe|basic render|microsoft basic|warp/i;function tx(e){let t=e.info??{},n=`${t.vendor??``} ${t.architecture??``} ${t.device??``} ${t.description??``}`;return{vendor:t.vendor??``,architecture:t.architecture??``,device:t.device??``,description:t.description??``,isSoftware:t.isFallbackAdapter===!0||e.isFallbackAdapter===!0||ex.test(n)}}var nx=class extends r.EventDispatcher{constructor(e,t={}){super();try{Zb.get(e)?.dispose()}catch(e){Qb.warn(`prior canvas owner dispose failed`,e)}Zb.set(e,this),this.canvas=e,this._autoResize=t.autoResize!==!1,this._maxSceneBytes=t.maxSceneBytes,this._container=t.container||null,this._applySceneMetadataEnabled=t.applySceneMetadata!==!1,this._applyingSceneMetadata=!1,this._profile=Le(t.profile),this._issues=new fn({strict:t.strict===!0,onIssue:e=>this.dispatchEvent({type:H.ISSUE,issue:e})}),this.color=new mo({issues:this._issues}),co(this.color),this.settings=new jg({...W,environmentRotation:this._profile.environmentRotation,saturation:this._profile.saturation},{issues:this._issues}),this.renderer=null,this.scene=null,this.meshScene=null,this._sceneHelpers=null,this.assetLoader=null,this._sdf=null,this._animRefitInFlight=!1,this._maxTextureSize=W.maxTextureSize,this.pipeline=null,this._pendingReservedRenderSize=null,this.stages={},this.cameraManager=null,this.lightManager=null,this.goboManager=null,this.iesManager=null,this.denoisingManager=null,this.overlayManager=null,this.interactionManager=null,this.transformManager=null,this.animationManager=new qb,this.environmentManager=null,this.isInitialized=!1,this.pauseRendering=!1,this._pathTracerEnabled=!0,this._rasterPrecompile=null,this.animationManagerId=null,this.needsReset=!1,this._loadingInProgress=!1,this._needsDisplayRefresh=!1,this._paused=!1,this._emissiveSamplingUserSet=!1,this.completion=new Tg,this._resizeDebounceTimer=null,this._displayWidth=0,this._displayHeight=0,this._renderScale=1,this._pendingRenderScale=null,this._trackedListeners=[],this._disposed=!1,this._deviceLost=!1,this._gpuDevice=null,this._deviceLostHolder=null,this._deterministic=!1,this._dispatchPinned=!1,this._deterministicRestore=null,this.adapterInfo=null}_addTrackedListener(e,t,n){e&&(e.addEventListener(t,n),this._trackedListeners.push({target:e,type:t,handler:n}))}_removeTrackedListeners(){for(let{target:e,type:t,handler:n}of this._trackedListeners)try{e.removeEventListener(t,n)}catch(e){Qb.warn(`failed to remove listener`,t,e)}this._trackedListeners.length=0}async init(){return await this._initRenderer(),this._applyPendingReservedRenderSize(),this._initCameraManager(),this._initScenes(),this._initAssetPipeline(),this._initPipeline(),await this._initManagers(),this._wireEvents(),this.stages.pathTracer.setTriangleData(new Float32Array(32),0),this.stages.pathTracer.setBVHData(new Float32Array(16)),this.stages.pathTracer.materialData.setMaterialData(new Float32Array(16)),this.stages.pathTracer.setupMaterial(),this.isInitialized=!0,Qb.debug(`WebGPU path tracer app initialized`),this}animate(){if(this._deviceLost)return;if(this.animationManagerId=requestAnimationFrame(()=>this.animate()),this._loadingInProgress||this._sdf?.isProcessing){this.dispatchEvent({type:H.FRAME});return}if(this.cameraManager.controls&&this.cameraManager.controls.update(),this._applyPendingRenderScale(),this.animationManager?.isPlaying&&!this._animRefitInFlight){let e=this.animationManager.update();e&&(this._animRefitInFlight=!0,this.refitBVH(e).catch(e=>Qb.error(`animation refit error:`,e)).finally(()=>{this._animRefitInFlight=!1}))}let e=this.needsReset;if(this.needsReset&&=(this.stages.pathTracer?.noteViewChanged(),this.reset(!0),!1),this.cameraManager.camera.updateMatrixWorld(),!this.pathTracerEnabled){this.renderer.render(this.meshScene,this.cameraManager.camera),this._renderHelperOverlay();return}if(!this.pauseRendering){if(this.cameraManager.updateAutoFocus(),this.stages.pathTracer?.isReady){if(this.stages.pathTracer.isComplete&&this.completion.renderCompleteDispatched){this._needsDisplayRefresh&&(this._needsDisplayRefresh=!1,this.stages.compositor.render(this.pipeline.context),this._renderHelperOverlay()),this.stopAnimation();return}if(this.denoisingManager?.skipsTrace()){e&&this.stages.pathTracer.enterInteractionMode(),this._renderHelperOverlay(),this.dispatchEvent({type:H.FRAME});return}this.pipeline.render(),this.stages.pathTracer.isComplete||(this.completion.updateTime(),this.denoisingManager?.tickContinuousDenoise(this.stages.pathTracer.frameCount)),this._ensureVRAMWiring();let t=this.stages.pathTracer?.vramTracker,n=this.stages.pathTracer?.frameCount??0;if(t&&(n<=1||n%30==0)&&t.measure(),Te({timeElapsed:this.completion.timeElapsed,samples:Ee(this.stages.pathTracer),memoryUsed:t?.current??0,memoryPeak:t?.peak??0}),this.completion.isTimeLimitReached(this.stages.pathTracer,this.settings.get(`renderLimitMode`),this.settings.get(`renderTimeLimit`))&&(this.stages.pathTracer.isComplete=!0),this.stages.pathTracer.isComplete&&this.completion.markComplete()){this.denoisingManager.onRenderComplete({isStillComplete:()=>this.completion.renderCompleteDispatched,context:this.pipeline?.context});let e={samples:this.stages.pathTracer.frameCount,timeElapsed:this.completion.timeElapsed,budgetOverrun:this.completion.budgetOverrun,reason:this.completion.stopCondition(this.stages.pathTracer)??`samples`};this.dispatchEvent({type:`RenderComplete`,...e}),this.dispatchEvent({type:H.RENDER_COMPLETE,...e})}}this._renderHelperOverlay(),this.dispatchEvent({type:H.FRAME})}}stopAnimation(){this.animationManagerId&&=(cancelAnimationFrame(this.animationManagerId),null)}_handleDeviceLost(e){this._deviceLost||(this._deviceLost=!0,Qb.error(`WebGPU device lost (${e?.reason||`unknown`}): ${e?.message||``}`),this.stopAnimation(),this.dispatchEvent({type:H.DEVICE_LOST,reason:e?.reason,message:e?.message}))}wake(){this._deviceLost||!this.animationManagerId&&this.isInitialized&&!this._paused&&this.animate()}pause(){this._paused=!0,this.stopAnimation()}resume(){this._paused=!1,this.animationManagerId||this.animate()}reset(e=!1){this.pipeline&&(this.pipeline.reset(),e||(this.pipeline.eventBus.emit(`asvgf:reset`),this.pipeline.eventBus.emit(`denoiser:reset`))),this._abortPostProcess({keepDisplay:!0}),this.completion.reset(),this.wake(),this.dispatchEvent({type:`RenderReset`}),this.dispatchEvent({type:H.RENDER_RESET})}dispose(){if(!this._disposed){if(this._disposed=!0,this.dispatchEvent({type:H.DISPOSE}),this.stopAnimation(),clearTimeout(this._resizeDebounceTimer),this._resizeDebounceTimer=null,this._removeTrackedListeners(),Ce(null),this._issues.detach(),this.color?.dispose(),this.color=null,this._textureReadback?.dispose(),this._textureReadback=null,this.interactionManager?.deselect?.(),this.transformManager?.detach?.(),this.animationManager?.dispose(),this.transformManager?.dispose(),this.overlayManager?.dispose(),this.lightManager?.dispose(),this.goboManager?.dispose(),this.iesManager?.dispose(),this.denoisingManager?.dispose(),this.interactionManager?.dispose(),this.cameraManager?.dispose(),this.pipeline?.dispose(),this._sdf?.dispose(),this._sdf=null,this.assetLoader?.dispose(),this.assetLoader=null,this.meshScene){this.meshScene.environment?.dispose(),this.meshScene.environment=null;for(let e of[...this.meshScene.children])je(e);this.meshScene.clear(),this.meshScene=null}this._sceneHelpers?.clear(),this._sceneHelpers=null,this.scene?.clear(),this.scene=null;try{let e=(0,n.texture)().value,t=(0,n.cubeTexture)().value;e?._listeners?.dispose&&(e._listeners.dispose.length=0),t?._listeners?.dispose&&(t._listeners.dispose.length=0)}catch(e){Qb.warn(`failed to clear TSL texture singleton listeners`,e)}this.canvas&&Zb.get(this.canvas)===this&&Zb.delete(this.canvas),this._gpuDevice&&=(this._gpuDevice.onuncapturederror=null,null),this._deviceLostHolder&&=(this._deviceLostHolder.app=null,null),Ae(this.renderer),this.renderer=null,this.stages={},this.isInitialized=!1}}unloadScene(){if(this.isInitialized){if(this._loadingInProgress)throw Error(`PathTracerApp.unloadScene: cannot unload while a load is in progress`);this._disposed||(this.animationManager?.dispose(),this._animRefitInFlight=!1,this.interactionManager?.deselect(),this.transformManager?.detach?.(),this.assetLoader?.releaseTargetModel(),this.lightManager?.clearLights?.(),this.stages.pathTracer&&(this.stages.pathTracer.setTriangleData(new Float32Array(32),0),this.stages.pathTracer.setBVHData(new Float32Array(16)),this.stages.pathTracer.materialData.setMaterialData(new Float32Array(16)),this.stages.pathTracer.setEmissiveTriangleData?.(new Float32Array,0,0),this.stages.pathTracer.setupMaterial()),this.denoisingManager?.dropDisplay(),this.reset(),this.dispatchEvent({type:`SceneUnloaded`}))}}async loadModel(e){await this._loadWithSceneRebuild(()=>this.assetLoader.loadModel(e),{type:`ModelLoaded`,url:e})}async loadObject3D(e,t=`object3d`){await this._loadWithSceneRebuild(()=>this.assetLoader.loadObject3D(e,t),{type:`Object3DLoaded`,name:t})}_busyError(e){let t=Error(`${e}: another load is already in progress`);return t.code=`LOAD_IN_PROGRESS`,t}async loadEnvironment(e){if(this._loadingInProgress)throw this._busyError(`PathTracerApp.loadEnvironment`);this._loadingInProgress=!0;try{await this.assetLoader.loadEnvironment(e);let t=this.meshScene.environment;t&&this.stages.pathTracer&&await this.stages.pathTracer.environment.setEnvironmentMap(t),this.pipeline?.eventBus.emit(`autoexposure:resetHistory`),this.reset(),this.dispatchEvent({type:`EnvironmentLoaded`,url:e})}finally{this._loadingInProgress=!1}}async inspectArchive(e){return await this.assetLoader.inspectArchive(e)}async loadFile(e,t={}){let n=this.assetLoader?.getFileFormat(e?.name||``);if(!n)throw Error(`Unsupported file format: ${e?.name}`);if(n.type!==`environment`&&n.type!==`image`){await this._loadWithSceneRebuild(()=>this.assetLoader.loadAssetFromFile(e,t),{type:`ModelLoaded`,filename:e.name});return}if(this._loadingInProgress)throw this._busyError(`PathTracerApp.loadFile`);this._loadingInProgress=!0;try{await this.assetLoader.loadAssetFromFile(e);let t=this.meshScene.environment;t&&this.stages.pathTracer&&await this.stages.pathTracer.environment.applyHDRI(t),this.pipeline?.eventBus.emit(`autoexposure:resetHistory`),this.reset(),this.dispatchEvent({type:`EnvironmentLoaded`,filename:e.name})}finally{this._loadingInProgress=!1}}async loadExampleModels(e,t){await this._loadWithSceneRebuild(()=>this.assetLoader.loadExampleModels(e,t),{type:`ModelLoaded`,index:e})}cancelLoad(){this._loadingInProgress&&this.assetLoader?.cancelActiveLoad()}async setMaxTextureSize(e,{reprocess:t=!0}={}){let n=this._maxTextureSize;if(this._maxTextureSize=this._sdf?.setMaxTextureSize(e)??e,typeof this.stages?.pathTracer?.sdfs?.setMaxTextureSize==`function`&&this.stages.pathTracer.sdfs.setMaxTextureSize(this._maxTextureSize),t&&this._maxTextureSize!==n&&this._sdf?.triangles&&!this._loadingInProgress){this._loadingInProgress=!0;try{await this.loadSceneData(),this.reset(),this.dispatchEvent({type:`TexturesReprocessed`,maxTextureSize:this._maxTextureSize})}finally{this._loadingInProgress=!1}}}async _loadWithSceneRebuild(e,t){if(this._loadingInProgress)throw this._busyError(`PathTracerApp`);this._loadingInProgress=!0;try{await e(),this._emissiveSamplingUserSet=!1,this._clearAppendedModels(),this._syncControlsAfterLoad(),await this.loadSceneData({pendingEnvironment:this._beginSceneMetadataEnvironment()}),this.pipeline?.eventBus.emit(`autoexposure:resetHistory`),this.denoisingManager?.dropDisplay(),this.reset(),this.cameraManager.currentCameraIndex=0,this.dispatchEvent(t),this._dispatchCamerasUpdated()}catch(e){throw(!e||e.code!==`LOAD_IN_PROGRESS`)&&this._discardFailedLoad(),e}finally{this._loadingInProgress=!1}}_discardFailedLoad(){try{this._clearAppendedModels(),this.assetLoader?.releaseTargetModel(),this.denoisingManager?.dropDisplay(),this.reset()}catch(e){console.warn(`PathTracerApp: could not clear the scene after a failed load`,e)}}get sceneMetadata(){return this.assetLoader?.sceneMetadata??null}_beginSceneMetadataEnvironment(){let e=this.sceneMetadata?.environment;return!this._applySceneMetadataEnabled||!e?.sourceFile||!this.stages.pathTracer?null:(this.stages.pathTracer.environment.beginHDRI(),this._applyingSceneMetadata=!0,this.assetLoader.loadEnvironment(e.sourceFile).catch(t=>(this._issues.record(ln.ENVIRONMENT_LOAD_FAILED,`authored environment "${e.sourceFile}" failed to load — lighting falls back to the previous environment`,{sourceFile:e.sourceFile,cause:String(t?.message??t)}),null)).finally(()=>{this._applyingSceneMetadata=!1}))}_applySceneMetadataSettings(e){let t=this.sceneMetadata,n=t?.environment;if(!n)return;let r={enableEnvironment:!0,showBackground:!0,transparentBackground:!1};n.intensity!==void 0&&(r.environmentIntensity=n.intensity,r.backgroundIntensity=n.intensity),n.rotation!==void 0&&(r.environmentRotation=n.rotation),this.settings.setMany(r,{reset:!1,source:kg.SCENE_METADATA}),this.scene&&(this.scene.background=e),this.dispatchEvent({type:H.SCENE_METADATA_APPLIED,metadata:t,environment:{...n}})}async loadSceneData({pendingEnvironment:e=null}={}){this._preserveSelectionOnRebuild||this.interactionManager?.deselect(),this.animationManager.dispose(),this._animRefitInFlight=!1,this._tagPrimarySceneObject();let t=new jd(``,{namespace:`scene`,level:`info`}),n=this.meshScene.environment,r=null;if(e?(t.start(`Environment fetch + CDF (concurrent)`),r=e.then(async e=>{e&&(await this.stages.pathTracer.environment.applyHDRI(e),this._applySceneMetadataSettings(e))}).catch(e=>this._issues.record(ln.ENVIRONMENT_LOAD_FAILED,`authored environment failed to install — the scene is lit by whatever was already loaded`,{cause:String(e?.message??e)})).finally(()=>t.end(`Environment fetch + CDF (concurrent)`))):n?.image?.data&&(t.start(`Environment CDF build (worker)`),this.stages.pathTracer.scene.environment=n,r=this.stages.pathTracer.environment.buildEnvironmentCDF().then(()=>{t.end(`Environment CDF build (worker)`),this._applySceneMetadataEnabled&&this._applySceneMetadataSettings(n)})),t.start(`BVH build (SceneProcessor)`),this._sdf.setMaxTextureSize(this._maxTextureSize),await this._sdf.buildBVH(this.meshScene),t.end(`BVH build (SceneProcessor)`),U({status:`Transferring data to GPU...`,progress:86}),await new Promise(e=>setTimeout(e,0)),t.start(`GPU data transfer`),!this._sdf.uploadToPathTracer(this.stages.pathTracer,this.lightManager,this.meshScene,this.meshScene.environment))return!1;this.stages.pathTracer._meshRefs=this.stages.pathTracer._collectMeshRefs(this.meshScene),this.stages.pathTracer.setMeshVisibilityData(this.stages.pathTracer._meshRefs),this._refreshEmissiveForVisibility(),t.end(`GPU data transfer`),U({status:`Compiling shaders...`,progress:90}),await new Promise(e=>setTimeout(e,0)),t.start(`Material setup (TSL compile)`),this.stages.pathTracer.setupMaterial(),t.end(`Material setup (TSL compile)`),this._rasterPrecompile=null,this._pathTracerEnabled||(t.start(`Pipeline precompile`),await this.precompileRaster(),t.end(`Pipeline precompile`)),r&&(U({status:`Finalizing environment map...`,progress:95}),await r,this.stages.pathTracer.environment.applyCDFResults());let i=this.getSceneMinY();if(this.settings.set(`groundProjectionLevel`,i,{reset:!1}),this.settings.set(`groundCatcherHeight`,i,{reset:!1}),!this._emissiveSamplingUserSet){let e=(this._sdf?.emissiveTriangleBuilder?.emissiveTriangles?.length??this._sdf?.emissiveTriangleCount??0)>0;this.settings.set(`enableEmissiveTriangleSampling`,e,{reset:!1})}return t.start(`Apply settings`),this.settings.applyAll(),this.stages.compositor.setTransparentBackground(this.settings.get(`transparentBackground`)),t.end(`Apply settings`),t.print(this._sceneSummaryParts()),we(),this._initAnimationAndTransforms(),this.dispatchEvent({type:`SceneRebuild`}),!0}_sceneSummaryParts(){let e=this.stages.pathTracer,t=this._sdf?.instanceTable?.setCount??0,n=this._sdf?.geometryExtractor?.maps?.length??0;return[Y.count(e.triangleCount,`tri`),t?Y.count(t,`mesh`,`meshes`):null,Y.count(e.materialData.materialCount,`material`),n?Y.count(n,`map`):null,Y.count(e.bvhNodeCount,`BVH node`)]}_tagPrimarySceneObject(){let e=this.sceneModel;e&&(e.userData.__rayzeeSceneObject=!0)}_clearAppendedModels(){let e=this.meshScene;if(!e)return;let t=this.assetLoader?.floorPlane,n=this.sceneModel;for(let r of[...e.children])r===t||r===n||r.userData?.__rayzeeSceneObject&&this.assetLoader.removeModelRoot(r)}async _finishRebuildNoReframe(e){await this.loadSceneData(),this._recalibrateControlLimits(),this.pipeline?.eventBus.emit(`autoexposure:resetHistory`),this.reset(),e&&this.dispatchEvent(e)}async addModel(e,{name:t}={}){if(this._loadingInProgress)throw Error(`PathTracerApp.addModel: another load is already in progress`);this._loadingInProgress=!0,this._preserveSelectionOnRebuild=!0;try{let{root:n}=await this.assetLoader.appendModel(e);return n.userData.__rayzeeSceneObject=!0,t&&(n.userData.__rayzeeName=t),await this._finishRebuildNoReframe({type:`ModelAdded`,url:e,id:n.uuid}),n.uuid}finally{this._preserveSelectionOnRebuild=!1,this._loadingInProgress=!1}}async addModelFromObject3D(e,{name:t}={}){if(this._loadingInProgress)throw Error(`PathTracerApp.addModelFromObject3D: another load is already in progress`);this._loadingInProgress=!0,this._preserveSelectionOnRebuild=!0;try{let{root:n}=this.assetLoader.appendObject3D(e,t||`object3d`);return n.userData.__rayzeeSceneObject=!0,t&&(n.userData.__rayzeeName=t),await this._finishRebuildNoReframe({type:`ModelAdded`,id:n.uuid}),n.uuid}finally{this._preserveSelectionOnRebuild=!1,this._loadingInProgress=!1}}async removeSceneObject(e){if(!this.meshScene)return!1;let t=this.assetLoader?.floorPlane;if(t&&t.uuid===e)return!1;let n=this.getSceneObject(e);if(!n)return!1;if(this._loadingInProgress)throw Error(`PathTracerApp.removeSceneObject: another load is already in progress`);this._loadingInProgress=!0;try{return this.interactionManager?.deselect(),this.transformManager?.detach?.(),n===this.sceneModel?this.assetLoader.releaseTargetModel():this.assetLoader.removeModelRoot(n),await this._finishRebuildNoReframe({type:`SceneObjectRemoved`,id:e}),!0}finally{this._loadingInProgress=!1}}setSceneObjectVisibility(e,t){return this.setMeshVisibilityByUuid(e,t)}get currentCameraIndex(){return this.cameraManager?.currentCameraIndex??0}addCamera({name:e}={}){let t=this.cameraManager.addCameraFromView(e);return this.cameraManager.switchCamera(t),this._dispatchCamerasUpdated(),t}removeCamera(e){let t=this.cameraManager.removeCamera(e);return t&&this._dispatchCamerasUpdated(),t}_dispatchCamerasUpdated(){this.dispatchEvent({type:`CamerasUpdated`,cameras:this.cameraManager.cameras,cameraNames:this.cameraManager.getCameraNames()})}get sceneMeshes(){return this._sdf?.meshes??[]}get sceneModel(){return this.assetLoader?.targetModel??null}getSceneObject(e){let t=this.meshScene?.children.find(t=>t.uuid===e);return t?.userData?.__rayzeeSceneObject?t:null}async refitBVH(e,t){let n=await this._sdf.refitBVH(e,t);return this.stages.pathTracer.updateTriangleData(this._sdf.triangles),this.stages.pathTracer.updateBVHData(this._sdf.bvh),this.reset(),n}refitBLASes(e,t,n){let r=this._sdf.refitBLASes(e,t,n),{triRanges:i,bvhRanges:a}=this._sdf.computeBLASDirtyRanges(e);return this.stages.pathTracer.updateBufferRanges(i,a),this.reset(),this._sdf.scheduleBackgroundRebuild(e,e=>{let t=this._sdf.computeBLASDirtyRanges([e]);this.stages.pathTracer.updateBufferRanges(t.triRanges,t.bvhRanges),this.reset()}),r}updateMeshTransforms(e){let t=this._sdf.updateMeshTransforms(e);return this.stages.pathTracer.updateBufferRanges([],[this._sdf.computeTLASDirtyRange()]),this.reset(),t}setReservedRenderResolution(e,{allowLower:t=!1}={}){let n=t?e:Math.max(e,G);if(!this.renderer)return this._pendingReservedRenderSize={requestedPx:e,allowLower:t},Math.max(256,Math.min(He,Math.floor(n)||256));let r=this.renderer.backend?.device?.limits?.maxStorageBufferBindingSize||128*1024*1024,i=(typeof navigator<`u`&&navigator.deviceMemory||4)>=8&&r>=1024*1024*1024?He:2048,a=Ue(Math.min(n,i));if((this.stages?.pathTracer?.storageTextures?.writeColor?.image?.width??a)!==a){let e=this.pauseRendering;this.pauseRendering=!0;try{let e=this.renderer.domElement;(e.width>a||e.height>a)&&this.renderer.setSize(Math.min(e.width,a),Math.min(e.height,a),!1);for(let e of Object.values(this.stages))e?.reallocateReservedStorage?.()}finally{this.pauseRendering=e}this.reset(),this.dispatchEvent({type:`reserved_render_size_changed`,size:a})}return a}_applyPendingReservedRenderSize(){let e=this._pendingReservedRenderSize;if(!e)return;this._pendingReservedRenderSize=null;let t=this.setReservedRenderResolution(e.requestedPx,{allowLower:e.allowLower});t<e.requestedPx&&this._issues.warn(ln.RENDER_RESERVE_CAPPED,`reserved render size ${Y.n(e.requestedPx)}px was capped to ${Y.n(t)}px by this device's limits — renders above ${Y.n(t)}px will be declined`,{requested:e.requestedPx,applied:t}),this.dispatchEvent({type:`reserved_render_size_changed`,size:t})}getReservedRenderResolution(){return G}_isRenderSizeSupported(e,t){return e>G||t>G?(this._issues.record(ln.RENDER_SIZE_DECLINED,`render resolution ${e}×${t} exceeds the ${G}px storage reserve — resize ignored, so output stays at the previous size. Raise it with setReservedRenderResolution( ${Math.max(e,t)} ) before init().`,{width:e,height:t,reserve:G}),!1):!0}onResize(){let e=this.canvas.clientWidth,t=this.canvas.clientHeight;if(e===0||t===0||!this._isRenderSizeSupported(e,t))return;this.renderer.setPixelRatio(1),this._setDisplaySize(e,t);let n=this.denoisingManager?._lastRenderWidth??0,r=this.denoisingManager?._lastRenderHeight??0;e===n&&t===r||(clearTimeout(this._resizeDebounceTimer),this._resizeDebounceTimer=setTimeout(()=>{this._applyRenderResize(e,t)},300))}_applyRenderResize(e,t){this._isRenderSizeSupported(e,t)&&(this.pipeline?.setSize(this._scaled(e),this._scaled(t)),this.denoisingManager?.setRenderSize(e,t),this.needsReset=!0,this.dispatchEvent({type:`resolution_changed`,width:e,height:t}))}setCanvasSize(e,t){return e===0||t===0||!this._isRenderSizeSupported(e,t)?null:(this.renderer.setPixelRatio(1),this._setDisplaySize(e,t),clearTimeout(this._resizeDebounceTimer),this._applyRenderResize(e,t),{width:e,height:t})}_scaled(e){return Math.max(1,Math.round(e*this._renderScale))}_setDisplaySize(e,t){this._displayWidth=e,this._displayHeight=t,this.renderer.setSize(this._scaled(e),this._scaled(t),!1),this.cameraManager.camera.aspect=e/t,this.cameraManager.camera.updateProjectionMatrix()}_interactionRenderScale(){if(this.denoisingManager?.continuousDenoise)return 1;let e=Number(this.settings.get(`interactionRenderScale`));return e>0?Math.min(1,Math.max(.125,e)):1}_requestRenderScale(e){this._pendingRenderScale=e}_applyPendingRenderScale(){this._pendingRenderScale!==null&&this._applyRenderScale(this._pendingRenderScale)}_applyRenderScale(e){this._pendingRenderScale=null,!(this._disposed||e===this._renderScale)&&(this._renderScale=e,!(!this._displayWidth||!this._displayHeight)&&(this._setDisplaySize(this._displayWidth,this._displayHeight),this.pipeline?.setSize(this._scaled(this._displayWidth),this._scaled(this._displayHeight)),this.pipeline?.eventBus.emit(`asvgf:reset`),this.pipeline?.eventBus.emit(`denoiser:reset`),this.needsReset=!0))}configureForMode(e,t={}){let n=e===`production`,r=n?wt:Tt;this.denoisingManager?.setCadenceSuspended(n),this.cameraManager.controls.enabled=!n,this.settings.setMany(Et(r),{silent:!0,source:kg.MODE_PRESET}),this.stages.pathTracer?.setUniform(`renderMode`,parseInt(r.renderMode)),this.stages.pathTracer?.updateCompletionThreshold?.();let i=this.denoisingManager?.denoiser;if(i&&(i.abort(),this.denoisingManager.applyOIDNEnabled(r.enableOIDN),this.denoisingManager.applyOIDNQuality(r.oidnQuality)),this.denoisingManager?._syncGBufferStages?.(),this.denoisingManager?.upscaler?.abort(),t.canvasWidth&&t.canvasHeight&&(this.setReservedRenderResolution(Math.max(t.canvasWidth,t.canvasHeight)),this.setCanvasSize(t.canvasWidth,t.canvasHeight)),this.needsReset=!1,this.pauseRendering=!1,n){let e=this.stages.pathTracer?.vramTracker;e&&(e.measure(),e.resetPeak())}this.reset()}refreshFrame(){this._needsDisplayRefresh=!0,this.wake()}_abortPostProcess({keepDisplay:e=!1}={}){if(this.denoisingManager?.abort(this.canvas,{keepDisplay:e}),this.denoisingManager?.restoreBaseResolution()){let e=this.denoisingManager._lastRenderWidth,t=this.denoisingManager._lastRenderHeight;this.dispatchEvent({type:`resolution_changed`,width:e,height:t})}}requestPostProcessRefresh(){!this.stages.pathTracer?.isReady||this._deviceLost||(this._abortPostProcess(),this.completion.renderCompleteDispatched=!1,this.wake())}setDeterministicMode(e=!0,{pinDispatch:t=!0}={}){let n=this.stages.pathTracer;if(!n)return!1;if(e)this._deterministicRestore||={settings:{useAdaptiveSampling:this.settings.get(`useAdaptiveSampling`),usePixelFreeze:this.settings.get(`usePixelFreeze`),interactionModeEnabled:this.settings.get(`interactionModeEnabled`),renderLimitMode:this.settings.get(`renderLimitMode`),renderTimeLimit:this.settings.get(`renderTimeLimit`)},bounceEarlyExit:n._bounceEarlyExitThreshold,dynamicDispatch:n._useDynamicDispatch,autoFocusMode:this.cameraManager?.autoFocusMode,autoExposure:this.stages.autoExposure?.enabled,continuousDenoise:this.denoisingManager?.continuousDenoise},this.settings.setMany({useAdaptiveSampling:!1,usePixelFreeze:!1,interactionModeEnabled:!1,renderLimitMode:`frames`,renderTimeLimit:0},{silent:!0}),t?(n._bounceEarlyExitThreshold=-1,n._useDynamicDispatch=!1):(n._bounceEarlyExitThreshold=this._deterministicRestore.bounceEarlyExit,n._useDynamicDispatch=this._deterministicRestore.dynamicDispatch),this.cameraManager?.setAutoFocusMode(`manual`),this.stages.autoExposure&&(this.stages.autoExposure.enabled=!1),this.denoisingManager?.setContinuousDenoise(!1),n._pinSeedToFrame=!0,this._deterministic=!0,this._dispatchPinned=t;else if(this._deterministicRestore){let e=this._deterministicRestore;this.settings.setMany(e.settings,{silent:!0}),n._bounceEarlyExitThreshold=e.bounceEarlyExit,n._useDynamicDispatch=e.dynamicDispatch,e.autoFocusMode!==void 0&&this.cameraManager?.setAutoFocusMode(e.autoFocusMode),this.stages.autoExposure&&e.autoExposure!==void 0&&(this.stages.autoExposure.enabled=e.autoExposure),e.continuousDenoise!==void 0&&this.denoisingManager?.setContinuousDenoise(e.continuousDenoise),n._pinSeedToFrame=!1,this._deterministicRestore=null,this._deterministic=!1,this._dispatchPinned=!1}return this.reset(),this.stopAnimation(),this._deterministic}get issues(){return this._issues.list}get issueErrors(){return this._issues.errors}clearIssues(){this._issues.clear()}get isDeterministic(){return this._deterministic&&this._dispatchPinned}async renderFrames(e,{reset:t=!0,yieldEvery:n=8,onProgress:r,allowEarlyRetire:i=!1}={}){let a=this.stages.pathTracer;if(!a)throw Error(`renderFrames: app is not initialized`);if(!(e>0))throw Error(`renderFrames: count must be positive, got ${e}`);await a.blueNoiseReady;let o=(t?0:a.frameCount)+e;this.settings.get(`maxSamples`)<o&&this.settings.set(`maxSamples`,o,{silent:!0,reset:!1}),t&&this.reset(),this.stopAnimation();let s=e+64,c=0,l=!1;for(;a.frameCount<o&&c<s;){if(this._deviceLost)throw Error(`renderFrames: WebGPU device lost`);if(!a.isReady)throw Error(`renderFrames: path tracer stage is not ready`);if(this.pipeline.render(),c++,a.isComplete&&a.frameCount<o){l=!0;break}r?.(a.frameCount),n>0&&c%n===0&&await new Promise(e=>setTimeout(e,0))}if(a.frameCount<o&&!(l&&i)){let e=l?"adaptive sampling retired the frame at the convergence threshold — pass `allowEarlyRetire: true`, or disable it with setDeterministicMode()":`something retired the render (maxSamples, a stray reset, or a canvas resize)`;throw Error(`renderFrames: stopped at ${a.frameCount}/${o} samples after ${c} passes — ${e}`)}return a.frameCount}async renderToBuffer({colorSpace:e=`srgb`,preserveAlpha:t=!1,source:n=`accumulation`}={}){let r=e!==`linear`&&e!==`srgb`;if(r&&!this.color?.hasConfig)throw Error(`renderToBuffer: colorSpace must be 'linear' or 'srgb' without a colour config loaded, got "${e}"`);let i=this.stages?.pathTracer,a=i?.storageTextures?.readTarget;if(!a)throw Error(`renderToBuffer: no render target — call init() and render at least one sample`);let{width:o,height:s}=i,c=n===`display`?await this._readDisplaySource(a,o,s):await this.renderer.readRenderTargetPixelsAsync(a,0,0,o,s,0);if(e===`linear`)return{data:c,width:o,height:s,colorSpace:e,workingSpace:this.color?.workingSpace??null};if(r){let{rgba:t,colorSpace:n}=this.color.exportPixels(c,e);return{data:t,width:o,height:s,colorSpace:n}}return{data:hd(c,{exposure:this.renderer.toneMappingExposure,toneMapping:this.renderer.toneMapping,saturation:this.settings.get(`saturation`)??1,preserveAlpha:t}),width:o,height:s,colorSpace:e}}enableGPUTiming(e=!0){let t=this.renderer?.backend;return!t||e&&t.hasFeature?.(`timestamp-query`)!==!0?!1:(t.trackTimestamp=e,t.trackTimestamp===e)}profileNextDenoise(){return this.denoisingManager?.denoiser?.profileNextDenoise()??!1}async getDenoiseProfile(){let e=this.denoisingManager?.denoiser;return e?{profile:await e.getLastDenoiseProfile(),runtime:e.getRuntimeInfo()}:null}async getGPUTimings(){let e=this.renderer;if(!e?.backend?.trackTimestamp)return null;await e.resolveTimestampsAsync(`compute`),await e.resolveTimestampsAsync(`render`);let t=e.info.compute.timestamp||0,n=e.info.render.timestamp||0;return{compute:t,render:n,total:t+n}}async getKernelGPUTimings(){let e=this.renderer;if(!e?.backend?.trackTimestamp)return null;await e.resolveTimestampsAsync(`compute`);let t=e.backend.timestampQueryPool?.compute?.timestamps;if(!t||t.size===0)return null;let n=new Map,r=this.stages?.pathTracer?._kernelManager?.kernels;if(r)for(let[e,t]of r)n.set(t.id,e);let i=[],a=-1;for(let[e,n]of t){let t=e.split(`:`);if(t.length!==4)continue;let r=Number(t[3].slice(1));Number.isFinite(r)&&(i.push({nodeId:Number(t[2]),f:r,ms:n}),r>a&&(a=r))}let o={},s=0,c=0;for(let e of i){if(e.f!==a)continue;s+=e.ms;let t=n.get(e.nodeId);t===void 0?c+=e.ms:o[t]=(o[t]??0)+e.ms}return{kernels:o,total:s,unattributed:c,frame:a}}getCanvas(){if(!this.renderer?.domElement)return null;let e=this.denoisingManager?.upscalerCanvas;return e&&e.style.display!==`none`?e:(this.stages.compositor&&this.pipeline?.context&&this.stages.compositor.render(this.pipeline.context),this.renderer.domElement)}screenshot({type:e=`image/png`,quality:t}={}){let n=this.getCanvas();return n?new Promise(r=>n.toBlob(r,e,t)):Promise.resolve(null)}getStatistics(){try{return this._sdf?.getStatistics?.()??null}catch{return null}}get pathTracerEnabled(){return this._pathTracerEnabled}set pathTracerEnabled(e){this._pathTracerEnabled=e,e||this.precompileRaster()}precompileRaster(){return!this.renderer||!this.meshScene?Promise.resolve():(this._rasterPrecompile??=this.renderer.compileAsync(this.meshScene,this.cameraManager.camera).catch(e=>Qb.warn(`raster fallback precompile failed`,e)),this._rasterPrecompile)}get isLoading(){return this._loadingInProgress}isComplete(){return this.stages.pathTracer?.isComplete??!1}getFrameCount(){return this.stages.pathTracer?.frameCount||0}getConvergenceStats(){return this.stages.pathTracer?.getConvergenceStats?.()??null}get vram(){return this.stages.pathTracer?.vramTracker??null}getMemoryInfo(){return this.stages.pathTracer?.vramTracker?.measure()??{current:0,peak:0,byCategory:{}}}getHostMemoryInfo(){let e=this._sdf;return e?.memory?{preflight:e.memoryPreflight,...e.memory.report}:null}_ensureVRAMWiring(){if(this._vramWired)return;let e=this.stages.pathTracer?.vramTracker;if(!e)return;e.register(`stages`,()=>this._collectStageTextures());let t=()=>e.measure();this._addTrackedListener(this,`SceneRebuild`,t),this._addTrackedListener(this,`EnvironmentLoaded`,t),this._addTrackedListener(this,`resolution_changed`,t),this._vramWired=!0}_collectStageTextures(){let e=[],t=this.stages||{},n=t.pathTracer;for(let r in t){let i=t[r];if(!(!i||i===n||typeof i!=`object`))for(let t in i){let n=i[t];n&&(n.isTexture||n.isRenderTarget)&&e.push(n)}}return e}getSceneMinY(){if(!this.meshScene)return 0;let e=new r.Box3().setFromObject(this.meshScene);return Number.isFinite(e.min.y)?e.min.y:0}getMaterialProperty(e,t){return this.stages.pathTracer?.materialData.getMaterialProperty(e,t)}getMaterialPropertySource(e,t){return this.stages.pathTracer?.materialData.getMaterialPropertySource(e,t)}setMaterialProperty(e,t,n){this.stages.pathTracer?.materialData.updateMaterialProperty(e,t,n),[`emissive`,`emissiveIntensity`].includes(t)&&this._sdf&&this._uploadEmissivePayload(this._sdf.updateMaterialEmissive(e,t,n)),this.reset()}_uploadEmissivePayload(e){!e||!this.stages.pathTracer||(this.stages.pathTracer.setEmissiveTriangleData(e.rawData,e.emissiveCount,e.totalPower,e.bitTrailMap),e.lightBVHNodeData&&this.stages.pathTracer.setLightBVHData(e.lightBVHNodeData,e.lightBVHNodeCount))}_refreshEmissiveForVisibility(){let e=this._sdf?.instanceTable;if(!e)return;let t=new Set;for(let n=0;n<e.count;n++)e.isSet[n]&&!e.visible[n]&&t.add(n);this._uploadEmissivePayload(this._sdf.rebuildEmissiveForVisibility(t))}setEmissiveTriangleSampling(e){this._emissiveSamplingUserSet=!0,this.settings.set(`enableEmissiveTriangleSampling`,e)}hasEmissiveGeometry(){return(this._sdf?.emissiveTriangleBuilder?.emissiveTriangles?.length??this._sdf?.emissiveTriangleCount??0)>0}setMeshVisibility(e,t){this.stages.pathTracer?.updateMeshVisibility(e,t),this._refreshEmissiveForVisibility(),this.reset()}updateAllMeshVisibility(){this.stages.pathTracer?.updateAllMeshVisibility(),this._refreshEmissiveForVisibility(),this.reset()}getScene(){return this.meshScene||this.scene}setMeshVisibilityByUuid(e,t){let n=this.getScene()?.getObjectByProperty(`uuid`,e);if(!n)return null;let r=typeof t==`function`?!!t(n.visible):!!t;return n.visible=r,this.updateAllMeshVisibility(),r}setTextureTransform(e,t,n){this.stages.pathTracer?.materialData.updateTextureTransform(e,t,n),this.reset()}async _readDisplaySource(e,t,n){let r=this.pipeline?.context,i=r&&this.stages.compositor?.resolveLightTexture(r);return!i||i===e.texture?await this.renderer.readRenderTargetPixelsAsync(e,0,0,t,n,0):(this._textureReadback??=new Eg(this.renderer),await this._textureReadback.read(i,t,n))}async setTextureColorSpace(e,n){if(!e?.isTexture)throw Error(`setTextureColorSpace wants a three.js texture`);let r=e.userData??={};r.__rayzeeOriginalColorSpace===void 0&&(r.__rayzeeOriginalColorSpace=e.colorSpace);let i=r.__rayzeeOriginalColorSpace;if(delete r.ocioColorSpace,delete r.__rayzeeColorSpaceChoice,n==null)e.colorSpace=i,delete r.__rayzeeOriginalColorSpace;else if(n===`srgb`||n===`linear`)e.colorSpace=n===`srgb`?t.SRGBColorSpace:t.LinearSRGBColorSpace,r.__rayzeeColorSpaceChoice=n;else{if(!this.color?.hasConfig)throw Error(`"${n}" needs a colour config loaded`);r.ocioColorSpace=n,e.colorSpace=t.SRGBColorSpace}e.needsUpdate=!0,this.stages.pathTracer?.sdfs&&await this.rebuildMaterials()}async loadColorConfig(e={}){await this._leaveColorWorkingSpace();let t=Wi(this.renderer?.toneMapping),n=await this.color.loadConfig(e);return this.color.workingSpaceAdopted&&await this.applyColorWorkingSpace(),(!(t?.source===`ocio`&&Wi(this.renderer?.toneMapping)===t)||this.color.workingSpaceAdopted)&&this.reset(),n}async unloadColorConfig(){await this._leaveColorWorkingSpace(),this.color.unloadConfig(),this.reset()}async _leaveColorWorkingSpace(){this.color?.workingSpaceAdopted&&(this.color.setWorkingSpace(null),await this.applyColorWorkingSpace())}async applyColorWorkingSpace(){let e=this.environmentManager?.getEnvironmentTexture?.(),t=!1;if(e&&this.color?.hasConfig)try{t=this.color.convertTexturePixels(e)}catch(e){Qb.warn(`environment colour conversion failed: ${e.message}`)}this.stages.pathTracer?.sdfs&&(await this.rebuildMaterials(),this._uploadEmissivePayload(this._sdf?.rebuildEmissiveColors?.()??null)),t&&await this.environmentManager?.buildEnvironmentCDF?.(),this.reset()}async rebuildMaterials(e){await this.stages.pathTracer?.rebuildMaterials(e||this.meshScene),this.reset()}async _initRenderer(){if(Ce(e=>this.dispatchEvent(e)),!navigator.gpu)throw Error(`WebGPU is not supported in this browser`);let e=await navigator.gpu.requestAdapter({powerPreference:`high-performance`});if(!e)throw Error(`Failed to get WebGPU adapter`);this.adapterInfo=tx(e),this.adapterInfo.isSoftware&&(this._issues.warn(ln.ADAPTER_SOFTWARE,`software GPU adapter "${this.adapterInfo.description||this.adapterInfo.vendor}" — renders are correct but orders of magnitude slower than hardware`,{...this.adapterInfo}),Qb.warn(`software GPU adapter — check app.adapterInfo.isSoftware. ${this.adapterInfo.description}`));let n=e.limits,r={maxColorAttachmentBytesPerSample:128};for(let e of[`maxBufferSize`,`maxStorageBufferBindingSize`,`maxSampledTexturesPerShaderStage`,`maxStorageTexturesPerShaderStage`,`maxTextureArrayLayers`,`maxTextureDimension2D`,`maxComputeInvocationsPerWorkgroup`,`maxComputeWorkgroupStorageSize`,`maxComputeWorkgroupSizeX`,`maxComputeWorkgroupSizeY`,`maxComputeWorkgroupSizeZ`]){let t=n[e];t!==void 0&&(r[e]=t)}if(r.maxStorageBuffersPerShaderStage=Math.min(n.maxStorageBuffersPerShaderStage,10),this.renderer=new t.WebGPURenderer({canvas:this.canvas,alpha:!0,powerPreference:`high-performance`,requiredLimits:r}),await this.renderer.init(),!this.renderer.backend?.isWebGPUBackend)throw Error(`WebGPU backend unavailable — three.js fell back to WebGL2, which cannot run the path tracer's compute kernels. Check GPU process flags and driver support.`);let a=this.renderer.backend?.device;a?.lost&&(this._gpuDevice=a,this._deviceLostHolder={app:this},$b(a,this._deviceLostHolder),a.onuncapturederror=e=>Qb.error(`WebGPU uncaptured error:`,e.error)),t.RectAreaLightNode.setLTC(i.RectAreaLightTexturesLib.init()),this.renderer.outputColorSpace=t.SRGBColorSpace,this.renderer.toneMapping=this._profile.toneMapping,this.renderer.toneMappingExposure=1,this.renderer.setPixelRatio(1),this.color.attachRenderer(this.renderer)}_initCameraManager(){this.cameraManager=new ay(this.canvas)}_initScenes(){this.scene=new r.Scene,this.meshScene=new r.Scene,this._sceneHelpers=new M}_initAssetPipeline(){this._sdf=new Bd({issues:this._issues,...this._maxSceneBytes===void 0?{}:{maxSceneBytes:this._maxSceneBytes}}),this.assetLoader=new ry(this.meshScene,this.cameraManager.camera,this.cameraManager.controls,{issues:this._issues,profile:this._profile}),this.assetLoader.setRenderer(this.renderer),this.assetLoader.createFloorPlane(),this._addTrackedListener(this.cameraManager.controls,`change`,()=>{this.needsReset=!0,this.stages.pathTracer?.enterInteractionMode(),this.wake()})}_initPipeline(){this._createStages();let{clientWidth:e,clientHeight:t}=this.canvas;this.pipeline=new Cg(this.renderer,e||1,t||1,{issues:this._issues}),this.pipeline.addStage(this.stages.pathTracer),this.pipeline.addStage(this.stages.normalDepth),this.pipeline.addStage(this.stages.motionVector),this.pipeline.addStage(this.stages.nrd),this.pipeline.addStage(this.stages.asvgf),this.pipeline.addStage(this.stages.variance),this.pipeline.addStage(this.stages.bilateralFilter),this.pipeline.addStage(this.stages.edgeFilter),this.pipeline.addStage(this.stages.autoExposure),this.pipeline.addStage(this.stages.compositor);let n=this.canvas.clientWidth||1,r=this.canvas.clientHeight||1;this._displayWidth=n,this._displayHeight=r,this.pipeline.setSize(n,r),this.pipeline.eventBus.on(`pathtracer:interactionStart`,()=>this._requestRenderScale(this._interactionRenderScale())),this.pipeline.eventBus.on(`pathtracer:interactionEnd`,()=>this._applyRenderScale(1))}async _initManagers(){this.interactionManager=new Dg({scene:this.meshScene,camera:this.cameraManager.camera,canvas:this.canvas,assetLoader:this.assetLoader,pathTracer:null,floorPlane:this.assetLoader.floorPlane}),this.interactionManager.wireAppEvents(this),this.cameraManager.setInteractionManager(this.interactionManager),this.lightManager=new oy(this.scene,this._sceneHelpers,this.stages.pathTracer,{onReset:()=>this.reset()}),this.goboManager=new sy(this.stages.pathTracer,{onReset:()=>this.reset()}),this.iesManager=new vy(this.stages.pathTracer,{onReset:()=>this.reset()}),this._setupDenoisingManager(),await this._setupOverlayManager(),this.transformManager=new Yb({camera:this.cameraManager.camera,canvas:this.canvas,orbitControls:this.cameraManager.controls,app:this}),this.overlayManager.register(`transform`,new Xb(this.transformManager)),this.interactionManager.setDependencies({overlayManager:this.overlayManager,transformManager:this.transformManager,appDispatch:e=>this.dispatchEvent(e),orbitControls:this.cameraManager.controls,helperScene:this._sceneHelpers.scene}),this.denoisingManager.setOverlayManager(this.overlayManager),this.denoisingManager.setResetCallback(()=>this.reset()),this.denoisingManager.setPostProcessRefreshCallback(()=>this.requestPostProcessRefresh()),this.denoisingManager.setDisplayRefreshCallback(()=>this.refreshFrame()),this.denoisingManager.setSettings(this.settings),this.environmentManager=this.stages.pathTracer.environment,this.environmentManager.callbacks.onAutoExposureReset=()=>this.pipeline.eventBus.emit(`autoexposure:resetHistory`)}_wireEvents(){this._addTrackedListener(this.cameraManager,`CameraSwitched`,e=>this.dispatchEvent(e)),this._addTrackedListener(this.cameraManager,H.AUTO_FOCUS_UPDATED,e=>this.dispatchEvent(e)),this._forwardEvents(this.denoisingManager,[H.DENOISING_START,H.DENOISING_END,H.UPSCALING_START,H.UPSCALING_PROGRESS,H.UPSCALING_END,`resolution_changed`]),this._setupAutoExposureListener(),this.animationManager.wakeCallback=()=>this.wake(),this._forwardEvents(this.animationManager,[H.ANIMATION_STARTED,H.ANIMATION_PAUSED,H.ANIMATION_STOPPED]),this._addTrackedListener(this.animationManager,H.ANIMATION_PAUSED,()=>{this._animRefitInFlight=!1}),this._addTrackedListener(this.animationManager,H.ANIMATION_STOPPED,()=>{this._animRefitInFlight=!1}),this.cameraManager.initCallbacks({onResize:()=>this.onResize(),onReset:()=>this.reset(),getSettings:e=>this.settings.get(e),applySettings:e=>this.settings.setMany(e,{silent:!0,reset:!1})}),this.cameraManager.initAutoFocus({meshScene:this.meshScene,assetLoader:this.assetLoader,floorPlane:this.assetLoader.floorPlane,pathTracer:this.stages.pathTracer,settings:this.settings,softReset:()=>this.reset(!0),hardReset:()=>this.reset()}),this.settings.bind({stages:this.stages,renderer:this.renderer,resetCallback:()=>this.reset(),reconcileCompletion:()=>this._reconcileCompletion(),denoisingManager:this.denoisingManager,cameraManager:this.cameraManager,onInteractionRenderScale:()=>{this.stages.pathTracer?.interactionMode&&this._requestRenderScale(this._interactionRenderScale())}}),this.renderer.toneMappingExposure=this.settings.get(`exposure`)??1,this.onResize(),this.resizeHandler=()=>this.onResize(),this._autoResize&&this._addTrackedListener(window,`resize`,this.resizeHandler),this._onAssetLoaded=async e=>{if(!this._loadingInProgress&&!(this._applyingSceneMetadata&&e.texture)){if(e.model)this._clearAppendedModels(),await this.loadSceneData({pendingEnvironment:this._beginSceneMetadataEnvironment()});else if(e.texture){let e=this.meshScene.environment;e&&this.stages.pathTracer&&await this.stages.pathTracer.environment.setEnvironmentMap(e),we()}this.pauseRendering=!1,this.reset()}},this._addTrackedListener(this.assetLoader,`load`,this._onAssetLoaded),this._addTrackedListener(this.assetLoader,`modelProcessed`,e=>{let t=[this.cameraManager.camera,...e.cameras||[]];this.cameraManager.setCameras(t),this.interactionManager&&(this.interactionManager.floorPlane=this.assetLoader.floorPlane)})}_initAnimationAndTransforms(){let e=this.assetLoader?.animations||[];if(e.length>0){let t=this.sceneModel||this.meshScene;this.animationManager.init(this.meshScene,t,this._sdf.meshes,e),this.animationManager.onFinished=()=>{this._animRefitInFlight=!1,this.dispatchEvent({type:H.ANIMATION_FINISHED})}}this.transformManager?.setMeshData(this._sdf.meshes)}_createStages(){this.stages.pathTracer=new nh(this.renderer,this.scene,this.cameraManager.camera),this.stages.normalDepth=new rh(this.renderer,{pathTracer:this.stages.pathTracer}),this.stages.motionVector=new ih(this.renderer,this.cameraManager.camera,{pathTracer:this.stages.pathTracer}),this.stages.asvgf=new sh(this.renderer,{enabled:!1}),this.stages.nrd=new Gh(this.renderer,{enabled:!1,pathTracer:this.stages.pathTracer}),this.stages.variance=new Jh(this.renderer,{enabled:!1}),this.stages.bilateralFilter=new Xh(this.renderer,{enabled:!1}),this.stages.edgeFilter=new ng(this.renderer,{enabled:!1}),this.stages.autoExposure=new lg(this.renderer,{enabled:W.autoExposure??!1}),this.stages.compositor=new ug(this.renderer,{saturation:this.settings.get(`saturation`)??W.saturation,pathTracer:this.stages.pathTracer})}_setupDenoisingManager(){this.denoisingManager=new Lb({renderer:this.renderer,mainCanvas:this.canvas,stages:{pathTracer:this.stages.pathTracer,normalDepth:this.stages.normalDepth,motionVector:this.stages.motionVector,asvgf:this.stages.asvgf,nrd:this.stages.nrd,variance:this.stages.variance,bilateralFilter:this.stages.bilateralFilter,edgeFilter:this.stages.edgeFilter,autoExposure:this.stages.autoExposure,compositor:this.stages.compositor},pipeline:this.pipeline,getExposure:()=>this.settings.get(`exposure`)??1,getSaturation:()=>this.settings.get(`saturation`)??1}),this.denoisingManager.setupDenoiser(),this.denoisingManager.setupUpscaler(),this.denoisingManager._syncGBufferStages();let e=this.canvas.clientWidth||1,t=this.canvas.clientHeight||1;this.denoisingManager.setRenderSize(e,t)}_reconcileCompletion(){let e=this.stages.pathTracer;if(!e)return;let t=this.completion.isLimitReached(e,this.settings.get(`renderLimitMode`),this.settings.get(`renderTimeLimit`));t&&!e.isComplete?e.isComplete=!0:!t&&e.isComplete&&(e.isComplete=!1,this.completion.resumeFromPause(),this.denoisingManager?.abort(this.canvas),this.dispatchEvent({type:H.RENDER_RESET}),this.wake())}_setupAutoExposureListener(){this.stages.autoExposure&&this.stages.autoExposure.on(`autoexposure:updated`,e=>{this.dispatchEvent({type:H.AUTO_EXPOSURE_UPDATED,exposure:e.exposure,luminance:e.luminance})})}_renderHelperOverlay(){this.scene.updateMatrixWorld(),this.overlayManager?.render()}async _setupOverlayManager(){this.overlayManager=new Kb(this.cameraManager.camera),this.overlayManager.setupDefaultHelpers({helperScene:this._sceneHelpers,meshScene:this.meshScene,pipeline:this.pipeline,denoisingManager:this.denoisingManager,app:this,renderWidth:this.denoisingManager?._lastRenderWidth||this.canvas.clientWidth||1,renderHeight:this.denoisingManager?._lastRenderHeight||this.canvas.clientHeight||1}),await this.overlayManager.initViewRenderer({device:this.renderer.backend?.device,sizeSource:this.canvas}),this._container=this._container||this.canvas.parentNode||null,this.overlayManager.mount(this._container)}_syncControlsAfterLoad(){this.cameraManager.controls.saveState(),this.cameraManager.controls.update()}_recalibrateControlLimits(){if(!this.meshScene||!this.cameraManager)return;let e=new r.Box3,t=new r.Box3;for(let n of this.meshScene.children)n.userData?.__rayzeeSceneObject&&(t.setFromObject(n),t.isEmpty()||e.union(t));if(e.isEmpty())return;let n=Math.max(e.max.x-e.min.x,e.max.y-e.min.y,e.max.z-e.min.z);if(!Number.isFinite(n)||n<=0)return;let{camera:i,controls:a}=this.cameraManager,o=i.fov*(Math.PI/180),s=Math.abs(n/Math.sin(o/2)/2);this.cameraManager.currentCameraIndex===0&&(i.near=n/100,i.far=n*100,i.updateProjectionMatrix());let c=i.position.distanceTo(a.target);a.minDistance=Math.min(n/1e3,c),a.maxDistance=Math.max(s*10,c*1.1),a.update()}_forwardEvents(e,t){if(e)for(let n of t)this._addTrackedListener(e,n,e=>this.dispatchEvent(e))}};async function rx(e){let t=await ax(e);try{return await ix(t,e)}finally{t.dispose()}}async function ix(e,{samples:t=64,colorSpace:n=`srgb`,allowEarlyRetire:r=!1,onProgress:i=void 0}={}){let a=await e.renderFrames(t,{onProgress:i,allowEarlyRetire:r});return{...await e.renderToBuffer({colorSpace:n}),samples:a,retiredBy:a<t?`converged`:`count`,issues:e.issues,adapter:e.adapterInfo}}async function ax({canvas:e,model:t=null,width:n=1920,height:r=1080,strict:i=!0,profile:a=`physical`,deterministic:o=!0,settings:s=null}={}){if(!e)throw Error(`openHeadless: a canvas is required`);let c=new nx(e,{autoResize:!1,strict:i,profile:a});try{return c.setReservedRenderResolution(Math.max(n,r)),await c.init(),c.setCanvasSize(n,r),t&&await c.loadModel(t),s&&c.settings.setMany(s,{silent:!0}),o&&c.setDeterministicMode(!0),c}catch(e){throw c.dispose(),e}}xe();var ox=class{constructor(e){this._app=e,this._cancelled=!1,this._rendering=!1}async renderAnimation(e={}){let{clipIndex:t=0,fps:n=30,speed:r=1,samplesPerFrame:i=wt.maxSamples,enableOIDN:a=!0,onFrame:o,onProgress:s,onComplete:c}=e,l=this._app;if(!l.animationManager?.hasAnimations){console.warn(`VideoRenderManager: No animation clips available`),c?.(!1);return}let u=l.animationManager.clips[t];if(!u){console.warn(`VideoRenderManager: Invalid clip index ${t}`),c?.(!1);return}let d=u.duration/(r||1),f=e.totalFrames||Math.ceil(d*n),p=1/n;this._cancelled=!1,this._rendering=!0;let m=this._saveState();l.stopAnimation(),l.configureForMode(`production`),l.settings.setMany({maxSamples:i},{silent:!0}),l.stages.pathTracer?.updateCompletionThreshold?.(),l.cameraManager.controls&&(l.cameraManager.controls.enabled=!1);try{for(let e=0;e<f&&!this._cancelled;e++){let n=e*p*r,i=l.animationManager.seekTo(n,t);if(i?await l.refitBVH(i):l.reset(),l.stopAnimation(),await this._accumulateFrame(l),this._cancelled||(a&&l.denoisingManager?.finalDenoise&&await this._waitForDenoise(l),this._cancelled))break;let c=l.getCanvas();if(c&&o){let t=await createImageBitmap(c);await o(t,e,f),t.close()}let u={frame:e+1,totalFrames:f,percent:(e+1)/f*100};s?.(u),l.dispatchEvent({type:H.VIDEO_RENDER_PROGRESS,...u})}}catch(e){console.error(`VideoRenderManager: Render error:`,e),this._cancelled=!0}finally{this._restoreState(m),this._rendering=!1;let e=!this._cancelled;c?.(e),l.dispatchEvent({type:H.VIDEO_RENDER_COMPLETE,success:e})}}cancel(){this._cancelled=!0}get isRendering(){return this._rendering}async _accumulateFrame(e){let t=e.stages.pathTracer;if(t?.isReady)for(;!t.isComplete&&!this._cancelled;)e.cameraManager.camera.updateMatrixWorld(),e.pipeline.render(),t.frameCount%4==0&&(Te({samples:Ee(t)}),await new Promise(e=>setTimeout(e,0)))}_waitForDenoise(e){return new Promise(t=>{let n,r=()=>{e.removeEventListener(H.DENOISING_END,i),clearTimeout(n)},i=()=>{r(),t()};n=setTimeout(()=>{console.warn(`VideoRenderManager: Denoise timed out, skipping`),r(),t()},3e4),e.addEventListener(H.DENOISING_END,i),e.denoisingManager.onRenderComplete({isStillComplete:()=>!this._cancelled,context:e.pipeline?.context})})}_saveState(){let e=this._app,t=e.settings.getEffective();return{settings:Object.keys(Et(wt)).map(e=>[e,t[e]]),renderMode:e.stages.pathTracer?.renderMode?.value,controlsEnabled:e.cameraManager.controls?.enabled,oidnEnabled:e.denoisingManager?.finalDenoise,oidnQuality:e.denoisingManager?.oidnQuality,wasPlaying:e.animationManager?.isPlaying,pauseRendering:e.pauseRendering}}_restoreState(e){let t=this._app;for(let[n,r]of e.settings)r&&t.settings.set(n,r.value,{silent:!0,reset:!1,source:r.source});t.stages.pathTracer&&e.renderMode!==void 0&&t.stages.pathTracer?.setUniform(`renderMode`,parseInt(e.renderMode)),t.stages.pathTracer?.updateCompletionThreshold?.(),t.cameraManager.controls&&(t.cameraManager.controls.enabled=e.controlsEnabled??!0),t.denoisingManager?.denoiser&&(t.denoisingManager.applyOIDNEnabled(e.oidnEnabled??!1),e.oidnQuality&&t.denoisingManager.applyOIDNQuality(e.oidnQuality)),t.pauseRendering=e.pauseRendering??!1,t.denoisingManager?.setCadenceSuspended(!1),t.animationManager?.stop(),t.reset(),t.wake()}};xe(),Ar(),qt(),pb(),Db(),ca(),e.AF_DEFAULTS=Qe,e.ASVGF_QUALITY_PRESETS=We,e.AUTO_FOCUS_MODES=Ze,e.AnimationManager=qb,e.BVH_LEAF_MARKERS=ct,e.CAMERA_PRESETS=Xe,e.CAMERA_RANGES=Je,e.CameraManager=ay,e.ColorManagement=mo,e.DEFAULT_LUT_SIZE=Ca,e.DEFAULT_MAX_EV=Sa,e.DEFAULT_MIN_EV=xa,e.DEFAULT_TEXTURE_MATRIX=Ct,e.DEFAULT_WORKING_SPACE=ao,e.DenoisingManager=Lb,e.ENGINE_DEFAULTS=W,e.EngineEvents=H,e.EngineIssueError=dn,e.GoboManager=sy,e.IESManager=vy,e.INTERACTIVE_RENDER_CONFIG=Tt,e.ISSUE_CODES=ln,e.ISSUE_SEVERITY=un,e.InteractionManager=Dg,e.IssueLog=fn,e.LOG_LEVELS=Lt,e.LightManager=oy,e.Logger=Gt,e.MATERIAL_DEFAULTS=J,e.MATERIAL_VALUE_SOURCE=Sn,e.MAX_RESERVABLE_RENDER_SIZE=He,e.MAX_SCENE_BYTES=Yu,e.MAX_TABLE_TRANSFORMS=ta,e.MEMORY_CONSTANTS=Dt,e.MemoryLedger=ed,e.NRD_DEFAULTS=Ge,e.NRD_HIT_DIST_A=ze,e.NRD_HIT_DIST_B=Be,e.NRD_PRESET_KEYS=Ke,e.NRD_QUALITY_PRESETS=qe,e.OCIO_VIEW_BASE=ea,e.OverlayManager=Kb,e.PRODUCTION_RENDER_CONFIG=wt,e.PathTracerApp=nx,e.PipelineContext=dg,e.RENDER_PROFILES=Ie,e.RETOUCH_DEFAULTS=vb,e.RETOUCH_MAX_PIXELS=bb,e.RETOUCH_RANGES=xb,e.RenderPipeline=Cg,e.RenderSettings=jg,e.RenderStage=V,e.SAFE_SCENE_BYTES=Ju,e.SETTING_SOURCE=kg,e.SKY_PRESETS=Ye,e.SR_MAX_INPUT=cb,e.SR_SCALE=ob,e.StageExecutionMode=ye,e.TEXTURE_CONSTANTS=dt,e.TRIANGLE_DATA_LAYOUT=$e,e.TransformManager=Yb,e.VIEW_TRANSFORMS=oa,e.VRAMTracker=tp,e.VideoRenderManager=ox,e.addAllOcioViews=Pa,e.addOcioView=Na,e.addViewTransform=Ji,e.applyMatrixRGBA8=Si,e.bakeLut=fa,e.bufferBytes=$f,e.buildOcioView=Aa,e.buildToneMapWGSL=Qi,e.canvasColorSpaceFor=lo,e.captureHeadless=ix,e.clearBindingAuditFindings=vg,e.clearInputOverrides=Ya,e.configureAssets=Dr,e.convertColor=li,e.convertEncodedRGBA8=_i,e.convertPixelsF32=ui,e.createLogger=Pt,e.deriveAlphaMode=En,e.describeAdapter=tx,e.displayCanvasFit=Er,e.estimateSceneBytes=Qu,e.extractMatrix=Ci,e.extractSceneMetadata=Jv,e.findNativeLinearSpace=po,e.fmt=Y,e.getActiveColorManagement=so,e.getAssetConfig=Or,e.getBindingAuditFindings=_g,e.getRegistryVersion=Hi,e.getRenderProfile=Le,e.getViewTransform=Wi,e.hasColorSpace=Ti,e.isColorManaged=ho,e.isDataSpace=wi,e.isDataTexture=to,e.linearToSrgb=pi,e.listFileRules=Qa,e.listInputOverrides=Xa,e.listViewTransforms=Gi,e.makeCpuSampler=va,e.measureBakeError=ba,e.onRegistryChange=Ui,e.openHeadless=ax,e.parseSceneMetadata=qv,e.probeAddressSpace=$u,e.removeViewTransform=Yi,e.renderHeadless=rx,e.renderUpscaled=rb,e.resolveInputSpace=eo,e.setActiveColorManagement=co,e.setBindingAudit=gg,e.setInputOverride=Ja,e.srgbToLinear=fi,e.textureBytes=ep,e.textureInputSpace=io});
|