// ==UserScript==
// @name         Blue Marble
// @namespace    https://github.com/SwingTheVine/
// @version      0.86.0
// @description  A userscript to automate and/or enhance the user experience on Wplace.live. Make sure to comply with the site's Terms of Service, and rules! This script is not affiliated with Wplace.live in any way, use at your own risk. This script is not affiliated with TamperMonkey. 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 image is owned by NASA.
// @author       SwingTheVine
// @license      MPL-2.0
// @supportURL   https://discord.gg/tpeBPy46hf
// @homepageURL  https://bluemarble.lol/
// @icon         https://raw.githubusercontent.com/SwingTheVine/Wplace-BlueMarble/30256c4535ef239f287a8b09caa5fcdd8161ad5d/dist/assets/Favicon.png
// @updateURL    https://raw.githubusercontent.com/SwingTheVine/Wplace-BlueMarble/main/dist/BlueMarble.user.js
// @downloadURL  https://raw.githubusercontent.com/SwingTheVine/Wplace-BlueMarble/main/dist/BlueMarble.user.js
// @match        https://wplace.live/*
// @grant        GM_getResourceText
// @grant        GM_addStyle
// @grant        GM.setValue
// @grant        GM_getValue
// @grant        GM_xmlhttpRequest
// @connect      telemetry.thebluecorner.net
// @resource     CSS-BM-File https://raw.githubusercontent.com/SwingTheVine/Wplace-BlueMarble/30256c4535ef239f287a8b09caa5fcdd8161ad5d/dist/BlueMarble.user.css
// ==/UserScript==

// Wplace  --> https://wplace.live
// License --> https://www.mozilla.org/en-US/MPL/2.0/

