audio-vis/out/js/scripts.min.js

1 line
37 KiB
JavaScript

class VTUtils{static random(e,t){let a=Math.random();if(void 0===e)return a;if(void 0===t)return e instanceof Array?e[Math.floor(a*e.length)]:a*e;if(e>t){let a=e;e=t,t=a}return a*(t-e)+e}static randomInt(e,t){return Math.floor(VTUtils.random(e,t))}static normalize(e,t,a){return(e-a)/(t-a)}static distance(e,t,a,i){let s=e-a,n=t-i;return Math.sqrt(s*s+n*n)}static map(e,t,a,i,s,n){let r=(e-t)/(a-t)*(s-i)+i;return n?i<s?this.constrain(r,i,s):this.constrain(r,s,i):r}static constrain(e,t,a){return Math.max(Math.min(e,a),t)}static hsvToRgb(e,t,a){let i,s,n,r=Math.floor(6*e),l=6*e-r,o=a*(1-t),d=a*(1-l*t),c=a*(1-(1-l)*t);switch(r%6){case 0:i=a,s=c,n=o;break;case 1:i=d,s=a,n=o;break;case 2:i=o,s=a,n=c;break;case 3:i=o,s=d,n=a;break;case 4:i=c,s=o,n=a;break;case 5:i=a,s=o,n=d}return{r:i,g:s,b:n}}static peakRGB(e){return{r:e,g:1-e,b:0}}}class VTVector{constructor(e,t,a){this.x=e||0,this.y=t||0,this.z=a||0}static createRandom(e,t,a){return e=e||1,t=t||1,a=a||0,new VTVector(VTUtils.random(-e,e),VTUtils.random(-t,t),VTUtils.random(-a,a))}mult(e){this.x*=e,this.y*=e,this.z*=e}set(e){this.x=e.x,this.y=e.y,this.z=e.z}add(e){this.x=this.x+e.x,this.y=this.y+e.y,this.z=this.z+e.z}addXYZ(e,t,a){this.x+=e,this.y+=t,this.z+=a}setXYZ(e,t,a){this.x=e||0,this.y=t||0,this.z=a||0}clone(){return new VTVector(this.x,this.y,this.z)}}function $(e,t){return(t=t||document).querySelector(e)}function $$(e,t){return(t=t||document).querySelectorAll(e)}function b64toBlob(e,t){const a=atob(e),i=new Array(a.length);for(let e=0;e<a.length;e++)i[e]=a.charCodeAt(e);const s=new Uint8Array(i);return new Blob([s],{type:t})}function create(e,t){let a=document.createElement(e);return t&&(a.innerHTML=t),a}function append(e,t){for(let a of t)e.appendChild(a)}function hexToRgb(e){e=e.replace("#","");let t=parseInt(e,16);return[(t>>16&255)/255,(t>>8&255)/255,(255&t)/255]}Node.prototype.addDelegatedEventListener=function(e,t,a){this.addEventListener(e,e=>{let i=e.target;if(i.matches(t))a(e,i);else{let s=i.closest(t);if(s)try{a(e,s)}catch(e){NotificationHandler.createNotification("FATAL ERROR WITHIN HANDLER!","error",1e3)}}})},Node.prototype.hasClass=function(e){let t=e.split(","),a=null;for(let e of t){if(!1===a)break;a=this.classList.contains(e.trim())}return!0===a},Node.prototype.addClass=function(e){let t=e.split(",");for(let e of t)this.classList.add(e.trim());return this},Node.prototype.removeClass=function(e){let t=e.split(",");for(let e of t)this.classList.remove(e.trim());return this},Node.prototype.toggleClass=function(e,t){let a=e.split(",");for(let e of a)this.classList.toggle(e.trim(),t)},Node.prototype.switchClass=function(e,t,a){let i=this.classList;a?(i.remove(e),i.add(t)):(i.remove(t),i.add(e))},Node.prototype.toggleCheck=function(e,t){let a=this.classList,i=e.split(",");for(let e of i){let i=e.trim();t?a.add(i):a.remove(i)}},String.prototype.firstUpper=function(){return this.charAt(0).toUpperCase()+this.slice(1)},File.prototype.toBase64=function(e){const t=new FileReader;t.onloadend=e,t.readAsDataURL(this)};class TDUtils{static lastMatrix={m:null};static multiply(e,t){let a=t[0],i=t[1],s=t[2],n=t[3],r=t[4],l=t[5],o=t[6],d=t[7],c=t[8],h=t[9],u=t[10],p=t[11],g=t[12],f=t[13],m=t[14],y=t[15],v=e[0],w=e[1],C=e[2],T=e[3],x=e[4],H=e[5],b=e[6],S=e[7],U=e[8],A=e[9],E=e[10],L=e[11],D=e[12],k=e[13],F=e[14],M=e[15];return[a*v+i*x+s*U+n*D,a*w+i*H+s*A+n*k,a*C+i*b+s*E+n*F,a*T+i*S+s*L+n*M,r*v+l*x+o*U+d*D,r*w+l*H+o*A+d*k,r*C+l*b+o*E+d*F,r*T+l*S+o*L+d*M,c*v+h*x+u*U+p*D,c*w+h*H+u*A+p*k,c*C+h*b+u*E+p*F,c*T+h*S+u*L+p*M,g*v+f*x+m*U+y*D,g*w+f*H+m*A+y*k,g*C+f*b+m*E+y*F,g*T+f*S+m*L+y*M]}static translate(e,t,a,i,s){s=s||new Float32Array(16);let n=e[0],r=e[1],l=e[2],o=e[3],d=e[4],c=e[5],h=e[6],u=e[7],p=e[8],g=e[9],f=e[10],m=e[11],y=e[12],v=e[13],w=e[14],C=e[15];return s[0]=n,s[1]=r,s[2]=l,s[3]=o,s[4]=d,s[5]=c,s[6]=h,s[7]=u,s[8]=p,s[9]=g,s[10]=f,s[11]=m,s[12]=n*t+d*a+p*i+y,s[13]=r*t+c*a+g*i+v,s[14]=l*t+h*a+f*i+w,s[15]=o*t+u*a+m*i+C,s}static xRotation(e){e=TDUtils.degToRad(e);let t=Math.cos(e),a=Math.sin(e);return[1,0,0,0,0,t,a,0,0,-a,t,0,0,0,0,1]}static yRotation(e){e=TDUtils.degToRad(e);let t=Math.cos(e),a=Math.sin(e);return[t,0,-a,0,0,1,0,0,a,0,t,0,0,0,0,1]}static zRotation(e){e=TDUtils.degToRad(e);let t=Math.cos(e),a=Math.sin(e);return[t,a,0,0,-a,t,0,0,0,0,1,0,0,0,0,1]}static degToRad(e){return e*Math.PI/180}static scale(e,t,a,i){return(i=i||new Float32Array(16))[0]=e,i[5]=t,i[10]=a,i}static lookAt(e,t,a,i){i=i||new Float32Array(16);let s=TDUtils.normalize(TDUtils.subtractVectors(e,t)),n=TDUtils.normalize(TDUtils.cross(a,s)),r=TDUtils.normalize(TDUtils.cross(s,n));return i[0]=n[0],i[1]=n[1],i[2]=n[2],i[4]=r[0],i[5]=r[1],i[6]=r[2],i[8]=s[0],i[9]=s[1],i[10]=s[2],i[12]=e[0],i[13]=e[1],i[14]=e[2],i[15]=1,i}static cross(e,t,a){return(a=a||new Float32Array(3))[0]=e[1]*t[2]-e[2]*t[1],a[1]=e[2]*t[0]-e[0]*t[2],a[2]=e[0]*t[1]-e[1]*t[0],a}static normalize(e,t){t=t||new Float32Array(3);let a=Math.sqrt(e[0]*e[0]+e[1]*e[1]+e[2]*e[2]);return a>1e-5&&(t[0]=e[0]/a,t[1]=e[1]/a,t[2]=e[2]/a),t}static subtractVectors(e,t,a){return(a=a||new Float32Array(3))[0]=e[0]-t[0],a[1]=e[1]-t[1],a[2]=e[2]-t[2],a}static perspective(e,t,a,i,s){s=s||new Float32Array(16);let n=Math.tan(.5*Math.PI-.5*e),r=1/(a-i);return s[0]=n/t,s[5]=n,s[10]=(a+i)*r,s[11]=-1,s[14]=a*i*r*2,s}static projection(e,t,a){return[2/e,0,0,0,0,-2/t,0,0,0,0,2/a,0,-1,1,0,1]}static inverse(e,t){t=t||new Float32Array(16);let a=e[0],i=e[1],s=e[2],n=e[3],r=e[4],l=e[5],o=e[6],d=e[7],c=e[8],h=e[9],u=e[10],p=e[11],g=e[12],f=e[13],m=e[14],y=e[15],v=u*y,w=m*p,C=o*y,T=m*d,x=o*p,H=u*d,b=s*y,S=m*n,U=s*p,A=u*n,E=s*d,L=o*n,D=c*f,k=g*h,F=r*f,M=g*l,R=r*h,I=c*l,N=a*f,P=g*i,V=a*h,$=c*i,B=a*l,z=r*i,O=v*l+T*h+x*f-(w*l+C*h+H*f),_=w*i+b*h+A*f-(v*i+S*h+U*f),G=C*i+S*l+E*f-(T*i+b*l+L*f),j=H*i+U*l+L*h-(x*i+A*l+E*h),K=1/(a*O+r*_+c*G+g*j);return t[0]=K*O,t[1]=K*_,t[2]=K*G,t[3]=K*j,t[4]=K*(w*r+C*c+H*g-(v*r+T*c+x*g)),t[5]=K*(v*a+S*c+U*g-(w*a+b*c+A*g)),t[6]=K*(T*a+b*r+L*g-(C*a+S*r+E*g)),t[7]=K*(x*a+A*r+E*c-(H*a+U*r+L*c)),t[8]=K*(D*d+M*p+R*y-(k*d+F*p+I*y)),t[9]=K*(k*n+N*p+$*y-(D*n+P*p+V*y)),t[10]=K*(F*n+P*d+B*y-(M*n+N*d+z*y)),t[11]=K*(I*n+V*d+z*p-(R*n+$*d+B*p)),t[12]=K*(F*u+I*m+k*o-(R*m+D*o+M*u)),t[13]=K*(V*m+D*s+P*u-(N*u+$*m+k*s)),t[14]=K*(N*o+z*m+M*s-(B*m+F*s+P*o)),t[15]=K*(B*u+R*s+$*o-(V*o+z*u+I*s)),t}static aspectView(e){return[1/e,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}static updateRotate(e,t){let a=vConf.get(e,t)+vConf.get(e+"-inc",0);a>360?a-=360:a<-360&&(a+=360),vConf.set(e,a)}static makeZToWMatrix(e){return[1,0,0,0,0,1,0,0,0,0,1,e,0,0,0,1]}}class GLHelper{constructor(e){this.matrix=new Float32Array(16),this.program=e}static uniform4fv(e,t,a){let i=gl.getUniformLocation(e,t);gl.uniform4fv(i,a)}static uniform3fv(e,t,a){let i=gl.getUniformLocation(e,t);gl.uniform3fv(i,a)}static uniform1f(e,t,a){let i=gl.getUniformLocation(e,t);gl.uniform1f(i,a)}rotateX(e){this.matrix=TDUtils.multiply(this.matrix,TDUtils.xRotation(e))}rotateY(e){this.matrix=TDUtils.multiply(this.matrix,TDUtils.yRotation(e))}rotateZ(e){this.matrix=TDUtils.multiply(this.matrix,TDUtils.zRotation(e))}scale(e){this.matrix=TDUtils.multiply(this.matrix,TDUtils.scale(e[0],e[1],e[2]))}project(e){e=e||c.width>c.height?c.width:c.height,this.matrix=TDUtils.projection(c.width,c.height,e)}translate(e){this.matrix=TDUtils.translate(this.matrix,e[0]||0,e[1]||0,e[2]||0)}addFudgeFactor(e){this.matrix=TDUtils.multiply(TDUtils.makeZToWMatrix(e),this.matrix)}applyMatrix(){let e=gl.getUniformLocation(this.program,"u_matrix");gl.uniformMatrix4fv(e,!1,this.matrix)}}class Camera{constructor(){this.mouse,this.rotation={x:0,y:0},this.lastMouse,this.mousePressed=!1,this.translate={x:0,y:0,z:0}}async init(){this.mouse={x:0,y:0},window.addEventListener("mousedown",this.mouseDown.bind(this)),window.addEventListener("mouseup",this.mouseUp.bind(this)),window.addEventListener("mousemove",this.mouseMove.bind(this),{passive:!0}),eventHandler.addEvent("keys-ArrowUp, keys-ArrowDown, keys-ArrowLeft, keys-ArrowRight, keys-KeyQ, keys-KeyE",this.keyPressed.bind(this))}mouseDown(){this.mousePressed=!0,this.lastMouse=null}mouseUp(){this.mousePressed=!1,this.lastMouse=null}mouseMove(e){if(this.mousePressed&&!gui.modal.open){if(this.lastMouse){let t=this.mouse,a=this.rotation;t.x+=.2*(this.lastMouse.x-e.clientX),t.y+=.2*(this.lastMouse.y-e.clientY),a.x=VTUtils.map(t.x,-c.width,c.width,180,-180,!1),a.y=VTUtils.map(t.y,-c.height,c.height,180,-180,!1)}this.lastMouse={x:e.clientX,y:e.clientY}}}keyPressed(e){switch(e){case"keys-ArrowUp":this.translate.z+=10;break;case"keys-ArrowDown":this.translate.z-=10;break;case"keys-ArrowLeft":this.translate.x-=10;break;case"keys-ArrowRight":this.translate.x+=10;break;case"keys-KeyQ":this.translate.y+=10;break;case"keys-KeyE":this.translate.y-=10}}}class Template{constructor(){this.tpl={}}async loadTemplate(e){let t=this;this.tpl[e]||(t.tpl[e]=await FetchHandler.loadFile(templateDir+e+".tpl",!1))}async loadArray(e){for(let t of e)await this.loadTemplate(t)}parseTemplate(e,t){if(!this.tpl[e])return"";let a,i=this.tpl[e];for(;null!==(a=templateEx.exec(i));){a.index===templateEx.lastIndex&&templateEx.lastIndex++;let e=a[0],s=t[a[1]];null==s&&(s=""),i=i.replace(e,s)}return i}}const templateEx=/\$(.*?)\$/gm,templateDir="/out/tpl/";class ShaderHandler{constructor(e){this.gl=e,this.shaderNames=[],this.shaders={},this.programs={}}setGL(e){this.gl=e}async loadShader(e,t){this.shaderNames.push(e),await this.load(e,t+e+".vert",this.gl.VERTEX_SHADER),await this.load(e,t+e+".frag",this.gl.FRAGMENT_SHADER)}async load(e,t,a){let i=e+"_"+a;if(!this.shaders[i]){let e=await FetchHandler.loadFile(t,!1),s=this.createShader(e,a);s&&(this.shaders[i]=s)}return!!this.shaders[i]}getShader(e,t){let a=e+"_"+t;return this.shaders[a]}getAllShaders(){return this.shaderNames}async createProgramForEach(e){e=e||this.shaderNames;for(let t=0;t<e.length;t++){let a=e[t];if(!await shaderHandler.createProgram(a,[a]))return!1}return!0}createShader(e,t){let a=this.gl,i=a.createShader(t);return a.shaderSource(i,e),a.compileShader(i),a.getShaderParameter(i,a.COMPILE_STATUS)?i:(console.error(a.getShaderInfoLog(i)),a.deleteShader(i),null)}createProgram(e,t){let a=this.gl,i=a.createProgram();for(let e=0;e<t.length;e++)a.attachShader(i,this.getShader(t[e],a.VERTEX_SHADER)),a.attachShader(i,this.getShader(t[e],a.FRAGMENT_SHADER));return a.linkProgram(i),a.getProgramParameter(i,a.LINK_STATUS)?(this.programs[e]=i,i):(console.log(a.getProgramInfoLog(i)),a.deleteProgram(i),null)}getProgram(e){return this.programs[e]}use(e){let t=this.programs[e];return this.gl.useProgram(t),t}async loadArray(e,t){let a=this;for(const i of e)await a.loadShader(i,t);await a.createProgramForEach(e)}}const AudioContext=window.AudioContext||window.webkitAudioContext;class AudioHandler{async init(){this.isStarted=!1,this.audioFile=new Audio,this.actx=new AudioContext,this.analyser=this.actx.createAnalyser(),this.analyser.fftSize=4096,this.lastSong=null,await this.connectAll()}async connectAll(){this.source=this.actx.createMediaElementSource(this.audioFile),this.source.connect(this.analyser),this.analyser.connect(this.actx.destination),this.audioFile.addEventListener("ended",player.nextSong.bind(player))}async start(){""!==this.audioFile.src&&(this.isStarted||(this.isStarted=!0,await this.actx.resume()))}async stop(){this.isStarted&&(this.isStarted=!1,await this.actx.suspend())}fftSize(e){this.analyser.fftSize=e}smoothing(e){this.analyser.smoothingTimeConstant=e}loadSong(e){if(!e)return NotificationHandler.createNotification("Sorry!<br> Currently no Song is uploaded!","error",2e3),!1;let t=this,a=e.file;t.lastSong&&URL.revokeObjectURL(t.lastSong),t.lastSong=this.audioFile.src=URL.createObjectURL(a),this.isStarted||this.start().catch(alert),this.audioFile.play().then(t=>{pConf.get("showPlaying","true")&&NotificationHandler.createNotification("<span class='now-playing'>Now Playing:</span>"+e.getAudioName(),"info",pConf.get("showPlayingTime",1e3)),window.dispatchEvent(new CustomEvent("playSong"))}).catch(e=>{NotificationHandler.createNotification(e.message,"error",1e3),player.nextSong()})}getIntArray(e){let t=new Uint8Array(e);return this.analyser.getByteFrequencyData(t),t}getFloatArray(){let e=new Float32Array(this.analyser.fftSize);return this.analyser.getFloatTimeDomainData(e),e}}class AudioPlayerFile{constructor(e,t){this.file=e,this.name=this.getName(),this.id3=null,this.index=t}getName(){let e=this.file.name.split(".");return e.pop(),e=e.join("."),e}getID3Tag(e){return e||null===this.id3?(eventHandler.sendData("getData",{file:this.file,name:this.name,index:this.index,force:!0===e}),{title:this.name,artist:"VA"}):this.id3}getAudioName(){let e=this.getID3Tag();return template.parseTemplate("audio-information",e)}}class FetchHandler{static files={};static async loadFiles(e,t){let a=[];for(let i=0;i<e;i++)a.push(await FetchHandler.loadFile(e[i],t));return a}static async loadFile(e,t){e+="?v="+version;let a=FetchHandler.files;if(a[e])return a[e];let i=await FetchHandler.tryFromCache(e);return t&&(i=JSON.parse(i)),a[e]=i,i}static async tryFromCache(e){if(caches){let t=await caches.open("vis3d-pwa-1"),a=await t.match(e);return a||(a=await fetch(e)),await a.text()}}}class PlayerConfigHandler{async init(){await template.loadArray(["config/nav","config/content","config/visualitem"]),this.last="base",$(".settings-icon").addEventListener("click",this.open.bind(this)),$("modal-content").addDelegatedEventListener("click",".config-nav .item",this.navHandler.bind(this))}open(){if(void 0===this.content){let e=template.parseTemplate("config/nav",{});e+=template.parseTemplate("config/content",{content:""}),this.content=e}gui.modal.renderModal("Settings",this.content,"by VersusTuneZ"),this.handleById(),gui.modal.showModal()}navHandler(e,t){this.last=t.dataset.id,this.handleById()}handleById(){let e=this.last;new VisualConfig("visual"===e,"base"===e);let t=$(".config-nav .item.active"),a=$('.config-nav .item[data-id="'+e+'"]');t&&t.removeClass("active"),a&&a.addClass("active")}}class VisualConfig{static visualTemplates={};constructor(e,t){this.content=$("modal-content .config-content"),e?this.renderVisualConfig(visual.c):t?this.renderBase():this.renderVisuals()}renderVisuals(){let e=Object.keys(visual.visuals),t='<section class="visuals">';for(let a=0;a<e.length;a++)t+=template.parseTemplate("config/visualitem",{title:visual.visuals[e[a]].name,id:e[a],active:e[a]===visual.c?"active":""});t+="</div>",this.content.innerHTML=t}async renderBase(){let e=await this.loadVisualConfig("base"),t=create("section");t.addClass("base"),t.innerHTML=GUIHelper.fromJSON(e,pConf),this.content.innerHTML=t.outerHTML}async renderVisualConfig(e){let t=await this.loadVisualConfig(e,vConf),a=create("section");a.addClass("visual"),a.innerHTML=GUIHelper.fromJSON(t,vConf),a.innerHTML+=GUIHelper.createButton({action:"resetVConf",name:"Reset Visual Config"}),a.innerHTML+=GUIHelper.createButton({action:"makeModalTransparent",name:"toggle Modal Opacity"}),this.content.innerHTML=a.outerHTML}async loadVisualConfig(e){let t=VisualConfig.visualTemplates;return t[e]||(t[e]=await FetchHandler.loadFile("/out/gui/"+e+".json",!0)),t[e]}}class Player{async init(){this.playlist=new Playlist}nextSong(){let e=this.playlist.getNext();audioHandler.loadSong(e)}prevSong(){let e=this.playlist.getPrevious();audioHandler.loadSong(e)}playStop(){if(!audioHandler.lastSong){let e=this.playlist.getCurrent();return void audioHandler.loadSong(e)}let e=audioHandler.audioFile;e.paused?e.play():e.pause(),window.dispatchEvent(new CustomEvent("playSong"))}stop(){if(!audioHandler.lastSong)return;let e=audioHandler.audioFile;e.pause(),e.currentTime=0,window.dispatchEvent(new CustomEvent("playSong"))}playByID(e){this.playlist.index=e;let t=this.playlist.getCurrent();audioHandler.loadSong(t)}}const PAGINATIONLIMIT=50;class Playlist{constructor(){this.list=[],this.shuffled=[],this.index=0,this.page=0,this.isShuffle=pConf.get("shuffle",!1),$("body").addDelegatedEventListener("change",'input[type="file"]',this.changeFiles.bind(this)),$("body").addDelegatedEventListener("click",".pagination .item",this.handlePagination.bind(this)),eventHandler.addEvent("id3-request",this.handle.bind(this)),eventHandler.addEvent("id3-request-force",this.forceID3.bind(this))}shuffle(){let e=this.list.length;if(e<3)this.shuffled=[0,1,2];else for(let t=0;t<e;t++){let a=VTUtils.randomInt(0,e-1);this.swap(t,a)}}swap(e,t){this.shuffled[e]=t,this.shuffled[t]=e}getNext(){let e=this.list,t=e.length-1,a=this.index+1;return a>t&&(a=0),this.index=a,e[this.getRealIndex()]}getPrevious(){let e=this.list,t=e.length-1,a=this.index-1;return a<0&&(a=t),this.index=a,e[this.getRealIndex()]}getCurrent(){return this.list[this.getRealIndex()]}setPlaylist(e){this.index=0,this.forceData=void 0,this.list=e,this.shuffle()}handlePagination(e,t){t.hasClass("inactive")||(t.hasClass("next-site")?this.renderPagination(this.page+1):this.renderPagination(this.page-1))}renderPagination(e){void 0===e&&(e=this.page);let t=this.list.length,a=Math.ceil(t/50)-1;e<0&&(e=0),e>a&&(e=a);let i=50*e,s=i+50,n="";if(this.page=e,s>=t&&(s=t),t>0){let e=this.list;for(let t=i;t<s;t++){let a={index:t.toString(),nr:t+1,title:e[this.getRealIndex(t)].getAudioName(),active:audioHandler.audioFile.paused||t!==this.index?"":"active"};n+=template.parseTemplate("playlist-item",a)}}else n="<h1>No Songs uploaded!</h1>";let r=a>1&&e<a;gui.modal.renderModal("Playlist",template.parseTemplate("playlist",{content:n}),template.parseTemplate("playlist-footer",{prevActive:e>0?"active":"inactive",nextActive:r?"active":"inactive",page:e+1+" / "+parseInt(a+1)}))}changeFiles(e,t){if("upload-dir"!==t.id)return;let a=[],i=0;for(let e of t.files)if(e&&-1!==e.type.indexOf("audio")&&null===e.name.match(".m3u")){let t=new AudioPlayerFile(e,i++);a.push(t)}this.setPlaylist(a),a.length>0?(NotificationHandler.createNotification("Songs added successfully!<br> Songs: "+a.length,"success",3e3),this.renderPagination(0)):NotificationHandler.createNotification("File Upload failed!","error",3e3)}getRealIndex(e){return void 0===e&&(e=this.index),this.isShuffle?this.shuffled[e]:e}handle(e){let t=e.index;"waiting"!==e.status&&(this.list[t].id3=e,this.timeout&&window.clearTimeout(this.timeout),this.timeout=setTimeout(this.renderPagination.bind(this),100))}forceID3(e){let t=this;t.forceData||(t.forceData={},t.forceNotification=NotificationHandler.createNotification("TagReader -> 0 / "+t.list.length,"info",-1));let a=e.index;if("waiting"===e.status)return;t.list[a].id3=e,t.forceData[a]=!0;let i=Object.keys(t.forceData).length;this.forceNotification.updateMessageOnly("TagReader -> "+i+" / "+t.list.length),i===t.list.length&&t.forceNotification.remove()}}class GUI{async init(){this.data={},this.modal=new Modal,await template.loadArray(["playlist-item","playlist","playlist-footer","audio-information","inputs/color","inputs/input","inputs/slider","inputs/switch","inputs/select","inputs/option","help"]),this.initDropZone()}openHelp(){gui.modal.renderModal("Help",template.parseTemplate("help",{})),gui.modal.showModal()}initDropZone(){"drag dragstart dragend dragover dragenter dragleave drop".split(" ").forEach(e=>{window.addEventListener(e,async e=>{e.preventDefault(),e.stopPropagation(),"drop"===e.type&&(e.dataTransfer.files.length>0?(e.dataTransfer.id="upload-dir",player.playlist.changeFiles(e,e.dataTransfer)):alert("Sorry you need to upload files!"))})})}}class GUIHelper{static fromJSON(e,t){let a=[];for(let i of e)switch(i.type){case"slider":a.push(GUIHelper.createSliders(i,t));break;case"color":a.push(GUIHelper.createColorPicker(i,t));break;case"checkbox":a.push(GUIHelper.createCheckbox(i,t));break;case"input":a.push(GUIHelper.createInputField(i,t));break;case"select":a.push(GUIHelper.createSelect(i,t));break;case"button":a.push(GUIHelper.createButton(i,t));break;default:console.error("Unknown Type: "+i.type)}return a.join(" ")}static createSliders(e,t){let a="";if("object"==typeof e.name)for(let i=0;i<e.name.length;i++){let s={};Object.assign(s,e),s.showName=GUIHelper.richShowName(e,e.name[i].firstUpper()),s.name=GUIHelper.richName(e,e.props[i]),a+=GUIHelper.createSlider(s,t)}else a=GUIHelper.createSlider(e,t);return a}static createSlider(e,t){let a={};return Object.assign(a,e),a.value=t.get(a.name,a.value),template.parseTemplate("inputs/slider",a)}static createColorPicker(e,t){let a={};return Object.assign(a,e),a.value=t.get(a.name,a.value),template.parseTemplate("inputs/color",a)}static createCheckbox(e,t){let a={};return Object.assign(a,e),a.value=t.get(a.name,a.value)?"checked":"",template.parseTemplate("inputs/switch",a)}static createInputField(e,t){let a={};return Object.assign(a,e),a.value=t.get(a.name,a.value),template.parseTemplate("inputs/input",a)}static createSelect(e,t){let a={};Object.assign(a,e),a.value=t.get(a.name,a.value);let i="";for(let e=0;e<a.options.length;e++)i+=template.parseTemplate("inputs/option",{value:a.options[e]});return a.options=i,a.event="visualConf",a.conf=t.type,template.parseTemplate("inputs/select",a)}static richName(e,t){return""!==e.group?e.group+"-"+t:t}static richShowName(e,t){return""!==e.group?e.group.firstUpper()+" "+t:t}static createButton(e,t){return`<div class='button spaced' data-action="${e.action}">${e.name}</div>`}}class Modal{constructor(){this.currentModal="",this.modal=$("#modal"),this.open=!1,this.parent=this.modal.parentNode,this.modal.addDelegatedEventListener("click","header .close",this.closeModal.bind(this))}resetModal(){this.renderModal("","","")}renderModal(e,t,a){$("#modal").removeClass("lightMode"),this.currentModal=e,this.renderHeader(e),this.renderContent(t),this.renderFooter(a)}renderHeader(e){$("header .headline",this.modal).innerHTML=e}renderContent(e){$("modal-content",this.modal).innerHTML=e}renderFooter(e){$("modal-footer .inner",this.modal).innerHTML=e||"by VersusTuneZ"}closeModal(){this.parent.addClass("hide"),this.open=!1}isCurrent(e){return e===this.currentModal}showModal(){this.parent.removeClass("hide"),this.open=!0}}class Visual{constructor(){this.data=[],this.dataArray=[],this.name="Default"}updateData(){}updateFFT(e){}draw(){}setup(){}}class VisualDrawer{constructor(){this.visuals={wave:new Wave,wave2d:new Wave2D},this.lastMainColor={base:"#-1",color:[0,0,0]},this.lastSecondColor={base:"#-1",color:[0,0,0]}}init(){this.switch(pConf.get("visual","wave2d")),this.updateLoop()}switch(e){null!=this.visuals[e]&&(this.c=e,vConf.loadConfigByName(this.c),this.visuals[this.c].setup(),pConf.set("visual",this.c),pConf.save())}updateLoop(){let e=this.visuals[this.c],t=shaderHandler.use(this.c);this.updateSeekbar(),this.prepare(t),e.updateData(),e.draw(t),requestAnimationFrame(this.updateLoop.bind(this))}updateSeekbar(){cInfo.width=window.innerWidth,cInfo.height=window.innerHeight;let e=audioHandler.audioFile;if(ctx.clearRect(0,0,cInfo.width,cInfo.height),!e.paused&&pConf.get("showSeekbar",!0)){let t=e.duration,a=e.currentTime/t*cInfo.width;ctx.fillStyle=pConf.get("seekColor","#fff"),ctx.fillRect(0,c.height-10,a,c.height)}}prepare(e){c.width=window.innerWidth,c.height=window.innerHeight,gl.viewport(0,0,gl.canvas.width,gl.canvas.height),gl.clearColor(0,0,0,parseFloat(pConf.get("alphaValue",0))),gl.clear(gl.COLOR_BUFFER_BIT|gl.DEPTH_BUFFER_BIT),gl.enable(gl.DEPTH_TEST),gl.depthFunc(gl.LEQUAL),gl.enable(gl.CULL_FACE),this.setColor(e)}setColor(e){let t=gl.getUniformLocation(e,"u_baseColor"),a=gl.getUniformLocation(e,"u_maxColor"),i=this.lastMainColor,s=this.lastSecondColor;this.updateColor("lastMainColor","baseColor"),this.updateColor("lastSecondColor","gradientToColor"),gl.uniform3fv(t,i.color),gl.uniform3fv(a,s.color)}updateColor(e,t){let a=this[e],i=vConf.get(t,"#ffffff");i!==a.base&&(a.color=hexToRgb(i),a.base=i)}}class ImageUploader{async init(){this.image=pConf.get("bgURL",""),this.color=pConf.get("bgColour","#000000"),this.alpha=pConf.get("alphaValue",.5),this.getRealImage(),this.applyValues(),$("#modal").addDelegatedEventListener("change",'#image-upload input:not([type="color"])',this.changeHandler.bind(this)),$("#modal").addDelegatedEventListener("input","#image-upload input#color",this.changeHandler.bind(this))}async renderModal(){await template.loadTemplate("image"),gui.modal.resetModal(),gui.modal.renderModal("Background-Image",template.parseTemplate("image",{value:this.image,bgValue:this.color,alphaValue:this.alpha}),""),gui.modal.showModal()}changeHandler(e,t){"color"===t.id?this.color=t.value:"alphaValue"===t.id?this.alpha=t.value:(pConf.set("bgMode",t.id),"image"===t.id?(t.files[0].toBase64((e,t)=>{t?alert("Error converting image!"):(pConf.set("bgURL",e.currentTarget.result),pConf.save())}),this.image=URL.createObjectURL(t.files[0])):(this.image=t.value,pConf.set("bgURL",this.image))),pConf.set("bgColour",this.color),pConf.set("alphaValue",this.alpha),this.applyValues(),pConf.save()}applyValues(){let e=$("body");e.style.backgroundImage="url("+this.image+")",e.style.backgroundColor=this.color}getRealImage(){let e=pConf.get("bgMode"),t=pConf.get("bgURL","");if("image"===e){if(""!==t&&t.startsWith("data:image")){let e=t.split(";"),a=e.shift(),i=e.join(";").replace("base64,","");this.image=URL.createObjectURL(b64toBlob(i,a))}}else this.image=t}}const imageUploader=new ImageUploader;class NotificationHandler{static instance=new NotificationHandler;constructor(){this.outer=$(".notification"),this.notifications=[]}async init(){await template.loadTemplate("notification")}static createNotification(e,t,a){a=parseInt(a||"3000");let i=NotificationHandler.instance,s=new Notification(e,t,a);return i.notifications.push(s),s.show(),s}}class Notification{constructor(e,t,a){this.outer=NotificationHandler.instance.outer,this.message=e,this.type=t,this.time=a,this.isRemoved=!1}async show(){let e=this,t=-1===e.time;e.item=create("div"),e.item.addClass("notification-item, "+e.type),t&&(e.type+=" endless"),e.updateContent(e.message),this.outer.prepend(e.item),t||setTimeout(this.remove.bind(this),e.time)}async remove(){if(this.isRemoved)return;this.isRemoved=!0,this.outer.removeChild(this.item);let e=NotificationHandler.instance.notifications,t=e.indexOf(this);e.splice(t,1)}updateContent(e){let t={message:e,time:-1===this.time?1e3:this.time+1,type:this.type};this.item.innerHTML=template.parseTemplate("notification",t)}updateMessageOnly(e){let t=$(".message",this.item);t&&(t.innerHTML=e)}}class Config{static allConfigs={};constructor(e){this.config={},this.name="",this.type=e,Config.allConfigs[e]=this}loadConfigByName(e){this.save(),this.name="config-"+e;let t=localStorage.getItem(this.name);t&&(this.config=JSON.parse(t))}save(){""!==this.name&&localStorage.setItem(this.name,JSON.stringify(this.config))}set(e,t){this.config[e]=t}remove(e){delete this.config[e]}get(e,t){let a=this.config[e];return null==a&&(this.config[e]=t,a=t),a}reset(){NotificationHandler.createNotification("CONFIG REQUEST SUCCESS FOR "+this.type,"success",2e3),this.config={},this.save()}}class Sphere extends Visual{constructor(){super(),this.name="Sphere"}draw(){}setup(){}}class Wave extends Visual{constructor(){super(),this.name="3D Wave"}updateData(){let e=audioHandler.getFloatArray(),t=2/e.length,a=-1,i=0;for(let s=0;s<e.length;s++)this.data[i]=a,this.data[i+1]=e[s],this.data[i+2]=0,this.data[i+3]=a,this.data[i+6]=a,this.data[i+8]=e[s+1]||0,i+=9,a+=t}draw(e){this.prepare(e);let t=this.position,a=gl.createBuffer();this.rotate(e),gl.bindBuffer(gl.ARRAY_BUFFER,a),gl.bufferData(gl.ARRAY_BUFFER,new Float32Array(this.data),gl.DYNAMIC_DRAW);let i=gl.createVertexArray();gl.bindVertexArray(i),gl.enableVertexAttribArray(t),gl.vertexAttribPointer(t,3,gl.FLOAT,!0,0,0),gl.drawArrays(vConf.get("waveForm",gl.TRIANGLES),0,this.data.length/3),this.afterDraw()}rotate(e){let t=[1/(c.width/c.height),0,0,0,0,.6,0,0,0,0,1,0,0,0,0,1];t=TDUtils.multiply(t,TDUtils.xRotation(vConf.get("rotation-x",10))),t=TDUtils.multiply(t,TDUtils.yRotation(vConf.get("rotation-y",50))),t=TDUtils.multiply(t,TDUtils.zRotation(vConf.get("rotation-z",-30)));let a=gl.getUniformLocation(e,"u_matrix");gl.uniformMatrix4fv(a,!1,t)}setup(){this.updateFFT(vConf.get("fftSize",4096)),vConf.get("rotation-z",-30),vConf.get("rotation-y",50),vConf.get("rotation-x",10)}updateFFT(e){audioHandler.fftSize(e),this.data=new Float32Array(9*e)}prepare(e){this.position=gl.getAttribLocation(e,"a_position"),this.color=gl.getUniformLocation(e,"u_color");let t=gl.getUniformLocation(e,"u_lightPos"),a=gl.getUniformLocation(e,"u_light");gl.uniform3fv(t,[vConf.get("light-x",0),vConf.get("light-y",5),vConf.get("light-z",-56)]),gl.uniform1f(a,parseFloat(vConf.get("light-strength",.3)))}afterDraw(){TDUtils.updateRotate("rotation-x",10),TDUtils.updateRotate("rotation-y",50),TDUtils.updateRotate("rotation-z",-30),vConf.save()}}class Wave2D extends Visual{constructor(){super(),this.name="2D Wave"}updateData(){let e=audioHandler.getFloatArray(),t=c.width/e.length,a=0,i=c.height/2,s=i/2,n=0;for(let r=0;r<e.length;r++)this.data[n]=a,this.data[n+1]=i+e[r]*s,this.data[n+2]=e[r],n+=3,a+=t}draw(e){this.prepare(e);let t=this.position,a=gl.createBuffer();this.rotate(e),gl.bindBuffer(gl.ARRAY_BUFFER,a),gl.bufferData(gl.ARRAY_BUFFER,new Float32Array(this.data),gl.DYNAMIC_DRAW);let i=gl.createVertexArray();gl.bindVertexArray(i),gl.enableVertexAttribArray(t),gl.vertexAttribPointer(t,3,gl.FLOAT,!0,0,0),gl.drawArrays(vConf.get("waveForm",gl.LINE_STRIP),0,this.data.length/3),this.afterDraw()}rotate(e){let t=new GLHelper(e);t.project(),t.addFudgeFactor(vConf.get("fudgeFactor",1)),t.translate([camera.translate.x,camera.translate.y,camera.translate.z]),t.rotateX(camera.mouse.x),t.rotateY(camera.mouse.y),t.rotateZ(vConf.get("rotation-z",0)),t.applyMatrix()}setup(){this.updateFFT(vConf.get("fftSize",16384))}updateFFT(e){audioHandler.fftSize(e),this.data=new Float32Array(3*e)}prepare(e){this.position=gl.getAttribLocation(e,"a_position"),GLHelper.uniform3fv(e,"u_lightPos",vConf.get("light",[0,5,-56]))}afterDraw(){TDUtils.updateRotate("rotation-x",0),TDUtils.updateRotate("rotation-y",0),TDUtils.updateRotate("rotation-z",0),vConf.save()}}class Water extends Visual{constructor(){super(),this.name="Water"}draw(){}setup(){audioHandler.fftSize(256)}}class EventHandler{constructor(){this.events={}}addEvent(e,t){let a=e.split(",");for(let e of a)this.events[e.trim()]=t}sendData(e,t){worker.postMessage({cmd:e,data:t})}handleEvent(e){let t=e.data;if(!t.cmd)return!1;if(this.events[t.cmd]){try{this.events[t.cmd](t.data)}catch(e){console.error("[EventHandler] > "+e.message)}return!0}return!1}}async function initHandler(){let e=$("body");$(".playlist.menu-icon").addEventListener("click",e=>{player.playlist.renderPagination(player.playlist.page),gui.modal.showModal()}),e.addDelegatedEventListener("click",".playlist-item",(e,t)=>{let a=t.dataset.index;player.playByID(parseInt(a)),togglePlayButton("pause")}),e.addDelegatedEventListener("click",".controls button",(e,t)=>{switch(t.id){case"previous":player.prevSong();break;case"next":player.nextSong();break;case"play":player.playStop();break;case"shuffle":toggleShuffle()}}),window.addEventListener("playSong",setActiveOnPlaylist),window.addEventListener("playSong",e=>{togglePlayButton(audioHandler.audioFile.paused?"play":"pause")}),$(".upload-image").addEventListener("click",imageUploader.renderModal.bind(imageUploader)),e.addDelegatedEventListener("click",".readAll",forceAllRead),e.addDelegatedEventListener("input",'.input-range input[type="range"]',(e,t)=>{$(".current",t.parentNode).innerText=t.value}),e.addDelegatedEventListener("input",'input[type="color"]',(e,t)=>{$(".colorBlob",t.parentNode).style.backgroundColor=t.value}),e.addDelegatedEventListener("click",".visual-item",(e,t)=>{visual.switch(t.dataset.id||"wave"),$("modal-content .visuals .active").removeClass("active"),t.addClass("active")}),e.addDelegatedEventListener("input","section.base input",(e,t)=>{"checkbox"===t.type?pConf.set(t.name,t.checked):setValue(t.name,t.value,pConf,t.dataset.type),pConf.save()}),e.addDelegatedEventListener("input","section.visual input",(e,t)=>{"checkbox"===t.type?vConf.set(t.name,t.checked):setValue(t.name,t.value,vConf,t.dataset.type),vConf.save()}),e.addDelegatedEventListener("click",".button[data-action]",(e,t)=>{switch(t.dataset.action){case"resetVConf":vConf.reset(),setTimeout(e=>{playerConf.handleById()},30);break;case"makeModalTransparent":$("#modal").toggleClass("lightMode")}}),$(".help.menu-icon").addEventListener("click",gui.openHelp),document.onfullscreenchange=t=>{e.hasClass("fullscreen")?e.removeClass("fullscreen"):e.addClass("fullscreen")}}function forceAllRead(){let e=player.playlist.list;for(let t=0;t<e.length;t++)e[t].getID3Tag(!0)}function setValue(e,t,a,i){switch(i){case"float":t=parseFloat(t);break;case"int":t=parseInt(t)}a.set(e,t)}function setActiveOnPlaylist(e){let t=$('.playlist-item[data-index="'+player.playlist.index+'"]'),a=$(".playlist-item.active");a&&a.removeClass("active"),t&&t.addClass("active")}function toggleShuffle(e){let t=player.playlist.isShuffle;if(!1!==e){t=!t;let e=t?"enabled":"disabled";NotificationHandler.createNotification("Shuffle: "+e,"info",500),pConf.set("shuffle",t),pConf.save(),player.playlist.isShuffle=t}$("#shuffle").toggleCheck("active",t)}function togglePlayButton(e){$$("#play .icon").forEach(t=>{t.dataset.name===e?t.removeClass("hide"):t.addClass("hide")})}!function(){const e=$("body");e.addDelegatedEventListener("click","custom-select .label",(e,t)=>{let a=t.parentNode,i=$$("custom-option",a),s=$("custom-options",a);if(a.hasClass("open"))s.style.maxHeight="",a.removeClass("open");else{let e=0;i.forEach((function(t){e+=t.offsetHeight})),s.style.maxHeight=e+"px",a.addClass("open")}}),e.addDelegatedEventListener("click","custom-select custom-option",(e,t)=>{let a=t.closest("custom-select"),i=$("input",a);$$("custom-option.active").forEach(e=>{e.removeClass("active")}),t.addClass("active"),i&&(i.value=t.dataset.value||t.innerText,$(".label",a).innerText=t.innerText,a.removeClass("open"),t.parentNode.style.maxHeight="",window.dispatchEvent(new CustomEvent("selectChanged",{detail:{select:a,event:a.dataset.event,value:i.value,name:i.name}})))}),window.addEventListener("selectChanged",e=>{"visualConf"===e.detail.event&&(e.preventDefault(),e.stopPropagation(),function(e){try{let t=e.value,a=Config.allConfigs[e.select.dataset.conf];"fftSize"===e.name&&(t=parseInt(e.value),visual.visuals[visual.c].updateFFT(t)),a.set(e.name,t),a.save()}catch(e){console.error(e)}}(e.detail))})}();class KeyHandler{async init(){await this.mediaKeys(),await this.addKeyHandler(),window.addEventListener("keydown",this.keyHandler.bind(this))}async mediaKeys(){if("mediaSession"in navigator){let e=navigator.mediaSession;e.setActionHandler("play",player.playStop.bind(player)),e.setActionHandler("pause",player.playStop.bind(player)),e.setActionHandler("previoustrack",player.prevSong.bind(player)),e.setActionHandler("nexttrack",player.nextSong.bind(player)),e.setActionHandler("stop",player.stop.bind(player))}}async addKeyHandler(){eventHandler.addEvent("keys-Space",player.playStop.bind(player)),eventHandler.addEvent("keys-KeyN",player.nextSong.bind(player)),eventHandler.addEvent("keys-KeyV",player.prevSong.bind(player)),eventHandler.addEvent("keys-KeyS",playerConf.open.bind(playerConf)),eventHandler.addEvent("keys-KeyS-shift",toggleShuffle),eventHandler.addEvent("keys-KeyB",imageUploader.renderModal.bind(imageUploader)),eventHandler.addEvent("keys-KeyF-shift",forceAllRead),eventHandler.addEvent("keys-KeyH",gui.openHelp),eventHandler.addEvent("keys-KeyP",e=>{player.playlist.renderPagination(player.playlist.page),gui.modal.showModal()}),eventHandler.addEvent("keys-Escape, keys-KeyC-shift",e=>{gui.modal.resetModal(),gui.modal.closeModal()}),eventHandler.addEvent("keys-F11",e=>{document.fullscreenElement?document.exitFullscreen().catch(console.error):document.body.requestFullscreen().catch(console.error)})}async keyHandler(e){let t="keys-"+e.code+(e.shiftKey?"-shift":"")+(e.ctrlKey?"-ctrl":"");eventHandler.handleEvent({data:{cmd:t,data:t}})&&(e.preventDefault(),e.stopPropagation())}}class Startup{constructor(){this.modules={startup:!1,"id3-ready":!1}}moduleLoaded(e){this.modules[e]=!0,this.allModulesLoaded()}allModulesLoaded(){for(let e in this.modules)if(!this.modules[e])return!1;return window.dispatchEvent(new CustomEvent("startupFin")),!0}}const shaderHandler=new ShaderHandler(null),audioHandler=new AudioHandler,gui=new GUI,visual=new VisualDrawer,template=new Template,player=new Player,vConf=new Config("visual"),pConf=new Config("player"),worker=new Worker("/out/js/worker.min.js"),startup=new Startup,eventHandler=new EventHandler,playerConf=new PlayerConfigHandler,keyHandler=new KeyHandler,version=1,camera=new Camera;let c,gl,cInfo,ctx,sw;async function startUP(){if("serviceWorker"in navigator&&(sw=await navigator.serviceWorker.register("/sw.js")),pConf.loadConfigByName("default"),c=$("#c"),gl=c.getContext("webgl2"),cInfo=$("#cInfo"),ctx=cInfo.getContext("2d"),!gl)return alert("SORRY THE BROWSER DOESN'T SUPPORT WEBGL2"),!1;shaderHandler.setGL(gl),await shaderHandler.loadArray(["wave","sphere","water","wave2d"],"/shaders/"),await NotificationHandler.instance.init(),await audioHandler.init(),await player.init(),await camera.init(),await visual.init(),await gui.init(),await imageUploader.init(),await playerConf.init(),await keyHandler.init(),await initHandler(),toggleShuffle(!1)}worker.addEventListener("message",e=>{"startup"!==e.data.status?eventHandler.handleEvent(e):startup.moduleLoaded(e.data.cmd)}),window.addEventListener("startupFin",e=>{setTimeout(e=>{$(".loading-screen").remove()},100)}),startUP().then(e=>{startup.moduleLoaded("startup")});