// ==UserScript==
// @name            Blue Marble
// @name:en         Blue Marble
// @namespace       https://github.com/SwingTheVine/
// @version         0.90.76
// @description     A userscript to enhance the user experience on Wplace.live. This includes, but is not limited to: uploading images to display locally on a canvas, adding a button to move the Wplace color palette menu, and other QoL features.
// @description:en  A userscript to enhance the user experience on Wplace.live. This includes, but is not limited to: uploading images to display locally on a canvas, adding a button to move the Wplace color palette menu, and other QoL features.
// @author          SwingTheVine
// @license         MPL-2.0
// @supportURL      https://discord.gg/tpeBPy46hf
// @homepageURL     https://bluemarble.lol/
// @icon64          data:image/png;base64, 
// @updateURL       https://raw.githubusercontent.com/SwingTheVine/Wplace-BlueMarble/main/dist/BlueMarble-Standalone.user.js
// @downloadURL     https://raw.githubusercontent.com/SwingTheVine/Wplace-BlueMarble/main/dist/BlueMarble-Standalone.user.js
// @match           https://wplace.live/*
// @grant           GM_getResourceText
// @grant           GM_addStyle
// @grant           GM.setValue
// @grant           GM_getValue
// @grant           GM_deleteValue
// @grant           GM_xmlhttpRequest
// @grant           GM.download
// @connect         telemetry.thebluecorner.net
// @antifeature     tracking Anonymous opt-in telemetry data
// @noframes
// ==/UserScript==

// Wplace  --> https://wplace.live
// License --> https://www.mozilla.org/en-US/MPL/2.0/
// Donate  --> https://ko-fi.com/swingthevine

/*!
  This script is not affiliated with Wplace.live in any way, use at your own risk.
  This script is not affiliated with any userscript manager.
  The author of this userscript is not responsible for any damages, issues, loss of data, or punishment that may occur as a result of using this script.
  This script is provided "as is" under the MPL-2.0 license.
  The "Blue Marble" icon is licensed under CC0 1.0 Universal (CC0 1.0) Public Domain Dedication.
  The "Blue Marble" image is owned by NASA.
*/

