Back to Home
Gistify Snippet
poster-lagu-3d.jsjavascript
763 lines| 1 | 'use strict'; |
| 2 | /* |
| 3 | * poster-lagu-3d.js — Pembuat Poster Lagu Tiga Dimensi dalam SATU file. |
| 4 | * 4 kartu pemutar musik 3D di sekeliling fotomu, karakter menimpa kartu, |
| 5 | * cover otomatis dari Deezer/iTunes. |
| 6 | * |
| 7 | * Pasang: npm i @napi-rs/canvas (wajib, Node 18+) |
| 8 | * npm i @gradio/client (opsional, buat efek karakter menimpa kartu lewat BRIA RMBG) |
| 9 | * Font: taruh Poppins-Bold.ttf, Poppins-Medium.ttf, Poppins-Regular.ttf di folder ./fonts (opsional, |
| 10 | * tanpa itu dipakai font sistem). |
| 11 | * |
| 12 | * Lewat terminal: |
| 13 | * node poster-lagu-3d.js foto.jpg "blank ruangBria taylor swift" "raimu laode iqro" "about you the 1975" "good life g-eazy kehlani" |
| 14 | * opsi: --nocut (tanpa efek karakter menimpa kartu) --out hasil.png |
| 15 | * |
| 16 | * Lewat kode: |
| 17 | * const { buatPosterLagu } = require('./poster-lagu-3d'); |
| 18 | * const png = await buatPosterLagu({ photo: fs.readFileSync('foto.jpg'), songs: ['blank ruangBria taylor swift', ...] }); |
| 19 | * |
| 20 | * Catatan: BRIA RMBG berlisensi non-komersial. Tidak ada API key / token yang tertanam di file ini. |
| 21 | * Env opsional: POSTER_COVER_ORDER (deezer,itunes), POSTER_ITUNES_COUNTRIES (ID,US), BRIA_SPACE, BATAS_WAKTU_BRIA, HF_TOKEN (diawali hf_). |
| 22 | */ |
| 23 | const fs = require('fs'); |
| 24 | const path = require('path'); |
| 25 | const { createCanvas, loadImage, GlobalFonts, ImageData } = require('@napi-rs/canvas'); |
| 26 | |
| 27 | /* ================================================================== */ |
| 28 | /* 1. CARI LAGU + COVER (Deezer / iTunes) */ |
| 29 | /* ================================================================== */ |
| 30 | const BATAS_WAKTU_NET = 15000; |
| 31 | const AGEN_PENGGUNA = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36'; |
| 32 | const SKOR_PAS = 0.6; // skor "cocok" |
| 33 | const SKOR_MINIMAL = 0.45; // di bawah ini dianggap salah lagu |
| 34 | const URUTAN_SUMBER = String(process.env.POSTER_COVER_ORDER || 'deezer,itunes').split(',').map((x) => x.trim().toLowerCase()).filter(Boolean); |
| 35 | const DAFTAR_NEGARA = String(process.env.POSTER_ITUNES_COUNTRIES || 'ID,US').split(',').map((x) => x.trim().toUpperCase()).filter(Boolean); |
| 36 | const tidurSebentar = (batasMs) => new Promise((r) => setTimeout(r, batasMs)); |
| 37 | |
| 38 | /** "a\nb | c; d" -> ['a','b','c','d'] (maks 4). Satu baris saja -> pisah dengan koma. */ |
| 39 | function uraikanDaftarLagu(text) { |
| 40 | const t = String(text || '').trim(); |
| 41 | const potonganTeks = /[\n|;]/.test(t) ? t.split(/[\n|;]+/) : t.split(/[,,]+/); |
| 42 | const semuaJudul = potonganTeks.map((s) => s.replace(/^\s*\d{1,2}\s*[.)]\s*/, '').trim()).filter(Boolean); |
| 43 | return { songs: semuaJudul.slice(0, 4), extra: Math.max(0, semuaJudul.length - 4) }; |
| 44 | } |
| 45 | |
| 46 | const normalkanTeks = (s) => String(s || '').toLowerCase().normalize('NFD').replace(/[\u0300-\u036f]/g, '').replace(/&/g, ' and ').replace(/[^a-z0-9]+/g, ' ').trim(); |
| 47 | const pecahKata = (s) => normalkanTeks(s).split(' ').filter(Boolean); |
| 48 | function jarakSuntingSatu(a, b) { |
| 49 | if (Math.abs(a.length - b.length) > 1) return false; |
| 50 | let i = 0, j = 0, dataPiksel = 0; |
| 51 | while (i < a.length && j < b.length) { |
| 52 | if (a[i] === b[j]) { i++; j++; continue; } |
| 53 | if (++dataPiksel > 1) return false; |
| 54 | if (a.length > b.length) i++; else if (a.length < b.length) j++; else { i++; j++; } |
| 55 | } |
| 56 | return dataPiksel + (a.length - i) + (b.length - j) <= 1; |
| 57 | } |
| 58 | function kataMirip(a, b) { |
| 59 | if (a === b) return true; |
| 60 | if (a.length >= 3 && b.length >= 3 && (a.startsWith(b) || b.startsWith(a))) return true; |
| 61 | return a.length >= 4 && b.length >= 4 && jarakSuntingSatu(a, b); |
| 62 | } |
| 63 | const POLA_VERSI_LAIN = /karaoke|instrumental|tribute|made famous|lullaby|piano version|8d|slowed|sped up|nightcore/i; |
| 64 | /** berapa kata input yang muncul di judul+artis hasil (urutan bebas, salah ketik kecil dimaafkan) */ |
| 65 | function hitungKecocokan(query, title, artist, album = '') { |
| 66 | const q = pecahKata(query), kolamKata = pecahKata(`${title} ${artist}`); |
| 67 | if (!q.length) return 0; |
| 68 | const sudahTerpakai = new Set(); let jumlahCocok = 0; |
| 69 | for (const t of q) { |
| 70 | const k = kolamKata.findIndex((p, i) => !sudahTerpakai.has(i) && kataMirip(t, p)); |
| 71 | if (k >= 0) { sudahTerpakai.add(k); jumlahCocok++; } |
| 72 | } |
| 73 | let s = jumlahCocok / q.length; |
| 74 | if (POLA_VERSI_LAIN.test(`${title} ${album}`) && !POLA_VERSI_LAIN.test(query)) s -= 0.2; |
| 75 | return Math.max(0, s); |
| 76 | } |
| 77 | |
| 78 | async function ambilJson(alamatHasil) { |
| 79 | const r = await fetch(alamatHasil, { signal: AbortSignal.timeout(BATAS_WAKTU_NET), headers: { 'User-Agent': AGEN_PENGGUNA } }); |
| 80 | if (!r.ok) throw new Error('HTTP ' + r.status); |
| 81 | return r.json(); |
| 82 | } |
| 83 | const cekBerkasGambar = (b) => b.length > 1000 && ((b[0] === 0xff && b[1] === 0xd8) || b.readUInt32BE(0) === 0x89504e47); |
| 84 | async function unduhGambar(daftarUrl) { |
| 85 | for (const u of daftarUrl.filter(Boolean)) { |
| 86 | try { |
| 87 | const r = await fetch(u, { signal: AbortSignal.timeout(BATAS_WAKTU_NET), headers: { 'User-Agent': AGEN_PENGGUNA } }); |
| 88 | if (!r.ok) continue; |
| 89 | const b = Buffer.from(await r.arrayBuffer()); |
| 90 | if (cekBerkasGambar(b)) return b; |
| 91 | } catch { /* coba URL berikutnya */ } |
| 92 | } |
| 93 | return null; |
| 94 | } |
| 95 | |
| 96 | // iTunes dibatasi ~20 permintaan/menit: antre dengan jeda minimal |
| 97 | let ekorAntreItunes = Promise.resolve(); |
| 98 | function ambilSlotItunes() { |
| 99 | const run = ekorAntreItunes.then(() => tidurSebentar(3200)); |
| 100 | ekorAntreItunes = run.catch(() => {}); |
| 101 | return run; |
| 102 | } |
| 103 | async function cariDiDeezer(q) { |
| 104 | const j = await ambilJson(`https://api.deezer.com/search?${new URLSearchParams({ q, limit: '6' })}`); |
| 105 | if (j.error) throw new Error('Deezer: ' + (j.error.message || j.error.type)); |
| 106 | return (j.data || []).map((x) => ({ |
| 107 | title: x.title, artist: x.artist && x.artist.name, album: x.album && x.album.title, duration: x.duration || 0, |
| 108 | covers: [x.album && x.album.cover_xl, x.album && x.album.cover_big, x.album && x.album.cover_medium], src: 'Deezer', |
| 109 | })); |
| 110 | } |
| 111 | async function cariDiItunes(q, negara) { |
| 112 | await ambilSlotItunes(); |
| 113 | const j = await ambilJson(`https://itunes.apple.com/search?${new URLSearchParams({ term: q, entity: 'dataLagu', limit: '6', negara })}`); |
| 114 | return (j.results || []).map((x) => ({ |
| 115 | title: x.trackName, artist: x.artistName, album: x.collectionName, duration: x.trackTimeMillis ? Math.round(x.trackTimeMillis / 1000) : 0, |
| 116 | covers: x.artworkUrl100 ? [x.artworkUrl100.replace(/\d+x\d+bb/, '1200x1200bb'), x.artworkUrl100.replace(/\d+x\d+bb/, '600x600bb')] : [], src: 'iTunes ' + negara, |
| 117 | })); |
| 118 | } |
| 119 | const ambilTerbaik = (q, hasilCari) => hasilCari.map((it, i) => ({ ...it, score: hitungKecocokan(q, it.title, it.artist, it.album) - i * 0.001 })).sort((a, b) => b.score - a.score)[0] || null; |
| 120 | |
| 121 | /** @returns {Promise<{title,artist,duration,cover:Buffer|null,source,found,hitungKecocokan}>} — gagal semua -> cover null (kartu pakai gradasi) */ |
| 122 | async function temukanLagu(query) { |
| 123 | let cadanganTerbaik = null; |
| 124 | const daftarUpaya = []; |
| 125 | for (const s of URUTAN_SUMBER) { |
| 126 | if (s === 'deezer') daftarUpaya.push(() => cariDiDeezer(query)); |
| 127 | else if (s === 'itunes') for (const c of DAFTAR_NEGARA) daftarUpaya.push(() => cariDiItunes(query, c)); |
| 128 | } |
| 129 | for (const run of daftarUpaya) { |
| 130 | let hasilCari; |
| 131 | try { hasilCari = await run(); } catch (e) { console.error('[poster-lagu] cari lagu gagal:', e.message); continue; } |
| 132 | const b = ambilTerbaik(query, hasilCari); |
| 133 | if (!b || b.score < SKOR_MINIMAL) continue; |
| 134 | const cover = await unduhGambar(b.covers); |
| 135 | if (b.score >= SKOR_PAS && cover) return { title: b.title, artist: b.artist || '', duration: b.duration, cover, source: b.src, found: true, score: +b.score.toFixed(2) }; |
| 136 | if (!cadanganTerbaik || b.score > cadanganTerbaik.score) cadanganTerbaik = { ...b, cover }; |
| 137 | } |
| 138 | if (cadanganTerbaik) return { title: cadanganTerbaik.title, artist: cadanganTerbaik.artist || '', duration: cadanganTerbaik.duration, cover: cadanganTerbaik.cover, source: cadanganTerbaik.src, found: true, score: +cadanganTerbaik.score.toFixed(2) }; |
| 139 | return { title: query, artist: '', duration: 0, cover: null, source: '-', found: false, score: 0 }; |
| 140 | } |
| 141 | |
| 142 | /* ================================================================== */ |
| 143 | /* 2. HAPUS BACKGROUND (BRIA RMBG 2.0, cadangan 1.4) */ |
| 144 | /* ================================================================== */ |
| 145 | const BRIA_PILIHAN = (process.env.BRIA_SPACE || '').trim(); |
| 146 | const RUANG_BRIA = BRIA_PILIHAN ? [BRIA_PILIHAN] : ['briaai/BRIA-RMBG-2.0', 'briaai/BRIA-RMBG-1.4']; |
| 147 | const jalurApiBria = (s) => (process.env.BRIA_API || (/2\.0/.test(s) ? '/image' : '/run')).trim(); |
| 148 | const BATAS_WAKTU_BRIA = Number(process.env.BRIA_TIMEOUT) || 90000; |
| 149 | const UKURAN_MAKS_MASUK = 10 * 1024 * 1024, UKURAN_MAKS_KELUAR = 20 * 1024 * 1024; |
| 150 | const TANDA_PNG = Buffer.from([0x89, 0x50, 0x4e, 0x47]); |
| 151 | const HOST_BRIA = ['hf.space', 'huggingface.co', 'hf.co']; |
| 152 | const hostBoleh = (h) => HOST_BRIA.some((x) => h === x || h.endsWith('.' + x)); |
| 153 | let ruangBriaTerpakai = ''; |
| 154 | const labelBria = () => (ruangBriaTerpakai ? 'BRIA RMBG ' + (ruangBriaTerpakai.match(/(\d+\.\d+)\s*$/) || [, '?'])[1] : 'BRIA RMBG'); |
| 155 | |
| 156 | function beriBatasWaktu(janjiProses, batasMs, namaProses) { |
| 157 | let t; |
| 158 | return Promise.race([janjiProses, new Promise((_, rej) => { t = setTimeout(() => rej(new Error(`${namaProses} kelamaan merespons (>${Math.round(batasMs / 1000)} dtk)`)), batasMs); })]).finally(() => clearTimeout(t)); |
| 159 | } |
| 160 | async function unduhDariBria(alamatHasil) { |
| 161 | let nilaiBerjalan = alamatHasil; |
| 162 | for (let jumlahLompat = 0; jumlahLompat <= 3; jumlahLompat++) { |
| 163 | let u; |
| 164 | try { u = new URL(nilaiBerjalan); } catch { throw new Error('alamat hasil BRIA tidak valid'); } |
| 165 | if (u.protocol !== 'https:' || !hostBoleh(u.hostname.toLowerCase())) throw new Error(`alamat hasil BRIA ditolak (${u.hostname})`); |
| 166 | const res = await fetch(u.href, { redirect: 'manual', signal: AbortSignal.timeout(45000) }); |
| 167 | if (res.status >= 300 && res.status < 400 && res.headers.get('location')) { nilaiBerjalan = new URL(res.headers.get('location'), u.href).href; continue; } |
| 168 | if (!res.ok) throw new Error(`unduh hasil BRIA gagal (HTTP ${res.status})`); |
| 169 | const penyanggaHasil = Buffer.from(await res.arrayBuffer()); |
| 170 | if (penyanggaHasil.length > UKURAN_MAKS_KELUAR) throw new Error('hasil BRIA terlalu besar'); |
| 171 | return penyanggaHasil; |
| 172 | } |
| 173 | throw new Error('terlalu banyak redirect dari server BRIA'); |
| 174 | } |
| 175 | /** @returns {Promise<Buffer>} PNG transparan */ |
| 176 | async function potongLatar(gambarMasukan, mime = 'image/jpeg') { |
| 177 | if (!Buffer.isBuffer(gambarMasukan) || !gambarMasukan.length) throw new Error('Input harus berupa gambar.'); |
| 178 | if (gambarMasukan.length > UKURAN_MAKS_MASUK) throw new Error('Gambar terlalu besar (maks 10 MB).'); |
| 179 | let modulGradio; |
| 180 | try { modulGradio = await import('@gradio/client'); } catch { throw new Error('modul "@gradio/client" belum terpasang (npm i @gradio/client)'); } |
| 181 | const Client = modulGradio.Client || (modulGradio.default && modulGradio.default.Client); |
| 182 | if (!Client) throw new Error('modul "@gradio/client" tidak punya Client (versi tidak cocok)'); |
| 183 | const opsiKlien = {}; |
| 184 | const tokenAkses = String(process.env.HF_TOKEN || '').trim(); |
| 185 | if (/^hf_/.test(tokenAkses)) opsiKlien.hf_token = tokenAkses; |
| 186 | let dataHasilBria, galatTerakhir; |
| 187 | for (const ruangBria of RUANG_BRIA) { |
| 188 | try { |
| 189 | dataHasilBria = await beriBatasWaktu((async () => { |
| 190 | const client = await Client.connect(ruangBria, opsiKlien); |
| 191 | const result = await client.predict(jalurApiBria(ruangBria), { image: new Blob([new Uint8Array(gambarMasukan)], { type: mime }) }); |
| 192 | const data = Array.isArray(result && result.data) ? result.data : []; |
| 193 | return data[1] && data[1].url ? data[1] : data.find((dataPiksel) => dataPiksel && dataPiksel.url && /\.png(\?|$)/i.test(dataPiksel.url)); |
| 194 | })(), BATAS_WAKTU_BRIA, 'BRIA'); |
| 195 | if (dataHasilBria && dataHasilBria.url) { ruangBriaTerpakai = ruangBria; break; } |
| 196 | galatTerakhir = new Error('BRIA tidak mengembalikan gambar transparan'); |
| 197 | } catch (e) { galatTerakhir = e; console.error(`[bria] ${ruangBria} gagal: ${String((e && e.message) || e).slice(0, 120)}`); } |
| 198 | } |
| 199 | if (!(dataHasilBria && dataHasilBria.url)) throw new Error(String((galatTerakhir && galatTerakhir.message) || galatTerakhir).slice(0, 200)); |
| 200 | const dataHasil = await unduhDariBria(dataHasilBria.url); |
| 201 | if (!dataHasil.subarray(0, 4).equals(TANDA_PNG)) throw new Error('hasil BRIA bukan gambar PNG'); |
| 202 | return dataHasil; |
| 203 | } |
| 204 | |
| 205 | /* ================================================================== */ |
| 206 | /* 3. RENDER POSTER */ |
| 207 | /* ================================================================== */ |
| 208 | const FOLDER_FONT = [path.join(__dirname, 'fonts'), '/usr/share/fonts/truetype/liberation', '/usr/share/fonts/truetype/dejavu']; |
| 209 | function daftarkanFontKeluarga(namaFont, daftarNamaFont) { |
| 210 | for (const n of daftarNamaFont) for (const dataPiksel of FOLDER_FONT) { |
| 211 | const f = path.join(dataPiksel, n); |
| 212 | if (fs.existsSync(f)) { try { GlobalFonts.registerFromPath(f, namaFont); return true; } catch { /* coba berikutnya */ } } |
| 213 | } |
| 214 | return false; |
| 215 | } |
| 216 | daftarkanFontKeluarga('PosTebal', ['Poppins-Bold.ttf', 'LiberationSans-Bold.ttf', 'DejaVuSans-Bold.ttf']); |
| 217 | daftarkanFontKeluarga('PosSedang', ['Poppins-Medium.ttf', 'LiberationSans-Regular.ttf', 'DejaVuSans.ttf']); |
| 218 | daftarkanFontKeluarga('PosBiasa', ['Poppins-Regular.ttf', 'LiberationSans-Regular.ttf', 'DejaVuSans.ttf']); |
| 219 | |
| 220 | /* Pose 4 kartu (kanvas 1080x1920): bidang 3D diputar (yaw/pitch/roll, derajat) lalu diproyeksikan ber-perspektif. |
| 221 | * front: true -> kartu digambar DI DEPAN karakter. Posisi ini acuan untuk foto uji; kalau ada karakter, posisi |
| 222 | * digeser/diskalakan otomatis mengikuti letak & tinggi karakter (autoFit). */ |
| 223 | const POSE_AWAL = [ |
| 224 | { cx: 274, cy: 494, yaw: -18, pitch: -4, roll: 4, scale: 0.82 }, // kiri atas |
| 225 | { cx: 842, cy: 434, yaw: 18, pitch: -4, roll: -3, scale: 0.84 }, // kanan atas (lebih tinggi) |
| 226 | { cx: 258, cy: 1216, yaw: -18, pitch: 5, roll: 3, scale: 0.82 }, // kiri bawah |
| 227 | { cx: 850, cy: 1241, yaw: 18, pitch: 5, roll: -4, scale: 0.84 } // kanan bawah (lebih turun) |
| 228 | ]; |
| 229 | const ACUAN_KARAKTER = { cx: 595, top: 260, h: 1390 }; // acuan letak karakter di foto uji |
| 230 | const PANJANG_FOKUS = 1700; |
| 231 | const KETEBALAN = 16; |
| 232 | |
| 233 | function pembangkitAcak(a) { |
| 234 | return function () { |
| 235 | a |= 0; a = (a + 0x6d2b79f5) | 0; |
| 236 | let t = Math.imul(a ^ (a >>> 15), 1 | a); |
| 237 | t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; |
| 238 | return ((t ^ (t >>> 14)) >>> 0) / 4294967296; |
| 239 | }; |
| 240 | } |
| 241 | const hashTeks = (s) => { let h = 2166136261; for (const c of String(s)) { h ^= c.charCodeAt(0); h = Math.imul(h, 16777619); } return h >>> 0; }; |
| 242 | const formatWaktu = (sec) => `${Math.floor(sec / 60)}:${String(Math.floor(sec % 60)).padStart(2, '0')}`; |
| 243 | |
| 244 | function jalurKotakBulat(g, x, y, w, h, r) { |
| 245 | g.beginPath(); |
| 246 | g.moveTo(x + r, y); |
| 247 | g.arcTo(x + w, y, x + w, y + h, r); |
| 248 | g.arcTo(x + w, y + h, x, y + h, r); |
| 249 | g.arcTo(x, y + h, x, y, r); |
| 250 | g.arcTo(x, y, x + w, y, r); |
| 251 | g.closePath(); |
| 252 | } |
| 253 | function potongTeksPas(g, text, maxW) { |
| 254 | text = String(text || ''); |
| 255 | if (g.measureText(text).width <= maxW) return text; |
| 256 | while (text.length > 1 && g.measureText(text + '…').width > maxW) text = text.slice(0, -1); |
| 257 | return text.trimEnd() + '…'; |
| 258 | } |
| 259 | function gambarPasPenuh(g, gambarMasukan, x, y, w, h) { |
| 260 | const s = Math.max(w / gambarMasukan.width, h / gambarMasukan.height); |
| 261 | const sw = w / s, sh = h / s; |
| 262 | g.drawImage(gambarMasukan, (gambarMasukan.width - sw) / 2, (gambarMasukan.height - sh) / 2, sw, sh, x, y, w, h); |
| 263 | } |
| 264 | async function muatGambar(titikAsal) { |
| 265 | if (!titikAsal) return null; |
| 266 | try { return await loadImage(titikAsal); } catch { return null; } |
| 267 | } |
| 268 | |
| 269 | function sampulPengganti(title, artist) { |
| 270 | const pengacak = pembangkitAcak(hashTeks(title + artist)); |
| 271 | const ronaSatu = Math.floor(pengacak() * 360), ronaDua = (ronaSatu + 40 + Math.floor(pengacak() * 120)) % 360; |
| 272 | const c = createCanvas(600, 600), g = c.getContext('2d'); |
| 273 | const gr = g.createLinearGradient(0, 0, 600, 600); |
| 274 | gr.addColorStop(0, `hsl(${ronaSatu},70%,48%)`); gr.addColorStop(1, `hsl(${ronaDua},75%,22%)`); |
| 275 | g.fillStyle = gr; g.fillRect(0, 0, 600, 600); |
| 276 | for (let i = 0; i < 5; i++) { |
| 277 | g.beginPath(); |
| 278 | g.arc(pengacak() * 600, pengacak() * 600, 70 + pengacak() * 190, 0, Math.PI * 2); |
| 279 | g.fillStyle = `hsla(${(ronaSatu + pengacak() * 90) % 360},80%,65%,${0.10 + pengacak() * 0.14})`; |
| 280 | g.fill(); |
| 281 | } |
| 282 | g.fillStyle = 'rgba(255,255,255,0.92)'; |
| 283 | g.font = '700 64px PosTebal'; g.textBaseline = 'alphabetic'; |
| 284 | const words = String(title).split(' '); |
| 285 | let line = ''; const lines = []; |
| 286 | for (const w of words) { const t = line ? line + ' ' + w : w; if (g.measureText(t).width > 500 && line) { lines.push(line); line = w; } else line = t; } |
| 287 | lines.push(line); |
| 288 | const start = 540 - (lines.length - 1) * 70; |
| 289 | lines.slice(-3).forEach((l, i) => g.fillText(l, 50, start + i * 70)); |
| 290 | return c; |
| 291 | } |
| 292 | |
| 293 | function ikonHati(g, cx, cy, s, a = 0.85) { |
| 294 | const t = s / 2; |
| 295 | g.beginPath(); |
| 296 | g.moveTo(cx, cy + t * 0.95); |
| 297 | g.bezierCurveTo(cx - t * 2.1, cy - t * 0.1, cx - t * 1.0, cy - t * 1.55, cx, cy - t * 0.45); |
| 298 | g.bezierCurveTo(cx + t * 1.0, cy - t * 1.55, cx + t * 2.1, cy - t * 0.1, cx, cy + t * 0.95); |
| 299 | g.closePath(); |
| 300 | g.lineWidth = 2.6; g.lineJoin = 'round'; g.strokeStyle = `rgba(255,255,255,${a})`; g.stroke(); |
| 301 | } |
| 302 | function ikonSegitiga(g, x, y, w, h, dir) { |
| 303 | g.beginPath(); |
| 304 | if (dir > 0) { g.moveTo(x, y); g.lineTo(x + w, y + h / 2); g.lineTo(x, y + h); } |
| 305 | else { g.moveTo(x + w, y); g.lineTo(x, y + h / 2); g.lineTo(x + w, y + h); } |
| 306 | g.closePath(); g.lineJoin = 'round'; g.lineWidth = 4; g.fill(); g.stroke(); |
| 307 | } |
| 308 | function ikonPengeras(g, x, y, a = 0.75) { |
| 309 | g.fillStyle = `rgba(255,255,255,${a})`; g.strokeStyle = `rgba(255,255,255,${a})`; |
| 310 | g.beginPath(); g.moveTo(x, y - 5); g.lineTo(x + 6, y - 5); g.lineTo(x + 13, y - 11); g.lineTo(x + 13, y + 11); g.lineTo(x + 6, y + 5); g.lineTo(x, y + 5); g.closePath(); g.fill(); |
| 311 | g.lineWidth = 2.4; g.lineCap = 'round'; |
| 312 | g.beginPath(); g.arc(x + 14, y, 7, -0.9, 0.9); g.stroke(); |
| 313 | g.beginPath(); g.arc(x + 14, y, 13, -0.9, 0.9); g.stroke(); |
| 314 | } |
| 315 | |
| 316 | /* ---- 1 kartu (datar) ---- */ |
| 317 | const LEBAR_KARTU = 420, TINGGI_KARTU = 700, MARGIN_KARTU = 4, RADIUS_SUDUT = 46; |
| 318 | function buatKartuLagu(dataLagu, cover, pengacak, skalaRender = 2) { |
| 319 | const c = createCanvas((LEBAR_KARTU + MARGIN_KARTU * 2) * skalaRender, (TINGGI_KARTU + MARGIN_KARTU * 2) * skalaRender), g = c.getContext('2d'); |
| 320 | g.scale(skalaRender, skalaRender); g.translate(MARGIN_KARTU, MARGIN_KARTU); |
| 321 | |
| 322 | const gradasiBadan = g.createLinearGradient(0, 0, 0, TINGGI_KARTU); |
| 323 | gradasiBadan.addColorStop(0, 'rgba(66,68,77,0.98)'); gradasiBadan.addColorStop(1, 'rgba(26,27,32,0.98)'); |
| 324 | jalurKotakBulat(g, 1.5, 1.5, LEBAR_KARTU - 3, TINGGI_KARTU - 3, RADIUS_SUDUT); g.fillStyle = gradasiBadan; g.fill(); |
| 325 | |
| 326 | g.save(); g.shadowColor = 'rgba(0,0,0,0.5)'; g.shadowBlur = 18; g.shadowOffsetY = 6; |
| 327 | jalurKotakBulat(g, 30, 30, 360, 360, 30); g.fillStyle = '#111'; g.fill(); g.restore(); |
| 328 | g.save(); jalurKotakBulat(g, 30, 30, 360, 360, 30); g.clip(); gambarPasPenuh(g, cover, 30, 30, 360, 360); |
| 329 | const gradasiSampul = g.createLinearGradient(30, 30, 390, 390); |
| 330 | gradasiSampul.addColorStop(0, 'rgba(255,255,255,0.12)'); gradasiSampul.addColorStop(0.4, 'rgba(255,255,255,0)'); |
| 331 | g.fillStyle = gradasiSampul; g.fillRect(30, 30, 360, 360); g.restore(); |
| 332 | |
| 333 | g.fillStyle = '#fff'; g.font = '41px PosTebal'; g.textBaseline = 'alphabetic'; |
| 334 | g.fillText(potongTeksPas(g, dataLagu.title, 308), 30, 462); |
| 335 | g.fillStyle = 'rgba(255,255,255,0.68)'; g.font = '27px PosBiasa'; |
| 336 | g.fillText(potongTeksPas(g, dataLagu.artist, 308), 30, 500); |
| 337 | ikonHati(g, 372, 456, 26); |
| 338 | |
| 339 | const durasiLagu = dataLagu.duration || Math.floor(150 + pengacak() * 110); |
| 340 | const p = dataLagu.progress != null ? dataLagu.progress : 0.22 + pengacak() * 0.5; |
| 341 | const px0 = 30, px1 = 390, py = 556; |
| 342 | g.lineCap = 'round'; g.lineWidth = 5; |
| 343 | g.strokeStyle = 'rgba(255,255,255,0.25)'; g.beginPath(); g.moveTo(px0, py); g.lineTo(px1, py); g.stroke(); |
| 344 | const posisiProgres = px0 + (px1 - px0) * p; |
| 345 | g.strokeStyle = 'rgba(255,255,255,0.92)'; g.beginPath(); g.moveTo(px0, py); g.lineTo(posisiProgres, py); g.stroke(); |
| 346 | g.fillStyle = '#fff'; g.beginPath(); g.arc(posisiProgres, py, 8, 0, Math.PI * 2); g.fill(); |
| 347 | g.fillStyle = 'rgba(255,255,255,0.6)'; g.font = '18px PosBiasa'; |
| 348 | g.fillText(formatWaktu(durasiLagu * p), 30, 592); |
| 349 | g.textAlign = 'right'; g.fillText('-' + formatWaktu(durasiLagu * (1 - p)), 390, 592); g.textAlign = 'left'; |
| 350 | |
| 351 | g.fillStyle = '#fff'; g.strokeStyle = '#fff'; |
| 352 | ikonSegitiga(g, 112, 612, 26, 30, -1); ikonSegitiga(g, 134, 612, 26, 30, -1); |
| 353 | g.lineWidth = 0; jalurKotakBulat(g, 192, 610, 12, 34, 4); g.fill(); jalurKotakBulat(g, 216, 610, 12, 34, 4); g.fill(); |
| 354 | ikonSegitiga(g, 262, 612, 26, 30, 1); ikonSegitiga(g, 284, 612, 26, 30, 1); |
| 355 | |
| 356 | const posisiVolume = 674, levelVolume = 0.3 + pengacak() * 0.5; |
| 357 | ikonPengeras(g, 30, posisiVolume, 0.6); |
| 358 | g.lineWidth = 4; g.lineCap = 'round'; |
| 359 | g.strokeStyle = 'rgba(255,255,255,0.25)'; g.beginPath(); g.moveTo(74, posisiVolume); g.lineTo(346, posisiVolume); g.stroke(); |
| 360 | g.strokeStyle = 'rgba(255,255,255,0.8)'; g.beginPath(); g.moveTo(74, posisiVolume); g.lineTo(74 + 272 * levelVolume, posisiVolume); g.stroke(); |
| 361 | ikonPengeras(g, 362, posisiVolume, 0.6); |
| 362 | |
| 363 | g.save(); jalurKotakBulat(g, 1.5, 1.5, LEBAR_KARTU - 3, TINGGI_KARTU - 3, RADIUS_SUDUT); g.clip(); |
| 364 | const gradasiKilap = g.createLinearGradient(0, 0, LEBAR_KARTU, TINGGI_KARTU * 0.55); |
| 365 | gradasiKilap.addColorStop(0, 'rgba(255,255,255,0.16)'); gradasiKilap.addColorStop(0.45, 'rgba(255,255,255,0.03)'); gradasiKilap.addColorStop(1, 'rgba(255,255,255,0)'); |
| 366 | g.fillStyle = gradasiKilap; g.fillRect(0, 0, LEBAR_KARTU, TINGGI_KARTU); |
| 367 | g.fillStyle = 'rgba(255,255,255,0.05)'; |
| 368 | g.beginPath(); g.moveTo(LEBAR_KARTU * 0.55, 0); g.lineTo(LEBAR_KARTU * 0.8, 0); g.lineTo(LEBAR_KARTU * 0.25, TINGGI_KARTU); g.lineTo(0, TINGGI_KARTU); g.closePath(); g.fill(); |
| 369 | g.restore(); |
| 370 | const gradasiTepi = g.createLinearGradient(0, 0, LEBAR_KARTU, TINGGI_KARTU); |
| 371 | gradasiTepi.addColorStop(0, 'rgba(255,255,255,0.45)'); gradasiTepi.addColorStop(0.5, 'rgba(255,255,255,0.08)'); gradasiTepi.addColorStop(1, 'rgba(255,255,255,0.25)'); |
| 372 | jalurKotakBulat(g, 1.5, 1.5, LEBAR_KARTU - 3, TINGGI_KARTU - 3, RADIUS_SUDUT); g.lineWidth = 2.5; g.strokeStyle = gradasiTepi; g.stroke(); |
| 373 | return c; |
| 374 | } |
| 375 | |
| 376 | /* ---- proyeksi 3D ---- */ |
| 377 | const keRadian = (dataPiksel) => dataPiksel * Math.PI / 180; |
| 378 | function buatProyeksi(poseKartu, W, H) { |
| 379 | const cr = Math.cos(keRadian(poseKartu.roll)), sr = Math.sin(keRadian(poseKartu.roll)); |
| 380 | const cp = Math.cos(keRadian(poseKartu.pitch)), sp = Math.sin(keRadian(poseKartu.pitch)); |
| 381 | const cy = Math.cos(keRadian(poseKartu.yaw)), sy = Math.sin(keRadian(poseKartu.yaw)); |
| 382 | const rot = (x, y, z) => { |
| 383 | let t = x * cr - y * sr; y = x * sr + y * cr; x = t; |
| 384 | t = y * cp - z * sp; z = y * sp + z * cp; y = t; |
| 385 | t = x * cy + z * sy; z = -x * sy + z * cy; x = t; |
| 386 | return [x, y, z]; |
| 387 | }; |
| 388 | const world = (u, v, w) => { |
| 389 | const r = rot(u * poseKartu.scale, v * poseKartu.scale, w * poseKartu.scale); |
| 390 | return [r[0] + (poseKartu.cx - W / 2), r[1] + (poseKartu.cy - H / 2), r[2] + PANJANG_FOKUS]; |
| 391 | }; |
| 392 | const screen = (proyeksiKartu) => [W / 2 + PANJANG_FOKUS * proyeksiKartu[0] / proyeksiKartu[2], H / 2 + PANJANG_FOKUS * proyeksiKartu[1] / proyeksiKartu[2]]; |
| 393 | return { rot, world, screen, pt: (u, v, w = 0) => screen(world(u, v, w)) }; |
| 394 | } |
| 395 | function hitungHomografi(titikAsal, titikSasaran) { |
| 396 | const A = [], b = []; |
| 397 | for (let i = 0; i < 4; i++) { |
| 398 | const [x, y] = titikAsal[i], [u, v] = titikSasaran[i]; |
| 399 | A.push([x, y, 1, 0, 0, 0, -u * x, -u * y]); b.push(u); |
| 400 | A.push([0, 0, 0, x, y, 1, -v * x, -v * y]); b.push(v); |
| 401 | } |
| 402 | const n = 8; |
| 403 | for (let i = 0; i < n; i++) { |
| 404 | let m = i; for (let r = i + 1; r < n; r++) if (Math.abs(A[r][i]) > Math.abs(A[m][i])) m = r; |
| 405 | [A[i], A[m]] = [A[m], A[i]]; [b[i], b[m]] = [b[m], b[i]]; |
| 406 | for (let r = i + 1; r < n; r++) { const f = A[r][i] / A[i][i]; for (let c = i; c < n; c++) A[r][c] -= f * A[i][c]; b[r] -= f * b[i]; } |
| 407 | } |
| 408 | const h = new Array(n); |
| 409 | for (let i = n - 1; i >= 0; i--) { let s = b[i]; for (let c = i + 1; c < n; c++) s -= A[i][c] * h[c]; h[i] = s / A[i][i]; } |
| 410 | return h; |
| 411 | } |
| 412 | /** gambar `kartuMentah` ke 4 titik tujuan dengan perspektif asli (invers homografi + 2x2 supersample) */ |
| 413 | function gambarPerspektif(ctx, kartuMentah, titikTujuan) { |
| 414 | const sw = kartuMentah.width, sh = kartuMentah.height; |
| 415 | const pikselSumber = kartuMentah.getContext('2d').getImageData(0, 0, sw, sh).data; |
| 416 | const xs = titikTujuan.map((p) => p[0]), ys = titikTujuan.map((p) => p[1]); |
| 417 | const x0 = Math.floor(Math.min(...xs)) - 2, y0 = Math.floor(Math.min(...ys)) - 2; |
| 418 | const bw = Math.ceil(Math.max(...xs)) - x0 + 3, bh = Math.ceil(Math.max(...ys)) - y0 + 3; |
| 419 | const h = hitungHomografi(titikTujuan, [[0, 0], [sw, 0], [sw, sh], [0, sh]]); |
| 420 | const dataHasil = new Uint8ClampedArray(bw * bh * 4); |
| 421 | const sampelSub = [[0.25, 0.25], [0.75, 0.25], [0.25, 0.75], [0.75, 0.75]]; |
| 422 | for (let y = 0; y < bh; y++) { |
| 423 | for (let x = 0; x < bw; x++) { |
| 424 | let R = 0, G = 0, B = 0, A = 0; |
| 425 | for (const [ox, oy] of sampelSub) { |
| 426 | const X = x0 + x + ox, Y = y0 + y + oy; |
| 427 | const w = h[6] * X + h[7] * Y + 1; |
| 428 | const u = (h[0] * X + h[1] * Y + h[2]) / w - 0.5, v = (h[3] * X + h[4] * Y + h[5]) / w - 0.5; |
| 429 | if (u < 0 || v < 0 || u >= sw - 1 || v >= sh - 1) continue; |
| 430 | const iu = u | 0, iv = v | 0, fu = u - iu, fv = v - iv; |
| 431 | const i00 = (iv * sw + iu) * 4, i10 = i00 + 4, i01 = i00 + sw * 4, i11 = i01 + 4; |
| 432 | const w00 = (1 - fu) * (1 - fv), w10 = fu * (1 - fv), w01 = (1 - fu) * fv, w11 = fu * fv; |
| 433 | const a00 = pikselSumber[i00 + 3] * w00, a10 = pikselSumber[i10 + 3] * w10, a01 = pikselSumber[i01 + 3] * w01, a11 = pikselSumber[i11 + 3] * w11; |
| 434 | R += pikselSumber[i00] * a00 + pikselSumber[i10] * a10 + pikselSumber[i01] * a01 + pikselSumber[i11] * a11; |
| 435 | G += pikselSumber[i00 + 1] * a00 + pikselSumber[i10 + 1] * a10 + pikselSumber[i01 + 1] * a01 + pikselSumber[i11 + 1] * a11; |
| 436 | B += pikselSumber[i00 + 2] * a00 + pikselSumber[i10 + 2] * a10 + pikselSumber[i01 + 2] * a01 + pikselSumber[i11 + 2] * a11; |
| 437 | A += a00 + a10 + a01 + a11; |
| 438 | } |
| 439 | if (A > 0) { |
| 440 | const opsiKerja = (y * bw + x) * 4; |
| 441 | dataHasil[opsiKerja] = R / A; dataHasil[opsiKerja + 1] = G / A; dataHasil[opsiKerja + 2] = B / A; dataHasil[opsiKerja + 3] = A / 4; |
| 442 | } |
| 443 | } |
| 444 | } |
| 445 | const kanvasSementara = createCanvas(bw, bh); |
| 446 | kanvasSementara.getContext('2d').putImageData(new ImageData(dataHasil, bw, bh), 0, 0); |
| 447 | ctx.drawImage(kanvasSementara, x0, y0); |
| 448 | } |
| 449 | function titikGarisLuar() { |
| 450 | const hw = LEBAR_KARTU / 2 - 1.5, hh = TINGGI_KARTU / 2 - 1.5, daftarTitik = []; |
| 451 | const daftarSudut = [[-hw + RADIUS_SUDUT, -hh + RADIUS_SUDUT, Math.PI], [hw - RADIUS_SUDUT, -hh + RADIUS_SUDUT, Math.PI * 1.5], [hw - RADIUS_SUDUT, hh - RADIUS_SUDUT, 0], [-hw + RADIUS_SUDUT, hh - RADIUS_SUDUT, Math.PI * 0.5]]; |
| 452 | for (const [cx, cy, a0] of daftarSudut) { |
| 453 | for (let i = 0; i <= 10; i++) { |
| 454 | const a = a0 + (Math.PI / 2) * (i / 10); |
| 455 | daftarTitik.push({ u: cx + RADIUS_SUDUT * Math.cos(a), v: cy + RADIUS_SUDUT * Math.sin(a), nx: Math.cos(a), ny: Math.sin(a) }); |
| 456 | } |
| 457 | } |
| 458 | return daftarTitik; |
| 459 | } |
| 460 | const GARIS_LUAR = titikGarisLuar(); |
| 461 | |
| 462 | /** bayangan saja (bentuk digeser jauh keluar kanvas, hanya bayangannya yang tampak) */ |
| 463 | function gambarBayangan(g, q, warnaBayang, blurBayang, geserY = 0) { |
| 464 | const OFF = 6000; |
| 465 | g.save(); |
| 466 | g.beginPath(); g.moveTo(q[0][0] - OFF, q[0][1]); for (let i = 1; i < q.length; i++) g.lineTo(q[i][0] - OFF, q[i][1]); g.closePath(); |
| 467 | g.shadowColor = warnaBayang; g.shadowBlur = blurBayang; g.shadowOffsetX = OFF; g.shadowOffsetY = geserY; g.fillStyle = '#000'; g.fill(); |
| 468 | g.restore(); |
| 469 | } |
| 470 | |
| 471 | /** 1 kartu 3D: bayangan -> sisi tebal -> muka kartu -> rim; mengembalikan posisi pojok kanan atas */ |
| 472 | function gambarKartuTigaDimensi(ctx, kartuMentah, poseKartu, W, H) { |
| 473 | const proyeksiKartu = buatProyeksi(poseKartu, W, H); |
| 474 | const hw = LEBAR_KARTU / 2 + MARGIN_KARTU, hh = TINGGI_KARTU / 2 + MARGIN_KARTU; |
| 475 | const titikTujuan = [proyeksiKartu.pt(-hw, -hh), proyeksiKartu.pt(hw, -hh), proyeksiKartu.pt(hw, hh), proyeksiKartu.pt(-hw, hh)]; |
| 476 | |
| 477 | const q = [proyeksiKartu.pt(-LEBAR_KARTU / 2, -TINGGI_KARTU / 2), proyeksiKartu.pt(LEBAR_KARTU / 2, -TINGGI_KARTU / 2), proyeksiKartu.pt(LEBAR_KARTU / 2, TINGGI_KARTU / 2), proyeksiKartu.pt(-LEBAR_KARTU / 2, TINGGI_KARTU / 2)]; |
| 478 | gambarBayangan(ctx, q, 'rgba(0,0,0,0.6)', 60, 22); |
| 479 | |
| 480 | const L = [-0.5, -0.7, -0.5]; const ln = Math.hypot(...L); |
| 481 | const daftarSisi = []; |
| 482 | for (let i = 0; i < GARIS_LUAR.length; i++) { |
| 483 | const a = GARIS_LUAR[i], b = GARIS_LUAR[(i + 1) % GARIS_LUAR.length]; |
| 484 | const titikDuniaA = proyeksiKartu.world(a.u, a.v, 0); |
| 485 | const n = proyeksiKartu.rot(a.nx, a.ny, 0); |
| 486 | const arahKamera = [-titikDuniaA[0], -titikDuniaA[1], -titikDuniaA[2]]; const hasilRapikan = Math.hypot(...arahKamera); |
| 487 | const nilaiVis = (n[0] * arahKamera[0] + n[1] * arahKamera[1] + n[2] * arahKamera[2]) / hasilRapikan; |
| 488 | if (nilaiVis <= 0) continue; |
| 489 | const lit = Math.max(0, -(n[0] * L[0] + n[1] * L[1] + n[2] * L[2]) / ln); |
| 490 | daftarSisi.push({ poly: [proyeksiKartu.pt(a.u, a.v, 0), proyeksiKartu.pt(b.u, b.v, 0), proyeksiKartu.pt(b.u, b.v, KETEBALAN), proyeksiKartu.pt(a.u, a.v, KETEBALAN)], lit }); |
| 491 | } |
| 492 | ctx.save(); ctx.lineJoin = 'round'; |
| 493 | for (const f of daftarSisi) { |
| 494 | const k = Math.pow(f.lit, 0.8); |
| 495 | const r = Math.round(30 + 170 * k), gg = Math.round(32 + 178 * k), bb = Math.round(38 + 190 * k); |
| 496 | ctx.fillStyle = ctx.strokeStyle = `rgb(${r},${gg},${bb})`; ctx.lineWidth = 1.2; |
| 497 | ctx.beginPath(); ctx.moveTo(...f.poly[0]); for (let i = 1; i < 4; i++) ctx.lineTo(...f.poly[i]); ctx.closePath(); ctx.fill(); ctx.stroke(); |
| 498 | } |
| 499 | ctx.restore(); |
| 500 | |
| 501 | gambarPerspektif(ctx, kartuMentah, titikTujuan); |
| 502 | |
| 503 | ctx.save(); |
| 504 | const t0 = proyeksiKartu.pt(-LEBAR_KARTU / 2, -TINGGI_KARTU / 2), t1 = proyeksiKartu.pt(LEBAR_KARTU / 2, TINGGI_KARTU / 2); |
| 505 | const rg = ctx.createLinearGradient(t0[0], t0[1], t1[0], t1[1]); |
| 506 | rg.addColorStop(0, 'rgba(255,255,255,0.55)'); rg.addColorStop(0.5, 'rgba(255,255,255,0.10)'); rg.addColorStop(1, 'rgba(255,255,255,0.3)'); |
| 507 | ctx.strokeStyle = rg; ctx.lineWidth = 2; ctx.lineJoin = 'round'; |
| 508 | ctx.beginPath(); GARIS_LUAR.forEach((opsiKerja, i) => { const p = proyeksiKartu.pt(opsiKerja.u, opsiKerja.v, 0); i ? ctx.lineTo(...p) : ctx.moveTo(...p); }); ctx.closePath(); ctx.stroke(); |
| 509 | ctx.restore(); |
| 510 | |
| 511 | return { corner: proyeksiKartu.pt(LEBAR_KARTU / 2 - 6, -TINGGI_KARTU / 2 + 6, 0), scale: poseKartu.scale }; |
| 512 | } |
| 513 | |
| 514 | /* ---- kilau bintang 4 sudut di pojok kanan atas kartu ---- */ |
| 515 | function kilauSilang(g, panjangKilau, tebalKilau, rot, a) { |
| 516 | g.save(); g.rotate(rot); |
| 517 | const gr = g.createLinearGradient(-panjangKilau, 0, panjangKilau, 0); |
| 518 | gr.addColorStop(0, 'rgba(255,255,255,0)'); gr.addColorStop(0.5, `rgba(255,255,255,${a})`); gr.addColorStop(1, 'rgba(255,255,255,0)'); |
| 519 | g.fillStyle = gr; |
| 520 | g.beginPath(); g.moveTo(-panjangKilau, 0); g.quadraticCurveTo(0, -tebalKilau, panjangKilau, 0); g.quadraticCurveTo(0, tebalKilau, -panjangKilau, 0); g.closePath(); g.fill(); |
| 521 | g.restore(); |
| 522 | } |
| 523 | function gambarKilau(g, x, y, r, a = 1) { |
| 524 | g.save(); g.translate(x, y); |
| 525 | g.globalCompositeOperation = 'lighter'; |
| 526 | const halo = g.createRadialGradient(0, 0, 0, 0, 0, r * 0.95); |
| 527 | halo.addColorStop(0, `rgba(255,255,255,${0.7 * a})`); halo.addColorStop(0.3, `rgba(220,235,255,${0.22 * a})`); halo.addColorStop(1, 'rgba(220,235,255,0)'); |
| 528 | g.fillStyle = halo; g.beginPath(); g.arc(0, 0, r * 0.95, 0, Math.PI * 2); g.fill(); |
| 529 | kilauSilang(g, r * 1.5, r * 0.05, 0, 0.85 * a); |
| 530 | kilauSilang(g, r * 1.8, r * 0.05, Math.PI / 2, 0.85 * a); |
| 531 | g.globalCompositeOperation = 'source-over'; |
| 532 | const rx = r * 0.78, ry = r * 1.05, k = r * 0.05; |
| 533 | g.fillStyle = '#fff'; g.shadowColor = 'rgba(255,255,255,0.95)'; g.shadowBlur = r * 0.35; |
| 534 | g.beginPath(); |
| 535 | g.moveTo(0, -ry); g.quadraticCurveTo(k, -k, rx, 0); |
| 536 | g.quadraticCurveTo(k, k, 0, ry); g.quadraticCurveTo(-k, k, -rx, 0); |
| 537 | g.quadraticCurveTo(-k, -k, 0, -ry); g.closePath(); g.fill(); |
| 538 | g.restore(); |
| 539 | } |
| 540 | |
| 541 | /* ---- rapikan potongan karakter ---- */ |
| 542 | function beriLabelKomponen(topengBiner, W, H) { |
| 543 | const N = W * H, lab = new Int32Array(N), tumpukanData = new Int32Array(N), info = [null]; |
| 544 | let n = 0; |
| 545 | for (let i = 0; i < N; i++) { |
| 546 | if (!topengBiner[i] || lab[i]) continue; |
| 547 | n++; let sp = 0, size = 0, border = false; |
| 548 | tumpukanData[sp++] = i; lab[i] = n; |
| 549 | while (sp) { |
| 550 | const p = tumpukanData[--sp]; size++; |
| 551 | const x = p % W, y = (p - x) / W; |
| 552 | if (x === 0 || y === 0 || x === W - 1 || y === H - 1) border = true; |
| 553 | let q; |
| 554 | if (x > 0 && topengBiner[q = p - 1] && !lab[q]) { lab[q] = n; tumpukanData[sp++] = q; } |
| 555 | if (x < W - 1 && topengBiner[q = p + 1] && !lab[q]) { lab[q] = n; tumpukanData[sp++] = q; } |
| 556 | if (y > 0 && topengBiner[q = p - W] && !lab[q]) { lab[q] = n; tumpukanData[sp++] = q; } |
| 557 | if (y < H - 1 && topengBiner[q = p + W] && !lab[q]) { lab[q] = n; tumpukanData[sp++] = q; } |
| 558 | } |
| 559 | info.push({ size, border }); |
| 560 | } |
| 561 | return { lab, info }; |
| 562 | } |
| 563 | /** buang serpihan, tutup lubang kecil, tegasin setengah transparan, kikis halo, haluskan tepi. |
| 564 | * Warna diambil dari foto asli kalau sebangun (tanpa halo bekas pemotong). */ |
| 565 | function bersihkanPotongan(gambarPotongan, gambarLatarAsli, W, H, opsiKerja = {}) { |
| 566 | const N = W * H; |
| 567 | const c = createCanvas(W, H), g = c.getContext('2d'); |
| 568 | gambarPasPenuh(g, gambarPotongan, 0, 0, W, H); |
| 569 | const dataPiksel = g.getImageData(0, 0, W, H).data; |
| 570 | const a = new Uint8ClampedArray(N); |
| 571 | for (let i = 0; i < N; i++) a[i] = dataPiksel[i * 4 + 3]; |
| 572 | |
| 573 | const topengBiner = new Uint8Array(N); |
| 574 | for (let i = 0; i < N; i++) topengBiner[i] = a[i] > 40 ? 1 : 0; |
| 575 | let L = beriLabelKomponen(topengBiner, W, H), big = 0; |
| 576 | for (let k = 1; k < L.info.length; k++) big = Math.max(big, L.info[k].size); |
| 577 | const minSize = Math.max(500, big * 0.004); |
| 578 | for (let i = 0; i < N; i++) if (L.lab[i] && L.info[L.lab[i]].size < minSize) a[i] = 0; |
| 579 | |
| 580 | for (let i = 0; i < N; i++) topengBiner[i] = a[i] <= 40 ? 1 : 0; |
| 581 | L = beriLabelKomponen(topengBiner, W, H); |
| 582 | const holeMax = opsiKerja.holeMax || 700; |
| 583 | for (let i = 0; i < N; i++) if (L.lab[i] && !L.info[L.lab[i]].border && L.info[L.lab[i]].size <= holeMax) a[i] = 255; |
| 584 | |
| 585 | for (let i = 0; i < N; i++) { const v = a[i]; a[i] = v <= 30 ? 0 : v >= 225 ? 255 : Math.round((v - 30) * 255 / 195); } |
| 586 | |
| 587 | let nilaiBerjalan = a; |
| 588 | const jumlahErosi = opsiKerja.erode == null ? 1 : opsiKerja.erode; |
| 589 | for (let r = 0; r < jumlahErosi; r++) { |
| 590 | const alfaBaru = new Uint8ClampedArray(N); |
| 591 | for (let y = 0; y < H; y++) for (let x = 0; x < W; x++) { |
| 592 | const p = y * W + x; let v = nilaiBerjalan[p]; |
| 593 | if (x > 0 && nilaiBerjalan[p - 1] < v) v = nilaiBerjalan[p - 1]; |
| 594 | if (x < W - 1 && nilaiBerjalan[p + 1] < v) v = nilaiBerjalan[p + 1]; |
| 595 | if (y > 0 && nilaiBerjalan[p - W] < v) v = nilaiBerjalan[p - W]; |
| 596 | if (y < H - 1 && nilaiBerjalan[p + W] < v) v = nilaiBerjalan[p + W]; |
| 597 | alfaBaru[p] = v; |
| 598 | } |
| 599 | nilaiBerjalan = alfaBaru; |
| 600 | } |
| 601 | const alfaFinal = new Uint8ClampedArray(N); |
| 602 | for (let y = 0; y < H; y++) for (let x = 0; x < W; x++) { |
| 603 | const p = y * W + x, v = nilaiBerjalan[p]; |
| 604 | const l = x > 0 ? nilaiBerjalan[p - 1] : v, rt = x < W - 1 ? nilaiBerjalan[p + 1] : v; |
| 605 | const u = y > 0 ? nilaiBerjalan[p - W] : v, dn = y < H - 1 ? nilaiBerjalan[p + W] : v; |
| 606 | alfaFinal[p] = (4 * v + l + rt + u + dn) >> 3; |
| 607 | } |
| 608 | |
| 609 | let rgb = dataPiksel; |
| 610 | const rasioAspek = gambarPotongan.width / gambarPotongan.height; |
| 611 | if (gambarLatarAsli && Math.abs(gambarLatarAsli.width / gambarLatarAsli.height - rasioAspek) / rasioAspek < 0.02) { |
| 612 | const bc = createCanvas(W, H), bg2 = bc.getContext('2d'); |
| 613 | gambarPasPenuh(bg2, gambarLatarAsli, 0, 0, W, H); |
| 614 | rgb = bg2.getImageData(0, 0, W, H).data; |
| 615 | } |
| 616 | const dataHasil = new Uint8ClampedArray(N * 4); |
| 617 | const hitungBaris = new Uint32Array(H), hitungKolom = new Uint32Array(W); |
| 618 | let totalPiksel = 0; |
| 619 | for (let y = 0; y < H; y++) for (let x = 0; x < W; x++) { |
| 620 | const p = y * W + x, q = p * 4; |
| 621 | dataHasil[q] = rgb[q]; dataHasil[q + 1] = rgb[q + 1]; dataHasil[q + 2] = rgb[q + 2]; dataHasil[q + 3] = alfaFinal[p]; |
| 622 | if (alfaFinal[p] > 128) { hitungBaris[y]++; hitungKolom[x]++; totalPiksel++; } |
| 623 | } |
| 624 | let top = 0; while (top < H && hitungBaris[top] < 6) top++; |
| 625 | let bot = H - 1; while (bot > top && hitungBaris[bot] < 6) bot--; |
| 626 | let akumulasiKolom = 0, tengahX = W / 2; |
| 627 | for (let x = 0; x < W; x++) { akumulasiKolom += hitungKolom[x]; if (akumulasiKolom >= totalPiksel / 2) { tengahX = x; break; } } |
| 628 | const layer = createCanvas(W, H); |
| 629 | layer.getContext('2d').putImageData(new ImageData(dataHasil, W, H), 0, 0); |
| 630 | return { layer, top, bot, cx: tengahX, ok: totalPiksel > N * 0.01 && bot > top }; |
| 631 | } |
| 632 | /** geser + skala posisi kartu mengikuti letak & tinggi karakter di foto */ |
| 633 | function sesuaikanPose(poseDasar, statistikPotongan) { |
| 634 | const k = Math.min(1.3, Math.max(0.75, (statistikPotongan.bot - statistikPotongan.top) / ACUAN_KARAKTER.h)); |
| 635 | return poseDasar.map((p) => Object.assign({}, p, { |
| 636 | cx: Math.round(statistikPotongan.cx + (p.cx - ACUAN_KARAKTER.cx) * k), |
| 637 | cy: Math.round(statistikPotongan.top + (p.cy - ACUAN_KARAKTER.top) * k), |
| 638 | scale: +(p.scale * k).toFixed(3) |
| 639 | })); |
| 640 | } |
| 641 | |
| 642 | /** |
| 643 | * @param {object} p |
| 644 | * @param {string|Buffer} p.background foto latar (path / Buffer) |
| 645 | * @param {string|Buffer} [p.character] PNG potongan karakter (transparan, sebangun dengan foto) -> menimpa kartu |
| 646 | * @param {{title,artist,cover?,duration?,progress?}[]} p.songs 4 lagu (kurang dari 4 diulang) |
| 647 | * @param {object} [p.options] { width, height, darken, sparkles, charShadow, autoFit, erode, seed, format:'png'|'jpg', poses } |
| 648 | * @returns {Promise<Buffer>} |
| 649 | */ |
| 650 | async function rakitPosterLagu({ background, character, songs, options = {} }) { |
| 651 | const opsiKerja = Object.assign({ |
| 652 | width: 1080, height: 1920, darken: 0.1, sparkles: true, |
| 653 | charShadow: true, autoFit: true, erode: 1, seed: Date.now() % 100000, format: 'png', poses: POSE_AWAL |
| 654 | }, options); |
| 655 | const pengacak = pembangkitAcak(opsiKerja.seed); |
| 656 | const { width: W, height: H } = opsiKerja; |
| 657 | |
| 658 | const canvas = createCanvas(W, H), ctx = canvas.getContext('2d'); |
| 659 | ctx.imageSmoothingEnabled = true; ctx.imageSmoothingQuality = 'high'; |
| 660 | |
| 661 | const gambarLatarFoto = await muatGambar(background); |
| 662 | if (gambarLatarFoto) gambarPasPenuh(ctx, gambarLatarFoto, 0, 0, W, H); else { ctx.fillStyle = '#0b0f1a'; ctx.fillRect(0, 0, W, H); } |
| 663 | if (opsiKerja.darken > 0) { ctx.fillStyle = `rgba(0,0,0,${opsiKerja.darken})`; ctx.fillRect(0, 0, W, H); } |
| 664 | |
| 665 | const daftarLaguFinal = []; |
| 666 | for (let i = 0; i < 4; i++) daftarLaguFinal.push(songs[i % songs.length]); |
| 667 | const daftarKartuRender = []; |
| 668 | for (let i = 0; i < 4; i++) { |
| 669 | const s = daftarLaguFinal[i]; |
| 670 | const cover = (await muatGambar(s.cover)) || sampulPengganti(s.title, s.artist); |
| 671 | daftarKartuRender.push(buatKartuLagu(s, cover, pengacak)); |
| 672 | } |
| 673 | const daftarSudut = []; |
| 674 | |
| 675 | const sumberKarakter = await muatGambar(character); |
| 676 | let lapisanKarakterFinal = null; |
| 677 | if (sumberKarakter) { |
| 678 | try { |
| 679 | const hasilRapikan = bersihkanPotongan(sumberKarakter, gambarLatarFoto, W, H, { erode: opsiKerja.erode }); |
| 680 | if (hasilRapikan.ok) { lapisanKarakterFinal = hasilRapikan.layer; if (opsiKerja.autoFit) opsiKerja.poses = sesuaikanPose(opsiKerja.poses, hasilRapikan); } |
| 681 | } catch (e) { console.error('[poster-lagu] rapikan potongan gagal:', e.message); } |
| 682 | if (!lapisanKarakterFinal) { lapisanKarakterFinal = createCanvas(W, H); gambarPasPenuh(lapisanKarakterFinal.getContext('2d'), sumberKarakter, 0, 0, W, H); } |
| 683 | } |
| 684 | |
| 685 | // kilau digambar SEBELUM karakter supaya tertimpa karakter |
| 686 | const ukuranKilau = [34, 42, 30, 38]; |
| 687 | const gambarSemuaKilau = (front) => { |
| 688 | if (!opsiKerja.sparkles) return; |
| 689 | for (let i = 0; i < 4; i++) { |
| 690 | if (!!opsiKerja.poses[i].front === front && daftarSudut[i]) gambarKilau(ctx, daftarSudut[i].corner[0], daftarSudut[i].corner[1], ukuranKilau[i] * daftarSudut[i].scale / 0.93, 1); |
| 691 | } |
| 692 | }; |
| 693 | |
| 694 | for (let i = 0; i < 4; i++) if (!opsiKerja.poses[i].front) daftarSudut[i] = gambarKartuTigaDimensi(ctx, daftarKartuRender[i], opsiKerja.poses[i], W, H); |
| 695 | gambarSemuaKilau(false); |
| 696 | if (lapisanKarakterFinal) { |
| 697 | ctx.save(); |
| 698 | if (opsiKerja.charShadow) { ctx.shadowColor = 'rgba(0,0,0,0.5)'; ctx.shadowBlur = 26; ctx.shadowOffsetY = 6; } |
| 699 | ctx.drawImage(lapisanKarakterFinal, 0, 0, W, H); |
| 700 | ctx.restore(); |
| 701 | } |
| 702 | for (let i = 0; i < 4; i++) if (opsiKerja.poses[i].front) daftarSudut[i] = gambarKartuTigaDimensi(ctx, daftarKartuRender[i], opsiKerja.poses[i], W, H); |
| 703 | gambarSemuaKilau(true); |
| 704 | |
| 705 | return opsiKerja.format === 'jpg' ? canvas.toBuffer('image/jpeg', 92) : canvas.toBuffer('image/png'); |
| 706 | } |
| 707 | |
| 708 | /* ================================================================== */ |
| 709 | /* 4. PINTU UTAMA */ |
| 710 | /* ================================================================== */ |
| 711 | /** |
| 712 | * Semua langkah sekaligus: cari lagu+cover, hapus background (opsional), render. |
| 713 | * @param {object} p |
| 714 | * @param {Buffer|string} p.photo foto (Buffer / path) |
| 715 | * @param {string[]} p.songs tulis bebas: "judul artis", "artis judul", atau "judul" saja (maks 4) |
| 716 | * @param {boolean} [p.cut=true] false = tanpa efek karakter menimpa kartu |
| 717 | * @param {'png'|'jpg'} [p.format='png'] |
| 718 | * @returns {Promise<Buffer>} |
| 719 | */ |
| 720 | async function buatPosterLagu({ photo, songs, cut = true, format = 'png' }) { |
| 721 | const penyanggaFoto = Buffer.isBuffer(photo) ? photo : fs.readFileSync(photo); |
| 722 | const daftarKueri = (Array.isArray(songs) ? songs : uraikanDaftarLagu(songs).songs).slice(0, 4); |
| 723 | if (!daftarKueri.length) throw new Error('Minimal satu lagu.'); |
| 724 | |
| 725 | const janjiLagu = Promise.all(daftarKueri.map((q) => temukanLagu(q))); |
| 726 | let penyanggaPotongan; |
| 727 | const janjiPotong = !cut ? Promise.resolve() : (async () => { |
| 728 | try { |
| 729 | const formatPng = penyanggaFoto.subarray(0, 4).equals(TANDA_PNG); |
| 730 | penyanggaPotongan = await potongLatar(penyanggaFoto, formatPng ? 'image/png' : 'image/jpeg'); |
| 731 | const [a, b] = await Promise.all([loadImage(penyanggaFoto), loadImage(penyanggaPotongan)]); |
| 732 | if (Math.abs(a.width / a.height - b.width / b.height) / (a.width / a.height) >= 0.02) throw new Error('ukuran hasil potongan beda dengan foto'); |
| 733 | console.log('[poster-lagu] karakter menimpa kartu:', labelBria()); |
| 734 | } catch (e) { penyanggaPotongan = undefined; console.error('[poster-lagu] tanpa efek karakter menimpa kartu:', e.message); } |
| 735 | })(); |
| 736 | const [laguTerpilih] = await Promise.all([janjiLagu, janjiPotong]); |
| 737 | laguTerpilih.forEach((r, i) => console.log(`[poster-lagu] ${i + 1}. ${r.found ? `${r.title} — ${r.artist} (${r.source})` : `${r.title} (tidak ketemu, cover cadangan)`}`)); |
| 738 | |
| 739 | return rakitPosterLagu({ |
| 740 | background: penyanggaFoto, |
| 741 | character: penyanggaPotongan, |
| 742 | songs: laguTerpilih.map((r) => ({ title: r.title, artist: r.artist, cover: r.cover || undefined, duration: r.duration || undefined })), |
| 743 | options: { format }, |
| 744 | }); |
| 745 | } |
| 746 | |
| 747 | module.exports = { buatPosterLagu, rakitPosterLagu, temukanLagu, uraikanDaftarLagu, potongLatar, POSE_AWAL }; |
| 748 | |
| 749 | /* ---- terminal: node poster-lagu-3d.js foto.jpg "lagu 1" "lagu 2" ... [--nocut] [--out hasil.png] ---- */ |
| 750 | if (require.main === module) { |
| 751 | (async () => { |
| 752 | const daftarArgumen = process.argv.slice(2); |
| 753 | const ambilOpsi = (flag) => { const i = daftarArgumen.indexOf(flag); if (i < 0) return null; daftarArgumen.splice(i, 1); return true; }; |
| 754 | const tanpaPotong = ambilOpsi('--nocut'); |
| 755 | let dataHasil = 'poster-lagu.png'; |
| 756 | const indeksOpsiOut = daftarArgumen.indexOf('--out'); if (indeksOpsiOut >= 0) { dataHasil = daftarArgumen[indeksOpsiOut + 1] || dataHasil; daftarArgumen.splice(indeksOpsiOut, 2); } |
| 757 | const [photo, ...songs] = daftarArgumen; |
| 758 | if (!photo || !songs.length) { console.log('Pakai: node poster-lagu-3d.js foto.jpg "judul artis" "judul artis" ... [--nocut] [--out hasil.png]'); process.exit(1); } |
| 759 | const penyanggaHasil = await buatPosterLagu({ photo, songs, cut: !tanpaPotong, format: /\.jpe?g$/i.test(dataHasil) ? 'jpg' : 'png' }); |
| 760 | fs.writeFileSync(dataHasil, penyanggaHasil); |
| 761 | console.log('Selesai ->', dataHasil); |
| 762 | })().catch((e) => { console.error('Gagal:', e.message); process.exit(1); }); |
| 763 | } |
Discussion & Comments0
No comments yet. Be the first to leave feedback or start a code discussion.
Sign in with your GitHub account to write comments and join the discussion.