UNPKG

@drincs/pixi-vn

Version:

Pixi'VN is a npm package that provides various features for creating visual novels.

1 lines 20.4 kB
import {i as i$1}from'./chunk-IWAXXFXE.mjs';import {e,d,f,g as g$1}from'./chunk-Z4GZCINS.mjs';import {GameUnifier,PixiError}from'@drincs/pixi-vn/core';import le from'@drincs/pixi-vn/pixi.js';import*as c from'tone';import {ToneAudioBuffer,Channel,Reverb,Time,PingPongDelay,FeedbackDelay,BitCrusher,Compressor,Delay,Distortion,FeedbackCombFilter,Freeverb,Gate,GreaterThan,GreaterThanZero,Limiter,MidSideCompressor,MultibandCompressor,Panner3D,Phaser,StereoWidener,AutoFilter,Chorus,Tremolo,Vibrato,AutoPanner,BiquadFilter,OnePoleFilter,Filter,Player,now}from'tone';var C;(s=>(s.mediaInstances=new Map,s.channels=new Map,s.transients=new Set,s.systemPausedAliases=new Set,s.bufferRegistry=new e({cacheSize:10})))(C||(C={}));var i=C;function T(a){return a.reduce((t,e)=>{switch(e.filterType){case "ReverbFilter":t.push(new Reverb({decay:e.decay,preDelay:e.preDelay,wet:e.wet}).toDestination());break;case "FeedbackDelayFilter":t.push(new FeedbackDelay({feedback:e.feedback,delayTime:e.delayTime,wet:e.wet}).toDestination());break;case "BitCrusherFilter":t.push(new BitCrusher({bits:e.bits}).toDestination());break;case "CompressorFilter":t.push(new Compressor({attack:e.attack,knee:e.knee,ratio:e.ratio,release:e.release,threshold:e.threshold}).toDestination());break;case "DelayFilter":t.push(new Delay({delayTime:e.delayTime,maxDelay:e.maxDelay}).toDestination());break;case "DistortionFilter":t.push(new Distortion({distortion:e.distortion,oversample:e.oversample,wet:e.wet}).toDestination());break;case "FeedbackCombFilterFilter":t.push(new FeedbackCombFilter({delayTime:e.delayTime,resonance:e.resonance}).toDestination());break;case "FreeverbFilter":t.push(new Freeverb({roomSize:e.roomSize,dampening:e.dampening,wet:e.wet}).toDestination());break;case "GateFilter":t.push(new Gate({threshold:e.threshold,smoothing:e.smoothing}).toDestination());break;case "GreaterThanFilter":t.push(new GreaterThan({value:e.value,convert:e.convert,maxValue:e.maxValue,minValue:e.minValue,units:e.units}).toDestination());break;case "GreaterThanZeroFilter":t.push(new GreaterThanZero);break;case "LimiterFilter":t.push(new Limiter({threshold:e.threshold}).toDestination());break;case "MidSideCompressorFilter":t.push(new MidSideCompressor({mid:e.mid,side:e.side}).toDestination());break;case "MultibandCompressorFilter":t.push(new MultibandCompressor({lowFrequency:e.lowFrequency,highFrequency:e.highFrequency,low:e.low,mid:e.mid,high:e.high}).toDestination());break;case "Panner3DFilter":t.push(new Panner3D({positionX:e.positionX,positionY:e.positionY,positionZ:e.positionZ,orientationX:e.orientationX,orientationY:e.orientationY,orientationZ:e.orientationZ,coneInnerAngle:e.coneInnerAngle,coneOuterAngle:e.coneOuterAngle,coneOuterGain:e.coneOuterGain,distanceModel:e.distanceModel,maxDistance:e.maxDistance,refDistance:e.refDistance,rolloffFactor:e.rolloffFactor,panningModel:e.panningModel}).toDestination());break;case "PhaserFilter":t.push(new Phaser({frequency:e.frequency,octaves:e.octaves,baseFrequency:e.baseFrequency,wet:e.wet,Q:e.Q,stages:e.stages}).toDestination());break;case "StereoWidenerFilter":t.push(new StereoWidener({width:e.width,wet:e.wet}).toDestination());break;case "PingPongDelayFilter":t.push(new PingPongDelay({wet:e.wet,delayTime:e.delayTime,feedback:e.feedback,maxDelay:e.maxDelay}).toDestination());break;case "AutoFilterFilter":t.push(new AutoFilter({frequency:e.frequency,depth:e.depth,baseFrequency:e.baseFrequency,octaves:e.octaves,filter:e.filter,wet:e.wet,type:e.type}).toDestination());break;case "BiquadFilterFilter":t.push(new BiquadFilter({frequency:e.frequency,detune:e.detune,Q:e.Q,type:e.type,gain:e.gain}).toDestination());break;case "OnePoleFilterFilter":t.push(new OnePoleFilter({type:e.type}).toDestination());break;case "CustomFilter":t.push(new Filter({frequency:e.frequency,Q:e.Q,type:e.type,detune:e.detune,gain:e.gain,rolloff:e.rolloff}).toDestination());break;case "ChorusFilter":t.push(new Chorus({frequency:e.frequency,delayTime:e.delayTime,depth:e.depth,type:e.type,spread:e.spread,feedback:e.feedback,wet:e.wet}).toDestination());break;case "TremoloFilter":t.push(new Tremolo({frequency:e.frequency,type:e.type,depth:e.depth,spread:e.spread,wet:e.wet}).toDestination());break;case "VibratoFilter":t.push(new Vibrato({maxDelay:e.maxDelay,frequency:e.frequency,depth:e.depth,type:e.type,wet:e.wet}).toDestination());break;case "AutoPannerFilter":t.push(new AutoPanner({frequency:e.frequency,type:e.type,depth:e.depth,channelCount:e.channelCount,wet:e.wet}).toDestination());break}return t},[])}function se(a){if(a)return Array.from(a).reduce((t,e)=>(e instanceof Reverb?t.push({filterType:"ReverbFilter",wet:e.wet.value,decay:Time(e.decay).toSeconds(),preDelay:Time(e.preDelay).toSeconds()}):e instanceof PingPongDelay?t.push({filterType:"PingPongDelayFilter",wet:e.wet.value,delayTime:e.delayTime.value,feedback:e.feedback.value}):e instanceof FeedbackDelay?t.push({filterType:"FeedbackDelayFilter",feedback:e.feedback.value,delayTime:e.delayTime.value,wet:e.wet.value}):e instanceof BitCrusher?t.push({filterType:"BitCrusherFilter",bits:e.bits.value,wet:e.wet.value}):e instanceof Compressor?t.push({filterType:"CompressorFilter",attack:e.attack.value,knee:e.knee.value,ratio:e.ratio.value,release:e.release.value,threshold:e.threshold.value}):e instanceof Delay?t.push({filterType:"DelayFilter",delayTime:e.delayTime.value,maxDelay:e.maxDelay}):e instanceof Distortion?t.push({filterType:"DistortionFilter",distortion:e.distortion,oversample:e.oversample,wet:e.wet.value}):e instanceof FeedbackCombFilter?t.push({filterType:"FeedbackCombFilterFilter",delayTime:e.delayTime.value,resonance:e.resonance.value}):e instanceof Freeverb?t.push({filterType:"FreeverbFilter",roomSize:e.roomSize.value,dampening:e.dampening,wet:e.wet.value}):e instanceof Gate?t.push({filterType:"GateFilter",threshold:e.threshold,smoothing:e.smoothing}):e instanceof GreaterThan?t.push({filterType:"GreaterThanFilter",value:e.comparator.value,convert:e.convert,maxValue:e.maxValue,minValue:e.minValue}):e instanceof GreaterThanZero?t.push({filterType:"GreaterThanZeroFilter"}):e instanceof Limiter?t.push({filterType:"LimiterFilter",threshold:e.threshold.value}):e instanceof MidSideCompressor?t.push({filterType:"MidSideCompressorFilter",mid:{attack:e.mid.attack.value,knee:e.mid.knee.value,ratio:e.mid.ratio.value,release:e.mid.release.value,threshold:e.mid.threshold.value},side:{attack:e.side.attack.value,knee:e.side.knee.value,ratio:e.side.ratio.value,release:e.side.release.value,threshold:e.side.threshold.value}}):e instanceof MultibandCompressor?t.push({filterType:"MultibandCompressorFilter",lowFrequency:e.lowFrequency.value,highFrequency:e.highFrequency.value,low:{attack:e.low.attack.value,knee:e.low.knee.value,ratio:e.low.ratio.value,release:e.low.release.value,threshold:e.low.threshold.value},mid:{attack:e.mid.attack.value,knee:e.mid.knee.value,ratio:e.mid.ratio.value,release:e.mid.release.value,threshold:e.mid.threshold.value},high:{attack:e.high.attack.value,knee:e.high.knee.value,ratio:e.high.ratio.value,release:e.high.release.value,threshold:e.high.threshold.value}}):e instanceof Panner3D?t.push({filterType:"Panner3DFilter",positionX:e.positionX.value,positionY:e.positionY.value,positionZ:e.positionZ.value,orientationX:e.orientationX.value,orientationY:e.orientationY.value,orientationZ:e.orientationZ.value,coneInnerAngle:e.coneInnerAngle,coneOuterAngle:e.coneOuterAngle,coneOuterGain:e.coneOuterGain,distanceModel:e.distanceModel,maxDistance:e.maxDistance,refDistance:e.refDistance,rolloffFactor:e.rolloffFactor,panningModel:e.panningModel}):e instanceof Phaser?t.push({filterType:"PhaserFilter",frequency:e.frequency.value,octaves:e.octaves,baseFrequency:e.baseFrequency,wet:e.wet.value,Q:e.Q.value}):e instanceof StereoWidener?t.push({filterType:"StereoWidenerFilter",width:e.width.value,wet:e.wet.value}):e instanceof AutoFilter?t.push({filterType:"AutoFilterFilter",type:e.type,frequency:e.frequency.value,depth:e.depth.value,baseFrequency:e.baseFrequency,octaves:e.octaves,filter:{Q:e.filter.Q.value,type:e.filter.type,rolloff:e.filter.rolloff},wet:e.wet.value}):e instanceof Chorus?t.push({filterType:"ChorusFilter",type:e.type,frequency:e.frequency.value,delayTime:e.delayTime,depth:e.depth,spread:e.spread,feedback:e.feedback.value,wet:e.wet.value}):e instanceof Tremolo?t.push({filterType:"TremoloFilter",type:e.type,frequency:e.frequency.value,depth:e.depth.value,spread:e.spread,wet:e.wet.value}):e instanceof Vibrato?t.push({filterType:"VibratoFilter",type:e.type,frequency:e.frequency.value,depth:e.depth.value,wet:e.wet.value}):e instanceof AutoPanner?t.push({filterType:"AutoPannerFilter",type:e.type,frequency:e.frequency.value,depth:e.depth.value,channelCount:e.channelCount,wet:e.wet.value}):e instanceof BiquadFilter?t.push({filterType:"BiquadFilterFilter",type:e.type,frequency:e.frequency.value,detune:e.detune.value,Q:e.Q.value,gain:e.gain.value}):e instanceof OnePoleFilter?t.push({filterType:"OnePoleFilterFilter",type:e.type}):e instanceof Filter?t.push({filterType:"CustomFilter",type:e.type,frequency:e.frequency.value,Q:e.Q.value,detune:e.detune.value,gain:e.gain.value,rolloff:e.rolloff}):f.warn(`Unsupported filter type for serialisation: ${e?.constructor?.name??e}, please report this to the developers if you encounter it.`),t),[])}function K(a){return a instanceof Reverb||a instanceof FeedbackDelay||a instanceof PingPongDelay||a instanceof BitCrusher||a instanceof Compressor||a instanceof Delay||a instanceof Distortion||a instanceof FeedbackCombFilter||a instanceof Freeverb||a instanceof Gate||a instanceof GreaterThan||a instanceof GreaterThanZero||a instanceof Limiter||a instanceof MidSideCompressor||a instanceof MultibandCompressor||a instanceof Panner3D||a instanceof Phaser||a instanceof StereoWidener||a instanceof AutoFilter||a instanceof Chorus||a instanceof Vibrato||a instanceof Tremolo||a instanceof AutoPanner||a instanceof BiquadFilter||a instanceof OnePoleFilter||a instanceof Filter}function h(a){return a<=0?-1/0:20*Math.log10(a)}function g(a){return a<=-1/0?0:10**(a/20)}async function P(a){if(i.bufferRegistry.has(a))return;let t=a;try{let e=le.Assets.resolver.resolve(a);e?.src&&(t=e.src);}catch{}try{let e=await ToneAudioBuffer.load(t),n=new ToneAudioBuffer(e);i.bufferRegistry.set(a,n);}catch(e){f.warn(`Failed to load audio buffer for "${a}" (url: "${t}"): ${e instanceof Error?e.message:e}`),i.bufferRegistry.set(a,new ToneAudioBuffer);}}var v=class extends Player{constructor(e,n,r,s,o={},l){super(o);d(this,"alias",e);d(this,"channelAlias",n);d(this,"soundAlias",r);d(this,"stepCounter",s);d(this,"delay",l);d(this,"options");d(this,"filters",new Set);d(this,"pausedAt");d(this,"playStartTime",now());this.options=o,this.playStartTime=now()+(l??0);}get memory(){let e=Math.max(0,this.pausedAt?this.pausedAt-this.playStartTime:now()-this.playStartTime),n=this.paused;return n&&i.systemPausedAliases.has(this.alias)&&(n=false),{...this.options,fadeIn:this.fadeIn,loop:this.loop,loopEnd:this.loopEnd,loopStart:this.loopStart,mute:this.mute,playbackRate:this.playbackRate,reverse:this.reverse,volume:g(this.volume.value),autostart:!this.paused,elapsed:e,paused:n,delay:this.delay}}set memory(e){this.paused=e.paused,this.loop!==(e.loop||false)&&(this.loop=e.loop||false),this.volume.value!==h(e.volume??1)&&(this.volume.value=h(e.volume??1)),this.mute!==(e.mute||false)&&(this.mute=e.mute||false),this.playbackRate!==(e.playbackRate??1)&&(this.playbackRate=e.playbackRate??1),this.reverse!==(e.reverse||false)&&(this.reverse=e.reverse||false),this.fadeIn!==(e.fadeIn||0)&&(this.fadeIn=e.fadeIn||0),this.loopStart!==(e.loopStart||0)&&(this.loopStart=e.loopStart||0),this.loopEnd!==(e.loopEnd||0)&&(this.loopEnd=e.loopEnd||0);}get paused(){return typeof this.pausedAt=="number"}set paused(e){let n=this.state;if(e)this.pausedAt=now(),n==="started"&&super.stop();else {let r;typeof this.pausedAt=="number"&&(r=this.pausedAt-this.playStartTime,this.pausedAt=void 0),n==="stopped"&&(this.delay?this.start(`+${this.delay}`,r):this.start(void 0,r));}}get muted(){return this.mute}set muted(e){this.mute=e;}get speed(){return this.playbackRate}set speed(e){this.playbackRate=e;}stop(e){return i.mediaInstances.delete(this.alias),super.stop(e)}start(e,n,r){let s=now(),o=s;if(typeof e=="number")o=e;else if(typeof e=="string"&&e.startsWith("+")){let m=Number(e.slice(1));Number.isNaN(m)||(o=s+m);}let l=typeof n=="number"?n:0;return this.playStartTime=o-l,super.start(e,n,r)}chain(...e){return e.forEach(n=>{K(n)&&(n.toDestination(),this.filters.add(n));}),super.chain(...e)}disconnect(e){return K(e)&&(e.disconnect(),this.filters.delete(e)),super.disconnect(e)}};var F=class{constructor(t,e={}){d(this,"alias",t);d(this,"toneChannel");d(this,"background");this.background=e.background??false,this.toneChannel=new Channel({volume:h(e.volume??1),mute:e.muted??false,pan:e.pan??0}).toDestination(),e.filters&&this.toneChannel.chain(...e.filters);}get volume(){return g(this.toneChannel.volume.value)}set volume(t){this.toneChannel.volume.value=h(t);}get volumeParam(){return this.toneChannel.volume}get pan(){return this.toneChannel.pan.value}set pan(t){this.toneChannel.pan.value=t;}get panParam(){return this.toneChannel.pan}get muted(){return this.toneChannel.mute}set muted(t){this.toneChannel.mute=t;}pauseAll(){for(let t of i.mediaInstances.values())t.channelAlias===this.alias&&!t.paused&&(t.paused=true);return this}resumeAll(){for(let t of i.mediaInstances.values())t.channelAlias===this.alias&&t.paused&&(t.paused=false);return this}chain(...t){return this.toneChannel.chain(...t),this}_createPlayer(t,e,n={}){let r=i.bufferRegistry.get(e);if(!r)throw new PixiError("unregistered_asset",`Sound buffer for alias "${e}" is not loaded. Call sound.load() first.`);let{delay:s,elapsed:o,filters:l=[],muted:m,autostart:y=true,speed:p,volume:A,...f$1}=n;m!==void 0&&(f.warn(`MediaInstance "${t}" is being created with muted=${m}. This will override the channel's muted state (${this.muted}).`),f$1.mute=m),p!==void 0&&(f.warn(`MediaInstance "${t}" is being created with speed=${p}. This will override the default playback speed of 1.`),f$1.playbackRate=p);let O=new v(t,this.alias,e,GameUnifier.stepCounter,{...f$1,volume:A!==void 0?h(A):void 0,url:r},s).chain(...l,this.toneChannel),ne=o!==void 0?Math.max(0,o):void 0;return y&&(s?O.start(`+${s}`,ne):O.start(void 0,ne)),O}async play(t,e,n){let r,s;if(typeof e=="string"?(r=t,s=e):(r=t,s=t,n=e),i.mediaInstances.has(r)){let l=i.mediaInstances.get(r);l&&(l.stop(),n={...l.memory,...n,filters:[...l.filters,...n?.filters||[]]});}await P(s);let o=this._createPlayer(r,s,n);return i.mediaInstances.set(r,o),o}toggleMuteAll(){return this.muted=!this.muted,this.muted}get mediaInstances(){return Array.from(i.mediaInstances.values()).reduce((t,e)=>(e.channelAlias===this.alias&&t.push(e),t),[])}stopAll(){let t=[];for(let[e,n]of i.mediaInstances.entries())n.channelAlias===this.alias&&(n.stop(),t.push(e));return t.forEach(e=>{i.mediaInstances.delete(e);}),this}};var w=class{constructor(){d(this,"_speedAll",1);d(this,"_defaultChannelAlias",i$1);}get volumeAll(){return g(c.getDestination().volume.value)}set volumeAll(t){c.getDestination().volume.value=h(t);}get speedAll(){return this._speedAll}set speedAll(t){this._speedAll=t;for(let e of i.mediaInstances.values())e.speed=t;}get defaultChannelAlias(){return this._defaultChannelAlias}set defaultChannelAlias(t){this._defaultChannelAlias=t;}add(t,e){if(!i.bufferRegistry.has(t)){let n=new c.ToneAudioBuffer(e);i.bufferRegistry.set(t,n);}}pauseAll(){for(let t of i.mediaInstances.values())t.paused||(t.paused=true);return this}resumeAll(){for(let t of i.mediaInstances.values())t.paused&&(t.paused=false);return this}get muted(){return c.getDestination().mute}toggleMuteAll(){let t=!c.getDestination().mute;return c.getDestination().mute=t,t}muteAll(){return c.getDestination().mute=true,this}unmuteAll(){return c.getDestination().mute=false,this}stopAll(){for(let t of i.mediaInstances.values())t.stop();return i.mediaInstances.clear(),this}pauseUnsavedAll(t){for(let[e,n]of i.mediaInstances.entries())t&&n.channelAlias!==t||n.paused||(n.paused=true,i.systemPausedAliases.add(e));if(!t){for(let e of i.transients)e.stop();i.transients.clear();}return this}resumeUnsavedAll(t){let e=[];for(let n of i.systemPausedAliases){let r=i.mediaInstances.get(n);if(!r){e.push(n);continue}t&&r.channelAlias!==t||(r.paused=false,e.push(n));}for(let n of e)i.systemPausedAliases.delete(n);return this}stopTransientAll(){for(let t of i.transients)t.stop();return i.transients.clear(),this}async play(t,e,n){let r,s;typeof e=="string"?(r=t,s=e):(r=t,s=t,n=e),i.bufferRegistry.has(s)||await this.load(s);let{channel:o=this.defaultChannelAlias,...l}=n??{};return await this.findChannel(o).play(r,s,l)}async playTransient(t,e){i.bufferRegistry.has(t)||await this.load(t);let n=i.bufferRegistry.get(t);if(!n)throw new PixiError("unregistered_asset",`Sound buffer for alias "${t}" is not loaded. Call sound.load() first.`);let{autostart:r=true,...s}=e??{},o=new c.Player({...s,url:n}).toDestination();return r&&o.start(),i.transients.add(o),o.onstop=()=>{o.dispose(),i.transients.delete(o);},o}find(t){return i.mediaInstances.get(t)}stop(t){let e=this.find(t);e?(e.stop(),i.mediaInstances.delete(t)):f.warn(`No media instance found with alias ${t} to stop.`);}pause(t){let e=this.find(t);if(!e){f.warn(`No media instance found with alias ${t} to pause.`);return}return e.paused=true,e}resume(t){let e=this.find(t);if(!e){f.warn(`No media instance found with alias ${t} to resume.`);return}return e.paused=false,e}duration(t){return i.bufferRegistry.get(t)?.duration??0}async load(...t){let e=t.map(P);await Promise.all(e);}backgroundLoad(...t){return this.load(...t).catch(e=>{f.error("Error background-loading sound",e);})}backgroundLoadBundle(t){let e=le.Assets.backgroundLoadBundle(t);return e.then(async()=>{try{let n=await le.Assets.loadBundle(t),r=[];for(let s in n)i.bufferRegistry.has(s)||r.push(this.load(s));await Promise.all(r);}catch(n){f.error("Error loading sound bundle",n);}}).catch(n=>{f.error("Error background-loading sound bundle",n);}),e}clear(){this.stopAll();}addChannel(t,e={}){if(typeof t!="string"){t.forEach(r=>{let s={...e,filters:e.filters?[...e.filters]:e.filters};this.addChannel(r,s);});return}if(i.channels.has(t)){f.warn(`Channel with alias ${t} already exists.`);return}let n=new F(t,e);return i.channels.set(t,n),n}findChannel(t){let e=i.channels.get(t);return e||this.addChannel(t)}get channels(){return Array.from(i.channels.values())}export(){let t=Array.from(i.mediaInstances.entries()).reduce((e,[n,r])=>(e[n]={channelAlias:r.channelAlias,soundAlias:r.soundAlias,stepCounter:r.stepCounter,paused:r.paused,options:{...r.memory,filters:se(r.filters)}},e),{});return {mediaInstances:g$1(t)}}async restore(t){try{if(Object.hasOwn(t,"soundsPlaying")){let e=t.soundsPlaying;if(e){let n=Object.keys(e).map(async r=>{await this.load(r),await this.play(r);});await Promise.all(n);}}if(Object.hasOwn(t,"mediaInstances")){let e=t.mediaInstances;if(e){let n=new Set,r=Object.values(e).map(async({soundAlias:o,channelAlias:l})=>(n.add(l),await this.load(o)));await Promise.all(r),this.channels.forEach(o=>{(!o.background||!n.has(o.alias))&&o.stopAll();});let s=Object.keys(e).map(async o=>{let l=e[o],m=this.findChannel(l.channelAlias),y=l.options.paused??l.paused??!1;if(m.background)if(l.stepCounter===GameUnifier.stepCounter||!this.find(o)){let p=await m.play(o,l.soundAlias,{...l.options,autostart:!y,filters:T(l.options.filters||[]),delay:l.options.delay});p.paused=y;}else {let p=i.mediaInstances.get(o);if(!p){f.warn(`No media instance found with alias ${o} while restoring background state.`);return}p.memory={...l.options,paused:y},[...p.filters].forEach(f=>{p.disconnect(f),f.dispose();}),p.chain(...T(l.options.filters||[]));}else {let p=await m.play(o,l.soundAlias,{...l.options,autostart:!y,filters:T(l.options.filters||[]),delay:l.options.delay});p.paused=y;}});await Promise.all(s);}}}catch(e){f.error("Error importing data",e);}}};var te=new w;GameUnifier.addOnPreContinue(async()=>{try{i.channels.forEach(a=>{a.background||a.stopAll();});}catch{}});if(typeof document<"u"){let a=false;document.addEventListener("visibilitychange",()=>{document.hidden?te.muted||(te.muteAll(),a=true):a&&(te.unmuteAll(),a=false);});}export{i as SoundRegistry,te as sound};