(()=>{var t,e,i=t=>{throw TypeError(t)},n=(t,e,n)=>e.has(t)?i("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,n),o=(t,e,n)=>(((t,e)=>{e.has(t)||i("Cannot access private method")})(t,e),n),r=class{constructor(e,i){n(this,t),this.name=e,this.version=i,this.t=null,this.i="bm-o",this.o=null,this.m=null,this.l=[]}u(t){this.t=t}h(){return this.l.length>0&&(this.m=this.l.pop()),this}p(t){t?.appendChild(this.o),this.o=null,this.m=null,this.l=[]}v(i={},n=()=>{}){return n(this,o(this,t,e).call(this,"div",{},i)),this}$(i={},n=()=>{}){return n(this,o(this,t,e).call(this,"p",{},i)),this}S(i={},n=()=>{}){return n(this,o(this,t,e).call(this,"small",{},i)),this}M(i={},n=()=>{}){return n(this,o(this,t,e).call(this,"img",{},i)),this}O(i,n={},r=()=>{}){return r(this,o(this,t,e).call(this,"h"+i,{},n)),this}T(i={},n=()=>{}){return n(this,o(this,t,e).call(this,"hr",{},i)),this}C(i={},n=()=>{}){return n(this,o(this,t,e).call(this,"br",{},i)),this}D(i={},n=()=>{}){const r=o(this,t,e).call(this,"label",{textContent:i.textContent??""});delete i.textContent;const s=o(this,t,e).call(this,"input",{type:"checkbox"},i);return r.insertBefore(s,r.firstChild),this.h(),n(this,r,s),this}k(i={},n=()=>{}){return n(this,o(this,t,e).call(this,"button",{},i)),this}N(i={},n=()=>{}){const r=i.title??i.textContent??"Help: No info";delete i.textContent,i.title=`Help: ${r}`;const s={textContent:"?",className:"bm-D",onclick:()=>{this.B(this.i,r)}};return n(this,o(this,t,e).call(this,"button",s,i)),this}I(i={},n=()=>{}){return n(this,o(this,t,e).call(this,"input",{},i)),this}L(i={},n=()=>{}){const r=i.textContent??"";delete i.textContent;const s=o(this,t,e).call(this,"div"),a=o(this,t,e).call(this,"input",{type:"file",style:"display: none !important; visibility: hidden !important; position: absolute !important; left: -9999px !important; width: 0 !important; height: 0 !important; opacity: 0 !important;"},i);this.h();const m=o(this,t,e).call(this,"button",{textContent:r});return this.h(),this.h(),a.setAttribute("tabindex","-1"),a.setAttribute("aria-hidden","true"),m.addEventListener("click",()=>{a.click()}),a.addEventListener("change",()=>{m.style.maxWidth=`${m.offsetWidth}px`,a.files.length>0?m.textContent=a.files[0].name:m.textContent=r}),n(this,s,a,m),this}G(i={},n=()=>{}){return n(this,o(this,t,e).call(this,"textarea",{},i)),this}B(t,e,i=!1){const n=document.getElementById(t.replace(/^#/,""));n&&(n instanceof HTMLInputElement?n.value=e:i?n.textContent=e:n.innerHTML=e)}W(t,e){let i,n=!1,o=0,r=null,s=0,a=0,m=0,l=0;if(t=document.querySelector("#"==t?.[0]?t:"#"+t),e=document.querySelector("#"==e?.[0]?e:"#"+e),!t||!e)return void this.P(`Can not drag! ${t?"":"moveMe"} ${t||e?"":"and "}${e?"":"iMoveThings "}was not found!`);const c=()=>{if(n){const e=Math.abs(s-m),i=Math.abs(a-l);(e>.5||i>.5)&&(s=m,a=l,t.style.transform=`translate(${s}px, ${a}px)`,t.style.left="0px",t.style.top="0px",t.style.right=""),r=requestAnimationFrame(c)}};let u=null;const d=(d,h)=>{n=!0,u=t.getBoundingClientRect(),i=d-u.left,o=h-u.top;const b=window.getComputedStyle(t).transform;if(b&&"none"!==b){const t=new DOMMatrix(b);s=t.m41,a=t.m42}else s=u.left,a=u.top;m=s,l=a,document.body.style.userSelect="none",e.classList.add("dragging"),r&&cancelAnimationFrame(r),c()},h=()=>{n=!1,r&&(cancelAnimationFrame(r),r=null),document.body.style.userSelect="",e.classList.remove("dragging")};e.addEventListener("mousedown",function(t){t.preventDefault(),d(t.clientX,t.clientY)}),e.addEventListener("touchstart",function(t){const e=t?.touches?.[0];e&&(d(e.clientX,e.clientY),t.preventDefault())},{passive:!1}),document.addEventListener("mousemove",function(t){n&&u&&(m=t.clientX-i,l=t.clientY-o)},{passive:!0}),document.addEventListener("touchmove",function(t){if(n&&u){const e=t?.touches?.[0];if(!e)return;m=e.clientX-i,l=e.clientY-o,t.preventDefault()}},{passive:!1}),document.addEventListener("mouseup",h),document.addEventListener("touchend",h),document.addEventListener("touchcancel",h)}_(t){(0,console.info)(`${this.name}: ${t}`),this.B(this.i,"Status: "+t,!0)}P(t){(0,console.error)(`${this.name}: ${t}`),this.B(this.i,"Error: "+t,!0)}};function s(...t){(0,console.error)(...t)}function a(t,e){if(0===t)return e[0];let i="";const n=e.length;for(;t>0;)i=e[t%n]+i,t=Math.floor(t/n);return i}function m(t){let e="";for(let i=0;i<t.length;i++)e+=String.fromCharCode(t[i]);return btoa(e)}function l(t){const e=atob(t),i=new Uint8Array(e.length);for(let t=0;t<e.length;t++)i[t]=e.charCodeAt(t);return i}t=new WeakSet,e=function(t,e={},i={}){const n=document.createElement(t);this.o?(this.m?.appendChild(n),this.l.push(this.m),this.m=n):(this.o=n,this.m=n);for(const[t,i]of Object.entries(e))n[t]=i;for(const[t,e]of Object.entries(i))n[t]=e;return n};var c,u,d,h,b,p,g=[{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]}],f=class{constructor({displayName:t="My template",F:e=0,j:i="",url:n="",file:o=null,coords:r=null,R:s=null,A:a=1e3}={}){this.displayName=t,this.F=e,this.j=i,this.url=n,this.file=o,this.coords=r,this.R=s,this.A=a,this.J=0,this.U=0,this.V=0,this.X={},this.q=new Set,this.H=null;const m=Array.isArray(g)?g:[];this.Y=new Set(m.filter(t=>"transparent"!==(t?.name||"").toLowerCase()&&Array.isArray(t?.rgb)).map(t=>`${t.rgb[0]},${t.rgb[1]},${t.rgb[2]}`));const l="222,250,206";this.Y.add(l);const c="other";this.Y.add(c),this.K=new Map(m.filter(t=>Array.isArray(t?.rgb)).map(t=>[`${t.rgb[0]},${t.rgb[1]},${t.rgb[2]}`,{id:t.id,premium:!!t.premium,name:t.name}]));try{const t=m.find(t=>"transparent"===(t?.name||"").toLowerCase());t&&Array.isArray(t.rgb)&&this.K.set(l,{id:t.id,premium:!!t.premium,name:t.name})}catch(t){}try{this.K.set(c,{id:"other",premium:!1,name:"Other"})}catch(t){}}async Z(){const t=await createImageBitmap(this.file),e=t.width,i=t.height,n=e*i;this.J=n;try{const n=new OffscreenCanvas(e,i).getContext("2d",{tt:!0});n.imageSmoothingEnabled=!1,n.clearRect(0,0,e,i),n.drawImage(t,0,0);const o=n.getImageData(0,0,e,i).data;let r=0,s=0;const a=new Map;for(let t=0;t<i;t++)for(let i=0;i<e;i++){const n=4*(t*e+i),m=o[n],l=o[n+1],c=o[n+2];if(0===o[n+3])continue;222===m&&250===l&&206===c&&s++;const u=this.Y.has(`${m},${l},${c}`)?`${m},${l},${c}`:"other";r++,a.set(u,(a.get(u)||0)+1)}this.U=r,this.V=s;const m={};for(const[t,e]of a.entries())m[t]={count:e,enabled:!0};this.X=m}catch(t){this.U=Math.max(0,this.J),this.V=0}const o={},r={},s=new OffscreenCanvas(this.A,this.A),a=s.getContext("2d",{tt:!0});for(let n=this.coords[3];n<i+this.coords[3];){const l=Math.min(this.A-n%this.A,i-(n-this.coords[3]));for(let i=this.coords[2];i<e+this.coords[2];){const c=Math.min(this.A-i%this.A,e-(i-this.coords[2])),u=3*c,d=3*l;s.width=u,s.height=d,a.imageSmoothingEnabled=!1,a.clearRect(0,0,u,d),a.drawImage(t,i-this.coords[2],n-this.coords[3],c,l,0,0,3*c,3*l);const h=a.getImageData(0,0,u,d);for(let t=0;t<d;t++)for(let e=0;e<u;e++){const i=4*(t*u+e);if(222===h.data[i]&&250===h.data[i+1]&&206===h.data[i+2])(e+t)%2==0?(h.data[i]=0,h.data[i+1]=0,h.data[i+2]=0):(h.data[i]=255,h.data[i+1]=255,h.data[i+2]=255),h.data[i+3]=32;else if(e%3!=1||t%3!=1)h.data[i+3]=0;else{const t=h.data[i],e=h.data[i+1],n=h.data[i+2];this.Y.has(`${t},${e},${n}`)}}a.putImageData(h,0,0);const b=`${(this.coords[0]+Math.floor(i/1e3)).toString().padStart(4,"0")},${(this.coords[1]+Math.floor(n/1e3)).toString().padStart(4,"0")},${(i%1e3).toString().padStart(3,"0")},${(n%1e3).toString().padStart(3,"0")}`;o[b]=await createImageBitmap(s),this.q.add(b.split(",").slice(0,2).join(","));const p=await s.convertToBlob(),g=await p.arrayBuffer(),f=Array.from(new Uint8Array(g));r[b]=m(f),i+=c}n+=l}return{et:o,it:r}}};c=new WeakSet,u=async function(){GM.setValue("bmTemplates",JSON.stringify(this.nt))},d=async function(t){const e=t.templates;if(Object.keys(e).length>0){for(const t in e){const i=t,n=e[t];if(e.hasOwnProperty(t)){const t=i.split(" "),o=Number(t?.[0]),r=t?.[1]||"0",s=n.name||`Template ${o||""}`,a=n.tiles,m={};let c=0;const u=new Map;for(const t in a)if(a.hasOwnProperty(t)){const e=l(a[t]),i=new Blob([e],{type:"image/png"}),n=await createImageBitmap(i);m[t]=n;try{const t=n.width,e=n.height,i=new OffscreenCanvas(t,e).getContext("2d",{tt:!0});i.imageSmoothingEnabled=!1,i.clearRect(0,0,t,e),i.drawImage(n,0,0);const o=i.getImageData(0,0,t,e).data;for(let i=0;i<e;i++)for(let e=0;e<t;e++){if(e%this.ot!==1||i%this.ot!==1)continue;const n=4*(i*t+e),r=o[n],s=o[n+1],a=o[n+2];if(o[n+3]<64)continue;if(222===r&&250===s&&206===a)continue;c++;const m=activeTemplate.Y.has(`${r},${s},${a}`)?`${r},${s},${a}`:"other";u.set(m,(u.get(m)||0)+1)}}catch(t){}}const d=new f({displayName:s,F:o||this.rt?.length||0,j:r||""});d.R=m,d.U=c;const h={};for(const[t,e]of u.entries())h[t]={count:e,enabled:!0};d.X=h;try{Object.keys(m).forEach(t=>{d.q?.add(t.split(",").slice(0,2).join(","))})}catch(t){}try{const t=e?.[i]?.palette;if(t)for(const[e,i]of Object.entries(t))d.X[e]?d.X[e].enabled=!!i?.enabled:d.X[e]={count:i?.count||0,enabled:!!i?.enabled}}catch(t){}d.H=i,this.rt.push(d)}}try{const t=document.querySelector("#bm-9");t&&(t.style.display=""),window.postMessage({source:"blue-marble",st:"bm-b"},"*")}catch(t){}}},h=new WeakSet,b=async function(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"},p=function(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"};var w=GM_info.script.name.toString(),y=GM_info.script.version.toString();!function(t){const e=document.createElement("script");e.setAttribute("bm-E",w),e.setAttribute("bm-B","color: cornflowerblue;"),e.textContent=`(${t})();`,document.documentElement?.appendChild(e),e.remove()}(()=>{const t=document.currentScript,e=t?.getAttribute("bm-E")||"Blue Marble",i=t?.getAttribute("bm-B")||"",n=new Map;window.addEventListener("message",t=>{const{source:o,endpoint:r,blobID:s,blobData:a,blink:m}=t.data;if(Date.now(),"blue-marble"==o&&s&&a&&!r){const t=n.get(s);"function"==typeof t?t(a):function(...t){(0,console.warn)(...t)}(`%c${e}%c: Attempted to retrieve a blob (%s) from queue, but the blobID was not a function! Skipping...`,i,"",s),n.delete(s)}});const o=window.fetch;window.fetch=async function(...t){const e=await o.apply(this,t),i=e.clone(),r=(t[0]instanceof Request?t[0]?.url:t[0])||"ignore",s=i.headers.get("content-type")||"";if(s.includes("application/json"))i.json().then(t=>{window.postMessage({source:"blue-marble",endpoint:r,jsonData:t},"*")}).catch(t=>{});else if(s.includes("image/")&&!r.includes("openfreemap")&&!r.includes("maps")){const t=Date.now(),e=await i.blob();return new Promise(o=>{const s=crypto.randomUUID();n.set(s,t=>{o(new Response(t,{headers:i.headers,status:i.status,statusText:i.statusText}))}),window.postMessage({source:"blue-marble",endpoint:r,blobID:s,blobData:e,blink:t})}).catch(t=>{Date.now()})}return e}});var v=GM_getResourceText("CSS-BM-File");GM_addStyle(v);var x=document.createElement("link");x.href="https://fonts.googleapis.com/css2?family=Roboto+Mono:ital,wght@0,100..700;1,100..700&display=swap",x.rel="preload",x.as="style",x.onload=function(){this.onload=null,this.rel="stylesheet"},document.head?.appendChild(x),new class{constructor(){this.lt=null,this.ct=null,this.ut="#bm-h"}dt(t){return this.ct=t,this.lt=new MutationObserver(t=>{for(const e of t)for(const t of e.addedNodes)t instanceof HTMLElement&&t.matches?.(this.ut)}),this}ht(){return this.lt}observe(t,e=!1,i=!1){t.observe(this.ct,{childList:e,subtree:i})}};var $=new r(w,y),S=(new r(w,y),new class{constructor(t,e,i){n(this,c),this.name=t,this.version=e,this.o=i,this.bt="1.0.0",this.gt=null,this.ft="!#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[]^_`abcdefghijklmnopqrstuvwxyz{|}~",this.A=1e3,this.ot=3,this.wt=null,this.yt=null,this.vt="bm-C",this.xt="div#map canvas.maplibregl-canvas",this.$t=null,this.St="",this.rt=[],this.nt=null,this.Mt=!0,this.Ot=new Map}Tt(){if(document.body.contains(this.wt))return this.wt;document.getElementById(this.vt)?.remove();const t=document.querySelector(this.xt),e=document.createElement("canvas");return e.id=this.vt,e.className="maplibregl-canvas",e.style.position="absolute",e.style.top="0",e.style.left="0",e.style.height=t?.clientHeight*(window.devicePixelRatio||1)+"px",e.style.width=t?.clientWidth*(window.devicePixelRatio||1)+"px",e.height=t?.clientHeight*(window.devicePixelRatio||1),e.width=t?.clientWidth*(window.devicePixelRatio||1),e.style.zIndex="8999",e.style.pointerEvents="none",t?.parentElement?.appendChild(e),this.wt=e,window.addEventListener("move",this.Ct),window.addEventListener("zoom",this.Dt),window.addEventListener("resize",this.kt),this.wt}async Nt(){return{whoami:this.name.replace(" ",""),scriptVersion:this.version,schemaVersion:this.bt,templates:{}}}async Bt(t,e,i){this.nt||(this.nt=await this.Nt()),this.o._(`Creating template at ${i.join(", ")}...`);const n=new f({displayName:e,F:0,j:a(this.gt||0,this.ft),file:t,coords:i}),{et:r,it:s}=await n.Z(this.A);n.R=r;const m=`${n.F} ${n.j}`;n.H=m,this.nt.templates[m]={name:n.displayName,coords:i.join(", "),enabled:!0,tiles:s,palette:n.X},this.rt=[],this.rt.push(n);const l=(new Intl.NumberFormat).format(n.J);this.o._(`Template created at ${i.join(", ")}! Total pixels: ${l}`);try{const t=document.querySelector("#bm-9");t&&(t.style.display=""),window.postMessage({source:"blue-marble",st:"bm-b"},"*")}catch(t){}await o(this,c,u).call(this)}It(){}async Lt(){this.nt||(this.nt=await this.Nt())}async Gt(t,e){if(!this.Mt)return t;const i=this.A*this.ot;e=e[0].toString().padStart(4,"0")+","+e[1].toString().padStart(4,"0");const n=this.rt;if(n.sort((t,e)=>t.F-e.F),!n.some(t=>!!t?.R&&(t.q&&t.q.size>0?t.q.has(e):Object.keys(t.R).some(t=>t.startsWith(e)))))return t;const o=n.map(t=>{const i=Object.keys(t.R).filter(t=>t.startsWith(e));if(0===i.length)return null;const n=i.map(e=>{const i=e.split(",");return{Wt:t.R[e],Pt:[i[0],i[1]],_t:[i[2],i[3]]}});return n?.[0]}).filter(Boolean),r=o?.length||0;let s=0,a=0,m=0;const l=await createImageBitmap(t),c=new OffscreenCanvas(i,i),u=c.getContext("2d");u.imageSmoothingEnabled=!1,u.beginPath(),u.rect(0,0,i,i),u.clip(),u.clearRect(0,0,i,i),u.drawImage(l,0,0,i,i);let d=null;try{d=u.getImageData(0,0,i,i).data}catch(t){}for(const t of o){if(d)try{const e=t.Wt.width,n=t.Wt.height,o=new OffscreenCanvas(e,n).getContext("2d",{tt:!0});o.imageSmoothingEnabled=!1,o.clearRect(0,0,e,n),o.drawImage(t.Wt,0,0);const r=o.getImageData(0,0,e,n).data,l=Number(t._t[0])*this.ot,c=Number(t._t[1])*this.ot;for(let t=0;t<n;t++)for(let n=0;n<e;n++){if(n%this.ot!==1||t%this.ot!==1)continue;const o=n+l,u=t+c;if(o<0||u<0||o>=i||u>=i)continue;const h=4*(t*e+n),b=r[h],p=r[h+1],g=r[h+2];if(r[h+3]<64){try{const t=this.rt?.[0],e=4*(u*i+o),n=d[e],r=d[e+1],s=d[e+2],m=d[e+3],l=t.Y.has(`${n},${r},${s}`)?`${n},${r},${s}`:"other",c=!!t?.Y&&t.Y.has(l);m>=64&&c&&a++}catch(t){}continue}m++;const f=4*(u*i+o),w=d[f],y=d[f+1],v=d[f+2];d[f+3]<64||(w===b&&y===p&&v===g?s++:a++)}}catch(t){}try{const e=this.rt?.[0],i=e?.X||{};if(Object.values(i).some(t=>!1===t?.enabled)){const n=t.Wt.width,o=t.Wt.height,r=new OffscreenCanvas(n,o),s=r.getContext("2d",{tt:!0});s.imageSmoothingEnabled=!1,s.clearRect(0,0,n,o),s.drawImage(t.Wt,0,0);const a=s.getImageData(0,0,n,o),m=a.data;for(let t=0;t<o;t++)for(let o=0;o<n;o++){if(o%this.ot!==1||t%this.ot!==1)continue;const r=4*(t*n+o),s=m[r],a=m[r+1],l=m[r+2];if(m[r+3]<1)continue;let c=e.Y.has(`${s},${a},${l}`)?`${s},${a},${l}`:"other";(!e?.Y||e.Y.has(c))&&!1!==i?.[c]?.enabled||(m[r+3]=0)}s.putImageData(a,0,0),u.drawImage(r,Number(t._t[0])*this.ot,Number(t._t[1])*this.ot)}else u.drawImage(t.Wt,Number(t._t[0])*this.ot,Number(t._t[1])*this.ot)}catch(e){u.drawImage(t.Wt,Number(t._t[0])*this.ot,Number(t._t[1])*this.ot)}}if(r>0){const t=e;this.Ot.set(t,{Et:s,required:m,Ft:a});let i=0,n=0,o=0;for(const t of this.Ot.values())i+=t.Et||0,n+=t.required||0,o+=t.Ft||0;const l=this.rt.reduce((t,e)=>t+(e.U||e.J||0),0),c=l>0?l:n,u=(new Intl.NumberFormat).format(i),d=(new Intl.NumberFormat).format(c),h=(new Intl.NumberFormat).format(c-i);this.o._(`Displaying ${r} template${1==r?"":"s"}.\nPainted ${u} / ${d} • Wrong ${h}`)}else this.o._(`Displaying ${r} templates.`);return await c.convertToBlob({type:"image/png"})}jt(t){"BlueMarble"==t?.whoami&&o(this,c,d).call(this,t)}Rt(t){this.Mt=t}}(w,y,$)),M=new class{constructor(t){n(this,h),this.At=t,this.Jt=!1,this.Ut=[],this.Vt=[]}Xt(t){window.addEventListener("message",async e=>{const i=e.data,n=i.jsonData;if(!i||"blue-marble"!==i.source)return;if(!i.endpoint)return;const o=i.endpoint?.split("?")[0].split("/").filter(t=>t&&isNaN(Number(t))).filter(t=>t&&!t.includes(".")).pop();switch(o){case"me":if(n.status&&"2"!=n.status?.toString()[0])return void t.P("You are not logged in!\nCould not fetch userdata.");const e=Math.ceil(Math.pow(Math.floor(n.level)*Math.pow(30,.65),1/.65)-n.pixelsPainted);n.id||n.id,this.At.gt=n.id,t.B("bm-u",`Username: <b>${function(t){const e=document.createElement("div");return e.textContent=t,e.innerHTML}(n.name)}</b>`),t.B("bm-p",`Droplets: <b>${(new Intl.NumberFormat).format(n.droplets)}</b>`),t.B("bm-i",`Next level in <b>${(new Intl.NumberFormat).format(e)}</b> pixel${1==e?"":"s"}`);break;case"pixel":const o=i.endpoint.split("?")[0].split("/").filter(t=>t&&!isNaN(Number(t))),a=new URLSearchParams(i.endpoint.split("?")[1]),m=[a.get("x"),a.get("y")];if(this.Ut.length&&(!o.length||!m.length))return void t.P("Coordinates are malformed!\nDid you try clicking the canvas first?");this.Ut=[...o,...m];const l=(r=o,s=m,[parseInt(r[0])%4*1e3+parseInt(s[0]),parseInt(r[1])%4*1e3+parseInt(s[1])]),c=document.querySelectorAll("span");for(const t of c)if(t.textContent.trim().includes(`${l[0]}, ${l[1]}`)){let e=document.querySelector("#bm-h");const i=`(Tl X: ${o[0]}, Tl Y: ${o[1]}, Px X: ${m[0]}, Px Y: ${m[1]})`;e?e.textContent=i:(e=document.createElement("span"),e.id="bm-h",e.textContent=i,e.style="margin-left: calc(var(--spacing)*3); font-size: small;",t.parentNode.parentNode.parentNode.insertAdjacentElement("afterend",e))}break;case"tiles":let u=i.endpoint.split("/");u=[parseInt(u[u.length-2]),parseInt(u[u.length-1].replace(".png",""))];const d=i.blobID,h=i.blobData,b=await this.At.Gt(h,u);window.postMessage({source:"blue-marble",blobID:d,blobData:b,blink:i.blink});break;case"robots":this.Jt="false"==n.userscript?.toString().toLowerCase()}var r,s})}async qt(t){let e=GM_getValue("bmUserSettings","{}");if(e=JSON.parse(e),!e||!e.telemetry||!e.uuid)return;const i=navigator.userAgent;let n=await o(this,h,b).call(this,i),r=o(this,h,p).call(this,i);GM_xmlhttpRequest({method:"POST",url:"https://telemetry.thebluecorner.net/heartbeat",headers:{"Content-Type":"application/json"},data:JSON.stringify({uuid:e.uuid,version:t,browser:n,os:r}),onload:t=>{200!==t.status&&s("Failed to send heartbeat:",t.statusText)},onerror:t=>{s("Error sending heartbeat:",t)}})}}(S);$.u(M);var O=JSON.parse(GM_getValue("bmTemplates","{}"));S.jt(O);var T=JSON.parse(GM_getValue("bmUserSettings","{}"));if(0==Object.keys(T).length){const t=crypto.randomUUID();GM.setValue("bmUserSettings",JSON.stringify({uuid:t}))}if(setInterval(()=>M.qt(y),18e5),null==T?.telemetry||T?.telemetry>1){const t=new r(w,y);t.u(M),t.v({id:"bm-d",style:"top: 0px; left: 0px; width: 100vw; max-width: 100vw; height: 100vh; max-height: 100vh; z-index: 9999;"}).v({id:"bm-7",style:"display: flex; flex-direction: column; align-items: center;"}).v({id:"bm-1",style:"margin-top: 10%;"}).O(1,{textContent:`${w} Telemetry`}).h().h().v({id:"bm-e",style:"max-width: 50%; overflow-y: auto; max-height: 80vh;"}).T().h().C().h().v({style:"width: fit-content; margin: auto; text-align: center;"}).k({id:"bm-8",textContent:"More Information"},(t,e)=>{e.onclick=()=>{window.open("https://github.com/SwingTheVine/Wplace-TelemetryServer#telemetry-data","_blank","noopener noreferrer")}}).h().h().C().h().v({style:"width: fit-content; margin: auto; text-align: center;"}).k({id:"bm-5",textContent:"Enable Telemetry",style:"margin-right: 2ch;"},(t,e)=>{e.onclick=()=>{const t=JSON.parse(GM_getValue("bmUserSettings","{}"));t.telemetry=1,GM.setValue("bmUserSettings",JSON.stringify(t));const e=document.getElementById("bm-d");e&&(e.style.display="none")}}).h().k({id:"bm-2",textContent:"Disable Telemetry"},(t,e)=>{e.onclick=()=>{const t=JSON.parse(GM_getValue("bmUserSettings","{}"));t.telemetry=0,GM.setValue("bmUserSettings",JSON.stringify(t));const e=document.getElementById("bm-d");e&&(e.style.display="none")}}).h().h().C().h().$({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 the Blue Marble!"}).h().$({textContent:'You can disable telemetry by pressing the "Disable" button below.'}).h().h().h().p(document.body)}!function(){let t=!1,e={};try{e=JSON.parse(GM_getValue("bmCoords","{}"))||{}}catch(t){e={}}const i=()=>{try{const t=Number(document.querySelector("#bm-v")?.value||""),e=Number(document.querySelector("#bm-w")?.value||""),i={Ht:t,Yt:e,px:Number(document.querySelector("#bm-x")?.value||""),zt:Number(document.querySelector("#bm-y")?.value||"")};GM.setValue("bmCoords",JSON.stringify(i))}catch(t){}};$.v({id:"bm-A",style:"top: 10px; right: 75px;"}).v({id:"bm-j"}).v({id:"bm-z"}).h().M({alt:"Blue Marble Icon - Click to minimize/maximize",src:"https://raw.githubusercontent.com/SwingTheVine/Wplace-BlueMarble/main/dist/assets/Favicon.png",style:"cursor: pointer;"},(e,i)=>{i.addEventListener("click",()=>{t=!t;const n=document.querySelector("#bm-A"),o=document.querySelector("#bm-j"),r=document.querySelector("#bm-z"),s=document.querySelector("#bm-k"),a=document.querySelector("#bm-q"),m=document.querySelector("#bm-r"),l=document.querySelector("#bm-s"),c=document.querySelector("#bm-l"),u=document.querySelectorAll("#bm-k input");t||(n.style.width="auto",n.style.maxWidth="300px",n.style.minWidth="200px",n.style.padding="10px"),["#bm-A h1","#bm-f","#bm-A hr","#bm-c > *:not(#bm-k)","#bm-a","#bm-6",`#${e.i}`,"#bm-9"].forEach(e=>{document.querySelectorAll(e).forEach(e=>{e.style.display=t?"none":""})}),t?(s&&(s.style.display="none"),a&&(a.style.display="none"),m&&(m.style.display="none"),l&&(l.style.display="none"),c&&(c.style.display="none"),u.forEach(t=>{t.style.display="none"}),n.style.width="60px",n.style.height="76px",n.style.maxWidth="60px",n.style.minWidth="60px",n.style.padding="8px",i.style.marginLeft="3px",o.style.textAlign="center",o.style.margin="0",o.style.marginBottom="0",r&&(r.style.display="",r.style.marginBottom="0.25em")):(s&&(s.style.display="",s.style.flexDirection="",s.style.justifyContent="",s.style.alignItems="",s.style.gap="",s.style.textAlign="",s.style.margin=""),a&&(a.style.display=""),m&&(m.style.display="",m.style.marginTop=""),l&&(l.style.display="",l.style.marginTop=""),c&&(c.style.display="",c.style.marginTop=""),u.forEach(t=>{t.style.display=""}),i.style.marginLeft="",n.style.padding="10px",o.style.textAlign="",o.style.margin="",o.style.marginBottom="",r&&(r.style.marginBottom="0.5em"),n.style.width="",n.style.height=""),i.alt=t?"Blue Marble Icon - Minimized (Click to maximize)":"Blue Marble Icon - Maximized (Click to minimize)"})}).h().O(1,{textContent:w}).h().h().T().h().v({id:"bm-f"}).$({id:"bm-u",textContent:"Username:"}).h().$({id:"bm-p",textContent:"Droplets:"}).h().$({id:"bm-i",textContent:"Next level in..."}).h().h().T().h().v({id:"bm-c"}).v({id:"bm-k"}).k({id:"bm-q",className:"bm-D",style:"margin-top: 0;",innerHTML:'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 4 6"><circle cx="2" cy="2" r="2"></circle><path d="M2 6 L3.7 3 L0.3 3 Z"></path><circle cx="2" cy="2" r="0.7" fill="white"></circle></svg></svg>'},(t,e)=>{e.onclick=()=>{const e=t.t?.Ut;e?.[0]?(t.B("bm-v",e?.[0]||""),t.B("bm-w",e?.[1]||""),t.B("bm-x",e?.[2]||""),t.B("bm-y",e?.[3]||""),i()):t.P("Coordinates are malformed! Did you try clicking on the canvas first?")}}).h().I({type:"number",id:"bm-v",placeholder:"Tl X",min:0,max:2047,step:1,required:!0,value:e.Ht??""},(t,e)=>{e.addEventListener("paste",t=>{let e=(t.clipboardData||window.clipboardData).getData("text").split(" ").filter(t=>t).map(Number).filter(t=>!isNaN(t));if(4!==e.length)return;let i=(n=document,coords=[],coords.push(n.querySelector("#bm-v")),coords.push(n.querySelector("#bm-w")),coords.push(n.querySelector("#bm-x")),coords.push(n.querySelector("#bm-y")),coords);var n;for(let t=0;t<i.length;t++)i[t].value=e[t];t.preventDefault()});const n=()=>i();e.addEventListener("input",n),e.addEventListener("change",n)}).h().I({type:"number",id:"bm-w",placeholder:"Tl Y",min:0,max:2047,step:1,required:!0,value:e.Yt??""},(t,e)=>{const n=()=>i();e.addEventListener("input",n),e.addEventListener("change",n)}).h().I({type:"number",id:"bm-x",placeholder:"Px X",min:0,max:2047,step:1,required:!0,value:e.px??""},(t,e)=>{const n=()=>i();e.addEventListener("input",n),e.addEventListener("change",n)}).h().I({type:"number",id:"bm-y",placeholder:"Px Y",min:0,max:2047,step:1,required:!0,value:e.zt??""},(t,e)=>{const n=()=>i();e.addEventListener("input",n),e.addEventListener("change",n)}).h().h().v({id:"bm-9",style:"max-height: 140px; overflow: auto; border: 1px solid rgba(255,255,255,0.1); padding: 4px; border-radius: 4px; display: none;"}).v({style:"display: flex; gap: 6px; margin-bottom: 6px;"}).k({id:"bm-3",textContent:"Enable All"},(t,e)=>{e.onclick=()=>{const e=S.rt[0];e?.X&&(Object.values(e.X).forEach(t=>t.enabled=!0),buildColorFilterList(),t._("Enabled all colors"))}}).h().k({id:"bm-0",textContent:"Disable All"},(t,e)=>{e.onclick=()=>{const e=S.rt[0];e?.X&&(Object.values(e.X).forEach(t=>t.enabled=!1),buildColorFilterList(),t._("Disabled all colors"))}}).h().h().v({id:"bm-g"}).h().h().L({id:"bm-a",textContent:"Upload Template",accept:"image/png, image/jpeg, image/webp, image/bmp, image/gif"}).h().v({id:"bm-4"}).k({id:"bm-s",textContent:"Enable"},(t,e)=>{e.onclick=()=>{t.t?.At?.Rt(!0),t._("Enabled templates!")}}).h().k({id:"bm-r",textContent:"Create"},(t,e)=>{e.onclick=()=>{const e=document.querySelector("#bm-a"),i=document.querySelector("#bm-v");if(!i.checkValidity())return i.reportValidity(),void t.P("Coordinates are malformed! Did you try clicking on the canvas first?");const n=document.querySelector("#bm-w");if(!n.checkValidity())return n.reportValidity(),void t.P("Coordinates are malformed! Did you try clicking on the canvas first?");const o=document.querySelector("#bm-x");if(!o.checkValidity())return o.reportValidity(),void t.P("Coordinates are malformed! Did you try clicking on the canvas first?");const r=document.querySelector("#bm-y");if(!r.checkValidity())return r.reportValidity(),void t.P("Coordinates are malformed! Did you try clicking on the canvas first?");e?.files[0]?(S.Bt(e.files[0],e.files[0]?.name.replace(/\.[^/.]+$/,""),[Number(i.value),Number(n.value),Number(o.value),Number(r.value)]),t._("Drew to canvas!")):t.P("No file selected!")}}).h().k({id:"bm-l",textContent:"Disable"},(t,e)=>{e.onclick=()=>{t.t?.At?.Rt(!1),t._("Disabled templates!")}}).h().h().G({id:$.i,placeholder:`Status: Sleeping...\nVersion: ${y}`,readOnly:!0}).h().v({id:"bm-6"}).v().k({id:"bm-m",className:"bm-D",innerHTML:"🎨",title:"Template Color Converter"},(t,e)=>{e.addEventListener("click",()=>{window.open("https://pepoafonso.github.io/color_converter_wplace/","_blank","noopener noreferrer")})}).h().k({id:"bm-n",className:"bm-D",innerHTML:"🌐",title:"Official Blue Marble Website"},(t,e)=>{e.addEventListener("click",()=>{window.open("https://bluemarble.lol/","_blank","noopener noreferrer")})}).h().h().S({textContent:"Made by SwingTheVine",style:"margin-top: auto;"}).h().h().h().p(document.body),window.buildColorFilterList=function(){const t=document.querySelector("#bm-g"),e=S.rt?.[0];if(!t||!e?.X)return void(t&&(t.innerHTML="<small>No template colors to display.</small>"));t.innerHTML="";const i=Object.entries(e.X).sort((t,e)=>e[1].count-t[1].count);for(const[e,n]of i){let i=document.createElement("div");i.style.display="flex",i.style.alignItems="center",i.style.gap="8px",i.style.margin="4px 0";let o=document.createElement("div");o.style.width="14px",o.style.height="14px",o.style.border="1px solid rgba(255,255,255,0.5)";let r=document.createElement("span");r.style.fontSize="12px";let s=`${n.count.toLocaleString()}`;if("other"===e)o.style.background="#888",s=`Other • ${s}`;else if("#deface"===e)o.style.background="#deface",s=`Transparent • ${s}`;else{const[t,i,n]=e.split(",").map(Number);o.style.background=`rgb(${t},${i},${n})`;try{const o=S.rt?.[0]?.K?.get(e);if(o&&"number"==typeof o.id){const e=o?.name||`rgb(${t},${i},${n})`,r=o.premium?"★ ":"";s=`#${o.id} ${r}${e} • ${s}`}}catch(t){}}r.textContent=s;const a=document.createElement("input");a.type="checkbox",a.checked=!!n.enabled,a.addEventListener("change",()=>{n.enabled=a.checked,$._(`${a.checked?"Enabled":"Disabled"} ${e}`);try{const t=S.rt?.[0],e=t?.H;t&&e&&S.nt?.templates?.[e]&&(S.nt.templates[e].palette=t.X,GM.setValue("bmTemplates",JSON.stringify(S.nt)))}catch(t){}}),i.appendChild(a),i.appendChild(o),i.appendChild(r),t.appendChild(i)}},window.addEventListener("message",t=>{if("bm-b"===t?.data?.st)try{buildColorFilterList()}catch(t){}}),setTimeout(()=>{try{if(S.rt?.length>0){const t=document.querySelector("#bm-9");t&&(t.style.display=""),buildColorFilterList()}}catch(t){}},0)}(),$.W("#bm-A","#bm-z"),M.Xt($),new MutationObserver((t,e)=>{const i=document.querySelector("#color-1");if(!i)return;let n=document.querySelector("#bm-t");if(!n){n=document.createElement("button"),n.id="bm-t",n.textContent="Move ↑",n.className="btn btn-soft",n.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=i.parentNode.parentNode.parentNode.parentNode.querySelector("h2");t.parentNode?.appendChild(n)}}).observe(document.body,{childList:!0,subtree:!0}),function(...t){(0,console.log)(...t)}(`%c${w}%c (${y}) userscript has loaded!`,"color: cornflowerblue;","")})();