2Btainment commited on
Commit
8da270f
·
verified ·
1 Parent(s): 61657d1

P5.1-5.3: Radio, Social, Shop studios + video reframe (9:16/16:9/4:5/1:1)

Browse files
app.js CHANGED
@@ -1,11 +1,12 @@
1
  import * as THREE from './vendor/three.module.min.js';
2
  import { STUDIOS, stopLoops } from './widgets.js?v=50';
3
- import './real.js?v=93';
4
- import './avatar.js?v=93';
5
- import './master.js?v=93';
6
- import './video.js?v=93';
7
- import './workspace.js?v=93';
8
- import { icon } from './icons.js?v=93';
 
9
  import { RoomEnvironment } from './vendor/addons/environments/RoomEnvironment.js';
10
  import { EffectComposer } from './vendor/addons/postprocessing/EffectComposer.js';
11
  import { RenderPass } from './vendor/addons/postprocessing/RenderPass.js';
 
1
  import * as THREE from './vendor/three.module.min.js';
2
  import { STUDIOS, stopLoops } from './widgets.js?v=50';
3
+ import './real.js?v=96';
4
+ import './avatar.js?v=96';
5
+ import './master.js?v=96';
6
+ import './video.js?v=96';
7
+ import './workspace.js?v=96';
8
+ import './studios5.js?v=96';
9
+ import { icon } from './icons.js?v=96';
10
  import { RoomEnvironment } from './vendor/addons/environments/RoomEnvironment.js';
11
  import { EffectComposer } from './vendor/addons/postprocessing/EffectComposer.js';
12
  import { RenderPass } from './vendor/addons/postprocessing/RenderPass.js';
avatar.js CHANGED
@@ -1,7 +1,7 @@
1
  // Avatar / Persona studio (DoD): persistent avatars as workspace asset type `avatar`
2
  // avatars/<slug>/avatar.json + ref.webp + voice.wav · reused by Chat, Image (Kontext), agents.
3
  import { STUDIOS, onStop } from './widgets.js?v=50';
4
- import { run, result, MODULES, esc, hf, stTxt, url, badge, setS, keep, LS, FLUX, KONTEXT, TTS, CHAT, signedIn } from './real.js?v=93';
5
 
6
  export const MODA = 'multimodalart/MoDA-fast-talking-head', W2L = 'pragnakalp/Wav2lip-ZeroGPU';
7
  const LANGS = ['German', 'English', 'French', 'Spanish', 'Auto'];
 
1
  // Avatar / Persona studio (DoD): persistent avatars as workspace asset type `avatar`
2
  // avatars/<slug>/avatar.json + ref.webp + voice.wav · reused by Chat, Image (Kontext), agents.
3
  import { STUDIOS, onStop } from './widgets.js?v=50';
4
+ import { run, result, MODULES, esc, hf, stTxt, url, badge, setS, keep, LS, FLUX, KONTEXT, TTS, CHAT, signedIn } from './real.js?v=96';
5
 
6
  export const MODA = 'multimodalart/MoDA-fast-talking-head', W2L = 'pragnakalp/Wav2lip-ZeroGPU';
7
  const LANGS = ['German', 'English', 'French', 'Spanish', 'Auto'];
