@bubo-squared/gyroview 0.5.0 → 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 +22 -0
- package/README.md +2 -2
- package/dist/index.d.ts +56 -15
- 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 +5 -3
- package/dist/packages/core/src/shared/math/Matrix3.js +12 -1
- 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/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 +1 -1
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)}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)}var Br=/* @__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 Vr(e){let t=Br.get(e);return N(t!==void 0,`unknown IMU axis ${e}`),t}function Hr(e){let[t,n,r]=e.map(e=>Vr(e));return[...t,...n,...r]}function Ur(e){return zr(Hr(e))===1}function Wr(e,t){return{...Kr(e,t),isVerified:!0}}function Gr(e,t){return{...Kr(e,t),isVerified:!1}}function Kr(e,t){return N(Ur(t),`IMU axes ${t.join(`, `)} are not a rotation`),{name:e,toBody:Hr(t)}}function qr(e,t){return Rr(e.toBody,t)}var Jr=[`x`,`z`,`-y`],Yr=Wr(`X5`,Jr),Xr=Wr(`X6`,Jr),Zr=Wr(`X4 Air`,Jr),Qr=Wr(`A1`,[`-z`,`-x`,`y`]),$r=Wr(`X3`,Jr),ei=Gr(`ONE RS (unverified)`,[`-y`,`x`,`z`]),ti=Gr(`aligned (unverified)`,[`x`,`y`,`z`]),ni=/* @__PURE__ */ new Map([[`Antigravity A1`,Qr],[`Insta360 X3`,$r],[`Insta360 X4 Air`,Zr],[`Insta360 X5`,Yr],[`Insta360 X6`,Xr],[`Insta360 OneRS`,ei]]);function ri(e){return ni.get(e.model?.trim()??``)??ti}function ii(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 ai=.02,oi=_t(R(1));function si(e,t,n){let r=mt(e.meanSampleInterval??oi),i=Math.max(1,Math.min(e.length,Math.round(n/r))),a=ci(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 ci(e,t){let n=new Float64Array(e.length);for(let r=0;r<e.length;r+=1)n[r]=Wt(qr(t,e.angularVelocityAt(r)));return n}function li({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,qr(t,n))}return Xt(i,1/Math.max(n.end-n.start,1))}function ui(e,t,n){let r=li({gyro:e,frame:t},n,e=>e.angularVelocity);return Wt(r)<=ai?r:Ut}var di=[0,0,0,1],fi=1e-12,pi=.9995;function mi(e,t){let n=Wt(e);if(n===0)return di;let r=t/2,i=Math.sin(r)/n;return[e[0]*i,e[1]*i,e[2]*i,Math.cos(r)]}function hi(e){let t=Wt(e);return t<fi?di:mi(e,n(t))}function gi(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 _i(e){let[t,n,r,i]=e;return[-t,-n,-r,i]}function vi(e){let[t,n,r,i]=e,a=Math.sqrt(t*t+n*n+r*r+i*i);return a===0?di:[t/a,n/a,r/a,i/a]}function yi(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 bi(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>pi)return vi([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 xi(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 Si=[0,1,0],Ci=.9,wi=1.1;function Ti(e){let t=Wt(e);return t>=Ci&&t<=wi?Xt(e,-1/t):void 0}function Ei(e,t){let n=Ti(t);return n?Kt(n,yi(_i(e),Si)):[0,0,0]}function Di(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 Oi(e,t,n){if(e.isEmpty)return di;let r=Di(e,n),i=Ti(li({gyro:e,frame:t},r,e=>e.acceleration));return i?ki(i,Si):di}function ki(e,t){let r=Kt(e,t),i=Gt(e,t),a=Wt(r);return a>0?mi(r,n(Math.atan2(a,i))):i>0?di:mi(Ai(e),n(Math.PI))}function Ai(e){return Math.abs(e[0])<Math.abs(e[2])?[0,-e[2],e[1]]:[-e[1],e[0],0]}var ji=l(o),Mi=l(t(-o)),Ni=l(s),Pi={name:`upright`,toBody:Bi(n(0))},Fi=[0,1,0],Ii=[0,0,1],Li=[Pi,{name:`upside down`,toBody:Bi(Ni)},{name:`on its right side`,toBody:Bi(Mi)},{name:`on its left side`,toBody:Bi(ji)}],Ri=[{name:`with lens 0 up`,toBody:Vi(Mi)},{name:`with lens 0 down`,toBody:Vi(ji)}],zi=Math.cos(l(t(30)));function Bi(e){return Ir(Fr(e),Pr(Ni))}function Vi(e){return Ir(Nr(e),Pr(Mi))}function Hi(e,t){if(!t.isVerified)return Pi;let n=Ki(e,t),r=Ui(n)?Ri:Li;return r[ii(r.map(e=>-Gt(Rr(e.toBody,Fi),n)))]??Pi}function Ui(e){return Math.abs(Gt(e,Ii))>zi*Wt(e)}function Wi(e,t){return{...e,toBody:Ir(Lr(t.toBody),e.toBody)}}function Gi(e,t){return Ir(e.toBody,t)}function Ki(e,t){let n=Ut;for(let r=0;r<e.length;r+=1){let i=Ti(qr(t,e.sampleAt(r).acceleration));i&&(n=Jt(n,i))}return n}var qi=.2,Ji=.5,Yi=.5,Xi=4,Zi=.05,Qi=class e{videoTimes;quaternions;constructor(e,t){this.videoTimes=e,this.quaternions=t,N(t.length===e.length*Xi,`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*Xi);if(n.isEmpty)return new e(a,o);let s={frame:i,bias:ui(n,i,si(n,i,R(Ji))),gravityGain:t.options?.gravityGain??qi};a.set($i(n,r));let c={orientation:Oi(n,i,R(Yi)),time:R(a[0]??0),rate:Ut};for(let e=0;e<n.length;e+=1){let t=R(a[e]??c.time);c=ta(c,{sample:ea(n,e),time:t},s),o.set(c.orientation,e*Xi)}return new e(a,o)}get length(){return this.videoTimes.length}orientationAt(e){if(this.length===0)return di;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 bi(this.quaternionAt(n),this.quaternionAt(t),i)}quaternionAt(e){let t=e*Xi,[n=0,r=0,i=0,a=1]=this.quaternions.subarray(t,t+Xi);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 $i(e,t){return e.captureTimes.map(e=>t.gyroVideoTimeOf(ft(e)))}function ea(e,t){let n=e.sampleAt(t);return N(qt(n.acceleration)&&qt(n.angularVelocity),`gyro sample ${t} is not finite`),n}function ta(e,{sample:t,time:n},r){let{frame:i,bias:a,gravityGain:o}=r,s=yr(n-e.time,0,Zi),c=Ei(e.orientation,qr(i,t.acceleration));return{orientation:ra(e.orientation,na(e.rate,c,o),s),time:n,rate:Yt(qr(i,t.angularVelocity),a)}}function na(e,t,n){return Jt(e,Xt(t,n))}function ra(e,t,n){return vi(gi(e,hi(Xt(t,n))))}var ia=`the recording has no gyro record; stabilization is unavailable`;async function aa(e,t){let n=await e.readGyroRecord();if(!n)return{setup:void 0,warnings:[ia]};let r=ri(e.info),i=Hi(n.track,r),a=Wi(r,i),o=Qi.integrate({gyro:n.track,clock:t,frame:a}),s=[...sa(r,e),...oa(n)];return{setup:{orientations:o,mounting:i,imuFrame:r},warnings:s}}function oa(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 sa(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 ca=`frame timing and stabilization are unavailable`,la=`the recording has no capture clock; ${ca}`,ua=`the recording has no frame source to time; ${ca}`,da=`no frame timing source is usable; frames are timed by their track timestamps`;async function fa(e,t){try{return await pa(e,t)}catch(e){if(!M(e,`unsupported-gyro-record`))throw e;return ha([`${ie(e)}; ${ca}`])}}async function pa(e,t){let n=await e.captureClock();if(!n)return ha([la]);if(!t)return ha([ua]);let r=await ma(n,t),[i,a]=await Promise.all([jr(e,t,r),aa(e,r.clock)]);return{frameTimes:i?.frameTimes,frameTimeSource:i?.source,motion:a.setup,warnings:[...i?.warnings??[da],...a.warnings]}}async function ma(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 ha(e){return{frameTimes:void 0,frameTimeSource:void 0,motion:void 0,warnings:e}}var ga=/^(?<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,_a=0,va=1,ya=0,ba=1,xa=class e{parts;constructor(e){this.parts=e}static parse(t){let n=ga.exec(t)?.groups;return n?new e(Sa(n)):void 0}get isBackLens(){return this.parts.lensDigit===_a}get isScreenLens(){return this.parts.lensDigit===va}get isProxy(){return this.parts.proxyDigit===ba}otherLensName(){let t=this.isBackLens?va:_a;return new e({...this.parts,lensDigit:t,proxyDigit:ya}).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 Sa(e){return{prefix:e.prefix??``,captureStamp:e.stamp??``,lensDigit:Number(e.lens),proxyDigit:Number(e.proxy),sequence:e.sequence??``,extension:e.extension??``}}var Ca=/[#?]/u;function wa(e){let t=e.search(Ca);return t===-1?{path:e,suffix:``}:{path:e.slice(0,t),suffix:e.slice(t)}}function Ta(e){let{path:t}=wa(e),n=t.slice(t.lastIndexOf(`/`)+1);try{return decodeURIComponent(n)}catch{return n}}async function Ea(e,t){let n=xa.parse(Ta(e));if(!n)return;let r=Da(e,n.otherLensName());return await t.exists(r)?r:void 0}function Da(e,t){let{path:n,suffix:r}=wa(e);return`${n.slice(0,n.lastIndexOf(`/`)+1)}${encodeURIComponent(t)}${r}`}var Oa={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`},ka={Video:`vide`,Sound:`soun`},Aa=[`avc1`,`avc3`],ja=[`hvc1`,`hev1`],Ma={isKeyframe:()=>!0},Na=31,Pa=1,Fa=4,Ia=5,La=1,Ra=63,za=16,Ba=23,Va={typeOf:e=>e&Na,verdictOn:e=>e===Ia?`keyframe`:e>=Pa&&e<=Fa?`not-a-keyframe`:`read-on`},Ha={typeOf:e=>e>>La&Ra,verdictOn:e=>e<za?`not-a-keyframe`:e<=Ba?`keyframe`:`read-on`},Ua=8,Wa=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+Ga(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 Ga(e,t,n){let r=0;for(let i=0;i<n;i+=1)r=r*2**Ua+(e[t+i]??0);return r}var Ka=[[Aa,Va],[ja,Ha]];function qa(e){let{sampleEntryType:t,nalLengthSize:n}=e,[,r]=Ka.find(([e])=>e.includes(t))??[];return r&&n!==void 0?new Wa(r,n):Ma}function Ja(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 Qa(`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 Ya(e,t){let n=Xa(e,t);if(!n)throw Qa(`has no ${t} box where one belongs`);return n}function Xa(e,t){return e.find(e=>e.type===t)}function Za(e){if(e.body.byteLength<4)throw Qa(`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 Qa(e){return new j(`unsupported-container`,`the movie box ${e}`)}var $a={0:{timescale:8,duration:{offset:12,kind:`uint32`},size:96},1:{timescale:16,duration:{offset:20,kind:`uint64`},size:108}},eo={0:8,1:16},to={0:{timescale:8,duration:{offset:12,kind:`uint32`},size:20},1:{timescale:16,duration:{offset:20,kind:`uint64`},size:32}},no={entrySize:8,fields:{sampleCount:{offset:0,kind:`uint32`},sampleDelta:{offset:4,kind:`uint32`}}},ro={entrySize:8,fields:{sampleCount:{offset:0,kind:`uint32`},sampleOffset:{offset:4,kind:`int32`}}},io={entrySize:4,fields:{sampleNumber:{offset:0,kind:`uint32`}}},ao={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`}}}},oo={entrySize:12,fields:{firstChunk:{offset:0,kind:`uint32`},samplesPerChunk:{offset:4,kind:`uint32`},sampleDescriptionIndex:{offset:8,kind:`uint32`}}},so={entrySize:4,fields:{chunkOffset:{offset:0,kind:`uint32`}}},co={entrySize:8,fields:{chunkOffset:{offset:0,kind:`uint64`}}},lo={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 uo(e,t,n=0){return lo[t.kind](e,n+t.offset)}function fo(e,t){let n=e.uint32BeAt(0);if(4+n*t.entrySize>e.length)throw Qa(`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)=>uo(e,t.fields[a],4+r*t.entrySize));return i}var po=1;function mo(e){let t=ho(Ya(e,Oa.SampleSize)),n=go(e),r=Za(Ya(e,Oa.SampleToChunk)).content;return{offsets:vo({sizes:t,chunkOffsets:n,perChunk:_o(fo(r,oo),n.length)}),sizes:t}}function ho(e){let{content:t}=Za(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 Qa(`lists ${r} sample sizes that do not fit in its box`);return Float64Array.from({length:r},(e,n)=>t.uint32BeAt(8+n*4))}function go(e){let t=Xa(e,Oa.ChunkLargeOffset),n=t??Xa(e,Oa.ChunkOffset);if(!n)throw Qa(`has a sample table without chunk offsets`);let r=t?co:so;return fo(Za(n).content,r).chunkOffset}function _o(e,t){let n=Array.from({length:t},()=>0);for(let[r,i]of e.firstChunk.entries()){let a=e.firstChunk[r+1]??t+po,o=e.samplesPerChunk[r]??0;n.fill(o,i-po,a-po)}return n}function vo(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 Qa(`has chunks for ${n} of its ${t.length} samples`);return t}var yo=4,bo=/* @__PURE__ */ new Map([[Oa.AvcConfiguration,4],[Oa.HevcConfiguration,21]]);function xo(e){let t=Za(Ya(e,Oa.MovieHeader));return t.content.uint32BeAt(wo(t,$a,Oa.MovieHeader).timescale)}function So(e){let t=Ja(e.body),n=Ja(Ya(t,Oa.Media).body);return{track:t,media:n,sampleTable:Ja(Ya(Ja(Ya(n,Oa.MediaInformation).body),Oa.SampleTable).body)}}function Co(e){let t=Do(e.media),n=Oo(e.sampleTable);return{trackId:To(e.track),handlerType:t,mediaTimescale:Eo(e.media),sampleEntryType:n.type,nalLengthSize:t===ka.Video?ko(n):void 0}}function wo(e,t,n){let r=e.version===0||e.version===1?t[e.version]:void 0;if(r===void 0)throw Qa(`has a ${n} box of version ${e.version}`);return r}function To(e){let t=Za(Ya(e,Oa.TrackHeader));return t.content.uint32BeAt(wo(t,eo,Oa.TrackHeader))}function Eo(e){let t=Za(Ya(e,Oa.MediaHeader));return t.content.uint32BeAt(wo(t,to,Oa.MediaHeader).timescale)}function Do(e){let{content:t}=Za(Ya(e,Oa.Handler));return t.asciiAt(4,yo)}function Oo(e){let{content:t}=Za(Ya(e,Oa.SampleDescription)),n=t.length-4,[r]=Ja(t.bytesAt(4,n));if(!r)throw Qa(`has a track without a sample entry`);return r}function ko(e){let t=Ja(e.body.subarray(78)).find(e=>bo.has(e.type)),n=t?.body[bo.get(t.type)??0];return n===void 0?void 0:(n&3)+1}function Ao(e){return Array.from({length:e.length},(e,t)=>t).toSorted((t,n)=>(e[t]??0)-(e[n]??0))}function jo(e,t){let n=Mo(Ya(e.sampleTable,Oa.TimeToSample),t),r=No(e.sampleTable,t.sampleCount),i=r?n.times.map((e,t)=>e+(r[t]??0)):n.times,a=Fo(e.track,t),o=i.map(e=>(e-a)/t.media),s=(r?Io(i,n.deltas):n.deltas).map(e=>e/t.media);return{timestamps:o,durations:s,end:Lo(o,s,t.media)}}function Mo(e,t){let n=fo(Za(e).content,no),r=Po(n.sampleCount,n.sampleDelta);if(r.length!==t.sampleCount)throw Qa(`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 No(e,t){let n=Xa(e,Oa.CompositionOffset);if(!n)return;let r=fo(Za(n).content,ro),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 Fo(e,t){let n=Xa(e,Oa.Edit),r=n&&Xa(Ja(n.body),Oa.EditList);if(!r)return 0;let i=Za(r),a=fo(i.content,wo(i,ao,Oa.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 Io(e,t){let n=Ao(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 Lo(e,t,n){let r=Ao(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 Ro=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 zo(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 Bo=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(Vo(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=Ao(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=zo(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[zo(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[zo(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 Vo(e,t){return e.every((n,r)=>Number.isSafeInteger(n)&&n>=0&&n<t&&n>(e[r-1]??-1))}var Ho={[ka.Video]:`video`,[ka.Sound]:`audio`},Uo=1;function Wo(e){let[t]=Ja(e);if(t?.type!==Oa.Movie)throw Qa(`is not where the file says it is`);let n=Ja(t.body);if(Xa(n,Oa.MovieExtends))throw Qa(`is fragmented: its samples are described in movie fragments after it`);let r=xo(n);return new Ro(n.filter(e=>e.type===Oa.Track).flatMap(e=>Go(So(e),r)))}function Go(e,t){let n=Co(e),r=Ho[n.handlerType];if(!r)return[];let i=mo(e.sampleTable),a=jo(e,{media:n.mediaTimescale,movie:t,sampleCount:i.sizes.length});return[new Bo({trackId:n.trackId,kind:r,...i,...a,syncSamples:Ko(e.sampleTable),keyframeRule:qa(n)})]}function Ko(e){let t=Xa(e,Oa.SyncSample);if(!t)return;let{sampleNumber:n}=fo(Za(t).content,io);return n.map(e=>e-Uo)}function qo(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 Jo(e){let t=await sr(e,await e.size()),n=t.find(e=>e.type===Oa.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===Oa.FileType),[i,a]=await Promise.all([Yo(e,r),Yo(e,n)]);return{table:Wo(a),movieBytes:qo([i,a])}}function Yo(e,t){return t?e.read(t.range):Promise.resolve(/* @__PURE__ */ new Uint8Array)}var Xo={x:0,y:0,width:1,height:1},Zo={x:0,y:0,width:.5,height:1},Qo={x:.5,y:0,width:.5,height:1},$o=2,es=2,ts=.02,ns=0,rs=1,is=2;function as(e,t){let n=e.flatMap((e,t)=>e.videoTracks.map(({description:n})=>({input:e,inputIndex:t,track:n})));if(e.length===1&&us(n))return os(n,t);if(e.length===$o&&ds(e,n))return ss(e,n);let[r]=n;if(r&&n.length===1&&ps(r.track))return cs(r);throw hs(e,n)}function os(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)=>ls(e,t)),evidence:[`one input with two video tracks`,...i,a]}}function ss(e,t){let n=t.toSorted((e,t)=>ms(e.input)-ms(t.input)),r=e.map(e=>e.name??`?`).join(`, `);return{kind:`split-files`,sources:n.map((e,t)=>ls(e,t)),evidence:[`two inputs with one video track each (${r})`,`lens 0 taken from the _00_ file when named`]}}function cs(e){let{inputIndex:t,track:n}=e;return{kind:`packed`,sources:[{lensIndex:0,inputIndex:t,trackIndex:n.trackIndex,region:Zo},{lensIndex:1,inputIndex:t,trackIndex:n.trackIndex,region:Qo}],evidence:[`single ${n.codedWidth}x${n.codedHeight} track with a 2:1 aspect ratio`]}}function ls(e,t){return{lensIndex:t,inputIndex:e.inputIndex,trackIndex:e.track.trackIndex,region:Xo}}function us(e){let[t,n]=e;return e.length===$o&&t!==void 0&&n!==void 0&&fs(t.track)&&t.track.codedWidth===n.track.codedWidth&&t.track.codedHeight===n.track.codedHeight}function ds(e,t){return t.length===$o&&e.every(e=>e.videoTracks.length===1)&&t.every(e=>fs(e.track))}function fs(e){return e.codedWidth===e.codedHeight}function ps(e){return Math.abs(e.codedWidth/e.codedHeight-es)<=ts}function ms(e){let t=xa.parse(e.name??``);return t?.isBackLens?ns:t?.isScreenLens?is:rs}function hs(e,t){let[n]=t;if(e.length===1&&t.length===1&&n!==void 0&&fs(n.track))return gs(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 gs(e){let t=xa.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 _s=6,vs=32,ys=31,bs=1,xs=5,Ss=6,Cs=11,ws=32,Ts=0,Es=33,Ds=3,Os=3,ks=2,As=[``,`A`,`B`,`C`],js=`L`,Ms=`H`,Ns=16;function Ps(e,t){return Hs(e,Fs(t))}function Fs(e){let t=Ls(new Qe(e),1);return t.profile===Ts?Is(e)??t:t}function Is(e){try{let t=zs(e);return t===void 0?void 0:Rs(t)}catch(e){if(M(e,`binary-out-of-bounds`))return;throw e}}function Ls(e,t){let n=e.uint8At(t);return{profileSpace:n>>_s,isHighTier:(n&vs)!==0,profile:n&ys,compatibilityFlags:e.uint32BeAt(t+bs),constraintFlags:[...e.bytesAt(t+xs,Ss)],level:e.uint8At(t+Cs)}}function Rs(e){return Ls(new Qe(Vs(e)),Ds)}function zs(e){let t=new Qe(e),n=23;for(let e=0;e<t.uint8At(22);e+=1){let e=Bs(t,n),[r]=e.nalUnitType===Es?e.nalUnits:[];if(r!==void 0)return r;n=e.end}}function Bs(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 Vs(e){let t=[],n=0;for(let r of e)n>=ks&&r===Os||t.push(r),n=r===0?n+1:0;return Uint8Array.from(t)}function Hs(e,t){let n=`${As[t.profileSpace]??``}${t.profile}`,r=t.isHighTier?Ms:js,i=Ws(t.constraintFlags).map(e=>Gs(e));return[e,n,Gs(Us(t.compatibilityFlags)),`${r}${t.level}`,...i].join(`.`)}function Us(e){let t=0;for(let n=0;n<ws;n+=1)t=t<<1|e>>>n&1;return t>>>0}function Ws(e){let t=e.findLastIndex(e=>e!==0);return e.slice(0,t+1)}function Gs(e){return e.toString(Ns).toUpperCase()}var Ks=[`off`,`lock`,`horizon`,`follow`],qs=`lock`,Js=class{nextRotation(){return Mr}},Ys=class{nextRotation(e){return xi(_i(e))}},Xs=class{nextRotation(e){let t=mi(Si,tc(e));return Ir(xi(_i(e)),xi(t))}},Zs={timeConstant:R(1.5),maxContinuousGap:R(1)},Qs=class{options;smoothed;previousTime;constructor(e=Zs){this.options=e}nextRotation(e,t){return this.smoothed=this.follow(e,t),this.previousTime=t,Ir(xi(_i(e)),xi(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 bi(this.smoothed,e,r)}},$s={off:()=>new Js,lock:()=>new Ys,horizon:()=>new Xs,follow:()=>new Qs};function ec(e){return $s[e]()}function tc(e){let[,t,,r]=e;return n(2*Math.atan2(t,r))}function nc(e){return t(2*(Math.round(e/o)*o)-e)}function rc(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(nc(i))),c)}var ic=1.5,ac=.01,oc=[1,1,1],sc={maxGain:2,timeConstant:R(ic)};function cc(e,t){let[n]=e;return n?e.map((e,r)=>r===0?oc:lc(n,e,t)):[]}function lc(e,t,n){return[uc(e[0],t[0],n),uc(e[1],t[1],n),uc(e[2],t[2],n)]}function uc(e,t,n){return e<ac||t<ac?1:yr(e/t,1/n,n)}var dc=class{options;current;lastTime;constructor(e=sc){this.options=e}update(e,t){let n=cc(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]??oc,e,i)),this.current}},fc=30,pc=120,mc=90,hc=90,gc={yaw:t(0),pitch:t(0),fieldOfView:t(mc)};function _c(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,hc)),fieldOfView:t(yr(e.fieldOfView,fc,pc))}}function vc(e,t){return e.yaw===t.yaw&&e.pitch===t.pitch&&e.fieldOfView===t.fieldOfView}function yc(e){return Ir(Pr(l(e.yaw)),Nr(l(e.pitch)))}var bc=[`fast`,`balanced`,`high`],xc=`balanced`,Sc={fast:1,balanced:2,high:3};function Cc(e){return Sc[e]}var wc=[`raw-lenses`,`equirectangular`,`normal`],Tc=`raw-lenses`,Ec=.5,Dc={x:0,y:0,width:1,height:1},Oc={x:Ec,y:Ec};function kc(e){return Math.max(e,1)}function Ac(e){return e.width/kc(e.height)}function jc(e,t){return{across:e.x/kc(t.width),down:e.y/kc(t.height)}}function Mc(e,t){return{x:(t.x-e.x)/e.width,y:(t.y-e.y)/e.height}}function Nc(e,t){let n=Lc(e,t),r=Lc(1/e,t);return n.height>=r.height/e?Pc(n,e):Fc(r,e)}function Pc(e,t){let n=e.width/t;return Array.from({length:t},(t,r)=>({...e,x:e.x+r*n,width:n}))}function Fc(e,t){let n=e.height/t;return Array.from({length:t},(t,r)=>({...e,y:e.y+r*n,height:n}))}function Ic(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 Lc(e,t){if(e>=t){let n=t/e;return{x:0,y:(1-n)*Ec,width:1,height:n}}let n=e/t;return{x:(1-n)*Ec,y:0,width:n,height:1}}function Rc(e){return Math.tan(l(t(e/2)))}function zc(e,t){return t*e.width/e.height}function Bc(e,t,n){let r=Rc(e),i=[(t.x*2-1)*r,(t.y*2-1)*r/n,1];return Xt(i,1/Wt(i))}function Vc(e,t,n){return Rr(yc(e),Bc(e.fieldOfView,t,n))}var Hc=1.1;function Uc(e){return Hc**e}function Wc(e,n){return t(e.fieldOfView/Math.max(n,1))}function Gc(e,n,r){let i=Wc(e,r);return _c({...e,yaw:t(e.yaw-n.x*i),pitch:t(e.pitch+n.y*i)})}function Kc(e,n){return _c({...e,fieldOfView:t(e.fieldOfView/Uc(n))})}function qc(e,t,r){let i=Kc(e,t.steps);if(t.focus.x===Oc.x&&t.focus.y===Oc.y||i.fieldOfView===e.fieldOfView)return i;let a=Vc(e,t.focus,r),o=Bc(i.fieldOfView,t.focus,r),s=Jc(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 _c({...i,yaw:d,pitch:s})}function Jc(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 Yc(e,t){return e<=0||t<=0?0:Math.log(t/e)/Math.log(Hc)}function Xc(e,t,n){return _c({...e,yaw:t,pitch:n})}var Zc={scale:1,centre:{x:Ec,y:Ec}},Qc=1e-9;function $c(e,t){return e.scale===t.scale&&e.centre.x===t.centre.x&&e.centre.y===t.centre.y}function el(e,t){let n=e.width*t.scale,r=e.height*t.scale;return{x:Oc.x-t.centre.x*n,y:Oc.y-t.centre.y*r,width:n,height:r}}function tl(e,t){let n=yr(t.scale,1,8),r=n-1<Qc?1:n;return{scale:r,centre:{x:al(t.centre.x,e.width*r),y:al(t.centre.y,e.height*r)}}}function nl(e,t,n){let r=tl(e,t),i=Mc(el(e,r),n.focus),a=r.scale*Uc(n.steps);return tl(e,{scale:a,centre:{x:i.x+(Oc.x-n.focus.x)/(e.width*a),y:i.y+(Oc.y-n.focus.y)/(e.height*a)}})}function rl(e,t,n){let r=tl(e,t),i=il(e,r,n);return tl(e,{scale:r.scale,centre:{x:r.centre.x-i.across,y:r.centre.y-i.down}})}function il(e,t,n){return{across:n.across/(e.width*t.scale),down:n.down/(e.height*t.scale)}}function al(e,t){if(t<=1)return Ec;let n=Ec/t;return yr(e,n,1-n)}var ol={view:gc,panorama:Zc,lenses:Zc};function sl(e,t){return vc(e.view,t.view)&&$c(e.panorama,t.panorama)&&$c(e.lenses,t.lenses)}function cl(e,t){return{...e,view:t}}function ll(e,t){return{...e,lenses:t}}var ul=90;function dl({viewport:e,lensCount:t}){let n=Nc(t,Ac(e));return{tiles:n,bounds:Ic(n)}}function fl(e,t,n){let r=jc(t,n.viewport);return ll(e,rl(dl(n).bounds,e.lenses,r))}function pl(e,t,n){let r=n.viewport.width/ul;return fl(e,{x:-(t.yaw*r),y:t.pitch*r},n)}function ml(e,t){let{tiles:n,bounds:r}=dl(t),i=tl(r,e.lenses),a=el(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 hl={isStabilized:!1,canPan:({lenses:e})=>e.scale>1,pan:fl,turn:pl,zoom:(e,t,n)=>ll(e,nl(dl(n).bounds,e.lenses,t)),reset:e=>ll(e,Zc),picture:(e,t)=>({kind:`lens-tiles`,tiles:ml(e,t)})},gl={isStabilized:!0,canPan:()=>!0,pan:(e,t,{viewport:n})=>cl(e,Gc(e.view,t,n.width)),turn:(e,n)=>{let{view:r}=e;return cl(e,Xc(r,t(r.yaw+n.yaw),t(r.pitch+n.pitch)))},zoom:(e,t,{viewport:n})=>cl(e,qc(e.view,t,Ac(n))),reset:e=>cl(e,gc),picture:({view:e})=>({kind:`rectilinear`,rotation:yc(e),fieldOfView:e.fieldOfView,area:Dc})},_l=2;function vl(e,t){let n=tl(e,t);return{...n,centre:{x:Ec,y:n.centre.y}}}function yl(e,{viewport:t}){let n=Lc(_l,Ac(t));return{fitted:n,panorama:vl(n,e.panorama)}}function bl(e,n,r){let{view:i}=e;return{...cl(e,Xc(i,t(i.yaw+r),i.pitch)),panorama:n}}function xl(e,n,r){let{fitted:i,panorama:a}=yl(e,r),o=jc(n,r.viewport);return bl(e,rl(i,a,{across:0,down:o.down}),t(-(il(i,a,o).across*c)))}function Sl(e,t,n){let{fitted:r,panorama:i}=yl(e,n);return bl(e,vl(r,{...i,centre:{x:Ec,y:i.centre.y-t.pitch/s}}),t.yaw)}function Cl(e,n,r){let{fitted:i,panorama:a}=yl(e,r),o=vl(i,nl(i,a,n)),s=Mc(el(i,a),n.focus),l=Mc(el(i,o),n.focus);return bl(e,o,t((s.x-l.x)*c))}var wl={normal:gl,equirectangular:{isStabilized:!0,canPan:()=>!0,pan:xl,turn:Sl,zoom:Cl,reset:e=>({...cl(e,Xc(e.view,t(0),e.view.pitch)),panorama:Zc}),picture:(e,t)=>{let{fitted:n,panorama:r}=yl(e,t);return{kind:`equirectangular`,rotation:Pr(l(e.view.yaw)),area:el(n,r)}}},"raw-lenses":hl};function Tl(e){return wl[e]}var El=t(90);function Dl(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 Ol=5,kl={start:l(t(El-Ol)),end:l(t(El+Ol))};function Al(e){let t=[];for(let n of e.sources)t.every(e=>!Nl(e,n))&&t.push({inputIndex:n.inputIndex,trackIndex:n.trackIndex});return t}function jl(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=Al(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=Pl(t,n.lensIndex),a=r.findIndex(e=>Nl(e,n));return{lensIndex:n.lensIndex,frameSlot:a,region:n.region,window:Fl(t,i),rotation:rc(i),projection:Dl(i.model.projection,t.radialScale),halfFieldOfView:i.model.halfFieldOfView,displayConversion:Ml(e.displayConversions,a)}}),frameSlotCount:r.length,feather:kl}}function Ml(e,t){let n=e[t];return N(n!==void 0,`no display conversion for frame slot ${t}`),n}function Nl(e,t){return e.inputIndex===t.inputIndex&&e.trackIndex===t.trackIndex}function Pl(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 Fl(e,t){let n=e.canvas.height;return{x:Math.floor(t.model.principalPoint.x/n)*n,y:0,width:n,height:n}}var Il=class{parts;stabilizer=new Js;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(Gi(r,i)),this.parts.sink.present(e)}exposureTimeOf(e){let{timestamp:t}=e.pair;return this.parts.frameTimes?.midExposureAt(t)??t}};function Ll(e){let t=e instanceof Error?e:Error(`a failure went unheard`,{cause:e});Promise.reject(t)}var Rl=.5,zl=class{meter;applyGains;reportFailure;matcher=new dc;lastMeasuredAt;inFlight;isStopped=!1;constructor(e,t,n=Ll){this.meter=e,this.applyGains=t,this.reportFailure=n}afterPresent(e){(this.lastMeasuredAt===void 0||Math.abs(e-this.lastMeasuredAt)>=Rl)&&!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}}},Bl=[1,1,1],Vl=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 zl(t,t=>{e.setLensGains(t)});this.active={meter:t,matching:n}}disable(){this.stop();let e=Array.from({length:this.renderer.lensCount},()=>Bl);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}},Hl=7,Ul=.5,Wl=5,Gl=360;El-Hl,Math.round(14/Ul),Math.round(Wl/Ul);var Kl=Math.round(Gl/Wl);Array.from({length:Kl},()=>t(0));var ql=[`bt709`,`bt470bg`,`smpte170m`,`bt2020`,`smpte432`],Jl=[`bt709`,`smpte170m`,`iec61966-2-1`,`linear`,`pq`,`hlg`],Yl=[`rgb`,`bt709`,`bt470bg`,`smpte170m`,`bt2020-ncl`];function Xl(e,t){return e.find(e=>e===t)??`unspecified`}var Zl={a:.17883277,b:.28466892,c:.55991073,segmentJoin:.5,squareSegmentDivisor:3,logSegmentDivisor:12},Ql=[1.660491,-.5876411,-.0728499,-.1245505,1.1328999,-.0083494,-.0181508,-.1005789,1.1187297],$l=[.2126,.7152,.0722],eu={exposure:1.4,kneeStart:.2,ceiling:1.5,exponent:2.2},tu=/* @__PURE__ */ new Set([`bt709`,`bt470bg`,`smpte170m`,`unspecified`]),nu={bt709:Mr,bt2020:Ql,unspecified:Ql,bt470bg:void 0,smpte170m:void 0,smpte432:void 0};function ru({matrix:e}){return{kind:`as-recorded`,matrix:e}}function iu(e){let t=ru(e);return tu.has(e.primaries)?{conversion:t}:{conversion:t,problem:`${e.primaries} primaries are shown as BT.709`}}function au(e){let t=nu[e.primaries],n={kind:`hlg-to-sdr-bt709`,matrix:e.matrix,gamut:t??Mr,tone:eu};return t===void 0?{conversion:n,problem:`HLG of ${e.primaries} primaries is shown without their gamut`}:{conversion:n}}function ou(e){return t=>({conversion:ru(t),problem:`the ${e} transfer cannot be shown yet: drawn as recorded`})}var su={bt709:iu,smpte170m:iu,"iec61966-2-1":iu,unspecified:iu,hlg:au,pq:ou(`pq`),linear:ou(`linear`)};function cu(e){let t=e.map(e=>su[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 lu={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 uu(e,t){let n=lu[e],r=lu[t];return n===void 0||r===void 0||e===t?Mr:Ir(du(n),fu(r))}function du({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 fu({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 pu(e){return Object.keys(e)}var mu=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}}}},hu={done:!0,value:void 0},gu=class{isEnded=!1;end(){this.isEnded=!0}hasEnded(){return this.isEnded}},_u=class{source;constructor(e){this.source=e}stream(e){return{[Symbol.asyncIterator]:()=>new vu(this.source,e)}}},vu=class{source;range;ending=new gu;constructor(e,t){this.source=e,this.range=t}async next(){if(await Promise.resolve(),this.ending.hasEnded())return hu;let e=await this.source.read(this.range);return this.ending.hasEnded()?hu:(this.ending.end(),e.byteLength===0?hu:{done:!1,value:e})}return(){return this.ending.end(),Promise.resolve(hu)}},yu=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 gu;constructor(e,t){this.track=e,this.cursor=t}async next(){let e=await this.cursor.nextSample();return!e||this.ending.hasEnded()?hu:{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(hu)}},xu=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 Su({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}}},Su=class{parts;cursor;isVerified=!1;ending=new gu;constructor(e){this.parts=e,this.cursor=e.open()}async next(){if(this.ending.hasEnded())return hu;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()?hu:!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(hu)}startEarlier(e,t){return this.parts.reject(t.sample),e.close(),this.cursor=this.parts.open(),this.next()}},Cu=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=>Tu(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]=Eu(e.offset,r.end,e.end):n.push(r)}return n}function Tu(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 Eu(e,t,n){return Fn.of(e,Math.max(t,n)-e)}var Du=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)}},Ou=class{blocks=[];get held(){return Cu.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 Du(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?ku(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 ku(e,t){let n=t.offset-e.range.offset;return e.bytes.subarray(n,n+t.length)}var Au=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}}},ju=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:Mu(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(Mu(e),t))}isRunning(e){return this.running.get(e.id)===e}};function Mu(e){let{range:t}=e.block;return Fn.of(t.offset+e.delivered,t.length-e.delivered)}function Nu(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 Pu(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 Cu.of(n)}function Fu(e){let{policy:t}=e,n=R(e.time+t.resumeSeconds),r=e.cursors.filter(e=>e.track.kind===`video`),i=Cu.of(r.flatMap(e=>Nu(e,n))),a=Math.min(t.requestSize,t.refillBytes);return Pu(i,t.aheadBytes-a)}function Iu(e){return Fu(e).subtract(e.held).isEmpty}function Lu(e){let t=e.cursors.filter(e=>Gu(e)),n=t.length>0?Bu(t):e.anchor,r=n??Ru(e);if(!r)return zu(e);let i=e.isReadingAhead?e.policy.aheadSeconds:0,a=R(r.time+i),o=Vu({state:e,windowStart:r,windowEnd:a}).bridgingGapsBelow(e.policy.bridgedGap),s=e.transfers.filter(e=>e.remaining.length===0||o.overlaps(e.remaining)),c=Cu.of(s.map(e=>e.remaining)),l=o.subtract(e.held).subtract(c).subtract(e.unreadable),u=e.policy.requestsInFlight-s.length;return{start:qu({state:e,windowStart:r,windowEnd:a,missing:l,threshold:Ku(e,r)})?Yu(l,e.policy,u):[],cancel:e.transfers.filter(e=>!s.includes(e)).map(e=>e.id),release:e.held.subtract(o.union(Xu(r,e.policy))),anchor:n}}function Ru(e){return e.isReadingAhead&&e.cursors.length>0?Bu(e.cursors):void 0}function zu(e){return{start:[],cancel:e.transfers.map(e=>e.id),release:Cu.empty,anchor:void 0}}function Bu(e){return{time:R(Math.min(...e.map(e=>$u(e)))),offset:Math.min(...e.map(e=>td(e))),keyframeOffset:Math.min(...e.map(e=>ed(e)))}}function Vu(e){let{state:t,windowEnd:n}=e,r=t.cursors.filter(t=>Hu(t,e)),i=r.flatMap(e=>Nu(e,Wu(n,e.target))),a=r.filter(e=>Uu(e,n)),o=Cu.of(a.map(e=>e.track.rangeOf(e.sample)));return Pu(Cu.of(i),t.policy.aheadBytes).union(o)}function Hu(e,t){return $u(e)>=t.windowStart.time-t.state.policy.keepBehindSeconds}function Uu(e,t){let n=e.isWaiting&&$u(e)<=t;return!Qu(e)&&(Gu(e)||n)}function Wu(e,t){return t!==void 0&&t>e?t:e}function Gu(e){return e.track.kind===`video`}function Ku(e,t){let n={cursors:e.cursors,time:t.time,policy:e.policy};return e.isReadingAhead?Fu(n):Cu.empty}function qu(e){let{state:t,missing:n,threshold:r}=e;return n.ranges.some(e=>r.overlaps(e))?!0:t.cursors.some(t=>Ju(t,e)&&n.overlaps(t.track.rangeOf(t.sample)))||n.totalLength>=t.policy.refillBytes}function Ju(e,t){if(!e.isWaiting||Qu(e))return!1;let{windowStart:n,state:r}=t,i=n.time+(r.isReadingAhead?r.policy.resumeSeconds:0);return Gu(e)||$u(e)<=i}function Yu(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 Xu(e,t){let n=Zu(e,t);return Cu.of([Fn.of(n,e.offset-n)])}function Zu(e,t){return Math.max(0,Math.min(e.keyframeOffset,e.offset-t.keepBehindBytes))}function Qu(e){return e.sample>=e.track.sampleCount}function $u(e){return Qu(e)?e.track.end:e.track.timestampOf(e.sample)}function ed(e){let{track:t}=e,n=Math.min(e.sample,t.sampleCount-1),r=t.syncSampleAtOrBefore(n);return r===void 0?td(e):t.rangeOf(r).offset}function td(e){let{track:t}=e;return Qu(e)?t.sampleCount>0?t.rangeOf(t.sampleCount-1).end:0:t.rangeOf(e.sample).offset}var nd=Fn.of(0,2**53-1),rd=class{parts;store=new Ou;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 ju({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 Au(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 Iu({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:nd,error:t});for(let e of this.cursors)e.fail(nd,t)}plan(){this.takenSincePlan=0;let e=Lu({cursors:this.positions(),held:this.store.held,transfers:this.transfers.states,unreadable:Cu.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 id(e){let t=new rd(e);return{download:t,videoTracks:e.codecs.video.map(n=>new xu({download:t,track:ad(e.table,n.trackId,`video`),codec:n})),audioTracks:e.codecs.audio.map(n=>({samples:new yu({download:t,track:ad(e.table,n.trackId,`audio`)}),configuration:n.configuration})),duration:e.table.duration,dispose:()=>{t.dispose()}}}function ad(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 od=1048576,sd=10,cd=128,ld=2,ud=32,dd=8,fd=2,pd=1,md=.25,hd=16,gd=4;function _d(e,t){let n=e.size/e.duration,r=Math.min(Math.round(sd*n),cd*od/t),i=Math.round(r*md);return{aheadSeconds:R(sd),aheadBytes:r,keepBehindBytes:Math.min(Math.round(ld*n),ud*od/t),keepBehindSeconds:R(ld),requestSize:dd*od,requestsInFlight:fd,bridgedGap:pd*od,refillBytes:i,replanBytes:Math.round(i/hd),resumeSeconds:R(gd)}}var vd=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 yd(e){for(let t of e.frames)t.close()}var bd=class{capacity;onPush;pairs=[];roomWaiters=[];isClosed=!1;constructor(e,t=xd){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){yd(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&&yd(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)yd(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 xd(){}var Sd=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}},Cd=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&&yd(this.held),this.held=void 0}hold(e){this.held&&(yd(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)}}},Td=Symbol(`stopped`),Ed=class{isStopped=!1;wakeWaiter;get wasStopped(){return this.isStopped}stop(){this.isStopped=!0,this.wakeWaiter?.()}async race(e){if(this.isStopped)return Td;N(this.wakeWaiter===void 0,`a run stop races one wait at a time`);let t=new Promise(e=>{this.wakeWaiter=()=>{e(Td)}});try{return await Promise.race([e(),t])}finally{this.wakeWaiter=void 0}}},Dd=class{frameSources;decoderPort;options;stop=new Ed;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 kd(n,e),n.failure.isSettled)throw await n.failure.promise;return Nd(n,e)}finally{jd(n)}}abort(){this.stop.stop(),Md(this.iterators)}async openRun(e,t){let{stop:n}=this,r=new wd,i={packets:0,pairs:0},a=new Cd(e,e=>{i.pairs+=1,t.push(e)}),o=new Sd(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 Md(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 Pd(i.reason)}return r}async feed(e){for(;!Od(e);){if(await e.stop.race(()=>e.output.waitForRoom()),Od(e))return!1;let t=await e.stop.race(()=>Fd(e.iterators));if(t===Td)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)),Od(e))return;r.decode(i),e.tally.packets+=1}}}packetIteratorsFrom(e){return this.frameSources.map(t=>t.packetsFrom(e)[Symbol.asyncIterator]())}};function Od(e){return e.stop.wasStopped||e.output.isClosedForGood}async function kd(e,t){await e.stop.race(()=>Ad(e.decoders,e.failure))!==Td&&t&&e.gate.release()}async function Ad(e,t){try{await Promise.all(e.map(e=>e.flush()))}catch(e){if(!t.isSettled)throw e}}function jd(e){for(let t of e.decoders)t.close();e.pairer.discardAll(),e.gate.discard(),Md(e.iterators)}function Md(e){for(let t of e)t.return?.()}function Nd(e,t){return{packetsDecoded:e.tally.packets,pairsDelivered:e.tally.pairs,unpairedFrames:e.pairer.unpaired,pairsDroppedBeforeStart:e.gate.dropped,hasReachedEnd:t}}function Pd(e){return e instanceof Error?e:new j(`decode`,`a decoder could not be created`,{cause:e})}async function Fd(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 Id={verdict:`decodes`,detail:void 0},Ld={verdict:`no-key-frame`,detail:`the track has no key frame`},Rd={verdict:`decode-failed`,detail:`the decoder accepted the first key frame but produced no picture`},zd={verdict:`timed-out`,detail:`the decoder produced no picture before the deadline`},Bd={verdict:`key-frame-late`,detail:`the first key frame did not arrive before the deadline`};async function Vd(e,t,n){let r=e.map(e=>new Wd(e,t));try{let e=await Promise.all(r.map(e=>Hd(e,n)));return{canDecode:e.every(e=>e.verdict===`decodes`),sources:e}}finally{for(let e of r)e.close()}}async function Hd(e,t){try{let n=await Promise.race([e.run(),Ud(t,e)]);return{track:e.track.description,...n}}finally{e.close()}}async function Ud(e,t){return await e.promise,t.outcomeAtDeadline}var Wd=class{track;decoderPort;decoder;firstOutcome;isClosed=!1;isReadingKeyFrame=!1;constructor(e,t){this.track=e,this.decoderPort=t}get outcomeAtDeadline(){return this.isReadingKeyFrame?Bd:zd}async run(){let e=await this.track.decoderConfiguration();if(!await this.decoderPort.isSupported(e))return Gd(e);if(this.isClosed)return zd;let t=await this.track.firstKeyframe();if(!t)return Ld;this.isReadingKeyFrame=!0;let n=await qd(this.track,t.timestamp);return this.isReadingKeyFrame=!1,n?await this.decodeFirst(e,n):Ld}close(){this.isClosed=!0,this.decoder?.close(),this.decoder=void 0,this.firstOutcome?.resolve(zd)}async decodeFirst(e,t){if(this.isClosed)return zd;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(Id)},onError:e=>{t.resolve(Kd(e))}});if(!this.isClosed)return n;n.close(),t.resolve(zd)}catch(e){t.resolve(Kd(e))}}async decodeInto(e,t,n){try{e.decode(t),await e.flush(),n.resolve(Rd)}catch(e){n.resolve(Kd(e))}}};function Gd(e){return{verdict:`unsupported-configuration`,detail:`${e.codec} at ${e.codedWidth}x${e.codedHeight} is not supported here`}}function Kd(e){let t=ie(e);return{verdict:M(e,`codec-unsupported`)?`unsupported-configuration`:`decode-failed`,detail:t}}async function qd(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 Jd=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()}},Yd={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:[]},Xd=/* @__PURE__ */ new Set([`playing`,`buffering`]);function Zd(e){return e!==void 0&&Xd.has(e)}var Qd=class{current=`ready`;get state(){return this.current}canTransitionTo(e){return Yd[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)}},$d=class{reportListenerError;listeners=/* @__PURE__ */ new Map;constructor(e=Ll){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()}},ef=1,tf=.25,nf=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))>tf}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>ef}};function rf(e){return!e.isRunning&&!e.hasEnded}function af(e,t){return e.hasEnded||e.currentTime>=t}var of=class{generation=0;scrubs=0;isFromFlowing=!1;get resumesPlaying(){return this.isFromFlowing}begin(e){this.isFromFlowing=Zd(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}},sf=.25,cf=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)>=sf)&&this.announce(e)}},lf=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()}},uf=class{machine=new Qd;outbox;constructor(e){this.outbox=new mu(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)}},df=2,ff=.25,pf=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(df,e.queueCapacity),this.queue=new bd(e.queueCapacity,()=>{this.isAborted||t.onProgress()}),this.stopFollowingBuffer=e.buffer?.onProgress(()=>{t.onProgress()})??(()=>void 0),this.pipeline=new Dd(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>ff}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 mf(e,t){try{return(await e.keyframeAt(t))?.timestamp??t}catch{return t}}var hf=class{parts;events=new $d;lifecycle=new uf(this.events);run;presented;timeUpdates=new cf(this.lifecycle);buffering=new lf(this.lifecycle);clockWatch=new nf;seeks=new of;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 mf(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&&yd(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(rf(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`||af(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&&yd(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=pf.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 gf(e,t){if(e===null)return;let n=e.trim().toLowerCase();return t.find(e=>e===n)}function _f(e){return gf(e,Ks)}function vf(e){return gf(e,wc)}function yf(e){return gf(e,bc)}function bf(e,t){for(let n of t)Object.defineProperty(e,Df(n),{configurable:!0,enumerable:!0,get(){return this.getAttribute(n)},set(e){Tf(this,n,e)}})}function xf(e,t){for(let n of t)Object.defineProperty(e,Df(n),{configurable:!0,enumerable:!0,get(){return this.hasAttribute(n)},set(e){this.toggleAttribute(n,!!e)}})}function Sf(e,t){for(let n of t)Object.defineProperty(e,Df(n.name),{configurable:!0,enumerable:!0,get(){return wf(n,this.getAttribute(n.name))},set(e){Tf(this,n.name,e)}})}function Cf(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){Tf(this,n.name,e)}})}function wf(e,t){let n=t?.trim().toLowerCase();return e.keywords.find(e=>e===n)??e.fallback}function Tf(e,t,n){if(n==null){e.removeAttribute(t);return}e.setAttribute(t,n)}var Ef=/-(?<letter>[a-z])/gu;function Df(e){return e.replaceAll(Ef,(e,t)=>t.toUpperCase())}function Of(e,t){if(typeof e!=`number`||!Number.isFinite(e))throw new j(`invalid-argument`,`${t} must be a finite number`)}function kf(e){return Of(e.yaw,`yaw`),Of(e.pitch,`pitch`),Of(e.fieldOfView,`fieldOfView`),{yaw:t(e.yaw),pitch:t(e.pitch),fieldOfView:t(e.fieldOfView)}}var Af=/* @__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`]]),jf=/* @__PURE__ */ new Map([[`ArrowLeft`,`seek-back`],[`ArrowRight`,`seek-forward`]]);function Mf(e){if(!e.hasSystemModifier)return e.key.length===1?Af.get(e.key.toLowerCase()):e.isShiftPressed?jf.get(e.key):Af.get(e.key)}var Nf=5;function Pf(e){return({player:t})=>{t.seek(t.currentTime+e)}}function Ff(e,t){return({player:n})=>{n.turn(e,t)}}var If={"toggle-play":e=>{e.togglePlay()},stop:({player:e})=>{e.stop()},"seek-back":Pf(-5),"seek-forward":Pf(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":Ff(-5,0),"look-right":Ff(Nf,0),"look-up":Ff(0,Nf),"look-down":Ff(0,-5)};function Lf(e,t){let n=new AbortController;return e.addEventListener(`keydown`,e=>{if(e.key===`Escape`&&t.isFullscreen()){t.exitFullscreen();return}let n=Mf({key:e.key,isShiftPressed:e.shiftKey,hasSystemModifier:e.ctrlKey||e.altKey||e.metaKey});n&&!Bf(e)&&(e.preventDefault(),If[n](t))},{signal:n.signal}),()=>{n.abort()}}var Rf=/* @__PURE__ */ new Set([`ArrowLeft`,`ArrowRight`,`ArrowUp`,`ArrowDown`]),zf=` `;function Bf(e){let[t]=e.composedPath();return t instanceof HTMLInputElement?Rf.has(e.key):t instanceof HTMLButtonElement&&e.key===zf}var Vf=100,Hf=`data-draggable`,Uf=0,Wf=4,Gf=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(Hf)}onPointerDown=e=>{(e.pointerType!==`mouse`||e.button===Uf)&&(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<Wf&&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/Vf,this.focusAt(t)),this.reflectDraggable()};reflectDraggable=()=>{this.surface.toggleAttribute(Hf,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=Yc(Kf(r,n),Kf(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 Kf(e,t){return Math.hypot(e.x-t.x,e.y-t.y)}function qf(e,t,n={}){let r=new Gf(e,t,n.onTap??(()=>{Yf(t)}));return()=>{r.detach()}}function Jf(e,t,n={}){let r=()=>e.matches(`:fullscreen`);return Lf(e,{player:t,togglePlay:()=>{Yf(t)},toggleFullscreen:n.toggleFullscreen??(()=>{r()?document.exitFullscreen():e.requestFullscreen()}),isFullscreen:r,exitFullscreen:()=>{document.exitFullscreen()}})}function Yf(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 Xf=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})}}},Zf=/^bytes (\d+)-(\d+)\/(\d+|\*)$/u,Qf=`*`;function $f(e){let t=Zf.exec(e.headers.get(`content-range`)??``);if(!t)return;let[,n,r,i]=t;return{first:Number(n),last:Number(r),total:i===Qf?void 0:Number(i)}}var ep=/* @__PURE__ */ new WeakSet;function tp(e){return ep.add(e),e}function np(e){return e instanceof j&&ep.has(e)}function rp(e){return M(e,`source-unreadable`)&&e instanceof Error?tp(new j(`source-unreadable`,e.message,{cause:e.cause})):e}function ip(e,t,n){return tp(new j(`source-unreadable`,`${e} broke off the ${t.length}-byte range at ${t.offset}`,{cause:n}))}function ap(e,t,n){return new j(`source-truncated`,`${e} returned ${t} bytes for a ${n.length}-byte range at ${n.offset}`)}var op=1e4,sp=class{resource;stallTimeoutMs;constructor(e,t={}){this.resource=e,this.stallTimeoutMs=t.stallTimeoutMs??op}stream(e){return{[Symbol.asyncIterator]:()=>new cp({resource:this.resource,range:e,stallTimeoutMs:this.stallTimeoutMs})}}},cp=class{parts;attempt;received=0;ending=new gu;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(),hu}return(){return this.end(),Promise.resolve(hu)}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=$f(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:ip(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 tp(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 ap(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)}},lp=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 ap(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:ip(this.resource.url,t,e)}}},up=`bytes=0-0`,dp=`Access-Control-Expose-Headers: Content-Range, Content-Length, Accept-Ranges, ETag`,fp=`Access-Control-Allow-Origin, ${dp}`,pp=`Access-Control-Allow-Origin naming this page's origin, not *; Access-Control-Allow-Credentials: true; ${dp}`,mp=`no-store`;async function hp(e,t,n){try{return await gp(e,t,n)}catch(t){throw re(t)?t:await yp(e,n,t)}}function gp(e,t,n){return(n.fetch??fetch)(e,{cache:mp,...n.requestInit,method:t.method,headers:{...wp(n.requestInit),...t.headers}})}function _p(e,t){let n=e.requestInit?.signal??void 0,r=n?vp(n,t):t;return{...e,requestInit:{...e.requestInit,signal:r}}}function vp(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 yp(e,t,n){return await xp(e,t)?new j(`cors`,`${e} answered, but its server does not allow this page's origin to read it; add CORS headers (${bp(t)})`,{cause:n}):new j(`source-unreadable`,`${e} could not be fetched; check the URL and the network`,{cause:n})}function bp(e){return e.requestInit?.credentials===`include`?pp:fp}async function xp(e,t){let n=t.fetch??fetch,r=t.requestInit?.signal??null;try{return Sp(await n(e,{method:`HEAD`,mode:`no-cors`,signal:r})),!0}catch(e){if(re(e))throw e;return!1}}function Sp(e){Cp(e)}async function Cp(e){try{await e.body?.cancel()}catch{}}function wp(e){return Object.fromEntries(new Headers(e?.headers).entries())}var Tp=200,Ep=/^W\//u;function Dp(e){let t=e.headers.get(`etag`),n=e.headers.get(`last-modified`),r=jp(e);return{...t!==null&&{etag:t},...n!==null&&{lastModified:n},...r!==void 0&&{size:r}}}function Op(e,t){return e.etag!==void 0&&t.etag!==void 0?kp(e.etag)===kp(t.etag):Ap(e.lastModified,t.lastModified)&&Ap(e.size,t.size)}function kp(e){return e.replace(Ep,``)}function Ap(e,t){return e===void 0||t===void 0||e===t}function jp(e){let t=e.status===Tp?Number(e.headers.get(`content-length`)??NaN):$f(e)?.total;return t!==void 0&&Number.isSafeInteger(t)&&t>0?t:void 0}var Mp=200,Np=206,Pp=500,Fp=[250,1e3],Ip=class{url;options;retryDelaysMs;sizePromise;hasReadRange=!1;version;constructor(e,t={},n){this.url=e,this.options=n?_p(t,n):t,this.retryDelaysMs=t.retryDelaysMs??Fp}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(!np(e))throw e}await Lp(t,this.options.requestInit?.signal)}return e()}async rangeAnswer(e,t){let n=t?_p(this.options,t):this.options,r=await this.requestRange(e,n);if(r.status!==Np)throw Sp(r),this.refusalOf(r.status);return this.hasReadRange=!0,this.ensureUnchanged(r),r}ensureUnchanged(e){let t=Dp(e);if(this.version??=t,!Op(this.version,t))throw Sp(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 gp(this.url,{method:`GET`,headers:n},t):await hp(this.url,{method:`GET`,headers:n},t)}catch(e){throw this.hasReadRange?this.passingOnceAnswered(e):rp(e)}}passingOnceAnswered(e){let t=`${this.url} could not be reached for a byte range`;return re(e)?e:tp(new j(`source-unreadable`,t,{cause:e}))}refusalOf(e){if(e===Mp)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>=Pp?tp(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(Sp(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(Sp(e),e.status!==Np)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=$f(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 ${dp}`)}request(e,t){return hp(this.url,{method:e,...t&&{headers:t}},this.options)}};function Lp(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(Rp(t))},{once:!0,signal:i.signal})})}function Rp(e){let t=e?.reason;return t instanceof Error?t:new DOMException(`the read was aborted`,`AbortError`)}var zp=/* @__PURE__ */ new Set([405,403]),Bp=class{options;constructor(e={}){this.options=e}async exists(e){try{let t=await gp(e,{method:`HEAD`},this.options);if(Sp(t),!zp.has(t.status))return t.ok;let n=await gp(e,{method:`GET`,headers:{Range:up}},this.options);return Sp(n),n.ok}catch{return!1}}};function z(e){if(!e)throw Error(`Assertion failed.`)}var Vp=Math.PI/180,Hp=180/Math.PI,Up=e=>{let t=(e%360+360)%360;if(t===0||t===90||t===180||t===270)return t;throw Error(`Invalid rotation ${e}.`)},Wp=[1,0,0,0,1,0,0,0,1],Gp=(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 Zp(Zp(Yp(-t/2,-n/2),e),Yp(s/2,c/2))},Kp=e=>{let[t,n]=e;return Up(Pm(Math.atan2(n,qp(e)?-t:t)*Hp,90))},qp=e=>{let[t,n,,r,i]=e;return t*i-n*r<0},Jp=e=>{let t=e*Vp,n=Math.round(Math.cos(t)),r=Math.round(Math.sin(t));return[n,r,0,-r,n,0,0,0,1]},Yp=(e,t)=>[1,0,0,0,1,0,e,t,1],Xp=(e,t)=>[e,0,0,0,t,0,0,0,1],Zp=(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},Qp=e=>e&&e[e.length-1],$p=e=>e>=0&&e<2**32,em=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)},tm=e=>{let t=B(e);return t&1?t+1>>1:-(t>>1)},nm=e=>e.constructor===Uint8Array?e:ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):new Uint8Array(e),rm=e=>e.constructor===DataView?e:ArrayBuffer.isView(e)?new DataView(e.buffer,e.byteOffset,e.byteLength):new DataView(e),im=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,am=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?nm(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,om=/* #__PURE__ */ new am,sm=/* #__PURE__ */ new im,cm=e=>Object.fromEntries(Object.entries(e).map(([e,t])=>[t,e])),lm={bt709:1,bt470bg:5,smpte170m:6,bt2020:9,smpte432:12},um=/* #__PURE__ */ cm(lm),dm={bt709:1,smpte170m:6,linear:8,"iec61966-2-1":13,pq:16,hlg:18},fm=/* #__PURE__ */ cm(dm),pm={rgb:0,bt709:1,bt470bg:5,smpte170m:6,"bt2020-ncl":9},mm=/* #__PURE__ */ cm(pm),hm=e=>!!e&&!!e.primaries&&!!e.transfer&&!!e.matrix&&e.fullRange!==void 0,gm=e=>!e||e.primaries==null&&e.transfer==null&&e.matrix==null&&e.fullRange==null,_m={primaries:void 0,transfer:void 0,matrix:void 0,fullRange:void 0},vm=e=>e instanceof ArrayBuffer||typeof SharedArrayBuffer<`u`&&e instanceof SharedArrayBuffer||ArrayBuffer.isView(e),ym=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}},bm=/^[0-9a-fA-F]+$/,xm=e=>[...e].map(e=>e.toString(16).padStart(2,`0`)).join(``),Sm=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},Cm=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),wm=(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},Tm=(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},Em=()=>{let e,t;return{promise:new Promise((n,r)=>{e=n,t=r}),resolve:e,reject:t}},Dm=(e,t)=>{let n=e.indexOf(t);n!==-1&&e.splice(n,1)},Om=(e,t)=>{for(let n=e.length-1;n>=0;n--)if(t(e[n]))return n;return-1},km=e=>{throw Error(`Unexpected value: ${e}`)},Am=(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},jm=(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))},Mm=(e,t,n)=>Math.max(t,Math.min(n,e)),Nm=e=>{let t=Math.round(e);return Math.abs(e/t-1)<10*2**-52?t:e},Pm=(e,t)=>Math.round(e/t)*t,Fm=(e,t)=>Math.round(e*t)/t,Im=e=>{let t=0;for(;e!==0;)e&=e-1,t++;return t},Lm=/^[a-z]{3}$/,Rm=e=>Lm.test(e),zm=1e6*(1+2**-52),Bm=(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}},Vm=null,Hm=()=>Vm===null?Vm=!(typeof navigator>`u`||!navigator.vendor?.includes(`Google Inc`)&&!/Chrome/.test(navigator.userAgent)):Vm,Um=(/* #__PURE__ */ (async()=>{})()).constructor,Wm=e=>e instanceof Um||e instanceof Promise||typeof e?.then==`function`,Gm=function*(e){for(let t in e){let n=e[t];n!==void 0&&(yield{key:t,value:n})}},Km=(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},qm=()=>{Symbol.dispose??=Symbol(`Symbol.dispose`)},Jm=e=>typeof e==`number`&&!Number.isNaN(e),Ym=(e,t)=>{let n=0;for(let r=0;r<e.length;r++)t(e[r])&&n++;return n},Xm=(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},Zm=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}},Qm=e=>Array.isArray(e)?e:[e],$m=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)}}},eh=e=>typeof e==`object`&&!!e&&Object.getPrototypeOf(e)===Object.prototype&&Object.values(e).every(e=>typeof e==`string`),th;(function(e){e[e.Silent=0]=`Silent`,e[e.Errors=1]=`Errors`,e[e.Warnings=2]=`Warnings`,e[e.Info=3]=`Info`})(th||={});var nh=class e{constructor(){}static get level(){return e._level}static set level(t){if(t!==th.Silent&&t!==th.Errors&&t!==th.Warnings&&t!==th.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 $m}static on(t,n,r){return e._emitter.on(t,n,r)}static _error(...t){e._emitter._emit(`error`,t),e._level>=th.Errors&&console.error(...t)}static _warn(...t){e._emitter._emit(`warn`,t),e._level>=th.Warnings&&console.warn(...t)}static _info(...t){e._emitter._emit(`info`,t),e._level>=th.Info&&console.info(...t)}};nh._level=th.Info,nh._emitterInstance=null;var rh=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.`)}},ih=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.`)}},ah=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 rh)&&!(t instanceof ih)&&!eh(t))throw TypeError(`Each value in tags.raw must be a string, string array, Uint8Array, RichImageData, AttachedFile, Record<string, string>, or null.`)}},oh={default:!0,primary:!0,forced:!1,original:!1,commentary:!1,hearingImpaired:!1,visuallyImpaired:!1},sh=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.`)},ch=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}},lh=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],uh=[-1,1,2,3,4,5,6,8],dh=e=>{if(!e||e.byteLength<2)throw TypeError(`AAC description must be at least 2 bytes long.`);let t=new ch(e),n=fh(t),{frequencyIndex:r,sampleRate:i}=ph(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=ph(t).sampleRate,s=fh(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}fh(t)===5&&t.readBits(1)&&(l=ph(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}},fh=e=>{let t=e.readBits(5);return t===31?32+e.readBits(6):t},ph=e=>{let t=e.readBits(4);return t===15?{frequencyIndex:t,sampleRate:e.readBits(24)}:{frequencyIndex:t,sampleRate:t<lh.length?lh[t]:null}},mh=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),_h(r)===15&&(o+=24),t&&(o+=9,_h(e.outputSampleRate)===15&&(o+=24));let s=Math.ceil(o/8),c=new Uint8Array(s),l=new ch(c);return hh(l,e.objectType),gh(l,r),l.writeBits(4,a),t&&(gh(l,e.outputSampleRate),hh(l,2)),l.writeBits(3,0),c},hh=(e,t)=>{t<32?e.writeBits(5,t):(e.writeBits(5,31),e.writeBits(6,t-32))},gh=(e,t)=>{let n=_h(t);e.writeBits(4,n),n===15&&e.writeBits(24,t)},_h=e=>{let t=lh.indexOf(e);return t===-1?15:t},vh=[48e3,44100,32e3],yh=[24e3,22050,16e3],bh;(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`})(bh||={});var xh;(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`})(xh||={});var Sh=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})},Ch=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=Am(r,n,!1):(z(t===4),e=r.getUint32(n,!1)),n+=t,yield{offset:n,length:e},n+=e}},wh=(e,t)=>t.description?Ch(e,(nm(t.description)[4]&3)+1):Sh(e),Th=e=>e&31,Eh=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 Dh=(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:jm(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},Oh=e=>{try{let t=[],n=[],r=[];for(let i of Sh(e)){let a=e.subarray(i.offset,i.offset+i.length),o=Th(a[0]);o===bh.SPS?t.push(a):o===bh.PPS?n.push(a):o===bh.SPS_EXT&&r.push(a)}if(t.length===0||n.length===0)return null;let i=t[0],a=Mh(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 nh._error(`Error building AVC Decoder Configuration Record:`,e),null}},kh=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)},Ah=e=>{try{let t=rm(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 nh._error(`Error deserializing AVC Decoder Configuration Record:`,e),null}},jh={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}},Mh=e=>{try{let t=Eh(e),n=new ch(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=tm(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),tm(n),tm(n);let e=B(n);for(let t=0;t<e;t++)tm(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=jh[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&&Nh(n);let t=n.readBits(1);t&&Nh(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=Pg.find(e=>e.level>=a)??Qp(Pg),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 nh._error(`Error parsing AVC SPS:`,e),null}},Nh=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)},Ph=(e,t)=>t.description?Ch(e,(nm(t.description)[21]&3)+1):Sh(e),Fh=e=>e>>1&63,Ih=e=>{try{let t=new ch(Eh(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}=Rh(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)&&zh(t),t.skipBits(1),t.skipBits(1),t.readBits(1)&&(t.skipBits(4),t.skipBits(4),B(t),B(t),t.skipBits(1)),Bh(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=Hh(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 nh._error(`Error parsing HEVC SPS:`,e),null}},Lh=e=>{try{let t=[],n=[],r=[],i=[];for(let a of Sh(e)){let o=e.subarray(a.offset,a.offset+a.length),s=Fh(o[0]);s===xh.VPS_NUT?t.push(o):s===xh.SPS_NUT?n.push(o):s===xh.PPS_NUT?r.push(o):(s===xh.PREFIX_SEI_NUT||s===xh.SUFFIX_SEI_NUT)&&i.push(o)}if(n.length===0||r.length===0)return null;let a=Ih(n[0]);if(!a)return null;let o=0;if(r.length>0){let e=r[0],t=new ch(Eh(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),tm(t),t.skipBits(1),t.skipBits(1),t.readBits(1)&&B(t),tm(t),tm(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:xh.VPS_NUT,nalUnits:t}]:[],...n.length?[{arrayCompleteness:1,nalUnitType:xh.SPS_NUT,nalUnits:n}]:[],...r.length?[{arrayCompleteness:1,nalUnitType:xh.PPS_NUT,nalUnits:r}]:[],...i.length?[{arrayCompleteness:1,nalUnitType:Fh(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 nh._error(`Error building HEVC Decoder Configuration Record:`,e),null}},Rh=(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}},zh=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&&tm(e);for(let t=0;t<n;t++)tm(e)}},Bh=(e,t)=>{let n=[];for(let r=0;r<t;r++)n[r]=Vh(e,r,t,n)},Vh=(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},Hh=(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=jh[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)&&Uh(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}},Uh=(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&&Wh(e,s,a),i&&Wh(e,s,a)}},Wh=(e,t,n)=>{for(let r=0;r<t;r++)B(e),B(e),n&&(B(e),B(e)),e.readBits(1)},Gh=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)},Kh=e=>{try{let t=rm(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 nh._error(`Error deserializing HEVC Decoder Configuration Record:`,e),null}},qh;(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`})(qh||={});var Jh={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}},Yh=e=>{let t=new ch(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=Qp(Fg).level;for(let e of Fg)if(u<=e.maxPictureSize){d=e.level;break}let f=Jh[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}},Xh=e=>e.colourPrimaries!==2||e.transferCharacteristics!==2||e.matrixCoefficients!==2,Zh=function*(e){let t=new ch(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)}},Qh=e=>{for(let{type:t,data:n}of Zh(e)){if(t!==1)continue;let e=new ch(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},$h=e=>e.colourPrimaries!==2||e.transferCharacteristics!==2||e.matrixCoefficients!==2,eg=e=>{if(e.length<36)return null;let t=rm(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)}},tg=e=>{let t=rm(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}},ng=(e,t,n)=>{switch(e){case`avc`:for(let e of wh(n,t)){let t=n[e.offset],r=Th(t);if(r>=bh.NON_IDR_SLICE&&r<=bh.SLICE_DPC)return`delta`;if(r===bh.IDR)return`key`;if(r===bh.SEI&&!Hm()){let t=Eh(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 ch(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 Ph(n,t)){let t=Fh(n[e.offset]);if(t<xh.BLA_W_LP)return`delta`;if(t<=xh.RSV_IRAP_VCL23)return`key`}return`delta`;case`vp8`:return n[0]&1?`delta`:`key`;case`vp9`:{let e=new ch(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 Zh(n))if(t===1){let t=new ch(r);t.skipBits(4),e=!!t.readBits(1)}else if(t===3||t===6||t===7){if(e)return`key`;let t=new ch(r);return t.readBits(1)?null:t.readBits(2)===0?`key`:`delta`}return null}case`prores`:return`key`;default:km(e),z(!1)}},rg;(function(e){e[e.STREAMINFO=0]=`STREAMINFO`,e[e.VORBIS_COMMENT=4]=`VORBIS_COMMENT`,e[e.PICTURE=6]=`PICTURE`})(rg||={});var ig=[2,1,2,3,3,4,4,5],ag=e=>{if(e.length<7||e[0]!==11||e[1]!==119)return null;let t=new ch(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 og=[1,2,3,6],sg=e=>{if(e.length<6||e[0]!==11||e[1]!==119)return null;let t=new ch(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=og[o],d;return d=i<3?vh[i]/1e3:yh[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}]}},cg=e=>{if(e.length<2)return null;let t=new ch(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}},lg=e=>{let t=e.substreams[0];return z(t),t.fscod<3?vh[t.fscod]:t.fscod2!==null&&t.fscod2<3?yh[t.fscod2]:null},ug=e=>{let t=e.substreams[0];z(t);let n=ig[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},dg=8,fg=[0,8e3,16e3,32e3,0,0,11025,22050,44100,0,0,12e3,24e3,48e3,96e3,192e3],pg=[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],mg=[16,16,20,20,0,24,24,0],hg=[1,2,2,2,2,3,3,4,4,5,6,6,6,7,8,8],gg=[1,2,2,2,2,3,18,19,6,7,518,323,83,519,582,535],_g=8,vg=44646,yg=[32e3,44100,48e3,0],bg=[8e3,16e3,32e3,64e3,128e3,22050,44100,88200,176400,352800,12e3,24e3,48e3,96e3,192e3,384e3],xg=[512,1024,2048,4096],Sg=e=>{let t=wg(e),n=rm(e),r=t?Math.ceil(t.frameSize/4)*4:0,i=null;for(;r+4<=e.length&&n.getUint32(r)===1683496997;){let t=Tg(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}},Cg=e=>{let t=Sg(e);return t?.core?t.hasExtensions?`dtsh`:`dtsc`:null},wg=e=>{if(e.length<18||e[0]!==127||e[1]!==254||e[2]!==128||e[3]!==1)return null;let t=new ch(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%dg!==0)return null;let i=t.readBits(14)+1;if(i<96)return null;let a=t.readBits(6);if(a>=hg.length)return null;let o=fg[t.readBits(4)];if(o===0)return null;let s=pg[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=mg[t.readBits(3)];if(l===0)return null;let u=c!==0;return{frameSize:i,sampleRate:o,numberOfChannels:hg[a]+ +!!u,sampleCount:r*32,channelLayout:gg[a]|(u?_g:0),amode:a,lfePresent:u,bitRate:s,pcmResolution:l}},Tg=e=>{if(e.length<10||e[0]!==100||e[1]!==88||e[2]!==32||e[3]!==37)return null;let t=new ch(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=yg[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*Im(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=bg[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}}},Eg=e=>{if(e.length<20)return null;let t=rm(e),n=t.getUint32(0);if(n===0)return null;let r=new ch(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<hg.length&&(c=hg[o]+a):c=Og(s),{sampleRate:n,maxBitrate:t.getUint32(4),avgBitrate:t.getUint32(8),pcmSampleDepth:e[12],sampleCount:xg[i],channelLayout:s,numberOfChannels:c}},Dg=e=>{let t=/* @__PURE__ */ new Uint8Array(20),n=rm(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 ch(t);return i.seekToByte(13),i.writeBits(2,Math.max(xg.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},Og=e=>Im(e)+Im(e&vg),kg=[`avc`,`hevc`,`vp9`,`av1`,`vp8`,`prores`],Ag=[`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`],jg=[`aac`,`opus`,`mp3`,`vorbis`,`flac`,`ac3`,`eac3`,`dts`],Mg=[...jg,...Ag],Ng=[`webvtt`],Pg=[{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}],Fg=[{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}],Ig=`.01.01.01.01.00`,Lg=`.0.110.01.01.01.0`,Rg=[`ap4x`,`ap4h`,`apch`,`apcn`,`apcs`,`apco`],zg=[`dtsc`,`dtsh`,`dtsl`,`dtse`],Bg=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]},Vg=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}.${xm(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}.${xm(n.subarray(1,4))}`}if(t===`hevc`){let e,t,r,i,o,s;if(a)e=a.generalProfileSpace,t=a.generalProfileIdc,r=Cm(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=rm(n),c=a.getUint8(1);e=c>>6&3,t=c&31,r=Cm(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=Qp(Fg).level;for(let e of Fg)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(Ig)&&(u=u.slice(0,-15)),u}if(t===`av1`){if(!s){let t=e.width*e.height,n=Qp(Fg).level;for(let e of Fg)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?lm[r.primaries]:1,u=r?.transfer?dm[r.transfer]:1,d=r?.matrix?pm[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(Lg)&&(p=p.slice(0,-17)),p}if(t===`prores`)return c??`apch`;throw t!==null&&km(t),TypeError(`Unhandled codec '${t}'.`)},Hg=e=>{switch(e.codec){case`avc`:{let t=e.avcCodecInfo?.sequenceParameterSets[0];if(!t&&e.codecDescription&&(t=Ah(e.codecDescription)?.sequenceParameterSets[0]),t){let e=Mh(t);if(e)return{primaries:um[e.colourPrimaries],transfer:fm[e.transferCharacteristics],matrix:mm[e.matrixCoefficients],fullRange:!!e.fullRangeFlag}}}break;case`hevc`:{let t=e.hevcCodecInfo?.arrays.find(e=>e.nalUnitType===xh.SPS_NUT)?.nalUnits[0];if(!t&&e.codecDescription&&(t=Kh(e.codecDescription)?.arrays.find(e=>e.nalUnitType===xh.SPS_NUT)?.nalUnits[0]),t){let e=Ih(t);if(e)return{primaries:um[e.colourPrimaries],transfer:fm[e.transferCharacteristics],matrix:mm[e.matrixCoefficients],fullRange:!!e.fullRangeFlag}}}break;case`vp8`:break;case`vp9`:if(e.vp9CodecInfo)return{primaries:um[e.vp9CodecInfo.colourPrimaries],transfer:fm[e.vp9CodecInfo.transferCharacteristics],matrix:mm[e.vp9CodecInfo.matrixCoefficients],fullRange:!!e.vp9CodecInfo.videoFullRangeFlag};break;case`av1`:if(e.av1CodecInfo)return{primaries:um[e.av1CodecInfo.colourPrimaries],transfer:fm[e.av1CodecInfo.transferCharacteristics],matrix:mm[e.av1CodecInfo.matrixCoefficients],fullRange:!!e.av1CodecInfo.videoFullRangeFlag};break;case`prores`:if(e.proresCodecInfo)return{primaries:um[e.proresCodecInfo.colourPrimaries],transfer:fm[e.proresCodecInfo.transferCharacteristics],matrix:mm[e.proresCodecInfo.matrixCoefficients],fullRange:e.proresCodecInfo.fullRange}}return{primaries:void 0,transfer:void 0,matrix:void 0,fullRange:void 0}},Ug=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?dh(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&&Ag.includes(t))return t;throw TypeError(`Unhandled codec '${t}'.`)},Wg=48e3,Gg=/^pcm-([usf])(\d+)(be)?$/,Kg=e=>{if(z(Ag.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=Gg.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}},qg=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`:Rg.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`:zg.includes(e)?`dts`:e===`ulaw`?`ulaw`:e===`alaw`?`alaw`:Gg.test(e)?e:e===`webvtt`?`webvtt`:null,Jg=[`avc1`,`avc3`,`hev1`,`hvc1`,`vp8`,`vp09`,`av01`,...Rg],Yg=/^(avc1|avc3)\.[0-9a-fA-F]{6}$/,Xg=/^(hev1|hvc1)\.(?:[ABC]?\d+)\.[0-9a-fA-F]{1,8}\.[LH]\d+(?:\.[0-9a-fA-F]{1,2}){0,6}$/,Zg=/^vp09(?:\.\d{2}){3}(?:(?:\.\d{2}){5})?$/,Qg=/^av01\.\d\.\d{2}[MH]\.\d{2}(?:\.\d\.\d{3}\.\d{2}\.\d{2}\.\d{2}\.\d)?$/,$g=(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(!Jg.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&&!vm(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(lm);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(dm);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(pm);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(!Yg.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(!Xg.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(!Zg.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(!Qg.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(Rg.some(t=>e.decoderConfig.codec.startsWith(t))&&!Rg.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: ${Rg.join(`, `)}.`);if(t!==null&&qg(e.decoderConfig.codec)!==t)throw TypeError(`Video chunk metadata decoder configuration codec string '${e.decoderConfig.codec}' does not fit to the track codec '${t}'.`)},e_=[`mp4a`,`mp3`,`opus`,`vorbis`,`flac`,`ulaw`,`alaw`,`pcm`,`ac-3`,`ec-3`,`dts`],t_=(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(!e_.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&&!vm(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(!zg.includes(e.decoderConfig.codec))throw TypeError(`Audio chunk metadata decoder configuration codec string for DTS must be one of the following four-character codes: ${zg.join(`, `)}.`)}else if((e.decoderConfig.codec.startsWith(`pcm`)||e.decoderConfig.codec.startsWith(`ulaw`)||e.decoderConfig.codec.startsWith(`alaw`))&&!Ag.includes(e.decoderConfig.codec))throw TypeError(`Audio chunk metadata decoder configuration codec string for PCM must be one of the supported PCM codecs (${Ag.join(`, `)}).`);if(t!==null&&qg(e.decoderConfig.codec)!==t)throw TypeError(`Audio chunk metadata decoder configuration codec string '${e.decoderConfig.codec}' does not fit to the track codec '${t}'.`)},n_=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.`)},r_=class{constructor(e){this.input=e}dispose(){}},i_=/* #__PURE__ */ new Uint8Array,a_=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===i_&&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===i_}get microsecondTimestamp(){return Math.trunc(zm*this.timestamp)}get microsecondDuration(){return Math.trunc(zm*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)}},o_=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},s_=e=>{let t=rm(e),n=0,r=t.getUint8(n);n+=1,n+=3;let i=xm(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(xm(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)}},c_=(e,t)=>e.systemId===t.systemId&&Km(e.data,t.data),l_=e=>{let t=H(e),n=Lv(e,4),r=8;t===1&&(t=Pv(e),r=16);let i=t-r;return i<0?null:{name:n,totalSize:t,headerSize:r,contentSize:i}},u_=e=>Nv(e)/65536,d_=e=>Nv(e)/1073741824,f_=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},p_=e=>{let t=Av(e);return e.skip(2),t=Math.min(t,e.remainingLength),om.decode(kv(e,t))},m_=e=>{let t=l_(e);if(!t||t.name!==`data`||e.remainingLength<8)return null;let n=H(e);e.skip(4);let r=kv(e,t.contentSize-8);switch(n){case 1:return om.decode(r);case 2:return new am(`utf-16be`).decode(r);case 13:return new rh(r,`image/jpeg`);case 14:return new rh(r,`image/png`);case 27:return new rh(r,`image/bmp`);default:return r}},h_=/* @__PURE__ */ new Uint32Array(256),g_=/* @__PURE__ */ new Uint32Array(256),__=/* @__PURE__ */ new Uint32Array(256),v_=/* @__PURE__ */ new Uint32Array(256),y_=/* @__PURE__ */ new Uint32Array(256),b_=/* @__PURE__ */ new Uint32Array(256),x_=/* @__PURE__ */ new Uint32Array(10),S_=!1,C_=()=>{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);h_[t]=n<<24|n<<16|n<<8|n,b_[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;g_[t]=l,__[t]=l>>>8|l<<24,v_[t]=l>>>16|l<<16,y_[t]=l>>>24|l<<8}let i=1;for(let e=0;e<10;e++)x_[e]=i<<24,i=i<<1^(i&128?283:0);S_=!0},w_=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),S_||C_();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]^h_[t>>>16&255]&4278190080^h_[t>>>8&255]&16711680^h_[t>>>0&255]&65280^h_[t>>>24&255]&255^x_[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]=g_[h_[n>>>24&255]&255]^__[h_[n>>>16&255]&255]^v_[h_[n>>>8&255]&255]^y_[h_[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=g_[e>>>24]^__[r>>>16&255]^v_[n>>>8&255]^y_[t&255]^this.roundkey[a],l=g_[t>>>24]^__[e>>>16&255]^v_[r>>>8&255]^y_[n&255]^this.roundkey[a+1],u=g_[n>>>24]^__[t>>>16&255]^v_[e>>>8&255]^y_[r&255]^this.roundkey[a+2],d=g_[r>>>24]^__[n>>>16&255]^v_[t>>>8&255]^y_[e&255]^this.roundkey[a+3],e=c,t=l,n=u,r=d}let f=b_[e>>>24&255]&4278190080^b_[r>>>16&255]&16711680^b_[n>>>8&255]&65280^b_[t>>>0&255]&255^this.roundkey[40],p=b_[t>>>24&255]&4278190080^b_[e>>>16&255]&16711680^b_[r>>>8&255]&65280^b_[n>>>0&255]&255^this.roundkey[41],m=b_[n>>>24&255]&4278190080^b_[t>>>16&255]&16711680^b_[e>>>8&255]&65280^b_[r>>>0&255]&255^this.roundkey[42],h=b_[r>>>24&255]&4278190080^b_[n>>>16&255]&16711680^b_[t>>>8&255]&65280^b_[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}},T_=class e extends r_{constructor(e){super(e),this.moovSlice=null,this.currentTrack=null,this.tracks=[],this.metadataPromise=null,this.movieTimescale=-1,this.movieDurationInTimescale=-1,this.movieMatrix=Wp,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 o_({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(Wm(r)&&(r=await r),!r)break;let i=e,a=l_(r);if(!a)break;if(a.name===`ftyp`||a.name===`styp`){let e=Lv(r,4);this.isQuickTime=e===`qt `}else if(a.name===`moov`){let e=this.reader.requestSlice(r.filePos,a.contentSize);if(Wm(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);Wm(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(Wm(e)&&(e=await e),e){let t=l_(e);if(t&&t.name===`mfra`){let n=this.reader.requestSlice(e.filePos,t.contentSize);Wm(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 D_(t),this.tracks.push(t)):t.info.type===`audio`&&t.info.numberOfChannels!==-1&&(t.trackBacking=new O_(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&&Ag.includes(e.info.codec)&&t.sampleCompositionTimeOffsets.length===0){z(e.info?.type===`audio`);let n=Kg(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=Tm(t.sampleTimingEntries,s,e=>e.startIndex),u=t.sampleTimingEntries[l],d=Tm(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=Qp(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);Wm(t)&&(t=await t),z(t);let n=l_(t);z(n?.name===`moof`);let r=this.reader.requestSlice(e,n.totalSize);Wm(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)N_(e,r.timestamp);else{let t=Tm(n,i.moofOffset-1,e=>e.moofOffset);if(t!==-1){let r=n[t];N_(e,r.endTimestamp)}}e.startTimestampIsFinal=!0}let r=Tm(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 L_(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=l_(e);if(!n)break;yield{boxInfo:n,slice:e},e.filePos=t+n.totalSize}}traverseBox(e){let t=e.filePos,n=l_(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=Pv(e)):(e.skip(8),this.movieTimescale=H(e),this.movieDurationInTimescale=H(e)),e.skip(16),this.movieMatrix=P_(e)}break;case`trak`:{let t={id:-1,demuxer:this,trackBacking:null,disposition:{...oh,primary:!1},info:null,timescale:-1,durationInMovieTimescale:-1,durationInMediaTimescale:-1,matrix:Wp,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 D_(t),this.tracks.push(t)):t.info.type===`audio`&&t.info.numberOfChannels!==-1&&(t.trackBacking=new O_(t),this.tracks.push(t))),this.currentTrack=null}break;case`tkhd`:{let t=this.currentTrack;if(!t)break;let n=V(e),r=!!(jv(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=Pv(e);else throw Error(`Incorrect track header version ${n}.`);e.skip(16),t.matrix=Zp(P_(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?Pv(e):H(e),o=n===1?Fv(e):Nv(e),s=u_(e);if(r){nh._warn(`Unsupported edit list: multiple edits are not currently supported. Only using first edit.`);break}if(o===-1){i+=a;continue}if(s!==1){nh._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=Pv(e));let r=Av(e);if(r>0){t.languageCode=``;for(let e=0;e<3;e++)t.languageCode=String.fromCharCode(96+(r&31))+t.languageCode,r>>=5;Rm(t.languageCode)||(t.languageCode=`und`)}}break;case`hdlr`:{let t=this.currentTrack;if(!t)break;e.skip(8);let n=Lv(e,4);n===`vide`?t.info={type:`video`,width:-1,height:-1,squarePixelWidth:-1,squarePixelHeight:-1,codec:null,codecDescription:null,colorSpace:{..._m},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=l_(e);if(!i)break;t.internalCodecId=i.name;let a=i.name.toLowerCase();if(t.info.type===`video`){e.skip(24),t.info.width=Av(e),t.info.height=Av(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`:Rg.includes(a)?(t.info.codec=`prores`,t.info.proresFormat=a):n===null?nh._warn(`Unknown encrypted video codec due to missing frma box.`):nh._warn(`Unsupported video codec (sample entry type '${i.name}').`)}else{e.skip(8);let o=Av(e);e.skip(6);let s=Av(e),c=Av(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=Iv(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=Wg;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(zg.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`:(nh._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`:(nh._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`:(nh._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`:(nh._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`:(nh._warn(`Invalid fpcm sample size ${e}.`),t.info.codec=null):e===32?t.info.codec=`pcm-f32be`:e===64?t.info.codec=`pcm-f64be`:(nh._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&&nh._warn(`Unsupported PCM format.`)}else d===null?nh._warn(`Unknown encrypted audio codec due to missing frma box.`):nh._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=Lv(e,4).toLowerCase()}break;case`schm`:{let t=this.currentTrack;if(!t)break;e.skip(4);let n=Lv(e,4);n===`cenc`||n===`cens`||n===`cbcs`?t.encryptionInfo={scheme:n,defaultKid:null,defaultIsProtected:null,defaultPerSampleIvSize:null,defaultConstantIv:null,defaultCryptByteBlock:null,defaultSkipByteBlock:null}:nh._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=xm(kv(e,16)),t.encryptionInfo.defaultIsProtected&&t.encryptionInfo.defaultPerSampleIvSize===0){let n=V(e),r=/* @__PURE__ */ new Uint8Array(16);r.set(kv(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=kv(e,n.contentSize)}break;case`hvcC`:{let t=this.currentTrack;if(!t||(z(t.info),n.contentSize===0))break;t.info.codecDescription=kv(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=Qh(kv(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=Lv(e,4);if(n!==`nclx`&&n!==`nclc`)break;let r=Av(e),i=Av(e),a=Av(e),o;n===`nclx`&&(o=!!(V(e)&128)),t.info.colorSpace={primaries:um[r],transfer:fm[i],matrix:mm[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),f_(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=f_(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`:nh._warn(`Unsupported audio codec (objectTypeIndication ${c}) - discarding track.`),e.skip(12),o>e.filePos-s){z(V(e)===5);let n=f_(e);if(t.info.codecDescription=kv(e,n),t.info.codec===`aac`){let e=dh(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=!!(Av(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=Av(e),i=H(e),a=Mv(e),o=V(e),s;s=o===0?/* @__PURE__ */ new Uint8Array:kv(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=jv(e);if((n&127)===rg.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=kv(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 ch(kv(e,3)),r=n.readBits(2);n.skipBits(8);let i=n.readBits(3),a=n.readBits(1);r<3&&(t.info.sampleRate=vh[r]),t.info.numberOfChannels=ig[i]+a}break;case`dec3`:{let t=this.currentTrack;if(!t)break;z(t.info?.type===`audio`);let r=cg(kv(e,n.contentSize));if(!r){nh._warn(`Invalid dec3 box contents, ignoring.`);break}let i=lg(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=Eg(kv(e,Math.min(n.contentSize,20)));if(!r){nh._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=Nv(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 ch(kv(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=Pv(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?Pv(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,Av,jv,H],l=c[a],u=c[o],d=c[s],f=H(e);for(let n=0;n<f;n++){let n=t===1?Pv(e):H(e),i=t===1?Pv(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[Qp(e.presentationTimestamps).sampleIndex];e.startTimestamp=t.presentationTimestamp,e.endTimestamp=n.presentationTimestamp+n.duration;let{currentFragmentState:r}=this.currentTrack;z(r),r.startTimestamp!==null&&(N_(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=s_(kv(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=jv(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=Pv(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):Pv(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=jv(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=Nv(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):Nv(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),jv(e)&1){let n=Lv(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=kv(e,r));let a=I_(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(jv(e)&1){let n=Lv(e,4),r=H(e);if(n!==t.encryptionInfo.scheme||r!==0)break}let r=H(e);if(r===0)break;r>1&&nh._warn(`Multiple saio entries are not supported; using the first offset only.`);let i=n===0?H(e):Number(Pv(e));this.currentFragment&&(i+=this.currentFragment.moofOffset);let a=I_(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=!!(jv(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(kv(e,a),0):i.set(t.encryptionInfo.defaultConstantIv,0);let s=null;if(r){let t=Av(e);s=[];for(let n=0;n<t;n++){let t=Av(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]??=p_(n):this.metadataTags.raw[e.name]??=kv(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=om.decode(kv(n,e.contentSize)):this.metadataTags.title??=p_(n);break;case`©des`:this.currentTrack||(this.metadataTags.description??=p_(n));break;case`©ART`:this.currentTrack||(this.metadataTags.artist??=p_(n));break;case`©alb`:this.currentTrack||(this.metadataTags.album??=p_(n));break;case`albr`:this.currentTrack||(this.metadataTags.albumArtist??=p_(n));break;case`©gen`:this.currentTrack||(this.metadataTags.genre??=p_(n));break;case`©day`:if(!this.currentTrack){let e=new Date(p_(n));Number.isNaN(e.getTime())||(this.metadataTags.date??=e)}break;case`©cmt`:this.currentTrack||(this.metadataTags.comment??=p_(n));break;case`©lyr`:this.currentTrack||(this.metadataTags.lyrics??=p_(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=om.decode(kv(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=m_(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 rh?(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=rm(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=rm(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}},E_=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 Nm(e*this.internalTrack.timescale)+this.internalTrack.editListOffset}async getPacket(e,t){let n=this.mapTimestampIntoTimescale(e),r=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),i=k_(r,n),a=await this.fetchPacketForSampleIndex(i,t);return!F_(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=Tm(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=A_(r,n),a=await this.fetchPacketForSampleIndex(i,t);return!F_(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=Om(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=M_(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=j_(this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),e);if(!n)return null;let r;if(t.metadataOnly)r=i_;else{let t=this.internalTrack.demuxer.reader.requestSlice(n.sampleOffset,n.sampleSize);if(Wm(t)&&(t=await t),!t)return null;if(r=kv(t,n.sampleSize),this.internalTrack.encryptionInfo){let t=null;if(this.internalTrack.encryptionAuxInfo){let n=await L_(this.internalTrack.demuxer.reader,this.internalTrack.encryptionInfo,this.internalTrack.encryptionAuxInfo);e<n.length&&(t=n[e])}t??=R_(this.internalTrack.encryptionInfo),t&&(r=await z_(this.internalTrack,t,r,null))}}let i=(n.presentationTimestamp-this.internalTrack.editListOffset)/this.internalTrack.timescale,a=n.duration/this.internalTrack.timescale,o=new a_(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=i_;else{let t=this.internalTrack.demuxer.reader.requestSlice(r.byteOffset,r.byteSize);if(Wm(t)&&(t=await t),!t)return null;if(i=kv(t,r.byteSize),this.internalTrack.encryptionInfo){let t=r.encryption??R_(this.internalTrack.encryptionInfo);t&&(i=await z_(this.internalTrack,t,i,e))}}let a=(r.presentationTimestamp-this.internalTrack.editListOffset)/this.internalTrack.timescale,o=r.duration/this.internalTrack.timescale,s=new a_(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=Tm(this.internalTrack.fragmentLookupTable,n,e=>e.timestamp),u=l===-1?null:this.internalTrack.fragmentLookupTable[l],d=Tm(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(Wm(e)&&(e=await e),!e)break;let n=m,l=l_(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}},D_=class extends E_{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&&Oh(e.data)}else if(this.internalTrack.info.codec===`hevc`&&!this.internalTrack.info.codecDescription){let e=await this.getFirstPacket({});this.internalTrack.info.hevcCodecInfo=e&&Lh(e.data)}else if(this.internalTrack.info.codec===`vp9`&&(!this.internalTrack.info.vp9CodecInfo||!Xh(this.internalTrack.info.vp9CodecInfo))){let e=await this.getFirstPacket({}),t=e&&Yh(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||!$h(this.internalTrack.info.av1CodecInfo))){let e=await this.getFirstPacket({}),t=e&&Qh(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&&eg(e.data)}if(!hm(this.internalTrack.info.colorSpace)){let e=Hg(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:Vg(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}},O_=class extends E_{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&&Cg(e.data)}return{codec:Ug(this.internalTrack.info),numberOfChannels:this.internalTrack.info.numberOfChannels,sampleRate:this.internalTrack.info.sampleRate,description:this.internalTrack.info.codecDescription??void 0}})():null}},k_=(e,t)=>{if(e.presentationTimestamps){let n=Tm(e.presentationTimestamps,t,e=>e.presentationTimestamp);return n===-1?-1:e.presentationTimestamps[n].sampleIndex}{let n=Tm(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)}},A_=(e,t)=>{if(!e.keySampleIndices)return k_(e,t);if(e.presentationTimestamps){let n=Tm(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(wm(e.keySampleIndices,n,e=>e)!==-1)return n}return-1}{let n=k_(e,t),r=Tm(e.keySampleIndices,n,e=>e);return e.keySampleIndices[r]??-1}},j_=(e,t)=>{let n=Tm(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=Tm(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=Tm(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||wm(e.keySampleIndices,t,e=>e)!==-1}},M_=(e,t)=>{if(!e.keySampleIndices)return t+1;let n=Tm(e.keySampleIndices,t,e=>e);return e.keySampleIndices[n+1]??-1},N_=(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},P_=e=>[u_(e),u_(e),d_(e),u_(e),u_(e),d_(e),u_(e),u_(e),d_(e)],F_=e=>e.sampleSizes.length===0,I_=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},L_=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(Wm(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(kv(i,a),0):s.set(t.defaultConstantIv,0);let c=null;if(r>a){let e=Av(i);c=[];for(let t=0;t<e;t++){let e=Av(i),t=H(i);c.push({clearLen:e,protectedLen:t})}}o.push({iv:s,subsamples:c})}return n.resolved=o,o},R_=e=>e.defaultConstantIv?{iv:e.defaultConstantIv,subsamples:null}:null,z_=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++)c_(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&&bm.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:Sm(n)})();e.demuxer.decryptionKeyCache.set(a,t),o=await t}return i.scheme===`cenc`||i.scheme===`cens`?B_(o,i,t,n):V_(o,i,t,n)},B_=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=H_(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},V_=(e,t,n,r)=>{let i=new w_;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=H_(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},H_=(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},U_=e=>{let t=e.filePos,n=new ch(kv(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={}})))(),qm();var W_=1/0;typeof FinalizationRegistry<`u`&&new FinalizationRegistry(e=>{e()});var G_=class extends $m{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 Tv;return this._sizePromise??=(async()=>{let e=this._getFileSize();return e===void 0?(await this._read(0,1,0,W_),e=this._getFileSize(),z(e!==void 0),e):e})()}async getSize(){if(this._disposed)throw new Tv;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 X_(this,e,t)}_dispatchRead(e,t){this.onread?.(e,t),this._emit(`read`,{start:e,end:t})}ref(){return new K_(this)}_incrementRefCount(){this._refCount++}_decrementRefCount(){this._refCount--,this._refCount===0&&(this._dispose(),this._disposed=!0)}},K_=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()}},q_=class extends G_{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 G_||e instanceof K_))throw TypeError(`requestHandler must return or resolve to a Source or SourceRef.`);let t=e instanceof G_?e.ref():e;return t.source._usedForHls||=this._usedForHls,t};return Wm(t)?t.then(n):n(t)}},J_=(e,t)=>e.path===t.path,Y_=class extends G_{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=nm(e),this._view=rm(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 X_=class extends G_{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:Mm(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 Wm(i)?i.then(a):a(i)}_dispose(){this._ref?.free()}ref(){return this._ref??=this._baseSource.ref(),super.ref()}},Z_=class{constructor(){this._isIsobmff=!1}},Q_=class extends Z_{constructor(){super(...arguments),this._isIsobmff=!0}async _getMajorBrand(e){let t=e._reader.requestSlice(0,12);if(Wm(t)&&(t=await t),!t)return null;t.skip(4);let n=Lv(t,4);return n!==`ftyp`&&n!==`styp`?null:Lv(t,4)}_createDemuxer(e){return new T_(e)}},$_=class extends Q_{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(Wm(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(Wm(t)&&(t=await t),!t)return!1;r=Pv(t),i=16}if(r<i)return!1;let a=Lv(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`}},ev=class extends Q_{async _canReadInput(e){return await this._getMajorBrand(e)===`qt `}get name(){return`QuickTime File Format`}get mimeType(){return`video/quicktime`}},tv=/* #__PURE__ */ new $_,nv=/* #__PURE__ */ new ev,rv=(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.`)}},iv=[],av=[],ov=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.`)},sv=e=>{if(!Jm(e))throw TypeError(`timestamp must be a number.`)},cv=(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,lv=class{constructor(e){if(!(e instanceof uv))throw TypeError(`track must be an InputTrack.`);this._track=e}async getFirstPacket(e={}){if(ov(e),this._track.input._disposed)throw new Tv;return cv(this._track,this._track._backing.getFirstPacket(e),e)}async getFirstKeyPacket(e={}){ov(e);let t=await this.getFirstPacket(e);return t?t.type===`key`?t:this.getNextKeyPacket(t,e):null}async getPacket(e,t={}){if(sv(e),ov(t),this._track.input._disposed)throw new Tv;return cv(this._track,this._track._backing.getPacket(e,t),t)}async getNextPacket(e,t={}){if(!(e instanceof a_))throw TypeError(`packet must be an EncodedPacket.`);if(ov(t),this._track.input._disposed)throw new Tv;return cv(this._track,this._track._backing.getNextPacket(e,t),t)}async getKeyPacket(e,t={}){if(sv(e),ov(t),this._track.input._disposed)throw new Tv;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 a_))throw TypeError(`packet must be an EncodedPacket.`);if(ov(t),this._track.input._disposed)throw new Tv;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 a_))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 a_))throw TypeError(`endPacket must be an EncodedPacket.`);if(ov(n),this._track.input._disposed)throw new Tv;let r=[],{promise:i,resolve:a}=Em(),{promise:o,resolve:s}=Em(),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}=Em()),await o;continue}r.push(u),a(),{promise:i,resolve:a}=Em(),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 Tv;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 pv}isAudioTrack(){return this instanceof mv}get id(){return this._backing.getId()}get number(){return this._backing.getNumber()}async getInternalCodecId(){return this._backing.getInternalCodecId()}get internalCodecId(){return dv(this._backing.getInternalCodecId(),`internalCodecId`,`getInternalCodecId`)}async getLanguageCode(){return this._backing.getLanguageCode()}get languageCode(){return dv(this._backing.getLanguageCode(),`languageCode`,`getLanguageCode`)}async getName(){return this._backing.getName()}get name(){return dv(this._backing.getName(),`name`,`getName`)}async getTimeResolution(){return this._backing.getTimeResolution()}get timeResolution(){return dv(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 dv(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 Fm((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 lv(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(vv({filter:e=>e.canBePairedWith(this)},e))}async getPairableVideoTracks(e){return this.input.getVideoTracks(vv({filter:e=>e.canBePairedWith(this)},e))}async getPairableAudioTracks(e){return this.input.getAudioTracks(vv({filter:e=>e.canBePairedWith(this)},e))}async getPrimaryPairableVideoTrack(e){return this.input.getPrimaryVideoTrack(vv({filter:e=>e.canBePairedWith(this)},e))}async getPrimaryPairableAudioTrack(e){return this.input.getPrimaryAudioTrack(vv({filter:e=>e.canBePairedWith(this)},e))}async hasPairableTrack(e){e&&=fv(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&&=fv(e),this.hasPairableTrack(async t=>t.isVideoTrack()&&(!e||await e(t)))}hasPairableAudioTrack(e){return e&&=fv(e),this.hasPairableTrack(async t=>t.isAudioTrack()&&(!e||await e(t)))}},dv=(e,t,n)=>{if(Wm(e))throw Error(`'${t}' is deprecated and not available synchronously for this track. Use the preferred '${n}()' instead.`);return e},fv=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 Wm(r)?r.then(n):n(r)}:void 0},pv=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 dv(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 dv(this._backing.getCodedWidth(),`codedWidth`,`getCodedWidth`)}async getCodedHeight(){return this._backing.getCodedHeight()}get codedHeight(){return dv(this._backing.getCodedHeight(),`codedHeight`,`getCodedHeight`)}async getTransformationMatrix(){return this._backing.getTransformationMatrix()}async getRotation(){return Kp(await this._backing.getTransformationMatrix())}get rotation(){return Kp(dv(this._backing.getTransformationMatrix(),`rotation`,`getRotation`))}async getFlip(){return qp(await this._backing.getTransformationMatrix())}async getSquarePixelWidth(){return this._backing.getSquarePixelWidth()}get squarePixelWidth(){return dv(this._backing.getSquarePixelWidth(),`squarePixelWidth`,`getSquarePixelWidth`)}async getSquarePixelHeight(){return this._backing.getSquarePixelHeight()}get squarePixelHeight(){return dv(this._backing.getSquarePixelHeight(),`squarePixelHeight`,`getSquarePixelHeight`)}async getPixelAspectRatio(){return this._pixelAspectRatioCache??=Zm({num:await this.getSquarePixelWidth()*await this.getCodedHeight(),den:await this.getSquarePixelHeight()*await this.getCodedWidth()})}get pixelAspectRatio(){return this._pixelAspectRatioCache??=Zm({num:dv(this._backing.getSquarePixelWidth(),`pixelAspectRatio`,`getPixelAspectRatio`)*dv(this._backing.getCodedHeight(),`pixelAspectRatio`,`getPixelAspectRatio`),den:dv(this._backing.getSquarePixelHeight(),`pixelAspectRatio`,`getPixelAspectRatio`)*dv(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=dv(e,`displayWidth`,`getDisplayWidth`);if(t!==null)return t}return dv(Kp(dv(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=dv(e,`displayHeight`,`getDisplayHeight`);if(t!==null)return t}return dv(Kp(dv(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),iv.some(n=>n.supports(t,e))?!0:typeof VideoDecoder>`u`?!1:(await VideoDecoder.isConfigSupported(e)).supported===!0}catch(e){return nh._error(`Error during decodability check:`,e),!1}}async determinePacketType(e){if(!(e instanceof a_))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),ng(t,n,e.data)}async computeFrameRateMetrics(e={}){if(!e||typeof e!=`object`)throw TypeError(`options must be an object.`);if(e.targetPacketCount!==void 0&&(!Jm(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 lv(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=bv(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?Sv(w):u,minFrameRate:d/h,maxFrameRate:d/m,averageFrameRate:d*_/g,medianFrameRate:w,frameRateIsConstant:u!==null&&m===1&&h===1,probedPacketCount:o}}},mv=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 dv(this._backing.getCodec(),`codec`,`getCodec`)}async hasOnlyKeyPackets(){return await this._backing.getHasOnlyKeyPackets?.()??!0}async getNumberOfChannels(){return this._backing.getNumberOfChannels()}get numberOfChannels(){return dv(this._backing.getNumberOfChannels(),`numberOfChannels`,`getNumberOfChannels`)}async getSampleRate(){return this._backing.getSampleRate()}get sampleRate(){return dv(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),av.some(n=>n.supports(t,e))||e.codec.startsWith(`pcm-`)?!0:typeof AudioDecoder>`u`?!1:(await AudioDecoder.isConfigSupported(e)).supported===!0}catch(e){return nh._error(`Error during decodability check:`,e),!1}}async determinePacketType(e){if(!(e instanceof a_))throw TypeError(`packet must be an EncodedPacket.`);return await this.getCodec()===null?null:`key`}},hv=e=>-(e??-1/0),gv=e=>-e,_v=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 Wm(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 Wm(r)?r.then(n):n(r)}:void 0}},vv=(e,t)=>({filter:e?.filter||t?.filter?n=>{let r=e?.filter?.(n)??!0,i=e=>e===!1?!1:t?.filter?.(n)??!0;return Wm(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 Wm(r)||Wm(i)?Promise.all([r,i]).then(([e,t])=>a(e,t)):a(r,i)}:void 0}),yv=async(e,t)=>{let n=e;if(t?.filter){let r=e.map(e=>t.filter(e));if(r.some(e=>Wm(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=>Wm(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)},bv=(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=xv(p,m,n),r=xv(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},xv=(e,t,n)=>{for(let r=1;r<=n;r++){let n=Math.floor(e*r)+1;if(n/r<t)return Zm({num:n,den:r})}return null},Sv=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};qm();var Cv=class e extends $m{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 Z_)))throw TypeError(`options.formats must be an array of InputFormat.`);if(!(t.source instanceof G_||t.source instanceof K_))throw TypeError(`options.source must be a Source or SourceRef.`);if(t.source instanceof G_&&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&&rv(t.formatOptions,`formatOptions`),this._formats=t.formats,this._initInput=t.initInput??null,this._formatOptions=t.formatOptions??{},this._rootRef=t.source instanceof G_?t.source.ref():t.source,this._sourceRefs.push(this._rootRef)}get _rootSource(){return this._rootRef.source}async _getSourceUncached(e){z(this._rootSource instanceof q_);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&&J_(n.request,e));if(n)return n.age++,Promise.resolve(n.sourceRef.source.ref());let r=this._sourceCachePromises.find(n=>n.cacheGroup===t&&J_(n.request,e));if(r)return r.promise.then(e=>e.sourceRef.source.ref());let i=(async()=>{let n=await this._getSourceUncached(e);if(Ym(this._sourceCache,e=>e.cacheGroup===t&&e.sourceRef.source._refCount===1)>=4){let e=Xm(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(),Dm(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 Ev(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 wv})()}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 wv)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&&=_v(e),yv((await this._getTrackBackings()).map(e=>this._wrapBackingAsTrack(e)),e)}async getVideoTracks(e){return e&&=_v(e),yv((await this.getTracks()).filter(e=>e.isVideoTrack()),e)}async getAudioTracks(e){return e&&=_v(e),yv((await this.getTracks()).filter(e=>e.isAudioTrack()),e)}async getPrimaryVideoTrack(e){e&&=_v(e);let t=vv(e,{sortBy:async e=>[gv((await e.getDisposition()).default),gv(await e.hasPairableAudioTrack()),gv(!await e.hasOnlyKeyPackets()),hv(await e.getBitrate())]});return(await this.getVideoTracks(t))[0]??null}async getPrimaryAudioTrack(e){e&&=_v(e);let t=await this.getPrimaryVideoTrack(),n=vv(e,{sortBy:async e=>[gv(!t||e.canBePairedWith(t)),gv((await e.getDisposition()).default),hv(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 pv(this,e):new mv(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()}},wv=class extends Error{constructor(e=`Input has an unsupported or unrecognizable format.`){super(e),this.name=`UnsupportedInputFormatError`}},Tv=class extends Error{constructor(e=`Input has been disposed.`){super(e),this.name=`InputDisposedError`}},Ev=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 Tv;if(e<0||this.fileSizeNonStrict!==null&&e+t>this.fileSizeNonStrict)return null;if(t===0){let t=/* @__PURE__ */ new Uint8Array;return new Dv(t,rm(t),0,e,e)}let n=e+t,r=this.source._read(e,n,0,W_);return Wm(r)?r.then(t=>t?new Dv(t.bytes,t.view,t.offset,e,n):null):r?new Dv(r.bytes,r.view,r.offset,e,n):null}requestSliceRange(e,t,n){if(this.source._disposed)throw new Tv;if(e<0)return null;if(this.fileSizeNonStrict!==null)return this.requestSlice(e,Mm(this.fileSizeNonStrict-e,t,n));{let r=this.requestSlice(e,n),i=r=>r||(z(this.fileSizeNonStrict!==null),this.requestSlice(e,Mm(this.fileSizeNonStrict-e,t,n)));return Wm(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(Wm(n)&&(n=await n),!n||n.length===0)break;let r=kv(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 Dv(n,rm(n),0,0,t)})():this.requestSlice(0,this.fileSizeNonStrict)}},Dv=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,rm(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)}},Ov=(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.`)},kv=(e,t)=>{Ov(e,t);let n=e.bytes.subarray(e.bufferPos,e.bufferPos+t);return e.bufferPos+=t,n},V=e=>(Ov(e,1),e.view.getUint8(e.bufferPos++)),Av=e=>{Ov(e,2);let t=e.view.getUint16(e.bufferPos,!1);return e.bufferPos+=2,t},jv=e=>{Ov(e,3);let t=Am(e.view,e.bufferPos,!1);return e.bufferPos+=3,t},Mv=e=>{Ov(e,2);let t=e.view.getInt16(e.bufferPos,!1);return e.bufferPos+=2,t},H=e=>{Ov(e,4);let t=e.view.getUint32(e.bufferPos,!1);return e.bufferPos+=4,t},Nv=e=>{Ov(e,4);let t=e.view.getInt32(e.bufferPos,!1);return e.bufferPos+=4,t},Pv=e=>{let t=H(e),n=H(e);return t*4294967296+n},Fv=e=>{let t=Nv(e),n=H(e);return t*4294967296+n},Iv=e=>{Ov(e,8);let t=e.view.getFloat64(e.bufferPos,!1);return e.bufferPos+=8,t},Lv=(e,t)=>{Ov(e,t);let n=``;for(let r=0;r<t;r++)n+=String.fromCharCode(e.bytes[e.bufferPos++]);return n},Rv=class{constructor(e){this.mutex=new ym,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)}}},zv=/<(?:(\d{2}):)?(\d{2}):(\d{2}).(\d{3})>/g,Bv=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`)},Vv=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),Hv=/* #__PURE__ */ new DataView(U.buffer),Uv=e=>[(e%256+256)%256],W=e=>(Hv.setUint16(0,e,!1),[U[0],U[1]]),Wv=e=>(Hv.setInt16(0,e,!1),[U[0],U[1]]),Gv=e=>(Hv.setUint32(0,e,!1),[U[1],U[2],U[3]]),G=e=>(Hv.setUint32(0,e,!1),[U[0],U[1],U[2],U[3]]),Kv=e=>(Hv.setInt32(0,e,!1),[U[0],U[1],U[2],U[3]]),qv=e=>(Hv.setUint32(0,Math.floor(e/2**32),!1),Hv.setUint32(4,e,!1),[U[0],U[1],U[2],U[3],U[4],U[5],U[6],U[7]]),Jv=e=>(Hv.setInt32(0,Math.floor(e/2**32),!1),Hv.setUint32(4,e,!1),[U[0],U[1],U[2],U[3],U[4],U[5],U[6],U[7]]),Yv=e=>(Hv.setInt16(0,256*e,!1),[U[0],U[1]]),Xv=e=>(Hv.setInt32(0,2**16*e,!1),[U[0],U[1],U[2],U[3]]),Zv=e=>(Hv.setInt32(0,2**30*e,!1),[U[0],U[1],U[2],U[3]]),Qv=(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()},$v=(e,t=!1)=>{let n=Array(e.length).fill(null).map((t,n)=>e.charCodeAt(n));return t&&n.push(0),n},ey=e=>[Xv(e[0]),Xv(e[1]),Zv(e[2]),Xv(e[3]),Xv(e[4]),Zv(e[5]),Xv(e[6]),Xv(e[7]),Zv(e[8])],K=(e,t,n)=>({type:e,contents:t&&new Uint8Array(t.flat(10)),children:n}),ty=(e,t,n,r,i)=>K(e,[Uv(t),Gv(n),r??[]],i),ny=e=>e.isQuickTime?K(`ftyp`,[$v(`qt `),G(512),$v(`qt `)]):e.fragmented?e.cmaf?K(`ftyp`,[$v(`iso5`),G(512),$v(`iso5`),$v(`iso6`),$v(`mp41`),$v(`cmfc`),$v(`dash`)]):K(`ftyp`,[$v(`iso5`),G(512),$v(`iso5`),$v(`iso6`),$v(`mp41`)]):K(`ftyp`,[$v(`isom`),G(512),$v(`isom`),e.holdsAvc?$v(`avc1`):[],$v(`mp41`)]),ry=()=>K(`styp`,[$v(`iso5`),G(0),$v(`iso5`),$v(`iso6`),$v(`mp41`),$v(`cmfc`),$v(`dash`)]),iy=(e,t)=>{let n=Math.max(0,e.minWrittenTimestamp),r=Math.max(0,e.maxWrittenEndTimestamp-n);return Number.isFinite(r)||(r=0),ty(`sidx`,1,0,[G(1),G(Ib),qv(zb(n,Ib)),qv(0),W(0),W(1),G(t&2147483647),G(zb(r,Ib)),G(0)])},ay=e=>({type:`mdat`,largeSize:e}),oy=e=>({type:`free`,size:e}),sy=e=>K(`moov`,void 0,[cy(e.creationTime,e.trackDatas),...e.trackDatas.map(t=>ly(t,e.creationTime)),e.isFragmented?Qy(e.trackDatas):null,pb(e)]),cy=(e,t)=>{let n=Math.max(0,...t.map(e=>Math.max(0,zb(Bb(e),Ib)+zb(e.startTimestampOffset??0,Ib)))),r=Math.max(0,...t.map(e=>e.track.id))+1,i=!$p(e)||!$p(n),a=i?qv:G;return ty(`mvhd`,+i,0,[a(e),a(e),G(Ib),a(n),Xv(1),Yv(1),Array(10).fill(0),ey(Wp),Array(24).fill(0),G(r)])},ly=(e,t)=>{let n=Rb(e),r=e.startTimestampOffset!==null&&e.startTimestampOffset!==0;return K(`trak`,void 0,[uy(e,t),r?dy(e):null,fy(e,t),n.name===void 0?null:K(`udta`,void 0,[K(`name`,[...sm.encode(n.name)])])])},uy=(e,t)=>{let n=Math.max(0,zb(Bb(e),Ib)+zb(e.startTimestampOffset??0,Ib)),r=!$p(t)||!$p(n),i=r?qv: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=Gp(Zp(Jp(t??0),Xp(n?-1:1,1)),e.info.width,e.info.height)}else a=Wp;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:km(e);return ty(`tkhd`,+r,o,[i(t),i(t),G(e.track.id),G(0),i(n),Array(8).fill(0),W(0),W(s),Yv(+(e.type===`audio`)),W(0),ey(a),Xv(e.type===`video`?e.info.width:0),Xv(e.type===`video`?e.info.height:0)])},dy=e=>{let t=e.startTimestampOffset;if(z(t!==null),t>0){let n=zb(t,Ib),r=zb(Bb(e),Ib),i=!$p(n)||!$p(r),a=i?qv:G,o=i?Jv:Kv;return K(`edts`,void 0,[ty(`elst`,+!!i,0,[G(2),a(n),o(-1),Xv(1),a(r),o(0),Xv(1)])])}{let n=zb(-t,e.timescale),r=Math.max(0,zb(Bb(e),Ib)+zb(t,Ib)),i=!em(n)||!$p(r),a=i?qv:G,o=i?Jv:Kv;return K(`edts`,void 0,[ty(`elst`,+!!i,0,[G(1),a(r),o(n),Xv(1)])])}},fy=(e,t)=>K(`mdia`,void 0,[py(e,t),gy(!0,my[e.type],hy[e.type]),_y(e)]),py=(e,t)=>{let n=zb(Bb(e),e.timescale),r=!$p(t)||!$p(n),i=r?qv:G;return ty(`mdhd`,+r,0,[i(t),i(t),G(e.timescale),i(n),W(Db(e.track.metadata.languageCode??`und`)),W(0)])},my={video:`vide`,audio:`soun`,subtitle:`text`},hy={video:`MediabunnyVideoHandler`,audio:`MediabunnySoundHandler`,subtitle:`MediabunnyTextHandler`},gy=(e,t,n,r=`\0\0\0\0`)=>ty(`hdlr`,0,0,[e?$v(`mhlr`):G(0),$v(t),$v(r),G(0),G(0),$v(n,!0)]),_y=e=>K(`minf`,void 0,[vy[e.type](),yy(),Sy(e)]),vy={video:()=>ty(`vmhd`,0,1,[W(0),W(0),W(0),W(0)]),audio:()=>ty(`smhd`,0,0,[W(0),W(0)]),subtitle:()=>ty(`nmhd`,0,0)},yy=()=>K(`dinf`,void 0,[by()]),by=()=>ty(`dref`,0,0,[G(1)],[xy()]),xy=()=>ty(`url `,0,1),Sy=e=>{let t=e.compositionTimeOffsetTable.length>1||e.compositionTimeOffsetTable.some(e=>e.sampleCompositionTimeOffset!==0);return K(`stbl`,void 0,[Cy(e),Gy(e),t?Xy(e):null,t?Zy(e):null,qy(e),Jy(e),Yy(e),Ky(e)])},Cy=e=>{let t;if(e.type===`video`)t=wy(xb(e.track.source._codec,e.info.decoderConfig.codec),e);else if(e.type===`audio`){let n=Cb(e.track.source._codec,e.info.decoderConfig.codec,e.muxer.isQuickTime);z(n),t=My(n,e)}else e.type===`subtitle`&&(t=Uy(Tb[e.track.source._codec],e));return z(t),ty(`stsd`,0,0,[G(1)],[t])},wy=(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),Uv(10),$v(`Mediabunny`),Array(21).fill(0),W(t.info.hasAlphaChannel?32:24),Wv(65535)],[Sb[t.track.source._codec]?.(t)??null,Ey(t),gm(t.info.decoderConfig.colorSpace)?null:Dy(t),Ty(t)]),Ty=e=>e.avgBitrate===0&&e.maxBitrate===0?null:K(`btrt`,[G(0),G(e.maxBitrate),G(e.avgBitrate)]),Ey=e=>e.info.pixelAspectRatio.num===e.info.pixelAspectRatio.den?null:K(`pasp`,[G(e.info.pixelAspectRatio.num),G(e.info.pixelAspectRatio.den)]),Dy=e=>{let t=e.info.decoderConfig.colorSpace;return K(`colr`,[$v(e.muxer.isQuickTime?`nclc`:`nclx`),W(t?.primaries==null?2:lm[t.primaries]),W(t?.transfer==null?2:dm[t.transfer]),W(t?.matrix==null?2:pm[t.matrix]),e.muxer.isQuickTime?[]:Uv(!!t?.fullRange<<7)])},Oy=e=>e.info.decoderConfig&&K(`avcC`,[...nm(e.info.decoderConfig.description)]),ky=e=>e.info.decoderConfig&&K(`hvcC`,[...nm(e.info.decoderConfig.description)]),Ay=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?lm[t.colorSpace.primaries]:1,u=n[6]?Number(n[6]):t.colorSpace?.transfer?dm[t.colorSpace.transfer]:1,d=n[7]?Number(n[7]):t.colorSpace?.matrix?pm[t.colorSpace.matrix]:1;return ty(`vpcC`,1,0,[Uv(r),Uv(i),Uv(c),Uv(l),Uv(u),Uv(d),W(0)])},jy=e=>K(`av1C`,Bg(e.info.decoderConfig.codec)),My=(e,t)=>{let n=0,r,i=16,a=Ag.includes(t.track.source._codec);if(a){let e=t.track.source._codec,{sampleSize:r}=Kg(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)),Wv(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,[wb(t.track.source._codec,t.muxer.isQuickTime)?.(t)??null,Ty(t)])},Ny=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=[...Uv(t),...Uv(21),...Gv(0),...G(e.maxBitrate),...G(e.avgBitrate)];if(e.info.decoderConfig.description){let t=nm(e.info.decoderConfig.description);n=[...n,...Uv(5),...Qv(t.byteLength),...t]}return n=[...W(1),...Uv(0),...Uv(4),...Qv(n.length),...n,...Uv(6),...Uv(1),...Uv(2)],n=[...Uv(3),...Qv(n.length),...n],ty(`esds`,0,0,n)},Py=e=>K(`wave`,void 0,[Fy(e),Iy(e),K(`\0\0\0\0`)]),Fy=e=>K(`frma`,[$v(Cb(e.track.source._codec,e.info.decoderConfig.codec,e.muxer.isQuickTime))]),Iy=e=>{let{littleEndian:t}=Kg(e.track.source._codec);return K(`enda`,[W(+t)])},Ly=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=tg(nm(s));t=e.outputChannelCount,n=e.preSkip,r=e.inputSampleRate,i=e.outputGain,a=e.channelMappingFamily,e.channelMappingTable&&(o=e.channelMappingTable)}return K(`dOps`,[Uv(0),Uv(t),W(n),G(r),Wv(i),Uv(a),...o])},Ry=e=>{let t=e.info.decoderConfig?.description;return z(t),ty(`dfLa`,0,0,[...nm(t).subarray(4)])},zy=e=>{let{littleEndian:t,sampleSize:n}=Kg(e.track.source._codec);return ty(`pcmC`,0,0,[Uv(+t),Uv(8*n)])},By=e=>{z(e.info.primingPacket);let t=ag(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 ch(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])},Vy=e=>{z(e.info.primingPacket);let t=sg(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 ch(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])},Hy=e=>{z(e.info.primingPacket);let t=Sg(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`,[...Dg(t)])},Uy=(e,t)=>K(e,[[,,,,,,].fill(0),W(1)],[Eb[t.track.source._codec](t),Ty(t)]),Wy=e=>K(`vttC`,[...sm.encode(e.info.config.description)]),Gy=e=>ty(`stts`,0,0,[G(e.timeToSampleTable.length),e.timeToSampleTable.map(e=>[G(e.sampleCount),G(e.sampleDelta)])]),Ky=e=>{if(e.samples.every(e=>e.type===`key`))return null;let t=[...e.samples.entries()].filter(([,e])=>e.type===`key`);return ty(`stss`,0,0,[G(t.length),t.map(([e])=>G(e+1))])},qy=e=>ty(`stsc`,0,0,[G(e.compactlyCodedChunkTable.length),e.compactlyCodedChunkTable.map(e=>[G(e.firstChunk),G(e.samplesPerChunk),G(1)])]),Jy=e=>{if(e.type===`audio`&&e.info.requiresPcmTransformation){let{sampleSize:t}=Kg(e.track.source._codec);return ty(`stsz`,0,0,[G(t*e.info.numberOfChannels),G(e.samples.reduce((t,n)=>t+zb(n.duration,e.timescale),0))])}return ty(`stsz`,0,0,[G(0),G(e.samples.length),e.samples.map(e=>G(e.size))])},Yy=e=>e.finalizedChunks.length>0&&Qp(e.finalizedChunks).offset>=2**32?ty(`co64`,0,0,[G(e.finalizedChunks.length),e.finalizedChunks.map(e=>qv(e.offset))]):ty(`stco`,0,0,[G(e.finalizedChunks.length),e.finalizedChunks.map(e=>G(e.offset))]),Xy=e=>ty(`ctts`,1,0,[G(e.compositionTimeOffsetTable.length),e.compositionTimeOffsetTable.map(e=>[G(e.sampleCount),Kv(e.sampleCompositionTimeOffset)])]),Zy=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,zb(n.timestamp,e.timescale)),i=Math.max(i,zb(n.timestamp+n.duration,e.timescale))}let a=Math.max(-t,0);return i>=2**31?null:ty(`cslg`,0,0,[Kv(a),Kv(t),Kv(n),Kv(r),Kv(i)])},Qy=e=>K(`mvex`,void 0,e.map($y)),$y=e=>ty(`trex`,0,0,[G(e.track.id),G(1),G(0),G(0),G(0)]),eb=(e,t)=>K(`moof`,void 0,[tb(e),...t.map(rb)]),tb=e=>ty(`mfhd`,0,0,[G(e)]),nb=e=>{let t=0,n=0,r=e.type===`delta`;return n|=+r,t|=r?1:2,t<<24|n<<16|0},rb=e=>K(`traf`,void 0,[ib(e),ab(e),ob(e)]),ib=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:nb(n)};return ty(`tfhd`,0,t,[G(e.track.id),G(r.duration),G(r.size),G(r.flags)])},ab=e=>(z(e.currentChunk),ty(`tfdt`,1,0,[qv(zb(e.currentChunk.startTimestamp,e.timescale))])),ob=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(nb),i=e.currentChunk.samples.map(t=>zb(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,ty(`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?Kv(i[a]):[]])])},sb=e=>K(`mfra`,void 0,[...e.map(cb),lb()]),cb=e=>ty(`tfra`,1,0,[G(e.track.id),G(63),G(e.finalizedChunks.length),e.finalizedChunks.map(t=>[qv(zb(t.samples[0].timestamp,e.timescale)),qv(t.moofOffset),G(t.trafIndex+1),G(1),G(1)])]),lb=()=>ty(`mfro`,0,0,[G(0)]),ub=()=>K(`vtte`),db=(e,t,n,r,i)=>K(`vttc`,void 0,[i===null?null:K(`vsid`,[Kv(i)]),n===null?null:K(`iden`,[...sm.encode(n)]),t===null?null:K(`ctim`,[...sm.encode(Bv(t))]),r===null?null:K(`sttg`,[...sm.encode(r)]),K(`payl`,[...sm.encode(e)])]),fb=e=>K(`vtta`,[...sm.encode(e)]),pb=e=>{let t=[],n=e.format._options.metadataFormat??`auto`,r=e.output._metadataTags;if(n===`mdir`||n===`auto`&&!e.isQuickTime){let e=vb(r);e&&t.push(e)}else if(n===`mdta`){let e=yb(r);e&&t.push(e)}else(n===`udta`||n===`auto`&&e.isQuickTime)&&mb(t,e.output._metadataTags);return t.length===0?null:K(`udta`,void 0,t)},mb=(e,t)=>{for(let{key:n,value:r}of Gm(t))switch(n){case`title`:e.push(hb(`©nam`,r));break;case`description`:e.push(hb(`©des`,r));break;case`artist`:e.push(hb(`©ART`,r));break;case`album`:e.push(hb(`©alb`,r));break;case`albumArtist`:e.push(hb(`albr`,r));break;case`genre`:e.push(hb(`©gen`,r));break;case`date`:e.push(hb(`©day`,r.toISOString().slice(0,10)));break;case`comment`:e.push(hb(`©cmt`,r));break;case`lyrics`:e.push(hb(`©lyr`,r));break;case`raw`:break;case`discNumber`:case`discsTotal`:case`trackNumber`:case`tracksTotal`:case`images`:break;default:km(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(hb(n,r)):r instanceof Uint8Array&&e.push(K(n,Array.from(r))))}},hb=(e,t)=>{let n=sm.encode(t);return K(e,[W(n.length),W(Db(`und`)),Array.from(n)])},gb={"image/jpeg":13,"image/png":14,"image/bmp":27},_b=(e,t)=>{let n=[];for(let{key:r,value:i}of Gm(e))switch(r){case`title`:n.push({key:t?`title`:`©nam`,value:bb(i)});break;case`description`:n.push({key:t?`description`:`©des`,value:bb(i)});break;case`artist`:n.push({key:t?`artist`:`©ART`,value:bb(i)});break;case`album`:n.push({key:t?`album`:`©alb`,value:bb(i)});break;case`albumArtist`:n.push({key:t?`album_artist`:`aART`,value:bb(i)});break;case`comment`:n.push({key:t?`comment`:`©cmt`,value:bb(i)});break;case`genre`:n.push({key:t?`genre`:`©gen`,value:bb(i)});break;case`lyrics`:n.push({key:t?`lyrics`:`©lyr`,value:bb(i)});break;case`date`:n.push({key:t?`date`:`©day`,value:bb(i.toISOString().slice(0,10))});break;case`images`:for(let e of i)e.kind===`coverFront`&&n.push({key:`covr`,value:K(`data`,[G(gb[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:bb(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:km(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:bb(i)}):i instanceof Uint8Array?n.push({key:r,value:K(`data`,[G(0),G(0),Array.from(i)])}):i instanceof rh&&n.push({key:r,value:K(`data`,[G(gb[i.mimeType]??0),G(0),Array.from(i.data)])}))}return n},vb=e=>{let t=_b(e,!1);return t.length===0?null:ty(`meta`,0,0,void 0,[gy(!1,`mdir`,``,`appl`),K(`ilst`,void 0,t.map(e=>K(e.key,void 0,[e.value])))])},yb=e=>{let t=_b(e,!0);return t.length===0?null:K(`meta`,void 0,[gy(!1,`mdta`,``),ty(`keys`,0,0,[G(t.length)],t.map(e=>K(`mdta`,[...sm.encode(e.key)]))),K(`ilst`,void 0,t.map((e,t)=>K(String.fromCharCode(...G(t+1)),void 0,[e.value])))])},bb=e=>K(`data`,[G(1),G(0),...sm.encode(e)]),xb=(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}},Sb={avc:Oy,hevc:ky,vp8:Ay,vp9:Ay,av1:jy,prores:null},Cb=(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`}},wb=(e,t)=>{switch(e){case`aac`:return Ny;case`mp3`:return Ny;case`opus`:return Ly;case`vorbis`:return Ny;case`flac`:return Ry;case`ac3`:return By;case`eac3`:return Vy;case`dts`:return Hy}if(t)switch(e){case`pcm-s24`:return Py;case`pcm-s24be`:return Py;case`pcm-s32`:return Py;case`pcm-s32be`:return Py;case`pcm-f32`:return Py;case`pcm-f32be`:return Py;case`pcm-f64`:return Py;case`pcm-f64be`:return Py}else switch(e){case`pcm-s16`:return zy;case`pcm-s16be`:return zy;case`pcm-s24`:return zy;case`pcm-s24be`:return zy;case`pcm-s32`:return zy;case`pcm-s32be`:return zy;case`pcm-f32`:return zy;case`pcm-f32be`:return zy;case`pcm-f64`:return zy;case`pcm-f64be`:return zy}return null},Tb={webvtt:`wvtt`},Eb={webvtt:Wy},Db=e=>{z(e.length===3);let t=0;for(let n=0;n<3;n++)t<<=5,t+=e.charCodeAt(n)-96;return t},Ob=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}},kb=class extends $m{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 Pb(this,e)}},Ab=2**16,jb=2**32,Mb=class extends kb{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(Ab,{maxByteLength:jb})}catch{this._buffer=new ArrayBuffer(Ab),this._supportsResize=!1}else this._buffer=new ArrayBuffer(Ab);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>jb)throw Error(`ArrayBuffer exceeded maximum size of ${jb} 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)}},Nb=class extends kb{_start(){}_write(e,t){this._dispatchWrite(t,t+e.byteLength)}async _flush(){}async _finalize(){this._emit(`finalized`)}async _close(){}},Pb=class extends kb{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)}},Fb=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.`)}},Ib=57600,Lb=2082844800,Rb=e=>{let t={},n=e.track;return n.metadata.name!==void 0&&(t.name=n.metadata.name),t},zb=(e,t,n=!0)=>{let r=e*t;return n?Math.round(r):r},Bb=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},Vb=class extends Rv{constructor(e,t){super(e),this.writer=null,this.boxWriter=null,this.initWriter=null,this.initBoxWriter=null,this.auxTarget=new Mb,this.auxWriter=new Ob(this.auxTarget,!1),this.auxBoxWriter=new Vv(this.auxWriter),this.mdat=null,this.ftypSize=null,this.trackDatas=[],this.allTracksKnown=Em(),this.creationTime=Math.floor(Date.now()/1e3)+Lb,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 Zb,this.isCmaf=t instanceof Xb,this.minimumFragmentDuration=this.formatOptions.minimumFragmentDuration??(t instanceof Xb?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 Mb:this.formatOptions.fastStart===`fragmented`),this.boxWriter=new Vv(this.writer),this.fastStart=this.formatOptions.fastStart??(this.writer.target instanceof Mb&&`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 Ob(await this.output._getInitTarget(),!0);e.start(),this.initWriter=e,this.initBoxWriter=new Vv(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(ny({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=ay(!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 o_({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;$g(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=Oh(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=kh(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=Lh(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=Gh(e),a=!0}let o=Bm(1/(e.metadata.frameRate??57600),1e6).den,s=i.displayAspectWidth,c=i.displayAspectHeight,l=s===void 0||c===void 0?{num:1,den:1}:Zm({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;t_(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=U_(Dv.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=lh[e.samplingFrequencyIndex],r=uh[e.channelConfiguration];if(n===void 0||r===void 0)throw Error(`Invalid ADTS frame header.`);i.description=mh({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&&Ag.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;n_(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=[...Sh(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=Dh(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=U_(Dv.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=Kg(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=zb(n,e.timescale);if(n=r/e.timescale,r>0){let{sampleSize:i,silentValue:a}=Kg(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;zv.lastIndex=0;let r=zv.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=fb(n.notes);this.auxBoxWriter.writeBox(e)}let c=db(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:zb(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=zb(r.duration,e.timescale);t+=i}if(e.timeToSampleTable.length===0)e.timeToSampleTable.push({sampleCount:t,sampleDelta:1});else{let n=Qp(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=zb(r.timestamp-r.decodeTimestamp,e.timescale),a=zb(r.duration,e.timescale);if(e.lastTimescaleUnits!==null){z(e.lastSample);let t=zb(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=Qp(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=Qp(e.compositionTimeOffsetTable);z(r),r.sampleCompositionTimeOffset===i?r.sampleCount++:e.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:i})}}else e.lastTimescaleUnits=zb(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=zb(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+zb(n.duration,e.timescale),0)),(e.compactlyCodedChunkTable.length===0||Qp(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=sy(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 Vv(this.writer);let e=this.boxWriter.measureBox(ry()),t=this.boxWriter.measureBox(iy(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=eb(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=eb(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=ay(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=sy(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=ay(!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=Bb(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=ay(!1);let e;for(let t=0;t<2;t++){let t=sy(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=sy(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(ry()),this.boxWriter.writeBox(iy(this,e))}else{let e=this.writer.getPos(),t=sb(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=sy(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(oy(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()}},Hb=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})()}},Ub=class extends Hb{constructor(e){if(super(),this._connectedTrack=null,!kg.includes(e))throw TypeError(`Invalid video codec '${e}'. Must be one of: ${kg.join(`, `)}.`);this._codec=e}},Wb=class extends Hb{constructor(e){if(super(),this._connectedTrack=null,!Mg.includes(e))throw TypeError(`Invalid audio codec '${e}'. Must be one of: ${Mg.join(`, `)}.`);this._codec=e}},Gb=class extends Wb{constructor(e){super(e)}add(e,t){if(!(e instanceof a_))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)}},Kb=class extends Hb{constructor(e){if(super(),this._connectedTrack=null,!Ng.includes(e))throw TypeError(`Invalid subtitle codec '${e}'. Must be one of: ${Ng.join(`, `)}.`);this._codec=e}},qb=class{get supportsVideoRotationMetadata(){return this.supportsVideoTransformationMetadata}getSupportedVideoCodecs(){return this.getSupportedCodecs().filter(e=>kg.includes(e))}getSupportedAudioCodecs(){return this.getSupportedCodecs().filter(e=>Mg.includes(e))}getSupportedSubtitleCodecs(){return this.getSupportedCodecs().filter(e=>Ng.includes(e))}_codecUnsupportedHint(e){return``}_isFragmentedIsobmff(){return!1}},Jb=class extends qb{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&&(!Jm(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 Vb(e,this)}_isFragmentedIsobmff(){return this._options.fastStart===`fragmented`}},Yb=class extends Jb{constructor(e){super(e)}get _name(){return`MP4`}get fileExtension(){return`.mp4`}get mimeType(){return`video/mp4`}getSupportedCodecs(){return[...kg,...jg,`pcm-s16`,`pcm-s16be`,`pcm-s24`,`pcm-s24be`,`pcm-s32`,`pcm-s32be`,`pcm-f32`,`pcm-f32be`,`pcm-f64`,`pcm-f64be`,...Ng]}_codecUnsupportedHint(e){return new Zb().getSupportedCodecs().includes(e)?` Switching to MOV will grant support for this codec.`:``}},Xb=class extends Jb{constructor(e){super(e)}get _name(){return`CMAF`}get fileExtension(){return`.m4s`}get mimeType(){return`video/mp4`}getSupportedCodecs(){return[...kg,...jg,`pcm-s16`,`pcm-s16be`,`pcm-s24`,`pcm-s24be`,`pcm-s32`,`pcm-s32be`,`pcm-f32`,`pcm-f32be`,`pcm-f64`,`pcm-f64be`,...Ng]}},Zb=class extends Jb{constructor(e){super(e)}get _name(){return`MOV`}get fileExtension(){return`.mov`}get mimeType(){return`video/quicktime`}getSupportedCodecs(){return[...kg,...Mg]}_codecUnsupportedHint(e){return new Yb().getSupportedCodecs().includes(e)?` Switching to MP4 will grant support for this codec.`:``}},Qb=[`video`,`audio`,`subtitle`],$b=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=Qm(this.metadata.group),r=Qm(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}},ex=class extends $b{constructor(e,t,n,r){super(e,t,`video`,n,r)}},tx=class extends $b{constructor(e,t,n,r){super(e,t,`audio`,n,r)}},nx=class extends $b{constructor(e,t,n,r){super(e,t,`subtitle`,n,r)}},rx=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)}},ix=e=>{if(!e||typeof e!=`object`)throw TypeError(`metadata must be an object.`);if(e.languageCode!==void 0&&!Rm(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&&sh(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 rx)&&(!Array.isArray(e.group)||e.group.some(e=>!(e instanceof rx))))throw TypeError(`metadata.group, when provided, must be an OutputTrackGroup instance or an array of OutputTrackGroup instances.`)},ax=class extends $m{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(Wm(t))throw TypeError(e);return t}constructor(e){if(super(),this.state=`pending`,this.defaultTrackGroup=new rx,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 ym,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 qb))throw TypeError(`options.format must be an OutputFormat.`);if(!(e.target instanceof kb||e.target instanceof Fb))throw TypeError(`options.target must be a Target or a PathedTarget.`);if(e.target instanceof kb&&this._rememberTarget(e.target),e.initTarget!==void 0&&!(e.initTarget instanceof kb)&&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 kb&&this._rememberTarget(this._initTarget),this._muxer=e.format._createMuxer(this)}_getTargetValidated(e){z(this._target instanceof Fb);let t=this._target.getTarget(e),n=e=>{if(!(e instanceof kb))throw TypeError(`getTarget must return a Target.`);return e};return Wm(t)?t.then(n):n(t)}async _getTarget(e){z(this._target instanceof Fb);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 kb)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 kb)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 Wm(t)?this._rootTargetPromise=t.then(n):n(t)}_getRootWriter(e){return this._rootWriterPromise??=(async()=>{let t=await this._getRootTarget(),n=new Ob(t,typeof e==`boolean`?e:e(t));return n.start(),n})()}addVideoTrack(e,t={}){if(!(e instanceof Ub))throw TypeError(`source must be a VideoSource.`);if(ix(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&&$g({decoderConfig:t.decoderConfig},e._codec),t.primingPacket!==void 0){if(!(t.primingPacket instanceof a_))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 ex(this.tracks.length+1,this,e,n))}addAudioTrack(e,t={}){if(!(e instanceof Wb))throw TypeError(`source must be an AudioSource.`);if(ix(t),t.decoderConfig!==void 0&&t_({decoderConfig:t.decoderConfig},e._codec),t.primingPacket!==void 0){if(!(t.primingPacket instanceof a_))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 tx(this.tracks.length+1,this,e,n))}addSubtitleTrack(e,t={}){if(!(e instanceof Kb))throw TypeError(`source must be a SubtitleSource.`);ix(t);let n={...t};return n.group??=this.defaultTrackGroup,this._addTrack(new nx(this.tracks.length+1,this,e,n))}setMetadataTags(e){if(ah(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 Qb)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 Qb){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?(nh._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`&&nh._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?(nh._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 ox(e){let t=ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):new Uint8Array(e);return Uint8Array.from(t)}var sx=/* @__PURE__ */ new Set([`hvc1`,`hev1`]);async function cx(e,t){let[n,r]=await Promise.all([e.getCodec(),e.getInternalCodecId()]);return n===`hevc`&&typeof r==`string`&&sx.has(r)&&t.description!==void 0?Ps(r,ox(t.description)):t.codec}function lx(e,t){return{codec:t.codec,codedWidth:e.codedWidth??t.codedWidth,codedHeight:e.codedHeight??t.codedHeight,description:e.description===void 0?void 0:ox(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:ox(e.description)}}function dx(e){return{primaries:Xl(ql,e?.primaries),transfer:Xl(Jl,e?.transfer),matrix:Xl(Yl,e?.matrix),range:fx(e?.fullRange)}}function fx(e){return e===!0?`full`:e===!1?`limited`:`unspecified`}var px=[tv,nv],mx=class{async read(e){let t=new Cv({formats:px,source:new Y_(e)});try{let[e,n]=await Promise.all([t.getVideoTracks(),t.getAudioTracks()]);return{video:await Promise.all(e.map((e,t)=>hx(e,t))),audio:(await Promise.all(n.map(e=>_x(e)))).flat()}}catch(e){throw vx(e)}finally{t.dispose()}}};async function hx(e,t){let[n,r,i]=await Promise.all([gx(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 cx(e,n),colour:dx(n.colorSpace)};return{trackId:e.id,description:a,configuration:lx(n,a)}}async function gx(e){try{return await e.getDecoderConfig()}catch{return null}}async function _x(e){let t=await e.getDecoderConfig();return t===null?[]:[{trackId:e.id,configuration:ux(t)}]}function vx(e){return re(e)||e instanceof j?e:new j(`unsupported-container`,`the movie box is not a readable movie`,{cause:e})}var yx=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=xx){return new bx({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()}},bx=class{parts;hasEnded=!1;constructor(e){this.parts=e}async next(){if(this.hasEnded)return hu;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,hu}};function xx(){}var Sx=1,Cx=2,wx=`mp4a.40.`,Tx=`aac`,Ex=class{segmentsOf(e,t){let n=Dx(t);return{mimeType:`audio/mp4; codecs="${t.codec}"`,duration:e.duration,segmentsFrom:r=>({[Symbol.asyncIterator]:()=>Ox({samples:e,configuration:t,codec:n},r)})}}};function Dx(e){if(e.codec.startsWith(wx))return Tx;throw new j(`codec-unsupported`,`audio in ${e.codec} cannot be re-packaged for playback`)}function Ox(e,t){let n=new yx(Cx),r=new ax({format:Nx(n),target:new Nb}),i=new Gb(e.codec);r.addAudioTrack(i);let a=e.samples.samplesFrom(t)[Symbol.asyncIterator](),o=Ax({samples:a,configuration:e.configuration,output:r,source:i,channel:n});return n.segments(()=>{a.return?.(),kx(o,r)})}async function kx(e,t){if(await e,t.state!==`finalized`)try{await t.cancel()}catch{}}async function Ax(e){try{await e.output.start();let t={decoderConfig:Mx(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(jx(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 jx(e){return new a_(e.data,`key`,e.timestamp,e.duration)}function Mx(e){return{codec:e.codec,sampleRate:e.sampleRate,numberOfChannels:e.numberOfChannels,...e.description&&{description:e.description}}}function Nx(e){let t=new Px(e);return new Yb({fastStart:`fragmented`,minimumFragmentDuration:Sx,onFtyp:e=>{t.begin(e)},onMoov:e=>{t.end(e)},onMoof:e=>{t.begin(e)},onMdat:e=>{t.end(e)}})}var Px=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 Fx(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:Ix(n)??t}function Ix(e){try{return new VideoColorSpace(e).toJSON()}catch{return}}var Lx=`no-preference`,Rx=class{async isSupported(e){if(typeof VideoDecoder>`u`)throw Bx();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 Bx();return new zx(this.toWebCodecsConfig(e),t)}toWebCodecsConfig(e){let{description:t}=e,n=Fx(e.colour);return{codec:e.codec,codedWidth:e.codedWidth,codedHeight:e.codedHeight,...t&&{description:t},...n&&{colorSpace:n},hardwareAcceleration:Lx,optimizeForLatency:!1}}},zx=class{decoder;failure;constructor(e,t){this.decoder=new VideoDecoder({output:e=>{t.onFrame(Hx(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(Vx(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 Bx(){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 Vx(e){return new EncodedVideoChunk({type:e.isKeyFrame?`key`:`delta`,timestamp:_t(e.timestamp),duration:_t(e.duration),data:e.data})}function Hx(e){return{timestamp:mt(ft(e.timestamp)),handle:e,close:()=>{e.close()}}}function Ux(e){return`url`in e}function Wx(e){return Ux(e)?Ta(e.url):e.name}var Gx=15e3;function Kx(e={}){let t=e.http??{},n=e.probeTimeoutMs??Gx;return{sources:qx(t),codecReader:new mx,audioPackager:new Ex,decoderPort:new Rx,locatorFor:e=>new Bp(Xx(t,e)),probeDeadline:()=>Zx(n)}}function qx(e){return{open:(t,n)=>Ux(t)?Jx(t,e,n):Yx(t)}}function Jx(e,t,n){let r=new Ip(e.url,Xx(t,e),n);return{source:new lp(r),stream:new sp(r)}}function Yx(e){let t=new Xf(e.blob);return{source:t,stream:new _u(t)}}function Xx(e,t){let{credentials:n}=t;return n===void 0?e:{...e,requestInit:{...e.requestInit,credentials:n}}}function Zx(e){let t=new wd;return setTimeout(()=>{t.resolve()},e),t}function Qx(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 $x=`ManagedMediaSource`,eS=`MediaSource`;function tS(e){return typeof e==`function`&&typeof e.isTypeSupported==`function`}function nS(e){let t=Reflect.get(globalThis,e);return tS(t)?t:void 0}function rS(){return nS($x)??nS(eS)}function iS(e){return rS()?.isTypeSupported(e)??!1}var aS=1e4;async function oS(e,t){let n=new t,r=sS(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 sS(e,t){let n=new AbortController;try{return await Promise.race([Qx(t,[`sourceopen`],n.signal),Qx(e,[`error`],n.signal),cS(aS,n.signal)])}finally{n.abort()}}function cS(e,t){return new Promise(n=>{let r=setTimeout(()=>{n(`timeout`)},e);t.addEventListener(`abort`,()=>{clearTimeout(r)},{once:!0})})}var lS=30,uS=30,dS=60,fS=1,pS=[`timeupdate`,`seeking`,`waiting`,`play`],mS=class{parts;stop=new Ed;run=Promise.resolve();failureValue;constructor(e){this.parts=e}get failure(){return this.failureValue}restartFrom(e){this.stop.stop();let t=new Ed;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-fS))}async pump(e,t){let n=await this.nextWhenNeeded(e,t);for(;n!==Td;){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()>=lS;){let t=new AbortController;await e.race(()=>Qx(this.parts.element,pS,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)<dS||this.parts.sourceBuffer.updating||this.parts.sourceBuffer.remove(0,t-uS)}async append(e){let{sourceBuffer:t}=this.parts;await this.settlePendingAppend();let n=Qx(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 Qx(this.parts.sourceBuffer,[`updateend`])}endStream(){let{mediaSource:e,sourceBuffer:t}=this.parts;e.readyState===`open`&&!t.updating&&e.endOfStream()}},hS=class e{element;feeder;attached;standingEnd;constructor(e,t,n){this.element=e,this.feeder=t,this.attached=n}static isSupported(e){return iS(e.mimeType)}static async open(t,n){let r=rS();if(!r?.isTypeSupported(n.mimeType))throw new j(`codec-unsupported`,`${n.mimeType} cannot play through Media Source Extensions here`);let i=await oS(t,r);try{let r=i.mediaSource.addSourceBuffer(n.mimeType);i.mediaSource.duration=n.duration;let a=new mS({element:t,mediaSource:i.mediaSource,sourceBuffer:r,source:n});return a.restartFrom(R(0)),new e(t,a,i)}catch(e){throw i.detach(),vS(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??_S(this.element)}async start(){if(!this.hasEnded)try{await this.element.play()}catch(e){if(re(e))return;let t=gS(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 gS(e,t){return e instanceof Error&&e.name===t}function _S(e){let{error:t}=e;return t===null?void 0:new j(`decode`,`the audio element failed (media error ${t.code})`,{cause:t})}function vS(e){return e instanceof j?e:new j(gS(e,`NotSupportedError`)?`codec-unsupported`:`decode`,`the audio element refused the recording's sound: ${ie(e)}`,{cause:e})}var yS=1e3,bS=1001,xS=1002,SS=1003,CS=1004,wS=1005,TS=1006,ES=1007,DS=1008,OS=1009,kS=1010,AS=1011,jS=1012,MS=1013,NS=1014,PS=1015,FS=1016,IS=1017,LS=1018,RS=1020,zS=35902,BS=35899,VS=1021,HS=1022,US=1023,WS=1026,GS=1027,KS=1028,qS=1029,JS=1030,YS=1031,XS=1033,ZS=33776,QS=33777,$S=33778,eC=33779,tC=35840,nC=35841,rC=35842,iC=35843,aC=36196,oC=37492,sC=37496,cC=37488,lC=37489,uC=37490,dC=37491,fC=37808,pC=37809,mC=37810,hC=37811,gC=37812,_C=37813,vC=37814,yC=37815,bC=37816,xC=37817,SC=37818,CC=37819,wC=37820,TC=37821,EC=36492,DC=36494,OC=36495,kC=36283,AC=36284,jC=36285,MC=36286,NC=2300,PC=2301,FC=2302,IC=2303,LC=2400,RC=2401,zC=2402,BC=3200,VC=`srgb`,HC=`srgb-linear`,UC=`linear`,WC=`srgb`,GC=7680,KC=35044,qC=`300 es`,JC=2e3;function YC(e){for(let t=e.length-1;t>=0;--t)if(e[t]>=65535)return!0;return!1}function XC(e){return ArrayBuffer.isView(e)&&!(e instanceof DataView)}function ZC(e){return document.createElementNS(`http://www.w3.org/1999/xhtml`,e)}function QC(){let e=ZC(`canvas`);return e.style.display=`block`,e}var $C={};function ew(...e){let t=`THREE.`+e.shift();console.log(t,...e)}function tw(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=tw(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=tw(e);let t=`THREE.`+e.shift();{let n=e[0];n&&n.isStackTrace?console.error(n.getError(t)):console.error(t,...e)}}function nw(...e){let t=e.join(` `);t in $C||($C[t]=!0,q(...e))}function rw(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 iw={0:1,2:6,4:7,3:5,1:0,6:2,7:4,5:3},aw=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}}},ow=/* @__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(`.`),sw=Math.PI/180,cw=180/Math.PI;function lw(){let e=Math.random()*4294967295|0,t=Math.random()*4294967295|0,n=Math.random()*4294967295|0,r=Math.random()*4294967295|0;return(ow[e&255]+ow[e>>8&255]+ow[e>>16&255]+ow[e>>24&255]+`-`+ow[t&255]+ow[t>>8&255]+`-`+ow[t>>16&15|64]+ow[t>>24&255]+`-`+ow[n&63|128]+ow[n>>8&255]+`-`+ow[n>>16&255]+ow[n>>24&255]+ow[r&255]+ow[r>>8&255]+ow[r>>16&255]+ow[r>>24&255]).toLowerCase()}function uw(e,t,n){return Math.max(t,Math.min(n,e))}function dw(e,t){return(e%t+t)%t}function fw(e,t,n){return(1-n)*e+n*t}function pw(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 mw(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}},hw=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(_w.setFromEuler(e))}applyAxisAngle(e,t){return this.applyQuaternion(_w.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 gw.copy(this).projectOnVector(e),this.sub(gw)}reflect(e){return this.sub(gw.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}},gw=/*@__PURE__*/ new X,_w=/*@__PURE__*/ new hw,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 nw(`Matrix3: .scale() is deprecated. Use .makeScale() instead.`),this.premultiply(vw.makeScale(e,t)),this}rotate(e){return nw(`Matrix3: .rotate() is deprecated. Use .makeRotation() instead.`),this.premultiply(vw.makeRotation(-e)),this}translate(e,t){return nw(`Matrix3: .translate() is deprecated. Use .makeTranslation() instead.`),this.premultiply(vw.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)}},vw=/*@__PURE__*/ new Z,yw=/*@__PURE__*/ new Z().set(.4123908,.3575843,.1804808,.212639,.7151687,.0721923,.0193308,.1191948,.9505322),bw=/*@__PURE__*/ new Z().set(3.2409699,-1.5373832,-.4986108,-.9692436,1.8759675,.0415551,.0556301,-.203977,1.0569715);function xw(){let e={enabled:!0,workingColorSpace:HC,spaces:{},convert:function(e,t,n){return this.enabled===!1||t===n||!t||!n?e:(this.spaces[t].transfer===`srgb`&&(e.r=Cw(e.r),e.g=Cw(e.g),e.b=Cw(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=ww(e.r),e.g=ww(e.g),e.b=ww(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===``?UC: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 nw(`ColorManagement: .fromWorkingColorSpace() has been renamed to .workingToColorSpace().`),e.workingToColorSpace(t,n)},toWorkingColorSpace:function(t,n){return nw(`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({[HC]:{primaries:t,whitePoint:r,transfer:UC,toXYZ:yw,fromXYZ:bw,luminanceCoefficients:n,workingColorSpaceConfig:{unpackColorSpace:VC},outputColorSpaceConfig:{drawingBufferColorSpace:VC}},[VC]:{primaries:t,whitePoint:r,transfer:WC,toXYZ:yw,fromXYZ:bw,luminanceCoefficients:n,outputColorSpaceConfig:{drawingBufferColorSpace:VC}}}),e}var Sw=/*@__PURE__*/ xw();function Cw(e){return e<.04045?e*.0773993808:(e*.9478672986+.0521327014)**2.4}function ww(e){return e<.0031308?e*12.92:1.055*e**.41666-.055}var Tw,Ew=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{Tw===void 0&&(Tw=ZC(`canvas`)),Tw.width=e.width,Tw.height=e.height;let t=Tw.getContext(`2d`);e instanceof ImageData?t.putImageData(e,0,0):t.drawImage(e,0,0,e.width,e.height),n=Tw}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=ZC(`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]=Cw(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(Cw(t[e]/255)*255):t[e]=Cw(t[e]);return{data:t,width:e.width,height:e.height}}return q(`ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied.`),e}},Dw=0,Ow=class{constructor(e=null){this.isTextureSource=!0,Object.defineProperty(this,"id",{value:Dw++}),this.uuid=lw(),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(kw(r[t].image)):e.push(kw(r[t]))}else e=kw(r);n.url=e}return t||(e.images[this.uuid]=n),n}};function kw(e){return typeof HTMLImageElement<`u`&&e instanceof HTMLImageElement||typeof HTMLCanvasElement<`u`&&e instanceof HTMLCanvasElement||typeof ImageBitmap<`u`&&e instanceof ImageBitmap?Ew.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 Aw=0,jw=/*@__PURE__*/ new X,Mw=class e extends aw{constructor(t=e.DEFAULT_IMAGE,n=e.DEFAULT_MAPPING,r=bS,i=bS,a=TS,o=DS,s=US,c=OS,l=e.DEFAULT_ANISOTROPY,u=``){super(),this.isTexture=!0,Object.defineProperty(this,"id",{value:Aw++}),this.uuid=lw(),this.name=``,this.source=new Ow(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(jw).x}get height(){return this.source.getSize(jw).y}get depth(){return this.source.getSize(jw).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 yS:e.x-=Math.floor(e.x);break;case bS:e.x=e.x<0?0:1;break;case xS: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 yS:e.y-=Math.floor(e.y);break;case bS:e.y=e.y<0?0:1;break;case xS: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++}};Mw.DEFAULT_IMAGE=null,Mw.DEFAULT_MAPPING=300,Mw.DEFAULT_ANISOTROPY=1;var Nw=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}},Pw=class extends aw{constructor(e=1,t=1,n={}){super(),n=Object.assign({generateMipmaps:!1,internalFormat:null,minFilter:TS,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 Nw(0,0,e,t),this.scissorTest=!1,this.viewport=new Nw(0,0,e,t),this.textures=[];let r=new Mw({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:TS,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 Ow(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`})}},Fw=class extends Pw{constructor(e=1,t=1,n={}){super(e,t,n),this.isWebGLRenderTarget=!0}},Iw=class extends Mw{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=SS,this.minFilter=SS,this.wrapR=bS,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()}},Lw=class extends Mw{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=SS,this.minFilter=SS,this.wrapR=bS,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}copy(e){return super.copy(e),this.wrapR=e.wrapR,this}},Rw=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/zw.setFromMatrixColumn(e,0).length(),i=1/zw.setFromMatrixColumn(e,1).length(),a=1/zw.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(Vw,e,Hw)}lookAt(e,t,n){let r=this.elements;return Gw.subVectors(e,t),Gw.lengthSq()===0&&(Gw.z=1),Gw.normalize(),Uw.crossVectors(n,Gw),Uw.lengthSq()===0&&(Math.abs(n.z)===1?Gw.x+=1e-4:Gw.z+=1e-4,Gw.normalize(),Uw.crossVectors(n,Gw)),Uw.normalize(),Ww.crossVectors(Gw,Uw),r[0]=Uw.x,r[4]=Ww.x,r[8]=Gw.x,r[1]=Uw.y,r[5]=Ww.y,r[9]=Gw.y,r[2]=Uw.z,r[6]=Ww.z,r[10]=Gw.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=zw.set(r[0],r[1],r[2]).length(),o=zw.set(r[4],r[5],r[6]).length(),s=zw.set(r[8],r[9],r[10]).length();i<0&&(a=-a),Bw.copy(this);let c=1/a,l=1/o,u=1/s;return Bw.elements[0]*=c,Bw.elements[1]*=c,Bw.elements[2]*=c,Bw.elements[4]*=l,Bw.elements[5]*=l,Bw.elements[6]*=l,Bw.elements[8]*=u,Bw.elements[9]*=u,Bw.elements[10]*=u,t.setFromRotationMatrix(Bw),n.x=a,n.y=o,n.z=s,this}makePerspective(e,t,n,r,i,a,o=JC,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=JC,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}},zw=/*@__PURE__*/ new X,Bw=/*@__PURE__*/ new Rw,Vw=/*@__PURE__*/ new X(0,0,0),Hw=/*@__PURE__*/ new X(1,1,1),Uw=/*@__PURE__*/ new X,Ww=/*@__PURE__*/ new X,Gw=/*@__PURE__*/ new X,Kw=/*@__PURE__*/ new Rw,qw=/*@__PURE__*/ new hw,Jw=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 Kw.makeRotationFromQuaternion(e),this.setFromRotationMatrix(Kw,t,n)}setFromVector3(e,t=this._order){return this.set(e.x,e.y,e.z,t)}reorder(e){return qw.setFromEuler(this),this.setFromQuaternion(qw,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}};Jw.DEFAULT_ORDER=`XYZ`;var Yw=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))}},Xw=0,Zw=/*@__PURE__*/ new X,Qw=/*@__PURE__*/ new hw,$w=/*@__PURE__*/ new Rw,eT=/*@__PURE__*/ new X,tT=/*@__PURE__*/ new X,nT=/*@__PURE__*/ new X,rT=/*@__PURE__*/ new hw,iT=/*@__PURE__*/ new X(1,0,0),aT=/*@__PURE__*/ new X(0,1,0),oT=/*@__PURE__*/ new X(0,0,1),sT={type:`added`},cT={type:`removed`},lT={type:`childadded`,child:null},uT={type:`childremoved`,child:null},dT=class e extends aw{constructor(){super(),this.isObject3D=!0,Object.defineProperty(this,"id",{value:Xw++}),this.uuid=lw(),this.name=``,this.type=`Object3D`,this.parent=null,this.children=[],this.up=e.DEFAULT_UP.clone();let t=new X,n=new Jw,r=new hw,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 Rw},normalMatrix:{value:new Z}}),this.matrix=new Rw,this.matrixWorld=new Rw,this.matrixAutoUpdate=e.DEFAULT_MATRIX_AUTO_UPDATE,this.matrixWorldAutoUpdate=e.DEFAULT_MATRIX_WORLD_AUTO_UPDATE,this.matrixWorldNeedsUpdate=!1,this.layers=new Yw,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 Qw.setFromAxisAngle(e,t),this.quaternion.multiply(Qw),this}rotateOnWorldAxis(e,t){return Qw.setFromAxisAngle(e,t),this.quaternion.premultiply(Qw),this}rotateX(e){return this.rotateOnAxis(iT,e)}rotateY(e){return this.rotateOnAxis(aT,e)}rotateZ(e){return this.rotateOnAxis(oT,e)}translateOnAxis(e,t){return Zw.copy(e).applyQuaternion(this.quaternion),this.position.add(Zw.multiplyScalar(t)),this}translateX(e){return this.translateOnAxis(iT,e)}translateY(e){return this.translateOnAxis(aT,e)}translateZ(e){return this.translateOnAxis(oT,e)}localToWorld(e){return this.updateWorldMatrix(!0,!1),e.applyMatrix4(this.matrixWorld)}worldToLocal(e){return this.updateWorldMatrix(!0,!1),e.applyMatrix4($w.copy(this.matrixWorld).invert())}lookAt(e,t,n){e.isVector3?eT.copy(e):eT.set(e,t,n);let r=this.parent;this.updateWorldMatrix(!0,!1),tT.setFromMatrixPosition(this.matrixWorld),this.isCamera||this.isLight?$w.lookAt(tT,eT,this.up):$w.lookAt(eT,tT,this.up),this.quaternion.setFromRotationMatrix($w),r&&($w.extractRotation(r.matrixWorld),Qw.setFromRotationMatrix($w),this.quaternion.premultiply(Qw.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(sT),lT.child=e,this.dispatchEvent(lT),lT.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(cT),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),$w.copy(this.matrixWorld).invert(),e.parent!==null&&(e.parent.updateWorldMatrix(!0,!1),$w.multiply(e.parent.matrixWorld)),e.applyMatrix4($w),e.removeFromParent(),e.parent=this,this.children.push(e),e.updateWorldMatrix(!1,!0),e.dispatchEvent(sT),lT.child=e,this.dispatchEvent(lT),lT.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(tT,e,nT),e}getWorldScale(e){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose(tT,rT,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`})}};dT.DEFAULT_UP=/*@__PURE__*/ new X(0,1,0),dT.DEFAULT_MATRIX_AUTO_UPDATE=!0,dT.DEFAULT_MATRIX_WORLD_AUTO_UPDATE=!0;var fT=class extends dT{constructor(){super(),this.isGroup=!0,this.type=`Group`}},pT={type:`move`},mT=class{constructor(){this._targetRay=null,this._grip=null,this._hand=null}getHandSpace(){return this._hand===null&&(this._hand=new fT,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 fT,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 fT,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(pT)))}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 fT;n.matrixAutoUpdate=!1,n.visible=!1,e.joints[t.jointName]=n,e.add(n)}return e.joints[t.jointName]}},hT={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},gT={h:0,s:0,l:0},_T={h:0,s:0,l:0};function vT(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 yT=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=VC){return e=Math.floor(e),this.r=(e>>16&255)/255,this.g=(e>>8&255)/255,this.b=(e&255)/255,Sw.colorSpaceToWorking(this,t),this}setRGB(e,t,n,r=Sw.workingColorSpace){return this.r=e,this.g=t,this.b=n,Sw.colorSpaceToWorking(this,r),this}setHSL(e,t,n,r=Sw.workingColorSpace){if(e=dw(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=vT(i,r,e+1/3),this.g=vT(i,r,e),this.b=vT(i,r,e-1/3)}return Sw.colorSpaceToWorking(this,r),this}setStyle(e,t=VC){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=VC){let n=hT[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=Cw(e.r),this.g=Cw(e.g),this.b=Cw(e.b),this}copyLinearToSRGB(e){return this.r=ww(e.r),this.g=ww(e.g),this.b=ww(e.b),this}convertSRGBToLinear(){return this.copySRGBToLinear(this),this}convertLinearToSRGB(){return this.copyLinearToSRGB(this),this}getHex(e=VC){return Sw.workingToColorSpace(bT.copy(this),e),Math.round(uw(bT.r*255,0,255))*65536+Math.round(uw(bT.g*255,0,255))*256+Math.round(uw(bT.b*255,0,255))}getHexString(e=VC){return(`000000`+this.getHex(e).toString(16)).slice(-6)}getHSL(e,t=Sw.workingColorSpace){Sw.workingToColorSpace(bT.copy(this),t);let n=bT.r,r=bT.g,i=bT.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=Sw.workingColorSpace){return Sw.workingToColorSpace(bT.copy(this),t),e.r=bT.r,e.g=bT.g,e.b=bT.b,e}getStyle(e=VC){Sw.workingToColorSpace(bT.copy(this),e);let t=bT.r,n=bT.g,r=bT.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(gT),this.setHSL(gT.h+e,gT.s+t,gT.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(gT),e.getHSL(_T);let n=fw(gT.h,_T.h,t),r=fw(gT.s,_T.s,t),i=fw(gT.l,_T.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}},bT=/*@__PURE__*/ new yT;yT.NAMES=hT;var xT=class extends dT{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 Jw,this.environmentIntensity=1,this.environmentRotation=new Jw,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}},ST=/*@__PURE__*/ new X,CT=/*@__PURE__*/ new X,wT=/*@__PURE__*/ new X,TT=/*@__PURE__*/ new X,ET=/*@__PURE__*/ new X,DT=/*@__PURE__*/ new X,OT=/*@__PURE__*/ new X,kT=/*@__PURE__*/ new X,AT=/*@__PURE__*/ new X,jT=/*@__PURE__*/ new X,MT=/*@__PURE__*/ new Nw,NT=/*@__PURE__*/ new Nw,PT=/*@__PURE__*/ new Nw,FT=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),ST.subVectors(e,t),r.cross(ST);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){ST.subVectors(r,t),CT.subVectors(n,t),wT.subVectors(e,t);let a=ST.dot(ST),o=ST.dot(CT),s=ST.dot(wT),c=CT.dot(CT),l=CT.dot(wT),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,TT)!==null&&TT.x>=0&&TT.y>=0&&TT.x+TT.y<=1}static getInterpolation(e,t,n,r,i,a,o,s){return this.getBarycoord(e,t,n,r,TT)===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,TT.x),s.addScaledVector(a,TT.y),s.addScaledVector(o,TT.z),s)}static getInterpolatedAttribute(e,t,n,r,i,a){return MT.setScalar(0),NT.setScalar(0),PT.setScalar(0),MT.fromBufferAttribute(e,t),NT.fromBufferAttribute(e,n),PT.fromBufferAttribute(e,r),a.setScalar(0),a.addScaledVector(MT,i.x),a.addScaledVector(NT,i.y),a.addScaledVector(PT,i.z),a}static isFrontFacing(e,t,n,r){return ST.subVectors(n,t),CT.subVectors(e,t),ST.cross(CT).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 ST.subVectors(this.c,this.b),CT.subVectors(this.a,this.b),ST.cross(CT).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;ET.subVectors(r,n),DT.subVectors(i,n),kT.subVectors(e,n);let s=ET.dot(kT),c=DT.dot(kT);if(s<=0&&c<=0)return t.copy(n);AT.subVectors(e,r);let l=ET.dot(AT),u=DT.dot(AT);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(ET,a);jT.subVectors(e,i);let f=ET.dot(jT),p=DT.dot(jT);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(DT,o);let h=l*p-f*u;if(h<=0&&u-l>=0&&f-p>=0)return OT.subVectors(i,r),o=(u-l)/(u-l+(f-p)),t.copy(r).addScaledVector(OT,o);let g=1/(h+m+d);return a=m*g,o=d*g,t.copy(n).addScaledVector(ET,a).addScaledVector(DT,o)}equals(e){return e.a.equals(this.a)&&e.b.equals(this.b)&&e.c.equals(this.c)}},IT=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(RT.fromArray(e,t));return this}setFromBufferAttribute(e){this.makeEmpty();for(let t=0,n=e.count;t<n;t++)this.expandByPoint(RT.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=RT.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,RT):RT.fromBufferAttribute(r,t),RT.applyMatrix4(e.matrixWorld),this.expandByPoint(RT);else e.boundingBox===void 0?(n.boundingBox===null&&n.computeBoundingBox(),zT.copy(n.boundingBox)):(e.boundingBox===null&&e.computeBoundingBox(),zT.copy(e.boundingBox)),zT.applyMatrix4(e.matrixWorld),this.union(zT)}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,RT),RT.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(KT),qT.subVectors(this.max,KT),BT.subVectors(e.a,KT),VT.subVectors(e.b,KT),HT.subVectors(e.c,KT),UT.subVectors(VT,BT),WT.subVectors(HT,VT),GT.subVectors(BT,HT);let t=[0,-UT.z,UT.y,0,-WT.z,WT.y,0,-GT.z,GT.y,UT.z,0,-UT.x,WT.z,0,-WT.x,GT.z,0,-GT.x,-UT.y,UT.x,0,-WT.y,WT.x,0,-GT.y,GT.x,0];return!XT(t,BT,VT,HT,qT)||(t=[1,0,0,0,1,0,0,0,1],!XT(t,BT,VT,HT,qT))?!1:(JT.crossVectors(UT,WT),t=[JT.x,JT.y,JT.z],XT(t,BT,VT,HT,qT))}clampPoint(e,t){return t.copy(e).clamp(this.min,this.max)}distanceToPoint(e){return this.clampPoint(e,RT).distanceTo(e)}getBoundingSphere(e){return this.isEmpty()?e.makeEmpty():(this.getCenter(e.center),e.radius=this.getSize(RT).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:(LT[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(e),LT[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(e),LT[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(e),LT[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(e),LT[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(e),LT[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(e),LT[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(e),LT[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(e),this.setFromPoints(LT),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}},LT=[/*@__PURE__*/ new X,/*@__PURE__*/ new X,/*@__PURE__*/ new X,/*@__PURE__*/ new X,/*@__PURE__*/ new X,/*@__PURE__*/ new X,/*@__PURE__*/ new X,/*@__PURE__*/ new X],RT=/*@__PURE__*/ new X,zT=/*@__PURE__*/ new IT,BT=/*@__PURE__*/ new X,VT=/*@__PURE__*/ new X,HT=/*@__PURE__*/ new X,UT=/*@__PURE__*/ new X,WT=/*@__PURE__*/ new X,GT=/*@__PURE__*/ new X,KT=/*@__PURE__*/ new X,qT=/*@__PURE__*/ new X,JT=/*@__PURE__*/ new X,YT=/*@__PURE__*/ new X;function XT(e,t,n,r,i){for(let a=0,o=e.length-3;a<=o;a+=3){YT.fromArray(e,a);let o=i.x*Math.abs(YT.x)+i.y*Math.abs(YT.y)+i.z*Math.abs(YT.z),s=t.dot(YT),c=n.dot(YT),l=r.dot(YT);if(Math.max(-Math.max(s,c,l),Math.min(s,c,l))>o)return!1}return!0}var ZT=/*@__PURE__*/ new X,QT=/*@__PURE__*/ new Y,$T=0,eE=class extends aw{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:$T++}),this.name=``,this.array=e,this.itemSize=t,this.count=e===void 0?0:e.length/t,this.normalized=n,this.usage=KC,this.updateRanges=[],this.gpuType=PS,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++)QT.fromBufferAttribute(this,t),QT.applyMatrix3(e),this.setXY(t,QT.x,QT.y);else if(this.itemSize===3)for(let t=0,n=this.count;t<n;t++)ZT.fromBufferAttribute(this,t),ZT.applyMatrix3(e),this.setXYZ(t,ZT.x,ZT.y,ZT.z);return this}applyMatrix4(e){for(let t=0,n=this.count;t<n;t++)ZT.fromBufferAttribute(this,t),ZT.applyMatrix4(e),this.setXYZ(t,ZT.x,ZT.y,ZT.z);return this}applyNormalMatrix(e){for(let t=0,n=this.count;t<n;t++)ZT.fromBufferAttribute(this,t),ZT.applyNormalMatrix(e),this.setXYZ(t,ZT.x,ZT.y,ZT.z);return this}transformDirection(e){for(let t=0,n=this.count;t<n;t++)ZT.fromBufferAttribute(this,t),ZT.transformDirection(e),this.setXYZ(t,ZT.x,ZT.y,ZT.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=pw(n,this.array)),n}setComponent(e,t,n){return this.normalized&&(n=mw(n,this.array)),this.array[e*this.itemSize+t]=n,this}getX(e){let t=this.array[e*this.itemSize];return this.normalized&&(t=pw(t,this.array)),t}setX(e,t){return this.normalized&&(t=mw(t,this.array)),this.array[e*this.itemSize]=t,this}getY(e){let t=this.array[e*this.itemSize+1];return this.normalized&&(t=pw(t,this.array)),t}setY(e,t){return this.normalized&&(t=mw(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=pw(t,this.array)),t}setZ(e,t){return this.normalized&&(t=mw(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=pw(t,this.array)),t}setW(e,t){return this.normalized&&(t=mw(t,this.array)),this.array[e*this.itemSize+3]=t,this}setXY(e,t,n){return e*=this.itemSize,this.normalized&&(t=mw(t,this.array),n=mw(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=mw(t,this.array),n=mw(n,this.array),r=mw(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=mw(t,this.array),n=mw(n,this.array),r=mw(r,this.array),i=mw(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`})}},tE=class extends eE{constructor(e,t,n){super(new Uint16Array(e),t,n)}},nE=class extends eE{constructor(e,t,n){super(new Uint32Array(e),t,n)}},rE=class extends eE{constructor(e,t,n){super(new Float32Array(e),t,n)}},iE=/*@__PURE__*/ new IT,aE=/*@__PURE__*/ new X,oE=/*@__PURE__*/ new X,sE=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?iE.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;aE.subVectors(e,this.center);let t=aE.lengthSq();if(t>this.radius*this.radius){let e=Math.sqrt(t),n=(e-this.radius)*.5;this.center.addScaledVector(aE,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):(oE.subVectors(e.center,this.center).setLength(e.radius),this.expandByPoint(aE.copy(e.center).add(oE)),this.expandByPoint(aE.copy(e.center).sub(oE))),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}},cE=0,lE=/*@__PURE__*/ new Rw,uE=/*@__PURE__*/ new dT,dE=/*@__PURE__*/ new X,fE=/*@__PURE__*/ new IT,pE=/*@__PURE__*/ new IT,mE=/*@__PURE__*/ new X,hE=class e extends aw{constructor(){super(),this.isBufferGeometry=!0,Object.defineProperty(this,"id",{value:cE++}),this.uuid=lw(),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(YC(e)?nE:tE)(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 lE.makeRotationFromQuaternion(e),this.applyMatrix4(lE),this}rotateX(e){return lE.makeRotationX(e),this.applyMatrix4(lE),this}rotateY(e){return lE.makeRotationY(e),this.applyMatrix4(lE),this}rotateZ(e){return lE.makeRotationZ(e),this.applyMatrix4(lE),this}translate(e,t,n){return lE.makeTranslation(e,t,n),this.applyMatrix4(lE),this}scale(e,t,n){return lE.makeScale(e,t,n),this.applyMatrix4(lE),this}lookAt(e){return uE.lookAt(e),uE.updateMatrix(),this.applyMatrix4(uE.matrix),this}center(){return this.computeBoundingBox(),this.boundingBox.getCenter(dE).negate(),this.translate(dE.x,dE.y,dE.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 rE(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 IT);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];fE.setFromBufferAttribute(n),this.morphTargetsRelative?(mE.addVectors(this.boundingBox.min,fE.min),this.boundingBox.expandByPoint(mE),mE.addVectors(this.boundingBox.max,fE.max),this.boundingBox.expandByPoint(mE)):(this.boundingBox.expandByPoint(fE.min),this.boundingBox.expandByPoint(fE.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 sE);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(fE.setFromBufferAttribute(e),t)for(let e=0,n=t.length;e<n;e++){let n=t[e];pE.setFromBufferAttribute(n),this.morphTargetsRelative?(mE.addVectors(fE.min,pE.min),fE.expandByPoint(mE),mE.addVectors(fE.max,pE.max),fE.expandByPoint(mE)):(fE.expandByPoint(pE.min),fE.expandByPoint(pE.max))}fE.getCenter(n);let r=0;for(let t=0,i=e.count;t<i;t++)mE.fromBufferAttribute(e,t),r=Math.max(r,n.distanceToSquared(mE));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++)mE.fromBufferAttribute(a,t),o&&(dE.fromBufferAttribute(e,t),mE.add(dE)),r=Math.max(r,n.distanceToSquared(mE))}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 eE(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 eE(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++)mE.fromBufferAttribute(e,t),mE.normalize(),e.setXYZ(t,mE.x,mE.y,mE.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 eE(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`})}},gE=/*@__PURE__*/ new X,_E=/*@__PURE__*/ new X,vE=/*@__PURE__*/ new Z,yE=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=gE.subVectors(n,t).cross(_E.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(gE),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||vE.getNormalMatrix(e),r=this.coplanarPoint(gE).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}},bE=0,xE=class extends aw{constructor(){super(),this.isMaterial=!0,Object.defineProperty(this,"id",{value:bE++}),this.uuid=lw(),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 yT(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=GC,this.stencilZFail=GC,this.stencilZPass=GC,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 yT().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 yE().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++}},SE=/*@__PURE__*/ new X,CE=/*@__PURE__*/ new X,wE=/*@__PURE__*/ new X,TE=/*@__PURE__*/ new X,EE=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,SE)),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=SE.subVectors(e,this.origin).dot(this.direction);return t<0?this.origin.distanceToSquared(e):(SE.copy(this.origin).addScaledVector(this.direction,t),SE.distanceToSquared(e))}distanceSqToSegment(e,t,n,r){CE.copy(e).add(t).multiplyScalar(.5),wE.copy(t).sub(e).normalize(),TE.copy(this.origin).sub(CE);let i=e.distanceTo(t)*.5,a=-this.direction.dot(wE),o=TE.dot(this.direction),s=-TE.dot(wE),c=TE.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(CE).addScaledVector(wE,d),f}intersectSphere(e,t){if(e.radius<0)return null;SE.subVectors(e.center,this.origin);let n=SE.dot(this.direction),r=SE.dot(SE)-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,SE)!==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)}},DE=class extends xE{constructor(e){super(),this.isMeshBasicMaterial=!0,this.type=`MeshBasicMaterial`,this.color=new yT(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 Jw,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}},OE=/*@__PURE__*/ new Rw,kE=/*@__PURE__*/ new EE,AE=/*@__PURE__*/ new sE,jE=/*@__PURE__*/ new X,ME=/*@__PURE__*/ new X,NE=/*@__PURE__*/ new X,PE=/*@__PURE__*/ new X,FE=/*@__PURE__*/ new X,IE=/*@__PURE__*/ new X,LE=/*@__PURE__*/ new X,RE=/*@__PURE__*/ new X,zE=class extends dT{constructor(e=new hE,t=new DE){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){IE.set(0,0,0);for(let n=0,r=i.length;n<r;n++){let r=o[n],s=i[n];r!==0&&(FE.fromBufferAttribute(s,e),a?IE.addScaledVector(FE,r):IE.addScaledVector(FE.sub(t),r))}t.add(IE)}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(),AE.copy(n.boundingSphere),AE.applyMatrix4(i),kE.copy(e.ray).recast(e.near),!(AE.containsPoint(kE.origin)===!1&&(kE.intersectSphere(AE,jE)===null||kE.origin.distanceToSquared(jE)>(e.far-e.near)**2))&&(OE.copy(i).invert(),kE.copy(e.ray).applyMatrix4(OE),(n.boundingBox===null||kE.intersectsBox(n.boundingBox)!==!1)&&this._computeIntersections(e,t,kE)))}_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=VE(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=VE(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=VE(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=VE(this,a,e,n,c,l,u,i,o,d),r&&(r.faceIndex=Math.floor(s/3),t.push(r))}}}}};function BE(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;RE.copy(s),RE.applyMatrix4(e.matrixWorld);let l=n.ray.origin.distanceTo(RE);return l<n.near||l>n.far?null:{distance:l,point:RE.clone(),object:e}}function VE(e,t,n,r,i,a,o,s,c,l){e.getVertexPosition(s,ME),e.getVertexPosition(c,NE),e.getVertexPosition(l,PE);let u=BE(e,t,n,r,ME,NE,PE,LE);if(u){let e=new X;FT.getBarycoord(LE,ME,NE,PE,e),i&&(u.uv=FT.getInterpolatedAttribute(i,s,c,l,e,new Y)),a&&(u.uv1=FT.getInterpolatedAttribute(a,s,c,l,e,new Y)),o&&(u.normal=FT.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};FT.getNormal(ME,NE,PE,t.normal),u.face=t,u.barycoord=e}return u}var HE=class extends Mw{constructor(e=null,t=1,n=1,r,i,a,o,s,c=SS,l=SS,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}},UE=/*@__PURE__*/ new sE,WE=/*@__PURE__*/ new Y(.5,.5),GE=/*@__PURE__*/ new X,KE=class{constructor(e=new yE,t=new yE,n=new yE,r=new yE,i=new yE,a=new yE){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=JC,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(),UE.copy(e.boundingSphere).applyMatrix4(e.matrixWorld);else{let t=e.geometry;t.boundingSphere===null&&t.computeBoundingSphere(),UE.copy(t.boundingSphere).applyMatrix4(e.matrixWorld)}return this.intersectsSphere(UE)}intersectsSprite(e){return UE.center.set(0,0,0),UE.radius=.7071067811865476+WE.distanceTo(e.center),UE.applyMatrix4(e.matrixWorld),this.intersectsSphere(UE)}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(GE.x=r.normal.x>0?e.max.x:e.min.x,GE.y=r.normal.y>0?e.max.y:e.min.y,GE.z=r.normal.z>0?e.max.z:e.min.z,r.distanceToPoint(GE)<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)}},qE=class extends Mw{constructor(e,t,n,r,i=TS,a=TS,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()}},JE=class extends qE{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}},YE=class extends Mw{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}},XE=class extends Mw{constructor(e,t,n=NS,r,i,a,o=SS,s=SS,c,l=WS,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 Ow(Object.assign({},e.image)),this.compareFunction=e.compareFunction,this}toJSON(e){let t=super.toJSON(e);return t.compareFunction=this.compareFunction,t}},ZE=class extends XE{constructor(e,t=NS,n=301,r,i,a=SS,o=SS,s,c=WS){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}},QE=class extends Mw{constructor(e=null){super(),this.sourceTexture=e,this.isExternalTexture=!0}copy(e){return super.copy(e),this.sourceTexture=e.sourceTexture,this}},$E=class e extends hE{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 rE(c,3)),this.setAttribute(`normal`,new rE(l,3)),this.setAttribute(`uv`,new rE(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)}},eD=class e extends hE{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 rE(p,3)),this.setAttribute(`normal`,new rE(m,3)),this.setAttribute(`uv`,new rE(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 tD(e){let t={};for(let n in e){t[n]={};for(let r in e[n]){let i=e[n][r];if(rD(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(rD(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 nD(e){let t={};for(let n=0;n<e.length;n++){let r=tD(e[n]);for(let e in r)t[e]=r[e]}return t}function rD(e){return e&&(e.isColor||e.isMatrix3||e.isMatrix4||e.isVector2||e.isVector3||e.isVector4||e.isTexture||e.isQuaternion)}function iD(e){let t=[];for(let n=0;n<e.length;n++)t.push(e[n].clone());return t}function aD(e){let t=e.getRenderTarget();return t===null?e.outputColorSpace:t.isXRRenderTarget===!0?t.texture.colorSpace:Sw.workingColorSpace}var oD={clone:tD,merge:nD},sD=`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
|
-
}`,lD=class extends xE{constructor(e){super(),this.isShaderMaterial=!0,this.type=`ShaderMaterial`,this.defines={},this.uniforms={},this.uniformsGroups=[],this.vertexShader=sD,this.fragmentShader=cD,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=tD(e.uniforms),this.uniformsGroups=iD(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 yT().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 Nw().fromArray(r.value);break;case`m3`:this.uniforms[n].value=new Z().fromArray(r.value);break;case`m4`:this.uniforms[n].value=new Rw().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 lD{constructor(e){super(e),this.isRawShaderMaterial=!0,this.type=`RawShaderMaterial`}},dD=class extends xE{constructor(e){super(),this.isMeshDepthMaterial=!0,this.type=`MeshDepthMaterial`,this.depthPacking=BC,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}},fD=class extends xE{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 pD(e,t){return!e||e.constructor===t?e:typeof t.BYTES_PER_ELEMENT==`number`?new t(e):Array.prototype.slice.call(e)}function mD(e){return e!==void 0&&e.inTangents!==void 0&&e.outTangents!==void 0}var hD=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_(){}},gD=class extends hD{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:LC,endingEnd:LC}}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 RC:i=e,o=2*t-n;break;case zC: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 RC:a=e,s=2*n-t;break;case zC: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}},_D=class extends hD{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}},vD=class extends hD{constructor(e,t,n,r){super(e,t,n,r)}interpolate_(e){return this.copySampleValue_(e-1)}},yD=class extends hD{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=SD(n,t,g,y,r);i[p]=bD(x,o,_,b,m)}return i}};function bD(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 xD(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 SD(e,t,n,r,i){let a=(e-t)/(i-t);for(let o=0;o<8;o++){let o=bD(a,t,n,r,i)-e;if(Math.abs(o)<1e-10)break;let s=xD(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 CD=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=pD(t,this.TimeBufferType),this.values=pD(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:pD(e.times,Array),values:pD(e.values,Array)};let t=e.getInterpolation();t!==e.DefaultInterpolation&&(n.interpolation=t),mD(e.settings)&&(n.settings={inTangents:pD(e.settings.inTangents,Array),outTangents:pD(e.settings.outTangents,Array)})}return n.type=e.ValueTypeName,n}InterpolantFactoryMethodDiscrete(e){return new vD(this.times,this.values,this.getValueSize(),e)}InterpolantFactoryMethodLinear(e){return new _D(this.times,this.values,this.getValueSize(),e)}InterpolantFactoryMethodSmooth(e){return new gD(this.times,this.values,this.getValueSize(),e)}InterpolantFactoryMethodBezier(e){let t=new yD(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 NC:t=this.InterpolantFactoryMethodDiscrete;break;case PC:t=this.InterpolantFactoryMethodLinear;break;case FC:t=this.InterpolantFactoryMethodSmooth;break;case IC: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 NC;case this.InterpolantFactoryMethodLinear:return PC;case this.InterpolantFactoryMethodSmooth:return FC;case this.InterpolantFactoryMethodBezier:return IC}}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;mD(this.settings)&&(wD(this.settings.inTangents,e),wD(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&&XC(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()===FC,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,mD(this.settings)&&(r.settings={inTangents:this.settings.inTangents.slice(),outTangents:this.settings.outTangents.slice()}),r}};function wD(e,t){for(let n=0,r=e.length;n!==r;n+=2)e[n]*=t}CD.prototype.ValueTypeName=``,CD.prototype.TimeBufferType=Float32Array,CD.prototype.ValueBufferType=Float32Array,CD.prototype.DefaultInterpolation=PC;var TD=class extends CD{constructor(e,t,n){super(e,t,n)}};TD.prototype.ValueTypeName=`bool`,TD.prototype.ValueBufferType=Array,TD.prototype.DefaultInterpolation=NC,TD.prototype.InterpolantFactoryMethodLinear=void 0,TD.prototype.InterpolantFactoryMethodSmooth=void 0;var ED=class extends CD{constructor(e,t,n,r){super(e,t,n,r)}};ED.prototype.ValueTypeName=`color`;var DD=class extends CD{constructor(e,t,n,r){super(e,t,n,r)}};DD.prototype.ValueTypeName=`number`;var OD=class extends hD{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)hw.slerpFlat(i,0,a,c-o,a,c,s);return i}},kD=class extends CD{constructor(e,t,n,r){super(e,t,n,r)}InterpolantFactoryMethodLinear(e){return new OD(this.times,this.values,this.getValueSize(),e)}};kD.prototype.ValueTypeName=`quaternion`,kD.prototype.InterpolantFactoryMethodSmooth=void 0;var AD=class extends CD{constructor(e,t,n){super(e,t,n)}};AD.prototype.ValueTypeName=`string`,AD.prototype.ValueBufferType=Array,AD.prototype.DefaultInterpolation=NC,AD.prototype.InterpolantFactoryMethodLinear=void 0,AD.prototype.InterpolantFactoryMethodSmooth=void 0;var jD=class extends CD{constructor(e,t,n,r){super(e,t,n,r)}};jD.prototype.ValueTypeName=`vector`;var MD=/*@__PURE__*/ new X,ND=/*@__PURE__*/ new hw,PD=/*@__PURE__*/ new X,FD=class extends dT{constructor(){super(),this.isCamera=!0,this.type=`Camera`,this.matrixWorldInverse=new Rw,this.projectionMatrix=new Rw,this.projectionMatrixInverse=new Rw,this.coordinateSystem=JC,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(MD,ND,PD),PD.x===1&&PD.y===1&&PD.z===1?this.matrixWorldInverse.copy(this.matrixWorld).invert():this.matrixWorldInverse.compose(MD,ND,PD.set(1,1,1)).invert()}updateWorldMatrix(e,t,n=!1){super.updateWorldMatrix(e,t,n),this.matrixWorld.decompose(MD,ND,PD),PD.x===1&&PD.y===1&&PD.z===1?this.matrixWorldInverse.copy(this.matrixWorld).invert():this.matrixWorldInverse.compose(MD,ND,PD.set(1,1,1)).invert()}clone(){return new this.constructor().copy(this)}},ID=/*@__PURE__*/ new X,LD=/*@__PURE__*/ new Y,RD=/*@__PURE__*/ new Y,zD=class extends FD{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=cw*2*Math.atan(t),this.updateProjectionMatrix()}getFocalLength(){let e=Math.tan(sw*.5*this.fov);return .5*this.getFilmHeight()/e}getEffectiveFOV(){return cw*2*Math.atan(Math.tan(sw*.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){ID.set(-1,-1,.5).applyMatrix4(this.projectionMatrixInverse),t.set(ID.x,ID.y).multiplyScalar(-e/ID.z),ID.set(1,1,.5).applyMatrix4(this.projectionMatrixInverse),n.set(ID.x,ID.y).multiplyScalar(-e/ID.z)}getViewSize(e,t){return this.getViewBounds(e,LD,RD),t.subVectors(RD,LD)}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(sw*.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}},BD=class extends FD{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}},VD=-90,HD=1,UD=class extends dT{constructor(e,t,n){super(),this.type=`CubeCamera`,this.renderTarget=n,this.coordinateSystem=null,this.activeMipmapLevel=0;let r=new zD(VD,HD,e,t);r.layers=this.layers,this.add(r);let i=new zD(VD,HD,e,t);i.layers=this.layers,this.add(i);let a=new zD(VD,HD,e,t);a.layers=this.layers,this.add(a);let o=new zD(VD,HD,e,t);o.layers=this.layers,this.add(o);let s=new zD(VD,HD,e,t);s.layers=this.layers,this.add(s);let c=new zD(VD,HD,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}},WD=class extends zD{constructor(e=[]){super(),this.isArrayCamera=!0,this.isMultiViewCamera=!1,this.cameras=e}},GD=`\\[\\]\\.:\\/`,KD=/* @__PURE__ */ RegExp(`[\\[\\]\\.:\\/]`,`g`),qD=`[^\\[\\]\\.:\\/]`,JD=`[^`+GD.replace(`\\.`,``)+`]`,YD=/*@__PURE__*/ `((?:WC+[\\/:])*)`.replace(`WC`,qD),XD=/*@__PURE__*/ `(WCOD+)?`.replace(`WCOD`,JD),ZD=/*@__PURE__*/ `(?:\\.(WC+)(?:\\[(.+)\\])?)?`.replace(`WC`,qD),QD=/*@__PURE__*/ `\\.(WC+)(?:\\[(.+)\\])?`.replace(`WC`,qD),$D=RegExp(`^`+YD+XD+ZD+QD+`$`),eO=[`material`,`materials`,`bones`,`map`],tO=class{constructor(e,t,n){let r=n||nO.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()}},nO=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(KD,``)}static parseTrackName(e){let t=$D.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);eO.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}};nO.Composite=tO,nO.prototype.BindingType={Direct:0,EntireArray:1,ArrayElement:2,HasFromToArray:3},nO.prototype.Versioning={None:0,NeedsUpdate:1,MatrixWorldNeedsUpdate:2},nO.prototype.GetterByBindingType=[nO.prototype._getValue_direct,nO.prototype._getValue_array,nO.prototype._getValue_arrayElement,nO.prototype._getValue_toArray],nO.prototype.SetterByBindingTypeAndVersioning=[[nO.prototype._setValue_direct,nO.prototype._setValue_direct_setNeedsUpdate,nO.prototype._setValue_direct_setMatrixWorldNeedsUpdate],[nO.prototype._setValue_array,nO.prototype._setValue_array_setNeedsUpdate,nO.prototype._setValue_array_setMatrixWorldNeedsUpdate],[nO.prototype._setValue_arrayElement,nO.prototype._setValue_arrayElement_setNeedsUpdate,nO.prototype._setValue_arrayElement_setMatrixWorldNeedsUpdate],[nO.prototype._setValue_fromArray,nO.prototype._setValue_fromArray_setNeedsUpdate,nO.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 rO(e,t,n,r){let i=iO(r);switch(n){case VS:return e*t;case KS:return e*t/i.components*i.byteLength;case qS:return e*t/i.components*i.byteLength;case JS:return e*t*2/i.components*i.byteLength;case YS:return e*t*2/i.components*i.byteLength;case HS:return e*t*3/i.components*i.byteLength;case US:return e*t*4/i.components*i.byteLength;case XS:return e*t*4/i.components*i.byteLength;case ZS:case QS:return Math.floor((e+3)/4)*Math.floor((t+3)/4)*8;case $S:case eC:return Math.floor((e+3)/4)*Math.floor((t+3)/4)*16;case nC:case iC:return Math.max(e,16)*Math.max(t,8)/4;case tC:case rC:return Math.max(e,8)*Math.max(t,8)/2;case aC:case oC:case cC:case lC:return Math.floor((e+3)/4)*Math.floor((t+3)/4)*8;case sC:case uC:case dC:return Math.floor((e+3)/4)*Math.floor((t+3)/4)*16;case fC:return Math.floor((e+3)/4)*Math.floor((t+3)/4)*16;case pC:return Math.floor((e+4)/5)*Math.floor((t+3)/4)*16;case mC:return Math.floor((e+4)/5)*Math.floor((t+4)/5)*16;case hC:return Math.floor((e+5)/6)*Math.floor((t+4)/5)*16;case gC:return Math.floor((e+5)/6)*Math.floor((t+5)/6)*16;case _C:return Math.floor((e+7)/8)*Math.floor((t+4)/5)*16;case vC:return Math.floor((e+7)/8)*Math.floor((t+5)/6)*16;case yC:return Math.floor((e+7)/8)*Math.floor((t+7)/8)*16;case bC:return Math.floor((e+9)/10)*Math.floor((t+4)/5)*16;case xC:return Math.floor((e+9)/10)*Math.floor((t+5)/6)*16;case SC:return Math.floor((e+9)/10)*Math.floor((t+7)/8)*16;case CC:return Math.floor((e+9)/10)*Math.floor((t+9)/10)*16;case wC:return Math.floor((e+11)/12)*Math.floor((t+9)/10)*16;case TC:return Math.floor((e+11)/12)*Math.floor((t+11)/12)*16;case EC:case DC:case OC:return Math.ceil(e/4)*Math.ceil(t/4)*16;case kC:case AC:return Math.ceil(e/4)*Math.ceil(t/4)*8;case jC:case MC:return Math.ceil(e/4)*Math.ceil(t/4)*16}throw Error(`Unable to determine texture byte length for ${n} format.`)}function iO(e){switch(e){case OS:case kS:return{byteLength:1,components:1};case jS:case AS:case FS:return{byteLength:2,components:1};case IS:case LS:return{byteLength:2,components:4};case NS:case MS:case PS:return{byteLength:4,components:1};case zS:case BS: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 aO(){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 oO(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 yT(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 yT(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 yT(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 yT(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}}},sO={basic:{uniforms:/*@__PURE__*/ nD([$.common,$.specularmap,$.envmap,$.aomap,$.lightmap,$.fog]),vertexShader:Q.meshbasic_vert,fragmentShader:Q.meshbasic_frag},lambert:{uniforms:/*@__PURE__*/ nD([$.common,$.specularmap,$.envmap,$.aomap,$.lightmap,$.emissivemap,$.bumpmap,$.normalmap,$.displacementmap,$.fog,$.lights,{emissive:{value:/*@__PURE__*/ new yT(0)},envMapIntensity:{value:1}}]),vertexShader:Q.meshlambert_vert,fragmentShader:Q.meshlambert_frag},phong:{uniforms:/*@__PURE__*/ nD([$.common,$.specularmap,$.envmap,$.aomap,$.lightmap,$.emissivemap,$.bumpmap,$.normalmap,$.displacementmap,$.fog,$.lights,{emissive:{value:/*@__PURE__*/ new yT(0)},specular:{value:/*@__PURE__*/ new yT(1118481)},shininess:{value:30},envMapIntensity:{value:1}}]),vertexShader:Q.meshphong_vert,fragmentShader:Q.meshphong_frag},standard:{uniforms:/*@__PURE__*/ nD([$.common,$.envmap,$.aomap,$.lightmap,$.emissivemap,$.bumpmap,$.normalmap,$.displacementmap,$.roughnessmap,$.metalnessmap,$.fog,$.lights,{emissive:{value:/*@__PURE__*/ new yT(0)},roughness:{value:1},metalness:{value:0},envMapIntensity:{value:1}}]),vertexShader:Q.meshphysical_vert,fragmentShader:Q.meshphysical_frag},toon:{uniforms:/*@__PURE__*/ nD([$.common,$.aomap,$.lightmap,$.emissivemap,$.bumpmap,$.normalmap,$.displacementmap,$.gradientmap,$.fog,$.lights,{emissive:{value:/*@__PURE__*/ new yT(0)}}]),vertexShader:Q.meshtoon_vert,fragmentShader:Q.meshtoon_frag},matcap:{uniforms:/*@__PURE__*/ nD([$.common,$.bumpmap,$.normalmap,$.displacementmap,$.fog,{matcap:{value:null}}]),vertexShader:Q.meshmatcap_vert,fragmentShader:Q.meshmatcap_frag},points:{uniforms:/*@__PURE__*/ nD([$.points,$.fog]),vertexShader:Q.points_vert,fragmentShader:Q.points_frag},dashed:{uniforms:/*@__PURE__*/ nD([$.common,$.fog,{scale:{value:1},dashSize:{value:1},totalSize:{value:2}}]),vertexShader:Q.linedashed_vert,fragmentShader:Q.linedashed_frag},depth:{uniforms:/*@__PURE__*/ nD([$.common,$.displacementmap]),vertexShader:Q.depth_vert,fragmentShader:Q.depth_frag},normal:{uniforms:/*@__PURE__*/ nD([$.common,$.bumpmap,$.normalmap,$.displacementmap,{opacity:{value:1}}]),vertexShader:Q.meshnormal_vert,fragmentShader:Q.meshnormal_frag},sprite:{uniforms:/*@__PURE__*/ nD([$.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__*/ nD([$.common,$.displacementmap,{referencePosition:{value:/*@__PURE__*/ new X},nearDistance:{value:1},farDistance:{value:1e3}}]),vertexShader:Q.distance_vert,fragmentShader:Q.distance_frag},shadow:{uniforms:/*@__PURE__*/ nD([$.lights,$.fog,{color:{value:/*@__PURE__*/ new yT(0)},opacity:{value:1}}]),vertexShader:Q.shadow_vert,fragmentShader:Q.shadow_frag}};sO.physical={uniforms:/*@__PURE__*/ nD([sO.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 yT(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 yT(0)},specularColor:{value:/*@__PURE__*/ new yT(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 cO={r:0,b:0,g:0},lO=/*@__PURE__*/ new Rw,uO=/*@__PURE__*/ new Z;uO.set(-1,0,0,0,1,0,0,0,1);function dO(e,t,n,r,i,a){let o=new yT(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 zE(new $E(1,1,1),new lD({name:`BackgroundCubeMaterial`,uniforms:tD(sO.backgroundCube.uniforms),vertexShader:sO.backgroundCube.vertexShader,fragmentShader:sO.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(lO.makeRotationFromEuler(n.backgroundRotation)).transpose(),i.isCubeTexture&&i.isRenderTargetTexture===!1&&l.material.uniforms.backgroundRotation.value.premultiply(uO),l.material.toneMapped=Sw.getTransfer(i.colorSpace)!==WC,(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 zE(new eD(2,2),new lD({name:`BackgroundMaterial`,uniforms:tD(sO.background.uniforms),vertexShader:sO.background.vertexShader,fragmentShader:sO.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=Sw.getTransfer(i.colorSpace)!==WC,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(cO,aD(e)),n.buffers.color.setClear(cO.r,cO.g,cO.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 fO(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 pO(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 mO(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 hO(e){let t=this,n=null,r=0,i=!1,a=!1,o=new yE,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 gO=4,_O=6,vO=20,yO=256,bO=/*@__PURE__*/ new BD,xO=/*@__PURE__*/ new yT,SO=null,CO=0,wO=0,TO=!1,EO=/*@__PURE__*/ new X,DO=/*@__PURE__*/ new X,OO=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=EO}=i;SO=this._renderer.getRenderTarget(),CO=this._renderer.getActiveCubeFace(),wO=this._renderer.getActiveMipmapLevel(),TO=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=FO(),this._compileMaterial(this._cubemapMaterial))}compileEquirectangularShader(){this._equirectMaterial===null&&(this._equirectMaterial=PO(),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(SO,CO,wO),this._renderer.xr.enabled=TO,e.scissorTest=!1,jO(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),SO=this._renderer.getRenderTarget(),CO=this._renderer.getActiveCubeFace(),wO=this._renderer.getActiveMipmapLevel(),TO=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:TS,minFilter:TS,generateMipmaps:!1,type:FS,format:US,colorSpace:HC,depthBuffer:!1},r=AO(e,t,n);if(this._pingPongRenderTarget===null||this._pingPongRenderTarget.width!==e||this._pingPongRenderTarget.height!==t){this._pingPongRenderTarget!==null&&this._dispose(),this._pingPongRenderTarget=AO(e,t,n);let{_lodMax:r}=this;({lodMeshes:this._lodMeshes,sizeLods:this._sizeLods}=kO(r)),this._blurMaterial=NO(r,e,t),this._ggxMaterial=MO(r,e,t)}return r}_compileMaterial(e){let t=new zE(new hE,e);this._renderer.compile(t,bO)}_sceneToCubeUV(e,t,n,r,i){let a=new zD(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(xO),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 zE(new $E,new DE({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(xO),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;jO(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=FO()),this._cubemapMaterial.uniforms.flipEnvMap.value=e.isRenderTargetTexture===!1?-1:1):this._equirectMaterial===null&&(this._equirectMaterial=PO());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;jO(t,0,0,3*s,2*s),n.setRenderTarget(t),n.render(a,bO)}_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-gO?n-d+gO:0),m=4*(this._cubeSize-f);s.envMap.value=e.texture,s.roughness.value=u,s.mipInt.value=d-t,jO(i,p,m,3*f,2*f),r.setRenderTarget(i),r.render(o,bO),s.envMap.value=i.texture,s.roughness.value=0,s.mipInt.value=d-n,jO(e,p,m,3*f,2*f),r.setRenderTarget(e),r.render(o,bO)}_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];jO(t,3*l*(r>this._lodMax-gO?r-this._lodMax+gO:0),4*(this._cubeSize-l),3*l,2*l),a.setRenderTarget(t),a.render(s,bO)}};function kO(e){let t=[],n=[],r=e,i=e-gO+1+_O;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?DO.set(1,r,n):e===1?DO.set(-n,1,-r):e===2?DO.set(-n,r,1):e===3?DO.set(-1,r,-n):e===4?DO.set(-n,-1,r):DO.set(n,r,-1),DO.toArray(l,(e*6+t)*3)}}let u=new hE;u.setAttribute(`position`,new eE(c,3)),u.setAttribute(`outputDirection`,new eE(l,3)),n.push(new zE(u,null)),r>gO&&r--}return{lodMeshes:n,sizeLods:t}}function AO(e,t,n){let r=new Fw(e,t,n);return r.texture.mapping=306,r.texture.name=`PMREM.cubeUv`,r.scissorTest=!0,r}function jO(e,t,n,r,i){e.viewport.set(t,n,r,i),e.scissor.set(t,n,r,i)}function MO(e,t,n){return new lD({name:`PMREMGGXConvolution`,defines:{GGX_SAMPLES:yO,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:IO(),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 $k(i,h),T=mA(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,tA)),E},this.destroy=function(){r.releaseStatesOfProgram(this),i.deleteProgram(h),this.program=void 0},this.type=n.shaderType,this.name=n.shaderName,this.id=nA++,this.cacheKey=t,this.usedTimes=1,this.program=h,this.vertexShader=x,this.fragmentShader=S,this}var IA=0,LA=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 RA(e),t.set(e,n)),n}},RA=class{constructor(e){this.id=IA++,this.code=e,this.usedTimes=0}};function zA(e){return e===1030||e===37490||e===36285}function BA(e,t,n,r,i,a){let o=new Yw,s=new LA,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=sO[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:Sw.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&&zA(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&&Sw.getTransfer(i.map.colorSpace)===`srgb`,decodeVideoTextureEmissive:le&&i.emissiveMap.isVideoTexture===!0&&Sw.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=sO[t];n=oD.clone(e.uniforms)}else n=e.uniforms;return n}function b(t,n){let r=u.get(n);return r===void 0?(r=new FA(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 VA(){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 HA(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 UA(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 WA(){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||HA),r.length>1&&r.sort(t||UA),i.length>1&&i.sort(t||UA)}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 GA(){let e=/* @__PURE__ */ new WeakMap;function t(t,n){let r=e.get(t),i;return r===void 0?(i=new WA,e.set(t,[i])):n>=r.length?(i=new WA,r.push(i)):i=r[n],i}function n(){e=/* @__PURE__ */ new WeakMap}return{get:t,dispose:n}}function KA(){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 yT};break;case`SpotLight`:n={position:new X,direction:new X,color:new yT,distance:0,coneCos:0,penumbraCos:0,decay:0};break;case`PointLight`:n={position:new X,color:new yT,distance:0,decay:0};break;case`HemisphereLight`:n={direction:new X,skyColor:new yT,groundColor:new yT};break;case`RectAreaLight`:n={color:new yT,position:new X,halfWidth:new X,halfHeight:new X}}return e[t.id]=n,n}}}function qA(){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 JA=0;function YA(e,t){return(t.castShadow?2:0)-(e.castShadow?2:0)+ +!!t.map-!!e.map}function XA(e){let t=new KA,n=qA(),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 Rw,o=new Rw;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(YA);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=JA++)}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 ZA(e){let t=new XA(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 QA(e){let t=/* @__PURE__ */ new WeakMap;function n(n,r=0){let i=t.get(n),a;return i===void 0?(a=new ZA(e),t.set(n,[a])):r>=i.length?(a=new ZA(e),i.push(a)):a=i[r],a}function r(){t=/* @__PURE__ */ new WeakMap}return{get:n,dispose:r}}var $A=`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
|
-
}`,tj=[/*@__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)],nj=[/*@__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)],rj=/*@__PURE__*/ new Rw,ij=/*@__PURE__*/ new X,aj=/*@__PURE__*/ new X;function oj(e,t,n){let r=new KE,i=new Y,a=new Y,o=new Nw,s=new dD,c=new fD,l={},u=n.maxTextureSize,d={0:1,1:0,2:2},f=new lD({defines:{VSM_SAMPLES:8},uniforms:{shadow_pass:{value:null},resolution:{value:new Y},radius:{value:4}},vertexShader:$A,fragmentShader:ej}),p=f.clone();p.defines.HORIZONTAL_PASS=1;let m=new hE;m.setAttribute(`position`,new eE(new Float32Array([-1,-1,.5,3,-1,.5,-1,3,.5]),3));let h=new zE(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 Fw(i.x,i.y,{format:JS,type:FS,minFilter:TS,magFilter:TS,generateMipmaps:!1}),d.map.texture.name=l.name+`.shadowMap`,d.map.depthTexture=new XE(i.x,i.y,PS),d.map.depthTexture.name=l.name+`.shadowMapDepth`,d.map.depthTexture.format=WS,d.map.depthTexture.compareFunction=null,d.map.depthTexture.minFilter=SS,d.map.depthTexture.magFilter=SS}else l.isPointLight?(d.map=new LO(i.x),d.map.depthTexture=new ZE(i.x,NS)):(d.map=new Fw(i.x,i.y),d.map.depthTexture=new XE(i.x,i.y,NS)),d.map.depthTexture.name=l.name+`.shadowMap`,d.map.depthTexture.format=WS,this.type===1?(d.map.depthTexture.compareFunction=h?518:515,d.map.depthTexture.minFilter=TS,d.map.depthTexture.magFilter=TS):(d.map.depthTexture.compareFunction=null,d.map.depthTexture.minFilter=SS,d.map.depthTexture.magFilter=SS);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()),ij.setFromMatrixPosition(l.matrixWorld),e.position.copy(ij),aj.copy(e.position),aj.add(tj[t]),e.up.copy(nj[t]),e.lookAt(aj),e.updateMatrixWorld(),n.makeTranslation(-ij.x,-ij.y,-ij.z),rj.multiplyMatrices(e.projectionMatrix,e.matrixWorldInverse),d._frustum.setFromProjectionMatrix(rj,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 Fw(i.x,i.y,{format:JS,type:FS}):(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 sj(e,t){function n(){let t=!1,n=new Nw,r=null,i=new Nw(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=iw[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 yT(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 Nw().fromArray(N),se=new Nw().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 yT(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 cj(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):ZC(`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?UC:Sw.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={[yS]:e.REPEAT,[bS]:e.CLAMP_TO_EDGE,[xS]:e.MIRRORED_REPEAT},ae={[SS]:e.NEAREST,[CS]:e.NEAREST_MIPMAP_NEAREST,[wS]:e.NEAREST_MIPMAP_LINEAR,[TS]:e.LINEAR,[ES]:e.LINEAR_MIPMAP_NEAREST,[DS]: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=Sw.getPrimaries(Sw.workingColorSpace),r=o.colorSpace===``?null:Sw.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===GS,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=rO(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=rO(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=Sw.getPrimaries(Sw.workingColorSpace),r=o.colorSpace===``?null:Sw.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!==``&&(Sw.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 lj(e,t){function n(n,r=``){let i,a=Sw.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=`
|
|
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
|
-
}`,fj=class{constructor(){this.texture=null,this.mesh=null,this.depthNear=0,this.depthFar=0}init(e,t){if(this.texture===null){let n=new QE(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 lD({vertexShader:uj,fragmentShader:dj,uniforms:{depthColor:{value:this.texture},depthWidth:{value:t.z},depthHeight:{value:t.w}}});this.mesh=new zE(new eD(20,20),n)}return this.mesh}reset(){this.texture=null,this.mesh=null}getDepthTexture(){return this.texture}},pj=class extends aw{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 fj,g={},_=t.getContextAttributes(),v=null,y=null,b=[],x=[],S=new Y,C=null,w=null,T=new zD;T.viewport=new Nw;let E=new zD;E.viewport=new Nw;let D=[T,E],O=new WD,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 mT,b[e]=t),t.getTargetRaySpace()},this.getControllerGrip=function(e){let t=b[e];return t===void 0&&(t=new mT,b[e]=t),t.getGripSpace()},this.getHand=function(e){let t=b[e];return t===void 0&&(t=new mT,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?GS:WS,a=_.stencil?RS:NS);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 Fw(d.textureWidth,d.textureHeight,{format:US,type:OS,depthTexture:new XE(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 Fw(f.framebufferWidth,f.framebufferHeight,{format:US,type:OS,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=cw*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 zD,o.layers.enable(n),o.viewport=new Nw,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 QE,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 aO;se.setAnimationLoop(oe),this.setAnimationLoop=function(e){ae=e},this.dispose=function(){}}},mj=/*@__PURE__*/ new Rw,hj=/*@__PURE__*/ new Z;hj.set(-1,0,0,0,1,0,0,0,1);function gj(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,aD(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(mj.makeRotationFromEuler(o)).transpose(),a.isCubeTexture&&a.isRenderTargetTexture===!1&&e.envMapRotation.value.premultiply(hj),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 _j(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 vj=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]),yj=null;function bj(){return yj===null&&(yj=new HE(vj,16,16,JS,FS),yj.name=`DFG_LUT`,yj.minFilter=TS,yj.magFilter=TS,yj.wrapS=bS,yj.wrapT=bS,yj.generateMipmaps=!1,yj.needsUpdate=!0),yj}var xj=class{constructor(e={}){let{canvas:t=QC(),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=OS}=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([XS,YS,qS]),g=/* @__PURE__ */ new Set([OS,NS,jS,RS,IS,LS]),_=/* @__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=VC;let ee=0,te=0,j=null,ne=-1,re=null,M=new Nw,ie=new Nw,N=null,ae=new yT(0),oe=0,se=t.width,ce=t.height,le=1,ue=null,de=null,fe=new Nw(0,0,se,ce),pe=new Nw(0,0,se,ce),me=!1,he=new KE,ge=!1,_e=!1,ve=new Rw,ye=new X,be=new Nw,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 zO(P),Te.init(),He=new lj(P,Te),Ee=new mO(P,Te,e,He),F=new sj(P,Te),Ee.reversedDepthBuffer&&d&&F.buffers.depth.setReversed(!0),O=P.createFramebuffer(),k=P.createFramebuffer(),A=P.createFramebuffer(),De=new HO(P),I=new VA,L=new cj(P,Te,F,I,Ee,He,De),Oe=new RO(T),ke=new oO(P),Ue=new fO(P,ke),Ae=new BO(P,ke,De,Ue),je=new WO(P,Ae,ke,Ue,De),ze=new UO(P,Ee,L),Ie=new hO(I),Me=new BA(T,Oe,Te,Ee,Ue,Ie),Ne=new gj(T,I),Pe=new GA,Fe=new QA(Te),Re=new dO(T,Oe,F,je,p,s),Le=new oj(T,je,Ee),We=new _j(P,De,Ee,F),Be=new pO(P,Te,De),Ve=new VO(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 KO(m,t.width,t.height,o,r,i));let Ke=new pj(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(),ew(`WebGLRenderer: Context Lost.`),E=!0}function Je(){ew(`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 aO;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,JC,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 Fw(1,1,{generateMipmaps:!0,type:e?FS:OS,minFilter:DS,samples:Math.max(4,Ee.samples),stencilBuffer:i,resolveDepthBuffer:!1,resolveStencilBuffer:!1,storeMultisampledDepthBuffer:!1,storeMultisampledStencilBuffer:!1,colorSpace:Sw.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=$k.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:Sw.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=bj()),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)}$k.upload(P,dt(v),k,L)}if(r.isShaderMaterial&&r.uniformsNeedUpdate===!0&&($k.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 rw(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 JC}get outputColorSpace(){return this._outputColorSpace}set outputColorSpace(e){this._outputColorSpace=e;let t=this.getContext();t.drawingBufferColorSpace=Sw._getDrawingBufferColorSpace(e),t.unpackColorSpace=Sw._getUnpackColorSpace()}},Sj={request:e=>{e()},cancel:()=>{}};function Cj(e){return new Z().set(...e)}var wj=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=Xl(Yl,r.colorSpace.matrix);i!==this.named[t]&&(this.named[t]=i,this.uniform.value[t]=Cj(uu(n.displayConversion.matrix,i)))}}};function Tj(e){return Number.isSafeInteger(e)?e.toFixed(1):String(e)}var Ej=0,Dj=1,Oj=[[`CONVERSION_HLG_TO_SDR_BT709`,Dj],[`HLG_A`,Tj(Zl.a)],[`HLG_B`,Tj(Zl.b)],[`HLG_C`,Tj(Zl.c)],[`HLG_SEGMENT_JOIN`,Tj(Zl.segmentJoin)],[`HLG_SQUARE_SEGMENT_DIVISOR`,Tj(Zl.squareSegmentDivisor)],[`HLG_LOG_SEGMENT_DIVISOR`,Tj(Zl.logSegmentDivisor)],[`BT709_LUMINANCE_RED`,Tj($l[0])],[`BT709_LUMINANCE_GREEN`,Tj($l[1])],[`BT709_LUMINANCE_BLUE`,Tj($l[2])]];function kj(e){let t=e.map(e=>Aj(e.displayConversion));return{uLensConversion:{value:t.map(e=>e.kind)},uLensMatrixCorrection:{value:e.map(()=>Cj(Mr))},uLensGamut:{value:t.map(e=>e.gamut)},uLensTone:{value:t.map(e=>e.tone)}}}function Aj(e){switch(e.kind){case`as-recorded`:return{kind:Ej,gamut:Cj(Mr),tone:new Nw};case`hlg-to-sdr-bt709`:{let{exposure:t,kneeStart:n,ceiling:r,exponent:i}=e.tone;return{kind:Dj,gamut:Cj(e.gamut),tone:new Nw(t,n,r,i)}}}}var jj={fast:{minFilter:TS,generateMipmaps:!1,anisotropy:1,shaderSampling:0},balanced:{minFilter:DS,generateMipmaps:!0,anisotropy:4,shaderSampling:1},high:{minFilter:DS,generateMipmaps:!0,anisotropy:8,shaderSampling:2}},Mj=0,Nj=1,Pj=Object.fromEntries([[`MAX_LENSES`,2],[`LENS_MEI`,Mj],[`LENS_RADIAL_POLYNOMIAL`,Nj],[`MEI_RADIAL_TERMS`,oe.radial],[`MEI_TANGENTIAL_ORDERS`,oe.tangential],[`MEI_THIN_PRISM_ORDERS`,oe.thinPrism],...Oj,[`SAMPLING_BILINEAR`,0],[`SAMPLING_TRILINEAR`,1],[`SAMPLING_SUPERSAMPLED`,2]]);function Fj(e,t){let n=Zj(e.lenses,`a stitching setup has one or two lenses`);return{...Ij(e),...Lj(n),...Hj(n),...kj(n),uTexture0:{value:t[0]??null},uTexture1:{value:t[1]??null}}}function Ij(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 Nw(0,0,1,1))},uFeather:{value:new Y(e.feather.start,e.feather.end)}}}function Lj(e){let t=e.map(e=>zj(e.projection));return{uLensRotation:{value:e.map(e=>Cj(e.rotation))},uLensKind:{value:t.map(e=>e.kind)},uLensPrincipalPoint:{value:e.map(e=>Xj(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 Rj={radial:[],tangential:[],thinPrism:[]};function zj(e){switch(e.kind){case`mei`:return{kind:Mj,focal:new Y(...e.focal),xi:e.xi,...Bj(e.distortion),polynomial:new Nw};case`radial-polynomial`:return{kind:Nj,focal:new Y,xi:0,...Bj(Rj),polynomial:new Nw(...e.coefficients)}}}function Bj(e){return{radial:Vj(e.radial,oe.radial,()=>0),tangential:Vj(e.tangential.map(e=>new Y(e.p1,e.p2)),oe.tangential,()=>new Y),thinPrism:Vj(e.thinPrism.map(e=>new Y(e.x,e.y)),oe.thinPrism,()=>new Y)}}function Vj(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 Hj(e){return{uLensWindow:{value:e.map(e=>new Nw(e.window.x,e.window.y,e.window.width,e.window.height))},uLensRegion:{value:e.map(e=>new Nw(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 Uj(e,t){e.uSampling.value=t.shaderSampling}function Wj(e,t){e.uStabilization.value=Cj(t)}function Gj(e,t,n){ae(t,e.uLensCount.value,`lens`),e.uLensGain.value[t]?.set(...n)}var Kj={rotation:Mr,planeHalfExtent:1,pictureAspect:1};function qj(e,t,n){let r=Jj(t,n);e.uViewRotation.value=Cj(r.rotation),e.uPlaneHalfExtent.value=r.planeHalfExtent,e.uPictureAspect.value=r.pictureAspect,e.uScreenArea.value=Zj(r.areas,`a picture fills one area per lens at most`).map(e=>Yj(e))}function Jj(e,t){switch(e.kind){case`rectilinear`:return{rotation:e.rotation,planeHalfExtent:Rc(e.fieldOfView),pictureAspect:zc(e.area,t),areas:[e.area]};case`equirectangular`:return{...Kj,rotation:e.rotation,areas:[e.area]};case`lens-tiles`:return{...Kj,areas:e.tiles}}}function Yj(e){return new Nw(e.x,e.y,e.width,e.height)}function Xj(e){return new Y(e.x,e.y)}function Zj(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 Qj=`// 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
|
-
`,wM=[yM,pM],TM=[...wM,_M,vM];function EM(e){return[gM,...TM,e]}function DM(e){let t=t=>[gM,SM,t,...TM,e,CM];return{rectilinear:t(xM),equirectangular:t(mM),"lens-tiles":[gM,SM,...wM,bM]}}var OM=DM(hM),kM=EM(fM);function AM(e){return[...new Set(e.flat())]}AM([...Object.values(OM),kM]);var jM=64,MM=class{renderer;lensCount;target=new Fw(jM,2,{depthBuffer:!1,stencilBuffer:!1});pixels=new Uint8Array(jM*2*4);camera=new FD;scene=new xT;material;geometry=nM();isDisposed=!1;constructor(e,t,n){this.renderer=e,this.lensCount=n,this.material=iM(t,rM(kM)),this.scene.add(new zE(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:cM(this.pixels,jM,this.lensCount)}dispose(){this.isDisposed||(this.isDisposed=!0,this.target.dispose(),this.material.dispose(),this.geometry.dispose())}draw(){dM(this.renderer,this.target,()=>{this.renderer.render(this.scene,this.camera)})}async readSeam(){this.draw(),await this.renderer.readRenderTargetPixelsAsync(this.target,0,0,jM,2,this.pixels)}};function NM(e,t){return Array.from({length:e},()=>{let e=new JE;return e.flipY=!1,e.colorSpace=``,e.magFilter=TS,PM(e,t),e})}function PM(e,t){e.minFilter=t.minFilter,e.generateMipmaps=t.generateMipmaps,e.anisotropy=t.anisotropy}var FM={programs:OM,defines:Pj};function IM(e,t){let n=n=>iM(e,{chunks:t.programs[n],defines:t.defines});return{rectilinear:n(`rectilinear`),equirectangular:n(`equirectangular`),"lens-tiles":n(`lens-tiles`)}}function LM(e,t,n){let r=new FD;for(let i of Object.values(n)){let n=new xT;n.add(new zE(t,i)),uM(e,n,r)}}function RM(e){for(let t of Object.values(e))t.dispose()}var zM={shaders:FM,uniforms:{}},BM=class{parts;canvas;framing=ol;viewMode=Tc;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:zM};return new this(this.openParts(e,t,r),e)}static openParts(e,t,n){VM(t);let r=aM(e,n.options);try{return{...UM(r,t,n.pictures),drawSchedule:n.options.drawSchedule??Sj}}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=jj[e];for(let e of this.parts.textures)PM(e,t),this.hasFrames&&(e.needsUpdate=!0);Uj(this.parts.uniforms,t),this.redraw()}setLensGains(e){this.ensureLive();for(let[t,n]of e.entries())Gj(this.parts.uniforms,t,n);this.redraw()}createSeamMeter(){this.ensureLive();let e=new MM(this.parts.renderer,this.parts.uniforms,this.parts.lensCount);return this.tracked({measure:()=>e.measure(),dispose:()=>{e.dispose()}})}setStabilization(e){this.ensureLive(),Wj(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();RM(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=Tl(this.viewMode).picture(this.framing,{viewport:e,lensCount:this.parts.lensCount});this.parts.pass.material=this.parts.materials[t.kind],qj(this.parts.uniforms,t,Ac(e))}};function VM(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 HM(e,t){let n=jj[xc],r=NM(e.frameSlotCount,n),i=Fj(e,r);return Uj(i,n),{textures:r,uniforms:i,materials:IM({...i,...t.uniforms},t.shaders)}}function UM(e,t,n){let{textures:r,uniforms:i,materials:a}=HM(t,n),o=new zE(nM(),a.rectilinear),s=WM(e,{pass:o,materials:a,textures:r,uniforms:i}),c=new xT;return c.add(o),{renderer:e,scene:c,camera:new FD,pass:o,materials:a,textures:r,uniforms:i,matrixCorrections:new wj(t.lenses,i.uLensMatrixCorrection),lensCount:t.lenses.length,seamProof:s}}function WM(e,t){let{pass:n,materials:r,textures:i,uniforms:a}=t;try{return LM(e,n.geometry,r),new MM(e,a,a.uLensCount.value)}catch(e){RM(r),n.geometry.dispose();for(let e of i)e.dispose();throw e}}var GM={request:e=>requestAnimationFrame(e),cancel:e=>{cancelAnimationFrame(e)}},KM=class{frames;pendingDraw;handle;constructor(e=GM){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?.()}},qM=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()}}},JM={maxPendingPackets:4,pairTolerance:R(5e-4)},YM=`the recording has no audio track; playback follows a silent clock`,XM=`this browser cannot play the audio track through Media Source Extensions; playback follows a silent clock`,ZM=`the audio track could not be prepared for playback; playback follows a silent clock`;async function QM(e){let t=new qM;try{let n=await tN(e);t.add(()=>{n.clock.dispose()}),e.signal.throwIfAborted();let r=$M(e,t),i=oN(e,n.clock,r.gainMatching);return t.add(()=>{i.dispose()}),aN(i,e.opened),{session:i,renderer:r.renderer,...eN(r,i),soundWarnings:n.warnings,dispose:t.toDisposer()}}catch(e){throw t.disposeAll(),e}}function $M(e,t){let n=BM.create(e.host.canvas,rN(e.opened),{drawSchedule:new KM});t.add(()=>{n.dispose()});let{sink:r,stabilizing:i}=iN(n,e.opened),a=new Vl(r,n);return t.add(()=>{a.dispose()}),{renderer:n,stabilizing:i,gainMatching:a}}function eN(e,t){return{setStabilization:n=>{e.stabilizing?.setStabilizer(ec(n)),t.redraw()},setQuality:t=>{e.renderer.setQuality(t)},setGainMatching:n=>{n?e.gainMatching.enable():e.gainMatching.disable(),t.redraw()}}}async function tN(e){let{soundSegments:t}=e.opened;if(!t)return nN(YM);try{let n=t();return hS.isSupported(n)?(e.signal.throwIfAborted(),{clock:await hS.open(e.host.audio,n),warnings:[]}):nN(XM)}catch(e){return nN(`${ZM} (${ie(e)})`)}}function nN(e){return{clock:new Jd(()=>pt(performance.now())),warnings:[e]}}function rN(e){return jl({calibration:e.calibration,layout:e.layout,displayConversions:e.displayConversions})}function iN(e,t){if(!t.motion)return e.setStabilization(Pi.toBody),{sink:e,stabilizing:void 0};let n=new Il({sink:e,motion:t.motion,frameTimes:t.frameTimes});return{sink:n,stabilizing:n}}function aN(e,t){e.events.on(`statechange`,e=>{Zd(e)&&t.readAhead()})}function oN(e,t,n){return new hf({frameSources:e.opened.frameSources,decoderPort:e.decoderPort,clock:t,sink:n,duration:e.opened.duration,buffer:e.opened.buffer,pipeline:JM,queueCapacity:4})}function sN(e,t,n=xc){let r=yr(t,1,Cc(n));return{width:Math.max(1,Math.round(e.width*r)),height:Math.max(1,Math.round(e.height*r))}}function cN(e){let{width:t,height:n}=e.getBoundingClientRect();return{width:t,height:n}}var lN=class{canvas;renderer;observer;ratioWatch=new AbortController;quality=xc;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=sN(cN(this.canvas),globalThis.devicePixelRatio,this.quality);(e.width!==this.canvas.width||e.height!==this.canvas.height)&&this.renderer.resize(e)}},uN=class{tick;scheduler;isActive=!1;handle;constructor(e,t=GM){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 dN(e,t){let{ports:n,signal:r}=t,i=await Vd(e,n.decoderPort,gN(t));if(r.throwIfAborted(),!i.canDecode)throw mN(i)}var fN={"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`}},pN={code:`codec-unsupported`,message:`this browser cannot decode the recording`};function mN(e){let t=hN(e),{code:n,message:r}=(t===void 0?void 0:fN[t])??pN;return new j(n,`${r}: ${_N(e)}`)}function hN(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 gN(e){let t=e.ports.probeDeadline();return e.signal.addEventListener(`abort`,()=>{t.resolve()},{once:!0}),t}function _N(e){return e.sources.filter(e=>e.verdict!==`decodes`).map(e=>`track ${e.track.trackIndex} ${e.verdict}${e.detail?` (${e.detail})`:``}`).join(`; `)}async function vN(e,t){let{ports:n,signal:r}=t,i=e.map(e=>({input:e,opened:n.sources.open(e,r)})),a=await CN(i,n);r.throwIfAborted();let o=[...i,...await xN(i,a,t)],s=await Promise.all(o.map(e=>bN(e,n)));return r.throwIfAborted(),{recording:a,inputs:s}}function yN(e){let t=e.codecs.video.map(({description:e})=>({description:e}));return{name:Wx(e.input),videoTracks:t}}async function bN(e,t){let{source:n}=e.opened,{table:r,movieBytes:i}=await Jo(n),a=await t.codecReader.read(i);return{...e,table:r,codecs:a,size:await n.size()}}async function xN(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 SN={fileLayout:void 0,trackOrder:void 0};async function CN(e,t){try{return await TN(e.map(({opened:e})=>e.source))}catch(n){let[r]=e;throw e.length===1&&M(n,`invalid-trailer`)&&r&&await wN(r,t),n}}async function wN(e,t){let n;try{n=await bN(e,t)}catch{return}try{as([yN(n)],SN)}catch(e){if(M(e,`missing-second-file`))throw e}}async function TN(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 EN(e,t){let n=new qM;try{let r=await vN(e,t),i=as(r.inputs.map(e=>yN(e)),r.recording.info),a=kN(r.recording),o=DN(r.inputs,n),s=Al(i).map(e=>ON(o,e));await dN(s,t);let c=await fa(r.recording,s[0]);return t.signal.throwIfAborted(),AN({read:r,files:o,layout:i,frameSources:s,calibration:a,timing:c},t.ports.audioPackager,n)}catch(e){throw n.disposeAll(),e}}function DN(e,t){return e.map(({opened:n,table:r,codecs:i,size:a})=>{let o=_d({size:a,duration:r.duration},e.length),s=id({table:r,stream:n.stream,codecs:i,policy:o});return t.add(()=>{s.dispose()}),s})}function ON(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 kN(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 AN(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=cu(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:jN(e,l,d!==void 0),warnings:[...c.warnings,...u.warnings],readAhead:()=>{for(let e of i)e.download.startReadingAhead()},buffer:new vd(i.map(e=>e.download)),dispose:n.toDisposer()}}function jN(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 MN(e,t,n){let r=NN(e,t,n),i=e.second?[e.main,e.second]:[e.main];try{return await EN(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 EN([e.main,a],r)}}function NN(e,t,n){let{main:r}=e;return e.second===void 0&&Ux(r)?{ports:t,signal:n,findSecondFile:$e(()=>PN(r,t))}:{ports:t,signal:n}}async function PN(e,t){let n=await Ea(e.url,t.locatorFor(e));return n===void 0?void 0:{...e,url:n}}async function FN(e){let{parts:t,signal:n}=e,r=await MN(e.source,t.ports,n),i=new qM;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 lN(t.host.canvas,e.renderer);i.add(()=>{a.dispose()});let o=IN(e,a);return{opened:r,pipeline:o,warnings:LN(r,o),dispose:i.toDisposer()}}catch(e){throw i.disposeAll(),e}}function IN(e,t){return{...e,setQuality:n=>{e.setQuality(n),t.setQuality(n)}}}function LN(e,t){return[...e.warnings.map(e=>({code:`recording-degraded`,message:e})),...t.soundWarnings.map(e=>({code:`no-sound`,message:e}))]}var RN={kind:`idle`};function zN(){return{kind:`loading`,controller:new AbortController,settled:new wd}}function BN(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 VN=class{events;mode=qs;isMatching=!0;qualityValue=xc;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))}},HN=class{audio;events;canSetVolume;constructor(e,t){this.audio=e,this.events=t,this.canSetVolume=WN(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})}},UN=.5;function WN(e){let t=e.createElement(`audio`);return t.volume=UN,t.volume===UN}var GN=2,KN=class{events;measureViewport;framing=ol;mode=Tc;surface;lensCount=GN;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:_c(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:Xc(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=Oc){this.frame(this.rules().zoom(this.framing,{steps:e,focus:t},this.context()))}reset(){this.frame(this.rules().reset(this.framing))}frame(e){if(sl(e,this.framing))return;let t=!vc(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 Tl(this.mode)}},qN=/* @__PURE__ */ new Set([`ready`,`paused`,`ended`]),JN=/* @__PURE__ */ new Map([[`playing`,`playing`],[`buffering`,`waiting`]]);function YN(e,t){return t===`seeking`?[`seeking`]:e===`seeking`?t===`buffering`?[`seeked`,`waiting`]:[`seeked`]:t===`paused`?e===`ready`?[]:[`pause`]:XN(e,t)}function XN(e,t){let n=JN.get(t);return n===void 0?[]:e===void 0||qN.has(e)?[`play`,n]:[n]}var ZN=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 YN(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)}},QN=class{parts;events=new $d;outbox=new mu(this.events);loop;phase=RN;viewing;picture=new VN(this.outbox);pendingStartTime;sound;relay=new ZN({events:this.outbox,onState:()=>{this.announceStatus()},onEnded:()=>{this.onEnded()}});isLoopingValue=!1;isDisposed=!1;lastStatus=`idle`;constructor(e){this.parts=e,this.loop=new uN(this.tick),e.host.audio.addEventListener(`ended`,this.tick),this.sound=new HN(e.host.audio,this.outbox);let{canvas:t}=e.host;this.viewing=new KN(this.outbox,()=>cN(t))}get status(){return BN(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!Zd(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=zN();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){Of(e,`time`);let t=this.loaded?.pipeline.session;t&&t.state!==`error`?t.seek(R(e)):this.pendingStartTime=R(e)}async scrub(e){Of(e,`time`),await this.loaded?.pipeline.session.scrub(R(e))}setView(e){this.viewing.set(kf(e))}lookAt(e,n){Of(e,`yaw`),Of(n,`pitch`),this.viewing.lookAt(t(e),t(n))}pan(e){this.viewing.pan(e)}turn(e,n){Of(e,`yaw turn`),Of(n,`pitch turn`),this.viewing.turn(t(e),t(n))}zoom(e,t){Of(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){Of(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 FN({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=RN,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 $N(e,t){return new QN({host:e,ports:Kx(t),pipelines:QM})}function eP(e,t={}){let n=t.signal??new AbortController().signal,{source:r}=qx(t.http??{}).open(tP(e),n);return dr(r)}function tP(e){return typeof e==`string`?{url:e}:{blob:e,name:e instanceof File?e.name:``}}var nP={Src:`src`,Src2:`src2`},rP={CrossOrigin:`crossorigin`},iP={FieldOfView:`fov`,Yaw:`yaw`,Pitch:`pitch`},aP={Autoplay:`autoplay`,Preload:`preload`,GainMatch:`gain-match`,Muted:`muted`,Loop:`loop`,Stabilization:`stabilization`,ViewMode:`view-mode`,Quality:`quality`,Controls:`controls`,Poster:`poster`},oP=[...Object.values(nP),...Object.values(rP),...Object.values(iP),...Object.values(aP)];function sP(e,t){let n=lP(e(rP.CrossOrigin)),r=cP(e(nP.Src),t,n);return r&&{main:r,second:cP(e(nP.Src2),t,n)}}function cP(e,t,n){let r=e?.trim()??``;return r===``?void 0:{url:uP(r,t),...n}}function lP(e){return wf(yP,e)===`use-credentials`?{credentials:`include`}:{}}function uP(e,t){try{return new URL(e,t).href}catch{return e}}var dP={[iP.FieldOfView]:`fieldOfView`,[iP.Yaw]:`yaw`,[iP.Pitch]:`pitch`};function fP(e,t,n){let r=dP[t],i=mP(n);return r===void 0||i===void 0?e:{...e,[r]:i}}function pP(e){return e!==null}function mP(e){if(e===null||e.trim()===``)return;let t=Number(e);return Number.isFinite(t)?t:void 0}function hP(e,t,n){return{code:`ignored-attribute`,message:`ignoring ${e}="${t}"; expected one of ${n.join(`, `)}`}}function gP(e,t){return t===null||mP(t)!==void 0?void 0:{code:`ignored-attribute`,message:`ignoring ${e}="${t}"; expected a number of degrees`}}var _P={name:aP.Preload,keywords:[`none`,`auto`],fallback:`auto`},vP={name:aP.GainMatch,keywords:[`on`,`off`],fallback:`on`},yP={name:rP.CrossOrigin,property:`crossOrigin`,keywords:[`anonymous`,`use-credentials`],fallback:`anonymous`};function bP(e){return wf(_P,e)===`auto`}function xP(e){return wf(vP,e)===`on`}function SP(e,t,n){return n?CP(n):sP(e,t)}function CP(e){return{main:{blob:e.main,name:e.main.name},second:e.second&&{blob:e.second,name:e.second.name}}}var wP=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(TP)}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=SP(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:bP(e(aP.Preload))});return n!==void 0&&this.player.seek(n),r}};function TP(){}var EP=`data-fill`,DP=class{element;constructor(e){this.element=e}get isActive(){return this.isNativelyFullscreen()||this.element.hasAttribute(EP)}async toggle(){await(this.isActive?this.exit():this.enter())}async exit(){this.isNativelyFullscreen()&&await document.exitFullscreen(),this.element.removeAttribute(EP)}isNativelyFullscreen(){return this.element.matches(`:fullscreen`)}async enter(){if(document.fullscreenEnabled)try{await this.element.requestFullscreen();return}catch{}this.element.setAttribute(EP,``)}},OP=`data-idle`,kP=2500,AP=[`pointermove`,`pointerdown`,`keydown`,`focusin`],jP={capture:!0},MP=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,jP);for(let e of AP)this.element.addEventListener(e,this.onActivity,jP);this.onActivity()}stop(){for(let e of AP)this.element.removeEventListener(e,this.onActivity,jP);this.element.removeEventListener(`pointerdown`,this.onPress,jP),this.clearTimer(),this.element.removeAttribute(OP)}refresh(){this.shouldHide()||this.element.removeAttribute(OP),this.restart()}onPress=()=>{this.wasIdleAtPress=this.element.hasAttribute(OP)};onActivity=()=>{this.element.removeAttribute(OP),this.restart()};restart(){this.clearTimer(),this.timer=setTimeout(()=>{this.shouldHide()&&this.element.setAttribute(OP,``)},kP)}clearTimer(){this.timer!==void 0&&clearTimeout(this.timer),this.timer=void 0}};function NP(e,t,n){return({player:r,warn:i},a)=>{let o=gf(a,t);o?n(r,o):a!==null&&i(hP(e,a,t))}}var PP={[aP.Stabilization]:NP(aP.Stabilization,Ks,(e,t)=>{e.setStabilization(t)}),[aP.ViewMode]:NP(aP.ViewMode,wc,(e,t)=>{e.setViewMode(t)}),[aP.Quality]:NP(aP.Quality,bc,(e,t)=>{e.setQuality(t)}),[aP.Muted]:({player:e},t)=>{e.setMuted(pP(t))},[aP.Loop]:({player:e},t)=>{e.setLooping(pP(t))},[aP.Poster]:({posterImage:e},t)=>{e.src=t??``},[aP.GainMatch]:({player:e},t)=>{e.setGainMatching(xP(t))}};function FP(e){return Object.hasOwn(PP,e)}function IP(e,t,n){FP(t)&&PP[t](e,n)}function LP(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 RP(e,t,n){e.getAttribute(`aria-label`)===t&&e.setAttribute(`aria-label`,n)}function zP(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 BP(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 VP=pu({stabilization:!0,viewMode:!0,quality:!0,fov:!0,yaw:!0,pitch:!0,muted:!0,loop:!0,volume:!0});function HP(e,t){let n={stabilization:{get:()=>t.stabilization,set:JP(e=>{t.setStabilization(GP(e))})},viewMode:{get:()=>t.viewMode,set:JP(e=>{t.setViewMode(KP(e))})},quality:{get:()=>t.quality,set:JP(e=>{t.setQuality(qP(e))})},...UP(t),...WP(t)};for(let[t,r]of Object.entries(n))Object.defineProperty(e,t,{configurable:!0,enumerable:!0,...r})}function UP(e){let t=(t,n)=>({get:()=>e.view[t],set:JP(r=>{e.setView({...e.view,[t]:XP(r,n)})})});return{fov:t(`fieldOfView`,`fov`),yaw:t(`yaw`,`yaw`),pitch:t(`pitch`,`pitch`)}}function WP(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:JP(t=>{e.setVolume(ZP(t,`volume`))})}}}function GP(e){return YP(e,_f,`stabilization`)}function KP(e){return YP(e,vf,`viewMode`)}function qP(e){return YP(e,yf,`quality`)}function JP(e){return t=>{t!=null&&t!==``&&e(t)}}function YP(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 XP(e,n){return t(ZP(e,n))}function ZP(e,t){return Of(e,t),e}var QP=`/*
|
|
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 LF=$e(()=>eF(IF())),RF=$e(()=>[FF,OF].map(e=>BF(e)));function zF(e){e.adoptedStyleSheets=RF(),e.append(LF().cloneNode(!0))}function BF(e){let t=new CSSStyleSheet;return t.replaceSync(e),t}var VF=typeof HTMLElement==`function`?HTMLElement:Object,HF=class extends VF{addEventListener(e,t,n){super.addEventListener(e,t,n)}removeEventListener(e,t,n){super.removeEventListener(e,t,n)}},UF=/* @__PURE__ */ new Map([[`ArrowDown`,(e,t)=>(e+1)%t],[`ArrowUp`,(e,t)=>(e-1+t)%t],[`Home`,()=>0],[`End`,(e,t)=>t-1]]),WF={capture:!0},GF=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=>KF(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()))},WF),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=UF.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 KF(e){return e.getAttribute(`aria-checked`)===`true`}var qF=class{viewMode;stabilization;player;constructor(e,t,n){let{player:r,wording:i}=n;this.player=r,this.viewMode=new GF(e,t.viewMode,{wording:i,choose:e=>{let t=vf(e);t&&r.setViewMode(t)}}),this.stabilization=new GF(e,t.stabilization,{wording:i,choose:e=>{let t=_f(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=Tl(this.player.viewMode).isStabilized;this.stabilization.setAvailable(e&&t)}},JF=60,YF=60;function XF(e){let t=Number.isFinite(e)?Math.max(0,Math.floor(e)):0,n=t%JF,r=Math.floor(t/JF)%YF,i=Math.floor(t/3600);return i>0?`${i}:${ZF(r)}:${ZF(n)}`:`${r}:${ZF(n)}`}function ZF(e){return String(e).padStart(2,`0`)}function QF(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 $F=/* @__PURE__ */ new Map([[`ArrowLeft`,-1],[`ArrowDown`,-1],[`ArrowRight`,1],[`ArrowUp`,1]]),eI=[`pointerup`,`pointercancel`,`change`],tI=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 eI)e.addEventListener(t,()=>{this.endScrub()});e.addEventListener(`keydown`,e=>{let t=$F.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]=[XF(e),XF(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),QF(this.parts.seek)}},nI=100,rI=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(lF(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*nI)}%`),QF(this.parts.volume)}},iI=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(lF(e?`play`:`pause`))}};function aI(e,t){e.resetView.addEventListener(`click`,()=>{t.player.resetView()}),e.fullscreen.addEventListener(`click`,()=>{t.toggleFullscreen()})}function oI(e,t){let n=MF(e);new iI(n,t),aI(n,t),new tI(n,t),new rI(n,t.player),new qF(e,n,{player:t.player,wording:t.wording})}var sI=`data-label`,cI=`data-text`,lI=`data-choice-text`,uI=`data-error`,dI={label:`[data-label]`,text:`[data-text]`,choiceText:`[data-choice-text]`,choice:`[data-choice]`,error:`[data-error]`},fI=class{words=_F;get current(){return this.words}replace(e){this.words=vF(e)}label(e,t){e.setAttribute(sI,t),e.setAttribute(`aria-label`,this.words.labels[t])}showError(e,t){e.setAttribute(uI,t),e.textContent=this.words.errors[t]}write(e){for(let t of e.querySelectorAll(dI.label))this.writeLabel(t);for(let t of e.querySelectorAll(dI.text))this.writeText(t);for(let t of e.querySelectorAll(dI.choiceText))this.writeChoiceText(t);for(let t of e.querySelectorAll(dI.error))this.writeError(t)}writeLabel(e){let t=e.getAttribute(sI);yF(t)&&e.setAttribute(`aria-label`,this.words.labels[t])}writeText(e){let t=e.getAttribute(cI);yF(t)&&(e.textContent=this.words.labels[t])}writeChoiceText(e){let t=e.getAttribute(lI),n=e.closest(dI.choice)?.dataset.choice;n!==void 0&&bF(t)&&(e.textContent=this.words[t][n]??``)}writeError(e){let t=e.getAttribute(uI);te(t)&&(e.textContent=this.words.errors[t])}},pI=[...Object.values(nP),aP.Poster],mI=[_P,vP],hI=[yP],gI=[aP.Autoplay,aP.Controls],_I=Object.values(nP),vI=Object.values(rP),yI=[...[...pI,...mI.map(({name:e})=>e),...gI].map(e=>Df(e)),...hI.map(({property:e})=>e),...VP,`currentTime`,`messages`],bI=Object.values(iP),xI=class extends HF{static observedAttributes=oP;earlyProperties;player;loads;wording=new fI;fullscreen=new DP(this);idle;posterImage;constructor(){super(),this.earlyProperties=zP(this,yI),bf(this,pI),Sf(this,mI),Cf(this,hI),xf(this,gI);let e=this.attachShadow({mode:`open`});zF(e),this.wording.write(e);let t=AF(e,`canvas`,HTMLCanvasElement),n=AF(e,`audio`,HTMLAudioElement);this.posterImage=AF(e,`.poster`,HTMLImageElement),this.player=$N({canvas:t,audio:n}),this.loads=new wP(this,this.player),HP(this,this.player);let r=this.controlsHost();oI(e,r),new Gf(t,this.player,this.onPictureTap),Lf(this,r),this.idle=new MP(this,()=>this.player.status===`playing`);let{idle:i,wording:a}=this;PF(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),RP(this,t,this.wording.current.labels.player)}connectedCallback(){LP(this,this.wording.current.labels.player),BP(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(_I.includes(e))this.loads.sourceChanged();else if(vI.includes(e))this.loads.requestChanged();else if(bI.includes(e)){this.player.setView(fP(this.player.view,e,n));let t=gP(e,n);t!==void 0&&this.warn(t)}else IP({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){Of(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(GP(e))}setViewMode(e){this.player.setViewMode(KP(e))}setQuality(e){this.player.setQuality(qP(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=()=>{Yf(this.player)};warn=e=>{this.dispatchEvent(new CustomEvent(`warning`,{detail:e,composed:!0}))}},SI=`gyro-view`;function CI(){if(typeof customElements>`u`)return;let e=customElements.get(SI);e===void 0?customElements.define(SI,xI):e!==xI&&wI()}var wI=$e(()=>{console.warn(`<${SI}> was defined by another copy of gyroview; that copy's element is used`)});CI();export{A as GYRO_VIEW_ERROR_CATEGORIES,k as GYRO_VIEW_ERROR_CODES,SI as GYRO_VIEW_TAG,xI as GyroViewElement,j as GyroViewError,bc as PICTURE_QUALITIES,QN as Player,Ks as STABILIZATION_MODES,wc as VIEW_MODES,Jf as attachKeyboard,qf as attachViewGestures,$N as createBrowserPlayer,CI as defineGyroView,M as hasErrorCode,eP 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};
|