@bubo-squared/gyroview 0.4.2 → 0.6.0
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/CHANGELOG.md +54 -0
- package/README.md +6 -6
- package/dist/index.d.ts +56 -15
- package/dist/packages/adapters/mediabunny/src/MediabunnyCodecReader.js +2 -2
- package/dist/packages/adapters/mediabunny/src/decoderConfigurations.js +20 -4
- package/dist/packages/core/src/application/recording/motionOf.js +5 -1
- package/dist/packages/core/src/application/stabilization/StabilizingFrameSink.js +4 -2
- package/dist/packages/core/src/domain/format/mp4/hevcCodecString.js +161 -0
- package/dist/packages/core/src/domain/motion/imu/ImuFrame.js +35 -3
- package/dist/packages/core/src/domain/motion/mounting/Mounting.js +117 -0
- package/dist/packages/core/src/domain/motion/orientation/OrientationTrack.js +4 -2
- package/dist/packages/core/src/domain/motion/orientation/gravity.js +1 -1
- package/dist/packages/core/src/domain/view/Framing.js +8 -2
- package/dist/packages/core/src/domain/view/ViewState.js +13 -8
- package/dist/packages/core/src/domain/view/lensTilesView.js +2 -1
- package/dist/packages/core/src/domain/view/motionLookView.js +103 -0
- package/dist/packages/core/src/domain/view/normalView.js +12 -5
- package/dist/packages/core/src/domain/view/panoramaView.js +2 -1
- package/dist/packages/core/src/domain/view/screenLook.js +74 -0
- package/dist/packages/core/src/domain/view/viewModes.js +18 -1
- package/dist/packages/core/src/index.js +8 -3
- package/dist/packages/core/src/shared/binary/ByteReader.js +4 -0
- package/dist/packages/core/src/shared/index.js +1 -0
- package/dist/packages/core/src/shared/math/Matrix3.js +29 -1
- package/dist/packages/core/src/shared/math/minimum.js +17 -0
- package/dist/packages/player/src/browserPlayer.js +6 -4
- package/dist/packages/player/src/composition/BrowserAttitudeSensor.js +192 -0
- package/dist/packages/player/src/composition/attitudeSensor.js +18 -0
- package/dist/packages/player/src/composition/buildPipeline.js +9 -5
- package/dist/packages/player/src/controls/MotionLookButton.js +35 -0
- package/dist/packages/player/src/controls/controlParts.js +1 -0
- package/dist/packages/player/src/controls/controls.js +1 -1
- package/dist/packages/player/src/controls/controlsBar.js +5 -3
- package/dist/packages/player/src/controls/controlsMarkup.js +1 -0
- package/dist/packages/player/src/controls/icons.js +1 -0
- package/dist/packages/player/src/controls/messages.js +1 -0
- package/dist/packages/player/src/element/GyroViewElement.js +21 -0
- package/dist/packages/player/src/player/AutomaticStarts.js +54 -0
- package/dist/packages/player/src/player/MotionLook.js +150 -0
- package/dist/packages/player/src/player/Player.js +46 -39
- package/dist/packages/player/src/player/PlayerEvents.js +1 -0
- package/dist/packages/player/src/player/PlayerView.js +44 -13
- package/dist/packages/player/src/player/ensureFinite.js +2 -1
- package/dist/packages/player/src/player/viewAngles.js +17 -0
- package/dist/standalone.js +115 -62
- package/package.json +3 -3
package/dist/standalone.js
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
/*! @bubo-squared/gyroview (MIT). Bundles three.js (MIT, https://github.com/mrdoob/three.js) and
|
|
2
2
|
mediabunny (MPL-2.0, source at https://github.com/Vanilagy/mediabunny). */
|
|
3
|
-
var e=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),t=e=>e,n=e=>e,r=90,i=180,a=360,o=t(r),s=t(i),c=t(a),l=e=>n(e*Math.PI/i),u=e=>t(e*i/Math.PI);function d(e){let n=e%c;return n>s&&(n-=c),n<=-s&&(n+=c),t(n)}var f={EdgeRadius:0,CenterX:1,CenterY:2,Yaw:3,Pitch:4,Roll:5},p={EdgeRadius:0,CenterX:1,CenterY:2,Yaw:3,Pitch:4,Roll:5,TranslationX:6,TranslationY:7,TranslationZ:8,C1:9,C2:10,C3:11,C4:12,CanvasWidth:13,CanvasHeight:14,LensType:15},m={Xi:0,FocalX:1,FocalY:2,CenterX:3,CenterY:4,Yaw:5,Pitch:6,Roll:7,TranslationX:8,TranslationY:9,TranslationZ:10},h={K1:11,K2:12,K3:13,P1:14,P2:15,CanvasWidth:16,CanvasHeight:17,LensType:18},g={K1:11,K2:12,K3:13,K4:14,K5:15,P1:16,P2:17,P3:18,P4:19,S1:20,S2:21,S3:22,S4:23,CanvasWidth:24,CanvasHeight:25,LensType:26},_={CanvasWidth:0,CanvasHeight:1,VersionWord:2};function v(e,n,r){return{yaw:t(e),pitch:t(n),roll:t(r)}}function y(e,t){let n=e>>>16;return n===t?void 0:`declares version ${n}`}function b(e,t,n){let[r]=e;return r?{width:r(t),height:r(n)}:x}var x={width:0,height:0};function S(e){let[t,r,i]=e,a=Math.hypot(t,r);return{theta:n(Math.atan2(a,i)),radialUnit:a===0?[0,0]:[t/a,r/a]}}function C(e,t,n){return{x:e.x+t*n[0],y:e.y+t*n[1]}}var w=l(t(100)),T=l(t(96)),E=class{parameters;kind=`equidistant`;halfFieldOfView=w;principalPoint;constructor(e){this.parameters=e,this.principalPoint=e.principalPoint}get projection(){return{kind:`radial-polynomial`,principalPoint:this.principalPoint,coefficients:[this.pixelsPerRadian,0,0,0]}}project(e){let{theta:t,radialUnit:n}=S(e);return t>this.halfFieldOfView?void 0:C(this.principalPoint,this.pixelsPerRadian*t,n)}get pixelsPerRadian(){return this.parameters.edgeRadius/this.parameters.radiusAngle}},D={Legacy:1,Polynomial:2,Mei:3,ExtendedMei:6},O={version:D.Legacy,lensTokens:6,trailingTokens:3,radialScale:1,parseLens(e,t){return{lensIndex:t,model:new E({edgeRadius:e(f.EdgeRadius),radiusAngle:T,principalPoint:{x:e(f.CenterX),y:e(f.CenterY)}}),orientation:v(e(f.Yaw),e(f.Pitch),e(f.Roll)),translation:[0,0,0]}},canvasOf(e){let t=1+(e[0]??0)*6;return{width:e[t+_.CanvasWidth]??0,height:e[t+_.CanvasHeight]??0}}},k=/* @__PURE__ */ `binary-out-of-bounds.binary-unsafe-integer.codec-unsupported.cors.decode.embed-destroyed.index-out-of-range.invalid-argument.invalid-byte-range.invalid-calibration.invalid-protobuf.invalid-trailer.invariant-violation.missing-second-file.no-calibration.no-info-record.no-key-frame.playback-blocked.range-unsupported.render-unavailable.source-changed.source-truncated.source-unreadable.unsupported-calibration.unsupported-container.unsupported-gyro-record.unsupported-info-format.unsupported-layout.webcodecs-unavailable`.split(`.`),A=[`browser`,`recording`,`source`,`usage`,`internal`],ee={"binary-out-of-bounds":`recording`,"binary-unsafe-integer":`recording`,"codec-unsupported":`browser`,cors:`source`,decode:`browser`,"embed-destroyed":`usage`,"index-out-of-range":`internal`,"invalid-argument":`usage`,"invalid-byte-range":`recording`,"invalid-calibration":`recording`,"invalid-protobuf":`recording`,"invalid-trailer":`recording`,"invariant-violation":`internal`,"missing-second-file":`recording`,"no-calibration":`recording`,"no-info-record":`recording`,"no-key-frame":`recording`,"playback-blocked":`browser`,"range-unsupported":`source`,"render-unavailable":`browser`,"source-changed":`source`,"source-truncated":`source`,"source-unreadable":`source`,"unsupported-calibration":`recording`,"unsupported-container":`recording`,"unsupported-gyro-record":`recording`,"unsupported-info-format":`recording`,"unsupported-layout":`recording`,"webcodecs-unavailable":`browser`};function te(e){return typeof e==`string`&&k.includes(e)}var j=class extends Error{code;category;constructor(e,t,n){super(t,n),this.code=e,this.name=`GyroViewError`,this.category=ee[e]}};function ne(e,t,n){return e instanceof j?e:new j(t,n,{cause:e})}function re(e){return e instanceof Error&&e.name===`AbortError`}function M(e,t){return e instanceof j&&e.code===t}function ie(e){return e instanceof Error?e.message:String(e)}function N(e,t){if(!e)throw new j(`invariant-violation`,t)}function ae(e,t,n){if(!Number.isSafeInteger(e)||e<0||e>=t)throw new j(`index-out-of-range`,`${n} index ${e} is outside 0..${t-1}`)}var oe={radial:5,tangential:2,thinPrism:2};function se(e){ce(`radial`,e.radial.length),ce(`tangential`,e.tangential.length),ce(`thinPrism`,e.thinPrism.length)}function ce(e,t){let n=oe[e];N(t<=n,`a Mei distortion has ${t} ${e} terms, more than the ${n} a string carries`)}function le(e,t){let[n,r]=t,i=n*n+r*r,a=1+i*ue(i,e.radial,e=>e),o=ue(i,e.tangential,e=>e.p1),s=ue(i,e.tangential,e=>e.p2),c=i*ue(i,e.thinPrism,e=>e.x),l=i*ue(i,e.thinPrism,e=>e.y);return[a*n+2*o*n*r+s*(i+2*n*n)+c,a*r+o*(i+2*r*r)+2*s*n*r+l]}function ue(e,t,n){return t.reduceRight((t,r)=>t*e+n(r),0)}var de=class{parameters;kind=`mei`;halfFieldOfView=w;principalPoint;constructor(e){this.parameters=e,se(e.distortion),this.principalPoint=e.principalPoint}get projection(){return{kind:`mei`,...this.parameters}}project(e){let[t,n,r]=e,i=r+this.parameters.xi;if(i<=0||Math.atan2(Math.hypot(t,n),r)>this.halfFieldOfView)return;let[a,o]=le(this.parameters.distortion,[t/i,n/i]);return{x:this.parameters.focal[0]*a+this.principalPoint.x,y:this.parameters.focal[1]*o+this.principalPoint.y}}},fe=({radial:e,tangential:t})=>{let[n,r]=t;return{radial:e,tangential:[{p1:n,p2:r}],thinPrism:[]}};function pe(e){return{version:e.version,lensTokens:e.lensTokens,trailingTokens:1,radialScale:e.radialScale,versionWordProblem:t=>y(t,e.version),parseLens:(t,n)=>me(t,n,e),canvasOf:(t,n)=>b(n,e.canvasTokens.width,e.canvasTokens.height)}}function me(e,t,n){return{lensIndex:t,model:new de({xi:e(m.Xi),focal:[e(m.FocalX),e(m.FocalY)],principalPoint:{x:e(m.CenterX),y:e(m.CenterY)},distortion:n.distortionOf(e)}),orientation:v(e(m.Yaw),e(m.Pitch),e(m.Roll)),translation:[e(m.TranslationX),e(m.TranslationY),e(m.TranslationZ)]}}var he=pe({version:D.Mei,lensTokens:19,canvasTokens:{width:h.CanvasWidth,height:h.CanvasHeight},distortionOf:e=>({radial:[e(h.K1),e(h.K2),e(h.K3)],tangential:[{p1:e(h.P1),p2:e(h.P2)}],thinPrism:[]}),radialScale:1}),ge=1.008;function _e(e){return pe({version:D.ExtendedMei,lensTokens:27,canvasTokens:{width:g.CanvasWidth,height:g.CanvasHeight},distortionOf:t=>e(ye(t)),radialScale:ge})}var ve=_e(fe);function ye(e){return{radial:[e(g.K1),e(g.K2),e(g.K3),e(g.K4),e(g.K5)],tangential:[e(g.P1),e(g.P2),e(g.P3),e(g.P4)],thinPrism:[e(g.S1),e(g.S2),e(g.S3),e(g.S4)]}}var be=class{parameters;kind=`polynomial`;halfFieldOfView=w;principalPoint;scale;constructor(e){this.parameters=e,this.principalPoint=e.principalPoint,this.scale=e.edgeRadius/this.polynomial(this.halfFieldOfView)}get projection(){let[e,t,n,r]=this.parameters.coefficients;return{kind:`radial-polynomial`,principalPoint:this.principalPoint,coefficients:[e*this.scale,t*this.scale,n*this.scale,r*this.scale]}}project(e){let{theta:t,radialUnit:n}=S(e);return t>this.halfFieldOfView?void 0:C(this.principalPoint,this.scale*this.polynomial(t),n)}polynomial(e){let[t,n,r,i]=this.parameters.coefficients;return e*(t+e*(n+e*(r+e*i)))}},xe={version:D.Polynomial,lensTokens:16,trailingTokens:1,radialScale:1,versionWordProblem:e=>y(e,D.Polynomial),parseLens(e,t){return{lensIndex:t,model:new be({edgeRadius:e(p.EdgeRadius),principalPoint:{x:e(p.CenterX),y:e(p.CenterY)},coefficients:[e(p.C1),e(p.C2),e(p.C3),e(p.C4)]}),orientation:v(e(p.Yaw),e(p.Pitch),e(p.Roll)),translation:[e(p.TranslationX),e(p.TranslationY),e(p.TranslationZ)]}},canvasOf(e,t){return b(t,p.CanvasWidth,p.CanvasHeight)}},Se=`_`,Ce=[O,xe,he,ve];function P(e,t=Ce){let n=e.split(Se).map(e=>De(e)),r=n[0]??0,i=Te(t,n);Ee(i,n.at(-1)??0);let a=Array.from({length:r},(e,t)=>F(n,1+t*i.lensTokens));return{version:i.version,canvas:i.canvasOf(n,a),lenses:a.map((e,t)=>i.parseLens(e,t)),radialScale:i.radialScale}}function we(e,t,n){return 1+e*t+n}function Te(e,t){let n=t[0]??0,r=e.find(e=>t.length===we(n,e.lensTokens,e.trailingTokens));if(r)return r;throw new j(`invalid-calibration`,`calibration string has ${t.length} tokens for ${n} lenses, matching no known layout`)}function Ee(e,t){let n=e.versionWordProblem?.(t);if(n!==void 0)throw new j(`invalid-calibration`,`calibration string has the v${e.version} layout but ${n}`)}function F(e,t){return n=>e[t+n]??NaN}function De(e){let t=Number(e);if(e.trim()===``||!Number.isFinite(t))throw new j(`invalid-calibration`,`calibration token "${e}" is not a finite number`);return t}var I={SerialNumber:1,Model:2,Firmware:3,Offset:5,Dimension:19,FrameRate:20,CaptureMode:22,FirstFrameTimestamp:24,RollingShutterTimeMs:25,FileGroupInfo:26,WindowCropInfo:27,GyroTimestampMs:28,HasGyroTimestamp:29,TotalFrames:40,IsFlowstateOnline:42,GyroType:51,OffsetV2:53,OffsetV3:54,IsRawGyro:62,PtsType:64,GyroConfig:65,FileLayout:79,TrackOrder:80,OffsetV6:111},L={Width:1,Height:2},Oe={AccelerometerRangeG:1,GyroscopeRangeDps:2},ke={SensorWidth:1,SensorHeight:2,CropWidth:3,CropHeight:4,CropOffsetX:5,CropOffsetY:6},Ae={TrackTimestamps:1,ExposureRecord:2},je={SplitFiles:1,MultiTrack:2},Me={Stream10First:1,Stream00First:2},Ne={offset:{field:I.Offset,name:`offset`},offsetV2:{field:I.OffsetV2,name:`offset_v2`},offsetV3:{field:I.OffsetV3,name:`offset_v3`},offsetV6:{field:I.OffsetV6,name:`offset_v6`}},Pe=/* @__PURE__ */ new Set([`invalid-calibration`,`unsupported-calibration`]),Fe=[`offset`,`offsetV6`,`offsetV3`,`offsetV2`];function Ie(e){let t=[];for(let n of Le(e)){if(`calibration`in n)return{calibration:n.calibration,warnings:t};t.push(n.warning)}return{calibration:void 0,warnings:t}}function*Le(e){for(let t of Fe){let n=e[t];n!==void 0&&(yield Re(Ne[t],n))}}function Re({name:e},t){try{return{calibration:P(t)}}catch(t){if(t instanceof j&&Pe.has(t.code))return{warning:`${e} skipped: ${t.message}`};throw t}}var ze={Index:0,Info:1,Thumbnail:2,Gyro:3,Exposure:4,ThumbnailExtended:5,FrameTimestamps:6,Gps:7},Be={Protobuf:1,Json:2},Ve=1,He=2,Ue=4,We=8,Ge=4,Ke=8,qe=8,Je=!0,Ye=!1,Xe=BigInt(-(2**53-1)),Ze=BigInt(2**53-1),Qe=class{bytes;view;constructor(e){this.bytes=e,this.view=new DataView(e.buffer,e.byteOffset,e.byteLength)}get length(){return this.bytes.byteLength}uint8At(e){return this.ensureAvailable(e,Ve),this.view.getUint8(e)}uint16LeAt(e){return this.ensureAvailable(e,He),this.view.getUint16(e,Je)}uint32LeAt(e){return this.ensureAvailable(e,Ue),this.view.getUint32(e,Je)}uint32BeAt(e){return this.ensureAvailable(e,Ue),this.view.getUint32(e,Ye)}int32BeAt(e){return this.ensureAvailable(e,Ge),this.view.getInt32(e,Ye)}uint64LeAt(e){return this.ensureAvailable(e,We),this.toSafeNumber(this.view.getBigUint64(e,Je),e)}uint64BeAt(e){return this.ensureAvailable(e,We),this.toSafeNumber(this.view.getBigUint64(e,Ye),e)}int64BeAt(e){return this.ensureAvailable(e,Ke),this.toSafeNumber(this.view.getBigInt64(e,Ye),e)}float64LeAt(e){return this.ensureAvailable(e,qe),this.view.getFloat64(e,Je)}bytesAt(e,t){return this.ensureAvailable(e,t),this.bytes.subarray(e,e+t)}asciiAt(e,t){return Array.from(this.bytesAt(e,t),e=>String.fromCodePoint(e)).join(``)}toSafeNumber(e,t){if(!(e>=Xe&&e<=Ze))throw new j(`binary-unsafe-integer`,`64-bit integer at offset ${t} (${e.toString()}) exceeds the safe integer range`);return Number(e)}ensureAvailable(e,t){if(e<0||t<0||e+t>this.bytes.byteLength)throw new j(`binary-out-of-bounds`,`read of ${t} byte(s) at offset ${e} exceeds ${this.bytes.byteLength} available`)}};function $e(e){let t;return()=>(t??={value:e()}).value}var et=$e(()=>new globalThis.TextDecoder(`utf8`));function tt(e){return et().decode(e)}var nt={Varint:0,Fixed64:1,LengthDelimited:2,Fixed32:5},rt=BigInt(7),it=BigInt(127),at=BigInt(2**53-1),ot=class e{decoded;constructor(e){this.decoded=e}static decode(t){let n=new st(t),r=[];for(;!n.atEnd;)r.push(n.readField());return new e(r)}varint(e){let t=this.valueOf(e);if(t!==void 0){if(t.kind!==`varint`)throw this.wrongType(e,`varint`,t.kind);if(t.value>at)throw new j(`binary-unsafe-integer`,`field ${e} holds ${t.value.toString()}, beyond the safe integer range`);return Number(t.value)}}boolean(e){let t=this.varint(e);return t===void 0?void 0:t!==0}double(e){let t=this.valueOf(e);if(t!==void 0){if(t.kind!==`fixed64`)throw this.wrongType(e,`fixed64`,t.kind);return new Qe(t.bytes).float64LeAt(0)}}bytes(e){let t=this.valueOf(e);if(t!==void 0){if(t.kind!==`bytes`)throw this.wrongType(e,`bytes`,t.kind);return t.bytes}}string(e){let t=this.bytes(e);return t===void 0?void 0:tt(t)}message(t){let n=this.bytes(t);return n===void 0?void 0:e.decode(n)}valueOf(e){return this.decoded.findLast(t=>t.number===e)?.value}wrongType(e,t,n){return new j(`invalid-protobuf`,`field ${e} is encoded as ${n}, expected ${t}`)}},st=class{bytes;position=0;reader;constructor(e){this.bytes=e,this.reader=new Qe(e)}get atEnd(){return this.position>=this.bytes.byteLength}readField(){let e=this.readVarint(),t=Number(e>>BigInt(3)),n=Number(e&BigInt(7));return{number:t,value:this.readValue(n,t)}}readValue(e,t){switch(e){case nt.Varint:return{kind:`varint`,value:this.readVarint()};case nt.Fixed64:return{kind:`fixed64`,bytes:this.readBytes(8)};case nt.Fixed32:return{kind:`fixed32`,bytes:this.readBytes(4)};case nt.LengthDelimited:return{kind:`bytes`,bytes:this.readBytes(this.readLength())};default:throw new j(`invalid-protobuf`,`field ${t} uses unsupported wire type ${e}`)}}readVarint(){let e=0n,t=0n;for(let n=0;n<10;n+=1){let n=this.readByte();if(e|=(BigInt(n)&it)<<t,!(n&128))return e;t+=rt}throw new j(`invalid-protobuf`,`varint longer than 10 bytes at byte ${this.position}`)}readLength(){let e=this.readVarint();if(e>BigInt(this.bytes.byteLength))throw new j(`invalid-protobuf`,`length ${e.toString()} exceeds the message at byte ${this.position}`);return Number(e)}readByte(){this.ensureRemaining(1);let e=this.reader.uint8At(this.position);return this.position+=1,e}readBytes(e){this.ensureRemaining(e);let t=this.reader.bytesAt(this.position,e);return this.position+=e,t}ensureRemaining(e){if(this.position+e>this.bytes.byteLength)throw new j(`invalid-protobuf`,`message truncated at byte ${this.position}`)}};function ct(e,t){let n=Object.entries(e).map(([e,n])=>[e,t(n,e)]);return Object.fromEntries(n)}var lt=1e6,ut=1e3,dt=1e3,ft=e=>e,pt=e=>e,R=e=>e,mt=e=>R(e/lt),ht=e=>ft(e*dt),gt=e=>R(e/ut),_t=e=>ft(e*lt);function vt(e,t){if(t!==Be.Protobuf)throw new j(`unsupported-info-format`,`info record uses format ${t}; only protobuf (${Be.Protobuf}) is supported`);let n=ot.decode(e);return{serialNumber:n.string(I.SerialNumber),model:n.string(I.Model),firmware:n.string(I.Firmware),calibration:Tt(n),dimension:Et(n.message(I.Dimension)),frameRate:n.varint(I.FrameRate),captureMode:n.string(I.CaptureMode),firstFrameTimestamp:n.varint(I.FirstFrameTimestamp),readoutTime:yt(n.double(I.RollingShutterTimeMs)),windowCrop:Dt(n.message(I.WindowCropInfo)),gyroOffset:bt(n),gyroType:n.varint(I.GyroType),isRawGyro:n.boolean(I.IsRawGyro),preferredFrameTimeSource:St(n.varint(I.PtsType)),sensorRanges:Ot(n.message(I.GyroConfig)),fileLayout:Ct(n.varint(I.FileLayout)),trackOrder:wt(n.varint(I.TrackOrder))}}function yt(e){return e===void 0?void 0:gt(pt(e))}function bt(e){return e.boolean(I.HasGyroTimestamp)===!0?xt(e.double(I.GyroTimestampMs)):void 0}function xt(e){return e===void 0?void 0:pt(e)}function St(e){return e===Ae.TrackTimestamps?`track-timestamps`:e===Ae.ExposureRecord?`exposure-record`:void 0}function Ct(e){return e===je.SplitFiles?`split-files`:e===je.MultiTrack?`multi-track`:void 0}function wt(e){return e===Me.Stream10First?`stream-10-first`:e===Me.Stream00First?`stream-00-first`:void 0}function Tt(e){return ct(Ne,t=>e.string(t.field))}function Et(e){let t=e?.varint(L.Width),n=e?.varint(L.Height);return t===void 0||n===void 0?void 0:{width:t,height:n}}function Dt(e){return e===void 0?void 0:{sensorWidth:e.varint(ke.SensorWidth),sensorHeight:e.varint(ke.SensorHeight),cropWidth:e.varint(ke.CropWidth),cropHeight:e.varint(ke.CropHeight),cropOffsetX:e.varint(ke.CropOffsetX),cropOffsetY:e.varint(ke.CropOffsetY)}}function Ot(e){return e===void 0?void 0:{accelerometerG:e.varint(Oe.AccelerometerRangeG),gyroscopeDps:e.varint(Oe.GyroscopeRangeDps)}}async function kt(e,t){let n=t.locationOf(ze.Info);if(!n)throw new j(`no-info-record`,`the trailer has no info record; the file is not a camera recording`);return vt(await e.read(n.payload),n.format)}var At=class e{captureTimeStore;shutterTimeStore;constructor(e,t){this.captureTimeStore=e,this.shutterTimeStore=t,N(e.length===t.length,`exposure record arrays disagree on the entry count`)}get length(){return this.captureTimeStore.length}get captureTimes(){return this.captureTimeStore}get shutterTimes(){return this.shutterTimeStore}entryAt(e){return ae(e,this.length,`exposure entry`),{captureTime:ft(this.captureTimeStore[e]??0),shutterTime:R(this.shutterTimeStore[e]??0)}}indexAtOrAfter(e){let t=0,n=this.captureTimeStore.length;for(;t<n;){let r=t+n>>>1;(this.captureTimeStore[r]??1/0)<e?t=r+1:n=r}return t}slice(t,n){return N(t>=0&&n>=0&&t+n<=this.length,`exposure slice out of range`),new e(this.captureTimeStore.slice(t,t+n),this.shutterTimeStore.slice(t,t+n))}},jt=60;function Mt(e,t){try{return Nt(e,t)}catch(e){if(M(e,`binary-unsafe-integer`))return;throw e}}function Nt(e,t){let n=Math.floor(e.byteLength/16),r=new Qe(e),i=new Float64Array(n),a=new Float64Array(n);for(let e=0;e<n;e+=1){let n=e*16;i[e]=t(r.uint64LeAt(n+0)),a[e]=r.float64LeAt(n+8)}return Pt(i)&&a.every(e=>Ft(e))?new At(i,a):void 0}function Pt(e){return e.every((t,n)=>n===0||t>=(e[n-1]??t))}function Ft(e){return e>=0&&e<=jt}var It=32768,Lt=32768,Rt=[Lt,Lt/2],zt=2e3,Bt=class{name=`float`;sampleSize=56;flipSteps={acceleration:[],angularVelocity:[]};captureTimeOf(e){return ht(pt(e))}timestampAt(e,t){return this.captureTimeOf(e.uint64LeAt(t+0))}accelerationAt(e,t){return this.vectorAt(e,t+8)}angularVelocityAt(e,t){return this.vectorAt(e,t+32)}vectorAt(e,t){return[e.float64LeAt(t),e.float64LeAt(t+8),e.float64LeAt(t+16)]}},Vt=class{name=`raw`;sampleSize=20;flipSteps;accelerationScale;angularVelocityScale;constructor(e={}){let n=Ht(e.accelerometerG,16),r=Ht(e.gyroscopeDps,zt);this.accelerationScale=n/Lt,this.angularVelocityScale=l(t(r))/Lt,this.flipSteps={acceleration:Rt.map(e=>e*this.accelerationScale),angularVelocity:Rt.map(e=>e*this.angularVelocityScale)}}captureTimeOf(e){return ft(e)}timestampAt(e,t){return this.captureTimeOf(e.uint64LeAt(t+0))}accelerationAt(e,t){return this.vectorAt(e,t+8,this.accelerationScale)}angularVelocityAt(e,t){return this.vectorAt(e,t+14,this.angularVelocityScale)}vectorAt(e,t,n){return[this.componentAt(e,t,n),this.componentAt(e,t+2,n),this.componentAt(e,t+4,n)]}componentAt(e,t,n){return(e.uint16LeAt(t)-It)*n}};function Ht(e,t){return e!==void 0&&e>0?e:t}var Ut=[0,0,0];function Wt(e){return Math.sqrt(Gt(e,e))}function Gt(e,t){return e[0]*t[0]+e[1]*t[1]+e[2]*t[2]}function Kt(e,t){return[e[1]*t[2]-e[2]*t[1],e[2]*t[0]-e[0]*t[2],e[0]*t[1]-e[1]*t[0]]}function qt(e){return e.every(e=>Number.isFinite(e))}function Jt(e,t){return[e[0]+t[0],e[1]+t[1],e[2]+t[2]]}function Yt(e,t){return[e[0]-t[0],e[1]-t[1],e[2]-t[2]]}function Xt(e,t){return[e[0]*t,e[1]*t,e[2]*t]}function Zt(e,t,n){return Jt(e,Xt(Yt(t,e),n))}var Qt=class{captureTimeStore;accelerationStore;angularVelocityStore;constructor(e,t,n){this.captureTimeStore=e,this.accelerationStore=t,this.angularVelocityStore=n;let r=e.length*3;N(t.length===r&&n.length===r,`gyro track arrays disagree on the sample count`),N($t(e),`gyro sample times go back`)}get length(){return this.captureTimeStore.length}get isEmpty(){return this.captureTimeStore.length===0}get captureTimes(){return this.captureTimeStore}get meanSampleInterval(){return this.length<2?void 0:ft(((this.captureTimeStore[this.length-1]??0)-(this.captureTimeStore[0]??0))/(this.length-1))}sampleAt(e){return ae(e,this.length,`gyro sample`),{captureTime:ft(this.captureTimeStore[e]??0),acceleration:this.vectorAt(this.accelerationStore,e),angularVelocity:this.vectorAt(this.angularVelocityStore,e)}}angularVelocityAt(e){return ae(e,this.length,`gyro sample`),this.vectorAt(this.angularVelocityStore,e)}vectorAt(e,t){let n=t*3;return[e[n]??NaN,e[n+1]??NaN,e[n+2]??NaN]}};function $t(e){return e.every((t,n)=>n===0||t>=(e[n-1]??t))}var en=16,tn=class{length=0;recordedTimes;accelerations;angularVelocities;constructor(e){this.recordedTimes=new Float64Array(e),this.accelerations=new Float32Array(e*3),this.angularVelocities=new Float32Array(e*3)}push(e){let t=this.length*3;this.recordedTimes[this.length]=e.captureTime;for(let n=0;n<3;n+=1)this.accelerations[t+n]=e.acceleration[n]??NaN,this.angularVelocities[t+n]=e.angularVelocity[n]??NaN;this.length+=1}dropFlippedBits(e){let t=0;for(let n=0;n<this.length;n+=1)this.isFlippedAt(n,e)||(this.moveSample(n,t),t+=1);this.length=t}captureTimes(){return this.recordedTimes.subarray(0,this.length)}toTrack(e){let t=this.length*3;return new Qt(e,this.accelerations.subarray(0,t),this.angularVelocities.subarray(0,t))}isFlippedAt(e,t){return e>0&&e<this.length-1&&(nn(this.accelerations,e,t.acceleration)||nn(this.angularVelocities,e,t.angularVelocity))}moveSample(e,t){if(e!==t){this.recordedTimes[t]=this.recordedTimes[e]??0;for(let n of[this.accelerations,this.angularVelocities])n.copyWithin(t*3,e*3,(e+1)*3)}}};function nn(e,t,n){for(let r=0;r<3;r+=1)if(rn(e,t*3+r,n))return!0;return!1}function rn(e,t,n){let r=e[t-3]??0,i=e[t+3]??0,a=Math.abs((e[t]??0)-(r+i)/2),o=Math.abs(r-i);for(let e of n){let t=e/en;if(o<=t&&Math.abs(a-e)<=t)return!0}return!1}function an(e){let t=e.subarray(1).map((t,n)=>t-(e[n]??t)).toSorted();return t[Math.floor(t.length/2)]??0}var on=50,sn=1e4,cn=17;function ln(e){let t=dn(e),n={recorded:e,interval:t,tolerance:un(t)},r=Float64Array.from(e);hn(r,pn(fn(n)),n);let i=r.filter((t,n)=>t!==e[n]).length;for(let e=1;e<r.length;e+=1)r[e]=Math.max(r[e]??0,r[e-1]??0);return{times:r,mended:i}}function un(e){return Math.max(on*e,sn)}function dn(e){return an(e.subarray(0,1025))}function fn({recorded:e,tolerance:t}){let n=[],r=0;for(let i=1;i<=e.length;i+=1){let a=(e[i]??-1/0)-(e[i-1]??0);a>=0&&a<=t||(n.push({start:r,end:i}),r=i)}return n}function pn(e){let t=0;for(let n of e)t=Math.max(t,mn(n));return e.filter(e=>{let n=mn(e);return n>=cn||n===t})}function mn(e){return e.end-e.start}function hn(e,t,n){let[r]=t;if(r){for(let t=r.start-1;t>=0;--t)e[t]=_n(t,(e[t+1]??0)-n.interval,n);for(let[r,i]of t.entries())gn(e,{start:i.end,end:t[r+1]?.start??e.length},n)}}function gn(e,t,n){for(let r=t.start;r<t.end;r+=1)e[r]=_n(r,(e[r-1]??0)+n.interval,n)}function _n(e,t,n){let r=n.recorded[e]??t;return Math.abs(r-t)<=n.tolerance?r:t}var vn=100,yn=1e4,bn=32,xn=2,Sn=64,Cn=100,wn=56*bn;function Tn(e,t){let n=new Vt(e.ranges),r=new Bt;if(e.isRawGyro!==void 0)return e.isRawGyro?n:r;if(t===void 0)return;let i=[n,r].filter(e=>An(t,e)),[a]=i;if(a&&i.length===1)return a;throw new j(`unsupported-gyro-record`,`cannot tell the gyro sample layout from the first ${t.byteLength} bytes without the info record`)}function En(e,t){let n=Math.floor(e.byteLength/t.sampleSize),r=new Qe(e),i=new tn(n);for(let e=0;e<n;e+=1){let n=Dn(r,t,e*t.sampleSize);n&&i.push(n)}i.dropFlippedBits(t.flipSteps);let a=ln(i.captureTimes());return{track:i.toTrack(a.times),layout:t.name,strayBytes:e.byteLength%t.sampleSize,damagedSamples:n-i.length,mendedStamps:a.mended}}function Dn(e,t,n){try{let r=t.timestampAt(e,n);if(r===0&&On(e.bytesAt(n,t.sampleSize)))return;let i={captureTime:r,acceleration:t.accelerationAt(e,n),angularVelocity:t.angularVelocityAt(e,n)};return kn(i.acceleration,Sn)&&kn(i.angularVelocity,Cn)?i:void 0}catch(e){if(M(e,`binary-unsafe-integer`))return;throw e}}function On(e){return e.every(e=>e===0)}function kn(e,t){return e.every(e=>Math.abs(e)<=t)}function An(e,t){let n=jn(e,t);if(n.length<xn)return!1;let r=an(n);return r>=vn&&r<=yn}function jn(e,t){let n=new Qe(e),r=Math.floor(e.byteLength/t.sampleSize),i=[];for(let e=0;e<r;e+=1){let r=Mn(n,t,e*t.sampleSize);r!==void 0&&i.push(r)}return Float64Array.from(i)}function Mn(e,t,n){try{return t.timestampAt(e,n)}catch(e){if(M(e,`binary-unsafe-integer`))return;throw e}}function Nn(e,t){return t?t.captureTimeOf(e):ft(e)}function Pn(e,t){let n=e.firstFrameTimestamp;return n===void 0?void 0:Nn(n,t)}var Fn=class e{offset;length;constructor(e,t){this.offset=e,this.length=t}static of(t,n){if(!Number.isSafeInteger(t)||t<0)throw new j(`invalid-byte-range`,`offset must be a non-negative integer, got ${t}`);if(!Number.isSafeInteger(n)||n<0)throw new j(`invalid-byte-range`,`length must be a non-negative integer, got ${n}`);return new e(t,n)}static lastOf(e,t){if(t>e)throw new j(`invalid-byte-range`,`cannot take ${t} bytes from a ${e}-byte source`);return this.of(e-t,t)}get end(){return this.offset+this.length}overlaps(e){return Math.max(this.offset,e.offset)<Math.min(this.end,e.end)}contains(e){return this.offset<=e.offset&&e.end<=this.end}ensureWithin(e,t){if(!(this.end<=e))throw new j(`invalid-byte-range`,`range ${this.offset}+${this.length} exceeds the ${e}-byte ${t}`)}},In=class{source;trailer;info;gyroLayoutPromise;constructor(e,t,n){this.source=e,this.trailer=t,this.info=n}get listsExposure(){return this.trailer.locationOf(ze.Exposure)!==void 0}async readGyro(){let e=this.trailer.locationOf(ze.Gyro);if(e===void 0)return;let[t,n]=await Promise.all([this.source.read(e.payload),this.gyroSampleLayout()]);return N(n!==void 0,`a gyro record always yields or refuses a layout`),En(t,n)}async readExposure(){let e=this.trailer.locationOf(ze.Exposure);if(e===void 0)return;let[t,n]=await Promise.all([this.source.read(e.payload),this.gyroSampleLayout()]);return Mt(t,e=>Nn(e,n))}async firstFrameCaptureTime(){return Pn(this.info,await this.gyroSampleLayout())}gyroSampleLayout(){return this.gyroLayoutPromise??=this.selectGyroLayout(),this.gyroLayoutPromise}async selectGyroLayout(){let e=this.gyroLayoutHints();if(e.isRawGyro!==void 0)return Tn(e,void 0);let t=this.trailer.locationOf(ze.Gyro);return Tn(e,t===void 0?void 0:await this.readHeadOf(t))}gyroLayoutHints(){return{isRawGyro:this.info.isRawGyro,ranges:this.info.sensorRanges}}readHeadOf(e){let t=Math.min(wn,e.payload.length);return this.source.read(Fn.of(e.payload.offset,t))}},Ln=class e{format;id;payloadSize;constructor(e,t,n){this.format=e,this.id=t,this.payloadSize=n}static parse(t){if(t.byteLength!==6)throw new j(`invalid-trailer`,`record header must be 6 bytes, got ${t.byteLength}`);let n=new Qe(t);return new e(n.uint8At(0),n.uint8At(1),n.uint32LeAt(2))}};function Rn(e,t){if(e.byteLength%10!=0)throw new j(`invalid-trailer`,`index size ${e.byteLength} is not a multiple of 10`);let n=new Qe(e),r=[];for(let i=0;i<e.byteLength;i+=10){let e=zn(n,i,t);e&&r.push(e)}return r}function zn(e,t,n){let r=e.uint32LeAt(t+2);return r===0?void 0:{id:e.uint8At(t+0),format:e.uint8At(t+1),payload:Fn.of(n+e.uint32LeAt(t+6),r)}}function Bn(e,t){return t.lastHeader.id===ze.Index?Vn(e,t):Un(e,t)}async function Vn(e,t){let n=t.fileSize-72-6-t.lastHeader.payloadSize;Kn(n,t.lastHeader,t.payloadStart);let r=Fn.of(n,t.lastHeader.payloadSize),i=Rn(await e.read(r),t.payloadStart);for(let e of i)Hn(e,r.offset);return i}function Hn(e,t){if(e.payload.end>t)throw new j(`invalid-trailer`,`record ${e.id} at ${e.payload.offset}+${e.payload.length} lies outside the trailer`)}async function Un(e,t){let n=[],r=new Gn(e,t.payloadStart),i=t.fileSize-72;for(;i>t.payloadStart;){let e=Ln.parse(await r.bytesEndingAt(i,6)),a=i-6-e.payloadSize;Kn(a,e,t.payloadStart),n.push({id:e.id,format:e.format,payload:Fn.of(a,e.payloadSize)}),i=a}return n.toReversed()}var Wn=65536,Gn=class{source;trailerStart;chunkStart=0;chunk=/* @__PURE__ */ new Uint8Array;constructor(e,t){this.source=e,this.trailerStart=t}async bytesEndingAt(e,t){let n=e-t;if(n<this.trailerStart)throw new j(`invalid-trailer`,`a record header at ${n} lies before the trailer`);return n>=this.chunkStart&&e<=this.chunkStart+this.chunk.byteLength||await this.readChunkEndingAt(e),this.chunk.subarray(n-this.chunkStart,e-this.chunkStart)}async readChunkEndingAt(e){this.chunkStart=Math.max(this.trailerStart,e-Wn),this.chunk=await this.source.read(Fn.of(this.chunkStart,e-this.chunkStart))}};function Kn(e,t,n){if(e<n)throw new j(`invalid-trailer`,`record ${t.id} (${t.payloadSize} bytes) runs past the trailer start; records are not contiguous`)}var qn=class{footer;payloadStart;byId;constructor(e,t,n){this.footer=e,this.payloadStart=t,this.byId=new Map(n.map(e=>[e.id,e]))}get records(){return[...this.byId.values()]}locationOf(e){return this.byId.get(e)}},Jn=class e{trailerSize;version;constructor(e,t){this.trailerSize=e,this.version=t}static parse(t){if(t.byteLength!==72)throw new j(`invalid-trailer`,`footer must be 72 bytes, got ${t.byteLength}`);let n=new Qe(t);if(n.asciiAt(40,32)!==`8db42d694ccc418790edff439fe026bf`)throw new j(`invalid-trailer`,`file does not end with the Insta360 magic`);return new e(n.uint32LeAt(32),n.uint32LeAt(36))}},Yn=78;async function Xn(e,t){if(t<Yn)throw new j(`invalid-trailer`,`file of ${t} bytes is too small to hold a trailer`);let n=Zn(await e.read(Fn.lastOf(t,Yn)),t);return new qn(n.footer,n.payloadStart,await Bn(e,n))}function Zn(e,t){let n=new Qe(e),r=Jn.parse(n.bytesAt(6,72));if(r.trailerSize>t)throw new j(`invalid-trailer`,`trailer size ${r.trailerSize} exceeds file size ${t}`);return{fileSize:t,payloadStart:t-r.trailerSize,footer:r,lastHeader:Ln.parse(n.bytesAt(0,6))}}var Qn=class e{firstFrameCaptureTime;gyroOffset;firstFrameVideoTime;constructor(e,t=pt(0),n=R(0)){this.firstFrameCaptureTime=e,this.gyroOffset=t,this.firstFrameVideoTime=n}withFirstFrameAt(t){return new e(this.firstFrameCaptureTime,this.gyroOffset,t)}videoTimeOf(e){let t=ft(e-this.firstFrameCaptureTime);return R(this.firstFrameVideoTime+mt(t))}gyroVideoTimeOf(e){return R(this.videoTimeOf(e)-gt(this.gyroOffset))}captureTimeOf(e){let t=_t(R(e-this.firstFrameVideoTime));return ft(Math.round(this.firstFrameCaptureTime+t))}};async function $n(e){let t=await Xn(e,await e.size()),n=await kt(e,t),r=new In(e,t,n);return{info:n,calibration:Ie(n.calibration),listsExposureRecord:r.listsExposure,captureClock:async()=>{let e=await r.firstFrameCaptureTime();return e===void 0?void 0:new Qn(e,n.gyroOffset)},readGyroRecord:()=>r.readGyro(),readExposureRecord:()=>r.readExposure()}}var er={Insta360Trailer:`inst`},tr=/^[ -~]{4}$/u;function nr(e){return tr.test(e)}function rr(e){return e.some(e=>e.type===er.Insta360Trailer)?`inst-box`:`bare`}function ir(e,t){if(e.length<8)return;let n=e.asciiAt(4,4);if(!nr(n))return;let r=ar(e,t);return r!==void 0&&r.size>=r.headerSize&&r.size<=t?{type:n,...r}:void 0}function ar(e,t){let n=e.uint32BeAt(0);return n===1&&e.length>=16?or(e):{size:n===0?t:n,headerSize:8}}function or(e){try{return{size:e.uint64BeAt(8),headerSize:16}}catch(e){if(M(e,`binary-unsafe-integer`))return;throw e}}async function sr(e,t){let n=[],r=0;for(;r+8<=t;){let i=await cr(e,r,t);if(!i)break;n.push(i),r=i.range.end}return n}async function cr(e,t,n){let r=n-t,i=Math.min(16,r),a=ir(new Qe(await e.read(Fn.of(t,i))),r);return a&&{type:a.type,range:Fn.of(t,a.size)}}async function lr(e){let t=await e.size(),[n,r]=await Promise.all([sr(e,t),Xn(e,t)]);return{fileSize:t,boxes:n,trailerWrapper:rr(n),trailerVersion:r.footer.version,trailerPayloadStart:r.payloadStart,records:r.records.toSorted((e,t)=>e.id-t.id)}}var ur=1e3;async function dr(e){let[t,n]=await Promise.all([lr(e),$n(e)]),r=await gr(n),i=await _r(n,r);return{...fr(t),info:n.info,calibration:pr(n),calibrationWarnings:n.calibration.warnings,gyro:r,exposure:i}}function fr(e){return{fileSize:e.fileSize,boxes:e.boxes.map(e=>({type:e.type,offset:e.range.offset,size:e.range.length})),trailerWrapper:e.trailerWrapper,trailerVersion:e.trailerVersion,payloadStart:e.trailerPayloadStart,records:e.records.map(e=>({id:e.id,format:e.format,offset:e.payload.offset,size:e.payload.length}))}}function pr(e){let{calibration:t}=e.calibration;return t===void 0?void 0:{version:t.version,canvas:[t.canvas.width,t.canvas.height],lenses:t.lenses.map(e=>({lensIndex:e.lensIndex,model:e.model.kind,principalPoint:[e.model.principalPoint.x,e.model.principalPoint.y],orientationDegrees:[e.orientation.yaw,e.orientation.pitch,e.orientation.roll],translationMetres:e.translation}))}}function mr(e){let{track:t,layout:n,strayBytes:r,damagedSamples:i,mendedStamps:a}=e,o=Math.min(ur,t.length),s=0;for(let e=0;e<o;e+=1)s+=Wt(t.sampleAt(e).acceleration);let c=t.isEmpty?0:t.sampleAt(t.length-1).captureTime-t.sampleAt(0).captureTime;return{layout:n,samples:t.length,strayBytes:r,damagedSamples:i,mendedStamps:a,spanSeconds:mt(ft(c)),meanIntervalUs:t.meanSampleInterval,meanAccelerationMagnitudeG:o>0?s/o:void 0}}function hr(e,t){let n=0;for(let t=0;t<e.length;t+=1)n+=e.entryAt(t).shutterTime;let r=e.length>0;return{entries:e.length,firstCaptureTimeUs:r?e.entryAt(0).captureTime:void 0,lastCaptureTimeUs:r?e.entryAt(e.length-1).captureTime:void 0,meanShutterTimeSeconds:r?n/e.length:void 0,firstEncodedFrameEntry:t}}async function gr(e){try{let t=await e.readGyroRecord();return t===void 0?void 0:mr(t)}catch(e){if(!M(e,`unsupported-gyro-record`))throw e;return{unreadable:ie(e)}}}async function _r(e,t){if(!e.listsExposureRecord)return;if(t!==void 0&&`unreadable`in t)return{unread:`gyro layout unknown`};let n=await e.readExposureRecord();return n?hr(n,await vr(n,e)):{damaged:!0}}async function vr(e,t){let n=await t.captureClock();return n===void 0?void 0:e.indexAtOrAfter(n.firstFrameCaptureTime)}function yr(e,t,n){return Math.min(Math.max(e,t),n)}var br=.01,xr=class e{clock;captureTimes;shutterTimes;frameDuration;constructor(e){N(e.shutterTimes===void 0||e.shutterTimes.length===e.captureTimes.length,`frame time arrays disagree on the frame count`),this.clock=e.clock,this.captureTimes=e.captureTimes,this.shutterTimes=e.shutterTimes,this.frameDuration=e.frameDuration}static withoutShutterTimes(t){return new e({...t,shutterTimes:void 0})}get frameCount(){return this.captureTimes.length}frameAt(e){ae(e,this.frameCount,`frame`);let t=ft(this.captureTimes[e]??0),n=this.shutterTimes?.[e],r=n===void 0?void 0:R(n),i=this.clock.videoTimeOf(t);return{index:e,captureTime:t,videoTime:i,shutterTime:r,midExposureVideoTime:R(i+(r??0)/2)}}midExposureAt(e){let t=this.frameIndexAt(e);return t===void 0?void 0:this.frameAt(t).midExposureVideoTime}frameIndexAt(e){return this.frameCount===0?void 0:yr(this.frameDuration===void 0?this.lastCapturedAt(e):this.onFrameGrid(e,this.frameDuration),0,this.frameCount-1)}onFrameGrid(e,t){let n=(e-this.clock.firstFrameVideoTime)/t;return Math.floor(n+br)}lastCapturedAt(e){let t=this.clock.captureTimeOf(e),n=0,r=this.frameCount-1;for(;n<r;){let e=Math.ceil((n+r)/2);(this.captureTimes[e]??1/0)<=t?n=e:r=e-1}return n}};function Sr(e){let{exposureRecord:t,clock:n,frameCount:r}=e;if(!t)return;let i=t.indexAtOrAfter(n.firstFrameCaptureTime);if(t.length-i<r)return;let a=t.slice(i,r);return new xr({clock:n,captureTimes:Float64Array.from(a.captureTimes),shutterTimes:Float64Array.from(a.shutterTimes),frameDuration:e.frameDuration})}function Cr(e){let{trackTimestamps:t,clock:n,frameCount:r}=e;if(!t||t.length<r)return;let i=Float64Array.from(t.slice(0,r),e=>n.captureTimeOf(e));return xr.withoutShutterTimes({clock:n,captureTimes:i,frameDuration:e.frameDuration})}function wr(e){let{frameRate:t,clock:n,frameCount:r}=e;if(t===void 0||t<=0)return;let i=Float64Array.from({length:r},(e,r)=>n.captureTimeOf(R(n.firstFrameVideoTime+r/t)));return xr.withoutShutterTimes({clock:n,captureTimes:i,frameDuration:e.frameDuration})}var Tr={"exposure-record":Sr,"track-timestamps":Cr,nominal:wr},Er=[`exposure-record`,`track-timestamps`,`nominal`],Dr=[`track-timestamps`,`exposure-record`,`nominal`];function Or(e,t){let n=[];for(let r of Ar(t)){let t=Tr[r](e);if(t)return{frameTimes:t,source:r,warnings:n};n.push(`${r} unavailable`)}}function kr(e,t){let n=[];for(let r of Ar(t)){if(r===`track-timestamps`)return{needsTrackTimestamps:!0,resolveWith:n=>Or({...e,trackTimestamps:n},t)};let i=Tr[r]({...e,trackTimestamps:void 0});if(i)return{needsTrackTimestamps:!1,resolved:{frameTimes:i,source:r,warnings:n}};n.push(`${r} unavailable`)}return{needsTrackTimestamps:!1,resolved:void 0}}function Ar(e){return e===`track-timestamps`?Dr:Er}async function jr(e,t,n){let{info:r}=e,[i,a]=await Promise.all([t.frameCount(),e.readExposureRecord()]),o=kr({...n,frameCount:i,frameRate:r.frameRate,exposureRecord:a},r.preferredFrameTimeSource);return o.needsTrackTimestamps?o.resolveWith(await t.sampleTimestamps()):o.resolved}var Mr=[1,0,0,0,1,0,0,0,1];function Nr(e){let t=Math.cos(e),n=Math.sin(e);return[1,0,0,0,t,-n,0,n,t]}function Pr(e){let t=Math.cos(e),n=Math.sin(e);return[t,0,n,0,1,0,-n,0,t]}function Fr(e){let t=Math.cos(e),n=Math.sin(e);return[t,-n,0,n,t,0,0,0,1]}function Ir(e,t){let[n,r,i,a,o,s,c,l,u]=e,[d,f,p,m,h,g,_,v,y]=t;return[n*d+r*m+i*_,n*f+r*h+i*v,n*p+r*g+i*y,a*d+o*m+s*_,a*f+o*h+s*v,a*p+o*g+s*y,c*d+l*m+u*_,c*f+l*h+u*v,c*p+l*g+u*y]}function Lr(e,t){let[n,r,i,a,o,s,c,l,u]=e,[d,f,p]=t;return[n*d+r*f+i*p,a*d+o*f+s*p,c*d+l*f+u*p]}function Rr(e){let[t,n,r,i,a,o,s,c,l]=e;return t*(a*l-o*c)-n*(i*l-o*s)+r*(i*c-a*s)}var zr=/* @__PURE__ */ new Map([[`x`,[1,0,0]],[`y`,[0,1,0]],[`z`,[0,0,1]],[`-x`,[-1,0,0]],[`-y`,[0,-1,0]],[`-z`,[0,0,-1]]]);function Br(e){let t=zr.get(e);return N(t!==void 0,`unknown IMU axis ${e}`),t}function Vr(e){let[t,n,r]=e.map(e=>Br(e));return[...t,...n,...r]}function Hr(e){return Rr(Vr(e))===1}function Ur(e,t){return{...Gr(e,t),isVerified:!0}}function Wr(e,t){return{...Gr(e,t),isVerified:!1}}function Gr(e,t){return N(Hr(t),`IMU axes ${t.join(`, `)} are not a rotation`),{name:e,toBody:Vr(t)}}function Kr(e,t){return Lr(e.toBody,t)}var qr=[`x`,`z`,`-y`],Jr=Ur(`X5`,qr),Yr=Ur(`X6`,qr),Xr=Ur(`X4 Air`,qr),Zr=Wr(`aligned (unverified)`,[`x`,`y`,`z`]),Qr=/* @__PURE__ */ new Map([[`Insta360 X4 Air`,Xr],[`Insta360 X5`,Jr],[`Insta360 X6`,Yr]]);function $r(e){return Qr.get(e.model?.trim()??``)??Zr}var ei=.02,ti=_t(R(1));function ni(e,t,n){let r=mt(e.meanSampleInterval??ti),i=Math.max(1,Math.min(e.length,Math.round(n/r))),a=ri(e,t),o=0;for(let e=0;e<i;e+=1)o+=a[e]??0;let s={start:0,sum:o};for(let t=1;t+i<=e.length;t+=1)o+=(a[t+i-1]??0)-(a[t-1]??0),o<s.sum&&(s={start:t,sum:o});return{start:s.start,end:s.start+i}}function ri(e,t){let n=new Float64Array(e.length);for(let r=0;r<e.length;r+=1)n[r]=Wt(Kr(t,e.angularVelocityAt(r)));return n}function ii({gyro:e,frame:t},n,r){let i=Ut;for(let a=n.start;a<n.end;a+=1){let n=r(e.sampleAt(a));i=Jt(i,Kr(t,n))}return Xt(i,1/Math.max(n.end-n.start,1))}function ai(e,t,n){let r=ii({gyro:e,frame:t},n,e=>e.angularVelocity);return Wt(r)<=ei?r:Ut}var oi=[0,0,0,1],si=1e-12,ci=.9995;function li(e,t){let n=Wt(e);if(n===0)return oi;let r=t/2,i=Math.sin(r)/n;return[e[0]*i,e[1]*i,e[2]*i,Math.cos(r)]}function ui(e){let t=Wt(e);return t<si?oi:li(e,n(t))}function di(e,t){let[n,r,i,a]=e,[o,s,c,l]=t;return[a*o+n*l+r*c-i*s,a*s-n*c+r*l+i*o,a*c+n*s-r*o+i*l,a*l-n*o-r*s-i*c]}function fi(e){let[t,n,r,i]=e;return[-t,-n,-r,i]}function pi(e){let[t,n,r,i]=e,a=Math.sqrt(t*t+n*n+r*r+i*i);return a===0?oi:[t/a,n/a,r/a,i/a]}function mi(e,t){let[n,r,i,a]=e,[o,s,c]=t,l=2*(r*c-i*s),u=2*(i*o-n*c),d=2*(n*s-r*o);return[o+a*l+(r*d-i*u),s+a*u+(i*l-n*d),c+a*d+(n*u-r*l)]}function hi(e,t,n){let[r,i,a,o]=e,[s,c,l,u]=t,d=r*s+i*c+a*l+o*u;if(d<0&&(d=-d,[s,c,l,u]=[-s,-c,-l,-u]),d>ci)return pi([r+(s-r)*n,i+(c-i)*n,a+(l-a)*n,o+(u-o)*n]);let f=Math.acos(d),p=Math.sin(f),m=Math.sin((1-n)*f)/p,h=Math.sin(n*f)/p;return[r*m+s*h,i*m+c*h,a*m+l*h,o*m+u*h]}function gi(e){let[t,n,r,i]=e;return[1-2*(n*n+r*r),2*(t*n-r*i),2*(t*r+n*i),2*(t*n+r*i),1-2*(t*t+r*r),2*(n*r-t*i),2*(t*r-n*i),2*(n*r+t*i),1-2*(t*t+n*n)]}var _i=[0,1,0],vi=.9,yi=1.1;function bi(e){let t=Wt(e);return t>=vi&&t<=yi?Xt(e,-1/t):void 0}function xi(e,t){let n=bi(t);return n?Kt(n,mi(fi(e),_i)):[0,0,0]}function Si(e,t){if(e.isEmpty)return{start:0,end:0};let n=e.sampleAt(0).captureTime,r=_t(t),i=1;for(;i<e.length&&e.sampleAt(i).captureTime-n<=r;)i+=1;return{start:0,end:i}}function Ci(e,t,n){if(e.isEmpty)return oi;let r=Si(e,n),i=bi(ii({gyro:e,frame:t},r,e=>e.acceleration));return i?wi(i,_i):oi}function wi(e,t){let r=Kt(e,t),i=Gt(e,t),a=Wt(r);return a>0?li(r,n(Math.atan2(a,i))):i>0?oi:li(Ti(e),n(Math.PI))}function Ti(e){return Math.abs(e[0])<Math.abs(e[2])?[0,-e[2],e[1]]:[-e[1],e[0],0]}var Ei=.2,Di=.5,Oi=.5,ki=4,Ai=.05,ji=class e{videoTimes;quaternions;constructor(e,t){this.videoTimes=e,this.quaternions=t,N(t.length===e.length*ki,`orientation track arrays disagree on the sample count`)}static integrate(t){let{gyro:n,clock:r,frame:i}=t,a=new Float64Array(n.length),o=new Float32Array(n.length*ki);if(n.isEmpty)return new e(a,o);let s={frame:i,bias:ai(n,i,ni(n,i,R(Di))),gravityGain:t.options?.gravityGain??Ei};a.set(Mi(n,r));let c={orientation:Ci(n,i,R(Oi)),time:R(a[0]??0),rate:Ut};for(let e=0;e<n.length;e+=1){let t=R(a[e]??c.time);c=Pi(c,{sample:Ni(n,e),time:t},s),o.set(c.orientation,e*ki)}return new e(a,o)}get length(){return this.videoTimes.length}orientationAt(e){if(this.length===0)return oi;let t=this.firstIndexAfter(e);if(t===0)return this.quaternionAt(0);if(t>=this.length)return this.quaternionAt(this.length-1);let n=t-1,r=(this.videoTimes[t]??0)-(this.videoTimes[n]??0),i=r>0?(e-(this.videoTimes[n]??0))/r:0;return hi(this.quaternionAt(n),this.quaternionAt(t),i)}quaternionAt(e){let t=e*ki,[n=0,r=0,i=0,a=1]=this.quaternions.subarray(t,t+ki);return[n,r,i,a]}firstIndexAfter(e){let t=0,n=this.length;for(;t<n;){let r=Math.floor((t+n)/2);(this.videoTimes[r]??1/0)<=e?t=r+1:n=r}return t}};function Mi(e,t){return e.captureTimes.map(e=>t.gyroVideoTimeOf(ft(e)))}function Ni(e,t){let n=e.sampleAt(t);return N(qt(n.acceleration)&&qt(n.angularVelocity),`gyro sample ${t} is not finite`),n}function Pi(e,{sample:t,time:n},r){let{frame:i,bias:a,gravityGain:o}=r,s=yr(n-e.time,0,Ai),c=xi(e.orientation,Kr(i,t.acceleration));return{orientation:Ii(e.orientation,Fi(e.rate,c,o),s),time:n,rate:Yt(Kr(i,t.angularVelocity),a)}}function Fi(e,t,n){return Jt(e,Xt(t,n))}function Ii(e,t,n){return pi(di(e,ui(Xt(t,n))))}var Li=`the recording has no gyro record; stabilization is unavailable`;async function Ri(e,t){let n=await e.readGyroRecord();if(!n)return{setup:void 0,warnings:[Li]};let r=$r(e.info),i=ji.integrate({gyro:n.track,clock:t,frame:r}),a=[...Bi(r,e),...zi(n)];return{setup:{orientations:i,imuFrame:r},warnings:a}}function zi(e){return[...e.damagedSamples>0?[`damaged gyro samples left out of stabilization: ${e.damagedSamples}`]:[],...e.mendedStamps>0?[`gyro stamps off their neighbours mended: ${e.mendedStamps}`]:[]]}function Bi(e,t){return e.isVerified?[]:[`the IMU frame of ${t.info.model??`this camera`} has not been verified on a recording; stabilization may misbehave`]}var Vi=`frame timing and stabilization are unavailable`,Hi=`the recording has no capture clock; ${Vi}`,Ui=`the recording has no frame source to time; ${Vi}`,Wi=`no frame timing source is usable; frames are timed by their track timestamps`;async function Gi(e,t){try{return await Ki(e,t)}catch(e){if(!M(e,`unsupported-gyro-record`))throw e;return Ji([`${ie(e)}; ${Vi}`])}}async function Ki(e,t){let n=await e.captureClock();if(!n)return Ji([Hi]);if(!t)return Ji([Ui]);let r=await qi(n,t),[i,a]=await Promise.all([jr(e,t,r),Ri(e,r.clock)]);return{frameTimes:i?.frameTimes,frameTimeSource:i?.source,motion:a.setup,warnings:[...i?.warnings??[Wi],...a.warnings]}}async function qi(e,t){let n=await t.firstKeyframe(),r=n!==void 0&&n.duration>0;return{clock:e.withFirstFrameAt(n?.timestamp??R(0)),frameDuration:r?n.duration:void 0}}function Ji(e){return{frameTimes:void 0,frameTimeSource:void 0,motion:void 0,warnings:e}}var Yi=/^(?<prefix>[A-Za-z]+(?:_[A-Za-z]+)*)_(?<stamp>\d{8}_\d{6})_(?<lens>\d)(?<proxy>\d)_(?<sequence>\d{3})\.(?<extension>[A-Za-z0-9]+)$/u,Xi=0,Zi=1,Qi=0,$i=1,ea=class e{parts;constructor(e){this.parts=e}static parse(t){let n=Yi.exec(t)?.groups;return n?new e(ta(n)):void 0}get isBackLens(){return this.parts.lensDigit===Xi}get isScreenLens(){return this.parts.lensDigit===Zi}get isProxy(){return this.parts.proxyDigit===$i}otherLensName(){let t=this.isBackLens?Zi:Xi;return new e({...this.parts,lensDigit:t,proxyDigit:Qi}).toString()}toString(){let{prefix:e,captureStamp:t,lensDigit:n,proxyDigit:r,sequence:i,extension:a}=this.parts;return`${e}_${t}_${n}${r}_${i}.${a}`}};function ta(e){return{prefix:e.prefix??``,captureStamp:e.stamp??``,lensDigit:Number(e.lens),proxyDigit:Number(e.proxy),sequence:e.sequence??``,extension:e.extension??``}}var na=/[#?]/u;function ra(e){let t=e.search(na);return t===-1?{path:e,suffix:``}:{path:e.slice(0,t),suffix:e.slice(t)}}function ia(e){let{path:t}=ra(e),n=t.slice(t.lastIndexOf(`/`)+1);try{return decodeURIComponent(n)}catch{return n}}async function aa(e,t){let n=ea.parse(ia(e));if(!n)return;let r=oa(e,n.otherLensName());return await t.exists(r)?r:void 0}function oa(e,t){let{path:n,suffix:r}=ra(e);return`${n.slice(0,n.lastIndexOf(`/`)+1)}${encodeURIComponent(t)}${r}`}var sa={FileType:`ftyp`,MediaData:`mdat`,Movie:`moov`,MovieHeader:`mvhd`,MovieExtends:`mvex`,Track:`trak`,TrackHeader:`tkhd`,Edit:`edts`,EditList:`elst`,Media:`mdia`,MediaHeader:`mdhd`,Handler:`hdlr`,MediaInformation:`minf`,SampleTable:`stbl`,SampleDescription:`stsd`,TimeToSample:`stts`,CompositionOffset:`ctts`,SyncSample:`stss`,SampleToChunk:`stsc`,SampleSize:`stsz`,ChunkOffset:`stco`,ChunkLargeOffset:`co64`,AvcConfiguration:`avcC`,HevcConfiguration:`hvcC`},ca={Video:`vide`,Sound:`soun`},la=[`avc1`,`avc3`],ua=[`hvc1`,`hev1`],da={isKeyframe:()=>!0},fa=31,pa=1,ma=4,ha=5,ga=1,_a=63,va=16,ya=23,ba={typeOf:e=>e&fa,verdictOn:e=>e===ha?`keyframe`:e>=pa&&e<=ma?`not-a-keyframe`:`read-on`},xa={typeOf:e=>e>>ga&_a,verdictOn:e=>e<va?`not-a-keyframe`:e<=ya?`keyframe`:`read-on`},Sa=8,Ca=class{family;lengthSize;constructor(e,t){this.family=e,this.lengthSize=t}isKeyframe(e){let t=0;for(;t+this.lengthSize<e.length;){let n=t+this.lengthSize,r=n+wa(e,t,this.lengthSize);if(r>e.length)return!1;let i=this.family.verdictOn(this.family.typeOf(e[n]??0));if(i!==`read-on`)return i===`keyframe`;t=r}return!1}};function wa(e,t,n){let r=0;for(let i=0;i<n;i+=1)r=r*2**Sa+(e[t+i]??0);return r}var Ta=[[la,ba],[ua,xa]];function Ea(e){let{sampleEntryType:t,nalLengthSize:n}=e,[,r]=Ta.find(([e])=>e.includes(t))??[];return r&&n!==void 0?new Ca(r,n):da}function Da(e){let t=[],n=0;for(;e.byteLength-n>=8;){let r=e.byteLength-n,i=ir(new Qe(e.subarray(n,n+16)),r);if(!i)throw ja(`holds no box at byte ${n} of ${e.byteLength}`);let a=e.subarray(n+i.headerSize,n+i.size);t.push({type:i.type,body:a}),n+=i.size}return t}function Oa(e,t){let n=ka(e,t);if(!n)throw ja(`has no ${t} box where one belongs`);return n}function ka(e,t){return e.find(e=>e.type===t)}function Aa(e){if(e.body.byteLength<4)throw ja(`has a ${e.type} box too short for its version and flags`);return{version:e.body[0]??0,content:new Qe(e.body.subarray(4))}}function ja(e){return new j(`unsupported-container`,`the movie box ${e}`)}var Ma={0:{timescale:8,duration:{offset:12,kind:`uint32`},size:96},1:{timescale:16,duration:{offset:20,kind:`uint64`},size:108}},Na={0:8,1:16},Pa={0:{timescale:8,duration:{offset:12,kind:`uint32`},size:20},1:{timescale:16,duration:{offset:20,kind:`uint64`},size:32}},Fa={entrySize:8,fields:{sampleCount:{offset:0,kind:`uint32`},sampleDelta:{offset:4,kind:`uint32`}}},Ia={entrySize:8,fields:{sampleCount:{offset:0,kind:`uint32`},sampleOffset:{offset:4,kind:`int32`}}},La={entrySize:4,fields:{sampleNumber:{offset:0,kind:`uint32`}}},Ra={0:{entrySize:12,fields:{segmentDuration:{offset:0,kind:`uint32`},mediaTime:{offset:4,kind:`int32`},mediaRate:{offset:8,kind:`uint32`}}},1:{entrySize:20,fields:{segmentDuration:{offset:0,kind:`uint64`},mediaTime:{offset:8,kind:`int64`},mediaRate:{offset:16,kind:`uint32`}}}},za={entrySize:12,fields:{firstChunk:{offset:0,kind:`uint32`},samplesPerChunk:{offset:4,kind:`uint32`},sampleDescriptionIndex:{offset:8,kind:`uint32`}}},Ba={entrySize:4,fields:{chunkOffset:{offset:0,kind:`uint32`}}},Va={entrySize:8,fields:{chunkOffset:{offset:0,kind:`uint64`}}},Ha={uint32:(e,t)=>e.uint32BeAt(t),uint64:(e,t)=>e.uint64BeAt(t),int32:(e,t)=>e.int32BeAt(t),int64:(e,t)=>e.int64BeAt(t)};function Ua(e,t,n=0){return Ha[t.kind](e,n+t.offset)}function Wa(e,t){let n=e.uint32BeAt(0);if(4+n*t.entrySize>e.length)throw ja(`has a table of ${n} entries that do not fit in its box`);let r=Object.keys(t.fields),i={};for(let a of r)i[a]=Array.from({length:n},(n,r)=>Ua(e,t.fields[a],4+r*t.entrySize));return i}var Ga=1;function Ka(e){let t=qa(Oa(e,sa.SampleSize)),n=Ja(e),r=Aa(Oa(e,sa.SampleToChunk)).content;return{offsets:Xa({sizes:t,chunkOffsets:n,perChunk:Ya(Wa(r,za),n.length)}),sizes:t}}function qa(e){let{content:t}=Aa(e),n=t.uint32BeAt(0),r=t.uint32BeAt(4);if(n!==0)return new Float64Array(r).fill(n);if(8+r*4>t.length)throw ja(`lists ${r} sample sizes that do not fit in its box`);return Float64Array.from({length:r},(e,n)=>t.uint32BeAt(8+n*4))}function Ja(e){let t=ka(e,sa.ChunkLargeOffset),n=t??ka(e,sa.ChunkOffset);if(!n)throw ja(`has a sample table without chunk offsets`);let r=t?Va:Ba;return Wa(Aa(n).content,r).chunkOffset}function Ya(e,t){let n=Array.from({length:t},()=>0);for(let[r,i]of e.firstChunk.entries()){let a=e.firstChunk[r+1]??t+Ga,o=e.samplesPerChunk[r]??0;n.fill(o,i-Ga,a-Ga)}return n}function Xa(e){let t=new Float64Array(e.sizes.length),n=0;for(let[r,i]of e.chunkOffsets.entries()){let a=i,o=Math.min(n+(e.perChunk[r]??0),t.length);for(;n<o;n+=1)t[n]=a,a+=e.sizes[n]??0}if(n<t.length)throw ja(`has chunks for ${n} of its ${t.length} samples`);return t}var Za=4,Qa=/* @__PURE__ */ new Map([[sa.AvcConfiguration,4],[sa.HevcConfiguration,21]]);function $a(e){let t=Aa(Oa(e,sa.MovieHeader));return t.content.uint32BeAt(no(t,Ma,sa.MovieHeader).timescale)}function eo(e){let t=Da(e.body),n=Da(Oa(t,sa.Media).body);return{track:t,media:n,sampleTable:Da(Oa(Da(Oa(n,sa.MediaInformation).body),sa.SampleTable).body)}}function to(e){let t=ao(e.media),n=oo(e.sampleTable);return{trackId:ro(e.track),handlerType:t,mediaTimescale:io(e.media),sampleEntryType:n.type,nalLengthSize:t===ca.Video?so(n):void 0}}function no(e,t,n){let r=e.version===0||e.version===1?t[e.version]:void 0;if(r===void 0)throw ja(`has a ${n} box of version ${e.version}`);return r}function ro(e){let t=Aa(Oa(e,sa.TrackHeader));return t.content.uint32BeAt(no(t,Na,sa.TrackHeader))}function io(e){let t=Aa(Oa(e,sa.MediaHeader));return t.content.uint32BeAt(no(t,Pa,sa.MediaHeader).timescale)}function ao(e){let{content:t}=Aa(Oa(e,sa.Handler));return t.asciiAt(4,Za)}function oo(e){let{content:t}=Aa(Oa(e,sa.SampleDescription)),n=t.length-4,[r]=Da(t.bytesAt(4,n));if(!r)throw ja(`has a track without a sample entry`);return r}function so(e){let t=Da(e.body.subarray(78)).find(e=>Qa.has(e.type)),n=t?.body[Qa.get(t.type)??0];return n===void 0?void 0:(n&3)+1}function co(e){return Array.from({length:e.length},(e,t)=>t).toSorted((t,n)=>(e[t]??0)-(e[n]??0))}function lo(e,t){let n=uo(Oa(e.sampleTable,sa.TimeToSample),t),r=fo(e.sampleTable,t.sampleCount),i=r?n.times.map((e,t)=>e+(r[t]??0)):n.times,a=mo(e.track,t),o=i.map(e=>(e-a)/t.media),s=(r?ho(i,n.deltas):n.deltas).map(e=>e/t.media);return{timestamps:o,durations:s,end:go(o,s,t.media)}}function uo(e,t){let n=Wa(Aa(e).content,Fa),r=po(n.sampleCount,n.sampleDelta);if(r.length!==t.sampleCount)throw ja(`times ${r.length} samples of a track that has ${t.sampleCount}`);let i=new Float64Array(r.length);for(let e=1;e<r.length;e+=1)i[e]=(i[e-1]??0)+(r[e-1]??0);return{times:i,deltas:r}}function fo(e,t){let n=ka(e,sa.CompositionOffset);if(!n)return;let r=Wa(Aa(n).content,Ia),i=new Float64Array(t);return i.set(po(r.sampleCount,r.sampleOffset).subarray(0,t)),i}function po(e,t){let n=e.reduce((e,t)=>e+t,0),r=new Float64Array(n),i=0;for(let[n,a]of e.entries())r.fill(t[n]??0,i,i+a),i+=a;return r}function mo(e,t){let n=ka(e,sa.Edit),r=n&&ka(Da(n.body),sa.EditList);if(!r)return 0;let i=Aa(r),a=Wa(i.content,no(i,Ra,sa.EditList)),o=0;for(let[e,n]of a.mediaTime.entries()){if(n===-1){o+=a.segmentDuration[e]??0;continue}return a.mediaRate[e]===65536?n-Math.round(o/t.movie*t.media):0}return 0}function ho(e,t){let n=co(e),r=Float64Array.from(t);for(let t=0;t<n.length-1;t+=1){let i=n[t]??0;r[i]=(e[n[t+1]??0]??0)-(e[i]??0)}return r}function go(e,t,n){let r=co(e).at(-1);if(r===void 0)return R(0);let i=(e[r]??0)+(t[r]??0);return R(Math.round(i*n)/n)}var _o=class{tracks;constructor(e){this.tracks=e}get videoTracks(){return this.tracks.filter(e=>e.kind===`video`)}get audioTracks(){return this.tracks.filter(e=>e.kind===`audio`)}get duration(){return R(Math.max(0,...this.tracks.map(e=>e.end)))}trackWithId(e){return this.tracks.find(t=>t.trackId===e)}};function vo(e,t,n){let r=0,i=e;for(;r<i;){let e=r+i>>>1;t(e)<=n?r=e+1:i=e}return r}var yo=class{parts;trackId;kind;end;keyframeRule;presentationOrder;constructor(e){this.parts=e;let{length:t}=e.offsets;N([e.sizes,e.timestamps,e.durations].every(e=>e.length===t),`the sample table of track ${e.trackId} disagrees on its sample count`),N(bo(e.syncSamples??[],t),`the sync samples of track ${e.trackId} are not samples of it in order`),this.trackId=e.trackId,this.kind=e.kind,this.end=e.end,this.keyframeRule=e.keyframeRule,this.presentationOrder=co(e.timestamps)}get sampleCount(){return this.parts.offsets.length}rangeOf(e){return this.ensureSample(e),Fn.of(this.parts.offsets[e]??0,this.parts.sizes[e]??0)}timestampOf(e){return this.ensureSample(e),R(this.parts.timestamps[e]??0)}durationOf(e){return this.ensureSample(e),R(this.parts.durations[e]??0)}isSync(e){return this.ensureSample(e),this.syncSampleAtOrBefore(e)===e}sampleShownAt(e){let t=vo(this.presentationOrder.length,e=>this.parts.timestamps[this.presentationOrder[e]??0]??1/0,e);return this.presentationOrder[t-1]}keyframeAt(e){let t=this.sampleShownAt(e);return t===void 0?void 0:this.syncSampleAtOrBefore(t)}syncSampleAtOrBefore(e){let{syncSamples:t}=this.parts;return t?t[vo(t.length,e=>t[e]??0,e)-1]:e>=0?e:void 0}syncSampleAtOrAfter(e){let{syncSamples:t}=this.parts,n=Math.max(0,e);return t?t[vo(t.length,e=>t[e]??0,n-1)]:n<this.sampleCount?n:void 0}timestampsInPresentationOrder(){return this.presentationOrder.map(e=>R(this.parts.timestamps[e]??0))}ensureSample(e){ae(e,this.sampleCount,`sample of track ${this.trackId}`)}};function bo(e,t){return e.every((n,r)=>Number.isSafeInteger(n)&&n>=0&&n<t&&n>(e[r-1]??-1))}var xo={[ca.Video]:`video`,[ca.Sound]:`audio`},So=1;function Co(e){let[t]=Da(e);if(t?.type!==sa.Movie)throw ja(`is not where the file says it is`);let n=Da(t.body);if(ka(n,sa.MovieExtends))throw ja(`is fragmented: its samples are described in movie fragments after it`);let r=$a(n);return new _o(n.filter(e=>e.type===sa.Track).flatMap(e=>wo(eo(e),r)))}function wo(e,t){let n=to(e),r=xo[n.handlerType];if(!r)return[];let i=Ka(e.sampleTable),a=lo(e,{media:n.mediaTimescale,movie:t,sampleCount:i.sizes.length});return[new yo({trackId:n.trackId,kind:r,...i,...a,syncSamples:To(e.sampleTable),keyframeRule:Ea(n)})]}function To(e){let t=ka(e,sa.SyncSample);if(!t)return;let{sampleNumber:n}=Wa(Aa(t).content,La);return n.map(e=>e-So)}function Eo(e){let t=new Uint8Array(e.reduce((e,t)=>e+t.byteLength,0)),n=0;for(let r of e)t.set(r,n),n+=r.byteLength;return t}async function Do(e){let t=await sr(e,await e.size()),n=t.find(e=>e.type===sa.Movie);if(!n)throw new j(`unsupported-container`,`the file has no movie box to read its samples from`);let r=t.find(e=>e.type===sa.FileType),[i,a]=await Promise.all([Oo(e,r),Oo(e,n)]);return{table:Co(a),movieBytes:Eo([i,a])}}function Oo(e,t){return t?e.read(t.range):Promise.resolve(/* @__PURE__ */ new Uint8Array)}var ko={x:0,y:0,width:1,height:1},Ao={x:0,y:0,width:.5,height:1},jo={x:.5,y:0,width:.5,height:1},Mo=2,No=2,Po=.02,Fo=0,Io=1,Lo=2;function Ro(e,t){let n=e.flatMap((e,t)=>e.videoTracks.map(({description:n})=>({input:e,inputIndex:t,track:n})));if(e.length===1&&Uo(n))return zo(n,t);if(e.length===Mo&&Wo(e,n))return Bo(e,n);let[r]=n;if(r&&n.length===1&&Ko(r.track))return Vo(r);throw Jo(e,n)}function zo(e,t){let n=t.trackOrder===`stream-10-first`,r=n?e.toReversed():e,i=t.fileLayout===void 0?[]:[`info record file layout ${t.fileLayout}`],a=t.trackOrder===void 0?`no track order hint: lens 0 assumed to be track 0`:`info record track order ${t.trackOrder}: lens 0 is track ${+!!n}`;return{kind:`multi-track`,sources:r.map((e,t)=>Ho(e,t)),evidence:[`one input with two video tracks`,...i,a]}}function Bo(e,t){let n=t.toSorted((e,t)=>qo(e.input)-qo(t.input)),r=e.map(e=>e.name??`?`).join(`, `);return{kind:`split-files`,sources:n.map((e,t)=>Ho(e,t)),evidence:[`two inputs with one video track each (${r})`,`lens 0 taken from the _00_ file when named`]}}function Vo(e){let{inputIndex:t,track:n}=e;return{kind:`packed`,sources:[{lensIndex:0,inputIndex:t,trackIndex:n.trackIndex,region:Ao},{lensIndex:1,inputIndex:t,trackIndex:n.trackIndex,region:jo}],evidence:[`single ${n.codedWidth}x${n.codedHeight} track with a 2:1 aspect ratio`]}}function Ho(e,t){return{lensIndex:t,inputIndex:e.inputIndex,trackIndex:e.track.trackIndex,region:ko}}function Uo(e){let[t,n]=e;return e.length===Mo&&t!==void 0&&n!==void 0&&Go(t.track)&&t.track.codedWidth===n.track.codedWidth&&t.track.codedHeight===n.track.codedHeight}function Wo(e,t){return t.length===Mo&&e.every(e=>e.videoTracks.length===1)&&t.every(e=>Go(e.track))}function Go(e){return e.codedWidth===e.codedHeight}function Ko(e){return Math.abs(e.codedWidth/e.codedHeight-No)<=Po}function qo(e){let t=ea.parse(e.name??``);return t?.isBackLens?Fo:t?.isScreenLens?Lo:Io}function Jo(e,t){let[n]=t;if(e.length===1&&t.length===1&&n!==void 0&&Go(n.track))return Yo(n.input);let r=t.map(e=>`${e.track.codedWidth}x${e.track.codedHeight}`).join(`, `);return new j(`unsupported-layout`,`cannot map ${t.length} video track(s) [${r}] in ${e.length} file(s) onto two lenses`)}function Yo(e){let t=ea.parse(e.name??``);return new j(`missing-second-file`,`this recording stores one lens per file; provide ${t?`the matching ${t.otherLensName()}`:`the other lens's file`} as the second source`)}var Xo=[`off`,`lock`,`horizon`,`follow`],Zo=`lock`,Qo=class{nextRotation(){return Mr}},$o=class{nextRotation(e){return gi(fi(e))}},es=class{nextRotation(e){let t=li(_i,as(e));return Ir(gi(fi(e)),gi(t))}},ts={timeConstant:R(1.5),maxContinuousGap:R(1)},ns=class{options;smoothed;previousTime;constructor(e=ts){this.options=e}nextRotation(e,t){return this.smoothed=this.follow(e,t),this.previousTime=t,Ir(gi(fi(e)),gi(this.smoothed))}follow(e,t){let n=this.previousTime===void 0?1/0:t-this.previousTime;if(!this.smoothed||Math.abs(n)>this.options.maxContinuousGap)return e;if(n<=0)return this.smoothed;let r=1-Math.exp(-n/this.options.timeConstant);return hi(this.smoothed,e,r)}},rs={off:()=>new Qo,lock:()=>new $o,horizon:()=>new es,follow:()=>new ns};function is(e){return rs[e]()}function as(e){let[,t,,r]=e;return n(2*Math.atan2(t,r))}function os(e){return t(2*(Math.round(e/o)*o)-e)}function ss(e){let{yaw:n,pitch:r,roll:i}=e.orientation,a=Pr(l(n)),o=Ir(Nr(l(r)),a),c=Ir(Nr(l(t(s*e.lensIndex))),o);return Ir(Fr(l(os(i))),c)}var cs=1.5,ls=.01,us=[1,1,1],ds={maxGain:2,timeConstant:R(cs)};function fs(e,t){let[n]=e;return n?e.map((e,r)=>r===0?us:ps(n,e,t)):[]}function ps(e,t,n){return[ms(e[0],t[0],n),ms(e[1],t[1],n),ms(e[2],t[2],n)]}function ms(e,t,n){return e<ls||t<ls?1:yr(e/t,1/n,n)}var hs=class{options;current;lastTime;constructor(e=ds){this.options=e}update(e,t){let n=fs(e,this.options.maxGain),r=this.lastTime===void 0?1/0:Math.max(t-this.lastTime,0);this.lastTime=t;let i=this.current?1-Math.exp(-r/this.options.timeConstant):1,a=this.current;return this.current=n.map((e,t)=>Zt(a?.[t]??us,e,i)),this.current}},gs=30,_s=120,vs=90,ys=90,bs={yaw:t(0),pitch:t(0),fieldOfView:t(vs)};function xs(e){return N([e.yaw,e.pitch,e.fieldOfView].every(e=>Number.isFinite(e)),`view angles must be finite`),{...e,yaw:d(e.yaw),pitch:t(yr(e.pitch,-90,ys)),fieldOfView:t(yr(e.fieldOfView,gs,_s))}}function Ss(e,t){return e.yaw===t.yaw&&e.pitch===t.pitch&&e.fieldOfView===t.fieldOfView}function Cs(e){return Ir(Pr(l(e.yaw)),Nr(l(e.pitch)))}var ws=[`fast`,`balanced`,`high`],Ts=`balanced`,Es={fast:1,balanced:2,high:3};function Ds(e){return Es[e]}var Os=[`raw-lenses`,`equirectangular`,`normal`],ks=`raw-lenses`,As=.5,js={x:0,y:0,width:1,height:1},Ms={x:As,y:As};function Ns(e){return Math.max(e,1)}function Ps(e){return e.width/Ns(e.height)}function Fs(e,t){return{across:e.x/Ns(t.width),down:e.y/Ns(t.height)}}function Is(e,t){return{x:(t.x-e.x)/e.width,y:(t.y-e.y)/e.height}}function Ls(e,t){let n=Vs(e,t),r=Vs(1/e,t);return n.height>=r.height/e?Rs(n,e):zs(r,e)}function Rs(e,t){let n=e.width/t;return Array.from({length:t},(t,r)=>({...e,x:e.x+r*n,width:n}))}function zs(e,t){let n=e.height/t;return Array.from({length:t},(t,r)=>({...e,y:e.y+r*n,height:n}))}function Bs(e){N(e.length>0,`bounds need at least one rectangle`);let t=Math.min(...e.map(e=>e.x)),n=Math.min(...e.map(e=>e.y)),r=Math.max(...e.map(e=>e.x+e.width)),i=Math.max(...e.map(e=>e.y+e.height));return{x:t,y:n,width:r-t,height:i-n}}function Vs(e,t){if(e>=t){let n=t/e;return{x:0,y:(1-n)*As,width:1,height:n}}let n=e/t;return{x:(1-n)*As,y:0,width:n,height:1}}function Hs(e){return Math.tan(l(t(e/2)))}function Us(e,t){return t*e.width/e.height}function Ws(e,t,n){let r=Hs(e),i=[(t.x*2-1)*r,(t.y*2-1)*r/n,1];return Xt(i,1/Wt(i))}function Gs(e,t,n){return Lr(Cs(e),Ws(e.fieldOfView,t,n))}var Ks=1.1;function qs(e){return Ks**e}function Js(e,n){return t(e.fieldOfView/Math.max(n,1))}function Ys(e,n,r){let i=Js(e,r);return xs({...e,yaw:t(e.yaw-n.x*i),pitch:t(e.pitch+n.y*i)})}function Xs(e,n){return xs({...e,fieldOfView:t(e.fieldOfView/qs(n))})}function Zs(e,t,r){let i=Xs(e,t.steps);if(t.focus.x===Ms.x&&t.focus.y===Ms.y||i.fieldOfView===e.fieldOfView)return i;let a=Gs(e,t.focus,r),o=Ws(i.fieldOfView,t.focus,r),s=Qs(o,a[1],e.pitch);if(s===void 0)return i;let c=Lr(Nr(l(s)),o),d=u(n(Math.atan2(a[0],a[2])-Math.atan2(c[0],c[2])));return xs({...i,yaw:d,pitch:s})}function Qs(e,r,i){let[,a,o]=e,s=r/Math.hypot(a,o);if(Math.abs(s)>1)return;let c=u(n(Math.atan2(o,a))),l=u(n(Math.acos(s))),f=d(t(l-c)),p=d(t(-l-c));return Math.abs(f-i)<=Math.abs(p-i)?f:p}function $s(e,t){return e<=0||t<=0?0:Math.log(t/e)/Math.log(Ks)}function ec(e,t,n){return xs({...e,yaw:t,pitch:n})}var tc={scale:1,centre:{x:As,y:As}},nc=1e-9;function rc(e,t){return e.scale===t.scale&&e.centre.x===t.centre.x&&e.centre.y===t.centre.y}function ic(e,t){let n=e.width*t.scale,r=e.height*t.scale;return{x:Ms.x-t.centre.x*n,y:Ms.y-t.centre.y*r,width:n,height:r}}function ac(e,t){let n=yr(t.scale,1,8),r=n-1<nc?1:n;return{scale:r,centre:{x:lc(t.centre.x,e.width*r),y:lc(t.centre.y,e.height*r)}}}function oc(e,t,n){let r=ac(e,t),i=Is(ic(e,r),n.focus),a=r.scale*qs(n.steps);return ac(e,{scale:a,centre:{x:i.x+(Ms.x-n.focus.x)/(e.width*a),y:i.y+(Ms.y-n.focus.y)/(e.height*a)}})}function sc(e,t,n){let r=ac(e,t),i=cc(e,r,n);return ac(e,{scale:r.scale,centre:{x:r.centre.x-i.across,y:r.centre.y-i.down}})}function cc(e,t,n){return{across:n.across/(e.width*t.scale),down:n.down/(e.height*t.scale)}}function lc(e,t){if(t<=1)return As;let n=As/t;return yr(e,n,1-n)}var uc={view:bs,panorama:tc,lenses:tc};function dc(e,t){return Ss(e.view,t.view)&&rc(e.panorama,t.panorama)&&rc(e.lenses,t.lenses)}function fc(e,t){return{...e,view:t}}function pc(e,t){return{...e,lenses:t}}var mc=90;function hc({viewport:e,lensCount:t}){let n=Ls(t,Ps(e));return{tiles:n,bounds:Bs(n)}}function gc(e,t,n){let r=Fs(t,n.viewport);return pc(e,sc(hc(n).bounds,e.lenses,r))}function _c(e,t,n){let r=n.viewport.width/mc;return gc(e,{x:-(t.yaw*r),y:t.pitch*r},n)}function vc(e,t){let{tiles:n,bounds:r}=hc(t),i=ac(r,e.lenses),a=ic(r,i);return n.map(e=>({x:a.x+(e.x-r.x)*i.scale,y:a.y+(e.y-r.y)*i.scale,width:e.width*i.scale,height:e.height*i.scale}))}var yc={isStabilized:!1,canPan:({lenses:e})=>e.scale>1,pan:gc,turn:_c,zoom:(e,t,n)=>pc(e,oc(hc(n).bounds,e.lenses,t)),reset:e=>pc(e,tc),picture:(e,t)=>({kind:`lens-tiles`,tiles:vc(e,t)})},bc={isStabilized:!0,canPan:()=>!0,pan:(e,t,{viewport:n})=>fc(e,Ys(e.view,t,n.width)),turn:(e,n)=>{let{view:r}=e;return fc(e,ec(r,t(r.yaw+n.yaw),t(r.pitch+n.pitch)))},zoom:(e,t,{viewport:n})=>fc(e,Zs(e.view,t,Ps(n))),reset:e=>fc(e,bs),picture:({view:e})=>({kind:`rectilinear`,rotation:Cs(e),fieldOfView:e.fieldOfView,area:js})},xc=2;function Sc(e,t){let n=ac(e,t);return{...n,centre:{x:As,y:n.centre.y}}}function Cc(e,{viewport:t}){let n=Vs(xc,Ps(t));return{fitted:n,panorama:Sc(n,e.panorama)}}function wc(e,n,r){let{view:i}=e;return{...fc(e,ec(i,t(i.yaw+r),i.pitch)),panorama:n}}function Tc(e,n,r){let{fitted:i,panorama:a}=Cc(e,r),o=Fs(n,r.viewport);return wc(e,sc(i,a,{across:0,down:o.down}),t(-(cc(i,a,o).across*c)))}function Ec(e,t,n){let{fitted:r,panorama:i}=Cc(e,n);return wc(e,Sc(r,{...i,centre:{x:As,y:i.centre.y-t.pitch/s}}),t.yaw)}function Dc(e,n,r){let{fitted:i,panorama:a}=Cc(e,r),o=Sc(i,oc(i,a,n)),s=Is(ic(i,a),n.focus),l=Is(ic(i,o),n.focus);return wc(e,o,t((s.x-l.x)*c))}var Oc={normal:bc,equirectangular:{isStabilized:!0,canPan:()=>!0,pan:Tc,turn:Ec,zoom:Dc,reset:e=>({...fc(e,ec(e.view,t(0),e.view.pitch)),panorama:tc}),picture:(e,t)=>{let{fitted:n,panorama:r}=Cc(e,t);return{kind:`equirectangular`,rotation:Pr(l(e.view.yaw)),area:ic(n,r)}}},"raw-lenses":yc};function kc(e){return Oc[e]}var Ac=t(90);function jc(e,t){switch(e.kind){case`mei`:{let[n,r]=e.focal;return{...e,focal:[n*t,r*t]}}case`radial-polynomial`:{let[n,r,i,a]=e.coefficients;return{...e,coefficients:[n*t,r*t,i*t,a*t]}}}}var Mc=5,Nc={start:l(t(Ac-Mc)),end:l(t(Ac+Mc))};function Pc(e){let t=[];for(let n of e.sources)t.every(e=>!Lc(e,n))&&t.push({inputIndex:n.inputIndex,trackIndex:n.trackIndex});return t}function Fc(e){let{calibration:t,layout:n}=e;if(t.lenses.length!==n.sources.length)throw new j(`unsupported-layout`,`the calibration describes ${t.lenses.length} lenses but the layout has ${n.sources.length}`);let r=Pc(n);return N(e.displayConversions.length===r.length,`${e.displayConversions.length} display conversions for ${r.length} frame sources`),{lenses:n.sources.map(n=>{let i=Rc(t,n.lensIndex),a=r.findIndex(e=>Lc(e,n));return{lensIndex:n.lensIndex,frameSlot:a,region:n.region,window:zc(t,i),rotation:ss(i),projection:jc(i.model.projection,t.radialScale),halfFieldOfView:i.model.halfFieldOfView,displayConversion:Ic(e.displayConversions,a)}}),frameSlotCount:r.length,feather:Nc}}function Ic(e,t){let n=e[t];return N(n!==void 0,`no display conversion for frame slot ${t}`),n}function Lc(e,t){return e.inputIndex===t.inputIndex&&e.trackIndex===t.trackIndex}function Rc(e,t){let n=e.lenses.find(e=>e.lensIndex===t);if(!n)throw new j(`invalid-calibration`,`the calibration has no lens ${t}`);return n}function zc(e,t){let n=e.canvas.height;return{x:Math.floor(t.model.principalPoint.x/n)*n,y:0,width:n,height:n}}var Bc=class{parts;stabilizer=new Qo;constructor(e){this.parts=e}setStabilizer(e){this.stabilizer=e}present(e){let t=this.exposureTimeOf(e),n=this.parts.orientations.orientationAt(t);this.parts.sink.setStabilization(this.stabilizer.nextRotation(n,t)),this.parts.sink.present(e)}exposureTimeOf(e){let{timestamp:t}=e.pair;return this.parts.frameTimes?.midExposureAt(t)??t}};function Vc(e){let t=e instanceof Error?e:Error(`a failure went unheard`,{cause:e});Promise.reject(t)}var Hc=.5,Uc=class{meter;applyGains;reportFailure;matcher=new hs;lastMeasuredAt;inFlight;isStopped=!1;constructor(e,t,n=Vc){this.meter=e,this.applyGains=t,this.reportFailure=n}afterPresent(e){(this.lastMeasuredAt===void 0||Math.abs(e-this.lastMeasuredAt)>=Hc)&&!this.isStopped&&this.matchReporting(e)}matchNow(e){return this.inFlight??=this.measureAt(e),this.inFlight}stop(){this.isStopped=!0}async matchReporting(e){try{await this.matchNow(e)}catch(e){this.reportFailure(e)}}async measureAt(e){this.lastMeasuredAt=e;try{let t=await this.meter.measure();t&&!this.isStopped&&this.applyGains(this.matcher.update(t,e))}catch(e){throw this.isStopped=!0,e}finally{this.inFlight=void 0}}},Wc=[1,1,1],Gc=class{sink;renderer;active;lastMediaTime;constructor(e,t){this.sink=e,this.renderer=t}enable(){if(this.active)return;let{renderer:e}=this,t=e.createSeamMeter(),n=new Uc(t,t=>{e.setLensGains(t)});this.active={meter:t,matching:n}}disable(){this.stop();let e=Array.from({length:this.renderer.lensCount},()=>Wc);this.renderer.setLensGains(e)}async matchNow(){this.lastMediaTime!==void 0&&await this.active?.matching.matchNow(this.lastMediaTime)}present(e){this.sink.present(e),this.lastMediaTime=e.mediaTime,this.active?.matching.afterPresent(e.mediaTime)}dispose(){this.stop()}stop(){this.active?.matching.stop(),this.active?.meter.dispose(),this.active=void 0}},Kc=7,qc=.5,Jc=5,Yc=360;Ac-Kc,Math.round(14/qc),Math.round(Jc/qc);var Xc=Math.round(Yc/Jc);Array.from({length:Xc},()=>t(0));var Zc=[`bt709`,`bt470bg`,`smpte170m`,`bt2020`,`smpte432`],Qc=[`bt709`,`smpte170m`,`iec61966-2-1`,`linear`,`pq`,`hlg`],$c=[`rgb`,`bt709`,`bt470bg`,`smpte170m`,`bt2020-ncl`];function el(e,t){return e.find(e=>e===t)??`unspecified`}var tl={a:.17883277,b:.28466892,c:.55991073,segmentJoin:.5,squareSegmentDivisor:3,logSegmentDivisor:12},nl=[1.660491,-.5876411,-.0728499,-.1245505,1.1328999,-.0083494,-.0181508,-.1005789,1.1187297],rl=[.2126,.7152,.0722],il={exposure:1.4,kneeStart:.2,ceiling:1.5,exponent:2.2},al=/* @__PURE__ */ new Set([`bt709`,`bt470bg`,`smpte170m`,`unspecified`]),ol={bt709:Mr,bt2020:nl,unspecified:nl,bt470bg:void 0,smpte170m:void 0,smpte432:void 0};function sl({matrix:e}){return{kind:`as-recorded`,matrix:e}}function cl(e){let t=sl(e);return al.has(e.primaries)?{conversion:t}:{conversion:t,problem:`${e.primaries} primaries are shown as BT.709`}}function ll(e){let t=ol[e.primaries],n={kind:`hlg-to-sdr-bt709`,matrix:e.matrix,gamut:t??Mr,tone:il};return t===void 0?{conversion:n,problem:`HLG of ${e.primaries} primaries is shown without their gamut`}:{conversion:n}}function ul(e){return t=>({conversion:sl(t),problem:`the ${e} transfer cannot be shown yet: drawn as recorded`})}var dl={bt709:cl,smpte170m:cl,"iec61966-2-1":cl,unspecified:cl,hlg:ll,pq:ul(`pq`),linear:ul(`linear`)};function fl(e){let t=e.map(e=>dl[e.transfer](e)),n=t.flatMap(e=>e.problem===void 0?[]:[e.problem]);return{conversions:t.map(e=>e.conversion),warnings:[...new Set(n)]}}var pl={bt709:{red:.2126,blue:.0722},"bt2020-ncl":{red:.2627,blue:.0593},bt470bg:{red:.299,blue:.114},smpte170m:{red:.299,blue:.114},rgb:void 0,unspecified:void 0};function ml(e,t){let n=pl[e],r=pl[t];return n===void 0||r===void 0||e===t?Mr:Ir(hl(n),gl(r))}function hl({red:e,blue:t}){let n=1-e-t,r=2*(1-e),i=2*(1-t);return[1,0,r,1,-t*i/n,-e*r/n,1,i,0]}function gl({red:e,blue:t}){let n=1-e-t,r=2*(1-t),i=2*(1-e);return[e,n,t,-e/r,-n/r,(1-t)/r,(1-e)/i,-n/i,-t/i]}function _l(e){return Object.keys(e)}var vl=class{emitter;queue=[];depth=0;isDelivering=!1;isSuperseding=!1;constructor(e){this.emitter=e}change(e){this.depth===0&&this.isDelivering&&(this.isSuperseding=!0),this.depth+=1;try{return e()}finally{--this.depth,this.depth===0&&(this.isSuperseding=!1,this.deliver())}}emit(e,t){this.post(()=>{this.emitter.emit(e,t)})}post(e){this.isSuperseding&&=(this.queue.length=0,!1),this.queue.push(e),this.depth===0&&this.deliver()}deliver(){if(!this.isDelivering){this.isDelivering=!0;try{for(let e=this.queue.shift();e;e=this.queue.shift())e()}finally{this.isDelivering=!1}}}},yl={done:!0,value:void 0},bl=class{isEnded=!1;end(){this.isEnded=!0}hasEnded(){return this.isEnded}},xl=class{source;constructor(e){this.source=e}stream(e){return{[Symbol.asyncIterator]:()=>new Sl(this.source,e)}}},Sl=class{source;range;ending=new bl;constructor(e,t){this.source=e,this.range=t}async next(){if(await Promise.resolve(),this.ending.hasEnded())return yl;let e=await this.source.read(this.range);return this.ending.hasEnded()?yl:(this.ending.end(),e.byteLength===0?yl:{done:!1,value:e})}return(){return this.ending.end(),Promise.resolve(yl)}},Cl=class{parts;constructor(e){this.parts=e}get duration(){return this.parts.track.end}samplesFrom(e){let{download:t,track:n}=this.parts;return{[Symbol.asyncIterator]:()=>new wl(n,t.openCursor(n,n.sampleShownAt(e)??0,e))}}},wl=class{track;cursor;ending=new bl;constructor(e,t){this.track=e,this.cursor=t}async next(){let e=await this.cursor.nextSample();return!e||this.ending.hasEnded()?yl:{done:!1,value:{timestamp:this.track.timestampOf(e.sample),duration:this.track.durationOf(e.sample),data:Uint8Array.from(e.bytes)}}}return(){return this.ending.end(),this.cursor.close(),Promise.resolve(yl)}},Tl=class{parts;rejected=/* @__PURE__ */ new Set;constructor(e){this.parts=e}get description(){return this.parts.codec.description}decoderConfiguration(){return Promise.resolve(this.parts.codec.configuration)}keyframeAt(e){return Promise.resolve(this.timeOf(this.keyframeSampleAt(e)))}firstKeyframe(){return Promise.resolve(this.timeOf(this.firstKeyframeSample()))}packetsFrom(e){return{[Symbol.asyncIterator]:()=>new El({track:this.parts.track,open:()=>this.cursorFrom(e),reject:e=>{this.rejected.add(e)},packetOf:e=>this.packetOf(e)})}}sampleTimestamps(){return Promise.resolve(this.parts.track.timestampsInPresentationOrder())}frameCount(){return Promise.resolve(this.parts.track.sampleCount)}cursorFrom(e){let t=this.keyframeSampleAt(e)??this.firstKeyframeSample();return t===void 0?void 0:this.parts.download.openCursor(this.parts.track,t,e)}keyframeSampleAt(e){let{track:t}=this.parts,n=t.keyframeAt(e);for(;n!==void 0&&this.rejected.has(n);)n=t.syncSampleAtOrBefore(n-1);return n}firstKeyframeSample(){let{track:e}=this.parts,t=e.syncSampleAtOrAfter(0);for(;t!==void 0&&this.rejected.has(t);)t=e.syncSampleAtOrAfter(t+1);return t}timeOf(e){let{track:t}=this.parts;return e===void 0?void 0:{timestamp:t.timestampOf(e),duration:t.durationOf(e)}}packetOf(e){let{track:t}=this.parts;return{timestamp:t.timestampOf(e.sample),duration:t.durationOf(e.sample),isKeyFrame:t.isSync(e.sample)&&!this.rejected.has(e.sample),data:e.bytes}}},El=class{parts;cursor;isVerified=!1;ending=new bl;constructor(e){this.parts=e,this.cursor=e.open()}async next(){if(this.ending.hasEnded())return yl;let{cursor:e}=this;if(!e)throw new j(`no-key-frame`,`track ${this.parts.track.trackId} has no key frame`);let t=await e.nextSample();return!t||this.ending.hasEnded()?yl:!this.isVerified&&!this.parts.track.keyframeRule.isKeyframe(t.bytes)?this.startEarlier(e,t):(this.isVerified=!0,{done:!1,value:this.parts.packetOf(t)})}return(){return this.ending.end(),this.cursor?.close(),Promise.resolve(yl)}startEarlier(e,t){return this.parts.reject(t.sample),e.close(),this.cursor=this.parts.open(),this.next()}},Dl=class e{ranges;static empty=new e([]);constructor(e){this.ranges=e}static of(t){let n=t.filter(e=>e.length>0).toSorted((e,t)=>e.offset-t.offset);return new e(Ol(n,0))}get isEmpty(){return this.ranges.length===0}get totalLength(){return this.ranges.reduce((e,t)=>e+t.length,0)}union(t){return e.of([...this.ranges,...t.ranges])}subtract(t){return new e(this.ranges.flatMap(e=>kl(e,t.ranges)))}covers(e){return e.length===0||this.ranges.some(t=>t.contains(e))}overlaps(e){return this.ranges.some(t=>t.overlaps(e))}bridgingGapsBelow(t){return new e(Ol(this.ranges,t))}};function Ol(e,t){let n=[];for(let r of e){let e=n.at(-1),i=e!==void 0&&r.offset-e.end<Math.max(t,1);e&&i?n[n.length-1]=Al(e.offset,r.end,e.end):n.push(r)}return n}function kl(e,t){let n=[],r=e.offset;for(let i of t)i.end<=r||i.offset>=e.end||(i.offset>r&&n.push(Fn.of(r,i.offset-r)),r=Math.max(r,i.end));return r<e.end&&n.push(Fn.of(r,e.end-r)),n}function Al(e,t,n){return Fn.of(e,Math.max(t,n)-e)}var jl=class{range;bytes;filled=0;isComplete=!1;constructor(e,t){this.range=e,this.bytes=t}get filledRange(){return Fn.of(this.range.offset,this.filled)}},Ml=class{blocks=[];get held(){return Dl.of(this.blocks.map(e=>e.filledRange))}get allocatedBytes(){return this.blocks.reduce((e,t)=>e+t.bytes.byteLength,0)}allocate(e){let t=new jl(e,new Uint8Array(e.length));return this.blocks.push(t),t}write(e,t){let n=this.fillingOf(e);n.bytes.set(t,n.filled),n.filled+=t.byteLength}complete(e){this.fillingOf(e).isComplete=!0}trim(e){let t=this.fillingOf(e);t.isComplete=!0,t.bytes=t.bytes.slice(0,t.filled),this.blocks=this.blocks.filter(e=>e.bytes.byteLength>0)}bytesOf(e){let t=this.blocks.find(t=>t.filledRange.contains(e));return t?Nl(t,e):this.held.covers(e)?this.copyOf(e):void 0}release(e){this.blocks=this.blocks.filter(t=>!t.isComplete||!e.covers(t.filledRange))}fillingOf(e){let t=this.blocks.find(t=>t===e);return N(t!==void 0,`the block is not one this store holds`),t}copyOf(e){let t=new Uint8Array(e.length);for(let n of this.blocks){let r=Math.max(n.range.offset,e.offset),i=Math.min(n.filledRange.end,e.end);r<i&&t.set(n.bytes.subarray(r-n.range.offset,i-n.range.offset),r-e.offset)}return t}};function Nl(e,t){let n=t.offset-e.range.offset;return e.bytes.subarray(n,n+t.length)}var Pl=class{track;host;target;next;waiter;isClosed=!1;constructor(e,t,n){this.track=e,this.host=n,this.next=t.sample,this.target=t.target}get position(){return this.next}get isWaiting(){return this.waiter!==void 0}nextSample(){if(this.isClosed||this.next>=this.track.sampleCount)return Promise.resolve(void 0);N(this.waiter===void 0,`a cursor reads one sample at a time`);let e=this.track.rangeOf(this.next),t=this.host.bytesOf(e);if(t)return Promise.resolve(this.take(t));let n=this.host.failureOf(e);return n===void 0?this.waitForBytes(e):Promise.reject(n)}serve(){let{waiter:e}=this,t=e&&this.host.bytesOf(this.track.rangeOf(this.next));e&&t&&(this.waiter=void 0,e.resolve(this.take(t)))}fail(e,t){let{waiter:n}=this;n!==void 0&&e.overlaps(this.track.rangeOf(this.next))&&(this.waiter=void 0,n.reject(t))}close(){this.isClosed||(this.isClosed=!0,this.waiter?.resolve(void 0),this.waiter=void 0,this.host.closed(this))}waitForBytes(e){return new Promise((t,n)=>{this.waiter={resolve:t,reject:n},this.host.waiting(e)})}take(e){let t=this.next;return this.next+=1,this.host.movedOn(e.byteLength),{sample:t,bytes:e}}},Fl=class{parts;nextId=1;running=/* @__PURE__ */ new Map;constructor(e){this.parts=e}get states(){return[...this.running.values()].map(e=>({id:e.id,remaining:Il(e)}))}isBringing(e){for(let t of this.running.values())if(t.block.range.contains(e))return!0;return!1}start(e){let t={id:this.nextId,block:this.parts.store.allocate(e),chunks:this.parts.stream.stream(e)[Symbol.asyncIterator](),delivered:0};this.nextId+=1,this.running.set(t.id,t),this.pump(t)}cancel(e){let t=this.running.get(e);t&&(this.running.delete(e),t.chunks.return?.(),this.parts.store.trim(t.block))}cancelAll(){for(let e of this.running.keys())this.cancel(e)}async pump(e){try{for(let t=await e.chunks.next();t.done!==!0;t=await e.chunks.next()){if(!this.isRunning(e))return;this.parts.store.write(e.block,t.value),e.delivered+=t.value.byteLength,this.parts.listener.onChunk()}this.finish(e)}catch(t){this.fail(e,t)}}finish(e){this.isRunning(e)&&(this.running.delete(e.id),this.parts.store.complete(e.block),this.parts.listener.onEnd())}fail(e,t){this.isRunning(e)&&(this.running.delete(e.id),this.parts.store.trim(e.block),this.parts.listener.onFailure(Il(e),t))}isRunning(e){return this.running.get(e.id)===e}};function Il(e){let{range:t}=e.block;return Fn.of(t.offset+e.delivered,t.length-e.delivered)}function Ll(e,t){let{track:n}=e,r=[];for(let i=e.sample;i<n.sampleCount&&!(n.timestampOf(i)>t);i+=1)r.push(n.rangeOf(i));return r}function Rl(e,t){let n=[],r=t;for(let t of e.ranges){if(r<=0)break;n.push(Fn.of(t.offset,Math.min(t.length,r))),r-=t.length}return Dl.of(n)}function zl(e){let{policy:t}=e,n=R(e.time+t.resumeSeconds),r=e.cursors.filter(e=>e.track.kind===`video`),i=Dl.of(r.flatMap(e=>Ll(e,n))),a=Math.min(t.requestSize,t.refillBytes);return Rl(i,t.aheadBytes-a)}function Bl(e){return zl(e).subtract(e.held).isEmpty}function Vl(e){let t=e.cursors.filter(e=>Yl(e)),n=t.length>0?Wl(t):e.anchor,r=n??Hl(e);if(!r)return Ul(e);let i=e.isReadingAhead?e.policy.aheadSeconds:0,a=R(r.time+i),o=Gl({state:e,windowStart:r,windowEnd:a}).bridgingGapsBelow(e.policy.bridgedGap),s=e.transfers.filter(e=>e.remaining.length===0||o.overlaps(e.remaining)),c=Dl.of(s.map(e=>e.remaining)),l=o.subtract(e.held).subtract(c).subtract(e.unreadable),u=e.policy.requestsInFlight-s.length;return{start:Zl({state:e,windowStart:r,windowEnd:a,missing:l,threshold:Xl(e,r)})?$l(l,e.policy,u):[],cancel:e.transfers.filter(e=>!s.includes(e)).map(e=>e.id),release:e.held.subtract(o.union(eu(r,e.policy))),anchor:n}}function Hl(e){return e.isReadingAhead&&e.cursors.length>0?Wl(e.cursors):void 0}function Ul(e){return{start:[],cancel:e.transfers.map(e=>e.id),release:Dl.empty,anchor:void 0}}function Wl(e){return{time:R(Math.min(...e.map(e=>ru(e)))),offset:Math.min(...e.map(e=>au(e))),keyframeOffset:Math.min(...e.map(e=>iu(e)))}}function Gl(e){let{state:t,windowEnd:n}=e,r=t.cursors.filter(t=>Kl(t,e)),i=r.flatMap(e=>Ll(e,Jl(n,e.target))),a=r.filter(e=>ql(e,n)),o=Dl.of(a.map(e=>e.track.rangeOf(e.sample)));return Rl(Dl.of(i),t.policy.aheadBytes).union(o)}function Kl(e,t){return ru(e)>=t.windowStart.time-t.state.policy.keepBehindSeconds}function ql(e,t){let n=e.isWaiting&&ru(e)<=t;return!nu(e)&&(Yl(e)||n)}function Jl(e,t){return t!==void 0&&t>e?t:e}function Yl(e){return e.track.kind===`video`}function Xl(e,t){let n={cursors:e.cursors,time:t.time,policy:e.policy};return e.isReadingAhead?zl(n):Dl.empty}function Zl(e){let{state:t,missing:n,threshold:r}=e;return n.ranges.some(e=>r.overlaps(e))?!0:t.cursors.some(t=>Ql(t,e)&&n.overlaps(t.track.rangeOf(t.sample)))||n.totalLength>=t.policy.refillBytes}function Ql(e,t){if(!e.isWaiting||nu(e))return!1;let{windowStart:n,state:r}=t,i=n.time+(r.isReadingAhead?r.policy.resumeSeconds:0);return Yl(e)||ru(e)<=i}function $l(e,t,n){let r=[];for(let i of e.ranges)for(let e=i.offset;e<i.end&&r.length<n;e+=t.requestSize)r.push(Fn.of(e,Math.min(t.requestSize,i.end-e)));return r}function eu(e,t){let n=tu(e,t);return Dl.of([Fn.of(n,e.offset-n)])}function tu(e,t){return Math.max(0,Math.min(e.keyframeOffset,e.offset-t.keepBehindBytes))}function nu(e){return e.sample>=e.track.sampleCount}function ru(e){return nu(e)?e.track.end:e.track.timestampOf(e.sample)}function iu(e){let{track:t}=e,n=Math.min(e.sample,t.sampleCount-1),r=t.syncSampleAtOrBefore(n);return r===void 0?au(e):t.rangeOf(r).offset}function au(e){let{track:t}=e;return nu(e)?t.sampleCount>0?t.rangeOf(t.sampleCount-1).end:0:t.rangeOf(e.sample).offset}var ou=Fn.of(0,2**53-1),su=class{parts;store=new Ml;progressListeners=/* @__PURE__ */ new Set;transfers;cursors=/* @__PURE__ */ new Set;host;failures=[];anchor;isReadingAhead=!1;isPlanDue=!1;takenSincePlan=0;isDisposed=!1;constructor(e){this.parts=e,this.transfers=new Fl({stream:e.stream,store:this.store,listener:{onChunk:()=>{this.serveCursors();for(let e of this.progressListeners)e()},onEnd:()=>{this.schedulePlan()},onFailure:(e,t)=>{this.fail(e,t)}}}),this.host=this.cursorHost()}openCursor(e,t,n){N(this.parts.table.tracks.includes(e),`the track is not one of this file`);let r=new Pl(e,{sample:t,target:n},this.host);return this.isDisposed?(r.close(),r):(this.failures=[],this.cursors.add(r),this.schedulePlan(),r)}startReadingAhead(){this.isReadingAhead=!0,this.schedulePlan()}isReadyToResumeAt(e){return Bl({cursors:this.positions(),held:this.store.held,time:e,policy:this.parts.policy})}onProgress(e){let t=()=>{e()};return this.progressListeners.add(t),()=>{this.progressListeners.delete(t)}}dispose(){this.isDisposed=!0,this.transfers.cancelAll();for(let e of this.cursors)e.close()}cursorHost(){return{bytesOf:e=>this.store.bytesOf(e),failureOf:e=>this.failures.find(t=>t.range.overlaps(e))?.error,movedOn:e=>{this.takenSincePlan+=e,this.takenSincePlan>=this.parts.policy.replanBytes&&this.schedulePlan()},waiting:e=>{this.transfers.isBringing(e)||this.schedulePlan()},closed:e=>{this.cursors.delete(e),this.schedulePlan()}}}schedulePlan(){this.isPlanDue||this.isDisposed||(this.isPlanDue=!0,this.planAfterThisTurn())}async planAfterThisTurn(){if(await Promise.resolve(),this.isPlanDue=!1,!this.isDisposed)try{this.plan()}catch(e){this.failEveryRead(e)}}failEveryRead(e){let t=ne(e,`invariant-violation`,`the download could not plan`);this.failures.push({range:ou,error:t});for(let e of this.cursors)e.fail(ou,t)}plan(){this.takenSincePlan=0;let e=Vl({cursors:this.positions(),held:this.store.held,transfers:this.transfers.states,unreadable:Dl.of(this.failures.map(e=>e.range)),isReadingAhead:this.isReadingAhead,anchor:this.anchor,policy:this.parts.policy});this.anchor=e.anchor,this.carryOut(e)}positions(){return[...this.cursors].map(e=>({track:e.track,sample:e.position,isWaiting:e.isWaiting,target:e.target}))}carryOut(e){for(let t of e.cancel)this.transfers.cancel(t);this.store.release(e.release);for(let t of e.start)this.transfers.start(t)}serveCursors(){for(let e of this.cursors)e.serve()}fail(e,t){let n=ne(t,`source-unreadable`,`a range of the recording could not be read`);this.failures.push({range:e,error:n});for(let t of this.cursors)t.fail(e,n);this.schedulePlan()}};function cu(e){let t=new su(e);return{download:t,videoTracks:e.codecs.video.map(n=>new Tl({download:t,track:lu(e.table,n.trackId,`video`),codec:n})),audioTracks:e.codecs.audio.map(n=>({samples:new Cl({download:t,track:lu(e.table,n.trackId,`audio`)}),configuration:n.configuration})),duration:e.table.duration,dispose:()=>{t.dispose()}}}function lu(e,t,n){let r=e.trackWithId(t);if(r?.kind!==n)throw new j(`unsupported-container`,`the movie box has no ${n} track ${t} to read`);return r}var uu=1048576,du=10,fu=128,pu=2,mu=32,hu=8,gu=2,_u=1,vu=.25,yu=16,bu=4;function xu(e,t){let n=e.size/e.duration,r=Math.min(Math.round(du*n),fu*uu/t),i=Math.round(r*vu);return{aheadSeconds:R(du),aheadBytes:r,keepBehindBytes:Math.min(Math.round(pu*n),mu*uu/t),keepBehindSeconds:R(pu),requestSize:hu*uu,requestsInFlight:gu,bridgedGap:_u*uu,refillBytes:i,replanBytes:Math.round(i/yu),resumeSeconds:R(bu)}}var Su=class{files;constructor(e){this.files=e}isReadyToResumeAt(e){return this.files.every(t=>t.isReadyToResumeAt(e))}onProgress(e){let t=this.files.map(t=>t.onProgress(e));return()=>{for(let e of t)e()}}};function Cu(e){for(let t of e.frames)t.close()}var wu=class{capacity;onPush;pairs=[];roomWaiters=[];isClosed=!1;constructor(e,t=Tu){this.capacity=e,this.onPush=t,N(Number.isSafeInteger(e)&&e>0,`queue capacity must be positive`)}get length(){return this.pairs.length}get isFull(){return this.pairs.length>=this.capacity}get isClosedForGood(){return this.isClosed}waitForRoom(){return!this.isFull||this.isClosed?Promise.resolve():new Promise(e=>{this.roomWaiters.push(e)})}push(e){if(this.isClosed){Cu(e);return}this.pairs.push(e),this.onPush()}takePairAt(e){let t;for(;this.pairs.length>0&&(this.pairs[0]?.timestamp??1/0)<=e;)t&&Cu(t),t=this.pairs.shift();return t&&this.wakeWaiters(),t}peekTimestamp(){return this.pairs[0]?.timestamp}newestTimestamp(){return this.pairs.at(-1)?.timestamp}close(){this.isClosed=!0;for(let e of this.pairs)Cu(e);this.pairs.length=0,this.wakeWaiters()}wakeWaiters(){if(this.isFull&&!this.isClosed)return;let e=this.roomWaiters;this.roomWaiters=[];for(let t of e)t()}};function Tu(){}var Eu=class{tolerance;onPair;queues;unpairedCount=0;constructor(e,t,n){this.tolerance=t,this.onPair=n,this.queues=Array.from({length:e},()=>[])}get unpaired(){return this.unpairedCount}push(e,t){ae(e,this.queues.length,`frame source`),this.queues[e]?.push(t),this.drain()}discardAll(){for(let e of this.queues){for(let t of e)t.close();e.length=0}}drain(){for(;this.queues.every(e=>e.length>0);){let e=this.queues.map(e=>e[0]).filter(e=>e!==void 0),t=Math.min(...e.map(e=>e.timestamp));e.every(e=>Math.abs(e.timestamp-t)<=this.tolerance)?this.emit(e,R(t)):this.dropHeadAt(t)}}emit(e,t){for(let e of this.queues)e.shift();this.onPair({timestamp:t,frames:e})}dropHeadAt(e){this.queues.find(t=>t[0]?.timestamp===e)?.shift()?.close(),this.unpairedCount+=1}},Du=class{from;deliver;held;droppedCount=0;constructor(e,t){this.from=e,this.deliver=t}get dropped(){return this.droppedCount}push(e){if(e.timestamp>=this.from){this.release(),this.deliver(e);return}this.hold(e)}release(){if(!this.held)return;let e=this.held;this.held=void 0,this.deliver(e)}discard(){this.held&&Cu(this.held),this.held=void 0}hold(e){this.held&&(Cu(this.held),this.droppedCount+=1),this.held=e}},Ou=class{promise;isSettledNow=!1;resolvePromise;rejectPromise;constructor(){this.promise=new Promise((e,t)=>{this.resolvePromise=e,this.rejectPromise=t})}get isSettled(){return this.isSettledNow}resolve(e){this.isSettledNow||(this.isSettledNow=!0,this.resolvePromise?.(e))}reject(e){this.isSettledNow||(this.isSettledNow=!0,this.rejectPromise?.(e))}async follow(e){try{this.resolve(await e)}catch(e){this.reject(e)}}},ku=Symbol(`stopped`),Au=class{isStopped=!1;wakeWaiter;get wasStopped(){return this.isStopped}stop(){this.isStopped=!0,this.wakeWaiter?.()}async race(e){if(this.isStopped)return ku;N(this.wakeWaiter===void 0,`a run stop races one wait at a time`);let t=new Promise(e=>{this.wakeWaiter=()=>{e(ku)}});try{return await Promise.race([e(),t])}finally{this.wakeWaiter=void 0}}},ju=class{frameSources;decoderPort;options;stop=new Au;hasRun=!1;iterators=[];constructor(e,t,n){if(this.frameSources=e,this.decoderPort=t,this.options=n,e.length===0)throw new j(`invariant-violation`,`a decode pipeline needs at least one frame source`)}async run(e,t){N(!this.hasRun,`a decode pipeline runs once; create a new one for each run`),this.hasRun=!0;let n=await this.openRun(e,t);try{let e=await this.feed(n);if(await Nu(n,e),n.failure.isSettled)throw await n.failure.promise;return Lu(n,e)}finally{Fu(n)}}abort(){this.stop.stop(),Iu(this.iterators)}async openRun(e,t){let{stop:n}=this,r=new Ou,i={packets:0,pairs:0},a=new Du(e,e=>{i.pairs+=1,t.push(e)}),o=new Eu(this.frameSources.length,this.options.pairTolerance,e=>{a.push(e)}),s=n.wasStopped?[]:this.packetIteratorsFrom(e);this.iterators=s;let c=e=>{r.resolve(e),n.stop()};try{return{output:t,stop:n,failure:r,tally:i,gate:a,pairer:o,iterators:s,decoders:n.wasStopped?[]:await this.createDecoders(o,c)}}catch(e){throw Iu(s),e}}async createDecoders(e,t){let n=await Promise.allSettled(this.frameSources.map(async(n,r)=>this.decoderPort.create(await n.decoderConfiguration(),{onFrame:t=>{e.push(r,t)},onError:t}))),r=n.flatMap(e=>e.status===`fulfilled`?[e.value]:[]),i=n.find(e=>e.status===`rejected`);if(i){for(let e of r)e.close();throw Ru(i.reason)}return r}async feed(e){for(;!Mu(e);){if(await e.stop.race(()=>e.output.waitForRoom()),Mu(e))return!1;let t=await e.stop.race(()=>zu(e.iterators));if(t===ku)return!1;if(!t)return!0;await this.decodeRound(e,t)}return!1}async decodeRound(e,t){for(let[n,r]of e.decoders.entries()){let i=t[n];if(i){if(await e.stop.race(()=>r.waitForPendingBelow(this.options.maxPendingPackets)),Mu(e))return;r.decode(i),e.tally.packets+=1}}}packetIteratorsFrom(e){return this.frameSources.map(t=>t.packetsFrom(e)[Symbol.asyncIterator]())}};function Mu(e){return e.stop.wasStopped||e.output.isClosedForGood}async function Nu(e,t){await e.stop.race(()=>Pu(e.decoders,e.failure))!==ku&&t&&e.gate.release()}async function Pu(e,t){try{await Promise.all(e.map(e=>e.flush()))}catch(e){if(!t.isSettled)throw e}}function Fu(e){for(let t of e.decoders)t.close();e.pairer.discardAll(),e.gate.discard(),Iu(e.iterators)}function Iu(e){for(let t of e)t.return?.()}function Lu(e,t){return{packetsDecoded:e.tally.packets,pairsDelivered:e.tally.pairs,unpairedFrames:e.pairer.unpaired,pairsDroppedBeforeStart:e.gate.dropped,hasReachedEnd:t}}function Ru(e){return e instanceof Error?e:new j(`decode`,`a decoder could not be created`,{cause:e})}async function zu(e){let t=await Promise.all(e.map(e=>e.next())),n=[];for(let e of t){if(e.done===!0)return;n.push(e.value)}return n}var Bu={verdict:`decodes`,detail:void 0},Vu={verdict:`no-key-frame`,detail:`the track has no key frame`},Hu={verdict:`decode-failed`,detail:`the decoder accepted the first key frame but produced no picture`},Uu={verdict:`timed-out`,detail:`the decoder produced no picture before the deadline`},Wu={verdict:`key-frame-late`,detail:`the first key frame did not arrive before the deadline`};async function Gu(e,t,n){let r=e.map(e=>new Ju(e,t));try{let e=await Promise.all(r.map(e=>Ku(e,n)));return{canDecode:e.every(e=>e.verdict===`decodes`),sources:e}}finally{for(let e of r)e.close()}}async function Ku(e,t){try{let n=await Promise.race([e.run(),qu(t,e)]);return{track:e.track.description,...n}}finally{e.close()}}async function qu(e,t){return await e.promise,t.outcomeAtDeadline}var Ju=class{track;decoderPort;decoder;firstOutcome;isClosed=!1;isReadingKeyFrame=!1;constructor(e,t){this.track=e,this.decoderPort=t}get outcomeAtDeadline(){return this.isReadingKeyFrame?Wu:Uu}async run(){let e=await this.track.decoderConfiguration();if(!await this.decoderPort.isSupported(e))return Yu(e);if(this.isClosed)return Uu;let t=await this.track.firstKeyframe();if(!t)return Vu;this.isReadingKeyFrame=!0;let n=await Zu(this.track,t.timestamp);return this.isReadingKeyFrame=!1,n?await this.decodeFirst(e,n):Vu}close(){this.isClosed=!0,this.decoder?.close(),this.decoder=void 0,this.firstOutcome?.resolve(Uu)}async decodeFirst(e,t){if(this.isClosed)return Uu;let n=new Ou;this.firstOutcome=n;let r=await this.openDecoder(e,n);return r===void 0?n.promise:(this.decoder=r,this.decodeInto(r,t,n),n.promise)}async openDecoder(e,t){try{let n=await this.decoderPort.create(e,{onFrame:e=>{e.close(),t.resolve(Bu)},onError:e=>{t.resolve(Xu(e))}});if(!this.isClosed)return n;n.close(),t.resolve(Uu)}catch(e){t.resolve(Xu(e))}}async decodeInto(e,t,n){try{e.decode(t),await e.flush(),n.resolve(Hu)}catch(e){n.resolve(Xu(e))}}};function Yu(e){return{verdict:`unsupported-configuration`,detail:`${e.codec} at ${e.codedWidth}x${e.codedHeight} is not supported here`}}function Xu(e){let t=ie(e);return{verdict:M(e,`codec-unsupported`)?`unsupported-configuration`:`decode-failed`,detail:t}}async function Zu(e,t){let n=e.packetsFrom(t)[Symbol.asyncIterator]();try{let e=await n.next();return e.done===!0?void 0:e.value}finally{n.return?.()}}var Qu=class{now;hasEnded=!1;failure=void 0;isRunningNow=!1;positionAtAnchor=R(0);anchorMs=0;constructor(e){this.now=e}get isRunning(){return this.isRunningNow}get currentTime(){if(!this.isRunningNow)return this.positionAtAnchor;let e=gt(pt(this.now()-this.anchorMs));return R(this.positionAtAnchor+e)}start(){return this.isRunningNow||=(this.anchorMs=this.now(),!0),Promise.resolve()}pause(){this.isRunningNow&&=(this.positionAtAnchor=this.currentTime,!1)}seek(e){this.positionAtAnchor=e,this.anchorMs=this.now()}dispose(){this.pause()}},$u={ready:[`playing`,`buffering`,`paused`,`seeking`,`error`,`disposed`],playing:[`buffering`,`paused`,`seeking`,`ended`,`error`,`disposed`],buffering:[`playing`,`paused`,`seeking`,`error`,`disposed`],paused:[`playing`,`buffering`,`seeking`,`error`,`disposed`],seeking:[`buffering`,`paused`,`error`,`disposed`],ended:[`seeking`,`error`,`disposed`],error:[`disposed`],disposed:[]},ed=/* @__PURE__ */ new Set([`playing`,`buffering`]);function td(e){return e!==void 0&&ed.has(e)}var nd=class{current=`ready`;get state(){return this.current}canTransitionTo(e){return $u[this.current].includes(e)}transitionTo(e){if(!this.canTransitionTo(e))throw new j(`invariant-violation`,`player cannot go from ${this.current} to ${e}`);this.current=e}isOneOf(...e){return e.includes(this.current)}},rd=class{reportListenerError;listeners=/* @__PURE__ */ new Map;constructor(e=Vc){this.reportListenerError=e}on(e,t){let n=this.listeners.get(e)??/* @__PURE__ */ new Set;return n.add(t),this.listeners.set(e,n),()=>{n.delete(t)}}emit(e,t){let n=this.listeners.get(e);if(!n)return;let r=[...n];for(let e of r)if(n.has(e))try{e(t)}catch(e){this.reportListenerError(e)}}removeAll(){for(let e of this.listeners.values())e.clear();this.listeners.clear()}},id=1,ad=.25,od=class{position;previousPlayingTick;placedAt(e){this.position=e}stoppedAt(e){(this.position===void 0||e>=this.position)&&(this.position=e)}playingFrom(e){this.previousPlayingTick=e}wasMovedFromOutside({now:e,state:t}){let n=this.position;return this.position=e,n!==void 0&&(t===`playing`?n-e:Math.abs(e-n))>ad}wereTicksMissed({now:e,state:t}){let n=t===`playing`,r=this.previousPlayingTick;this.previousPlayingTick=n?e:void 0;let i=r===void 0?0:e-r;return n&&i>id}};function sd(e){return!e.isRunning&&!e.hasEnded}function cd(e,t){return e.hasEnded||e.currentTime>=t}var ld=class{generation=0;scrubs=0;isFromFlowing=!1;get resumesPlaying(){return this.isFromFlowing}begin(e){this.isFromFlowing=td(e),this.generation+=1}claimScrub(){return this.scrubs+=1,{seek:this.generation,scrub:this.scrubs}}isScrubCurrent(e){return e.seek===this.generation&&e.scrub===this.scrubs}},ud=.25,dd=class{lifecycle;announced;constructor(e){this.lifecycle=e}announce(e){this.announced=e,this.lifecycle.announce(`timeupdate`,e)}followPlayback(e){let{announced:t}=this;(t===void 0||Math.abs(e-t)>=ud)&&this.announce(e)}},fd=class{lifecycle;cause=`priming`;startAttempt;constructor(e){this.lifecycle=e}get waitingStart(){return this.startAttempt?.promise}enter(e){this.cause=e,this.lifecycle.moveTo(`buffering`)}enterForStart(){let e=new Ou;return this.startAttempt=e,this.enter(`priming`),e.promise}isOverAt(e,t){return!e||!this.lifecycle.is(`buffering`)?!1:this.cause===`priming`?e.isPrimedAt(t):e.isReadyToResumeAt(t)}takeStart(){let e=this.startAttempt;return this.startAttempt=void 0,e}settleStart(){this.takeStart()?.resolve()}},pd=class{machine=new nd;outbox;constructor(e){this.outbox=new vl(e)}get current(){return this.machine.state}is(e){return this.machine.state===e}isOneOf(...e){return this.machine.isOneOf(...e)}canMoveTo(e){return this.machine.canTransitionTo(e)}moveTo(e){this.machine.transitionTo(e),this.announce(`statechange`,e)}announce(e,t){this.outbox.emit(e,t)}change(e){return this.outbox.change(e)}},md=2,hd=.25,gd=class e{parts;listener;queue;pipeline;primingPairs;stopFollowingBuffer;isAborted=!1;hasReachedEnd=!1;hasHandedOutPair=!1;constructor(e,t){this.parts=e,this.listener=t,this.primingPairs=Math.min(md,e.queueCapacity),this.queue=new wu(e.queueCapacity,()=>{this.isAborted||t.onProgress()}),this.stopFollowingBuffer=e.buffer?.onProgress(()=>{t.onProgress()})??(()=>void 0),this.pipeline=new ju(e.frameSources,e.decoderPort,e.pipeline)}static start(t,n,r){let i=new e(t,r);return i.follow(i.pipeline.run(n,i.queue)),i}get isDrained(){return this.hasReachedEnd&&this.queue.length===0}isPrimedAt(e){let t=(this.queue.newestTimestamp()??-1/0)>=e;return this.hasReachedEnd||t&&this.queue.length>=this.primingPairs}isReadyToResumeAt(e){return this.isPrimedAt(e)&&(this.hasReachedEnd||(this.parts.buffer?.isReadyToResumeAt(e)??!0))}isStarvedAt(e,t){let n=this.queue.length===0&&!this.hasReachedEnd,r=e-(t??-1/0);return n&&r>hd}takePairAt(e){let t=this.queue.peekTimestamp(),n=!this.hasHandedOutPair&&t!==void 0,r=this.queue.takePairAt(n?R(Math.max(e,t)):e);return r&&(this.hasHandedOutPair=!0),r}abort(){this.isAborted=!0,this.stopFollowingBuffer(),this.pipeline.abort(),this.queue.close()}async follow(e){try{let{hasReachedEnd:t}=await e;if(this.isAborted)return;this.hasReachedEnd=t,this.listener.onProgress()}catch(e){this.isAborted||this.listener.onFailure(e)}}};async function _d(e,t){try{return(await e.keyframeAt(t))?.timestamp??t}catch{return t}}var vd=class{parts;events=new rd;lifecycle=new pd(this.events);run;presented;timeUpdates=new dd(this.lifecycle);buffering=new fd(this.lifecycle);clockWatch=new od;seeks=new ld;constructor(e){this.parts=e}get state(){return this.lifecycle.current}get currentTime(){return this.parts.clock.currentTime}async play(){if(this.lifecycle.current!==`playing`){if(this.lifecycle.current===`buffering`){await this.buffering.waitingStart;return}await this.lifecycle.change(()=>this.beginStart())}}pause(){this.lifecycle.change(()=>{let e=this.parts.clock.isRunning;this.parts.clock.pause(),e&&this.clockWatch.stoppedAt(this.parts.clock.currentTime),this.lifecycle.canMoveTo(`paused`)&&(this.lifecycle.moveTo(`paused`),this.buffering.settleStart(),this.timeUpdates.announce(this.parts.clock.currentTime))})}stop(){this.lifecycle.change(()=>{this.pause(),this.seek(R(0))})}seek(e){this.lifecycle.isOneOf(`disposed`,`error`)||this.lifecycle.change(()=>{let t=R(yr(e,0,this.parts.duration));this.seeks.begin(this.lifecycle.current),this.moveClockTo(t),this.startRun(t),this.lifecycle.moveTo(`seeking`),this.seeks.resumesPlaying?this.buffering.enter(`priming`):this.lifecycle.moveTo(`paused`),this.timeUpdates.announce(t)})}async scrub(e){let[t]=this.parts.frameSources;if(!t||this.lifecycle.isOneOf(`disposed`,`error`))return;let n=R(yr(e,0,this.parts.duration)),r=this.seeks.claimScrub(),i=await _d(t,n);this.seeks.isScrubCurrent(r)&&!this.lifecycle.isOneOf(`disposed`,`error`)&&this.seek(i)}preload(){this.run||this.lifecycle.current!==`ready`||this.lifecycle.change(()=>{this.startRun(this.parts.clock.currentTime)})}tick(){this.lifecycle.isOneOf(`disposed`,`error`)||this.lifecycle.change(()=>{let{failure:e}=this.parts.clock;if(e){this.fail(e);return}let t=this.parts.clock.currentTime;if(this.clockWatch.wasMovedFromOutside({now:t,state:this.lifecycle.current})){this.followMoveFromOutside(t);return}if(this.haveTicksStopped(t)){this.restartAt(t);return}this.presentDue(t),this.lifecycle.is(`playing`)?this.followClock(t):this.isStartedFromOutside()&&this.followStartFromOutside()})}redraw(){if(!this.presented||this.lifecycle.isOneOf(`playing`,`error`))return;let{presented:e}=this;this.lifecycle.change(()=>this.draw(e))}dispose(){this.lifecycle.current!==`disposed`&&(this.lifecycle.change(()=>{this.abortRun(),this.presented&&Cu(this.presented.pair),this.presented=void 0,this.parts.clock.pause(),this.lifecycle.moveTo(`disposed`),this.buffering.settleStart()}),this.events.removeAll())}beginStart(){if(this.isAtTheEnd()&&this.seek(R(0)),this.lifecycle.canMoveTo(`buffering`))return this.run||this.startRun(this.parts.clock.currentTime),this.isPrimed()?(this.enterPlaying(),this.startClockOnceHeard()):this.startOncePrimed()}startOncePrimed(){return this.parts.clock.pause(),this.buffering.enterForStart()}async startClockOnceHeard(){await Promise.resolve(),this.lifecycle.is(`playing`)&&await this.startClock()}enterPlaying(){this.clockWatch.playingFrom(this.parts.clock.currentTime),this.lifecycle.moveTo(`playing`)}presentDue(e){let t=this.run?.takePairAt(e);t&&this.present(t,e)}followClock(e){if(this.isPlayedOut(e)){this.end();return}if(sd(this.parts.clock)){this.lifecycle.moveTo(`paused`),this.timeUpdates.announce(e);return}if(this.run?.isStarvedAt(e,this.presented?.pair.timestamp)===!0){this.parts.clock.pause(),this.buffering.enter(`starvation`);return}this.timeUpdates.followPlayback(e)}isStartedFromOutside(){return this.parts.clock.isRunning&&this.lifecycle.isOneOf(`ready`,`paused`,`ended`)}async followStartFromOutside(){try{await this.play()}catch{}}moveClockTo(e){this.parts.clock.pause(),this.parts.clock.seek(e),this.clockWatch.placedAt(this.parts.clock.currentTime)}followMoveFromOutside(e){let t=this.parts.clock.isRunning;!t&&this.lifecycle.is(`playing`)&&this.pause(),this.seek(e),t&&this.lifecycle.is(`paused`)&&this.followStartFromOutside()}haveTicksStopped(e){return this.clockWatch.wereTicksMissed({now:e,state:this.lifecycle.current})&&!this.parts.clock.hasEnded}restartAt(e){let{clock:t,duration:n}=this.parts;if(e>=n){this.moveClockTo(n),this.end();return}let r=t.isRunning;if(t.pause(),this.startRun(e),r){this.buffering.enter(`priming`);return}this.lifecycle.moveTo(`paused`),this.timeUpdates.announce(e)}isAtTheEnd(){return this.lifecycle.current===`ended`||cd(this.parts.clock,this.parts.duration)}isPrimed(){return this.run?.isPrimedAt(this.parts.clock.currentTime)===!0}resumeIfPrimed(){this.buffering.isOverAt(this.run,this.parts.clock.currentTime)&&this.resume()}async resume(){let e=this.buffering.takeStart();this.enterPlaying();try{await this.startClockOnceHeard(),e?.resolve()}catch(t){e?.reject(t)}}async startClock(){try{await this.parts.clock.start()}catch(e){throw this.lifecycle.is(`playing`)&&this.lifecycle.moveTo(`paused`),e}}isPlayedOut(e){let t=this.run?.isDrained===!0&&e>=this.parts.duration;return this.parts.clock.hasEnded||t}present(e,t){this.presented&&Cu(this.presented.pair),this.presented={pair:e,mediaTime:t},this.draw(this.presented)&&this.lifecycle.announce(`present`,t)}draw(e){try{return this.parts.sink.present(e),!0}catch(e){return this.fail(ne(e,`render-unavailable`,`the picture could not be drawn`)),!1}}startRun(e){this.abortRun(),this.run=gd.start(this.parts,e,{onProgress:()=>{this.resumeIfPrimed()},onFailure:e=>{this.fail(e)}})}abortRun(){this.run?.abort(),this.run=void 0}end(){this.lifecycle.canMoveTo(`ended`)&&(this.parts.clock.pause(),this.lifecycle.moveTo(`ended`),this.timeUpdates.announce(this.parts.clock.currentTime),this.lifecycle.announce(`ended`,void 0))}fail(e){this.lifecycle.canMoveTo(`error`)&&this.lifecycle.change(()=>{this.parts.clock.pause(),this.abortRun(),this.lifecycle.moveTo(`error`),this.buffering.settleStart(),this.lifecycle.announce(`error`,ne(e,`decode`,`playback failed`))})}};function yd(e,t){if(e===null)return;let n=e.trim().toLowerCase();return t.find(e=>e===n)}function bd(e){return yd(e,Xo)}function xd(e){return yd(e,Os)}function Sd(e){return yd(e,ws)}function Cd(e,t){for(let n of t)Object.defineProperty(e,Ad(n),{configurable:!0,enumerable:!0,get(){return this.getAttribute(n)},set(e){Od(this,n,e)}})}function wd(e,t){for(let n of t)Object.defineProperty(e,Ad(n),{configurable:!0,enumerable:!0,get(){return this.hasAttribute(n)},set(e){this.toggleAttribute(n,!!e)}})}function Td(e,t){for(let n of t)Object.defineProperty(e,Ad(n.name),{configurable:!0,enumerable:!0,get(){return Dd(n,this.getAttribute(n.name))},set(e){Od(this,n.name,e)}})}function Ed(e,t){for(let n of t)Object.defineProperty(e,n.property,{configurable:!0,enumerable:!0,get(){let e=this.getAttribute(n.name);return e===null?null:Dd(n,e)},set(e){Od(this,n.name,e)}})}function Dd(e,t){let n=t?.trim().toLowerCase();return e.keywords.find(e=>e===n)??e.fallback}function Od(e,t,n){if(n==null){e.removeAttribute(t);return}e.setAttribute(t,n)}var kd=/-(?<letter>[a-z])/gu;function Ad(e){return e.replaceAll(kd,(e,t)=>t.toUpperCase())}function jd(e,t){if(typeof e!=`number`||!Number.isFinite(e))throw new j(`invalid-argument`,`${t} must be a finite number`)}function Md(e){return jd(e.yaw,`yaw`),jd(e.pitch,`pitch`),jd(e.fieldOfView,`fieldOfView`),{yaw:t(e.yaw),pitch:t(e.pitch),fieldOfView:t(e.fieldOfView)}}var Nd=/* @__PURE__ */ new Map([[` `,`toggle-play`],[`k`,`toggle-play`],[`j`,`seek-back`],[`l`,`seek-forward`],[`s`,`stop`],[`m`,`toggle-mute`],[`f`,`toggle-fullscreen`],[`0`,`reset-view`],[`+`,`zoom-in`],[`=`,`zoom-in`],[`-`,`zoom-out`],[`ArrowLeft`,`look-left`],[`ArrowRight`,`look-right`],[`ArrowUp`,`look-up`],[`ArrowDown`,`look-down`]]),Pd=/* @__PURE__ */ new Map([[`ArrowLeft`,`seek-back`],[`ArrowRight`,`seek-forward`]]);function Fd(e){if(!e.hasSystemModifier)return e.key.length===1?Nd.get(e.key.toLowerCase()):e.isShiftPressed?Pd.get(e.key):Nd.get(e.key)}var Id=5;function Ld(e){return({player:t})=>{t.seek(t.currentTime+e)}}function Rd(e,t){return({player:n})=>{n.turn(e,t)}}var zd={"toggle-play":e=>{e.togglePlay()},stop:({player:e})=>{e.stop()},"seek-back":Ld(-5),"seek-forward":Ld(5),"toggle-mute":({player:e})=>{e.setMuted(!e.isMuted)},"toggle-fullscreen":e=>{e.toggleFullscreen()},"reset-view":({player:e})=>{e.resetView()},"zoom-in":({player:e})=>{e.zoom(1)},"zoom-out":({player:e})=>{e.zoom(-1)},"look-left":Rd(-5,0),"look-right":Rd(Id,0),"look-up":Rd(0,Id),"look-down":Rd(0,-5)};function Bd(e,t){let n=new AbortController;return e.addEventListener(`keydown`,e=>{if(e.key===`Escape`&&t.isFullscreen()){t.exitFullscreen();return}let n=Fd({key:e.key,isShiftPressed:e.shiftKey,hasSystemModifier:e.ctrlKey||e.altKey||e.metaKey});n&&!Ud(e)&&(e.preventDefault(),zd[n](t))},{signal:n.signal}),()=>{n.abort()}}var Vd=/* @__PURE__ */ new Set([`ArrowLeft`,`ArrowRight`,`ArrowUp`,`ArrowDown`]),Hd=` `;function Ud(e){let[t]=e.composedPath();return t instanceof HTMLInputElement?Vd.has(e.key):t instanceof HTMLButtonElement&&e.key===Hd}var Wd=100,Gd=`data-draggable`,Kd=0,qd=4,Jd=class{surface;player;onTap;pointers=/* @__PURE__ */ new Map;listening=new AbortController;dragDistance=0;constructor(e,t,n){this.surface=e,this.player=t,this.onTap=n;let{signal:r}=this.listening;e.addEventListener(`pointerenter`,this.reflectDraggable,{signal:r}),e.addEventListener(`pointerdown`,this.onPointerDown,{signal:r}),e.addEventListener(`pointermove`,this.onPointerMove,{signal:r}),e.addEventListener(`pointerup`,this.onPointerUp,{signal:r}),e.addEventListener(`pointercancel`,this.onPointerCancel,{signal:r}),e.addEventListener(`lostpointercapture`,this.onPointerCancel,{signal:r}),e.addEventListener(`wheel`,this.onWheel,{passive:!1,signal:r})}detach(){this.listening.abort(),this.pointers.clear(),this.surface.removeAttribute(Gd)}onPointerDown=e=>{(e.pointerType!==`mouse`||e.button===Kd)&&(this.pointers.size===0&&(this.dragDistance=0),this.pointers.set(e.pointerId,{x:e.clientX,y:e.clientY}),this.surface.setPointerCapture(e.pointerId))};onPointerMove=e=>{this.reflectDraggable();let t=this.pointers.get(e.pointerId);if(!t)return;let n={x:e.clientX,y:e.clientY};this.pointers.size===1?this.pan(t,n):this.pinch(e.pointerId,n),this.pointers.set(e.pointerId,n)};onPointerUp=e=>{!this.pointers.delete(e.pointerId)||this.pointers.size>0||this.dragDistance<qd&&this.onTap(e.pointerType)};onPointerCancel=e=>{this.pointers.delete(e.pointerId),this.dragDistance=1/0};onWheel=e=>{e.preventDefault();let t={x:e.clientX,y:e.clientY};this.player.zoom(-e.deltaY/Wd,this.focusAt(t)),this.reflectDraggable()};reflectDraggable=()=>{this.surface.toggleAttribute(Gd,this.player.canPan)};pan(e,t){let n={x:t.x-e.x,y:t.y-e.y};this.dragDistance+=Math.hypot(n.x,n.y),this.player.pan(n)}pinch(e,t){let n=[...this.pointers].find(([t])=>t!==e)?.[1],r=this.pointers.get(e);if(!n||!r)return;this.dragDistance=1/0;let i=$s(Yd(r,n),Yd(t,n)),a={x:(t.x+n.x)/2,y:(t.y+n.y)/2};this.player.zoom(i,this.focusAt(a))}focusAt(e){let t=this.surface.getBoundingClientRect();return{x:(e.x-t.left)/Math.max(t.width,1),y:(e.y-t.top)/Math.max(t.height,1)}}};function Yd(e,t){return Math.hypot(e.x-t.x,e.y-t.y)}function Xd(e,t,n={}){let r=new Jd(e,t,n.onTap??(()=>{Qd(t)}));return()=>{r.detach()}}function Zd(e,t,n={}){let r=()=>e.matches(`:fullscreen`);return Bd(e,{player:t,togglePlay:()=>{Qd(t)},toggleFullscreen:n.toggleFullscreen??(()=>{r()?document.exitFullscreen():e.requestFullscreen()}),isFullscreen:r,exitFullscreen:()=>{document.exitFullscreen()}})}function Qd(e){if(!e.isPaused){e.pause();return}e.play().catch(t=>{e.events.emit(`warning`,{code:`playback-failed`,message:`playback could not start: ${ie(t)}`})})}var $d=class{blob;constructor(e){this.blob=e}size(){return Promise.resolve(this.blob.size)}async read(e){if(e.ensureWithin(this.blob.size,`blob`),e.length===0)return/* @__PURE__ */ new Uint8Array;let t=await this.bytesOf(this.blob.slice(e.offset,e.end));if(t.byteLength!==e.length)throw new j(`source-truncated`,`the blob yielded ${t.byteLength} bytes for a ${e.length}-byte range at ${e.offset}; the file may have changed on disk`);return t}async bytesOf(e){try{return new Uint8Array(await e.arrayBuffer())}catch(e){throw new j(`source-unreadable`,`the blob could not be read`,{cause:e})}}},ef=/^bytes (\d+)-(\d+)\/(\d+|\*)$/u,tf=`*`;function nf(e){let t=ef.exec(e.headers.get(`content-range`)??``);if(!t)return;let[,n,r,i]=t;return{first:Number(n),last:Number(r),total:i===tf?void 0:Number(i)}}var rf=/* @__PURE__ */ new WeakSet;function af(e){return rf.add(e),e}function of(e){return e instanceof j&&rf.has(e)}function sf(e){return M(e,`source-unreadable`)&&e instanceof Error?af(new j(`source-unreadable`,e.message,{cause:e.cause})):e}function cf(e,t,n){return af(new j(`source-unreadable`,`${e} broke off the ${t.length}-byte range at ${t.offset}`,{cause:n}))}function lf(e,t,n){return new j(`source-truncated`,`${e} returned ${t} bytes for a ${n.length}-byte range at ${n.offset}`)}var uf=1e4,df=class{resource;stallTimeoutMs;constructor(e,t={}){this.resource=e,this.stallTimeoutMs=t.stallTimeoutMs??uf}stream(e){return{[Symbol.asyncIterator]:()=>new ff({resource:this.resource,range:e,stallTimeoutMs:this.stallTimeoutMs})}}},ff=class{parts;attempt;received=0;ending=new bl;constructor(e){this.parts=e}async next(){try{let e=await this.parts.resource.askingAgain(()=>this.readChunk());if(e)return{done:!1,value:e}}catch(e){if(!this.ending.hasEnded())throw this.end(),e}return this.end(),yl}return(){return this.end(),Promise.resolve(yl)}async readChunk(){let{resource:e,range:t}=this.parts;if(await e.ensureFits(t),this.ending.hasEnded()||t.length===0)return;this.attempt??=this.attemptAtTheRest();let{attempt:n}=this;try{let e=await this.withinStallTimeout(this.readFrom(n));return this.taken(e)}catch(e){throw this.drop(n),e}}attemptAtTheRest(){let{range:e}=this.parts,t=Fn.of(e.offset+this.received,e.length-this.received),n=new AbortController;return{request:n,body:this.bodyOf(t,n.signal)}}async bodyOf(e,t){let n=await this.parts.resource.rangeAnswer(e,t);return this.ensureAnswers(n,e),n.body?.getReader()??new ReadableStream().getReader()}ensureAnswers(e,t){let n=nf(e);if(!n)return;let r=`${t.offset}-${t.end-1}`,i=`${n.first}-${n.last}`;if(i!==r)throw new j(`source-unreadable`,`${this.parts.resource.url} answered bytes ${i} to a request for bytes ${r}`)}async readFrom(e){let t=await e.body;try{return await t.read()}catch(e){throw re(e)?e:cf(this.parts.resource.url,this.parts.range,e)}}async withinStallTimeout(e){let t,n=new Promise((e,n)=>{t=setTimeout(()=>{n(this.stalled())},this.parts.stallTimeoutMs)});try{return await Promise.race([e,n])}finally{clearTimeout(t)}}stalled(){let{resource:e,range:t,stallTimeoutMs:n}=this.parts;return af(new j(`source-unreadable`,`${e.url} sent nothing of the ${t.length}-byte range at ${t.offset} for ${n} ms`))}taken(e){if(e.done){this.ensureWhole();return}return this.count(e.value),e.value}count(e){let{resource:t,range:n}=this.parts;if(this.received+=e.byteLength,!(this.received<=n.length))throw new j(`source-unreadable`,`${t.url} sent more than the ${n.length}-byte range at ${n.offset}`)}ensureWhole(){let{resource:e,range:t}=this.parts;if(this.received!==t.length)throw lf(e.url,this.received,t)}drop(e){e.request.abort(),this.attempt===e&&(this.attempt=void 0)}end(){this.ending.end(),this.attempt&&this.drop(this.attempt)}},pf=class{resource;constructor(e){this.resource=e}size(){return this.resource.size()}async read(e){return await this.resource.ensureFits(e),e.length===0?/* @__PURE__ */ new Uint8Array:this.resource.askingAgain(()=>this.readOnce(e))}async readOnce(e){let t=await this.resource.rangeAnswer(e),n=await this.bodyOf(t,e);if(n.byteLength!==e.length)throw lf(this.resource.url,n.byteLength,e);return n}async bodyOf(e,t){try{return new Uint8Array(await e.arrayBuffer())}catch(e){throw re(e)?e:cf(this.resource.url,t,e)}}},mf=`bytes=0-0`,hf=`Access-Control-Expose-Headers: Content-Range, Content-Length, Accept-Ranges, ETag`,gf=`Access-Control-Allow-Origin, ${hf}`,_f=`Access-Control-Allow-Origin naming this page's origin, not *; Access-Control-Allow-Credentials: true; ${hf}`,vf=`no-store`;async function yf(e,t,n){try{return await bf(e,t,n)}catch(t){throw re(t)?t:await Cf(e,n,t)}}function bf(e,t,n){return(n.fetch??fetch)(e,{cache:vf,...n.requestInit,method:t.method,headers:{...Of(n.requestInit),...t.headers}})}function xf(e,t){let n=e.requestInit?.signal??void 0,r=n?Sf(n,t):t;return{...e,requestInit:{...e.requestInit,signal:r}}}function Sf(e,t){let n=new AbortController;for(let r of[e,t])r.aborted&&n.abort(r.reason),r.addEventListener(`abort`,()=>{n.abort(r.reason)},{once:!0,signal:n.signal});return n.signal}async function Cf(e,t,n){return await Tf(e,t)?new j(`cors`,`${e} answered, but its server does not allow this page's origin to read it; add CORS headers (${wf(t)})`,{cause:n}):new j(`source-unreadable`,`${e} could not be fetched; check the URL and the network`,{cause:n})}function wf(e){return e.requestInit?.credentials===`include`?_f:gf}async function Tf(e,t){let n=t.fetch??fetch,r=t.requestInit?.signal??null;try{return Ef(await n(e,{method:`HEAD`,mode:`no-cors`,signal:r})),!0}catch(e){if(re(e))throw e;return!1}}function Ef(e){Df(e)}async function Df(e){try{await e.body?.cancel()}catch{}}function Of(e){return Object.fromEntries(new Headers(e?.headers).entries())}var kf=200,Af=/^W\//u;function jf(e){let t=e.headers.get(`etag`),n=e.headers.get(`last-modified`),r=Ff(e);return{...t!==null&&{etag:t},...n!==null&&{lastModified:n},...r!==void 0&&{size:r}}}function Mf(e,t){return e.etag!==void 0&&t.etag!==void 0?Nf(e.etag)===Nf(t.etag):Pf(e.lastModified,t.lastModified)&&Pf(e.size,t.size)}function Nf(e){return e.replace(Af,``)}function Pf(e,t){return e===void 0||t===void 0||e===t}function Ff(e){let t=e.status===kf?Number(e.headers.get(`content-length`)??NaN):nf(e)?.total;return t!==void 0&&Number.isSafeInteger(t)&&t>0?t:void 0}var If=200,Lf=206,Rf=500,zf=[250,1e3],Bf=class{url;options;retryDelaysMs;sizePromise;hasReadRange=!1;version;constructor(e,t={},n){this.url=e,this.options=n?xf(t,n):t,this.retryDelaysMs=t.retryDelaysMs??zf}size(){return this.sizePromise??=this.rememberSize(),this.sizePromise}async ensureFits(e){e.ensureWithin(await this.size(),`resource ${this.url}`)}async askingAgain(e){for(let t of this.retryDelaysMs){try{return await e()}catch(e){if(!of(e))throw e}await Vf(t,this.options.requestInit?.signal)}return e()}async rangeAnswer(e,t){let n=t?xf(this.options,t):this.options,r=await this.requestRange(e,n);if(r.status!==Lf)throw Ef(r),this.refusalOf(r.status);return this.hasReadRange=!0,this.ensureUnchanged(r),r}ensureUnchanged(e){let t=jf(e);if(this.version??=t,!Mf(this.version,t))throw Ef(e),new j(`source-changed`,`${this.url} was replaced while it played; load it again`)}async requestRange(e,t){let n={Range:`bytes=${e.offset}-${e.end-1}`};try{return this.hasReadRange?await bf(this.url,{method:`GET`,headers:n},t):await yf(this.url,{method:`GET`,headers:n},t)}catch(e){throw this.hasReadRange?this.passingOnceAnswered(e):sf(e)}}passingOnceAnswered(e){let t=`${this.url} could not be reached for a byte range`;return re(e)?e:af(new j(`source-unreadable`,t,{cause:e}))}refusalOf(e){if(e===If)return new j(`range-unsupported`,`${this.url} ignores Range requests (answered 200 to a byte range)`);let t=`${this.url} answered ${e} to a byte range`;return e>=Rf?af(new j(`source-unreadable`,t)):new j(`source-unreadable`,t)}async rememberSize(){try{return await this.fetchSize()}catch(e){throw this.sizePromise=void 0,e}}async fetchSize(){let e=await this.request(`HEAD`);if(Ef(e),!e.ok)return this.sizeFromContentRange();this.ensureUnchanged(e);let t=Number(e.headers.get(`content-length`));return Number.isSafeInteger(t)&&t>0?t:this.sizeFromContentRange()}async sizeFromContentRange(){let e=await this.request(`GET`,{Range:mf});if(Ef(e),e.status!==Lf)throw new j(`source-unreadable`,`${this.url} answered ${e.status} to a byte range; cannot determine the file size`);return this.hasReadRange=!0,this.ensureUnchanged(e),this.totalOf(e)}totalOf(e){if(!e.headers.has(`content-range`)&&e.type===`cors`)throw this.hiddenContentRange();let t=nf(e)?.total;if(t===void 0)throw new j(`source-unreadable`,`${this.url} reports neither Content-Length nor Content-Range; cannot determine the file size`);return t}hiddenContentRange(){return new j(`cors`,`${this.url} answered a byte range but hides its Content-Range from this origin; add ${hf}`)}request(e,t){return yf(this.url,{method:e,...t&&{headers:t}},this.options)}};function Vf(e,t){return new Promise((n,r)=>{t?.throwIfAborted();let i=new AbortController,a=setTimeout(()=>{i.abort(),n()},e);t?.addEventListener(`abort`,()=>{clearTimeout(a),r(Hf(t))},{once:!0,signal:i.signal})})}function Hf(e){let t=e?.reason;return t instanceof Error?t:new DOMException(`the read was aborted`,`AbortError`)}var Uf=/* @__PURE__ */ new Set([405,403]),Wf=class{options;constructor(e={}){this.options=e}async exists(e){try{let t=await bf(e,{method:`HEAD`},this.options);if(Ef(t),!Uf.has(t.status))return t.ok;let n=await bf(e,{method:`GET`,headers:{Range:mf}},this.options);return Ef(n),n.ok}catch{return!1}}};function z(e){if(!e)throw Error(`Assertion failed.`)}var Gf=Math.PI/180,Kf=180/Math.PI,qf=e=>{let t=(e%360+360)%360;if(t===0||t===90||t===180||t===270)return t;throw Error(`Invalid rotation ${e}.`)},Jf=[1,0,0,0,1,0,0,0,1],Yf=(e,t,n)=>{let[r,i,,a,o]=e,s=Math.abs(r)*t+Math.abs(a)*n,c=Math.abs(i)*t+Math.abs(o)*n;return tp(tp($f(-t/2,-n/2),e),$f(s/2,c/2))},Xf=e=>{let[t,n]=e;return qf(Rp(Math.atan2(n,Zf(e)?-t:t)*Kf,90))},Zf=e=>{let[t,n,,r,i]=e;return t*i-n*r<0},Qf=e=>{let t=e*Gf,n=Math.round(Math.cos(t)),r=Math.round(Math.sin(t));return[n,r,0,-r,n,0,0,0,1]},$f=(e,t)=>[1,0,0,0,1,0,e,t,1],ep=(e,t)=>[e,0,0,0,t,0,0,0,1],tp=(e,t)=>{let n=Array(9);for(let r=0;r<3;r++)for(let i=0;i<3;i++)n[3*r+i]=e[3*r]*t[i]+e[3*r+1]*t[3+i]+e[3*r+2]*t[6+i];return n},np=e=>e&&e[e.length-1],rp=e=>e>=0&&e<2**32,ip=e=>e>=-(2**31)&&e<2**31,B=e=>{let t=0;for(;e.readBits(1)===0&&t<32;)t++;if(t>=32)throw Error(`Invalid exponential-Golomb code.`);return(1<<t)-1+e.readBits(t)},ap=e=>{let t=B(e);return t&1?t+1>>1:-(t>>1)},op=e=>e.constructor===Uint8Array?e:ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):new Uint8Array(e),sp=e=>e.constructor===DataView?e:ArrayBuffer.isView(e)?new DataView(e.buffer,e.byteOffset,e.byteLength):new DataView(e),cp=globalThis.TextEncoder===void 0?class{constructor(){this.encoding=`utf-8`}encode(e=``){let t=new Uint8Array(3*e.length),n=0;for(let r=0;r<e.length;r++){let i=e.charCodeAt(r);if(i<128)t[n++]=i;else if(i<2048)t[n++]=192|i>>6,t[n++]=128|i&63;else if(i<55296||i>57343)t[n++]=224|i>>12,t[n++]=128|i>>6&63,t[n++]=128|i&63;else{let a=r+1<e.length?e.charCodeAt(r+1):0;i<56320&&a>=56320&&a<=57343?(i=65536+(i-55296<<10)+(a-56320),r++,t[n++]=240|i>>18,t[n++]=128|i>>12&63,t[n++]=128|i>>6&63,t[n++]=128|i&63):(t[n++]=239,t[n++]=191,t[n++]=189)}}return t.slice(0,n)}}:globalThis.TextEncoder,lp=globalThis.TextDecoder===void 0?class{constructor(e=`utf-8`){let t=e.trim().toLowerCase();if(t===`utf-8`||t===`utf8`||t===`unicode-1-1-utf-8`)this.encoding=`utf-8`;else if(t===`utf-16le`||t===`utf-16`)this.encoding=`utf-16le`;else if(t===`utf-16be`)this.encoding=`utf-16be`;else throw RangeError(`The encoding label provided ('${e}') is invalid.`)}decode(e){let t=e?op(e):/* @__PURE__ */ new Uint8Array,n=[];if(this.encoding===`utf-8`){let e=t.length>=3&&t[0]===239&&t[1]===187&&t[2]===191?3:0;for(;e<t.length;){let r=t[e];if(r<128){n.push(r),e++;continue}let i,a;if(r>=194&&r<224)i=1,a=r&31;else if(r>=224&&r<240)i=2,a=r&15;else if(r>=240&&r<245)i=3,a=r&7;else{n.push(65533),e++;continue}let o=r===224?160:r===240?144:128,s=r===237?159:r===244?143:191,c=1;for(;c<=i;c++){let n=e+c<t.length?t[e+c]:0;if(n<o||n>s)break;a=a<<6|n&63,o=128,s=191}e+=c,c<=i?n.push(65533):a>=65536?(a-=65536,n.push(55296|a>>10,56320|a&1023)):n.push(a)}}else{let e=this.encoding===`utf-16le`,r=e?255:254,i=e?254:255,a=t.length>=2&&t[0]===r&&t[1]===i?2:0;for(;a+1<t.length;){let r=e?t[a]|t[a+1]<<8:t[a]<<8|t[a+1];if(a+=2,r>=55296&&r<=56319){let i=a+1<t.length?e?t[a]|t[a+1]<<8:t[a]<<8|t[a+1]:-1;i>=56320&&i<=57343?(n.push(r,i),a+=2):n.push(65533)}else r>=56320&&r<=57343?n.push(65533):n.push(r)}a<t.length&&n.push(65533)}let r=``;for(let e=0;e<n.length;e+=8192)r+=String.fromCharCode(...n.slice(e,e+8192));return r}}:globalThis.TextDecoder,up=/* #__PURE__ */ new lp,dp=/* #__PURE__ */ new cp,fp=e=>Object.fromEntries(Object.entries(e).map(([e,t])=>[t,e])),pp={bt709:1,bt470bg:5,smpte170m:6,bt2020:9,smpte432:12},mp=/* #__PURE__ */ fp(pp),hp={bt709:1,smpte170m:6,linear:8,"iec61966-2-1":13,pq:16,hlg:18},gp=/* #__PURE__ */ fp(hp),_p={rgb:0,bt709:1,bt470bg:5,smpte170m:6,"bt2020-ncl":9},vp=/* #__PURE__ */ fp(_p),yp=e=>!!e&&!!e.primaries&&!!e.transfer&&!!e.matrix&&e.fullRange!==void 0,bp=e=>!e||e.primaries==null&&e.transfer==null&&e.matrix==null&&e.fullRange==null,xp={primaries:void 0,transfer:void 0,matrix:void 0,fullRange:void 0},Sp=e=>e instanceof ArrayBuffer||typeof SharedArrayBuffer<`u`&&e instanceof SharedArrayBuffer||ArrayBuffer.isView(e),Cp=class{constructor(){this.currentPromise=Promise.resolve(),this.pending=0}async acquire(){let e,t=new Promise(t=>{let n=!1;e=()=>{n||=(t(),this.pending--,!0)}}),n=this.currentPromise;return this.currentPromise=t,this.pending++,await n,e}},wp=/^[0-9a-fA-F]+$/,Tp=e=>[...e].map(e=>e.toString(16).padStart(2,`0`)).join(``),Ep=e=>{z(e.length%2==0);let t=new Uint8Array(e.length/2);for(let n=0;n<e.length;n+=2)t[n/2]=parseInt(e.slice(n,n+2),16);return t},Dp=e=>(e=e>>1&1431655765|(e&1431655765)<<1,e=e>>2&858993459|(e&858993459)<<2,e=e>>4&252645135|(e&252645135)<<4,e=e>>8&16711935|(e&16711935)<<8,e=e>>16&65535|(e&65535)<<16,e>>>0),Op=(e,t,n)=>{let r=0,i=e.length-1,a=-1;for(;r<=i;){let o=r+i>>1,s=n(e[o]);s===t?(a=o,i=o-1):s<t?r=o+1:i=o-1}return a},kp=(e,t,n)=>{let r=0,i=e.length-1,a=-1;for(;r<=i;){let o=r+(i-r+1)/2|0;n(e[o])<=t?(a=o,r=o+1):i=o-1}return a},Ap=()=>{let e,t;return{promise:new Promise((n,r)=>{e=n,t=r}),resolve:e,reject:t}},jp=(e,t)=>{let n=e.indexOf(t);n!==-1&&e.splice(n,1)},Mp=(e,t)=>{for(let n=e.length-1;n>=0;n--)if(t(e[n]))return n;return-1},Np=e=>{throw Error(`Unexpected value: ${e}`)},Pp=(e,t,n)=>{let r=e.getUint8(t),i=e.getUint8(t+1),a=e.getUint8(t+2);return n?r|i<<8|a<<16:r<<16|i<<8|a},Fp=(e,t,n,r)=>{n>>>=0,n&=16777215,r?(e.setUint8(t,n&255),e.setUint8(t+1,n>>>8&255),e.setUint8(t+2,n>>>16&255)):(e.setUint8(t,n>>>16&255),e.setUint8(t+1,n>>>8&255),e.setUint8(t+2,n&255))},Ip=(e,t,n)=>Math.max(t,Math.min(n,e)),Lp=e=>{let t=Math.round(e);return Math.abs(e/t-1)<10*2**-52?t:e},Rp=(e,t)=>Math.round(e/t)*t,zp=(e,t)=>Math.round(e*t)/t,Bp=e=>{let t=0;for(;e!==0;)e&=e-1,t++;return t},Vp=/^[a-z]{3}$/,Hp=e=>Vp.test(e),Up=1e6*(1+2**-52),Wp=(e,t)=>{let n=e<0?-1:1;e=Math.abs(e);let r=0,i=1,a=1,o=0,s=e;for(;;){let e=Math.floor(s),c=e*a+r,l=e*o+i;if(l>t)return{num:n*a,den:o};if(r=a,i=o,a=c,o=l,s=1/(s-e),!isFinite(s))break}return{num:n*a,den:o}},Gp=null,Kp=()=>Gp===null?Gp=!(typeof navigator>`u`||!navigator.vendor?.includes(`Google Inc`)&&!/Chrome/.test(navigator.userAgent)):Gp,qp=(/* #__PURE__ */ (async()=>{})()).constructor,Jp=e=>e instanceof qp||e instanceof Promise||typeof e?.then==`function`,Yp=function*(e){for(let t in e){let n=e[t];n!==void 0&&(yield{key:t,value:n})}},Xp=(e,t)=>{if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0},Zp=()=>{Symbol.dispose??=Symbol(`Symbol.dispose`)},Qp=e=>typeof e==`number`&&!Number.isNaN(e),$p=(e,t)=>{let n=0;for(let r=0;r<e.length;r++)t(e[r])&&n++;return n},em=(e,t)=>{let n=-1,r=1/0;for(let i=0;i<e.length;i++){let a=t(e[i]);a<r&&(r=a,n=i)}return n},tm=e=>{z(Number.isInteger(e.num)),z(Number.isInteger(e.den)),z(e.den!==0);let t=Math.abs(e.num),n=Math.abs(e.den);for(;n!==0;){let e=t%n;t=n,n=e}let r=t||1;return{num:e.num/r,den:e.den/r}},nm=e=>Array.isArray(e)?e:[e],rm=class{constructor(){this._listeners=/* @__PURE__ */ new Map}on(e,t,n){this._listeners.has(e)||this._listeners.set(e,/* @__PURE__ */ new Set);let r={fn:t,once:n?.once??!1};return this._listeners.get(e).add(r),()=>{this._listeners.get(e)?.delete(r)}}_emit(...e){let[t,n]=e,r=this._listeners.get(t);if(r)for(let e of r){try{e.fn(n)}catch(e){console.error(e)}e.once&&r.delete(e)}}},im=e=>typeof e==`object`&&!!e&&Object.getPrototypeOf(e)===Object.prototype&&Object.values(e).every(e=>typeof e==`string`),am;(function(e){e[e.Silent=0]=`Silent`,e[e.Errors=1]=`Errors`,e[e.Warnings=2]=`Warnings`,e[e.Info=3]=`Info`})(am||={});var om=class e{constructor(){}static get level(){return e._level}static set level(t){if(t!==am.Silent&&t!==am.Errors&&t!==am.Warnings&&t!==am.Info)throw TypeError(`Invalid log level. Use one of the values of the LogLevel enum.`);e._level=t}static get _emitter(){return e._emitterInstance??=new rm}static on(t,n,r){return e._emitter.on(t,n,r)}static _error(...t){e._emitter._emit(`error`,t),e._level>=am.Errors&&console.error(...t)}static _warn(...t){e._emitter._emit(`warn`,t),e._level>=am.Warnings&&console.warn(...t)}static _info(...t){e._emitter._emit(`info`,t),e._level>=am.Info&&console.info(...t)}};om._level=am.Info,om._emitterInstance=null;var sm=class{constructor(e,t){if(this.data=e,this.mimeType=t,!(e instanceof Uint8Array))throw TypeError(`data must be a Uint8Array.`);if(typeof t!=`string`)throw TypeError(`mimeType must be a string.`)}},cm=class{constructor(e,t,n,r){if(this.data=e,this.mimeType=t,this.name=n,this.description=r,!(e instanceof Uint8Array))throw TypeError(`data must be a Uint8Array.`);if(t!==void 0&&typeof t!=`string`)throw TypeError(`mimeType, when provided, must be a string.`);if(n!==void 0&&typeof n!=`string`)throw TypeError(`name, when provided, must be a string.`);if(r!==void 0&&typeof r!=`string`)throw TypeError(`description, when provided, must be a string.`)}},lm=e=>{if(!e||typeof e!=`object`)throw TypeError(`tags must be an object.`);if(e.title!==void 0&&typeof e.title!=`string`)throw TypeError(`tags.title, when provided, must be a string.`);if(e.description!==void 0&&typeof e.description!=`string`)throw TypeError(`tags.description, when provided, must be a string.`);if(e.artist!==void 0&&typeof e.artist!=`string`)throw TypeError(`tags.artist, when provided, must be a string.`);if(e.album!==void 0&&typeof e.album!=`string`)throw TypeError(`tags.album, when provided, must be a string.`);if(e.albumArtist!==void 0&&typeof e.albumArtist!=`string`)throw TypeError(`tags.albumArtist, when provided, must be a string.`);if(e.trackNumber!==void 0&&(!Number.isInteger(e.trackNumber)||e.trackNumber<=0))throw TypeError(`tags.trackNumber, when provided, must be a positive integer.`);if(e.tracksTotal!==void 0&&(!Number.isInteger(e.tracksTotal)||e.tracksTotal<=0))throw TypeError(`tags.tracksTotal, when provided, must be a positive integer.`);if(e.discNumber!==void 0&&(!Number.isInteger(e.discNumber)||e.discNumber<=0))throw TypeError(`tags.discNumber, when provided, must be a positive integer.`);if(e.discsTotal!==void 0&&(!Number.isInteger(e.discsTotal)||e.discsTotal<=0))throw TypeError(`tags.discsTotal, when provided, must be a positive integer.`);if(e.genre!==void 0&&typeof e.genre!=`string`)throw TypeError(`tags.genre, when provided, must be a string.`);if(e.date!==void 0&&(!(e.date instanceof Date)||Number.isNaN(e.date.getTime())))throw TypeError(`tags.date, when provided, must be a valid Date.`);if(e.lyrics!==void 0&&typeof e.lyrics!=`string`)throw TypeError(`tags.lyrics, when provided, must be a string.`);if(e.images!==void 0){if(!Array.isArray(e.images))throw TypeError(`tags.images, when provided, must be an array.`);for(let t of e.images){if(!t||typeof t!=`object`)throw TypeError(`Each image in tags.images must be an object.`);if(!(t.data instanceof Uint8Array))throw TypeError(`Each image.data must be a Uint8Array.`);if(typeof t.mimeType!=`string`)throw TypeError(`Each image.mimeType must be a string.`);if(![`coverFront`,`coverBack`,`unknown`].includes(t.kind))throw TypeError(`Each image.kind must be 'coverFront', 'coverBack', or 'unknown'.`)}}if(e.comment!==void 0&&typeof e.comment!=`string`)throw TypeError(`tags.comment, when provided, must be a string.`);if(e.raw!==void 0){if(!e.raw||typeof e.raw!=`object`)throw TypeError(`tags.raw, when provided, must be an object.`);for(let t of Object.values(e.raw))if(t!==null&&typeof t!=`string`&&!(Array.isArray(t)&&t.every(e=>typeof e==`string`))&&!(t instanceof Uint8Array)&&!(t instanceof sm)&&!(t instanceof cm)&&!im(t))throw TypeError(`Each value in tags.raw must be a string, string array, Uint8Array, RichImageData, AttachedFile, Record<string, string>, or null.`)}},um={default:!0,primary:!0,forced:!1,original:!1,commentary:!1,hearingImpaired:!1,visuallyImpaired:!1},dm=e=>{if(!e||typeof e!=`object`)throw TypeError(`disposition must be an object.`);if(e.default!==void 0&&typeof e.default!=`boolean`)throw TypeError(`disposition.default must be a boolean.`);if(e.primary!==void 0&&typeof e.primary!=`boolean`)throw TypeError(`disposition.primary must be a boolean.`);if(e.forced!==void 0&&typeof e.forced!=`boolean`)throw TypeError(`disposition.forced must be a boolean.`);if(e.original!==void 0&&typeof e.original!=`boolean`)throw TypeError(`disposition.original must be a boolean.`);if(e.commentary!==void 0&&typeof e.commentary!=`boolean`)throw TypeError(`disposition.commentary must be a boolean.`);if(e.hearingImpaired!==void 0&&typeof e.hearingImpaired!=`boolean`)throw TypeError(`disposition.hearingImpaired must be a boolean.`);if(e.visuallyImpaired!==void 0&&typeof e.visuallyImpaired!=`boolean`)throw TypeError(`disposition.visuallyImpaired must be a boolean.`)},fm=class e{constructor(e){this.bytes=e,this.pos=0}seekToByte(e){this.pos=8*e}readBit(){let e=Math.floor(this.pos/8),t=this.bytes[e]??0,n=7-(this.pos&7),r=(t&1<<n)>>n;return this.pos++,r}readBits(e){if(e===1)return this.readBit();let t=0;for(let n=0;n<e;n++)t<<=1,t|=this.readBit();return t}writeBits(e,t){let n=this.pos+e;for(let e=this.pos;e<n;e++){let r=Math.floor(e/8),i=this.bytes[r],a=7-(e&7);i&=~(1<<a),i|=(t&1<<n-e-1)>>n-e-1<<a,this.bytes[r]=i}this.pos=n}copyBits(e,t){let n=0;for(;n<e-7;n+=8)this.writeBits(8,t.readBits(8));let r=e-n;r>0&&this.writeBits(r,t.readBits(r))}readAlignedByte(){if(this.pos%8!=0)throw Error(`Bitstream is not byte-aligned.`);let e=this.pos/8,t=this.bytes[e]??0;return this.pos+=8,t}skipBits(e){this.pos+=e}getBitsLeft(){return this.bytes.length*8-this.pos}clone(){let t=new e(this.bytes);return t.pos=this.pos,t}},pm=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],mm=[-1,1,2,3,4,5,6,8],hm=e=>{if(!e||e.byteLength<2)throw TypeError(`AAC description must be at least 2 bytes long.`);let t=new fm(e),n=gm(t),{frequencyIndex:r,sampleRate:i}=_m(t),a=t.readBits(4),o=null;a>=1&&a<=7&&(o=mm[a]);let s=n,c=!1,l=i;if(n===5||n===29)c=n===29,l=_m(t).sampleRate,s=gm(t),s===22&&t.skipBits(4);else for(;t.getBitsLeft()>15;){let e=t.pos;if(t.readBits(11)!==695){t.pos=e+1;continue}gm(t)===5&&t.readBits(1)&&(l=_m(t).sampleRate,t.getBitsLeft()>11&&t.readBits(11)===1352&&(c=!!t.readBits(1)));break}return o!==null&&o>1&&(c=!1),{objectType:n,coreObjectType:s,frequencyIndex:r,channelConfiguration:a,outputSampleRate:l,outputNumberOfChannels:c&&o===1?2:o}},gm=e=>{let t=e.readBits(5);return t===31?32+e.readBits(6):t},_m=e=>{let t=e.readBits(4);return t===15?{frequencyIndex:t,sampleRate:e.readBits(24)}:{frequencyIndex:t,sampleRate:t<pm.length?pm[t]:null}},vm=e=>{let t=e.objectType===5||e.objectType===29,n=e.objectType===29,r=t?e.outputSampleRate/2:e.outputSampleRate,i=n?1:e.outputNumberOfChannels,a=mm.indexOf(i);if(a===-1)throw TypeError(`Unsupported number of channels: ${e.outputNumberOfChannels}`);let o=16;e.objectType>=32&&(o+=6),xm(r)===15&&(o+=24),t&&(o+=9,xm(e.outputSampleRate)===15&&(o+=24));let s=Math.ceil(o/8),c=new Uint8Array(s),l=new fm(c);return ym(l,e.objectType),bm(l,r),l.writeBits(4,a),t&&(bm(l,e.outputSampleRate),ym(l,2)),l.writeBits(3,0),c},ym=(e,t)=>{t<32?e.writeBits(5,t):(e.writeBits(5,31),e.writeBits(6,t-32))},bm=(e,t)=>{let n=xm(t);e.writeBits(4,n),n===15&&e.writeBits(24,t)},xm=e=>{let t=pm.indexOf(e);return t===-1?15:t},Sm=[48e3,44100,32e3],Cm=[24e3,22050,16e3],wm;(function(e){e[e.NON_IDR_SLICE=1]=`NON_IDR_SLICE`,e[e.SLICE_DPA=2]=`SLICE_DPA`,e[e.SLICE_DPB=3]=`SLICE_DPB`,e[e.SLICE_DPC=4]=`SLICE_DPC`,e[e.IDR=5]=`IDR`,e[e.SEI=6]=`SEI`,e[e.SPS=7]=`SPS`,e[e.PPS=8]=`PPS`,e[e.AUD=9]=`AUD`,e[e.SPS_EXT=13]=`SPS_EXT`})(wm||={});var Tm;(function(e){e[e.RASL_N=8]=`RASL_N`,e[e.RASL_R=9]=`RASL_R`,e[e.BLA_W_LP=16]=`BLA_W_LP`,e[e.RSV_IRAP_VCL23=23]=`RSV_IRAP_VCL23`,e[e.VPS_NUT=32]=`VPS_NUT`,e[e.SPS_NUT=33]=`SPS_NUT`,e[e.PPS_NUT=34]=`PPS_NUT`,e[e.AUD_NUT=35]=`AUD_NUT`,e[e.PREFIX_SEI_NUT=39]=`PREFIX_SEI_NUT`,e[e.SUFFIX_SEI_NUT=40]=`SUFFIX_SEI_NUT`})(Tm||={});var Em=function*(e){let t=0,n=-1;for(;t<e.length-2;){let r=e.indexOf(0,t);if(r===-1||r>=e.length-2)break;t=r;let i=0;if(t+3<e.length&&e[t+1]===0&&e[t+2]===0&&e[t+3]===1?i=4:e[t+1]===0&&e[t+2]===1&&(i=3),i===0){t++;continue}n!==-1&&t>n&&(yield{offset:n,length:t-n}),n=t+i,t=n}n!==-1&&n<e.length&&(yield{offset:n,length:e.length-n})},Dm=function*(e,t){let n=0,r=new DataView(e.buffer,e.byteOffset,e.byteLength);for(;n+t<=e.length;){let e;t===1?e=r.getUint8(n):t===2?e=r.getUint16(n,!1):t===3?e=Pp(r,n,!1):(z(t===4),e=r.getUint32(n,!1)),n+=t,yield{offset:n,length:e},n+=e}},Om=(e,t)=>t.description?Dm(e,(op(t.description)[4]&3)+1):Em(e),km=e=>e&31,Am=e=>{let t=[],n=e.length;for(let r=0;r<n;r++)r+2<n&&e[r]===0&&e[r+1]===0&&e[r+2]===3?(t.push(0,0),r+=2):t.push(e[r]);return new Uint8Array(t)};new Uint8Array([0,0,0,1]);var jm=(e,t)=>{let n=e.reduce((e,n)=>e+t+n.byteLength,0),r=new Uint8Array(n),i=0;for(let n of e){let e=new DataView(r.buffer,r.byteOffset,r.byteLength);switch(t){case 1:e.setUint8(i,n.byteLength);break;case 2:e.setUint16(i,n.byteLength,!1);break;case 3:Fp(e,i,n.byteLength,!1);break;case 4:e.setUint32(i,n.byteLength,!1)}i+=t,r.set(n,i),i+=n.byteLength}return r},Mm=e=>{try{let t=[],n=[],r=[];for(let i of Em(e)){let a=e.subarray(i.offset,i.offset+i.length),o=km(a[0]);o===wm.SPS?t.push(a):o===wm.PPS?n.push(a):o===wm.SPS_EXT&&r.push(a)}if(t.length===0||n.length===0)return null;let i=t[0],a=Im(i);z(a!==null);let o=a.profileIdc===100||a.profileIdc===110||a.profileIdc===122||a.profileIdc===144;return{configurationVersion:1,avcProfileIndication:a.profileIdc,profileCompatibility:a.constraintFlags,avcLevelIndication:a.levelIdc,lengthSizeMinusOne:3,sequenceParameterSets:t,pictureParameterSets:n,chromaFormat:o?a.chromaFormatIdc:null,bitDepthLumaMinus8:o?a.bitDepthLumaMinus8:null,bitDepthChromaMinus8:o?a.bitDepthChromaMinus8:null,sequenceParameterSetExt:o?r:null}}catch(e){return om._error(`Error building AVC Decoder Configuration Record:`,e),null}},Nm=e=>{let t=[];t.push(e.configurationVersion),t.push(e.avcProfileIndication),t.push(e.profileCompatibility),t.push(e.avcLevelIndication),t.push(252|e.lengthSizeMinusOne&3),t.push(224|e.sequenceParameterSets.length&31);for(let n of e.sequenceParameterSets){let e=n.byteLength;t.push(e>>8),t.push(e&255);for(let r=0;r<e;r++)t.push(n[r])}t.push(e.pictureParameterSets.length);for(let n of e.pictureParameterSets){let e=n.byteLength;t.push(e>>8),t.push(e&255);for(let r=0;r<e;r++)t.push(n[r])}if((e.avcProfileIndication===100||e.avcProfileIndication===110||e.avcProfileIndication===122||e.avcProfileIndication===144)&&e.chromaFormat!==null){z(e.bitDepthLumaMinus8!==null),z(e.bitDepthChromaMinus8!==null),z(e.sequenceParameterSetExt!==null),t.push(252|e.chromaFormat&3),t.push(248|e.bitDepthLumaMinus8&7),t.push(248|e.bitDepthChromaMinus8&7),t.push(e.sequenceParameterSetExt.length);for(let n of e.sequenceParameterSetExt){let e=n.byteLength;t.push(e>>8),t.push(e&255);for(let r=0;r<e;r++)t.push(n[r])}}return new Uint8Array(t)},Pm=e=>{try{let t=sp(e),n=0,r=t.getUint8(n++),i=t.getUint8(n++),a=t.getUint8(n++),o=t.getUint8(n++),s=t.getUint8(n++)&3,c=t.getUint8(n++)&31,l=[];for(let r=0;r<c;r++){let r=t.getUint16(n,!1);n+=2,l.push(e.subarray(n,n+r)),n+=r}let u=t.getUint8(n++),d=[];for(let r=0;r<u;r++){let r=t.getUint16(n,!1);n+=2,d.push(e.subarray(n,n+r)),n+=r}let f={configurationVersion:r,avcProfileIndication:i,profileCompatibility:a,avcLevelIndication:o,lengthSizeMinusOne:s,sequenceParameterSets:l,pictureParameterSets:d,chromaFormat:null,bitDepthLumaMinus8:null,bitDepthChromaMinus8:null,sequenceParameterSetExt:null};if((i===100||i===110||i===122||i===144)&&n+4<=e.length){let r=t.getUint8(n++)&3,i=t.getUint8(n++)&7,a=t.getUint8(n++)&7,o=t.getUint8(n++);f.chromaFormat=r,f.bitDepthLumaMinus8=i,f.bitDepthChromaMinus8=a;let s=[];for(let r=0;r<o;r++){let r=t.getUint16(n,!1);n+=2,s.push(e.subarray(n,n+r)),n+=r}f.sequenceParameterSetExt=s}return f}catch(e){return om._error(`Error deserializing AVC Decoder Configuration Record:`,e),null}},Fm={1:{num:1,den:1},2:{num:12,den:11},3:{num:10,den:11},4:{num:16,den:11},5:{num:40,den:33},6:{num:24,den:11},7:{num:20,den:11},8:{num:32,den:11},9:{num:80,den:33},10:{num:18,den:11},11:{num:15,den:11},12:{num:64,den:33},13:{num:160,den:99},14:{num:4,den:3},15:{num:3,den:2},16:{num:2,den:1}},Im=e=>{try{let t=Am(e),n=new fm(t);if(n.skipBits(1),n.skipBits(2),n.readBits(5)!==7)return null;let r=n.readAlignedByte(),i=n.readAlignedByte(),a=n.readAlignedByte();B(n);let o=1,s=0,c=0,l=0;if((r===100||r===110||r===122||r===244||r===44||r===83||r===86||r===118||r===128)&&(o=B(n),o===3&&(l=n.readBits(1)),s=B(n),c=B(n),n.skipBits(1),n.readBits(1))){for(let e=0;e<(o===3?12:8);e++)if(n.readBits(1)){let t=e<6?16:64,r=8,i=8;for(let e=0;e<t;e++){if(i!==0){let e=ap(n);i=(r+e+256)%256}r=i===0?r:i}}}B(n);let u=B(n);if(u===0)B(n);else if(u===1){n.skipBits(1),ap(n),ap(n);let e=B(n);for(let t=0;t<e;t++)ap(n)}B(n),n.skipBits(1);let d=B(n),f=B(n),p=16*(d+1),m=16*(f+1),h=p,g=m,_=n.readBits(1);if(_||n.skipBits(1),n.skipBits(1),n.readBits(1)){let e=B(n),t=B(n),r=B(n),i=B(n),a,s;if((l===0?o:0)===0)a=1,s=2-_;else{let e=o===3?1:2,t=o===1?2:1;a=e,s=t*(2-_)}h-=a*(e+t),g-=s*(r+i)}let v=2,y=2,b=2,x=0,S={num:1,den:1},C=null,w=null,T=null,E=null,D=n.pos;if(n.readBits(1)){if(n.readBits(1)){let e=n.readBits(8);if(e===255)S={num:n.readBits(16),den:n.readBits(16)};else{let t=Fm[e];t&&(S=t)}}n.readBits(1)&&n.skipBits(1),n.readBits(1)&&(n.skipBits(3),x=n.readBits(1),n.readBits(1)&&(v=n.readBits(8),y=n.readBits(8),b=n.readBits(8))),n.readBits(1)&&(B(n),B(n)),n.readBits(1)&&(n.skipBits(32),n.skipBits(32),n.skipBits(1));let e=n.readBits(1);e&&Lm(n);let t=n.readBits(1);t&&Lm(n),(e||t)&&n.skipBits(1),n.skipBits(1),T=n.pos,E=n.readBits(1),E&&(n.skipBits(1),B(n),B(n),B(n),B(n),C=B(n),w=B(n))}if(C===null){z(w===null);let e=i&16;if((r===44||r===86||r===100||r===110||r===122||r===244)&&e)C=0,w=0;else{let e=d+1,t=f+1,n=(2-_)*t,r=Rh.find(e=>e.level>=a)??np(Rh),i=Math.min(Math.floor(r.maxDpbMbs/(e*n)),16);C=i,w=i}}return z(w!==null),{emulationUnpreventedBytes:t,profileIdc:r,constraintFlags:i,levelIdc:a,frameMbsOnlyFlag:_,chromaFormatIdc:o,bitDepthLumaMinus8:s,bitDepthChromaMinus8:c,codedWidth:p,codedHeight:m,displayWidth:h,displayHeight:g,pixelAspectRatio:S,colourPrimaries:v,matrixCoefficients:b,transferCharacteristics:y,fullRangeFlag:x,numReorderFrames:C,maxDecFrameBuffering:w,vuiParametersFlagBitOffset:D,bitstreamRestrictionFlagBitOffset:T,bitstreamRestrictionFlag:E}}catch(e){return om._error(`Error parsing AVC SPS:`,e),null}},Lm=e=>{let t=B(e);e.skipBits(4),e.skipBits(4);for(let n=0;n<=t;n++)B(e),B(e),e.skipBits(1);e.skipBits(5),e.skipBits(5),e.skipBits(5),e.skipBits(5)},Rm=(e,t)=>t.description?Dm(e,(op(t.description)[21]&3)+1):Em(e),zm=e=>e>>1&63,Bm=e=>{try{let t=new fm(Am(e));t.skipBits(16),t.readBits(4);let n=t.readBits(3),r=t.readBits(1),{general_profile_space:i,general_tier_flag:a,general_profile_idc:o,general_profile_compatibility_flags:s,general_constraint_indicator_flags:c,general_level_idc:l}=Hm(t,n);B(t);let u=B(t),d=0;u===3&&(d=t.readBits(1));let f=B(t),p=B(t),m=f,h=p;if(t.readBits(1)){let e=B(t),n=B(t),r=B(t),i=B(t),a=1,o=1,s=d===0?u:0;s===1?(a=2,o=2):s===2&&(a=2,o=1),m-=(e+n)*a,h-=(r+i)*o}let g=B(t),_=B(t);B(t);let v=t.readBits(1)?0:n,y=0;for(let e=v;e<=n;e++)B(t),y=B(t),B(t);if(B(t),B(t),B(t),B(t),B(t),B(t),t.readBits(1)&&t.readBits(1)&&Um(t),t.skipBits(1),t.skipBits(1),t.readBits(1)&&(t.skipBits(4),t.skipBits(4),B(t),B(t),t.skipBits(1)),Wm(t,B(t)),t.readBits(1)){let e=B(t);for(let n=0;n<e;n++)B(t),t.skipBits(1)}t.skipBits(1),t.skipBits(1);let b=2,x=2,S=2,C=0,w=0,T={num:1,den:1};if(t.readBits(1)){let e=Km(t,n);T=e.pixelAspectRatio,b=e.colourPrimaries,x=e.transferCharacteristics,S=e.matrixCoefficients,C=e.fullRangeFlag,w=e.minSpatialSegmentationIdc}return{displayWidth:m,displayHeight:h,pixelAspectRatio:T,colourPrimaries:b,transferCharacteristics:x,matrixCoefficients:S,fullRangeFlag:C,maxDecFrameBuffering:y+1,spsMaxSubLayersMinus1:n,spsTemporalIdNestingFlag:r,generalProfileSpace:i,generalTierFlag:a,generalProfileIdc:o,generalProfileCompatibilityFlags:s,generalConstraintIndicatorFlags:c,generalLevelIdc:l,chromaFormatIdc:u,bitDepthLumaMinus8:g,bitDepthChromaMinus8:_,minSpatialSegmentationIdc:w}}catch(e){return om._error(`Error parsing HEVC SPS:`,e),null}},Vm=e=>{try{let t=[],n=[],r=[],i=[];for(let a of Em(e)){let o=e.subarray(a.offset,a.offset+a.length),s=zm(o[0]);s===Tm.VPS_NUT?t.push(o):s===Tm.SPS_NUT?n.push(o):s===Tm.PPS_NUT?r.push(o):(s===Tm.PREFIX_SEI_NUT||s===Tm.SUFFIX_SEI_NUT)&&i.push(o)}if(n.length===0||r.length===0)return null;let a=Bm(n[0]);if(!a)return null;let o=0;if(r.length>0){let e=r[0],t=new fm(Am(e));t.skipBits(16),B(t),B(t),t.skipBits(1),t.skipBits(1),t.skipBits(3),t.skipBits(1),t.skipBits(1),B(t),B(t),ap(t),t.skipBits(1),t.skipBits(1),t.readBits(1)&&B(t),ap(t),ap(t),t.skipBits(1),t.skipBits(1),t.skipBits(1),t.skipBits(1);let n=t.readBits(1),i=t.readBits(1);o=!n&&!i?0:n&&!i?2:!n&&i?3:0}let s=[...t.length?[{arrayCompleteness:1,nalUnitType:Tm.VPS_NUT,nalUnits:t}]:[],...n.length?[{arrayCompleteness:1,nalUnitType:Tm.SPS_NUT,nalUnits:n}]:[],...r.length?[{arrayCompleteness:1,nalUnitType:Tm.PPS_NUT,nalUnits:r}]:[],...i.length?[{arrayCompleteness:1,nalUnitType:zm(i[0][0]),nalUnits:i}]:[]];return{configurationVersion:1,generalProfileSpace:a.generalProfileSpace,generalTierFlag:a.generalTierFlag,generalProfileIdc:a.generalProfileIdc,generalProfileCompatibilityFlags:a.generalProfileCompatibilityFlags,generalConstraintIndicatorFlags:a.generalConstraintIndicatorFlags,generalLevelIdc:a.generalLevelIdc,minSpatialSegmentationIdc:a.minSpatialSegmentationIdc,parallelismType:o,chromaFormatIdc:a.chromaFormatIdc,bitDepthLumaMinus8:a.bitDepthLumaMinus8,bitDepthChromaMinus8:a.bitDepthChromaMinus8,avgFrameRate:0,constantFrameRate:0,numTemporalLayers:a.spsMaxSubLayersMinus1+1,temporalIdNested:a.spsTemporalIdNestingFlag,lengthSizeMinusOne:3,arrays:s}}catch(e){return om._error(`Error building HEVC Decoder Configuration Record:`,e),null}},Hm=(e,t)=>{let n=e.readBits(2),r=e.readBits(1),i=e.readBits(5),a=0;for(let t=0;t<32;t++)a=a<<1|e.readBits(1);let o=/* @__PURE__ */ new Uint8Array(6);for(let t=0;t<6;t++)o[t]=e.readBits(8);let s=e.readBits(8),c=[],l=[];for(let n=0;n<t;n++)c.push(e.readBits(1)),l.push(e.readBits(1));if(t>0)for(let n=t;n<8;n++)e.skipBits(2);for(let n=0;n<t;n++)c[n]&&e.skipBits(88),l[n]&&e.skipBits(8);return{general_profile_space:n,general_tier_flag:r,general_profile_idc:i,general_profile_compatibility_flags:a,general_constraint_indicator_flags:o,general_level_idc:s}},Um=e=>{for(let t=0;t<4;t++)for(let n=0;n<(t===3?2:6);n++)if(!e.readBits(1))B(e);else{let n=Math.min(64,1<<4+(t<<1));t>1&&ap(e);for(let t=0;t<n;t++)ap(e)}},Wm=(e,t)=>{let n=[];for(let r=0;r<t;r++)n[r]=Gm(e,r,t,n)},Gm=(e,t,n,r)=>{let i=0,a=0,o=0;if(t!==0&&(a=e.readBits(1)),a){o=t===n?t-(B(e)+1):t-1,e.readBits(1),B(e);let a=r[o]??0;for(let t=0;t<=a;t++)e.readBits(1)||e.readBits(1);i=r[o]}else{let t=B(e),n=B(e);for(let n=0;n<t;n++)B(e),e.readBits(1);for(let t=0;t<n;t++)B(e),e.readBits(1);i=t+n}return i},Km=(e,t)=>{let n=2,r=2,i=2,a=0,o=0,s={num:1,den:1};if(e.readBits(1)){let t=e.readBits(8);if(t===255)s={num:e.readBits(16),den:e.readBits(16)};else{let e=Fm[t];e&&(s=e)}}return e.readBits(1)&&e.readBits(1),e.readBits(1)&&(e.readBits(3),a=e.readBits(1),e.readBits(1)&&(n=e.readBits(8),r=e.readBits(8),i=e.readBits(8))),e.readBits(1)&&(B(e),B(e)),e.readBits(1),e.readBits(1),e.readBits(1),e.readBits(1)&&(B(e),B(e),B(e),B(e)),e.readBits(1)&&(e.readBits(32),e.readBits(32),e.readBits(1)&&B(e),e.readBits(1)&&qm(e,!0,t)),e.readBits(1)&&(e.readBits(1),e.readBits(1),e.readBits(1),o=B(e),B(e),B(e),B(e),B(e)),{pixelAspectRatio:s,colourPrimaries:n,transferCharacteristics:r,matrixCoefficients:i,fullRangeFlag:a,minSpatialSegmentationIdc:o}},qm=(e,t,n)=>{let r=!1,i=!1,a=!1;t&&(r=e.readBits(1)===1,i=e.readBits(1)===1,(r||i)&&(a=e.readBits(1)===1,a&&(e.readBits(8),e.readBits(5),e.readBits(1),e.readBits(5)),e.readBits(4),e.readBits(4),a&&e.readBits(4),e.readBits(5),e.readBits(5),e.readBits(5)));for(let t=0;t<=n;t++){let t=e.readBits(1)===1,n=!0;t||(n=e.readBits(1)===1);let o=!1;n?B(e):o=e.readBits(1)===1;let s=1;o||(s=B(e)+1),r&&Jm(e,s,a),i&&Jm(e,s,a)}},Jm=(e,t,n)=>{for(let r=0;r<t;r++)B(e),B(e),n&&(B(e),B(e)),e.readBits(1)},Ym=e=>{let t=[];t.push(e.configurationVersion),t.push((e.generalProfileSpace&3)<<6|(e.generalTierFlag&1)<<5|e.generalProfileIdc&31),t.push(e.generalProfileCompatibilityFlags>>>24&255),t.push(e.generalProfileCompatibilityFlags>>>16&255),t.push(e.generalProfileCompatibilityFlags>>>8&255),t.push(e.generalProfileCompatibilityFlags&255),t.push(...e.generalConstraintIndicatorFlags),t.push(e.generalLevelIdc&255),t.push(240|e.minSpatialSegmentationIdc>>8&15),t.push(e.minSpatialSegmentationIdc&255),t.push(252|e.parallelismType&3),t.push(252|e.chromaFormatIdc&3),t.push(248|e.bitDepthLumaMinus8&7),t.push(248|e.bitDepthChromaMinus8&7),t.push(e.avgFrameRate>>8&255),t.push(e.avgFrameRate&255),t.push((e.constantFrameRate&3)<<6|(e.numTemporalLayers&7)<<3|(e.temporalIdNested&1)<<2|e.lengthSizeMinusOne&3),t.push(e.arrays.length&255);for(let n of e.arrays){t.push((n.arrayCompleteness&1)<<7|0|n.nalUnitType&63),t.push(n.nalUnits.length>>8&255),t.push(n.nalUnits.length&255);for(let e of n.nalUnits){t.push(e.length>>8&255),t.push(e.length&255);for(let n=0;n<e.length;n++)t.push(e[n])}}return new Uint8Array(t)},Xm=e=>{try{let t=sp(e),n=0,r=t.getUint8(n++),i=t.getUint8(n++),a=i>>6&3,o=i>>5&1,s=i&31,c=t.getUint32(n,!1);n+=4;let l=e.subarray(n,n+6);n+=6;let u=t.getUint8(n++),d=(t.getUint8(n++)&15)<<8|t.getUint8(n++),f=t.getUint8(n++)&3,p=t.getUint8(n++)&3,m=t.getUint8(n++)&7,h=t.getUint8(n++)&7,g=t.getUint16(n,!1);n+=2;let _=t.getUint8(n++),v=_>>6&3,y=_>>3&7,b=_>>2&1,x=_&3,S=t.getUint8(n++),C=[];for(let r=0;r<S;r++){let r=t.getUint8(n++),i=r>>7&1,a=r&63,o=t.getUint16(n,!1);n+=2;let s=[];for(let r=0;r<o;r++){let r=t.getUint16(n,!1);n+=2,s.push(e.subarray(n,n+r)),n+=r}C.push({arrayCompleteness:i,nalUnitType:a,nalUnits:s})}return{configurationVersion:r,generalProfileSpace:a,generalTierFlag:o,generalProfileIdc:s,generalProfileCompatibilityFlags:c,generalConstraintIndicatorFlags:l,generalLevelIdc:u,minSpatialSegmentationIdc:d,parallelismType:f,chromaFormatIdc:p,bitDepthLumaMinus8:m,bitDepthChromaMinus8:h,avgFrameRate:g,constantFrameRate:v,numTemporalLayers:y,temporalIdNested:b,lengthSizeMinusOne:x,arrays:C}}catch(e){return om._error(`Error deserializing HEVC Decoder Configuration Record:`,e),null}},Zm;(function(e){e[e.audAllowed=0]=`audAllowed`,e[e.beforeFirstVcl=1]=`beforeFirstVcl`,e[e.afterFirstVcl=2]=`afterFirstVcl`,e[e.eoBitstreamAllowed=3]=`eoBitstreamAllowed`,e[e.noMoreDataAllowed=4]=`noMoreDataAllowed`})(Zm||={});var Qm={1:{colourPrimaries:5,transferCharacteristics:6,matrixCoefficients:5},2:{colourPrimaries:1,transferCharacteristics:1,matrixCoefficients:1},3:{colourPrimaries:6,transferCharacteristics:6,matrixCoefficients:6},4:{colourPrimaries:7,transferCharacteristics:7,matrixCoefficients:7},5:{colourPrimaries:9,transferCharacteristics:14,matrixCoefficients:9},7:{colourPrimaries:1,transferCharacteristics:13,matrixCoefficients:0}},$m=e=>{let t=new fm(e);if(t.readBits(2)!==2)return null;let n=t.readBits(1),r=(t.readBits(1)<<1)+n;if(r===3&&t.skipBits(1),t.readBits(1)===1||t.readBits(1)!==0||(t.skipBits(2),t.readBits(24)!==4817730))return null;let i=8;r>=2&&(i=t.readBits(1)?12:10);let a=t.readBits(3),o=0,s=0;if(a!==7){if(s=t.readBits(1),r===1||r===3){let e=t.readBits(1),n=t.readBits(1);o=!e&&!n?3:e&&!n?2:1,t.skipBits(1)}else o=1}else o=3,s=1;let c=t.readBits(16),l=t.readBits(16),u=(c+1)*(l+1),d=np(zh).level;for(let e of zh)if(u<=e.maxPictureSize){d=e.level;break}let f=Qm[a],p=f?.colourPrimaries??2,m=f?.transferCharacteristics??2,h=f?.matrixCoefficients??2;return{profile:r,level:d,bitDepth:i,chromaSubsampling:o,videoFullRangeFlag:s,colourPrimaries:p,transferCharacteristics:m,matrixCoefficients:h}},eh=e=>e.colourPrimaries!==2||e.transferCharacteristics!==2||e.matrixCoefficients!==2,th=function*(e){let t=new fm(e),n=()=>{let e=0;for(let n=0;n<8;n++){let r=t.readAlignedByte();if(e+=(r&127)*2**(n*7),!(r&128))break;if(n===7&&r&128)return null}return e>2**32-1?null:e};for(;t.getBitsLeft()>=8;){t.skipBits(1);let r=t.readBits(4),i=t.readBits(1),a=t.readBits(1);t.skipBits(1),i&&t.skipBits(8);let o;if(a){let e=n();if(e===null)return;o=e}else o=Math.floor(t.getBitsLeft()/8);z(t.pos%8==0),yield{type:r,data:e.subarray(t.pos/8,t.pos/8+o)},t.skipBits(o*8)}},nh=e=>{for(let{type:t,data:n}of th(e)){if(t!==1)continue;let e=new fm(n),r=e.readBits(3);e.readBits(1);let i=e.readBits(1),a=0,o=0,s=0;if(i)a=e.readBits(5);else{let t=e.readBits(1),n=0;if(t){if(e.skipBits(32),e.skipBits(32),e.readBits(1)){let t=0;for(;t<32&&!e.readBits(1);)t++;t<32&&e.skipBits(t)}n=e.readBits(1),n&&(s=e.readBits(5),e.skipBits(32),e.skipBits(5),e.skipBits(5))}let r=e.readBits(1),i=e.readBits(5);for(let t=0;t<=i;t++){e.skipBits(12);let i=e.readBits(5);if(t===0&&(a=i),i>7){let n=e.readBits(1);t===0&&(o=n)}if(n&&e.readBits(1)){let t=s+1;e.skipBits(t),e.skipBits(t),e.skipBits(1)}r&&e.readBits(1)&&e.skipBits(4)}}let c=e.readBits(4),l=e.readBits(4),u=c+1;e.skipBits(u);let d=l+1;e.skipBits(d);let f=0;if(f=i?0:e.readBits(1),f&&(e.skipBits(4),e.skipBits(3)),e.skipBits(1),e.skipBits(1),e.skipBits(1),!i){e.skipBits(1),e.skipBits(1),e.skipBits(1),e.skipBits(1);let t=e.readBits(1);t&&(e.skipBits(1),e.skipBits(1));let n=e.readBits(1),r=0;r=n?2:e.readBits(1),r>0&&(e.readBits(1)||e.skipBits(1)),t&&e.skipBits(3)}e.skipBits(1),e.skipBits(1),e.skipBits(1);let p=e.readBits(1),m=8;r===2&&p?m=e.readBits(1)?12:10:r<=2&&(m=p?10:8);let h=0;r!==1&&(h=e.readBits(1));let g=2,_=2,v=2;e.readBits(1)&&(g=e.readBits(8),_=e.readBits(8),v=e.readBits(8));let y=0,b=1,x=1,S=0;return h?y=e.readBits(1):g===1&&_===13&&v===0?(y=1,b=0,x=0):(y=e.readBits(1),r===0?(b=1,x=1):r===1?(b=0,x=0):m===12?(b=e.readBits(1),x=b?e.readBits(1):0):(b=1,x=0),b&&x&&(S=e.readBits(2))),{profile:r,level:a,tier:o,bitDepth:m,monochrome:h,chromaSubsamplingX:b,chromaSubsamplingY:x,chromaSamplePosition:S,videoFullRangeFlag:y,colourPrimaries:g,transferCharacteristics:_,matrixCoefficients:v}}return null},rh=e=>e.colourPrimaries!==2||e.transferCharacteristics!==2||e.matrixCoefficients!==2,ih=e=>{if(e.length<36)return null;let t=sp(e);return t.getUint32(4)!==1768124518||t.getUint16(8)<28?null:{fullRange:!1,colourPrimaries:t.getUint8(22),transferCharacteristics:t.getUint8(23),matrixCoefficients:t.getUint8(24)}},ah=e=>{let t=sp(e),n=t.getUint8(9),r=t.getUint16(10,!0),i=t.getUint32(12,!0),a=t.getInt16(16,!0),o=t.getUint8(18),s=null;return o&&(s=e.subarray(19,21+n)),{outputChannelCount:n,preSkip:r,inputSampleRate:i,outputGain:a,channelMappingFamily:o,channelMappingTable:s}},oh=(e,t,n)=>{switch(e){case`avc`:for(let e of Om(n,t)){let t=n[e.offset],r=km(t);if(r>=wm.NON_IDR_SLICE&&r<=wm.SLICE_DPC)return`delta`;if(r===wm.IDR)return`key`;if(r===wm.SEI&&!Kp()){let t=Am(n.subarray(e.offset,e.offset+e.length)),r=1;do{let e=0;for(;;){let n=t[r++];if(n===void 0||(e+=n,n<255))break}let n=0;for(;;){let e=t[r++];if(e===void 0||(n+=e,e<255))break}if(e===6){let e=new fm(t);e.pos=8*r;let n=B(e),i=e.readBits(1);if(n===0&&i===1)return`key`}r+=n}while(r<t.length-1)}}return`delta`;case`hevc`:for(let e of Rm(n,t)){let t=zm(n[e.offset]);if(t<Tm.BLA_W_LP)return`delta`;if(t<=Tm.RSV_IRAP_VCL23)return`key`}return`delta`;case`vp8`:return n[0]&1?`delta`:`key`;case`vp9`:{let e=new fm(n);if(e.readBits(2)!==2)return null;let t=e.readBits(1);return(e.readBits(1)<<1)+t===3&&e.skipBits(1),e.readBits(1)?null:e.readBits(1)===0?`key`:`delta`}case`av1`:{let e=!1;for(let{type:t,data:r}of th(n))if(t===1){let t=new fm(r);t.skipBits(4),e=!!t.readBits(1)}else if(t===3||t===6||t===7){if(e)return`key`;let t=new fm(r);return t.readBits(1)?null:t.readBits(2)===0?`key`:`delta`}return null}case`prores`:return`key`;default:Np(e),z(!1)}},sh;(function(e){e[e.STREAMINFO=0]=`STREAMINFO`,e[e.VORBIS_COMMENT=4]=`VORBIS_COMMENT`,e[e.PICTURE=6]=`PICTURE`})(sh||={});var ch=[2,1,2,3,3,4,4,5],lh=e=>{if(e.length<7||e[0]!==11||e[1]!==119)return null;let t=new fm(e);t.skipBits(16),t.skipBits(16);let n=t.readBits(2);if(n===3)return null;let r=t.readBits(6),i=t.readBits(5);if(i>8)return null;let a=t.readBits(3),o=t.readBits(3);return o&1&&o!==1&&t.skipBits(2),o&4&&t.skipBits(2),o===2&&t.skipBits(2),{fscod:n,bsid:i,bsmod:a,acmod:o,lfeon:t.readBits(1),bitRateCode:Math.floor(r/2)}};new Uint8Array([5,4,65,67,45,51]),new Uint8Array([5,4,69,65,67,51]);var uh=[1,2,3,6],dh=e=>{if(e.length<6||e[0]!==11||e[1]!==119)return null;let t=new fm(e);t.skipBits(16);let n=t.readBits(2);if(t.skipBits(3),n!==0&&n!==2)return null;let r=t.readBits(11),i=t.readBits(2),a=0,o;i===3?(a=t.readBits(2),o=3):o=t.readBits(2);let s=t.readBits(3),c=t.readBits(1),l=t.readBits(5);if(l<11||l>16)return null;let u=uh[o],d;return d=i<3?Sm[i]/1e3:Cm[a]/1e3,{dataRate:Math.round((r+1)*d/(u*16)),substreams:[{fscod:i,fscod2:a,bsid:l,bsmod:0,acmod:s,lfeon:c,numDepSub:0,chanLoc:0}]}},fh=e=>{if(e.length<2)return null;let t=new fm(e),n=t.readBits(13),r=t.readBits(3),i=[];for(let n=0;n<=r&&!(Math.ceil(t.pos/8)+3>e.length);n++){let e=t.readBits(2),n=t.readBits(5);t.skipBits(1),t.skipBits(1);let r=t.readBits(3),a=t.readBits(3),o=t.readBits(1);t.skipBits(3);let s=t.readBits(4),c=0;s>0?c=t.readBits(9):t.skipBits(1),i.push({fscod:e,fscod2:null,bsid:n,bsmod:r,acmod:a,lfeon:o,numDepSub:s,chanLoc:c})}return i.length===0?null:{dataRate:n,substreams:i}},ph=e=>{let t=e.substreams[0];return z(t),t.fscod<3?Sm[t.fscod]:t.fscod2!==null&&t.fscod2<3?Cm[t.fscod2]:null},mh=e=>{let t=e.substreams[0];z(t);let n=ch[t.acmod]+t.lfeon;if(t.numDepSub>0){let e=[2,2,1,1,2,2,2,1,1];for(let r=0;r<9;r++)t.chanLoc&1<<8-r&&(n+=e[r])}return n},hh=8,gh=[0,8e3,16e3,32e3,0,0,11025,22050,44100,0,0,12e3,24e3,48e3,96e3,192e3],_h=[32e3,56e3,64e3,96e3,112e3,128e3,192e3,224e3,256e3,32e4,384e3,448e3,512e3,576e3,64e4,768e3,96e4,1024e3,1152e3,128e4,1344e3,1408e3,1411200,1472e3,1536e3,192e4,2048e3,3072e3,384e4,0,0,0],vh=[16,16,20,20,0,24,24,0],yh=[1,2,2,2,2,3,3,4,4,5,6,6,6,7,8,8],bh=[1,2,2,2,2,3,18,19,6,7,518,323,83,519,582,535],xh=8,Sh=44646,Ch=[32e3,44100,48e3,0],wh=[8e3,16e3,32e3,64e3,128e3,22050,44100,88200,176400,352800,12e3,24e3,48e3,96e3,192e3,384e3],Th=[512,1024,2048,4096],Eh=e=>{let t=Oh(e),n=sp(e),r=t?Math.ceil(t.frameSize/4)*4:0,i=null;for(;r+4<=e.length&&n.getUint32(r)===1683496997;){let t=kh(e.subarray(r));if(!t)break;i??=t,r+=t.frameSize}if(t)return{frameSize:i?r:t.frameSize,sampleRate:t.sampleRate,numberOfChannels:t.numberOfChannels,sampleCount:t.sampleCount,channelLayout:t.channelLayout,pcmResolution:t.pcmResolution,bitRate:t.bitRate,core:t,hasExtensions:i!==null};if(!i?.asset)return null;let{asset:a}=i;return{frameSize:r,sampleRate:a.sampleRate,numberOfChannels:a.numberOfChannels,sampleCount:a.sampleCount,channelLayout:a.channelLayout,pcmResolution:a.pcmResolution,bitRate:0,core:null,hasExtensions:!0}},Dh=e=>{let t=Eh(e);return t?.core?t.hasExtensions?`dtsh`:`dtsc`:null},Oh=e=>{if(e.length<18||e[0]!==127||e[1]!==254||e[2]!==128||e[3]!==1)return null;let t=new fm(e);if(t.skipBits(32),t.skipBits(1),t.readBits(5)!==31)return null;let n=t.readBits(1),r=t.readBits(7)+1;if(r%hh!==0)return null;let i=t.readBits(14)+1;if(i<96)return null;let a=t.readBits(6);if(a>=yh.length)return null;let o=gh[t.readBits(4)];if(o===0)return null;let s=_h[t.readBits(5)];if(t.readBits(1)!==0)return null;t.skipBits(4),t.skipBits(5);let c=t.readBits(2);if(c===3)return null;t.skipBits(1),n&&t.skipBits(16),t.skipBits(7);let l=vh[t.readBits(3)];if(l===0)return null;let u=c!==0;return{frameSize:i,sampleRate:o,numberOfChannels:yh[a]+ +!!u,sampleCount:r*32,channelLayout:bh[a]|(u?xh:0),amode:a,lfePresent:u,bitRate:s,pcmResolution:l}},kh=e=>{if(e.length<10||e[0]!==100||e[1]!==88||e[2]!==32||e[3]!==37)return null;let t=new fm(e);t.skipBits(32),t.skipBits(8);let n=t.readBits(2),r=t.readBits(1),i=8+4*r,a=16+4*r;t.skipBits(i);let o=t.readBits(a)+1,s={frameSize:o,asset:null};if(!t.readBits(1))return s;let c=Ch[t.readBits(2)],l=512*(t.readBits(3)+1);t.readBits(1)&&t.skipBits(36);let u=t.readBits(3)+1,d=t.readBits(3)+1,f=[];for(let e=0;e<u;e++)f.push(t.readBits(n+1));for(let e of f)t.skipBits(8*Bp(e));if(t.readBits(1)){t.skipBits(2);let e=t.readBits(2)+1<<2,n=t.readBits(2)+1;t.skipBits(n*e)}for(let e=0;e<d;e++)t.skipBits(a);t.skipBits(9),t.skipBits(3),t.readBits(1)&&t.skipBits(4),t.readBits(1)&&t.skipBits(24),t.readBits(1)&&t.skipBits(8*(t.readBits(10)+1));let p=t.readBits(5)+1,m=wh[t.readBits(4)],h=t.readBits(8)+1,g=0;if(t.readBits(1)&&(h>2&&t.skipBits(1),h>6&&t.skipBits(1),t.readBits(1))){let e=t.readBits(2)+1<<2;g=t.readBits(e)}return c===0||t.getBitsLeft()<0?s:{frameSize:o,asset:{sampleRate:m,numberOfChannels:h,sampleCount:Math.round(l*m/c),channelLayout:g,pcmResolution:p}}},Ah=e=>{if(e.length<20)return null;let t=sp(e),n=t.getUint32(0);if(n===0)return null;let r=new fm(e);r.seekToByte(13);let i=r.readBits(2);r.skipBits(5);let a=r.readBits(1),o=r.readBits(6);r.skipBits(14),r.skipBits(1),r.skipBits(3);let s=r.readBits(16),c=null;return s===0?o<yh.length&&(c=yh[o]+a):c=Mh(s),{sampleRate:n,maxBitrate:t.getUint32(4),avgBitrate:t.getUint32(8),pcmSampleDepth:e[12],sampleCount:Th[i],channelLayout:s,numberOfChannels:c}},jh=e=>{let t=/* @__PURE__ */ new Uint8Array(20),n=sp(t);n.setUint32(0,e.sampleRate),n.setUint32(4,e.bitRate),n.setUint32(8,e.bitRate),t[12]=e.pcmResolution;let r=e.core&&!e.hasExtensions?1:0,i=new fm(t);return i.seekToByte(13),i.writeBits(2,Math.max(Th.indexOf(e.sampleCount),0)),i.writeBits(5,r),i.writeBits(1,+!!e.core?.lfePresent),i.writeBits(6,e.core?.amode??0),i.writeBits(14,e.core?e.core.frameSize-1:0),i.writeBits(1,0),i.writeBits(3,0),i.writeBits(16,e.channelLayout),i.writeBits(1,0),i.writeBits(1,0),i.writeBits(1,0),i.writeBits(5,0),t},Mh=e=>Bp(e)+Bp(e&Sh),Nh=[`avc`,`hevc`,`vp9`,`av1`,`vp8`,`prores`],Ph=[`pcm-s16`,`pcm-s16be`,`pcm-s24`,`pcm-s24be`,`pcm-s32`,`pcm-s32be`,`pcm-f32`,`pcm-f32be`,`pcm-f64`,`pcm-f64be`,`pcm-u8`,`pcm-s8`,`ulaw`,`alaw`],Fh=[`aac`,`opus`,`mp3`,`vorbis`,`flac`,`ac3`,`eac3`,`dts`],Ih=[...Fh,...Ph],Lh=[`webvtt`],Rh=[{maxMacroblocks:99,maxBitrate:64e3,maxDpbMbs:396,level:10},{maxMacroblocks:396,maxBitrate:192e3,maxDpbMbs:900,level:11},{maxMacroblocks:396,maxBitrate:384e3,maxDpbMbs:2376,level:12},{maxMacroblocks:396,maxBitrate:768e3,maxDpbMbs:2376,level:13},{maxMacroblocks:396,maxBitrate:2e6,maxDpbMbs:2376,level:20},{maxMacroblocks:792,maxBitrate:4e6,maxDpbMbs:4752,level:21},{maxMacroblocks:1620,maxBitrate:4e6,maxDpbMbs:8100,level:22},{maxMacroblocks:1620,maxBitrate:1e7,maxDpbMbs:8100,level:30},{maxMacroblocks:3600,maxBitrate:14e6,maxDpbMbs:18e3,level:31},{maxMacroblocks:5120,maxBitrate:2e7,maxDpbMbs:20480,level:32},{maxMacroblocks:8192,maxBitrate:2e7,maxDpbMbs:32768,level:40},{maxMacroblocks:8192,maxBitrate:5e7,maxDpbMbs:32768,level:41},{maxMacroblocks:8704,maxBitrate:5e7,maxDpbMbs:34816,level:42},{maxMacroblocks:22080,maxBitrate:135e6,maxDpbMbs:110400,level:50},{maxMacroblocks:36864,maxBitrate:24e7,maxDpbMbs:184320,level:51},{maxMacroblocks:36864,maxBitrate:24e7,maxDpbMbs:184320,level:52},{maxMacroblocks:139264,maxBitrate:24e7,maxDpbMbs:696320,level:60},{maxMacroblocks:139264,maxBitrate:48e7,maxDpbMbs:696320,level:61},{maxMacroblocks:139264,maxBitrate:8e8,maxDpbMbs:696320,level:62}],zh=[{maxPictureSize:36864,maxBitrate:2e5,level:10},{maxPictureSize:73728,maxBitrate:8e5,level:11},{maxPictureSize:122880,maxBitrate:18e5,level:20},{maxPictureSize:245760,maxBitrate:36e5,level:21},{maxPictureSize:552960,maxBitrate:72e5,level:30},{maxPictureSize:983040,maxBitrate:12e6,level:31},{maxPictureSize:2228224,maxBitrate:18e6,level:40},{maxPictureSize:2228224,maxBitrate:3e7,level:41},{maxPictureSize:8912896,maxBitrate:6e7,level:50},{maxPictureSize:8912896,maxBitrate:12e7,level:51},{maxPictureSize:8912896,maxBitrate:18e7,level:52},{maxPictureSize:35651584,maxBitrate:18e7,level:60},{maxPictureSize:35651584,maxBitrate:24e7,level:61},{maxPictureSize:35651584,maxBitrate:48e7,level:62}],Bh=`.01.01.01.01.00`,Vh=`.0.110.01.01.01.0`,Hh=[`ap4x`,`ap4h`,`apch`,`apcn`,`apcs`,`apco`],Uh=[`dtsc`,`dtsh`,`dtsl`,`dtse`],Wh=e=>{let t=e.split(`.`),n=Number(t[1]),r=t[2],i=Number(r.slice(0,-1)),a=(n<<5)+i,o=+(r.slice(-1)===`H`),s=Number(t[3]),c=s===8?0:1,l=+(s===12),u=t[4]?Number(t[4]):0,d=t[5]?Number(t[5][0]):1,f=t[5]?Number(t[5][1]):1,p=t[5]?Number(t[5][2]):0;return[129,a,(o<<7)+(c<<6)+(l<<5)+(u<<4)+(d<<3)+(f<<2)+p,0]},Gh=e=>{let{codec:t,codecDescription:n,colorSpace:r,avcCodecInfo:i,hevcCodecInfo:a,vp9CodecInfo:o,av1CodecInfo:s,proresFormat:c}=e;if(t===`avc`){if(z(e.avcType!==null),i){let t=new Uint8Array([i.avcProfileIndication,i.profileCompatibility,i.avcLevelIndication]);return`avc${e.avcType}.${Tp(t)}`}if(!n||n.byteLength<4)throw TypeError(`AVC decoder description is not provided or is not at least 4 bytes long.`);return`avc${e.avcType}.${Tp(n.subarray(1,4))}`}if(t===`hevc`){let e,t,r,i,o,s;if(a)e=a.generalProfileSpace,t=a.generalProfileIdc,r=Dp(a.generalProfileCompatibilityFlags),i=a.generalTierFlag,o=a.generalLevelIdc,s=[...a.generalConstraintIndicatorFlags];else{if(!n||n.byteLength<23)throw TypeError(`HEVC decoder description is not provided or is not at least 23 bytes long.`);let a=sp(n),c=a.getUint8(1);e=c>>6&3,t=c&31,r=Dp(a.getUint32(2)),i=c>>5&1,o=a.getUint8(12),s=[];for(let e=0;e<6;e++)s.push(a.getUint8(6+e))}let c=`hev1.`;for(c+=[``,`A`,`B`,`C`][e]+t,c+=`.`,c+=r.toString(16).toUpperCase(),c+=`.`,c+=i===0?`L`:`H`,c+=o;s.length>0&&s[s.length-1]===0;)s.pop();return s.length>0&&(c+=`.`,c+=s.map(e=>e.toString(16).toUpperCase()).join(`.`)),c}if(t===`vp8`)return`vp8`;if(t===`vp9`){if(!o){let t=e.width*e.height,n=np(zh).level;for(let e of zh)if(t<=e.maxPictureSize){n=e.level;break}return`vp09.00.${n.toString().padStart(2,`0`)}.08`}let t=o.profile.toString().padStart(2,`0`),n=o.level.toString().padStart(2,`0`),r=o.bitDepth.toString().padStart(2,`0`),i=o.chromaSubsampling.toString().padStart(2,`0`),a=o.colourPrimaries.toString().padStart(2,`0`),s=o.transferCharacteristics.toString().padStart(2,`0`),c=o.matrixCoefficients.toString().padStart(2,`0`),l=o.videoFullRangeFlag.toString().padStart(2,`0`),u=`vp09.${t}.${n}.${r}.${i}`;return u+=`.${a}.${s}.${c}.${l}`,u.endsWith(Bh)&&(u=u.slice(0,-15)),u}if(t===`av1`){if(!s){let t=e.width*e.height,n=np(zh).level;for(let e of zh)if(t<=e.maxPictureSize){n=e.level;break}return`av01.0.${n.toString().padStart(2,`0`)}M.08`}let t=s.profile,n=s.level.toString().padStart(2,`0`),i=s.tier?`H`:`M`,a=s.bitDepth.toString().padStart(2,`0`),o=s.monochrome?`1`:`0`,c=100*s.chromaSubsamplingX+10*s.chromaSubsamplingY+1*(s.chromaSubsamplingX&&s.chromaSubsamplingY?s.chromaSamplePosition:0),l=r?.primaries?pp[r.primaries]:1,u=r?.transfer?hp[r.transfer]:1,d=r?.matrix?_p[r.matrix]:1,f=+!!r?.fullRange,p=`av01.${t}.${n}${i}.${a}`;return p+=`.${o}.${c.toString().padStart(3,`0`)}`,p+=`.${l.toString().padStart(2,`0`)}`,p+=`.${u.toString().padStart(2,`0`)}`,p+=`.${d.toString().padStart(2,`0`)}`,p+=`.${f}`,p.endsWith(Vh)&&(p=p.slice(0,-17)),p}if(t===`prores`)return c??`apch`;throw t!==null&&Np(t),TypeError(`Unhandled codec '${t}'.`)},Kh=e=>{switch(e.codec){case`avc`:{let t=e.avcCodecInfo?.sequenceParameterSets[0];if(!t&&e.codecDescription&&(t=Pm(e.codecDescription)?.sequenceParameterSets[0]),t){let e=Im(t);if(e)return{primaries:mp[e.colourPrimaries],transfer:gp[e.transferCharacteristics],matrix:vp[e.matrixCoefficients],fullRange:!!e.fullRangeFlag}}}break;case`hevc`:{let t=e.hevcCodecInfo?.arrays.find(e=>e.nalUnitType===Tm.SPS_NUT)?.nalUnits[0];if(!t&&e.codecDescription&&(t=Xm(e.codecDescription)?.arrays.find(e=>e.nalUnitType===Tm.SPS_NUT)?.nalUnits[0]),t){let e=Bm(t);if(e)return{primaries:mp[e.colourPrimaries],transfer:gp[e.transferCharacteristics],matrix:vp[e.matrixCoefficients],fullRange:!!e.fullRangeFlag}}}break;case`vp8`:break;case`vp9`:if(e.vp9CodecInfo)return{primaries:mp[e.vp9CodecInfo.colourPrimaries],transfer:gp[e.vp9CodecInfo.transferCharacteristics],matrix:vp[e.vp9CodecInfo.matrixCoefficients],fullRange:!!e.vp9CodecInfo.videoFullRangeFlag};break;case`av1`:if(e.av1CodecInfo)return{primaries:mp[e.av1CodecInfo.colourPrimaries],transfer:gp[e.av1CodecInfo.transferCharacteristics],matrix:vp[e.av1CodecInfo.matrixCoefficients],fullRange:!!e.av1CodecInfo.videoFullRangeFlag};break;case`prores`:if(e.proresCodecInfo)return{primaries:mp[e.proresCodecInfo.colourPrimaries],transfer:gp[e.proresCodecInfo.transferCharacteristics],matrix:vp[e.proresCodecInfo.matrixCoefficients],fullRange:e.proresCodecInfo.fullRange}}return{primaries:void 0,transfer:void 0,matrix:void 0,fullRange:void 0}},qh=e=>{let{codec:t,codecDescription:n,aacCodecInfo:r,dtsFormat:i}=e;if(t===`aac`){if(!r)throw TypeError(`AAC codec info must be provided.`);if(r.isMpeg2)return`mp4a.67`;{let e;return e=r.objectType===null?hm(n).objectType:r.objectType,`mp4a.40.${e}`}}if(t===`mp3`)return`mp3`;if(t===`opus`)return`opus`;if(t===`vorbis`)return`vorbis`;if(t===`flac`)return`flac`;if(t===`ac3`)return`ac-3`;if(t===`eac3`)return`ec-3`;if(t===`dts`)return i??`dtsc`;if(t&&Ph.includes(t))return t;throw TypeError(`Unhandled codec '${t}'.`)},Jh=48e3,Yh=/^pcm-([usf])(\d+)(be)?$/,Xh=e=>{if(z(Ph.includes(e)),e===`ulaw`)return{dataType:`ulaw`,sampleSize:1,littleEndian:!0,silentValue:255};if(e===`alaw`)return{dataType:`alaw`,sampleSize:1,littleEndian:!0,silentValue:213};let t=Yh.exec(e);z(t);let n;n=t[1]===`u`?`unsigned`:t[1]===`s`?`signed`:`float`;let r=Number(t[2])/8,i=t[3]!==`be`;return{dataType:n,sampleSize:r,littleEndian:i,silentValue:e===`pcm-u8`?128:0}},Zh=e=>e.startsWith(`avc1`)||e.startsWith(`avc3`)?`avc`:e.startsWith(`hev1`)||e.startsWith(`hvc1`)?`hevc`:e===`vp8`?`vp8`:e.startsWith(`vp09`)?`vp9`:e.startsWith(`av01`)?`av1`:Hh.includes(e)?`prores`:e===`mp3`||e===`mp4a.69`||e===`mp4a.6B`||e===`mp4a.6b`||e===`mp4a.40.34`?`mp3`:e.startsWith(`mp4a.40.`)||e===`mp4a.67`?`aac`:e===`opus`?`opus`:e===`vorbis`?`vorbis`:e===`flac`?`flac`:e===`ac-3`||e===`ac3`?`ac3`:e===`ec-3`||e===`eac3`?`eac3`:Uh.includes(e)?`dts`:e===`ulaw`?`ulaw`:e===`alaw`?`alaw`:Yh.test(e)?e:e===`webvtt`?`webvtt`:null,Qh=[`avc1`,`avc3`,`hev1`,`hvc1`,`vp8`,`vp09`,`av01`,...Hh],$h=/^(avc1|avc3)\.[0-9a-fA-F]{6}$/,eg=/^(hev1|hvc1)\.(?:[ABC]?\d+)\.[0-9a-fA-F]{1,8}\.[LH]\d+(?:\.[0-9a-fA-F]{1,2}){0,6}$/,tg=/^vp09(?:\.\d{2}){3}(?:(?:\.\d{2}){5})?$/,ng=/^av01\.\d\.\d{2}[MH]\.\d{2}(?:\.\d\.\d{3}\.\d{2}\.\d{2}\.\d{2}\.\d)?$/,rg=(e,t)=>{if(!e)throw TypeError(`Video chunk metadata must be provided.`);if(typeof e!=`object`)throw TypeError(`Video chunk metadata must be an object.`);if(!e.decoderConfig)throw TypeError(`Video chunk metadata must include a decoder configuration.`);if(typeof e.decoderConfig!=`object`)throw TypeError(`Video chunk metadata decoder configuration must be an object.`);if(typeof e.decoderConfig.codec!=`string`)throw TypeError(`Video chunk metadata decoder configuration must specify a codec string.`);if(!Qh.some(t=>e.decoderConfig.codec.startsWith(t)))throw TypeError(`Video chunk metadata decoder configuration codec string must be a valid video codec string as specified in the Mediabunny Codec Registry.`);if(!Number.isInteger(e.decoderConfig.codedWidth)||e.decoderConfig.codedWidth<=0)throw TypeError(`Video chunk metadata decoder configuration must specify a valid codedWidth (positive integer).`);if(!Number.isInteger(e.decoderConfig.codedHeight)||e.decoderConfig.codedHeight<=0)throw TypeError(`Video chunk metadata decoder configuration must specify a valid codedHeight (positive integer).`);if(e.decoderConfig.displayAspectWidth!==void 0&&(!Number.isInteger(e.decoderConfig.displayAspectWidth)||e.decoderConfig.displayAspectWidth<=0))throw TypeError(`Video chunk metadata decoder configuration displayAspectWidth, when defined, must be a positive integer.`);if(e.decoderConfig.displayAspectHeight!==void 0&&(!Number.isInteger(e.decoderConfig.displayAspectHeight)||e.decoderConfig.displayAspectHeight<=0))throw TypeError(`Video chunk metadata decoder configuration displayAspectHeight, when defined, must be a positive integer.`);if(e.decoderConfig.displayAspectWidth!==void 0!=(e.decoderConfig.displayAspectHeight!==void 0))throw TypeError(`Video chunk metadata decoder configuration must specify both displayAspectWidth and displayAspectHeight, or neither.`);if(e.decoderConfig.description!==void 0&&!Sp(e.decoderConfig.description))throw TypeError(`Video chunk metadata decoder configuration description, when defined, must be an ArrayBuffer or an ArrayBuffer view.`);if(e.decoderConfig.colorSpace!==void 0){let{colorSpace:t}=e.decoderConfig;if(typeof t!=`object`)throw TypeError(`Video chunk metadata decoder configuration colorSpace, when provided, must be an object.`);let n=Object.keys(pp);if(t.primaries!=null&&!n.includes(t.primaries))throw TypeError(`Video chunk metadata decoder configuration colorSpace primaries, when defined, must be one of ${n.join(`, `)}.`);let r=Object.keys(hp);if(t.transfer!=null&&!r.includes(t.transfer))throw TypeError(`Video chunk metadata decoder configuration colorSpace transfer, when defined, must be one of ${r.join(`, `)}.`);let i=Object.keys(_p);if(t.matrix!=null&&!i.includes(t.matrix))throw TypeError(`Video chunk metadata decoder configuration colorSpace matrix, when defined, must be one of ${i.join(`, `)}.`);if(t.fullRange!=null&&typeof t.fullRange!=`boolean`)throw TypeError(`Video chunk metadata decoder configuration colorSpace fullRange, when defined, must be a boolean.`)}if(e.decoderConfig.codec.startsWith(`avc1`)||e.decoderConfig.codec.startsWith(`avc3`)){if(!$h.test(e.decoderConfig.codec))throw TypeError(`Video chunk metadata decoder configuration codec string for AVC must be a valid AVC codec string as specified in Section 3.4 of RFC 6381.`)}else if(e.decoderConfig.codec.startsWith(`hev1`)||e.decoderConfig.codec.startsWith(`hvc1`)){if(!eg.test(e.decoderConfig.codec))throw TypeError(`Video chunk metadata decoder configuration codec string for HEVC must be a valid HEVC codec string as specified in Section E.3 of ISO 14496-15.`)}else if(e.decoderConfig.codec.startsWith(`vp8`)){if(e.decoderConfig.codec!==`vp8`)throw TypeError(`Video chunk metadata decoder configuration codec string for VP8 must be "vp8".`)}else if(e.decoderConfig.codec.startsWith(`vp09`)){if(!tg.test(e.decoderConfig.codec))throw TypeError(`Video chunk metadata decoder configuration codec string for VP9 must be a valid VP9 codec string as specified in Section "Codecs Parameter String" of https://www.webmproject.org/vp9/mp4/.`)}else if(e.decoderConfig.codec.startsWith(`av01`)){if(!ng.test(e.decoderConfig.codec))throw TypeError(`Video chunk metadata decoder configuration codec string for AV1 must be a valid AV1 codec string as specified in Section "Codecs Parameter String" of https://aomediacodec.github.io/av1-isobmff/.`)}else if(Hh.some(t=>e.decoderConfig.codec.startsWith(t))&&!Hh.some(t=>e.decoderConfig.codec===t))throw TypeError(`Video chunk metadata decoder configuration codec string for ProRes must be one of the valid ProRes four-character codes: ${Hh.join(`, `)}.`);if(t!==null&&Zh(e.decoderConfig.codec)!==t)throw TypeError(`Video chunk metadata decoder configuration codec string '${e.decoderConfig.codec}' does not fit to the track codec '${t}'.`)},ig=[`mp4a`,`mp3`,`opus`,`vorbis`,`flac`,`ulaw`,`alaw`,`pcm`,`ac-3`,`ec-3`,`dts`],ag=(e,t)=>{if(!e)throw TypeError(`Audio chunk metadata must be provided.`);if(typeof e!=`object`)throw TypeError(`Audio chunk metadata must be an object.`);if(!e.decoderConfig)throw TypeError(`Audio chunk metadata must include a decoder configuration.`);if(typeof e.decoderConfig!=`object`)throw TypeError(`Audio chunk metadata decoder configuration must be an object.`);if(typeof e.decoderConfig.codec!=`string`)throw TypeError(`Audio chunk metadata decoder configuration must specify a codec string.`);if(!ig.some(t=>e.decoderConfig.codec.startsWith(t)))throw TypeError(`Audio chunk metadata decoder configuration codec string must be a valid audio codec string as specified in the Mediabunny Codec Registry.`);if(!Number.isInteger(e.decoderConfig.sampleRate)||e.decoderConfig.sampleRate<=0)throw TypeError(`Audio chunk metadata decoder configuration must specify a valid sampleRate (positive integer).`);if(!Number.isInteger(e.decoderConfig.numberOfChannels)||e.decoderConfig.numberOfChannels<=0)throw TypeError(`Audio chunk metadata decoder configuration must specify a valid numberOfChannels (positive integer).`);if(e.decoderConfig.description!==void 0&&!Sp(e.decoderConfig.description))throw TypeError(`Audio chunk metadata decoder configuration description, when defined, must be an ArrayBuffer or an ArrayBuffer view.`);if(e.decoderConfig.codec.startsWith(`mp4a`)&&e.decoderConfig.codec!==`mp4a.69`&&e.decoderConfig.codec!==`mp4a.6B`&&e.decoderConfig.codec!==`mp4a.6b`){if(![`mp4a.40.2`,`mp4a.40.02`,`mp4a.40.5`,`mp4a.40.05`,`mp4a.40.29`,`mp4a.67`].includes(e.decoderConfig.codec))throw TypeError(`Audio chunk metadata decoder configuration codec string for AAC must be a valid AAC codec string as specified in https://www.w3.org/TR/webcodecs-aac-codec-registration/.`)}else if(e.decoderConfig.codec.startsWith(`mp3`)||e.decoderConfig.codec.startsWith(`mp4a`)){if(e.decoderConfig.codec!==`mp3`&&e.decoderConfig.codec!==`mp4a.69`&&e.decoderConfig.codec!==`mp4a.6B`&&e.decoderConfig.codec!==`mp4a.6b`)throw TypeError(`Audio chunk metadata decoder configuration codec string for MP3 must be "mp3", "mp4a.69" or "mp4a.6B".`)}else if(e.decoderConfig.codec.startsWith(`opus`)){if(e.decoderConfig.codec!==`opus`)throw TypeError(`Audio chunk metadata decoder configuration codec string for Opus must be "opus".`);if(e.decoderConfig.description&&e.decoderConfig.description.byteLength<18)throw TypeError(`Audio chunk metadata decoder configuration description, when specified, is expected to be an Identification Header as specified in Section 5.1 of RFC 7845.`)}else if(e.decoderConfig.codec.startsWith(`vorbis`)){if(e.decoderConfig.codec!==`vorbis`)throw TypeError(`Audio chunk metadata decoder configuration codec string for Vorbis must be "vorbis".`);if(!e.decoderConfig.description)throw TypeError(`Audio chunk metadata decoder configuration for Vorbis must include a description, which is expected to adhere to the format described in https://www.w3.org/TR/webcodecs-vorbis-codec-registration/.`)}else if(e.decoderConfig.codec.startsWith(`flac`)){if(e.decoderConfig.codec!==`flac`)throw TypeError(`Audio chunk metadata decoder configuration codec string for FLAC must be "flac".`);if(!e.decoderConfig.description||e.decoderConfig.description.byteLength<42)throw TypeError(`Audio chunk metadata decoder configuration for FLAC must include a description, which is expected to adhere to the format described in https://www.w3.org/TR/webcodecs-flac-codec-registration/.`)}else if(e.decoderConfig.codec.startsWith(`ac-3`)||e.decoderConfig.codec.startsWith(`ac3`)){if(e.decoderConfig.codec!==`ac-3`)throw TypeError(`Audio chunk metadata decoder configuration codec string for AC-3 must be "ac-3".`)}else if(e.decoderConfig.codec.startsWith(`ec-3`)||e.decoderConfig.codec.startsWith(`eac3`)){if(e.decoderConfig.codec!==`ec-3`)throw TypeError(`Audio chunk metadata decoder configuration codec string for EC-3 must be "ec-3".`)}else if(e.decoderConfig.codec.startsWith(`dts`)){if(!Uh.includes(e.decoderConfig.codec))throw TypeError(`Audio chunk metadata decoder configuration codec string for DTS must be one of the following four-character codes: ${Uh.join(`, `)}.`)}else if((e.decoderConfig.codec.startsWith(`pcm`)||e.decoderConfig.codec.startsWith(`ulaw`)||e.decoderConfig.codec.startsWith(`alaw`))&&!Ph.includes(e.decoderConfig.codec))throw TypeError(`Audio chunk metadata decoder configuration codec string for PCM must be one of the supported PCM codecs (${Ph.join(`, `)}).`);if(t!==null&&Zh(e.decoderConfig.codec)!==t)throw TypeError(`Audio chunk metadata decoder configuration codec string '${e.decoderConfig.codec}' does not fit to the track codec '${t}'.`)},og=e=>{if(!e)throw TypeError(`Subtitle metadata must be provided.`);if(typeof e!=`object`)throw TypeError(`Subtitle metadata must be an object.`);if(!e.config)throw TypeError(`Subtitle metadata must include a config object.`);if(typeof e.config!=`object`)throw TypeError(`Subtitle metadata config must be an object.`);if(typeof e.config.description!=`string`)throw TypeError(`Subtitle metadata config description must be a string.`)},sg=class{constructor(e){this.input=e}dispose(){}},cg=/* #__PURE__ */ new Uint8Array,lg=class e{constructor(e,t,n,r,i=-1,a,o){if(this.data=e,this.type=t,this.timestamp=n,this.duration=r,this.sequenceNumber=i,e===cg&&a===void 0)throw Error(`Internal error: byteLength must be explicitly provided when constructing metadata-only packets.`);if(a===void 0&&(a=e.byteLength),!(e instanceof Uint8Array))throw TypeError(`data must be a Uint8Array.`);if(t!==`key`&&t!==`delta`)throw TypeError(`type must be either "key" or "delta".`);if(!Number.isFinite(n))throw TypeError(`timestamp must be a number.`);if(!Number.isFinite(r)||r<0)throw TypeError(`duration must be a non-negative number.`);if(!Number.isFinite(i))throw TypeError(`sequenceNumber must be a number.`);if(!Number.isInteger(a)||a<0)throw TypeError(`byteLength must be a non-negative integer.`);if(o!==void 0&&(typeof o!=`object`||!o))throw TypeError(`sideData, when provided, must be an object.`);if(o?.alpha!==void 0&&!(o.alpha instanceof Uint8Array))throw TypeError(`sideData.alpha, when provided, must be a Uint8Array.`);if(o?.alphaByteLength!==void 0&&(!Number.isInteger(o.alphaByteLength)||o.alphaByteLength<0))throw TypeError(`sideData.alphaByteLength, when provided, must be a non-negative integer.`);this.byteLength=a,this.sideData=o??{},this.sideData.alpha&&this.sideData.alphaByteLength===void 0&&(this.sideData.alphaByteLength=this.sideData.alpha.byteLength)}get isMetadataOnly(){return this.data===cg}get microsecondTimestamp(){return Math.trunc(Up*this.timestamp)}get microsecondDuration(){return Math.trunc(Up*this.duration)}toEncodedVideoChunk(){if(this.isMetadataOnly)throw TypeError(`Metadata-only packets cannot be converted to a video chunk.`);if(typeof EncodedVideoChunk>`u`)throw Error(`EncodedVideoChunk is not available in this environment.`);return new EncodedVideoChunk({data:this.data,type:this.type,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}alphaToEncodedVideoChunk(e=this.type){if(!this.sideData.alpha)throw TypeError(`This packet does not contain alpha side data.`);if(this.isMetadataOnly)throw TypeError(`Metadata-only packets cannot be converted to a video chunk.`);if(typeof EncodedVideoChunk>`u`)throw Error(`EncodedVideoChunk is not available in this environment.`);return new EncodedVideoChunk({data:this.sideData.alpha,type:e,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}toEncodedAudioChunk(){if(this.isMetadataOnly)throw TypeError(`Metadata-only packets cannot be converted to an audio chunk.`);if(typeof EncodedAudioChunk>`u`)throw Error(`EncodedAudioChunk is not available in this environment.`);return new EncodedAudioChunk({data:this.data,type:this.type,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}static fromEncodedChunk(t,n){if(!(t instanceof EncodedVideoChunk||t instanceof EncodedAudioChunk))throw TypeError(`chunk must be an EncodedVideoChunk or EncodedAudioChunk.`);let r=new Uint8Array(t.byteLength);return t.copyTo(r),new e(r,t.type,t.timestamp/1e6,(t.duration??0)/1e6,void 0,void 0,n)}clone(t){if(t!==void 0&&(typeof t!=`object`||!t))throw TypeError(`options, when provided, must be an object.`);if(t?.data!==void 0&&!(t.data instanceof Uint8Array))throw TypeError(`options.data, when provided, must be a Uint8Array.`);if(t?.type!==void 0&&t.type!==`key`&&t.type!==`delta`)throw TypeError(`options.type, when provided, must be either "key" or "delta".`);if(t?.timestamp!==void 0&&!Number.isFinite(t.timestamp))throw TypeError(`options.timestamp, when provided, must be a number.`);if(t?.duration!==void 0&&!Number.isFinite(t.duration))throw TypeError(`options.duration, when provided, must be a number.`);if(t?.sequenceNumber!==void 0&&!Number.isFinite(t.sequenceNumber))throw TypeError(`options.sequenceNumber, when provided, must be a number.`);if(t?.sideData!==void 0&&(typeof t.sideData!=`object`||t.sideData===null))throw TypeError(`options.sideData, when provided, must be an object.`);return new e(t?.data??this.data,t?.type??this.type,t?.timestamp??this.timestamp,t?.duration??this.duration,t?.sequenceNumber??this.sequenceNumber,this.byteLength,t?.sideData??this.sideData)}},ug=e=>{let t=(e.hasVideo?`video/`:e.hasAudio?`audio/`:`application/`)+(e.isQuickTime?`quicktime`:`mp4`);if(e.codecStrings.length>0){let n=[...new Set(e.codecStrings)];t+=`; codecs="${n.join(`, `)}"`}return t},dg=e=>{let t=sp(e),n=0,r=t.getUint8(n);n+=1,n+=3;let i=Tp(e.subarray(n,n+16));n+=16;let a=null;if(r>0){let r=t.getUint32(n);if(n+=4,r>0){a=[];for(let t=0;t<r;t++)a.push(Tp(e.subarray(n,n+16))),n+=16}}let o=t.getUint32(n);return n+=4,{systemId:i,keyIds:a,data:e.slice(n,n+o)}},fg=(e,t)=>e.systemId===t.systemId&&Xp(e.data,t.data),pg=e=>{let t=H(e),n=V_(e,4),r=8;t===1&&(t=R_(e),r=16);let i=t-r;return i<0?null:{name:n,totalSize:t,headerSize:r,contentSize:i}},mg=e=>L_(e)/65536,hg=e=>L_(e)/1073741824,gg=e=>{let t=0;for(let n=0;n<4;n++){t<<=7;let n=V(e);if(t|=n&127,!(n&128))break}return t},_g=e=>{let t=P_(e);return e.skip(2),t=Math.min(t,e.remainingLength),up.decode(N_(e,t))},vg=e=>{let t=pg(e);if(!t||t.name!==`data`||e.remainingLength<8)return null;let n=H(e);e.skip(4);let r=N_(e,t.contentSize-8);switch(n){case 1:return up.decode(r);case 2:return new lp(`utf-16be`).decode(r);case 13:return new sm(r,`image/jpeg`);case 14:return new sm(r,`image/png`);case 27:return new sm(r,`image/bmp`);default:return r}},yg=/* @__PURE__ */ new Uint32Array(256),bg=/* @__PURE__ */ new Uint32Array(256),xg=/* @__PURE__ */ new Uint32Array(256),Sg=/* @__PURE__ */ new Uint32Array(256),Cg=/* @__PURE__ */ new Uint32Array(256),wg=/* @__PURE__ */ new Uint32Array(256),Tg=/* @__PURE__ */ new Uint32Array(10),Eg=!1,Dg=()=>{let e=/* @__PURE__ */ new Uint8Array(256),t=/* @__PURE__ */ new Uint8Array(256),n=/* @__PURE__ */ new Uint8Array(256);for(let e=0,r=1;e<256;e++)n[e]=r,t[r]=e,r=r^r<<1^(r&128?283:0);let r=(e,r)=>e&&r?n[(t[e]+t[r])%255]:0;e[0]=99;for(let r=1;r<256;r++){let i=n[255-t[r]],a=i^i<<1^i<<2^i<<3^i<<4;a=a>>>8^a&255^99,e[r]=a}for(let t=0;t<256;t++){let n=e[t],i=e.indexOf(t);yg[t]=n<<24|n<<16|n<<8|n,wg[t]=i<<24|i<<16|i<<8|i;let a=r(i,14),o=r(i,9),s=r(i,13),c=r(i,11),l=a<<24|o<<16|s<<8|c;bg[t]=l,xg[t]=l>>>8|l<<24,Sg[t]=l>>>16|l<<16,Cg[t]=l>>>24|l<<8}let i=1;for(let e=0;e<10;e++)Tg[e]=i<<24,i=i<<1^(i&128?283:0);Eg=!0},Og=class{constructor(){this.roundkey=/* @__PURE__ */ new Uint32Array(44),this.iv=new Uint32Array(16/Uint32Array.BYTES_PER_ELEMENT),this.in=/* @__PURE__ */ new Uint8Array(16),this.out=/* @__PURE__ */ new Uint8Array(16),this.inView=new DataView(this.in.buffer),this.outView=new DataView(this.out.buffer)}init({key:e,iv:t}){z(e.byteLength===16),z(t.byteLength===16),Eg||Dg();let n=new DataView(e.buffer,e.byteOffset,e.byteLength),r=new DataView(t.buffer,t.byteOffset,t.byteLength);this.roundkey[0]=n.getUint32(0,!1),this.roundkey[1]=n.getUint32(4,!1),this.roundkey[2]=n.getUint32(8,!1),this.roundkey[3]=n.getUint32(12,!1),this.iv[0]=r.getUint32(0,!1),this.iv[1]=r.getUint32(4,!1),this.iv[2]=r.getUint32(8,!1),this.iv[3]=r.getUint32(12,!1);for(let e=4;e<44;e+=4){let t=this.roundkey[e-1];this.roundkey[e]=this.roundkey[e-4]^yg[t>>>16&255]&4278190080^yg[t>>>8&255]&16711680^yg[t>>>0&255]&65280^yg[t>>>24&255]&255^Tg[e/4-1],this.roundkey[e+1]=this.roundkey[e-3]^this.roundkey[e],this.roundkey[e+2]=this.roundkey[e-2]^this.roundkey[e+1],this.roundkey[e+3]=this.roundkey[e-1]^this.roundkey[e+2]}for(let e=0,t=40;e<t;e+=4,t-=4)for(let n=0;n<4;n++){let r=this.roundkey[e+n];this.roundkey[e+n]=this.roundkey[t+n],this.roundkey[t+n]=r}for(let e=4;e<40;e+=4)for(let t=0;t<4;t++){let n=this.roundkey[e+t];this.roundkey[e+t]=bg[yg[n>>>24&255]&255]^xg[yg[n>>>16&255]&255]^Sg[yg[n>>>8&255]&255]^Cg[yg[n>>>0&255]&255]}}decrypt(){let e=this.inView.getUint32(0,!1)^this.roundkey[0],t=this.inView.getUint32(4,!1)^this.roundkey[1],n=this.inView.getUint32(8,!1)^this.roundkey[2],r=this.inView.getUint32(12,!1)^this.roundkey[3],i=this.inView.getUint32(0,!1),a=this.inView.getUint32(4,!1),o=this.inView.getUint32(8,!1),s=this.inView.getUint32(12,!1),c,l,u,d;for(let i=1;i<10;i++){let a=i*4;c=bg[e>>>24]^xg[r>>>16&255]^Sg[n>>>8&255]^Cg[t&255]^this.roundkey[a],l=bg[t>>>24]^xg[e>>>16&255]^Sg[r>>>8&255]^Cg[n&255]^this.roundkey[a+1],u=bg[n>>>24]^xg[t>>>16&255]^Sg[e>>>8&255]^Cg[r&255]^this.roundkey[a+2],d=bg[r>>>24]^xg[n>>>16&255]^Sg[t>>>8&255]^Cg[e&255]^this.roundkey[a+3],e=c,t=l,n=u,r=d}let f=wg[e>>>24&255]&4278190080^wg[r>>>16&255]&16711680^wg[n>>>8&255]&65280^wg[t>>>0&255]&255^this.roundkey[40],p=wg[t>>>24&255]&4278190080^wg[e>>>16&255]&16711680^wg[r>>>8&255]&65280^wg[n>>>0&255]&255^this.roundkey[41],m=wg[n>>>24&255]&4278190080^wg[t>>>16&255]&16711680^wg[e>>>8&255]&65280^wg[r>>>0&255]&255^this.roundkey[42],h=wg[r>>>24&255]&4278190080^wg[n>>>16&255]&16711680^wg[t>>>8&255]&65280^wg[e>>>0&255]&255^this.roundkey[43];this.outView.setUint32(0,f^this.iv[0],!1),this.outView.setUint32(4,p^this.iv[1],!1),this.outView.setUint32(8,m^this.iv[2],!1),this.outView.setUint32(12,h^this.iv[3],!1),this.iv[0]=i,this.iv[1]=a,this.iv[2]=o,this.iv[3]=s}},kg=class e extends sg{constructor(e){super(e),this.moovSlice=null,this.currentTrack=null,this.tracks=[],this.metadataPromise=null,this.movieTimescale=-1,this.movieDurationInTimescale=-1,this.movieMatrix=Jf,this.isQuickTime=!1,this.metadataTags={},this.currentMetadataKeys=null,this.isFragmented=!1,this.fragmentTrackDefaults=[],this.psshBoxes=[],this.currentFragment=null,this.lastReadFragment=null,this.decryptionKeyCache=/* @__PURE__ */ new Map,this.reader=e._reader}async getTrackBackings(){return await this.readMetadata(),this.tracks.map(e=>e.trackBacking)}async getMimeType(){await this.readMetadata();let e=await this.getTrackBackings(),t=await Promise.all(e.map(e=>e.getDecoderConfig().then(e=>e?.codec??null)));return ug({isQuickTime:this.isQuickTime,hasVideo:this.tracks.some(e=>e.info?.type===`video`),hasAudio:this.tracks.some(e=>e.info?.type===`audio`),codecStrings:t.filter(Boolean)})}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}readMetadata(){return this.metadataPromise??=(async()=>{let e=0,t=!1,n=!1;for(;;){let r=this.reader.requestSliceRange(e,8,16);if(Jp(r)&&(r=await r),!r)break;let i=e,a=pg(r);if(!a)break;if(a.name===`ftyp`||a.name===`styp`){let e=V_(r,4);this.isQuickTime=e===`qt `}else if(a.name===`moov`){let e=this.reader.requestSlice(r.filePos,a.contentSize);if(Jp(e)&&(e=await e),!e)break;this.moovSlice=e,this.readContiguousBoxes(this.moovSlice);for(let e of this.tracks){let t=e.editListPreviousSegmentDurations/this.movieTimescale;e.editListOffset-=Math.round(t*e.timescale)}t=this.isFragmented&&this.reader.fileSize!==null&&this.reader.fileSize>i+a.totalSize,n=!0;break}else if(a.name===`moof`){if(!this.input._initInput)throw Error(`"moof" box encountered with no "moov" box present; this file is likely a Segment as described in ISO/IEC 14496-12 Section 8.16. A separate init file that contains a "moov" box is required to read this file, please provide it using InputOptions.initInput.`);await this.copyMetadataFromInitInput(this.input._initInput),t=!1,n=!0;break}e=i+a.totalSize}if(!n&&this.input._initInput&&await this.copyMetadataFromInitInput(this.input._initInput),t){z(this.reader.fileSize!==null);let e=this.reader.requestSlice(this.reader.fileSize-4,4);Jp(e)&&(e=await e),z(e);let t=H(e),n=this.reader.fileSize-t;if(n>=0&&n<=this.reader.fileSize-16){let e=this.reader.requestSliceRange(n,8,16);if(Jp(e)&&(e=await e),e){let t=pg(e);if(t&&t.name===`mfra`){let n=this.reader.requestSlice(e.filePos,t.contentSize);Jp(n)&&(n=await n),n&&this.readContiguousBoxes(n)}}}}})()}async copyMetadataFromInitInput(t){let n=await t._getDemuxer();if(n.constructor!==e)throw Error(`Init input must match the input's format.`);await n.readMetadata(),this.movieTimescale=n.movieTimescale,this.movieDurationInTimescale=n.movieDurationInTimescale,this.movieMatrix=n.movieMatrix,this.metadataTags=n.metadataTags,this.isFragmented=!0,this.fragmentTrackDefaults=n.fragmentTrackDefaults,this.psshBoxes=n.psshBoxes;for(let e of n.tracks){let t={id:e.id,demuxer:this,trackBacking:null,disposition:e.disposition,timescale:e.timescale,durationInMediaTimescale:e.durationInMediaTimescale,durationInMovieTimescale:e.durationInMovieTimescale,matrix:e.matrix,internalCodecId:e.internalCodecId,name:e.name,languageCode:e.languageCode,sampleTableByteOffset:null,sampleTable:null,fragmentLookupTable:[],currentFragmentState:null,fragmentPositionCache:[],editListPreviousSegmentDurations:e.editListPreviousSegmentDurations,editListOffset:e.editListOffset,encryptionInfo:e.encryptionInfo,encryptionAuxInfo:null,frmaCodecString:null,maxBitrate:e.maxBitrate,avgBitrate:e.avgBitrate,info:e.info};e.trackBacking&&(z(t.info),t.info.type===`video`&&t.info.width!==-1?(t.trackBacking=new jg(t),this.tracks.push(t)):t.info.type===`audio`&&t.info.numberOfChannels!==-1&&(t.trackBacking=new Mg(t),this.tracks.push(t)))}}getSampleTableForTrack(e){if(e.sampleTable)return e.sampleTable;let t={sampleTimingEntries:[],sampleCompositionTimeOffsets:[],sampleSizes:[],keySampleIndices:null,chunkOffsets:[],sampleToChunk:[],presentationTimestamps:null,presentationTimestampIndexMap:null};if(e.sampleTable=t,e.sampleTableByteOffset===null)return t;z(this.moovSlice);let n=this.moovSlice.slice(e.sampleTableByteOffset);if(this.currentTrack=e,this.traverseBox(n),this.currentTrack=null,e.info?.type===`audio`&&e.info.codec&&Ph.includes(e.info.codec)&&t.sampleCompositionTimeOffsets.length===0){z(e.info?.type===`audio`);let n=Xh(e.info.codec),r=[],i=[];for(let a=0;a<t.sampleToChunk.length;a++){let o=t.sampleToChunk[a],s=t.sampleToChunk[a+1],c=(s?s.startChunkIndex:t.chunkOffsets.length)-o.startChunkIndex;for(let a=0;a<c;a++){let s=o.startSampleIndex+a*o.samplesPerChunk,c=s+o.samplesPerChunk,l=kp(t.sampleTimingEntries,s,e=>e.startIndex),u=t.sampleTimingEntries[l],d=kp(t.sampleTimingEntries,c,e=>e.startIndex),f=t.sampleTimingEntries[d],p=u.startDecodeTimestamp+(s-u.startIndex)*u.delta,m=f.startDecodeTimestamp+(c-f.startIndex)*f.delta-p,h=np(r);h&&h.delta===m?h.count++:r.push({startIndex:o.startChunkIndex+a,startDecodeTimestamp:p,count:1,delta:m});let g=o.samplesPerChunk*n.sampleSize*e.info.numberOfChannels;i.push(g)}o.startSampleIndex=o.startChunkIndex,o.samplesPerChunk=1}t.sampleTimingEntries=r,t.sampleSizes=i}if(t.sampleCompositionTimeOffsets.length>0){t.presentationTimestamps=[];for(let e of t.sampleTimingEntries)for(let n=0;n<e.count;n++)t.presentationTimestamps.push({presentationTimestamp:e.startDecodeTimestamp+n*e.delta,sampleIndex:e.startIndex+n});for(let e of t.sampleCompositionTimeOffsets)for(let n=0;n<e.count;n++){let r=e.startIndex+n,i=t.presentationTimestamps[r];i&&(i.presentationTimestamp+=e.offset)}t.presentationTimestamps.sort((e,t)=>e.presentationTimestamp-t.presentationTimestamp),t.presentationTimestampIndexMap=Array(t.presentationTimestamps.length).fill(-1);for(let e=0;e<t.presentationTimestamps.length;e++)t.presentationTimestampIndexMap[t.presentationTimestamps[e].sampleIndex]=e}return t}async readFragment(e){if(this.lastReadFragment?.moofOffset===e)return this.lastReadFragment;let t=this.reader.requestSliceRange(e,8,16);Jp(t)&&(t=await t),z(t);let n=pg(t);z(n?.name===`moof`);let r=this.reader.requestSlice(e,n.totalSize);Jp(r)&&(r=await r),z(r),this.traverseBox(r);let i=this.lastReadFragment;z(i&&i.moofOffset===e);for(let[,e]of i.trackData){let t=e.track,{fragmentPositionCache:n}=t;if(!e.startTimestampIsFinal){let r=t.fragmentLookupTable.find(e=>e.moofOffset===i.moofOffset);if(r)Lg(e,r.timestamp);else{let t=kp(n,i.moofOffset-1,e=>e.moofOffset);if(t!==-1){let r=n[t];Lg(e,r.endTimestamp)}}e.startTimestampIsFinal=!0}let r=kp(n,e.startTimestamp,e=>e.startTimestamp);if((r===-1||n[r].moofOffset!==i.moofOffset)&&n.splice(r+1,0,{moofOffset:i.moofOffset,startTimestamp:e.startTimestamp,endTimestamp:e.endTimestamp}),e.encryptionAuxInfo&&t.encryptionInfo){let n=await Vg(this.reader,t.encryptionInfo,e.encryptionAuxInfo);for(let t=0;t<Math.min(e.samples.length,n.length);t++){let r=n[t];e.samples[t].encryption=r}}}return i}readContiguousBoxes(e){let t=e.filePos;for(;e.filePos-t<=e.length-8&&this.traverseBox(e););}*iterateContiguousBoxes(e){let t=e.filePos;for(;e.filePos-t<=e.length-8;){let t=e.filePos,n=pg(e);if(!n)break;yield{boxInfo:n,slice:e},e.filePos=t+n.totalSize}}traverseBox(e){let t=e.filePos,n=pg(e);if(!n)return!1;let r=e.filePos,i=t+n.totalSize;switch(n.name){case`mdia`:case`minf`:case`dinf`:case`mfra`:case`edts`:case`sinf`:case`schi`:this.readContiguousBoxes(e.slice(r,n.contentSize));break;case`mvhd`:{let t=V(e);e.skip(3),t===1?(e.skip(16),this.movieTimescale=H(e),this.movieDurationInTimescale=R_(e)):(e.skip(8),this.movieTimescale=H(e),this.movieDurationInTimescale=H(e)),e.skip(16),this.movieMatrix=Rg(e)}break;case`trak`:{let t={id:-1,demuxer:this,trackBacking:null,disposition:{...um,primary:!1},info:null,timescale:-1,durationInMovieTimescale:-1,durationInMediaTimescale:-1,matrix:Jf,internalCodecId:null,name:null,languageCode:`und`,sampleTableByteOffset:-1,sampleTable:null,fragmentLookupTable:[],currentFragmentState:null,fragmentPositionCache:[],editListPreviousSegmentDurations:0,editListOffset:0,encryptionInfo:null,encryptionAuxInfo:null,frmaCodecString:null,maxBitrate:null,avgBitrate:null};this.currentTrack=t,this.readContiguousBoxes(e.slice(r,n.contentSize)),t.id!==-1&&t.timescale!==-1&&t.info!==null&&(t.info.type===`video`&&t.info.width!==-1?(t.trackBacking=new jg(t),this.tracks.push(t)):t.info.type===`audio`&&t.info.numberOfChannels!==-1&&(t.trackBacking=new Mg(t),this.tracks.push(t))),this.currentTrack=null}break;case`tkhd`:{let t=this.currentTrack;if(!t)break;let n=V(e),r=!!(F_(e)&1);if(t.disposition.default=r,n===0)e.skip(8),t.id=H(e),e.skip(4),t.durationInMovieTimescale=H(e);else if(n===1)e.skip(16),t.id=H(e),e.skip(4),t.durationInMovieTimescale=R_(e);else throw Error(`Incorrect track header version ${n}.`);e.skip(16),t.matrix=tp(Rg(e),this.movieMatrix)}break;case`elst`:{let t=this.currentTrack;if(!t)break;let n=V(e);e.skip(3);let r=!1,i=0,a=H(e);for(let o=0;o<a;o++){let a=n===1?R_(e):H(e),o=n===1?z_(e):L_(e),s=mg(e);if(r){om._warn(`Unsupported edit list: multiple edits are not currently supported. Only using first edit.`);break}if(o===-1){i+=a;continue}if(s!==1){om._warn(`Unsupported edit list entry: media rate must be 1.`);break}t.editListPreviousSegmentDurations=i,t.editListOffset=o,r=!0}}break;case`mdhd`:{let t=this.currentTrack;if(!t)break;let n=V(e);e.skip(3),n===0?(e.skip(8),t.timescale=H(e),t.durationInMediaTimescale=H(e)):n===1&&(e.skip(16),t.timescale=H(e),t.durationInMediaTimescale=R_(e));let r=P_(e);if(r>0){t.languageCode=``;for(let e=0;e<3;e++)t.languageCode=String.fromCharCode(96+(r&31))+t.languageCode,r>>=5;Hp(t.languageCode)||(t.languageCode=`und`)}}break;case`hdlr`:{let t=this.currentTrack;if(!t)break;e.skip(8);let n=V_(e,4);n===`vide`?t.info={type:`video`,width:-1,height:-1,squarePixelWidth:-1,squarePixelHeight:-1,codec:null,codecDescription:null,colorSpace:{...xp},avcType:null,avcCodecInfo:null,hevcCodecInfo:null,vp9CodecInfo:null,av1CodecInfo:null,proresCodecInfo:null,proresFormat:null}:n===`soun`&&(t.info={type:`audio`,numberOfChannels:-1,sampleRate:-1,codec:null,codecDescription:null,aacCodecInfo:null,dtsFormat:null,pcmLittleEndian:!1,pcmSampleSize:null})}break;case`stbl`:{let i=this.currentTrack;if(!i)break;i.sampleTableByteOffset=t,this.readContiguousBoxes(e.slice(r,n.contentSize))}break;case`stsd`:{let t=this.currentTrack;if(!t||t.info===null||t.sampleTable)break;let n=V(e);e.skip(3);let r=H(e);for(let i=0;i<r;i++){let r=e.filePos,i=pg(e);if(!i)break;t.internalCodecId=i.name;let a=i.name.toLowerCase();if(t.info.type===`video`){e.skip(24),t.info.width=P_(e),t.info.height=P_(e),t.info.squarePixelWidth=t.info.width,t.info.squarePixelHeight=t.info.height,e.skip(50),t.frmaCodecString=null,this.readContiguousBoxes(e.slice(e.filePos,r+i.totalSize-e.filePos));let n=a===`encv`?t.frmaCodecString:a;t.frmaCodecString=null,n===`avc1`||n===`avc3`?(t.info.codec=`avc`,t.info.avcType=n===`avc1`?1:3):n===`hvc1`||n===`hev1`?t.info.codec=`hevc`:n===`vp08`?t.info.codec=`vp8`:n===`vp09`?t.info.codec=`vp9`:n===`av01`?t.info.codec=`av1`:Hh.includes(a)?(t.info.codec=`prores`,t.info.proresFormat=a):n===null?om._warn(`Unknown encrypted video codec due to missing frma box.`):om._warn(`Unsupported video codec (sample entry type '${i.name}').`)}else{e.skip(8);let o=P_(e);e.skip(6);let s=P_(e),c=P_(e);e.skip(4);let l=H(e)/65536,u=null;n===0&&o>0&&(o===1?(e.skip(4),c=8*H(e),e.skip(8)):o===2&&(e.skip(4),l=B_(e),s=H(e),e.skip(4),c=H(e),u=H(e),e.skip(8))),t.info.numberOfChannels=s,t.info.sampleRate=l,t.frmaCodecString=null,this.readContiguousBoxes(e.slice(e.filePos,r+i.totalSize-e.filePos));let d=a===`enca`?t.frmaCodecString:a;if(t.frmaCodecString=null,d!==`mp4a`){if(d===`opus`)t.info.codec=`opus`,t.info.sampleRate=Jh;else if(d===`flac`)t.info.codec=`flac`;else if(d===`ulaw`)t.info.codec=`ulaw`;else if(d===`alaw`)t.info.codec=`alaw`;else if(d===`ac-3`)t.info.codec=`ac3`;else if(d===`ec-3`)t.info.codec=`eac3`;else if(Uh.includes(d))t.info.codec=`dts`,t.info.dtsFormat=d;else if(d===`twos`)c===8?t.info.codec=`pcm-s8`:c===16?t.info.codec=t.info.pcmLittleEndian?`pcm-s16`:`pcm-s16be`:(om._warn(`Unsupported sample size ${c} for codec 'twos'.`),t.info.codec=null);else if(d===`sowt`)c===8?t.info.codec=`pcm-s8`:c===16?t.info.codec=`pcm-s16`:(om._warn(`Unsupported sample size ${c} for codec 'sowt'.`),t.info.codec=null);else if(d===`raw `)t.info.codec=`pcm-u8`;else if(d===`in24`)t.info.codec=t.info.pcmLittleEndian?`pcm-s24`:`pcm-s24be`;else if(d===`in32`)t.info.codec=t.info.pcmLittleEndian?`pcm-s32`:`pcm-s32be`;else if(d===`fl32`)t.info.codec=t.info.pcmLittleEndian?`pcm-f32`:`pcm-f32be`;else if(d===`fl64`)t.info.codec=t.info.pcmLittleEndian?`pcm-f64`:`pcm-f64be`;else if(d===`ipcm`){let e=t.info.pcmSampleSize;t.info.pcmLittleEndian?e===16?t.info.codec=`pcm-s16`:e===24?t.info.codec=`pcm-s24`:e===32?t.info.codec=`pcm-s32`:(om._warn(`Invalid ipcm sample size ${e}.`),t.info.codec=null):e===16?t.info.codec=`pcm-s16be`:e===24?t.info.codec=`pcm-s24be`:e===32?t.info.codec=`pcm-s32be`:(om._warn(`Invalid ipcm sample size ${e}.`),t.info.codec=null)}else if(d===`fpcm`){let e=t.info.pcmSampleSize;t.info.pcmLittleEndian?e===32?t.info.codec=`pcm-f32`:e===64?t.info.codec=`pcm-f64`:(om._warn(`Invalid fpcm sample size ${e}.`),t.info.codec=null):e===32?t.info.codec=`pcm-f32be`:e===64?t.info.codec=`pcm-f64be`:(om._warn(`Invalid fpcm sample size ${e}.`),t.info.codec=null)}else if(d===`lpcm`&&u!==null){let e=c+7>>3,n=!!(u&1),r=!!(u&2),i=u&4?-1:0;c>0&&c<=64&&(n?c===32&&(t.info.codec=r?`pcm-f32be`:`pcm-f32`):i&1<<e-1?e===1?t.info.codec=`pcm-s8`:e===2?t.info.codec=r?`pcm-s16be`:`pcm-s16`:e===3?t.info.codec=r?`pcm-s24be`:`pcm-s24`:e===4&&(t.info.codec=r?`pcm-s32be`:`pcm-s32`):e===1&&(t.info.codec=`pcm-u8`)),t.info.codec===null&&om._warn(`Unsupported PCM format.`)}else d===null?om._warn(`Unknown encrypted audio codec due to missing frma box.`):om._warn(`Unsupported audio codec (sample entry type '${i.name}').`)}}e.filePos=r+i.totalSize}}break;case`frma`:{let t=this.currentTrack;if(!t)break;t.frmaCodecString=V_(e,4).toLowerCase()}break;case`schm`:{let t=this.currentTrack;if(!t)break;e.skip(4);let n=V_(e,4);n===`cenc`||n===`cens`||n===`cbcs`?t.encryptionInfo={scheme:n,defaultKid:null,defaultIsProtected:null,defaultPerSampleIvSize:null,defaultConstantIv:null,defaultCryptByteBlock:null,defaultSkipByteBlock:null}:om._warn(`Unsupported encryption scheme '${n}'.`)}break;case`tenc`:{let t=this.currentTrack;if(!t||!t.encryptionInfo)break;let n=V(e);e.skip(3),e.skip(1);let r=V(e);if(n>0?(t.encryptionInfo.defaultCryptByteBlock=r>>4,t.encryptionInfo.defaultSkipByteBlock=r&15):(t.encryptionInfo.defaultCryptByteBlock=0,t.encryptionInfo.defaultSkipByteBlock=0),t.encryptionInfo.defaultIsProtected=V(e)!==0,t.encryptionInfo.defaultPerSampleIvSize=V(e),t.encryptionInfo.defaultKid=Tp(N_(e,16)),t.encryptionInfo.defaultIsProtected&&t.encryptionInfo.defaultPerSampleIvSize===0){let n=V(e),r=/* @__PURE__ */ new Uint8Array(16);r.set(N_(e,n),0),t.encryptionInfo.defaultConstantIv=r}}break;case`avcC`:{let t=this.currentTrack;if(!t||(z(t.info),n.contentSize===0))break;t.info.codecDescription=N_(e,n.contentSize)}break;case`hvcC`:{let t=this.currentTrack;if(!t||(z(t.info),n.contentSize===0))break;t.info.codecDescription=N_(e,n.contentSize)}break;case`vpcC`:{let t=this.currentTrack;if(!t)break;z(t.info?.type===`video`),e.skip(4);let n=V(e),r=V(e),i=V(e),a=i>>4,o=i>>1&7,s=i&1,c=V(e),l=V(e),u=V(e);t.info.vp9CodecInfo={profile:n,level:r,bitDepth:a,chromaSubsampling:o,videoFullRangeFlag:s,colourPrimaries:c,transferCharacteristics:l,matrixCoefficients:u}}break;case`av1C`:{let t=this.currentTrack;if(!t)break;z(t.info?.type===`video`),e.skip(1);let r=V(e),i=r>>5,a=r&31,o=V(e),s=o>>7,c=o>>6&1,l=o>>5&1,u=o>>4&1,d=o>>3&1,f=o>>2&1,p=o&3,m=i===2&&c?l?12:10:c?10:8;e.skip(1);let h=nh(N_(e,n.contentSize-4));t.info.av1CodecInfo={profile:i,level:a,tier:s,bitDepth:m,monochrome:u,chromaSubsamplingX:d,chromaSubsamplingY:f,chromaSamplePosition:p,videoFullRangeFlag:h?.videoFullRangeFlag??0,colourPrimaries:h?.colourPrimaries??2,transferCharacteristics:h?.transferCharacteristics??2,matrixCoefficients:h?.matrixCoefficients??2}}break;case`colr`:{let t=this.currentTrack;if(!t)break;z(t.info?.type===`video`);let n=V_(e,4);if(n!==`nclx`&&n!==`nclc`)break;let r=P_(e),i=P_(e),a=P_(e),o;n===`nclx`&&(o=!!(V(e)&128)),t.info.colorSpace={primaries:mp[r],transfer:gp[i],matrix:vp[a],fullRange:o}}break;case`pasp`:{let t=this.currentTrack;if(!t)break;z(t.info?.type===`video`);let n=H(e),r=H(e);n>0&&r>0&&(n>r?t.info.squarePixelWidth=Math.round(t.info.width*n/r):t.info.squarePixelHeight=Math.round(t.info.height*r/n))}break;case`btrt`:{let t=this.currentTrack;if(!t)break;e.skip(4);let n=H(e),r=H(e);t.maxBitrate=n>0?n:null,t.avgBitrate=r>0?r:null}break;case`wave`:this.readContiguousBoxes(e.slice(r,n.contentSize));break;case`esds`:{let t=this.currentTrack;if(!t||t.info?.type!==`audio`)break;e.skip(4),z(V(e)===3),gg(e),e.skip(2);let n=V(e),r=!!(n&128),i=!!(n&64),a=!!(n&32);if(r&&e.skip(2),i){let t=V(e);e.skip(t)}a&&e.skip(2),z(V(e)===4);let o=gg(e),s=e.filePos,c=V(e);if(c===64||c===103?(t.info.codec=`aac`,t.info.aacCodecInfo={isMpeg2:c===103,objectType:null}):c===105||c===107?t.info.codec=`mp3`:c===221?t.info.codec=`vorbis`:c===169?t.info.codec=`dts`:om._warn(`Unsupported audio codec (objectTypeIndication ${c}) - discarding track.`),e.skip(12),o>e.filePos-s){z(V(e)===5);let n=gg(e);if(t.info.codecDescription=N_(e,n),t.info.codec===`aac`){let e=hm(t.info.codecDescription);e.outputNumberOfChannels!==null&&(t.info.numberOfChannels=e.outputNumberOfChannels),e.outputSampleRate!==null&&(t.info.sampleRate=e.outputSampleRate)}}}break;case`enda`:{let t=this.currentTrack;if(!t)break;z(t.info?.type===`audio`),t.info.pcmLittleEndian=!!(P_(e)&255)}break;case`pcmC`:{let t=this.currentTrack;if(!t)break;z(t.info?.type===`audio`),e.skip(4);let n=V(e);t.info.pcmLittleEndian=!!(n&1),t.info.pcmSampleSize=V(e)}break;case`dOps`:{let t=this.currentTrack;if(!t)break;z(t.info?.type===`audio`),e.skip(1);let n=V(e),r=P_(e),i=H(e),a=I_(e),o=V(e),s;s=o===0?/* @__PURE__ */ new Uint8Array:N_(e,2+n);let c=new Uint8Array(19+s.byteLength),l=new DataView(c.buffer);l.setUint32(0,1332770163,!1),l.setUint32(4,1214603620,!1),l.setUint8(8,1),l.setUint8(9,n),l.setUint16(10,r,!0),l.setUint32(12,i,!0),l.setInt16(16,a,!0),l.setUint8(18,o),c.set(s,19),t.info.codecDescription=c,t.info.numberOfChannels=n}break;case`dfLa`:{let t=this.currentTrack;if(!t)break;z(t.info?.type===`audio`),e.skip(4);let n=e.filePos;for(;e.filePos<i;){let n=V(e),r=F_(e);if((n&127)===sh.STREAMINFO){e.skip(10);let n=H(e),r=n>>>12,i=(n>>9&7)+1;t.info.sampleRate=r,t.info.numberOfChannels=i,e.skip(20)}else e.skip(r);if(n&128)break}let r=e.filePos;e.filePos=n;let a=N_(e,r-n),o=new Uint8Array(4+a.byteLength);new DataView(o.buffer).setUint32(0,1716281667,!1),o.set(a,4),t.info.codecDescription=o}break;case`dac3`:{let t=this.currentTrack;if(!t)break;z(t.info?.type===`audio`);let n=new fm(N_(e,3)),r=n.readBits(2);n.skipBits(8);let i=n.readBits(3),a=n.readBits(1);r<3&&(t.info.sampleRate=Sm[r]),t.info.numberOfChannels=ch[i]+a}break;case`dec3`:{let t=this.currentTrack;if(!t)break;z(t.info?.type===`audio`);let r=fh(N_(e,n.contentSize));if(!r){om._warn(`Invalid dec3 box contents, ignoring.`);break}let i=ph(r);i!==null&&(t.info.sampleRate=i),t.info.numberOfChannels=mh(r)}break;case`ddts`:{let t=this.currentTrack;if(!t)break;z(t.info?.type===`audio`);let r=Ah(N_(e,Math.min(n.contentSize,20)));if(!r){om._warn(`Invalid ddts box contents, ignoring.`);break}t.info.sampleRate=r.sampleRate,r.numberOfChannels!==null&&(t.info.numberOfChannels=r.numberOfChannels)}break;case`stts`:{let t=this.currentTrack;if(!t||!t.sampleTable)break;e.skip(4);let n=H(e),r=0,i=0;for(let a=0;a<n;a++){let n=H(e),a=H(e);t.sampleTable.sampleTimingEntries.push({startIndex:r,startDecodeTimestamp:i,count:n,delta:a}),r+=n,i+=n*a}}break;case`ctts`:{let t=this.currentTrack;if(!t||!t.sampleTable)break;e.skip(4);let n=H(e),r=0;for(let i=0;i<n;i++){let n=H(e),i=L_(e);t.sampleTable.sampleCompositionTimeOffsets.push({startIndex:r,count:n,offset:i}),r+=n}}break;case`stsz`:{let t=this.currentTrack;if(!t||!t.sampleTable)break;e.skip(4);let n=H(e),r=H(e);if(n===0)for(let n=0;n<r;n++){let n=H(e);t.sampleTable.sampleSizes.push(n)}else t.sampleTable.sampleSizes.push(n)}break;case`stz2`:{let t=this.currentTrack;if(!t||!t.sampleTable)break;e.skip(4),e.skip(3);let n=V(e),r=H(e),i=new fm(N_(e,Math.ceil(r*n/8)));for(let e=0;e<r;e++){let e=i.readBits(n);t.sampleTable.sampleSizes.push(e)}}break;case`stss`:{let t=this.currentTrack;if(!t||!t.sampleTable)break;e.skip(4),t.sampleTable.keySampleIndices=[];let n=H(e);for(let r=0;r<n;r++){let n=H(e)-1;t.sampleTable.keySampleIndices.push(n)}t.sampleTable.keySampleIndices[0]!==0&&t.sampleTable.keySampleIndices.unshift(0)}break;case`stsc`:{let t=this.currentTrack;if(!t||!t.sampleTable)break;e.skip(4);let n=H(e);for(let r=0;r<n;r++){let n=H(e)-1,r=H(e),i=H(e);t.sampleTable.sampleToChunk.push({startSampleIndex:-1,startChunkIndex:n,samplesPerChunk:r,sampleDescriptionIndex:i})}let r=0;for(let e=0;e<t.sampleTable.sampleToChunk.length;e++)if(t.sampleTable.sampleToChunk[e].startSampleIndex=r,e<t.sampleTable.sampleToChunk.length-1){let n=t.sampleTable.sampleToChunk[e+1].startChunkIndex-t.sampleTable.sampleToChunk[e].startChunkIndex;r+=n*t.sampleTable.sampleToChunk[e].samplesPerChunk}}break;case`stco`:{let t=this.currentTrack;if(!t||!t.sampleTable)break;e.skip(4);let n=H(e);for(let r=0;r<n;r++){let n=H(e);t.sampleTable.chunkOffsets.push(n)}}break;case`co64`:{let t=this.currentTrack;if(!t||!t.sampleTable)break;e.skip(4);let n=H(e);for(let r=0;r<n;r++){let n=R_(e);t.sampleTable.chunkOffsets.push(n)}}break;case`mvex`:this.isFragmented=!0,this.readContiguousBoxes(e.slice(r,n.contentSize));break;case`mehd`:{let t=V(e);e.skip(3);let n=t===1?R_(e):H(e);this.movieDurationInTimescale=n}break;case`trex`:{e.skip(4);let t=H(e),n=H(e),r=H(e),i=H(e),a=H(e);this.fragmentTrackDefaults.push({trackId:t,defaultSampleDescriptionIndex:n,defaultSampleDuration:r,defaultSampleSize:i,defaultSampleFlags:a})}break;case`tfra`:{let t=V(e);e.skip(3);let n=H(e),r=this.tracks.find(e=>e.id===n);if(!r)break;let i=H(e),a=(i&48)>>4,o=(i&12)>>2,s=i&3,c=[V,P_,F_,H],l=c[a],u=c[o],d=c[s],f=H(e);for(let n=0;n<f;n++){let n=t===1?R_(e):H(e),i=t===1?R_(e):H(e);l(e),u(e),d(e),r.fragmentLookupTable.push({timestamp:n,moofOffset:i})}r.fragmentLookupTable.sort((e,t)=>e.timestamp-t.timestamp);for(let e=0;e<r.fragmentLookupTable.length-1;e++){let t=r.fragmentLookupTable[e],n=r.fragmentLookupTable[e+1];t.timestamp===n.timestamp&&(r.fragmentLookupTable.splice(e+1,1),e--)}}break;case`moof`:this.currentFragment={moofOffset:t,moofSize:n.totalSize,implicitBaseDataOffset:t,trackData:/* @__PURE__ */ new Map,psshBoxes:[]},this.readContiguousBoxes(e.slice(r,n.contentSize)),this.lastReadFragment=this.currentFragment,this.currentFragment=null;break;case`traf`:if(z(this.currentFragment),this.readContiguousBoxes(e.slice(r,n.contentSize)),this.currentTrack){let e=this.currentFragment.trackData.get(this.currentTrack.id);cond:if(e){if(e.samples.length===0){this.currentFragment.trackData.delete(this.currentTrack.id);break cond}e.presentationTimestamps=e.samples.map((e,t)=>({presentationTimestamp:e.presentationTimestamp,sampleIndex:t})).sort((e,t)=>e.presentationTimestamp-t.presentationTimestamp);for(let t=0;t<e.presentationTimestamps.length;t++){let n=e.presentationTimestamps[t],r=e.samples[n.sampleIndex];e.firstKeyFrameTimestamp===null&&r.isKeyFrame&&(e.firstKeyFrameTimestamp=r.presentationTimestamp),t<e.presentationTimestamps.length-1&&(r.duration=e.presentationTimestamps[t+1].presentationTimestamp-n.presentationTimestamp)}let t=e.samples[e.presentationTimestamps[0].sampleIndex],n=e.samples[np(e.presentationTimestamps).sampleIndex];e.startTimestamp=t.presentationTimestamp,e.endTimestamp=n.presentationTimestamp+n.duration;let{currentFragmentState:r}=this.currentTrack;z(r),r.startTimestamp!==null&&(Lg(e,r.startTimestamp),e.startTimestampIsFinal=!0),r.encryptionAuxInfo&&!e.samples[0].encryption&&(e.encryptionAuxInfo=r.encryptionAuxInfo)}this.currentTrack.currentFragmentState=null,this.currentTrack=null}break;case`pssh`:{if(this.input._formatOptions.isobmff?._suppressPsshParsing)break;let t=dg(N_(e,n.contentSize));this.currentFragment?this.currentFragment.psshBoxes.push(t):this.currentTrack||this.psshBoxes.push(t)}break;case`tfhd`:{z(this.currentFragment),e.skip(1);let t=F_(e),n=!!(t&1),r=!!(t&2),i=!!(t&8),a=!!(t&16),o=!!(t&32),s=!!(t&65536),c=!!(t&131072),l=H(e),u=this.tracks.find(e=>e.id===l);if(!u)break;let d=this.fragmentTrackDefaults.find(e=>e.trackId===l);this.currentTrack=u,u.currentFragmentState={baseDataOffset:this.currentFragment.implicitBaseDataOffset,sampleDescriptionIndex:d?.defaultSampleDescriptionIndex??null,defaultSampleDuration:d?.defaultSampleDuration??null,defaultSampleSize:d?.defaultSampleSize??null,defaultSampleFlags:d?.defaultSampleFlags??null,startTimestamp:null,encryptionAuxInfo:null},n?u.currentFragmentState.baseDataOffset=R_(e):c&&(u.currentFragmentState.baseDataOffset=this.currentFragment.moofOffset),r&&(u.currentFragmentState.sampleDescriptionIndex=H(e)),i&&(u.currentFragmentState.defaultSampleDuration=H(e)),a&&(u.currentFragmentState.defaultSampleSize=H(e)),o&&(u.currentFragmentState.defaultSampleFlags=H(e)),s&&(u.currentFragmentState.defaultSampleDuration=0)}break;case`tfdt`:{let t=this.currentTrack;if(!t)break;z(t.currentFragmentState);let n=V(e);e.skip(3);let r=n===0?H(e):R_(e);t.currentFragmentState.startTimestamp=r}break;case`trun`:{let t=this.currentTrack;if(!t)break;z(this.currentFragment),z(t.currentFragmentState);let n=V(e),r=F_(e),i=!!(r&1),a=!!(r&4),o=!!(r&256),s=!!(r&512),c=!!(r&1024),l=!!(r&2048),u=H(e),d=null;i&&(d=L_(e));let f=null;a&&(f=H(e));let p;this.currentFragment.trackData.has(t.id)?(p=this.currentFragment.trackData.get(t.id),d!==null&&(p.currentOffset=t.currentFragmentState.baseDataOffset+d)):(p={track:t,currentTimestamp:0,currentOffset:t.currentFragmentState.baseDataOffset+(d??0),startTimestamp:0,endTimestamp:0,firstKeyFrameTimestamp:null,samples:[],presentationTimestamps:[],startTimestampIsFinal:!1,encryptionAuxInfo:null},this.currentFragment.trackData.set(t.id,p));for(let r=0;r<u;r++){let i;o?i=H(e):(z(t.currentFragmentState.defaultSampleDuration!==null),i=t.currentFragmentState.defaultSampleDuration);let a;s?a=H(e):(z(t.currentFragmentState.defaultSampleSize!==null),a=t.currentFragmentState.defaultSampleSize);let u;c?u=H(e):(z(t.currentFragmentState.defaultSampleFlags!==null),u=t.currentFragmentState.defaultSampleFlags),r===0&&f!==null&&(u=f);let d=0;l&&(d=n===0?H(e):L_(e));let m=!(u&65536);p.samples.push({presentationTimestamp:p.currentTimestamp+d,duration:i,byteOffset:p.currentOffset,byteSize:a,isKeyFrame:m,encryption:null}),p.currentOffset+=a,p.currentTimestamp+=i}this.currentFragment.implicitBaseDataOffset=p.currentOffset}break;case`saiz`:{let t=this.currentTrack;if(!t||!t.encryptionInfo)break;if(e.skip(1),F_(e)&1){let n=V_(e,4),r=H(e);if(n!==t.encryptionInfo.scheme||r!==0)break}let n=V(e),r=H(e),i=null;n===0&&r>0&&(i=N_(e,r));let a=Bg(t);a.defaultSampleInfoSize=n,a.sampleSizes=i,a.sampleCount=r}break;case`saio`:{let t=this.currentTrack;if(!t||!t.encryptionInfo)break;let n=V(e);if(F_(e)&1){let n=V_(e,4),r=H(e);if(n!==t.encryptionInfo.scheme||r!==0)break}let r=H(e);if(r===0)break;r>1&&om._warn(`Multiple saio entries are not supported; using the first offset only.`);let i=n===0?H(e):Number(R_(e));this.currentFragment&&(i+=this.currentFragment.moofOffset);let a=Bg(t);a.offset=i}break;case`senc`:{let t=this.currentTrack;if(!t||!t.encryptionInfo)break;z(this.currentFragment);let n=this.currentFragment.trackData.get(t.id);if(!n)break;e.skip(1);let r=!!(F_(e)&2),i=H(e),a=t.encryptionInfo.defaultPerSampleIvSize;z(a!==null);for(let o=0;o<Math.min(i,n.samples.length);o++){let i=/* @__PURE__ */ new Uint8Array(16);a>0?i.set(N_(e,a),0):i.set(t.encryptionInfo.defaultConstantIv,0);let s=null;if(r){let t=P_(e);s=[];for(let n=0;n<t;n++){let t=P_(e),n=H(e);s.push({clearLen:t,protectedLen:n})}}let c=n.samples[o];c.encryption={iv:i,subsamples:s}}}break;case`udta`:{let t=this.iterateContiguousBoxes(e.slice(r,n.contentSize));for(let{boxInfo:e,slice:n}of t){if(e.name!==`meta`&&!this.currentTrack){let t=n.filePos;this.metadataTags.raw??={},e.name[0]===`©`?this.metadataTags.raw[e.name]??=_g(n):this.metadataTags.raw[e.name]??=N_(n,e.contentSize),n.filePos=t}switch(e.name){case`meta`:n.skip(-e.headerSize),this.traverseBox(n);break;case`©nam`:case`name`:this.currentTrack?this.currentTrack.name=up.decode(N_(n,e.contentSize)):this.metadataTags.title??=_g(n);break;case`©des`:this.currentTrack||(this.metadataTags.description??=_g(n));break;case`©ART`:this.currentTrack||(this.metadataTags.artist??=_g(n));break;case`©alb`:this.currentTrack||(this.metadataTags.album??=_g(n));break;case`albr`:this.currentTrack||(this.metadataTags.albumArtist??=_g(n));break;case`©gen`:this.currentTrack||(this.metadataTags.genre??=_g(n));break;case`©day`:if(!this.currentTrack){let e=new Date(_g(n));Number.isNaN(e.getTime())||(this.metadataTags.date??=e)}break;case`©cmt`:this.currentTrack||(this.metadataTags.comment??=_g(n));break;case`©lyr`:this.currentTrack||(this.metadataTags.lyrics??=_g(n))}}}break;case`meta`:{if(this.currentTrack)break;let t=H(e)!==0;this.currentMetadataKeys=/* @__PURE__ */ new Map,t?this.readContiguousBoxes(e.slice(r,n.contentSize)):this.readContiguousBoxes(e.slice(r+4,n.contentSize-4)),this.currentMetadataKeys=null}break;case`keys`:{if(!this.currentMetadataKeys)break;e.skip(4);let t=H(e);for(let n=0;n<t;n++){let t=H(e);e.skip(4);let r=up.decode(N_(e,t-8));this.currentMetadataKeys.set(n+1,r)}}break;case`ilst`:{if(!this.currentMetadataKeys)break;let t=this.iterateContiguousBoxes(e.slice(r,n.contentSize));for(let{boxInfo:e,slice:n}of t){let t=e.name,r=(t.charCodeAt(0)<<24)+(t.charCodeAt(1)<<16)+(t.charCodeAt(2)<<8)+t.charCodeAt(3);this.currentMetadataKeys.has(r)&&(t=this.currentMetadataKeys.get(r));let i=vg(n);switch(this.metadataTags.raw??={},this.metadataTags.raw[t]??=i,t){case`©nam`:case`titl`:case`com.apple.quicktime.title`:case`title`:typeof i==`string`&&(this.metadataTags.title??=i);break;case`©des`:case`desc`:case`dscp`:case`com.apple.quicktime.description`:case`description`:typeof i==`string`&&(this.metadataTags.description??=i);break;case`©ART`:case`com.apple.quicktime.artist`:case`artist`:typeof i==`string`&&(this.metadataTags.artist??=i);break;case`©alb`:case`albm`:case`com.apple.quicktime.album`:case`album`:typeof i==`string`&&(this.metadataTags.album??=i);break;case`aART`:case`album_artist`:typeof i==`string`&&(this.metadataTags.albumArtist??=i);break;case`©cmt`:case`com.apple.quicktime.comment`:case`comment`:typeof i==`string`&&(this.metadataTags.comment??=i);break;case`©gen`:case`gnre`:case`com.apple.quicktime.genre`:case`genre`:typeof i==`string`&&(this.metadataTags.genre??=i);break;case`©lyr`:case`lyrics`:typeof i==`string`&&(this.metadataTags.lyrics??=i);break;case`©day`:case`rldt`:case`com.apple.quicktime.creationdate`:case`date`:if(typeof i==`string`){let e=new Date(i);Number.isNaN(e.getTime())||(this.metadataTags.date??=e)}break;case`covr`:case`com.apple.quicktime.artwork`:i instanceof sm?(this.metadataTags.images??=[],this.metadataTags.images.push({data:i.data,kind:`coverFront`,mimeType:i.mimeType})):i instanceof Uint8Array&&(this.metadataTags.images??=[],this.metadataTags.images.push({data:i,kind:`coverFront`,mimeType:`image/*`}));break;case`track`:if(typeof i==`string`){let e=i.split(`/`),t=Number.parseInt(e[0],10),n=e[1]&&Number.parseInt(e[1],10);Number.isInteger(t)&&t>0&&(this.metadataTags.trackNumber??=t),n&&Number.isInteger(n)&&n>0&&(this.metadataTags.tracksTotal??=n)}break;case`trkn`:if(i instanceof Uint8Array&&i.length>=6){let e=sp(i),t=e.getUint16(2,!1),n=e.getUint16(4,!1);t>0&&(this.metadataTags.trackNumber??=t),n>0&&(this.metadataTags.tracksTotal??=n)}break;case`disc`:case`disk`:if(i instanceof Uint8Array&&i.length>=6){let e=sp(i),t=e.getUint16(2,!1),n=e.getUint16(4,!1);t>0&&(this.metadataTags.discNumber??=t),n>0&&(this.metadataTags.discsTotal??=n)}}}}}return e.filePos=i,!0}},Ag=class{constructor(e){this.internalTrack=e,this.packetToSampleIndex=/* @__PURE__ */ new WeakMap,this.packetToFragmentLocation=/* @__PURE__ */ new WeakMap}getId(){return this.internalTrack.id}getNumber(){let e=this.internalTrack.demuxer,t=this.internalTrack.trackBacking.getType(),n=0;for(let r of e.tracks)if(r.trackBacking.getType()===t&&n++,r===this.internalTrack)break;return n}getCodec(){throw Error(`Not implemented on base class.`)}getInternalCodecId(){return this.internalTrack.internalCodecId}getName(){return this.internalTrack.name}getLanguageCode(){return this.internalTrack.languageCode}getTimeResolution(){return this.internalTrack.timescale}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getDisposition(){return this.internalTrack.disposition}getPairingMask(){return 1n}getBitrate(){return this.internalTrack.maxBitrate}getAverageBitrate(){return this.internalTrack.avgBitrate}async getDurationFromMetadata(){let e=this.internalTrack;return e.durationInMediaTimescale<=0?null:(z(e.trackBacking),((await e.trackBacking.getFirstPacket({metadataOnly:!0}))?.timestamp??0)+e.durationInMediaTimescale/e.timescale)}async getLiveRefreshInterval(){return null}async getFirstPacket(e){let t=await this.fetchPacketForSampleIndex(0,e);return t||!this.internalTrack.demuxer.isFragmented?t:this.performFragmentedLookup(null,e=>e.trackData.get(this.internalTrack.id)?{sampleIndex:0,correctSampleFound:!0}:{sampleIndex:-1,correctSampleFound:!1},-1/0,1/0,e)}mapTimestampIntoTimescale(e){return Lp(e*this.internalTrack.timescale)+this.internalTrack.editListOffset}async getPacket(e,t){let n=this.mapTimestampIntoTimescale(e),r=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),i=Ng(r,n),a=await this.fetchPacketForSampleIndex(i,t);return!zg(r)||!this.internalTrack.demuxer.isFragmented?a:this.performFragmentedLookup(null,e=>{let t=e.trackData.get(this.internalTrack.id);if(!t)return{sampleIndex:-1,correctSampleFound:!1};let r=kp(t.presentationTimestamps,n,e=>e.presentationTimestamp);return{sampleIndex:r===-1?-1:t.presentationTimestamps[r].sampleIndex,correctSampleFound:r!==-1&&n<t.endTimestamp}},n,n,t)}async getNextPacket(e,t){let n=this.packetToSampleIndex.get(e);if(n!==void 0)return this.fetchPacketForSampleIndex(n+1,t);let r=this.packetToFragmentLocation.get(e);if(r===void 0)throw Error(`Packet was not created from this track.`);return this.performFragmentedLookup(r.fragment,e=>{if(e===r.fragment){let t=e.trackData.get(this.internalTrack.id);if(r.sampleIndex+1<t.samples.length)return{sampleIndex:r.sampleIndex+1,correctSampleFound:!0}}else if(e.trackData.get(this.internalTrack.id))return{sampleIndex:0,correctSampleFound:!0};return{sampleIndex:-1,correctSampleFound:!1}},-1/0,1/0,t)}async getKeyPacket(e,t){let n=this.mapTimestampIntoTimescale(e),r=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),i=Pg(r,n),a=await this.fetchPacketForSampleIndex(i,t);return!zg(r)||!this.internalTrack.demuxer.isFragmented?a:this.performFragmentedLookup(null,e=>{let t=e.trackData.get(this.internalTrack.id);if(!t)return{sampleIndex:-1,correctSampleFound:!1};let r=Mp(t.presentationTimestamps,e=>t.samples[e.sampleIndex].isKeyFrame&&e.presentationTimestamp<=n);return{sampleIndex:r===-1?-1:t.presentationTimestamps[r].sampleIndex,correctSampleFound:r!==-1&&n<t.endTimestamp}},n,n,t)}async getNextKeyPacket(e,t){let n=this.packetToSampleIndex.get(e);if(n!==void 0){let e=Ig(this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),n);return this.fetchPacketForSampleIndex(e,t)}let r=this.packetToFragmentLocation.get(e);if(r===void 0)throw Error(`Packet was not created from this track.`);return this.performFragmentedLookup(r.fragment,e=>{if(e===r.fragment){let t=e.trackData.get(this.internalTrack.id).samples.findIndex((e,t)=>e.isKeyFrame&&t>r.sampleIndex);if(t!==-1)return{sampleIndex:t,correctSampleFound:!0}}else{let t=e.trackData.get(this.internalTrack.id);if(t&&t.firstKeyFrameTimestamp!==null){let e=t.samples.findIndex(e=>e.isKeyFrame);return z(e!==-1),{sampleIndex:e,correctSampleFound:!0}}}return{sampleIndex:-1,correctSampleFound:!1}},-1/0,1/0,t)}async fetchPacketForSampleIndex(e,t){if(e===-1)return null;let n=Fg(this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),e);if(!n)return null;let r;if(t.metadataOnly)r=cg;else{let t=this.internalTrack.demuxer.reader.requestSlice(n.sampleOffset,n.sampleSize);if(Jp(t)&&(t=await t),!t)return null;if(r=N_(t,n.sampleSize),this.internalTrack.encryptionInfo){let t=null;if(this.internalTrack.encryptionAuxInfo){let n=await Vg(this.internalTrack.demuxer.reader,this.internalTrack.encryptionInfo,this.internalTrack.encryptionAuxInfo);e<n.length&&(t=n[e])}t??=Hg(this.internalTrack.encryptionInfo),t&&(r=await Ug(this.internalTrack,t,r,null))}}let i=(n.presentationTimestamp-this.internalTrack.editListOffset)/this.internalTrack.timescale,a=n.duration/this.internalTrack.timescale,o=new lg(r,n.isKeyFrame?`key`:`delta`,i,a,e,n.sampleSize);return this.packetToSampleIndex.set(o,e),o}async fetchPacketInFragment(e,t,n){if(t===-1)return null;let r=e.trackData.get(this.internalTrack.id).samples[t];z(r);let i;if(n.metadataOnly)i=cg;else{let t=this.internalTrack.demuxer.reader.requestSlice(r.byteOffset,r.byteSize);if(Jp(t)&&(t=await t),!t)return null;if(i=N_(t,r.byteSize),this.internalTrack.encryptionInfo){let t=r.encryption??Hg(this.internalTrack.encryptionInfo);t&&(i=await Ug(this.internalTrack,t,i,e))}}let a=(r.presentationTimestamp-this.internalTrack.editListOffset)/this.internalTrack.timescale,o=r.duration/this.internalTrack.timescale,s=new lg(i,r.isKeyFrame?`key`:`delta`,a,o,e.moofOffset+t,r.byteSize);return this.packetToFragmentLocation.set(s,{fragment:e,sampleIndex:t}),s}async performFragmentedLookup(e,t,n,r,i){let a=this.internalTrack.demuxer,o=null,s=null,c=-1;if(e){let{sampleIndex:n,correctSampleFound:r}=t(e);if(r)return this.fetchPacketInFragment(e,n,i);n!==-1&&(s=e,c=n)}let l=kp(this.internalTrack.fragmentLookupTable,n,e=>e.timestamp),u=l===-1?null:this.internalTrack.fragmentLookupTable[l],d=kp(this.internalTrack.fragmentPositionCache,n,e=>e.startTimestamp),f=d===-1?null:this.internalTrack.fragmentPositionCache[d],p=Math.max(u?.moofOffset??0,f?.moofOffset??0)||null,m;for(e?p===null||e.moofOffset>=p?(m=e.moofOffset+e.moofSize,o=e):m=p:m=p??0;;){if(o){let e=o.trackData.get(this.internalTrack.id);if(e&&e.startTimestamp>r)break}let e=a.reader.requestSliceRange(m,8,16);if(Jp(e)&&(e=await e),!e)break;let n=m,l=pg(e);if(!l)break;if(l.name===`moof`){o=await a.readFragment(n);let{sampleIndex:e,correctSampleFound:r}=t(o);if(r)return this.fetchPacketInFragment(o,e,i);e!==-1&&(s=o,c=e)}m=n+l.totalSize}if(u&&(!s||s.moofOffset<u.moofOffset)){let e=this.internalTrack.fragmentLookupTable[l-1];z(!e||e.timestamp<u.timestamp);let n=e?.timestamp??-1/0;return this.performFragmentedLookup(null,t,n,r,i)}return s?this.fetchPacketInFragment(s,c,i):null}},jg=class extends Ag{constructor(e){super(e),this.decoderConfigPromise=null,this.internalTrack=e}getType(){return`video`}getCodec(){return this.internalTrack.info.codec}getCodedWidth(){return this.internalTrack.info.width}getCodedHeight(){return this.internalTrack.info.height}getSquarePixelWidth(){return this.internalTrack.info.squarePixelWidth}getSquarePixelHeight(){return this.internalTrack.info.squarePixelHeight}getTransformationMatrix(){return[...this.internalTrack.matrix]}async getColorSpace(){let e=await this.getDecoderConfig();return e?{primaries:e.colorSpace?.primaries,transfer:e.colorSpace?.transfer,matrix:e.colorSpace?.matrix,fullRange:e.colorSpace?.fullRange}:this.internalTrack.info.colorSpace}async canBeTransparent(){return this.internalTrack.info.codec===`prores`&&(this.internalTrack.info.proresFormat===`ap4h`||this.internalTrack.info.proresFormat===`ap4x`)}async getDecoderConfig(){return this.internalTrack.info.codec?this.decoderConfigPromise??=(async()=>{if(this.internalTrack.info.codec===`avc`&&!this.internalTrack.info.codecDescription){let e=await this.getFirstPacket({});this.internalTrack.info.avcCodecInfo=e&&Mm(e.data)}else if(this.internalTrack.info.codec===`hevc`&&!this.internalTrack.info.codecDescription){let e=await this.getFirstPacket({});this.internalTrack.info.hevcCodecInfo=e&&Vm(e.data)}else if(this.internalTrack.info.codec===`vp9`&&(!this.internalTrack.info.vp9CodecInfo||!eh(this.internalTrack.info.vp9CodecInfo))){let e=await this.getFirstPacket({}),t=e&&$m(e.data);t&&(this.internalTrack.info.vp9CodecInfo={...this.internalTrack.info.vp9CodecInfo??t,videoFullRangeFlag:t.videoFullRangeFlag,colourPrimaries:t.colourPrimaries,transferCharacteristics:t.transferCharacteristics,matrixCoefficients:t.matrixCoefficients})}else if(this.internalTrack.info.codec===`av1`&&(!this.internalTrack.info.av1CodecInfo||!rh(this.internalTrack.info.av1CodecInfo))){let e=await this.getFirstPacket({}),t=e&&nh(e.data);t&&(this.internalTrack.info.av1CodecInfo=t)}else if(this.internalTrack.info.codec===`prores`&&!this.internalTrack.info.proresCodecInfo){let e=await this.getFirstPacket({});this.internalTrack.info.proresCodecInfo=e&&ih(e.data)}if(!yp(this.internalTrack.info.colorSpace)){let e=Kh(this.internalTrack.info);this.internalTrack.info.colorSpace.primaries??=e.primaries,this.internalTrack.info.colorSpace.transfer??=e.transfer,this.internalTrack.info.colorSpace.matrix??=e.matrix,this.internalTrack.info.colorSpace.fullRange??=e.fullRange}let e={codec:Gh(this.internalTrack.info),codedWidth:this.internalTrack.info.width,codedHeight:this.internalTrack.info.height,description:this.internalTrack.info.codecDescription??void 0,colorSpace:this.internalTrack.info.colorSpace};return(this.internalTrack.info.width!==this.internalTrack.info.squarePixelWidth||this.internalTrack.info.height!==this.internalTrack.info.squarePixelHeight)&&(e.displayAspectWidth=this.internalTrack.info.squarePixelWidth,e.displayAspectHeight=this.internalTrack.info.squarePixelHeight),e})():null}},Mg=class extends Ag{constructor(e){super(e),this.decoderConfigPromise=null,this.internalTrack=e}getType(){return`audio`}getCodec(){return this.internalTrack.info.codec}getNumberOfChannels(){return this.internalTrack.info.numberOfChannels}getSampleRate(){return this.internalTrack.info.sampleRate}async getDecoderConfig(){return this.internalTrack.info.codec?this.decoderConfigPromise??=(async()=>{if(this.internalTrack.info.codec===`dts`&&!this.internalTrack.info.dtsFormat){let e=await this.getFirstPacket({});this.internalTrack.info.dtsFormat=e&&Dh(e.data)}return{codec:qh(this.internalTrack.info),numberOfChannels:this.internalTrack.info.numberOfChannels,sampleRate:this.internalTrack.info.sampleRate,description:this.internalTrack.info.codecDescription??void 0}})():null}},Ng=(e,t)=>{if(e.presentationTimestamps){let n=kp(e.presentationTimestamps,t,e=>e.presentationTimestamp);return n===-1?-1:e.presentationTimestamps[n].sampleIndex}{let n=kp(e.sampleTimingEntries,t,e=>e.startDecodeTimestamp);if(n===-1)return-1;let r=e.sampleTimingEntries[n];return r.startIndex+Math.min(Math.floor((t-r.startDecodeTimestamp)/r.delta),r.count-1)}},Pg=(e,t)=>{if(!e.keySampleIndices)return Ng(e,t);if(e.presentationTimestamps){let n=kp(e.presentationTimestamps,t,e=>e.presentationTimestamp);if(n===-1)return-1;for(let t=n;t>=0;t--){let n=e.presentationTimestamps[t].sampleIndex;if(Op(e.keySampleIndices,n,e=>e)!==-1)return n}return-1}{let n=Ng(e,t),r=kp(e.keySampleIndices,n,e=>e);return e.keySampleIndices[r]??-1}},Fg=(e,t)=>{let n=kp(e.sampleTimingEntries,t,e=>e.startIndex),r=e.sampleTimingEntries[n];if(!r||r.startIndex+r.count<=t)return null;let i=r.startDecodeTimestamp+(t-r.startIndex)*r.delta,a=kp(e.sampleCompositionTimeOffsets,t,e=>e.startIndex),o=e.sampleCompositionTimeOffsets[a];o&&t-o.startIndex<o.count&&(i+=o.offset);let s=e.sampleSizes[Math.min(t,e.sampleSizes.length-1)],c=kp(e.sampleToChunk,t,e=>e.startSampleIndex),l=e.sampleToChunk[c];z(l);let u=l.startChunkIndex+Math.floor((t-l.startSampleIndex)/l.samplesPerChunk),d=e.chunkOffsets[u],f=l.startSampleIndex+(u-l.startChunkIndex)*l.samplesPerChunk,p=0,m=d;if(e.sampleSizes.length===1)m+=s*(t-f),p+=s*l.samplesPerChunk;else for(let n=f;n<f+l.samplesPerChunk;n++){let r=e.sampleSizes[n];n<t&&(m+=r),p+=r}let h=r.delta;if(e.presentationTimestamps){let n=e.presentationTimestampIndexMap[t];z(n!==void 0),n<e.presentationTimestamps.length-1&&(h=e.presentationTimestamps[n+1].presentationTimestamp-i)}return{presentationTimestamp:i,duration:h,sampleOffset:m,sampleSize:s,chunkOffset:d,chunkSize:p,isKeyFrame:!e.keySampleIndices||Op(e.keySampleIndices,t,e=>e)!==-1}},Ig=(e,t)=>{if(!e.keySampleIndices)return t+1;let n=kp(e.keySampleIndices,t,e=>e);return e.keySampleIndices[n+1]??-1},Lg=(e,t)=>{e.startTimestamp+=t,e.endTimestamp+=t;for(let n of e.samples)n.presentationTimestamp+=t;for(let n of e.presentationTimestamps)n.presentationTimestamp+=t},Rg=e=>[mg(e),mg(e),hg(e),mg(e),mg(e),hg(e),mg(e),mg(e),hg(e)],zg=e=>e.sampleSizes.length===0,Bg=e=>e.currentFragmentState?e.currentFragmentState.encryptionAuxInfo??={defaultSampleInfoSize:0,sampleSizes:null,sampleCount:0,offset:null,resolved:null}:e.encryptionAuxInfo??={defaultSampleInfoSize:0,sampleSizes:null,sampleCount:0,offset:null,resolved:null},Vg=async(e,t,n)=>{if(n.resolved)return n.resolved;if(n.offset===null||n.sampleCount===0)throw Error(`Incomplete saiz/saio info; cannot resolve encryption data.`);let r=0;if(n.defaultSampleInfoSize>0)r=n.defaultSampleInfoSize*n.sampleCount;else{z(n.sampleSizes);for(let e=0;e<n.sampleCount;e++)r+=n.sampleSizes[e]}let i=e.requestSlice(n.offset,r);if(Jp(i)&&(i=await i),!i)throw Error(`Failed to read auxiliary encryption info.`);let a=t.defaultPerSampleIvSize;z(a!==null);let o=[];for(let e=0;e<n.sampleCount;e++){let r=n.defaultSampleInfoSize>0?n.defaultSampleInfoSize:n.sampleSizes[e],s=/* @__PURE__ */ new Uint8Array(16);a>0?s.set(N_(i,a),0):s.set(t.defaultConstantIv,0);let c=null;if(r>a){let e=P_(i);c=[];for(let t=0;t<e;t++){let e=P_(i),t=H(i);c.push({clearLen:e,protectedLen:t})}}o.push({iv:s,subsamples:c})}return n.resolved=o,o},Hg=e=>e.defaultConstantIv?{iv:e.defaultConstantIv,subsamples:null}:null,Ug=async(e,t,n,r)=>{z(e.encryptionInfo);let i=e.encryptionInfo;z(i.defaultKid!==null);let a=i.defaultKid,o,s=e.demuxer.decryptionKeyCache.get(a);if(s)o=await s;else{if(!e.demuxer.input._formatOptions.isobmff?.resolveKeyId)throw Error(`Encrypted media samples encountered. To decrypt them, please provide a callback for InputOptions.formatOptions.isobmff.resolveKeyId.`);let t=(async()=>{let t=e.demuxer.psshBoxes;if(r){t=[...t,...r.psshBoxes].filter(e=>e.keyIds===null||e.keyIds.includes(a));for(let e=0;e<t.length-1;e++)for(let n=e+1;n<t.length;n++)fg(t[e],t[n])&&(t.splice(n,1),n--)}let n=await e.demuxer.input._formatOptions.isobmff.resolveKeyId({keyId:a,psshBoxes:t});if(!(typeof n==`string`&&n.length===32&&wp.test(n)||n instanceof Uint8Array&&n.byteLength===16))throw TypeError(`resolveKeyId must return a 32-character hex string or a 16-byte Uint8Array containing the decryption key.`);return n instanceof Uint8Array?n:Ep(n)})();e.demuxer.decryptionKeyCache.set(a,t),o=await t}return i.scheme===`cenc`||i.scheme===`cens`?Wg(o,i,t,n):Gg(o,i,t,n)},Wg=async(e,t,n,r)=>{let i=/* @__PURE__ */ new Uint8Array(16);i.set(n.iv,0);let a=await crypto.subtle.importKey(`raw`,e,{name:`AES-CTR`},!1,[`decrypt`]),o=async e=>{let t=await crypto.subtle.decrypt({name:`AES-CTR`,counter:i,length:64},a,e);return new Uint8Array(t)};if(!n.subsamples)return o(r);z(t.defaultCryptByteBlock!==null&&t.defaultSkipByteBlock!==null);let s=Kg(n.subsamples,t.defaultCryptByteBlock,t.defaultSkipByteBlock),c=0;for(let e of s)for(let t of e.perSubsample)c+=t.length;let l=new Uint8Array(c),u=0;for(let e of s)for(let t of e.perSubsample)l.set(r.subarray(t.offset,t.offset+t.length),u),u+=t.length;let d=await o(l),f=new Uint8Array(r),p=0;for(let e of s)for(let t of e.perSubsample)f.set(d.subarray(p,p+t.length),t.offset),p+=t.length;return f},Gg=(e,t,n,r)=>{let i=new Og;i.init({key:e,iv:n.iv});let a=t.defaultCryptByteBlock,o=t.defaultSkipByteBlock;if(z(a!==null&&o!==null),!n.subsamples){let e=new Uint8Array(r),t=Math.floor(r.length/16);for(let n=0;n<t;n++){let t=n*16;i.in.set(r.subarray(t,t+16)),i.decrypt(),e.set(i.out,t)}return e}if(a===0&&o===0)throw Error(`cbcs with subsamples requires pattern encryption.`);let s=new Uint8Array(r),c=Kg(n.subsamples,a,o),l=new DataView(n.iv.buffer,n.iv.byteOffset,16);for(let e of c){i.iv[0]=l.getUint32(0,!1),i.iv[1]=l.getUint32(4,!1),i.iv[2]=l.getUint32(8,!1),i.iv[3]=l.getUint32(12,!1);for(let t of e.perSubsample){let e=t.length/16;for(let n=0;n<e;n++){let e=t.offset+n*16;i.in.set(r.subarray(e,e+16)),i.decrypt(),s.set(i.out,e)}}}return s},Kg=(e,t,n)=>{let r=[],i=t!==0||n!==0,a=0;for(let o of e){a+=o.clearLen;let e=[];if(!i)o.protectedLen>0&&e.push({offset:a,length:o.protectedLen}),a+=o.protectedLen;else{let r=o.protectedLen,i=a;for(;r>0&&!(r<16*t);){let a=16*t;e.push({offset:i,length:a}),i+=a,r-=a;let o=Math.min(16*n,r);i+=o,r-=o}a+=o.protectedLen}r.push({perSubsample:e})}return r},qg=e=>{let t=e.filePos,n=new fm(N_(e,9));if(n.readBits(12)!==4095||(n.skipBits(1),n.readBits(2)!==0))return null;let r=n.readBits(1),i=n.readBits(2)+1,a=n.readBits(4);if(a===15)return null;n.skipBits(1);let o=n.readBits(3);if(o===0)throw Error(`ADTS frames with channel configuration 0 are not supported.`);n.skipBits(1),n.skipBits(1),n.skipBits(1),n.skipBits(1);let s=n.readBits(13);n.skipBits(11);let c=n.readBits(2)+1;if(c!==1)throw Error(`ADTS frames with more than one AAC frame are not supported.`);let l=null;return r===1?e.filePos-=2:l=n.readBits(16),{objectType:i,samplingFrequencyIndex:a,channelConfiguration:o,frameLength:s,numberOfAacFrames:c,crcCheck:l,startPos:t}};(/* @__PURE__ */ e(((e,t)=>{t.exports={}})))(),Zp();var Jg=1/0;typeof FinalizationRegistry<`u`&&new FinalizationRegistry(e=>{e()});var Yg=class extends rm{constructor(){super(),this._disposed=!1,this._refCount=0,this._usedForHls=!1,this._refFinalizationRegistry=null,this._sizePromise=null,this.onread=null,typeof FinalizationRegistry<`u`&&(this._refFinalizationRegistry=new FinalizationRegistry(e=>{e._decrementRefCount()}))}async getSizeOrNull(){if(this._disposed)throw new k_;return this._sizePromise??=(async()=>{let e=this._getFileSize();return e===void 0?(await this._read(0,1,0,Jg),e=this._getFileSize(),z(e!==void 0),e):e})()}async getSize(){if(this._disposed)throw new k_;let e=await this.getSizeOrNull();if(e===null)throw Error(`Cannot determine the size of an unsized source.`);return e}slice(e,t){if(!Number.isInteger(e)||e<0)throw TypeError(`offset must be a non-negative integer.`);if(t!==void 0&&(!Number.isInteger(t)||t<0))throw TypeError(`length, when provided, must be a non-negative integer.`);return new e_(this,e,t)}_dispatchRead(e,t){this.onread?.(e,t),this._emit(`read`,{start:e,end:t})}ref(){return new Xg(this)}_incrementRefCount(){this._refCount++}_decrementRefCount(){this._refCount--,this._refCount===0&&(this._dispose(),this._disposed=!0)}},Xg=class{constructor(e){if(this._freed=!1,e._disposed)throw Error(`Cannot ref a disposed source.`);e._incrementRefCount(),e._refFinalizationRegistry?.register(this,e,this),this._source=e}get source(){if(!this._source)throw Error(`Can't get source; ref has already been freed.`);return this._source}get freed(){return this._freed}free(){if(this._freed)throw Error(`Illegal operation: double free on SourceRef.`);let e=this.source;z(e._refCount>0),e._decrementRefCount(),e._refFinalizationRegistry?.unregister(this),this._freed=!0,this._source=null}[Symbol.dispose](){this.freed||this.free()}},Zg=class extends Yg{constructor(e,t){if(typeof e!=`string`)throw TypeError(`rootPath must be a string.`);if(typeof t!=`function`)throw TypeError(`requestHandler must be a function.`);super(),this.rootPath=e,this.requestHandler=t}_resolveRequest(e){let t=this.requestHandler(e),n=e=>{if(!(e instanceof Yg||e instanceof Xg))throw TypeError(`requestHandler must return or resolve to a Source or SourceRef.`);let t=e instanceof Yg?e.ref():e;return t.source._usedForHls||=this._usedForHls,t};return Jp(t)?t.then(n):n(t)}},Qg=(e,t)=>e.path===t.path,$g=class extends Yg{constructor(e){if(!(e instanceof ArrayBuffer)&&!(typeof SharedArrayBuffer<`u`&&e instanceof SharedArrayBuffer)&&!ArrayBuffer.isView(e))throw TypeError(`buffer must be an ArrayBuffer, SharedArrayBuffer, or ArrayBufferView.`);super(),this._onreadCalled=!1,this._bytes=op(e),this._view=sp(e)}_getFileSize(){return this._bytes.byteLength}_read(){return this._onreadCalled||=(this._dispatchRead(0,this._bytes.byteLength),!0),{bytes:this._bytes,view:this._view,offset:0}}_dispose(){}};typeof FinalizationRegistry<`u`&&new FinalizationRegistry(e=>{e.cancel().catch(()=>{})});var e_=class extends Yg{constructor(e,t,n){if(super(),this._ref=null,e._disposed)throw Error(`Cannot create a slice of a disposed source.`);this._baseSource=e,this._offset=t,this._length=n??null}_getFileSize(){let e=this._baseSource._getFileSize();return e===void 0?this._length===null?void 0:this._length:e===null?this._length===null?null:this._length:Ip(e-this._offset,0,this._length??1/0)}_read(e,t,n,r){if(this._length!==null&&t>this._length)return null;let i=this._baseSource._read(this._offset+e,this._offset+t,this._offset+n,this._offset+r),a=e=>e?(e.offset-=this._offset,e):null;return Jp(i)?i.then(a):a(i)}_dispose(){this._ref?.free()}ref(){return this._ref??=this._baseSource.ref(),super.ref()}},t_=class{constructor(){this._isIsobmff=!1}},n_=class extends t_{constructor(){super(...arguments),this._isIsobmff=!0}async _getMajorBrand(e){let t=e._reader.requestSlice(0,12);if(Jp(t)&&(t=await t),!t)return null;t.skip(4);let n=V_(t,4);return n!==`ftyp`&&n!==`styp`?null:V_(t,4)}_createDemuxer(e){return new kg(e)}},r_=class extends n_{async _canReadInput(e){let t=await this._getMajorBrand(e);if(t!==null)return t!==`qt `;let n=0;for(let t=0;t<10;t++){let t=e._reader.requestSlice(n,8);if(Jp(t)&&(t=await t),!t)return!1;let r=H(t),i=8;if(r===1){let t=e._reader.requestSlice(n+8,8);if(Jp(t)&&(t=await t),!t)return!1;r=R_(t),i=16}if(r<i)return!1;let a=V_(t,4);if(a===`moof`||a===`sidx`)return!0;if(a===`emsg`||a===`prft`||a===`free`)n+=r;else return!1}return!1}get name(){return`MP4`}get mimeType(){return`video/mp4`}},i_=class extends n_{async _canReadInput(e){return await this._getMajorBrand(e)===`qt `}get name(){return`QuickTime File Format`}get mimeType(){return`video/quicktime`}},a_=/* #__PURE__ */ new r_,o_=/* #__PURE__ */ new i_,s_=(e,t)=>{if(!e||typeof e!=`object`)throw TypeError(`${t}, when provided, must be an object.`);if(e.isobmff!==void 0){if(!e.isobmff||typeof e.isobmff!=`object`)throw TypeError(`${t}.isobmff, when provided, must be an object.`);if(e.isobmff.resolveKeyId!==void 0&&typeof e.isobmff.resolveKeyId!=`function`)throw TypeError(`${t}.isobmff.resolveKeyId, when provided, must be a function.`)}if(e.hls!==void 0){if(!e.hls||typeof e.hls!=`object`)throw TypeError(`${t}.hls, when provided, must be an object.`);if(e.hls.offsetTimestampsByDateTime!==void 0&&typeof e.hls.offsetTimestampsByDateTime!=`boolean`)throw TypeError(`${t}.hls.offsetTimestampsByDateTime, when provided, must be a boolean.`)}},c_=[],l_=[],u_=e=>{if(!e||typeof e!=`object`)throw TypeError(`options must be an object.`);if(e.metadataOnly!==void 0&&typeof e.metadataOnly!=`boolean`)throw TypeError(`options.metadataOnly, when defined, must be a boolean.`);if(e.verifyKeyPackets!==void 0&&typeof e.verifyKeyPackets!=`boolean`)throw TypeError(`options.verifyKeyPackets, when defined, must be a boolean.`);if(e.verifyKeyPackets&&e.metadataOnly)throw TypeError(`options.verifyKeyPackets and options.metadataOnly cannot be enabled together.`);if(e.skipLiveWait!==void 0&&typeof e.skipLiveWait!=`boolean`)throw TypeError(`options.skipLiveWait, when defined, must be a boolean.`)},d_=e=>{if(!Qp(e))throw TypeError(`timestamp must be a number.`)},f_=(e,t,n)=>n.verifyKeyPackets?t.then(async t=>{if(!t||t.type===`delta`)return t;let n=await e.determinePacketType(t);return n&&(t.type=n),t}):t,p_=class{constructor(e){if(!(e instanceof m_))throw TypeError(`track must be an InputTrack.`);this._track=e}async getFirstPacket(e={}){if(u_(e),this._track.input._disposed)throw new k_;return f_(this._track,this._track._backing.getFirstPacket(e),e)}async getFirstKeyPacket(e={}){u_(e);let t=await this.getFirstPacket(e);return t?t.type===`key`?t:this.getNextKeyPacket(t,e):null}async getPacket(e,t={}){if(d_(e),u_(t),this._track.input._disposed)throw new k_;return f_(this._track,this._track._backing.getPacket(e,t),t)}async getNextPacket(e,t={}){if(!(e instanceof lg))throw TypeError(`packet must be an EncodedPacket.`);if(u_(t),this._track.input._disposed)throw new k_;return f_(this._track,this._track._backing.getNextPacket(e,t),t)}async getKeyPacket(e,t={}){if(d_(e),u_(t),this._track.input._disposed)throw new k_;if(!t.verifyKeyPackets)return this._track._backing.getKeyPacket(e,t);let n=await this._track._backing.getKeyPacket(e,t);return n&&(z(n.type===`key`),await this._track.determinePacketType(n)===`delta`?this.getKeyPacket(n.timestamp-1/await this._track.getTimeResolution(),t):n)}async getNextKeyPacket(e,t={}){if(!(e instanceof lg))throw TypeError(`packet must be an EncodedPacket.`);if(u_(t),this._track.input._disposed)throw new k_;if(!t.verifyKeyPackets)return this._track._backing.getNextKeyPacket(e,t);let n=await this._track._backing.getNextKeyPacket(e,t);return n&&(z(n.type===`key`),await this._track.determinePacketType(n)===`delta`?this.getNextKeyPacket(n,t):n)}packets(e,t,n={}){if(e!==void 0&&!(e instanceof lg))throw TypeError(`startPacket must be an EncodedPacket.`);if(e!==void 0&&e.isMetadataOnly&&!n?.metadataOnly)throw TypeError(`startPacket can only be metadata-only if options.metadataOnly is enabled.`);if(t!==void 0&&!(t instanceof lg))throw TypeError(`endPacket must be an EncodedPacket.`);if(u_(n),this._track.input._disposed)throw new k_;let r=[],{promise:i,resolve:a}=Ap(),{promise:o,resolve:s}=Ap(),c=!1,l=!1,u=null,d=!1,f=[],p=()=>Math.max(2,f.length);(async()=>{let u=e??await this.getFirstPacket(n);for(;u&&!l&&!this._track.input._disposed&&!(t&&u.sequenceNumber>=t?.sequenceNumber);){if(r.length>p()){({promise:o,resolve:s}=Ap()),await o;continue}r.push(u),a(),{promise:i,resolve:a}=Ap(),u=await this.getNextPacket(u,n)}c=!0,a()})().catch(e=>{d||(u=e,d=!0,a())});let m=this._track;return{async next(){for(;;)if(m.input._disposed)throw new k_;else if(l)return{value:void 0,done:!0};else if(d)throw u;else if(r.length>0){let e=r.shift(),t=performance.now();for(f.push(t);f.length>0&&t-f[0]>=1e3;)f.shift();return s(),{value:e,done:!1}}else if(c)return{value:void 0,done:!0};else await i},async return(){return l=!0,s(),a(),{value:void 0,done:!0}},async throw(e){throw e},[Symbol.asyncIterator](){return this}}}},m_=class e{constructor(e,t){this.input=e,this._backing=t}isVideoTrack(){return this instanceof __}isAudioTrack(){return this instanceof v_}get id(){return this._backing.getId()}get number(){return this._backing.getNumber()}async getInternalCodecId(){return this._backing.getInternalCodecId()}get internalCodecId(){return h_(this._backing.getInternalCodecId(),`internalCodecId`,`getInternalCodecId`)}async getLanguageCode(){return this._backing.getLanguageCode()}get languageCode(){return h_(this._backing.getLanguageCode(),`languageCode`,`getLanguageCode`)}async getName(){return this._backing.getName()}get name(){return h_(this._backing.getName(),`name`,`getName`)}async getTimeResolution(){return this._backing.getTimeResolution()}get timeResolution(){return h_(this._backing.getTimeResolution(),`timeResolution`,`getTimeResolution`)}async isRelativeToUnixEpoch(){return this._backing.isRelativeToUnixEpoch()}async getUnixTimeForTimestamp(e){return this._backing.getUnixTimeForTimestamp(e)}async hasUnixTimeMapping(){return await this._backing.getUnixTimeForTimestamp(await this.getFirstTimestamp())!==null}async getDisposition(){return this._backing.getDisposition()}get disposition(){return h_(this._backing.getDisposition(),`disposition`,`getDisposition`)}async getBitrate(){return this._backing.getBitrate()}async getAverageBitrate(){return this._backing.getAverageBitrate()}async getFirstTimestamp(){return(await this._backing.getFirstPacket({metadataOnly:!0}))?.timestamp??0}async computeDuration(e){let t=await this._backing.getPacket(1/0,{metadataOnly:!0,...e});return zp((t?.timestamp??0)+(t?.duration??0),await this.getTimeResolution())}async getDurationFromMetadata(e={}){return this._backing.getDurationFromMetadata(e)}async computePacketStats(e=1/0,t){let n=new p_(this),r=1/0,i=-1/0,a=0,o=0;for await(let s of n.packets(void 0,void 0,{metadataOnly:!0,...t})){if(a>=e&&s.timestamp>=i)break;r=Math.min(r,s.timestamp),i=Math.max(i,s.timestamp+s.duration),a++,o+=s.byteLength}return{packetCount:a,averagePacketRate:a?Number((a/(i-r)).toPrecision(16)):0,averageBitrate:a?Number((8*o/(i-r)).toPrecision(16)):0}}async isLive(){return await this._backing.getLiveRefreshInterval()!==null}async getLiveRefreshInterval(){return this._backing.getLiveRefreshInterval()}canBePairedWith(t){if(!(t instanceof e))throw TypeError(`other must be an InputTrack.`);return this.input!==t.input||this===t?!1:(this._backing.getPairingMask()&t._backing.getPairingMask())!==0n}async getPairableTracks(e){return this.input.getTracks(S_({filter:e=>e.canBePairedWith(this)},e))}async getPairableVideoTracks(e){return this.input.getVideoTracks(S_({filter:e=>e.canBePairedWith(this)},e))}async getPairableAudioTracks(e){return this.input.getAudioTracks(S_({filter:e=>e.canBePairedWith(this)},e))}async getPrimaryPairableVideoTrack(e){return this.input.getPrimaryVideoTrack(S_({filter:e=>e.canBePairedWith(this)},e))}async getPrimaryPairableAudioTrack(e){return this.input.getPrimaryAudioTrack(S_({filter:e=>e.canBePairedWith(this)},e))}async hasPairableTrack(e){e&&=g_(e);let t=await this.input.getTracks();for(let n of t)if(this.canBePairedWith(n)&&(!e||await e(n)))return!0;return!1}hasPairableVideoTrack(e){return e&&=g_(e),this.hasPairableTrack(async t=>t.isVideoTrack()&&(!e||await e(t)))}hasPairableAudioTrack(e){return e&&=g_(e),this.hasPairableTrack(async t=>t.isAudioTrack()&&(!e||await e(t)))}},h_=(e,t,n)=>{if(Jp(e))throw Error(`'${t}' is deprecated and not available synchronously for this track. Use the preferred '${n}()' instead.`);return e},g_=e=>{if(e!==void 0&&typeof e!=`function`)throw TypeError(`predicate, when provided, must be a function.`);return e?t=>{let n=e=>{if(typeof e!=`boolean`)throw TypeError(`predicate must return or resolve to a boolean value.`);return e},r=e(t);return Jp(r)?r.then(n):n(r)}:void 0},__=class extends m_{constructor(e,t){super(e,t),this._pixelAspectRatioCache=null,this._backing=t}get type(){return`video`}async getCodec(){return this._backing.getCodec()}get codec(){return h_(this._backing.getCodec(),`codec`,`getCodec`)}async hasOnlyKeyPackets(){return await this._backing.getHasOnlyKeyPackets?.()??await this._backing.getCodec()===`prores`}async getCodedWidth(){return this._backing.getCodedWidth()}get codedWidth(){return h_(this._backing.getCodedWidth(),`codedWidth`,`getCodedWidth`)}async getCodedHeight(){return this._backing.getCodedHeight()}get codedHeight(){return h_(this._backing.getCodedHeight(),`codedHeight`,`getCodedHeight`)}async getTransformationMatrix(){return this._backing.getTransformationMatrix()}async getRotation(){return Xf(await this._backing.getTransformationMatrix())}get rotation(){return Xf(h_(this._backing.getTransformationMatrix(),`rotation`,`getRotation`))}async getFlip(){return Zf(await this._backing.getTransformationMatrix())}async getSquarePixelWidth(){return this._backing.getSquarePixelWidth()}get squarePixelWidth(){return h_(this._backing.getSquarePixelWidth(),`squarePixelWidth`,`getSquarePixelWidth`)}async getSquarePixelHeight(){return this._backing.getSquarePixelHeight()}get squarePixelHeight(){return h_(this._backing.getSquarePixelHeight(),`squarePixelHeight`,`getSquarePixelHeight`)}async getPixelAspectRatio(){return this._pixelAspectRatioCache??=tm({num:await this.getSquarePixelWidth()*await this.getCodedHeight(),den:await this.getSquarePixelHeight()*await this.getCodedWidth()})}get pixelAspectRatio(){return this._pixelAspectRatioCache??=tm({num:h_(this._backing.getSquarePixelWidth(),`pixelAspectRatio`,`getPixelAspectRatio`)*h_(this._backing.getCodedHeight(),`pixelAspectRatio`,`getPixelAspectRatio`),den:h_(this._backing.getSquarePixelHeight(),`pixelAspectRatio`,`getPixelAspectRatio`)*h_(this._backing.getCodedWidth(),`pixelAspectRatio`,`getPixelAspectRatio`)})}async getDisplayWidth(){return await this._backing.getMetadataDisplayWidth?.()??(await this.getRotation()%180==0?this.getSquarePixelWidth():this.getSquarePixelHeight())}get displayWidth(){let e=this._backing.getMetadataDisplayWidth?.();if(e!==void 0){let t=h_(e,`displayWidth`,`getDisplayWidth`);if(t!==null)return t}return h_(Xf(h_(this._backing.getTransformationMatrix(),`displayWidth`,`getDisplayWidth`))%180==0?this._backing.getSquarePixelWidth():this._backing.getSquarePixelHeight(),`displayWidth`,`getDisplayWidth`)}async getDisplayHeight(){return await this._backing.getMetadataDisplayHeight?.()??(await this.getRotation()%180==0?this.getSquarePixelHeight():this.getSquarePixelWidth())}get displayHeight(){let e=this._backing.getMetadataDisplayHeight?.();if(e!==void 0){let t=h_(e,`displayHeight`,`getDisplayHeight`);if(t!==null)return t}return h_(Xf(h_(this._backing.getTransformationMatrix(),`displayHeight`,`getDisplayHeight`))%180==0?this._backing.getSquarePixelHeight():this._backing.getSquarePixelWidth(),`displayHeight`,`getDisplayHeight`)}async getColorSpace(){return this._backing.getColorSpace()}async hasHighDynamicRange(){let e=await this._backing.getColorSpace();return e.primaries===`bt2020`||e.primaries===`smpte432`||e.transfer===`pq`||e.transfer===`hlg`||e.matrix===`bt2020-ncl`}async canBeTransparent(){return this._backing.canBeTransparent()}async getDecoderConfig(){return this._backing.getDecoderConfig()}async getCodecParameterString(){return await this._backing.getMetadataCodecParameterString?.()??(await this._backing.getDecoderConfig())?.codec??null}async canDecode(){try{let e=await this._backing.getDecoderConfig();if(!e)return!1;let t=await this._backing.getCodec();return z(t!==null),c_.some(n=>n.supports(t,e))?!0:typeof VideoDecoder>`u`?!1:(await VideoDecoder.isConfigSupported(e)).supported===!0}catch(e){return om._error(`Error during decodability check:`,e),!1}}async determinePacketType(e){if(!(e instanceof lg))throw TypeError(`packet must be an EncodedPacket.`);if(e.isMetadataOnly)throw TypeError(`packet must not be metadata-only to determine its type.`);let t=await this.getCodec();if(t===null)return null;let n=await this.getDecoderConfig();return z(n),oh(t,n,e.data)}async computeFrameRateMetrics(e={}){if(!e||typeof e!=`object`)throw TypeError(`options must be an object.`);if(e.targetPacketCount!==void 0&&(!Qp(e.targetPacketCount)||e.targetPacketCount<0))throw TypeError(`options.targetPacketCount must be a non-negative number.`);let t=await this.getTimeResolution(),n=e.targetPacketCount??256,r=new p_(this),i=[],a=-1/0,o=0;for await(let e of r.packets(void 0,void 0,{metadataOnly:!0})){if(i.length>=n&&e.timestamp>=a)break;i.push(e.timestamp),a=Math.max(a,e.timestamp),o++}let s=new Float64Array(i.length);for(let e=0;e<i.length;e++)s[e]=Math.round(i[e]*t);s.sort();let c=1;for(let e=1;e<s.length;e++)s[e]!==s[c-1]&&(s[c++]=s[e]);if(c<2)return{underlyingFrameRate:null,bestGuessFrameRate:t,minFrameRate:t,maxFrameRate:t,averageFrameRate:t,medianFrameRate:t,frameRateIsConstant:!0,probedPacketCount:o};let l=s.subarray(0,c),u=w_(l,t),d=u??t,f=u===null?null:t/u,p=/* @__PURE__ */ new Map,m=1/0,h=-1/0,g=0;for(let e=1;e<c;e++){let t=l[e]-l[e-1],n=f===null?t:Math.max(1,Math.round(t/f));p.set(n,(p.get(n)??0)+1),m=Math.min(m,n),h=Math.max(h,n),g+=n}let _=c-1,v=[...p.keys()].sort((e,t)=>e-t),y=_-1>>1,b=_>>1,x=0,S=0,C=0;for(let e of v)if(C+=p.get(e),x===0&&C>y&&(x=e),C>b){S=e;break}let w=(d/x+d/S)/2;return{underlyingFrameRate:u,bestGuessFrameRate:u===null?E_(w):u,minFrameRate:d/h,maxFrameRate:d/m,averageFrameRate:d*_/g,medianFrameRate:w,frameRateIsConstant:u!==null&&m===1&&h===1,probedPacketCount:o}}},v_=class extends m_{constructor(e,t){super(e,t),this._backing=t}get type(){return`audio`}async getCodec(){return this._backing.getCodec()}get codec(){return h_(this._backing.getCodec(),`codec`,`getCodec`)}async hasOnlyKeyPackets(){return await this._backing.getHasOnlyKeyPackets?.()??!0}async getNumberOfChannels(){return this._backing.getNumberOfChannels()}get numberOfChannels(){return h_(this._backing.getNumberOfChannels(),`numberOfChannels`,`getNumberOfChannels`)}async getSampleRate(){return this._backing.getSampleRate()}get sampleRate(){return h_(this._backing.getSampleRate(),`sampleRate`,`getSampleRate`)}async getDecoderConfig(){return this._backing.getDecoderConfig()}async getCodecParameterString(){return await this._backing.getMetadataCodecParameterString?.()??(await this._backing.getDecoderConfig())?.codec??null}async canDecode(){try{let e=await this._backing.getDecoderConfig();if(!e)return!1;let t=await this._backing.getCodec();return z(t!==null),l_.some(n=>n.supports(t,e))||e.codec.startsWith(`pcm-`)?!0:typeof AudioDecoder>`u`?!1:(await AudioDecoder.isConfigSupported(e)).supported===!0}catch(e){return om._error(`Error during decodability check:`,e),!1}}async determinePacketType(e){if(!(e instanceof lg))throw TypeError(`packet must be an EncodedPacket.`);return await this.getCodec()===null?null:`key`}},y_=e=>-(e??-1/0),b_=e=>-e,x_=e=>{if(typeof e!=`object`||!e)throw TypeError(`query must be an object.`);if(e.filter!==void 0&&typeof e.filter!=`function`)throw TypeError(`query.filter, when provided, must be a function.`);if(e.sortBy!==void 0&&typeof e.sortBy!=`function`)throw TypeError(`query.sortBy, when provided, must be a function.`);return{filter:e.filter?t=>{let n=e=>{if(typeof e!=`boolean`)throw TypeError(`query.filter must return or resolve to a boolean.`);return e},r=e.filter(t);return Jp(r)?r.then(n):n(r)}:void 0,sortBy:e.sortBy?t=>{let n=e=>{if(typeof e!=`number`&&(!Array.isArray(e)||!e.every(e=>typeof e==`number`)))throw TypeError(`query.sortBy must return or resolve to a number or an array of numbers.`);return e},r=e.sortBy(t);return Jp(r)?r.then(n):n(r)}:void 0}},S_=(e,t)=>({filter:e?.filter||t?.filter?n=>{let r=e?.filter?.(n)??!0,i=e=>e===!1?!1:t?.filter?.(n)??!0;return Jp(r)?r.then(i):i(r)}:void 0,sortBy:e?.sortBy||t?.sortBy?n=>{let r=e?.sortBy?.(n)??[],i=t?.sortBy?.(n)??[],a=(e,t)=>[...Array.isArray(e)?e:[e],...Array.isArray(t)?t:[t]];return Jp(r)||Jp(i)?Promise.all([r,i]).then(([e,t])=>a(e,t)):a(r,i)}:void 0}),C_=async(e,t)=>{let n=e;if(t?.filter){let r=e.map(e=>t.filter(e));if(r.some(e=>Jp(e))){let t=await Promise.all(r);n=e.filter((e,n)=>t[n])}else n=e.filter((e,t)=>r[t])}if(!t?.sortBy)return n;let r=n.map(e=>t.sortBy(e)),i=r.some(e=>Jp(e))?await Promise.all(r):r;return n.map((e,t)=>({track:e,sortValue:i[t]})).sort((e,t)=>{let n=Array.isArray(e.sortValue)?e.sortValue:[e.sortValue],r=Array.isArray(t.sortValue)?t.sortValue:[t.sortValue],i=Math.max(n.length,r.length);for(let e=0;e<i;e++){let t=n[e]??0,i=r[e]??0;if(t!==i)return t-i}return 0}).map(e=>e.track)},w_=(e,t)=>{let n=1e6,r=.98,i=1+1e-9,a=[12,15,20,24e3/1001,24,25,3e4/1001,30,48,50,6e4/1001,60,100,12e4/1001,120,144,240];if(e.length<2)return null;let o=new Float64Array(e.length-1);for(let t=1;t<e.length;t++){let n=e[t]-e[t-1];if(!(n>0))return null;o[t-1]=n}let s=o.slice();s.sort();let c=s[Math.floor(s.length*.05)];for(let e=0;e<6;e++){let e=0,t=0;for(let n of o){let r=Math.max(1,Math.round(n/c));Math.abs(n-r*c)>=i||(e+=n,t+=r)}if(t===0)return null;let n=e/t;if(Math.abs(n-c)<=1e-12*Math.max(1,c)){c=n;break}c=n}let l=0,u=0,d=0;for(let e of o){let t=Math.max(1,Math.round(e/c));Math.abs(e-t*c)>=i||(l++,u+=e,d+=t)}if(l/o.length<r)return null;c=u/d;let f=1/Math.min(d,1e3),p=Math.max(2**-52,c-f),m=c+f,h=t/m,g=t/p,_=t/c,v=null,y=1/0;for(let e of a){if(e<h||e>g)continue;let t=Math.abs(e/_-1);t<y&&(v=e,y=t)}if(v===null){let e=T_(p,m,n),r=T_(h,g,n);if(r&&(!e||r.den<e.den||r.den===e.den&&r.num<=e.num))v=r.num/r.den;else if(e)v=t*e.den/e.num;else return null}let b=t/v,x=0;for(let e of o){let t=Math.max(1,Math.round(e/b));Math.abs(e-t*b)<i&&x++}return x/o.length<r?null:v},T_=(e,t,n)=>{for(let r=1;r<=n;r++){let n=Math.floor(e*r)+1;if(n/r<t)return tm({num:n,den:r})}return null},E_=e=>{let t=[24/1.001,30/1.001,60/1.001,120/1.001],n=[12,15,20,24,25,30,48,50,60,100,120,144,240];for(let n of t)if(Math.abs(n/e-1)<=5e-4)return n;let r=e,i=1/0;for(let t of n){let n=Math.abs(t/e-1);n<=.025&&n<i&&(r=t,i=n)}return r};Zp();var D_=class e extends rm{get disposed(){return this._disposed}constructor(t){if(super(),this._demuxerPromise=null,this._format=null,this._trackBackingsCache=null,this._backingToTrack=/* @__PURE__ */ new Map,this._disposed=!1,this._nextSourceCacheAge=0,this._sourceRefs=[],this._sourceCache=[],this._sourceCachePromises=[],this._onFormatDetermined=null,!t||typeof t!=`object`)throw TypeError(`options must be an object.`);if(!Array.isArray(t.formats)||t.formats.some(e=>!(e instanceof t_)))throw TypeError(`options.formats must be an array of InputFormat.`);if(!(t.source instanceof Yg||t.source instanceof Xg))throw TypeError(`options.source must be a Source or SourceRef.`);if(t.source instanceof Yg&&t.source._disposed)throw TypeError(`options.source must not be a disposed Source.`);if(t.initInput!==void 0&&!(t.initInput instanceof e))throw TypeError(`options.initInput, when provided, must be an Input.`);t.formatOptions!==void 0&&s_(t.formatOptions,`formatOptions`),this._formats=t.formats,this._initInput=t.initInput??null,this._formatOptions=t.formatOptions??{},this._rootRef=t.source instanceof Yg?t.source.ref():t.source,this._sourceRefs.push(this._rootRef)}get _rootSource(){return this._rootRef.source}async _getSourceUncached(e){z(this._rootSource instanceof Zg);let t=await this._rootSource._resolveRequest(e);return this._emit(`source`,{source:t.source,request:e,isRoot:e.isRoot}),t}_getSourceCached(e,t=1){let n=this._sourceCache.find(n=>n.cacheGroup===t&&Qg(n.request,e));if(n)return n.age++,Promise.resolve(n.sourceRef.source.ref());let r=this._sourceCachePromises.find(n=>n.cacheGroup===t&&Qg(n.request,e));if(r)return r.promise.then(e=>e.sourceRef.source.ref());let i=(async()=>{let n=await this._getSourceUncached(e);if($p(this._sourceCache,e=>e.cacheGroup===t&&e.sourceRef.source._refCount===1)>=4){let e=em(this._sourceCache,e=>e.cacheGroup===t&&e.sourceRef.source._refCount===1?e.age:1/0);z(e!==-1);let n=this._sourceCache[e];this._sourceCache.splice(e,1),n.sourceRef.free(),jp(this._sourceRefs,n.sourceRef)}this._sourceRefs.push(n);let r=this._sourceCachePromises.findIndex(t=>t.request===e);return z(r!==-1),this._sourceCachePromises.splice(r,1),{request:e,sourceRef:n,age:this._nextSourceCacheAge++,cacheGroup:t}})();return this._sourceCachePromises.push({request:e,cacheGroup:t,promise:i}),i.then(e=>{let t=e.sourceRef.source.ref();return this._sourceCache.push(e),t})}_getDemuxer(){return this._demuxerPromise??=(async()=>{this._reader=new A_(this._rootSource),this._emit(`source`,{source:this._rootSource,request:null,isRoot:!0});for(let e of this._formats)if(await e._canReadInput(this))return this._format=e,this._onFormatDetermined?.(e),e._createDemuxer(this);throw new O_})()}get source(){return this._rootSource}async getFormat(){return await this._getDemuxer(),z(this._format),this._format}async canRead(){try{return await this._getDemuxer(),!0}catch(e){if(e instanceof O_)return!1;throw e}}async getFirstTimestamp(e){e??=await this.getTracks();let t=e.filter(e=>e!==null);if(t.length===0)return 0;let n=await Promise.all(t.map(e=>e._backing.getFirstPacket({metadataOnly:!0}))),r=Math.min(...n.map(e=>e?.timestamp??1/0));return r===1/0?0:r}async computeDuration(e,t){e??=await this.getTracks();let n=e.filter(e=>e!==null);if(n.length===0)return 0;let r=await Promise.all(n.map(e=>e.computeDuration(t)));return Math.max(...r)}async getDurationFromMetadata(e,t){e??=await this.getTracks();let n=e.filter(e=>e!==null),r=(await Promise.all(n.map(e=>e.getDurationFromMetadata(t)))).filter(e=>e!==null);return r.length===0?null:Math.max(...r)}async getTracks(e){return e&&=x_(e),C_((await this._getTrackBackings()).map(e=>this._wrapBackingAsTrack(e)),e)}async getVideoTracks(e){return e&&=x_(e),C_((await this.getTracks()).filter(e=>e.isVideoTrack()),e)}async getAudioTracks(e){return e&&=x_(e),C_((await this.getTracks()).filter(e=>e.isAudioTrack()),e)}async getPrimaryVideoTrack(e){e&&=x_(e);let t=S_(e,{sortBy:async e=>[b_((await e.getDisposition()).default),b_(await e.hasPairableAudioTrack()),b_(!await e.hasOnlyKeyPackets()),y_(await e.getBitrate())]});return(await this.getVideoTracks(t))[0]??null}async getPrimaryAudioTrack(e){e&&=x_(e);let t=await this.getPrimaryVideoTrack(),n=S_(e,{sortBy:async e=>[b_(!t||e.canBePairedWith(t)),b_((await e.getDisposition()).default),y_(await e.getBitrate())]});return(await this.getAudioTracks(n))[0]??null}async _getTrackBackings(){let e=await this._getDemuxer();return this._trackBackingsCache??=await e.getTrackBackings()}_wrapBackingAsTrack(e){let t=this._backingToTrack.get(e);if(t)return t;let n=e.getType()===`video`?new __(this,e):new v_(this,e);return this._backingToTrack.set(e,n),n}async getMimeType(){return(await this._getDemuxer()).getMimeType()}async getMetadataTags(){return(await this._getDemuxer()).getMetadataTags()}dispose(){if(!this._disposed){this._disposed=!0;for(let e of this._sourceRefs)e.free();this._sourceRefs.length=0,this._demuxerPromise&&this._demuxerPromise.then(e=>e.dispose()).catch(()=>{})}}[Symbol.dispose](){this.dispose()}},O_=class extends Error{constructor(e=`Input has an unsupported or unrecognizable format.`){super(e),this.name=`UnsupportedInputFormatError`}},k_=class extends Error{constructor(e=`Input has been disposed.`){super(e),this.name=`InputDisposedError`}},A_=class{constructor(e){this.source=e}get fileSize(){let e=this.source._getFileSize();if(e===void 0)throw Error(`Reading file size too early; read required first.`);return e}get fileSizeNonStrict(){return this.source._getFileSize()??null}requestSlice(e,t){if(this.source._disposed)throw new k_;if(e<0||this.fileSizeNonStrict!==null&&e+t>this.fileSizeNonStrict)return null;if(t===0){let t=/* @__PURE__ */ new Uint8Array;return new j_(t,sp(t),0,e,e)}let n=e+t,r=this.source._read(e,n,0,Jg);return Jp(r)?r.then(t=>t?new j_(t.bytes,t.view,t.offset,e,n):null):r?new j_(r.bytes,r.view,r.offset,e,n):null}requestSliceRange(e,t,n){if(this.source._disposed)throw new k_;if(e<0)return null;if(this.fileSizeNonStrict!==null)return this.requestSlice(e,Ip(this.fileSizeNonStrict-e,t,n));{let r=this.requestSlice(e,n),i=r=>r||(z(this.fileSizeNonStrict!==null),this.requestSlice(e,Ip(this.fileSizeNonStrict-e,t,n)));return Jp(r)?r.then(i):i(r)}}requestEntireFile(){return this.fileSizeNonStrict===null?(async()=>{let e=[],t=0;for(;;){if(e.length===1&&this.fileSizeNonStrict!==null)return this.requestSlice(0,this.fileSizeNonStrict);let n=this.requestSliceRange(t,0,1024);if(Jp(n)&&(n=await n),!n||n.length===0)break;let r=N_(n,n.length);e.push(r),t+=n.length}let n=new Uint8Array(t),r=0;for(let t of e)n.set(t,r),r+=t.length;return new j_(n,sp(n),0,0,t)})():this.requestSlice(0,this.fileSizeNonStrict)}},j_=class e{constructor(e,t,n,r,i){this.bytes=e,this.view=t,this.offset=n,this.start=r,this.end=i,this.bufferPos=r-n}static tempFromBytes(t){return new e(t,sp(t),0,0,t.length)}get length(){return this.end-this.start}get filePos(){return this.offset+this.bufferPos}set filePos(e){this.bufferPos=e-this.offset}get remainingLength(){return Math.max(this.end-this.filePos,0)}skip(e){this.bufferPos+=e}slice(t,n=this.end-t){if(t<this.start||t+n>this.end)throw RangeError(`Slicing outside of original slice.`);return new e(this.bytes,this.view,this.offset,t,t+n)}},M_=(e,t)=>{if(e.filePos<e.start||e.filePos+t>e.end)throw RangeError(`Tried reading [${e.filePos}, ${e.filePos+t}), but slice is [${e.start}, ${e.end}). This is likely an internal error, please report it alongside the file that caused it.`)},N_=(e,t)=>{M_(e,t);let n=e.bytes.subarray(e.bufferPos,e.bufferPos+t);return e.bufferPos+=t,n},V=e=>(M_(e,1),e.view.getUint8(e.bufferPos++)),P_=e=>{M_(e,2);let t=e.view.getUint16(e.bufferPos,!1);return e.bufferPos+=2,t},F_=e=>{M_(e,3);let t=Pp(e.view,e.bufferPos,!1);return e.bufferPos+=3,t},I_=e=>{M_(e,2);let t=e.view.getInt16(e.bufferPos,!1);return e.bufferPos+=2,t},H=e=>{M_(e,4);let t=e.view.getUint32(e.bufferPos,!1);return e.bufferPos+=4,t},L_=e=>{M_(e,4);let t=e.view.getInt32(e.bufferPos,!1);return e.bufferPos+=4,t},R_=e=>{let t=H(e),n=H(e);return t*4294967296+n},z_=e=>{let t=L_(e),n=H(e);return t*4294967296+n},B_=e=>{M_(e,8);let t=e.view.getFloat64(e.bufferPos,!1);return e.bufferPos+=8,t},V_=(e,t)=>{M_(e,t);let n=``;for(let r=0;r<t;r++)n+=String.fromCharCode(e.bytes[e.bufferPos++]);return n},H_=class{constructor(e){this.mutex=new Cp,this.trackTimestampInfo=/* @__PURE__ */ new WeakMap,this.output=e}onTrackClose(e){}validateTimestamp(e,t,n){let r=this.trackTimestampInfo.get(e);if(r){if(n&&(r.maxTimestampBeforeLastKeyPacket=r.maxTimestamp),r.maxTimestampBeforeLastKeyPacket!==null&&t<r.maxTimestampBeforeLastKeyPacket)throw Error(`Timestamps cannot be smaller than the largest timestamp of the previous GOP (a GOP begins with a key packet and ends right before the next key packet). Got ${t}s, but largest timestamp is ${r.maxTimestampBeforeLastKeyPacket}s.`);r.maxTimestamp=Math.max(r.maxTimestamp,t)}else{if(!n)throw Error(`First packet must be a key packet.`);r={maxTimestamp:t,maxTimestampBeforeLastKeyPacket:null},this.trackTimestampInfo.set(e,r)}}},U_=/<(?:(\d{2}):)?(\d{2}):(\d{2}).(\d{3})>/g,W_=e=>{let t=Math.floor(e/36e5),n=Math.floor(e%36e5/6e4),r=Math.floor(e%6e4/1e3),i=e%1e3;return t.toString().padStart(2,`0`)+`:`+n.toString().padStart(2,`0`)+`:`+r.toString().padStart(2,`0`)+`.`+i.toString().padStart(3,`0`)},G_=class{constructor(e){this.writer=e,this.helper=/* @__PURE__ */ new Uint8Array(8),this.helperView=new DataView(this.helper.buffer),this.offsets=/* @__PURE__ */ new WeakMap}writeU32(e){this.helperView.setUint32(0,e,!1),this.writer.write(this.helper.subarray(0,4))}writeU64(e){this.helperView.setUint32(0,Math.floor(e/2**32),!1),this.helperView.setUint32(4,e,!1),this.writer.write(this.helper.subarray(0,8))}writeAscii(e){for(let t=0;t<e.length;t++)this.helperView.setUint8(t%8,e.charCodeAt(t)),t%8==7&&this.writer.write(this.helper);e.length%8!=0&&this.writer.write(this.helper.subarray(0,e.length%8))}writeBox(e){if(this.offsets.set(e,this.writer.getPos()),e.contents&&!e.children)this.writeBoxHeader(e,e.size??e.contents.byteLength+8),this.writer.write(e.contents);else{let t=this.writer.getPos();if(this.writeBoxHeader(e,0),e.contents&&this.writer.write(e.contents),e.children)for(let t of e.children)t&&this.writeBox(t);let n=this.writer.getPos(),r=e.size??n-t;this.writer.seek(t),this.writeBoxHeader(e,r),this.writer.seek(n)}}writeBoxHeader(e,t){this.writeU32(e.largeSize?1:t),this.writeAscii(e.type),e.largeSize&&this.writeU64(t)}measureBoxHeader(e){return 8+(e.largeSize?8:0)}patchBox(e){let t=this.offsets.get(e);z(t!==void 0);let n=this.writer.getPos();this.writer.seek(t),this.writeBox(e),this.writer.seek(n)}measureBox(e){if(e.contents&&!e.children)return this.measureBoxHeader(e)+e.contents.byteLength;{let t=this.measureBoxHeader(e);if(e.contents&&(t+=e.contents.byteLength),e.children)for(let n of e.children)n&&(t+=this.measureBox(n));return t}}},U=/* #__PURE__ */ new Uint8Array(8),K_=/* #__PURE__ */ new DataView(U.buffer),q_=e=>[(e%256+256)%256],W=e=>(K_.setUint16(0,e,!1),[U[0],U[1]]),J_=e=>(K_.setInt16(0,e,!1),[U[0],U[1]]),Y_=e=>(K_.setUint32(0,e,!1),[U[1],U[2],U[3]]),G=e=>(K_.setUint32(0,e,!1),[U[0],U[1],U[2],U[3]]),X_=e=>(K_.setInt32(0,e,!1),[U[0],U[1],U[2],U[3]]),Z_=e=>(K_.setUint32(0,Math.floor(e/2**32),!1),K_.setUint32(4,e,!1),[U[0],U[1],U[2],U[3],U[4],U[5],U[6],U[7]]),Q_=e=>(K_.setInt32(0,Math.floor(e/2**32),!1),K_.setUint32(4,e,!1),[U[0],U[1],U[2],U[3],U[4],U[5],U[6],U[7]]),$_=e=>(K_.setInt16(0,256*e,!1),[U[0],U[1]]),ev=e=>(K_.setInt32(0,2**16*e,!1),[U[0],U[1],U[2],U[3]]),tv=e=>(K_.setInt32(0,2**30*e,!1),[U[0],U[1],U[2],U[3]]),nv=(e,t)=>{let n=[],r=e;do{let e=r&127;r>>=7,n.length>0&&(e|=128),n.push(e),t!==void 0&&t--}while(r>0||t);return n.reverse()},rv=(e,t=!1)=>{let n=Array(e.length).fill(null).map((t,n)=>e.charCodeAt(n));return t&&n.push(0),n},iv=e=>[ev(e[0]),ev(e[1]),tv(e[2]),ev(e[3]),ev(e[4]),tv(e[5]),ev(e[6]),ev(e[7]),tv(e[8])],K=(e,t,n)=>({type:e,contents:t&&new Uint8Array(t.flat(10)),children:n}),av=(e,t,n,r,i)=>K(e,[q_(t),Y_(n),r??[]],i),ov=e=>e.isQuickTime?K(`ftyp`,[rv(`qt `),G(512),rv(`qt `)]):e.fragmented?e.cmaf?K(`ftyp`,[rv(`iso5`),G(512),rv(`iso5`),rv(`iso6`),rv(`mp41`),rv(`cmfc`),rv(`dash`)]):K(`ftyp`,[rv(`iso5`),G(512),rv(`iso5`),rv(`iso6`),rv(`mp41`)]):K(`ftyp`,[rv(`isom`),G(512),rv(`isom`),e.holdsAvc?rv(`avc1`):[],rv(`mp41`)]),sv=()=>K(`styp`,[rv(`iso5`),G(0),rv(`iso5`),rv(`iso6`),rv(`mp41`),rv(`cmfc`),rv(`dash`)]),cv=(e,t)=>{let n=Math.max(0,e.minWrittenTimestamp),r=Math.max(0,e.maxWrittenEndTimestamp-n);return Number.isFinite(r)||(r=0),av(`sidx`,1,0,[G(1),G(By),Z_(Uy(n,By)),Z_(0),W(0),W(1),G(t&2147483647),G(Uy(r,By)),G(0)])},lv=e=>({type:`mdat`,largeSize:e}),uv=e=>({type:`free`,size:e}),dv=e=>K(`moov`,void 0,[fv(e.creationTime,e.trackDatas),...e.trackDatas.map(t=>pv(t,e.creationTime)),e.isFragmented?ny(e.trackDatas):null,_y(e)]),fv=(e,t)=>{let n=Math.max(0,...t.map(e=>Math.max(0,Uy(Wy(e),By)+Uy(e.startTimestampOffset??0,By)))),r=Math.max(0,...t.map(e=>e.track.id))+1,i=!rp(e)||!rp(n),a=i?Z_:G;return av(`mvhd`,+i,0,[a(e),a(e),G(By),a(n),ev(1),$_(1),Array(10).fill(0),iv(Jf),Array(24).fill(0),G(r)])},pv=(e,t)=>{let n=Hy(e),r=e.startTimestampOffset!==null&&e.startTimestampOffset!==0;return K(`trak`,void 0,[mv(e,t),r?hv(e):null,gv(e,t),n.name===void 0?null:K(`udta`,void 0,[K(`name`,[...dp.encode(n.name)])])])},mv=(e,t)=>{let n=Math.max(0,Uy(Wy(e),By)+Uy(e.startTimestampOffset??0,By)),r=!rp(t)||!rp(n),i=r?Z_:G,a;if(e.type===`video`&&e.track.metadata.transformationMatrix)a=e.track.metadata.transformationMatrix;else if(e.type===`video`){let{rotation:t,flip:n}=e.track.metadata;a=Yf(tp(Qf(t??0),ep(n?-1:1,1)),e.info.width,e.info.height)}else a=Jf;let o=2;e.track.metadata.disposition?.default!==!1&&(o|=1);let s=e.type===`video`?0:e.type===`audio`?1:e.type===`subtitle`?2:Np(e);return av(`tkhd`,+r,o,[i(t),i(t),G(e.track.id),G(0),i(n),Array(8).fill(0),W(0),W(s),$_(+(e.type===`audio`)),W(0),iv(a),ev(e.type===`video`?e.info.width:0),ev(e.type===`video`?e.info.height:0)])},hv=e=>{let t=e.startTimestampOffset;if(z(t!==null),t>0){let n=Uy(t,By),r=Uy(Wy(e),By),i=!rp(n)||!rp(r),a=i?Z_:G,o=i?Q_:X_;return K(`edts`,void 0,[av(`elst`,+!!i,0,[G(2),a(n),o(-1),ev(1),a(r),o(0),ev(1)])])}{let n=Uy(-t,e.timescale),r=Math.max(0,Uy(Wy(e),By)+Uy(t,By)),i=!ip(n)||!rp(r),a=i?Z_:G,o=i?Q_:X_;return K(`edts`,void 0,[av(`elst`,+!!i,0,[G(1),a(r),o(n),ev(1)])])}},gv=(e,t)=>K(`mdia`,void 0,[_v(e,t),bv(!0,vv[e.type],yv[e.type]),xv(e)]),_v=(e,t)=>{let n=Uy(Wy(e),e.timescale),r=!rp(t)||!rp(n),i=r?Z_:G;return av(`mdhd`,+r,0,[i(t),i(t),G(e.timescale),i(n),W(jy(e.track.metadata.languageCode??`und`)),W(0)])},vv={video:`vide`,audio:`soun`,subtitle:`text`},yv={video:`MediabunnyVideoHandler`,audio:`MediabunnySoundHandler`,subtitle:`MediabunnyTextHandler`},bv=(e,t,n,r=`\0\0\0\0`)=>av(`hdlr`,0,0,[e?rv(`mhlr`):G(0),rv(t),rv(r),G(0),G(0),rv(n,!0)]),xv=e=>K(`minf`,void 0,[Sv[e.type](),Cv(),Ev(e)]),Sv={video:()=>av(`vmhd`,0,1,[W(0),W(0),W(0),W(0)]),audio:()=>av(`smhd`,0,0,[W(0),W(0)]),subtitle:()=>av(`nmhd`,0,0)},Cv=()=>K(`dinf`,void 0,[wv()]),wv=()=>av(`dref`,0,0,[G(1)],[Tv()]),Tv=()=>av(`url `,0,1),Ev=e=>{let t=e.compositionTimeOffsetTable.length>1||e.compositionTimeOffsetTable.some(e=>e.sampleCompositionTimeOffset!==0);return K(`stbl`,void 0,[Dv(e),Yv(e),t?ey(e):null,t?ty(e):null,Zv(e),Qv(e),$v(e),Xv(e)])},Dv=e=>{let t;if(e.type===`video`)t=Ov(Ty(e.track.source._codec,e.info.decoderConfig.codec),e);else if(e.type===`audio`){let n=Dy(e.track.source._codec,e.info.decoderConfig.codec,e.muxer.isQuickTime);z(n),t=Iv(n,e)}else e.type===`subtitle`&&(t=qv(ky[e.track.source._codec],e));return z(t),av(`stsd`,0,0,[G(1)],[t])},Ov=(e,t)=>K(e,[[,,,,,,].fill(0),W(1),W(0),W(0),Array(12).fill(0),W(t.info.width),W(t.info.height),G(4718592),G(4718592),G(0),W(1),q_(10),rv(`Mediabunny`),Array(21).fill(0),W(t.info.hasAlphaChannel?32:24),J_(65535)],[Ey[t.track.source._codec]?.(t)??null,Av(t),bp(t.info.decoderConfig.colorSpace)?null:jv(t),kv(t)]),kv=e=>e.avgBitrate===0&&e.maxBitrate===0?null:K(`btrt`,[G(0),G(e.maxBitrate),G(e.avgBitrate)]),Av=e=>e.info.pixelAspectRatio.num===e.info.pixelAspectRatio.den?null:K(`pasp`,[G(e.info.pixelAspectRatio.num),G(e.info.pixelAspectRatio.den)]),jv=e=>{let t=e.info.decoderConfig.colorSpace;return K(`colr`,[rv(e.muxer.isQuickTime?`nclc`:`nclx`),W(t?.primaries==null?2:pp[t.primaries]),W(t?.transfer==null?2:hp[t.transfer]),W(t?.matrix==null?2:_p[t.matrix]),e.muxer.isQuickTime?[]:q_(!!t?.fullRange<<7)])},Mv=e=>e.info.decoderConfig&&K(`avcC`,[...op(e.info.decoderConfig.description)]),Nv=e=>e.info.decoderConfig&&K(`hvcC`,[...op(e.info.decoderConfig.description)]),Pv=e=>{if(!e.info.decoderConfig)return null;let t=e.info.decoderConfig,n=t.codec.split(`.`),r=Number(n[1]),i=Number(n[2]),a=Number(n[3]),o=n[4]?Number(n[4]):1,s=n[8]?Number(n[8]):Number(t.colorSpace?.fullRange??0),c=(a<<4)+(o<<1)+s,l=n[5]?Number(n[5]):t.colorSpace?.primaries?pp[t.colorSpace.primaries]:1,u=n[6]?Number(n[6]):t.colorSpace?.transfer?hp[t.colorSpace.transfer]:1,d=n[7]?Number(n[7]):t.colorSpace?.matrix?_p[t.colorSpace.matrix]:1;return av(`vpcC`,1,0,[q_(r),q_(i),q_(c),q_(l),q_(u),q_(d),W(0)])},Fv=e=>K(`av1C`,Wh(e.info.decoderConfig.codec)),Iv=(e,t)=>{let n=0,r,i=16,a=Ph.includes(t.track.source._codec);if(a){let e=t.track.source._codec,{sampleSize:r}=Xh(e);i=8*r,i>16&&(n=1)}if(t.muxer.isQuickTime&&(n=1),n===0)r=[[,,,,,,].fill(0),W(1),W(n),W(0),G(0),W(t.info.numberOfChannels),W(i),W(0),W(0),W(t.info.sampleRate<2**16?t.info.sampleRate:0),W(0)];else{let e=a?0:-2;r=[[,,,,,,].fill(0),W(1),W(n),W(0),G(0),W(t.info.numberOfChannels),W(Math.min(i,16)),J_(e),W(0),W(t.info.sampleRate<2**16?t.info.sampleRate:0),W(0),a?[G(1),G(i/8),G(t.info.numberOfChannels*i/8)]:[G(0),G(0),G(0)],G(2)]}return K(e,r,[Oy(t.track.source._codec,t.muxer.isQuickTime)?.(t)??null,kv(t)])},Lv=e=>{let t;switch(e.track.source._codec){case`aac`:t=64;break;case`mp3`:t=107;break;case`vorbis`:t=221;break;default:throw Error(`Unhandled audio codec: ${e.track.source._codec}`)}let n=[...q_(t),...q_(21),...Y_(0),...G(e.maxBitrate),...G(e.avgBitrate)];if(e.info.decoderConfig.description){let t=op(e.info.decoderConfig.description);n=[...n,...q_(5),...nv(t.byteLength),...t]}return n=[...W(1),...q_(0),...q_(4),...nv(n.length),...n,...q_(6),...q_(1),...q_(2)],n=[...q_(3),...nv(n.length),...n],av(`esds`,0,0,n)},Rv=e=>K(`wave`,void 0,[zv(e),Bv(e),K(`\0\0\0\0`)]),zv=e=>K(`frma`,[rv(Dy(e.track.source._codec,e.info.decoderConfig.codec,e.muxer.isQuickTime))]),Bv=e=>{let{littleEndian:t}=Xh(e.track.source._codec);return K(`enda`,[W(+t)])},Vv=e=>{let t=e.info.numberOfChannels,n=3840,r=e.info.sampleRate,i=0,a=0,o=/* @__PURE__ */ new Uint8Array,s=e.info.decoderConfig?.description;if(s){z(s.byteLength>=18);let e=ah(op(s));t=e.outputChannelCount,n=e.preSkip,r=e.inputSampleRate,i=e.outputGain,a=e.channelMappingFamily,e.channelMappingTable&&(o=e.channelMappingTable)}return K(`dOps`,[q_(0),q_(t),W(n),G(r),J_(i),q_(a),...o])},Hv=e=>{let t=e.info.decoderConfig?.description;return z(t),av(`dfLa`,0,0,[...op(t).subarray(4)])},Uv=e=>{let{littleEndian:t,sampleSize:n}=Xh(e.track.source._codec);return av(`pcmC`,0,0,[q_(+t),q_(8*n)])},Wv=e=>{z(e.info.primingPacket);let t=lh(e.info.primingPacket.data);if(!t)throw Error(`Couldn't extract AC-3 frame info from the audio packet. Ensure the packets contain valid AC-3 sync frames (as specified in ETSI TS 102 366).`);let n=/* @__PURE__ */ new Uint8Array(3),r=new fm(n);return r.writeBits(2,t.fscod),r.writeBits(5,t.bsid),r.writeBits(3,t.bsmod),r.writeBits(3,t.acmod),r.writeBits(1,t.lfeon),r.writeBits(5,t.bitRateCode),r.writeBits(5,0),K(`dac3`,[...n])},Gv=e=>{z(e.info.primingPacket);let t=dh(e.info.primingPacket.data);if(!t)throw Error(`Couldn't extract E-AC-3 frame info from the audio packet. Ensure the packets contain valid E-AC-3 sync frames (as specified in ETSI TS 102 366).`);let n=16;for(let e of t.substreams)n+=23,e.numDepSub>0?n+=9:n+=1;let r=Math.ceil(n/8),i=new Uint8Array(r),a=new fm(i);a.writeBits(13,t.dataRate),a.writeBits(3,t.substreams.length-1);for(let e of t.substreams)a.writeBits(2,e.fscod),a.writeBits(5,e.bsid),a.writeBits(1,0),a.writeBits(1,0),a.writeBits(3,e.bsmod),a.writeBits(3,e.acmod),a.writeBits(1,e.lfeon),a.writeBits(3,0),a.writeBits(4,e.numDepSub),e.numDepSub>0?a.writeBits(9,e.chanLoc):a.writeBits(1,0);return K(`dec3`,[...i])},Kv=e=>{z(e.info.primingPacket);let t=Eh(e.info.primingPacket.data);if(!t)throw Error(`Couldn't extract DTS frame info from the audio packet. Ensure the packets contain valid DTS frames as specified in ETSI TS 102 114.`);return K(`ddts`,[...jh(t)])},qv=(e,t)=>K(e,[[,,,,,,].fill(0),W(1)],[Ay[t.track.source._codec](t),kv(t)]),Jv=e=>K(`vttC`,[...dp.encode(e.info.config.description)]),Yv=e=>av(`stts`,0,0,[G(e.timeToSampleTable.length),e.timeToSampleTable.map(e=>[G(e.sampleCount),G(e.sampleDelta)])]),Xv=e=>{if(e.samples.every(e=>e.type===`key`))return null;let t=[...e.samples.entries()].filter(([,e])=>e.type===`key`);return av(`stss`,0,0,[G(t.length),t.map(([e])=>G(e+1))])},Zv=e=>av(`stsc`,0,0,[G(e.compactlyCodedChunkTable.length),e.compactlyCodedChunkTable.map(e=>[G(e.firstChunk),G(e.samplesPerChunk),G(1)])]),Qv=e=>{if(e.type===`audio`&&e.info.requiresPcmTransformation){let{sampleSize:t}=Xh(e.track.source._codec);return av(`stsz`,0,0,[G(t*e.info.numberOfChannels),G(e.samples.reduce((t,n)=>t+Uy(n.duration,e.timescale),0))])}return av(`stsz`,0,0,[G(0),G(e.samples.length),e.samples.map(e=>G(e.size))])},$v=e=>e.finalizedChunks.length>0&&np(e.finalizedChunks).offset>=2**32?av(`co64`,0,0,[G(e.finalizedChunks.length),e.finalizedChunks.map(e=>Z_(e.offset))]):av(`stco`,0,0,[G(e.finalizedChunks.length),e.finalizedChunks.map(e=>G(e.offset))]),ey=e=>av(`ctts`,1,0,[G(e.compositionTimeOffsetTable.length),e.compositionTimeOffsetTable.map(e=>[G(e.sampleCount),X_(e.sampleCompositionTimeOffset)])]),ty=e=>{let t=1/0,n=-1/0,r=1/0,i=-1/0;z(e.compositionTimeOffsetTable.length>0),z(e.samples.length>0);for(let r=0;r<e.compositionTimeOffsetTable.length;r++){let i=e.compositionTimeOffsetTable[r];t=Math.min(t,i.sampleCompositionTimeOffset),n=Math.max(n,i.sampleCompositionTimeOffset)}for(let t=0;t<e.samples.length;t++){let n=e.samples[t];r=Math.min(r,Uy(n.timestamp,e.timescale)),i=Math.max(i,Uy(n.timestamp+n.duration,e.timescale))}let a=Math.max(-t,0);return i>=2**31?null:av(`cslg`,0,0,[X_(a),X_(t),X_(n),X_(r),X_(i)])},ny=e=>K(`mvex`,void 0,e.map(ry)),ry=e=>av(`trex`,0,0,[G(e.track.id),G(1),G(0),G(0),G(0)]),iy=(e,t)=>K(`moof`,void 0,[ay(e),...t.map(sy)]),ay=e=>av(`mfhd`,0,0,[G(e)]),oy=e=>{let t=0,n=0,r=e.type===`delta`;return n|=+r,t|=r?1:2,t<<24|n<<16|0},sy=e=>K(`traf`,void 0,[cy(e),ly(e),uy(e)]),cy=e=>{z(e.currentChunk);let t=0;t|=8,t|=16,t|=32,t|=131072;let n=e.currentChunk.samples[1]??e.currentChunk.samples[0],r={duration:n.timescaleUnitsToNextSample,size:n.size,flags:oy(n)};return av(`tfhd`,0,t,[G(e.track.id),G(r.duration),G(r.size),G(r.flags)])},ly=e=>(z(e.currentChunk),av(`tfdt`,1,0,[Z_(Uy(e.currentChunk.startTimestamp,e.timescale))])),uy=e=>{z(e.currentChunk);let t=e.currentChunk.samples.map(e=>e.timescaleUnitsToNextSample),n=e.currentChunk.samples.map(e=>e.size),r=e.currentChunk.samples.map(oy),i=e.currentChunk.samples.map(t=>Uy(t.timestamp-t.decodeTimestamp,e.timescale)),a=new Set(t),o=new Set(n),s=new Set(r),c=new Set(i),l=s.size===2&&r[0]!==r[1],u=a.size>1,d=o.size>1,f=!l&&s.size>1,p=c.size>1||[...c].some(e=>e!==0),m=0;return m|=1,m|=4*l,m|=256*u,m|=512*d,m|=1024*f,m|=2048*p,av(`trun`,1,m,[G(e.currentChunk.samples.length),G(e.currentChunk.offset-e.currentChunk.moofOffset||0),l?G(r[0]):[],e.currentChunk.samples.map((e,a)=>[u?G(t[a]):[],d?G(n[a]):[],f?G(r[a]):[],p?X_(i[a]):[]])])},dy=e=>K(`mfra`,void 0,[...e.map(fy),py()]),fy=e=>av(`tfra`,1,0,[G(e.track.id),G(63),G(e.finalizedChunks.length),e.finalizedChunks.map(t=>[Z_(Uy(t.samples[0].timestamp,e.timescale)),Z_(t.moofOffset),G(t.trafIndex+1),G(1),G(1)])]),py=()=>av(`mfro`,0,0,[G(0)]),my=()=>K(`vtte`),hy=(e,t,n,r,i)=>K(`vttc`,void 0,[i===null?null:K(`vsid`,[X_(i)]),n===null?null:K(`iden`,[...dp.encode(n)]),t===null?null:K(`ctim`,[...dp.encode(W_(t))]),r===null?null:K(`sttg`,[...dp.encode(r)]),K(`payl`,[...dp.encode(e)])]),gy=e=>K(`vtta`,[...dp.encode(e)]),_y=e=>{let t=[],n=e.format._options.metadataFormat??`auto`,r=e.output._metadataTags;if(n===`mdir`||n===`auto`&&!e.isQuickTime){let e=Sy(r);e&&t.push(e)}else if(n===`mdta`){let e=Cy(r);e&&t.push(e)}else(n===`udta`||n===`auto`&&e.isQuickTime)&&vy(t,e.output._metadataTags);return t.length===0?null:K(`udta`,void 0,t)},vy=(e,t)=>{for(let{key:n,value:r}of Yp(t))switch(n){case`title`:e.push(yy(`©nam`,r));break;case`description`:e.push(yy(`©des`,r));break;case`artist`:e.push(yy(`©ART`,r));break;case`album`:e.push(yy(`©alb`,r));break;case`albumArtist`:e.push(yy(`albr`,r));break;case`genre`:e.push(yy(`©gen`,r));break;case`date`:e.push(yy(`©day`,r.toISOString().slice(0,10)));break;case`comment`:e.push(yy(`©cmt`,r));break;case`lyrics`:e.push(yy(`©lyr`,r));break;case`raw`:break;case`discNumber`:case`discsTotal`:case`trackNumber`:case`tracksTotal`:case`images`:break;default:Np(n)}if(t.raw)for(let n in t.raw){let r=t.raw[n];r==null||n.length!==4||e.some(e=>e.type===n)||(typeof r==`string`?e.push(yy(n,r)):r instanceof Uint8Array&&e.push(K(n,Array.from(r))))}},yy=(e,t)=>{let n=dp.encode(t);return K(e,[W(n.length),W(jy(`und`)),Array.from(n)])},by={"image/jpeg":13,"image/png":14,"image/bmp":27},xy=(e,t)=>{let n=[];for(let{key:r,value:i}of Yp(e))switch(r){case`title`:n.push({key:t?`title`:`©nam`,value:wy(i)});break;case`description`:n.push({key:t?`description`:`©des`,value:wy(i)});break;case`artist`:n.push({key:t?`artist`:`©ART`,value:wy(i)});break;case`album`:n.push({key:t?`album`:`©alb`,value:wy(i)});break;case`albumArtist`:n.push({key:t?`album_artist`:`aART`,value:wy(i)});break;case`comment`:n.push({key:t?`comment`:`©cmt`,value:wy(i)});break;case`genre`:n.push({key:t?`genre`:`©gen`,value:wy(i)});break;case`lyrics`:n.push({key:t?`lyrics`:`©lyr`,value:wy(i)});break;case`date`:n.push({key:t?`date`:`©day`,value:wy(i.toISOString().slice(0,10))});break;case`images`:for(let e of i)e.kind===`coverFront`&&n.push({key:`covr`,value:K(`data`,[G(by[e.mimeType]??0),G(0),Array.from(e.data)])});break;case`trackNumber`:if(t){let t=e.tracksTotal===void 0?i.toString():`${i}/${e.tracksTotal}`;n.push({key:`track`,value:wy(t)})}else n.push({key:`trkn`,value:K(`data`,[G(0),G(0),W(0),W(i),W(e.tracksTotal??0),W(0)])});break;case`discNumber`:t||n.push({key:`disc`,value:K(`data`,[G(0),G(0),W(0),W(i),W(e.discsTotal??0),W(0)])});break;case`tracksTotal`:case`discsTotal`:break;case`raw`:break;default:Np(r)}if(e.raw)for(let r in e.raw){let i=e.raw[r];i==null||!t&&r.length!==4||n.some(e=>e.key===r)||(typeof i==`string`?n.push({key:r,value:wy(i)}):i instanceof Uint8Array?n.push({key:r,value:K(`data`,[G(0),G(0),Array.from(i)])}):i instanceof sm&&n.push({key:r,value:K(`data`,[G(by[i.mimeType]??0),G(0),Array.from(i.data)])}))}return n},Sy=e=>{let t=xy(e,!1);return t.length===0?null:av(`meta`,0,0,void 0,[bv(!1,`mdir`,``,`appl`),K(`ilst`,void 0,t.map(e=>K(e.key,void 0,[e.value])))])},Cy=e=>{let t=xy(e,!0);return t.length===0?null:K(`meta`,void 0,[bv(!1,`mdta`,``),av(`keys`,0,0,[G(t.length)],t.map(e=>K(`mdta`,[...dp.encode(e.key)]))),K(`ilst`,void 0,t.map((e,t)=>K(String.fromCharCode(...G(t+1)),void 0,[e.value])))])},wy=e=>K(`data`,[G(1),G(0),...dp.encode(e)]),Ty=(e,t)=>{switch(e){case`avc`:return t.startsWith(`avc3`)?`avc3`:`avc1`;case`hevc`:return`hvc1`;case`vp8`:return`vp08`;case`vp9`:return`vp09`;case`av1`:return`av01`;case`prores`:return t}},Ey={avc:Mv,hevc:Nv,vp8:Pv,vp9:Pv,av1:Fv,prores:null},Dy=(e,t,n)=>{switch(e){case`aac`:return`mp4a`;case`mp3`:return`mp4a`;case`opus`:return`Opus`;case`vorbis`:return`mp4a`;case`flac`:return`fLaC`;case`ulaw`:return`ulaw`;case`alaw`:return`alaw`;case`pcm-u8`:return`raw `;case`pcm-s8`:return`sowt`;case`ac3`:return`ac-3`;case`eac3`:return`ec-3`;case`dts`:return t}if(n)switch(e){case`pcm-s16`:return`sowt`;case`pcm-s16be`:return`twos`;case`pcm-s24`:return`in24`;case`pcm-s24be`:return`in24`;case`pcm-s32`:return`in32`;case`pcm-s32be`:return`in32`;case`pcm-f32`:return`fl32`;case`pcm-f32be`:return`fl32`;case`pcm-f64`:return`fl64`;case`pcm-f64be`:return`fl64`}else switch(e){case`pcm-s16`:return`ipcm`;case`pcm-s16be`:return`ipcm`;case`pcm-s24`:return`ipcm`;case`pcm-s24be`:return`ipcm`;case`pcm-s32`:return`ipcm`;case`pcm-s32be`:return`ipcm`;case`pcm-f32`:return`fpcm`;case`pcm-f32be`:return`fpcm`;case`pcm-f64`:return`fpcm`;case`pcm-f64be`:return`fpcm`}},Oy=(e,t)=>{switch(e){case`aac`:return Lv;case`mp3`:return Lv;case`opus`:return Vv;case`vorbis`:return Lv;case`flac`:return Hv;case`ac3`:return Wv;case`eac3`:return Gv;case`dts`:return Kv}if(t)switch(e){case`pcm-s24`:return Rv;case`pcm-s24be`:return Rv;case`pcm-s32`:return Rv;case`pcm-s32be`:return Rv;case`pcm-f32`:return Rv;case`pcm-f32be`:return Rv;case`pcm-f64`:return Rv;case`pcm-f64be`:return Rv}else switch(e){case`pcm-s16`:return Uv;case`pcm-s16be`:return Uv;case`pcm-s24`:return Uv;case`pcm-s24be`:return Uv;case`pcm-s32`:return Uv;case`pcm-s32be`:return Uv;case`pcm-f32`:return Uv;case`pcm-f32be`:return Uv;case`pcm-f64`:return Uv;case`pcm-f64be`:return Uv}return null},ky={webvtt:`wvtt`},Ay={webvtt:Jv},jy=e=>{z(e.length===3);let t=0;for(let n=0;n<3;n++)t<<=5,t+=e.charCodeAt(n)-96;return t},My=class{constructor(e,t){if(this.finalized=!1,this.started=!1,this.pos=0,this.trackedWrites=null,this.trackedStart=-1,this.trackedEnd=-1,e._writerAcquired)throw Error(`Can't have multiple Writers for the same Target.`);this.target=e,e._setMonotonicity(t),e._writerAcquired=!0}start(){z(!this.started),this.target._start(),this.started=!0}write(e){z(this.started&&!this.finalized),this.maybeTrackWrites(e),this.target._write(e,this.pos),this.pos+=e.byteLength}seek(e){this.pos=e}getPos(){return this.pos}async flush(){return z(this.started&&!this.finalized),this.target._flush()}async finalize(){z(this.started&&!this.finalized),await this.target._finalize(),this.finalized=!0}maybeTrackWrites(e){if(!this.trackedWrites)return;let t=this.getPos();if(t<this.trackedStart){if(t+e.byteLength<=this.trackedStart)return;e=e.subarray(this.trackedStart-t),t=0}let n=t+e.byteLength-this.trackedStart,r=this.trackedWrites.byteLength;for(;r<n;)r*=2;if(r!==this.trackedWrites.byteLength){let e=new Uint8Array(r);e.set(this.trackedWrites,0),this.trackedWrites=e}this.trackedWrites.set(e,t-this.trackedStart),this.trackedEnd=Math.max(this.trackedEnd,t+e.byteLength)}startTrackingWrites(){this.trackedWrites=/* @__PURE__ */ new Uint8Array(1024),this.trackedStart=this.getPos(),this.trackedEnd=this.trackedStart}stopTrackingWrites(){if(!this.trackedWrites)throw Error(`Internal error: Can't get tracked writes since nothing was tracked.`);let e={data:this.trackedWrites.subarray(0,this.trackedEnd-this.trackedStart),start:this.trackedStart,end:this.trackedEnd};return this.trackedWrites=null,e}},Ny=class extends rm{constructor(){super(...arguments),this._writerAcquired=!1,this._monotonicity=null,this.onwrite=null}_setMonotonicity(e){this._monotonicity!==!1&&(this._monotonicity=e)}_dispatchWrite(e,t){this.onwrite?.(e,t),this._emit(`write`,{start:e,end:t})}slice(e){if(!Number.isInteger(e)||e<0)throw TypeError(`offset must be a non-negative integer.`);return new Ry(this,e)}},Py=2**16,Fy=2**32,Iy=class extends Ny{constructor(e={}){if(super(),this.buffer=null,this._maxPos=0,!e||typeof e!=`object`)throw TypeError(`BufferTarget options, when provided, must be an object.`);if(e.onFinalize!==void 0&&typeof e.onFinalize!=`function`)throw TypeError(`options.onFinalize, when provided, must be a function.`);if(this._options=e,this._supportsResize=`resize`in/* @__PURE__ */ new ArrayBuffer(0),this._supportsResize)try{this._buffer=new ArrayBuffer(Py,{maxByteLength:Fy})}catch{this._buffer=new ArrayBuffer(Py),this._supportsResize=!1}else this._buffer=new ArrayBuffer(Py);this._bytes=new Uint8Array(this._buffer)}_ensureSize(e){let t=this._buffer.byteLength;for(;t<e;)t*=2;if(t!==this._buffer.byteLength){if(t>Fy)throw Error(`ArrayBuffer exceeded maximum size of ${Fy} bytes. Please consider using another target.`);if(this._supportsResize)this._buffer.resize(t);else{let e=new ArrayBuffer(t),n=new Uint8Array(e);n.set(this._bytes,0),this._buffer=e,this._bytes=n}}}_start(){}_write(e,t){this._ensureSize(t+e.byteLength),this._bytes.set(e,t),this._maxPos=Math.max(this._maxPos,t+e.byteLength),this._dispatchWrite(t,t+e.byteLength)}async _flush(){}async _finalize(){this.buffer=this._buffer.slice(0,this._maxPos),this._options.onFinalize&&await this._options.onFinalize(this.buffer),this._emit(`finalized`)}async _close(){}_getSlice(e,t){return this._bytes.slice(e,t)}},Ly=class extends Ny{_start(){}_write(e,t){this._dispatchWrite(t,t+e.byteLength)}async _flush(){}async _finalize(){this._emit(`finalized`)}async _close(){}},Ry=class extends Ny{constructor(e,t){super(),this._baseTarget=e,this._offset=t}_start(){}_write(e,t){this._baseTarget._write(e,this._offset+t),this._dispatchWrite(t,t+e.byteLength)}_flush(){return this._baseTarget._flush()}async _finalize(){this._emit(`finalized`)}async _close(){}_setMonotonicity(e){super._setMonotonicity(e),this._baseTarget._setMonotonicity(e)}},zy=class{constructor(e,t){if(this.rootPath=e,this.getTarget=t,typeof e!=`string`)throw TypeError(`rootPath must be a string.`);if(typeof t!=`function`)throw TypeError(`getTarget must be a function.`)}},By=57600,Vy=2082844800,Hy=e=>{let t={},n=e.track;return n.metadata.name!==void 0&&(t.name=n.metadata.name),t},Uy=(e,t,n=!0)=>{let r=e*t;return n?Math.round(r):r},Wy=e=>{if(e.samples.length===0)return 0;let t=1/0,n=-1/0;for(let r=0;r<e.samples.length;r++){let i=e.samples[r];i.timestamp<t&&(t=i.timestamp),i.timestamp+i.duration>n&&(n=i.timestamp+i.duration)}return t===1/0?0:n-t},Gy=class extends H_{constructor(e,t){super(e),this.writer=null,this.boxWriter=null,this.initWriter=null,this.initBoxWriter=null,this.auxTarget=new Iy,this.auxWriter=new My(this.auxTarget,!1),this.auxBoxWriter=new G_(this.auxWriter),this.mdat=null,this.ftypSize=null,this.trackDatas=[],this.allTracksKnown=Ap(),this.creationTime=Math.floor(Date.now()/1e3)+Vy,this.finalizedChunks=[],this.wroteFragmentedHeader=!1,this.nextFragmentNumber=1,this.maxWrittenTimestamp=-1/0,this.minWrittenTimestamp=1/0,this.maxWrittenEndTimestamp=-1/0,this.segmentHeaderSize=null,this.format=t,this.formatOptions={...t._options},this.isQuickTime=t instanceof tb,this.isCmaf=t instanceof eb,this.minimumFragmentDuration=this.formatOptions.minimumFragmentDuration??(t instanceof eb?1/0:1),this.auxWriter.start()}async start(){let e=await this.mutex.acquire();if(this.isCmaf?(this.fastStart=`fragmented`,this.isFragmented=!0):(this.writer=await this.output._getRootWriter(e=>this.formatOptions.fastStart===void 0?e instanceof Iy:this.formatOptions.fastStart===`fragmented`),this.boxWriter=new G_(this.writer),this.fastStart=this.formatOptions.fastStart??(this.writer.target instanceof Iy&&`in-memory`),this.isFragmented=this.fastStart===`fragmented`),this.isCmaf){if(!this.output._hasInitTarget())throw Error(`CMAF outputs require the initTarget field in OutputOptions to be set; the init segment will be written to it.`);let e=new My(await this.output._getInitTarget(),!0);e.start(),this.initWriter=e,this.initBoxWriter=new G_(e)}let t=this.output.tracks.some(e=>e.isVideoTrack()&&e.source._codec===`avc`);{let e=this.initBoxWriter??this.boxWriter;if(z(e),this.formatOptions.onFtyp&&e.writer.startTrackingWrites(),e.writeBox(ov({isQuickTime:this.isQuickTime,holdsAvc:t,fragmented:this.isFragmented,cmaf:this.isCmaf})),this.formatOptions.onFtyp){let{data:t,start:n}=e.writer.stopTrackingWrites();this.formatOptions.onFtyp(t,n)}this.ftypSize=e.writer.getPos(),this.isCmaf&&await this.initWriter.flush()}if(this.fastStart!==`in-memory`){if(this.fastStart===`reserve`){for(let e of this.output.tracks)if(e.metadata.maximumPacketCount===void 0)throw Error(`All tracks must specify maximumPacketCount in their metadata when using fastStart: 'reserve'.`)}else this.isFragmented||(z(this.writer),z(this.boxWriter),this.formatOptions.onMdat&&this.writer.startTrackingWrites(),this.mdat=lv(!0),this.boxWriter.writeBox(this.mdat))}await this.writer?.flush();for(let e of this.output.tracks)e.isVideoTrack()&&e.metadata.decoderConfig?this.getVideoTrackData(e,e.metadata.primingPacket??null,{decoderConfig:e.metadata.decoderConfig}):e.isAudioTrack()&&e.metadata.decoderConfig&&this.getAudioTrackData(e,e.metadata.primingPacket??null,{decoderConfig:e.metadata.decoderConfig});e()}allTracksAreKnown(){for(let e of this.output.tracks)if(!e.source._closed&&!this.trackDatas.some(t=>t.track===e))return!1;return!0}async getMimeType(){await this.allTracksKnown.promise;let e=this.trackDatas.map(e=>e.type===`video`||e.type===`audio`?e.info.decoderConfig.codec:{webvtt:`wvtt`}[e.track.source._codec]);return ug({isQuickTime:this.isQuickTime,hasVideo:this.trackDatas.some(e=>e.type===`video`),hasAudio:this.trackDatas.some(e=>e.type===`audio`),codecStrings:e})}getVideoTrackData(e,t,n){let r=this.trackDatas.find(t=>t.track===e);if(r)return r;rg(n,e.source._codec),z(n),z(n.decoderConfig);let i={...n.decoderConfig};z(i.codedWidth!==void 0),z(i.codedHeight!==void 0);let a=!1;if(e.source._codec===`avc`&&!i.description){if(!t)throw Error(`No AVC description provided; you must therefore provide a priming packet.`);let e=Mm(t.data);if(!e)throw Error(`Couldn't extract an AVCDecoderConfigurationRecord from the AVC packet. Make sure the packets are in Annex B format (as specified in ITU-T-REC-H.264) when not providing a description, or provide a description (must be an AVCDecoderConfigurationRecord as specified in ISO 14496-15) and ensure the packets are in AVCC format.`);i.description=Nm(e),a=!0}else if(e.source._codec===`hevc`&&!i.description){if(!t)throw Error(`No HEVC description provided; you must therefore provide a priming packet.`);let e=Vm(t.data);if(!e)throw Error(`Couldn't extract an HEVCDecoderConfigurationRecord from the HEVC packet. Make sure the packets are in Annex B format (as specified in ITU-T-REC-H.265) when not providing a description, or provide a description (must be an HEVCDecoderConfigurationRecord as specified in ISO 14496-15) and ensure the packets are in HEVC format.`);i.description=Ym(e),a=!0}let o=Wp(1/(e.metadata.frameRate??57600),1e6).den,s=i.displayAspectWidth,c=i.displayAspectHeight,l=s===void 0||c===void 0?{num:1,den:1}:tm({num:s*i.codedHeight,den:c*i.codedWidth}),u=i.codec===`ap4h`||i.codec===`ap4x`,d={muxer:this,track:e,type:`video`,info:{width:i.codedWidth,height:i.codedHeight,pixelAspectRatio:l,decoderConfig:i,requiresAnnexBTransformation:a,hasAlphaChannel:u},timescale:o,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,startTimestampOffset:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[],closed:!1,avgBitrate:e.source._nominalBitrate??e.metadata.averageBitrate??0,maxBitrate:e.source._nominalBitrate??e.metadata.bitrate??0};return this.trackDatas.push(d),this.trackDatas.sort((e,t)=>e.track.id-t.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),d}getAudioTrackData(e,t,n){let r=this.trackDatas.find(t=>t.track===e);if(r)return r;ag(n,e.source._codec),z(n),z(n.decoderConfig);let i={...n.decoderConfig},a=!1;if(e.source._codec===`aac`&&!i.description){if(!t)throw Error(`No AAC description provided; you must therefore provide a priming packet.`);let e=qg(j_.tempFromBytes(t.data));if(!e)throw Error(`Couldn't parse ADTS header from the AAC packet. Make sure the packets are in ADTS format (as specified in ISO 13818-7) when not providing a description, or provide a description (must be an AudioSpecificConfig as specified in ISO 14496-3) and ensure the packets are raw AAC data.`);let n=pm[e.samplingFrequencyIndex],r=mm[e.channelConfiguration];if(n===void 0||r===void 0)throw Error(`Invalid ADTS frame header.`);i.description=vm({objectType:e.objectType,outputSampleRate:n,outputNumberOfChannels:r}),a=!0}if(!t){if(e.source._codec===`ac3`||e.source._codec===`eac3`)throw Error(`AC-3/E-AC-3 require a priming packet.`);if(e.source._codec===`dts`)throw Error(`DTS requires a priming packet.`)}let o={muxer:this,track:e,type:`audio`,info:{numberOfChannels:n.decoderConfig.numberOfChannels,sampleRate:n.decoderConfig.sampleRate,decoderConfig:i,requiresPcmTransformation:!this.isFragmented&&Ph.includes(e.source._codec),expectedNextPcmPacketTimestamp:null,requiresAdtsStripping:a,primingPacket:t},timescale:i.sampleRate,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,startTimestampOffset:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[],closed:!1,avgBitrate:e.source._nominalBitrate??e.metadata.averageBitrate??0,maxBitrate:e.source._nominalBitrate??e.metadata.bitrate??0};return this.trackDatas.push(o),this.trackDatas.sort((e,t)=>e.track.id-t.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),o}getSubtitleTrackData(e,t){let n=this.trackDatas.find(t=>t.track===e);if(n)return n;og(t),z(t),z(t.config);let r={muxer:this,track:e,type:`subtitle`,info:{config:t.config},timescale:1e3,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,startTimestampOffset:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[],closed:!1,avgBitrate:e.source._nominalBitrate??e.metadata.averageBitrate??0,maxBitrate:e.source._nominalBitrate??e.metadata.bitrate??0,lastCueEndTimestamp:null,cueQueue:[],nextSourceId:0,cueToSourceId:/* @__PURE__ */ new WeakMap};return this.trackDatas.push(r),this.trackDatas.sort((e,t)=>e.track.id-t.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),r}async addEncodedVideoPacket(e,t,n){let r=await this.mutex.acquire();try{let r=this.getVideoTrackData(e,t,n),i=t.data;if(r.info.requiresAnnexBTransformation){let e=[...Em(i)].map(e=>i.subarray(e.offset,e.offset+e.length));if(e.length===0)throw Error(`Failed to transform packet data. Make sure all packets are provided in Annex B format, as specified in ITU-T-REC-H.264 and ITU-T-REC-H.265.`);i=jm(e,4)}this.validateTimestamp(r.track,t.timestamp,t.type===`key`);let a=this.createSampleForTrack(r,i,t.timestamp,t.duration,t.type);await this.registerSample(r,a)}finally{r()}}async addEncodedAudioPacket(e,t,n){let r=await this.mutex.acquire();try{let r=this.getAudioTrackData(e,t,n),i=t.data;if(r.info.requiresAdtsStripping){let e=qg(j_.tempFromBytes(i));if(!e)throw Error(`Expected ADTS frame, didn't get one.`);let t=e.crcCheck===null?7:9;i=i.subarray(t)}this.validateTimestamp(r.track,t.timestamp,t.type===`key`);let a=t.timestamp,o=t.duration;if(r.info.requiresPcmTransformation){let e=Xh(r.info.decoderConfig.codec).sampleSize*r.info.numberOfChannels;if(o=i.byteLength/e/r.info.sampleRate,r.info.expectedNextPcmPacketTimestamp!==null){let e=a-r.info.expectedNextPcmPacketTimestamp;if(e<.01)a=r.info.expectedNextPcmPacketTimestamp;else{let t=await this.padWithSilence(r,r.info.expectedNextPcmPacketTimestamp,e);a=r.info.expectedNextPcmPacketTimestamp+t}}r.info.expectedNextPcmPacketTimestamp=a+o}let s=this.createSampleForTrack(r,i,a,o,t.type);await this.registerSample(r,s)}finally{r()}}async padWithSilence(e,t,n){let r=Uy(n,e.timescale);if(n=r/e.timescale,r>0){let{sampleSize:i,silentValue:a}=Xh(e.info.decoderConfig.codec),o=r*e.info.numberOfChannels,s=new Uint8Array(i*o).fill(a),c=this.createSampleForTrack(e,new Uint8Array(s.buffer),t,n,`key`);await this.registerSample(e,c)}return n}async addSubtitleCue(e,t,n){let r=await this.mutex.acquire();try{let r=this.getSubtitleTrackData(e,n);this.validateTimestamp(r.track,t.timestamp,!0),e.source._codec===`webvtt`&&(r.cueQueue.push(t),await this.processWebVTTCues(r,t.timestamp))}finally{r()}}async processWebVTTCues(e,t){for(;e.cueQueue.length>0;){e.lastCueEndTimestamp??=Math.min(0,e.cueQueue[0].timestamp);let n=/* @__PURE__ */ new Set([]);for(let r of e.cueQueue)z(r.timestamp<=t),z(e.lastCueEndTimestamp<=r.timestamp+r.duration),n.add(Math.max(r.timestamp,e.lastCueEndTimestamp)),n.add(r.timestamp+r.duration);let r=[...n].sort((e,t)=>e-t),i=r[0],a=r[1]??i;if(t<a)break;if(e.lastCueEndTimestamp<i){this.auxWriter.seek(0);let t=my();this.auxBoxWriter.writeBox(t);let n=this.auxTarget._getSlice(0,this.auxWriter.getPos()),r=this.createSampleForTrack(e,n,e.lastCueEndTimestamp,i-e.lastCueEndTimestamp,`key`);await this.registerSample(e,r),e.lastCueEndTimestamp=i}this.auxWriter.seek(0);for(let t=0;t<e.cueQueue.length;t++){let n=e.cueQueue[t];if(n.timestamp>=a)break;U_.lastIndex=0;let r=U_.test(n.text),o=n.timestamp+n.duration,s=e.cueToSourceId.get(n);if(s===void 0&&a<o&&(s=e.nextSourceId++,e.cueToSourceId.set(n,s)),n.notes){let e=gy(n.notes);this.auxBoxWriter.writeBox(e)}let c=hy(n.text,r?i:null,n.identifier??null,n.settings??null,s??null);this.auxBoxWriter.writeBox(c),o===a&&e.cueQueue.splice(t--,1)}let o=this.auxTarget._getSlice(0,this.auxWriter.getPos()),s=this.createSampleForTrack(e,o,i,a-i,`key`);await this.registerSample(e,s),e.lastCueEndTimestamp=a}}createSampleForTrack(e,t,n,r,i){return{timestamp:n,decodeTimestamp:n,duration:r,data:t,size:t.byteLength,type:i,timescaleUnitsToNextSample:Uy(r,e.timescale)}}processTimestamps(e,t){if(e.timestampProcessingQueue.length===0)return;if(e.type===`audio`&&e.info.requiresPcmTransformation){z(!this.isFragmented),e.startTimestampOffset??=e.timestampProcessingQueue[0].timestamp;let t=0;for(let n=0;n<e.timestampProcessingQueue.length;n++){let r=e.timestampProcessingQueue[n],i=Uy(r.duration,e.timescale);t+=i}if(e.timeToSampleTable.length===0)e.timeToSampleTable.push({sampleCount:t,sampleDelta:1});else{let n=np(e.timeToSampleTable);n.sampleCount+=t}e.timestampProcessingQueue.length=0;return}let n=e.timestampProcessingQueue.map(e=>e.timestamp).sort((e,t)=>e-t);this.isFragmented?e.startTimestampOffset??=Math.min(n[0],0):e.startTimestampOffset??=n[0];for(let t=0;t<e.timestampProcessingQueue.length;t++){let r=e.timestampProcessingQueue[t];r.decodeTimestamp=n[t];let i=Uy(r.timestamp-r.decodeTimestamp,e.timescale),a=Uy(r.duration,e.timescale);if(e.lastTimescaleUnits!==null){z(e.lastSample);let t=Uy(r.decodeTimestamp,e.timescale,!1),n=Math.round(t-e.lastTimescaleUnits);if(z(n>=0),e.lastTimescaleUnits+=n,e.lastSample.timescaleUnitsToNextSample=n,!this.isFragmented){let t=np(e.timeToSampleTable);if(z(t),t.sampleCount===1){t.sampleDelta=n;let r=e.timeToSampleTable[e.timeToSampleTable.length-2];r&&r.sampleDelta===n&&(r.sampleCount++,e.timeToSampleTable.pop(),t=r)}else t.sampleDelta!==n&&(t.sampleCount--,e.timeToSampleTable.push(t={sampleCount:1,sampleDelta:n}));t.sampleDelta===a?t.sampleCount++:e.timeToSampleTable.push({sampleCount:1,sampleDelta:a});let r=np(e.compositionTimeOffsetTable);z(r),r.sampleCompositionTimeOffset===i?r.sampleCount++:e.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:i})}}else e.lastTimescaleUnits=Uy(r.decodeTimestamp,e.timescale,!1),this.isFragmented||(e.timeToSampleTable.push({sampleCount:1,sampleDelta:a}),e.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:i}));e.lastSample=r}if(e.timestampProcessingQueue.length=0,z(e.lastSample),z(e.lastTimescaleUnits!==null),t!==void 0&&e.lastSample.timescaleUnitsToNextSample===0){z(t.type===`key`);let n=Uy(t.timestamp,e.timescale,!1),r=Math.round(n-e.lastTimescaleUnits);e.lastSample.timescaleUnitsToNextSample=r}}async registerSample(e,t){t.type===`key`&&this.processTimestamps(e,t),e.timestampProcessingQueue.push(t),this.isFragmented?(e.sampleQueue.push(t),await this.interleaveSamples()):this.fastStart===`reserve`?await this.registerSampleFastStartReserve(e,t):await this.addSampleToTrack(e,t)}async addSampleToTrack(e,t){if(!this.isFragmented&&(e.samples.push(t),this.fastStart===`reserve`)){let t=e.track.metadata.maximumPacketCount;if(z(t!==void 0),e.samples.length>t)throw Error(`Track #${e.track.id} has already reached the maximum packet count (${t}). Either add less packets or increase the maximum packet count.`)}let n=!1;if(!e.currentChunk)n=!0;else{e.currentChunk.startTimestamp=Math.min(e.currentChunk.startTimestamp,t.timestamp);let r=t.timestamp-e.currentChunk.startTimestamp;if(this.isFragmented){let i=this.trackDatas.every(n=>{if(e===n)return t.type===`key`;let r=n.sampleQueue[0];return r?r.type===`key`:n.closed});r>=this.minimumFragmentDuration&&i&&t.timestamp>this.maxWrittenTimestamp&&(n=!0,await this.finalizeFragment())}else n=r>=.5}n&&(e.currentChunk&&await this.finalizeCurrentChunk(e),e.currentChunk={startTimestamp:t.timestamp,samples:[],offset:null,moofOffset:null,trafIndex:null}),z(e.currentChunk),e.currentChunk.samples.push(t),this.isFragmented&&(this.maxWrittenTimestamp=Math.max(this.maxWrittenTimestamp,t.timestamp),this.maxWrittenEndTimestamp=Math.max(this.maxWrittenEndTimestamp,t.timestamp+t.duration),this.minWrittenTimestamp=Math.min(this.minWrittenTimestamp,t.timestamp))}async finalizeCurrentChunk(e){if(z(!this.isFragmented),z(this.writer),!e.currentChunk)return;e.finalizedChunks.push(e.currentChunk),this.finalizedChunks.push(e.currentChunk);let t=e.currentChunk.samples.length;if(e.type===`audio`&&e.info.requiresPcmTransformation&&(t=e.currentChunk.samples.reduce((t,n)=>t+Uy(n.duration,e.timescale),0)),(e.compactlyCodedChunkTable.length===0||np(e.compactlyCodedChunkTable).samplesPerChunk!==t)&&e.compactlyCodedChunkTable.push({firstChunk:e.finalizedChunks.length,samplesPerChunk:t}),this.fastStart===`in-memory`){e.currentChunk.offset=0;return}e.currentChunk.offset=this.writer.getPos();for(let t of e.currentChunk.samples)z(t.data),this.writer.write(t.data),t.data=null;await this.writer.flush()}async interleaveSamples(e=!1){if(z(this.isFragmented),e||this.allTracksAreKnown())outer:for(;;){let t=null,n=1/0;for(let r of this.trackDatas){if(!e&&r.sampleQueue.length===0&&!r.closed)break outer;r.sampleQueue.length>0&&r.sampleQueue[0].timestamp<n&&(t=r,n=r.sampleQueue[0].timestamp)}if(!t)break;let r=t.sampleQueue.shift();await this.addSampleToTrack(t,r)}}async finalizeFragment(e=!this.isCmaf){if(z(this.isFragmented),!this.wroteFragmentedHeader){this.wroteFragmentedHeader=!0;let e=this.initBoxWriter??this.boxWriter;z(e),this.formatOptions.onMoov&&e.writer.startTrackingWrites(),this.ensureOneEnabledTrack();let t=dv(this);if(e.writeBox(t),this.formatOptions.onMoov){let{data:t,start:n}=e.writer.stopTrackingWrites();this.formatOptions.onMoov(t,n)}if(this.isCmaf){z(this.initWriter),await this.initWriter.flush(),await this.initWriter.finalize(),this.writer=await this.output._getRootWriter(!0),this.boxWriter=new G_(this.writer);let e=this.boxWriter.measureBox(sv()),t=this.boxWriter.measureBox(cv(this,0));this.segmentHeaderSize=e+t,this.writer.seek(this.segmentHeaderSize)}}z(this.writer),z(this.boxWriter);let t=this.trackDatas.filter(e=>e.currentChunk);if(t.length===0){e&&await this.writer.flush();return}let n=this.nextFragmentNumber++,r=iy(n,t),i=this.writer.getPos(),a=i+this.boxWriter.measureBox(r),o=a+8,s=1/0;for(let e=0;e<t.length;e++){let n=t[e];z(n.currentChunk),z(n.startTimestampOffset!==null),n.currentChunk.offset=o,n.currentChunk.moofOffset=i,n.currentChunk.trafIndex=e,n.currentChunk.startTimestamp-=n.startTimestampOffset;for(let e of n.currentChunk.samples)o+=e.size,e.timestamp-=n.startTimestampOffset,e.decodeTimestamp-=n.startTimestampOffset;s=Math.min(s,n.currentChunk.startTimestamp)}let c=o-a,l=c>=2**32;if(l)for(let e of t)e.currentChunk.offset+=8;this.formatOptions.onMoof&&this.writer.startTrackingWrites();let u=iy(n,t);if(this.boxWriter.writeBox(u),this.formatOptions.onMoof){let{data:e,start:t}=this.writer.stopTrackingWrites();this.formatOptions.onMoof(e,t,s)}z(this.writer.getPos()===a),this.formatOptions.onMdat&&this.writer.startTrackingWrites();let d=lv(l);d.size=c,this.boxWriter.writeBox(d),this.writer.seek(a+(l?16:8));for(let e of t)for(let t of e.currentChunk.samples)this.writer.write(t.data),t.data=null;if(this.formatOptions.onMdat){let{data:e,start:t}=this.writer.stopTrackingWrites();this.formatOptions.onMdat(e,t)}for(let e of t)e.finalizedChunks.push(e.currentChunk),this.finalizedChunks.push(e.currentChunk),e.currentChunk=null;e&&await this.writer.flush()}async registerSampleFastStartReserve(e,t){this.allTracksAreKnown()?(this.mdat||await this.createFastStartReserveMdat(),await this.addSampleToTrack(e,t)):e.sampleQueue.push(t)}async createFastStartReserveMdat(){z(this.writer),z(this.boxWriter),this.ensureOneEnabledTrack();let e=dv(this),t=this.boxWriter.measureBox(e)+this.computeSampleTableSizeUpperBound()+4096;z(this.ftypSize!==null),this.writer.seek(this.ftypSize+t),this.formatOptions.onMdat&&this.writer.startTrackingWrites(),this.mdat=lv(!0),this.boxWriter.writeBox(this.mdat);for(let e of this.trackDatas){for(let t of e.sampleQueue)await this.addSampleToTrack(e,t);e.sampleQueue.length=0}}computeSampleTableSizeUpperBound(){z(this.fastStart===`reserve`);let e=0;for(let t of this.trackDatas){let n=t.track.metadata.maximumPacketCount;z(n!==void 0),e+=8*Math.ceil(2/3*n),e+=4*n,e+=8*Math.ceil(2/3*n),e+=12*Math.ceil(2/3*n),e+=4*n,e+=8*n}return e}async onTrackClose(e){let t=await this.mutex.acquire(),n=this.trackDatas.find(t=>t.track===e);n&&(n.closed=!0,n.type===`subtitle`&&e.source._codec===`webvtt`&&await this.processWebVTTCues(n,1/0),this.processTimestamps(n)),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),this.isFragmented&&await this.interleaveSamples(),t()}ensureOneEnabledTrack(){for(let e of[`video`,`audio`,`subtitle`]){let t=this.trackDatas.filter(t=>t.type===e);if(t.length!==0&&!t.some(e=>e.track.metadata.disposition?.default!==!1)){let e=t[0];e.track.metadata.disposition={...e.track.metadata.disposition,default:!0}}}}async forceFragmentFinalization(){z(this.isFragmented);let e=await this.mutex.acquire();try{for(let e of this.trackDatas)e.type===`subtitle`&&e.track.source._codec===`webvtt`&&await this.processWebVTTCues(e,1/0),this.processTimestamps(e);await this.interleaveSamples(!0),await this.finalizeFragment()}finally{e()}}async finalize(){let e=await this.mutex.acquire();this.allTracksKnown.resolve(),this.ensureOneEnabledTrack(),!this.mdat&&this.fastStart===`reserve`&&await this.createFastStartReserveMdat();for(let e of this.trackDatas)e.closed=!0,e.type===`subtitle`&&e.track.source._codec===`webvtt`&&await this.processWebVTTCues(e,1/0),this.processTimestamps(e);if(this.isFragmented)await this.interleaveSamples(!0),await this.finalizeFragment(!1);else for(let e of this.trackDatas){await this.finalizeCurrentChunk(e);let t=Wy(e);if(t>0){let n=0;for(let t of e.samples)n+=t.size;e.avgBitrate=Math.round(8*n/t)}else e.avgBitrate=0;let n=0,r=0,i=0;for(let t=0;t<e.samples.length;t++){let a=e.samples[t];for(r+=a.size;a.decodeTimestamp-e.samples[n].decodeTimestamp>=1;)r-=e.samples[n].size,n++;i=Math.max(i,r)}if(e.maxBitrate=8*i,e.startTimestampOffset!==null)for(let t=0;t<e.samples.length;t++){let n=e.samples[t];n.timestamp-=e.startTimestampOffset,n.decodeTimestamp-=e.startTimestampOffset}}if(z(this.writer),z(this.boxWriter),this.fastStart===`in-memory`){this.mdat=lv(!1);let e;for(let t=0;t<2;t++){let t=dv(this),n=this.boxWriter.measureBox(t);e=this.boxWriter.measureBox(this.mdat);let r=this.writer.getPos()+n+e;for(let t of this.finalizedChunks){t.offset=r;for(let{data:n}of t.samples)z(n),r+=n.byteLength,e+=n.byteLength}if(r<2**32)break;e>=2**32&&(this.mdat.largeSize=!0)}this.formatOptions.onMoov&&this.writer.startTrackingWrites();let t=dv(this);if(this.boxWriter.writeBox(t),this.formatOptions.onMoov){let{data:e,start:t}=this.writer.stopTrackingWrites();this.formatOptions.onMoov(e,t)}this.formatOptions.onMdat&&this.writer.startTrackingWrites(),this.mdat.size=e,this.boxWriter.writeBox(this.mdat);for(let e of this.finalizedChunks)for(let t of e.samples)z(t.data),this.writer.write(t.data),t.data=null;if(this.formatOptions.onMdat){let{data:e,start:t}=this.writer.stopTrackingWrites();this.formatOptions.onMdat(e,t)}}else if(this.isFragmented){if(this.isCmaf){let e=this.segmentHeaderSize===null?0:this.writer.getPos()-this.segmentHeaderSize;this.writer.seek(0),this.boxWriter.writeBox(sv()),this.boxWriter.writeBox(cv(this,e))}else{let e=this.writer.getPos(),t=dy(this.trackDatas);this.boxWriter.writeBox(t);let n=this.writer.getPos()-e;this.writer.seek(this.writer.getPos()-4),this.boxWriter.writeU32(n)}}else{z(this.mdat);let e=this.boxWriter.offsets.get(this.mdat);z(e!==void 0);let t=this.writer.getPos()-e;if(this.mdat.size=t,this.mdat.largeSize=t>=2**32,this.boxWriter.patchBox(this.mdat),this.formatOptions.onMdat){let{data:e,start:t}=this.writer.stopTrackingWrites();this.formatOptions.onMdat(e,t)}let n=dv(this);if(this.fastStart===`reserve`){z(this.ftypSize!==null),this.writer.seek(this.ftypSize),this.formatOptions.onMoov&&this.writer.startTrackingWrites(),this.boxWriter.writeBox(n);let e=this.boxWriter.offsets.get(this.mdat)-this.writer.getPos();this.boxWriter.writeBox(uv(e))}else this.formatOptions.onMoov&&this.writer.startTrackingWrites(),this.boxWriter.writeBox(n);if(this.formatOptions.onMoov){let{data:e,start:t}=this.writer.stopTrackingWrites();this.formatOptions.onMoov(e,t)}}e()}},Ky=class{constructor(){this._connectedTrack=null,this._closingPromise=null,this._closed=!1,this._nominalBitrate=null}_ensureValidAdd(){if(!this._connectedTrack)throw Error(`Source is not connected to an output track.`);if(this._connectedTrack.output.state===`canceled`)throw Error(`Output has been canceled.`);if(this._connectedTrack.output.state===`finalizing`||this._connectedTrack.output.state===`finalized`)throw Error(`Output has been finalized.`);if(this._connectedTrack.output.state===`pending`)throw Error(`Output has not started.`);if(this._closed)throw Error(`Source is closed.`)}async _start(){}async _flushAndClose(e){}close(){if(this._closingPromise)return;let e=this._connectedTrack;if(!e)throw Error(`Cannot call close without connecting the source to an output track.`);if(e.output.state===`pending`)throw Error(`Cannot call close before output has been started.`);this._closingPromise=(async()=>{await this._flushAndClose(!1),this._closed=!0,e.output.state!==`finalizing`&&e.output.state!==`finalized`&&e.output._muxer.onTrackClose(e)})()}async _flushOrWaitForOngoingClose(e){return this._closingPromise??=(async()=>{await this._flushAndClose(e),this._closed=!0})()}},qy=class extends Ky{constructor(e){if(super(),this._connectedTrack=null,!Nh.includes(e))throw TypeError(`Invalid video codec '${e}'. Must be one of: ${Nh.join(`, `)}.`);this._codec=e}},Jy=class extends Ky{constructor(e){if(super(),this._connectedTrack=null,!Ih.includes(e))throw TypeError(`Invalid audio codec '${e}'. Must be one of: ${Ih.join(`, `)}.`);this._codec=e}},Yy=class extends Jy{constructor(e){super(e)}add(e,t){if(!(e instanceof lg))throw TypeError(`packet must be an EncodedPacket.`);if(e.isMetadataOnly)throw TypeError(`Metadata-only packets cannot be added.`);if(t!==void 0&&(!t||typeof t!=`object`))throw TypeError(`meta, when provided, must be an object.`);return this._ensureValidAdd(),this._connectedTrack.output._muxer.addEncodedAudioPacket(this._connectedTrack,e,t)}},Xy=class extends Ky{constructor(e){if(super(),this._connectedTrack=null,!Lh.includes(e))throw TypeError(`Invalid subtitle codec '${e}'. Must be one of: ${Lh.join(`, `)}.`);this._codec=e}},Zy=class{get supportsVideoRotationMetadata(){return this.supportsVideoTransformationMetadata}getSupportedVideoCodecs(){return this.getSupportedCodecs().filter(e=>Nh.includes(e))}getSupportedAudioCodecs(){return this.getSupportedCodecs().filter(e=>Ih.includes(e))}getSupportedSubtitleCodecs(){return this.getSupportedCodecs().filter(e=>Lh.includes(e))}_codecUnsupportedHint(e){return``}_isFragmentedIsobmff(){return!1}},Qy=class extends Zy{constructor(e={}){if(!e||typeof e!=`object`)throw TypeError(`options must be an object.`);if(e.fastStart!==void 0&&![!1,`in-memory`,`reserve`,`fragmented`].includes(e.fastStart))throw TypeError(`options.fastStart, when provided, must be false, 'in-memory', 'reserve', or 'fragmented'.`);if(e.minimumFragmentDuration!==void 0&&(!Qp(e.minimumFragmentDuration)||e.minimumFragmentDuration<0))throw TypeError(`options.minimumFragmentDuration, when provided, must be a non-negative number.`);if(e.onFtyp!==void 0&&typeof e.onFtyp!=`function`)throw TypeError(`options.onFtyp, when provided, must be a function.`);if(e.onMoov!==void 0&&typeof e.onMoov!=`function`)throw TypeError(`options.onMoov, when provided, must be a function.`);if(e.onMdat!==void 0&&typeof e.onMdat!=`function`)throw TypeError(`options.onMdat, when provided, must be a function.`);if(e.onMoof!==void 0&&typeof e.onMoof!=`function`)throw TypeError(`options.onMoof, when provided, must be a function.`);if(e.metadataFormat!==void 0&&![`mdir`,`mdta`,`udta`,`auto`].includes(e.metadataFormat))throw TypeError(`options.metadataFormat, when provided, must be either 'auto', 'mdir', 'mdta', or 'udta'.`);super(),this._options=e}getSupportedTrackCounts(){let e=2**32-1;return{video:{min:0,max:e},audio:{min:0,max:e},subtitle:{min:0,max:e},total:{min:0,max:e}}}get supportsVideoTransformationMetadata(){return!0}get supportsTimestampedMediaData(){return!0}get negativeTimestampSupport(){return`full`}_createMuxer(e){return new Gy(e,this)}_isFragmentedIsobmff(){return this._options.fastStart===`fragmented`}},$y=class extends Qy{constructor(e){super(e)}get _name(){return`MP4`}get fileExtension(){return`.mp4`}get mimeType(){return`video/mp4`}getSupportedCodecs(){return[...Nh,...Fh,`pcm-s16`,`pcm-s16be`,`pcm-s24`,`pcm-s24be`,`pcm-s32`,`pcm-s32be`,`pcm-f32`,`pcm-f32be`,`pcm-f64`,`pcm-f64be`,...Lh]}_codecUnsupportedHint(e){return new tb().getSupportedCodecs().includes(e)?` Switching to MOV will grant support for this codec.`:``}},eb=class extends Qy{constructor(e){super(e)}get _name(){return`CMAF`}get fileExtension(){return`.m4s`}get mimeType(){return`video/mp4`}getSupportedCodecs(){return[...Nh,...Fh,`pcm-s16`,`pcm-s16be`,`pcm-s24`,`pcm-s24be`,`pcm-s32`,`pcm-s32be`,`pcm-f32`,`pcm-f32be`,`pcm-f64`,`pcm-f64be`,...Lh]}},tb=class extends Qy{constructor(e){super(e)}get _name(){return`MOV`}get fileExtension(){return`.mov`}get mimeType(){return`video/quicktime`}getSupportedCodecs(){return[...Nh,...Ih]}_codecUnsupportedHint(e){return new $y().getSupportedCodecs().includes(e)?` Switching to MP4 will grant support for this codec.`:``}},nb=[`video`,`audio`,`subtitle`],rb=class e{constructor(e,t,n,r,i){this.id=e,this.output=t,this.type=n,this.source=r,this.metadata=i}isVideoTrack(){return this.type===`video`}isAudioTrack(){return this.type===`audio`}isSubtitleTrack(){return this.type===`subtitle`}canBePairedWith(t){if(!(t instanceof e))throw TypeError(`other must be an OutputTrack.`);if(this===t)return!1;let n=nm(this.metadata.group),r=nm(t.metadata.group);for(let e of n)if(this.type!==t.type&&r.some(t=>e===t)||r.some(t=>e._pairedGroups.has(t)))return!0;return!1}},ib=class extends rb{constructor(e,t,n,r){super(e,t,`video`,n,r)}},ab=class extends rb{constructor(e,t,n,r){super(e,t,`audio`,n,r)}},ob=class extends rb{constructor(e,t,n,r){super(e,t,`subtitle`,n,r)}},sb=class e{constructor(){this._pairedGroups=/* @__PURE__ */ new Set}pairWith(t){if(!(t instanceof e))throw TypeError(`other must be an OutputTrackGroup.`);if(this===t)throw TypeError(`Cannot pair a group with itself.`);this._pairedGroups.add(t),t._pairedGroups.add(this)}},cb=e=>{if(!e||typeof e!=`object`)throw TypeError(`metadata must be an object.`);if(e.languageCode!==void 0&&!Hp(e.languageCode))throw TypeError(`metadata.languageCode, when provided, must be a three-letter, ISO 639-2/T language code.`);if(e.name!==void 0&&typeof e.name!=`string`)throw TypeError(`metadata.name, when provided, must be a string.`);if(e.disposition!==void 0&&dm(e.disposition),e.maximumPacketCount!==void 0&&(!Number.isInteger(e.maximumPacketCount)||e.maximumPacketCount<0))throw TypeError(`metadata.maximumPacketCount, when provided, must be a non-negative integer.`);if(e.bitrate!==void 0&&(!Number.isFinite(e.bitrate)||e.bitrate<0))throw TypeError(`metadata.bitrate, when provided, must be a non-negative number.`);if(e.averageBitrate!==void 0&&(!Number.isFinite(e.averageBitrate)||e.averageBitrate<0))throw TypeError(`metadata.averageBitrate, when provided, must be a non-negative number.`);if(e.group!==void 0&&!(e.group instanceof sb)&&(!Array.isArray(e.group)||e.group.some(e=>!(e instanceof sb))))throw TypeError(`metadata.group, when provided, must be an OutputTrackGroup instance or an array of OutputTrackGroup instances.`)},lb=class extends rm{get target(){let e=`Output.target cannot be used when using PathedTarget with an async callback. Use the 'target' event instead.`;if(this._rootTargetPromise)throw TypeError(e);let t=this._getRootTarget();if(Jp(t))throw TypeError(e);return t}constructor(e){if(super(),this.state=`pending`,this.defaultTrackGroup=new sb,this.tracks=[],this._onFinalize=null,this._unfinalizedTargets=/* @__PURE__ */ new Set,this._rootWriterPromise=null,this._startPromise=null,this._cancelPromise=null,this._finalizePromise=null,this._mutex=new Cp,this._metadataTags={},this._rootTarget=null,this._rootTargetPromise=null,this._firstMediaStreamTimestamp=null,!e||typeof e!=`object`)throw TypeError(`options must be an object.`);if(!(e.format instanceof Zy))throw TypeError(`options.format must be an OutputFormat.`);if(!(e.target instanceof Ny||e.target instanceof zy))throw TypeError(`options.target must be a Target or a PathedTarget.`);if(e.target instanceof Ny&&this._rememberTarget(e.target),e.initTarget!==void 0&&!(e.initTarget instanceof Ny)&&typeof e.initTarget!=`function`)throw Error(`options.initTarget, when provided, must be a Target or a function that returns or resolves to a Target.`);if(e.onFinalize!==void 0&&typeof e.onFinalize!=`function`)throw TypeError(`options.onFinalize, when provided, must be a function.`);this.format=e.format,this._target=e.target,this._onFinalize=e.onFinalize??null,this._initTarget=e.initTarget??null,this._initTarget instanceof Ny&&this._rememberTarget(this._initTarget),this._muxer=e.format._createMuxer(this)}_getTargetValidated(e){z(this._target instanceof zy);let t=this._target.getTarget(e),n=e=>{if(!(e instanceof Ny))throw TypeError(`getTarget must return a Target.`);return e};return Jp(t)?t.then(n):n(t)}async _getTarget(e){z(this._target instanceof zy);let t=await this._getTargetValidated(e);return this._emit(`target`,{target:t,request:e,isRoot:e.isRoot}),this.state===`canceled`?await t._close():this._rememberTarget(t),t}_rememberTarget(e){this._unfinalizedTargets.add(e),e.on(`finalized`,()=>this._unfinalizedTargets.delete(e),{once:!0})}async _getInitTarget(){if(z(this._initTarget!==null),this._initTarget instanceof Ny)return this._initTarget;let e=await this._initTarget();return this.state===`canceled`?await e._close():this._rememberTarget(e),e}_hasInitTarget(){return this._initTarget!==null}_getRootTarget(){if(this._rootTarget)return this._rootTarget;if(this._rootTargetPromise)return this._rootTargetPromise;if(this._target instanceof Ny)return this._emit(`target`,{target:this._target,request:null,isRoot:!0}),this._rootTarget=this._target,this._target;let e={path:this._target.rootPath,isRoot:!0,mimeType:this.format.mimeType},t=this._getTargetValidated(e),n=t=>(this.state===`canceled`?t._close():this._rememberTarget(t),this._emit(`target`,{target:t,request:e,isRoot:!0}),this._rootTarget=t,t);return Jp(t)?this._rootTargetPromise=t.then(n):n(t)}_getRootWriter(e){return this._rootWriterPromise??=(async()=>{let t=await this._getRootTarget(),n=new My(t,typeof e==`boolean`?e:e(t));return n.start(),n})()}addVideoTrack(e,t={}){if(!(e instanceof qy))throw TypeError(`source must be a VideoSource.`);if(cb(t),t.rotation!==void 0&&![0,90,180,270].includes(t.rotation))throw TypeError(`Invalid video rotation: ${t.rotation}. Has to be 0, 90, 180 or 270.`);if(t.flip!==void 0&&typeof t.flip!=`boolean`)throw TypeError(`metadata.flip, when provided, must be a boolean.`);if(t.transformationMatrix!==void 0&&(!Array.isArray(t.transformationMatrix)||t.transformationMatrix.length!==9||!t.transformationMatrix.every(e=>Number.isFinite(e))))throw TypeError(`metadata.transformationMatrix, when provided, must be an array of 9 finite numbers.`);if(t.frameRate!==void 0&&(!Number.isFinite(t.frameRate)||t.frameRate<=0))throw TypeError(`Invalid video frame rate: ${t.frameRate}. Must be a positive number.`);if(t.decoderConfig!==void 0&&rg({decoderConfig:t.decoderConfig},e._codec),t.primingPacket!==void 0){if(!(t.primingPacket instanceof lg))throw TypeError(`metadata.primingPacket, when provided, must be an EncodedPacket.`);if(t.decoderConfig===void 0)throw TypeError(`metadata.primingPacket can only be provided alongside metadata.decoderConfig.`)}let n={...t};return n.group??=this.defaultTrackGroup,this._addTrack(new ib(this.tracks.length+1,this,e,n))}addAudioTrack(e,t={}){if(!(e instanceof Jy))throw TypeError(`source must be an AudioSource.`);if(cb(t),t.decoderConfig!==void 0&&ag({decoderConfig:t.decoderConfig},e._codec),t.primingPacket!==void 0){if(!(t.primingPacket instanceof lg))throw TypeError(`metadata.primingPacket, when provided, must be an EncodedPacket.`);if(t.decoderConfig===void 0)throw TypeError(`metadata.primingPacket can only be provided alongside metadata.decoderConfig.`)}let n={...t};return n.group??=this.defaultTrackGroup,this._addTrack(new ab(this.tracks.length+1,this,e,n))}addSubtitleTrack(e,t={}){if(!(e instanceof Xy))throw TypeError(`source must be a SubtitleSource.`);cb(t);let n={...t};return n.group??=this.defaultTrackGroup,this._addTrack(new ob(this.tracks.length+1,this,e,n))}setMetadataTags(e){if(lm(e),this.state!==`pending`)throw Error(`Cannot set metadata tags after output has been started or canceled.`);this._metadataTags=e}_addTrack(e){if(this.state!==`pending`)throw Error(`Cannot add track after output has been started or canceled.`);if(e.source._connectedTrack)throw Error(`Source is already used for a track.`);let t=this.format.getSupportedTrackCounts(),n=this.tracks.reduce((t,n)=>t+ +(n.type===e.type),0),r=t[e.type].max;if(n===r)throw Error(r===0?`${this.format._name} does not support ${e.type} tracks.`:`${this.format._name} does not support more than ${r} ${e.type} track${r===1?``:`s`}.`);let i=t.total.max;if(this.tracks.length===i)throw Error(`${this.format._name} does not support more than ${i} tracks${i===1?``:`s`} in total.`);if(e.isVideoTrack()){let t=this.format.getSupportedVideoCodecs();if(t.length===0)throw Error(`${this.format._name} does not support video tracks.`+this.format._codecUnsupportedHint(e.source._codec));if(!t.includes(e.source._codec))throw Error(`Codec '${e.source._codec}' cannot be contained within ${this.format._name}. Supported video codecs are: ${t.map(e=>`'${e}'`).join(`, `)}.`+this.format._codecUnsupportedHint(e.source._codec))}else if(e.isAudioTrack()){let t=this.format.getSupportedAudioCodecs();if(t.length===0)throw Error(`${this.format._name} does not support audio tracks.`+this.format._codecUnsupportedHint(e.source._codec));if(!t.includes(e.source._codec))throw Error(`Codec '${e.source._codec}' cannot be contained within ${this.format._name}. Supported audio codecs are: ${t.map(e=>`'${e}'`).join(`, `)}.`+this.format._codecUnsupportedHint(e.source._codec))}else if(e.isSubtitleTrack()){let t=this.format.getSupportedSubtitleCodecs();if(t.length===0)throw Error(`${this.format._name} does not support subtitle tracks.`+this.format._codecUnsupportedHint(e.source._codec));if(!t.includes(e.source._codec))throw Error(`Codec '${e.source._codec}' cannot be contained within ${this.format._name}. Supported subtitle codecs are: ${t.map(e=>`'${e}'`).join(`, `)}.`+this.format._codecUnsupportedHint(e.source._codec))}return this.tracks.push(e),e.source._connectedTrack=e,e}hasEnoughTracks(){let e=this.format.getSupportedTrackCounts();for(let t of nb)if(this.tracks.reduce((e,n)=>e+ +(n.type===t),0)<e[t].min)return!1;let t=e.total.min;return!(this.tracks.length<t)}async start(){let e=this.format.getSupportedTrackCounts();for(let t of nb){let n=this.tracks.reduce((e,n)=>e+ +(n.type===t),0),r=e[t].min;if(n<r)throw Error(r===e[t].max?`${this.format._name} requires exactly ${r} ${t} track${r===1?``:`s`}.`:`${this.format._name} requires at least ${r} ${t} track${r===1?``:`s`}.`)}let t=e.total.min;if(this.tracks.length<t)throw Error(t===e.total.max?`${this.format._name} requires exactly ${t} track${t===1?``:`s`}.`:`${this.format._name} requires at least ${t} track${t===1?``:`s`}.`);if(this.state===`canceled`)throw Error(`Output has been canceled.`);return this._startPromise?(om._warn(`Output has already been started.`),this._startPromise):this._startPromise=(async()=>{this.state=`started`;let e=this._mutex.acquire();try{await this._muxer.start();let e=this.tracks.map(e=>e.source._start());await Promise.all(e)}finally{(await e)()}})()}getMimeType(){return this._muxer.getMimeType()}async cancel(){if(this.state===`canceled`)return this._cancelPromise??void 0;if(this.state===`finalizing`||this.state===`finalized`){this.state===`finalized`&&om._warn(`Output has already been finalized.`);return}return this._cancelPromise=(async()=>{this.state=`canceled`;let e=await this._mutex.acquire();try{let e=this.tracks.map(e=>e.source._flushOrWaitForOngoingClose(!0));await Promise.all(e),await Promise.all([...this._unfinalizedTargets].map(e=>e._close())),this._unfinalizedTargets.clear()}finally{e()}})()}async finalize(){if(this.state===`pending`)throw Error(`Cannot finalize before starting.`);if(this.state===`canceled`)throw Error(`Cannot finalize after canceling.`);return this._finalizePromise?(om._warn(`Output has already been finalized.`),this._finalizePromise):this._finalizePromise=(async()=>{this.state=`finalizing`;let e=await this._mutex.acquire();try{let e=this.tracks.map(e=>e.source._flushOrWaitForOngoingClose(!1));if(await Promise.all(e),await this._muxer.finalize(),this._rootWriterPromise){let e=await this._rootWriterPromise;e.finalized||(await e.flush(),await e.finalize())}this._onFinalize&&await this._onFinalize(),this.state=`finalized`}catch(e){throw this.state=`canceled`,e}finally{await Promise.all([...this._unfinalizedTargets].map(e=>e._close().catch(()=>{}))),this._unfinalizedTargets.clear(),e()}})()}};function ub(e){let t=ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):new Uint8Array(e);return Uint8Array.from(t)}function db(e,t){return{codec:e.codec,codedWidth:e.codedWidth??t.codedWidth,codedHeight:e.codedHeight??t.codedHeight,description:e.description===void 0?void 0:ub(e.description),colour:t.colour}}function fb(e){return{codec:e.codec,sampleRate:e.sampleRate,numberOfChannels:e.numberOfChannels,description:e.description===void 0?void 0:ub(e.description)}}function pb(e){return{primaries:el(Zc,e?.primaries),transfer:el(Qc,e?.transfer),matrix:el($c,e?.matrix),range:mb(e?.fullRange)}}function mb(e){return e===!0?`full`:e===!1?`limited`:`unspecified`}var hb=[a_,o_],gb=class{async read(e){let t=new D_({formats:hb,source:new $g(e)});try{let[e,n]=await Promise.all([t.getVideoTracks(),t.getAudioTracks()]);return{video:await Promise.all(e.map((e,t)=>_b(e,t))),audio:(await Promise.all(n.map(e=>yb(e)))).flat()}}catch(e){throw bb(e)}finally{t.dispose()}}};async function _b(e,t){let[n,r,i]=await Promise.all([vb(e),e.getCodedWidth(),e.getCodedHeight()]);if(n===null)throw new j(`codec-unsupported`,`video track ${t} has no decoder configuration in its sample entry`);let a={trackIndex:t,codedWidth:r,codedHeight:i,codec:n.codec,colour:pb(n.colorSpace)};return{trackId:e.id,description:a,configuration:db(n,a)}}async function vb(e){try{return await e.getDecoderConfig()}catch{return null}}async function yb(e){let t=await e.getDecoderConfig();return t===null?[]:[{trackId:e.id,configuration:fb(t)}]}function bb(e){return re(e)||e instanceof j?e:new j(`unsupported-container`,`the movie box is not a readable movie`,{cause:e})}var xb=class{capacity;queue=[];roomWaiters=[];takeWaiter;isClosedNow=!1;failure;constructor(e){this.capacity=e}get isClosed(){return this.isClosedNow}push(e){this.isClosedNow||(this.queue.push(e),this.wakeTaker())}waitForRoom(){return this.queue.length<this.capacity||this.isClosedNow?Promise.resolve():new Promise(e=>{this.roomWaiters.push(e)})}close(){this.isClosedNow=!0,this.wakeTaker(),this.wakeRoomWaiters()}fail(e){this.failure??=e instanceof Error?e:new j(`decode`,`audio re-packaging failed`,{cause:e}),this.close()}segments(e=Cb){return new Sb({take:()=>this.take(),close:()=>{this.close()},onEnd:e})}async take(){for(;this.queue.length===0&&!this.isClosedNow;)await this.nextPush();let e=this.queue.shift();if(e)return this.wakeRoomWaiters(),e;if(this.failure)throw this.failure}nextPush(){return N(this.takeWaiter===void 0,`a segment channel has one consumer`),new Promise(e=>{this.takeWaiter=e})}wakeTaker(){let e=this.takeWaiter;this.takeWaiter=void 0,e?.()}wakeRoomWaiters(){if(this.queue.length>=this.capacity&&!this.isClosedNow)return;let e=this.roomWaiters;this.roomWaiters=[];for(let t of e)t()}},Sb=class{parts;hasEnded=!1;constructor(e){this.parts=e}async next(){if(this.hasEnded)return yl;try{let e=await this.parts.take();return e===void 0||this.wasEnded()?this.end():{done:!1,value:e}}catch(e){throw this.end(),e}}return(){return this.parts.close(),Promise.resolve(this.end())}[Symbol.asyncIterator](){return this}wasEnded(){return this.hasEnded}end(){return this.hasEnded||this.parts.onEnd(),this.hasEnded=!0,yl}};function Cb(){}var wb=1,Tb=2,Eb=`mp4a.40.`,Db=`aac`,Ob=class{segmentsOf(e,t){let n=kb(t);return{mimeType:`audio/mp4; codecs="${t.codec}"`,duration:e.duration,segmentsFrom:r=>({[Symbol.asyncIterator]:()=>Ab({samples:e,configuration:t,codec:n},r)})}}};function kb(e){if(e.codec.startsWith(Eb))return Db;throw new j(`codec-unsupported`,`audio in ${e.codec} cannot be re-packaged for playback`)}function Ab(e,t){let n=new xb(Tb),r=new lb({format:Fb(n),target:new Ly}),i=new Yy(e.codec);r.addAudioTrack(i);let a=e.samples.samplesFrom(t)[Symbol.asyncIterator](),o=Mb({samples:a,configuration:e.configuration,output:r,source:i,channel:n});return n.segments(()=>{a.return?.(),jb(o,r)})}async function jb(e,t){if(await e,t.state!==`finalized`)try{await t.cancel()}catch{}}async function Mb(e){try{await e.output.start();let t={decoderConfig:Pb(e.configuration)};for(let n=await e.samples.next();n.done!==!0;n=await e.samples.next()){if(await e.channel.waitForRoom(),e.channel.isClosed)return;await e.source.add(Nb(n.value),t),t=void 0}if(e.channel.isClosed)return;await e.output.finalize(),e.channel.close()}catch(t){e.channel.fail(t)}}function Nb(e){return new lg(e.data,`key`,e.timestamp,e.duration)}function Pb(e){return{codec:e.codec,sampleRate:e.sampleRate,numberOfChannels:e.numberOfChannels,...e.description&&{description:e.description}}}function Fb(e){let t=new Ib(e);return new $y({fastStart:`fragmented`,minimumFragmentDuration:wb,onFtyp:e=>{t.begin(e)},onMoov:e=>{t.end(e)},onMoof:e=>{t.begin(e)},onMdat:e=>{t.end(e)}})}var Ib=class{channel;opening;constructor(e){this.channel=e}begin(e){N(this.opening===void 0,`a segment began before the last one ended`),this.opening=new Uint8Array(e)}end(e){let{opening:t}=this;N(t!==void 0,`a segment ended that never began`);let n=new Uint8Array(t.byteLength+e.byteLength);n.set(t),n.set(e,t.byteLength),this.opening=void 0,this.channel.push(n)}};function Lb(e){let t=e.range===`unspecified`?void 0:{fullRange:e.range===`full`},n={...e.primaries!==`unspecified`&&{primaries:e.primaries},...e.transfer!==`unspecified`&&{transfer:e.transfer},...e.matrix!==`unspecified`&&{matrix:e.matrix},...t};return Object.keys(n).length===0?void 0:Rb(n)??t}function Rb(e){try{return new VideoColorSpace(e).toJSON()}catch{return}}var zb=`no-preference`,Bb=class{async isSupported(e){if(typeof VideoDecoder>`u`)throw Hb();try{return(await VideoDecoder.isConfigSupported(this.toWebCodecsConfig(e))).supported===!0}catch{return!1}}create(e,t){try{return Promise.resolve(this.configureDecoder(e,t))}catch(e){return Promise.reject(ne(e,`codec-unsupported`,`the decoder rejected its configuration`))}}configureDecoder(e,t){if(typeof VideoDecoder>`u`)throw Hb();return new Vb(this.toWebCodecsConfig(e),t)}toWebCodecsConfig(e){let{description:t}=e,n=Lb(e.colour);return{codec:e.codec,codedWidth:e.codedWidth,codedHeight:e.codedHeight,...t&&{description:t},...n&&{colorSpace:n},hardwareAcceleration:zb,optimizeForLatency:!1}}},Vb=class{decoder;failure;constructor(e,t){this.decoder=new VideoDecoder({output:e=>{t.onFrame(Wb(e))},error:e=>{this.failure??=new j(`decode`,`video decoder failed: ${e.message}`,{cause:e}),t.onError(this.failure)}});try{this.decoder.configure(e)}catch(e){throw this.decoder.close(),e}}get pendingCount(){return this.decoder.decodeQueueSize}decode(e){if(this.failure)throw this.failure;try{this.decoder.decode(Ub(e))}catch(e){throw new j(`decode`,`the decoder refused a packet: ${ie(e)}`,{cause:e})}}waitForPendingBelow(e){return this.decoder.decodeQueueSize<e?Promise.resolve():new Promise(t=>{let n=()=>{this.decoder.decodeQueueSize>=e&&this.decoder.state===`configured`||(this.decoder.removeEventListener(`dequeue`,n),t())};this.decoder.addEventListener(`dequeue`,n)})}async flush(){if(this.decoder.state!==`configured`)throw this.failure??new j(`decode`,`flush on a closed decoder`);try{await this.decoder.flush()}catch(e){throw this.failure??new j(`decode`,`the decoder could not be flushed`,{cause:e})}}close(){this.decoder.state!==`closed`&&this.decoder.close()}};function Hb(){return new j(`webcodecs-unavailable`,globalThis.isSecureContext?`this browser has no WebCodecs VideoDecoder`:`WebCodecs exists only in secure contexts (HTTPS), and this page is not one`)}function Ub(e){return new EncodedVideoChunk({type:e.isKeyFrame?`key`:`delta`,timestamp:_t(e.timestamp),duration:_t(e.duration),data:e.data})}function Wb(e){return{timestamp:mt(ft(e.timestamp)),handle:e,close:()=>{e.close()}}}function Gb(e){return`url`in e}function Kb(e){return Gb(e)?ia(e.url):e.name}var qb=15e3;function Jb(e={}){let t=e.http??{},n=e.probeTimeoutMs??qb;return{sources:Yb(t),codecReader:new gb,audioPackager:new Ob,decoderPort:new Bb,locatorFor:e=>new Wf(Qb(t,e)),probeDeadline:()=>$b(n)}}function Yb(e){return{open:(t,n)=>Gb(t)?Xb(t,e,n):Zb(t)}}function Xb(e,t,n){let r=new Bf(e.url,Qb(t,e),n);return{source:new pf(r),stream:new df(r)}}function Zb(e){let t=new $d(e.blob);return{source:t,stream:new xl(t)}}function Qb(e,t){let{credentials:n}=t;return n===void 0?e:{...e,requestInit:{...e.requestInit,credentials:n}}}function $b(e){let t=new Ou;return setTimeout(()=>{t.resolve()},e),t}function ex(e,t,n){let r=new AbortController;return n?.addEventListener(`abort`,()=>{r.abort()},{once:!0,signal:r.signal}),new Promise(n=>{for(let i of t)e.addEventListener(i,()=>{r.abort(),n(i)},{once:!0,signal:r.signal})})}var tx=`ManagedMediaSource`,nx=`MediaSource`;function rx(e){return typeof e==`function`&&typeof e.isTypeSupported==`function`}function ix(e){let t=Reflect.get(globalThis,e);return rx(t)?t:void 0}function ax(){return ix(tx)??ix(nx)}function ox(e){return ax()?.isTypeSupported(e)??!1}var sx=1e4;async function cx(e,t){let n=new t,r=lx(e,n),i=URL.createObjectURL(n);e.disableRemotePlayback=!0,e.src=i;let a={mediaSource:n,detach:()=>{e.src===i&&(e.removeAttribute(`src`),e.load()),URL.revokeObjectURL(i)}},o=await r;if(o!==`sourceopen`)throw a.detach(),new j(`decode`,`the audio element could not open its media source (${o})`);return a}async function lx(e,t){let n=new AbortController;try{return await Promise.race([ex(t,[`sourceopen`],n.signal),ex(e,[`error`],n.signal),ux(sx,n.signal)])}finally{n.abort()}}function ux(e,t){return new Promise(n=>{let r=setTimeout(()=>{n(`timeout`)},e);t.addEventListener(`abort`,()=>{clearTimeout(r)},{once:!0})})}var dx=30,fx=30,px=60,mx=1,hx=[`timeupdate`,`seeking`,`waiting`,`play`],gx=class{parts;stop=new Au;run=Promise.resolve();failureValue;constructor(e){this.parts=e}get failure(){return this.failureValue}restartFrom(e){this.stop.stop();let t=new Au;this.stop=t,this.run=this.feedAfter(this.run,e,t)}dispose(){this.stop.stop()}async feedAfter(e,t,n){await e,await this.feed(t,n)}async feed(e,t){try{if(await this.settlePendingAppend(),t.wasStopped||this.hasElementFailed()||this.hasAllAudioFrom(e))return;await this.feedFrom(this.startOf(e),t)}catch(e){this.failureValue??=ne(e,`decode`,`feeding the audio buffer failed`)}}async feedFrom(e,t){let n=this.parts.source.segmentsFrom(e)[Symbol.asyncIterator]();try{await this.pump(n,t)&&this.endStream()}finally{n.return?.()}}hasAllAudioFrom(e){let{buffered:t}=this.parts.element,n=this.bufferedEndAt(e);return this.parts.mediaSource.readyState===`ended`&&n>e&&n===t.end(t.length-1)}startOf(e){let t=this.bufferedEndAt(e);return R(t>e?t:Math.max(0,e-mx))}async pump(e,t){let n=await this.nextWhenNeeded(e,t);for(;n!==ku;){if(n.done===!0)return!0;if(this.hasElementFailed())return!1;this.evictBehind(),await this.append(n.value),n=await this.nextWhenNeeded(e,t)}return!1}async nextWhenNeeded(e,t){return await this.waitUntilNeeded(t),t.race(()=>e.next())}async waitUntilNeeded(e){for(;!e.wasStopped&&this.bufferedAhead()>=dx;){let t=new AbortController;await e.race(()=>ex(this.parts.element,hx,t.signal)),t.abort()}}bufferedAhead(){let{currentTime:e}=this.parts.element;return R(this.bufferedEndAt(e)-e)}bufferedEndAt(e){let{buffered:t}=this.parts.element;for(let n=0;n<t.length;n+=1)if(t.start(n)<=e&&e<t.end(n))return t.end(n);return e}evictBehind(){let{buffered:e,currentTime:t}=this.parts.element;t-(e.length>0?e.start(0):t)<px||this.parts.sourceBuffer.updating||this.parts.sourceBuffer.remove(0,t-fx)}async append(e){let{sourceBuffer:t}=this.parts;await this.settlePendingAppend();let n=ex(t,[`updateend`,`error`]);try{t.appendBuffer(e)}catch(e){throw new j(`decode`,`the audio buffer rejected a segment`,{cause:e})}if(await n===`error`)throw new j(`decode`,`the audio buffer could not parse a segment`)}hasElementFailed(){return this.parts.element.error!==null}async settlePendingAppend(){this.parts.sourceBuffer.updating&&await ex(this.parts.sourceBuffer,[`updateend`])}endStream(){let{mediaSource:e,sourceBuffer:t}=this.parts;e.readyState===`open`&&!t.updating&&e.endOfStream()}},_x=class e{element;feeder;attached;standingEnd;constructor(e,t,n){this.element=e,this.feeder=t,this.attached=n}static isSupported(e){return ox(e.mimeType)}static async open(t,n){let r=ax();if(!r?.isTypeSupported(n.mimeType))throw new j(`codec-unsupported`,`${n.mimeType} cannot play through Media Source Extensions here`);let i=await cx(t,r);try{let r=i.mediaSource.addSourceBuffer(n.mimeType);i.mediaSource.duration=n.duration;let a=new gx({element:t,mediaSource:i.mediaSource,sourceBuffer:r,source:n});return a.restartFrom(R(0)),new e(t,a,i)}catch(e){throw i.detach(),bx(e)}}get currentTime(){return this.standingEnd??R(this.element.currentTime)}get isRunning(){return!this.element.paused}get hasEnded(){return this.standingEnd!==void 0||this.element.ended}get failure(){return this.feeder.failure??yx(this.element)}async start(){if(!this.hasEnded)try{await this.element.play()}catch(e){if(re(e))return;let t=vx(e,`NotAllowedError`);throw new j(t?`playback-blocked`:`decode`,t?`the browser refused to start audio playback; a user gesture is needed`:`audio playback failed to start`,{cause:e})}}pause(){this.element.pause()}seek(e){let t=this.attached.mediaSource.duration;if(e>=t){this.standAtEnd(R(t));return}this.standingEnd=void 0,this.element.currentTime=e,this.feeder.restartFrom(e)}dispose(){this.feeder.dispose(),this.element.pause(),this.attached.detach()}standAtEnd(e){this.element.pause(),this.standingEnd=e}};function vx(e,t){return e instanceof Error&&e.name===t}function yx(e){let{error:t}=e;return t===null?void 0:new j(`decode`,`the audio element failed (media error ${t.code})`,{cause:t})}function bx(e){return e instanceof j?e:new j(vx(e,`NotSupportedError`)?`codec-unsupported`:`decode`,`the audio element refused the recording's sound: ${ie(e)}`,{cause:e})}var xx=1e3,Sx=1001,Cx=1002,wx=1003,Tx=1004,Ex=1005,Dx=1006,Ox=1007,kx=1008,Ax=1009,jx=1010,Mx=1011,Nx=1012,Px=1013,Fx=1014,Ix=1015,Lx=1016,Rx=1017,zx=1018,Bx=1020,Vx=35902,Hx=35899,Ux=1021,Wx=1022,Gx=1023,Kx=1026,qx=1027,Jx=1028,Yx=1029,Xx=1030,Zx=1031,Qx=1033,$x=33776,eS=33777,tS=33778,nS=33779,rS=35840,iS=35841,aS=35842,oS=35843,sS=36196,cS=37492,lS=37496,uS=37488,dS=37489,fS=37490,pS=37491,mS=37808,hS=37809,gS=37810,_S=37811,vS=37812,yS=37813,bS=37814,xS=37815,SS=37816,CS=37817,wS=37818,TS=37819,ES=37820,DS=37821,OS=36492,kS=36494,AS=36495,jS=36283,MS=36284,NS=36285,PS=36286,FS=2300,IS=2301,LS=2302,RS=2303,zS=2400,BS=2401,VS=2402,HS=3200,US=`srgb`,WS=`srgb-linear`,GS=`linear`,KS=`srgb`,qS=7680,JS=35044,YS=`300 es`,XS=2e3;function ZS(e){for(let t=e.length-1;t>=0;--t)if(e[t]>=65535)return!0;return!1}function QS(e){return ArrayBuffer.isView(e)&&!(e instanceof DataView)}function $S(e){return document.createElementNS(`http://www.w3.org/1999/xhtml`,e)}function eC(){let e=$S(`canvas`);return e.style.display=`block`,e}var tC={};function nC(...e){let t=`THREE.`+e.shift();console.log(t,...e)}function rC(e){let t=e[0];if(typeof t==`string`&&t.startsWith(`TSL:`)){let t=e[1];t&&t.isStackTrace?e[0]+=` `+t.getLocation():e[1]=`Stack trace not available. Enable "THREE.Node.captureStackTrace" to capture stack traces.`}return e}function q(...e){e=rC(e);let t=`THREE.`+e.shift();{let n=e[0];n&&n.isStackTrace?console.warn(n.getError(t)):console.warn(t,...e)}}function J(...e){e=rC(e);let t=`THREE.`+e.shift();{let n=e[0];n&&n.isStackTrace?console.error(n.getError(t)):console.error(t,...e)}}function iC(...e){let t=e.join(` `);t in tC||(tC[t]=!0,q(...e))}function aC(e,t,n){return new Promise(function(r,i){function a(){switch(e.clientWaitSync(t,e.SYNC_FLUSH_COMMANDS_BIT,0)){case e.WAIT_FAILED:i();break;case e.TIMEOUT_EXPIRED:setTimeout(a,n);break;default:r()}}setTimeout(a,n)})}var oC={0:1,2:6,4:7,3:5,1:0,6:2,7:4,5:3},sC=class{addEventListener(e,t){this._listeners===void 0&&(this._listeners={});let n=this._listeners;n[e]===void 0&&(n[e]=[]),n[e].indexOf(t)===-1&&n[e].push(t)}hasEventListener(e,t){let n=this._listeners;return n!==void 0&&n[e]!==void 0&&n[e].indexOf(t)!==-1}removeEventListener(e,t){let n=this._listeners;if(n===void 0)return;let r=n[e];if(r!==void 0){let e=r.indexOf(t);e!==-1&&r.splice(e,1)}}dispatchEvent(e){let t=this._listeners;if(t===void 0)return;let n=t[e.type];if(n!==void 0){e.target=this;let t=n.slice(0);for(let n=0,r=t.length;n<r;n++)t[n].call(this,e);e.target=null}}},cC=/* @__PURE__ */ `00.01.02.03.04.05.06.07.08.09.0a.0b.0c.0d.0e.0f.10.11.12.13.14.15.16.17.18.19.1a.1b.1c.1d.1e.1f.20.21.22.23.24.25.26.27.28.29.2a.2b.2c.2d.2e.2f.30.31.32.33.34.35.36.37.38.39.3a.3b.3c.3d.3e.3f.40.41.42.43.44.45.46.47.48.49.4a.4b.4c.4d.4e.4f.50.51.52.53.54.55.56.57.58.59.5a.5b.5c.5d.5e.5f.60.61.62.63.64.65.66.67.68.69.6a.6b.6c.6d.6e.6f.70.71.72.73.74.75.76.77.78.79.7a.7b.7c.7d.7e.7f.80.81.82.83.84.85.86.87.88.89.8a.8b.8c.8d.8e.8f.90.91.92.93.94.95.96.97.98.99.9a.9b.9c.9d.9e.9f.a0.a1.a2.a3.a4.a5.a6.a7.a8.a9.aa.ab.ac.ad.ae.af.b0.b1.b2.b3.b4.b5.b6.b7.b8.b9.ba.bb.bc.bd.be.bf.c0.c1.c2.c3.c4.c5.c6.c7.c8.c9.ca.cb.cc.cd.ce.cf.d0.d1.d2.d3.d4.d5.d6.d7.d8.d9.da.db.dc.dd.de.df.e0.e1.e2.e3.e4.e5.e6.e7.e8.e9.ea.eb.ec.ed.ee.ef.f0.f1.f2.f3.f4.f5.f6.f7.f8.f9.fa.fb.fc.fd.fe.ff`.split(`.`),lC=Math.PI/180,uC=180/Math.PI;function dC(){let e=Math.random()*4294967295|0,t=Math.random()*4294967295|0,n=Math.random()*4294967295|0,r=Math.random()*4294967295|0;return(cC[e&255]+cC[e>>8&255]+cC[e>>16&255]+cC[e>>24&255]+`-`+cC[t&255]+cC[t>>8&255]+`-`+cC[t>>16&15|64]+cC[t>>24&255]+`-`+cC[n&63|128]+cC[n>>8&255]+`-`+cC[n>>16&255]+cC[n>>24&255]+cC[r&255]+cC[r>>8&255]+cC[r>>16&255]+cC[r>>24&255]).toLowerCase()}function fC(e,t,n){return Math.max(t,Math.min(n,e))}function pC(e,t){return(e%t+t)%t}function mC(e,t,n){return(1-n)*e+n*t}function hC(e,t){switch(t.constructor){case Float32Array:return e;case Uint32Array:return e/4294967295;case Uint16Array:return e/65535;case Uint8Array:case Uint8ClampedArray:return e/255;case Int32Array:return Math.max(e/2147483647,-1);case Int16Array:return Math.max(e/32767,-1);case Int8Array:return Math.max(e/127,-1);default:throw Error(`THREE.MathUtils: Invalid component type.`)}}function gC(e,t){switch(t.constructor){case Float32Array:return e;case Uint32Array:return Math.round(e*4294967295);case Uint16Array:return Math.round(e*65535);case Uint8Array:case Uint8ClampedArray:return Math.round(e*255);case Int32Array:return Math.round(e*2147483647);case Int16Array:return Math.round(e*32767);case Int8Array:return Math.round(e*127);default:throw Error(`THREE.MathUtils: Invalid component type.`)}}var Y=class e{static{e.prototype.isVector2=!0}constructor(e=0,t=0){this.x=e,this.y=t}get width(){return this.x}set width(e){this.x=e}get height(){return this.y}set height(e){this.y=e}set(e,t){return this.x=e,this.y=t,this}setScalar(e){return this.x=e,this.y=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;default:throw Error(`THREE.Vector2: index is out of range: `+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;default:throw Error(`THREE.Vector2: index is out of range: `+e)}}clone(){return new this.constructor(this.x,this.y)}copy(e){return this.x=e.x,this.y=e.y,this}add(e){return this.x+=e.x,this.y+=e.y,this}addScalar(e){return this.x+=e,this.y+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this}subScalar(e){return this.x-=e,this.y-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this}multiply(e){return this.x*=e.x,this.y*=e.y,this}multiplyScalar(e){return this.x*=e,this.y*=e,this}divide(e){return this.x/=e.x,this.y/=e.y,this}divideScalar(e){return this.multiplyScalar(1/e)}applyMatrix3(e){let t=this.x,n=this.y,r=e.elements;return this.x=r[0]*t+r[3]*n+r[6],this.y=r[1]*t+r[4]*n+r[7],this}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this}clamp(e,t){return this.x=fC(this.x,e.x,t.x),this.y=fC(this.y,e.y,t.y),this}clampScalar(e,t){return this.x=fC(this.x,e,t),this.y=fC(this.y,e,t),this}clampLength(e,t){let n=this.length();return this.divideScalar(n||1).multiplyScalar(fC(n,e,t))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this}negate(){return this.x=-this.x,this.y=-this.y,this}dot(e){return this.x*e.x+this.y*e.y}cross(e){return this.x*e.y-this.y*e.x}lengthSq(){return this.x*this.x+this.y*this.y}length(){return Math.sqrt(this.x*this.x+this.y*this.y)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)}normalize(){return this.divideScalar(this.length()||1)}angle(){return Math.atan2(-this.y,-this.x)+Math.PI}angleTo(e){let t=Math.sqrt(this.lengthSq()*e.lengthSq());if(t===0)return Math.PI/2;let n=this.dot(e)/t;return Math.acos(fC(n,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){let t=this.x-e.x,n=this.y-e.y;return t*t+n*n}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this}lerpVectors(e,t,n){return this.x=e.x+(t.x-e.x)*n,this.y=e.y+(t.y-e.y)*n,this}equals(e){return e.x===this.x&&e.y===this.y}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this}rotateAround(e,t){let n=Math.cos(t),r=Math.sin(t),i=this.x-e.x,a=this.y-e.y;return this.x=i*n-a*r+e.x,this.y=i*r+a*n+e.y,this}random(){return this.x=Math.random(),this.y=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y}},_C=class{constructor(e=0,t=0,n=0,r=1){this.isQuaternion=!0,this._x=e,this._y=t,this._z=n,this._w=r}static slerpFlat(e,t,n,r,i,a,o){let s=n[r+0],c=n[r+1],l=n[r+2],u=n[r+3],d=i[a+0],f=i[a+1],p=i[a+2],m=i[a+3];if(u!==m||s!==d||c!==f||l!==p){let e=s*d+c*f+l*p+u*m;e<0&&(d=-d,f=-f,p=-p,m=-m,e=-e);let t=1-o;if(e<.9995){let n=Math.acos(e),r=Math.sin(n);t=Math.sin(t*n)/r,o=Math.sin(o*n)/r,s=s*t+d*o,c=c*t+f*o,l=l*t+p*o,u=u*t+m*o}else{s=s*t+d*o,c=c*t+f*o,l=l*t+p*o,u=u*t+m*o;let e=1/Math.sqrt(s*s+c*c+l*l+u*u);s*=e,c*=e,l*=e,u*=e}}e[t]=s,e[t+1]=c,e[t+2]=l,e[t+3]=u}static multiplyQuaternionsFlat(e,t,n,r,i,a){let o=n[r],s=n[r+1],c=n[r+2],l=n[r+3],u=i[a],d=i[a+1],f=i[a+2],p=i[a+3];return e[t]=o*p+l*u+s*f-c*d,e[t+1]=s*p+l*d+c*u-o*f,e[t+2]=c*p+l*f+o*d-s*u,e[t+3]=l*p-o*u-s*d-c*f,e}get x(){return this._x}set x(e){this._x=e,this._onChangeCallback()}get y(){return this._y}set y(e){this._y=e,this._onChangeCallback()}get z(){return this._z}set z(e){this._z=e,this._onChangeCallback()}get w(){return this._w}set w(e){this._w=e,this._onChangeCallback()}set(e,t,n,r){return this._x=e,this._y=t,this._z=n,this._w=r,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._w)}copy(e){return this._x=e.x,this._y=e.y,this._z=e.z,this._w=e.w,this._onChangeCallback(),this}setFromEuler(e,t=!0){let n=e._x,r=e._y,i=e._z,a=e._order,o=Math.cos,s=Math.sin,c=o(n/2),l=o(r/2),u=o(i/2),d=s(n/2),f=s(r/2),p=s(i/2);switch(a){case`XYZ`:this._x=d*l*u+c*f*p,this._y=c*f*u-d*l*p,this._z=c*l*p+d*f*u,this._w=c*l*u-d*f*p;break;case`YXZ`:this._x=d*l*u+c*f*p,this._y=c*f*u-d*l*p,this._z=c*l*p-d*f*u,this._w=c*l*u+d*f*p;break;case`ZXY`:this._x=d*l*u-c*f*p,this._y=c*f*u+d*l*p,this._z=c*l*p+d*f*u,this._w=c*l*u-d*f*p;break;case`ZYX`:this._x=d*l*u-c*f*p,this._y=c*f*u+d*l*p,this._z=c*l*p-d*f*u,this._w=c*l*u+d*f*p;break;case`YZX`:this._x=d*l*u+c*f*p,this._y=c*f*u+d*l*p,this._z=c*l*p-d*f*u,this._w=c*l*u-d*f*p;break;case`XZY`:this._x=d*l*u-c*f*p,this._y=c*f*u-d*l*p,this._z=c*l*p+d*f*u,this._w=c*l*u+d*f*p;break;default:q(`Quaternion: .setFromEuler() encountered an unknown order: `+a)}return t===!0&&this._onChangeCallback(),this}setFromAxisAngle(e,t){let n=t/2,r=Math.sin(n);return this._x=e.x*r,this._y=e.y*r,this._z=e.z*r,this._w=Math.cos(n),this._onChangeCallback(),this}setFromRotationMatrix(e){let t=e.elements,n=t[0],r=t[4],i=t[8],a=t[1],o=t[5],s=t[9],c=t[2],l=t[6],u=t[10],d=n+o+u;if(d>0){let e=.5/Math.sqrt(d+1);this._w=.25/e,this._x=(l-s)*e,this._y=(i-c)*e,this._z=(a-r)*e}else if(n>o&&n>u){let e=2*Math.sqrt(1+n-o-u);this._w=(l-s)/e,this._x=.25*e,this._y=(r+a)/e,this._z=(i+c)/e}else if(o>u){let e=2*Math.sqrt(1+o-n-u);this._w=(i-c)/e,this._x=(r+a)/e,this._y=.25*e,this._z=(s+l)/e}else{let e=2*Math.sqrt(1+u-n-o);this._w=(a-r)/e,this._x=(i+c)/e,this._y=(s+l)/e,this._z=.25*e}return this._onChangeCallback(),this}setFromUnitVectors(e,t){let n=e.dot(t)+1;return n<1e-8?(n=0,Math.abs(e.x)>Math.abs(e.z)?(this._x=-e.y,this._y=e.x,this._z=0,this._w=n):(this._x=0,this._y=-e.z,this._z=e.y,this._w=n)):(this._x=e.y*t.z-e.z*t.y,this._y=e.z*t.x-e.x*t.z,this._z=e.x*t.y-e.y*t.x,this._w=n),this.normalize()}angleTo(e){return 2*Math.acos(Math.abs(fC(this.dot(e),-1,1)))}rotateTowards(e,t){let n=this.angleTo(e);if(n===0)return this;let r=Math.min(1,t/n);return this.slerp(e,r),this}identity(){return this.set(0,0,0,1)}invert(){return this.conjugate()}conjugate(){return this._x*=-1,this._y*=-1,this._z*=-1,this._onChangeCallback(),this}dot(e){return this._x*e._x+this._y*e._y+this._z*e._z+this._w*e._w}lengthSq(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w}length(){return Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w)}normalize(){let e=this.length();return e===0?(this._x=0,this._y=0,this._z=0,this._w=1):(e=1/e,this._x*=e,this._y*=e,this._z*=e,this._w*=e),this._onChangeCallback(),this}multiply(e){return this.multiplyQuaternions(this,e)}premultiply(e){return this.multiplyQuaternions(e,this)}multiplyQuaternions(e,t){let n=e._x,r=e._y,i=e._z,a=e._w,o=t._x,s=t._y,c=t._z,l=t._w;return this._x=n*l+a*o+r*c-i*s,this._y=r*l+a*s+i*o-n*c,this._z=i*l+a*c+n*s-r*o,this._w=a*l-n*o-r*s-i*c,this._onChangeCallback(),this}slerp(e,t){let n=e._x,r=e._y,i=e._z,a=e._w,o=this.dot(e);o<0&&(n=-n,r=-r,i=-i,a=-a,o=-o);let s=1-t;if(o<.9995){let e=Math.acos(o),c=Math.sin(e);s=Math.sin(s*e)/c,t=Math.sin(t*e)/c,this._x=this._x*s+n*t,this._y=this._y*s+r*t,this._z=this._z*s+i*t,this._w=this._w*s+a*t,this._onChangeCallback()}else this._x=this._x*s+n*t,this._y=this._y*s+r*t,this._z=this._z*s+i*t,this._w=this._w*s+a*t,this.normalize();return this}slerpQuaternions(e,t,n){return this.copy(e).slerp(t,n)}random(){let e=2*Math.PI*Math.random(),t=2*Math.PI*Math.random(),n=Math.random(),r=Math.sqrt(1-n),i=Math.sqrt(n);return this.set(r*Math.sin(e),r*Math.cos(e),i*Math.sin(t),i*Math.cos(t))}equals(e){return e._x===this._x&&e._y===this._y&&e._z===this._z&&e._w===this._w}fromArray(e,t=0){return this._x=e[t],this._y=e[t+1],this._z=e[t+2],this._w=e[t+3],this._onChangeCallback(),this}toArray(e=[],t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,e[t+3]=this._w,e}fromBufferAttribute(e,t){return this._x=e.getX(t),this._y=e.getY(t),this._z=e.getZ(t),this._w=e.getW(t),this._onChangeCallback(),this}toJSON(){return this.toArray()}_onChange(e){return this._onChangeCallback=e,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._w}},X=class e{static{e.prototype.isVector3=!0}constructor(e=0,t=0,n=0){this.x=e,this.y=t,this.z=n}set(e,t,n){return n===void 0&&(n=this.z),this.x=e,this.y=t,this.z=n,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;case 2:this.z=t;break;default:throw Error(`THREE.Vector3: index is out of range: `+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;default:throw Error(`THREE.Vector3: index is out of range: `+e)}}clone(){return new this.constructor(this.x,this.y,this.z)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this.z=e.z+t.z,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this.z+=e.z*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this.z=e.z-t.z,this}multiply(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this}multiplyVectors(e,t){return this.x=e.x*t.x,this.y=e.y*t.y,this.z=e.z*t.z,this}applyEuler(e){return this.applyQuaternion(yC.setFromEuler(e))}applyAxisAngle(e,t){return this.applyQuaternion(yC.setFromAxisAngle(e,t))}applyMatrix3(e){let t=this.x,n=this.y,r=this.z,i=e.elements;return this.x=i[0]*t+i[3]*n+i[6]*r,this.y=i[1]*t+i[4]*n+i[7]*r,this.z=i[2]*t+i[5]*n+i[8]*r,this}applyNormalMatrix(e){return this.applyMatrix3(e).normalize()}applyMatrix4(e){let t=this.x,n=this.y,r=this.z,i=e.elements,a=1/(i[3]*t+i[7]*n+i[11]*r+i[15]);return this.x=(i[0]*t+i[4]*n+i[8]*r+i[12])*a,this.y=(i[1]*t+i[5]*n+i[9]*r+i[13])*a,this.z=(i[2]*t+i[6]*n+i[10]*r+i[14])*a,this}applyQuaternion(e){let t=this.x,n=this.y,r=this.z,i=e.x,a=e.y,o=e.z,s=e.w,c=2*(a*r-o*n),l=2*(o*t-i*r),u=2*(i*n-a*t);return this.x=t+s*c+a*u-o*l,this.y=n+s*l+o*c-i*u,this.z=r+s*u+i*l-a*c,this}project(e){return this.applyMatrix4(e.matrixWorldInverse).applyMatrix4(e.projectionMatrix)}unproject(e){return this.applyMatrix4(e.projectionMatrixInverse).applyMatrix4(e.matrixWorld)}transformDirection(e){let t=this.x,n=this.y,r=this.z,i=e.elements;return this.x=i[0]*t+i[4]*n+i[8]*r,this.y=i[1]*t+i[5]*n+i[9]*r,this.z=i[2]*t+i[6]*n+i[10]*r,this.normalize()}divide(e){return this.x/=e.x,this.y/=e.y,this.z/=e.z,this}divideScalar(e){return this.multiplyScalar(1/e)}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this.z=Math.min(this.z,e.z),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this.z=Math.max(this.z,e.z),this}clamp(e,t){return this.x=fC(this.x,e.x,t.x),this.y=fC(this.y,e.y,t.y),this.z=fC(this.z,e.z,t.z),this}clampScalar(e,t){return this.x=fC(this.x,e,t),this.y=fC(this.y,e,t),this.z=fC(this.z,e,t),this}clampLength(e,t){let n=this.length();return this.divideScalar(n||1).multiplyScalar(fC(n,e,t))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)}normalize(){return this.divideScalar(this.length()||1)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this.z+=(e.z-this.z)*t,this}lerpVectors(e,t,n){return this.x=e.x+(t.x-e.x)*n,this.y=e.y+(t.y-e.y)*n,this.z=e.z+(t.z-e.z)*n,this}cross(e){return this.crossVectors(this,e)}crossVectors(e,t){let n=e.x,r=e.y,i=e.z,a=t.x,o=t.y,s=t.z;return this.x=r*s-i*o,this.y=i*a-n*s,this.z=n*o-r*a,this}projectOnVector(e){let t=e.lengthSq();if(t===0)return this.set(0,0,0);let n=e.dot(this)/t;return this.copy(e).multiplyScalar(n)}projectOnPlane(e){return vC.copy(this).projectOnVector(e),this.sub(vC)}reflect(e){return this.sub(vC.copy(e).multiplyScalar(2*this.dot(e)))}angleTo(e){let t=Math.sqrt(this.lengthSq()*e.lengthSq());if(t===0)return Math.PI/2;let n=this.dot(e)/t;return Math.acos(fC(n,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){let t=this.x-e.x,n=this.y-e.y,r=this.z-e.z;return t*t+n*n+r*r}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)+Math.abs(this.z-e.z)}setFromSpherical(e){return this.setFromSphericalCoords(e.radius,e.phi,e.theta)}setFromSphericalCoords(e,t,n){let r=Math.sin(t)*e;return this.x=r*Math.sin(n),this.y=Math.cos(t)*e,this.z=r*Math.cos(n),this}setFromCylindrical(e){return this.setFromCylindricalCoords(e.radius,e.theta,e.y)}setFromCylindricalCoords(e,t,n){return this.x=e*Math.sin(t),this.y=n,this.z=e*Math.cos(t),this}setFromMatrixPosition(e){let t=e.elements;return this.x=t[12],this.y=t[13],this.z=t[14],this}setFromMatrixScale(e){let t=this.setFromMatrixColumn(e,0).length(),n=this.setFromMatrixColumn(e,1).length(),r=this.setFromMatrixColumn(e,2).length();return this.x=t,this.y=n,this.z=r,this}setFromMatrixColumn(e,t){return this.fromArray(e.elements,t*4)}setFromMatrix3Column(e,t){return this.fromArray(e.elements,t*3)}setFromEuler(e){return this.x=e._x,this.y=e._y,this.z=e._z,this}setFromColor(e){return this.x=e.r,this.y=e.g,this.z=e.b,this}equals(e){return e.x===this.x&&e.y===this.y&&e.z===this.z}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this.z=e[t+2],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e[t+2]=this.z,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this.z=e.getZ(t),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this}randomDirection(){let e=Math.random()*Math.PI*2,t=Math.random()*2-1,n=Math.sqrt(1-t*t);return this.x=n*Math.cos(e),this.y=t,this.z=n*Math.sin(e),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z}},vC=/*@__PURE__*/ new X,yC=/*@__PURE__*/ new _C,Z=class e{static{e.prototype.isMatrix3=!0}constructor(e,t,n,r,i,a,o,s,c){this.elements=[1,0,0,0,1,0,0,0,1],e!==void 0&&this.set(e,t,n,r,i,a,o,s,c)}set(e,t,n,r,i,a,o,s,c){let l=this.elements;return l[0]=e,l[1]=r,l[2]=o,l[3]=t,l[4]=i,l[5]=s,l[6]=n,l[7]=a,l[8]=c,this}identity(){return this.set(1,0,0,0,1,0,0,0,1),this}copy(e){let t=this.elements,n=e.elements;return t[0]=n[0],t[1]=n[1],t[2]=n[2],t[3]=n[3],t[4]=n[4],t[5]=n[5],t[6]=n[6],t[7]=n[7],t[8]=n[8],this}extractBasis(e,t,n){return e.setFromMatrix3Column(this,0),t.setFromMatrix3Column(this,1),n.setFromMatrix3Column(this,2),this}setFromMatrix4(e){let t=e.elements;return this.set(t[0],t[4],t[8],t[1],t[5],t[9],t[2],t[6],t[10]),this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,t){let n=e.elements,r=t.elements,i=this.elements,a=n[0],o=n[3],s=n[6],c=n[1],l=n[4],u=n[7],d=n[2],f=n[5],p=n[8],m=r[0],h=r[3],g=r[6],_=r[1],v=r[4],y=r[7],b=r[2],x=r[5],S=r[8];return i[0]=a*m+o*_+s*b,i[3]=a*h+o*v+s*x,i[6]=a*g+o*y+s*S,i[1]=c*m+l*_+u*b,i[4]=c*h+l*v+u*x,i[7]=c*g+l*y+u*S,i[2]=d*m+f*_+p*b,i[5]=d*h+f*v+p*x,i[8]=d*g+f*y+p*S,this}multiplyScalar(e){let t=this.elements;return t[0]*=e,t[3]*=e,t[6]*=e,t[1]*=e,t[4]*=e,t[7]*=e,t[2]*=e,t[5]*=e,t[8]*=e,this}determinant(){let e=this.elements,t=e[0],n=e[1],r=e[2],i=e[3],a=e[4],o=e[5],s=e[6],c=e[7],l=e[8];return t*a*l-t*o*c-n*i*l+n*o*s+r*i*c-r*a*s}invert(){let e=this.elements,t=e[0],n=e[1],r=e[2],i=e[3],a=e[4],o=e[5],s=e[6],c=e[7],l=e[8],u=l*a-o*c,d=o*s-l*i,f=c*i-a*s,p=t*u+n*d+r*f;if(p===0)return this.set(0,0,0,0,0,0,0,0,0);let m=1/p;return e[0]=u*m,e[1]=(r*c-l*n)*m,e[2]=(o*n-r*a)*m,e[3]=d*m,e[4]=(l*t-r*s)*m,e[5]=(r*i-o*t)*m,e[6]=f*m,e[7]=(n*s-c*t)*m,e[8]=(a*t-n*i)*m,this}transpose(){let e,t=this.elements;return e=t[1],t[1]=t[3],t[3]=e,e=t[2],t[2]=t[6],t[6]=e,e=t[5],t[5]=t[7],t[7]=e,this}getNormalMatrix(e){return this.setFromMatrix4(e).invert().transpose()}transposeIntoArray(e){let t=this.elements;return e[0]=t[0],e[1]=t[3],e[2]=t[6],e[3]=t[1],e[4]=t[4],e[5]=t[7],e[6]=t[2],e[7]=t[5],e[8]=t[8],this}setUvTransform(e,t,n,r,i,a,o){let s=Math.cos(i),c=Math.sin(i);return this.set(n*s,n*c,-n*(s*a+c*o)+a+e,-r*c,r*s,-r*(-c*a+s*o)+o+t,0,0,1),this}scale(e,t){return iC(`Matrix3: .scale() is deprecated. Use .makeScale() instead.`),this.premultiply(bC.makeScale(e,t)),this}rotate(e){return iC(`Matrix3: .rotate() is deprecated. Use .makeRotation() instead.`),this.premultiply(bC.makeRotation(-e)),this}translate(e,t){return iC(`Matrix3: .translate() is deprecated. Use .makeTranslation() instead.`),this.premultiply(bC.makeTranslation(e,t)),this}makeTranslation(e,t){return e.isVector2?this.set(1,0,e.x,0,1,e.y,0,0,1):this.set(1,0,e,0,1,t,0,0,1),this}makeRotation(e){let t=Math.cos(e),n=Math.sin(e);return this.set(t,-n,0,n,t,0,0,0,1),this}makeScale(e,t){return this.set(e,0,0,0,t,0,0,0,1),this}equals(e){let t=this.elements,n=e.elements;for(let e=0;e<9;e++)if(t[e]!==n[e])return!1;return!0}fromArray(e,t=0){for(let n=0;n<9;n++)this.elements[n]=e[n+t];return this}toArray(e=[],t=0){let n=this.elements;return e[t]=n[0],e[t+1]=n[1],e[t+2]=n[2],e[t+3]=n[3],e[t+4]=n[4],e[t+5]=n[5],e[t+6]=n[6],e[t+7]=n[7],e[t+8]=n[8],e}clone(){return new this.constructor().fromArray(this.elements)}},bC=/*@__PURE__*/ new Z,xC=/*@__PURE__*/ new Z().set(.4123908,.3575843,.1804808,.212639,.7151687,.0721923,.0193308,.1191948,.9505322),SC=/*@__PURE__*/ new Z().set(3.2409699,-1.5373832,-.4986108,-.9692436,1.8759675,.0415551,.0556301,-.203977,1.0569715);function CC(){let e={enabled:!0,workingColorSpace:WS,spaces:{},convert:function(e,t,n){return this.enabled===!1||t===n||!t||!n?e:(this.spaces[t].transfer===`srgb`&&(e.r=TC(e.r),e.g=TC(e.g),e.b=TC(e.b)),this.spaces[t].primaries!==this.spaces[n].primaries&&(e.applyMatrix3(this.spaces[t].toXYZ),e.applyMatrix3(this.spaces[n].fromXYZ)),this.spaces[n].transfer===`srgb`&&(e.r=EC(e.r),e.g=EC(e.g),e.b=EC(e.b)),e)},workingToColorSpace:function(e,t){return this.convert(e,this.workingColorSpace,t)},colorSpaceToWorking:function(e,t){return this.convert(e,t,this.workingColorSpace)},getPrimaries:function(e){return this.spaces[e].primaries},getTransfer:function(e){return e===``?GS:this.spaces[e].transfer},getToneMappingMode:function(e){return this.spaces[e].outputColorSpaceConfig.toneMappingMode||`standard`},getLuminanceCoefficients:function(e,t=this.workingColorSpace){return e.fromArray(this.spaces[t].luminanceCoefficients)},define:function(e){Object.assign(this.spaces,e)},_getMatrix:function(e,t,n){return e.copy(this.spaces[t].toXYZ).multiply(this.spaces[n].fromXYZ)},_getDrawingBufferColorSpace:function(e){return this.spaces[e].outputColorSpaceConfig.drawingBufferColorSpace},_getUnpackColorSpace:function(e=this.workingColorSpace){return this.spaces[e].workingColorSpaceConfig.unpackColorSpace},fromWorkingColorSpace:function(t,n){return iC(`ColorManagement: .fromWorkingColorSpace() has been renamed to .workingToColorSpace().`),e.workingToColorSpace(t,n)},toWorkingColorSpace:function(t,n){return iC(`ColorManagement: .toWorkingColorSpace() has been renamed to .colorSpaceToWorking().`),e.colorSpaceToWorking(t,n)}},t=[.64,.33,.3,.6,.15,.06],n=[.2126,.7152,.0722],r=[.3127,.329];return e.define({[WS]:{primaries:t,whitePoint:r,transfer:GS,toXYZ:xC,fromXYZ:SC,luminanceCoefficients:n,workingColorSpaceConfig:{unpackColorSpace:US},outputColorSpaceConfig:{drawingBufferColorSpace:US}},[US]:{primaries:t,whitePoint:r,transfer:KS,toXYZ:xC,fromXYZ:SC,luminanceCoefficients:n,outputColorSpaceConfig:{drawingBufferColorSpace:US}}}),e}var wC=/*@__PURE__*/ CC();function TC(e){return e<.04045?e*.0773993808:(e*.9478672986+.0521327014)**2.4}function EC(e){return e<.0031308?e*12.92:1.055*e**.41666-.055}var DC,OC=class{static getDataURL(e,t=`image/png`){if(/^data:/i.test(e.src)||typeof HTMLCanvasElement>`u`)return e.src;let n;if(e instanceof HTMLCanvasElement)n=e;else{DC===void 0&&(DC=$S(`canvas`)),DC.width=e.width,DC.height=e.height;let t=DC.getContext(`2d`);e instanceof ImageData?t.putImageData(e,0,0):t.drawImage(e,0,0,e.width,e.height),n=DC}return n.toDataURL(t)}static sRGBToLinear(e){if(typeof HTMLImageElement<`u`&&e instanceof HTMLImageElement||typeof HTMLCanvasElement<`u`&&e instanceof HTMLCanvasElement||typeof ImageBitmap<`u`&&e instanceof ImageBitmap){let t=$S(`canvas`);t.width=e.width,t.height=e.height;let n=t.getContext(`2d`);n.drawImage(e,0,0,e.width,e.height);let r=n.getImageData(0,0,e.width,e.height),i=r.data;for(let e=0;e<i.length;e++)i[e]=TC(i[e]/255)*255;return n.putImageData(r,0,0),t}if(e.data){let t=e.data.slice(0);for(let e=0;e<t.length;e++)t instanceof Uint8Array||t instanceof Uint8ClampedArray?t[e]=Math.floor(TC(t[e]/255)*255):t[e]=TC(t[e]);return{data:t,width:e.width,height:e.height}}return q(`ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied.`),e}},kC=0,AC=class{constructor(e=null){this.isTextureSource=!0,Object.defineProperty(this,"id",{value:kC++}),this.uuid=dC(),this.data=e,this.dataReady=!0,this.version=0}getSize(e){let t=this.data;return typeof HTMLVideoElement<`u`&&t instanceof HTMLVideoElement?e.set(t.videoWidth,t.videoHeight,0):typeof VideoFrame<`u`&&t instanceof VideoFrame?e.set(t.displayWidth,t.displayHeight,0):t===null?e.set(0,0,0):e.set(t.width,t.height,t.depth||0),e}set needsUpdate(e){e===!0&&this.version++}toJSON(e){let t=e===void 0||typeof e==`string`;if(!t&&e.images[this.uuid]!==void 0)return e.images[this.uuid];let n={uuid:this.uuid,url:``},r=this.data;if(r!==null){let e;if(Array.isArray(r)){e=[];for(let t=0,n=r.length;t<n;t++)r[t].isDataTexture?e.push(jC(r[t].image)):e.push(jC(r[t]))}else e=jC(r);n.url=e}return t||(e.images[this.uuid]=n),n}};function jC(e){return typeof HTMLImageElement<`u`&&e instanceof HTMLImageElement||typeof HTMLCanvasElement<`u`&&e instanceof HTMLCanvasElement||typeof ImageBitmap<`u`&&e instanceof ImageBitmap?OC.getDataURL(e):e.data?{data:Array.from(e.data),width:e.width,height:e.height,type:e.data.constructor.name}:(q(`Texture: Unable to serialize Texture.`),{})}var MC=0,NC=/*@__PURE__*/ new X,PC=class e extends sC{constructor(t=e.DEFAULT_IMAGE,n=e.DEFAULT_MAPPING,r=Sx,i=Sx,a=Dx,o=kx,s=Gx,c=Ax,l=e.DEFAULT_ANISOTROPY,u=``){super(),this.isTexture=!0,Object.defineProperty(this,"id",{value:MC++}),this.uuid=dC(),this.name=``,this.source=new AC(t),this.mipmaps=[],this.mapping=n,this.channel=0,this.wrapS=r,this.wrapT=i,this.magFilter=a,this.minFilter=o,this.anisotropy=l,this.format=s,this.internalFormat=null,this.type=c,this.offset=new Y(0,0),this.repeat=new Y(1,1),this.center=new Y(0,0),this.rotation=0,this.matrixAutoUpdate=!0,this.matrix=new Z,this.generateMipmaps=!0,this.premultiplyAlpha=!1,this.flipY=!0,this.unpackAlignment=4,this.colorSpace=u,this.userData={},this.updateRanges=[],this.version=0,this.onUpdate=null,this.renderTarget=null,this.isRenderTargetTexture=!1,this.isArrayTexture=!!(t&&t.depth&&t.depth>1),this.pmremVersion=0,this.normalized=!1}get width(){return this.source.getSize(NC).x}get height(){return this.source.getSize(NC).y}get depth(){return this.source.getSize(NC).z}get image(){return this.source.data}set image(e){this.source.data=e}updateMatrix(){this.matrix.setUvTransform(this.offset.x,this.offset.y,this.repeat.x,this.repeat.y,this.rotation,this.center.x,this.center.y)}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}clone(){return new this.constructor().copy(this)}copy(e){return this.name=e.name,this.source=e.source,this.mipmaps=e.mipmaps.slice(0),this.mapping=e.mapping,this.channel=e.channel,this.wrapS=e.wrapS,this.wrapT=e.wrapT,this.magFilter=e.magFilter,this.minFilter=e.minFilter,this.anisotropy=e.anisotropy,this.format=e.format,this.internalFormat=e.internalFormat,this.type=e.type,this.normalized=e.normalized,this.offset.copy(e.offset),this.repeat.copy(e.repeat),this.center.copy(e.center),this.rotation=e.rotation,this.matrixAutoUpdate=e.matrixAutoUpdate,this.matrix.copy(e.matrix),this.generateMipmaps=e.generateMipmaps,this.premultiplyAlpha=e.premultiplyAlpha,this.flipY=e.flipY,this.unpackAlignment=e.unpackAlignment,this.colorSpace=e.colorSpace,this.renderTarget=e.renderTarget,this.isRenderTargetTexture=e.isRenderTargetTexture,this.isArrayTexture=e.isArrayTexture,this.userData=JSON.parse(JSON.stringify(e.userData)),this.needsUpdate=!0,this}setValues(e){for(let t in e){let n=e[t];if(n===void 0){q(`Texture.setValues(): parameter '${t}' has value of undefined.`);continue}let r=this[t];if(r===void 0){q(`Texture.setValues(): property '${t}' does not exist.`);continue}r&&n&&r.isVector2&&n.isVector2||r&&n&&r.isVector3&&n.isVector3||r&&n&&r.isMatrix3&&n.isMatrix3?r.copy(n):this[t]=n}}toJSON(e){let t=e===void 0||typeof e==`string`;if(!t&&e.textures[this.uuid]!==void 0)return e.textures[this.uuid];let n={metadata:{version:4.7,type:`Texture`,generator:`Texture.toJSON`},uuid:this.uuid,name:this.name,image:this.source.toJSON(e).uuid,mapping:this.mapping,channel:this.channel,repeat:[this.repeat.x,this.repeat.y],offset:[this.offset.x,this.offset.y],center:[this.center.x,this.center.y],rotation:this.rotation,wrap:[this.wrapS,this.wrapT],format:this.format,internalFormat:this.internalFormat,type:this.type,normalized:this.normalized,colorSpace:this.colorSpace,minFilter:this.minFilter,magFilter:this.magFilter,anisotropy:this.anisotropy,flipY:this.flipY,generateMipmaps:this.generateMipmaps,premultiplyAlpha:this.premultiplyAlpha,unpackAlignment:this.unpackAlignment};return Object.keys(this.userData).length>0&&(n.userData=this.userData),t||(e.textures[this.uuid]=n),n}dispose(){this.dispatchEvent({type:`dispose`})}transformUv(e){if(this.mapping!==300)return e;if(e.applyMatrix3(this.matrix),e.x<0||e.x>1)switch(this.wrapS){case xx:e.x-=Math.floor(e.x);break;case Sx:e.x=e.x<0?0:1;break;case Cx:Math.abs(Math.floor(e.x)%2)===1?e.x=Math.ceil(e.x)-e.x:e.x-=Math.floor(e.x)}if(e.y<0||e.y>1)switch(this.wrapT){case xx:e.y-=Math.floor(e.y);break;case Sx:e.y=e.y<0?0:1;break;case Cx:Math.abs(Math.floor(e.y)%2)===1?e.y=Math.ceil(e.y)-e.y:e.y-=Math.floor(e.y)}return this.flipY&&(e.y=1-e.y),e}set needsUpdate(e){e===!0&&(this.version++,this.source.needsUpdate=!0)}set needsPMREMUpdate(e){e===!0&&this.pmremVersion++}};PC.DEFAULT_IMAGE=null,PC.DEFAULT_MAPPING=300,PC.DEFAULT_ANISOTROPY=1;var FC=class e{static{e.prototype.isVector4=!0}constructor(e=0,t=0,n=0,r=1){this.x=e,this.y=t,this.z=n,this.w=r}get width(){return this.z}set width(e){this.z=e}get height(){return this.w}set height(e){this.w=e}set(e,t,n,r){return this.x=e,this.y=t,this.z=n,this.w=r,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this.w=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setW(e){return this.w=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;case 2:this.z=t;break;case 3:this.w=t;break;default:throw Error(`THREE.Vector4: index is out of range: `+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;case 3:return this.w;default:throw Error(`THREE.Vector4: index is out of range: `+e)}}clone(){return new this.constructor(this.x,this.y,this.z,this.w)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this.w=e.w===void 0?1:e.w,this}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this.w+=e.w,this}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this.w+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this.z=e.z+t.z,this.w=e.w+t.w,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this.z+=e.z*t,this.w+=e.w*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this.w-=e.w,this}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this.w-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this.z=e.z-t.z,this.w=e.w-t.w,this}multiply(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this.w*=e.w,this}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this.w*=e,this}applyMatrix4(e){let t=this.x,n=this.y,r=this.z,i=this.w,a=e.elements;return this.x=a[0]*t+a[4]*n+a[8]*r+a[12]*i,this.y=a[1]*t+a[5]*n+a[9]*r+a[13]*i,this.z=a[2]*t+a[6]*n+a[10]*r+a[14]*i,this.w=a[3]*t+a[7]*n+a[11]*r+a[15]*i,this}divide(e){return this.x/=e.x,this.y/=e.y,this.z/=e.z,this.w/=e.w,this}divideScalar(e){return this.multiplyScalar(1/e)}setAxisAngleFromQuaternion(e){this.w=2*Math.acos(e.w);let t=Math.sqrt(1-e.w*e.w);return t<1e-4?(this.x=1,this.y=0,this.z=0):(this.x=e.x/t,this.y=e.y/t,this.z=e.z/t),this}setAxisAngleFromRotationMatrix(e){let t,n,r,i,a=.01,o=.1,s=e.elements,c=s[0],l=s[4],u=s[8],d=s[1],f=s[5],p=s[9],m=s[2],h=s[6],g=s[10];if(Math.abs(l-d)<a&&Math.abs(u-m)<a&&Math.abs(p-h)<a){if(Math.abs(l+d)<o&&Math.abs(u+m)<o&&Math.abs(p+h)<o&&Math.abs(c+f+g-3)<o)return this.set(1,0,0,0),this;t=Math.PI;let e=(c+1)/2,s=(f+1)/2,_=(g+1)/2,v=(l+d)/4,y=(u+m)/4,b=(p+h)/4;return e>s&&e>_?e<a?(n=0,r=.707106781,i=.707106781):(n=Math.sqrt(e),r=v/n,i=y/n):s>_?s<a?(n=.707106781,r=0,i=.707106781):(r=Math.sqrt(s),n=v/r,i=b/r):_<a?(n=.707106781,r=.707106781,i=0):(i=Math.sqrt(_),n=y/i,r=b/i),this.set(n,r,i,t),this}let _=Math.sqrt((h-p)*(h-p)+(u-m)*(u-m)+(d-l)*(d-l));return Math.abs(_)<.001&&(_=1),this.x=(h-p)/_,this.y=(u-m)/_,this.z=(d-l)/_,this.w=Math.acos((c+f+g-1)/2),this}setFromMatrixPosition(e){let t=e.elements;return this.x=t[12],this.y=t[13],this.z=t[14],this.w=t[15],this}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this.z=Math.min(this.z,e.z),this.w=Math.min(this.w,e.w),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this.z=Math.max(this.z,e.z),this.w=Math.max(this.w,e.w),this}clamp(e,t){return this.x=fC(this.x,e.x,t.x),this.y=fC(this.y,e.y,t.y),this.z=fC(this.z,e.z,t.z),this.w=fC(this.w,e.w,t.w),this}clampScalar(e,t){return this.x=fC(this.x,e,t),this.y=fC(this.y,e,t),this.z=fC(this.z,e,t),this.w=fC(this.w,e,t),this}clampLength(e,t){let n=this.length();return this.divideScalar(n||1).multiplyScalar(fC(n,e,t))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this.w=Math.floor(this.w),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this.w=Math.ceil(this.w),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this.w=Math.round(this.w),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this.w=Math.trunc(this.w),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this.w=-this.w,this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z+this.w*e.w}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)+Math.abs(this.w)}normalize(){return this.divideScalar(this.length()||1)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this.z+=(e.z-this.z)*t,this.w+=(e.w-this.w)*t,this}lerpVectors(e,t,n){return this.x=e.x+(t.x-e.x)*n,this.y=e.y+(t.y-e.y)*n,this.z=e.z+(t.z-e.z)*n,this.w=e.w+(t.w-e.w)*n,this}equals(e){return e.x===this.x&&e.y===this.y&&e.z===this.z&&e.w===this.w}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this.z=e[t+2],this.w=e[t+3],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e[t+2]=this.z,e[t+3]=this.w,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this.z=e.getZ(t),this.w=e.getW(t),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this.w=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z,yield this.w}},IC=class extends sC{constructor(e=1,t=1,n={}){super(),n=Object.assign({generateMipmaps:!1,internalFormat:null,minFilter:Dx,depthBuffer:!0,stencilBuffer:!1,resolveColorBuffer:!0,resolveDepthBuffer:!0,resolveStencilBuffer:!0,storeMultisampledColorBuffer:!0,storeMultisampledDepthBuffer:!0,storeMultisampledStencilBuffer:!0,depthTexture:null,samples:0,count:1,depth:1,multiview:!1,useArrayDepthTexture:!1},n),this.isRenderTarget=!0,this.width=e,this.height=t,this.depth=n.depth,this.scissor=new FC(0,0,e,t),this.scissorTest=!1,this.viewport=new FC(0,0,e,t),this.textures=[];let r=new PC({width:e,height:t,depth:n.depth}),i=n.count;for(let e=0;e<i;e++)this.textures[e]=r.clone(),this.textures[e].isRenderTargetTexture=!0,this.textures[e].renderTarget=this;this._setTextureOptions(n),this.depthBuffer=n.depthBuffer,this.stencilBuffer=n.stencilBuffer,this.resolveColorBuffer=n.resolveColorBuffer,this.resolveDepthBuffer=n.resolveDepthBuffer,this.resolveStencilBuffer=n.resolveStencilBuffer,this.storeMultisampledColorBuffer=n.storeMultisampledColorBuffer,this.storeMultisampledDepthBuffer=n.storeMultisampledDepthBuffer,this.storeMultisampledStencilBuffer=n.storeMultisampledStencilBuffer,this._depthTexture=null,this.depthTexture=n.depthTexture,this.samples=n.samples,this.multiview=n.multiview,this.useArrayDepthTexture=n.useArrayDepthTexture}_setTextureOptions(e={}){let t={minFilter:Dx,generateMipmaps:!1,flipY:!1,internalFormat:null};e.mapping!==void 0&&(t.mapping=e.mapping),e.wrapS!==void 0&&(t.wrapS=e.wrapS),e.wrapT!==void 0&&(t.wrapT=e.wrapT),e.wrapR!==void 0&&(t.wrapR=e.wrapR),e.magFilter!==void 0&&(t.magFilter=e.magFilter),e.minFilter!==void 0&&(t.minFilter=e.minFilter),e.format!==void 0&&(t.format=e.format),e.type!==void 0&&(t.type=e.type),e.anisotropy!==void 0&&(t.anisotropy=e.anisotropy),e.colorSpace!==void 0&&(t.colorSpace=e.colorSpace),e.flipY!==void 0&&(t.flipY=e.flipY),e.generateMipmaps!==void 0&&(t.generateMipmaps=e.generateMipmaps),e.internalFormat!==void 0&&(t.internalFormat=e.internalFormat);for(let e=0;e<this.textures.length;e++)this.textures[e].setValues(t)}get texture(){return this.textures[0]}set texture(e){this.textures[0]=e}set depthTexture(e){this._depthTexture!==null&&this._depthTexture.renderTarget===this&&(this._depthTexture.renderTarget=null),e!==null&&e.renderTarget===null&&(e.renderTarget=this),this._depthTexture=e}get depthTexture(){return this._depthTexture}setSize(e,t,n=1){if(this.width!==e||this.height!==t||this.depth!==n){this.width=e,this.height=t,this.depth=n;for(let r=0,i=this.textures.length;r<i;r++)this.textures[r].image.width=e,this.textures[r].image.height=t,this.textures[r].image.depth=n,this.textures[r].isData3DTexture!==!0&&(this.textures[r].isArrayTexture=this.textures[r].image.depth>1);this.dispose()}this.viewport.set(0,0,e,t),this.scissor.set(0,0,e,t)}clone(){return new this.constructor().copy(this)}copy(e){this.width=e.width,this.height=e.height,this.depth=e.depth,this.scissor.copy(e.scissor),this.scissorTest=e.scissorTest,this.viewport.copy(e.viewport),this.textures.length=0;for(let t=0,n=e.textures.length;t<n;t++){this.textures[t]=e.textures[t].clone(),this.textures[t].isRenderTargetTexture=!0,this.textures[t].renderTarget=this;let n=Object.assign({},e.textures[t].image);this.textures[t].source=new AC(n)}if(this.depthBuffer=e.depthBuffer,this.stencilBuffer=e.stencilBuffer,this.resolveColorBuffer=e.resolveColorBuffer,this.resolveDepthBuffer=e.resolveDepthBuffer,this.resolveStencilBuffer=e.resolveStencilBuffer,this.storeMultisampledColorBuffer=e.storeMultisampledColorBuffer,this.storeMultisampledDepthBuffer=e.storeMultisampledDepthBuffer,this.storeMultisampledStencilBuffer=e.storeMultisampledStencilBuffer,e.depthTexture!==null){if(e.depthTexture.renderTarget===e){let t=e.depthTexture.clone();t.renderTarget=null,this.depthTexture=t}else this.depthTexture=e.depthTexture}return this.samples=e.samples,this.multiview=e.multiview,this.useArrayDepthTexture=e.useArrayDepthTexture,this}dispose(){this.dispatchEvent({type:`dispose`})}},LC=class extends IC{constructor(e=1,t=1,n={}){super(e,t,n),this.isWebGLRenderTarget=!0}},RC=class extends PC{constructor(e=null,t=1,n=1,r=1){super(null),this.isDataArrayTexture=!0,this.image={data:e,width:t,height:n,depth:r},this.magFilter=wx,this.minFilter=wx,this.wrapR=Sx,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1,this.layerUpdates=/* @__PURE__ */ new Set}copy(e){return super.copy(e),this.wrapR=e.wrapR,this}addLayerUpdate(e){this.layerUpdates.add(e)}clearLayerUpdates(){this.layerUpdates.clear()}},zC=class extends PC{constructor(e=null,t=1,n=1,r=1){super(null),this.isData3DTexture=!0,this.image={data:e,width:t,height:n,depth:r},this.magFilter=wx,this.minFilter=wx,this.wrapR=Sx,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}copy(e){return super.copy(e),this.wrapR=e.wrapR,this}},BC=class e{static{e.prototype.isMatrix4=!0}constructor(e,t,n,r,i,a,o,s,c,l,u,d,f,p,m,h){this.elements=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],e!==void 0&&this.set(e,t,n,r,i,a,o,s,c,l,u,d,f,p,m,h)}set(e,t,n,r,i,a,o,s,c,l,u,d,f,p,m,h){let g=this.elements;return g[0]=e,g[4]=t,g[8]=n,g[12]=r,g[1]=i,g[5]=a,g[9]=o,g[13]=s,g[2]=c,g[6]=l,g[10]=u,g[14]=d,g[3]=f,g[7]=p,g[11]=m,g[15]=h,this}identity(){return this.set(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1),this}clone(){return new e().fromArray(this.elements)}copy(e){let t=this.elements,n=e.elements;return t[0]=n[0],t[1]=n[1],t[2]=n[2],t[3]=n[3],t[4]=n[4],t[5]=n[5],t[6]=n[6],t[7]=n[7],t[8]=n[8],t[9]=n[9],t[10]=n[10],t[11]=n[11],t[12]=n[12],t[13]=n[13],t[14]=n[14],t[15]=n[15],this}copyPosition(e){let t=this.elements,n=e.elements;return t[12]=n[12],t[13]=n[13],t[14]=n[14],this}setFromMatrix3(e){let t=e.elements;return this.set(t[0],t[3],t[6],0,t[1],t[4],t[7],0,t[2],t[5],t[8],0,0,0,0,1),this}extractBasis(e,t,n){return this.determinantAffine()===0?(e.set(1,0,0),t.set(0,1,0),n.set(0,0,1),this):(e.setFromMatrixColumn(this,0),t.setFromMatrixColumn(this,1),n.setFromMatrixColumn(this,2),this)}makeBasis(e,t,n){return this.set(e.x,t.x,n.x,0,e.y,t.y,n.y,0,e.z,t.z,n.z,0,0,0,0,1),this}extractRotation(e){if(e.determinantAffine()===0)return this.identity();let t=this.elements,n=e.elements,r=1/VC.setFromMatrixColumn(e,0).length(),i=1/VC.setFromMatrixColumn(e,1).length(),a=1/VC.setFromMatrixColumn(e,2).length();return t[0]=n[0]*r,t[1]=n[1]*r,t[2]=n[2]*r,t[3]=0,t[4]=n[4]*i,t[5]=n[5]*i,t[6]=n[6]*i,t[7]=0,t[8]=n[8]*a,t[9]=n[9]*a,t[10]=n[10]*a,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this}makeRotationFromEuler(e){let t=this.elements,n=e.x,r=e.y,i=e.z,a=Math.cos(n),o=Math.sin(n),s=Math.cos(r),c=Math.sin(r),l=Math.cos(i),u=Math.sin(i);if(e.order===`XYZ`){let e=a*l,n=a*u,r=o*l,i=o*u;t[0]=s*l,t[4]=-s*u,t[8]=c,t[1]=n+r*c,t[5]=e-i*c,t[9]=-o*s,t[2]=i-e*c,t[6]=r+n*c,t[10]=a*s}else if(e.order===`YXZ`){let e=s*l,n=s*u,r=c*l,i=c*u;t[0]=e+i*o,t[4]=r*o-n,t[8]=a*c,t[1]=a*u,t[5]=a*l,t[9]=-o,t[2]=n*o-r,t[6]=i+e*o,t[10]=a*s}else if(e.order===`ZXY`){let e=s*l,n=s*u,r=c*l,i=c*u;t[0]=e-i*o,t[4]=-a*u,t[8]=r+n*o,t[1]=n+r*o,t[5]=a*l,t[9]=i-e*o,t[2]=-a*c,t[6]=o,t[10]=a*s}else if(e.order===`ZYX`){let e=a*l,n=a*u,r=o*l,i=o*u;t[0]=s*l,t[4]=r*c-n,t[8]=e*c+i,t[1]=s*u,t[5]=i*c+e,t[9]=n*c-r,t[2]=-c,t[6]=o*s,t[10]=a*s}else if(e.order===`YZX`){let e=a*s,n=a*c,r=o*s,i=o*c;t[0]=s*l,t[4]=i-e*u,t[8]=r*u+n,t[1]=u,t[5]=a*l,t[9]=-o*l,t[2]=-c*l,t[6]=n*u+r,t[10]=e-i*u}else if(e.order===`XZY`){let e=a*s,n=a*c,r=o*s,i=o*c;t[0]=s*l,t[4]=-u,t[8]=c*l,t[1]=e*u+i,t[5]=a*l,t[9]=n*u-r,t[2]=r*u-n,t[6]=o*l,t[10]=i*u+e}return t[3]=0,t[7]=0,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this}makeRotationFromQuaternion(e){return this.compose(UC,e,WC)}lookAt(e,t,n){let r=this.elements;return qC.subVectors(e,t),qC.lengthSq()===0&&(qC.z=1),qC.normalize(),GC.crossVectors(n,qC),GC.lengthSq()===0&&(Math.abs(n.z)===1?qC.x+=1e-4:qC.z+=1e-4,qC.normalize(),GC.crossVectors(n,qC)),GC.normalize(),KC.crossVectors(qC,GC),r[0]=GC.x,r[4]=KC.x,r[8]=qC.x,r[1]=GC.y,r[5]=KC.y,r[9]=qC.y,r[2]=GC.z,r[6]=KC.z,r[10]=qC.z,this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,t){let n=e.elements,r=t.elements,i=this.elements,a=n[0],o=n[4],s=n[8],c=n[12],l=n[1],u=n[5],d=n[9],f=n[13],p=n[2],m=n[6],h=n[10],g=n[14],_=n[3],v=n[7],y=n[11],b=n[15],x=r[0],S=r[4],C=r[8],w=r[12],T=r[1],E=r[5],D=r[9],O=r[13],k=r[2],A=r[6],ee=r[10],te=r[14],j=r[3],ne=r[7],re=r[11],M=r[15];return i[0]=a*x+o*T+s*k+c*j,i[4]=a*S+o*E+s*A+c*ne,i[8]=a*C+o*D+s*ee+c*re,i[12]=a*w+o*O+s*te+c*M,i[1]=l*x+u*T+d*k+f*j,i[5]=l*S+u*E+d*A+f*ne,i[9]=l*C+u*D+d*ee+f*re,i[13]=l*w+u*O+d*te+f*M,i[2]=p*x+m*T+h*k+g*j,i[6]=p*S+m*E+h*A+g*ne,i[10]=p*C+m*D+h*ee+g*re,i[14]=p*w+m*O+h*te+g*M,i[3]=_*x+v*T+y*k+b*j,i[7]=_*S+v*E+y*A+b*ne,i[11]=_*C+v*D+y*ee+b*re,i[15]=_*w+v*O+y*te+b*M,this}multiplyScalar(e){let t=this.elements;return t[0]*=e,t[4]*=e,t[8]*=e,t[12]*=e,t[1]*=e,t[5]*=e,t[9]*=e,t[13]*=e,t[2]*=e,t[6]*=e,t[10]*=e,t[14]*=e,t[3]*=e,t[7]*=e,t[11]*=e,t[15]*=e,this}determinant(){let e=this.elements,t=e[0],n=e[4],r=e[8],i=e[12],a=e[1],o=e[5],s=e[9],c=e[13],l=e[2],u=e[6],d=e[10],f=e[14],p=e[3],m=e[7],h=e[11],g=e[15],_=s*f-c*d,v=o*f-c*u,y=o*d-s*u,b=a*f-c*l,x=a*d-s*l,S=a*u-o*l;return t*(m*_-h*v+g*y)-n*(p*_-h*b+g*x)+r*(p*v-m*b+g*S)-i*(p*y-m*x+h*S)}determinantAffine(){let e=this.elements,t=e[0],n=e[4],r=e[8],i=e[1],a=e[5],o=e[9],s=e[2],c=e[6],l=e[10];return t*(a*l-o*c)-n*(i*l-o*s)+r*(i*c-a*s)}transpose(){let e=this.elements,t;return t=e[1],e[1]=e[4],e[4]=t,t=e[2],e[2]=e[8],e[8]=t,t=e[6],e[6]=e[9],e[9]=t,t=e[3],e[3]=e[12],e[12]=t,t=e[7],e[7]=e[13],e[13]=t,t=e[11],e[11]=e[14],e[14]=t,this}setPosition(e,t,n){let r=this.elements;return e.isVector3?(r[12]=e.x,r[13]=e.y,r[14]=e.z):(r[12]=e,r[13]=t,r[14]=n),this}invert(){let e=this.elements,t=e[0],n=e[1],r=e[2],i=e[3],a=e[4],o=e[5],s=e[6],c=e[7],l=e[8],u=e[9],d=e[10],f=e[11],p=e[12],m=e[13],h=e[14],g=e[15],_=t*o-n*a,v=t*s-r*a,y=t*c-i*a,b=n*s-r*o,x=n*c-i*o,S=r*c-i*s,C=l*m-u*p,w=l*h-d*p,T=l*g-f*p,E=u*h-d*m,D=u*g-f*m,O=d*g-f*h,k=_*O-v*D+y*E+b*T-x*w+S*C;if(k===0)return this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);let A=1/k;return e[0]=(o*O-s*D+c*E)*A,e[1]=(r*D-n*O-i*E)*A,e[2]=(m*S-h*x+g*b)*A,e[3]=(d*x-u*S-f*b)*A,e[4]=(s*T-a*O-c*w)*A,e[5]=(t*O-r*T+i*w)*A,e[6]=(h*y-p*S-g*v)*A,e[7]=(l*S-d*y+f*v)*A,e[8]=(a*D-o*T+c*C)*A,e[9]=(n*T-t*D-i*C)*A,e[10]=(p*x-m*y+g*_)*A,e[11]=(u*y-l*x-f*_)*A,e[12]=(o*w-a*E-s*C)*A,e[13]=(t*E-n*w+r*C)*A,e[14]=(m*v-p*b-h*_)*A,e[15]=(l*b-u*v+d*_)*A,this}scale(e){let t=this.elements,n=e.x,r=e.y,i=e.z;return t[0]*=n,t[4]*=r,t[8]*=i,t[1]*=n,t[5]*=r,t[9]*=i,t[2]*=n,t[6]*=r,t[10]*=i,t[3]*=n,t[7]*=r,t[11]*=i,this}getMaxScaleOnAxis(){let e=this.elements,t=e[0]*e[0]+e[1]*e[1]+e[2]*e[2],n=e[4]*e[4]+e[5]*e[5]+e[6]*e[6],r=e[8]*e[8]+e[9]*e[9]+e[10]*e[10];return Math.sqrt(Math.max(t,n,r))}makeTranslation(e,t,n){return e.isVector3?this.set(1,0,0,e.x,0,1,0,e.y,0,0,1,e.z,0,0,0,1):this.set(1,0,0,e,0,1,0,t,0,0,1,n,0,0,0,1),this}makeRotationX(e){let t=Math.cos(e),n=Math.sin(e);return this.set(1,0,0,0,0,t,-n,0,0,n,t,0,0,0,0,1),this}makeRotationY(e){let t=Math.cos(e),n=Math.sin(e);return this.set(t,0,n,0,0,1,0,0,-n,0,t,0,0,0,0,1),this}makeRotationZ(e){let t=Math.cos(e),n=Math.sin(e);return this.set(t,-n,0,0,n,t,0,0,0,0,1,0,0,0,0,1),this}makeRotationAxis(e,t){let n=Math.cos(t),r=Math.sin(t),i=1-n,a=e.x,o=e.y,s=e.z,c=i*a,l=i*o;return this.set(c*a+n,c*o-r*s,c*s+r*o,0,c*o+r*s,l*o+n,l*s-r*a,0,c*s-r*o,l*s+r*a,i*s*s+n,0,0,0,0,1),this}makeScale(e,t,n){return this.set(e,0,0,0,0,t,0,0,0,0,n,0,0,0,0,1),this}makeShear(e,t,n,r,i,a){return this.set(1,n,i,0,e,1,a,0,t,r,1,0,0,0,0,1),this}compose(e,t,n){let r=this.elements,i=t._x,a=t._y,o=t._z,s=t._w,c=i+i,l=a+a,u=o+o,d=i*c,f=i*l,p=i*u,m=a*l,h=a*u,g=o*u,_=s*c,v=s*l,y=s*u,b=n.x,x=n.y,S=n.z;return r[0]=(1-(m+g))*b,r[1]=(f+y)*b,r[2]=(p-v)*b,r[3]=0,r[4]=(f-y)*x,r[5]=(1-(d+g))*x,r[6]=(h+_)*x,r[7]=0,r[8]=(p+v)*S,r[9]=(h-_)*S,r[10]=(1-(d+m))*S,r[11]=0,r[12]=e.x,r[13]=e.y,r[14]=e.z,r[15]=1,this}decompose(e,t,n){let r=this.elements;e.x=r[12],e.y=r[13],e.z=r[14];let i=this.determinantAffine();if(i===0)return n.set(1,1,1),t.identity(),this;let a=VC.set(r[0],r[1],r[2]).length(),o=VC.set(r[4],r[5],r[6]).length(),s=VC.set(r[8],r[9],r[10]).length();i<0&&(a=-a),HC.copy(this);let c=1/a,l=1/o,u=1/s;return HC.elements[0]*=c,HC.elements[1]*=c,HC.elements[2]*=c,HC.elements[4]*=l,HC.elements[5]*=l,HC.elements[6]*=l,HC.elements[8]*=u,HC.elements[9]*=u,HC.elements[10]*=u,t.setFromRotationMatrix(HC),n.x=a,n.y=o,n.z=s,this}makePerspective(e,t,n,r,i,a,o=XS,s=!1){let c=this.elements,l=2*i/(t-e),u=2*i/(n-r),d=(t+e)/(t-e),f=(n+r)/(n-r),p,m;if(s)p=i/(a-i),m=a*i/(a-i);else if(o===2e3)p=-(a+i)/(a-i),m=-2*a*i/(a-i);else if(o===2001)p=-a/(a-i),m=-a*i/(a-i);else throw Error(`THREE.Matrix4.makePerspective(): Invalid coordinate system: `+o);return c[0]=l,c[4]=0,c[8]=d,c[12]=0,c[1]=0,c[5]=u,c[9]=f,c[13]=0,c[2]=0,c[6]=0,c[10]=p,c[14]=m,c[3]=0,c[7]=0,c[11]=-1,c[15]=0,this}makeOrthographic(e,t,n,r,i,a,o=XS,s=!1){let c=this.elements,l=2/(t-e),u=2/(n-r),d=-(t+e)/(t-e),f=-(n+r)/(n-r),p,m;if(s)p=1/(a-i),m=a/(a-i);else if(o===2e3)p=-2/(a-i),m=-(a+i)/(a-i);else if(o===2001)p=-1/(a-i),m=-i/(a-i);else throw Error(`THREE.Matrix4.makeOrthographic(): Invalid coordinate system: `+o);return c[0]=l,c[4]=0,c[8]=0,c[12]=d,c[1]=0,c[5]=u,c[9]=0,c[13]=f,c[2]=0,c[6]=0,c[10]=p,c[14]=m,c[3]=0,c[7]=0,c[11]=0,c[15]=1,this}equals(e){let t=this.elements,n=e.elements;for(let e=0;e<16;e++)if(t[e]!==n[e])return!1;return!0}fromArray(e,t=0){for(let n=0;n<16;n++)this.elements[n]=e[n+t];return this}toArray(e=[],t=0){let n=this.elements;return e[t]=n[0],e[t+1]=n[1],e[t+2]=n[2],e[t+3]=n[3],e[t+4]=n[4],e[t+5]=n[5],e[t+6]=n[6],e[t+7]=n[7],e[t+8]=n[8],e[t+9]=n[9],e[t+10]=n[10],e[t+11]=n[11],e[t+12]=n[12],e[t+13]=n[13],e[t+14]=n[14],e[t+15]=n[15],e}},VC=/*@__PURE__*/ new X,HC=/*@__PURE__*/ new BC,UC=/*@__PURE__*/ new X(0,0,0),WC=/*@__PURE__*/ new X(1,1,1),GC=/*@__PURE__*/ new X,KC=/*@__PURE__*/ new X,qC=/*@__PURE__*/ new X,JC=/*@__PURE__*/ new BC,YC=/*@__PURE__*/ new _C,XC=class e{constructor(t=0,n=0,r=0,i=e.DEFAULT_ORDER){this.isEuler=!0,this._x=t,this._y=n,this._z=r,this._order=i}get x(){return this._x}set x(e){this._x=e,this._onChangeCallback()}get y(){return this._y}set y(e){this._y=e,this._onChangeCallback()}get z(){return this._z}set z(e){this._z=e,this._onChangeCallback()}get order(){return this._order}set order(e){this._order=e,this._onChangeCallback()}set(e,t,n,r=this._order){return this._x=e,this._y=t,this._z=n,this._order=r,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._order)}copy(e){return this._x=e._x,this._y=e._y,this._z=e._z,this._order=e._order,this._onChangeCallback(),this}setFromRotationMatrix(e,t=this._order,n=!0){let r=e.elements,i=r[0],a=r[4],o=r[8],s=r[1],c=r[5],l=r[9],u=r[2],d=r[6],f=r[10];switch(t){case`XYZ`:this._y=Math.asin(fC(o,-1,1)),Math.abs(o)<.9999999?(this._x=Math.atan2(-l,f),this._z=Math.atan2(-a,i)):(this._x=Math.atan2(d,c),this._z=0);break;case`YXZ`:this._x=Math.asin(-fC(l,-1,1)),Math.abs(l)<.9999999?(this._y=Math.atan2(o,f),this._z=Math.atan2(s,c)):(this._y=Math.atan2(-u,i),this._z=0);break;case`ZXY`:this._x=Math.asin(fC(d,-1,1)),Math.abs(d)<.9999999?(this._y=Math.atan2(-u,f),this._z=Math.atan2(-a,c)):(this._y=0,this._z=Math.atan2(s,i));break;case`ZYX`:this._y=Math.asin(-fC(u,-1,1)),Math.abs(u)<.9999999?(this._x=Math.atan2(d,f),this._z=Math.atan2(s,i)):(this._x=0,this._z=Math.atan2(-a,c));break;case`YZX`:this._z=Math.asin(fC(s,-1,1)),Math.abs(s)<.9999999?(this._x=Math.atan2(-l,c),this._y=Math.atan2(-u,i)):(this._x=0,this._y=Math.atan2(o,f));break;case`XZY`:this._z=Math.asin(-fC(a,-1,1)),Math.abs(a)<.9999999?(this._x=Math.atan2(d,c),this._y=Math.atan2(o,i)):(this._x=Math.atan2(-l,f),this._y=0);break;default:q(`Euler: .setFromRotationMatrix() encountered an unknown order: `+t)}return this._order=t,n===!0&&this._onChangeCallback(),this}setFromQuaternion(e,t,n){return JC.makeRotationFromQuaternion(e),this.setFromRotationMatrix(JC,t,n)}setFromVector3(e,t=this._order){return this.set(e.x,e.y,e.z,t)}reorder(e){return YC.setFromEuler(this),this.setFromQuaternion(YC,e)}equals(e){return e._x===this._x&&e._y===this._y&&e._z===this._z&&e._order===this._order}fromArray(e){return this._x=e[0],this._y=e[1],this._z=e[2],e[3]!==void 0&&(this._order=e[3]),this._onChangeCallback(),this}toArray(e=[],t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,e[t+3]=this._order,e}_onChange(e){return this._onChangeCallback=e,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._order}};XC.DEFAULT_ORDER=`XYZ`;var ZC=class{constructor(){this.mask=1}set(e){this.mask=(1<<e|0)>>>0}enable(e){this.mask|=1<<e|0}enableAll(){this.mask=-1}toggle(e){this.mask^=1<<e|0}disable(e){this.mask&=~(1<<e|0)}disableAll(){this.mask=0}test(e){return(this.mask&e.mask)!==0}isEnabled(e){return!!(this.mask&(1<<e|0))}},QC=0,$C=/*@__PURE__*/ new X,ew=/*@__PURE__*/ new _C,tw=/*@__PURE__*/ new BC,nw=/*@__PURE__*/ new X,rw=/*@__PURE__*/ new X,iw=/*@__PURE__*/ new X,aw=/*@__PURE__*/ new _C,ow=/*@__PURE__*/ new X(1,0,0),sw=/*@__PURE__*/ new X(0,1,0),cw=/*@__PURE__*/ new X(0,0,1),lw={type:`added`},uw={type:`removed`},dw={type:`childadded`,child:null},fw={type:`childremoved`,child:null},pw=class e extends sC{constructor(){super(),this.isObject3D=!0,Object.defineProperty(this,"id",{value:QC++}),this.uuid=dC(),this.name=``,this.type=`Object3D`,this.parent=null,this.children=[],this.up=e.DEFAULT_UP.clone();let t=new X,n=new XC,r=new _C,i=new X(1,1,1);function a(){r.setFromEuler(n,!1)}function o(){n.setFromQuaternion(r,void 0,!1)}n._onChange(a),r._onChange(o),Object.defineProperties(this,{position:{configurable:!0,enumerable:!0,value:t},rotation:{configurable:!0,enumerable:!0,value:n},quaternion:{configurable:!0,enumerable:!0,value:r},scale:{configurable:!0,enumerable:!0,value:i},modelViewMatrix:{value:new BC},normalMatrix:{value:new Z}}),this.matrix=new BC,this.matrixWorld=new BC,this.matrixAutoUpdate=e.DEFAULT_MATRIX_AUTO_UPDATE,this.matrixWorldAutoUpdate=e.DEFAULT_MATRIX_WORLD_AUTO_UPDATE,this.matrixWorldNeedsUpdate=!1,this.layers=new ZC,this.visible=!0,this.castShadow=!1,this.receiveShadow=!1,this.frustumCulled=!0,this.renderOrder=0,this.animations=[],this.customDepthMaterial=void 0,this.customDistanceMaterial=void 0,this.static=!1,this.userData={},this.pivot=null}onBeforeShadow(){}onAfterShadow(){}onBeforeRender(){}onAfterRender(){}applyMatrix4(e){this.matrixAutoUpdate&&this.updateMatrix(),this.matrix.premultiply(e),this.matrix.decompose(this.position,this.quaternion,this.scale)}applyQuaternion(e){return this.quaternion.premultiply(e),this}setRotationFromAxisAngle(e,t){this.quaternion.setFromAxisAngle(e,t)}setRotationFromEuler(e){this.quaternion.setFromEuler(e,!0)}setRotationFromMatrix(e){this.quaternion.setFromRotationMatrix(e)}setRotationFromQuaternion(e){this.quaternion.copy(e)}rotateOnAxis(e,t){return ew.setFromAxisAngle(e,t),this.quaternion.multiply(ew),this}rotateOnWorldAxis(e,t){return ew.setFromAxisAngle(e,t),this.quaternion.premultiply(ew),this}rotateX(e){return this.rotateOnAxis(ow,e)}rotateY(e){return this.rotateOnAxis(sw,e)}rotateZ(e){return this.rotateOnAxis(cw,e)}translateOnAxis(e,t){return $C.copy(e).applyQuaternion(this.quaternion),this.position.add($C.multiplyScalar(t)),this}translateX(e){return this.translateOnAxis(ow,e)}translateY(e){return this.translateOnAxis(sw,e)}translateZ(e){return this.translateOnAxis(cw,e)}localToWorld(e){return this.updateWorldMatrix(!0,!1),e.applyMatrix4(this.matrixWorld)}worldToLocal(e){return this.updateWorldMatrix(!0,!1),e.applyMatrix4(tw.copy(this.matrixWorld).invert())}lookAt(e,t,n){e.isVector3?nw.copy(e):nw.set(e,t,n);let r=this.parent;this.updateWorldMatrix(!0,!1),rw.setFromMatrixPosition(this.matrixWorld),this.isCamera||this.isLight?tw.lookAt(rw,nw,this.up):tw.lookAt(nw,rw,this.up),this.quaternion.setFromRotationMatrix(tw),r&&(tw.extractRotation(r.matrixWorld),ew.setFromRotationMatrix(tw),this.quaternion.premultiply(ew.invert()))}add(e){if(arguments.length>1){for(let e=0;e<arguments.length;e++)this.add(arguments[e]);return this}return e===this?(J(`Object3D.add: object can't be added as a child of itself.`,e),this):(e&&e.isObject3D?(e.removeFromParent(),e.parent=this,this.children.push(e),e.dispatchEvent(lw),dw.child=e,this.dispatchEvent(dw),dw.child=null):J(`Object3D.add: object not an instance of THREE.Object3D.`,e),this)}remove(e){if(arguments.length>1){for(let e=0;e<arguments.length;e++)this.remove(arguments[e]);return this}let t=this.children.indexOf(e);return t!==-1&&(e.parent=null,this.children.splice(t,1),e.dispatchEvent(uw),fw.child=e,this.dispatchEvent(fw),fw.child=null),this}removeFromParent(){let e=this.parent;return e!==null&&e.remove(this),this}clear(){return this.remove(...this.children)}attach(e){return this.updateWorldMatrix(!0,!1),tw.copy(this.matrixWorld).invert(),e.parent!==null&&(e.parent.updateWorldMatrix(!0,!1),tw.multiply(e.parent.matrixWorld)),e.applyMatrix4(tw),e.removeFromParent(),e.parent=this,this.children.push(e),e.updateWorldMatrix(!1,!0),e.dispatchEvent(lw),dw.child=e,this.dispatchEvent(dw),dw.child=null,this}getObjectById(e){return this.getObjectByProperty(`id`,e)}getObjectByName(e){return this.getObjectByProperty(`name`,e)}getObjectByProperty(e,t){if(this[e]===t)return this;for(let n=0,r=this.children.length;n<r;n++){let r=this.children[n].getObjectByProperty(e,t);if(r!==void 0)return r}}getObjectsByProperty(e,t,n=[]){this[e]===t&&n.push(this);let r=this.children;for(let i=0,a=r.length;i<a;i++)r[i].getObjectsByProperty(e,t,n);return n}getWorldPosition(e){return this.updateWorldMatrix(!0,!1),e.setFromMatrixPosition(this.matrixWorld)}getWorldQuaternion(e){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose(rw,e,iw),e}getWorldScale(e){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose(rw,aw,e),e}getWorldDirection(e){this.updateWorldMatrix(!0,!1);let t=this.matrixWorld.elements;return e.set(t[8],t[9],t[10]).normalize()}raycast(){}intersectsFrustum(){}traverse(e){e(this);let t=this.children;for(let n=0,r=t.length;n<r;n++)t[n].traverse(e)}traverseVisible(e){if(this.visible===!1)return;e(this);let t=this.children;for(let n=0,r=t.length;n<r;n++)t[n].traverseVisible(e)}traverseAncestors(e){let t=this.parent;t!==null&&(e(t),t.traverseAncestors(e))}updateMatrix(){this.matrix.compose(this.position,this.quaternion,this.scale);let e=this.pivot;if(e!==null){let t=e.x,n=e.y,r=e.z,i=this.matrix.elements;i[12]+=t-i[0]*t-i[4]*n-i[8]*r,i[13]+=n-i[1]*t-i[5]*n-i[9]*r,i[14]+=r-i[2]*t-i[6]*n-i[10]*r}this.matrixWorldNeedsUpdate=!0}updateMatrixWorld(e){this.matrixAutoUpdate&&this.updateMatrix(),(this.matrixWorldNeedsUpdate||e)&&(this.matrixWorldAutoUpdate===!0&&(this.parent===null?this.matrixWorld.copy(this.matrix):this.matrixWorld.multiplyMatrices(this.parent.matrixWorld,this.matrix)),this.matrixWorldNeedsUpdate=!1,e=!0);let t=this.children;for(let n=0,r=t.length;n<r;n++)t[n].updateMatrixWorld(e)}updateWorldMatrix(e,t,n=!1){let r=this.parent;if(e===!0&&r!==null&&r.updateWorldMatrix(!0,!1),this.matrixAutoUpdate&&this.updateMatrix(),(this.matrixWorldNeedsUpdate||n)&&(this.matrixWorldAutoUpdate===!0&&(this.parent===null?this.matrixWorld.copy(this.matrix):this.matrixWorld.multiplyMatrices(this.parent.matrixWorld,this.matrix)),this.matrixWorldNeedsUpdate=!1,n=!0),t===!0){let e=this.children;for(let t=0,r=e.length;t<r;t++)e[t].updateWorldMatrix(!1,!0,n)}}toJSON(e){let t=e===void 0||typeof e==`string`,n={};t&&(e={geometries:{},materials:{},textures:{},images:{},shapes:{},skeletons:{},animations:{},nodes:{}},n.metadata={version:4.7,type:`Object`,generator:`Object3D.toJSON`});let r={};r.uuid=this.uuid,r.type=this.type,r.name=this.name,r.castShadow=this.castShadow,r.receiveShadow=this.receiveShadow,r.visible=this.visible,r.frustumCulled=this.frustumCulled,r.renderOrder=this.renderOrder,r.static=this.static,r.matrixAutoUpdate=this.matrixAutoUpdate,Object.keys(this.userData).length>0&&(r.userData=this.userData),r.layers=this.layers.mask,r.matrix=this.matrix.toArray(),r.up=this.up.toArray(),this.pivot!==null&&(r.pivot=this.pivot.toArray()),this.morphTargetDictionary!==void 0&&(r.morphTargetDictionary=Object.assign({},this.morphTargetDictionary)),this.morphTargetInfluences!==void 0&&(r.morphTargetInfluences=this.morphTargetInfluences.slice()),this.isInstancedMesh&&(r.type=`InstancedMesh`,r.count=this.count,r.instanceMatrix=this.instanceMatrix.toJSON(),this.instanceColor!==null&&(r.instanceColor=this.instanceColor.toJSON())),this.isBatchedMesh&&(r.type=`BatchedMesh`,r.perObjectFrustumCulled=this.perObjectFrustumCulled,r.sortObjects=this.sortObjects,r.drawRanges=this._drawRanges,r.reservedRanges=this._reservedRanges,r.geometryInfo=this._geometryInfo.map(e=>({...e,boundingBox:e.boundingBox?e.boundingBox.toJSON():void 0,boundingSphere:e.boundingSphere?e.boundingSphere.toJSON():void 0})),r.instanceInfo=this._instanceInfo.map(e=>({...e})),r.availableInstanceIds=this._availableInstanceIds.slice(),r.availableGeometryIds=this._availableGeometryIds.slice(),r.nextIndexStart=this._nextIndexStart,r.nextVertexStart=this._nextVertexStart,r.geometryCount=this._geometryCount,r.maxInstanceCount=this._maxInstanceCount,r.maxVertexCount=this._maxVertexCount,r.maxIndexCount=this._maxIndexCount,r.geometryInitialized=this._geometryInitialized,r.matricesTexture=this._matricesTexture.toJSON(e),r.indirectTexture=this._indirectTexture.toJSON(e),this._colorsTexture!==null&&(r.colorsTexture=this._colorsTexture.toJSON(e)),this.boundingSphere!==null&&(r.boundingSphere=this.boundingSphere.toJSON()),this.boundingBox!==null&&(r.boundingBox=this.boundingBox.toJSON()));function i(t,n){return t[n.uuid]===void 0&&(t[n.uuid]=n.toJSON(e)),n.uuid}if(this.isScene)this.background&&(this.background.isColor?r.background=this.background.toJSON():this.background.isTexture&&(r.background=this.background.toJSON(e).uuid)),this.environment&&this.environment.isTexture&&this.environment.isRenderTargetTexture!==!0&&(r.environment=this.environment.toJSON(e).uuid);else if(this.isMesh||this.isLine||this.isPoints){r.geometry=i(e.geometries,this.geometry);let t=this.geometry.parameters;if(t!==void 0&&t.shapes!==void 0){let n=t.shapes;if(Array.isArray(n))for(let t=0,r=n.length;t<r;t++){let r=n[t];i(e.shapes,r)}else i(e.shapes,n)}}if(this.isSkinnedMesh&&(r.bindMode=this.bindMode,r.bindMatrix=this.bindMatrix.toArray(),this.skeleton!==void 0&&(i(e.skeletons,this.skeleton),r.skeleton=this.skeleton.uuid)),this.material!==void 0){if(Array.isArray(this.material)){let t=[];for(let n=0,r=this.material.length;n<r;n++)t.push(i(e.materials,this.material[n]));r.material=t}else r.material=i(e.materials,this.material)}if(this.children.length>0){r.children=[];for(let t=0;t<this.children.length;t++)r.children.push(this.children[t].toJSON(e).object)}if(this.animations.length>0){r.animations=[];for(let t=0;t<this.animations.length;t++){let n=this.animations[t];r.animations.push(i(e.animations,n))}}if(t){let t=a(e.geometries),r=a(e.materials),i=a(e.textures),o=a(e.images),s=a(e.shapes),c=a(e.skeletons),l=a(e.animations),u=a(e.nodes);t.length>0&&(n.geometries=t),r.length>0&&(n.materials=r),i.length>0&&(n.textures=i),o.length>0&&(n.images=o),s.length>0&&(n.shapes=s),c.length>0&&(n.skeletons=c),l.length>0&&(n.animations=l),u.length>0&&(n.nodes=u)}return n.object=r,n;function a(e){let t=[];for(let n in e){let r=e[n];delete r.metadata,t.push(r)}return t}}clone(e){return new this.constructor().copy(this,e)}copy(e,t=!0){if(this.name=e.name,this.up.copy(e.up),this.position.copy(e.position),this.rotation.order=e.rotation.order,this.quaternion.copy(e.quaternion),this.scale.copy(e.scale),this.pivot=e.pivot===null?null:e.pivot.clone(),this.matrix.copy(e.matrix),this.matrixWorld.copy(e.matrixWorld),this.matrixAutoUpdate=e.matrixAutoUpdate,this.matrixWorldAutoUpdate=e.matrixWorldAutoUpdate,this.matrixWorldNeedsUpdate=e.matrixWorldNeedsUpdate,this.layers.mask=e.layers.mask,this.visible=e.visible,this.castShadow=e.castShadow,this.receiveShadow=e.receiveShadow,this.frustumCulled=e.frustumCulled,this.renderOrder=e.renderOrder,this.static=e.static,this.animations=e.animations.slice(),this.userData=JSON.parse(JSON.stringify(e.userData)),t===!0)for(let t=0;t<e.children.length;t++){let n=e.children[t];this.add(n.clone())}return this}dispose(){this.dispatchEvent({type:`dispose`})}};pw.DEFAULT_UP=/*@__PURE__*/ new X(0,1,0),pw.DEFAULT_MATRIX_AUTO_UPDATE=!0,pw.DEFAULT_MATRIX_WORLD_AUTO_UPDATE=!0;var mw=class extends pw{constructor(){super(),this.isGroup=!0,this.type=`Group`}},hw={type:`move`},gw=class{constructor(){this._targetRay=null,this._grip=null,this._hand=null}getHandSpace(){return this._hand===null&&(this._hand=new mw,this._hand.matrixAutoUpdate=!1,this._hand.visible=!1,this._hand.joints={},this._hand.inputState={pinching:!1}),this._hand}getTargetRaySpace(){return this._targetRay===null&&(this._targetRay=new mw,this._targetRay.matrixAutoUpdate=!1,this._targetRay.visible=!1,this._targetRay.hasLinearVelocity=!1,this._targetRay.linearVelocity=new X,this._targetRay.hasAngularVelocity=!1,this._targetRay.angularVelocity=new X),this._targetRay}getGripSpace(){return this._grip===null&&(this._grip=new mw,this._grip.matrixAutoUpdate=!1,this._grip.visible=!1,this._grip.hasLinearVelocity=!1,this._grip.linearVelocity=new X,this._grip.hasAngularVelocity=!1,this._grip.angularVelocity=new X,this._grip.eventsEnabled=!1),this._grip}dispatchEvent(e){return this._targetRay!==null&&this._targetRay.dispatchEvent(e),this._grip!==null&&this._grip.dispatchEvent(e),this._hand!==null&&this._hand.dispatchEvent(e),this}connect(e){if(e&&e.hand){let t=this._hand;if(t)for(let n of e.hand.values())this._getHandJoint(t,n)}return this.dispatchEvent({type:`connected`,data:e}),this}disconnect(e){return this.dispatchEvent({type:`disconnected`,data:e}),this._targetRay!==null&&(this._targetRay.visible=!1),this._grip!==null&&(this._grip.visible=!1),this._hand!==null&&(this._hand.visible=!1),this}update(e,t,n){let r=null,i=null,a=null,o=this._targetRay,s=this._grip,c=this._hand;if(e&&t.session.visibilityState!==`visible-blurred`){if(c&&e.hand){a=!0;for(let r of e.hand.values()){let e=t.getJointPose(r,n),i=this._getHandJoint(c,r);e!==null&&(i.matrix.fromArray(e.transform.matrix),i.matrix.decompose(i.position,i.rotation,i.scale),i.matrixWorldNeedsUpdate=!0,i.jointRadius=e.radius),i.visible=e!==null}let r=c.joints[`index-finger-tip`],i=c.joints[`thumb-tip`],o=r.position.distanceTo(i.position);c.inputState.pinching&&o>.025?(c.inputState.pinching=!1,this.dispatchEvent({type:`pinchend`,handedness:e.handedness,target:this})):!c.inputState.pinching&&o<=.015&&(c.inputState.pinching=!0,this.dispatchEvent({type:`pinchstart`,handedness:e.handedness,target:this}))}else s!==null&&e.gripSpace&&(i=t.getPose(e.gripSpace,n),i!==null&&(s.matrix.fromArray(i.transform.matrix),s.matrix.decompose(s.position,s.rotation,s.scale),s.matrixWorldNeedsUpdate=!0,i.linearVelocity?(s.hasLinearVelocity=!0,s.linearVelocity.copy(i.linearVelocity)):s.hasLinearVelocity=!1,i.angularVelocity?(s.hasAngularVelocity=!0,s.angularVelocity.copy(i.angularVelocity)):s.hasAngularVelocity=!1,s.eventsEnabled&&s.dispatchEvent({type:`gripUpdated`,data:e,target:this})));o!==null&&(r=t.getPose(e.targetRaySpace,n),r===null&&i!==null&&(r=i),r!==null&&(o.matrix.fromArray(r.transform.matrix),o.matrix.decompose(o.position,o.rotation,o.scale),o.matrixWorldNeedsUpdate=!0,r.linearVelocity?(o.hasLinearVelocity=!0,o.linearVelocity.copy(r.linearVelocity)):o.hasLinearVelocity=!1,r.angularVelocity?(o.hasAngularVelocity=!0,o.angularVelocity.copy(r.angularVelocity)):o.hasAngularVelocity=!1,this.dispatchEvent(hw)))}return o!==null&&(o.visible=r!==null),s!==null&&(s.visible=i!==null),c!==null&&(c.visible=a!==null),this}_getHandJoint(e,t){if(e.joints[t.jointName]===void 0){let n=new mw;n.matrixAutoUpdate=!1,n.visible=!1,e.joints[t.jointName]=n,e.add(n)}return e.joints[t.jointName]}},_w={aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,rebeccapurple:6697881,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074},vw={h:0,s:0,l:0},yw={h:0,s:0,l:0};function bw(e,t,n){return n<0&&(n+=1),n>1&&--n,n<1/6?e+(t-e)*6*n:n<1/2?t:n<2/3?e+(t-e)*6*(2/3-n):e}var xw=class{constructor(e,t,n){return this.isColor=!0,this.r=1,this.g=1,this.b=1,this.set(e,t,n)}set(e,t,n){if(t===void 0&&n===void 0){let t=e;t&&t.isColor?this.copy(t):typeof t==`number`?this.setHex(t):typeof t==`string`&&this.setStyle(t)}else this.setRGB(e,t,n);return this}setScalar(e){return this.r=e,this.g=e,this.b=e,this}setHex(e,t=US){return e=Math.floor(e),this.r=(e>>16&255)/255,this.g=(e>>8&255)/255,this.b=(e&255)/255,wC.colorSpaceToWorking(this,t),this}setRGB(e,t,n,r=wC.workingColorSpace){return this.r=e,this.g=t,this.b=n,wC.colorSpaceToWorking(this,r),this}setHSL(e,t,n,r=wC.workingColorSpace){if(e=pC(e,1),t=fC(t,0,1),n=fC(n,0,1),t===0)this.r=this.g=this.b=n;else{let r=n<=.5?n*(1+t):n+t-n*t,i=2*n-r;this.r=bw(i,r,e+1/3),this.g=bw(i,r,e),this.b=bw(i,r,e-1/3)}return wC.colorSpaceToWorking(this,r),this}setStyle(e,t=US){function n(t){t!==void 0&&parseFloat(t)<1&&q(`Color: Alpha component of `+e+` will be ignored.`)}let r;if(r=/^(\w+)\(([^\)]*)\)/.exec(e)){let i,a=r[1],o=r[2];switch(a){case`rgb`:case`rgba`:if(i=/^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return n(i[4]),this.setRGB(Math.min(255,parseInt(i[1],10))/255,Math.min(255,parseInt(i[2],10))/255,Math.min(255,parseInt(i[3],10))/255,t);if(i=/^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return n(i[4]),this.setRGB(Math.min(100,parseInt(i[1],10))/100,Math.min(100,parseInt(i[2],10))/100,Math.min(100,parseInt(i[3],10))/100,t);break;case`hsl`:case`hsla`:if(i=/^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return n(i[4]),this.setHSL(parseFloat(i[1])/360,parseFloat(i[2])/100,parseFloat(i[3])/100,t);break;default:q(`Color: Unknown color model `+e)}}else if(r=/^\#([A-Fa-f\d]+)$/.exec(e)){let n=r[1],i=n.length;if(i===3)return this.setRGB(parseInt(n.charAt(0),16)/15,parseInt(n.charAt(1),16)/15,parseInt(n.charAt(2),16)/15,t);if(i===6)return this.setHex(parseInt(n,16),t);q(`Color: Invalid hex color `+e)}else if(e&&e.length>0)return this.setColorName(e,t);return this}setColorName(e,t=US){let n=_w[e.toLowerCase()];return n===void 0?q(`Color: Unknown color `+e):this.setHex(n,t),this}clone(){return new this.constructor(this.r,this.g,this.b)}copy(e){return this.r=e.r,this.g=e.g,this.b=e.b,this}copySRGBToLinear(e){return this.r=TC(e.r),this.g=TC(e.g),this.b=TC(e.b),this}copyLinearToSRGB(e){return this.r=EC(e.r),this.g=EC(e.g),this.b=EC(e.b),this}convertSRGBToLinear(){return this.copySRGBToLinear(this),this}convertLinearToSRGB(){return this.copyLinearToSRGB(this),this}getHex(e=US){return wC.workingToColorSpace(Sw.copy(this),e),Math.round(fC(Sw.r*255,0,255))*65536+Math.round(fC(Sw.g*255,0,255))*256+Math.round(fC(Sw.b*255,0,255))}getHexString(e=US){return(`000000`+this.getHex(e).toString(16)).slice(-6)}getHSL(e,t=wC.workingColorSpace){wC.workingToColorSpace(Sw.copy(this),t);let n=Sw.r,r=Sw.g,i=Sw.b,a=Math.max(n,r,i),o=Math.min(n,r,i),s,c,l=(o+a)/2;if(o===a)s=0,c=0;else{let e=a-o;switch(c=l<=.5?e/(a+o):e/(2-a-o),a){case n:s=(r-i)/e+(r<i?6:0);break;case r:s=(i-n)/e+2;break;case i:s=(n-r)/e+4}s/=6}return e.h=s,e.s=c,e.l=l,e}getRGB(e,t=wC.workingColorSpace){return wC.workingToColorSpace(Sw.copy(this),t),e.r=Sw.r,e.g=Sw.g,e.b=Sw.b,e}getStyle(e=US){wC.workingToColorSpace(Sw.copy(this),e);let t=Sw.r,n=Sw.g,r=Sw.b;return e===`srgb`?`rgb(${Math.round(t*255)},${Math.round(n*255)},${Math.round(r*255)})`:`color(${e} ${t.toFixed(3)} ${n.toFixed(3)} ${r.toFixed(3)})`}offsetHSL(e,t,n){return this.getHSL(vw),this.setHSL(vw.h+e,vw.s+t,vw.l+n)}add(e){return this.r+=e.r,this.g+=e.g,this.b+=e.b,this}addColors(e,t){return this.r=e.r+t.r,this.g=e.g+t.g,this.b=e.b+t.b,this}addScalar(e){return this.r+=e,this.g+=e,this.b+=e,this}sub(e){return this.r=Math.max(0,this.r-e.r),this.g=Math.max(0,this.g-e.g),this.b=Math.max(0,this.b-e.b),this}multiply(e){return this.r*=e.r,this.g*=e.g,this.b*=e.b,this}multiplyScalar(e){return this.r*=e,this.g*=e,this.b*=e,this}lerp(e,t){return this.r+=(e.r-this.r)*t,this.g+=(e.g-this.g)*t,this.b+=(e.b-this.b)*t,this}lerpColors(e,t,n){return this.r=e.r+(t.r-e.r)*n,this.g=e.g+(t.g-e.g)*n,this.b=e.b+(t.b-e.b)*n,this}lerpHSL(e,t){this.getHSL(vw),e.getHSL(yw);let n=mC(vw.h,yw.h,t),r=mC(vw.s,yw.s,t),i=mC(vw.l,yw.l,t);return this.setHSL(n,r,i),this}setFromVector3(e){return this.r=e.x,this.g=e.y,this.b=e.z,this}applyMatrix3(e){let t=this.r,n=this.g,r=this.b,i=e.elements;return this.r=i[0]*t+i[3]*n+i[6]*r,this.g=i[1]*t+i[4]*n+i[7]*r,this.b=i[2]*t+i[5]*n+i[8]*r,this}equals(e){return e.r===this.r&&e.g===this.g&&e.b===this.b}fromArray(e,t=0){return this.r=e[t],this.g=e[t+1],this.b=e[t+2],this}toArray(e=[],t=0){return e[t]=this.r,e[t+1]=this.g,e[t+2]=this.b,e}fromBufferAttribute(e,t){return this.r=e.getX(t),this.g=e.getY(t),this.b=e.getZ(t),this}toJSON(){return this.getHex()}*[Symbol.iterator](){yield this.r,yield this.g,yield this.b}},Sw=/*@__PURE__*/ new xw;xw.NAMES=_w;var Cw=class extends pw{constructor(){super(),this.isScene=!0,this.type=`Scene`,this.background=null,this.environment=null,this.fog=null,this.backgroundBlurriness=0,this.backgroundIntensity=1,this.backgroundRotation=new XC,this.environmentIntensity=1,this.environmentRotation=new XC,this.overrideMaterial=null,typeof __THREE_DEVTOOLS__<`u`&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent(`observe`,{detail:this}))}copy(e,t){return super.copy(e,t),e.background!==null&&(this.background=e.background.clone()),e.environment!==null&&(this.environment=e.environment.clone()),e.fog!==null&&(this.fog=e.fog.clone()),this.backgroundBlurriness=e.backgroundBlurriness,this.backgroundIntensity=e.backgroundIntensity,this.backgroundRotation.copy(e.backgroundRotation),this.environmentIntensity=e.environmentIntensity,this.environmentRotation.copy(e.environmentRotation),e.overrideMaterial!==null&&(this.overrideMaterial=e.overrideMaterial.clone()),this.matrixAutoUpdate=e.matrixAutoUpdate,this}toJSON(e){let t=super.toJSON(e);return this.fog!==null&&(t.object.fog=this.fog.toJSON()),t.object.backgroundBlurriness=this.backgroundBlurriness,t.object.backgroundIntensity=this.backgroundIntensity,t.object.backgroundRotation=this.backgroundRotation.toArray(),t.object.environmentIntensity=this.environmentIntensity,t.object.environmentRotation=this.environmentRotation.toArray(),t}},ww=/*@__PURE__*/ new X,Tw=/*@__PURE__*/ new X,Ew=/*@__PURE__*/ new X,Dw=/*@__PURE__*/ new X,Ow=/*@__PURE__*/ new X,kw=/*@__PURE__*/ new X,Aw=/*@__PURE__*/ new X,jw=/*@__PURE__*/ new X,Mw=/*@__PURE__*/ new X,Nw=/*@__PURE__*/ new X,Pw=/*@__PURE__*/ new FC,Fw=/*@__PURE__*/ new FC,Iw=/*@__PURE__*/ new FC,Lw=class e{constructor(e=new X,t=new X,n=new X){this.a=e,this.b=t,this.c=n}static getNormal(e,t,n,r){r.subVectors(n,t),ww.subVectors(e,t),r.cross(ww);let i=r.lengthSq();return i>0?r.multiplyScalar(1/Math.sqrt(i)):r.set(0,0,0)}static getBarycoord(e,t,n,r,i){ww.subVectors(r,t),Tw.subVectors(n,t),Ew.subVectors(e,t);let a=ww.dot(ww),o=ww.dot(Tw),s=ww.dot(Ew),c=Tw.dot(Tw),l=Tw.dot(Ew),u=a*c-o*o;if(u===0)return i.set(0,0,0),null;let d=1/u,f=(c*s-o*l)*d,p=(a*l-o*s)*d;return i.set(1-f-p,p,f)}static containsPoint(e,t,n,r){return this.getBarycoord(e,t,n,r,Dw)!==null&&Dw.x>=0&&Dw.y>=0&&Dw.x+Dw.y<=1}static getInterpolation(e,t,n,r,i,a,o,s){return this.getBarycoord(e,t,n,r,Dw)===null?(s.x=0,s.y=0,`z`in s&&(s.z=0),`w`in s&&(s.w=0),null):(s.setScalar(0),s.addScaledVector(i,Dw.x),s.addScaledVector(a,Dw.y),s.addScaledVector(o,Dw.z),s)}static getInterpolatedAttribute(e,t,n,r,i,a){return Pw.setScalar(0),Fw.setScalar(0),Iw.setScalar(0),Pw.fromBufferAttribute(e,t),Fw.fromBufferAttribute(e,n),Iw.fromBufferAttribute(e,r),a.setScalar(0),a.addScaledVector(Pw,i.x),a.addScaledVector(Fw,i.y),a.addScaledVector(Iw,i.z),a}static isFrontFacing(e,t,n,r){return ww.subVectors(n,t),Tw.subVectors(e,t),ww.cross(Tw).dot(r)<0}set(e,t,n){return this.a.copy(e),this.b.copy(t),this.c.copy(n),this}setFromPointsAndIndices(e,t,n,r){return this.a.copy(e[t]),this.b.copy(e[n]),this.c.copy(e[r]),this}setFromAttributeAndIndices(e,t,n,r){return this.a.fromBufferAttribute(e,t),this.b.fromBufferAttribute(e,n),this.c.fromBufferAttribute(e,r),this}clone(){return new this.constructor().copy(this)}copy(e){return this.a.copy(e.a),this.b.copy(e.b),this.c.copy(e.c),this}getArea(){return ww.subVectors(this.c,this.b),Tw.subVectors(this.a,this.b),ww.cross(Tw).length()*.5}getMidpoint(e){return e.addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)}getNormal(t){return e.getNormal(this.a,this.b,this.c,t)}getPlane(e){return e.setFromCoplanarPoints(this.a,this.b,this.c)}getBarycoord(t,n){return e.getBarycoord(t,this.a,this.b,this.c,n)}getInterpolation(t,n,r,i,a){return e.getInterpolation(t,this.a,this.b,this.c,n,r,i,a)}containsPoint(t){return e.containsPoint(t,this.a,this.b,this.c)}isFrontFacing(t){return e.isFrontFacing(this.a,this.b,this.c,t)}intersectsBox(e){return e.intersectsTriangle(this)}closestPointToPoint(e,t){let n=this.a,r=this.b,i=this.c,a,o;Ow.subVectors(r,n),kw.subVectors(i,n),jw.subVectors(e,n);let s=Ow.dot(jw),c=kw.dot(jw);if(s<=0&&c<=0)return t.copy(n);Mw.subVectors(e,r);let l=Ow.dot(Mw),u=kw.dot(Mw);if(l>=0&&u<=l)return t.copy(r);let d=s*u-l*c;if(d<=0&&s>=0&&l<=0)return a=s/(s-l),t.copy(n).addScaledVector(Ow,a);Nw.subVectors(e,i);let f=Ow.dot(Nw),p=kw.dot(Nw);if(p>=0&&f<=p)return t.copy(i);let m=f*c-s*p;if(m<=0&&c>=0&&p<=0)return o=c/(c-p),t.copy(n).addScaledVector(kw,o);let h=l*p-f*u;if(h<=0&&u-l>=0&&f-p>=0)return Aw.subVectors(i,r),o=(u-l)/(u-l+(f-p)),t.copy(r).addScaledVector(Aw,o);let g=1/(h+m+d);return a=m*g,o=d*g,t.copy(n).addScaledVector(Ow,a).addScaledVector(kw,o)}equals(e){return e.a.equals(this.a)&&e.b.equals(this.b)&&e.c.equals(this.c)}},Rw=class{constructor(e=new X(1/0,1/0,1/0),t=new X(-1/0,-1/0,-1/0)){this.isBox3=!0,this.min=e,this.max=t}set(e,t){return this.min.copy(e),this.max.copy(t),this}setFromArray(e){this.makeEmpty();for(let t=0,n=e.length;t<n;t+=3)this.expandByPoint(Bw.fromArray(e,t));return this}setFromBufferAttribute(e){this.makeEmpty();for(let t=0,n=e.count;t<n;t++)this.expandByPoint(Bw.fromBufferAttribute(e,t));return this}setFromPoints(e){this.makeEmpty();for(let t=0,n=e.length;t<n;t++)this.expandByPoint(e[t]);return this}setFromCenterAndSize(e,t){let n=Bw.copy(t).multiplyScalar(.5);return this.min.copy(e).sub(n),this.max.copy(e).add(n),this}setFromObject(e,t=!1){return this.makeEmpty(),this.expandByObject(e,t)}clone(){return new this.constructor().copy(this)}copy(e){return this.min.copy(e.min),this.max.copy(e.max),this}makeEmpty(){return this.min.x=this.min.y=this.min.z=1/0,this.max.x=this.max.y=this.max.z=-1/0,this}isEmpty(){return this.max.x<this.min.x||this.max.y<this.min.y||this.max.z<this.min.z}getCenter(e){return this.isEmpty()?e.set(0,0,0):e.addVectors(this.min,this.max).multiplyScalar(.5)}getSize(e){return this.isEmpty()?e.set(0,0,0):e.subVectors(this.max,this.min)}expandByPoint(e){return this.min.min(e),this.max.max(e),this}expandByVector(e){return this.min.sub(e),this.max.add(e),this}expandByScalar(e){return this.min.addScalar(-e),this.max.addScalar(e),this}expandByObject(e,t=!1){e.updateWorldMatrix(!1,!1);let n=e.geometry;if(n!==void 0){let r=n.getAttribute(`position`);if(t===!0&&r!==void 0&&e.isInstancedMesh!==!0)for(let t=0,n=r.count;t<n;t++)e.isMesh===!0?e.getVertexPosition(t,Bw):Bw.fromBufferAttribute(r,t),Bw.applyMatrix4(e.matrixWorld),this.expandByPoint(Bw);else e.boundingBox===void 0?(n.boundingBox===null&&n.computeBoundingBox(),Vw.copy(n.boundingBox)):(e.boundingBox===null&&e.computeBoundingBox(),Vw.copy(e.boundingBox)),Vw.applyMatrix4(e.matrixWorld),this.union(Vw)}let r=e.children;for(let e=0,n=r.length;e<n;e++)this.expandByObject(r[e],t);return this}containsPoint(e){return e.x>=this.min.x&&e.x<=this.max.x&&e.y>=this.min.y&&e.y<=this.max.y&&e.z>=this.min.z&&e.z<=this.max.z}containsBox(e){return this.min.x<=e.min.x&&e.max.x<=this.max.x&&this.min.y<=e.min.y&&e.max.y<=this.max.y&&this.min.z<=e.min.z&&e.max.z<=this.max.z}getParameter(e,t){return t.set((e.x-this.min.x)/(this.max.x-this.min.x),(e.y-this.min.y)/(this.max.y-this.min.y),(e.z-this.min.z)/(this.max.z-this.min.z))}intersectsBox(e){return e.max.x>=this.min.x&&e.min.x<=this.max.x&&e.max.y>=this.min.y&&e.min.y<=this.max.y&&e.max.z>=this.min.z&&e.min.z<=this.max.z}intersectsSphere(e){return this.clampPoint(e.center,Bw),Bw.distanceToSquared(e.center)<=e.radius*e.radius}intersectsPlane(e){let t,n;return e.normal.x>0?(t=e.normal.x*this.min.x,n=e.normal.x*this.max.x):(t=e.normal.x*this.max.x,n=e.normal.x*this.min.x),e.normal.y>0?(t+=e.normal.y*this.min.y,n+=e.normal.y*this.max.y):(t+=e.normal.y*this.max.y,n+=e.normal.y*this.min.y),e.normal.z>0?(t+=e.normal.z*this.min.z,n+=e.normal.z*this.max.z):(t+=e.normal.z*this.max.z,n+=e.normal.z*this.min.z),t<=-e.constant&&n>=-e.constant}intersectsTriangle(e){if(this.isEmpty())return!1;this.getCenter(Jw),Yw.subVectors(this.max,Jw),Hw.subVectors(e.a,Jw),Uw.subVectors(e.b,Jw),Ww.subVectors(e.c,Jw),Gw.subVectors(Uw,Hw),Kw.subVectors(Ww,Uw),qw.subVectors(Hw,Ww);let t=[0,-Gw.z,Gw.y,0,-Kw.z,Kw.y,0,-qw.z,qw.y,Gw.z,0,-Gw.x,Kw.z,0,-Kw.x,qw.z,0,-qw.x,-Gw.y,Gw.x,0,-Kw.y,Kw.x,0,-qw.y,qw.x,0];return!Qw(t,Hw,Uw,Ww,Yw)||(t=[1,0,0,0,1,0,0,0,1],!Qw(t,Hw,Uw,Ww,Yw))?!1:(Xw.crossVectors(Gw,Kw),t=[Xw.x,Xw.y,Xw.z],Qw(t,Hw,Uw,Ww,Yw))}clampPoint(e,t){return t.copy(e).clamp(this.min,this.max)}distanceToPoint(e){return this.clampPoint(e,Bw).distanceTo(e)}getBoundingSphere(e){return this.isEmpty()?e.makeEmpty():(this.getCenter(e.center),e.radius=this.getSize(Bw).length()*.5),e}intersect(e){return this.min.max(e.min),this.max.min(e.max),this.isEmpty()&&this.makeEmpty(),this}union(e){return this.min.min(e.min),this.max.max(e.max),this}applyMatrix4(e){return this.isEmpty()?this:(zw[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(e),zw[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(e),zw[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(e),zw[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(e),zw[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(e),zw[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(e),zw[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(e),zw[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(e),this.setFromPoints(zw),this)}translate(e){return this.min.add(e),this.max.add(e),this}equals(e){return e.min.equals(this.min)&&e.max.equals(this.max)}toJSON(){return{min:this.min.toArray(),max:this.max.toArray()}}fromJSON(e){return this.min.fromArray(e.min),this.max.fromArray(e.max),this}},zw=[/*@__PURE__*/ new X,/*@__PURE__*/ new X,/*@__PURE__*/ new X,/*@__PURE__*/ new X,/*@__PURE__*/ new X,/*@__PURE__*/ new X,/*@__PURE__*/ new X,/*@__PURE__*/ new X],Bw=/*@__PURE__*/ new X,Vw=/*@__PURE__*/ new Rw,Hw=/*@__PURE__*/ new X,Uw=/*@__PURE__*/ new X,Ww=/*@__PURE__*/ new X,Gw=/*@__PURE__*/ new X,Kw=/*@__PURE__*/ new X,qw=/*@__PURE__*/ new X,Jw=/*@__PURE__*/ new X,Yw=/*@__PURE__*/ new X,Xw=/*@__PURE__*/ new X,Zw=/*@__PURE__*/ new X;function Qw(e,t,n,r,i){for(let a=0,o=e.length-3;a<=o;a+=3){Zw.fromArray(e,a);let o=i.x*Math.abs(Zw.x)+i.y*Math.abs(Zw.y)+i.z*Math.abs(Zw.z),s=t.dot(Zw),c=n.dot(Zw),l=r.dot(Zw);if(Math.max(-Math.max(s,c,l),Math.min(s,c,l))>o)return!1}return!0}var $w=/*@__PURE__*/ new X,eT=/*@__PURE__*/ new Y,tT=0,nT=class extends sC{constructor(e,t,n=!1){if(super(),Array.isArray(e))throw TypeError(`THREE.BufferAttribute: array should be a Typed Array.`);this.isBufferAttribute=!0,Object.defineProperty(this,"id",{value:tT++}),this.name=``,this.array=e,this.itemSize=t,this.count=e===void 0?0:e.length/t,this.normalized=n,this.usage=JS,this.updateRanges=[],this.gpuType=Ix,this.version=0}onUploadCallback(){}set needsUpdate(e){e===!0&&this.version++}setUsage(e){return this.usage=e,this}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}copy(e){return this.name=e.name,this.array=new e.array.constructor(e.array),this.itemSize=e.itemSize,this.count=e.count,this.normalized=e.normalized,this.usage=e.usage,this.gpuType=e.gpuType,this}copyAt(e,t,n){e*=this.itemSize,n*=t.itemSize;for(let r=0,i=this.itemSize;r<i;r++)this.array[e+r]=t.array[n+r];return this}copyArray(e){return this.array.set(e),this}applyMatrix3(e){if(this.itemSize===2)for(let t=0,n=this.count;t<n;t++)eT.fromBufferAttribute(this,t),eT.applyMatrix3(e),this.setXY(t,eT.x,eT.y);else if(this.itemSize===3)for(let t=0,n=this.count;t<n;t++)$w.fromBufferAttribute(this,t),$w.applyMatrix3(e),this.setXYZ(t,$w.x,$w.y,$w.z);return this}applyMatrix4(e){for(let t=0,n=this.count;t<n;t++)$w.fromBufferAttribute(this,t),$w.applyMatrix4(e),this.setXYZ(t,$w.x,$w.y,$w.z);return this}applyNormalMatrix(e){for(let t=0,n=this.count;t<n;t++)$w.fromBufferAttribute(this,t),$w.applyNormalMatrix(e),this.setXYZ(t,$w.x,$w.y,$w.z);return this}transformDirection(e){for(let t=0,n=this.count;t<n;t++)$w.fromBufferAttribute(this,t),$w.transformDirection(e),this.setXYZ(t,$w.x,$w.y,$w.z);return this}set(e,t=0){return this.array.set(e,t),this}getComponent(e,t){let n=this.array[e*this.itemSize+t];return this.normalized&&(n=hC(n,this.array)),n}setComponent(e,t,n){return this.normalized&&(n=gC(n,this.array)),this.array[e*this.itemSize+t]=n,this}getX(e){let t=this.array[e*this.itemSize];return this.normalized&&(t=hC(t,this.array)),t}setX(e,t){return this.normalized&&(t=gC(t,this.array)),this.array[e*this.itemSize]=t,this}getY(e){let t=this.array[e*this.itemSize+1];return this.normalized&&(t=hC(t,this.array)),t}setY(e,t){return this.normalized&&(t=gC(t,this.array)),this.array[e*this.itemSize+1]=t,this}getZ(e){let t=this.array[e*this.itemSize+2];return this.normalized&&(t=hC(t,this.array)),t}setZ(e,t){return this.normalized&&(t=gC(t,this.array)),this.array[e*this.itemSize+2]=t,this}getW(e){let t=this.array[e*this.itemSize+3];return this.normalized&&(t=hC(t,this.array)),t}setW(e,t){return this.normalized&&(t=gC(t,this.array)),this.array[e*this.itemSize+3]=t,this}setXY(e,t,n){return e*=this.itemSize,this.normalized&&(t=gC(t,this.array),n=gC(n,this.array)),this.array[e+0]=t,this.array[e+1]=n,this}setXYZ(e,t,n,r){return e*=this.itemSize,this.normalized&&(t=gC(t,this.array),n=gC(n,this.array),r=gC(r,this.array)),this.array[e+0]=t,this.array[e+1]=n,this.array[e+2]=r,this}setXYZW(e,t,n,r,i){return e*=this.itemSize,this.normalized&&(t=gC(t,this.array),n=gC(n,this.array),r=gC(r,this.array),i=gC(i,this.array)),this.array[e+0]=t,this.array[e+1]=n,this.array[e+2]=r,this.array[e+3]=i,this}onUpload(e){return this.onUploadCallback=e,this}clone(){return new this.constructor(this.array,this.itemSize).copy(this)}toJSON(){let e={itemSize:this.itemSize,type:this.array.constructor.name,array:Array.from(this.array),normalized:this.normalized};return e.name=this.name,e.usage=this.usage,e.gpuType=this.gpuType,e}dispose(){this.dispatchEvent({type:`dispose`})}},rT=class extends nT{constructor(e,t,n){super(new Uint16Array(e),t,n)}},iT=class extends nT{constructor(e,t,n){super(new Uint32Array(e),t,n)}},aT=class extends nT{constructor(e,t,n){super(new Float32Array(e),t,n)}},oT=/*@__PURE__*/ new Rw,sT=/*@__PURE__*/ new X,cT=/*@__PURE__*/ new X,lT=class{constructor(e=new X,t=-1){this.isSphere=!0,this.center=e,this.radius=t}set(e,t){return this.center.copy(e),this.radius=t,this}setFromPoints(e,t){let n=this.center;t===void 0?oT.setFromPoints(e).getCenter(n):n.copy(t);let r=0;for(let t=0,i=e.length;t<i;t++)r=Math.max(r,n.distanceToSquared(e[t]));return this.radius=Math.sqrt(r),this}copy(e){return this.center.copy(e.center),this.radius=e.radius,this}isEmpty(){return this.radius<0}makeEmpty(){return this.center.set(0,0,0),this.radius=-1,this}containsPoint(e){return e.distanceToSquared(this.center)<=this.radius*this.radius}distanceToPoint(e){return e.distanceTo(this.center)-this.radius}intersectsSphere(e){let t=this.radius+e.radius;return e.center.distanceToSquared(this.center)<=t*t}intersectsBox(e){return e.intersectsSphere(this)}intersectsPlane(e){return Math.abs(e.distanceToPoint(this.center))<=this.radius}clampPoint(e,t){let n=this.center.distanceToSquared(e);return t.copy(e),n>this.radius*this.radius&&(t.sub(this.center).normalize(),t.multiplyScalar(this.radius).add(this.center)),t}getBoundingBox(e){return this.isEmpty()?(e.makeEmpty(),e):(e.set(this.center,this.center),e.expandByScalar(this.radius),e)}applyMatrix4(e){return this.center.applyMatrix4(e),this.radius*=e.getMaxScaleOnAxis(),this}translate(e){return this.center.add(e),this}expandByPoint(e){if(this.isEmpty())return this.center.copy(e),this.radius=0,this;sT.subVectors(e,this.center);let t=sT.lengthSq();if(t>this.radius*this.radius){let e=Math.sqrt(t),n=(e-this.radius)*.5;this.center.addScaledVector(sT,n/e),this.radius+=n}return this}union(e){return e.isEmpty()?this:this.isEmpty()?(this.copy(e),this):(this.center.equals(e.center)===!0?this.radius=Math.max(this.radius,e.radius):(cT.subVectors(e.center,this.center).setLength(e.radius),this.expandByPoint(sT.copy(e.center).add(cT)),this.expandByPoint(sT.copy(e.center).sub(cT))),this)}equals(e){return e.center.equals(this.center)&&e.radius===this.radius}clone(){return new this.constructor().copy(this)}toJSON(){return{radius:this.radius,center:this.center.toArray()}}fromJSON(e){return this.radius=e.radius,this.center.fromArray(e.center),this}},uT=0,dT=/*@__PURE__*/ new BC,fT=/*@__PURE__*/ new pw,pT=/*@__PURE__*/ new X,mT=/*@__PURE__*/ new Rw,hT=/*@__PURE__*/ new Rw,gT=/*@__PURE__*/ new X,_T=class e extends sC{constructor(){super(),this.isBufferGeometry=!0,Object.defineProperty(this,"id",{value:uT++}),this.uuid=dC(),this.name=``,this.type=`BufferGeometry`,this.index=null,this.indirect=null,this.indirectOffset=0,this.attributes={},this.morphAttributes={},this.morphTargetsRelative=!1,this.groups=[],this.boundingBox=null,this.boundingSphere=null,this.drawRange={start:0,count:1/0},this.userData={},this._transformed=!1}getIndex(){return this.index}setIndex(e){return this.index=Array.isArray(e)?new(ZS(e)?iT:rT)(e,1):e,this}setIndirect(e,t=0){return this.indirect=e,this.indirectOffset=t,this}getIndirect(){return this.indirect}getAttribute(e){return this.attributes[e]}setAttribute(e,t){return this.attributes[e]=t,this}deleteAttribute(e){return delete this.attributes[e],this}hasAttribute(e){return this.attributes[e]!==void 0}addGroup(e,t,n=0){this.groups.push({start:e,count:t,materialIndex:n})}clearGroups(){this.groups=[]}setDrawRange(e,t){this.drawRange.start=e,this.drawRange.count=t}applyMatrix4(e){let t=this.attributes.position;t!==void 0&&(t.applyMatrix4(e),t.needsUpdate=!0);let n=this.attributes.normal;if(n!==void 0){let t=new Z().getNormalMatrix(e);n.applyNormalMatrix(t),n.needsUpdate=!0}let r=this.attributes.tangent;return r!==void 0&&(r.transformDirection(e),r.needsUpdate=!0),this.boundingBox!==null&&this.computeBoundingBox(),this.boundingSphere!==null&&this.computeBoundingSphere(),this._transformed=!0,this}applyQuaternion(e){return dT.makeRotationFromQuaternion(e),this.applyMatrix4(dT),this}rotateX(e){return dT.makeRotationX(e),this.applyMatrix4(dT),this}rotateY(e){return dT.makeRotationY(e),this.applyMatrix4(dT),this}rotateZ(e){return dT.makeRotationZ(e),this.applyMatrix4(dT),this}translate(e,t,n){return dT.makeTranslation(e,t,n),this.applyMatrix4(dT),this}scale(e,t,n){return dT.makeScale(e,t,n),this.applyMatrix4(dT),this}lookAt(e){return fT.lookAt(e),fT.updateMatrix(),this.applyMatrix4(fT.matrix),this}center(){return this.computeBoundingBox(),this.boundingBox.getCenter(pT).negate(),this.translate(pT.x,pT.y,pT.z),this}setFromPoints(e){let t=this.getAttribute(`position`);if(t===void 0){let t=[];for(let n=0,r=e.length;n<r;n++){let r=e[n];t.push(r.x,r.y,r.z||0)}this.setAttribute(`position`,new aT(t,3))}else{let n=Math.min(e.length,t.count);for(let r=0;r<n;r++){let n=e[r];t.setXYZ(r,n.x,n.y,n.z||0)}e.length>t.count&&q(`BufferGeometry: Buffer size too small for points data. Use .dispose() and create a new geometry.`),t.needsUpdate=!0}return this}computeBoundingBox(){this.boundingBox===null&&(this.boundingBox=new Rw);let e=this.attributes.position,t=this.morphAttributes.position;if(e&&e.isGLBufferAttribute){J(`BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.`,this),this.boundingBox.set(new X(-1/0,-1/0,-1/0),new X(1/0,1/0,1/0));return}if(e!==void 0){if(this.boundingBox.setFromBufferAttribute(e),t)for(let e=0,n=t.length;e<n;e++){let n=t[e];mT.setFromBufferAttribute(n),this.morphTargetsRelative?(gT.addVectors(this.boundingBox.min,mT.min),this.boundingBox.expandByPoint(gT),gT.addVectors(this.boundingBox.max,mT.max),this.boundingBox.expandByPoint(gT)):(this.boundingBox.expandByPoint(mT.min),this.boundingBox.expandByPoint(mT.max))}}else this.boundingBox.makeEmpty();(isNaN(this.boundingBox.min.x)||isNaN(this.boundingBox.min.y)||isNaN(this.boundingBox.min.z))&&J(`BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.`,this)}computeBoundingSphere(){this.boundingSphere===null&&(this.boundingSphere=new lT);let e=this.attributes.position,t=this.morphAttributes.position;if(e&&e.isGLBufferAttribute){J(`BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere.`,this),this.boundingSphere.set(new X,1/0);return}if(e){let n=this.boundingSphere.center;if(mT.setFromBufferAttribute(e),t)for(let e=0,n=t.length;e<n;e++){let n=t[e];hT.setFromBufferAttribute(n),this.morphTargetsRelative?(gT.addVectors(mT.min,hT.min),mT.expandByPoint(gT),gT.addVectors(mT.max,hT.max),mT.expandByPoint(gT)):(mT.expandByPoint(hT.min),mT.expandByPoint(hT.max))}mT.getCenter(n);let r=0;for(let t=0,i=e.count;t<i;t++)gT.fromBufferAttribute(e,t),r=Math.max(r,n.distanceToSquared(gT));if(t)for(let i=0,a=t.length;i<a;i++){let a=t[i],o=this.morphTargetsRelative;for(let t=0,i=a.count;t<i;t++)gT.fromBufferAttribute(a,t),o&&(pT.fromBufferAttribute(e,t),gT.add(pT)),r=Math.max(r,n.distanceToSquared(gT))}this.boundingSphere.radius=Math.sqrt(r),isNaN(this.boundingSphere.radius)&&J(`BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.`,this)}}computeTangents(){let e=this.index,t=this.attributes;if(e===null||t.position===void 0||t.normal===void 0||t.uv===void 0){J(`BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)`);return}let n=t.position,r=t.normal,i=t.uv,a=this.getAttribute(`tangent`);(a===void 0||a.count!==n.count)&&(a=new nT(new Float32Array(4*n.count),4),this.setAttribute(`tangent`,a));let o=[],s=[];for(let e=0;e<n.count;e++)o[e]=new X,s[e]=new X;let c=new X,l=new X,u=new X,d=new Y,f=new Y,p=new Y,m=new X,h=new X;function g(e,t,r){c.fromBufferAttribute(n,e),l.fromBufferAttribute(n,t),u.fromBufferAttribute(n,r),d.fromBufferAttribute(i,e),f.fromBufferAttribute(i,t),p.fromBufferAttribute(i,r),l.sub(c),u.sub(c),f.sub(d),p.sub(d);let a=1/(f.x*p.y-p.x*f.y);isFinite(a)&&(m.copy(l).multiplyScalar(p.y).addScaledVector(u,-f.y).multiplyScalar(a),h.copy(u).multiplyScalar(f.x).addScaledVector(l,-p.x).multiplyScalar(a),o[e].add(m),o[t].add(m),o[r].add(m),s[e].add(h),s[t].add(h),s[r].add(h))}let _=this.groups;_.length===0&&(_=[{start:0,count:e.count}]);for(let t=0,n=_.length;t<n;++t){let n=_[t],r=n.start,i=n.count;for(let t=r,n=r+i;t<n;t+=3)g(e.getX(t+0),e.getX(t+1),e.getX(t+2))}let v=new X,y=new X,b=new X,x=new X;function S(e){b.fromBufferAttribute(r,e),x.copy(b);let t=o[e];v.copy(t),v.sub(b.multiplyScalar(b.dot(t))).normalize(),y.crossVectors(x,t);let n=y.dot(s[e])<0?-1:1;a.setXYZW(e,v.x,v.y,v.z,n)}for(let t=0,n=_.length;t<n;++t){let n=_[t],r=n.start,i=n.count;for(let t=r,n=r+i;t<n;t+=3)S(e.getX(t+0)),S(e.getX(t+1)),S(e.getX(t+2))}this._transformed=!0}computeVertexNormals(){let e=this.index,t=this.getAttribute(`position`);if(t!==void 0){let n=this.getAttribute(`normal`);if(n===void 0||n.count!==t.count)n=new nT(new Float32Array(t.count*3),3),this.setAttribute(`normal`,n);else for(let e=0,t=n.count;e<t;e++)n.setXYZ(e,0,0,0);let r=new X,i=new X,a=new X,o=new X,s=new X,c=new X,l=new X,u=new X;if(e)for(let d=0,f=e.count;d<f;d+=3){let f=e.getX(d+0),p=e.getX(d+1),m=e.getX(d+2);r.fromBufferAttribute(t,f),i.fromBufferAttribute(t,p),a.fromBufferAttribute(t,m),l.subVectors(a,i),u.subVectors(r,i),l.cross(u),o.fromBufferAttribute(n,f),s.fromBufferAttribute(n,p),c.fromBufferAttribute(n,m),o.add(l),s.add(l),c.add(l),n.setXYZ(f,o.x,o.y,o.z),n.setXYZ(p,s.x,s.y,s.z),n.setXYZ(m,c.x,c.y,c.z)}else for(let e=0,o=t.count;e<o;e+=3)r.fromBufferAttribute(t,e+0),i.fromBufferAttribute(t,e+1),a.fromBufferAttribute(t,e+2),l.subVectors(a,i),u.subVectors(r,i),l.cross(u),n.setXYZ(e+0,l.x,l.y,l.z),n.setXYZ(e+1,l.x,l.y,l.z),n.setXYZ(e+2,l.x,l.y,l.z);this.normalizeNormals(),n.needsUpdate=!0}}normalizeNormals(){let e=this.attributes.normal;for(let t=0,n=e.count;t<n;t++)gT.fromBufferAttribute(e,t),gT.normalize(),e.setXYZ(t,gT.x,gT.y,gT.z)}toNonIndexed(){function t(e,t){let n=e.array,r=e.itemSize,i=e.normalized,a=new n.constructor(t.length*r),o=0,s=0;for(let i=0,c=t.length;i<c;i++){o=e.isInterleavedBufferAttribute?t[i]*e.data.stride+e.offset:t[i]*r;for(let e=0;e<r;e++)a[s++]=n[o++]}return new nT(a,r,i)}if(this.index===null)return q(`BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed.`),this;let n=new e,r=this.index.array,i=this.attributes;for(let e in i){let a=i[e],o=t(a,r);n.setAttribute(e,o)}let a=this.morphAttributes;for(let e in a){let i=[],o=a[e];for(let e=0,n=o.length;e<n;e++){let n=o[e],a=t(n,r);i.push(a)}n.morphAttributes[e]=i}n.morphTargetsRelative=this.morphTargetsRelative;let o=this.groups;for(let e=0,t=o.length;e<t;e++){let t=o[e];n.addGroup(t.start,t.count,t.materialIndex)}return n}toJSON(){let e={metadata:{version:4.7,type:`BufferGeometry`,generator:`BufferGeometry.toJSON`}};if(e.uuid=this.uuid,e.type=this.parameters!==void 0&&this._transformed===!0?`BufferGeometry`:this.type,e.name=this.name,Object.keys(this.userData).length>0&&(e.userData=this.userData),this.parameters!==void 0&&this._transformed!==!0){let t=this.parameters;for(let n in t)t[n]!==void 0&&(e[n]=t[n]);return e}e.data={attributes:{}};let t=this.index;t!==null&&(e.data.index={type:t.array.constructor.name,array:Array.prototype.slice.call(t.array)});let n=this.attributes;for(let t in n){let r=n[t];e.data.attributes[t]=r.toJSON(e.data)}let r={},i=!1;for(let t in this.morphAttributes){let n=this.morphAttributes[t],a=[];for(let t=0,r=n.length;t<r;t++){let r=n[t];a.push(r.toJSON(e.data))}a.length>0&&(r[t]=a,i=!0)}i&&(e.data.morphAttributes=r,e.data.morphTargetsRelative=this.morphTargetsRelative);let a=this.groups;a.length>0&&(e.data.groups=JSON.parse(JSON.stringify(a)));let o=this.boundingSphere;return o!==null&&(e.data.boundingSphere=o.toJSON()),e}clone(){return new this.constructor().copy(this)}copy(e){this.index=null,this.attributes={},this.morphAttributes={},this.groups=[],this.boundingBox=null,this.boundingSphere=null;let t={};this.name=e.name;let n=e.index;n!==null&&this.setIndex(n.clone());let r=e.attributes;for(let e in r){let n=r[e];this.setAttribute(e,n.clone(t))}let i=e.morphAttributes;for(let e in i){let n=[],r=i[e];for(let e=0,i=r.length;e<i;e++)n.push(r[e].clone(t));this.morphAttributes[e]=n}this.morphTargetsRelative=e.morphTargetsRelative;let a=e.groups;for(let e=0,t=a.length;e<t;e++){let t=a[e];this.addGroup(t.start,t.count,t.materialIndex)}let o=e.boundingBox;o!==null&&(this.boundingBox=o.clone());let s=e.boundingSphere;return s!==null&&(this.boundingSphere=s.clone()),this.drawRange.start=e.drawRange.start,this.drawRange.count=e.drawRange.count,this.userData=e.userData,this._transformed=e._transformed,this}dispose(){this.dispatchEvent({type:`dispose`})}},vT=/*@__PURE__*/ new X,yT=/*@__PURE__*/ new X,bT=/*@__PURE__*/ new Z,xT=class{constructor(e=new X(1,0,0),t=0){this.isPlane=!0,this.normal=e,this.constant=t}set(e,t){return this.normal.copy(e),this.constant=t,this}setComponents(e,t,n,r){return this.normal.set(e,t,n),this.constant=r,this}setFromNormalAndCoplanarPoint(e,t){return this.normal.copy(e),this.constant=-t.dot(this.normal),this}setFromCoplanarPoints(e,t,n){let r=vT.subVectors(n,t).cross(yT.subVectors(e,t)).normalize();return this.setFromNormalAndCoplanarPoint(r,e),this}copy(e){return this.normal.copy(e.normal),this.constant=e.constant,this}normalize(){let e=1/this.normal.length();return this.normal.multiplyScalar(e),this.constant*=e,this}negate(){return this.constant*=-1,this.normal.negate(),this}distanceToPoint(e){return this.normal.dot(e)+this.constant}distanceToSphere(e){return this.distanceToPoint(e.center)-e.radius}projectPoint(e,t){return t.copy(e).addScaledVector(this.normal,-this.distanceToPoint(e))}intersectLine(e,t,n=!0){let r=e.delta(vT),i=this.normal.dot(r);if(i===0)return this.distanceToPoint(e.start)===0?t.copy(e.start):null;let a=-(e.start.dot(this.normal)+this.constant)/i;return n===!0&&(a<0||a>1)?null:t.copy(e.start).addScaledVector(r,a)}intersectsLine(e){let t=this.distanceToPoint(e.start),n=this.distanceToPoint(e.end);return t<0&&n>0||n<0&&t>0}intersectsBox(e){return e.intersectsPlane(this)}intersectsSphere(e){return e.intersectsPlane(this)}coplanarPoint(e){return e.copy(this.normal).multiplyScalar(-this.constant)}applyMatrix4(e,t){let n=t||bT.getNormalMatrix(e),r=this.coplanarPoint(vT).applyMatrix4(e),i=this.normal.applyMatrix3(n).normalize();return this.constant=-r.dot(i),this}translate(e){return this.constant-=e.dot(this.normal),this}equals(e){return e.normal.equals(this.normal)&&e.constant===this.constant}clone(){return new this.constructor().copy(this)}toJSON(){return{normal:this.normal.toArray(),constant:this.constant}}fromJSON(e){return this.normal.fromArray(e.normal),this.constant=e.constant,this}},ST=0,CT=class extends sC{constructor(){super(),this.isMaterial=!0,Object.defineProperty(this,"id",{value:ST++}),this.uuid=dC(),this.name=``,this.type=`Material`,this.blending=1,this.side=0,this.vertexColors=!1,this.opacity=1,this.transparent=!1,this.alphaHash=!1,this.blendSrc=204,this.blendDst=205,this.blendEquation=100,this.blendSrcAlpha=null,this.blendDstAlpha=null,this.blendEquationAlpha=null,this.blendColor=new xw(0,0,0),this.blendAlpha=0,this.depthFunc=3,this.depthTest=!0,this.depthWrite=!0,this.stencilWriteMask=255,this.stencilFunc=519,this.stencilRef=0,this.stencilFuncMask=255,this.stencilFail=qS,this.stencilZFail=qS,this.stencilZPass=qS,this.stencilWrite=!1,this.clippingPlanes=null,this.clipIntersection=!1,this.clipShadows=!1,this.shadowSide=null,this.colorWrite=!0,this.precision=null,this.polygonOffset=!1,this.polygonOffsetFactor=0,this.polygonOffsetUnits=0,this.dithering=!1,this.alphaToCoverage=!1,this.premultipliedAlpha=!1,this.forceSinglePass=!1,this.allowOverride=!0,this.visible=!0,this.toneMapped=!0,this.userData={},this.version=0,this._alphaTest=0}get alphaTest(){return this._alphaTest}set alphaTest(e){this._alphaTest>0!=e>0&&this.version++,this._alphaTest=e}onBeforeRender(){}onBeforeCompile(){}customProgramCacheKey(){return this.onBeforeCompile.toString()}setValues(e){if(e!==void 0)for(let t in e){let n=e[t];if(n===void 0){q(`Material: parameter '${t}' has value of undefined.`);continue}let r=this[t];if(r===void 0){q(`Material: '${t}' is not a property of THREE.${this.type}.`);continue}r&&r.isColor?r.set(n):r&&r.isVector2&&n&&n.isVector2||r&&r.isEuler&&n&&n.isEuler||r&&r.isVector3&&n&&n.isVector3?r.copy(n):this[t]=n}}toJSON(e){let t=e===void 0||typeof e==`string`;t&&(e={textures:{},images:{}});let n={metadata:{version:4.7,type:`Material`,generator:`Material.toJSON`}};n.uuid=this.uuid,n.type=this.type,n.blending=this.blending,n.side=this.side,n.shadowSide=this.shadowSide,n.vertexColors=this.vertexColors,n.opacity=this.opacity,n.transparent=this.transparent,n.blendSrc=this.blendSrc,n.blendDst=this.blendDst,n.blendEquation=this.blendEquation,n.blendSrcAlpha=this.blendSrcAlpha,n.blendDstAlpha=this.blendDstAlpha,n.blendEquationAlpha=this.blendEquationAlpha,n.blendColor=this.blendColor.getHex(),n.blendAlpha=this.blendAlpha,n.depthFunc=this.depthFunc,n.depthTest=this.depthTest,n.depthWrite=this.depthWrite,n.colorWrite=this.colorWrite,n.clipIntersection=this.clipIntersection,n.clipShadows=this.clipShadows,n.stencilWriteMask=this.stencilWriteMask,n.stencilFunc=this.stencilFunc,n.stencilRef=this.stencilRef,n.stencilFuncMask=this.stencilFuncMask,n.stencilFail=this.stencilFail,n.stencilZFail=this.stencilZFail,n.stencilZPass=this.stencilZPass,n.stencilWrite=this.stencilWrite,n.polygonOffset=this.polygonOffset,n.polygonOffsetFactor=this.polygonOffsetFactor,n.polygonOffsetUnits=this.polygonOffsetUnits,n.dithering=this.dithering,n.alphaTest=this.alphaTest,n.alphaHash=this.alphaHash,n.alphaToCoverage=this.alphaToCoverage,n.premultipliedAlpha=this.premultipliedAlpha,n.forceSinglePass=this.forceSinglePass,n.allowOverride=this.allowOverride,n.visible=this.visible,n.toneMapped=this.toneMapped,n.name=this.name,this.color&&this.color.isColor&&(n.color=this.color.getHex()),this.roughness!==void 0&&(n.roughness=this.roughness),this.metalness!==void 0&&(n.metalness=this.metalness),this.sheen!==void 0&&(n.sheen=this.sheen),this.sheenColor&&this.sheenColor.isColor&&(n.sheenColor=this.sheenColor.getHex()),this.sheenRoughness!==void 0&&(n.sheenRoughness=this.sheenRoughness),this.emissive&&this.emissive.isColor&&(n.emissive=this.emissive.getHex()),this.emissiveIntensity!==void 0&&(n.emissiveIntensity=this.emissiveIntensity),this.specular&&this.specular.isColor&&(n.specular=this.specular.getHex()),this.specularIntensity!==void 0&&(n.specularIntensity=this.specularIntensity),this.specularColor&&this.specularColor.isColor&&(n.specularColor=this.specularColor.getHex()),this.shininess!==void 0&&(n.shininess=this.shininess),this.clearcoat!==void 0&&(n.clearcoat=this.clearcoat),this.clearcoatRoughness!==void 0&&(n.clearcoatRoughness=this.clearcoatRoughness),this.clearcoatMap&&this.clearcoatMap.isTexture&&(n.clearcoatMap=this.clearcoatMap.toJSON(e).uuid),this.clearcoatRoughnessMap&&this.clearcoatRoughnessMap.isTexture&&(n.clearcoatRoughnessMap=this.clearcoatRoughnessMap.toJSON(e).uuid),this.clearcoatNormalMap&&this.clearcoatNormalMap.isTexture&&(n.clearcoatNormalMap=this.clearcoatNormalMap.toJSON(e).uuid,n.clearcoatNormalScale=this.clearcoatNormalScale.toArray()),this.sheenColorMap&&this.sheenColorMap.isTexture&&(n.sheenColorMap=this.sheenColorMap.toJSON(e).uuid),this.sheenRoughnessMap&&this.sheenRoughnessMap.isTexture&&(n.sheenRoughnessMap=this.sheenRoughnessMap.toJSON(e).uuid),this.dispersion!==void 0&&(n.dispersion=this.dispersion),this.retroreflectivity!==void 0&&(n.retroreflectivity=this.retroreflectivity),this.iridescence!==void 0&&(n.iridescence=this.iridescence),this.iridescenceIOR!==void 0&&(n.iridescenceIOR=this.iridescenceIOR),this.iridescenceThicknessRange!==void 0&&(n.iridescenceThicknessRange=this.iridescenceThicknessRange),this.iridescenceMap&&this.iridescenceMap.isTexture&&(n.iridescenceMap=this.iridescenceMap.toJSON(e).uuid),this.iridescenceThicknessMap&&this.iridescenceThicknessMap.isTexture&&(n.iridescenceThicknessMap=this.iridescenceThicknessMap.toJSON(e).uuid),this.anisotropy!==void 0&&(n.anisotropy=this.anisotropy),this.anisotropyRotation!==void 0&&(n.anisotropyRotation=this.anisotropyRotation),this.anisotropyMap&&this.anisotropyMap.isTexture&&(n.anisotropyMap=this.anisotropyMap.toJSON(e).uuid),this.map&&this.map.isTexture&&(n.map=this.map.toJSON(e).uuid),this.matcap&&this.matcap.isTexture&&(n.matcap=this.matcap.toJSON(e).uuid),this.alphaMap&&this.alphaMap.isTexture&&(n.alphaMap=this.alphaMap.toJSON(e).uuid),this.lightMap&&this.lightMap.isTexture&&(n.lightMap=this.lightMap.toJSON(e).uuid,n.lightMapIntensity=this.lightMapIntensity),this.aoMap&&this.aoMap.isTexture&&(n.aoMap=this.aoMap.toJSON(e).uuid,n.aoMapIntensity=this.aoMapIntensity),this.bumpMap&&this.bumpMap.isTexture&&(n.bumpMap=this.bumpMap.toJSON(e).uuid,n.bumpScale=this.bumpScale),this.normalMap&&this.normalMap.isTexture&&(n.normalMap=this.normalMap.toJSON(e).uuid,n.normalMapType=this.normalMapType,n.normalScale=this.normalScale.toArray()),this.displacementMap&&this.displacementMap.isTexture&&(n.displacementMap=this.displacementMap.toJSON(e).uuid,n.displacementScale=this.displacementScale,n.displacementBias=this.displacementBias),this.roughnessMap&&this.roughnessMap.isTexture&&(n.roughnessMap=this.roughnessMap.toJSON(e).uuid),this.metalnessMap&&this.metalnessMap.isTexture&&(n.metalnessMap=this.metalnessMap.toJSON(e).uuid),this.emissiveMap&&this.emissiveMap.isTexture&&(n.emissiveMap=this.emissiveMap.toJSON(e).uuid),this.specularMap&&this.specularMap.isTexture&&(n.specularMap=this.specularMap.toJSON(e).uuid),this.specularIntensityMap&&this.specularIntensityMap.isTexture&&(n.specularIntensityMap=this.specularIntensityMap.toJSON(e).uuid),this.specularColorMap&&this.specularColorMap.isTexture&&(n.specularColorMap=this.specularColorMap.toJSON(e).uuid),this.envMap&&this.envMap.isTexture&&(n.envMap=this.envMap.toJSON(e).uuid,this.combine!==void 0&&(n.combine=this.combine)),this.envMapRotation!==void 0&&(n.envMapRotation=this.envMapRotation.toArray()),this.envMapIntensity!==void 0&&(n.envMapIntensity=this.envMapIntensity),this.reflectivity!==void 0&&(n.reflectivity=this.reflectivity),this.refractionRatio!==void 0&&(n.refractionRatio=this.refractionRatio),this.gradientMap&&this.gradientMap.isTexture&&(n.gradientMap=this.gradientMap.toJSON(e).uuid),this.transmission!==void 0&&(n.transmission=this.transmission),this.transmissionMap&&this.transmissionMap.isTexture&&(n.transmissionMap=this.transmissionMap.toJSON(e).uuid),this.thickness!==void 0&&(n.thickness=this.thickness),this.thicknessMap&&this.thicknessMap.isTexture&&(n.thicknessMap=this.thicknessMap.toJSON(e).uuid),this.attenuationDistance!==void 0&&(n.attenuationDistance=this.attenuationDistance),this.attenuationColor!==void 0&&(n.attenuationColor=this.attenuationColor.getHex()),this.size!==void 0&&(n.size=this.size),this.sizeAttenuation!==void 0&&(n.sizeAttenuation=this.sizeAttenuation),Array.isArray(this.clippingPlanes)&&this.clippingPlanes.length>0&&(n.clippingPlanes=this.clippingPlanes.map(e=>e.toJSON())),this.rotation!==void 0&&(n.rotation=this.rotation),this.depthPacking!==void 0&&(n.depthPacking=this.depthPacking),this.linewidth!==void 0&&(n.linewidth=this.linewidth),this.linecap!==void 0&&(n.linecap=this.linecap),this.linejoin!==void 0&&(n.linejoin=this.linejoin),this.dashSize!==void 0&&(n.dashSize=this.dashSize),this.gapSize!==void 0&&(n.gapSize=this.gapSize),this.scale!==void 0&&(n.scale=this.scale),this.wireframe!==void 0&&(n.wireframe=this.wireframe),this.wireframeLinewidth!==void 0&&(n.wireframeLinewidth=this.wireframeLinewidth),this.wireframeLinecap!==void 0&&(n.wireframeLinecap=this.wireframeLinecap),this.wireframeLinejoin!==void 0&&(n.wireframeLinejoin=this.wireframeLinejoin),this.flatShading!==void 0&&(n.flatShading=this.flatShading),this.fog!==void 0&&(n.fog=this.fog),Object.keys(this.userData).length>0&&(n.userData=this.userData);function r(e){let t=[];for(let n in e){let r=e[n];delete r.metadata,t.push(r)}return t}if(t){let t=r(e.textures),i=r(e.images);t.length>0&&(n.textures=t),i.length>0&&(n.images=i)}return n}fromJSON(e,t){if(e.uuid!==void 0&&(this.uuid=e.uuid),e.name!==void 0&&(this.name=e.name),e.color!==void 0&&this.color!==void 0&&this.color.setHex(e.color),e.roughness!==void 0&&(this.roughness=e.roughness),e.metalness!==void 0&&(this.metalness=e.metalness),e.sheen!==void 0&&(this.sheen=e.sheen),e.sheenColor!==void 0&&(this.sheenColor=new xw().setHex(e.sheenColor)),e.sheenRoughness!==void 0&&(this.sheenRoughness=e.sheenRoughness),e.emissive!==void 0&&this.emissive!==void 0&&this.emissive.setHex(e.emissive),e.specular!==void 0&&this.specular!==void 0&&this.specular.setHex(e.specular),e.specularIntensity!==void 0&&(this.specularIntensity=e.specularIntensity),e.specularColor!==void 0&&this.specularColor!==void 0&&this.specularColor.setHex(e.specularColor),e.shininess!==void 0&&(this.shininess=e.shininess),e.clearcoat!==void 0&&(this.clearcoat=e.clearcoat),e.clearcoatRoughness!==void 0&&(this.clearcoatRoughness=e.clearcoatRoughness),e.dispersion!==void 0&&(this.dispersion=e.dispersion),e.retroreflectivity!==void 0&&(this.retroreflectivity=e.retroreflectivity),e.iridescence!==void 0&&(this.iridescence=e.iridescence),e.iridescenceIOR!==void 0&&(this.iridescenceIOR=e.iridescenceIOR),e.iridescenceThicknessRange!==void 0&&(this.iridescenceThicknessRange=e.iridescenceThicknessRange),e.transmission!==void 0&&(this.transmission=e.transmission),e.thickness!==void 0&&(this.thickness=e.thickness),e.attenuationDistance!==void 0&&(this.attenuationDistance=e.attenuationDistance),e.attenuationColor!==void 0&&this.attenuationColor!==void 0&&this.attenuationColor.setHex(e.attenuationColor),e.anisotropy!==void 0&&(this.anisotropy=e.anisotropy),e.anisotropyRotation!==void 0&&(this.anisotropyRotation=e.anisotropyRotation),e.fog!==void 0&&(this.fog=e.fog),e.flatShading!==void 0&&(this.flatShading=e.flatShading),e.blending!==void 0&&(this.blending=e.blending),e.combine!==void 0&&(this.combine=e.combine),e.side!==void 0&&(this.side=e.side),e.shadowSide!==void 0&&(this.shadowSide=e.shadowSide),e.opacity!==void 0&&(this.opacity=e.opacity),e.transparent!==void 0&&(this.transparent=e.transparent),e.alphaTest!==void 0&&(this.alphaTest=e.alphaTest),e.alphaHash!==void 0&&(this.alphaHash=e.alphaHash),e.depthFunc!==void 0&&(this.depthFunc=e.depthFunc),e.depthTest!==void 0&&(this.depthTest=e.depthTest),e.depthWrite!==void 0&&(this.depthWrite=e.depthWrite),e.colorWrite!==void 0&&(this.colorWrite=e.colorWrite),e.clippingPlanes!==void 0&&(this.clippingPlanes=e.clippingPlanes.map(e=>new xT().fromJSON(e))),e.clipIntersection!==void 0&&(this.clipIntersection=e.clipIntersection),e.clipShadows!==void 0&&(this.clipShadows=e.clipShadows),e.depthPacking!==void 0&&(this.depthPacking=e.depthPacking),e.blendSrc!==void 0&&(this.blendSrc=e.blendSrc),e.blendDst!==void 0&&(this.blendDst=e.blendDst),e.blendEquation!==void 0&&(this.blendEquation=e.blendEquation),e.blendSrcAlpha!==void 0&&(this.blendSrcAlpha=e.blendSrcAlpha),e.blendDstAlpha!==void 0&&(this.blendDstAlpha=e.blendDstAlpha),e.blendEquationAlpha!==void 0&&(this.blendEquationAlpha=e.blendEquationAlpha),e.blendColor!==void 0&&this.blendColor!==void 0&&this.blendColor.setHex(e.blendColor),e.blendAlpha!==void 0&&(this.blendAlpha=e.blendAlpha),e.stencilWriteMask!==void 0&&(this.stencilWriteMask=e.stencilWriteMask),e.stencilFunc!==void 0&&(this.stencilFunc=e.stencilFunc),e.stencilRef!==void 0&&(this.stencilRef=e.stencilRef),e.stencilFuncMask!==void 0&&(this.stencilFuncMask=e.stencilFuncMask),e.stencilFail!==void 0&&(this.stencilFail=e.stencilFail),e.stencilZFail!==void 0&&(this.stencilZFail=e.stencilZFail),e.stencilZPass!==void 0&&(this.stencilZPass=e.stencilZPass),e.stencilWrite!==void 0&&(this.stencilWrite=e.stencilWrite),e.wireframe!==void 0&&(this.wireframe=e.wireframe),e.wireframeLinewidth!==void 0&&(this.wireframeLinewidth=e.wireframeLinewidth),e.wireframeLinecap!==void 0&&(this.wireframeLinecap=e.wireframeLinecap),e.wireframeLinejoin!==void 0&&(this.wireframeLinejoin=e.wireframeLinejoin),e.rotation!==void 0&&(this.rotation=e.rotation),e.linewidth!==void 0&&(this.linewidth=e.linewidth),e.linecap!==void 0&&(this.linecap=e.linecap),e.linejoin!==void 0&&(this.linejoin=e.linejoin),e.dashSize!==void 0&&(this.dashSize=e.dashSize),e.gapSize!==void 0&&(this.gapSize=e.gapSize),e.scale!==void 0&&(this.scale=e.scale),e.polygonOffset!==void 0&&(this.polygonOffset=e.polygonOffset),e.polygonOffsetFactor!==void 0&&(this.polygonOffsetFactor=e.polygonOffsetFactor),e.polygonOffsetUnits!==void 0&&(this.polygonOffsetUnits=e.polygonOffsetUnits),e.dithering!==void 0&&(this.dithering=e.dithering),e.alphaToCoverage!==void 0&&(this.alphaToCoverage=e.alphaToCoverage),e.premultipliedAlpha!==void 0&&(this.premultipliedAlpha=e.premultipliedAlpha),e.forceSinglePass!==void 0&&(this.forceSinglePass=e.forceSinglePass),e.allowOverride!==void 0&&(this.allowOverride=e.allowOverride),e.visible!==void 0&&(this.visible=e.visible),e.toneMapped!==void 0&&(this.toneMapped=e.toneMapped),e.userData!==void 0&&(this.userData=e.userData),e.vertexColors!==void 0&&(this.vertexColors=typeof e.vertexColors==`number`?e.vertexColors>0:e.vertexColors),e.size!==void 0&&(this.size=e.size),e.sizeAttenuation!==void 0&&(this.sizeAttenuation=e.sizeAttenuation),e.map!==void 0&&(this.map=t[e.map]||null),e.matcap!==void 0&&(this.matcap=t[e.matcap]||null),e.alphaMap!==void 0&&(this.alphaMap=t[e.alphaMap]||null),e.bumpMap!==void 0&&(this.bumpMap=t[e.bumpMap]||null),e.bumpScale!==void 0&&(this.bumpScale=e.bumpScale),e.normalMap!==void 0&&(this.normalMap=t[e.normalMap]||null),e.normalMapType!==void 0&&(this.normalMapType=e.normalMapType),e.normalScale!==void 0){let t=e.normalScale;Array.isArray(t)===!1&&(t=[t,t]),this.normalScale=new Y().fromArray(t)}return e.displacementMap!==void 0&&(this.displacementMap=t[e.displacementMap]||null),e.displacementScale!==void 0&&(this.displacementScale=e.displacementScale),e.displacementBias!==void 0&&(this.displacementBias=e.displacementBias),e.roughnessMap!==void 0&&(this.roughnessMap=t[e.roughnessMap]||null),e.metalnessMap!==void 0&&(this.metalnessMap=t[e.metalnessMap]||null),e.emissiveMap!==void 0&&(this.emissiveMap=t[e.emissiveMap]||null),e.emissiveIntensity!==void 0&&(this.emissiveIntensity=e.emissiveIntensity),e.specularMap!==void 0&&(this.specularMap=t[e.specularMap]||null),e.specularIntensityMap!==void 0&&(this.specularIntensityMap=t[e.specularIntensityMap]||null),e.specularColorMap!==void 0&&(this.specularColorMap=t[e.specularColorMap]||null),e.envMap!==void 0&&(this.envMap=t[e.envMap]||null),e.envMapRotation!==void 0&&this.envMapRotation.fromArray(e.envMapRotation),e.envMapIntensity!==void 0&&(this.envMapIntensity=e.envMapIntensity),e.reflectivity!==void 0&&(this.reflectivity=e.reflectivity),e.refractionRatio!==void 0&&(this.refractionRatio=e.refractionRatio),e.lightMap!==void 0&&(this.lightMap=t[e.lightMap]||null),e.lightMapIntensity!==void 0&&(this.lightMapIntensity=e.lightMapIntensity),e.aoMap!==void 0&&(this.aoMap=t[e.aoMap]||null),e.aoMapIntensity!==void 0&&(this.aoMapIntensity=e.aoMapIntensity),e.gradientMap!==void 0&&(this.gradientMap=t[e.gradientMap]||null),e.clearcoatMap!==void 0&&(this.clearcoatMap=t[e.clearcoatMap]||null),e.clearcoatRoughnessMap!==void 0&&(this.clearcoatRoughnessMap=t[e.clearcoatRoughnessMap]||null),e.clearcoatNormalMap!==void 0&&(this.clearcoatNormalMap=t[e.clearcoatNormalMap]||null),e.clearcoatNormalScale!==void 0&&(this.clearcoatNormalScale=new Y().fromArray(e.clearcoatNormalScale)),e.iridescenceMap!==void 0&&(this.iridescenceMap=t[e.iridescenceMap]||null),e.iridescenceThicknessMap!==void 0&&(this.iridescenceThicknessMap=t[e.iridescenceThicknessMap]||null),e.transmissionMap!==void 0&&(this.transmissionMap=t[e.transmissionMap]||null),e.thicknessMap!==void 0&&(this.thicknessMap=t[e.thicknessMap]||null),e.anisotropyMap!==void 0&&(this.anisotropyMap=t[e.anisotropyMap]||null),e.sheenColorMap!==void 0&&(this.sheenColorMap=t[e.sheenColorMap]||null),e.sheenRoughnessMap!==void 0&&(this.sheenRoughnessMap=t[e.sheenRoughnessMap]||null),this}clone(){return new this.constructor().copy(this)}copy(e){this.name=e.name,this.blending=e.blending,this.side=e.side,this.vertexColors=e.vertexColors,this.opacity=e.opacity,this.transparent=e.transparent,this.blendSrc=e.blendSrc,this.blendDst=e.blendDst,this.blendEquation=e.blendEquation,this.blendSrcAlpha=e.blendSrcAlpha,this.blendDstAlpha=e.blendDstAlpha,this.blendEquationAlpha=e.blendEquationAlpha,this.blendColor.copy(e.blendColor),this.blendAlpha=e.blendAlpha,this.depthFunc=e.depthFunc,this.depthTest=e.depthTest,this.depthWrite=e.depthWrite,this.stencilWriteMask=e.stencilWriteMask,this.stencilFunc=e.stencilFunc,this.stencilRef=e.stencilRef,this.stencilFuncMask=e.stencilFuncMask,this.stencilFail=e.stencilFail,this.stencilZFail=e.stencilZFail,this.stencilZPass=e.stencilZPass,this.stencilWrite=e.stencilWrite;let t=e.clippingPlanes,n=null;if(t!==null){let e=t.length;n=Array(e);for(let r=0;r!==e;++r)n[r]=t[r].clone()}return this.clippingPlanes=n,this.clipIntersection=e.clipIntersection,this.clipShadows=e.clipShadows,this.shadowSide=e.shadowSide,this.colorWrite=e.colorWrite,this.precision=e.precision,this.polygonOffset=e.polygonOffset,this.polygonOffsetFactor=e.polygonOffsetFactor,this.polygonOffsetUnits=e.polygonOffsetUnits,this.dithering=e.dithering,this.alphaTest=e.alphaTest,this.alphaHash=e.alphaHash,this.alphaToCoverage=e.alphaToCoverage,this.premultipliedAlpha=e.premultipliedAlpha,this.forceSinglePass=e.forceSinglePass,this.allowOverride=e.allowOverride,this.visible=e.visible,this.toneMapped=e.toneMapped,this.userData=JSON.parse(JSON.stringify(e.userData)),this}dispose(){this.dispatchEvent({type:`dispose`})}set needsUpdate(e){e===!0&&this.version++}},wT=/*@__PURE__*/ new X,TT=/*@__PURE__*/ new X,ET=/*@__PURE__*/ new X,DT=/*@__PURE__*/ new X,OT=class{constructor(e=new X,t=new X(0,0,-1)){this.origin=e,this.direction=t}set(e,t){return this.origin.copy(e),this.direction.copy(t),this}copy(e){return this.origin.copy(e.origin),this.direction.copy(e.direction),this}at(e,t){return t.copy(this.origin).addScaledVector(this.direction,e)}lookAt(e){return this.direction.copy(e).sub(this.origin).normalize(),this}recast(e){return this.origin.copy(this.at(e,wT)),this}closestPointToPoint(e,t){t.subVectors(e,this.origin);let n=t.dot(this.direction);return n<0?t.copy(this.origin):t.copy(this.origin).addScaledVector(this.direction,n)}distanceToPoint(e){return Math.sqrt(this.distanceSqToPoint(e))}distanceSqToPoint(e){let t=wT.subVectors(e,this.origin).dot(this.direction);return t<0?this.origin.distanceToSquared(e):(wT.copy(this.origin).addScaledVector(this.direction,t),wT.distanceToSquared(e))}distanceSqToSegment(e,t,n,r){TT.copy(e).add(t).multiplyScalar(.5),ET.copy(t).sub(e).normalize(),DT.copy(this.origin).sub(TT);let i=e.distanceTo(t)*.5,a=-this.direction.dot(ET),o=DT.dot(this.direction),s=-DT.dot(ET),c=DT.lengthSq(),l=Math.abs(1-a*a),u,d,f,p;if(l>0){if(u=a*s-o,d=a*o-s,p=i*l,u>=0){if(d>=-p){if(d<=p){let e=1/l;u*=e,d*=e,f=u*(u+a*d+2*o)+d*(a*u+d+2*s)+c}else d=i,u=Math.max(0,-(a*d+o)),f=-u*u+d*(d+2*s)+c}else d=-i,u=Math.max(0,-(a*d+o)),f=-u*u+d*(d+2*s)+c}else d<=-p?(u=Math.max(0,-(-a*i+o)),d=u>0?-i:Math.min(Math.max(-i,-s),i),f=-u*u+d*(d+2*s)+c):d<=p?(u=0,d=Math.min(Math.max(-i,-s),i),f=d*(d+2*s)+c):(u=Math.max(0,-(a*i+o)),d=u>0?i:Math.min(Math.max(-i,-s),i),f=-u*u+d*(d+2*s)+c)}else d=a>0?-i:i,u=Math.max(0,-(a*d+o)),f=-u*u+d*(d+2*s)+c;return n&&n.copy(this.origin).addScaledVector(this.direction,u),r&&r.copy(TT).addScaledVector(ET,d),f}intersectSphere(e,t){if(e.radius<0)return null;wT.subVectors(e.center,this.origin);let n=wT.dot(this.direction),r=wT.dot(wT)-n*n,i=e.radius*e.radius;if(r>i)return null;let a=Math.sqrt(i-r),o=n-a,s=n+a;return s<0?null:o<0?this.at(s,t):this.at(o,t)}intersectsSphere(e){return e.radius<0?!1:this.distanceSqToPoint(e.center)<=e.radius*e.radius}distanceToPlane(e){let t=e.normal.dot(this.direction);if(t===0)return e.distanceToPoint(this.origin)===0?0:null;let n=-(this.origin.dot(e.normal)+e.constant)/t;return n>=0?n:null}intersectPlane(e,t){let n=this.distanceToPlane(e);return n===null?null:this.at(n,t)}intersectsPlane(e){let t=e.distanceToPoint(this.origin);return t===0||e.normal.dot(this.direction)*t<0}intersectBox(e,t){let n,r,i,a,o,s,c=1/this.direction.x,l=1/this.direction.y,u=1/this.direction.z,d=this.origin;return c>=0?(n=(e.min.x-d.x)*c,r=(e.max.x-d.x)*c):(n=(e.max.x-d.x)*c,r=(e.min.x-d.x)*c),l>=0?(i=(e.min.y-d.y)*l,a=(e.max.y-d.y)*l):(i=(e.max.y-d.y)*l,a=(e.min.y-d.y)*l),n>a||i>r||((i>n||isNaN(n))&&(n=i),(a<r||isNaN(r))&&(r=a),u>=0?(o=(e.min.z-d.z)*u,s=(e.max.z-d.z)*u):(o=(e.max.z-d.z)*u,s=(e.min.z-d.z)*u),n>s||o>r)||((o>n||n!==n)&&(n=o),(s<r||r!==r)&&(r=s),r<0)?null:this.at(n>=0?n:r,t)}intersectsBox(e){return this.intersectBox(e,wT)!==null}intersectTriangle(e,t,n,r,i){let a=this.origin,o=this.direction,s=o.x,c=o.y,l=o.z,u=e.x-a.x,d=e.y-a.y,f=e.z-a.z,p=t.x-a.x,m=t.y-a.y,h=t.z-a.z,g=n.x-a.x,_=n.y-a.y,v=n.z-a.z,y=Math.abs(s),b=Math.abs(c),x=Math.abs(l),S,C,w,T,E,D,O,k,A,ee,te,j;if(y>=b&&y>=x?(w=s,D=u,A=p,j=g,s>=0?(S=c,C=l,T=d,E=f,O=m,k=h,ee=_,te=v):(S=l,C=c,T=f,E=d,O=h,k=m,ee=v,te=_)):b>=x?(w=c,D=d,A=m,j=_,c>=0?(S=l,C=s,T=f,E=u,O=h,k=p,ee=v,te=g):(S=s,C=l,T=u,E=f,O=p,k=h,ee=g,te=v)):(w=l,D=f,A=h,j=v,l>=0?(S=s,C=c,T=u,E=d,O=p,k=m,ee=g,te=_):(S=c,C=s,T=d,E=u,O=m,k=p,ee=_,te=g)),w===0)return null;let ne=S/w,re=C/w,M=1/w,ie=T-ne*D,N=E-re*D,ae=O-ne*A,oe=k-re*A,se=ee-ne*j,ce=te-re*j,le=se*oe-ce*ae,ue=ie*ce-N*se,de=ae*N-oe*ie;if(r){if(le<0||ue<0||de<0)return null}else if((le<0||ue<0||de<0)&&(le>0||ue>0||de>0))return null;let fe=le+ue+de;if(fe===0)return null;let pe=M*(le*D+ue*A+de*j);return(fe>0?pe<0:pe>0)?null:this.at(pe/fe,i)}applyMatrix4(e){return this.origin.applyMatrix4(e),this.direction.transformDirection(e),this}equals(e){return e.origin.equals(this.origin)&&e.direction.equals(this.direction)}clone(){return new this.constructor().copy(this)}},kT=class extends CT{constructor(e){super(),this.isMeshBasicMaterial=!0,this.type=`MeshBasicMaterial`,this.color=new xw(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new XC,this.combine=0,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap=`round`,this.wireframeLinejoin=`round`,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.specularMap=e.specularMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.combine=e.combine,this.reflectivity=e.reflectivity,this.refractionRatio=e.refractionRatio,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.fog=e.fog,this}},AT=/*@__PURE__*/ new BC,jT=/*@__PURE__*/ new OT,MT=/*@__PURE__*/ new lT,NT=/*@__PURE__*/ new X,PT=/*@__PURE__*/ new X,FT=/*@__PURE__*/ new X,IT=/*@__PURE__*/ new X,LT=/*@__PURE__*/ new X,RT=/*@__PURE__*/ new X,zT=/*@__PURE__*/ new X,BT=/*@__PURE__*/ new X,VT=class extends pw{constructor(e=new _T,t=new kT){super(),this.isMesh=!0,this.type=`Mesh`,this.geometry=e,this.material=t,this.morphTargetDictionary=void 0,this.morphTargetInfluences=void 0,this.count=1,this.updateMorphTargets()}copy(e,t){return super.copy(e,t),e.morphTargetInfluences!==void 0&&(this.morphTargetInfluences=e.morphTargetInfluences.slice()),e.morphTargetDictionary!==void 0&&(this.morphTargetDictionary=Object.assign({},e.morphTargetDictionary)),this.material=Array.isArray(e.material)?e.material.slice():e.material,this.geometry=e.geometry,this}updateMorphTargets(){let e=this.geometry.morphAttributes,t=Object.keys(e);if(t.length>0){let n=e[t[0]];if(n!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let e=0,t=n.length;e<t;e++){let t=n[e].name||String(e);this.morphTargetInfluences.push(0),this.morphTargetDictionary[t]=e}}}}getVertexPosition(e,t){let n=this.geometry,r=n.attributes.position,i=n.morphAttributes.position,a=n.morphTargetsRelative;t.fromBufferAttribute(r,e);let o=this.morphTargetInfluences;if(i&&o){RT.set(0,0,0);for(let n=0,r=i.length;n<r;n++){let r=o[n],s=i[n];r!==0&&(LT.fromBufferAttribute(s,e),a?RT.addScaledVector(LT,r):RT.addScaledVector(LT.sub(t),r))}t.add(RT)}return t}intersectsFrustum(e){return e.intersectsObject(this)}raycast(e,t){let n=this.geometry,r=this.material,i=this.matrixWorld;r!==void 0&&(n.boundingSphere===null&&n.computeBoundingSphere(),MT.copy(n.boundingSphere),MT.applyMatrix4(i),jT.copy(e.ray).recast(e.near),!(MT.containsPoint(jT.origin)===!1&&(jT.intersectSphere(MT,NT)===null||jT.origin.distanceToSquared(NT)>(e.far-e.near)**2))&&(AT.copy(i).invert(),jT.copy(e.ray).applyMatrix4(AT),(n.boundingBox===null||jT.intersectsBox(n.boundingBox)!==!1)&&this._computeIntersections(e,t,jT)))}_computeIntersections(e,t,n){let r,i=this.geometry,a=this.material,o=i.index,s=i.attributes.position,c=i.attributes.uv,l=i.attributes.uv1,u=i.attributes.normal,d=i.groups,f=i.drawRange;if(o!==null){if(Array.isArray(a))for(let i=0,s=d.length;i<s;i++){let s=d[i],p=a[s.materialIndex],m=Math.max(s.start,f.start),h=Math.min(o.count,Math.min(s.start+s.count,f.start+f.count));for(let i=m,a=h;i<a;i+=3){let a=o.getX(i),d=o.getX(i+1),f=o.getX(i+2);r=UT(this,p,e,n,c,l,u,a,d,f),r&&(r.faceIndex=Math.floor(i/3),r.face.materialIndex=s.materialIndex,t.push(r))}}else{let i=Math.max(0,f.start),s=Math.min(o.count,f.start+f.count);for(let d=i,f=s;d<f;d+=3){let i=o.getX(d),s=o.getX(d+1),f=o.getX(d+2);r=UT(this,a,e,n,c,l,u,i,s,f),r&&(r.faceIndex=Math.floor(d/3),t.push(r))}}}else if(s!==void 0){if(Array.isArray(a))for(let i=0,o=d.length;i<o;i++){let o=d[i],p=a[o.materialIndex],m=Math.max(o.start,f.start),h=Math.min(s.count,Math.min(o.start+o.count,f.start+f.count));for(let i=m,a=h;i<a;i+=3){let a=i,s=i+1,d=i+2;r=UT(this,p,e,n,c,l,u,a,s,d),r&&(r.faceIndex=Math.floor(i/3),r.face.materialIndex=o.materialIndex,t.push(r))}}else{let i=Math.max(0,f.start),o=Math.min(s.count,f.start+f.count);for(let s=i,d=o;s<d;s+=3){let i=s,o=s+1,d=s+2;r=UT(this,a,e,n,c,l,u,i,o,d),r&&(r.faceIndex=Math.floor(s/3),t.push(r))}}}}};function HT(e,t,n,r,i,a,o,s){let c;if(c=t.side===1?r.intersectTriangle(o,a,i,!0,s):r.intersectTriangle(i,a,o,t.side===0,s),c===null)return null;BT.copy(s),BT.applyMatrix4(e.matrixWorld);let l=n.ray.origin.distanceTo(BT);return l<n.near||l>n.far?null:{distance:l,point:BT.clone(),object:e}}function UT(e,t,n,r,i,a,o,s,c,l){e.getVertexPosition(s,PT),e.getVertexPosition(c,FT),e.getVertexPosition(l,IT);let u=HT(e,t,n,r,PT,FT,IT,zT);if(u){let e=new X;Lw.getBarycoord(zT,PT,FT,IT,e),i&&(u.uv=Lw.getInterpolatedAttribute(i,s,c,l,e,new Y)),a&&(u.uv1=Lw.getInterpolatedAttribute(a,s,c,l,e,new Y)),o&&(u.normal=Lw.getInterpolatedAttribute(o,s,c,l,e,new X),u.normal.dot(r.direction)>0&&u.normal.multiplyScalar(-1));let t={a:s,b:c,c:l,normal:new X,materialIndex:0};Lw.getNormal(PT,FT,IT,t.normal),u.face=t,u.barycoord=e}return u}var WT=class extends PC{constructor(e=null,t=1,n=1,r,i,a,o,s,c=wx,l=wx,u,d){super(null,a,o,s,c,l,r,i,u,d),this.isDataTexture=!0,this.image={data:e,width:t,height:n},this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}},GT=/*@__PURE__*/ new lT,KT=/*@__PURE__*/ new Y(.5,.5),qT=/*@__PURE__*/ new X,JT=class{constructor(e=new xT,t=new xT,n=new xT,r=new xT,i=new xT,a=new xT){this.planes=[e,t,n,r,i,a]}set(e,t,n,r,i,a){let o=this.planes;return o[0].copy(e),o[1].copy(t),o[2].copy(n),o[3].copy(r),o[4].copy(i),o[5].copy(a),this}copy(e){let t=this.planes;for(let n=0;n<6;n++)t[n].copy(e.planes[n]);return this}setFromProjectionMatrix(e,t=XS,n=!1){let r=this.planes,i=e.elements,a=i[0],o=i[1],s=i[2],c=i[3],l=i[4],u=i[5],d=i[6],f=i[7],p=i[8],m=i[9],h=i[10],g=i[11],_=i[12],v=i[13],y=i[14],b=i[15];if(r[0].setComponents(c-a,f-l,g-p,b-_).normalize(),r[1].setComponents(c+a,f+l,g+p,b+_).normalize(),r[2].setComponents(c+o,f+u,g+m,b+v).normalize(),r[3].setComponents(c-o,f-u,g-m,b-v).normalize(),n)r[4].setComponents(s,d,h,y).normalize(),r[5].setComponents(c-s,f-d,g-h,b-y).normalize();else if(r[4].setComponents(c-s,f-d,g-h,b-y).normalize(),t===2e3)r[5].setComponents(c+s,f+d,g+h,b+y).normalize();else if(t===2001)r[5].setComponents(s,d,h,y).normalize();else throw Error(`THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: `+t);return this}intersectsObject(e){if(e.boundingSphere!==void 0)e.boundingSphere===null&&e.computeBoundingSphere(),GT.copy(e.boundingSphere).applyMatrix4(e.matrixWorld);else{let t=e.geometry;t.boundingSphere===null&&t.computeBoundingSphere(),GT.copy(t.boundingSphere).applyMatrix4(e.matrixWorld)}return this.intersectsSphere(GT)}intersectsSprite(e){return GT.center.set(0,0,0),GT.radius=.7071067811865476+KT.distanceTo(e.center),GT.applyMatrix4(e.matrixWorld),this.intersectsSphere(GT)}intersectsSphere(e){let t=this.planes,n=e.center,r=-e.radius;for(let e=0;e<6;e++)if(t[e].distanceToPoint(n)<r)return!1;return!0}intersectsBox(e){let t=this.planes;for(let n=0;n<6;n++){let r=t[n];if(qT.x=r.normal.x>0?e.max.x:e.min.x,qT.y=r.normal.y>0?e.max.y:e.min.y,qT.z=r.normal.z>0?e.max.z:e.min.z,r.distanceToPoint(qT)<0)return!1}return!0}containsPoint(e){let t=this.planes;for(let n=0;n<6;n++)if(t[n].distanceToPoint(e)<0)return!1;return!0}clone(){return new this.constructor().copy(this)}},YT=class extends PC{constructor(e,t,n,r,i=Dx,a=Dx,o,s,c){super(e,t,n,r,i,a,o,s,c),this.isVideoTexture=!0,this.generateMipmaps=!1,this._requestVideoFrameCallbackId=0;let l=this;function u(){l.needsUpdate=!0,l._requestVideoFrameCallbackId=e.requestVideoFrameCallback(u)}`requestVideoFrameCallback`in e&&(this._requestVideoFrameCallbackId=e.requestVideoFrameCallback(u))}clone(){return new this.constructor(this.image).copy(this)}update(){let e=this.image;!(`requestVideoFrameCallback`in e)&&e.readyState>=e.HAVE_CURRENT_DATA&&(this.needsUpdate=!0)}dispose(){this._requestVideoFrameCallbackId!==0&&(this.source.data.cancelVideoFrameCallback(this._requestVideoFrameCallbackId),this._requestVideoFrameCallbackId=0),super.dispose()}},XT=class extends YT{constructor(e,t,n,r,i,a,o,s){super({},e,t,n,r,i,a,o,s),this.isVideoFrameTexture=!0}update(){}clone(){return new this.constructor().copy(this)}setFrame(e){this.image=e,this.needsUpdate=!0}},ZT=class extends PC{constructor(e=[],t=301,n,r,i,a,o,s,c,l){super(e,t,n,r,i,a,o,s,c,l),this.isCubeTexture=!0,this.flipY=!1}get images(){return this.image}set images(e){this.image=e}},QT=class extends PC{constructor(e,t,n=Fx,r,i,a,o=wx,s=wx,c,l=Kx,u=1){if(l!==1026&&l!==1027)throw Error(`THREE.DepthTexture: format must be either THREE.DepthFormat or THREE.DepthStencilFormat`);super({width:e,height:t,depth:u},r,i,a,o,s,l,n,c),this.isDepthTexture=!0,this.flipY=!1,this.generateMipmaps=!1,this.compareFunction=null}copy(e){return super.copy(e),this.source=new AC(Object.assign({},e.image)),this.compareFunction=e.compareFunction,this}toJSON(e){let t=super.toJSON(e);return t.compareFunction=this.compareFunction,t}},$T=class extends QT{constructor(e,t=Fx,n=301,r,i,a=wx,o=wx,s,c=Kx){let l={width:e,height:e,depth:1},u=[l,l,l,l,l,l];super(e,e,t,n,r,i,a,o,s,c),this.image=u,this.isCubeDepthTexture=!0,this.isCubeTexture=!0}get images(){return this.image}set images(e){this.image=e}},eE=class extends PC{constructor(e=null){super(),this.sourceTexture=e,this.isExternalTexture=!0}copy(e){return super.copy(e),this.sourceTexture=e.sourceTexture,this}},tE=class e extends _T{constructor(e=1,t=1,n=1,r=1,i=1,a=1){super(),this.type=`BoxGeometry`,this.parameters={width:e,height:t,depth:n,widthSegments:r,heightSegments:i,depthSegments:a};let o=this;r=Math.floor(r),i=Math.floor(i),a=Math.floor(a);let s=[],c=[],l=[],u=[],d=0,f=0;p(`z`,`y`,`x`,-1,-1,n,t,e,a,i,0),p(`z`,`y`,`x`,1,-1,n,t,-e,a,i,1),p(`x`,`z`,`y`,1,1,e,n,t,r,a,2),p(`x`,`z`,`y`,1,-1,e,n,-t,r,a,3),p(`x`,`y`,`z`,1,-1,e,t,n,r,i,4),p(`x`,`y`,`z`,-1,-1,e,t,-n,r,i,5),this.setIndex(s),this.setAttribute(`position`,new aT(c,3)),this.setAttribute(`normal`,new aT(l,3)),this.setAttribute(`uv`,new aT(u,2));function p(e,t,n,r,i,a,p,m,h,g,_){let v=a/h,y=p/g,b=a/2,x=p/2,S=m/2,C=h+1,w=g+1,T=0,E=0,D=new X;for(let a=0;a<w;a++){let o=a*y-x;for(let s=0;s<C;s++)D[e]=(s*v-b)*r,D[t]=o*i,D[n]=S,c.push(D.x,D.y,D.z),D[e]=0,D[t]=0,D[n]=m>0?1:-1,l.push(D.x,D.y,D.z),u.push(s/h),u.push(1-a/g),T+=1}for(let e=0;e<g;e++)for(let t=0;t<h;t++){let n=d+t+C*e,r=d+t+C*(e+1),i=d+(t+1)+C*(e+1),a=d+(t+1)+C*e;s.push(n,r,a),s.push(r,i,a),E+=6}o.addGroup(f,E,_),f+=E,d+=T}}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(t){return new e(t.width,t.height,t.depth,t.widthSegments,t.heightSegments,t.depthSegments)}},nE=class e extends _T{constructor(e=1,t=1,n=1,r=1){super(),this.type=`PlaneGeometry`,this.parameters={width:e,height:t,widthSegments:n,heightSegments:r};let i=e/2,a=t/2,o=Math.floor(n),s=Math.floor(r),c=o+1,l=s+1,u=e/o,d=t/s,f=[],p=[],m=[],h=[];for(let e=0;e<l;e++){let t=e*d-a;for(let n=0;n<c;n++){let r=n*u-i;p.push(r,-t,0),m.push(0,0,1),h.push(n/o),h.push(1-e/s)}}for(let e=0;e<s;e++)for(let t=0;t<o;t++){let n=t+c*e,r=t+c*(e+1),i=t+1+c*(e+1),a=t+1+c*e;f.push(n,r,a),f.push(r,i,a)}this.setIndex(f),this.setAttribute(`position`,new aT(p,3)),this.setAttribute(`normal`,new aT(m,3)),this.setAttribute(`uv`,new aT(h,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(t){return new e(t.width,t.height,t.widthSegments,t.heightSegments)}};function rE(e){let t={};for(let n in e){t[n]={};for(let r in e[n]){let i=e[n][r];if(aE(i))i.isRenderTargetTexture?(q(`UniformsUtils: Textures of render targets cannot be cloned via cloneUniforms() or mergeUniforms().`),t[n][r]=null):t[n][r]=i.clone();else if(Array.isArray(i)){if(aE(i[0])){let e=[];for(let t=0,n=i.length;t<n;t++)e[t]=i[t].clone();t[n][r]=e}else t[n][r]=i.slice()}else t[n][r]=i}}return t}function iE(e){let t={};for(let n=0;n<e.length;n++){let r=rE(e[n]);for(let e in r)t[e]=r[e]}return t}function aE(e){return e&&(e.isColor||e.isMatrix3||e.isMatrix4||e.isVector2||e.isVector3||e.isVector4||e.isTexture||e.isQuaternion)}function oE(e){let t=[];for(let n=0;n<e.length;n++)t.push(e[n].clone());return t}function sE(e){let t=e.getRenderTarget();return t===null?e.outputColorSpace:t.isXRRenderTarget===!0?t.texture.colorSpace:wC.workingColorSpace}var cE={clone:rE,merge:iE},lE=`void main() {
|
|
3
|
+
var e=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),t=e=>e,n=e=>e,r=90,i=180,a=360,o=t(r),s=t(i),c=t(a),l=e=>n(e*Math.PI/i),u=e=>t(e*i/Math.PI);function d(e){let n=e%c;return n>s&&(n-=c),n<=-s&&(n+=c),t(n)}var f={EdgeRadius:0,CenterX:1,CenterY:2,Yaw:3,Pitch:4,Roll:5},p={EdgeRadius:0,CenterX:1,CenterY:2,Yaw:3,Pitch:4,Roll:5,TranslationX:6,TranslationY:7,TranslationZ:8,C1:9,C2:10,C3:11,C4:12,CanvasWidth:13,CanvasHeight:14,LensType:15},m={Xi:0,FocalX:1,FocalY:2,CenterX:3,CenterY:4,Yaw:5,Pitch:6,Roll:7,TranslationX:8,TranslationY:9,TranslationZ:10},h={K1:11,K2:12,K3:13,P1:14,P2:15,CanvasWidth:16,CanvasHeight:17,LensType:18},g={K1:11,K2:12,K3:13,K4:14,K5:15,P1:16,P2:17,P3:18,P4:19,S1:20,S2:21,S3:22,S4:23,CanvasWidth:24,CanvasHeight:25,LensType:26},_={CanvasWidth:0,CanvasHeight:1,VersionWord:2};function v(e,n,r){return{yaw:t(e),pitch:t(n),roll:t(r)}}function y(e,t){let n=e>>>16;return n===t?void 0:`declares version ${n}`}function b(e,t,n){let[r]=e;return r?{width:r(t),height:r(n)}:x}var x={width:0,height:0};function S(e){let[t,r,i]=e,a=Math.hypot(t,r);return{theta:n(Math.atan2(a,i)),radialUnit:a===0?[0,0]:[t/a,r/a]}}function C(e,t,n){return{x:e.x+t*n[0],y:e.y+t*n[1]}}var w=l(t(100)),T=l(t(96)),E=class{parameters;kind=`equidistant`;halfFieldOfView=w;principalPoint;constructor(e){this.parameters=e,this.principalPoint=e.principalPoint}get projection(){return{kind:`radial-polynomial`,principalPoint:this.principalPoint,coefficients:[this.pixelsPerRadian,0,0,0]}}project(e){let{theta:t,radialUnit:n}=S(e);return t>this.halfFieldOfView?void 0:C(this.principalPoint,this.pixelsPerRadian*t,n)}get pixelsPerRadian(){return this.parameters.edgeRadius/this.parameters.radiusAngle}},D={Legacy:1,Polynomial:2,Mei:3,ExtendedMei:6},O={version:D.Legacy,lensTokens:6,trailingTokens:3,radialScale:1,parseLens(e,t){return{lensIndex:t,model:new E({edgeRadius:e(f.EdgeRadius),radiusAngle:T,principalPoint:{x:e(f.CenterX),y:e(f.CenterY)}}),orientation:v(e(f.Yaw),e(f.Pitch),e(f.Roll)),translation:[0,0,0]}},canvasOf(e){let t=1+(e[0]??0)*6;return{width:e[t+_.CanvasWidth]??0,height:e[t+_.CanvasHeight]??0}}},k=/* @__PURE__ */ `binary-out-of-bounds.binary-unsafe-integer.codec-unsupported.cors.decode.embed-destroyed.index-out-of-range.invalid-argument.invalid-byte-range.invalid-calibration.invalid-protobuf.invalid-trailer.invariant-violation.missing-second-file.no-calibration.no-info-record.no-key-frame.playback-blocked.range-unsupported.render-unavailable.source-changed.source-truncated.source-unreadable.unsupported-calibration.unsupported-container.unsupported-gyro-record.unsupported-info-format.unsupported-layout.webcodecs-unavailable`.split(`.`),A=[`browser`,`recording`,`source`,`usage`,`internal`],ee={"binary-out-of-bounds":`recording`,"binary-unsafe-integer":`recording`,"codec-unsupported":`browser`,cors:`source`,decode:`browser`,"embed-destroyed":`usage`,"index-out-of-range":`internal`,"invalid-argument":`usage`,"invalid-byte-range":`recording`,"invalid-calibration":`recording`,"invalid-protobuf":`recording`,"invalid-trailer":`recording`,"invariant-violation":`internal`,"missing-second-file":`recording`,"no-calibration":`recording`,"no-info-record":`recording`,"no-key-frame":`recording`,"playback-blocked":`browser`,"range-unsupported":`source`,"render-unavailable":`browser`,"source-changed":`source`,"source-truncated":`source`,"source-unreadable":`source`,"unsupported-calibration":`recording`,"unsupported-container":`recording`,"unsupported-gyro-record":`recording`,"unsupported-info-format":`recording`,"unsupported-layout":`recording`,"webcodecs-unavailable":`browser`};function te(e){return typeof e==`string`&&k.includes(e)}var j=class extends Error{code;category;constructor(e,t,n){super(t,n),this.code=e,this.name=`GyroViewError`,this.category=ee[e]}};function ne(e,t,n){return e instanceof j?e:new j(t,n,{cause:e})}function re(e){return e instanceof Error&&e.name===`AbortError`}function M(e,t){return e instanceof j&&e.code===t}function ie(e){return e instanceof Error?e.message:String(e)}function N(e,t){if(!e)throw new j(`invariant-violation`,t)}function ae(e,t,n){if(!Number.isSafeInteger(e)||e<0||e>=t)throw new j(`index-out-of-range`,`${n} index ${e} is outside 0..${t-1}`)}var oe={radial:5,tangential:2,thinPrism:2};function se(e){ce(`radial`,e.radial.length),ce(`tangential`,e.tangential.length),ce(`thinPrism`,e.thinPrism.length)}function ce(e,t){let n=oe[e];N(t<=n,`a Mei distortion has ${t} ${e} terms, more than the ${n} a string carries`)}function le(e,t){let[n,r]=t,i=n*n+r*r,a=1+i*ue(i,e.radial,e=>e),o=ue(i,e.tangential,e=>e.p1),s=ue(i,e.tangential,e=>e.p2),c=i*ue(i,e.thinPrism,e=>e.x),l=i*ue(i,e.thinPrism,e=>e.y);return[a*n+2*o*n*r+s*(i+2*n*n)+c,a*r+o*(i+2*r*r)+2*s*n*r+l]}function ue(e,t,n){return t.reduceRight((t,r)=>t*e+n(r),0)}var de=class{parameters;kind=`mei`;halfFieldOfView=w;principalPoint;constructor(e){this.parameters=e,se(e.distortion),this.principalPoint=e.principalPoint}get projection(){return{kind:`mei`,...this.parameters}}project(e){let[t,n,r]=e,i=r+this.parameters.xi;if(i<=0||Math.atan2(Math.hypot(t,n),r)>this.halfFieldOfView)return;let[a,o]=le(this.parameters.distortion,[t/i,n/i]);return{x:this.parameters.focal[0]*a+this.principalPoint.x,y:this.parameters.focal[1]*o+this.principalPoint.y}}},fe=({radial:e,tangential:t})=>{let[n,r]=t;return{radial:e,tangential:[{p1:n,p2:r}],thinPrism:[]}};function pe(e){return{version:e.version,lensTokens:e.lensTokens,trailingTokens:1,radialScale:e.radialScale,versionWordProblem:t=>y(t,e.version),parseLens:(t,n)=>me(t,n,e),canvasOf:(t,n)=>b(n,e.canvasTokens.width,e.canvasTokens.height)}}function me(e,t,n){return{lensIndex:t,model:new de({xi:e(m.Xi),focal:[e(m.FocalX),e(m.FocalY)],principalPoint:{x:e(m.CenterX),y:e(m.CenterY)},distortion:n.distortionOf(e)}),orientation:v(e(m.Yaw),e(m.Pitch),e(m.Roll)),translation:[e(m.TranslationX),e(m.TranslationY),e(m.TranslationZ)]}}var he=pe({version:D.Mei,lensTokens:19,canvasTokens:{width:h.CanvasWidth,height:h.CanvasHeight},distortionOf:e=>({radial:[e(h.K1),e(h.K2),e(h.K3)],tangential:[{p1:e(h.P1),p2:e(h.P2)}],thinPrism:[]}),radialScale:1}),ge=1.008;function _e(e){return pe({version:D.ExtendedMei,lensTokens:27,canvasTokens:{width:g.CanvasWidth,height:g.CanvasHeight},distortionOf:t=>e(ye(t)),radialScale:ge})}var ve=_e(fe);function ye(e){return{radial:[e(g.K1),e(g.K2),e(g.K3),e(g.K4),e(g.K5)],tangential:[e(g.P1),e(g.P2),e(g.P3),e(g.P4)],thinPrism:[e(g.S1),e(g.S2),e(g.S3),e(g.S4)]}}var be=class{parameters;kind=`polynomial`;halfFieldOfView=w;principalPoint;scale;constructor(e){this.parameters=e,this.principalPoint=e.principalPoint,this.scale=e.edgeRadius/this.polynomial(this.halfFieldOfView)}get projection(){let[e,t,n,r]=this.parameters.coefficients;return{kind:`radial-polynomial`,principalPoint:this.principalPoint,coefficients:[e*this.scale,t*this.scale,n*this.scale,r*this.scale]}}project(e){let{theta:t,radialUnit:n}=S(e);return t>this.halfFieldOfView?void 0:C(this.principalPoint,this.scale*this.polynomial(t),n)}polynomial(e){let[t,n,r,i]=this.parameters.coefficients;return e*(t+e*(n+e*(r+e*i)))}},xe={version:D.Polynomial,lensTokens:16,trailingTokens:1,radialScale:1,versionWordProblem:e=>y(e,D.Polynomial),parseLens(e,t){return{lensIndex:t,model:new be({edgeRadius:e(p.EdgeRadius),principalPoint:{x:e(p.CenterX),y:e(p.CenterY)},coefficients:[e(p.C1),e(p.C2),e(p.C3),e(p.C4)]}),orientation:v(e(p.Yaw),e(p.Pitch),e(p.Roll)),translation:[e(p.TranslationX),e(p.TranslationY),e(p.TranslationZ)]}},canvasOf(e,t){return b(t,p.CanvasWidth,p.CanvasHeight)}},Se=`_`,Ce=[O,xe,he,ve];function P(e,t=Ce){let n=e.split(Se).map(e=>De(e)),r=n[0]??0,i=Te(t,n);Ee(i,n.at(-1)??0);let a=Array.from({length:r},(e,t)=>F(n,1+t*i.lensTokens));return{version:i.version,canvas:i.canvasOf(n,a),lenses:a.map((e,t)=>i.parseLens(e,t)),radialScale:i.radialScale}}function we(e,t,n){return 1+e*t+n}function Te(e,t){let n=t[0]??0,r=e.find(e=>t.length===we(n,e.lensTokens,e.trailingTokens));if(r)return r;throw new j(`invalid-calibration`,`calibration string has ${t.length} tokens for ${n} lenses, matching no known layout`)}function Ee(e,t){let n=e.versionWordProblem?.(t);if(n!==void 0)throw new j(`invalid-calibration`,`calibration string has the v${e.version} layout but ${n}`)}function F(e,t){return n=>e[t+n]??NaN}function De(e){let t=Number(e);if(e.trim()===``||!Number.isFinite(t))throw new j(`invalid-calibration`,`calibration token "${e}" is not a finite number`);return t}var I={SerialNumber:1,Model:2,Firmware:3,Offset:5,Dimension:19,FrameRate:20,CaptureMode:22,FirstFrameTimestamp:24,RollingShutterTimeMs:25,FileGroupInfo:26,WindowCropInfo:27,GyroTimestampMs:28,HasGyroTimestamp:29,TotalFrames:40,IsFlowstateOnline:42,GyroType:51,OffsetV2:53,OffsetV3:54,IsRawGyro:62,PtsType:64,GyroConfig:65,FileLayout:79,TrackOrder:80,OffsetV6:111},L={Width:1,Height:2},Oe={AccelerometerRangeG:1,GyroscopeRangeDps:2},ke={SensorWidth:1,SensorHeight:2,CropWidth:3,CropHeight:4,CropOffsetX:5,CropOffsetY:6},Ae={TrackTimestamps:1,ExposureRecord:2},je={SplitFiles:1,MultiTrack:2},Me={Stream10First:1,Stream00First:2},Ne={offset:{field:I.Offset,name:`offset`},offsetV2:{field:I.OffsetV2,name:`offset_v2`},offsetV3:{field:I.OffsetV3,name:`offset_v3`},offsetV6:{field:I.OffsetV6,name:`offset_v6`}},Pe=/* @__PURE__ */ new Set([`invalid-calibration`,`unsupported-calibration`]),Fe=[`offset`,`offsetV6`,`offsetV3`,`offsetV2`];function Ie(e){let t=[];for(let n of Le(e)){if(`calibration`in n)return{calibration:n.calibration,warnings:t};t.push(n.warning)}return{calibration:void 0,warnings:t}}function*Le(e){for(let t of Fe){let n=e[t];n!==void 0&&(yield Re(Ne[t],n))}}function Re({name:e},t){try{return{calibration:P(t)}}catch(t){if(t instanceof j&&Pe.has(t.code))return{warning:`${e} skipped: ${t.message}`};throw t}}var ze={Index:0,Info:1,Thumbnail:2,Gyro:3,Exposure:4,ThumbnailExtended:5,FrameTimestamps:6,Gps:7},Be={Protobuf:1,Json:2},Ve=1,He=2,Ue=4,We=8,Ge=4,Ke=8,qe=8,Je=!0,Ye=!1,Xe=BigInt(-(2**53-1)),Ze=BigInt(2**53-1),Qe=class{bytes;view;constructor(e){this.bytes=e,this.view=new DataView(e.buffer,e.byteOffset,e.byteLength)}get length(){return this.bytes.byteLength}uint8At(e){return this.ensureAvailable(e,Ve),this.view.getUint8(e)}uint16LeAt(e){return this.ensureAvailable(e,He),this.view.getUint16(e,Je)}uint32LeAt(e){return this.ensureAvailable(e,Ue),this.view.getUint32(e,Je)}uint16BeAt(e){return this.ensureAvailable(e,He),this.view.getUint16(e,Ye)}uint32BeAt(e){return this.ensureAvailable(e,Ue),this.view.getUint32(e,Ye)}int32BeAt(e){return this.ensureAvailable(e,Ge),this.view.getInt32(e,Ye)}uint64LeAt(e){return this.ensureAvailable(e,We),this.toSafeNumber(this.view.getBigUint64(e,Je),e)}uint64BeAt(e){return this.ensureAvailable(e,We),this.toSafeNumber(this.view.getBigUint64(e,Ye),e)}int64BeAt(e){return this.ensureAvailable(e,Ke),this.toSafeNumber(this.view.getBigInt64(e,Ye),e)}float64LeAt(e){return this.ensureAvailable(e,qe),this.view.getFloat64(e,Je)}bytesAt(e,t){return this.ensureAvailable(e,t),this.bytes.subarray(e,e+t)}asciiAt(e,t){return Array.from(this.bytesAt(e,t),e=>String.fromCodePoint(e)).join(``)}toSafeNumber(e,t){if(!(e>=Xe&&e<=Ze))throw new j(`binary-unsafe-integer`,`64-bit integer at offset ${t} (${e.toString()}) exceeds the safe integer range`);return Number(e)}ensureAvailable(e,t){if(e<0||t<0||e+t>this.bytes.byteLength)throw new j(`binary-out-of-bounds`,`read of ${t} byte(s) at offset ${e} exceeds ${this.bytes.byteLength} available`)}};function $e(e){let t;return()=>(t??={value:e()}).value}var et=$e(()=>new globalThis.TextDecoder(`utf8`));function tt(e){return et().decode(e)}var nt={Varint:0,Fixed64:1,LengthDelimited:2,Fixed32:5},rt=BigInt(7),it=BigInt(127),at=BigInt(2**53-1),ot=class e{decoded;constructor(e){this.decoded=e}static decode(t){let n=new st(t),r=[];for(;!n.atEnd;)r.push(n.readField());return new e(r)}varint(e){let t=this.valueOf(e);if(t!==void 0){if(t.kind!==`varint`)throw this.wrongType(e,`varint`,t.kind);if(t.value>at)throw new j(`binary-unsafe-integer`,`field ${e} holds ${t.value.toString()}, beyond the safe integer range`);return Number(t.value)}}boolean(e){let t=this.varint(e);return t===void 0?void 0:t!==0}double(e){let t=this.valueOf(e);if(t!==void 0){if(t.kind!==`fixed64`)throw this.wrongType(e,`fixed64`,t.kind);return new Qe(t.bytes).float64LeAt(0)}}bytes(e){let t=this.valueOf(e);if(t!==void 0){if(t.kind!==`bytes`)throw this.wrongType(e,`bytes`,t.kind);return t.bytes}}string(e){let t=this.bytes(e);return t===void 0?void 0:tt(t)}message(t){let n=this.bytes(t);return n===void 0?void 0:e.decode(n)}valueOf(e){return this.decoded.findLast(t=>t.number===e)?.value}wrongType(e,t,n){return new j(`invalid-protobuf`,`field ${e} is encoded as ${n}, expected ${t}`)}},st=class{bytes;position=0;reader;constructor(e){this.bytes=e,this.reader=new Qe(e)}get atEnd(){return this.position>=this.bytes.byteLength}readField(){let e=this.readVarint(),t=Number(e>>BigInt(3)),n=Number(e&BigInt(7));return{number:t,value:this.readValue(n,t)}}readValue(e,t){switch(e){case nt.Varint:return{kind:`varint`,value:this.readVarint()};case nt.Fixed64:return{kind:`fixed64`,bytes:this.readBytes(8)};case nt.Fixed32:return{kind:`fixed32`,bytes:this.readBytes(4)};case nt.LengthDelimited:return{kind:`bytes`,bytes:this.readBytes(this.readLength())};default:throw new j(`invalid-protobuf`,`field ${t} uses unsupported wire type ${e}`)}}readVarint(){let e=0n,t=0n;for(let n=0;n<10;n+=1){let n=this.readByte();if(e|=(BigInt(n)&it)<<t,!(n&128))return e;t+=rt}throw new j(`invalid-protobuf`,`varint longer than 10 bytes at byte ${this.position}`)}readLength(){let e=this.readVarint();if(e>BigInt(this.bytes.byteLength))throw new j(`invalid-protobuf`,`length ${e.toString()} exceeds the message at byte ${this.position}`);return Number(e)}readByte(){this.ensureRemaining(1);let e=this.reader.uint8At(this.position);return this.position+=1,e}readBytes(e){this.ensureRemaining(e);let t=this.reader.bytesAt(this.position,e);return this.position+=e,t}ensureRemaining(e){if(this.position+e>this.bytes.byteLength)throw new j(`invalid-protobuf`,`message truncated at byte ${this.position}`)}};function ct(e,t){let n=Object.entries(e).map(([e,n])=>[e,t(n,e)]);return Object.fromEntries(n)}var lt=1e6,ut=1e3,dt=1e3,ft=e=>e,pt=e=>e,R=e=>e,mt=e=>R(e/lt),ht=e=>ft(e*dt),gt=e=>R(e/ut),_t=e=>ft(e*lt);function vt(e,t){if(t!==Be.Protobuf)throw new j(`unsupported-info-format`,`info record uses format ${t}; only protobuf (${Be.Protobuf}) is supported`);let n=ot.decode(e);return{serialNumber:n.string(I.SerialNumber),model:n.string(I.Model),firmware:n.string(I.Firmware),calibration:Tt(n),dimension:Et(n.message(I.Dimension)),frameRate:n.varint(I.FrameRate),captureMode:n.string(I.CaptureMode),firstFrameTimestamp:n.varint(I.FirstFrameTimestamp),readoutTime:yt(n.double(I.RollingShutterTimeMs)),windowCrop:Dt(n.message(I.WindowCropInfo)),gyroOffset:bt(n),gyroType:n.varint(I.GyroType),isRawGyro:n.boolean(I.IsRawGyro),preferredFrameTimeSource:St(n.varint(I.PtsType)),sensorRanges:Ot(n.message(I.GyroConfig)),fileLayout:Ct(n.varint(I.FileLayout)),trackOrder:wt(n.varint(I.TrackOrder))}}function yt(e){return e===void 0?void 0:gt(pt(e))}function bt(e){return e.boolean(I.HasGyroTimestamp)===!0?xt(e.double(I.GyroTimestampMs)):void 0}function xt(e){return e===void 0?void 0:pt(e)}function St(e){return e===Ae.TrackTimestamps?`track-timestamps`:e===Ae.ExposureRecord?`exposure-record`:void 0}function Ct(e){return e===je.SplitFiles?`split-files`:e===je.MultiTrack?`multi-track`:void 0}function wt(e){return e===Me.Stream10First?`stream-10-first`:e===Me.Stream00First?`stream-00-first`:void 0}function Tt(e){return ct(Ne,t=>e.string(t.field))}function Et(e){let t=e?.varint(L.Width),n=e?.varint(L.Height);return t===void 0||n===void 0?void 0:{width:t,height:n}}function Dt(e){return e===void 0?void 0:{sensorWidth:e.varint(ke.SensorWidth),sensorHeight:e.varint(ke.SensorHeight),cropWidth:e.varint(ke.CropWidth),cropHeight:e.varint(ke.CropHeight),cropOffsetX:e.varint(ke.CropOffsetX),cropOffsetY:e.varint(ke.CropOffsetY)}}function Ot(e){return e===void 0?void 0:{accelerometerG:e.varint(Oe.AccelerometerRangeG),gyroscopeDps:e.varint(Oe.GyroscopeRangeDps)}}async function kt(e,t){let n=t.locationOf(ze.Info);if(!n)throw new j(`no-info-record`,`the trailer has no info record; the file is not a camera recording`);return vt(await e.read(n.payload),n.format)}var At=class e{captureTimeStore;shutterTimeStore;constructor(e,t){this.captureTimeStore=e,this.shutterTimeStore=t,N(e.length===t.length,`exposure record arrays disagree on the entry count`)}get length(){return this.captureTimeStore.length}get captureTimes(){return this.captureTimeStore}get shutterTimes(){return this.shutterTimeStore}entryAt(e){return ae(e,this.length,`exposure entry`),{captureTime:ft(this.captureTimeStore[e]??0),shutterTime:R(this.shutterTimeStore[e]??0)}}indexAtOrAfter(e){let t=0,n=this.captureTimeStore.length;for(;t<n;){let r=t+n>>>1;(this.captureTimeStore[r]??1/0)<e?t=r+1:n=r}return t}slice(t,n){return N(t>=0&&n>=0&&t+n<=this.length,`exposure slice out of range`),new e(this.captureTimeStore.slice(t,t+n),this.shutterTimeStore.slice(t,t+n))}},jt=60;function Mt(e,t){try{return Nt(e,t)}catch(e){if(M(e,`binary-unsafe-integer`))return;throw e}}function Nt(e,t){let n=Math.floor(e.byteLength/16),r=new Qe(e),i=new Float64Array(n),a=new Float64Array(n);for(let e=0;e<n;e+=1){let n=e*16;i[e]=t(r.uint64LeAt(n+0)),a[e]=r.float64LeAt(n+8)}return Pt(i)&&a.every(e=>Ft(e))?new At(i,a):void 0}function Pt(e){return e.every((t,n)=>n===0||t>=(e[n-1]??t))}function Ft(e){return e>=0&&e<=jt}var It=32768,Lt=32768,Rt=[Lt,Lt/2],zt=2e3,Bt=class{name=`float`;sampleSize=56;flipSteps={acceleration:[],angularVelocity:[]};captureTimeOf(e){return ht(pt(e))}timestampAt(e,t){return this.captureTimeOf(e.uint64LeAt(t+0))}accelerationAt(e,t){return this.vectorAt(e,t+8)}angularVelocityAt(e,t){return this.vectorAt(e,t+32)}vectorAt(e,t){return[e.float64LeAt(t),e.float64LeAt(t+8),e.float64LeAt(t+16)]}},Vt=class{name=`raw`;sampleSize=20;flipSteps;accelerationScale;angularVelocityScale;constructor(e={}){let n=Ht(e.accelerometerG,16),r=Ht(e.gyroscopeDps,zt);this.accelerationScale=n/Lt,this.angularVelocityScale=l(t(r))/Lt,this.flipSteps={acceleration:Rt.map(e=>e*this.accelerationScale),angularVelocity:Rt.map(e=>e*this.angularVelocityScale)}}captureTimeOf(e){return ft(e)}timestampAt(e,t){return this.captureTimeOf(e.uint64LeAt(t+0))}accelerationAt(e,t){return this.vectorAt(e,t+8,this.accelerationScale)}angularVelocityAt(e,t){return this.vectorAt(e,t+14,this.angularVelocityScale)}vectorAt(e,t,n){return[this.componentAt(e,t,n),this.componentAt(e,t+2,n),this.componentAt(e,t+4,n)]}componentAt(e,t,n){return(e.uint16LeAt(t)-It)*n}};function Ht(e,t){return e!==void 0&&e>0?e:t}var Ut=[0,0,0];function Wt(e){return Math.sqrt(Gt(e,e))}function Gt(e,t){return e[0]*t[0]+e[1]*t[1]+e[2]*t[2]}function Kt(e,t){return[e[1]*t[2]-e[2]*t[1],e[2]*t[0]-e[0]*t[2],e[0]*t[1]-e[1]*t[0]]}function qt(e){return e.every(e=>Number.isFinite(e))}function Jt(e,t){return[e[0]+t[0],e[1]+t[1],e[2]+t[2]]}function Yt(e,t){return[e[0]-t[0],e[1]-t[1],e[2]-t[2]]}function Xt(e,t){return[e[0]*t,e[1]*t,e[2]*t]}function Zt(e,t,n){return Jt(e,Xt(Yt(t,e),n))}var Qt=class{captureTimeStore;accelerationStore;angularVelocityStore;constructor(e,t,n){this.captureTimeStore=e,this.accelerationStore=t,this.angularVelocityStore=n;let r=e.length*3;N(t.length===r&&n.length===r,`gyro track arrays disagree on the sample count`),N($t(e),`gyro sample times go back`)}get length(){return this.captureTimeStore.length}get isEmpty(){return this.captureTimeStore.length===0}get captureTimes(){return this.captureTimeStore}get meanSampleInterval(){return this.length<2?void 0:ft(((this.captureTimeStore[this.length-1]??0)-(this.captureTimeStore[0]??0))/(this.length-1))}sampleAt(e){return ae(e,this.length,`gyro sample`),{captureTime:ft(this.captureTimeStore[e]??0),acceleration:this.vectorAt(this.accelerationStore,e),angularVelocity:this.vectorAt(this.angularVelocityStore,e)}}angularVelocityAt(e){return ae(e,this.length,`gyro sample`),this.vectorAt(this.angularVelocityStore,e)}vectorAt(e,t){let n=t*3;return[e[n]??NaN,e[n+1]??NaN,e[n+2]??NaN]}};function $t(e){return e.every((t,n)=>n===0||t>=(e[n-1]??t))}var en=16,tn=class{length=0;recordedTimes;accelerations;angularVelocities;constructor(e){this.recordedTimes=new Float64Array(e),this.accelerations=new Float32Array(e*3),this.angularVelocities=new Float32Array(e*3)}push(e){let t=this.length*3;this.recordedTimes[this.length]=e.captureTime;for(let n=0;n<3;n+=1)this.accelerations[t+n]=e.acceleration[n]??NaN,this.angularVelocities[t+n]=e.angularVelocity[n]??NaN;this.length+=1}dropFlippedBits(e){let t=0;for(let n=0;n<this.length;n+=1)this.isFlippedAt(n,e)||(this.moveSample(n,t),t+=1);this.length=t}captureTimes(){return this.recordedTimes.subarray(0,this.length)}toTrack(e){let t=this.length*3;return new Qt(e,this.accelerations.subarray(0,t),this.angularVelocities.subarray(0,t))}isFlippedAt(e,t){return e>0&&e<this.length-1&&(nn(this.accelerations,e,t.acceleration)||nn(this.angularVelocities,e,t.angularVelocity))}moveSample(e,t){if(e!==t){this.recordedTimes[t]=this.recordedTimes[e]??0;for(let n of[this.accelerations,this.angularVelocities])n.copyWithin(t*3,e*3,(e+1)*3)}}};function nn(e,t,n){for(let r=0;r<3;r+=1)if(rn(e,t*3+r,n))return!0;return!1}function rn(e,t,n){let r=e[t-3]??0,i=e[t+3]??0,a=Math.abs((e[t]??0)-(r+i)/2),o=Math.abs(r-i);for(let e of n){let t=e/en;if(o<=t&&Math.abs(a-e)<=t)return!0}return!1}function an(e){let t=e.subarray(1).map((t,n)=>t-(e[n]??t)).toSorted();return t[Math.floor(t.length/2)]??0}var on=50,sn=1e4,cn=17;function ln(e){let t=dn(e),n={recorded:e,interval:t,tolerance:un(t)},r=Float64Array.from(e);hn(r,pn(fn(n)),n);let i=r.filter((t,n)=>t!==e[n]).length;for(let e=1;e<r.length;e+=1)r[e]=Math.max(r[e]??0,r[e-1]??0);return{times:r,mended:i}}function un(e){return Math.max(on*e,sn)}function dn(e){return an(e.subarray(0,1025))}function fn({recorded:e,tolerance:t}){let n=[],r=0;for(let i=1;i<=e.length;i+=1){let a=(e[i]??-1/0)-(e[i-1]??0);a>=0&&a<=t||(n.push({start:r,end:i}),r=i)}return n}function pn(e){let t=0;for(let n of e)t=Math.max(t,mn(n));return e.filter(e=>{let n=mn(e);return n>=cn||n===t})}function mn(e){return e.end-e.start}function hn(e,t,n){let[r]=t;if(r){for(let t=r.start-1;t>=0;--t)e[t]=_n(t,(e[t+1]??0)-n.interval,n);for(let[r,i]of t.entries())gn(e,{start:i.end,end:t[r+1]?.start??e.length},n)}}function gn(e,t,n){for(let r=t.start;r<t.end;r+=1)e[r]=_n(r,(e[r-1]??0)+n.interval,n)}function _n(e,t,n){let r=n.recorded[e]??t;return Math.abs(r-t)<=n.tolerance?r:t}var vn=100,yn=1e4,bn=32,xn=2,Sn=64,Cn=100,wn=56*bn;function Tn(e,t){let n=new Vt(e.ranges),r=new Bt;if(e.isRawGyro!==void 0)return e.isRawGyro?n:r;if(t===void 0)return;let i=[n,r].filter(e=>An(t,e)),[a]=i;if(a&&i.length===1)return a;throw new j(`unsupported-gyro-record`,`cannot tell the gyro sample layout from the first ${t.byteLength} bytes without the info record`)}function En(e,t){let n=Math.floor(e.byteLength/t.sampleSize),r=new Qe(e),i=new tn(n);for(let e=0;e<n;e+=1){let n=Dn(r,t,e*t.sampleSize);n&&i.push(n)}i.dropFlippedBits(t.flipSteps);let a=ln(i.captureTimes());return{track:i.toTrack(a.times),layout:t.name,strayBytes:e.byteLength%t.sampleSize,damagedSamples:n-i.length,mendedStamps:a.mended}}function Dn(e,t,n){try{let r=t.timestampAt(e,n);if(r===0&&On(e.bytesAt(n,t.sampleSize)))return;let i={captureTime:r,acceleration:t.accelerationAt(e,n),angularVelocity:t.angularVelocityAt(e,n)};return kn(i.acceleration,Sn)&&kn(i.angularVelocity,Cn)?i:void 0}catch(e){if(M(e,`binary-unsafe-integer`))return;throw e}}function On(e){return e.every(e=>e===0)}function kn(e,t){return e.every(e=>Math.abs(e)<=t)}function An(e,t){let n=jn(e,t);if(n.length<xn)return!1;let r=an(n);return r>=vn&&r<=yn}function jn(e,t){let n=new Qe(e),r=Math.floor(e.byteLength/t.sampleSize),i=[];for(let e=0;e<r;e+=1){let r=Mn(n,t,e*t.sampleSize);r!==void 0&&i.push(r)}return Float64Array.from(i)}function Mn(e,t,n){try{return t.timestampAt(e,n)}catch(e){if(M(e,`binary-unsafe-integer`))return;throw e}}function Nn(e,t){return t?t.captureTimeOf(e):ft(e)}function Pn(e,t){let n=e.firstFrameTimestamp;return n===void 0?void 0:Nn(n,t)}var Fn=class e{offset;length;constructor(e,t){this.offset=e,this.length=t}static of(t,n){if(!Number.isSafeInteger(t)||t<0)throw new j(`invalid-byte-range`,`offset must be a non-negative integer, got ${t}`);if(!Number.isSafeInteger(n)||n<0)throw new j(`invalid-byte-range`,`length must be a non-negative integer, got ${n}`);return new e(t,n)}static lastOf(e,t){if(t>e)throw new j(`invalid-byte-range`,`cannot take ${t} bytes from a ${e}-byte source`);return this.of(e-t,t)}get end(){return this.offset+this.length}overlaps(e){return Math.max(this.offset,e.offset)<Math.min(this.end,e.end)}contains(e){return this.offset<=e.offset&&e.end<=this.end}ensureWithin(e,t){if(!(this.end<=e))throw new j(`invalid-byte-range`,`range ${this.offset}+${this.length} exceeds the ${e}-byte ${t}`)}},In=class{source;trailer;info;gyroLayoutPromise;constructor(e,t,n){this.source=e,this.trailer=t,this.info=n}get listsExposure(){return this.trailer.locationOf(ze.Exposure)!==void 0}async readGyro(){let e=this.trailer.locationOf(ze.Gyro);if(e===void 0)return;let[t,n]=await Promise.all([this.source.read(e.payload),this.gyroSampleLayout()]);return N(n!==void 0,`a gyro record always yields or refuses a layout`),En(t,n)}async readExposure(){let e=this.trailer.locationOf(ze.Exposure);if(e===void 0)return;let[t,n]=await Promise.all([this.source.read(e.payload),this.gyroSampleLayout()]);return Mt(t,e=>Nn(e,n))}async firstFrameCaptureTime(){return Pn(this.info,await this.gyroSampleLayout())}gyroSampleLayout(){return this.gyroLayoutPromise??=this.selectGyroLayout(),this.gyroLayoutPromise}async selectGyroLayout(){let e=this.gyroLayoutHints();if(e.isRawGyro!==void 0)return Tn(e,void 0);let t=this.trailer.locationOf(ze.Gyro);return Tn(e,t===void 0?void 0:await this.readHeadOf(t))}gyroLayoutHints(){return{isRawGyro:this.info.isRawGyro,ranges:this.info.sensorRanges}}readHeadOf(e){let t=Math.min(wn,e.payload.length);return this.source.read(Fn.of(e.payload.offset,t))}},Ln=class e{format;id;payloadSize;constructor(e,t,n){this.format=e,this.id=t,this.payloadSize=n}static parse(t){if(t.byteLength!==6)throw new j(`invalid-trailer`,`record header must be 6 bytes, got ${t.byteLength}`);let n=new Qe(t);return new e(n.uint8At(0),n.uint8At(1),n.uint32LeAt(2))}};function Rn(e,t){if(e.byteLength%10!=0)throw new j(`invalid-trailer`,`index size ${e.byteLength} is not a multiple of 10`);let n=new Qe(e),r=[];for(let i=0;i<e.byteLength;i+=10){let e=zn(n,i,t);e&&r.push(e)}return r}function zn(e,t,n){let r=e.uint32LeAt(t+2);return r===0?void 0:{id:e.uint8At(t+0),format:e.uint8At(t+1),payload:Fn.of(n+e.uint32LeAt(t+6),r)}}function Bn(e,t){return t.lastHeader.id===ze.Index?Vn(e,t):Un(e,t)}async function Vn(e,t){let n=t.fileSize-72-6-t.lastHeader.payloadSize;Kn(n,t.lastHeader,t.payloadStart);let r=Fn.of(n,t.lastHeader.payloadSize),i=Rn(await e.read(r),t.payloadStart);for(let e of i)Hn(e,r.offset);return i}function Hn(e,t){if(e.payload.end>t)throw new j(`invalid-trailer`,`record ${e.id} at ${e.payload.offset}+${e.payload.length} lies outside the trailer`)}async function Un(e,t){let n=[],r=new Gn(e,t.payloadStart),i=t.fileSize-72;for(;i>t.payloadStart;){let e=Ln.parse(await r.bytesEndingAt(i,6)),a=i-6-e.payloadSize;Kn(a,e,t.payloadStart),n.push({id:e.id,format:e.format,payload:Fn.of(a,e.payloadSize)}),i=a}return n.toReversed()}var Wn=65536,Gn=class{source;trailerStart;chunkStart=0;chunk=/* @__PURE__ */ new Uint8Array;constructor(e,t){this.source=e,this.trailerStart=t}async bytesEndingAt(e,t){let n=e-t;if(n<this.trailerStart)throw new j(`invalid-trailer`,`a record header at ${n} lies before the trailer`);return n>=this.chunkStart&&e<=this.chunkStart+this.chunk.byteLength||await this.readChunkEndingAt(e),this.chunk.subarray(n-this.chunkStart,e-this.chunkStart)}async readChunkEndingAt(e){this.chunkStart=Math.max(this.trailerStart,e-Wn),this.chunk=await this.source.read(Fn.of(this.chunkStart,e-this.chunkStart))}};function Kn(e,t,n){if(e<n)throw new j(`invalid-trailer`,`record ${t.id} (${t.payloadSize} bytes) runs past the trailer start; records are not contiguous`)}var qn=class{footer;payloadStart;byId;constructor(e,t,n){this.footer=e,this.payloadStart=t,this.byId=new Map(n.map(e=>[e.id,e]))}get records(){return[...this.byId.values()]}locationOf(e){return this.byId.get(e)}},Jn=class e{trailerSize;version;constructor(e,t){this.trailerSize=e,this.version=t}static parse(t){if(t.byteLength!==72)throw new j(`invalid-trailer`,`footer must be 72 bytes, got ${t.byteLength}`);let n=new Qe(t);if(n.asciiAt(40,32)!==`8db42d694ccc418790edff439fe026bf`)throw new j(`invalid-trailer`,`file does not end with the Insta360 magic`);return new e(n.uint32LeAt(32),n.uint32LeAt(36))}},Yn=78;async function Xn(e,t){if(t<Yn)throw new j(`invalid-trailer`,`file of ${t} bytes is too small to hold a trailer`);let n=Zn(await e.read(Fn.lastOf(t,Yn)),t);return new qn(n.footer,n.payloadStart,await Bn(e,n))}function Zn(e,t){let n=new Qe(e),r=Jn.parse(n.bytesAt(6,72));if(r.trailerSize>t)throw new j(`invalid-trailer`,`trailer size ${r.trailerSize} exceeds file size ${t}`);return{fileSize:t,payloadStart:t-r.trailerSize,footer:r,lastHeader:Ln.parse(n.bytesAt(0,6))}}var Qn=class e{firstFrameCaptureTime;gyroOffset;firstFrameVideoTime;constructor(e,t=pt(0),n=R(0)){this.firstFrameCaptureTime=e,this.gyroOffset=t,this.firstFrameVideoTime=n}withFirstFrameAt(t){return new e(this.firstFrameCaptureTime,this.gyroOffset,t)}videoTimeOf(e){let t=ft(e-this.firstFrameCaptureTime);return R(this.firstFrameVideoTime+mt(t))}gyroVideoTimeOf(e){return R(this.videoTimeOf(e)-gt(this.gyroOffset))}captureTimeOf(e){let t=_t(R(e-this.firstFrameVideoTime));return ft(Math.round(this.firstFrameCaptureTime+t))}};async function $n(e){let t=await Xn(e,await e.size()),n=await kt(e,t),r=new In(e,t,n);return{info:n,calibration:Ie(n.calibration),listsExposureRecord:r.listsExposure,captureClock:async()=>{let e=await r.firstFrameCaptureTime();return e===void 0?void 0:new Qn(e,n.gyroOffset)},readGyroRecord:()=>r.readGyro(),readExposureRecord:()=>r.readExposure()}}var er={Insta360Trailer:`inst`},tr=/^[ -~]{4}$/u;function nr(e){return tr.test(e)}function rr(e){return e.some(e=>e.type===er.Insta360Trailer)?`inst-box`:`bare`}function ir(e,t){if(e.length<8)return;let n=e.asciiAt(4,4);if(!nr(n))return;let r=ar(e,t);return r!==void 0&&r.size>=r.headerSize&&r.size<=t?{type:n,...r}:void 0}function ar(e,t){let n=e.uint32BeAt(0);return n===1&&e.length>=16?or(e):{size:n===0?t:n,headerSize:8}}function or(e){try{return{size:e.uint64BeAt(8),headerSize:16}}catch(e){if(M(e,`binary-unsafe-integer`))return;throw e}}async function sr(e,t){let n=[],r=0;for(;r+8<=t;){let i=await cr(e,r,t);if(!i)break;n.push(i),r=i.range.end}return n}async function cr(e,t,n){let r=n-t,i=Math.min(16,r),a=ir(new Qe(await e.read(Fn.of(t,i))),r);return a&&{type:a.type,range:Fn.of(t,a.size)}}async function lr(e){let t=await e.size(),[n,r]=await Promise.all([sr(e,t),Xn(e,t)]);return{fileSize:t,boxes:n,trailerWrapper:rr(n),trailerVersion:r.footer.version,trailerPayloadStart:r.payloadStart,records:r.records.toSorted((e,t)=>e.id-t.id)}}var ur=1e3;async function dr(e){let[t,n]=await Promise.all([lr(e),$n(e)]),r=await gr(n),i=await _r(n,r);return{...fr(t),info:n.info,calibration:pr(n),calibrationWarnings:n.calibration.warnings,gyro:r,exposure:i}}function fr(e){return{fileSize:e.fileSize,boxes:e.boxes.map(e=>({type:e.type,offset:e.range.offset,size:e.range.length})),trailerWrapper:e.trailerWrapper,trailerVersion:e.trailerVersion,payloadStart:e.trailerPayloadStart,records:e.records.map(e=>({id:e.id,format:e.format,offset:e.payload.offset,size:e.payload.length}))}}function pr(e){let{calibration:t}=e.calibration;return t===void 0?void 0:{version:t.version,canvas:[t.canvas.width,t.canvas.height],lenses:t.lenses.map(e=>({lensIndex:e.lensIndex,model:e.model.kind,principalPoint:[e.model.principalPoint.x,e.model.principalPoint.y],orientationDegrees:[e.orientation.yaw,e.orientation.pitch,e.orientation.roll],translationMetres:e.translation}))}}function mr(e){let{track:t,layout:n,strayBytes:r,damagedSamples:i,mendedStamps:a}=e,o=Math.min(ur,t.length),s=0;for(let e=0;e<o;e+=1)s+=Wt(t.sampleAt(e).acceleration);let c=t.isEmpty?0:t.sampleAt(t.length-1).captureTime-t.sampleAt(0).captureTime;return{layout:n,samples:t.length,strayBytes:r,damagedSamples:i,mendedStamps:a,spanSeconds:mt(ft(c)),meanIntervalUs:t.meanSampleInterval,meanAccelerationMagnitudeG:o>0?s/o:void 0}}function hr(e,t){let n=0;for(let t=0;t<e.length;t+=1)n+=e.entryAt(t).shutterTime;let r=e.length>0;return{entries:e.length,firstCaptureTimeUs:r?e.entryAt(0).captureTime:void 0,lastCaptureTimeUs:r?e.entryAt(e.length-1).captureTime:void 0,meanShutterTimeSeconds:r?n/e.length:void 0,firstEncodedFrameEntry:t}}async function gr(e){try{let t=await e.readGyroRecord();return t===void 0?void 0:mr(t)}catch(e){if(!M(e,`unsupported-gyro-record`))throw e;return{unreadable:ie(e)}}}async function _r(e,t){if(!e.listsExposureRecord)return;if(t!==void 0&&`unreadable`in t)return{unread:`gyro layout unknown`};let n=await e.readExposureRecord();return n?hr(n,await vr(n,e)):{damaged:!0}}async function vr(e,t){let n=await t.captureClock();return n===void 0?void 0:e.indexAtOrAfter(n.firstFrameCaptureTime)}function yr(e,t,n){return Math.min(Math.max(e,t),n)}var br=.01,xr=class e{clock;captureTimes;shutterTimes;frameDuration;constructor(e){N(e.shutterTimes===void 0||e.shutterTimes.length===e.captureTimes.length,`frame time arrays disagree on the frame count`),this.clock=e.clock,this.captureTimes=e.captureTimes,this.shutterTimes=e.shutterTimes,this.frameDuration=e.frameDuration}static withoutShutterTimes(t){return new e({...t,shutterTimes:void 0})}get frameCount(){return this.captureTimes.length}frameAt(e){ae(e,this.frameCount,`frame`);let t=ft(this.captureTimes[e]??0),n=this.shutterTimes?.[e],r=n===void 0?void 0:R(n),i=this.clock.videoTimeOf(t);return{index:e,captureTime:t,videoTime:i,shutterTime:r,midExposureVideoTime:R(i+(r??0)/2)}}midExposureAt(e){let t=this.frameIndexAt(e);return t===void 0?void 0:this.frameAt(t).midExposureVideoTime}frameIndexAt(e){return this.frameCount===0?void 0:yr(this.frameDuration===void 0?this.lastCapturedAt(e):this.onFrameGrid(e,this.frameDuration),0,this.frameCount-1)}onFrameGrid(e,t){let n=(e-this.clock.firstFrameVideoTime)/t;return Math.floor(n+br)}lastCapturedAt(e){let t=this.clock.captureTimeOf(e),n=0,r=this.frameCount-1;for(;n<r;){let e=Math.ceil((n+r)/2);(this.captureTimes[e]??1/0)<=t?n=e:r=e-1}return n}};function Sr(e){let{exposureRecord:t,clock:n,frameCount:r}=e;if(!t)return;let i=t.indexAtOrAfter(n.firstFrameCaptureTime);if(t.length-i<r)return;let a=t.slice(i,r);return new xr({clock:n,captureTimes:Float64Array.from(a.captureTimes),shutterTimes:Float64Array.from(a.shutterTimes),frameDuration:e.frameDuration})}function Cr(e){let{trackTimestamps:t,clock:n,frameCount:r}=e;if(!t||t.length<r)return;let i=Float64Array.from(t.slice(0,r),e=>n.captureTimeOf(e));return xr.withoutShutterTimes({clock:n,captureTimes:i,frameDuration:e.frameDuration})}function wr(e){let{frameRate:t,clock:n,frameCount:r}=e;if(t===void 0||t<=0)return;let i=Float64Array.from({length:r},(e,r)=>n.captureTimeOf(R(n.firstFrameVideoTime+r/t)));return xr.withoutShutterTimes({clock:n,captureTimes:i,frameDuration:e.frameDuration})}var Tr={"exposure-record":Sr,"track-timestamps":Cr,nominal:wr},Er=[`exposure-record`,`track-timestamps`,`nominal`],Dr=[`track-timestamps`,`exposure-record`,`nominal`];function Or(e,t){let n=[];for(let r of Ar(t)){let t=Tr[r](e);if(t)return{frameTimes:t,source:r,warnings:n};n.push(`${r} unavailable`)}}function kr(e,t){let n=[];for(let r of Ar(t)){if(r===`track-timestamps`)return{needsTrackTimestamps:!0,resolveWith:n=>Or({...e,trackTimestamps:n},t)};let i=Tr[r]({...e,trackTimestamps:void 0});if(i)return{needsTrackTimestamps:!1,resolved:{frameTimes:i,source:r,warnings:n}};n.push(`${r} unavailable`)}return{needsTrackTimestamps:!1,resolved:void 0}}function Ar(e){return e===`track-timestamps`?Dr:Er}async function jr(e,t,n){let{info:r}=e,[i,a]=await Promise.all([t.frameCount(),e.readExposureRecord()]),o=kr({...n,frameCount:i,frameRate:r.frameRate,exposureRecord:a},r.preferredFrameTimeSource);return o.needsTrackTimestamps?o.resolveWith(await t.sampleTimestamps()):o.resolved}var Mr=[1,0,0,0,1,0,0,0,1];function Nr(e){let t=Math.cos(e),n=Math.sin(e);return[1,0,0,0,t,-n,0,n,t]}function Pr(e){let t=Math.cos(e),n=Math.sin(e);return[t,0,n,0,1,0,-n,0,t]}function Fr(e){let t=Math.cos(e),n=Math.sin(e);return[t,-n,0,n,t,0,0,0,1]}function Ir(e,t){let[n,r,i,a,o,s,c,l,u]=e,[d,f,p,m,h,g,_,v,y]=t;return[n*d+r*m+i*_,n*f+r*h+i*v,n*p+r*g+i*y,a*d+o*m+s*_,a*f+o*h+s*v,a*p+o*g+s*y,c*d+l*m+u*_,c*f+l*h+u*v,c*p+l*g+u*y]}function Lr(e){let[t,n,r,i,a,o,s,c,l]=e;return[t,i,s,n,a,c,r,o,l]}function Rr(e,t){let[n,r,i,a,o,s,c,l,u]=e,[d,f,p]=t;return[n*d+r*f+i*p,a*d+o*f+s*p,c*d+l*f+u*p]}function zr(e){let[t,n,r,i,a,o,s,c,l]=e;return t*(a*l-o*c)-n*(i*l-o*s)+r*(i*c-a*s)}function Br(e,t){let r=e.reduce((e,n,r)=>e+n*(t[r]??0),0);return n(Math.acos(yr((r-1)/2,-1,1)))}var Vr=/* @__PURE__ */ new Map([[`x`,[1,0,0]],[`y`,[0,1,0]],[`z`,[0,0,1]],[`-x`,[-1,0,0]],[`-y`,[0,-1,0]],[`-z`,[0,0,-1]]]);function Hr(e){let t=Vr.get(e);return N(t!==void 0,`unknown IMU axis ${e}`),t}function Ur(e){let[t,n,r]=e.map(e=>Hr(e));return[...t,...n,...r]}function Wr(e){return zr(Ur(e))===1}function Gr(e,t){return{...qr(e,t),isVerified:!0}}function Kr(e,t){return{...qr(e,t),isVerified:!1}}function qr(e,t){return N(Wr(t),`IMU axes ${t.join(`, `)} are not a rotation`),{name:e,toBody:Ur(t)}}function Jr(e,t){return Rr(e.toBody,t)}var Yr=[`x`,`z`,`-y`],Xr=Gr(`X5`,Yr),Zr=Gr(`X6`,Yr),Qr=Gr(`X4 Air`,Yr),$r=Gr(`A1`,[`-z`,`-x`,`y`]),ei=Gr(`X3`,Yr),ti=Kr(`ONE RS (unverified)`,[`-y`,`x`,`z`]),ni=Kr(`aligned (unverified)`,[`x`,`y`,`z`]),ri=/* @__PURE__ */ new Map([[`Antigravity A1`,$r],[`Insta360 X3`,ei],[`Insta360 X4 Air`,Qr],[`Insta360 X5`,Xr],[`Insta360 X6`,Zr],[`Insta360 OneRS`,ti]]);function ii(e){return ri.get(e.model?.trim()??``)??ni}function ai(e){let t=0,n=1/0;for(let[r,i]of e.entries())Number.isFinite(i)&&i<n&&(t=r,n=i);return t}var oi=.02,si=_t(R(1));function ci(e,t,n){let r=mt(e.meanSampleInterval??si),i=Math.max(1,Math.min(e.length,Math.round(n/r))),a=li(e,t),o=0;for(let e=0;e<i;e+=1)o+=a[e]??0;let s={start:0,sum:o};for(let t=1;t+i<=e.length;t+=1)o+=(a[t+i-1]??0)-(a[t-1]??0),o<s.sum&&(s={start:t,sum:o});return{start:s.start,end:s.start+i}}function li(e,t){let n=new Float64Array(e.length);for(let r=0;r<e.length;r+=1)n[r]=Wt(Jr(t,e.angularVelocityAt(r)));return n}function ui({gyro:e,frame:t},n,r){let i=Ut;for(let a=n.start;a<n.end;a+=1){let n=r(e.sampleAt(a));i=Jt(i,Jr(t,n))}return Xt(i,1/Math.max(n.end-n.start,1))}function di(e,t,n){let r=ui({gyro:e,frame:t},n,e=>e.angularVelocity);return Wt(r)<=oi?r:Ut}var fi=[0,0,0,1],pi=1e-12,mi=.9995;function hi(e,t){let n=Wt(e);if(n===0)return fi;let r=t/2,i=Math.sin(r)/n;return[e[0]*i,e[1]*i,e[2]*i,Math.cos(r)]}function gi(e){let t=Wt(e);return t<pi?fi:hi(e,n(t))}function _i(e,t){let[n,r,i,a]=e,[o,s,c,l]=t;return[a*o+n*l+r*c-i*s,a*s-n*c+r*l+i*o,a*c+n*s-r*o+i*l,a*l-n*o-r*s-i*c]}function vi(e){let[t,n,r,i]=e;return[-t,-n,-r,i]}function yi(e){let[t,n,r,i]=e,a=Math.sqrt(t*t+n*n+r*r+i*i);return a===0?fi:[t/a,n/a,r/a,i/a]}function bi(e,t){let[n,r,i,a]=e,[o,s,c]=t,l=2*(r*c-i*s),u=2*(i*o-n*c),d=2*(n*s-r*o);return[o+a*l+(r*d-i*u),s+a*u+(i*l-n*d),c+a*d+(n*u-r*l)]}function xi(e,t,n){let[r,i,a,o]=e,[s,c,l,u]=t,d=r*s+i*c+a*l+o*u;if(d<0&&(d=-d,[s,c,l,u]=[-s,-c,-l,-u]),d>mi)return yi([r+(s-r)*n,i+(c-i)*n,a+(l-a)*n,o+(u-o)*n]);let f=Math.acos(d),p=Math.sin(f),m=Math.sin((1-n)*f)/p,h=Math.sin(n*f)/p;return[r*m+s*h,i*m+c*h,a*m+l*h,o*m+u*h]}function Si(e){let[t,n,r,i]=e;return[1-2*(n*n+r*r),2*(t*n-r*i),2*(t*r+n*i),2*(t*n+r*i),1-2*(t*t+r*r),2*(n*r-t*i),2*(t*r-n*i),2*(n*r+t*i),1-2*(t*t+n*n)]}var Ci=[0,1,0],wi=.9,Ti=1.1;function Ei(e){let t=Wt(e);return t>=wi&&t<=Ti?Xt(e,-1/t):void 0}function Di(e,t){let n=Ei(t);return n?Kt(n,bi(vi(e),Ci)):[0,0,0]}function Oi(e,t){if(e.isEmpty)return{start:0,end:0};let n=e.sampleAt(0).captureTime,r=_t(t),i=1;for(;i<e.length&&e.sampleAt(i).captureTime-n<=r;)i+=1;return{start:0,end:i}}function ki(e,t,n){if(e.isEmpty)return fi;let r=Oi(e,n),i=Ei(ui({gyro:e,frame:t},r,e=>e.acceleration));return i?Ai(i,Ci):fi}function Ai(e,t){let r=Kt(e,t),i=Gt(e,t),a=Wt(r);return a>0?hi(r,n(Math.atan2(a,i))):i>0?fi:hi(ji(e),n(Math.PI))}function ji(e){return Math.abs(e[0])<Math.abs(e[2])?[0,-e[2],e[1]]:[-e[1],e[0],0]}var Mi=l(o),Ni=l(t(-o)),Pi=l(s),Fi={name:`upright`,toBody:Vi(n(0))},Ii=[0,1,0],Li=[0,0,1],Ri=[Fi,{name:`upside down`,toBody:Vi(Pi)},{name:`on its right side`,toBody:Vi(Ni)},{name:`on its left side`,toBody:Vi(Mi)}],zi=[{name:`with lens 0 up`,toBody:Hi(Ni)},{name:`with lens 0 down`,toBody:Hi(Mi)}],Bi=Math.cos(l(t(30)));function Vi(e){return Ir(Fr(e),Pr(Pi))}function Hi(e){return Ir(Nr(e),Pr(Ni))}function Ui(e,t){if(!t.isVerified)return Fi;let n=qi(e,t),r=Wi(n)?zi:Ri;return r[ai(r.map(e=>-Gt(Rr(e.toBody,Ii),n)))]??Fi}function Wi(e){return Math.abs(Gt(e,Li))>Bi*Wt(e)}function Gi(e,t){return{...e,toBody:Ir(Lr(t.toBody),e.toBody)}}function Ki(e,t){return Ir(e.toBody,t)}function qi(e,t){let n=Ut;for(let r=0;r<e.length;r+=1){let i=Ei(Jr(t,e.sampleAt(r).acceleration));i&&(n=Jt(n,i))}return n}var Ji=.2,Yi=.5,Xi=.5,Zi=4,Qi=.05,$i=class e{videoTimes;quaternions;constructor(e,t){this.videoTimes=e,this.quaternions=t,N(t.length===e.length*Zi,`orientation track arrays disagree on the sample count`)}static integrate(t){let{gyro:n,clock:r,frame:i}=t,a=new Float64Array(n.length),o=new Float32Array(n.length*Zi);if(n.isEmpty)return new e(a,o);let s={frame:i,bias:di(n,i,ci(n,i,R(Yi))),gravityGain:t.options?.gravityGain??Ji};a.set(ea(n,r));let c={orientation:ki(n,i,R(Xi)),time:R(a[0]??0),rate:Ut};for(let e=0;e<n.length;e+=1){let t=R(a[e]??c.time);c=na(c,{sample:ta(n,e),time:t},s),o.set(c.orientation,e*Zi)}return new e(a,o)}get length(){return this.videoTimes.length}orientationAt(e){if(this.length===0)return fi;let t=this.firstIndexAfter(e);if(t===0)return this.quaternionAt(0);if(t>=this.length)return this.quaternionAt(this.length-1);let n=t-1,r=(this.videoTimes[t]??0)-(this.videoTimes[n]??0),i=r>0?(e-(this.videoTimes[n]??0))/r:0;return xi(this.quaternionAt(n),this.quaternionAt(t),i)}quaternionAt(e){let t=e*Zi,[n=0,r=0,i=0,a=1]=this.quaternions.subarray(t,t+Zi);return[n,r,i,a]}firstIndexAfter(e){let t=0,n=this.length;for(;t<n;){let r=Math.floor((t+n)/2);(this.videoTimes[r]??1/0)<=e?t=r+1:n=r}return t}};function ea(e,t){return e.captureTimes.map(e=>t.gyroVideoTimeOf(ft(e)))}function ta(e,t){let n=e.sampleAt(t);return N(qt(n.acceleration)&&qt(n.angularVelocity),`gyro sample ${t} is not finite`),n}function na(e,{sample:t,time:n},r){let{frame:i,bias:a,gravityGain:o}=r,s=yr(n-e.time,0,Qi),c=Di(e.orientation,Jr(i,t.acceleration));return{orientation:ia(e.orientation,ra(e.rate,c,o),s),time:n,rate:Yt(Jr(i,t.angularVelocity),a)}}function ra(e,t,n){return Jt(e,Xt(t,n))}function ia(e,t,n){return yi(_i(e,gi(Xt(t,n))))}var aa=`the recording has no gyro record; stabilization is unavailable`;async function oa(e,t){let n=await e.readGyroRecord();if(!n)return{setup:void 0,warnings:[aa]};let r=ii(e.info),i=Ui(n.track,r),a=Gi(r,i),o=$i.integrate({gyro:n.track,clock:t,frame:a}),s=[...ca(r,e),...sa(n)];return{setup:{orientations:o,mounting:i,imuFrame:r},warnings:s}}function sa(e){return[...e.damagedSamples>0?[`damaged gyro samples left out of stabilization: ${e.damagedSamples}`]:[],...e.mendedStamps>0?[`gyro stamps off their neighbours mended: ${e.mendedStamps}`]:[]]}function ca(e,t){return e.isVerified?[]:[`the IMU frame of ${t.info.model??`this camera`} has not been verified on a recording; stabilization may misbehave`]}var la=`frame timing and stabilization are unavailable`,ua=`the recording has no capture clock; ${la}`,da=`the recording has no frame source to time; ${la}`,fa=`no frame timing source is usable; frames are timed by their track timestamps`;async function pa(e,t){try{return await ma(e,t)}catch(e){if(!M(e,`unsupported-gyro-record`))throw e;return ga([`${ie(e)}; ${la}`])}}async function ma(e,t){let n=await e.captureClock();if(!n)return ga([ua]);if(!t)return ga([da]);let r=await ha(n,t),[i,a]=await Promise.all([jr(e,t,r),oa(e,r.clock)]);return{frameTimes:i?.frameTimes,frameTimeSource:i?.source,motion:a.setup,warnings:[...i?.warnings??[fa],...a.warnings]}}async function ha(e,t){let n=await t.firstKeyframe(),r=n!==void 0&&n.duration>0;return{clock:e.withFirstFrameAt(n?.timestamp??R(0)),frameDuration:r?n.duration:void 0}}function ga(e){return{frameTimes:void 0,frameTimeSource:void 0,motion:void 0,warnings:e}}var _a=/^(?<prefix>[A-Za-z]+(?:_[A-Za-z]+)*)_(?<stamp>\d{8}_\d{6})_(?<lens>\d)(?<proxy>\d)_(?<sequence>\d{3})\.(?<extension>[A-Za-z0-9]+)$/u,va=0,ya=1,ba=0,xa=1,Sa=class e{parts;constructor(e){this.parts=e}static parse(t){let n=_a.exec(t)?.groups;return n?new e(Ca(n)):void 0}get isBackLens(){return this.parts.lensDigit===va}get isScreenLens(){return this.parts.lensDigit===ya}get isProxy(){return this.parts.proxyDigit===xa}otherLensName(){let t=this.isBackLens?ya:va;return new e({...this.parts,lensDigit:t,proxyDigit:ba}).toString()}toString(){let{prefix:e,captureStamp:t,lensDigit:n,proxyDigit:r,sequence:i,extension:a}=this.parts;return`${e}_${t}_${n}${r}_${i}.${a}`}};function Ca(e){return{prefix:e.prefix??``,captureStamp:e.stamp??``,lensDigit:Number(e.lens),proxyDigit:Number(e.proxy),sequence:e.sequence??``,extension:e.extension??``}}var wa=/[#?]/u;function Ta(e){let t=e.search(wa);return t===-1?{path:e,suffix:``}:{path:e.slice(0,t),suffix:e.slice(t)}}function Ea(e){let{path:t}=Ta(e),n=t.slice(t.lastIndexOf(`/`)+1);try{return decodeURIComponent(n)}catch{return n}}async function Da(e,t){let n=Sa.parse(Ea(e));if(!n)return;let r=Oa(e,n.otherLensName());return await t.exists(r)?r:void 0}function Oa(e,t){let{path:n,suffix:r}=Ta(e);return`${n.slice(0,n.lastIndexOf(`/`)+1)}${encodeURIComponent(t)}${r}`}var ka={FileType:`ftyp`,MediaData:`mdat`,Movie:`moov`,MovieHeader:`mvhd`,MovieExtends:`mvex`,Track:`trak`,TrackHeader:`tkhd`,Edit:`edts`,EditList:`elst`,Media:`mdia`,MediaHeader:`mdhd`,Handler:`hdlr`,MediaInformation:`minf`,SampleTable:`stbl`,SampleDescription:`stsd`,TimeToSample:`stts`,CompositionOffset:`ctts`,SyncSample:`stss`,SampleToChunk:`stsc`,SampleSize:`stsz`,ChunkOffset:`stco`,ChunkLargeOffset:`co64`,AvcConfiguration:`avcC`,HevcConfiguration:`hvcC`},Aa={Video:`vide`,Sound:`soun`},ja=[`avc1`,`avc3`],Ma=[`hvc1`,`hev1`],Na={isKeyframe:()=>!0},Pa=31,Fa=1,Ia=4,La=5,Ra=1,za=63,Ba=16,Va=23,Ha={typeOf:e=>e&Pa,verdictOn:e=>e===La?`keyframe`:e>=Fa&&e<=Ia?`not-a-keyframe`:`read-on`},Ua={typeOf:e=>e>>Ra&za,verdictOn:e=>e<Ba?`not-a-keyframe`:e<=Va?`keyframe`:`read-on`},Wa=8,Ga=class{family;lengthSize;constructor(e,t){this.family=e,this.lengthSize=t}isKeyframe(e){let t=0;for(;t+this.lengthSize<e.length;){let n=t+this.lengthSize,r=n+Ka(e,t,this.lengthSize);if(r>e.length)return!1;let i=this.family.verdictOn(this.family.typeOf(e[n]??0));if(i!==`read-on`)return i===`keyframe`;t=r}return!1}};function Ka(e,t,n){let r=0;for(let i=0;i<n;i+=1)r=r*2**Wa+(e[t+i]??0);return r}var qa=[[ja,Ha],[Ma,Ua]];function Ja(e){let{sampleEntryType:t,nalLengthSize:n}=e,[,r]=qa.find(([e])=>e.includes(t))??[];return r&&n!==void 0?new Ga(r,n):Na}function Ya(e){let t=[],n=0;for(;e.byteLength-n>=8;){let r=e.byteLength-n,i=ir(new Qe(e.subarray(n,n+16)),r);if(!i)throw $a(`holds no box at byte ${n} of ${e.byteLength}`);let a=e.subarray(n+i.headerSize,n+i.size);t.push({type:i.type,body:a}),n+=i.size}return t}function Xa(e,t){let n=Za(e,t);if(!n)throw $a(`has no ${t} box where one belongs`);return n}function Za(e,t){return e.find(e=>e.type===t)}function Qa(e){if(e.body.byteLength<4)throw $a(`has a ${e.type} box too short for its version and flags`);return{version:e.body[0]??0,content:new Qe(e.body.subarray(4))}}function $a(e){return new j(`unsupported-container`,`the movie box ${e}`)}var eo={0:{timescale:8,duration:{offset:12,kind:`uint32`},size:96},1:{timescale:16,duration:{offset:20,kind:`uint64`},size:108}},to={0:8,1:16},no={0:{timescale:8,duration:{offset:12,kind:`uint32`},size:20},1:{timescale:16,duration:{offset:20,kind:`uint64`},size:32}},ro={entrySize:8,fields:{sampleCount:{offset:0,kind:`uint32`},sampleDelta:{offset:4,kind:`uint32`}}},io={entrySize:8,fields:{sampleCount:{offset:0,kind:`uint32`},sampleOffset:{offset:4,kind:`int32`}}},ao={entrySize:4,fields:{sampleNumber:{offset:0,kind:`uint32`}}},oo={0:{entrySize:12,fields:{segmentDuration:{offset:0,kind:`uint32`},mediaTime:{offset:4,kind:`int32`},mediaRate:{offset:8,kind:`uint32`}}},1:{entrySize:20,fields:{segmentDuration:{offset:0,kind:`uint64`},mediaTime:{offset:8,kind:`int64`},mediaRate:{offset:16,kind:`uint32`}}}},so={entrySize:12,fields:{firstChunk:{offset:0,kind:`uint32`},samplesPerChunk:{offset:4,kind:`uint32`},sampleDescriptionIndex:{offset:8,kind:`uint32`}}},co={entrySize:4,fields:{chunkOffset:{offset:0,kind:`uint32`}}},lo={entrySize:8,fields:{chunkOffset:{offset:0,kind:`uint64`}}},uo={uint32:(e,t)=>e.uint32BeAt(t),uint64:(e,t)=>e.uint64BeAt(t),int32:(e,t)=>e.int32BeAt(t),int64:(e,t)=>e.int64BeAt(t)};function fo(e,t,n=0){return uo[t.kind](e,n+t.offset)}function po(e,t){let n=e.uint32BeAt(0);if(4+n*t.entrySize>e.length)throw $a(`has a table of ${n} entries that do not fit in its box`);let r=Object.keys(t.fields),i={};for(let a of r)i[a]=Array.from({length:n},(n,r)=>fo(e,t.fields[a],4+r*t.entrySize));return i}var mo=1;function ho(e){let t=go(Xa(e,ka.SampleSize)),n=_o(e),r=Qa(Xa(e,ka.SampleToChunk)).content;return{offsets:yo({sizes:t,chunkOffsets:n,perChunk:vo(po(r,so),n.length)}),sizes:t}}function go(e){let{content:t}=Qa(e),n=t.uint32BeAt(0),r=t.uint32BeAt(4);if(n!==0)return new Float64Array(r).fill(n);if(8+r*4>t.length)throw $a(`lists ${r} sample sizes that do not fit in its box`);return Float64Array.from({length:r},(e,n)=>t.uint32BeAt(8+n*4))}function _o(e){let t=Za(e,ka.ChunkLargeOffset),n=t??Za(e,ka.ChunkOffset);if(!n)throw $a(`has a sample table without chunk offsets`);let r=t?lo:co;return po(Qa(n).content,r).chunkOffset}function vo(e,t){let n=Array.from({length:t},()=>0);for(let[r,i]of e.firstChunk.entries()){let a=e.firstChunk[r+1]??t+mo,o=e.samplesPerChunk[r]??0;n.fill(o,i-mo,a-mo)}return n}function yo(e){let t=new Float64Array(e.sizes.length),n=0;for(let[r,i]of e.chunkOffsets.entries()){let a=i,o=Math.min(n+(e.perChunk[r]??0),t.length);for(;n<o;n+=1)t[n]=a,a+=e.sizes[n]??0}if(n<t.length)throw $a(`has chunks for ${n} of its ${t.length} samples`);return t}var bo=4,xo=/* @__PURE__ */ new Map([[ka.AvcConfiguration,4],[ka.HevcConfiguration,21]]);function So(e){let t=Qa(Xa(e,ka.MovieHeader));return t.content.uint32BeAt(To(t,eo,ka.MovieHeader).timescale)}function Co(e){let t=Ya(e.body),n=Ya(Xa(t,ka.Media).body);return{track:t,media:n,sampleTable:Ya(Xa(Ya(Xa(n,ka.MediaInformation).body),ka.SampleTable).body)}}function wo(e){let t=Oo(e.media),n=ko(e.sampleTable);return{trackId:Eo(e.track),handlerType:t,mediaTimescale:Do(e.media),sampleEntryType:n.type,nalLengthSize:t===Aa.Video?Ao(n):void 0}}function To(e,t,n){let r=e.version===0||e.version===1?t[e.version]:void 0;if(r===void 0)throw $a(`has a ${n} box of version ${e.version}`);return r}function Eo(e){let t=Qa(Xa(e,ka.TrackHeader));return t.content.uint32BeAt(To(t,to,ka.TrackHeader))}function Do(e){let t=Qa(Xa(e,ka.MediaHeader));return t.content.uint32BeAt(To(t,no,ka.MediaHeader).timescale)}function Oo(e){let{content:t}=Qa(Xa(e,ka.Handler));return t.asciiAt(4,bo)}function ko(e){let{content:t}=Qa(Xa(e,ka.SampleDescription)),n=t.length-4,[r]=Ya(t.bytesAt(4,n));if(!r)throw $a(`has a track without a sample entry`);return r}function Ao(e){let t=Ya(e.body.subarray(78)).find(e=>xo.has(e.type)),n=t?.body[xo.get(t.type)??0];return n===void 0?void 0:(n&3)+1}function jo(e){return Array.from({length:e.length},(e,t)=>t).toSorted((t,n)=>(e[t]??0)-(e[n]??0))}function Mo(e,t){let n=No(Xa(e.sampleTable,ka.TimeToSample),t),r=Po(e.sampleTable,t.sampleCount),i=r?n.times.map((e,t)=>e+(r[t]??0)):n.times,a=Io(e.track,t),o=i.map(e=>(e-a)/t.media),s=(r?Lo(i,n.deltas):n.deltas).map(e=>e/t.media);return{timestamps:o,durations:s,end:Ro(o,s,t.media)}}function No(e,t){let n=po(Qa(e).content,ro),r=Fo(n.sampleCount,n.sampleDelta);if(r.length!==t.sampleCount)throw $a(`times ${r.length} samples of a track that has ${t.sampleCount}`);let i=new Float64Array(r.length);for(let e=1;e<r.length;e+=1)i[e]=(i[e-1]??0)+(r[e-1]??0);return{times:i,deltas:r}}function Po(e,t){let n=Za(e,ka.CompositionOffset);if(!n)return;let r=po(Qa(n).content,io),i=new Float64Array(t);return i.set(Fo(r.sampleCount,r.sampleOffset).subarray(0,t)),i}function Fo(e,t){let n=e.reduce((e,t)=>e+t,0),r=new Float64Array(n),i=0;for(let[n,a]of e.entries())r.fill(t[n]??0,i,i+a),i+=a;return r}function Io(e,t){let n=Za(e,ka.Edit),r=n&&Za(Ya(n.body),ka.EditList);if(!r)return 0;let i=Qa(r),a=po(i.content,To(i,oo,ka.EditList)),o=0;for(let[e,n]of a.mediaTime.entries()){if(n===-1){o+=a.segmentDuration[e]??0;continue}return a.mediaRate[e]===65536?n-Math.round(o/t.movie*t.media):0}return 0}function Lo(e,t){let n=jo(e),r=Float64Array.from(t);for(let t=0;t<n.length-1;t+=1){let i=n[t]??0;r[i]=(e[n[t+1]??0]??0)-(e[i]??0)}return r}function Ro(e,t,n){let r=jo(e).at(-1);if(r===void 0)return R(0);let i=(e[r]??0)+(t[r]??0);return R(Math.round(i*n)/n)}var zo=class{tracks;constructor(e){this.tracks=e}get videoTracks(){return this.tracks.filter(e=>e.kind===`video`)}get audioTracks(){return this.tracks.filter(e=>e.kind===`audio`)}get duration(){return R(Math.max(0,...this.tracks.map(e=>e.end)))}trackWithId(e){return this.tracks.find(t=>t.trackId===e)}};function Bo(e,t,n){let r=0,i=e;for(;r<i;){let e=r+i>>>1;t(e)<=n?r=e+1:i=e}return r}var Vo=class{parts;trackId;kind;end;keyframeRule;presentationOrder;constructor(e){this.parts=e;let{length:t}=e.offsets;N([e.sizes,e.timestamps,e.durations].every(e=>e.length===t),`the sample table of track ${e.trackId} disagrees on its sample count`),N(Ho(e.syncSamples??[],t),`the sync samples of track ${e.trackId} are not samples of it in order`),this.trackId=e.trackId,this.kind=e.kind,this.end=e.end,this.keyframeRule=e.keyframeRule,this.presentationOrder=jo(e.timestamps)}get sampleCount(){return this.parts.offsets.length}rangeOf(e){return this.ensureSample(e),Fn.of(this.parts.offsets[e]??0,this.parts.sizes[e]??0)}timestampOf(e){return this.ensureSample(e),R(this.parts.timestamps[e]??0)}durationOf(e){return this.ensureSample(e),R(this.parts.durations[e]??0)}isSync(e){return this.ensureSample(e),this.syncSampleAtOrBefore(e)===e}sampleShownAt(e){let t=Bo(this.presentationOrder.length,e=>this.parts.timestamps[this.presentationOrder[e]??0]??1/0,e);return this.presentationOrder[t-1]}keyframeAt(e){let t=this.sampleShownAt(e);return t===void 0?void 0:this.syncSampleAtOrBefore(t)}syncSampleAtOrBefore(e){let{syncSamples:t}=this.parts;return t?t[Bo(t.length,e=>t[e]??0,e)-1]:e>=0?e:void 0}syncSampleAtOrAfter(e){let{syncSamples:t}=this.parts,n=Math.max(0,e);return t?t[Bo(t.length,e=>t[e]??0,n-1)]:n<this.sampleCount?n:void 0}timestampsInPresentationOrder(){return this.presentationOrder.map(e=>R(this.parts.timestamps[e]??0))}ensureSample(e){ae(e,this.sampleCount,`sample of track ${this.trackId}`)}};function Ho(e,t){return e.every((n,r)=>Number.isSafeInteger(n)&&n>=0&&n<t&&n>(e[r-1]??-1))}var Uo={[Aa.Video]:`video`,[Aa.Sound]:`audio`},Wo=1;function Go(e){let[t]=Ya(e);if(t?.type!==ka.Movie)throw $a(`is not where the file says it is`);let n=Ya(t.body);if(Za(n,ka.MovieExtends))throw $a(`is fragmented: its samples are described in movie fragments after it`);let r=So(n);return new zo(n.filter(e=>e.type===ka.Track).flatMap(e=>Ko(Co(e),r)))}function Ko(e,t){let n=wo(e),r=Uo[n.handlerType];if(!r)return[];let i=ho(e.sampleTable),a=Mo(e,{media:n.mediaTimescale,movie:t,sampleCount:i.sizes.length});return[new Vo({trackId:n.trackId,kind:r,...i,...a,syncSamples:qo(e.sampleTable),keyframeRule:Ja(n)})]}function qo(e){let t=Za(e,ka.SyncSample);if(!t)return;let{sampleNumber:n}=po(Qa(t).content,ao);return n.map(e=>e-Wo)}function Jo(e){let t=new Uint8Array(e.reduce((e,t)=>e+t.byteLength,0)),n=0;for(let r of e)t.set(r,n),n+=r.byteLength;return t}async function Yo(e){let t=await sr(e,await e.size()),n=t.find(e=>e.type===ka.Movie);if(!n)throw new j(`unsupported-container`,`the file has no movie box to read its samples from`);let r=t.find(e=>e.type===ka.FileType),[i,a]=await Promise.all([Xo(e,r),Xo(e,n)]);return{table:Go(a),movieBytes:Jo([i,a])}}function Xo(e,t){return t?e.read(t.range):Promise.resolve(/* @__PURE__ */ new Uint8Array)}var Zo={x:0,y:0,width:1,height:1},Qo={x:0,y:0,width:.5,height:1},$o={x:.5,y:0,width:.5,height:1},es=2,ts=2,ns=.02,rs=0,is=1,as=2;function os(e,t){let n=e.flatMap((e,t)=>e.videoTracks.map(({description:n})=>({input:e,inputIndex:t,track:n})));if(e.length===1&&ds(n))return ss(n,t);if(e.length===es&&fs(e,n))return cs(e,n);let[r]=n;if(r&&n.length===1&&ms(r.track))return ls(r);throw gs(e,n)}function ss(e,t){let n=t.trackOrder===`stream-10-first`,r=n?e.toReversed():e,i=t.fileLayout===void 0?[]:[`info record file layout ${t.fileLayout}`],a=t.trackOrder===void 0?`no track order hint: lens 0 assumed to be track 0`:`info record track order ${t.trackOrder}: lens 0 is track ${+!!n}`;return{kind:`multi-track`,sources:r.map((e,t)=>us(e,t)),evidence:[`one input with two video tracks`,...i,a]}}function cs(e,t){let n=t.toSorted((e,t)=>hs(e.input)-hs(t.input)),r=e.map(e=>e.name??`?`).join(`, `);return{kind:`split-files`,sources:n.map((e,t)=>us(e,t)),evidence:[`two inputs with one video track each (${r})`,`lens 0 taken from the _00_ file when named`]}}function ls(e){let{inputIndex:t,track:n}=e;return{kind:`packed`,sources:[{lensIndex:0,inputIndex:t,trackIndex:n.trackIndex,region:Qo},{lensIndex:1,inputIndex:t,trackIndex:n.trackIndex,region:$o}],evidence:[`single ${n.codedWidth}x${n.codedHeight} track with a 2:1 aspect ratio`]}}function us(e,t){return{lensIndex:t,inputIndex:e.inputIndex,trackIndex:e.track.trackIndex,region:Zo}}function ds(e){let[t,n]=e;return e.length===es&&t!==void 0&&n!==void 0&&ps(t.track)&&t.track.codedWidth===n.track.codedWidth&&t.track.codedHeight===n.track.codedHeight}function fs(e,t){return t.length===es&&e.every(e=>e.videoTracks.length===1)&&t.every(e=>ps(e.track))}function ps(e){return e.codedWidth===e.codedHeight}function ms(e){return Math.abs(e.codedWidth/e.codedHeight-ts)<=ns}function hs(e){let t=Sa.parse(e.name??``);return t?.isBackLens?rs:t?.isScreenLens?as:is}function gs(e,t){let[n]=t;if(e.length===1&&t.length===1&&n!==void 0&&ps(n.track))return _s(n.input);let r=t.map(e=>`${e.track.codedWidth}x${e.track.codedHeight}`).join(`, `);return new j(`unsupported-layout`,`cannot map ${t.length} video track(s) [${r}] in ${e.length} file(s) onto two lenses`)}function _s(e){let t=Sa.parse(e.name??``);return new j(`missing-second-file`,`this recording stores one lens per file; provide ${t?`the matching ${t.otherLensName()}`:`the other lens's file`} as the second source`)}var vs=6,ys=32,bs=31,xs=1,Ss=5,Cs=6,ws=11,Ts=32,Es=0,Ds=33,Os=3,ks=3,As=2,js=[``,`A`,`B`,`C`],Ms=`L`,Ns=`H`,Ps=16;function Fs(e,t){return Us(e,Is(t))}function Is(e){let t=Rs(new Qe(e),1);return t.profile===Es?Ls(e)??t:t}function Ls(e){try{let t=Bs(e);return t===void 0?void 0:zs(t)}catch(e){if(M(e,`binary-out-of-bounds`))return;throw e}}function Rs(e,t){let n=e.uint8At(t);return{profileSpace:n>>vs,isHighTier:(n&ys)!==0,profile:n&bs,compatibilityFlags:e.uint32BeAt(t+xs),constraintFlags:[...e.bytesAt(t+Ss,Cs)],level:e.uint8At(t+ws)}}function zs(e){return Rs(new Qe(Hs(e)),Os)}function Bs(e){let t=new Qe(e),n=23;for(let e=0;e<t.uint8At(22);e+=1){let e=Vs(t,n),[r]=e.nalUnitType===Ds?e.nalUnits:[];if(r!==void 0)return r;n=e.end}}function Vs(e,t){let n=e.uint8At(t)&63,r=e.uint16BeAt(t+1),i=[],a=t+3;for(let t=0;t<r;t+=1){let t=e.uint16BeAt(a);i.push(e.bytesAt(a+2,t)),a+=2+t}return{nalUnitType:n,nalUnits:i,end:a}}function Hs(e){let t=[],n=0;for(let r of e)n>=As&&r===ks||t.push(r),n=r===0?n+1:0;return Uint8Array.from(t)}function Us(e,t){let n=`${js[t.profileSpace]??``}${t.profile}`,r=t.isHighTier?Ns:Ms,i=Gs(t.constraintFlags).map(e=>Ks(e));return[e,n,Ks(Ws(t.compatibilityFlags)),`${r}${t.level}`,...i].join(`.`)}function Ws(e){let t=0;for(let n=0;n<Ts;n+=1)t=t<<1|e>>>n&1;return t>>>0}function Gs(e){let t=e.findLastIndex(e=>e!==0);return e.slice(0,t+1)}function Ks(e){return e.toString(Ps).toUpperCase()}var qs=[`off`,`lock`,`horizon`,`follow`],Js=`lock`,Ys=class{nextRotation(){return Mr}},Xs=class{nextRotation(e){return Si(vi(e))}},Zs=class{nextRotation(e){let t=hi(Ci,nc(e));return Ir(Si(vi(e)),Si(t))}},Qs={timeConstant:R(1.5),maxContinuousGap:R(1)},$s=class{options;smoothed;previousTime;constructor(e=Qs){this.options=e}nextRotation(e,t){return this.smoothed=this.follow(e,t),this.previousTime=t,Ir(Si(vi(e)),Si(this.smoothed))}follow(e,t){let n=this.previousTime===void 0?1/0:t-this.previousTime;if(!this.smoothed||Math.abs(n)>this.options.maxContinuousGap)return e;if(n<=0)return this.smoothed;let r=1-Math.exp(-n/this.options.timeConstant);return xi(this.smoothed,e,r)}},ec={off:()=>new Ys,lock:()=>new Xs,horizon:()=>new Zs,follow:()=>new $s};function tc(e){return ec[e]()}function nc(e){let[,t,,r]=e;return n(2*Math.atan2(t,r))}function rc(e){return t(2*(Math.round(e/o)*o)-e)}function ic(e){let{yaw:n,pitch:r,roll:i}=e.orientation,a=Pr(l(n)),o=Ir(Nr(l(r)),a),c=Ir(Nr(l(t(s*e.lensIndex))),o);return Ir(Fr(l(rc(i))),c)}var ac=1.5,oc=.01,sc=[1,1,1],cc={maxGain:2,timeConstant:R(ac)};function lc(e,t){let[n]=e;return n?e.map((e,r)=>r===0?sc:uc(n,e,t)):[]}function uc(e,t,n){return[dc(e[0],t[0],n),dc(e[1],t[1],n),dc(e[2],t[2],n)]}function dc(e,t,n){return e<oc||t<oc?1:yr(e/t,1/n,n)}var fc=class{options;current;lastTime;constructor(e=cc){this.options=e}update(e,t){let n=lc(e,this.options.maxGain),r=this.lastTime===void 0?1/0:Math.max(t-this.lastTime,0);this.lastTime=t;let i=this.current?1-Math.exp(-r/this.options.timeConstant):1,a=this.current;return this.current=n.map((e,t)=>Zt(a?.[t]??sc,e,i)),this.current}},pc=30,mc=120,hc=90,gc=90,_c={yaw:t(0),pitch:t(0),roll:t(0),fieldOfView:t(hc)};function vc(e){return N([e.yaw,e.pitch,e.roll,e.fieldOfView].every(e=>Number.isFinite(e)),`view angles must be finite`),{...e,yaw:d(e.yaw),roll:d(e.roll),pitch:t(yr(e.pitch,-90,gc)),fieldOfView:t(yr(e.fieldOfView,pc,mc))}}function yc(e,t){return e.yaw===t.yaw&&e.pitch===t.pitch&&e.roll===t.roll&&e.fieldOfView===t.fieldOfView}function bc(e){return Ir(Ir(Pr(l(e.yaw)),Nr(l(e.pitch))),Fr(l(e.roll)))}var xc=[`fast`,`balanced`,`high`],Sc=`balanced`,Cc={fast:1,balanced:2,high:3};function wc(e){return Cc[e]}var Tc=[`raw-lenses`,`equirectangular`,`normal`],Ec=`raw-lenses`,Dc=.5,Oc={x:0,y:0,width:1,height:1},kc={x:Dc,y:Dc};function Ac(e){return Math.max(e,1)}function jc(e){return e.width/Ac(e.height)}function Mc(e,t){return{across:e.x/Ac(t.width),down:e.y/Ac(t.height)}}function Nc(e,t){return{x:(t.x-e.x)/e.width,y:(t.y-e.y)/e.height}}function Pc(e,t){let n=Rc(e,t),r=Rc(1/e,t);return n.height>=r.height/e?Fc(n,e):Ic(r,e)}function Fc(e,t){let n=e.width/t;return Array.from({length:t},(t,r)=>({...e,x:e.x+r*n,width:n}))}function Ic(e,t){let n=e.height/t;return Array.from({length:t},(t,r)=>({...e,y:e.y+r*n,height:n}))}function Lc(e){N(e.length>0,`bounds need at least one rectangle`);let t=Math.min(...e.map(e=>e.x)),n=Math.min(...e.map(e=>e.y)),r=Math.max(...e.map(e=>e.x+e.width)),i=Math.max(...e.map(e=>e.y+e.height));return{x:t,y:n,width:r-t,height:i-n}}function Rc(e,t){if(e>=t){let n=t/e;return{x:0,y:(1-n)*Dc,width:1,height:n}}let n=e/t;return{x:(1-n)*Dc,y:0,width:n,height:1}}function zc(e){return Math.tan(l(t(e/2)))}function Bc(e,t){return t*e.width/e.height}function Vc(e,t,n){let r=zc(e),i=[(t.x*2-1)*r,(t.y*2-1)*r/n,1];return Xt(i,1/Wt(i))}function Hc(e,t,n){return Rr(bc(e),Vc(e.fieldOfView,t,n))}var Uc=1.1;function Wc(e){return Uc**e}function Gc(e,n){return t(e.fieldOfView/Math.max(n,1))}function Kc(e,n,r){let i=Gc(e,r);return vc({...e,yaw:t(e.yaw-n.x*i),pitch:t(e.pitch+n.y*i)})}function qc(e,n){return vc({...e,fieldOfView:t(e.fieldOfView/Wc(n))})}function Jc(e,t,r){let i=qc(e,t.steps);if(t.focus.x===kc.x&&t.focus.y===kc.y||i.fieldOfView===e.fieldOfView)return i;let a=Hc(e,t.focus,r),o=Vc(i.fieldOfView,t.focus,r),s=Yc(o,a[1],e.pitch);if(s===void 0)return i;let c=Rr(Nr(l(s)),o),d=u(n(Math.atan2(a[0],a[2])-Math.atan2(c[0],c[2])));return vc({...i,yaw:d,pitch:s})}function Yc(e,r,i){let[,a,o]=e,s=r/Math.hypot(a,o);if(Math.abs(s)>1)return;let c=u(n(Math.atan2(o,a))),l=u(n(Math.acos(s))),f=d(t(l-c)),p=d(t(-l-c));return Math.abs(f-i)<=Math.abs(p-i)?f:p}function Xc(e,t){return e<=0||t<=0?0:Math.log(t/e)/Math.log(Uc)}function Zc(e,t,n){return vc({...e,yaw:t,pitch:n})}var Qc={scale:1,centre:{x:Dc,y:Dc}},$c=1e-9;function el(e,t){return e.scale===t.scale&&e.centre.x===t.centre.x&&e.centre.y===t.centre.y}function tl(e,t){let n=e.width*t.scale,r=e.height*t.scale;return{x:kc.x-t.centre.x*n,y:kc.y-t.centre.y*r,width:n,height:r}}function nl(e,t){let n=yr(t.scale,1,8),r=n-1<$c?1:n;return{scale:r,centre:{x:ol(t.centre.x,e.width*r),y:ol(t.centre.y,e.height*r)}}}function rl(e,t,n){let r=nl(e,t),i=Nc(tl(e,r),n.focus),a=r.scale*Wc(n.steps);return nl(e,{scale:a,centre:{x:i.x+(kc.x-n.focus.x)/(e.width*a),y:i.y+(kc.y-n.focus.y)/(e.height*a)}})}function il(e,t,n){let r=nl(e,t),i=al(e,r,n);return nl(e,{scale:r.scale,centre:{x:r.centre.x-i.across,y:r.centre.y-i.down}})}function al(e,t,n){return{across:n.across/(e.width*t.scale),down:n.down/(e.height*t.scale)}}function ol(e,t){if(t<=1)return Dc;let n=Dc/t;return yr(e,n,1-n)}var sl={view:_c,panorama:Qc,lenses:Qc};function cl(e,t){return yc(e.view,t.view)&&el(e.panorama,t.panorama)&&el(e.lenses,t.lenses)}function ll(e,t){return{...e,view:t}}function ul(e,t){return ll(e,vc(t))}function dl(e,t){return{...e,lenses:t}}var fl=90;function pl({viewport:e,lensCount:t}){let n=Pc(t,jc(e));return{tiles:n,bounds:Lc(n)}}function ml(e,t,n){let r=Mc(t,n.viewport);return dl(e,il(pl(n).bounds,e.lenses,r))}function hl(e,t,n){let r=n.viewport.width/fl;return ml(e,{x:-(t.yaw*r),y:t.pitch*r},n)}function gl(e,t){let{tiles:n,bounds:r}=pl(t),i=nl(r,e.lenses),a=tl(r,i);return n.map(e=>({x:a.x+(e.x-r.x)*i.scale,y:a.y+(e.y-r.y)*i.scale,width:e.width*i.scale,height:e.height*i.scale}))}var _l={isStabilized:!1,canPan:({lenses:e})=>e.scale>1,pan:ml,turn:hl,zoom:(e,t,n)=>dl(e,rl(pl(n).bounds,e.lenses,t)),reset:e=>dl(e,Qc),place:ul,picture:(e,t)=>({kind:`lens-tiles`,tiles:gl(e,t)})},vl={isStabilized:!0,canPan:()=>!0,pan:(e,t,{viewport:n})=>ll(e,Kc(e.view,t,n.width)),turn:(e,n)=>{let{view:r}=e;return ll(e,Zc(r,t(r.yaw+n.yaw),t(r.pitch+n.pitch)))},zoom:(e,t,{viewport:n})=>ll(e,Jc(e.view,t,jc(n))),reset:e=>ll(e,_c),place:ul,picture:yl};function yl({view:e}){return{kind:`rectilinear`,rotation:bc(e),fieldOfView:e.fieldOfView,area:Oc}}var bl=pt(500),xl=l(t(.01));function Sl(e,n,r){let{pitch:i,roll:a}=r.look;if(!Cl(n,r))return{view:vc({...e,pitch:i,roll:a}),reading:r};let o=t(e.yaw+d(t(r.look.yaw-n.look.yaw))),s=vc({...e,yaw:o,pitch:i,roll:a});return wl(e,s)?{view:e,reading:{look:n.look,at:r.at}}:{view:s,reading:r}}function Cl(e,t){return e!==void 0&&t.at-e.at<=bl}function wl(e,t){return Br(bc(e),bc(t))<xl}function Tl(e){return{...e,roll:t(0)}}var El={isStabilized:!0,canPan:()=>!0,pan:(e,t,{viewport:n})=>ll(e,Kc(e.view,{x:t.x,y:0},n.width)),turn:(e,n)=>{let{view:r}=e;return ll(e,Zc(r,t(r.yaw+n.yaw),r.pitch))},zoom:(e,t,{viewport:n})=>ll(e,Jc(e.view,{steps:t.steps,focus:kc},jc(n))),reset:e=>Dl(e,{...e.view,yaw:t(0),fieldOfView:_c.fieldOfView}),place:Dl,picture:yl};function Dl(e,t){let{yaw:n,fieldOfView:r}=t;return ll(e,vc({...e.view,yaw:n,fieldOfView:r}))}var Ol=2;function kl(e,t){let n=nl(e,t);return{...n,centre:{x:Dc,y:n.centre.y}}}function Al(e,{viewport:t}){let n=Rc(Ol,jc(t));return{fitted:n,panorama:kl(n,e.panorama)}}function jl(e,n,r){let{view:i}=e;return{...ll(e,Zc(i,t(i.yaw+r),i.pitch)),panorama:n}}function Ml(e,n,r){let{fitted:i,panorama:a}=Al(e,r),o=Mc(n,r.viewport);return jl(e,il(i,a,{across:0,down:o.down}),t(-(al(i,a,o).across*c)))}function Nl(e,t,n){let{fitted:r,panorama:i}=Al(e,n);return jl(e,kl(r,{...i,centre:{x:Dc,y:i.centre.y-t.pitch/s}}),t.yaw)}function Pl(e,n,r){let{fitted:i,panorama:a}=Al(e,r),o=kl(i,rl(i,a,n)),s=Nc(tl(i,a),n.focus),l=Nc(tl(i,o),n.focus);return jl(e,o,t((s.x-l.x)*c))}var Fl={normal:vl,equirectangular:{isStabilized:!0,canPan:()=>!0,pan:Ml,turn:Nl,zoom:Pl,reset:e=>({...ll(e,Zc(e.view,t(0),e.view.pitch)),panorama:Qc}),place:ul,picture:(e,t)=>{let{fitted:n,panorama:r}=Al(e,t);return{kind:`equirectangular`,rotation:Pr(l(e.view.yaw)),area:tl(n,r)}}},"raw-lenses":_l};function Il(e){return Fl[e]}var Ll={normal:El,equirectangular:void 0,"raw-lenses":void 0};function Rl(e){return Ll[e]}var zl=[1,0,0,0,-1,0,0,0,-1],Bl=[1,0,0,0,0,-1,0,1,0],Vl=1e-6;function Hl(e){let n=Ir(Ir(Wl(Fr,e.alpha),Wl(Nr,e.beta)),Wl(Pr,e.gamma)),r=Ir(Wl(Fr,t(-e.screenAngle)),zl);return Ir(Ir(Bl,n),r)}function Ul(e){let[n,,r,i,a,o,s,,c]=Hl(e),l=Gl(Math.asin(-yr(o,-1,1)));return Math.hypot(i,a)<Vl?{yaw:Gl(Math.atan2(-s,n)),pitch:l,roll:t(0)}:{yaw:Gl(Math.atan2(r,c)),pitch:l,roll:Gl(Math.atan2(i,a))}}function Wl(e,t){return e(l(t))}function Gl(e){return u(n(e))}var Kl=t(90);function ql(e,t){switch(e.kind){case`mei`:{let[n,r]=e.focal;return{...e,focal:[n*t,r*t]}}case`radial-polynomial`:{let[n,r,i,a]=e.coefficients;return{...e,coefficients:[n*t,r*t,i*t,a*t]}}}}var Jl=5,Yl={start:l(t(Kl-Jl)),end:l(t(Kl+Jl))};function Xl(e){let t=[];for(let n of e.sources)t.every(e=>!$l(e,n))&&t.push({inputIndex:n.inputIndex,trackIndex:n.trackIndex});return t}function Zl(e){let{calibration:t,layout:n}=e;if(t.lenses.length!==n.sources.length)throw new j(`unsupported-layout`,`the calibration describes ${t.lenses.length} lenses but the layout has ${n.sources.length}`);let r=Xl(n);return N(e.displayConversions.length===r.length,`${e.displayConversions.length} display conversions for ${r.length} frame sources`),{lenses:n.sources.map(n=>{let i=eu(t,n.lensIndex),a=r.findIndex(e=>$l(e,n));return{lensIndex:n.lensIndex,frameSlot:a,region:n.region,window:tu(t,i),rotation:ic(i),projection:ql(i.model.projection,t.radialScale),halfFieldOfView:i.model.halfFieldOfView,displayConversion:Ql(e.displayConversions,a)}}),frameSlotCount:r.length,feather:Yl}}function Ql(e,t){let n=e[t];return N(n!==void 0,`no display conversion for frame slot ${t}`),n}function $l(e,t){return e.inputIndex===t.inputIndex&&e.trackIndex===t.trackIndex}function eu(e,t){let n=e.lenses.find(e=>e.lensIndex===t);if(!n)throw new j(`invalid-calibration`,`the calibration has no lens ${t}`);return n}function tu(e,t){let n=e.canvas.height;return{x:Math.floor(t.model.principalPoint.x/n)*n,y:0,width:n,height:n}}var nu=class{parts;stabilizer=new Ys;constructor(e){this.parts=e}setStabilizer(e){this.stabilizer=e}present(e){let t=this.exposureTimeOf(e),{orientations:n,mounting:r}=this.parts.motion,i=this.stabilizer.nextRotation(n.orientationAt(t),t);this.parts.sink.setStabilization(Ki(r,i)),this.parts.sink.present(e)}exposureTimeOf(e){let{timestamp:t}=e.pair;return this.parts.frameTimes?.midExposureAt(t)??t}};function ru(e){let t=e instanceof Error?e:Error(`a failure went unheard`,{cause:e});Promise.reject(t)}var iu=.5,au=class{meter;applyGains;reportFailure;matcher=new fc;lastMeasuredAt;inFlight;isStopped=!1;constructor(e,t,n=ru){this.meter=e,this.applyGains=t,this.reportFailure=n}afterPresent(e){(this.lastMeasuredAt===void 0||Math.abs(e-this.lastMeasuredAt)>=iu)&&!this.isStopped&&this.matchReporting(e)}matchNow(e){return this.inFlight??=this.measureAt(e),this.inFlight}stop(){this.isStopped=!0}async matchReporting(e){try{await this.matchNow(e)}catch(e){this.reportFailure(e)}}async measureAt(e){this.lastMeasuredAt=e;try{let t=await this.meter.measure();t&&!this.isStopped&&this.applyGains(this.matcher.update(t,e))}catch(e){throw this.isStopped=!0,e}finally{this.inFlight=void 0}}},ou=[1,1,1],su=class{sink;renderer;active;lastMediaTime;constructor(e,t){this.sink=e,this.renderer=t}enable(){if(this.active)return;let{renderer:e}=this,t=e.createSeamMeter(),n=new au(t,t=>{e.setLensGains(t)});this.active={meter:t,matching:n}}disable(){this.stop();let e=Array.from({length:this.renderer.lensCount},()=>ou);this.renderer.setLensGains(e)}async matchNow(){this.lastMediaTime!==void 0&&await this.active?.matching.matchNow(this.lastMediaTime)}present(e){this.sink.present(e),this.lastMediaTime=e.mediaTime,this.active?.matching.afterPresent(e.mediaTime)}dispose(){this.stop()}stop(){this.active?.matching.stop(),this.active?.meter.dispose(),this.active=void 0}},cu=7,lu=.5,uu=5,du=360;Kl-cu,Math.round(14/lu),Math.round(uu/lu);var fu=Math.round(du/uu);Array.from({length:fu},()=>t(0));var pu=[`bt709`,`bt470bg`,`smpte170m`,`bt2020`,`smpte432`],mu=[`bt709`,`smpte170m`,`iec61966-2-1`,`linear`,`pq`,`hlg`],hu=[`rgb`,`bt709`,`bt470bg`,`smpte170m`,`bt2020-ncl`];function gu(e,t){return e.find(e=>e===t)??`unspecified`}var _u={a:.17883277,b:.28466892,c:.55991073,segmentJoin:.5,squareSegmentDivisor:3,logSegmentDivisor:12},vu=[1.660491,-.5876411,-.0728499,-.1245505,1.1328999,-.0083494,-.0181508,-.1005789,1.1187297],yu=[.2126,.7152,.0722],bu={exposure:1.4,kneeStart:.2,ceiling:1.5,exponent:2.2},xu=/* @__PURE__ */ new Set([`bt709`,`bt470bg`,`smpte170m`,`unspecified`]),Su={bt709:Mr,bt2020:vu,unspecified:vu,bt470bg:void 0,smpte170m:void 0,smpte432:void 0};function Cu({matrix:e}){return{kind:`as-recorded`,matrix:e}}function wu(e){let t=Cu(e);return xu.has(e.primaries)?{conversion:t}:{conversion:t,problem:`${e.primaries} primaries are shown as BT.709`}}function Tu(e){let t=Su[e.primaries],n={kind:`hlg-to-sdr-bt709`,matrix:e.matrix,gamut:t??Mr,tone:bu};return t===void 0?{conversion:n,problem:`HLG of ${e.primaries} primaries is shown without their gamut`}:{conversion:n}}function Eu(e){return t=>({conversion:Cu(t),problem:`the ${e} transfer cannot be shown yet: drawn as recorded`})}var Du={bt709:wu,smpte170m:wu,"iec61966-2-1":wu,unspecified:wu,hlg:Tu,pq:Eu(`pq`),linear:Eu(`linear`)};function Ou(e){let t=e.map(e=>Du[e.transfer](e)),n=t.flatMap(e=>e.problem===void 0?[]:[e.problem]);return{conversions:t.map(e=>e.conversion),warnings:[...new Set(n)]}}var ku={bt709:{red:.2126,blue:.0722},"bt2020-ncl":{red:.2627,blue:.0593},bt470bg:{red:.299,blue:.114},smpte170m:{red:.299,blue:.114},rgb:void 0,unspecified:void 0};function Au(e,t){let n=ku[e],r=ku[t];return n===void 0||r===void 0||e===t?Mr:Ir(ju(n),Mu(r))}function ju({red:e,blue:t}){let n=1-e-t,r=2*(1-e),i=2*(1-t);return[1,0,r,1,-t*i/n,-e*r/n,1,i,0]}function Mu({red:e,blue:t}){let n=1-e-t,r=2*(1-t),i=2*(1-e);return[e,n,t,-e/r,-n/r,(1-t)/r,(1-e)/i,-n/i,-t/i]}function Nu(e){return Object.keys(e)}var Pu=class{emitter;queue=[];depth=0;isDelivering=!1;isSuperseding=!1;constructor(e){this.emitter=e}change(e){this.depth===0&&this.isDelivering&&(this.isSuperseding=!0),this.depth+=1;try{return e()}finally{--this.depth,this.depth===0&&(this.isSuperseding=!1,this.deliver())}}emit(e,t){this.post(()=>{this.emitter.emit(e,t)})}post(e){this.isSuperseding&&=(this.queue.length=0,!1),this.queue.push(e),this.depth===0&&this.deliver()}deliver(){if(!this.isDelivering){this.isDelivering=!0;try{for(let e=this.queue.shift();e;e=this.queue.shift())e()}finally{this.isDelivering=!1}}}},Fu={done:!0,value:void 0},Iu=class{isEnded=!1;end(){this.isEnded=!0}hasEnded(){return this.isEnded}},Lu=class{source;constructor(e){this.source=e}stream(e){return{[Symbol.asyncIterator]:()=>new Ru(this.source,e)}}},Ru=class{source;range;ending=new Iu;constructor(e,t){this.source=e,this.range=t}async next(){if(await Promise.resolve(),this.ending.hasEnded())return Fu;let e=await this.source.read(this.range);return this.ending.hasEnded()?Fu:(this.ending.end(),e.byteLength===0?Fu:{done:!1,value:e})}return(){return this.ending.end(),Promise.resolve(Fu)}},zu=class{parts;constructor(e){this.parts=e}get duration(){return this.parts.track.end}samplesFrom(e){let{download:t,track:n}=this.parts;return{[Symbol.asyncIterator]:()=>new Bu(n,t.openCursor(n,n.sampleShownAt(e)??0,e))}}},Bu=class{track;cursor;ending=new Iu;constructor(e,t){this.track=e,this.cursor=t}async next(){let e=await this.cursor.nextSample();return!e||this.ending.hasEnded()?Fu:{done:!1,value:{timestamp:this.track.timestampOf(e.sample),duration:this.track.durationOf(e.sample),data:Uint8Array.from(e.bytes)}}}return(){return this.ending.end(),this.cursor.close(),Promise.resolve(Fu)}},Vu=class{parts;rejected=/* @__PURE__ */ new Set;constructor(e){this.parts=e}get description(){return this.parts.codec.description}decoderConfiguration(){return Promise.resolve(this.parts.codec.configuration)}keyframeAt(e){return Promise.resolve(this.timeOf(this.keyframeSampleAt(e)))}firstKeyframe(){return Promise.resolve(this.timeOf(this.firstKeyframeSample()))}packetsFrom(e){return{[Symbol.asyncIterator]:()=>new Hu({track:this.parts.track,open:()=>this.cursorFrom(e),reject:e=>{this.rejected.add(e)},packetOf:e=>this.packetOf(e)})}}sampleTimestamps(){return Promise.resolve(this.parts.track.timestampsInPresentationOrder())}frameCount(){return Promise.resolve(this.parts.track.sampleCount)}cursorFrom(e){let t=this.keyframeSampleAt(e)??this.firstKeyframeSample();return t===void 0?void 0:this.parts.download.openCursor(this.parts.track,t,e)}keyframeSampleAt(e){let{track:t}=this.parts,n=t.keyframeAt(e);for(;n!==void 0&&this.rejected.has(n);)n=t.syncSampleAtOrBefore(n-1);return n}firstKeyframeSample(){let{track:e}=this.parts,t=e.syncSampleAtOrAfter(0);for(;t!==void 0&&this.rejected.has(t);)t=e.syncSampleAtOrAfter(t+1);return t}timeOf(e){let{track:t}=this.parts;return e===void 0?void 0:{timestamp:t.timestampOf(e),duration:t.durationOf(e)}}packetOf(e){let{track:t}=this.parts;return{timestamp:t.timestampOf(e.sample),duration:t.durationOf(e.sample),isKeyFrame:t.isSync(e.sample)&&!this.rejected.has(e.sample),data:e.bytes}}},Hu=class{parts;cursor;isVerified=!1;ending=new Iu;constructor(e){this.parts=e,this.cursor=e.open()}async next(){if(this.ending.hasEnded())return Fu;let{cursor:e}=this;if(!e)throw new j(`no-key-frame`,`track ${this.parts.track.trackId} has no key frame`);let t=await e.nextSample();return!t||this.ending.hasEnded()?Fu:!this.isVerified&&!this.parts.track.keyframeRule.isKeyframe(t.bytes)?this.startEarlier(e,t):(this.isVerified=!0,{done:!1,value:this.parts.packetOf(t)})}return(){return this.ending.end(),this.cursor?.close(),Promise.resolve(Fu)}startEarlier(e,t){return this.parts.reject(t.sample),e.close(),this.cursor=this.parts.open(),this.next()}},Uu=class e{ranges;static empty=new e([]);constructor(e){this.ranges=e}static of(t){let n=t.filter(e=>e.length>0).toSorted((e,t)=>e.offset-t.offset);return new e(Wu(n,0))}get isEmpty(){return this.ranges.length===0}get totalLength(){return this.ranges.reduce((e,t)=>e+t.length,0)}union(t){return e.of([...this.ranges,...t.ranges])}subtract(t){return new e(this.ranges.flatMap(e=>Gu(e,t.ranges)))}covers(e){return e.length===0||this.ranges.some(t=>t.contains(e))}overlaps(e){return this.ranges.some(t=>t.overlaps(e))}bridgingGapsBelow(t){return new e(Wu(this.ranges,t))}};function Wu(e,t){let n=[];for(let r of e){let e=n.at(-1),i=e!==void 0&&r.offset-e.end<Math.max(t,1);e&&i?n[n.length-1]=Ku(e.offset,r.end,e.end):n.push(r)}return n}function Gu(e,t){let n=[],r=e.offset;for(let i of t)i.end<=r||i.offset>=e.end||(i.offset>r&&n.push(Fn.of(r,i.offset-r)),r=Math.max(r,i.end));return r<e.end&&n.push(Fn.of(r,e.end-r)),n}function Ku(e,t,n){return Fn.of(e,Math.max(t,n)-e)}var qu=class{range;bytes;filled=0;isComplete=!1;constructor(e,t){this.range=e,this.bytes=t}get filledRange(){return Fn.of(this.range.offset,this.filled)}},Ju=class{blocks=[];get held(){return Uu.of(this.blocks.map(e=>e.filledRange))}get allocatedBytes(){return this.blocks.reduce((e,t)=>e+t.bytes.byteLength,0)}allocate(e){let t=new qu(e,new Uint8Array(e.length));return this.blocks.push(t),t}write(e,t){let n=this.fillingOf(e);n.bytes.set(t,n.filled),n.filled+=t.byteLength}complete(e){this.fillingOf(e).isComplete=!0}trim(e){let t=this.fillingOf(e);t.isComplete=!0,t.bytes=t.bytes.slice(0,t.filled),this.blocks=this.blocks.filter(e=>e.bytes.byteLength>0)}bytesOf(e){let t=this.blocks.find(t=>t.filledRange.contains(e));return t?Yu(t,e):this.held.covers(e)?this.copyOf(e):void 0}release(e){this.blocks=this.blocks.filter(t=>!t.isComplete||!e.covers(t.filledRange))}fillingOf(e){let t=this.blocks.find(t=>t===e);return N(t!==void 0,`the block is not one this store holds`),t}copyOf(e){let t=new Uint8Array(e.length);for(let n of this.blocks){let r=Math.max(n.range.offset,e.offset),i=Math.min(n.filledRange.end,e.end);r<i&&t.set(n.bytes.subarray(r-n.range.offset,i-n.range.offset),r-e.offset)}return t}};function Yu(e,t){let n=t.offset-e.range.offset;return e.bytes.subarray(n,n+t.length)}var Xu=class{track;host;target;next;waiter;isClosed=!1;constructor(e,t,n){this.track=e,this.host=n,this.next=t.sample,this.target=t.target}get position(){return this.next}get isWaiting(){return this.waiter!==void 0}nextSample(){if(this.isClosed||this.next>=this.track.sampleCount)return Promise.resolve(void 0);N(this.waiter===void 0,`a cursor reads one sample at a time`);let e=this.track.rangeOf(this.next),t=this.host.bytesOf(e);if(t)return Promise.resolve(this.take(t));let n=this.host.failureOf(e);return n===void 0?this.waitForBytes(e):Promise.reject(n)}serve(){let{waiter:e}=this,t=e&&this.host.bytesOf(this.track.rangeOf(this.next));e&&t&&(this.waiter=void 0,e.resolve(this.take(t)))}fail(e,t){let{waiter:n}=this;n!==void 0&&e.overlaps(this.track.rangeOf(this.next))&&(this.waiter=void 0,n.reject(t))}close(){this.isClosed||(this.isClosed=!0,this.waiter?.resolve(void 0),this.waiter=void 0,this.host.closed(this))}waitForBytes(e){return new Promise((t,n)=>{this.waiter={resolve:t,reject:n},this.host.waiting(e)})}take(e){let t=this.next;return this.next+=1,this.host.movedOn(e.byteLength),{sample:t,bytes:e}}},Zu=class{parts;nextId=1;running=/* @__PURE__ */ new Map;constructor(e){this.parts=e}get states(){return[...this.running.values()].map(e=>({id:e.id,remaining:Qu(e)}))}isBringing(e){for(let t of this.running.values())if(t.block.range.contains(e))return!0;return!1}start(e){let t={id:this.nextId,block:this.parts.store.allocate(e),chunks:this.parts.stream.stream(e)[Symbol.asyncIterator](),delivered:0};this.nextId+=1,this.running.set(t.id,t),this.pump(t)}cancel(e){let t=this.running.get(e);t&&(this.running.delete(e),t.chunks.return?.(),this.parts.store.trim(t.block))}cancelAll(){for(let e of this.running.keys())this.cancel(e)}async pump(e){try{for(let t=await e.chunks.next();t.done!==!0;t=await e.chunks.next()){if(!this.isRunning(e))return;this.parts.store.write(e.block,t.value),e.delivered+=t.value.byteLength,this.parts.listener.onChunk()}this.finish(e)}catch(t){this.fail(e,t)}}finish(e){this.isRunning(e)&&(this.running.delete(e.id),this.parts.store.complete(e.block),this.parts.listener.onEnd())}fail(e,t){this.isRunning(e)&&(this.running.delete(e.id),this.parts.store.trim(e.block),this.parts.listener.onFailure(Qu(e),t))}isRunning(e){return this.running.get(e.id)===e}};function Qu(e){let{range:t}=e.block;return Fn.of(t.offset+e.delivered,t.length-e.delivered)}function $u(e,t){let{track:n}=e,r=[];for(let i=e.sample;i<n.sampleCount&&!(n.timestampOf(i)>t);i+=1)r.push(n.rangeOf(i));return r}function ed(e,t){let n=[],r=t;for(let t of e.ranges){if(r<=0)break;n.push(Fn.of(t.offset,Math.min(t.length,r))),r-=t.length}return Uu.of(n)}function td(e){let{policy:t}=e,n=R(e.time+t.resumeSeconds),r=e.cursors.filter(e=>e.track.kind===`video`),i=Uu.of(r.flatMap(e=>$u(e,n))),a=Math.min(t.requestSize,t.refillBytes);return ed(i,t.aheadBytes-a)}function nd(e){return td(e).subtract(e.held).isEmpty}function rd(e){let t=e.cursors.filter(e=>dd(e)),n=t.length>0?od(t):e.anchor,r=n??id(e);if(!r)return ad(e);let i=e.isReadingAhead?e.policy.aheadSeconds:0,a=R(r.time+i),o=sd({state:e,windowStart:r,windowEnd:a}).bridgingGapsBelow(e.policy.bridgedGap),s=e.transfers.filter(e=>e.remaining.length===0||o.overlaps(e.remaining)),c=Uu.of(s.map(e=>e.remaining)),l=o.subtract(e.held).subtract(c).subtract(e.unreadable),u=e.policy.requestsInFlight-s.length;return{start:pd({state:e,windowStart:r,windowEnd:a,missing:l,threshold:fd(e,r)})?hd(l,e.policy,u):[],cancel:e.transfers.filter(e=>!s.includes(e)).map(e=>e.id),release:e.held.subtract(o.union(gd(r,e.policy))),anchor:n}}function id(e){return e.isReadingAhead&&e.cursors.length>0?od(e.cursors):void 0}function ad(e){return{start:[],cancel:e.transfers.map(e=>e.id),release:Uu.empty,anchor:void 0}}function od(e){return{time:R(Math.min(...e.map(e=>yd(e)))),offset:Math.min(...e.map(e=>xd(e))),keyframeOffset:Math.min(...e.map(e=>bd(e)))}}function sd(e){let{state:t,windowEnd:n}=e,r=t.cursors.filter(t=>cd(t,e)),i=r.flatMap(e=>$u(e,ud(n,e.target))),a=r.filter(e=>ld(e,n)),o=Uu.of(a.map(e=>e.track.rangeOf(e.sample)));return ed(Uu.of(i),t.policy.aheadBytes).union(o)}function cd(e,t){return yd(e)>=t.windowStart.time-t.state.policy.keepBehindSeconds}function ld(e,t){let n=e.isWaiting&&yd(e)<=t;return!vd(e)&&(dd(e)||n)}function ud(e,t){return t!==void 0&&t>e?t:e}function dd(e){return e.track.kind===`video`}function fd(e,t){let n={cursors:e.cursors,time:t.time,policy:e.policy};return e.isReadingAhead?td(n):Uu.empty}function pd(e){let{state:t,missing:n,threshold:r}=e;return n.ranges.some(e=>r.overlaps(e))?!0:t.cursors.some(t=>md(t,e)&&n.overlaps(t.track.rangeOf(t.sample)))||n.totalLength>=t.policy.refillBytes}function md(e,t){if(!e.isWaiting||vd(e))return!1;let{windowStart:n,state:r}=t,i=n.time+(r.isReadingAhead?r.policy.resumeSeconds:0);return dd(e)||yd(e)<=i}function hd(e,t,n){let r=[];for(let i of e.ranges)for(let e=i.offset;e<i.end&&r.length<n;e+=t.requestSize)r.push(Fn.of(e,Math.min(t.requestSize,i.end-e)));return r}function gd(e,t){let n=_d(e,t);return Uu.of([Fn.of(n,e.offset-n)])}function _d(e,t){return Math.max(0,Math.min(e.keyframeOffset,e.offset-t.keepBehindBytes))}function vd(e){return e.sample>=e.track.sampleCount}function yd(e){return vd(e)?e.track.end:e.track.timestampOf(e.sample)}function bd(e){let{track:t}=e,n=Math.min(e.sample,t.sampleCount-1),r=t.syncSampleAtOrBefore(n);return r===void 0?xd(e):t.rangeOf(r).offset}function xd(e){let{track:t}=e;return vd(e)?t.sampleCount>0?t.rangeOf(t.sampleCount-1).end:0:t.rangeOf(e.sample).offset}var Sd=Fn.of(0,2**53-1),Cd=class{parts;store=new Ju;progressListeners=/* @__PURE__ */ new Set;transfers;cursors=/* @__PURE__ */ new Set;host;failures=[];anchor;isReadingAhead=!1;isPlanDue=!1;takenSincePlan=0;isDisposed=!1;constructor(e){this.parts=e,this.transfers=new Zu({stream:e.stream,store:this.store,listener:{onChunk:()=>{this.serveCursors();for(let e of this.progressListeners)e()},onEnd:()=>{this.schedulePlan()},onFailure:(e,t)=>{this.fail(e,t)}}}),this.host=this.cursorHost()}openCursor(e,t,n){N(this.parts.table.tracks.includes(e),`the track is not one of this file`);let r=new Xu(e,{sample:t,target:n},this.host);return this.isDisposed?(r.close(),r):(this.failures=[],this.cursors.add(r),this.schedulePlan(),r)}startReadingAhead(){this.isReadingAhead=!0,this.schedulePlan()}isReadyToResumeAt(e){return nd({cursors:this.positions(),held:this.store.held,time:e,policy:this.parts.policy})}onProgress(e){let t=()=>{e()};return this.progressListeners.add(t),()=>{this.progressListeners.delete(t)}}dispose(){this.isDisposed=!0,this.transfers.cancelAll();for(let e of this.cursors)e.close()}cursorHost(){return{bytesOf:e=>this.store.bytesOf(e),failureOf:e=>this.failures.find(t=>t.range.overlaps(e))?.error,movedOn:e=>{this.takenSincePlan+=e,this.takenSincePlan>=this.parts.policy.replanBytes&&this.schedulePlan()},waiting:e=>{this.transfers.isBringing(e)||this.schedulePlan()},closed:e=>{this.cursors.delete(e),this.schedulePlan()}}}schedulePlan(){this.isPlanDue||this.isDisposed||(this.isPlanDue=!0,this.planAfterThisTurn())}async planAfterThisTurn(){if(await Promise.resolve(),this.isPlanDue=!1,!this.isDisposed)try{this.plan()}catch(e){this.failEveryRead(e)}}failEveryRead(e){let t=ne(e,`invariant-violation`,`the download could not plan`);this.failures.push({range:Sd,error:t});for(let e of this.cursors)e.fail(Sd,t)}plan(){this.takenSincePlan=0;let e=rd({cursors:this.positions(),held:this.store.held,transfers:this.transfers.states,unreadable:Uu.of(this.failures.map(e=>e.range)),isReadingAhead:this.isReadingAhead,anchor:this.anchor,policy:this.parts.policy});this.anchor=e.anchor,this.carryOut(e)}positions(){return[...this.cursors].map(e=>({track:e.track,sample:e.position,isWaiting:e.isWaiting,target:e.target}))}carryOut(e){for(let t of e.cancel)this.transfers.cancel(t);this.store.release(e.release);for(let t of e.start)this.transfers.start(t)}serveCursors(){for(let e of this.cursors)e.serve()}fail(e,t){let n=ne(t,`source-unreadable`,`a range of the recording could not be read`);this.failures.push({range:e,error:n});for(let t of this.cursors)t.fail(e,n);this.schedulePlan()}};function wd(e){let t=new Cd(e);return{download:t,videoTracks:e.codecs.video.map(n=>new Vu({download:t,track:Td(e.table,n.trackId,`video`),codec:n})),audioTracks:e.codecs.audio.map(n=>({samples:new zu({download:t,track:Td(e.table,n.trackId,`audio`)}),configuration:n.configuration})),duration:e.table.duration,dispose:()=>{t.dispose()}}}function Td(e,t,n){let r=e.trackWithId(t);if(r?.kind!==n)throw new j(`unsupported-container`,`the movie box has no ${n} track ${t} to read`);return r}var Ed=1048576,Dd=10,Od=128,kd=2,Ad=32,jd=8,Md=2,Nd=1,Pd=.25,Fd=16,Id=4;function Ld(e,t){let n=e.size/e.duration,r=Math.min(Math.round(Dd*n),Od*Ed/t),i=Math.round(r*Pd);return{aheadSeconds:R(Dd),aheadBytes:r,keepBehindBytes:Math.min(Math.round(kd*n),Ad*Ed/t),keepBehindSeconds:R(kd),requestSize:jd*Ed,requestsInFlight:Md,bridgedGap:Nd*Ed,refillBytes:i,replanBytes:Math.round(i/Fd),resumeSeconds:R(Id)}}var Rd=class{files;constructor(e){this.files=e}isReadyToResumeAt(e){return this.files.every(t=>t.isReadyToResumeAt(e))}onProgress(e){let t=this.files.map(t=>t.onProgress(e));return()=>{for(let e of t)e()}}};function zd(e){for(let t of e.frames)t.close()}var Bd=class{capacity;onPush;pairs=[];roomWaiters=[];isClosed=!1;constructor(e,t=Vd){this.capacity=e,this.onPush=t,N(Number.isSafeInteger(e)&&e>0,`queue capacity must be positive`)}get length(){return this.pairs.length}get isFull(){return this.pairs.length>=this.capacity}get isClosedForGood(){return this.isClosed}waitForRoom(){return!this.isFull||this.isClosed?Promise.resolve():new Promise(e=>{this.roomWaiters.push(e)})}push(e){if(this.isClosed){zd(e);return}this.pairs.push(e),this.onPush()}takePairAt(e){let t;for(;this.pairs.length>0&&(this.pairs[0]?.timestamp??1/0)<=e;)t&&zd(t),t=this.pairs.shift();return t&&this.wakeWaiters(),t}peekTimestamp(){return this.pairs[0]?.timestamp}newestTimestamp(){return this.pairs.at(-1)?.timestamp}close(){this.isClosed=!0;for(let e of this.pairs)zd(e);this.pairs.length=0,this.wakeWaiters()}wakeWaiters(){if(this.isFull&&!this.isClosed)return;let e=this.roomWaiters;this.roomWaiters=[];for(let t of e)t()}};function Vd(){}var Hd=class{tolerance;onPair;queues;unpairedCount=0;constructor(e,t,n){this.tolerance=t,this.onPair=n,this.queues=Array.from({length:e},()=>[])}get unpaired(){return this.unpairedCount}push(e,t){ae(e,this.queues.length,`frame source`),this.queues[e]?.push(t),this.drain()}discardAll(){for(let e of this.queues){for(let t of e)t.close();e.length=0}}drain(){for(;this.queues.every(e=>e.length>0);){let e=this.queues.map(e=>e[0]).filter(e=>e!==void 0),t=Math.min(...e.map(e=>e.timestamp));e.every(e=>Math.abs(e.timestamp-t)<=this.tolerance)?this.emit(e,R(t)):this.dropHeadAt(t)}}emit(e,t){for(let e of this.queues)e.shift();this.onPair({timestamp:t,frames:e})}dropHeadAt(e){this.queues.find(t=>t[0]?.timestamp===e)?.shift()?.close(),this.unpairedCount+=1}},Ud=class{from;deliver;held;droppedCount=0;constructor(e,t){this.from=e,this.deliver=t}get dropped(){return this.droppedCount}push(e){if(e.timestamp>=this.from){this.release(),this.deliver(e);return}this.hold(e)}release(){if(!this.held)return;let e=this.held;this.held=void 0,this.deliver(e)}discard(){this.held&&zd(this.held),this.held=void 0}hold(e){this.held&&(zd(this.held),this.droppedCount+=1),this.held=e}},Wd=class{promise;isSettledNow=!1;resolvePromise;rejectPromise;constructor(){this.promise=new Promise((e,t)=>{this.resolvePromise=e,this.rejectPromise=t})}get isSettled(){return this.isSettledNow}resolve(e){this.isSettledNow||(this.isSettledNow=!0,this.resolvePromise?.(e))}reject(e){this.isSettledNow||(this.isSettledNow=!0,this.rejectPromise?.(e))}async follow(e){try{this.resolve(await e)}catch(e){this.reject(e)}}},Gd=Symbol(`stopped`),Kd=class{isStopped=!1;wakeWaiter;get wasStopped(){return this.isStopped}stop(){this.isStopped=!0,this.wakeWaiter?.()}async race(e){if(this.isStopped)return Gd;N(this.wakeWaiter===void 0,`a run stop races one wait at a time`);let t=new Promise(e=>{this.wakeWaiter=()=>{e(Gd)}});try{return await Promise.race([e(),t])}finally{this.wakeWaiter=void 0}}},qd=class{frameSources;decoderPort;options;stop=new Kd;hasRun=!1;iterators=[];constructor(e,t,n){if(this.frameSources=e,this.decoderPort=t,this.options=n,e.length===0)throw new j(`invariant-violation`,`a decode pipeline needs at least one frame source`)}async run(e,t){N(!this.hasRun,`a decode pipeline runs once; create a new one for each run`),this.hasRun=!0;let n=await this.openRun(e,t);try{let e=await this.feed(n);if(await Yd(n,e),n.failure.isSettled)throw await n.failure.promise;return $d(n,e)}finally{Zd(n)}}abort(){this.stop.stop(),Qd(this.iterators)}async openRun(e,t){let{stop:n}=this,r=new Wd,i={packets:0,pairs:0},a=new Ud(e,e=>{i.pairs+=1,t.push(e)}),o=new Hd(this.frameSources.length,this.options.pairTolerance,e=>{a.push(e)}),s=n.wasStopped?[]:this.packetIteratorsFrom(e);this.iterators=s;let c=e=>{r.resolve(e),n.stop()};try{return{output:t,stop:n,failure:r,tally:i,gate:a,pairer:o,iterators:s,decoders:n.wasStopped?[]:await this.createDecoders(o,c)}}catch(e){throw Qd(s),e}}async createDecoders(e,t){let n=await Promise.allSettled(this.frameSources.map(async(n,r)=>this.decoderPort.create(await n.decoderConfiguration(),{onFrame:t=>{e.push(r,t)},onError:t}))),r=n.flatMap(e=>e.status===`fulfilled`?[e.value]:[]),i=n.find(e=>e.status===`rejected`);if(i){for(let e of r)e.close();throw ef(i.reason)}return r}async feed(e){for(;!Jd(e);){if(await e.stop.race(()=>e.output.waitForRoom()),Jd(e))return!1;let t=await e.stop.race(()=>tf(e.iterators));if(t===Gd)return!1;if(!t)return!0;await this.decodeRound(e,t)}return!1}async decodeRound(e,t){for(let[n,r]of e.decoders.entries()){let i=t[n];if(i){if(await e.stop.race(()=>r.waitForPendingBelow(this.options.maxPendingPackets)),Jd(e))return;r.decode(i),e.tally.packets+=1}}}packetIteratorsFrom(e){return this.frameSources.map(t=>t.packetsFrom(e)[Symbol.asyncIterator]())}};function Jd(e){return e.stop.wasStopped||e.output.isClosedForGood}async function Yd(e,t){await e.stop.race(()=>Xd(e.decoders,e.failure))!==Gd&&t&&e.gate.release()}async function Xd(e,t){try{await Promise.all(e.map(e=>e.flush()))}catch(e){if(!t.isSettled)throw e}}function Zd(e){for(let t of e.decoders)t.close();e.pairer.discardAll(),e.gate.discard(),Qd(e.iterators)}function Qd(e){for(let t of e)t.return?.()}function $d(e,t){return{packetsDecoded:e.tally.packets,pairsDelivered:e.tally.pairs,unpairedFrames:e.pairer.unpaired,pairsDroppedBeforeStart:e.gate.dropped,hasReachedEnd:t}}function ef(e){return e instanceof Error?e:new j(`decode`,`a decoder could not be created`,{cause:e})}async function tf(e){let t=await Promise.all(e.map(e=>e.next())),n=[];for(let e of t){if(e.done===!0)return;n.push(e.value)}return n}var nf={verdict:`decodes`,detail:void 0},rf={verdict:`no-key-frame`,detail:`the track has no key frame`},af={verdict:`decode-failed`,detail:`the decoder accepted the first key frame but produced no picture`},of={verdict:`timed-out`,detail:`the decoder produced no picture before the deadline`},sf={verdict:`key-frame-late`,detail:`the first key frame did not arrive before the deadline`};async function cf(e,t,n){let r=e.map(e=>new df(e,t));try{let e=await Promise.all(r.map(e=>lf(e,n)));return{canDecode:e.every(e=>e.verdict===`decodes`),sources:e}}finally{for(let e of r)e.close()}}async function lf(e,t){try{let n=await Promise.race([e.run(),uf(t,e)]);return{track:e.track.description,...n}}finally{e.close()}}async function uf(e,t){return await e.promise,t.outcomeAtDeadline}var df=class{track;decoderPort;decoder;firstOutcome;isClosed=!1;isReadingKeyFrame=!1;constructor(e,t){this.track=e,this.decoderPort=t}get outcomeAtDeadline(){return this.isReadingKeyFrame?sf:of}async run(){let e=await this.track.decoderConfiguration();if(!await this.decoderPort.isSupported(e))return ff(e);if(this.isClosed)return of;let t=await this.track.firstKeyframe();if(!t)return rf;this.isReadingKeyFrame=!0;let n=await mf(this.track,t.timestamp);return this.isReadingKeyFrame=!1,n?await this.decodeFirst(e,n):rf}close(){this.isClosed=!0,this.decoder?.close(),this.decoder=void 0,this.firstOutcome?.resolve(of)}async decodeFirst(e,t){if(this.isClosed)return of;let n=new Wd;this.firstOutcome=n;let r=await this.openDecoder(e,n);return r===void 0?n.promise:(this.decoder=r,this.decodeInto(r,t,n),n.promise)}async openDecoder(e,t){try{let n=await this.decoderPort.create(e,{onFrame:e=>{e.close(),t.resolve(nf)},onError:e=>{t.resolve(pf(e))}});if(!this.isClosed)return n;n.close(),t.resolve(of)}catch(e){t.resolve(pf(e))}}async decodeInto(e,t,n){try{e.decode(t),await e.flush(),n.resolve(af)}catch(e){n.resolve(pf(e))}}};function ff(e){return{verdict:`unsupported-configuration`,detail:`${e.codec} at ${e.codedWidth}x${e.codedHeight} is not supported here`}}function pf(e){let t=ie(e);return{verdict:M(e,`codec-unsupported`)?`unsupported-configuration`:`decode-failed`,detail:t}}async function mf(e,t){let n=e.packetsFrom(t)[Symbol.asyncIterator]();try{let e=await n.next();return e.done===!0?void 0:e.value}finally{n.return?.()}}var hf=class{now;hasEnded=!1;failure=void 0;isRunningNow=!1;positionAtAnchor=R(0);anchorMs=0;constructor(e){this.now=e}get isRunning(){return this.isRunningNow}get currentTime(){if(!this.isRunningNow)return this.positionAtAnchor;let e=gt(pt(this.now()-this.anchorMs));return R(this.positionAtAnchor+e)}start(){return this.isRunningNow||=(this.anchorMs=this.now(),!0),Promise.resolve()}pause(){this.isRunningNow&&=(this.positionAtAnchor=this.currentTime,!1)}seek(e){this.positionAtAnchor=e,this.anchorMs=this.now()}dispose(){this.pause()}},gf={ready:[`playing`,`buffering`,`paused`,`seeking`,`error`,`disposed`],playing:[`buffering`,`paused`,`seeking`,`ended`,`error`,`disposed`],buffering:[`playing`,`paused`,`seeking`,`error`,`disposed`],paused:[`playing`,`buffering`,`seeking`,`error`,`disposed`],seeking:[`buffering`,`paused`,`error`,`disposed`],ended:[`seeking`,`error`,`disposed`],error:[`disposed`],disposed:[]},_f=/* @__PURE__ */ new Set([`playing`,`buffering`]);function vf(e){return e!==void 0&&_f.has(e)}var yf=class{current=`ready`;get state(){return this.current}canTransitionTo(e){return gf[this.current].includes(e)}transitionTo(e){if(!this.canTransitionTo(e))throw new j(`invariant-violation`,`player cannot go from ${this.current} to ${e}`);this.current=e}isOneOf(...e){return e.includes(this.current)}},bf=class{reportListenerError;listeners=/* @__PURE__ */ new Map;constructor(e=ru){this.reportListenerError=e}on(e,t){let n=this.listeners.get(e)??/* @__PURE__ */ new Set;return n.add(t),this.listeners.set(e,n),()=>{n.delete(t)}}emit(e,t){let n=this.listeners.get(e);if(!n)return;let r=[...n];for(let e of r)if(n.has(e))try{e(t)}catch(e){this.reportListenerError(e)}}removeAll(){for(let e of this.listeners.values())e.clear();this.listeners.clear()}},xf=1,Sf=.25,Cf=class{position;previousPlayingTick;placedAt(e){this.position=e}stoppedAt(e){(this.position===void 0||e>=this.position)&&(this.position=e)}playingFrom(e){this.previousPlayingTick=e}wasMovedFromOutside({now:e,state:t}){let n=this.position;return this.position=e,n!==void 0&&(t===`playing`?n-e:Math.abs(e-n))>Sf}wereTicksMissed({now:e,state:t}){let n=t===`playing`,r=this.previousPlayingTick;this.previousPlayingTick=n?e:void 0;let i=r===void 0?0:e-r;return n&&i>xf}};function wf(e){return!e.isRunning&&!e.hasEnded}function Tf(e,t){return e.hasEnded||e.currentTime>=t}var Ef=class{generation=0;scrubs=0;isFromFlowing=!1;get resumesPlaying(){return this.isFromFlowing}begin(e){this.isFromFlowing=vf(e),this.generation+=1}claimScrub(){return this.scrubs+=1,{seek:this.generation,scrub:this.scrubs}}isScrubCurrent(e){return e.seek===this.generation&&e.scrub===this.scrubs}},Df=.25,Of=class{lifecycle;announced;constructor(e){this.lifecycle=e}announce(e){this.announced=e,this.lifecycle.announce(`timeupdate`,e)}followPlayback(e){let{announced:t}=this;(t===void 0||Math.abs(e-t)>=Df)&&this.announce(e)}},kf=class{lifecycle;cause=`priming`;startAttempt;constructor(e){this.lifecycle=e}get waitingStart(){return this.startAttempt?.promise}enter(e){this.cause=e,this.lifecycle.moveTo(`buffering`)}enterForStart(){let e=new Wd;return this.startAttempt=e,this.enter(`priming`),e.promise}isOverAt(e,t){return!e||!this.lifecycle.is(`buffering`)?!1:this.cause===`priming`?e.isPrimedAt(t):e.isReadyToResumeAt(t)}takeStart(){let e=this.startAttempt;return this.startAttempt=void 0,e}settleStart(){this.takeStart()?.resolve()}},Af=class{machine=new yf;outbox;constructor(e){this.outbox=new Pu(e)}get current(){return this.machine.state}is(e){return this.machine.state===e}isOneOf(...e){return this.machine.isOneOf(...e)}canMoveTo(e){return this.machine.canTransitionTo(e)}moveTo(e){this.machine.transitionTo(e),this.announce(`statechange`,e)}announce(e,t){this.outbox.emit(e,t)}change(e){return this.outbox.change(e)}},jf=2,Mf=.25,Nf=class e{parts;listener;queue;pipeline;primingPairs;stopFollowingBuffer;isAborted=!1;hasReachedEnd=!1;hasHandedOutPair=!1;constructor(e,t){this.parts=e,this.listener=t,this.primingPairs=Math.min(jf,e.queueCapacity),this.queue=new Bd(e.queueCapacity,()=>{this.isAborted||t.onProgress()}),this.stopFollowingBuffer=e.buffer?.onProgress(()=>{t.onProgress()})??(()=>void 0),this.pipeline=new qd(e.frameSources,e.decoderPort,e.pipeline)}static start(t,n,r){let i=new e(t,r);return i.follow(i.pipeline.run(n,i.queue)),i}get isDrained(){return this.hasReachedEnd&&this.queue.length===0}isPrimedAt(e){let t=(this.queue.newestTimestamp()??-1/0)>=e;return this.hasReachedEnd||t&&this.queue.length>=this.primingPairs}isReadyToResumeAt(e){return this.isPrimedAt(e)&&(this.hasReachedEnd||(this.parts.buffer?.isReadyToResumeAt(e)??!0))}isStarvedAt(e,t){let n=this.queue.length===0&&!this.hasReachedEnd,r=e-(t??-1/0);return n&&r>Mf}takePairAt(e){let t=this.queue.peekTimestamp(),n=!this.hasHandedOutPair&&t!==void 0,r=this.queue.takePairAt(n?R(Math.max(e,t)):e);return r&&(this.hasHandedOutPair=!0),r}abort(){this.isAborted=!0,this.stopFollowingBuffer(),this.pipeline.abort(),this.queue.close()}async follow(e){try{let{hasReachedEnd:t}=await e;if(this.isAborted)return;this.hasReachedEnd=t,this.listener.onProgress()}catch(e){this.isAborted||this.listener.onFailure(e)}}};async function Pf(e,t){try{return(await e.keyframeAt(t))?.timestamp??t}catch{return t}}var Ff=class{parts;events=new bf;lifecycle=new Af(this.events);run;presented;timeUpdates=new Of(this.lifecycle);buffering=new kf(this.lifecycle);clockWatch=new Cf;seeks=new Ef;constructor(e){this.parts=e}get state(){return this.lifecycle.current}get currentTime(){return this.parts.clock.currentTime}async play(){if(this.lifecycle.current!==`playing`){if(this.lifecycle.current===`buffering`){await this.buffering.waitingStart;return}await this.lifecycle.change(()=>this.beginStart())}}pause(){this.lifecycle.change(()=>{let e=this.parts.clock.isRunning;this.parts.clock.pause(),e&&this.clockWatch.stoppedAt(this.parts.clock.currentTime),this.lifecycle.canMoveTo(`paused`)&&(this.lifecycle.moveTo(`paused`),this.buffering.settleStart(),this.timeUpdates.announce(this.parts.clock.currentTime))})}stop(){this.lifecycle.change(()=>{this.pause(),this.seek(R(0))})}seek(e){this.lifecycle.isOneOf(`disposed`,`error`)||this.lifecycle.change(()=>{let t=R(yr(e,0,this.parts.duration));this.seeks.begin(this.lifecycle.current),this.moveClockTo(t),this.startRun(t),this.lifecycle.moveTo(`seeking`),this.seeks.resumesPlaying?this.buffering.enter(`priming`):this.lifecycle.moveTo(`paused`),this.timeUpdates.announce(t)})}async scrub(e){let[t]=this.parts.frameSources;if(!t||this.lifecycle.isOneOf(`disposed`,`error`))return;let n=R(yr(e,0,this.parts.duration)),r=this.seeks.claimScrub(),i=await Pf(t,n);this.seeks.isScrubCurrent(r)&&!this.lifecycle.isOneOf(`disposed`,`error`)&&this.seek(i)}preload(){this.run||this.lifecycle.current!==`ready`||this.lifecycle.change(()=>{this.startRun(this.parts.clock.currentTime)})}tick(){this.lifecycle.isOneOf(`disposed`,`error`)||this.lifecycle.change(()=>{let{failure:e}=this.parts.clock;if(e){this.fail(e);return}let t=this.parts.clock.currentTime;if(this.clockWatch.wasMovedFromOutside({now:t,state:this.lifecycle.current})){this.followMoveFromOutside(t);return}if(this.haveTicksStopped(t)){this.restartAt(t);return}this.presentDue(t),this.lifecycle.is(`playing`)?this.followClock(t):this.isStartedFromOutside()&&this.followStartFromOutside()})}redraw(){if(!this.presented||this.lifecycle.isOneOf(`playing`,`error`))return;let{presented:e}=this;this.lifecycle.change(()=>this.draw(e))}dispose(){this.lifecycle.current!==`disposed`&&(this.lifecycle.change(()=>{this.abortRun(),this.presented&&zd(this.presented.pair),this.presented=void 0,this.parts.clock.pause(),this.lifecycle.moveTo(`disposed`),this.buffering.settleStart()}),this.events.removeAll())}beginStart(){if(this.isAtTheEnd()&&this.seek(R(0)),this.lifecycle.canMoveTo(`buffering`))return this.run||this.startRun(this.parts.clock.currentTime),this.isPrimed()?(this.enterPlaying(),this.startClockOnceHeard()):this.startOncePrimed()}startOncePrimed(){return this.parts.clock.pause(),this.buffering.enterForStart()}async startClockOnceHeard(){await Promise.resolve(),this.lifecycle.is(`playing`)&&await this.startClock()}enterPlaying(){this.clockWatch.playingFrom(this.parts.clock.currentTime),this.lifecycle.moveTo(`playing`)}presentDue(e){let t=this.run?.takePairAt(e);t&&this.present(t,e)}followClock(e){if(this.isPlayedOut(e)){this.end();return}if(wf(this.parts.clock)){this.lifecycle.moveTo(`paused`),this.timeUpdates.announce(e);return}if(this.run?.isStarvedAt(e,this.presented?.pair.timestamp)===!0){this.parts.clock.pause(),this.buffering.enter(`starvation`);return}this.timeUpdates.followPlayback(e)}isStartedFromOutside(){return this.parts.clock.isRunning&&this.lifecycle.isOneOf(`ready`,`paused`,`ended`)}async followStartFromOutside(){try{await this.play()}catch{}}moveClockTo(e){this.parts.clock.pause(),this.parts.clock.seek(e),this.clockWatch.placedAt(this.parts.clock.currentTime)}followMoveFromOutside(e){let t=this.parts.clock.isRunning;!t&&this.lifecycle.is(`playing`)&&this.pause(),this.seek(e),t&&this.lifecycle.is(`paused`)&&this.followStartFromOutside()}haveTicksStopped(e){return this.clockWatch.wereTicksMissed({now:e,state:this.lifecycle.current})&&!this.parts.clock.hasEnded}restartAt(e){let{clock:t,duration:n}=this.parts;if(e>=n){this.moveClockTo(n),this.end();return}let r=t.isRunning;if(t.pause(),this.startRun(e),r){this.buffering.enter(`priming`);return}this.lifecycle.moveTo(`paused`),this.timeUpdates.announce(e)}isAtTheEnd(){return this.lifecycle.current===`ended`||Tf(this.parts.clock,this.parts.duration)}isPrimed(){return this.run?.isPrimedAt(this.parts.clock.currentTime)===!0}resumeIfPrimed(){this.buffering.isOverAt(this.run,this.parts.clock.currentTime)&&this.resume()}async resume(){let e=this.buffering.takeStart();this.enterPlaying();try{await this.startClockOnceHeard(),e?.resolve()}catch(t){e?.reject(t)}}async startClock(){try{await this.parts.clock.start()}catch(e){throw this.lifecycle.is(`playing`)&&this.lifecycle.moveTo(`paused`),e}}isPlayedOut(e){let t=this.run?.isDrained===!0&&e>=this.parts.duration;return this.parts.clock.hasEnded||t}present(e,t){this.presented&&zd(this.presented.pair),this.presented={pair:e,mediaTime:t},this.draw(this.presented)&&this.lifecycle.announce(`present`,t)}draw(e){try{return this.parts.sink.present(e),!0}catch(e){return this.fail(ne(e,`render-unavailable`,`the picture could not be drawn`)),!1}}startRun(e){this.abortRun(),this.run=Nf.start(this.parts,e,{onProgress:()=>{this.resumeIfPrimed()},onFailure:e=>{this.fail(e)}})}abortRun(){this.run?.abort(),this.run=void 0}end(){this.lifecycle.canMoveTo(`ended`)&&(this.parts.clock.pause(),this.lifecycle.moveTo(`ended`),this.timeUpdates.announce(this.parts.clock.currentTime),this.lifecycle.announce(`ended`,void 0))}fail(e){this.lifecycle.canMoveTo(`error`)&&this.lifecycle.change(()=>{this.parts.clock.pause(),this.abortRun(),this.lifecycle.moveTo(`error`),this.buffering.settleStart(),this.lifecycle.announce(`error`,ne(e,`decode`,`playback failed`))})}};function If(e,t){if(e===null)return;let n=e.trim().toLowerCase();return t.find(e=>e===n)}function Lf(e){return If(e,qs)}function Rf(e){return If(e,Tc)}function zf(e){return If(e,xc)}function Bf(e,t){for(let n of t)Object.defineProperty(e,qf(n),{configurable:!0,enumerable:!0,get(){return this.getAttribute(n)},set(e){Gf(this,n,e)}})}function Vf(e,t){for(let n of t)Object.defineProperty(e,qf(n),{configurable:!0,enumerable:!0,get(){return this.hasAttribute(n)},set(e){this.toggleAttribute(n,!!e)}})}function Hf(e,t){for(let n of t)Object.defineProperty(e,qf(n.name),{configurable:!0,enumerable:!0,get(){return Wf(n,this.getAttribute(n.name))},set(e){Gf(this,n.name,e)}})}function Uf(e,t){for(let n of t)Object.defineProperty(e,n.property,{configurable:!0,enumerable:!0,get(){let e=this.getAttribute(n.name);return e===null?null:Wf(n,e)},set(e){Gf(this,n.name,e)}})}function Wf(e,t){let n=t?.trim().toLowerCase();return e.keywords.find(e=>e===n)??e.fallback}function Gf(e,t,n){if(n==null){e.removeAttribute(t);return}e.setAttribute(t,n)}var Kf=/-(?<letter>[a-z])/gu;function qf(e){return e.replaceAll(Kf,(e,t)=>t.toUpperCase())}function Jf(e,t){if(typeof e!=`number`||!Number.isFinite(e))throw new j(`invalid-argument`,`${t} must be a finite number`)}function Yf(e){return Jf(e.yaw,`yaw`),Jf(e.pitch,`pitch`),Jf(e.fieldOfView,`fieldOfView`),{yaw:t(e.yaw),pitch:t(e.pitch),roll:t(0),fieldOfView:t(e.fieldOfView)}}var Xf=/* @__PURE__ */ new Map([[` `,`toggle-play`],[`k`,`toggle-play`],[`j`,`seek-back`],[`l`,`seek-forward`],[`s`,`stop`],[`m`,`toggle-mute`],[`f`,`toggle-fullscreen`],[`0`,`reset-view`],[`+`,`zoom-in`],[`=`,`zoom-in`],[`-`,`zoom-out`],[`ArrowLeft`,`look-left`],[`ArrowRight`,`look-right`],[`ArrowUp`,`look-up`],[`ArrowDown`,`look-down`]]),Zf=/* @__PURE__ */ new Map([[`ArrowLeft`,`seek-back`],[`ArrowRight`,`seek-forward`]]);function Qf(e){if(!e.hasSystemModifier)return e.key.length===1?Xf.get(e.key.toLowerCase()):e.isShiftPressed?Zf.get(e.key):Xf.get(e.key)}var $f=5;function ep(e){return({player:t})=>{t.seek(t.currentTime+e)}}function tp(e,t){return({player:n})=>{n.turn(e,t)}}var np={"toggle-play":e=>{e.togglePlay()},stop:({player:e})=>{e.stop()},"seek-back":ep(-5),"seek-forward":ep(5),"toggle-mute":({player:e})=>{e.setMuted(!e.isMuted)},"toggle-fullscreen":e=>{e.toggleFullscreen()},"reset-view":({player:e})=>{e.resetView()},"zoom-in":({player:e})=>{e.zoom(1)},"zoom-out":({player:e})=>{e.zoom(-1)},"look-left":tp(-5,0),"look-right":tp($f,0),"look-up":tp(0,$f),"look-down":tp(0,-5)};function rp(e,t){let n=new AbortController;return e.addEventListener(`keydown`,e=>{if(e.key===`Escape`&&t.isFullscreen()){t.exitFullscreen();return}let n=Qf({key:e.key,isShiftPressed:e.shiftKey,hasSystemModifier:e.ctrlKey||e.altKey||e.metaKey});n&&!op(e)&&(e.preventDefault(),np[n](t))},{signal:n.signal}),()=>{n.abort()}}var ip=/* @__PURE__ */ new Set([`ArrowLeft`,`ArrowRight`,`ArrowUp`,`ArrowDown`]),ap=` `;function op(e){let[t]=e.composedPath();return t instanceof HTMLInputElement?ip.has(e.key):t instanceof HTMLButtonElement&&e.key===ap}var sp=100,cp=`data-draggable`,lp=0,up=4,dp=class{surface;player;onTap;pointers=/* @__PURE__ */ new Map;listening=new AbortController;dragDistance=0;constructor(e,t,n){this.surface=e,this.player=t,this.onTap=n;let{signal:r}=this.listening;e.addEventListener(`pointerenter`,this.reflectDraggable,{signal:r}),e.addEventListener(`pointerdown`,this.onPointerDown,{signal:r}),e.addEventListener(`pointermove`,this.onPointerMove,{signal:r}),e.addEventListener(`pointerup`,this.onPointerUp,{signal:r}),e.addEventListener(`pointercancel`,this.onPointerCancel,{signal:r}),e.addEventListener(`lostpointercapture`,this.onPointerCancel,{signal:r}),e.addEventListener(`wheel`,this.onWheel,{passive:!1,signal:r})}detach(){this.listening.abort(),this.pointers.clear(),this.surface.removeAttribute(cp)}onPointerDown=e=>{(e.pointerType!==`mouse`||e.button===lp)&&(this.pointers.size===0&&(this.dragDistance=0),this.pointers.set(e.pointerId,{x:e.clientX,y:e.clientY}),this.surface.setPointerCapture(e.pointerId))};onPointerMove=e=>{this.reflectDraggable();let t=this.pointers.get(e.pointerId);if(!t)return;let n={x:e.clientX,y:e.clientY};this.pointers.size===1?this.pan(t,n):this.pinch(e.pointerId,n),this.pointers.set(e.pointerId,n)};onPointerUp=e=>{!this.pointers.delete(e.pointerId)||this.pointers.size>0||this.dragDistance<up&&this.onTap(e.pointerType)};onPointerCancel=e=>{this.pointers.delete(e.pointerId),this.dragDistance=1/0};onWheel=e=>{e.preventDefault();let t={x:e.clientX,y:e.clientY};this.player.zoom(-e.deltaY/sp,this.focusAt(t)),this.reflectDraggable()};reflectDraggable=()=>{this.surface.toggleAttribute(cp,this.player.canPan)};pan(e,t){let n={x:t.x-e.x,y:t.y-e.y};this.dragDistance+=Math.hypot(n.x,n.y),this.player.pan(n)}pinch(e,t){let n=[...this.pointers].find(([t])=>t!==e)?.[1],r=this.pointers.get(e);if(!n||!r)return;this.dragDistance=1/0;let i=Xc(fp(r,n),fp(t,n)),a={x:(t.x+n.x)/2,y:(t.y+n.y)/2};this.player.zoom(i,this.focusAt(a))}focusAt(e){let t=this.surface.getBoundingClientRect();return{x:(e.x-t.left)/Math.max(t.width,1),y:(e.y-t.top)/Math.max(t.height,1)}}};function fp(e,t){return Math.hypot(e.x-t.x,e.y-t.y)}function pp(e,t,n={}){let r=new dp(e,t,n.onTap??(()=>{hp(t)}));return()=>{r.detach()}}function mp(e,t,n={}){let r=()=>e.matches(`:fullscreen`);return rp(e,{player:t,togglePlay:()=>{hp(t)},toggleFullscreen:n.toggleFullscreen??(()=>{r()?document.exitFullscreen():e.requestFullscreen()}),isFullscreen:r,exitFullscreen:()=>{document.exitFullscreen()}})}function hp(e){if(!e.isPaused){e.pause();return}e.play().catch(t=>{e.events.emit(`warning`,{code:`playback-failed`,message:`playback could not start: ${ie(t)}`})})}var gp=()=>void 0,_p={availability:`unavailable`,onAvailabilityChange:()=>gp,requestAccess:()=>Promise.resolve(`denied`),listen:()=>gp,dispose:gp},vp=`deviceorientation`;function yp(){return{target:globalThis,mayReadSensors:globalThis.isSecureContext&&xp(),orientationEvents:`DeviceOrientationEvent`in globalThis?DeviceOrientationEvent:void 0,touchPoints:navigator.maxTouchPoints,screenAngle:()=>globalThis.screen.orientation.angle}}var bp=[`accelerometer`,`gyroscope`];function xp(){let e=Reflect.get(document,`featurePolicy`),t=typeof e==`object`&&e?Reflect.get(e,`allowsFeature`):void 0;return typeof t!=`function`||bp.every(n=>Reflect.apply(t,e,[n])===!0)}var Sp=class{source;stops=/* @__PURE__ */ new Set;constructor(e=yp()){this.source=e,this.canReport()&&Op(e.target)}get availability(){return this.isAvailable()?`available`:`unavailable`}onAvailabilityChange(e){return this.canReport()?this.track(Op(this.source.target).onChange(e)):gp}async requestAccess(){if(!this.canReport())return`denied`;let e=this.permissionRequest();if(!e||Op(this.source.target).heard===`angles`)return`granted`;try{return Cp(await e())}catch{return`needs-gesture`}}listen(e){let{target:t}=this.source,n=t=>{let n=wp(t,this.source.screenAngle());n&&e({look:Ul(n),at:pt(t.timeStamp)})};return t.addEventListener(vp,n),this.track(()=>{t.removeEventListener(vp,n)})}dispose(){for(let e of this.stops)e()}isAvailable(){if(!this.canReport())return!1;let{heard:e}=Op(this.source.target),t=this.permissionRequest()!==void 0&&this.source.touchPoints>0;return e===`angles`||e===`nothing`&&t}canReport(){return this.source.mayReadSensors&&this.source.orientationEvents!==void 0}permissionRequest(){let e=this.source.orientationEvents,t=e===void 0?void 0:Reflect.get(e,`requestPermission`);return typeof t==`function`?()=>Reflect.apply(t,e,[]):void 0}track(e){let t=()=>{this.stops.delete(t)&&e()};return this.stops.add(t),t}};function Cp(e){return e===`granted`?`granted`:e===`denied`?`denied`:`needs-gesture`}function wp(e,n){let{alpha:r,beta:i,gamma:a}=e;return Tp(r)&&Tp(i)&&Tp(a)?{alpha:t(r),beta:t(i),gamma:t(a),screenAngle:t(n)}:void 0}function Tp(e){return typeof e==`number`&&Number.isFinite(e)}var Ep=class{target;heardValue=`nothing`;listeners=/* @__PURE__ */ new Set;constructor(e){this.target=e,e.addEventListener(vp,this.hear)}get heard(){return this.heardValue}onChange(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}hear=e=>{let t=wp(e,0)?`angles`:`no-angles`;if(t===this.heardValue)return;this.heardValue=t;let n=[...this.listeners];t===`angles`&&(this.target.removeEventListener(vp,this.hear),this.listeners.clear());for(let e of n)e()}},Dp=/* @__PURE__ */ new WeakMap;function Op(e){let t=Dp.get(e);return t||(t=new Ep(e),Dp.set(e,t)),t}var kp=class{blob;constructor(e){this.blob=e}size(){return Promise.resolve(this.blob.size)}async read(e){if(e.ensureWithin(this.blob.size,`blob`),e.length===0)return/* @__PURE__ */ new Uint8Array;let t=await this.bytesOf(this.blob.slice(e.offset,e.end));if(t.byteLength!==e.length)throw new j(`source-truncated`,`the blob yielded ${t.byteLength} bytes for a ${e.length}-byte range at ${e.offset}; the file may have changed on disk`);return t}async bytesOf(e){try{return new Uint8Array(await e.arrayBuffer())}catch(e){throw new j(`source-unreadable`,`the blob could not be read`,{cause:e})}}},Ap=/^bytes (\d+)-(\d+)\/(\d+|\*)$/u,jp=`*`;function Mp(e){let t=Ap.exec(e.headers.get(`content-range`)??``);if(!t)return;let[,n,r,i]=t;return{first:Number(n),last:Number(r),total:i===jp?void 0:Number(i)}}var Np=/* @__PURE__ */ new WeakSet;function Pp(e){return Np.add(e),e}function Fp(e){return e instanceof j&&Np.has(e)}function Ip(e){return M(e,`source-unreadable`)&&e instanceof Error?Pp(new j(`source-unreadable`,e.message,{cause:e.cause})):e}function Lp(e,t,n){return Pp(new j(`source-unreadable`,`${e} broke off the ${t.length}-byte range at ${t.offset}`,{cause:n}))}function Rp(e,t,n){return new j(`source-truncated`,`${e} returned ${t} bytes for a ${n.length}-byte range at ${n.offset}`)}var zp=1e4,Bp=class{resource;stallTimeoutMs;constructor(e,t={}){this.resource=e,this.stallTimeoutMs=t.stallTimeoutMs??zp}stream(e){return{[Symbol.asyncIterator]:()=>new Vp({resource:this.resource,range:e,stallTimeoutMs:this.stallTimeoutMs})}}},Vp=class{parts;attempt;received=0;ending=new Iu;constructor(e){this.parts=e}async next(){try{let e=await this.parts.resource.askingAgain(()=>this.readChunk());if(e)return{done:!1,value:e}}catch(e){if(!this.ending.hasEnded())throw this.end(),e}return this.end(),Fu}return(){return this.end(),Promise.resolve(Fu)}async readChunk(){let{resource:e,range:t}=this.parts;if(await e.ensureFits(t),this.ending.hasEnded()||t.length===0)return;this.attempt??=this.attemptAtTheRest();let{attempt:n}=this;try{let e=await this.withinStallTimeout(this.readFrom(n));return this.taken(e)}catch(e){throw this.drop(n),e}}attemptAtTheRest(){let{range:e}=this.parts,t=Fn.of(e.offset+this.received,e.length-this.received),n=new AbortController;return{request:n,body:this.bodyOf(t,n.signal)}}async bodyOf(e,t){let n=await this.parts.resource.rangeAnswer(e,t);return this.ensureAnswers(n,e),n.body?.getReader()??new ReadableStream().getReader()}ensureAnswers(e,t){let n=Mp(e);if(!n)return;let r=`${t.offset}-${t.end-1}`,i=`${n.first}-${n.last}`;if(i!==r)throw new j(`source-unreadable`,`${this.parts.resource.url} answered bytes ${i} to a request for bytes ${r}`)}async readFrom(e){let t=await e.body;try{return await t.read()}catch(e){throw re(e)?e:Lp(this.parts.resource.url,this.parts.range,e)}}async withinStallTimeout(e){let t,n=new Promise((e,n)=>{t=setTimeout(()=>{n(this.stalled())},this.parts.stallTimeoutMs)});try{return await Promise.race([e,n])}finally{clearTimeout(t)}}stalled(){let{resource:e,range:t,stallTimeoutMs:n}=this.parts;return Pp(new j(`source-unreadable`,`${e.url} sent nothing of the ${t.length}-byte range at ${t.offset} for ${n} ms`))}taken(e){if(e.done){this.ensureWhole();return}return this.count(e.value),e.value}count(e){let{resource:t,range:n}=this.parts;if(this.received+=e.byteLength,!(this.received<=n.length))throw new j(`source-unreadable`,`${t.url} sent more than the ${n.length}-byte range at ${n.offset}`)}ensureWhole(){let{resource:e,range:t}=this.parts;if(this.received!==t.length)throw Rp(e.url,this.received,t)}drop(e){e.request.abort(),this.attempt===e&&(this.attempt=void 0)}end(){this.ending.end(),this.attempt&&this.drop(this.attempt)}},Hp=class{resource;constructor(e){this.resource=e}size(){return this.resource.size()}async read(e){return await this.resource.ensureFits(e),e.length===0?/* @__PURE__ */ new Uint8Array:this.resource.askingAgain(()=>this.readOnce(e))}async readOnce(e){let t=await this.resource.rangeAnswer(e),n=await this.bodyOf(t,e);if(n.byteLength!==e.length)throw Rp(this.resource.url,n.byteLength,e);return n}async bodyOf(e,t){try{return new Uint8Array(await e.arrayBuffer())}catch(e){throw re(e)?e:Lp(this.resource.url,t,e)}}},Up=`bytes=0-0`,Wp=`Access-Control-Expose-Headers: Content-Range, Content-Length, Accept-Ranges, ETag`,Gp=`Access-Control-Allow-Origin, ${Wp}`,Kp=`Access-Control-Allow-Origin naming this page's origin, not *; Access-Control-Allow-Credentials: true; ${Wp}`,qp=`no-store`;async function Jp(e,t,n){try{return await Yp(e,t,n)}catch(t){throw re(t)?t:await Qp(e,n,t)}}function Yp(e,t,n){return(n.fetch??fetch)(e,{cache:qp,...n.requestInit,method:t.method,headers:{...rm(n.requestInit),...t.headers}})}function Xp(e,t){let n=e.requestInit?.signal??void 0,r=n?Zp(n,t):t;return{...e,requestInit:{...e.requestInit,signal:r}}}function Zp(e,t){let n=new AbortController;for(let r of[e,t])r.aborted&&n.abort(r.reason),r.addEventListener(`abort`,()=>{n.abort(r.reason)},{once:!0,signal:n.signal});return n.signal}async function Qp(e,t,n){return await em(e,t)?new j(`cors`,`${e} answered, but its server does not allow this page's origin to read it; add CORS headers (${$p(t)})`,{cause:n}):new j(`source-unreadable`,`${e} could not be fetched; check the URL and the network`,{cause:n})}function $p(e){return e.requestInit?.credentials===`include`?Kp:Gp}async function em(e,t){let n=t.fetch??fetch,r=t.requestInit?.signal??null;try{return tm(await n(e,{method:`HEAD`,mode:`no-cors`,signal:r})),!0}catch(e){if(re(e))throw e;return!1}}function tm(e){nm(e)}async function nm(e){try{await e.body?.cancel()}catch{}}function rm(e){return Object.fromEntries(new Headers(e?.headers).entries())}var im=200,am=/^W\//u;function om(e){let t=e.headers.get(`etag`),n=e.headers.get(`last-modified`),r=um(e);return{...t!==null&&{etag:t},...n!==null&&{lastModified:n},...r!==void 0&&{size:r}}}function sm(e,t){return e.etag!==void 0&&t.etag!==void 0?cm(e.etag)===cm(t.etag):lm(e.lastModified,t.lastModified)&&lm(e.size,t.size)}function cm(e){return e.replace(am,``)}function lm(e,t){return e===void 0||t===void 0||e===t}function um(e){let t=e.status===im?Number(e.headers.get(`content-length`)??NaN):Mp(e)?.total;return t!==void 0&&Number.isSafeInteger(t)&&t>0?t:void 0}var dm=200,fm=206,pm=500,mm=[250,1e3],hm=class{url;options;retryDelaysMs;sizePromise;hasReadRange=!1;version;constructor(e,t={},n){this.url=e,this.options=n?Xp(t,n):t,this.retryDelaysMs=t.retryDelaysMs??mm}size(){return this.sizePromise??=this.rememberSize(),this.sizePromise}async ensureFits(e){e.ensureWithin(await this.size(),`resource ${this.url}`)}async askingAgain(e){for(let t of this.retryDelaysMs){try{return await e()}catch(e){if(!Fp(e))throw e}await gm(t,this.options.requestInit?.signal)}return e()}async rangeAnswer(e,t){let n=t?Xp(this.options,t):this.options,r=await this.requestRange(e,n);if(r.status!==fm)throw tm(r),this.refusalOf(r.status);return this.hasReadRange=!0,this.ensureUnchanged(r),r}ensureUnchanged(e){let t=om(e);if(this.version??=t,!sm(this.version,t))throw tm(e),new j(`source-changed`,`${this.url} was replaced while it played; load it again`)}async requestRange(e,t){let n={Range:`bytes=${e.offset}-${e.end-1}`};try{return this.hasReadRange?await Yp(this.url,{method:`GET`,headers:n},t):await Jp(this.url,{method:`GET`,headers:n},t)}catch(e){throw this.hasReadRange?this.passingOnceAnswered(e):Ip(e)}}passingOnceAnswered(e){let t=`${this.url} could not be reached for a byte range`;return re(e)?e:Pp(new j(`source-unreadable`,t,{cause:e}))}refusalOf(e){if(e===dm)return new j(`range-unsupported`,`${this.url} ignores Range requests (answered 200 to a byte range)`);let t=`${this.url} answered ${e} to a byte range`;return e>=pm?Pp(new j(`source-unreadable`,t)):new j(`source-unreadable`,t)}async rememberSize(){try{return await this.fetchSize()}catch(e){throw this.sizePromise=void 0,e}}async fetchSize(){let e=await this.request(`HEAD`);if(tm(e),!e.ok)return this.sizeFromContentRange();this.ensureUnchanged(e);let t=Number(e.headers.get(`content-length`));return Number.isSafeInteger(t)&&t>0?t:this.sizeFromContentRange()}async sizeFromContentRange(){let e=await this.request(`GET`,{Range:Up});if(tm(e),e.status!==fm)throw new j(`source-unreadable`,`${this.url} answered ${e.status} to a byte range; cannot determine the file size`);return this.hasReadRange=!0,this.ensureUnchanged(e),this.totalOf(e)}totalOf(e){if(!e.headers.has(`content-range`)&&e.type===`cors`)throw this.hiddenContentRange();let t=Mp(e)?.total;if(t===void 0)throw new j(`source-unreadable`,`${this.url} reports neither Content-Length nor Content-Range; cannot determine the file size`);return t}hiddenContentRange(){return new j(`cors`,`${this.url} answered a byte range but hides its Content-Range from this origin; add ${Wp}`)}request(e,t){return Jp(this.url,{method:e,...t&&{headers:t}},this.options)}};function gm(e,t){return new Promise((n,r)=>{t?.throwIfAborted();let i=new AbortController,a=setTimeout(()=>{i.abort(),n()},e);t?.addEventListener(`abort`,()=>{clearTimeout(a),r(_m(t))},{once:!0,signal:i.signal})})}function _m(e){let t=e?.reason;return t instanceof Error?t:new DOMException(`the read was aborted`,`AbortError`)}var vm=/* @__PURE__ */ new Set([405,403]),ym=class{options;constructor(e={}){this.options=e}async exists(e){try{let t=await Yp(e,{method:`HEAD`},this.options);if(tm(t),!vm.has(t.status))return t.ok;let n=await Yp(e,{method:`GET`,headers:{Range:Up}},this.options);return tm(n),n.ok}catch{return!1}}};function z(e){if(!e)throw Error(`Assertion failed.`)}var bm=Math.PI/180,xm=180/Math.PI,Sm=e=>{let t=(e%360+360)%360;if(t===0||t===90||t===180||t===270)return t;throw Error(`Invalid rotation ${e}.`)},Cm=[1,0,0,0,1,0,0,0,1],wm=(e,t,n)=>{let[r,i,,a,o]=e,s=Math.abs(r)*t+Math.abs(a)*n,c=Math.abs(i)*t+Math.abs(o)*n;return Am(Am(Om(-t/2,-n/2),e),Om(s/2,c/2))},Tm=e=>{let[t,n]=e;return Sm(ph(Math.atan2(n,Em(e)?-t:t)*xm,90))},Em=e=>{let[t,n,,r,i]=e;return t*i-n*r<0},Dm=e=>{let t=e*bm,n=Math.round(Math.cos(t)),r=Math.round(Math.sin(t));return[n,r,0,-r,n,0,0,0,1]},Om=(e,t)=>[1,0,0,0,1,0,e,t,1],km=(e,t)=>[e,0,0,0,t,0,0,0,1],Am=(e,t)=>{let n=Array(9);for(let r=0;r<3;r++)for(let i=0;i<3;i++)n[3*r+i]=e[3*r]*t[i]+e[3*r+1]*t[3+i]+e[3*r+2]*t[6+i];return n},jm=e=>e&&e[e.length-1],Mm=e=>e>=0&&e<2**32,Nm=e=>e>=-(2**31)&&e<2**31,B=e=>{let t=0;for(;e.readBits(1)===0&&t<32;)t++;if(t>=32)throw Error(`Invalid exponential-Golomb code.`);return(1<<t)-1+e.readBits(t)},Pm=e=>{let t=B(e);return t&1?t+1>>1:-(t>>1)},Fm=e=>e.constructor===Uint8Array?e:ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):new Uint8Array(e),Im=e=>e.constructor===DataView?e:ArrayBuffer.isView(e)?new DataView(e.buffer,e.byteOffset,e.byteLength):new DataView(e),Lm=globalThis.TextEncoder===void 0?class{constructor(){this.encoding=`utf-8`}encode(e=``){let t=new Uint8Array(3*e.length),n=0;for(let r=0;r<e.length;r++){let i=e.charCodeAt(r);if(i<128)t[n++]=i;else if(i<2048)t[n++]=192|i>>6,t[n++]=128|i&63;else if(i<55296||i>57343)t[n++]=224|i>>12,t[n++]=128|i>>6&63,t[n++]=128|i&63;else{let a=r+1<e.length?e.charCodeAt(r+1):0;i<56320&&a>=56320&&a<=57343?(i=65536+(i-55296<<10)+(a-56320),r++,t[n++]=240|i>>18,t[n++]=128|i>>12&63,t[n++]=128|i>>6&63,t[n++]=128|i&63):(t[n++]=239,t[n++]=191,t[n++]=189)}}return t.slice(0,n)}}:globalThis.TextEncoder,Rm=globalThis.TextDecoder===void 0?class{constructor(e=`utf-8`){let t=e.trim().toLowerCase();if(t===`utf-8`||t===`utf8`||t===`unicode-1-1-utf-8`)this.encoding=`utf-8`;else if(t===`utf-16le`||t===`utf-16`)this.encoding=`utf-16le`;else if(t===`utf-16be`)this.encoding=`utf-16be`;else throw RangeError(`The encoding label provided ('${e}') is invalid.`)}decode(e){let t=e?Fm(e):/* @__PURE__ */ new Uint8Array,n=[];if(this.encoding===`utf-8`){let e=t.length>=3&&t[0]===239&&t[1]===187&&t[2]===191?3:0;for(;e<t.length;){let r=t[e];if(r<128){n.push(r),e++;continue}let i,a;if(r>=194&&r<224)i=1,a=r&31;else if(r>=224&&r<240)i=2,a=r&15;else if(r>=240&&r<245)i=3,a=r&7;else{n.push(65533),e++;continue}let o=r===224?160:r===240?144:128,s=r===237?159:r===244?143:191,c=1;for(;c<=i;c++){let n=e+c<t.length?t[e+c]:0;if(n<o||n>s)break;a=a<<6|n&63,o=128,s=191}e+=c,c<=i?n.push(65533):a>=65536?(a-=65536,n.push(55296|a>>10,56320|a&1023)):n.push(a)}}else{let e=this.encoding===`utf-16le`,r=e?255:254,i=e?254:255,a=t.length>=2&&t[0]===r&&t[1]===i?2:0;for(;a+1<t.length;){let r=e?t[a]|t[a+1]<<8:t[a]<<8|t[a+1];if(a+=2,r>=55296&&r<=56319){let i=a+1<t.length?e?t[a]|t[a+1]<<8:t[a]<<8|t[a+1]:-1;i>=56320&&i<=57343?(n.push(r,i),a+=2):n.push(65533)}else r>=56320&&r<=57343?n.push(65533):n.push(r)}a<t.length&&n.push(65533)}let r=``;for(let e=0;e<n.length;e+=8192)r+=String.fromCharCode(...n.slice(e,e+8192));return r}}:globalThis.TextDecoder,zm=/* #__PURE__ */ new Rm,Bm=/* #__PURE__ */ new Lm,Vm=e=>Object.fromEntries(Object.entries(e).map(([e,t])=>[t,e])),Hm={bt709:1,bt470bg:5,smpte170m:6,bt2020:9,smpte432:12},Um=/* #__PURE__ */ Vm(Hm),Wm={bt709:1,smpte170m:6,linear:8,"iec61966-2-1":13,pq:16,hlg:18},Gm=/* #__PURE__ */ Vm(Wm),Km={rgb:0,bt709:1,bt470bg:5,smpte170m:6,"bt2020-ncl":9},qm=/* #__PURE__ */ Vm(Km),Jm=e=>!!e&&!!e.primaries&&!!e.transfer&&!!e.matrix&&e.fullRange!==void 0,Ym=e=>!e||e.primaries==null&&e.transfer==null&&e.matrix==null&&e.fullRange==null,Xm={primaries:void 0,transfer:void 0,matrix:void 0,fullRange:void 0},Zm=e=>e instanceof ArrayBuffer||typeof SharedArrayBuffer<`u`&&e instanceof SharedArrayBuffer||ArrayBuffer.isView(e),Qm=class{constructor(){this.currentPromise=Promise.resolve(),this.pending=0}async acquire(){let e,t=new Promise(t=>{let n=!1;e=()=>{n||=(t(),this.pending--,!0)}}),n=this.currentPromise;return this.currentPromise=t,this.pending++,await n,e}},$m=/^[0-9a-fA-F]+$/,eh=e=>[...e].map(e=>e.toString(16).padStart(2,`0`)).join(``),th=e=>{z(e.length%2==0);let t=new Uint8Array(e.length/2);for(let n=0;n<e.length;n+=2)t[n/2]=parseInt(e.slice(n,n+2),16);return t},nh=e=>(e=e>>1&1431655765|(e&1431655765)<<1,e=e>>2&858993459|(e&858993459)<<2,e=e>>4&252645135|(e&252645135)<<4,e=e>>8&16711935|(e&16711935)<<8,e=e>>16&65535|(e&65535)<<16,e>>>0),rh=(e,t,n)=>{let r=0,i=e.length-1,a=-1;for(;r<=i;){let o=r+i>>1,s=n(e[o]);s===t?(a=o,i=o-1):s<t?r=o+1:i=o-1}return a},ih=(e,t,n)=>{let r=0,i=e.length-1,a=-1;for(;r<=i;){let o=r+(i-r+1)/2|0;n(e[o])<=t?(a=o,r=o+1):i=o-1}return a},ah=()=>{let e,t;return{promise:new Promise((n,r)=>{e=n,t=r}),resolve:e,reject:t}},oh=(e,t)=>{let n=e.indexOf(t);n!==-1&&e.splice(n,1)},sh=(e,t)=>{for(let n=e.length-1;n>=0;n--)if(t(e[n]))return n;return-1},ch=e=>{throw Error(`Unexpected value: ${e}`)},lh=(e,t,n)=>{let r=e.getUint8(t),i=e.getUint8(t+1),a=e.getUint8(t+2);return n?r|i<<8|a<<16:r<<16|i<<8|a},uh=(e,t,n,r)=>{n>>>=0,n&=16777215,r?(e.setUint8(t,n&255),e.setUint8(t+1,n>>>8&255),e.setUint8(t+2,n>>>16&255)):(e.setUint8(t,n>>>16&255),e.setUint8(t+1,n>>>8&255),e.setUint8(t+2,n&255))},dh=(e,t,n)=>Math.max(t,Math.min(n,e)),fh=e=>{let t=Math.round(e);return Math.abs(e/t-1)<10*2**-52?t:e},ph=(e,t)=>Math.round(e/t)*t,mh=(e,t)=>Math.round(e*t)/t,hh=e=>{let t=0;for(;e!==0;)e&=e-1,t++;return t},gh=/^[a-z]{3}$/,_h=e=>gh.test(e),vh=1e6*(1+2**-52),yh=(e,t)=>{let n=e<0?-1:1;e=Math.abs(e);let r=0,i=1,a=1,o=0,s=e;for(;;){let e=Math.floor(s),c=e*a+r,l=e*o+i;if(l>t)return{num:n*a,den:o};if(r=a,i=o,a=c,o=l,s=1/(s-e),!isFinite(s))break}return{num:n*a,den:o}},bh=null,xh=()=>bh===null?bh=!(typeof navigator>`u`||!navigator.vendor?.includes(`Google Inc`)&&!/Chrome/.test(navigator.userAgent)):bh,Sh=(/* #__PURE__ */ (async()=>{})()).constructor,Ch=e=>e instanceof Sh||e instanceof Promise||typeof e?.then==`function`,wh=function*(e){for(let t in e){let n=e[t];n!==void 0&&(yield{key:t,value:n})}},Th=(e,t)=>{if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0},Eh=()=>{Symbol.dispose??=Symbol(`Symbol.dispose`)},Dh=e=>typeof e==`number`&&!Number.isNaN(e),Oh=(e,t)=>{let n=0;for(let r=0;r<e.length;r++)t(e[r])&&n++;return n},kh=(e,t)=>{let n=-1,r=1/0;for(let i=0;i<e.length;i++){let a=t(e[i]);a<r&&(r=a,n=i)}return n},Ah=e=>{z(Number.isInteger(e.num)),z(Number.isInteger(e.den)),z(e.den!==0);let t=Math.abs(e.num),n=Math.abs(e.den);for(;n!==0;){let e=t%n;t=n,n=e}let r=t||1;return{num:e.num/r,den:e.den/r}},jh=e=>Array.isArray(e)?e:[e],Mh=class{constructor(){this._listeners=/* @__PURE__ */ new Map}on(e,t,n){this._listeners.has(e)||this._listeners.set(e,/* @__PURE__ */ new Set);let r={fn:t,once:n?.once??!1};return this._listeners.get(e).add(r),()=>{this._listeners.get(e)?.delete(r)}}_emit(...e){let[t,n]=e,r=this._listeners.get(t);if(r)for(let e of r){try{e.fn(n)}catch(e){console.error(e)}e.once&&r.delete(e)}}},Nh=e=>typeof e==`object`&&!!e&&Object.getPrototypeOf(e)===Object.prototype&&Object.values(e).every(e=>typeof e==`string`),Ph;(function(e){e[e.Silent=0]=`Silent`,e[e.Errors=1]=`Errors`,e[e.Warnings=2]=`Warnings`,e[e.Info=3]=`Info`})(Ph||={});var Fh=class e{constructor(){}static get level(){return e._level}static set level(t){if(t!==Ph.Silent&&t!==Ph.Errors&&t!==Ph.Warnings&&t!==Ph.Info)throw TypeError(`Invalid log level. Use one of the values of the LogLevel enum.`);e._level=t}static get _emitter(){return e._emitterInstance??=new Mh}static on(t,n,r){return e._emitter.on(t,n,r)}static _error(...t){e._emitter._emit(`error`,t),e._level>=Ph.Errors&&console.error(...t)}static _warn(...t){e._emitter._emit(`warn`,t),e._level>=Ph.Warnings&&console.warn(...t)}static _info(...t){e._emitter._emit(`info`,t),e._level>=Ph.Info&&console.info(...t)}};Fh._level=Ph.Info,Fh._emitterInstance=null;var Ih=class{constructor(e,t){if(this.data=e,this.mimeType=t,!(e instanceof Uint8Array))throw TypeError(`data must be a Uint8Array.`);if(typeof t!=`string`)throw TypeError(`mimeType must be a string.`)}},Lh=class{constructor(e,t,n,r){if(this.data=e,this.mimeType=t,this.name=n,this.description=r,!(e instanceof Uint8Array))throw TypeError(`data must be a Uint8Array.`);if(t!==void 0&&typeof t!=`string`)throw TypeError(`mimeType, when provided, must be a string.`);if(n!==void 0&&typeof n!=`string`)throw TypeError(`name, when provided, must be a string.`);if(r!==void 0&&typeof r!=`string`)throw TypeError(`description, when provided, must be a string.`)}},Rh=e=>{if(!e||typeof e!=`object`)throw TypeError(`tags must be an object.`);if(e.title!==void 0&&typeof e.title!=`string`)throw TypeError(`tags.title, when provided, must be a string.`);if(e.description!==void 0&&typeof e.description!=`string`)throw TypeError(`tags.description, when provided, must be a string.`);if(e.artist!==void 0&&typeof e.artist!=`string`)throw TypeError(`tags.artist, when provided, must be a string.`);if(e.album!==void 0&&typeof e.album!=`string`)throw TypeError(`tags.album, when provided, must be a string.`);if(e.albumArtist!==void 0&&typeof e.albumArtist!=`string`)throw TypeError(`tags.albumArtist, when provided, must be a string.`);if(e.trackNumber!==void 0&&(!Number.isInteger(e.trackNumber)||e.trackNumber<=0))throw TypeError(`tags.trackNumber, when provided, must be a positive integer.`);if(e.tracksTotal!==void 0&&(!Number.isInteger(e.tracksTotal)||e.tracksTotal<=0))throw TypeError(`tags.tracksTotal, when provided, must be a positive integer.`);if(e.discNumber!==void 0&&(!Number.isInteger(e.discNumber)||e.discNumber<=0))throw TypeError(`tags.discNumber, when provided, must be a positive integer.`);if(e.discsTotal!==void 0&&(!Number.isInteger(e.discsTotal)||e.discsTotal<=0))throw TypeError(`tags.discsTotal, when provided, must be a positive integer.`);if(e.genre!==void 0&&typeof e.genre!=`string`)throw TypeError(`tags.genre, when provided, must be a string.`);if(e.date!==void 0&&(!(e.date instanceof Date)||Number.isNaN(e.date.getTime())))throw TypeError(`tags.date, when provided, must be a valid Date.`);if(e.lyrics!==void 0&&typeof e.lyrics!=`string`)throw TypeError(`tags.lyrics, when provided, must be a string.`);if(e.images!==void 0){if(!Array.isArray(e.images))throw TypeError(`tags.images, when provided, must be an array.`);for(let t of e.images){if(!t||typeof t!=`object`)throw TypeError(`Each image in tags.images must be an object.`);if(!(t.data instanceof Uint8Array))throw TypeError(`Each image.data must be a Uint8Array.`);if(typeof t.mimeType!=`string`)throw TypeError(`Each image.mimeType must be a string.`);if(![`coverFront`,`coverBack`,`unknown`].includes(t.kind))throw TypeError(`Each image.kind must be 'coverFront', 'coverBack', or 'unknown'.`)}}if(e.comment!==void 0&&typeof e.comment!=`string`)throw TypeError(`tags.comment, when provided, must be a string.`);if(e.raw!==void 0){if(!e.raw||typeof e.raw!=`object`)throw TypeError(`tags.raw, when provided, must be an object.`);for(let t of Object.values(e.raw))if(t!==null&&typeof t!=`string`&&!(Array.isArray(t)&&t.every(e=>typeof e==`string`))&&!(t instanceof Uint8Array)&&!(t instanceof Ih)&&!(t instanceof Lh)&&!Nh(t))throw TypeError(`Each value in tags.raw must be a string, string array, Uint8Array, RichImageData, AttachedFile, Record<string, string>, or null.`)}},zh={default:!0,primary:!0,forced:!1,original:!1,commentary:!1,hearingImpaired:!1,visuallyImpaired:!1},Bh=e=>{if(!e||typeof e!=`object`)throw TypeError(`disposition must be an object.`);if(e.default!==void 0&&typeof e.default!=`boolean`)throw TypeError(`disposition.default must be a boolean.`);if(e.primary!==void 0&&typeof e.primary!=`boolean`)throw TypeError(`disposition.primary must be a boolean.`);if(e.forced!==void 0&&typeof e.forced!=`boolean`)throw TypeError(`disposition.forced must be a boolean.`);if(e.original!==void 0&&typeof e.original!=`boolean`)throw TypeError(`disposition.original must be a boolean.`);if(e.commentary!==void 0&&typeof e.commentary!=`boolean`)throw TypeError(`disposition.commentary must be a boolean.`);if(e.hearingImpaired!==void 0&&typeof e.hearingImpaired!=`boolean`)throw TypeError(`disposition.hearingImpaired must be a boolean.`);if(e.visuallyImpaired!==void 0&&typeof e.visuallyImpaired!=`boolean`)throw TypeError(`disposition.visuallyImpaired must be a boolean.`)},Vh=class e{constructor(e){this.bytes=e,this.pos=0}seekToByte(e){this.pos=8*e}readBit(){let e=Math.floor(this.pos/8),t=this.bytes[e]??0,n=7-(this.pos&7),r=(t&1<<n)>>n;return this.pos++,r}readBits(e){if(e===1)return this.readBit();let t=0;for(let n=0;n<e;n++)t<<=1,t|=this.readBit();return t}writeBits(e,t){let n=this.pos+e;for(let e=this.pos;e<n;e++){let r=Math.floor(e/8),i=this.bytes[r],a=7-(e&7);i&=~(1<<a),i|=(t&1<<n-e-1)>>n-e-1<<a,this.bytes[r]=i}this.pos=n}copyBits(e,t){let n=0;for(;n<e-7;n+=8)this.writeBits(8,t.readBits(8));let r=e-n;r>0&&this.writeBits(r,t.readBits(r))}readAlignedByte(){if(this.pos%8!=0)throw Error(`Bitstream is not byte-aligned.`);let e=this.pos/8,t=this.bytes[e]??0;return this.pos+=8,t}skipBits(e){this.pos+=e}getBitsLeft(){return this.bytes.length*8-this.pos}clone(){let t=new e(this.bytes);return t.pos=this.pos,t}},Hh=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],Uh=[-1,1,2,3,4,5,6,8],Wh=e=>{if(!e||e.byteLength<2)throw TypeError(`AAC description must be at least 2 bytes long.`);let t=new Vh(e),n=Gh(t),{frequencyIndex:r,sampleRate:i}=Kh(t),a=t.readBits(4),o=null;a>=1&&a<=7&&(o=Uh[a]);let s=n,c=!1,l=i;if(n===5||n===29)c=n===29,l=Kh(t).sampleRate,s=Gh(t),s===22&&t.skipBits(4);else for(;t.getBitsLeft()>15;){let e=t.pos;if(t.readBits(11)!==695){t.pos=e+1;continue}Gh(t)===5&&t.readBits(1)&&(l=Kh(t).sampleRate,t.getBitsLeft()>11&&t.readBits(11)===1352&&(c=!!t.readBits(1)));break}return o!==null&&o>1&&(c=!1),{objectType:n,coreObjectType:s,frequencyIndex:r,channelConfiguration:a,outputSampleRate:l,outputNumberOfChannels:c&&o===1?2:o}},Gh=e=>{let t=e.readBits(5);return t===31?32+e.readBits(6):t},Kh=e=>{let t=e.readBits(4);return t===15?{frequencyIndex:t,sampleRate:e.readBits(24)}:{frequencyIndex:t,sampleRate:t<Hh.length?Hh[t]:null}},qh=e=>{let t=e.objectType===5||e.objectType===29,n=e.objectType===29,r=t?e.outputSampleRate/2:e.outputSampleRate,i=n?1:e.outputNumberOfChannels,a=Uh.indexOf(i);if(a===-1)throw TypeError(`Unsupported number of channels: ${e.outputNumberOfChannels}`);let o=16;e.objectType>=32&&(o+=6),Xh(r)===15&&(o+=24),t&&(o+=9,Xh(e.outputSampleRate)===15&&(o+=24));let s=Math.ceil(o/8),c=new Uint8Array(s),l=new Vh(c);return Jh(l,e.objectType),Yh(l,r),l.writeBits(4,a),t&&(Yh(l,e.outputSampleRate),Jh(l,2)),l.writeBits(3,0),c},Jh=(e,t)=>{t<32?e.writeBits(5,t):(e.writeBits(5,31),e.writeBits(6,t-32))},Yh=(e,t)=>{let n=Xh(t);e.writeBits(4,n),n===15&&e.writeBits(24,t)},Xh=e=>{let t=Hh.indexOf(e);return t===-1?15:t},Zh=[48e3,44100,32e3],Qh=[24e3,22050,16e3],$h;(function(e){e[e.NON_IDR_SLICE=1]=`NON_IDR_SLICE`,e[e.SLICE_DPA=2]=`SLICE_DPA`,e[e.SLICE_DPB=3]=`SLICE_DPB`,e[e.SLICE_DPC=4]=`SLICE_DPC`,e[e.IDR=5]=`IDR`,e[e.SEI=6]=`SEI`,e[e.SPS=7]=`SPS`,e[e.PPS=8]=`PPS`,e[e.AUD=9]=`AUD`,e[e.SPS_EXT=13]=`SPS_EXT`})($h||={});var eg;(function(e){e[e.RASL_N=8]=`RASL_N`,e[e.RASL_R=9]=`RASL_R`,e[e.BLA_W_LP=16]=`BLA_W_LP`,e[e.RSV_IRAP_VCL23=23]=`RSV_IRAP_VCL23`,e[e.VPS_NUT=32]=`VPS_NUT`,e[e.SPS_NUT=33]=`SPS_NUT`,e[e.PPS_NUT=34]=`PPS_NUT`,e[e.AUD_NUT=35]=`AUD_NUT`,e[e.PREFIX_SEI_NUT=39]=`PREFIX_SEI_NUT`,e[e.SUFFIX_SEI_NUT=40]=`SUFFIX_SEI_NUT`})(eg||={});var tg=function*(e){let t=0,n=-1;for(;t<e.length-2;){let r=e.indexOf(0,t);if(r===-1||r>=e.length-2)break;t=r;let i=0;if(t+3<e.length&&e[t+1]===0&&e[t+2]===0&&e[t+3]===1?i=4:e[t+1]===0&&e[t+2]===1&&(i=3),i===0){t++;continue}n!==-1&&t>n&&(yield{offset:n,length:t-n}),n=t+i,t=n}n!==-1&&n<e.length&&(yield{offset:n,length:e.length-n})},ng=function*(e,t){let n=0,r=new DataView(e.buffer,e.byteOffset,e.byteLength);for(;n+t<=e.length;){let e;t===1?e=r.getUint8(n):t===2?e=r.getUint16(n,!1):t===3?e=lh(r,n,!1):(z(t===4),e=r.getUint32(n,!1)),n+=t,yield{offset:n,length:e},n+=e}},rg=(e,t)=>t.description?ng(e,(Fm(t.description)[4]&3)+1):tg(e),ig=e=>e&31,ag=e=>{let t=[],n=e.length;for(let r=0;r<n;r++)r+2<n&&e[r]===0&&e[r+1]===0&&e[r+2]===3?(t.push(0,0),r+=2):t.push(e[r]);return new Uint8Array(t)};new Uint8Array([0,0,0,1]);var og=(e,t)=>{let n=e.reduce((e,n)=>e+t+n.byteLength,0),r=new Uint8Array(n),i=0;for(let n of e){let e=new DataView(r.buffer,r.byteOffset,r.byteLength);switch(t){case 1:e.setUint8(i,n.byteLength);break;case 2:e.setUint16(i,n.byteLength,!1);break;case 3:uh(e,i,n.byteLength,!1);break;case 4:e.setUint32(i,n.byteLength,!1)}i+=t,r.set(n,i),i+=n.byteLength}return r},sg=e=>{try{let t=[],n=[],r=[];for(let i of tg(e)){let a=e.subarray(i.offset,i.offset+i.length),o=ig(a[0]);o===$h.SPS?t.push(a):o===$h.PPS?n.push(a):o===$h.SPS_EXT&&r.push(a)}if(t.length===0||n.length===0)return null;let i=t[0],a=dg(i);z(a!==null);let o=a.profileIdc===100||a.profileIdc===110||a.profileIdc===122||a.profileIdc===144;return{configurationVersion:1,avcProfileIndication:a.profileIdc,profileCompatibility:a.constraintFlags,avcLevelIndication:a.levelIdc,lengthSizeMinusOne:3,sequenceParameterSets:t,pictureParameterSets:n,chromaFormat:o?a.chromaFormatIdc:null,bitDepthLumaMinus8:o?a.bitDepthLumaMinus8:null,bitDepthChromaMinus8:o?a.bitDepthChromaMinus8:null,sequenceParameterSetExt:o?r:null}}catch(e){return Fh._error(`Error building AVC Decoder Configuration Record:`,e),null}},cg=e=>{let t=[];t.push(e.configurationVersion),t.push(e.avcProfileIndication),t.push(e.profileCompatibility),t.push(e.avcLevelIndication),t.push(252|e.lengthSizeMinusOne&3),t.push(224|e.sequenceParameterSets.length&31);for(let n of e.sequenceParameterSets){let e=n.byteLength;t.push(e>>8),t.push(e&255);for(let r=0;r<e;r++)t.push(n[r])}t.push(e.pictureParameterSets.length);for(let n of e.pictureParameterSets){let e=n.byteLength;t.push(e>>8),t.push(e&255);for(let r=0;r<e;r++)t.push(n[r])}if((e.avcProfileIndication===100||e.avcProfileIndication===110||e.avcProfileIndication===122||e.avcProfileIndication===144)&&e.chromaFormat!==null){z(e.bitDepthLumaMinus8!==null),z(e.bitDepthChromaMinus8!==null),z(e.sequenceParameterSetExt!==null),t.push(252|e.chromaFormat&3),t.push(248|e.bitDepthLumaMinus8&7),t.push(248|e.bitDepthChromaMinus8&7),t.push(e.sequenceParameterSetExt.length);for(let n of e.sequenceParameterSetExt){let e=n.byteLength;t.push(e>>8),t.push(e&255);for(let r=0;r<e;r++)t.push(n[r])}}return new Uint8Array(t)},lg=e=>{try{let t=Im(e),n=0,r=t.getUint8(n++),i=t.getUint8(n++),a=t.getUint8(n++),o=t.getUint8(n++),s=t.getUint8(n++)&3,c=t.getUint8(n++)&31,l=[];for(let r=0;r<c;r++){let r=t.getUint16(n,!1);n+=2,l.push(e.subarray(n,n+r)),n+=r}let u=t.getUint8(n++),d=[];for(let r=0;r<u;r++){let r=t.getUint16(n,!1);n+=2,d.push(e.subarray(n,n+r)),n+=r}let f={configurationVersion:r,avcProfileIndication:i,profileCompatibility:a,avcLevelIndication:o,lengthSizeMinusOne:s,sequenceParameterSets:l,pictureParameterSets:d,chromaFormat:null,bitDepthLumaMinus8:null,bitDepthChromaMinus8:null,sequenceParameterSetExt:null};if((i===100||i===110||i===122||i===144)&&n+4<=e.length){let r=t.getUint8(n++)&3,i=t.getUint8(n++)&7,a=t.getUint8(n++)&7,o=t.getUint8(n++);f.chromaFormat=r,f.bitDepthLumaMinus8=i,f.bitDepthChromaMinus8=a;let s=[];for(let r=0;r<o;r++){let r=t.getUint16(n,!1);n+=2,s.push(e.subarray(n,n+r)),n+=r}f.sequenceParameterSetExt=s}return f}catch(e){return Fh._error(`Error deserializing AVC Decoder Configuration Record:`,e),null}},ug={1:{num:1,den:1},2:{num:12,den:11},3:{num:10,den:11},4:{num:16,den:11},5:{num:40,den:33},6:{num:24,den:11},7:{num:20,den:11},8:{num:32,den:11},9:{num:80,den:33},10:{num:18,den:11},11:{num:15,den:11},12:{num:64,den:33},13:{num:160,den:99},14:{num:4,den:3},15:{num:3,den:2},16:{num:2,den:1}},dg=e=>{try{let t=ag(e),n=new Vh(t);if(n.skipBits(1),n.skipBits(2),n.readBits(5)!==7)return null;let r=n.readAlignedByte(),i=n.readAlignedByte(),a=n.readAlignedByte();B(n);let o=1,s=0,c=0,l=0;if((r===100||r===110||r===122||r===244||r===44||r===83||r===86||r===118||r===128)&&(o=B(n),o===3&&(l=n.readBits(1)),s=B(n),c=B(n),n.skipBits(1),n.readBits(1))){for(let e=0;e<(o===3?12:8);e++)if(n.readBits(1)){let t=e<6?16:64,r=8,i=8;for(let e=0;e<t;e++){if(i!==0){let e=Pm(n);i=(r+e+256)%256}r=i===0?r:i}}}B(n);let u=B(n);if(u===0)B(n);else if(u===1){n.skipBits(1),Pm(n),Pm(n);let e=B(n);for(let t=0;t<e;t++)Pm(n)}B(n),n.skipBits(1);let d=B(n),f=B(n),p=16*(d+1),m=16*(f+1),h=p,g=m,_=n.readBits(1);if(_||n.skipBits(1),n.skipBits(1),n.readBits(1)){let e=B(n),t=B(n),r=B(n),i=B(n),a,s;if((l===0?o:0)===0)a=1,s=2-_;else{let e=o===3?1:2,t=o===1?2:1;a=e,s=t*(2-_)}h-=a*(e+t),g-=s*(r+i)}let v=2,y=2,b=2,x=0,S={num:1,den:1},C=null,w=null,T=null,E=null,D=n.pos;if(n.readBits(1)){if(n.readBits(1)){let e=n.readBits(8);if(e===255)S={num:n.readBits(16),den:n.readBits(16)};else{let t=ug[e];t&&(S=t)}}n.readBits(1)&&n.skipBits(1),n.readBits(1)&&(n.skipBits(3),x=n.readBits(1),n.readBits(1)&&(v=n.readBits(8),y=n.readBits(8),b=n.readBits(8))),n.readBits(1)&&(B(n),B(n)),n.readBits(1)&&(n.skipBits(32),n.skipBits(32),n.skipBits(1));let e=n.readBits(1);e&&fg(n);let t=n.readBits(1);t&&fg(n),(e||t)&&n.skipBits(1),n.skipBits(1),T=n.pos,E=n.readBits(1),E&&(n.skipBits(1),B(n),B(n),B(n),B(n),C=B(n),w=B(n))}if(C===null){z(w===null);let e=i&16;if((r===44||r===86||r===100||r===110||r===122||r===244)&&e)C=0,w=0;else{let e=d+1,t=f+1,n=(2-_)*t,r=p_.find(e=>e.level>=a)??jm(p_),i=Math.min(Math.floor(r.maxDpbMbs/(e*n)),16);C=i,w=i}}return z(w!==null),{emulationUnpreventedBytes:t,profileIdc:r,constraintFlags:i,levelIdc:a,frameMbsOnlyFlag:_,chromaFormatIdc:o,bitDepthLumaMinus8:s,bitDepthChromaMinus8:c,codedWidth:p,codedHeight:m,displayWidth:h,displayHeight:g,pixelAspectRatio:S,colourPrimaries:v,matrixCoefficients:b,transferCharacteristics:y,fullRangeFlag:x,numReorderFrames:C,maxDecFrameBuffering:w,vuiParametersFlagBitOffset:D,bitstreamRestrictionFlagBitOffset:T,bitstreamRestrictionFlag:E}}catch(e){return Fh._error(`Error parsing AVC SPS:`,e),null}},fg=e=>{let t=B(e);e.skipBits(4),e.skipBits(4);for(let n=0;n<=t;n++)B(e),B(e),e.skipBits(1);e.skipBits(5),e.skipBits(5),e.skipBits(5),e.skipBits(5)},pg=(e,t)=>t.description?ng(e,(Fm(t.description)[21]&3)+1):tg(e),mg=e=>e>>1&63,hg=e=>{try{let t=new Vh(ag(e));t.skipBits(16),t.readBits(4);let n=t.readBits(3),r=t.readBits(1),{general_profile_space:i,general_tier_flag:a,general_profile_idc:o,general_profile_compatibility_flags:s,general_constraint_indicator_flags:c,general_level_idc:l}=_g(t,n);B(t);let u=B(t),d=0;u===3&&(d=t.readBits(1));let f=B(t),p=B(t),m=f,h=p;if(t.readBits(1)){let e=B(t),n=B(t),r=B(t),i=B(t),a=1,o=1,s=d===0?u:0;s===1?(a=2,o=2):s===2&&(a=2,o=1),m-=(e+n)*a,h-=(r+i)*o}let g=B(t),_=B(t);B(t);let v=t.readBits(1)?0:n,y=0;for(let e=v;e<=n;e++)B(t),y=B(t),B(t);if(B(t),B(t),B(t),B(t),B(t),B(t),t.readBits(1)&&t.readBits(1)&&vg(t),t.skipBits(1),t.skipBits(1),t.readBits(1)&&(t.skipBits(4),t.skipBits(4),B(t),B(t),t.skipBits(1)),yg(t,B(t)),t.readBits(1)){let e=B(t);for(let n=0;n<e;n++)B(t),t.skipBits(1)}t.skipBits(1),t.skipBits(1);let b=2,x=2,S=2,C=0,w=0,T={num:1,den:1};if(t.readBits(1)){let e=xg(t,n);T=e.pixelAspectRatio,b=e.colourPrimaries,x=e.transferCharacteristics,S=e.matrixCoefficients,C=e.fullRangeFlag,w=e.minSpatialSegmentationIdc}return{displayWidth:m,displayHeight:h,pixelAspectRatio:T,colourPrimaries:b,transferCharacteristics:x,matrixCoefficients:S,fullRangeFlag:C,maxDecFrameBuffering:y+1,spsMaxSubLayersMinus1:n,spsTemporalIdNestingFlag:r,generalProfileSpace:i,generalTierFlag:a,generalProfileIdc:o,generalProfileCompatibilityFlags:s,generalConstraintIndicatorFlags:c,generalLevelIdc:l,chromaFormatIdc:u,bitDepthLumaMinus8:g,bitDepthChromaMinus8:_,minSpatialSegmentationIdc:w}}catch(e){return Fh._error(`Error parsing HEVC SPS:`,e),null}},gg=e=>{try{let t=[],n=[],r=[],i=[];for(let a of tg(e)){let o=e.subarray(a.offset,a.offset+a.length),s=mg(o[0]);s===eg.VPS_NUT?t.push(o):s===eg.SPS_NUT?n.push(o):s===eg.PPS_NUT?r.push(o):(s===eg.PREFIX_SEI_NUT||s===eg.SUFFIX_SEI_NUT)&&i.push(o)}if(n.length===0||r.length===0)return null;let a=hg(n[0]);if(!a)return null;let o=0;if(r.length>0){let e=r[0],t=new Vh(ag(e));t.skipBits(16),B(t),B(t),t.skipBits(1),t.skipBits(1),t.skipBits(3),t.skipBits(1),t.skipBits(1),B(t),B(t),Pm(t),t.skipBits(1),t.skipBits(1),t.readBits(1)&&B(t),Pm(t),Pm(t),t.skipBits(1),t.skipBits(1),t.skipBits(1),t.skipBits(1);let n=t.readBits(1),i=t.readBits(1);o=!n&&!i?0:n&&!i?2:!n&&i?3:0}let s=[...t.length?[{arrayCompleteness:1,nalUnitType:eg.VPS_NUT,nalUnits:t}]:[],...n.length?[{arrayCompleteness:1,nalUnitType:eg.SPS_NUT,nalUnits:n}]:[],...r.length?[{arrayCompleteness:1,nalUnitType:eg.PPS_NUT,nalUnits:r}]:[],...i.length?[{arrayCompleteness:1,nalUnitType:mg(i[0][0]),nalUnits:i}]:[]];return{configurationVersion:1,generalProfileSpace:a.generalProfileSpace,generalTierFlag:a.generalTierFlag,generalProfileIdc:a.generalProfileIdc,generalProfileCompatibilityFlags:a.generalProfileCompatibilityFlags,generalConstraintIndicatorFlags:a.generalConstraintIndicatorFlags,generalLevelIdc:a.generalLevelIdc,minSpatialSegmentationIdc:a.minSpatialSegmentationIdc,parallelismType:o,chromaFormatIdc:a.chromaFormatIdc,bitDepthLumaMinus8:a.bitDepthLumaMinus8,bitDepthChromaMinus8:a.bitDepthChromaMinus8,avgFrameRate:0,constantFrameRate:0,numTemporalLayers:a.spsMaxSubLayersMinus1+1,temporalIdNested:a.spsTemporalIdNestingFlag,lengthSizeMinusOne:3,arrays:s}}catch(e){return Fh._error(`Error building HEVC Decoder Configuration Record:`,e),null}},_g=(e,t)=>{let n=e.readBits(2),r=e.readBits(1),i=e.readBits(5),a=0;for(let t=0;t<32;t++)a=a<<1|e.readBits(1);let o=/* @__PURE__ */ new Uint8Array(6);for(let t=0;t<6;t++)o[t]=e.readBits(8);let s=e.readBits(8),c=[],l=[];for(let n=0;n<t;n++)c.push(e.readBits(1)),l.push(e.readBits(1));if(t>0)for(let n=t;n<8;n++)e.skipBits(2);for(let n=0;n<t;n++)c[n]&&e.skipBits(88),l[n]&&e.skipBits(8);return{general_profile_space:n,general_tier_flag:r,general_profile_idc:i,general_profile_compatibility_flags:a,general_constraint_indicator_flags:o,general_level_idc:s}},vg=e=>{for(let t=0;t<4;t++)for(let n=0;n<(t===3?2:6);n++)if(!e.readBits(1))B(e);else{let n=Math.min(64,1<<4+(t<<1));t>1&&Pm(e);for(let t=0;t<n;t++)Pm(e)}},yg=(e,t)=>{let n=[];for(let r=0;r<t;r++)n[r]=bg(e,r,t,n)},bg=(e,t,n,r)=>{let i=0,a=0,o=0;if(t!==0&&(a=e.readBits(1)),a){o=t===n?t-(B(e)+1):t-1,e.readBits(1),B(e);let a=r[o]??0;for(let t=0;t<=a;t++)e.readBits(1)||e.readBits(1);i=r[o]}else{let t=B(e),n=B(e);for(let n=0;n<t;n++)B(e),e.readBits(1);for(let t=0;t<n;t++)B(e),e.readBits(1);i=t+n}return i},xg=(e,t)=>{let n=2,r=2,i=2,a=0,o=0,s={num:1,den:1};if(e.readBits(1)){let t=e.readBits(8);if(t===255)s={num:e.readBits(16),den:e.readBits(16)};else{let e=ug[t];e&&(s=e)}}return e.readBits(1)&&e.readBits(1),e.readBits(1)&&(e.readBits(3),a=e.readBits(1),e.readBits(1)&&(n=e.readBits(8),r=e.readBits(8),i=e.readBits(8))),e.readBits(1)&&(B(e),B(e)),e.readBits(1),e.readBits(1),e.readBits(1),e.readBits(1)&&(B(e),B(e),B(e),B(e)),e.readBits(1)&&(e.readBits(32),e.readBits(32),e.readBits(1)&&B(e),e.readBits(1)&&Sg(e,!0,t)),e.readBits(1)&&(e.readBits(1),e.readBits(1),e.readBits(1),o=B(e),B(e),B(e),B(e),B(e)),{pixelAspectRatio:s,colourPrimaries:n,transferCharacteristics:r,matrixCoefficients:i,fullRangeFlag:a,minSpatialSegmentationIdc:o}},Sg=(e,t,n)=>{let r=!1,i=!1,a=!1;t&&(r=e.readBits(1)===1,i=e.readBits(1)===1,(r||i)&&(a=e.readBits(1)===1,a&&(e.readBits(8),e.readBits(5),e.readBits(1),e.readBits(5)),e.readBits(4),e.readBits(4),a&&e.readBits(4),e.readBits(5),e.readBits(5),e.readBits(5)));for(let t=0;t<=n;t++){let t=e.readBits(1)===1,n=!0;t||(n=e.readBits(1)===1);let o=!1;n?B(e):o=e.readBits(1)===1;let s=1;o||(s=B(e)+1),r&&Cg(e,s,a),i&&Cg(e,s,a)}},Cg=(e,t,n)=>{for(let r=0;r<t;r++)B(e),B(e),n&&(B(e),B(e)),e.readBits(1)},wg=e=>{let t=[];t.push(e.configurationVersion),t.push((e.generalProfileSpace&3)<<6|(e.generalTierFlag&1)<<5|e.generalProfileIdc&31),t.push(e.generalProfileCompatibilityFlags>>>24&255),t.push(e.generalProfileCompatibilityFlags>>>16&255),t.push(e.generalProfileCompatibilityFlags>>>8&255),t.push(e.generalProfileCompatibilityFlags&255),t.push(...e.generalConstraintIndicatorFlags),t.push(e.generalLevelIdc&255),t.push(240|e.minSpatialSegmentationIdc>>8&15),t.push(e.minSpatialSegmentationIdc&255),t.push(252|e.parallelismType&3),t.push(252|e.chromaFormatIdc&3),t.push(248|e.bitDepthLumaMinus8&7),t.push(248|e.bitDepthChromaMinus8&7),t.push(e.avgFrameRate>>8&255),t.push(e.avgFrameRate&255),t.push((e.constantFrameRate&3)<<6|(e.numTemporalLayers&7)<<3|(e.temporalIdNested&1)<<2|e.lengthSizeMinusOne&3),t.push(e.arrays.length&255);for(let n of e.arrays){t.push((n.arrayCompleteness&1)<<7|0|n.nalUnitType&63),t.push(n.nalUnits.length>>8&255),t.push(n.nalUnits.length&255);for(let e of n.nalUnits){t.push(e.length>>8&255),t.push(e.length&255);for(let n=0;n<e.length;n++)t.push(e[n])}}return new Uint8Array(t)},Tg=e=>{try{let t=Im(e),n=0,r=t.getUint8(n++),i=t.getUint8(n++),a=i>>6&3,o=i>>5&1,s=i&31,c=t.getUint32(n,!1);n+=4;let l=e.subarray(n,n+6);n+=6;let u=t.getUint8(n++),d=(t.getUint8(n++)&15)<<8|t.getUint8(n++),f=t.getUint8(n++)&3,p=t.getUint8(n++)&3,m=t.getUint8(n++)&7,h=t.getUint8(n++)&7,g=t.getUint16(n,!1);n+=2;let _=t.getUint8(n++),v=_>>6&3,y=_>>3&7,b=_>>2&1,x=_&3,S=t.getUint8(n++),C=[];for(let r=0;r<S;r++){let r=t.getUint8(n++),i=r>>7&1,a=r&63,o=t.getUint16(n,!1);n+=2;let s=[];for(let r=0;r<o;r++){let r=t.getUint16(n,!1);n+=2,s.push(e.subarray(n,n+r)),n+=r}C.push({arrayCompleteness:i,nalUnitType:a,nalUnits:s})}return{configurationVersion:r,generalProfileSpace:a,generalTierFlag:o,generalProfileIdc:s,generalProfileCompatibilityFlags:c,generalConstraintIndicatorFlags:l,generalLevelIdc:u,minSpatialSegmentationIdc:d,parallelismType:f,chromaFormatIdc:p,bitDepthLumaMinus8:m,bitDepthChromaMinus8:h,avgFrameRate:g,constantFrameRate:v,numTemporalLayers:y,temporalIdNested:b,lengthSizeMinusOne:x,arrays:C}}catch(e){return Fh._error(`Error deserializing HEVC Decoder Configuration Record:`,e),null}},Eg;(function(e){e[e.audAllowed=0]=`audAllowed`,e[e.beforeFirstVcl=1]=`beforeFirstVcl`,e[e.afterFirstVcl=2]=`afterFirstVcl`,e[e.eoBitstreamAllowed=3]=`eoBitstreamAllowed`,e[e.noMoreDataAllowed=4]=`noMoreDataAllowed`})(Eg||={});var Dg={1:{colourPrimaries:5,transferCharacteristics:6,matrixCoefficients:5},2:{colourPrimaries:1,transferCharacteristics:1,matrixCoefficients:1},3:{colourPrimaries:6,transferCharacteristics:6,matrixCoefficients:6},4:{colourPrimaries:7,transferCharacteristics:7,matrixCoefficients:7},5:{colourPrimaries:9,transferCharacteristics:14,matrixCoefficients:9},7:{colourPrimaries:1,transferCharacteristics:13,matrixCoefficients:0}},Og=e=>{let t=new Vh(e);if(t.readBits(2)!==2)return null;let n=t.readBits(1),r=(t.readBits(1)<<1)+n;if(r===3&&t.skipBits(1),t.readBits(1)===1||t.readBits(1)!==0||(t.skipBits(2),t.readBits(24)!==4817730))return null;let i=8;r>=2&&(i=t.readBits(1)?12:10);let a=t.readBits(3),o=0,s=0;if(a!==7){if(s=t.readBits(1),r===1||r===3){let e=t.readBits(1),n=t.readBits(1);o=!e&&!n?3:e&&!n?2:1,t.skipBits(1)}else o=1}else o=3,s=1;let c=t.readBits(16),l=t.readBits(16),u=(c+1)*(l+1),d=jm(m_).level;for(let e of m_)if(u<=e.maxPictureSize){d=e.level;break}let f=Dg[a],p=f?.colourPrimaries??2,m=f?.transferCharacteristics??2,h=f?.matrixCoefficients??2;return{profile:r,level:d,bitDepth:i,chromaSubsampling:o,videoFullRangeFlag:s,colourPrimaries:p,transferCharacteristics:m,matrixCoefficients:h}},kg=e=>e.colourPrimaries!==2||e.transferCharacteristics!==2||e.matrixCoefficients!==2,Ag=function*(e){let t=new Vh(e),n=()=>{let e=0;for(let n=0;n<8;n++){let r=t.readAlignedByte();if(e+=(r&127)*2**(n*7),!(r&128))break;if(n===7&&r&128)return null}return e>2**32-1?null:e};for(;t.getBitsLeft()>=8;){t.skipBits(1);let r=t.readBits(4),i=t.readBits(1),a=t.readBits(1);t.skipBits(1),i&&t.skipBits(8);let o;if(a){let e=n();if(e===null)return;o=e}else o=Math.floor(t.getBitsLeft()/8);z(t.pos%8==0),yield{type:r,data:e.subarray(t.pos/8,t.pos/8+o)},t.skipBits(o*8)}},jg=e=>{for(let{type:t,data:n}of Ag(e)){if(t!==1)continue;let e=new Vh(n),r=e.readBits(3);e.readBits(1);let i=e.readBits(1),a=0,o=0,s=0;if(i)a=e.readBits(5);else{let t=e.readBits(1),n=0;if(t){if(e.skipBits(32),e.skipBits(32),e.readBits(1)){let t=0;for(;t<32&&!e.readBits(1);)t++;t<32&&e.skipBits(t)}n=e.readBits(1),n&&(s=e.readBits(5),e.skipBits(32),e.skipBits(5),e.skipBits(5))}let r=e.readBits(1),i=e.readBits(5);for(let t=0;t<=i;t++){e.skipBits(12);let i=e.readBits(5);if(t===0&&(a=i),i>7){let n=e.readBits(1);t===0&&(o=n)}if(n&&e.readBits(1)){let t=s+1;e.skipBits(t),e.skipBits(t),e.skipBits(1)}r&&e.readBits(1)&&e.skipBits(4)}}let c=e.readBits(4),l=e.readBits(4),u=c+1;e.skipBits(u);let d=l+1;e.skipBits(d);let f=0;if(f=i?0:e.readBits(1),f&&(e.skipBits(4),e.skipBits(3)),e.skipBits(1),e.skipBits(1),e.skipBits(1),!i){e.skipBits(1),e.skipBits(1),e.skipBits(1),e.skipBits(1);let t=e.readBits(1);t&&(e.skipBits(1),e.skipBits(1));let n=e.readBits(1),r=0;r=n?2:e.readBits(1),r>0&&(e.readBits(1)||e.skipBits(1)),t&&e.skipBits(3)}e.skipBits(1),e.skipBits(1),e.skipBits(1);let p=e.readBits(1),m=8;r===2&&p?m=e.readBits(1)?12:10:r<=2&&(m=p?10:8);let h=0;r!==1&&(h=e.readBits(1));let g=2,_=2,v=2;e.readBits(1)&&(g=e.readBits(8),_=e.readBits(8),v=e.readBits(8));let y=0,b=1,x=1,S=0;return h?y=e.readBits(1):g===1&&_===13&&v===0?(y=1,b=0,x=0):(y=e.readBits(1),r===0?(b=1,x=1):r===1?(b=0,x=0):m===12?(b=e.readBits(1),x=b?e.readBits(1):0):(b=1,x=0),b&&x&&(S=e.readBits(2))),{profile:r,level:a,tier:o,bitDepth:m,monochrome:h,chromaSubsamplingX:b,chromaSubsamplingY:x,chromaSamplePosition:S,videoFullRangeFlag:y,colourPrimaries:g,transferCharacteristics:_,matrixCoefficients:v}}return null},Mg=e=>e.colourPrimaries!==2||e.transferCharacteristics!==2||e.matrixCoefficients!==2,Ng=e=>{if(e.length<36)return null;let t=Im(e);return t.getUint32(4)!==1768124518||t.getUint16(8)<28?null:{fullRange:!1,colourPrimaries:t.getUint8(22),transferCharacteristics:t.getUint8(23),matrixCoefficients:t.getUint8(24)}},Pg=e=>{let t=Im(e),n=t.getUint8(9),r=t.getUint16(10,!0),i=t.getUint32(12,!0),a=t.getInt16(16,!0),o=t.getUint8(18),s=null;return o&&(s=e.subarray(19,21+n)),{outputChannelCount:n,preSkip:r,inputSampleRate:i,outputGain:a,channelMappingFamily:o,channelMappingTable:s}},Fg=(e,t,n)=>{switch(e){case`avc`:for(let e of rg(n,t)){let t=n[e.offset],r=ig(t);if(r>=$h.NON_IDR_SLICE&&r<=$h.SLICE_DPC)return`delta`;if(r===$h.IDR)return`key`;if(r===$h.SEI&&!xh()){let t=ag(n.subarray(e.offset,e.offset+e.length)),r=1;do{let e=0;for(;;){let n=t[r++];if(n===void 0||(e+=n,n<255))break}let n=0;for(;;){let e=t[r++];if(e===void 0||(n+=e,e<255))break}if(e===6){let e=new Vh(t);e.pos=8*r;let n=B(e),i=e.readBits(1);if(n===0&&i===1)return`key`}r+=n}while(r<t.length-1)}}return`delta`;case`hevc`:for(let e of pg(n,t)){let t=mg(n[e.offset]);if(t<eg.BLA_W_LP)return`delta`;if(t<=eg.RSV_IRAP_VCL23)return`key`}return`delta`;case`vp8`:return n[0]&1?`delta`:`key`;case`vp9`:{let e=new Vh(n);if(e.readBits(2)!==2)return null;let t=e.readBits(1);return(e.readBits(1)<<1)+t===3&&e.skipBits(1),e.readBits(1)?null:e.readBits(1)===0?`key`:`delta`}case`av1`:{let e=!1;for(let{type:t,data:r}of Ag(n))if(t===1){let t=new Vh(r);t.skipBits(4),e=!!t.readBits(1)}else if(t===3||t===6||t===7){if(e)return`key`;let t=new Vh(r);return t.readBits(1)?null:t.readBits(2)===0?`key`:`delta`}return null}case`prores`:return`key`;default:ch(e),z(!1)}},Ig;(function(e){e[e.STREAMINFO=0]=`STREAMINFO`,e[e.VORBIS_COMMENT=4]=`VORBIS_COMMENT`,e[e.PICTURE=6]=`PICTURE`})(Ig||={});var Lg=[2,1,2,3,3,4,4,5],Rg=e=>{if(e.length<7||e[0]!==11||e[1]!==119)return null;let t=new Vh(e);t.skipBits(16),t.skipBits(16);let n=t.readBits(2);if(n===3)return null;let r=t.readBits(6),i=t.readBits(5);if(i>8)return null;let a=t.readBits(3),o=t.readBits(3);return o&1&&o!==1&&t.skipBits(2),o&4&&t.skipBits(2),o===2&&t.skipBits(2),{fscod:n,bsid:i,bsmod:a,acmod:o,lfeon:t.readBits(1),bitRateCode:Math.floor(r/2)}};new Uint8Array([5,4,65,67,45,51]),new Uint8Array([5,4,69,65,67,51]);var zg=[1,2,3,6],Bg=e=>{if(e.length<6||e[0]!==11||e[1]!==119)return null;let t=new Vh(e);t.skipBits(16);let n=t.readBits(2);if(t.skipBits(3),n!==0&&n!==2)return null;let r=t.readBits(11),i=t.readBits(2),a=0,o;i===3?(a=t.readBits(2),o=3):o=t.readBits(2);let s=t.readBits(3),c=t.readBits(1),l=t.readBits(5);if(l<11||l>16)return null;let u=zg[o],d;return d=i<3?Zh[i]/1e3:Qh[a]/1e3,{dataRate:Math.round((r+1)*d/(u*16)),substreams:[{fscod:i,fscod2:a,bsid:l,bsmod:0,acmod:s,lfeon:c,numDepSub:0,chanLoc:0}]}},Vg=e=>{if(e.length<2)return null;let t=new Vh(e),n=t.readBits(13),r=t.readBits(3),i=[];for(let n=0;n<=r&&!(Math.ceil(t.pos/8)+3>e.length);n++){let e=t.readBits(2),n=t.readBits(5);t.skipBits(1),t.skipBits(1);let r=t.readBits(3),a=t.readBits(3),o=t.readBits(1);t.skipBits(3);let s=t.readBits(4),c=0;s>0?c=t.readBits(9):t.skipBits(1),i.push({fscod:e,fscod2:null,bsid:n,bsmod:r,acmod:a,lfeon:o,numDepSub:s,chanLoc:c})}return i.length===0?null:{dataRate:n,substreams:i}},Hg=e=>{let t=e.substreams[0];return z(t),t.fscod<3?Zh[t.fscod]:t.fscod2!==null&&t.fscod2<3?Qh[t.fscod2]:null},Ug=e=>{let t=e.substreams[0];z(t);let n=Lg[t.acmod]+t.lfeon;if(t.numDepSub>0){let e=[2,2,1,1,2,2,2,1,1];for(let r=0;r<9;r++)t.chanLoc&1<<8-r&&(n+=e[r])}return n},Wg=8,Gg=[0,8e3,16e3,32e3,0,0,11025,22050,44100,0,0,12e3,24e3,48e3,96e3,192e3],Kg=[32e3,56e3,64e3,96e3,112e3,128e3,192e3,224e3,256e3,32e4,384e3,448e3,512e3,576e3,64e4,768e3,96e4,1024e3,1152e3,128e4,1344e3,1408e3,1411200,1472e3,1536e3,192e4,2048e3,3072e3,384e4,0,0,0],qg=[16,16,20,20,0,24,24,0],Jg=[1,2,2,2,2,3,3,4,4,5,6,6,6,7,8,8],Yg=[1,2,2,2,2,3,18,19,6,7,518,323,83,519,582,535],Xg=8,Zg=44646,Qg=[32e3,44100,48e3,0],$g=[8e3,16e3,32e3,64e3,128e3,22050,44100,88200,176400,352800,12e3,24e3,48e3,96e3,192e3,384e3],e_=[512,1024,2048,4096],t_=e=>{let t=r_(e),n=Im(e),r=t?Math.ceil(t.frameSize/4)*4:0,i=null;for(;r+4<=e.length&&n.getUint32(r)===1683496997;){let t=i_(e.subarray(r));if(!t)break;i??=t,r+=t.frameSize}if(t)return{frameSize:i?r:t.frameSize,sampleRate:t.sampleRate,numberOfChannels:t.numberOfChannels,sampleCount:t.sampleCount,channelLayout:t.channelLayout,pcmResolution:t.pcmResolution,bitRate:t.bitRate,core:t,hasExtensions:i!==null};if(!i?.asset)return null;let{asset:a}=i;return{frameSize:r,sampleRate:a.sampleRate,numberOfChannels:a.numberOfChannels,sampleCount:a.sampleCount,channelLayout:a.channelLayout,pcmResolution:a.pcmResolution,bitRate:0,core:null,hasExtensions:!0}},n_=e=>{let t=t_(e);return t?.core?t.hasExtensions?`dtsh`:`dtsc`:null},r_=e=>{if(e.length<18||e[0]!==127||e[1]!==254||e[2]!==128||e[3]!==1)return null;let t=new Vh(e);if(t.skipBits(32),t.skipBits(1),t.readBits(5)!==31)return null;let n=t.readBits(1),r=t.readBits(7)+1;if(r%Wg!==0)return null;let i=t.readBits(14)+1;if(i<96)return null;let a=t.readBits(6);if(a>=Jg.length)return null;let o=Gg[t.readBits(4)];if(o===0)return null;let s=Kg[t.readBits(5)];if(t.readBits(1)!==0)return null;t.skipBits(4),t.skipBits(5);let c=t.readBits(2);if(c===3)return null;t.skipBits(1),n&&t.skipBits(16),t.skipBits(7);let l=qg[t.readBits(3)];if(l===0)return null;let u=c!==0;return{frameSize:i,sampleRate:o,numberOfChannels:Jg[a]+ +!!u,sampleCount:r*32,channelLayout:Yg[a]|(u?Xg:0),amode:a,lfePresent:u,bitRate:s,pcmResolution:l}},i_=e=>{if(e.length<10||e[0]!==100||e[1]!==88||e[2]!==32||e[3]!==37)return null;let t=new Vh(e);t.skipBits(32),t.skipBits(8);let n=t.readBits(2),r=t.readBits(1),i=8+4*r,a=16+4*r;t.skipBits(i);let o=t.readBits(a)+1,s={frameSize:o,asset:null};if(!t.readBits(1))return s;let c=Qg[t.readBits(2)],l=512*(t.readBits(3)+1);t.readBits(1)&&t.skipBits(36);let u=t.readBits(3)+1,d=t.readBits(3)+1,f=[];for(let e=0;e<u;e++)f.push(t.readBits(n+1));for(let e of f)t.skipBits(8*hh(e));if(t.readBits(1)){t.skipBits(2);let e=t.readBits(2)+1<<2,n=t.readBits(2)+1;t.skipBits(n*e)}for(let e=0;e<d;e++)t.skipBits(a);t.skipBits(9),t.skipBits(3),t.readBits(1)&&t.skipBits(4),t.readBits(1)&&t.skipBits(24),t.readBits(1)&&t.skipBits(8*(t.readBits(10)+1));let p=t.readBits(5)+1,m=$g[t.readBits(4)],h=t.readBits(8)+1,g=0;if(t.readBits(1)&&(h>2&&t.skipBits(1),h>6&&t.skipBits(1),t.readBits(1))){let e=t.readBits(2)+1<<2;g=t.readBits(e)}return c===0||t.getBitsLeft()<0?s:{frameSize:o,asset:{sampleRate:m,numberOfChannels:h,sampleCount:Math.round(l*m/c),channelLayout:g,pcmResolution:p}}},a_=e=>{if(e.length<20)return null;let t=Im(e),n=t.getUint32(0);if(n===0)return null;let r=new Vh(e);r.seekToByte(13);let i=r.readBits(2);r.skipBits(5);let a=r.readBits(1),o=r.readBits(6);r.skipBits(14),r.skipBits(1),r.skipBits(3);let s=r.readBits(16),c=null;return s===0?o<Jg.length&&(c=Jg[o]+a):c=s_(s),{sampleRate:n,maxBitrate:t.getUint32(4),avgBitrate:t.getUint32(8),pcmSampleDepth:e[12],sampleCount:e_[i],channelLayout:s,numberOfChannels:c}},o_=e=>{let t=/* @__PURE__ */ new Uint8Array(20),n=Im(t);n.setUint32(0,e.sampleRate),n.setUint32(4,e.bitRate),n.setUint32(8,e.bitRate),t[12]=e.pcmResolution;let r=e.core&&!e.hasExtensions?1:0,i=new Vh(t);return i.seekToByte(13),i.writeBits(2,Math.max(e_.indexOf(e.sampleCount),0)),i.writeBits(5,r),i.writeBits(1,+!!e.core?.lfePresent),i.writeBits(6,e.core?.amode??0),i.writeBits(14,e.core?e.core.frameSize-1:0),i.writeBits(1,0),i.writeBits(3,0),i.writeBits(16,e.channelLayout),i.writeBits(1,0),i.writeBits(1,0),i.writeBits(1,0),i.writeBits(5,0),t},s_=e=>hh(e)+hh(e&Zg),c_=[`avc`,`hevc`,`vp9`,`av1`,`vp8`,`prores`],l_=[`pcm-s16`,`pcm-s16be`,`pcm-s24`,`pcm-s24be`,`pcm-s32`,`pcm-s32be`,`pcm-f32`,`pcm-f32be`,`pcm-f64`,`pcm-f64be`,`pcm-u8`,`pcm-s8`,`ulaw`,`alaw`],u_=[`aac`,`opus`,`mp3`,`vorbis`,`flac`,`ac3`,`eac3`,`dts`],d_=[...u_,...l_],f_=[`webvtt`],p_=[{maxMacroblocks:99,maxBitrate:64e3,maxDpbMbs:396,level:10},{maxMacroblocks:396,maxBitrate:192e3,maxDpbMbs:900,level:11},{maxMacroblocks:396,maxBitrate:384e3,maxDpbMbs:2376,level:12},{maxMacroblocks:396,maxBitrate:768e3,maxDpbMbs:2376,level:13},{maxMacroblocks:396,maxBitrate:2e6,maxDpbMbs:2376,level:20},{maxMacroblocks:792,maxBitrate:4e6,maxDpbMbs:4752,level:21},{maxMacroblocks:1620,maxBitrate:4e6,maxDpbMbs:8100,level:22},{maxMacroblocks:1620,maxBitrate:1e7,maxDpbMbs:8100,level:30},{maxMacroblocks:3600,maxBitrate:14e6,maxDpbMbs:18e3,level:31},{maxMacroblocks:5120,maxBitrate:2e7,maxDpbMbs:20480,level:32},{maxMacroblocks:8192,maxBitrate:2e7,maxDpbMbs:32768,level:40},{maxMacroblocks:8192,maxBitrate:5e7,maxDpbMbs:32768,level:41},{maxMacroblocks:8704,maxBitrate:5e7,maxDpbMbs:34816,level:42},{maxMacroblocks:22080,maxBitrate:135e6,maxDpbMbs:110400,level:50},{maxMacroblocks:36864,maxBitrate:24e7,maxDpbMbs:184320,level:51},{maxMacroblocks:36864,maxBitrate:24e7,maxDpbMbs:184320,level:52},{maxMacroblocks:139264,maxBitrate:24e7,maxDpbMbs:696320,level:60},{maxMacroblocks:139264,maxBitrate:48e7,maxDpbMbs:696320,level:61},{maxMacroblocks:139264,maxBitrate:8e8,maxDpbMbs:696320,level:62}],m_=[{maxPictureSize:36864,maxBitrate:2e5,level:10},{maxPictureSize:73728,maxBitrate:8e5,level:11},{maxPictureSize:122880,maxBitrate:18e5,level:20},{maxPictureSize:245760,maxBitrate:36e5,level:21},{maxPictureSize:552960,maxBitrate:72e5,level:30},{maxPictureSize:983040,maxBitrate:12e6,level:31},{maxPictureSize:2228224,maxBitrate:18e6,level:40},{maxPictureSize:2228224,maxBitrate:3e7,level:41},{maxPictureSize:8912896,maxBitrate:6e7,level:50},{maxPictureSize:8912896,maxBitrate:12e7,level:51},{maxPictureSize:8912896,maxBitrate:18e7,level:52},{maxPictureSize:35651584,maxBitrate:18e7,level:60},{maxPictureSize:35651584,maxBitrate:24e7,level:61},{maxPictureSize:35651584,maxBitrate:48e7,level:62}],h_=`.01.01.01.01.00`,g_=`.0.110.01.01.01.0`,__=[`ap4x`,`ap4h`,`apch`,`apcn`,`apcs`,`apco`],v_=[`dtsc`,`dtsh`,`dtsl`,`dtse`],y_=e=>{let t=e.split(`.`),n=Number(t[1]),r=t[2],i=Number(r.slice(0,-1)),a=(n<<5)+i,o=+(r.slice(-1)===`H`),s=Number(t[3]),c=s===8?0:1,l=+(s===12),u=t[4]?Number(t[4]):0,d=t[5]?Number(t[5][0]):1,f=t[5]?Number(t[5][1]):1,p=t[5]?Number(t[5][2]):0;return[129,a,(o<<7)+(c<<6)+(l<<5)+(u<<4)+(d<<3)+(f<<2)+p,0]},b_=e=>{let{codec:t,codecDescription:n,colorSpace:r,avcCodecInfo:i,hevcCodecInfo:a,vp9CodecInfo:o,av1CodecInfo:s,proresFormat:c}=e;if(t===`avc`){if(z(e.avcType!==null),i){let t=new Uint8Array([i.avcProfileIndication,i.profileCompatibility,i.avcLevelIndication]);return`avc${e.avcType}.${eh(t)}`}if(!n||n.byteLength<4)throw TypeError(`AVC decoder description is not provided or is not at least 4 bytes long.`);return`avc${e.avcType}.${eh(n.subarray(1,4))}`}if(t===`hevc`){let e,t,r,i,o,s;if(a)e=a.generalProfileSpace,t=a.generalProfileIdc,r=nh(a.generalProfileCompatibilityFlags),i=a.generalTierFlag,o=a.generalLevelIdc,s=[...a.generalConstraintIndicatorFlags];else{if(!n||n.byteLength<23)throw TypeError(`HEVC decoder description is not provided or is not at least 23 bytes long.`);let a=Im(n),c=a.getUint8(1);e=c>>6&3,t=c&31,r=nh(a.getUint32(2)),i=c>>5&1,o=a.getUint8(12),s=[];for(let e=0;e<6;e++)s.push(a.getUint8(6+e))}let c=`hev1.`;for(c+=[``,`A`,`B`,`C`][e]+t,c+=`.`,c+=r.toString(16).toUpperCase(),c+=`.`,c+=i===0?`L`:`H`,c+=o;s.length>0&&s[s.length-1]===0;)s.pop();return s.length>0&&(c+=`.`,c+=s.map(e=>e.toString(16).toUpperCase()).join(`.`)),c}if(t===`vp8`)return`vp8`;if(t===`vp9`){if(!o){let t=e.width*e.height,n=jm(m_).level;for(let e of m_)if(t<=e.maxPictureSize){n=e.level;break}return`vp09.00.${n.toString().padStart(2,`0`)}.08`}let t=o.profile.toString().padStart(2,`0`),n=o.level.toString().padStart(2,`0`),r=o.bitDepth.toString().padStart(2,`0`),i=o.chromaSubsampling.toString().padStart(2,`0`),a=o.colourPrimaries.toString().padStart(2,`0`),s=o.transferCharacteristics.toString().padStart(2,`0`),c=o.matrixCoefficients.toString().padStart(2,`0`),l=o.videoFullRangeFlag.toString().padStart(2,`0`),u=`vp09.${t}.${n}.${r}.${i}`;return u+=`.${a}.${s}.${c}.${l}`,u.endsWith(h_)&&(u=u.slice(0,-15)),u}if(t===`av1`){if(!s){let t=e.width*e.height,n=jm(m_).level;for(let e of m_)if(t<=e.maxPictureSize){n=e.level;break}return`av01.0.${n.toString().padStart(2,`0`)}M.08`}let t=s.profile,n=s.level.toString().padStart(2,`0`),i=s.tier?`H`:`M`,a=s.bitDepth.toString().padStart(2,`0`),o=s.monochrome?`1`:`0`,c=100*s.chromaSubsamplingX+10*s.chromaSubsamplingY+1*(s.chromaSubsamplingX&&s.chromaSubsamplingY?s.chromaSamplePosition:0),l=r?.primaries?Hm[r.primaries]:1,u=r?.transfer?Wm[r.transfer]:1,d=r?.matrix?Km[r.matrix]:1,f=+!!r?.fullRange,p=`av01.${t}.${n}${i}.${a}`;return p+=`.${o}.${c.toString().padStart(3,`0`)}`,p+=`.${l.toString().padStart(2,`0`)}`,p+=`.${u.toString().padStart(2,`0`)}`,p+=`.${d.toString().padStart(2,`0`)}`,p+=`.${f}`,p.endsWith(g_)&&(p=p.slice(0,-17)),p}if(t===`prores`)return c??`apch`;throw t!==null&&ch(t),TypeError(`Unhandled codec '${t}'.`)},x_=e=>{switch(e.codec){case`avc`:{let t=e.avcCodecInfo?.sequenceParameterSets[0];if(!t&&e.codecDescription&&(t=lg(e.codecDescription)?.sequenceParameterSets[0]),t){let e=dg(t);if(e)return{primaries:Um[e.colourPrimaries],transfer:Gm[e.transferCharacteristics],matrix:qm[e.matrixCoefficients],fullRange:!!e.fullRangeFlag}}}break;case`hevc`:{let t=e.hevcCodecInfo?.arrays.find(e=>e.nalUnitType===eg.SPS_NUT)?.nalUnits[0];if(!t&&e.codecDescription&&(t=Tg(e.codecDescription)?.arrays.find(e=>e.nalUnitType===eg.SPS_NUT)?.nalUnits[0]),t){let e=hg(t);if(e)return{primaries:Um[e.colourPrimaries],transfer:Gm[e.transferCharacteristics],matrix:qm[e.matrixCoefficients],fullRange:!!e.fullRangeFlag}}}break;case`vp8`:break;case`vp9`:if(e.vp9CodecInfo)return{primaries:Um[e.vp9CodecInfo.colourPrimaries],transfer:Gm[e.vp9CodecInfo.transferCharacteristics],matrix:qm[e.vp9CodecInfo.matrixCoefficients],fullRange:!!e.vp9CodecInfo.videoFullRangeFlag};break;case`av1`:if(e.av1CodecInfo)return{primaries:Um[e.av1CodecInfo.colourPrimaries],transfer:Gm[e.av1CodecInfo.transferCharacteristics],matrix:qm[e.av1CodecInfo.matrixCoefficients],fullRange:!!e.av1CodecInfo.videoFullRangeFlag};break;case`prores`:if(e.proresCodecInfo)return{primaries:Um[e.proresCodecInfo.colourPrimaries],transfer:Gm[e.proresCodecInfo.transferCharacteristics],matrix:qm[e.proresCodecInfo.matrixCoefficients],fullRange:e.proresCodecInfo.fullRange}}return{primaries:void 0,transfer:void 0,matrix:void 0,fullRange:void 0}},S_=e=>{let{codec:t,codecDescription:n,aacCodecInfo:r,dtsFormat:i}=e;if(t===`aac`){if(!r)throw TypeError(`AAC codec info must be provided.`);if(r.isMpeg2)return`mp4a.67`;{let e;return e=r.objectType===null?Wh(n).objectType:r.objectType,`mp4a.40.${e}`}}if(t===`mp3`)return`mp3`;if(t===`opus`)return`opus`;if(t===`vorbis`)return`vorbis`;if(t===`flac`)return`flac`;if(t===`ac3`)return`ac-3`;if(t===`eac3`)return`ec-3`;if(t===`dts`)return i??`dtsc`;if(t&&l_.includes(t))return t;throw TypeError(`Unhandled codec '${t}'.`)},C_=48e3,w_=/^pcm-([usf])(\d+)(be)?$/,T_=e=>{if(z(l_.includes(e)),e===`ulaw`)return{dataType:`ulaw`,sampleSize:1,littleEndian:!0,silentValue:255};if(e===`alaw`)return{dataType:`alaw`,sampleSize:1,littleEndian:!0,silentValue:213};let t=w_.exec(e);z(t);let n;n=t[1]===`u`?`unsigned`:t[1]===`s`?`signed`:`float`;let r=Number(t[2])/8,i=t[3]!==`be`;return{dataType:n,sampleSize:r,littleEndian:i,silentValue:e===`pcm-u8`?128:0}},E_=e=>e.startsWith(`avc1`)||e.startsWith(`avc3`)?`avc`:e.startsWith(`hev1`)||e.startsWith(`hvc1`)?`hevc`:e===`vp8`?`vp8`:e.startsWith(`vp09`)?`vp9`:e.startsWith(`av01`)?`av1`:__.includes(e)?`prores`:e===`mp3`||e===`mp4a.69`||e===`mp4a.6B`||e===`mp4a.6b`||e===`mp4a.40.34`?`mp3`:e.startsWith(`mp4a.40.`)||e===`mp4a.67`?`aac`:e===`opus`?`opus`:e===`vorbis`?`vorbis`:e===`flac`?`flac`:e===`ac-3`||e===`ac3`?`ac3`:e===`ec-3`||e===`eac3`?`eac3`:v_.includes(e)?`dts`:e===`ulaw`?`ulaw`:e===`alaw`?`alaw`:w_.test(e)?e:e===`webvtt`?`webvtt`:null,D_=[`avc1`,`avc3`,`hev1`,`hvc1`,`vp8`,`vp09`,`av01`,...__],O_=/^(avc1|avc3)\.[0-9a-fA-F]{6}$/,k_=/^(hev1|hvc1)\.(?:[ABC]?\d+)\.[0-9a-fA-F]{1,8}\.[LH]\d+(?:\.[0-9a-fA-F]{1,2}){0,6}$/,A_=/^vp09(?:\.\d{2}){3}(?:(?:\.\d{2}){5})?$/,j_=/^av01\.\d\.\d{2}[MH]\.\d{2}(?:\.\d\.\d{3}\.\d{2}\.\d{2}\.\d{2}\.\d)?$/,M_=(e,t)=>{if(!e)throw TypeError(`Video chunk metadata must be provided.`);if(typeof e!=`object`)throw TypeError(`Video chunk metadata must be an object.`);if(!e.decoderConfig)throw TypeError(`Video chunk metadata must include a decoder configuration.`);if(typeof e.decoderConfig!=`object`)throw TypeError(`Video chunk metadata decoder configuration must be an object.`);if(typeof e.decoderConfig.codec!=`string`)throw TypeError(`Video chunk metadata decoder configuration must specify a codec string.`);if(!D_.some(t=>e.decoderConfig.codec.startsWith(t)))throw TypeError(`Video chunk metadata decoder configuration codec string must be a valid video codec string as specified in the Mediabunny Codec Registry.`);if(!Number.isInteger(e.decoderConfig.codedWidth)||e.decoderConfig.codedWidth<=0)throw TypeError(`Video chunk metadata decoder configuration must specify a valid codedWidth (positive integer).`);if(!Number.isInteger(e.decoderConfig.codedHeight)||e.decoderConfig.codedHeight<=0)throw TypeError(`Video chunk metadata decoder configuration must specify a valid codedHeight (positive integer).`);if(e.decoderConfig.displayAspectWidth!==void 0&&(!Number.isInteger(e.decoderConfig.displayAspectWidth)||e.decoderConfig.displayAspectWidth<=0))throw TypeError(`Video chunk metadata decoder configuration displayAspectWidth, when defined, must be a positive integer.`);if(e.decoderConfig.displayAspectHeight!==void 0&&(!Number.isInteger(e.decoderConfig.displayAspectHeight)||e.decoderConfig.displayAspectHeight<=0))throw TypeError(`Video chunk metadata decoder configuration displayAspectHeight, when defined, must be a positive integer.`);if(e.decoderConfig.displayAspectWidth!==void 0!=(e.decoderConfig.displayAspectHeight!==void 0))throw TypeError(`Video chunk metadata decoder configuration must specify both displayAspectWidth and displayAspectHeight, or neither.`);if(e.decoderConfig.description!==void 0&&!Zm(e.decoderConfig.description))throw TypeError(`Video chunk metadata decoder configuration description, when defined, must be an ArrayBuffer or an ArrayBuffer view.`);if(e.decoderConfig.colorSpace!==void 0){let{colorSpace:t}=e.decoderConfig;if(typeof t!=`object`)throw TypeError(`Video chunk metadata decoder configuration colorSpace, when provided, must be an object.`);let n=Object.keys(Hm);if(t.primaries!=null&&!n.includes(t.primaries))throw TypeError(`Video chunk metadata decoder configuration colorSpace primaries, when defined, must be one of ${n.join(`, `)}.`);let r=Object.keys(Wm);if(t.transfer!=null&&!r.includes(t.transfer))throw TypeError(`Video chunk metadata decoder configuration colorSpace transfer, when defined, must be one of ${r.join(`, `)}.`);let i=Object.keys(Km);if(t.matrix!=null&&!i.includes(t.matrix))throw TypeError(`Video chunk metadata decoder configuration colorSpace matrix, when defined, must be one of ${i.join(`, `)}.`);if(t.fullRange!=null&&typeof t.fullRange!=`boolean`)throw TypeError(`Video chunk metadata decoder configuration colorSpace fullRange, when defined, must be a boolean.`)}if(e.decoderConfig.codec.startsWith(`avc1`)||e.decoderConfig.codec.startsWith(`avc3`)){if(!O_.test(e.decoderConfig.codec))throw TypeError(`Video chunk metadata decoder configuration codec string for AVC must be a valid AVC codec string as specified in Section 3.4 of RFC 6381.`)}else if(e.decoderConfig.codec.startsWith(`hev1`)||e.decoderConfig.codec.startsWith(`hvc1`)){if(!k_.test(e.decoderConfig.codec))throw TypeError(`Video chunk metadata decoder configuration codec string for HEVC must be a valid HEVC codec string as specified in Section E.3 of ISO 14496-15.`)}else if(e.decoderConfig.codec.startsWith(`vp8`)){if(e.decoderConfig.codec!==`vp8`)throw TypeError(`Video chunk metadata decoder configuration codec string for VP8 must be "vp8".`)}else if(e.decoderConfig.codec.startsWith(`vp09`)){if(!A_.test(e.decoderConfig.codec))throw TypeError(`Video chunk metadata decoder configuration codec string for VP9 must be a valid VP9 codec string as specified in Section "Codecs Parameter String" of https://www.webmproject.org/vp9/mp4/.`)}else if(e.decoderConfig.codec.startsWith(`av01`)){if(!j_.test(e.decoderConfig.codec))throw TypeError(`Video chunk metadata decoder configuration codec string for AV1 must be a valid AV1 codec string as specified in Section "Codecs Parameter String" of https://aomediacodec.github.io/av1-isobmff/.`)}else if(__.some(t=>e.decoderConfig.codec.startsWith(t))&&!__.some(t=>e.decoderConfig.codec===t))throw TypeError(`Video chunk metadata decoder configuration codec string for ProRes must be one of the valid ProRes four-character codes: ${__.join(`, `)}.`);if(t!==null&&E_(e.decoderConfig.codec)!==t)throw TypeError(`Video chunk metadata decoder configuration codec string '${e.decoderConfig.codec}' does not fit to the track codec '${t}'.`)},N_=[`mp4a`,`mp3`,`opus`,`vorbis`,`flac`,`ulaw`,`alaw`,`pcm`,`ac-3`,`ec-3`,`dts`],P_=(e,t)=>{if(!e)throw TypeError(`Audio chunk metadata must be provided.`);if(typeof e!=`object`)throw TypeError(`Audio chunk metadata must be an object.`);if(!e.decoderConfig)throw TypeError(`Audio chunk metadata must include a decoder configuration.`);if(typeof e.decoderConfig!=`object`)throw TypeError(`Audio chunk metadata decoder configuration must be an object.`);if(typeof e.decoderConfig.codec!=`string`)throw TypeError(`Audio chunk metadata decoder configuration must specify a codec string.`);if(!N_.some(t=>e.decoderConfig.codec.startsWith(t)))throw TypeError(`Audio chunk metadata decoder configuration codec string must be a valid audio codec string as specified in the Mediabunny Codec Registry.`);if(!Number.isInteger(e.decoderConfig.sampleRate)||e.decoderConfig.sampleRate<=0)throw TypeError(`Audio chunk metadata decoder configuration must specify a valid sampleRate (positive integer).`);if(!Number.isInteger(e.decoderConfig.numberOfChannels)||e.decoderConfig.numberOfChannels<=0)throw TypeError(`Audio chunk metadata decoder configuration must specify a valid numberOfChannels (positive integer).`);if(e.decoderConfig.description!==void 0&&!Zm(e.decoderConfig.description))throw TypeError(`Audio chunk metadata decoder configuration description, when defined, must be an ArrayBuffer or an ArrayBuffer view.`);if(e.decoderConfig.codec.startsWith(`mp4a`)&&e.decoderConfig.codec!==`mp4a.69`&&e.decoderConfig.codec!==`mp4a.6B`&&e.decoderConfig.codec!==`mp4a.6b`){if(![`mp4a.40.2`,`mp4a.40.02`,`mp4a.40.5`,`mp4a.40.05`,`mp4a.40.29`,`mp4a.67`].includes(e.decoderConfig.codec))throw TypeError(`Audio chunk metadata decoder configuration codec string for AAC must be a valid AAC codec string as specified in https://www.w3.org/TR/webcodecs-aac-codec-registration/.`)}else if(e.decoderConfig.codec.startsWith(`mp3`)||e.decoderConfig.codec.startsWith(`mp4a`)){if(e.decoderConfig.codec!==`mp3`&&e.decoderConfig.codec!==`mp4a.69`&&e.decoderConfig.codec!==`mp4a.6B`&&e.decoderConfig.codec!==`mp4a.6b`)throw TypeError(`Audio chunk metadata decoder configuration codec string for MP3 must be "mp3", "mp4a.69" or "mp4a.6B".`)}else if(e.decoderConfig.codec.startsWith(`opus`)){if(e.decoderConfig.codec!==`opus`)throw TypeError(`Audio chunk metadata decoder configuration codec string for Opus must be "opus".`);if(e.decoderConfig.description&&e.decoderConfig.description.byteLength<18)throw TypeError(`Audio chunk metadata decoder configuration description, when specified, is expected to be an Identification Header as specified in Section 5.1 of RFC 7845.`)}else if(e.decoderConfig.codec.startsWith(`vorbis`)){if(e.decoderConfig.codec!==`vorbis`)throw TypeError(`Audio chunk metadata decoder configuration codec string for Vorbis must be "vorbis".`);if(!e.decoderConfig.description)throw TypeError(`Audio chunk metadata decoder configuration for Vorbis must include a description, which is expected to adhere to the format described in https://www.w3.org/TR/webcodecs-vorbis-codec-registration/.`)}else if(e.decoderConfig.codec.startsWith(`flac`)){if(e.decoderConfig.codec!==`flac`)throw TypeError(`Audio chunk metadata decoder configuration codec string for FLAC must be "flac".`);if(!e.decoderConfig.description||e.decoderConfig.description.byteLength<42)throw TypeError(`Audio chunk metadata decoder configuration for FLAC must include a description, which is expected to adhere to the format described in https://www.w3.org/TR/webcodecs-flac-codec-registration/.`)}else if(e.decoderConfig.codec.startsWith(`ac-3`)||e.decoderConfig.codec.startsWith(`ac3`)){if(e.decoderConfig.codec!==`ac-3`)throw TypeError(`Audio chunk metadata decoder configuration codec string for AC-3 must be "ac-3".`)}else if(e.decoderConfig.codec.startsWith(`ec-3`)||e.decoderConfig.codec.startsWith(`eac3`)){if(e.decoderConfig.codec!==`ec-3`)throw TypeError(`Audio chunk metadata decoder configuration codec string for EC-3 must be "ec-3".`)}else if(e.decoderConfig.codec.startsWith(`dts`)){if(!v_.includes(e.decoderConfig.codec))throw TypeError(`Audio chunk metadata decoder configuration codec string for DTS must be one of the following four-character codes: ${v_.join(`, `)}.`)}else if((e.decoderConfig.codec.startsWith(`pcm`)||e.decoderConfig.codec.startsWith(`ulaw`)||e.decoderConfig.codec.startsWith(`alaw`))&&!l_.includes(e.decoderConfig.codec))throw TypeError(`Audio chunk metadata decoder configuration codec string for PCM must be one of the supported PCM codecs (${l_.join(`, `)}).`);if(t!==null&&E_(e.decoderConfig.codec)!==t)throw TypeError(`Audio chunk metadata decoder configuration codec string '${e.decoderConfig.codec}' does not fit to the track codec '${t}'.`)},F_=e=>{if(!e)throw TypeError(`Subtitle metadata must be provided.`);if(typeof e!=`object`)throw TypeError(`Subtitle metadata must be an object.`);if(!e.config)throw TypeError(`Subtitle metadata must include a config object.`);if(typeof e.config!=`object`)throw TypeError(`Subtitle metadata config must be an object.`);if(typeof e.config.description!=`string`)throw TypeError(`Subtitle metadata config description must be a string.`)},I_=class{constructor(e){this.input=e}dispose(){}},L_=/* #__PURE__ */ new Uint8Array,R_=class e{constructor(e,t,n,r,i=-1,a,o){if(this.data=e,this.type=t,this.timestamp=n,this.duration=r,this.sequenceNumber=i,e===L_&&a===void 0)throw Error(`Internal error: byteLength must be explicitly provided when constructing metadata-only packets.`);if(a===void 0&&(a=e.byteLength),!(e instanceof Uint8Array))throw TypeError(`data must be a Uint8Array.`);if(t!==`key`&&t!==`delta`)throw TypeError(`type must be either "key" or "delta".`);if(!Number.isFinite(n))throw TypeError(`timestamp must be a number.`);if(!Number.isFinite(r)||r<0)throw TypeError(`duration must be a non-negative number.`);if(!Number.isFinite(i))throw TypeError(`sequenceNumber must be a number.`);if(!Number.isInteger(a)||a<0)throw TypeError(`byteLength must be a non-negative integer.`);if(o!==void 0&&(typeof o!=`object`||!o))throw TypeError(`sideData, when provided, must be an object.`);if(o?.alpha!==void 0&&!(o.alpha instanceof Uint8Array))throw TypeError(`sideData.alpha, when provided, must be a Uint8Array.`);if(o?.alphaByteLength!==void 0&&(!Number.isInteger(o.alphaByteLength)||o.alphaByteLength<0))throw TypeError(`sideData.alphaByteLength, when provided, must be a non-negative integer.`);this.byteLength=a,this.sideData=o??{},this.sideData.alpha&&this.sideData.alphaByteLength===void 0&&(this.sideData.alphaByteLength=this.sideData.alpha.byteLength)}get isMetadataOnly(){return this.data===L_}get microsecondTimestamp(){return Math.trunc(vh*this.timestamp)}get microsecondDuration(){return Math.trunc(vh*this.duration)}toEncodedVideoChunk(){if(this.isMetadataOnly)throw TypeError(`Metadata-only packets cannot be converted to a video chunk.`);if(typeof EncodedVideoChunk>`u`)throw Error(`EncodedVideoChunk is not available in this environment.`);return new EncodedVideoChunk({data:this.data,type:this.type,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}alphaToEncodedVideoChunk(e=this.type){if(!this.sideData.alpha)throw TypeError(`This packet does not contain alpha side data.`);if(this.isMetadataOnly)throw TypeError(`Metadata-only packets cannot be converted to a video chunk.`);if(typeof EncodedVideoChunk>`u`)throw Error(`EncodedVideoChunk is not available in this environment.`);return new EncodedVideoChunk({data:this.sideData.alpha,type:e,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}toEncodedAudioChunk(){if(this.isMetadataOnly)throw TypeError(`Metadata-only packets cannot be converted to an audio chunk.`);if(typeof EncodedAudioChunk>`u`)throw Error(`EncodedAudioChunk is not available in this environment.`);return new EncodedAudioChunk({data:this.data,type:this.type,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}static fromEncodedChunk(t,n){if(!(t instanceof EncodedVideoChunk||t instanceof EncodedAudioChunk))throw TypeError(`chunk must be an EncodedVideoChunk or EncodedAudioChunk.`);let r=new Uint8Array(t.byteLength);return t.copyTo(r),new e(r,t.type,t.timestamp/1e6,(t.duration??0)/1e6,void 0,void 0,n)}clone(t){if(t!==void 0&&(typeof t!=`object`||!t))throw TypeError(`options, when provided, must be an object.`);if(t?.data!==void 0&&!(t.data instanceof Uint8Array))throw TypeError(`options.data, when provided, must be a Uint8Array.`);if(t?.type!==void 0&&t.type!==`key`&&t.type!==`delta`)throw TypeError(`options.type, when provided, must be either "key" or "delta".`);if(t?.timestamp!==void 0&&!Number.isFinite(t.timestamp))throw TypeError(`options.timestamp, when provided, must be a number.`);if(t?.duration!==void 0&&!Number.isFinite(t.duration))throw TypeError(`options.duration, when provided, must be a number.`);if(t?.sequenceNumber!==void 0&&!Number.isFinite(t.sequenceNumber))throw TypeError(`options.sequenceNumber, when provided, must be a number.`);if(t?.sideData!==void 0&&(typeof t.sideData!=`object`||t.sideData===null))throw TypeError(`options.sideData, when provided, must be an object.`);return new e(t?.data??this.data,t?.type??this.type,t?.timestamp??this.timestamp,t?.duration??this.duration,t?.sequenceNumber??this.sequenceNumber,this.byteLength,t?.sideData??this.sideData)}},z_=e=>{let t=(e.hasVideo?`video/`:e.hasAudio?`audio/`:`application/`)+(e.isQuickTime?`quicktime`:`mp4`);if(e.codecStrings.length>0){let n=[...new Set(e.codecStrings)];t+=`; codecs="${n.join(`, `)}"`}return t},B_=e=>{let t=Im(e),n=0,r=t.getUint8(n);n+=1,n+=3;let i=eh(e.subarray(n,n+16));n+=16;let a=null;if(r>0){let r=t.getUint32(n);if(n+=4,r>0){a=[];for(let t=0;t<r;t++)a.push(eh(e.subarray(n,n+16))),n+=16}}let o=t.getUint32(n);return n+=4,{systemId:i,keyIds:a,data:e.slice(n,n+o)}},V_=(e,t)=>e.systemId===t.systemId&&Th(e.data,t.data),H_=e=>{let t=H(e),n=gy(e,4),r=8;t===1&&(t=py(e),r=16);let i=t-r;return i<0?null:{name:n,totalSize:t,headerSize:r,contentSize:i}},U_=e=>fy(e)/65536,W_=e=>fy(e)/1073741824,G_=e=>{let t=0;for(let n=0;n<4;n++){t<<=7;let n=V(e);if(t|=n&127,!(n&128))break}return t},K_=e=>{let t=ly(e);return e.skip(2),t=Math.min(t,e.remainingLength),zm.decode(cy(e,t))},q_=e=>{let t=H_(e);if(!t||t.name!==`data`||e.remainingLength<8)return null;let n=H(e);e.skip(4);let r=cy(e,t.contentSize-8);switch(n){case 1:return zm.decode(r);case 2:return new Rm(`utf-16be`).decode(r);case 13:return new Ih(r,`image/jpeg`);case 14:return new Ih(r,`image/png`);case 27:return new Ih(r,`image/bmp`);default:return r}},J_=/* @__PURE__ */ new Uint32Array(256),Y_=/* @__PURE__ */ new Uint32Array(256),X_=/* @__PURE__ */ new Uint32Array(256),Z_=/* @__PURE__ */ new Uint32Array(256),Q_=/* @__PURE__ */ new Uint32Array(256),$_=/* @__PURE__ */ new Uint32Array(256),ev=/* @__PURE__ */ new Uint32Array(10),tv=!1,nv=()=>{let e=/* @__PURE__ */ new Uint8Array(256),t=/* @__PURE__ */ new Uint8Array(256),n=/* @__PURE__ */ new Uint8Array(256);for(let e=0,r=1;e<256;e++)n[e]=r,t[r]=e,r=r^r<<1^(r&128?283:0);let r=(e,r)=>e&&r?n[(t[e]+t[r])%255]:0;e[0]=99;for(let r=1;r<256;r++){let i=n[255-t[r]],a=i^i<<1^i<<2^i<<3^i<<4;a=a>>>8^a&255^99,e[r]=a}for(let t=0;t<256;t++){let n=e[t],i=e.indexOf(t);J_[t]=n<<24|n<<16|n<<8|n,$_[t]=i<<24|i<<16|i<<8|i;let a=r(i,14),o=r(i,9),s=r(i,13),c=r(i,11),l=a<<24|o<<16|s<<8|c;Y_[t]=l,X_[t]=l>>>8|l<<24,Z_[t]=l>>>16|l<<16,Q_[t]=l>>>24|l<<8}let i=1;for(let e=0;e<10;e++)ev[e]=i<<24,i=i<<1^(i&128?283:0);tv=!0},rv=class{constructor(){this.roundkey=/* @__PURE__ */ new Uint32Array(44),this.iv=new Uint32Array(16/Uint32Array.BYTES_PER_ELEMENT),this.in=/* @__PURE__ */ new Uint8Array(16),this.out=/* @__PURE__ */ new Uint8Array(16),this.inView=new DataView(this.in.buffer),this.outView=new DataView(this.out.buffer)}init({key:e,iv:t}){z(e.byteLength===16),z(t.byteLength===16),tv||nv();let n=new DataView(e.buffer,e.byteOffset,e.byteLength),r=new DataView(t.buffer,t.byteOffset,t.byteLength);this.roundkey[0]=n.getUint32(0,!1),this.roundkey[1]=n.getUint32(4,!1),this.roundkey[2]=n.getUint32(8,!1),this.roundkey[3]=n.getUint32(12,!1),this.iv[0]=r.getUint32(0,!1),this.iv[1]=r.getUint32(4,!1),this.iv[2]=r.getUint32(8,!1),this.iv[3]=r.getUint32(12,!1);for(let e=4;e<44;e+=4){let t=this.roundkey[e-1];this.roundkey[e]=this.roundkey[e-4]^J_[t>>>16&255]&4278190080^J_[t>>>8&255]&16711680^J_[t>>>0&255]&65280^J_[t>>>24&255]&255^ev[e/4-1],this.roundkey[e+1]=this.roundkey[e-3]^this.roundkey[e],this.roundkey[e+2]=this.roundkey[e-2]^this.roundkey[e+1],this.roundkey[e+3]=this.roundkey[e-1]^this.roundkey[e+2]}for(let e=0,t=40;e<t;e+=4,t-=4)for(let n=0;n<4;n++){let r=this.roundkey[e+n];this.roundkey[e+n]=this.roundkey[t+n],this.roundkey[t+n]=r}for(let e=4;e<40;e+=4)for(let t=0;t<4;t++){let n=this.roundkey[e+t];this.roundkey[e+t]=Y_[J_[n>>>24&255]&255]^X_[J_[n>>>16&255]&255]^Z_[J_[n>>>8&255]&255]^Q_[J_[n>>>0&255]&255]}}decrypt(){let e=this.inView.getUint32(0,!1)^this.roundkey[0],t=this.inView.getUint32(4,!1)^this.roundkey[1],n=this.inView.getUint32(8,!1)^this.roundkey[2],r=this.inView.getUint32(12,!1)^this.roundkey[3],i=this.inView.getUint32(0,!1),a=this.inView.getUint32(4,!1),o=this.inView.getUint32(8,!1),s=this.inView.getUint32(12,!1),c,l,u,d;for(let i=1;i<10;i++){let a=i*4;c=Y_[e>>>24]^X_[r>>>16&255]^Z_[n>>>8&255]^Q_[t&255]^this.roundkey[a],l=Y_[t>>>24]^X_[e>>>16&255]^Z_[r>>>8&255]^Q_[n&255]^this.roundkey[a+1],u=Y_[n>>>24]^X_[t>>>16&255]^Z_[e>>>8&255]^Q_[r&255]^this.roundkey[a+2],d=Y_[r>>>24]^X_[n>>>16&255]^Z_[t>>>8&255]^Q_[e&255]^this.roundkey[a+3],e=c,t=l,n=u,r=d}let f=$_[e>>>24&255]&4278190080^$_[r>>>16&255]&16711680^$_[n>>>8&255]&65280^$_[t>>>0&255]&255^this.roundkey[40],p=$_[t>>>24&255]&4278190080^$_[e>>>16&255]&16711680^$_[r>>>8&255]&65280^$_[n>>>0&255]&255^this.roundkey[41],m=$_[n>>>24&255]&4278190080^$_[t>>>16&255]&16711680^$_[e>>>8&255]&65280^$_[r>>>0&255]&255^this.roundkey[42],h=$_[r>>>24&255]&4278190080^$_[n>>>16&255]&16711680^$_[t>>>8&255]&65280^$_[e>>>0&255]&255^this.roundkey[43];this.outView.setUint32(0,f^this.iv[0],!1),this.outView.setUint32(4,p^this.iv[1],!1),this.outView.setUint32(8,m^this.iv[2],!1),this.outView.setUint32(12,h^this.iv[3],!1),this.iv[0]=i,this.iv[1]=a,this.iv[2]=o,this.iv[3]=s}},iv=class e extends I_{constructor(e){super(e),this.moovSlice=null,this.currentTrack=null,this.tracks=[],this.metadataPromise=null,this.movieTimescale=-1,this.movieDurationInTimescale=-1,this.movieMatrix=Cm,this.isQuickTime=!1,this.metadataTags={},this.currentMetadataKeys=null,this.isFragmented=!1,this.fragmentTrackDefaults=[],this.psshBoxes=[],this.currentFragment=null,this.lastReadFragment=null,this.decryptionKeyCache=/* @__PURE__ */ new Map,this.reader=e._reader}async getTrackBackings(){return await this.readMetadata(),this.tracks.map(e=>e.trackBacking)}async getMimeType(){await this.readMetadata();let e=await this.getTrackBackings(),t=await Promise.all(e.map(e=>e.getDecoderConfig().then(e=>e?.codec??null)));return z_({isQuickTime:this.isQuickTime,hasVideo:this.tracks.some(e=>e.info?.type===`video`),hasAudio:this.tracks.some(e=>e.info?.type===`audio`),codecStrings:t.filter(Boolean)})}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}readMetadata(){return this.metadataPromise??=(async()=>{let e=0,t=!1,n=!1;for(;;){let r=this.reader.requestSliceRange(e,8,16);if(Ch(r)&&(r=await r),!r)break;let i=e,a=H_(r);if(!a)break;if(a.name===`ftyp`||a.name===`styp`){let e=gy(r,4);this.isQuickTime=e===`qt `}else if(a.name===`moov`){let e=this.reader.requestSlice(r.filePos,a.contentSize);if(Ch(e)&&(e=await e),!e)break;this.moovSlice=e,this.readContiguousBoxes(this.moovSlice);for(let e of this.tracks){let t=e.editListPreviousSegmentDurations/this.movieTimescale;e.editListOffset-=Math.round(t*e.timescale)}t=this.isFragmented&&this.reader.fileSize!==null&&this.reader.fileSize>i+a.totalSize,n=!0;break}else if(a.name===`moof`){if(!this.input._initInput)throw Error(`"moof" box encountered with no "moov" box present; this file is likely a Segment as described in ISO/IEC 14496-12 Section 8.16. A separate init file that contains a "moov" box is required to read this file, please provide it using InputOptions.initInput.`);await this.copyMetadataFromInitInput(this.input._initInput),t=!1,n=!0;break}e=i+a.totalSize}if(!n&&this.input._initInput&&await this.copyMetadataFromInitInput(this.input._initInput),t){z(this.reader.fileSize!==null);let e=this.reader.requestSlice(this.reader.fileSize-4,4);Ch(e)&&(e=await e),z(e);let t=H(e),n=this.reader.fileSize-t;if(n>=0&&n<=this.reader.fileSize-16){let e=this.reader.requestSliceRange(n,8,16);if(Ch(e)&&(e=await e),e){let t=H_(e);if(t&&t.name===`mfra`){let n=this.reader.requestSlice(e.filePos,t.contentSize);Ch(n)&&(n=await n),n&&this.readContiguousBoxes(n)}}}}})()}async copyMetadataFromInitInput(t){let n=await t._getDemuxer();if(n.constructor!==e)throw Error(`Init input must match the input's format.`);await n.readMetadata(),this.movieTimescale=n.movieTimescale,this.movieDurationInTimescale=n.movieDurationInTimescale,this.movieMatrix=n.movieMatrix,this.metadataTags=n.metadataTags,this.isFragmented=!0,this.fragmentTrackDefaults=n.fragmentTrackDefaults,this.psshBoxes=n.psshBoxes;for(let e of n.tracks){let t={id:e.id,demuxer:this,trackBacking:null,disposition:e.disposition,timescale:e.timescale,durationInMediaTimescale:e.durationInMediaTimescale,durationInMovieTimescale:e.durationInMovieTimescale,matrix:e.matrix,internalCodecId:e.internalCodecId,name:e.name,languageCode:e.languageCode,sampleTableByteOffset:null,sampleTable:null,fragmentLookupTable:[],currentFragmentState:null,fragmentPositionCache:[],editListPreviousSegmentDurations:e.editListPreviousSegmentDurations,editListOffset:e.editListOffset,encryptionInfo:e.encryptionInfo,encryptionAuxInfo:null,frmaCodecString:null,maxBitrate:e.maxBitrate,avgBitrate:e.avgBitrate,info:e.info};e.trackBacking&&(z(t.info),t.info.type===`video`&&t.info.width!==-1?(t.trackBacking=new ov(t),this.tracks.push(t)):t.info.type===`audio`&&t.info.numberOfChannels!==-1&&(t.trackBacking=new sv(t),this.tracks.push(t)))}}getSampleTableForTrack(e){if(e.sampleTable)return e.sampleTable;let t={sampleTimingEntries:[],sampleCompositionTimeOffsets:[],sampleSizes:[],keySampleIndices:null,chunkOffsets:[],sampleToChunk:[],presentationTimestamps:null,presentationTimestampIndexMap:null};if(e.sampleTable=t,e.sampleTableByteOffset===null)return t;z(this.moovSlice);let n=this.moovSlice.slice(e.sampleTableByteOffset);if(this.currentTrack=e,this.traverseBox(n),this.currentTrack=null,e.info?.type===`audio`&&e.info.codec&&l_.includes(e.info.codec)&&t.sampleCompositionTimeOffsets.length===0){z(e.info?.type===`audio`);let n=T_(e.info.codec),r=[],i=[];for(let a=0;a<t.sampleToChunk.length;a++){let o=t.sampleToChunk[a],s=t.sampleToChunk[a+1],c=(s?s.startChunkIndex:t.chunkOffsets.length)-o.startChunkIndex;for(let a=0;a<c;a++){let s=o.startSampleIndex+a*o.samplesPerChunk,c=s+o.samplesPerChunk,l=ih(t.sampleTimingEntries,s,e=>e.startIndex),u=t.sampleTimingEntries[l],d=ih(t.sampleTimingEntries,c,e=>e.startIndex),f=t.sampleTimingEntries[d],p=u.startDecodeTimestamp+(s-u.startIndex)*u.delta,m=f.startDecodeTimestamp+(c-f.startIndex)*f.delta-p,h=jm(r);h&&h.delta===m?h.count++:r.push({startIndex:o.startChunkIndex+a,startDecodeTimestamp:p,count:1,delta:m});let g=o.samplesPerChunk*n.sampleSize*e.info.numberOfChannels;i.push(g)}o.startSampleIndex=o.startChunkIndex,o.samplesPerChunk=1}t.sampleTimingEntries=r,t.sampleSizes=i}if(t.sampleCompositionTimeOffsets.length>0){t.presentationTimestamps=[];for(let e of t.sampleTimingEntries)for(let n=0;n<e.count;n++)t.presentationTimestamps.push({presentationTimestamp:e.startDecodeTimestamp+n*e.delta,sampleIndex:e.startIndex+n});for(let e of t.sampleCompositionTimeOffsets)for(let n=0;n<e.count;n++){let r=e.startIndex+n,i=t.presentationTimestamps[r];i&&(i.presentationTimestamp+=e.offset)}t.presentationTimestamps.sort((e,t)=>e.presentationTimestamp-t.presentationTimestamp),t.presentationTimestampIndexMap=Array(t.presentationTimestamps.length).fill(-1);for(let e=0;e<t.presentationTimestamps.length;e++)t.presentationTimestampIndexMap[t.presentationTimestamps[e].sampleIndex]=e}return t}async readFragment(e){if(this.lastReadFragment?.moofOffset===e)return this.lastReadFragment;let t=this.reader.requestSliceRange(e,8,16);Ch(t)&&(t=await t),z(t);let n=H_(t);z(n?.name===`moof`);let r=this.reader.requestSlice(e,n.totalSize);Ch(r)&&(r=await r),z(r),this.traverseBox(r);let i=this.lastReadFragment;z(i&&i.moofOffset===e);for(let[,e]of i.trackData){let t=e.track,{fragmentPositionCache:n}=t;if(!e.startTimestampIsFinal){let r=t.fragmentLookupTable.find(e=>e.moofOffset===i.moofOffset);if(r)fv(e,r.timestamp);else{let t=ih(n,i.moofOffset-1,e=>e.moofOffset);if(t!==-1){let r=n[t];fv(e,r.endTimestamp)}}e.startTimestampIsFinal=!0}let r=ih(n,e.startTimestamp,e=>e.startTimestamp);if((r===-1||n[r].moofOffset!==i.moofOffset)&&n.splice(r+1,0,{moofOffset:i.moofOffset,startTimestamp:e.startTimestamp,endTimestamp:e.endTimestamp}),e.encryptionAuxInfo&&t.encryptionInfo){let n=await gv(this.reader,t.encryptionInfo,e.encryptionAuxInfo);for(let t=0;t<Math.min(e.samples.length,n.length);t++){let r=n[t];e.samples[t].encryption=r}}}return i}readContiguousBoxes(e){let t=e.filePos;for(;e.filePos-t<=e.length-8&&this.traverseBox(e););}*iterateContiguousBoxes(e){let t=e.filePos;for(;e.filePos-t<=e.length-8;){let t=e.filePos,n=H_(e);if(!n)break;yield{boxInfo:n,slice:e},e.filePos=t+n.totalSize}}traverseBox(e){let t=e.filePos,n=H_(e);if(!n)return!1;let r=e.filePos,i=t+n.totalSize;switch(n.name){case`mdia`:case`minf`:case`dinf`:case`mfra`:case`edts`:case`sinf`:case`schi`:this.readContiguousBoxes(e.slice(r,n.contentSize));break;case`mvhd`:{let t=V(e);e.skip(3),t===1?(e.skip(16),this.movieTimescale=H(e),this.movieDurationInTimescale=py(e)):(e.skip(8),this.movieTimescale=H(e),this.movieDurationInTimescale=H(e)),e.skip(16),this.movieMatrix=pv(e)}break;case`trak`:{let t={id:-1,demuxer:this,trackBacking:null,disposition:{...zh,primary:!1},info:null,timescale:-1,durationInMovieTimescale:-1,durationInMediaTimescale:-1,matrix:Cm,internalCodecId:null,name:null,languageCode:`und`,sampleTableByteOffset:-1,sampleTable:null,fragmentLookupTable:[],currentFragmentState:null,fragmentPositionCache:[],editListPreviousSegmentDurations:0,editListOffset:0,encryptionInfo:null,encryptionAuxInfo:null,frmaCodecString:null,maxBitrate:null,avgBitrate:null};this.currentTrack=t,this.readContiguousBoxes(e.slice(r,n.contentSize)),t.id!==-1&&t.timescale!==-1&&t.info!==null&&(t.info.type===`video`&&t.info.width!==-1?(t.trackBacking=new ov(t),this.tracks.push(t)):t.info.type===`audio`&&t.info.numberOfChannels!==-1&&(t.trackBacking=new sv(t),this.tracks.push(t))),this.currentTrack=null}break;case`tkhd`:{let t=this.currentTrack;if(!t)break;let n=V(e),r=!!(uy(e)&1);if(t.disposition.default=r,n===0)e.skip(8),t.id=H(e),e.skip(4),t.durationInMovieTimescale=H(e);else if(n===1)e.skip(16),t.id=H(e),e.skip(4),t.durationInMovieTimescale=py(e);else throw Error(`Incorrect track header version ${n}.`);e.skip(16),t.matrix=Am(pv(e),this.movieMatrix)}break;case`elst`:{let t=this.currentTrack;if(!t)break;let n=V(e);e.skip(3);let r=!1,i=0,a=H(e);for(let o=0;o<a;o++){let a=n===1?py(e):H(e),o=n===1?my(e):fy(e),s=U_(e);if(r){Fh._warn(`Unsupported edit list: multiple edits are not currently supported. Only using first edit.`);break}if(o===-1){i+=a;continue}if(s!==1){Fh._warn(`Unsupported edit list entry: media rate must be 1.`);break}t.editListPreviousSegmentDurations=i,t.editListOffset=o,r=!0}}break;case`mdhd`:{let t=this.currentTrack;if(!t)break;let n=V(e);e.skip(3),n===0?(e.skip(8),t.timescale=H(e),t.durationInMediaTimescale=H(e)):n===1&&(e.skip(16),t.timescale=H(e),t.durationInMediaTimescale=py(e));let r=ly(e);if(r>0){t.languageCode=``;for(let e=0;e<3;e++)t.languageCode=String.fromCharCode(96+(r&31))+t.languageCode,r>>=5;_h(t.languageCode)||(t.languageCode=`und`)}}break;case`hdlr`:{let t=this.currentTrack;if(!t)break;e.skip(8);let n=gy(e,4);n===`vide`?t.info={type:`video`,width:-1,height:-1,squarePixelWidth:-1,squarePixelHeight:-1,codec:null,codecDescription:null,colorSpace:{...Xm},avcType:null,avcCodecInfo:null,hevcCodecInfo:null,vp9CodecInfo:null,av1CodecInfo:null,proresCodecInfo:null,proresFormat:null}:n===`soun`&&(t.info={type:`audio`,numberOfChannels:-1,sampleRate:-1,codec:null,codecDescription:null,aacCodecInfo:null,dtsFormat:null,pcmLittleEndian:!1,pcmSampleSize:null})}break;case`stbl`:{let i=this.currentTrack;if(!i)break;i.sampleTableByteOffset=t,this.readContiguousBoxes(e.slice(r,n.contentSize))}break;case`stsd`:{let t=this.currentTrack;if(!t||t.info===null||t.sampleTable)break;let n=V(e);e.skip(3);let r=H(e);for(let i=0;i<r;i++){let r=e.filePos,i=H_(e);if(!i)break;t.internalCodecId=i.name;let a=i.name.toLowerCase();if(t.info.type===`video`){e.skip(24),t.info.width=ly(e),t.info.height=ly(e),t.info.squarePixelWidth=t.info.width,t.info.squarePixelHeight=t.info.height,e.skip(50),t.frmaCodecString=null,this.readContiguousBoxes(e.slice(e.filePos,r+i.totalSize-e.filePos));let n=a===`encv`?t.frmaCodecString:a;t.frmaCodecString=null,n===`avc1`||n===`avc3`?(t.info.codec=`avc`,t.info.avcType=n===`avc1`?1:3):n===`hvc1`||n===`hev1`?t.info.codec=`hevc`:n===`vp08`?t.info.codec=`vp8`:n===`vp09`?t.info.codec=`vp9`:n===`av01`?t.info.codec=`av1`:__.includes(a)?(t.info.codec=`prores`,t.info.proresFormat=a):n===null?Fh._warn(`Unknown encrypted video codec due to missing frma box.`):Fh._warn(`Unsupported video codec (sample entry type '${i.name}').`)}else{e.skip(8);let o=ly(e);e.skip(6);let s=ly(e),c=ly(e);e.skip(4);let l=H(e)/65536,u=null;n===0&&o>0&&(o===1?(e.skip(4),c=8*H(e),e.skip(8)):o===2&&(e.skip(4),l=hy(e),s=H(e),e.skip(4),c=H(e),u=H(e),e.skip(8))),t.info.numberOfChannels=s,t.info.sampleRate=l,t.frmaCodecString=null,this.readContiguousBoxes(e.slice(e.filePos,r+i.totalSize-e.filePos));let d=a===`enca`?t.frmaCodecString:a;if(t.frmaCodecString=null,d!==`mp4a`){if(d===`opus`)t.info.codec=`opus`,t.info.sampleRate=C_;else if(d===`flac`)t.info.codec=`flac`;else if(d===`ulaw`)t.info.codec=`ulaw`;else if(d===`alaw`)t.info.codec=`alaw`;else if(d===`ac-3`)t.info.codec=`ac3`;else if(d===`ec-3`)t.info.codec=`eac3`;else if(v_.includes(d))t.info.codec=`dts`,t.info.dtsFormat=d;else if(d===`twos`)c===8?t.info.codec=`pcm-s8`:c===16?t.info.codec=t.info.pcmLittleEndian?`pcm-s16`:`pcm-s16be`:(Fh._warn(`Unsupported sample size ${c} for codec 'twos'.`),t.info.codec=null);else if(d===`sowt`)c===8?t.info.codec=`pcm-s8`:c===16?t.info.codec=`pcm-s16`:(Fh._warn(`Unsupported sample size ${c} for codec 'sowt'.`),t.info.codec=null);else if(d===`raw `)t.info.codec=`pcm-u8`;else if(d===`in24`)t.info.codec=t.info.pcmLittleEndian?`pcm-s24`:`pcm-s24be`;else if(d===`in32`)t.info.codec=t.info.pcmLittleEndian?`pcm-s32`:`pcm-s32be`;else if(d===`fl32`)t.info.codec=t.info.pcmLittleEndian?`pcm-f32`:`pcm-f32be`;else if(d===`fl64`)t.info.codec=t.info.pcmLittleEndian?`pcm-f64`:`pcm-f64be`;else if(d===`ipcm`){let e=t.info.pcmSampleSize;t.info.pcmLittleEndian?e===16?t.info.codec=`pcm-s16`:e===24?t.info.codec=`pcm-s24`:e===32?t.info.codec=`pcm-s32`:(Fh._warn(`Invalid ipcm sample size ${e}.`),t.info.codec=null):e===16?t.info.codec=`pcm-s16be`:e===24?t.info.codec=`pcm-s24be`:e===32?t.info.codec=`pcm-s32be`:(Fh._warn(`Invalid ipcm sample size ${e}.`),t.info.codec=null)}else if(d===`fpcm`){let e=t.info.pcmSampleSize;t.info.pcmLittleEndian?e===32?t.info.codec=`pcm-f32`:e===64?t.info.codec=`pcm-f64`:(Fh._warn(`Invalid fpcm sample size ${e}.`),t.info.codec=null):e===32?t.info.codec=`pcm-f32be`:e===64?t.info.codec=`pcm-f64be`:(Fh._warn(`Invalid fpcm sample size ${e}.`),t.info.codec=null)}else if(d===`lpcm`&&u!==null){let e=c+7>>3,n=!!(u&1),r=!!(u&2),i=u&4?-1:0;c>0&&c<=64&&(n?c===32&&(t.info.codec=r?`pcm-f32be`:`pcm-f32`):i&1<<e-1?e===1?t.info.codec=`pcm-s8`:e===2?t.info.codec=r?`pcm-s16be`:`pcm-s16`:e===3?t.info.codec=r?`pcm-s24be`:`pcm-s24`:e===4&&(t.info.codec=r?`pcm-s32be`:`pcm-s32`):e===1&&(t.info.codec=`pcm-u8`)),t.info.codec===null&&Fh._warn(`Unsupported PCM format.`)}else d===null?Fh._warn(`Unknown encrypted audio codec due to missing frma box.`):Fh._warn(`Unsupported audio codec (sample entry type '${i.name}').`)}}e.filePos=r+i.totalSize}}break;case`frma`:{let t=this.currentTrack;if(!t)break;t.frmaCodecString=gy(e,4).toLowerCase()}break;case`schm`:{let t=this.currentTrack;if(!t)break;e.skip(4);let n=gy(e,4);n===`cenc`||n===`cens`||n===`cbcs`?t.encryptionInfo={scheme:n,defaultKid:null,defaultIsProtected:null,defaultPerSampleIvSize:null,defaultConstantIv:null,defaultCryptByteBlock:null,defaultSkipByteBlock:null}:Fh._warn(`Unsupported encryption scheme '${n}'.`)}break;case`tenc`:{let t=this.currentTrack;if(!t||!t.encryptionInfo)break;let n=V(e);e.skip(3),e.skip(1);let r=V(e);if(n>0?(t.encryptionInfo.defaultCryptByteBlock=r>>4,t.encryptionInfo.defaultSkipByteBlock=r&15):(t.encryptionInfo.defaultCryptByteBlock=0,t.encryptionInfo.defaultSkipByteBlock=0),t.encryptionInfo.defaultIsProtected=V(e)!==0,t.encryptionInfo.defaultPerSampleIvSize=V(e),t.encryptionInfo.defaultKid=eh(cy(e,16)),t.encryptionInfo.defaultIsProtected&&t.encryptionInfo.defaultPerSampleIvSize===0){let n=V(e),r=/* @__PURE__ */ new Uint8Array(16);r.set(cy(e,n),0),t.encryptionInfo.defaultConstantIv=r}}break;case`avcC`:{let t=this.currentTrack;if(!t||(z(t.info),n.contentSize===0))break;t.info.codecDescription=cy(e,n.contentSize)}break;case`hvcC`:{let t=this.currentTrack;if(!t||(z(t.info),n.contentSize===0))break;t.info.codecDescription=cy(e,n.contentSize)}break;case`vpcC`:{let t=this.currentTrack;if(!t)break;z(t.info?.type===`video`),e.skip(4);let n=V(e),r=V(e),i=V(e),a=i>>4,o=i>>1&7,s=i&1,c=V(e),l=V(e),u=V(e);t.info.vp9CodecInfo={profile:n,level:r,bitDepth:a,chromaSubsampling:o,videoFullRangeFlag:s,colourPrimaries:c,transferCharacteristics:l,matrixCoefficients:u}}break;case`av1C`:{let t=this.currentTrack;if(!t)break;z(t.info?.type===`video`),e.skip(1);let r=V(e),i=r>>5,a=r&31,o=V(e),s=o>>7,c=o>>6&1,l=o>>5&1,u=o>>4&1,d=o>>3&1,f=o>>2&1,p=o&3,m=i===2&&c?l?12:10:c?10:8;e.skip(1);let h=jg(cy(e,n.contentSize-4));t.info.av1CodecInfo={profile:i,level:a,tier:s,bitDepth:m,monochrome:u,chromaSubsamplingX:d,chromaSubsamplingY:f,chromaSamplePosition:p,videoFullRangeFlag:h?.videoFullRangeFlag??0,colourPrimaries:h?.colourPrimaries??2,transferCharacteristics:h?.transferCharacteristics??2,matrixCoefficients:h?.matrixCoefficients??2}}break;case`colr`:{let t=this.currentTrack;if(!t)break;z(t.info?.type===`video`);let n=gy(e,4);if(n!==`nclx`&&n!==`nclc`)break;let r=ly(e),i=ly(e),a=ly(e),o;n===`nclx`&&(o=!!(V(e)&128)),t.info.colorSpace={primaries:Um[r],transfer:Gm[i],matrix:qm[a],fullRange:o}}break;case`pasp`:{let t=this.currentTrack;if(!t)break;z(t.info?.type===`video`);let n=H(e),r=H(e);n>0&&r>0&&(n>r?t.info.squarePixelWidth=Math.round(t.info.width*n/r):t.info.squarePixelHeight=Math.round(t.info.height*r/n))}break;case`btrt`:{let t=this.currentTrack;if(!t)break;e.skip(4);let n=H(e),r=H(e);t.maxBitrate=n>0?n:null,t.avgBitrate=r>0?r:null}break;case`wave`:this.readContiguousBoxes(e.slice(r,n.contentSize));break;case`esds`:{let t=this.currentTrack;if(!t||t.info?.type!==`audio`)break;e.skip(4),z(V(e)===3),G_(e),e.skip(2);let n=V(e),r=!!(n&128),i=!!(n&64),a=!!(n&32);if(r&&e.skip(2),i){let t=V(e);e.skip(t)}a&&e.skip(2),z(V(e)===4);let o=G_(e),s=e.filePos,c=V(e);if(c===64||c===103?(t.info.codec=`aac`,t.info.aacCodecInfo={isMpeg2:c===103,objectType:null}):c===105||c===107?t.info.codec=`mp3`:c===221?t.info.codec=`vorbis`:c===169?t.info.codec=`dts`:Fh._warn(`Unsupported audio codec (objectTypeIndication ${c}) - discarding track.`),e.skip(12),o>e.filePos-s){z(V(e)===5);let n=G_(e);if(t.info.codecDescription=cy(e,n),t.info.codec===`aac`){let e=Wh(t.info.codecDescription);e.outputNumberOfChannels!==null&&(t.info.numberOfChannels=e.outputNumberOfChannels),e.outputSampleRate!==null&&(t.info.sampleRate=e.outputSampleRate)}}}break;case`enda`:{let t=this.currentTrack;if(!t)break;z(t.info?.type===`audio`),t.info.pcmLittleEndian=!!(ly(e)&255)}break;case`pcmC`:{let t=this.currentTrack;if(!t)break;z(t.info?.type===`audio`),e.skip(4);let n=V(e);t.info.pcmLittleEndian=!!(n&1),t.info.pcmSampleSize=V(e)}break;case`dOps`:{let t=this.currentTrack;if(!t)break;z(t.info?.type===`audio`),e.skip(1);let n=V(e),r=ly(e),i=H(e),a=dy(e),o=V(e),s;s=o===0?/* @__PURE__ */ new Uint8Array:cy(e,2+n);let c=new Uint8Array(19+s.byteLength),l=new DataView(c.buffer);l.setUint32(0,1332770163,!1),l.setUint32(4,1214603620,!1),l.setUint8(8,1),l.setUint8(9,n),l.setUint16(10,r,!0),l.setUint32(12,i,!0),l.setInt16(16,a,!0),l.setUint8(18,o),c.set(s,19),t.info.codecDescription=c,t.info.numberOfChannels=n}break;case`dfLa`:{let t=this.currentTrack;if(!t)break;z(t.info?.type===`audio`),e.skip(4);let n=e.filePos;for(;e.filePos<i;){let n=V(e),r=uy(e);if((n&127)===Ig.STREAMINFO){e.skip(10);let n=H(e),r=n>>>12,i=(n>>9&7)+1;t.info.sampleRate=r,t.info.numberOfChannels=i,e.skip(20)}else e.skip(r);if(n&128)break}let r=e.filePos;e.filePos=n;let a=cy(e,r-n),o=new Uint8Array(4+a.byteLength);new DataView(o.buffer).setUint32(0,1716281667,!1),o.set(a,4),t.info.codecDescription=o}break;case`dac3`:{let t=this.currentTrack;if(!t)break;z(t.info?.type===`audio`);let n=new Vh(cy(e,3)),r=n.readBits(2);n.skipBits(8);let i=n.readBits(3),a=n.readBits(1);r<3&&(t.info.sampleRate=Zh[r]),t.info.numberOfChannels=Lg[i]+a}break;case`dec3`:{let t=this.currentTrack;if(!t)break;z(t.info?.type===`audio`);let r=Vg(cy(e,n.contentSize));if(!r){Fh._warn(`Invalid dec3 box contents, ignoring.`);break}let i=Hg(r);i!==null&&(t.info.sampleRate=i),t.info.numberOfChannels=Ug(r)}break;case`ddts`:{let t=this.currentTrack;if(!t)break;z(t.info?.type===`audio`);let r=a_(cy(e,Math.min(n.contentSize,20)));if(!r){Fh._warn(`Invalid ddts box contents, ignoring.`);break}t.info.sampleRate=r.sampleRate,r.numberOfChannels!==null&&(t.info.numberOfChannels=r.numberOfChannels)}break;case`stts`:{let t=this.currentTrack;if(!t||!t.sampleTable)break;e.skip(4);let n=H(e),r=0,i=0;for(let a=0;a<n;a++){let n=H(e),a=H(e);t.sampleTable.sampleTimingEntries.push({startIndex:r,startDecodeTimestamp:i,count:n,delta:a}),r+=n,i+=n*a}}break;case`ctts`:{let t=this.currentTrack;if(!t||!t.sampleTable)break;e.skip(4);let n=H(e),r=0;for(let i=0;i<n;i++){let n=H(e),i=fy(e);t.sampleTable.sampleCompositionTimeOffsets.push({startIndex:r,count:n,offset:i}),r+=n}}break;case`stsz`:{let t=this.currentTrack;if(!t||!t.sampleTable)break;e.skip(4);let n=H(e),r=H(e);if(n===0)for(let n=0;n<r;n++){let n=H(e);t.sampleTable.sampleSizes.push(n)}else t.sampleTable.sampleSizes.push(n)}break;case`stz2`:{let t=this.currentTrack;if(!t||!t.sampleTable)break;e.skip(4),e.skip(3);let n=V(e),r=H(e),i=new Vh(cy(e,Math.ceil(r*n/8)));for(let e=0;e<r;e++){let e=i.readBits(n);t.sampleTable.sampleSizes.push(e)}}break;case`stss`:{let t=this.currentTrack;if(!t||!t.sampleTable)break;e.skip(4),t.sampleTable.keySampleIndices=[];let n=H(e);for(let r=0;r<n;r++){let n=H(e)-1;t.sampleTable.keySampleIndices.push(n)}t.sampleTable.keySampleIndices[0]!==0&&t.sampleTable.keySampleIndices.unshift(0)}break;case`stsc`:{let t=this.currentTrack;if(!t||!t.sampleTable)break;e.skip(4);let n=H(e);for(let r=0;r<n;r++){let n=H(e)-1,r=H(e),i=H(e);t.sampleTable.sampleToChunk.push({startSampleIndex:-1,startChunkIndex:n,samplesPerChunk:r,sampleDescriptionIndex:i})}let r=0;for(let e=0;e<t.sampleTable.sampleToChunk.length;e++)if(t.sampleTable.sampleToChunk[e].startSampleIndex=r,e<t.sampleTable.sampleToChunk.length-1){let n=t.sampleTable.sampleToChunk[e+1].startChunkIndex-t.sampleTable.sampleToChunk[e].startChunkIndex;r+=n*t.sampleTable.sampleToChunk[e].samplesPerChunk}}break;case`stco`:{let t=this.currentTrack;if(!t||!t.sampleTable)break;e.skip(4);let n=H(e);for(let r=0;r<n;r++){let n=H(e);t.sampleTable.chunkOffsets.push(n)}}break;case`co64`:{let t=this.currentTrack;if(!t||!t.sampleTable)break;e.skip(4);let n=H(e);for(let r=0;r<n;r++){let n=py(e);t.sampleTable.chunkOffsets.push(n)}}break;case`mvex`:this.isFragmented=!0,this.readContiguousBoxes(e.slice(r,n.contentSize));break;case`mehd`:{let t=V(e);e.skip(3);let n=t===1?py(e):H(e);this.movieDurationInTimescale=n}break;case`trex`:{e.skip(4);let t=H(e),n=H(e),r=H(e),i=H(e),a=H(e);this.fragmentTrackDefaults.push({trackId:t,defaultSampleDescriptionIndex:n,defaultSampleDuration:r,defaultSampleSize:i,defaultSampleFlags:a})}break;case`tfra`:{let t=V(e);e.skip(3);let n=H(e),r=this.tracks.find(e=>e.id===n);if(!r)break;let i=H(e),a=(i&48)>>4,o=(i&12)>>2,s=i&3,c=[V,ly,uy,H],l=c[a],u=c[o],d=c[s],f=H(e);for(let n=0;n<f;n++){let n=t===1?py(e):H(e),i=t===1?py(e):H(e);l(e),u(e),d(e),r.fragmentLookupTable.push({timestamp:n,moofOffset:i})}r.fragmentLookupTable.sort((e,t)=>e.timestamp-t.timestamp);for(let e=0;e<r.fragmentLookupTable.length-1;e++){let t=r.fragmentLookupTable[e],n=r.fragmentLookupTable[e+1];t.timestamp===n.timestamp&&(r.fragmentLookupTable.splice(e+1,1),e--)}}break;case`moof`:this.currentFragment={moofOffset:t,moofSize:n.totalSize,implicitBaseDataOffset:t,trackData:/* @__PURE__ */ new Map,psshBoxes:[]},this.readContiguousBoxes(e.slice(r,n.contentSize)),this.lastReadFragment=this.currentFragment,this.currentFragment=null;break;case`traf`:if(z(this.currentFragment),this.readContiguousBoxes(e.slice(r,n.contentSize)),this.currentTrack){let e=this.currentFragment.trackData.get(this.currentTrack.id);cond:if(e){if(e.samples.length===0){this.currentFragment.trackData.delete(this.currentTrack.id);break cond}e.presentationTimestamps=e.samples.map((e,t)=>({presentationTimestamp:e.presentationTimestamp,sampleIndex:t})).sort((e,t)=>e.presentationTimestamp-t.presentationTimestamp);for(let t=0;t<e.presentationTimestamps.length;t++){let n=e.presentationTimestamps[t],r=e.samples[n.sampleIndex];e.firstKeyFrameTimestamp===null&&r.isKeyFrame&&(e.firstKeyFrameTimestamp=r.presentationTimestamp),t<e.presentationTimestamps.length-1&&(r.duration=e.presentationTimestamps[t+1].presentationTimestamp-n.presentationTimestamp)}let t=e.samples[e.presentationTimestamps[0].sampleIndex],n=e.samples[jm(e.presentationTimestamps).sampleIndex];e.startTimestamp=t.presentationTimestamp,e.endTimestamp=n.presentationTimestamp+n.duration;let{currentFragmentState:r}=this.currentTrack;z(r),r.startTimestamp!==null&&(fv(e,r.startTimestamp),e.startTimestampIsFinal=!0),r.encryptionAuxInfo&&!e.samples[0].encryption&&(e.encryptionAuxInfo=r.encryptionAuxInfo)}this.currentTrack.currentFragmentState=null,this.currentTrack=null}break;case`pssh`:{if(this.input._formatOptions.isobmff?._suppressPsshParsing)break;let t=B_(cy(e,n.contentSize));this.currentFragment?this.currentFragment.psshBoxes.push(t):this.currentTrack||this.psshBoxes.push(t)}break;case`tfhd`:{z(this.currentFragment),e.skip(1);let t=uy(e),n=!!(t&1),r=!!(t&2),i=!!(t&8),a=!!(t&16),o=!!(t&32),s=!!(t&65536),c=!!(t&131072),l=H(e),u=this.tracks.find(e=>e.id===l);if(!u)break;let d=this.fragmentTrackDefaults.find(e=>e.trackId===l);this.currentTrack=u,u.currentFragmentState={baseDataOffset:this.currentFragment.implicitBaseDataOffset,sampleDescriptionIndex:d?.defaultSampleDescriptionIndex??null,defaultSampleDuration:d?.defaultSampleDuration??null,defaultSampleSize:d?.defaultSampleSize??null,defaultSampleFlags:d?.defaultSampleFlags??null,startTimestamp:null,encryptionAuxInfo:null},n?u.currentFragmentState.baseDataOffset=py(e):c&&(u.currentFragmentState.baseDataOffset=this.currentFragment.moofOffset),r&&(u.currentFragmentState.sampleDescriptionIndex=H(e)),i&&(u.currentFragmentState.defaultSampleDuration=H(e)),a&&(u.currentFragmentState.defaultSampleSize=H(e)),o&&(u.currentFragmentState.defaultSampleFlags=H(e)),s&&(u.currentFragmentState.defaultSampleDuration=0)}break;case`tfdt`:{let t=this.currentTrack;if(!t)break;z(t.currentFragmentState);let n=V(e);e.skip(3);let r=n===0?H(e):py(e);t.currentFragmentState.startTimestamp=r}break;case`trun`:{let t=this.currentTrack;if(!t)break;z(this.currentFragment),z(t.currentFragmentState);let n=V(e),r=uy(e),i=!!(r&1),a=!!(r&4),o=!!(r&256),s=!!(r&512),c=!!(r&1024),l=!!(r&2048),u=H(e),d=null;i&&(d=fy(e));let f=null;a&&(f=H(e));let p;this.currentFragment.trackData.has(t.id)?(p=this.currentFragment.trackData.get(t.id),d!==null&&(p.currentOffset=t.currentFragmentState.baseDataOffset+d)):(p={track:t,currentTimestamp:0,currentOffset:t.currentFragmentState.baseDataOffset+(d??0),startTimestamp:0,endTimestamp:0,firstKeyFrameTimestamp:null,samples:[],presentationTimestamps:[],startTimestampIsFinal:!1,encryptionAuxInfo:null},this.currentFragment.trackData.set(t.id,p));for(let r=0;r<u;r++){let i;o?i=H(e):(z(t.currentFragmentState.defaultSampleDuration!==null),i=t.currentFragmentState.defaultSampleDuration);let a;s?a=H(e):(z(t.currentFragmentState.defaultSampleSize!==null),a=t.currentFragmentState.defaultSampleSize);let u;c?u=H(e):(z(t.currentFragmentState.defaultSampleFlags!==null),u=t.currentFragmentState.defaultSampleFlags),r===0&&f!==null&&(u=f);let d=0;l&&(d=n===0?H(e):fy(e));let m=!(u&65536);p.samples.push({presentationTimestamp:p.currentTimestamp+d,duration:i,byteOffset:p.currentOffset,byteSize:a,isKeyFrame:m,encryption:null}),p.currentOffset+=a,p.currentTimestamp+=i}this.currentFragment.implicitBaseDataOffset=p.currentOffset}break;case`saiz`:{let t=this.currentTrack;if(!t||!t.encryptionInfo)break;if(e.skip(1),uy(e)&1){let n=gy(e,4),r=H(e);if(n!==t.encryptionInfo.scheme||r!==0)break}let n=V(e),r=H(e),i=null;n===0&&r>0&&(i=cy(e,r));let a=hv(t);a.defaultSampleInfoSize=n,a.sampleSizes=i,a.sampleCount=r}break;case`saio`:{let t=this.currentTrack;if(!t||!t.encryptionInfo)break;let n=V(e);if(uy(e)&1){let n=gy(e,4),r=H(e);if(n!==t.encryptionInfo.scheme||r!==0)break}let r=H(e);if(r===0)break;r>1&&Fh._warn(`Multiple saio entries are not supported; using the first offset only.`);let i=n===0?H(e):Number(py(e));this.currentFragment&&(i+=this.currentFragment.moofOffset);let a=hv(t);a.offset=i}break;case`senc`:{let t=this.currentTrack;if(!t||!t.encryptionInfo)break;z(this.currentFragment);let n=this.currentFragment.trackData.get(t.id);if(!n)break;e.skip(1);let r=!!(uy(e)&2),i=H(e),a=t.encryptionInfo.defaultPerSampleIvSize;z(a!==null);for(let o=0;o<Math.min(i,n.samples.length);o++){let i=/* @__PURE__ */ new Uint8Array(16);a>0?i.set(cy(e,a),0):i.set(t.encryptionInfo.defaultConstantIv,0);let s=null;if(r){let t=ly(e);s=[];for(let n=0;n<t;n++){let t=ly(e),n=H(e);s.push({clearLen:t,protectedLen:n})}}let c=n.samples[o];c.encryption={iv:i,subsamples:s}}}break;case`udta`:{let t=this.iterateContiguousBoxes(e.slice(r,n.contentSize));for(let{boxInfo:e,slice:n}of t){if(e.name!==`meta`&&!this.currentTrack){let t=n.filePos;this.metadataTags.raw??={},e.name[0]===`©`?this.metadataTags.raw[e.name]??=K_(n):this.metadataTags.raw[e.name]??=cy(n,e.contentSize),n.filePos=t}switch(e.name){case`meta`:n.skip(-e.headerSize),this.traverseBox(n);break;case`©nam`:case`name`:this.currentTrack?this.currentTrack.name=zm.decode(cy(n,e.contentSize)):this.metadataTags.title??=K_(n);break;case`©des`:this.currentTrack||(this.metadataTags.description??=K_(n));break;case`©ART`:this.currentTrack||(this.metadataTags.artist??=K_(n));break;case`©alb`:this.currentTrack||(this.metadataTags.album??=K_(n));break;case`albr`:this.currentTrack||(this.metadataTags.albumArtist??=K_(n));break;case`©gen`:this.currentTrack||(this.metadataTags.genre??=K_(n));break;case`©day`:if(!this.currentTrack){let e=new Date(K_(n));Number.isNaN(e.getTime())||(this.metadataTags.date??=e)}break;case`©cmt`:this.currentTrack||(this.metadataTags.comment??=K_(n));break;case`©lyr`:this.currentTrack||(this.metadataTags.lyrics??=K_(n))}}}break;case`meta`:{if(this.currentTrack)break;let t=H(e)!==0;this.currentMetadataKeys=/* @__PURE__ */ new Map,t?this.readContiguousBoxes(e.slice(r,n.contentSize)):this.readContiguousBoxes(e.slice(r+4,n.contentSize-4)),this.currentMetadataKeys=null}break;case`keys`:{if(!this.currentMetadataKeys)break;e.skip(4);let t=H(e);for(let n=0;n<t;n++){let t=H(e);e.skip(4);let r=zm.decode(cy(e,t-8));this.currentMetadataKeys.set(n+1,r)}}break;case`ilst`:{if(!this.currentMetadataKeys)break;let t=this.iterateContiguousBoxes(e.slice(r,n.contentSize));for(let{boxInfo:e,slice:n}of t){let t=e.name,r=(t.charCodeAt(0)<<24)+(t.charCodeAt(1)<<16)+(t.charCodeAt(2)<<8)+t.charCodeAt(3);this.currentMetadataKeys.has(r)&&(t=this.currentMetadataKeys.get(r));let i=q_(n);switch(this.metadataTags.raw??={},this.metadataTags.raw[t]??=i,t){case`©nam`:case`titl`:case`com.apple.quicktime.title`:case`title`:typeof i==`string`&&(this.metadataTags.title??=i);break;case`©des`:case`desc`:case`dscp`:case`com.apple.quicktime.description`:case`description`:typeof i==`string`&&(this.metadataTags.description??=i);break;case`©ART`:case`com.apple.quicktime.artist`:case`artist`:typeof i==`string`&&(this.metadataTags.artist??=i);break;case`©alb`:case`albm`:case`com.apple.quicktime.album`:case`album`:typeof i==`string`&&(this.metadataTags.album??=i);break;case`aART`:case`album_artist`:typeof i==`string`&&(this.metadataTags.albumArtist??=i);break;case`©cmt`:case`com.apple.quicktime.comment`:case`comment`:typeof i==`string`&&(this.metadataTags.comment??=i);break;case`©gen`:case`gnre`:case`com.apple.quicktime.genre`:case`genre`:typeof i==`string`&&(this.metadataTags.genre??=i);break;case`©lyr`:case`lyrics`:typeof i==`string`&&(this.metadataTags.lyrics??=i);break;case`©day`:case`rldt`:case`com.apple.quicktime.creationdate`:case`date`:if(typeof i==`string`){let e=new Date(i);Number.isNaN(e.getTime())||(this.metadataTags.date??=e)}break;case`covr`:case`com.apple.quicktime.artwork`:i instanceof Ih?(this.metadataTags.images??=[],this.metadataTags.images.push({data:i.data,kind:`coverFront`,mimeType:i.mimeType})):i instanceof Uint8Array&&(this.metadataTags.images??=[],this.metadataTags.images.push({data:i,kind:`coverFront`,mimeType:`image/*`}));break;case`track`:if(typeof i==`string`){let e=i.split(`/`),t=Number.parseInt(e[0],10),n=e[1]&&Number.parseInt(e[1],10);Number.isInteger(t)&&t>0&&(this.metadataTags.trackNumber??=t),n&&Number.isInteger(n)&&n>0&&(this.metadataTags.tracksTotal??=n)}break;case`trkn`:if(i instanceof Uint8Array&&i.length>=6){let e=Im(i),t=e.getUint16(2,!1),n=e.getUint16(4,!1);t>0&&(this.metadataTags.trackNumber??=t),n>0&&(this.metadataTags.tracksTotal??=n)}break;case`disc`:case`disk`:if(i instanceof Uint8Array&&i.length>=6){let e=Im(i),t=e.getUint16(2,!1),n=e.getUint16(4,!1);t>0&&(this.metadataTags.discNumber??=t),n>0&&(this.metadataTags.discsTotal??=n)}}}}}return e.filePos=i,!0}},av=class{constructor(e){this.internalTrack=e,this.packetToSampleIndex=/* @__PURE__ */ new WeakMap,this.packetToFragmentLocation=/* @__PURE__ */ new WeakMap}getId(){return this.internalTrack.id}getNumber(){let e=this.internalTrack.demuxer,t=this.internalTrack.trackBacking.getType(),n=0;for(let r of e.tracks)if(r.trackBacking.getType()===t&&n++,r===this.internalTrack)break;return n}getCodec(){throw Error(`Not implemented on base class.`)}getInternalCodecId(){return this.internalTrack.internalCodecId}getName(){return this.internalTrack.name}getLanguageCode(){return this.internalTrack.languageCode}getTimeResolution(){return this.internalTrack.timescale}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getDisposition(){return this.internalTrack.disposition}getPairingMask(){return 1n}getBitrate(){return this.internalTrack.maxBitrate}getAverageBitrate(){return this.internalTrack.avgBitrate}async getDurationFromMetadata(){let e=this.internalTrack;return e.durationInMediaTimescale<=0?null:(z(e.trackBacking),((await e.trackBacking.getFirstPacket({metadataOnly:!0}))?.timestamp??0)+e.durationInMediaTimescale/e.timescale)}async getLiveRefreshInterval(){return null}async getFirstPacket(e){let t=await this.fetchPacketForSampleIndex(0,e);return t||!this.internalTrack.demuxer.isFragmented?t:this.performFragmentedLookup(null,e=>e.trackData.get(this.internalTrack.id)?{sampleIndex:0,correctSampleFound:!0}:{sampleIndex:-1,correctSampleFound:!1},-1/0,1/0,e)}mapTimestampIntoTimescale(e){return fh(e*this.internalTrack.timescale)+this.internalTrack.editListOffset}async getPacket(e,t){let n=this.mapTimestampIntoTimescale(e),r=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),i=cv(r,n),a=await this.fetchPacketForSampleIndex(i,t);return!mv(r)||!this.internalTrack.demuxer.isFragmented?a:this.performFragmentedLookup(null,e=>{let t=e.trackData.get(this.internalTrack.id);if(!t)return{sampleIndex:-1,correctSampleFound:!1};let r=ih(t.presentationTimestamps,n,e=>e.presentationTimestamp);return{sampleIndex:r===-1?-1:t.presentationTimestamps[r].sampleIndex,correctSampleFound:r!==-1&&n<t.endTimestamp}},n,n,t)}async getNextPacket(e,t){let n=this.packetToSampleIndex.get(e);if(n!==void 0)return this.fetchPacketForSampleIndex(n+1,t);let r=this.packetToFragmentLocation.get(e);if(r===void 0)throw Error(`Packet was not created from this track.`);return this.performFragmentedLookup(r.fragment,e=>{if(e===r.fragment){let t=e.trackData.get(this.internalTrack.id);if(r.sampleIndex+1<t.samples.length)return{sampleIndex:r.sampleIndex+1,correctSampleFound:!0}}else if(e.trackData.get(this.internalTrack.id))return{sampleIndex:0,correctSampleFound:!0};return{sampleIndex:-1,correctSampleFound:!1}},-1/0,1/0,t)}async getKeyPacket(e,t){let n=this.mapTimestampIntoTimescale(e),r=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),i=lv(r,n),a=await this.fetchPacketForSampleIndex(i,t);return!mv(r)||!this.internalTrack.demuxer.isFragmented?a:this.performFragmentedLookup(null,e=>{let t=e.trackData.get(this.internalTrack.id);if(!t)return{sampleIndex:-1,correctSampleFound:!1};let r=sh(t.presentationTimestamps,e=>t.samples[e.sampleIndex].isKeyFrame&&e.presentationTimestamp<=n);return{sampleIndex:r===-1?-1:t.presentationTimestamps[r].sampleIndex,correctSampleFound:r!==-1&&n<t.endTimestamp}},n,n,t)}async getNextKeyPacket(e,t){let n=this.packetToSampleIndex.get(e);if(n!==void 0){let e=dv(this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),n);return this.fetchPacketForSampleIndex(e,t)}let r=this.packetToFragmentLocation.get(e);if(r===void 0)throw Error(`Packet was not created from this track.`);return this.performFragmentedLookup(r.fragment,e=>{if(e===r.fragment){let t=e.trackData.get(this.internalTrack.id).samples.findIndex((e,t)=>e.isKeyFrame&&t>r.sampleIndex);if(t!==-1)return{sampleIndex:t,correctSampleFound:!0}}else{let t=e.trackData.get(this.internalTrack.id);if(t&&t.firstKeyFrameTimestamp!==null){let e=t.samples.findIndex(e=>e.isKeyFrame);return z(e!==-1),{sampleIndex:e,correctSampleFound:!0}}}return{sampleIndex:-1,correctSampleFound:!1}},-1/0,1/0,t)}async fetchPacketForSampleIndex(e,t){if(e===-1)return null;let n=uv(this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),e);if(!n)return null;let r;if(t.metadataOnly)r=L_;else{let t=this.internalTrack.demuxer.reader.requestSlice(n.sampleOffset,n.sampleSize);if(Ch(t)&&(t=await t),!t)return null;if(r=cy(t,n.sampleSize),this.internalTrack.encryptionInfo){let t=null;if(this.internalTrack.encryptionAuxInfo){let n=await gv(this.internalTrack.demuxer.reader,this.internalTrack.encryptionInfo,this.internalTrack.encryptionAuxInfo);e<n.length&&(t=n[e])}t??=_v(this.internalTrack.encryptionInfo),t&&(r=await vv(this.internalTrack,t,r,null))}}let i=(n.presentationTimestamp-this.internalTrack.editListOffset)/this.internalTrack.timescale,a=n.duration/this.internalTrack.timescale,o=new R_(r,n.isKeyFrame?`key`:`delta`,i,a,e,n.sampleSize);return this.packetToSampleIndex.set(o,e),o}async fetchPacketInFragment(e,t,n){if(t===-1)return null;let r=e.trackData.get(this.internalTrack.id).samples[t];z(r);let i;if(n.metadataOnly)i=L_;else{let t=this.internalTrack.demuxer.reader.requestSlice(r.byteOffset,r.byteSize);if(Ch(t)&&(t=await t),!t)return null;if(i=cy(t,r.byteSize),this.internalTrack.encryptionInfo){let t=r.encryption??_v(this.internalTrack.encryptionInfo);t&&(i=await vv(this.internalTrack,t,i,e))}}let a=(r.presentationTimestamp-this.internalTrack.editListOffset)/this.internalTrack.timescale,o=r.duration/this.internalTrack.timescale,s=new R_(i,r.isKeyFrame?`key`:`delta`,a,o,e.moofOffset+t,r.byteSize);return this.packetToFragmentLocation.set(s,{fragment:e,sampleIndex:t}),s}async performFragmentedLookup(e,t,n,r,i){let a=this.internalTrack.demuxer,o=null,s=null,c=-1;if(e){let{sampleIndex:n,correctSampleFound:r}=t(e);if(r)return this.fetchPacketInFragment(e,n,i);n!==-1&&(s=e,c=n)}let l=ih(this.internalTrack.fragmentLookupTable,n,e=>e.timestamp),u=l===-1?null:this.internalTrack.fragmentLookupTable[l],d=ih(this.internalTrack.fragmentPositionCache,n,e=>e.startTimestamp),f=d===-1?null:this.internalTrack.fragmentPositionCache[d],p=Math.max(u?.moofOffset??0,f?.moofOffset??0)||null,m;for(e?p===null||e.moofOffset>=p?(m=e.moofOffset+e.moofSize,o=e):m=p:m=p??0;;){if(o){let e=o.trackData.get(this.internalTrack.id);if(e&&e.startTimestamp>r)break}let e=a.reader.requestSliceRange(m,8,16);if(Ch(e)&&(e=await e),!e)break;let n=m,l=H_(e);if(!l)break;if(l.name===`moof`){o=await a.readFragment(n);let{sampleIndex:e,correctSampleFound:r}=t(o);if(r)return this.fetchPacketInFragment(o,e,i);e!==-1&&(s=o,c=e)}m=n+l.totalSize}if(u&&(!s||s.moofOffset<u.moofOffset)){let e=this.internalTrack.fragmentLookupTable[l-1];z(!e||e.timestamp<u.timestamp);let n=e?.timestamp??-1/0;return this.performFragmentedLookup(null,t,n,r,i)}return s?this.fetchPacketInFragment(s,c,i):null}},ov=class extends av{constructor(e){super(e),this.decoderConfigPromise=null,this.internalTrack=e}getType(){return`video`}getCodec(){return this.internalTrack.info.codec}getCodedWidth(){return this.internalTrack.info.width}getCodedHeight(){return this.internalTrack.info.height}getSquarePixelWidth(){return this.internalTrack.info.squarePixelWidth}getSquarePixelHeight(){return this.internalTrack.info.squarePixelHeight}getTransformationMatrix(){return[...this.internalTrack.matrix]}async getColorSpace(){let e=await this.getDecoderConfig();return e?{primaries:e.colorSpace?.primaries,transfer:e.colorSpace?.transfer,matrix:e.colorSpace?.matrix,fullRange:e.colorSpace?.fullRange}:this.internalTrack.info.colorSpace}async canBeTransparent(){return this.internalTrack.info.codec===`prores`&&(this.internalTrack.info.proresFormat===`ap4h`||this.internalTrack.info.proresFormat===`ap4x`)}async getDecoderConfig(){return this.internalTrack.info.codec?this.decoderConfigPromise??=(async()=>{if(this.internalTrack.info.codec===`avc`&&!this.internalTrack.info.codecDescription){let e=await this.getFirstPacket({});this.internalTrack.info.avcCodecInfo=e&&sg(e.data)}else if(this.internalTrack.info.codec===`hevc`&&!this.internalTrack.info.codecDescription){let e=await this.getFirstPacket({});this.internalTrack.info.hevcCodecInfo=e&&gg(e.data)}else if(this.internalTrack.info.codec===`vp9`&&(!this.internalTrack.info.vp9CodecInfo||!kg(this.internalTrack.info.vp9CodecInfo))){let e=await this.getFirstPacket({}),t=e&&Og(e.data);t&&(this.internalTrack.info.vp9CodecInfo={...this.internalTrack.info.vp9CodecInfo??t,videoFullRangeFlag:t.videoFullRangeFlag,colourPrimaries:t.colourPrimaries,transferCharacteristics:t.transferCharacteristics,matrixCoefficients:t.matrixCoefficients})}else if(this.internalTrack.info.codec===`av1`&&(!this.internalTrack.info.av1CodecInfo||!Mg(this.internalTrack.info.av1CodecInfo))){let e=await this.getFirstPacket({}),t=e&&jg(e.data);t&&(this.internalTrack.info.av1CodecInfo=t)}else if(this.internalTrack.info.codec===`prores`&&!this.internalTrack.info.proresCodecInfo){let e=await this.getFirstPacket({});this.internalTrack.info.proresCodecInfo=e&&Ng(e.data)}if(!Jm(this.internalTrack.info.colorSpace)){let e=x_(this.internalTrack.info);this.internalTrack.info.colorSpace.primaries??=e.primaries,this.internalTrack.info.colorSpace.transfer??=e.transfer,this.internalTrack.info.colorSpace.matrix??=e.matrix,this.internalTrack.info.colorSpace.fullRange??=e.fullRange}let e={codec:b_(this.internalTrack.info),codedWidth:this.internalTrack.info.width,codedHeight:this.internalTrack.info.height,description:this.internalTrack.info.codecDescription??void 0,colorSpace:this.internalTrack.info.colorSpace};return(this.internalTrack.info.width!==this.internalTrack.info.squarePixelWidth||this.internalTrack.info.height!==this.internalTrack.info.squarePixelHeight)&&(e.displayAspectWidth=this.internalTrack.info.squarePixelWidth,e.displayAspectHeight=this.internalTrack.info.squarePixelHeight),e})():null}},sv=class extends av{constructor(e){super(e),this.decoderConfigPromise=null,this.internalTrack=e}getType(){return`audio`}getCodec(){return this.internalTrack.info.codec}getNumberOfChannels(){return this.internalTrack.info.numberOfChannels}getSampleRate(){return this.internalTrack.info.sampleRate}async getDecoderConfig(){return this.internalTrack.info.codec?this.decoderConfigPromise??=(async()=>{if(this.internalTrack.info.codec===`dts`&&!this.internalTrack.info.dtsFormat){let e=await this.getFirstPacket({});this.internalTrack.info.dtsFormat=e&&n_(e.data)}return{codec:S_(this.internalTrack.info),numberOfChannels:this.internalTrack.info.numberOfChannels,sampleRate:this.internalTrack.info.sampleRate,description:this.internalTrack.info.codecDescription??void 0}})():null}},cv=(e,t)=>{if(e.presentationTimestamps){let n=ih(e.presentationTimestamps,t,e=>e.presentationTimestamp);return n===-1?-1:e.presentationTimestamps[n].sampleIndex}{let n=ih(e.sampleTimingEntries,t,e=>e.startDecodeTimestamp);if(n===-1)return-1;let r=e.sampleTimingEntries[n];return r.startIndex+Math.min(Math.floor((t-r.startDecodeTimestamp)/r.delta),r.count-1)}},lv=(e,t)=>{if(!e.keySampleIndices)return cv(e,t);if(e.presentationTimestamps){let n=ih(e.presentationTimestamps,t,e=>e.presentationTimestamp);if(n===-1)return-1;for(let t=n;t>=0;t--){let n=e.presentationTimestamps[t].sampleIndex;if(rh(e.keySampleIndices,n,e=>e)!==-1)return n}return-1}{let n=cv(e,t),r=ih(e.keySampleIndices,n,e=>e);return e.keySampleIndices[r]??-1}},uv=(e,t)=>{let n=ih(e.sampleTimingEntries,t,e=>e.startIndex),r=e.sampleTimingEntries[n];if(!r||r.startIndex+r.count<=t)return null;let i=r.startDecodeTimestamp+(t-r.startIndex)*r.delta,a=ih(e.sampleCompositionTimeOffsets,t,e=>e.startIndex),o=e.sampleCompositionTimeOffsets[a];o&&t-o.startIndex<o.count&&(i+=o.offset);let s=e.sampleSizes[Math.min(t,e.sampleSizes.length-1)],c=ih(e.sampleToChunk,t,e=>e.startSampleIndex),l=e.sampleToChunk[c];z(l);let u=l.startChunkIndex+Math.floor((t-l.startSampleIndex)/l.samplesPerChunk),d=e.chunkOffsets[u],f=l.startSampleIndex+(u-l.startChunkIndex)*l.samplesPerChunk,p=0,m=d;if(e.sampleSizes.length===1)m+=s*(t-f),p+=s*l.samplesPerChunk;else for(let n=f;n<f+l.samplesPerChunk;n++){let r=e.sampleSizes[n];n<t&&(m+=r),p+=r}let h=r.delta;if(e.presentationTimestamps){let n=e.presentationTimestampIndexMap[t];z(n!==void 0),n<e.presentationTimestamps.length-1&&(h=e.presentationTimestamps[n+1].presentationTimestamp-i)}return{presentationTimestamp:i,duration:h,sampleOffset:m,sampleSize:s,chunkOffset:d,chunkSize:p,isKeyFrame:!e.keySampleIndices||rh(e.keySampleIndices,t,e=>e)!==-1}},dv=(e,t)=>{if(!e.keySampleIndices)return t+1;let n=ih(e.keySampleIndices,t,e=>e);return e.keySampleIndices[n+1]??-1},fv=(e,t)=>{e.startTimestamp+=t,e.endTimestamp+=t;for(let n of e.samples)n.presentationTimestamp+=t;for(let n of e.presentationTimestamps)n.presentationTimestamp+=t},pv=e=>[U_(e),U_(e),W_(e),U_(e),U_(e),W_(e),U_(e),U_(e),W_(e)],mv=e=>e.sampleSizes.length===0,hv=e=>e.currentFragmentState?e.currentFragmentState.encryptionAuxInfo??={defaultSampleInfoSize:0,sampleSizes:null,sampleCount:0,offset:null,resolved:null}:e.encryptionAuxInfo??={defaultSampleInfoSize:0,sampleSizes:null,sampleCount:0,offset:null,resolved:null},gv=async(e,t,n)=>{if(n.resolved)return n.resolved;if(n.offset===null||n.sampleCount===0)throw Error(`Incomplete saiz/saio info; cannot resolve encryption data.`);let r=0;if(n.defaultSampleInfoSize>0)r=n.defaultSampleInfoSize*n.sampleCount;else{z(n.sampleSizes);for(let e=0;e<n.sampleCount;e++)r+=n.sampleSizes[e]}let i=e.requestSlice(n.offset,r);if(Ch(i)&&(i=await i),!i)throw Error(`Failed to read auxiliary encryption info.`);let a=t.defaultPerSampleIvSize;z(a!==null);let o=[];for(let e=0;e<n.sampleCount;e++){let r=n.defaultSampleInfoSize>0?n.defaultSampleInfoSize:n.sampleSizes[e],s=/* @__PURE__ */ new Uint8Array(16);a>0?s.set(cy(i,a),0):s.set(t.defaultConstantIv,0);let c=null;if(r>a){let e=ly(i);c=[];for(let t=0;t<e;t++){let e=ly(i),t=H(i);c.push({clearLen:e,protectedLen:t})}}o.push({iv:s,subsamples:c})}return n.resolved=o,o},_v=e=>e.defaultConstantIv?{iv:e.defaultConstantIv,subsamples:null}:null,vv=async(e,t,n,r)=>{z(e.encryptionInfo);let i=e.encryptionInfo;z(i.defaultKid!==null);let a=i.defaultKid,o,s=e.demuxer.decryptionKeyCache.get(a);if(s)o=await s;else{if(!e.demuxer.input._formatOptions.isobmff?.resolveKeyId)throw Error(`Encrypted media samples encountered. To decrypt them, please provide a callback for InputOptions.formatOptions.isobmff.resolveKeyId.`);let t=(async()=>{let t=e.demuxer.psshBoxes;if(r){t=[...t,...r.psshBoxes].filter(e=>e.keyIds===null||e.keyIds.includes(a));for(let e=0;e<t.length-1;e++)for(let n=e+1;n<t.length;n++)V_(t[e],t[n])&&(t.splice(n,1),n--)}let n=await e.demuxer.input._formatOptions.isobmff.resolveKeyId({keyId:a,psshBoxes:t});if(!(typeof n==`string`&&n.length===32&&$m.test(n)||n instanceof Uint8Array&&n.byteLength===16))throw TypeError(`resolveKeyId must return a 32-character hex string or a 16-byte Uint8Array containing the decryption key.`);return n instanceof Uint8Array?n:th(n)})();e.demuxer.decryptionKeyCache.set(a,t),o=await t}return i.scheme===`cenc`||i.scheme===`cens`?yv(o,i,t,n):bv(o,i,t,n)},yv=async(e,t,n,r)=>{let i=/* @__PURE__ */ new Uint8Array(16);i.set(n.iv,0);let a=await crypto.subtle.importKey(`raw`,e,{name:`AES-CTR`},!1,[`decrypt`]),o=async e=>{let t=await crypto.subtle.decrypt({name:`AES-CTR`,counter:i,length:64},a,e);return new Uint8Array(t)};if(!n.subsamples)return o(r);z(t.defaultCryptByteBlock!==null&&t.defaultSkipByteBlock!==null);let s=xv(n.subsamples,t.defaultCryptByteBlock,t.defaultSkipByteBlock),c=0;for(let e of s)for(let t of e.perSubsample)c+=t.length;let l=new Uint8Array(c),u=0;for(let e of s)for(let t of e.perSubsample)l.set(r.subarray(t.offset,t.offset+t.length),u),u+=t.length;let d=await o(l),f=new Uint8Array(r),p=0;for(let e of s)for(let t of e.perSubsample)f.set(d.subarray(p,p+t.length),t.offset),p+=t.length;return f},bv=(e,t,n,r)=>{let i=new rv;i.init({key:e,iv:n.iv});let a=t.defaultCryptByteBlock,o=t.defaultSkipByteBlock;if(z(a!==null&&o!==null),!n.subsamples){let e=new Uint8Array(r),t=Math.floor(r.length/16);for(let n=0;n<t;n++){let t=n*16;i.in.set(r.subarray(t,t+16)),i.decrypt(),e.set(i.out,t)}return e}if(a===0&&o===0)throw Error(`cbcs with subsamples requires pattern encryption.`);let s=new Uint8Array(r),c=xv(n.subsamples,a,o),l=new DataView(n.iv.buffer,n.iv.byteOffset,16);for(let e of c){i.iv[0]=l.getUint32(0,!1),i.iv[1]=l.getUint32(4,!1),i.iv[2]=l.getUint32(8,!1),i.iv[3]=l.getUint32(12,!1);for(let t of e.perSubsample){let e=t.length/16;for(let n=0;n<e;n++){let e=t.offset+n*16;i.in.set(r.subarray(e,e+16)),i.decrypt(),s.set(i.out,e)}}}return s},xv=(e,t,n)=>{let r=[],i=t!==0||n!==0,a=0;for(let o of e){a+=o.clearLen;let e=[];if(!i)o.protectedLen>0&&e.push({offset:a,length:o.protectedLen}),a+=o.protectedLen;else{let r=o.protectedLen,i=a;for(;r>0&&!(r<16*t);){let a=16*t;e.push({offset:i,length:a}),i+=a,r-=a;let o=Math.min(16*n,r);i+=o,r-=o}a+=o.protectedLen}r.push({perSubsample:e})}return r},Sv=e=>{let t=e.filePos,n=new Vh(cy(e,9));if(n.readBits(12)!==4095||(n.skipBits(1),n.readBits(2)!==0))return null;let r=n.readBits(1),i=n.readBits(2)+1,a=n.readBits(4);if(a===15)return null;n.skipBits(1);let o=n.readBits(3);if(o===0)throw Error(`ADTS frames with channel configuration 0 are not supported.`);n.skipBits(1),n.skipBits(1),n.skipBits(1),n.skipBits(1);let s=n.readBits(13);n.skipBits(11);let c=n.readBits(2)+1;if(c!==1)throw Error(`ADTS frames with more than one AAC frame are not supported.`);let l=null;return r===1?e.filePos-=2:l=n.readBits(16),{objectType:i,samplingFrequencyIndex:a,channelConfiguration:o,frameLength:s,numberOfAacFrames:c,crcCheck:l,startPos:t}};(/* @__PURE__ */ e(((e,t)=>{t.exports={}})))(),Eh();var Cv=1/0;typeof FinalizationRegistry<`u`&&new FinalizationRegistry(e=>{e()});var wv=class extends Mh{constructor(){super(),this._disposed=!1,this._refCount=0,this._usedForHls=!1,this._refFinalizationRegistry=null,this._sizePromise=null,this.onread=null,typeof FinalizationRegistry<`u`&&(this._refFinalizationRegistry=new FinalizationRegistry(e=>{e._decrementRefCount()}))}async getSizeOrNull(){if(this._disposed)throw new iy;return this._sizePromise??=(async()=>{let e=this._getFileSize();return e===void 0?(await this._read(0,1,0,Cv),e=this._getFileSize(),z(e!==void 0),e):e})()}async getSize(){if(this._disposed)throw new iy;let e=await this.getSizeOrNull();if(e===null)throw Error(`Cannot determine the size of an unsized source.`);return e}slice(e,t){if(!Number.isInteger(e)||e<0)throw TypeError(`offset must be a non-negative integer.`);if(t!==void 0&&(!Number.isInteger(t)||t<0))throw TypeError(`length, when provided, must be a non-negative integer.`);return new kv(this,e,t)}_dispatchRead(e,t){this.onread?.(e,t),this._emit(`read`,{start:e,end:t})}ref(){return new Tv(this)}_incrementRefCount(){this._refCount++}_decrementRefCount(){this._refCount--,this._refCount===0&&(this._dispose(),this._disposed=!0)}},Tv=class{constructor(e){if(this._freed=!1,e._disposed)throw Error(`Cannot ref a disposed source.`);e._incrementRefCount(),e._refFinalizationRegistry?.register(this,e,this),this._source=e}get source(){if(!this._source)throw Error(`Can't get source; ref has already been freed.`);return this._source}get freed(){return this._freed}free(){if(this._freed)throw Error(`Illegal operation: double free on SourceRef.`);let e=this.source;z(e._refCount>0),e._decrementRefCount(),e._refFinalizationRegistry?.unregister(this),this._freed=!0,this._source=null}[Symbol.dispose](){this.freed||this.free()}},Ev=class extends wv{constructor(e,t){if(typeof e!=`string`)throw TypeError(`rootPath must be a string.`);if(typeof t!=`function`)throw TypeError(`requestHandler must be a function.`);super(),this.rootPath=e,this.requestHandler=t}_resolveRequest(e){let t=this.requestHandler(e),n=e=>{if(!(e instanceof wv||e instanceof Tv))throw TypeError(`requestHandler must return or resolve to a Source or SourceRef.`);let t=e instanceof wv?e.ref():e;return t.source._usedForHls||=this._usedForHls,t};return Ch(t)?t.then(n):n(t)}},Dv=(e,t)=>e.path===t.path,Ov=class extends wv{constructor(e){if(!(e instanceof ArrayBuffer)&&!(typeof SharedArrayBuffer<`u`&&e instanceof SharedArrayBuffer)&&!ArrayBuffer.isView(e))throw TypeError(`buffer must be an ArrayBuffer, SharedArrayBuffer, or ArrayBufferView.`);super(),this._onreadCalled=!1,this._bytes=Fm(e),this._view=Im(e)}_getFileSize(){return this._bytes.byteLength}_read(){return this._onreadCalled||=(this._dispatchRead(0,this._bytes.byteLength),!0),{bytes:this._bytes,view:this._view,offset:0}}_dispose(){}};typeof FinalizationRegistry<`u`&&new FinalizationRegistry(e=>{e.cancel().catch(()=>{})});var kv=class extends wv{constructor(e,t,n){if(super(),this._ref=null,e._disposed)throw Error(`Cannot create a slice of a disposed source.`);this._baseSource=e,this._offset=t,this._length=n??null}_getFileSize(){let e=this._baseSource._getFileSize();return e===void 0?this._length===null?void 0:this._length:e===null?this._length===null?null:this._length:dh(e-this._offset,0,this._length??1/0)}_read(e,t,n,r){if(this._length!==null&&t>this._length)return null;let i=this._baseSource._read(this._offset+e,this._offset+t,this._offset+n,this._offset+r),a=e=>e?(e.offset-=this._offset,e):null;return Ch(i)?i.then(a):a(i)}_dispose(){this._ref?.free()}ref(){return this._ref??=this._baseSource.ref(),super.ref()}},Av=class{constructor(){this._isIsobmff=!1}},jv=class extends Av{constructor(){super(...arguments),this._isIsobmff=!0}async _getMajorBrand(e){let t=e._reader.requestSlice(0,12);if(Ch(t)&&(t=await t),!t)return null;t.skip(4);let n=gy(t,4);return n!==`ftyp`&&n!==`styp`?null:gy(t,4)}_createDemuxer(e){return new iv(e)}},Mv=class extends jv{async _canReadInput(e){let t=await this._getMajorBrand(e);if(t!==null)return t!==`qt `;let n=0;for(let t=0;t<10;t++){let t=e._reader.requestSlice(n,8);if(Ch(t)&&(t=await t),!t)return!1;let r=H(t),i=8;if(r===1){let t=e._reader.requestSlice(n+8,8);if(Ch(t)&&(t=await t),!t)return!1;r=py(t),i=16}if(r<i)return!1;let a=gy(t,4);if(a===`moof`||a===`sidx`)return!0;if(a===`emsg`||a===`prft`||a===`free`)n+=r;else return!1}return!1}get name(){return`MP4`}get mimeType(){return`video/mp4`}},Nv=class extends jv{async _canReadInput(e){return await this._getMajorBrand(e)===`qt `}get name(){return`QuickTime File Format`}get mimeType(){return`video/quicktime`}},Pv=/* #__PURE__ */ new Mv,Fv=/* #__PURE__ */ new Nv,Iv=(e,t)=>{if(!e||typeof e!=`object`)throw TypeError(`${t}, when provided, must be an object.`);if(e.isobmff!==void 0){if(!e.isobmff||typeof e.isobmff!=`object`)throw TypeError(`${t}.isobmff, when provided, must be an object.`);if(e.isobmff.resolveKeyId!==void 0&&typeof e.isobmff.resolveKeyId!=`function`)throw TypeError(`${t}.isobmff.resolveKeyId, when provided, must be a function.`)}if(e.hls!==void 0){if(!e.hls||typeof e.hls!=`object`)throw TypeError(`${t}.hls, when provided, must be an object.`);if(e.hls.offsetTimestampsByDateTime!==void 0&&typeof e.hls.offsetTimestampsByDateTime!=`boolean`)throw TypeError(`${t}.hls.offsetTimestampsByDateTime, when provided, must be a boolean.`)}},Lv=[],Rv=[],zv=e=>{if(!e||typeof e!=`object`)throw TypeError(`options must be an object.`);if(e.metadataOnly!==void 0&&typeof e.metadataOnly!=`boolean`)throw TypeError(`options.metadataOnly, when defined, must be a boolean.`);if(e.verifyKeyPackets!==void 0&&typeof e.verifyKeyPackets!=`boolean`)throw TypeError(`options.verifyKeyPackets, when defined, must be a boolean.`);if(e.verifyKeyPackets&&e.metadataOnly)throw TypeError(`options.verifyKeyPackets and options.metadataOnly cannot be enabled together.`);if(e.skipLiveWait!==void 0&&typeof e.skipLiveWait!=`boolean`)throw TypeError(`options.skipLiveWait, when defined, must be a boolean.`)},Bv=e=>{if(!Dh(e))throw TypeError(`timestamp must be a number.`)},Vv=(e,t,n)=>n.verifyKeyPackets?t.then(async t=>{if(!t||t.type===`delta`)return t;let n=await e.determinePacketType(t);return n&&(t.type=n),t}):t,Hv=class{constructor(e){if(!(e instanceof Uv))throw TypeError(`track must be an InputTrack.`);this._track=e}async getFirstPacket(e={}){if(zv(e),this._track.input._disposed)throw new iy;return Vv(this._track,this._track._backing.getFirstPacket(e),e)}async getFirstKeyPacket(e={}){zv(e);let t=await this.getFirstPacket(e);return t?t.type===`key`?t:this.getNextKeyPacket(t,e):null}async getPacket(e,t={}){if(Bv(e),zv(t),this._track.input._disposed)throw new iy;return Vv(this._track,this._track._backing.getPacket(e,t),t)}async getNextPacket(e,t={}){if(!(e instanceof R_))throw TypeError(`packet must be an EncodedPacket.`);if(zv(t),this._track.input._disposed)throw new iy;return Vv(this._track,this._track._backing.getNextPacket(e,t),t)}async getKeyPacket(e,t={}){if(Bv(e),zv(t),this._track.input._disposed)throw new iy;if(!t.verifyKeyPackets)return this._track._backing.getKeyPacket(e,t);let n=await this._track._backing.getKeyPacket(e,t);return n&&(z(n.type===`key`),await this._track.determinePacketType(n)===`delta`?this.getKeyPacket(n.timestamp-1/await this._track.getTimeResolution(),t):n)}async getNextKeyPacket(e,t={}){if(!(e instanceof R_))throw TypeError(`packet must be an EncodedPacket.`);if(zv(t),this._track.input._disposed)throw new iy;if(!t.verifyKeyPackets)return this._track._backing.getNextKeyPacket(e,t);let n=await this._track._backing.getNextKeyPacket(e,t);return n&&(z(n.type===`key`),await this._track.determinePacketType(n)===`delta`?this.getNextKeyPacket(n,t):n)}packets(e,t,n={}){if(e!==void 0&&!(e instanceof R_))throw TypeError(`startPacket must be an EncodedPacket.`);if(e!==void 0&&e.isMetadataOnly&&!n?.metadataOnly)throw TypeError(`startPacket can only be metadata-only if options.metadataOnly is enabled.`);if(t!==void 0&&!(t instanceof R_))throw TypeError(`endPacket must be an EncodedPacket.`);if(zv(n),this._track.input._disposed)throw new iy;let r=[],{promise:i,resolve:a}=ah(),{promise:o,resolve:s}=ah(),c=!1,l=!1,u=null,d=!1,f=[],p=()=>Math.max(2,f.length);(async()=>{let u=e??await this.getFirstPacket(n);for(;u&&!l&&!this._track.input._disposed&&!(t&&u.sequenceNumber>=t?.sequenceNumber);){if(r.length>p()){({promise:o,resolve:s}=ah()),await o;continue}r.push(u),a(),{promise:i,resolve:a}=ah(),u=await this.getNextPacket(u,n)}c=!0,a()})().catch(e=>{d||(u=e,d=!0,a())});let m=this._track;return{async next(){for(;;)if(m.input._disposed)throw new iy;else if(l)return{value:void 0,done:!0};else if(d)throw u;else if(r.length>0){let e=r.shift(),t=performance.now();for(f.push(t);f.length>0&&t-f[0]>=1e3;)f.shift();return s(),{value:e,done:!1}}else if(c)return{value:void 0,done:!0};else await i},async return(){return l=!0,s(),a(),{value:void 0,done:!0}},async throw(e){throw e},[Symbol.asyncIterator](){return this}}}},Uv=class e{constructor(e,t){this.input=e,this._backing=t}isVideoTrack(){return this instanceof Kv}isAudioTrack(){return this instanceof qv}get id(){return this._backing.getId()}get number(){return this._backing.getNumber()}async getInternalCodecId(){return this._backing.getInternalCodecId()}get internalCodecId(){return Wv(this._backing.getInternalCodecId(),`internalCodecId`,`getInternalCodecId`)}async getLanguageCode(){return this._backing.getLanguageCode()}get languageCode(){return Wv(this._backing.getLanguageCode(),`languageCode`,`getLanguageCode`)}async getName(){return this._backing.getName()}get name(){return Wv(this._backing.getName(),`name`,`getName`)}async getTimeResolution(){return this._backing.getTimeResolution()}get timeResolution(){return Wv(this._backing.getTimeResolution(),`timeResolution`,`getTimeResolution`)}async isRelativeToUnixEpoch(){return this._backing.isRelativeToUnixEpoch()}async getUnixTimeForTimestamp(e){return this._backing.getUnixTimeForTimestamp(e)}async hasUnixTimeMapping(){return await this._backing.getUnixTimeForTimestamp(await this.getFirstTimestamp())!==null}async getDisposition(){return this._backing.getDisposition()}get disposition(){return Wv(this._backing.getDisposition(),`disposition`,`getDisposition`)}async getBitrate(){return this._backing.getBitrate()}async getAverageBitrate(){return this._backing.getAverageBitrate()}async getFirstTimestamp(){return(await this._backing.getFirstPacket({metadataOnly:!0}))?.timestamp??0}async computeDuration(e){let t=await this._backing.getPacket(1/0,{metadataOnly:!0,...e});return mh((t?.timestamp??0)+(t?.duration??0),await this.getTimeResolution())}async getDurationFromMetadata(e={}){return this._backing.getDurationFromMetadata(e)}async computePacketStats(e=1/0,t){let n=new Hv(this),r=1/0,i=-1/0,a=0,o=0;for await(let s of n.packets(void 0,void 0,{metadataOnly:!0,...t})){if(a>=e&&s.timestamp>=i)break;r=Math.min(r,s.timestamp),i=Math.max(i,s.timestamp+s.duration),a++,o+=s.byteLength}return{packetCount:a,averagePacketRate:a?Number((a/(i-r)).toPrecision(16)):0,averageBitrate:a?Number((8*o/(i-r)).toPrecision(16)):0}}async isLive(){return await this._backing.getLiveRefreshInterval()!==null}async getLiveRefreshInterval(){return this._backing.getLiveRefreshInterval()}canBePairedWith(t){if(!(t instanceof e))throw TypeError(`other must be an InputTrack.`);return this.input!==t.input||this===t?!1:(this._backing.getPairingMask()&t._backing.getPairingMask())!==0n}async getPairableTracks(e){return this.input.getTracks(Zv({filter:e=>e.canBePairedWith(this)},e))}async getPairableVideoTracks(e){return this.input.getVideoTracks(Zv({filter:e=>e.canBePairedWith(this)},e))}async getPairableAudioTracks(e){return this.input.getAudioTracks(Zv({filter:e=>e.canBePairedWith(this)},e))}async getPrimaryPairableVideoTrack(e){return this.input.getPrimaryVideoTrack(Zv({filter:e=>e.canBePairedWith(this)},e))}async getPrimaryPairableAudioTrack(e){return this.input.getPrimaryAudioTrack(Zv({filter:e=>e.canBePairedWith(this)},e))}async hasPairableTrack(e){e&&=Gv(e);let t=await this.input.getTracks();for(let n of t)if(this.canBePairedWith(n)&&(!e||await e(n)))return!0;return!1}hasPairableVideoTrack(e){return e&&=Gv(e),this.hasPairableTrack(async t=>t.isVideoTrack()&&(!e||await e(t)))}hasPairableAudioTrack(e){return e&&=Gv(e),this.hasPairableTrack(async t=>t.isAudioTrack()&&(!e||await e(t)))}},Wv=(e,t,n)=>{if(Ch(e))throw Error(`'${t}' is deprecated and not available synchronously for this track. Use the preferred '${n}()' instead.`);return e},Gv=e=>{if(e!==void 0&&typeof e!=`function`)throw TypeError(`predicate, when provided, must be a function.`);return e?t=>{let n=e=>{if(typeof e!=`boolean`)throw TypeError(`predicate must return or resolve to a boolean value.`);return e},r=e(t);return Ch(r)?r.then(n):n(r)}:void 0},Kv=class extends Uv{constructor(e,t){super(e,t),this._pixelAspectRatioCache=null,this._backing=t}get type(){return`video`}async getCodec(){return this._backing.getCodec()}get codec(){return Wv(this._backing.getCodec(),`codec`,`getCodec`)}async hasOnlyKeyPackets(){return await this._backing.getHasOnlyKeyPackets?.()??await this._backing.getCodec()===`prores`}async getCodedWidth(){return this._backing.getCodedWidth()}get codedWidth(){return Wv(this._backing.getCodedWidth(),`codedWidth`,`getCodedWidth`)}async getCodedHeight(){return this._backing.getCodedHeight()}get codedHeight(){return Wv(this._backing.getCodedHeight(),`codedHeight`,`getCodedHeight`)}async getTransformationMatrix(){return this._backing.getTransformationMatrix()}async getRotation(){return Tm(await this._backing.getTransformationMatrix())}get rotation(){return Tm(Wv(this._backing.getTransformationMatrix(),`rotation`,`getRotation`))}async getFlip(){return Em(await this._backing.getTransformationMatrix())}async getSquarePixelWidth(){return this._backing.getSquarePixelWidth()}get squarePixelWidth(){return Wv(this._backing.getSquarePixelWidth(),`squarePixelWidth`,`getSquarePixelWidth`)}async getSquarePixelHeight(){return this._backing.getSquarePixelHeight()}get squarePixelHeight(){return Wv(this._backing.getSquarePixelHeight(),`squarePixelHeight`,`getSquarePixelHeight`)}async getPixelAspectRatio(){return this._pixelAspectRatioCache??=Ah({num:await this.getSquarePixelWidth()*await this.getCodedHeight(),den:await this.getSquarePixelHeight()*await this.getCodedWidth()})}get pixelAspectRatio(){return this._pixelAspectRatioCache??=Ah({num:Wv(this._backing.getSquarePixelWidth(),`pixelAspectRatio`,`getPixelAspectRatio`)*Wv(this._backing.getCodedHeight(),`pixelAspectRatio`,`getPixelAspectRatio`),den:Wv(this._backing.getSquarePixelHeight(),`pixelAspectRatio`,`getPixelAspectRatio`)*Wv(this._backing.getCodedWidth(),`pixelAspectRatio`,`getPixelAspectRatio`)})}async getDisplayWidth(){return await this._backing.getMetadataDisplayWidth?.()??(await this.getRotation()%180==0?this.getSquarePixelWidth():this.getSquarePixelHeight())}get displayWidth(){let e=this._backing.getMetadataDisplayWidth?.();if(e!==void 0){let t=Wv(e,`displayWidth`,`getDisplayWidth`);if(t!==null)return t}return Wv(Tm(Wv(this._backing.getTransformationMatrix(),`displayWidth`,`getDisplayWidth`))%180==0?this._backing.getSquarePixelWidth():this._backing.getSquarePixelHeight(),`displayWidth`,`getDisplayWidth`)}async getDisplayHeight(){return await this._backing.getMetadataDisplayHeight?.()??(await this.getRotation()%180==0?this.getSquarePixelHeight():this.getSquarePixelWidth())}get displayHeight(){let e=this._backing.getMetadataDisplayHeight?.();if(e!==void 0){let t=Wv(e,`displayHeight`,`getDisplayHeight`);if(t!==null)return t}return Wv(Tm(Wv(this._backing.getTransformationMatrix(),`displayHeight`,`getDisplayHeight`))%180==0?this._backing.getSquarePixelHeight():this._backing.getSquarePixelWidth(),`displayHeight`,`getDisplayHeight`)}async getColorSpace(){return this._backing.getColorSpace()}async hasHighDynamicRange(){let e=await this._backing.getColorSpace();return e.primaries===`bt2020`||e.primaries===`smpte432`||e.transfer===`pq`||e.transfer===`hlg`||e.matrix===`bt2020-ncl`}async canBeTransparent(){return this._backing.canBeTransparent()}async getDecoderConfig(){return this._backing.getDecoderConfig()}async getCodecParameterString(){return await this._backing.getMetadataCodecParameterString?.()??(await this._backing.getDecoderConfig())?.codec??null}async canDecode(){try{let e=await this._backing.getDecoderConfig();if(!e)return!1;let t=await this._backing.getCodec();return z(t!==null),Lv.some(n=>n.supports(t,e))?!0:typeof VideoDecoder>`u`?!1:(await VideoDecoder.isConfigSupported(e)).supported===!0}catch(e){return Fh._error(`Error during decodability check:`,e),!1}}async determinePacketType(e){if(!(e instanceof R_))throw TypeError(`packet must be an EncodedPacket.`);if(e.isMetadataOnly)throw TypeError(`packet must not be metadata-only to determine its type.`);let t=await this.getCodec();if(t===null)return null;let n=await this.getDecoderConfig();return z(n),Fg(t,n,e.data)}async computeFrameRateMetrics(e={}){if(!e||typeof e!=`object`)throw TypeError(`options must be an object.`);if(e.targetPacketCount!==void 0&&(!Dh(e.targetPacketCount)||e.targetPacketCount<0))throw TypeError(`options.targetPacketCount must be a non-negative number.`);let t=await this.getTimeResolution(),n=e.targetPacketCount??256,r=new Hv(this),i=[],a=-1/0,o=0;for await(let e of r.packets(void 0,void 0,{metadataOnly:!0})){if(i.length>=n&&e.timestamp>=a)break;i.push(e.timestamp),a=Math.max(a,e.timestamp),o++}let s=new Float64Array(i.length);for(let e=0;e<i.length;e++)s[e]=Math.round(i[e]*t);s.sort();let c=1;for(let e=1;e<s.length;e++)s[e]!==s[c-1]&&(s[c++]=s[e]);if(c<2)return{underlyingFrameRate:null,bestGuessFrameRate:t,minFrameRate:t,maxFrameRate:t,averageFrameRate:t,medianFrameRate:t,frameRateIsConstant:!0,probedPacketCount:o};let l=s.subarray(0,c),u=$v(l,t),d=u??t,f=u===null?null:t/u,p=/* @__PURE__ */ new Map,m=1/0,h=-1/0,g=0;for(let e=1;e<c;e++){let t=l[e]-l[e-1],n=f===null?t:Math.max(1,Math.round(t/f));p.set(n,(p.get(n)??0)+1),m=Math.min(m,n),h=Math.max(h,n),g+=n}let _=c-1,v=[...p.keys()].sort((e,t)=>e-t),y=_-1>>1,b=_>>1,x=0,S=0,C=0;for(let e of v)if(C+=p.get(e),x===0&&C>y&&(x=e),C>b){S=e;break}let w=(d/x+d/S)/2;return{underlyingFrameRate:u,bestGuessFrameRate:u===null?ty(w):u,minFrameRate:d/h,maxFrameRate:d/m,averageFrameRate:d*_/g,medianFrameRate:w,frameRateIsConstant:u!==null&&m===1&&h===1,probedPacketCount:o}}},qv=class extends Uv{constructor(e,t){super(e,t),this._backing=t}get type(){return`audio`}async getCodec(){return this._backing.getCodec()}get codec(){return Wv(this._backing.getCodec(),`codec`,`getCodec`)}async hasOnlyKeyPackets(){return await this._backing.getHasOnlyKeyPackets?.()??!0}async getNumberOfChannels(){return this._backing.getNumberOfChannels()}get numberOfChannels(){return Wv(this._backing.getNumberOfChannels(),`numberOfChannels`,`getNumberOfChannels`)}async getSampleRate(){return this._backing.getSampleRate()}get sampleRate(){return Wv(this._backing.getSampleRate(),`sampleRate`,`getSampleRate`)}async getDecoderConfig(){return this._backing.getDecoderConfig()}async getCodecParameterString(){return await this._backing.getMetadataCodecParameterString?.()??(await this._backing.getDecoderConfig())?.codec??null}async canDecode(){try{let e=await this._backing.getDecoderConfig();if(!e)return!1;let t=await this._backing.getCodec();return z(t!==null),Rv.some(n=>n.supports(t,e))||e.codec.startsWith(`pcm-`)?!0:typeof AudioDecoder>`u`?!1:(await AudioDecoder.isConfigSupported(e)).supported===!0}catch(e){return Fh._error(`Error during decodability check:`,e),!1}}async determinePacketType(e){if(!(e instanceof R_))throw TypeError(`packet must be an EncodedPacket.`);return await this.getCodec()===null?null:`key`}},Jv=e=>-(e??-1/0),Yv=e=>-e,Xv=e=>{if(typeof e!=`object`||!e)throw TypeError(`query must be an object.`);if(e.filter!==void 0&&typeof e.filter!=`function`)throw TypeError(`query.filter, when provided, must be a function.`);if(e.sortBy!==void 0&&typeof e.sortBy!=`function`)throw TypeError(`query.sortBy, when provided, must be a function.`);return{filter:e.filter?t=>{let n=e=>{if(typeof e!=`boolean`)throw TypeError(`query.filter must return or resolve to a boolean.`);return e},r=e.filter(t);return Ch(r)?r.then(n):n(r)}:void 0,sortBy:e.sortBy?t=>{let n=e=>{if(typeof e!=`number`&&(!Array.isArray(e)||!e.every(e=>typeof e==`number`)))throw TypeError(`query.sortBy must return or resolve to a number or an array of numbers.`);return e},r=e.sortBy(t);return Ch(r)?r.then(n):n(r)}:void 0}},Zv=(e,t)=>({filter:e?.filter||t?.filter?n=>{let r=e?.filter?.(n)??!0,i=e=>e===!1?!1:t?.filter?.(n)??!0;return Ch(r)?r.then(i):i(r)}:void 0,sortBy:e?.sortBy||t?.sortBy?n=>{let r=e?.sortBy?.(n)??[],i=t?.sortBy?.(n)??[],a=(e,t)=>[...Array.isArray(e)?e:[e],...Array.isArray(t)?t:[t]];return Ch(r)||Ch(i)?Promise.all([r,i]).then(([e,t])=>a(e,t)):a(r,i)}:void 0}),Qv=async(e,t)=>{let n=e;if(t?.filter){let r=e.map(e=>t.filter(e));if(r.some(e=>Ch(e))){let t=await Promise.all(r);n=e.filter((e,n)=>t[n])}else n=e.filter((e,t)=>r[t])}if(!t?.sortBy)return n;let r=n.map(e=>t.sortBy(e)),i=r.some(e=>Ch(e))?await Promise.all(r):r;return n.map((e,t)=>({track:e,sortValue:i[t]})).sort((e,t)=>{let n=Array.isArray(e.sortValue)?e.sortValue:[e.sortValue],r=Array.isArray(t.sortValue)?t.sortValue:[t.sortValue],i=Math.max(n.length,r.length);for(let e=0;e<i;e++){let t=n[e]??0,i=r[e]??0;if(t!==i)return t-i}return 0}).map(e=>e.track)},$v=(e,t)=>{let n=1e6,r=.98,i=1+1e-9,a=[12,15,20,24e3/1001,24,25,3e4/1001,30,48,50,6e4/1001,60,100,12e4/1001,120,144,240];if(e.length<2)return null;let o=new Float64Array(e.length-1);for(let t=1;t<e.length;t++){let n=e[t]-e[t-1];if(!(n>0))return null;o[t-1]=n}let s=o.slice();s.sort();let c=s[Math.floor(s.length*.05)];for(let e=0;e<6;e++){let e=0,t=0;for(let n of o){let r=Math.max(1,Math.round(n/c));Math.abs(n-r*c)>=i||(e+=n,t+=r)}if(t===0)return null;let n=e/t;if(Math.abs(n-c)<=1e-12*Math.max(1,c)){c=n;break}c=n}let l=0,u=0,d=0;for(let e of o){let t=Math.max(1,Math.round(e/c));Math.abs(e-t*c)>=i||(l++,u+=e,d+=t)}if(l/o.length<r)return null;c=u/d;let f=1/Math.min(d,1e3),p=Math.max(2**-52,c-f),m=c+f,h=t/m,g=t/p,_=t/c,v=null,y=1/0;for(let e of a){if(e<h||e>g)continue;let t=Math.abs(e/_-1);t<y&&(v=e,y=t)}if(v===null){let e=ey(p,m,n),r=ey(h,g,n);if(r&&(!e||r.den<e.den||r.den===e.den&&r.num<=e.num))v=r.num/r.den;else if(e)v=t*e.den/e.num;else return null}let b=t/v,x=0;for(let e of o){let t=Math.max(1,Math.round(e/b));Math.abs(e-t*b)<i&&x++}return x/o.length<r?null:v},ey=(e,t,n)=>{for(let r=1;r<=n;r++){let n=Math.floor(e*r)+1;if(n/r<t)return Ah({num:n,den:r})}return null},ty=e=>{let t=[24/1.001,30/1.001,60/1.001,120/1.001],n=[12,15,20,24,25,30,48,50,60,100,120,144,240];for(let n of t)if(Math.abs(n/e-1)<=5e-4)return n;let r=e,i=1/0;for(let t of n){let n=Math.abs(t/e-1);n<=.025&&n<i&&(r=t,i=n)}return r};Eh();var ny=class e extends Mh{get disposed(){return this._disposed}constructor(t){if(super(),this._demuxerPromise=null,this._format=null,this._trackBackingsCache=null,this._backingToTrack=/* @__PURE__ */ new Map,this._disposed=!1,this._nextSourceCacheAge=0,this._sourceRefs=[],this._sourceCache=[],this._sourceCachePromises=[],this._onFormatDetermined=null,!t||typeof t!=`object`)throw TypeError(`options must be an object.`);if(!Array.isArray(t.formats)||t.formats.some(e=>!(e instanceof Av)))throw TypeError(`options.formats must be an array of InputFormat.`);if(!(t.source instanceof wv||t.source instanceof Tv))throw TypeError(`options.source must be a Source or SourceRef.`);if(t.source instanceof wv&&t.source._disposed)throw TypeError(`options.source must not be a disposed Source.`);if(t.initInput!==void 0&&!(t.initInput instanceof e))throw TypeError(`options.initInput, when provided, must be an Input.`);t.formatOptions!==void 0&&Iv(t.formatOptions,`formatOptions`),this._formats=t.formats,this._initInput=t.initInput??null,this._formatOptions=t.formatOptions??{},this._rootRef=t.source instanceof wv?t.source.ref():t.source,this._sourceRefs.push(this._rootRef)}get _rootSource(){return this._rootRef.source}async _getSourceUncached(e){z(this._rootSource instanceof Ev);let t=await this._rootSource._resolveRequest(e);return this._emit(`source`,{source:t.source,request:e,isRoot:e.isRoot}),t}_getSourceCached(e,t=1){let n=this._sourceCache.find(n=>n.cacheGroup===t&&Dv(n.request,e));if(n)return n.age++,Promise.resolve(n.sourceRef.source.ref());let r=this._sourceCachePromises.find(n=>n.cacheGroup===t&&Dv(n.request,e));if(r)return r.promise.then(e=>e.sourceRef.source.ref());let i=(async()=>{let n=await this._getSourceUncached(e);if(Oh(this._sourceCache,e=>e.cacheGroup===t&&e.sourceRef.source._refCount===1)>=4){let e=kh(this._sourceCache,e=>e.cacheGroup===t&&e.sourceRef.source._refCount===1?e.age:1/0);z(e!==-1);let n=this._sourceCache[e];this._sourceCache.splice(e,1),n.sourceRef.free(),oh(this._sourceRefs,n.sourceRef)}this._sourceRefs.push(n);let r=this._sourceCachePromises.findIndex(t=>t.request===e);return z(r!==-1),this._sourceCachePromises.splice(r,1),{request:e,sourceRef:n,age:this._nextSourceCacheAge++,cacheGroup:t}})();return this._sourceCachePromises.push({request:e,cacheGroup:t,promise:i}),i.then(e=>{let t=e.sourceRef.source.ref();return this._sourceCache.push(e),t})}_getDemuxer(){return this._demuxerPromise??=(async()=>{this._reader=new ay(this._rootSource),this._emit(`source`,{source:this._rootSource,request:null,isRoot:!0});for(let e of this._formats)if(await e._canReadInput(this))return this._format=e,this._onFormatDetermined?.(e),e._createDemuxer(this);throw new ry})()}get source(){return this._rootSource}async getFormat(){return await this._getDemuxer(),z(this._format),this._format}async canRead(){try{return await this._getDemuxer(),!0}catch(e){if(e instanceof ry)return!1;throw e}}async getFirstTimestamp(e){e??=await this.getTracks();let t=e.filter(e=>e!==null);if(t.length===0)return 0;let n=await Promise.all(t.map(e=>e._backing.getFirstPacket({metadataOnly:!0}))),r=Math.min(...n.map(e=>e?.timestamp??1/0));return r===1/0?0:r}async computeDuration(e,t){e??=await this.getTracks();let n=e.filter(e=>e!==null);if(n.length===0)return 0;let r=await Promise.all(n.map(e=>e.computeDuration(t)));return Math.max(...r)}async getDurationFromMetadata(e,t){e??=await this.getTracks();let n=e.filter(e=>e!==null),r=(await Promise.all(n.map(e=>e.getDurationFromMetadata(t)))).filter(e=>e!==null);return r.length===0?null:Math.max(...r)}async getTracks(e){return e&&=Xv(e),Qv((await this._getTrackBackings()).map(e=>this._wrapBackingAsTrack(e)),e)}async getVideoTracks(e){return e&&=Xv(e),Qv((await this.getTracks()).filter(e=>e.isVideoTrack()),e)}async getAudioTracks(e){return e&&=Xv(e),Qv((await this.getTracks()).filter(e=>e.isAudioTrack()),e)}async getPrimaryVideoTrack(e){e&&=Xv(e);let t=Zv(e,{sortBy:async e=>[Yv((await e.getDisposition()).default),Yv(await e.hasPairableAudioTrack()),Yv(!await e.hasOnlyKeyPackets()),Jv(await e.getBitrate())]});return(await this.getVideoTracks(t))[0]??null}async getPrimaryAudioTrack(e){e&&=Xv(e);let t=await this.getPrimaryVideoTrack(),n=Zv(e,{sortBy:async e=>[Yv(!t||e.canBePairedWith(t)),Yv((await e.getDisposition()).default),Jv(await e.getBitrate())]});return(await this.getAudioTracks(n))[0]??null}async _getTrackBackings(){let e=await this._getDemuxer();return this._trackBackingsCache??=await e.getTrackBackings()}_wrapBackingAsTrack(e){let t=this._backingToTrack.get(e);if(t)return t;let n=e.getType()===`video`?new Kv(this,e):new qv(this,e);return this._backingToTrack.set(e,n),n}async getMimeType(){return(await this._getDemuxer()).getMimeType()}async getMetadataTags(){return(await this._getDemuxer()).getMetadataTags()}dispose(){if(!this._disposed){this._disposed=!0;for(let e of this._sourceRefs)e.free();this._sourceRefs.length=0,this._demuxerPromise&&this._demuxerPromise.then(e=>e.dispose()).catch(()=>{})}}[Symbol.dispose](){this.dispose()}},ry=class extends Error{constructor(e=`Input has an unsupported or unrecognizable format.`){super(e),this.name=`UnsupportedInputFormatError`}},iy=class extends Error{constructor(e=`Input has been disposed.`){super(e),this.name=`InputDisposedError`}},ay=class{constructor(e){this.source=e}get fileSize(){let e=this.source._getFileSize();if(e===void 0)throw Error(`Reading file size too early; read required first.`);return e}get fileSizeNonStrict(){return this.source._getFileSize()??null}requestSlice(e,t){if(this.source._disposed)throw new iy;if(e<0||this.fileSizeNonStrict!==null&&e+t>this.fileSizeNonStrict)return null;if(t===0){let t=/* @__PURE__ */ new Uint8Array;return new oy(t,Im(t),0,e,e)}let n=e+t,r=this.source._read(e,n,0,Cv);return Ch(r)?r.then(t=>t?new oy(t.bytes,t.view,t.offset,e,n):null):r?new oy(r.bytes,r.view,r.offset,e,n):null}requestSliceRange(e,t,n){if(this.source._disposed)throw new iy;if(e<0)return null;if(this.fileSizeNonStrict!==null)return this.requestSlice(e,dh(this.fileSizeNonStrict-e,t,n));{let r=this.requestSlice(e,n),i=r=>r||(z(this.fileSizeNonStrict!==null),this.requestSlice(e,dh(this.fileSizeNonStrict-e,t,n)));return Ch(r)?r.then(i):i(r)}}requestEntireFile(){return this.fileSizeNonStrict===null?(async()=>{let e=[],t=0;for(;;){if(e.length===1&&this.fileSizeNonStrict!==null)return this.requestSlice(0,this.fileSizeNonStrict);let n=this.requestSliceRange(t,0,1024);if(Ch(n)&&(n=await n),!n||n.length===0)break;let r=cy(n,n.length);e.push(r),t+=n.length}let n=new Uint8Array(t),r=0;for(let t of e)n.set(t,r),r+=t.length;return new oy(n,Im(n),0,0,t)})():this.requestSlice(0,this.fileSizeNonStrict)}},oy=class e{constructor(e,t,n,r,i){this.bytes=e,this.view=t,this.offset=n,this.start=r,this.end=i,this.bufferPos=r-n}static tempFromBytes(t){return new e(t,Im(t),0,0,t.length)}get length(){return this.end-this.start}get filePos(){return this.offset+this.bufferPos}set filePos(e){this.bufferPos=e-this.offset}get remainingLength(){return Math.max(this.end-this.filePos,0)}skip(e){this.bufferPos+=e}slice(t,n=this.end-t){if(t<this.start||t+n>this.end)throw RangeError(`Slicing outside of original slice.`);return new e(this.bytes,this.view,this.offset,t,t+n)}},sy=(e,t)=>{if(e.filePos<e.start||e.filePos+t>e.end)throw RangeError(`Tried reading [${e.filePos}, ${e.filePos+t}), but slice is [${e.start}, ${e.end}). This is likely an internal error, please report it alongside the file that caused it.`)},cy=(e,t)=>{sy(e,t);let n=e.bytes.subarray(e.bufferPos,e.bufferPos+t);return e.bufferPos+=t,n},V=e=>(sy(e,1),e.view.getUint8(e.bufferPos++)),ly=e=>{sy(e,2);let t=e.view.getUint16(e.bufferPos,!1);return e.bufferPos+=2,t},uy=e=>{sy(e,3);let t=lh(e.view,e.bufferPos,!1);return e.bufferPos+=3,t},dy=e=>{sy(e,2);let t=e.view.getInt16(e.bufferPos,!1);return e.bufferPos+=2,t},H=e=>{sy(e,4);let t=e.view.getUint32(e.bufferPos,!1);return e.bufferPos+=4,t},fy=e=>{sy(e,4);let t=e.view.getInt32(e.bufferPos,!1);return e.bufferPos+=4,t},py=e=>{let t=H(e),n=H(e);return t*4294967296+n},my=e=>{let t=fy(e),n=H(e);return t*4294967296+n},hy=e=>{sy(e,8);let t=e.view.getFloat64(e.bufferPos,!1);return e.bufferPos+=8,t},gy=(e,t)=>{sy(e,t);let n=``;for(let r=0;r<t;r++)n+=String.fromCharCode(e.bytes[e.bufferPos++]);return n},_y=class{constructor(e){this.mutex=new Qm,this.trackTimestampInfo=/* @__PURE__ */ new WeakMap,this.output=e}onTrackClose(e){}validateTimestamp(e,t,n){let r=this.trackTimestampInfo.get(e);if(r){if(n&&(r.maxTimestampBeforeLastKeyPacket=r.maxTimestamp),r.maxTimestampBeforeLastKeyPacket!==null&&t<r.maxTimestampBeforeLastKeyPacket)throw Error(`Timestamps cannot be smaller than the largest timestamp of the previous GOP (a GOP begins with a key packet and ends right before the next key packet). Got ${t}s, but largest timestamp is ${r.maxTimestampBeforeLastKeyPacket}s.`);r.maxTimestamp=Math.max(r.maxTimestamp,t)}else{if(!n)throw Error(`First packet must be a key packet.`);r={maxTimestamp:t,maxTimestampBeforeLastKeyPacket:null},this.trackTimestampInfo.set(e,r)}}},vy=/<(?:(\d{2}):)?(\d{2}):(\d{2}).(\d{3})>/g,yy=e=>{let t=Math.floor(e/36e5),n=Math.floor(e%36e5/6e4),r=Math.floor(e%6e4/1e3),i=e%1e3;return t.toString().padStart(2,`0`)+`:`+n.toString().padStart(2,`0`)+`:`+r.toString().padStart(2,`0`)+`.`+i.toString().padStart(3,`0`)},by=class{constructor(e){this.writer=e,this.helper=/* @__PURE__ */ new Uint8Array(8),this.helperView=new DataView(this.helper.buffer),this.offsets=/* @__PURE__ */ new WeakMap}writeU32(e){this.helperView.setUint32(0,e,!1),this.writer.write(this.helper.subarray(0,4))}writeU64(e){this.helperView.setUint32(0,Math.floor(e/2**32),!1),this.helperView.setUint32(4,e,!1),this.writer.write(this.helper.subarray(0,8))}writeAscii(e){for(let t=0;t<e.length;t++)this.helperView.setUint8(t%8,e.charCodeAt(t)),t%8==7&&this.writer.write(this.helper);e.length%8!=0&&this.writer.write(this.helper.subarray(0,e.length%8))}writeBox(e){if(this.offsets.set(e,this.writer.getPos()),e.contents&&!e.children)this.writeBoxHeader(e,e.size??e.contents.byteLength+8),this.writer.write(e.contents);else{let t=this.writer.getPos();if(this.writeBoxHeader(e,0),e.contents&&this.writer.write(e.contents),e.children)for(let t of e.children)t&&this.writeBox(t);let n=this.writer.getPos(),r=e.size??n-t;this.writer.seek(t),this.writeBoxHeader(e,r),this.writer.seek(n)}}writeBoxHeader(e,t){this.writeU32(e.largeSize?1:t),this.writeAscii(e.type),e.largeSize&&this.writeU64(t)}measureBoxHeader(e){return 8+(e.largeSize?8:0)}patchBox(e){let t=this.offsets.get(e);z(t!==void 0);let n=this.writer.getPos();this.writer.seek(t),this.writeBox(e),this.writer.seek(n)}measureBox(e){if(e.contents&&!e.children)return this.measureBoxHeader(e)+e.contents.byteLength;{let t=this.measureBoxHeader(e);if(e.contents&&(t+=e.contents.byteLength),e.children)for(let n of e.children)n&&(t+=this.measureBox(n));return t}}},U=/* #__PURE__ */ new Uint8Array(8),xy=/* #__PURE__ */ new DataView(U.buffer),Sy=e=>[(e%256+256)%256],W=e=>(xy.setUint16(0,e,!1),[U[0],U[1]]),Cy=e=>(xy.setInt16(0,e,!1),[U[0],U[1]]),wy=e=>(xy.setUint32(0,e,!1),[U[1],U[2],U[3]]),G=e=>(xy.setUint32(0,e,!1),[U[0],U[1],U[2],U[3]]),Ty=e=>(xy.setInt32(0,e,!1),[U[0],U[1],U[2],U[3]]),Ey=e=>(xy.setUint32(0,Math.floor(e/2**32),!1),xy.setUint32(4,e,!1),[U[0],U[1],U[2],U[3],U[4],U[5],U[6],U[7]]),Dy=e=>(xy.setInt32(0,Math.floor(e/2**32),!1),xy.setUint32(4,e,!1),[U[0],U[1],U[2],U[3],U[4],U[5],U[6],U[7]]),Oy=e=>(xy.setInt16(0,256*e,!1),[U[0],U[1]]),ky=e=>(xy.setInt32(0,2**16*e,!1),[U[0],U[1],U[2],U[3]]),Ay=e=>(xy.setInt32(0,2**30*e,!1),[U[0],U[1],U[2],U[3]]),jy=(e,t)=>{let n=[],r=e;do{let e=r&127;r>>=7,n.length>0&&(e|=128),n.push(e),t!==void 0&&t--}while(r>0||t);return n.reverse()},My=(e,t=!1)=>{let n=Array(e.length).fill(null).map((t,n)=>e.charCodeAt(n));return t&&n.push(0),n},Ny=e=>[ky(e[0]),ky(e[1]),Ay(e[2]),ky(e[3]),ky(e[4]),Ay(e[5]),ky(e[6]),ky(e[7]),Ay(e[8])],K=(e,t,n)=>({type:e,contents:t&&new Uint8Array(t.flat(10)),children:n}),Py=(e,t,n,r,i)=>K(e,[Sy(t),wy(n),r??[]],i),Fy=e=>e.isQuickTime?K(`ftyp`,[My(`qt `),G(512),My(`qt `)]):e.fragmented?e.cmaf?K(`ftyp`,[My(`iso5`),G(512),My(`iso5`),My(`iso6`),My(`mp41`),My(`cmfc`),My(`dash`)]):K(`ftyp`,[My(`iso5`),G(512),My(`iso5`),My(`iso6`),My(`mp41`)]):K(`ftyp`,[My(`isom`),G(512),My(`isom`),e.holdsAvc?My(`avc1`):[],My(`mp41`)]),Iy=()=>K(`styp`,[My(`iso5`),G(0),My(`iso5`),My(`iso6`),My(`mp41`),My(`cmfc`),My(`dash`)]),Ly=(e,t)=>{let n=Math.max(0,e.minWrittenTimestamp),r=Math.max(0,e.maxWrittenEndTimestamp-n);return Number.isFinite(r)||(r=0),Py(`sidx`,1,0,[G(1),G(hx),Ey(vx(n,hx)),Ey(0),W(0),W(1),G(t&2147483647),G(vx(r,hx)),G(0)])},Ry=e=>({type:`mdat`,largeSize:e}),zy=e=>({type:`free`,size:e}),By=e=>K(`moov`,void 0,[Vy(e.creationTime,e.trackDatas),...e.trackDatas.map(t=>Hy(t,e.creationTime)),e.isFragmented?jb(e.trackDatas):null,Kb(e)]),Vy=(e,t)=>{let n=Math.max(0,...t.map(e=>Math.max(0,vx(yx(e),hx)+vx(e.startTimestampOffset??0,hx)))),r=Math.max(0,...t.map(e=>e.track.id))+1,i=!Mm(e)||!Mm(n),a=i?Ey:G;return Py(`mvhd`,+i,0,[a(e),a(e),G(hx),a(n),ky(1),Oy(1),Array(10).fill(0),Ny(Cm),Array(24).fill(0),G(r)])},Hy=(e,t)=>{let n=_x(e),r=e.startTimestampOffset!==null&&e.startTimestampOffset!==0;return K(`trak`,void 0,[Uy(e,t),r?Wy(e):null,Gy(e,t),n.name===void 0?null:K(`udta`,void 0,[K(`name`,[...Bm.encode(n.name)])])])},Uy=(e,t)=>{let n=Math.max(0,vx(yx(e),hx)+vx(e.startTimestampOffset??0,hx)),r=!Mm(t)||!Mm(n),i=r?Ey:G,a;if(e.type===`video`&&e.track.metadata.transformationMatrix)a=e.track.metadata.transformationMatrix;else if(e.type===`video`){let{rotation:t,flip:n}=e.track.metadata;a=wm(Am(Dm(t??0),km(n?-1:1,1)),e.info.width,e.info.height)}else a=Cm;let o=2;e.track.metadata.disposition?.default!==!1&&(o|=1);let s=e.type===`video`?0:e.type===`audio`?1:e.type===`subtitle`?2:ch(e);return Py(`tkhd`,+r,o,[i(t),i(t),G(e.track.id),G(0),i(n),Array(8).fill(0),W(0),W(s),Oy(+(e.type===`audio`)),W(0),Ny(a),ky(e.type===`video`?e.info.width:0),ky(e.type===`video`?e.info.height:0)])},Wy=e=>{let t=e.startTimestampOffset;if(z(t!==null),t>0){let n=vx(t,hx),r=vx(yx(e),hx),i=!Mm(n)||!Mm(r),a=i?Ey:G,o=i?Dy:Ty;return K(`edts`,void 0,[Py(`elst`,+!!i,0,[G(2),a(n),o(-1),ky(1),a(r),o(0),ky(1)])])}{let n=vx(-t,e.timescale),r=Math.max(0,vx(yx(e),hx)+vx(t,hx)),i=!Nm(n)||!Mm(r),a=i?Ey:G,o=i?Dy:Ty;return K(`edts`,void 0,[Py(`elst`,+!!i,0,[G(1),a(r),o(n),ky(1)])])}},Gy=(e,t)=>K(`mdia`,void 0,[Ky(e,t),Yy(!0,qy[e.type],Jy[e.type]),Xy(e)]),Ky=(e,t)=>{let n=vx(yx(e),e.timescale),r=!Mm(t)||!Mm(n),i=r?Ey:G;return Py(`mdhd`,+r,0,[i(t),i(t),G(e.timescale),i(n),W(ox(e.track.metadata.languageCode??`und`)),W(0)])},qy={video:`vide`,audio:`soun`,subtitle:`text`},Jy={video:`MediabunnyVideoHandler`,audio:`MediabunnySoundHandler`,subtitle:`MediabunnyTextHandler`},Yy=(e,t,n,r=`\0\0\0\0`)=>Py(`hdlr`,0,0,[e?My(`mhlr`):G(0),My(t),My(r),G(0),G(0),My(n,!0)]),Xy=e=>K(`minf`,void 0,[Zy[e.type](),Qy(),tb(e)]),Zy={video:()=>Py(`vmhd`,0,1,[W(0),W(0),W(0),W(0)]),audio:()=>Py(`smhd`,0,0,[W(0),W(0)]),subtitle:()=>Py(`nmhd`,0,0)},Qy=()=>K(`dinf`,void 0,[$y()]),$y=()=>Py(`dref`,0,0,[G(1)],[eb()]),eb=()=>Py(`url `,0,1),tb=e=>{let t=e.compositionTimeOffsetTable.length>1||e.compositionTimeOffsetTable.some(e=>e.sampleCompositionTimeOffset!==0);return K(`stbl`,void 0,[nb(e),wb(e),t?kb(e):null,t?Ab(e):null,Eb(e),Db(e),Ob(e),Tb(e)])},nb=e=>{let t;if(e.type===`video`)t=rb(ex(e.track.source._codec,e.info.decoderConfig.codec),e);else if(e.type===`audio`){let n=nx(e.track.source._codec,e.info.decoderConfig.codec,e.muxer.isQuickTime);z(n),t=db(n,e)}else e.type===`subtitle`&&(t=Sb(ix[e.track.source._codec],e));return z(t),Py(`stsd`,0,0,[G(1)],[t])},rb=(e,t)=>K(e,[[,,,,,,].fill(0),W(1),W(0),W(0),Array(12).fill(0),W(t.info.width),W(t.info.height),G(4718592),G(4718592),G(0),W(1),Sy(10),My(`Mediabunny`),Array(21).fill(0),W(t.info.hasAlphaChannel?32:24),Cy(65535)],[tx[t.track.source._codec]?.(t)??null,ab(t),Ym(t.info.decoderConfig.colorSpace)?null:ob(t),ib(t)]),ib=e=>e.avgBitrate===0&&e.maxBitrate===0?null:K(`btrt`,[G(0),G(e.maxBitrate),G(e.avgBitrate)]),ab=e=>e.info.pixelAspectRatio.num===e.info.pixelAspectRatio.den?null:K(`pasp`,[G(e.info.pixelAspectRatio.num),G(e.info.pixelAspectRatio.den)]),ob=e=>{let t=e.info.decoderConfig.colorSpace;return K(`colr`,[My(e.muxer.isQuickTime?`nclc`:`nclx`),W(t?.primaries==null?2:Hm[t.primaries]),W(t?.transfer==null?2:Wm[t.transfer]),W(t?.matrix==null?2:Km[t.matrix]),e.muxer.isQuickTime?[]:Sy(!!t?.fullRange<<7)])},sb=e=>e.info.decoderConfig&&K(`avcC`,[...Fm(e.info.decoderConfig.description)]),cb=e=>e.info.decoderConfig&&K(`hvcC`,[...Fm(e.info.decoderConfig.description)]),lb=e=>{if(!e.info.decoderConfig)return null;let t=e.info.decoderConfig,n=t.codec.split(`.`),r=Number(n[1]),i=Number(n[2]),a=Number(n[3]),o=n[4]?Number(n[4]):1,s=n[8]?Number(n[8]):Number(t.colorSpace?.fullRange??0),c=(a<<4)+(o<<1)+s,l=n[5]?Number(n[5]):t.colorSpace?.primaries?Hm[t.colorSpace.primaries]:1,u=n[6]?Number(n[6]):t.colorSpace?.transfer?Wm[t.colorSpace.transfer]:1,d=n[7]?Number(n[7]):t.colorSpace?.matrix?Km[t.colorSpace.matrix]:1;return Py(`vpcC`,1,0,[Sy(r),Sy(i),Sy(c),Sy(l),Sy(u),Sy(d),W(0)])},ub=e=>K(`av1C`,y_(e.info.decoderConfig.codec)),db=(e,t)=>{let n=0,r,i=16,a=l_.includes(t.track.source._codec);if(a){let e=t.track.source._codec,{sampleSize:r}=T_(e);i=8*r,i>16&&(n=1)}if(t.muxer.isQuickTime&&(n=1),n===0)r=[[,,,,,,].fill(0),W(1),W(n),W(0),G(0),W(t.info.numberOfChannels),W(i),W(0),W(0),W(t.info.sampleRate<2**16?t.info.sampleRate:0),W(0)];else{let e=a?0:-2;r=[[,,,,,,].fill(0),W(1),W(n),W(0),G(0),W(t.info.numberOfChannels),W(Math.min(i,16)),Cy(e),W(0),W(t.info.sampleRate<2**16?t.info.sampleRate:0),W(0),a?[G(1),G(i/8),G(t.info.numberOfChannels*i/8)]:[G(0),G(0),G(0)],G(2)]}return K(e,r,[rx(t.track.source._codec,t.muxer.isQuickTime)?.(t)??null,ib(t)])},fb=e=>{let t;switch(e.track.source._codec){case`aac`:t=64;break;case`mp3`:t=107;break;case`vorbis`:t=221;break;default:throw Error(`Unhandled audio codec: ${e.track.source._codec}`)}let n=[...Sy(t),...Sy(21),...wy(0),...G(e.maxBitrate),...G(e.avgBitrate)];if(e.info.decoderConfig.description){let t=Fm(e.info.decoderConfig.description);n=[...n,...Sy(5),...jy(t.byteLength),...t]}return n=[...W(1),...Sy(0),...Sy(4),...jy(n.length),...n,...Sy(6),...Sy(1),...Sy(2)],n=[...Sy(3),...jy(n.length),...n],Py(`esds`,0,0,n)},pb=e=>K(`wave`,void 0,[mb(e),hb(e),K(`\0\0\0\0`)]),mb=e=>K(`frma`,[My(nx(e.track.source._codec,e.info.decoderConfig.codec,e.muxer.isQuickTime))]),hb=e=>{let{littleEndian:t}=T_(e.track.source._codec);return K(`enda`,[W(+t)])},gb=e=>{let t=e.info.numberOfChannels,n=3840,r=e.info.sampleRate,i=0,a=0,o=/* @__PURE__ */ new Uint8Array,s=e.info.decoderConfig?.description;if(s){z(s.byteLength>=18);let e=Pg(Fm(s));t=e.outputChannelCount,n=e.preSkip,r=e.inputSampleRate,i=e.outputGain,a=e.channelMappingFamily,e.channelMappingTable&&(o=e.channelMappingTable)}return K(`dOps`,[Sy(0),Sy(t),W(n),G(r),Cy(i),Sy(a),...o])},_b=e=>{let t=e.info.decoderConfig?.description;return z(t),Py(`dfLa`,0,0,[...Fm(t).subarray(4)])},vb=e=>{let{littleEndian:t,sampleSize:n}=T_(e.track.source._codec);return Py(`pcmC`,0,0,[Sy(+t),Sy(8*n)])},yb=e=>{z(e.info.primingPacket);let t=Rg(e.info.primingPacket.data);if(!t)throw Error(`Couldn't extract AC-3 frame info from the audio packet. Ensure the packets contain valid AC-3 sync frames (as specified in ETSI TS 102 366).`);let n=/* @__PURE__ */ new Uint8Array(3),r=new Vh(n);return r.writeBits(2,t.fscod),r.writeBits(5,t.bsid),r.writeBits(3,t.bsmod),r.writeBits(3,t.acmod),r.writeBits(1,t.lfeon),r.writeBits(5,t.bitRateCode),r.writeBits(5,0),K(`dac3`,[...n])},bb=e=>{z(e.info.primingPacket);let t=Bg(e.info.primingPacket.data);if(!t)throw Error(`Couldn't extract E-AC-3 frame info from the audio packet. Ensure the packets contain valid E-AC-3 sync frames (as specified in ETSI TS 102 366).`);let n=16;for(let e of t.substreams)n+=23,e.numDepSub>0?n+=9:n+=1;let r=Math.ceil(n/8),i=new Uint8Array(r),a=new Vh(i);a.writeBits(13,t.dataRate),a.writeBits(3,t.substreams.length-1);for(let e of t.substreams)a.writeBits(2,e.fscod),a.writeBits(5,e.bsid),a.writeBits(1,0),a.writeBits(1,0),a.writeBits(3,e.bsmod),a.writeBits(3,e.acmod),a.writeBits(1,e.lfeon),a.writeBits(3,0),a.writeBits(4,e.numDepSub),e.numDepSub>0?a.writeBits(9,e.chanLoc):a.writeBits(1,0);return K(`dec3`,[...i])},xb=e=>{z(e.info.primingPacket);let t=t_(e.info.primingPacket.data);if(!t)throw Error(`Couldn't extract DTS frame info from the audio packet. Ensure the packets contain valid DTS frames as specified in ETSI TS 102 114.`);return K(`ddts`,[...o_(t)])},Sb=(e,t)=>K(e,[[,,,,,,].fill(0),W(1)],[ax[t.track.source._codec](t),ib(t)]),Cb=e=>K(`vttC`,[...Bm.encode(e.info.config.description)]),wb=e=>Py(`stts`,0,0,[G(e.timeToSampleTable.length),e.timeToSampleTable.map(e=>[G(e.sampleCount),G(e.sampleDelta)])]),Tb=e=>{if(e.samples.every(e=>e.type===`key`))return null;let t=[...e.samples.entries()].filter(([,e])=>e.type===`key`);return Py(`stss`,0,0,[G(t.length),t.map(([e])=>G(e+1))])},Eb=e=>Py(`stsc`,0,0,[G(e.compactlyCodedChunkTable.length),e.compactlyCodedChunkTable.map(e=>[G(e.firstChunk),G(e.samplesPerChunk),G(1)])]),Db=e=>{if(e.type===`audio`&&e.info.requiresPcmTransformation){let{sampleSize:t}=T_(e.track.source._codec);return Py(`stsz`,0,0,[G(t*e.info.numberOfChannels),G(e.samples.reduce((t,n)=>t+vx(n.duration,e.timescale),0))])}return Py(`stsz`,0,0,[G(0),G(e.samples.length),e.samples.map(e=>G(e.size))])},Ob=e=>e.finalizedChunks.length>0&&jm(e.finalizedChunks).offset>=2**32?Py(`co64`,0,0,[G(e.finalizedChunks.length),e.finalizedChunks.map(e=>Ey(e.offset))]):Py(`stco`,0,0,[G(e.finalizedChunks.length),e.finalizedChunks.map(e=>G(e.offset))]),kb=e=>Py(`ctts`,1,0,[G(e.compositionTimeOffsetTable.length),e.compositionTimeOffsetTable.map(e=>[G(e.sampleCount),Ty(e.sampleCompositionTimeOffset)])]),Ab=e=>{let t=1/0,n=-1/0,r=1/0,i=-1/0;z(e.compositionTimeOffsetTable.length>0),z(e.samples.length>0);for(let r=0;r<e.compositionTimeOffsetTable.length;r++){let i=e.compositionTimeOffsetTable[r];t=Math.min(t,i.sampleCompositionTimeOffset),n=Math.max(n,i.sampleCompositionTimeOffset)}for(let t=0;t<e.samples.length;t++){let n=e.samples[t];r=Math.min(r,vx(n.timestamp,e.timescale)),i=Math.max(i,vx(n.timestamp+n.duration,e.timescale))}let a=Math.max(-t,0);return i>=2**31?null:Py(`cslg`,0,0,[Ty(a),Ty(t),Ty(n),Ty(r),Ty(i)])},jb=e=>K(`mvex`,void 0,e.map(Mb)),Mb=e=>Py(`trex`,0,0,[G(e.track.id),G(1),G(0),G(0),G(0)]),Nb=(e,t)=>K(`moof`,void 0,[Pb(e),...t.map(Ib)]),Pb=e=>Py(`mfhd`,0,0,[G(e)]),Fb=e=>{let t=0,n=0,r=e.type===`delta`;return n|=+r,t|=r?1:2,t<<24|n<<16|0},Ib=e=>K(`traf`,void 0,[Lb(e),Rb(e),zb(e)]),Lb=e=>{z(e.currentChunk);let t=0;t|=8,t|=16,t|=32,t|=131072;let n=e.currentChunk.samples[1]??e.currentChunk.samples[0],r={duration:n.timescaleUnitsToNextSample,size:n.size,flags:Fb(n)};return Py(`tfhd`,0,t,[G(e.track.id),G(r.duration),G(r.size),G(r.flags)])},Rb=e=>(z(e.currentChunk),Py(`tfdt`,1,0,[Ey(vx(e.currentChunk.startTimestamp,e.timescale))])),zb=e=>{z(e.currentChunk);let t=e.currentChunk.samples.map(e=>e.timescaleUnitsToNextSample),n=e.currentChunk.samples.map(e=>e.size),r=e.currentChunk.samples.map(Fb),i=e.currentChunk.samples.map(t=>vx(t.timestamp-t.decodeTimestamp,e.timescale)),a=new Set(t),o=new Set(n),s=new Set(r),c=new Set(i),l=s.size===2&&r[0]!==r[1],u=a.size>1,d=o.size>1,f=!l&&s.size>1,p=c.size>1||[...c].some(e=>e!==0),m=0;return m|=1,m|=4*l,m|=256*u,m|=512*d,m|=1024*f,m|=2048*p,Py(`trun`,1,m,[G(e.currentChunk.samples.length),G(e.currentChunk.offset-e.currentChunk.moofOffset||0),l?G(r[0]):[],e.currentChunk.samples.map((e,a)=>[u?G(t[a]):[],d?G(n[a]):[],f?G(r[a]):[],p?Ty(i[a]):[]])])},Bb=e=>K(`mfra`,void 0,[...e.map(Vb),Hb()]),Vb=e=>Py(`tfra`,1,0,[G(e.track.id),G(63),G(e.finalizedChunks.length),e.finalizedChunks.map(t=>[Ey(vx(t.samples[0].timestamp,e.timescale)),Ey(t.moofOffset),G(t.trafIndex+1),G(1),G(1)])]),Hb=()=>Py(`mfro`,0,0,[G(0)]),Ub=()=>K(`vtte`),Wb=(e,t,n,r,i)=>K(`vttc`,void 0,[i===null?null:K(`vsid`,[Ty(i)]),n===null?null:K(`iden`,[...Bm.encode(n)]),t===null?null:K(`ctim`,[...Bm.encode(yy(t))]),r===null?null:K(`sttg`,[...Bm.encode(r)]),K(`payl`,[...Bm.encode(e)])]),Gb=e=>K(`vtta`,[...Bm.encode(e)]),Kb=e=>{let t=[],n=e.format._options.metadataFormat??`auto`,r=e.output._metadataTags;if(n===`mdir`||n===`auto`&&!e.isQuickTime){let e=Zb(r);e&&t.push(e)}else if(n===`mdta`){let e=Qb(r);e&&t.push(e)}else(n===`udta`||n===`auto`&&e.isQuickTime)&&qb(t,e.output._metadataTags);return t.length===0?null:K(`udta`,void 0,t)},qb=(e,t)=>{for(let{key:n,value:r}of wh(t))switch(n){case`title`:e.push(Jb(`©nam`,r));break;case`description`:e.push(Jb(`©des`,r));break;case`artist`:e.push(Jb(`©ART`,r));break;case`album`:e.push(Jb(`©alb`,r));break;case`albumArtist`:e.push(Jb(`albr`,r));break;case`genre`:e.push(Jb(`©gen`,r));break;case`date`:e.push(Jb(`©day`,r.toISOString().slice(0,10)));break;case`comment`:e.push(Jb(`©cmt`,r));break;case`lyrics`:e.push(Jb(`©lyr`,r));break;case`raw`:break;case`discNumber`:case`discsTotal`:case`trackNumber`:case`tracksTotal`:case`images`:break;default:ch(n)}if(t.raw)for(let n in t.raw){let r=t.raw[n];r==null||n.length!==4||e.some(e=>e.type===n)||(typeof r==`string`?e.push(Jb(n,r)):r instanceof Uint8Array&&e.push(K(n,Array.from(r))))}},Jb=(e,t)=>{let n=Bm.encode(t);return K(e,[W(n.length),W(ox(`und`)),Array.from(n)])},Yb={"image/jpeg":13,"image/png":14,"image/bmp":27},Xb=(e,t)=>{let n=[];for(let{key:r,value:i}of wh(e))switch(r){case`title`:n.push({key:t?`title`:`©nam`,value:$b(i)});break;case`description`:n.push({key:t?`description`:`©des`,value:$b(i)});break;case`artist`:n.push({key:t?`artist`:`©ART`,value:$b(i)});break;case`album`:n.push({key:t?`album`:`©alb`,value:$b(i)});break;case`albumArtist`:n.push({key:t?`album_artist`:`aART`,value:$b(i)});break;case`comment`:n.push({key:t?`comment`:`©cmt`,value:$b(i)});break;case`genre`:n.push({key:t?`genre`:`©gen`,value:$b(i)});break;case`lyrics`:n.push({key:t?`lyrics`:`©lyr`,value:$b(i)});break;case`date`:n.push({key:t?`date`:`©day`,value:$b(i.toISOString().slice(0,10))});break;case`images`:for(let e of i)e.kind===`coverFront`&&n.push({key:`covr`,value:K(`data`,[G(Yb[e.mimeType]??0),G(0),Array.from(e.data)])});break;case`trackNumber`:if(t){let t=e.tracksTotal===void 0?i.toString():`${i}/${e.tracksTotal}`;n.push({key:`track`,value:$b(t)})}else n.push({key:`trkn`,value:K(`data`,[G(0),G(0),W(0),W(i),W(e.tracksTotal??0),W(0)])});break;case`discNumber`:t||n.push({key:`disc`,value:K(`data`,[G(0),G(0),W(0),W(i),W(e.discsTotal??0),W(0)])});break;case`tracksTotal`:case`discsTotal`:break;case`raw`:break;default:ch(r)}if(e.raw)for(let r in e.raw){let i=e.raw[r];i==null||!t&&r.length!==4||n.some(e=>e.key===r)||(typeof i==`string`?n.push({key:r,value:$b(i)}):i instanceof Uint8Array?n.push({key:r,value:K(`data`,[G(0),G(0),Array.from(i)])}):i instanceof Ih&&n.push({key:r,value:K(`data`,[G(Yb[i.mimeType]??0),G(0),Array.from(i.data)])}))}return n},Zb=e=>{let t=Xb(e,!1);return t.length===0?null:Py(`meta`,0,0,void 0,[Yy(!1,`mdir`,``,`appl`),K(`ilst`,void 0,t.map(e=>K(e.key,void 0,[e.value])))])},Qb=e=>{let t=Xb(e,!0);return t.length===0?null:K(`meta`,void 0,[Yy(!1,`mdta`,``),Py(`keys`,0,0,[G(t.length)],t.map(e=>K(`mdta`,[...Bm.encode(e.key)]))),K(`ilst`,void 0,t.map((e,t)=>K(String.fromCharCode(...G(t+1)),void 0,[e.value])))])},$b=e=>K(`data`,[G(1),G(0),...Bm.encode(e)]),ex=(e,t)=>{switch(e){case`avc`:return t.startsWith(`avc3`)?`avc3`:`avc1`;case`hevc`:return`hvc1`;case`vp8`:return`vp08`;case`vp9`:return`vp09`;case`av1`:return`av01`;case`prores`:return t}},tx={avc:sb,hevc:cb,vp8:lb,vp9:lb,av1:ub,prores:null},nx=(e,t,n)=>{switch(e){case`aac`:return`mp4a`;case`mp3`:return`mp4a`;case`opus`:return`Opus`;case`vorbis`:return`mp4a`;case`flac`:return`fLaC`;case`ulaw`:return`ulaw`;case`alaw`:return`alaw`;case`pcm-u8`:return`raw `;case`pcm-s8`:return`sowt`;case`ac3`:return`ac-3`;case`eac3`:return`ec-3`;case`dts`:return t}if(n)switch(e){case`pcm-s16`:return`sowt`;case`pcm-s16be`:return`twos`;case`pcm-s24`:return`in24`;case`pcm-s24be`:return`in24`;case`pcm-s32`:return`in32`;case`pcm-s32be`:return`in32`;case`pcm-f32`:return`fl32`;case`pcm-f32be`:return`fl32`;case`pcm-f64`:return`fl64`;case`pcm-f64be`:return`fl64`}else switch(e){case`pcm-s16`:return`ipcm`;case`pcm-s16be`:return`ipcm`;case`pcm-s24`:return`ipcm`;case`pcm-s24be`:return`ipcm`;case`pcm-s32`:return`ipcm`;case`pcm-s32be`:return`ipcm`;case`pcm-f32`:return`fpcm`;case`pcm-f32be`:return`fpcm`;case`pcm-f64`:return`fpcm`;case`pcm-f64be`:return`fpcm`}},rx=(e,t)=>{switch(e){case`aac`:return fb;case`mp3`:return fb;case`opus`:return gb;case`vorbis`:return fb;case`flac`:return _b;case`ac3`:return yb;case`eac3`:return bb;case`dts`:return xb}if(t)switch(e){case`pcm-s24`:return pb;case`pcm-s24be`:return pb;case`pcm-s32`:return pb;case`pcm-s32be`:return pb;case`pcm-f32`:return pb;case`pcm-f32be`:return pb;case`pcm-f64`:return pb;case`pcm-f64be`:return pb}else switch(e){case`pcm-s16`:return vb;case`pcm-s16be`:return vb;case`pcm-s24`:return vb;case`pcm-s24be`:return vb;case`pcm-s32`:return vb;case`pcm-s32be`:return vb;case`pcm-f32`:return vb;case`pcm-f32be`:return vb;case`pcm-f64`:return vb;case`pcm-f64be`:return vb}return null},ix={webvtt:`wvtt`},ax={webvtt:Cb},ox=e=>{z(e.length===3);let t=0;for(let n=0;n<3;n++)t<<=5,t+=e.charCodeAt(n)-96;return t},sx=class{constructor(e,t){if(this.finalized=!1,this.started=!1,this.pos=0,this.trackedWrites=null,this.trackedStart=-1,this.trackedEnd=-1,e._writerAcquired)throw Error(`Can't have multiple Writers for the same Target.`);this.target=e,e._setMonotonicity(t),e._writerAcquired=!0}start(){z(!this.started),this.target._start(),this.started=!0}write(e){z(this.started&&!this.finalized),this.maybeTrackWrites(e),this.target._write(e,this.pos),this.pos+=e.byteLength}seek(e){this.pos=e}getPos(){return this.pos}async flush(){return z(this.started&&!this.finalized),this.target._flush()}async finalize(){z(this.started&&!this.finalized),await this.target._finalize(),this.finalized=!0}maybeTrackWrites(e){if(!this.trackedWrites)return;let t=this.getPos();if(t<this.trackedStart){if(t+e.byteLength<=this.trackedStart)return;e=e.subarray(this.trackedStart-t),t=0}let n=t+e.byteLength-this.trackedStart,r=this.trackedWrites.byteLength;for(;r<n;)r*=2;if(r!==this.trackedWrites.byteLength){let e=new Uint8Array(r);e.set(this.trackedWrites,0),this.trackedWrites=e}this.trackedWrites.set(e,t-this.trackedStart),this.trackedEnd=Math.max(this.trackedEnd,t+e.byteLength)}startTrackingWrites(){this.trackedWrites=/* @__PURE__ */ new Uint8Array(1024),this.trackedStart=this.getPos(),this.trackedEnd=this.trackedStart}stopTrackingWrites(){if(!this.trackedWrites)throw Error(`Internal error: Can't get tracked writes since nothing was tracked.`);let e={data:this.trackedWrites.subarray(0,this.trackedEnd-this.trackedStart),start:this.trackedStart,end:this.trackedEnd};return this.trackedWrites=null,e}},cx=class extends Mh{constructor(){super(...arguments),this._writerAcquired=!1,this._monotonicity=null,this.onwrite=null}_setMonotonicity(e){this._monotonicity!==!1&&(this._monotonicity=e)}_dispatchWrite(e,t){this.onwrite?.(e,t),this._emit(`write`,{start:e,end:t})}slice(e){if(!Number.isInteger(e)||e<0)throw TypeError(`offset must be a non-negative integer.`);return new px(this,e)}},lx=2**16,ux=2**32,dx=class extends cx{constructor(e={}){if(super(),this.buffer=null,this._maxPos=0,!e||typeof e!=`object`)throw TypeError(`BufferTarget options, when provided, must be an object.`);if(e.onFinalize!==void 0&&typeof e.onFinalize!=`function`)throw TypeError(`options.onFinalize, when provided, must be a function.`);if(this._options=e,this._supportsResize=`resize`in/* @__PURE__ */ new ArrayBuffer(0),this._supportsResize)try{this._buffer=new ArrayBuffer(lx,{maxByteLength:ux})}catch{this._buffer=new ArrayBuffer(lx),this._supportsResize=!1}else this._buffer=new ArrayBuffer(lx);this._bytes=new Uint8Array(this._buffer)}_ensureSize(e){let t=this._buffer.byteLength;for(;t<e;)t*=2;if(t!==this._buffer.byteLength){if(t>ux)throw Error(`ArrayBuffer exceeded maximum size of ${ux} bytes. Please consider using another target.`);if(this._supportsResize)this._buffer.resize(t);else{let e=new ArrayBuffer(t),n=new Uint8Array(e);n.set(this._bytes,0),this._buffer=e,this._bytes=n}}}_start(){}_write(e,t){this._ensureSize(t+e.byteLength),this._bytes.set(e,t),this._maxPos=Math.max(this._maxPos,t+e.byteLength),this._dispatchWrite(t,t+e.byteLength)}async _flush(){}async _finalize(){this.buffer=this._buffer.slice(0,this._maxPos),this._options.onFinalize&&await this._options.onFinalize(this.buffer),this._emit(`finalized`)}async _close(){}_getSlice(e,t){return this._bytes.slice(e,t)}},fx=class extends cx{_start(){}_write(e,t){this._dispatchWrite(t,t+e.byteLength)}async _flush(){}async _finalize(){this._emit(`finalized`)}async _close(){}},px=class extends cx{constructor(e,t){super(),this._baseTarget=e,this._offset=t}_start(){}_write(e,t){this._baseTarget._write(e,this._offset+t),this._dispatchWrite(t,t+e.byteLength)}_flush(){return this._baseTarget._flush()}async _finalize(){this._emit(`finalized`)}async _close(){}_setMonotonicity(e){super._setMonotonicity(e),this._baseTarget._setMonotonicity(e)}},mx=class{constructor(e,t){if(this.rootPath=e,this.getTarget=t,typeof e!=`string`)throw TypeError(`rootPath must be a string.`);if(typeof t!=`function`)throw TypeError(`getTarget must be a function.`)}},hx=57600,gx=2082844800,_x=e=>{let t={},n=e.track;return n.metadata.name!==void 0&&(t.name=n.metadata.name),t},vx=(e,t,n=!0)=>{let r=e*t;return n?Math.round(r):r},yx=e=>{if(e.samples.length===0)return 0;let t=1/0,n=-1/0;for(let r=0;r<e.samples.length;r++){let i=e.samples[r];i.timestamp<t&&(t=i.timestamp),i.timestamp+i.duration>n&&(n=i.timestamp+i.duration)}return t===1/0?0:n-t},bx=class extends _y{constructor(e,t){super(e),this.writer=null,this.boxWriter=null,this.initWriter=null,this.initBoxWriter=null,this.auxTarget=new dx,this.auxWriter=new sx(this.auxTarget,!1),this.auxBoxWriter=new by(this.auxWriter),this.mdat=null,this.ftypSize=null,this.trackDatas=[],this.allTracksKnown=ah(),this.creationTime=Math.floor(Date.now()/1e3)+gx,this.finalizedChunks=[],this.wroteFragmentedHeader=!1,this.nextFragmentNumber=1,this.maxWrittenTimestamp=-1/0,this.minWrittenTimestamp=1/0,this.maxWrittenEndTimestamp=-1/0,this.segmentHeaderSize=null,this.format=t,this.formatOptions={...t._options},this.isQuickTime=t instanceof Ax,this.isCmaf=t instanceof kx,this.minimumFragmentDuration=this.formatOptions.minimumFragmentDuration??(t instanceof kx?1/0:1),this.auxWriter.start()}async start(){let e=await this.mutex.acquire();if(this.isCmaf?(this.fastStart=`fragmented`,this.isFragmented=!0):(this.writer=await this.output._getRootWriter(e=>this.formatOptions.fastStart===void 0?e instanceof dx:this.formatOptions.fastStart===`fragmented`),this.boxWriter=new by(this.writer),this.fastStart=this.formatOptions.fastStart??(this.writer.target instanceof dx&&`in-memory`),this.isFragmented=this.fastStart===`fragmented`),this.isCmaf){if(!this.output._hasInitTarget())throw Error(`CMAF outputs require the initTarget field in OutputOptions to be set; the init segment will be written to it.`);let e=new sx(await this.output._getInitTarget(),!0);e.start(),this.initWriter=e,this.initBoxWriter=new by(e)}let t=this.output.tracks.some(e=>e.isVideoTrack()&&e.source._codec===`avc`);{let e=this.initBoxWriter??this.boxWriter;if(z(e),this.formatOptions.onFtyp&&e.writer.startTrackingWrites(),e.writeBox(Fy({isQuickTime:this.isQuickTime,holdsAvc:t,fragmented:this.isFragmented,cmaf:this.isCmaf})),this.formatOptions.onFtyp){let{data:t,start:n}=e.writer.stopTrackingWrites();this.formatOptions.onFtyp(t,n)}this.ftypSize=e.writer.getPos(),this.isCmaf&&await this.initWriter.flush()}if(this.fastStart!==`in-memory`){if(this.fastStart===`reserve`){for(let e of this.output.tracks)if(e.metadata.maximumPacketCount===void 0)throw Error(`All tracks must specify maximumPacketCount in their metadata when using fastStart: 'reserve'.`)}else this.isFragmented||(z(this.writer),z(this.boxWriter),this.formatOptions.onMdat&&this.writer.startTrackingWrites(),this.mdat=Ry(!0),this.boxWriter.writeBox(this.mdat))}await this.writer?.flush();for(let e of this.output.tracks)e.isVideoTrack()&&e.metadata.decoderConfig?this.getVideoTrackData(e,e.metadata.primingPacket??null,{decoderConfig:e.metadata.decoderConfig}):e.isAudioTrack()&&e.metadata.decoderConfig&&this.getAudioTrackData(e,e.metadata.primingPacket??null,{decoderConfig:e.metadata.decoderConfig});e()}allTracksAreKnown(){for(let e of this.output.tracks)if(!e.source._closed&&!this.trackDatas.some(t=>t.track===e))return!1;return!0}async getMimeType(){await this.allTracksKnown.promise;let e=this.trackDatas.map(e=>e.type===`video`||e.type===`audio`?e.info.decoderConfig.codec:{webvtt:`wvtt`}[e.track.source._codec]);return z_({isQuickTime:this.isQuickTime,hasVideo:this.trackDatas.some(e=>e.type===`video`),hasAudio:this.trackDatas.some(e=>e.type===`audio`),codecStrings:e})}getVideoTrackData(e,t,n){let r=this.trackDatas.find(t=>t.track===e);if(r)return r;M_(n,e.source._codec),z(n),z(n.decoderConfig);let i={...n.decoderConfig};z(i.codedWidth!==void 0),z(i.codedHeight!==void 0);let a=!1;if(e.source._codec===`avc`&&!i.description){if(!t)throw Error(`No AVC description provided; you must therefore provide a priming packet.`);let e=sg(t.data);if(!e)throw Error(`Couldn't extract an AVCDecoderConfigurationRecord from the AVC packet. Make sure the packets are in Annex B format (as specified in ITU-T-REC-H.264) when not providing a description, or provide a description (must be an AVCDecoderConfigurationRecord as specified in ISO 14496-15) and ensure the packets are in AVCC format.`);i.description=cg(e),a=!0}else if(e.source._codec===`hevc`&&!i.description){if(!t)throw Error(`No HEVC description provided; you must therefore provide a priming packet.`);let e=gg(t.data);if(!e)throw Error(`Couldn't extract an HEVCDecoderConfigurationRecord from the HEVC packet. Make sure the packets are in Annex B format (as specified in ITU-T-REC-H.265) when not providing a description, or provide a description (must be an HEVCDecoderConfigurationRecord as specified in ISO 14496-15) and ensure the packets are in HEVC format.`);i.description=wg(e),a=!0}let o=yh(1/(e.metadata.frameRate??57600),1e6).den,s=i.displayAspectWidth,c=i.displayAspectHeight,l=s===void 0||c===void 0?{num:1,den:1}:Ah({num:s*i.codedHeight,den:c*i.codedWidth}),u=i.codec===`ap4h`||i.codec===`ap4x`,d={muxer:this,track:e,type:`video`,info:{width:i.codedWidth,height:i.codedHeight,pixelAspectRatio:l,decoderConfig:i,requiresAnnexBTransformation:a,hasAlphaChannel:u},timescale:o,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,startTimestampOffset:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[],closed:!1,avgBitrate:e.source._nominalBitrate??e.metadata.averageBitrate??0,maxBitrate:e.source._nominalBitrate??e.metadata.bitrate??0};return this.trackDatas.push(d),this.trackDatas.sort((e,t)=>e.track.id-t.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),d}getAudioTrackData(e,t,n){let r=this.trackDatas.find(t=>t.track===e);if(r)return r;P_(n,e.source._codec),z(n),z(n.decoderConfig);let i={...n.decoderConfig},a=!1;if(e.source._codec===`aac`&&!i.description){if(!t)throw Error(`No AAC description provided; you must therefore provide a priming packet.`);let e=Sv(oy.tempFromBytes(t.data));if(!e)throw Error(`Couldn't parse ADTS header from the AAC packet. Make sure the packets are in ADTS format (as specified in ISO 13818-7) when not providing a description, or provide a description (must be an AudioSpecificConfig as specified in ISO 14496-3) and ensure the packets are raw AAC data.`);let n=Hh[e.samplingFrequencyIndex],r=Uh[e.channelConfiguration];if(n===void 0||r===void 0)throw Error(`Invalid ADTS frame header.`);i.description=qh({objectType:e.objectType,outputSampleRate:n,outputNumberOfChannels:r}),a=!0}if(!t){if(e.source._codec===`ac3`||e.source._codec===`eac3`)throw Error(`AC-3/E-AC-3 require a priming packet.`);if(e.source._codec===`dts`)throw Error(`DTS requires a priming packet.`)}let o={muxer:this,track:e,type:`audio`,info:{numberOfChannels:n.decoderConfig.numberOfChannels,sampleRate:n.decoderConfig.sampleRate,decoderConfig:i,requiresPcmTransformation:!this.isFragmented&&l_.includes(e.source._codec),expectedNextPcmPacketTimestamp:null,requiresAdtsStripping:a,primingPacket:t},timescale:i.sampleRate,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,startTimestampOffset:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[],closed:!1,avgBitrate:e.source._nominalBitrate??e.metadata.averageBitrate??0,maxBitrate:e.source._nominalBitrate??e.metadata.bitrate??0};return this.trackDatas.push(o),this.trackDatas.sort((e,t)=>e.track.id-t.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),o}getSubtitleTrackData(e,t){let n=this.trackDatas.find(t=>t.track===e);if(n)return n;F_(t),z(t),z(t.config);let r={muxer:this,track:e,type:`subtitle`,info:{config:t.config},timescale:1e3,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,startTimestampOffset:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[],closed:!1,avgBitrate:e.source._nominalBitrate??e.metadata.averageBitrate??0,maxBitrate:e.source._nominalBitrate??e.metadata.bitrate??0,lastCueEndTimestamp:null,cueQueue:[],nextSourceId:0,cueToSourceId:/* @__PURE__ */ new WeakMap};return this.trackDatas.push(r),this.trackDatas.sort((e,t)=>e.track.id-t.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),r}async addEncodedVideoPacket(e,t,n){let r=await this.mutex.acquire();try{let r=this.getVideoTrackData(e,t,n),i=t.data;if(r.info.requiresAnnexBTransformation){let e=[...tg(i)].map(e=>i.subarray(e.offset,e.offset+e.length));if(e.length===0)throw Error(`Failed to transform packet data. Make sure all packets are provided in Annex B format, as specified in ITU-T-REC-H.264 and ITU-T-REC-H.265.`);i=og(e,4)}this.validateTimestamp(r.track,t.timestamp,t.type===`key`);let a=this.createSampleForTrack(r,i,t.timestamp,t.duration,t.type);await this.registerSample(r,a)}finally{r()}}async addEncodedAudioPacket(e,t,n){let r=await this.mutex.acquire();try{let r=this.getAudioTrackData(e,t,n),i=t.data;if(r.info.requiresAdtsStripping){let e=Sv(oy.tempFromBytes(i));if(!e)throw Error(`Expected ADTS frame, didn't get one.`);let t=e.crcCheck===null?7:9;i=i.subarray(t)}this.validateTimestamp(r.track,t.timestamp,t.type===`key`);let a=t.timestamp,o=t.duration;if(r.info.requiresPcmTransformation){let e=T_(r.info.decoderConfig.codec).sampleSize*r.info.numberOfChannels;if(o=i.byteLength/e/r.info.sampleRate,r.info.expectedNextPcmPacketTimestamp!==null){let e=a-r.info.expectedNextPcmPacketTimestamp;if(e<.01)a=r.info.expectedNextPcmPacketTimestamp;else{let t=await this.padWithSilence(r,r.info.expectedNextPcmPacketTimestamp,e);a=r.info.expectedNextPcmPacketTimestamp+t}}r.info.expectedNextPcmPacketTimestamp=a+o}let s=this.createSampleForTrack(r,i,a,o,t.type);await this.registerSample(r,s)}finally{r()}}async padWithSilence(e,t,n){let r=vx(n,e.timescale);if(n=r/e.timescale,r>0){let{sampleSize:i,silentValue:a}=T_(e.info.decoderConfig.codec),o=r*e.info.numberOfChannels,s=new Uint8Array(i*o).fill(a),c=this.createSampleForTrack(e,new Uint8Array(s.buffer),t,n,`key`);await this.registerSample(e,c)}return n}async addSubtitleCue(e,t,n){let r=await this.mutex.acquire();try{let r=this.getSubtitleTrackData(e,n);this.validateTimestamp(r.track,t.timestamp,!0),e.source._codec===`webvtt`&&(r.cueQueue.push(t),await this.processWebVTTCues(r,t.timestamp))}finally{r()}}async processWebVTTCues(e,t){for(;e.cueQueue.length>0;){e.lastCueEndTimestamp??=Math.min(0,e.cueQueue[0].timestamp);let n=/* @__PURE__ */ new Set([]);for(let r of e.cueQueue)z(r.timestamp<=t),z(e.lastCueEndTimestamp<=r.timestamp+r.duration),n.add(Math.max(r.timestamp,e.lastCueEndTimestamp)),n.add(r.timestamp+r.duration);let r=[...n].sort((e,t)=>e-t),i=r[0],a=r[1]??i;if(t<a)break;if(e.lastCueEndTimestamp<i){this.auxWriter.seek(0);let t=Ub();this.auxBoxWriter.writeBox(t);let n=this.auxTarget._getSlice(0,this.auxWriter.getPos()),r=this.createSampleForTrack(e,n,e.lastCueEndTimestamp,i-e.lastCueEndTimestamp,`key`);await this.registerSample(e,r),e.lastCueEndTimestamp=i}this.auxWriter.seek(0);for(let t=0;t<e.cueQueue.length;t++){let n=e.cueQueue[t];if(n.timestamp>=a)break;vy.lastIndex=0;let r=vy.test(n.text),o=n.timestamp+n.duration,s=e.cueToSourceId.get(n);if(s===void 0&&a<o&&(s=e.nextSourceId++,e.cueToSourceId.set(n,s)),n.notes){let e=Gb(n.notes);this.auxBoxWriter.writeBox(e)}let c=Wb(n.text,r?i:null,n.identifier??null,n.settings??null,s??null);this.auxBoxWriter.writeBox(c),o===a&&e.cueQueue.splice(t--,1)}let o=this.auxTarget._getSlice(0,this.auxWriter.getPos()),s=this.createSampleForTrack(e,o,i,a-i,`key`);await this.registerSample(e,s),e.lastCueEndTimestamp=a}}createSampleForTrack(e,t,n,r,i){return{timestamp:n,decodeTimestamp:n,duration:r,data:t,size:t.byteLength,type:i,timescaleUnitsToNextSample:vx(r,e.timescale)}}processTimestamps(e,t){if(e.timestampProcessingQueue.length===0)return;if(e.type===`audio`&&e.info.requiresPcmTransformation){z(!this.isFragmented),e.startTimestampOffset??=e.timestampProcessingQueue[0].timestamp;let t=0;for(let n=0;n<e.timestampProcessingQueue.length;n++){let r=e.timestampProcessingQueue[n],i=vx(r.duration,e.timescale);t+=i}if(e.timeToSampleTable.length===0)e.timeToSampleTable.push({sampleCount:t,sampleDelta:1});else{let n=jm(e.timeToSampleTable);n.sampleCount+=t}e.timestampProcessingQueue.length=0;return}let n=e.timestampProcessingQueue.map(e=>e.timestamp).sort((e,t)=>e-t);this.isFragmented?e.startTimestampOffset??=Math.min(n[0],0):e.startTimestampOffset??=n[0];for(let t=0;t<e.timestampProcessingQueue.length;t++){let r=e.timestampProcessingQueue[t];r.decodeTimestamp=n[t];let i=vx(r.timestamp-r.decodeTimestamp,e.timescale),a=vx(r.duration,e.timescale);if(e.lastTimescaleUnits!==null){z(e.lastSample);let t=vx(r.decodeTimestamp,e.timescale,!1),n=Math.round(t-e.lastTimescaleUnits);if(z(n>=0),e.lastTimescaleUnits+=n,e.lastSample.timescaleUnitsToNextSample=n,!this.isFragmented){let t=jm(e.timeToSampleTable);if(z(t),t.sampleCount===1){t.sampleDelta=n;let r=e.timeToSampleTable[e.timeToSampleTable.length-2];r&&r.sampleDelta===n&&(r.sampleCount++,e.timeToSampleTable.pop(),t=r)}else t.sampleDelta!==n&&(t.sampleCount--,e.timeToSampleTable.push(t={sampleCount:1,sampleDelta:n}));t.sampleDelta===a?t.sampleCount++:e.timeToSampleTable.push({sampleCount:1,sampleDelta:a});let r=jm(e.compositionTimeOffsetTable);z(r),r.sampleCompositionTimeOffset===i?r.sampleCount++:e.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:i})}}else e.lastTimescaleUnits=vx(r.decodeTimestamp,e.timescale,!1),this.isFragmented||(e.timeToSampleTable.push({sampleCount:1,sampleDelta:a}),e.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:i}));e.lastSample=r}if(e.timestampProcessingQueue.length=0,z(e.lastSample),z(e.lastTimescaleUnits!==null),t!==void 0&&e.lastSample.timescaleUnitsToNextSample===0){z(t.type===`key`);let n=vx(t.timestamp,e.timescale,!1),r=Math.round(n-e.lastTimescaleUnits);e.lastSample.timescaleUnitsToNextSample=r}}async registerSample(e,t){t.type===`key`&&this.processTimestamps(e,t),e.timestampProcessingQueue.push(t),this.isFragmented?(e.sampleQueue.push(t),await this.interleaveSamples()):this.fastStart===`reserve`?await this.registerSampleFastStartReserve(e,t):await this.addSampleToTrack(e,t)}async addSampleToTrack(e,t){if(!this.isFragmented&&(e.samples.push(t),this.fastStart===`reserve`)){let t=e.track.metadata.maximumPacketCount;if(z(t!==void 0),e.samples.length>t)throw Error(`Track #${e.track.id} has already reached the maximum packet count (${t}). Either add less packets or increase the maximum packet count.`)}let n=!1;if(!e.currentChunk)n=!0;else{e.currentChunk.startTimestamp=Math.min(e.currentChunk.startTimestamp,t.timestamp);let r=t.timestamp-e.currentChunk.startTimestamp;if(this.isFragmented){let i=this.trackDatas.every(n=>{if(e===n)return t.type===`key`;let r=n.sampleQueue[0];return r?r.type===`key`:n.closed});r>=this.minimumFragmentDuration&&i&&t.timestamp>this.maxWrittenTimestamp&&(n=!0,await this.finalizeFragment())}else n=r>=.5}n&&(e.currentChunk&&await this.finalizeCurrentChunk(e),e.currentChunk={startTimestamp:t.timestamp,samples:[],offset:null,moofOffset:null,trafIndex:null}),z(e.currentChunk),e.currentChunk.samples.push(t),this.isFragmented&&(this.maxWrittenTimestamp=Math.max(this.maxWrittenTimestamp,t.timestamp),this.maxWrittenEndTimestamp=Math.max(this.maxWrittenEndTimestamp,t.timestamp+t.duration),this.minWrittenTimestamp=Math.min(this.minWrittenTimestamp,t.timestamp))}async finalizeCurrentChunk(e){if(z(!this.isFragmented),z(this.writer),!e.currentChunk)return;e.finalizedChunks.push(e.currentChunk),this.finalizedChunks.push(e.currentChunk);let t=e.currentChunk.samples.length;if(e.type===`audio`&&e.info.requiresPcmTransformation&&(t=e.currentChunk.samples.reduce((t,n)=>t+vx(n.duration,e.timescale),0)),(e.compactlyCodedChunkTable.length===0||jm(e.compactlyCodedChunkTable).samplesPerChunk!==t)&&e.compactlyCodedChunkTable.push({firstChunk:e.finalizedChunks.length,samplesPerChunk:t}),this.fastStart===`in-memory`){e.currentChunk.offset=0;return}e.currentChunk.offset=this.writer.getPos();for(let t of e.currentChunk.samples)z(t.data),this.writer.write(t.data),t.data=null;await this.writer.flush()}async interleaveSamples(e=!1){if(z(this.isFragmented),e||this.allTracksAreKnown())outer:for(;;){let t=null,n=1/0;for(let r of this.trackDatas){if(!e&&r.sampleQueue.length===0&&!r.closed)break outer;r.sampleQueue.length>0&&r.sampleQueue[0].timestamp<n&&(t=r,n=r.sampleQueue[0].timestamp)}if(!t)break;let r=t.sampleQueue.shift();await this.addSampleToTrack(t,r)}}async finalizeFragment(e=!this.isCmaf){if(z(this.isFragmented),!this.wroteFragmentedHeader){this.wroteFragmentedHeader=!0;let e=this.initBoxWriter??this.boxWriter;z(e),this.formatOptions.onMoov&&e.writer.startTrackingWrites(),this.ensureOneEnabledTrack();let t=By(this);if(e.writeBox(t),this.formatOptions.onMoov){let{data:t,start:n}=e.writer.stopTrackingWrites();this.formatOptions.onMoov(t,n)}if(this.isCmaf){z(this.initWriter),await this.initWriter.flush(),await this.initWriter.finalize(),this.writer=await this.output._getRootWriter(!0),this.boxWriter=new by(this.writer);let e=this.boxWriter.measureBox(Iy()),t=this.boxWriter.measureBox(Ly(this,0));this.segmentHeaderSize=e+t,this.writer.seek(this.segmentHeaderSize)}}z(this.writer),z(this.boxWriter);let t=this.trackDatas.filter(e=>e.currentChunk);if(t.length===0){e&&await this.writer.flush();return}let n=this.nextFragmentNumber++,r=Nb(n,t),i=this.writer.getPos(),a=i+this.boxWriter.measureBox(r),o=a+8,s=1/0;for(let e=0;e<t.length;e++){let n=t[e];z(n.currentChunk),z(n.startTimestampOffset!==null),n.currentChunk.offset=o,n.currentChunk.moofOffset=i,n.currentChunk.trafIndex=e,n.currentChunk.startTimestamp-=n.startTimestampOffset;for(let e of n.currentChunk.samples)o+=e.size,e.timestamp-=n.startTimestampOffset,e.decodeTimestamp-=n.startTimestampOffset;s=Math.min(s,n.currentChunk.startTimestamp)}let c=o-a,l=c>=2**32;if(l)for(let e of t)e.currentChunk.offset+=8;this.formatOptions.onMoof&&this.writer.startTrackingWrites();let u=Nb(n,t);if(this.boxWriter.writeBox(u),this.formatOptions.onMoof){let{data:e,start:t}=this.writer.stopTrackingWrites();this.formatOptions.onMoof(e,t,s)}z(this.writer.getPos()===a),this.formatOptions.onMdat&&this.writer.startTrackingWrites();let d=Ry(l);d.size=c,this.boxWriter.writeBox(d),this.writer.seek(a+(l?16:8));for(let e of t)for(let t of e.currentChunk.samples)this.writer.write(t.data),t.data=null;if(this.formatOptions.onMdat){let{data:e,start:t}=this.writer.stopTrackingWrites();this.formatOptions.onMdat(e,t)}for(let e of t)e.finalizedChunks.push(e.currentChunk),this.finalizedChunks.push(e.currentChunk),e.currentChunk=null;e&&await this.writer.flush()}async registerSampleFastStartReserve(e,t){this.allTracksAreKnown()?(this.mdat||await this.createFastStartReserveMdat(),await this.addSampleToTrack(e,t)):e.sampleQueue.push(t)}async createFastStartReserveMdat(){z(this.writer),z(this.boxWriter),this.ensureOneEnabledTrack();let e=By(this),t=this.boxWriter.measureBox(e)+this.computeSampleTableSizeUpperBound()+4096;z(this.ftypSize!==null),this.writer.seek(this.ftypSize+t),this.formatOptions.onMdat&&this.writer.startTrackingWrites(),this.mdat=Ry(!0),this.boxWriter.writeBox(this.mdat);for(let e of this.trackDatas){for(let t of e.sampleQueue)await this.addSampleToTrack(e,t);e.sampleQueue.length=0}}computeSampleTableSizeUpperBound(){z(this.fastStart===`reserve`);let e=0;for(let t of this.trackDatas){let n=t.track.metadata.maximumPacketCount;z(n!==void 0),e+=8*Math.ceil(2/3*n),e+=4*n,e+=8*Math.ceil(2/3*n),e+=12*Math.ceil(2/3*n),e+=4*n,e+=8*n}return e}async onTrackClose(e){let t=await this.mutex.acquire(),n=this.trackDatas.find(t=>t.track===e);n&&(n.closed=!0,n.type===`subtitle`&&e.source._codec===`webvtt`&&await this.processWebVTTCues(n,1/0),this.processTimestamps(n)),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),this.isFragmented&&await this.interleaveSamples(),t()}ensureOneEnabledTrack(){for(let e of[`video`,`audio`,`subtitle`]){let t=this.trackDatas.filter(t=>t.type===e);if(t.length!==0&&!t.some(e=>e.track.metadata.disposition?.default!==!1)){let e=t[0];e.track.metadata.disposition={...e.track.metadata.disposition,default:!0}}}}async forceFragmentFinalization(){z(this.isFragmented);let e=await this.mutex.acquire();try{for(let e of this.trackDatas)e.type===`subtitle`&&e.track.source._codec===`webvtt`&&await this.processWebVTTCues(e,1/0),this.processTimestamps(e);await this.interleaveSamples(!0),await this.finalizeFragment()}finally{e()}}async finalize(){let e=await this.mutex.acquire();this.allTracksKnown.resolve(),this.ensureOneEnabledTrack(),!this.mdat&&this.fastStart===`reserve`&&await this.createFastStartReserveMdat();for(let e of this.trackDatas)e.closed=!0,e.type===`subtitle`&&e.track.source._codec===`webvtt`&&await this.processWebVTTCues(e,1/0),this.processTimestamps(e);if(this.isFragmented)await this.interleaveSamples(!0),await this.finalizeFragment(!1);else for(let e of this.trackDatas){await this.finalizeCurrentChunk(e);let t=yx(e);if(t>0){let n=0;for(let t of e.samples)n+=t.size;e.avgBitrate=Math.round(8*n/t)}else e.avgBitrate=0;let n=0,r=0,i=0;for(let t=0;t<e.samples.length;t++){let a=e.samples[t];for(r+=a.size;a.decodeTimestamp-e.samples[n].decodeTimestamp>=1;)r-=e.samples[n].size,n++;i=Math.max(i,r)}if(e.maxBitrate=8*i,e.startTimestampOffset!==null)for(let t=0;t<e.samples.length;t++){let n=e.samples[t];n.timestamp-=e.startTimestampOffset,n.decodeTimestamp-=e.startTimestampOffset}}if(z(this.writer),z(this.boxWriter),this.fastStart===`in-memory`){this.mdat=Ry(!1);let e;for(let t=0;t<2;t++){let t=By(this),n=this.boxWriter.measureBox(t);e=this.boxWriter.measureBox(this.mdat);let r=this.writer.getPos()+n+e;for(let t of this.finalizedChunks){t.offset=r;for(let{data:n}of t.samples)z(n),r+=n.byteLength,e+=n.byteLength}if(r<2**32)break;e>=2**32&&(this.mdat.largeSize=!0)}this.formatOptions.onMoov&&this.writer.startTrackingWrites();let t=By(this);if(this.boxWriter.writeBox(t),this.formatOptions.onMoov){let{data:e,start:t}=this.writer.stopTrackingWrites();this.formatOptions.onMoov(e,t)}this.formatOptions.onMdat&&this.writer.startTrackingWrites(),this.mdat.size=e,this.boxWriter.writeBox(this.mdat);for(let e of this.finalizedChunks)for(let t of e.samples)z(t.data),this.writer.write(t.data),t.data=null;if(this.formatOptions.onMdat){let{data:e,start:t}=this.writer.stopTrackingWrites();this.formatOptions.onMdat(e,t)}}else if(this.isFragmented){if(this.isCmaf){let e=this.segmentHeaderSize===null?0:this.writer.getPos()-this.segmentHeaderSize;this.writer.seek(0),this.boxWriter.writeBox(Iy()),this.boxWriter.writeBox(Ly(this,e))}else{let e=this.writer.getPos(),t=Bb(this.trackDatas);this.boxWriter.writeBox(t);let n=this.writer.getPos()-e;this.writer.seek(this.writer.getPos()-4),this.boxWriter.writeU32(n)}}else{z(this.mdat);let e=this.boxWriter.offsets.get(this.mdat);z(e!==void 0);let t=this.writer.getPos()-e;if(this.mdat.size=t,this.mdat.largeSize=t>=2**32,this.boxWriter.patchBox(this.mdat),this.formatOptions.onMdat){let{data:e,start:t}=this.writer.stopTrackingWrites();this.formatOptions.onMdat(e,t)}let n=By(this);if(this.fastStart===`reserve`){z(this.ftypSize!==null),this.writer.seek(this.ftypSize),this.formatOptions.onMoov&&this.writer.startTrackingWrites(),this.boxWriter.writeBox(n);let e=this.boxWriter.offsets.get(this.mdat)-this.writer.getPos();this.boxWriter.writeBox(zy(e))}else this.formatOptions.onMoov&&this.writer.startTrackingWrites(),this.boxWriter.writeBox(n);if(this.formatOptions.onMoov){let{data:e,start:t}=this.writer.stopTrackingWrites();this.formatOptions.onMoov(e,t)}}e()}},xx=class{constructor(){this._connectedTrack=null,this._closingPromise=null,this._closed=!1,this._nominalBitrate=null}_ensureValidAdd(){if(!this._connectedTrack)throw Error(`Source is not connected to an output track.`);if(this._connectedTrack.output.state===`canceled`)throw Error(`Output has been canceled.`);if(this._connectedTrack.output.state===`finalizing`||this._connectedTrack.output.state===`finalized`)throw Error(`Output has been finalized.`);if(this._connectedTrack.output.state===`pending`)throw Error(`Output has not started.`);if(this._closed)throw Error(`Source is closed.`)}async _start(){}async _flushAndClose(e){}close(){if(this._closingPromise)return;let e=this._connectedTrack;if(!e)throw Error(`Cannot call close without connecting the source to an output track.`);if(e.output.state===`pending`)throw Error(`Cannot call close before output has been started.`);this._closingPromise=(async()=>{await this._flushAndClose(!1),this._closed=!0,e.output.state!==`finalizing`&&e.output.state!==`finalized`&&e.output._muxer.onTrackClose(e)})()}async _flushOrWaitForOngoingClose(e){return this._closingPromise??=(async()=>{await this._flushAndClose(e),this._closed=!0})()}},Sx=class extends xx{constructor(e){if(super(),this._connectedTrack=null,!c_.includes(e))throw TypeError(`Invalid video codec '${e}'. Must be one of: ${c_.join(`, `)}.`);this._codec=e}},Cx=class extends xx{constructor(e){if(super(),this._connectedTrack=null,!d_.includes(e))throw TypeError(`Invalid audio codec '${e}'. Must be one of: ${d_.join(`, `)}.`);this._codec=e}},wx=class extends Cx{constructor(e){super(e)}add(e,t){if(!(e instanceof R_))throw TypeError(`packet must be an EncodedPacket.`);if(e.isMetadataOnly)throw TypeError(`Metadata-only packets cannot be added.`);if(t!==void 0&&(!t||typeof t!=`object`))throw TypeError(`meta, when provided, must be an object.`);return this._ensureValidAdd(),this._connectedTrack.output._muxer.addEncodedAudioPacket(this._connectedTrack,e,t)}},Tx=class extends xx{constructor(e){if(super(),this._connectedTrack=null,!f_.includes(e))throw TypeError(`Invalid subtitle codec '${e}'. Must be one of: ${f_.join(`, `)}.`);this._codec=e}},Ex=class{get supportsVideoRotationMetadata(){return this.supportsVideoTransformationMetadata}getSupportedVideoCodecs(){return this.getSupportedCodecs().filter(e=>c_.includes(e))}getSupportedAudioCodecs(){return this.getSupportedCodecs().filter(e=>d_.includes(e))}getSupportedSubtitleCodecs(){return this.getSupportedCodecs().filter(e=>f_.includes(e))}_codecUnsupportedHint(e){return``}_isFragmentedIsobmff(){return!1}},Dx=class extends Ex{constructor(e={}){if(!e||typeof e!=`object`)throw TypeError(`options must be an object.`);if(e.fastStart!==void 0&&![!1,`in-memory`,`reserve`,`fragmented`].includes(e.fastStart))throw TypeError(`options.fastStart, when provided, must be false, 'in-memory', 'reserve', or 'fragmented'.`);if(e.minimumFragmentDuration!==void 0&&(!Dh(e.minimumFragmentDuration)||e.minimumFragmentDuration<0))throw TypeError(`options.minimumFragmentDuration, when provided, must be a non-negative number.`);if(e.onFtyp!==void 0&&typeof e.onFtyp!=`function`)throw TypeError(`options.onFtyp, when provided, must be a function.`);if(e.onMoov!==void 0&&typeof e.onMoov!=`function`)throw TypeError(`options.onMoov, when provided, must be a function.`);if(e.onMdat!==void 0&&typeof e.onMdat!=`function`)throw TypeError(`options.onMdat, when provided, must be a function.`);if(e.onMoof!==void 0&&typeof e.onMoof!=`function`)throw TypeError(`options.onMoof, when provided, must be a function.`);if(e.metadataFormat!==void 0&&![`mdir`,`mdta`,`udta`,`auto`].includes(e.metadataFormat))throw TypeError(`options.metadataFormat, when provided, must be either 'auto', 'mdir', 'mdta', or 'udta'.`);super(),this._options=e}getSupportedTrackCounts(){let e=2**32-1;return{video:{min:0,max:e},audio:{min:0,max:e},subtitle:{min:0,max:e},total:{min:0,max:e}}}get supportsVideoTransformationMetadata(){return!0}get supportsTimestampedMediaData(){return!0}get negativeTimestampSupport(){return`full`}_createMuxer(e){return new bx(e,this)}_isFragmentedIsobmff(){return this._options.fastStart===`fragmented`}},Ox=class extends Dx{constructor(e){super(e)}get _name(){return`MP4`}get fileExtension(){return`.mp4`}get mimeType(){return`video/mp4`}getSupportedCodecs(){return[...c_,...u_,`pcm-s16`,`pcm-s16be`,`pcm-s24`,`pcm-s24be`,`pcm-s32`,`pcm-s32be`,`pcm-f32`,`pcm-f32be`,`pcm-f64`,`pcm-f64be`,...f_]}_codecUnsupportedHint(e){return new Ax().getSupportedCodecs().includes(e)?` Switching to MOV will grant support for this codec.`:``}},kx=class extends Dx{constructor(e){super(e)}get _name(){return`CMAF`}get fileExtension(){return`.m4s`}get mimeType(){return`video/mp4`}getSupportedCodecs(){return[...c_,...u_,`pcm-s16`,`pcm-s16be`,`pcm-s24`,`pcm-s24be`,`pcm-s32`,`pcm-s32be`,`pcm-f32`,`pcm-f32be`,`pcm-f64`,`pcm-f64be`,...f_]}},Ax=class extends Dx{constructor(e){super(e)}get _name(){return`MOV`}get fileExtension(){return`.mov`}get mimeType(){return`video/quicktime`}getSupportedCodecs(){return[...c_,...d_]}_codecUnsupportedHint(e){return new Ox().getSupportedCodecs().includes(e)?` Switching to MP4 will grant support for this codec.`:``}},jx=[`video`,`audio`,`subtitle`],Mx=class e{constructor(e,t,n,r,i){this.id=e,this.output=t,this.type=n,this.source=r,this.metadata=i}isVideoTrack(){return this.type===`video`}isAudioTrack(){return this.type===`audio`}isSubtitleTrack(){return this.type===`subtitle`}canBePairedWith(t){if(!(t instanceof e))throw TypeError(`other must be an OutputTrack.`);if(this===t)return!1;let n=jh(this.metadata.group),r=jh(t.metadata.group);for(let e of n)if(this.type!==t.type&&r.some(t=>e===t)||r.some(t=>e._pairedGroups.has(t)))return!0;return!1}},Nx=class extends Mx{constructor(e,t,n,r){super(e,t,`video`,n,r)}},Px=class extends Mx{constructor(e,t,n,r){super(e,t,`audio`,n,r)}},Fx=class extends Mx{constructor(e,t,n,r){super(e,t,`subtitle`,n,r)}},Ix=class e{constructor(){this._pairedGroups=/* @__PURE__ */ new Set}pairWith(t){if(!(t instanceof e))throw TypeError(`other must be an OutputTrackGroup.`);if(this===t)throw TypeError(`Cannot pair a group with itself.`);this._pairedGroups.add(t),t._pairedGroups.add(this)}},Lx=e=>{if(!e||typeof e!=`object`)throw TypeError(`metadata must be an object.`);if(e.languageCode!==void 0&&!_h(e.languageCode))throw TypeError(`metadata.languageCode, when provided, must be a three-letter, ISO 639-2/T language code.`);if(e.name!==void 0&&typeof e.name!=`string`)throw TypeError(`metadata.name, when provided, must be a string.`);if(e.disposition!==void 0&&Bh(e.disposition),e.maximumPacketCount!==void 0&&(!Number.isInteger(e.maximumPacketCount)||e.maximumPacketCount<0))throw TypeError(`metadata.maximumPacketCount, when provided, must be a non-negative integer.`);if(e.bitrate!==void 0&&(!Number.isFinite(e.bitrate)||e.bitrate<0))throw TypeError(`metadata.bitrate, when provided, must be a non-negative number.`);if(e.averageBitrate!==void 0&&(!Number.isFinite(e.averageBitrate)||e.averageBitrate<0))throw TypeError(`metadata.averageBitrate, when provided, must be a non-negative number.`);if(e.group!==void 0&&!(e.group instanceof Ix)&&(!Array.isArray(e.group)||e.group.some(e=>!(e instanceof Ix))))throw TypeError(`metadata.group, when provided, must be an OutputTrackGroup instance or an array of OutputTrackGroup instances.`)},Rx=class extends Mh{get target(){let e=`Output.target cannot be used when using PathedTarget with an async callback. Use the 'target' event instead.`;if(this._rootTargetPromise)throw TypeError(e);let t=this._getRootTarget();if(Ch(t))throw TypeError(e);return t}constructor(e){if(super(),this.state=`pending`,this.defaultTrackGroup=new Ix,this.tracks=[],this._onFinalize=null,this._unfinalizedTargets=/* @__PURE__ */ new Set,this._rootWriterPromise=null,this._startPromise=null,this._cancelPromise=null,this._finalizePromise=null,this._mutex=new Qm,this._metadataTags={},this._rootTarget=null,this._rootTargetPromise=null,this._firstMediaStreamTimestamp=null,!e||typeof e!=`object`)throw TypeError(`options must be an object.`);if(!(e.format instanceof Ex))throw TypeError(`options.format must be an OutputFormat.`);if(!(e.target instanceof cx||e.target instanceof mx))throw TypeError(`options.target must be a Target or a PathedTarget.`);if(e.target instanceof cx&&this._rememberTarget(e.target),e.initTarget!==void 0&&!(e.initTarget instanceof cx)&&typeof e.initTarget!=`function`)throw Error(`options.initTarget, when provided, must be a Target or a function that returns or resolves to a Target.`);if(e.onFinalize!==void 0&&typeof e.onFinalize!=`function`)throw TypeError(`options.onFinalize, when provided, must be a function.`);this.format=e.format,this._target=e.target,this._onFinalize=e.onFinalize??null,this._initTarget=e.initTarget??null,this._initTarget instanceof cx&&this._rememberTarget(this._initTarget),this._muxer=e.format._createMuxer(this)}_getTargetValidated(e){z(this._target instanceof mx);let t=this._target.getTarget(e),n=e=>{if(!(e instanceof cx))throw TypeError(`getTarget must return a Target.`);return e};return Ch(t)?t.then(n):n(t)}async _getTarget(e){z(this._target instanceof mx);let t=await this._getTargetValidated(e);return this._emit(`target`,{target:t,request:e,isRoot:e.isRoot}),this.state===`canceled`?await t._close():this._rememberTarget(t),t}_rememberTarget(e){this._unfinalizedTargets.add(e),e.on(`finalized`,()=>this._unfinalizedTargets.delete(e),{once:!0})}async _getInitTarget(){if(z(this._initTarget!==null),this._initTarget instanceof cx)return this._initTarget;let e=await this._initTarget();return this.state===`canceled`?await e._close():this._rememberTarget(e),e}_hasInitTarget(){return this._initTarget!==null}_getRootTarget(){if(this._rootTarget)return this._rootTarget;if(this._rootTargetPromise)return this._rootTargetPromise;if(this._target instanceof cx)return this._emit(`target`,{target:this._target,request:null,isRoot:!0}),this._rootTarget=this._target,this._target;let e={path:this._target.rootPath,isRoot:!0,mimeType:this.format.mimeType},t=this._getTargetValidated(e),n=t=>(this.state===`canceled`?t._close():this._rememberTarget(t),this._emit(`target`,{target:t,request:e,isRoot:!0}),this._rootTarget=t,t);return Ch(t)?this._rootTargetPromise=t.then(n):n(t)}_getRootWriter(e){return this._rootWriterPromise??=(async()=>{let t=await this._getRootTarget(),n=new sx(t,typeof e==`boolean`?e:e(t));return n.start(),n})()}addVideoTrack(e,t={}){if(!(e instanceof Sx))throw TypeError(`source must be a VideoSource.`);if(Lx(t),t.rotation!==void 0&&![0,90,180,270].includes(t.rotation))throw TypeError(`Invalid video rotation: ${t.rotation}. Has to be 0, 90, 180 or 270.`);if(t.flip!==void 0&&typeof t.flip!=`boolean`)throw TypeError(`metadata.flip, when provided, must be a boolean.`);if(t.transformationMatrix!==void 0&&(!Array.isArray(t.transformationMatrix)||t.transformationMatrix.length!==9||!t.transformationMatrix.every(e=>Number.isFinite(e))))throw TypeError(`metadata.transformationMatrix, when provided, must be an array of 9 finite numbers.`);if(t.frameRate!==void 0&&(!Number.isFinite(t.frameRate)||t.frameRate<=0))throw TypeError(`Invalid video frame rate: ${t.frameRate}. Must be a positive number.`);if(t.decoderConfig!==void 0&&M_({decoderConfig:t.decoderConfig},e._codec),t.primingPacket!==void 0){if(!(t.primingPacket instanceof R_))throw TypeError(`metadata.primingPacket, when provided, must be an EncodedPacket.`);if(t.decoderConfig===void 0)throw TypeError(`metadata.primingPacket can only be provided alongside metadata.decoderConfig.`)}let n={...t};return n.group??=this.defaultTrackGroup,this._addTrack(new Nx(this.tracks.length+1,this,e,n))}addAudioTrack(e,t={}){if(!(e instanceof Cx))throw TypeError(`source must be an AudioSource.`);if(Lx(t),t.decoderConfig!==void 0&&P_({decoderConfig:t.decoderConfig},e._codec),t.primingPacket!==void 0){if(!(t.primingPacket instanceof R_))throw TypeError(`metadata.primingPacket, when provided, must be an EncodedPacket.`);if(t.decoderConfig===void 0)throw TypeError(`metadata.primingPacket can only be provided alongside metadata.decoderConfig.`)}let n={...t};return n.group??=this.defaultTrackGroup,this._addTrack(new Px(this.tracks.length+1,this,e,n))}addSubtitleTrack(e,t={}){if(!(e instanceof Tx))throw TypeError(`source must be a SubtitleSource.`);Lx(t);let n={...t};return n.group??=this.defaultTrackGroup,this._addTrack(new Fx(this.tracks.length+1,this,e,n))}setMetadataTags(e){if(Rh(e),this.state!==`pending`)throw Error(`Cannot set metadata tags after output has been started or canceled.`);this._metadataTags=e}_addTrack(e){if(this.state!==`pending`)throw Error(`Cannot add track after output has been started or canceled.`);if(e.source._connectedTrack)throw Error(`Source is already used for a track.`);let t=this.format.getSupportedTrackCounts(),n=this.tracks.reduce((t,n)=>t+ +(n.type===e.type),0),r=t[e.type].max;if(n===r)throw Error(r===0?`${this.format._name} does not support ${e.type} tracks.`:`${this.format._name} does not support more than ${r} ${e.type} track${r===1?``:`s`}.`);let i=t.total.max;if(this.tracks.length===i)throw Error(`${this.format._name} does not support more than ${i} tracks${i===1?``:`s`} in total.`);if(e.isVideoTrack()){let t=this.format.getSupportedVideoCodecs();if(t.length===0)throw Error(`${this.format._name} does not support video tracks.`+this.format._codecUnsupportedHint(e.source._codec));if(!t.includes(e.source._codec))throw Error(`Codec '${e.source._codec}' cannot be contained within ${this.format._name}. Supported video codecs are: ${t.map(e=>`'${e}'`).join(`, `)}.`+this.format._codecUnsupportedHint(e.source._codec))}else if(e.isAudioTrack()){let t=this.format.getSupportedAudioCodecs();if(t.length===0)throw Error(`${this.format._name} does not support audio tracks.`+this.format._codecUnsupportedHint(e.source._codec));if(!t.includes(e.source._codec))throw Error(`Codec '${e.source._codec}' cannot be contained within ${this.format._name}. Supported audio codecs are: ${t.map(e=>`'${e}'`).join(`, `)}.`+this.format._codecUnsupportedHint(e.source._codec))}else if(e.isSubtitleTrack()){let t=this.format.getSupportedSubtitleCodecs();if(t.length===0)throw Error(`${this.format._name} does not support subtitle tracks.`+this.format._codecUnsupportedHint(e.source._codec));if(!t.includes(e.source._codec))throw Error(`Codec '${e.source._codec}' cannot be contained within ${this.format._name}. Supported subtitle codecs are: ${t.map(e=>`'${e}'`).join(`, `)}.`+this.format._codecUnsupportedHint(e.source._codec))}return this.tracks.push(e),e.source._connectedTrack=e,e}hasEnoughTracks(){let e=this.format.getSupportedTrackCounts();for(let t of jx)if(this.tracks.reduce((e,n)=>e+ +(n.type===t),0)<e[t].min)return!1;let t=e.total.min;return!(this.tracks.length<t)}async start(){let e=this.format.getSupportedTrackCounts();for(let t of jx){let n=this.tracks.reduce((e,n)=>e+ +(n.type===t),0),r=e[t].min;if(n<r)throw Error(r===e[t].max?`${this.format._name} requires exactly ${r} ${t} track${r===1?``:`s`}.`:`${this.format._name} requires at least ${r} ${t} track${r===1?``:`s`}.`)}let t=e.total.min;if(this.tracks.length<t)throw Error(t===e.total.max?`${this.format._name} requires exactly ${t} track${t===1?``:`s`}.`:`${this.format._name} requires at least ${t} track${t===1?``:`s`}.`);if(this.state===`canceled`)throw Error(`Output has been canceled.`);return this._startPromise?(Fh._warn(`Output has already been started.`),this._startPromise):this._startPromise=(async()=>{this.state=`started`;let e=this._mutex.acquire();try{await this._muxer.start();let e=this.tracks.map(e=>e.source._start());await Promise.all(e)}finally{(await e)()}})()}getMimeType(){return this._muxer.getMimeType()}async cancel(){if(this.state===`canceled`)return this._cancelPromise??void 0;if(this.state===`finalizing`||this.state===`finalized`){this.state===`finalized`&&Fh._warn(`Output has already been finalized.`);return}return this._cancelPromise=(async()=>{this.state=`canceled`;let e=await this._mutex.acquire();try{let e=this.tracks.map(e=>e.source._flushOrWaitForOngoingClose(!0));await Promise.all(e),await Promise.all([...this._unfinalizedTargets].map(e=>e._close())),this._unfinalizedTargets.clear()}finally{e()}})()}async finalize(){if(this.state===`pending`)throw Error(`Cannot finalize before starting.`);if(this.state===`canceled`)throw Error(`Cannot finalize after canceling.`);return this._finalizePromise?(Fh._warn(`Output has already been finalized.`),this._finalizePromise):this._finalizePromise=(async()=>{this.state=`finalizing`;let e=await this._mutex.acquire();try{let e=this.tracks.map(e=>e.source._flushOrWaitForOngoingClose(!1));if(await Promise.all(e),await this._muxer.finalize(),this._rootWriterPromise){let e=await this._rootWriterPromise;e.finalized||(await e.flush(),await e.finalize())}this._onFinalize&&await this._onFinalize(),this.state=`finalized`}catch(e){throw this.state=`canceled`,e}finally{await Promise.all([...this._unfinalizedTargets].map(e=>e._close().catch(()=>{}))),this._unfinalizedTargets.clear(),e()}})()}};function zx(e){let t=ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):new Uint8Array(e);return Uint8Array.from(t)}var Bx=/* @__PURE__ */ new Set([`hvc1`,`hev1`]);async function Vx(e,t){let[n,r]=await Promise.all([e.getCodec(),e.getInternalCodecId()]);return n===`hevc`&&typeof r==`string`&&Bx.has(r)&&t.description!==void 0?Fs(r,zx(t.description)):t.codec}function Hx(e,t){return{codec:t.codec,codedWidth:e.codedWidth??t.codedWidth,codedHeight:e.codedHeight??t.codedHeight,description:e.description===void 0?void 0:zx(e.description),colour:t.colour}}function Ux(e){return{codec:e.codec,sampleRate:e.sampleRate,numberOfChannels:e.numberOfChannels,description:e.description===void 0?void 0:zx(e.description)}}function Wx(e){return{primaries:gu(pu,e?.primaries),transfer:gu(mu,e?.transfer),matrix:gu(hu,e?.matrix),range:Gx(e?.fullRange)}}function Gx(e){return e===!0?`full`:e===!1?`limited`:`unspecified`}var Kx=[Pv,Fv],qx=class{async read(e){let t=new ny({formats:Kx,source:new Ov(e)});try{let[e,n]=await Promise.all([t.getVideoTracks(),t.getAudioTracks()]);return{video:await Promise.all(e.map((e,t)=>Jx(e,t))),audio:(await Promise.all(n.map(e=>Xx(e)))).flat()}}catch(e){throw Zx(e)}finally{t.dispose()}}};async function Jx(e,t){let[n,r,i]=await Promise.all([Yx(e),e.getCodedWidth(),e.getCodedHeight()]);if(n===null)throw new j(`codec-unsupported`,`video track ${t} has no decoder configuration in its sample entry`);let a={trackIndex:t,codedWidth:r,codedHeight:i,codec:await Vx(e,n),colour:Wx(n.colorSpace)};return{trackId:e.id,description:a,configuration:Hx(n,a)}}async function Yx(e){try{return await e.getDecoderConfig()}catch{return null}}async function Xx(e){let t=await e.getDecoderConfig();return t===null?[]:[{trackId:e.id,configuration:Ux(t)}]}function Zx(e){return re(e)||e instanceof j?e:new j(`unsupported-container`,`the movie box is not a readable movie`,{cause:e})}var Qx=class{capacity;queue=[];roomWaiters=[];takeWaiter;isClosedNow=!1;failure;constructor(e){this.capacity=e}get isClosed(){return this.isClosedNow}push(e){this.isClosedNow||(this.queue.push(e),this.wakeTaker())}waitForRoom(){return this.queue.length<this.capacity||this.isClosedNow?Promise.resolve():new Promise(e=>{this.roomWaiters.push(e)})}close(){this.isClosedNow=!0,this.wakeTaker(),this.wakeRoomWaiters()}fail(e){this.failure??=e instanceof Error?e:new j(`decode`,`audio re-packaging failed`,{cause:e}),this.close()}segments(e=eS){return new $x({take:()=>this.take(),close:()=>{this.close()},onEnd:e})}async take(){for(;this.queue.length===0&&!this.isClosedNow;)await this.nextPush();let e=this.queue.shift();if(e)return this.wakeRoomWaiters(),e;if(this.failure)throw this.failure}nextPush(){return N(this.takeWaiter===void 0,`a segment channel has one consumer`),new Promise(e=>{this.takeWaiter=e})}wakeTaker(){let e=this.takeWaiter;this.takeWaiter=void 0,e?.()}wakeRoomWaiters(){if(this.queue.length>=this.capacity&&!this.isClosedNow)return;let e=this.roomWaiters;this.roomWaiters=[];for(let t of e)t()}},$x=class{parts;hasEnded=!1;constructor(e){this.parts=e}async next(){if(this.hasEnded)return Fu;try{let e=await this.parts.take();return e===void 0||this.wasEnded()?this.end():{done:!1,value:e}}catch(e){throw this.end(),e}}return(){return this.parts.close(),Promise.resolve(this.end())}[Symbol.asyncIterator](){return this}wasEnded(){return this.hasEnded}end(){return this.hasEnded||this.parts.onEnd(),this.hasEnded=!0,Fu}};function eS(){}var tS=1,nS=2,rS=`mp4a.40.`,iS=`aac`,aS=class{segmentsOf(e,t){let n=oS(t);return{mimeType:`audio/mp4; codecs="${t.codec}"`,duration:e.duration,segmentsFrom:r=>({[Symbol.asyncIterator]:()=>sS({samples:e,configuration:t,codec:n},r)})}}};function oS(e){if(e.codec.startsWith(rS))return iS;throw new j(`codec-unsupported`,`audio in ${e.codec} cannot be re-packaged for playback`)}function sS(e,t){let n=new Qx(nS),r=new Rx({format:fS(n),target:new fx}),i=new wx(e.codec);r.addAudioTrack(i);let a=e.samples.samplesFrom(t)[Symbol.asyncIterator](),o=lS({samples:a,configuration:e.configuration,output:r,source:i,channel:n});return n.segments(()=>{a.return?.(),cS(o,r)})}async function cS(e,t){if(await e,t.state!==`finalized`)try{await t.cancel()}catch{}}async function lS(e){try{await e.output.start();let t={decoderConfig:dS(e.configuration)};for(let n=await e.samples.next();n.done!==!0;n=await e.samples.next()){if(await e.channel.waitForRoom(),e.channel.isClosed)return;await e.source.add(uS(n.value),t),t=void 0}if(e.channel.isClosed)return;await e.output.finalize(),e.channel.close()}catch(t){e.channel.fail(t)}}function uS(e){return new R_(e.data,`key`,e.timestamp,e.duration)}function dS(e){return{codec:e.codec,sampleRate:e.sampleRate,numberOfChannels:e.numberOfChannels,...e.description&&{description:e.description}}}function fS(e){let t=new pS(e);return new Ox({fastStart:`fragmented`,minimumFragmentDuration:tS,onFtyp:e=>{t.begin(e)},onMoov:e=>{t.end(e)},onMoof:e=>{t.begin(e)},onMdat:e=>{t.end(e)}})}var pS=class{channel;opening;constructor(e){this.channel=e}begin(e){N(this.opening===void 0,`a segment began before the last one ended`),this.opening=new Uint8Array(e)}end(e){let{opening:t}=this;N(t!==void 0,`a segment ended that never began`);let n=new Uint8Array(t.byteLength+e.byteLength);n.set(t),n.set(e,t.byteLength),this.opening=void 0,this.channel.push(n)}};function mS(e){let t=e.range===`unspecified`?void 0:{fullRange:e.range===`full`},n={...e.primaries!==`unspecified`&&{primaries:e.primaries},...e.transfer!==`unspecified`&&{transfer:e.transfer},...e.matrix!==`unspecified`&&{matrix:e.matrix},...t};return Object.keys(n).length===0?void 0:hS(n)??t}function hS(e){try{return new VideoColorSpace(e).toJSON()}catch{return}}var gS=`no-preference`,_S=class{async isSupported(e){if(typeof VideoDecoder>`u`)throw yS();try{return(await VideoDecoder.isConfigSupported(this.toWebCodecsConfig(e))).supported===!0}catch{return!1}}create(e,t){try{return Promise.resolve(this.configureDecoder(e,t))}catch(e){return Promise.reject(ne(e,`codec-unsupported`,`the decoder rejected its configuration`))}}configureDecoder(e,t){if(typeof VideoDecoder>`u`)throw yS();return new vS(this.toWebCodecsConfig(e),t)}toWebCodecsConfig(e){let{description:t}=e,n=mS(e.colour);return{codec:e.codec,codedWidth:e.codedWidth,codedHeight:e.codedHeight,...t&&{description:t},...n&&{colorSpace:n},hardwareAcceleration:gS,optimizeForLatency:!1}}},vS=class{decoder;failure;constructor(e,t){this.decoder=new VideoDecoder({output:e=>{t.onFrame(xS(e))},error:e=>{this.failure??=new j(`decode`,`video decoder failed: ${e.message}`,{cause:e}),t.onError(this.failure)}});try{this.decoder.configure(e)}catch(e){throw this.decoder.close(),e}}get pendingCount(){return this.decoder.decodeQueueSize}decode(e){if(this.failure)throw this.failure;try{this.decoder.decode(bS(e))}catch(e){throw new j(`decode`,`the decoder refused a packet: ${ie(e)}`,{cause:e})}}waitForPendingBelow(e){return this.decoder.decodeQueueSize<e?Promise.resolve():new Promise(t=>{let n=()=>{this.decoder.decodeQueueSize>=e&&this.decoder.state===`configured`||(this.decoder.removeEventListener(`dequeue`,n),t())};this.decoder.addEventListener(`dequeue`,n)})}async flush(){if(this.decoder.state!==`configured`)throw this.failure??new j(`decode`,`flush on a closed decoder`);try{await this.decoder.flush()}catch(e){throw this.failure??new j(`decode`,`the decoder could not be flushed`,{cause:e})}}close(){this.decoder.state!==`closed`&&this.decoder.close()}};function yS(){return new j(`webcodecs-unavailable`,globalThis.isSecureContext?`this browser has no WebCodecs VideoDecoder`:`WebCodecs exists only in secure contexts (HTTPS), and this page is not one`)}function bS(e){return new EncodedVideoChunk({type:e.isKeyFrame?`key`:`delta`,timestamp:_t(e.timestamp),duration:_t(e.duration),data:e.data})}function xS(e){return{timestamp:mt(ft(e.timestamp)),handle:e,close:()=>{e.close()}}}function SS(e){return`url`in e}function CS(e){return SS(e)?Ea(e.url):e.name}var wS=15e3;function TS(e={}){let t=e.http??{},n=e.probeTimeoutMs??wS;return{sources:ES(t),codecReader:new qx,audioPackager:new aS,decoderPort:new _S,locatorFor:e=>new ym(kS(t,e)),probeDeadline:()=>AS(n)}}function ES(e){return{open:(t,n)=>SS(t)?DS(t,e,n):OS(t)}}function DS(e,t,n){let r=new hm(e.url,kS(t,e),n);return{source:new Hp(r),stream:new Bp(r)}}function OS(e){let t=new kp(e.blob);return{source:t,stream:new Lu(t)}}function kS(e,t){let{credentials:n}=t;return n===void 0?e:{...e,requestInit:{...e.requestInit,credentials:n}}}function AS(e){let t=new Wd;return setTimeout(()=>{t.resolve()},e),t}function jS(e,t,n){let r=new AbortController;return n?.addEventListener(`abort`,()=>{r.abort()},{once:!0,signal:r.signal}),new Promise(n=>{for(let i of t)e.addEventListener(i,()=>{r.abort(),n(i)},{once:!0,signal:r.signal})})}var MS=`ManagedMediaSource`,NS=`MediaSource`;function PS(e){return typeof e==`function`&&typeof e.isTypeSupported==`function`}function FS(e){let t=Reflect.get(globalThis,e);return PS(t)?t:void 0}function IS(){return FS(MS)??FS(NS)}function LS(e){return IS()?.isTypeSupported(e)??!1}var RS=1e4;async function zS(e,t){let n=new t,r=BS(e,n),i=URL.createObjectURL(n);e.disableRemotePlayback=!0,e.src=i;let a={mediaSource:n,detach:()=>{e.src===i&&(e.removeAttribute(`src`),e.load()),URL.revokeObjectURL(i)}},o=await r;if(o!==`sourceopen`)throw a.detach(),new j(`decode`,`the audio element could not open its media source (${o})`);return a}async function BS(e,t){let n=new AbortController;try{return await Promise.race([jS(t,[`sourceopen`],n.signal),jS(e,[`error`],n.signal),VS(RS,n.signal)])}finally{n.abort()}}function VS(e,t){return new Promise(n=>{let r=setTimeout(()=>{n(`timeout`)},e);t.addEventListener(`abort`,()=>{clearTimeout(r)},{once:!0})})}var HS=30,US=30,WS=60,GS=1,KS=[`timeupdate`,`seeking`,`waiting`,`play`],qS=class{parts;stop=new Kd;run=Promise.resolve();failureValue;constructor(e){this.parts=e}get failure(){return this.failureValue}restartFrom(e){this.stop.stop();let t=new Kd;this.stop=t,this.run=this.feedAfter(this.run,e,t)}dispose(){this.stop.stop()}async feedAfter(e,t,n){await e,await this.feed(t,n)}async feed(e,t){try{if(await this.settlePendingAppend(),t.wasStopped||this.hasElementFailed()||this.hasAllAudioFrom(e))return;await this.feedFrom(this.startOf(e),t)}catch(e){this.failureValue??=ne(e,`decode`,`feeding the audio buffer failed`)}}async feedFrom(e,t){let n=this.parts.source.segmentsFrom(e)[Symbol.asyncIterator]();try{await this.pump(n,t)&&this.endStream()}finally{n.return?.()}}hasAllAudioFrom(e){let{buffered:t}=this.parts.element,n=this.bufferedEndAt(e);return this.parts.mediaSource.readyState===`ended`&&n>e&&n===t.end(t.length-1)}startOf(e){let t=this.bufferedEndAt(e);return R(t>e?t:Math.max(0,e-GS))}async pump(e,t){let n=await this.nextWhenNeeded(e,t);for(;n!==Gd;){if(n.done===!0)return!0;if(this.hasElementFailed())return!1;this.evictBehind(),await this.append(n.value),n=await this.nextWhenNeeded(e,t)}return!1}async nextWhenNeeded(e,t){return await this.waitUntilNeeded(t),t.race(()=>e.next())}async waitUntilNeeded(e){for(;!e.wasStopped&&this.bufferedAhead()>=HS;){let t=new AbortController;await e.race(()=>jS(this.parts.element,KS,t.signal)),t.abort()}}bufferedAhead(){let{currentTime:e}=this.parts.element;return R(this.bufferedEndAt(e)-e)}bufferedEndAt(e){let{buffered:t}=this.parts.element;for(let n=0;n<t.length;n+=1)if(t.start(n)<=e&&e<t.end(n))return t.end(n);return e}evictBehind(){let{buffered:e,currentTime:t}=this.parts.element;t-(e.length>0?e.start(0):t)<WS||this.parts.sourceBuffer.updating||this.parts.sourceBuffer.remove(0,t-US)}async append(e){let{sourceBuffer:t}=this.parts;await this.settlePendingAppend();let n=jS(t,[`updateend`,`error`]);try{t.appendBuffer(e)}catch(e){throw new j(`decode`,`the audio buffer rejected a segment`,{cause:e})}if(await n===`error`)throw new j(`decode`,`the audio buffer could not parse a segment`)}hasElementFailed(){return this.parts.element.error!==null}async settlePendingAppend(){this.parts.sourceBuffer.updating&&await jS(this.parts.sourceBuffer,[`updateend`])}endStream(){let{mediaSource:e,sourceBuffer:t}=this.parts;e.readyState===`open`&&!t.updating&&e.endOfStream()}},JS=class e{element;feeder;attached;standingEnd;constructor(e,t,n){this.element=e,this.feeder=t,this.attached=n}static isSupported(e){return LS(e.mimeType)}static async open(t,n){let r=IS();if(!r?.isTypeSupported(n.mimeType))throw new j(`codec-unsupported`,`${n.mimeType} cannot play through Media Source Extensions here`);let i=await zS(t,r);try{let r=i.mediaSource.addSourceBuffer(n.mimeType);i.mediaSource.duration=n.duration;let a=new qS({element:t,mediaSource:i.mediaSource,sourceBuffer:r,source:n});return a.restartFrom(R(0)),new e(t,a,i)}catch(e){throw i.detach(),ZS(e)}}get currentTime(){return this.standingEnd??R(this.element.currentTime)}get isRunning(){return!this.element.paused}get hasEnded(){return this.standingEnd!==void 0||this.element.ended}get failure(){return this.feeder.failure??XS(this.element)}async start(){if(!this.hasEnded)try{await this.element.play()}catch(e){if(re(e))return;let t=YS(e,`NotAllowedError`);throw new j(t?`playback-blocked`:`decode`,t?`the browser refused to start audio playback; a user gesture is needed`:`audio playback failed to start`,{cause:e})}}pause(){this.element.pause()}seek(e){let t=this.attached.mediaSource.duration;if(e>=t){this.standAtEnd(R(t));return}this.standingEnd=void 0,this.element.currentTime=e,this.feeder.restartFrom(e)}dispose(){this.feeder.dispose(),this.element.pause(),this.attached.detach()}standAtEnd(e){this.element.pause(),this.standingEnd=e}};function YS(e,t){return e instanceof Error&&e.name===t}function XS(e){let{error:t}=e;return t===null?void 0:new j(`decode`,`the audio element failed (media error ${t.code})`,{cause:t})}function ZS(e){return e instanceof j?e:new j(YS(e,`NotSupportedError`)?`codec-unsupported`:`decode`,`the audio element refused the recording's sound: ${ie(e)}`,{cause:e})}var QS=1e3,$S=1001,eC=1002,tC=1003,nC=1004,rC=1005,iC=1006,aC=1007,oC=1008,sC=1009,cC=1010,lC=1011,uC=1012,dC=1013,fC=1014,pC=1015,mC=1016,hC=1017,gC=1018,_C=1020,vC=35902,yC=35899,bC=1021,xC=1022,SC=1023,CC=1026,wC=1027,TC=1028,EC=1029,DC=1030,OC=1031,kC=1033,AC=33776,jC=33777,MC=33778,NC=33779,PC=35840,FC=35841,IC=35842,LC=35843,RC=36196,zC=37492,BC=37496,VC=37488,HC=37489,UC=37490,WC=37491,GC=37808,KC=37809,qC=37810,JC=37811,YC=37812,XC=37813,ZC=37814,QC=37815,$C=37816,ew=37817,tw=37818,nw=37819,rw=37820,iw=37821,aw=36492,ow=36494,sw=36495,cw=36283,lw=36284,uw=36285,dw=36286,fw=2300,pw=2301,mw=2302,hw=2303,gw=2400,_w=2401,vw=2402,yw=3200,bw=`srgb`,xw=`srgb-linear`,Sw=`linear`,Cw=`srgb`,ww=7680,Tw=35044,Ew=`300 es`,Dw=2e3;function Ow(e){for(let t=e.length-1;t>=0;--t)if(e[t]>=65535)return!0;return!1}function kw(e){return ArrayBuffer.isView(e)&&!(e instanceof DataView)}function Aw(e){return document.createElementNS(`http://www.w3.org/1999/xhtml`,e)}function jw(){let e=Aw(`canvas`);return e.style.display=`block`,e}var Mw={};function Nw(...e){let t=`THREE.`+e.shift();console.log(t,...e)}function Pw(e){let t=e[0];if(typeof t==`string`&&t.startsWith(`TSL:`)){let t=e[1];t&&t.isStackTrace?e[0]+=` `+t.getLocation():e[1]=`Stack trace not available. Enable "THREE.Node.captureStackTrace" to capture stack traces.`}return e}function q(...e){e=Pw(e);let t=`THREE.`+e.shift();{let n=e[0];n&&n.isStackTrace?console.warn(n.getError(t)):console.warn(t,...e)}}function J(...e){e=Pw(e);let t=`THREE.`+e.shift();{let n=e[0];n&&n.isStackTrace?console.error(n.getError(t)):console.error(t,...e)}}function Fw(...e){let t=e.join(` `);t in Mw||(Mw[t]=!0,q(...e))}function Iw(e,t,n){return new Promise(function(r,i){function a(){switch(e.clientWaitSync(t,e.SYNC_FLUSH_COMMANDS_BIT,0)){case e.WAIT_FAILED:i();break;case e.TIMEOUT_EXPIRED:setTimeout(a,n);break;default:r()}}setTimeout(a,n)})}var Lw={0:1,2:6,4:7,3:5,1:0,6:2,7:4,5:3},Rw=class{addEventListener(e,t){this._listeners===void 0&&(this._listeners={});let n=this._listeners;n[e]===void 0&&(n[e]=[]),n[e].indexOf(t)===-1&&n[e].push(t)}hasEventListener(e,t){let n=this._listeners;return n!==void 0&&n[e]!==void 0&&n[e].indexOf(t)!==-1}removeEventListener(e,t){let n=this._listeners;if(n===void 0)return;let r=n[e];if(r!==void 0){let e=r.indexOf(t);e!==-1&&r.splice(e,1)}}dispatchEvent(e){let t=this._listeners;if(t===void 0)return;let n=t[e.type];if(n!==void 0){e.target=this;let t=n.slice(0);for(let n=0,r=t.length;n<r;n++)t[n].call(this,e);e.target=null}}},zw=/* @__PURE__ */ `00.01.02.03.04.05.06.07.08.09.0a.0b.0c.0d.0e.0f.10.11.12.13.14.15.16.17.18.19.1a.1b.1c.1d.1e.1f.20.21.22.23.24.25.26.27.28.29.2a.2b.2c.2d.2e.2f.30.31.32.33.34.35.36.37.38.39.3a.3b.3c.3d.3e.3f.40.41.42.43.44.45.46.47.48.49.4a.4b.4c.4d.4e.4f.50.51.52.53.54.55.56.57.58.59.5a.5b.5c.5d.5e.5f.60.61.62.63.64.65.66.67.68.69.6a.6b.6c.6d.6e.6f.70.71.72.73.74.75.76.77.78.79.7a.7b.7c.7d.7e.7f.80.81.82.83.84.85.86.87.88.89.8a.8b.8c.8d.8e.8f.90.91.92.93.94.95.96.97.98.99.9a.9b.9c.9d.9e.9f.a0.a1.a2.a3.a4.a5.a6.a7.a8.a9.aa.ab.ac.ad.ae.af.b0.b1.b2.b3.b4.b5.b6.b7.b8.b9.ba.bb.bc.bd.be.bf.c0.c1.c2.c3.c4.c5.c6.c7.c8.c9.ca.cb.cc.cd.ce.cf.d0.d1.d2.d3.d4.d5.d6.d7.d8.d9.da.db.dc.dd.de.df.e0.e1.e2.e3.e4.e5.e6.e7.e8.e9.ea.eb.ec.ed.ee.ef.f0.f1.f2.f3.f4.f5.f6.f7.f8.f9.fa.fb.fc.fd.fe.ff`.split(`.`),Bw=Math.PI/180,Vw=180/Math.PI;function Hw(){let e=Math.random()*4294967295|0,t=Math.random()*4294967295|0,n=Math.random()*4294967295|0,r=Math.random()*4294967295|0;return(zw[e&255]+zw[e>>8&255]+zw[e>>16&255]+zw[e>>24&255]+`-`+zw[t&255]+zw[t>>8&255]+`-`+zw[t>>16&15|64]+zw[t>>24&255]+`-`+zw[n&63|128]+zw[n>>8&255]+`-`+zw[n>>16&255]+zw[n>>24&255]+zw[r&255]+zw[r>>8&255]+zw[r>>16&255]+zw[r>>24&255]).toLowerCase()}function Uw(e,t,n){return Math.max(t,Math.min(n,e))}function Ww(e,t){return(e%t+t)%t}function Gw(e,t,n){return(1-n)*e+n*t}function Kw(e,t){switch(t.constructor){case Float32Array:return e;case Uint32Array:return e/4294967295;case Uint16Array:return e/65535;case Uint8Array:case Uint8ClampedArray:return e/255;case Int32Array:return Math.max(e/2147483647,-1);case Int16Array:return Math.max(e/32767,-1);case Int8Array:return Math.max(e/127,-1);default:throw Error(`THREE.MathUtils: Invalid component type.`)}}function qw(e,t){switch(t.constructor){case Float32Array:return e;case Uint32Array:return Math.round(e*4294967295);case Uint16Array:return Math.round(e*65535);case Uint8Array:case Uint8ClampedArray:return Math.round(e*255);case Int32Array:return Math.round(e*2147483647);case Int16Array:return Math.round(e*32767);case Int8Array:return Math.round(e*127);default:throw Error(`THREE.MathUtils: Invalid component type.`)}}var Y=class e{static{e.prototype.isVector2=!0}constructor(e=0,t=0){this.x=e,this.y=t}get width(){return this.x}set width(e){this.x=e}get height(){return this.y}set height(e){this.y=e}set(e,t){return this.x=e,this.y=t,this}setScalar(e){return this.x=e,this.y=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;default:throw Error(`THREE.Vector2: index is out of range: `+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;default:throw Error(`THREE.Vector2: index is out of range: `+e)}}clone(){return new this.constructor(this.x,this.y)}copy(e){return this.x=e.x,this.y=e.y,this}add(e){return this.x+=e.x,this.y+=e.y,this}addScalar(e){return this.x+=e,this.y+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this}subScalar(e){return this.x-=e,this.y-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this}multiply(e){return this.x*=e.x,this.y*=e.y,this}multiplyScalar(e){return this.x*=e,this.y*=e,this}divide(e){return this.x/=e.x,this.y/=e.y,this}divideScalar(e){return this.multiplyScalar(1/e)}applyMatrix3(e){let t=this.x,n=this.y,r=e.elements;return this.x=r[0]*t+r[3]*n+r[6],this.y=r[1]*t+r[4]*n+r[7],this}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this}clamp(e,t){return this.x=Uw(this.x,e.x,t.x),this.y=Uw(this.y,e.y,t.y),this}clampScalar(e,t){return this.x=Uw(this.x,e,t),this.y=Uw(this.y,e,t),this}clampLength(e,t){let n=this.length();return this.divideScalar(n||1).multiplyScalar(Uw(n,e,t))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this}negate(){return this.x=-this.x,this.y=-this.y,this}dot(e){return this.x*e.x+this.y*e.y}cross(e){return this.x*e.y-this.y*e.x}lengthSq(){return this.x*this.x+this.y*this.y}length(){return Math.sqrt(this.x*this.x+this.y*this.y)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)}normalize(){return this.divideScalar(this.length()||1)}angle(){return Math.atan2(-this.y,-this.x)+Math.PI}angleTo(e){let t=Math.sqrt(this.lengthSq()*e.lengthSq());if(t===0)return Math.PI/2;let n=this.dot(e)/t;return Math.acos(Uw(n,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){let t=this.x-e.x,n=this.y-e.y;return t*t+n*n}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this}lerpVectors(e,t,n){return this.x=e.x+(t.x-e.x)*n,this.y=e.y+(t.y-e.y)*n,this}equals(e){return e.x===this.x&&e.y===this.y}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this}rotateAround(e,t){let n=Math.cos(t),r=Math.sin(t),i=this.x-e.x,a=this.y-e.y;return this.x=i*n-a*r+e.x,this.y=i*r+a*n+e.y,this}random(){return this.x=Math.random(),this.y=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y}},Jw=class{constructor(e=0,t=0,n=0,r=1){this.isQuaternion=!0,this._x=e,this._y=t,this._z=n,this._w=r}static slerpFlat(e,t,n,r,i,a,o){let s=n[r+0],c=n[r+1],l=n[r+2],u=n[r+3],d=i[a+0],f=i[a+1],p=i[a+2],m=i[a+3];if(u!==m||s!==d||c!==f||l!==p){let e=s*d+c*f+l*p+u*m;e<0&&(d=-d,f=-f,p=-p,m=-m,e=-e);let t=1-o;if(e<.9995){let n=Math.acos(e),r=Math.sin(n);t=Math.sin(t*n)/r,o=Math.sin(o*n)/r,s=s*t+d*o,c=c*t+f*o,l=l*t+p*o,u=u*t+m*o}else{s=s*t+d*o,c=c*t+f*o,l=l*t+p*o,u=u*t+m*o;let e=1/Math.sqrt(s*s+c*c+l*l+u*u);s*=e,c*=e,l*=e,u*=e}}e[t]=s,e[t+1]=c,e[t+2]=l,e[t+3]=u}static multiplyQuaternionsFlat(e,t,n,r,i,a){let o=n[r],s=n[r+1],c=n[r+2],l=n[r+3],u=i[a],d=i[a+1],f=i[a+2],p=i[a+3];return e[t]=o*p+l*u+s*f-c*d,e[t+1]=s*p+l*d+c*u-o*f,e[t+2]=c*p+l*f+o*d-s*u,e[t+3]=l*p-o*u-s*d-c*f,e}get x(){return this._x}set x(e){this._x=e,this._onChangeCallback()}get y(){return this._y}set y(e){this._y=e,this._onChangeCallback()}get z(){return this._z}set z(e){this._z=e,this._onChangeCallback()}get w(){return this._w}set w(e){this._w=e,this._onChangeCallback()}set(e,t,n,r){return this._x=e,this._y=t,this._z=n,this._w=r,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._w)}copy(e){return this._x=e.x,this._y=e.y,this._z=e.z,this._w=e.w,this._onChangeCallback(),this}setFromEuler(e,t=!0){let n=e._x,r=e._y,i=e._z,a=e._order,o=Math.cos,s=Math.sin,c=o(n/2),l=o(r/2),u=o(i/2),d=s(n/2),f=s(r/2),p=s(i/2);switch(a){case`XYZ`:this._x=d*l*u+c*f*p,this._y=c*f*u-d*l*p,this._z=c*l*p+d*f*u,this._w=c*l*u-d*f*p;break;case`YXZ`:this._x=d*l*u+c*f*p,this._y=c*f*u-d*l*p,this._z=c*l*p-d*f*u,this._w=c*l*u+d*f*p;break;case`ZXY`:this._x=d*l*u-c*f*p,this._y=c*f*u+d*l*p,this._z=c*l*p+d*f*u,this._w=c*l*u-d*f*p;break;case`ZYX`:this._x=d*l*u-c*f*p,this._y=c*f*u+d*l*p,this._z=c*l*p-d*f*u,this._w=c*l*u+d*f*p;break;case`YZX`:this._x=d*l*u+c*f*p,this._y=c*f*u+d*l*p,this._z=c*l*p-d*f*u,this._w=c*l*u-d*f*p;break;case`XZY`:this._x=d*l*u-c*f*p,this._y=c*f*u-d*l*p,this._z=c*l*p+d*f*u,this._w=c*l*u+d*f*p;break;default:q(`Quaternion: .setFromEuler() encountered an unknown order: `+a)}return t===!0&&this._onChangeCallback(),this}setFromAxisAngle(e,t){let n=t/2,r=Math.sin(n);return this._x=e.x*r,this._y=e.y*r,this._z=e.z*r,this._w=Math.cos(n),this._onChangeCallback(),this}setFromRotationMatrix(e){let t=e.elements,n=t[0],r=t[4],i=t[8],a=t[1],o=t[5],s=t[9],c=t[2],l=t[6],u=t[10],d=n+o+u;if(d>0){let e=.5/Math.sqrt(d+1);this._w=.25/e,this._x=(l-s)*e,this._y=(i-c)*e,this._z=(a-r)*e}else if(n>o&&n>u){let e=2*Math.sqrt(1+n-o-u);this._w=(l-s)/e,this._x=.25*e,this._y=(r+a)/e,this._z=(i+c)/e}else if(o>u){let e=2*Math.sqrt(1+o-n-u);this._w=(i-c)/e,this._x=(r+a)/e,this._y=.25*e,this._z=(s+l)/e}else{let e=2*Math.sqrt(1+u-n-o);this._w=(a-r)/e,this._x=(i+c)/e,this._y=(s+l)/e,this._z=.25*e}return this._onChangeCallback(),this}setFromUnitVectors(e,t){let n=e.dot(t)+1;return n<1e-8?(n=0,Math.abs(e.x)>Math.abs(e.z)?(this._x=-e.y,this._y=e.x,this._z=0,this._w=n):(this._x=0,this._y=-e.z,this._z=e.y,this._w=n)):(this._x=e.y*t.z-e.z*t.y,this._y=e.z*t.x-e.x*t.z,this._z=e.x*t.y-e.y*t.x,this._w=n),this.normalize()}angleTo(e){return 2*Math.acos(Math.abs(Uw(this.dot(e),-1,1)))}rotateTowards(e,t){let n=this.angleTo(e);if(n===0)return this;let r=Math.min(1,t/n);return this.slerp(e,r),this}identity(){return this.set(0,0,0,1)}invert(){return this.conjugate()}conjugate(){return this._x*=-1,this._y*=-1,this._z*=-1,this._onChangeCallback(),this}dot(e){return this._x*e._x+this._y*e._y+this._z*e._z+this._w*e._w}lengthSq(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w}length(){return Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w)}normalize(){let e=this.length();return e===0?(this._x=0,this._y=0,this._z=0,this._w=1):(e=1/e,this._x*=e,this._y*=e,this._z*=e,this._w*=e),this._onChangeCallback(),this}multiply(e){return this.multiplyQuaternions(this,e)}premultiply(e){return this.multiplyQuaternions(e,this)}multiplyQuaternions(e,t){let n=e._x,r=e._y,i=e._z,a=e._w,o=t._x,s=t._y,c=t._z,l=t._w;return this._x=n*l+a*o+r*c-i*s,this._y=r*l+a*s+i*o-n*c,this._z=i*l+a*c+n*s-r*o,this._w=a*l-n*o-r*s-i*c,this._onChangeCallback(),this}slerp(e,t){let n=e._x,r=e._y,i=e._z,a=e._w,o=this.dot(e);o<0&&(n=-n,r=-r,i=-i,a=-a,o=-o);let s=1-t;if(o<.9995){let e=Math.acos(o),c=Math.sin(e);s=Math.sin(s*e)/c,t=Math.sin(t*e)/c,this._x=this._x*s+n*t,this._y=this._y*s+r*t,this._z=this._z*s+i*t,this._w=this._w*s+a*t,this._onChangeCallback()}else this._x=this._x*s+n*t,this._y=this._y*s+r*t,this._z=this._z*s+i*t,this._w=this._w*s+a*t,this.normalize();return this}slerpQuaternions(e,t,n){return this.copy(e).slerp(t,n)}random(){let e=2*Math.PI*Math.random(),t=2*Math.PI*Math.random(),n=Math.random(),r=Math.sqrt(1-n),i=Math.sqrt(n);return this.set(r*Math.sin(e),r*Math.cos(e),i*Math.sin(t),i*Math.cos(t))}equals(e){return e._x===this._x&&e._y===this._y&&e._z===this._z&&e._w===this._w}fromArray(e,t=0){return this._x=e[t],this._y=e[t+1],this._z=e[t+2],this._w=e[t+3],this._onChangeCallback(),this}toArray(e=[],t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,e[t+3]=this._w,e}fromBufferAttribute(e,t){return this._x=e.getX(t),this._y=e.getY(t),this._z=e.getZ(t),this._w=e.getW(t),this._onChangeCallback(),this}toJSON(){return this.toArray()}_onChange(e){return this._onChangeCallback=e,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._w}},X=class e{static{e.prototype.isVector3=!0}constructor(e=0,t=0,n=0){this.x=e,this.y=t,this.z=n}set(e,t,n){return n===void 0&&(n=this.z),this.x=e,this.y=t,this.z=n,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;case 2:this.z=t;break;default:throw Error(`THREE.Vector3: index is out of range: `+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;default:throw Error(`THREE.Vector3: index is out of range: `+e)}}clone(){return new this.constructor(this.x,this.y,this.z)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this.z=e.z+t.z,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this.z+=e.z*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this.z=e.z-t.z,this}multiply(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this}multiplyVectors(e,t){return this.x=e.x*t.x,this.y=e.y*t.y,this.z=e.z*t.z,this}applyEuler(e){return this.applyQuaternion(Xw.setFromEuler(e))}applyAxisAngle(e,t){return this.applyQuaternion(Xw.setFromAxisAngle(e,t))}applyMatrix3(e){let t=this.x,n=this.y,r=this.z,i=e.elements;return this.x=i[0]*t+i[3]*n+i[6]*r,this.y=i[1]*t+i[4]*n+i[7]*r,this.z=i[2]*t+i[5]*n+i[8]*r,this}applyNormalMatrix(e){return this.applyMatrix3(e).normalize()}applyMatrix4(e){let t=this.x,n=this.y,r=this.z,i=e.elements,a=1/(i[3]*t+i[7]*n+i[11]*r+i[15]);return this.x=(i[0]*t+i[4]*n+i[8]*r+i[12])*a,this.y=(i[1]*t+i[5]*n+i[9]*r+i[13])*a,this.z=(i[2]*t+i[6]*n+i[10]*r+i[14])*a,this}applyQuaternion(e){let t=this.x,n=this.y,r=this.z,i=e.x,a=e.y,o=e.z,s=e.w,c=2*(a*r-o*n),l=2*(o*t-i*r),u=2*(i*n-a*t);return this.x=t+s*c+a*u-o*l,this.y=n+s*l+o*c-i*u,this.z=r+s*u+i*l-a*c,this}project(e){return this.applyMatrix4(e.matrixWorldInverse).applyMatrix4(e.projectionMatrix)}unproject(e){return this.applyMatrix4(e.projectionMatrixInverse).applyMatrix4(e.matrixWorld)}transformDirection(e){let t=this.x,n=this.y,r=this.z,i=e.elements;return this.x=i[0]*t+i[4]*n+i[8]*r,this.y=i[1]*t+i[5]*n+i[9]*r,this.z=i[2]*t+i[6]*n+i[10]*r,this.normalize()}divide(e){return this.x/=e.x,this.y/=e.y,this.z/=e.z,this}divideScalar(e){return this.multiplyScalar(1/e)}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this.z=Math.min(this.z,e.z),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this.z=Math.max(this.z,e.z),this}clamp(e,t){return this.x=Uw(this.x,e.x,t.x),this.y=Uw(this.y,e.y,t.y),this.z=Uw(this.z,e.z,t.z),this}clampScalar(e,t){return this.x=Uw(this.x,e,t),this.y=Uw(this.y,e,t),this.z=Uw(this.z,e,t),this}clampLength(e,t){let n=this.length();return this.divideScalar(n||1).multiplyScalar(Uw(n,e,t))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)}normalize(){return this.divideScalar(this.length()||1)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this.z+=(e.z-this.z)*t,this}lerpVectors(e,t,n){return this.x=e.x+(t.x-e.x)*n,this.y=e.y+(t.y-e.y)*n,this.z=e.z+(t.z-e.z)*n,this}cross(e){return this.crossVectors(this,e)}crossVectors(e,t){let n=e.x,r=e.y,i=e.z,a=t.x,o=t.y,s=t.z;return this.x=r*s-i*o,this.y=i*a-n*s,this.z=n*o-r*a,this}projectOnVector(e){let t=e.lengthSq();if(t===0)return this.set(0,0,0);let n=e.dot(this)/t;return this.copy(e).multiplyScalar(n)}projectOnPlane(e){return Yw.copy(this).projectOnVector(e),this.sub(Yw)}reflect(e){return this.sub(Yw.copy(e).multiplyScalar(2*this.dot(e)))}angleTo(e){let t=Math.sqrt(this.lengthSq()*e.lengthSq());if(t===0)return Math.PI/2;let n=this.dot(e)/t;return Math.acos(Uw(n,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){let t=this.x-e.x,n=this.y-e.y,r=this.z-e.z;return t*t+n*n+r*r}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)+Math.abs(this.z-e.z)}setFromSpherical(e){return this.setFromSphericalCoords(e.radius,e.phi,e.theta)}setFromSphericalCoords(e,t,n){let r=Math.sin(t)*e;return this.x=r*Math.sin(n),this.y=Math.cos(t)*e,this.z=r*Math.cos(n),this}setFromCylindrical(e){return this.setFromCylindricalCoords(e.radius,e.theta,e.y)}setFromCylindricalCoords(e,t,n){return this.x=e*Math.sin(t),this.y=n,this.z=e*Math.cos(t),this}setFromMatrixPosition(e){let t=e.elements;return this.x=t[12],this.y=t[13],this.z=t[14],this}setFromMatrixScale(e){let t=this.setFromMatrixColumn(e,0).length(),n=this.setFromMatrixColumn(e,1).length(),r=this.setFromMatrixColumn(e,2).length();return this.x=t,this.y=n,this.z=r,this}setFromMatrixColumn(e,t){return this.fromArray(e.elements,t*4)}setFromMatrix3Column(e,t){return this.fromArray(e.elements,t*3)}setFromEuler(e){return this.x=e._x,this.y=e._y,this.z=e._z,this}setFromColor(e){return this.x=e.r,this.y=e.g,this.z=e.b,this}equals(e){return e.x===this.x&&e.y===this.y&&e.z===this.z}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this.z=e[t+2],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e[t+2]=this.z,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this.z=e.getZ(t),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this}randomDirection(){let e=Math.random()*Math.PI*2,t=Math.random()*2-1,n=Math.sqrt(1-t*t);return this.x=n*Math.cos(e),this.y=t,this.z=n*Math.sin(e),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z}},Yw=/*@__PURE__*/ new X,Xw=/*@__PURE__*/ new Jw,Z=class e{static{e.prototype.isMatrix3=!0}constructor(e,t,n,r,i,a,o,s,c){this.elements=[1,0,0,0,1,0,0,0,1],e!==void 0&&this.set(e,t,n,r,i,a,o,s,c)}set(e,t,n,r,i,a,o,s,c){let l=this.elements;return l[0]=e,l[1]=r,l[2]=o,l[3]=t,l[4]=i,l[5]=s,l[6]=n,l[7]=a,l[8]=c,this}identity(){return this.set(1,0,0,0,1,0,0,0,1),this}copy(e){let t=this.elements,n=e.elements;return t[0]=n[0],t[1]=n[1],t[2]=n[2],t[3]=n[3],t[4]=n[4],t[5]=n[5],t[6]=n[6],t[7]=n[7],t[8]=n[8],this}extractBasis(e,t,n){return e.setFromMatrix3Column(this,0),t.setFromMatrix3Column(this,1),n.setFromMatrix3Column(this,2),this}setFromMatrix4(e){let t=e.elements;return this.set(t[0],t[4],t[8],t[1],t[5],t[9],t[2],t[6],t[10]),this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,t){let n=e.elements,r=t.elements,i=this.elements,a=n[0],o=n[3],s=n[6],c=n[1],l=n[4],u=n[7],d=n[2],f=n[5],p=n[8],m=r[0],h=r[3],g=r[6],_=r[1],v=r[4],y=r[7],b=r[2],x=r[5],S=r[8];return i[0]=a*m+o*_+s*b,i[3]=a*h+o*v+s*x,i[6]=a*g+o*y+s*S,i[1]=c*m+l*_+u*b,i[4]=c*h+l*v+u*x,i[7]=c*g+l*y+u*S,i[2]=d*m+f*_+p*b,i[5]=d*h+f*v+p*x,i[8]=d*g+f*y+p*S,this}multiplyScalar(e){let t=this.elements;return t[0]*=e,t[3]*=e,t[6]*=e,t[1]*=e,t[4]*=e,t[7]*=e,t[2]*=e,t[5]*=e,t[8]*=e,this}determinant(){let e=this.elements,t=e[0],n=e[1],r=e[2],i=e[3],a=e[4],o=e[5],s=e[6],c=e[7],l=e[8];return t*a*l-t*o*c-n*i*l+n*o*s+r*i*c-r*a*s}invert(){let e=this.elements,t=e[0],n=e[1],r=e[2],i=e[3],a=e[4],o=e[5],s=e[6],c=e[7],l=e[8],u=l*a-o*c,d=o*s-l*i,f=c*i-a*s,p=t*u+n*d+r*f;if(p===0)return this.set(0,0,0,0,0,0,0,0,0);let m=1/p;return e[0]=u*m,e[1]=(r*c-l*n)*m,e[2]=(o*n-r*a)*m,e[3]=d*m,e[4]=(l*t-r*s)*m,e[5]=(r*i-o*t)*m,e[6]=f*m,e[7]=(n*s-c*t)*m,e[8]=(a*t-n*i)*m,this}transpose(){let e,t=this.elements;return e=t[1],t[1]=t[3],t[3]=e,e=t[2],t[2]=t[6],t[6]=e,e=t[5],t[5]=t[7],t[7]=e,this}getNormalMatrix(e){return this.setFromMatrix4(e).invert().transpose()}transposeIntoArray(e){let t=this.elements;return e[0]=t[0],e[1]=t[3],e[2]=t[6],e[3]=t[1],e[4]=t[4],e[5]=t[7],e[6]=t[2],e[7]=t[5],e[8]=t[8],this}setUvTransform(e,t,n,r,i,a,o){let s=Math.cos(i),c=Math.sin(i);return this.set(n*s,n*c,-n*(s*a+c*o)+a+e,-r*c,r*s,-r*(-c*a+s*o)+o+t,0,0,1),this}scale(e,t){return Fw(`Matrix3: .scale() is deprecated. Use .makeScale() instead.`),this.premultiply(Zw.makeScale(e,t)),this}rotate(e){return Fw(`Matrix3: .rotate() is deprecated. Use .makeRotation() instead.`),this.premultiply(Zw.makeRotation(-e)),this}translate(e,t){return Fw(`Matrix3: .translate() is deprecated. Use .makeTranslation() instead.`),this.premultiply(Zw.makeTranslation(e,t)),this}makeTranslation(e,t){return e.isVector2?this.set(1,0,e.x,0,1,e.y,0,0,1):this.set(1,0,e,0,1,t,0,0,1),this}makeRotation(e){let t=Math.cos(e),n=Math.sin(e);return this.set(t,-n,0,n,t,0,0,0,1),this}makeScale(e,t){return this.set(e,0,0,0,t,0,0,0,1),this}equals(e){let t=this.elements,n=e.elements;for(let e=0;e<9;e++)if(t[e]!==n[e])return!1;return!0}fromArray(e,t=0){for(let n=0;n<9;n++)this.elements[n]=e[n+t];return this}toArray(e=[],t=0){let n=this.elements;return e[t]=n[0],e[t+1]=n[1],e[t+2]=n[2],e[t+3]=n[3],e[t+4]=n[4],e[t+5]=n[5],e[t+6]=n[6],e[t+7]=n[7],e[t+8]=n[8],e}clone(){return new this.constructor().fromArray(this.elements)}},Zw=/*@__PURE__*/ new Z,Qw=/*@__PURE__*/ new Z().set(.4123908,.3575843,.1804808,.212639,.7151687,.0721923,.0193308,.1191948,.9505322),$w=/*@__PURE__*/ new Z().set(3.2409699,-1.5373832,-.4986108,-.9692436,1.8759675,.0415551,.0556301,-.203977,1.0569715);function eT(){let e={enabled:!0,workingColorSpace:xw,spaces:{},convert:function(e,t,n){return this.enabled===!1||t===n||!t||!n?e:(this.spaces[t].transfer===`srgb`&&(e.r=nT(e.r),e.g=nT(e.g),e.b=nT(e.b)),this.spaces[t].primaries!==this.spaces[n].primaries&&(e.applyMatrix3(this.spaces[t].toXYZ),e.applyMatrix3(this.spaces[n].fromXYZ)),this.spaces[n].transfer===`srgb`&&(e.r=rT(e.r),e.g=rT(e.g),e.b=rT(e.b)),e)},workingToColorSpace:function(e,t){return this.convert(e,this.workingColorSpace,t)},colorSpaceToWorking:function(e,t){return this.convert(e,t,this.workingColorSpace)},getPrimaries:function(e){return this.spaces[e].primaries},getTransfer:function(e){return e===``?Sw:this.spaces[e].transfer},getToneMappingMode:function(e){return this.spaces[e].outputColorSpaceConfig.toneMappingMode||`standard`},getLuminanceCoefficients:function(e,t=this.workingColorSpace){return e.fromArray(this.spaces[t].luminanceCoefficients)},define:function(e){Object.assign(this.spaces,e)},_getMatrix:function(e,t,n){return e.copy(this.spaces[t].toXYZ).multiply(this.spaces[n].fromXYZ)},_getDrawingBufferColorSpace:function(e){return this.spaces[e].outputColorSpaceConfig.drawingBufferColorSpace},_getUnpackColorSpace:function(e=this.workingColorSpace){return this.spaces[e].workingColorSpaceConfig.unpackColorSpace},fromWorkingColorSpace:function(t,n){return Fw(`ColorManagement: .fromWorkingColorSpace() has been renamed to .workingToColorSpace().`),e.workingToColorSpace(t,n)},toWorkingColorSpace:function(t,n){return Fw(`ColorManagement: .toWorkingColorSpace() has been renamed to .colorSpaceToWorking().`),e.colorSpaceToWorking(t,n)}},t=[.64,.33,.3,.6,.15,.06],n=[.2126,.7152,.0722],r=[.3127,.329];return e.define({[xw]:{primaries:t,whitePoint:r,transfer:Sw,toXYZ:Qw,fromXYZ:$w,luminanceCoefficients:n,workingColorSpaceConfig:{unpackColorSpace:bw},outputColorSpaceConfig:{drawingBufferColorSpace:bw}},[bw]:{primaries:t,whitePoint:r,transfer:Cw,toXYZ:Qw,fromXYZ:$w,luminanceCoefficients:n,outputColorSpaceConfig:{drawingBufferColorSpace:bw}}}),e}var tT=/*@__PURE__*/ eT();function nT(e){return e<.04045?e*.0773993808:(e*.9478672986+.0521327014)**2.4}function rT(e){return e<.0031308?e*12.92:1.055*e**.41666-.055}var iT,aT=class{static getDataURL(e,t=`image/png`){if(/^data:/i.test(e.src)||typeof HTMLCanvasElement>`u`)return e.src;let n;if(e instanceof HTMLCanvasElement)n=e;else{iT===void 0&&(iT=Aw(`canvas`)),iT.width=e.width,iT.height=e.height;let t=iT.getContext(`2d`);e instanceof ImageData?t.putImageData(e,0,0):t.drawImage(e,0,0,e.width,e.height),n=iT}return n.toDataURL(t)}static sRGBToLinear(e){if(typeof HTMLImageElement<`u`&&e instanceof HTMLImageElement||typeof HTMLCanvasElement<`u`&&e instanceof HTMLCanvasElement||typeof ImageBitmap<`u`&&e instanceof ImageBitmap){let t=Aw(`canvas`);t.width=e.width,t.height=e.height;let n=t.getContext(`2d`);n.drawImage(e,0,0,e.width,e.height);let r=n.getImageData(0,0,e.width,e.height),i=r.data;for(let e=0;e<i.length;e++)i[e]=nT(i[e]/255)*255;return n.putImageData(r,0,0),t}if(e.data){let t=e.data.slice(0);for(let e=0;e<t.length;e++)t instanceof Uint8Array||t instanceof Uint8ClampedArray?t[e]=Math.floor(nT(t[e]/255)*255):t[e]=nT(t[e]);return{data:t,width:e.width,height:e.height}}return q(`ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied.`),e}},oT=0,sT=class{constructor(e=null){this.isTextureSource=!0,Object.defineProperty(this,"id",{value:oT++}),this.uuid=Hw(),this.data=e,this.dataReady=!0,this.version=0}getSize(e){let t=this.data;return typeof HTMLVideoElement<`u`&&t instanceof HTMLVideoElement?e.set(t.videoWidth,t.videoHeight,0):typeof VideoFrame<`u`&&t instanceof VideoFrame?e.set(t.displayWidth,t.displayHeight,0):t===null?e.set(0,0,0):e.set(t.width,t.height,t.depth||0),e}set needsUpdate(e){e===!0&&this.version++}toJSON(e){let t=e===void 0||typeof e==`string`;if(!t&&e.images[this.uuid]!==void 0)return e.images[this.uuid];let n={uuid:this.uuid,url:``},r=this.data;if(r!==null){let e;if(Array.isArray(r)){e=[];for(let t=0,n=r.length;t<n;t++)r[t].isDataTexture?e.push(cT(r[t].image)):e.push(cT(r[t]))}else e=cT(r);n.url=e}return t||(e.images[this.uuid]=n),n}};function cT(e){return typeof HTMLImageElement<`u`&&e instanceof HTMLImageElement||typeof HTMLCanvasElement<`u`&&e instanceof HTMLCanvasElement||typeof ImageBitmap<`u`&&e instanceof ImageBitmap?aT.getDataURL(e):e.data?{data:Array.from(e.data),width:e.width,height:e.height,type:e.data.constructor.name}:(q(`Texture: Unable to serialize Texture.`),{})}var lT=0,uT=/*@__PURE__*/ new X,dT=class e extends Rw{constructor(t=e.DEFAULT_IMAGE,n=e.DEFAULT_MAPPING,r=$S,i=$S,a=iC,o=oC,s=SC,c=sC,l=e.DEFAULT_ANISOTROPY,u=``){super(),this.isTexture=!0,Object.defineProperty(this,"id",{value:lT++}),this.uuid=Hw(),this.name=``,this.source=new sT(t),this.mipmaps=[],this.mapping=n,this.channel=0,this.wrapS=r,this.wrapT=i,this.magFilter=a,this.minFilter=o,this.anisotropy=l,this.format=s,this.internalFormat=null,this.type=c,this.offset=new Y(0,0),this.repeat=new Y(1,1),this.center=new Y(0,0),this.rotation=0,this.matrixAutoUpdate=!0,this.matrix=new Z,this.generateMipmaps=!0,this.premultiplyAlpha=!1,this.flipY=!0,this.unpackAlignment=4,this.colorSpace=u,this.userData={},this.updateRanges=[],this.version=0,this.onUpdate=null,this.renderTarget=null,this.isRenderTargetTexture=!1,this.isArrayTexture=!!(t&&t.depth&&t.depth>1),this.pmremVersion=0,this.normalized=!1}get width(){return this.source.getSize(uT).x}get height(){return this.source.getSize(uT).y}get depth(){return this.source.getSize(uT).z}get image(){return this.source.data}set image(e){this.source.data=e}updateMatrix(){this.matrix.setUvTransform(this.offset.x,this.offset.y,this.repeat.x,this.repeat.y,this.rotation,this.center.x,this.center.y)}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}clone(){return new this.constructor().copy(this)}copy(e){return this.name=e.name,this.source=e.source,this.mipmaps=e.mipmaps.slice(0),this.mapping=e.mapping,this.channel=e.channel,this.wrapS=e.wrapS,this.wrapT=e.wrapT,this.magFilter=e.magFilter,this.minFilter=e.minFilter,this.anisotropy=e.anisotropy,this.format=e.format,this.internalFormat=e.internalFormat,this.type=e.type,this.normalized=e.normalized,this.offset.copy(e.offset),this.repeat.copy(e.repeat),this.center.copy(e.center),this.rotation=e.rotation,this.matrixAutoUpdate=e.matrixAutoUpdate,this.matrix.copy(e.matrix),this.generateMipmaps=e.generateMipmaps,this.premultiplyAlpha=e.premultiplyAlpha,this.flipY=e.flipY,this.unpackAlignment=e.unpackAlignment,this.colorSpace=e.colorSpace,this.renderTarget=e.renderTarget,this.isRenderTargetTexture=e.isRenderTargetTexture,this.isArrayTexture=e.isArrayTexture,this.userData=JSON.parse(JSON.stringify(e.userData)),this.needsUpdate=!0,this}setValues(e){for(let t in e){let n=e[t];if(n===void 0){q(`Texture.setValues(): parameter '${t}' has value of undefined.`);continue}let r=this[t];if(r===void 0){q(`Texture.setValues(): property '${t}' does not exist.`);continue}r&&n&&r.isVector2&&n.isVector2||r&&n&&r.isVector3&&n.isVector3||r&&n&&r.isMatrix3&&n.isMatrix3?r.copy(n):this[t]=n}}toJSON(e){let t=e===void 0||typeof e==`string`;if(!t&&e.textures[this.uuid]!==void 0)return e.textures[this.uuid];let n={metadata:{version:4.7,type:`Texture`,generator:`Texture.toJSON`},uuid:this.uuid,name:this.name,image:this.source.toJSON(e).uuid,mapping:this.mapping,channel:this.channel,repeat:[this.repeat.x,this.repeat.y],offset:[this.offset.x,this.offset.y],center:[this.center.x,this.center.y],rotation:this.rotation,wrap:[this.wrapS,this.wrapT],format:this.format,internalFormat:this.internalFormat,type:this.type,normalized:this.normalized,colorSpace:this.colorSpace,minFilter:this.minFilter,magFilter:this.magFilter,anisotropy:this.anisotropy,flipY:this.flipY,generateMipmaps:this.generateMipmaps,premultiplyAlpha:this.premultiplyAlpha,unpackAlignment:this.unpackAlignment};return Object.keys(this.userData).length>0&&(n.userData=this.userData),t||(e.textures[this.uuid]=n),n}dispose(){this.dispatchEvent({type:`dispose`})}transformUv(e){if(this.mapping!==300)return e;if(e.applyMatrix3(this.matrix),e.x<0||e.x>1)switch(this.wrapS){case QS:e.x-=Math.floor(e.x);break;case $S:e.x=e.x<0?0:1;break;case eC:Math.abs(Math.floor(e.x)%2)===1?e.x=Math.ceil(e.x)-e.x:e.x-=Math.floor(e.x)}if(e.y<0||e.y>1)switch(this.wrapT){case QS:e.y-=Math.floor(e.y);break;case $S:e.y=e.y<0?0:1;break;case eC:Math.abs(Math.floor(e.y)%2)===1?e.y=Math.ceil(e.y)-e.y:e.y-=Math.floor(e.y)}return this.flipY&&(e.y=1-e.y),e}set needsUpdate(e){e===!0&&(this.version++,this.source.needsUpdate=!0)}set needsPMREMUpdate(e){e===!0&&this.pmremVersion++}};dT.DEFAULT_IMAGE=null,dT.DEFAULT_MAPPING=300,dT.DEFAULT_ANISOTROPY=1;var fT=class e{static{e.prototype.isVector4=!0}constructor(e=0,t=0,n=0,r=1){this.x=e,this.y=t,this.z=n,this.w=r}get width(){return this.z}set width(e){this.z=e}get height(){return this.w}set height(e){this.w=e}set(e,t,n,r){return this.x=e,this.y=t,this.z=n,this.w=r,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this.w=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setW(e){return this.w=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;case 2:this.z=t;break;case 3:this.w=t;break;default:throw Error(`THREE.Vector4: index is out of range: `+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;case 3:return this.w;default:throw Error(`THREE.Vector4: index is out of range: `+e)}}clone(){return new this.constructor(this.x,this.y,this.z,this.w)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this.w=e.w===void 0?1:e.w,this}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this.w+=e.w,this}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this.w+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this.z=e.z+t.z,this.w=e.w+t.w,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this.z+=e.z*t,this.w+=e.w*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this.w-=e.w,this}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this.w-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this.z=e.z-t.z,this.w=e.w-t.w,this}multiply(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this.w*=e.w,this}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this.w*=e,this}applyMatrix4(e){let t=this.x,n=this.y,r=this.z,i=this.w,a=e.elements;return this.x=a[0]*t+a[4]*n+a[8]*r+a[12]*i,this.y=a[1]*t+a[5]*n+a[9]*r+a[13]*i,this.z=a[2]*t+a[6]*n+a[10]*r+a[14]*i,this.w=a[3]*t+a[7]*n+a[11]*r+a[15]*i,this}divide(e){return this.x/=e.x,this.y/=e.y,this.z/=e.z,this.w/=e.w,this}divideScalar(e){return this.multiplyScalar(1/e)}setAxisAngleFromQuaternion(e){this.w=2*Math.acos(e.w);let t=Math.sqrt(1-e.w*e.w);return t<1e-4?(this.x=1,this.y=0,this.z=0):(this.x=e.x/t,this.y=e.y/t,this.z=e.z/t),this}setAxisAngleFromRotationMatrix(e){let t,n,r,i,a=.01,o=.1,s=e.elements,c=s[0],l=s[4],u=s[8],d=s[1],f=s[5],p=s[9],m=s[2],h=s[6],g=s[10];if(Math.abs(l-d)<a&&Math.abs(u-m)<a&&Math.abs(p-h)<a){if(Math.abs(l+d)<o&&Math.abs(u+m)<o&&Math.abs(p+h)<o&&Math.abs(c+f+g-3)<o)return this.set(1,0,0,0),this;t=Math.PI;let e=(c+1)/2,s=(f+1)/2,_=(g+1)/2,v=(l+d)/4,y=(u+m)/4,b=(p+h)/4;return e>s&&e>_?e<a?(n=0,r=.707106781,i=.707106781):(n=Math.sqrt(e),r=v/n,i=y/n):s>_?s<a?(n=.707106781,r=0,i=.707106781):(r=Math.sqrt(s),n=v/r,i=b/r):_<a?(n=.707106781,r=.707106781,i=0):(i=Math.sqrt(_),n=y/i,r=b/i),this.set(n,r,i,t),this}let _=Math.sqrt((h-p)*(h-p)+(u-m)*(u-m)+(d-l)*(d-l));return Math.abs(_)<.001&&(_=1),this.x=(h-p)/_,this.y=(u-m)/_,this.z=(d-l)/_,this.w=Math.acos((c+f+g-1)/2),this}setFromMatrixPosition(e){let t=e.elements;return this.x=t[12],this.y=t[13],this.z=t[14],this.w=t[15],this}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this.z=Math.min(this.z,e.z),this.w=Math.min(this.w,e.w),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this.z=Math.max(this.z,e.z),this.w=Math.max(this.w,e.w),this}clamp(e,t){return this.x=Uw(this.x,e.x,t.x),this.y=Uw(this.y,e.y,t.y),this.z=Uw(this.z,e.z,t.z),this.w=Uw(this.w,e.w,t.w),this}clampScalar(e,t){return this.x=Uw(this.x,e,t),this.y=Uw(this.y,e,t),this.z=Uw(this.z,e,t),this.w=Uw(this.w,e,t),this}clampLength(e,t){let n=this.length();return this.divideScalar(n||1).multiplyScalar(Uw(n,e,t))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this.w=Math.floor(this.w),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this.w=Math.ceil(this.w),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this.w=Math.round(this.w),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this.w=Math.trunc(this.w),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this.w=-this.w,this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z+this.w*e.w}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)+Math.abs(this.w)}normalize(){return this.divideScalar(this.length()||1)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this.z+=(e.z-this.z)*t,this.w+=(e.w-this.w)*t,this}lerpVectors(e,t,n){return this.x=e.x+(t.x-e.x)*n,this.y=e.y+(t.y-e.y)*n,this.z=e.z+(t.z-e.z)*n,this.w=e.w+(t.w-e.w)*n,this}equals(e){return e.x===this.x&&e.y===this.y&&e.z===this.z&&e.w===this.w}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this.z=e[t+2],this.w=e[t+3],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e[t+2]=this.z,e[t+3]=this.w,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this.z=e.getZ(t),this.w=e.getW(t),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this.w=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z,yield this.w}},pT=class extends Rw{constructor(e=1,t=1,n={}){super(),n=Object.assign({generateMipmaps:!1,internalFormat:null,minFilter:iC,depthBuffer:!0,stencilBuffer:!1,resolveColorBuffer:!0,resolveDepthBuffer:!0,resolveStencilBuffer:!0,storeMultisampledColorBuffer:!0,storeMultisampledDepthBuffer:!0,storeMultisampledStencilBuffer:!0,depthTexture:null,samples:0,count:1,depth:1,multiview:!1,useArrayDepthTexture:!1},n),this.isRenderTarget=!0,this.width=e,this.height=t,this.depth=n.depth,this.scissor=new fT(0,0,e,t),this.scissorTest=!1,this.viewport=new fT(0,0,e,t),this.textures=[];let r=new dT({width:e,height:t,depth:n.depth}),i=n.count;for(let e=0;e<i;e++)this.textures[e]=r.clone(),this.textures[e].isRenderTargetTexture=!0,this.textures[e].renderTarget=this;this._setTextureOptions(n),this.depthBuffer=n.depthBuffer,this.stencilBuffer=n.stencilBuffer,this.resolveColorBuffer=n.resolveColorBuffer,this.resolveDepthBuffer=n.resolveDepthBuffer,this.resolveStencilBuffer=n.resolveStencilBuffer,this.storeMultisampledColorBuffer=n.storeMultisampledColorBuffer,this.storeMultisampledDepthBuffer=n.storeMultisampledDepthBuffer,this.storeMultisampledStencilBuffer=n.storeMultisampledStencilBuffer,this._depthTexture=null,this.depthTexture=n.depthTexture,this.samples=n.samples,this.multiview=n.multiview,this.useArrayDepthTexture=n.useArrayDepthTexture}_setTextureOptions(e={}){let t={minFilter:iC,generateMipmaps:!1,flipY:!1,internalFormat:null};e.mapping!==void 0&&(t.mapping=e.mapping),e.wrapS!==void 0&&(t.wrapS=e.wrapS),e.wrapT!==void 0&&(t.wrapT=e.wrapT),e.wrapR!==void 0&&(t.wrapR=e.wrapR),e.magFilter!==void 0&&(t.magFilter=e.magFilter),e.minFilter!==void 0&&(t.minFilter=e.minFilter),e.format!==void 0&&(t.format=e.format),e.type!==void 0&&(t.type=e.type),e.anisotropy!==void 0&&(t.anisotropy=e.anisotropy),e.colorSpace!==void 0&&(t.colorSpace=e.colorSpace),e.flipY!==void 0&&(t.flipY=e.flipY),e.generateMipmaps!==void 0&&(t.generateMipmaps=e.generateMipmaps),e.internalFormat!==void 0&&(t.internalFormat=e.internalFormat);for(let e=0;e<this.textures.length;e++)this.textures[e].setValues(t)}get texture(){return this.textures[0]}set texture(e){this.textures[0]=e}set depthTexture(e){this._depthTexture!==null&&this._depthTexture.renderTarget===this&&(this._depthTexture.renderTarget=null),e!==null&&e.renderTarget===null&&(e.renderTarget=this),this._depthTexture=e}get depthTexture(){return this._depthTexture}setSize(e,t,n=1){if(this.width!==e||this.height!==t||this.depth!==n){this.width=e,this.height=t,this.depth=n;for(let r=0,i=this.textures.length;r<i;r++)this.textures[r].image.width=e,this.textures[r].image.height=t,this.textures[r].image.depth=n,this.textures[r].isData3DTexture!==!0&&(this.textures[r].isArrayTexture=this.textures[r].image.depth>1);this.dispose()}this.viewport.set(0,0,e,t),this.scissor.set(0,0,e,t)}clone(){return new this.constructor().copy(this)}copy(e){this.width=e.width,this.height=e.height,this.depth=e.depth,this.scissor.copy(e.scissor),this.scissorTest=e.scissorTest,this.viewport.copy(e.viewport),this.textures.length=0;for(let t=0,n=e.textures.length;t<n;t++){this.textures[t]=e.textures[t].clone(),this.textures[t].isRenderTargetTexture=!0,this.textures[t].renderTarget=this;let n=Object.assign({},e.textures[t].image);this.textures[t].source=new sT(n)}if(this.depthBuffer=e.depthBuffer,this.stencilBuffer=e.stencilBuffer,this.resolveColorBuffer=e.resolveColorBuffer,this.resolveDepthBuffer=e.resolveDepthBuffer,this.resolveStencilBuffer=e.resolveStencilBuffer,this.storeMultisampledColorBuffer=e.storeMultisampledColorBuffer,this.storeMultisampledDepthBuffer=e.storeMultisampledDepthBuffer,this.storeMultisampledStencilBuffer=e.storeMultisampledStencilBuffer,e.depthTexture!==null){if(e.depthTexture.renderTarget===e){let t=e.depthTexture.clone();t.renderTarget=null,this.depthTexture=t}else this.depthTexture=e.depthTexture}return this.samples=e.samples,this.multiview=e.multiview,this.useArrayDepthTexture=e.useArrayDepthTexture,this}dispose(){this.dispatchEvent({type:`dispose`})}},mT=class extends pT{constructor(e=1,t=1,n={}){super(e,t,n),this.isWebGLRenderTarget=!0}},hT=class extends dT{constructor(e=null,t=1,n=1,r=1){super(null),this.isDataArrayTexture=!0,this.image={data:e,width:t,height:n,depth:r},this.magFilter=tC,this.minFilter=tC,this.wrapR=$S,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1,this.layerUpdates=/* @__PURE__ */ new Set}copy(e){return super.copy(e),this.wrapR=e.wrapR,this}addLayerUpdate(e){this.layerUpdates.add(e)}clearLayerUpdates(){this.layerUpdates.clear()}},gT=class extends dT{constructor(e=null,t=1,n=1,r=1){super(null),this.isData3DTexture=!0,this.image={data:e,width:t,height:n,depth:r},this.magFilter=tC,this.minFilter=tC,this.wrapR=$S,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}copy(e){return super.copy(e),this.wrapR=e.wrapR,this}},_T=class e{static{e.prototype.isMatrix4=!0}constructor(e,t,n,r,i,a,o,s,c,l,u,d,f,p,m,h){this.elements=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],e!==void 0&&this.set(e,t,n,r,i,a,o,s,c,l,u,d,f,p,m,h)}set(e,t,n,r,i,a,o,s,c,l,u,d,f,p,m,h){let g=this.elements;return g[0]=e,g[4]=t,g[8]=n,g[12]=r,g[1]=i,g[5]=a,g[9]=o,g[13]=s,g[2]=c,g[6]=l,g[10]=u,g[14]=d,g[3]=f,g[7]=p,g[11]=m,g[15]=h,this}identity(){return this.set(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1),this}clone(){return new e().fromArray(this.elements)}copy(e){let t=this.elements,n=e.elements;return t[0]=n[0],t[1]=n[1],t[2]=n[2],t[3]=n[3],t[4]=n[4],t[5]=n[5],t[6]=n[6],t[7]=n[7],t[8]=n[8],t[9]=n[9],t[10]=n[10],t[11]=n[11],t[12]=n[12],t[13]=n[13],t[14]=n[14],t[15]=n[15],this}copyPosition(e){let t=this.elements,n=e.elements;return t[12]=n[12],t[13]=n[13],t[14]=n[14],this}setFromMatrix3(e){let t=e.elements;return this.set(t[0],t[3],t[6],0,t[1],t[4],t[7],0,t[2],t[5],t[8],0,0,0,0,1),this}extractBasis(e,t,n){return this.determinantAffine()===0?(e.set(1,0,0),t.set(0,1,0),n.set(0,0,1),this):(e.setFromMatrixColumn(this,0),t.setFromMatrixColumn(this,1),n.setFromMatrixColumn(this,2),this)}makeBasis(e,t,n){return this.set(e.x,t.x,n.x,0,e.y,t.y,n.y,0,e.z,t.z,n.z,0,0,0,0,1),this}extractRotation(e){if(e.determinantAffine()===0)return this.identity();let t=this.elements,n=e.elements,r=1/vT.setFromMatrixColumn(e,0).length(),i=1/vT.setFromMatrixColumn(e,1).length(),a=1/vT.setFromMatrixColumn(e,2).length();return t[0]=n[0]*r,t[1]=n[1]*r,t[2]=n[2]*r,t[3]=0,t[4]=n[4]*i,t[5]=n[5]*i,t[6]=n[6]*i,t[7]=0,t[8]=n[8]*a,t[9]=n[9]*a,t[10]=n[10]*a,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this}makeRotationFromEuler(e){let t=this.elements,n=e.x,r=e.y,i=e.z,a=Math.cos(n),o=Math.sin(n),s=Math.cos(r),c=Math.sin(r),l=Math.cos(i),u=Math.sin(i);if(e.order===`XYZ`){let e=a*l,n=a*u,r=o*l,i=o*u;t[0]=s*l,t[4]=-s*u,t[8]=c,t[1]=n+r*c,t[5]=e-i*c,t[9]=-o*s,t[2]=i-e*c,t[6]=r+n*c,t[10]=a*s}else if(e.order===`YXZ`){let e=s*l,n=s*u,r=c*l,i=c*u;t[0]=e+i*o,t[4]=r*o-n,t[8]=a*c,t[1]=a*u,t[5]=a*l,t[9]=-o,t[2]=n*o-r,t[6]=i+e*o,t[10]=a*s}else if(e.order===`ZXY`){let e=s*l,n=s*u,r=c*l,i=c*u;t[0]=e-i*o,t[4]=-a*u,t[8]=r+n*o,t[1]=n+r*o,t[5]=a*l,t[9]=i-e*o,t[2]=-a*c,t[6]=o,t[10]=a*s}else if(e.order===`ZYX`){let e=a*l,n=a*u,r=o*l,i=o*u;t[0]=s*l,t[4]=r*c-n,t[8]=e*c+i,t[1]=s*u,t[5]=i*c+e,t[9]=n*c-r,t[2]=-c,t[6]=o*s,t[10]=a*s}else if(e.order===`YZX`){let e=a*s,n=a*c,r=o*s,i=o*c;t[0]=s*l,t[4]=i-e*u,t[8]=r*u+n,t[1]=u,t[5]=a*l,t[9]=-o*l,t[2]=-c*l,t[6]=n*u+r,t[10]=e-i*u}else if(e.order===`XZY`){let e=a*s,n=a*c,r=o*s,i=o*c;t[0]=s*l,t[4]=-u,t[8]=c*l,t[1]=e*u+i,t[5]=a*l,t[9]=n*u-r,t[2]=r*u-n,t[6]=o*l,t[10]=i*u+e}return t[3]=0,t[7]=0,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this}makeRotationFromQuaternion(e){return this.compose(bT,e,xT)}lookAt(e,t,n){let r=this.elements;return wT.subVectors(e,t),wT.lengthSq()===0&&(wT.z=1),wT.normalize(),ST.crossVectors(n,wT),ST.lengthSq()===0&&(Math.abs(n.z)===1?wT.x+=1e-4:wT.z+=1e-4,wT.normalize(),ST.crossVectors(n,wT)),ST.normalize(),CT.crossVectors(wT,ST),r[0]=ST.x,r[4]=CT.x,r[8]=wT.x,r[1]=ST.y,r[5]=CT.y,r[9]=wT.y,r[2]=ST.z,r[6]=CT.z,r[10]=wT.z,this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,t){let n=e.elements,r=t.elements,i=this.elements,a=n[0],o=n[4],s=n[8],c=n[12],l=n[1],u=n[5],d=n[9],f=n[13],p=n[2],m=n[6],h=n[10],g=n[14],_=n[3],v=n[7],y=n[11],b=n[15],x=r[0],S=r[4],C=r[8],w=r[12],T=r[1],E=r[5],D=r[9],O=r[13],k=r[2],A=r[6],ee=r[10],te=r[14],j=r[3],ne=r[7],re=r[11],M=r[15];return i[0]=a*x+o*T+s*k+c*j,i[4]=a*S+o*E+s*A+c*ne,i[8]=a*C+o*D+s*ee+c*re,i[12]=a*w+o*O+s*te+c*M,i[1]=l*x+u*T+d*k+f*j,i[5]=l*S+u*E+d*A+f*ne,i[9]=l*C+u*D+d*ee+f*re,i[13]=l*w+u*O+d*te+f*M,i[2]=p*x+m*T+h*k+g*j,i[6]=p*S+m*E+h*A+g*ne,i[10]=p*C+m*D+h*ee+g*re,i[14]=p*w+m*O+h*te+g*M,i[3]=_*x+v*T+y*k+b*j,i[7]=_*S+v*E+y*A+b*ne,i[11]=_*C+v*D+y*ee+b*re,i[15]=_*w+v*O+y*te+b*M,this}multiplyScalar(e){let t=this.elements;return t[0]*=e,t[4]*=e,t[8]*=e,t[12]*=e,t[1]*=e,t[5]*=e,t[9]*=e,t[13]*=e,t[2]*=e,t[6]*=e,t[10]*=e,t[14]*=e,t[3]*=e,t[7]*=e,t[11]*=e,t[15]*=e,this}determinant(){let e=this.elements,t=e[0],n=e[4],r=e[8],i=e[12],a=e[1],o=e[5],s=e[9],c=e[13],l=e[2],u=e[6],d=e[10],f=e[14],p=e[3],m=e[7],h=e[11],g=e[15],_=s*f-c*d,v=o*f-c*u,y=o*d-s*u,b=a*f-c*l,x=a*d-s*l,S=a*u-o*l;return t*(m*_-h*v+g*y)-n*(p*_-h*b+g*x)+r*(p*v-m*b+g*S)-i*(p*y-m*x+h*S)}determinantAffine(){let e=this.elements,t=e[0],n=e[4],r=e[8],i=e[1],a=e[5],o=e[9],s=e[2],c=e[6],l=e[10];return t*(a*l-o*c)-n*(i*l-o*s)+r*(i*c-a*s)}transpose(){let e=this.elements,t;return t=e[1],e[1]=e[4],e[4]=t,t=e[2],e[2]=e[8],e[8]=t,t=e[6],e[6]=e[9],e[9]=t,t=e[3],e[3]=e[12],e[12]=t,t=e[7],e[7]=e[13],e[13]=t,t=e[11],e[11]=e[14],e[14]=t,this}setPosition(e,t,n){let r=this.elements;return e.isVector3?(r[12]=e.x,r[13]=e.y,r[14]=e.z):(r[12]=e,r[13]=t,r[14]=n),this}invert(){let e=this.elements,t=e[0],n=e[1],r=e[2],i=e[3],a=e[4],o=e[5],s=e[6],c=e[7],l=e[8],u=e[9],d=e[10],f=e[11],p=e[12],m=e[13],h=e[14],g=e[15],_=t*o-n*a,v=t*s-r*a,y=t*c-i*a,b=n*s-r*o,x=n*c-i*o,S=r*c-i*s,C=l*m-u*p,w=l*h-d*p,T=l*g-f*p,E=u*h-d*m,D=u*g-f*m,O=d*g-f*h,k=_*O-v*D+y*E+b*T-x*w+S*C;if(k===0)return this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);let A=1/k;return e[0]=(o*O-s*D+c*E)*A,e[1]=(r*D-n*O-i*E)*A,e[2]=(m*S-h*x+g*b)*A,e[3]=(d*x-u*S-f*b)*A,e[4]=(s*T-a*O-c*w)*A,e[5]=(t*O-r*T+i*w)*A,e[6]=(h*y-p*S-g*v)*A,e[7]=(l*S-d*y+f*v)*A,e[8]=(a*D-o*T+c*C)*A,e[9]=(n*T-t*D-i*C)*A,e[10]=(p*x-m*y+g*_)*A,e[11]=(u*y-l*x-f*_)*A,e[12]=(o*w-a*E-s*C)*A,e[13]=(t*E-n*w+r*C)*A,e[14]=(m*v-p*b-h*_)*A,e[15]=(l*b-u*v+d*_)*A,this}scale(e){let t=this.elements,n=e.x,r=e.y,i=e.z;return t[0]*=n,t[4]*=r,t[8]*=i,t[1]*=n,t[5]*=r,t[9]*=i,t[2]*=n,t[6]*=r,t[10]*=i,t[3]*=n,t[7]*=r,t[11]*=i,this}getMaxScaleOnAxis(){let e=this.elements,t=e[0]*e[0]+e[1]*e[1]+e[2]*e[2],n=e[4]*e[4]+e[5]*e[5]+e[6]*e[6],r=e[8]*e[8]+e[9]*e[9]+e[10]*e[10];return Math.sqrt(Math.max(t,n,r))}makeTranslation(e,t,n){return e.isVector3?this.set(1,0,0,e.x,0,1,0,e.y,0,0,1,e.z,0,0,0,1):this.set(1,0,0,e,0,1,0,t,0,0,1,n,0,0,0,1),this}makeRotationX(e){let t=Math.cos(e),n=Math.sin(e);return this.set(1,0,0,0,0,t,-n,0,0,n,t,0,0,0,0,1),this}makeRotationY(e){let t=Math.cos(e),n=Math.sin(e);return this.set(t,0,n,0,0,1,0,0,-n,0,t,0,0,0,0,1),this}makeRotationZ(e){let t=Math.cos(e),n=Math.sin(e);return this.set(t,-n,0,0,n,t,0,0,0,0,1,0,0,0,0,1),this}makeRotationAxis(e,t){let n=Math.cos(t),r=Math.sin(t),i=1-n,a=e.x,o=e.y,s=e.z,c=i*a,l=i*o;return this.set(c*a+n,c*o-r*s,c*s+r*o,0,c*o+r*s,l*o+n,l*s-r*a,0,c*s-r*o,l*s+r*a,i*s*s+n,0,0,0,0,1),this}makeScale(e,t,n){return this.set(e,0,0,0,0,t,0,0,0,0,n,0,0,0,0,1),this}makeShear(e,t,n,r,i,a){return this.set(1,n,i,0,e,1,a,0,t,r,1,0,0,0,0,1),this}compose(e,t,n){let r=this.elements,i=t._x,a=t._y,o=t._z,s=t._w,c=i+i,l=a+a,u=o+o,d=i*c,f=i*l,p=i*u,m=a*l,h=a*u,g=o*u,_=s*c,v=s*l,y=s*u,b=n.x,x=n.y,S=n.z;return r[0]=(1-(m+g))*b,r[1]=(f+y)*b,r[2]=(p-v)*b,r[3]=0,r[4]=(f-y)*x,r[5]=(1-(d+g))*x,r[6]=(h+_)*x,r[7]=0,r[8]=(p+v)*S,r[9]=(h-_)*S,r[10]=(1-(d+m))*S,r[11]=0,r[12]=e.x,r[13]=e.y,r[14]=e.z,r[15]=1,this}decompose(e,t,n){let r=this.elements;e.x=r[12],e.y=r[13],e.z=r[14];let i=this.determinantAffine();if(i===0)return n.set(1,1,1),t.identity(),this;let a=vT.set(r[0],r[1],r[2]).length(),o=vT.set(r[4],r[5],r[6]).length(),s=vT.set(r[8],r[9],r[10]).length();i<0&&(a=-a),yT.copy(this);let c=1/a,l=1/o,u=1/s;return yT.elements[0]*=c,yT.elements[1]*=c,yT.elements[2]*=c,yT.elements[4]*=l,yT.elements[5]*=l,yT.elements[6]*=l,yT.elements[8]*=u,yT.elements[9]*=u,yT.elements[10]*=u,t.setFromRotationMatrix(yT),n.x=a,n.y=o,n.z=s,this}makePerspective(e,t,n,r,i,a,o=Dw,s=!1){let c=this.elements,l=2*i/(t-e),u=2*i/(n-r),d=(t+e)/(t-e),f=(n+r)/(n-r),p,m;if(s)p=i/(a-i),m=a*i/(a-i);else if(o===2e3)p=-(a+i)/(a-i),m=-2*a*i/(a-i);else if(o===2001)p=-a/(a-i),m=-a*i/(a-i);else throw Error(`THREE.Matrix4.makePerspective(): Invalid coordinate system: `+o);return c[0]=l,c[4]=0,c[8]=d,c[12]=0,c[1]=0,c[5]=u,c[9]=f,c[13]=0,c[2]=0,c[6]=0,c[10]=p,c[14]=m,c[3]=0,c[7]=0,c[11]=-1,c[15]=0,this}makeOrthographic(e,t,n,r,i,a,o=Dw,s=!1){let c=this.elements,l=2/(t-e),u=2/(n-r),d=-(t+e)/(t-e),f=-(n+r)/(n-r),p,m;if(s)p=1/(a-i),m=a/(a-i);else if(o===2e3)p=-2/(a-i),m=-(a+i)/(a-i);else if(o===2001)p=-1/(a-i),m=-i/(a-i);else throw Error(`THREE.Matrix4.makeOrthographic(): Invalid coordinate system: `+o);return c[0]=l,c[4]=0,c[8]=0,c[12]=d,c[1]=0,c[5]=u,c[9]=0,c[13]=f,c[2]=0,c[6]=0,c[10]=p,c[14]=m,c[3]=0,c[7]=0,c[11]=0,c[15]=1,this}equals(e){let t=this.elements,n=e.elements;for(let e=0;e<16;e++)if(t[e]!==n[e])return!1;return!0}fromArray(e,t=0){for(let n=0;n<16;n++)this.elements[n]=e[n+t];return this}toArray(e=[],t=0){let n=this.elements;return e[t]=n[0],e[t+1]=n[1],e[t+2]=n[2],e[t+3]=n[3],e[t+4]=n[4],e[t+5]=n[5],e[t+6]=n[6],e[t+7]=n[7],e[t+8]=n[8],e[t+9]=n[9],e[t+10]=n[10],e[t+11]=n[11],e[t+12]=n[12],e[t+13]=n[13],e[t+14]=n[14],e[t+15]=n[15],e}},vT=/*@__PURE__*/ new X,yT=/*@__PURE__*/ new _T,bT=/*@__PURE__*/ new X(0,0,0),xT=/*@__PURE__*/ new X(1,1,1),ST=/*@__PURE__*/ new X,CT=/*@__PURE__*/ new X,wT=/*@__PURE__*/ new X,TT=/*@__PURE__*/ new _T,ET=/*@__PURE__*/ new Jw,DT=class e{constructor(t=0,n=0,r=0,i=e.DEFAULT_ORDER){this.isEuler=!0,this._x=t,this._y=n,this._z=r,this._order=i}get x(){return this._x}set x(e){this._x=e,this._onChangeCallback()}get y(){return this._y}set y(e){this._y=e,this._onChangeCallback()}get z(){return this._z}set z(e){this._z=e,this._onChangeCallback()}get order(){return this._order}set order(e){this._order=e,this._onChangeCallback()}set(e,t,n,r=this._order){return this._x=e,this._y=t,this._z=n,this._order=r,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._order)}copy(e){return this._x=e._x,this._y=e._y,this._z=e._z,this._order=e._order,this._onChangeCallback(),this}setFromRotationMatrix(e,t=this._order,n=!0){let r=e.elements,i=r[0],a=r[4],o=r[8],s=r[1],c=r[5],l=r[9],u=r[2],d=r[6],f=r[10];switch(t){case`XYZ`:this._y=Math.asin(Uw(o,-1,1)),Math.abs(o)<.9999999?(this._x=Math.atan2(-l,f),this._z=Math.atan2(-a,i)):(this._x=Math.atan2(d,c),this._z=0);break;case`YXZ`:this._x=Math.asin(-Uw(l,-1,1)),Math.abs(l)<.9999999?(this._y=Math.atan2(o,f),this._z=Math.atan2(s,c)):(this._y=Math.atan2(-u,i),this._z=0);break;case`ZXY`:this._x=Math.asin(Uw(d,-1,1)),Math.abs(d)<.9999999?(this._y=Math.atan2(-u,f),this._z=Math.atan2(-a,c)):(this._y=0,this._z=Math.atan2(s,i));break;case`ZYX`:this._y=Math.asin(-Uw(u,-1,1)),Math.abs(u)<.9999999?(this._x=Math.atan2(d,f),this._z=Math.atan2(s,i)):(this._x=0,this._z=Math.atan2(-a,c));break;case`YZX`:this._z=Math.asin(Uw(s,-1,1)),Math.abs(s)<.9999999?(this._x=Math.atan2(-l,c),this._y=Math.atan2(-u,i)):(this._x=0,this._y=Math.atan2(o,f));break;case`XZY`:this._z=Math.asin(-Uw(a,-1,1)),Math.abs(a)<.9999999?(this._x=Math.atan2(d,c),this._y=Math.atan2(o,i)):(this._x=Math.atan2(-l,f),this._y=0);break;default:q(`Euler: .setFromRotationMatrix() encountered an unknown order: `+t)}return this._order=t,n===!0&&this._onChangeCallback(),this}setFromQuaternion(e,t,n){return TT.makeRotationFromQuaternion(e),this.setFromRotationMatrix(TT,t,n)}setFromVector3(e,t=this._order){return this.set(e.x,e.y,e.z,t)}reorder(e){return ET.setFromEuler(this),this.setFromQuaternion(ET,e)}equals(e){return e._x===this._x&&e._y===this._y&&e._z===this._z&&e._order===this._order}fromArray(e){return this._x=e[0],this._y=e[1],this._z=e[2],e[3]!==void 0&&(this._order=e[3]),this._onChangeCallback(),this}toArray(e=[],t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,e[t+3]=this._order,e}_onChange(e){return this._onChangeCallback=e,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._order}};DT.DEFAULT_ORDER=`XYZ`;var OT=class{constructor(){this.mask=1}set(e){this.mask=(1<<e|0)>>>0}enable(e){this.mask|=1<<e|0}enableAll(){this.mask=-1}toggle(e){this.mask^=1<<e|0}disable(e){this.mask&=~(1<<e|0)}disableAll(){this.mask=0}test(e){return(this.mask&e.mask)!==0}isEnabled(e){return!!(this.mask&(1<<e|0))}},kT=0,AT=/*@__PURE__*/ new X,jT=/*@__PURE__*/ new Jw,MT=/*@__PURE__*/ new _T,NT=/*@__PURE__*/ new X,PT=/*@__PURE__*/ new X,FT=/*@__PURE__*/ new X,IT=/*@__PURE__*/ new Jw,LT=/*@__PURE__*/ new X(1,0,0),RT=/*@__PURE__*/ new X(0,1,0),zT=/*@__PURE__*/ new X(0,0,1),BT={type:`added`},VT={type:`removed`},HT={type:`childadded`,child:null},UT={type:`childremoved`,child:null},WT=class e extends Rw{constructor(){super(),this.isObject3D=!0,Object.defineProperty(this,"id",{value:kT++}),this.uuid=Hw(),this.name=``,this.type=`Object3D`,this.parent=null,this.children=[],this.up=e.DEFAULT_UP.clone();let t=new X,n=new DT,r=new Jw,i=new X(1,1,1);function a(){r.setFromEuler(n,!1)}function o(){n.setFromQuaternion(r,void 0,!1)}n._onChange(a),r._onChange(o),Object.defineProperties(this,{position:{configurable:!0,enumerable:!0,value:t},rotation:{configurable:!0,enumerable:!0,value:n},quaternion:{configurable:!0,enumerable:!0,value:r},scale:{configurable:!0,enumerable:!0,value:i},modelViewMatrix:{value:new _T},normalMatrix:{value:new Z}}),this.matrix=new _T,this.matrixWorld=new _T,this.matrixAutoUpdate=e.DEFAULT_MATRIX_AUTO_UPDATE,this.matrixWorldAutoUpdate=e.DEFAULT_MATRIX_WORLD_AUTO_UPDATE,this.matrixWorldNeedsUpdate=!1,this.layers=new OT,this.visible=!0,this.castShadow=!1,this.receiveShadow=!1,this.frustumCulled=!0,this.renderOrder=0,this.animations=[],this.customDepthMaterial=void 0,this.customDistanceMaterial=void 0,this.static=!1,this.userData={},this.pivot=null}onBeforeShadow(){}onAfterShadow(){}onBeforeRender(){}onAfterRender(){}applyMatrix4(e){this.matrixAutoUpdate&&this.updateMatrix(),this.matrix.premultiply(e),this.matrix.decompose(this.position,this.quaternion,this.scale)}applyQuaternion(e){return this.quaternion.premultiply(e),this}setRotationFromAxisAngle(e,t){this.quaternion.setFromAxisAngle(e,t)}setRotationFromEuler(e){this.quaternion.setFromEuler(e,!0)}setRotationFromMatrix(e){this.quaternion.setFromRotationMatrix(e)}setRotationFromQuaternion(e){this.quaternion.copy(e)}rotateOnAxis(e,t){return jT.setFromAxisAngle(e,t),this.quaternion.multiply(jT),this}rotateOnWorldAxis(e,t){return jT.setFromAxisAngle(e,t),this.quaternion.premultiply(jT),this}rotateX(e){return this.rotateOnAxis(LT,e)}rotateY(e){return this.rotateOnAxis(RT,e)}rotateZ(e){return this.rotateOnAxis(zT,e)}translateOnAxis(e,t){return AT.copy(e).applyQuaternion(this.quaternion),this.position.add(AT.multiplyScalar(t)),this}translateX(e){return this.translateOnAxis(LT,e)}translateY(e){return this.translateOnAxis(RT,e)}translateZ(e){return this.translateOnAxis(zT,e)}localToWorld(e){return this.updateWorldMatrix(!0,!1),e.applyMatrix4(this.matrixWorld)}worldToLocal(e){return this.updateWorldMatrix(!0,!1),e.applyMatrix4(MT.copy(this.matrixWorld).invert())}lookAt(e,t,n){e.isVector3?NT.copy(e):NT.set(e,t,n);let r=this.parent;this.updateWorldMatrix(!0,!1),PT.setFromMatrixPosition(this.matrixWorld),this.isCamera||this.isLight?MT.lookAt(PT,NT,this.up):MT.lookAt(NT,PT,this.up),this.quaternion.setFromRotationMatrix(MT),r&&(MT.extractRotation(r.matrixWorld),jT.setFromRotationMatrix(MT),this.quaternion.premultiply(jT.invert()))}add(e){if(arguments.length>1){for(let e=0;e<arguments.length;e++)this.add(arguments[e]);return this}return e===this?(J(`Object3D.add: object can't be added as a child of itself.`,e),this):(e&&e.isObject3D?(e.removeFromParent(),e.parent=this,this.children.push(e),e.dispatchEvent(BT),HT.child=e,this.dispatchEvent(HT),HT.child=null):J(`Object3D.add: object not an instance of THREE.Object3D.`,e),this)}remove(e){if(arguments.length>1){for(let e=0;e<arguments.length;e++)this.remove(arguments[e]);return this}let t=this.children.indexOf(e);return t!==-1&&(e.parent=null,this.children.splice(t,1),e.dispatchEvent(VT),UT.child=e,this.dispatchEvent(UT),UT.child=null),this}removeFromParent(){let e=this.parent;return e!==null&&e.remove(this),this}clear(){return this.remove(...this.children)}attach(e){return this.updateWorldMatrix(!0,!1),MT.copy(this.matrixWorld).invert(),e.parent!==null&&(e.parent.updateWorldMatrix(!0,!1),MT.multiply(e.parent.matrixWorld)),e.applyMatrix4(MT),e.removeFromParent(),e.parent=this,this.children.push(e),e.updateWorldMatrix(!1,!0),e.dispatchEvent(BT),HT.child=e,this.dispatchEvent(HT),HT.child=null,this}getObjectById(e){return this.getObjectByProperty(`id`,e)}getObjectByName(e){return this.getObjectByProperty(`name`,e)}getObjectByProperty(e,t){if(this[e]===t)return this;for(let n=0,r=this.children.length;n<r;n++){let r=this.children[n].getObjectByProperty(e,t);if(r!==void 0)return r}}getObjectsByProperty(e,t,n=[]){this[e]===t&&n.push(this);let r=this.children;for(let i=0,a=r.length;i<a;i++)r[i].getObjectsByProperty(e,t,n);return n}getWorldPosition(e){return this.updateWorldMatrix(!0,!1),e.setFromMatrixPosition(this.matrixWorld)}getWorldQuaternion(e){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose(PT,e,FT),e}getWorldScale(e){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose(PT,IT,e),e}getWorldDirection(e){this.updateWorldMatrix(!0,!1);let t=this.matrixWorld.elements;return e.set(t[8],t[9],t[10]).normalize()}raycast(){}intersectsFrustum(){}traverse(e){e(this);let t=this.children;for(let n=0,r=t.length;n<r;n++)t[n].traverse(e)}traverseVisible(e){if(this.visible===!1)return;e(this);let t=this.children;for(let n=0,r=t.length;n<r;n++)t[n].traverseVisible(e)}traverseAncestors(e){let t=this.parent;t!==null&&(e(t),t.traverseAncestors(e))}updateMatrix(){this.matrix.compose(this.position,this.quaternion,this.scale);let e=this.pivot;if(e!==null){let t=e.x,n=e.y,r=e.z,i=this.matrix.elements;i[12]+=t-i[0]*t-i[4]*n-i[8]*r,i[13]+=n-i[1]*t-i[5]*n-i[9]*r,i[14]+=r-i[2]*t-i[6]*n-i[10]*r}this.matrixWorldNeedsUpdate=!0}updateMatrixWorld(e){this.matrixAutoUpdate&&this.updateMatrix(),(this.matrixWorldNeedsUpdate||e)&&(this.matrixWorldAutoUpdate===!0&&(this.parent===null?this.matrixWorld.copy(this.matrix):this.matrixWorld.multiplyMatrices(this.parent.matrixWorld,this.matrix)),this.matrixWorldNeedsUpdate=!1,e=!0);let t=this.children;for(let n=0,r=t.length;n<r;n++)t[n].updateMatrixWorld(e)}updateWorldMatrix(e,t,n=!1){let r=this.parent;if(e===!0&&r!==null&&r.updateWorldMatrix(!0,!1),this.matrixAutoUpdate&&this.updateMatrix(),(this.matrixWorldNeedsUpdate||n)&&(this.matrixWorldAutoUpdate===!0&&(this.parent===null?this.matrixWorld.copy(this.matrix):this.matrixWorld.multiplyMatrices(this.parent.matrixWorld,this.matrix)),this.matrixWorldNeedsUpdate=!1,n=!0),t===!0){let e=this.children;for(let t=0,r=e.length;t<r;t++)e[t].updateWorldMatrix(!1,!0,n)}}toJSON(e){let t=e===void 0||typeof e==`string`,n={};t&&(e={geometries:{},materials:{},textures:{},images:{},shapes:{},skeletons:{},animations:{},nodes:{}},n.metadata={version:4.7,type:`Object`,generator:`Object3D.toJSON`});let r={};r.uuid=this.uuid,r.type=this.type,r.name=this.name,r.castShadow=this.castShadow,r.receiveShadow=this.receiveShadow,r.visible=this.visible,r.frustumCulled=this.frustumCulled,r.renderOrder=this.renderOrder,r.static=this.static,r.matrixAutoUpdate=this.matrixAutoUpdate,Object.keys(this.userData).length>0&&(r.userData=this.userData),r.layers=this.layers.mask,r.matrix=this.matrix.toArray(),r.up=this.up.toArray(),this.pivot!==null&&(r.pivot=this.pivot.toArray()),this.morphTargetDictionary!==void 0&&(r.morphTargetDictionary=Object.assign({},this.morphTargetDictionary)),this.morphTargetInfluences!==void 0&&(r.morphTargetInfluences=this.morphTargetInfluences.slice()),this.isInstancedMesh&&(r.type=`InstancedMesh`,r.count=this.count,r.instanceMatrix=this.instanceMatrix.toJSON(),this.instanceColor!==null&&(r.instanceColor=this.instanceColor.toJSON())),this.isBatchedMesh&&(r.type=`BatchedMesh`,r.perObjectFrustumCulled=this.perObjectFrustumCulled,r.sortObjects=this.sortObjects,r.drawRanges=this._drawRanges,r.reservedRanges=this._reservedRanges,r.geometryInfo=this._geometryInfo.map(e=>({...e,boundingBox:e.boundingBox?e.boundingBox.toJSON():void 0,boundingSphere:e.boundingSphere?e.boundingSphere.toJSON():void 0})),r.instanceInfo=this._instanceInfo.map(e=>({...e})),r.availableInstanceIds=this._availableInstanceIds.slice(),r.availableGeometryIds=this._availableGeometryIds.slice(),r.nextIndexStart=this._nextIndexStart,r.nextVertexStart=this._nextVertexStart,r.geometryCount=this._geometryCount,r.maxInstanceCount=this._maxInstanceCount,r.maxVertexCount=this._maxVertexCount,r.maxIndexCount=this._maxIndexCount,r.geometryInitialized=this._geometryInitialized,r.matricesTexture=this._matricesTexture.toJSON(e),r.indirectTexture=this._indirectTexture.toJSON(e),this._colorsTexture!==null&&(r.colorsTexture=this._colorsTexture.toJSON(e)),this.boundingSphere!==null&&(r.boundingSphere=this.boundingSphere.toJSON()),this.boundingBox!==null&&(r.boundingBox=this.boundingBox.toJSON()));function i(t,n){return t[n.uuid]===void 0&&(t[n.uuid]=n.toJSON(e)),n.uuid}if(this.isScene)this.background&&(this.background.isColor?r.background=this.background.toJSON():this.background.isTexture&&(r.background=this.background.toJSON(e).uuid)),this.environment&&this.environment.isTexture&&this.environment.isRenderTargetTexture!==!0&&(r.environment=this.environment.toJSON(e).uuid);else if(this.isMesh||this.isLine||this.isPoints){r.geometry=i(e.geometries,this.geometry);let t=this.geometry.parameters;if(t!==void 0&&t.shapes!==void 0){let n=t.shapes;if(Array.isArray(n))for(let t=0,r=n.length;t<r;t++){let r=n[t];i(e.shapes,r)}else i(e.shapes,n)}}if(this.isSkinnedMesh&&(r.bindMode=this.bindMode,r.bindMatrix=this.bindMatrix.toArray(),this.skeleton!==void 0&&(i(e.skeletons,this.skeleton),r.skeleton=this.skeleton.uuid)),this.material!==void 0){if(Array.isArray(this.material)){let t=[];for(let n=0,r=this.material.length;n<r;n++)t.push(i(e.materials,this.material[n]));r.material=t}else r.material=i(e.materials,this.material)}if(this.children.length>0){r.children=[];for(let t=0;t<this.children.length;t++)r.children.push(this.children[t].toJSON(e).object)}if(this.animations.length>0){r.animations=[];for(let t=0;t<this.animations.length;t++){let n=this.animations[t];r.animations.push(i(e.animations,n))}}if(t){let t=a(e.geometries),r=a(e.materials),i=a(e.textures),o=a(e.images),s=a(e.shapes),c=a(e.skeletons),l=a(e.animations),u=a(e.nodes);t.length>0&&(n.geometries=t),r.length>0&&(n.materials=r),i.length>0&&(n.textures=i),o.length>0&&(n.images=o),s.length>0&&(n.shapes=s),c.length>0&&(n.skeletons=c),l.length>0&&(n.animations=l),u.length>0&&(n.nodes=u)}return n.object=r,n;function a(e){let t=[];for(let n in e){let r=e[n];delete r.metadata,t.push(r)}return t}}clone(e){return new this.constructor().copy(this,e)}copy(e,t=!0){if(this.name=e.name,this.up.copy(e.up),this.position.copy(e.position),this.rotation.order=e.rotation.order,this.quaternion.copy(e.quaternion),this.scale.copy(e.scale),this.pivot=e.pivot===null?null:e.pivot.clone(),this.matrix.copy(e.matrix),this.matrixWorld.copy(e.matrixWorld),this.matrixAutoUpdate=e.matrixAutoUpdate,this.matrixWorldAutoUpdate=e.matrixWorldAutoUpdate,this.matrixWorldNeedsUpdate=e.matrixWorldNeedsUpdate,this.layers.mask=e.layers.mask,this.visible=e.visible,this.castShadow=e.castShadow,this.receiveShadow=e.receiveShadow,this.frustumCulled=e.frustumCulled,this.renderOrder=e.renderOrder,this.static=e.static,this.animations=e.animations.slice(),this.userData=JSON.parse(JSON.stringify(e.userData)),t===!0)for(let t=0;t<e.children.length;t++){let n=e.children[t];this.add(n.clone())}return this}dispose(){this.dispatchEvent({type:`dispose`})}};WT.DEFAULT_UP=/*@__PURE__*/ new X(0,1,0),WT.DEFAULT_MATRIX_AUTO_UPDATE=!0,WT.DEFAULT_MATRIX_WORLD_AUTO_UPDATE=!0;var GT=class extends WT{constructor(){super(),this.isGroup=!0,this.type=`Group`}},KT={type:`move`},qT=class{constructor(){this._targetRay=null,this._grip=null,this._hand=null}getHandSpace(){return this._hand===null&&(this._hand=new GT,this._hand.matrixAutoUpdate=!1,this._hand.visible=!1,this._hand.joints={},this._hand.inputState={pinching:!1}),this._hand}getTargetRaySpace(){return this._targetRay===null&&(this._targetRay=new GT,this._targetRay.matrixAutoUpdate=!1,this._targetRay.visible=!1,this._targetRay.hasLinearVelocity=!1,this._targetRay.linearVelocity=new X,this._targetRay.hasAngularVelocity=!1,this._targetRay.angularVelocity=new X),this._targetRay}getGripSpace(){return this._grip===null&&(this._grip=new GT,this._grip.matrixAutoUpdate=!1,this._grip.visible=!1,this._grip.hasLinearVelocity=!1,this._grip.linearVelocity=new X,this._grip.hasAngularVelocity=!1,this._grip.angularVelocity=new X,this._grip.eventsEnabled=!1),this._grip}dispatchEvent(e){return this._targetRay!==null&&this._targetRay.dispatchEvent(e),this._grip!==null&&this._grip.dispatchEvent(e),this._hand!==null&&this._hand.dispatchEvent(e),this}connect(e){if(e&&e.hand){let t=this._hand;if(t)for(let n of e.hand.values())this._getHandJoint(t,n)}return this.dispatchEvent({type:`connected`,data:e}),this}disconnect(e){return this.dispatchEvent({type:`disconnected`,data:e}),this._targetRay!==null&&(this._targetRay.visible=!1),this._grip!==null&&(this._grip.visible=!1),this._hand!==null&&(this._hand.visible=!1),this}update(e,t,n){let r=null,i=null,a=null,o=this._targetRay,s=this._grip,c=this._hand;if(e&&t.session.visibilityState!==`visible-blurred`){if(c&&e.hand){a=!0;for(let r of e.hand.values()){let e=t.getJointPose(r,n),i=this._getHandJoint(c,r);e!==null&&(i.matrix.fromArray(e.transform.matrix),i.matrix.decompose(i.position,i.rotation,i.scale),i.matrixWorldNeedsUpdate=!0,i.jointRadius=e.radius),i.visible=e!==null}let r=c.joints[`index-finger-tip`],i=c.joints[`thumb-tip`],o=r.position.distanceTo(i.position);c.inputState.pinching&&o>.025?(c.inputState.pinching=!1,this.dispatchEvent({type:`pinchend`,handedness:e.handedness,target:this})):!c.inputState.pinching&&o<=.015&&(c.inputState.pinching=!0,this.dispatchEvent({type:`pinchstart`,handedness:e.handedness,target:this}))}else s!==null&&e.gripSpace&&(i=t.getPose(e.gripSpace,n),i!==null&&(s.matrix.fromArray(i.transform.matrix),s.matrix.decompose(s.position,s.rotation,s.scale),s.matrixWorldNeedsUpdate=!0,i.linearVelocity?(s.hasLinearVelocity=!0,s.linearVelocity.copy(i.linearVelocity)):s.hasLinearVelocity=!1,i.angularVelocity?(s.hasAngularVelocity=!0,s.angularVelocity.copy(i.angularVelocity)):s.hasAngularVelocity=!1,s.eventsEnabled&&s.dispatchEvent({type:`gripUpdated`,data:e,target:this})));o!==null&&(r=t.getPose(e.targetRaySpace,n),r===null&&i!==null&&(r=i),r!==null&&(o.matrix.fromArray(r.transform.matrix),o.matrix.decompose(o.position,o.rotation,o.scale),o.matrixWorldNeedsUpdate=!0,r.linearVelocity?(o.hasLinearVelocity=!0,o.linearVelocity.copy(r.linearVelocity)):o.hasLinearVelocity=!1,r.angularVelocity?(o.hasAngularVelocity=!0,o.angularVelocity.copy(r.angularVelocity)):o.hasAngularVelocity=!1,this.dispatchEvent(KT)))}return o!==null&&(o.visible=r!==null),s!==null&&(s.visible=i!==null),c!==null&&(c.visible=a!==null),this}_getHandJoint(e,t){if(e.joints[t.jointName]===void 0){let n=new GT;n.matrixAutoUpdate=!1,n.visible=!1,e.joints[t.jointName]=n,e.add(n)}return e.joints[t.jointName]}},JT={aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,rebeccapurple:6697881,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074},YT={h:0,s:0,l:0},XT={h:0,s:0,l:0};function ZT(e,t,n){return n<0&&(n+=1),n>1&&--n,n<1/6?e+(t-e)*6*n:n<1/2?t:n<2/3?e+(t-e)*6*(2/3-n):e}var QT=class{constructor(e,t,n){return this.isColor=!0,this.r=1,this.g=1,this.b=1,this.set(e,t,n)}set(e,t,n){if(t===void 0&&n===void 0){let t=e;t&&t.isColor?this.copy(t):typeof t==`number`?this.setHex(t):typeof t==`string`&&this.setStyle(t)}else this.setRGB(e,t,n);return this}setScalar(e){return this.r=e,this.g=e,this.b=e,this}setHex(e,t=bw){return e=Math.floor(e),this.r=(e>>16&255)/255,this.g=(e>>8&255)/255,this.b=(e&255)/255,tT.colorSpaceToWorking(this,t),this}setRGB(e,t,n,r=tT.workingColorSpace){return this.r=e,this.g=t,this.b=n,tT.colorSpaceToWorking(this,r),this}setHSL(e,t,n,r=tT.workingColorSpace){if(e=Ww(e,1),t=Uw(t,0,1),n=Uw(n,0,1),t===0)this.r=this.g=this.b=n;else{let r=n<=.5?n*(1+t):n+t-n*t,i=2*n-r;this.r=ZT(i,r,e+1/3),this.g=ZT(i,r,e),this.b=ZT(i,r,e-1/3)}return tT.colorSpaceToWorking(this,r),this}setStyle(e,t=bw){function n(t){t!==void 0&&parseFloat(t)<1&&q(`Color: Alpha component of `+e+` will be ignored.`)}let r;if(r=/^(\w+)\(([^\)]*)\)/.exec(e)){let i,a=r[1],o=r[2];switch(a){case`rgb`:case`rgba`:if(i=/^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return n(i[4]),this.setRGB(Math.min(255,parseInt(i[1],10))/255,Math.min(255,parseInt(i[2],10))/255,Math.min(255,parseInt(i[3],10))/255,t);if(i=/^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return n(i[4]),this.setRGB(Math.min(100,parseInt(i[1],10))/100,Math.min(100,parseInt(i[2],10))/100,Math.min(100,parseInt(i[3],10))/100,t);break;case`hsl`:case`hsla`:if(i=/^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return n(i[4]),this.setHSL(parseFloat(i[1])/360,parseFloat(i[2])/100,parseFloat(i[3])/100,t);break;default:q(`Color: Unknown color model `+e)}}else if(r=/^\#([A-Fa-f\d]+)$/.exec(e)){let n=r[1],i=n.length;if(i===3)return this.setRGB(parseInt(n.charAt(0),16)/15,parseInt(n.charAt(1),16)/15,parseInt(n.charAt(2),16)/15,t);if(i===6)return this.setHex(parseInt(n,16),t);q(`Color: Invalid hex color `+e)}else if(e&&e.length>0)return this.setColorName(e,t);return this}setColorName(e,t=bw){let n=JT[e.toLowerCase()];return n===void 0?q(`Color: Unknown color `+e):this.setHex(n,t),this}clone(){return new this.constructor(this.r,this.g,this.b)}copy(e){return this.r=e.r,this.g=e.g,this.b=e.b,this}copySRGBToLinear(e){return this.r=nT(e.r),this.g=nT(e.g),this.b=nT(e.b),this}copyLinearToSRGB(e){return this.r=rT(e.r),this.g=rT(e.g),this.b=rT(e.b),this}convertSRGBToLinear(){return this.copySRGBToLinear(this),this}convertLinearToSRGB(){return this.copyLinearToSRGB(this),this}getHex(e=bw){return tT.workingToColorSpace($T.copy(this),e),Math.round(Uw($T.r*255,0,255))*65536+Math.round(Uw($T.g*255,0,255))*256+Math.round(Uw($T.b*255,0,255))}getHexString(e=bw){return(`000000`+this.getHex(e).toString(16)).slice(-6)}getHSL(e,t=tT.workingColorSpace){tT.workingToColorSpace($T.copy(this),t);let n=$T.r,r=$T.g,i=$T.b,a=Math.max(n,r,i),o=Math.min(n,r,i),s,c,l=(o+a)/2;if(o===a)s=0,c=0;else{let e=a-o;switch(c=l<=.5?e/(a+o):e/(2-a-o),a){case n:s=(r-i)/e+(r<i?6:0);break;case r:s=(i-n)/e+2;break;case i:s=(n-r)/e+4}s/=6}return e.h=s,e.s=c,e.l=l,e}getRGB(e,t=tT.workingColorSpace){return tT.workingToColorSpace($T.copy(this),t),e.r=$T.r,e.g=$T.g,e.b=$T.b,e}getStyle(e=bw){tT.workingToColorSpace($T.copy(this),e);let t=$T.r,n=$T.g,r=$T.b;return e===`srgb`?`rgb(${Math.round(t*255)},${Math.round(n*255)},${Math.round(r*255)})`:`color(${e} ${t.toFixed(3)} ${n.toFixed(3)} ${r.toFixed(3)})`}offsetHSL(e,t,n){return this.getHSL(YT),this.setHSL(YT.h+e,YT.s+t,YT.l+n)}add(e){return this.r+=e.r,this.g+=e.g,this.b+=e.b,this}addColors(e,t){return this.r=e.r+t.r,this.g=e.g+t.g,this.b=e.b+t.b,this}addScalar(e){return this.r+=e,this.g+=e,this.b+=e,this}sub(e){return this.r=Math.max(0,this.r-e.r),this.g=Math.max(0,this.g-e.g),this.b=Math.max(0,this.b-e.b),this}multiply(e){return this.r*=e.r,this.g*=e.g,this.b*=e.b,this}multiplyScalar(e){return this.r*=e,this.g*=e,this.b*=e,this}lerp(e,t){return this.r+=(e.r-this.r)*t,this.g+=(e.g-this.g)*t,this.b+=(e.b-this.b)*t,this}lerpColors(e,t,n){return this.r=e.r+(t.r-e.r)*n,this.g=e.g+(t.g-e.g)*n,this.b=e.b+(t.b-e.b)*n,this}lerpHSL(e,t){this.getHSL(YT),e.getHSL(XT);let n=Gw(YT.h,XT.h,t),r=Gw(YT.s,XT.s,t),i=Gw(YT.l,XT.l,t);return this.setHSL(n,r,i),this}setFromVector3(e){return this.r=e.x,this.g=e.y,this.b=e.z,this}applyMatrix3(e){let t=this.r,n=this.g,r=this.b,i=e.elements;return this.r=i[0]*t+i[3]*n+i[6]*r,this.g=i[1]*t+i[4]*n+i[7]*r,this.b=i[2]*t+i[5]*n+i[8]*r,this}equals(e){return e.r===this.r&&e.g===this.g&&e.b===this.b}fromArray(e,t=0){return this.r=e[t],this.g=e[t+1],this.b=e[t+2],this}toArray(e=[],t=0){return e[t]=this.r,e[t+1]=this.g,e[t+2]=this.b,e}fromBufferAttribute(e,t){return this.r=e.getX(t),this.g=e.getY(t),this.b=e.getZ(t),this}toJSON(){return this.getHex()}*[Symbol.iterator](){yield this.r,yield this.g,yield this.b}},$T=/*@__PURE__*/ new QT;QT.NAMES=JT;var eE=class extends WT{constructor(){super(),this.isScene=!0,this.type=`Scene`,this.background=null,this.environment=null,this.fog=null,this.backgroundBlurriness=0,this.backgroundIntensity=1,this.backgroundRotation=new DT,this.environmentIntensity=1,this.environmentRotation=new DT,this.overrideMaterial=null,typeof __THREE_DEVTOOLS__<`u`&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent(`observe`,{detail:this}))}copy(e,t){return super.copy(e,t),e.background!==null&&(this.background=e.background.clone()),e.environment!==null&&(this.environment=e.environment.clone()),e.fog!==null&&(this.fog=e.fog.clone()),this.backgroundBlurriness=e.backgroundBlurriness,this.backgroundIntensity=e.backgroundIntensity,this.backgroundRotation.copy(e.backgroundRotation),this.environmentIntensity=e.environmentIntensity,this.environmentRotation.copy(e.environmentRotation),e.overrideMaterial!==null&&(this.overrideMaterial=e.overrideMaterial.clone()),this.matrixAutoUpdate=e.matrixAutoUpdate,this}toJSON(e){let t=super.toJSON(e);return this.fog!==null&&(t.object.fog=this.fog.toJSON()),t.object.backgroundBlurriness=this.backgroundBlurriness,t.object.backgroundIntensity=this.backgroundIntensity,t.object.backgroundRotation=this.backgroundRotation.toArray(),t.object.environmentIntensity=this.environmentIntensity,t.object.environmentRotation=this.environmentRotation.toArray(),t}},tE=/*@__PURE__*/ new X,nE=/*@__PURE__*/ new X,rE=/*@__PURE__*/ new X,iE=/*@__PURE__*/ new X,aE=/*@__PURE__*/ new X,oE=/*@__PURE__*/ new X,sE=/*@__PURE__*/ new X,cE=/*@__PURE__*/ new X,lE=/*@__PURE__*/ new X,uE=/*@__PURE__*/ new X,dE=/*@__PURE__*/ new fT,fE=/*@__PURE__*/ new fT,pE=/*@__PURE__*/ new fT,mE=class e{constructor(e=new X,t=new X,n=new X){this.a=e,this.b=t,this.c=n}static getNormal(e,t,n,r){r.subVectors(n,t),tE.subVectors(e,t),r.cross(tE);let i=r.lengthSq();return i>0?r.multiplyScalar(1/Math.sqrt(i)):r.set(0,0,0)}static getBarycoord(e,t,n,r,i){tE.subVectors(r,t),nE.subVectors(n,t),rE.subVectors(e,t);let a=tE.dot(tE),o=tE.dot(nE),s=tE.dot(rE),c=nE.dot(nE),l=nE.dot(rE),u=a*c-o*o;if(u===0)return i.set(0,0,0),null;let d=1/u,f=(c*s-o*l)*d,p=(a*l-o*s)*d;return i.set(1-f-p,p,f)}static containsPoint(e,t,n,r){return this.getBarycoord(e,t,n,r,iE)!==null&&iE.x>=0&&iE.y>=0&&iE.x+iE.y<=1}static getInterpolation(e,t,n,r,i,a,o,s){return this.getBarycoord(e,t,n,r,iE)===null?(s.x=0,s.y=0,`z`in s&&(s.z=0),`w`in s&&(s.w=0),null):(s.setScalar(0),s.addScaledVector(i,iE.x),s.addScaledVector(a,iE.y),s.addScaledVector(o,iE.z),s)}static getInterpolatedAttribute(e,t,n,r,i,a){return dE.setScalar(0),fE.setScalar(0),pE.setScalar(0),dE.fromBufferAttribute(e,t),fE.fromBufferAttribute(e,n),pE.fromBufferAttribute(e,r),a.setScalar(0),a.addScaledVector(dE,i.x),a.addScaledVector(fE,i.y),a.addScaledVector(pE,i.z),a}static isFrontFacing(e,t,n,r){return tE.subVectors(n,t),nE.subVectors(e,t),tE.cross(nE).dot(r)<0}set(e,t,n){return this.a.copy(e),this.b.copy(t),this.c.copy(n),this}setFromPointsAndIndices(e,t,n,r){return this.a.copy(e[t]),this.b.copy(e[n]),this.c.copy(e[r]),this}setFromAttributeAndIndices(e,t,n,r){return this.a.fromBufferAttribute(e,t),this.b.fromBufferAttribute(e,n),this.c.fromBufferAttribute(e,r),this}clone(){return new this.constructor().copy(this)}copy(e){return this.a.copy(e.a),this.b.copy(e.b),this.c.copy(e.c),this}getArea(){return tE.subVectors(this.c,this.b),nE.subVectors(this.a,this.b),tE.cross(nE).length()*.5}getMidpoint(e){return e.addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)}getNormal(t){return e.getNormal(this.a,this.b,this.c,t)}getPlane(e){return e.setFromCoplanarPoints(this.a,this.b,this.c)}getBarycoord(t,n){return e.getBarycoord(t,this.a,this.b,this.c,n)}getInterpolation(t,n,r,i,a){return e.getInterpolation(t,this.a,this.b,this.c,n,r,i,a)}containsPoint(t){return e.containsPoint(t,this.a,this.b,this.c)}isFrontFacing(t){return e.isFrontFacing(this.a,this.b,this.c,t)}intersectsBox(e){return e.intersectsTriangle(this)}closestPointToPoint(e,t){let n=this.a,r=this.b,i=this.c,a,o;aE.subVectors(r,n),oE.subVectors(i,n),cE.subVectors(e,n);let s=aE.dot(cE),c=oE.dot(cE);if(s<=0&&c<=0)return t.copy(n);lE.subVectors(e,r);let l=aE.dot(lE),u=oE.dot(lE);if(l>=0&&u<=l)return t.copy(r);let d=s*u-l*c;if(d<=0&&s>=0&&l<=0)return a=s/(s-l),t.copy(n).addScaledVector(aE,a);uE.subVectors(e,i);let f=aE.dot(uE),p=oE.dot(uE);if(p>=0&&f<=p)return t.copy(i);let m=f*c-s*p;if(m<=0&&c>=0&&p<=0)return o=c/(c-p),t.copy(n).addScaledVector(oE,o);let h=l*p-f*u;if(h<=0&&u-l>=0&&f-p>=0)return sE.subVectors(i,r),o=(u-l)/(u-l+(f-p)),t.copy(r).addScaledVector(sE,o);let g=1/(h+m+d);return a=m*g,o=d*g,t.copy(n).addScaledVector(aE,a).addScaledVector(oE,o)}equals(e){return e.a.equals(this.a)&&e.b.equals(this.b)&&e.c.equals(this.c)}},hE=class{constructor(e=new X(1/0,1/0,1/0),t=new X(-1/0,-1/0,-1/0)){this.isBox3=!0,this.min=e,this.max=t}set(e,t){return this.min.copy(e),this.max.copy(t),this}setFromArray(e){this.makeEmpty();for(let t=0,n=e.length;t<n;t+=3)this.expandByPoint(_E.fromArray(e,t));return this}setFromBufferAttribute(e){this.makeEmpty();for(let t=0,n=e.count;t<n;t++)this.expandByPoint(_E.fromBufferAttribute(e,t));return this}setFromPoints(e){this.makeEmpty();for(let t=0,n=e.length;t<n;t++)this.expandByPoint(e[t]);return this}setFromCenterAndSize(e,t){let n=_E.copy(t).multiplyScalar(.5);return this.min.copy(e).sub(n),this.max.copy(e).add(n),this}setFromObject(e,t=!1){return this.makeEmpty(),this.expandByObject(e,t)}clone(){return new this.constructor().copy(this)}copy(e){return this.min.copy(e.min),this.max.copy(e.max),this}makeEmpty(){return this.min.x=this.min.y=this.min.z=1/0,this.max.x=this.max.y=this.max.z=-1/0,this}isEmpty(){return this.max.x<this.min.x||this.max.y<this.min.y||this.max.z<this.min.z}getCenter(e){return this.isEmpty()?e.set(0,0,0):e.addVectors(this.min,this.max).multiplyScalar(.5)}getSize(e){return this.isEmpty()?e.set(0,0,0):e.subVectors(this.max,this.min)}expandByPoint(e){return this.min.min(e),this.max.max(e),this}expandByVector(e){return this.min.sub(e),this.max.add(e),this}expandByScalar(e){return this.min.addScalar(-e),this.max.addScalar(e),this}expandByObject(e,t=!1){e.updateWorldMatrix(!1,!1);let n=e.geometry;if(n!==void 0){let r=n.getAttribute(`position`);if(t===!0&&r!==void 0&&e.isInstancedMesh!==!0)for(let t=0,n=r.count;t<n;t++)e.isMesh===!0?e.getVertexPosition(t,_E):_E.fromBufferAttribute(r,t),_E.applyMatrix4(e.matrixWorld),this.expandByPoint(_E);else e.boundingBox===void 0?(n.boundingBox===null&&n.computeBoundingBox(),vE.copy(n.boundingBox)):(e.boundingBox===null&&e.computeBoundingBox(),vE.copy(e.boundingBox)),vE.applyMatrix4(e.matrixWorld),this.union(vE)}let r=e.children;for(let e=0,n=r.length;e<n;e++)this.expandByObject(r[e],t);return this}containsPoint(e){return e.x>=this.min.x&&e.x<=this.max.x&&e.y>=this.min.y&&e.y<=this.max.y&&e.z>=this.min.z&&e.z<=this.max.z}containsBox(e){return this.min.x<=e.min.x&&e.max.x<=this.max.x&&this.min.y<=e.min.y&&e.max.y<=this.max.y&&this.min.z<=e.min.z&&e.max.z<=this.max.z}getParameter(e,t){return t.set((e.x-this.min.x)/(this.max.x-this.min.x),(e.y-this.min.y)/(this.max.y-this.min.y),(e.z-this.min.z)/(this.max.z-this.min.z))}intersectsBox(e){return e.max.x>=this.min.x&&e.min.x<=this.max.x&&e.max.y>=this.min.y&&e.min.y<=this.max.y&&e.max.z>=this.min.z&&e.min.z<=this.max.z}intersectsSphere(e){return this.clampPoint(e.center,_E),_E.distanceToSquared(e.center)<=e.radius*e.radius}intersectsPlane(e){let t,n;return e.normal.x>0?(t=e.normal.x*this.min.x,n=e.normal.x*this.max.x):(t=e.normal.x*this.max.x,n=e.normal.x*this.min.x),e.normal.y>0?(t+=e.normal.y*this.min.y,n+=e.normal.y*this.max.y):(t+=e.normal.y*this.max.y,n+=e.normal.y*this.min.y),e.normal.z>0?(t+=e.normal.z*this.min.z,n+=e.normal.z*this.max.z):(t+=e.normal.z*this.max.z,n+=e.normal.z*this.min.z),t<=-e.constant&&n>=-e.constant}intersectsTriangle(e){if(this.isEmpty())return!1;this.getCenter(TE),EE.subVectors(this.max,TE),yE.subVectors(e.a,TE),bE.subVectors(e.b,TE),xE.subVectors(e.c,TE),SE.subVectors(bE,yE),CE.subVectors(xE,bE),wE.subVectors(yE,xE);let t=[0,-SE.z,SE.y,0,-CE.z,CE.y,0,-wE.z,wE.y,SE.z,0,-SE.x,CE.z,0,-CE.x,wE.z,0,-wE.x,-SE.y,SE.x,0,-CE.y,CE.x,0,-wE.y,wE.x,0];return!kE(t,yE,bE,xE,EE)||(t=[1,0,0,0,1,0,0,0,1],!kE(t,yE,bE,xE,EE))?!1:(DE.crossVectors(SE,CE),t=[DE.x,DE.y,DE.z],kE(t,yE,bE,xE,EE))}clampPoint(e,t){return t.copy(e).clamp(this.min,this.max)}distanceToPoint(e){return this.clampPoint(e,_E).distanceTo(e)}getBoundingSphere(e){return this.isEmpty()?e.makeEmpty():(this.getCenter(e.center),e.radius=this.getSize(_E).length()*.5),e}intersect(e){return this.min.max(e.min),this.max.min(e.max),this.isEmpty()&&this.makeEmpty(),this}union(e){return this.min.min(e.min),this.max.max(e.max),this}applyMatrix4(e){return this.isEmpty()?this:(gE[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(e),gE[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(e),gE[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(e),gE[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(e),gE[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(e),gE[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(e),gE[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(e),gE[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(e),this.setFromPoints(gE),this)}translate(e){return this.min.add(e),this.max.add(e),this}equals(e){return e.min.equals(this.min)&&e.max.equals(this.max)}toJSON(){return{min:this.min.toArray(),max:this.max.toArray()}}fromJSON(e){return this.min.fromArray(e.min),this.max.fromArray(e.max),this}},gE=[/*@__PURE__*/ new X,/*@__PURE__*/ new X,/*@__PURE__*/ new X,/*@__PURE__*/ new X,/*@__PURE__*/ new X,/*@__PURE__*/ new X,/*@__PURE__*/ new X,/*@__PURE__*/ new X],_E=/*@__PURE__*/ new X,vE=/*@__PURE__*/ new hE,yE=/*@__PURE__*/ new X,bE=/*@__PURE__*/ new X,xE=/*@__PURE__*/ new X,SE=/*@__PURE__*/ new X,CE=/*@__PURE__*/ new X,wE=/*@__PURE__*/ new X,TE=/*@__PURE__*/ new X,EE=/*@__PURE__*/ new X,DE=/*@__PURE__*/ new X,OE=/*@__PURE__*/ new X;function kE(e,t,n,r,i){for(let a=0,o=e.length-3;a<=o;a+=3){OE.fromArray(e,a);let o=i.x*Math.abs(OE.x)+i.y*Math.abs(OE.y)+i.z*Math.abs(OE.z),s=t.dot(OE),c=n.dot(OE),l=r.dot(OE);if(Math.max(-Math.max(s,c,l),Math.min(s,c,l))>o)return!1}return!0}var AE=/*@__PURE__*/ new X,jE=/*@__PURE__*/ new Y,ME=0,NE=class extends Rw{constructor(e,t,n=!1){if(super(),Array.isArray(e))throw TypeError(`THREE.BufferAttribute: array should be a Typed Array.`);this.isBufferAttribute=!0,Object.defineProperty(this,"id",{value:ME++}),this.name=``,this.array=e,this.itemSize=t,this.count=e===void 0?0:e.length/t,this.normalized=n,this.usage=Tw,this.updateRanges=[],this.gpuType=pC,this.version=0}onUploadCallback(){}set needsUpdate(e){e===!0&&this.version++}setUsage(e){return this.usage=e,this}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}copy(e){return this.name=e.name,this.array=new e.array.constructor(e.array),this.itemSize=e.itemSize,this.count=e.count,this.normalized=e.normalized,this.usage=e.usage,this.gpuType=e.gpuType,this}copyAt(e,t,n){e*=this.itemSize,n*=t.itemSize;for(let r=0,i=this.itemSize;r<i;r++)this.array[e+r]=t.array[n+r];return this}copyArray(e){return this.array.set(e),this}applyMatrix3(e){if(this.itemSize===2)for(let t=0,n=this.count;t<n;t++)jE.fromBufferAttribute(this,t),jE.applyMatrix3(e),this.setXY(t,jE.x,jE.y);else if(this.itemSize===3)for(let t=0,n=this.count;t<n;t++)AE.fromBufferAttribute(this,t),AE.applyMatrix3(e),this.setXYZ(t,AE.x,AE.y,AE.z);return this}applyMatrix4(e){for(let t=0,n=this.count;t<n;t++)AE.fromBufferAttribute(this,t),AE.applyMatrix4(e),this.setXYZ(t,AE.x,AE.y,AE.z);return this}applyNormalMatrix(e){for(let t=0,n=this.count;t<n;t++)AE.fromBufferAttribute(this,t),AE.applyNormalMatrix(e),this.setXYZ(t,AE.x,AE.y,AE.z);return this}transformDirection(e){for(let t=0,n=this.count;t<n;t++)AE.fromBufferAttribute(this,t),AE.transformDirection(e),this.setXYZ(t,AE.x,AE.y,AE.z);return this}set(e,t=0){return this.array.set(e,t),this}getComponent(e,t){let n=this.array[e*this.itemSize+t];return this.normalized&&(n=Kw(n,this.array)),n}setComponent(e,t,n){return this.normalized&&(n=qw(n,this.array)),this.array[e*this.itemSize+t]=n,this}getX(e){let t=this.array[e*this.itemSize];return this.normalized&&(t=Kw(t,this.array)),t}setX(e,t){return this.normalized&&(t=qw(t,this.array)),this.array[e*this.itemSize]=t,this}getY(e){let t=this.array[e*this.itemSize+1];return this.normalized&&(t=Kw(t,this.array)),t}setY(e,t){return this.normalized&&(t=qw(t,this.array)),this.array[e*this.itemSize+1]=t,this}getZ(e){let t=this.array[e*this.itemSize+2];return this.normalized&&(t=Kw(t,this.array)),t}setZ(e,t){return this.normalized&&(t=qw(t,this.array)),this.array[e*this.itemSize+2]=t,this}getW(e){let t=this.array[e*this.itemSize+3];return this.normalized&&(t=Kw(t,this.array)),t}setW(e,t){return this.normalized&&(t=qw(t,this.array)),this.array[e*this.itemSize+3]=t,this}setXY(e,t,n){return e*=this.itemSize,this.normalized&&(t=qw(t,this.array),n=qw(n,this.array)),this.array[e+0]=t,this.array[e+1]=n,this}setXYZ(e,t,n,r){return e*=this.itemSize,this.normalized&&(t=qw(t,this.array),n=qw(n,this.array),r=qw(r,this.array)),this.array[e+0]=t,this.array[e+1]=n,this.array[e+2]=r,this}setXYZW(e,t,n,r,i){return e*=this.itemSize,this.normalized&&(t=qw(t,this.array),n=qw(n,this.array),r=qw(r,this.array),i=qw(i,this.array)),this.array[e+0]=t,this.array[e+1]=n,this.array[e+2]=r,this.array[e+3]=i,this}onUpload(e){return this.onUploadCallback=e,this}clone(){return new this.constructor(this.array,this.itemSize).copy(this)}toJSON(){let e={itemSize:this.itemSize,type:this.array.constructor.name,array:Array.from(this.array),normalized:this.normalized};return e.name=this.name,e.usage=this.usage,e.gpuType=this.gpuType,e}dispose(){this.dispatchEvent({type:`dispose`})}},PE=class extends NE{constructor(e,t,n){super(new Uint16Array(e),t,n)}},FE=class extends NE{constructor(e,t,n){super(new Uint32Array(e),t,n)}},IE=class extends NE{constructor(e,t,n){super(new Float32Array(e),t,n)}},LE=/*@__PURE__*/ new hE,RE=/*@__PURE__*/ new X,zE=/*@__PURE__*/ new X,BE=class{constructor(e=new X,t=-1){this.isSphere=!0,this.center=e,this.radius=t}set(e,t){return this.center.copy(e),this.radius=t,this}setFromPoints(e,t){let n=this.center;t===void 0?LE.setFromPoints(e).getCenter(n):n.copy(t);let r=0;for(let t=0,i=e.length;t<i;t++)r=Math.max(r,n.distanceToSquared(e[t]));return this.radius=Math.sqrt(r),this}copy(e){return this.center.copy(e.center),this.radius=e.radius,this}isEmpty(){return this.radius<0}makeEmpty(){return this.center.set(0,0,0),this.radius=-1,this}containsPoint(e){return e.distanceToSquared(this.center)<=this.radius*this.radius}distanceToPoint(e){return e.distanceTo(this.center)-this.radius}intersectsSphere(e){let t=this.radius+e.radius;return e.center.distanceToSquared(this.center)<=t*t}intersectsBox(e){return e.intersectsSphere(this)}intersectsPlane(e){return Math.abs(e.distanceToPoint(this.center))<=this.radius}clampPoint(e,t){let n=this.center.distanceToSquared(e);return t.copy(e),n>this.radius*this.radius&&(t.sub(this.center).normalize(),t.multiplyScalar(this.radius).add(this.center)),t}getBoundingBox(e){return this.isEmpty()?(e.makeEmpty(),e):(e.set(this.center,this.center),e.expandByScalar(this.radius),e)}applyMatrix4(e){return this.center.applyMatrix4(e),this.radius*=e.getMaxScaleOnAxis(),this}translate(e){return this.center.add(e),this}expandByPoint(e){if(this.isEmpty())return this.center.copy(e),this.radius=0,this;RE.subVectors(e,this.center);let t=RE.lengthSq();if(t>this.radius*this.radius){let e=Math.sqrt(t),n=(e-this.radius)*.5;this.center.addScaledVector(RE,n/e),this.radius+=n}return this}union(e){return e.isEmpty()?this:this.isEmpty()?(this.copy(e),this):(this.center.equals(e.center)===!0?this.radius=Math.max(this.radius,e.radius):(zE.subVectors(e.center,this.center).setLength(e.radius),this.expandByPoint(RE.copy(e.center).add(zE)),this.expandByPoint(RE.copy(e.center).sub(zE))),this)}equals(e){return e.center.equals(this.center)&&e.radius===this.radius}clone(){return new this.constructor().copy(this)}toJSON(){return{radius:this.radius,center:this.center.toArray()}}fromJSON(e){return this.radius=e.radius,this.center.fromArray(e.center),this}},VE=0,HE=/*@__PURE__*/ new _T,UE=/*@__PURE__*/ new WT,WE=/*@__PURE__*/ new X,GE=/*@__PURE__*/ new hE,KE=/*@__PURE__*/ new hE,qE=/*@__PURE__*/ new X,JE=class e extends Rw{constructor(){super(),this.isBufferGeometry=!0,Object.defineProperty(this,"id",{value:VE++}),this.uuid=Hw(),this.name=``,this.type=`BufferGeometry`,this.index=null,this.indirect=null,this.indirectOffset=0,this.attributes={},this.morphAttributes={},this.morphTargetsRelative=!1,this.groups=[],this.boundingBox=null,this.boundingSphere=null,this.drawRange={start:0,count:1/0},this.userData={},this._transformed=!1}getIndex(){return this.index}setIndex(e){return this.index=Array.isArray(e)?new(Ow(e)?FE:PE)(e,1):e,this}setIndirect(e,t=0){return this.indirect=e,this.indirectOffset=t,this}getIndirect(){return this.indirect}getAttribute(e){return this.attributes[e]}setAttribute(e,t){return this.attributes[e]=t,this}deleteAttribute(e){return delete this.attributes[e],this}hasAttribute(e){return this.attributes[e]!==void 0}addGroup(e,t,n=0){this.groups.push({start:e,count:t,materialIndex:n})}clearGroups(){this.groups=[]}setDrawRange(e,t){this.drawRange.start=e,this.drawRange.count=t}applyMatrix4(e){let t=this.attributes.position;t!==void 0&&(t.applyMatrix4(e),t.needsUpdate=!0);let n=this.attributes.normal;if(n!==void 0){let t=new Z().getNormalMatrix(e);n.applyNormalMatrix(t),n.needsUpdate=!0}let r=this.attributes.tangent;return r!==void 0&&(r.transformDirection(e),r.needsUpdate=!0),this.boundingBox!==null&&this.computeBoundingBox(),this.boundingSphere!==null&&this.computeBoundingSphere(),this._transformed=!0,this}applyQuaternion(e){return HE.makeRotationFromQuaternion(e),this.applyMatrix4(HE),this}rotateX(e){return HE.makeRotationX(e),this.applyMatrix4(HE),this}rotateY(e){return HE.makeRotationY(e),this.applyMatrix4(HE),this}rotateZ(e){return HE.makeRotationZ(e),this.applyMatrix4(HE),this}translate(e,t,n){return HE.makeTranslation(e,t,n),this.applyMatrix4(HE),this}scale(e,t,n){return HE.makeScale(e,t,n),this.applyMatrix4(HE),this}lookAt(e){return UE.lookAt(e),UE.updateMatrix(),this.applyMatrix4(UE.matrix),this}center(){return this.computeBoundingBox(),this.boundingBox.getCenter(WE).negate(),this.translate(WE.x,WE.y,WE.z),this}setFromPoints(e){let t=this.getAttribute(`position`);if(t===void 0){let t=[];for(let n=0,r=e.length;n<r;n++){let r=e[n];t.push(r.x,r.y,r.z||0)}this.setAttribute(`position`,new IE(t,3))}else{let n=Math.min(e.length,t.count);for(let r=0;r<n;r++){let n=e[r];t.setXYZ(r,n.x,n.y,n.z||0)}e.length>t.count&&q(`BufferGeometry: Buffer size too small for points data. Use .dispose() and create a new geometry.`),t.needsUpdate=!0}return this}computeBoundingBox(){this.boundingBox===null&&(this.boundingBox=new hE);let e=this.attributes.position,t=this.morphAttributes.position;if(e&&e.isGLBufferAttribute){J(`BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.`,this),this.boundingBox.set(new X(-1/0,-1/0,-1/0),new X(1/0,1/0,1/0));return}if(e!==void 0){if(this.boundingBox.setFromBufferAttribute(e),t)for(let e=0,n=t.length;e<n;e++){let n=t[e];GE.setFromBufferAttribute(n),this.morphTargetsRelative?(qE.addVectors(this.boundingBox.min,GE.min),this.boundingBox.expandByPoint(qE),qE.addVectors(this.boundingBox.max,GE.max),this.boundingBox.expandByPoint(qE)):(this.boundingBox.expandByPoint(GE.min),this.boundingBox.expandByPoint(GE.max))}}else this.boundingBox.makeEmpty();(isNaN(this.boundingBox.min.x)||isNaN(this.boundingBox.min.y)||isNaN(this.boundingBox.min.z))&&J(`BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.`,this)}computeBoundingSphere(){this.boundingSphere===null&&(this.boundingSphere=new BE);let e=this.attributes.position,t=this.morphAttributes.position;if(e&&e.isGLBufferAttribute){J(`BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere.`,this),this.boundingSphere.set(new X,1/0);return}if(e){let n=this.boundingSphere.center;if(GE.setFromBufferAttribute(e),t)for(let e=0,n=t.length;e<n;e++){let n=t[e];KE.setFromBufferAttribute(n),this.morphTargetsRelative?(qE.addVectors(GE.min,KE.min),GE.expandByPoint(qE),qE.addVectors(GE.max,KE.max),GE.expandByPoint(qE)):(GE.expandByPoint(KE.min),GE.expandByPoint(KE.max))}GE.getCenter(n);let r=0;for(let t=0,i=e.count;t<i;t++)qE.fromBufferAttribute(e,t),r=Math.max(r,n.distanceToSquared(qE));if(t)for(let i=0,a=t.length;i<a;i++){let a=t[i],o=this.morphTargetsRelative;for(let t=0,i=a.count;t<i;t++)qE.fromBufferAttribute(a,t),o&&(WE.fromBufferAttribute(e,t),qE.add(WE)),r=Math.max(r,n.distanceToSquared(qE))}this.boundingSphere.radius=Math.sqrt(r),isNaN(this.boundingSphere.radius)&&J(`BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.`,this)}}computeTangents(){let e=this.index,t=this.attributes;if(e===null||t.position===void 0||t.normal===void 0||t.uv===void 0){J(`BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)`);return}let n=t.position,r=t.normal,i=t.uv,a=this.getAttribute(`tangent`);(a===void 0||a.count!==n.count)&&(a=new NE(new Float32Array(4*n.count),4),this.setAttribute(`tangent`,a));let o=[],s=[];for(let e=0;e<n.count;e++)o[e]=new X,s[e]=new X;let c=new X,l=new X,u=new X,d=new Y,f=new Y,p=new Y,m=new X,h=new X;function g(e,t,r){c.fromBufferAttribute(n,e),l.fromBufferAttribute(n,t),u.fromBufferAttribute(n,r),d.fromBufferAttribute(i,e),f.fromBufferAttribute(i,t),p.fromBufferAttribute(i,r),l.sub(c),u.sub(c),f.sub(d),p.sub(d);let a=1/(f.x*p.y-p.x*f.y);isFinite(a)&&(m.copy(l).multiplyScalar(p.y).addScaledVector(u,-f.y).multiplyScalar(a),h.copy(u).multiplyScalar(f.x).addScaledVector(l,-p.x).multiplyScalar(a),o[e].add(m),o[t].add(m),o[r].add(m),s[e].add(h),s[t].add(h),s[r].add(h))}let _=this.groups;_.length===0&&(_=[{start:0,count:e.count}]);for(let t=0,n=_.length;t<n;++t){let n=_[t],r=n.start,i=n.count;for(let t=r,n=r+i;t<n;t+=3)g(e.getX(t+0),e.getX(t+1),e.getX(t+2))}let v=new X,y=new X,b=new X,x=new X;function S(e){b.fromBufferAttribute(r,e),x.copy(b);let t=o[e];v.copy(t),v.sub(b.multiplyScalar(b.dot(t))).normalize(),y.crossVectors(x,t);let n=y.dot(s[e])<0?-1:1;a.setXYZW(e,v.x,v.y,v.z,n)}for(let t=0,n=_.length;t<n;++t){let n=_[t],r=n.start,i=n.count;for(let t=r,n=r+i;t<n;t+=3)S(e.getX(t+0)),S(e.getX(t+1)),S(e.getX(t+2))}this._transformed=!0}computeVertexNormals(){let e=this.index,t=this.getAttribute(`position`);if(t!==void 0){let n=this.getAttribute(`normal`);if(n===void 0||n.count!==t.count)n=new NE(new Float32Array(t.count*3),3),this.setAttribute(`normal`,n);else for(let e=0,t=n.count;e<t;e++)n.setXYZ(e,0,0,0);let r=new X,i=new X,a=new X,o=new X,s=new X,c=new X,l=new X,u=new X;if(e)for(let d=0,f=e.count;d<f;d+=3){let f=e.getX(d+0),p=e.getX(d+1),m=e.getX(d+2);r.fromBufferAttribute(t,f),i.fromBufferAttribute(t,p),a.fromBufferAttribute(t,m),l.subVectors(a,i),u.subVectors(r,i),l.cross(u),o.fromBufferAttribute(n,f),s.fromBufferAttribute(n,p),c.fromBufferAttribute(n,m),o.add(l),s.add(l),c.add(l),n.setXYZ(f,o.x,o.y,o.z),n.setXYZ(p,s.x,s.y,s.z),n.setXYZ(m,c.x,c.y,c.z)}else for(let e=0,o=t.count;e<o;e+=3)r.fromBufferAttribute(t,e+0),i.fromBufferAttribute(t,e+1),a.fromBufferAttribute(t,e+2),l.subVectors(a,i),u.subVectors(r,i),l.cross(u),n.setXYZ(e+0,l.x,l.y,l.z),n.setXYZ(e+1,l.x,l.y,l.z),n.setXYZ(e+2,l.x,l.y,l.z);this.normalizeNormals(),n.needsUpdate=!0}}normalizeNormals(){let e=this.attributes.normal;for(let t=0,n=e.count;t<n;t++)qE.fromBufferAttribute(e,t),qE.normalize(),e.setXYZ(t,qE.x,qE.y,qE.z)}toNonIndexed(){function t(e,t){let n=e.array,r=e.itemSize,i=e.normalized,a=new n.constructor(t.length*r),o=0,s=0;for(let i=0,c=t.length;i<c;i++){o=e.isInterleavedBufferAttribute?t[i]*e.data.stride+e.offset:t[i]*r;for(let e=0;e<r;e++)a[s++]=n[o++]}return new NE(a,r,i)}if(this.index===null)return q(`BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed.`),this;let n=new e,r=this.index.array,i=this.attributes;for(let e in i){let a=i[e],o=t(a,r);n.setAttribute(e,o)}let a=this.morphAttributes;for(let e in a){let i=[],o=a[e];for(let e=0,n=o.length;e<n;e++){let n=o[e],a=t(n,r);i.push(a)}n.morphAttributes[e]=i}n.morphTargetsRelative=this.morphTargetsRelative;let o=this.groups;for(let e=0,t=o.length;e<t;e++){let t=o[e];n.addGroup(t.start,t.count,t.materialIndex)}return n}toJSON(){let e={metadata:{version:4.7,type:`BufferGeometry`,generator:`BufferGeometry.toJSON`}};if(e.uuid=this.uuid,e.type=this.parameters!==void 0&&this._transformed===!0?`BufferGeometry`:this.type,e.name=this.name,Object.keys(this.userData).length>0&&(e.userData=this.userData),this.parameters!==void 0&&this._transformed!==!0){let t=this.parameters;for(let n in t)t[n]!==void 0&&(e[n]=t[n]);return e}e.data={attributes:{}};let t=this.index;t!==null&&(e.data.index={type:t.array.constructor.name,array:Array.prototype.slice.call(t.array)});let n=this.attributes;for(let t in n){let r=n[t];e.data.attributes[t]=r.toJSON(e.data)}let r={},i=!1;for(let t in this.morphAttributes){let n=this.morphAttributes[t],a=[];for(let t=0,r=n.length;t<r;t++){let r=n[t];a.push(r.toJSON(e.data))}a.length>0&&(r[t]=a,i=!0)}i&&(e.data.morphAttributes=r,e.data.morphTargetsRelative=this.morphTargetsRelative);let a=this.groups;a.length>0&&(e.data.groups=JSON.parse(JSON.stringify(a)));let o=this.boundingSphere;return o!==null&&(e.data.boundingSphere=o.toJSON()),e}clone(){return new this.constructor().copy(this)}copy(e){this.index=null,this.attributes={},this.morphAttributes={},this.groups=[],this.boundingBox=null,this.boundingSphere=null;let t={};this.name=e.name;let n=e.index;n!==null&&this.setIndex(n.clone());let r=e.attributes;for(let e in r){let n=r[e];this.setAttribute(e,n.clone(t))}let i=e.morphAttributes;for(let e in i){let n=[],r=i[e];for(let e=0,i=r.length;e<i;e++)n.push(r[e].clone(t));this.morphAttributes[e]=n}this.morphTargetsRelative=e.morphTargetsRelative;let a=e.groups;for(let e=0,t=a.length;e<t;e++){let t=a[e];this.addGroup(t.start,t.count,t.materialIndex)}let o=e.boundingBox;o!==null&&(this.boundingBox=o.clone());let s=e.boundingSphere;return s!==null&&(this.boundingSphere=s.clone()),this.drawRange.start=e.drawRange.start,this.drawRange.count=e.drawRange.count,this.userData=e.userData,this._transformed=e._transformed,this}dispose(){this.dispatchEvent({type:`dispose`})}},YE=/*@__PURE__*/ new X,XE=/*@__PURE__*/ new X,ZE=/*@__PURE__*/ new Z,QE=class{constructor(e=new X(1,0,0),t=0){this.isPlane=!0,this.normal=e,this.constant=t}set(e,t){return this.normal.copy(e),this.constant=t,this}setComponents(e,t,n,r){return this.normal.set(e,t,n),this.constant=r,this}setFromNormalAndCoplanarPoint(e,t){return this.normal.copy(e),this.constant=-t.dot(this.normal),this}setFromCoplanarPoints(e,t,n){let r=YE.subVectors(n,t).cross(XE.subVectors(e,t)).normalize();return this.setFromNormalAndCoplanarPoint(r,e),this}copy(e){return this.normal.copy(e.normal),this.constant=e.constant,this}normalize(){let e=1/this.normal.length();return this.normal.multiplyScalar(e),this.constant*=e,this}negate(){return this.constant*=-1,this.normal.negate(),this}distanceToPoint(e){return this.normal.dot(e)+this.constant}distanceToSphere(e){return this.distanceToPoint(e.center)-e.radius}projectPoint(e,t){return t.copy(e).addScaledVector(this.normal,-this.distanceToPoint(e))}intersectLine(e,t,n=!0){let r=e.delta(YE),i=this.normal.dot(r);if(i===0)return this.distanceToPoint(e.start)===0?t.copy(e.start):null;let a=-(e.start.dot(this.normal)+this.constant)/i;return n===!0&&(a<0||a>1)?null:t.copy(e.start).addScaledVector(r,a)}intersectsLine(e){let t=this.distanceToPoint(e.start),n=this.distanceToPoint(e.end);return t<0&&n>0||n<0&&t>0}intersectsBox(e){return e.intersectsPlane(this)}intersectsSphere(e){return e.intersectsPlane(this)}coplanarPoint(e){return e.copy(this.normal).multiplyScalar(-this.constant)}applyMatrix4(e,t){let n=t||ZE.getNormalMatrix(e),r=this.coplanarPoint(YE).applyMatrix4(e),i=this.normal.applyMatrix3(n).normalize();return this.constant=-r.dot(i),this}translate(e){return this.constant-=e.dot(this.normal),this}equals(e){return e.normal.equals(this.normal)&&e.constant===this.constant}clone(){return new this.constructor().copy(this)}toJSON(){return{normal:this.normal.toArray(),constant:this.constant}}fromJSON(e){return this.normal.fromArray(e.normal),this.constant=e.constant,this}},$E=0,eD=class extends Rw{constructor(){super(),this.isMaterial=!0,Object.defineProperty(this,"id",{value:$E++}),this.uuid=Hw(),this.name=``,this.type=`Material`,this.blending=1,this.side=0,this.vertexColors=!1,this.opacity=1,this.transparent=!1,this.alphaHash=!1,this.blendSrc=204,this.blendDst=205,this.blendEquation=100,this.blendSrcAlpha=null,this.blendDstAlpha=null,this.blendEquationAlpha=null,this.blendColor=new QT(0,0,0),this.blendAlpha=0,this.depthFunc=3,this.depthTest=!0,this.depthWrite=!0,this.stencilWriteMask=255,this.stencilFunc=519,this.stencilRef=0,this.stencilFuncMask=255,this.stencilFail=ww,this.stencilZFail=ww,this.stencilZPass=ww,this.stencilWrite=!1,this.clippingPlanes=null,this.clipIntersection=!1,this.clipShadows=!1,this.shadowSide=null,this.colorWrite=!0,this.precision=null,this.polygonOffset=!1,this.polygonOffsetFactor=0,this.polygonOffsetUnits=0,this.dithering=!1,this.alphaToCoverage=!1,this.premultipliedAlpha=!1,this.forceSinglePass=!1,this.allowOverride=!0,this.visible=!0,this.toneMapped=!0,this.userData={},this.version=0,this._alphaTest=0}get alphaTest(){return this._alphaTest}set alphaTest(e){this._alphaTest>0!=e>0&&this.version++,this._alphaTest=e}onBeforeRender(){}onBeforeCompile(){}customProgramCacheKey(){return this.onBeforeCompile.toString()}setValues(e){if(e!==void 0)for(let t in e){let n=e[t];if(n===void 0){q(`Material: parameter '${t}' has value of undefined.`);continue}let r=this[t];if(r===void 0){q(`Material: '${t}' is not a property of THREE.${this.type}.`);continue}r&&r.isColor?r.set(n):r&&r.isVector2&&n&&n.isVector2||r&&r.isEuler&&n&&n.isEuler||r&&r.isVector3&&n&&n.isVector3?r.copy(n):this[t]=n}}toJSON(e){let t=e===void 0||typeof e==`string`;t&&(e={textures:{},images:{}});let n={metadata:{version:4.7,type:`Material`,generator:`Material.toJSON`}};n.uuid=this.uuid,n.type=this.type,n.blending=this.blending,n.side=this.side,n.shadowSide=this.shadowSide,n.vertexColors=this.vertexColors,n.opacity=this.opacity,n.transparent=this.transparent,n.blendSrc=this.blendSrc,n.blendDst=this.blendDst,n.blendEquation=this.blendEquation,n.blendSrcAlpha=this.blendSrcAlpha,n.blendDstAlpha=this.blendDstAlpha,n.blendEquationAlpha=this.blendEquationAlpha,n.blendColor=this.blendColor.getHex(),n.blendAlpha=this.blendAlpha,n.depthFunc=this.depthFunc,n.depthTest=this.depthTest,n.depthWrite=this.depthWrite,n.colorWrite=this.colorWrite,n.clipIntersection=this.clipIntersection,n.clipShadows=this.clipShadows,n.stencilWriteMask=this.stencilWriteMask,n.stencilFunc=this.stencilFunc,n.stencilRef=this.stencilRef,n.stencilFuncMask=this.stencilFuncMask,n.stencilFail=this.stencilFail,n.stencilZFail=this.stencilZFail,n.stencilZPass=this.stencilZPass,n.stencilWrite=this.stencilWrite,n.polygonOffset=this.polygonOffset,n.polygonOffsetFactor=this.polygonOffsetFactor,n.polygonOffsetUnits=this.polygonOffsetUnits,n.dithering=this.dithering,n.alphaTest=this.alphaTest,n.alphaHash=this.alphaHash,n.alphaToCoverage=this.alphaToCoverage,n.premultipliedAlpha=this.premultipliedAlpha,n.forceSinglePass=this.forceSinglePass,n.allowOverride=this.allowOverride,n.visible=this.visible,n.toneMapped=this.toneMapped,n.name=this.name,this.color&&this.color.isColor&&(n.color=this.color.getHex()),this.roughness!==void 0&&(n.roughness=this.roughness),this.metalness!==void 0&&(n.metalness=this.metalness),this.sheen!==void 0&&(n.sheen=this.sheen),this.sheenColor&&this.sheenColor.isColor&&(n.sheenColor=this.sheenColor.getHex()),this.sheenRoughness!==void 0&&(n.sheenRoughness=this.sheenRoughness),this.emissive&&this.emissive.isColor&&(n.emissive=this.emissive.getHex()),this.emissiveIntensity!==void 0&&(n.emissiveIntensity=this.emissiveIntensity),this.specular&&this.specular.isColor&&(n.specular=this.specular.getHex()),this.specularIntensity!==void 0&&(n.specularIntensity=this.specularIntensity),this.specularColor&&this.specularColor.isColor&&(n.specularColor=this.specularColor.getHex()),this.shininess!==void 0&&(n.shininess=this.shininess),this.clearcoat!==void 0&&(n.clearcoat=this.clearcoat),this.clearcoatRoughness!==void 0&&(n.clearcoatRoughness=this.clearcoatRoughness),this.clearcoatMap&&this.clearcoatMap.isTexture&&(n.clearcoatMap=this.clearcoatMap.toJSON(e).uuid),this.clearcoatRoughnessMap&&this.clearcoatRoughnessMap.isTexture&&(n.clearcoatRoughnessMap=this.clearcoatRoughnessMap.toJSON(e).uuid),this.clearcoatNormalMap&&this.clearcoatNormalMap.isTexture&&(n.clearcoatNormalMap=this.clearcoatNormalMap.toJSON(e).uuid,n.clearcoatNormalScale=this.clearcoatNormalScale.toArray()),this.sheenColorMap&&this.sheenColorMap.isTexture&&(n.sheenColorMap=this.sheenColorMap.toJSON(e).uuid),this.sheenRoughnessMap&&this.sheenRoughnessMap.isTexture&&(n.sheenRoughnessMap=this.sheenRoughnessMap.toJSON(e).uuid),this.dispersion!==void 0&&(n.dispersion=this.dispersion),this.retroreflectivity!==void 0&&(n.retroreflectivity=this.retroreflectivity),this.iridescence!==void 0&&(n.iridescence=this.iridescence),this.iridescenceIOR!==void 0&&(n.iridescenceIOR=this.iridescenceIOR),this.iridescenceThicknessRange!==void 0&&(n.iridescenceThicknessRange=this.iridescenceThicknessRange),this.iridescenceMap&&this.iridescenceMap.isTexture&&(n.iridescenceMap=this.iridescenceMap.toJSON(e).uuid),this.iridescenceThicknessMap&&this.iridescenceThicknessMap.isTexture&&(n.iridescenceThicknessMap=this.iridescenceThicknessMap.toJSON(e).uuid),this.anisotropy!==void 0&&(n.anisotropy=this.anisotropy),this.anisotropyRotation!==void 0&&(n.anisotropyRotation=this.anisotropyRotation),this.anisotropyMap&&this.anisotropyMap.isTexture&&(n.anisotropyMap=this.anisotropyMap.toJSON(e).uuid),this.map&&this.map.isTexture&&(n.map=this.map.toJSON(e).uuid),this.matcap&&this.matcap.isTexture&&(n.matcap=this.matcap.toJSON(e).uuid),this.alphaMap&&this.alphaMap.isTexture&&(n.alphaMap=this.alphaMap.toJSON(e).uuid),this.lightMap&&this.lightMap.isTexture&&(n.lightMap=this.lightMap.toJSON(e).uuid,n.lightMapIntensity=this.lightMapIntensity),this.aoMap&&this.aoMap.isTexture&&(n.aoMap=this.aoMap.toJSON(e).uuid,n.aoMapIntensity=this.aoMapIntensity),this.bumpMap&&this.bumpMap.isTexture&&(n.bumpMap=this.bumpMap.toJSON(e).uuid,n.bumpScale=this.bumpScale),this.normalMap&&this.normalMap.isTexture&&(n.normalMap=this.normalMap.toJSON(e).uuid,n.normalMapType=this.normalMapType,n.normalScale=this.normalScale.toArray()),this.displacementMap&&this.displacementMap.isTexture&&(n.displacementMap=this.displacementMap.toJSON(e).uuid,n.displacementScale=this.displacementScale,n.displacementBias=this.displacementBias),this.roughnessMap&&this.roughnessMap.isTexture&&(n.roughnessMap=this.roughnessMap.toJSON(e).uuid),this.metalnessMap&&this.metalnessMap.isTexture&&(n.metalnessMap=this.metalnessMap.toJSON(e).uuid),this.emissiveMap&&this.emissiveMap.isTexture&&(n.emissiveMap=this.emissiveMap.toJSON(e).uuid),this.specularMap&&this.specularMap.isTexture&&(n.specularMap=this.specularMap.toJSON(e).uuid),this.specularIntensityMap&&this.specularIntensityMap.isTexture&&(n.specularIntensityMap=this.specularIntensityMap.toJSON(e).uuid),this.specularColorMap&&this.specularColorMap.isTexture&&(n.specularColorMap=this.specularColorMap.toJSON(e).uuid),this.envMap&&this.envMap.isTexture&&(n.envMap=this.envMap.toJSON(e).uuid,this.combine!==void 0&&(n.combine=this.combine)),this.envMapRotation!==void 0&&(n.envMapRotation=this.envMapRotation.toArray()),this.envMapIntensity!==void 0&&(n.envMapIntensity=this.envMapIntensity),this.reflectivity!==void 0&&(n.reflectivity=this.reflectivity),this.refractionRatio!==void 0&&(n.refractionRatio=this.refractionRatio),this.gradientMap&&this.gradientMap.isTexture&&(n.gradientMap=this.gradientMap.toJSON(e).uuid),this.transmission!==void 0&&(n.transmission=this.transmission),this.transmissionMap&&this.transmissionMap.isTexture&&(n.transmissionMap=this.transmissionMap.toJSON(e).uuid),this.thickness!==void 0&&(n.thickness=this.thickness),this.thicknessMap&&this.thicknessMap.isTexture&&(n.thicknessMap=this.thicknessMap.toJSON(e).uuid),this.attenuationDistance!==void 0&&(n.attenuationDistance=this.attenuationDistance),this.attenuationColor!==void 0&&(n.attenuationColor=this.attenuationColor.getHex()),this.size!==void 0&&(n.size=this.size),this.sizeAttenuation!==void 0&&(n.sizeAttenuation=this.sizeAttenuation),Array.isArray(this.clippingPlanes)&&this.clippingPlanes.length>0&&(n.clippingPlanes=this.clippingPlanes.map(e=>e.toJSON())),this.rotation!==void 0&&(n.rotation=this.rotation),this.depthPacking!==void 0&&(n.depthPacking=this.depthPacking),this.linewidth!==void 0&&(n.linewidth=this.linewidth),this.linecap!==void 0&&(n.linecap=this.linecap),this.linejoin!==void 0&&(n.linejoin=this.linejoin),this.dashSize!==void 0&&(n.dashSize=this.dashSize),this.gapSize!==void 0&&(n.gapSize=this.gapSize),this.scale!==void 0&&(n.scale=this.scale),this.wireframe!==void 0&&(n.wireframe=this.wireframe),this.wireframeLinewidth!==void 0&&(n.wireframeLinewidth=this.wireframeLinewidth),this.wireframeLinecap!==void 0&&(n.wireframeLinecap=this.wireframeLinecap),this.wireframeLinejoin!==void 0&&(n.wireframeLinejoin=this.wireframeLinejoin),this.flatShading!==void 0&&(n.flatShading=this.flatShading),this.fog!==void 0&&(n.fog=this.fog),Object.keys(this.userData).length>0&&(n.userData=this.userData);function r(e){let t=[];for(let n in e){let r=e[n];delete r.metadata,t.push(r)}return t}if(t){let t=r(e.textures),i=r(e.images);t.length>0&&(n.textures=t),i.length>0&&(n.images=i)}return n}fromJSON(e,t){if(e.uuid!==void 0&&(this.uuid=e.uuid),e.name!==void 0&&(this.name=e.name),e.color!==void 0&&this.color!==void 0&&this.color.setHex(e.color),e.roughness!==void 0&&(this.roughness=e.roughness),e.metalness!==void 0&&(this.metalness=e.metalness),e.sheen!==void 0&&(this.sheen=e.sheen),e.sheenColor!==void 0&&(this.sheenColor=new QT().setHex(e.sheenColor)),e.sheenRoughness!==void 0&&(this.sheenRoughness=e.sheenRoughness),e.emissive!==void 0&&this.emissive!==void 0&&this.emissive.setHex(e.emissive),e.specular!==void 0&&this.specular!==void 0&&this.specular.setHex(e.specular),e.specularIntensity!==void 0&&(this.specularIntensity=e.specularIntensity),e.specularColor!==void 0&&this.specularColor!==void 0&&this.specularColor.setHex(e.specularColor),e.shininess!==void 0&&(this.shininess=e.shininess),e.clearcoat!==void 0&&(this.clearcoat=e.clearcoat),e.clearcoatRoughness!==void 0&&(this.clearcoatRoughness=e.clearcoatRoughness),e.dispersion!==void 0&&(this.dispersion=e.dispersion),e.retroreflectivity!==void 0&&(this.retroreflectivity=e.retroreflectivity),e.iridescence!==void 0&&(this.iridescence=e.iridescence),e.iridescenceIOR!==void 0&&(this.iridescenceIOR=e.iridescenceIOR),e.iridescenceThicknessRange!==void 0&&(this.iridescenceThicknessRange=e.iridescenceThicknessRange),e.transmission!==void 0&&(this.transmission=e.transmission),e.thickness!==void 0&&(this.thickness=e.thickness),e.attenuationDistance!==void 0&&(this.attenuationDistance=e.attenuationDistance),e.attenuationColor!==void 0&&this.attenuationColor!==void 0&&this.attenuationColor.setHex(e.attenuationColor),e.anisotropy!==void 0&&(this.anisotropy=e.anisotropy),e.anisotropyRotation!==void 0&&(this.anisotropyRotation=e.anisotropyRotation),e.fog!==void 0&&(this.fog=e.fog),e.flatShading!==void 0&&(this.flatShading=e.flatShading),e.blending!==void 0&&(this.blending=e.blending),e.combine!==void 0&&(this.combine=e.combine),e.side!==void 0&&(this.side=e.side),e.shadowSide!==void 0&&(this.shadowSide=e.shadowSide),e.opacity!==void 0&&(this.opacity=e.opacity),e.transparent!==void 0&&(this.transparent=e.transparent),e.alphaTest!==void 0&&(this.alphaTest=e.alphaTest),e.alphaHash!==void 0&&(this.alphaHash=e.alphaHash),e.depthFunc!==void 0&&(this.depthFunc=e.depthFunc),e.depthTest!==void 0&&(this.depthTest=e.depthTest),e.depthWrite!==void 0&&(this.depthWrite=e.depthWrite),e.colorWrite!==void 0&&(this.colorWrite=e.colorWrite),e.clippingPlanes!==void 0&&(this.clippingPlanes=e.clippingPlanes.map(e=>new QE().fromJSON(e))),e.clipIntersection!==void 0&&(this.clipIntersection=e.clipIntersection),e.clipShadows!==void 0&&(this.clipShadows=e.clipShadows),e.depthPacking!==void 0&&(this.depthPacking=e.depthPacking),e.blendSrc!==void 0&&(this.blendSrc=e.blendSrc),e.blendDst!==void 0&&(this.blendDst=e.blendDst),e.blendEquation!==void 0&&(this.blendEquation=e.blendEquation),e.blendSrcAlpha!==void 0&&(this.blendSrcAlpha=e.blendSrcAlpha),e.blendDstAlpha!==void 0&&(this.blendDstAlpha=e.blendDstAlpha),e.blendEquationAlpha!==void 0&&(this.blendEquationAlpha=e.blendEquationAlpha),e.blendColor!==void 0&&this.blendColor!==void 0&&this.blendColor.setHex(e.blendColor),e.blendAlpha!==void 0&&(this.blendAlpha=e.blendAlpha),e.stencilWriteMask!==void 0&&(this.stencilWriteMask=e.stencilWriteMask),e.stencilFunc!==void 0&&(this.stencilFunc=e.stencilFunc),e.stencilRef!==void 0&&(this.stencilRef=e.stencilRef),e.stencilFuncMask!==void 0&&(this.stencilFuncMask=e.stencilFuncMask),e.stencilFail!==void 0&&(this.stencilFail=e.stencilFail),e.stencilZFail!==void 0&&(this.stencilZFail=e.stencilZFail),e.stencilZPass!==void 0&&(this.stencilZPass=e.stencilZPass),e.stencilWrite!==void 0&&(this.stencilWrite=e.stencilWrite),e.wireframe!==void 0&&(this.wireframe=e.wireframe),e.wireframeLinewidth!==void 0&&(this.wireframeLinewidth=e.wireframeLinewidth),e.wireframeLinecap!==void 0&&(this.wireframeLinecap=e.wireframeLinecap),e.wireframeLinejoin!==void 0&&(this.wireframeLinejoin=e.wireframeLinejoin),e.rotation!==void 0&&(this.rotation=e.rotation),e.linewidth!==void 0&&(this.linewidth=e.linewidth),e.linecap!==void 0&&(this.linecap=e.linecap),e.linejoin!==void 0&&(this.linejoin=e.linejoin),e.dashSize!==void 0&&(this.dashSize=e.dashSize),e.gapSize!==void 0&&(this.gapSize=e.gapSize),e.scale!==void 0&&(this.scale=e.scale),e.polygonOffset!==void 0&&(this.polygonOffset=e.polygonOffset),e.polygonOffsetFactor!==void 0&&(this.polygonOffsetFactor=e.polygonOffsetFactor),e.polygonOffsetUnits!==void 0&&(this.polygonOffsetUnits=e.polygonOffsetUnits),e.dithering!==void 0&&(this.dithering=e.dithering),e.alphaToCoverage!==void 0&&(this.alphaToCoverage=e.alphaToCoverage),e.premultipliedAlpha!==void 0&&(this.premultipliedAlpha=e.premultipliedAlpha),e.forceSinglePass!==void 0&&(this.forceSinglePass=e.forceSinglePass),e.allowOverride!==void 0&&(this.allowOverride=e.allowOverride),e.visible!==void 0&&(this.visible=e.visible),e.toneMapped!==void 0&&(this.toneMapped=e.toneMapped),e.userData!==void 0&&(this.userData=e.userData),e.vertexColors!==void 0&&(this.vertexColors=typeof e.vertexColors==`number`?e.vertexColors>0:e.vertexColors),e.size!==void 0&&(this.size=e.size),e.sizeAttenuation!==void 0&&(this.sizeAttenuation=e.sizeAttenuation),e.map!==void 0&&(this.map=t[e.map]||null),e.matcap!==void 0&&(this.matcap=t[e.matcap]||null),e.alphaMap!==void 0&&(this.alphaMap=t[e.alphaMap]||null),e.bumpMap!==void 0&&(this.bumpMap=t[e.bumpMap]||null),e.bumpScale!==void 0&&(this.bumpScale=e.bumpScale),e.normalMap!==void 0&&(this.normalMap=t[e.normalMap]||null),e.normalMapType!==void 0&&(this.normalMapType=e.normalMapType),e.normalScale!==void 0){let t=e.normalScale;Array.isArray(t)===!1&&(t=[t,t]),this.normalScale=new Y().fromArray(t)}return e.displacementMap!==void 0&&(this.displacementMap=t[e.displacementMap]||null),e.displacementScale!==void 0&&(this.displacementScale=e.displacementScale),e.displacementBias!==void 0&&(this.displacementBias=e.displacementBias),e.roughnessMap!==void 0&&(this.roughnessMap=t[e.roughnessMap]||null),e.metalnessMap!==void 0&&(this.metalnessMap=t[e.metalnessMap]||null),e.emissiveMap!==void 0&&(this.emissiveMap=t[e.emissiveMap]||null),e.emissiveIntensity!==void 0&&(this.emissiveIntensity=e.emissiveIntensity),e.specularMap!==void 0&&(this.specularMap=t[e.specularMap]||null),e.specularIntensityMap!==void 0&&(this.specularIntensityMap=t[e.specularIntensityMap]||null),e.specularColorMap!==void 0&&(this.specularColorMap=t[e.specularColorMap]||null),e.envMap!==void 0&&(this.envMap=t[e.envMap]||null),e.envMapRotation!==void 0&&this.envMapRotation.fromArray(e.envMapRotation),e.envMapIntensity!==void 0&&(this.envMapIntensity=e.envMapIntensity),e.reflectivity!==void 0&&(this.reflectivity=e.reflectivity),e.refractionRatio!==void 0&&(this.refractionRatio=e.refractionRatio),e.lightMap!==void 0&&(this.lightMap=t[e.lightMap]||null),e.lightMapIntensity!==void 0&&(this.lightMapIntensity=e.lightMapIntensity),e.aoMap!==void 0&&(this.aoMap=t[e.aoMap]||null),e.aoMapIntensity!==void 0&&(this.aoMapIntensity=e.aoMapIntensity),e.gradientMap!==void 0&&(this.gradientMap=t[e.gradientMap]||null),e.clearcoatMap!==void 0&&(this.clearcoatMap=t[e.clearcoatMap]||null),e.clearcoatRoughnessMap!==void 0&&(this.clearcoatRoughnessMap=t[e.clearcoatRoughnessMap]||null),e.clearcoatNormalMap!==void 0&&(this.clearcoatNormalMap=t[e.clearcoatNormalMap]||null),e.clearcoatNormalScale!==void 0&&(this.clearcoatNormalScale=new Y().fromArray(e.clearcoatNormalScale)),e.iridescenceMap!==void 0&&(this.iridescenceMap=t[e.iridescenceMap]||null),e.iridescenceThicknessMap!==void 0&&(this.iridescenceThicknessMap=t[e.iridescenceThicknessMap]||null),e.transmissionMap!==void 0&&(this.transmissionMap=t[e.transmissionMap]||null),e.thicknessMap!==void 0&&(this.thicknessMap=t[e.thicknessMap]||null),e.anisotropyMap!==void 0&&(this.anisotropyMap=t[e.anisotropyMap]||null),e.sheenColorMap!==void 0&&(this.sheenColorMap=t[e.sheenColorMap]||null),e.sheenRoughnessMap!==void 0&&(this.sheenRoughnessMap=t[e.sheenRoughnessMap]||null),this}clone(){return new this.constructor().copy(this)}copy(e){this.name=e.name,this.blending=e.blending,this.side=e.side,this.vertexColors=e.vertexColors,this.opacity=e.opacity,this.transparent=e.transparent,this.blendSrc=e.blendSrc,this.blendDst=e.blendDst,this.blendEquation=e.blendEquation,this.blendSrcAlpha=e.blendSrcAlpha,this.blendDstAlpha=e.blendDstAlpha,this.blendEquationAlpha=e.blendEquationAlpha,this.blendColor.copy(e.blendColor),this.blendAlpha=e.blendAlpha,this.depthFunc=e.depthFunc,this.depthTest=e.depthTest,this.depthWrite=e.depthWrite,this.stencilWriteMask=e.stencilWriteMask,this.stencilFunc=e.stencilFunc,this.stencilRef=e.stencilRef,this.stencilFuncMask=e.stencilFuncMask,this.stencilFail=e.stencilFail,this.stencilZFail=e.stencilZFail,this.stencilZPass=e.stencilZPass,this.stencilWrite=e.stencilWrite;let t=e.clippingPlanes,n=null;if(t!==null){let e=t.length;n=Array(e);for(let r=0;r!==e;++r)n[r]=t[r].clone()}return this.clippingPlanes=n,this.clipIntersection=e.clipIntersection,this.clipShadows=e.clipShadows,this.shadowSide=e.shadowSide,this.colorWrite=e.colorWrite,this.precision=e.precision,this.polygonOffset=e.polygonOffset,this.polygonOffsetFactor=e.polygonOffsetFactor,this.polygonOffsetUnits=e.polygonOffsetUnits,this.dithering=e.dithering,this.alphaTest=e.alphaTest,this.alphaHash=e.alphaHash,this.alphaToCoverage=e.alphaToCoverage,this.premultipliedAlpha=e.premultipliedAlpha,this.forceSinglePass=e.forceSinglePass,this.allowOverride=e.allowOverride,this.visible=e.visible,this.toneMapped=e.toneMapped,this.userData=JSON.parse(JSON.stringify(e.userData)),this}dispose(){this.dispatchEvent({type:`dispose`})}set needsUpdate(e){e===!0&&this.version++}},tD=/*@__PURE__*/ new X,nD=/*@__PURE__*/ new X,rD=/*@__PURE__*/ new X,iD=/*@__PURE__*/ new X,aD=class{constructor(e=new X,t=new X(0,0,-1)){this.origin=e,this.direction=t}set(e,t){return this.origin.copy(e),this.direction.copy(t),this}copy(e){return this.origin.copy(e.origin),this.direction.copy(e.direction),this}at(e,t){return t.copy(this.origin).addScaledVector(this.direction,e)}lookAt(e){return this.direction.copy(e).sub(this.origin).normalize(),this}recast(e){return this.origin.copy(this.at(e,tD)),this}closestPointToPoint(e,t){t.subVectors(e,this.origin);let n=t.dot(this.direction);return n<0?t.copy(this.origin):t.copy(this.origin).addScaledVector(this.direction,n)}distanceToPoint(e){return Math.sqrt(this.distanceSqToPoint(e))}distanceSqToPoint(e){let t=tD.subVectors(e,this.origin).dot(this.direction);return t<0?this.origin.distanceToSquared(e):(tD.copy(this.origin).addScaledVector(this.direction,t),tD.distanceToSquared(e))}distanceSqToSegment(e,t,n,r){nD.copy(e).add(t).multiplyScalar(.5),rD.copy(t).sub(e).normalize(),iD.copy(this.origin).sub(nD);let i=e.distanceTo(t)*.5,a=-this.direction.dot(rD),o=iD.dot(this.direction),s=-iD.dot(rD),c=iD.lengthSq(),l=Math.abs(1-a*a),u,d,f,p;if(l>0){if(u=a*s-o,d=a*o-s,p=i*l,u>=0){if(d>=-p){if(d<=p){let e=1/l;u*=e,d*=e,f=u*(u+a*d+2*o)+d*(a*u+d+2*s)+c}else d=i,u=Math.max(0,-(a*d+o)),f=-u*u+d*(d+2*s)+c}else d=-i,u=Math.max(0,-(a*d+o)),f=-u*u+d*(d+2*s)+c}else d<=-p?(u=Math.max(0,-(-a*i+o)),d=u>0?-i:Math.min(Math.max(-i,-s),i),f=-u*u+d*(d+2*s)+c):d<=p?(u=0,d=Math.min(Math.max(-i,-s),i),f=d*(d+2*s)+c):(u=Math.max(0,-(a*i+o)),d=u>0?i:Math.min(Math.max(-i,-s),i),f=-u*u+d*(d+2*s)+c)}else d=a>0?-i:i,u=Math.max(0,-(a*d+o)),f=-u*u+d*(d+2*s)+c;return n&&n.copy(this.origin).addScaledVector(this.direction,u),r&&r.copy(nD).addScaledVector(rD,d),f}intersectSphere(e,t){if(e.radius<0)return null;tD.subVectors(e.center,this.origin);let n=tD.dot(this.direction),r=tD.dot(tD)-n*n,i=e.radius*e.radius;if(r>i)return null;let a=Math.sqrt(i-r),o=n-a,s=n+a;return s<0?null:o<0?this.at(s,t):this.at(o,t)}intersectsSphere(e){return e.radius<0?!1:this.distanceSqToPoint(e.center)<=e.radius*e.radius}distanceToPlane(e){let t=e.normal.dot(this.direction);if(t===0)return e.distanceToPoint(this.origin)===0?0:null;let n=-(this.origin.dot(e.normal)+e.constant)/t;return n>=0?n:null}intersectPlane(e,t){let n=this.distanceToPlane(e);return n===null?null:this.at(n,t)}intersectsPlane(e){let t=e.distanceToPoint(this.origin);return t===0||e.normal.dot(this.direction)*t<0}intersectBox(e,t){let n,r,i,a,o,s,c=1/this.direction.x,l=1/this.direction.y,u=1/this.direction.z,d=this.origin;return c>=0?(n=(e.min.x-d.x)*c,r=(e.max.x-d.x)*c):(n=(e.max.x-d.x)*c,r=(e.min.x-d.x)*c),l>=0?(i=(e.min.y-d.y)*l,a=(e.max.y-d.y)*l):(i=(e.max.y-d.y)*l,a=(e.min.y-d.y)*l),n>a||i>r||((i>n||isNaN(n))&&(n=i),(a<r||isNaN(r))&&(r=a),u>=0?(o=(e.min.z-d.z)*u,s=(e.max.z-d.z)*u):(o=(e.max.z-d.z)*u,s=(e.min.z-d.z)*u),n>s||o>r)||((o>n||n!==n)&&(n=o),(s<r||r!==r)&&(r=s),r<0)?null:this.at(n>=0?n:r,t)}intersectsBox(e){return this.intersectBox(e,tD)!==null}intersectTriangle(e,t,n,r,i){let a=this.origin,o=this.direction,s=o.x,c=o.y,l=o.z,u=e.x-a.x,d=e.y-a.y,f=e.z-a.z,p=t.x-a.x,m=t.y-a.y,h=t.z-a.z,g=n.x-a.x,_=n.y-a.y,v=n.z-a.z,y=Math.abs(s),b=Math.abs(c),x=Math.abs(l),S,C,w,T,E,D,O,k,A,ee,te,j;if(y>=b&&y>=x?(w=s,D=u,A=p,j=g,s>=0?(S=c,C=l,T=d,E=f,O=m,k=h,ee=_,te=v):(S=l,C=c,T=f,E=d,O=h,k=m,ee=v,te=_)):b>=x?(w=c,D=d,A=m,j=_,c>=0?(S=l,C=s,T=f,E=u,O=h,k=p,ee=v,te=g):(S=s,C=l,T=u,E=f,O=p,k=h,ee=g,te=v)):(w=l,D=f,A=h,j=v,l>=0?(S=s,C=c,T=u,E=d,O=p,k=m,ee=g,te=_):(S=c,C=s,T=d,E=u,O=m,k=p,ee=_,te=g)),w===0)return null;let ne=S/w,re=C/w,M=1/w,ie=T-ne*D,N=E-re*D,ae=O-ne*A,oe=k-re*A,se=ee-ne*j,ce=te-re*j,le=se*oe-ce*ae,ue=ie*ce-N*se,de=ae*N-oe*ie;if(r){if(le<0||ue<0||de<0)return null}else if((le<0||ue<0||de<0)&&(le>0||ue>0||de>0))return null;let fe=le+ue+de;if(fe===0)return null;let pe=M*(le*D+ue*A+de*j);return(fe>0?pe<0:pe>0)?null:this.at(pe/fe,i)}applyMatrix4(e){return this.origin.applyMatrix4(e),this.direction.transformDirection(e),this}equals(e){return e.origin.equals(this.origin)&&e.direction.equals(this.direction)}clone(){return new this.constructor().copy(this)}},oD=class extends eD{constructor(e){super(),this.isMeshBasicMaterial=!0,this.type=`MeshBasicMaterial`,this.color=new QT(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new DT,this.combine=0,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap=`round`,this.wireframeLinejoin=`round`,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.specularMap=e.specularMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.combine=e.combine,this.reflectivity=e.reflectivity,this.refractionRatio=e.refractionRatio,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.fog=e.fog,this}},sD=/*@__PURE__*/ new _T,cD=/*@__PURE__*/ new aD,lD=/*@__PURE__*/ new BE,uD=/*@__PURE__*/ new X,dD=/*@__PURE__*/ new X,fD=/*@__PURE__*/ new X,pD=/*@__PURE__*/ new X,mD=/*@__PURE__*/ new X,hD=/*@__PURE__*/ new X,gD=/*@__PURE__*/ new X,_D=/*@__PURE__*/ new X,vD=class extends WT{constructor(e=new JE,t=new oD){super(),this.isMesh=!0,this.type=`Mesh`,this.geometry=e,this.material=t,this.morphTargetDictionary=void 0,this.morphTargetInfluences=void 0,this.count=1,this.updateMorphTargets()}copy(e,t){return super.copy(e,t),e.morphTargetInfluences!==void 0&&(this.morphTargetInfluences=e.morphTargetInfluences.slice()),e.morphTargetDictionary!==void 0&&(this.morphTargetDictionary=Object.assign({},e.morphTargetDictionary)),this.material=Array.isArray(e.material)?e.material.slice():e.material,this.geometry=e.geometry,this}updateMorphTargets(){let e=this.geometry.morphAttributes,t=Object.keys(e);if(t.length>0){let n=e[t[0]];if(n!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let e=0,t=n.length;e<t;e++){let t=n[e].name||String(e);this.morphTargetInfluences.push(0),this.morphTargetDictionary[t]=e}}}}getVertexPosition(e,t){let n=this.geometry,r=n.attributes.position,i=n.morphAttributes.position,a=n.morphTargetsRelative;t.fromBufferAttribute(r,e);let o=this.morphTargetInfluences;if(i&&o){hD.set(0,0,0);for(let n=0,r=i.length;n<r;n++){let r=o[n],s=i[n];r!==0&&(mD.fromBufferAttribute(s,e),a?hD.addScaledVector(mD,r):hD.addScaledVector(mD.sub(t),r))}t.add(hD)}return t}intersectsFrustum(e){return e.intersectsObject(this)}raycast(e,t){let n=this.geometry,r=this.material,i=this.matrixWorld;r!==void 0&&(n.boundingSphere===null&&n.computeBoundingSphere(),lD.copy(n.boundingSphere),lD.applyMatrix4(i),cD.copy(e.ray).recast(e.near),!(lD.containsPoint(cD.origin)===!1&&(cD.intersectSphere(lD,uD)===null||cD.origin.distanceToSquared(uD)>(e.far-e.near)**2))&&(sD.copy(i).invert(),cD.copy(e.ray).applyMatrix4(sD),(n.boundingBox===null||cD.intersectsBox(n.boundingBox)!==!1)&&this._computeIntersections(e,t,cD)))}_computeIntersections(e,t,n){let r,i=this.geometry,a=this.material,o=i.index,s=i.attributes.position,c=i.attributes.uv,l=i.attributes.uv1,u=i.attributes.normal,d=i.groups,f=i.drawRange;if(o!==null){if(Array.isArray(a))for(let i=0,s=d.length;i<s;i++){let s=d[i],p=a[s.materialIndex],m=Math.max(s.start,f.start),h=Math.min(o.count,Math.min(s.start+s.count,f.start+f.count));for(let i=m,a=h;i<a;i+=3){let a=o.getX(i),d=o.getX(i+1),f=o.getX(i+2);r=bD(this,p,e,n,c,l,u,a,d,f),r&&(r.faceIndex=Math.floor(i/3),r.face.materialIndex=s.materialIndex,t.push(r))}}else{let i=Math.max(0,f.start),s=Math.min(o.count,f.start+f.count);for(let d=i,f=s;d<f;d+=3){let i=o.getX(d),s=o.getX(d+1),f=o.getX(d+2);r=bD(this,a,e,n,c,l,u,i,s,f),r&&(r.faceIndex=Math.floor(d/3),t.push(r))}}}else if(s!==void 0){if(Array.isArray(a))for(let i=0,o=d.length;i<o;i++){let o=d[i],p=a[o.materialIndex],m=Math.max(o.start,f.start),h=Math.min(s.count,Math.min(o.start+o.count,f.start+f.count));for(let i=m,a=h;i<a;i+=3){let a=i,s=i+1,d=i+2;r=bD(this,p,e,n,c,l,u,a,s,d),r&&(r.faceIndex=Math.floor(i/3),r.face.materialIndex=o.materialIndex,t.push(r))}}else{let i=Math.max(0,f.start),o=Math.min(s.count,f.start+f.count);for(let s=i,d=o;s<d;s+=3){let i=s,o=s+1,d=s+2;r=bD(this,a,e,n,c,l,u,i,o,d),r&&(r.faceIndex=Math.floor(s/3),t.push(r))}}}}};function yD(e,t,n,r,i,a,o,s){let c;if(c=t.side===1?r.intersectTriangle(o,a,i,!0,s):r.intersectTriangle(i,a,o,t.side===0,s),c===null)return null;_D.copy(s),_D.applyMatrix4(e.matrixWorld);let l=n.ray.origin.distanceTo(_D);return l<n.near||l>n.far?null:{distance:l,point:_D.clone(),object:e}}function bD(e,t,n,r,i,a,o,s,c,l){e.getVertexPosition(s,dD),e.getVertexPosition(c,fD),e.getVertexPosition(l,pD);let u=yD(e,t,n,r,dD,fD,pD,gD);if(u){let e=new X;mE.getBarycoord(gD,dD,fD,pD,e),i&&(u.uv=mE.getInterpolatedAttribute(i,s,c,l,e,new Y)),a&&(u.uv1=mE.getInterpolatedAttribute(a,s,c,l,e,new Y)),o&&(u.normal=mE.getInterpolatedAttribute(o,s,c,l,e,new X),u.normal.dot(r.direction)>0&&u.normal.multiplyScalar(-1));let t={a:s,b:c,c:l,normal:new X,materialIndex:0};mE.getNormal(dD,fD,pD,t.normal),u.face=t,u.barycoord=e}return u}var xD=class extends dT{constructor(e=null,t=1,n=1,r,i,a,o,s,c=tC,l=tC,u,d){super(null,a,o,s,c,l,r,i,u,d),this.isDataTexture=!0,this.image={data:e,width:t,height:n},this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}},SD=/*@__PURE__*/ new BE,CD=/*@__PURE__*/ new Y(.5,.5),wD=/*@__PURE__*/ new X,TD=class{constructor(e=new QE,t=new QE,n=new QE,r=new QE,i=new QE,a=new QE){this.planes=[e,t,n,r,i,a]}set(e,t,n,r,i,a){let o=this.planes;return o[0].copy(e),o[1].copy(t),o[2].copy(n),o[3].copy(r),o[4].copy(i),o[5].copy(a),this}copy(e){let t=this.planes;for(let n=0;n<6;n++)t[n].copy(e.planes[n]);return this}setFromProjectionMatrix(e,t=Dw,n=!1){let r=this.planes,i=e.elements,a=i[0],o=i[1],s=i[2],c=i[3],l=i[4],u=i[5],d=i[6],f=i[7],p=i[8],m=i[9],h=i[10],g=i[11],_=i[12],v=i[13],y=i[14],b=i[15];if(r[0].setComponents(c-a,f-l,g-p,b-_).normalize(),r[1].setComponents(c+a,f+l,g+p,b+_).normalize(),r[2].setComponents(c+o,f+u,g+m,b+v).normalize(),r[3].setComponents(c-o,f-u,g-m,b-v).normalize(),n)r[4].setComponents(s,d,h,y).normalize(),r[5].setComponents(c-s,f-d,g-h,b-y).normalize();else if(r[4].setComponents(c-s,f-d,g-h,b-y).normalize(),t===2e3)r[5].setComponents(c+s,f+d,g+h,b+y).normalize();else if(t===2001)r[5].setComponents(s,d,h,y).normalize();else throw Error(`THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: `+t);return this}intersectsObject(e){if(e.boundingSphere!==void 0)e.boundingSphere===null&&e.computeBoundingSphere(),SD.copy(e.boundingSphere).applyMatrix4(e.matrixWorld);else{let t=e.geometry;t.boundingSphere===null&&t.computeBoundingSphere(),SD.copy(t.boundingSphere).applyMatrix4(e.matrixWorld)}return this.intersectsSphere(SD)}intersectsSprite(e){return SD.center.set(0,0,0),SD.radius=.7071067811865476+CD.distanceTo(e.center),SD.applyMatrix4(e.matrixWorld),this.intersectsSphere(SD)}intersectsSphere(e){let t=this.planes,n=e.center,r=-e.radius;for(let e=0;e<6;e++)if(t[e].distanceToPoint(n)<r)return!1;return!0}intersectsBox(e){let t=this.planes;for(let n=0;n<6;n++){let r=t[n];if(wD.x=r.normal.x>0?e.max.x:e.min.x,wD.y=r.normal.y>0?e.max.y:e.min.y,wD.z=r.normal.z>0?e.max.z:e.min.z,r.distanceToPoint(wD)<0)return!1}return!0}containsPoint(e){let t=this.planes;for(let n=0;n<6;n++)if(t[n].distanceToPoint(e)<0)return!1;return!0}clone(){return new this.constructor().copy(this)}},ED=class extends dT{constructor(e,t,n,r,i=iC,a=iC,o,s,c){super(e,t,n,r,i,a,o,s,c),this.isVideoTexture=!0,this.generateMipmaps=!1,this._requestVideoFrameCallbackId=0;let l=this;function u(){l.needsUpdate=!0,l._requestVideoFrameCallbackId=e.requestVideoFrameCallback(u)}`requestVideoFrameCallback`in e&&(this._requestVideoFrameCallbackId=e.requestVideoFrameCallback(u))}clone(){return new this.constructor(this.image).copy(this)}update(){let e=this.image;!(`requestVideoFrameCallback`in e)&&e.readyState>=e.HAVE_CURRENT_DATA&&(this.needsUpdate=!0)}dispose(){this._requestVideoFrameCallbackId!==0&&(this.source.data.cancelVideoFrameCallback(this._requestVideoFrameCallbackId),this._requestVideoFrameCallbackId=0),super.dispose()}},DD=class extends ED{constructor(e,t,n,r,i,a,o,s){super({},e,t,n,r,i,a,o,s),this.isVideoFrameTexture=!0}update(){}clone(){return new this.constructor().copy(this)}setFrame(e){this.image=e,this.needsUpdate=!0}},OD=class extends dT{constructor(e=[],t=301,n,r,i,a,o,s,c,l){super(e,t,n,r,i,a,o,s,c,l),this.isCubeTexture=!0,this.flipY=!1}get images(){return this.image}set images(e){this.image=e}},kD=class extends dT{constructor(e,t,n=fC,r,i,a,o=tC,s=tC,c,l=CC,u=1){if(l!==1026&&l!==1027)throw Error(`THREE.DepthTexture: format must be either THREE.DepthFormat or THREE.DepthStencilFormat`);super({width:e,height:t,depth:u},r,i,a,o,s,l,n,c),this.isDepthTexture=!0,this.flipY=!1,this.generateMipmaps=!1,this.compareFunction=null}copy(e){return super.copy(e),this.source=new sT(Object.assign({},e.image)),this.compareFunction=e.compareFunction,this}toJSON(e){let t=super.toJSON(e);return t.compareFunction=this.compareFunction,t}},AD=class extends kD{constructor(e,t=fC,n=301,r,i,a=tC,o=tC,s,c=CC){let l={width:e,height:e,depth:1},u=[l,l,l,l,l,l];super(e,e,t,n,r,i,a,o,s,c),this.image=u,this.isCubeDepthTexture=!0,this.isCubeTexture=!0}get images(){return this.image}set images(e){this.image=e}},jD=class extends dT{constructor(e=null){super(),this.sourceTexture=e,this.isExternalTexture=!0}copy(e){return super.copy(e),this.sourceTexture=e.sourceTexture,this}},MD=class e extends JE{constructor(e=1,t=1,n=1,r=1,i=1,a=1){super(),this.type=`BoxGeometry`,this.parameters={width:e,height:t,depth:n,widthSegments:r,heightSegments:i,depthSegments:a};let o=this;r=Math.floor(r),i=Math.floor(i),a=Math.floor(a);let s=[],c=[],l=[],u=[],d=0,f=0;p(`z`,`y`,`x`,-1,-1,n,t,e,a,i,0),p(`z`,`y`,`x`,1,-1,n,t,-e,a,i,1),p(`x`,`z`,`y`,1,1,e,n,t,r,a,2),p(`x`,`z`,`y`,1,-1,e,n,-t,r,a,3),p(`x`,`y`,`z`,1,-1,e,t,n,r,i,4),p(`x`,`y`,`z`,-1,-1,e,t,-n,r,i,5),this.setIndex(s),this.setAttribute(`position`,new IE(c,3)),this.setAttribute(`normal`,new IE(l,3)),this.setAttribute(`uv`,new IE(u,2));function p(e,t,n,r,i,a,p,m,h,g,_){let v=a/h,y=p/g,b=a/2,x=p/2,S=m/2,C=h+1,w=g+1,T=0,E=0,D=new X;for(let a=0;a<w;a++){let o=a*y-x;for(let s=0;s<C;s++)D[e]=(s*v-b)*r,D[t]=o*i,D[n]=S,c.push(D.x,D.y,D.z),D[e]=0,D[t]=0,D[n]=m>0?1:-1,l.push(D.x,D.y,D.z),u.push(s/h),u.push(1-a/g),T+=1}for(let e=0;e<g;e++)for(let t=0;t<h;t++){let n=d+t+C*e,r=d+t+C*(e+1),i=d+(t+1)+C*(e+1),a=d+(t+1)+C*e;s.push(n,r,a),s.push(r,i,a),E+=6}o.addGroup(f,E,_),f+=E,d+=T}}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(t){return new e(t.width,t.height,t.depth,t.widthSegments,t.heightSegments,t.depthSegments)}},ND=class e extends JE{constructor(e=1,t=1,n=1,r=1){super(),this.type=`PlaneGeometry`,this.parameters={width:e,height:t,widthSegments:n,heightSegments:r};let i=e/2,a=t/2,o=Math.floor(n),s=Math.floor(r),c=o+1,l=s+1,u=e/o,d=t/s,f=[],p=[],m=[],h=[];for(let e=0;e<l;e++){let t=e*d-a;for(let n=0;n<c;n++){let r=n*u-i;p.push(r,-t,0),m.push(0,0,1),h.push(n/o),h.push(1-e/s)}}for(let e=0;e<s;e++)for(let t=0;t<o;t++){let n=t+c*e,r=t+c*(e+1),i=t+1+c*(e+1),a=t+1+c*e;f.push(n,r,a),f.push(r,i,a)}this.setIndex(f),this.setAttribute(`position`,new IE(p,3)),this.setAttribute(`normal`,new IE(m,3)),this.setAttribute(`uv`,new IE(h,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(t){return new e(t.width,t.height,t.widthSegments,t.heightSegments)}};function PD(e){let t={};for(let n in e){t[n]={};for(let r in e[n]){let i=e[n][r];if(ID(i))i.isRenderTargetTexture?(q(`UniformsUtils: Textures of render targets cannot be cloned via cloneUniforms() or mergeUniforms().`),t[n][r]=null):t[n][r]=i.clone();else if(Array.isArray(i)){if(ID(i[0])){let e=[];for(let t=0,n=i.length;t<n;t++)e[t]=i[t].clone();t[n][r]=e}else t[n][r]=i.slice()}else t[n][r]=i}}return t}function FD(e){let t={};for(let n=0;n<e.length;n++){let r=PD(e[n]);for(let e in r)t[e]=r[e]}return t}function ID(e){return e&&(e.isColor||e.isMatrix3||e.isMatrix4||e.isVector2||e.isVector3||e.isVector4||e.isTexture||e.isQuaternion)}function LD(e){let t=[];for(let n=0;n<e.length;n++)t.push(e[n].clone());return t}function RD(e){let t=e.getRenderTarget();return t===null?e.outputColorSpace:t.isXRRenderTarget===!0?t.texture.colorSpace:tT.workingColorSpace}var zD={clone:PD,merge:FD},BD=`void main() {
|
|
4
4
|
gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
|
|
5
|
-
}`,
|
|
5
|
+
}`,VD=`void main() {
|
|
6
6
|
gl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );
|
|
7
|
-
}`,dE=class extends CT{constructor(e){super(),this.isShaderMaterial=!0,this.type=`ShaderMaterial`,this.defines={},this.uniforms={},this.uniformsGroups=[],this.vertexShader=lE,this.fragmentShader=uE,this.linewidth=1,this.wireframe=!1,this.wireframeLinewidth=1,this.fog=!1,this.lights=!1,this.clipping=!1,this.forceSinglePass=!0,this.extensions={clipCullDistance:!1,multiDraw:!1},this.defaultAttributeValues={color:[1,1,1],uv:[0,0],uv1:[0,0]},this.index0AttributeName=void 0,this.uniformsNeedUpdate=!1,this.glslVersion=null,e!==void 0&&this.setValues(e)}copy(e){return super.copy(e),this.fragmentShader=e.fragmentShader,this.vertexShader=e.vertexShader,this.uniforms=rE(e.uniforms),this.uniformsGroups=oE(e.uniformsGroups),this.defines=Object.assign({},e.defines),this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.fog=e.fog,this.lights=e.lights,this.clipping=e.clipping,this.extensions=Object.assign({},e.extensions),this.glslVersion=e.glslVersion,this.defaultAttributeValues=Object.assign({},e.defaultAttributeValues),this.index0AttributeName=e.index0AttributeName,this.uniformsNeedUpdate=e.uniformsNeedUpdate,this}toJSON(e){let t=super.toJSON(e);t.glslVersion=this.glslVersion,t.uniforms={};for(let n in this.uniforms){let r=this.uniforms[n].value;r&&r.isTexture?t.uniforms[n]={type:`t`,value:r.toJSON(e).uuid}:r&&r.isColor?t.uniforms[n]={type:`c`,value:r.getHex()}:r&&r.isVector2?t.uniforms[n]={type:`v2`,value:r.toArray()}:r&&r.isVector3?t.uniforms[n]={type:`v3`,value:r.toArray()}:r&&r.isVector4?t.uniforms[n]={type:`v4`,value:r.toArray()}:r&&r.isMatrix3?t.uniforms[n]={type:`m3`,value:r.toArray()}:r&&r.isMatrix4?t.uniforms[n]={type:`m4`,value:r.toArray()}:t.uniforms[n]={value:r}}Object.keys(this.defines).length>0&&(t.defines=this.defines),t.vertexShader=this.vertexShader,t.fragmentShader=this.fragmentShader,t.lights=this.lights,t.clipping=this.clipping;let n={};for(let e in this.extensions)this.extensions[e]===!0&&(n[e]=!0);return Object.keys(n).length>0&&(t.extensions=n),t}fromJSON(e,t){if(super.fromJSON(e,t),e.uniforms!==void 0)for(let n in e.uniforms){let r=e.uniforms[n];switch(this.uniforms[n]={},r.type){case`t`:this.uniforms[n].value=t[r.value]||null;break;case`c`:this.uniforms[n].value=new xw().setHex(r.value);break;case`v2`:this.uniforms[n].value=new Y().fromArray(r.value);break;case`v3`:this.uniforms[n].value=new X().fromArray(r.value);break;case`v4`:this.uniforms[n].value=new FC().fromArray(r.value);break;case`m3`:this.uniforms[n].value=new Z().fromArray(r.value);break;case`m4`:this.uniforms[n].value=new BC().fromArray(r.value);break;default:this.uniforms[n].value=r.value}}if(e.defines!==void 0&&(this.defines=e.defines),e.vertexShader!==void 0&&(this.vertexShader=e.vertexShader),e.fragmentShader!==void 0&&(this.fragmentShader=e.fragmentShader),e.glslVersion!==void 0&&(this.glslVersion=e.glslVersion),e.extensions!==void 0)for(let t in e.extensions)this.extensions[t]=e.extensions[t];return e.lights!==void 0&&(this.lights=e.lights),e.clipping!==void 0&&(this.clipping=e.clipping),this}},fE=class extends dE{constructor(e){super(e),this.isRawShaderMaterial=!0,this.type=`RawShaderMaterial`}},pE=class extends CT{constructor(e){super(),this.isMeshDepthMaterial=!0,this.type=`MeshDepthMaterial`,this.depthPacking=HS,this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.wireframe=!1,this.wireframeLinewidth=1,this.setValues(e)}copy(e){return super.copy(e),this.depthPacking=e.depthPacking,this.map=e.map,this.alphaMap=e.alphaMap,this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this}},mE=class extends CT{constructor(e){super(),this.isMeshDistanceMaterial=!0,this.type=`MeshDistanceMaterial`,this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.setValues(e)}copy(e){return super.copy(e),this.map=e.map,this.alphaMap=e.alphaMap,this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this}};function hE(e,t){return!e||e.constructor===t?e:typeof t.BYTES_PER_ELEMENT==`number`?new t(e):Array.prototype.slice.call(e)}function gE(e){return e!==void 0&&e.inTangents!==void 0&&e.outTangents!==void 0}var _E=class{constructor(e,t,n,r){this.parameterPositions=e,this._cachedIndex=0,this.resultBuffer=r===void 0?new t.constructor(n):r,this.sampleValues=t,this.valueSize=n,this.settings=null,this.DefaultSettings_={}}evaluate(e){let t=this.parameterPositions,n=this._cachedIndex,r=t[n],i=t[n-1];validate_interval:{seek:{let a;linear_scan:{forward_scan:if(!(e<r)){for(let a=n+2;;){if(r===void 0){if(e<i)break forward_scan;return n=t.length,this._cachedIndex=n,this.copySampleValue_(n-1)}if(n===a)break;if(i=r,r=t[++n],e<r)break seek}a=t.length;break linear_scan}if(!(e>=i)){let o=t[1];e<o&&(n=2,i=o);for(let a=n-2;;){if(i===void 0)return this._cachedIndex=0,this.copySampleValue_(0);if(n===a)break;if(r=i,i=t[--n-1],e>=i)break seek}a=n,n=0;break linear_scan}break validate_interval}for(;n<a;){let r=n+a>>>1;e<t[r]?a=r:n=r+1}if(r=t[n],i=t[n-1],i===void 0)return this._cachedIndex=0,this.copySampleValue_(0);if(r===void 0)return n=t.length,this._cachedIndex=n,this.copySampleValue_(n-1)}this._cachedIndex=n,this.intervalChanged_(n,i,r)}return this.interpolate_(n,i,e,r)}getSettings_(){return this.settings||this.DefaultSettings_}copySampleValue_(e){let t=this.resultBuffer,n=this.sampleValues,r=this.valueSize,i=e*r;for(let e=0;e!==r;++e)t[e]=n[i+e];return t}interpolate_(){throw Error(`THREE.Interpolant: Call to abstract method.`)}intervalChanged_(){}},vE=class extends _E{constructor(e,t,n,r){super(e,t,n,r),this._weightPrev=-0,this._offsetPrev=-0,this._weightNext=-0,this._offsetNext=-0,this.DefaultSettings_={endingStart:zS,endingEnd:zS}}intervalChanged_(e,t,n){let r=this.parameterPositions,i=e-2,a=e+1,o=r[i],s=r[a];if(o===void 0)switch(this.getSettings_().endingStart){case BS:i=e,o=2*t-n;break;case VS:i=r.length-2,o=t+r[i]-r[i+1];break;default:i=e,o=n}if(s===void 0)switch(this.getSettings_().endingEnd){case BS:a=e,s=2*n-t;break;case VS:a=1,s=n+r[1]-r[0];break;default:a=e-1,s=t}let c=(n-t)*.5,l=this.valueSize;this._weightPrev=c/(t-o),this._weightNext=c/(s-n),this._offsetPrev=i*l,this._offsetNext=a*l}interpolate_(e,t,n,r){let i=this.resultBuffer,a=this.sampleValues,o=this.valueSize,s=e*o,c=s-o,l=this._offsetPrev,u=this._offsetNext,d=this._weightPrev,f=this._weightNext,p=(n-t)/(r-t),m=p*p,h=m*p,g=-d*h+2*d*m-d*p,_=(1+d)*h+(-1.5-2*d)*m+(-.5+d)*p+1,v=(-1-f)*h+(1.5+f)*m+.5*p,y=f*h-f*m;for(let e=0;e!==o;++e)i[e]=g*a[l+e]+_*a[c+e]+v*a[s+e]+y*a[u+e];return i}},yE=class extends _E{constructor(e,t,n,r){super(e,t,n,r)}interpolate_(e,t,n,r){let i=this.resultBuffer,a=this.sampleValues,o=this.valueSize,s=e*o,c=s-o,l=(n-t)/(r-t),u=1-l;for(let e=0;e!==o;++e)i[e]=a[c+e]*u+a[s+e]*l;return i}},bE=class extends _E{constructor(e,t,n,r){super(e,t,n,r)}interpolate_(e){return this.copySampleValue_(e-1)}},xE=class extends _E{interpolate_(e,t,n,r){let i=this.resultBuffer,a=this.sampleValues,o=this.valueSize,s=e*o,c=s-o,l=this.inTangents,u=this.outTangents;if(!l||!u){let e=(n-t)/(r-t),l=1-e;for(let t=0;t!==o;++t)i[t]=a[c+t]*l+a[s+t]*e;return i}let d=o*2,f=e-1;for(let p=0;p!==o;++p){let o=a[c+p],m=a[s+p],h=f*d+p*2,g=u[h],_=u[h+1],v=e*d+p*2,y=l[v],b=l[v+1],x=wE(n,t,g,y,r);i[p]=SE(x,o,_,b,m)}return i}};function SE(e,t,n,r,i){let a=1-e;return a*a*a*t+3*a*a*e*n+3*a*e*e*r+e*e*e*i}function CE(e,t,n,r,i){let a=1-e;return 3*a*a*(n-t)+6*a*e*(r-n)+3*e*e*(i-r)}function wE(e,t,n,r,i){let a=(e-t)/(i-t);for(let o=0;o<8;o++){let o=SE(a,t,n,r,i)-e;if(Math.abs(o)<1e-10)break;let s=CE(a,t,n,r,i);if(Math.abs(s)<1e-10)break;a=Math.max(0,Math.min(1,a-o/s))}return a}var TE=class{constructor(e,t,n,r){if(e===void 0)throw Error(`THREE.KeyframeTrack: track name is undefined`);if(t===void 0||t.length===0)throw Error(`THREE.KeyframeTrack: no keyframes in track named `+e);this.name=e,this.times=hE(t,this.TimeBufferType),this.values=hE(n,this.ValueBufferType),this.setInterpolation(r||this.DefaultInterpolation)}static toJSON(e){let t=e.constructor,n;if(t.toJSON!==this.toJSON)n=t.toJSON(e);else{n={name:e.name,times:hE(e.times,Array),values:hE(e.values,Array)};let t=e.getInterpolation();t!==e.DefaultInterpolation&&(n.interpolation=t),gE(e.settings)&&(n.settings={inTangents:hE(e.settings.inTangents,Array),outTangents:hE(e.settings.outTangents,Array)})}return n.type=e.ValueTypeName,n}InterpolantFactoryMethodDiscrete(e){return new bE(this.times,this.values,this.getValueSize(),e)}InterpolantFactoryMethodLinear(e){return new yE(this.times,this.values,this.getValueSize(),e)}InterpolantFactoryMethodSmooth(e){return new vE(this.times,this.values,this.getValueSize(),e)}InterpolantFactoryMethodBezier(e){let t=new xE(this.times,this.values,this.getValueSize(),e);return this.settings&&(t.inTangents=this.settings.inTangents,t.outTangents=this.settings.outTangents),t}setInterpolation(e){let t;switch(e){case FS:t=this.InterpolantFactoryMethodDiscrete;break;case IS:t=this.InterpolantFactoryMethodLinear;break;case LS:t=this.InterpolantFactoryMethodSmooth;break;case RS:t=this.InterpolantFactoryMethodBezier}if(t===void 0){let t=`unsupported interpolation for `+this.ValueTypeName+` keyframe track named `+this.name;if(this.createInterpolant===void 0){if(e!==this.DefaultInterpolation)this.setInterpolation(this.DefaultInterpolation);else throw Error(t)}return q(`KeyframeTrack:`,t),this}return this.createInterpolant=t,this}getInterpolation(){switch(this.createInterpolant){case this.InterpolantFactoryMethodDiscrete:return FS;case this.InterpolantFactoryMethodLinear:return IS;case this.InterpolantFactoryMethodSmooth:return LS;case this.InterpolantFactoryMethodBezier:return RS}}getValueSize(){return this.values.length/this.times.length}shift(e){if(e!==0){let t=this.times;for(let n=0,r=t.length;n!==r;++n)t[n]+=e}return this}scale(e){if(e!==1){let t=this.times;for(let n=0,r=t.length;n!==r;++n)t[n]*=e;gE(this.settings)&&(EE(this.settings.inTangents,e),EE(this.settings.outTangents,e))}return this}trim(e,t){let n=this.times,r=n.length,i=0,a=r-1;for(;i!==r&&n[i]<e;)++i;for(;a!==-1&&n[a]>t;)--a;if(++a,i!==0||a!==r){i>=a&&(a=Math.max(a,1),i=a-1);let e=this.getValueSize();this.times=n.slice(i,a),this.values=this.values.slice(i*e,a*e)}return this}validate(){let e=!0,t=this.getValueSize();t-Math.floor(t)!==0&&(J(`KeyframeTrack: Invalid value size in track.`,this),e=!1);let n=this.times,r=this.values,i=n.length;i===0&&(J(`KeyframeTrack: Track is empty.`,this),e=!1);let a=null;for(let t=0;t!==i;t++){let r=n[t];if(typeof r==`number`&&isNaN(r)){J(`KeyframeTrack: Time is not a valid number.`,this,t,r),e=!1;break}if(a!==null&&a>r){J(`KeyframeTrack: Out of order keys.`,this,t,r,a),e=!1;break}a=r}if(r!==void 0&&QS(r))for(let t=0,n=r.length;t!==n;++t){let n=r[t];if(isNaN(n)){J(`KeyframeTrack: Value is not a valid number.`,this,t,n),e=!1;break}}return e}optimize(){let e=this.times.slice(),t=this.values.slice(),n=this.getValueSize(),r=this.getInterpolation()===LS,i=e.length-1,a=1;for(let o=1;o<i;++o){let i=!1,s=e[o];if(s!==e[o+1]&&(o!==1||s!==e[0])){if(r)i=!0;else{let e=o*n,r=e-n,a=e+n;for(let o=0;o!==n;++o){let n=t[e+o];if(n!==t[r+o]||n!==t[a+o]){i=!0;break}}}}if(i){if(o!==a){e[a]=e[o];let r=o*n,i=a*n;for(let e=0;e!==n;++e)t[i+e]=t[r+e]}++a}}if(i>0){e[a]=e[i];for(let e=i*n,r=a*n,o=0;o!==n;++o)t[r+o]=t[e+o];++a}return a===e.length?(this.times=e,this.values=t):(this.times=e.slice(0,a),this.values=t.slice(0,a*n)),this}clone(){let e=this.times.slice(),t=this.values.slice(),n=this.constructor,r=new n(this.name,e,t);return r.createInterpolant=this.createInterpolant,gE(this.settings)&&(r.settings={inTangents:this.settings.inTangents.slice(),outTangents:this.settings.outTangents.slice()}),r}};function EE(e,t){for(let n=0,r=e.length;n!==r;n+=2)e[n]*=t}TE.prototype.ValueTypeName=``,TE.prototype.TimeBufferType=Float32Array,TE.prototype.ValueBufferType=Float32Array,TE.prototype.DefaultInterpolation=IS;var DE=class extends TE{constructor(e,t,n){super(e,t,n)}};DE.prototype.ValueTypeName=`bool`,DE.prototype.ValueBufferType=Array,DE.prototype.DefaultInterpolation=FS,DE.prototype.InterpolantFactoryMethodLinear=void 0,DE.prototype.InterpolantFactoryMethodSmooth=void 0;var OE=class extends TE{constructor(e,t,n,r){super(e,t,n,r)}};OE.prototype.ValueTypeName=`color`;var kE=class extends TE{constructor(e,t,n,r){super(e,t,n,r)}};kE.prototype.ValueTypeName=`number`;var AE=class extends _E{constructor(e,t,n,r){super(e,t,n,r)}interpolate_(e,t,n,r){let i=this.resultBuffer,a=this.sampleValues,o=this.valueSize,s=(n-t)/(r-t),c=e*o;for(let e=c+o;c!==e;c+=4)_C.slerpFlat(i,0,a,c-o,a,c,s);return i}},jE=class extends TE{constructor(e,t,n,r){super(e,t,n,r)}InterpolantFactoryMethodLinear(e){return new AE(this.times,this.values,this.getValueSize(),e)}};jE.prototype.ValueTypeName=`quaternion`,jE.prototype.InterpolantFactoryMethodSmooth=void 0;var ME=class extends TE{constructor(e,t,n){super(e,t,n)}};ME.prototype.ValueTypeName=`string`,ME.prototype.ValueBufferType=Array,ME.prototype.DefaultInterpolation=FS,ME.prototype.InterpolantFactoryMethodLinear=void 0,ME.prototype.InterpolantFactoryMethodSmooth=void 0;var NE=class extends TE{constructor(e,t,n,r){super(e,t,n,r)}};NE.prototype.ValueTypeName=`vector`;var PE=/*@__PURE__*/ new X,FE=/*@__PURE__*/ new _C,IE=/*@__PURE__*/ new X,LE=class extends pw{constructor(){super(),this.isCamera=!0,this.type=`Camera`,this.matrixWorldInverse=new BC,this.projectionMatrix=new BC,this.projectionMatrixInverse=new BC,this.coordinateSystem=XS,this._reversedDepth=!1}get reversedDepth(){return this._reversedDepth}copy(e,t){return super.copy(e,t),this.matrixWorldInverse.copy(e.matrixWorldInverse),this.projectionMatrix.copy(e.projectionMatrix),this.projectionMatrixInverse.copy(e.projectionMatrixInverse),this.coordinateSystem=e.coordinateSystem,this}getWorldDirection(e){return super.getWorldDirection(e).negate()}updateMatrixWorld(e){super.updateMatrixWorld(e),this.matrixWorld.decompose(PE,FE,IE),IE.x===1&&IE.y===1&&IE.z===1?this.matrixWorldInverse.copy(this.matrixWorld).invert():this.matrixWorldInverse.compose(PE,FE,IE.set(1,1,1)).invert()}updateWorldMatrix(e,t,n=!1){super.updateWorldMatrix(e,t,n),this.matrixWorld.decompose(PE,FE,IE),IE.x===1&&IE.y===1&&IE.z===1?this.matrixWorldInverse.copy(this.matrixWorld).invert():this.matrixWorldInverse.compose(PE,FE,IE.set(1,1,1)).invert()}clone(){return new this.constructor().copy(this)}},RE=/*@__PURE__*/ new X,zE=/*@__PURE__*/ new Y,BE=/*@__PURE__*/ new Y,VE=class extends LE{constructor(e=50,t=1,n=.1,r=2e3){super(),this.isPerspectiveCamera=!0,this.type=`PerspectiveCamera`,this.fov=e,this.zoom=1,this.near=n,this.far=r,this.focus=10,this.aspect=t,this.view=null,this.filmGauge=35,this.filmOffset=0,this.updateProjectionMatrix()}copy(e,t){return super.copy(e,t),this.fov=e.fov,this.zoom=e.zoom,this.near=e.near,this.far=e.far,this.focus=e.focus,this.aspect=e.aspect,this.view=e.view===null?null:Object.assign({},e.view),this.filmGauge=e.filmGauge,this.filmOffset=e.filmOffset,this}setFocalLength(e){let t=.5*this.getFilmHeight()/e;this.fov=uC*2*Math.atan(t),this.updateProjectionMatrix()}getFocalLength(){let e=Math.tan(lC*.5*this.fov);return .5*this.getFilmHeight()/e}getEffectiveFOV(){return uC*2*Math.atan(Math.tan(lC*.5*this.fov)/this.zoom)}getFilmWidth(){return this.filmGauge*Math.min(this.aspect,1)}getFilmHeight(){return this.filmGauge/Math.max(this.aspect,1)}getViewBounds(e,t,n){RE.set(-1,-1,.5).applyMatrix4(this.projectionMatrixInverse),t.set(RE.x,RE.y).multiplyScalar(-e/RE.z),RE.set(1,1,.5).applyMatrix4(this.projectionMatrixInverse),n.set(RE.x,RE.y).multiplyScalar(-e/RE.z)}getViewSize(e,t){return this.getViewBounds(e,zE,BE),t.subVectors(BE,zE)}setViewOffset(e,t,n,r,i,a){this.aspect=e/t,this.view===null&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1}),this.view.enabled=!0,this.view.fullWidth=e,this.view.fullHeight=t,this.view.offsetX=n,this.view.offsetY=r,this.view.width=i,this.view.height=a,this.updateProjectionMatrix()}clearViewOffset(){this.view!==null&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){let e=this.near,t=e*Math.tan(lC*.5*this.fov)/this.zoom,n=2*t,r=this.aspect*n,i=-.5*r,a=this.view;if(this.view!==null&&this.view.enabled){let e=a.fullWidth,o=a.fullHeight;i+=a.offsetX*r/e,t-=a.offsetY*n/o,r*=a.width/e,n*=a.height/o}let o=this.filmOffset;o!==0&&(i+=e*o/this.getFilmWidth()),this.projectionMatrix.makePerspective(i,i+r,t,t-n,e,this.far,this.coordinateSystem,this.reversedDepth),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(e){let t=super.toJSON(e);return t.object.fov=this.fov,t.object.zoom=this.zoom,t.object.near=this.near,t.object.far=this.far,t.object.focus=this.focus,t.object.aspect=this.aspect,this.view!==null&&(t.object.view=Object.assign({},this.view)),t.object.filmGauge=this.filmGauge,t.object.filmOffset=this.filmOffset,t}},HE=class extends LE{constructor(e=-1,t=1,n=1,r=-1,i=.1,a=2e3){super(),this.isOrthographicCamera=!0,this.type=`OrthographicCamera`,this.zoom=1,this.view=null,this.left=e,this.right=t,this.top=n,this.bottom=r,this.near=i,this.far=a,this.updateProjectionMatrix()}copy(e,t){return super.copy(e,t),this.left=e.left,this.right=e.right,this.top=e.top,this.bottom=e.bottom,this.near=e.near,this.far=e.far,this.zoom=e.zoom,this.view=e.view===null?null:Object.assign({},e.view),this}setViewOffset(e,t,n,r,i,a){this.view===null&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1}),this.view.enabled=!0,this.view.fullWidth=e,this.view.fullHeight=t,this.view.offsetX=n,this.view.offsetY=r,this.view.width=i,this.view.height=a,this.updateProjectionMatrix()}clearViewOffset(){this.view!==null&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){let e=(this.right-this.left)/(2*this.zoom),t=(this.top-this.bottom)/(2*this.zoom),n=(this.right+this.left)/2,r=(this.top+this.bottom)/2,i=n-e,a=n+e,o=r+t,s=r-t;if(this.view!==null&&this.view.enabled){let e=(this.right-this.left)/this.view.fullWidth/this.zoom,t=(this.top-this.bottom)/this.view.fullHeight/this.zoom;i+=e*this.view.offsetX,a=i+e*this.view.width,o-=t*this.view.offsetY,s=o-t*this.view.height}this.projectionMatrix.makeOrthographic(i,a,o,s,this.near,this.far,this.coordinateSystem,this.reversedDepth),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(e){let t=super.toJSON(e);return t.object.zoom=this.zoom,t.object.left=this.left,t.object.right=this.right,t.object.top=this.top,t.object.bottom=this.bottom,t.object.near=this.near,t.object.far=this.far,this.view!==null&&(t.object.view=Object.assign({},this.view)),t}},UE=-90,WE=1,GE=class extends pw{constructor(e,t,n){super(),this.type=`CubeCamera`,this.renderTarget=n,this.coordinateSystem=null,this.activeMipmapLevel=0;let r=new VE(UE,WE,e,t);r.layers=this.layers,this.add(r);let i=new VE(UE,WE,e,t);i.layers=this.layers,this.add(i);let a=new VE(UE,WE,e,t);a.layers=this.layers,this.add(a);let o=new VE(UE,WE,e,t);o.layers=this.layers,this.add(o);let s=new VE(UE,WE,e,t);s.layers=this.layers,this.add(s);let c=new VE(UE,WE,e,t);c.layers=this.layers,this.add(c)}updateCoordinateSystem(){let e=this.coordinateSystem,t=this.children.concat(),[n,r,i,a,o,s]=t;for(let e of t)this.remove(e);if(e===2e3)n.up.set(0,1,0),n.lookAt(1,0,0),r.up.set(0,1,0),r.lookAt(-1,0,0),i.up.set(0,0,-1),i.lookAt(0,1,0),a.up.set(0,0,1),a.lookAt(0,-1,0),o.up.set(0,1,0),o.lookAt(0,0,1),s.up.set(0,1,0),s.lookAt(0,0,-1);else if(e===2001)n.up.set(0,-1,0),n.lookAt(-1,0,0),r.up.set(0,-1,0),r.lookAt(1,0,0),i.up.set(0,0,1),i.lookAt(0,1,0),a.up.set(0,0,-1),a.lookAt(0,-1,0),o.up.set(0,-1,0),o.lookAt(0,0,1),s.up.set(0,-1,0),s.lookAt(0,0,-1);else throw Error(`THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: `+e);for(let e of t)this.add(e),e.updateMatrixWorld()}update(e,t){this.parent===null&&this.updateMatrixWorld();let{renderTarget:n,activeMipmapLevel:r}=this;this.coordinateSystem!==e.coordinateSystem&&(this.coordinateSystem=e.coordinateSystem,this.updateCoordinateSystem());let[i,a,o,s,c,l]=this.children,u=e.getRenderTarget(),d=e.getActiveCubeFace(),f=e.getActiveMipmapLevel(),p=e.xr.enabled;e.xr.enabled=!1;let m=n.texture.generateMipmaps;n.texture.generateMipmaps=!1;let h=!1;h=e.isWebGLRenderer===!0?e.state.buffers.depth.getReversed():e.reversedDepthBuffer,e.setRenderTarget(n,0,r),h&&e.autoClear===!1&&e.clearDepth(),e.render(t,i),e.setRenderTarget(n,1,r),h&&e.autoClear===!1&&e.clearDepth(),e.render(t,a),e.setRenderTarget(n,2,r),h&&e.autoClear===!1&&e.clearDepth(),e.render(t,o),e.setRenderTarget(n,3,r),h&&e.autoClear===!1&&e.clearDepth(),e.render(t,s),e.setRenderTarget(n,4,r),h&&e.autoClear===!1&&e.clearDepth(),e.render(t,c),n.texture.generateMipmaps=m,e.setRenderTarget(n,5,r),h&&e.autoClear===!1&&e.clearDepth(),e.render(t,l),e.setRenderTarget(u,d,f),e.xr.enabled=p,n.texture.needsPMREMUpdate=!0}},KE=class extends VE{constructor(e=[]){super(),this.isArrayCamera=!0,this.isMultiViewCamera=!1,this.cameras=e}},qE=`\\[\\]\\.:\\/`,JE=/* @__PURE__ */ RegExp(`[\\[\\]\\.:\\/]`,`g`),YE=`[^\\[\\]\\.:\\/]`,XE=`[^`+qE.replace(`\\.`,``)+`]`,ZE=/*@__PURE__*/ `((?:WC+[\\/:])*)`.replace(`WC`,YE),QE=/*@__PURE__*/ `(WCOD+)?`.replace(`WCOD`,XE),$E=/*@__PURE__*/ `(?:\\.(WC+)(?:\\[(.+)\\])?)?`.replace(`WC`,YE),eD=/*@__PURE__*/ `\\.(WC+)(?:\\[(.+)\\])?`.replace(`WC`,YE),tD=RegExp(`^`+ZE+QE+$E+eD+`$`),nD=[`material`,`materials`,`bones`,`map`],rD=class{constructor(e,t,n){let r=n||iD.parseTrackName(t);this._targetGroup=e,this._bindings=e.subscribe_(t,r)}getValue(e,t){this.bind();let n=this._targetGroup.nCachedObjects_,r=this._bindings[n];r!==void 0&&r.getValue(e,t)}setValue(e,t){let n=this._bindings;for(let r=this._targetGroup.nCachedObjects_,i=n.length;r!==i;++r)n[r].setValue(e,t)}bind(){let e=this._bindings;for(let t=this._targetGroup.nCachedObjects_,n=e.length;t!==n;++t)e[t].bind()}unbind(){let e=this._bindings;for(let t=this._targetGroup.nCachedObjects_,n=e.length;t!==n;++t)e[t].unbind()}},iD=class e{constructor(t,n,r){this.path=n,this.parsedPath=r||e.parseTrackName(n),this.node=e.findNode(t,this.parsedPath.nodeName),this.rootNode=t,this.getValue=this._getValue_unbound,this.setValue=this._setValue_unbound}static create(t,n,r){return t&&t.isAnimationObjectGroup?new e.Composite(t,n,r):new e(t,n,r)}static sanitizeNodeName(e){return e.replace(/\s/g,`_`).replace(JE,``)}static parseTrackName(e){let t=tD.exec(e);if(t===null)throw Error(`THREE.PropertyBinding: Cannot parse trackName: `+e);let n={nodeName:t[2],objectName:t[3],objectIndex:t[4],propertyName:t[5],propertyIndex:t[6]},r=n.nodeName&&n.nodeName.lastIndexOf(`.`);if(r!==void 0&&r!==-1){let e=n.nodeName.substring(r+1);nD.indexOf(e)!==-1&&(n.nodeName=n.nodeName.substring(0,r),n.objectName=e)}if(n.propertyName===null||n.propertyName.length===0)throw Error(`THREE.PropertyBinding: can not parse propertyName from trackName: `+e);return n}static findNode(e,t){if(t===void 0||t===``||t===`.`||t===-1||t===e.name||t===e.uuid)return e;if(e.skeleton){let n=e.skeleton.getBoneByName(t);if(n!==void 0)return n}if(e.children){let n=function(e){for(let r=0;r<e.length;r++){let i=e[r];if(i.name===t||i.uuid===t)return i;let a=n(i.children);if(a)return a}return null},r=n(e.children);if(r)return r}return null}_getValue_unavailable(){}_setValue_unavailable(){}_getValue_direct(e,t){e[t]=this.targetObject[this.propertyName]}_getValue_array(e,t){let n=this.resolvedProperty;for(let r=0,i=n.length;r!==i;++r)e[t++]=n[r]}_getValue_arrayElement(e,t){e[t]=this.resolvedProperty[this.propertyIndex]}_getValue_toArray(e,t){this.resolvedProperty.toArray(e,t)}_setValue_direct(e,t){this.targetObject[this.propertyName]=e[t]}_setValue_direct_setNeedsUpdate(e,t){this.targetObject[this.propertyName]=e[t],this.targetObject.needsUpdate=!0}_setValue_direct_setMatrixWorldNeedsUpdate(e,t){this.targetObject[this.propertyName]=e[t],this.targetObject.matrixWorldNeedsUpdate=!0}_setValue_array(e,t){let n=this.resolvedProperty;for(let r=0,i=n.length;r!==i;++r)n[r]=e[t++]}_setValue_array_setNeedsUpdate(e,t){let n=this.resolvedProperty;for(let r=0,i=n.length;r!==i;++r)n[r]=e[t++];this.targetObject.needsUpdate=!0}_setValue_array_setMatrixWorldNeedsUpdate(e,t){let n=this.resolvedProperty;for(let r=0,i=n.length;r!==i;++r)n[r]=e[t++];this.targetObject.matrixWorldNeedsUpdate=!0}_setValue_arrayElement(e,t){this.resolvedProperty[this.propertyIndex]=e[t]}_setValue_arrayElement_setNeedsUpdate(e,t){this.resolvedProperty[this.propertyIndex]=e[t],this.targetObject.needsUpdate=!0}_setValue_arrayElement_setMatrixWorldNeedsUpdate(e,t){this.resolvedProperty[this.propertyIndex]=e[t],this.targetObject.matrixWorldNeedsUpdate=!0}_setValue_fromArray(e,t){this.resolvedProperty.fromArray(e,t)}_setValue_fromArray_setNeedsUpdate(e,t){this.resolvedProperty.fromArray(e,t),this.targetObject.needsUpdate=!0}_setValue_fromArray_setMatrixWorldNeedsUpdate(e,t){this.resolvedProperty.fromArray(e,t),this.targetObject.matrixWorldNeedsUpdate=!0}_getValue_unbound(e,t){this.bind(),this.getValue(e,t)}_setValue_unbound(e,t){this.bind(),this.setValue(e,t)}bind(){let t=this.node,n=this.parsedPath,r=n.objectName,i=n.propertyName,a=n.propertyIndex;if(t||(t=e.findNode(this.rootNode,n.nodeName),this.node=t),this.getValue=this._getValue_unavailable,this.setValue=this._setValue_unavailable,!t){q(`PropertyBinding: No target node found for track: `+this.path+`.`);return}if(r){let e=n.objectIndex;switch(r){case`materials`:if(!t.material){J(`PropertyBinding: Can not bind to material as node does not have a material.`,this);return}if(!t.material.materials){J(`PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.`,this);return}t=t.material.materials;break;case`bones`:if(!t.skeleton){J(`PropertyBinding: Can not bind to bones as node does not have a skeleton.`,this);return}t=t.skeleton.bones;for(let n=0;n<t.length;n++)if(t[n].name===e){e=n;break}break;case`map`:if(`map`in t){t=t.map;break}if(!t.material){J(`PropertyBinding: Can not bind to material as node does not have a material.`,this);return}if(!t.material.map){J(`PropertyBinding: Can not bind to material.map as node.material does not have a map.`,this);return}t=t.material.map;break;default:if(t[r]===void 0){J(`PropertyBinding: Can not bind to objectName of node undefined.`,this);return}t=t[r]}if(e!==void 0){if(t[e]===void 0){J(`PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.`,this,t);return}t=t[e]}}let o=t[i];if(o===void 0){let e=n.nodeName;J(`PropertyBinding: Trying to update property for track: `+e+`.`+i+` but it wasn't found.`,t);return}let s=this.Versioning.None;this.targetObject=t,t.isMaterial===!0?s=this.Versioning.NeedsUpdate:t.isObject3D===!0&&(s=this.Versioning.MatrixWorldNeedsUpdate);let c=this.BindingType.Direct;if(a!==void 0){if(i===`morphTargetInfluences`){if(!t.geometry){J(`PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.`,this);return}if(!t.geometry.morphAttributes){J(`PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.`,this);return}t.morphTargetDictionary[a]!==void 0&&(a=t.morphTargetDictionary[a])}c=this.BindingType.ArrayElement,this.resolvedProperty=o,this.propertyIndex=a}else o.fromArray!==void 0&&o.toArray!==void 0?(c=this.BindingType.HasFromToArray,this.resolvedProperty=o):Array.isArray(o)?(c=this.BindingType.EntireArray,this.resolvedProperty=o):this.propertyName=i;this.getValue=this.GetterByBindingType[c],this.setValue=this.SetterByBindingTypeAndVersioning[c][s]}unbind(){this.node=null,this.getValue=this._getValue_unbound,this.setValue=this._setValue_unbound}};iD.Composite=rD,iD.prototype.BindingType={Direct:0,EntireArray:1,ArrayElement:2,HasFromToArray:3},iD.prototype.Versioning={None:0,NeedsUpdate:1,MatrixWorldNeedsUpdate:2},iD.prototype.GetterByBindingType=[iD.prototype._getValue_direct,iD.prototype._getValue_array,iD.prototype._getValue_arrayElement,iD.prototype._getValue_toArray],iD.prototype.SetterByBindingTypeAndVersioning=[[iD.prototype._setValue_direct,iD.prototype._setValue_direct_setNeedsUpdate,iD.prototype._setValue_direct_setMatrixWorldNeedsUpdate],[iD.prototype._setValue_array,iD.prototype._setValue_array_setNeedsUpdate,iD.prototype._setValue_array_setMatrixWorldNeedsUpdate],[iD.prototype._setValue_arrayElement,iD.prototype._setValue_arrayElement_setNeedsUpdate,iD.prototype._setValue_arrayElement_setMatrixWorldNeedsUpdate],[iD.prototype._setValue_fromArray,iD.prototype._setValue_fromArray_setNeedsUpdate,iD.prototype._setValue_fromArray_setMatrixWorldNeedsUpdate]],class e{static{e.prototype.isMatrix2=!0}constructor(e,t,n,r){this.elements=[1,0,0,1],e!==void 0&&this.set(e,t,n,r)}identity(){return this.set(1,0,0,1),this}fromArray(e,t=0){for(let n=0;n<4;n++)this.elements[n]=e[n+t];return this}set(e,t,n,r){let i=this.elements;return i[0]=e,i[2]=t,i[1]=n,i[3]=r,this}};function aD(e,t,n,r){let i=oD(r);switch(n){case Ux:return e*t;case Jx:return e*t/i.components*i.byteLength;case Yx:return e*t/i.components*i.byteLength;case Xx:return e*t*2/i.components*i.byteLength;case Zx:return e*t*2/i.components*i.byteLength;case Wx:return e*t*3/i.components*i.byteLength;case Gx:return e*t*4/i.components*i.byteLength;case Qx:return e*t*4/i.components*i.byteLength;case $x:case eS:return Math.floor((e+3)/4)*Math.floor((t+3)/4)*8;case tS:case nS:return Math.floor((e+3)/4)*Math.floor((t+3)/4)*16;case iS:case oS:return Math.max(e,16)*Math.max(t,8)/4;case rS:case aS:return Math.max(e,8)*Math.max(t,8)/2;case sS:case cS:case uS:case dS:return Math.floor((e+3)/4)*Math.floor((t+3)/4)*8;case lS:case fS:case pS:return Math.floor((e+3)/4)*Math.floor((t+3)/4)*16;case mS:return Math.floor((e+3)/4)*Math.floor((t+3)/4)*16;case hS:return Math.floor((e+4)/5)*Math.floor((t+3)/4)*16;case gS:return Math.floor((e+4)/5)*Math.floor((t+4)/5)*16;case _S:return Math.floor((e+5)/6)*Math.floor((t+4)/5)*16;case vS:return Math.floor((e+5)/6)*Math.floor((t+5)/6)*16;case yS:return Math.floor((e+7)/8)*Math.floor((t+4)/5)*16;case bS:return Math.floor((e+7)/8)*Math.floor((t+5)/6)*16;case xS:return Math.floor((e+7)/8)*Math.floor((t+7)/8)*16;case SS:return Math.floor((e+9)/10)*Math.floor((t+4)/5)*16;case CS:return Math.floor((e+9)/10)*Math.floor((t+5)/6)*16;case wS:return Math.floor((e+9)/10)*Math.floor((t+7)/8)*16;case TS:return Math.floor((e+9)/10)*Math.floor((t+9)/10)*16;case ES:return Math.floor((e+11)/12)*Math.floor((t+9)/10)*16;case DS:return Math.floor((e+11)/12)*Math.floor((t+11)/12)*16;case OS:case kS:case AS:return Math.ceil(e/4)*Math.ceil(t/4)*16;case jS:case MS:return Math.ceil(e/4)*Math.ceil(t/4)*8;case NS:case PS:return Math.ceil(e/4)*Math.ceil(t/4)*16}throw Error(`Unable to determine texture byte length for ${n} format.`)}function oD(e){switch(e){case Ax:case jx:return{byteLength:1,components:1};case Nx:case Mx:case Lx:return{byteLength:2,components:1};case Rx:case zx:return{byteLength:2,components:4};case Fx:case Px:case Ix:return{byteLength:4,components:1};case Vx:case Hx:return{byteLength:4,components:3}}throw Error(`THREE.TextureUtils: Unknown texture type ${e}.`)}typeof __THREE_DEVTOOLS__<`u`&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent(`register`,{detail:{revision:`186`}})),typeof window<`u`&&(window.__THREE__?q(`WARNING: Multiple instances of Three.js being imported.`):window.__THREE__=`186`);function sD(){let e=null,t=!1,n=null,r=null;function i(t,a){r=e.requestAnimationFrame(i),n(t,a)}return{start:function(){t!==!0&&n!==null&&e!==null&&(r=e.requestAnimationFrame(i),t=!0)},stop:function(){e!==null&&e.cancelAnimationFrame(r),t=!1},setAnimationLoop:function(e){n=e},setContext:function(t){e=t}}}function cD(e){let t=/* @__PURE__ */ new WeakMap;function n(t,n){let r=t.array,i=t.usage,a=r.byteLength,o=e.createBuffer();e.bindBuffer(n,o),e.bufferData(n,r,i),t.onUploadCallback();let s;if(r instanceof Float32Array)s=e.FLOAT;else if(typeof Float16Array<`u`&&r instanceof Float16Array)s=e.HALF_FLOAT;else if(r instanceof Uint16Array)s=t.isFloat16BufferAttribute?e.HALF_FLOAT:e.UNSIGNED_SHORT;else if(r instanceof Int16Array)s=e.SHORT;else if(r instanceof Uint32Array)s=e.UNSIGNED_INT;else if(r instanceof Int32Array)s=e.INT;else if(r instanceof Int8Array)s=e.BYTE;else if(r instanceof Uint8Array)s=e.UNSIGNED_BYTE;else if(r instanceof Uint8ClampedArray)s=e.UNSIGNED_BYTE;else throw Error(`THREE.WebGLAttributes: Unsupported buffer data format: `+r);return{buffer:o,type:s,bytesPerElement:r.BYTES_PER_ELEMENT,version:t.version,size:a}}function r(t,n,r){let i=n.array,a=n.updateRanges;if(e.bindBuffer(r,t),a.length===0)e.bufferSubData(r,0,i);else{a.sort((e,t)=>e.start-t.start);let t=0;for(let e=1;e<a.length;e++){let n=a[t],r=a[e];r.start<=n.start+n.count+1?n.count=Math.max(n.count,r.start+r.count-n.start):(++t,a[t]=r)}a.length=t+1;for(let t=0,n=a.length;t<n;t++){let n=a[t];e.bufferSubData(r,n.start*i.BYTES_PER_ELEMENT,i,n.start,n.count)}n.clearUpdateRanges()}n.onUploadCallback()}function i(e){return e.isInterleavedBufferAttribute&&(e=e.data),t.get(e)}function a(n){n.isInterleavedBufferAttribute&&(n=n.data);let r=t.get(n);r&&(e.deleteBuffer(r.buffer),t.delete(n))}function o(e,i){if(e.isInterleavedBufferAttribute&&(e=e.data),e.isGLBufferAttribute){let n=t.get(e);(!n||n.version<e.version)&&t.set(e,{buffer:e.buffer,type:e.type,bytesPerElement:e.elementSize,version:e.version});return}let a=t.get(e);if(a===void 0)t.set(e,n(e,i));else if(a.version<e.version){if(a.size!==e.array.byteLength)throw Error(`THREE.WebGLAttributes: The size of the buffer attribute's array buffer does not match the original size. Resizing buffer attributes is not supported.`);r(a.buffer,e,i),a.version=e.version}}return{get:i,remove:a,update:o}}var Q={alphahash_fragment:`#ifdef USE_ALPHAHASH
|
|
7
|
+
}`,HD=class extends eD{constructor(e){super(),this.isShaderMaterial=!0,this.type=`ShaderMaterial`,this.defines={},this.uniforms={},this.uniformsGroups=[],this.vertexShader=BD,this.fragmentShader=VD,this.linewidth=1,this.wireframe=!1,this.wireframeLinewidth=1,this.fog=!1,this.lights=!1,this.clipping=!1,this.forceSinglePass=!0,this.extensions={clipCullDistance:!1,multiDraw:!1},this.defaultAttributeValues={color:[1,1,1],uv:[0,0],uv1:[0,0]},this.index0AttributeName=void 0,this.uniformsNeedUpdate=!1,this.glslVersion=null,e!==void 0&&this.setValues(e)}copy(e){return super.copy(e),this.fragmentShader=e.fragmentShader,this.vertexShader=e.vertexShader,this.uniforms=PD(e.uniforms),this.uniformsGroups=LD(e.uniformsGroups),this.defines=Object.assign({},e.defines),this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.fog=e.fog,this.lights=e.lights,this.clipping=e.clipping,this.extensions=Object.assign({},e.extensions),this.glslVersion=e.glslVersion,this.defaultAttributeValues=Object.assign({},e.defaultAttributeValues),this.index0AttributeName=e.index0AttributeName,this.uniformsNeedUpdate=e.uniformsNeedUpdate,this}toJSON(e){let t=super.toJSON(e);t.glslVersion=this.glslVersion,t.uniforms={};for(let n in this.uniforms){let r=this.uniforms[n].value;r&&r.isTexture?t.uniforms[n]={type:`t`,value:r.toJSON(e).uuid}:r&&r.isColor?t.uniforms[n]={type:`c`,value:r.getHex()}:r&&r.isVector2?t.uniforms[n]={type:`v2`,value:r.toArray()}:r&&r.isVector3?t.uniforms[n]={type:`v3`,value:r.toArray()}:r&&r.isVector4?t.uniforms[n]={type:`v4`,value:r.toArray()}:r&&r.isMatrix3?t.uniforms[n]={type:`m3`,value:r.toArray()}:r&&r.isMatrix4?t.uniforms[n]={type:`m4`,value:r.toArray()}:t.uniforms[n]={value:r}}Object.keys(this.defines).length>0&&(t.defines=this.defines),t.vertexShader=this.vertexShader,t.fragmentShader=this.fragmentShader,t.lights=this.lights,t.clipping=this.clipping;let n={};for(let e in this.extensions)this.extensions[e]===!0&&(n[e]=!0);return Object.keys(n).length>0&&(t.extensions=n),t}fromJSON(e,t){if(super.fromJSON(e,t),e.uniforms!==void 0)for(let n in e.uniforms){let r=e.uniforms[n];switch(this.uniforms[n]={},r.type){case`t`:this.uniforms[n].value=t[r.value]||null;break;case`c`:this.uniforms[n].value=new QT().setHex(r.value);break;case`v2`:this.uniforms[n].value=new Y().fromArray(r.value);break;case`v3`:this.uniforms[n].value=new X().fromArray(r.value);break;case`v4`:this.uniforms[n].value=new fT().fromArray(r.value);break;case`m3`:this.uniforms[n].value=new Z().fromArray(r.value);break;case`m4`:this.uniforms[n].value=new _T().fromArray(r.value);break;default:this.uniforms[n].value=r.value}}if(e.defines!==void 0&&(this.defines=e.defines),e.vertexShader!==void 0&&(this.vertexShader=e.vertexShader),e.fragmentShader!==void 0&&(this.fragmentShader=e.fragmentShader),e.glslVersion!==void 0&&(this.glslVersion=e.glslVersion),e.extensions!==void 0)for(let t in e.extensions)this.extensions[t]=e.extensions[t];return e.lights!==void 0&&(this.lights=e.lights),e.clipping!==void 0&&(this.clipping=e.clipping),this}},UD=class extends HD{constructor(e){super(e),this.isRawShaderMaterial=!0,this.type=`RawShaderMaterial`}},WD=class extends eD{constructor(e){super(),this.isMeshDepthMaterial=!0,this.type=`MeshDepthMaterial`,this.depthPacking=yw,this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.wireframe=!1,this.wireframeLinewidth=1,this.setValues(e)}copy(e){return super.copy(e),this.depthPacking=e.depthPacking,this.map=e.map,this.alphaMap=e.alphaMap,this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this}},GD=class extends eD{constructor(e){super(),this.isMeshDistanceMaterial=!0,this.type=`MeshDistanceMaterial`,this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.setValues(e)}copy(e){return super.copy(e),this.map=e.map,this.alphaMap=e.alphaMap,this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this}};function KD(e,t){return!e||e.constructor===t?e:typeof t.BYTES_PER_ELEMENT==`number`?new t(e):Array.prototype.slice.call(e)}function qD(e){return e!==void 0&&e.inTangents!==void 0&&e.outTangents!==void 0}var JD=class{constructor(e,t,n,r){this.parameterPositions=e,this._cachedIndex=0,this.resultBuffer=r===void 0?new t.constructor(n):r,this.sampleValues=t,this.valueSize=n,this.settings=null,this.DefaultSettings_={}}evaluate(e){let t=this.parameterPositions,n=this._cachedIndex,r=t[n],i=t[n-1];validate_interval:{seek:{let a;linear_scan:{forward_scan:if(!(e<r)){for(let a=n+2;;){if(r===void 0){if(e<i)break forward_scan;return n=t.length,this._cachedIndex=n,this.copySampleValue_(n-1)}if(n===a)break;if(i=r,r=t[++n],e<r)break seek}a=t.length;break linear_scan}if(!(e>=i)){let o=t[1];e<o&&(n=2,i=o);for(let a=n-2;;){if(i===void 0)return this._cachedIndex=0,this.copySampleValue_(0);if(n===a)break;if(r=i,i=t[--n-1],e>=i)break seek}a=n,n=0;break linear_scan}break validate_interval}for(;n<a;){let r=n+a>>>1;e<t[r]?a=r:n=r+1}if(r=t[n],i=t[n-1],i===void 0)return this._cachedIndex=0,this.copySampleValue_(0);if(r===void 0)return n=t.length,this._cachedIndex=n,this.copySampleValue_(n-1)}this._cachedIndex=n,this.intervalChanged_(n,i,r)}return this.interpolate_(n,i,e,r)}getSettings_(){return this.settings||this.DefaultSettings_}copySampleValue_(e){let t=this.resultBuffer,n=this.sampleValues,r=this.valueSize,i=e*r;for(let e=0;e!==r;++e)t[e]=n[i+e];return t}interpolate_(){throw Error(`THREE.Interpolant: Call to abstract method.`)}intervalChanged_(){}},YD=class extends JD{constructor(e,t,n,r){super(e,t,n,r),this._weightPrev=-0,this._offsetPrev=-0,this._weightNext=-0,this._offsetNext=-0,this.DefaultSettings_={endingStart:gw,endingEnd:gw}}intervalChanged_(e,t,n){let r=this.parameterPositions,i=e-2,a=e+1,o=r[i],s=r[a];if(o===void 0)switch(this.getSettings_().endingStart){case _w:i=e,o=2*t-n;break;case vw:i=r.length-2,o=t+r[i]-r[i+1];break;default:i=e,o=n}if(s===void 0)switch(this.getSettings_().endingEnd){case _w:a=e,s=2*n-t;break;case vw:a=1,s=n+r[1]-r[0];break;default:a=e-1,s=t}let c=(n-t)*.5,l=this.valueSize;this._weightPrev=c/(t-o),this._weightNext=c/(s-n),this._offsetPrev=i*l,this._offsetNext=a*l}interpolate_(e,t,n,r){let i=this.resultBuffer,a=this.sampleValues,o=this.valueSize,s=e*o,c=s-o,l=this._offsetPrev,u=this._offsetNext,d=this._weightPrev,f=this._weightNext,p=(n-t)/(r-t),m=p*p,h=m*p,g=-d*h+2*d*m-d*p,_=(1+d)*h+(-1.5-2*d)*m+(-.5+d)*p+1,v=(-1-f)*h+(1.5+f)*m+.5*p,y=f*h-f*m;for(let e=0;e!==o;++e)i[e]=g*a[l+e]+_*a[c+e]+v*a[s+e]+y*a[u+e];return i}},XD=class extends JD{constructor(e,t,n,r){super(e,t,n,r)}interpolate_(e,t,n,r){let i=this.resultBuffer,a=this.sampleValues,o=this.valueSize,s=e*o,c=s-o,l=(n-t)/(r-t),u=1-l;for(let e=0;e!==o;++e)i[e]=a[c+e]*u+a[s+e]*l;return i}},ZD=class extends JD{constructor(e,t,n,r){super(e,t,n,r)}interpolate_(e){return this.copySampleValue_(e-1)}},QD=class extends JD{interpolate_(e,t,n,r){let i=this.resultBuffer,a=this.sampleValues,o=this.valueSize,s=e*o,c=s-o,l=this.inTangents,u=this.outTangents;if(!l||!u){let e=(n-t)/(r-t),l=1-e;for(let t=0;t!==o;++t)i[t]=a[c+t]*l+a[s+t]*e;return i}let d=o*2,f=e-1;for(let p=0;p!==o;++p){let o=a[c+p],m=a[s+p],h=f*d+p*2,g=u[h],_=u[h+1],v=e*d+p*2,y=l[v],b=l[v+1],x=tO(n,t,g,y,r);i[p]=$D(x,o,_,b,m)}return i}};function $D(e,t,n,r,i){let a=1-e;return a*a*a*t+3*a*a*e*n+3*a*e*e*r+e*e*e*i}function eO(e,t,n,r,i){let a=1-e;return 3*a*a*(n-t)+6*a*e*(r-n)+3*e*e*(i-r)}function tO(e,t,n,r,i){let a=(e-t)/(i-t);for(let o=0;o<8;o++){let o=$D(a,t,n,r,i)-e;if(Math.abs(o)<1e-10)break;let s=eO(a,t,n,r,i);if(Math.abs(s)<1e-10)break;a=Math.max(0,Math.min(1,a-o/s))}return a}var nO=class{constructor(e,t,n,r){if(e===void 0)throw Error(`THREE.KeyframeTrack: track name is undefined`);if(t===void 0||t.length===0)throw Error(`THREE.KeyframeTrack: no keyframes in track named `+e);this.name=e,this.times=KD(t,this.TimeBufferType),this.values=KD(n,this.ValueBufferType),this.setInterpolation(r||this.DefaultInterpolation)}static toJSON(e){let t=e.constructor,n;if(t.toJSON!==this.toJSON)n=t.toJSON(e);else{n={name:e.name,times:KD(e.times,Array),values:KD(e.values,Array)};let t=e.getInterpolation();t!==e.DefaultInterpolation&&(n.interpolation=t),qD(e.settings)&&(n.settings={inTangents:KD(e.settings.inTangents,Array),outTangents:KD(e.settings.outTangents,Array)})}return n.type=e.ValueTypeName,n}InterpolantFactoryMethodDiscrete(e){return new ZD(this.times,this.values,this.getValueSize(),e)}InterpolantFactoryMethodLinear(e){return new XD(this.times,this.values,this.getValueSize(),e)}InterpolantFactoryMethodSmooth(e){return new YD(this.times,this.values,this.getValueSize(),e)}InterpolantFactoryMethodBezier(e){let t=new QD(this.times,this.values,this.getValueSize(),e);return this.settings&&(t.inTangents=this.settings.inTangents,t.outTangents=this.settings.outTangents),t}setInterpolation(e){let t;switch(e){case fw:t=this.InterpolantFactoryMethodDiscrete;break;case pw:t=this.InterpolantFactoryMethodLinear;break;case mw:t=this.InterpolantFactoryMethodSmooth;break;case hw:t=this.InterpolantFactoryMethodBezier}if(t===void 0){let t=`unsupported interpolation for `+this.ValueTypeName+` keyframe track named `+this.name;if(this.createInterpolant===void 0){if(e!==this.DefaultInterpolation)this.setInterpolation(this.DefaultInterpolation);else throw Error(t)}return q(`KeyframeTrack:`,t),this}return this.createInterpolant=t,this}getInterpolation(){switch(this.createInterpolant){case this.InterpolantFactoryMethodDiscrete:return fw;case this.InterpolantFactoryMethodLinear:return pw;case this.InterpolantFactoryMethodSmooth:return mw;case this.InterpolantFactoryMethodBezier:return hw}}getValueSize(){return this.values.length/this.times.length}shift(e){if(e!==0){let t=this.times;for(let n=0,r=t.length;n!==r;++n)t[n]+=e}return this}scale(e){if(e!==1){let t=this.times;for(let n=0,r=t.length;n!==r;++n)t[n]*=e;qD(this.settings)&&(rO(this.settings.inTangents,e),rO(this.settings.outTangents,e))}return this}trim(e,t){let n=this.times,r=n.length,i=0,a=r-1;for(;i!==r&&n[i]<e;)++i;for(;a!==-1&&n[a]>t;)--a;if(++a,i!==0||a!==r){i>=a&&(a=Math.max(a,1),i=a-1);let e=this.getValueSize();this.times=n.slice(i,a),this.values=this.values.slice(i*e,a*e)}return this}validate(){let e=!0,t=this.getValueSize();t-Math.floor(t)!==0&&(J(`KeyframeTrack: Invalid value size in track.`,this),e=!1);let n=this.times,r=this.values,i=n.length;i===0&&(J(`KeyframeTrack: Track is empty.`,this),e=!1);let a=null;for(let t=0;t!==i;t++){let r=n[t];if(typeof r==`number`&&isNaN(r)){J(`KeyframeTrack: Time is not a valid number.`,this,t,r),e=!1;break}if(a!==null&&a>r){J(`KeyframeTrack: Out of order keys.`,this,t,r,a),e=!1;break}a=r}if(r!==void 0&&kw(r))for(let t=0,n=r.length;t!==n;++t){let n=r[t];if(isNaN(n)){J(`KeyframeTrack: Value is not a valid number.`,this,t,n),e=!1;break}}return e}optimize(){let e=this.times.slice(),t=this.values.slice(),n=this.getValueSize(),r=this.getInterpolation()===mw,i=e.length-1,a=1;for(let o=1;o<i;++o){let i=!1,s=e[o];if(s!==e[o+1]&&(o!==1||s!==e[0])){if(r)i=!0;else{let e=o*n,r=e-n,a=e+n;for(let o=0;o!==n;++o){let n=t[e+o];if(n!==t[r+o]||n!==t[a+o]){i=!0;break}}}}if(i){if(o!==a){e[a]=e[o];let r=o*n,i=a*n;for(let e=0;e!==n;++e)t[i+e]=t[r+e]}++a}}if(i>0){e[a]=e[i];for(let e=i*n,r=a*n,o=0;o!==n;++o)t[r+o]=t[e+o];++a}return a===e.length?(this.times=e,this.values=t):(this.times=e.slice(0,a),this.values=t.slice(0,a*n)),this}clone(){let e=this.times.slice(),t=this.values.slice(),n=this.constructor,r=new n(this.name,e,t);return r.createInterpolant=this.createInterpolant,qD(this.settings)&&(r.settings={inTangents:this.settings.inTangents.slice(),outTangents:this.settings.outTangents.slice()}),r}};function rO(e,t){for(let n=0,r=e.length;n!==r;n+=2)e[n]*=t}nO.prototype.ValueTypeName=``,nO.prototype.TimeBufferType=Float32Array,nO.prototype.ValueBufferType=Float32Array,nO.prototype.DefaultInterpolation=pw;var iO=class extends nO{constructor(e,t,n){super(e,t,n)}};iO.prototype.ValueTypeName=`bool`,iO.prototype.ValueBufferType=Array,iO.prototype.DefaultInterpolation=fw,iO.prototype.InterpolantFactoryMethodLinear=void 0,iO.prototype.InterpolantFactoryMethodSmooth=void 0;var aO=class extends nO{constructor(e,t,n,r){super(e,t,n,r)}};aO.prototype.ValueTypeName=`color`;var oO=class extends nO{constructor(e,t,n,r){super(e,t,n,r)}};oO.prototype.ValueTypeName=`number`;var sO=class extends JD{constructor(e,t,n,r){super(e,t,n,r)}interpolate_(e,t,n,r){let i=this.resultBuffer,a=this.sampleValues,o=this.valueSize,s=(n-t)/(r-t),c=e*o;for(let e=c+o;c!==e;c+=4)Jw.slerpFlat(i,0,a,c-o,a,c,s);return i}},cO=class extends nO{constructor(e,t,n,r){super(e,t,n,r)}InterpolantFactoryMethodLinear(e){return new sO(this.times,this.values,this.getValueSize(),e)}};cO.prototype.ValueTypeName=`quaternion`,cO.prototype.InterpolantFactoryMethodSmooth=void 0;var lO=class extends nO{constructor(e,t,n){super(e,t,n)}};lO.prototype.ValueTypeName=`string`,lO.prototype.ValueBufferType=Array,lO.prototype.DefaultInterpolation=fw,lO.prototype.InterpolantFactoryMethodLinear=void 0,lO.prototype.InterpolantFactoryMethodSmooth=void 0;var uO=class extends nO{constructor(e,t,n,r){super(e,t,n,r)}};uO.prototype.ValueTypeName=`vector`;var dO=/*@__PURE__*/ new X,fO=/*@__PURE__*/ new Jw,pO=/*@__PURE__*/ new X,mO=class extends WT{constructor(){super(),this.isCamera=!0,this.type=`Camera`,this.matrixWorldInverse=new _T,this.projectionMatrix=new _T,this.projectionMatrixInverse=new _T,this.coordinateSystem=Dw,this._reversedDepth=!1}get reversedDepth(){return this._reversedDepth}copy(e,t){return super.copy(e,t),this.matrixWorldInverse.copy(e.matrixWorldInverse),this.projectionMatrix.copy(e.projectionMatrix),this.projectionMatrixInverse.copy(e.projectionMatrixInverse),this.coordinateSystem=e.coordinateSystem,this}getWorldDirection(e){return super.getWorldDirection(e).negate()}updateMatrixWorld(e){super.updateMatrixWorld(e),this.matrixWorld.decompose(dO,fO,pO),pO.x===1&&pO.y===1&&pO.z===1?this.matrixWorldInverse.copy(this.matrixWorld).invert():this.matrixWorldInverse.compose(dO,fO,pO.set(1,1,1)).invert()}updateWorldMatrix(e,t,n=!1){super.updateWorldMatrix(e,t,n),this.matrixWorld.decompose(dO,fO,pO),pO.x===1&&pO.y===1&&pO.z===1?this.matrixWorldInverse.copy(this.matrixWorld).invert():this.matrixWorldInverse.compose(dO,fO,pO.set(1,1,1)).invert()}clone(){return new this.constructor().copy(this)}},hO=/*@__PURE__*/ new X,gO=/*@__PURE__*/ new Y,_O=/*@__PURE__*/ new Y,vO=class extends mO{constructor(e=50,t=1,n=.1,r=2e3){super(),this.isPerspectiveCamera=!0,this.type=`PerspectiveCamera`,this.fov=e,this.zoom=1,this.near=n,this.far=r,this.focus=10,this.aspect=t,this.view=null,this.filmGauge=35,this.filmOffset=0,this.updateProjectionMatrix()}copy(e,t){return super.copy(e,t),this.fov=e.fov,this.zoom=e.zoom,this.near=e.near,this.far=e.far,this.focus=e.focus,this.aspect=e.aspect,this.view=e.view===null?null:Object.assign({},e.view),this.filmGauge=e.filmGauge,this.filmOffset=e.filmOffset,this}setFocalLength(e){let t=.5*this.getFilmHeight()/e;this.fov=Vw*2*Math.atan(t),this.updateProjectionMatrix()}getFocalLength(){let e=Math.tan(Bw*.5*this.fov);return .5*this.getFilmHeight()/e}getEffectiveFOV(){return Vw*2*Math.atan(Math.tan(Bw*.5*this.fov)/this.zoom)}getFilmWidth(){return this.filmGauge*Math.min(this.aspect,1)}getFilmHeight(){return this.filmGauge/Math.max(this.aspect,1)}getViewBounds(e,t,n){hO.set(-1,-1,.5).applyMatrix4(this.projectionMatrixInverse),t.set(hO.x,hO.y).multiplyScalar(-e/hO.z),hO.set(1,1,.5).applyMatrix4(this.projectionMatrixInverse),n.set(hO.x,hO.y).multiplyScalar(-e/hO.z)}getViewSize(e,t){return this.getViewBounds(e,gO,_O),t.subVectors(_O,gO)}setViewOffset(e,t,n,r,i,a){this.aspect=e/t,this.view===null&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1}),this.view.enabled=!0,this.view.fullWidth=e,this.view.fullHeight=t,this.view.offsetX=n,this.view.offsetY=r,this.view.width=i,this.view.height=a,this.updateProjectionMatrix()}clearViewOffset(){this.view!==null&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){let e=this.near,t=e*Math.tan(Bw*.5*this.fov)/this.zoom,n=2*t,r=this.aspect*n,i=-.5*r,a=this.view;if(this.view!==null&&this.view.enabled){let e=a.fullWidth,o=a.fullHeight;i+=a.offsetX*r/e,t-=a.offsetY*n/o,r*=a.width/e,n*=a.height/o}let o=this.filmOffset;o!==0&&(i+=e*o/this.getFilmWidth()),this.projectionMatrix.makePerspective(i,i+r,t,t-n,e,this.far,this.coordinateSystem,this.reversedDepth),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(e){let t=super.toJSON(e);return t.object.fov=this.fov,t.object.zoom=this.zoom,t.object.near=this.near,t.object.far=this.far,t.object.focus=this.focus,t.object.aspect=this.aspect,this.view!==null&&(t.object.view=Object.assign({},this.view)),t.object.filmGauge=this.filmGauge,t.object.filmOffset=this.filmOffset,t}},yO=class extends mO{constructor(e=-1,t=1,n=1,r=-1,i=.1,a=2e3){super(),this.isOrthographicCamera=!0,this.type=`OrthographicCamera`,this.zoom=1,this.view=null,this.left=e,this.right=t,this.top=n,this.bottom=r,this.near=i,this.far=a,this.updateProjectionMatrix()}copy(e,t){return super.copy(e,t),this.left=e.left,this.right=e.right,this.top=e.top,this.bottom=e.bottom,this.near=e.near,this.far=e.far,this.zoom=e.zoom,this.view=e.view===null?null:Object.assign({},e.view),this}setViewOffset(e,t,n,r,i,a){this.view===null&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1}),this.view.enabled=!0,this.view.fullWidth=e,this.view.fullHeight=t,this.view.offsetX=n,this.view.offsetY=r,this.view.width=i,this.view.height=a,this.updateProjectionMatrix()}clearViewOffset(){this.view!==null&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){let e=(this.right-this.left)/(2*this.zoom),t=(this.top-this.bottom)/(2*this.zoom),n=(this.right+this.left)/2,r=(this.top+this.bottom)/2,i=n-e,a=n+e,o=r+t,s=r-t;if(this.view!==null&&this.view.enabled){let e=(this.right-this.left)/this.view.fullWidth/this.zoom,t=(this.top-this.bottom)/this.view.fullHeight/this.zoom;i+=e*this.view.offsetX,a=i+e*this.view.width,o-=t*this.view.offsetY,s=o-t*this.view.height}this.projectionMatrix.makeOrthographic(i,a,o,s,this.near,this.far,this.coordinateSystem,this.reversedDepth),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(e){let t=super.toJSON(e);return t.object.zoom=this.zoom,t.object.left=this.left,t.object.right=this.right,t.object.top=this.top,t.object.bottom=this.bottom,t.object.near=this.near,t.object.far=this.far,this.view!==null&&(t.object.view=Object.assign({},this.view)),t}},bO=-90,xO=1,SO=class extends WT{constructor(e,t,n){super(),this.type=`CubeCamera`,this.renderTarget=n,this.coordinateSystem=null,this.activeMipmapLevel=0;let r=new vO(bO,xO,e,t);r.layers=this.layers,this.add(r);let i=new vO(bO,xO,e,t);i.layers=this.layers,this.add(i);let a=new vO(bO,xO,e,t);a.layers=this.layers,this.add(a);let o=new vO(bO,xO,e,t);o.layers=this.layers,this.add(o);let s=new vO(bO,xO,e,t);s.layers=this.layers,this.add(s);let c=new vO(bO,xO,e,t);c.layers=this.layers,this.add(c)}updateCoordinateSystem(){let e=this.coordinateSystem,t=this.children.concat(),[n,r,i,a,o,s]=t;for(let e of t)this.remove(e);if(e===2e3)n.up.set(0,1,0),n.lookAt(1,0,0),r.up.set(0,1,0),r.lookAt(-1,0,0),i.up.set(0,0,-1),i.lookAt(0,1,0),a.up.set(0,0,1),a.lookAt(0,-1,0),o.up.set(0,1,0),o.lookAt(0,0,1),s.up.set(0,1,0),s.lookAt(0,0,-1);else if(e===2001)n.up.set(0,-1,0),n.lookAt(-1,0,0),r.up.set(0,-1,0),r.lookAt(1,0,0),i.up.set(0,0,1),i.lookAt(0,1,0),a.up.set(0,0,-1),a.lookAt(0,-1,0),o.up.set(0,-1,0),o.lookAt(0,0,1),s.up.set(0,-1,0),s.lookAt(0,0,-1);else throw Error(`THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: `+e);for(let e of t)this.add(e),e.updateMatrixWorld()}update(e,t){this.parent===null&&this.updateMatrixWorld();let{renderTarget:n,activeMipmapLevel:r}=this;this.coordinateSystem!==e.coordinateSystem&&(this.coordinateSystem=e.coordinateSystem,this.updateCoordinateSystem());let[i,a,o,s,c,l]=this.children,u=e.getRenderTarget(),d=e.getActiveCubeFace(),f=e.getActiveMipmapLevel(),p=e.xr.enabled;e.xr.enabled=!1;let m=n.texture.generateMipmaps;n.texture.generateMipmaps=!1;let h=!1;h=e.isWebGLRenderer===!0?e.state.buffers.depth.getReversed():e.reversedDepthBuffer,e.setRenderTarget(n,0,r),h&&e.autoClear===!1&&e.clearDepth(),e.render(t,i),e.setRenderTarget(n,1,r),h&&e.autoClear===!1&&e.clearDepth(),e.render(t,a),e.setRenderTarget(n,2,r),h&&e.autoClear===!1&&e.clearDepth(),e.render(t,o),e.setRenderTarget(n,3,r),h&&e.autoClear===!1&&e.clearDepth(),e.render(t,s),e.setRenderTarget(n,4,r),h&&e.autoClear===!1&&e.clearDepth(),e.render(t,c),n.texture.generateMipmaps=m,e.setRenderTarget(n,5,r),h&&e.autoClear===!1&&e.clearDepth(),e.render(t,l),e.setRenderTarget(u,d,f),e.xr.enabled=p,n.texture.needsPMREMUpdate=!0}},CO=class extends vO{constructor(e=[]){super(),this.isArrayCamera=!0,this.isMultiViewCamera=!1,this.cameras=e}},wO=`\\[\\]\\.:\\/`,TO=/* @__PURE__ */ RegExp(`[\\[\\]\\.:\\/]`,`g`),EO=`[^\\[\\]\\.:\\/]`,DO=`[^`+wO.replace(`\\.`,``)+`]`,OO=/*@__PURE__*/ `((?:WC+[\\/:])*)`.replace(`WC`,EO),kO=/*@__PURE__*/ `(WCOD+)?`.replace(`WCOD`,DO),AO=/*@__PURE__*/ `(?:\\.(WC+)(?:\\[(.+)\\])?)?`.replace(`WC`,EO),jO=/*@__PURE__*/ `\\.(WC+)(?:\\[(.+)\\])?`.replace(`WC`,EO),MO=RegExp(`^`+OO+kO+AO+jO+`$`),NO=[`material`,`materials`,`bones`,`map`],PO=class{constructor(e,t,n){let r=n||FO.parseTrackName(t);this._targetGroup=e,this._bindings=e.subscribe_(t,r)}getValue(e,t){this.bind();let n=this._targetGroup.nCachedObjects_,r=this._bindings[n];r!==void 0&&r.getValue(e,t)}setValue(e,t){let n=this._bindings;for(let r=this._targetGroup.nCachedObjects_,i=n.length;r!==i;++r)n[r].setValue(e,t)}bind(){let e=this._bindings;for(let t=this._targetGroup.nCachedObjects_,n=e.length;t!==n;++t)e[t].bind()}unbind(){let e=this._bindings;for(let t=this._targetGroup.nCachedObjects_,n=e.length;t!==n;++t)e[t].unbind()}},FO=class e{constructor(t,n,r){this.path=n,this.parsedPath=r||e.parseTrackName(n),this.node=e.findNode(t,this.parsedPath.nodeName),this.rootNode=t,this.getValue=this._getValue_unbound,this.setValue=this._setValue_unbound}static create(t,n,r){return t&&t.isAnimationObjectGroup?new e.Composite(t,n,r):new e(t,n,r)}static sanitizeNodeName(e){return e.replace(/\s/g,`_`).replace(TO,``)}static parseTrackName(e){let t=MO.exec(e);if(t===null)throw Error(`THREE.PropertyBinding: Cannot parse trackName: `+e);let n={nodeName:t[2],objectName:t[3],objectIndex:t[4],propertyName:t[5],propertyIndex:t[6]},r=n.nodeName&&n.nodeName.lastIndexOf(`.`);if(r!==void 0&&r!==-1){let e=n.nodeName.substring(r+1);NO.indexOf(e)!==-1&&(n.nodeName=n.nodeName.substring(0,r),n.objectName=e)}if(n.propertyName===null||n.propertyName.length===0)throw Error(`THREE.PropertyBinding: can not parse propertyName from trackName: `+e);return n}static findNode(e,t){if(t===void 0||t===``||t===`.`||t===-1||t===e.name||t===e.uuid)return e;if(e.skeleton){let n=e.skeleton.getBoneByName(t);if(n!==void 0)return n}if(e.children){let n=function(e){for(let r=0;r<e.length;r++){let i=e[r];if(i.name===t||i.uuid===t)return i;let a=n(i.children);if(a)return a}return null},r=n(e.children);if(r)return r}return null}_getValue_unavailable(){}_setValue_unavailable(){}_getValue_direct(e,t){e[t]=this.targetObject[this.propertyName]}_getValue_array(e,t){let n=this.resolvedProperty;for(let r=0,i=n.length;r!==i;++r)e[t++]=n[r]}_getValue_arrayElement(e,t){e[t]=this.resolvedProperty[this.propertyIndex]}_getValue_toArray(e,t){this.resolvedProperty.toArray(e,t)}_setValue_direct(e,t){this.targetObject[this.propertyName]=e[t]}_setValue_direct_setNeedsUpdate(e,t){this.targetObject[this.propertyName]=e[t],this.targetObject.needsUpdate=!0}_setValue_direct_setMatrixWorldNeedsUpdate(e,t){this.targetObject[this.propertyName]=e[t],this.targetObject.matrixWorldNeedsUpdate=!0}_setValue_array(e,t){let n=this.resolvedProperty;for(let r=0,i=n.length;r!==i;++r)n[r]=e[t++]}_setValue_array_setNeedsUpdate(e,t){let n=this.resolvedProperty;for(let r=0,i=n.length;r!==i;++r)n[r]=e[t++];this.targetObject.needsUpdate=!0}_setValue_array_setMatrixWorldNeedsUpdate(e,t){let n=this.resolvedProperty;for(let r=0,i=n.length;r!==i;++r)n[r]=e[t++];this.targetObject.matrixWorldNeedsUpdate=!0}_setValue_arrayElement(e,t){this.resolvedProperty[this.propertyIndex]=e[t]}_setValue_arrayElement_setNeedsUpdate(e,t){this.resolvedProperty[this.propertyIndex]=e[t],this.targetObject.needsUpdate=!0}_setValue_arrayElement_setMatrixWorldNeedsUpdate(e,t){this.resolvedProperty[this.propertyIndex]=e[t],this.targetObject.matrixWorldNeedsUpdate=!0}_setValue_fromArray(e,t){this.resolvedProperty.fromArray(e,t)}_setValue_fromArray_setNeedsUpdate(e,t){this.resolvedProperty.fromArray(e,t),this.targetObject.needsUpdate=!0}_setValue_fromArray_setMatrixWorldNeedsUpdate(e,t){this.resolvedProperty.fromArray(e,t),this.targetObject.matrixWorldNeedsUpdate=!0}_getValue_unbound(e,t){this.bind(),this.getValue(e,t)}_setValue_unbound(e,t){this.bind(),this.setValue(e,t)}bind(){let t=this.node,n=this.parsedPath,r=n.objectName,i=n.propertyName,a=n.propertyIndex;if(t||(t=e.findNode(this.rootNode,n.nodeName),this.node=t),this.getValue=this._getValue_unavailable,this.setValue=this._setValue_unavailable,!t){q(`PropertyBinding: No target node found for track: `+this.path+`.`);return}if(r){let e=n.objectIndex;switch(r){case`materials`:if(!t.material){J(`PropertyBinding: Can not bind to material as node does not have a material.`,this);return}if(!t.material.materials){J(`PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.`,this);return}t=t.material.materials;break;case`bones`:if(!t.skeleton){J(`PropertyBinding: Can not bind to bones as node does not have a skeleton.`,this);return}t=t.skeleton.bones;for(let n=0;n<t.length;n++)if(t[n].name===e){e=n;break}break;case`map`:if(`map`in t){t=t.map;break}if(!t.material){J(`PropertyBinding: Can not bind to material as node does not have a material.`,this);return}if(!t.material.map){J(`PropertyBinding: Can not bind to material.map as node.material does not have a map.`,this);return}t=t.material.map;break;default:if(t[r]===void 0){J(`PropertyBinding: Can not bind to objectName of node undefined.`,this);return}t=t[r]}if(e!==void 0){if(t[e]===void 0){J(`PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.`,this,t);return}t=t[e]}}let o=t[i];if(o===void 0){let e=n.nodeName;J(`PropertyBinding: Trying to update property for track: `+e+`.`+i+` but it wasn't found.`,t);return}let s=this.Versioning.None;this.targetObject=t,t.isMaterial===!0?s=this.Versioning.NeedsUpdate:t.isObject3D===!0&&(s=this.Versioning.MatrixWorldNeedsUpdate);let c=this.BindingType.Direct;if(a!==void 0){if(i===`morphTargetInfluences`){if(!t.geometry){J(`PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.`,this);return}if(!t.geometry.morphAttributes){J(`PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.`,this);return}t.morphTargetDictionary[a]!==void 0&&(a=t.morphTargetDictionary[a])}c=this.BindingType.ArrayElement,this.resolvedProperty=o,this.propertyIndex=a}else o.fromArray!==void 0&&o.toArray!==void 0?(c=this.BindingType.HasFromToArray,this.resolvedProperty=o):Array.isArray(o)?(c=this.BindingType.EntireArray,this.resolvedProperty=o):this.propertyName=i;this.getValue=this.GetterByBindingType[c],this.setValue=this.SetterByBindingTypeAndVersioning[c][s]}unbind(){this.node=null,this.getValue=this._getValue_unbound,this.setValue=this._setValue_unbound}};FO.Composite=PO,FO.prototype.BindingType={Direct:0,EntireArray:1,ArrayElement:2,HasFromToArray:3},FO.prototype.Versioning={None:0,NeedsUpdate:1,MatrixWorldNeedsUpdate:2},FO.prototype.GetterByBindingType=[FO.prototype._getValue_direct,FO.prototype._getValue_array,FO.prototype._getValue_arrayElement,FO.prototype._getValue_toArray],FO.prototype.SetterByBindingTypeAndVersioning=[[FO.prototype._setValue_direct,FO.prototype._setValue_direct_setNeedsUpdate,FO.prototype._setValue_direct_setMatrixWorldNeedsUpdate],[FO.prototype._setValue_array,FO.prototype._setValue_array_setNeedsUpdate,FO.prototype._setValue_array_setMatrixWorldNeedsUpdate],[FO.prototype._setValue_arrayElement,FO.prototype._setValue_arrayElement_setNeedsUpdate,FO.prototype._setValue_arrayElement_setMatrixWorldNeedsUpdate],[FO.prototype._setValue_fromArray,FO.prototype._setValue_fromArray_setNeedsUpdate,FO.prototype._setValue_fromArray_setMatrixWorldNeedsUpdate]],class e{static{e.prototype.isMatrix2=!0}constructor(e,t,n,r){this.elements=[1,0,0,1],e!==void 0&&this.set(e,t,n,r)}identity(){return this.set(1,0,0,1),this}fromArray(e,t=0){for(let n=0;n<4;n++)this.elements[n]=e[n+t];return this}set(e,t,n,r){let i=this.elements;return i[0]=e,i[2]=t,i[1]=n,i[3]=r,this}};function IO(e,t,n,r){let i=LO(r);switch(n){case bC:return e*t;case TC:return e*t/i.components*i.byteLength;case EC:return e*t/i.components*i.byteLength;case DC:return e*t*2/i.components*i.byteLength;case OC:return e*t*2/i.components*i.byteLength;case xC:return e*t*3/i.components*i.byteLength;case SC:return e*t*4/i.components*i.byteLength;case kC:return e*t*4/i.components*i.byteLength;case AC:case jC:return Math.floor((e+3)/4)*Math.floor((t+3)/4)*8;case MC:case NC:return Math.floor((e+3)/4)*Math.floor((t+3)/4)*16;case FC:case LC:return Math.max(e,16)*Math.max(t,8)/4;case PC:case IC:return Math.max(e,8)*Math.max(t,8)/2;case RC:case zC:case VC:case HC:return Math.floor((e+3)/4)*Math.floor((t+3)/4)*8;case BC:case UC:case WC:return Math.floor((e+3)/4)*Math.floor((t+3)/4)*16;case GC:return Math.floor((e+3)/4)*Math.floor((t+3)/4)*16;case KC:return Math.floor((e+4)/5)*Math.floor((t+3)/4)*16;case qC:return Math.floor((e+4)/5)*Math.floor((t+4)/5)*16;case JC:return Math.floor((e+5)/6)*Math.floor((t+4)/5)*16;case YC:return Math.floor((e+5)/6)*Math.floor((t+5)/6)*16;case XC:return Math.floor((e+7)/8)*Math.floor((t+4)/5)*16;case ZC:return Math.floor((e+7)/8)*Math.floor((t+5)/6)*16;case QC:return Math.floor((e+7)/8)*Math.floor((t+7)/8)*16;case $C:return Math.floor((e+9)/10)*Math.floor((t+4)/5)*16;case ew:return Math.floor((e+9)/10)*Math.floor((t+5)/6)*16;case tw:return Math.floor((e+9)/10)*Math.floor((t+7)/8)*16;case nw:return Math.floor((e+9)/10)*Math.floor((t+9)/10)*16;case rw:return Math.floor((e+11)/12)*Math.floor((t+9)/10)*16;case iw:return Math.floor((e+11)/12)*Math.floor((t+11)/12)*16;case aw:case ow:case sw:return Math.ceil(e/4)*Math.ceil(t/4)*16;case cw:case lw:return Math.ceil(e/4)*Math.ceil(t/4)*8;case uw:case dw:return Math.ceil(e/4)*Math.ceil(t/4)*16}throw Error(`Unable to determine texture byte length for ${n} format.`)}function LO(e){switch(e){case sC:case cC:return{byteLength:1,components:1};case uC:case lC:case mC:return{byteLength:2,components:1};case hC:case gC:return{byteLength:2,components:4};case fC:case dC:case pC:return{byteLength:4,components:1};case vC:case yC:return{byteLength:4,components:3}}throw Error(`THREE.TextureUtils: Unknown texture type ${e}.`)}typeof __THREE_DEVTOOLS__<`u`&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent(`register`,{detail:{revision:`186`}})),typeof window<`u`&&(window.__THREE__?q(`WARNING: Multiple instances of Three.js being imported.`):window.__THREE__=`186`);function RO(){let e=null,t=!1,n=null,r=null;function i(t,a){r=e.requestAnimationFrame(i),n(t,a)}return{start:function(){t!==!0&&n!==null&&e!==null&&(r=e.requestAnimationFrame(i),t=!0)},stop:function(){e!==null&&e.cancelAnimationFrame(r),t=!1},setAnimationLoop:function(e){n=e},setContext:function(t){e=t}}}function zO(e){let t=/* @__PURE__ */ new WeakMap;function n(t,n){let r=t.array,i=t.usage,a=r.byteLength,o=e.createBuffer();e.bindBuffer(n,o),e.bufferData(n,r,i),t.onUploadCallback();let s;if(r instanceof Float32Array)s=e.FLOAT;else if(typeof Float16Array<`u`&&r instanceof Float16Array)s=e.HALF_FLOAT;else if(r instanceof Uint16Array)s=t.isFloat16BufferAttribute?e.HALF_FLOAT:e.UNSIGNED_SHORT;else if(r instanceof Int16Array)s=e.SHORT;else if(r instanceof Uint32Array)s=e.UNSIGNED_INT;else if(r instanceof Int32Array)s=e.INT;else if(r instanceof Int8Array)s=e.BYTE;else if(r instanceof Uint8Array)s=e.UNSIGNED_BYTE;else if(r instanceof Uint8ClampedArray)s=e.UNSIGNED_BYTE;else throw Error(`THREE.WebGLAttributes: Unsupported buffer data format: `+r);return{buffer:o,type:s,bytesPerElement:r.BYTES_PER_ELEMENT,version:t.version,size:a}}function r(t,n,r){let i=n.array,a=n.updateRanges;if(e.bindBuffer(r,t),a.length===0)e.bufferSubData(r,0,i);else{a.sort((e,t)=>e.start-t.start);let t=0;for(let e=1;e<a.length;e++){let n=a[t],r=a[e];r.start<=n.start+n.count+1?n.count=Math.max(n.count,r.start+r.count-n.start):(++t,a[t]=r)}a.length=t+1;for(let t=0,n=a.length;t<n;t++){let n=a[t];e.bufferSubData(r,n.start*i.BYTES_PER_ELEMENT,i,n.start,n.count)}n.clearUpdateRanges()}n.onUploadCallback()}function i(e){return e.isInterleavedBufferAttribute&&(e=e.data),t.get(e)}function a(n){n.isInterleavedBufferAttribute&&(n=n.data);let r=t.get(n);r&&(e.deleteBuffer(r.buffer),t.delete(n))}function o(e,i){if(e.isInterleavedBufferAttribute&&(e=e.data),e.isGLBufferAttribute){let n=t.get(e);(!n||n.version<e.version)&&t.set(e,{buffer:e.buffer,type:e.type,bytesPerElement:e.elementSize,version:e.version});return}let a=t.get(e);if(a===void 0)t.set(e,n(e,i));else if(a.version<e.version){if(a.size!==e.array.byteLength)throw Error(`THREE.WebGLAttributes: The size of the buffer attribute's array buffer does not match the original size. Resizing buffer attributes is not supported.`);r(a.buffer,e,i),a.version=e.version}}return{get:i,remove:a,update:o}}var Q={alphahash_fragment:`#ifdef USE_ALPHAHASH
|
|
8
8
|
if ( diffuseColor.a < getAlphaHashThreshold( vPosition ) ) discard;
|
|
9
9
|
#endif`,alphahash_pars_fragment:`#ifdef USE_ALPHAHASH
|
|
10
10
|
const float ALPHA_HASH_SCALE = 0.05;
|
|
@@ -3822,7 +3822,7 @@ void main() {
|
|
|
3822
3822
|
#include <tonemapping_fragment>
|
|
3823
3823
|
#include <colorspace_fragment>
|
|
3824
3824
|
#include <fog_fragment>
|
|
3825
|
-
}`},$={common:{diffuse:{value:/*@__PURE__*/ new xw(16777215)},opacity:{value:1},map:{value:null},mapTransform:{value:/*@__PURE__*/ new Z},alphaMap:{value:null},alphaMapTransform:{value:/*@__PURE__*/ new Z},alphaTest:{value:0}},specularmap:{specularMap:{value:null},specularMapTransform:{value:/*@__PURE__*/ new Z}},envmap:{envMap:{value:null},envMapRotation:{value:/*@__PURE__*/ new Z},reflectivity:{value:1},ior:{value:1.5},refractionRatio:{value:.98},dfgLUT:{value:null}},aomap:{aoMap:{value:null},aoMapIntensity:{value:1},aoMapTransform:{value:/*@__PURE__*/ new Z}},lightmap:{lightMap:{value:null},lightMapIntensity:{value:1},lightMapTransform:{value:/*@__PURE__*/ new Z}},bumpmap:{bumpMap:{value:null},bumpMapTransform:{value:/*@__PURE__*/ new Z},bumpScale:{value:1}},normalmap:{normalMap:{value:null},normalMapTransform:{value:/*@__PURE__*/ new Z},normalScale:{value:/*@__PURE__*/ new Y(1,1)}},displacementmap:{displacementMap:{value:null},displacementMapTransform:{value:/*@__PURE__*/ new Z},displacementScale:{value:1},displacementBias:{value:0}},emissivemap:{emissiveMap:{value:null},emissiveMapTransform:{value:/*@__PURE__*/ new Z}},metalnessmap:{metalnessMap:{value:null},metalnessMapTransform:{value:/*@__PURE__*/ new Z}},roughnessmap:{roughnessMap:{value:null},roughnessMapTransform:{value:/*@__PURE__*/ new Z}},gradientmap:{gradientMap:{value:null}},fog:{fogDensity:{value:25e-5},fogNear:{value:1},fogFar:{value:2e3},fogColor:{value:/*@__PURE__*/ new xw(16777215)}},lights:{ambientLightColor:{value:[]},lightProbe:{value:[]},sunLights:{value:[],properties:{direction:{},color:{}}},sunLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},sunShadowMatrix:{value:[]},sunShadowCascade:{value:[]},directionalLights:{value:[],properties:{direction:{},color:{}}},directionalLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},directionalShadowMatrix:{value:[]},spotLights:{value:[],properties:{color:{},position:{},direction:{},distance:{},coneCos:{},penumbraCos:{},decay:{}}},spotLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},spotLightMap:{value:[]},spotLightMatrix:{value:[]},pointLights:{value:[],properties:{color:{},position:{},decay:{},distance:{}}},pointLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{},shadowCameraNear:{},shadowCameraFar:{}}},pointShadowMatrix:{value:[]},hemisphereLights:{value:[],properties:{direction:{},skyColor:{},groundColor:{}}},rectAreaLights:{value:[],properties:{color:{},position:{},width:{},height:{}}},ltc_1:{value:null},ltc_2:{value:null},probesSH:{value:null},probesMin:{value:/*@__PURE__*/ new X},probesMax:{value:/*@__PURE__*/ new X},probesResolution:{value:/*@__PURE__*/ new X}},points:{diffuse:{value:/*@__PURE__*/ new xw(16777215)},opacity:{value:1},size:{value:1},scale:{value:1},map:{value:null},alphaMap:{value:null},alphaMapTransform:{value:/*@__PURE__*/ new Z},alphaTest:{value:0},uvTransform:{value:/*@__PURE__*/ new Z}},sprite:{diffuse:{value:/*@__PURE__*/ new xw(16777215)},opacity:{value:1},center:{value:/*@__PURE__*/ new Y(.5,.5)},rotation:{value:0},map:{value:null},mapTransform:{value:/*@__PURE__*/ new Z},alphaMap:{value:null},alphaMapTransform:{value:/*@__PURE__*/ new Z},alphaTest:{value:0}}},lD={basic:{uniforms:/*@__PURE__*/ iE([$.common,$.specularmap,$.envmap,$.aomap,$.lightmap,$.fog]),vertexShader:Q.meshbasic_vert,fragmentShader:Q.meshbasic_frag},lambert:{uniforms:/*@__PURE__*/ iE([$.common,$.specularmap,$.envmap,$.aomap,$.lightmap,$.emissivemap,$.bumpmap,$.normalmap,$.displacementmap,$.fog,$.lights,{emissive:{value:/*@__PURE__*/ new xw(0)},envMapIntensity:{value:1}}]),vertexShader:Q.meshlambert_vert,fragmentShader:Q.meshlambert_frag},phong:{uniforms:/*@__PURE__*/ iE([$.common,$.specularmap,$.envmap,$.aomap,$.lightmap,$.emissivemap,$.bumpmap,$.normalmap,$.displacementmap,$.fog,$.lights,{emissive:{value:/*@__PURE__*/ new xw(0)},specular:{value:/*@__PURE__*/ new xw(1118481)},shininess:{value:30},envMapIntensity:{value:1}}]),vertexShader:Q.meshphong_vert,fragmentShader:Q.meshphong_frag},standard:{uniforms:/*@__PURE__*/ iE([$.common,$.envmap,$.aomap,$.lightmap,$.emissivemap,$.bumpmap,$.normalmap,$.displacementmap,$.roughnessmap,$.metalnessmap,$.fog,$.lights,{emissive:{value:/*@__PURE__*/ new xw(0)},roughness:{value:1},metalness:{value:0},envMapIntensity:{value:1}}]),vertexShader:Q.meshphysical_vert,fragmentShader:Q.meshphysical_frag},toon:{uniforms:/*@__PURE__*/ iE([$.common,$.aomap,$.lightmap,$.emissivemap,$.bumpmap,$.normalmap,$.displacementmap,$.gradientmap,$.fog,$.lights,{emissive:{value:/*@__PURE__*/ new xw(0)}}]),vertexShader:Q.meshtoon_vert,fragmentShader:Q.meshtoon_frag},matcap:{uniforms:/*@__PURE__*/ iE([$.common,$.bumpmap,$.normalmap,$.displacementmap,$.fog,{matcap:{value:null}}]),vertexShader:Q.meshmatcap_vert,fragmentShader:Q.meshmatcap_frag},points:{uniforms:/*@__PURE__*/ iE([$.points,$.fog]),vertexShader:Q.points_vert,fragmentShader:Q.points_frag},dashed:{uniforms:/*@__PURE__*/ iE([$.common,$.fog,{scale:{value:1},dashSize:{value:1},totalSize:{value:2}}]),vertexShader:Q.linedashed_vert,fragmentShader:Q.linedashed_frag},depth:{uniforms:/*@__PURE__*/ iE([$.common,$.displacementmap]),vertexShader:Q.depth_vert,fragmentShader:Q.depth_frag},normal:{uniforms:/*@__PURE__*/ iE([$.common,$.bumpmap,$.normalmap,$.displacementmap,{opacity:{value:1}}]),vertexShader:Q.meshnormal_vert,fragmentShader:Q.meshnormal_frag},sprite:{uniforms:/*@__PURE__*/ iE([$.sprite,$.fog]),vertexShader:Q.sprite_vert,fragmentShader:Q.sprite_frag},background:{uniforms:{uvTransform:{value:/*@__PURE__*/ new Z},t2D:{value:null},backgroundIntensity:{value:1}},vertexShader:Q.background_vert,fragmentShader:Q.background_frag},backgroundCube:{uniforms:{envMap:{value:null},backgroundBlurriness:{value:0},backgroundIntensity:{value:1},backgroundRotation:{value:/*@__PURE__*/ new Z}},vertexShader:Q.backgroundCube_vert,fragmentShader:Q.backgroundCube_frag},cube:{uniforms:{tCube:{value:null},tFlip:{value:-1},opacity:{value:1}},vertexShader:Q.cube_vert,fragmentShader:Q.cube_frag},equirect:{uniforms:{tEquirect:{value:null}},vertexShader:Q.equirect_vert,fragmentShader:Q.equirect_frag},distance:{uniforms:/*@__PURE__*/ iE([$.common,$.displacementmap,{referencePosition:{value:/*@__PURE__*/ new X},nearDistance:{value:1},farDistance:{value:1e3}}]),vertexShader:Q.distance_vert,fragmentShader:Q.distance_frag},shadow:{uniforms:/*@__PURE__*/ iE([$.lights,$.fog,{color:{value:/*@__PURE__*/ new xw(0)},opacity:{value:1}}]),vertexShader:Q.shadow_vert,fragmentShader:Q.shadow_frag}};lD.physical={uniforms:/*@__PURE__*/ iE([lD.standard.uniforms,{clearcoat:{value:0},clearcoatMap:{value:null},clearcoatMapTransform:{value:/*@__PURE__*/ new Z},clearcoatNormalMap:{value:null},clearcoatNormalMapTransform:{value:/*@__PURE__*/ new Z},clearcoatNormalScale:{value:/*@__PURE__*/ new Y(1,1)},clearcoatRoughness:{value:0},clearcoatRoughnessMap:{value:null},clearcoatRoughnessMapTransform:{value:/*@__PURE__*/ new Z},dispersion:{value:0},retroreflectivity:{value:0},iridescence:{value:0},iridescenceMap:{value:null},iridescenceMapTransform:{value:/*@__PURE__*/ new Z},iridescenceIOR:{value:1.3},iridescenceThicknessMinimum:{value:100},iridescenceThicknessMaximum:{value:400},iridescenceThicknessMap:{value:null},iridescenceThicknessMapTransform:{value:/*@__PURE__*/ new Z},sheen:{value:0},sheenColor:{value:/*@__PURE__*/ new xw(0)},sheenColorMap:{value:null},sheenColorMapTransform:{value:/*@__PURE__*/ new Z},sheenRoughness:{value:1},sheenRoughnessMap:{value:null},sheenRoughnessMapTransform:{value:/*@__PURE__*/ new Z},transmission:{value:0},transmissionMap:{value:null},transmissionMapTransform:{value:/*@__PURE__*/ new Z},transmissionSamplerSize:{value:/*@__PURE__*/ new Y},transmissionSamplerMap:{value:null},thickness:{value:0},thicknessMap:{value:null},thicknessMapTransform:{value:/*@__PURE__*/ new Z},attenuationDistance:{value:0},attenuationColor:{value:/*@__PURE__*/ new xw(0)},specularColor:{value:/*@__PURE__*/ new xw(1,1,1)},specularColorMap:{value:null},specularColorMapTransform:{value:/*@__PURE__*/ new Z},specularIntensity:{value:1},specularIntensityMap:{value:null},specularIntensityMapTransform:{value:/*@__PURE__*/ new Z},anisotropyVector:{value:/*@__PURE__*/ new Y},anisotropyMap:{value:null},anisotropyMapTransform:{value:/*@__PURE__*/ new Z}}]),vertexShader:Q.meshphysical_vert,fragmentShader:Q.meshphysical_frag};var uD={r:0,b:0,g:0},dD=/*@__PURE__*/ new BC,fD=/*@__PURE__*/ new Z;fD.set(-1,0,0,0,1,0,0,0,1);function pD(e,t,n,r,i,a){let o=new xw(0),s=i===!0?0:1,c,l,u=null,d=0,f=null;function p(e){let n=e.isScene===!0?e.background:null;if(n&&n.isTexture){let r=e.backgroundBlurriness>0;n=t.get(n,r)}return n}function m(t){let r=!1,i=p(t);i===null?g(o,s):i&&i.isColor&&(g(i,1),r=!0);let c=e.xr.getEnvironmentBlendMode();c===`additive`?n.buffers.color.setClear(0,0,0,1,a):c===`alpha-blend`&&n.buffers.color.setClear(0,0,0,0,a),(e.autoClear||r)&&(n.buffers.depth.setTest(!0),n.buffers.depth.setMask(!0),n.buffers.color.setMask(!0),e.clear(e.autoClearColor,e.autoClearDepth,e.autoClearStencil))}function h(t,n){let i=p(n);i&&(i.isCubeTexture||i.mapping===306)?(l===void 0&&(l=new VT(new tE(1,1,1),new dE({name:`BackgroundCubeMaterial`,uniforms:rE(lD.backgroundCube.uniforms),vertexShader:lD.backgroundCube.vertexShader,fragmentShader:lD.backgroundCube.fragmentShader,side:1,depthTest:!1,depthWrite:!1,fog:!1,allowOverride:!1})),l.geometry.deleteAttribute(`normal`),l.geometry.deleteAttribute(`uv`),l.onBeforeRender=function(e,t,n){this.matrixWorld.copyPosition(n.matrixWorld)},Object.defineProperty(l.material,"envMap",{get:function(){return this.uniforms.envMap.value}}),r.update(l)),l.material.uniforms.envMap.value=i,l.material.uniforms.backgroundBlurriness.value=n.backgroundBlurriness,l.material.uniforms.backgroundIntensity.value=n.backgroundIntensity,l.material.uniforms.backgroundRotation.value.setFromMatrix4(dD.makeRotationFromEuler(n.backgroundRotation)).transpose(),i.isCubeTexture&&i.isRenderTargetTexture===!1&&l.material.uniforms.backgroundRotation.value.premultiply(fD),l.material.toneMapped=wC.getTransfer(i.colorSpace)!==KS,(u!==i||d!==i.version||f!==e.toneMapping)&&(l.material.needsUpdate=!0,u=i,d=i.version,f=e.toneMapping),l.layers.enableAll(),t.unshift(l,l.geometry,l.material,0,0,null)):i&&i.isTexture&&(c===void 0&&(c=new VT(new nE(2,2),new dE({name:`BackgroundMaterial`,uniforms:rE(lD.background.uniforms),vertexShader:lD.background.vertexShader,fragmentShader:lD.background.fragmentShader,side:0,depthTest:!1,depthWrite:!1,fog:!1,allowOverride:!1})),c.geometry.deleteAttribute(`normal`),Object.defineProperty(c.material,"map",{get:function(){return this.uniforms.t2D.value}}),r.update(c)),c.material.uniforms.t2D.value=i,c.material.uniforms.backgroundIntensity.value=n.backgroundIntensity,c.material.toneMapped=wC.getTransfer(i.colorSpace)!==KS,i.matrixAutoUpdate===!0&&i.updateMatrix(),c.material.uniforms.uvTransform.value.copy(i.matrix),(u!==i||d!==i.version||f!==e.toneMapping)&&(c.material.needsUpdate=!0,u=i,d=i.version,f=e.toneMapping),c.layers.enableAll(),t.unshift(c,c.geometry,c.material,0,0,null))}function g(t,r){t.getRGB(uD,sE(e)),n.buffers.color.setClear(uD.r,uD.g,uD.b,r,a)}function _(){l!==void 0&&(l.geometry.dispose(),l.material.dispose(),l=void 0),c!==void 0&&(c.geometry.dispose(),c.material.dispose(),c=void 0)}return{getClearColor:function(){return o},setClearColor:function(e,t=1){o.set(e),s=t,g(o,s)},getClearAlpha:function(){return s},setClearAlpha:function(e){s=e,g(o,s)},render:m,addToRenderList:h,dispose:_}}function mD(e,t){let n=e.getParameter(e.MAX_VERTEX_ATTRIBS),r={},i=f(null),a=i,o=!1;function s(n,r,i,s,c){let u=!1,f=d(n,s,i,r);a!==f&&(a=f,l(a.object)),u=p(n,s,i,c),u&&m(n,s,i,c),c!==null&&t.update(c,e.ELEMENT_ARRAY_BUFFER),(u||o)&&(o=!1,b(n,r,i,s),c!==null&&e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,t.get(c).buffer))}function c(){return e.createVertexArray()}function l(t){return e.bindVertexArray(t)}function u(t){return e.deleteVertexArray(t)}function d(e,t,n,i){let a=i.wireframe===!0,o=r[t.id];o===void 0&&(o={},r[t.id]=o);let s=e.isInstancedMesh===!0?e.id:0,l=o[s];l===void 0&&(l={},o[s]=l);let u=l[n.id];u===void 0&&(u={},l[n.id]=u);let d=u[a];return d===void 0&&(d=f(c()),u[a]=d),d}function f(e){let t=[],r=[],i=[];for(let e=0;e<n;e++)t[e]=0,r[e]=0,i[e]=0;return{geometry:null,program:null,wireframe:!1,newAttributes:t,enabledAttributes:r,attributeDivisors:i,object:e,attributes:{},index:null}}function p(e,t,n,r){let i=a.attributes,o=t.attributes,s=0,c=n.getAttributes();for(let t in c)if(c[t].location>=0){let n=i[t],r=o[t];if(r===void 0&&(t===`instanceMatrix`&&e.instanceMatrix&&(r=e.instanceMatrix),t===`instanceColor`&&e.instanceColor&&(r=e.instanceColor)),n===void 0||n.attribute!==r||r&&n.data!==r.data)return!0;s++}return a.attributesNum!==s||a.index!==r}function m(e,t,n,r){let i={},o=t.attributes,s=0,c=n.getAttributes();for(let t in c)if(c[t].location>=0){let n=o[t];n===void 0&&(t===`instanceMatrix`&&e.instanceMatrix&&(n=e.instanceMatrix),t===`instanceColor`&&e.instanceColor&&(n=e.instanceColor));let r={};r.attribute=n,n&&n.data&&(r.data=n.data),i[t]=r,s++}a.attributes=i,a.attributesNum=s,a.index=r}function h(){let e=a.newAttributes;for(let t=0,n=e.length;t<n;t++)e[t]=0}function g(e){_(e,0)}function _(t,n){let r=a.newAttributes,i=a.enabledAttributes,o=a.attributeDivisors;r[t]=1,i[t]===0&&(e.enableVertexAttribArray(t),i[t]=1),o[t]!==n&&(e.vertexAttribDivisor(t,n),o[t]=n)}function v(){let t=a.newAttributes,n=a.enabledAttributes;for(let r=0,i=n.length;r<i;r++)n[r]!==t[r]&&(e.disableVertexAttribArray(r),n[r]=0)}function y(t,n,r,i,a,o,s){s===!0?e.vertexAttribIPointer(t,n,r,a,o):e.vertexAttribPointer(t,n,r,i,a,o)}function b(n,r,i,a){h();let o=a.attributes,s=i.getAttributes(),c=r.defaultAttributeValues;for(let r in s){let i=s[r];if(i.location>=0){let s=o[r];if(s===void 0&&(r===`instanceMatrix`&&n.instanceMatrix&&(s=n.instanceMatrix),r===`instanceColor`&&n.instanceColor&&(s=n.instanceColor)),s!==void 0){let r=s.normalized,o=s.itemSize,c=t.get(s);if(c===void 0)continue;let l=c.buffer,u=c.type,d=c.bytesPerElement,f=u===e.INT||u===e.UNSIGNED_INT||s.gpuType===1013;if(s.isInterleavedBufferAttribute){let t=s.data,c=t.stride,p=s.offset;if(t.isInstancedInterleavedBuffer){for(let e=0;e<i.locationSize;e++)_(i.location+e,t.meshPerAttribute);n.isInstancedMesh!==!0&&a._maxInstanceCount===void 0&&(a._maxInstanceCount=t.meshPerAttribute*t.count)}else for(let e=0;e<i.locationSize;e++)g(i.location+e);e.bindBuffer(e.ARRAY_BUFFER,l);for(let e=0;e<i.locationSize;e++)y(i.location+e,o/i.locationSize,u,r,c*d,(p+o/i.locationSize*e)*d,f)}else{if(s.isInstancedBufferAttribute){for(let e=0;e<i.locationSize;e++)_(i.location+e,s.meshPerAttribute);n.isInstancedMesh!==!0&&a._maxInstanceCount===void 0&&(a._maxInstanceCount=s.meshPerAttribute*s.count)}else for(let e=0;e<i.locationSize;e++)g(i.location+e);e.bindBuffer(e.ARRAY_BUFFER,l);for(let e=0;e<i.locationSize;e++)y(i.location+e,o/i.locationSize,u,r,o*d,o/i.locationSize*e*d,f)}}else if(c!==void 0){let t=c[r];if(t!==void 0)switch(t.length){case 2:e.vertexAttrib2fv(i.location,t);break;case 3:e.vertexAttrib3fv(i.location,t);break;case 4:e.vertexAttrib4fv(i.location,t);break;default:e.vertexAttrib1fv(i.location,t)}}}}v()}function x(){T();for(let e in r){let t=r[e];for(let e in t){let n=t[e];for(let e in n){let t=n[e];for(let e in t)u(t[e].object),delete t[e];delete n[e]}}delete r[e]}}function S(e){if(r[e.id]===void 0)return;let t=r[e.id];for(let e in t){let n=t[e];for(let e in n){let t=n[e];for(let e in t)u(t[e].object),delete t[e];delete n[e]}}delete r[e.id]}function C(e){for(let t in r){let n=r[t];for(let t in n){let r=n[t];if(r[e.id]===void 0)continue;let i=r[e.id];for(let e in i)u(i[e].object),delete i[e];delete r[e.id]}}}function w(e){for(let t in r){let n=r[t],i=e.isInstancedMesh===!0?e.id:0,a=n[i];if(a!==void 0){for(let e in a){let t=a[e];for(let e in t)u(t[e].object),delete t[e];delete a[e]}delete n[i],Object.keys(n).length===0&&delete r[t]}}}function T(){E(),o=!0,a!==i&&(a=i,l(a.object))}function E(){i.geometry=null,i.program=null,i.wireframe=!1}return{setup:s,reset:T,resetDefaultState:E,dispose:x,releaseStatesOfGeometry:S,releaseStatesOfObject:w,releaseStatesOfProgram:C,initAttributes:h,enableAttribute:g,disableUnusedAttributes:v}}function hD(e,t,n){let r;function i(e){r=e}function a(t,i){e.drawArrays(r,t,i),n.update(i,r,1)}function o(t,i,a){a!==0&&(e.drawArraysInstanced(r,t,i,a),n.update(i,r,a))}function s(e,i,a){if(a===0)return;t.get(`WEBGL_multi_draw`).multiDrawArraysWEBGL(r,e,0,i,0,a);let o=0;for(let e=0;e<a;e++)o+=i[e];n.update(o,r,1)}this.setMode=i,this.render=a,this.renderInstances=o,this.renderMultiDraw=s}function gD(e,t,n,r){let i;function a(){if(i!==void 0)return i;if(t.has(`EXT_texture_filter_anisotropic`)===!0){let n=t.get(`EXT_texture_filter_anisotropic`);i=e.getParameter(n.MAX_TEXTURE_MAX_ANISOTROPY_EXT)}else i=0;return i}function o(t){return t===1023||r.convert(t)===e.getParameter(e.IMPLEMENTATION_COLOR_READ_FORMAT)}function s(n){let i=n===1016&&(t.has(`EXT_color_buffer_half_float`)||t.has(`EXT_color_buffer_float`));return!(n!==1009&&n!==1015&&!i&&r.convert(n)!==e.getParameter(e.IMPLEMENTATION_COLOR_READ_TYPE))}function c(t){if(t===`highp`){if(e.getShaderPrecisionFormat(e.VERTEX_SHADER,e.HIGH_FLOAT).precision>0&&e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_FLOAT).precision>0)return`highp`;t=`mediump`}return t===`mediump`&&e.getShaderPrecisionFormat(e.VERTEX_SHADER,e.MEDIUM_FLOAT).precision>0&&e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_FLOAT).precision>0?`mediump`:`lowp`}let l=n.precision===void 0?`highp`:n.precision,u=c(l);u!==l&&(q(`WebGLRenderer:`,l,`not supported, using`,u,`instead.`),l=u);let d=n.logarithmicDepthBuffer===!0,f=n.reversedDepthBuffer===!0&&t.has(`EXT_clip_control`);n.reversedDepthBuffer===!0&&f===!1&&q(`WebGLRenderer: Unable to use reversed depth buffer due to missing EXT_clip_control extension. Fallback to default depth buffer.`);let p=e.getParameter(e.MAX_TEXTURE_IMAGE_UNITS),m=e.getParameter(e.MAX_VERTEX_TEXTURE_IMAGE_UNITS),h=e.getParameter(e.MAX_TEXTURE_SIZE),g=e.getParameter(e.MAX_CUBE_MAP_TEXTURE_SIZE),_=e.getParameter(e.MAX_VERTEX_ATTRIBS),v=e.getParameter(e.MAX_VERTEX_UNIFORM_VECTORS),y=e.getParameter(e.MAX_VARYING_VECTORS),b=e.getParameter(e.MAX_FRAGMENT_UNIFORM_VECTORS),x=e.getParameter(e.MAX_SAMPLES),S=e.getParameter(e.SAMPLES);return{isWebGL2:!0,getMaxAnisotropy:a,getMaxPrecision:c,textureFormatReadable:o,textureTypeReadable:s,precision:l,logarithmicDepthBuffer:d,reversedDepthBuffer:f,maxTextures:p,maxVertexTextures:m,maxTextureSize:h,maxCubemapSize:g,maxAttributes:_,maxVertexUniforms:v,maxVaryings:y,maxFragmentUniforms:b,maxSamples:x,samples:S}}function _D(e){let t=this,n=null,r=0,i=!1,a=!1,o=new xT,s=new Z,c={value:null,needsUpdate:!1};this.uniform=c,this.numPlanes=0,this.numIntersection=0,this.init=function(e,t){let n=e.length!==0||t||r!==0||i;return i=t,r=e.length,n},this.beginShadows=function(){a=!0,u(null)},this.endShadows=function(){a=!1},this.setGlobalState=function(e,t){n=u(e,t,0)},this.setState=function(t,o,s){let d=t.clippingPlanes,f=t.clipIntersection,p=t.clipShadows,m=e.get(t);if(!i||d===null||d.length===0||a&&!p)a?u(null):l();else{let e=a?0:r,t=e*4,i=m.clippingState||null;c.value=i,i=u(d,o,t,s);for(let e=0;e!==t;++e)i[e]=n[e];m.clippingState=i,this.numIntersection=f?this.numPlanes:0,this.numPlanes+=e}};function l(){c.value!==n&&(c.value=n,c.needsUpdate=r>0),t.numPlanes=r,t.numIntersection=0}function u(e,n,r,i){let a=e===null?0:e.length,l=null;if(a!==0){if(l=c.value,i!==!0||l===null){let t=r+a*4,i=n.matrixWorldInverse;s.getNormalMatrix(i),(l===null||l.length<t)&&(l=new Float32Array(t));for(let t=0,n=r;t!==a;++t,n+=4)o.copy(e[t]).applyMatrix4(i,s),o.normal.toArray(l,n),l[n+3]=o.constant}c.value=l,c.needsUpdate=!0}return t.numPlanes=a,t.numIntersection=0,l}}var vD=4,yD=6,bD=20,xD=256,SD=/*@__PURE__*/ new HE,CD=/*@__PURE__*/ new xw,wD=null,TD=0,ED=0,DD=!1,OD=/*@__PURE__*/ new X,kD=/*@__PURE__*/ new X,AD=class{constructor(e){this._renderer=e,this._pingPongRenderTarget=null,this._lodMax=0,this._cubeSize=0,this._sizeLods=[],this._lodMeshes=[],this._backgroundBox=null,this._cubemapMaterial=null,this._equirectMaterial=null,this._blurMaterial=null,this._ggxMaterial=null}fromScene(e,t=0,n=.1,r=100,i={}){let{size:a=256,position:o=OD}=i;wD=this._renderer.getRenderTarget(),TD=this._renderer.getActiveCubeFace(),ED=this._renderer.getActiveMipmapLevel(),DD=this._renderer.xr.enabled,this._renderer.xr.enabled=!1,this._setSize(a);let s=this._allocateTargets();return s.depthBuffer=!0,this._sceneToCubeUV(e,n,r,s,o),t>0&&this._blur(s,0,0,t),this._applyPMREM(s),this._cleanup(s),s}fromEquirectangular(e,t=null){return this._fromTexture(e,t)}fromCubemap(e,t=null){return this._fromTexture(e,t)}compileCubemapShader(){this._cubemapMaterial===null&&(this._cubemapMaterial=LD(),this._compileMaterial(this._cubemapMaterial))}compileEquirectangularShader(){this._equirectMaterial===null&&(this._equirectMaterial=ID(),this._compileMaterial(this._equirectMaterial))}dispose(){this._dispose(),this._cubemapMaterial!==null&&this._cubemapMaterial.dispose(),this._equirectMaterial!==null&&this._equirectMaterial.dispose(),this._backgroundBox!==null&&(this._backgroundBox.geometry.dispose(),this._backgroundBox.material.dispose())}_setSize(e){this._lodMax=Math.floor(Math.log2(e)),this._cubeSize=2**this._lodMax}_dispose(){this._blurMaterial!==null&&this._blurMaterial.dispose(),this._ggxMaterial!==null&&this._ggxMaterial.dispose(),this._pingPongRenderTarget!==null&&this._pingPongRenderTarget.dispose();for(let e=0;e<this._lodMeshes.length;e++)this._lodMeshes[e].geometry.dispose()}_cleanup(e){this._renderer.setRenderTarget(wD,TD,ED),this._renderer.xr.enabled=DD,e.scissorTest=!1,ND(e,0,0,e.width,e.height)}_fromTexture(e,t){e.mapping===301||e.mapping===302?this._setSize(e.image.length===0?16:e.image[0].width||e.image[0].image.width):this._setSize(e.image.width/4),wD=this._renderer.getRenderTarget(),TD=this._renderer.getActiveCubeFace(),ED=this._renderer.getActiveMipmapLevel(),DD=this._renderer.xr.enabled,this._renderer.xr.enabled=!1;let n=t||this._allocateTargets();return this._textureToCubeUV(e,n),this._applyPMREM(n),this._cleanup(n),n}_allocateTargets(){let e=3*Math.max(this._cubeSize,112),t=4*this._cubeSize,n={magFilter:Dx,minFilter:Dx,generateMipmaps:!1,type:Lx,format:Gx,colorSpace:WS,depthBuffer:!1},r=MD(e,t,n);if(this._pingPongRenderTarget===null||this._pingPongRenderTarget.width!==e||this._pingPongRenderTarget.height!==t){this._pingPongRenderTarget!==null&&this._dispose(),this._pingPongRenderTarget=MD(e,t,n);let{_lodMax:r}=this;({lodMeshes:this._lodMeshes,sizeLods:this._sizeLods}=jD(r)),this._blurMaterial=FD(r,e,t),this._ggxMaterial=PD(r,e,t)}return r}_compileMaterial(e){let t=new VT(new _T,e);this._renderer.compile(t,SD)}_sceneToCubeUV(e,t,n,r,i){let a=new VE(90,1,t,n),o=[1,-1,1,1,1,1],s=[1,1,1,-1,-1,-1],c=this._renderer,l=c.autoClear,u=c.toneMapping;c.getClearColor(CD),c.toneMapping=0,c.autoClear=!1,c.state.buffers.depth.getReversed()&&(c.setRenderTarget(r),c.clearDepth(),c.setRenderTarget(null)),this._backgroundBox===null&&(this._backgroundBox=new VT(new tE,new kT({name:`PMREM.Background`,side:1,depthWrite:!1,depthTest:!1})));let d=this._backgroundBox,f=d.material,p=!1,m=e.background;m?m.isColor&&(f.color.copy(m),e.background=null,p=!0):(f.color.copy(CD),p=!0);for(let t=0;t<6;t++){let n=t%3;n===0?(a.up.set(0,o[t],0),a.position.set(i.x,i.y,i.z),a.lookAt(i.x+s[t],i.y,i.z)):n===1?(a.up.set(0,0,o[t]),a.position.set(i.x,i.y,i.z),a.lookAt(i.x,i.y+s[t],i.z)):(a.up.set(0,o[t],0),a.position.set(i.x,i.y,i.z),a.lookAt(i.x,i.y,i.z+s[t]));let l=this._cubeSize;ND(r,n*l,t>2?l:0,l,l),c.setRenderTarget(r),p&&c.render(d,a),c.render(e,a)}c.toneMapping=u,c.autoClear=l,e.background=m}_textureToCubeUV(e,t){let n=this._renderer,r=e.mapping===301||e.mapping===302;r?(this._cubemapMaterial===null&&(this._cubemapMaterial=LD()),this._cubemapMaterial.uniforms.flipEnvMap.value=e.isRenderTargetTexture===!1?-1:1):this._equirectMaterial===null&&(this._equirectMaterial=ID());let i=r?this._cubemapMaterial:this._equirectMaterial,a=this._lodMeshes[0];a.material=i;let o=i.uniforms;o.envMap.value=e;let s=this._cubeSize;ND(t,0,0,3*s,2*s),n.setRenderTarget(t),n.render(a,SD)}_applyPMREM(e){let t=this._renderer,n=t.autoClear;t.autoClear=!1;let r=this._lodMeshes.length;for(let t=1;t<r;t++)this._applyGGXFilter(e,t-1,t);t.autoClear=n}_applyGGXFilter(e,t,n){let r=this._renderer,i=this._pingPongRenderTarget,a=this._ggxMaterial,o=this._lodMeshes[n];o.material=a;let s=a.uniforms,c=n/(this._lodMeshes.length-1),l=t/(this._lodMeshes.length-1),u=Math.sqrt(c*c-l*l)*(c*1.25),{_lodMax:d}=this,f=this._sizeLods[n],p=3*f*(n>d-vD?n-d+vD:0),m=4*(this._cubeSize-f);s.envMap.value=e.texture,s.roughness.value=u,s.mipInt.value=d-t,ND(i,p,m,3*f,2*f),r.setRenderTarget(i),r.render(o,SD),s.envMap.value=i.texture,s.roughness.value=0,s.mipInt.value=d-n,ND(e,p,m,3*f,2*f),r.setRenderTarget(e),r.render(o,SD)}_blur(e,t,n,r){let i=this._pingPongRenderTarget,a=Math.min(r,Math.PI)/Math.SQRT2;this._blurPass(e,i,t,n,a),this._blurPass(i,e,n,n,a)}_blurPass(e,t,n,r,i){let a=this._renderer,o=this._blurMaterial,s=this._lodMeshes[r];s.material=o;let c=o.uniforms;c.envMap.value=e.texture,c.sigma.value=i,c.mipInt.value=this._lodMax-n;let l=this._sizeLods[r];ND(t,3*l*(r>this._lodMax-vD?r-this._lodMax+vD:0),4*(this._cubeSize-l),3*l,2*l),a.setRenderTarget(t),a.render(s,SD)}};function jD(e){let t=[],n=[],r=e,i=e-vD+1+yD;for(let e=0;e<i;e++){let e=2**r;t.push(e);let i=1/(e-2),a=-i,o=1+i,s=[a,a,o,a,o,o,a,a,o,o,a,o],c=/* @__PURE__ */ new Float32Array(108),l=/* @__PURE__ */ new Float32Array(108);for(let e=0;e<6;e++){let t=e%3*2/3-1,n=e>2?0:-1,r=[t,n,0,t+2/3,n,0,t+2/3,n+1,0,t,n,0,t+2/3,n+1,0,t,n+1,0];c.set(r,18*e);for(let t=0;t<6;t++){let n=s[t*2]*2-1,r=s[t*2+1]*2-1;e===0?kD.set(1,r,n):e===1?kD.set(-n,1,-r):e===2?kD.set(-n,r,1):e===3?kD.set(-1,r,-n):e===4?kD.set(-n,-1,r):kD.set(n,r,-1),kD.toArray(l,(e*6+t)*3)}}let u=new _T;u.setAttribute(`position`,new nT(c,3)),u.setAttribute(`outputDirection`,new nT(l,3)),n.push(new VT(u,null)),r>vD&&r--}return{lodMeshes:n,sizeLods:t}}function MD(e,t,n){let r=new LC(e,t,n);return r.texture.mapping=306,r.texture.name=`PMREM.cubeUv`,r.scissorTest=!0,r}function ND(e,t,n,r,i){e.viewport.set(t,n,r,i),e.scissor.set(t,n,r,i)}function PD(e,t,n){return new dE({name:`PMREMGGXConvolution`,defines:{GGX_SAMPLES:xD,CUBEUV_TEXEL_WIDTH:1/t,CUBEUV_TEXEL_HEIGHT:1/n,CUBEUV_MAX_MIP:`${e}.0`},uniforms:{envMap:{value:null},roughness:{value:0},mipInt:{value:0}},vertexShader:RD(),fragmentShader:`
|
|
3825
|
+
}`},$={common:{diffuse:{value:/*@__PURE__*/ new QT(16777215)},opacity:{value:1},map:{value:null},mapTransform:{value:/*@__PURE__*/ new Z},alphaMap:{value:null},alphaMapTransform:{value:/*@__PURE__*/ new Z},alphaTest:{value:0}},specularmap:{specularMap:{value:null},specularMapTransform:{value:/*@__PURE__*/ new Z}},envmap:{envMap:{value:null},envMapRotation:{value:/*@__PURE__*/ new Z},reflectivity:{value:1},ior:{value:1.5},refractionRatio:{value:.98},dfgLUT:{value:null}},aomap:{aoMap:{value:null},aoMapIntensity:{value:1},aoMapTransform:{value:/*@__PURE__*/ new Z}},lightmap:{lightMap:{value:null},lightMapIntensity:{value:1},lightMapTransform:{value:/*@__PURE__*/ new Z}},bumpmap:{bumpMap:{value:null},bumpMapTransform:{value:/*@__PURE__*/ new Z},bumpScale:{value:1}},normalmap:{normalMap:{value:null},normalMapTransform:{value:/*@__PURE__*/ new Z},normalScale:{value:/*@__PURE__*/ new Y(1,1)}},displacementmap:{displacementMap:{value:null},displacementMapTransform:{value:/*@__PURE__*/ new Z},displacementScale:{value:1},displacementBias:{value:0}},emissivemap:{emissiveMap:{value:null},emissiveMapTransform:{value:/*@__PURE__*/ new Z}},metalnessmap:{metalnessMap:{value:null},metalnessMapTransform:{value:/*@__PURE__*/ new Z}},roughnessmap:{roughnessMap:{value:null},roughnessMapTransform:{value:/*@__PURE__*/ new Z}},gradientmap:{gradientMap:{value:null}},fog:{fogDensity:{value:25e-5},fogNear:{value:1},fogFar:{value:2e3},fogColor:{value:/*@__PURE__*/ new QT(16777215)}},lights:{ambientLightColor:{value:[]},lightProbe:{value:[]},sunLights:{value:[],properties:{direction:{},color:{}}},sunLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},sunShadowMatrix:{value:[]},sunShadowCascade:{value:[]},directionalLights:{value:[],properties:{direction:{},color:{}}},directionalLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},directionalShadowMatrix:{value:[]},spotLights:{value:[],properties:{color:{},position:{},direction:{},distance:{},coneCos:{},penumbraCos:{},decay:{}}},spotLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},spotLightMap:{value:[]},spotLightMatrix:{value:[]},pointLights:{value:[],properties:{color:{},position:{},decay:{},distance:{}}},pointLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{},shadowCameraNear:{},shadowCameraFar:{}}},pointShadowMatrix:{value:[]},hemisphereLights:{value:[],properties:{direction:{},skyColor:{},groundColor:{}}},rectAreaLights:{value:[],properties:{color:{},position:{},width:{},height:{}}},ltc_1:{value:null},ltc_2:{value:null},probesSH:{value:null},probesMin:{value:/*@__PURE__*/ new X},probesMax:{value:/*@__PURE__*/ new X},probesResolution:{value:/*@__PURE__*/ new X}},points:{diffuse:{value:/*@__PURE__*/ new QT(16777215)},opacity:{value:1},size:{value:1},scale:{value:1},map:{value:null},alphaMap:{value:null},alphaMapTransform:{value:/*@__PURE__*/ new Z},alphaTest:{value:0},uvTransform:{value:/*@__PURE__*/ new Z}},sprite:{diffuse:{value:/*@__PURE__*/ new QT(16777215)},opacity:{value:1},center:{value:/*@__PURE__*/ new Y(.5,.5)},rotation:{value:0},map:{value:null},mapTransform:{value:/*@__PURE__*/ new Z},alphaMap:{value:null},alphaMapTransform:{value:/*@__PURE__*/ new Z},alphaTest:{value:0}}},BO={basic:{uniforms:/*@__PURE__*/ FD([$.common,$.specularmap,$.envmap,$.aomap,$.lightmap,$.fog]),vertexShader:Q.meshbasic_vert,fragmentShader:Q.meshbasic_frag},lambert:{uniforms:/*@__PURE__*/ FD([$.common,$.specularmap,$.envmap,$.aomap,$.lightmap,$.emissivemap,$.bumpmap,$.normalmap,$.displacementmap,$.fog,$.lights,{emissive:{value:/*@__PURE__*/ new QT(0)},envMapIntensity:{value:1}}]),vertexShader:Q.meshlambert_vert,fragmentShader:Q.meshlambert_frag},phong:{uniforms:/*@__PURE__*/ FD([$.common,$.specularmap,$.envmap,$.aomap,$.lightmap,$.emissivemap,$.bumpmap,$.normalmap,$.displacementmap,$.fog,$.lights,{emissive:{value:/*@__PURE__*/ new QT(0)},specular:{value:/*@__PURE__*/ new QT(1118481)},shininess:{value:30},envMapIntensity:{value:1}}]),vertexShader:Q.meshphong_vert,fragmentShader:Q.meshphong_frag},standard:{uniforms:/*@__PURE__*/ FD([$.common,$.envmap,$.aomap,$.lightmap,$.emissivemap,$.bumpmap,$.normalmap,$.displacementmap,$.roughnessmap,$.metalnessmap,$.fog,$.lights,{emissive:{value:/*@__PURE__*/ new QT(0)},roughness:{value:1},metalness:{value:0},envMapIntensity:{value:1}}]),vertexShader:Q.meshphysical_vert,fragmentShader:Q.meshphysical_frag},toon:{uniforms:/*@__PURE__*/ FD([$.common,$.aomap,$.lightmap,$.emissivemap,$.bumpmap,$.normalmap,$.displacementmap,$.gradientmap,$.fog,$.lights,{emissive:{value:/*@__PURE__*/ new QT(0)}}]),vertexShader:Q.meshtoon_vert,fragmentShader:Q.meshtoon_frag},matcap:{uniforms:/*@__PURE__*/ FD([$.common,$.bumpmap,$.normalmap,$.displacementmap,$.fog,{matcap:{value:null}}]),vertexShader:Q.meshmatcap_vert,fragmentShader:Q.meshmatcap_frag},points:{uniforms:/*@__PURE__*/ FD([$.points,$.fog]),vertexShader:Q.points_vert,fragmentShader:Q.points_frag},dashed:{uniforms:/*@__PURE__*/ FD([$.common,$.fog,{scale:{value:1},dashSize:{value:1},totalSize:{value:2}}]),vertexShader:Q.linedashed_vert,fragmentShader:Q.linedashed_frag},depth:{uniforms:/*@__PURE__*/ FD([$.common,$.displacementmap]),vertexShader:Q.depth_vert,fragmentShader:Q.depth_frag},normal:{uniforms:/*@__PURE__*/ FD([$.common,$.bumpmap,$.normalmap,$.displacementmap,{opacity:{value:1}}]),vertexShader:Q.meshnormal_vert,fragmentShader:Q.meshnormal_frag},sprite:{uniforms:/*@__PURE__*/ FD([$.sprite,$.fog]),vertexShader:Q.sprite_vert,fragmentShader:Q.sprite_frag},background:{uniforms:{uvTransform:{value:/*@__PURE__*/ new Z},t2D:{value:null},backgroundIntensity:{value:1}},vertexShader:Q.background_vert,fragmentShader:Q.background_frag},backgroundCube:{uniforms:{envMap:{value:null},backgroundBlurriness:{value:0},backgroundIntensity:{value:1},backgroundRotation:{value:/*@__PURE__*/ new Z}},vertexShader:Q.backgroundCube_vert,fragmentShader:Q.backgroundCube_frag},cube:{uniforms:{tCube:{value:null},tFlip:{value:-1},opacity:{value:1}},vertexShader:Q.cube_vert,fragmentShader:Q.cube_frag},equirect:{uniforms:{tEquirect:{value:null}},vertexShader:Q.equirect_vert,fragmentShader:Q.equirect_frag},distance:{uniforms:/*@__PURE__*/ FD([$.common,$.displacementmap,{referencePosition:{value:/*@__PURE__*/ new X},nearDistance:{value:1},farDistance:{value:1e3}}]),vertexShader:Q.distance_vert,fragmentShader:Q.distance_frag},shadow:{uniforms:/*@__PURE__*/ FD([$.lights,$.fog,{color:{value:/*@__PURE__*/ new QT(0)},opacity:{value:1}}]),vertexShader:Q.shadow_vert,fragmentShader:Q.shadow_frag}};BO.physical={uniforms:/*@__PURE__*/ FD([BO.standard.uniforms,{clearcoat:{value:0},clearcoatMap:{value:null},clearcoatMapTransform:{value:/*@__PURE__*/ new Z},clearcoatNormalMap:{value:null},clearcoatNormalMapTransform:{value:/*@__PURE__*/ new Z},clearcoatNormalScale:{value:/*@__PURE__*/ new Y(1,1)},clearcoatRoughness:{value:0},clearcoatRoughnessMap:{value:null},clearcoatRoughnessMapTransform:{value:/*@__PURE__*/ new Z},dispersion:{value:0},retroreflectivity:{value:0},iridescence:{value:0},iridescenceMap:{value:null},iridescenceMapTransform:{value:/*@__PURE__*/ new Z},iridescenceIOR:{value:1.3},iridescenceThicknessMinimum:{value:100},iridescenceThicknessMaximum:{value:400},iridescenceThicknessMap:{value:null},iridescenceThicknessMapTransform:{value:/*@__PURE__*/ new Z},sheen:{value:0},sheenColor:{value:/*@__PURE__*/ new QT(0)},sheenColorMap:{value:null},sheenColorMapTransform:{value:/*@__PURE__*/ new Z},sheenRoughness:{value:1},sheenRoughnessMap:{value:null},sheenRoughnessMapTransform:{value:/*@__PURE__*/ new Z},transmission:{value:0},transmissionMap:{value:null},transmissionMapTransform:{value:/*@__PURE__*/ new Z},transmissionSamplerSize:{value:/*@__PURE__*/ new Y},transmissionSamplerMap:{value:null},thickness:{value:0},thicknessMap:{value:null},thicknessMapTransform:{value:/*@__PURE__*/ new Z},attenuationDistance:{value:0},attenuationColor:{value:/*@__PURE__*/ new QT(0)},specularColor:{value:/*@__PURE__*/ new QT(1,1,1)},specularColorMap:{value:null},specularColorMapTransform:{value:/*@__PURE__*/ new Z},specularIntensity:{value:1},specularIntensityMap:{value:null},specularIntensityMapTransform:{value:/*@__PURE__*/ new Z},anisotropyVector:{value:/*@__PURE__*/ new Y},anisotropyMap:{value:null},anisotropyMapTransform:{value:/*@__PURE__*/ new Z}}]),vertexShader:Q.meshphysical_vert,fragmentShader:Q.meshphysical_frag};var VO={r:0,b:0,g:0},HO=/*@__PURE__*/ new _T,UO=/*@__PURE__*/ new Z;UO.set(-1,0,0,0,1,0,0,0,1);function WO(e,t,n,r,i,a){let o=new QT(0),s=i===!0?0:1,c,l,u=null,d=0,f=null;function p(e){let n=e.isScene===!0?e.background:null;if(n&&n.isTexture){let r=e.backgroundBlurriness>0;n=t.get(n,r)}return n}function m(t){let r=!1,i=p(t);i===null?g(o,s):i&&i.isColor&&(g(i,1),r=!0);let c=e.xr.getEnvironmentBlendMode();c===`additive`?n.buffers.color.setClear(0,0,0,1,a):c===`alpha-blend`&&n.buffers.color.setClear(0,0,0,0,a),(e.autoClear||r)&&(n.buffers.depth.setTest(!0),n.buffers.depth.setMask(!0),n.buffers.color.setMask(!0),e.clear(e.autoClearColor,e.autoClearDepth,e.autoClearStencil))}function h(t,n){let i=p(n);i&&(i.isCubeTexture||i.mapping===306)?(l===void 0&&(l=new vD(new MD(1,1,1),new HD({name:`BackgroundCubeMaterial`,uniforms:PD(BO.backgroundCube.uniforms),vertexShader:BO.backgroundCube.vertexShader,fragmentShader:BO.backgroundCube.fragmentShader,side:1,depthTest:!1,depthWrite:!1,fog:!1,allowOverride:!1})),l.geometry.deleteAttribute(`normal`),l.geometry.deleteAttribute(`uv`),l.onBeforeRender=function(e,t,n){this.matrixWorld.copyPosition(n.matrixWorld)},Object.defineProperty(l.material,"envMap",{get:function(){return this.uniforms.envMap.value}}),r.update(l)),l.material.uniforms.envMap.value=i,l.material.uniforms.backgroundBlurriness.value=n.backgroundBlurriness,l.material.uniforms.backgroundIntensity.value=n.backgroundIntensity,l.material.uniforms.backgroundRotation.value.setFromMatrix4(HO.makeRotationFromEuler(n.backgroundRotation)).transpose(),i.isCubeTexture&&i.isRenderTargetTexture===!1&&l.material.uniforms.backgroundRotation.value.premultiply(UO),l.material.toneMapped=tT.getTransfer(i.colorSpace)!==Cw,(u!==i||d!==i.version||f!==e.toneMapping)&&(l.material.needsUpdate=!0,u=i,d=i.version,f=e.toneMapping),l.layers.enableAll(),t.unshift(l,l.geometry,l.material,0,0,null)):i&&i.isTexture&&(c===void 0&&(c=new vD(new ND(2,2),new HD({name:`BackgroundMaterial`,uniforms:PD(BO.background.uniforms),vertexShader:BO.background.vertexShader,fragmentShader:BO.background.fragmentShader,side:0,depthTest:!1,depthWrite:!1,fog:!1,allowOverride:!1})),c.geometry.deleteAttribute(`normal`),Object.defineProperty(c.material,"map",{get:function(){return this.uniforms.t2D.value}}),r.update(c)),c.material.uniforms.t2D.value=i,c.material.uniforms.backgroundIntensity.value=n.backgroundIntensity,c.material.toneMapped=tT.getTransfer(i.colorSpace)!==Cw,i.matrixAutoUpdate===!0&&i.updateMatrix(),c.material.uniforms.uvTransform.value.copy(i.matrix),(u!==i||d!==i.version||f!==e.toneMapping)&&(c.material.needsUpdate=!0,u=i,d=i.version,f=e.toneMapping),c.layers.enableAll(),t.unshift(c,c.geometry,c.material,0,0,null))}function g(t,r){t.getRGB(VO,RD(e)),n.buffers.color.setClear(VO.r,VO.g,VO.b,r,a)}function _(){l!==void 0&&(l.geometry.dispose(),l.material.dispose(),l=void 0),c!==void 0&&(c.geometry.dispose(),c.material.dispose(),c=void 0)}return{getClearColor:function(){return o},setClearColor:function(e,t=1){o.set(e),s=t,g(o,s)},getClearAlpha:function(){return s},setClearAlpha:function(e){s=e,g(o,s)},render:m,addToRenderList:h,dispose:_}}function GO(e,t){let n=e.getParameter(e.MAX_VERTEX_ATTRIBS),r={},i=f(null),a=i,o=!1;function s(n,r,i,s,c){let u=!1,f=d(n,s,i,r);a!==f&&(a=f,l(a.object)),u=p(n,s,i,c),u&&m(n,s,i,c),c!==null&&t.update(c,e.ELEMENT_ARRAY_BUFFER),(u||o)&&(o=!1,b(n,r,i,s),c!==null&&e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,t.get(c).buffer))}function c(){return e.createVertexArray()}function l(t){return e.bindVertexArray(t)}function u(t){return e.deleteVertexArray(t)}function d(e,t,n,i){let a=i.wireframe===!0,o=r[t.id];o===void 0&&(o={},r[t.id]=o);let s=e.isInstancedMesh===!0?e.id:0,l=o[s];l===void 0&&(l={},o[s]=l);let u=l[n.id];u===void 0&&(u={},l[n.id]=u);let d=u[a];return d===void 0&&(d=f(c()),u[a]=d),d}function f(e){let t=[],r=[],i=[];for(let e=0;e<n;e++)t[e]=0,r[e]=0,i[e]=0;return{geometry:null,program:null,wireframe:!1,newAttributes:t,enabledAttributes:r,attributeDivisors:i,object:e,attributes:{},index:null}}function p(e,t,n,r){let i=a.attributes,o=t.attributes,s=0,c=n.getAttributes();for(let t in c)if(c[t].location>=0){let n=i[t],r=o[t];if(r===void 0&&(t===`instanceMatrix`&&e.instanceMatrix&&(r=e.instanceMatrix),t===`instanceColor`&&e.instanceColor&&(r=e.instanceColor)),n===void 0||n.attribute!==r||r&&n.data!==r.data)return!0;s++}return a.attributesNum!==s||a.index!==r}function m(e,t,n,r){let i={},o=t.attributes,s=0,c=n.getAttributes();for(let t in c)if(c[t].location>=0){let n=o[t];n===void 0&&(t===`instanceMatrix`&&e.instanceMatrix&&(n=e.instanceMatrix),t===`instanceColor`&&e.instanceColor&&(n=e.instanceColor));let r={};r.attribute=n,n&&n.data&&(r.data=n.data),i[t]=r,s++}a.attributes=i,a.attributesNum=s,a.index=r}function h(){let e=a.newAttributes;for(let t=0,n=e.length;t<n;t++)e[t]=0}function g(e){_(e,0)}function _(t,n){let r=a.newAttributes,i=a.enabledAttributes,o=a.attributeDivisors;r[t]=1,i[t]===0&&(e.enableVertexAttribArray(t),i[t]=1),o[t]!==n&&(e.vertexAttribDivisor(t,n),o[t]=n)}function v(){let t=a.newAttributes,n=a.enabledAttributes;for(let r=0,i=n.length;r<i;r++)n[r]!==t[r]&&(e.disableVertexAttribArray(r),n[r]=0)}function y(t,n,r,i,a,o,s){s===!0?e.vertexAttribIPointer(t,n,r,a,o):e.vertexAttribPointer(t,n,r,i,a,o)}function b(n,r,i,a){h();let o=a.attributes,s=i.getAttributes(),c=r.defaultAttributeValues;for(let r in s){let i=s[r];if(i.location>=0){let s=o[r];if(s===void 0&&(r===`instanceMatrix`&&n.instanceMatrix&&(s=n.instanceMatrix),r===`instanceColor`&&n.instanceColor&&(s=n.instanceColor)),s!==void 0){let r=s.normalized,o=s.itemSize,c=t.get(s);if(c===void 0)continue;let l=c.buffer,u=c.type,d=c.bytesPerElement,f=u===e.INT||u===e.UNSIGNED_INT||s.gpuType===1013;if(s.isInterleavedBufferAttribute){let t=s.data,c=t.stride,p=s.offset;if(t.isInstancedInterleavedBuffer){for(let e=0;e<i.locationSize;e++)_(i.location+e,t.meshPerAttribute);n.isInstancedMesh!==!0&&a._maxInstanceCount===void 0&&(a._maxInstanceCount=t.meshPerAttribute*t.count)}else for(let e=0;e<i.locationSize;e++)g(i.location+e);e.bindBuffer(e.ARRAY_BUFFER,l);for(let e=0;e<i.locationSize;e++)y(i.location+e,o/i.locationSize,u,r,c*d,(p+o/i.locationSize*e)*d,f)}else{if(s.isInstancedBufferAttribute){for(let e=0;e<i.locationSize;e++)_(i.location+e,s.meshPerAttribute);n.isInstancedMesh!==!0&&a._maxInstanceCount===void 0&&(a._maxInstanceCount=s.meshPerAttribute*s.count)}else for(let e=0;e<i.locationSize;e++)g(i.location+e);e.bindBuffer(e.ARRAY_BUFFER,l);for(let e=0;e<i.locationSize;e++)y(i.location+e,o/i.locationSize,u,r,o*d,o/i.locationSize*e*d,f)}}else if(c!==void 0){let t=c[r];if(t!==void 0)switch(t.length){case 2:e.vertexAttrib2fv(i.location,t);break;case 3:e.vertexAttrib3fv(i.location,t);break;case 4:e.vertexAttrib4fv(i.location,t);break;default:e.vertexAttrib1fv(i.location,t)}}}}v()}function x(){T();for(let e in r){let t=r[e];for(let e in t){let n=t[e];for(let e in n){let t=n[e];for(let e in t)u(t[e].object),delete t[e];delete n[e]}}delete r[e]}}function S(e){if(r[e.id]===void 0)return;let t=r[e.id];for(let e in t){let n=t[e];for(let e in n){let t=n[e];for(let e in t)u(t[e].object),delete t[e];delete n[e]}}delete r[e.id]}function C(e){for(let t in r){let n=r[t];for(let t in n){let r=n[t];if(r[e.id]===void 0)continue;let i=r[e.id];for(let e in i)u(i[e].object),delete i[e];delete r[e.id]}}}function w(e){for(let t in r){let n=r[t],i=e.isInstancedMesh===!0?e.id:0,a=n[i];if(a!==void 0){for(let e in a){let t=a[e];for(let e in t)u(t[e].object),delete t[e];delete a[e]}delete n[i],Object.keys(n).length===0&&delete r[t]}}}function T(){E(),o=!0,a!==i&&(a=i,l(a.object))}function E(){i.geometry=null,i.program=null,i.wireframe=!1}return{setup:s,reset:T,resetDefaultState:E,dispose:x,releaseStatesOfGeometry:S,releaseStatesOfObject:w,releaseStatesOfProgram:C,initAttributes:h,enableAttribute:g,disableUnusedAttributes:v}}function KO(e,t,n){let r;function i(e){r=e}function a(t,i){e.drawArrays(r,t,i),n.update(i,r,1)}function o(t,i,a){a!==0&&(e.drawArraysInstanced(r,t,i,a),n.update(i,r,a))}function s(e,i,a){if(a===0)return;t.get(`WEBGL_multi_draw`).multiDrawArraysWEBGL(r,e,0,i,0,a);let o=0;for(let e=0;e<a;e++)o+=i[e];n.update(o,r,1)}this.setMode=i,this.render=a,this.renderInstances=o,this.renderMultiDraw=s}function qO(e,t,n,r){let i;function a(){if(i!==void 0)return i;if(t.has(`EXT_texture_filter_anisotropic`)===!0){let n=t.get(`EXT_texture_filter_anisotropic`);i=e.getParameter(n.MAX_TEXTURE_MAX_ANISOTROPY_EXT)}else i=0;return i}function o(t){return t===1023||r.convert(t)===e.getParameter(e.IMPLEMENTATION_COLOR_READ_FORMAT)}function s(n){let i=n===1016&&(t.has(`EXT_color_buffer_half_float`)||t.has(`EXT_color_buffer_float`));return!(n!==1009&&n!==1015&&!i&&r.convert(n)!==e.getParameter(e.IMPLEMENTATION_COLOR_READ_TYPE))}function c(t){if(t===`highp`){if(e.getShaderPrecisionFormat(e.VERTEX_SHADER,e.HIGH_FLOAT).precision>0&&e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_FLOAT).precision>0)return`highp`;t=`mediump`}return t===`mediump`&&e.getShaderPrecisionFormat(e.VERTEX_SHADER,e.MEDIUM_FLOAT).precision>0&&e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_FLOAT).precision>0?`mediump`:`lowp`}let l=n.precision===void 0?`highp`:n.precision,u=c(l);u!==l&&(q(`WebGLRenderer:`,l,`not supported, using`,u,`instead.`),l=u);let d=n.logarithmicDepthBuffer===!0,f=n.reversedDepthBuffer===!0&&t.has(`EXT_clip_control`);n.reversedDepthBuffer===!0&&f===!1&&q(`WebGLRenderer: Unable to use reversed depth buffer due to missing EXT_clip_control extension. Fallback to default depth buffer.`);let p=e.getParameter(e.MAX_TEXTURE_IMAGE_UNITS),m=e.getParameter(e.MAX_VERTEX_TEXTURE_IMAGE_UNITS),h=e.getParameter(e.MAX_TEXTURE_SIZE),g=e.getParameter(e.MAX_CUBE_MAP_TEXTURE_SIZE),_=e.getParameter(e.MAX_VERTEX_ATTRIBS),v=e.getParameter(e.MAX_VERTEX_UNIFORM_VECTORS),y=e.getParameter(e.MAX_VARYING_VECTORS),b=e.getParameter(e.MAX_FRAGMENT_UNIFORM_VECTORS),x=e.getParameter(e.MAX_SAMPLES),S=e.getParameter(e.SAMPLES);return{isWebGL2:!0,getMaxAnisotropy:a,getMaxPrecision:c,textureFormatReadable:o,textureTypeReadable:s,precision:l,logarithmicDepthBuffer:d,reversedDepthBuffer:f,maxTextures:p,maxVertexTextures:m,maxTextureSize:h,maxCubemapSize:g,maxAttributes:_,maxVertexUniforms:v,maxVaryings:y,maxFragmentUniforms:b,maxSamples:x,samples:S}}function JO(e){let t=this,n=null,r=0,i=!1,a=!1,o=new QE,s=new Z,c={value:null,needsUpdate:!1};this.uniform=c,this.numPlanes=0,this.numIntersection=0,this.init=function(e,t){let n=e.length!==0||t||r!==0||i;return i=t,r=e.length,n},this.beginShadows=function(){a=!0,u(null)},this.endShadows=function(){a=!1},this.setGlobalState=function(e,t){n=u(e,t,0)},this.setState=function(t,o,s){let d=t.clippingPlanes,f=t.clipIntersection,p=t.clipShadows,m=e.get(t);if(!i||d===null||d.length===0||a&&!p)a?u(null):l();else{let e=a?0:r,t=e*4,i=m.clippingState||null;c.value=i,i=u(d,o,t,s);for(let e=0;e!==t;++e)i[e]=n[e];m.clippingState=i,this.numIntersection=f?this.numPlanes:0,this.numPlanes+=e}};function l(){c.value!==n&&(c.value=n,c.needsUpdate=r>0),t.numPlanes=r,t.numIntersection=0}function u(e,n,r,i){let a=e===null?0:e.length,l=null;if(a!==0){if(l=c.value,i!==!0||l===null){let t=r+a*4,i=n.matrixWorldInverse;s.getNormalMatrix(i),(l===null||l.length<t)&&(l=new Float32Array(t));for(let t=0,n=r;t!==a;++t,n+=4)o.copy(e[t]).applyMatrix4(i,s),o.normal.toArray(l,n),l[n+3]=o.constant}c.value=l,c.needsUpdate=!0}return t.numPlanes=a,t.numIntersection=0,l}}var YO=4,XO=6,ZO=20,QO=256,$O=/*@__PURE__*/ new yO,ek=/*@__PURE__*/ new QT,tk=null,nk=0,rk=0,ik=!1,ak=/*@__PURE__*/ new X,ok=/*@__PURE__*/ new X,sk=class{constructor(e){this._renderer=e,this._pingPongRenderTarget=null,this._lodMax=0,this._cubeSize=0,this._sizeLods=[],this._lodMeshes=[],this._backgroundBox=null,this._cubemapMaterial=null,this._equirectMaterial=null,this._blurMaterial=null,this._ggxMaterial=null}fromScene(e,t=0,n=.1,r=100,i={}){let{size:a=256,position:o=ak}=i;tk=this._renderer.getRenderTarget(),nk=this._renderer.getActiveCubeFace(),rk=this._renderer.getActiveMipmapLevel(),ik=this._renderer.xr.enabled,this._renderer.xr.enabled=!1,this._setSize(a);let s=this._allocateTargets();return s.depthBuffer=!0,this._sceneToCubeUV(e,n,r,s,o),t>0&&this._blur(s,0,0,t),this._applyPMREM(s),this._cleanup(s),s}fromEquirectangular(e,t=null){return this._fromTexture(e,t)}fromCubemap(e,t=null){return this._fromTexture(e,t)}compileCubemapShader(){this._cubemapMaterial===null&&(this._cubemapMaterial=mk(),this._compileMaterial(this._cubemapMaterial))}compileEquirectangularShader(){this._equirectMaterial===null&&(this._equirectMaterial=pk(),this._compileMaterial(this._equirectMaterial))}dispose(){this._dispose(),this._cubemapMaterial!==null&&this._cubemapMaterial.dispose(),this._equirectMaterial!==null&&this._equirectMaterial.dispose(),this._backgroundBox!==null&&(this._backgroundBox.geometry.dispose(),this._backgroundBox.material.dispose())}_setSize(e){this._lodMax=Math.floor(Math.log2(e)),this._cubeSize=2**this._lodMax}_dispose(){this._blurMaterial!==null&&this._blurMaterial.dispose(),this._ggxMaterial!==null&&this._ggxMaterial.dispose(),this._pingPongRenderTarget!==null&&this._pingPongRenderTarget.dispose();for(let e=0;e<this._lodMeshes.length;e++)this._lodMeshes[e].geometry.dispose()}_cleanup(e){this._renderer.setRenderTarget(tk,nk,rk),this._renderer.xr.enabled=ik,e.scissorTest=!1,uk(e,0,0,e.width,e.height)}_fromTexture(e,t){e.mapping===301||e.mapping===302?this._setSize(e.image.length===0?16:e.image[0].width||e.image[0].image.width):this._setSize(e.image.width/4),tk=this._renderer.getRenderTarget(),nk=this._renderer.getActiveCubeFace(),rk=this._renderer.getActiveMipmapLevel(),ik=this._renderer.xr.enabled,this._renderer.xr.enabled=!1;let n=t||this._allocateTargets();return this._textureToCubeUV(e,n),this._applyPMREM(n),this._cleanup(n),n}_allocateTargets(){let e=3*Math.max(this._cubeSize,112),t=4*this._cubeSize,n={magFilter:iC,minFilter:iC,generateMipmaps:!1,type:mC,format:SC,colorSpace:xw,depthBuffer:!1},r=lk(e,t,n);if(this._pingPongRenderTarget===null||this._pingPongRenderTarget.width!==e||this._pingPongRenderTarget.height!==t){this._pingPongRenderTarget!==null&&this._dispose(),this._pingPongRenderTarget=lk(e,t,n);let{_lodMax:r}=this;({lodMeshes:this._lodMeshes,sizeLods:this._sizeLods}=ck(r)),this._blurMaterial=fk(r,e,t),this._ggxMaterial=dk(r,e,t)}return r}_compileMaterial(e){let t=new vD(new JE,e);this._renderer.compile(t,$O)}_sceneToCubeUV(e,t,n,r,i){let a=new vO(90,1,t,n),o=[1,-1,1,1,1,1],s=[1,1,1,-1,-1,-1],c=this._renderer,l=c.autoClear,u=c.toneMapping;c.getClearColor(ek),c.toneMapping=0,c.autoClear=!1,c.state.buffers.depth.getReversed()&&(c.setRenderTarget(r),c.clearDepth(),c.setRenderTarget(null)),this._backgroundBox===null&&(this._backgroundBox=new vD(new MD,new oD({name:`PMREM.Background`,side:1,depthWrite:!1,depthTest:!1})));let d=this._backgroundBox,f=d.material,p=!1,m=e.background;m?m.isColor&&(f.color.copy(m),e.background=null,p=!0):(f.color.copy(ek),p=!0);for(let t=0;t<6;t++){let n=t%3;n===0?(a.up.set(0,o[t],0),a.position.set(i.x,i.y,i.z),a.lookAt(i.x+s[t],i.y,i.z)):n===1?(a.up.set(0,0,o[t]),a.position.set(i.x,i.y,i.z),a.lookAt(i.x,i.y+s[t],i.z)):(a.up.set(0,o[t],0),a.position.set(i.x,i.y,i.z),a.lookAt(i.x,i.y,i.z+s[t]));let l=this._cubeSize;uk(r,n*l,t>2?l:0,l,l),c.setRenderTarget(r),p&&c.render(d,a),c.render(e,a)}c.toneMapping=u,c.autoClear=l,e.background=m}_textureToCubeUV(e,t){let n=this._renderer,r=e.mapping===301||e.mapping===302;r?(this._cubemapMaterial===null&&(this._cubemapMaterial=mk()),this._cubemapMaterial.uniforms.flipEnvMap.value=e.isRenderTargetTexture===!1?-1:1):this._equirectMaterial===null&&(this._equirectMaterial=pk());let i=r?this._cubemapMaterial:this._equirectMaterial,a=this._lodMeshes[0];a.material=i;let o=i.uniforms;o.envMap.value=e;let s=this._cubeSize;uk(t,0,0,3*s,2*s),n.setRenderTarget(t),n.render(a,$O)}_applyPMREM(e){let t=this._renderer,n=t.autoClear;t.autoClear=!1;let r=this._lodMeshes.length;for(let t=1;t<r;t++)this._applyGGXFilter(e,t-1,t);t.autoClear=n}_applyGGXFilter(e,t,n){let r=this._renderer,i=this._pingPongRenderTarget,a=this._ggxMaterial,o=this._lodMeshes[n];o.material=a;let s=a.uniforms,c=n/(this._lodMeshes.length-1),l=t/(this._lodMeshes.length-1),u=Math.sqrt(c*c-l*l)*(c*1.25),{_lodMax:d}=this,f=this._sizeLods[n],p=3*f*(n>d-YO?n-d+YO:0),m=4*(this._cubeSize-f);s.envMap.value=e.texture,s.roughness.value=u,s.mipInt.value=d-t,uk(i,p,m,3*f,2*f),r.setRenderTarget(i),r.render(o,$O),s.envMap.value=i.texture,s.roughness.value=0,s.mipInt.value=d-n,uk(e,p,m,3*f,2*f),r.setRenderTarget(e),r.render(o,$O)}_blur(e,t,n,r){let i=this._pingPongRenderTarget,a=Math.min(r,Math.PI)/Math.SQRT2;this._blurPass(e,i,t,n,a),this._blurPass(i,e,n,n,a)}_blurPass(e,t,n,r,i){let a=this._renderer,o=this._blurMaterial,s=this._lodMeshes[r];s.material=o;let c=o.uniforms;c.envMap.value=e.texture,c.sigma.value=i,c.mipInt.value=this._lodMax-n;let l=this._sizeLods[r];uk(t,3*l*(r>this._lodMax-YO?r-this._lodMax+YO:0),4*(this._cubeSize-l),3*l,2*l),a.setRenderTarget(t),a.render(s,$O)}};function ck(e){let t=[],n=[],r=e,i=e-YO+1+XO;for(let e=0;e<i;e++){let e=2**r;t.push(e);let i=1/(e-2),a=-i,o=1+i,s=[a,a,o,a,o,o,a,a,o,o,a,o],c=/* @__PURE__ */ new Float32Array(108),l=/* @__PURE__ */ new Float32Array(108);for(let e=0;e<6;e++){let t=e%3*2/3-1,n=e>2?0:-1,r=[t,n,0,t+2/3,n,0,t+2/3,n+1,0,t,n,0,t+2/3,n+1,0,t,n+1,0];c.set(r,18*e);for(let t=0;t<6;t++){let n=s[t*2]*2-1,r=s[t*2+1]*2-1;e===0?ok.set(1,r,n):e===1?ok.set(-n,1,-r):e===2?ok.set(-n,r,1):e===3?ok.set(-1,r,-n):e===4?ok.set(-n,-1,r):ok.set(n,r,-1),ok.toArray(l,(e*6+t)*3)}}let u=new JE;u.setAttribute(`position`,new NE(c,3)),u.setAttribute(`outputDirection`,new NE(l,3)),n.push(new vD(u,null)),r>YO&&r--}return{lodMeshes:n,sizeLods:t}}function lk(e,t,n){let r=new mT(e,t,n);return r.texture.mapping=306,r.texture.name=`PMREM.cubeUv`,r.scissorTest=!0,r}function uk(e,t,n,r,i){e.viewport.set(t,n,r,i),e.scissor.set(t,n,r,i)}function dk(e,t,n){return new HD({name:`PMREMGGXConvolution`,defines:{GGX_SAMPLES:QO,CUBEUV_TEXEL_WIDTH:1/t,CUBEUV_TEXEL_HEIGHT:1/n,CUBEUV_MAX_MIP:`${e}.0`},uniforms:{envMap:{value:null},roughness:{value:0},mipInt:{value:0}},vertexShader:hk(),fragmentShader:`
|
|
3826
3826
|
|
|
3827
3827
|
precision highp float;
|
|
3828
3828
|
precision highp int;
|
|
@@ -3926,7 +3926,7 @@ void main() {
|
|
|
3926
3926
|
|
|
3927
3927
|
gl_FragColor = vec4(prefilteredColor, 1.0);
|
|
3928
3928
|
}
|
|
3929
|
-
`,blending:0,depthTest:!1,depthWrite:!1})}function
|
|
3929
|
+
`,blending:0,depthTest:!1,depthWrite:!1})}function fk(e,t,n){return new HD({name:`SphericalGaussianBlur`,defines:{SAMPLES:ZO,CUBEUV_TEXEL_WIDTH:1/t,CUBEUV_TEXEL_HEIGHT:1/n,CUBEUV_MAX_MIP:`${e}.0`},uniforms:{envMap:{value:null},sigma:{value:0},mipInt:{value:0}},vertexShader:hk(),fragmentShader:`
|
|
3930
3930
|
|
|
3931
3931
|
precision highp float;
|
|
3932
3932
|
precision highp int;
|
|
@@ -3986,7 +3986,7 @@ void main() {
|
|
|
3986
3986
|
gl_FragColor = vec4( accumColor / accumWeight, 1.0 );
|
|
3987
3987
|
|
|
3988
3988
|
}
|
|
3989
|
-
`,blending:0,depthTest:!1,depthWrite:!1})}function
|
|
3989
|
+
`,blending:0,depthTest:!1,depthWrite:!1})}function pk(){return new HD({name:`EquirectangularToCubeUV`,uniforms:{envMap:{value:null}},vertexShader:hk(),fragmentShader:`
|
|
3990
3990
|
|
|
3991
3991
|
precision mediump float;
|
|
3992
3992
|
precision mediump int;
|
|
@@ -4005,7 +4005,7 @@ void main() {
|
|
|
4005
4005
|
gl_FragColor = vec4( texture2D ( envMap, uv ).rgb, 1.0 );
|
|
4006
4006
|
|
|
4007
4007
|
}
|
|
4008
|
-
`,blending:0,depthTest:!1,depthWrite:!1})}function
|
|
4008
|
+
`,blending:0,depthTest:!1,depthWrite:!1})}function mk(){return new HD({name:`CubemapToCubeUV`,uniforms:{envMap:{value:null},flipEnvMap:{value:-1}},vertexShader:hk(),fragmentShader:`
|
|
4009
4009
|
|
|
4010
4010
|
precision mediump float;
|
|
4011
4011
|
precision mediump int;
|
|
@@ -4021,7 +4021,7 @@ void main() {
|
|
|
4021
4021
|
gl_FragColor = textureCube( envMap, vec3( flipEnvMap * vOutputDirection.x, vOutputDirection.yz ) );
|
|
4022
4022
|
|
|
4023
4023
|
}
|
|
4024
|
-
`,blending:0,depthTest:!1,depthWrite:!1})}function
|
|
4024
|
+
`,blending:0,depthTest:!1,depthWrite:!1})}function hk(){return`
|
|
4025
4025
|
|
|
4026
4026
|
precision mediump float;
|
|
4027
4027
|
precision mediump int;
|
|
@@ -4036,7 +4036,7 @@ void main() {
|
|
|
4036
4036
|
gl_Position = vec4( position, 1.0 );
|
|
4037
4037
|
|
|
4038
4038
|
}
|
|
4039
|
-
`}var
|
|
4039
|
+
`}var gk=class extends mT{constructor(e=1,t={}){super(e,e,t),this.isWebGLCubeRenderTarget=!0;let n={width:e,height:e,depth:1},r=[n,n,n,n,n,n];this.texture=new OD(r),this._setTextureOptions(t),this.texture.isRenderTargetTexture=!0}fromEquirectangularTexture(e,t){this.texture.type=t.type,this.texture.colorSpace=t.colorSpace,this.texture.generateMipmaps=t.generateMipmaps,this.texture.minFilter=t.minFilter,this.texture.magFilter=t.magFilter;let n={uniforms:{tEquirect:{value:null}},vertexShader:`
|
|
4040
4040
|
|
|
4041
4041
|
varying vec3 vWorldDirection;
|
|
4042
4042
|
|
|
@@ -4071,7 +4071,7 @@ void main() {
|
|
|
4071
4071
|
gl_FragColor = texture2D( tEquirect, sampleUV );
|
|
4072
4072
|
|
|
4073
4073
|
}
|
|
4074
|
-
`},r=new
|
|
4074
|
+
`},r=new MD(5,5,5),i=new HD({name:`CubemapFromEquirect`,uniforms:PD(n.uniforms),vertexShader:n.vertexShader,fragmentShader:n.fragmentShader,side:1,blending:0});i.uniforms.tEquirect.value=t;let a=new vD(r,i),o=t.minFilter;return t.minFilter===1008&&(t.minFilter=iC),new SO(1,10,this).update(e,a),t.minFilter=o,a.geometry.dispose(),a.material.dispose(),this}clear(e,t=!0,n=!0,r=!0){let i=e.getRenderTarget();for(let i=0;i<6;i++)e.setRenderTarget(this,i),e.clear(t,n,r);e.setRenderTarget(i)}};function _k(e){let t=/* @__PURE__ */ new WeakMap,n=/* @__PURE__ */ new WeakMap,r=null;function i(e,t=!1){return e==null?null:t?o(e):a(e)}function a(n){if(n&&n.isTexture){let r=n.mapping;if(r===303||r===304){if(t.has(n)){let e=t.get(n).texture;return s(e,n.mapping)}{let r=n.image;if(r&&r.height>0){let i=new gk(r.height);return i.fromEquirectangularTexture(e,n),t.set(n,i),n.addEventListener(`dispose`,l),s(i.texture,n.mapping)}return null}}}return n}function o(t){if(t&&t.isTexture){let i=t.mapping,a=i===303||i===304,o=i===301||i===302;if(a||o){let i=n.get(t),s=i===void 0?0:i.texture.pmremVersion;if(t.isRenderTargetTexture&&t.pmremVersion!==s)return r===null&&(r=new sk(e)),i=a?r.fromEquirectangular(t,i):r.fromCubemap(t,i),i.texture.pmremVersion=t.pmremVersion,n.set(t,i),i.texture;if(i!==void 0)return i.texture;{let s=t.image;return a&&s&&s.height>0||o&&s&&c(s)?(r===null&&(r=new sk(e)),i=a?r.fromEquirectangular(t):r.fromCubemap(t),i.texture.pmremVersion=t.pmremVersion,n.set(t,i),t.addEventListener(`dispose`,u),i.texture):null}}}return t}function s(e,t){return t===303?e.mapping=301:t===304&&(e.mapping=302),e}function c(e){let t=0;for(let n=0;n<6;n++)e[n]!==void 0&&t++;return t===6}function l(e){let n=e.target;n.removeEventListener(`dispose`,l);let r=t.get(n);r!==void 0&&(t.delete(n),r.dispose())}function u(e){let t=e.target;t.removeEventListener(`dispose`,u);let r=n.get(t);r!==void 0&&(n.delete(t),r.dispose())}function d(){t=/* @__PURE__ */ new WeakMap,n=/* @__PURE__ */ new WeakMap,r!==null&&(r.dispose(),r=null)}return{get:i,dispose:d}}function vk(e){let t={};function n(n){if(t[n]!==void 0)return t[n];let r=e.getExtension(n);return t[n]=r,r}return{has:function(e){return n(e)!==null},init:function(){n(`EXT_color_buffer_float`),n(`WEBGL_clip_cull_distance`),n(`OES_texture_float_linear`),n(`EXT_color_buffer_half_float`),n(`WEBGL_multisampled_render_to_texture`),n(`WEBGL_render_shared_exponent`)},get:function(e){let t=n(e);return t===null&&Fw(`WebGLRenderer: `+e+` extension not supported.`),t}}}function yk(e,t,n,r){let i={},a=/* @__PURE__ */ new WeakMap;function o(e){let s=e.target;s.index!==null&&t.remove(s.index);for(let e in s.attributes)t.remove(s.attributes[e]);s.removeEventListener(`dispose`,o),delete i[s.id];let c=a.get(s);c&&(t.remove(c),a.delete(s)),r.releaseStatesOfGeometry(s),s.isInstancedBufferGeometry===!0&&delete s._maxInstanceCount,n.memory.geometries--}function s(e,t){return i[t.id]===!0?t:(t.addEventListener(`dispose`,o),i[t.id]=!0,n.memory.geometries++,t)}function c(n){let r=n.attributes;for(let n in r)t.update(r[n],e.ARRAY_BUFFER)}function l(e){let n=[],r=e.index,i=e.attributes.position,o=0;if(i===void 0)return;if(r!==null){let e=r.array;o=r.version;for(let t=0,r=e.length;t<r;t+=3){let r=e[t+0],i=e[t+1],a=e[t+2];n.push(r,i,i,a,a,r)}}else{let e=i.array;o=i.version;for(let t=0,r=e.length/3-1;t<r;t+=3){let e=t+0,r=t+1,i=t+2;n.push(e,r,r,i,i,e)}}let s=new(i.count>=65535?FE:PE)(n,1);s.version=o;let c=a.get(e);c&&t.remove(c),a.set(e,s)}function u(e){let t=a.get(e);if(t){let n=e.index;n!==null&&t.version<n.version&&l(e)}else l(e);return a.get(e)}return{get:s,update:c,getWireframeAttribute:u}}function bk(e,t,n){let r;function i(e){r=e}let a,o;function s(e){a=e.type,o=e.bytesPerElement}function c(t,i){e.drawElements(r,i,a,t*o),n.update(i,r,1)}function l(t,i,s){s!==0&&(e.drawElementsInstanced(r,i,a,t*o,s),n.update(i,r,s))}function u(e,i,o){if(o===0)return;t.get(`WEBGL_multi_draw`).multiDrawElementsWEBGL(r,i,0,a,e,0,o);let s=0;for(let e=0;e<o;e++)s+=i[e];n.update(s,r,1)}this.setMode=i,this.setIndex=s,this.render=c,this.renderInstances=l,this.renderMultiDraw=u}function xk(e){let t={geometries:0,textures:0},n={frame:0,calls:0,triangles:0,points:0,lines:0};function r(t,r,i){switch(n.calls++,r){case e.TRIANGLES:n.triangles+=t/3*i;break;case e.LINES:n.lines+=t/2*i;break;case e.LINE_STRIP:n.lines+=i*(t-1);break;case e.LINE_LOOP:n.lines+=i*t;break;case e.POINTS:n.points+=i*t;break;default:J(`WebGLInfo: Unknown draw mode:`,r)}}function i(){n.calls=0,n.triangles=0,n.points=0,n.lines=0}return{memory:t,render:n,programs:null,autoReset:!0,reset:i,update:r}}function Sk(e,t,n){let r=/* @__PURE__ */ new WeakMap,i=new fT;function a(a,o,s){let c=a.morphTargetInfluences,l=o.morphAttributes.position||o.morphAttributes.normal||o.morphAttributes.color,u=l===void 0?0:l.length,d=r.get(o);if(d===void 0||d.count!==u){d!==void 0&&d.texture.dispose();let e=o.morphAttributes.position!==void 0,n=o.morphAttributes.normal!==void 0,a=o.morphAttributes.color!==void 0,s=o.morphAttributes.position||[],c=o.morphAttributes.normal||[],l=o.morphAttributes.color||[],f=0;e===!0&&(f=1),n===!0&&(f=2),a===!0&&(f=3);let p=o.attributes.position.count*f,m=1;p>t.maxTextureSize&&(m=Math.ceil(p/t.maxTextureSize),p=t.maxTextureSize);let h=new Float32Array(p*m*4*u),g=new hT(h,p,m,u);g.type=pC,g.needsUpdate=!0;let _=f*4;for(let t=0;t<u;t++){let r=s[t],o=c[t],u=l[t],d=p*m*4*t;for(let t=0;t<r.count;t++){let s=t*_;e===!0&&(i.fromBufferAttribute(r,t),h[d+s+0]=i.x,h[d+s+1]=i.y,h[d+s+2]=i.z,h[d+s+3]=0),n===!0&&(i.fromBufferAttribute(o,t),h[d+s+4]=i.x,h[d+s+5]=i.y,h[d+s+6]=i.z,h[d+s+7]=0),a===!0&&(i.fromBufferAttribute(u,t),h[d+s+8]=i.x,h[d+s+9]=i.y,h[d+s+10]=i.z,h[d+s+11]=u.itemSize===4?i.w:1)}}d={count:u,texture:g,size:new Y(p,m)},r.set(o,d);function v(){g.dispose(),r.delete(o),o.removeEventListener(`dispose`,v)}o.addEventListener(`dispose`,v)}if(a.isInstancedMesh===!0&&a.morphTexture!==null)s.getUniforms().setValue(e,`morphTexture`,a.morphTexture,n);else{let t=0;for(let e=0;e<c.length;e++)t+=c[e];let n=o.morphTargetsRelative?1:1-t;s.getUniforms().setValue(e,`morphTargetBaseInfluence`,n),s.getUniforms().setValue(e,`morphTargetInfluences`,c)}s.getUniforms().setValue(e,`morphTargetsTexture`,d.texture,n),s.getUniforms().setValue(e,`morphTargetsTextureSize`,d.size)}return{update:a}}function Ck(e,t,n,r,i){let a=/* @__PURE__ */ new WeakMap;function o(r){let o=i.render.frame,s=r.geometry,l=t.get(r,s);if(a.get(l)!==o&&(t.update(l),a.set(l,o)),r.isInstancedMesh&&(r.hasEventListener(`dispose`,c)===!1&&r.addEventListener(`dispose`,c),a.get(r)!==o&&(n.update(r.instanceMatrix,e.ARRAY_BUFFER),r.instanceColor!==null&&n.update(r.instanceColor,e.ARRAY_BUFFER),a.set(r,o))),r.isSkinnedMesh){let e=r.skeleton;a.get(e)!==o&&(e.update(),a.set(e,o))}return l}function s(){a=/* @__PURE__ */ new WeakMap}function c(e){let t=e.target;t.removeEventListener(`dispose`,c),r.releaseStatesOfObject(t),n.remove(t.instanceMatrix),t.instanceColor!==null&&n.remove(t.instanceColor)}return{update:o,dispose:s}}var wk={1:`LINEAR_TONE_MAPPING`,2:`REINHARD_TONE_MAPPING`,3:`CINEON_TONE_MAPPING`,4:`ACES_FILMIC_TONE_MAPPING`,6:`AGX_TONE_MAPPING`,7:`NEUTRAL_TONE_MAPPING`,5:`CUSTOM_TONE_MAPPING`};function Tk(e,t,n,r,i,a){let o=new mT(t,n,{type:e,depthBuffer:i,stencilBuffer:a,samples:r?4:0,storeMultisampledDepthBuffer:!1,storeMultisampledStencilBuffer:!1,resolveDepthBuffer:!1,resolveStencilBuffer:!1}),s=null,c=null,l=new JE;l.setAttribute(`position`,new IE([-1,3,0,-1,-1,0,3,-1,0],3)),l.setAttribute(`uv`,new IE([0,2,0,0,2,0],2));let u=new UD({uniforms:{tDiffuse:{value:null}},vertexShader:`
|
|
4075
4075
|
precision highp float;
|
|
4076
4076
|
|
|
4077
4077
|
uniform mat4 modelViewMatrix;
|
|
@@ -4117,17 +4117,17 @@ void main() {
|
|
|
4117
4117
|
#ifdef SRGB_TRANSFER
|
|
4118
4118
|
gl_FragColor = sRGBTransferOETF( gl_FragColor );
|
|
4119
4119
|
#endif
|
|
4120
|
-
}`,depthTest:!1,depthWrite:!1}),d=new
|
|
4120
|
+
}`,depthTest:!1,depthWrite:!1}),d=new vD(l,u),f=new yO(-1,1,1,-1,0,1),p=null,m=null,h=!1,g,_=null,v=[],y=!1;this.setSize=function(e,t){o.setSize(e,t),s!==null&&s.setSize(e,t),c!==null&&c.setSize(e,t);for(let n=0;n<v.length;n++){let r=v[n];r.setSize&&r.setSize(e,t)}},this.setEffects=function(e){v=e,y=v.length>0&&v[0].isRenderPass===!0;let t=o.width,n=o.height;v.length>0&&s===null&&(s=new mT(t,n,{type:mC,depthBuffer:!1,stencilBuffer:!1}),c=new mT(t,n,{type:mC,depthBuffer:!1,stencilBuffer:!1}));for(let e=0;e<v.length;e++){let r=v[e];r.setSize&&r.setSize(t,n)}},this.begin=function(e,t){if(h||e.toneMapping===0&&v.length===0)return!1;if(_=t,t!==null){let e=t.width,n=t.height;(o.width!==e||o.height!==n)&&this.setSize(e,n)}return y===!1&&e.setRenderTarget(o),g=e.toneMapping,e.toneMapping=0,!0},this.hasRenderPass=function(){return y},this.end=function(e,t){e.toneMapping=g,h=!0;let n=o,r=s;for(let i=0;i<v.length;i++){let a=v[i];a.enabled!==!1&&(a.render(e,r,n,t),a.needsSwap!==!1&&(n=r,r=r===s?c:s))}if(p!==e.outputColorSpace||m!==e.toneMapping){p=e.outputColorSpace,m=e.toneMapping,u.defines={},tT.getTransfer(p)===`srgb`&&(u.defines.SRGB_TRANSFER=``);let t=wk[m];t&&(u.defines[t]=``),u.needsUpdate=!0}u.uniforms.tDiffuse.value=n.texture,e.setRenderTarget(_),e.render(d,f),_=null,h=!1},this.isCompositing=function(){return h},this.dispose=function(){o.dispose(),s!==null&&s.dispose(),c!==null&&c.dispose(),l.dispose(),u.dispose()}}var Ek=/*@__PURE__*/ new dT,Dk=/*@__PURE__*/ new kD(1,1),Ok=/*@__PURE__*/ new hT,kk=/*@__PURE__*/ new gT,Ak=/*@__PURE__*/ new OD,jk=[],Mk=[],Nk=/* @__PURE__ */ new Float32Array(16),Pk=/* @__PURE__ */ new Float32Array(9),Fk=/* @__PURE__ */ new Float32Array(4);function Ik(e,t,n){let r=e[0];if(r<=0||r>0)return e;let i=t*n,a=jk[i];if(a===void 0&&(a=new Float32Array(i),jk[i]=a),t!==0){r.toArray(a,0);for(let r=1,i=0;r!==t;++r)i+=n,e[r].toArray(a,i)}return a}function Lk(e,t){if(e.length!==t.length)return!1;for(let n=0,r=e.length;n<r;n++)if(e[n]!==t[n])return!1;return!0}function Rk(e,t){for(let n=0,r=t.length;n<r;n++)e[n]=t[n]}function zk(e,t){let n=Mk[t];n===void 0&&(n=new Int32Array(t),Mk[t]=n);for(let r=0;r!==t;++r)n[r]=e.allocateTextureUnit();return n}function Bk(e,t){let n=this.cache;n[0]!==t&&(e.uniform1f(this.addr,t),n[0]=t)}function Vk(e,t){let n=this.cache;if(t.x!==void 0)(n[0]!==t.x||n[1]!==t.y)&&(e.uniform2f(this.addr,t.x,t.y),n[0]=t.x,n[1]=t.y);else{if(Lk(n,t))return;e.uniform2fv(this.addr,t),Rk(n,t)}}function Hk(e,t){let n=this.cache;if(t.x!==void 0)(n[0]!==t.x||n[1]!==t.y||n[2]!==t.z)&&(e.uniform3f(this.addr,t.x,t.y,t.z),n[0]=t.x,n[1]=t.y,n[2]=t.z);else if(t.r!==void 0)(n[0]!==t.r||n[1]!==t.g||n[2]!==t.b)&&(e.uniform3f(this.addr,t.r,t.g,t.b),n[0]=t.r,n[1]=t.g,n[2]=t.b);else{if(Lk(n,t))return;e.uniform3fv(this.addr,t),Rk(n,t)}}function Uk(e,t){let n=this.cache;if(t.x!==void 0)(n[0]!==t.x||n[1]!==t.y||n[2]!==t.z||n[3]!==t.w)&&(e.uniform4f(this.addr,t.x,t.y,t.z,t.w),n[0]=t.x,n[1]=t.y,n[2]=t.z,n[3]=t.w);else{if(Lk(n,t))return;e.uniform4fv(this.addr,t),Rk(n,t)}}function Wk(e,t){let n=this.cache,r=t.elements;if(r===void 0){if(Lk(n,t))return;e.uniformMatrix2fv(this.addr,!1,t),Rk(n,t)}else{if(Lk(n,r))return;Fk.set(r),e.uniformMatrix2fv(this.addr,!1,Fk),Rk(n,r)}}function Gk(e,t){let n=this.cache,r=t.elements;if(r===void 0){if(Lk(n,t))return;e.uniformMatrix3fv(this.addr,!1,t),Rk(n,t)}else{if(Lk(n,r))return;Pk.set(r),e.uniformMatrix3fv(this.addr,!1,Pk),Rk(n,r)}}function Kk(e,t){let n=this.cache,r=t.elements;if(r===void 0){if(Lk(n,t))return;e.uniformMatrix4fv(this.addr,!1,t),Rk(n,t)}else{if(Lk(n,r))return;Nk.set(r),e.uniformMatrix4fv(this.addr,!1,Nk),Rk(n,r)}}function qk(e,t){let n=this.cache;n[0]!==t&&(e.uniform1i(this.addr,t),n[0]=t)}function Jk(e,t){let n=this.cache;if(t.x!==void 0)(n[0]!==t.x||n[1]!==t.y)&&(e.uniform2i(this.addr,t.x,t.y),n[0]=t.x,n[1]=t.y);else{if(Lk(n,t))return;e.uniform2iv(this.addr,t),Rk(n,t)}}function Yk(e,t){let n=this.cache;if(t.x!==void 0)(n[0]!==t.x||n[1]!==t.y||n[2]!==t.z)&&(e.uniform3i(this.addr,t.x,t.y,t.z),n[0]=t.x,n[1]=t.y,n[2]=t.z);else{if(Lk(n,t))return;e.uniform3iv(this.addr,t),Rk(n,t)}}function Xk(e,t){let n=this.cache;if(t.x!==void 0)(n[0]!==t.x||n[1]!==t.y||n[2]!==t.z||n[3]!==t.w)&&(e.uniform4i(this.addr,t.x,t.y,t.z,t.w),n[0]=t.x,n[1]=t.y,n[2]=t.z,n[3]=t.w);else{if(Lk(n,t))return;e.uniform4iv(this.addr,t),Rk(n,t)}}function Zk(e,t){let n=this.cache;n[0]!==t&&(e.uniform1ui(this.addr,t),n[0]=t)}function Qk(e,t){let n=this.cache;if(t.x!==void 0)(n[0]!==t.x||n[1]!==t.y)&&(e.uniform2ui(this.addr,t.x,t.y),n[0]=t.x,n[1]=t.y);else{if(Lk(n,t))return;e.uniform2uiv(this.addr,t),Rk(n,t)}}function $k(e,t){let n=this.cache;if(t.x!==void 0)(n[0]!==t.x||n[1]!==t.y||n[2]!==t.z)&&(e.uniform3ui(this.addr,t.x,t.y,t.z),n[0]=t.x,n[1]=t.y,n[2]=t.z);else{if(Lk(n,t))return;e.uniform3uiv(this.addr,t),Rk(n,t)}}function eA(e,t){let n=this.cache;if(t.x!==void 0)(n[0]!==t.x||n[1]!==t.y||n[2]!==t.z||n[3]!==t.w)&&(e.uniform4ui(this.addr,t.x,t.y,t.z,t.w),n[0]=t.x,n[1]=t.y,n[2]=t.z,n[3]=t.w);else{if(Lk(n,t))return;e.uniform4uiv(this.addr,t),Rk(n,t)}}function tA(e,t,n){let r=this.cache,i=n.allocateTextureUnit();r[0]!==i&&(e.uniform1i(this.addr,i),r[0]=i);let a;this.type===e.SAMPLER_2D_SHADOW?(Dk.compareFunction=n.isReversedDepthBuffer()?518:515,a=Dk):a=Ek,n.setTexture2D(t||a,i)}function nA(e,t,n){let r=this.cache,i=n.allocateTextureUnit();r[0]!==i&&(e.uniform1i(this.addr,i),r[0]=i),n.setTexture3D(t||kk,i)}function rA(e,t,n){let r=this.cache,i=n.allocateTextureUnit();r[0]!==i&&(e.uniform1i(this.addr,i),r[0]=i),n.setTextureCube(t||Ak,i)}function iA(e,t,n){let r=this.cache,i=n.allocateTextureUnit();r[0]!==i&&(e.uniform1i(this.addr,i),r[0]=i),n.setTexture2DArray(t||Ok,i)}function aA(e){switch(e){case 5126:return Bk;case 35664:return Vk;case 35665:return Hk;case 35666:return Uk;case 35674:return Wk;case 35675:return Gk;case 35676:return Kk;case 5124:case 35670:return qk;case 35667:case 35671:return Jk;case 35668:case 35672:return Yk;case 35669:case 35673:return Xk;case 5125:return Zk;case 36294:return Qk;case 36295:return $k;case 36296:return eA;case 35678:case 36198:case 36298:case 36306:case 35682:return tA;case 35679:case 36299:case 36307:return nA;case 35680:case 36300:case 36308:case 36293:return rA;case 36289:case 36303:case 36311:case 36292:return iA}}function oA(e,t){e.uniform1fv(this.addr,t)}function sA(e,t){let n=Ik(t,this.size,2);e.uniform2fv(this.addr,n)}function cA(e,t){let n=Ik(t,this.size,3);e.uniform3fv(this.addr,n)}function lA(e,t){let n=Ik(t,this.size,4);e.uniform4fv(this.addr,n)}function uA(e,t){let n=Ik(t,this.size,4);e.uniformMatrix2fv(this.addr,!1,n)}function dA(e,t){let n=Ik(t,this.size,9);e.uniformMatrix3fv(this.addr,!1,n)}function fA(e,t){let n=Ik(t,this.size,16);e.uniformMatrix4fv(this.addr,!1,n)}function pA(e,t){e.uniform1iv(this.addr,t)}function mA(e,t){e.uniform2iv(this.addr,t)}function hA(e,t){e.uniform3iv(this.addr,t)}function gA(e,t){e.uniform4iv(this.addr,t)}function _A(e,t){e.uniform1uiv(this.addr,t)}function vA(e,t){e.uniform2uiv(this.addr,t)}function yA(e,t){e.uniform3uiv(this.addr,t)}function bA(e,t){e.uniform4uiv(this.addr,t)}function xA(e,t,n){let r=this.cache,i=t.length,a=zk(n,i);Lk(r,a)||(e.uniform1iv(this.addr,a),Rk(r,a));let o;o=this.type===e.SAMPLER_2D_SHADOW?Dk:Ek;for(let e=0;e!==i;++e)n.setTexture2D(t[e]||o,a[e])}function SA(e,t,n){let r=this.cache,i=t.length,a=zk(n,i);Lk(r,a)||(e.uniform1iv(this.addr,a),Rk(r,a));for(let e=0;e!==i;++e)n.setTexture3D(t[e]||kk,a[e])}function CA(e,t,n){let r=this.cache,i=t.length,a=zk(n,i);Lk(r,a)||(e.uniform1iv(this.addr,a),Rk(r,a));for(let e=0;e!==i;++e)n.setTextureCube(t[e]||Ak,a[e])}function wA(e,t,n){let r=this.cache,i=t.length,a=zk(n,i);Lk(r,a)||(e.uniform1iv(this.addr,a),Rk(r,a));for(let e=0;e!==i;++e)n.setTexture2DArray(t[e]||Ok,a[e])}function TA(e){switch(e){case 5126:return oA;case 35664:return sA;case 35665:return cA;case 35666:return lA;case 35674:return uA;case 35675:return dA;case 35676:return fA;case 5124:case 35670:return pA;case 35667:case 35671:return mA;case 35668:case 35672:return hA;case 35669:case 35673:return gA;case 5125:return _A;case 36294:return vA;case 36295:return yA;case 36296:return bA;case 35678:case 36198:case 36298:case 36306:case 35682:return xA;case 35679:case 36299:case 36307:return SA;case 35680:case 36300:case 36308:case 36293:return CA;case 36289:case 36303:case 36311:case 36292:return wA}}var EA=class{constructor(e,t,n){this.id=e,this.addr=n,this.cache=[],this.type=t.type,this.setValue=aA(t.type)}},DA=class{constructor(e,t,n){this.id=e,this.addr=n,this.cache=[],this.type=t.type,this.size=t.size,this.setValue=TA(t.type)}},OA=class{constructor(e){this.id=e,this.seq=[],this.map={}}setValue(e,t,n){let r=this.seq;for(let i=0,a=r.length;i!==a;++i){let a=r[i];a.setValue(e,t[a.id],n)}}},kA=/(\w+)(\])?(\[|\.)?/g;function AA(e,t){e.seq.push(t),e.map[t.id]=t}function jA(e,t,n){let r=e.name,i=r.length;for(kA.lastIndex=0;;){let a=kA.exec(r),o=kA.lastIndex,s=a[1],c=a[2]===`]`,l=a[3];if(c&&(s|=0),l===void 0||l===`[`&&o+2===i){AA(n,l===void 0?new EA(s,e,t):new DA(s,e,t));break}{let e=n.map[s];e===void 0&&(e=new OA(s),AA(n,e)),n=e}}}var MA=class{constructor(e,t){this.seq=[],this.map={};let n=e.getProgramParameter(t,e.ACTIVE_UNIFORMS);for(let r=0;r<n;++r){let n=e.getActiveUniform(t,r);jA(n,e.getUniformLocation(t,n.name),this)}let r=[],i=[];for(let t of this.seq)t.type===e.SAMPLER_2D_SHADOW||t.type===e.SAMPLER_CUBE_SHADOW||t.type===e.SAMPLER_2D_ARRAY_SHADOW?r.push(t):i.push(t);r.length>0&&(this.seq=r.concat(i))}setValue(e,t,n,r){let i=this.map[t];i!==void 0&&i.setValue(e,n,r)}setOptional(e,t,n){let r=t[n];r!==void 0&&this.setValue(e,n,r)}static upload(e,t,n,r){for(let i=0,a=t.length;i!==a;++i){let a=t[i],o=n[a.id];o.needsUpdate!==!1&&a.setValue(e,o.value,r)}}static seqWithValue(e,t){let n=[];for(let r=0,i=e.length;r!==i;++r){let i=e[r];i.id in t&&n.push(i)}return n}};function NA(e,t,n){let r=e.createShader(t);return e.shaderSource(r,n),e.compileShader(r),r}var PA=37297,FA=0;function IA(e,t){let n=e.split(`
|
|
4121
4121
|
`),r=[],i=Math.max(t-6,0),a=Math.min(t+6,n.length);for(let e=i;e<a;e++){let i=e+1;r.push(`${i===t?`>`:` `} ${i}: ${n[e]}`)}return r.join(`
|
|
4122
|
-
`)}var
|
|
4122
|
+
`)}var LA=/*@__PURE__*/ new Z;function RA(e){tT._getMatrix(LA,tT.workingColorSpace,e);let t=`mat3( ${LA.elements.map(e=>e.toFixed(4))} )`;switch(tT.getTransfer(e)){case Sw:return[t,`LinearTransferOETF`];case Cw:return[t,`sRGBTransferOETF`];default:return q(`WebGLProgram: Unsupported color space: `,e),[t,`LinearTransferOETF`]}}function zA(e,t,n){let r=e.getShaderParameter(t,e.COMPILE_STATUS),i=(e.getShaderInfoLog(t)||``).trim();if(r&&i===``)return``;let a=/ERROR: 0:(\d+)/.exec(i);if(a){let r=parseInt(a[1]);return n.toUpperCase()+`
|
|
4123
4123
|
|
|
4124
4124
|
`+i+`
|
|
4125
4125
|
|
|
4126
|
-
`+
|
|
4127
|
-
`)}var
|
|
4128
|
-
`)}function
|
|
4129
|
-
`)}function
|
|
4130
|
-
`)}function
|
|
4126
|
+
`+IA(e.getShaderSource(t),r)}return i}function BA(e,t){let n=RA(t);return[`vec4 ${e}( vec4 value ) {`,` return ${n[1]}( vec4( value.rgb * ${n[0]}, value.a ) );`,`}`].join(`
|
|
4127
|
+
`)}var VA={1:`Linear`,2:`Reinhard`,3:`Cineon`,4:`ACESFilmic`,6:`AgX`,7:`Neutral`,5:`Custom`};function HA(e,t){let n=VA[t];return n===void 0?(q(`WebGLProgram: Unsupported toneMapping:`,t),`vec3 `+e+`( vec3 color ) { return LinearToneMapping( color ); }`):`vec3 `+e+`( vec3 color ) { return `+n+`ToneMapping( color ); }`}var UA=/*@__PURE__*/ new X;function WA(){return tT.getLuminanceCoefficients(UA),[`float luminance( const in vec3 rgb ) {`,` const vec3 weights = vec3( ${UA.x.toFixed(4)}, ${UA.y.toFixed(4)}, ${UA.z.toFixed(4)} );`,` return dot( weights, rgb );`,`}`].join(`
|
|
4128
|
+
`)}function GA(e){return[e.extensionClipCullDistance?`#extension GL_ANGLE_clip_cull_distance : require`:``,e.extensionMultiDraw?`#extension GL_ANGLE_multi_draw : require`:``].filter(JA).join(`
|
|
4129
|
+
`)}function KA(e){let t=[];for(let n in e){let r=e[n];r!==!1&&t.push(`#define `+n+` `+r)}return t.join(`
|
|
4130
|
+
`)}function qA(e,t){let n={},r=e.getProgramParameter(t,e.ACTIVE_ATTRIBUTES);for(let i=0;i<r;i++){let r=e.getActiveAttrib(t,i),a=r.name,o=1;r.type===e.FLOAT_MAT2&&(o=2),r.type===e.FLOAT_MAT3&&(o=3),r.type===e.FLOAT_MAT4&&(o=4),n[a]={type:r.type,location:e.getAttribLocation(t,a),locationSize:o}}return n}function JA(e){return e!==``}function YA(e,t){let n=t.numSpotLightShadows+t.numSpotLightMaps-t.numSpotLightShadowsWithMaps;return e.replace(/NUM_SUN_LIGHTS/g,t.numSunLights).replace(/NUM_DIR_LIGHTS/g,t.numDirLights).replace(/NUM_SPOT_LIGHTS/g,t.numSpotLights).replace(/NUM_SPOT_LIGHT_MAPS/g,t.numSpotLightMaps).replace(/NUM_SPOT_LIGHT_COORDS/g,n).replace(/NUM_RECT_AREA_LIGHTS/g,t.numRectAreaLights).replace(/NUM_POINT_LIGHTS/g,t.numPointLights).replace(/NUM_HEMI_LIGHTS/g,t.numHemiLights).replace(/NUM_SUN_LIGHT_SHADOWS/g,t.numSunLightShadows).replace(/NUM_DIR_LIGHT_SHADOWS/g,t.numDirLightShadows).replace(/NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS/g,t.numSpotLightShadowsWithMaps).replace(/NUM_SPOT_LIGHT_SHADOWS/g,t.numSpotLightShadows).replace(/NUM_POINT_LIGHT_SHADOWS/g,t.numPointLightShadows)}function XA(e,t){return e.replace(/NUM_CLIPPING_PLANES/g,t.numClippingPlanes).replace(/UNION_CLIPPING_PLANES/g,t.numClippingPlanes-t.numClipIntersection)}var ZA=/^[ \t]*#include +<([\w\d./]+)>/gm;function QA(e){return e.replace(ZA,ej)}var $A=/* @__PURE__ */ new Map;function ej(e,t){let n=Q[t];if(n===void 0){let e=$A.get(t);if(e!==void 0)n=Q[e],q(`WebGLRenderer: Shader chunk "%s" has been deprecated. Use "%s" instead.`,t,e);else throw Error(`THREE.WebGLProgram: Can not resolve #include <`+t+`>`)}return QA(n)}var tj=/#pragma unroll_loop_start\s+for\s*\(\s*int\s+i\s*=\s*(\d+)\s*;\s*i\s*<\s*(\d+)\s*;\s*i\s*\+\+\s*\)\s*{([\s\S]+?)}\s+#pragma unroll_loop_end/g;function nj(e){return e.replace(tj,rj)}function rj(e,t,n,r){let i=``;for(let e=parseInt(t);e<parseInt(n);e++)i+=r.replace(/\[\s*i\s*\]/g,`[ `+e+` ]`).replace(/UNROLLED_LOOP_INDEX/g,e);return i}function ij(e){let t=`precision ${e.precision} float;
|
|
4131
4131
|
precision ${e.precision} int;
|
|
4132
4132
|
precision ${e.precision} sampler2D;
|
|
4133
4133
|
precision ${e.precision} samplerCube;
|
|
@@ -4147,30 +4147,30 @@ void main() {
|
|
|
4147
4147
|
`;return e.precision===`highp`?t+=`
|
|
4148
4148
|
#define HIGH_PRECISION`:e.precision===`mediump`?t+=`
|
|
4149
4149
|
#define MEDIUM_PRECISION`:e.precision===`lowp`&&(t+=`
|
|
4150
|
-
#define LOW_PRECISION`),t}var
|
|
4151
|
-
`:``;n.isRawShaderMaterial?(g=[`#define SHADER_TYPE `+n.shaderType,`#define SHADER_NAME `+n.shaderName,m].filter(
|
|
4150
|
+
#define LOW_PRECISION`),t}var aj={1:`SHADOWMAP_TYPE_PCF`,3:`SHADOWMAP_TYPE_VSM`};function oj(e){return aj[e.shadowMapType]||`SHADOWMAP_TYPE_BASIC`}var sj={301:`ENVMAP_TYPE_CUBE`,302:`ENVMAP_TYPE_CUBE`,306:`ENVMAP_TYPE_CUBE_UV`};function cj(e){return e.envMap===!1?`ENVMAP_TYPE_CUBE`:sj[e.envMapMode]||`ENVMAP_TYPE_CUBE`}var lj={302:`ENVMAP_MODE_REFRACTION`};function uj(e){return e.envMap===!1?`ENVMAP_MODE_REFLECTION`:lj[e.envMapMode]||`ENVMAP_MODE_REFLECTION`}var dj={0:`ENVMAP_BLENDING_MULTIPLY`,1:`ENVMAP_BLENDING_MIX`,2:`ENVMAP_BLENDING_ADD`};function fj(e){return e.envMap===!1?`ENVMAP_BLENDING_NONE`:dj[e.combine]||`ENVMAP_BLENDING_NONE`}function pj(e){let t=e.envMapCubeUVHeight;if(t===null)return null;let n=Math.log2(t)-2,r=1/t;return{texelWidth:1/(3*Math.max(2**n,112)),texelHeight:r,maxMip:n}}function mj(e,t,n,r){let i=e.getContext(),a=n.defines,o=n.vertexShader,s=n.fragmentShader,c=oj(n),l=cj(n),u=uj(n),d=fj(n),f=pj(n),p=GA(n),m=KA(a),h=i.createProgram(),g,_,v=n.glslVersion?`#version `+n.glslVersion+`
|
|
4151
|
+
`:``;n.isRawShaderMaterial?(g=[`#define SHADER_TYPE `+n.shaderType,`#define SHADER_NAME `+n.shaderName,m].filter(JA).join(`
|
|
4152
4152
|
`),g.length>0&&(g+=`
|
|
4153
|
-
`),_=[`#define SHADER_TYPE `+n.shaderType,`#define SHADER_NAME `+n.shaderName,m].filter(
|
|
4153
|
+
`),_=[`#define SHADER_TYPE `+n.shaderType,`#define SHADER_NAME `+n.shaderName,m].filter(JA).join(`
|
|
4154
4154
|
`),_.length>0&&(_+=`
|
|
4155
|
-
`)):(g=[
|
|
4156
|
-
`].filter(
|
|
4157
|
-
`),_=[
|
|
4158
|
-
`].filter(
|
|
4159
|
-
`)),o=
|
|
4155
|
+
`)):(g=[ij(n),`#define SHADER_TYPE `+n.shaderType,`#define SHADER_NAME `+n.shaderName,m,n.extensionClipCullDistance?`#define USE_CLIP_DISTANCE`:``,n.batching?`#define USE_BATCHING`:``,n.batchingColor?`#define USE_BATCHING_COLOR`:``,n.instancing?`#define USE_INSTANCING`:``,n.instancingColor?`#define USE_INSTANCING_COLOR`:``,n.instancingMorph?`#define USE_INSTANCING_MORPH`:``,n.useFog&&n.fog?`#define USE_FOG`:``,n.useFog&&n.fogExp2?`#define FOG_EXP2`:``,n.map?`#define USE_MAP`:``,n.envMap?`#define USE_ENVMAP`:``,n.envMap?`#define `+u:``,n.lightMap?`#define USE_LIGHTMAP`:``,n.aoMap?`#define USE_AOMAP`:``,n.bumpMap?`#define USE_BUMPMAP`:``,n.normalMap?`#define USE_NORMALMAP`:``,n.normalMapObjectSpace?`#define USE_NORMALMAP_OBJECTSPACE`:``,n.normalMapTangentSpace?`#define USE_NORMALMAP_TANGENTSPACE`:``,n.displacementMap?`#define USE_DISPLACEMENTMAP`:``,n.emissiveMap?`#define USE_EMISSIVEMAP`:``,n.anisotropy?`#define USE_ANISOTROPY`:``,n.anisotropyMap?`#define USE_ANISOTROPYMAP`:``,n.clearcoatMap?`#define USE_CLEARCOATMAP`:``,n.clearcoatRoughnessMap?`#define USE_CLEARCOAT_ROUGHNESSMAP`:``,n.clearcoatNormalMap?`#define USE_CLEARCOAT_NORMALMAP`:``,n.iridescenceMap?`#define USE_IRIDESCENCEMAP`:``,n.iridescenceThicknessMap?`#define USE_IRIDESCENCE_THICKNESSMAP`:``,n.specularMap?`#define USE_SPECULARMAP`:``,n.specularColorMap?`#define USE_SPECULAR_COLORMAP`:``,n.specularIntensityMap?`#define USE_SPECULAR_INTENSITYMAP`:``,n.roughnessMap?`#define USE_ROUGHNESSMAP`:``,n.metalnessMap?`#define USE_METALNESSMAP`:``,n.alphaMap?`#define USE_ALPHAMAP`:``,n.alphaHash?`#define USE_ALPHAHASH`:``,n.transmission?`#define USE_TRANSMISSION`:``,n.transmissionMap?`#define USE_TRANSMISSIONMAP`:``,n.thicknessMap?`#define USE_THICKNESSMAP`:``,n.sheenColorMap?`#define USE_SHEEN_COLORMAP`:``,n.sheenRoughnessMap?`#define USE_SHEEN_ROUGHNESSMAP`:``,n.mapUv?`#define MAP_UV `+n.mapUv:``,n.alphaMapUv?`#define ALPHAMAP_UV `+n.alphaMapUv:``,n.lightMapUv?`#define LIGHTMAP_UV `+n.lightMapUv:``,n.aoMapUv?`#define AOMAP_UV `+n.aoMapUv:``,n.emissiveMapUv?`#define EMISSIVEMAP_UV `+n.emissiveMapUv:``,n.bumpMapUv?`#define BUMPMAP_UV `+n.bumpMapUv:``,n.normalMapUv?`#define NORMALMAP_UV `+n.normalMapUv:``,n.displacementMapUv?`#define DISPLACEMENTMAP_UV `+n.displacementMapUv:``,n.metalnessMapUv?`#define METALNESSMAP_UV `+n.metalnessMapUv:``,n.roughnessMapUv?`#define ROUGHNESSMAP_UV `+n.roughnessMapUv:``,n.anisotropyMapUv?`#define ANISOTROPYMAP_UV `+n.anisotropyMapUv:``,n.clearcoatMapUv?`#define CLEARCOATMAP_UV `+n.clearcoatMapUv:``,n.clearcoatNormalMapUv?`#define CLEARCOAT_NORMALMAP_UV `+n.clearcoatNormalMapUv:``,n.clearcoatRoughnessMapUv?`#define CLEARCOAT_ROUGHNESSMAP_UV `+n.clearcoatRoughnessMapUv:``,n.iridescenceMapUv?`#define IRIDESCENCEMAP_UV `+n.iridescenceMapUv:``,n.iridescenceThicknessMapUv?`#define IRIDESCENCE_THICKNESSMAP_UV `+n.iridescenceThicknessMapUv:``,n.sheenColorMapUv?`#define SHEEN_COLORMAP_UV `+n.sheenColorMapUv:``,n.sheenRoughnessMapUv?`#define SHEEN_ROUGHNESSMAP_UV `+n.sheenRoughnessMapUv:``,n.specularMapUv?`#define SPECULARMAP_UV `+n.specularMapUv:``,n.specularColorMapUv?`#define SPECULAR_COLORMAP_UV `+n.specularColorMapUv:``,n.specularIntensityMapUv?`#define SPECULAR_INTENSITYMAP_UV `+n.specularIntensityMapUv:``,n.transmissionMapUv?`#define TRANSMISSIONMAP_UV `+n.transmissionMapUv:``,n.thicknessMapUv?`#define THICKNESSMAP_UV `+n.thicknessMapUv:``,n.vertexTangents&&n.flatShading===!1?`#define USE_TANGENT`:``,n.vertexNormals?`#define HAS_NORMAL`:``,n.vertexColors?`#define USE_COLOR`:``,n.vertexAlphas?`#define USE_COLOR_ALPHA`:``,n.vertexUv1s?`#define USE_UV1`:``,n.vertexUv2s?`#define USE_UV2`:``,n.vertexUv3s?`#define USE_UV3`:``,n.pointsUvs?`#define USE_POINTS_UV`:``,n.flatShading?`#define FLAT_SHADED`:``,n.skinning?`#define USE_SKINNING`:``,n.morphTargets?`#define USE_MORPHTARGETS`:``,n.morphNormals&&n.flatShading===!1?`#define USE_MORPHNORMALS`:``,n.morphColors?`#define USE_MORPHCOLORS`:``,n.morphTargetsCount>0?`#define MORPHTARGETS_TEXTURE_STRIDE `+n.morphTextureStride:``,n.morphTargetsCount>0?`#define MORPHTARGETS_COUNT `+n.morphTargetsCount:``,n.doubleSided?`#define DOUBLE_SIDED`:``,n.flipSided?`#define FLIP_SIDED`:``,n.shadowMapEnabled?`#define USE_SHADOWMAP`:``,n.shadowMapEnabled?`#define `+c:``,n.sizeAttenuation?`#define USE_SIZEATTENUATION`:``,n.numLightProbes>0?`#define USE_LIGHT_PROBES`:``,n.logarithmicDepthBuffer?`#define USE_LOGARITHMIC_DEPTH_BUFFER`:``,n.reversedDepthBuffer?`#define USE_REVERSED_DEPTH_BUFFER`:``,`uniform mat4 modelMatrix;`,`uniform mat4 modelViewMatrix;`,`uniform mat4 projectionMatrix;`,`uniform mat4 viewMatrix;`,`uniform mat3 normalMatrix;`,`uniform vec3 cameraPosition;`,`uniform bool isOrthographic;`,`#ifdef USE_INSTANCING`,` attribute mat4 instanceMatrix;`,`#endif`,`#ifdef USE_INSTANCING_COLOR`,` attribute vec3 instanceColor;`,`#endif`,`#ifdef USE_INSTANCING_MORPH`,` uniform sampler2D morphTexture;`,`#endif`,`attribute vec3 position;`,`attribute vec3 normal;`,`attribute vec2 uv;`,`#ifdef USE_UV1`,` attribute vec2 uv1;`,`#endif`,`#ifdef USE_UV2`,` attribute vec2 uv2;`,`#endif`,`#ifdef USE_UV3`,` attribute vec2 uv3;`,`#endif`,`#ifdef USE_TANGENT`,` attribute vec4 tangent;`,`#endif`,`#if defined( USE_COLOR_ALPHA )`,` attribute vec4 color;`,`#elif defined( USE_COLOR )`,` attribute vec3 color;`,`#endif`,`#ifdef USE_SKINNING`,` attribute vec4 skinIndex;`,` attribute vec4 skinWeight;`,`#endif`,`
|
|
4156
|
+
`].filter(JA).join(`
|
|
4157
|
+
`),_=[ij(n),`#define SHADER_TYPE `+n.shaderType,`#define SHADER_NAME `+n.shaderName,m,n.useFog&&n.fog?`#define USE_FOG`:``,n.useFog&&n.fogExp2?`#define FOG_EXP2`:``,n.alphaToCoverage?`#define ALPHA_TO_COVERAGE`:``,n.map?`#define USE_MAP`:``,n.matcap?`#define USE_MATCAP`:``,n.envMap?`#define USE_ENVMAP`:``,n.envMap?`#define `+l:``,n.envMap?`#define `+u:``,n.envMap?`#define `+d:``,f?`#define CUBEUV_TEXEL_WIDTH `+f.texelWidth:``,f?`#define CUBEUV_TEXEL_HEIGHT `+f.texelHeight:``,f?`#define CUBEUV_MAX_MIP `+f.maxMip+`.0`:``,n.lightMap?`#define USE_LIGHTMAP`:``,n.aoMap?`#define USE_AOMAP`:``,n.bumpMap?`#define USE_BUMPMAP`:``,n.normalMap?`#define USE_NORMALMAP`:``,n.normalMapObjectSpace?`#define USE_NORMALMAP_OBJECTSPACE`:``,n.normalMapTangentSpace?`#define USE_NORMALMAP_TANGENTSPACE`:``,n.packedNormalMap?`#define USE_PACKED_NORMALMAP`:``,n.emissiveMap?`#define USE_EMISSIVEMAP`:``,n.anisotropy?`#define USE_ANISOTROPY`:``,n.anisotropyMap?`#define USE_ANISOTROPYMAP`:``,n.clearcoat?`#define USE_CLEARCOAT`:``,n.clearcoatMap?`#define USE_CLEARCOATMAP`:``,n.clearcoatRoughnessMap?`#define USE_CLEARCOAT_ROUGHNESSMAP`:``,n.clearcoatNormalMap?`#define USE_CLEARCOAT_NORMALMAP`:``,n.dispersion?`#define USE_DISPERSION`:``,n.retroreflection?`#define USE_RETROREFLECTION`:``,n.iridescence?`#define USE_IRIDESCENCE`:``,n.iridescenceMap?`#define USE_IRIDESCENCEMAP`:``,n.iridescenceThicknessMap?`#define USE_IRIDESCENCE_THICKNESSMAP`:``,n.specularMap?`#define USE_SPECULARMAP`:``,n.specularColorMap?`#define USE_SPECULAR_COLORMAP`:``,n.specularIntensityMap?`#define USE_SPECULAR_INTENSITYMAP`:``,n.roughnessMap?`#define USE_ROUGHNESSMAP`:``,n.metalnessMap?`#define USE_METALNESSMAP`:``,n.alphaMap?`#define USE_ALPHAMAP`:``,n.alphaTest?`#define USE_ALPHATEST`:``,n.alphaHash?`#define USE_ALPHAHASH`:``,n.sheen?`#define USE_SHEEN`:``,n.sheenColorMap?`#define USE_SHEEN_COLORMAP`:``,n.sheenRoughnessMap?`#define USE_SHEEN_ROUGHNESSMAP`:``,n.transmission?`#define USE_TRANSMISSION`:``,n.transmissionMap?`#define USE_TRANSMISSIONMAP`:``,n.thicknessMap?`#define USE_THICKNESSMAP`:``,n.vertexTangents&&n.flatShading===!1?`#define USE_TANGENT`:``,n.vertexColors||n.instancingColor?`#define USE_COLOR`:``,n.vertexAlphas||n.batchingColor?`#define USE_COLOR_ALPHA`:``,n.vertexUv1s?`#define USE_UV1`:``,n.vertexUv2s?`#define USE_UV2`:``,n.vertexUv3s?`#define USE_UV3`:``,n.pointsUvs?`#define USE_POINTS_UV`:``,n.gradientMap?`#define USE_GRADIENTMAP`:``,n.flatShading?`#define FLAT_SHADED`:``,n.doubleSided?`#define DOUBLE_SIDED`:``,n.flipSided?`#define FLIP_SIDED`:``,n.shadowMapEnabled?`#define USE_SHADOWMAP`:``,n.shadowMapEnabled?`#define `+c:``,n.premultipliedAlpha?`#define PREMULTIPLIED_ALPHA`:``,n.numLightProbes>0?`#define USE_LIGHT_PROBES`:``,n.numLightProbeGrids>0?`#define USE_LIGHT_PROBES_GRID`:``,n.decodeVideoTexture?`#define DECODE_VIDEO_TEXTURE`:``,n.decodeVideoTextureEmissive?`#define DECODE_VIDEO_TEXTURE_EMISSIVE`:``,n.logarithmicDepthBuffer?`#define USE_LOGARITHMIC_DEPTH_BUFFER`:``,n.reversedDepthBuffer?`#define USE_REVERSED_DEPTH_BUFFER`:``,`uniform mat4 viewMatrix;`,`uniform vec3 cameraPosition;`,`uniform bool isOrthographic;`,n.toneMapping===0?``:`#define TONE_MAPPING`,n.toneMapping===0?``:Q.tonemapping_pars_fragment,n.toneMapping===0?``:HA(`toneMapping`,n.toneMapping),n.dithering?`#define DITHERING`:``,n.opaque?`#define OPAQUE`:``,Q.colorspace_pars_fragment,BA(`linearToOutputTexel`,n.outputColorSpace),WA(),n.useDepthPacking?`#define DEPTH_PACKING `+n.depthPacking:``,`
|
|
4158
|
+
`].filter(JA).join(`
|
|
4159
|
+
`)),o=QA(o),o=YA(o,n),o=XA(o,n),s=QA(s),s=YA(s,n),s=XA(s,n),o=nj(o),s=nj(s),n.isRawShaderMaterial!==!0&&(v=`#version 300 es
|
|
4160
4160
|
`,g=[p,`#define attribute in`,`#define varying out`,`#define texture2D texture`].join(`
|
|
4161
4161
|
`)+`
|
|
4162
4162
|
`+g,_=[`#define varying in`,n.glslVersion===`300 es`?``:`layout(location = 0) out highp vec4 pc_fragColor;`,n.glslVersion===`300 es`?``:`#define gl_FragColor pc_fragColor`,`#define gl_FragDepthEXT gl_FragDepth`,`#define texture2D texture`,`#define textureCube texture`,`#define texture2DProj textureProj`,`#define texture2DLodEXT textureLod`,`#define texture2DProjLodEXT textureProjLod`,`#define textureCubeLodEXT textureLod`,`#define texture2DGradEXT textureGrad`,`#define texture2DProjGradEXT textureProjGrad`,`#define textureCubeGradEXT textureGrad`].join(`
|
|
4163
4163
|
`)+`
|
|
4164
|
-
`+_);let y=v+g+o,b=v+_+s,x=
|
|
4164
|
+
`+_);let y=v+g+o,b=v+_+s,x=NA(i,i.VERTEX_SHADER,y),S=NA(i,i.FRAGMENT_SHADER,b);i.attachShader(h,x),i.attachShader(h,S),n.index0AttributeName===void 0?n.hasPositionAttribute===!0&&i.bindAttribLocation(h,0,`position`):i.bindAttribLocation(h,0,n.index0AttributeName),i.linkProgram(h);function C(t){if(e.debug.checkShaderErrors){let n=i.getProgramInfoLog(h)||``,r=i.getShaderInfoLog(x)||``,a=i.getShaderInfoLog(S)||``,o=n.trim(),s=r.trim(),c=a.trim(),l=!0,u=!0;if(i.getProgramParameter(h,i.LINK_STATUS)===!1){if(l=!1,typeof e.debug.onShaderError==`function`)e.debug.onShaderError(i,h,x,S);else{let e=zA(i,x,`vertex`),n=zA(i,S,`fragment`);J(`WebGLProgram: Shader Error `+i.getError()+` - VALIDATE_STATUS `+i.getProgramParameter(h,i.VALIDATE_STATUS)+`
|
|
4165
4165
|
|
|
4166
4166
|
Material Name: `+t.name+`
|
|
4167
4167
|
Material Type: `+t.type+`
|
|
4168
4168
|
|
|
4169
4169
|
Program Info Log: `+o+`
|
|
4170
4170
|
`+e+`
|
|
4171
|
-
`+n)}}else o===``?(s===``||c===``)&&(u=!1):q(`WebGLProgram: Program Info Log:`,o);u&&(t.diagnostics={runnable:l,programLog:o,vertexShader:{log:s,prefix:g},fragmentShader:{log:c,prefix:_}})}i.deleteShader(x),i.deleteShader(S),w=new tk(i,h),T=gk(i,h)}let w;this.getUniforms=function(){return w===void 0&&C(this),w};let T;this.getAttributes=function(){return T===void 0&&C(this),T};let E=n.rendererExtensionParallelShaderCompile===!1;return this.isReady=function(){return E===!1&&(E=i.getProgramParameter(h,rk)),E},this.destroy=function(){r.releaseStatesOfProgram(this),i.deleteProgram(h),this.program=void 0},this.type=n.shaderType,this.name=n.shaderName,this.id=ik++,this.cacheKey=t,this.usedTimes=1,this.program=h,this.vertexShader=x,this.fragmentShader=S,this}var Rk=0,zk=class{constructor(){this.shaderCache=/* @__PURE__ */ new Map,this.materialCache=/* @__PURE__ */ new Map}update(e,t,n){let r=this._getShaderCacheForMaterial(e);return r.has(t)===!1&&(r.add(t),t.usedTimes++),r.has(n)===!1&&(r.add(n),n.usedTimes++),this}remove(e){let t=this.materialCache.get(e);for(let e of t)e.usedTimes--,e.usedTimes===0&&this.shaderCache.delete(e.code);return this.materialCache.delete(e),this}getVertexShaderStage(e){return this._getShaderStage(e.vertexShader)}getFragmentShaderStage(e){return this._getShaderStage(e.fragmentShader)}dispose(){this.shaderCache.clear(),this.materialCache.clear()}_getShaderCacheForMaterial(e){let t=this.materialCache,n=t.get(e);return n===void 0&&(n=/* @__PURE__ */ new Set,t.set(e,n)),n}_getShaderStage(e){let t=this.shaderCache,n=t.get(e);return n===void 0&&(n=new Bk(e),t.set(e,n)),n}},Bk=class{constructor(e){this.id=Rk++,this.code=e,this.usedTimes=0}};function Vk(e){return e===1030||e===37490||e===36285}function Hk(e,t,n,r,i,a){let o=new ZC,s=new zk,c=/* @__PURE__ */ new Set,l=[],u=/* @__PURE__ */ new Map,d=r.logarithmicDepthBuffer,f=r.precision,p={MeshDepthMaterial:`depth`,MeshDistanceMaterial:`distance`,MeshNormalMaterial:`normal`,MeshBasicMaterial:`basic`,MeshLambertMaterial:`lambert`,MeshPhongMaterial:`phong`,MeshToonMaterial:`toon`,MeshStandardMaterial:`physical`,MeshPhysicalMaterial:`physical`,MeshMatcapMaterial:`matcap`,LineBasicMaterial:`basic`,LineDashedMaterial:`dashed`,PointsMaterial:`points`,ShadowMaterial:`shadow`,SpriteMaterial:`sprite`};function m(e){return c.add(e),e===0?`uv`:`uv${e}`}function h(i,o,l,u,h,g){let _=u.fog,v=h.geometry,y=i.isMeshStandardMaterial||i.isMeshLambertMaterial||i.isMeshPhongMaterial?u.environment:null,b=i.isMeshStandardMaterial||i.isMeshLambertMaterial&&!i.envMap||i.isMeshPhongMaterial&&!i.envMap,x=t.get(i.envMap||y,b),S=x&&x.mapping===306?x.image.height:null,C=p[i.type];i.precision!==null&&(f=r.getMaxPrecision(i.precision),f!==i.precision&&q(`WebGLProgram.getParameters:`,i.precision,`not supported, using`,f,`instead.`));let w=v.morphAttributes.position||v.morphAttributes.normal||v.morphAttributes.color,T=w===void 0?0:w.length,E=0;v.morphAttributes.position!==void 0&&(E=1),v.morphAttributes.normal!==void 0&&(E=2),v.morphAttributes.color!==void 0&&(E=3);let D,O,k,A;if(C){let e=lD[C];D=e.vertexShader,O=e.fragmentShader}else{D=i.vertexShader,O=i.fragmentShader;let e=s.getVertexShaderStage(i),t=s.getFragmentShaderStage(i);s.update(i,e,t),k=e.id,A=t.id}let ee=e.getRenderTarget(),te=e.state.buffers.depth.getReversed(),j=h.isInstancedMesh===!0,ne=h.isBatchedMesh===!0,re=!!i.map,M=!!i.matcap,ie=!!x,N=!!i.aoMap,ae=!!i.lightMap,oe=!!i.bumpMap&&i.wireframe===!1,se=!!i.normalMap,ce=!!i.displacementMap,le=!!i.emissiveMap,ue=!!i.metalnessMap,de=!!i.roughnessMap,fe=i.anisotropy>0,pe=i.clearcoat>0,me=i.dispersion>0,he=i.retroreflectivity>0,ge=i.iridescence>0,_e=i.sheen>0,ve=i.transmission>0,ye=fe&&!!i.anisotropyMap,be=pe&&!!i.clearcoatMap,xe=pe&&!!i.clearcoatNormalMap,Se=pe&&!!i.clearcoatRoughnessMap,Ce=ge&&!!i.iridescenceMap,P=ge&&!!i.iridescenceThicknessMap,we=_e&&!!i.sheenColorMap,Te=_e&&!!i.sheenRoughnessMap,Ee=!!i.specularMap,F=!!i.specularColorMap,De=!!i.specularIntensityMap,I=ve&&!!i.transmissionMap,L=ve&&!!i.thicknessMap,Oe=!!i.gradientMap,ke=!!i.alphaMap,Ae=i.alphaTest>0,je=!!i.alphaHash,Me=!!i.extensions,Ne=0;i.toneMapped&&(ee===null||ee.isXRRenderTarget===!0)&&(Ne=e.toneMapping);let Pe={shaderID:C,shaderType:i.type,shaderName:i.name,vertexShader:D,fragmentShader:O,defines:i.defines,customVertexShaderID:k,customFragmentShaderID:A,isRawShaderMaterial:i.isRawShaderMaterial===!0,glslVersion:i.glslVersion,precision:f,batching:ne,batchingColor:ne&&h._colorsTexture!==null,instancing:j,instancingColor:j&&h.instanceColor!==null,instancingMorph:j&&h.morphTexture!==null,outputColorSpace:ee===null?e.outputColorSpace:ee.isXRRenderTarget===!0?ee.texture.colorSpace:wC.workingColorSpace,alphaToCoverage:!!i.alphaToCoverage,map:re,matcap:M,envMap:ie,envMapMode:ie&&x.mapping,envMapCubeUVHeight:S,aoMap:N,lightMap:ae,bumpMap:oe,normalMap:se,displacementMap:ce,emissiveMap:le,normalMapObjectSpace:se&&i.normalMapType===1,normalMapTangentSpace:se&&i.normalMapType===0,packedNormalMap:se&&i.normalMapType===0&&Vk(i.normalMap.format),metalnessMap:ue,roughnessMap:de,anisotropy:fe,anisotropyMap:ye,clearcoat:pe,clearcoatMap:be,clearcoatNormalMap:xe,clearcoatRoughnessMap:Se,dispersion:me,retroreflection:he,iridescence:ge,iridescenceMap:Ce,iridescenceThicknessMap:P,sheen:_e,sheenColorMap:we,sheenRoughnessMap:Te,specularMap:Ee,specularColorMap:F,specularIntensityMap:De,transmission:ve,transmissionMap:I,thicknessMap:L,gradientMap:Oe,opaque:i.transparent===!1&&i.blending===1&&i.alphaToCoverage===!1,alphaMap:ke,alphaTest:Ae,alphaHash:je,combine:i.combine,mapUv:re&&m(i.map.channel),aoMapUv:N&&m(i.aoMap.channel),lightMapUv:ae&&m(i.lightMap.channel),bumpMapUv:oe&&m(i.bumpMap.channel),normalMapUv:se&&m(i.normalMap.channel),displacementMapUv:ce&&m(i.displacementMap.channel),emissiveMapUv:le&&m(i.emissiveMap.channel),metalnessMapUv:ue&&m(i.metalnessMap.channel),roughnessMapUv:de&&m(i.roughnessMap.channel),anisotropyMapUv:ye&&m(i.anisotropyMap.channel),clearcoatMapUv:be&&m(i.clearcoatMap.channel),clearcoatNormalMapUv:xe&&m(i.clearcoatNormalMap.channel),clearcoatRoughnessMapUv:Se&&m(i.clearcoatRoughnessMap.channel),iridescenceMapUv:Ce&&m(i.iridescenceMap.channel),iridescenceThicknessMapUv:P&&m(i.iridescenceThicknessMap.channel),sheenColorMapUv:we&&m(i.sheenColorMap.channel),sheenRoughnessMapUv:Te&&m(i.sheenRoughnessMap.channel),specularMapUv:Ee&&m(i.specularMap.channel),specularColorMapUv:F&&m(i.specularColorMap.channel),specularIntensityMapUv:De&&m(i.specularIntensityMap.channel),transmissionMapUv:I&&m(i.transmissionMap.channel),thicknessMapUv:L&&m(i.thicknessMap.channel),alphaMapUv:ke&&m(i.alphaMap.channel),vertexTangents:!!v.attributes.tangent&&(se||fe),vertexNormals:!!v.attributes.normal,vertexColors:i.vertexColors,vertexAlphas:i.vertexColors===!0&&!!v.attributes.color&&v.attributes.color.itemSize===4,pointsUvs:h.isPoints===!0&&!!v.attributes.uv&&(re||ke),fog:!!_,useFog:i.fog===!0,fogExp2:!!_&&_.isFogExp2,flatShading:i.wireframe===!1&&(i.flatShading===!0||v.attributes.normal===void 0&&se===!1&&(i.isMeshLambertMaterial||i.isMeshPhongMaterial||i.isMeshStandardMaterial||i.isMeshPhysicalMaterial)),sizeAttenuation:i.sizeAttenuation===!0,logarithmicDepthBuffer:d,reversedDepthBuffer:te,skinning:h.isSkinnedMesh===!0,hasPositionAttribute:v.attributes.position!==void 0,morphTargets:v.morphAttributes.position!==void 0,morphNormals:v.morphAttributes.normal!==void 0,morphColors:v.morphAttributes.color!==void 0,morphTargetsCount:T,morphTextureStride:E,numSunLights:o.sun.length,numDirLights:o.directional.length,numPointLights:o.point.length,numSpotLights:o.spot.length,numSpotLightMaps:o.spotLightMap.length,numRectAreaLights:o.rectArea.length,numHemiLights:o.hemi.length,numSunLightShadows:o.sunShadowMap.length,numDirLightShadows:o.directionalShadowMap.length,numPointLightShadows:o.pointShadowMap.length,numSpotLightShadows:o.spotShadowMap.length,numSpotLightShadowsWithMaps:o.numSpotLightShadowsWithMaps,numLightProbes:o.numLightProbes,numLightProbeGrids:g.length,numClippingPlanes:a.numPlanes,numClipIntersection:a.numIntersection,dithering:i.dithering,shadowMapEnabled:e.shadowMap.enabled&&l.length>0,shadowMapType:e.shadowMap.type,toneMapping:Ne,decodeVideoTexture:re&&i.map.isVideoTexture===!0&&wC.getTransfer(i.map.colorSpace)===`srgb`,decodeVideoTextureEmissive:le&&i.emissiveMap.isVideoTexture===!0&&wC.getTransfer(i.emissiveMap.colorSpace)===`srgb`,premultipliedAlpha:i.premultipliedAlpha,doubleSided:i.side===2,flipSided:i.side===1,useDepthPacking:i.depthPacking>=0,depthPacking:i.depthPacking||0,index0AttributeName:i.index0AttributeName,extensionClipCullDistance:Me&&i.extensions.clipCullDistance===!0&&n.has(`WEBGL_clip_cull_distance`),extensionMultiDraw:(Me&&i.extensions.multiDraw===!0||ne)&&n.has(`WEBGL_multi_draw`),rendererExtensionParallelShaderCompile:n.has(`KHR_parallel_shader_compile`),customProgramCacheKey:i.customProgramCacheKey()};return Pe.vertexUv1s=c.has(1),Pe.vertexUv2s=c.has(2),Pe.vertexUv3s=c.has(3),c.clear(),Pe}function g(t){let n=[];if(t.shaderID?n.push(t.shaderID):(n.push(t.customVertexShaderID),n.push(t.customFragmentShaderID)),t.defines!==void 0)for(let e in t.defines)n.push(e),n.push(t.defines[e]);return t.isRawShaderMaterial===!1&&(_(n,t),v(n,t),n.push(e.outputColorSpace)),n.push(t.customProgramCacheKey),n.join()}function _(e,t){e.push(t.precision),e.push(t.outputColorSpace),e.push(t.envMapMode),e.push(t.envMapCubeUVHeight),e.push(t.mapUv),e.push(t.alphaMapUv),e.push(t.lightMapUv),e.push(t.aoMapUv),e.push(t.bumpMapUv),e.push(t.normalMapUv),e.push(t.displacementMapUv),e.push(t.emissiveMapUv),e.push(t.metalnessMapUv),e.push(t.roughnessMapUv),e.push(t.anisotropyMapUv),e.push(t.clearcoatMapUv),e.push(t.clearcoatNormalMapUv),e.push(t.clearcoatRoughnessMapUv),e.push(t.iridescenceMapUv),e.push(t.iridescenceThicknessMapUv),e.push(t.sheenColorMapUv),e.push(t.sheenRoughnessMapUv),e.push(t.specularMapUv),e.push(t.specularColorMapUv),e.push(t.specularIntensityMapUv),e.push(t.transmissionMapUv),e.push(t.thicknessMapUv),e.push(t.combine),e.push(t.fogExp2),e.push(t.sizeAttenuation),e.push(t.morphTargetsCount),e.push(t.morphAttributeCount),e.push(t.numSunLights),e.push(t.numDirLights),e.push(t.numPointLights),e.push(t.numSpotLights),e.push(t.numSpotLightMaps),e.push(t.numHemiLights),e.push(t.numRectAreaLights),e.push(t.numSunLightShadows),e.push(t.numDirLightShadows),e.push(t.numPointLightShadows),e.push(t.numSpotLightShadows),e.push(t.numSpotLightShadowsWithMaps),e.push(t.numLightProbes),e.push(t.shadowMapType),e.push(t.toneMapping),e.push(t.numClippingPlanes),e.push(t.numClipIntersection),e.push(t.depthPacking)}function v(e,t){o.disableAll(),t.instancing&&o.enable(0),t.instancingColor&&o.enable(1),t.instancingMorph&&o.enable(2),t.matcap&&o.enable(3),t.envMap&&o.enable(4),t.normalMapObjectSpace&&o.enable(5),t.normalMapTangentSpace&&o.enable(6),t.clearcoat&&o.enable(7),t.iridescence&&o.enable(8),t.alphaTest&&o.enable(9),t.vertexColors&&o.enable(10),t.vertexAlphas&&o.enable(11),t.vertexUv1s&&o.enable(12),t.vertexUv2s&&o.enable(13),t.vertexUv3s&&o.enable(14),t.vertexTangents&&o.enable(15),t.anisotropy&&o.enable(16),t.alphaHash&&o.enable(17),t.batching&&o.enable(18),t.dispersion&&o.enable(19),t.retroreflection&&o.enable(24),t.batchingColor&&o.enable(20),t.gradientMap&&o.enable(21),t.packedNormalMap&&o.enable(22),t.vertexNormals&&o.enable(23),e.push(o.mask),o.disableAll(),t.fog&&o.enable(0),t.useFog&&o.enable(1),t.flatShading&&o.enable(2),t.logarithmicDepthBuffer&&o.enable(3),t.reversedDepthBuffer&&o.enable(4),t.skinning&&o.enable(5),t.morphTargets&&o.enable(6),t.morphNormals&&o.enable(7),t.morphColors&&o.enable(8),t.premultipliedAlpha&&o.enable(9),t.shadowMapEnabled&&o.enable(10),t.doubleSided&&o.enable(11),t.flipSided&&o.enable(12),t.useDepthPacking&&o.enable(13),t.dithering&&o.enable(14),t.transmission&&o.enable(15),t.sheen&&o.enable(16),t.opaque&&o.enable(17),t.pointsUvs&&o.enable(18),t.decodeVideoTexture&&o.enable(19),t.decodeVideoTextureEmissive&&o.enable(20),t.alphaToCoverage&&o.enable(21),t.numLightProbeGrids>0&&o.enable(22),t.hasPositionAttribute&&o.enable(23),e.push(o.mask)}function y(e){let t=p[e.type],n;if(t){let e=lD[t];n=cE.clone(e.uniforms)}else n=e.uniforms;return n}function b(t,n){let r=u.get(n);return r===void 0?(r=new Lk(e,n,t,i),l.push(r),u.set(n,r)):++r.usedTimes,r}function x(e){if(--e.usedTimes===0){let t=l.indexOf(e);l[t]=l[l.length-1],l.pop(),u.delete(e.cacheKey),e.destroy()}}function S(e){s.remove(e)}function C(){s.dispose()}return{getParameters:h,getProgramCacheKey:g,getUniforms:y,acquireProgram:b,releaseProgram:x,releaseShaderCache:S,programs:l,dispose:C}}function Uk(){let e=/* @__PURE__ */ new WeakMap;function t(t){return e.has(t)}function n(t){let n=e.get(t);return n===void 0&&(n={},e.set(t,n)),n}function r(t){e.delete(t)}function i(t,n,r){e.get(t)[n]=r}function a(){e=/* @__PURE__ */ new WeakMap}return{has:t,get:n,remove:r,update:i,dispose:a}}function Wk(e,t){return e.groupOrder===t.groupOrder?e.renderOrder===t.renderOrder?e.material.id===t.material.id?e.materialVariant===t.materialVariant?e.z===t.z?e.id-t.id:e.z-t.z:e.materialVariant-t.materialVariant:e.material.id-t.material.id:e.renderOrder-t.renderOrder:e.groupOrder-t.groupOrder}function Gk(e,t){return e.groupOrder===t.groupOrder?e.renderOrder===t.renderOrder?e.z===t.z?e.id-t.id:t.z-e.z:e.renderOrder-t.renderOrder:e.groupOrder-t.groupOrder}function Kk(){let e=[],t=0,n=[],r=[],i=[];function a(){t=0,n.length=0,r.length=0,i.length=0}function o(e){let t=0;return e.isInstancedMesh&&(t+=2),e.isSkinnedMesh&&(t+=1),t}function s(n,r,i,a,s,c){let l=e[t];return l===void 0?(l={id:n.id,object:n,geometry:r,material:i,materialVariant:o(n),groupOrder:a,renderOrder:n.renderOrder,z:s,group:c},e[t]=l):(l.id=n.id,l.object=n,l.geometry=r,l.material=i,l.materialVariant=o(n),l.groupOrder=a,l.renderOrder=n.renderOrder,l.z=s,l.group=c),t++,l}function c(e,t,a,o,c,l,u){u.reversedDepth===!0&&(c=-c);let d=s(e,t,a,o,c,l);a.transmission>0?r.push(d):a.transparent===!0?i.push(d):n.push(d)}function l(e,t,a,o,c,l){let u=s(e,t,a,o,c,l);a.transmission>0?r.unshift(u):a.transparent===!0?i.unshift(u):n.unshift(u)}function u(e,t){n.length>1&&n.sort(e||Wk),r.length>1&&r.sort(t||Gk),i.length>1&&i.sort(t||Gk)}function d(){for(let n=t,r=e.length;n<r;n++){let t=e[n];if(t.id===null)break;t.id=null,t.object=null,t.geometry=null,t.material=null,t.group=null}}return{opaque:n,transmissive:r,transparent:i,init:a,push:c,unshift:l,finish:d,sort:u}}function qk(){let e=/* @__PURE__ */ new WeakMap;function t(t,n){let r=e.get(t),i;return r===void 0?(i=new Kk,e.set(t,[i])):n>=r.length?(i=new Kk,r.push(i)):i=r[n],i}function n(){e=/* @__PURE__ */ new WeakMap}return{get:t,dispose:n}}function Jk(){let e={};return{get:function(t){if(e[t.id]!==void 0)return e[t.id];let n;switch(t.type){case`SunLight`:case`DirectionalLight`:n={direction:new X,color:new xw};break;case`SpotLight`:n={position:new X,direction:new X,color:new xw,distance:0,coneCos:0,penumbraCos:0,decay:0};break;case`PointLight`:n={position:new X,color:new xw,distance:0,decay:0};break;case`HemisphereLight`:n={direction:new X,skyColor:new xw,groundColor:new xw};break;case`RectAreaLight`:n={color:new xw,position:new X,halfWidth:new X,halfHeight:new X}}return e[t.id]=n,n}}}function Yk(){let e={};return{get:function(t){if(e[t.id]!==void 0)return e[t.id];let n;switch(t.type){case`SunLight`:case`DirectionalLight`:n={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new Y};break;case`SpotLight`:n={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new Y};break;case`PointLight`:n={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new Y,shadowCameraNear:1,shadowCameraFar:1e3}}return e[t.id]=n,n}}}var Xk=0;function Zk(e,t){return(t.castShadow?2:0)-(e.castShadow?2:0)+ +!!t.map-!!e.map}function Qk(e){let t=new Jk,n=Yk(),r={version:0,hash:{sunLength:-1,directionalLength:-1,pointLength:-1,spotLength:-1,rectAreaLength:-1,hemiLength:-1,numSunShadows:-1,numDirectionalShadows:-1,numPointShadows:-1,numSpotShadows:-1,numSpotMaps:-1,numLightProbes:-1},ambient:[0,0,0],probe:[],sun:[],sunShadow:[],sunShadowMap:[],sunShadowMatrix:[],sunShadowCascade:[],directional:[],directionalShadow:[],directionalShadowMap:[],directionalShadowMatrix:[],spot:[],spotLightMap:[],spotShadow:[],spotShadowMap:[],spotLightMatrix:[],rectArea:[],rectAreaLTC1:null,rectAreaLTC2:null,point:[],pointShadow:[],pointShadowMap:[],pointShadowMatrix:[],hemi:[],numSpotLightShadowsWithMaps:0,numLightProbes:0};for(let e=0;e<9;e++)r.probe.push(new X);let i=new X,a=new BC,o=new BC;function s(i){let a=0,o=0,s=0;for(let e=0;e<9;e++)r.probe[e].set(0,0,0);let c=0,l=0,u=0,d=0,f=0,p=0,m=0,h=0,g=0,_=0,v=0,y=0,b=0,x=0;i.sort(Zk);for(let e=0,S=i.length;e<S;e++){let S=i[e],C=S.color,w=S.intensity,T=S.distance,E=null;if(S.shadow&&S.shadow.map&&(E=S.shadow.map.texture.format===1030?S.shadow.map.texture:S.shadow.map.depthTexture||S.shadow.map.texture),S.isAmbientLight)a+=C.r*w,o+=C.g*w,s+=C.b*w;else if(S.isLightProbe){for(let e=0;e<9;e++)r.probe[e].addScaledVector(S.sh.coefficients[e],w);x++}else if(S.isSunLight){let e=t.get(S);if(e.color.copy(S.color).multiplyScalar(S.intensity),S.castShadow){let e=S.shadow,t=n.get(S);t.shadowIntensity=e.intensity,t.shadowBias=e.bias,t.shadowNormalBias=e.normalBias,t.shadowRadius=e.radius,t.shadowMapSize.copy(e.mapSize).multiply(e.getFrameExtents()),r.sunShadow[l]=t,r.sunShadowMap[l]=E;let i=e.getViewportCount();for(let t=0;t<i;t++)r.sunShadowMatrix[u+t]=e.getMatrix(t),r.sunShadowCascade[u+t]=e._cascadeData[t];u+=i,l++}r.sun[c]=e,c++}else if(S.isDirectionalLight){let e=t.get(S);if(e.color.copy(S.color).multiplyScalar(S.intensity),S.castShadow){let e=S.shadow,t=n.get(S);t.shadowIntensity=e.intensity,t.shadowBias=e.bias,t.shadowNormalBias=e.normalBias,t.shadowRadius=e.radius,t.shadowMapSize=e.mapSize,r.directionalShadow[d]=t,r.directionalShadowMap[d]=E,r.directionalShadowMatrix[d]=S.shadow.matrix,g++}r.directional[d]=e,d++}else if(S.isSpotLight){let e=t.get(S);e.position.setFromMatrixPosition(S.matrixWorld),e.color.copy(C).multiplyScalar(w),e.distance=T,e.coneCos=Math.cos(S.angle),e.penumbraCos=Math.cos(S.angle*(1-S.penumbra)),e.decay=S.decay,r.spot[p]=e;let i=S.shadow;if(S.map&&(r.spotLightMap[y]=S.map,y++,i.updateMatrices(S),S.castShadow&&b++),r.spotLightMatrix[p]=i.matrix,S.castShadow){let e=n.get(S);e.shadowIntensity=i.intensity,e.shadowBias=i.bias,e.shadowNormalBias=i.normalBias,e.shadowRadius=i.radius,e.shadowMapSize=i.mapSize,r.spotShadow[p]=e,r.spotShadowMap[p]=E,v++}p++}else if(S.isRectAreaLight){let e=t.get(S);e.color.copy(C).multiplyScalar(w),e.halfWidth.set(S.width*.5,0,0),e.halfHeight.set(0,S.height*.5,0),r.rectArea[m]=e,m++}else if(S.isPointLight){let e=t.get(S);if(e.color.copy(S.color).multiplyScalar(S.intensity),e.distance=S.distance,e.decay=S.decay,S.castShadow){let e=S.shadow,t=n.get(S);t.shadowIntensity=e.intensity,t.shadowBias=e.bias,t.shadowNormalBias=e.normalBias,t.shadowRadius=e.radius,t.shadowMapSize=e.mapSize,t.shadowCameraNear=e.camera.near,t.shadowCameraFar=e.camera.far,r.pointShadow[f]=t,r.pointShadowMap[f]=E,r.pointShadowMatrix[f]=S.shadow.matrix,_++}r.point[f]=e,f++}else if(S.isHemisphereLight){let e=t.get(S);e.skyColor.copy(S.color).multiplyScalar(w),e.groundColor.copy(S.groundColor).multiplyScalar(w),r.hemi[h]=e,h++}}m>0&&(e.has(`OES_texture_float_linear`)===!0?(r.rectAreaLTC1=$.LTC_FLOAT_1,r.rectAreaLTC2=$.LTC_FLOAT_2):(r.rectAreaLTC1=$.LTC_HALF_1,r.rectAreaLTC2=$.LTC_HALF_2)),r.ambient[0]=a,r.ambient[1]=o,r.ambient[2]=s;let S=r.hash;(S.sunLength!==c||S.directionalLength!==d||S.pointLength!==f||S.spotLength!==p||S.rectAreaLength!==m||S.hemiLength!==h||S.numSunShadows!==l||S.numDirectionalShadows!==g||S.numPointShadows!==_||S.numSpotShadows!==v||S.numSpotMaps!==y||S.numLightProbes!==x)&&(r.sun.length=c,r.directional.length=d,r.spot.length=p,r.rectArea.length=m,r.point.length=f,r.hemi.length=h,r.sunShadow.length=l,r.sunShadowMap.length=l,r.sunShadowMatrix.length=u,r.sunShadowCascade.length=u,r.directionalShadow.length=g,r.directionalShadowMap.length=g,r.directionalShadowMatrix.length=g,r.pointShadow.length=_,r.pointShadowMap.length=_,r.pointShadowMatrix.length=_,r.spotShadow.length=v,r.spotShadowMap.length=v,r.spotLightMatrix.length=v+y-b,r.spotLightMap.length=y,r.numSpotLightShadowsWithMaps=b,r.numLightProbes=x,S.sunLength=c,S.directionalLength=d,S.pointLength=f,S.spotLength=p,S.rectAreaLength=m,S.hemiLength=h,S.numSunShadows=l,S.numDirectionalShadows=g,S.numPointShadows=_,S.numSpotShadows=v,S.numSpotMaps=y,S.numLightProbes=x,r.version=Xk++)}function c(e,t){let n=0,s=0,c=0,l=0,u=0,d=0,f=t.matrixWorldInverse;for(let t=0,p=e.length;t<p;t++){let p=e[t];if(p.isSunLight){let e=r.sun[n];e.direction.setFromMatrixPosition(p.matrixWorld),e.direction.transformDirection(f),n++}else if(p.isDirectionalLight){let e=r.directional[s];e.direction.setFromMatrixPosition(p.matrixWorld),i.setFromMatrixPosition(p.target.matrixWorld),e.direction.sub(i),e.direction.transformDirection(f),s++}else if(p.isSpotLight){let e=r.spot[l];e.position.setFromMatrixPosition(p.matrixWorld),e.position.applyMatrix4(f),e.direction.setFromMatrixPosition(p.matrixWorld),i.setFromMatrixPosition(p.target.matrixWorld),e.direction.sub(i),e.direction.transformDirection(f),l++}else if(p.isRectAreaLight){let e=r.rectArea[u];e.position.setFromMatrixPosition(p.matrixWorld),e.position.applyMatrix4(f),o.identity(),a.copy(p.matrixWorld),a.premultiply(f),o.extractRotation(a),e.halfWidth.set(p.width*.5,0,0),e.halfHeight.set(0,p.height*.5,0),e.halfWidth.applyMatrix4(o),e.halfHeight.applyMatrix4(o),u++}else if(p.isPointLight){let e=r.point[c];e.position.setFromMatrixPosition(p.matrixWorld),e.position.applyMatrix4(f),c++}else if(p.isHemisphereLight){let e=r.hemi[d];e.direction.setFromMatrixPosition(p.matrixWorld),e.direction.transformDirection(f),d++}}}return{setup:s,setupView:c,state:r}}function $k(e){let t=new Qk(e),n=[],r=[],i=[];function a(e){d.camera=e,n.length=0,r.length=0,i.length=0}function o(e){n.push(e)}function s(e){r.push(e)}function c(e){i.push(e)}function l(){t.setup(n)}function u(e){t.setupView(n,e)}let d={lightsArray:n,shadowsArray:r,lightProbeGridArray:i,camera:null,lights:t,transmissionRenderTarget:{},textureUnits:0};return{init:a,state:d,setupLights:l,setupLightsView:u,pushLight:o,pushShadow:s,pushLightProbeGrid:c}}function eA(e){let t=/* @__PURE__ */ new WeakMap;function n(n,r=0){let i=t.get(n),a;return i===void 0?(a=new $k(e),t.set(n,[a])):r>=i.length?(a=new $k(e),i.push(a)):a=i[r],a}function r(){t=/* @__PURE__ */ new WeakMap}return{get:n,dispose:r}}var tA=`void main() {
|
|
4171
|
+
`+n)}}else o===``?(s===``||c===``)&&(u=!1):q(`WebGLProgram: Program Info Log:`,o);u&&(t.diagnostics={runnable:l,programLog:o,vertexShader:{log:s,prefix:g},fragmentShader:{log:c,prefix:_}})}i.deleteShader(x),i.deleteShader(S),w=new MA(i,h),T=qA(i,h)}let w;this.getUniforms=function(){return w===void 0&&C(this),w};let T;this.getAttributes=function(){return T===void 0&&C(this),T};let E=n.rendererExtensionParallelShaderCompile===!1;return this.isReady=function(){return E===!1&&(E=i.getProgramParameter(h,PA)),E},this.destroy=function(){r.releaseStatesOfProgram(this),i.deleteProgram(h),this.program=void 0},this.type=n.shaderType,this.name=n.shaderName,this.id=FA++,this.cacheKey=t,this.usedTimes=1,this.program=h,this.vertexShader=x,this.fragmentShader=S,this}var hj=0,gj=class{constructor(){this.shaderCache=/* @__PURE__ */ new Map,this.materialCache=/* @__PURE__ */ new Map}update(e,t,n){let r=this._getShaderCacheForMaterial(e);return r.has(t)===!1&&(r.add(t),t.usedTimes++),r.has(n)===!1&&(r.add(n),n.usedTimes++),this}remove(e){let t=this.materialCache.get(e);for(let e of t)e.usedTimes--,e.usedTimes===0&&this.shaderCache.delete(e.code);return this.materialCache.delete(e),this}getVertexShaderStage(e){return this._getShaderStage(e.vertexShader)}getFragmentShaderStage(e){return this._getShaderStage(e.fragmentShader)}dispose(){this.shaderCache.clear(),this.materialCache.clear()}_getShaderCacheForMaterial(e){let t=this.materialCache,n=t.get(e);return n===void 0&&(n=/* @__PURE__ */ new Set,t.set(e,n)),n}_getShaderStage(e){let t=this.shaderCache,n=t.get(e);return n===void 0&&(n=new _j(e),t.set(e,n)),n}},_j=class{constructor(e){this.id=hj++,this.code=e,this.usedTimes=0}};function vj(e){return e===1030||e===37490||e===36285}function yj(e,t,n,r,i,a){let o=new OT,s=new gj,c=/* @__PURE__ */ new Set,l=[],u=/* @__PURE__ */ new Map,d=r.logarithmicDepthBuffer,f=r.precision,p={MeshDepthMaterial:`depth`,MeshDistanceMaterial:`distance`,MeshNormalMaterial:`normal`,MeshBasicMaterial:`basic`,MeshLambertMaterial:`lambert`,MeshPhongMaterial:`phong`,MeshToonMaterial:`toon`,MeshStandardMaterial:`physical`,MeshPhysicalMaterial:`physical`,MeshMatcapMaterial:`matcap`,LineBasicMaterial:`basic`,LineDashedMaterial:`dashed`,PointsMaterial:`points`,ShadowMaterial:`shadow`,SpriteMaterial:`sprite`};function m(e){return c.add(e),e===0?`uv`:`uv${e}`}function h(i,o,l,u,h,g){let _=u.fog,v=h.geometry,y=i.isMeshStandardMaterial||i.isMeshLambertMaterial||i.isMeshPhongMaterial?u.environment:null,b=i.isMeshStandardMaterial||i.isMeshLambertMaterial&&!i.envMap||i.isMeshPhongMaterial&&!i.envMap,x=t.get(i.envMap||y,b),S=x&&x.mapping===306?x.image.height:null,C=p[i.type];i.precision!==null&&(f=r.getMaxPrecision(i.precision),f!==i.precision&&q(`WebGLProgram.getParameters:`,i.precision,`not supported, using`,f,`instead.`));let w=v.morphAttributes.position||v.morphAttributes.normal||v.morphAttributes.color,T=w===void 0?0:w.length,E=0;v.morphAttributes.position!==void 0&&(E=1),v.morphAttributes.normal!==void 0&&(E=2),v.morphAttributes.color!==void 0&&(E=3);let D,O,k,A;if(C){let e=BO[C];D=e.vertexShader,O=e.fragmentShader}else{D=i.vertexShader,O=i.fragmentShader;let e=s.getVertexShaderStage(i),t=s.getFragmentShaderStage(i);s.update(i,e,t),k=e.id,A=t.id}let ee=e.getRenderTarget(),te=e.state.buffers.depth.getReversed(),j=h.isInstancedMesh===!0,ne=h.isBatchedMesh===!0,re=!!i.map,M=!!i.matcap,ie=!!x,N=!!i.aoMap,ae=!!i.lightMap,oe=!!i.bumpMap&&i.wireframe===!1,se=!!i.normalMap,ce=!!i.displacementMap,le=!!i.emissiveMap,ue=!!i.metalnessMap,de=!!i.roughnessMap,fe=i.anisotropy>0,pe=i.clearcoat>0,me=i.dispersion>0,he=i.retroreflectivity>0,ge=i.iridescence>0,_e=i.sheen>0,ve=i.transmission>0,ye=fe&&!!i.anisotropyMap,be=pe&&!!i.clearcoatMap,xe=pe&&!!i.clearcoatNormalMap,Se=pe&&!!i.clearcoatRoughnessMap,Ce=ge&&!!i.iridescenceMap,P=ge&&!!i.iridescenceThicknessMap,we=_e&&!!i.sheenColorMap,Te=_e&&!!i.sheenRoughnessMap,Ee=!!i.specularMap,F=!!i.specularColorMap,De=!!i.specularIntensityMap,I=ve&&!!i.transmissionMap,L=ve&&!!i.thicknessMap,Oe=!!i.gradientMap,ke=!!i.alphaMap,Ae=i.alphaTest>0,je=!!i.alphaHash,Me=!!i.extensions,Ne=0;i.toneMapped&&(ee===null||ee.isXRRenderTarget===!0)&&(Ne=e.toneMapping);let Pe={shaderID:C,shaderType:i.type,shaderName:i.name,vertexShader:D,fragmentShader:O,defines:i.defines,customVertexShaderID:k,customFragmentShaderID:A,isRawShaderMaterial:i.isRawShaderMaterial===!0,glslVersion:i.glslVersion,precision:f,batching:ne,batchingColor:ne&&h._colorsTexture!==null,instancing:j,instancingColor:j&&h.instanceColor!==null,instancingMorph:j&&h.morphTexture!==null,outputColorSpace:ee===null?e.outputColorSpace:ee.isXRRenderTarget===!0?ee.texture.colorSpace:tT.workingColorSpace,alphaToCoverage:!!i.alphaToCoverage,map:re,matcap:M,envMap:ie,envMapMode:ie&&x.mapping,envMapCubeUVHeight:S,aoMap:N,lightMap:ae,bumpMap:oe,normalMap:se,displacementMap:ce,emissiveMap:le,normalMapObjectSpace:se&&i.normalMapType===1,normalMapTangentSpace:se&&i.normalMapType===0,packedNormalMap:se&&i.normalMapType===0&&vj(i.normalMap.format),metalnessMap:ue,roughnessMap:de,anisotropy:fe,anisotropyMap:ye,clearcoat:pe,clearcoatMap:be,clearcoatNormalMap:xe,clearcoatRoughnessMap:Se,dispersion:me,retroreflection:he,iridescence:ge,iridescenceMap:Ce,iridescenceThicknessMap:P,sheen:_e,sheenColorMap:we,sheenRoughnessMap:Te,specularMap:Ee,specularColorMap:F,specularIntensityMap:De,transmission:ve,transmissionMap:I,thicknessMap:L,gradientMap:Oe,opaque:i.transparent===!1&&i.blending===1&&i.alphaToCoverage===!1,alphaMap:ke,alphaTest:Ae,alphaHash:je,combine:i.combine,mapUv:re&&m(i.map.channel),aoMapUv:N&&m(i.aoMap.channel),lightMapUv:ae&&m(i.lightMap.channel),bumpMapUv:oe&&m(i.bumpMap.channel),normalMapUv:se&&m(i.normalMap.channel),displacementMapUv:ce&&m(i.displacementMap.channel),emissiveMapUv:le&&m(i.emissiveMap.channel),metalnessMapUv:ue&&m(i.metalnessMap.channel),roughnessMapUv:de&&m(i.roughnessMap.channel),anisotropyMapUv:ye&&m(i.anisotropyMap.channel),clearcoatMapUv:be&&m(i.clearcoatMap.channel),clearcoatNormalMapUv:xe&&m(i.clearcoatNormalMap.channel),clearcoatRoughnessMapUv:Se&&m(i.clearcoatRoughnessMap.channel),iridescenceMapUv:Ce&&m(i.iridescenceMap.channel),iridescenceThicknessMapUv:P&&m(i.iridescenceThicknessMap.channel),sheenColorMapUv:we&&m(i.sheenColorMap.channel),sheenRoughnessMapUv:Te&&m(i.sheenRoughnessMap.channel),specularMapUv:Ee&&m(i.specularMap.channel),specularColorMapUv:F&&m(i.specularColorMap.channel),specularIntensityMapUv:De&&m(i.specularIntensityMap.channel),transmissionMapUv:I&&m(i.transmissionMap.channel),thicknessMapUv:L&&m(i.thicknessMap.channel),alphaMapUv:ke&&m(i.alphaMap.channel),vertexTangents:!!v.attributes.tangent&&(se||fe),vertexNormals:!!v.attributes.normal,vertexColors:i.vertexColors,vertexAlphas:i.vertexColors===!0&&!!v.attributes.color&&v.attributes.color.itemSize===4,pointsUvs:h.isPoints===!0&&!!v.attributes.uv&&(re||ke),fog:!!_,useFog:i.fog===!0,fogExp2:!!_&&_.isFogExp2,flatShading:i.wireframe===!1&&(i.flatShading===!0||v.attributes.normal===void 0&&se===!1&&(i.isMeshLambertMaterial||i.isMeshPhongMaterial||i.isMeshStandardMaterial||i.isMeshPhysicalMaterial)),sizeAttenuation:i.sizeAttenuation===!0,logarithmicDepthBuffer:d,reversedDepthBuffer:te,skinning:h.isSkinnedMesh===!0,hasPositionAttribute:v.attributes.position!==void 0,morphTargets:v.morphAttributes.position!==void 0,morphNormals:v.morphAttributes.normal!==void 0,morphColors:v.morphAttributes.color!==void 0,morphTargetsCount:T,morphTextureStride:E,numSunLights:o.sun.length,numDirLights:o.directional.length,numPointLights:o.point.length,numSpotLights:o.spot.length,numSpotLightMaps:o.spotLightMap.length,numRectAreaLights:o.rectArea.length,numHemiLights:o.hemi.length,numSunLightShadows:o.sunShadowMap.length,numDirLightShadows:o.directionalShadowMap.length,numPointLightShadows:o.pointShadowMap.length,numSpotLightShadows:o.spotShadowMap.length,numSpotLightShadowsWithMaps:o.numSpotLightShadowsWithMaps,numLightProbes:o.numLightProbes,numLightProbeGrids:g.length,numClippingPlanes:a.numPlanes,numClipIntersection:a.numIntersection,dithering:i.dithering,shadowMapEnabled:e.shadowMap.enabled&&l.length>0,shadowMapType:e.shadowMap.type,toneMapping:Ne,decodeVideoTexture:re&&i.map.isVideoTexture===!0&&tT.getTransfer(i.map.colorSpace)===`srgb`,decodeVideoTextureEmissive:le&&i.emissiveMap.isVideoTexture===!0&&tT.getTransfer(i.emissiveMap.colorSpace)===`srgb`,premultipliedAlpha:i.premultipliedAlpha,doubleSided:i.side===2,flipSided:i.side===1,useDepthPacking:i.depthPacking>=0,depthPacking:i.depthPacking||0,index0AttributeName:i.index0AttributeName,extensionClipCullDistance:Me&&i.extensions.clipCullDistance===!0&&n.has(`WEBGL_clip_cull_distance`),extensionMultiDraw:(Me&&i.extensions.multiDraw===!0||ne)&&n.has(`WEBGL_multi_draw`),rendererExtensionParallelShaderCompile:n.has(`KHR_parallel_shader_compile`),customProgramCacheKey:i.customProgramCacheKey()};return Pe.vertexUv1s=c.has(1),Pe.vertexUv2s=c.has(2),Pe.vertexUv3s=c.has(3),c.clear(),Pe}function g(t){let n=[];if(t.shaderID?n.push(t.shaderID):(n.push(t.customVertexShaderID),n.push(t.customFragmentShaderID)),t.defines!==void 0)for(let e in t.defines)n.push(e),n.push(t.defines[e]);return t.isRawShaderMaterial===!1&&(_(n,t),v(n,t),n.push(e.outputColorSpace)),n.push(t.customProgramCacheKey),n.join()}function _(e,t){e.push(t.precision),e.push(t.outputColorSpace),e.push(t.envMapMode),e.push(t.envMapCubeUVHeight),e.push(t.mapUv),e.push(t.alphaMapUv),e.push(t.lightMapUv),e.push(t.aoMapUv),e.push(t.bumpMapUv),e.push(t.normalMapUv),e.push(t.displacementMapUv),e.push(t.emissiveMapUv),e.push(t.metalnessMapUv),e.push(t.roughnessMapUv),e.push(t.anisotropyMapUv),e.push(t.clearcoatMapUv),e.push(t.clearcoatNormalMapUv),e.push(t.clearcoatRoughnessMapUv),e.push(t.iridescenceMapUv),e.push(t.iridescenceThicknessMapUv),e.push(t.sheenColorMapUv),e.push(t.sheenRoughnessMapUv),e.push(t.specularMapUv),e.push(t.specularColorMapUv),e.push(t.specularIntensityMapUv),e.push(t.transmissionMapUv),e.push(t.thicknessMapUv),e.push(t.combine),e.push(t.fogExp2),e.push(t.sizeAttenuation),e.push(t.morphTargetsCount),e.push(t.morphAttributeCount),e.push(t.numSunLights),e.push(t.numDirLights),e.push(t.numPointLights),e.push(t.numSpotLights),e.push(t.numSpotLightMaps),e.push(t.numHemiLights),e.push(t.numRectAreaLights),e.push(t.numSunLightShadows),e.push(t.numDirLightShadows),e.push(t.numPointLightShadows),e.push(t.numSpotLightShadows),e.push(t.numSpotLightShadowsWithMaps),e.push(t.numLightProbes),e.push(t.shadowMapType),e.push(t.toneMapping),e.push(t.numClippingPlanes),e.push(t.numClipIntersection),e.push(t.depthPacking)}function v(e,t){o.disableAll(),t.instancing&&o.enable(0),t.instancingColor&&o.enable(1),t.instancingMorph&&o.enable(2),t.matcap&&o.enable(3),t.envMap&&o.enable(4),t.normalMapObjectSpace&&o.enable(5),t.normalMapTangentSpace&&o.enable(6),t.clearcoat&&o.enable(7),t.iridescence&&o.enable(8),t.alphaTest&&o.enable(9),t.vertexColors&&o.enable(10),t.vertexAlphas&&o.enable(11),t.vertexUv1s&&o.enable(12),t.vertexUv2s&&o.enable(13),t.vertexUv3s&&o.enable(14),t.vertexTangents&&o.enable(15),t.anisotropy&&o.enable(16),t.alphaHash&&o.enable(17),t.batching&&o.enable(18),t.dispersion&&o.enable(19),t.retroreflection&&o.enable(24),t.batchingColor&&o.enable(20),t.gradientMap&&o.enable(21),t.packedNormalMap&&o.enable(22),t.vertexNormals&&o.enable(23),e.push(o.mask),o.disableAll(),t.fog&&o.enable(0),t.useFog&&o.enable(1),t.flatShading&&o.enable(2),t.logarithmicDepthBuffer&&o.enable(3),t.reversedDepthBuffer&&o.enable(4),t.skinning&&o.enable(5),t.morphTargets&&o.enable(6),t.morphNormals&&o.enable(7),t.morphColors&&o.enable(8),t.premultipliedAlpha&&o.enable(9),t.shadowMapEnabled&&o.enable(10),t.doubleSided&&o.enable(11),t.flipSided&&o.enable(12),t.useDepthPacking&&o.enable(13),t.dithering&&o.enable(14),t.transmission&&o.enable(15),t.sheen&&o.enable(16),t.opaque&&o.enable(17),t.pointsUvs&&o.enable(18),t.decodeVideoTexture&&o.enable(19),t.decodeVideoTextureEmissive&&o.enable(20),t.alphaToCoverage&&o.enable(21),t.numLightProbeGrids>0&&o.enable(22),t.hasPositionAttribute&&o.enable(23),e.push(o.mask)}function y(e){let t=p[e.type],n;if(t){let e=BO[t];n=zD.clone(e.uniforms)}else n=e.uniforms;return n}function b(t,n){let r=u.get(n);return r===void 0?(r=new mj(e,n,t,i),l.push(r),u.set(n,r)):++r.usedTimes,r}function x(e){if(--e.usedTimes===0){let t=l.indexOf(e);l[t]=l[l.length-1],l.pop(),u.delete(e.cacheKey),e.destroy()}}function S(e){s.remove(e)}function C(){s.dispose()}return{getParameters:h,getProgramCacheKey:g,getUniforms:y,acquireProgram:b,releaseProgram:x,releaseShaderCache:S,programs:l,dispose:C}}function bj(){let e=/* @__PURE__ */ new WeakMap;function t(t){return e.has(t)}function n(t){let n=e.get(t);return n===void 0&&(n={},e.set(t,n)),n}function r(t){e.delete(t)}function i(t,n,r){e.get(t)[n]=r}function a(){e=/* @__PURE__ */ new WeakMap}return{has:t,get:n,remove:r,update:i,dispose:a}}function xj(e,t){return e.groupOrder===t.groupOrder?e.renderOrder===t.renderOrder?e.material.id===t.material.id?e.materialVariant===t.materialVariant?e.z===t.z?e.id-t.id:e.z-t.z:e.materialVariant-t.materialVariant:e.material.id-t.material.id:e.renderOrder-t.renderOrder:e.groupOrder-t.groupOrder}function Sj(e,t){return e.groupOrder===t.groupOrder?e.renderOrder===t.renderOrder?e.z===t.z?e.id-t.id:t.z-e.z:e.renderOrder-t.renderOrder:e.groupOrder-t.groupOrder}function Cj(){let e=[],t=0,n=[],r=[],i=[];function a(){t=0,n.length=0,r.length=0,i.length=0}function o(e){let t=0;return e.isInstancedMesh&&(t+=2),e.isSkinnedMesh&&(t+=1),t}function s(n,r,i,a,s,c){let l=e[t];return l===void 0?(l={id:n.id,object:n,geometry:r,material:i,materialVariant:o(n),groupOrder:a,renderOrder:n.renderOrder,z:s,group:c},e[t]=l):(l.id=n.id,l.object=n,l.geometry=r,l.material=i,l.materialVariant=o(n),l.groupOrder=a,l.renderOrder=n.renderOrder,l.z=s,l.group=c),t++,l}function c(e,t,a,o,c,l,u){u.reversedDepth===!0&&(c=-c);let d=s(e,t,a,o,c,l);a.transmission>0?r.push(d):a.transparent===!0?i.push(d):n.push(d)}function l(e,t,a,o,c,l){let u=s(e,t,a,o,c,l);a.transmission>0?r.unshift(u):a.transparent===!0?i.unshift(u):n.unshift(u)}function u(e,t){n.length>1&&n.sort(e||xj),r.length>1&&r.sort(t||Sj),i.length>1&&i.sort(t||Sj)}function d(){for(let n=t,r=e.length;n<r;n++){let t=e[n];if(t.id===null)break;t.id=null,t.object=null,t.geometry=null,t.material=null,t.group=null}}return{opaque:n,transmissive:r,transparent:i,init:a,push:c,unshift:l,finish:d,sort:u}}function wj(){let e=/* @__PURE__ */ new WeakMap;function t(t,n){let r=e.get(t),i;return r===void 0?(i=new Cj,e.set(t,[i])):n>=r.length?(i=new Cj,r.push(i)):i=r[n],i}function n(){e=/* @__PURE__ */ new WeakMap}return{get:t,dispose:n}}function Tj(){let e={};return{get:function(t){if(e[t.id]!==void 0)return e[t.id];let n;switch(t.type){case`SunLight`:case`DirectionalLight`:n={direction:new X,color:new QT};break;case`SpotLight`:n={position:new X,direction:new X,color:new QT,distance:0,coneCos:0,penumbraCos:0,decay:0};break;case`PointLight`:n={position:new X,color:new QT,distance:0,decay:0};break;case`HemisphereLight`:n={direction:new X,skyColor:new QT,groundColor:new QT};break;case`RectAreaLight`:n={color:new QT,position:new X,halfWidth:new X,halfHeight:new X}}return e[t.id]=n,n}}}function Ej(){let e={};return{get:function(t){if(e[t.id]!==void 0)return e[t.id];let n;switch(t.type){case`SunLight`:case`DirectionalLight`:n={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new Y};break;case`SpotLight`:n={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new Y};break;case`PointLight`:n={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new Y,shadowCameraNear:1,shadowCameraFar:1e3}}return e[t.id]=n,n}}}var Dj=0;function Oj(e,t){return(t.castShadow?2:0)-(e.castShadow?2:0)+ +!!t.map-!!e.map}function kj(e){let t=new Tj,n=Ej(),r={version:0,hash:{sunLength:-1,directionalLength:-1,pointLength:-1,spotLength:-1,rectAreaLength:-1,hemiLength:-1,numSunShadows:-1,numDirectionalShadows:-1,numPointShadows:-1,numSpotShadows:-1,numSpotMaps:-1,numLightProbes:-1},ambient:[0,0,0],probe:[],sun:[],sunShadow:[],sunShadowMap:[],sunShadowMatrix:[],sunShadowCascade:[],directional:[],directionalShadow:[],directionalShadowMap:[],directionalShadowMatrix:[],spot:[],spotLightMap:[],spotShadow:[],spotShadowMap:[],spotLightMatrix:[],rectArea:[],rectAreaLTC1:null,rectAreaLTC2:null,point:[],pointShadow:[],pointShadowMap:[],pointShadowMatrix:[],hemi:[],numSpotLightShadowsWithMaps:0,numLightProbes:0};for(let e=0;e<9;e++)r.probe.push(new X);let i=new X,a=new _T,o=new _T;function s(i){let a=0,o=0,s=0;for(let e=0;e<9;e++)r.probe[e].set(0,0,0);let c=0,l=0,u=0,d=0,f=0,p=0,m=0,h=0,g=0,_=0,v=0,y=0,b=0,x=0;i.sort(Oj);for(let e=0,S=i.length;e<S;e++){let S=i[e],C=S.color,w=S.intensity,T=S.distance,E=null;if(S.shadow&&S.shadow.map&&(E=S.shadow.map.texture.format===1030?S.shadow.map.texture:S.shadow.map.depthTexture||S.shadow.map.texture),S.isAmbientLight)a+=C.r*w,o+=C.g*w,s+=C.b*w;else if(S.isLightProbe){for(let e=0;e<9;e++)r.probe[e].addScaledVector(S.sh.coefficients[e],w);x++}else if(S.isSunLight){let e=t.get(S);if(e.color.copy(S.color).multiplyScalar(S.intensity),S.castShadow){let e=S.shadow,t=n.get(S);t.shadowIntensity=e.intensity,t.shadowBias=e.bias,t.shadowNormalBias=e.normalBias,t.shadowRadius=e.radius,t.shadowMapSize.copy(e.mapSize).multiply(e.getFrameExtents()),r.sunShadow[l]=t,r.sunShadowMap[l]=E;let i=e.getViewportCount();for(let t=0;t<i;t++)r.sunShadowMatrix[u+t]=e.getMatrix(t),r.sunShadowCascade[u+t]=e._cascadeData[t];u+=i,l++}r.sun[c]=e,c++}else if(S.isDirectionalLight){let e=t.get(S);if(e.color.copy(S.color).multiplyScalar(S.intensity),S.castShadow){let e=S.shadow,t=n.get(S);t.shadowIntensity=e.intensity,t.shadowBias=e.bias,t.shadowNormalBias=e.normalBias,t.shadowRadius=e.radius,t.shadowMapSize=e.mapSize,r.directionalShadow[d]=t,r.directionalShadowMap[d]=E,r.directionalShadowMatrix[d]=S.shadow.matrix,g++}r.directional[d]=e,d++}else if(S.isSpotLight){let e=t.get(S);e.position.setFromMatrixPosition(S.matrixWorld),e.color.copy(C).multiplyScalar(w),e.distance=T,e.coneCos=Math.cos(S.angle),e.penumbraCos=Math.cos(S.angle*(1-S.penumbra)),e.decay=S.decay,r.spot[p]=e;let i=S.shadow;if(S.map&&(r.spotLightMap[y]=S.map,y++,i.updateMatrices(S),S.castShadow&&b++),r.spotLightMatrix[p]=i.matrix,S.castShadow){let e=n.get(S);e.shadowIntensity=i.intensity,e.shadowBias=i.bias,e.shadowNormalBias=i.normalBias,e.shadowRadius=i.radius,e.shadowMapSize=i.mapSize,r.spotShadow[p]=e,r.spotShadowMap[p]=E,v++}p++}else if(S.isRectAreaLight){let e=t.get(S);e.color.copy(C).multiplyScalar(w),e.halfWidth.set(S.width*.5,0,0),e.halfHeight.set(0,S.height*.5,0),r.rectArea[m]=e,m++}else if(S.isPointLight){let e=t.get(S);if(e.color.copy(S.color).multiplyScalar(S.intensity),e.distance=S.distance,e.decay=S.decay,S.castShadow){let e=S.shadow,t=n.get(S);t.shadowIntensity=e.intensity,t.shadowBias=e.bias,t.shadowNormalBias=e.normalBias,t.shadowRadius=e.radius,t.shadowMapSize=e.mapSize,t.shadowCameraNear=e.camera.near,t.shadowCameraFar=e.camera.far,r.pointShadow[f]=t,r.pointShadowMap[f]=E,r.pointShadowMatrix[f]=S.shadow.matrix,_++}r.point[f]=e,f++}else if(S.isHemisphereLight){let e=t.get(S);e.skyColor.copy(S.color).multiplyScalar(w),e.groundColor.copy(S.groundColor).multiplyScalar(w),r.hemi[h]=e,h++}}m>0&&(e.has(`OES_texture_float_linear`)===!0?(r.rectAreaLTC1=$.LTC_FLOAT_1,r.rectAreaLTC2=$.LTC_FLOAT_2):(r.rectAreaLTC1=$.LTC_HALF_1,r.rectAreaLTC2=$.LTC_HALF_2)),r.ambient[0]=a,r.ambient[1]=o,r.ambient[2]=s;let S=r.hash;(S.sunLength!==c||S.directionalLength!==d||S.pointLength!==f||S.spotLength!==p||S.rectAreaLength!==m||S.hemiLength!==h||S.numSunShadows!==l||S.numDirectionalShadows!==g||S.numPointShadows!==_||S.numSpotShadows!==v||S.numSpotMaps!==y||S.numLightProbes!==x)&&(r.sun.length=c,r.directional.length=d,r.spot.length=p,r.rectArea.length=m,r.point.length=f,r.hemi.length=h,r.sunShadow.length=l,r.sunShadowMap.length=l,r.sunShadowMatrix.length=u,r.sunShadowCascade.length=u,r.directionalShadow.length=g,r.directionalShadowMap.length=g,r.directionalShadowMatrix.length=g,r.pointShadow.length=_,r.pointShadowMap.length=_,r.pointShadowMatrix.length=_,r.spotShadow.length=v,r.spotShadowMap.length=v,r.spotLightMatrix.length=v+y-b,r.spotLightMap.length=y,r.numSpotLightShadowsWithMaps=b,r.numLightProbes=x,S.sunLength=c,S.directionalLength=d,S.pointLength=f,S.spotLength=p,S.rectAreaLength=m,S.hemiLength=h,S.numSunShadows=l,S.numDirectionalShadows=g,S.numPointShadows=_,S.numSpotShadows=v,S.numSpotMaps=y,S.numLightProbes=x,r.version=Dj++)}function c(e,t){let n=0,s=0,c=0,l=0,u=0,d=0,f=t.matrixWorldInverse;for(let t=0,p=e.length;t<p;t++){let p=e[t];if(p.isSunLight){let e=r.sun[n];e.direction.setFromMatrixPosition(p.matrixWorld),e.direction.transformDirection(f),n++}else if(p.isDirectionalLight){let e=r.directional[s];e.direction.setFromMatrixPosition(p.matrixWorld),i.setFromMatrixPosition(p.target.matrixWorld),e.direction.sub(i),e.direction.transformDirection(f),s++}else if(p.isSpotLight){let e=r.spot[l];e.position.setFromMatrixPosition(p.matrixWorld),e.position.applyMatrix4(f),e.direction.setFromMatrixPosition(p.matrixWorld),i.setFromMatrixPosition(p.target.matrixWorld),e.direction.sub(i),e.direction.transformDirection(f),l++}else if(p.isRectAreaLight){let e=r.rectArea[u];e.position.setFromMatrixPosition(p.matrixWorld),e.position.applyMatrix4(f),o.identity(),a.copy(p.matrixWorld),a.premultiply(f),o.extractRotation(a),e.halfWidth.set(p.width*.5,0,0),e.halfHeight.set(0,p.height*.5,0),e.halfWidth.applyMatrix4(o),e.halfHeight.applyMatrix4(o),u++}else if(p.isPointLight){let e=r.point[c];e.position.setFromMatrixPosition(p.matrixWorld),e.position.applyMatrix4(f),c++}else if(p.isHemisphereLight){let e=r.hemi[d];e.direction.setFromMatrixPosition(p.matrixWorld),e.direction.transformDirection(f),d++}}}return{setup:s,setupView:c,state:r}}function Aj(e){let t=new kj(e),n=[],r=[],i=[];function a(e){d.camera=e,n.length=0,r.length=0,i.length=0}function o(e){n.push(e)}function s(e){r.push(e)}function c(e){i.push(e)}function l(){t.setup(n)}function u(e){t.setupView(n,e)}let d={lightsArray:n,shadowsArray:r,lightProbeGridArray:i,camera:null,lights:t,transmissionRenderTarget:{},textureUnits:0};return{init:a,state:d,setupLights:l,setupLightsView:u,pushLight:o,pushShadow:s,pushLightProbeGrid:c}}function jj(e){let t=/* @__PURE__ */ new WeakMap;function n(n,r=0){let i=t.get(n),a;return i===void 0?(a=new Aj(e),t.set(n,[a])):r>=i.length?(a=new Aj(e),i.push(a)):a=i[r],a}function r(){t=/* @__PURE__ */ new WeakMap}return{get:n,dispose:r}}var Mj=`void main() {
|
|
4172
4172
|
gl_Position = vec4( position, 1.0 );
|
|
4173
|
-
}`,
|
|
4173
|
+
}`,Nj=`uniform sampler2D shadow_pass;
|
|
4174
4174
|
uniform vec2 resolution;
|
|
4175
4175
|
uniform float radius;
|
|
4176
4176
|
void main() {
|
|
@@ -4195,12 +4195,12 @@ void main() {
|
|
|
4195
4195
|
squared_mean = squared_mean / samples;
|
|
4196
4196
|
float std_dev = sqrt( max( 0.0, squared_mean - mean * mean ) );
|
|
4197
4197
|
gl_FragColor = vec4( mean, std_dev, 0.0, 1.0 );
|
|
4198
|
-
}`,rA=[/*@__PURE__*/ new X(1,0,0),/*@__PURE__*/ new X(-1,0,0),/*@__PURE__*/ new X(0,1,0),/*@__PURE__*/ new X(0,-1,0),/*@__PURE__*/ new X(0,0,1),/*@__PURE__*/ new X(0,0,-1)],iA=[/*@__PURE__*/ new X(0,-1,0),/*@__PURE__*/ new X(0,-1,0),/*@__PURE__*/ new X(0,0,1),/*@__PURE__*/ new X(0,0,-1),/*@__PURE__*/ new X(0,-1,0),/*@__PURE__*/ new X(0,-1,0)],aA=/*@__PURE__*/ new BC,oA=/*@__PURE__*/ new X,sA=/*@__PURE__*/ new X;function cA(e,t,n){let r=new JT,i=new Y,a=new Y,o=new FC,s=new pE,c=new mE,l={},u=n.maxTextureSize,d={0:1,1:0,2:2},f=new dE({defines:{VSM_SAMPLES:8},uniforms:{shadow_pass:{value:null},resolution:{value:new Y},radius:{value:4}},vertexShader:tA,fragmentShader:nA}),p=f.clone();p.defines.HORIZONTAL_PASS=1;let m=new _T;m.setAttribute(`position`,new nT(new Float32Array([-1,-1,.5,3,-1,.5,-1,3,.5]),3));let h=new VT(m,f),g=this;this.enabled=!1,this.autoUpdate=!0,this.needsUpdate=!1,this.type=1;let _=this.type;this.render=function(t,n,s){if(g.enabled===!1||g.autoUpdate===!1&&g.needsUpdate===!1||t.length===0)return;this.type===2&&(q(`WebGLShadowMap: PCFSoftShadowMap has been removed. Using PCFShadowMap instead.`),this.type=1);let c=e.getRenderTarget(),l=e.getActiveCubeFace(),d=e.getActiveMipmapLevel(),f=e.state;f.setBlending(0),f.buffers.depth.getReversed()===!0?f.buffers.color.setClear(0,0,0,0):f.buffers.color.setClear(1,1,1,1),f.buffers.depth.setTest(!0),f.setScissorTest(!1);let p=_!==this.type;p&&n.traverse(function(e){e.material&&(Array.isArray(e.material)?e.material.forEach(e=>e.needsUpdate=!0):e.material.needsUpdate=!0)});for(let c=0,l=t.length;c<l;c++){let l=t[c],d=l.shadow;if(d===void 0){q(`WebGLShadowMap:`,l,`has no shadow.`);continue}if(d.autoUpdate===!1&&d.needsUpdate===!1)continue;i.copy(d.mapSize);let m=d.getFrameExtents();i.multiply(m),a.copy(d.mapSize),(i.x>u||i.y>u)&&(i.x>u&&(a.x=Math.floor(u/m.x),i.x=a.x*m.x,d.mapSize.x=a.x),i.y>u&&(a.y=Math.floor(u/m.y),i.y=a.y*m.y,d.mapSize.y=a.y));let h=e.state.buffers.depth.getReversed();if(d.camera._reversedDepth=h,d.map===null||p===!0){if(d.map!==null&&(d.map.depthTexture!==null&&(d.map.depthTexture.dispose(),d.map.depthTexture=null),d.map.dispose()),this.type===3){if(l.isPointLight){q(`WebGLShadowMap: VSM shadow maps are not supported for PointLights. Use PCF or BasicShadowMap instead.`);continue}d.map=new LC(i.x,i.y,{format:Xx,type:Lx,minFilter:Dx,magFilter:Dx,generateMipmaps:!1}),d.map.texture.name=l.name+`.shadowMap`,d.map.depthTexture=new QT(i.x,i.y,Ix),d.map.depthTexture.name=l.name+`.shadowMapDepth`,d.map.depthTexture.format=Kx,d.map.depthTexture.compareFunction=null,d.map.depthTexture.minFilter=wx,d.map.depthTexture.magFilter=wx}else l.isPointLight?(d.map=new zD(i.x),d.map.depthTexture=new $T(i.x,Fx)):(d.map=new LC(i.x,i.y),d.map.depthTexture=new QT(i.x,i.y,Fx)),d.map.depthTexture.name=l.name+`.shadowMap`,d.map.depthTexture.format=Kx,this.type===1?(d.map.depthTexture.compareFunction=h?518:515,d.map.depthTexture.minFilter=Dx,d.map.depthTexture.magFilter=Dx):(d.map.depthTexture.compareFunction=null,d.map.depthTexture.minFilter=wx,d.map.depthTexture.magFilter=wx);d.camera.updateProjectionMatrix()}d.map.isWebGLCubeRenderTarget!==!0&&(d.map.width!==i.x||d.map.height!==i.y)&&d.map.setSize(i.x,i.y);let g=d.map.isWebGLCubeRenderTarget?6:d.getViewportCount();l.isPointLight!==!0&&d.updateMatrices(l,s);for(let t=0;t<g;t++){let i=d.getCamera(t);if(l.isPointLight){let e=d.camera,n=d.matrix,r=l.distance||e.far;r!==e.far&&(e.far=r,e.updateProjectionMatrix()),oA.setFromMatrixPosition(l.matrixWorld),e.position.copy(oA),sA.copy(e.position),sA.add(rA[t]),e.up.copy(iA[t]),e.lookAt(sA),e.updateMatrixWorld(),n.makeTranslation(-oA.x,-oA.y,-oA.z),aA.multiplyMatrices(e.projectionMatrix,e.matrixWorldInverse),d._frustum.setFromProjectionMatrix(aA,e.coordinateSystem,e.reversedDepth)}if(d.map.isWebGLCubeRenderTarget)e.setRenderTarget(d.map,t),e.clear();else{t===0&&(e.setRenderTarget(d.map),e.clear());let n=d.getViewport(t);o.set(a.x*n.x,a.y*n.y,a.x*n.z,a.y*n.w),f.viewport(o)}r=d.getFrustum(t),b(n,s,i,l,this.type)}d.isPointLightShadow!==!0&&this.type===3&&v(d,s),d.needsUpdate=!1}_=this.type,g.needsUpdate=!1,e.setRenderTarget(c,l,d)};function v(n,r){let a=t.update(h);f.defines.VSM_SAMPLES!==n.blurSamples&&(f.defines.VSM_SAMPLES=n.blurSamples,p.defines.VSM_SAMPLES=n.blurSamples,f.needsUpdate=!0,p.needsUpdate=!0),n.mapPass===null?n.mapPass=new LC(i.x,i.y,{format:Xx,type:Lx}):(n.mapPass.width!==n.map.width||n.mapPass.height!==n.map.height)&&n.mapPass.setSize(n.map.width,n.map.height),f.uniforms.shadow_pass.value=n.map.depthTexture,f.uniforms.resolution.value.set(n.map.width,n.map.height),f.uniforms.radius.value=n.radius,e.setRenderTarget(n.mapPass),e.clear(),e.renderBufferDirect(r,null,a,f,h,null),p.uniforms.shadow_pass.value=n.mapPass.texture,p.uniforms.resolution.value.set(n.map.width,n.map.height),p.uniforms.radius.value=n.radius,e.setRenderTarget(n.map),e.clear(),e.renderBufferDirect(r,null,a,p,h,null)}function y(t,n,r,i){let a=null,o=r.isPointLight===!0?t.customDistanceMaterial:t.customDepthMaterial;if(o!==void 0)a=o;else if(a=r.isPointLight===!0?c:s,e.localClippingEnabled&&n.clipShadows===!0&&Array.isArray(n.clippingPlanes)&&n.clippingPlanes.length!==0||n.displacementMap&&n.displacementScale!==0||n.alphaMap&&n.alphaTest>0||n.map&&n.alphaTest>0||n.alphaToCoverage===!0){let e=a.uuid,t=n.uuid,r=l[e];r===void 0&&(r={},l[e]=r);let i=r[t];i===void 0&&(i=a.clone(),r[t]=i,n.addEventListener(`dispose`,x)),a=i}if(a.visible=n.visible,a.wireframe=n.wireframe,i===3?a.side=n.shadowSide===null?n.side:n.shadowSide:a.side=n.shadowSide===null?d[n.side]:n.shadowSide,a.alphaMap=n.alphaMap,a.alphaTest=n.alphaToCoverage===!0?.5:n.alphaTest,a.map=n.map,a.clipShadows=n.clipShadows,a.clippingPlanes=n.clippingPlanes,a.clipIntersection=n.clipIntersection,a.displacementMap=n.displacementMap,a.displacementScale=n.displacementScale,a.displacementBias=n.displacementBias,a.wireframeLinewidth=n.wireframeLinewidth,a.linewidth=n.linewidth,r.isPointLight===!0&&a.isMeshDistanceMaterial===!0){let t=e.properties.get(a);t.light=r}return a}function b(n,i,a,o,s){if(n.visible===!1)return;if(n.layers.test(i.layers)&&(n.isMesh||n.isLine||n.isPoints)&&(n.castShadow||n.receiveShadow&&s===3)&&(!n.frustumCulled||n.intersectsFrustum(r))){n.modelViewMatrix.multiplyMatrices(a.matrixWorldInverse,n.matrixWorld);let r=t.update(n),c=n.material;if(Array.isArray(c)){let t=r.groups;for(let l=0,u=t.length;l<u;l++){let u=t[l],d=c[u.materialIndex];if(d&&d.visible){let t=y(n,d,o,s);n.onBeforeShadow(e,n,i,a,r,t,u),e.renderBufferDirect(a,null,r,t,n,u),n.onAfterShadow(e,n,i,a,r,t,u)}}}else if(c.visible){let t=y(n,c,o,s);n.onBeforeShadow(e,n,i,a,r,t,null),e.renderBufferDirect(a,null,r,t,n,null),n.onAfterShadow(e,n,i,a,r,t,null)}}let c=n.children;for(let e=0,t=c.length;e<t;e++)b(c[e],i,a,o,s)}function x(e){e.target.removeEventListener(`dispose`,x);for(let t in l){let n=l[t],r=e.target.uuid;r in n&&(n[r].dispose(),delete n[r])}}}function lA(e,t){function n(){let t=!1,n=new FC,r=null,i=new FC(0,0,0,0);return{setMask:function(n){r!==n&&!t&&(e.colorMask(n,n,n,n),r=n)},setLocked:function(e){t=e},setClear:function(t,r,a,o,s){s===!0&&(t*=o,r*=o,a*=o),n.set(t,r,a,o),i.equals(n)===!1&&(e.clearColor(t,r,a,o),i.copy(n))},reset:function(){t=!1,r=null,i.set(-1,0,0,0)}}}function r(){let n=!1,r=!1,i=null,a=null,o=null;return{setReversed:function(e){if(r!==e){let n=t.get(`EXT_clip_control`);e?n.clipControlEXT(n.LOWER_LEFT_EXT,n.ZERO_TO_ONE_EXT):n.clipControlEXT(n.LOWER_LEFT_EXT,n.NEGATIVE_ONE_TO_ONE_EXT),r=e;let i=o;o=null,this.setClear(i)}},getReversed:function(){return r},setTest:function(t){t?ue(e.DEPTH_TEST):de(e.DEPTH_TEST)},setMask:function(t){i!==t&&!n&&(e.depthMask(t),i=t)},setFunc:function(t){if(r&&(t=oC[t]),a!==t){switch(t){case 0:e.depthFunc(e.NEVER);break;case 1:e.depthFunc(e.ALWAYS);break;case 2:e.depthFunc(e.LESS);break;case 3:e.depthFunc(e.LEQUAL);break;case 4:e.depthFunc(e.EQUAL);break;case 5:e.depthFunc(e.GEQUAL);break;case 6:e.depthFunc(e.GREATER);break;case 7:e.depthFunc(e.NOTEQUAL);break;default:e.depthFunc(e.LEQUAL)}a=t}},setLocked:function(e){n=e},setClear:function(t){o!==t&&(o=t,r&&(t=1-t),e.clearDepth(t))},reset:function(){n=!1,i=null,a=null,o=null,r=!1}}}function i(){let t=!1,n=null,r=null,i=null,a=null,o=null,s=null,c=null,l=null;return{setTest:function(n){t||(n?ue(e.STENCIL_TEST):de(e.STENCIL_TEST))},setMask:function(r){n!==r&&!t&&(e.stencilMask(r),n=r)},setFunc:function(t,n,o){(r!==t||i!==n||a!==o)&&(e.stencilFunc(t,n,o),r=t,i=n,a=o)},setOp:function(t,n,r){(o!==t||s!==n||c!==r)&&(e.stencilOp(t,n,r),o=t,s=n,c=r)},setLocked:function(e){t=e},setClear:function(t){l!==t&&(e.clearStencil(t),l=t)},reset:function(){t=!1,n=null,r=null,i=null,a=null,o=null,s=null,c=null,l=null}}}let a=new n,o=new r,s=new i,c=/* @__PURE__ */ new WeakMap,l=/* @__PURE__ */ new WeakMap,u={},d={},f={},p=/* @__PURE__ */ new WeakMap,m=[],h=null,g=!1,_=null,v=null,y=null,b=null,x=null,S=null,C=null,w=new xw(0,0,0),T=0,E=!1,D=null,O=null,k=null,A=null,ee=null,te=e.getParameter(e.MAX_COMBINED_TEXTURE_IMAGE_UNITS),j=!1,ne=0,re=e.getParameter(e.VERSION);re.indexOf(`WebGL`)===-1?re.indexOf(`OpenGL ES`)!==-1&&(ne=parseFloat(/^OpenGL ES (\d)/.exec(re)[1]),j=ne>=2):(ne=parseFloat(/^WebGL (\d)/.exec(re)[1]),j=ne>=1);let M=null,ie={},N=e.getParameter(e.SCISSOR_BOX),ae=e.getParameter(e.VIEWPORT),oe=new FC().fromArray(N),se=new FC().fromArray(ae);function ce(t,n,r,i){let a=/* @__PURE__ */ new Uint8Array(4),o=e.createTexture();e.bindTexture(t,o),e.texParameteri(t,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(t,e.TEXTURE_MAG_FILTER,e.NEAREST);for(let o=0;o<r;o++)t===e.TEXTURE_3D||t===e.TEXTURE_2D_ARRAY?e.texImage3D(n,0,e.RGBA,1,1,i,0,e.RGBA,e.UNSIGNED_BYTE,a):e.texImage2D(n+o,0,e.RGBA,1,1,0,e.RGBA,e.UNSIGNED_BYTE,a);return o}let le={};le[e.TEXTURE_2D]=ce(e.TEXTURE_2D,e.TEXTURE_2D,1),le[e.TEXTURE_CUBE_MAP]=ce(e.TEXTURE_CUBE_MAP,e.TEXTURE_CUBE_MAP_POSITIVE_X,6),le[e.TEXTURE_2D_ARRAY]=ce(e.TEXTURE_2D_ARRAY,e.TEXTURE_2D_ARRAY,1,1),le[e.TEXTURE_3D]=ce(e.TEXTURE_3D,e.TEXTURE_3D,1,1),a.setClear(0,0,0,1),o.setClear(1),s.setClear(0),ue(e.DEPTH_TEST),o.setFunc(3),ye(!1),be(1),ue(e.CULL_FACE),_e(0);function ue(t){u[t]!==!0&&(e.enable(t),u[t]=!0)}function de(t){u[t]!==!1&&(e.disable(t),u[t]=!1)}function fe(t,n){return f[t]!==n&&(e.bindFramebuffer(t,n),f[t]=n,t===e.DRAW_FRAMEBUFFER&&(f[e.FRAMEBUFFER]=n),t===e.FRAMEBUFFER&&(f[e.DRAW_FRAMEBUFFER]=n),!0)}function pe(t,n){let r=m,i=!1;if(t){r=p.get(n),r===void 0&&(r=[],p.set(n,r));let a=t.textures;if(r.length!==a.length||r[0]!==e.COLOR_ATTACHMENT0){for(let t=0,n=a.length;t<n;t++)r[t]=e.COLOR_ATTACHMENT0+t;r.length=a.length,i=!0}}else r[0]!==e.BACK&&(r[0]=e.BACK,i=!0);i&&e.drawBuffers(r)}function me(t){return h!==t&&(e.useProgram(t),h=t,!0)}let he={100:e.FUNC_ADD,101:e.FUNC_SUBTRACT,102:e.FUNC_REVERSE_SUBTRACT};he[103]=e.MIN,he[104]=e.MAX;let ge={200:e.ZERO,201:e.ONE,202:e.SRC_COLOR,204:e.SRC_ALPHA,210:e.SRC_ALPHA_SATURATE,208:e.DST_COLOR,206:e.DST_ALPHA,203:e.ONE_MINUS_SRC_COLOR,205:e.ONE_MINUS_SRC_ALPHA,209:e.ONE_MINUS_DST_COLOR,207:e.ONE_MINUS_DST_ALPHA,211:e.CONSTANT_COLOR,212:e.ONE_MINUS_CONSTANT_COLOR,213:e.CONSTANT_ALPHA,214:e.ONE_MINUS_CONSTANT_ALPHA};function _e(t,n,r,i,a,o,s,c,l,u){if(t===0){g===!0&&(de(e.BLEND),g=!1);return}if(g===!1&&(ue(e.BLEND),g=!0),t!==5){if(t!==_||u!==E){if((v!==100||x!==100)&&(e.blendEquation(e.FUNC_ADD),v=100,x=100),u)switch(t){case 1:e.blendFuncSeparate(e.ONE,e.ONE_MINUS_SRC_ALPHA,e.ONE,e.ONE_MINUS_SRC_ALPHA);break;case 2:e.blendFunc(e.ONE,e.ONE);break;case 3:e.blendFuncSeparate(e.ZERO,e.ONE_MINUS_SRC_COLOR,e.ZERO,e.ONE);break;case 4:e.blendFuncSeparate(e.DST_COLOR,e.ONE_MINUS_SRC_ALPHA,e.ZERO,e.ONE);break;default:J(`WebGLState: Invalid blending: `,t)}else switch(t){case 1:e.blendFuncSeparate(e.SRC_ALPHA,e.ONE_MINUS_SRC_ALPHA,e.ONE,e.ONE_MINUS_SRC_ALPHA);break;case 2:e.blendFuncSeparate(e.SRC_ALPHA,e.ONE,e.ONE,e.ONE);break;case 3:J(`WebGLState: SubtractiveBlending requires material.premultipliedAlpha = true`);break;case 4:J(`WebGLState: MultiplyBlending requires material.premultipliedAlpha = true`);break;default:J(`WebGLState: Invalid blending: `,t)}y=null,b=null,S=null,C=null,w.set(0,0,0),T=0,_=t,E=u}return}a||=n,o||=r,s||=i,(n!==v||a!==x)&&(e.blendEquationSeparate(he[n],he[a]),v=n,x=a),(r!==y||i!==b||o!==S||s!==C)&&(e.blendFuncSeparate(ge[r],ge[i],ge[o],ge[s]),y=r,b=i,S=o,C=s),(c.equals(w)===!1||l!==T)&&(e.blendColor(c.r,c.g,c.b,l),w.copy(c),T=l),_=t,E=!1}function ve(t,n){t.side===2?de(e.CULL_FACE):ue(e.CULL_FACE);let r=t.side===1;n&&(r=!r),ye(r),t.blending===1&&t.transparent===!1?_e(0):_e(t.blending,t.blendEquation,t.blendSrc,t.blendDst,t.blendEquationAlpha,t.blendSrcAlpha,t.blendDstAlpha,t.blendColor,t.blendAlpha,t.premultipliedAlpha),o.setFunc(t.depthFunc),o.setTest(t.depthTest),o.setMask(t.depthWrite),a.setMask(t.colorWrite);let i=t.stencilWrite;s.setTest(i),i&&(s.setMask(t.stencilWriteMask),s.setFunc(t.stencilFunc,t.stencilRef,t.stencilFuncMask),s.setOp(t.stencilFail,t.stencilZFail,t.stencilZPass)),Se(t.polygonOffset,t.polygonOffsetFactor,t.polygonOffsetUnits),t.alphaToCoverage===!0?ue(e.SAMPLE_ALPHA_TO_COVERAGE):de(e.SAMPLE_ALPHA_TO_COVERAGE)}function ye(t){D!==t&&(t?e.frontFace(e.CW):e.frontFace(e.CCW),D=t)}function be(t){t===0?de(e.CULL_FACE):(ue(e.CULL_FACE),t!==O&&(t===1?e.cullFace(e.BACK):t===2?e.cullFace(e.FRONT):e.cullFace(e.FRONT_AND_BACK))),O=t}function xe(t){t!==k&&(j&&e.lineWidth(t),k=t)}function Se(t,n,r){t?(ue(e.POLYGON_OFFSET_FILL),(A!==n||ee!==r)&&(A=n,ee=r,o.getReversed()&&(n=-n),e.polygonOffset(n,r))):de(e.POLYGON_OFFSET_FILL)}function Ce(t){t?ue(e.SCISSOR_TEST):de(e.SCISSOR_TEST)}function P(t){t===void 0&&(t=e.TEXTURE0+te-1),M!==t&&(e.activeTexture(t),M=t)}function we(t,n,r){r===void 0&&(r=M===null?e.TEXTURE0+te-1:M);let i=ie[r];i===void 0&&(i={type:void 0,texture:void 0},ie[r]=i),(i.type!==t||i.texture!==n)&&(M!==r&&(e.activeTexture(r),M=r),e.bindTexture(t,n||le[t]),i.type=t,i.texture=n)}function Te(){let t=ie[M];t!==void 0&&t.type!==void 0&&(e.bindTexture(t.type,null),t.type=void 0,t.texture=void 0)}function Ee(){try{e.compressedTexImage2D(...arguments)}catch(e){J(`WebGLState:`,e)}}function F(){try{e.compressedTexImage3D(...arguments)}catch(e){J(`WebGLState:`,e)}}function De(){try{e.texSubImage2D(...arguments)}catch(e){J(`WebGLState:`,e)}}function I(){try{e.texSubImage3D(...arguments)}catch(e){J(`WebGLState:`,e)}}function L(){try{e.compressedTexSubImage2D(...arguments)}catch(e){J(`WebGLState:`,e)}}function Oe(){try{e.compressedTexSubImage3D(...arguments)}catch(e){J(`WebGLState:`,e)}}function ke(){try{e.texStorage2D(...arguments)}catch(e){J(`WebGLState:`,e)}}function Ae(){try{e.texStorage3D(...arguments)}catch(e){J(`WebGLState:`,e)}}function je(){try{e.texImage2D(...arguments)}catch(e){J(`WebGLState:`,e)}}function Me(){try{e.texImage3D(...arguments)}catch(e){J(`WebGLState:`,e)}}function Ne(t){return d[t]===void 0?e.getParameter(t):d[t]}function Pe(t,n){d[t]!==n&&(e.pixelStorei(t,n),d[t]=n)}function Fe(t){oe.equals(t)===!1&&(e.scissor(t.x,t.y,t.z,t.w),oe.copy(t))}function Ie(t){se.equals(t)===!1&&(e.viewport(t.x,t.y,t.z,t.w),se.copy(t))}function Le(t,n){let r=l.get(n);r===void 0&&(r=/* @__PURE__ */ new WeakMap,l.set(n,r));let i=r.get(t);i===void 0&&(i=e.getUniformBlockIndex(n,t.name),r.set(t,i))}function Re(t,n){let r=l.get(n).get(t);c.get(n)!==r&&(e.uniformBlockBinding(n,r,t.__bindingPointIndex),c.set(n,r))}function ze(){e.disable(e.BLEND),e.disable(e.CULL_FACE),e.disable(e.DEPTH_TEST),e.disable(e.POLYGON_OFFSET_FILL),e.disable(e.SCISSOR_TEST),e.disable(e.STENCIL_TEST),e.disable(e.SAMPLE_ALPHA_TO_COVERAGE),e.blendEquation(e.FUNC_ADD),e.blendFunc(e.ONE,e.ZERO),e.blendFuncSeparate(e.ONE,e.ZERO,e.ONE,e.ZERO),e.blendColor(0,0,0,0),e.colorMask(!0,!0,!0,!0),e.clearColor(0,0,0,0),e.depthMask(!0),e.depthFunc(e.LESS),o.setReversed(!1),e.clearDepth(1),e.stencilMask(4294967295),e.stencilFunc(e.ALWAYS,0,4294967295),e.stencilOp(e.KEEP,e.KEEP,e.KEEP),e.clearStencil(0),e.cullFace(e.BACK),e.frontFace(e.CCW),e.polygonOffset(0,0),e.activeTexture(e.TEXTURE0),e.bindFramebuffer(e.FRAMEBUFFER,null),e.bindFramebuffer(e.DRAW_FRAMEBUFFER,null),e.bindFramebuffer(e.READ_FRAMEBUFFER,null),e.useProgram(null),e.lineWidth(1),e.scissor(0,0,e.canvas.width,e.canvas.height),e.viewport(0,0,e.canvas.width,e.canvas.height),e.pixelStorei(e.PACK_ALIGNMENT,4),e.pixelStorei(e.UNPACK_ALIGNMENT,4),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,!1),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,!1),e.pixelStorei(e.UNPACK_COLORSPACE_CONVERSION_WEBGL,e.BROWSER_DEFAULT_WEBGL),e.pixelStorei(e.PACK_ROW_LENGTH,0),e.pixelStorei(e.PACK_SKIP_PIXELS,0),e.pixelStorei(e.PACK_SKIP_ROWS,0),e.pixelStorei(e.UNPACK_ROW_LENGTH,0),e.pixelStorei(e.UNPACK_IMAGE_HEIGHT,0),e.pixelStorei(e.UNPACK_SKIP_PIXELS,0),e.pixelStorei(e.UNPACK_SKIP_ROWS,0),e.pixelStorei(e.UNPACK_SKIP_IMAGES,0),u={},d={},M=null,ie={},f={},p=/* @__PURE__ */ new WeakMap,m=[],h=null,g=!1,_=null,v=null,y=null,b=null,x=null,S=null,C=null,w=new xw(0,0,0),T=0,E=!1,D=null,O=null,k=null,A=null,ee=null,oe.set(0,0,e.canvas.width,e.canvas.height),se.set(0,0,e.canvas.width,e.canvas.height),a.reset(),o.reset(),s.reset()}return{buffers:{color:a,depth:o,stencil:s},enable:ue,disable:de,bindFramebuffer:fe,drawBuffers:pe,useProgram:me,setBlending:_e,setMaterial:ve,setFlipSided:ye,setCullFace:be,setLineWidth:xe,setPolygonOffset:Se,setScissorTest:Ce,activeTexture:P,bindTexture:we,unbindTexture:Te,compressedTexImage2D:Ee,compressedTexImage3D:F,texImage2D:je,texImage3D:Me,pixelStorei:Pe,getParameter:Ne,updateUBOMapping:Le,uniformBlockBinding:Re,texStorage2D:ke,texStorage3D:Ae,texSubImage2D:De,texSubImage3D:I,compressedTexSubImage2D:L,compressedTexSubImage3D:Oe,scissor:Fe,viewport:Ie,reset:ze}}function uA(e,t,n,r,i,a,o){let s=t.has(`WEBGL_multisampled_render_to_texture`)?t.get(`WEBGL_multisampled_render_to_texture`):null,c=typeof navigator>`u`?!1:/OculusBrowser/g.test(navigator.userAgent),l=new Y,u=/* @__PURE__ */ new WeakMap,d=/* @__PURE__ */ new Set,f,p=/* @__PURE__ */ new WeakMap,m=!1;try{m=typeof OffscreenCanvas<`u`&&new OffscreenCanvas(1,1).getContext(`2d`)!==null}catch{}function h(e,t){return m?new OffscreenCanvas(e,t):$S(`canvas`)}function g(e,t,n){let r=1,i=Ee(e);if((i.width>n||i.height>n)&&(r=n/Math.max(i.width,i.height)),r<1){if(typeof HTMLImageElement<`u`&&e instanceof HTMLImageElement||typeof HTMLCanvasElement<`u`&&e instanceof HTMLCanvasElement||typeof ImageBitmap<`u`&&e instanceof ImageBitmap||typeof VideoFrame<`u`&&e instanceof VideoFrame){let n=Math.floor(r*i.width),a=Math.floor(r*i.height);f===void 0&&(f=h(n,a));let o=t?h(n,a):f;return o.width=n,o.height=a,o.getContext(`2d`).drawImage(e,0,0,n,a),q(`WebGLRenderer: Texture has been resized from (`+i.width+`x`+i.height+`) to (`+n+`x`+a+`).`),o}return`data`in e&&q(`WebGLRenderer: Image in DataTexture is too big (`+i.width+`x`+i.height+`).`),e}return e}function _(e){return e.generateMipmaps}function v(t){e.generateMipmap(t)}function y(t){return t.isWebGLCubeRenderTarget?e.TEXTURE_CUBE_MAP:t.isWebGL3DRenderTarget?e.TEXTURE_3D:t.isWebGLArrayRenderTarget||t.isCompressedArrayTexture?e.TEXTURE_2D_ARRAY:e.TEXTURE_2D}function b(n,r,i,a,o,s=!1){if(n!==null){if(e[n]!==void 0)return e[n];q(`WebGLRenderer: Attempt to use non-existing WebGL internal format '`+n+`'`)}let c;a&&(c=t.get(`EXT_texture_norm16`),c||q(`WebGLRenderer: Unable to use normalized textures without EXT_texture_norm16 extension`));let l=r;if(r===e.RED&&(i===e.FLOAT&&(l=e.R32F),i===e.HALF_FLOAT&&(l=e.R16F),i===e.UNSIGNED_BYTE&&(l=e.R8),i===e.UNSIGNED_SHORT&&c&&(l=c.R16_EXT),i===e.SHORT&&c&&(l=c.R16_SNORM_EXT)),r===e.RED_INTEGER&&(i===e.UNSIGNED_BYTE&&(l=e.R8UI),i===e.UNSIGNED_SHORT&&(l=e.R16UI),i===e.UNSIGNED_INT&&(l=e.R32UI),i===e.BYTE&&(l=e.R8I),i===e.SHORT&&(l=e.R16I),i===e.INT&&(l=e.R32I)),r===e.RG&&(i===e.FLOAT&&(l=e.RG32F),i===e.HALF_FLOAT&&(l=e.RG16F),i===e.UNSIGNED_BYTE&&(l=e.RG8),i===e.UNSIGNED_SHORT&&c&&(l=c.RG16_EXT),i===e.SHORT&&c&&(l=c.RG16_SNORM_EXT)),r===e.RG_INTEGER&&(i===e.UNSIGNED_BYTE&&(l=e.RG8UI),i===e.UNSIGNED_SHORT&&(l=e.RG16UI),i===e.UNSIGNED_INT&&(l=e.RG32UI),i===e.BYTE&&(l=e.RG8I),i===e.SHORT&&(l=e.RG16I),i===e.INT&&(l=e.RG32I)),r===e.RGB_INTEGER&&(i===e.UNSIGNED_BYTE&&(l=e.RGB8UI),i===e.UNSIGNED_SHORT&&(l=e.RGB16UI),i===e.UNSIGNED_INT&&(l=e.RGB32UI),i===e.BYTE&&(l=e.RGB8I),i===e.SHORT&&(l=e.RGB16I),i===e.INT&&(l=e.RGB32I)),r===e.RGBA_INTEGER&&(i===e.UNSIGNED_BYTE&&(l=e.RGBA8UI),i===e.UNSIGNED_SHORT&&(l=e.RGBA16UI),i===e.UNSIGNED_INT&&(l=e.RGBA32UI),i===e.BYTE&&(l=e.RGBA8I),i===e.SHORT&&(l=e.RGBA16I),i===e.INT&&(l=e.RGBA32I)),r===e.RGB&&(i===e.UNSIGNED_SHORT&&c&&(l=c.RGB16_EXT),i===e.SHORT&&c&&(l=c.RGB16_SNORM_EXT),i===e.UNSIGNED_INT_5_9_9_9_REV&&(l=e.RGB9_E5),i===e.UNSIGNED_INT_10F_11F_11F_REV&&(l=e.R11F_G11F_B10F)),r===e.RGBA){let t=s?GS:wC.getTransfer(o);i===e.FLOAT&&(l=e.RGBA32F),i===e.HALF_FLOAT&&(l=e.RGBA16F),i===e.UNSIGNED_BYTE&&(l=t===`srgb`?e.SRGB8_ALPHA8:e.RGBA8),i===e.UNSIGNED_SHORT&&c&&(l=c.RGBA16_EXT),i===e.SHORT&&c&&(l=c.RGBA16_SNORM_EXT),i===e.UNSIGNED_SHORT_4_4_4_4&&(l=e.RGBA4),i===e.UNSIGNED_SHORT_5_5_5_1&&(l=e.RGB5_A1)}return(l===e.R16F||l===e.R32F||l===e.RG16F||l===e.RG32F||l===e.RGBA16F||l===e.RGBA32F)&&t.get(`EXT_color_buffer_float`),l}function x(t,n){let r;return t?n===null||n===1014||n===1020?r=e.DEPTH24_STENCIL8:n===1015?r=e.DEPTH32F_STENCIL8:n===1012&&(r=e.DEPTH24_STENCIL8,q(`DepthTexture: 16 bit depth attachment is not supported with stencil. Using 24-bit attachment.`)):n===null||n===1014||n===1020?r=e.DEPTH_COMPONENT24:n===1015?r=e.DEPTH_COMPONENT32F:n===1012&&(r=e.DEPTH_COMPONENT16),r}function S(e,t){return _(e)===!0||e.isFramebufferTexture&&e.minFilter!==1003&&e.minFilter!==1006?Math.log2(Math.max(t.width,t.height))+1:e.mipmaps!==void 0&&e.mipmaps.length>0?e.mipmaps.length:e.isCompressedTexture&&Array.isArray(e.image)?t.mipmaps.length:1}function C(e){let t=e.target;t.removeEventListener(`dispose`,C),T(t),t.isVideoTexture&&u.delete(t),t.isHTMLTexture&&d.delete(t)}function w(e){let t=e.target;t.removeEventListener(`dispose`,w),D(t)}function T(e){let t=r.get(e);if(t.__webglInit===void 0)return;let n=e.source,i=p.get(n);if(i){let r=i[t.__cacheKey];r.usedTimes--,r.usedTimes===0&&E(e),Object.keys(i).length===0&&p.delete(n)}r.remove(e)}function E(t){let n=r.get(t);e.deleteTexture(n.__webglTexture);let i=t.source,a=p.get(i);delete a[n.__cacheKey],o.memory.textures--}function D(t){let n=r.get(t);if(t.depthTexture&&(t.depthTexture.dispose(),r.remove(t.depthTexture)),t.isWebGLCubeRenderTarget)for(let t=0;t<6;t++){if(Array.isArray(n.__webglFramebuffer[t]))for(let r=0;r<n.__webglFramebuffer[t].length;r++)e.deleteFramebuffer(n.__webglFramebuffer[t][r]);else e.deleteFramebuffer(n.__webglFramebuffer[t]);n.__webglDepthbuffer&&e.deleteRenderbuffer(n.__webglDepthbuffer[t])}else{if(Array.isArray(n.__webglFramebuffer))for(let t=0;t<n.__webglFramebuffer.length;t++)e.deleteFramebuffer(n.__webglFramebuffer[t]);else e.deleteFramebuffer(n.__webglFramebuffer);if(n.__webglDepthbuffer&&e.deleteRenderbuffer(n.__webglDepthbuffer),n.__webglMultisampledFramebuffer&&e.deleteFramebuffer(n.__webglMultisampledFramebuffer),n.__webglColorRenderbuffer)for(let t=0;t<n.__webglColorRenderbuffer.length;t++)n.__webglColorRenderbuffer[t]&&e.deleteRenderbuffer(n.__webglColorRenderbuffer[t]);n.__webglDepthRenderbuffer&&e.deleteRenderbuffer(n.__webglDepthRenderbuffer)}let i=t.textures;for(let t=0,n=i.length;t<n;t++){let n=r.get(i[t]);n.__webglTexture&&(e.deleteTexture(n.__webglTexture),o.memory.textures--),r.remove(i[t])}r.remove(t)}let O=0;function k(){O=0}function A(){return O}function ee(e){O=e}function te(){let e=O;return e>=i.maxTextures&&q(`WebGLTextures: Trying to use `+(e+1)+` texture units while this GPU supports only `+i.maxTextures),O+=1,e}function j(e){let t=[];return t.push(e.wrapS),t.push(e.wrapT),t.push(e.wrapR||0),t.push(e.magFilter),t.push(e.minFilter),t.push(e.anisotropy),t.push(e.internalFormat),t.push(e.format),t.push(e.type),t.push(e.generateMipmaps),t.push(e.premultiplyAlpha),t.push(e.flipY),t.push(e.unpackAlignment),t.push(e.colorSpace),t.join()}function ne(t,i){let a=r.get(t);if(t.isVideoTexture&&we(t),t.isRenderTargetTexture===!1&&t.isExternalTexture!==!0&&t.version>0&&a.__version!==t.version){let e=t.image;if(e===null)q(`WebGLRenderer: Texture marked for update but no image data found.`);else if(e.complete===!1)q(`WebGLRenderer: Texture marked for update but image is incomplete`);else{de(a,t,i);return}}else t.isExternalTexture&&(a.__webglTexture=t.sourceTexture?t.sourceTexture:null);n.bindTexture(e.TEXTURE_2D,a.__webglTexture,e.TEXTURE0+i)}function re(t,i){let a=r.get(t);if(t.isRenderTargetTexture===!1&&t.version>0&&a.__version!==t.version){de(a,t,i);return}t.isExternalTexture&&(a.__webglTexture=t.sourceTexture?t.sourceTexture:null),n.bindTexture(e.TEXTURE_2D_ARRAY,a.__webglTexture,e.TEXTURE0+i)}function M(t,i){let a=r.get(t);if(t.isRenderTargetTexture===!1&&t.version>0&&a.__version!==t.version){de(a,t,i);return}n.bindTexture(e.TEXTURE_3D,a.__webglTexture,e.TEXTURE0+i)}function ie(t,i){let a=r.get(t);if(t.isCubeDepthTexture!==!0&&t.version>0&&a.__version!==t.version){fe(a,t,i);return}n.bindTexture(e.TEXTURE_CUBE_MAP,a.__webglTexture,e.TEXTURE0+i)}let N={[xx]:e.REPEAT,[Sx]:e.CLAMP_TO_EDGE,[Cx]:e.MIRRORED_REPEAT},ae={[wx]:e.NEAREST,[Tx]:e.NEAREST_MIPMAP_NEAREST,[Ex]:e.NEAREST_MIPMAP_LINEAR,[Dx]:e.LINEAR,[Ox]:e.LINEAR_MIPMAP_NEAREST,[kx]:e.LINEAR_MIPMAP_LINEAR},oe={512:e.NEVER,519:e.ALWAYS,513:e.LESS,515:e.LEQUAL,514:e.EQUAL,518:e.GEQUAL,516:e.GREATER,517:e.NOTEQUAL};function se(n,a){if(a.type===1015&&t.has(`OES_texture_float_linear`)===!1&&(a.magFilter===1006||a.magFilter===1007||a.magFilter===1005||a.magFilter===1008||a.minFilter===1006||a.minFilter===1007||a.minFilter===1005||a.minFilter===1008)&&q(`WebGLRenderer: Unable to use linear filtering with floating point textures. OES_texture_float_linear not supported on this device.`),e.texParameteri(n,e.TEXTURE_WRAP_S,N[a.wrapS]),e.texParameteri(n,e.TEXTURE_WRAP_T,N[a.wrapT]),(n===e.TEXTURE_3D||n===e.TEXTURE_2D_ARRAY)&&e.texParameteri(n,e.TEXTURE_WRAP_R,N[a.wrapR]),e.texParameteri(n,e.TEXTURE_MAG_FILTER,ae[a.magFilter]),e.texParameteri(n,e.TEXTURE_MIN_FILTER,ae[a.minFilter]),a.compareFunction&&(e.texParameteri(n,e.TEXTURE_COMPARE_MODE,e.COMPARE_REF_TO_TEXTURE),e.texParameteri(n,e.TEXTURE_COMPARE_FUNC,oe[a.compareFunction])),t.has(`EXT_texture_filter_anisotropic`)===!0){if(a.magFilter===1003||a.minFilter!==1005&&a.minFilter!==1008||a.type===1015&&t.has(`OES_texture_float_linear`)===!1)return;if(a.anisotropy>1||r.get(a).__currentAnisotropy){let o=t.get(`EXT_texture_filter_anisotropic`);e.texParameterf(n,o.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(a.anisotropy,i.getMaxAnisotropy())),r.get(a).__currentAnisotropy=a.anisotropy}}}function ce(t,n){let r=!1;t.__webglInit===void 0&&(t.__webglInit=!0,n.addEventListener(`dispose`,C));let i=n.source,a=p.get(i);a===void 0&&(a={},p.set(i,a));let s=j(n);if(s!==t.__cacheKey){a[s]===void 0&&(a[s]={texture:e.createTexture(),usedTimes:0},o.memory.textures++,r=!0),a[s].usedTimes++;let i=a[t.__cacheKey];i!==void 0&&(a[t.__cacheKey].usedTimes--,i.usedTimes===0&&E(n)),t.__cacheKey=s,t.__webglTexture=a[s].texture}return r}function le(e,t,n){return Math.floor(Math.floor(e/n)/t)}function ue(t,r,i,a){let o=t.updateRanges;if(o.length===0)n.texSubImage2D(e.TEXTURE_2D,0,0,0,r.width,r.height,i,a,r.data);else{o.sort((e,t)=>e.start-t.start);let s=0;for(let e=1;e<o.length;e++){let t=o[s],n=o[e],i=t.start+t.count,a=le(n.start,r.width,4),c=le(t.start,r.width,4);n.start<=i+1&&a===c&&le(n.start+n.count-1,r.width,4)===a?t.count=Math.max(t.count,n.start+n.count-t.start):(++s,o[s]=n)}o.length=s+1;let c=n.getParameter(e.UNPACK_ROW_LENGTH),l=n.getParameter(e.UNPACK_SKIP_PIXELS),u=n.getParameter(e.UNPACK_SKIP_ROWS);n.pixelStorei(e.UNPACK_ROW_LENGTH,r.width);for(let t=0,s=o.length;t<s;t++){let s=o[t],c=Math.floor(s.start/4),l=Math.ceil(s.count/4),u=c%r.width,d=Math.floor(c/r.width),f=l;n.pixelStorei(e.UNPACK_SKIP_PIXELS,u),n.pixelStorei(e.UNPACK_SKIP_ROWS,d),n.texSubImage2D(e.TEXTURE_2D,0,u,d,f,1,i,a,r.data)}t.clearUpdateRanges(),n.pixelStorei(e.UNPACK_ROW_LENGTH,c),n.pixelStorei(e.UNPACK_SKIP_PIXELS,l),n.pixelStorei(e.UNPACK_SKIP_ROWS,u)}}function de(t,o,s){let c=e.TEXTURE_2D;(o.isDataArrayTexture||o.isCompressedArrayTexture)&&(c=e.TEXTURE_2D_ARRAY),o.isData3DTexture&&(c=e.TEXTURE_3D);let l=ce(t,o),u=o.source;n.bindTexture(c,t.__webglTexture,e.TEXTURE0+s);let f=r.get(u);if(u.version!==f.__version||l===!0){if(n.activeTexture(e.TEXTURE0+s),!(typeof ImageBitmap<`u`&&o.image instanceof ImageBitmap)){let t=wC.getPrimaries(wC.workingColorSpace),r=o.colorSpace===``?null:wC.getPrimaries(o.colorSpace),i=o.colorSpace===``||t===r?e.NONE:e.BROWSER_DEFAULT_WEBGL;n.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,o.flipY),n.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,o.premultiplyAlpha),n.pixelStorei(e.UNPACK_COLORSPACE_CONVERSION_WEBGL,i)}n.pixelStorei(e.UNPACK_ALIGNMENT,o.unpackAlignment);let t=g(o.image,!1,i.maxTextureSize);t=Te(o,t);let r=a.convert(o.format,o.colorSpace),p=a.convert(o.type),m=b(o.internalFormat,r,p,o.normalized,o.colorSpace,o.isVideoTexture);se(c,o);let h,y=o.mipmaps,C=o.isVideoTexture!==!0,w=f.__version===void 0||l===!0,T=u.dataReady,E=S(o,t);if(o.isDepthTexture)m=x(o.format===qx,o.type),w&&(C?n.texStorage2D(e.TEXTURE_2D,1,m,t.width,t.height):n.texImage2D(e.TEXTURE_2D,0,m,t.width,t.height,0,r,p,null));else if(o.isDataTexture){if(y.length>0){C&&w&&n.texStorage2D(e.TEXTURE_2D,E,m,y[0].width,y[0].height);for(let t=0,i=y.length;t<i;t++)h=y[t],C?T&&n.texSubImage2D(e.TEXTURE_2D,t,0,0,h.width,h.height,r,p,h.data):n.texImage2D(e.TEXTURE_2D,t,m,h.width,h.height,0,r,p,h.data);o.generateMipmaps=!1}else C?(w&&n.texStorage2D(e.TEXTURE_2D,E,m,t.width,t.height),T&&ue(o,t,r,p)):n.texImage2D(e.TEXTURE_2D,0,m,t.width,t.height,0,r,p,t.data)}else if(o.isCompressedTexture){if(o.isCompressedArrayTexture){C&&w&&n.texStorage3D(e.TEXTURE_2D_ARRAY,E,m,y[0].width,y[0].height,t.depth);for(let i=0,a=y.length;i<a;i++)if(h=y[i],o.format!==1023){if(r!==null){if(C){if(T){if(o.layerUpdates.size>0){let t=aD(h.width,h.height,o.format,o.type);for(let a of o.layerUpdates){let o=h.data.subarray(a*t/h.data.BYTES_PER_ELEMENT,(a+1)*t/h.data.BYTES_PER_ELEMENT);n.compressedTexSubImage3D(e.TEXTURE_2D_ARRAY,i,0,0,a,h.width,h.height,1,r,o)}}else n.compressedTexSubImage3D(e.TEXTURE_2D_ARRAY,i,0,0,0,h.width,h.height,t.depth,r,h.data)}}else n.compressedTexImage3D(e.TEXTURE_2D_ARRAY,i,m,h.width,h.height,t.depth,0,h.data,0,0)}else q(`WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()`)}else C?T&&n.texSubImage3D(e.TEXTURE_2D_ARRAY,i,0,0,0,h.width,h.height,t.depth,r,p,h.data):n.texImage3D(e.TEXTURE_2D_ARRAY,i,m,h.width,h.height,t.depth,0,r,p,h.data);o.layerUpdates.size>0&&o.clearLayerUpdates()}else{C&&w&&n.texStorage2D(e.TEXTURE_2D,E,m,y[0].width,y[0].height);for(let t=0,i=y.length;t<i;t++)h=y[t],o.format===1023?C?T&&n.texSubImage2D(e.TEXTURE_2D,t,0,0,h.width,h.height,r,p,h.data):n.texImage2D(e.TEXTURE_2D,t,m,h.width,h.height,0,r,p,h.data):r===null?q(`WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()`):C?T&&n.compressedTexSubImage2D(e.TEXTURE_2D,t,0,0,h.width,h.height,r,h.data):n.compressedTexImage2D(e.TEXTURE_2D,t,m,h.width,h.height,0,h.data)}}else if(o.isDataArrayTexture){if(C){if(w&&n.texStorage3D(e.TEXTURE_2D_ARRAY,E,m,t.width,t.height,t.depth),T){if(o.layerUpdates.size>0){let i=aD(t.width,t.height,o.format,o.type);for(let a of o.layerUpdates){let o=t.data.subarray(a*i/t.data.BYTES_PER_ELEMENT,(a+1)*i/t.data.BYTES_PER_ELEMENT);n.texSubImage3D(e.TEXTURE_2D_ARRAY,0,0,0,a,t.width,t.height,1,r,p,o)}o.clearLayerUpdates()}else n.texSubImage3D(e.TEXTURE_2D_ARRAY,0,0,0,0,t.width,t.height,t.depth,r,p,t.data)}}else n.texImage3D(e.TEXTURE_2D_ARRAY,0,m,t.width,t.height,t.depth,0,r,p,t.data)}else if(o.isData3DTexture)C?(w&&n.texStorage3D(e.TEXTURE_3D,E,m,t.width,t.height,t.depth),T&&n.texSubImage3D(e.TEXTURE_3D,0,0,0,0,t.width,t.height,t.depth,r,p,t.data)):n.texImage3D(e.TEXTURE_3D,0,m,t.width,t.height,t.depth,0,r,p,t.data);else if(o.isFramebufferTexture){if(w){if(C)n.texStorage2D(e.TEXTURE_2D,E,m,t.width,t.height);else{let i=t.width,a=t.height;for(let t=0;t<E;t++)n.texImage2D(e.TEXTURE_2D,t,m,i,a,0,r,p,null),i>>=1,a>>=1}}}else if(o.isHTMLTexture){if(`texElementImage2D`in e){let n=e.canvas;if(n.hasAttribute(`layoutsubtree`)||n.setAttribute(`layoutsubtree`,`true`),t.parentNode!==n){n.appendChild(t),d.add(o),n.onpaint=e=>{let t=e.changedElements;for(let e of d)t.includes(e.image)&&(e.needsUpdate=!0)},n.requestPaint();return}if(e.texElementImage2D.length===3)e.texElementImage2D(e.TEXTURE_2D,e.RGBA8,t);else{let n=e.RGBA,r=e.RGBA,i=e.UNSIGNED_BYTE;e.texElementImage2D(e.TEXTURE_2D,0,n,r,i,t)}e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE)}}else if(y.length>0){if(C&&w){let t=Ee(y[0]);n.texStorage2D(e.TEXTURE_2D,E,m,t.width,t.height)}for(let t=0,i=y.length;t<i;t++)h=y[t],C?T&&n.texSubImage2D(e.TEXTURE_2D,t,0,0,r,p,h):n.texImage2D(e.TEXTURE_2D,t,m,r,p,h);o.generateMipmaps=!1}else if(C){if(w){let r=Ee(t);n.texStorage2D(e.TEXTURE_2D,E,m,r.width,r.height)}T&&n.texSubImage2D(e.TEXTURE_2D,0,0,0,r,p,t)}else n.texImage2D(e.TEXTURE_2D,0,m,r,p,t);_(o)&&v(c),f.__version=u.version,o.onUpdate&&o.onUpdate(o)}t.__version=o.version}function fe(t,o,s){if(o.image.length!==6)return;let c=ce(t,o),l=o.source;n.bindTexture(e.TEXTURE_CUBE_MAP,t.__webglTexture,e.TEXTURE0+s);let u=r.get(l);if(l.version!==u.__version||c===!0){n.activeTexture(e.TEXTURE0+s);let t=wC.getPrimaries(wC.workingColorSpace),r=o.colorSpace===``?null:wC.getPrimaries(o.colorSpace),d=o.colorSpace===``||t===r?e.NONE:e.BROWSER_DEFAULT_WEBGL;n.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,o.flipY),n.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,o.premultiplyAlpha),n.pixelStorei(e.UNPACK_ALIGNMENT,o.unpackAlignment),n.pixelStorei(e.UNPACK_COLORSPACE_CONVERSION_WEBGL,d);let f=o.isCompressedTexture||o.image[0].isCompressedTexture,p=o.image[0]&&o.image[0].isDataTexture,m=[];for(let e=0;e<6;e++)!f&&!p?m[e]=g(o.image[e],!0,i.maxCubemapSize):m[e]=p?o.image[e].image:o.image[e],m[e]=Te(o,m[e]);let h=m[0],y=a.convert(o.format,o.colorSpace),x=a.convert(o.type),C=b(o.internalFormat,y,x,o.normalized,o.colorSpace),w=o.isVideoTexture!==!0,T=u.__version===void 0||c===!0,E=l.dataReady,D=S(o,h);se(e.TEXTURE_CUBE_MAP,o);let O;if(f){w&&T&&n.texStorage2D(e.TEXTURE_CUBE_MAP,D,C,h.width,h.height);for(let t=0;t<6;t++){O=m[t].mipmaps;for(let r=0;r<O.length;r++){let i=O[r];o.format===1023?w?E&&n.texSubImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,r,0,0,i.width,i.height,y,x,i.data):n.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,r,C,i.width,i.height,0,y,x,i.data):y===null?q(`WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()`):w?E&&n.compressedTexSubImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,r,0,0,i.width,i.height,y,i.data):n.compressedTexImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,r,C,i.width,i.height,0,i.data)}}}else{if(O=o.mipmaps,w&&T){O.length>0&&D++;let t=Ee(m[0]);n.texStorage2D(e.TEXTURE_CUBE_MAP,D,C,t.width,t.height)}for(let t=0;t<6;t++)if(p){w?E&&n.texSubImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,0,0,0,m[t].width,m[t].height,y,x,m[t].data):n.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,0,C,m[t].width,m[t].height,0,y,x,m[t].data);for(let r=0;r<O.length;r++){let i=O[r].image[t].image;w?E&&n.texSubImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,r+1,0,0,i.width,i.height,y,x,i.data):n.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,r+1,C,i.width,i.height,0,y,x,i.data)}}else{w?E&&n.texSubImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,0,0,0,y,x,m[t]):n.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,0,C,y,x,m[t]);for(let r=0;r<O.length;r++){let i=O[r];w?E&&n.texSubImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,r+1,0,0,y,x,i.image[t]):n.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,r+1,C,y,x,i.image[t])}}}_(o)&&v(e.TEXTURE_CUBE_MAP),u.__version=l.version,o.onUpdate&&o.onUpdate(o)}t.__version=o.version}function pe(t,i,o,c,l,u){let d=a.convert(o.format,o.colorSpace),f=a.convert(o.type),p=b(o.internalFormat,d,f,o.normalized,o.colorSpace),m=r.get(i),h=r.get(o);if(h.__renderTarget=i,!m.__hasExternalTextures){let t=Math.max(1,i.width>>u),r=Math.max(1,i.height>>u);l===e.TEXTURE_3D||l===e.TEXTURE_2D_ARRAY?n.texImage3D(l,u,p,t,r,i.depth,0,d,f,null):n.texImage2D(l,u,p,t,r,0,d,f,null)}n.bindFramebuffer(e.FRAMEBUFFER,t),P(i)?s.framebufferTexture2DMultisampleEXT(e.FRAMEBUFFER,c,l,h.__webglTexture,0,Ce(i)):(l===e.TEXTURE_2D||l>=e.TEXTURE_CUBE_MAP_POSITIVE_X&&l<=e.TEXTURE_CUBE_MAP_NEGATIVE_Z)&&e.framebufferTexture2D(e.FRAMEBUFFER,c,l,h.__webglTexture,u),n.bindFramebuffer(e.FRAMEBUFFER,null)}function me(t,n,r){if(e.bindRenderbuffer(e.RENDERBUFFER,t),n.depthBuffer){let i=n.depthTexture,a=i&&i.isDepthTexture?i.type:null,o=x(n.stencilBuffer,a),c=n.stencilBuffer?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT;P(n)?s.renderbufferStorageMultisampleEXT(e.RENDERBUFFER,Ce(n),o,n.width,n.height):r?e.renderbufferStorageMultisample(e.RENDERBUFFER,Ce(n),o,n.width,n.height):e.renderbufferStorage(e.RENDERBUFFER,o,n.width,n.height),e.framebufferRenderbuffer(e.FRAMEBUFFER,c,e.RENDERBUFFER,t)}else{let t=n.textures;for(let i=0;i<t.length;i++){let o=t[i],c=a.convert(o.format,o.colorSpace),l=a.convert(o.type),u=b(o.internalFormat,c,l,o.normalized,o.colorSpace);P(n)?s.renderbufferStorageMultisampleEXT(e.RENDERBUFFER,Ce(n),u,n.width,n.height):r?e.renderbufferStorageMultisample(e.RENDERBUFFER,Ce(n),u,n.width,n.height):e.renderbufferStorage(e.RENDERBUFFER,u,n.width,n.height)}}e.bindRenderbuffer(e.RENDERBUFFER,null)}function he(t,i,o){let c=i.isWebGLCubeRenderTarget===!0;if(n.bindFramebuffer(e.FRAMEBUFFER,t),!(i.depthTexture&&i.depthTexture.isDepthTexture))throw Error(`THREE.WebGLTextures: renderTarget.depthTexture must be an instance of THREE.DepthTexture.`);let l=r.get(i.depthTexture);if(l.__renderTarget=i,(!l.__webglTexture||i.depthTexture.image.width!==i.width||i.depthTexture.image.height!==i.height)&&(i.depthTexture.image.width=i.width,i.depthTexture.image.height=i.height,i.depthTexture.needsUpdate=!0),c){if(l.__webglInit===void 0&&(l.__webglInit=!0,i.depthTexture.addEventListener(`dispose`,C)),l.__webglTexture===void 0){l.__webglTexture=e.createTexture(),n.bindTexture(e.TEXTURE_CUBE_MAP,l.__webglTexture),se(e.TEXTURE_CUBE_MAP,i.depthTexture);let t=a.convert(i.depthTexture.format),r=a.convert(i.depthTexture.type),o;i.depthTexture.format===1026?o=e.DEPTH_COMPONENT24:i.depthTexture.format===1027&&(o=e.DEPTH24_STENCIL8);for(let n=0;n<6;n++)e.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+n,0,o,i.width,i.height,0,t,r,null)}}else ne(i.depthTexture,0);let u=l.__webglTexture,d=Ce(i),f=c?e.TEXTURE_CUBE_MAP_POSITIVE_X+o:e.TEXTURE_2D,p=i.depthTexture.format===1027?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT;if(i.depthTexture.format===1026)P(i)?s.framebufferTexture2DMultisampleEXT(e.FRAMEBUFFER,p,f,u,0,d):e.framebufferTexture2D(e.FRAMEBUFFER,p,f,u,0);else if(i.depthTexture.format===1027)P(i)?s.framebufferTexture2DMultisampleEXT(e.FRAMEBUFFER,p,f,u,0,d):e.framebufferTexture2D(e.FRAMEBUFFER,p,f,u,0);else throw Error(`THREE.WebGLTextures: Unknown depthTexture format.`)}function ge(t){let i=r.get(t),a=t.isWebGLCubeRenderTarget===!0;if(i.__boundDepthTexture!==t.depthTexture){let e=t.depthTexture;if(i.__depthDisposeCallback&&i.__depthDisposeCallback(),e){let t=()=>{delete i.__boundDepthTexture,delete i.__depthDisposeCallback,e.removeEventListener(`dispose`,t)};e.addEventListener(`dispose`,t),i.__depthDisposeCallback=t}i.__boundDepthTexture=e}if(t.depthTexture&&!i.__autoAllocateDepthBuffer){if(a)for(let e=0;e<6;e++)he(i.__webglFramebuffer[e],t,e);else{let e=t.texture.mipmaps;e&&e.length>0?he(i.__webglFramebuffer[0],t,0):he(i.__webglFramebuffer,t,0)}}else if(a){i.__webglDepthbuffer=[];for(let r=0;r<6;r++)if(n.bindFramebuffer(e.FRAMEBUFFER,i.__webglFramebuffer[r]),i.__webglDepthbuffer[r]===void 0)i.__webglDepthbuffer[r]=e.createRenderbuffer(),me(i.__webglDepthbuffer[r],t,!1);else{let n=t.stencilBuffer?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT,a=i.__webglDepthbuffer[r];e.bindRenderbuffer(e.RENDERBUFFER,a),e.framebufferRenderbuffer(e.FRAMEBUFFER,n,e.RENDERBUFFER,a)}}else{let r=t.texture.mipmaps;if(r&&r.length>0?n.bindFramebuffer(e.FRAMEBUFFER,i.__webglFramebuffer[0]):n.bindFramebuffer(e.FRAMEBUFFER,i.__webglFramebuffer),i.__webglDepthbuffer===void 0)i.__webglDepthbuffer=e.createRenderbuffer(),me(i.__webglDepthbuffer,t,!1);else{let n=t.stencilBuffer?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT,r=i.__webglDepthbuffer;e.bindRenderbuffer(e.RENDERBUFFER,r),e.framebufferRenderbuffer(e.FRAMEBUFFER,n,e.RENDERBUFFER,r)}}n.bindFramebuffer(e.FRAMEBUFFER,null)}function _e(t,n,i){let a=r.get(t);n!==void 0&&pe(a.__webglFramebuffer,t,t.texture,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,0),i!==void 0&&ge(t)}function ve(t){let i=t.texture,s=r.get(t),c=r.get(i);t.addEventListener(`dispose`,w);let l=t.textures,u=t.isWebGLCubeRenderTarget===!0,d=l.length>1;if(d||(c.__webglTexture===void 0&&(c.__webglTexture=e.createTexture()),c.__version=i.version,o.memory.textures++),u){s.__webglFramebuffer=[];for(let t=0;t<6;t++)if(i.mipmaps&&i.mipmaps.length>0){s.__webglFramebuffer[t]=[];for(let n=0;n<i.mipmaps.length;n++)s.__webglFramebuffer[t][n]=e.createFramebuffer()}else s.__webglFramebuffer[t]=e.createFramebuffer()}else{if(i.mipmaps&&i.mipmaps.length>0){s.__webglFramebuffer=[];for(let t=0;t<i.mipmaps.length;t++)s.__webglFramebuffer[t]=e.createFramebuffer()}else s.__webglFramebuffer=e.createFramebuffer();if(d)for(let t=0,n=l.length;t<n;t++){let n=r.get(l[t]);n.__webglTexture===void 0&&(n.__webglTexture=e.createTexture(),o.memory.textures++)}if(t.samples>0&&P(t)===!1){s.__webglMultisampledFramebuffer=e.createFramebuffer(),s.__webglColorRenderbuffer=[],n.bindFramebuffer(e.FRAMEBUFFER,s.__webglMultisampledFramebuffer);for(let n=0;n<l.length;n++){let r=l[n];s.__webglColorRenderbuffer[n]=e.createRenderbuffer(),e.bindRenderbuffer(e.RENDERBUFFER,s.__webglColorRenderbuffer[n]);let i=a.convert(r.format,r.colorSpace),o=a.convert(r.type),c=b(r.internalFormat,i,o,r.normalized,r.colorSpace,t.isXRRenderTarget===!0),u=Ce(t);e.renderbufferStorageMultisample(e.RENDERBUFFER,u,c,t.width,t.height),e.framebufferRenderbuffer(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0+n,e.RENDERBUFFER,s.__webglColorRenderbuffer[n])}e.bindRenderbuffer(e.RENDERBUFFER,null),t.depthBuffer&&(s.__webglDepthRenderbuffer=e.createRenderbuffer(),me(s.__webglDepthRenderbuffer,t,!0)),n.bindFramebuffer(e.FRAMEBUFFER,null)}}if(u){n.bindTexture(e.TEXTURE_CUBE_MAP,c.__webglTexture),se(e.TEXTURE_CUBE_MAP,i);for(let n=0;n<6;n++)if(i.mipmaps&&i.mipmaps.length>0)for(let r=0;r<i.mipmaps.length;r++)pe(s.__webglFramebuffer[n][r],t,i,e.COLOR_ATTACHMENT0,e.TEXTURE_CUBE_MAP_POSITIVE_X+n,r);else pe(s.__webglFramebuffer[n],t,i,e.COLOR_ATTACHMENT0,e.TEXTURE_CUBE_MAP_POSITIVE_X+n,0);_(i)&&v(e.TEXTURE_CUBE_MAP),n.unbindTexture()}else if(d){for(let i=0,a=l.length;i<a;i++){let a=l[i],o=r.get(a),c=e.TEXTURE_2D;(t.isWebGL3DRenderTarget||t.isWebGLArrayRenderTarget)&&(c=t.isWebGL3DRenderTarget?e.TEXTURE_3D:e.TEXTURE_2D_ARRAY),n.bindTexture(c,o.__webglTexture),se(c,a),pe(s.__webglFramebuffer,t,a,e.COLOR_ATTACHMENT0+i,c,0),_(a)&&v(c)}n.unbindTexture()}else{let r=e.TEXTURE_2D;if((t.isWebGL3DRenderTarget||t.isWebGLArrayRenderTarget)&&(r=t.isWebGL3DRenderTarget?e.TEXTURE_3D:e.TEXTURE_2D_ARRAY),n.bindTexture(r,c.__webglTexture),se(r,i),i.mipmaps&&i.mipmaps.length>0)for(let n=0;n<i.mipmaps.length;n++)pe(s.__webglFramebuffer[n],t,i,e.COLOR_ATTACHMENT0,r,n);else pe(s.__webglFramebuffer,t,i,e.COLOR_ATTACHMENT0,r,0);_(i)&&v(r),n.unbindTexture()}t.depthBuffer&&ge(t)}function ye(e){let t=e.textures;for(let i=0,a=t.length;i<a;i++){let a=t[i];if(_(a)){let t=y(e),i=r.get(a).__webglTexture;n.bindTexture(t,i),v(t),n.unbindTexture()}}}let be=[],xe=[];function Se(t){if(t.samples>0){if(P(t)===!1){let i=t.textures,a=t.width,o=t.height,s=e.COLOR_BUFFER_BIT,l=t.stencilBuffer?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT,u=r.get(t),d=i.length>1;if(d)for(let t=0;t<i.length;t++)n.bindFramebuffer(e.FRAMEBUFFER,u.__webglMultisampledFramebuffer),e.framebufferRenderbuffer(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0+t,e.RENDERBUFFER,null),n.bindFramebuffer(e.FRAMEBUFFER,u.__webglFramebuffer),e.framebufferTexture2D(e.DRAW_FRAMEBUFFER,e.COLOR_ATTACHMENT0+t,e.TEXTURE_2D,null,0);n.bindFramebuffer(e.READ_FRAMEBUFFER,u.__webglMultisampledFramebuffer);let f=t.texture.mipmaps;f&&f.length>0?n.bindFramebuffer(e.DRAW_FRAMEBUFFER,u.__webglFramebuffer[0]):n.bindFramebuffer(e.DRAW_FRAMEBUFFER,u.__webglFramebuffer);for(let n=0;n<i.length;n++){if(t.resolveDepthBuffer&&(t.depthBuffer&&(s|=e.DEPTH_BUFFER_BIT),t.stencilBuffer&&t.resolveStencilBuffer&&(s|=e.STENCIL_BUFFER_BIT)),d){e.framebufferRenderbuffer(e.READ_FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.RENDERBUFFER,u.__webglColorRenderbuffer[n]);let t=r.get(i[n]).__webglTexture;e.framebufferTexture2D(e.DRAW_FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0)}e.blitFramebuffer(0,0,a,o,0,0,a,o,s,e.NEAREST),c===!0&&(be.length=0,xe.length=0,be.push(e.COLOR_ATTACHMENT0+n),t.depthBuffer&&t.storeMultisampledDepthBuffer===!1&&(be.push(l),xe.push(l),e.invalidateFramebuffer(e.DRAW_FRAMEBUFFER,xe)),e.invalidateFramebuffer(e.READ_FRAMEBUFFER,be))}if(n.bindFramebuffer(e.READ_FRAMEBUFFER,null),n.bindFramebuffer(e.DRAW_FRAMEBUFFER,null),d)for(let t=0;t<i.length;t++){n.bindFramebuffer(e.FRAMEBUFFER,u.__webglMultisampledFramebuffer),e.framebufferRenderbuffer(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0+t,e.RENDERBUFFER,u.__webglColorRenderbuffer[t]);let a=r.get(i[t]).__webglTexture;n.bindFramebuffer(e.FRAMEBUFFER,u.__webglFramebuffer),e.framebufferTexture2D(e.DRAW_FRAMEBUFFER,e.COLOR_ATTACHMENT0+t,e.TEXTURE_2D,a,0)}n.bindFramebuffer(e.DRAW_FRAMEBUFFER,u.__webglMultisampledFramebuffer)}else if(t.depthBuffer&&t.storeMultisampledDepthBuffer===!1&&c){let n=t.stencilBuffer?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT;e.invalidateFramebuffer(e.DRAW_FRAMEBUFFER,[n])}}}function Ce(e){return Math.min(i.maxSamples,e.samples)}function P(e){let n=r.get(e);return e.samples>0&&t.has(`WEBGL_multisampled_render_to_texture`)===!0&&n.__useRenderToTexture!==!1}function we(e){let t=o.render.frame;u.get(e)!==t&&(u.set(e,t),e.update())}function Te(e,t){let n=e.colorSpace,r=e.format,i=e.type;return e.isCompressedTexture===!0||e.isVideoTexture===!0||n!==`srgb-linear`&&n!==``&&(wC.getTransfer(n)===`srgb`?(r!==1023||i!==1009)&&q(`WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType.`):J(`WebGLTextures: Unsupported texture color space:`,n)),t}function Ee(e){return typeof HTMLImageElement<`u`&&e instanceof HTMLImageElement?(l.width=e.naturalWidth||e.width,l.height=e.naturalHeight||e.height):typeof VideoFrame<`u`&&e instanceof VideoFrame?(l.width=e.displayWidth,l.height=e.displayHeight):(l.width=e.width,l.height=e.height),l}this.allocateTextureUnit=te,this.resetTextureUnits=k,this.getTextureUnits=A,this.setTextureUnits=ee,this.setTexture2D=ne,this.setTexture2DArray=re,this.setTexture3D=M,this.setTextureCube=ie,this.rebindTextures=_e,this.setupRenderTarget=ve,this.updateRenderTargetMipmap=ye,this.updateMultisampleRenderTarget=Se,this.setupDepthRenderbuffer=ge,this.setupFrameBufferTexture=pe,this.useMultisampledRTT=P,this.isReversedDepthBuffer=function(){return n.buffers.depth.getReversed()}}function dA(e,t){function n(n,r=``){let i,a=wC.getTransfer(r);if(n===1009)return e.UNSIGNED_BYTE;if(n===1017)return e.UNSIGNED_SHORT_4_4_4_4;if(n===1018)return e.UNSIGNED_SHORT_5_5_5_1;if(n===35902)return e.UNSIGNED_INT_5_9_9_9_REV;if(n===35899)return e.UNSIGNED_INT_10F_11F_11F_REV;if(n===1010)return e.BYTE;if(n===1011)return e.SHORT;if(n===1012)return e.UNSIGNED_SHORT;if(n===1013)return e.INT;if(n===1014)return e.UNSIGNED_INT;if(n===1015)return e.FLOAT;if(n===1016)return e.HALF_FLOAT;if(n===1021)return e.ALPHA;if(n===1022)return e.RGB;if(n===1023)return e.RGBA;if(n===1026)return e.DEPTH_COMPONENT;if(n===1027)return e.DEPTH_STENCIL;if(n===1028)return e.RED;if(n===1029)return e.RED_INTEGER;if(n===1030)return e.RG;if(n===1031)return e.RG_INTEGER;if(n===1033)return e.RGBA_INTEGER;if(n===33776||n===33777||n===33778||n===33779){if(a===`srgb`){if(i=t.get(`WEBGL_compressed_texture_s3tc_srgb`),i!==null){if(n===33776)return i.COMPRESSED_SRGB_S3TC_DXT1_EXT;if(n===33777)return i.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;if(n===33778)return i.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;if(n===33779)return i.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}else return null}else if(i=t.get(`WEBGL_compressed_texture_s3tc`),i!==null){if(n===33776)return i.COMPRESSED_RGB_S3TC_DXT1_EXT;if(n===33777)return i.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(n===33778)return i.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(n===33779)return i.COMPRESSED_RGBA_S3TC_DXT5_EXT}else return null}if(n===35840||n===35841||n===35842||n===35843){if(i=t.get(`WEBGL_compressed_texture_pvrtc`),i!==null){if(n===35840)return i.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(n===35841)return i.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(n===35842)return i.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(n===35843)return i.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}else return null}if(n===36196||n===37492||n===37496||n===37488||n===37489||n===37490||n===37491){if(i=t.get(`WEBGL_compressed_texture_etc`),i!==null){if(n===36196||n===37492)return a===`srgb`?i.COMPRESSED_SRGB8_ETC2:i.COMPRESSED_RGB8_ETC2;if(n===37496)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:i.COMPRESSED_RGBA8_ETC2_EAC;if(n===37488)return i.COMPRESSED_R11_EAC;if(n===37489)return i.COMPRESSED_SIGNED_R11_EAC;if(n===37490)return i.COMPRESSED_RG11_EAC;if(n===37491)return i.COMPRESSED_SIGNED_RG11_EAC}else return null}if(n===37808||n===37809||n===37810||n===37811||n===37812||n===37813||n===37814||n===37815||n===37816||n===37817||n===37818||n===37819||n===37820||n===37821){if(i=t.get(`WEBGL_compressed_texture_astc`),i!==null){if(n===37808)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:i.COMPRESSED_RGBA_ASTC_4x4_KHR;if(n===37809)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:i.COMPRESSED_RGBA_ASTC_5x4_KHR;if(n===37810)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:i.COMPRESSED_RGBA_ASTC_5x5_KHR;if(n===37811)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:i.COMPRESSED_RGBA_ASTC_6x5_KHR;if(n===37812)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:i.COMPRESSED_RGBA_ASTC_6x6_KHR;if(n===37813)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:i.COMPRESSED_RGBA_ASTC_8x5_KHR;if(n===37814)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:i.COMPRESSED_RGBA_ASTC_8x6_KHR;if(n===37815)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:i.COMPRESSED_RGBA_ASTC_8x8_KHR;if(n===37816)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:i.COMPRESSED_RGBA_ASTC_10x5_KHR;if(n===37817)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:i.COMPRESSED_RGBA_ASTC_10x6_KHR;if(n===37818)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:i.COMPRESSED_RGBA_ASTC_10x8_KHR;if(n===37819)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:i.COMPRESSED_RGBA_ASTC_10x10_KHR;if(n===37820)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:i.COMPRESSED_RGBA_ASTC_12x10_KHR;if(n===37821)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:i.COMPRESSED_RGBA_ASTC_12x12_KHR}else return null}if(n===36492||n===36494||n===36495){if(i=t.get(`EXT_texture_compression_bptc`),i!==null){if(n===36492)return a===`srgb`?i.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT:i.COMPRESSED_RGBA_BPTC_UNORM_EXT;if(n===36494)return i.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT;if(n===36495)return i.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT}else return null}if(n===36283||n===36284||n===36285||n===36286){if(i=t.get(`EXT_texture_compression_rgtc`),i!==null){if(n===36283)return i.COMPRESSED_RED_RGTC1_EXT;if(n===36284)return i.COMPRESSED_SIGNED_RED_RGTC1_EXT;if(n===36285)return i.COMPRESSED_RED_GREEN_RGTC2_EXT;if(n===36286)return i.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT}else return null}return n===1020?e.UNSIGNED_INT_24_8:e[n]===void 0?null:e[n]}return{convert:n}}var fA=`
|
|
4198
|
+
}`,Pj=[/*@__PURE__*/ new X(1,0,0),/*@__PURE__*/ new X(-1,0,0),/*@__PURE__*/ new X(0,1,0),/*@__PURE__*/ new X(0,-1,0),/*@__PURE__*/ new X(0,0,1),/*@__PURE__*/ new X(0,0,-1)],Fj=[/*@__PURE__*/ new X(0,-1,0),/*@__PURE__*/ new X(0,-1,0),/*@__PURE__*/ new X(0,0,1),/*@__PURE__*/ new X(0,0,-1),/*@__PURE__*/ new X(0,-1,0),/*@__PURE__*/ new X(0,-1,0)],Ij=/*@__PURE__*/ new _T,Lj=/*@__PURE__*/ new X,Rj=/*@__PURE__*/ new X;function zj(e,t,n){let r=new TD,i=new Y,a=new Y,o=new fT,s=new WD,c=new GD,l={},u=n.maxTextureSize,d={0:1,1:0,2:2},f=new HD({defines:{VSM_SAMPLES:8},uniforms:{shadow_pass:{value:null},resolution:{value:new Y},radius:{value:4}},vertexShader:Mj,fragmentShader:Nj}),p=f.clone();p.defines.HORIZONTAL_PASS=1;let m=new JE;m.setAttribute(`position`,new NE(new Float32Array([-1,-1,.5,3,-1,.5,-1,3,.5]),3));let h=new vD(m,f),g=this;this.enabled=!1,this.autoUpdate=!0,this.needsUpdate=!1,this.type=1;let _=this.type;this.render=function(t,n,s){if(g.enabled===!1||g.autoUpdate===!1&&g.needsUpdate===!1||t.length===0)return;this.type===2&&(q(`WebGLShadowMap: PCFSoftShadowMap has been removed. Using PCFShadowMap instead.`),this.type=1);let c=e.getRenderTarget(),l=e.getActiveCubeFace(),d=e.getActiveMipmapLevel(),f=e.state;f.setBlending(0),f.buffers.depth.getReversed()===!0?f.buffers.color.setClear(0,0,0,0):f.buffers.color.setClear(1,1,1,1),f.buffers.depth.setTest(!0),f.setScissorTest(!1);let p=_!==this.type;p&&n.traverse(function(e){e.material&&(Array.isArray(e.material)?e.material.forEach(e=>e.needsUpdate=!0):e.material.needsUpdate=!0)});for(let c=0,l=t.length;c<l;c++){let l=t[c],d=l.shadow;if(d===void 0){q(`WebGLShadowMap:`,l,`has no shadow.`);continue}if(d.autoUpdate===!1&&d.needsUpdate===!1)continue;i.copy(d.mapSize);let m=d.getFrameExtents();i.multiply(m),a.copy(d.mapSize),(i.x>u||i.y>u)&&(i.x>u&&(a.x=Math.floor(u/m.x),i.x=a.x*m.x,d.mapSize.x=a.x),i.y>u&&(a.y=Math.floor(u/m.y),i.y=a.y*m.y,d.mapSize.y=a.y));let h=e.state.buffers.depth.getReversed();if(d.camera._reversedDepth=h,d.map===null||p===!0){if(d.map!==null&&(d.map.depthTexture!==null&&(d.map.depthTexture.dispose(),d.map.depthTexture=null),d.map.dispose()),this.type===3){if(l.isPointLight){q(`WebGLShadowMap: VSM shadow maps are not supported for PointLights. Use PCF or BasicShadowMap instead.`);continue}d.map=new mT(i.x,i.y,{format:DC,type:mC,minFilter:iC,magFilter:iC,generateMipmaps:!1}),d.map.texture.name=l.name+`.shadowMap`,d.map.depthTexture=new kD(i.x,i.y,pC),d.map.depthTexture.name=l.name+`.shadowMapDepth`,d.map.depthTexture.format=CC,d.map.depthTexture.compareFunction=null,d.map.depthTexture.minFilter=tC,d.map.depthTexture.magFilter=tC}else l.isPointLight?(d.map=new gk(i.x),d.map.depthTexture=new AD(i.x,fC)):(d.map=new mT(i.x,i.y),d.map.depthTexture=new kD(i.x,i.y,fC)),d.map.depthTexture.name=l.name+`.shadowMap`,d.map.depthTexture.format=CC,this.type===1?(d.map.depthTexture.compareFunction=h?518:515,d.map.depthTexture.minFilter=iC,d.map.depthTexture.magFilter=iC):(d.map.depthTexture.compareFunction=null,d.map.depthTexture.minFilter=tC,d.map.depthTexture.magFilter=tC);d.camera.updateProjectionMatrix()}d.map.isWebGLCubeRenderTarget!==!0&&(d.map.width!==i.x||d.map.height!==i.y)&&d.map.setSize(i.x,i.y);let g=d.map.isWebGLCubeRenderTarget?6:d.getViewportCount();l.isPointLight!==!0&&d.updateMatrices(l,s);for(let t=0;t<g;t++){let i=d.getCamera(t);if(l.isPointLight){let e=d.camera,n=d.matrix,r=l.distance||e.far;r!==e.far&&(e.far=r,e.updateProjectionMatrix()),Lj.setFromMatrixPosition(l.matrixWorld),e.position.copy(Lj),Rj.copy(e.position),Rj.add(Pj[t]),e.up.copy(Fj[t]),e.lookAt(Rj),e.updateMatrixWorld(),n.makeTranslation(-Lj.x,-Lj.y,-Lj.z),Ij.multiplyMatrices(e.projectionMatrix,e.matrixWorldInverse),d._frustum.setFromProjectionMatrix(Ij,e.coordinateSystem,e.reversedDepth)}if(d.map.isWebGLCubeRenderTarget)e.setRenderTarget(d.map,t),e.clear();else{t===0&&(e.setRenderTarget(d.map),e.clear());let n=d.getViewport(t);o.set(a.x*n.x,a.y*n.y,a.x*n.z,a.y*n.w),f.viewport(o)}r=d.getFrustum(t),b(n,s,i,l,this.type)}d.isPointLightShadow!==!0&&this.type===3&&v(d,s),d.needsUpdate=!1}_=this.type,g.needsUpdate=!1,e.setRenderTarget(c,l,d)};function v(n,r){let a=t.update(h);f.defines.VSM_SAMPLES!==n.blurSamples&&(f.defines.VSM_SAMPLES=n.blurSamples,p.defines.VSM_SAMPLES=n.blurSamples,f.needsUpdate=!0,p.needsUpdate=!0),n.mapPass===null?n.mapPass=new mT(i.x,i.y,{format:DC,type:mC}):(n.mapPass.width!==n.map.width||n.mapPass.height!==n.map.height)&&n.mapPass.setSize(n.map.width,n.map.height),f.uniforms.shadow_pass.value=n.map.depthTexture,f.uniforms.resolution.value.set(n.map.width,n.map.height),f.uniforms.radius.value=n.radius,e.setRenderTarget(n.mapPass),e.clear(),e.renderBufferDirect(r,null,a,f,h,null),p.uniforms.shadow_pass.value=n.mapPass.texture,p.uniforms.resolution.value.set(n.map.width,n.map.height),p.uniforms.radius.value=n.radius,e.setRenderTarget(n.map),e.clear(),e.renderBufferDirect(r,null,a,p,h,null)}function y(t,n,r,i){let a=null,o=r.isPointLight===!0?t.customDistanceMaterial:t.customDepthMaterial;if(o!==void 0)a=o;else if(a=r.isPointLight===!0?c:s,e.localClippingEnabled&&n.clipShadows===!0&&Array.isArray(n.clippingPlanes)&&n.clippingPlanes.length!==0||n.displacementMap&&n.displacementScale!==0||n.alphaMap&&n.alphaTest>0||n.map&&n.alphaTest>0||n.alphaToCoverage===!0){let e=a.uuid,t=n.uuid,r=l[e];r===void 0&&(r={},l[e]=r);let i=r[t];i===void 0&&(i=a.clone(),r[t]=i,n.addEventListener(`dispose`,x)),a=i}if(a.visible=n.visible,a.wireframe=n.wireframe,i===3?a.side=n.shadowSide===null?n.side:n.shadowSide:a.side=n.shadowSide===null?d[n.side]:n.shadowSide,a.alphaMap=n.alphaMap,a.alphaTest=n.alphaToCoverage===!0?.5:n.alphaTest,a.map=n.map,a.clipShadows=n.clipShadows,a.clippingPlanes=n.clippingPlanes,a.clipIntersection=n.clipIntersection,a.displacementMap=n.displacementMap,a.displacementScale=n.displacementScale,a.displacementBias=n.displacementBias,a.wireframeLinewidth=n.wireframeLinewidth,a.linewidth=n.linewidth,r.isPointLight===!0&&a.isMeshDistanceMaterial===!0){let t=e.properties.get(a);t.light=r}return a}function b(n,i,a,o,s){if(n.visible===!1)return;if(n.layers.test(i.layers)&&(n.isMesh||n.isLine||n.isPoints)&&(n.castShadow||n.receiveShadow&&s===3)&&(!n.frustumCulled||n.intersectsFrustum(r))){n.modelViewMatrix.multiplyMatrices(a.matrixWorldInverse,n.matrixWorld);let r=t.update(n),c=n.material;if(Array.isArray(c)){let t=r.groups;for(let l=0,u=t.length;l<u;l++){let u=t[l],d=c[u.materialIndex];if(d&&d.visible){let t=y(n,d,o,s);n.onBeforeShadow(e,n,i,a,r,t,u),e.renderBufferDirect(a,null,r,t,n,u),n.onAfterShadow(e,n,i,a,r,t,u)}}}else if(c.visible){let t=y(n,c,o,s);n.onBeforeShadow(e,n,i,a,r,t,null),e.renderBufferDirect(a,null,r,t,n,null),n.onAfterShadow(e,n,i,a,r,t,null)}}let c=n.children;for(let e=0,t=c.length;e<t;e++)b(c[e],i,a,o,s)}function x(e){e.target.removeEventListener(`dispose`,x);for(let t in l){let n=l[t],r=e.target.uuid;r in n&&(n[r].dispose(),delete n[r])}}}function Bj(e,t){function n(){let t=!1,n=new fT,r=null,i=new fT(0,0,0,0);return{setMask:function(n){r!==n&&!t&&(e.colorMask(n,n,n,n),r=n)},setLocked:function(e){t=e},setClear:function(t,r,a,o,s){s===!0&&(t*=o,r*=o,a*=o),n.set(t,r,a,o),i.equals(n)===!1&&(e.clearColor(t,r,a,o),i.copy(n))},reset:function(){t=!1,r=null,i.set(-1,0,0,0)}}}function r(){let n=!1,r=!1,i=null,a=null,o=null;return{setReversed:function(e){if(r!==e){let n=t.get(`EXT_clip_control`);e?n.clipControlEXT(n.LOWER_LEFT_EXT,n.ZERO_TO_ONE_EXT):n.clipControlEXT(n.LOWER_LEFT_EXT,n.NEGATIVE_ONE_TO_ONE_EXT),r=e;let i=o;o=null,this.setClear(i)}},getReversed:function(){return r},setTest:function(t){t?ue(e.DEPTH_TEST):de(e.DEPTH_TEST)},setMask:function(t){i!==t&&!n&&(e.depthMask(t),i=t)},setFunc:function(t){if(r&&(t=Lw[t]),a!==t){switch(t){case 0:e.depthFunc(e.NEVER);break;case 1:e.depthFunc(e.ALWAYS);break;case 2:e.depthFunc(e.LESS);break;case 3:e.depthFunc(e.LEQUAL);break;case 4:e.depthFunc(e.EQUAL);break;case 5:e.depthFunc(e.GEQUAL);break;case 6:e.depthFunc(e.GREATER);break;case 7:e.depthFunc(e.NOTEQUAL);break;default:e.depthFunc(e.LEQUAL)}a=t}},setLocked:function(e){n=e},setClear:function(t){o!==t&&(o=t,r&&(t=1-t),e.clearDepth(t))},reset:function(){n=!1,i=null,a=null,o=null,r=!1}}}function i(){let t=!1,n=null,r=null,i=null,a=null,o=null,s=null,c=null,l=null;return{setTest:function(n){t||(n?ue(e.STENCIL_TEST):de(e.STENCIL_TEST))},setMask:function(r){n!==r&&!t&&(e.stencilMask(r),n=r)},setFunc:function(t,n,o){(r!==t||i!==n||a!==o)&&(e.stencilFunc(t,n,o),r=t,i=n,a=o)},setOp:function(t,n,r){(o!==t||s!==n||c!==r)&&(e.stencilOp(t,n,r),o=t,s=n,c=r)},setLocked:function(e){t=e},setClear:function(t){l!==t&&(e.clearStencil(t),l=t)},reset:function(){t=!1,n=null,r=null,i=null,a=null,o=null,s=null,c=null,l=null}}}let a=new n,o=new r,s=new i,c=/* @__PURE__ */ new WeakMap,l=/* @__PURE__ */ new WeakMap,u={},d={},f={},p=/* @__PURE__ */ new WeakMap,m=[],h=null,g=!1,_=null,v=null,y=null,b=null,x=null,S=null,C=null,w=new QT(0,0,0),T=0,E=!1,D=null,O=null,k=null,A=null,ee=null,te=e.getParameter(e.MAX_COMBINED_TEXTURE_IMAGE_UNITS),j=!1,ne=0,re=e.getParameter(e.VERSION);re.indexOf(`WebGL`)===-1?re.indexOf(`OpenGL ES`)!==-1&&(ne=parseFloat(/^OpenGL ES (\d)/.exec(re)[1]),j=ne>=2):(ne=parseFloat(/^WebGL (\d)/.exec(re)[1]),j=ne>=1);let M=null,ie={},N=e.getParameter(e.SCISSOR_BOX),ae=e.getParameter(e.VIEWPORT),oe=new fT().fromArray(N),se=new fT().fromArray(ae);function ce(t,n,r,i){let a=/* @__PURE__ */ new Uint8Array(4),o=e.createTexture();e.bindTexture(t,o),e.texParameteri(t,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(t,e.TEXTURE_MAG_FILTER,e.NEAREST);for(let o=0;o<r;o++)t===e.TEXTURE_3D||t===e.TEXTURE_2D_ARRAY?e.texImage3D(n,0,e.RGBA,1,1,i,0,e.RGBA,e.UNSIGNED_BYTE,a):e.texImage2D(n+o,0,e.RGBA,1,1,0,e.RGBA,e.UNSIGNED_BYTE,a);return o}let le={};le[e.TEXTURE_2D]=ce(e.TEXTURE_2D,e.TEXTURE_2D,1),le[e.TEXTURE_CUBE_MAP]=ce(e.TEXTURE_CUBE_MAP,e.TEXTURE_CUBE_MAP_POSITIVE_X,6),le[e.TEXTURE_2D_ARRAY]=ce(e.TEXTURE_2D_ARRAY,e.TEXTURE_2D_ARRAY,1,1),le[e.TEXTURE_3D]=ce(e.TEXTURE_3D,e.TEXTURE_3D,1,1),a.setClear(0,0,0,1),o.setClear(1),s.setClear(0),ue(e.DEPTH_TEST),o.setFunc(3),ye(!1),be(1),ue(e.CULL_FACE),_e(0);function ue(t){u[t]!==!0&&(e.enable(t),u[t]=!0)}function de(t){u[t]!==!1&&(e.disable(t),u[t]=!1)}function fe(t,n){return f[t]!==n&&(e.bindFramebuffer(t,n),f[t]=n,t===e.DRAW_FRAMEBUFFER&&(f[e.FRAMEBUFFER]=n),t===e.FRAMEBUFFER&&(f[e.DRAW_FRAMEBUFFER]=n),!0)}function pe(t,n){let r=m,i=!1;if(t){r=p.get(n),r===void 0&&(r=[],p.set(n,r));let a=t.textures;if(r.length!==a.length||r[0]!==e.COLOR_ATTACHMENT0){for(let t=0,n=a.length;t<n;t++)r[t]=e.COLOR_ATTACHMENT0+t;r.length=a.length,i=!0}}else r[0]!==e.BACK&&(r[0]=e.BACK,i=!0);i&&e.drawBuffers(r)}function me(t){return h!==t&&(e.useProgram(t),h=t,!0)}let he={100:e.FUNC_ADD,101:e.FUNC_SUBTRACT,102:e.FUNC_REVERSE_SUBTRACT};he[103]=e.MIN,he[104]=e.MAX;let ge={200:e.ZERO,201:e.ONE,202:e.SRC_COLOR,204:e.SRC_ALPHA,210:e.SRC_ALPHA_SATURATE,208:e.DST_COLOR,206:e.DST_ALPHA,203:e.ONE_MINUS_SRC_COLOR,205:e.ONE_MINUS_SRC_ALPHA,209:e.ONE_MINUS_DST_COLOR,207:e.ONE_MINUS_DST_ALPHA,211:e.CONSTANT_COLOR,212:e.ONE_MINUS_CONSTANT_COLOR,213:e.CONSTANT_ALPHA,214:e.ONE_MINUS_CONSTANT_ALPHA};function _e(t,n,r,i,a,o,s,c,l,u){if(t===0){g===!0&&(de(e.BLEND),g=!1);return}if(g===!1&&(ue(e.BLEND),g=!0),t!==5){if(t!==_||u!==E){if((v!==100||x!==100)&&(e.blendEquation(e.FUNC_ADD),v=100,x=100),u)switch(t){case 1:e.blendFuncSeparate(e.ONE,e.ONE_MINUS_SRC_ALPHA,e.ONE,e.ONE_MINUS_SRC_ALPHA);break;case 2:e.blendFunc(e.ONE,e.ONE);break;case 3:e.blendFuncSeparate(e.ZERO,e.ONE_MINUS_SRC_COLOR,e.ZERO,e.ONE);break;case 4:e.blendFuncSeparate(e.DST_COLOR,e.ONE_MINUS_SRC_ALPHA,e.ZERO,e.ONE);break;default:J(`WebGLState: Invalid blending: `,t)}else switch(t){case 1:e.blendFuncSeparate(e.SRC_ALPHA,e.ONE_MINUS_SRC_ALPHA,e.ONE,e.ONE_MINUS_SRC_ALPHA);break;case 2:e.blendFuncSeparate(e.SRC_ALPHA,e.ONE,e.ONE,e.ONE);break;case 3:J(`WebGLState: SubtractiveBlending requires material.premultipliedAlpha = true`);break;case 4:J(`WebGLState: MultiplyBlending requires material.premultipliedAlpha = true`);break;default:J(`WebGLState: Invalid blending: `,t)}y=null,b=null,S=null,C=null,w.set(0,0,0),T=0,_=t,E=u}return}a||=n,o||=r,s||=i,(n!==v||a!==x)&&(e.blendEquationSeparate(he[n],he[a]),v=n,x=a),(r!==y||i!==b||o!==S||s!==C)&&(e.blendFuncSeparate(ge[r],ge[i],ge[o],ge[s]),y=r,b=i,S=o,C=s),(c.equals(w)===!1||l!==T)&&(e.blendColor(c.r,c.g,c.b,l),w.copy(c),T=l),_=t,E=!1}function ve(t,n){t.side===2?de(e.CULL_FACE):ue(e.CULL_FACE);let r=t.side===1;n&&(r=!r),ye(r),t.blending===1&&t.transparent===!1?_e(0):_e(t.blending,t.blendEquation,t.blendSrc,t.blendDst,t.blendEquationAlpha,t.blendSrcAlpha,t.blendDstAlpha,t.blendColor,t.blendAlpha,t.premultipliedAlpha),o.setFunc(t.depthFunc),o.setTest(t.depthTest),o.setMask(t.depthWrite),a.setMask(t.colorWrite);let i=t.stencilWrite;s.setTest(i),i&&(s.setMask(t.stencilWriteMask),s.setFunc(t.stencilFunc,t.stencilRef,t.stencilFuncMask),s.setOp(t.stencilFail,t.stencilZFail,t.stencilZPass)),Se(t.polygonOffset,t.polygonOffsetFactor,t.polygonOffsetUnits),t.alphaToCoverage===!0?ue(e.SAMPLE_ALPHA_TO_COVERAGE):de(e.SAMPLE_ALPHA_TO_COVERAGE)}function ye(t){D!==t&&(t?e.frontFace(e.CW):e.frontFace(e.CCW),D=t)}function be(t){t===0?de(e.CULL_FACE):(ue(e.CULL_FACE),t!==O&&(t===1?e.cullFace(e.BACK):t===2?e.cullFace(e.FRONT):e.cullFace(e.FRONT_AND_BACK))),O=t}function xe(t){t!==k&&(j&&e.lineWidth(t),k=t)}function Se(t,n,r){t?(ue(e.POLYGON_OFFSET_FILL),(A!==n||ee!==r)&&(A=n,ee=r,o.getReversed()&&(n=-n),e.polygonOffset(n,r))):de(e.POLYGON_OFFSET_FILL)}function Ce(t){t?ue(e.SCISSOR_TEST):de(e.SCISSOR_TEST)}function P(t){t===void 0&&(t=e.TEXTURE0+te-1),M!==t&&(e.activeTexture(t),M=t)}function we(t,n,r){r===void 0&&(r=M===null?e.TEXTURE0+te-1:M);let i=ie[r];i===void 0&&(i={type:void 0,texture:void 0},ie[r]=i),(i.type!==t||i.texture!==n)&&(M!==r&&(e.activeTexture(r),M=r),e.bindTexture(t,n||le[t]),i.type=t,i.texture=n)}function Te(){let t=ie[M];t!==void 0&&t.type!==void 0&&(e.bindTexture(t.type,null),t.type=void 0,t.texture=void 0)}function Ee(){try{e.compressedTexImage2D(...arguments)}catch(e){J(`WebGLState:`,e)}}function F(){try{e.compressedTexImage3D(...arguments)}catch(e){J(`WebGLState:`,e)}}function De(){try{e.texSubImage2D(...arguments)}catch(e){J(`WebGLState:`,e)}}function I(){try{e.texSubImage3D(...arguments)}catch(e){J(`WebGLState:`,e)}}function L(){try{e.compressedTexSubImage2D(...arguments)}catch(e){J(`WebGLState:`,e)}}function Oe(){try{e.compressedTexSubImage3D(...arguments)}catch(e){J(`WebGLState:`,e)}}function ke(){try{e.texStorage2D(...arguments)}catch(e){J(`WebGLState:`,e)}}function Ae(){try{e.texStorage3D(...arguments)}catch(e){J(`WebGLState:`,e)}}function je(){try{e.texImage2D(...arguments)}catch(e){J(`WebGLState:`,e)}}function Me(){try{e.texImage3D(...arguments)}catch(e){J(`WebGLState:`,e)}}function Ne(t){return d[t]===void 0?e.getParameter(t):d[t]}function Pe(t,n){d[t]!==n&&(e.pixelStorei(t,n),d[t]=n)}function Fe(t){oe.equals(t)===!1&&(e.scissor(t.x,t.y,t.z,t.w),oe.copy(t))}function Ie(t){se.equals(t)===!1&&(e.viewport(t.x,t.y,t.z,t.w),se.copy(t))}function Le(t,n){let r=l.get(n);r===void 0&&(r=/* @__PURE__ */ new WeakMap,l.set(n,r));let i=r.get(t);i===void 0&&(i=e.getUniformBlockIndex(n,t.name),r.set(t,i))}function Re(t,n){let r=l.get(n).get(t);c.get(n)!==r&&(e.uniformBlockBinding(n,r,t.__bindingPointIndex),c.set(n,r))}function ze(){e.disable(e.BLEND),e.disable(e.CULL_FACE),e.disable(e.DEPTH_TEST),e.disable(e.POLYGON_OFFSET_FILL),e.disable(e.SCISSOR_TEST),e.disable(e.STENCIL_TEST),e.disable(e.SAMPLE_ALPHA_TO_COVERAGE),e.blendEquation(e.FUNC_ADD),e.blendFunc(e.ONE,e.ZERO),e.blendFuncSeparate(e.ONE,e.ZERO,e.ONE,e.ZERO),e.blendColor(0,0,0,0),e.colorMask(!0,!0,!0,!0),e.clearColor(0,0,0,0),e.depthMask(!0),e.depthFunc(e.LESS),o.setReversed(!1),e.clearDepth(1),e.stencilMask(4294967295),e.stencilFunc(e.ALWAYS,0,4294967295),e.stencilOp(e.KEEP,e.KEEP,e.KEEP),e.clearStencil(0),e.cullFace(e.BACK),e.frontFace(e.CCW),e.polygonOffset(0,0),e.activeTexture(e.TEXTURE0),e.bindFramebuffer(e.FRAMEBUFFER,null),e.bindFramebuffer(e.DRAW_FRAMEBUFFER,null),e.bindFramebuffer(e.READ_FRAMEBUFFER,null),e.useProgram(null),e.lineWidth(1),e.scissor(0,0,e.canvas.width,e.canvas.height),e.viewport(0,0,e.canvas.width,e.canvas.height),e.pixelStorei(e.PACK_ALIGNMENT,4),e.pixelStorei(e.UNPACK_ALIGNMENT,4),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,!1),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,!1),e.pixelStorei(e.UNPACK_COLORSPACE_CONVERSION_WEBGL,e.BROWSER_DEFAULT_WEBGL),e.pixelStorei(e.PACK_ROW_LENGTH,0),e.pixelStorei(e.PACK_SKIP_PIXELS,0),e.pixelStorei(e.PACK_SKIP_ROWS,0),e.pixelStorei(e.UNPACK_ROW_LENGTH,0),e.pixelStorei(e.UNPACK_IMAGE_HEIGHT,0),e.pixelStorei(e.UNPACK_SKIP_PIXELS,0),e.pixelStorei(e.UNPACK_SKIP_ROWS,0),e.pixelStorei(e.UNPACK_SKIP_IMAGES,0),u={},d={},M=null,ie={},f={},p=/* @__PURE__ */ new WeakMap,m=[],h=null,g=!1,_=null,v=null,y=null,b=null,x=null,S=null,C=null,w=new QT(0,0,0),T=0,E=!1,D=null,O=null,k=null,A=null,ee=null,oe.set(0,0,e.canvas.width,e.canvas.height),se.set(0,0,e.canvas.width,e.canvas.height),a.reset(),o.reset(),s.reset()}return{buffers:{color:a,depth:o,stencil:s},enable:ue,disable:de,bindFramebuffer:fe,drawBuffers:pe,useProgram:me,setBlending:_e,setMaterial:ve,setFlipSided:ye,setCullFace:be,setLineWidth:xe,setPolygonOffset:Se,setScissorTest:Ce,activeTexture:P,bindTexture:we,unbindTexture:Te,compressedTexImage2D:Ee,compressedTexImage3D:F,texImage2D:je,texImage3D:Me,pixelStorei:Pe,getParameter:Ne,updateUBOMapping:Le,uniformBlockBinding:Re,texStorage2D:ke,texStorage3D:Ae,texSubImage2D:De,texSubImage3D:I,compressedTexSubImage2D:L,compressedTexSubImage3D:Oe,scissor:Fe,viewport:Ie,reset:ze}}function Vj(e,t,n,r,i,a,o){let s=t.has(`WEBGL_multisampled_render_to_texture`)?t.get(`WEBGL_multisampled_render_to_texture`):null,c=typeof navigator>`u`?!1:/OculusBrowser/g.test(navigator.userAgent),l=new Y,u=/* @__PURE__ */ new WeakMap,d=/* @__PURE__ */ new Set,f,p=/* @__PURE__ */ new WeakMap,m=!1;try{m=typeof OffscreenCanvas<`u`&&new OffscreenCanvas(1,1).getContext(`2d`)!==null}catch{}function h(e,t){return m?new OffscreenCanvas(e,t):Aw(`canvas`)}function g(e,t,n){let r=1,i=Ee(e);if((i.width>n||i.height>n)&&(r=n/Math.max(i.width,i.height)),r<1){if(typeof HTMLImageElement<`u`&&e instanceof HTMLImageElement||typeof HTMLCanvasElement<`u`&&e instanceof HTMLCanvasElement||typeof ImageBitmap<`u`&&e instanceof ImageBitmap||typeof VideoFrame<`u`&&e instanceof VideoFrame){let n=Math.floor(r*i.width),a=Math.floor(r*i.height);f===void 0&&(f=h(n,a));let o=t?h(n,a):f;return o.width=n,o.height=a,o.getContext(`2d`).drawImage(e,0,0,n,a),q(`WebGLRenderer: Texture has been resized from (`+i.width+`x`+i.height+`) to (`+n+`x`+a+`).`),o}return`data`in e&&q(`WebGLRenderer: Image in DataTexture is too big (`+i.width+`x`+i.height+`).`),e}return e}function _(e){return e.generateMipmaps}function v(t){e.generateMipmap(t)}function y(t){return t.isWebGLCubeRenderTarget?e.TEXTURE_CUBE_MAP:t.isWebGL3DRenderTarget?e.TEXTURE_3D:t.isWebGLArrayRenderTarget||t.isCompressedArrayTexture?e.TEXTURE_2D_ARRAY:e.TEXTURE_2D}function b(n,r,i,a,o,s=!1){if(n!==null){if(e[n]!==void 0)return e[n];q(`WebGLRenderer: Attempt to use non-existing WebGL internal format '`+n+`'`)}let c;a&&(c=t.get(`EXT_texture_norm16`),c||q(`WebGLRenderer: Unable to use normalized textures without EXT_texture_norm16 extension`));let l=r;if(r===e.RED&&(i===e.FLOAT&&(l=e.R32F),i===e.HALF_FLOAT&&(l=e.R16F),i===e.UNSIGNED_BYTE&&(l=e.R8),i===e.UNSIGNED_SHORT&&c&&(l=c.R16_EXT),i===e.SHORT&&c&&(l=c.R16_SNORM_EXT)),r===e.RED_INTEGER&&(i===e.UNSIGNED_BYTE&&(l=e.R8UI),i===e.UNSIGNED_SHORT&&(l=e.R16UI),i===e.UNSIGNED_INT&&(l=e.R32UI),i===e.BYTE&&(l=e.R8I),i===e.SHORT&&(l=e.R16I),i===e.INT&&(l=e.R32I)),r===e.RG&&(i===e.FLOAT&&(l=e.RG32F),i===e.HALF_FLOAT&&(l=e.RG16F),i===e.UNSIGNED_BYTE&&(l=e.RG8),i===e.UNSIGNED_SHORT&&c&&(l=c.RG16_EXT),i===e.SHORT&&c&&(l=c.RG16_SNORM_EXT)),r===e.RG_INTEGER&&(i===e.UNSIGNED_BYTE&&(l=e.RG8UI),i===e.UNSIGNED_SHORT&&(l=e.RG16UI),i===e.UNSIGNED_INT&&(l=e.RG32UI),i===e.BYTE&&(l=e.RG8I),i===e.SHORT&&(l=e.RG16I),i===e.INT&&(l=e.RG32I)),r===e.RGB_INTEGER&&(i===e.UNSIGNED_BYTE&&(l=e.RGB8UI),i===e.UNSIGNED_SHORT&&(l=e.RGB16UI),i===e.UNSIGNED_INT&&(l=e.RGB32UI),i===e.BYTE&&(l=e.RGB8I),i===e.SHORT&&(l=e.RGB16I),i===e.INT&&(l=e.RGB32I)),r===e.RGBA_INTEGER&&(i===e.UNSIGNED_BYTE&&(l=e.RGBA8UI),i===e.UNSIGNED_SHORT&&(l=e.RGBA16UI),i===e.UNSIGNED_INT&&(l=e.RGBA32UI),i===e.BYTE&&(l=e.RGBA8I),i===e.SHORT&&(l=e.RGBA16I),i===e.INT&&(l=e.RGBA32I)),r===e.RGB&&(i===e.UNSIGNED_SHORT&&c&&(l=c.RGB16_EXT),i===e.SHORT&&c&&(l=c.RGB16_SNORM_EXT),i===e.UNSIGNED_INT_5_9_9_9_REV&&(l=e.RGB9_E5),i===e.UNSIGNED_INT_10F_11F_11F_REV&&(l=e.R11F_G11F_B10F)),r===e.RGBA){let t=s?Sw:tT.getTransfer(o);i===e.FLOAT&&(l=e.RGBA32F),i===e.HALF_FLOAT&&(l=e.RGBA16F),i===e.UNSIGNED_BYTE&&(l=t===`srgb`?e.SRGB8_ALPHA8:e.RGBA8),i===e.UNSIGNED_SHORT&&c&&(l=c.RGBA16_EXT),i===e.SHORT&&c&&(l=c.RGBA16_SNORM_EXT),i===e.UNSIGNED_SHORT_4_4_4_4&&(l=e.RGBA4),i===e.UNSIGNED_SHORT_5_5_5_1&&(l=e.RGB5_A1)}return(l===e.R16F||l===e.R32F||l===e.RG16F||l===e.RG32F||l===e.RGBA16F||l===e.RGBA32F)&&t.get(`EXT_color_buffer_float`),l}function x(t,n){let r;return t?n===null||n===1014||n===1020?r=e.DEPTH24_STENCIL8:n===1015?r=e.DEPTH32F_STENCIL8:n===1012&&(r=e.DEPTH24_STENCIL8,q(`DepthTexture: 16 bit depth attachment is not supported with stencil. Using 24-bit attachment.`)):n===null||n===1014||n===1020?r=e.DEPTH_COMPONENT24:n===1015?r=e.DEPTH_COMPONENT32F:n===1012&&(r=e.DEPTH_COMPONENT16),r}function S(e,t){return _(e)===!0||e.isFramebufferTexture&&e.minFilter!==1003&&e.minFilter!==1006?Math.log2(Math.max(t.width,t.height))+1:e.mipmaps!==void 0&&e.mipmaps.length>0?e.mipmaps.length:e.isCompressedTexture&&Array.isArray(e.image)?t.mipmaps.length:1}function C(e){let t=e.target;t.removeEventListener(`dispose`,C),T(t),t.isVideoTexture&&u.delete(t),t.isHTMLTexture&&d.delete(t)}function w(e){let t=e.target;t.removeEventListener(`dispose`,w),D(t)}function T(e){let t=r.get(e);if(t.__webglInit===void 0)return;let n=e.source,i=p.get(n);if(i){let r=i[t.__cacheKey];r.usedTimes--,r.usedTimes===0&&E(e),Object.keys(i).length===0&&p.delete(n)}r.remove(e)}function E(t){let n=r.get(t);e.deleteTexture(n.__webglTexture);let i=t.source,a=p.get(i);delete a[n.__cacheKey],o.memory.textures--}function D(t){let n=r.get(t);if(t.depthTexture&&(t.depthTexture.dispose(),r.remove(t.depthTexture)),t.isWebGLCubeRenderTarget)for(let t=0;t<6;t++){if(Array.isArray(n.__webglFramebuffer[t]))for(let r=0;r<n.__webglFramebuffer[t].length;r++)e.deleteFramebuffer(n.__webglFramebuffer[t][r]);else e.deleteFramebuffer(n.__webglFramebuffer[t]);n.__webglDepthbuffer&&e.deleteRenderbuffer(n.__webglDepthbuffer[t])}else{if(Array.isArray(n.__webglFramebuffer))for(let t=0;t<n.__webglFramebuffer.length;t++)e.deleteFramebuffer(n.__webglFramebuffer[t]);else e.deleteFramebuffer(n.__webglFramebuffer);if(n.__webglDepthbuffer&&e.deleteRenderbuffer(n.__webglDepthbuffer),n.__webglMultisampledFramebuffer&&e.deleteFramebuffer(n.__webglMultisampledFramebuffer),n.__webglColorRenderbuffer)for(let t=0;t<n.__webglColorRenderbuffer.length;t++)n.__webglColorRenderbuffer[t]&&e.deleteRenderbuffer(n.__webglColorRenderbuffer[t]);n.__webglDepthRenderbuffer&&e.deleteRenderbuffer(n.__webglDepthRenderbuffer)}let i=t.textures;for(let t=0,n=i.length;t<n;t++){let n=r.get(i[t]);n.__webglTexture&&(e.deleteTexture(n.__webglTexture),o.memory.textures--),r.remove(i[t])}r.remove(t)}let O=0;function k(){O=0}function A(){return O}function ee(e){O=e}function te(){let e=O;return e>=i.maxTextures&&q(`WebGLTextures: Trying to use `+(e+1)+` texture units while this GPU supports only `+i.maxTextures),O+=1,e}function j(e){let t=[];return t.push(e.wrapS),t.push(e.wrapT),t.push(e.wrapR||0),t.push(e.magFilter),t.push(e.minFilter),t.push(e.anisotropy),t.push(e.internalFormat),t.push(e.format),t.push(e.type),t.push(e.generateMipmaps),t.push(e.premultiplyAlpha),t.push(e.flipY),t.push(e.unpackAlignment),t.push(e.colorSpace),t.join()}function ne(t,i){let a=r.get(t);if(t.isVideoTexture&&we(t),t.isRenderTargetTexture===!1&&t.isExternalTexture!==!0&&t.version>0&&a.__version!==t.version){let e=t.image;if(e===null)q(`WebGLRenderer: Texture marked for update but no image data found.`);else if(e.complete===!1)q(`WebGLRenderer: Texture marked for update but image is incomplete`);else{de(a,t,i);return}}else t.isExternalTexture&&(a.__webglTexture=t.sourceTexture?t.sourceTexture:null);n.bindTexture(e.TEXTURE_2D,a.__webglTexture,e.TEXTURE0+i)}function re(t,i){let a=r.get(t);if(t.isRenderTargetTexture===!1&&t.version>0&&a.__version!==t.version){de(a,t,i);return}t.isExternalTexture&&(a.__webglTexture=t.sourceTexture?t.sourceTexture:null),n.bindTexture(e.TEXTURE_2D_ARRAY,a.__webglTexture,e.TEXTURE0+i)}function M(t,i){let a=r.get(t);if(t.isRenderTargetTexture===!1&&t.version>0&&a.__version!==t.version){de(a,t,i);return}n.bindTexture(e.TEXTURE_3D,a.__webglTexture,e.TEXTURE0+i)}function ie(t,i){let a=r.get(t);if(t.isCubeDepthTexture!==!0&&t.version>0&&a.__version!==t.version){fe(a,t,i);return}n.bindTexture(e.TEXTURE_CUBE_MAP,a.__webglTexture,e.TEXTURE0+i)}let N={[QS]:e.REPEAT,[$S]:e.CLAMP_TO_EDGE,[eC]:e.MIRRORED_REPEAT},ae={[tC]:e.NEAREST,[nC]:e.NEAREST_MIPMAP_NEAREST,[rC]:e.NEAREST_MIPMAP_LINEAR,[iC]:e.LINEAR,[aC]:e.LINEAR_MIPMAP_NEAREST,[oC]:e.LINEAR_MIPMAP_LINEAR},oe={512:e.NEVER,519:e.ALWAYS,513:e.LESS,515:e.LEQUAL,514:e.EQUAL,518:e.GEQUAL,516:e.GREATER,517:e.NOTEQUAL};function se(n,a){if(a.type===1015&&t.has(`OES_texture_float_linear`)===!1&&(a.magFilter===1006||a.magFilter===1007||a.magFilter===1005||a.magFilter===1008||a.minFilter===1006||a.minFilter===1007||a.minFilter===1005||a.minFilter===1008)&&q(`WebGLRenderer: Unable to use linear filtering with floating point textures. OES_texture_float_linear not supported on this device.`),e.texParameteri(n,e.TEXTURE_WRAP_S,N[a.wrapS]),e.texParameteri(n,e.TEXTURE_WRAP_T,N[a.wrapT]),(n===e.TEXTURE_3D||n===e.TEXTURE_2D_ARRAY)&&e.texParameteri(n,e.TEXTURE_WRAP_R,N[a.wrapR]),e.texParameteri(n,e.TEXTURE_MAG_FILTER,ae[a.magFilter]),e.texParameteri(n,e.TEXTURE_MIN_FILTER,ae[a.minFilter]),a.compareFunction&&(e.texParameteri(n,e.TEXTURE_COMPARE_MODE,e.COMPARE_REF_TO_TEXTURE),e.texParameteri(n,e.TEXTURE_COMPARE_FUNC,oe[a.compareFunction])),t.has(`EXT_texture_filter_anisotropic`)===!0){if(a.magFilter===1003||a.minFilter!==1005&&a.minFilter!==1008||a.type===1015&&t.has(`OES_texture_float_linear`)===!1)return;if(a.anisotropy>1||r.get(a).__currentAnisotropy){let o=t.get(`EXT_texture_filter_anisotropic`);e.texParameterf(n,o.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(a.anisotropy,i.getMaxAnisotropy())),r.get(a).__currentAnisotropy=a.anisotropy}}}function ce(t,n){let r=!1;t.__webglInit===void 0&&(t.__webglInit=!0,n.addEventListener(`dispose`,C));let i=n.source,a=p.get(i);a===void 0&&(a={},p.set(i,a));let s=j(n);if(s!==t.__cacheKey){a[s]===void 0&&(a[s]={texture:e.createTexture(),usedTimes:0},o.memory.textures++,r=!0),a[s].usedTimes++;let i=a[t.__cacheKey];i!==void 0&&(a[t.__cacheKey].usedTimes--,i.usedTimes===0&&E(n)),t.__cacheKey=s,t.__webglTexture=a[s].texture}return r}function le(e,t,n){return Math.floor(Math.floor(e/n)/t)}function ue(t,r,i,a){let o=t.updateRanges;if(o.length===0)n.texSubImage2D(e.TEXTURE_2D,0,0,0,r.width,r.height,i,a,r.data);else{o.sort((e,t)=>e.start-t.start);let s=0;for(let e=1;e<o.length;e++){let t=o[s],n=o[e],i=t.start+t.count,a=le(n.start,r.width,4),c=le(t.start,r.width,4);n.start<=i+1&&a===c&&le(n.start+n.count-1,r.width,4)===a?t.count=Math.max(t.count,n.start+n.count-t.start):(++s,o[s]=n)}o.length=s+1;let c=n.getParameter(e.UNPACK_ROW_LENGTH),l=n.getParameter(e.UNPACK_SKIP_PIXELS),u=n.getParameter(e.UNPACK_SKIP_ROWS);n.pixelStorei(e.UNPACK_ROW_LENGTH,r.width);for(let t=0,s=o.length;t<s;t++){let s=o[t],c=Math.floor(s.start/4),l=Math.ceil(s.count/4),u=c%r.width,d=Math.floor(c/r.width),f=l;n.pixelStorei(e.UNPACK_SKIP_PIXELS,u),n.pixelStorei(e.UNPACK_SKIP_ROWS,d),n.texSubImage2D(e.TEXTURE_2D,0,u,d,f,1,i,a,r.data)}t.clearUpdateRanges(),n.pixelStorei(e.UNPACK_ROW_LENGTH,c),n.pixelStorei(e.UNPACK_SKIP_PIXELS,l),n.pixelStorei(e.UNPACK_SKIP_ROWS,u)}}function de(t,o,s){let c=e.TEXTURE_2D;(o.isDataArrayTexture||o.isCompressedArrayTexture)&&(c=e.TEXTURE_2D_ARRAY),o.isData3DTexture&&(c=e.TEXTURE_3D);let l=ce(t,o),u=o.source;n.bindTexture(c,t.__webglTexture,e.TEXTURE0+s);let f=r.get(u);if(u.version!==f.__version||l===!0){if(n.activeTexture(e.TEXTURE0+s),!(typeof ImageBitmap<`u`&&o.image instanceof ImageBitmap)){let t=tT.getPrimaries(tT.workingColorSpace),r=o.colorSpace===``?null:tT.getPrimaries(o.colorSpace),i=o.colorSpace===``||t===r?e.NONE:e.BROWSER_DEFAULT_WEBGL;n.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,o.flipY),n.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,o.premultiplyAlpha),n.pixelStorei(e.UNPACK_COLORSPACE_CONVERSION_WEBGL,i)}n.pixelStorei(e.UNPACK_ALIGNMENT,o.unpackAlignment);let t=g(o.image,!1,i.maxTextureSize);t=Te(o,t);let r=a.convert(o.format,o.colorSpace),p=a.convert(o.type),m=b(o.internalFormat,r,p,o.normalized,o.colorSpace,o.isVideoTexture);se(c,o);let h,y=o.mipmaps,C=o.isVideoTexture!==!0,w=f.__version===void 0||l===!0,T=u.dataReady,E=S(o,t);if(o.isDepthTexture)m=x(o.format===wC,o.type),w&&(C?n.texStorage2D(e.TEXTURE_2D,1,m,t.width,t.height):n.texImage2D(e.TEXTURE_2D,0,m,t.width,t.height,0,r,p,null));else if(o.isDataTexture){if(y.length>0){C&&w&&n.texStorage2D(e.TEXTURE_2D,E,m,y[0].width,y[0].height);for(let t=0,i=y.length;t<i;t++)h=y[t],C?T&&n.texSubImage2D(e.TEXTURE_2D,t,0,0,h.width,h.height,r,p,h.data):n.texImage2D(e.TEXTURE_2D,t,m,h.width,h.height,0,r,p,h.data);o.generateMipmaps=!1}else C?(w&&n.texStorage2D(e.TEXTURE_2D,E,m,t.width,t.height),T&&ue(o,t,r,p)):n.texImage2D(e.TEXTURE_2D,0,m,t.width,t.height,0,r,p,t.data)}else if(o.isCompressedTexture){if(o.isCompressedArrayTexture){C&&w&&n.texStorage3D(e.TEXTURE_2D_ARRAY,E,m,y[0].width,y[0].height,t.depth);for(let i=0,a=y.length;i<a;i++)if(h=y[i],o.format!==1023){if(r!==null){if(C){if(T){if(o.layerUpdates.size>0){let t=IO(h.width,h.height,o.format,o.type);for(let a of o.layerUpdates){let o=h.data.subarray(a*t/h.data.BYTES_PER_ELEMENT,(a+1)*t/h.data.BYTES_PER_ELEMENT);n.compressedTexSubImage3D(e.TEXTURE_2D_ARRAY,i,0,0,a,h.width,h.height,1,r,o)}}else n.compressedTexSubImage3D(e.TEXTURE_2D_ARRAY,i,0,0,0,h.width,h.height,t.depth,r,h.data)}}else n.compressedTexImage3D(e.TEXTURE_2D_ARRAY,i,m,h.width,h.height,t.depth,0,h.data,0,0)}else q(`WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()`)}else C?T&&n.texSubImage3D(e.TEXTURE_2D_ARRAY,i,0,0,0,h.width,h.height,t.depth,r,p,h.data):n.texImage3D(e.TEXTURE_2D_ARRAY,i,m,h.width,h.height,t.depth,0,r,p,h.data);o.layerUpdates.size>0&&o.clearLayerUpdates()}else{C&&w&&n.texStorage2D(e.TEXTURE_2D,E,m,y[0].width,y[0].height);for(let t=0,i=y.length;t<i;t++)h=y[t],o.format===1023?C?T&&n.texSubImage2D(e.TEXTURE_2D,t,0,0,h.width,h.height,r,p,h.data):n.texImage2D(e.TEXTURE_2D,t,m,h.width,h.height,0,r,p,h.data):r===null?q(`WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()`):C?T&&n.compressedTexSubImage2D(e.TEXTURE_2D,t,0,0,h.width,h.height,r,h.data):n.compressedTexImage2D(e.TEXTURE_2D,t,m,h.width,h.height,0,h.data)}}else if(o.isDataArrayTexture){if(C){if(w&&n.texStorage3D(e.TEXTURE_2D_ARRAY,E,m,t.width,t.height,t.depth),T){if(o.layerUpdates.size>0){let i=IO(t.width,t.height,o.format,o.type);for(let a of o.layerUpdates){let o=t.data.subarray(a*i/t.data.BYTES_PER_ELEMENT,(a+1)*i/t.data.BYTES_PER_ELEMENT);n.texSubImage3D(e.TEXTURE_2D_ARRAY,0,0,0,a,t.width,t.height,1,r,p,o)}o.clearLayerUpdates()}else n.texSubImage3D(e.TEXTURE_2D_ARRAY,0,0,0,0,t.width,t.height,t.depth,r,p,t.data)}}else n.texImage3D(e.TEXTURE_2D_ARRAY,0,m,t.width,t.height,t.depth,0,r,p,t.data)}else if(o.isData3DTexture)C?(w&&n.texStorage3D(e.TEXTURE_3D,E,m,t.width,t.height,t.depth),T&&n.texSubImage3D(e.TEXTURE_3D,0,0,0,0,t.width,t.height,t.depth,r,p,t.data)):n.texImage3D(e.TEXTURE_3D,0,m,t.width,t.height,t.depth,0,r,p,t.data);else if(o.isFramebufferTexture){if(w){if(C)n.texStorage2D(e.TEXTURE_2D,E,m,t.width,t.height);else{let i=t.width,a=t.height;for(let t=0;t<E;t++)n.texImage2D(e.TEXTURE_2D,t,m,i,a,0,r,p,null),i>>=1,a>>=1}}}else if(o.isHTMLTexture){if(`texElementImage2D`in e){let n=e.canvas;if(n.hasAttribute(`layoutsubtree`)||n.setAttribute(`layoutsubtree`,`true`),t.parentNode!==n){n.appendChild(t),d.add(o),n.onpaint=e=>{let t=e.changedElements;for(let e of d)t.includes(e.image)&&(e.needsUpdate=!0)},n.requestPaint();return}if(e.texElementImage2D.length===3)e.texElementImage2D(e.TEXTURE_2D,e.RGBA8,t);else{let n=e.RGBA,r=e.RGBA,i=e.UNSIGNED_BYTE;e.texElementImage2D(e.TEXTURE_2D,0,n,r,i,t)}e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE)}}else if(y.length>0){if(C&&w){let t=Ee(y[0]);n.texStorage2D(e.TEXTURE_2D,E,m,t.width,t.height)}for(let t=0,i=y.length;t<i;t++)h=y[t],C?T&&n.texSubImage2D(e.TEXTURE_2D,t,0,0,r,p,h):n.texImage2D(e.TEXTURE_2D,t,m,r,p,h);o.generateMipmaps=!1}else if(C){if(w){let r=Ee(t);n.texStorage2D(e.TEXTURE_2D,E,m,r.width,r.height)}T&&n.texSubImage2D(e.TEXTURE_2D,0,0,0,r,p,t)}else n.texImage2D(e.TEXTURE_2D,0,m,r,p,t);_(o)&&v(c),f.__version=u.version,o.onUpdate&&o.onUpdate(o)}t.__version=o.version}function fe(t,o,s){if(o.image.length!==6)return;let c=ce(t,o),l=o.source;n.bindTexture(e.TEXTURE_CUBE_MAP,t.__webglTexture,e.TEXTURE0+s);let u=r.get(l);if(l.version!==u.__version||c===!0){n.activeTexture(e.TEXTURE0+s);let t=tT.getPrimaries(tT.workingColorSpace),r=o.colorSpace===``?null:tT.getPrimaries(o.colorSpace),d=o.colorSpace===``||t===r?e.NONE:e.BROWSER_DEFAULT_WEBGL;n.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,o.flipY),n.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,o.premultiplyAlpha),n.pixelStorei(e.UNPACK_ALIGNMENT,o.unpackAlignment),n.pixelStorei(e.UNPACK_COLORSPACE_CONVERSION_WEBGL,d);let f=o.isCompressedTexture||o.image[0].isCompressedTexture,p=o.image[0]&&o.image[0].isDataTexture,m=[];for(let e=0;e<6;e++)!f&&!p?m[e]=g(o.image[e],!0,i.maxCubemapSize):m[e]=p?o.image[e].image:o.image[e],m[e]=Te(o,m[e]);let h=m[0],y=a.convert(o.format,o.colorSpace),x=a.convert(o.type),C=b(o.internalFormat,y,x,o.normalized,o.colorSpace),w=o.isVideoTexture!==!0,T=u.__version===void 0||c===!0,E=l.dataReady,D=S(o,h);se(e.TEXTURE_CUBE_MAP,o);let O;if(f){w&&T&&n.texStorage2D(e.TEXTURE_CUBE_MAP,D,C,h.width,h.height);for(let t=0;t<6;t++){O=m[t].mipmaps;for(let r=0;r<O.length;r++){let i=O[r];o.format===1023?w?E&&n.texSubImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,r,0,0,i.width,i.height,y,x,i.data):n.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,r,C,i.width,i.height,0,y,x,i.data):y===null?q(`WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()`):w?E&&n.compressedTexSubImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,r,0,0,i.width,i.height,y,i.data):n.compressedTexImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,r,C,i.width,i.height,0,i.data)}}}else{if(O=o.mipmaps,w&&T){O.length>0&&D++;let t=Ee(m[0]);n.texStorage2D(e.TEXTURE_CUBE_MAP,D,C,t.width,t.height)}for(let t=0;t<6;t++)if(p){w?E&&n.texSubImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,0,0,0,m[t].width,m[t].height,y,x,m[t].data):n.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,0,C,m[t].width,m[t].height,0,y,x,m[t].data);for(let r=0;r<O.length;r++){let i=O[r].image[t].image;w?E&&n.texSubImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,r+1,0,0,i.width,i.height,y,x,i.data):n.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,r+1,C,i.width,i.height,0,y,x,i.data)}}else{w?E&&n.texSubImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,0,0,0,y,x,m[t]):n.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,0,C,y,x,m[t]);for(let r=0;r<O.length;r++){let i=O[r];w?E&&n.texSubImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,r+1,0,0,y,x,i.image[t]):n.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,r+1,C,y,x,i.image[t])}}}_(o)&&v(e.TEXTURE_CUBE_MAP),u.__version=l.version,o.onUpdate&&o.onUpdate(o)}t.__version=o.version}function pe(t,i,o,c,l,u){let d=a.convert(o.format,o.colorSpace),f=a.convert(o.type),p=b(o.internalFormat,d,f,o.normalized,o.colorSpace),m=r.get(i),h=r.get(o);if(h.__renderTarget=i,!m.__hasExternalTextures){let t=Math.max(1,i.width>>u),r=Math.max(1,i.height>>u);l===e.TEXTURE_3D||l===e.TEXTURE_2D_ARRAY?n.texImage3D(l,u,p,t,r,i.depth,0,d,f,null):n.texImage2D(l,u,p,t,r,0,d,f,null)}n.bindFramebuffer(e.FRAMEBUFFER,t),P(i)?s.framebufferTexture2DMultisampleEXT(e.FRAMEBUFFER,c,l,h.__webglTexture,0,Ce(i)):(l===e.TEXTURE_2D||l>=e.TEXTURE_CUBE_MAP_POSITIVE_X&&l<=e.TEXTURE_CUBE_MAP_NEGATIVE_Z)&&e.framebufferTexture2D(e.FRAMEBUFFER,c,l,h.__webglTexture,u),n.bindFramebuffer(e.FRAMEBUFFER,null)}function me(t,n,r){if(e.bindRenderbuffer(e.RENDERBUFFER,t),n.depthBuffer){let i=n.depthTexture,a=i&&i.isDepthTexture?i.type:null,o=x(n.stencilBuffer,a),c=n.stencilBuffer?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT;P(n)?s.renderbufferStorageMultisampleEXT(e.RENDERBUFFER,Ce(n),o,n.width,n.height):r?e.renderbufferStorageMultisample(e.RENDERBUFFER,Ce(n),o,n.width,n.height):e.renderbufferStorage(e.RENDERBUFFER,o,n.width,n.height),e.framebufferRenderbuffer(e.FRAMEBUFFER,c,e.RENDERBUFFER,t)}else{let t=n.textures;for(let i=0;i<t.length;i++){let o=t[i],c=a.convert(o.format,o.colorSpace),l=a.convert(o.type),u=b(o.internalFormat,c,l,o.normalized,o.colorSpace);P(n)?s.renderbufferStorageMultisampleEXT(e.RENDERBUFFER,Ce(n),u,n.width,n.height):r?e.renderbufferStorageMultisample(e.RENDERBUFFER,Ce(n),u,n.width,n.height):e.renderbufferStorage(e.RENDERBUFFER,u,n.width,n.height)}}e.bindRenderbuffer(e.RENDERBUFFER,null)}function he(t,i,o){let c=i.isWebGLCubeRenderTarget===!0;if(n.bindFramebuffer(e.FRAMEBUFFER,t),!(i.depthTexture&&i.depthTexture.isDepthTexture))throw Error(`THREE.WebGLTextures: renderTarget.depthTexture must be an instance of THREE.DepthTexture.`);let l=r.get(i.depthTexture);if(l.__renderTarget=i,(!l.__webglTexture||i.depthTexture.image.width!==i.width||i.depthTexture.image.height!==i.height)&&(i.depthTexture.image.width=i.width,i.depthTexture.image.height=i.height,i.depthTexture.needsUpdate=!0),c){if(l.__webglInit===void 0&&(l.__webglInit=!0,i.depthTexture.addEventListener(`dispose`,C)),l.__webglTexture===void 0){l.__webglTexture=e.createTexture(),n.bindTexture(e.TEXTURE_CUBE_MAP,l.__webglTexture),se(e.TEXTURE_CUBE_MAP,i.depthTexture);let t=a.convert(i.depthTexture.format),r=a.convert(i.depthTexture.type),o;i.depthTexture.format===1026?o=e.DEPTH_COMPONENT24:i.depthTexture.format===1027&&(o=e.DEPTH24_STENCIL8);for(let n=0;n<6;n++)e.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+n,0,o,i.width,i.height,0,t,r,null)}}else ne(i.depthTexture,0);let u=l.__webglTexture,d=Ce(i),f=c?e.TEXTURE_CUBE_MAP_POSITIVE_X+o:e.TEXTURE_2D,p=i.depthTexture.format===1027?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT;if(i.depthTexture.format===1026)P(i)?s.framebufferTexture2DMultisampleEXT(e.FRAMEBUFFER,p,f,u,0,d):e.framebufferTexture2D(e.FRAMEBUFFER,p,f,u,0);else if(i.depthTexture.format===1027)P(i)?s.framebufferTexture2DMultisampleEXT(e.FRAMEBUFFER,p,f,u,0,d):e.framebufferTexture2D(e.FRAMEBUFFER,p,f,u,0);else throw Error(`THREE.WebGLTextures: Unknown depthTexture format.`)}function ge(t){let i=r.get(t),a=t.isWebGLCubeRenderTarget===!0;if(i.__boundDepthTexture!==t.depthTexture){let e=t.depthTexture;if(i.__depthDisposeCallback&&i.__depthDisposeCallback(),e){let t=()=>{delete i.__boundDepthTexture,delete i.__depthDisposeCallback,e.removeEventListener(`dispose`,t)};e.addEventListener(`dispose`,t),i.__depthDisposeCallback=t}i.__boundDepthTexture=e}if(t.depthTexture&&!i.__autoAllocateDepthBuffer){if(a)for(let e=0;e<6;e++)he(i.__webglFramebuffer[e],t,e);else{let e=t.texture.mipmaps;e&&e.length>0?he(i.__webglFramebuffer[0],t,0):he(i.__webglFramebuffer,t,0)}}else if(a){i.__webglDepthbuffer=[];for(let r=0;r<6;r++)if(n.bindFramebuffer(e.FRAMEBUFFER,i.__webglFramebuffer[r]),i.__webglDepthbuffer[r]===void 0)i.__webglDepthbuffer[r]=e.createRenderbuffer(),me(i.__webglDepthbuffer[r],t,!1);else{let n=t.stencilBuffer?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT,a=i.__webglDepthbuffer[r];e.bindRenderbuffer(e.RENDERBUFFER,a),e.framebufferRenderbuffer(e.FRAMEBUFFER,n,e.RENDERBUFFER,a)}}else{let r=t.texture.mipmaps;if(r&&r.length>0?n.bindFramebuffer(e.FRAMEBUFFER,i.__webglFramebuffer[0]):n.bindFramebuffer(e.FRAMEBUFFER,i.__webglFramebuffer),i.__webglDepthbuffer===void 0)i.__webglDepthbuffer=e.createRenderbuffer(),me(i.__webglDepthbuffer,t,!1);else{let n=t.stencilBuffer?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT,r=i.__webglDepthbuffer;e.bindRenderbuffer(e.RENDERBUFFER,r),e.framebufferRenderbuffer(e.FRAMEBUFFER,n,e.RENDERBUFFER,r)}}n.bindFramebuffer(e.FRAMEBUFFER,null)}function _e(t,n,i){let a=r.get(t);n!==void 0&&pe(a.__webglFramebuffer,t,t.texture,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,0),i!==void 0&&ge(t)}function ve(t){let i=t.texture,s=r.get(t),c=r.get(i);t.addEventListener(`dispose`,w);let l=t.textures,u=t.isWebGLCubeRenderTarget===!0,d=l.length>1;if(d||(c.__webglTexture===void 0&&(c.__webglTexture=e.createTexture()),c.__version=i.version,o.memory.textures++),u){s.__webglFramebuffer=[];for(let t=0;t<6;t++)if(i.mipmaps&&i.mipmaps.length>0){s.__webglFramebuffer[t]=[];for(let n=0;n<i.mipmaps.length;n++)s.__webglFramebuffer[t][n]=e.createFramebuffer()}else s.__webglFramebuffer[t]=e.createFramebuffer()}else{if(i.mipmaps&&i.mipmaps.length>0){s.__webglFramebuffer=[];for(let t=0;t<i.mipmaps.length;t++)s.__webglFramebuffer[t]=e.createFramebuffer()}else s.__webglFramebuffer=e.createFramebuffer();if(d)for(let t=0,n=l.length;t<n;t++){let n=r.get(l[t]);n.__webglTexture===void 0&&(n.__webglTexture=e.createTexture(),o.memory.textures++)}if(t.samples>0&&P(t)===!1){s.__webglMultisampledFramebuffer=e.createFramebuffer(),s.__webglColorRenderbuffer=[],n.bindFramebuffer(e.FRAMEBUFFER,s.__webglMultisampledFramebuffer);for(let n=0;n<l.length;n++){let r=l[n];s.__webglColorRenderbuffer[n]=e.createRenderbuffer(),e.bindRenderbuffer(e.RENDERBUFFER,s.__webglColorRenderbuffer[n]);let i=a.convert(r.format,r.colorSpace),o=a.convert(r.type),c=b(r.internalFormat,i,o,r.normalized,r.colorSpace,t.isXRRenderTarget===!0),u=Ce(t);e.renderbufferStorageMultisample(e.RENDERBUFFER,u,c,t.width,t.height),e.framebufferRenderbuffer(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0+n,e.RENDERBUFFER,s.__webglColorRenderbuffer[n])}e.bindRenderbuffer(e.RENDERBUFFER,null),t.depthBuffer&&(s.__webglDepthRenderbuffer=e.createRenderbuffer(),me(s.__webglDepthRenderbuffer,t,!0)),n.bindFramebuffer(e.FRAMEBUFFER,null)}}if(u){n.bindTexture(e.TEXTURE_CUBE_MAP,c.__webglTexture),se(e.TEXTURE_CUBE_MAP,i);for(let n=0;n<6;n++)if(i.mipmaps&&i.mipmaps.length>0)for(let r=0;r<i.mipmaps.length;r++)pe(s.__webglFramebuffer[n][r],t,i,e.COLOR_ATTACHMENT0,e.TEXTURE_CUBE_MAP_POSITIVE_X+n,r);else pe(s.__webglFramebuffer[n],t,i,e.COLOR_ATTACHMENT0,e.TEXTURE_CUBE_MAP_POSITIVE_X+n,0);_(i)&&v(e.TEXTURE_CUBE_MAP),n.unbindTexture()}else if(d){for(let i=0,a=l.length;i<a;i++){let a=l[i],o=r.get(a),c=e.TEXTURE_2D;(t.isWebGL3DRenderTarget||t.isWebGLArrayRenderTarget)&&(c=t.isWebGL3DRenderTarget?e.TEXTURE_3D:e.TEXTURE_2D_ARRAY),n.bindTexture(c,o.__webglTexture),se(c,a),pe(s.__webglFramebuffer,t,a,e.COLOR_ATTACHMENT0+i,c,0),_(a)&&v(c)}n.unbindTexture()}else{let r=e.TEXTURE_2D;if((t.isWebGL3DRenderTarget||t.isWebGLArrayRenderTarget)&&(r=t.isWebGL3DRenderTarget?e.TEXTURE_3D:e.TEXTURE_2D_ARRAY),n.bindTexture(r,c.__webglTexture),se(r,i),i.mipmaps&&i.mipmaps.length>0)for(let n=0;n<i.mipmaps.length;n++)pe(s.__webglFramebuffer[n],t,i,e.COLOR_ATTACHMENT0,r,n);else pe(s.__webglFramebuffer,t,i,e.COLOR_ATTACHMENT0,r,0);_(i)&&v(r),n.unbindTexture()}t.depthBuffer&&ge(t)}function ye(e){let t=e.textures;for(let i=0,a=t.length;i<a;i++){let a=t[i];if(_(a)){let t=y(e),i=r.get(a).__webglTexture;n.bindTexture(t,i),v(t),n.unbindTexture()}}}let be=[],xe=[];function Se(t){if(t.samples>0){if(P(t)===!1){let i=t.textures,a=t.width,o=t.height,s=e.COLOR_BUFFER_BIT,l=t.stencilBuffer?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT,u=r.get(t),d=i.length>1;if(d)for(let t=0;t<i.length;t++)n.bindFramebuffer(e.FRAMEBUFFER,u.__webglMultisampledFramebuffer),e.framebufferRenderbuffer(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0+t,e.RENDERBUFFER,null),n.bindFramebuffer(e.FRAMEBUFFER,u.__webglFramebuffer),e.framebufferTexture2D(e.DRAW_FRAMEBUFFER,e.COLOR_ATTACHMENT0+t,e.TEXTURE_2D,null,0);n.bindFramebuffer(e.READ_FRAMEBUFFER,u.__webglMultisampledFramebuffer);let f=t.texture.mipmaps;f&&f.length>0?n.bindFramebuffer(e.DRAW_FRAMEBUFFER,u.__webglFramebuffer[0]):n.bindFramebuffer(e.DRAW_FRAMEBUFFER,u.__webglFramebuffer);for(let n=0;n<i.length;n++){if(t.resolveDepthBuffer&&(t.depthBuffer&&(s|=e.DEPTH_BUFFER_BIT),t.stencilBuffer&&t.resolveStencilBuffer&&(s|=e.STENCIL_BUFFER_BIT)),d){e.framebufferRenderbuffer(e.READ_FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.RENDERBUFFER,u.__webglColorRenderbuffer[n]);let t=r.get(i[n]).__webglTexture;e.framebufferTexture2D(e.DRAW_FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0)}e.blitFramebuffer(0,0,a,o,0,0,a,o,s,e.NEAREST),c===!0&&(be.length=0,xe.length=0,be.push(e.COLOR_ATTACHMENT0+n),t.depthBuffer&&t.storeMultisampledDepthBuffer===!1&&(be.push(l),xe.push(l),e.invalidateFramebuffer(e.DRAW_FRAMEBUFFER,xe)),e.invalidateFramebuffer(e.READ_FRAMEBUFFER,be))}if(n.bindFramebuffer(e.READ_FRAMEBUFFER,null),n.bindFramebuffer(e.DRAW_FRAMEBUFFER,null),d)for(let t=0;t<i.length;t++){n.bindFramebuffer(e.FRAMEBUFFER,u.__webglMultisampledFramebuffer),e.framebufferRenderbuffer(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0+t,e.RENDERBUFFER,u.__webglColorRenderbuffer[t]);let a=r.get(i[t]).__webglTexture;n.bindFramebuffer(e.FRAMEBUFFER,u.__webglFramebuffer),e.framebufferTexture2D(e.DRAW_FRAMEBUFFER,e.COLOR_ATTACHMENT0+t,e.TEXTURE_2D,a,0)}n.bindFramebuffer(e.DRAW_FRAMEBUFFER,u.__webglMultisampledFramebuffer)}else if(t.depthBuffer&&t.storeMultisampledDepthBuffer===!1&&c){let n=t.stencilBuffer?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT;e.invalidateFramebuffer(e.DRAW_FRAMEBUFFER,[n])}}}function Ce(e){return Math.min(i.maxSamples,e.samples)}function P(e){let n=r.get(e);return e.samples>0&&t.has(`WEBGL_multisampled_render_to_texture`)===!0&&n.__useRenderToTexture!==!1}function we(e){let t=o.render.frame;u.get(e)!==t&&(u.set(e,t),e.update())}function Te(e,t){let n=e.colorSpace,r=e.format,i=e.type;return e.isCompressedTexture===!0||e.isVideoTexture===!0||n!==`srgb-linear`&&n!==``&&(tT.getTransfer(n)===`srgb`?(r!==1023||i!==1009)&&q(`WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType.`):J(`WebGLTextures: Unsupported texture color space:`,n)),t}function Ee(e){return typeof HTMLImageElement<`u`&&e instanceof HTMLImageElement?(l.width=e.naturalWidth||e.width,l.height=e.naturalHeight||e.height):typeof VideoFrame<`u`&&e instanceof VideoFrame?(l.width=e.displayWidth,l.height=e.displayHeight):(l.width=e.width,l.height=e.height),l}this.allocateTextureUnit=te,this.resetTextureUnits=k,this.getTextureUnits=A,this.setTextureUnits=ee,this.setTexture2D=ne,this.setTexture2DArray=re,this.setTexture3D=M,this.setTextureCube=ie,this.rebindTextures=_e,this.setupRenderTarget=ve,this.updateRenderTargetMipmap=ye,this.updateMultisampleRenderTarget=Se,this.setupDepthRenderbuffer=ge,this.setupFrameBufferTexture=pe,this.useMultisampledRTT=P,this.isReversedDepthBuffer=function(){return n.buffers.depth.getReversed()}}function Hj(e,t){function n(n,r=``){let i,a=tT.getTransfer(r);if(n===1009)return e.UNSIGNED_BYTE;if(n===1017)return e.UNSIGNED_SHORT_4_4_4_4;if(n===1018)return e.UNSIGNED_SHORT_5_5_5_1;if(n===35902)return e.UNSIGNED_INT_5_9_9_9_REV;if(n===35899)return e.UNSIGNED_INT_10F_11F_11F_REV;if(n===1010)return e.BYTE;if(n===1011)return e.SHORT;if(n===1012)return e.UNSIGNED_SHORT;if(n===1013)return e.INT;if(n===1014)return e.UNSIGNED_INT;if(n===1015)return e.FLOAT;if(n===1016)return e.HALF_FLOAT;if(n===1021)return e.ALPHA;if(n===1022)return e.RGB;if(n===1023)return e.RGBA;if(n===1026)return e.DEPTH_COMPONENT;if(n===1027)return e.DEPTH_STENCIL;if(n===1028)return e.RED;if(n===1029)return e.RED_INTEGER;if(n===1030)return e.RG;if(n===1031)return e.RG_INTEGER;if(n===1033)return e.RGBA_INTEGER;if(n===33776||n===33777||n===33778||n===33779){if(a===`srgb`){if(i=t.get(`WEBGL_compressed_texture_s3tc_srgb`),i!==null){if(n===33776)return i.COMPRESSED_SRGB_S3TC_DXT1_EXT;if(n===33777)return i.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;if(n===33778)return i.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;if(n===33779)return i.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}else return null}else if(i=t.get(`WEBGL_compressed_texture_s3tc`),i!==null){if(n===33776)return i.COMPRESSED_RGB_S3TC_DXT1_EXT;if(n===33777)return i.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(n===33778)return i.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(n===33779)return i.COMPRESSED_RGBA_S3TC_DXT5_EXT}else return null}if(n===35840||n===35841||n===35842||n===35843){if(i=t.get(`WEBGL_compressed_texture_pvrtc`),i!==null){if(n===35840)return i.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(n===35841)return i.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(n===35842)return i.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(n===35843)return i.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}else return null}if(n===36196||n===37492||n===37496||n===37488||n===37489||n===37490||n===37491){if(i=t.get(`WEBGL_compressed_texture_etc`),i!==null){if(n===36196||n===37492)return a===`srgb`?i.COMPRESSED_SRGB8_ETC2:i.COMPRESSED_RGB8_ETC2;if(n===37496)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:i.COMPRESSED_RGBA8_ETC2_EAC;if(n===37488)return i.COMPRESSED_R11_EAC;if(n===37489)return i.COMPRESSED_SIGNED_R11_EAC;if(n===37490)return i.COMPRESSED_RG11_EAC;if(n===37491)return i.COMPRESSED_SIGNED_RG11_EAC}else return null}if(n===37808||n===37809||n===37810||n===37811||n===37812||n===37813||n===37814||n===37815||n===37816||n===37817||n===37818||n===37819||n===37820||n===37821){if(i=t.get(`WEBGL_compressed_texture_astc`),i!==null){if(n===37808)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:i.COMPRESSED_RGBA_ASTC_4x4_KHR;if(n===37809)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:i.COMPRESSED_RGBA_ASTC_5x4_KHR;if(n===37810)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:i.COMPRESSED_RGBA_ASTC_5x5_KHR;if(n===37811)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:i.COMPRESSED_RGBA_ASTC_6x5_KHR;if(n===37812)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:i.COMPRESSED_RGBA_ASTC_6x6_KHR;if(n===37813)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:i.COMPRESSED_RGBA_ASTC_8x5_KHR;if(n===37814)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:i.COMPRESSED_RGBA_ASTC_8x6_KHR;if(n===37815)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:i.COMPRESSED_RGBA_ASTC_8x8_KHR;if(n===37816)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:i.COMPRESSED_RGBA_ASTC_10x5_KHR;if(n===37817)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:i.COMPRESSED_RGBA_ASTC_10x6_KHR;if(n===37818)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:i.COMPRESSED_RGBA_ASTC_10x8_KHR;if(n===37819)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:i.COMPRESSED_RGBA_ASTC_10x10_KHR;if(n===37820)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:i.COMPRESSED_RGBA_ASTC_12x10_KHR;if(n===37821)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:i.COMPRESSED_RGBA_ASTC_12x12_KHR}else return null}if(n===36492||n===36494||n===36495){if(i=t.get(`EXT_texture_compression_bptc`),i!==null){if(n===36492)return a===`srgb`?i.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT:i.COMPRESSED_RGBA_BPTC_UNORM_EXT;if(n===36494)return i.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT;if(n===36495)return i.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT}else return null}if(n===36283||n===36284||n===36285||n===36286){if(i=t.get(`EXT_texture_compression_rgtc`),i!==null){if(n===36283)return i.COMPRESSED_RED_RGTC1_EXT;if(n===36284)return i.COMPRESSED_SIGNED_RED_RGTC1_EXT;if(n===36285)return i.COMPRESSED_RED_GREEN_RGTC2_EXT;if(n===36286)return i.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT}else return null}return n===1020?e.UNSIGNED_INT_24_8:e[n]===void 0?null:e[n]}return{convert:n}}var Uj=`
|
|
4199
4199
|
void main() {
|
|
4200
4200
|
|
|
4201
4201
|
gl_Position = vec4( position, 1.0 );
|
|
4202
4202
|
|
|
4203
|
-
}`,
|
|
4203
|
+
}`,Wj=`
|
|
4204
4204
|
uniform sampler2DArray depthColor;
|
|
4205
4205
|
uniform float depthWidth;
|
|
4206
4206
|
uniform float depthHeight;
|
|
@@ -4219,7 +4219,7 @@ void main() {
|
|
|
4219
4219
|
|
|
4220
4220
|
}
|
|
4221
4221
|
|
|
4222
|
-
}`,mA=class{constructor(){this.texture=null,this.mesh=null,this.depthNear=0,this.depthFar=0}init(e,t){if(this.texture===null){let n=new eE(e.texture);(e.depthNear!==t.depthNear||e.depthFar!==t.depthFar)&&(this.depthNear=e.depthNear,this.depthFar=e.depthFar),this.texture=n}}getMesh(e){if(this.texture!==null&&this.mesh===null){let t=e.cameras[0].viewport,n=new dE({vertexShader:fA,fragmentShader:pA,uniforms:{depthColor:{value:this.texture},depthWidth:{value:t.z},depthHeight:{value:t.w}}});this.mesh=new VT(new nE(20,20),n)}return this.mesh}reset(){this.texture=null,this.mesh=null}getDepthTexture(){return this.texture}},hA=class extends sC{constructor(e,t){super();let n=this,r=null,i=1,a=null,o=`local-floor`,s=1,c=null,l=null,u=null,d=null,f=null,p=null,m=typeof XRWebGLBinding<`u`,h=new mA,g={},_=t.getContextAttributes(),v=null,y=null,b=[],x=[],S=new Y,C=null,w=null,T=new VE;T.viewport=new FC;let E=new VE;E.viewport=new FC;let D=[T,E],O=new KE,k=null,A=null;this.cameraAutoUpdate=!0,this.enabled=!1,this.isPresenting=!1,this.getController=function(e){let t=b[e];return t===void 0&&(t=new gw,b[e]=t),t.getTargetRaySpace()},this.getControllerGrip=function(e){let t=b[e];return t===void 0&&(t=new gw,b[e]=t),t.getGripSpace()},this.getHand=function(e){let t=b[e];return t===void 0&&(t=new gw,b[e]=t),t.getHandSpace()};function ee(e){let t=x.indexOf(e.inputSource);if(t===-1)return;let n=b[t];n!==void 0&&(n.update(e.inputSource,e.frame,c||a),n.dispatchEvent({type:e.type,data:e.inputSource}))}function te(){r.removeEventListener(`select`,ee),r.removeEventListener(`selectstart`,ee),r.removeEventListener(`selectend`,ee),r.removeEventListener(`squeeze`,ee),r.removeEventListener(`squeezestart`,ee),r.removeEventListener(`squeezeend`,ee),r.removeEventListener(`end`,te),r.removeEventListener(`inputsourceschange`,j);for(let e=0;e<b.length;e++){let t=x[e];t!==null&&(x[e]=null,b[e].disconnect(t))}k=null,A=null,h.reset();for(let e in g)delete g[e];if(e.setRenderTarget(v),f=null,d=null,u=null,r=null,y=null,se.stop(),n.isPresenting=!1,e.setPixelRatio(C),e.setSize(S.width,S.height,!1),w!==null){let e=w.camera;e.fov=w.fov,e.zoom=w.zoom,e.updateProjectionMatrix(),w=null}n.dispatchEvent({type:`sessionend`})}this.setFramebufferScaleFactor=function(e){i=e,n.isPresenting===!0&&q(`WebXRManager: Cannot change framebuffer scale while presenting.`)},this.setReferenceSpaceType=function(e){o=e,n.isPresenting===!0&&q(`WebXRManager: Cannot change reference space type while presenting.`)},this.getReferenceSpace=function(){return c||a},this.setReferenceSpace=function(e){c=e},this.getBaseLayer=function(){return d===null?f:d},this.getBinding=function(){return u===null&&m&&(u=new XRWebGLBinding(r,t)),u},this.getFrame=function(){return p},this.getSession=function(){return r},this.setSession=async function(l){if(r=l,r!==null){if(v=e.getRenderTarget(),r.addEventListener(`select`,ee),r.addEventListener(`selectstart`,ee),r.addEventListener(`selectend`,ee),r.addEventListener(`squeeze`,ee),r.addEventListener(`squeezestart`,ee),r.addEventListener(`squeezeend`,ee),r.addEventListener(`end`,te),r.addEventListener(`inputsourceschange`,j),_.xrCompatible!==!0&&await t.makeXRCompatible(),C=e.getPixelRatio(),e.getSize(S),m&&`createProjectionLayer`in XRWebGLBinding.prototype){let n=null,a=null,o=null;_.depth&&(o=_.stencil?t.DEPTH24_STENCIL8:t.DEPTH_COMPONENT24,n=_.stencil?qx:Kx,a=_.stencil?Bx:Fx);let s={colorFormat:t.RGBA8,depthFormat:o,scaleFactor:i};u=this.getBinding(),d=u.createProjectionLayer(s),r.updateRenderState({layers:[d]}),e.setPixelRatio(1),e.setSize(d.textureWidth,d.textureHeight,!1),y=new LC(d.textureWidth,d.textureHeight,{format:Gx,type:Ax,depthTexture:new QT(d.textureWidth,d.textureHeight,a,void 0,void 0,void 0,void 0,void 0,void 0,n),stencilBuffer:_.stencil,colorSpace:e.outputColorSpace,samples:_.antialias?4:0,resolveDepthBuffer:d.ignoreDepthValues===!1,resolveStencilBuffer:d.ignoreDepthValues===!1,storeMultisampledDepthBuffer:d.ignoreDepthValues===!1,storeMultisampledStencilBuffer:d.ignoreDepthValues===!1})}else{let n={antialias:_.antialias,alpha:!0,depth:_.depth,stencil:_.stencil,framebufferScaleFactor:i};f=new XRWebGLLayer(r,t,n),r.updateRenderState({baseLayer:f}),e.setPixelRatio(1),e.setSize(f.framebufferWidth,f.framebufferHeight,!1),y=new LC(f.framebufferWidth,f.framebufferHeight,{format:Gx,type:Ax,colorSpace:e.outputColorSpace,stencilBuffer:_.stencil,resolveDepthBuffer:f.ignoreDepthValues===!1,resolveStencilBuffer:f.ignoreDepthValues===!1,storeMultisampledDepthBuffer:f.ignoreDepthValues===!1,storeMultisampledStencilBuffer:f.ignoreDepthValues===!1})}y.isXRRenderTarget=!0,this.setFoveation(s),c=null,a=await r.requestReferenceSpace(o),se.setContext(r),se.start(),n.isPresenting=!0,n.dispatchEvent({type:`sessionstart`})}},this.getEnvironmentBlendMode=function(){if(r!==null)return r.environmentBlendMode},this.getDepthTexture=function(){return h.getDepthTexture()};function j(e){for(let t=0;t<e.removed.length;t++){let n=e.removed[t],r=x.indexOf(n);r>=0&&(x[r]=null,b[r].disconnect(n))}for(let t=0;t<e.added.length;t++){let n=e.added[t],r=x.indexOf(n);if(r===-1){for(let e=0;e<b.length;e++)if(e>=x.length){x.push(n),r=e;break}else if(x[e]===null){x[e]=n,r=e;break}if(r===-1)break}let i=b[r];i&&i.connect(n)}}let ne=new X,re=new X;function M(e,t,n){ne.setFromMatrixPosition(t.matrixWorld),re.setFromMatrixPosition(n.matrixWorld);let r=ne.distanceTo(re),i=t.projectionMatrix.elements,a=n.projectionMatrix.elements,o=i[14]/(i[10]-1),s=i[14]/(i[10]+1),c=(i[9]+1)/i[5],l=(i[9]-1)/i[5],u=(i[8]-1)/i[0],d=(a[8]+1)/a[0],f=o*u,p=o*d,m=r/(-u+d),h=m*-u;if(t.matrixWorld.decompose(e.position,e.quaternion,e.scale),e.translateX(h),e.translateZ(m),e.matrixWorld.compose(e.position,e.quaternion,e.scale),e.matrixWorldInverse.copy(e.matrixWorld).invert(),i[10]===-1)e.projectionMatrix.copy(t.projectionMatrix),e.projectionMatrixInverse.copy(t.projectionMatrixInverse);else{let t=o+m,n=s+m,i=f-h,a=p+(r-h),u=c*s/n*t,d=l*s/n*t;e.projectionMatrix.makePerspective(i,a,u,d,t,n),e.projectionMatrixInverse.copy(e.projectionMatrix).invert()}}function ie(e,t){t===null?e.matrixWorld.copy(e.matrix):e.matrixWorld.multiplyMatrices(t.matrixWorld,e.matrix),e.matrixWorldInverse.copy(e.matrixWorld).invert()}this.updateCamera=function(e){if(r===null)return;let t=e.near,n=e.far;h.texture!==null&&(h.depthNear>0&&(t=h.depthNear),h.depthFar>0&&(n=h.depthFar)),O.near=E.near=T.near=t,O.far=E.far=T.far=n,(k!==O.near||A!==O.far)&&(r.updateRenderState({depthNear:O.near,depthFar:O.far}),k=O.near,A=O.far),O.layers.mask=e.layers.mask|6,T.layers.mask=O.layers.mask&-5,E.layers.mask=O.layers.mask&-3;let i=e.parent,a=O.cameras;ie(O,i);for(let e=0;e<a.length;e++)ie(a[e],i);a.length===2?M(O,T,E):O.projectionMatrix.copy(T.projectionMatrix),w===null&&e.isPerspectiveCamera&&(w={camera:e,fov:e.fov,zoom:e.zoom}),N(e,O,i)};function N(e,t,n){n===null?e.matrix.copy(t.matrixWorld):(e.matrix.copy(n.matrixWorld),e.matrix.invert(),e.matrix.multiply(t.matrixWorld)),e.matrix.decompose(e.position,e.quaternion,e.scale),e.updateMatrixWorld(!0),e.projectionMatrix.copy(t.projectionMatrix),e.projectionMatrixInverse.copy(t.projectionMatrixInverse),e.isPerspectiveCamera&&(e.fov=uC*2*Math.atan(1/e.projectionMatrix.elements[5]),e.zoom=1)}this.getCamera=function(){return O},this.getFoveation=function(){if(d!==null||f!==null)return s},this.setFoveation=function(e){s=e,d!==null&&(d.fixedFoveation=e),f!==null&&f.fixedFoveation!==void 0&&(f.fixedFoveation=e)},this.hasDepthSensing=function(){return h.texture!==null},this.getDepthSensingMesh=function(){return h.getMesh(O)},this.getCameraTexture=function(e){return g[e]};let ae=null;function oe(t,i){if(l=i.getViewerPose(c||a),p=i,l!==null){let t=l.views;f!==null&&(e.setRenderTargetFramebuffer(y,f.framebuffer),e.setRenderTarget(y));let i=!1;t.length!==O.cameras.length&&(O.cameras.length=0,i=!0);for(let n=0;n<t.length;n++){let r=t[n],a=null;if(f!==null)a=f.getViewport(r);else{let t=u.getViewSubImage(d,r);a=t.viewport,n===0&&(e.setRenderTargetTextures(y,t.colorTexture,t.depthStencilTexture),e.setRenderTarget(y))}let o=D[n];o===void 0&&(o=new VE,o.layers.enable(n),o.viewport=new FC,D[n]=o),o.matrix.fromArray(r.transform.matrix),o.matrix.decompose(o.position,o.quaternion,o.scale),o.projectionMatrix.fromArray(r.projectionMatrix),o.projectionMatrixInverse.copy(o.projectionMatrix).invert(),o.viewport.set(a.x,a.y,a.width,a.height),n===0&&(O.matrix.copy(o.matrix),O.matrix.decompose(O.position,O.quaternion,O.scale)),i===!0&&O.cameras.push(o)}let a=r.enabledFeatures;if(a&&a.includes(`depth-sensing`)&&r.depthUsage==`gpu-optimized`&&m){u=n.getBinding();let e=u.getDepthInformation(t[0]);e&&e.isValid&&e.texture&&h.init(e,r.renderState)}if(a&&a.includes(`camera-access`)&&m){e.state.unbindTexture(),u=n.getBinding();for(let e=0;e<t.length;e++){let n=t[e].camera;if(n){let e=g[n];e||(e=new eE,g[n]=e);let t=u.getCameraImage(n);e.sourceTexture=t}}}}for(let e=0;e<b.length;e++){let t=x[e],n=b[e];t!==null&&n!==void 0&&n.update(t,i,c||a)}ae&&ae(t,i),i.detectedPlanes&&n.dispatchEvent({type:`planesdetected`,data:i}),p=null}let se=new sD;se.setAnimationLoop(oe),this.setAnimationLoop=function(e){ae=e},this.dispose=function(){}}},gA=/*@__PURE__*/ new BC,_A=/*@__PURE__*/ new Z;_A.set(-1,0,0,0,1,0,0,0,1);function vA(e,t){function n(e,t){e.matrixAutoUpdate===!0&&e.updateMatrix(),t.value.copy(e.matrix)}function r(t,n){n.color.getRGB(t.fogColor.value,sE(e)),n.isFog?(t.fogNear.value=n.near,t.fogFar.value=n.far):n.isFogExp2&&(t.fogDensity.value=n.density)}function i(e,t,n,r,i){t.isNodeMaterial?t.uniformsNeedUpdate=!1:t.isMeshBasicMaterial?a(e,t):t.isMeshLambertMaterial?(a(e,t),t.envMap&&(e.envMapIntensity.value=t.envMapIntensity)):t.isMeshToonMaterial?(a(e,t),d(e,t)):t.isMeshPhongMaterial?(a(e,t),u(e,t),t.envMap&&(e.envMapIntensity.value=t.envMapIntensity)):t.isMeshStandardMaterial?(a(e,t),f(e,t),t.isMeshPhysicalMaterial&&p(e,t,i)):t.isMeshMatcapMaterial?(a(e,t),m(e,t)):t.isMeshDepthMaterial?a(e,t):t.isMeshDistanceMaterial?(a(e,t),h(e,t)):t.isMeshNormalMaterial?a(e,t):t.isLineBasicMaterial?(o(e,t),t.isLineDashedMaterial&&s(e,t)):t.isPointsMaterial?c(e,t,n,r):t.isSpriteMaterial?l(e,t):t.isShadowMaterial?(e.color.value.copy(t.color),e.opacity.value=t.opacity):t.isShaderMaterial&&(t.uniformsNeedUpdate=!1)}function a(e,r){e.opacity.value=r.opacity,r.color&&e.diffuse.value.copy(r.color),r.emissive&&e.emissive.value.copy(r.emissive).multiplyScalar(r.emissiveIntensity),r.map&&(e.map.value=r.map,n(r.map,e.mapTransform)),r.alphaMap&&(e.alphaMap.value=r.alphaMap,n(r.alphaMap,e.alphaMapTransform)),r.bumpMap&&(e.bumpMap.value=r.bumpMap,n(r.bumpMap,e.bumpMapTransform),e.bumpScale.value=r.bumpScale,r.side===1&&(e.bumpScale.value*=-1)),r.normalMap&&(e.normalMap.value=r.normalMap,n(r.normalMap,e.normalMapTransform),e.normalScale.value.copy(r.normalScale),r.side===1&&e.normalScale.value.negate()),r.displacementMap&&(e.displacementMap.value=r.displacementMap,n(r.displacementMap,e.displacementMapTransform),e.displacementScale.value=r.displacementScale,e.displacementBias.value=r.displacementBias),r.emissiveMap&&(e.emissiveMap.value=r.emissiveMap,n(r.emissiveMap,e.emissiveMapTransform)),r.specularMap&&(e.specularMap.value=r.specularMap,n(r.specularMap,e.specularMapTransform)),r.alphaTest>0&&(e.alphaTest.value=r.alphaTest);let i=t.get(r),a=i.envMap,o=i.envMapRotation;a&&(e.envMap.value=a,e.envMapRotation.value.setFromMatrix4(gA.makeRotationFromEuler(o)).transpose(),a.isCubeTexture&&a.isRenderTargetTexture===!1&&e.envMapRotation.value.premultiply(_A),e.reflectivity.value=r.reflectivity,e.ior.value=r.ior,e.refractionRatio.value=r.refractionRatio),r.lightMap&&(e.lightMap.value=r.lightMap,e.lightMapIntensity.value=r.lightMapIntensity,n(r.lightMap,e.lightMapTransform)),r.aoMap&&(e.aoMap.value=r.aoMap,e.aoMapIntensity.value=r.aoMapIntensity,n(r.aoMap,e.aoMapTransform))}function o(e,t){e.diffuse.value.copy(t.color),e.opacity.value=t.opacity,t.map&&(e.map.value=t.map,n(t.map,e.mapTransform))}function s(e,t){e.dashSize.value=t.dashSize,e.totalSize.value=t.dashSize+t.gapSize,e.scale.value=t.scale}function c(e,t,r,i){e.diffuse.value.copy(t.color),e.opacity.value=t.opacity,e.size.value=t.size*r,e.scale.value=i*.5,t.map&&(e.map.value=t.map,n(t.map,e.uvTransform)),t.alphaMap&&(e.alphaMap.value=t.alphaMap,n(t.alphaMap,e.alphaMapTransform)),t.alphaTest>0&&(e.alphaTest.value=t.alphaTest)}function l(e,t){e.diffuse.value.copy(t.color),e.opacity.value=t.opacity,e.rotation.value=t.rotation,t.map&&(e.map.value=t.map,n(t.map,e.mapTransform)),t.alphaMap&&(e.alphaMap.value=t.alphaMap,n(t.alphaMap,e.alphaMapTransform)),t.alphaTest>0&&(e.alphaTest.value=t.alphaTest)}function u(e,t){e.specular.value.copy(t.specular),e.shininess.value=Math.max(t.shininess,1e-4)}function d(e,t){t.gradientMap&&(e.gradientMap.value=t.gradientMap)}function f(e,t){e.metalness.value=t.metalness,t.metalnessMap&&(e.metalnessMap.value=t.metalnessMap,n(t.metalnessMap,e.metalnessMapTransform)),e.roughness.value=t.roughness,t.roughnessMap&&(e.roughnessMap.value=t.roughnessMap,n(t.roughnessMap,e.roughnessMapTransform)),t.envMap&&(e.envMapIntensity.value=t.envMapIntensity)}function p(e,t,r){e.ior.value=t.ior,t.sheen>0&&(e.sheenColor.value.copy(t.sheenColor).multiplyScalar(t.sheen),e.sheenRoughness.value=t.sheenRoughness,t.sheenColorMap&&(e.sheenColorMap.value=t.sheenColorMap,n(t.sheenColorMap,e.sheenColorMapTransform)),t.sheenRoughnessMap&&(e.sheenRoughnessMap.value=t.sheenRoughnessMap,n(t.sheenRoughnessMap,e.sheenRoughnessMapTransform))),t.clearcoat>0&&(e.clearcoat.value=t.clearcoat,e.clearcoatRoughness.value=t.clearcoatRoughness,t.clearcoatMap&&(e.clearcoatMap.value=t.clearcoatMap,n(t.clearcoatMap,e.clearcoatMapTransform)),t.clearcoatRoughnessMap&&(e.clearcoatRoughnessMap.value=t.clearcoatRoughnessMap,n(t.clearcoatRoughnessMap,e.clearcoatRoughnessMapTransform)),t.clearcoatNormalMap&&(e.clearcoatNormalMap.value=t.clearcoatNormalMap,n(t.clearcoatNormalMap,e.clearcoatNormalMapTransform),e.clearcoatNormalScale.value.copy(t.clearcoatNormalScale),t.side===1&&e.clearcoatNormalScale.value.negate())),t.dispersion>0&&(e.dispersion.value=t.dispersion),t.retroreflectivity>0&&(e.retroreflectivity.value=t.retroreflectivity),t.iridescence>0&&(e.iridescence.value=t.iridescence,e.iridescenceIOR.value=t.iridescenceIOR,e.iridescenceThicknessMinimum.value=t.iridescenceThicknessRange[0],e.iridescenceThicknessMaximum.value=t.iridescenceThicknessRange[1],t.iridescenceMap&&(e.iridescenceMap.value=t.iridescenceMap,n(t.iridescenceMap,e.iridescenceMapTransform)),t.iridescenceThicknessMap&&(e.iridescenceThicknessMap.value=t.iridescenceThicknessMap,n(t.iridescenceThicknessMap,e.iridescenceThicknessMapTransform))),t.transmission>0&&(e.transmission.value=t.transmission,e.transmissionSamplerMap.value=r.texture,e.transmissionSamplerSize.value.set(r.width,r.height),t.transmissionMap&&(e.transmissionMap.value=t.transmissionMap,n(t.transmissionMap,e.transmissionMapTransform)),e.thickness.value=t.thickness,t.thicknessMap&&(e.thicknessMap.value=t.thicknessMap,n(t.thicknessMap,e.thicknessMapTransform)),e.attenuationDistance.value=t.attenuationDistance,e.attenuationColor.value.copy(t.attenuationColor)),t.anisotropy>0&&(e.anisotropyVector.value.set(t.anisotropy*Math.cos(t.anisotropyRotation),t.anisotropy*Math.sin(t.anisotropyRotation)),t.anisotropyMap&&(e.anisotropyMap.value=t.anisotropyMap,n(t.anisotropyMap,e.anisotropyMapTransform))),e.specularIntensity.value=t.specularIntensity,e.specularColor.value.copy(t.specularColor),t.specularColorMap&&(e.specularColorMap.value=t.specularColorMap,n(t.specularColorMap,e.specularColorMapTransform)),t.specularIntensityMap&&(e.specularIntensityMap.value=t.specularIntensityMap,n(t.specularIntensityMap,e.specularIntensityMapTransform))}function m(e,t){t.matcap&&(e.matcap.value=t.matcap)}function h(e,n){let r=t.get(n).light;e.referencePosition.value.setFromMatrixPosition(r.matrixWorld),e.nearDistance.value=r.shadow.camera.near,e.farDistance.value=r.shadow.camera.far}return{refreshFogUniforms:r,refreshMaterialUniforms:i}}function yA(e,t,n,r){let i={},a={},o=[],s=e.getParameter(e.MAX_UNIFORM_BUFFER_BINDINGS);function c(e,t){let n=t.program;r.uniformBlockBinding(e,n)}function l(e,n){let o=i[e.id];o===void 0&&(g(e),o=u(e),i[e.id]=o,e.addEventListener(`dispose`,v));let s=n.program;r.updateUBOMapping(e,s);let c=t.render.frame;a[e.id]!==c&&(f(e),a[e.id]=c)}function u(t){let n=d();t.__bindingPointIndex=n;let r=e.createBuffer(),i=t.__size,a=t.usage;return e.bindBuffer(e.UNIFORM_BUFFER,r),e.bufferData(e.UNIFORM_BUFFER,i,a),e.bindBuffer(e.UNIFORM_BUFFER,null),e.bindBufferBase(e.UNIFORM_BUFFER,n,r),r}function d(){for(let e=0;e<s;e++)if(o.indexOf(e)===-1)return o.push(e),e;return J(`WebGLRenderer: Maximum number of simultaneously usable uniforms groups reached.`),0}function f(t){let n=i[t.id],r=t.uniforms,a=t.__cache;e.bindBuffer(e.UNIFORM_BUFFER,n);for(let e=0,t=r.length;e<t;e++){let t=r[e];if(Array.isArray(t))for(let n=0,r=t.length;n<r;n++)p(t[n],e,n,a);else p(t,e,0,a)}e.bindBuffer(e.UNIFORM_BUFFER,null)}function p(t,n,r,i){if(h(t,n,r,i)===!0){let n=t.__offset,r=t.value;if(Array.isArray(r)){let e=0;for(let n=0;n<r.length;n++){let i=r[n],a=_(i);m(i,t.__data,e),typeof i!=`number`&&typeof i!=`boolean`&&!i.isMatrix3&&!ArrayBuffer.isView(i)&&(e+=a.storage/Float32Array.BYTES_PER_ELEMENT)}}else m(r,t.__data,0);e.bufferSubData(e.UNIFORM_BUFFER,n,t.__data)}}function m(e,t,n){typeof e==`number`||typeof e==`boolean`?t[0]=e:e.isMatrix3?(t[0]=e.elements[0],t[1]=e.elements[1],t[2]=e.elements[2],t[3]=0,t[4]=e.elements[3],t[5]=e.elements[4],t[6]=e.elements[5],t[7]=0,t[8]=e.elements[6],t[9]=e.elements[7],t[10]=e.elements[8],t[11]=0):ArrayBuffer.isView(e)?t.set(new e.constructor(e.buffer,e.byteOffset,t.length)):e.toArray(t,n)}function h(e,t,n,r){let i=e.value,a=t+`_`+n;if(r[a]===void 0)return r[a]=typeof i==`number`||typeof i==`boolean`?i:ArrayBuffer.isView(i)?i.slice():i.clone(),!0;{let e=r[a];if(typeof i==`number`||typeof i==`boolean`){if(e!==i)return r[a]=i,!0}else if(ArrayBuffer.isView(i))return!0;else if(e.equals(i)===!1)return e.copy(i),!0}return!1}function g(e){let t=e.uniforms,n=0;for(let e=0,r=t.length;e<r;e++){let r=Array.isArray(t[e])?t[e]:[t[e]];for(let e=0,t=r.length;e<t;e++){let t=r[e],i=Array.isArray(t.value)?t.value:[t.value];for(let e=0,r=i.length;e<r;e++){let r=i[e],a=_(r),o=n%16,s=o%a.boundary,c=o+s;n+=s,c!==0&&16-c<a.storage&&(n+=16-c),t.__data=new Float32Array(a.storage/Float32Array.BYTES_PER_ELEMENT),t.__offset=n,n+=a.storage}}}let r=n%16;return r>0&&(n+=16-r),e.__size=n,e.__cache={},this}function _(e){let t={boundary:0,storage:0};return typeof e==`number`||typeof e==`boolean`?(t.boundary=4,t.storage=4):e.isVector2?(t.boundary=8,t.storage=8):e.isVector3||e.isColor?(t.boundary=16,t.storage=12):e.isVector4?(t.boundary=16,t.storage=16):e.isMatrix3?(t.boundary=48,t.storage=48):e.isMatrix4?(t.boundary=64,t.storage=64):e.isTexture?q(`WebGLRenderer: Texture samplers can not be part of an uniforms group.`):ArrayBuffer.isView(e)?(t.boundary=16,t.storage=e.byteLength):q(`WebGLRenderer: Unsupported uniform value type.`,e),t}function v(t){let n=t.target;n.removeEventListener(`dispose`,v);let r=o.indexOf(n.__bindingPointIndex);o.splice(r,1),e.deleteBuffer(i[n.id]),delete i[n.id],delete a[n.id]}function y(){for(let t in i)e.deleteBuffer(i[t]);o=[],i={},a={}}return{bind:c,update:l,dispose:y}}var bA=new Uint16Array([12469,15057,12620,14925,13266,14620,13807,14376,14323,13990,14545,13625,14713,13328,14840,12882,14931,12528,14996,12233,15039,11829,15066,11525,15080,11295,15085,10976,15082,10705,15073,10495,13880,14564,13898,14542,13977,14430,14158,14124,14393,13732,14556,13410,14702,12996,14814,12596,14891,12291,14937,11834,14957,11489,14958,11194,14943,10803,14921,10506,14893,10278,14858,9960,14484,14039,14487,14025,14499,13941,14524,13740,14574,13468,14654,13106,14743,12678,14818,12344,14867,11893,14889,11509,14893,11180,14881,10751,14852,10428,14812,10128,14765,9754,14712,9466,14764,13480,14764,13475,14766,13440,14766,13347,14769,13070,14786,12713,14816,12387,14844,11957,14860,11549,14868,11215,14855,10751,14825,10403,14782,10044,14729,9651,14666,9352,14599,9029,14967,12835,14966,12831,14963,12804,14954,12723,14936,12564,14917,12347,14900,11958,14886,11569,14878,11247,14859,10765,14828,10401,14784,10011,14727,9600,14660,9289,14586,8893,14508,8533,15111,12234,15110,12234,15104,12216,15092,12156,15067,12010,15028,11776,14981,11500,14942,11205,14902,10752,14861,10393,14812,9991,14752,9570,14682,9252,14603,8808,14519,8445,14431,8145,15209,11449,15208,11451,15202,11451,15190,11438,15163,11384,15117,11274,15055,10979,14994,10648,14932,10343,14871,9936,14803,9532,14729,9218,14645,8742,14556,8381,14461,8020,14365,7603,15273,10603,15272,10607,15267,10619,15256,10631,15231,10614,15182,10535,15118,10389,15042,10167,14963,9787,14883,9447,14800,9115,14710,8665,14615,8318,14514,7911,14411,7507,14279,7198,15314,9675,15313,9683,15309,9712,15298,9759,15277,9797,15229,9773,15166,9668,15084,9487,14995,9274,14898,8910,14800,8539,14697,8234,14590,7790,14479,7409,14367,7067,14178,6621,15337,8619,15337,8631,15333,8677,15325,8769,15305,8871,15264,8940,15202,8909,15119,8775,15022,8565,14916,8328,14804,8009,14688,7614,14569,7287,14448,6888,14321,6483,14088,6171,15350,7402,15350,7419,15347,7480,15340,7613,15322,7804,15287,7973,15229,8057,15148,8012,15046,7846,14933,7611,14810,7357,14682,7069,14552,6656,14421,6316,14251,5948,14007,5528,15356,5942,15356,5977,15353,6119,15348,6294,15332,6551,15302,6824,15249,7044,15171,7122,15070,7050,14949,6861,14818,6611,14679,6349,14538,6067,14398,5651,14189,5311,13935,4958,15359,4123,15359,4153,15356,4296,15353,4646,15338,5160,15311,5508,15263,5829,15188,6042,15088,6094,14966,6001,14826,5796,14678,5543,14527,5287,14377,4985,14133,4586,13869,4257,15360,1563,15360,1642,15358,2076,15354,2636,15341,3350,15317,4019,15273,4429,15203,4732,15105,4911,14981,4932,14836,4818,14679,4621,14517,4386,14359,4156,14083,3795,13808,3437,15360,122,15360,137,15358,285,15355,636,15344,1274,15322,2177,15281,2765,15215,3223,15120,3451,14995,3569,14846,3567,14681,3466,14511,3305,14344,3121,14037,2800,13753,2467,15360,0,15360,1,15359,21,15355,89,15346,253,15325,479,15287,796,15225,1148,15133,1492,15008,1749,14856,1882,14685,1886,14506,1783,14324,1608,13996,1398,13702,1183]),xA=null;function SA(){return xA===null&&(xA=new WT(bA,16,16,Xx,Lx),xA.name=`DFG_LUT`,xA.minFilter=Dx,xA.magFilter=Dx,xA.wrapS=Sx,xA.wrapT=Sx,xA.generateMipmaps=!1,xA.needsUpdate=!0),xA}var CA=class{constructor(e={}){let{canvas:t=eC(),context:n=null,depth:r=!0,stencil:i=!1,alpha:a=!1,antialias:o=!1,premultipliedAlpha:s=!0,preserveDrawingBuffer:c=!1,powerPreference:l=`default`,failIfMajorPerformanceCaveat:u=!1,reversedDepthBuffer:d=!1,outputBufferType:f=Ax}=e;this.isWebGLRenderer=!0;let p;if(n!==null){if(typeof WebGLRenderingContext<`u`&&n instanceof WebGLRenderingContext)throw Error(`THREE.WebGLRenderer: WebGL 1 is not supported since r163.`);p=n.getContextAttributes().alpha}else p=a;let m=f,h=/* @__PURE__ */ new Set([Qx,Zx,Yx]),g=/* @__PURE__ */ new Set([Ax,Fx,Nx,Bx,Rx,zx]),_=/* @__PURE__ */ new Uint32Array(4),v=/* @__PURE__ */ new Int32Array(4),y=new X,b=null,x=null,S=[],C=[],w=null;this.domElement=t,this.debug={checkShaderErrors:!0,diagnostics:{keywords:!1},onShaderError:null},this.autoClear=!0,this.autoClearColor=!0,this.autoClearDepth=!0,this.autoClearStencil=!0,this.sortObjects=!0,this.clippingPlanes=[],this.localClippingEnabled=!1,this.toneMapping=0,this.toneMappingExposure=1,this.transmissionResolutionScale=1;let T=this,E=!1,D=null,O=null,k=null,A=null;this._outputColorSpace=US;let ee=0,te=0,j=null,ne=-1,re=null,M=new FC,ie=new FC,N=null,ae=new xw(0),oe=0,se=t.width,ce=t.height,le=1,ue=null,de=null,fe=new FC(0,0,se,ce),pe=new FC(0,0,se,ce),me=!1,he=new JT,ge=!1,_e=!1,ve=new BC,ye=new X,be=new FC,xe={background:null,fog:null,environment:null,overrideMaterial:null,isScene:!0},Se=!1;function Ce(){return j===null?le:1}let P=n;function we(e,n){return t.getContext(e,n)}let Te,Ee,F,De,I,L,Oe,ke,Ae,je,Me,Ne,Pe,Fe,Ie,Le,Re,ze,Be,Ve,He,Ue,We;try{let e={alpha:!0,depth:r,stencil:i,antialias:o,premultipliedAlpha:s,preserveDrawingBuffer:c,powerPreference:l,failIfMajorPerformanceCaveat:u};if(`setAttribute`in t&&t.setAttribute(`data-engine`,`three.js r186`),t.addEventListener(`webglcontextlost`,qe,!1),t.addEventListener(`webglcontextrestored`,Je,!1),t.addEventListener(`webglcontextcreationerror`,Ye,!1),P===null){let t=`webgl2`;if(P=we(t,e),P===null)throw we(t)?Error(`THREE.WebGLRenderer: Error creating WebGL context with your selected attributes.`):Error(`THREE.WebGLRenderer: Error creating WebGL context.`)}Ge()}catch(e){throw t.removeEventListener(`webglcontextlost`,qe,!1),t.removeEventListener(`webglcontextrestored`,Je,!1),t.removeEventListener(`webglcontextcreationerror`,Ye,!1),J(`WebGLRenderer: `+e.message),e}function Ge(){Te=new VD(P),Te.init(),He=new dA(P,Te),Ee=new gD(P,Te,e,He),F=new lA(P,Te),Ee.reversedDepthBuffer&&d&&F.buffers.depth.setReversed(!0),O=P.createFramebuffer(),k=P.createFramebuffer(),A=P.createFramebuffer(),De=new WD(P),I=new Uk,L=new uA(P,Te,F,I,Ee,He,De),Oe=new BD(T),ke=new cD(P),Ue=new mD(P,ke),Ae=new HD(P,ke,De,Ue),je=new KD(P,Ae,ke,Ue,De),ze=new GD(P,Ee,L),Ie=new _D(I),Me=new Hk(T,Oe,Te,Ee,Ue,Ie),Ne=new vA(T,I),Pe=new qk,Fe=new eA(Te),Re=new pD(T,Oe,F,je,p,s),Le=new cA(T,je,Ee),We=new yA(P,De,Ee,F),Be=new hD(P,Te,De),Ve=new UD(P,Te,De),De.programs=Me.programs,T.capabilities=Ee,T.extensions=Te,T.properties=I,T.renderLists=Pe,T.shadowMap=Le,T.state=F,T.info=De}m!==1009&&(w=new JD(m,t.width,t.height,o,r,i));let Ke=new hA(T,P);this.xr=Ke,this.getContext=function(){return P},this.getContextAttributes=function(){return P.getContextAttributes()},this.forceContextLoss=function(){let e=Te.get(`WEBGL_lose_context`);e&&e.loseContext()},this.forceContextRestore=function(){let e=Te.get(`WEBGL_lose_context`);e&&e.restoreContext()},this.getPixelRatio=function(){return le},this.setPixelRatio=function(e){e!==void 0&&(le=e,this.setSize(se,ce,!1))},this.getSize=function(e){return e.set(se,ce)},this.setSize=function(e,n,r=!0){if(Ke.isPresenting){q(`WebGLRenderer: Can't change size while VR device is presenting.`);return}se=e,ce=n,t.width=Math.floor(e*le),t.height=Math.floor(n*le),r===!0&&(t.style.width=e+`px`,t.style.height=n+`px`),w!==null&&w.setSize(t.width,t.height),this.setViewport(0,0,e,n)},this.getDrawingBufferSize=function(e){return e.set(se*le,ce*le).floor()},this.setDrawingBufferSize=function(e,n,r){se=e,ce=n,le=r,t.width=Math.floor(e*r),t.height=Math.floor(n*r),this.setViewport(0,0,e,n)},this.setEffects=function(e){if(m===1009){J(`WebGLRenderer: setEffects() requires outputBufferType set to HalfFloatType or FloatType.`);return}if(e){for(let t=0;t<e.length;t++)if(e[t].isOutputPass===!0){q(`WebGLRenderer: OutputPass is not needed in setEffects(). Tone mapping and color space conversion are applied automatically.`);break}}w.setEffects(e||[])},this.getCurrentViewport=function(e){return e.copy(M)},this.getViewport=function(e){return e.copy(fe)},this.setViewport=function(e,t,n,r){e.isVector4?fe.set(e.x,e.y,e.z,e.w):fe.set(e,t,n,r),F.viewport(M.copy(fe).multiplyScalar(le).round())},this.getScissor=function(e){return e.copy(pe)},this.setScissor=function(e,t,n,r){e.isVector4?pe.set(e.x,e.y,e.z,e.w):pe.set(e,t,n,r),F.scissor(ie.copy(pe).multiplyScalar(le).round())},this.getScissorTest=function(){return me},this.setScissorTest=function(e){F.setScissorTest(me=e)},this.setOpaqueSort=function(e){ue=e},this.setTransparentSort=function(e){de=e},this.getClearColor=function(e){return e.copy(Re.getClearColor())},this.setClearColor=function(){Re.setClearColor(...arguments)},this.getClearAlpha=function(){return Re.getClearAlpha()},this.setClearAlpha=function(){Re.setClearAlpha(...arguments)},this.clear=function(e=!0,t=!0,n=!0){let r=0;if(e){let e=!1;if(j!==null){let t=j.texture.format;e=h.has(t)}if(e){let e=j.texture.type,t=g.has(e),n=Re.getClearColor(),r=Re.getClearAlpha(),i=n.r,a=n.g,o=n.b;t?(_[0]=i,_[1]=a,_[2]=o,_[3]=r,P.clearBufferuiv(P.COLOR,0,_)):(v[0]=i,v[1]=a,v[2]=o,v[3]=r,P.clearBufferiv(P.COLOR,0,v))}else r|=P.COLOR_BUFFER_BIT}t&&(r|=P.DEPTH_BUFFER_BIT,this.state.buffers.depth.setMask(!0)),n&&(r|=P.STENCIL_BUFFER_BIT,this.state.buffers.stencil.setMask(4294967295)),r!==0&&P.clear(r)},this.clearColor=function(){this.clear(!0,!1,!1)},this.clearDepth=function(){this.clear(!1,!0,!1)},this.clearStencil=function(){this.clear(!1,!1,!0)},this.setNodesHandler=function(e){e.setRenderer(this),D=e},this.dispose=function(){t.removeEventListener(`webglcontextlost`,qe,!1),t.removeEventListener(`webglcontextrestored`,Je,!1),t.removeEventListener(`webglcontextcreationerror`,Ye,!1),Re.dispose(),Pe.dispose(),Fe.dispose(),I.dispose(),Oe.dispose(),je.dispose(),Ue.dispose(),We.dispose(),Me.dispose(),Ke.dispose(),Ke.removeEventListener(`sessionstart`,nt),Ke.removeEventListener(`sessionend`,rt),it.stop()};function qe(e){e.preventDefault(),nC(`WebGLRenderer: Context Lost.`),E=!0}function Je(){nC(`WebGLRenderer: Context Restored.`),E=!1;let e=De.autoReset,t=Le.enabled,n=Le.autoUpdate,r=Le.needsUpdate,i=Le.type;Ge(),De.autoReset=e,Le.enabled=t,Le.autoUpdate=n,Le.needsUpdate=r,Le.type=i}function Ye(e){J(`WebGLRenderer: A WebGL context could not be created. Reason: `,e.statusMessage)}function Xe(e){let t=e.target;t.removeEventListener(`dispose`,Xe),Ze(t)}function Ze(e){Qe(e),I.remove(e)}function Qe(e){let t=I.get(e).programs;t!==void 0&&(t.forEach(function(e){Me.releaseProgram(e)}),e.isShaderMaterial&&Me.releaseShaderCache(e))}this.renderBufferDirect=function(e,t,n,r,i,a){t===null&&(t=xe);let o=i.isMesh&&i.matrixWorld.determinantAffine()<0,s=R(e,t,n,r,i);F.setMaterial(r,o);let c=n.index,l=1;if(r.wireframe===!0){if(c=Ae.getWireframeAttribute(n),c===void 0)return;l=2}let u=n.drawRange,d=n.attributes.position,f=u.start*l,p=(u.start+u.count)*l;a!==null&&(f=Math.max(f,a.start*l),p=Math.min(p,(a.start+a.count)*l)),c===null?d!=null&&(f=Math.max(f,0),p=Math.min(p,d.count)):(f=Math.max(f,0),p=Math.min(p,c.count));let m=p-f;if(m<0||m===1/0)return;Ue.setup(i,r,s,n,c);let h,g=Be;if(c!==null&&(h=ke.get(c),g=Ve,g.setIndex(h)),i.isMesh)r.wireframe===!0?(F.setLineWidth(r.wireframeLinewidth*Ce()),g.setMode(P.LINES)):g.setMode(P.TRIANGLES);else if(i.isLine){let e=r.linewidth;e===void 0&&(e=1),F.setLineWidth(e*Ce()),i.isLineSegments?g.setMode(P.LINES):i.isLineLoop?g.setMode(P.LINE_LOOP):g.setMode(P.LINE_STRIP)}else i.isPoints?g.setMode(P.POINTS):i.isSprite&&g.setMode(P.TRIANGLES);if(i.isBatchedMesh){if(Te.get(`WEBGL_multi_draw`))g.renderMultiDraw(i._multiDrawStarts,i._multiDrawCounts,i._multiDrawCount);else{let e=i._multiDrawStarts,t=i._multiDrawCounts,n=i._multiDrawCount,a=c?ke.get(c).bytesPerElement:1,o=I.get(r).currentProgram.getUniforms();for(let r=0;r<n;r++)o.setValue(P,`_gl_DrawID`,r),g.render(e[r]/a,t[r])}}else if(i.isInstancedMesh)g.renderInstances(f,m,i.count);else if(n.isInstancedBufferGeometry){let e=n._maxInstanceCount===void 0?1/0:n._maxInstanceCount,t=Math.min(n.instanceCount,e);g.renderInstances(f,m,t)}else g.render(f,m)};function $e(e,t,n,r){D!==null&&e.isNodeMaterial&&D.setObject(r,e),ge===!0&&Ie.setState(e,n,!1),e.transparent===!0&&e.side===2&&e.forceSinglePass===!1?(e.side=1,e.needsUpdate=!0,ut(e,t,r),e.side=0,e.needsUpdate=!0,ut(e,t,r),e.side=2):ut(e,t,r)}this.compile=function(e,t,n=null){n===null&&(n=e),D!==null&&D.renderStart(e,t,n),x=Fe.get(n),x.init(t),C.push(x),n.traverseVisible(function(e){e.isLight&&e.layers.test(t.layers)&&(x.pushLight(e),e.castShadow&&x.pushShadow(e))}),e!==n&&e.traverseVisible(function(e){e.isLight&&e.layers.test(t.layers)&&(x.pushLight(e),e.castShadow&&x.pushShadow(e))}),x.setupLights(),D!==null&&D.updateLights(x.state.lightsArray),_e=this.localClippingEnabled,ge=Ie.init(this.clippingPlanes,_e),ge===!0&&Ie.setGlobalState(this.clippingPlanes,t),D!==null&&Le.render(x.state.shadowsArray,n,t);let r=/* @__PURE__ */ new Set;return e.traverse(function(e){if(!(e.isMesh||e.isPoints||e.isLine||e.isSprite))return;let i=e.material;if(i){if(Array.isArray(i))for(let a=0;a<i.length;a++){let o=i[a];$e(o,n,t,e),r.add(o)}else $e(i,n,t,e),r.add(i)}}),x=C.pop(),D!==null&&D.renderEnd(),r},this.compileAsync=function(e,t,n=null){let r=this.compile(e,t,n);return new Promise(t=>{function n(){if(r.forEach(function(e){let t=I.get(e).currentProgram;(t===void 0||t.isReady())&&r.delete(e)}),r.size===0){t(e);return}setTimeout(n,10)}Te.get(`KHR_parallel_shader_compile`)===null?setTimeout(n,10):n()})};let et=null;function tt(e){et&&et(e)}function nt(){it.stop()}function rt(){it.start()}let it=new sD;it.setAnimationLoop(tt),typeof self<`u`&&it.setContext(self),this.setAnimationLoop=function(e){et=e,Ke.setAnimationLoop(e),e===null?it.stop():it.start()},Ke.addEventListener(`sessionstart`,nt),Ke.addEventListener(`sessionend`,rt),this.render=function(e,t){if(t!==void 0&&t.isCamera!==!0){J(`WebGLRenderer.render: camera is not an instance of THREE.Camera.`);return}if(E===!0)return;D!==null&&D.renderStart(e,t);let n=Ke.enabled===!0&&Ke.isPresenting===!0,r=w!==null&&(j===null||n)&&w.begin(T,j);if(e.matrixWorldAutoUpdate===!0&&e.updateMatrixWorld(),t.parent===null&&t.matrixWorldAutoUpdate===!0&&t.updateMatrixWorld(),Ke.enabled===!0&&Ke.isPresenting===!0&&(w===null||w.isCompositing()===!1)&&(Ke.cameraAutoUpdate===!0&&Ke.updateCamera(t),t=Ke.getCamera()),e.isScene===!0&&e.onBeforeRender(T,e,t,j),x=Fe.get(e,C.length),x.init(t),x.state.textureUnits=L.getTextureUnits(),C.push(x),ve.multiplyMatrices(t.projectionMatrix,t.matrixWorldInverse),he.setFromProjectionMatrix(ve,XS,t.reversedDepth),_e=this.localClippingEnabled,ge=Ie.init(this.clippingPlanes,_e),b=Pe.get(e,S.length),b.init(),S.push(b),Ke.enabled===!0&&Ke.isPresenting===!0){let e=T.xr.getDepthSensingMesh();e!==null&&at(e,t,-1/0,T.sortObjects)}at(e,t,0,T.sortObjects),b.finish(),D!==null&&D.updateLights(x.state.lightsArray),T.sortObjects===!0&&b.sort(ue,de),Se=Ke.enabled===!1||Ke.isPresenting===!1||Ke.hasDepthSensing()===!1,Se&&Re.addToRenderList(b,e),this.info.render.frame++,this.info.autoReset===!0&&this.info.reset(),ge===!0&&Ie.beginShadows();let i=x.state.shadowsArray;if(Le.render(i,e,t),ge===!0&&Ie.endShadows(),(r&&w.hasRenderPass())===!1){let n=b.opaque,r=b.transmissive;if(x.setupLights(),t.isArrayCamera){let i=t.cameras;if(r.length>0)for(let t=0,a=i.length;t<a;t++){let a=i[t];st(n,r,e,a)}Se&&Re.render(e);for(let t=0,n=i.length;t<n;t++){let n=i[t];ot(b,e,n,n.viewport)}}else r.length>0&&st(n,r,e,t),Se&&Re.render(e),ot(b,e,t)}j!==null&&te===0&&(L.updateMultisampleRenderTarget(j),L.updateRenderTargetMipmap(j)),r&&w.end(T),e.isScene===!0&&e.onAfterRender(T,e,t),Ue.resetDefaultState(),ne=-1,re=null,C.pop(),C.length>0?(x=C[C.length-1],L.setTextureUnits(x.state.textureUnits),ge===!0&&Ie.setGlobalState(T.clippingPlanes,x.state.camera)):x=null,S.pop(),b=S.length>0?S[S.length-1]:null,D!==null&&D.renderEnd()};function at(e,t,n,r){if(e.visible===!1)return;if(e.layers.test(t.layers)){if(e.isGroup)n=e.renderOrder;else if(e.isLOD)e.autoUpdate===!0&&e.update(t);else if(e.isLightProbeGrid)x.pushLightProbeGrid(e);else if(e.isLight)x.pushLight(e),e.castShadow&&x.pushShadow(e);else if(e.isSprite){if(!e.frustumCulled||e.intersectsFrustum(he)){r&&be.setFromMatrixPosition(e.matrixWorld).applyMatrix4(ve);let i=je.update(e),a=e.material;a.visible&&b.push(e,i,a,n,be.z,null,t)}}else if((e.isMesh||e.isLine||e.isPoints)&&(!e.frustumCulled||e.intersectsFrustum(he))){let i=je.update(e),a=e.material;if(r&&(e.boundingSphere===void 0?(i.boundingSphere===null&&i.computeBoundingSphere(),be.copy(i.boundingSphere.center)):(e.boundingSphere===null&&e.computeBoundingSphere(),be.copy(e.boundingSphere.center)),be.applyMatrix4(e.matrixWorld).applyMatrix4(ve)),Array.isArray(a)){let r=i.groups;for(let o=0,s=r.length;o<s;o++){let s=r[o],c=a[s.materialIndex];c&&c.visible&&b.push(e,i,c,n,be.z,s,t)}}else a.visible&&b.push(e,i,a,n,be.z,null,t)}}let i=e.children;for(let e=0,a=i.length;e<a;e++)at(i[e],t,n,r)}function ot(e,t,n,r){let{opaque:i,transmissive:a,transparent:o}=e;x.setupLightsView(n),ge===!0&&Ie.setGlobalState(T.clippingPlanes,n),r&&F.viewport(M.copy(r)),i.length>0&&ct(i,t,n),a.length>0&&ct(a,t,n),o.length>0&&ct(o,t,n),F.buffers.depth.setTest(!0),F.buffers.depth.setMask(!0),F.buffers.color.setMask(!0),F.setPolygonOffset(!1)}function st(e,t,n,r){if((n.isScene===!0?n.overrideMaterial:null)!==null)return;if(x.state.transmissionRenderTarget[r.id]===void 0){let e=Te.has(`EXT_color_buffer_half_float`)||Te.has(`EXT_color_buffer_float`);x.state.transmissionRenderTarget[r.id]=new LC(1,1,{generateMipmaps:!0,type:e?Lx:Ax,minFilter:kx,samples:Math.max(4,Ee.samples),stencilBuffer:i,resolveDepthBuffer:!1,resolveStencilBuffer:!1,storeMultisampledDepthBuffer:!1,storeMultisampledStencilBuffer:!1,colorSpace:wC.workingColorSpace})}let a=x.state.transmissionRenderTarget[r.id],o=r.viewport||M;a.setSize(o.z*T.transmissionResolutionScale,o.w*T.transmissionResolutionScale);let s=T.getRenderTarget(),c=T.getActiveCubeFace(),l=T.getActiveMipmapLevel();T.setRenderTarget(a),T.getClearColor(ae),oe=T.getClearAlpha(),oe<1&&T.setClearColor(16777215,.5),T.clear(),Se&&Re.render(n);let u=T.toneMapping;T.toneMapping=0;let d=r.viewport;if(r.viewport!==void 0&&(r.viewport=void 0),x.setupLightsView(r),ge===!0&&Ie.setGlobalState(T.clippingPlanes,r),ct(e,n,r),L.updateMultisampleRenderTarget(a),L.updateRenderTargetMipmap(a),Te.has(`WEBGL_multisampled_render_to_texture`)===!1){let e=!1;for(let i=0,a=t.length;i<a;i++){let{object:a,geometry:o,material:s,group:c}=t[i];if(s.side===2&&a.layers.test(r.layers)){let t=s.side;s.side=1,s.needsUpdate=!0,lt(a,n,r,o,s,c),s.side=t,s.needsUpdate=!0,e=!0}}e===!0&&(L.updateMultisampleRenderTarget(a),L.updateRenderTargetMipmap(a))}T.setRenderTarget(s,c,l),T.setClearColor(ae,oe),d!==void 0&&(r.viewport=d),T.toneMapping=u}function ct(e,t,n){let r=t.isScene===!0?t.overrideMaterial:null;for(let i=0,a=e.length;i<a;i++){let a=e[i],{object:o,geometry:s,group:c}=a,l=a.material;l.allowOverride===!0&&r!==null&&(l=r),o.layers.test(n.layers)&<(o,t,n,s,l,c)}}function lt(e,t,n,r,i,a){D!==null&&i.isNodeMaterial&&D.setObject(e,i),e.onBeforeRender(T,t,n,r,i,a),e.modelViewMatrix.multiplyMatrices(n.matrixWorldInverse,e.matrixWorld),e.normalMatrix.getNormalMatrix(e.modelViewMatrix),i.onBeforeRender(T,t,n,r,e,a),i.transparent===!0&&i.side===2&&i.forceSinglePass===!1?(i.side=1,i.needsUpdate=!0,T.renderBufferDirect(n,t,r,i,e,a),i.side=0,i.needsUpdate=!0,T.renderBufferDirect(n,t,r,i,e,a),i.side=2):T.renderBufferDirect(n,t,r,i,e,a),e.onAfterRender(T,t,n,r,i,a)}function ut(e,t,n){t.isScene!==!0&&(t=xe);let r=I.get(e),i=x.state.lights,a=x.state.shadowsArray,o=i.state.version,s=Me.getParameters(e,i.state,a,t,n,x.state.lightProbeGridArray),c=Me.getProgramCacheKey(s),l=r.programs;r.environment=e.isMeshStandardMaterial||e.isMeshLambertMaterial||e.isMeshPhongMaterial?t.environment:null,r.fog=t.fog;let u=e.isMeshStandardMaterial||e.isMeshLambertMaterial&&!e.envMap||e.isMeshPhongMaterial&&!e.envMap;r.envMap=Oe.get(e.envMap||r.environment,u),r.envMapRotation=r.environment!==null&&e.envMap===null?t.environmentRotation:e.envMapRotation,l===void 0&&(e.addEventListener(`dispose`,Xe),l=/* @__PURE__ */ new Map,r.programs=l);let d=l.get(c);if(d!==void 0){if(r.currentProgram===d&&r.lightsStateVersion===o)return ft(e,s),d}else s.uniforms=Me.getUniforms(e),D!==null&&e.isNodeMaterial&&D.build(e,n,s),e.onBeforeCompile(s,T),d=Me.acquireProgram(s,c),l.set(c,d),r.uniforms=s.uniforms;let f=r.uniforms;return(!e.isShaderMaterial&&!e.isRawShaderMaterial||e.clipping===!0)&&(f.clippingPlanes=Ie.uniform),ft(e,s),r.needsLights=ht(e),r.lightsStateVersion=o,r.needsLights&&(f.ambientLightColor.value=i.state.ambient,f.lightProbe.value=i.state.probe,f.sunLights.value=i.state.sun,f.sunLightShadows.value=i.state.sunShadow,f.directionalLights.value=i.state.directional,f.directionalLightShadows.value=i.state.directionalShadow,f.spotLights.value=i.state.spot,f.spotLightShadows.value=i.state.spotShadow,f.rectAreaLights.value=i.state.rectArea,f.ltc_1.value=i.state.rectAreaLTC1,f.ltc_2.value=i.state.rectAreaLTC2,f.pointLights.value=i.state.point,f.pointLightShadows.value=i.state.pointShadow,f.hemisphereLights.value=i.state.hemi,f.sunShadowMatrix.value=i.state.sunShadowMatrix,f.sunShadowCascade.value=i.state.sunShadowCascade,f.directionalShadowMatrix.value=i.state.directionalShadowMatrix,f.spotLightMatrix.value=i.state.spotLightMatrix,f.spotLightMap.value=i.state.spotLightMap,f.pointShadowMatrix.value=i.state.pointShadowMatrix),r.lightProbeGrid=x.state.lightProbeGridArray.length>0,r.currentProgram=d,r.uniformsList=null,d}function dt(e){if(e.uniformsList===null){let t=e.currentProgram.getUniforms();e.uniformsList=tk.seqWithValue(t.seq,e.uniforms)}return e.uniformsList}function ft(e,t){let n=I.get(e);n.outputColorSpace=t.outputColorSpace,n.batching=t.batching,n.batchingColor=t.batchingColor,n.instancing=t.instancing,n.instancingColor=t.instancingColor,n.instancingMorph=t.instancingMorph,n.skinning=t.skinning,n.morphTargets=t.morphTargets,n.morphNormals=t.morphNormals,n.morphColors=t.morphColors,n.morphTargetsCount=t.morphTargetsCount,n.numClippingPlanes=t.numClippingPlanes,n.numIntersection=t.numClipIntersection,n.vertexAlphas=t.vertexAlphas,n.vertexTangents=t.vertexTangents,n.toneMapping=t.toneMapping}function pt(e,t){if(e.length===0)return null;if(e.length===1)return e[0].texture===null?null:e[0];y.setFromMatrixPosition(t.matrixWorld);for(let t=0,n=e.length;t<n;t++){let n=e[t];if(n.texture!==null&&n.boundingBox.containsPoint(y))return n}return null}function R(e,t,n,r,i){t.isScene!==!0&&(t=xe),L.resetTextureUnits();let a=t.fog,o=r.isMeshStandardMaterial||r.isMeshLambertMaterial||r.isMeshPhongMaterial?t.environment:null,s=j===null?T.outputColorSpace:j.isXRRenderTarget===!0?j.texture.colorSpace:wC.workingColorSpace,c=r.isMeshStandardMaterial||r.isMeshLambertMaterial&&!r.envMap||r.isMeshPhongMaterial&&!r.envMap,l=Oe.get(r.envMap||o,c),u=r.vertexColors===!0&&!!n.attributes.color&&n.attributes.color.itemSize===4,d=!!n.attributes.tangent&&(!!r.normalMap||r.anisotropy>0),f=!!n.morphAttributes.position,p=!!n.morphAttributes.normal,m=!!n.morphAttributes.color,h=0;r.toneMapped&&(j===null||j.isXRRenderTarget===!0)&&(h=T.toneMapping);let g=n.morphAttributes.position||n.morphAttributes.normal||n.morphAttributes.color,_=g===void 0?0:g.length,v=I.get(r),y=x.state.lights;if(ge===!0&&(_e===!0||e!==re)){let t=e===re&&r.id===ne;Ie.setState(r,e,t)}let b=!1;r.version===v.__version?v.needsLights&&v.lightsStateVersion!==y.state.version?b=!0:v.outputColorSpace===s?i.isBatchedMesh&&v.batching===!1||!i.isBatchedMesh&&v.batching===!0||i.isBatchedMesh&&v.batchingColor===!0&&i._colorsTexture===null||i.isBatchedMesh&&v.batchingColor===!1&&i._colorsTexture!==null||i.isInstancedMesh&&v.instancing===!1||!i.isInstancedMesh&&v.instancing===!0||i.isSkinnedMesh&&v.skinning===!1||!i.isSkinnedMesh&&v.skinning===!0||i.isInstancedMesh&&v.instancingColor===!0&&i.instanceColor===null||i.isInstancedMesh&&v.instancingColor===!1&&i.instanceColor!==null||i.isInstancedMesh&&v.instancingMorph===!0&&i.morphTexture===null||i.isInstancedMesh&&v.instancingMorph===!1&&i.morphTexture!==null?b=!0:v.envMap===l?r.fog===!0&&v.fog!==a||v.numClippingPlanes!==void 0&&(v.numClippingPlanes!==Ie.numPlanes||v.numIntersection!==Ie.numIntersection)?b=!0:v.vertexAlphas===u&&v.vertexTangents===d&&v.morphTargets===f&&v.morphNormals===p&&v.morphColors===m&&v.toneMapping===h&&v.morphTargetsCount===_?!!v.lightProbeGrid!=x.state.lightProbeGridArray.length>0&&(b=!0):b=!0:b=!0:b=!0:(b=!0,v.__version=r.version);let S=v.currentProgram;b===!0&&(S=ut(r,t,i),D&&r.isNodeMaterial&&D.onUpdateProgram(r,S,v));let C=!1,w=!1,E=!1,O=S.getUniforms(),k=v.uniforms;if(F.useProgram(S.program)&&(C=!0,w=!0,E=!0),r.id!==ne&&(ne=r.id,w=!0),v.needsLights){let e=pt(x.state.lightProbeGridArray,i);v.lightProbeGrid!==e&&(v.lightProbeGrid=e,w=!0)}if(C||re!==e){F.buffers.depth.getReversed()&&e.reversedDepth!==!0&&(e._reversedDepth=!0,e.updateProjectionMatrix()),O.setValue(P,`projectionMatrix`,e.projectionMatrix),O.setValue(P,`viewMatrix`,e.matrixWorldInverse);let t=O.map.cameraPosition;t!==void 0&&t.setValue(P,ye.setFromMatrixPosition(e.matrixWorld)),Ee.logarithmicDepthBuffer&&O.setValue(P,`logDepthBufFC`,2/(Math.log(e.far+1)/Math.LN2)),(r.isMeshPhongMaterial||r.isMeshToonMaterial||r.isMeshLambertMaterial||r.isMeshBasicMaterial||r.isMeshStandardMaterial||r.isShaderMaterial)&&O.setValue(P,`isOrthographic`,e.isOrthographicCamera===!0),re!==e&&(re=e,w=!0,E=!0)}if(v.needsLights&&(y.state.sunShadowMap.length>0&&O.setValue(P,`sunShadowMap`,y.state.sunShadowMap,L),y.state.directionalShadowMap.length>0&&O.setValue(P,`directionalShadowMap`,y.state.directionalShadowMap,L),y.state.spotShadowMap.length>0&&O.setValue(P,`spotShadowMap`,y.state.spotShadowMap,L),y.state.pointShadowMap.length>0&&O.setValue(P,`pointShadowMap`,y.state.pointShadowMap,L)),i.isSkinnedMesh){O.setOptional(P,i,`bindMatrix`),O.setOptional(P,i,`bindMatrixInverse`);let e=i.skeleton;e&&(e.boneTexture===null&&e.computeBoneTexture(),O.setValue(P,`boneTexture`,e.boneTexture,L))}i.isBatchedMesh&&(O.setOptional(P,i,`batchingTexture`),O.setValue(P,`batchingTexture`,i._matricesTexture,L),O.setOptional(P,i,`batchingIdTexture`),O.setValue(P,`batchingIdTexture`,i._indirectTexture,L),O.setOptional(P,i,`batchingColorTexture`),i._colorsTexture!==null&&O.setValue(P,`batchingColorTexture`,i._colorsTexture,L));let A=n.morphAttributes;if((A.position!==void 0||A.normal!==void 0||A.color!==void 0)&&ze.update(i,n,S),(w||v.receiveShadow!==i.receiveShadow)&&(v.receiveShadow=i.receiveShadow,O.setValue(P,`receiveShadow`,i.receiveShadow)),(r.isMeshStandardMaterial||r.isMeshLambertMaterial||r.isMeshPhongMaterial)&&r.envMap===null&&t.environment!==null&&(k.envMapIntensity.value=t.environmentIntensity),k.dfgLUT!==void 0&&(k.dfgLUT.value=SA()),w){if(O.setValue(P,`toneMappingExposure`,T.toneMappingExposure),v.needsLights&&mt(k,E),a&&r.fog===!0&&Ne.refreshFogUniforms(k,a),Ne.refreshMaterialUniforms(k,r,le,ce,x.state.transmissionRenderTarget[e.id]),v.needsLights&&v.lightProbeGrid){let e=v.lightProbeGrid;k.probesSH.value=e.texture,k.probesMin.value.copy(e.boundingBox.min),k.probesMax.value.copy(e.boundingBox.max),k.probesResolution.value.copy(e.resolution)}tk.upload(P,dt(v),k,L)}if(r.isShaderMaterial&&r.uniformsNeedUpdate===!0&&(tk.upload(P,dt(v),k,L),r.uniformsNeedUpdate=!1),r.isSpriteMaterial&&O.setValue(P,`center`,i.center),O.setValue(P,`modelViewMatrix`,i.modelViewMatrix),O.setValue(P,`normalMatrix`,i.normalMatrix),O.setValue(P,`modelMatrix`,i.matrixWorld),r.uniformsGroups!==void 0){let e=r.uniformsGroups;for(let t=0,n=e.length;t<n;t++){let n=e[t];We.update(n,S),We.bind(n,S)}}return S}function mt(e,t){e.ambientLightColor.needsUpdate=t,e.lightProbe.needsUpdate=t,e.sunLights.needsUpdate=t,e.sunLightShadows.needsUpdate=t,e.directionalLights.needsUpdate=t,e.directionalLightShadows.needsUpdate=t,e.pointLights.needsUpdate=t,e.pointLightShadows.needsUpdate=t,e.spotLights.needsUpdate=t,e.spotLightShadows.needsUpdate=t,e.rectAreaLights.needsUpdate=t,e.hemisphereLights.needsUpdate=t}function ht(e){return e.isMeshLambertMaterial||e.isMeshToonMaterial||e.isMeshPhongMaterial||e.isMeshStandardMaterial||e.isShadowMaterial||e.isShaderMaterial&&e.lights===!0}this.getActiveCubeFace=function(){return ee},this.getActiveMipmapLevel=function(){return te},this.getRenderTarget=function(){return j},this.setRenderTargetTextures=function(e,t,n){let r=I.get(e);r.__autoAllocateDepthBuffer=e.resolveDepthBuffer===!1,r.__autoAllocateDepthBuffer===!1&&(r.__useRenderToTexture=!1),I.get(e.texture).__webglTexture=t,I.get(e.depthTexture).__webglTexture=r.__autoAllocateDepthBuffer?void 0:n,r.__hasExternalTextures=!0},this.setRenderTargetFramebuffer=function(e,t){let n=I.get(e);n.__webglFramebuffer=t,n.__useDefaultFramebuffer=t===void 0},this.setRenderTarget=function(e,t=0,n=0){j=e,ee=t,te=n;let r=null,i=!1,a=!1;if(e){let o=I.get(e);if(o.__useDefaultFramebuffer!==void 0){F.bindFramebuffer(P.FRAMEBUFFER,o.__webglFramebuffer),M.copy(e.viewport),ie.copy(e.scissor),N=e.scissorTest,F.viewport(M),F.scissor(ie),F.setScissorTest(N),ne=-1;return}if(o.__webglFramebuffer===void 0)L.setupRenderTarget(e);else if(o.__hasExternalTextures)L.rebindTextures(e,I.get(e.texture).__webglTexture,I.get(e.depthTexture).__webglTexture);else if(e.depthBuffer){let t=e.depthTexture;if(o.__boundDepthTexture!==t){if(t!==null&&I.has(t)&&(e.width!==t.image.width||e.height!==t.image.height))throw Error(`THREE.WebGLRenderer: Attached DepthTexture is initialized to the incorrect size.`);L.setupDepthRenderbuffer(e)}}let s=e.texture;(s.isData3DTexture||s.isDataArrayTexture||s.isCompressedArrayTexture)&&(a=!0);let c=I.get(e).__webglFramebuffer;e.isWebGLCubeRenderTarget?(r=Array.isArray(c[t])?c[t][n]:c[t],i=!0):r=e.samples>0&&L.useMultisampledRTT(e)===!1?I.get(e).__webglMultisampledFramebuffer:Array.isArray(c)?c[n]:c,M.copy(e.viewport),ie.copy(e.scissor),N=e.scissorTest}else M.copy(fe).multiplyScalar(le).floor(),ie.copy(pe).multiplyScalar(le).floor(),N=me;if(n!==0&&(r=O),F.bindFramebuffer(P.FRAMEBUFFER,r)&&F.drawBuffers(e,r),F.viewport(M),F.scissor(ie),F.setScissorTest(N),i){let r=I.get(e.texture);P.framebufferTexture2D(P.FRAMEBUFFER,P.COLOR_ATTACHMENT0,P.TEXTURE_CUBE_MAP_POSITIVE_X+t,r.__webglTexture,n)}else if(a){let r=t;for(let t=0;t<e.textures.length;t++){let i=I.get(e.textures[t]);P.framebufferTextureLayer(P.FRAMEBUFFER,P.COLOR_ATTACHMENT0+t,i.__webglTexture,n,r)}}else if(e!==null&&n!==0){let t=I.get(e.texture);P.framebufferTexture2D(P.FRAMEBUFFER,P.COLOR_ATTACHMENT0,P.TEXTURE_2D,t.__webglTexture,n)}ne=-1};function gt(e){let t=I.get(e);return(t.__readFormat!==e.format||t.__readType!==e.type)&&(t.__readFormat=e.format,t.__readType=e.type,t.__formatReadable=Ee.textureFormatReadable(e.format),t.__typeReadable=Ee.textureTypeReadable(e.type)),t}this.readRenderTargetPixels=function(e,t,n,r,i,a,o,s=0){if(!(e&&e.isWebGLRenderTarget)){J(`WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.`);return}let c=I.get(e).__webglFramebuffer;if(e.isWebGLCubeRenderTarget&&o!==void 0&&(c=c[o]),c){F.bindFramebuffer(P.FRAMEBUFFER,c);try{let o=e.textures[s],c=o.format,l=o.type;e.textures.length>1&&P.readBuffer(P.COLOR_ATTACHMENT0+s);let u=gt(o);if(u.__formatReadable===!1){J(`WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.`);return}if(u.__typeReadable===!1){J(`WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.`);return}t>=0&&t<=e.width-r&&n>=0&&n<=e.height-i&&P.readPixels(t,n,r,i,He.convert(c),He.convert(l),a)}finally{let e=j===null?null:I.get(j).__webglFramebuffer;F.bindFramebuffer(P.FRAMEBUFFER,e)}}},this.readRenderTargetPixelsAsync=async function(e,t,n,r,i,a,o,s=0){if(!(e&&e.isWebGLRenderTarget))throw Error(`THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.`);let c=I.get(e).__webglFramebuffer;if(e.isWebGLCubeRenderTarget&&o!==void 0&&(c=c[o]),c){if(t>=0&&t<=e.width-r&&n>=0&&n<=e.height-i){F.bindFramebuffer(P.FRAMEBUFFER,c);let o=e.textures[s],l=o.format,u=o.type;e.textures.length>1&&P.readBuffer(P.COLOR_ATTACHMENT0+s);let d=gt(o);if(d.__formatReadable===!1)throw Error(`THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in RGBA or implementation defined format.`);if(d.__typeReadable===!1)throw Error(`THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in UnsignedByteType or implementation defined type.`);let f=P.createBuffer();P.bindBuffer(P.PIXEL_PACK_BUFFER,f),P.bufferData(P.PIXEL_PACK_BUFFER,a.byteLength,P.STREAM_READ),P.readPixels(t,n,r,i,He.convert(l),He.convert(u),0),P.bindBuffer(P.PIXEL_PACK_BUFFER,null);let p=j===null?null:I.get(j).__webglFramebuffer;F.bindFramebuffer(P.FRAMEBUFFER,p);let m=P.fenceSync(P.SYNC_GPU_COMMANDS_COMPLETE,0);return P.flush(),await aC(P,m,4),P.bindBuffer(P.PIXEL_PACK_BUFFER,f),P.getBufferSubData(P.PIXEL_PACK_BUFFER,0,a),P.bindBuffer(P.PIXEL_PACK_BUFFER,null),P.deleteBuffer(f),P.deleteSync(m),a}throw Error(`THREE.WebGLRenderer.readRenderTargetPixelsAsync: requested read bounds are out of range.`)}},this.copyFramebufferToTexture=function(e,t=null,n=0){let r=2**-n,i=Math.floor(e.image.width*r),a=Math.floor(e.image.height*r),o=t===null?0:t.x,s=t===null?0:t.y;L.setTexture2D(e,0),P.copyTexSubImage2D(P.TEXTURE_2D,n,0,0,o,s,i,a),F.unbindTexture()},this.copyTextureToTexture=function(e,t,n=null,r=null,i=0,a=0){let o,s,c,l,u,d,f,p,m,h=e.isCompressedTexture?e.mipmaps[a]:e.image;if(n!==null)o=n.max.x-n.min.x,s=n.max.y-n.min.y,c=n.isBox3?n.max.z-n.min.z:1,l=n.min.x,u=n.min.y,d=n.isBox3?n.min.z:0;else{let t=2**-i;o=Math.floor(h.width*t),s=Math.floor(h.height*t),c=e.isDataArrayTexture?h.depth:e.isData3DTexture?Math.floor(h.depth*t):1,l=0,u=0,d=0}r===null?(f=0,p=0,m=0):(f=r.x,p=r.y,m=r.z);let g=He.convert(t.format),_=He.convert(t.type),v;t.isData3DTexture?(L.setTexture3D(t,0),v=P.TEXTURE_3D):t.isDataArrayTexture||t.isCompressedArrayTexture?(L.setTexture2DArray(t,0),v=P.TEXTURE_2D_ARRAY):(L.setTexture2D(t,0),v=P.TEXTURE_2D),F.activeTexture(P.TEXTURE0),F.pixelStorei(P.UNPACK_FLIP_Y_WEBGL,t.flipY),F.pixelStorei(P.UNPACK_PREMULTIPLY_ALPHA_WEBGL,t.premultiplyAlpha),F.pixelStorei(P.UNPACK_ALIGNMENT,t.unpackAlignment);let y=F.getParameter(P.UNPACK_ROW_LENGTH),b=F.getParameter(P.UNPACK_IMAGE_HEIGHT),x=F.getParameter(P.UNPACK_SKIP_PIXELS),S=F.getParameter(P.UNPACK_SKIP_ROWS),C=F.getParameter(P.UNPACK_SKIP_IMAGES);F.pixelStorei(P.UNPACK_ROW_LENGTH,h.width),F.pixelStorei(P.UNPACK_IMAGE_HEIGHT,h.height),F.pixelStorei(P.UNPACK_SKIP_PIXELS,l),F.pixelStorei(P.UNPACK_SKIP_ROWS,u),F.pixelStorei(P.UNPACK_SKIP_IMAGES,d);let w=e.isDataArrayTexture||e.isData3DTexture,T=t.isDataArrayTexture||t.isData3DTexture;if(e.isDepthTexture){let n=I.get(e),r=I.get(t),h=I.get(n.__renderTarget),g=I.get(r.__renderTarget);F.bindFramebuffer(P.READ_FRAMEBUFFER,h.__webglFramebuffer),F.bindFramebuffer(P.DRAW_FRAMEBUFFER,g.__webglFramebuffer);for(let n=0;n<c;n++)w&&(P.framebufferTextureLayer(P.READ_FRAMEBUFFER,P.COLOR_ATTACHMENT0,I.get(e).__webglTexture,i,d+n),P.framebufferTextureLayer(P.DRAW_FRAMEBUFFER,P.COLOR_ATTACHMENT0,I.get(t).__webglTexture,a,m+n)),P.blitFramebuffer(l,u,o,s,f,p,o,s,P.DEPTH_BUFFER_BIT,P.NEAREST);F.bindFramebuffer(P.READ_FRAMEBUFFER,null),F.bindFramebuffer(P.DRAW_FRAMEBUFFER,null)}else if(i!==0||e.isRenderTargetTexture||I.has(e)){let n=I.get(e),r=I.get(t);F.bindFramebuffer(P.READ_FRAMEBUFFER,k),F.bindFramebuffer(P.DRAW_FRAMEBUFFER,A);for(let e=0;e<c;e++)w?P.framebufferTextureLayer(P.READ_FRAMEBUFFER,P.COLOR_ATTACHMENT0,n.__webglTexture,i,d+e):P.framebufferTexture2D(P.READ_FRAMEBUFFER,P.COLOR_ATTACHMENT0,P.TEXTURE_2D,n.__webglTexture,i),T?P.framebufferTextureLayer(P.DRAW_FRAMEBUFFER,P.COLOR_ATTACHMENT0,r.__webglTexture,a,m+e):P.framebufferTexture2D(P.DRAW_FRAMEBUFFER,P.COLOR_ATTACHMENT0,P.TEXTURE_2D,r.__webglTexture,a),i===0?T?P.copyTexSubImage3D(v,a,f,p,m+e,l,u,o,s):P.copyTexSubImage2D(v,a,f,p,l,u,o,s):P.blitFramebuffer(l,u,o,s,f,p,o,s,P.COLOR_BUFFER_BIT,P.NEAREST);F.bindFramebuffer(P.READ_FRAMEBUFFER,null),F.bindFramebuffer(P.DRAW_FRAMEBUFFER,null)}else T?e.isDataTexture||e.isData3DTexture?P.texSubImage3D(v,a,f,p,m,o,s,c,g,_,h.data):t.isCompressedArrayTexture?P.compressedTexSubImage3D(v,a,f,p,m,o,s,c,g,h.data):P.texSubImage3D(v,a,f,p,m,o,s,c,g,_,h):e.isDataTexture?P.texSubImage2D(P.TEXTURE_2D,a,f,p,o,s,g,_,h.data):e.isCompressedTexture?P.compressedTexSubImage2D(P.TEXTURE_2D,a,f,p,h.width,h.height,g,h.data):P.texSubImage2D(P.TEXTURE_2D,a,f,p,o,s,g,_,h);F.pixelStorei(P.UNPACK_ROW_LENGTH,y),F.pixelStorei(P.UNPACK_IMAGE_HEIGHT,b),F.pixelStorei(P.UNPACK_SKIP_PIXELS,x),F.pixelStorei(P.UNPACK_SKIP_ROWS,S),F.pixelStorei(P.UNPACK_SKIP_IMAGES,C),a===0&&t.generateMipmaps&&P.generateMipmap(v),F.unbindTexture()},this.initRenderTarget=function(e){I.get(e).__webglFramebuffer===void 0&&L.setupRenderTarget(e)},this.initTexture=function(e){e.isCubeTexture?L.setTextureCube(e,0):e.isData3DTexture?L.setTexture3D(e,0):e.isDataArrayTexture||e.isCompressedArrayTexture?L.setTexture2DArray(e,0):L.setTexture2D(e,0),F.unbindTexture()},this.resetState=function(){ee=0,te=0,j=null,F.reset(),Ue.reset()},typeof __THREE_DEVTOOLS__<`u`&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent(`observe`,{detail:this}))}get coordinateSystem(){return XS}get outputColorSpace(){return this._outputColorSpace}set outputColorSpace(e){this._outputColorSpace=e;let t=this.getContext();t.drawingBufferColorSpace=wC._getDrawingBufferColorSpace(e),t.unpackColorSpace=wC._getUnpackColorSpace()}},wA={request:e=>{e()},cancel:()=>{}};function TA(e){return new Z().set(...e)}var EA=class{lenses;uniform;named;constructor(e,t){this.lenses=e,this.uniform=t,this.named=Array.from({length:e.length})}follow(e){for(let[t,n]of this.lenses.entries()){let r=e[n.frameSlot];if(!r)continue;let i=el($c,r.colorSpace.matrix);i!==this.named[t]&&(this.named[t]=i,this.uniform.value[t]=TA(ml(n.displayConversion.matrix,i)))}}};function DA(e){return Number.isSafeInteger(e)?e.toFixed(1):String(e)}var OA=0,kA=1,AA=[[`CONVERSION_HLG_TO_SDR_BT709`,kA],[`HLG_A`,DA(tl.a)],[`HLG_B`,DA(tl.b)],[`HLG_C`,DA(tl.c)],[`HLG_SEGMENT_JOIN`,DA(tl.segmentJoin)],[`HLG_SQUARE_SEGMENT_DIVISOR`,DA(tl.squareSegmentDivisor)],[`HLG_LOG_SEGMENT_DIVISOR`,DA(tl.logSegmentDivisor)],[`BT709_LUMINANCE_RED`,DA(rl[0])],[`BT709_LUMINANCE_GREEN`,DA(rl[1])],[`BT709_LUMINANCE_BLUE`,DA(rl[2])]];function jA(e){let t=e.map(e=>MA(e.displayConversion));return{uLensConversion:{value:t.map(e=>e.kind)},uLensMatrixCorrection:{value:e.map(()=>TA(Mr))},uLensGamut:{value:t.map(e=>e.gamut)},uLensTone:{value:t.map(e=>e.tone)}}}function MA(e){switch(e.kind){case`as-recorded`:return{kind:OA,gamut:TA(Mr),tone:new FC};case`hlg-to-sdr-bt709`:{let{exposure:t,kneeStart:n,ceiling:r,exponent:i}=e.tone;return{kind:kA,gamut:TA(e.gamut),tone:new FC(t,n,r,i)}}}}var NA={fast:{minFilter:Dx,generateMipmaps:!1,anisotropy:1,shaderSampling:0},balanced:{minFilter:kx,generateMipmaps:!0,anisotropy:4,shaderSampling:1},high:{minFilter:kx,generateMipmaps:!0,anisotropy:8,shaderSampling:2}},PA=0,FA=1,IA=Object.fromEntries([[`MAX_LENSES`,2],[`LENS_MEI`,PA],[`LENS_RADIAL_POLYNOMIAL`,FA],[`MEI_RADIAL_TERMS`,oe.radial],[`MEI_TANGENTIAL_ORDERS`,oe.tangential],[`MEI_THIN_PRISM_ORDERS`,oe.thinPrism],...AA,[`SAMPLING_BILINEAR`,0],[`SAMPLING_TRILINEAR`,1],[`SAMPLING_SUPERSAMPLED`,2]]);function LA(e,t){let n=$A(e.lenses,`a stitching setup has one or two lenses`);return{...RA(e),...zA(n),...WA(n),...jA(n),uTexture0:{value:t[0]??null},uTexture1:{value:t[1]??null}}}function RA(e){return{uLensCount:{value:e.lenses.length},uViewRotation:{value:new Z},uStabilization:{value:new Z},uPlaneHalfExtent:{value:1},uPictureAspect:{value:1},uScreenArea:{value:Array.from({length:2},()=>new FC(0,0,1,1))},uFeather:{value:new Y(e.feather.start,e.feather.end)}}}function zA(e){let t=e.map(e=>VA(e.projection));return{uLensRotation:{value:e.map(e=>TA(e.rotation))},uLensKind:{value:t.map(e=>e.kind)},uLensPrincipalPoint:{value:e.map(e=>QA(e.projection.principalPoint))},uLensFocal:{value:t.map(e=>e.focal)},uLensXi:{value:t.map(e=>e.xi)},uLensRadial:{value:t.flatMap(e=>e.radial)},uLensTangential:{value:t.flatMap(e=>e.tangential)},uLensThinPrism:{value:t.flatMap(e=>e.thinPrism)},uLensPolynomial:{value:t.map(e=>e.polynomial)},uLensHalfFov:{value:e.map(e=>e.halfFieldOfView)}}}var BA={radial:[],tangential:[],thinPrism:[]};function VA(e){switch(e.kind){case`mei`:return{kind:PA,focal:new Y(...e.focal),xi:e.xi,...HA(e.distortion),polynomial:new FC};case`radial-polynomial`:return{kind:FA,focal:new Y,xi:0,...HA(BA),polynomial:new FC(...e.coefficients)}}}function HA(e){return{radial:UA(e.radial,oe.radial,()=>0),tangential:UA(e.tangential.map(e=>new Y(e.p1,e.p2)),oe.tangential,()=>new Y),thinPrism:UA(e.thinPrism.map(e=>new Y(e.x,e.y)),oe.thinPrism,()=>new Y)}}function UA(e,t,n){return N(e.length<=t,`a Mei lens has ${e.length} terms of a family the shader holds ${t} of`),Array.from({length:t},(t,r)=>e[r]??n())}function WA(e){return{uLensWindow:{value:e.map(e=>new FC(e.window.x,e.window.y,e.window.width,e.window.height))},uLensRegion:{value:e.map(e=>new FC(e.region.x,e.region.y,e.region.width,e.region.height))},uLensTexture:{value:e.map(e=>e.frameSlot)},uLensGain:{value:e.map(()=>new X(1,1,1))},uSampling:{value:0}}}function GA(e,t){e.uSampling.value=t.shaderSampling}function KA(e,t){e.uStabilization.value=TA(t)}function qA(e,t,n){ae(t,e.uLensCount.value,`lens`),e.uLensGain.value[t]?.set(...n)}var JA={rotation:Mr,planeHalfExtent:1,pictureAspect:1};function YA(e,t,n){let r=XA(t,n);e.uViewRotation.value=TA(r.rotation),e.uPlaneHalfExtent.value=r.planeHalfExtent,e.uPictureAspect.value=r.pictureAspect,e.uScreenArea.value=$A(r.areas,`a picture fills one area per lens at most`).map(e=>ZA(e))}function XA(e,t){switch(e.kind){case`rectilinear`:return{rotation:e.rotation,planeHalfExtent:Hs(e.fieldOfView),pictureAspect:Us(e.area,t),areas:[e.area]};case`equirectangular`:return{...JA,rotation:e.rotation,areas:[e.area]};case`lens-tiles`:return{...JA,areas:e.tiles}}}function ZA(e){return new FC(e.x,e.y,e.width,e.height)}function QA(e){return new Y(e.x,e.y)}function $A(e,t){let n=e.at(-1);return N(n!==void 0&&e.length<=2,t),Array.from({length:2},(t,r)=>e[r]??n)}var ej=`// One triangle covering the whole viewport; the fragment shader does all the work.
|
|
4222
|
+
}`,Gj=class{constructor(){this.texture=null,this.mesh=null,this.depthNear=0,this.depthFar=0}init(e,t){if(this.texture===null){let n=new jD(e.texture);(e.depthNear!==t.depthNear||e.depthFar!==t.depthFar)&&(this.depthNear=e.depthNear,this.depthFar=e.depthFar),this.texture=n}}getMesh(e){if(this.texture!==null&&this.mesh===null){let t=e.cameras[0].viewport,n=new HD({vertexShader:Uj,fragmentShader:Wj,uniforms:{depthColor:{value:this.texture},depthWidth:{value:t.z},depthHeight:{value:t.w}}});this.mesh=new vD(new ND(20,20),n)}return this.mesh}reset(){this.texture=null,this.mesh=null}getDepthTexture(){return this.texture}},Kj=class extends Rw{constructor(e,t){super();let n=this,r=null,i=1,a=null,o=`local-floor`,s=1,c=null,l=null,u=null,d=null,f=null,p=null,m=typeof XRWebGLBinding<`u`,h=new Gj,g={},_=t.getContextAttributes(),v=null,y=null,b=[],x=[],S=new Y,C=null,w=null,T=new vO;T.viewport=new fT;let E=new vO;E.viewport=new fT;let D=[T,E],O=new CO,k=null,A=null;this.cameraAutoUpdate=!0,this.enabled=!1,this.isPresenting=!1,this.getController=function(e){let t=b[e];return t===void 0&&(t=new qT,b[e]=t),t.getTargetRaySpace()},this.getControllerGrip=function(e){let t=b[e];return t===void 0&&(t=new qT,b[e]=t),t.getGripSpace()},this.getHand=function(e){let t=b[e];return t===void 0&&(t=new qT,b[e]=t),t.getHandSpace()};function ee(e){let t=x.indexOf(e.inputSource);if(t===-1)return;let n=b[t];n!==void 0&&(n.update(e.inputSource,e.frame,c||a),n.dispatchEvent({type:e.type,data:e.inputSource}))}function te(){r.removeEventListener(`select`,ee),r.removeEventListener(`selectstart`,ee),r.removeEventListener(`selectend`,ee),r.removeEventListener(`squeeze`,ee),r.removeEventListener(`squeezestart`,ee),r.removeEventListener(`squeezeend`,ee),r.removeEventListener(`end`,te),r.removeEventListener(`inputsourceschange`,j);for(let e=0;e<b.length;e++){let t=x[e];t!==null&&(x[e]=null,b[e].disconnect(t))}k=null,A=null,h.reset();for(let e in g)delete g[e];if(e.setRenderTarget(v),f=null,d=null,u=null,r=null,y=null,se.stop(),n.isPresenting=!1,e.setPixelRatio(C),e.setSize(S.width,S.height,!1),w!==null){let e=w.camera;e.fov=w.fov,e.zoom=w.zoom,e.updateProjectionMatrix(),w=null}n.dispatchEvent({type:`sessionend`})}this.setFramebufferScaleFactor=function(e){i=e,n.isPresenting===!0&&q(`WebXRManager: Cannot change framebuffer scale while presenting.`)},this.setReferenceSpaceType=function(e){o=e,n.isPresenting===!0&&q(`WebXRManager: Cannot change reference space type while presenting.`)},this.getReferenceSpace=function(){return c||a},this.setReferenceSpace=function(e){c=e},this.getBaseLayer=function(){return d===null?f:d},this.getBinding=function(){return u===null&&m&&(u=new XRWebGLBinding(r,t)),u},this.getFrame=function(){return p},this.getSession=function(){return r},this.setSession=async function(l){if(r=l,r!==null){if(v=e.getRenderTarget(),r.addEventListener(`select`,ee),r.addEventListener(`selectstart`,ee),r.addEventListener(`selectend`,ee),r.addEventListener(`squeeze`,ee),r.addEventListener(`squeezestart`,ee),r.addEventListener(`squeezeend`,ee),r.addEventListener(`end`,te),r.addEventListener(`inputsourceschange`,j),_.xrCompatible!==!0&&await t.makeXRCompatible(),C=e.getPixelRatio(),e.getSize(S),m&&`createProjectionLayer`in XRWebGLBinding.prototype){let n=null,a=null,o=null;_.depth&&(o=_.stencil?t.DEPTH24_STENCIL8:t.DEPTH_COMPONENT24,n=_.stencil?wC:CC,a=_.stencil?_C:fC);let s={colorFormat:t.RGBA8,depthFormat:o,scaleFactor:i};u=this.getBinding(),d=u.createProjectionLayer(s),r.updateRenderState({layers:[d]}),e.setPixelRatio(1),e.setSize(d.textureWidth,d.textureHeight,!1),y=new mT(d.textureWidth,d.textureHeight,{format:SC,type:sC,depthTexture:new kD(d.textureWidth,d.textureHeight,a,void 0,void 0,void 0,void 0,void 0,void 0,n),stencilBuffer:_.stencil,colorSpace:e.outputColorSpace,samples:_.antialias?4:0,resolveDepthBuffer:d.ignoreDepthValues===!1,resolveStencilBuffer:d.ignoreDepthValues===!1,storeMultisampledDepthBuffer:d.ignoreDepthValues===!1,storeMultisampledStencilBuffer:d.ignoreDepthValues===!1})}else{let n={antialias:_.antialias,alpha:!0,depth:_.depth,stencil:_.stencil,framebufferScaleFactor:i};f=new XRWebGLLayer(r,t,n),r.updateRenderState({baseLayer:f}),e.setPixelRatio(1),e.setSize(f.framebufferWidth,f.framebufferHeight,!1),y=new mT(f.framebufferWidth,f.framebufferHeight,{format:SC,type:sC,colorSpace:e.outputColorSpace,stencilBuffer:_.stencil,resolveDepthBuffer:f.ignoreDepthValues===!1,resolveStencilBuffer:f.ignoreDepthValues===!1,storeMultisampledDepthBuffer:f.ignoreDepthValues===!1,storeMultisampledStencilBuffer:f.ignoreDepthValues===!1})}y.isXRRenderTarget=!0,this.setFoveation(s),c=null,a=await r.requestReferenceSpace(o),se.setContext(r),se.start(),n.isPresenting=!0,n.dispatchEvent({type:`sessionstart`})}},this.getEnvironmentBlendMode=function(){if(r!==null)return r.environmentBlendMode},this.getDepthTexture=function(){return h.getDepthTexture()};function j(e){for(let t=0;t<e.removed.length;t++){let n=e.removed[t],r=x.indexOf(n);r>=0&&(x[r]=null,b[r].disconnect(n))}for(let t=0;t<e.added.length;t++){let n=e.added[t],r=x.indexOf(n);if(r===-1){for(let e=0;e<b.length;e++)if(e>=x.length){x.push(n),r=e;break}else if(x[e]===null){x[e]=n,r=e;break}if(r===-1)break}let i=b[r];i&&i.connect(n)}}let ne=new X,re=new X;function M(e,t,n){ne.setFromMatrixPosition(t.matrixWorld),re.setFromMatrixPosition(n.matrixWorld);let r=ne.distanceTo(re),i=t.projectionMatrix.elements,a=n.projectionMatrix.elements,o=i[14]/(i[10]-1),s=i[14]/(i[10]+1),c=(i[9]+1)/i[5],l=(i[9]-1)/i[5],u=(i[8]-1)/i[0],d=(a[8]+1)/a[0],f=o*u,p=o*d,m=r/(-u+d),h=m*-u;if(t.matrixWorld.decompose(e.position,e.quaternion,e.scale),e.translateX(h),e.translateZ(m),e.matrixWorld.compose(e.position,e.quaternion,e.scale),e.matrixWorldInverse.copy(e.matrixWorld).invert(),i[10]===-1)e.projectionMatrix.copy(t.projectionMatrix),e.projectionMatrixInverse.copy(t.projectionMatrixInverse);else{let t=o+m,n=s+m,i=f-h,a=p+(r-h),u=c*s/n*t,d=l*s/n*t;e.projectionMatrix.makePerspective(i,a,u,d,t,n),e.projectionMatrixInverse.copy(e.projectionMatrix).invert()}}function ie(e,t){t===null?e.matrixWorld.copy(e.matrix):e.matrixWorld.multiplyMatrices(t.matrixWorld,e.matrix),e.matrixWorldInverse.copy(e.matrixWorld).invert()}this.updateCamera=function(e){if(r===null)return;let t=e.near,n=e.far;h.texture!==null&&(h.depthNear>0&&(t=h.depthNear),h.depthFar>0&&(n=h.depthFar)),O.near=E.near=T.near=t,O.far=E.far=T.far=n,(k!==O.near||A!==O.far)&&(r.updateRenderState({depthNear:O.near,depthFar:O.far}),k=O.near,A=O.far),O.layers.mask=e.layers.mask|6,T.layers.mask=O.layers.mask&-5,E.layers.mask=O.layers.mask&-3;let i=e.parent,a=O.cameras;ie(O,i);for(let e=0;e<a.length;e++)ie(a[e],i);a.length===2?M(O,T,E):O.projectionMatrix.copy(T.projectionMatrix),w===null&&e.isPerspectiveCamera&&(w={camera:e,fov:e.fov,zoom:e.zoom}),N(e,O,i)};function N(e,t,n){n===null?e.matrix.copy(t.matrixWorld):(e.matrix.copy(n.matrixWorld),e.matrix.invert(),e.matrix.multiply(t.matrixWorld)),e.matrix.decompose(e.position,e.quaternion,e.scale),e.updateMatrixWorld(!0),e.projectionMatrix.copy(t.projectionMatrix),e.projectionMatrixInverse.copy(t.projectionMatrixInverse),e.isPerspectiveCamera&&(e.fov=Vw*2*Math.atan(1/e.projectionMatrix.elements[5]),e.zoom=1)}this.getCamera=function(){return O},this.getFoveation=function(){if(d!==null||f!==null)return s},this.setFoveation=function(e){s=e,d!==null&&(d.fixedFoveation=e),f!==null&&f.fixedFoveation!==void 0&&(f.fixedFoveation=e)},this.hasDepthSensing=function(){return h.texture!==null},this.getDepthSensingMesh=function(){return h.getMesh(O)},this.getCameraTexture=function(e){return g[e]};let ae=null;function oe(t,i){if(l=i.getViewerPose(c||a),p=i,l!==null){let t=l.views;f!==null&&(e.setRenderTargetFramebuffer(y,f.framebuffer),e.setRenderTarget(y));let i=!1;t.length!==O.cameras.length&&(O.cameras.length=0,i=!0);for(let n=0;n<t.length;n++){let r=t[n],a=null;if(f!==null)a=f.getViewport(r);else{let t=u.getViewSubImage(d,r);a=t.viewport,n===0&&(e.setRenderTargetTextures(y,t.colorTexture,t.depthStencilTexture),e.setRenderTarget(y))}let o=D[n];o===void 0&&(o=new vO,o.layers.enable(n),o.viewport=new fT,D[n]=o),o.matrix.fromArray(r.transform.matrix),o.matrix.decompose(o.position,o.quaternion,o.scale),o.projectionMatrix.fromArray(r.projectionMatrix),o.projectionMatrixInverse.copy(o.projectionMatrix).invert(),o.viewport.set(a.x,a.y,a.width,a.height),n===0&&(O.matrix.copy(o.matrix),O.matrix.decompose(O.position,O.quaternion,O.scale)),i===!0&&O.cameras.push(o)}let a=r.enabledFeatures;if(a&&a.includes(`depth-sensing`)&&r.depthUsage==`gpu-optimized`&&m){u=n.getBinding();let e=u.getDepthInformation(t[0]);e&&e.isValid&&e.texture&&h.init(e,r.renderState)}if(a&&a.includes(`camera-access`)&&m){e.state.unbindTexture(),u=n.getBinding();for(let e=0;e<t.length;e++){let n=t[e].camera;if(n){let e=g[n];e||(e=new jD,g[n]=e);let t=u.getCameraImage(n);e.sourceTexture=t}}}}for(let e=0;e<b.length;e++){let t=x[e],n=b[e];t!==null&&n!==void 0&&n.update(t,i,c||a)}ae&&ae(t,i),i.detectedPlanes&&n.dispatchEvent({type:`planesdetected`,data:i}),p=null}let se=new RO;se.setAnimationLoop(oe),this.setAnimationLoop=function(e){ae=e},this.dispose=function(){}}},qj=/*@__PURE__*/ new _T,Jj=/*@__PURE__*/ new Z;Jj.set(-1,0,0,0,1,0,0,0,1);function Yj(e,t){function n(e,t){e.matrixAutoUpdate===!0&&e.updateMatrix(),t.value.copy(e.matrix)}function r(t,n){n.color.getRGB(t.fogColor.value,RD(e)),n.isFog?(t.fogNear.value=n.near,t.fogFar.value=n.far):n.isFogExp2&&(t.fogDensity.value=n.density)}function i(e,t,n,r,i){t.isNodeMaterial?t.uniformsNeedUpdate=!1:t.isMeshBasicMaterial?a(e,t):t.isMeshLambertMaterial?(a(e,t),t.envMap&&(e.envMapIntensity.value=t.envMapIntensity)):t.isMeshToonMaterial?(a(e,t),d(e,t)):t.isMeshPhongMaterial?(a(e,t),u(e,t),t.envMap&&(e.envMapIntensity.value=t.envMapIntensity)):t.isMeshStandardMaterial?(a(e,t),f(e,t),t.isMeshPhysicalMaterial&&p(e,t,i)):t.isMeshMatcapMaterial?(a(e,t),m(e,t)):t.isMeshDepthMaterial?a(e,t):t.isMeshDistanceMaterial?(a(e,t),h(e,t)):t.isMeshNormalMaterial?a(e,t):t.isLineBasicMaterial?(o(e,t),t.isLineDashedMaterial&&s(e,t)):t.isPointsMaterial?c(e,t,n,r):t.isSpriteMaterial?l(e,t):t.isShadowMaterial?(e.color.value.copy(t.color),e.opacity.value=t.opacity):t.isShaderMaterial&&(t.uniformsNeedUpdate=!1)}function a(e,r){e.opacity.value=r.opacity,r.color&&e.diffuse.value.copy(r.color),r.emissive&&e.emissive.value.copy(r.emissive).multiplyScalar(r.emissiveIntensity),r.map&&(e.map.value=r.map,n(r.map,e.mapTransform)),r.alphaMap&&(e.alphaMap.value=r.alphaMap,n(r.alphaMap,e.alphaMapTransform)),r.bumpMap&&(e.bumpMap.value=r.bumpMap,n(r.bumpMap,e.bumpMapTransform),e.bumpScale.value=r.bumpScale,r.side===1&&(e.bumpScale.value*=-1)),r.normalMap&&(e.normalMap.value=r.normalMap,n(r.normalMap,e.normalMapTransform),e.normalScale.value.copy(r.normalScale),r.side===1&&e.normalScale.value.negate()),r.displacementMap&&(e.displacementMap.value=r.displacementMap,n(r.displacementMap,e.displacementMapTransform),e.displacementScale.value=r.displacementScale,e.displacementBias.value=r.displacementBias),r.emissiveMap&&(e.emissiveMap.value=r.emissiveMap,n(r.emissiveMap,e.emissiveMapTransform)),r.specularMap&&(e.specularMap.value=r.specularMap,n(r.specularMap,e.specularMapTransform)),r.alphaTest>0&&(e.alphaTest.value=r.alphaTest);let i=t.get(r),a=i.envMap,o=i.envMapRotation;a&&(e.envMap.value=a,e.envMapRotation.value.setFromMatrix4(qj.makeRotationFromEuler(o)).transpose(),a.isCubeTexture&&a.isRenderTargetTexture===!1&&e.envMapRotation.value.premultiply(Jj),e.reflectivity.value=r.reflectivity,e.ior.value=r.ior,e.refractionRatio.value=r.refractionRatio),r.lightMap&&(e.lightMap.value=r.lightMap,e.lightMapIntensity.value=r.lightMapIntensity,n(r.lightMap,e.lightMapTransform)),r.aoMap&&(e.aoMap.value=r.aoMap,e.aoMapIntensity.value=r.aoMapIntensity,n(r.aoMap,e.aoMapTransform))}function o(e,t){e.diffuse.value.copy(t.color),e.opacity.value=t.opacity,t.map&&(e.map.value=t.map,n(t.map,e.mapTransform))}function s(e,t){e.dashSize.value=t.dashSize,e.totalSize.value=t.dashSize+t.gapSize,e.scale.value=t.scale}function c(e,t,r,i){e.diffuse.value.copy(t.color),e.opacity.value=t.opacity,e.size.value=t.size*r,e.scale.value=i*.5,t.map&&(e.map.value=t.map,n(t.map,e.uvTransform)),t.alphaMap&&(e.alphaMap.value=t.alphaMap,n(t.alphaMap,e.alphaMapTransform)),t.alphaTest>0&&(e.alphaTest.value=t.alphaTest)}function l(e,t){e.diffuse.value.copy(t.color),e.opacity.value=t.opacity,e.rotation.value=t.rotation,t.map&&(e.map.value=t.map,n(t.map,e.mapTransform)),t.alphaMap&&(e.alphaMap.value=t.alphaMap,n(t.alphaMap,e.alphaMapTransform)),t.alphaTest>0&&(e.alphaTest.value=t.alphaTest)}function u(e,t){e.specular.value.copy(t.specular),e.shininess.value=Math.max(t.shininess,1e-4)}function d(e,t){t.gradientMap&&(e.gradientMap.value=t.gradientMap)}function f(e,t){e.metalness.value=t.metalness,t.metalnessMap&&(e.metalnessMap.value=t.metalnessMap,n(t.metalnessMap,e.metalnessMapTransform)),e.roughness.value=t.roughness,t.roughnessMap&&(e.roughnessMap.value=t.roughnessMap,n(t.roughnessMap,e.roughnessMapTransform)),t.envMap&&(e.envMapIntensity.value=t.envMapIntensity)}function p(e,t,r){e.ior.value=t.ior,t.sheen>0&&(e.sheenColor.value.copy(t.sheenColor).multiplyScalar(t.sheen),e.sheenRoughness.value=t.sheenRoughness,t.sheenColorMap&&(e.sheenColorMap.value=t.sheenColorMap,n(t.sheenColorMap,e.sheenColorMapTransform)),t.sheenRoughnessMap&&(e.sheenRoughnessMap.value=t.sheenRoughnessMap,n(t.sheenRoughnessMap,e.sheenRoughnessMapTransform))),t.clearcoat>0&&(e.clearcoat.value=t.clearcoat,e.clearcoatRoughness.value=t.clearcoatRoughness,t.clearcoatMap&&(e.clearcoatMap.value=t.clearcoatMap,n(t.clearcoatMap,e.clearcoatMapTransform)),t.clearcoatRoughnessMap&&(e.clearcoatRoughnessMap.value=t.clearcoatRoughnessMap,n(t.clearcoatRoughnessMap,e.clearcoatRoughnessMapTransform)),t.clearcoatNormalMap&&(e.clearcoatNormalMap.value=t.clearcoatNormalMap,n(t.clearcoatNormalMap,e.clearcoatNormalMapTransform),e.clearcoatNormalScale.value.copy(t.clearcoatNormalScale),t.side===1&&e.clearcoatNormalScale.value.negate())),t.dispersion>0&&(e.dispersion.value=t.dispersion),t.retroreflectivity>0&&(e.retroreflectivity.value=t.retroreflectivity),t.iridescence>0&&(e.iridescence.value=t.iridescence,e.iridescenceIOR.value=t.iridescenceIOR,e.iridescenceThicknessMinimum.value=t.iridescenceThicknessRange[0],e.iridescenceThicknessMaximum.value=t.iridescenceThicknessRange[1],t.iridescenceMap&&(e.iridescenceMap.value=t.iridescenceMap,n(t.iridescenceMap,e.iridescenceMapTransform)),t.iridescenceThicknessMap&&(e.iridescenceThicknessMap.value=t.iridescenceThicknessMap,n(t.iridescenceThicknessMap,e.iridescenceThicknessMapTransform))),t.transmission>0&&(e.transmission.value=t.transmission,e.transmissionSamplerMap.value=r.texture,e.transmissionSamplerSize.value.set(r.width,r.height),t.transmissionMap&&(e.transmissionMap.value=t.transmissionMap,n(t.transmissionMap,e.transmissionMapTransform)),e.thickness.value=t.thickness,t.thicknessMap&&(e.thicknessMap.value=t.thicknessMap,n(t.thicknessMap,e.thicknessMapTransform)),e.attenuationDistance.value=t.attenuationDistance,e.attenuationColor.value.copy(t.attenuationColor)),t.anisotropy>0&&(e.anisotropyVector.value.set(t.anisotropy*Math.cos(t.anisotropyRotation),t.anisotropy*Math.sin(t.anisotropyRotation)),t.anisotropyMap&&(e.anisotropyMap.value=t.anisotropyMap,n(t.anisotropyMap,e.anisotropyMapTransform))),e.specularIntensity.value=t.specularIntensity,e.specularColor.value.copy(t.specularColor),t.specularColorMap&&(e.specularColorMap.value=t.specularColorMap,n(t.specularColorMap,e.specularColorMapTransform)),t.specularIntensityMap&&(e.specularIntensityMap.value=t.specularIntensityMap,n(t.specularIntensityMap,e.specularIntensityMapTransform))}function m(e,t){t.matcap&&(e.matcap.value=t.matcap)}function h(e,n){let r=t.get(n).light;e.referencePosition.value.setFromMatrixPosition(r.matrixWorld),e.nearDistance.value=r.shadow.camera.near,e.farDistance.value=r.shadow.camera.far}return{refreshFogUniforms:r,refreshMaterialUniforms:i}}function Xj(e,t,n,r){let i={},a={},o=[],s=e.getParameter(e.MAX_UNIFORM_BUFFER_BINDINGS);function c(e,t){let n=t.program;r.uniformBlockBinding(e,n)}function l(e,n){let o=i[e.id];o===void 0&&(g(e),o=u(e),i[e.id]=o,e.addEventListener(`dispose`,v));let s=n.program;r.updateUBOMapping(e,s);let c=t.render.frame;a[e.id]!==c&&(f(e),a[e.id]=c)}function u(t){let n=d();t.__bindingPointIndex=n;let r=e.createBuffer(),i=t.__size,a=t.usage;return e.bindBuffer(e.UNIFORM_BUFFER,r),e.bufferData(e.UNIFORM_BUFFER,i,a),e.bindBuffer(e.UNIFORM_BUFFER,null),e.bindBufferBase(e.UNIFORM_BUFFER,n,r),r}function d(){for(let e=0;e<s;e++)if(o.indexOf(e)===-1)return o.push(e),e;return J(`WebGLRenderer: Maximum number of simultaneously usable uniforms groups reached.`),0}function f(t){let n=i[t.id],r=t.uniforms,a=t.__cache;e.bindBuffer(e.UNIFORM_BUFFER,n);for(let e=0,t=r.length;e<t;e++){let t=r[e];if(Array.isArray(t))for(let n=0,r=t.length;n<r;n++)p(t[n],e,n,a);else p(t,e,0,a)}e.bindBuffer(e.UNIFORM_BUFFER,null)}function p(t,n,r,i){if(h(t,n,r,i)===!0){let n=t.__offset,r=t.value;if(Array.isArray(r)){let e=0;for(let n=0;n<r.length;n++){let i=r[n],a=_(i);m(i,t.__data,e),typeof i!=`number`&&typeof i!=`boolean`&&!i.isMatrix3&&!ArrayBuffer.isView(i)&&(e+=a.storage/Float32Array.BYTES_PER_ELEMENT)}}else m(r,t.__data,0);e.bufferSubData(e.UNIFORM_BUFFER,n,t.__data)}}function m(e,t,n){typeof e==`number`||typeof e==`boolean`?t[0]=e:e.isMatrix3?(t[0]=e.elements[0],t[1]=e.elements[1],t[2]=e.elements[2],t[3]=0,t[4]=e.elements[3],t[5]=e.elements[4],t[6]=e.elements[5],t[7]=0,t[8]=e.elements[6],t[9]=e.elements[7],t[10]=e.elements[8],t[11]=0):ArrayBuffer.isView(e)?t.set(new e.constructor(e.buffer,e.byteOffset,t.length)):e.toArray(t,n)}function h(e,t,n,r){let i=e.value,a=t+`_`+n;if(r[a]===void 0)return r[a]=typeof i==`number`||typeof i==`boolean`?i:ArrayBuffer.isView(i)?i.slice():i.clone(),!0;{let e=r[a];if(typeof i==`number`||typeof i==`boolean`){if(e!==i)return r[a]=i,!0}else if(ArrayBuffer.isView(i))return!0;else if(e.equals(i)===!1)return e.copy(i),!0}return!1}function g(e){let t=e.uniforms,n=0;for(let e=0,r=t.length;e<r;e++){let r=Array.isArray(t[e])?t[e]:[t[e]];for(let e=0,t=r.length;e<t;e++){let t=r[e],i=Array.isArray(t.value)?t.value:[t.value];for(let e=0,r=i.length;e<r;e++){let r=i[e],a=_(r),o=n%16,s=o%a.boundary,c=o+s;n+=s,c!==0&&16-c<a.storage&&(n+=16-c),t.__data=new Float32Array(a.storage/Float32Array.BYTES_PER_ELEMENT),t.__offset=n,n+=a.storage}}}let r=n%16;return r>0&&(n+=16-r),e.__size=n,e.__cache={},this}function _(e){let t={boundary:0,storage:0};return typeof e==`number`||typeof e==`boolean`?(t.boundary=4,t.storage=4):e.isVector2?(t.boundary=8,t.storage=8):e.isVector3||e.isColor?(t.boundary=16,t.storage=12):e.isVector4?(t.boundary=16,t.storage=16):e.isMatrix3?(t.boundary=48,t.storage=48):e.isMatrix4?(t.boundary=64,t.storage=64):e.isTexture?q(`WebGLRenderer: Texture samplers can not be part of an uniforms group.`):ArrayBuffer.isView(e)?(t.boundary=16,t.storage=e.byteLength):q(`WebGLRenderer: Unsupported uniform value type.`,e),t}function v(t){let n=t.target;n.removeEventListener(`dispose`,v);let r=o.indexOf(n.__bindingPointIndex);o.splice(r,1),e.deleteBuffer(i[n.id]),delete i[n.id],delete a[n.id]}function y(){for(let t in i)e.deleteBuffer(i[t]);o=[],i={},a={}}return{bind:c,update:l,dispose:y}}var Zj=new Uint16Array([12469,15057,12620,14925,13266,14620,13807,14376,14323,13990,14545,13625,14713,13328,14840,12882,14931,12528,14996,12233,15039,11829,15066,11525,15080,11295,15085,10976,15082,10705,15073,10495,13880,14564,13898,14542,13977,14430,14158,14124,14393,13732,14556,13410,14702,12996,14814,12596,14891,12291,14937,11834,14957,11489,14958,11194,14943,10803,14921,10506,14893,10278,14858,9960,14484,14039,14487,14025,14499,13941,14524,13740,14574,13468,14654,13106,14743,12678,14818,12344,14867,11893,14889,11509,14893,11180,14881,10751,14852,10428,14812,10128,14765,9754,14712,9466,14764,13480,14764,13475,14766,13440,14766,13347,14769,13070,14786,12713,14816,12387,14844,11957,14860,11549,14868,11215,14855,10751,14825,10403,14782,10044,14729,9651,14666,9352,14599,9029,14967,12835,14966,12831,14963,12804,14954,12723,14936,12564,14917,12347,14900,11958,14886,11569,14878,11247,14859,10765,14828,10401,14784,10011,14727,9600,14660,9289,14586,8893,14508,8533,15111,12234,15110,12234,15104,12216,15092,12156,15067,12010,15028,11776,14981,11500,14942,11205,14902,10752,14861,10393,14812,9991,14752,9570,14682,9252,14603,8808,14519,8445,14431,8145,15209,11449,15208,11451,15202,11451,15190,11438,15163,11384,15117,11274,15055,10979,14994,10648,14932,10343,14871,9936,14803,9532,14729,9218,14645,8742,14556,8381,14461,8020,14365,7603,15273,10603,15272,10607,15267,10619,15256,10631,15231,10614,15182,10535,15118,10389,15042,10167,14963,9787,14883,9447,14800,9115,14710,8665,14615,8318,14514,7911,14411,7507,14279,7198,15314,9675,15313,9683,15309,9712,15298,9759,15277,9797,15229,9773,15166,9668,15084,9487,14995,9274,14898,8910,14800,8539,14697,8234,14590,7790,14479,7409,14367,7067,14178,6621,15337,8619,15337,8631,15333,8677,15325,8769,15305,8871,15264,8940,15202,8909,15119,8775,15022,8565,14916,8328,14804,8009,14688,7614,14569,7287,14448,6888,14321,6483,14088,6171,15350,7402,15350,7419,15347,7480,15340,7613,15322,7804,15287,7973,15229,8057,15148,8012,15046,7846,14933,7611,14810,7357,14682,7069,14552,6656,14421,6316,14251,5948,14007,5528,15356,5942,15356,5977,15353,6119,15348,6294,15332,6551,15302,6824,15249,7044,15171,7122,15070,7050,14949,6861,14818,6611,14679,6349,14538,6067,14398,5651,14189,5311,13935,4958,15359,4123,15359,4153,15356,4296,15353,4646,15338,5160,15311,5508,15263,5829,15188,6042,15088,6094,14966,6001,14826,5796,14678,5543,14527,5287,14377,4985,14133,4586,13869,4257,15360,1563,15360,1642,15358,2076,15354,2636,15341,3350,15317,4019,15273,4429,15203,4732,15105,4911,14981,4932,14836,4818,14679,4621,14517,4386,14359,4156,14083,3795,13808,3437,15360,122,15360,137,15358,285,15355,636,15344,1274,15322,2177,15281,2765,15215,3223,15120,3451,14995,3569,14846,3567,14681,3466,14511,3305,14344,3121,14037,2800,13753,2467,15360,0,15360,1,15359,21,15355,89,15346,253,15325,479,15287,796,15225,1148,15133,1492,15008,1749,14856,1882,14685,1886,14506,1783,14324,1608,13996,1398,13702,1183]),Qj=null;function $j(){return Qj===null&&(Qj=new xD(Zj,16,16,DC,mC),Qj.name=`DFG_LUT`,Qj.minFilter=iC,Qj.magFilter=iC,Qj.wrapS=$S,Qj.wrapT=$S,Qj.generateMipmaps=!1,Qj.needsUpdate=!0),Qj}var eM=class{constructor(e={}){let{canvas:t=jw(),context:n=null,depth:r=!0,stencil:i=!1,alpha:a=!1,antialias:o=!1,premultipliedAlpha:s=!0,preserveDrawingBuffer:c=!1,powerPreference:l=`default`,failIfMajorPerformanceCaveat:u=!1,reversedDepthBuffer:d=!1,outputBufferType:f=sC}=e;this.isWebGLRenderer=!0;let p;if(n!==null){if(typeof WebGLRenderingContext<`u`&&n instanceof WebGLRenderingContext)throw Error(`THREE.WebGLRenderer: WebGL 1 is not supported since r163.`);p=n.getContextAttributes().alpha}else p=a;let m=f,h=/* @__PURE__ */ new Set([kC,OC,EC]),g=/* @__PURE__ */ new Set([sC,fC,uC,_C,hC,gC]),_=/* @__PURE__ */ new Uint32Array(4),v=/* @__PURE__ */ new Int32Array(4),y=new X,b=null,x=null,S=[],C=[],w=null;this.domElement=t,this.debug={checkShaderErrors:!0,diagnostics:{keywords:!1},onShaderError:null},this.autoClear=!0,this.autoClearColor=!0,this.autoClearDepth=!0,this.autoClearStencil=!0,this.sortObjects=!0,this.clippingPlanes=[],this.localClippingEnabled=!1,this.toneMapping=0,this.toneMappingExposure=1,this.transmissionResolutionScale=1;let T=this,E=!1,D=null,O=null,k=null,A=null;this._outputColorSpace=bw;let ee=0,te=0,j=null,ne=-1,re=null,M=new fT,ie=new fT,N=null,ae=new QT(0),oe=0,se=t.width,ce=t.height,le=1,ue=null,de=null,fe=new fT(0,0,se,ce),pe=new fT(0,0,se,ce),me=!1,he=new TD,ge=!1,_e=!1,ve=new _T,ye=new X,be=new fT,xe={background:null,fog:null,environment:null,overrideMaterial:null,isScene:!0},Se=!1;function Ce(){return j===null?le:1}let P=n;function we(e,n){return t.getContext(e,n)}let Te,Ee,F,De,I,L,Oe,ke,Ae,je,Me,Ne,Pe,Fe,Ie,Le,Re,ze,Be,Ve,He,Ue,We;try{let e={alpha:!0,depth:r,stencil:i,antialias:o,premultipliedAlpha:s,preserveDrawingBuffer:c,powerPreference:l,failIfMajorPerformanceCaveat:u};if(`setAttribute`in t&&t.setAttribute(`data-engine`,`three.js r186`),t.addEventListener(`webglcontextlost`,qe,!1),t.addEventListener(`webglcontextrestored`,Je,!1),t.addEventListener(`webglcontextcreationerror`,Ye,!1),P===null){let t=`webgl2`;if(P=we(t,e),P===null)throw we(t)?Error(`THREE.WebGLRenderer: Error creating WebGL context with your selected attributes.`):Error(`THREE.WebGLRenderer: Error creating WebGL context.`)}Ge()}catch(e){throw t.removeEventListener(`webglcontextlost`,qe,!1),t.removeEventListener(`webglcontextrestored`,Je,!1),t.removeEventListener(`webglcontextcreationerror`,Ye,!1),J(`WebGLRenderer: `+e.message),e}function Ge(){Te=new vk(P),Te.init(),He=new Hj(P,Te),Ee=new qO(P,Te,e,He),F=new Bj(P,Te),Ee.reversedDepthBuffer&&d&&F.buffers.depth.setReversed(!0),O=P.createFramebuffer(),k=P.createFramebuffer(),A=P.createFramebuffer(),De=new xk(P),I=new bj,L=new Vj(P,Te,F,I,Ee,He,De),Oe=new _k(T),ke=new zO(P),Ue=new GO(P,ke),Ae=new yk(P,ke,De,Ue),je=new Ck(P,Ae,ke,Ue,De),ze=new Sk(P,Ee,L),Ie=new JO(I),Me=new yj(T,Oe,Te,Ee,Ue,Ie),Ne=new Yj(T,I),Pe=new wj,Fe=new jj(Te),Re=new WO(T,Oe,F,je,p,s),Le=new zj(T,je,Ee),We=new Xj(P,De,Ee,F),Be=new KO(P,Te,De),Ve=new bk(P,Te,De),De.programs=Me.programs,T.capabilities=Ee,T.extensions=Te,T.properties=I,T.renderLists=Pe,T.shadowMap=Le,T.state=F,T.info=De}m!==1009&&(w=new Tk(m,t.width,t.height,o,r,i));let Ke=new Kj(T,P);this.xr=Ke,this.getContext=function(){return P},this.getContextAttributes=function(){return P.getContextAttributes()},this.forceContextLoss=function(){let e=Te.get(`WEBGL_lose_context`);e&&e.loseContext()},this.forceContextRestore=function(){let e=Te.get(`WEBGL_lose_context`);e&&e.restoreContext()},this.getPixelRatio=function(){return le},this.setPixelRatio=function(e){e!==void 0&&(le=e,this.setSize(se,ce,!1))},this.getSize=function(e){return e.set(se,ce)},this.setSize=function(e,n,r=!0){if(Ke.isPresenting){q(`WebGLRenderer: Can't change size while VR device is presenting.`);return}se=e,ce=n,t.width=Math.floor(e*le),t.height=Math.floor(n*le),r===!0&&(t.style.width=e+`px`,t.style.height=n+`px`),w!==null&&w.setSize(t.width,t.height),this.setViewport(0,0,e,n)},this.getDrawingBufferSize=function(e){return e.set(se*le,ce*le).floor()},this.setDrawingBufferSize=function(e,n,r){se=e,ce=n,le=r,t.width=Math.floor(e*r),t.height=Math.floor(n*r),this.setViewport(0,0,e,n)},this.setEffects=function(e){if(m===1009){J(`WebGLRenderer: setEffects() requires outputBufferType set to HalfFloatType or FloatType.`);return}if(e){for(let t=0;t<e.length;t++)if(e[t].isOutputPass===!0){q(`WebGLRenderer: OutputPass is not needed in setEffects(). Tone mapping and color space conversion are applied automatically.`);break}}w.setEffects(e||[])},this.getCurrentViewport=function(e){return e.copy(M)},this.getViewport=function(e){return e.copy(fe)},this.setViewport=function(e,t,n,r){e.isVector4?fe.set(e.x,e.y,e.z,e.w):fe.set(e,t,n,r),F.viewport(M.copy(fe).multiplyScalar(le).round())},this.getScissor=function(e){return e.copy(pe)},this.setScissor=function(e,t,n,r){e.isVector4?pe.set(e.x,e.y,e.z,e.w):pe.set(e,t,n,r),F.scissor(ie.copy(pe).multiplyScalar(le).round())},this.getScissorTest=function(){return me},this.setScissorTest=function(e){F.setScissorTest(me=e)},this.setOpaqueSort=function(e){ue=e},this.setTransparentSort=function(e){de=e},this.getClearColor=function(e){return e.copy(Re.getClearColor())},this.setClearColor=function(){Re.setClearColor(...arguments)},this.getClearAlpha=function(){return Re.getClearAlpha()},this.setClearAlpha=function(){Re.setClearAlpha(...arguments)},this.clear=function(e=!0,t=!0,n=!0){let r=0;if(e){let e=!1;if(j!==null){let t=j.texture.format;e=h.has(t)}if(e){let e=j.texture.type,t=g.has(e),n=Re.getClearColor(),r=Re.getClearAlpha(),i=n.r,a=n.g,o=n.b;t?(_[0]=i,_[1]=a,_[2]=o,_[3]=r,P.clearBufferuiv(P.COLOR,0,_)):(v[0]=i,v[1]=a,v[2]=o,v[3]=r,P.clearBufferiv(P.COLOR,0,v))}else r|=P.COLOR_BUFFER_BIT}t&&(r|=P.DEPTH_BUFFER_BIT,this.state.buffers.depth.setMask(!0)),n&&(r|=P.STENCIL_BUFFER_BIT,this.state.buffers.stencil.setMask(4294967295)),r!==0&&P.clear(r)},this.clearColor=function(){this.clear(!0,!1,!1)},this.clearDepth=function(){this.clear(!1,!0,!1)},this.clearStencil=function(){this.clear(!1,!1,!0)},this.setNodesHandler=function(e){e.setRenderer(this),D=e},this.dispose=function(){t.removeEventListener(`webglcontextlost`,qe,!1),t.removeEventListener(`webglcontextrestored`,Je,!1),t.removeEventListener(`webglcontextcreationerror`,Ye,!1),Re.dispose(),Pe.dispose(),Fe.dispose(),I.dispose(),Oe.dispose(),je.dispose(),Ue.dispose(),We.dispose(),Me.dispose(),Ke.dispose(),Ke.removeEventListener(`sessionstart`,nt),Ke.removeEventListener(`sessionend`,rt),it.stop()};function qe(e){e.preventDefault(),Nw(`WebGLRenderer: Context Lost.`),E=!0}function Je(){Nw(`WebGLRenderer: Context Restored.`),E=!1;let e=De.autoReset,t=Le.enabled,n=Le.autoUpdate,r=Le.needsUpdate,i=Le.type;Ge(),De.autoReset=e,Le.enabled=t,Le.autoUpdate=n,Le.needsUpdate=r,Le.type=i}function Ye(e){J(`WebGLRenderer: A WebGL context could not be created. Reason: `,e.statusMessage)}function Xe(e){let t=e.target;t.removeEventListener(`dispose`,Xe),Ze(t)}function Ze(e){Qe(e),I.remove(e)}function Qe(e){let t=I.get(e).programs;t!==void 0&&(t.forEach(function(e){Me.releaseProgram(e)}),e.isShaderMaterial&&Me.releaseShaderCache(e))}this.renderBufferDirect=function(e,t,n,r,i,a){t===null&&(t=xe);let o=i.isMesh&&i.matrixWorld.determinantAffine()<0,s=R(e,t,n,r,i);F.setMaterial(r,o);let c=n.index,l=1;if(r.wireframe===!0){if(c=Ae.getWireframeAttribute(n),c===void 0)return;l=2}let u=n.drawRange,d=n.attributes.position,f=u.start*l,p=(u.start+u.count)*l;a!==null&&(f=Math.max(f,a.start*l),p=Math.min(p,(a.start+a.count)*l)),c===null?d!=null&&(f=Math.max(f,0),p=Math.min(p,d.count)):(f=Math.max(f,0),p=Math.min(p,c.count));let m=p-f;if(m<0||m===1/0)return;Ue.setup(i,r,s,n,c);let h,g=Be;if(c!==null&&(h=ke.get(c),g=Ve,g.setIndex(h)),i.isMesh)r.wireframe===!0?(F.setLineWidth(r.wireframeLinewidth*Ce()),g.setMode(P.LINES)):g.setMode(P.TRIANGLES);else if(i.isLine){let e=r.linewidth;e===void 0&&(e=1),F.setLineWidth(e*Ce()),i.isLineSegments?g.setMode(P.LINES):i.isLineLoop?g.setMode(P.LINE_LOOP):g.setMode(P.LINE_STRIP)}else i.isPoints?g.setMode(P.POINTS):i.isSprite&&g.setMode(P.TRIANGLES);if(i.isBatchedMesh){if(Te.get(`WEBGL_multi_draw`))g.renderMultiDraw(i._multiDrawStarts,i._multiDrawCounts,i._multiDrawCount);else{let e=i._multiDrawStarts,t=i._multiDrawCounts,n=i._multiDrawCount,a=c?ke.get(c).bytesPerElement:1,o=I.get(r).currentProgram.getUniforms();for(let r=0;r<n;r++)o.setValue(P,`_gl_DrawID`,r),g.render(e[r]/a,t[r])}}else if(i.isInstancedMesh)g.renderInstances(f,m,i.count);else if(n.isInstancedBufferGeometry){let e=n._maxInstanceCount===void 0?1/0:n._maxInstanceCount,t=Math.min(n.instanceCount,e);g.renderInstances(f,m,t)}else g.render(f,m)};function $e(e,t,n,r){D!==null&&e.isNodeMaterial&&D.setObject(r,e),ge===!0&&Ie.setState(e,n,!1),e.transparent===!0&&e.side===2&&e.forceSinglePass===!1?(e.side=1,e.needsUpdate=!0,ut(e,t,r),e.side=0,e.needsUpdate=!0,ut(e,t,r),e.side=2):ut(e,t,r)}this.compile=function(e,t,n=null){n===null&&(n=e),D!==null&&D.renderStart(e,t,n),x=Fe.get(n),x.init(t),C.push(x),n.traverseVisible(function(e){e.isLight&&e.layers.test(t.layers)&&(x.pushLight(e),e.castShadow&&x.pushShadow(e))}),e!==n&&e.traverseVisible(function(e){e.isLight&&e.layers.test(t.layers)&&(x.pushLight(e),e.castShadow&&x.pushShadow(e))}),x.setupLights(),D!==null&&D.updateLights(x.state.lightsArray),_e=this.localClippingEnabled,ge=Ie.init(this.clippingPlanes,_e),ge===!0&&Ie.setGlobalState(this.clippingPlanes,t),D!==null&&Le.render(x.state.shadowsArray,n,t);let r=/* @__PURE__ */ new Set;return e.traverse(function(e){if(!(e.isMesh||e.isPoints||e.isLine||e.isSprite))return;let i=e.material;if(i){if(Array.isArray(i))for(let a=0;a<i.length;a++){let o=i[a];$e(o,n,t,e),r.add(o)}else $e(i,n,t,e),r.add(i)}}),x=C.pop(),D!==null&&D.renderEnd(),r},this.compileAsync=function(e,t,n=null){let r=this.compile(e,t,n);return new Promise(t=>{function n(){if(r.forEach(function(e){let t=I.get(e).currentProgram;(t===void 0||t.isReady())&&r.delete(e)}),r.size===0){t(e);return}setTimeout(n,10)}Te.get(`KHR_parallel_shader_compile`)===null?setTimeout(n,10):n()})};let et=null;function tt(e){et&&et(e)}function nt(){it.stop()}function rt(){it.start()}let it=new RO;it.setAnimationLoop(tt),typeof self<`u`&&it.setContext(self),this.setAnimationLoop=function(e){et=e,Ke.setAnimationLoop(e),e===null?it.stop():it.start()},Ke.addEventListener(`sessionstart`,nt),Ke.addEventListener(`sessionend`,rt),this.render=function(e,t){if(t!==void 0&&t.isCamera!==!0){J(`WebGLRenderer.render: camera is not an instance of THREE.Camera.`);return}if(E===!0)return;D!==null&&D.renderStart(e,t);let n=Ke.enabled===!0&&Ke.isPresenting===!0,r=w!==null&&(j===null||n)&&w.begin(T,j);if(e.matrixWorldAutoUpdate===!0&&e.updateMatrixWorld(),t.parent===null&&t.matrixWorldAutoUpdate===!0&&t.updateMatrixWorld(),Ke.enabled===!0&&Ke.isPresenting===!0&&(w===null||w.isCompositing()===!1)&&(Ke.cameraAutoUpdate===!0&&Ke.updateCamera(t),t=Ke.getCamera()),e.isScene===!0&&e.onBeforeRender(T,e,t,j),x=Fe.get(e,C.length),x.init(t),x.state.textureUnits=L.getTextureUnits(),C.push(x),ve.multiplyMatrices(t.projectionMatrix,t.matrixWorldInverse),he.setFromProjectionMatrix(ve,Dw,t.reversedDepth),_e=this.localClippingEnabled,ge=Ie.init(this.clippingPlanes,_e),b=Pe.get(e,S.length),b.init(),S.push(b),Ke.enabled===!0&&Ke.isPresenting===!0){let e=T.xr.getDepthSensingMesh();e!==null&&at(e,t,-1/0,T.sortObjects)}at(e,t,0,T.sortObjects),b.finish(),D!==null&&D.updateLights(x.state.lightsArray),T.sortObjects===!0&&b.sort(ue,de),Se=Ke.enabled===!1||Ke.isPresenting===!1||Ke.hasDepthSensing()===!1,Se&&Re.addToRenderList(b,e),this.info.render.frame++,this.info.autoReset===!0&&this.info.reset(),ge===!0&&Ie.beginShadows();let i=x.state.shadowsArray;if(Le.render(i,e,t),ge===!0&&Ie.endShadows(),(r&&w.hasRenderPass())===!1){let n=b.opaque,r=b.transmissive;if(x.setupLights(),t.isArrayCamera){let i=t.cameras;if(r.length>0)for(let t=0,a=i.length;t<a;t++){let a=i[t];st(n,r,e,a)}Se&&Re.render(e);for(let t=0,n=i.length;t<n;t++){let n=i[t];ot(b,e,n,n.viewport)}}else r.length>0&&st(n,r,e,t),Se&&Re.render(e),ot(b,e,t)}j!==null&&te===0&&(L.updateMultisampleRenderTarget(j),L.updateRenderTargetMipmap(j)),r&&w.end(T),e.isScene===!0&&e.onAfterRender(T,e,t),Ue.resetDefaultState(),ne=-1,re=null,C.pop(),C.length>0?(x=C[C.length-1],L.setTextureUnits(x.state.textureUnits),ge===!0&&Ie.setGlobalState(T.clippingPlanes,x.state.camera)):x=null,S.pop(),b=S.length>0?S[S.length-1]:null,D!==null&&D.renderEnd()};function at(e,t,n,r){if(e.visible===!1)return;if(e.layers.test(t.layers)){if(e.isGroup)n=e.renderOrder;else if(e.isLOD)e.autoUpdate===!0&&e.update(t);else if(e.isLightProbeGrid)x.pushLightProbeGrid(e);else if(e.isLight)x.pushLight(e),e.castShadow&&x.pushShadow(e);else if(e.isSprite){if(!e.frustumCulled||e.intersectsFrustum(he)){r&&be.setFromMatrixPosition(e.matrixWorld).applyMatrix4(ve);let i=je.update(e),a=e.material;a.visible&&b.push(e,i,a,n,be.z,null,t)}}else if((e.isMesh||e.isLine||e.isPoints)&&(!e.frustumCulled||e.intersectsFrustum(he))){let i=je.update(e),a=e.material;if(r&&(e.boundingSphere===void 0?(i.boundingSphere===null&&i.computeBoundingSphere(),be.copy(i.boundingSphere.center)):(e.boundingSphere===null&&e.computeBoundingSphere(),be.copy(e.boundingSphere.center)),be.applyMatrix4(e.matrixWorld).applyMatrix4(ve)),Array.isArray(a)){let r=i.groups;for(let o=0,s=r.length;o<s;o++){let s=r[o],c=a[s.materialIndex];c&&c.visible&&b.push(e,i,c,n,be.z,s,t)}}else a.visible&&b.push(e,i,a,n,be.z,null,t)}}let i=e.children;for(let e=0,a=i.length;e<a;e++)at(i[e],t,n,r)}function ot(e,t,n,r){let{opaque:i,transmissive:a,transparent:o}=e;x.setupLightsView(n),ge===!0&&Ie.setGlobalState(T.clippingPlanes,n),r&&F.viewport(M.copy(r)),i.length>0&&ct(i,t,n),a.length>0&&ct(a,t,n),o.length>0&&ct(o,t,n),F.buffers.depth.setTest(!0),F.buffers.depth.setMask(!0),F.buffers.color.setMask(!0),F.setPolygonOffset(!1)}function st(e,t,n,r){if((n.isScene===!0?n.overrideMaterial:null)!==null)return;if(x.state.transmissionRenderTarget[r.id]===void 0){let e=Te.has(`EXT_color_buffer_half_float`)||Te.has(`EXT_color_buffer_float`);x.state.transmissionRenderTarget[r.id]=new mT(1,1,{generateMipmaps:!0,type:e?mC:sC,minFilter:oC,samples:Math.max(4,Ee.samples),stencilBuffer:i,resolveDepthBuffer:!1,resolveStencilBuffer:!1,storeMultisampledDepthBuffer:!1,storeMultisampledStencilBuffer:!1,colorSpace:tT.workingColorSpace})}let a=x.state.transmissionRenderTarget[r.id],o=r.viewport||M;a.setSize(o.z*T.transmissionResolutionScale,o.w*T.transmissionResolutionScale);let s=T.getRenderTarget(),c=T.getActiveCubeFace(),l=T.getActiveMipmapLevel();T.setRenderTarget(a),T.getClearColor(ae),oe=T.getClearAlpha(),oe<1&&T.setClearColor(16777215,.5),T.clear(),Se&&Re.render(n);let u=T.toneMapping;T.toneMapping=0;let d=r.viewport;if(r.viewport!==void 0&&(r.viewport=void 0),x.setupLightsView(r),ge===!0&&Ie.setGlobalState(T.clippingPlanes,r),ct(e,n,r),L.updateMultisampleRenderTarget(a),L.updateRenderTargetMipmap(a),Te.has(`WEBGL_multisampled_render_to_texture`)===!1){let e=!1;for(let i=0,a=t.length;i<a;i++){let{object:a,geometry:o,material:s,group:c}=t[i];if(s.side===2&&a.layers.test(r.layers)){let t=s.side;s.side=1,s.needsUpdate=!0,lt(a,n,r,o,s,c),s.side=t,s.needsUpdate=!0,e=!0}}e===!0&&(L.updateMultisampleRenderTarget(a),L.updateRenderTargetMipmap(a))}T.setRenderTarget(s,c,l),T.setClearColor(ae,oe),d!==void 0&&(r.viewport=d),T.toneMapping=u}function ct(e,t,n){let r=t.isScene===!0?t.overrideMaterial:null;for(let i=0,a=e.length;i<a;i++){let a=e[i],{object:o,geometry:s,group:c}=a,l=a.material;l.allowOverride===!0&&r!==null&&(l=r),o.layers.test(n.layers)&<(o,t,n,s,l,c)}}function lt(e,t,n,r,i,a){D!==null&&i.isNodeMaterial&&D.setObject(e,i),e.onBeforeRender(T,t,n,r,i,a),e.modelViewMatrix.multiplyMatrices(n.matrixWorldInverse,e.matrixWorld),e.normalMatrix.getNormalMatrix(e.modelViewMatrix),i.onBeforeRender(T,t,n,r,e,a),i.transparent===!0&&i.side===2&&i.forceSinglePass===!1?(i.side=1,i.needsUpdate=!0,T.renderBufferDirect(n,t,r,i,e,a),i.side=0,i.needsUpdate=!0,T.renderBufferDirect(n,t,r,i,e,a),i.side=2):T.renderBufferDirect(n,t,r,i,e,a),e.onAfterRender(T,t,n,r,i,a)}function ut(e,t,n){t.isScene!==!0&&(t=xe);let r=I.get(e),i=x.state.lights,a=x.state.shadowsArray,o=i.state.version,s=Me.getParameters(e,i.state,a,t,n,x.state.lightProbeGridArray),c=Me.getProgramCacheKey(s),l=r.programs;r.environment=e.isMeshStandardMaterial||e.isMeshLambertMaterial||e.isMeshPhongMaterial?t.environment:null,r.fog=t.fog;let u=e.isMeshStandardMaterial||e.isMeshLambertMaterial&&!e.envMap||e.isMeshPhongMaterial&&!e.envMap;r.envMap=Oe.get(e.envMap||r.environment,u),r.envMapRotation=r.environment!==null&&e.envMap===null?t.environmentRotation:e.envMapRotation,l===void 0&&(e.addEventListener(`dispose`,Xe),l=/* @__PURE__ */ new Map,r.programs=l);let d=l.get(c);if(d!==void 0){if(r.currentProgram===d&&r.lightsStateVersion===o)return ft(e,s),d}else s.uniforms=Me.getUniforms(e),D!==null&&e.isNodeMaterial&&D.build(e,n,s),e.onBeforeCompile(s,T),d=Me.acquireProgram(s,c),l.set(c,d),r.uniforms=s.uniforms;let f=r.uniforms;return(!e.isShaderMaterial&&!e.isRawShaderMaterial||e.clipping===!0)&&(f.clippingPlanes=Ie.uniform),ft(e,s),r.needsLights=ht(e),r.lightsStateVersion=o,r.needsLights&&(f.ambientLightColor.value=i.state.ambient,f.lightProbe.value=i.state.probe,f.sunLights.value=i.state.sun,f.sunLightShadows.value=i.state.sunShadow,f.directionalLights.value=i.state.directional,f.directionalLightShadows.value=i.state.directionalShadow,f.spotLights.value=i.state.spot,f.spotLightShadows.value=i.state.spotShadow,f.rectAreaLights.value=i.state.rectArea,f.ltc_1.value=i.state.rectAreaLTC1,f.ltc_2.value=i.state.rectAreaLTC2,f.pointLights.value=i.state.point,f.pointLightShadows.value=i.state.pointShadow,f.hemisphereLights.value=i.state.hemi,f.sunShadowMatrix.value=i.state.sunShadowMatrix,f.sunShadowCascade.value=i.state.sunShadowCascade,f.directionalShadowMatrix.value=i.state.directionalShadowMatrix,f.spotLightMatrix.value=i.state.spotLightMatrix,f.spotLightMap.value=i.state.spotLightMap,f.pointShadowMatrix.value=i.state.pointShadowMatrix),r.lightProbeGrid=x.state.lightProbeGridArray.length>0,r.currentProgram=d,r.uniformsList=null,d}function dt(e){if(e.uniformsList===null){let t=e.currentProgram.getUniforms();e.uniformsList=MA.seqWithValue(t.seq,e.uniforms)}return e.uniformsList}function ft(e,t){let n=I.get(e);n.outputColorSpace=t.outputColorSpace,n.batching=t.batching,n.batchingColor=t.batchingColor,n.instancing=t.instancing,n.instancingColor=t.instancingColor,n.instancingMorph=t.instancingMorph,n.skinning=t.skinning,n.morphTargets=t.morphTargets,n.morphNormals=t.morphNormals,n.morphColors=t.morphColors,n.morphTargetsCount=t.morphTargetsCount,n.numClippingPlanes=t.numClippingPlanes,n.numIntersection=t.numClipIntersection,n.vertexAlphas=t.vertexAlphas,n.vertexTangents=t.vertexTangents,n.toneMapping=t.toneMapping}function pt(e,t){if(e.length===0)return null;if(e.length===1)return e[0].texture===null?null:e[0];y.setFromMatrixPosition(t.matrixWorld);for(let t=0,n=e.length;t<n;t++){let n=e[t];if(n.texture!==null&&n.boundingBox.containsPoint(y))return n}return null}function R(e,t,n,r,i){t.isScene!==!0&&(t=xe),L.resetTextureUnits();let a=t.fog,o=r.isMeshStandardMaterial||r.isMeshLambertMaterial||r.isMeshPhongMaterial?t.environment:null,s=j===null?T.outputColorSpace:j.isXRRenderTarget===!0?j.texture.colorSpace:tT.workingColorSpace,c=r.isMeshStandardMaterial||r.isMeshLambertMaterial&&!r.envMap||r.isMeshPhongMaterial&&!r.envMap,l=Oe.get(r.envMap||o,c),u=r.vertexColors===!0&&!!n.attributes.color&&n.attributes.color.itemSize===4,d=!!n.attributes.tangent&&(!!r.normalMap||r.anisotropy>0),f=!!n.morphAttributes.position,p=!!n.morphAttributes.normal,m=!!n.morphAttributes.color,h=0;r.toneMapped&&(j===null||j.isXRRenderTarget===!0)&&(h=T.toneMapping);let g=n.morphAttributes.position||n.morphAttributes.normal||n.morphAttributes.color,_=g===void 0?0:g.length,v=I.get(r),y=x.state.lights;if(ge===!0&&(_e===!0||e!==re)){let t=e===re&&r.id===ne;Ie.setState(r,e,t)}let b=!1;r.version===v.__version?v.needsLights&&v.lightsStateVersion!==y.state.version?b=!0:v.outputColorSpace===s?i.isBatchedMesh&&v.batching===!1||!i.isBatchedMesh&&v.batching===!0||i.isBatchedMesh&&v.batchingColor===!0&&i._colorsTexture===null||i.isBatchedMesh&&v.batchingColor===!1&&i._colorsTexture!==null||i.isInstancedMesh&&v.instancing===!1||!i.isInstancedMesh&&v.instancing===!0||i.isSkinnedMesh&&v.skinning===!1||!i.isSkinnedMesh&&v.skinning===!0||i.isInstancedMesh&&v.instancingColor===!0&&i.instanceColor===null||i.isInstancedMesh&&v.instancingColor===!1&&i.instanceColor!==null||i.isInstancedMesh&&v.instancingMorph===!0&&i.morphTexture===null||i.isInstancedMesh&&v.instancingMorph===!1&&i.morphTexture!==null?b=!0:v.envMap===l?r.fog===!0&&v.fog!==a||v.numClippingPlanes!==void 0&&(v.numClippingPlanes!==Ie.numPlanes||v.numIntersection!==Ie.numIntersection)?b=!0:v.vertexAlphas===u&&v.vertexTangents===d&&v.morphTargets===f&&v.morphNormals===p&&v.morphColors===m&&v.toneMapping===h&&v.morphTargetsCount===_?!!v.lightProbeGrid!=x.state.lightProbeGridArray.length>0&&(b=!0):b=!0:b=!0:b=!0:(b=!0,v.__version=r.version);let S=v.currentProgram;b===!0&&(S=ut(r,t,i),D&&r.isNodeMaterial&&D.onUpdateProgram(r,S,v));let C=!1,w=!1,E=!1,O=S.getUniforms(),k=v.uniforms;if(F.useProgram(S.program)&&(C=!0,w=!0,E=!0),r.id!==ne&&(ne=r.id,w=!0),v.needsLights){let e=pt(x.state.lightProbeGridArray,i);v.lightProbeGrid!==e&&(v.lightProbeGrid=e,w=!0)}if(C||re!==e){F.buffers.depth.getReversed()&&e.reversedDepth!==!0&&(e._reversedDepth=!0,e.updateProjectionMatrix()),O.setValue(P,`projectionMatrix`,e.projectionMatrix),O.setValue(P,`viewMatrix`,e.matrixWorldInverse);let t=O.map.cameraPosition;t!==void 0&&t.setValue(P,ye.setFromMatrixPosition(e.matrixWorld)),Ee.logarithmicDepthBuffer&&O.setValue(P,`logDepthBufFC`,2/(Math.log(e.far+1)/Math.LN2)),(r.isMeshPhongMaterial||r.isMeshToonMaterial||r.isMeshLambertMaterial||r.isMeshBasicMaterial||r.isMeshStandardMaterial||r.isShaderMaterial)&&O.setValue(P,`isOrthographic`,e.isOrthographicCamera===!0),re!==e&&(re=e,w=!0,E=!0)}if(v.needsLights&&(y.state.sunShadowMap.length>0&&O.setValue(P,`sunShadowMap`,y.state.sunShadowMap,L),y.state.directionalShadowMap.length>0&&O.setValue(P,`directionalShadowMap`,y.state.directionalShadowMap,L),y.state.spotShadowMap.length>0&&O.setValue(P,`spotShadowMap`,y.state.spotShadowMap,L),y.state.pointShadowMap.length>0&&O.setValue(P,`pointShadowMap`,y.state.pointShadowMap,L)),i.isSkinnedMesh){O.setOptional(P,i,`bindMatrix`),O.setOptional(P,i,`bindMatrixInverse`);let e=i.skeleton;e&&(e.boneTexture===null&&e.computeBoneTexture(),O.setValue(P,`boneTexture`,e.boneTexture,L))}i.isBatchedMesh&&(O.setOptional(P,i,`batchingTexture`),O.setValue(P,`batchingTexture`,i._matricesTexture,L),O.setOptional(P,i,`batchingIdTexture`),O.setValue(P,`batchingIdTexture`,i._indirectTexture,L),O.setOptional(P,i,`batchingColorTexture`),i._colorsTexture!==null&&O.setValue(P,`batchingColorTexture`,i._colorsTexture,L));let A=n.morphAttributes;if((A.position!==void 0||A.normal!==void 0||A.color!==void 0)&&ze.update(i,n,S),(w||v.receiveShadow!==i.receiveShadow)&&(v.receiveShadow=i.receiveShadow,O.setValue(P,`receiveShadow`,i.receiveShadow)),(r.isMeshStandardMaterial||r.isMeshLambertMaterial||r.isMeshPhongMaterial)&&r.envMap===null&&t.environment!==null&&(k.envMapIntensity.value=t.environmentIntensity),k.dfgLUT!==void 0&&(k.dfgLUT.value=$j()),w){if(O.setValue(P,`toneMappingExposure`,T.toneMappingExposure),v.needsLights&&mt(k,E),a&&r.fog===!0&&Ne.refreshFogUniforms(k,a),Ne.refreshMaterialUniforms(k,r,le,ce,x.state.transmissionRenderTarget[e.id]),v.needsLights&&v.lightProbeGrid){let e=v.lightProbeGrid;k.probesSH.value=e.texture,k.probesMin.value.copy(e.boundingBox.min),k.probesMax.value.copy(e.boundingBox.max),k.probesResolution.value.copy(e.resolution)}MA.upload(P,dt(v),k,L)}if(r.isShaderMaterial&&r.uniformsNeedUpdate===!0&&(MA.upload(P,dt(v),k,L),r.uniformsNeedUpdate=!1),r.isSpriteMaterial&&O.setValue(P,`center`,i.center),O.setValue(P,`modelViewMatrix`,i.modelViewMatrix),O.setValue(P,`normalMatrix`,i.normalMatrix),O.setValue(P,`modelMatrix`,i.matrixWorld),r.uniformsGroups!==void 0){let e=r.uniformsGroups;for(let t=0,n=e.length;t<n;t++){let n=e[t];We.update(n,S),We.bind(n,S)}}return S}function mt(e,t){e.ambientLightColor.needsUpdate=t,e.lightProbe.needsUpdate=t,e.sunLights.needsUpdate=t,e.sunLightShadows.needsUpdate=t,e.directionalLights.needsUpdate=t,e.directionalLightShadows.needsUpdate=t,e.pointLights.needsUpdate=t,e.pointLightShadows.needsUpdate=t,e.spotLights.needsUpdate=t,e.spotLightShadows.needsUpdate=t,e.rectAreaLights.needsUpdate=t,e.hemisphereLights.needsUpdate=t}function ht(e){return e.isMeshLambertMaterial||e.isMeshToonMaterial||e.isMeshPhongMaterial||e.isMeshStandardMaterial||e.isShadowMaterial||e.isShaderMaterial&&e.lights===!0}this.getActiveCubeFace=function(){return ee},this.getActiveMipmapLevel=function(){return te},this.getRenderTarget=function(){return j},this.setRenderTargetTextures=function(e,t,n){let r=I.get(e);r.__autoAllocateDepthBuffer=e.resolveDepthBuffer===!1,r.__autoAllocateDepthBuffer===!1&&(r.__useRenderToTexture=!1),I.get(e.texture).__webglTexture=t,I.get(e.depthTexture).__webglTexture=r.__autoAllocateDepthBuffer?void 0:n,r.__hasExternalTextures=!0},this.setRenderTargetFramebuffer=function(e,t){let n=I.get(e);n.__webglFramebuffer=t,n.__useDefaultFramebuffer=t===void 0},this.setRenderTarget=function(e,t=0,n=0){j=e,ee=t,te=n;let r=null,i=!1,a=!1;if(e){let o=I.get(e);if(o.__useDefaultFramebuffer!==void 0){F.bindFramebuffer(P.FRAMEBUFFER,o.__webglFramebuffer),M.copy(e.viewport),ie.copy(e.scissor),N=e.scissorTest,F.viewport(M),F.scissor(ie),F.setScissorTest(N),ne=-1;return}if(o.__webglFramebuffer===void 0)L.setupRenderTarget(e);else if(o.__hasExternalTextures)L.rebindTextures(e,I.get(e.texture).__webglTexture,I.get(e.depthTexture).__webglTexture);else if(e.depthBuffer){let t=e.depthTexture;if(o.__boundDepthTexture!==t){if(t!==null&&I.has(t)&&(e.width!==t.image.width||e.height!==t.image.height))throw Error(`THREE.WebGLRenderer: Attached DepthTexture is initialized to the incorrect size.`);L.setupDepthRenderbuffer(e)}}let s=e.texture;(s.isData3DTexture||s.isDataArrayTexture||s.isCompressedArrayTexture)&&(a=!0);let c=I.get(e).__webglFramebuffer;e.isWebGLCubeRenderTarget?(r=Array.isArray(c[t])?c[t][n]:c[t],i=!0):r=e.samples>0&&L.useMultisampledRTT(e)===!1?I.get(e).__webglMultisampledFramebuffer:Array.isArray(c)?c[n]:c,M.copy(e.viewport),ie.copy(e.scissor),N=e.scissorTest}else M.copy(fe).multiplyScalar(le).floor(),ie.copy(pe).multiplyScalar(le).floor(),N=me;if(n!==0&&(r=O),F.bindFramebuffer(P.FRAMEBUFFER,r)&&F.drawBuffers(e,r),F.viewport(M),F.scissor(ie),F.setScissorTest(N),i){let r=I.get(e.texture);P.framebufferTexture2D(P.FRAMEBUFFER,P.COLOR_ATTACHMENT0,P.TEXTURE_CUBE_MAP_POSITIVE_X+t,r.__webglTexture,n)}else if(a){let r=t;for(let t=0;t<e.textures.length;t++){let i=I.get(e.textures[t]);P.framebufferTextureLayer(P.FRAMEBUFFER,P.COLOR_ATTACHMENT0+t,i.__webglTexture,n,r)}}else if(e!==null&&n!==0){let t=I.get(e.texture);P.framebufferTexture2D(P.FRAMEBUFFER,P.COLOR_ATTACHMENT0,P.TEXTURE_2D,t.__webglTexture,n)}ne=-1};function gt(e){let t=I.get(e);return(t.__readFormat!==e.format||t.__readType!==e.type)&&(t.__readFormat=e.format,t.__readType=e.type,t.__formatReadable=Ee.textureFormatReadable(e.format),t.__typeReadable=Ee.textureTypeReadable(e.type)),t}this.readRenderTargetPixels=function(e,t,n,r,i,a,o,s=0){if(!(e&&e.isWebGLRenderTarget)){J(`WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.`);return}let c=I.get(e).__webglFramebuffer;if(e.isWebGLCubeRenderTarget&&o!==void 0&&(c=c[o]),c){F.bindFramebuffer(P.FRAMEBUFFER,c);try{let o=e.textures[s],c=o.format,l=o.type;e.textures.length>1&&P.readBuffer(P.COLOR_ATTACHMENT0+s);let u=gt(o);if(u.__formatReadable===!1){J(`WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.`);return}if(u.__typeReadable===!1){J(`WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.`);return}t>=0&&t<=e.width-r&&n>=0&&n<=e.height-i&&P.readPixels(t,n,r,i,He.convert(c),He.convert(l),a)}finally{let e=j===null?null:I.get(j).__webglFramebuffer;F.bindFramebuffer(P.FRAMEBUFFER,e)}}},this.readRenderTargetPixelsAsync=async function(e,t,n,r,i,a,o,s=0){if(!(e&&e.isWebGLRenderTarget))throw Error(`THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.`);let c=I.get(e).__webglFramebuffer;if(e.isWebGLCubeRenderTarget&&o!==void 0&&(c=c[o]),c){if(t>=0&&t<=e.width-r&&n>=0&&n<=e.height-i){F.bindFramebuffer(P.FRAMEBUFFER,c);let o=e.textures[s],l=o.format,u=o.type;e.textures.length>1&&P.readBuffer(P.COLOR_ATTACHMENT0+s);let d=gt(o);if(d.__formatReadable===!1)throw Error(`THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in RGBA or implementation defined format.`);if(d.__typeReadable===!1)throw Error(`THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in UnsignedByteType or implementation defined type.`);let f=P.createBuffer();P.bindBuffer(P.PIXEL_PACK_BUFFER,f),P.bufferData(P.PIXEL_PACK_BUFFER,a.byteLength,P.STREAM_READ),P.readPixels(t,n,r,i,He.convert(l),He.convert(u),0),P.bindBuffer(P.PIXEL_PACK_BUFFER,null);let p=j===null?null:I.get(j).__webglFramebuffer;F.bindFramebuffer(P.FRAMEBUFFER,p);let m=P.fenceSync(P.SYNC_GPU_COMMANDS_COMPLETE,0);return P.flush(),await Iw(P,m,4),P.bindBuffer(P.PIXEL_PACK_BUFFER,f),P.getBufferSubData(P.PIXEL_PACK_BUFFER,0,a),P.bindBuffer(P.PIXEL_PACK_BUFFER,null),P.deleteBuffer(f),P.deleteSync(m),a}throw Error(`THREE.WebGLRenderer.readRenderTargetPixelsAsync: requested read bounds are out of range.`)}},this.copyFramebufferToTexture=function(e,t=null,n=0){let r=2**-n,i=Math.floor(e.image.width*r),a=Math.floor(e.image.height*r),o=t===null?0:t.x,s=t===null?0:t.y;L.setTexture2D(e,0),P.copyTexSubImage2D(P.TEXTURE_2D,n,0,0,o,s,i,a),F.unbindTexture()},this.copyTextureToTexture=function(e,t,n=null,r=null,i=0,a=0){let o,s,c,l,u,d,f,p,m,h=e.isCompressedTexture?e.mipmaps[a]:e.image;if(n!==null)o=n.max.x-n.min.x,s=n.max.y-n.min.y,c=n.isBox3?n.max.z-n.min.z:1,l=n.min.x,u=n.min.y,d=n.isBox3?n.min.z:0;else{let t=2**-i;o=Math.floor(h.width*t),s=Math.floor(h.height*t),c=e.isDataArrayTexture?h.depth:e.isData3DTexture?Math.floor(h.depth*t):1,l=0,u=0,d=0}r===null?(f=0,p=0,m=0):(f=r.x,p=r.y,m=r.z);let g=He.convert(t.format),_=He.convert(t.type),v;t.isData3DTexture?(L.setTexture3D(t,0),v=P.TEXTURE_3D):t.isDataArrayTexture||t.isCompressedArrayTexture?(L.setTexture2DArray(t,0),v=P.TEXTURE_2D_ARRAY):(L.setTexture2D(t,0),v=P.TEXTURE_2D),F.activeTexture(P.TEXTURE0),F.pixelStorei(P.UNPACK_FLIP_Y_WEBGL,t.flipY),F.pixelStorei(P.UNPACK_PREMULTIPLY_ALPHA_WEBGL,t.premultiplyAlpha),F.pixelStorei(P.UNPACK_ALIGNMENT,t.unpackAlignment);let y=F.getParameter(P.UNPACK_ROW_LENGTH),b=F.getParameter(P.UNPACK_IMAGE_HEIGHT),x=F.getParameter(P.UNPACK_SKIP_PIXELS),S=F.getParameter(P.UNPACK_SKIP_ROWS),C=F.getParameter(P.UNPACK_SKIP_IMAGES);F.pixelStorei(P.UNPACK_ROW_LENGTH,h.width),F.pixelStorei(P.UNPACK_IMAGE_HEIGHT,h.height),F.pixelStorei(P.UNPACK_SKIP_PIXELS,l),F.pixelStorei(P.UNPACK_SKIP_ROWS,u),F.pixelStorei(P.UNPACK_SKIP_IMAGES,d);let w=e.isDataArrayTexture||e.isData3DTexture,T=t.isDataArrayTexture||t.isData3DTexture;if(e.isDepthTexture){let n=I.get(e),r=I.get(t),h=I.get(n.__renderTarget),g=I.get(r.__renderTarget);F.bindFramebuffer(P.READ_FRAMEBUFFER,h.__webglFramebuffer),F.bindFramebuffer(P.DRAW_FRAMEBUFFER,g.__webglFramebuffer);for(let n=0;n<c;n++)w&&(P.framebufferTextureLayer(P.READ_FRAMEBUFFER,P.COLOR_ATTACHMENT0,I.get(e).__webglTexture,i,d+n),P.framebufferTextureLayer(P.DRAW_FRAMEBUFFER,P.COLOR_ATTACHMENT0,I.get(t).__webglTexture,a,m+n)),P.blitFramebuffer(l,u,o,s,f,p,o,s,P.DEPTH_BUFFER_BIT,P.NEAREST);F.bindFramebuffer(P.READ_FRAMEBUFFER,null),F.bindFramebuffer(P.DRAW_FRAMEBUFFER,null)}else if(i!==0||e.isRenderTargetTexture||I.has(e)){let n=I.get(e),r=I.get(t);F.bindFramebuffer(P.READ_FRAMEBUFFER,k),F.bindFramebuffer(P.DRAW_FRAMEBUFFER,A);for(let e=0;e<c;e++)w?P.framebufferTextureLayer(P.READ_FRAMEBUFFER,P.COLOR_ATTACHMENT0,n.__webglTexture,i,d+e):P.framebufferTexture2D(P.READ_FRAMEBUFFER,P.COLOR_ATTACHMENT0,P.TEXTURE_2D,n.__webglTexture,i),T?P.framebufferTextureLayer(P.DRAW_FRAMEBUFFER,P.COLOR_ATTACHMENT0,r.__webglTexture,a,m+e):P.framebufferTexture2D(P.DRAW_FRAMEBUFFER,P.COLOR_ATTACHMENT0,P.TEXTURE_2D,r.__webglTexture,a),i===0?T?P.copyTexSubImage3D(v,a,f,p,m+e,l,u,o,s):P.copyTexSubImage2D(v,a,f,p,l,u,o,s):P.blitFramebuffer(l,u,o,s,f,p,o,s,P.COLOR_BUFFER_BIT,P.NEAREST);F.bindFramebuffer(P.READ_FRAMEBUFFER,null),F.bindFramebuffer(P.DRAW_FRAMEBUFFER,null)}else T?e.isDataTexture||e.isData3DTexture?P.texSubImage3D(v,a,f,p,m,o,s,c,g,_,h.data):t.isCompressedArrayTexture?P.compressedTexSubImage3D(v,a,f,p,m,o,s,c,g,h.data):P.texSubImage3D(v,a,f,p,m,o,s,c,g,_,h):e.isDataTexture?P.texSubImage2D(P.TEXTURE_2D,a,f,p,o,s,g,_,h.data):e.isCompressedTexture?P.compressedTexSubImage2D(P.TEXTURE_2D,a,f,p,h.width,h.height,g,h.data):P.texSubImage2D(P.TEXTURE_2D,a,f,p,o,s,g,_,h);F.pixelStorei(P.UNPACK_ROW_LENGTH,y),F.pixelStorei(P.UNPACK_IMAGE_HEIGHT,b),F.pixelStorei(P.UNPACK_SKIP_PIXELS,x),F.pixelStorei(P.UNPACK_SKIP_ROWS,S),F.pixelStorei(P.UNPACK_SKIP_IMAGES,C),a===0&&t.generateMipmaps&&P.generateMipmap(v),F.unbindTexture()},this.initRenderTarget=function(e){I.get(e).__webglFramebuffer===void 0&&L.setupRenderTarget(e)},this.initTexture=function(e){e.isCubeTexture?L.setTextureCube(e,0):e.isData3DTexture?L.setTexture3D(e,0):e.isDataArrayTexture||e.isCompressedArrayTexture?L.setTexture2DArray(e,0):L.setTexture2D(e,0),F.unbindTexture()},this.resetState=function(){ee=0,te=0,j=null,F.reset(),Ue.reset()},typeof __THREE_DEVTOOLS__<`u`&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent(`observe`,{detail:this}))}get coordinateSystem(){return Dw}get outputColorSpace(){return this._outputColorSpace}set outputColorSpace(e){this._outputColorSpace=e;let t=this.getContext();t.drawingBufferColorSpace=tT._getDrawingBufferColorSpace(e),t.unpackColorSpace=tT._getUnpackColorSpace()}},tM={request:e=>{e()},cancel:()=>{}};function nM(e){return new Z().set(...e)}var rM=class{lenses;uniform;named;constructor(e,t){this.lenses=e,this.uniform=t,this.named=Array.from({length:e.length})}follow(e){for(let[t,n]of this.lenses.entries()){let r=e[n.frameSlot];if(!r)continue;let i=gu(hu,r.colorSpace.matrix);i!==this.named[t]&&(this.named[t]=i,this.uniform.value[t]=nM(Au(n.displayConversion.matrix,i)))}}};function iM(e){return Number.isSafeInteger(e)?e.toFixed(1):String(e)}var aM=0,oM=1,sM=[[`CONVERSION_HLG_TO_SDR_BT709`,oM],[`HLG_A`,iM(_u.a)],[`HLG_B`,iM(_u.b)],[`HLG_C`,iM(_u.c)],[`HLG_SEGMENT_JOIN`,iM(_u.segmentJoin)],[`HLG_SQUARE_SEGMENT_DIVISOR`,iM(_u.squareSegmentDivisor)],[`HLG_LOG_SEGMENT_DIVISOR`,iM(_u.logSegmentDivisor)],[`BT709_LUMINANCE_RED`,iM(yu[0])],[`BT709_LUMINANCE_GREEN`,iM(yu[1])],[`BT709_LUMINANCE_BLUE`,iM(yu[2])]];function cM(e){let t=e.map(e=>lM(e.displayConversion));return{uLensConversion:{value:t.map(e=>e.kind)},uLensMatrixCorrection:{value:e.map(()=>nM(Mr))},uLensGamut:{value:t.map(e=>e.gamut)},uLensTone:{value:t.map(e=>e.tone)}}}function lM(e){switch(e.kind){case`as-recorded`:return{kind:aM,gamut:nM(Mr),tone:new fT};case`hlg-to-sdr-bt709`:{let{exposure:t,kneeStart:n,ceiling:r,exponent:i}=e.tone;return{kind:oM,gamut:nM(e.gamut),tone:new fT(t,n,r,i)}}}}var uM={fast:{minFilter:iC,generateMipmaps:!1,anisotropy:1,shaderSampling:0},balanced:{minFilter:oC,generateMipmaps:!0,anisotropy:4,shaderSampling:1},high:{minFilter:oC,generateMipmaps:!0,anisotropy:8,shaderSampling:2}},dM=0,fM=1,pM=Object.fromEntries([[`MAX_LENSES`,2],[`LENS_MEI`,dM],[`LENS_RADIAL_POLYNOMIAL`,fM],[`MEI_RADIAL_TERMS`,oe.radial],[`MEI_TANGENTIAL_ORDERS`,oe.tangential],[`MEI_THIN_PRISM_ORDERS`,oe.thinPrism],...sM,[`SAMPLING_BILINEAR`,0],[`SAMPLING_TRILINEAR`,1],[`SAMPLING_SUPERSAMPLED`,2]]);function mM(e,t){let n=AM(e.lenses,`a stitching setup has one or two lenses`);return{...hM(e),...gM(n),...xM(n),...cM(n),uTexture0:{value:t[0]??null},uTexture1:{value:t[1]??null}}}function hM(e){return{uLensCount:{value:e.lenses.length},uViewRotation:{value:new Z},uStabilization:{value:new Z},uPlaneHalfExtent:{value:1},uPictureAspect:{value:1},uScreenArea:{value:Array.from({length:2},()=>new fT(0,0,1,1))},uFeather:{value:new Y(e.feather.start,e.feather.end)}}}function gM(e){let t=e.map(e=>vM(e.projection));return{uLensRotation:{value:e.map(e=>nM(e.rotation))},uLensKind:{value:t.map(e=>e.kind)},uLensPrincipalPoint:{value:e.map(e=>kM(e.projection.principalPoint))},uLensFocal:{value:t.map(e=>e.focal)},uLensXi:{value:t.map(e=>e.xi)},uLensRadial:{value:t.flatMap(e=>e.radial)},uLensTangential:{value:t.flatMap(e=>e.tangential)},uLensThinPrism:{value:t.flatMap(e=>e.thinPrism)},uLensPolynomial:{value:t.map(e=>e.polynomial)},uLensHalfFov:{value:e.map(e=>e.halfFieldOfView)}}}var _M={radial:[],tangential:[],thinPrism:[]};function vM(e){switch(e.kind){case`mei`:return{kind:dM,focal:new Y(...e.focal),xi:e.xi,...yM(e.distortion),polynomial:new fT};case`radial-polynomial`:return{kind:fM,focal:new Y,xi:0,...yM(_M),polynomial:new fT(...e.coefficients)}}}function yM(e){return{radial:bM(e.radial,oe.radial,()=>0),tangential:bM(e.tangential.map(e=>new Y(e.p1,e.p2)),oe.tangential,()=>new Y),thinPrism:bM(e.thinPrism.map(e=>new Y(e.x,e.y)),oe.thinPrism,()=>new Y)}}function bM(e,t,n){return N(e.length<=t,`a Mei lens has ${e.length} terms of a family the shader holds ${t} of`),Array.from({length:t},(t,r)=>e[r]??n())}function xM(e){return{uLensWindow:{value:e.map(e=>new fT(e.window.x,e.window.y,e.window.width,e.window.height))},uLensRegion:{value:e.map(e=>new fT(e.region.x,e.region.y,e.region.width,e.region.height))},uLensTexture:{value:e.map(e=>e.frameSlot)},uLensGain:{value:e.map(()=>new X(1,1,1))},uSampling:{value:0}}}function SM(e,t){e.uSampling.value=t.shaderSampling}function CM(e,t){e.uStabilization.value=nM(t)}function wM(e,t,n){ae(t,e.uLensCount.value,`lens`),e.uLensGain.value[t]?.set(...n)}var TM={rotation:Mr,planeHalfExtent:1,pictureAspect:1};function EM(e,t,n){let r=DM(t,n);e.uViewRotation.value=nM(r.rotation),e.uPlaneHalfExtent.value=r.planeHalfExtent,e.uPictureAspect.value=r.pictureAspect,e.uScreenArea.value=AM(r.areas,`a picture fills one area per lens at most`).map(e=>OM(e))}function DM(e,t){switch(e.kind){case`rectilinear`:return{rotation:e.rotation,planeHalfExtent:zc(e.fieldOfView),pictureAspect:Bc(e.area,t),areas:[e.area]};case`equirectangular`:return{...TM,rotation:e.rotation,areas:[e.area]};case`lens-tiles`:return{...TM,areas:e.tiles}}}function OM(e){return new fT(e.x,e.y,e.width,e.height)}function kM(e){return new Y(e.x,e.y)}function AM(e,t){let n=e.at(-1);return N(n!==void 0&&e.length<=2,t),Array.from({length:2},(t,r)=>e[r]??n)}var jM=`// One triangle covering the whole viewport; the fragment shader does all the work.
|
|
4223
4223
|
in vec3 position;
|
|
4224
4224
|
out vec2 vNdc;
|
|
4225
4225
|
|
|
@@ -4227,9 +4227,9 @@ void main() {
|
|
|
4227
4227
|
vNdc = position.xy;
|
|
4228
4228
|
gl_Position = vec4(position.xy, 0.0, 1.0);
|
|
4229
4229
|
}
|
|
4230
|
-
`,
|
|
4231
|
-
`),uniforms:{...e},depthTest:!1,depthWrite:!1})}function
|
|
4232
|
-
`)}`)}var
|
|
4230
|
+
`,MM=3,NM=[-1,-1,0,MM,-1,0,-1,MM,0],PM=3;function FM(){let e=new JE;return e.setAttribute(`position`,new IE(NM,PM)),e}function IM(e){return{chunks:e,defines:pM}}function LM(e,t){return new UD({glslVersion:Ew,defines:{...t.defines},vertexShader:jM,fragmentShader:t.chunks.join(`
|
|
4231
|
+
`),uniforms:{...e},depthTest:!1,depthWrite:!1})}function RM(e,t){let n=e.getContext(`webgl2`,{preserveDrawingBuffer:t.preserveDrawingBuffer??!1,antialias:!1,alpha:!1,depth:!1,stencil:!1});if(!n)throw new j(`render-unavailable`,`this browser has no WebGL2 context`);let r=new eM({canvas:e,context:n});return r.setPixelRatio(1),r.debug.onShaderError=(e,t,...n)=>{zM(e,t,n)},r}function zM(e,t,n){throw new j(`render-unavailable`,`a shader did not compile or link: ${[e.getProgramInfoLog(t),...n.map(t=>e.getShaderInfoLog(t))].filter(Boolean).join(`
|
|
4232
|
+
`)}`)}var BM=255;function VM(e,t,n){let r=[];for(let i=0;i<n;i+=1){let n=HM(e.subarray(i*t*4,(i+1)*t*4));if(!n)return;r.push(n)}return r}function HM(e){let t=[0,0,0],n=0;for(let r=0;r+4<=e.length;r+=4)(e[r+4-1]??0)!==0&&(t[0]+=e[r]??0,t[1]+=e[r+1]??0,t[2]+=e[r+2]??0,n+=1);if(n===0)return;let r=n*BM;return[t[0]/r,t[1]/r,t[2]/r]}function UM(e,t,n){e.compile(t,n);let r=e.info.programs??[];for(let e of r)e.getUniforms()}function WM(e,t,n){let r=e.getRenderTarget();e.setRenderTarget(t);try{n()}finally{e.setRenderTarget(r)}}var GM=`in vec2 vNdc;
|
|
4233
4233
|
out vec4 outColor;
|
|
4234
4234
|
|
|
4235
4235
|
// One row per lens: what that lens sees along the seam ring, the circle of directions halfway
|
|
@@ -4250,7 +4250,7 @@ void main() {
|
|
|
4250
4250
|
LensSample seen = sampleLensWith(lens, dirBody, SAMPLING_BILINEAR);
|
|
4251
4251
|
outColor = seen.isImaged ? vec4(seen.signal, 1.0) : vec4(0.0);
|
|
4252
4252
|
}
|
|
4253
|
-
`,
|
|
4253
|
+
`,KM=`// How lens i's texels are brought to the SDR BT.709 display, as the core's exposureSignalOf and
|
|
4254
4254
|
// shownOf (ADR 0033): the browser's upload has applied the track's matrix and range; the
|
|
4255
4255
|
// transfer and primaries are this chunk's. Shown as recorded, or HLG converted to scene light,
|
|
4256
4256
|
// into BT.709 and toned; gain matching scales the exposure signal between the two (ADR 0012).
|
|
@@ -4325,7 +4325,7 @@ vec3 shownOf(int i, vec3 signal) {
|
|
|
4325
4325
|
vec3 toDisplay(int i, vec3 texel) {
|
|
4326
4326
|
return shownOf(i, exposureSignalOf(i, texel));
|
|
4327
4327
|
}
|
|
4328
|
-
`,
|
|
4328
|
+
`,qM=`// An equirectangular picture: a full turn across and a half turn from top to bottom.
|
|
4329
4329
|
|
|
4330
4330
|
// Direction in view space (x right, y down, z forward) seen through a point of the picture, given
|
|
4331
4331
|
// as fractions of the picture from its top-left corner.
|
|
@@ -4335,7 +4335,7 @@ vec3 rayThroughPicture(vec2 point) {
|
|
|
4335
4335
|
float pitch = -centred.y * HALF_PI;
|
|
4336
4336
|
return vec3(sin(yaw) * cos(pitch), -sin(pitch), cos(yaw) * cos(pitch));
|
|
4337
4337
|
}
|
|
4338
|
-
`,
|
|
4338
|
+
`,JM=`// The fixed join: every lens read where the calibration's template reads it, for an infinitely
|
|
4339
4339
|
// far scene, and blended across the whole feather band. The stitch the player draws; the lab's
|
|
4340
4340
|
// bent join (ADR 0026) implements the same three functions.
|
|
4341
4341
|
float disparityAt(vec3 dirBody) {
|
|
@@ -4349,14 +4349,14 @@ vec3 seamReadDirection(int i, vec3 dirBody, float disparity) {
|
|
|
4349
4349
|
vec2 seamFeather(float disparity) {
|
|
4350
4350
|
return uFeather;
|
|
4351
4351
|
}
|
|
4352
|
-
`,
|
|
4352
|
+
`,YM=`// GLSL ES 3.0 needs the default precisions before any float or int is mentioned.
|
|
4353
4353
|
precision highp float;
|
|
4354
4354
|
precision highp int;
|
|
4355
4355
|
|
|
4356
4356
|
const float PI = 3.14159265358979;
|
|
4357
4357
|
const float HALF_PI = 0.5 * PI;
|
|
4358
4358
|
const float TWO_PI = 2.0 * PI;
|
|
4359
|
-
`,
|
|
4359
|
+
`,XM=`// The depth is positive for every direction inside a lens's field; directions behind it are
|
|
4360
4360
|
// projected too, for the footprint's derivatives, and must not divide by zero.
|
|
4361
4361
|
const float MIN_DEPTH = 1e-3;
|
|
4362
4362
|
|
|
@@ -4424,7 +4424,7 @@ vec2 projectRadialPolynomial(int i, vec3 d, float theta) {
|
|
|
4424
4424
|
vec2 unit = lateral > 0.0 ? d.xy / lateral : vec2(0.0);
|
|
4425
4425
|
return uLensPrincipalPoint[i] + radius * unit;
|
|
4426
4426
|
}
|
|
4427
|
-
`,
|
|
4427
|
+
`,ZM=`// How a body direction becomes a texel of one lens, for the stitch and the seam meters: the
|
|
4428
4428
|
// pose and field as uniforms, and the sampling through each lens model, the texel as its
|
|
4429
4429
|
// exposure signal. Needs lensTextures.glsl, displayConversion.glsl and lensModels.glsl.
|
|
4430
4430
|
uniform vec2 uFeather;
|
|
@@ -4481,7 +4481,7 @@ LensSample sampleLensWith(int i, vec3 dirBody, int sampling) {
|
|
|
4481
4481
|
LensSample sampleLensAt(int i, vec3 dirBody) {
|
|
4482
4482
|
return sampleLensWith(i, dirBody, uSampling);
|
|
4483
4483
|
}
|
|
4484
|
-
`,
|
|
4484
|
+
`,QM=`// Where each lens's image is: the decoded frames as textures, each lens's region of its frame,
|
|
4485
4485
|
// and how a screen pixel reads them. Every program that reads a lens needs these.
|
|
4486
4486
|
uniform int uLensCount;
|
|
4487
4487
|
uniform vec4 uLensRegion[MAX_LENSES];
|
|
@@ -4558,7 +4558,7 @@ vec4 sampleLens(int textureIndex, Footprint footprint, int sampling) {
|
|
|
4558
4558
|
if (sampling == SAMPLING_SUPERSAMPLED) return fetchSupersampled(textureIndex, footprint);
|
|
4559
4559
|
return fetchBase(textureIndex, footprint.uv);
|
|
4560
4560
|
}
|
|
4561
|
-
|
|
4561
|
+
`,$M=`// The decoded lens images on their own, unstitched: each lens's region of its frame as the
|
|
4562
4562
|
// decoder delivered it, brought to the display (ADR 0033), in the lens's screen area, with no
|
|
4563
4563
|
// pose, stabilization or gain. Black around the areas. Every pixel reads every tile, and the area
|
|
4564
4564
|
// picks one without a branch: a read inside a branch that some pixels of a 2x2 quad skip took a
|
|
@@ -4578,7 +4578,7 @@ void main() {
|
|
|
4578
4578
|
}
|
|
4579
4579
|
outColor = vec4(color, 1.0);
|
|
4580
4580
|
}
|
|
4581
|
-
`,
|
|
4581
|
+
`,eN=`// A rectilinear picture: the image plane scaled so that the horizontal field of view means what
|
|
4582
4582
|
// the picture says.
|
|
4583
4583
|
uniform float uPlaneHalfExtent;
|
|
4584
4584
|
uniform float uPictureAspect;
|
|
@@ -4590,7 +4590,7 @@ vec3 rayThroughPicture(vec2 point) {
|
|
|
4590
4590
|
vec2 plane = vec2(centred.x * uPlaneHalfExtent, centred.y * uPlaneHalfExtent / uPictureAspect);
|
|
4591
4591
|
return normalize(vec3(plane, 1.0));
|
|
4592
4592
|
}
|
|
4593
|
-
`,
|
|
4593
|
+
`,tN=`// Where on the viewport the picture goes: per area, x, y, width and height as fractions of the
|
|
4594
4594
|
// viewport from its top-left corner.
|
|
4595
4595
|
uniform vec4 uScreenArea[MAX_LENSES];
|
|
4596
4596
|
|
|
@@ -4604,7 +4604,7 @@ vec2 pointInArea(vec2 ndc, vec4 area) {
|
|
|
4604
4604
|
bool isInArea(vec2 point) {
|
|
4605
4605
|
return all(greaterThanEqual(point, vec2(0.0))) && all(lessThanEqual(point, vec2(1.0)));
|
|
4606
4606
|
}
|
|
4607
|
-
`,
|
|
4607
|
+
`,nN=`// The stitched sphere through the picture's rays: each lens's texel for the ray, read and weighted
|
|
4608
4608
|
// across the feather band as the seam join says, and matched in exposure. Every pixel samples,
|
|
4609
4609
|
// even outside the picture's area, so the footprints' derivatives are defined; the area decides
|
|
4610
4610
|
// what shows.
|
|
@@ -4639,17 +4639,20 @@ void main() {
|
|
|
4639
4639
|
bool isShown = isInArea(point) && weightSum > 0.0;
|
|
4640
4640
|
outColor = isShown ? vec4(sum / weightSum, 1.0) : vec4(0.0, 0.0, 0.0, 1.0);
|
|
4641
4641
|
}
|
|
4642
|
-
`,Ej=[xj,hj],Dj=[...Ej,yj,bj];function Oj(e){return[vj,...Dj,e]}function kj(e){let t=t=>[vj,wj,t,...Dj,e,Tj];return{rectilinear:t(Cj),equirectangular:t(gj),"lens-tiles":[vj,wj,...Ej,Sj]}}var Aj=kj(_j),jj=Oj(mj);function Mj(e){return[...new Set(e.flat())]}Mj([...Object.values(Aj),jj]);var Nj=64,Pj=class{renderer;lensCount;target=new LC(Nj,2,{depthBuffer:!1,stencilBuffer:!1});pixels=new Uint8Array(Nj*2*4);camera=new LE;scene=new Cw;material;geometry=ij();isDisposed=!1;constructor(e,t,n){this.renderer=e,this.lensCount=n,this.material=oj(t,aj(jj)),this.scene.add(new VT(this.geometry,this.material));try{fj(e,this.scene,this.camera)}catch(e){throw this.dispose(),e}}async measure(){try{await this.readSeam()}catch(e){if(this.isDisposed||this.renderer.getContext().isContextLost())return;throw e}return this.isDisposed?void 0:uj(this.pixels,Nj,this.lensCount)}dispose(){this.isDisposed||(this.isDisposed=!0,this.target.dispose(),this.material.dispose(),this.geometry.dispose())}draw(){pj(this.renderer,this.target,()=>{this.renderer.render(this.scene,this.camera)})}async readSeam(){this.draw(),await this.renderer.readRenderTargetPixelsAsync(this.target,0,0,Nj,2,this.pixels)}};function Fj(e,t){return Array.from({length:e},()=>{let e=new XT;return e.flipY=!1,e.colorSpace=``,e.magFilter=Dx,Ij(e,t),e})}function Ij(e,t){e.minFilter=t.minFilter,e.generateMipmaps=t.generateMipmaps,e.anisotropy=t.anisotropy}var Lj={programs:Aj,defines:IA};function Rj(e,t){let n=n=>oj(e,{chunks:t.programs[n],defines:t.defines});return{rectilinear:n(`rectilinear`),equirectangular:n(`equirectangular`),"lens-tiles":n(`lens-tiles`)}}function zj(e,t,n){let r=new LE;for(let i of Object.values(n)){let n=new Cw;n.add(new VT(t,i)),fj(e,n,r)}}function Bj(e){for(let t of Object.values(e))t.dispose()}var Vj={shaders:Lj,uniforms:{}},Hj=class{parts;canvas;framing=uc;viewMode=ks;hasFrames=!1;isDisposed=!1;meters=/* @__PURE__ */ new Set;constructor(e,t){this.parts=e,this.canvas=t,this.applyFraming(),t.addEventListener(`webglcontextrestored`,this.onContextRestored)}static create(e,t,n={}){let r={options:n,pictures:Vj};return new this(this.openParts(e,t,r),e)}static openParts(e,t,n){Uj(t);let r=sj(e,n.options);try{return{...Gj(r,t,n.pictures),drawSchedule:n.options.drawSchedule??wA}}catch(e){throw r.dispose(),e}}get lensCount(){return this.parts.lensCount}setFraming(e){this.ensureLive(),this.framing=e,this.applyFraming(),this.redraw()}setViewMode(e){this.ensureLive(),this.viewMode=e,this.applyFraming(),this.redraw()}setQuality(e){this.ensureLive();let t=NA[e];for(let e of this.parts.textures)Ij(e,t),this.hasFrames&&(e.needsUpdate=!0);GA(this.parts.uniforms,t),this.redraw()}setLensGains(e){this.ensureLive();for(let[t,n]of e.entries())qA(this.parts.uniforms,t,n);this.redraw()}createSeamMeter(){this.ensureLive();let e=new Pj(this.parts.renderer,this.parts.uniforms,this.parts.lensCount);return this.tracked({measure:()=>e.measure(),dispose:()=>{e.dispose()}})}setStabilization(e){this.ensureLive(),KA(this.parts.uniforms,e)}present(e){this.ensureLive();let{frames:t}=e.pair;N(t.length===this.parts.textures.length,`a pair of ${t.length} frames does not fit ${this.parts.textures.length} lens textures`);for(let[e,n]of this.parts.textures.entries()){let r=t[e];r&&n.setFrame(r.handle)}this.parts.matrixCorrections.follow(t.map(e=>e.handle)),this.hasFrames=!0,this.drawNow()}resize(e){this.ensureLive(),this.parts.renderer.setSize(e.width,e.height,!1),this.applyFraming(),this.drawNow()}dispose(){if(!this.isDisposed){this.isDisposed=!0,this.parts.drawSchedule.cancel(),this.canvas.removeEventListener(`webglcontextrestored`,this.onContextRestored);for(let e of this.meters)e.dispose();this.parts.seamProof.dispose();for(let e of this.parts.textures)e.dispose();Bj(this.parts.materials),this.parts.pass.geometry.dispose(),this.parts.renderer.dispose()}}get webgl(){return this.parts.renderer}get uniforms(){return this.parts.uniforms}tracked(e){let t={...e,dispose:()=>{this.meters.delete(t),e.dispose()}};return this.meters.add(t),t}redraw(){this.parts.drawSchedule.request(this.draw)}ensureLive(){N(!this.isDisposed,`the renderer has been disposed`)}onContextRestored=()=>{this.redraw()};drawNow(){this.parts.drawSchedule.cancel(),this.draw()}draw=()=>{this.hasFrames&&this.parts.renderer.render(this.parts.scene,this.parts.camera)};applyFraming(){let e={width:this.canvas.width,height:this.canvas.height},t=kc(this.viewMode).picture(this.framing,{viewport:e,lensCount:this.parts.lensCount});this.parts.pass.material=this.parts.materials[t.kind],YA(this.parts.uniforms,t,Ps(e))}};function Uj(e){if(!(e.lenses.length<=2&&e.frameSlotCount<=2))throw new j(`unsupported-layout`,`the renderer draws at most 2 lenses from 2 frames; the layout has ${e.lenses.length} lenses in ${e.frameSlotCount} frames`)}function Wj(e,t){let n=NA[Ts],r=Fj(e.frameSlotCount,n),i=LA(e,r);return GA(i,n),{textures:r,uniforms:i,materials:Rj({...i,...t.uniforms},t.shaders)}}function Gj(e,t,n){let{textures:r,uniforms:i,materials:a}=Wj(t,n),o=new VT(ij(),a.rectilinear),s=Kj(e,{pass:o,materials:a,textures:r,uniforms:i}),c=new Cw;return c.add(o),{renderer:e,scene:c,camera:new LE,pass:o,materials:a,textures:r,uniforms:i,matrixCorrections:new EA(t.lenses,i.uLensMatrixCorrection),lensCount:t.lenses.length,seamProof:s}}function Kj(e,t){let{pass:n,materials:r,textures:i,uniforms:a}=t;try{return zj(e,n.geometry,r),new Pj(e,a,a.uLensCount.value)}catch(e){Bj(r),n.geometry.dispose();for(let e of i)e.dispose();throw e}}var qj={request:e=>requestAnimationFrame(e),cancel:e=>{cancelAnimationFrame(e)}},Jj=class{frames;pendingDraw;handle;constructor(e=qj){this.frames=e}request(e){let t=this.pendingDraw!==void 0;this.pendingDraw=e,t||(this.handle=this.frames.request(this.drawPending))}cancel(){this.pendingDraw=void 0,this.handle!==void 0&&(this.frames.cancel(this.handle),this.handle=void 0)}drawPending=()=>{let e=this.pendingDraw;this.pendingDraw=void 0,this.handle=void 0,e?.()}},Yj=class{actions=[];isDisposed=!1;add(e){if(this.isDisposed){e();return}this.actions.push(e)}disposeAll(){if(!this.isDisposed){this.isDisposed=!0;for(let e of this.actions.splice(0).toReversed())e()}}toDisposer(){return()=>{this.disposeAll()}}},Xj={maxPendingPackets:4,pairTolerance:R(5e-4)},Zj=`the recording has no audio track; playback follows a silent clock`,Qj=`this browser cannot play the audio track through Media Source Extensions; playback follows a silent clock`,$j=`the audio track could not be prepared for playback; playback follows a silent clock`;async function eM(e){let t=new Yj;try{let n=await rM(e);t.add(()=>{n.clock.dispose()}),e.signal.throwIfAborted();let r=tM(e,t),i=cM(e,n.clock,r.gainMatching);return t.add(()=>{i.dispose()}),sM(i,e.opened),{session:i,renderer:r.renderer,...nM(r,i),soundWarnings:n.warnings,dispose:t.toDisposer()}}catch(e){throw t.disposeAll(),e}}function tM(e,t){let n=Hj.create(e.host.canvas,aM(e.opened),{drawSchedule:new Jj});t.add(()=>{n.dispose()});let{sink:r,stabilizing:i}=oM(n,e.opened),a=new Gc(r,n);return t.add(()=>{a.dispose()}),{renderer:n,stabilizing:i,gainMatching:a}}function nM(e,t){return{setStabilization:n=>{e.stabilizing?.setStabilizer(is(n)),t.redraw()},setQuality:t=>{e.renderer.setQuality(t)},setGainMatching:n=>{n?e.gainMatching.enable():e.gainMatching.disable(),t.redraw()}}}async function rM(e){let{soundSegments:t}=e.opened;if(!t)return iM(Zj);try{let n=t();return _x.isSupported(n)?(e.signal.throwIfAborted(),{clock:await _x.open(e.host.audio,n),warnings:[]}):iM(Qj)}catch(e){return iM(`${$j} (${ie(e)})`)}}function iM(e){return{clock:new Qu(()=>pt(performance.now())),warnings:[e]}}function aM(e){return Fc({calibration:e.calibration,layout:e.layout,displayConversions:e.displayConversions})}function oM(e,t){if(!t.motion)return{sink:e,stabilizing:void 0};let n=new Bc({sink:e,orientations:t.motion.orientations,frameTimes:t.frameTimes});return{sink:n,stabilizing:n}}function sM(e,t){e.events.on(`statechange`,e=>{td(e)&&t.readAhead()})}function cM(e,t,n){return new vd({frameSources:e.opened.frameSources,decoderPort:e.decoderPort,clock:t,sink:n,duration:e.opened.duration,buffer:e.opened.buffer,pipeline:Xj,queueCapacity:4})}function lM(e,t,n=Ts){let r=yr(t,1,Ds(n));return{width:Math.max(1,Math.round(e.width*r)),height:Math.max(1,Math.round(e.height*r))}}function uM(e){let{width:t,height:n}=e.getBoundingClientRect();return{width:t,height:n}}var dM=class{canvas;renderer;observer;ratioWatch=new AbortController;quality=Ts;constructor(e,t){this.canvas=e,this.renderer=t,this.observer=new ResizeObserver(()=>{this.fit()}),this.observer.observe(e),this.watchPixelRatio(),this.fit()}setQuality(e){this.quality=e,this.fit()}dispose(){this.observer.disconnect(),this.ratioWatch.abort()}watchPixelRatio(){globalThis.matchMedia(`(resolution: ${globalThis.devicePixelRatio}dppx)`).addEventListener(`change`,()=>{this.fit(),this.watchPixelRatio()},{once:!0,signal:this.ratioWatch.signal})}fit(){let e=lM(uM(this.canvas),globalThis.devicePixelRatio,this.quality);(e.width!==this.canvas.width||e.height!==this.canvas.height)&&this.renderer.resize(e)}},fM=class{tick;scheduler;isActive=!1;handle;constructor(e,t=qj){this.tick=e,this.scheduler=t}start(){this.isActive||(this.isActive=!0,this.schedule())}stop(){this.isActive=!1,this.handle!==void 0&&(this.scheduler.cancel(this.handle),this.handle=void 0)}schedule(){this.handle=this.scheduler.request(()=>{this.handle=void 0,this.tick(),this.isActive&&this.schedule()})}};async function pM(e,t){let{ports:n,signal:r}=t,i=await Gu(e,n.decoderPort,vM(t));if(r.throwIfAborted(),!i.canDecode)throw gM(i)}var mM={"no-key-frame":{code:`no-key-frame`,message:`the recording has no key frame to start decoding from`},"key-frame-late":{code:`source-unreadable`,message:`the recording's first frames did not arrive in time`}},hM={code:`codec-unsupported`,message:`this browser cannot decode the recording`};function gM(e){let t=_M(e),{code:n,message:r}=(t===void 0?void 0:mM[t])??hM;return new j(n,`${r}: ${yM(e)}`)}function _M(e){let t=new Set(e.sources.filter(e=>e.verdict!==`decodes`).map(e=>e.verdict));t.has(`key-frame-late`)&&t.delete(`timed-out`);let[n]=t;return t.size===1?n:void 0}function vM(e){let t=e.ports.probeDeadline();return e.signal.addEventListener(`abort`,()=>{t.resolve()},{once:!0}),t}function yM(e){return e.sources.filter(e=>e.verdict!==`decodes`).map(e=>`track ${e.track.trackIndex} ${e.verdict}${e.detail?` (${e.detail})`:``}`).join(`; `)}async function bM(e,t){let{ports:n,signal:r}=t,i=e.map(e=>({input:e,opened:n.sources.open(e,r)})),a=await TM(i,n);r.throwIfAborted();let o=[...i,...await CM(i,a,t)],s=await Promise.all(o.map(e=>SM(e,n)));return r.throwIfAborted(),{recording:a,inputs:s}}function xM(e){let t=e.codecs.video.map(({description:e})=>({description:e}));return{name:Kb(e.input),videoTracks:t}}async function SM(e,t){let{source:n}=e.opened,{table:r,movieBytes:i}=await Do(n),a=await t.codecReader.read(i);return{...e,table:r,codecs:a,size:await n.size()}}async function CM(e,t,n){if(e.length!==1||t.info.fileLayout!==`split-files`||!n.findSecondFile)return[];let r=await n.findSecondFile();return n.signal.throwIfAborted(),r===void 0?[]:[{input:r,opened:n.ports.sources.open(r,n.signal)}]}var wM={fileLayout:void 0,trackOrder:void 0};async function TM(e,t){try{return await DM(e.map(({opened:e})=>e.source))}catch(n){let[r]=e;throw e.length===1&&M(n,`invalid-trailer`)&&r&&await EM(r,t),n}}async function EM(e,t){let n;try{n=await SM(e,t)}catch{return}try{Ro([xM(n)],wM)}catch(e){if(M(e,`missing-second-file`))throw e}}async function DM(e){let[t,n]=e;N(t!==void 0,`a recording needs at least one input`);try{return await $n(t)}catch(e){if(n===void 0||!M(e,`invalid-trailer`))throw e;return $n(n)}}async function OM(e,t){let n=new Yj;try{let r=await bM(e,t),i=Ro(r.inputs.map(e=>xM(e)),r.recording.info),a=jM(r.recording),o=kM(r.inputs,n),s=Pc(i).map(e=>AM(o,e));await pM(s,t);let c=await Gi(r.recording,s[0]);return t.signal.throwIfAborted(),MM({read:r,files:o,layout:i,frameSources:s,calibration:a,timing:c},t.ports.audioPackager,n)}catch(e){throw n.disposeAll(),e}}function kM(e,t){return e.map(({opened:n,table:r,codecs:i,size:a})=>{let o=xu({size:a,duration:r.duration},e.length),s=cu({table:r,stream:n.stream,codecs:i,policy:o});return t.add(()=>{s.dispose()}),s})}function AM(e,t){let n=e[t.inputIndex]?.videoTracks[t.trackIndex];return N(n!==void 0,`the layout points at track ${t.trackIndex} of input ${t.inputIndex}, which does not exist`),n}function jM(e){let{calibration:t,warnings:n}=e.calibration;if(t)return t;throw new j(`no-calibration`,`the recording carries no usable lens calibration, so it cannot be stitched${n.length>0?` (${n.join(`; `)})`:``}`)}function MM(e,t,n){let{read:r,files:i,layout:a,frameSources:o,calibration:s,timing:c}=e,l=R(Math.min(...i.map(e=>e.duration))),u=fl(o.map(e=>e.description.colour)),[d]=i.flatMap(e=>e.audioTracks);return{recording:r.recording,layout:a,frameSources:o,calibration:s,displayConversions:u.conversions,duration:l,frameTimes:c.frameTimes,motion:c.motion,soundSegments:d&&(()=>t.segmentsOf(d.samples,d.configuration)),metadata:NM(e,l,d!==void 0),warnings:[...c.warnings,...u.warnings],readAhead:()=>{for(let e of i)e.download.startReadingAhead()},buffer:new Su(i.map(e=>e.download)),dispose:n.toDisposer()}}function NM(e,t,n){let{info:r}=e.read.recording,{motion:i}=e.timing;return{model:r.model,firmware:r.firmware,captureMode:r.captureMode,layout:e.layout.kind,layoutEvidence:e.layout.evidence,tracks:e.frameSources.map(e=>e.description),calibrationVersion:e.calibration.version,frameTimeSource:e.timing.frameTimeSource,hasGyro:i!==void 0,imuFrame:i&&{name:i.imuFrame.name,isVerified:i.imuFrame.isVerified},hasAudio:n,duration:t}}async function PM(e,t,n){let r=FM(e,t,n),i=e.second?[e.main,e.second]:[e.main];try{return await OM(i,r)}catch(t){let{findSecondFile:i}=r;if(!i||!M(t,`missing-second-file`))throw t;let a=await i();if(n.throwIfAborted(),!a)throw t;return OM([e.main,a],r)}}function FM(e,t,n){let{main:r}=e;return e.second===void 0&&Gb(r)?{ports:t,signal:n,findSecondFile:$e(()=>IM(r,t))}:{ports:t,signal:n}}async function IM(e,t){let n=await aa(e.url,t.locatorFor(e));return n===void 0?void 0:{...e,url:n}}async function LM(e){let{parts:t,signal:n}=e,r=await PM(e.source,t.ports,n),i=new Yj;i.add(()=>{r.dispose()});try{let e=await t.pipelines({opened:r,host:t.host,decoderPort:t.ports.decoderPort,signal:n});i.add(()=>{e.dispose()}),n.throwIfAborted();let a=new dM(t.host.canvas,e.renderer);i.add(()=>{a.dispose()});let o=RM(e,a);return{opened:r,pipeline:o,warnings:zM(r,o),dispose:i.toDisposer()}}catch(e){throw i.disposeAll(),e}}function RM(e,t){return{...e,setQuality:n=>{e.setQuality(n),t.setQuality(n)}}}function zM(e,t){return[...e.warnings.map(e=>({code:`recording-degraded`,message:e})),...t.soundWarnings.map(e=>({code:`no-sound`,message:e}))]}var BM={kind:`idle`};function VM(){return{kind:`loading`,controller:new AbortController,settled:new Ou}}function HM(e){switch(e.kind){case`idle`:return`idle`;case`loading`:return`loading`;case`loaded`:return e.loaded.pipeline.session.state;case`failed`:return`error`}}var UM=class{events;mode=Zo;isMatching=!0;qualityValue=Ts;target;constructor(e){this.events=e}get stabilization(){return this.mode}get quality(){return this.qualityValue}attach(e){this.target=e,e?.setStabilization(this.mode),e?.setGainMatching(this.isMatching),e?.setQuality(this.qualityValue)}setStabilization(e){e!==this.mode&&(this.mode=e,this.target?.setStabilization(e),this.events.emit(`stabilizationchange`,e))}setGainMatching(e){this.isMatching=e,this.target?.setGainMatching(e)}setQuality(e){e!==this.qualityValue&&(this.qualityValue=e,this.target?.setQuality(e),this.events.emit(`qualitychange`,e))}},WM=class{audio;events;canSetVolume;constructor(e,t){this.audio=e,this.events=t,this.canSetVolume=KM(e.ownerDocument),e.addEventListener(`volumechange`,this.onVolumeChange)}get volume(){return this.audio.volume}get isMuted(){return this.audio.muted}setVolume(e){this.audio.volume=yr(e,0,1)}setMuted(e){this.audio.muted=e}dispose(){this.audio.removeEventListener(`volumechange`,this.onVolumeChange)}onVolumeChange=()=>{this.events.emit(`volumechange`,{volume:this.volume,isMuted:this.isMuted})}},GM=.5;function KM(e){let t=e.createElement(`audio`);return t.volume=GM,t.volume===GM}var qM=2,JM=class{events;measureViewport;framing=uc;mode=ks;surface;lensCount=qM;constructor(e,t){this.events=e,this.measureViewport=t}get current(){return this.framing.view}get viewMode(){return this.mode}get canPan(){return this.rules().canPan(this.framing)}attach(e){this.surface=e,e&&(this.lensCount=e.lensCount),e?.setViewMode(this.mode),e?.setFraming(this.framing)}set(e){this.frame({...this.framing,view:xs(e)})}setMode(e){e!==this.mode&&(this.mode=e,this.surface?.setViewMode(e),this.events.emit(`viewmodechange`,e))}lookAt(e,t){this.frame({...this.framing,view:ec(this.framing.view,e,t)})}pan(e){this.frame(this.rules().pan(this.framing,e,this.context()))}turn(e,t){this.frame(this.rules().turn(this.framing,{yaw:e,pitch:t},this.context()))}zoom(e,t=Ms){this.frame(this.rules().zoom(this.framing,{steps:e,focus:t},this.context()))}reset(){this.frame(this.rules().reset(this.framing))}frame(e){if(dc(e,this.framing))return;let t=!Ss(e.view,this.framing.view);this.framing=e,this.surface?.setFraming(e),t&&this.events.emit(`viewchange`,e.view)}context(){return{viewport:this.measureViewport(),lensCount:this.lensCount}}rules(){return kc(this.mode)}},YM=/* @__PURE__ */ new Set([`ready`,`paused`,`ended`]),XM=/* @__PURE__ */ new Map([[`playing`,`playing`],[`buffering`,`waiting`]]);function ZM(e,t){return t===`seeking`?[`seeking`]:e===`seeking`?t===`buffering`?[`seeked`,`waiting`]:[`seeked`]:t===`paused`?e===`ready`?[]:[`pause`]:QM(e,t)}function QM(e,t){let n=XM.get(t);return n===void 0?[]:e===void 0||YM.has(e)?[`play`,n]:[n]}var $M=class{targets;stopListening=[];lastState;detachments=0;constructor(e){this.targets=e}attach(e){this.detach(),this.lastState=e.state;let{events:t}=this.targets;this.stopListening=[e.events.on(`statechange`,t=>{this.onStateChange(t,e)}),e.events.on(`timeupdate`,e=>{t.emit(`timeupdate`,e)}),e.events.on(`present`,e=>{t.emit(`frame`,e)}),e.events.on(`ended`,()=>{this.targets.onEnded()}),e.events.on(`error`,e=>{t.emit(`error`,e)})]}detach(){for(let e of this.stopListening)e();this.stopListening=[],this.lastState=void 0,this.detachments+=1}onStateChange(e,t){let n=this.lastState;this.lastState=e;let r=this.detachments;for(let i of ZM(n,e))if(this.emitTransport(i,t),this.detachments!==r)return;this.targets.onState(e)}emitTransport(e,t){let{events:n}=this.targets;e===`seeking`||e===`seeked`?n.emit(e,t.currentTime):n.emit(e,void 0)}},eN=class{parts;events=new rd;outbox=new vl(this.events);loop;phase=BM;viewing;picture=new UM(this.outbox);pendingStartTime;sound;relay=new $M({events:this.outbox,onState:()=>{this.announceStatus()},onEnded:()=>{this.onEnded()}});isLoopingValue=!1;isDisposed=!1;lastStatus=`idle`;constructor(e){this.parts=e,this.loop=new fM(this.tick),e.host.audio.addEventListener(`ended`,this.tick),this.sound=new WM(e.host.audio,this.outbox);let{canvas:t}=e.host;this.viewing=new JM(this.outbox,()=>uM(t))}get status(){return HM(this.phase)}get metadata(){return this.loaded?.opened.metadata}get currentTime(){return this.loaded?.pipeline.session.currentTime??R(0)}get duration(){return this.loaded?.opened.duration??R(0)}get isPaused(){return!td(this.loaded?.pipeline.session.state)}get view(){return this.viewing.current}get viewMode(){return this.viewing.viewMode}get canPan(){return this.viewing.canPan}get stabilization(){return this.picture.stabilization}get quality(){return this.picture.quality}get isLooping(){return this.isLoopingValue}get volume(){return this.sound.volume}get isMuted(){return this.sound.isMuted}get canSetVolume(){return this.sound.canSetVolume}async load(e,t={}){if(this.isDisposed)return;let n=this.outbox.change(()=>{this.unload();let e=VM();return this.phase=e,this.announceStatus(),e});try{await this.complete(n,e,t)}catch(e){if(n.controller.signal.aborted)return;throw this.failWith(e)}finally{n.settled.resolve()}}unload(){this.outbox.change(()=>{this.release(),this.announceStatus()})}async play(){if(await this.loadInProgress(),this.phase.kind===`failed`)throw this.phase.failure;await this.loaded?.pipeline.session.play()}pause(){this.loaded?.pipeline.session.pause()}stop(){this.loaded?.pipeline.session.stop()}seek(e){jd(e,`time`);let t=this.loaded?.pipeline.session;t&&t.state!==`error`?t.seek(R(e)):this.pendingStartTime=R(e)}async scrub(e){jd(e,`time`),await this.loaded?.pipeline.session.scrub(R(e))}setView(e){this.viewing.set(Md(e))}lookAt(e,n){jd(e,`yaw`),jd(n,`pitch`),this.viewing.lookAt(t(e),t(n))}pan(e){this.viewing.pan(e)}turn(e,n){jd(e,`yaw turn`),jd(n,`pitch turn`),this.viewing.turn(t(e),t(n))}zoom(e,t){jd(e,`zoom steps`),this.viewing.zoom(e,t)}resetView(){this.viewing.reset()}setViewMode(e){this.viewing.setMode(e)}setStabilization(e){this.picture.setStabilization(e)}setQuality(e){this.picture.setQuality(e)}setLooping(e){this.isLoopingValue=e}setGainMatching(e){this.picture.setGainMatching(e)}setVolume(e){jd(e,`volume`),this.sound.setVolume(e)}setMuted(e){this.sound.setMuted(e)}dispose(){this.isDisposed=!0,this.unload(),this.parts.host.audio.removeEventListener(`ended`,this.tick),this.sound.dispose(),this.events.removeAll()}tick=()=>{this.loaded?.pipeline.session.tick()};async loadInProgress(){this.phase.kind===`loading`&&await this.phase.settled.promise}get loaded(){return this.phase.kind===`loaded`?this.phase.loaded:void 0}async complete(e,t,n){let{signal:r}=e.controller,i=await LM({source:t,parts:this.parts,signal:r});if(r.aborted){i.dispose();return}this.outbox.change(()=>{this.attach(i,e.controller),this.startAtPendingTime(i),n.preload!==!1&&i.pipeline.session.preload()}),n.autoplay&&this.loaded===i&&await this.autoplay()}startAtPendingTime(e){let t=this.pendingStartTime;this.pendingStartTime=void 0,t!==void 0&&e.pipeline.session.seek(t)}attach(e,t){this.phase={kind:`loaded`,loaded:e,controller:t},this.viewing.attach(e.pipeline.renderer);let{session:n}=e.pipeline;this.picture.attach(e.pipeline),this.relay.attach(n),this.loop.start(),this.announceStatus();for(let t of e.warnings)this.outbox.emit(`warning`,t);this.outbox.emit(`ready`,e.opened.metadata)}async autoplay(){try{await this.play()}catch(e){this.outbox.emit(`warning`,M(e,`playback-blocked`)?{code:`autoplay-blocked`,message:`playback waits for a user gesture`}:{code:`playback-failed`,message:`autoplay failed: ${ie(e)}`})}}onEnded(){this.outbox.emit(`ended`,void 0),this.isLoopingValue&&this.replay()}async replay(){try{await this.play()}catch(e){this.outbox.emit(`warning`,{code:`playback-failed`,message:`the loop could not restart playback: ${ie(e)}`})}}release(){let e=this.phase;this.phase=BM,e.kind===`loading`&&e.controller.abort(),this.loop.stop(),this.relay.detach(),this.viewing.attach(void 0),this.picture.attach(void 0),e.kind===`loaded`&&(e.loaded.dispose(),e.controller.abort())}failWith(e){let t=ne(e,`invariant-violation`,`the player failed unexpectedly`);return this.outbox.change(()=>{this.release(),this.phase={kind:`failed`,failure:t},this.announceStatus(),this.outbox.emit(`error`,t)}),t}announceStatus(){let{status:e}=this;this.outbox.post(()=>{e!==this.lastStatus&&(this.lastStatus=e,this.events.emit(`statuschange`,e))})}};function tN(e,t){return new eN({host:e,ports:Jb(t),pipelines:eM})}function nN(e,t={}){let n=t.signal??new AbortController().signal,{source:r}=Yb(t.http??{}).open(rN(e),n);return dr(r)}function rN(e){return typeof e==`string`?{url:e}:{blob:e,name:e instanceof File?e.name:``}}var iN={Src:`src`,Src2:`src2`},aN={CrossOrigin:`crossorigin`},oN={FieldOfView:`fov`,Yaw:`yaw`,Pitch:`pitch`},sN={Autoplay:`autoplay`,Preload:`preload`,GainMatch:`gain-match`,Muted:`muted`,Loop:`loop`,Stabilization:`stabilization`,ViewMode:`view-mode`,Quality:`quality`,Controls:`controls`,Poster:`poster`},cN=[...Object.values(iN),...Object.values(aN),...Object.values(oN),...Object.values(sN)];function lN(e,t){let n=dN(e(aN.CrossOrigin)),r=uN(e(iN.Src),t,n);return r&&{main:r,second:uN(e(iN.Src2),t,n)}}function uN(e,t,n){let r=e?.trim()??``;return r===``?void 0:{url:fN(r,t),...n}}function dN(e){return Dd(xN,e)===`use-credentials`?{credentials:`include`}:{}}function fN(e,t){try{return new URL(e,t).href}catch{return e}}var pN={[oN.FieldOfView]:`fieldOfView`,[oN.Yaw]:`yaw`,[oN.Pitch]:`pitch`};function mN(e,t,n){let r=pN[t],i=gN(n);return r===void 0||i===void 0?e:{...e,[r]:i}}function hN(e){return e!==null}function gN(e){if(e===null||e.trim()===``)return;let t=Number(e);return Number.isFinite(t)?t:void 0}function _N(e,t,n){return{code:`ignored-attribute`,message:`ignoring ${e}="${t}"; expected one of ${n.join(`, `)}`}}function vN(e,t){return t===null||gN(t)!==void 0?void 0:{code:`ignored-attribute`,message:`ignoring ${e}="${t}"; expected a number of degrees`}}var yN={name:sN.Preload,keywords:[`none`,`auto`],fallback:`auto`},bN={name:sN.GainMatch,keywords:[`on`,`off`],fallback:`on`},xN={name:aN.CrossOrigin,property:`crossOrigin`,keywords:[`anonymous`,`use-credentials`],fallback:`anonymous`};function SN(e){return Dd(yN,e)===`auto`}function CN(e){return Dd(bN,e)===`on`}function wN(e,t,n){return n?TN(n):lN(e,t)}function TN(e){return{main:{blob:e.main,name:e.main.name},second:e.second&&{blob:e.second,name:e.second.name}}}var EN=class{element;player;scheduled;isOwed=!0;awaited;startTime;files;constructor(e,t){this.element=e,this.player=t}connected(){this.isOwed&&this.schedule(),this.awaited?.follow(this.scheduled??Promise.resolve()),this.awaited=void 0}async disconnected(){await Promise.resolve(),!this.element.isConnected&&(this.player.unload(),this.isOwed=!0)}sourceChanged(){this.files=void 0,this.schedule()}requestChanged(){this.files===void 0&&this.schedule()}loadFiles(e){this.files=e,this.schedule()}load(){return this.element.isConnected?this.scheduled??this.reload():this.loadOnConnection()}seek(e){this.scheduled?this.startTime=e:this.player.seek(e)}async settled(){try{await this.scheduled}catch{}}loadOnConnection(){return this.isOwed=!0,this.awaited??=new Ou,this.awaited.promise}schedule(){if(this.isOwed=!this.element.isConnected,this.scheduled||!this.element.isConnected)return;let e=this.loadAfterPendingChanges();this.scheduled=e,e.catch(DN)}async loadAfterPendingChanges(){await Promise.resolve(),this.scheduled=void 0,this.element.isConnected&&await this.reload()}reload(){this.isOwed=!1;let e=e=>this.element.getAttribute(e),t=wN(e,document.baseURI,this.files);delete this.element.dataset.hasFrame;let n=this.startTime;if(this.startTime=void 0,!t)return this.player.unload(),Promise.resolve();let r=this.player.load(t,{autoplay:this.element.autoplay,preload:SN(e(sN.Preload))});return n!==void 0&&this.player.seek(n),r}};function DN(){}var ON=`data-fill`,kN=class{element;constructor(e){this.element=e}get isActive(){return this.isNativelyFullscreen()||this.element.hasAttribute(ON)}async toggle(){await(this.isActive?this.exit():this.enter())}async exit(){this.isNativelyFullscreen()&&await document.exitFullscreen(),this.element.removeAttribute(ON)}isNativelyFullscreen(){return this.element.matches(`:fullscreen`)}async enter(){if(document.fullscreenEnabled)try{await this.element.requestFullscreen();return}catch{}this.element.setAttribute(ON,``)}},AN=`data-idle`,jN=2500,MN=[`pointermove`,`pointerdown`,`keydown`,`focusin`],NN={capture:!0},PN=class{element;shouldHide;timer;wasIdleAtPress=!1;constructor(e,t){this.element=e,this.shouldHide=t}get wasIdleAtLastPress(){return this.wasIdleAtPress}start(){this.element.addEventListener(`pointerdown`,this.onPress,NN);for(let e of MN)this.element.addEventListener(e,this.onActivity,NN);this.onActivity()}stop(){for(let e of MN)this.element.removeEventListener(e,this.onActivity,NN);this.element.removeEventListener(`pointerdown`,this.onPress,NN),this.clearTimer(),this.element.removeAttribute(AN)}refresh(){this.shouldHide()||this.element.removeAttribute(AN),this.restart()}onPress=()=>{this.wasIdleAtPress=this.element.hasAttribute(AN)};onActivity=()=>{this.element.removeAttribute(AN),this.restart()};restart(){this.clearTimer(),this.timer=setTimeout(()=>{this.shouldHide()&&this.element.setAttribute(AN,``)},jN)}clearTimer(){this.timer!==void 0&&clearTimeout(this.timer),this.timer=void 0}};function FN(e,t,n){return({player:r,warn:i},a)=>{let o=yd(a,t);o?n(r,o):a!==null&&i(_N(e,a,t))}}var IN={[sN.Stabilization]:FN(sN.Stabilization,Xo,(e,t)=>{e.setStabilization(t)}),[sN.ViewMode]:FN(sN.ViewMode,Os,(e,t)=>{e.setViewMode(t)}),[sN.Quality]:FN(sN.Quality,ws,(e,t)=>{e.setQuality(t)}),[sN.Muted]:({player:e},t)=>{e.setMuted(hN(t))},[sN.Loop]:({player:e},t)=>{e.setLooping(hN(t))},[sN.Poster]:({posterImage:e},t)=>{e.src=t??``},[sN.GainMatch]:({player:e},t)=>{e.setGainMatching(CN(t))}};function LN(e){return Object.hasOwn(IN,e)}function RN(e,t,n){LN(t)&&IN[t](e,n)}function zN(e,t){e.hasAttribute(`tabindex`)||(e.tabIndex=0),e.hasAttribute(`role`)||e.setAttribute(`role`,`region`),e.hasAttribute(`aria-label`)||e.hasAttribute(`aria-labelledby`)||e.setAttribute(`aria-label`,t)}function BN(e,t,n){e.getAttribute(`aria-label`)===t&&e.setAttribute(`aria-label`,n)}function VN(e,t){let n=/* @__PURE__ */ new Map;for(let r of t)Object.hasOwn(e,r)&&(n.set(r,Reflect.get(e,r)),Reflect.deleteProperty(e,r));return n}function HN(e,t,n){let r=[...t];t.clear();for(let[t,i]of r)try{Reflect.set(e,t,i)}catch(e){n({code:`refused-property`,message:`${t} set before the element was defined was refused: ${ie(e)}`})}}var UN=_l({stabilization:!0,viewMode:!0,quality:!0,fov:!0,yaw:!0,pitch:!0,muted:!0,loop:!0,volume:!0});function WN(e,t){let n={stabilization:{get:()=>t.stabilization,set:XN(e=>{t.setStabilization(qN(e))})},viewMode:{get:()=>t.viewMode,set:XN(e=>{t.setViewMode(JN(e))})},quality:{get:()=>t.quality,set:XN(e=>{t.setQuality(YN(e))})},...GN(t),...KN(t)};for(let[t,r]of Object.entries(n))Object.defineProperty(e,t,{configurable:!0,enumerable:!0,...r})}function GN(e){let t=(t,n)=>({get:()=>e.view[t],set:XN(r=>{e.setView({...e.view,[t]:QN(r,n)})})});return{fov:t(`fieldOfView`,`fov`),yaw:t(`yaw`,`yaw`),pitch:t(`pitch`,`pitch`)}}function KN(e){return{muted:{get:()=>e.isMuted,set:t=>{e.setMuted(!!t)}},loop:{get:()=>e.isLooping,set:t=>{e.setLooping(!!t)}},volume:{get:()=>e.volume,set:XN(t=>{e.setVolume($N(t,`volume`))})}}}function qN(e){return ZN(e,bd,`stabilization`)}function JN(e){return ZN(e,xd,`viewMode`)}function YN(e){return ZN(e,Sd,`quality`)}function XN(e){return t=>{t!=null&&t!==``&&e(t)}}function ZN(e,t,n){let r=typeof e==`string`?t(e):void 0;if(r===void 0)throw new j(`invalid-argument`,`${n} cannot be ${String(e)}`);return r}function QN(e,n){return t($N(e,n))}function $N(e,t){return jd(e,t),e}var eP=`/*
|
|
4642
|
+
`,rN=[QM,KM],iN=[...rN,XM,ZM];function aN(e){return[YM,...iN,e]}function oN(e){let t=t=>[YM,tN,t,...iN,e,nN];return{rectilinear:t(eN),equirectangular:t(qM),"lens-tiles":[YM,tN,...rN,$M]}}var sN=oN(JM),cN=aN(GM);function lN(e){return[...new Set(e.flat())]}lN([...Object.values(sN),cN]);var uN=64,dN=class{renderer;lensCount;target=new mT(uN,2,{depthBuffer:!1,stencilBuffer:!1});pixels=new Uint8Array(uN*2*4);camera=new mO;scene=new eE;material;geometry=FM();isDisposed=!1;constructor(e,t,n){this.renderer=e,this.lensCount=n,this.material=LM(t,IM(cN)),this.scene.add(new vD(this.geometry,this.material));try{UM(e,this.scene,this.camera)}catch(e){throw this.dispose(),e}}async measure(){try{await this.readSeam()}catch(e){if(this.isDisposed||this.renderer.getContext().isContextLost())return;throw e}return this.isDisposed?void 0:VM(this.pixels,uN,this.lensCount)}dispose(){this.isDisposed||(this.isDisposed=!0,this.target.dispose(),this.material.dispose(),this.geometry.dispose())}draw(){WM(this.renderer,this.target,()=>{this.renderer.render(this.scene,this.camera)})}async readSeam(){this.draw(),await this.renderer.readRenderTargetPixelsAsync(this.target,0,0,uN,2,this.pixels)}};function fN(e,t){return Array.from({length:e},()=>{let e=new DD;return e.flipY=!1,e.colorSpace=``,e.magFilter=iC,pN(e,t),e})}function pN(e,t){e.minFilter=t.minFilter,e.generateMipmaps=t.generateMipmaps,e.anisotropy=t.anisotropy}var mN={programs:sN,defines:pM};function hN(e,t){let n=n=>LM(e,{chunks:t.programs[n],defines:t.defines});return{rectilinear:n(`rectilinear`),equirectangular:n(`equirectangular`),"lens-tiles":n(`lens-tiles`)}}function gN(e,t,n){let r=new mO;for(let i of Object.values(n)){let n=new eE;n.add(new vD(t,i)),UM(e,n,r)}}function _N(e){for(let t of Object.values(e))t.dispose()}var vN={shaders:mN,uniforms:{}},yN=class{parts;canvas;framing=sl;viewMode=Ec;hasFrames=!1;isDisposed=!1;meters=/* @__PURE__ */ new Set;constructor(e,t){this.parts=e,this.canvas=t,this.applyFraming(),t.addEventListener(`webglcontextrestored`,this.onContextRestored)}static create(e,t,n={}){let r={options:n,pictures:vN};return new this(this.openParts(e,t,r),e)}static openParts(e,t,n){bN(t);let r=RM(e,n.options);try{return{...SN(r,t,n.pictures),drawSchedule:n.options.drawSchedule??tM}}catch(e){throw r.dispose(),e}}get lensCount(){return this.parts.lensCount}setFraming(e){this.ensureLive(),this.framing=e,this.applyFraming(),this.redraw()}setViewMode(e){this.ensureLive(),this.viewMode=e,this.applyFraming(),this.redraw()}setQuality(e){this.ensureLive();let t=uM[e];for(let e of this.parts.textures)pN(e,t),this.hasFrames&&(e.needsUpdate=!0);SM(this.parts.uniforms,t),this.redraw()}setLensGains(e){this.ensureLive();for(let[t,n]of e.entries())wM(this.parts.uniforms,t,n);this.redraw()}createSeamMeter(){this.ensureLive();let e=new dN(this.parts.renderer,this.parts.uniforms,this.parts.lensCount);return this.tracked({measure:()=>e.measure(),dispose:()=>{e.dispose()}})}setStabilization(e){this.ensureLive(),CM(this.parts.uniforms,e)}present(e){this.ensureLive();let{frames:t}=e.pair;N(t.length===this.parts.textures.length,`a pair of ${t.length} frames does not fit ${this.parts.textures.length} lens textures`);for(let[e,n]of this.parts.textures.entries()){let r=t[e];r&&n.setFrame(r.handle)}this.parts.matrixCorrections.follow(t.map(e=>e.handle)),this.hasFrames=!0,this.drawNow()}resize(e){this.ensureLive(),this.parts.renderer.setSize(e.width,e.height,!1),this.applyFraming(),this.drawNow()}dispose(){if(!this.isDisposed){this.isDisposed=!0,this.parts.drawSchedule.cancel(),this.canvas.removeEventListener(`webglcontextrestored`,this.onContextRestored);for(let e of this.meters)e.dispose();this.parts.seamProof.dispose();for(let e of this.parts.textures)e.dispose();_N(this.parts.materials),this.parts.pass.geometry.dispose(),this.parts.renderer.dispose()}}get webgl(){return this.parts.renderer}get uniforms(){return this.parts.uniforms}tracked(e){let t={...e,dispose:()=>{this.meters.delete(t),e.dispose()}};return this.meters.add(t),t}redraw(){this.parts.drawSchedule.request(this.draw)}ensureLive(){N(!this.isDisposed,`the renderer has been disposed`)}onContextRestored=()=>{this.redraw()};drawNow(){this.parts.drawSchedule.cancel(),this.draw()}draw=()=>{this.hasFrames&&this.parts.renderer.render(this.parts.scene,this.parts.camera)};applyFraming(){let e={width:this.canvas.width,height:this.canvas.height},t=Il(this.viewMode).picture(this.framing,{viewport:e,lensCount:this.parts.lensCount});this.parts.pass.material=this.parts.materials[t.kind],EM(this.parts.uniforms,t,jc(e))}};function bN(e){if(!(e.lenses.length<=2&&e.frameSlotCount<=2))throw new j(`unsupported-layout`,`the renderer draws at most 2 lenses from 2 frames; the layout has ${e.lenses.length} lenses in ${e.frameSlotCount} frames`)}function xN(e,t){let n=uM[Sc],r=fN(e.frameSlotCount,n),i=mM(e,r);return SM(i,n),{textures:r,uniforms:i,materials:hN({...i,...t.uniforms},t.shaders)}}function SN(e,t,n){let{textures:r,uniforms:i,materials:a}=xN(t,n),o=new vD(FM(),a.rectilinear),s=CN(e,{pass:o,materials:a,textures:r,uniforms:i}),c=new eE;return c.add(o),{renderer:e,scene:c,camera:new mO,pass:o,materials:a,textures:r,uniforms:i,matrixCorrections:new rM(t.lenses,i.uLensMatrixCorrection),lensCount:t.lenses.length,seamProof:s}}function CN(e,t){let{pass:n,materials:r,textures:i,uniforms:a}=t;try{return gN(e,n.geometry,r),new dN(e,a,a.uLensCount.value)}catch(e){_N(r),n.geometry.dispose();for(let e of i)e.dispose();throw e}}var wN={request:e=>requestAnimationFrame(e),cancel:e=>{cancelAnimationFrame(e)}},TN=class{frames;pendingDraw;handle;constructor(e=wN){this.frames=e}request(e){let t=this.pendingDraw!==void 0;this.pendingDraw=e,t||(this.handle=this.frames.request(this.drawPending))}cancel(){this.pendingDraw=void 0,this.handle!==void 0&&(this.frames.cancel(this.handle),this.handle=void 0)}drawPending=()=>{let e=this.pendingDraw;this.pendingDraw=void 0,this.handle=void 0,e?.()}},EN=class{actions=[];isDisposed=!1;add(e){if(this.isDisposed){e();return}this.actions.push(e)}disposeAll(){if(!this.isDisposed){this.isDisposed=!0;for(let e of this.actions.splice(0).toReversed())e()}}toDisposer(){return()=>{this.disposeAll()}}},DN={maxPendingPackets:4,pairTolerance:R(5e-4)},ON=`the recording has no audio track; playback follows a silent clock`,kN=`this browser cannot play the audio track through Media Source Extensions; playback follows a silent clock`,AN=`the audio track could not be prepared for playback; playback follows a silent clock`;async function jN(e){let t=new EN;try{let n=await PN(e);t.add(()=>{n.clock.dispose()}),e.signal.throwIfAborted();let r=MN(e,t),i=zN(e,n.clock,r.gainMatching);return t.add(()=>{i.dispose()}),RN(i,e.opened),{session:i,renderer:r.renderer,...NN(r,i),soundWarnings:n.warnings,dispose:t.toDisposer()}}catch(e){throw t.disposeAll(),e}}function MN(e,t){let n=yN.create(e.host.canvas,IN(e.opened),{drawSchedule:new TN});t.add(()=>{n.dispose()});let{sink:r,stabilizing:i}=LN(n,e.opened),a=new su(r,n);return t.add(()=>{a.dispose()}),{renderer:n,stabilizing:i,gainMatching:a}}function NN(e,t){return{setStabilization:n=>{e.stabilizing?.setStabilizer(tc(n)),t.redraw()},setQuality:t=>{e.renderer.setQuality(t)},setGainMatching:n=>{n?e.gainMatching.enable():e.gainMatching.disable(),t.redraw()}}}async function PN(e){let{soundSegments:t}=e.opened;if(!t)return FN(ON);try{let n=t();return JS.isSupported(n)?(e.signal.throwIfAborted(),{clock:await JS.open(e.host.audio,n),warnings:[]}):FN(kN)}catch(e){return FN(`${AN} (${ie(e)})`)}}function FN(e){return{clock:new hf(()=>pt(performance.now())),warnings:[e]}}function IN(e){return Zl({calibration:e.calibration,layout:e.layout,displayConversions:e.displayConversions})}function LN(e,t){if(!t.motion)return e.setStabilization(Fi.toBody),{sink:e,stabilizing:void 0};let n=new nu({sink:e,motion:t.motion,frameTimes:t.frameTimes});return{sink:n,stabilizing:n}}function RN(e,t){e.events.on(`statechange`,e=>{vf(e)&&t.readAhead()})}function zN(e,t,n){return new Ff({frameSources:e.opened.frameSources,decoderPort:e.decoderPort,clock:t,sink:n,duration:e.opened.duration,buffer:e.opened.buffer,pipeline:DN,queueCapacity:4})}var BN=class{events;play;isLoopingValue=!1;constructor(e,t){this.events=e,this.play=t}get isLooping(){return this.isLoopingValue}setLooping(e){this.isLoopingValue=e}async autoplay(){try{await this.play()}catch(e){this.events.emit(`warning`,M(e,`playback-blocked`)?{code:`autoplay-blocked`,message:`playback waits for a user gesture`}:{code:`playback-failed`,message:`autoplay failed: ${ie(e)}`})}}ended(){this.events.emit(`ended`,void 0),this.isLoopingValue&&this.replay()}async replay(){try{await this.play()}catch(e){this.events.emit(`warning`,{code:`playback-failed`,message:`the loop could not restart playback: ${ie(e)}`})}}};function VN(e,t,n=Sc){let r=yr(t,1,wc(n));return{width:Math.max(1,Math.round(e.width*r)),height:Math.max(1,Math.round(e.height*r))}}function HN(e){let{width:t,height:n}=e.getBoundingClientRect();return{width:t,height:n}}var UN=class{canvas;renderer;observer;ratioWatch=new AbortController;quality=Sc;constructor(e,t){this.canvas=e,this.renderer=t,this.observer=new ResizeObserver(()=>{this.fit()}),this.observer.observe(e),this.watchPixelRatio(),this.fit()}setQuality(e){this.quality=e,this.fit()}dispose(){this.observer.disconnect(),this.ratioWatch.abort()}watchPixelRatio(){globalThis.matchMedia(`(resolution: ${globalThis.devicePixelRatio}dppx)`).addEventListener(`change`,()=>{this.fit(),this.watchPixelRatio()},{once:!0,signal:this.ratioWatch.signal})}fit(){let e=VN(HN(this.canvas),globalThis.devicePixelRatio,this.quality);(e.width!==this.canvas.width||e.height!==this.canvas.height)&&this.renderer.resize(e)}},WN=class{tick;scheduler;isActive=!1;handle;constructor(e,t=wN){this.tick=e,this.scheduler=t}start(){this.isActive||(this.isActive=!0,this.schedule())}stop(){this.isActive=!1,this.handle!==void 0&&(this.scheduler.cancel(this.handle),this.handle=void 0)}schedule(){this.handle=this.scheduler.request(()=>{this.handle=void 0,this.tick(),this.isActive&&this.schedule()})}};async function GN(e,t){let{ports:n,signal:r}=t,i=await cf(e,n.decoderPort,XN(t));if(r.throwIfAborted(),!i.canDecode)throw JN(i)}var KN={"no-key-frame":{code:`no-key-frame`,message:`the recording has no key frame to start decoding from`},"key-frame-late":{code:`source-unreadable`,message:`the recording's first frames did not arrive in time`}},qN={code:`codec-unsupported`,message:`this browser cannot decode the recording`};function JN(e){let t=YN(e),{code:n,message:r}=(t===void 0?void 0:KN[t])??qN;return new j(n,`${r}: ${ZN(e)}`)}function YN(e){let t=new Set(e.sources.filter(e=>e.verdict!==`decodes`).map(e=>e.verdict));t.has(`key-frame-late`)&&t.delete(`timed-out`);let[n]=t;return t.size===1?n:void 0}function XN(e){let t=e.ports.probeDeadline();return e.signal.addEventListener(`abort`,()=>{t.resolve()},{once:!0}),t}function ZN(e){return e.sources.filter(e=>e.verdict!==`decodes`).map(e=>`track ${e.track.trackIndex} ${e.verdict}${e.detail?` (${e.detail})`:``}`).join(`; `)}async function QN(e,t){let{ports:n,signal:r}=t,i=e.map(e=>({input:e,opened:n.sources.open(e,r)})),a=await rP(i,n);r.throwIfAborted();let o=[...i,...await tP(i,a,t)],s=await Promise.all(o.map(e=>eP(e,n)));return r.throwIfAborted(),{recording:a,inputs:s}}function $N(e){let t=e.codecs.video.map(({description:e})=>({description:e}));return{name:CS(e.input),videoTracks:t}}async function eP(e,t){let{source:n}=e.opened,{table:r,movieBytes:i}=await Yo(n),a=await t.codecReader.read(i);return{...e,table:r,codecs:a,size:await n.size()}}async function tP(e,t,n){if(e.length!==1||t.info.fileLayout!==`split-files`||!n.findSecondFile)return[];let r=await n.findSecondFile();return n.signal.throwIfAborted(),r===void 0?[]:[{input:r,opened:n.ports.sources.open(r,n.signal)}]}var nP={fileLayout:void 0,trackOrder:void 0};async function rP(e,t){try{return await aP(e.map(({opened:e})=>e.source))}catch(n){let[r]=e;throw e.length===1&&M(n,`invalid-trailer`)&&r&&await iP(r,t),n}}async function iP(e,t){let n;try{n=await eP(e,t)}catch{return}try{os([$N(n)],nP)}catch(e){if(M(e,`missing-second-file`))throw e}}async function aP(e){let[t,n]=e;N(t!==void 0,`a recording needs at least one input`);try{return await $n(t)}catch(e){if(n===void 0||!M(e,`invalid-trailer`))throw e;return $n(n)}}async function oP(e,t){let n=new EN;try{let r=await QN(e,t),i=os(r.inputs.map(e=>$N(e)),r.recording.info),a=lP(r.recording),o=sP(r.inputs,n),s=Xl(i).map(e=>cP(o,e));await GN(s,t);let c=await pa(r.recording,s[0]);return t.signal.throwIfAborted(),uP({read:r,files:o,layout:i,frameSources:s,calibration:a,timing:c},t.ports.audioPackager,n)}catch(e){throw n.disposeAll(),e}}function sP(e,t){return e.map(({opened:n,table:r,codecs:i,size:a})=>{let o=Ld({size:a,duration:r.duration},e.length),s=wd({table:r,stream:n.stream,codecs:i,policy:o});return t.add(()=>{s.dispose()}),s})}function cP(e,t){let n=e[t.inputIndex]?.videoTracks[t.trackIndex];return N(n!==void 0,`the layout points at track ${t.trackIndex} of input ${t.inputIndex}, which does not exist`),n}function lP(e){let{calibration:t,warnings:n}=e.calibration;if(t)return t;throw new j(`no-calibration`,`the recording carries no usable lens calibration, so it cannot be stitched${n.length>0?` (${n.join(`; `)})`:``}`)}function uP(e,t,n){let{read:r,files:i,layout:a,frameSources:o,calibration:s,timing:c}=e,l=R(Math.min(...i.map(e=>e.duration))),u=Ou(o.map(e=>e.description.colour)),[d]=i.flatMap(e=>e.audioTracks);return{recording:r.recording,layout:a,frameSources:o,calibration:s,displayConversions:u.conversions,duration:l,frameTimes:c.frameTimes,motion:c.motion,soundSegments:d&&(()=>t.segmentsOf(d.samples,d.configuration)),metadata:dP(e,l,d!==void 0),warnings:[...c.warnings,...u.warnings],readAhead:()=>{for(let e of i)e.download.startReadingAhead()},buffer:new Rd(i.map(e=>e.download)),dispose:n.toDisposer()}}function dP(e,t,n){let{info:r}=e.read.recording,{motion:i}=e.timing;return{model:r.model,firmware:r.firmware,captureMode:r.captureMode,layout:e.layout.kind,layoutEvidence:e.layout.evidence,tracks:e.frameSources.map(e=>e.description),calibrationVersion:e.calibration.version,frameTimeSource:e.timing.frameTimeSource,hasGyro:i!==void 0,imuFrame:i&&{name:i.imuFrame.name,isVerified:i.imuFrame.isVerified},hasAudio:n,duration:t}}async function fP(e,t,n){let r=pP(e,t,n),i=e.second?[e.main,e.second]:[e.main];try{return await oP(i,r)}catch(t){let{findSecondFile:i}=r;if(!i||!M(t,`missing-second-file`))throw t;let a=await i();if(n.throwIfAborted(),!a)throw t;return oP([e.main,a],r)}}function pP(e,t,n){let{main:r}=e;return e.second===void 0&&SS(r)?{ports:t,signal:n,findSecondFile:$e(()=>mP(r,t))}:{ports:t,signal:n}}async function mP(e,t){let n=await Da(e.url,t.locatorFor(e));return n===void 0?void 0:{...e,url:n}}async function hP(e){let{parts:t,signal:n}=e,r=await fP(e.source,t.ports,n),i=new EN;i.add(()=>{r.dispose()});try{let e=await t.pipelines({opened:r,host:t.host,decoderPort:t.ports.decoderPort,signal:n});i.add(()=>{e.dispose()}),n.throwIfAborted();let a=new UN(t.host.canvas,e.renderer);i.add(()=>{a.dispose()});let o=gP(e,a);return{opened:r,pipeline:o,warnings:_P(r,o),dispose:i.toDisposer()}}catch(e){throw i.disposeAll(),e}}function gP(e,t){return{...e,setQuality:n=>{e.setQuality(n),t.setQuality(n)}}}function _P(e,t){return[...e.warnings.map(e=>({code:`recording-degraded`,message:e})),...t.soundWarnings.map(e=>({code:`no-sound`,message:e}))]}var vP=class{parts;stateValue;request;generation=0;stopHearing;stopFollowingAvailability;wasRefused=!1;constructor(e){this.parts=e,this.stateValue=e.sensor.availability===`available`?`off`:`unavailable`}get state(){return this.stateValue}start(){return this.followAvailability(),this.stateValue===`off`?(this.request??=this.ask(),this.request):Promise.resolve(this.stateValue)}stop(){this.overtakeRequest(),this.stateValue===`on`&&this.change(`off`)}reconsider(){this.reconsiderAvailability(),this.reconsiderHearing()}dispose(){this.overtakeRequest(),this.stopFollowingAvailability?.(),this.stopFollowingAvailability=void 0,this.stopHearing?.(),this.stopHearing=void 0,this.parts.sensor.dispose()}reconsiderAvailability(){let e=this.parts.hasRecording();e&&!this.stopFollowingAvailability?(this.stopFollowingAvailability=this.parts.sensor.onAvailabilityChange(()=>{this.followAvailability()}),this.followAvailability()):!e&&this.stopFollowingAvailability&&(this.stopFollowingAvailability(),this.stopFollowingAvailability=void 0)}reconsiderHearing(){let{sensor:e,view:t,hasRecording:n}=this.parts,r=this.stateValue===`on`&&n()&&t.followsDevice;r&&!this.stopHearing?this.stopHearing=e.listen(e=>{t.followDevice(e)}):!r&&this.stopHearing&&(this.stopHearing(),this.stopHearing=void 0,t.letGo())}followAvailability(){let e=this.parts.sensor.availability===`available`;this.wasRefused||e===(this.stateValue!==`unavailable`)||(this.overtakeRequest(),this.change(e?`off`:`unavailable`))}async ask(){let e=this.generation,t=await this.accessOrGesture();return e===this.generation?(this.request=void 0,this.answer(t),this.stateValue):this.stateValue}async accessOrGesture(){try{return await this.parts.sensor.requestAccess()}catch{return`needs-gesture`}}answer(e){e===`granted`?this.change(`on`):e===`denied`?(this.wasRefused=!0,this.change(`unavailable`),this.warn(`motion-look-refused`,yP)):this.warn(`motion-look-needs-gesture`,bP)}overtakeRequest(){this.generation+=1,this.request=void 0}change(e){this.stateValue=e,this.reconsiderHearing(),this.parts.events.emit(`motionlookchange`,e)}warn(e,t){this.parts.events.emit(`warning`,{code:e,message:t})}},yP="motion look was refused: by the viewer, or by an iframe whose `allow` leaves out accelerometer, gyroscope and magnetometer",bP=`motion look asks for access, which this browser grants only from a user gesture such as a tap`,xP={kind:`idle`};function SP(){return{kind:`loading`,controller:new AbortController,settled:new Wd}}function CP(e){switch(e.kind){case`idle`:return`idle`;case`loading`:return`loading`;case`loaded`:return e.loaded.pipeline.session.state;case`failed`:return`error`}}var wP=class{events;mode=Js;isMatching=!0;qualityValue=Sc;target;constructor(e){this.events=e}get stabilization(){return this.mode}get quality(){return this.qualityValue}attach(e){this.target=e,e?.setStabilization(this.mode),e?.setGainMatching(this.isMatching),e?.setQuality(this.qualityValue)}setStabilization(e){e!==this.mode&&(this.mode=e,this.target?.setStabilization(e),this.events.emit(`stabilizationchange`,e))}setGainMatching(e){this.isMatching=e,this.target?.setGainMatching(e)}setQuality(e){e!==this.qualityValue&&(this.qualityValue=e,this.target?.setQuality(e),this.events.emit(`qualitychange`,e))}},TP=class{audio;events;canSetVolume;constructor(e,t){this.audio=e,this.events=t,this.canSetVolume=DP(e.ownerDocument),e.addEventListener(`volumechange`,this.onVolumeChange)}get volume(){return this.audio.volume}get isMuted(){return this.audio.muted}setVolume(e){this.audio.volume=yr(e,0,1)}setMuted(e){this.audio.muted=e}dispose(){this.audio.removeEventListener(`volumechange`,this.onVolumeChange)}onVolumeChange=()=>{this.events.emit(`volumechange`,{volume:this.volume,isMuted:this.isMuted})}},EP=.5;function DP(e){let t=e.createElement(`audio`);return t.volume=EP,t.volume===EP}function OP(e){return{yaw:e.yaw,pitch:e.pitch,fieldOfView:e.fieldOfView}}function kP(e,t){return e.yaw===t.yaw&&e.pitch===t.pitch&&e.fieldOfView===t.fieldOfView}var AP=2,jP=class{events;measureViewport;framing=sl;mode=Ec;surface;lensCount=AP;previous;constructor(e,t){this.events=e,this.measureViewport=t}get current(){return this.framing.view}get viewMode(){return this.mode}get canPan(){return this.rules().canPan(this.framing)}get followsDevice(){return Rl(this.mode)!==void 0}attach(e){this.surface=e,e&&(this.lensCount=e.lensCount),e?.setViewMode(this.mode),e?.setFraming(this.framing)}set(e){this.frame(this.rules().place(this.framing,e))}setMode(e){e!==this.mode&&(this.mode=e,this.surface?.setViewMode(e),this.events.emit(`viewmodechange`,e))}lookAt(e,t){this.frame(this.rules().place(this.framing,Zc(this.framing.view,e,t)))}followDevice(e){let t=Sl(this.framing.view,this.previous,e);this.previous=t.reading,this.frame({...this.framing,view:t.view})}letGo(){this.previous&&(this.previous=void 0,this.frame({...this.framing,view:Tl(this.framing.view)}))}pan(e){this.frame(this.rules().pan(this.framing,e,this.context()))}turn(e,t){this.frame(this.rules().turn(this.framing,{yaw:e,pitch:t},this.context()))}zoom(e,t=kc){this.frame(this.rules().zoom(this.framing,{steps:e,focus:t},this.context()))}reset(){this.frame(this.rules().reset(this.framing))}frame(e){if(cl(e,this.framing))return;let t=!kP(e.view,this.framing.view);this.framing=e,this.surface?.setFraming(e),t&&this.events.emit(`viewchange`,OP(e.view))}context(){return{viewport:this.measureViewport(),lensCount:this.lensCount}}rules(){return(this.previous===void 0?void 0:Rl(this.mode))??Il(this.mode)}},MP=/* @__PURE__ */ new Set([`ready`,`paused`,`ended`]),NP=/* @__PURE__ */ new Map([[`playing`,`playing`],[`buffering`,`waiting`]]);function PP(e,t){return t===`seeking`?[`seeking`]:e===`seeking`?t===`buffering`?[`seeked`,`waiting`]:[`seeked`]:t===`paused`?e===`ready`?[]:[`pause`]:FP(e,t)}function FP(e,t){let n=NP.get(t);return n===void 0?[]:e===void 0||MP.has(e)?[`play`,n]:[n]}var IP=class{targets;stopListening=[];lastState;detachments=0;constructor(e){this.targets=e}attach(e){this.detach(),this.lastState=e.state;let{events:t}=this.targets;this.stopListening=[e.events.on(`statechange`,t=>{this.onStateChange(t,e)}),e.events.on(`timeupdate`,e=>{t.emit(`timeupdate`,e)}),e.events.on(`present`,e=>{t.emit(`frame`,e)}),e.events.on(`ended`,()=>{this.targets.onEnded()}),e.events.on(`error`,e=>{t.emit(`error`,e)})]}detach(){for(let e of this.stopListening)e();this.stopListening=[],this.lastState=void 0,this.detachments+=1}onStateChange(e,t){let n=this.lastState;this.lastState=e;let r=this.detachments;for(let i of PP(n,e))if(this.emitTransport(i,t),this.detachments!==r)return;this.targets.onState(e)}emitTransport(e,t){let{events:n}=this.targets;e===`seeking`||e===`seeked`?n.emit(e,t.currentTime):n.emit(e,void 0)}},LP=class{parts;events=new bf;outbox=new Pu(this.events);loop;phase=xP;viewing;motion;picture=new wP(this.outbox);pendingStartTime;sound;relay=new IP({events:this.outbox,onState:()=>{this.announceStatus()},onEnded:()=>{this.starts.ended()}});starts=new BN(this.outbox,()=>this.play());isDisposed=!1;lastStatus=`idle`;constructor(e){this.parts=e,this.loop=new WN(this.tick),e.host.audio.addEventListener(`ended`,this.tick),this.sound=new TP(e.host.audio,this.outbox);let{canvas:t}=e.host;this.viewing=new jP(this.outbox,()=>HN(t)),this.motion=new vP({sensor:e.attitude??_p,view:this.viewing,events:this.outbox,hasRecording:()=>this.loaded!==void 0})}get status(){return CP(this.phase)}get metadata(){return this.loaded?.opened.metadata}get currentTime(){return this.loaded?.pipeline.session.currentTime??R(0)}get duration(){return this.loaded?.opened.duration??R(0)}get isPaused(){return!vf(this.loaded?.pipeline.session.state)}get view(){return OP(this.viewing.current)}get viewMode(){return this.viewing.viewMode}get canPan(){return this.viewing.canPan}get motionLook(){return this.motion.state}get stabilization(){return this.picture.stabilization}get quality(){return this.picture.quality}get isLooping(){return this.starts.isLooping}get volume(){return this.sound.volume}get isMuted(){return this.sound.isMuted}get canSetVolume(){return this.sound.canSetVolume}async load(e,t={}){if(this.isDisposed)return;let n=this.outbox.change(()=>{this.unload();let e=SP();return this.phase=e,this.announceStatus(),e});try{await this.complete(n,e,t)}catch(e){if(n.controller.signal.aborted)return;throw this.failWith(e)}finally{n.settled.resolve()}}unload(){this.outbox.change(()=>{this.release(),this.announceStatus()})}async play(){if(await this.loadInProgress(),this.phase.kind===`failed`)throw this.phase.failure;await this.loaded?.pipeline.session.play()}pause(){this.loaded?.pipeline.session.pause()}stop(){this.loaded?.pipeline.session.stop()}seek(e){Jf(e,`time`);let t=this.loaded?.pipeline.session;t&&t.state!==`error`?t.seek(R(e)):this.pendingStartTime=R(e)}async scrub(e){Jf(e,`time`),await this.loaded?.pipeline.session.scrub(R(e))}setView(e){this.viewing.set(Yf(e))}lookAt(e,n){Jf(e,`yaw`),Jf(n,`pitch`),this.viewing.lookAt(t(e),t(n))}pan(e){this.viewing.pan(e)}turn(e,n){Jf(e,`yaw turn`),Jf(n,`pitch turn`),this.viewing.turn(t(e),t(n))}zoom(e,t){Jf(e,`zoom steps`),this.viewing.zoom(e,t)}resetView(){this.viewing.reset()}setViewMode(e){this.viewing.setMode(e),this.motion.reconsider()}startMotionLook(){return this.motion.start()}stopMotionLook(){this.motion.stop()}setStabilization(e){this.picture.setStabilization(e)}setQuality(e){this.picture.setQuality(e)}setLooping(e){this.starts.setLooping(e)}setGainMatching(e){this.picture.setGainMatching(e)}setVolume(e){Jf(e,`volume`),this.sound.setVolume(e)}setMuted(e){this.sound.setMuted(e)}dispose(){this.isDisposed=!0,this.unload(),this.motion.dispose(),this.parts.host.audio.removeEventListener(`ended`,this.tick),this.sound.dispose(),this.events.removeAll()}tick=()=>{this.loaded?.pipeline.session.tick()};async loadInProgress(){this.phase.kind===`loading`&&await this.phase.settled.promise}get loaded(){return this.phase.kind===`loaded`?this.phase.loaded:void 0}async complete(e,t,n){let{signal:r}=e.controller,i=await hP({source:t,parts:this.parts,signal:r});if(r.aborted){i.dispose();return}this.outbox.change(()=>{this.attach(i,e.controller),this.startAtPendingTime(i),n.preload!==!1&&i.pipeline.session.preload()}),n.autoplay&&this.loaded===i&&await this.starts.autoplay()}startAtPendingTime(e){let t=this.pendingStartTime;this.pendingStartTime=void 0,t!==void 0&&e.pipeline.session.seek(t)}attach(e,t){this.phase={kind:`loaded`,loaded:e,controller:t},this.viewing.attach(e.pipeline.renderer),this.motion.reconsider();let{session:n}=e.pipeline;this.picture.attach(e.pipeline),this.relay.attach(n),this.loop.start(),this.announceStatus();for(let t of e.warnings)this.outbox.emit(`warning`,t);this.outbox.emit(`ready`,e.opened.metadata)}release(){let e=this.phase;this.phase=xP,e.kind===`loading`&&e.controller.abort(),this.loop.stop(),this.relay.detach(),this.viewing.attach(void 0),this.motion.reconsider(),this.picture.attach(void 0),e.kind===`loaded`&&(e.loaded.dispose(),e.controller.abort())}failWith(e){let t=ne(e,`invariant-violation`,`the player failed unexpectedly`);return this.outbox.change(()=>{this.release(),this.phase={kind:`failed`,failure:t},this.announceStatus(),this.outbox.emit(`error`,t)}),t}announceStatus(){let{status:e}=this;this.outbox.post(()=>{e!==this.lastStatus&&(this.lastStatus=e,this.events.emit(`statuschange`,e))})}};function RP(e,t){return new LP({host:e,ports:TS(t),pipelines:jN,attitude:new Sp})}function zP(e,t={}){let n=t.signal??new AbortController().signal,{source:r}=ES(t.http??{}).open(BP(e),n);return dr(r)}function BP(e){return typeof e==`string`?{url:e}:{blob:e,name:e instanceof File?e.name:``}}var VP={Src:`src`,Src2:`src2`},HP={CrossOrigin:`crossorigin`},UP={FieldOfView:`fov`,Yaw:`yaw`,Pitch:`pitch`},WP={Autoplay:`autoplay`,Preload:`preload`,GainMatch:`gain-match`,Muted:`muted`,Loop:`loop`,Stabilization:`stabilization`,ViewMode:`view-mode`,Quality:`quality`,Controls:`controls`,Poster:`poster`},GP=[...Object.values(VP),...Object.values(HP),...Object.values(UP),...Object.values(WP)];function KP(e,t){let n=JP(e(HP.CrossOrigin)),r=qP(e(VP.Src),t,n);return r&&{main:r,second:qP(e(VP.Src2),t,n)}}function qP(e,t,n){let r=e?.trim()??``;return r===``?void 0:{url:YP(r,t),...n}}function JP(e){return Wf(iF,e)===`use-credentials`?{credentials:`include`}:{}}function YP(e,t){try{return new URL(e,t).href}catch{return e}}var XP={[UP.FieldOfView]:`fieldOfView`,[UP.Yaw]:`yaw`,[UP.Pitch]:`pitch`};function ZP(e,t,n){let r=XP[t],i=$P(n);return r===void 0||i===void 0?e:{...e,[r]:i}}function QP(e){return e!==null}function $P(e){if(e===null||e.trim()===``)return;let t=Number(e);return Number.isFinite(t)?t:void 0}function eF(e,t,n){return{code:`ignored-attribute`,message:`ignoring ${e}="${t}"; expected one of ${n.join(`, `)}`}}function tF(e,t){return t===null||$P(t)!==void 0?void 0:{code:`ignored-attribute`,message:`ignoring ${e}="${t}"; expected a number of degrees`}}var nF={name:WP.Preload,keywords:[`none`,`auto`],fallback:`auto`},rF={name:WP.GainMatch,keywords:[`on`,`off`],fallback:`on`},iF={name:HP.CrossOrigin,property:`crossOrigin`,keywords:[`anonymous`,`use-credentials`],fallback:`anonymous`};function aF(e){return Wf(nF,e)===`auto`}function oF(e){return Wf(rF,e)===`on`}function sF(e,t,n){return n?cF(n):KP(e,t)}function cF(e){return{main:{blob:e.main,name:e.main.name},second:e.second&&{blob:e.second,name:e.second.name}}}var lF=class{element;player;scheduled;isOwed=!0;awaited;startTime;files;constructor(e,t){this.element=e,this.player=t}connected(){this.isOwed&&this.schedule(),this.awaited?.follow(this.scheduled??Promise.resolve()),this.awaited=void 0}async disconnected(){await Promise.resolve(),!this.element.isConnected&&(this.player.unload(),this.isOwed=!0)}sourceChanged(){this.files=void 0,this.schedule()}requestChanged(){this.files===void 0&&this.schedule()}loadFiles(e){this.files=e,this.schedule()}load(){return this.element.isConnected?this.scheduled??this.reload():this.loadOnConnection()}seek(e){this.scheduled?this.startTime=e:this.player.seek(e)}async settled(){try{await this.scheduled}catch{}}loadOnConnection(){return this.isOwed=!0,this.awaited??=new Wd,this.awaited.promise}schedule(){if(this.isOwed=!this.element.isConnected,this.scheduled||!this.element.isConnected)return;let e=this.loadAfterPendingChanges();this.scheduled=e,e.catch(uF)}async loadAfterPendingChanges(){await Promise.resolve(),this.scheduled=void 0,this.element.isConnected&&await this.reload()}reload(){this.isOwed=!1;let e=e=>this.element.getAttribute(e),t=sF(e,document.baseURI,this.files);delete this.element.dataset.hasFrame;let n=this.startTime;if(this.startTime=void 0,!t)return this.player.unload(),Promise.resolve();let r=this.player.load(t,{autoplay:this.element.autoplay,preload:aF(e(WP.Preload))});return n!==void 0&&this.player.seek(n),r}};function uF(){}var dF=`data-fill`,fF=class{element;constructor(e){this.element=e}get isActive(){return this.isNativelyFullscreen()||this.element.hasAttribute(dF)}async toggle(){await(this.isActive?this.exit():this.enter())}async exit(){this.isNativelyFullscreen()&&await document.exitFullscreen(),this.element.removeAttribute(dF)}isNativelyFullscreen(){return this.element.matches(`:fullscreen`)}async enter(){if(document.fullscreenEnabled)try{await this.element.requestFullscreen();return}catch{}this.element.setAttribute(dF,``)}},pF=`data-idle`,mF=2500,hF=[`pointermove`,`pointerdown`,`keydown`,`focusin`],gF={capture:!0},_F=class{element;shouldHide;timer;wasIdleAtPress=!1;constructor(e,t){this.element=e,this.shouldHide=t}get wasIdleAtLastPress(){return this.wasIdleAtPress}start(){this.element.addEventListener(`pointerdown`,this.onPress,gF);for(let e of hF)this.element.addEventListener(e,this.onActivity,gF);this.onActivity()}stop(){for(let e of hF)this.element.removeEventListener(e,this.onActivity,gF);this.element.removeEventListener(`pointerdown`,this.onPress,gF),this.clearTimer(),this.element.removeAttribute(pF)}refresh(){this.shouldHide()||this.element.removeAttribute(pF),this.restart()}onPress=()=>{this.wasIdleAtPress=this.element.hasAttribute(pF)};onActivity=()=>{this.element.removeAttribute(pF),this.restart()};restart(){this.clearTimer(),this.timer=setTimeout(()=>{this.shouldHide()&&this.element.setAttribute(pF,``)},mF)}clearTimer(){this.timer!==void 0&&clearTimeout(this.timer),this.timer=void 0}};function vF(e,t,n){return({player:r,warn:i},a)=>{let o=If(a,t);o?n(r,o):a!==null&&i(eF(e,a,t))}}var yF={[WP.Stabilization]:vF(WP.Stabilization,qs,(e,t)=>{e.setStabilization(t)}),[WP.ViewMode]:vF(WP.ViewMode,Tc,(e,t)=>{e.setViewMode(t)}),[WP.Quality]:vF(WP.Quality,xc,(e,t)=>{e.setQuality(t)}),[WP.Muted]:({player:e},t)=>{e.setMuted(QP(t))},[WP.Loop]:({player:e},t)=>{e.setLooping(QP(t))},[WP.Poster]:({posterImage:e},t)=>{e.src=t??``},[WP.GainMatch]:({player:e},t)=>{e.setGainMatching(oF(t))}};function bF(e){return Object.hasOwn(yF,e)}function xF(e,t,n){bF(t)&&yF[t](e,n)}function SF(e,t){e.hasAttribute(`tabindex`)||(e.tabIndex=0),e.hasAttribute(`role`)||e.setAttribute(`role`,`region`),e.hasAttribute(`aria-label`)||e.hasAttribute(`aria-labelledby`)||e.setAttribute(`aria-label`,t)}function CF(e,t,n){e.getAttribute(`aria-label`)===t&&e.setAttribute(`aria-label`,n)}function wF(e,t){let n=/* @__PURE__ */ new Map;for(let r of t)Object.hasOwn(e,r)&&(n.set(r,Reflect.get(e,r)),Reflect.deleteProperty(e,r));return n}function TF(e,t,n){let r=[...t];t.clear();for(let[t,i]of r)try{Reflect.set(e,t,i)}catch(e){n({code:`refused-property`,message:`${t} set before the element was defined was refused: ${ie(e)}`})}}var EF=Nu({stabilization:!0,viewMode:!0,quality:!0,fov:!0,yaw:!0,pitch:!0,muted:!0,loop:!0,volume:!0});function DF(e,t){let n={stabilization:{get:()=>t.stabilization,set:NF(e=>{t.setStabilization(AF(e))})},viewMode:{get:()=>t.viewMode,set:NF(e=>{t.setViewMode(jF(e))})},quality:{get:()=>t.quality,set:NF(e=>{t.setQuality(MF(e))})},...OF(t),...kF(t)};for(let[t,r]of Object.entries(n))Object.defineProperty(e,t,{configurable:!0,enumerable:!0,...r})}function OF(e){let t=(t,n)=>({get:()=>e.view[t],set:NF(r=>{e.setView({...e.view,[t]:FF(r,n)})})});return{fov:t(`fieldOfView`,`fov`),yaw:t(`yaw`,`yaw`),pitch:t(`pitch`,`pitch`)}}function kF(e){return{muted:{get:()=>e.isMuted,set:t=>{e.setMuted(!!t)}},loop:{get:()=>e.isLooping,set:t=>{e.setLooping(!!t)}},volume:{get:()=>e.volume,set:NF(t=>{e.setVolume(IF(t,`volume`))})}}}function AF(e){return PF(e,Lf,`stabilization`)}function jF(e){return PF(e,Rf,`viewMode`)}function MF(e){return PF(e,zf,`quality`)}function NF(e){return t=>{t!=null&&t!==``&&e(t)}}function PF(e,t,n){let r=typeof e==`string`?t(e):void 0;if(r===void 0)throw new j(`invalid-argument`,`${n} cannot be ${String(e)}`);return r}function FF(e,n){return t(IF(e,n))}function IF(e,t){return Jf(e,t),e}var LF=`/*
|
|
4643
4643
|
* The controls' own styles: the big play button, the bar, its buttons, sliders and menus, and the
|
|
4644
4644
|
* grab hand over the picture. The host's custom properties (\`--gyro-view-*\`) theme them. Secondary
|
|
4645
4645
|
* words, fills and tracks are the text colour at lower strengths, so a page that changes the text
|
|
4646
4646
|
* colour changes them with it.
|
|
4647
4647
|
*
|
|
4648
|
-
*
|
|
4648
|
+
* Three things change the bar. A coarse pointer makes every target 44 pixels and leaves the
|
|
4649
4649
|
* volume to the device's own buttons. A narrow player, whatever the pointer, gives up the volume
|
|
4650
4650
|
* slider, shows the menus over the whole player, and past that gives up the time and then Reset
|
|
4651
|
-
* view (the widths below).
|
|
4652
|
-
*
|
|
4651
|
+
* view (the widths below). The motion look toggle, shown only where the device reports its
|
|
4652
|
+
* attitude, makes the bar one target wider, so each part gives way one target sooner, and on the
|
|
4653
|
+
* narrowest players the stabilization menu gives way to it: the toggle never hides, since the
|
|
4654
|
+
* device may be turning the view. Sizes are in rem like the page's text, so larger text moves the
|
|
4655
|
+
* widths with it.
|
|
4653
4656
|
*/
|
|
4654
4657
|
|
|
4655
4658
|
.big-play {
|
|
@@ -4850,7 +4853,8 @@ input[type='range']::-moz-range-thumb {
|
|
|
4850
4853
|
display: inline-flex;
|
|
4851
4854
|
}
|
|
4852
4855
|
|
|
4853
|
-
.setting[aria-expanded='true']
|
|
4856
|
+
.setting[aria-expanded='true'],
|
|
4857
|
+
.motion-look[aria-pressed='true'] {
|
|
4854
4858
|
background: color-mix(in srgb, var(--gyro-view-text) 20%, transparent);
|
|
4855
4859
|
}
|
|
4856
4860
|
|
|
@@ -5063,6 +5067,54 @@ input[type='range']::-moz-range-thumb {
|
|
|
5063
5067
|
}
|
|
5064
5068
|
}
|
|
5065
5069
|
|
|
5070
|
+
/* With the motion look toggle each width moves out by one target and its gap; below the
|
|
5071
|
+
narrowest bar that fits without it, the stabilization menu gives way to it. */
|
|
5072
|
+
@container (max-width: 26rem) {
|
|
5073
|
+
.row:has(.motion-look:not([hidden])) .time {
|
|
5074
|
+
display: none;
|
|
5075
|
+
}
|
|
5076
|
+
}
|
|
5077
|
+
|
|
5078
|
+
@container (max-width: 20rem) {
|
|
5079
|
+
.controls:has(.motion-look:not([hidden])) {
|
|
5080
|
+
padding-inline: 0.5rem;
|
|
5081
|
+
}
|
|
5082
|
+
|
|
5083
|
+
.row:has(.motion-look:not([hidden])) .reset-view {
|
|
5084
|
+
display: none;
|
|
5085
|
+
}
|
|
5086
|
+
}
|
|
5087
|
+
|
|
5088
|
+
@container (max-width: 16rem) {
|
|
5089
|
+
.row:has(.motion-look:not([hidden])) .choice:has(.stabilization-button) {
|
|
5090
|
+
display: none;
|
|
5091
|
+
}
|
|
5092
|
+
}
|
|
5093
|
+
|
|
5094
|
+
@media (pointer: coarse) {
|
|
5095
|
+
@container (max-width: 29.5rem) {
|
|
5096
|
+
.row:has(.motion-look:not([hidden])) .time {
|
|
5097
|
+
display: none;
|
|
5098
|
+
}
|
|
5099
|
+
}
|
|
5100
|
+
|
|
5101
|
+
@container (max-width: 23.5rem) {
|
|
5102
|
+
.controls:has(.motion-look:not([hidden])) {
|
|
5103
|
+
padding-inline: 0.5rem;
|
|
5104
|
+
}
|
|
5105
|
+
|
|
5106
|
+
.row:has(.motion-look:not([hidden])) .reset-view {
|
|
5107
|
+
display: none;
|
|
5108
|
+
}
|
|
5109
|
+
}
|
|
5110
|
+
|
|
5111
|
+
@container (max-width: 19rem) {
|
|
5112
|
+
.row:has(.motion-look:not([hidden])) .choice:has(.stabilization-button) {
|
|
5113
|
+
display: none;
|
|
5114
|
+
}
|
|
5115
|
+
}
|
|
5116
|
+
}
|
|
5117
|
+
|
|
5066
5118
|
/* Without a blur behind it, or for a viewer who asked for less transparency, a menu is laid
|
|
5067
5119
|
twice over itself: its own colour, near enough opaque. */
|
|
5068
5120
|
@supports not ((backdrop-filter: blur(1px)) or (-webkit-backdrop-filter: blur(1px))) {
|
|
@@ -5113,17 +5165,17 @@ canvas[data-draggable]:active {
|
|
|
5113
5165
|
transition: none;
|
|
5114
5166
|
}
|
|
5115
5167
|
}
|
|
5116
|
-
`,
|
|
5168
|
+
`,RF=`gyroview`;function zF(e){let t=document.createElement(`template`);return t.innerHTML=BF()?.createHTML(e)??e,t.content}var BF=$e(()=>{let e=globalThis.trustedTypes;try{return e?.createPolicy(RF,{createHTML:e=>e})}catch{return}});function VF(e){return`<svg class="icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" focusable="false">${e}</svg>`}function HF(e){return VF(`<g transform="scale(1.2)" stroke-width="1.5">${e}</g>`)}var UF=`<path d="M4 9.5v5h3.5L12 19V5L7.5 9.5z"/>`,WF={play:VF(`<path d="M8 5v14l11-7z" fill="currentColor"/>`),pause:VF(`<rect x="6" y="5" width="4" height="14" rx="1" fill="currentColor" stroke="none"/><rect x="14" y="5" width="4" height="14" rx="1" fill="currentColor" stroke="none"/>`),sound:VF(`${UF}<path d="M15.5 9a4 4 0 0 1 0 6"/><path d="M18.5 6a8 8 0 0 1 0 12"/>`),muted:VF(`${UF}<path d="M16 9.5l5 5M21 9.5l-5 5"/>`),resetView:VF(`<path d="M4.5 12a7.5 7.5 0 1 0 2.2-5.3"/><path d="M4.5 4.5v4h4"/>`),motionLook:VF(`<rect x="8.5" y="4.5" width="7" height="15" rx="1.5"/><path d="M11 16.5h2"/><path d="M5 8.5a7 7 0 0 0 0 7"/><path d="M19 8.5a7 7 0 0 1 0 7"/>`),fullscreen:VF(`<path d="M4 9V4h5M15 4h5v5M20 15v5h-5M9 20H4v-5"/>`),close:VF(`<path d="M6 6l12 12M18 6L6 18"/>`)},GF={off:HF(`<path d="M2 11l2.5-3 3 4.5 3-6 3 5 2-2.5L18 11"/>`),lock:HF(`<rect x="4.5" y="9" width="11" height="8" rx="1.5"/><path d="M7 9V6.5a3 3 0 016 0V9"/>`),horizon:HF(`<circle cx="10" cy="10" r="7"/><path d="M3 10h14M8 13h4"/>`),follow:HF(`<path d="M3 15c3.5 0 4-9 8.5-9 2 0 3 1 4.5 1"/><path d="M14 4.5L16.5 7 14 9.5"/>`)},KF={"raw-lenses":HF(`<circle cx="6" cy="10" r="4.25"/><circle cx="14" cy="10" r="4.25"/>`),equirectangular:HF(`<rect x="2" y="5" width="16" height="10" rx="1.5"/><path d="M2 10h16M7.5 5c-1.2 3.3-1.2 6.7 0 10M12.5 5c1.2 3.3 1.2 6.7 0 10"/>`),normal:HF(`<path d="M10 16L3.2 7.2a10 10 0 0113.6 0z"/>`)},qF=/* @__PURE__ */ new Map;function JF(e){let t=qF.get(e);return t||(t=zF(WF[e]),qF.set(e,t)),t.cloneNode(!0)}var YF={names:`stabilizationModes`,descriptions:`stabilizationModeDescriptions`},XF={names:`viewModes`,descriptions:`viewModeDescriptions`},ZF=new Set([YF,XF].flatMap(e=>[e.names,e.descriptions])),QF=`The video could not be loaded.`,$F=`This browser cannot play this video.`,eI=`This file cannot be played.`,tI=`The video could not be played.`,nI={labels:{player:`360° video player`,loading:`Loading`,play:`Play`,pause:`Pause`,seek:`Seek`,position:`{time} of {duration}`,mute:`Mute`,volume:`Volume`,resetView:`Reset view`,motionLook:`Look by moving the device`,stabilization:`Stabilization`,viewMode:`View`,fullscreen:`Fullscreen`,close:`Close`},stabilizationModes:{off:`Off`,lock:`Lock`,horizon:`Horizon`,follow:`Follow`},stabilizationModeDescriptions:{off:`Footage as the camera moved`,lock:`Orientation fixed to the world`,horizon:`Level horizon, follows heading`,follow:`Follows turns, smooths out shake`},viewModes:{"raw-lenses":`Raw lenses`,equirectangular:`Equirectangular`,normal:`Normal`},viewModeDescriptions:{"raw-lenses":`Both fisheye images as recorded`,equirectangular:`The full 360° frame, unwrapped`,normal:`Standard view, drag to look around`},errors:{"binary-out-of-bounds":eI,"binary-unsafe-integer":eI,"codec-unsupported":$F,cors:QF,decode:tI,"embed-destroyed":tI,"index-out-of-range":tI,"invalid-argument":tI,"invalid-byte-range":QF,"invalid-calibration":eI,"invalid-protobuf":eI,"invalid-trailer":eI,"invariant-violation":tI,"missing-second-file":`Part of this recording is missing.`,"no-calibration":eI,"no-info-record":eI,"no-key-frame":eI,"playback-blocked":tI,"range-unsupported":QF,"render-unavailable":$F,"source-changed":`The video was replaced while it played.`,"source-truncated":QF,"source-unreadable":QF,"unsupported-calibration":eI,"unsupported-container":eI,"unsupported-gyro-record":eI,"unsupported-info-format":eI,"unsupported-layout":eI,"webcodecs-unavailable":$F}};function rI(e){let t=sI(e)?e:{};return{labels:oI(nI.labels,t.labels),stabilizationModes:oI(nI.stabilizationModes,t.stabilizationModes),stabilizationModeDescriptions:oI(nI.stabilizationModeDescriptions,t.stabilizationModeDescriptions),viewModes:oI(nI.viewModes,t.viewModes),viewModeDescriptions:oI(nI.viewModeDescriptions,t.viewModeDescriptions),errors:oI(nI.errors,t.errors)}}function iI(e){return e!==null&&Object.hasOwn(nI.labels,e)}function aI(e){return e!==null&&ZF.has(e)}function oI(e,t){if(!sI(t))return e;let n=Object.entries(e).map(([e,n])=>{let r=t[e];return[e,typeof r==`string`?r:n]});return Object.fromEntries(n)}function sI(e){return typeof e==`object`&&!!e}var cI={Stabilization:`stabilization`,ViewMode:`view-mode`};function lI(e){return{button:`${e}-button`,popup:`${e}-menu`}}function uI(e){return e.choices.map(t=>{let n=`${e.name}-${t}`;return`<button type="button" role="menuitemradio" aria-checked="false" tabindex="-1" data-choice="${t}" aria-labelledby="${n}-name" aria-describedby="${n}-description"><span class="choice-icon">${e.icons[t]??``}</span><span class="choice-name" id="${n}-name" data-choice-text="${e.words.names}"></span><span class="choice-description" id="${n}-description" data-choice-text="${e.words.descriptions}"></span></button>`}).join(``)}function dI(e){let t=lI(e.name),[n,r]=[`${e.name}-label`,`${e.name}-value`];return`<div class="choice">
|
|
5117
5169
|
<button class="icon-button setting ${t.button}" type="button" aria-haspopup="menu" aria-expanded="false" aria-labelledby="${n} ${r}"><span class="setting-icon"></span><span hidden><span id="${n}" data-text="${e.title}"></span> <span id="${r}" data-choice-text="${e.words.names}"></span></span></button>
|
|
5118
5170
|
<div class="popup ${t.popup}" hidden>
|
|
5119
5171
|
<div class="popup-header">
|
|
5120
5172
|
<p class="popup-title" aria-hidden="true" data-text="${e.title}"></p>
|
|
5121
|
-
<button class="icon-button popup-close" type="button" data-label="close">${
|
|
5173
|
+
<button class="icon-button popup-close" type="button" data-label="close">${WF.close}</button>
|
|
5122
5174
|
</div>
|
|
5123
|
-
<div role="menu" data-label="${e.title}">${
|
|
5175
|
+
<div role="menu" data-label="${e.title}">${uI(e)}</div>
|
|
5124
5176
|
</div>
|
|
5125
|
-
</div>`}function
|
|
5126
|
-
<button class="big-play" part="big-play" type="button">${
|
|
5177
|
+
</div>`}function fI(){return dI({name:cI.Stabilization,title:`stabilization`,choices:qs,icons:GF,words:YF})+dI({name:cI.ViewMode,title:`viewMode`,choices:Tc,icons:KF,words:XF})}var pI=LF;function mI(){return`
|
|
5178
|
+
<button class="big-play" part="big-play" type="button">${WF.play}</button>
|
|
5127
5179
|
<div class="controls" part="controls">
|
|
5128
5180
|
<input class="seek" type="range" min="0" max="0" step="0.01" value="0" data-label="seek" />
|
|
5129
5181
|
<div class="row">
|
|
@@ -5132,11 +5184,12 @@ canvas[data-draggable]:active {
|
|
|
5132
5184
|
<input class="volume" type="range" min="0" max="1" step="0.01" value="1" data-label="volume" />
|
|
5133
5185
|
<span class="time"><span class="elapsed">0:00</span> <span class="total">/ 0:00</span></span>
|
|
5134
5186
|
<span class="spacer"></span>
|
|
5135
|
-
${
|
|
5136
|
-
<button class="icon-button
|
|
5137
|
-
<button class="icon-button
|
|
5187
|
+
${fI()}
|
|
5188
|
+
<button class="icon-button motion-look" type="button" aria-pressed="false" data-label="motionLook" hidden>${WF.motionLook}</button>
|
|
5189
|
+
<button class="icon-button reset-view" type="button" data-label="resetView">${WF.resetView}</button>
|
|
5190
|
+
<button class="icon-button fullscreen" type="button" data-label="fullscreen">${WF.fullscreen}</button>
|
|
5138
5191
|
</div>
|
|
5139
|
-
</div>`}function
|
|
5192
|
+
</div>`}function hI(e,t,n){let r=e.querySelector(t);return N(r instanceof n,`the element template lacks ${t}`),r}function gI(e,t){let n=lI(t);return{button:hI(e,`.${n.button}`,HTMLButtonElement),icon:hI(e,`.${n.button} .setting-icon`,HTMLElement),popup:hI(e,`.${n.popup}`,HTMLElement),close:hI(e,`.${n.popup} .popup-close`,HTMLButtonElement)}}function _I(e){return{seek:hI(e,`.seek`,HTMLInputElement),play:hI(e,`.play`,HTMLButtonElement),bigPlay:hI(e,`.big-play`,HTMLButtonElement),elapsed:hI(e,`.time .elapsed`,HTMLElement),total:hI(e,`.time .total`,HTMLElement),mute:hI(e,`.mute`,HTMLButtonElement),volume:hI(e,`.volume`,HTMLInputElement),resetView:hI(e,`.reset-view`,HTMLButtonElement),motionLook:hI(e,`.motion-look`,HTMLButtonElement),stabilization:gI(e,cI.Stabilization),viewMode:gI(e,cI.ViewMode),fullscreen:hI(e,`.fullscreen`,HTMLButtonElement)}}var vI=Nu({statuschange:!0,ready:!0,play:!0,playing:!0,waiting:!0,pause:!0,ended:!0,timeupdate:!0,seeking:!0,seeked:!0,frame:!0,viewchange:!0,viewmodechange:!0,motionlookchange:!0,stabilizationchange:!0,qualitychange:!0,volumechange:!0,warning:!0,error:!0});function yI(e,t){let{element:n,shadow:r,idle:i,wording:a}=t,o=hI(r,`.error-message`,HTMLElement),s=hI(r,`.error-code`,HTMLElement);e.events.on(`statuschange`,e=>{n.dataset.status=e,i.refresh()}),e.events.on(`frame`,()=>{n.dataset.hasFrame=``}),e.events.on(`error`,e=>{a.showError(o,e.code),s.textContent=e.code});for(let t of vI)e.events.on(t,e=>{n.dispatchEvent(new CustomEvent(t,{detail:e,composed:!0}))})}var bI=`:host {
|
|
5140
5193
|
--gyro-view-accent: #fff;
|
|
5141
5194
|
--gyro-view-controls-background: rgb(0 0 0 / 60%);
|
|
5142
5195
|
--gyro-view-menu-background: rgb(24 24 23 / 92%);
|
|
@@ -5271,7 +5324,7 @@ canvas {
|
|
|
5271
5324
|
font-size: 0.8rem;
|
|
5272
5325
|
opacity: 0.7;
|
|
5273
5326
|
}
|
|
5274
|
-
`;function
|
|
5327
|
+
`;function xI(){return`
|
|
5275
5328
|
<div class="stage" part="stage">
|
|
5276
5329
|
<canvas part="canvas"></canvas>
|
|
5277
5330
|
<img class="poster" part="poster" alt="" />
|
|
@@ -5283,6 +5336,6 @@ canvas {
|
|
|
5283
5336
|
<p class="error-message" part="error-message"></p>
|
|
5284
5337
|
<p class="error-code" part="error-code"></p>
|
|
5285
5338
|
</div>
|
|
5286
|
-
${
|
|
5339
|
+
${mI()}
|
|
5287
5340
|
</div>
|
|
5288
|
-
`}var zP=$e(()=>nP(RP())),BP=$e(()=>[LP,AP].map(e=>HP(e)));function VP(e){e.adoptedStyleSheets=BP(),e.append(zP().cloneNode(!0))}function HP(e){let t=new CSSStyleSheet;return t.replaceSync(e),t}var UP=typeof HTMLElement==`function`?HTMLElement:Object,WP=class extends UP{addEventListener(e,t,n){super.addEventListener(e,t,n)}removeEventListener(e,t,n){super.removeEventListener(e,t,n)}},GP=/* @__PURE__ */ new Map([[`ArrowDown`,(e,t)=>(e+1)%t],[`ArrowUp`,(e,t)=>(e-1+t)%t],[`Home`,()=>0],[`End`,(e,t)=>t-1]]),KP={capture:!0},qP=class{parts;host;items;constructor(e,t,n){this.parts=t,this.host=n,this.items=[...t.popup.querySelectorAll(`:scope [role="menuitemradio"]`)];for(let e of this.items)e.addEventListener(`click`,()=>{this.closeToButton();let{choice:t}=e.dataset;t!==void 0&&n.choose(t)});t.close.addEventListener(`click`,()=>{this.closeToButton()}),this.bindButton(),this.bindDismissal(e),this.bindKeys(e)}get isOpen(){return!this.parts.popup.hidden}markChosen(e){for(let t of this.items)t.setAttribute(`aria-checked`,String(t.dataset.choice===e));let t=this.items.find(t=>t.dataset.choice===e)?.querySelector(`:scope .choice-icon > svg`);this.parts.icon.replaceChildren(...t?[t.cloneNode(!0)]:[]),this.parts.button.dataset.choice=e,this.host.wording.write(this.parts.button)}setAvailable(e){this.parts.button.hidden=!e,e||this.setOpen(!1)}bindButton(){this.parts.button.addEventListener(`click`,()=>{this.setOpen(!this.isOpen),this.isOpen&&this.focusItem(this.items.findIndex(e=>JP(e)))})}bindDismissal(e){let{button:t,popup:n}=this.parts;e.addEventListener(`pointerdown`,e=>{this.isOpen&&(e.composedPath().some(e=>e===n||e===t)||(this.setOpen(!1),e.stopPropagation()))},KP),e.addEventListener(`focusout`,e=>{let r=e instanceof FocusEvent?e.relatedTarget:null;r!==t&&r instanceof Node&&!n.contains(r)&&this.setOpen(!1)})}bindKeys(e){e.addEventListener(`keydown`,e=>{this.isOpen&&e instanceof KeyboardEvent&&this.onKey(e)})}onKey(e){let t=e.composedPath();if(e.key===`Escape`){this.closeToButton(),e.stopPropagation();return}t.includes(this.parts.popup)&&(e.stopPropagation(),e.key===`Tab`?this.setOpen(!1):this.moveFocus(e,t))}moveFocus(e,t){let n=GP.get(e.key);if(!n)return;e.preventDefault();let r=this.items.findIndex(e=>t.includes(e));this.focusItem(n(r,this.items.length))}focusItem(e){(this.items[e]??this.items[0])?.focus()}closeToButton(){this.setOpen(!1),this.parts.button.focus()}setOpen(e){this.parts.popup.hidden=!e,this.parts.button.setAttribute(`aria-expanded`,String(e))}};function JP(e){return e.getAttribute(`aria-checked`)===`true`}var YP=class{viewMode;stabilization;player;constructor(e,t,n){let{player:r,wording:i}=n;this.player=r,this.viewMode=new qP(e,t.viewMode,{wording:i,choose:e=>{let t=xd(e);t&&r.setViewMode(t)}}),this.stabilization=new qP(e,t.stabilization,{wording:i,choose:e=>{let t=bd(e);t&&r.setStabilization(t)}}),this.followPlayer()}followPlayer(){let{player:e}=this;e.events.on(`viewmodechange`,e=>{this.viewMode.markChosen(e),this.offerStabilization()}),e.events.on(`stabilizationchange`,e=>{this.stabilization.markChosen(e)}),e.events.on(`statuschange`,()=>{this.offerStabilization()}),this.viewMode.markChosen(e.viewMode),this.stabilization.markChosen(e.stabilization),this.offerStabilization()}offerStabilization(){let e=this.player.metadata?.hasGyro===!0,t=kc(this.player.viewMode).isStabilized;this.stabilization.setAvailable(e&&t)}},XP=60,ZP=60;function QP(e){let t=Number.isFinite(e)?Math.max(0,Math.floor(e)):0,n=t%XP,r=Math.floor(t/XP)%ZP,i=Math.floor(t/3600);return i>0?`${i}:${$P(r)}:${$P(n)}`:`${r}:${$P(n)}`}function $P(e){return String(e).padStart(2,`0`)}function eF(e){let t=Number(e.min),n=Number(e.max)-t,r=n>0?(Number(e.value)-t)/n:0;e.style.setProperty(`--fill`,String(yr(r,0,1)))}var tF=/* @__PURE__ */ new Map([[`ArrowLeft`,-1],[`ArrowDown`,-1],[`ArrowRight`,1],[`ArrowUp`,1]]),nF=[`pointerup`,`pointercancel`,`change`],rF=class{parts;host;isScrubbing=!1;scrubTarget;scrubbing;constructor(e,t){this.parts=e,this.host=t,this.bindInput();let{events:n}=this.host.player;n.on(`statuschange`,()=>{this.showRecording()}),n.on(`timeupdate`,e=>{this.follow(e)}),this.showRecording()}bindInput(){let{seek:e}=this.parts;e.addEventListener(`input`,()=>{this.isScrubbing=!0;let t=Number(e.value);this.showTime(t),this.scrubTo(t)});for(let t of nF)e.addEventListener(t,()=>{this.endScrub()});e.addEventListener(`keydown`,e=>{let t=tF.get(e.key);if(t===void 0)return;e.preventDefault();let{player:n}=this.host;n.seek(n.currentTime+t*5)})}showRecording(){let{duration:e,currentTime:t}=this.host.player;this.parts.seek.max=String(e),this.follow(t)}follow(e){this.isScrubbing||(this.parts.seek.value=String(e),this.showTime(e))}scrubTo(e){this.scrubTarget=e,this.scrubbing??=this.drainScrubs()}async drainScrubs(){try{for(;this.scrubTarget!==void 0;){let e=this.scrubTarget;this.scrubTarget=void 0,await this.host.player.scrub(e)}}catch(e){this.host.warn({code:`playback-failed`,message:`the seek bar could not show that moment: ${ie(e)}`})}finally{this.scrubbing=void 0}}endScrub(){this.isScrubbing&&(this.isScrubbing=!1,this.scrubTarget=void 0,this.host.player.seek(Number(this.parts.seek.value)))}showTime(e){let[t,n]=[QP(e),QP(this.host.player.duration)];this.parts.elapsed.textContent=t,this.parts.total.textContent=`/ ${n}`;let{position:r}=this.host.wording.current.labels,i=r.replaceAll(`{time}`,()=>t).replaceAll(`{duration}`,()=>n);this.parts.seek.setAttribute(`aria-valuetext`,i),eF(this.parts.seek)}},iF=100,aF=class{parts;player;constructor(e,t){this.parts=e,this.player=t,e.volume.hidden=!t.canSetVolume,e.mute.addEventListener(`click`,()=>{t.setMuted(!t.isMuted)}),e.volume.addEventListener(`input`,()=>{t.setVolume(Number(e.volume.value)),t.isMuted&&t.setMuted(!1)}),t.events.on(`volumechange`,()=>{this.reflect()}),this.reflect()}reflect(){let{isMuted:e,volume:t}=this.player,n=e?0:t;this.parts.mute.replaceChildren(dP(e?`muted`:`sound`)),this.parts.mute.setAttribute(`aria-pressed`,String(e)),this.parts.volume.value=String(n),this.parts.volume.setAttribute(`aria-valuetext`,`${Math.round(n*iF)}%`),eF(this.parts.volume)}},oF=class{parts;host;constructor(e,t){this.parts=e,this.host=t;let{player:n}=t;for(let n of[e.play,e.bigPlay])n.addEventListener(`click`,()=>{t.togglePlay()});n.events.on(`statuschange`,()=>{this.reflect(n.isPaused)}),this.reflect(n.isPaused)}reflect(e){for(let t of[this.parts.play,this.parts.bigPlay])this.host.wording.label(t,e?`play`:`pause`);this.parts.play.replaceChildren(dP(e?`play`:`pause`))}};function sF(e,t){e.resetView.addEventListener(`click`,()=>{t.player.resetView()}),e.fullscreen.addEventListener(`click`,()=>{t.toggleFullscreen()})}function cF(e,t){let n=PP(e);new oF(n,t),sF(n,t),new rF(n,t),new aF(n,t.player),new YP(e,n,{player:t.player,wording:t.wording})}var lF=`data-label`,uF=`data-text`,dF=`data-choice-text`,fF=`data-error`,pF={label:`[data-label]`,text:`[data-text]`,choiceText:`[data-choice-text]`,choice:`[data-choice]`,error:`[data-error]`},mF=class{words=yP;get current(){return this.words}replace(e){this.words=bP(e)}label(e,t){e.setAttribute(lF,t),e.setAttribute(`aria-label`,this.words.labels[t])}showError(e,t){e.setAttribute(fF,t),e.textContent=this.words.errors[t]}write(e){for(let t of e.querySelectorAll(pF.label))this.writeLabel(t);for(let t of e.querySelectorAll(pF.text))this.writeText(t);for(let t of e.querySelectorAll(pF.choiceText))this.writeChoiceText(t);for(let t of e.querySelectorAll(pF.error))this.writeError(t)}writeLabel(e){let t=e.getAttribute(lF);xP(t)&&e.setAttribute(`aria-label`,this.words.labels[t])}writeText(e){let t=e.getAttribute(uF);xP(t)&&(e.textContent=this.words.labels[t])}writeChoiceText(e){let t=e.getAttribute(dF),n=e.closest(pF.choice)?.dataset.choice;n!==void 0&&SP(t)&&(e.textContent=this.words[t][n]??``)}writeError(e){let t=e.getAttribute(fF);te(t)&&(e.textContent=this.words.errors[t])}},hF=[...Object.values(iN),sN.Poster],gF=[yN,bN],_F=[xN],vF=[sN.Autoplay,sN.Controls],yF=Object.values(iN),bF=Object.values(aN),xF=[...[...hF,...gF.map(({name:e})=>e),...vF].map(e=>Ad(e)),..._F.map(({property:e})=>e),...UN,`currentTime`,`messages`],SF=Object.values(oN),CF=class extends WP{static observedAttributes=cN;earlyProperties;player;loads;wording=new mF;fullscreen=new kN(this);idle;posterImage;constructor(){super(),this.earlyProperties=VN(this,xF),Cd(this,hF),Td(this,gF),Ed(this,_F),wd(this,vF);let e=this.attachShadow({mode:`open`});VP(e),this.wording.write(e);let t=MP(e,`canvas`,HTMLCanvasElement),n=MP(e,`audio`,HTMLAudioElement);this.posterImage=MP(e,`.poster`,HTMLImageElement),this.player=tN({canvas:t,audio:n}),this.loads=new EN(this,this.player),WN(this,this.player);let r=this.controlsHost();cF(e,r),new Jd(t,this.player,this.onPictureTap),Bd(this,r),this.idle=new PN(this,()=>this.player.status===`playing`);let{idle:i,wording:a}=this;IP(this.player,{element:this,shadow:e,idle:i,wording:a})}get status(){return this.player.status}get metadata(){return this.player.metadata}get currentTime(){return this.player.currentTime}set currentTime(e){this.seek(e)}get duration(){return this.player.duration}get paused(){return this.player.isPaused}get view(){return this.player.view}get messages(){return this.wording.current}set messages(e){let t=this.wording.current.labels.player;this.wording.replace(e),this.shadowRoot&&this.wording.write(this.shadowRoot),BN(this,t,this.wording.current.labels.player)}connectedCallback(){zN(this,this.wording.current.labels.player),HN(this,this.earlyProperties,this.warn),this.dataset.status=this.player.status,this.idle.start(),this.loads.connected()}disconnectedCallback(){this.idle.stop(),this.loads.disconnected()}attributeChangedCallback(e,t,n){if(yF.includes(e))this.loads.sourceChanged();else if(bF.includes(e))this.loads.requestChanged();else if(SF.includes(e)){this.player.setView(mN(this.player.view,e,n));let t=vN(e,n);t!==void 0&&this.warn(t)}else RN({player:this.player,posterImage:this.posterImage,warn:this.warn},e,n)}async play(){await this.loads.settled(),await this.player.play()}pause(){this.player.pause()}stop(){this.player.stop()}seek(e){jd(e,`time`),this.loads.seek(e)}scrub(e){return this.player.scrub(e)}lookAt(e,t){this.player.lookAt(e,t)}resetView(){this.player.resetView()}zoom(e,t){this.player.zoom(e,t)}setStabilization(e){this.player.setStabilization(qN(e))}setViewMode(e){this.player.setViewMode(JN(e))}setQuality(e){this.player.setQuality(YN(e))}toggleFullscreen(){return this.fullscreen.toggle()}load(){return this.loads.load()}loadFiles(e){this.loads.loadFiles(e)}controlsHost(){return{player:this.player,wording:this.wording,togglePlay:this.togglePlayback,toggleFullscreen:()=>{this.toggleFullscreen()},warn:this.warn,isFullscreen:()=>this.fullscreen.isActive,exitFullscreen:()=>{this.fullscreen.exit()}}}onPictureTap=e=>{let t=this.controls&&this.idle.wasIdleAtLastPress;e!==`mouse`&&t||this.togglePlayback()};togglePlayback=()=>{Qd(this.player)};warn=e=>{this.dispatchEvent(new CustomEvent(`warning`,{detail:e,composed:!0}))}},wF=`gyro-view`;function TF(){if(typeof customElements>`u`)return;let e=customElements.get(wF);e===void 0?customElements.define(wF,CF):e!==CF&&EF()}var EF=$e(()=>{console.warn(`<${wF}> was defined by another copy of gyroview; that copy's element is used`)});TF();export{A as GYRO_VIEW_ERROR_CATEGORIES,k as GYRO_VIEW_ERROR_CODES,wF as GYRO_VIEW_TAG,CF as GyroViewElement,j as GyroViewError,ws as PICTURE_QUALITIES,eN as Player,Xo as STABILIZATION_MODES,Os as VIEW_MODES,Zd as attachKeyboard,Xd as attachViewGestures,tN as createBrowserPlayer,TF as defineGyroView,M as hasErrorCode,nN as inspectRecording,te as isGyroViewErrorCode};
|
|
5341
|
+
`}var SI=$e(()=>zF(xI())),CI=$e(()=>[bI,pI].map(e=>TI(e)));function wI(e){e.adoptedStyleSheets=CI(),e.append(SI().cloneNode(!0))}function TI(e){let t=new CSSStyleSheet;return t.replaceSync(e),t}var EI=typeof HTMLElement==`function`?HTMLElement:Object,DI=class extends EI{addEventListener(e,t,n){super.addEventListener(e,t,n)}removeEventListener(e,t,n){super.removeEventListener(e,t,n)}},OI=class{parts;player;constructor(e,t){this.parts=e,this.player=t,e.motionLook.addEventListener(`click`,()=>{t.motionLook===`on`?t.stopMotionLook():t.startMotionLook()}),t.events.on(`motionlookchange`,()=>{this.reflect()}),t.events.on(`viewmodechange`,()=>{this.reflect()}),this.reflect()}reflect(){let{motionLook:e,viewMode:t}=this.player,n=this.parts.motionLook;n.hidden=e===`unavailable`||Rl(t)===void 0,n.setAttribute(`aria-pressed`,String(e===`on`))}},kI=/* @__PURE__ */ new Map([[`ArrowDown`,(e,t)=>(e+1)%t],[`ArrowUp`,(e,t)=>(e-1+t)%t],[`Home`,()=>0],[`End`,(e,t)=>t-1]]),AI={capture:!0},jI=class{parts;host;items;constructor(e,t,n){this.parts=t,this.host=n,this.items=[...t.popup.querySelectorAll(`:scope [role="menuitemradio"]`)];for(let e of this.items)e.addEventListener(`click`,()=>{this.closeToButton();let{choice:t}=e.dataset;t!==void 0&&n.choose(t)});t.close.addEventListener(`click`,()=>{this.closeToButton()}),this.bindButton(),this.bindDismissal(e),this.bindKeys(e)}get isOpen(){return!this.parts.popup.hidden}markChosen(e){for(let t of this.items)t.setAttribute(`aria-checked`,String(t.dataset.choice===e));let t=this.items.find(t=>t.dataset.choice===e)?.querySelector(`:scope .choice-icon > svg`);this.parts.icon.replaceChildren(...t?[t.cloneNode(!0)]:[]),this.parts.button.dataset.choice=e,this.host.wording.write(this.parts.button)}setAvailable(e){this.parts.button.hidden=!e,e||this.setOpen(!1)}bindButton(){this.parts.button.addEventListener(`click`,()=>{this.setOpen(!this.isOpen),this.isOpen&&this.focusItem(this.items.findIndex(e=>MI(e)))})}bindDismissal(e){let{button:t,popup:n}=this.parts;e.addEventListener(`pointerdown`,e=>{this.isOpen&&(e.composedPath().some(e=>e===n||e===t)||(this.setOpen(!1),e.stopPropagation()))},AI),e.addEventListener(`focusout`,e=>{let r=e instanceof FocusEvent?e.relatedTarget:null;r!==t&&r instanceof Node&&!n.contains(r)&&this.setOpen(!1)})}bindKeys(e){e.addEventListener(`keydown`,e=>{this.isOpen&&e instanceof KeyboardEvent&&this.onKey(e)})}onKey(e){let t=e.composedPath();if(e.key===`Escape`){this.closeToButton(),e.stopPropagation();return}t.includes(this.parts.popup)&&(e.stopPropagation(),e.key===`Tab`?this.setOpen(!1):this.moveFocus(e,t))}moveFocus(e,t){let n=kI.get(e.key);if(!n)return;e.preventDefault();let r=this.items.findIndex(e=>t.includes(e));this.focusItem(n(r,this.items.length))}focusItem(e){(this.items[e]??this.items[0])?.focus()}closeToButton(){this.setOpen(!1),this.parts.button.focus()}setOpen(e){this.parts.popup.hidden=!e,this.parts.button.setAttribute(`aria-expanded`,String(e))}};function MI(e){return e.getAttribute(`aria-checked`)===`true`}var NI=class{viewMode;stabilization;player;constructor(e,t,n){let{player:r,wording:i}=n;this.player=r,this.viewMode=new jI(e,t.viewMode,{wording:i,choose:e=>{let t=Rf(e);t&&r.setViewMode(t)}}),this.stabilization=new jI(e,t.stabilization,{wording:i,choose:e=>{let t=Lf(e);t&&r.setStabilization(t)}}),this.followPlayer()}followPlayer(){let{player:e}=this;e.events.on(`viewmodechange`,e=>{this.viewMode.markChosen(e),this.offerStabilization()}),e.events.on(`stabilizationchange`,e=>{this.stabilization.markChosen(e)}),e.events.on(`statuschange`,()=>{this.offerStabilization()}),this.viewMode.markChosen(e.viewMode),this.stabilization.markChosen(e.stabilization),this.offerStabilization()}offerStabilization(){let e=this.player.metadata?.hasGyro===!0,t=Il(this.player.viewMode).isStabilized;this.stabilization.setAvailable(e&&t)}},PI=60,FI=60;function II(e){let t=Number.isFinite(e)?Math.max(0,Math.floor(e)):0,n=t%PI,r=Math.floor(t/PI)%FI,i=Math.floor(t/3600);return i>0?`${i}:${LI(r)}:${LI(n)}`:`${r}:${LI(n)}`}function LI(e){return String(e).padStart(2,`0`)}function RI(e){let t=Number(e.min),n=Number(e.max)-t,r=n>0?(Number(e.value)-t)/n:0;e.style.setProperty(`--fill`,String(yr(r,0,1)))}var zI=/* @__PURE__ */ new Map([[`ArrowLeft`,-1],[`ArrowDown`,-1],[`ArrowRight`,1],[`ArrowUp`,1]]),BI=[`pointerup`,`pointercancel`,`change`],VI=class{parts;host;isScrubbing=!1;scrubTarget;scrubbing;constructor(e,t){this.parts=e,this.host=t,this.bindInput();let{events:n}=this.host.player;n.on(`statuschange`,()=>{this.showRecording()}),n.on(`timeupdate`,e=>{this.follow(e)}),this.showRecording()}bindInput(){let{seek:e}=this.parts;e.addEventListener(`input`,()=>{this.isScrubbing=!0;let t=Number(e.value);this.showTime(t),this.scrubTo(t)});for(let t of BI)e.addEventListener(t,()=>{this.endScrub()});e.addEventListener(`keydown`,e=>{let t=zI.get(e.key);if(t===void 0)return;e.preventDefault();let{player:n}=this.host;n.seek(n.currentTime+t*5)})}showRecording(){let{duration:e,currentTime:t}=this.host.player;this.parts.seek.max=String(e),this.follow(t)}follow(e){this.isScrubbing||(this.parts.seek.value=String(e),this.showTime(e))}scrubTo(e){this.scrubTarget=e,this.scrubbing??=this.drainScrubs()}async drainScrubs(){try{for(;this.scrubTarget!==void 0;){let e=this.scrubTarget;this.scrubTarget=void 0,await this.host.player.scrub(e)}}catch(e){this.host.warn({code:`playback-failed`,message:`the seek bar could not show that moment: ${ie(e)}`})}finally{this.scrubbing=void 0}}endScrub(){this.isScrubbing&&(this.isScrubbing=!1,this.scrubTarget=void 0,this.host.player.seek(Number(this.parts.seek.value)))}showTime(e){let[t,n]=[II(e),II(this.host.player.duration)];this.parts.elapsed.textContent=t,this.parts.total.textContent=`/ ${n}`;let{position:r}=this.host.wording.current.labels,i=r.replaceAll(`{time}`,()=>t).replaceAll(`{duration}`,()=>n);this.parts.seek.setAttribute(`aria-valuetext`,i),RI(this.parts.seek)}},HI=100,UI=class{parts;player;constructor(e,t){this.parts=e,this.player=t,e.volume.hidden=!t.canSetVolume,e.mute.addEventListener(`click`,()=>{t.setMuted(!t.isMuted)}),e.volume.addEventListener(`input`,()=>{t.setVolume(Number(e.volume.value)),t.isMuted&&t.setMuted(!1)}),t.events.on(`volumechange`,()=>{this.reflect()}),this.reflect()}reflect(){let{isMuted:e,volume:t}=this.player,n=e?0:t;this.parts.mute.replaceChildren(JF(e?`muted`:`sound`)),this.parts.mute.setAttribute(`aria-pressed`,String(e)),this.parts.volume.value=String(n),this.parts.volume.setAttribute(`aria-valuetext`,`${Math.round(n*HI)}%`),RI(this.parts.volume)}},WI=class{parts;host;constructor(e,t){this.parts=e,this.host=t;let{player:n}=t;for(let n of[e.play,e.bigPlay])n.addEventListener(`click`,()=>{t.togglePlay()});n.events.on(`statuschange`,()=>{this.reflect(n.isPaused)}),this.reflect(n.isPaused)}reflect(e){for(let t of[this.parts.play,this.parts.bigPlay])this.host.wording.label(t,e?`play`:`pause`);this.parts.play.replaceChildren(JF(e?`play`:`pause`))}};function GI(e,t){e.resetView.addEventListener(`click`,()=>{t.player.resetView()}),e.fullscreen.addEventListener(`click`,()=>{t.toggleFullscreen()})}function KI(e,t){let n=_I(e);new WI(n,t),GI(n,t),new VI(n,t),new UI(n,t.player),new NI(e,n,{player:t.player,wording:t.wording}),new OI(n,t.player)}var qI=`data-label`,JI=`data-text`,YI=`data-choice-text`,XI=`data-error`,ZI={label:`[data-label]`,text:`[data-text]`,choiceText:`[data-choice-text]`,choice:`[data-choice]`,error:`[data-error]`},QI=class{words=nI;get current(){return this.words}replace(e){this.words=rI(e)}label(e,t){e.setAttribute(qI,t),e.setAttribute(`aria-label`,this.words.labels[t])}showError(e,t){e.setAttribute(XI,t),e.textContent=this.words.errors[t]}write(e){for(let t of e.querySelectorAll(ZI.label))this.writeLabel(t);for(let t of e.querySelectorAll(ZI.text))this.writeText(t);for(let t of e.querySelectorAll(ZI.choiceText))this.writeChoiceText(t);for(let t of e.querySelectorAll(ZI.error))this.writeError(t)}writeLabel(e){let t=e.getAttribute(qI);iI(t)&&e.setAttribute(`aria-label`,this.words.labels[t])}writeText(e){let t=e.getAttribute(JI);iI(t)&&(e.textContent=this.words.labels[t])}writeChoiceText(e){let t=e.getAttribute(YI),n=e.closest(ZI.choice)?.dataset.choice;n!==void 0&&aI(t)&&(e.textContent=this.words[t][n]??``)}writeError(e){let t=e.getAttribute(XI);te(t)&&(e.textContent=this.words.errors[t])}},$I=[...Object.values(VP),WP.Poster],eL=[nF,rF],tL=[iF],nL=[WP.Autoplay,WP.Controls],rL=Object.values(VP),iL=Object.values(HP),aL=[...[...$I,...eL.map(({name:e})=>e),...nL].map(e=>qf(e)),...tL.map(({property:e})=>e),...EF,`currentTime`,`messages`],oL=Object.values(UP),sL=class extends DI{static observedAttributes=GP;earlyProperties;player;loads;wording=new QI;fullscreen=new fF(this);idle;posterImage;constructor(){super(),this.earlyProperties=wF(this,aL),Bf(this,$I),Hf(this,eL),Uf(this,tL),Vf(this,nL);let e=this.attachShadow({mode:`open`});wI(e),this.wording.write(e);let t=hI(e,`canvas`,HTMLCanvasElement),n=hI(e,`audio`,HTMLAudioElement);this.posterImage=hI(e,`.poster`,HTMLImageElement),this.player=RP({canvas:t,audio:n}),this.loads=new lF(this,this.player),DF(this,this.player);let r=this.controlsHost();KI(e,r),new dp(t,this.player,this.onPictureTap),rp(this,r),this.idle=new _F(this,()=>this.player.status===`playing`);let{idle:i,wording:a}=this;yI(this.player,{element:this,shadow:e,idle:i,wording:a})}get status(){return this.player.status}get metadata(){return this.player.metadata}get currentTime(){return this.player.currentTime}set currentTime(e){this.seek(e)}get duration(){return this.player.duration}get paused(){return this.player.isPaused}get view(){return this.player.view}get motionLook(){return this.player.motionLook}get messages(){return this.wording.current}set messages(e){let t=this.wording.current.labels.player;this.wording.replace(e),this.shadowRoot&&this.wording.write(this.shadowRoot),CF(this,t,this.wording.current.labels.player)}connectedCallback(){SF(this,this.wording.current.labels.player),TF(this,this.earlyProperties,this.warn),this.dataset.status=this.player.status,this.idle.start(),this.loads.connected()}disconnectedCallback(){this.idle.stop(),this.loads.disconnected()}attributeChangedCallback(e,t,n){if(rL.includes(e))this.loads.sourceChanged();else if(iL.includes(e))this.loads.requestChanged();else if(oL.includes(e)){this.player.setView(ZP(this.player.view,e,n));let t=tF(e,n);t!==void 0&&this.warn(t)}else xF({player:this.player,posterImage:this.posterImage,warn:this.warn},e,n)}async play(){await this.loads.settled(),await this.player.play()}pause(){this.player.pause()}stop(){this.player.stop()}seek(e){Jf(e,`time`),this.loads.seek(e)}scrub(e){return this.player.scrub(e)}lookAt(e,t){this.player.lookAt(e,t)}resetView(){this.player.resetView()}zoom(e,t){this.player.zoom(e,t)}startMotionLook(){return this.player.startMotionLook()}stopMotionLook(){this.player.stopMotionLook()}setStabilization(e){this.player.setStabilization(AF(e))}setViewMode(e){this.player.setViewMode(jF(e))}setQuality(e){this.player.setQuality(MF(e))}toggleFullscreen(){return this.fullscreen.toggle()}load(){return this.loads.load()}loadFiles(e){this.loads.loadFiles(e)}controlsHost(){return{player:this.player,wording:this.wording,togglePlay:this.togglePlayback,toggleFullscreen:()=>{this.toggleFullscreen()},warn:this.warn,isFullscreen:()=>this.fullscreen.isActive,exitFullscreen:()=>{this.fullscreen.exit()}}}onPictureTap=e=>{let t=this.controls&&this.idle.wasIdleAtLastPress;e!==`mouse`&&t||this.togglePlayback()};togglePlayback=()=>{hp(this.player)};warn=e=>{this.dispatchEvent(new CustomEvent(`warning`,{detail:e,composed:!0}))}},cL=`gyro-view`;function lL(){if(typeof customElements>`u`)return;let e=customElements.get(cL);e===void 0?customElements.define(cL,sL):e!==sL&&uL()}var uL=$e(()=>{console.warn(`<${cL}> was defined by another copy of gyroview; that copy's element is used`)});lL();export{A as GYRO_VIEW_ERROR_CATEGORIES,k as GYRO_VIEW_ERROR_CODES,cL as GYRO_VIEW_TAG,sL as GyroViewElement,j as GyroViewError,xc as PICTURE_QUALITIES,LP as Player,qs as STABILIZATION_MODES,Tc as VIEW_MODES,mp as attachKeyboard,pp as attachViewGestures,RP as createBrowserPlayer,lL as defineGyroView,M as hasErrorCode,zP as inspectRecording,te as isGyroViewErrorCode};
|