icons.js CHANGED
@@ -17,6 +17,9 @@ const P = {
17
  merge:'<path d="M6 3v6a6 6 0 006 6h0a6 6 0 006-6V3"/><path d="M12 15v6M9 18l3 3 3-3"/>',
18
  master:'<path d="M4 21v-7M4 10V3M12 21v-9M12 8V3M20 21v-5M20 12V3"/><path d="M1 14h6M9 8h6M17 16h6"/>',
19
  avatar:'<circle cx="12" cy="8" r="4"/><path d="M4 21c0-4 4-6 8-6s8 2 8 6"/><path d="M17 4l1.5-1.5M19 7h2"/>',
 
 
 
20
  sound:'<path d="M4 9h4l5-4v14l-5-4H4z"/><path d="M16 9a4 4 0 010 6M18.5 6.5a8 8 0 010 11"/>',
21
  mute:'<path d="M4 9h4l5-4v14l-5-4H4z"/><path d="M16 9l5 6M21 9l-5 6"/>',
22
  bell:'<path d="M6 16V11a6 6 0 0112 0v5l2 2H4z"/><path d="M10 20a2 2 0 004 0"/>',
 
17
  merge:'<path d="M6 3v6a6 6 0 006 6h0a6 6 0 006-6V3"/><path d="M12 15v6M9 18l3 3 3-3"/>',
18
  master:'<path d="M4 21v-7M4 10V3M12 21v-9M12 8V3M20 21v-5M20 12V3"/><path d="M1 14h6M9 8h6M17 16h6"/>',
19
  avatar:'<circle cx="12" cy="8" r="4"/><path d="M4 21c0-4 4-6 8-6s8 2 8 6"/><path d="M17 4l1.5-1.5M19 7h2"/>',
20
+ radio:'<rect x="3" y="9" width="18" height="12" rx="2"/><path d="M7 9l10-6"/><circle cx="8" cy="15" r="2.5"/><path d="M14 13h4M14 17h4"/>',
21
+ social:'<path d="M3 10v4h3l7 5V5L6 10z"/><path d="M17 8a5 5 0 010 8M20 5a9 9 0 010 14"/>',
22
+ shop:'<path d="M5 8h14l-1 13H6z"/><path d="M9 8V6a3 3 0 016 0v2"/>',
23
  sound:'<path d="M4 9h4l5-4v14l-5-4H4z"/><path d="M16 9a4 4 0 010 6M18.5 6.5a8 8 0 010 11"/>',
24
  mute:'<path d="M4 9h4l5-4v14l-5-4H4z"/><path d="M16 9l5 6M21 9l-5 6"/>',
25
  bell:'<path d="M6 16V11a6 6 0 0112 0v5l2 2H4z"/><path d="M10 20a2 2 0 004 0"/>',
index.html CHANGED
@@ -8,7 +8,7 @@
8
  <title>STUDIUS · DAS Studio — Einswarm</title>
9
  <link rel="icon" href="assets/einswarm-mascot.webp">
10
  <link rel="preload" href="fonts/outfit-latin-wght.woff2" as="font" type="font/woff2" crossorigin>
11
- <link rel="stylesheet" href="style.css?v=93">
12
  </head>
13
  <body>
14
  <canvas id="gl"></canvas>
@@ -49,6 +49,6 @@
49
 
50
  <a id="bmc" href="https://www.buymeacoffee.com/2btainment" target="_blank" rel="noopener noreferrer">Buy me a coffee</a>
51
  <noscript><p style="color:#f2c94c;padding:2em">STUDIUS braucht JavaScript.</p></noscript>
52
- <script type="module" src="app.js?v=93"></script>
53
  </body>
54
  </html>
 
8
  <title>STUDIUS · DAS Studio — Einswarm</title>
9
  <link rel="icon" href="assets/einswarm-mascot.webp">
10
  <link rel="preload" href="fonts/outfit-latin-wght.woff2" as="font" type="font/woff2" crossorigin>
11
+ <link rel="stylesheet" href="style.css?v=96">
12
  </head>
13
  <body>
14
  <canvas id="gl"></canvas>
 
49
 
50
  <a id="bmc" href="https://www.buymeacoffee.com/2btainment" target="_blank" rel="noopener noreferrer">Buy me a coffee</a>
51
  <noscript><p style="color:#f2c94c;padding:2em">STUDIUS braucht JavaScript.</p></noscript>
52
+ <script type="module" src="app.js?v=96"></script>
53
  </body>
54
  </html>
master.js CHANGED
@@ -1,7 +1,7 @@
1
  // Mastering studio (DoD): client-side WebAudio chain EQ → compressor → limiter, loudness normalisation to target LUFS
2
  // (ITU-R BS.1770-4 K-weighting + gating, measured offline), live meter, A/B, WAV/MP3 export, save to workspace.
3
  import { STUDIOS, onStop, loop, cv } from './widgets.js?v=50';
4
- import { result, MODULES, esc, setS, keep } from './real.js?v=93';
5
 
6
  /* ---------- BS.1770 loudness ---------- */
7
  function biquad(x, b0, b1, b2, a0, a1, a2) { const y = new Float32Array(x.length); b0 /= a0; b1 /= a0; b2 /= a0; a1 /= a0; a2 /= a0; let x1 = 0, x2 = 0, y1 = 0, y2 = 0;
 
1
  // Mastering studio (DoD): client-side WebAudio chain EQ → compressor → limiter, loudness normalisation to target LUFS
2
  // (ITU-R BS.1770-4 K-weighting + gating, measured offline), live meter, A/B, WAV/MP3 export, save to workspace.
3
  import { STUDIOS, onStop, loop, cv } from './widgets.js?v=50';
4
+ import { result, MODULES, esc, setS, keep } from './real.js?v=96';
5
 
6
  /* ---------- BS.1770 loudness ---------- */
7
  function biquad(x, b0, b1, b2, a0, a1, a2) { const y = new Float32Array(x.length); b0 /= a0; b1 /= a0; b2 /= a0; a1 /= a0; a2 /= a0; let x1 = 0, x2 = 0, y1 = 0, y2 = 0;
server/main.py CHANGED
@@ -331,6 +331,34 @@ async def stillvideo(req: Request, image: UploadFile = File(...), audio: UploadF
331
  u = tmp_put(out); shutil.rmtree(d, ignore_errors=True)
332
  return {"url": u}
333
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
334
  @app.get("/api/quota")
335
  async def quota(req: Request):
336
  """User's own ZeroGPU quota (GPU-seconds) from the Hub. Token stays server-side."""
 
331
  u = tmp_put(out); shutil.rmtree(d, ignore_errors=True)
332
  return {"url": u}
333
 
334
+ @app.post("/api/reframe")
335
+ async def reframe(req: Request, file: UploadFile | None = File(None), src: str = Form(""), aspect: str = Form("9:16"), mode: str = Form("blur"), name: str = Form("video")):
336
+ """Reframe a video for platforms: 9:16 / 16:9 / 1:1 / 4:5, either blurred-background fill or centre crop. H.264/AAC faststart."""
337
+ import asyncio, shutil, subprocess
338
+ from .infer import tmp_put, tmp_path
339
+ need(req)
340
+ if not shutil.which("ffmpeg"): raise HTTPException(503, "ffmpeg not installed")
341
+ dims = {"9:16": (1080, 1920), "16:9": (1920, 1080), "1:1": (1080, 1080), "4:5": (1080, 1350)}
342
+ if aspect not in dims or mode not in ("blur", "crop"): raise HTTPException(400, "aspect/mode")
343
+ W, H = dims[aspect]; d = tempfile.mkdtemp(); stem = re.sub(r"[^\w.-]+", "-", Path(name).stem)[:70] or "video"; out = f"{d}/{stem}-{aspect.replace(':', 'x')}.mp4"
344
+ if src:
345
+ inp = tmp_path(src)
346
+ if not inp: shutil.rmtree(d, ignore_errors=True); raise HTTPException(400, "tmp file expired")
347
+ elif file is not None:
348
+ b = await file.read(MAX_UP + 1)
349
+ if len(b) > MAX_UP: shutil.rmtree(d, ignore_errors=True); raise HTTPException(413, "max 200 MB")
350
+ inp = f"{d}/in.bin"; Path(inp).write_bytes(b)
351
+ else: raise HTTPException(400, "file or src required")
352
+ if mode == "crop": fc = f"[0:v]scale={W}:{H}:force_original_aspect_ratio=increase,crop={W}:{H},setsar=1,format=yuv420p[v]"
353
+ else: fc = (f"[0:v]split[a][b];[a]scale={W}:{H}:force_original_aspect_ratio=increase,crop={W}:{H},boxblur=30:2,eq=brightness=-0.08[bg];"
354
+ f"[b]scale={W}:{H}:force_original_aspect_ratio=decrease[fg];[bg][fg]overlay=(W-w)/2:(H-h)/2,setsar=1,format=yuv420p[v]")
355
+ cmd = ["ffmpeg", "-hide_banner", "-loglevel", "error", "-y", "-i", inp, "-filter_complex", fc, "-map", "[v]", "-map", "0:a:0?", "-r", "30", "-c:v", "libx264", "-profile:v", "high", "-level", "4.1",
356
+ "-preset", "veryfast", "-crf", "21", "-pix_fmt", "yuv420p", "-c:a", "aac", "-b:a", "160k", "-ar", "48000", "-ac", "2", "-movflags", "+faststart", out]
357
+ p = await asyncio.to_thread(subprocess.run, cmd, capture_output=True, text=True, timeout=600)
358
+ if p.returncode != 0 or not os.path.exists(out): shutil.rmtree(d, ignore_errors=True); raise HTTPException(422, "ffmpeg: " + (p.stderr or "failed")[-300:])
359
+ u = tmp_put(out); shutil.rmtree(d, ignore_errors=True)
360
+ return {"url": u, "width": W, "height": H, "aspect": aspect, "mode": mode}
361
+
362
  @app.get("/api/quota")
363
  async def quota(req: Request):
364
  """User's own ZeroGPU quota (GPU-seconds) from the Hub. Token stays server-side."""
studios5.js ADDED
@@ -0,0 +1,281 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // STUDIUS P5: Radio Studio · Social/Marketing Studio · Shop Studio (JDT link-shop) + video reframe helper.
2
+ // Every result goes on the asset bus (save to workspace / send to studio). Nothing is ever posted or published externally.
3
+ import { STUDIOS } from './widgets.js?v=50';
4
+ import { run, result, MODULES, esc, hf, stTxt, url, badge, setS, keep, signedIn, TF, CHAT, FLUX } from './real.js?v=96';
5
+ import { Avatars } from './avatar.js?v=96';
6
+ import { toWav, toMp3 } from './master.js?v=96';
7
+
8
+ const bucket = () => signedIn() && window.__ws?.bucket;
9
+ const wsFile = (p) => '/api/ws/file?bucket=' + encodeURIComponent(window.__ws.bucket) + '&path=' + encodeURIComponent(p);
10
+ const toBlob = async (u) => u instanceof Blob ? u : (await fetch(u, { credentials: 'include' })).blob();
11
+ const slug = (n) => (n || 'x').toLowerCase().normalize('NFKD').replace(/[^\w]+/g, '-').replace(/^-|-$/g, '').slice(0, 40) || 'x';
12
+ const ts = () => new Date().toISOString().slice(0, 16).replace(/[-:T]/g, '');
13
+ async function upload(path, blob, studio) { if (!bucket()) throw new Error('Bitte anmelden + Workspace-Bucket verbinden'); const f = new FormData(); f.append('bucket', window.__ws.bucket); f.append('path', path); f.append('studio', studio); f.append('file', blob, path.split('/').pop());
14
+ const r = await fetch('/api/ws/upload', { method: 'POST', body: f, credentials: 'include' }); if (!r.ok) throw new Error((await r.json().catch(() => ({}))).detail || 'Upload ' + r.status); return r.json(); }
15
+ async function wsList(prefix = '') { if (!bucket()) return []; const r = await fetch('/api/ws/list?bucket=' + encodeURIComponent(window.__ws.bucket) + '&prefix=' + encodeURIComponent(prefix), { credentials: 'include' }); return r.ok ? (await r.json()).files || [] : []; }
16
+ async function wsJson(path, dflt) { if (!bucket()) return dflt; try { const r = await fetch(wsFile(path), { credentials: 'include' }); return r.ok ? await r.json() : dflt; } catch (e) { return dflt; } }
17
+ const saveJson = (path, obj, studio) => upload(path, new Blob([JSON.stringify(obj, null, 1)], { type: 'application/json' }), studio);
18
+ async function llm(prompt, on = {}) { const r = await MODULES.chat.actions.reply.run({ prompt }, on); return (r.text || '').replace(/\*\*/g, '').replace(/^[ \t]*["„“]|["“”][ \t]*$/gm, '').replace(/\n{3,}/g, '\n\n').trim(); }
19
+ const dl = (blob, name) => { const a = document.createElement('a'); a.href = URL.createObjectURL(blob); a.download = name; a.click(); setTimeout(() => URL.revokeObjectURL(a.href), 4000); };
20
+ const canvasBlob = (c, t = 'image/png') => new Promise(r => c.toBlob(r, t, .92));
21
+ const loadImg = (src) => new Promise((ok, no) => { const i = new Image(); i.crossOrigin = 'anonymous'; i.onload = () => ok(i); i.onerror = () => no(new Error('Bild lädt nicht')); i.src = src; });
22
+ const cover = (x, img, X, Y, W, H) => { const s = Math.max(W / img.width, H / img.height), w = img.width * s, h = img.height * s; x.save(); x.beginPath(); x.rect(X, Y, W, H); x.clip(); x.drawImage(img, X + (W - w) / 2, Y + (H - h) / 2, w, h); x.restore(); };
23
+ function wrap(x, text, X, Y, maxW, lh, maxLines = 4) { const words = String(text).split(/\s+/); let line = '', n = 0; for (const w of words) { const t = line ? line + ' ' + w : w; if (x.measureText(t).width > maxW && line) { x.fillText(line, X, Y + n * lh); line = w; if (++n >= maxLines) return; } else line = t; } if (line) x.fillText(line, X, Y + n * lh); }
24
+ const avOptions = async (sel, empty) => { const l = await Avatars.list().catch(() => []); sel.innerHTML = `<option value="">${empty}</option>` + l.map(a => `<option value="${esc(a.id)}">${esc(a.name || a.id)}</option>`).join(''); sel._list = l; return l; };
25
+
26
+ /* ---------- shared: reframe a video (server ffmpeg) ---------- */
27
+ export async function reframe(video, aspect = '9:16', mode = 'blur', name = 'video') {
28
+ const f = new FormData(); f.append('aspect', aspect); f.append('mode', mode); f.append('name', name);
29
+ if (typeof video === 'string' && video.startsWith('/api/tmp/')) f.append('src', video); else f.append('file', await toBlob(video), name + '.mp4');
30
+ const r = await fetch('/api/reframe', { method: 'POST', body: f, credentials: 'include' }); if (!r.ok) throw new Error('Reframe: ' + ((await r.json().catch(() => ({}))).detail || r.status)); return r.json(); }
31
+ window.__reframe = reframe;
32
+ export function reframeRow(host, getVideo, base = {}) { // UI row: format + mode → new video asset on the bus
33
+ const d = document.createElement('div'); d.className = 'row reframe'; d.innerHTML = `<select class="rfa" aria-label="Zielformat"><option value="9:16">9:16 Reel/TikTok/Story</option><option value="16:9">16:9 YouTube</option><option value="4:5">4:5 Instagram</option><option value="1:1">1:1 Quadrat</option></select><select class="rfm" aria-label="Füllmodus"><option value="blur">Unscharfer Hintergrund</option><option value="crop">Zuschneiden</option></select><button class="btn alt rfgo">↔ Umformatieren</button><small class="rfst mut"></small><div class="rfout" style="width:100%"></div>`;
34
+ host.append(d); const q = (s) => d.querySelector(s);
35
+ q('.rfgo').onclick = async () => { const v = getVideo(); if (!v) return q('.rfst').textContent = 'kein Video'; q('.rfgo').disabled = true; q('.rfst').textContent = 'ffmpeg…';
36
+ try { const r = await reframe(v, q('.rfa').value, q('.rfm').value, base.name || 'video'); q('.rfout').innerHTML = `<video controls playsinline src="${esc(r.url)}" style="max-height:260px"></video>`; q('.rfst').textContent = `✔ ${r.width}×${r.height}`; window.__reframed = r;
37
+ result(q('.rfout'), { kind: 'video', mime: 'video/mp4', url: r.url, name: `${slug(base.name || 'video')}-${r.aspect.replace(':', 'x')}-${Date.now()}.mp4`, studio: base.studio || 'videoedit', prompt: base.prompt || '', model: 'ffmpeg reframe ' + r.aspect + ' ' + r.mode }); }
38
+ catch (e) { q('.rfst').textContent = '⚠ ' + e.message; } finally { q('.rfgo').disabled = false; } };
39
+ return d;
40
+ }
41
+ // Avatar Studio: reframe talking-head output (square MoDA → 9:16 / 16:9 …)
42
+ new MutationObserver(() => { const o = document.querySelector('#pop .talkout'); if (o && o.querySelector('video') && !o.parentElement.querySelector('.reframe')) reframeRow(o.parentElement, () => o.querySelector('video')?.getAttribute('src'), { name: 'talk', studio: 'avatar' }); }).observe(document.body, { childList: true, subtree: true });
43
+
44
+ /* =================== RADIO STUDIO =================== */
45
+ const RAD = { station: 'STUDIUS FM', tracks: [], host: '', xf: 3, epoch: Date.now(), buf: new Map() };
46
+ const isAudio = (p) => /\.(wav|mp3|ogg|flac|m4a|opus)$/i.test(p);
47
+ async function decodeUrl(u) { if (RAD.buf.has(u)) return RAD.buf.get(u); const ac = new OfflineAudioContext(2, 1, 44100); const b = await ac.decodeAudioData(await (await toBlob(u)).arrayBuffer()); RAD.buf.set(u, b); return b; }
48
+ function plan(bufs, xf) { let t = 0; return bufs.map((b, i) => { const st = t, f = Math.min(xf, b.duration / 3); t += b.duration - (i < bufs.length - 1 ? f : 0); return { st, dur: b.duration, f }; }); }
49
+ function schedule(ctx, bufs, P, from = 0, t0 = 0) { const nodes = []; bufs.forEach((b, i) => { const p = P[i], end = p.st + p.dur; if (end <= from) return;
50
+ const s = ctx.createBufferSource(); s.buffer = b; const g = ctx.createGain(); s.connect(g).connect(ctx.destination); const off = Math.max(0, from - p.st), at = t0 + Math.max(0, p.st - from);
51
+ const gv = (tt) => Math.min(1, i > 0 ? (tt - p.st) / p.f : 1, i < bufs.length - 1 ? (end - tt) / p.f : 1); const a0 = p.st + off;
52
+ g.gain.setValueAtTime(Math.max(0, gv(a0)), at); if (i > 0 && a0 < p.st + p.f) g.gain.linearRampToValueAtTime(1, t0 + p.st + p.f - from);
53
+ if (i < bufs.length - 1) { g.gain.setValueAtTime(1, Math.max(at, t0 + end - p.f - from)); g.gain.linearRampToValueAtTime(0, t0 + end - from); }
54
+ s.start(at, off); nodes.push(s); }); return nodes; }
55
+ async function mixJingle(voice, bed, len = 10) { // bed ducked under voice, fade out
56
+ const sr = 44100, v = voice ? await decodeUrl(voice) : null, b = bed ? await decodeUrl(bed) : null, dur = Math.max(v ? v.duration + 1.6 : 0, Math.min(b ? b.duration : 0, len)) || 4;
57
+ const ctx = new OfflineAudioContext(2, Math.ceil(dur * sr), sr);
58
+ if (b) { const s = ctx.createBufferSource(); s.buffer = b; const g = ctx.createGain(); s.connect(g).connect(ctx.destination); g.gain.setValueAtTime(.9, 0);
59
+ if (v) { g.gain.linearRampToValueAtTime(.22, .6); g.gain.setValueAtTime(.22, .6 + v.duration); g.gain.linearRampToValueAtTime(.9, 1.2 + v.duration); } g.gain.setValueAtTime(g.gain.value, Math.max(0, dur - 1.2)); g.gain.linearRampToValueAtTime(0, dur); s.start(0); }
60
+ if (v) { const s = ctx.createBufferSource(); s.buffer = v; const g = ctx.createGain(); g.gain.value = 1.1; s.connect(g).connect(ctx.destination); s.start(.6); }
61
+ return ctx.startRendering(); }
62
+ STUDIOS.push({ id: 'radio', cat: 'Audio', icon: '📻', name: 'Radio Studio', like: 'Sender & Playlist', real: 'API', accepts: ['audio'], build(el) {
63
+ el.innerHTML = `<div class="row" style="margin:0 0 6px"><span class="badge real">REAL</span><span class="stat">Sender bauen: Playlist · Jingles · Moderation · Export</span></div>
64
+ <div class="row"><input class="stn" aria-label="Sendername" value="${esc(RAD.station)}"><select class="host" aria-label="Moderator (Avatar)"></select><select class="xf" aria-label="Crossfade"><option value="0">kein Crossfade</option><option value="3" selected>Crossfade 3 s</option><option value="6">Crossfade 6 s</option></select></div>
65
+ <fieldset class="grp"><legend>Playlist</legend><div class="row"><button class="btn alt wsadd">📂 Aus Workspace</button><label class="btn alt">⬆ Audio<input type="file" accept="audio/*" multiple hidden class="up"></label><small class="tot mut"></small></div><div class="wspick"></div><ol class="pl"></ol></fieldset>
66
+ <fieldset class="grp"><legend>Jingle-Generator</legend><input class="jt" aria-label="Jingle-Text" placeholder="Jingle-Text"><div class="row"><select class="bed" aria-label="Musikbett"><option value="gen">Musikbett erzeugen (TangoFlux)</option><option value="track">1. Track als Bett</option><option value="none">ohne Musik</option></select><input class="bedp" aria-label="Musikbett-Prompt" value="upbeat radio station jingle, bright synth stinger, punchy drums"></div><div class="row"><button class="btn alt jgo">🎺 Jingle erzeugen</button></div></fieldset>
67
+ <fieldset class="grp"><legend>Moderation (Avatar als Host)</legend><div class="row"><select class="mtr" aria-label="Ansage vor Track"></select><button class="btn alt mgo">🎙 Ansage erzeugen</button></div><small class="mut">Der Host schreibt (LLM) und spricht (seine Stimme) eine kurze Ansage, die vor dem Track eingefügt wird.</small></fieldset>
68
+ <div class="row"><button class="btn play">▶ Abspielen</button><button class="btn alt live">📡 Live (pseudo)</button><button class="btn alt stop">■</button><span class="np mut"></span></div>
69
+ <div class="row"><button class="btn alt exp">⬇ Sendung exportieren (MP3 + Playlist)</button></div><div class="out"></div>
70
+ <div class="credit">Jingles: ${hf(TF)} + Avatar-Stimme · Moderation: ${hf(CHAT)} · Crossfade/Export lokal (WebAudio) · Pseudo-Live: <code>position = (jetzt − Epoch) mod Länge</code> · Export: <code>projects/radio/&lt;sender&gt;/</code> (MP3 + playlist.json + .m3u für Icecast/Liquidsoap)</div>`;
71
+ keep(el); const q = (s) => el.querySelector(s); let ctx = null, nodes = [], tick = null;
72
+ q('.jt').value = `${RAD.station} – dein Sender aus dem Bienenstock!`;
73
+ avOptions(q('.host'), '🎙 Host: Standardstimme').then(() => { q('.host').value = RAD.host; });
74
+ q('.host').onchange = () => RAD.host = q('.host').value; q('.stn').onchange = () => RAD.station = q('.stn').value.trim() || 'STUDIUS FM'; q('.xf').value = String(RAD.xf); q('.xf').onchange = () => RAD.xf = +q('.xf').value;
75
+ const hostAv = () => q('.host')._list?.find(a => a.id === q('.host').value) || { id: 'host', name: 'Host', voice: { description: 'energetic, warm German radio host, clear diction', language: 'German' } };
76
+ const render = async () => { const pl = q('.pl'); pl.innerHTML = RAD.tracks.map((t, i) => `<li data-i="${i}"><span class="tk ${t.type}">${t.type === 'jingle' ? '🎺' : t.type === 'talk' ? '🎙' : '🎵'}</span> ${esc(t.name)} <small class="mut">${t.dur ? t.dur.toFixed(1) + ' s' : ''}</small> <button class="ib" data-a="up" aria-label="hoch">↑</button><button class="ib" data-a="dn" aria-label="runter">↓</button><button class="ib" data-a="rm" aria-label="aus Playlist entfernen">✕</button></li>`).join('') || '<small class="mut">Leer – Tracks aus dem Workspace hinzufügen oder aus Music/Mastering senden.</small>';
77
+ q('.mtr').innerHTML = RAD.tracks.map((t, i) => t.type === 'track' ? `<option value="${i}">vor: ${esc(t.name)}</option>` : '').join('');
78
+ const tot = RAD.tracks.reduce((a, t) => a + (t.dur || 0), 0); q('.tot').textContent = `${RAD.tracks.length} Elemente · ${Math.floor(tot / 60)}:${String(Math.round(tot % 60)).padStart(2, '0')} min`; window.__radio = { station: RAD.station, n: RAD.tracks.length, tracks: RAD.tracks.map(t => [t.type, t.name, +(t.dur || 0).toFixed(1)]) }; };
79
+ const add = async (t, at) => { try { t.dur = (await decodeUrl(t.url)).duration; } catch (e) { setS(el, '⚠ ' + t.name + ': nicht dekodierbar', true); return; } at == null ? RAD.tracks.push(t) : RAD.tracks.splice(at, 0, t); render(); };
80
+ q('.pl').onclick = (e) => { const b = e.target.closest('[data-a]'); if (!b) return; const i = +b.closest('li').dataset.i, T = RAD.tracks, a = b.dataset.a;
81
+ if (a === 'rm') T.splice(i, 1); if (a === 'up' && i > 0) [T[i - 1], T[i]] = [T[i], T[i - 1]]; if (a === 'dn' && i < T.length - 1) [T[i + 1], T[i]] = [T[i], T[i + 1]]; render(); };
82
+ q('.up').onchange = async () => { for (const f of q('.up').files) await add({ type: 'track', name: f.name, url: URL.createObjectURL(f), blob: f }); };
83
+ q('.wsadd').onclick = async () => { const box = q('.wspick'); if (!bucket()) return setS(el, '⚠ Bitte anmelden + Workspace verbinden', true); box.innerHTML = '<small class="mut">lade…</small>';
84
+ const fs = (await wsList('')).filter(f => isAudio(f.path) && !f.path.startsWith('.studius/')); window.__radioWs = fs.length;
85
+ box.innerHTML = fs.length ? `<div class="wsl">${fs.slice(0, 60).map(f => `<label><input type="checkbox" value="${esc(f.path)}"> ${esc(f.path)}</label>`).join('')}</div><button class="btn alt wsok">➕ Hinzufügen</button>` : '<small class="mut">Keine Audios im Workspace.</small>';
86
+ box.querySelector('.wsok')?.addEventListener('click', async () => { const sel = [...box.querySelectorAll('input:checked')].map(i => i.value); box.innerHTML = ''; for (const p of sel) await add({ type: p.includes('/jingles/') ? 'jingle' : 'track', name: p.split('/').pop(), url: wsFile(p), path: p }); setS(el, `✔ ${sel.length} aus Workspace`); }); };
87
+ q('.jgo').onclick = async (e) => { const b = e.target; b.disabled = true; const text = q('.jt').value.trim();
88
+ try { setS(el, 'Jingle: Stimme…'); const voice = text ? await Avatars.speak(hostAv(), text.slice(0, 200), { el, onStatus: m => setS(el, 'Jingle-Stimme: ' + stTxt(m)) }) : null;
89
+ let bed = null, mode = q('.bed').value; if (mode === 'gen') { setS(el, 'Jingle: Musikbett���'); bed = (await MODULES.music.actions.compose.run({ prompt: q('.bedp').value }, { status: m => setS(el, 'Musikbett: ' + stTxt(m)) })).url; } else if (mode === 'track') bed = RAD.tracks.find(t => t.type === 'track')?.url;
90
+ setS(el, 'Jingle: Mix (Ducking)…'); const buf = await mixJingle(voice, bed); const blob = toWav(buf), name = `${slug(RAD.station)}-jingle-${ts()}.wav`, u = URL.createObjectURL(blob);
91
+ RAD.buf.set(u, buf); await add({ type: 'jingle', name, url: u, blob }, 0); q('.out').innerHTML = `<audio controls src="${u}"></audio>`;
92
+ result(q('.out'), { kind: 'audio', mime: 'audio/wav', blob, url: u, name, path: `projects/radio/${slug(RAD.station)}/jingles/${name}`, studio: 'radio', prompt: text, model: 'Qwen3-TTS + TangoFlux (Mix lokal)' }); window.__jingle = { name, dur: buf.duration, bed: mode }; setS(el, `✔ Jingle ${buf.duration.toFixed(1)} s → Playlist (Position 1)`); badge(el, 'REAL'); }
93
+ catch (er) { setS(el, '⚠ ' + er.message, true); window.__jingle = { err: er.message }; } finally { b.disabled = false; } };
94
+ q('.mgo').onclick = async (e) => { const i = +q('.mtr').value, t = RAD.tracks[i]; if (!t) return setS(el, '⚠ Erst Tracks hinzufügen', true); const b = e.target; b.disabled = true; const av = hostAv();
95
+ try { setS(el, 'Moderation: Text…'); let txt = await llm(`${av.system ? 'System: ' + Avatars.persona(av) + '\n' : ''}Du bist Radiomoderator von "${RAD.station}". Schreibe EINE kurze, lockere Ansage auf Deutsch (max. 25 Wörter) für den nächsten Song "${t.name.replace(/\.\w+$/, '').replace(/[-_]/g, ' ')}". Nur die Ansage, ohne Anführungszeichen.`, { status: m => setS(el, 'Moderation: ' + stTxt(m)) });
96
+ txt = txt.replace(/^["„]|["“]$/g, '').split('\n').filter(Boolean)[0]?.slice(0, 220) || `Und jetzt auf ${RAD.station}: ${t.name}`;
97
+ setS(el, 'Moderation: Stimme…'); const u = await Avatars.speak(av, txt, { el, onStatus: m => setS(el, 'Moderation: ' + stTxt(m)) }); const name = `${slug(RAD.station)}-talk-${ts()}.wav`;
98
+ await add({ type: 'talk', name, url: u, text: txt }, i); q('.out').innerHTML = `<p class="mut">🎙 „${esc(txt)}“</p><audio controls src="${esc(u)}"></audio>`;
99
+ result(q('.out'), { kind: 'audio', url: u, name, path: `projects/radio/${slug(RAD.station)}/talk/${name}`, studio: 'radio', prompt: txt }); window.__talkRadio = { txt, i }; setS(el, '✔ Ansage eingefügt'); }
100
+ catch (er) { setS(el, '⚠ ' + er.message, true); window.__talkRadio = { err: er.message }; } finally { b.disabled = false; } };
101
+ const stop = () => { nodes.forEach(n => { try { n.stop(); } catch (e) {} }); nodes = []; clearInterval(tick); q('.np').textContent = ''; };
102
+ const play = async (live) => { stop(); if (!RAD.tracks.length) return setS(el, '⚠ Playlist leer', true); setS(el, 'Lade Audio…'); const bufs = await Promise.all(RAD.tracks.map(t => decodeUrl(t.url))); const P = plan(bufs, RAD.xf), total = P.at(-1).st + P.at(-1).dur;
103
+ ctx ||= new AudioContext(); await ctx.resume(); const from = live ? ((Date.now() - RAD.epoch) / 1000) % total : 0, t0 = ctx.currentTime + .1; nodes = schedule(ctx, bufs, P, from, t0);
104
+ tick = setInterval(() => { const pos = from + ctx.currentTime - t0; if (pos > total) { stop(); if (live) play(true); return; } const i = P.findLastIndex(p => p.st <= pos); q('.np').textContent = `${live ? '📡 LIVE · ' : ''}▶ ${RAD.tracks[i]?.name || ''} · ${Math.floor(pos / 60)}:${String(Math.floor(pos % 60)).padStart(2, '0')} / ${Math.floor(total / 60)}:${String(Math.round(total % 60)).padStart(2, '0')}`; window.__radioNow = { i, pos: +pos.toFixed(1), live }; }, 250);
105
+ setS(el, live ? `📡 Pseudo-live ab ${from.toFixed(0)} s (Epoch ${new Date(RAD.epoch).toLocaleTimeString('de-DE')})` : '▶ Sendung läuft'); };
106
+ q('.play').onclick = () => play(false); q('.live').onclick = () => play(true); q('.stop').onclick = stop; el.__stop = stop;
107
+ q('.exp').onclick = async (e) => { if (!RAD.tracks.length) return setS(el, '⚠ Playlist leer', true); const b = e.target; b.disabled = true;
108
+ try { setS(el, 'Rendere Sendung…'); const bufs = await Promise.all(RAD.tracks.map(t => decodeUrl(t.url))); const P = plan(bufs, RAD.xf), total = P.at(-1).st + P.at(-1).dur; if (total > 1800) throw new Error('max. 30 min pro Export');
109
+ const oc = new OfflineAudioContext(2, Math.ceil(total * 44100), 44100); schedule(oc, bufs, P, 0, 0); const buf = await oc.startRendering();
110
+ setS(el, 'MP3-Encoding…'); const mp3 = await toMp3(buf, 192, p => setS(el, `MP3 ${Math.round(p * 100)} %`)); const st = slug(RAD.station), base = `projects/radio/${st}/`, name = `${st}-show-${ts()}.mp3`;
111
+ const pl = { type: 'studius.radio', v: 1, station: RAD.station, epoch: RAD.epoch, crossfade: RAD.xf, total: +total.toFixed(2), host: RAD.host || null, show: base + name,
112
+ items: RAD.tracks.map((t, i) => ({ type: t.type, name: t.name, path: t.path || null, text: t.text || null, start: +P[i].st.toFixed(2), duration: +P[i].dur.toFixed(2) })) };
113
+ const m3u = '#EXTM3U\n#PLAYLIST:' + RAD.station + '\n' + pl.items.map(it => `#EXTINF:${Math.round(it.duration)},${it.name}\n${it.path || it.name}`).join('\n') + '\n';
114
+ const u = URL.createObjectURL(mp3); q('.out').innerHTML = `<audio controls src="${u}"></audio><div class="row"><button class="btn alt dmp3">⬇ MP3</button><button class="btn alt dm3u">⬇ .m3u</button></div>`;
115
+ q('.dmp3').onclick = () => dl(mp3, name); q('.dm3u').onclick = () => dl(new Blob([m3u], { type: 'audio/x-mpegurl' }), st + '.m3u');
116
+ let saved = null; if (bucket()) { setS(el, 'Speichere im Workspace…'); for (const t of RAD.tracks) if (!t.path && t.blob) { const p = base + (t.type === 'jingle' ? 'jingles/' : 'tracks/') + t.name; await upload(p, t.blob, 'radio'); t.path = p; }
117
+ pl.items = RAD.tracks.map((t, i) => ({ ...pl.items[i], path: t.path || null })); await upload(base + name, mp3, 'radio'); await saveJson(base + 'playlist.json', pl, 'radio'); await upload(base + 'playlist.m3u', new Blob([m3u], { type: 'audio/x-mpegurl' }), 'radio'); saved = base; }
118
+ result(q('.out'), { kind: 'audio', mime: 'audio/mpeg', blob: mp3, url: u, name, path: base + name, studio: 'radio', prompt: RAD.station });
119
+ window.__radioExport = { total: +total.toFixed(1), bytes: mp3.size, saved, items: pl.items.length }; setS(el, `✔ Sendung ${Math.floor(total / 60)}:${String(Math.round(total % 60)).padStart(2, '0')} min · ${(mp3.size / 1e6).toFixed(1)} MB${saved ? ' · ' + saved : ''}`); badge(el, 'REAL'); }
120
+ catch (er) { setS(el, '⚠ ' + er.message, true); window.__radioExport = { err: er.message }; } finally { b.disabled = false; } };
121
+ el.__addAudio = (t) => add(t); render();
122
+ }, accept: async (el, a) => { await el.__addAudio({ type: /jingle/i.test(a.name || '') ? 'jingle' : 'track', name: a.name || 'audio.wav', url: a.blob ? URL.createObjectURL(a.blob) : a.url, blob: a.blob, path: a.path }); return true; } });
123
+
124
+ /* =================== SOCIAL / MARKETING STUDIO =================== */
125
+ const PLAT = { ig: { n: 'Instagram Post 4:5', w: 1080, h: 1350, tag: 'Instagram' }, sq: { n: 'Quadrat 1:1', w: 1080, h: 1080, tag: 'Instagram' }, story: { n: 'Story/Reel/TikTok 9:16', w: 1080, h: 1920, tag: 'TikTok' },
126
+ x: { n: 'X / Twitter 16:9', w: 1600, h: 900, tag: 'X' }, li: { n: 'LinkedIn 1.91:1', w: 1200, h: 627, tag: 'LinkedIn' }, yt: { n: 'YouTube Thumbnail', w: 1280, h: 720, tag: 'YouTube' } };
127
+ const CAPS = ['Instagram', 'TikTok', 'X', 'LinkedIn', 'YouTube'];
128
+ const SOC = { img: null, imgName: '', video: null, brief: 'Neuer Lofi-Track der STUDIUS-Bienen – jetzt im Radio', head: 'Neu: Honey Lofi', brand: { name: 'STUDIUS', handle: '@einswarm', c1: '#f2c94c', c2: '#0b0b0b', cta: 'Jetzt reinhören', link: '' }, plats: ['ig', 'story', 'x'], caps: {}, mock: {}, sched: null };
129
+ export function renderPost(img, P, { head, brand }) { // brand mockup for one platform → canvas
130
+ const c = document.createElement('canvas'); c.width = P.w; c.height = P.h; const x = c.getContext('2d'), s = Math.min(P.w, P.h) / 1080, tall = P.h / P.w > 1.2;
131
+ const g = x.createLinearGradient(0, 0, P.w, P.h); g.addColorStop(0, brand.c2); g.addColorStop(1, '#1a1406'); x.fillStyle = g; x.fillRect(0, 0, P.w, P.h);
132
+ const bar = 120 * s, imgH = tall ? P.h * .62 : P.h - bar, imgW = tall ? P.w : P.w * .6; if (img) cover(x, img, 0, 0, imgW, imgH);
133
+ x.fillStyle = brand.c1; x.fillRect(0, tall ? imgH : 0, tall ? P.w : 0, tall ? 10 * s : 0); if (!tall) x.fillRect(imgW, 0, 8 * s, P.h - bar);
134
+ x.fillStyle = '#fff'; x.textBaseline = 'top'; x.font = `800 ${(tall ? 92 : 64) * s}px system-ui, sans-serif`; const tx = tall ? 60 * s : imgW + 40 * s, tw = tall ? P.w - 120 * s : P.w - imgW - 80 * s, ty = tall ? imgH + 60 * s : 60 * s;
135
+ wrap(x, head, tx, ty, tw, (tall ? 104 : 74) * s, 3);
136
+ x.fillStyle = brand.c1; x.fillRect(0, P.h - bar, P.w, bar); x.fillStyle = brand.c2; x.font = `700 ${46 * s}px system-ui, sans-serif`; x.textBaseline = 'middle'; x.fillText(brand.name + ' ' + brand.handle, 40 * s, P.h - bar / 2);
137
+ const cta = brand.cta + ' →'; x.font = `800 ${40 * s}px system-ui, sans-serif`; const cw = x.measureText(cta).width + 50 * s; x.fillStyle = brand.c2; x.beginPath(); x.roundRect(P.w - cw - 30 * s, P.h - bar + 22 * s, cw, bar - 44 * s, 30 * s); x.fill(); x.fillStyle = brand.c1; x.fillText(cta, P.w - cw - 5 * s, P.h - bar / 2);
138
+ return c; }
139
+ function parseCaps(t) { const out = {}; let cur = null; for (const line of t.split('\n')) { const m = line.match(/^\W*(Instagram|TikTok|X|Twitter|LinkedIn|YouTube)\W*[::]\s*(.*)$/i); if (m) { cur = /twitter/i.test(m[1]) ? 'X' : CAPS.find(c => c.toLowerCase() === m[1].toLowerCase()); out[cur] = m[2]; } else if (cur && line.trim()) out[cur] += '\n' + line.trim(); } return out; }
140
+ const icsDate = (d) => d.toISOString().replace(/[-:]/g, '').replace(/\.\d+/, '');
141
+ STUDIOS.push({ id: 'social', cat: 'Community', icon: '📣', name: 'Social Studio', like: 'Post-Composer & Marketing', real: 'API', accepts: ['image', 'video', 'text'], build(el) {
142
+ el.innerHTML = `<div class="row" style="margin:0 0 6px"><span class="badge real">REAL</span><span class="stat">Post-Composer: Captions · Branding · Formate · Plan (STUDIUS postet nie selbst)</span></div>
143
+ <label class="fl">Briefing<textarea class="br" rows="2" aria-label="Briefing"></textarea></label><label class="fl">Headline<input class="hd" aria-label="Headline"></label>
144
+ <fieldset class="grp"><legend>Branding</legend><div class="row"><input class="bn" aria-label="Marke" style="width:30%"><input class="bh" aria-label="Handle" style="width:30%"><input type="color" class="c1" aria-label="Akzentfarbe"><input type="color" class="c2" aria-label="Grundfarbe"></div><div class="row"><input class="bc" aria-label="Call to Action" style="width:40%"><input class="bl" aria-label="Link (z. B. Shop)" placeholder="Link (Shop/Track)" style="width:55%"></div></fieldset>
145
+ <fieldset class="grp"><legend>Visual</legend><div class="row"><label class="btn alt">🖼 Bild<input type="file" accept="image/*" hidden class="ui"></label><button class="btn alt gi">✨ Bild aus Briefing</button><span class="imn mut">kein Bild</span></div><div class="vrow"></div></fieldset>
146
+ <fieldset class="grp"><legend>Formate</legend><div class="pls">${Object.entries(PLAT).map(([k, p]) => `<label><input type="checkbox" value="${k}"> ${p.n} <small class="mut">${p.w}×${p.h}</small></label>`).join('')}</div></fieldset>
147
+ <div class="row"><button class="btn cap">✍ Captions & Hashtags</button><button class="btn alt mk">🖼 Mockups rendern</button><button class="btn alt sva">💾 Kampagne speichern</button></div>
148
+ <div class="caps"></div><div class="mocks"></div>
149
+ <fieldset class="grp"><legend>Redaktionsplan</legend><div class="row"><input type="datetime-local" class="sd" aria-label="Termin"><select class="sp" aria-label="Plattform">${CAPS.map(c => `<option>${c}</option>`).join('')}</select><button class="btn alt sadd">➕ Einplanen</button><button class="btn alt ics">⬇ Kalender (.ics)</button></div><table class="sched"></table><small class="mut">Status „Freigegeben“ ist nur eine Markierung – gepostet wird manuell bzw. erst nach deiner ausdrücklichen Freigabe pro Post.</small></fieldset>
150
+ <div class="credit">Captions: ${hf(CHAT)} · Visual: ${hf(FLUX)} · Mockups & Formate lokal (Canvas), Video-Formate per Server-ffmpeg · gespeichert in <code>projects/social/</code></div>`;
151
+ keep(el); const q = (s) => el.querySelector(s); const B = SOC.brand; let img = null;
152
+ q('.br').value = SOC.brief; q('.hd').value = SOC.head; q('.bn').value = B.name; q('.bh').value = B.handle; q('.c1').value = B.c1; q('.c2').value = B.c2; q('.bc').value = B.cta; q('.bl').value = B.link;
153
+ el.querySelectorAll('.pls input').forEach(i => { i.checked = SOC.plats.includes(i.value); });
154
+ const read = () => { SOC.brief = q('.br').value.trim(); SOC.head = q('.hd').value.trim(); Object.assign(B, { name: q('.bn').value.trim(), handle: q('.bh').value.trim(), c1: q('.c1').value, c2: q('.c2').value, cta: q('.bc').value.trim(), link: q('.bl').value.trim() }); SOC.plats = [...el.querySelectorAll('.pls input:checked')].map(i => i.value); };
155
+ const setImg = async (blob, name) => { SOC.img = blob; SOC.imgName = name || 'visual'; img = await loadImg(URL.createObjectURL(blob)); q('.imn').textContent = '🖼 ' + SOC.imgName; };
156
+ const setVideo = (u, name) => { SOC.video = { url: u, name }; const v = q('.vrow'); v.innerHTML = `<video controls playsinline src="${esc(u)}" style="max-height:200px"></video>`; reframeRow(v, () => SOC.video.url, { name: name || 'social', studio: 'social', prompt: SOC.brief }); };
157
+ el.__setImg = setImg; el.__setVideo = setVideo; if (SOC.img) setImg(SOC.img, SOC.imgName); if (SOC.video) setVideo(SOC.video.url, SOC.video.name);
158
+ q('.ui').onchange = () => q('.ui').files[0] && setImg(q('.ui').files[0], q('.ui').files[0].name);
159
+ q('.gi').onclick = async (e) => { read(); e.target.disabled = true; try { const a = await MODULES.image.actions.generate.run({ prompt: `social media key visual, ${SOC.brief}, bold, clean composition, no text` }, { status: m => setS(el, 'Bild: ' + stTxt(m)) }); await setImg(await toBlob(a.url), a.name); setS(el, '✔ Visual erzeugt'); } catch (er) { setS(el, '⚠ ' + er.message, true); } finally { e.target.disabled = false; } };
160
+ const showCaps = () => { q('.caps').innerHTML = Object.keys(SOC.caps).length ? CAPS.filter(c => SOC.caps[c] != null).map(c => `<label class="fl">${c} <small class="mut cc" data-c="${c}"></small><textarea rows="3" data-c="${c}">${esc(SOC.caps[c])}</textarea></label>`).join('') : '';
161
+ const lim = { X: 280, Instagram: 2200, TikTok: 2200, LinkedIn: 3000, YouTube: 5000 }; const cnt = () => q('.caps').querySelectorAll('textarea').forEach(t => { SOC.caps[t.dataset.c] = t.value; const n = t.value.length, L = lim[t.dataset.c]; const s = q(`.cc[data-c="${t.dataset.c}"]`); s.textContent = `${n}/${L} · ${(t.value.match(/#\w+/g) || []).length} #`; s.style.color = n > L ? '#e66' : ''; });
162
+ q('.caps').oninput = cnt; keep(q('.caps')); cnt(); };
163
+ q('.cap').onclick = async (e) => { read(); e.target.disabled = true;
164
+ try { const t = await llm(`Du bist Social-Media-Manager der Marke ${B.name} (${B.handle}). Thema: ${SOC.brief}. Call-to-Action: ${B.cta}${B.link ? ' (' + B.link + ')' : ''}.
165
+ Schreibe je eine Caption auf Deutsch mit passenden Hashtags am Ende, genau in diesem Format (eine Zeile pro Plattform):
166
+ Instagram: <Caption, 2-3 Sätze, Emojis, 6-10 Hashtags>
167
+ TikTok: <kurz, Hook, 3-5 Hashtags>
168
+ X: <max. 240 Zeichen inkl. 2 Hashtags>
169
+ LinkedIn: <professionell, 2-3 Sätze, 3 Hashtags>
170
+ YouTube: <Titel-tauglicher Satz + 3 Hashtags>`, { status: m => setS(el, 'Captions: ' + stTxt(m)) });
171
+ let caps = parseCaps(t); if (Object.keys(caps).length < 2) caps = Object.fromEntries(CAPS.map(c => [c, t])); if (caps.X && caps.X.length > 280) caps.X = caps.X.slice(0, 277) + '…';
172
+ SOC.caps = caps; showCaps(); window.__social = { ...(window.__social || {}), caps: Object.keys(caps), sample: (caps.Instagram || '').slice(0, 160) };
173
+ result(q('.caps'), { kind: 'text', mime: 'text/plain', text: CAPS.filter(c => caps[c]).map(c => c + ': ' + caps[c]).join('\n\n'), name: `captions-${ts()}.txt`, path: `projects/social/${slug(SOC.head)}/captions.txt`, studio: 'social', prompt: SOC.brief }); setS(el, `✔ Captions für ${Object.keys(caps).length} Plattformen`); badge(el, 'REAL'); }
174
+ catch (er) { setS(el, '⚠ ' + er.message, true); } finally { e.target.disabled = false; } };
175
+ q('.mk').onclick = async () => { read(); if (!SOC.plats.length) return setS(el, '⚠ Format wählen', true); SOC.mock = {}; const box = q('.mocks'); box.innerHTML = '<div class="mockg"></div>'; const g = box.firstChild;
176
+ for (const k of SOC.plats) { const c = renderPost(img, PLAT[k], { head: SOC.head, brand: B }); const blob = await canvasBlob(c); SOC.mock[k] = blob; const u = URL.createObjectURL(blob);
177
+ const fig = document.createElement('figure'); fig.innerHTML = `<img src="${u}" alt="${esc(PLAT[k].n)}"><figcaption>${esc(PLAT[k].n)} · ${PLAT[k].w}×${PLAT[k].h}</figcaption>`; g.append(fig);
178
+ result(fig, { kind: 'image', mime: 'image/png', blob, url: u, name: `${slug(SOC.head)}-${k}.png`, path: `projects/social/${slug(SOC.head)}/${k}-${PLAT[k].w}x${PLAT[k].h}.png`, studio: 'social', prompt: SOC.head }); }
179
+ window.__social = { ...(window.__social || {}), mock: SOC.plats.map(k => [k, PLAT[k].w, PLAT[k].h, SOC.mock[k].size]) }; setS(el, `✔ ${SOC.plats.length} Formate gerendert`); };
180
+ q('.sva').onclick = async (e) => { read(); e.target.disabled = true; try { const base = `projects/social/${slug(SOC.head)}/`; const files = [];
181
+ for (const [k, b] of Object.entries(SOC.mock)) { const p = `${base}${k}-${PLAT[k].w}x${PLAT[k].h}.png`; await upload(p, b, 'social'); files.push(p); }
182
+ if (SOC.img) { const p = base + 'visual.' + ((SOC.img.type || 'image/png').split('/')[1] || 'png').replace('jpeg', 'jpg'); await upload(p, SOC.img, 'social'); files.push(p); }
183
+ await saveJson(base + 'campaign.json', { type: 'studius.social', v: 1, brief: SOC.brief, head: SOC.head, brand: B, captions: SOC.caps, formats: Object.keys(SOC.mock), files, updated: Date.now() }, 'social');
184
+ window.__socialSaved = { base, files: files.length }; setS(el, `✔ Kampagne gespeichert: ${base} (${files.length} Dateien)`); } catch (er) { setS(el, '⚠ ' + er.message, true); } finally { e.target.disabled = false; } };
185
+ // schedule (stored in workspace; never posts)
186
+ const SP = 'projects/social/schedule.json'; const showSched = () => { const t = q('.sched'); t.innerHTML = (SOC.sched || []).length ? '<tr><th>Termin</th><th>Plattform</th><th>Post</th><th>Status</th></tr>' + SOC.sched.map((r, i) => `<tr><td>${esc(new Date(r.at).toLocaleString('de-DE', { dateStyle: 'short', timeStyle: 'short' }))}</td><td>${esc(r.platform)}</td><td>${esc(r.head)}</td><td><button class="ib st" data-i="${i}" aria-label="Status umschalten">${r.status === 'freigegeben' ? '✅ Freigegeben' : '📝 Entwurf'}</button><button class="ib rm" data-i="${i}" aria-label="aus Plan entfernen">✕</button></td></tr>`).join('') : '<tr><td class="mut">Noch nichts geplant.</td></tr>'; window.__sched = (SOC.sched || []).map(r => [r.platform, r.status]); };
187
+ const saveSched = async () => { showSched(); if (bucket()) try { await saveJson(SP, { type: 'studius.schedule', v: 1, posts: SOC.sched }, 'social'); window.__schedSaved = SOC.sched.length; } catch (e) { setS(el, '⚠ ' + e.message, true); } };
188
+ (async () => { if (!SOC.sched) SOC.sched = (await wsJson(SP, { posts: [] })).posts || []; showSched(); })();
189
+ const d0 = new Date(Date.now() + 864e5); d0.setHours(18, 0, 0, 0); q('.sd').value = new Date(d0 - d0.getTimezoneOffset() * 6e4).toISOString().slice(0, 16);
190
+ q('.sadd').onclick = () => { read(); const pf = q('.sp').value; SOC.sched.push({ id: 'p' + Date.now().toString(36), at: new Date(q('.sd').value).getTime(), platform: pf, head: SOC.head, caption: SOC.caps[pf] || '', asset: `projects/social/${slug(SOC.head)}/`, status: 'entwurf' }); SOC.sched.sort((a, b) => a.at - b.at); saveSched(); };
191
+ q('.sched').onclick = (e) => { const b = e.target.closest('button'); if (!b) return; const i = +b.dataset.i; if (b.classList.contains('rm')) SOC.sched.splice(i, 1); else SOC.sched[i].status = SOC.sched[i].status === 'freigegeben' ? 'entwurf' : 'freigegeben'; saveSched(); };
192
+ q('.ics').onclick = () => { const ev = SOC.sched.map(r => `BEGIN:VEVENT\r\nUID:${r.id}@studius\r\nDTSTAMP:${icsDate(new Date())}\r\nDTSTART:${icsDate(new Date(r.at))}\r\nDURATION:PT15M\r\nSUMMARY:${(r.platform + ': ' + r.head).replace(/[,;]/g, ' ')} (${r.status})\r\nDESCRIPTION:${(r.caption || '').replace(/\n/g, '\\n').replace(/[,;]/g, ' ').slice(0, 900)}\r\nEND:VEVENT`).join('\r\n');
193
+ dl(new Blob([`BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//STUDIUS//Social//DE\r\n${ev}\r\nEND:VCALENDAR\r\n`], { type: 'text/calendar' }), 'studius-redaktionsplan.ics'); };
194
+ if (SOC.caps && Object.keys(SOC.caps).length) showCaps();
195
+ }, accept: async (el, a) => { if (a.kind === 'video') { el.__setVideo(a.blob ? URL.createObjectURL(a.blob) : a.url, a.name); return true; }
196
+ if (a.kind === 'text') { const t = a.text ?? await (await toBlob(a.url)).text(); el.querySelector('.br').value = t.slice(0, 600); return true; }
197
+ const b = a.blob || await toBlob(a.url); await el.__setImg(b, a.name); if (a.prompt) el.querySelector('.hd').value ||= a.prompt.slice(0, 60); if (a.shop) { el.querySelector('.br').value = a.shop.brief; el.querySelector('.hd').value = a.shop.head; if (a.shop.link) el.querySelector('.bl').value = a.shop.link; } return true; } });
198
+
199
+ /* =================== SHOP STUDIO (Jenniisdriptees link-shop) =================== */
200
+ // Product types / pricing mirror the JDT design-studio domain (shared/domain.ts): base cost + shipping, margin, artist royalty, 19 % VAT, ,99 rounding.
201
+ const PT = { TEE: { l: 'T-Shirt', base: 1150, ship: 399, sizes: ['S', 'M', 'L', 'XL', '2XL'], colors: [['Schwarz', '#111111', 'BLK'], ['Weiß', '#f5f5f5', 'WHT'], ['Sand', '#d8c8a8', 'SND'], ['Navy', '#1f2a44', 'NVY']] },
202
+ HOD: { l: 'Hoodie', base: 2450, ship: 499, sizes: ['S', 'M', 'L', 'XL', '2XL'], colors: [['Schwarz', '#111111', 'BLK'], ['Grau meliert', '#9a9a9a', 'GRY'], ['Weiß', '#f5f5f5', 'WHT']] },
203
+ MUG: { l: 'Tasse 11oz', base: 650, ship: 499, sizes: ['11oz'], colors: [['Weiß', '#ffffff', 'WHT']] }, PST: { l: 'Poster', base: 900, ship: 599, sizes: ['A3', 'A2'], colors: [['Matt', '#ffffff', 'MAT']] },
204
+ STK: { l: 'Sticker', base: 250, ship: 199, sizes: ['7.5cm', '10cm'], colors: [['Weiß', '#ffffff', 'WHT']] } };
205
+ const LINES = { OWN: 'Eigene Produkte & Logos', ART: 'Artist-Merch', APP: 'App-/Agenten-Merch' };
206
+ const STAT = { entwurf: '📝 Entwurf', mockup: '🖼 Mockup', review: '🔎 Review', freigegeben: '✅ Freigegeben (Rob)' };
207
+ const slugCode = (s, m = 8) => (s || '').replace(/[äöüßÄÖÜ]/g, c => ({ ä: 'AE', ö: 'OE', ü: 'UE', ß: 'SS', Ä: 'AE', Ö: 'OE', Ü: 'UE' })[c]).toUpperCase().replace(/[^A-Z0-9]/g, '').slice(0, m) || 'X';
208
+ export function suggestPrice({ base, ship, margin, royalty = 0, vat = 19, inclShip = true }) { const share = Math.min(.9, (margin + royalty) / 100), cost = base + (inclShip ? ship : 0), net = Math.round(cost / (1 - share)), gross = Math.round(net * (1 + vat / 100)), sug = Math.ceil(gross / 100) * 100 - 1; return { cost, net, gross, sug, profit: Math.round(sug / (1 + vat / 100) - cost) }; }
209
+ const eur = (c) => (c / 100).toLocaleString('de-DE', { style: 'currency', currency: 'EUR' });
210
+ function tee(x, w, h, col, hood) { x.fillStyle = col; x.strokeStyle = 'rgba(0,0,0,.25)'; x.lineWidth = 3; x.beginPath(); const cx = w / 2;
211
+ x.moveTo(cx - 120, 140); x.lineTo(cx - 250, 200); x.lineTo(cx - 330, 360); x.lineTo(cx - 240, 400); x.lineTo(cx - 200, 330); x.lineTo(cx - 200, h - 120); x.lineTo(cx + 200, h - 120); x.lineTo(cx + 200, 330); x.lineTo(cx + 240, 400); x.lineTo(cx + 330, 360); x.lineTo(cx + 250, 200); x.lineTo(cx + 120, 140);
212
+ if (hood) { x.quadraticCurveTo(cx + 120, 40, cx, 40); x.quadraticCurveTo(cx - 120, 40, cx - 120, 140); } else x.quadraticCurveTo(cx, 220, cx - 120, 140); x.closePath(); x.fill(); x.stroke();
213
+ if (hood) { x.fillStyle = 'rgba(0,0,0,.18)'; x.beginPath(); x.ellipse(cx, 150, 90, 60, 0, 0, 7); x.fill(); x.fillRect(cx - 110, h - 330, 220, 120); } }
214
+ export async function mockup(design, type, color) { const w = 900, h = 1000, c = document.createElement('canvas'); c.width = w; c.height = h; const x = c.getContext('2d');
215
+ const bg = x.createLinearGradient(0, 0, 0, h); bg.addColorStop(0, '#efe9dc'); bg.addColorStop(1, '#cfc6b2'); x.fillStyle = bg; x.fillRect(0, 0, w, h); x.fillStyle = 'rgba(0,0,0,.12)'; x.beginPath(); x.ellipse(w / 2, h - 90, 300, 30, 0, 0, 7); x.fill();
216
+ const img = design ? await loadImg(design) : null; const put = (X, Y, W, H) => { if (img) { x.save(); x.globalAlpha = .95; cover(x, img, X, Y, W, H); x.restore(); } };
217
+ if (type === 'TEE' || type === 'HOD') { tee(x, w, h, color, type === 'HOD'); put(w / 2 - 130, type === 'HOD' ? 290 : 260, 260, 300); }
218
+ else if (type === 'MUG') { x.fillStyle = '#fff'; x.strokeStyle = 'rgba(0,0,0,.2)'; x.lineWidth = 4; x.beginPath(); x.roundRect(220, 280, 380, 460, 30); x.fill(); x.stroke(); x.lineWidth = 40; x.strokeStyle = '#f4f4f4'; x.beginPath(); x.ellipse(620, 500, 90, 120, 0, -1.3, 1.3); x.stroke(); put(260, 360, 300, 280); }
219
+ else if (type === 'PST') { x.fillStyle = '#222'; x.fillRect(205, 105, 490, 690); x.fillStyle = '#fff'; x.fillRect(225, 125, 450, 650); put(255, 155, 390, 590); }
220
+ else { x.fillStyle = '#fff'; x.shadowColor = 'rgba(0,0,0,.25)'; x.shadowBlur = 20; x.beginPath(); x.arc(w / 2, 480, 290, 0, 7); x.fill(); x.shadowBlur = 0; if (img) { x.save(); x.beginPath(); x.arc(w / 2, 480, 262, 0, 7); x.clip(); cover(x, img, w / 2 - 262, 218, 524, 524); x.restore(); } }
221
+ return c; }
222
+ const SHOP = { design: null, designName: '', p: { title: 'Golden Bee Tee', line: 'OWN', artist: 'Jenni', type: 'TEE', colors: ['BLK', 'SND'], margin: 35, royalty: 0, inclShip: true, desc: '', tags: [], link: '', status: 'entwurf' }, mocks: {}, list: null };
223
+ STUDIOS.push({ id: 'shop', cat: 'Community', icon: '🛍', name: 'Shop Studio', like: 'Jenniisdriptees POD-Entwürfe', real: 'API', accepts: ['image', 'text'], build(el) {
224
+ el.innerHTML = `<div class="row" style="margin:0 0 6px"><span class="badge real">REAL</span><span class="stat">Produktentwürfe für Jenniisdriptees (Print-on-Demand) – keine Änderungen am echten Shop</span></div>
225
+ <fieldset class="grp"><legend>Motiv</legend><div class="row"><label class="btn alt">🖼 Motiv<input type="file" accept="image/*" hidden class="ui"></label><input class="gp" aria-label="Motiv-Prompt" value="golden honey bee emblem, bold vector streetwear graphic, drip style, isolated, flat colors"><button class="btn alt gi">✨ Motiv</button></div><span class="dn mut">kein Motiv</span></fieldset>
226
+ <fieldset class="grp"><legend>Artikel</legend><div class="row"><input class="ti" aria-label="Titel" style="width:45%"><select class="ln" aria-label="Linie">${Object.entries(LINES).map(([k, v]) => `<option value="${k}">${k} · ${v}</option>`).join('')}</select><input class="ar" aria-label="Künstler" style="width:20%"></div>
227
+ <div class="row"><select class="ty" aria-label="Produkttyp">${Object.entries(PT).map(([k, v]) => `<option value="${k}">${v.l}</option>`).join('')}</select><span class="cols"></span></div>
228
+ <div class="row"><label>Marge <input type="number" class="mg" min="0" max="80" style="width:60px"> %</label><label>Künstler <input type="number" class="ry" min="0" max="50" style="width:60px"> %</label><label><input type="checkbox" class="is"> Versand einpreisen</label></div><div class="price"></div>
229
+ <div class="row"><input class="lk" aria-label="Checkout-/Produktlink (JDT-Shop)" placeholder="Checkout-/Produktlink im JDT-Shop (optional)" style="width:100%"></div></fieldset>
230
+ <div class="row"><button class="btn mk">🖼 Mockups</button><button class="btn alt tx">✍ Beschreibung & Tags</button></div><div class="mocks"></div>
231
+ <label class="fl">Beschreibung<textarea class="ds" rows="4" aria-label="Beschreibung"></textarea></label><label class="fl">Tags (max. 13) <small class="tc mut"></small><input class="tg" aria-label="Tags"></label>
232
+ <div class="row"><span class="sts"></span><button class="btn alt nx">→ Nächster Status</button><button class="btn psv">💾 Entwurf speichern</button><button class="btn alt so" title="Mockup + Text an Social Studio">📣 An Social Studio</button></div>
233
+ <small class="mut">Freigabe-Workflow wie im JDT-Studio: Entwurf → Mockup → Review → <b>Freigabe durch Rob</b>. Veröffentlichen (Printify/Shop) passiert nur dort und nur nach Freigabe – STUDIUS ändert keinen Shop.</small>
234
+ <fieldset class="grp"><legend>Link-Shop (Workspace <code>projects/shop/products.json</code>)</legend><div class="grid"></div></fieldset>
235
+ <div class="credit">Motiv: ${hf(FLUX)} · Texte: ${hf(CHAT)} · Mockups & Preislogik lokal (JDT-Domänenmodell: Basis + Versand, Marge, Künstleranteil, 19 % MwSt, ,99)</div>`;
236
+ keep(el); const q = (s) => el.querySelector(s); const P = SHOP.p;
237
+ const fill = () => { q('.ti').value = P.title; q('.ln').value = P.line; q('.ar').value = P.artist; q('.ty').value = P.type; q('.mg').value = P.margin; q('.ry').value = P.royalty; q('.is').checked = P.inclShip; q('.ds').value = P.desc; q('.tg').value = P.tags.join(', '); q('.lk').value = P.link; cols(); price(); stat(); };
238
+ const read = () => { Object.assign(P, { title: q('.ti').value.trim(), line: q('.ln').value, artist: q('.ar').value.trim(), type: q('.ty').value, margin: +q('.mg').value || 0, royalty: +q('.ry').value || 0, inclShip: q('.is').checked, desc: q('.ds').value.trim(), link: q('.lk').value.trim(), tags: q('.tg').value.split(',').map(s => s.trim().replace(/^#/, '')).filter(Boolean).slice(0, 13) }); P.colors = [...el.querySelectorAll('.cols input:checked')].map(i => i.value); if (!P.colors.length) P.colors = [PT[P.type].colors[0][2]]; };
239
+ const cols = () => { const T = PT[q('.ty').value]; q('.cols').innerHTML = T.colors.map(([n, h, c]) => `<label title="${n}"><input type="checkbox" value="${c}" ${P.colors.includes(c) ? 'checked' : ''}><i class="sw" style="background:${h}"></i>${n}</label>`).join(''); };
240
+ const price = () => { read(); const T = PT[P.type], r = suggestPrice({ base: T.base, ship: T.ship, margin: P.margin, royalty: P.royalty, inclShip: P.inclShip }); P.price = r.sug; P.sku = `JDT-${P.line}-${P.type}-${slugCode(P.title)}-001`;
241
+ q('.price').innerHTML = `<b>${eur(r.sug)}</b> <small class="mut">inkl. 19 % MwSt · Kosten ${eur(r.cost)} · netto ${eur(r.net)} · Gewinn/Stk ${eur(r.profit)} · SKU ${esc(P.sku)}</small>`; q('.tc').textContent = `${P.tags.length}/13`; window.__shopPrice = { type: P.type, ...r, sku: P.sku }; };
242
+ const stat = () => { q('.sts').textContent = STAT[P.status]; q('.nx').disabled = P.status === 'freigegeben'; q('.nx').textContent = P.status === 'review' ? '✅ Freigabe durch Rob' : '→ Nächster Status'; };
243
+ el.addEventListener('input', (e) => { if (e.target.closest('.grp') && !e.target.matches('.gp,.ui')) price(); }); el.addEventListener('change', (e) => { if (e.target.matches('.ty')) { P.type = e.target.value; P.colors = [PT[P.type].colors[0][2]]; cols(); } price(); });
244
+ const setDesign = async (blob, name) => { SHOP.design = blob; SHOP.designName = name || 'design'; q('.dn').innerHTML = `<img src="${URL.createObjectURL(blob)}" alt="Motiv" style="height:60px;vertical-align:middle"> ${esc(SHOP.designName)}`; }; el.__setDesign = setDesign; if (SHOP.design) setDesign(SHOP.design, SHOP.designName);
245
+ q('.ui').onchange = () => q('.ui').files[0] && setDesign(q('.ui').files[0], q('.ui').files[0].name);
246
+ q('.gi').onclick = async (e) => { e.target.disabled = true; try { const a = await MODULES.image.actions.generate.run({ prompt: q('.gp').value }, { status: m => setS(el, 'Motiv: ' + stTxt(m)) }); await setDesign(await toBlob(a.url), a.name); setS(el, '✔ Motiv erzeugt'); } catch (er) { setS(el, '⚠ ' + er.message, true); } finally { e.target.disabled = false; } };
247
+ q('.mk').onclick = async () => { read(); if (!SHOP.design) return setS(el, '⚠ Erst Motiv wählen/erzeugen', true); const T = PT[P.type], du = URL.createObjectURL(SHOP.design), g = q('.mocks'); g.innerHTML = '<div class="mockg"></div>'; SHOP.mocks = {};
248
+ for (const code of P.colors) { const [n, hex] = T.colors.find(c => c[2] === code); const c = await mockup(du, P.type, hex), blob = await canvasBlob(c); SHOP.mocks[code] = blob; const u = URL.createObjectURL(blob);
249
+ const fig = document.createElement('figure'); fig.innerHTML = `<img src="${u}" alt="Mockup ${esc(T.l)} ${esc(n)}"><figcaption>${esc(T.l)} · ${esc(n)}</figcaption>`; g.firstChild.append(fig);
250
+ result(fig, { kind: 'image', mime: 'image/png', blob, url: u, name: `${slug(P.title)}-${P.type}-${code}.png`, path: `projects/shop/${slug(P.title)}/mockup-${P.type}-${code}.png`, studio: 'shop', prompt: P.title, shop: { brief: `${P.title} – ${T.l} von Jenniisdriptees, ${eur(P.price)}`, head: P.title, link: P.link } }); }
251
+ if (P.status === 'entwurf') P.status = 'mockup'; stat(); window.__shopMock = { type: P.type, colors: P.colors, n: Object.keys(SHOP.mocks).length }; setS(el, `✔ ${P.colors.length} Mockup(s)`); };
252
+ q('.tx').onclick = async (e) => { read(); e.target.disabled = true;
253
+ try { const t = await llm(`Du schreibst Produkttexte für die Streetwear-/Print-on-Demand-Marke Jenniisdriptees. Produkt: ${PT[P.type].l} "${P.title}" (Linie: ${LINES[P.line]}${P.artist ? ', Künstler: ' + P.artist : ''}). Motiv: ${q('.gp').value}.
254
+ Antworte genau so:
255
+ BESCHREIBUNG: <3-4 Sätze, Deutsch, verkaufsstark, Material-/Druckhinweis allgemein halten>
256
+ TAGS: <13 kurze Tags, kommagetrennt, ohne #>`, { status: m => setS(el, 'Text: ' + stTxt(m)) });
257
+ const d = (t.match(/BESCHREIBUNG\s*:\s*([\s\S]*?)(?:\n\s*TAGS|$)/i)?.[1] || t).trim(), tg = (t.match(/TAGS\s*:\s*(.*)/i)?.[1] || '').split(/[,;]/).map(s => s.trim().replace(/^#/, '')).filter(Boolean).slice(0, 13);
258
+ q('.ds').value = d; q('.tg').value = tg.join(', '); price(); window.__shopText = { len: d.length, tags: tg.length }; setS(el, `✔ Beschreibung + ${tg.length} Tags`); badge(el, 'REAL'); }
259
+ catch (er) { setS(el, '⚠ ' + er.message, true); } finally { e.target.disabled = false; } };
260
+ q('.nx').onclick = () => { const o = Object.keys(STAT); if (P.status === 'review' && !confirm('Freigabe durch Rob für diesen Entwurf setzen? (Veröffentlicht nichts.)')) return; P.status = o[Math.min(o.length - 1, o.indexOf(P.status) + 1)]; if (P.status === 'freigegeben') P.approved = { by: 'Rob', at: Date.now() }; stat(); };
261
+ const PJ = 'projects/shop/products.json';
262
+ const grid = async (reload) => { if (reload || !SHOP.list) SHOP.list = (await wsJson(PJ, { products: [] })).products || []; const g = q('.grid');
263
+ g.innerHTML = SHOP.list.length ? SHOP.list.map(p => `<div class="pcard">${p.mockups?.[0] ? `<img loading="lazy" src="${esc(wsFile(p.mockups[0]))}" alt="${esc(p.title)}">` : ''}<b>${esc(p.title)}</b><small>${esc(PT[p.type]?.l || p.type)} · ${eur(p.price)} · ${STAT[p.status] || p.status}</small>${p.link ? `<a href="${esc(p.link)}" target="_blank" rel="noopener">Zum Shop ↗</a>` : '<small class="mut">kein Shop-Link</small>'}<button class="ib ld" data-id="${esc(p.id)}">✎ laden</button></div>`).join('') : '<small class="mut">Noch keine Produkte im Workspace.</small>';
264
+ window.__shopList = SHOP.list.map(p => [p.id, p.status, p.price]); };
265
+ q('.grid').onclick = (e) => { const b = e.target.closest('.ld'); if (!b) return; const p = SHOP.list.find(x => x.id === b.dataset.id); if (!p) return; Object.assign(P, structuredClone(p)); fill(); setS(el, 'Geladen: ' + p.title); };
266
+ q(".psv").onclick = async (e) => { read(); price(); if (!bucket()) return setS(el, '⚠ Bitte anmelden + Workspace verbinden', true); e.target.disabled = true;
267
+ try { const id = P.id ||= slug(P.title) + '-' + P.type.toLowerCase(), base = `projects/shop/${slug(P.title)}/`, mocks = [];
268
+ if (SHOP.design) { const p = base + 'design.' + ((SHOP.design.type || 'image/png').split('/')[1] || 'png').replace('jpeg', 'jpg'); await upload(p, SHOP.design, 'shop'); P.design = p; }
269
+ for (const [code, b] of Object.entries(SHOP.mocks)) { const p = `${base}mockup-${P.type}-${code}.png`; await upload(p, b, 'shop'); mocks.push(p); } if (mocks.length) P.mockups = mocks;
270
+ const T = PT[P.type]; P.variants = P.colors.flatMap(c => T.sizes.map(s => `${P.sku}-${slugCode(c, 3)}-${slugCode(s, 4)}`)); P.updated = Date.now(); P.brand = 'Jenniisdriptees';
271
+ const list = (await wsJson(PJ, { products: [] })).products || []; const i = list.findIndex(x => x.id === id); i < 0 ? list.push(structuredClone(P)) : (list[i] = structuredClone(P));
272
+ await saveJson(PJ, { type: 'studius.shop', v: 1, brand: 'Jenniisdriptees', note: 'Entwürfe – Veröffentlichung nur nach Freigabe durch Rob im JDT-Studio/Printify', products: list }, 'shop'); SHOP.list = list; await grid();
273
+ window.__shopSaved = { id, mocks: mocks.length, variants: P.variants.length, status: P.status }; setS(el, `✔ Gespeichert: ${PJ} · ${P.variants.length} Varianten`); } catch (er) { setS(el, '⚠ ' + er.message, true); } finally { e.target.disabled = false; } };
274
+ q('.so').onclick = () => { const k = Object.keys(SHOP.mocks)[0]; if (!k) return setS(el, '⚠ Erst Mockups rendern', true); window.__bus.sendTo('social', { kind: 'image', blob: SHOP.mocks[k], name: `${slug(P.title)}-mockup.png`, studio: 'shop', prompt: P.title, shop: { brief: `${P.title} – neues ${PT[P.type].l} von Jenniisdriptees für ${eur(P.price)}. ${P.desc.slice(0, 200)}`, head: P.title, link: P.link } }); };
275
+ fill(); grid();
276
+ }, accept: async (el, a) => { if (a.kind === 'text') { el.querySelector('.ds').value = (a.text ?? await (await toBlob(a.url)).text()).slice(0, 1500); return true; } await el.__setDesign(a.blob || await toBlob(a.url), a.name); return true; } });
277
+
278
+ /* Module API for agents (Social/Shop templates) */
279
+ MODULES.social = { id: 'social', name: 'Social', backend: CHAT, inputs: [{ name: 'prompt', type: 'text' }], outputs: [{ kind: 'text' }],
280
+ actions: { captions: { desc: 'Schreibt Social-Media-Captions mit Hashtags (Instagram, TikTok, X, LinkedIn) zu einem Thema. Postet NICHTS', params: { prompt: 'string' }, run: async ({ prompt }, on = {}) => {
281
+ const t = await llm(`Schreibe Social-Media-Captions auf Deutsch zu: ${prompt}\nFormat, je eine Zeile:\nInstagram: …\nTikTok: …\nX: … (max. 240 Zeichen)\nLinkedIn: …\nJeweils mit passenden Hashtags.`, on); return { kind: 'text', mime: 'text/plain', text: t, name: `captions-${Date.now()}.txt`, studio: 'social', prompt }; } } } };
style.css CHANGED
@@ -239,3 +239,12 @@ body:not(.live) #beebtn{display:none}
239
  @media (max-width:1600px){#bkchip{max-width:150px}#bkchip .s{overflow:hidden;text-overflow:ellipsis;max-width:105px;display:inline-block;vertical-align:middle}}
240
  @media (max-width:1440px){#bkchip .s{display:none}#bkchip{max-width:48px;padding:0 8px}.hbtn.q .s{font-size:10px}}
241
  .tpls{display:grid;grid-template-columns:1fr 1fr;gap:6px;margin-top:6px}.tpl{display:flex;flex-direction:column;gap:3px;text-align:left;padding:7px 8px;background:rgba(242,201,76,.06);border:1px solid var(--line);border-radius:6px;color:var(--txt);cursor:pointer;font:inherit}.tpl:hover{border-color:var(--gold)}.tpl b{color:var(--gold);font-size:11.5px}.tpl small{opacity:.75;font-size:10px;line-height:1.3}.tpl:disabled{opacity:.5}
 
 
 
 
 
 
 
 
 
 
239
  @media (max-width:1600px){#bkchip{max-width:150px}#bkchip .s{overflow:hidden;text-overflow:ellipsis;max-width:105px;display:inline-block;vertical-align:middle}}
240
  @media (max-width:1440px){#bkchip .s{display:none}#bkchip{max-width:48px;padding:0 8px}.hbtn.q .s{font-size:10px}}
241
  .tpls{display:grid;grid-template-columns:1fr 1fr;gap:6px;margin-top:6px}.tpl{display:flex;flex-direction:column;gap:3px;text-align:left;padding:7px 8px;background:rgba(242,201,76,.06);border:1px solid var(--line);border-radius:6px;color:var(--txt);cursor:pointer;font:inherit}.tpl:hover{border-color:var(--gold)}.tpl b{color:var(--gold);font-size:11.5px}.tpl small{opacity:.75;font-size:10px;line-height:1.3}.tpl:disabled{opacity:.5}
242
+
243
+ /* P5 studios */
244
+ .pl{margin:4px 0;padding-left:20px;max-height:180px;overflow:auto;font-size:12px}.pl li{margin:2px 0}.pl .ib{padding:0 5px}
245
+ .wsl{max-height:140px;overflow:auto;display:flex;flex-direction:column;gap:2px;font-size:11px;margin:4px 0}
246
+ .mockg{display:grid;grid-template-columns:repeat(auto-fill,minmax(120px,1fr));gap:8px;margin:6px 0}.mockg figure{margin:0}.mockg img{width:100%;border:1px solid var(--line);border-radius:6px;background:#111}.mockg figcaption{font-size:10px;color:var(--mut)}
247
+ .pls{display:flex;flex-wrap:wrap;gap:4px 12px;font-size:12px}.sched{width:100%;font-size:11px;border-collapse:collapse;margin:6px 0}.sched td,.sched th{border-bottom:1px solid var(--line);padding:3px;text-align:left}
248
+ .cols label{margin-right:8px;font-size:12px}.sw{display:inline-block;width:12px;height:12px;border-radius:50%;border:1px solid var(--line2);margin:0 3px -2px}
249
+ .price{margin:4px 0}.price b{color:var(--gold);font-size:18px}
250
+ #pop .grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(130px,1fr));gap:8px}.pcard{border:1px solid var(--line);border-radius:8px;padding:6px;display:flex;flex-direction:column;gap:3px;font-size:11px}.pcard img{width:100%;border-radius:6px}.pcard a{color:var(--gold)}
vendor/addons/math/ImprovedNoise.js ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // https://cs.nyu.edu/~perlin/noise/
2
+
3
+ const _p = [ 151, 160, 137, 91, 90, 15, 131, 13, 201, 95, 96, 53, 194, 233, 7, 225, 140, 36, 103, 30, 69, 142, 8, 99, 37, 240, 21, 10,
4
+ 23, 190, 6, 148, 247, 120, 234, 75, 0, 26, 197, 62, 94, 252, 219, 203, 117, 35, 11, 32, 57, 177, 33, 88, 237, 149, 56, 87,
5
+ 174, 20, 125, 136, 171, 168, 68, 175, 74, 165, 71, 134, 139, 48, 27, 166, 77, 146, 158, 231, 83, 111, 229, 122, 60, 211,
6
+ 133, 230, 220, 105, 92, 41, 55, 46, 245, 40, 244, 102, 143, 54, 65, 25, 63, 161, 1, 216, 80, 73, 209, 76, 132, 187, 208,
7
+ 89, 18, 169, 200, 196, 135, 130, 116, 188, 159, 86, 164, 100, 109, 198, 173, 186, 3, 64, 52, 217, 226, 250, 124, 123, 5,
8
+ 202, 38, 147, 118, 126, 255, 82, 85, 212, 207, 206, 59, 227, 47, 16, 58, 17, 182, 189, 28, 42, 223, 183, 170, 213, 119,
9
+ 248, 152, 2, 44, 154, 163, 70, 221, 153, 101, 155, 167, 43, 172, 9, 129, 22, 39, 253, 19, 98, 108, 110, 79, 113, 224, 232,
10
+ 178, 185, 112, 104, 218, 246, 97, 228, 251, 34, 242, 193, 238, 210, 144, 12, 191, 179, 162, 241, 81, 51, 145, 235, 249,
11
+ 14, 239, 107, 49, 192, 214, 31, 181, 199, 106, 157, 184, 84, 204, 176, 115, 121, 50, 45, 127, 4, 150, 254, 138, 236, 205,
12
+ 93, 222, 114, 67, 29, 24, 72, 243, 141, 128, 195, 78, 66, 215, 61, 156, 180 ];
13
+
14
+ for ( let i = 0; i < 256; i ++ ) {
15
+
16
+ _p[ 256 + i ] = _p[ i ];
17
+
18
+ }
19
+
20
+ function fade( t ) {
21
+
22
+ return t * t * t * ( t * ( t * 6 - 15 ) + 10 );
23
+
24
+ }
25
+
26
+ function lerp( t, a, b ) {
27
+
28
+ return a + t * ( b - a );
29
+
30
+ }
31
+
32
+ function grad( hash, x, y, z ) {
33
+
34
+ const h = hash & 15;
35
+ const u = h < 8 ? x : y, v = h < 4 ? y : h == 12 || h == 14 ? x : z;
36
+ return ( ( h & 1 ) == 0 ? u : - u ) + ( ( h & 2 ) == 0 ? v : - v );
37
+
38
+ }
39
+
40
+ class ImprovedNoise {
41
+
42
+ noise( x, y, z ) {
43
+
44
+ const floorX = Math.floor( x ), floorY = Math.floor( y ), floorZ = Math.floor( z );
45
+
46
+ const X = floorX & 255, Y = floorY & 255, Z = floorZ & 255;
47
+
48
+ x -= floorX;
49
+ y -= floorY;
50
+ z -= floorZ;
51
+
52
+ const xMinus1 = x - 1, yMinus1 = y - 1, zMinus1 = z - 1;
53
+
54
+ const u = fade( x ), v = fade( y ), w = fade( z );
55
+
56
+ const A = _p[ X ] + Y, AA = _p[ A ] + Z, AB = _p[ A + 1 ] + Z, B = _p[ X + 1 ] + Y, BA = _p[ B ] + Z, BB = _p[ B + 1 ] + Z;
57
+
58
+ return lerp( w, lerp( v, lerp( u, grad( _p[ AA ], x, y, z ),
59
+ grad( _p[ BA ], xMinus1, y, z ) ),
60
+ lerp( u, grad( _p[ AB ], x, yMinus1, z ),
61
+ grad( _p[ BB ], xMinus1, yMinus1, z ) ) ),
62
+ lerp( v, lerp( u, grad( _p[ AA + 1 ], x, y, zMinus1 ),
63
+ grad( _p[ BA + 1 ], xMinus1, y, zMinus1 ) ),
64
+ lerp( u, grad( _p[ AB + 1 ], x, yMinus1, zMinus1 ),
65
+ grad( _p[ BB + 1 ], xMinus1, yMinus1, zMinus1 ) ) ) );
66
+
67
+ }
68
+
69
+ }
70
+
71
+ export { ImprovedNoise };
vendor/addons/math/SimplexNoise.js ADDED
@@ -0,0 +1,444 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Ported from Stefan Gustavson's java implementation
2
+ // http://staffwww.itn.liu.se/~stegu/simplexnoise/simplexnoise.pdf
3
+ // Read Stefan's excellent paper for details on how this code works.
4
+ //
5
+ // Sean McCullough banksean@gmail.com
6
+ //
7
+ // Added 4D noise
8
+
9
+ /**
10
+ * You can pass in a random number generator object if you like.
11
+ * It is assumed to have a random() method.
12
+ */
13
+ class SimplexNoise {
14
+
15
+ constructor( r = Math ) {
16
+
17
+ this.grad3 = [[ 1, 1, 0 ], [ - 1, 1, 0 ], [ 1, - 1, 0 ], [ - 1, - 1, 0 ],
18
+ [ 1, 0, 1 ], [ - 1, 0, 1 ], [ 1, 0, - 1 ], [ - 1, 0, - 1 ],
19
+ [ 0, 1, 1 ], [ 0, - 1, 1 ], [ 0, 1, - 1 ], [ 0, - 1, - 1 ]];
20
+
21
+ this.grad4 = [[ 0, 1, 1, 1 ], [ 0, 1, 1, - 1 ], [ 0, 1, - 1, 1 ], [ 0, 1, - 1, - 1 ],
22
+ [ 0, - 1, 1, 1 ], [ 0, - 1, 1, - 1 ], [ 0, - 1, - 1, 1 ], [ 0, - 1, - 1, - 1 ],
23
+ [ 1, 0, 1, 1 ], [ 1, 0, 1, - 1 ], [ 1, 0, - 1, 1 ], [ 1, 0, - 1, - 1 ],
24
+ [ - 1, 0, 1, 1 ], [ - 1, 0, 1, - 1 ], [ - 1, 0, - 1, 1 ], [ - 1, 0, - 1, - 1 ],
25
+ [ 1, 1, 0, 1 ], [ 1, 1, 0, - 1 ], [ 1, - 1, 0, 1 ], [ 1, - 1, 0, - 1 ],
26
+ [ - 1, 1, 0, 1 ], [ - 1, 1, 0, - 1 ], [ - 1, - 1, 0, 1 ], [ - 1, - 1, 0, - 1 ],
27
+ [ 1, 1, 1, 0 ], [ 1, 1, - 1, 0 ], [ 1, - 1, 1, 0 ], [ 1, - 1, - 1, 0 ],
28
+ [ - 1, 1, 1, 0 ], [ - 1, 1, - 1, 0 ], [ - 1, - 1, 1, 0 ], [ - 1, - 1, - 1, 0 ]];
29
+
30
+ this.p = [];
31
+
32
+ for ( let i = 0; i < 256; i ++ ) {
33
+
34
+ this.p[ i ] = Math.floor( r.random() * 256 );
35
+
36
+ }
37
+
38
+ // To remove the need for index wrapping, double the permutation table length
39
+ this.perm = [];
40
+
41
+ for ( let i = 0; i < 512; i ++ ) {
42
+
43
+ this.perm[ i ] = this.p[ i & 255 ];
44
+
45
+ }
46
+
47
+ // A lookup table to traverse the simplex around a given point in 4D.
48
+ // Details can be found where this table is used, in the 4D noise method.
49
+ this.simplex = [
50
+ [ 0, 1, 2, 3 ], [ 0, 1, 3, 2 ], [ 0, 0, 0, 0 ], [ 0, 2, 3, 1 ], [ 0, 0, 0, 0 ], [ 0, 0, 0, 0 ], [ 0, 0, 0, 0 ], [ 1, 2, 3, 0 ],
51
+ [ 0, 2, 1, 3 ], [ 0, 0, 0, 0 ], [ 0, 3, 1, 2 ], [ 0, 3, 2, 1 ], [ 0, 0, 0, 0 ], [ 0, 0, 0, 0 ], [ 0, 0, 0, 0 ], [ 1, 3, 2, 0 ],
52
+ [ 0, 0, 0, 0 ], [ 0, 0, 0, 0 ], [ 0, 0, 0, 0 ], [ 0, 0, 0, 0 ], [ 0, 0, 0, 0 ], [ 0, 0, 0, 0 ], [ 0, 0, 0, 0 ], [ 0, 0, 0, 0 ],
53
+ [ 1, 2, 0, 3 ], [ 0, 0, 0, 0 ], [ 1, 3, 0, 2 ], [ 0, 0, 0, 0 ], [ 0, 0, 0, 0 ], [ 0, 0, 0, 0 ], [ 2, 3, 0, 1 ], [ 2, 3, 1, 0 ],
54
+ [ 1, 0, 2, 3 ], [ 1, 0, 3, 2 ], [ 0, 0, 0, 0 ], [ 0, 0, 0, 0 ], [ 0, 0, 0, 0 ], [ 2, 0, 3, 1 ], [ 0, 0, 0, 0 ], [ 2, 1, 3, 0 ],
55
+ [ 0, 0, 0, 0 ], [ 0, 0, 0, 0 ], [ 0, 0, 0, 0 ], [ 0, 0, 0, 0 ], [ 0, 0, 0, 0 ], [ 0, 0, 0, 0 ], [ 0, 0, 0, 0 ], [ 0, 0, 0, 0 ],
56
+ [ 2, 0, 1, 3 ], [ 0, 0, 0, 0 ], [ 0, 0, 0, 0 ], [ 0, 0, 0, 0 ], [ 3, 0, 1, 2 ], [ 3, 0, 2, 1 ], [ 0, 0, 0, 0 ], [ 3, 1, 2, 0 ],
57
+ [ 2, 1, 0, 3 ], [ 0, 0, 0, 0 ], [ 0, 0, 0, 0 ], [ 0, 0, 0, 0 ], [ 3, 1, 0, 2 ], [ 0, 0, 0, 0 ], [ 3, 2, 0, 1 ], [ 3, 2, 1, 0 ]];
58
+
59
+ }
60
+
61
+ dot( g, x, y ) {
62
+
63
+ return g[ 0 ] * x + g[ 1 ] * y;
64
+
65
+ }
66
+
67
+ dot3( g, x, y, z ) {
68
+
69
+ return g[ 0 ] * x + g[ 1 ] * y + g[ 2 ] * z;
70
+
71
+ }
72
+
73
+ dot4( g, x, y, z, w ) {
74
+
75
+ return g[ 0 ] * x + g[ 1 ] * y + g[ 2 ] * z + g[ 3 ] * w;
76
+
77
+ }
78
+
79
+ noise( xin, yin ) {
80
+
81
+ let n0; // Noise contributions from the three corners
82
+ let n1;
83
+ let n2;
84
+ // Skew the input space to determine which simplex cell we're in
85
+ const F2 = 0.5 * ( Math.sqrt( 3.0 ) - 1.0 );
86
+ const s = ( xin + yin ) * F2; // Hairy factor for 2D
87
+ const i = Math.floor( xin + s );
88
+ const j = Math.floor( yin + s );
89
+ const G2 = ( 3.0 - Math.sqrt( 3.0 ) ) / 6.0;
90
+ const t = ( i + j ) * G2;
91
+ const X0 = i - t; // Unskew the cell origin back to (x,y) space
92
+ const Y0 = j - t;
93
+ const x0 = xin - X0; // The x,y distances from the cell origin
94
+ const y0 = yin - Y0;
95
+
96
+ // For the 2D case, the simplex shape is an equilateral triangle.
97
+ // Determine which simplex we are in.
98
+ let i1; // Offsets for second (middle) corner of simplex in (i,j) coords
99
+
100
+ let j1;
101
+ if ( x0 > y0 ) {
102
+
103
+ i1 = 1; j1 = 0;
104
+
105
+ // lower triangle, XY order: (0,0)->(1,0)->(1,1)
106
+
107
+ } else {
108
+
109
+ i1 = 0; j1 = 1;
110
+
111
+ } // upper triangle, YX order: (0,0)->(0,1)->(1,1)
112
+
113
+ // A step of (1,0) in (i,j) means a step of (1-c,-c) in (x,y), and
114
+ // a step of (0,1) in (i,j) means a step of (-c,1-c) in (x,y), where
115
+ // c = (3-sqrt(3))/6
116
+ const x1 = x0 - i1 + G2; // Offsets for middle corner in (x,y) unskewed coords
117
+ const y1 = y0 - j1 + G2;
118
+ const x2 = x0 - 1.0 + 2.0 * G2; // Offsets for last corner in (x,y) unskewed coords
119
+ const y2 = y0 - 1.0 + 2.0 * G2;
120
+ // Work out the hashed gradient indices of the three simplex corners
121
+ const ii = i & 255;
122
+ const jj = j & 255;
123
+ const gi0 = this.perm[ ii + this.perm[ jj ] ] % 12;
124
+ const gi1 = this.perm[ ii + i1 + this.perm[ jj + j1 ] ] % 12;
125
+ const gi2 = this.perm[ ii + 1 + this.perm[ jj + 1 ] ] % 12;
126
+ // Calculate the contribution from the three corners
127
+ let t0 = 0.5 - x0 * x0 - y0 * y0;
128
+ if ( t0 < 0 ) n0 = 0.0;
129
+ else {
130
+
131
+ t0 *= t0;
132
+ n0 = t0 * t0 * this.dot( this.grad3[ gi0 ], x0, y0 ); // (x,y) of grad3 used for 2D gradient
133
+
134
+ }
135
+
136
+ let t1 = 0.5 - x1 * x1 - y1 * y1;
137
+ if ( t1 < 0 ) n1 = 0.0;
138
+ else {
139
+
140
+ t1 *= t1;
141
+ n1 = t1 * t1 * this.dot( this.grad3[ gi1 ], x1, y1 );
142
+
143
+ }
144
+
145
+ let t2 = 0.5 - x2 * x2 - y2 * y2;
146
+ if ( t2 < 0 ) n2 = 0.0;
147
+ else {
148
+
149
+ t2 *= t2;
150
+ n2 = t2 * t2 * this.dot( this.grad3[ gi2 ], x2, y2 );
151
+
152
+ }
153
+
154
+ // Add contributions from each corner to get the final noise value.
155
+ // The result is scaled to return values in the interval [-1,1].
156
+ return 70.0 * ( n0 + n1 + n2 );
157
+
158
+ }
159
+
160
+ // 3D simplex noise
161
+ noise3d( xin, yin, zin ) {
162
+
163
+ let n0; // Noise contributions from the four corners
164
+ let n1;
165
+ let n2;
166
+ let n3;
167
+ // Skew the input space to determine which simplex cell we're in
168
+ const F3 = 1.0 / 3.0;
169
+ const s = ( xin + yin + zin ) * F3; // Very nice and simple skew factor for 3D
170
+ const i = Math.floor( xin + s );
171
+ const j = Math.floor( yin + s );
172
+ const k = Math.floor( zin + s );
173
+ const G3 = 1.0 / 6.0; // Very nice and simple unskew factor, too
174
+ const t = ( i + j + k ) * G3;
175
+ const X0 = i - t; // Unskew the cell origin back to (x,y,z) space
176
+ const Y0 = j - t;
177
+ const Z0 = k - t;
178
+ const x0 = xin - X0; // The x,y,z distances from the cell origin
179
+ const y0 = yin - Y0;
180
+ const z0 = zin - Z0;
181
+
182
+ // For the 3D case, the simplex shape is a slightly irregular tetrahedron.
183
+ // Determine which simplex we are in.
184
+ let i1; // Offsets for second corner of simplex in (i,j,k) coords
185
+
186
+ let j1;
187
+ let k1;
188
+ let i2; // Offsets for third corner of simplex in (i,j,k) coords
189
+ let j2;
190
+ let k2;
191
+ if ( x0 >= y0 ) {
192
+
193
+ if ( y0 >= z0 ) {
194
+
195
+ i1 = 1; j1 = 0; k1 = 0; i2 = 1; j2 = 1; k2 = 0;
196
+
197
+ // X Y Z order
198
+
199
+ } else if ( x0 >= z0 ) {
200
+
201
+ i1 = 1; j1 = 0; k1 = 0; i2 = 1; j2 = 0; k2 = 1;
202
+
203
+ // X Z Y order
204
+
205
+ } else {
206
+
207
+ i1 = 0; j1 = 0; k1 = 1; i2 = 1; j2 = 0; k2 = 1;
208
+
209
+ } // Z X Y order
210
+
211
+ } else { // x0<y0
212
+
213
+ if ( y0 < z0 ) {
214
+
215
+ i1 = 0; j1 = 0; k1 = 1; i2 = 0; j2 = 1; k2 = 1;
216
+
217
+ // Z Y X order
218
+
219
+ } else if ( x0 < z0 ) {
220
+
221
+ i1 = 0; j1 = 1; k1 = 0; i2 = 0; j2 = 1; k2 = 1;
222
+
223
+ // Y Z X order
224
+
225
+ } else {
226
+
227
+ i1 = 0; j1 = 1; k1 = 0; i2 = 1; j2 = 1; k2 = 0;
228
+
229
+ } // Y X Z order
230
+
231
+ }
232
+
233
+ // A step of (1,0,0) in (i,j,k) means a step of (1-c,-c,-c) in (x,y,z),
234
+ // a step of (0,1,0) in (i,j,k) means a step of (-c,1-c,-c) in (x,y,z), and
235
+ // a step of (0,0,1) in (i,j,k) means a step of (-c,-c,1-c) in (x,y,z), where
236
+ // c = 1/6.
237
+ const x1 = x0 - i1 + G3; // Offsets for second corner in (x,y,z) coords
238
+ const y1 = y0 - j1 + G3;
239
+ const z1 = z0 - k1 + G3;
240
+ const x2 = x0 - i2 + 2.0 * G3; // Offsets for third corner in (x,y,z) coords
241
+ const y2 = y0 - j2 + 2.0 * G3;
242
+ const z2 = z0 - k2 + 2.0 * G3;
243
+ const x3 = x0 - 1.0 + 3.0 * G3; // Offsets for last corner in (x,y,z) coords
244
+ const y3 = y0 - 1.0 + 3.0 * G3;
245
+ const z3 = z0 - 1.0 + 3.0 * G3;
246
+ // Work out the hashed gradient indices of the four simplex corners
247
+ const ii = i & 255;
248
+ const jj = j & 255;
249
+ const kk = k & 255;
250
+ const gi0 = this.perm[ ii + this.perm[ jj + this.perm[ kk ] ] ] % 12;
251
+ const gi1 = this.perm[ ii + i1 + this.perm[ jj + j1 + this.perm[ kk + k1 ] ] ] % 12;
252
+ const gi2 = this.perm[ ii + i2 + this.perm[ jj + j2 + this.perm[ kk + k2 ] ] ] % 12;
253
+ const gi3 = this.perm[ ii + 1 + this.perm[ jj + 1 + this.perm[ kk + 1 ] ] ] % 12;
254
+ // Calculate the contribution from the four corners
255
+ let t0 = 0.6 - x0 * x0 - y0 * y0 - z0 * z0;
256
+ if ( t0 < 0 ) n0 = 0.0;
257
+ else {
258
+
259
+ t0 *= t0;
260
+ n0 = t0 * t0 * this.dot3( this.grad3[ gi0 ], x0, y0, z0 );
261
+
262
+ }
263
+
264
+ let t1 = 0.6 - x1 * x1 - y1 * y1 - z1 * z1;
265
+ if ( t1 < 0 ) n1 = 0.0;
266
+ else {
267
+
268
+ t1 *= t1;
269
+ n1 = t1 * t1 * this.dot3( this.grad3[ gi1 ], x1, y1, z1 );
270
+
271
+ }
272
+
273
+ let t2 = 0.6 - x2 * x2 - y2 * y2 - z2 * z2;
274
+ if ( t2 < 0 ) n2 = 0.0;
275
+ else {
276
+
277
+ t2 *= t2;
278
+ n2 = t2 * t2 * this.dot3( this.grad3[ gi2 ], x2, y2, z2 );
279
+
280
+ }
281
+
282
+ let t3 = 0.6 - x3 * x3 - y3 * y3 - z3 * z3;
283
+ if ( t3 < 0 ) n3 = 0.0;
284
+ else {
285
+
286
+ t3 *= t3;
287
+ n3 = t3 * t3 * this.dot3( this.grad3[ gi3 ], x3, y3, z3 );
288
+
289
+ }
290
+
291
+ // Add contributions from each corner to get the final noise value.
292
+ // The result is scaled to stay just inside [-1,1]
293
+ return 32.0 * ( n0 + n1 + n2 + n3 );
294
+
295
+ }
296
+
297
+ // 4D simplex noise
298
+ noise4d( x, y, z, w ) {
299
+
300
+ // For faster and easier lookups
301
+ const grad4 = this.grad4;
302
+ const simplex = this.simplex;
303
+ const perm = this.perm;
304
+
305
+ // The skewing and unskewing factors are hairy again for the 4D case
306
+ const F4 = ( Math.sqrt( 5.0 ) - 1.0 ) / 4.0;
307
+ const G4 = ( 5.0 - Math.sqrt( 5.0 ) ) / 20.0;
308
+ let n0; // Noise contributions from the five corners
309
+ let n1;
310
+ let n2;
311
+ let n3;
312
+ let n4;
313
+ // Skew the (x,y,z,w) space to determine which cell of 24 simplices we're in
314
+ const s = ( x + y + z + w ) * F4; // Factor for 4D skewing
315
+ const i = Math.floor( x + s );
316
+ const j = Math.floor( y + s );
317
+ const k = Math.floor( z + s );
318
+ const l = Math.floor( w + s );
319
+ const t = ( i + j + k + l ) * G4; // Factor for 4D unskewing
320
+ const X0 = i - t; // Unskew the cell origin back to (x,y,z,w) space
321
+ const Y0 = j - t;
322
+ const Z0 = k - t;
323
+ const W0 = l - t;
324
+ const x0 = x - X0; // The x,y,z,w distances from the cell origin
325
+ const y0 = y - Y0;
326
+ const z0 = z - Z0;
327
+ const w0 = w - W0;
328
+
329
+ // For the 4D case, the simplex is a 4D shape I won't even try to describe.
330
+ // To find out which of the 24 possible simplices we're in, we need to
331
+ // determine the magnitude ordering of x0, y0, z0 and w0.
332
+ // The method below is a good way of finding the ordering of x,y,z,w and
333
+ // then find the correct traversal order for the simplex we’re in.
334
+ // First, six pair-wise comparisons are performed between each possible pair
335
+ // of the four coordinates, and the results are used to add up binary bits
336
+ // for an integer index.
337
+ const c1 = ( x0 > y0 ) ? 32 : 0;
338
+ const c2 = ( x0 > z0 ) ? 16 : 0;
339
+ const c3 = ( y0 > z0 ) ? 8 : 0;
340
+ const c4 = ( x0 > w0 ) ? 4 : 0;
341
+ const c5 = ( y0 > w0 ) ? 2 : 0;
342
+ const c6 = ( z0 > w0 ) ? 1 : 0;
343
+ const c = c1 + c2 + c3 + c4 + c5 + c6;
344
+
345
+ // simplex[c] is a 4-vector with the numbers 0, 1, 2 and 3 in some order.
346
+ // Many values of c will never occur, since e.g. x>y>z>w makes x<z, y<w and x<w
347
+ // impossible. Only the 24 indices which have non-zero entries make any sense.
348
+ // We use a thresholding to set the coordinates in turn from the largest magnitude.
349
+ // The number 3 in the "simplex" array is at the position of the largest coordinate.
350
+ const i1 = simplex[ c ][ 0 ] >= 3 ? 1 : 0;
351
+ const j1 = simplex[ c ][ 1 ] >= 3 ? 1 : 0;
352
+ const k1 = simplex[ c ][ 2 ] >= 3 ? 1 : 0;
353
+ const l1 = simplex[ c ][ 3 ] >= 3 ? 1 : 0;
354
+ // The number 2 in the "simplex" array is at the second largest coordinate.
355
+ const i2 = simplex[ c ][ 0 ] >= 2 ? 1 : 0;
356
+ const j2 = simplex[ c ][ 1 ] >= 2 ? 1 : 0;
357
+ const k2 = simplex[ c ][ 2 ] >= 2 ? 1 : 0;
358
+ const l2 = simplex[ c ][ 3 ] >= 2 ? 1 : 0;
359
+ // The number 1 in the "simplex" array is at the second smallest coordinate.
360
+ const i3 = simplex[ c ][ 0 ] >= 1 ? 1 : 0;
361
+ const j3 = simplex[ c ][ 1 ] >= 1 ? 1 : 0;
362
+ const k3 = simplex[ c ][ 2 ] >= 1 ? 1 : 0;
363
+ const l3 = simplex[ c ][ 3 ] >= 1 ? 1 : 0;
364
+ // The fifth corner has all coordinate offsets = 1, so no need to look that up.
365
+ const x1 = x0 - i1 + G4; // Offsets for second corner in (x,y,z,w) coords
366
+ const y1 = y0 - j1 + G4;
367
+ const z1 = z0 - k1 + G4;
368
+ const w1 = w0 - l1 + G4;
369
+ const x2 = x0 - i2 + 2.0 * G4; // Offsets for third corner in (x,y,z,w) coords
370
+ const y2 = y0 - j2 + 2.0 * G4;
371
+ const z2 = z0 - k2 + 2.0 * G4;
372
+ const w2 = w0 - l2 + 2.0 * G4;
373
+ const x3 = x0 - i3 + 3.0 * G4; // Offsets for fourth corner in (x,y,z,w) coords
374
+ const y3 = y0 - j3 + 3.0 * G4;
375
+ const z3 = z0 - k3 + 3.0 * G4;
376
+ const w3 = w0 - l3 + 3.0 * G4;
377
+ const x4 = x0 - 1.0 + 4.0 * G4; // Offsets for last corner in (x,y,z,w) coords
378
+ const y4 = y0 - 1.0 + 4.0 * G4;
379
+ const z4 = z0 - 1.0 + 4.0 * G4;
380
+ const w4 = w0 - 1.0 + 4.0 * G4;
381
+ // Work out the hashed gradient indices of the five simplex corners
382
+ const ii = i & 255;
383
+ const jj = j & 255;
384
+ const kk = k & 255;
385
+ const ll = l & 255;
386
+ const gi0 = perm[ ii + perm[ jj + perm[ kk + perm[ ll ] ] ] ] % 32;
387
+ const gi1 = perm[ ii + i1 + perm[ jj + j1 + perm[ kk + k1 + perm[ ll + l1 ] ] ] ] % 32;
388
+ const gi2 = perm[ ii + i2 + perm[ jj + j2 + perm[ kk + k2 + perm[ ll + l2 ] ] ] ] % 32;
389
+ const gi3 = perm[ ii + i3 + perm[ jj + j3 + perm[ kk + k3 + perm[ ll + l3 ] ] ] ] % 32;
390
+ const gi4 = perm[ ii + 1 + perm[ jj + 1 + perm[ kk + 1 + perm[ ll + 1 ] ] ] ] % 32;
391
+ // Calculate the contribution from the five corners
392
+ let t0 = 0.6 - x0 * x0 - y0 * y0 - z0 * z0 - w0 * w0;
393
+ if ( t0 < 0 ) n0 = 0.0;
394
+ else {
395
+
396
+ t0 *= t0;
397
+ n0 = t0 * t0 * this.dot4( grad4[ gi0 ], x0, y0, z0, w0 );
398
+
399
+ }
400
+
401
+ let t1 = 0.6 - x1 * x1 - y1 * y1 - z1 * z1 - w1 * w1;
402
+ if ( t1 < 0 ) n1 = 0.0;
403
+ else {
404
+
405
+ t1 *= t1;
406
+ n1 = t1 * t1 * this.dot4( grad4[ gi1 ], x1, y1, z1, w1 );
407
+
408
+ }
409
+
410
+ let t2 = 0.6 - x2 * x2 - y2 * y2 - z2 * z2 - w2 * w2;
411
+ if ( t2 < 0 ) n2 = 0.0;
412
+ else {
413
+
414
+ t2 *= t2;
415
+ n2 = t2 * t2 * this.dot4( grad4[ gi2 ], x2, y2, z2, w2 );
416
+
417
+ }
418
+
419
+ let t3 = 0.6 - x3 * x3 - y3 * y3 - z3 * z3 - w3 * w3;
420
+ if ( t3 < 0 ) n3 = 0.0;
421
+ else {
422
+
423
+ t3 *= t3;
424
+ n3 = t3 * t3 * this.dot4( grad4[ gi3 ], x3, y3, z3, w3 );
425
+
426
+ }
427
+
428
+ let t4 = 0.6 - x4 * x4 - y4 * y4 - z4 * z4 - w4 * w4;
429
+ if ( t4 < 0 ) n4 = 0.0;
430
+ else {
431
+
432
+ t4 *= t4;
433
+ n4 = t4 * t4 * this.dot4( grad4[ gi4 ], x4, y4, z4, w4 );
434
+
435
+ }
436
+
437
+ // Sum up and scale the result to cover the range [-1,1]
438
+ return 27.0 * ( n0 + n1 + n2 + n3 + n4 );
439
+
440
+ }
441
+
442
+ }
443
+
444
+ export { SimplexNoise };
vendor/addons/objects/Sky.js ADDED
@@ -0,0 +1,219 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import {
2
+ BackSide,
3
+ BoxGeometry,
4
+ Mesh,
5
+ ShaderMaterial,
6
+ UniformsUtils,
7
+ Vector3
8
+ } from '../../three.module.min.js';
9
+
10
+ /**
11
+ * Based on "A Practical Analytic Model for Daylight"
12
+ * aka The Preetham Model, the de facto standard analytic skydome model
13
+ * https://www.researchgate.net/publication/220720443_A_Practical_Analytic_Model_for_Daylight
14
+ *
15
+ * First implemented by Simon Wallner
16
+ * http://simonwallner.at/project/atmospheric-scattering/
17
+ *
18
+ * Improved by Martin Upitis
19
+ * http://blenderartists.org/forum/showthread.php?245954-preethams-sky-impementation-HDR
20
+ *
21
+ * Three.js integration by zz85 http://twitter.com/blurspline
22
+ */
23
+
24
+ class Sky extends Mesh {
25
+
26
+ constructor() {
27
+
28
+ const shader = Sky.SkyShader;
29
+
30
+ const material = new ShaderMaterial( {
31
+ name: shader.name,
32
+ uniforms: UniformsUtils.clone( shader.uniforms ),
33
+ vertexShader: shader.vertexShader,
34
+ fragmentShader: shader.fragmentShader,
35
+ side: BackSide,
36
+ depthWrite: false
37
+ } );
38
+
39
+ super( new BoxGeometry( 1, 1, 1 ), material );
40
+
41
+ this.isSky = true;
42
+
43
+ }
44
+
45
+ }
46
+
47
+ Sky.SkyShader = {
48
+
49
+ name: 'SkyShader',
50
+
51
+ uniforms: {
52
+ 'turbidity': { value: 2 },
53
+ 'rayleigh': { value: 1 },
54
+ 'mieCoefficient': { value: 0.005 },
55
+ 'mieDirectionalG': { value: 0.8 },
56
+ 'sunPosition': { value: new Vector3() },
57
+ 'up': { value: new Vector3( 0, 1, 0 ) }
58
+ },
59
+
60
+ vertexShader: /* glsl */`
61
+ uniform vec3 sunPosition;
62
+ uniform float rayleigh;
63
+ uniform float turbidity;
64
+ uniform float mieCoefficient;
65
+ uniform vec3 up;
66
+
67
+ varying vec3 vWorldPosition;
68
+ varying vec3 vSunDirection;
69
+ varying float vSunfade;
70
+ varying vec3 vBetaR;
71
+ varying vec3 vBetaM;
72
+ varying float vSunE;
73
+
74
+ // constants for atmospheric scattering
75
+ const float e = 2.71828182845904523536028747135266249775724709369995957;
76
+ const float pi = 3.141592653589793238462643383279502884197169;
77
+
78
+ // wavelength of used primaries, according to preetham
79
+ const vec3 lambda = vec3( 680E-9, 550E-9, 450E-9 );
80
+ // this pre-calcuation replaces older TotalRayleigh(vec3 lambda) function:
81
+ // (8.0 * pow(pi, 3.0) * pow(pow(n, 2.0) - 1.0, 2.0) * (6.0 + 3.0 * pn)) / (3.0 * N * pow(lambda, vec3(4.0)) * (6.0 - 7.0 * pn))
82
+ const vec3 totalRayleigh = vec3( 5.804542996261093E-6, 1.3562911419845635E-5, 3.0265902468824876E-5 );
83
+
84
+ // mie stuff
85
+ // K coefficient for the primaries
86
+ const float v = 4.0;
87
+ const vec3 K = vec3( 0.686, 0.678, 0.666 );
88
+ // MieConst = pi * pow( ( 2.0 * pi ) / lambda, vec3( v - 2.0 ) ) * K
89
+ const vec3 MieConst = vec3( 1.8399918514433978E14, 2.7798023919660528E14, 4.0790479543861094E14 );
90
+
91
+ // earth shadow hack
92
+ // cutoffAngle = pi / 1.95;
93
+ const float cutoffAngle = 1.6110731556870734;
94
+ const float steepness = 1.5;
95
+ const float EE = 1000.0;
96
+
97
+ float sunIntensity( float zenithAngleCos ) {
98
+ zenithAngleCos = clamp( zenithAngleCos, -1.0, 1.0 );
99
+ return EE * max( 0.0, 1.0 - pow( e, -( ( cutoffAngle - acos( zenithAngleCos ) ) / steepness ) ) );
100
+ }
101
+
102
+ vec3 totalMie( float T ) {
103
+ float c = ( 0.2 * T ) * 10E-18;
104
+ return 0.434 * c * MieConst;
105
+ }
106
+
107
+ void main() {
108
+
109
+ vec4 worldPosition = modelMatrix * vec4( position, 1.0 );
110
+ vWorldPosition = worldPosition.xyz;
111
+
112
+ gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
113
+ gl_Position.z = gl_Position.w; // set z to camera.far
114
+
115
+ vSunDirection = normalize( sunPosition );
116
+
117
+ vSunE = sunIntensity( dot( vSunDirection, up ) );
118
+
119
+ vSunfade = 1.0 - clamp( 1.0 - exp( ( sunPosition.y / 450000.0 ) ), 0.0, 1.0 );
120
+
121
+ float rayleighCoefficient = rayleigh - ( 1.0 * ( 1.0 - vSunfade ) );
122
+
123
+ // extinction (absorbtion + out scattering)
124
+ // rayleigh coefficients
125
+ vBetaR = totalRayleigh * rayleighCoefficient;
126
+
127
+ // mie coefficients
128
+ vBetaM = totalMie( turbidity ) * mieCoefficient;
129
+
130
+ }`,
131
+
132
+ fragmentShader: /* glsl */`
133
+ varying vec3 vWorldPosition;
134
+ varying vec3 vSunDirection;
135
+ varying float vSunfade;
136
+ varying vec3 vBetaR;
137
+ varying vec3 vBetaM;
138
+ varying float vSunE;
139
+
140
+ uniform float mieDirectionalG;
141
+ uniform vec3 up;
142
+
143
+ // constants for atmospheric scattering
144
+ const float pi = 3.141592653589793238462643383279502884197169;
145
+
146
+ const float n = 1.0003; // refractive index of air
147
+ const float N = 2.545E25; // number of molecules per unit volume for air at 288.15K and 1013mb (sea level -45 celsius)
148
+
149
+ // optical length at zenith for molecules
150
+ const float rayleighZenithLength = 8.4E3;
151
+ const float mieZenithLength = 1.25E3;
152
+ // 66 arc seconds -> degrees, and the cosine of that
153
+ const float sunAngularDiameterCos = 0.999956676946448443553574619906976478926848692873900859324;
154
+
155
+ // 3.0 / ( 16.0 * pi )
156
+ const float THREE_OVER_SIXTEENPI = 0.05968310365946075;
157
+ // 1.0 / ( 4.0 * pi )
158
+ const float ONE_OVER_FOURPI = 0.07957747154594767;
159
+
160
+ float rayleighPhase( float cosTheta ) {
161
+ return THREE_OVER_SIXTEENPI * ( 1.0 + pow( cosTheta, 2.0 ) );
162
+ }
163
+
164
+ float hgPhase( float cosTheta, float g ) {
165
+ float g2 = pow( g, 2.0 );
166
+ float inverse = 1.0 / pow( 1.0 - 2.0 * g * cosTheta + g2, 1.5 );
167
+ return ONE_OVER_FOURPI * ( ( 1.0 - g2 ) * inverse );
168
+ }
169
+
170
+ void main() {
171
+
172
+ vec3 direction = normalize( vWorldPosition - cameraPosition );
173
+
174
+ // optical length
175
+ // cutoff angle at 90 to avoid singularity in next formula.
176
+ float zenithAngle = acos( max( 0.0, dot( up, direction ) ) );
177
+ float inverse = 1.0 / ( cos( zenithAngle ) + 0.15 * pow( 93.885 - ( ( zenithAngle * 180.0 ) / pi ), -1.253 ) );
178
+ float sR = rayleighZenithLength * inverse;
179
+ float sM = mieZenithLength * inverse;
180
+
181
+ // combined extinction factor
182
+ vec3 Fex = exp( -( vBetaR * sR + vBetaM * sM ) );
183
+
184
+ // in scattering
185
+ float cosTheta = dot( direction, vSunDirection );
186
+
187
+ float rPhase = rayleighPhase( cosTheta * 0.5 + 0.5 );
188
+ vec3 betaRTheta = vBetaR * rPhase;
189
+
190
+ float mPhase = hgPhase( cosTheta, mieDirectionalG );
191
+ vec3 betaMTheta = vBetaM * mPhase;
192
+
193
+ vec3 Lin = pow( vSunE * ( ( betaRTheta + betaMTheta ) / ( vBetaR + vBetaM ) ) * ( 1.0 - Fex ), vec3( 1.5 ) );
194
+ Lin *= mix( vec3( 1.0 ), pow( vSunE * ( ( betaRTheta + betaMTheta ) / ( vBetaR + vBetaM ) ) * Fex, vec3( 1.0 / 2.0 ) ), clamp( pow( 1.0 - dot( up, vSunDirection ), 5.0 ), 0.0, 1.0 ) );
195
+
196
+ // nightsky
197
+ float theta = acos( direction.y ); // elevation --> y-axis, [-pi/2, pi/2]
198
+ float phi = atan( direction.z, direction.x ); // azimuth --> x-axis [-pi/2, pi/2]
199
+ vec2 uv = vec2( phi, theta ) / vec2( 2.0 * pi, pi ) + vec2( 0.5, 0.0 );
200
+ vec3 L0 = vec3( 0.1 ) * Fex;
201
+
202
+ // composition + solar disc
203
+ float sundisk = smoothstep( sunAngularDiameterCos, sunAngularDiameterCos + 0.00002, cosTheta );
204
+ L0 += ( vSunE * 19000.0 * Fex ) * sundisk;
205
+
206
+ vec3 texColor = ( Lin + L0 ) * 0.04 + vec3( 0.0, 0.0003, 0.00075 );
207
+
208
+ vec3 retColor = pow( texColor, vec3( 1.0 / ( 1.2 + ( 1.2 * vSunfade ) ) ) );
209
+
210
+ gl_FragColor = vec4( retColor, 1.0 );
211
+
212
+ #include <tonemapping_fragment>
213
+ #include <colorspace_fragment>
214
+
215
+ }`
216
+
217
+ };
218
+
219
+ export { Sky };
vendor/addons/postprocessing/BokehPass.js ADDED
@@ -0,0 +1,141 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import {
2
+ Color,
3
+ HalfFloatType,
4
+ MeshDepthMaterial,
5
+ NearestFilter,
6
+ NoBlending,
7
+ RGBADepthPacking,
8
+ ShaderMaterial,
9
+ UniformsUtils,
10
+ WebGLRenderTarget
11
+ } from '../../three.module.min.js';
12
+ import { Pass, FullScreenQuad } from './Pass.js';
13
+ import { BokehShader } from '../shaders/BokehShader.js';
14
+
15
+ /**
16
+ * Depth-of-field post-process with bokeh shader
17
+ */
18
+
19
+ class BokehPass extends Pass {
20
+
21
+ constructor( scene, camera, params ) {
22
+
23
+ super();
24
+
25
+ this.scene = scene;
26
+ this.camera = camera;
27
+
28
+ const focus = ( params.focus !== undefined ) ? params.focus : 1.0;
29
+ const aperture = ( params.aperture !== undefined ) ? params.aperture : 0.025;
30
+ const maxblur = ( params.maxblur !== undefined ) ? params.maxblur : 1.0;
31
+
32
+ // render targets
33
+
34
+ this.renderTargetDepth = new WebGLRenderTarget( 1, 1, { // will be resized later
35
+ minFilter: NearestFilter,
36
+ magFilter: NearestFilter,
37
+ type: HalfFloatType
38
+ } );
39
+
40
+ this.renderTargetDepth.texture.name = 'BokehPass.depth';
41
+
42
+ // depth material
43
+
44
+ this.materialDepth = new MeshDepthMaterial();
45
+ this.materialDepth.depthPacking = RGBADepthPacking;
46
+ this.materialDepth.blending = NoBlending;
47
+
48
+ // bokeh material
49
+
50
+ const bokehShader = BokehShader;
51
+ const bokehUniforms = UniformsUtils.clone( bokehShader.uniforms );
52
+
53
+ bokehUniforms[ 'tDepth' ].value = this.renderTargetDepth.texture;
54
+
55
+ bokehUniforms[ 'focus' ].value = focus;
56
+ bokehUniforms[ 'aspect' ].value = camera.aspect;
57
+ bokehUniforms[ 'aperture' ].value = aperture;
58
+ bokehUniforms[ 'maxblur' ].value = maxblur;
59
+ bokehUniforms[ 'nearClip' ].value = camera.near;
60
+ bokehUniforms[ 'farClip' ].value = camera.far;
61
+
62
+ this.materialBokeh = new ShaderMaterial( {
63
+ defines: Object.assign( {}, bokehShader.defines ),
64
+ uniforms: bokehUniforms,
65
+ vertexShader: bokehShader.vertexShader,
66
+ fragmentShader: bokehShader.fragmentShader
67
+ } );
68
+
69
+ this.uniforms = bokehUniforms;
70
+
71
+ this.fsQuad = new FullScreenQuad( this.materialBokeh );
72
+
73
+ this._oldClearColor = new Color();
74
+
75
+ }
76
+
77
+ render( renderer, writeBuffer, readBuffer/*, deltaTime, maskActive*/ ) {
78
+
79
+ // Render depth into texture
80
+
81
+ this.scene.overrideMaterial = this.materialDepth;
82
+
83
+ renderer.getClearColor( this._oldClearColor );
84
+ const oldClearAlpha = renderer.getClearAlpha();
85
+ const oldAutoClear = renderer.autoClear;
86
+ renderer.autoClear = false;
87
+
88
+ renderer.setClearColor( 0xffffff );
89
+ renderer.setClearAlpha( 1.0 );
90
+ renderer.setRenderTarget( this.renderTargetDepth );
91
+ renderer.clear();
92
+ renderer.render( this.scene, this.camera );
93
+
94
+ // Render bokeh composite
95
+
96
+ this.uniforms[ 'tColor' ].value = readBuffer.texture;
97
+ this.uniforms[ 'nearClip' ].value = this.camera.near;
98
+ this.uniforms[ 'farClip' ].value = this.camera.far;
99
+
100
+ if ( this.renderToScreen ) {
101
+
102
+ renderer.setRenderTarget( null );
103
+ this.fsQuad.render( renderer );
104
+
105
+ } else {
106
+
107
+ renderer.setRenderTarget( writeBuffer );
108
+ renderer.clear();
109
+ this.fsQuad.render( renderer );
110
+
111
+ }
112
+
113
+ this.scene.overrideMaterial = null;
114
+ renderer.setClearColor( this._oldClearColor );
115
+ renderer.setClearAlpha( oldClearAlpha );
116
+ renderer.autoClear = oldAutoClear;
117
+
118
+ }
119
+
120
+ setSize( width, height ) {
121
+
122
+ this.materialBokeh.uniforms[ 'aspect' ].value = width / height;
123
+
124
+ this.renderTargetDepth.setSize( width, height );
125
+
126
+ }
127
+
128
+ dispose() {
129
+
130
+ this.renderTargetDepth.dispose();
131
+
132
+ this.materialDepth.dispose();
133
+ this.materialBokeh.dispose();
134
+
135
+ this.fsQuad.dispose();
136
+
137
+ }
138
+
139
+ }
140
+
141
+ export { BokehPass };
vendor/addons/postprocessing/GTAOPass.js ADDED
@@ -0,0 +1,582 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import {
2
+ AddEquation,
3
+ Color,
4
+ CustomBlending,
5
+ DataTexture,
6
+ DepthTexture,
7
+ DepthStencilFormat,
8
+ DstAlphaFactor,
9
+ DstColorFactor,
10
+ HalfFloatType,
11
+ MeshNormalMaterial,
12
+ NearestFilter,
13
+ NoBlending,
14
+ RepeatWrapping,
15
+ RGBAFormat,
16
+ ShaderMaterial,
17
+ UniformsUtils,
18
+ UnsignedByteType,
19
+ UnsignedInt248Type,
20
+ WebGLRenderTarget,
21
+ ZeroFactor
22
+ } from '../../three.module.min.js';
23
+ import { Pass, FullScreenQuad } from './Pass.js';
24
+ import { generateMagicSquareNoise, GTAOShader, GTAODepthShader, GTAOBlendShader } from '../shaders/GTAOShader.js';
25
+ import { generatePdSamplePointInitializer, PoissonDenoiseShader } from '../shaders/PoissonDenoiseShader.js';
26
+ import { CopyShader } from '../shaders/CopyShader.js';
27
+ import { SimplexNoise } from '../math/SimplexNoise.js';
28
+
29
+ class GTAOPass extends Pass {
30
+
31
+ constructor( scene, camera, width, height, parameters, aoParameters, pdParameters ) {
32
+
33
+ super();
34
+
35
+ this.width = ( width !== undefined ) ? width : 512;
36
+ this.height = ( height !== undefined ) ? height : 512;
37
+ this.clear = true;
38
+ this.camera = camera;
39
+ this.scene = scene;
40
+ this.output = 0;
41
+ this._renderGBuffer = true;
42
+ this._visibilityCache = new Map();
43
+ this.blendIntensity = 1.;
44
+
45
+ this.pdRings = 2.;
46
+ this.pdRadiusExponent = 2.;
47
+ this.pdSamples = 16;
48
+
49
+ this.gtaoNoiseTexture = generateMagicSquareNoise();
50
+ this.pdNoiseTexture = this.generateNoise();
51
+
52
+ this.gtaoRenderTarget = new WebGLRenderTarget( this.width, this.height, { type: HalfFloatType } );
53
+ this.pdRenderTarget = this.gtaoRenderTarget.clone();
54
+
55
+ this.gtaoMaterial = new ShaderMaterial( {
56
+ defines: Object.assign( {}, GTAOShader.defines ),
57
+ uniforms: UniformsUtils.clone( GTAOShader.uniforms ),
58
+ vertexShader: GTAOShader.vertexShader,
59
+ fragmentShader: GTAOShader.fragmentShader,
60
+ blending: NoBlending,
61
+ depthTest: false,
62
+ depthWrite: false,
63
+ } );
64
+ this.gtaoMaterial.defines.PERSPECTIVE_CAMERA = this.camera.isPerspectiveCamera ? 1 : 0;
65
+ this.gtaoMaterial.uniforms.tNoise.value = this.gtaoNoiseTexture;
66
+ this.gtaoMaterial.uniforms.resolution.value.set( this.width, this.height );
67
+ this.gtaoMaterial.uniforms.cameraNear.value = this.camera.near;
68
+ this.gtaoMaterial.uniforms.cameraFar.value = this.camera.far;
69
+
70
+ this.normalMaterial = new MeshNormalMaterial();
71
+ this.normalMaterial.blending = NoBlending;
72
+
73
+ this.pdMaterial = new ShaderMaterial( {
74
+ defines: Object.assign( {}, PoissonDenoiseShader.defines ),
75
+ uniforms: UniformsUtils.clone( PoissonDenoiseShader.uniforms ),
76
+ vertexShader: PoissonDenoiseShader.vertexShader,
77
+ fragmentShader: PoissonDenoiseShader.fragmentShader,
78
+ depthTest: false,
79
+ depthWrite: false,
80
+ } );
81
+ this.pdMaterial.uniforms.tDiffuse.value = this.gtaoRenderTarget.texture;
82
+ this.pdMaterial.uniforms.tNoise.value = this.pdNoiseTexture;
83
+ this.pdMaterial.uniforms.resolution.value.set( this.width, this.height );
84
+ this.pdMaterial.uniforms.lumaPhi.value = 10;
85
+ this.pdMaterial.uniforms.depthPhi.value = 2;
86
+ this.pdMaterial.uniforms.normalPhi.value = 3;
87
+ this.pdMaterial.uniforms.radius.value = 8;
88
+
89
+ this.depthRenderMaterial = new ShaderMaterial( {
90
+ defines: Object.assign( {}, GTAODepthShader.defines ),
91
+ uniforms: UniformsUtils.clone( GTAODepthShader.uniforms ),
92
+ vertexShader: GTAODepthShader.vertexShader,
93
+ fragmentShader: GTAODepthShader.fragmentShader,
94
+ blending: NoBlending
95
+ } );
96
+ this.depthRenderMaterial.uniforms.cameraNear.value = this.camera.near;
97
+ this.depthRenderMaterial.uniforms.cameraFar.value = this.camera.far;
98
+
99
+ this.copyMaterial = new ShaderMaterial( {
100
+ uniforms: UniformsUtils.clone( CopyShader.uniforms ),
101
+ vertexShader: CopyShader.vertexShader,
102
+ fragmentShader: CopyShader.fragmentShader,
103
+ transparent: true,
104
+ depthTest: false,
105
+ depthWrite: false,
106
+ blendSrc: DstColorFactor,
107
+ blendDst: ZeroFactor,
108
+ blendEquation: AddEquation,
109
+ blendSrcAlpha: DstAlphaFactor,
110
+ blendDstAlpha: ZeroFactor,
111
+ blendEquationAlpha: AddEquation
112
+ } );
113
+
114
+ this.blendMaterial = new ShaderMaterial( {
115
+ uniforms: UniformsUtils.clone( GTAOBlendShader.uniforms ),
116
+ vertexShader: GTAOBlendShader.vertexShader,
117
+ fragmentShader: GTAOBlendShader.fragmentShader,
118
+ transparent: true,
119
+ depthTest: false,
120
+ depthWrite: false,
121
+ blending: CustomBlending,
122
+ blendSrc: DstColorFactor,
123
+ blendDst: ZeroFactor,
124
+ blendEquation: AddEquation,
125
+ blendSrcAlpha: DstAlphaFactor,
126
+ blendDstAlpha: ZeroFactor,
127
+ blendEquationAlpha: AddEquation
128
+ } );
129
+
130
+ this.fsQuad = new FullScreenQuad( null );
131
+
132
+ this.originalClearColor = new Color();
133
+
134
+ this.setGBuffer( parameters ? parameters.depthTexture : undefined, parameters ? parameters.normalTexture : undefined );
135
+
136
+ if ( aoParameters !== undefined ) {
137
+
138
+ this.updateGtaoMaterial( aoParameters );
139
+
140
+ }
141
+
142
+ if ( pdParameters !== undefined ) {
143
+
144
+ this.updatePdMaterial( pdParameters );
145
+
146
+ }
147
+
148
+ }
149
+
150
+ dispose() {
151
+
152
+ this.gtaoNoiseTexture.dispose();
153
+ this.pdNoiseTexture.dispose();
154
+ this.normalRenderTarget.dispose();
155
+ this.gtaoRenderTarget.dispose();
156
+ this.pdRenderTarget.dispose();
157
+ this.normalMaterial.dispose();
158
+ this.pdMaterial.dispose();
159
+ this.copyMaterial.dispose();
160
+ this.depthRenderMaterial.dispose();
161
+ this.fsQuad.dispose();
162
+
163
+ }
164
+
165
+ get gtaoMap() {
166
+
167
+ return this.pdRenderTarget.texture;
168
+
169
+ }
170
+
171
+ setGBuffer( depthTexture, normalTexture ) {
172
+
173
+ if ( depthTexture !== undefined ) {
174
+
175
+ this.depthTexture = depthTexture;
176
+ this.normalTexture = normalTexture;
177
+ this._renderGBuffer = false;
178
+
179
+ } else {
180
+
181
+ this.depthTexture = new DepthTexture();
182
+ this.depthTexture.format = DepthStencilFormat;
183
+ this.depthTexture.type = UnsignedInt248Type;
184
+ this.normalRenderTarget = new WebGLRenderTarget( this.width, this.height, {
185
+ minFilter: NearestFilter,
186
+ magFilter: NearestFilter,
187
+ type: HalfFloatType,
188
+ depthTexture: this.depthTexture
189
+ } );
190
+ this.normalTexture = this.normalRenderTarget.texture;
191
+ this._renderGBuffer = true;
192
+
193
+ }
194
+
195
+ const normalVectorType = ( this.normalTexture ) ? 1 : 0;
196
+ const depthValueSource = ( this.depthTexture === this.normalTexture ) ? 'w' : 'x';
197
+
198
+ this.gtaoMaterial.defines.NORMAL_VECTOR_TYPE = normalVectorType;
199
+ this.gtaoMaterial.defines.DEPTH_SWIZZLING = depthValueSource;
200
+ this.gtaoMaterial.uniforms.tNormal.value = this.normalTexture;
201
+ this.gtaoMaterial.uniforms.tDepth.value = this.depthTexture;
202
+
203
+ this.pdMaterial.defines.NORMAL_VECTOR_TYPE = normalVectorType;
204
+ this.pdMaterial.defines.DEPTH_SWIZZLING = depthValueSource;
205
+ this.pdMaterial.uniforms.tNormal.value = this.normalTexture;
206
+ this.pdMaterial.uniforms.tDepth.value = this.depthTexture;
207
+
208
+ this.depthRenderMaterial.uniforms.tDepth.value = this.normalRenderTarget.depthTexture;
209
+
210
+ }
211
+
212
+ setSceneClipBox( box ) {
213
+
214
+ if ( box ) {
215
+
216
+ this.gtaoMaterial.needsUpdate = this.gtaoMaterial.defines.SCENE_CLIP_BOX !== 1;
217
+ this.gtaoMaterial.defines.SCENE_CLIP_BOX = 1;
218
+ this.gtaoMaterial.uniforms.sceneBoxMin.value.copy( box.min );
219
+ this.gtaoMaterial.uniforms.sceneBoxMax.value.copy( box.max );
220
+
221
+ } else {
222
+
223
+ this.gtaoMaterial.needsUpdate = this.gtaoMaterial.defines.SCENE_CLIP_BOX === 0;
224
+ this.gtaoMaterial.defines.SCENE_CLIP_BOX = 0;
225
+
226
+ }
227
+
228
+ }
229
+
230
+ updateGtaoMaterial( parameters ) {
231
+
232
+ if ( parameters.radius !== undefined ) {
233
+
234
+ this.gtaoMaterial.uniforms.radius.value = parameters.radius;
235
+
236
+ }
237
+
238
+ if ( parameters.distanceExponent !== undefined ) {
239
+
240
+ this.gtaoMaterial.uniforms.distanceExponent.value = parameters.distanceExponent;
241
+
242
+ }
243
+
244
+ if ( parameters.thickness !== undefined ) {
245
+
246
+ this.gtaoMaterial.uniforms.thickness.value = parameters.thickness;
247
+
248
+ }
249
+
250
+ if ( parameters.distanceFallOff !== undefined ) {
251
+
252
+ this.gtaoMaterial.uniforms.distanceFallOff.value = parameters.distanceFallOff;
253
+ this.gtaoMaterial.needsUpdate = true;
254
+
255
+ }
256
+
257
+ if ( parameters.scale !== undefined ) {
258
+
259
+ this.gtaoMaterial.uniforms.scale.value = parameters.scale;
260
+
261
+ }
262
+
263
+ if ( parameters.samples !== undefined && parameters.samples !== this.gtaoMaterial.defines.SAMPLES ) {
264
+
265
+ this.gtaoMaterial.defines.SAMPLES = parameters.samples;
266
+ this.gtaoMaterial.needsUpdate = true;
267
+
268
+ }
269
+
270
+ if ( parameters.screenSpaceRadius !== undefined && ( parameters.screenSpaceRadius ? 1 : 0 ) !== this.gtaoMaterial.defines.SCREEN_SPACE_RADIUS ) {
271
+
272
+ this.gtaoMaterial.defines.SCREEN_SPACE_RADIUS = parameters.screenSpaceRadius ? 1 : 0;
273
+ this.gtaoMaterial.needsUpdate = true;
274
+
275
+ }
276
+
277
+ }
278
+
279
+ updatePdMaterial( parameters ) {
280
+
281
+ let updateShader = false;
282
+
283
+ if ( parameters.lumaPhi !== undefined ) {
284
+
285
+ this.pdMaterial.uniforms.lumaPhi.value = parameters.lumaPhi;
286
+
287
+ }
288
+
289
+ if ( parameters.depthPhi !== undefined ) {
290
+
291
+ this.pdMaterial.uniforms.depthPhi.value = parameters.depthPhi;
292
+
293
+ }
294
+
295
+ if ( parameters.normalPhi !== undefined ) {
296
+
297
+ this.pdMaterial.uniforms.normalPhi.value = parameters.normalPhi;
298
+
299
+ }
300
+
301
+ if ( parameters.radius !== undefined && parameters.radius !== this.radius ) {
302
+
303
+ this.pdMaterial.uniforms.radius.value = parameters.radius;
304
+
305
+ }
306
+
307
+ if ( parameters.radiusExponent !== undefined && parameters.radiusExponent !== this.pdRadiusExponent ) {
308
+
309
+ this.pdRadiusExponent = parameters.radiusExponent;
310
+ updateShader = true;
311
+
312
+ }
313
+
314
+ if ( parameters.rings !== undefined && parameters.rings !== this.pdRings ) {
315
+
316
+ this.pdRings = parameters.rings;
317
+ updateShader = true;
318
+
319
+ }
320
+
321
+ if ( parameters.samples !== undefined && parameters.samples !== this.pdSamples ) {
322
+
323
+ this.pdSamples = parameters.samples;
324
+ updateShader = true;
325
+
326
+ }
327
+
328
+ if ( updateShader ) {
329
+
330
+ this.pdMaterial.defines.SAMPLES = this.pdSamples;
331
+ this.pdMaterial.defines.SAMPLE_VECTORS = generatePdSamplePointInitializer( this.pdSamples, this.pdRings, this.pdRadiusExponent );
332
+ this.pdMaterial.needsUpdate = true;
333
+
334
+ }
335
+
336
+ }
337
+
338
+ render( renderer, writeBuffer, readBuffer /*, deltaTime, maskActive */ ) {
339
+
340
+ // render normals and depth (honor only meshes, points and lines do not contribute to AO)
341
+
342
+ if ( this._renderGBuffer ) {
343
+
344
+ this.overrideVisibility();
345
+ this.renderOverride( renderer, this.normalMaterial, this.normalRenderTarget, 0x7777ff, 1.0 );
346
+ this.restoreVisibility();
347
+
348
+ }
349
+
350
+ // render AO
351
+
352
+ this.gtaoMaterial.uniforms.cameraNear.value = this.camera.near;
353
+ this.gtaoMaterial.uniforms.cameraFar.value = this.camera.far;
354
+ this.gtaoMaterial.uniforms.cameraProjectionMatrix.value.copy( this.camera.projectionMatrix );
355
+ this.gtaoMaterial.uniforms.cameraProjectionMatrixInverse.value.copy( this.camera.projectionMatrixInverse );
356
+ this.gtaoMaterial.uniforms.cameraWorldMatrix.value.copy( this.camera.matrixWorld );
357
+ this.renderPass( renderer, this.gtaoMaterial, this.gtaoRenderTarget, 0xffffff, 1.0 );
358
+
359
+ // render poisson denoise
360
+
361
+ this.pdMaterial.uniforms.cameraProjectionMatrixInverse.value.copy( this.camera.projectionMatrixInverse );
362
+ this.renderPass( renderer, this.pdMaterial, this.pdRenderTarget, 0xffffff, 1.0 );
363
+
364
+ // output result to screen
365
+
366
+ switch ( this.output ) {
367
+
368
+ case GTAOPass.OUTPUT.Off:
369
+ break;
370
+
371
+ case GTAOPass.OUTPUT.Diffuse:
372
+
373
+ this.copyMaterial.uniforms.tDiffuse.value = readBuffer.texture;
374
+ this.copyMaterial.blending = NoBlending;
375
+ this.renderPass( renderer, this.copyMaterial, this.renderToScreen ? null : writeBuffer );
376
+
377
+ break;
378
+
379
+ case GTAOPass.OUTPUT.AO:
380
+
381
+ this.copyMaterial.uniforms.tDiffuse.value = this.gtaoRenderTarget.texture;
382
+ this.copyMaterial.blending = NoBlending;
383
+ this.renderPass( renderer, this.copyMaterial, this.renderToScreen ? null : writeBuffer );
384
+
385
+ break;
386
+
387
+ case GTAOPass.OUTPUT.Denoise:
388
+
389
+ this.copyMaterial.uniforms.tDiffuse.value = this.pdRenderTarget.texture;
390
+ this.copyMaterial.blending = NoBlending;
391
+ this.renderPass( renderer, this.copyMaterial, this.renderToScreen ? null : writeBuffer );
392
+
393
+ break;
394
+
395
+ case GTAOPass.OUTPUT.Depth:
396
+
397
+ this.depthRenderMaterial.uniforms.cameraNear.value = this.camera.near;
398
+ this.depthRenderMaterial.uniforms.cameraFar.value = this.camera.far;
399
+ this.renderPass( renderer, this.depthRenderMaterial, this.renderToScreen ? null : writeBuffer );
400
+
401
+ break;
402
+
403
+ case GTAOPass.OUTPUT.Normal:
404
+
405
+ this.copyMaterial.uniforms.tDiffuse.value = this.normalRenderTarget.texture;
406
+ this.copyMaterial.blending = NoBlending;
407
+ this.renderPass( renderer, this.copyMaterial, this.renderToScreen ? null : writeBuffer );
408
+
409
+ break;
410
+
411
+ case GTAOPass.OUTPUT.Default:
412
+
413
+ this.copyMaterial.uniforms.tDiffuse.value = readBuffer.texture;
414
+ this.copyMaterial.blending = NoBlending;
415
+ this.renderPass( renderer, this.copyMaterial, this.renderToScreen ? null : writeBuffer );
416
+
417
+ this.blendMaterial.uniforms.intensity.value = this.blendIntensity;
418
+ this.blendMaterial.uniforms.tDiffuse.value = this.pdRenderTarget.texture;
419
+ this.renderPass( renderer, this.blendMaterial, this.renderToScreen ? null : writeBuffer );
420
+
421
+ break;
422
+
423
+ default:
424
+ console.warn( 'THREE.GTAOPass: Unknown output type.' );
425
+
426
+ }
427
+
428
+ }
429
+
430
+ renderPass( renderer, passMaterial, renderTarget, clearColor, clearAlpha ) {
431
+
432
+ // save original state
433
+ renderer.getClearColor( this.originalClearColor );
434
+ const originalClearAlpha = renderer.getClearAlpha();
435
+ const originalAutoClear = renderer.autoClear;
436
+
437
+ renderer.setRenderTarget( renderTarget );
438
+
439
+ // setup pass state
440
+ renderer.autoClear = false;
441
+ if ( ( clearColor !== undefined ) && ( clearColor !== null ) ) {
442
+
443
+ renderer.setClearColor( clearColor );
444
+ renderer.setClearAlpha( clearAlpha || 0.0 );
445
+ renderer.clear();
446
+
447
+ }
448
+
449
+ this.fsQuad.material = passMaterial;
450
+ this.fsQuad.render( renderer );
451
+
452
+ // restore original state
453
+ renderer.autoClear = originalAutoClear;
454
+ renderer.setClearColor( this.originalClearColor );
455
+ renderer.setClearAlpha( originalClearAlpha );
456
+
457
+ }
458
+
459
+ renderOverride( renderer, overrideMaterial, renderTarget, clearColor, clearAlpha ) {
460
+
461
+ renderer.getClearColor( this.originalClearColor );
462
+ const originalClearAlpha = renderer.getClearAlpha();
463
+ const originalAutoClear = renderer.autoClear;
464
+
465
+ renderer.setRenderTarget( renderTarget );
466
+ renderer.autoClear = false;
467
+
468
+ clearColor = overrideMaterial.clearColor || clearColor;
469
+ clearAlpha = overrideMaterial.clearAlpha || clearAlpha;
470
+
471
+ if ( ( clearColor !== undefined ) && ( clearColor !== null ) ) {
472
+
473
+ renderer.setClearColor( clearColor );
474
+ renderer.setClearAlpha( clearAlpha || 0.0 );
475
+ renderer.clear();
476
+
477
+ }
478
+
479
+ this.scene.overrideMaterial = overrideMaterial;
480
+ renderer.render( this.scene, this.camera );
481
+ this.scene.overrideMaterial = null;
482
+
483
+ renderer.autoClear = originalAutoClear;
484
+ renderer.setClearColor( this.originalClearColor );
485
+ renderer.setClearAlpha( originalClearAlpha );
486
+
487
+ }
488
+
489
+ setSize( width, height ) {
490
+
491
+ this.width = width;
492
+ this.height = height;
493
+
494
+ this.gtaoRenderTarget.setSize( width, height );
495
+ this.normalRenderTarget.setSize( width, height );
496
+ this.pdRenderTarget.setSize( width, height );
497
+
498
+ this.gtaoMaterial.uniforms.resolution.value.set( width, height );
499
+ this.gtaoMaterial.uniforms.cameraProjectionMatrix.value.copy( this.camera.projectionMatrix );
500
+ this.gtaoMaterial.uniforms.cameraProjectionMatrixInverse.value.copy( this.camera.projectionMatrixInverse );
501
+
502
+ this.pdMaterial.uniforms.resolution.value.set( width, height );
503
+ this.pdMaterial.uniforms.cameraProjectionMatrixInverse.value.copy( this.camera.projectionMatrixInverse );
504
+
505
+ }
506
+
507
+ overrideVisibility() {
508
+
509
+ const scene = this.scene;
510
+ const cache = this._visibilityCache;
511
+
512
+ scene.traverse( function ( object ) {
513
+
514
+ cache.set( object, object.visible );
515
+
516
+ if ( object.isPoints || object.isLine ) object.visible = false;
517
+
518
+ } );
519
+
520
+ }
521
+
522
+ restoreVisibility() {
523
+
524
+ const scene = this.scene;
525
+ const cache = this._visibilityCache;
526
+
527
+ scene.traverse( function ( object ) {
528
+
529
+ const visible = cache.get( object );
530
+ object.visible = visible;
531
+
532
+ } );
533
+
534
+ cache.clear();
535
+
536
+ }
537
+
538
+ generateNoise( size = 64 ) {
539
+
540
+ const simplex = new SimplexNoise();
541
+
542
+ const arraySize = size * size * 4;
543
+ const data = new Uint8Array( arraySize );
544
+
545
+ for ( let i = 0; i < size; i ++ ) {
546
+
547
+ for ( let j = 0; j < size; j ++ ) {
548
+
549
+ const x = i;
550
+ const y = j;
551
+
552
+ data[ ( i * size + j ) * 4 ] = ( simplex.noise( x, y ) * 0.5 + 0.5 ) * 255;
553
+ data[ ( i * size + j ) * 4 + 1 ] = ( simplex.noise( x + size, y ) * 0.5 + 0.5 ) * 255;
554
+ data[ ( i * size + j ) * 4 + 2 ] = ( simplex.noise( x, y + size ) * 0.5 + 0.5 ) * 255;
555
+ data[ ( i * size + j ) * 4 + 3 ] = ( simplex.noise( x + size, y + size ) * 0.5 + 0.5 ) * 255;
556
+
557
+ }
558
+
559
+ }
560
+
561
+ const noiseTexture = new DataTexture( data, size, size, RGBAFormat, UnsignedByteType );
562
+ noiseTexture.wrapS = RepeatWrapping;
563
+ noiseTexture.wrapT = RepeatWrapping;
564
+ noiseTexture.needsUpdate = true;
565
+
566
+ return noiseTexture;
567
+
568
+ }
569
+
570
+ }
571
+
572
+ GTAOPass.OUTPUT = {
573
+ 'Off': - 1,
574
+ 'Default': 0,
575
+ 'Diffuse': 1,
576
+ 'Depth': 2,
577
+ 'Normal': 3,
578
+ 'AO': 4,
579
+ 'Denoise': 5,
580
+ };
581
+
582
+ export { GTAOPass };
vendor/addons/shaders/BokehShader.js ADDED
@@ -0,0 +1,145 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * Depth-of-field shader with bokeh
3
+ * ported from GLSL shader by Martins Upitis
4
+ * http://artmartinsh.blogspot.com/2010/02/glsl-lens-blur-filter-with-bokeh.html
5
+ */
6
+
7
+ const BokehShader = {
8
+
9
+ name: 'BokehShader',
10
+
11
+ defines: {
12
+ 'DEPTH_PACKING': 1,
13
+ 'PERSPECTIVE_CAMERA': 1,
14
+ },
15
+
16
+ uniforms: {
17
+
18
+ 'tColor': { value: null },
19
+ 'tDepth': { value: null },
20
+ 'focus': { value: 1.0 },
21
+ 'aspect': { value: 1.0 },
22
+ 'aperture': { value: 0.025 },
23
+ 'maxblur': { value: 0.01 },
24
+ 'nearClip': { value: 1.0 },
25
+ 'farClip': { value: 1000.0 },
26
+
27
+ },
28
+
29
+ vertexShader: /* glsl */`
30
+
31
+ varying vec2 vUv;
32
+
33
+ void main() {
34
+
35
+ vUv = uv;
36
+ gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
37
+
38
+ }`,
39
+
40
+ fragmentShader: /* glsl */`
41
+
42
+ #include <common>
43
+
44
+ varying vec2 vUv;
45
+
46
+ uniform sampler2D tColor;
47
+ uniform sampler2D tDepth;
48
+
49
+ uniform float maxblur; // max blur amount
50
+ uniform float aperture; // aperture - bigger values for shallower depth of field
51
+
52
+ uniform float nearClip;
53
+ uniform float farClip;
54
+
55
+ uniform float focus;
56
+ uniform float aspect;
57
+
58
+ #include <packing>
59
+
60
+ float getDepth( const in vec2 screenPosition ) {
61
+ #if DEPTH_PACKING == 1
62
+ return unpackRGBAToDepth( texture2D( tDepth, screenPosition ) );
63
+ #else
64
+ return texture2D( tDepth, screenPosition ).x;
65
+ #endif
66
+ }
67
+
68
+ float getViewZ( const in float depth ) {
69
+ #if PERSPECTIVE_CAMERA == 1
70
+ return perspectiveDepthToViewZ( depth, nearClip, farClip );
71
+ #else
72
+ return orthographicDepthToViewZ( depth, nearClip, farClip );
73
+ #endif
74
+ }
75
+
76
+
77
+ void main() {
78
+
79
+ vec2 aspectcorrect = vec2( 1.0, aspect );
80
+
81
+ float viewZ = getViewZ( getDepth( vUv ) );
82
+
83
+ float factor = ( focus + viewZ ); // viewZ is <= 0, so this is a difference equation
84
+
85
+ vec2 dofblur = vec2 ( clamp( factor * aperture, -maxblur, maxblur ) );
86
+
87
+ vec2 dofblur9 = dofblur * 0.9;
88
+ vec2 dofblur7 = dofblur * 0.7;
89
+ vec2 dofblur4 = dofblur * 0.4;
90
+
91
+ vec4 col = vec4( 0.0 );
92
+
93
+ col += texture2D( tColor, vUv.xy );
94
+ col += texture2D( tColor, vUv.xy + ( vec2( 0.0, 0.4 ) * aspectcorrect ) * dofblur );
95
+ col += texture2D( tColor, vUv.xy + ( vec2( 0.15, 0.37 ) * aspectcorrect ) * dofblur );
96
+ col += texture2D( tColor, vUv.xy + ( vec2( 0.29, 0.29 ) * aspectcorrect ) * dofblur );
97
+ col += texture2D( tColor, vUv.xy + ( vec2( -0.37, 0.15 ) * aspectcorrect ) * dofblur );
98
+ col += texture2D( tColor, vUv.xy + ( vec2( 0.40, 0.0 ) * aspectcorrect ) * dofblur );
99
+ col += texture2D( tColor, vUv.xy + ( vec2( 0.37, -0.15 ) * aspectcorrect ) * dofblur );
100
+ col += texture2D( tColor, vUv.xy + ( vec2( 0.29, -0.29 ) * aspectcorrect ) * dofblur );
101
+ col += texture2D( tColor, vUv.xy + ( vec2( -0.15, -0.37 ) * aspectcorrect ) * dofblur );
102
+ col += texture2D( tColor, vUv.xy + ( vec2( 0.0, -0.4 ) * aspectcorrect ) * dofblur );
103
+ col += texture2D( tColor, vUv.xy + ( vec2( -0.15, 0.37 ) * aspectcorrect ) * dofblur );
104
+ col += texture2D( tColor, vUv.xy + ( vec2( -0.29, 0.29 ) * aspectcorrect ) * dofblur );
105
+ col += texture2D( tColor, vUv.xy + ( vec2( 0.37, 0.15 ) * aspectcorrect ) * dofblur );
106
+ col += texture2D( tColor, vUv.xy + ( vec2( -0.4, 0.0 ) * aspectcorrect ) * dofblur );
107
+ col += texture2D( tColor, vUv.xy + ( vec2( -0.37, -0.15 ) * aspectcorrect ) * dofblur );
108
+ col += texture2D( tColor, vUv.xy + ( vec2( -0.29, -0.29 ) * aspectcorrect ) * dofblur );
109
+ col += texture2D( tColor, vUv.xy + ( vec2( 0.15, -0.37 ) * aspectcorrect ) * dofblur );
110
+
111
+ col += texture2D( tColor, vUv.xy + ( vec2( 0.15, 0.37 ) * aspectcorrect ) * dofblur9 );
112
+ col += texture2D( tColor, vUv.xy + ( vec2( -0.37, 0.15 ) * aspectcorrect ) * dofblur9 );
113
+ col += texture2D( tColor, vUv.xy + ( vec2( 0.37, -0.15 ) * aspectcorrect ) * dofblur9 );
114
+ col += texture2D( tColor, vUv.xy + ( vec2( -0.15, -0.37 ) * aspectcorrect ) * dofblur9 );
115
+ col += texture2D( tColor, vUv.xy + ( vec2( -0.15, 0.37 ) * aspectcorrect ) * dofblur9 );
116
+ col += texture2D( tColor, vUv.xy + ( vec2( 0.37, 0.15 ) * aspectcorrect ) * dofblur9 );
117
+ col += texture2D( tColor, vUv.xy + ( vec2( -0.37, -0.15 ) * aspectcorrect ) * dofblur9 );
118
+ col += texture2D( tColor, vUv.xy + ( vec2( 0.15, -0.37 ) * aspectcorrect ) * dofblur9 );
119
+
120
+ col += texture2D( tColor, vUv.xy + ( vec2( 0.29, 0.29 ) * aspectcorrect ) * dofblur7 );
121
+ col += texture2D( tColor, vUv.xy + ( vec2( 0.40, 0.0 ) * aspectcorrect ) * dofblur7 );
122
+ col += texture2D( tColor, vUv.xy + ( vec2( 0.29, -0.29 ) * aspectcorrect ) * dofblur7 );
123
+ col += texture2D( tColor, vUv.xy + ( vec2( 0.0, -0.4 ) * aspectcorrect ) * dofblur7 );
124
+ col += texture2D( tColor, vUv.xy + ( vec2( -0.29, 0.29 ) * aspectcorrect ) * dofblur7 );
125
+ col += texture2D( tColor, vUv.xy + ( vec2( -0.4, 0.0 ) * aspectcorrect ) * dofblur7 );
126
+ col += texture2D( tColor, vUv.xy + ( vec2( -0.29, -0.29 ) * aspectcorrect ) * dofblur7 );
127
+ col += texture2D( tColor, vUv.xy + ( vec2( 0.0, 0.4 ) * aspectcorrect ) * dofblur7 );
128
+
129
+ col += texture2D( tColor, vUv.xy + ( vec2( 0.29, 0.29 ) * aspectcorrect ) * dofblur4 );
130
+ col += texture2D( tColor, vUv.xy + ( vec2( 0.4, 0.0 ) * aspectcorrect ) * dofblur4 );
131
+ col += texture2D( tColor, vUv.xy + ( vec2( 0.29, -0.29 ) * aspectcorrect ) * dofblur4 );
132
+ col += texture2D( tColor, vUv.xy + ( vec2( 0.0, -0.4 ) * aspectcorrect ) * dofblur4 );
133
+ col += texture2D( tColor, vUv.xy + ( vec2( -0.29, 0.29 ) * aspectcorrect ) * dofblur4 );
134
+ col += texture2D( tColor, vUv.xy + ( vec2( -0.4, 0.0 ) * aspectcorrect ) * dofblur4 );
135
+ col += texture2D( tColor, vUv.xy + ( vec2( -0.29, -0.29 ) * aspectcorrect ) * dofblur4 );
136
+ col += texture2D( tColor, vUv.xy + ( vec2( 0.0, 0.4 ) * aspectcorrect ) * dofblur4 );
137
+
138
+ gl_FragColor = col / 41.0;
139
+ gl_FragColor.a = 1.0;
140
+
141
+ }`
142
+
143
+ };
144
+
145
+ export { BokehShader };
vendor/addons/shaders/GTAOShader.js ADDED
@@ -0,0 +1,424 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import {
2
+ DataTexture,
3
+ Matrix4,
4
+ RepeatWrapping,
5
+ Vector2,
6
+ Vector3,
7
+ } from '../../three.module.min.js';
8
+
9
+ /**
10
+ * References:
11
+ * - implemented algorithm - GTAO
12
+ * - https://iryoku.com/downloads/Practical-Realtime-Strategies-for-Accurate-Indirect-Occlusion.pdf
13
+ * - https://github.com/Patapom/GodComplex/blob/master/Tests/TestHBIL/2018%20Mayaux%20-%20Horizon-Based%20Indirect%20Lighting%20(HBIL).pdf
14
+ *
15
+ * - other AO algorithms that are not implemented here:
16
+ * - Screen Space Ambient Occlusion (SSAO), see also SSAOShader.js
17
+ * - http://john-chapman-graphics.blogspot.com/2013/01/ssao-tutorial.html
18
+ * - https://learnopengl.com/Advanced-Lighting/SSAO
19
+ * - https://creativecoding.soe.ucsc.edu/courses/cmpm164/_schedule/AmbientOcclusion.pdf
20
+ * - https://drive.google.com/file/d/1SyagcEVplIm2KkRD3WQYSO9O0Iyi1hfy/edit
21
+ * - Scalable Ambient Occlusion (SAO), see also SAOShader.js
22
+ * - https://casual-effects.com/research/McGuire2012SAO/index.html
23
+ * - https://research.nvidia.com/sites/default/files/pubs/2012-06_Scalable-Ambient-Obscurance/McGuire12SAO.pdf
24
+ * - N8HO
25
+ * - https://github.com/N8python/n8ao
26
+ * - Horizon Based Ambient Occlusion (HBAO)
27
+ * - http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.577.2286&rep=rep1&type=pdf
28
+ * - https://www.derschmale.com/2013/12/20/an-alternative-implementation-for-hbao-2/
29
+ *
30
+ * - further reading
31
+ * - https://ceur-ws.org/Vol-3027/paper5.pdf
32
+ * - https://www.comp.nus.edu.sg/~lowkl/publications/mssao_visual_computer_2012.pdf
33
+ * - https://web.ics.purdue.edu/~tmcgraw/papers/mcgraw-ao-2008.pdf
34
+ * - https://www.activision.com/cdn/research/Practical_Real_Time_Strategies_for_Accurate_Indirect_Occlusion_NEW%20VERSION_COLOR.pdf
35
+ * - https://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.390.2463&rep=rep1&type=pdf
36
+ * - https://www.intel.com/content/www/us/en/developer/articles/technical/adaptive-screen-space-ambient-occlusion.html
37
+ */
38
+
39
+ const GTAOShader = {
40
+
41
+ name: 'GTAOShader',
42
+
43
+ defines: {
44
+ PERSPECTIVE_CAMERA: 1,
45
+ SAMPLES: 16,
46
+ NORMAL_VECTOR_TYPE: 1,
47
+ DEPTH_SWIZZLING: 'x',
48
+ SCREEN_SPACE_RADIUS: 0,
49
+ SCREEN_SPACE_RADIUS_SCALE: 100.0,
50
+ SCENE_CLIP_BOX: 0,
51
+ },
52
+
53
+ uniforms: {
54
+ tNormal: { value: null },
55
+ tDepth: { value: null },
56
+ tNoise: { value: null },
57
+ resolution: { value: new Vector2() },
58
+ cameraNear: { value: null },
59
+ cameraFar: { value: null },
60
+ cameraProjectionMatrix: { value: new Matrix4() },
61
+ cameraProjectionMatrixInverse: { value: new Matrix4() },
62
+ cameraWorldMatrix: { value: new Matrix4() },
63
+ radius: { value: 0.25 },
64
+ distanceExponent: { value: 1. },
65
+ thickness: { value: 1. },
66
+ distanceFallOff: { value: 1. },
67
+ scale: { value: 1. },
68
+ sceneBoxMin: { value: new Vector3( - 1, - 1, - 1 ) },
69
+ sceneBoxMax: { value: new Vector3( 1, 1, 1 ) },
70
+ },
71
+
72
+ vertexShader: /* glsl */`
73
+
74
+ varying vec2 vUv;
75
+
76
+ void main() {
77
+ vUv = uv;
78
+ gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
79
+ }`,
80
+
81
+ fragmentShader: /* glsl */`
82
+ varying vec2 vUv;
83
+ uniform highp sampler2D tNormal;
84
+ uniform highp sampler2D tDepth;
85
+ uniform sampler2D tNoise;
86
+ uniform vec2 resolution;
87
+ uniform float cameraNear;
88
+ uniform float cameraFar;
89
+ uniform mat4 cameraProjectionMatrix;
90
+ uniform mat4 cameraProjectionMatrixInverse;
91
+ uniform mat4 cameraWorldMatrix;
92
+ uniform float radius;
93
+ uniform float distanceExponent;
94
+ uniform float thickness;
95
+ uniform float distanceFallOff;
96
+ uniform float scale;
97
+ #if SCENE_CLIP_BOX == 1
98
+ uniform vec3 sceneBoxMin;
99
+ uniform vec3 sceneBoxMax;
100
+ #endif
101
+
102
+ #include <common>
103
+ #include <packing>
104
+
105
+ #ifndef FRAGMENT_OUTPUT
106
+ #define FRAGMENT_OUTPUT vec4(vec3(ao), 1.)
107
+ #endif
108
+
109
+ vec3 getViewPosition(const in vec2 screenPosition, const in float depth) {
110
+ vec4 clipSpacePosition = vec4(vec3(screenPosition, depth) * 2.0 - 1.0, 1.0);
111
+ vec4 viewSpacePosition = cameraProjectionMatrixInverse * clipSpacePosition;
112
+ return viewSpacePosition.xyz / viewSpacePosition.w;
113
+ }
114
+
115
+ float getDepth(const vec2 uv) {
116
+ return textureLod(tDepth, uv.xy, 0.0).DEPTH_SWIZZLING;
117
+ }
118
+
119
+ float fetchDepth(const ivec2 uv) {
120
+ return texelFetch(tDepth, uv.xy, 0).DEPTH_SWIZZLING;
121
+ }
122
+
123
+ float getViewZ(const in float depth) {
124
+ #if PERSPECTIVE_CAMERA == 1
125
+ return perspectiveDepthToViewZ(depth, cameraNear, cameraFar);
126
+ #else
127
+ return orthographicDepthToViewZ(depth, cameraNear, cameraFar);
128
+ #endif
129
+ }
130
+
131
+ vec3 computeNormalFromDepth(const vec2 uv) {
132
+ vec2 size = vec2(textureSize(tDepth, 0));
133
+ ivec2 p = ivec2(uv * size);
134
+ float c0 = fetchDepth(p);
135
+ float l2 = fetchDepth(p - ivec2(2, 0));
136
+ float l1 = fetchDepth(p - ivec2(1, 0));
137
+ float r1 = fetchDepth(p + ivec2(1, 0));
138
+ float r2 = fetchDepth(p + ivec2(2, 0));
139
+ float b2 = fetchDepth(p - ivec2(0, 2));
140
+ float b1 = fetchDepth(p - ivec2(0, 1));
141
+ float t1 = fetchDepth(p + ivec2(0, 1));
142
+ float t2 = fetchDepth(p + ivec2(0, 2));
143
+ float dl = abs((2.0 * l1 - l2) - c0);
144
+ float dr = abs((2.0 * r1 - r2) - c0);
145
+ float db = abs((2.0 * b1 - b2) - c0);
146
+ float dt = abs((2.0 * t1 - t2) - c0);
147
+ vec3 ce = getViewPosition(uv, c0).xyz;
148
+ vec3 dpdx = (dl < dr) ? ce - getViewPosition((uv - vec2(1.0 / size.x, 0.0)), l1).xyz : -ce + getViewPosition((uv + vec2(1.0 / size.x, 0.0)), r1).xyz;
149
+ vec3 dpdy = (db < dt) ? ce - getViewPosition((uv - vec2(0.0, 1.0 / size.y)), b1).xyz : -ce + getViewPosition((uv + vec2(0.0, 1.0 / size.y)), t1).xyz;
150
+ return normalize(cross(dpdx, dpdy));
151
+ }
152
+
153
+ vec3 getViewNormal(const vec2 uv) {
154
+ #if NORMAL_VECTOR_TYPE == 2
155
+ return normalize(textureLod(tNormal, uv, 0.).rgb);
156
+ #elif NORMAL_VECTOR_TYPE == 1
157
+ return unpackRGBToNormal(textureLod(tNormal, uv, 0.).rgb);
158
+ #else
159
+ return computeNormalFromDepth(uv);
160
+ #endif
161
+ }
162
+
163
+ vec3 getSceneUvAndDepth(vec3 sampleViewPos) {
164
+ vec4 sampleClipPos = cameraProjectionMatrix * vec4(sampleViewPos, 1.);
165
+ vec2 sampleUv = sampleClipPos.xy / sampleClipPos.w * 0.5 + 0.5;
166
+ float sampleSceneDepth = getDepth(sampleUv);
167
+ return vec3(sampleUv, sampleSceneDepth);
168
+ }
169
+
170
+ void main() {
171
+ float depth = getDepth(vUv.xy);
172
+ if (depth >= 1.0) {
173
+ discard;
174
+ return;
175
+ }
176
+ vec3 viewPos = getViewPosition(vUv, depth);
177
+ vec3 viewNormal = getViewNormal(vUv);
178
+
179
+ float radiusToUse = radius;
180
+ float distanceFalloffToUse = thickness;
181
+ #if SCREEN_SPACE_RADIUS == 1
182
+ float radiusScale = getViewPosition(vec2(0.5 + float(SCREEN_SPACE_RADIUS_SCALE) / resolution.x, 0.0), depth).x;
183
+ radiusToUse *= radiusScale;
184
+ distanceFalloffToUse *= radiusScale;
185
+ #endif
186
+
187
+ #if SCENE_CLIP_BOX == 1
188
+ vec3 worldPos = (cameraWorldMatrix * vec4(viewPos, 1.0)).xyz;
189
+ float boxDistance = length(max(vec3(0.0), max(sceneBoxMin - worldPos, worldPos - sceneBoxMax)));
190
+ if (boxDistance > radiusToUse) {
191
+ discard;
192
+ return;
193
+ }
194
+ #endif
195
+
196
+ vec2 noiseResolution = vec2(textureSize(tNoise, 0));
197
+ vec2 noiseUv = vUv * resolution / noiseResolution;
198
+ vec4 noiseTexel = textureLod(tNoise, noiseUv, 0.0);
199
+ vec3 randomVec = noiseTexel.xyz * 2.0 - 1.0;
200
+ vec3 tangent = normalize(vec3(randomVec.xy, 0.));
201
+ vec3 bitangent = vec3(-tangent.y, tangent.x, 0.);
202
+ mat3 kernelMatrix = mat3(tangent, bitangent, vec3(0., 0., 1.));
203
+
204
+ const int DIRECTIONS = SAMPLES < 30 ? 3 : 5;
205
+ const int STEPS = (SAMPLES + DIRECTIONS - 1) / DIRECTIONS;
206
+ float ao = 0.0;
207
+ for (int i = 0; i < DIRECTIONS; ++i) {
208
+
209
+ float angle = float(i) / float(DIRECTIONS) * PI;
210
+ vec4 sampleDir = vec4(cos(angle), sin(angle), 0., 0.5 + 0.5 * noiseTexel.w);
211
+ sampleDir.xyz = normalize(kernelMatrix * sampleDir.xyz);
212
+
213
+ vec3 viewDir = normalize(-viewPos.xyz);
214
+ vec3 sliceBitangent = normalize(cross(sampleDir.xyz, viewDir));
215
+ vec3 sliceTangent = cross(sliceBitangent, viewDir);
216
+ vec3 normalInSlice = normalize(viewNormal - sliceBitangent * dot(viewNormal, sliceBitangent));
217
+
218
+ vec3 tangentToNormalInSlice = cross(normalInSlice, sliceBitangent);
219
+ vec2 cosHorizons = vec2(dot(viewDir, tangentToNormalInSlice), dot(viewDir, -tangentToNormalInSlice));
220
+
221
+ for (int j = 0; j < STEPS; ++j) {
222
+ vec3 sampleViewOffset = sampleDir.xyz * radiusToUse * sampleDir.w * pow(float(j + 1) / float(STEPS), distanceExponent);
223
+
224
+ vec3 sampleSceneUvDepth = getSceneUvAndDepth(viewPos + sampleViewOffset);
225
+ vec3 sampleSceneViewPos = getViewPosition(sampleSceneUvDepth.xy, sampleSceneUvDepth.z);
226
+ vec3 viewDelta = sampleSceneViewPos - viewPos;
227
+ if (abs(viewDelta.z) < thickness) {
228
+ float sampleCosHorizon = dot(viewDir, normalize(viewDelta));
229
+ cosHorizons.x += max(0., (sampleCosHorizon - cosHorizons.x) * mix(1., 2. / float(j + 2), distanceFallOff));
230
+ }
231
+
232
+ sampleSceneUvDepth = getSceneUvAndDepth(viewPos - sampleViewOffset);
233
+ sampleSceneViewPos = getViewPosition(sampleSceneUvDepth.xy, sampleSceneUvDepth.z);
234
+ viewDelta = sampleSceneViewPos - viewPos;
235
+ if (abs(viewDelta.z) < thickness) {
236
+ float sampleCosHorizon = dot(viewDir, normalize(viewDelta));
237
+ cosHorizons.y += max(0., (sampleCosHorizon - cosHorizons.y) * mix(1., 2. / float(j + 2), distanceFallOff));
238
+ }
239
+ }
240
+
241
+ vec2 sinHorizons = sqrt(1. - cosHorizons * cosHorizons);
242
+ float nx = dot(normalInSlice, sliceTangent);
243
+ float ny = dot(normalInSlice, viewDir);
244
+ float nxb = 1. / 2. * (acos(cosHorizons.y) - acos(cosHorizons.x) + sinHorizons.x * cosHorizons.x - sinHorizons.y * cosHorizons.y);
245
+ float nyb = 1. / 2. * (2. - cosHorizons.x * cosHorizons.x - cosHorizons.y * cosHorizons.y);
246
+ float occlusion = nx * nxb + ny * nyb;
247
+ ao += occlusion;
248
+ }
249
+
250
+ ao = clamp(ao / float(DIRECTIONS), 0., 1.);
251
+ #if SCENE_CLIP_BOX == 1
252
+ ao = mix(ao, 1., smoothstep(0., radiusToUse, boxDistance));
253
+ #endif
254
+ ao = pow(ao, scale);
255
+
256
+ gl_FragColor = FRAGMENT_OUTPUT;
257
+ }`
258
+
259
+ };
260
+
261
+ const GTAODepthShader = {
262
+
263
+ name: 'GTAODepthShader',
264
+
265
+ defines: {
266
+ PERSPECTIVE_CAMERA: 1
267
+ },
268
+
269
+ uniforms: {
270
+ tDepth: { value: null },
271
+ cameraNear: { value: null },
272
+ cameraFar: { value: null },
273
+ },
274
+
275
+ vertexShader: /* glsl */`
276
+ varying vec2 vUv;
277
+
278
+ void main() {
279
+ vUv = uv;
280
+ gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
281
+ }`,
282
+
283
+ fragmentShader: /* glsl */`
284
+ uniform sampler2D tDepth;
285
+ uniform float cameraNear;
286
+ uniform float cameraFar;
287
+ varying vec2 vUv;
288
+
289
+ #include <packing>
290
+
291
+ float getLinearDepth( const in vec2 screenPosition ) {
292
+ #if PERSPECTIVE_CAMERA == 1
293
+ float fragCoordZ = texture2D( tDepth, screenPosition ).x;
294
+ float viewZ = perspectiveDepthToViewZ( fragCoordZ, cameraNear, cameraFar );
295
+ return viewZToOrthographicDepth( viewZ, cameraNear, cameraFar );
296
+ #else
297
+ return texture2D( tDepth, screenPosition ).x;
298
+ #endif
299
+ }
300
+
301
+ void main() {
302
+ float depth = getLinearDepth( vUv );
303
+ gl_FragColor = vec4( vec3( 1.0 - depth ), 1.0 );
304
+
305
+ }`
306
+
307
+ };
308
+
309
+ const GTAOBlendShader = {
310
+
311
+ name: 'GTAOBlendShader',
312
+
313
+ uniforms: {
314
+ tDiffuse: { value: null },
315
+ intensity: { value: 1.0 }
316
+ },
317
+
318
+ vertexShader: /* glsl */`
319
+ varying vec2 vUv;
320
+
321
+ void main() {
322
+ vUv = uv;
323
+ gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
324
+ }`,
325
+
326
+ fragmentShader: /* glsl */`
327
+ uniform float intensity;
328
+ uniform sampler2D tDiffuse;
329
+ varying vec2 vUv;
330
+
331
+ void main() {
332
+ vec4 texel = texture2D( tDiffuse, vUv );
333
+ gl_FragColor = vec4(mix(vec3(1.), texel.rgb, intensity), texel.a);
334
+ }`
335
+
336
+ };
337
+
338
+
339
+ function generateMagicSquareNoise( size = 5 ) {
340
+
341
+ const noiseSize = Math.floor( size ) % 2 === 0 ? Math.floor( size ) + 1 : Math.floor( size );
342
+ const magicSquare = generateMagicSquare( noiseSize );
343
+ const noiseSquareSize = magicSquare.length;
344
+ const data = new Uint8Array( noiseSquareSize * 4 );
345
+
346
+ for ( let inx = 0; inx < noiseSquareSize; ++ inx ) {
347
+
348
+ const iAng = magicSquare[ inx ];
349
+ const angle = ( 2 * Math.PI * iAng ) / noiseSquareSize;
350
+ const randomVec = new Vector3(
351
+ Math.cos( angle ),
352
+ Math.sin( angle ),
353
+ 0
354
+ ).normalize();
355
+ data[ inx * 4 ] = ( randomVec.x * 0.5 + 0.5 ) * 255;
356
+ data[ inx * 4 + 1 ] = ( randomVec.y * 0.5 + 0.5 ) * 255;
357
+ data[ inx * 4 + 2 ] = 127;
358
+ data[ inx * 4 + 3 ] = 255;
359
+
360
+ }
361
+
362
+ const noiseTexture = new DataTexture( data, noiseSize, noiseSize );
363
+ noiseTexture.wrapS = RepeatWrapping;
364
+ noiseTexture.wrapT = RepeatWrapping;
365
+ noiseTexture.needsUpdate = true;
366
+
367
+ return noiseTexture;
368
+
369
+ }
370
+
371
+ function generateMagicSquare( size ) {
372
+
373
+ const noiseSize = Math.floor( size ) % 2 === 0 ? Math.floor( size ) + 1 : Math.floor( size );
374
+ const noiseSquareSize = noiseSize * noiseSize;
375
+ const magicSquare = Array( noiseSquareSize ).fill( 0 );
376
+ let i = Math.floor( noiseSize / 2 );
377
+ let j = noiseSize - 1;
378
+
379
+ for ( let num = 1; num <= noiseSquareSize; ) {
380
+
381
+ if ( i === - 1 && j === noiseSize ) {
382
+
383
+ j = noiseSize - 2;
384
+ i = 0;
385
+
386
+ } else {
387
+
388
+ if ( j === noiseSize ) {
389
+
390
+ j = 0;
391
+
392
+ }
393
+
394
+ if ( i < 0 ) {
395
+
396
+ i = noiseSize - 1;
397
+
398
+ }
399
+
400
+ }
401
+
402
+ if ( magicSquare[ i * noiseSize + j ] !== 0 ) {
403
+
404
+ j -= 2;
405
+ i ++;
406
+ continue;
407
+
408
+ } else {
409
+
410
+ magicSquare[ i * noiseSize + j ] = num ++;
411
+
412
+ }
413
+
414
+ j ++;
415
+ i --;
416
+
417
+ }
418
+
419
+ return magicSquare;
420
+
421
+ }
422
+
423
+
424
+ export { generateMagicSquareNoise, GTAOShader, GTAODepthShader, GTAOBlendShader };
vendor/addons/shaders/PoissonDenoiseShader.js ADDED
@@ -0,0 +1,226 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import {
2
+ Matrix4,
3
+ Vector2,
4
+ Vector3,
5
+ } from '../../three.module.min.js';
6
+
7
+ /**
8
+ * References:
9
+ * https://openaccess.thecvf.com/content/WACV2021/papers/Khademi_Self-Supervised_Poisson-Gaussian_Denoising_WACV_2021_paper.pdf
10
+ * https://arxiv.org/pdf/2206.01856.pdf
11
+ */
12
+
13
+ const PoissonDenoiseShader = {
14
+
15
+ name: 'PoissonDenoiseShader',
16
+
17
+ defines: {
18
+ 'SAMPLES': 16,
19
+ 'SAMPLE_VECTORS': generatePdSamplePointInitializer( 16, 2, 1 ),
20
+ 'NORMAL_VECTOR_TYPE': 1,
21
+ 'DEPTH_VALUE_SOURCE': 0,
22
+ },
23
+
24
+ uniforms: {
25
+ 'tDiffuse': { value: null },
26
+ 'tNormal': { value: null },
27
+ 'tDepth': { value: null },
28
+ 'tNoise': { value: null },
29
+ 'resolution': { value: new Vector2() },
30
+ 'cameraProjectionMatrixInverse': { value: new Matrix4() },
31
+ 'lumaPhi': { value: 5. },
32
+ 'depthPhi': { value: 5. },
33
+ 'normalPhi': { value: 5. },
34
+ 'radius': { value: 4. },
35
+ 'index': { value: 0 }
36
+ },
37
+
38
+ vertexShader: /* glsl */`
39
+
40
+ varying vec2 vUv;
41
+
42
+ void main() {
43
+ vUv = uv;
44
+ gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
45
+ }`,
46
+
47
+ fragmentShader: /* glsl */`
48
+
49
+ varying vec2 vUv;
50
+
51
+ uniform sampler2D tDiffuse;
52
+ uniform sampler2D tNormal;
53
+ uniform sampler2D tDepth;
54
+ uniform sampler2D tNoise;
55
+ uniform vec2 resolution;
56
+ uniform mat4 cameraProjectionMatrixInverse;
57
+ uniform float lumaPhi;
58
+ uniform float depthPhi;
59
+ uniform float normalPhi;
60
+ uniform float radius;
61
+ uniform int index;
62
+
63
+ #include <common>
64
+ #include <packing>
65
+
66
+ #ifndef SAMPLE_LUMINANCE
67
+ #define SAMPLE_LUMINANCE dot(vec3(0.2125, 0.7154, 0.0721), a)
68
+ #endif
69
+
70
+ #ifndef FRAGMENT_OUTPUT
71
+ #define FRAGMENT_OUTPUT vec4(denoised, 1.)
72
+ #endif
73
+
74
+ float getLuminance(const in vec3 a) {
75
+ return SAMPLE_LUMINANCE;
76
+ }
77
+
78
+ const vec3 poissonDisk[SAMPLES] = SAMPLE_VECTORS;
79
+
80
+ vec3 getViewPosition(const in vec2 screenPosition, const in float depth) {
81
+ vec4 clipSpacePosition = vec4(vec3(screenPosition, depth) * 2.0 - 1.0, 1.0);
82
+ vec4 viewSpacePosition = cameraProjectionMatrixInverse * clipSpacePosition;
83
+ return viewSpacePosition.xyz / viewSpacePosition.w;
84
+ }
85
+
86
+ float getDepth(const vec2 uv) {
87
+ #if DEPTH_VALUE_SOURCE == 1
88
+ return textureLod(tDepth, uv.xy, 0.0).a;
89
+ #else
90
+ return textureLod(tDepth, uv.xy, 0.0).r;
91
+ #endif
92
+ }
93
+
94
+ float fetchDepth(const ivec2 uv) {
95
+ #if DEPTH_VALUE_SOURCE == 1
96
+ return texelFetch(tDepth, uv.xy, 0).a;
97
+ #else
98
+ return texelFetch(tDepth, uv.xy, 0).r;
99
+ #endif
100
+ }
101
+
102
+ vec3 computeNormalFromDepth(const vec2 uv) {
103
+ vec2 size = vec2(textureSize(tDepth, 0));
104
+ ivec2 p = ivec2(uv * size);
105
+ float c0 = fetchDepth(p);
106
+ float l2 = fetchDepth(p - ivec2(2, 0));
107
+ float l1 = fetchDepth(p - ivec2(1, 0));
108
+ float r1 = fetchDepth(p + ivec2(1, 0));
109
+ float r2 = fetchDepth(p + ivec2(2, 0));
110
+ float b2 = fetchDepth(p - ivec2(0, 2));
111
+ float b1 = fetchDepth(p - ivec2(0, 1));
112
+ float t1 = fetchDepth(p + ivec2(0, 1));
113
+ float t2 = fetchDepth(p + ivec2(0, 2));
114
+ float dl = abs((2.0 * l1 - l2) - c0);
115
+ float dr = abs((2.0 * r1 - r2) - c0);
116
+ float db = abs((2.0 * b1 - b2) - c0);
117
+ float dt = abs((2.0 * t1 - t2) - c0);
118
+ vec3 ce = getViewPosition(uv, c0).xyz;
119
+ vec3 dpdx = (dl < dr) ? ce - getViewPosition((uv - vec2(1.0 / size.x, 0.0)), l1).xyz
120
+ : -ce + getViewPosition((uv + vec2(1.0 / size.x, 0.0)), r1).xyz;
121
+ vec3 dpdy = (db < dt) ? ce - getViewPosition((uv - vec2(0.0, 1.0 / size.y)), b1).xyz
122
+ : -ce + getViewPosition((uv + vec2(0.0, 1.0 / size.y)), t1).xyz;
123
+ return normalize(cross(dpdx, dpdy));
124
+ }
125
+
126
+ vec3 getViewNormal(const vec2 uv) {
127
+ #if NORMAL_VECTOR_TYPE == 2
128
+ return normalize(textureLod(tNormal, uv, 0.).rgb);
129
+ #elif NORMAL_VECTOR_TYPE == 1
130
+ return unpackRGBToNormal(textureLod(tNormal, uv, 0.).rgb);
131
+ #else
132
+ return computeNormalFromDepth(uv);
133
+ #endif
134
+ }
135
+
136
+ void denoiseSample(in vec3 center, in vec3 viewNormal, in vec3 viewPos, in vec2 sampleUv, inout vec3 denoised, inout float totalWeight) {
137
+ vec4 sampleTexel = textureLod(tDiffuse, sampleUv, 0.0);
138
+ float sampleDepth = getDepth(sampleUv);
139
+ vec3 sampleNormal = getViewNormal(sampleUv);
140
+ vec3 neighborColor = sampleTexel.rgb;
141
+ vec3 viewPosSample = getViewPosition(sampleUv, sampleDepth);
142
+
143
+ float normalDiff = dot(viewNormal, sampleNormal);
144
+ float normalSimilarity = pow(max(normalDiff, 0.), normalPhi);
145
+ float lumaDiff = abs(getLuminance(neighborColor) - getLuminance(center));
146
+ float lumaSimilarity = max(1.0 - lumaDiff / lumaPhi, 0.0);
147
+ float depthDiff = abs(dot(viewPos - viewPosSample, viewNormal));
148
+ float depthSimilarity = max(1. - depthDiff / depthPhi, 0.);
149
+ float w = lumaSimilarity * depthSimilarity * normalSimilarity;
150
+
151
+ denoised += w * neighborColor;
152
+ totalWeight += w;
153
+ }
154
+
155
+ void main() {
156
+ float depth = getDepth(vUv.xy);
157
+ vec3 viewNormal = getViewNormal(vUv);
158
+ if (depth == 1. || dot(viewNormal, viewNormal) == 0.) {
159
+ discard;
160
+ return;
161
+ }
162
+ vec4 texel = textureLod(tDiffuse, vUv, 0.0);
163
+ vec3 center = texel.rgb;
164
+ vec3 viewPos = getViewPosition(vUv, depth);
165
+
166
+ vec2 noiseResolution = vec2(textureSize(tNoise, 0));
167
+ vec2 noiseUv = vUv * resolution / noiseResolution;
168
+ vec4 noiseTexel = textureLod(tNoise, noiseUv, 0.0);
169
+ vec2 noiseVec = vec2(sin(noiseTexel[index % 4] * 2. * PI), cos(noiseTexel[index % 4] * 2. * PI));
170
+ mat2 rotationMatrix = mat2(noiseVec.x, -noiseVec.y, noiseVec.x, noiseVec.y);
171
+
172
+ float totalWeight = 1.0;
173
+ vec3 denoised = texel.rgb;
174
+ for (int i = 0; i < SAMPLES; i++) {
175
+ vec3 sampleDir = poissonDisk[i];
176
+ vec2 offset = rotationMatrix * (sampleDir.xy * (1. + sampleDir.z * (radius - 1.)) / resolution);
177
+ vec2 sampleUv = vUv + offset;
178
+ denoiseSample(center, viewNormal, viewPos, sampleUv, denoised, totalWeight);
179
+ }
180
+
181
+ if (totalWeight > 0.) {
182
+ denoised /= totalWeight;
183
+ }
184
+ gl_FragColor = FRAGMENT_OUTPUT;
185
+ }`
186
+
187
+ };
188
+
189
+ function generatePdSamplePointInitializer( samples, rings, radiusExponent ) {
190
+
191
+ const poissonDisk = generateDenoiseSamples(
192
+ samples,
193
+ rings,
194
+ radiusExponent,
195
+ );
196
+
197
+ let glslCode = 'vec3[SAMPLES](';
198
+
199
+ for ( let i = 0; i < samples; i ++ ) {
200
+
201
+ const sample = poissonDisk[ i ];
202
+ glslCode += `vec3(${sample.x}, ${sample.y}, ${sample.z})${( i < samples - 1 ) ? ',' : ')'}`;
203
+
204
+ }
205
+
206
+ return glslCode;
207
+
208
+ }
209
+
210
+ function generateDenoiseSamples( numSamples, numRings, radiusExponent ) {
211
+
212
+ const samples = [];
213
+
214
+ for ( let i = 0; i < numSamples; i ++ ) {
215
+
216
+ const angle = 2 * Math.PI * numRings * i / numSamples;
217
+ const radius = Math.pow( i / ( numSamples - 1 ), radiusExponent );
218
+ samples.push( new Vector3( Math.cos( angle ), Math.sin( angle ), radius ) );
219
+
220
+ }
221
+
222
+ return samples;
223
+
224
+ }
225
+
226
+ export { generatePdSamplePointInitializer, PoissonDenoiseShader };
video.js CHANGED
@@ -1,7 +1,7 @@
1
  // STUDIUS P3.4: Video Gen (LTX-Video, text→video + image→video), Video Edit (trim, soundtrack, title, fades → MP4/WebM export)
2
  // and Stems (Demucs split → synced mixer with gain/mute/solo → WAV mixdown). All results go on the asset bus (save / send).
3
- import { run, result, MODULES, esc, hf, stTxt, url, badge, timer, setS, S, keep } from './real.js?v=93';
4
- import { toWav } from './master.js?v=93';
5
  import { onStop } from './widgets.js?v=50';
6
 
7
  export const LTX = 'Lightricks/ltx-video-distilled';
 
1
  // STUDIUS P3.4: Video Gen (LTX-Video, text→video + image→video), Video Edit (trim, soundtrack, title, fades → MP4/WebM export)
2
  // and Stems (Demucs split → synced mixer with gain/mute/solo → WAV mixdown). All results go on the asset bus (save / send).
3
+ import { run, result, MODULES, esc, hf, stTxt, url, badge, timer, setS, S, keep } from './real.js?v=96';
4
+ import { toWav } from './master.js?v=96';
5
  import { onStop } from './widgets.js?v=50';
6
 
7
  export const LTX = 'Lightricks/ltx-video-distilled';
workspace.js CHANGED
@@ -1,6 +1,6 @@
1
  // STUDIUS empire backbone (frontend): HF sign-in, Workspace (user's HF Bucket), asset bus hand-off, bee agent dock.
2
- import { MODULES, refreshQuota } from './real.js?v=93';
3
- import { Avatars } from './avatar.js?v=93';
4
  const $ = (s, r = document) => r.querySelector(s);
5
  const esc = (t) => String(t ?? '').replace(/[&<>"']/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
6
  const ST = () => window.__studius.STUDIOS;
@@ -142,7 +142,7 @@ const TEMPLATES = [
142
  { id: 'musik-team', name: 'Musik-Team', icon: '🎵', task: 'Mach einen kurzen Lofi-Beat mit warmem Piano, mastere ihn auf -14 LUFS und speichere ihn im Workspace',
143
  members: [['komponist', 'Komponist', 'Komponiert kurze Musikstücke nach Vorgabe', ['music']], ['stem-engineer', 'Stem-Engineer', 'Trennt Songs in Stems, wenn Vocals stören; sonst nichts tun', ['stems']], ['mastering', 'Mastering-Engineer', 'Mastert Audio auf -14 LUFS (Streaming)', ['master']], ['archivar', 'Archivar', 'Speichert fertige Ergebnisse im Workspace', ['workspace']]] },
144
  { id: 'social-team', name: 'Social-Media-Team', icon: '📱', task: 'Erstelle einen kurzen Social-Clip: goldene Biene über Honigwaben, mit Caption',
145
- members: [['texter', 'Social-Texter', 'Schreibt eine knackige Caption mit 3 Hashtags', ['chat']], ['art-director', 'Art-Director', 'Erzeugt das Key-Visual als Bild', ['image']], ['video-producer', 'Video-Producer', 'Erzeugt aus dem Prompt einen 2-3 s Clip', ['video']], ['archivar', 'Archivar', 'Speichert fertige Ergebnisse im Workspace', ['workspace']]] },
146
  { id: 'radio-team', name: 'Radio-Team', icon: '📻', task: 'Produziere eine 15-Sekunden-Radio-Ansage für die STUDIUS-Launch-Party mit Jingle',
147
  members: [['redakteur', 'Redakteur', 'Schreibt einen kurzen Moderationstext (max. 2 Sätze)', ['chat']], ['sprecher', 'Sprecher', 'Spricht den Moderationstext mit der Avatar-Stimme', ['avatar']], ['jingle', 'Jingle-Komponist', 'Komponiert einen kurzen Radio-Jingle', ['music']], ['mastering', 'Mastering-Engineer', 'Mastert Audio auf -16 LUFS (Podcast/Radio)', ['master']], ['archivar', 'Archivar', 'Speichert fertige Ergebnisse im Workspace', ['workspace']]] },
148
  { id: 'shop-team', name: 'Shop/Marketing-Team', icon: '🛍', task: 'Bewirb ein goldenes Bienen-T-Shirt: Produkttext, Produktfoto und kurzer Werbeclip',
 
1
  // STUDIUS empire backbone (frontend): HF sign-in, Workspace (user's HF Bucket), asset bus hand-off, bee agent dock.
2
+ import { MODULES, refreshQuota } from './real.js?v=96';
3
+ import { Avatars } from './avatar.js?v=96';
4
  const $ = (s, r = document) => r.querySelector(s);
5
  const esc = (t) => String(t ?? '').replace(/[&<>"']/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
6
  const ST = () => window.__studius.STUDIOS;
 
142
  { id: 'musik-team', name: 'Musik-Team', icon: '🎵', task: 'Mach einen kurzen Lofi-Beat mit warmem Piano, mastere ihn auf -14 LUFS und speichere ihn im Workspace',
143
  members: [['komponist', 'Komponist', 'Komponiert kurze Musikstücke nach Vorgabe', ['music']], ['stem-engineer', 'Stem-Engineer', 'Trennt Songs in Stems, wenn Vocals stören; sonst nichts tun', ['stems']], ['mastering', 'Mastering-Engineer', 'Mastert Audio auf -14 LUFS (Streaming)', ['master']], ['archivar', 'Archivar', 'Speichert fertige Ergebnisse im Workspace', ['workspace']]] },
144
  { id: 'social-team', name: 'Social-Media-Team', icon: '📱', task: 'Erstelle einen kurzen Social-Clip: goldene Biene über Honigwaben, mit Caption',
145
+ members: [['texter', 'Social-Texter', 'Schreibt Captions mit Hashtags pro Plattform (social.captions)', ['social', 'chat']], ['art-director', 'Art-Director', 'Erzeugt das Key-Visual als Bild', ['image']], ['video-producer', 'Video-Producer', 'Erzeugt aus dem Prompt einen 2-3 s Clip', ['video']], ['archivar', 'Archivar', 'Speichert fertige Ergebnisse im Workspace', ['workspace']]] },
146
  { id: 'radio-team', name: 'Radio-Team', icon: '📻', task: 'Produziere eine 15-Sekunden-Radio-Ansage für die STUDIUS-Launch-Party mit Jingle',
147
  members: [['redakteur', 'Redakteur', 'Schreibt einen kurzen Moderationstext (max. 2 Sätze)', ['chat']], ['sprecher', 'Sprecher', 'Spricht den Moderationstext mit der Avatar-Stimme', ['avatar']], ['jingle', 'Jingle-Komponist', 'Komponiert einen kurzen Radio-Jingle', ['music']], ['mastering', 'Mastering-Engineer', 'Mastert Audio auf -16 LUFS (Podcast/Radio)', ['master']], ['archivar', 'Archivar', 'Speichert fertige Ergebnisse im Workspace', ['workspace']]] },
148
  { id: 'shop-team', name: 'Shop/Marketing-Team', icon: '🛍', task: 'Bewirb ein goldenes Bienen-T-Shirt: Produkttext, Produktfoto und kurzer Werbeclip',