(()=>{var t=t=>{throw TypeError(t)},e=(e,n,i)=>n.has(e)?t("Cannot add the same private member more than once"):n instanceof WeakSet?n.add(e):n.set(e,i),n=(e,n,i)=>(((e,n)=>{n.has(e)||t("Cannot access private method")})(e,n),i);function i(t){return new Promise(e=>setTimeout(e,t))}function s(t){return(new Intl.NumberFormat).format(t)}function o(t){return new Intl.NumberFormat(void 0,{style:"percent",t:2,i:2}).format(t)}function a(t){return t.toLocaleString(void 0,{o:"long",l:"numeric",h:"2-digit",m:"2-digit",u:"2-digit"})}function r(t){const e=document.createElement("div");return e.textContent=t,e.innerHTML}function l(...t){(0,console.log)(...t)}function c(...t){(0,console.error)(...t)}function h(...t){(0,console.warn)(...t)}function m(t,e){if(0===t)return e[0];let n="";const i=e.length;for(;t>0;)n=e[t%i]+n,t=Math.floor(t/i);return n}function d(t,e){let n=0;const i=e.length;for(const s of t){const t=e.indexOf(s);-1==t&&c(`Invalid character '${s}' encountered whilst decoding! Is the decode alphabet/base incorrect?`),n=n*i+t}return n}function u(t){let e="";for(let n=0;n<t.length;n++)e+=String.fromCharCode(t[n]);return btoa(e)}function b(t){const e=atob(t),n=new Uint8Array(e.length);for(let t=0;t<e.length;t++)n[t]=e.charCodeAt(t);return n}function p(t){const e=t.map(t=>(t/=255)<=.03928?t/12.92:Math.pow((t+.055)/1.055,2.4));return.2126*e[0]+.7152*e[1]+.0722*e[2]}function f(t,e,n){return Array.isArray(t)&&([t,e,n]=t),(1<<24|t<<16|e<<8|n).toString(16).slice(1)}var g,w,y,$,x,v=[{id:0,premium:!1,name:"Transparent",rgb:[0,0,0]},{id:1,premium:!1,name:"Black",rgb:[0,0,0]},{id:2,premium:!1,name:"Dark Gray",rgb:[60,60,60]},{id:3,premium:!1,name:"Gray",rgb:[120,120,120]},{id:4,premium:!1,name:"Light Gray",rgb:[210,210,210]},{id:5,premium:!1,name:"White",rgb:[255,255,255]},{id:6,premium:!1,name:"Deep Red",rgb:[96,0,24]},{id:7,premium:!1,name:"Red",rgb:[237,28,36]},{id:8,premium:!1,name:"Orange",rgb:[255,127,39]},{id:9,premium:!1,name:"Gold",rgb:[246,170,9]},{id:10,premium:!1,name:"Yellow",rgb:[249,221,59]},{id:11,premium:!1,name:"Light Yellow",rgb:[255,250,188]},{id:12,premium:!1,name:"Dark Green",rgb:[14,185,104]},{id:13,premium:!1,name:"Green",rgb:[19,230,123]},{id:14,premium:!1,name:"Light Green",rgb:[135,255,94]},{id:15,premium:!1,name:"Dark Teal",rgb:[12,129,110]},{id:16,premium:!1,name:"Teal",rgb:[16,174,166]},{id:17,premium:!1,name:"Light Teal",rgb:[19,225,190]},{id:18,premium:!1,name:"Dark Blue",rgb:[40,80,158]},{id:19,premium:!1,name:"Blue",rgb:[64,147,228]},{id:20,premium:!1,name:"Cyan",rgb:[96,247,242]},{id:21,premium:!1,name:"Indigo",rgb:[107,80,246]},{id:22,premium:!1,name:"Light Indigo",rgb:[153,177,251]},{id:23,premium:!1,name:"Dark Purple",rgb:[120,12,153]},{id:24,premium:!1,name:"Purple",rgb:[170,56,185]},{id:25,premium:!1,name:"Light Purple",rgb:[224,159,249]},{id:26,premium:!1,name:"Dark Pink",rgb:[203,0,122]},{id:27,premium:!1,name:"Pink",rgb:[236,31,128]},{id:28,premium:!1,name:"Light Pink",rgb:[243,141,169]},{id:29,premium:!1,name:"Dark Brown",rgb:[104,70,52]},{id:30,premium:!1,name:"Brown",rgb:[149,104,42]},{id:31,premium:!1,name:"Beige",rgb:[248,178,119]},{id:32,premium:!0,name:"Medium Gray",rgb:[170,170,170]},{id:33,premium:!0,name:"Dark Red",rgb:[165,14,30]},{id:34,premium:!0,name:"Light Red",rgb:[250,128,114]},{id:35,premium:!0,name:"Dark Orange",rgb:[228,92,26]},{id:36,premium:!0,name:"Light Tan",rgb:[214,181,148]},{id:37,premium:!0,name:"Dark Goldenrod",rgb:[156,132,49]},{id:38,premium:!0,name:"Goldenrod",rgb:[197,173,49]},{id:39,premium:!0,name:"Light Goldenrod",rgb:[232,212,95]},{id:40,premium:!0,name:"Dark Olive",rgb:[74,107,58]},{id:41,premium:!0,name:"Olive",rgb:[90,148,74]},{id:42,premium:!0,name:"Light Olive",rgb:[132,197,115]},{id:43,premium:!0,name:"Dark Cyan",rgb:[15,121,159]},{id:44,premium:!0,name:"Light Cyan",rgb:[187,250,242]},{id:45,premium:!0,name:"Light Blue",rgb:[125,199,255]},{id:46,premium:!0,name:"Dark Indigo",rgb:[77,49,184]},{id:47,premium:!0,name:"Dark Slate Blue",rgb:[74,66,132]},{id:48,premium:!0,name:"Slate Blue",rgb:[122,113,196]},{id:49,premium:!0,name:"Light Slate Blue",rgb:[181,174,241]},{id:50,premium:!0,name:"Light Brown",rgb:[219,164,99]},{id:51,premium:!0,name:"Dark Beige",rgb:[209,128,81]},{id:52,premium:!0,name:"Light Beige",rgb:[255,197,165]},{id:53,premium:!0,name:"Dark Peach",rgb:[155,82,73]},{id:54,premium:!0,name:"Peach",rgb:[209,128,120]},{id:55,premium:!0,name:"Light Peach",rgb:[250,182,164]},{id:56,premium:!0,name:"Dark Tan",rgb:[123,99,82]},{id:57,premium:!0,name:"Tan",rgb:[156,132,107]},{id:58,premium:!0,name:"Dark Slate",rgb:[51,57,65]},{id:59,premium:!0,name:"Slate",rgb:[109,117,141]},{id:60,premium:!0,name:"Light Slate",rgb:[179,185,209]},{id:61,premium:!0,name:"Dark Stone",rgb:[109,100,63]},{id:62,premium:!0,name:"Stone",rgb:[148,140,107]},{id:63,premium:!0,name:"Light Stone",rgb:[205,197,158]}],M=class{constructor({displayName:t="My template",p:n=0,$:i="",url:s="",file:o=null,coords:a=null,v:r=null,M:l={},C:c=1e3}={}){e(this,g),this.displayName=t,this.p=n,this.$=i,this.url=s,this.file=o,this.coords=a,this.v=r,this.M=l,this.C=c,this.T={total:0,colors:new Map}}async S(t,e){console.log("Template coordinates:",this.coords);const i=await createImageBitmap(this.file),s=i.width,o=i.height;this.C=t;const a={},r={},l=new OffscreenCanvas(this.C,this.C),c=l.getContext("2d",{willReadFrequently:!0});l.width=s,l.height=o,c.imageSmoothingEnabled=!1,c.drawImage(i,0,0);let h=Date.now();const m=n(this,g,w).call(this,c.getImageData(0,0,s,o),e);console.log(`Calculating total pixels took ${(Date.now()-h)/1e3} seconds`);let d=0;for(const[t,e]of m)0!=t&&(d+=e);this.T={total:d,colors:m},h=Date.now();const b=new OffscreenCanvas(3,3),p=b.getContext("2d");p.clearRect(0,0,3,3),p.fillStyle="white",p.fillRect(1,1,1,1);for(let t=this.coords[3];t<o+this.coords[3];){const e=Math.min(this.C-t%this.C,o-(t-this.coords[3]));console.log(`Math.min(${this.C} - (${t} % ${this.C}), ${o} - (${t-this.coords[3]}))`);for(let n=this.coords[2];n<s+this.coords[2];){console.log(`Pixel X: ${n}\nPixel Y: ${t}`);const o=Math.min(this.C-n%this.C,s-(n-this.coords[2]));console.log(`Math.min(${this.C} - (${n} % ${this.C}), ${s} - (${n-this.coords[2]}))`),console.log(`Draw Size X: ${o}\nDraw Size Y: ${e}`);const h=3*o,m=3*e;l.width=h,l.height=m,console.log(`Draw X: ${o}\nDraw Y: ${e}\nCanvas Width: ${h}\nCanvas Height: ${m}`),c.imageSmoothingEnabled=!1,console.log(`Getting X ${n}-${n+o}\nGetting Y ${t}-${t+e}`),c.clearRect(0,0,h,m),c.drawImage(i,n-this.coords[2],t-this.coords[3],o,e,0,0,3*o,3*e),c.save(),c.globalCompositeOperation="destination-in",c.fillStyle=c.createPattern(b,"repeat"),c.fillRect(0,0,h,m),c.restore();const d=c.getImageData(0,0,h,m);console.log(`Shreaded pixels for ${n}, ${t}`,d);const p=`${(this.coords[0]+Math.floor(n/1e3)).toString().padStart(4,"0")},${(this.coords[1]+Math.floor(t/1e3)).toString().padStart(4,"0")},${(n%1e3).toString().padStart(3,"0")},${(t%1e3).toString().padStart(3,"0")}`;this.M[p]=new Uint32Array(d.data.buffer),a[p]=await createImageBitmap(l);const f=await l.convertToBlob(),g=await f.arrayBuffer(),w=Array.from(new Uint8Array(g));r[p]=u(w),console.log(a),n+=o}t+=e}return console.log(`Parsing template took ${(Date.now()-h)/1e3} seconds`),console.log("Template Tiles: ",a),console.log("Template Tiles Buffers: ",r),console.log("Template Tiles Uint32Array: ",this.M),{k:a,D:r}}L(){let t=[1/0,1/0,1/0,1/0];Object.keys(this.v).sort().forEach((e,n)=>{const[i,s,o,a]=e.split(",").map(Number);(s<t[1]||s==t[1]&&i<t[0])&&(t=[i,s,o,a])}),this.coords=t}};g=new WeakSet,w=function(t,e){const n=new Uint32Array(t.data.buffer),{palette:i,O:s}=e,o=new Map;for(let t=0;t<n.length;t++){const e=n[t];let i=-2;i=e>>>24==0?0:s.get(e)??-2;const a=o.get(i);o.set(i,a?a+1:1)}return console.log(o),o};var C,T,S,k,D=class{constructor(t,n){e(this,y),this.name=t,this.version=n,this.N=null,this.B="bm-i",this.I=null,this.H=null,this.A=[]}P(t){this.N=t}W(){return this.A.length>0&&(this.H=this.A.pop()),this}_(t){t?.appendChild(this.I),this.I=null,this.H=null,this.A=[]}G(t={},e=()=>{}){return e(this,n(this,y,$).call(this,"div",{},t)),this}U(t={},e=()=>{}){return e(this,n(this,y,$).call(this,"p",{},t)),this}F(t={},e=()=>{}){return e(this,n(this,y,$).call(this,"small",{},t)),this}R(t={},e=()=>{}){return e(this,n(this,y,$).call(this,"span",{},t)),this}j(t={},e=()=>{}){return e(this,n(this,y,$).call(this,"details",{},t)),this}Y(t={},e=()=>{}){return e(this,n(this,y,$).call(this,"summary",{},t)),this}V(t={},e=()=>{}){return e(this,n(this,y,$).call(this,"img",{},t)),this}J(t,e={},i=()=>{}){return i(this,n(this,y,$).call(this,"h"+t,{},e)),this}X(t={},e=()=>{}){return e(this,n(this,y,$).call(this,"hr",{},t)),this}q(t={},e=()=>{}){return e(this,n(this,y,$).call(this,"br",{},t)),this}Z(t={},e=()=>{}){return e(this,n(this,y,$).call(this,"form",{},t)),this}K(t={},e=()=>{}){return e(this,n(this,y,$).call(this,"fieldset",{},t)),this}tt(t={},e=()=>{}){return e(this,n(this,y,$).call(this,"legend",{},t)),this}et(t={},e=()=>{}){const i=n(this,y,$).call(this,"label",{textContent:t.textContent??""});delete t.textContent;const s=n(this,y,$).call(this,"input",{type:"checkbox"},t);return i.insertBefore(s,i.firstChild),this.W(),e(this,i,s),this}nt(t={},e=()=>{}){const i=n(this,y,$).call(this,"label",{textContent:t.textContent??"",for:t.id??""});return delete t.textContent,this.W(),e(this,i,n(this,y,$).call(this,"select",{},t)),this}it(t={},e=()=>{}){return e(this,n(this,y,$).call(this,"option",{},t)),this}st(t={},e=()=>{}){return e(this,n(this,y,$).call(this,"ol",{},t)),this}ot(t={},e=()=>{}){return e(this,n(this,y,$).call(this,"ul",{},t)),this}rt(t={},e=()=>{}){return e(this,n(this,y,$).call(this,"menu",{},t)),this}lt(t={},e=()=>{}){return e(this,n(this,y,$).call(this,"li",{},t)),this}ct(t={},e=()=>{}){return e(this,n(this,y,$).call(this,"table",{},t)),this}ht(t={},e=()=>{}){return e(this,n(this,y,$).call(this,"caption",{},t)),this}dt(t={},e=()=>{}){return e(this,n(this,y,$).call(this,"thead",{},t)),this}ut(t={},e=()=>{}){return e(this,n(this,y,$).call(this,"tbody",{},t)),this}bt(t={},e=()=>{}){return e(this,n(this,y,$).call(this,"tfoot",{},t)),this}ft(t={},e=()=>{}){return e(this,n(this,y,$).call(this,"tr",{},t)),this}gt(t={},e=()=>{}){return e(this,n(this,y,$).call(this,"th",{},t)),this}wt(t={},e=()=>{}){return e(this,n(this,y,$).call(this,"td",{},t)),this}yt(t={},e=()=>{}){return e(this,n(this,y,$).call(this,"button",{},t)),this}$t(t={},e=()=>{}){const i=t.title??t.textContent??"Help: No info";delete t.textContent,t.title=`Help: ${i}`;const s={textContent:"?",className:"bm-M",onclick:()=>{this.xt(this.B,i)}};return e(this,n(this,y,$).call(this,"button",s,t)),this}vt(t={},e=()=>{}){return e(this,n(this,y,$).call(this,"input",{},t)),this}Mt(t={},e=()=>{}){const i=t.textContent??"";delete t.textContent;const s=n(this,y,$).call(this,"div"),o=n(this,y,$).call(this,"input",{type:"file",tabindex:"-1","aria-hidden":"true"},t);this.W();const a=n(this,y,$).call(this,"button",{textContent:i});return this.W(),this.W(),a.addEventListener("click",()=>{o.click()}),o.addEventListener("change",()=>{a.style.maxWidth=`${a.offsetWidth}px`,o.files.length>0?a.textContent=o.files[0].name:a.textContent=i}),e(this,s,o,a),this}Ct(t={},e=()=>{}){return e(this,n(this,y,$).call(this,"textarea",{},t)),this}Tt(t={},e=()=>{}){return e(this,n(this,y,$).call(this,"div",{class:"bm-H"},t)),this}St(t=Date.now(),e=500,i={},s=()=>{}){const o="bm-L",a=i?.id||o+"-"+crypto.randomUUID().slice(0,8),r={class:o},l=n(this,y,$).call(this,"time",r,i);return l.id=a,l.dataset.endDate=t,setInterval(()=>{if(!l.isConnected)return;const t=Math.max(l.dataset.endDate-Date.now(),0),e=Math.floor(t/1e3),n=Math.floor(e/3600),i=Math.floor(e%60),s=Math.floor(e%3600/60);l.setAttribute("datetime",`PT${n}H${s}M${i}S`),l.textContent=String(n).padStart(2,"0")+":"+String(s).padStart(2,"0")+":"+String(i).padStart(2,"0")},e),s(this,l),this}xt(t,e,n=!1){const i=document.getElementById(t.replace(/^#/,""));i&&(i instanceof HTMLInputElement?i.value=e:n?i.textContent=e:i.innerHTML=e)}kt(t){if(t.disabled)return;t.disabled=!0,t.style.textDecoration="none";const e=t.closest(".bm-J"),n=t.closest(".bm-H"),i=e.querySelector("h1"),s=e.querySelector(".bm-f");if(e.parentElement.append(e),"expanded"==t.dataset.buttonStatus){s.style.height=s.scrollHeight+"px",e.style.width=e.scrollWidth+"px",s.style.height="0",s.addEventListener("transitionend",function e(){s.style.display="none",t.disabled=!1,t.style.textDecoration="",s.removeEventListener("transitionend",e)});const n=i.cloneNode(!0),o=n.textContent;t.nextElementSibling.appendChild(n),t.textContent="▶",t.dataset.buttonStatus="collapsed",t.ariaLabel=`Unminimize window "${o}"`}else{const i=n.querySelector("h1"),o=i.textContent;i.remove(),s.style.display="",s.style.height="0",e.style.width="",s.style.height=s.scrollHeight+"px",s.addEventListener("transitionend",function e(){s.style.height="",t.disabled=!1,t.style.textDecoration="",s.removeEventListener("transitionend",e)}),t.textContent="▼",t.dataset.buttonStatus="expanded",t.ariaLabel=`Minimize window "${o}"`}}Dt(t,e){const n=document.querySelector(t),i=document.querySelector(e);if(!n||!i)return void this.Lt(`Can not drag! ${n?"":"moveMe"} ${n||i?"":"and "}${i?"":"iMoveThings "}was not found!`);let s,o=!1,a=0,r=null,l=0,c=0,h=0,m=0,d=null;const u=()=>{if(o){const t=Math.abs(l-h),e=Math.abs(c-m);(t>.5||e>.5)&&(l=h,c=m,n.style.transform=`translate(${l}px, ${c}px)`,n.style.left="0px",n.style.top="0px",n.style.right=""),r=requestAnimationFrame(u)}},b=(t,e)=>{o=!0,d=n.getBoundingClientRect(),s=t-d.left,a=e-d.top;const b=window.getComputedStyle(n).transform;if(b&&"none"!==b){const t=new DOMMatrix(b);l=t.m41,c=t.m42}else l=d.left,c=d.top;h=l,m=c,document.body.style.userSelect="none",i.classList.add("bm-C"),document.addEventListener("mousemove",f),document.addEventListener("touchmove",g,{passive:!1}),document.addEventListener("mouseup",p),document.addEventListener("touchend",p),document.addEventListener("touchcancel",p),r&&cancelAnimationFrame(r),u()},p=()=>{o=!1,r&&(cancelAnimationFrame(r),r=null),document.body.style.userSelect="",i.classList.remove("bm-C"),document.removeEventListener("mousemove",f),document.removeEventListener("touchmove",g),document.removeEventListener("mouseup",p),document.removeEventListener("touchend",p),document.removeEventListener("touchcancel",p)},f=t=>{o&&d&&(h=t.clientX-s,m=t.clientY-a)},g=t=>{if(o&&d){const e=t.touches[0];if(!e)return;h=e.clientX-s,m=e.clientY-a,t.preventDefault()}};i.addEventListener("mousedown",function(t){t.preventDefault(),b(t.clientX,t.clientY)}),i.addEventListener("touchstart",function(t){const e=t?.touches?.[0];e&&(b(e.clientX,e.clientY),t.preventDefault())},{passive:!1})}Ot(t){(0,console.info)(`${this.name}: ${t}`),this.xt(this.B,"Status: "+t,!0)}Lt(t){(0,console.error)(`${this.name}: ${t}`),this.xt(this.B,"Error: "+t,!0)}};y=new WeakSet,$=function(t,e={},i={}){const s=document.createElement(t);this.I?(this.H?.appendChild(s),this.A.push(this.H),this.H=s):(this.I=s,this.H=s);for(const[t,i]of Object.entries(e))n(this,y,x).call(this,s,t,i);for(const[t,e]of Object.entries(i))n(this,y,x).call(this,s,t,e);return s},x=function(t,e,n){if("class"==e)t.classList.add(...n.split(/\s+/));else if("for"==e)t.htmlFor=n;else if("tabindex"==e)t.tabIndex=Number(n);else if("readonly"==e)t.readOnly="true"==n||"1"==n;else if("maxlength"==e)t.maxLength=Number(n);else if(e.startsWith("data"))t.dataset[e.slice(5).split("-").map((t,e)=>0==e?t:t[0].toUpperCase()+t.slice(1)).join("")]=n;else if(e.startsWith("aria")){const i=e.slice(5).split("-").map((t,e)=>0==e?t:t[0].toUpperCase()+t.slice(1)).join("");t["aria"+i[0].toUpperCase()+i.slice(1)]=n}else t[e]=n};var L=class extends D{constructor(t,n,i,s=void 0){super(t,n),e(this,C),this.window=null,this.Nt="bm-j",this.Bt=document.body,this.It=JSON.parse(GM_getValue("bmTemplates","{}")),this.scriptVersion=this.It?.scriptVersion,this.schemaVersion=this.It?.schemaVersion,this.Ht=void 0,this.At=i,this.Pt=s}Wt(){if(document.querySelector(`#${this.Nt}`))return void document.querySelector(`#${this.Nt}`).remove();let t="";document.querySelector("#bm-t")||(t=t.concat("z-index: 9001;").trim()),this.window=this.G({id:this.Nt,class:"bm-J",style:t},(t,e)=>{}).Tt().yt({class:"bm-k",textContent:"▼","aria-label":'Minimize window "Template Wizard"',"data-button-status":"expanded"},(t,e)=>{e.onclick=()=>t.kt(e),e.ontouchend=()=>{e.click()}}).W().G().W().yt({class:"bm-k",textContent:"✖","aria-label":'Close window "Template Wizard"'},(t,e)=>{e.onclick=()=>{document.querySelector(`#${this.Nt}`)?.remove()},e.ontouchend=()=>{e.click()}}).W().W().G({class:"bm-f"}).G({class:"bm-B bm-b"}).J(1,{textContent:"Template Wizard"}).W().W().X().W().G({class:"bm-B"}).J(2,{textContent:"Status"}).W().U({id:"bm-l",textContent:"Loading template storage status..."}).W().W().G({class:"bm-B bm-x"}).J(2,{textContent:"Detected templates:"}).W().W().W().W()._(this.Bt),this.Dt(`#${this.Nt}.bm-J`,`#${this.Nt} .bm-H`),n(this,C,T).call(this),n(this,C,S).call(this)}};C=new WeakSet,T=function(){const t=this.schemaVersion.split(/[-\.\+]/),e=this.At.split(/[-\.\+]/);let i="";t[0]==e[0]?t[1]==e[1]?(i='Template storage health: <b style="color:#0f0;">Healthy!</b><br>No futher action required. (Reason: Semantic version matches)',this.Ht="Good"):(i='Template storage health: <b style="color:#ff0;">Poor!</b><br>You can still use your template, but some features may not work. It is recommended that you update Blue Marble\'s template storage. (Reason: MINOR version mismatch)',this.Ht="Poor"):t[0]<e[0]?(i='Template storage health: <b style="color:#f00;">Bad!</b><br>It is guaranteed that some features are broken. You <em>might</em> still be able to use the template. It is HIGHLY recommended that you download all templates and update Blue Marble\'s template storage before continuing. (Reason: MAJOR version mismatch)',this.Ht="Bad"):(i='Template storage health: <b style="color:#f00">Dead!</b><br>Blue Marble can not load the template storage. (Reason: MAJOR version unknown)',this.Ht="Dead");const s=`<hr style="margin:.5ch">If you want to continue using your current templates, then make sure the template storage (schema) is up-to-date.<br>If you don't want to update the template storage, then downgrade Blue Marble to version <b>${r(this.scriptVersion)}</b> to continue using your templates.<br>Alternatively, if you don't care about corrupting the templates listed below, you can fix any issues with the template storage by uploading a new template.`,o=function(){const t=[...document.querySelectorAll("body > div > .hidden")].filter(t=>/version:/i.test(t.textContent));if(t[0]){const e=t[0].textContent?.match(/\d+/);return e?new Date(Number(e[0])):void 0}}();let l=o?a(o):"???";this.xt("#bm-l",`${i}<br>Your templates were created during Blue Marble version <b>${r(this.scriptVersion)}</b> with schema version <b>${r(this.schemaVersion)}</b>.<br>The current Blue Marble version is <b>${r(this.version)}</b> and requires schema version <b>${r(this.At)}</b>.<br>Wplace was last updated on <b>${l}</b>.${"Good"!=this.Ht?s:""}`);const c=new D(this.name,this.version);"Dead"!=this.Ht&&(c.G({class:"bm-B bm-u bm-b",style:"gap: 1.5ch;"}),c.yt({textContent:"Download all templates"},(t,e)=>{e.onclick=()=>{e.disabled=!0,this.Pt.zt().then(()=>{e.disabled=!1})}}).W()),"Poor"!=this.Ht&&"Bad"!=this.Ht||c.yt({textContent:`Update template storage to ${this.At}`},(t,e)=>{e.onclick=()=>{e.disabled=!0,n(this,C,k).call(this,!0)}}).W(),c.W()._(document.querySelector("#bm-l").parentNode)},S=function(){const t=this.It?.templates;if(Object.keys(t).length>0){const e=document.querySelector(`#${this.Nt} .bm-x`),n=new D(this.name,this.version);n.G({id:"bm-o",class:"bm-B"});for(const e in t){const i=e,o=t[e];if(t.hasOwnProperty(e)){const t=i.split(" "),e=Number(t?.[0]),a=d(t?.[1]||"0",this.Pt._t),r=o.name||`Template ${e||""}`,l=o?.coords?.split(",").map(Number),c=o.pixels?.total??void 0,h=void 0,m="number"==typeof e?s(e):"???",u="number"==typeof a?s(a):"???",b="number"==typeof c?s(c):"???";n.G({class:"bm-B bm-u"}).G({class:"bm-u",style:"flex-direction: column; gap: 0;"}).G({class:"bm-1",textContent:h||"🖼️"}).W().F({textContent:`#${m}`}).W().W().G({class:"bm-u bm-0"}).J(3,{textContent:r}).W().R({textContent:`Uploaded by user #${u}`}).W().R({textContent:`Coordinates: ${l.join(", ")}`}).W().R({textContent:`Total Pixels: ${b}`}).W().W().W()}}n.W()._(e)}},k=async function(t){if(t){const t=document.querySelector(`#${this.Nt} .bm-f`);t.innerHTML="",new D(this.name,this.version).G({class:"bm-B"}).G({class:"bm-B bm-b"}).J(1,{textContent:"Template Wizard"}).W().W().X().W().G({class:"bm-B"}).J(2,{textContent:"Status"}).W().U({textContent:"Updating template storage. Please wait..."}).W().W().W()._(t)}GM_deleteValue("bmCoords");const e=this.It?.templates;if(Object.keys(e).length>0)for(const[t,n]of Object.entries(e))if(e.hasOwnProperty(t)){const t=new M({displayName:n.name,v:n.tiles});t.L();const e=await this.Pt.Gt(t);await this.Pt.Ut(e,t.displayName,t.coords)}t&&(console.log("Restarting Template Wizard..."),document.querySelector(`#${this.Nt}`).remove(),new L(this.name,this.version,this.At,this.Pt).Wt())};var O,N,B,I,H=L;O=new WeakSet,N=async function(){GM.setValue("bmTemplates",JSON.stringify(this.Ft))},B=async function(t){console.log("Parsing BlueMarble...");const e=t.templates;console.log(`BlueMarble length: ${Object.keys(e).length}`);const n=t?.schemaVersion,i=n.split(/[-\.\+]/),s=this.schemaVersion.split(/[-\.\+]/),o=t?.scriptVersion;console.log(`BlueMarble Template Schema: ${n}; Script Version: ${o}`),i[0]==s[0]?(i[1]!=s[1]&&new H(this.name,this.version,this.schemaVersion,this).Wt(),this.Rt=await async function({C:t,jt:n,Rt:i}){if(Object.keys(e).length>0)for(const s in e){const o=s,a=e[s];if(console.log(`Template Key: ${o}`),e.hasOwnProperty(s)){const e=o.split(" "),s=Number(e?.[0]),r=e?.[1]||"0",l=a.name||`Template ${s||""}`,c={total:a.pixels?.total,colors:new Map(Object.entries(a.pixels?.colors||{}).map(([t,e])=>[Number(t),e]))},h=a.tiles,m={},d={},u=t*n;for(const t in h)if(console.log(t),h.hasOwnProperty(t)){const e=b(h[t]),n=new Blob([e],{type:"image/png"}),i=await createImageBitmap(n);m[t]=i;const s=new OffscreenCanvas(u,u).getContext("2d");s.drawImage(i,0,0);const o=s.getImageData(0,0,i.width,i.height);d[t]=new Uint32Array(o.data.buffer)}const p=new M({displayName:l,p:s||this.Rt?.length||0,$:r||""});p.T=c,p.v=m,p.M=d,i.push(p),console.log(this.Rt),console.log("^^^ This ^^^")}}return i}({C:this.C,jt:this.jt,Rt:this.Rt})):i[0]<s[0]?new H(this.name,this.version,this.schemaVersion,this).Wt():this.I.Lt(`Template version ${n} is unsupported.\nUse Blue Marble version ${o} or load a new template.`)},I=function({Et:t,Yt:e,Vt:n}){const i=this.jt,s=this.C*i,o=n[0],a=n[1],r=n[2],l=n[3],c=this.Jt,{palette:h,O:m}=this.Xt,d=new Map;for(let n=1;n<l;n+=i)for(let l=1;l<r;l+=i){const h=a+n+-1,u=o+l+0,b=t[h*s+u],p=e[n*r+l],f=p>>>24&255,g=b>>>24&255,w=m.get(p)??-2;if(this.qt.get(w)&&(e[n*r+l]=b),-1==w){const t=536870912;this.qt.get(w)?e[n*r+l]=0:(h/i&1)==(u/i&1)?(e[n*r+l]=t,e[(n-1)*r+(l-1)]=t,e[(n-1)*r+(l+1)]=t,e[(n+1)*r+(l-1)]=t,e[(n+1)*r+(l+1)]=t):(e[n*r+l]=0,e[(n-1)*r+l]=t,e[(n+1)*r+l]=t,e[n*r+(l-1)]=t,e[n*r+(l+1)]=t)}if(-1==w&&b<=c){const t=d.get(w);d.set(w,t?t+1:1);continue}if(f<=c||g<=c)continue;if((m.get(b)??-2)!=w)continue;const y=d.get(w);d.set(w,y?y+1:1)}return console.log("List of template pixels that match the tile:"),console.log(d),{Qt:d,Zt:e}};var A=class{constructor(){this.Kt=Math.ceil(80/1300*window.innerWidth),this.te=v.slice(1)}ee(t){const e=document.createElement("div");for(let t=0;t<this.Kt;t++){const t=document.createElement("confetti-piece");t.style.setProperty("--x",100*Math.random()+"vw"),t.style.setProperty("--delay",2*Math.random()+"s"),t.style.setProperty("--duration",3+3*Math.random()+"s"),t.style.setProperty("--rot",360*Math.random()+"deg"),t.style.setProperty("--size",6+6*Math.random()+"px"),t.style.backgroundColor=`rgb(${this.te[Math.floor(Math.random()*this.te.length)].rgb.join(",")})`,t.onanimationend=()=>{t.parentNode.childElementCount<=1?t.parentNode.remove():t.remove()},e.appendChild(t)}t.appendChild(e)}},P=class extends HTMLElement{};customElements.define("confetti-piece",P);var W,z,_,G,U,F,R,j,E,Y,V=class extends D{constructor(t,e){super(t,e),this.window=null,this.Nt="bm-J-credits",this.Bt=document.body}Wt(){document.querySelector(`#${this.Nt}`)?document.querySelector(`#${this.Nt}`).remove():(this.window=this.G({id:this.Nt,class:"bm-J"},(t,e)=>{}).Tt().yt({class:"bm-k",textContent:"▼","aria-label":'Minimize window "Credits"',"data-button-status":"expanded"},(t,e)=>{e.onclick=()=>t.kt(e),e.ontouchend=()=>{e.click()}}).W().G().W().yt({class:"bm-k",textContent:"✖","aria-label":'Close window "Credits"'},(t,e)=>{e.onclick=()=>{document.querySelector(`#${this.Nt}`)?.remove()},e.ontouchend=()=>{e.click()}}).W().W().G({class:"bm-f"}).G({class:"bm-B bm-b"}).J(1,{textContent:"Credits"}).W().W().X().W().G({class:"bm-B bm-x"}).R({role:"img","aria-label":this.name}).R({innerHTML:"\n██████╗ ██╗     ██╗   ██╗███████╗\n██╔══██╗██║     ██║   ██║██╔════╝\n██████╔╝██║     ██║   ██║█████╗  \n██╔══██╗██║     ██║   ██║██╔══╝  \n██████╔╝███████╗╚██████╔╝███████╗\n╚═════╝ ╚══════╝ ╚═════╝ ╚══════╝\n\n███╗   ███╗ █████╗ ██████╗ ██████╗ ██╗     ███████╗\n████╗ ████║██╔══██╗██╔══██╗██╔══██╗██║     ██╔════╝\n██╔████╔██║███████║██████╔╝██████╔╝██║     █████╗  \n██║╚██╔╝██║██╔══██║██╔══██╗██╔══██╗██║     ██╔══╝  \n██║ ╚═╝ ██║██║  ██║██║  ██║██████╔╝███████╗███████╗\n╚═╝     ╚═╝╚═╝  ╚═╝╚═╝  ╚═╝╚═════╝ ╚══════╝╚══════╝\n",class:"bm-1E","aria-hidden":"true"}).W().W().q().W().X().W().q().W().R({textContent:'"Blue Marble" userscript is made by SwingTheVine.'}).W().q().W().R({innerHTML:'The <a href="https://bluemarble.lol/" target="_blank" rel="noopener noreferrer">Blue Marble Website</a> is made by <a href="https://github.com/crqch" target="_blank" rel="noopener noreferrer">crqch</a>.'}).W().q().W().R({textContent:`The Blue Marble Website used until ${a(new Date(175606932e4))} was made by Camille Daguin.`}).W().q().W().R({textContent:'The favicon "Blue Marble" is owned by NASA. (The image of the Earth is owned by NASA)'}).W().q().W().R({textContent:"Special Thanks:"}).W().ot().lt({textContent:"Espresso, Meqa, and Robot for moderating SwingTheVine's community."}).W().lt({innerHTML:'nof, <a href="https://github.com/TouchedByDarkness" target="_blank" rel="noopener noreferrer">darkness</a> for creating similar userscripts!'}).W().lt({innerHTML:'<a href="https://wondapon.net/" target="_blank" rel="noopener noreferrer">Wonda</a> for the Blue Marble banner image!'}).W().lt({innerHTML:'<a href="https://github.com/BullStein" target="_blank" rel="noopener noreferrer">BullStein</a>, <a href="https://github.com/allanf181" target="_blank" rel="noopener noreferrer">allanf181</a> for being early beta testers!'}).W().lt({innerHTML:'guidu_ and <a href="https://github.com/Nick-machado" target="_blank" rel="noopener noreferrer">Nick-machado</a> for the original "Minimize" Button code!'}).W().lt({innerHTML:'Nomad and <a href="https://www.youtube.com/@gustav_vv" target="_blank" rel="noopener noreferrer">Gustav</a> for the tutorials!'}).W().lt({innerHTML:'<a href="https://github.com/cfpwastaken" target="_blank" rel="noopener noreferrer">cfp</a> for creating the template overlay that Blue Marble was based on!'}).W().lt({innerHTML:'<a href="https://forcenetwork.cloud/" target="_blank" rel="noopener noreferrer">Force Network</a> for hosting the <a href="https://github.com/SwingTheVine/Wplace-TelemetryServer" target="_blank" rel="noopener noreferrer">telemetry server</a>!'}).W().lt({innerHTML:'<a href="https://thebluecorner.net" target="_blank" rel="noopener noreferrer">TheBlueCorner</a> for getting me interested in online pixel canvases!'}).W().W().q().W().R({innerHTML:'<a href="https://ko-fi.com/swingthevine" target="_blank" rel="noopener noreferrer">Donators</a>:'}).W().ot().lt({textContent:"Espresso"}).W().lt({textContent:"BEST FAN"}).W().lt({textContent:"Jack"}).W().lt({textContent:"raiken_au"}).W().lt({textContent:"Jacob"}).W().lt({textContent:"StupidOne"}).W().lt({textContent:"1 Anonymous Supporter"}).W().W().W().W().W()._(this.Bt),this.Dt(`#${this.Nt}.bm-J`,`#${this.Nt} .bm-H`))}},J=class extends D{constructor(t){super(t.name,t.version),e(this,W),this.window=null,this.Nt="bm-m",this.ne="bm-v",this.Bt=document.body,this.Pt=t.N?.Pt,this.ie='<svg viewBox="0 .5 6 3"><path d="M0,2Q3-1 6,2Q3,5 0,2H2A1,1 0 1 0 3,1Q3,2 2,2"/></svg>',this.se='<svg viewBox="0 1 12 6"><mask id="a"><path d="M0,0H12V8L0,2" fill="#fff"/></mask><path d="M0,4Q6-2 12,4Q6,10 0,4H4A2,2 0 1 0 6,2Q6,4 4,4ZM1,2L10,6.5L9.5,7L.5,2.5" mask="url(#a)"/></svg>';const{palette:n,O:i}=this.Pt.Xt;this.palette=n,this.oe=0,this.ae=0,this.re=new Map,this.le=new Map,this.ce=0,this.he=0,this.timeRemaining=0,this.me="",this.sortPrimary="id",this.sortSecondary="ascending",this.showUnused=!1}Wt(){if(document.querySelector(`#${this.Nt}`))return void document.querySelector(`#${this.Nt}`).remove();this.window=this.G({id:this.Nt,class:"bm-J"},(t,e)=>{}).Tt().yt({class:"bm-k",textContent:"▼","aria-label":'Minimize window "Color Filter"',"data-button-status":"expanded"},(t,e)=>{e.onclick=()=>t.kt(e),e.ontouchend=()=>{e.click()}}).W().G().W().G({class:"bm-u"}).yt({class:"bm-k",textContent:"🗗","aria-label":'Switch to windowed mode for "Color Filter"'},(t,e)=>{e.onclick=()=>{document.querySelector(`#${this.Nt}`)?.remove(),this.de()},e.ontouchend=()=>{e.click()}}).W().yt({class:"bm-k",textContent:"✖","aria-label":'Close window "Color Filter"'},(t,e)=>{e.onclick=()=>{document.querySelector(`#${this.Nt}`)?.remove()},e.ontouchend=()=>{e.click()}}).W().W().W().G({class:"bm-f"}).G({class:"bm-B bm-b"}).J(1,{textContent:"Color Filter"}).W().W().X().W().G({class:"bm-B bm-p bm-b",style:"gap: 1.5ch;"}).yt({textContent:"Hide All Colors"},(t,e)=>{e.onclick=()=>n(this,W,G).call(this,!1)}).W().yt({textContent:"Refresh Data"},(t,e)=>{e.onclick=()=>{e.disabled=!0,this.ue(),e.disabled=!1}}).W().yt({textContent:"Show All Colors"},(t,e)=>{e.onclick=()=>n(this,W,G).call(this,!0)}).W().W().G({class:"bm-B bm-x"}).G({class:"bm-B",style:"margin-left: 2.5ch; margin-right: 2.5ch;"}).G({class:"bm-B"}).R({id:"bm-c",innerHTML:"<b>Tiles Loaded:</b> 0 / ???"}).W().q().W().R({id:"bm-7",innerHTML:"<b>Correct Pixels:</b> ???"}).W().q().W().R({id:"bm-d",innerHTML:"<b>Total Pixels:</b> ???"}).W().q().W().R({id:"bm-3",innerHTML:"<b>Complete:</b> ??? (???)"}).W().q().W().R({id:"bm-4",innerHTML:"??? ???"}).W().W().G({class:"bm-B"}).U({innerHTML:`Colors with the icon ${this.ie.replace("<svg",'<svg aria-label="Eye Open"')} will be shown on the canvas. Colors with the icon ${this.se.replace("<svg",'<svg aria-label="Eye Closed"')} will not be shown on the canvas. The "Hide All Colors" and "Show All Colors" buttons only apply to colors that display in the list below. The amount of correct pixels is dependent on how many tiles of the template you have loaded since you last opened Wplace.live. If all tiles have been loaded, then the "correct pixel" count is accurate.`}).W().W().X().W().Z({class:"bm-B"}).K().tt({textContent:"Sort Options:",style:"font-weight: 700;"}).W().G({class:"bm-B"}).nt({id:"bm-6",name:"sortPrimary",textContent:"I want to view "}).it({value:"id",textContent:"color IDs"}).W().it({value:"name",textContent:"color names"}).W().it({value:"premium",textContent:"premium colors"}).W().it({value:"percent",textContent:"percentage"}).W().it({value:"correct",textContent:"correct pixels"}).W().it({value:"incorrect",textContent:"incorrect pixels"}).W().it({value:"total",textContent:"total pixels"}).W().W().nt({id:"bm-2",name:"sortSecondary",textContent:" in "}).it({value:"ascending",textContent:"ascending"}).W().it({value:"descending",textContent:"descending"}).W().W().R({textContent:" order."}).W().W().G({class:"bm-B"}).et({id:"bm-8",name:"showUnused",textContent:"Show unused colors"}).W().W().W().G({class:"bm-B"}).yt({textContent:"Sort Colors",type:"submit"},(t,e)=>{e.onclick=t=>{t.preventDefault();const e=new FormData(document.querySelector(`#${this.Nt} form`)),i={};for(const[t,n]of e)i[t]=n;console.log(`Primary: ${i.sortPrimary}; Secondary: ${i.sortSecondary}; Unused: ${"on"==i.showUnused}`),n(this,W,_).call(this,i.sortPrimary,i.sortSecondary,"on"==i.showUnused)}}).W().W().W().W().W().W().W()._(this.Bt),this.Dt(`#${this.Nt}.bm-J`,`#${this.Nt} .bm-H`);const t=document.querySelector(`#${this.Nt} .bm-B.bm-x`);n(this,W,z).call(this,t),n(this,W,_).call(this,this.sortPrimary,this.sortSecondary,this.showUnused),this.xt("#bm-c",`<b>Tiles Loaded:</b> ${s(this.oe)} / ${s(this.ae)}`),this.xt("#bm-7",`<b>Correct Pixels:</b> ${s(this.ce)}`),this.xt("#bm-d",`<b>Total Pixels:</b> ${s(this.he)}`),this.xt("#bm-3",`<b>Remaining:</b> ${s((this.he||0)-(this.ce||0))} (${o(((this.he||0)-(this.ce||0))/(this.he||1))})`),this.xt("#bm-4",`<b>Completed at:</b> <time datetime="${this.timeRemaining.toISOString().replace(/\.\d{3}Z$/,"Z")}">${this.me}</time>`)}de(){if(document.querySelector(`#${this.Nt}`))return void document.querySelector(`#${this.Nt}`).remove();this.window=this.G({id:this.Nt,class:"bm-J bm-Jed"}).Tt().yt({class:"bm-k",textContent:"▼","aria-label":'Minimize window "Color Filter"',"data-button-status":"expanded"},(t,e)=>{e.onclick=()=>t.kt(e),e.ontouchend=()=>{e.click()}}).W().G().W().G({class:"bm-u"}).yt({class:"bm-k",textContent:"🗖","aria-label":'Switch to fullscreen mode for "Color Filter"'},(t,e)=>{e.onclick=()=>{document.querySelector(`#${this.Nt}`)?.remove(),this.Wt()},e.ontouchend=()=>{e.click()}}).W().yt({class:"bm-k",textContent:"✖","aria-label":'Close window "Color Filter"'},(t,e)=>{e.onclick=()=>{document.querySelector(`#${this.Nt}`)?.remove()},e.ontouchend=()=>{e.click()}}).W().W().W().G({class:"bm-f"}).G({class:"bm-B bm-b"}).J(1,{textContent:"Color Filter"}).W().W().X().W().G({class:"bm-B bm-p bm-b",style:"gap: 1.5ch;"}).yt({textContent:"None"},(t,e)=>{e.onclick=()=>n(this,W,G).call(this,!1)}).W().yt({textContent:"Refresh"},(t,e)=>{e.onclick=()=>{e.disabled=!0,this.ue(),e.disabled=!1}}).W().yt({textContent:"All"},(t,e)=>{e.onclick=()=>n(this,W,G).call(this,!0)}).W().W().G({class:"bm-B bm-x"}).W().W().W()._(this.Bt),this.Dt(`#${this.Nt}.bm-J`,`#${this.Nt} .bm-H`);const t=document.querySelector(`#${this.Nt} .bm-B.bm-x`);n(this,W,z).call(this,t),n(this,W,_).call(this,this.sortPrimary,this.sortSecondary,this.showUnused)}ue(){n(this,W,U).call(this);const t=document.querySelector(`#${this.ne}`),e={};for(const t of this.palette){const n=this.re.get(t.id)??0,i=s(n);let a=0,r="0",l=o(1);0!=n&&(a=this.le.get(t.id)??"???","number"!=typeof a&&this.oe==this.ae&&t.id&&(a=0),r="string"==typeof a?a:s(a),l=isNaN(a/n)?"???":o(a/n));const c=parseInt(n)-parseInt(a);e[t.id]={be:n,pe:i,fe:a,ge:r,we:l,ye:c}}if(!t)return e;const i=Array.from(t.children);for(const t of i){const n=parseInt(t.dataset.id),{fe:i,ge:s,we:o,be:a,pe:r,ye:l}=e[n];t.dataset.correct=Number.isNaN(parseInt(i))?"0":i,t.dataset.total=a,t.dataset.percent="%"==o.slice(-1)?o.slice(0,-1):"0",t.dataset.incorrect=l||0;const c=document.querySelector(`#${this.Nt} .bm-q[data-id="${n}"] .bm-q-pxl-cnt`);c&&(c.textContent=`${s} / ${r}`);const h=document.querySelector(`#${this.Nt} .bm-q[data-id="${n}"] .bm-q-pxl-desc`);h&&(h.textContent=`${"number"!=typeof l||isNaN(l)?"???":l} incorrect pixels. Completed: ${o}`)}n(this,W,_).call(this,this.sortPrimary,this.sortSecondary,this.showUnused)}};W=new WeakSet,z=function(t){const e=t.closest(`#${this.Nt}`)?.classList.contains("bm-Jed");console.log(`Is Windowed Mode: ${e}`);const n=new D(this.name,this.version);n.G({id:this.ne});const i=this.ue();for(const t of this.palette){const s="#"+f(t.rgb).toUpperCase(),o=p(t.rgb);let a=1.05/(o+.05)>(o+.05)/.05?"white":"black";t.id||(a="transparent");const r="white"==a?"bm-9":"bm-a",{fe:l,ge:c,we:h,be:m,pe:d,ye:u}=i[t.id],b=!!this.Pt.qt.get(t.id);if(e){const e=`background-size: auto 100%; background-repeat: repeat-x; background-image: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 100'><path d='M50,5L79,91L2,39L98,39L21,91' fill='${a}' fill-opacity='.1'/></svg>");`;n.G({class:"bm-B bm-q bm-p","data-id":t.id,"data-name":t.name,"data-premium":+t.premium,"data-correct":Number.isNaN(parseInt(l))?"0":l,"data-total":m,"data-percent":"%"==h.slice(-1)?h.slice(0,-1):"0","data-incorrect":u||0}).G({class:"bm-5",style:`background-color: rgb(${t.rgb?.map(t=>Number(t)||0).join(",")});${t.premium?e:""}`}).yt({class:"bm-r "+r,"data-state":b?"hidden":"shown","aria-label":b?`Show the color ${t.name||""} on templates.`:`Hide the color ${t.name||""} on templates.`,innerHTML:b?this.se.replace("<svg",`<svg fill="${a}"`):this.ie.replace("<svg",`<svg fill="${a}"`)},(e,n)=>{n.onclick=()=>{n.style.textDecoration="none",n.disabled=!0,"shown"==n.dataset.state?(n.innerHTML=this.se.replace("<svg",`<svg fill="${a}"`),n.dataset.state="hidden",n.ariaLabel=`Show the color ${t.name||""} on templates.`,this.Pt.qt.set(t.id,!0)):(n.innerHTML=this.ie.replace("<svg",`<svg fill="${a}"`),n.dataset.state="shown",n.ariaLabel=`Hide the color ${t.name||""} on templates.`,this.Pt.qt.delete(t.id)),n.disabled=!1,n.style.textDecoration=""},t.id||(n.disabled=!0)}).W().F({textContent:`#${t.id.toString().padStart(2,0)}`,style:`color: ${-1==t.id||0==t.id?"white":a}`}).W().J(2,{textContent:t.name,style:`color: ${-1==t.id||0==t.id?"white":a}`}).W().F({class:"bm-q-pxl-cnt",textContent:`${c} / ${d}`,style:`color: ${-1==t.id||0==t.id?"white":a}; flex: 1 1 auto; text-align: right;`}).W().W().W()}else n.G({class:"bm-B bm-q bm-p","data-id":t.id,"data-name":t.name,"data-premium":+t.premium,"data-correct":Number.isNaN(parseInt(l))?"0":l,"data-total":m,"data-percent":"%"==h.slice(-1)?h.slice(0,-1):"0","data-incorrect":u||0}).G({class:"bm-u",style:"flex-direction: column;"}).G({class:"bm-5",style:`background-color: rgb(${t.rgb?.map(t=>Number(t)||0).join(",")});`}).yt({class:"bm-r "+r,"data-state":b?"hidden":"shown","aria-label":b?`Show the color ${t.name||""} on templates.`:`Hide the color ${t.name||""} on templates.`,innerHTML:b?this.se.replace("<svg",`<svg fill="${a}"`):this.ie.replace("<svg",`<svg fill="${a}"`)},(e,n)=>{n.onclick=()=>{n.style.textDecoration="none",n.disabled=!0,"shown"==n.dataset.state?(n.innerHTML=this.se.replace("<svg",`<svg fill="${a}"`),n.dataset.state="hidden",n.ariaLabel=`Show the color ${t.name||""} on templates.`,this.Pt.qt.set(t.id,!0)):(n.innerHTML=this.ie.replace("<svg",`<svg fill="${a}"`),n.dataset.state="shown",n.ariaLabel=`Hide the color ${t.name||""} on templates.`,this.Pt.qt.delete(t.id)),n.disabled=!1,n.style.textDecoration=""},t.id||(n.disabled=!0)}).W().W().F({textContent:-2==t.id?"???????":s}).W().W().G({class:"bm-p"}).J(2,{textContent:(t.premium?"★ ":"")+t.name}).W().G({class:"bm-p",style:"gap: 1.5ch;"}).F({textContent:`#${t.id.toString().padStart(2,0)}`}).W().F({class:"bm-q-pxl-cnt",textContent:`${c} / ${d}`}).W().W().U({class:"bm-q-pxl-desc",textContent:`${"number"!=typeof u||isNaN(u)?"???":u} incorrect pixels. Completed: ${h}`}).W().W().W()}n._(t)},_=function(t,e,n){this.sortPrimary=t,this.sortSecondary=e,this.showUnused=n;const i=document.querySelector(`#${this.ne}`),s=Array.from(i.children);s.sort((i,s)=>{const o=i.getAttribute("data-"+t),a=s.getAttribute("data-"+t),r=parseFloat(o),l=parseFloat(a),c=!isNaN(r),h=!isNaN(l);if(n?i.classList.remove("bm-y"):Number(i.getAttribute("data-total"))||i.classList.add("bm-y"),c&&h)return"ascending"===e?r-l:l-r;{const t=o.toLowerCase(),n=a.toLowerCase();return t<n?"ascending"===e?-1:1:t>n?"ascending"===e?1:-1:0}}),s.forEach(t=>i.appendChild(t))},G=function(t){const e=document.querySelector(`#${this.ne}`),n=Array.from(e.children);for(const e of n){if(e.classList?.contains("bm-y"))continue;const n=e.querySelector(".bm-5 button");("hidden"!=n.dataset.state||t)&&("shown"==n.dataset.state&&t||n.click())}},U=function(){this.he=0,this.ce=0,this.le=new Map,this.re=new Map;for(const t of this.Pt.Rt){const e=t.T?.total??0;this.he+=e??0;const n=t.T?.colors??new Map;for(const[t,e]of n){const n=Number(e)||0,i=this.re.get(t)??0;this.re.set(t,i+n)}const i=t.T?.correct??{};this.oe+=Object.keys(i).length,this.ae+=Object.keys(t.v).length;for(const t of Object.values(i))for(const[e,n]of t){const t=Number(n)||0;this.ce+=t;const i=this.le.get(e)??0;this.le.set(e,i+t)}}console.log(`Tiles loaded: ${this.oe} / ${this.ae}`),this.ce>=this.he&&this.he&&this.oe==this.ae&&(new A).ee(document.querySelector(`#${this.Nt}`)),this.timeRemaining=new Date(30*(this.he-this.ce)*1e3+Date.now()),this.me=a(this.timeRemaining)},F=new WeakSet,R=function(){new J(this).Wt()},j=async function(t,e,n){n.preventDefault();const i=await async function(t){let e="";return t&&(e=t.clipboardData.getData("text/plain")),0!=e.length||(await navigator.clipboard.readText().then(t=>{e=t}).catch(t=>{l("Failed to retrieve clipboard data using navigator! Using fallback methods...")}),0!=e.length||(e=window.clipboardData?.getData("Text"))),e}(n),s=i.split(/[^a-zA-Z0-9]+/).filter(t=>t).map(Number).filter(t=>!isNaN(t));2==s.length&&"bm-D"==e.id?(t.xt("bm-D",s?.[0]||""),t.xt("bm-E",s?.[1]||"")):1==s.length?t.xt(e.id,s?.[0]||""):(t.xt("bm-F",s?.[0]||""),t.xt("bm-G",s?.[1]||""),t.xt("bm-D",s?.[2]||""),t.xt("bm-E",s?.[3]||""))},E=new WeakSet,Y=function(t){const e=JSON.parse(GM_getValue("bmUserSettings","{}"));e.telemetry=t,GM.setValue("bmUserSettings",JSON.stringify(e))};var X=GM_info.script.name.toString(),q=GM_info.script.version.toString();!function(t){const e=document.createElement("script");e.setAttribute("bm-N",X),e.setAttribute("bm-K","color: cornflowerblue;"),e.textContent=`(${t})();`,document.documentElement?.appendChild(e),e.remove()}(()=>{const t=document.currentScript,e=t?.getAttribute("bm-N")||"Blue Marble",n=t?.getAttribute("bm-K")||"",i=new Map;window.addEventListener("message",t=>{const{source:s,endpoint:o,blobID:a,blobData:r,blink:l}=t.data,c=Date.now()-l;if(console.groupCollapsed(`%c${e}%c: ${i.size} Recieved IMAGE message about blob "${a}"`,n,""),console.log(`Blob fetch took %c${String(Math.floor(c/6e4)).padStart(2,"0")}:${String(Math.floor(c/1e3)%60).padStart(2,"0")}.${String(c%1e3).padStart(3,"0")}%c MM:SS.mmm`,n,""),console.log(i),console.groupEnd(),"blue-marble"==s&&a&&r&&!o){const t=i.get(a);"function"==typeof t?t(r):h(`%c${e}%c: Attempted to retrieve a blob (%s) from queue, but the blobID was not a function! Skipping...`,n,"",a),i.delete(a)}});const s=window.fetch;window.fetch=async function(...t){const o=await s.apply(this,t),a=o.clone(),r=(t[0]instanceof Request?t[0]?.url:t[0])||"ignore",l=a.headers.get("content-type")||"";if(l.includes("application/json"))console.log(`%c${e}%c: Sending JSON message about endpoint "${r}"`,n,""),a.json().then(t=>{window.postMessage({source:"blue-marble",endpoint:r,jsonData:t},"*")}).catch(t=>{console.error(`%c${e}%c: Failed to parse JSON: `,n,"",t)});else if(l.includes("image/")&&!r.includes("openfreemap")&&!r.includes("maps")){const t=Date.now(),s=await a.blob();return console.log(`%c${e}%c: ${i.size} Sending IMAGE message about endpoint "${r}"`,n,""),new Promise(o=>{const l=crypto.randomUUID();i.set(l,t=>{o(new Response(t,{headers:a.headers,status:a.status,statusText:a.statusText})),console.log(`%c${e}%c: ${i.size} Processed blob "${l}"`,n,"")}),window.postMessage({source:"blue-marble",endpoint:r,blobID:l,blobData:s,blink:t})}).catch(s=>{const o=Date.now();console.error(`%c${e}%c: Failed to Promise blob!`,n,""),console.groupCollapsed(`%c${e}%c: Details of failed blob Promise:`,n,""),console.log(`Endpoint: ${r}\nThere are ${i.size} blobs processing...\nBlink: ${t.toLocaleString()}\nTime Since Blink: ${String(Math.floor(o/6e4)).padStart(2,"0")}:${String(Math.floor(o/1e3)%60).padStart(2,"0")}.${String(o%1e3).padStart(3,"0")} MM:SS.mmm`),console.error("Exception stack:",s),console.groupEnd()})}return o}});var Q=`div:has(>confetti-piece){position:absolute;inset:0;overflow:hidden;pointer-events:none}confetti-piece{position:absolute;top:-10px;width:var(--size);height:var(--size);background:currentColor;transform:translate3d(var(--x),-10vh,0) rotate(var(--rot));animation:fall var(--duration) linear var(--delay);will-change:transform;pointer-events:none}@keyframes fall{to{transform:translate3d(var(--x),110vh,0) rotate(calc(var(--rot) + 720deg))}}.bm-screenreader{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border:0}.bm-J{position:fixed;background-color:#153063e6;color:#fff;padding:10px;border-radius:8px;z-index:9000;transition:all .3s ease,transform 0s;top:75px;left:60px;width:auto;max-height:fit-content;max-width:calc(100% - 135px);font-family:Roboto Mono,Courier New,Monaco,DejaVu Sans Mono,monospace,Arial;letter-spacing:.05em}.bm-J.bm-Jed{max-width:300px}.bm-H{display:grid;grid-template-columns:auto 1fr auto;align-items:center;gap:.5ch;background:url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="5" height="5"><circle cx="3" cy="3" r="1.5" fill="CornflowerBlue"/></svg>') repeat;cursor:grab;width:100%;height:fit-content}.bm-H.bm-C{cursor:grabbing}.bm-J:has(.bm-H.bm-C){pointer-events:none;user-select:none;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none}.bm-H.bm-C{pointer-events:auto}.bm-I{display:inline-block;height:2.5em;margin-right:1ch;vertical-align:middle}.bm-J h1{display:inline-block;font-size:x-large;font-weight:700;vertical-align:middle}.bm-H h1{font-size:1.2em;user-select:none;overflow:hidden;white-space:nowrap;text-overflow:ellipsis;text-shadow:3px 0px rgba(21,48,99,.5),-3px 0px rgba(21,48,99,.5),0px 3px rgba(21,48,99,.5),0px -3px rgba(21,48,99,.5),3px 3px rgba(21,48,99,.5),-3px 3px rgba(21,48,99,.5),3px -3px rgba(21,48,99,.5),-3px -3px rgba(21,48,99,.5)}.bm-H div:has(h1){display:contents}.bm-J h2{display:inline-block;font-size:larger;font-weight:700;vertical-align:middle}.bm-J h3{display:inline-block;font-size:large;font-weight:700}.bm-B.bm-b{width:fit-content;margin-left:auto;margin-right:auto}.bm-B{margin:.5em 0}.bm-J button{background-color:#144eb9;border-radius:1em;padding:0 .75ch}.bm-J button:hover,.bm-J button:focus-visible{background-color:#1061e5}.bm-J button:active,.bm-J button:disabled{background-color:#2e97ff}.bm-J button:disabled{text-decoration:line-through;cursor:not-allowed}.bm-k{border:white 1px solid;height:1.5em;width:1.5em;margin-top:2px;text-align:center;line-height:1em;padding:0!important}.bm-z{vertical-align:middle}.bm-z svg{width:50%;margin:0 auto;fill:#111}.bm-J button.bm-r{background-color:unset}.bm-r.bm-9:hover,.bm-r.bm-9:focus{background-color:#ffffff2b}.bm-r.bm-9:active{background-color:#ffffff38}.bm-r.bm-a:hover,.bm-r.bm-a:focus{background-color:#0000002b}.bm-r.bm-a:active{background-color:#00000038}input[type=number].bm-s{appearance:auto;-moz-appearance:textfield;width:5.5ch;margin-left:1ch;background-color:#0003;padding:0 .5ch;font-size:small}input[type=number].bm-s::-webkit-outer-spin-button,input[type=number].bm-s::-webkit-inner-spin-button{-webkit-appearance:none;margin:0}div:has(>.bm-A)>button{width:100%;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.bm-A,input[type=file]{display:none!important;visibility:hidden!important;position:absolute!important;left:-9999px!important;top:-9999px!important;width:0!important;height:0!important;opacity:0!important;z-index:-9999!important;pointer-events:none!important}.bm-J select{color:#fff;background-color:#144eb9;border-radius:1em;padding:0 .5ch}.bm-J label:has(input[type=checkbox]){display:flex;width:fit-content;gap:1ch}.bm-J input[type=checkbox]{width:1em}.bm-f{overflow:hidden;transition:height .3s cubic-bezier(.4,0,.2,1)}.bm-J textarea{font-size:small;background-color:#0003;padding:0 .5ch;height:5.25em;width:100%}.bm-J a:not(:has(*)){text-decoration:underline}.bm-J small{font-size:x-small;color:#d3d3d3}.bm-J ul li{list-style:disc;margin-left:5ch}.bm-J .bm-B.bm-x{max-height:calc(80vh - 150px);overflow:auto}.bm-p{display:flex;align-content:center;justify-content:space-between;align-items:center;gap:.5ch}.bm-u{display:flex;align-content:center;justify-content:center;align-items:center;gap:.5ch}.bm-1E{white-space:pre;letter-spacing:0;line-height:1!important;font-size:1.6em;font-family:monospace}.bm-B:not(#bm-t .bm-B){margin:.25em 0}.bm-Jed h1:not(#bm-t h1){font-size:1em}#bm-m p svg{display:inline;height:1em;fill:#fff}#bm-v{display:flex;flex-direction:row;flex-wrap:wrap;justify-content:center;gap:1em 3ch}.bm-q{width:fit-content;max-width:35ch;background-color:#153063e6;border-radius:1em;padding:.5em;gap:1ch;transition:background-color .3s ease}.bm-q:hover,.bm-q:focus-within{background-color:#112855e6}.bm-5{display:block;border:thick double darkslategray;width:fit-content;height:fit-content;padding:1ch}.bm-q[data-id="-2"] .bm-5{background:conic-gradient(#a00,#aa0 16.6%,#0a0,#0aa 50%,#00a 66.6%,#a0a,#a00)}.bm-q[data-id="-1"] .bm-5{background:url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewbox="0 0 8 8" width="1em" height="1em"><path d="M0,0V8H16V16H8V0" fill="rgba(0,0,0,0.5)"/></svg>') repeat;background-color:transparent!important}.bm-q[data-id="-1"] .bm-5 svg{fill:#fff!important}.bm-q[data-id="0"] .bm-5{background-color:transparent!important}#bm-m .bm-5 button{padding:.75em .5ch}.bm-5 svg{width:4ch}.bm-q>.bm-p{flex-direction:column;align-items:flex-start;gap:0}.bm-q small{font-size:.75em}#bm-m .bm-q.bm-y{display:none}.bm-Jed #bm-v{flex-direction:column;gap:.25em}.bm-Jed .bm-q{width:auto;margin:0;padding:0}.bm-Jed .bm-5{display:flex;width:100%;gap:.5ch;align-items:center;padding:.1em .5ch;border:none;border-radius:1em}#bm-m.bm-Jed .bm-5 button{padding:.5em .25ch}.bm-Jed .bm-5 svg{width:3ch}.bm-Jed .bm-q h2{font-size:.75em}#bm-o{display:flex;flex-direction:column;justify-content:flex-start;align-items:flex-start}#bm-o>.bm-B{width:100%;justify-content:flex-start;background-color:#153063e6;border-radius:1em;padding:.5em;transition:background-color .3s ease}#bm-o>.bm-B:hover,#bm-o>.bm-B:focus-within{background-color:#112855e6}#bm-o .bm-1{height:100%;font-size:xxx-large}#bm-o .bm-0{flex-direction:column;align-items:flex-start;gap:0}`;GM_addStyle(Q);var Z,K="@font-face{font-family:'Roboto Mono';font-style:normal;font-weight:400;src:url(data:font/woff2;base64, )format('woff2');}";K.indexOf("@font-face")+1?(console.log("Loading Roboto Mono as a file..."),GM_addStyle(K)):((Z=document.createElement("link")).href="https://fonts.googleapis.com/css2?family=Roboto+Mono:ital,wght@0,100..700;1,100..700&display=swap",Z.rel="preload",Z.as="style",Z.onload=function(){this.onload=null,this.rel="stylesheet"},document.head?.appendChild(Z)),new class{constructor(){this.$e=null,this.xe=null,this.ve="#bm-g"}Me(t){return this.xe=t,this.$e=new MutationObserver(t=>{for(const e of t)for(const t of e.addedNodes)t instanceof HTMLElement&&t.matches?.(this.ve)}),this}Ce(){return this.$e}observe(t,e=!1,n=!1){t.observe(this.xe,{childList:e,subtree:n})}};var tt=new class extends D{constructor(t,n){super(t,n),e(this,F),this.window=null,this.Nt="bm-t",this.Bt=document.body}Wt(){document.querySelector(`#${this.Nt}`)?this.Lt("Main window already exists!"):(this.window=this.G({id:this.Nt,class:"bm-J bm-Jed",style:"top: 10px; left: unset; right: 75px;"},(t,e)=>{}).Tt().yt({class:"bm-k",textContent:"▼","aria-label":'Minimize window "Blue Marble"',"data-button-status":"expanded"},(t,e)=>{e.onclick=()=>t.kt(e),e.ontouchend=()=>{e.click()}}).W().G().W().W().G({class:"bm-f"}).G({class:"bm-B"}).V({class:"bm-I",src:"data:image/png;base64, "},(t,e)=>{const n=new Date;204==Math.floor((n.getTime()-new Date(n.getFullYear(),0,1))/864e5)+1&&(e.parentNode.style.position="relative",e.parentNode.innerHTML=e.parentNode.innerHTML+'<svg viewBox="0 0 9 7" width="2em" height="2em" style="position: absolute; top: -.75em; left: 3.25ch;"><path d="M0,3L9,0L2,7" fill="#0af"/><path d="M0,3A.4,.4 0 1 1 1,5" fill="#a00"/><path d="M1.5,6A1,1 0 0 1 3,6L2,7" fill="#a0f"/><path d="M4,5A.6,.6 0 1 1 5,4" fill="#0a0"/><path d="M6,3A.8,.8 0 1 1 7,2" fill="#fa0"/><path d="M4.5,1.5A1,1 0 0 1 3,2" fill="#aa0"/></svg>',e.onload=()=>{(new A).ee(document.querySelector(`#${this.Nt}`))})}).W().J(1,{textContent:this.name}).W().W().X().W().G({class:"bm-B"}).R({id:"bm-n",textContent:"Droplets:"}).W().q().W().R({id:"bm-h",textContent:"Next level in..."}).W().q().W().R({textContent:"Charges: "}).St(Date.now(),1e3,{style:"font-weight: 700;"},(t,e)=>{t.N.Te=e.id}).W().W().W().X().W().G({class:"bm-B"}).G({class:"bm-B"}).yt({class:"bm-k bm-z",style:"margin-top: 0;",innerHTML:'<svg viewBox="0 0 4 6"><path d="M.5,3.4A2,2 0 1 1 3.5,3.4L2,6"/><circle cx="2" cy="2" r=".7" fill="#fff"/></svg>'},(t,e)=>{e.onclick=()=>{const e=t.N?.Se;e?.[0]?(t.xt("bm-F",e?.[0]||""),t.xt("bm-G",e?.[1]||""),t.xt("bm-D",e?.[2]||""),t.xt("bm-E",e?.[3]||"")):t.Lt("Coordinates are malformed! Did you try clicking on the canvas first?")}}).W().vt({type:"number",id:"bm-F",class:"bm-s",placeholder:"Tl X",min:0,max:2047,step:1,required:!0},(t,e)=>{e.addEventListener("paste",i=>n(this,F,j).call(this,t,e,i))}).W().vt({type:"number",id:"bm-G",class:"bm-s",placeholder:"Tl Y",min:0,max:2047,step:1,required:!0},(t,e)=>{e.addEventListener("paste",i=>n(this,F,j).call(this,t,e,i))}).W().vt({type:"number",id:"bm-D",class:"bm-s",placeholder:"Px X",min:0,max:2047,step:1,required:!0},(t,e)=>{e.addEventListener("paste",i=>n(this,F,j).call(this,t,e,i))}).W().vt({type:"number",id:"bm-E",class:"bm-s",placeholder:"Px Y",min:0,max:2047,step:1,required:!0},(t,e)=>{e.addEventListener("paste",i=>n(this,F,j).call(this,t,e,i))}).W().W().G({class:"bm-B"}).Mt({class:"bm-A",textContent:"Upload Template",accept:"image/png, image/jpeg, image/webp, image/bmp, image/gif"}).W().W().G({class:"bm-B bm-p"}).yt({textContent:"Disable","data-button-status":"shown"},(t,e)=>{e.onclick=()=>{e.disabled=!0,"shown"==e.dataset.buttonStatus?(t.N?.Pt?.ke(!1),e.dataset.buttonStatus="hidden",e.textContent="Enable",t.Ot("Disabled templates!")):(t.N?.Pt?.ke(!0),e.dataset.buttonStatus="shown",e.textContent="Disable",t.Ot("Enabled templates!")),e.disabled=!1}}).W().yt({textContent:"Create"},(t,e)=>{e.onclick=()=>{const e=document.querySelector(`#${this.Nt} .bm-A`),n=document.querySelector("#bm-F");if(!n.checkValidity())return n.reportValidity(),void t.Lt("Coordinates are malformed! Did you try clicking on the canvas first?");const i=document.querySelector("#bm-G");if(!i.checkValidity())return i.reportValidity(),void t.Lt("Coordinates are malformed! Did you try clicking on the canvas first?");const s=document.querySelector("#bm-D");if(!s.checkValidity())return s.reportValidity(),void t.Lt("Coordinates are malformed! Did you try clicking on the canvas first?");const o=document.querySelector("#bm-E");if(!o.checkValidity())return o.reportValidity(),void t.Lt("Coordinates are malformed! Did you try clicking on the canvas first?");e?.files[0]?(t?.N?.Pt.Ut(e.files[0],e.files[0]?.name.replace(/\.[^/.]+$/,""),[Number(n.value),Number(i.value),Number(s.value),Number(o.value)]),t.Ot("Drew to canvas!")):t.Lt("No file selected!")}}).W().yt({textContent:"Filter"},(t,e)=>{e.onclick=()=>n(this,F,R).call(this)}).W().W().G({class:"bm-B"}).Ct({id:this.B,placeholder:`Status: Sleeping...\nVersion: ${this.version}`,readOnly:!0}).W().W().G({class:"bm-B bm-p",style:"margin-bottom: 0; flex-direction: column;"}).G({class:"bm-p"}).yt({class:"bm-k",innerHTML:"🧙",title:"Template Wizard"},(t,e)=>{e.onclick=()=>{const e=t.N?.Pt;new H(this.name,this.version,e?.schemaVersion,e).Wt()}}).W().yt({class:"bm-k",innerHTML:"🎨",title:"Template Color Converter"},(t,e)=>{e.onclick=()=>{window.open("https://pepoafonso.github.io/color_converter_wplace/","_blank","noopener noreferrer")}}).W().yt({class:"bm-k",innerHTML:"🌐",title:"Official Blue Marble Website"},(t,e)=>{e.onclick=()=>{window.open("https://bluemarble.lol/","_blank","noopener noreferrer")}}).W().yt({class:"bm-k",title:"Donate to SwingTheVine",innerHTML:'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512" fill="#fff" style="width:80%; margin:auto;"><path d="M249.8 75c89.8 0 113 1.1 146.3 4.4 78.1 7.8 123.6 56 123.6 125.2l0 8.9c0 64.3-47.1 116.9-110.8 122.4-5 16.6-12.8 33.2-23.3 49.9-24.4 37.7-73.1 85.3-162.9 85.3l-17.7 0c-73.1 0-129.7-31.6-163.5-89.2-29.9-50.4-33.8-106.4-33.8-181.2 0-73.7 44.4-113.6 96.4-120.2 39.3-5 88.1-5.5 145.7-5.5zm0 41.6c-60.4 0-103.6 .5-136.3 5.5-46 6.7-64.3 32.7-64.3 79.2l.2 25.7c1.2 57.3 7.1 97.1 27.5 134.5 26.6 49.3 74.8 68.2 129.7 68.2l17.2 0c72 0 107-34.9 126.3-65.4 9.4-15.5 17.7-32.7 22.2-54.3l3.3-13.8 19.9 0c44.3 0 82.6-36 82.6-82l0-8.3c0-51.5-32.2-78.7-88.1-85.3-31.6-2.8-50.4-3.9-140.2-3.9zM267 169.2c38.2 0 64.8 31.6 64.8 67 0 32.7-18.3 61-42.1 83.1-15 15-39.3 30.5-55.9 40.5-4.4 2.8-10 4.4-16.7 4.4-5.5 0-10.5-1.7-15.5-4.4-16.6-10-41-25.5-56.5-40.5-21.8-20.8-39.2-46.9-41.3-77l-.2-6.1c0-35.5 25.5-67 64.3-67 22.7 0 38.8 11.6 49.3 27.7 11.6-16.1 27.2-27.7 49.9-27.7zm122.5-3.9c28.3 0 43.8 16.6 43.8 43.2s-15.5 42.7-43.8 42.7c-8.9 0-13.8-5-13.8-11.7l0-62.6c0-6.7 5-11.6 13.8-11.6z"/></svg>'},(t,e)=>{e.onclick=()=>{window.open("https://ko-fi.com/swingthevine","_blank","noopener noreferrer")}}).W().yt({class:"bm-k",innerHTML:"🤝",title:"Credits"},(t,e)=>{e.onclick=()=>{new V(this.name,this.version).Wt()}}).W().W().F({textContent:"Made by SwingTheVine",style:"margin-top: auto;"}).W().W().W().W().W()._(this.Bt),this.Dt(`#${this.Nt}.bm-J`,`#${this.Nt} .bm-H`))}}(X,q),et=new class{constructor(t,n,i){e(this,O),this.name=t,this.version=n,this.I=i,this.schemaVersion="2.0.0",this.De=null,this._t="!#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[]^_`abcdefghijklmnopqrstuvwxyz{|}~",this.C=1e3,this.jt=3,this.Jt=3,this.Xt=function(t){const e=v;e.unshift({id:-1,premium:!1,name:"Erased",rgb:[222,250,206]}),e.unshift({id:-2,premium:!1,name:"Other",rgb:[0,0,0]});const n=new Map;for(const i of e){if(0==i.id||-2==i.id)continue;const e=i.rgb[0],s=i.rgb[1],o=i.rgb[2];for(let a=-t;a<=t;a++)for(let r=-t;r<=t;r++)for(let l=-t;l<=t;l++){const t=e+a,c=s+r,h=o+l;if(t<0||t>255||c<0||c>255||h<0||h>255)continue;const m=(255<<24|h<<16|c<<8|t)>>>0;n.has(m)||n.set(m,i.id)}}return{palette:e,O:n}}(this.Jt),this.Yt=null,this.Le="",this.Rt=[],this.Ft=null,this.Oe=!0,this.Ne=null,this.qt=new Map}async Be(){return{whoami:this.name.replace(" ",""),scriptVersion:this.version,schemaVersion:this.schemaVersion,templates:{}}}async Ut(t,e,i){this.Ft||(this.Ft=await this.Be(),console.log("Creating JSON...")),this.I.Ot(`Creating template at ${i.join(", ")}...`);const s=new M({displayName:e,p:0,$:m(this.De||0,this._t),file:t,coords:i}),{k:o,D:a}=await s.S(this.C,this.Xt);s.v=o;const r={total:s.T.total,colors:Object.fromEntries(s.T.colors)};this.Ft.templates[`${s.p} ${s.$}`]={name:s.displayName,coords:i.join(", "),enabled:!0,pixels:r,tiles:a},this.Rt=[],this.Rt.push(s),this.I.Ot(`Template created at ${i.join(", ")}!`),console.log(Object.keys(this.Ft.templates).length),console.log(this.Ft),console.log(this.Rt),console.log(JSON.stringify(this.Ft)),await n(this,O,N).call(this)}Ie(){}async He(){this.Ft||(this.Ft=await this.Be(),console.log("Creating JSON..."))}async Ae(){l("Downloading all templates..."),console.log(this.Rt);for(const t of this.Rt)await this.Pe(t),await i(500)}async zt(){const t=JSON.parse(GM_getValue("bmTemplates","{}"))?.templates;if(console.log(t),Object.keys(t).length>0)for(const[e,n]of Object.entries(t))t.hasOwnProperty(e)&&(await this.Pe(new M({displayName:n.name,p:e.split(" ")?.[0],$:e.split(" ")?.[1],v:n.tiles})),await i(500))}async Pe(t){t.L();const e=`${t.coords.join("-")}_${t.displayName.replaceAll(" ","-")}`,n=await this.Gt(t);await GM.download({url:URL.createObjectURL(n),name:e+".png",We:"uniquify",onload:()=>{l(`Download of template '${e}' complete!`)},onerror:(t,n)=>{c(`Download of template '${e}' failed because ${t}! Details: ${n}`)},ontimeout:()=>{h(`Download of template '${e}' has timed out!`)}})}async Gt(t){console.log(t);const e=t.v,n=Object.keys(e).sort(),i=await Promise.all(n.map(t=>{return n=e[t],new Promise((t,e)=>{const i=new Image;i.onload=()=>t(i),i.onerror=e,i.src="data:image/png;base64,"+n});var n}));let s=1/0,o=1/0,a=0,r=0;n.forEach((t,e)=>{const[n,l,c,h]=t.split(",").map(Number),m=i[e],d=n*this.C+c,u=l*this.C+h;s=Math.min(s,d),o=Math.min(o,u),a=Math.max(a,d+m.width/this.jt),r=Math.max(r,u+m.height/this.jt)}),console.log(`Absolute coordinates: (${s}, ${o}) and (${a}, ${r})`);const l=a-s,c=r-o,h=l*this.jt,m=c*this.jt;console.log(`Template Width: ${l}\nTemplate Height: ${c}\nCanvas Width: ${h}\nCanvas Height: ${m}`);const d=new OffscreenCanvas(h,m),u=d.getContext("2d");n.forEach((t,e)=>{const[n,a,r,l]=t.split(",").map(Number),c=i[e],h=n*this.C+r,m=a*this.C+l;console.log(`Drawing tile (${n}, ${a}, ${r}, ${l}) (${h}, ${m}) at (${h-s}, ${m-o}) on the canvas...`),u.drawImage(c,(h-s)*this.jt,(m-o)*this.jt,c.width,c.height)}),u.globalCompositeOperation="destination-over",u.drawImage(d,0,-1),u.drawImage(d,0,1),u.drawImage(d,-1,0),u.drawImage(d,1,0);const b=new OffscreenCanvas(l,c),p=b.getContext("2d");return p.imageSmoothingEnabled=!1,p.drawImage(d,0,0,l*this.jt,c*this.jt,0,0,l,c),b.convertToBlob({type:"image/png"})}async ze(t,e){if(!this.Oe)return t;const i=this.C*this.jt;e=e[0].toString().padStart(4,"0")+","+e[1].toString().padStart(4,"0"),console.log(`Searching for templates in tile: "${e}"`);const o=this.Rt;console.log(o),o.sort((t,e)=>t.p-e.p),console.log(o);const a=o.map(t=>{const n=Object.keys(t.v).filter(t=>t.startsWith(e));if(0===n.length)return null;const i=n.map(e=>{const n=e.split(",");return{_e:t,Ge:t.v[e],M:t.M?.[e],Ue:[n[0],n[1]],Fe:[n[2],n[3]]}});return i?.[0]}).filter(Boolean);console.log(a);const r=a?.length||0;if(console.log(`templateCount = ${r}`),!(r>0))return this.I.Ot(`Sleeping\nVersion: ${this.version}`),t;{const t=s(o.filter(t=>Object.keys(t.v).filter(t=>t.startsWith(e)).length>0).reduce((t,e)=>t+(e.T.total||0),0));this.I.Ot(`Displaying ${r} template${1==r?"":"s"}.\nTotal pixels: ${t}`)}const l=await createImageBitmap(t),c=new OffscreenCanvas(i,i),h=c.getContext("2d");h.imageSmoothingEnabled=!1,h.beginPath(),h.rect(0,0,i,i),h.clip(),h.clearRect(0,0,i,i),h.drawImage(l,0,0,i,i);const m=h.getImageData(0,0,i,i),d=new Uint32Array(m.data.buffer);for(const t of a){console.log("Template:"),console.log(t);const i=!!t._e.T?.colors?.get(-1);let s=t.M.slice();const o=Number(t.Fe[0])*this.jt,a=Number(t.Fe[1])*this.jt;if(0!=this.qt.size||i||h.drawImage(t.Ge,o,a),!s){const e=h.getImageData(o,a,t.Ge.width,t.Ge.height);s=new Uint32Array(e.data.buffer)}const r=Date.now(),{Qt:l,Zt:c}=n(this,O,I).call(this,{Et:d,Yt:s,Vt:[o,a,t.Ge.width,t.Ge.height]});let m=0;const u=0;for(const[t,e]of l)t!=u&&(m+=e);(0!=this.qt.size||i)&&(console.log("Colors to filter: ",this.qt),h.drawImage(await createImageBitmap(new ImageData(new Uint8ClampedArray(c.buffer),t.Ge.width,t.Ge.height)),o,a)),console.log(`Finished calculating correct pixels & filtering colors for the tile ${e} in ${(Date.now()-r)/1e3} seconds!\nThere are ${m} correct pixels.`),void 0===t._e.T.correct&&(t._e.T.correct={}),t._e.T.correct[e]=l}return await c.convertToBlob({type:"image/png"})}Re(t){console.log("Importing JSON..."),console.log(t),"BlueMarble"==t?.whoami&&n(this,O,B).call(this,t)}ke(t){this.Oe=t}}(X,q,tt),nt=new class{constructor(t){this.Pt=t,this.je=!1,this.Te="",this.Se=[],this.Ee=[]}Ye(t){window.addEventListener("message",async e=>{const n=e.data,i=n.jsonData;if(!n||"blue-marble"!==n.source)return;if(!n.endpoint)return;const o=n.endpoint?.split("?")[0].split("/").filter(t=>t&&isNaN(Number(t))).filter(t=>t&&!t.includes(".")).pop();switch(console.log('%cBlue Marble%c: Recieved message about "%s"',"color: cornflowerblue;","",o),o){case"me":if(i.status&&"2"!=i.status?.toString()[0])return void t.Lt("You are not logged in or Wplace is offline!\nCould not fetch userdata.");const e=Math.ceil(Math.pow(Math.floor(i.level)*Math.pow(30,.65),1/.65)-i.pixelsPainted);if(console.log(i.id),(i.id||0===i.id)&&console.log(m(i.id,"!#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[]^_`abcdefghijklmnopqrstuvwxyz{|}~")),this.Pt.De=i.id,0!=this.Te.length){const t=document.querySelector("#"+this.Te);if(t){const e=i.charges;t.dataset.endDate=Date.now()+(e.max-e.count)*e.cooldownMs}}t.xt("bm-n",`Droplets: <b>${s(i.droplets)}</b>`),t.xt("bm-h",`Next level in <b>${s(e)}</b> pixel${1==e?"":"s"}`);break;case"pixel":const o=n.endpoint.split("?")[0].split("/").filter(t=>t&&!isNaN(Number(t))),l=new URLSearchParams(n.endpoint.split("?")[1]),c=[l.get("x"),l.get("y")];if(this.Se.length&&(!o.length||!c.length))return void t.Lt("Coordinates are malformed!\nDid you try clicking the canvas first?");this.Se=[...o,...c];const h=(a=o,r=c,[parseInt(a[0])%4*1e3+parseInt(r[0]),parseInt(a[1])%4*1e3+parseInt(r[1])]),d=document.querySelectorAll("span");for(const t of d)if(t.textContent.trim().includes(`${h[0]}, ${h[1]}`)){let e=document.querySelector("#bm-g");const n=`(Tl X: ${o[0]}, Tl Y: ${o[1]}, Px X: ${c[0]}, Px Y: ${c[1]})`;e?e.textContent=n:(e=document.createElement("span"),e.id="bm-g",e.textContent=n,e.style="margin-left: calc(var(--spacing)*3); font-size: small;",t.parentNode.parentNode.insertAdjacentElement("afterend",e))}break;case"tile":case"tiles":let u=n.endpoint.split("/");u=[parseInt(u[u.length-2]),parseInt(u[u.length-1].replace(".png",""))];const b=n.blobID,p=n.blobData,f=Date.now(),g=await this.Pt.ze(p,u);console.log(`Finished loading the tile in ${(Date.now()-f)/1e3} seconds!`),window.postMessage({source:"blue-marble",blobID:b,blobData:g,blink:n.blink});break;case"robots":this.je="false"==i.userscript?.toString().toLowerCase();break}var a,r})}async Ve(t){console.log("Sending heartbeat to telemetry server...");let e=GM_getValue("bmUserSettings","{}");if(e=JSON.parse(e),!e||!e.telemetry||!e.uuid)return void console.log("Telemetry is disabled, not sending heartbeat.");const n=navigator.userAgent;let i=await this.Je(n),s=this.Xe(n);GM_xmlhttpRequest({method:"POST",url:"https://telemetry.thebluecorner.net/heartbeat",headers:{"Content-Type":"application/json"},data:JSON.stringify({uuid:e.uuid,version:t,browser:i,os:s}),onload:t=>{200!==t.status&&c("Failed to send heartbeat:",t.statusText)},onerror:t=>{c("Error sending heartbeat:",t)}})}async Je(t=navigator.userAgent){return(t=t||"").includes("OPR/")||t.includes("Opera")?"Opera":t.includes("Edg/")?"Edge":t.includes("Vivaldi")?"Vivaldi":t.includes("YaBrowser")?"Yandex":t.includes("Kiwi")?"Kiwi":t.includes("Brave")?"Brave":t.includes("Firefox/")?"Firefox":t.includes("Chrome/")?"Chrome":t.includes("Safari/")?"Safari":navigator.brave&&"function"==typeof navigator.brave.isBrave&&await navigator.brave.isBrave()?"Brave":"Unknown"}Xe(t=navigator.userAgent){return/Windows NT 11/i.test(t=t||"")?"Windows 11":/Windows NT 10/i.test(t)?"Windows 10":/Windows NT 6\.3/i.test(t)?"Windows 8.1":/Windows NT 6\.2/i.test(t)?"Windows 8":/Windows NT 6\.1/i.test(t)?"Windows 7":/Windows NT 6\.0/i.test(t)?"Windows Vista":/Windows NT 5\.1|Windows XP/i.test(t)?"Windows XP":/Mac OS X 10[_\.]15/i.test(t)?"macOS Catalina":/Mac OS X 10[_\.]14/i.test(t)?"macOS Mojave":/Mac OS X 10[_\.]13/i.test(t)?"macOS High Sierra":/Mac OS X 10[_\.]12/i.test(t)?"macOS Sierra":/Mac OS X 10[_\.]11/i.test(t)?"OS X El Capitan":/Mac OS X 10[_\.]10/i.test(t)?"OS X Yosemite":/Mac OS X 10[_\.]/i.test(t)?"macOS":/Android/i.test(t)?"Android":/iPhone|iPad|iPod/i.test(t)?"iOS":/Linux/i.test(t)?"Linux":"Unknown"}}(et);tt.P(nt);var it=JSON.parse(GM_getValue("bmTemplates","{}"));console.log(it),et.Re(it);var st=JSON.parse(GM_getValue("bmUserSettings","{}"));if(console.log(st),console.log(Object.keys(st).length),0==Object.keys(st).length){const t=crypto.randomUUID();console.log(t),GM.setValue("bmUserSettings",JSON.stringify({uuid:t}))}setInterval(()=>nt.Ve(q),18e5);var ot=st?.telemetry;if(console.log(`Telemetry is ${!(null==ot)}`),null==ot||ot>1){const t=new class extends D{constructor(t,n,i,s){super(t,n),e(this,E),this.window=null,this.Nt="bm-e",this.Bt=document.body,this.qe=i,this.uuid=s}async Wt(){if(document.querySelector(`#${this.Nt}`))return void this.Lt("Telemetry window already exists!");const t=await this.N.Je(navigator.userAgent),e=this.N.Xe(navigator.userAgent);this.window=this.G({id:this.Nt,class:"bm-J",style:"height: 80vh; z-index: 9998;"}).G({class:"bm-f"}).G({class:"bm-B bm-b"}).J(1,{textContent:`${this.name} Telemetry`}).W().W().X().W().G({class:"bm-B bm-u",style:"gap: 1.5ch; flex-wrap: wrap;"}).yt({textContent:"Enable Telemetry"},(t,e)=>{e.onclick=()=>{n(this,E,Y).call(this,this.qe);const t=document.getElementById(this.Nt);t?.remove()}}).W().yt({textContent:"Disable Telemetry"},(t,e)=>{e.onclick=()=>{n(this,E,Y).call(this,0);const t=document.getElementById(this.Nt);t?.remove()}}).W().yt({textContent:"More Information"},(t,e)=>{e.onclick=()=>{window.open("https://github.com/SwingTheVine/Wplace-TelemetryServer#telemetry-data","_blank","noopener noreferrer")}}).W().W().G({class:"bm-B bm-x"}).G({class:"bm-B"}).J(2,{textContent:"Legal"}).W().U({textContent:`We collect anonymous telemetry data such as your browser, OS, and script version to make the experience better for everyone. The data is never shared personally. The data is never sold. You can turn this off by pressing the "Disable" button, but keeping it on helps us improve features and reliability faster. Thank you for supporting ${this.name}!`}).W().W().X().W().G({class:"bm-B"}).J(2,{textContent:"Non-Legal Summary"}).W().U({innerHTML:'You can disable telemetry by pressing the "Disable" button. If you would like to read more about what information we collect, press the "More Information" button.<br>This is the data <em>stored</em> on our servers:'}).W().ot().lt({innerHTML:`A unique identifier (UUIDv4) generated by Blue Marble. This enables our telemetry to function without tracking your actual user ID.<br>Your UUID is: <b>${r(this.uuid)}</b>`}).W().lt({innerHTML:`The version of Blue Marble you are using.<br>Your version is: <b>${r(this.version)}</b>`}).W().lt({innerHTML:`Your browser type, which is used to determine Blue Marble outages and browser popularity.<br>Your browser type is: <b>${r(t)}</b>`}).W().lt({innerHTML:`Your OS type, which is used to determine Blue Marble outages and OS popularity.<br>Your OS type is: <b>${r(e)}</b>`}).W().lt({innerHTML:"The date and time that Blue Marble sent the telemetry information."}).W().W().U({innerHTML:'All of the data mentioned above is <b>aggregated every hour</b>. This means every hour, anything that could even remotly be considered "personal data" is deleted from our server. Here, "aggregated" data means things like "42 people used Blue Marble on Google Chrome this hour", which can\'t be used to identify anyone in particular.'}).W().W().W().W().W()._(this.Bt)}}(X,q,1,st?.uuid);t.P(nt),t.Wt()}tt.Wt(),nt.Ye(tt),new MutationObserver((t,e)=>{const n=document.querySelector("#color-1");if(!n)return;let i=document.querySelector("#bm-w");if(!i){i=document.createElement("button"),i.id="bm-w",i.textContent="Move ↑",i.className="btn btn-soft",i.onclick=function(){const t=this.parentNode.parentNode.parentNode.parentNode,e="Move ↑"==this.textContent;t.parentNode.className=t.parentNode.className.replace(e?"bottom":"top",e?"top":"bottom"),t.style.borderTopLeftRadius=e?"0px":"var(--radius-box)",t.style.borderTopRightRadius=e?"0px":"var(--radius-box)",t.style.borderBottomLeftRadius=e?"var(--radius-box)":"0px",t.style.borderBottomRightRadius=e?"var(--radius-box)":"0px",this.textContent=e?"Move ↓":"Move ↑"};const t=n.parentNode.parentNode.parentNode.parentNode.querySelector("h2");t.parentNode?.appendChild(i)}}).observe(document.body,{childList:!0,subtree:!0}),l(`%c${X}%c (${q}) userscript has loaded!`,"color: cornflowerblue;","")})();