SupPepper commited on
Commit
ddd189b
·
1 Parent(s): 1173d68

Feat : Music and Relations

Browse files

commit 30b115e35191d24a85c0cd89d30c2469306d959d
Author: SupPepper <99681586+LorenzoLepoivre@users.noreply.github.com>
Date: Tue Jun 9 17:43:14 2026 +0200

Update index.html

commit 8640b91fd31b1dc92eebc1db4586cc47803e1dc8
Author: SupPepper <99681586+LorenzoLepoivre@users.noreply.github.com>
Date: Tue Jun 9 17:30:59 2026 +0200

save

commit d09ba91ec6cdcf88e58fa9e423998fa32fc9e40e
Author: SupPepper <99681586+LorenzoLepoivre@users.noreply.github.com>
Date: Tue Jun 9 16:44:47 2026 +0200

Update index.html

commit b4fea552a0b39eed5fa74883cc5676f7052edac9
Author: SupPepper <99681586+LorenzoLepoivre@users.noreply.github.com>
Date: Tue Jun 9 16:41:42 2026 +0200

feat: BGM system, NPC bonds, save/load, progress bar, UI polish

- Background music: 6 mood tracks, set_music directive, crossfade transitions
- NPC-NPC relationship system: directed bonds, bond graph in Relations tab
- Save/load: file-based JSON save with journal history + audio settings
- Two-phase start: /start_text (LLM) then /start_images (painter) with real progress bar
- Relations tab: directed bond list (A->B and B->A shown separately)
- Settings panel: BGM + TTS volume sliders, save button
- Bond graph: semantic color (jealousy=red, camaraderie=green), no player node
- Fix: UnicodeEncodeError in ModalLLM print (cp1252 safe)

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>

.gitignore CHANGED
@@ -32,3 +32,4 @@ memory/
32
  .python-version
33
 
34
  uv.lock
 
 
32
  .python-version
33
 
34
  uv.lock
35
+ frontend/music/*.mp3
app.py CHANGED
@@ -163,6 +163,10 @@ def build_server():
163
  app = Server()
164
  # serve generated images (backdrops/sprites) as static files at /images/<name>
165
  app.mount("/images", StaticFiles(directory=str(config.CACHE_DIR)), name="images")
 
 
 
 
166
 
167
  @app.get("/", response_class=HTMLResponse)
168
  async def home() -> str:
@@ -177,6 +181,18 @@ def build_server():
177
  def start(theme: str = "school", tone: str = "romantic", seed: int | None = None) -> dict:
178
  return ENGINE.start(SetupForm(theme=theme, tone=tone, seed=seed)).model_dump()
179
 
 
 
 
 
 
 
 
 
 
 
 
 
180
  @app.api(name="turn")
181
  @gpu
182
  def turn(player_input: str, action: str = "talk", target: str = "") -> dict:
 
163
  app = Server()
164
  # serve generated images (backdrops/sprites) as static files at /images/<name>
165
  app.mount("/images", StaticFiles(directory=str(config.CACHE_DIR)), name="images")
166
+ # serve background music tracks at /music/<name>.mp3|ogg
167
+ _music_dir = Path(__file__).parent / "frontend" / "music"
168
+ _music_dir.mkdir(exist_ok=True)
169
+ app.mount("/music", StaticFiles(directory=str(_music_dir)), name="music")
170
 
171
  @app.get("/", response_class=HTMLResponse)
172
  async def home() -> str:
 
181
  def start(theme: str = "school", tone: str = "romantic", seed: int | None = None) -> dict:
182
  return ENGINE.start(SetupForm(theme=theme, tone=tone, seed=seed)).model_dump()
183
 
184
+ @app.api(name="start_text")
185
+ @gpu
186
+ def start_text(theme: str = "school", tone: str = "romantic", seed: int | None = None) -> dict:
187
+ """Phase 1 — LLM init only. Returns text-only ViewState (no images)."""
188
+ return ENGINE.start_text(SetupForm(theme=theme, tone=tone, seed=seed)).model_dump()
189
+
190
+ @app.api(name="start_images")
191
+ @gpu
192
+ def start_images() -> dict:
193
+ """Phase 2 — paint backdrop + sprite. Call after start_text."""
194
+ return ENGINE.start_images().model_dump()
195
+
196
  @app.api(name="turn")
197
  @gpu
198
  def turn(player_input: str, action: str = "talk", target: str = "") -> dict:
frontend/index.html CHANGED
@@ -143,9 +143,144 @@
143
  @keyframes pulse-rec{0%,100%{opacity:1}50%{opacity:.6}}
144
  #mic.live{background:var(--rose); animation:pulse-rec 1.2s ease-in-out infinite}
145
  #mic.waiting{background:rgba(255,255,255,.12); color:var(--ink-dim); cursor:wait}
146
- #tts-toggle{min-width:42px; background:transparent; color:var(--ink-dim);
147
- border:1px solid rgba(255,255,255,.22); font-size:1.1rem}
148
- #tts-toggle.active{color:var(--gold); border-color:rgba(232,193,114,.5)}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
149
  /* ---- book intro overlay ---- */
150
  #intro-book{
151
  position:fixed; inset:0; z-index:30; display:flex; align-items:center; justify-content:center;
@@ -205,6 +340,16 @@
205
  border:1px solid rgba(255,255,255,.18); border-radius:10px; padding:10px 12px; font-family:var(--body)}
206
  select option{background:var(--dusk-2); color:var(--ink)}
207
  #enter{width:100%; margin-top:16px; padding:14px; font-size:1.05rem}
 
 
 
 
 
 
 
 
 
 
208
  .shimmer{color:var(--ink-dim); font-style:italic}
209
  .hidden{display:none !important}
210
  /* ---- journal button (top-right) ---- */
@@ -333,6 +478,23 @@
333
  .rel-score.neg{color:var(--rose)}
334
  .rel-score.zero{color:var(--ink-dim)}
335
  .rel-offstage{font-size:.7rem; color:rgba(200,190,175,.75); font-style:italic}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
336
  </style>
337
  </head>
338
  <body>
@@ -357,11 +519,35 @@
357
  <input id="say" placeholder="say something…" autocomplete="off" />
358
  <button id="send">✓</button>
359
  <button id="mic" class="ghost" title="hold to speak">🎙️</button>
360
- <button id="tts-toggle" title="toggle voice output">🔇</button>
361
  </div>
362
  </div>
363
  </div>
364
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
365
  <!-- Journal button — hidden until game starts -->
366
  <button id="journal-btn" class="hidden" title="Story journal">
367
  <span class="jb-icon">📖</span>
@@ -373,12 +559,7 @@
373
  <div id="journal-overlay">
374
  <div id="journal-header">
375
  <h3>📖 Journal</h3>
376
- <div style="display:flex;gap:8px;align-items:center">
377
- <button id="download-save-btn" title="Download save file" style="background:none;border:1px solid rgba(232,193,114,.3);
378
- border-radius:6px;color:var(--gold);padding:4px 10px;font-size:.82rem;cursor:pointer;
379
- transition:background .15s" class="hidden">💾</button>
380
- <button id="journal-close" title="Close">✕</button>
381
- </div>
382
  </div>
383
  <div id="journal-tabs">
384
  <button class="jtab active" data-tab="story">Story</button>
@@ -404,6 +585,16 @@
404
  </div>
405
  </div>
406
 
 
 
 
 
 
 
 
 
 
 
407
  <!-- Choice screen: new game or load file -->
408
  <div id="choice-screen" style="position:fixed;inset:0;z-index:10;display:grid;place-items:center;
409
  background:radial-gradient(80% 80% at 50% 30%, var(--dusk-2), var(--dusk-0))">
@@ -430,6 +621,24 @@
430
  <div class="field"><label>Theme</label><select id="theme"></select></div>
431
  <div class="field"><label>Tone</label><select id="tone"></select></div>
432
  <button id="enter">Enter the story</button>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
433
  </div>
434
  </div>
435
 
@@ -455,8 +664,9 @@ let client;
455
  // --- journal ---
456
  let history = [];
457
  let journalTurn = 0;
458
- let knownChars = []; // updated each render with known_characters from ViewState
459
- const spriteCache = {}; // id last known sprite_url (persists when char goes off-stage)
 
460
 
461
  const ACTION_ICONS = { talk:"💬", flirt:"🌸", touch:"🤝", ask:"🤔", silent:"😶", give:"🎁", move:"🚪" };
462
 
@@ -502,9 +712,10 @@ function renderRelations() {
502
  panel.innerHTML = '<div class="je-empty">No characters met yet…</div>';
503
  return;
504
  }
505
- // Sort: on-stage first, then by relationship desc
 
506
  const sorted = [...knownChars].sort((a, b) => b.relationship - a.relationship);
507
- panel.innerHTML = sorted.map(ch => {
508
  const rel = ch.relationship ?? 0;
509
  const posW = rel > 0 ? rel.toFixed(1) : "0";
510
  const negW = rel < 0 ? Math.abs(rel).toFixed(1) : "0";
@@ -515,11 +726,10 @@ function renderRelations() {
515
  ? `<img src="${spriteUrl}" alt="${ch.name}" />`
516
  : `<span>👤</span>`;
517
  const isPresent = (window._presentIds || []).includes(ch.id);
518
- const statusText = isPresent ? "on stage" : "away";
519
  return `<div class="rel-entry">
520
  <div class="rel-avatar">${avatarHtml}</div>
521
  <div class="rel-info">
522
- <div class="rel-name">${ch.name} <span class="rel-offstage">${statusText}</span></div>
523
  <div class="rel-mini-bar">
524
  <div class="rel-mini-neg" style="width:${negW}%"></div>
525
  <div class="rel-mini-pos" style="width:${posW}%"></div>
@@ -528,6 +738,173 @@ function renderRelations() {
528
  <span class="rel-score ${scoreClass}">${label}</span>
529
  </div>`;
530
  }).join("");
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
531
  }
532
 
533
  // keep track of who's currently on stage for the relations panel
@@ -596,15 +973,16 @@ let lastBg = null;
596
  function render(v){
597
  if (v.known_characters?.length) {
598
  knownChars = v.known_characters;
599
- // cache sprite URLs so they survive when chars go off-stage
600
  for (const ch of knownChars) {
601
  if (ch.sprite_url) spriteCache[ch.id] = ch.sprite_url;
602
  }
603
  }
 
604
  $("place").textContent = v.place || "";
605
  $("speaker").textContent = v.speaker || "";
606
  typeOut($("line"), v.dialogue || "");
607
  playTTS(v.audio_b64);
 
608
  if (v.backdrop_url && v.backdrop_url !== lastBg){
609
  const bg = $("backdrop");
610
  bg.classList.remove("on");
@@ -671,6 +1049,44 @@ function render(v){
671
 
672
  // target chips — show only when multiple characters are on stage
673
  updateTargetRow(v.present);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
674
  }
675
 
676
  function showNotif(msg){
@@ -763,17 +1179,11 @@ function busy(state){
763
  document.querySelectorAll(".target-chip").forEach(b => b.disabled = state);
764
  }
765
 
766
- // --- TTS toggle ---
 
767
  let ttsEnabled = true;
768
- const ttsBtn = $("tts-toggle");
769
- ttsBtn.textContent = "🔊";
770
- ttsBtn.classList.add("active");
771
- ttsBtn.addEventListener("click", () => {
772
- ttsEnabled = !ttsEnabled;
773
- ttsBtn.textContent = ttsEnabled ? "🔊" : "🔇";
774
- ttsBtn.classList.toggle("active", ttsEnabled);
775
- if (!ttsEnabled) { const a = $("vn-audio"); if (a) { a.pause(); a.src = ""; } }
776
- });
777
 
778
  function playTTS(audio_b64) {
779
  if (!ttsEnabled || !audio_b64) return;
@@ -783,8 +1193,90 @@ function playTTS(audio_b64) {
783
  audio.id = "vn-audio";
784
  document.body.appendChild(audio);
785
  }
 
786
  audio.src = audio_b64;
787
- audio.play().catch(() => {}); // swallow autoplay policy errors silently
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
788
  }
789
 
790
  // --- book overlay dismiss ---
@@ -793,6 +1285,24 @@ $("book-close").addEventListener("click", () => {
793
  $("say").focus();
794
  });
795
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
796
  // --- choice screen ---
797
  $("btn-new").addEventListener("click", () => {
798
  $("choice-screen").classList.add("hidden");
@@ -803,12 +1313,17 @@ $("load-file-input").addEventListener("change", async (e) => {
803
  const file = e.target.files[0];
804
  if (!file) return;
805
  const text = await file.text();
 
 
 
 
806
  busy(true);
807
  try {
808
  // Extract client-side journal history before sending state to server
809
  let parsed;
810
  try { parsed = JSON.parse(text); } catch { parsed = {}; }
811
  const savedHistory = Array.isArray(parsed.journal_history) ? parsed.journal_history : [];
 
812
 
813
  const { data } = await client.predict("/load_file", { data: text });
814
  $("choice-screen").classList.add("hidden");
@@ -818,49 +1333,218 @@ $("load-file-input").addEventListener("change", async (e) => {
818
  history = savedHistory;
819
  journalTurn = savedHistory.length > 0 ? savedHistory[savedHistory.length - 1].turn : 0;
820
 
821
- render(data[0]);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
822
  $("journal-btn").classList.remove("hidden");
823
- $("download-save-btn").classList.remove("hidden");
824
  } catch(err) { alert("Could not load save: " + (err?.message || err)); }
825
  busy(false);
826
  });
827
 
828
- // --- download save ---
829
- $("download-save-btn").addEventListener("click", async () => {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
830
  try {
831
  const { data } = await client.predict("/save_data", {});
832
- // Embed the client-side journal history into the save file
833
  const saveObj = JSON.parse(data[0].json);
834
  saveObj.journal_history = history;
 
 
 
 
 
835
  const blob = new Blob([JSON.stringify(saveObj)], { type: "application/json" });
836
  const a = document.createElement("a");
837
  a.href = URL.createObjectURL(blob);
838
  a.download = "ephemeral-hearts-save.json";
839
  a.click();
840
  URL.revokeObjectURL(a.href);
841
- } catch(err) { console.error("download failed", err); }
 
 
 
 
 
 
842
  });
843
 
 
 
 
844
  // --- start ---
845
  $("enter").addEventListener("click", async () => {
846
  const btn = $("enter");
847
  btn.disabled = true;
848
  const orig = btn.textContent;
849
  btn.textContent = "✨ Creating your story…";
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
850
  try {
851
- const { data } = await client.predict("/start", { theme: $("theme").value, tone: $("tone").value });
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
852
  $("setup").classList.add("hidden");
853
- render(data[0]);
854
- addToHistory("", data[0]);
855
  $("journal-btn").classList.remove("hidden");
856
- $("download-save-btn").classList.remove("hidden");
857
- // Show the book intro overlay if the engine sent an intro text
858
- if (data[0]?.intro_text) {
859
- $("book-text").textContent = data[0].intro_text;
860
- $("intro-book").classList.remove("hidden");
861
- }
 
 
 
 
862
  } catch(err) {
863
  console.error("start failed", err);
 
 
 
864
  btn.textContent = "⚠️ Failed — try again";
865
  btn.disabled = false;
866
  setTimeout(() => { btn.textContent = orig; }, 3000);
 
143
  @keyframes pulse-rec{0%,100%{opacity:1}50%{opacity:.6}}
144
  #mic.live{background:var(--rose); animation:pulse-rec 1.2s ease-in-out infinite}
145
  #mic.waiting{background:rgba(255,255,255,.12); color:var(--ink-dim); cursor:wait}
146
+ /* ---- settings button ---- */
147
+ #settings-btn{
148
+ position:fixed; top:56px; left:16px; z-index:8;
149
+ display:flex; align-items:center; gap:7px;
150
+ background:rgba(10,13,24,.82); border:1px solid rgba(232,193,114,.30);
151
+ border-radius:10px; padding:9px 14px;
152
+ color:var(--ink-dim); font-family:var(--display); font-size:1rem;
153
+ backdrop-filter:blur(6px); cursor:pointer;
154
+ transition:background .15s, border-color .15s, color .15s, transform .15s;
155
+ }
156
+ #settings-btn:hover{
157
+ background:rgba(232,193,114,.10); border-color:rgba(232,193,114,.5);
158
+ color:var(--gold); transform:translateY(-1px);
159
+ }
160
+ /* ---- settings overlay ---- */
161
+ #settings-overlay{
162
+ display:none; position:fixed; inset:0; z-index:35;
163
+ background:rgba(0,0,0,.55); backdrop-filter:blur(4px);
164
+ align-items:center; justify-content:center;
165
+ }
166
+ #settings-overlay.open{display:flex}
167
+ #settings-panel{
168
+ width:min(380px,90vw); background:var(--dusk-1);
169
+ border:1px solid rgba(232,193,114,.25); border-radius:16px;
170
+ padding:28px 28px 24px; box-shadow:0 8px 40px rgba(0,0,0,.5);
171
+ }
172
+ #settings-header{
173
+ display:flex; align-items:center; justify-content:space-between; margin-bottom:24px;
174
+ }
175
+ #settings-header h3{
176
+ font-family:var(--display); font-size:1.2rem; color:var(--gold); font-weight:600;
177
+ }
178
+ #settings-close{
179
+ background:none; border:none; color:var(--ink-dim); font-size:1.1rem;
180
+ padding:4px 8px; cursor:pointer; border-radius:6px;
181
+ }
182
+ #settings-close:hover{color:var(--ink)}
183
+ .settings-row{
184
+ display:flex; align-items:center; gap:12px; margin-bottom:20px;
185
+ }
186
+ .settings-row label{
187
+ font-family:var(--display); font-size:.9rem; color:var(--ink); min-width:120px; flex-shrink:0;
188
+ }
189
+ .settings-row input[type=range]{
190
+ flex:1; -webkit-appearance:none; appearance:none;
191
+ height:4px; border-radius:2px; background:rgba(255,255,255,.15); outline:none; cursor:pointer;
192
+ }
193
+ .settings-row input[type=range]::-webkit-slider-thumb{
194
+ -webkit-appearance:none; appearance:none;
195
+ width:16px; height:16px; border-radius:50%;
196
+ background:var(--gold); cursor:pointer; box-shadow:0 0 4px rgba(232,193,114,.4);
197
+ }
198
+ .settings-row input[type=range]::-moz-range-thumb{
199
+ width:16px; height:16px; border-radius:50%; border:none;
200
+ background:var(--gold); cursor:pointer;
201
+ }
202
+ .settings-vol-val{
203
+ font-family:var(--body); font-size:.82rem; color:var(--ink-dim);
204
+ min-width:36px; text-align:right;
205
+ }
206
+ .settings-divider{
207
+ border:none; border-top:1px solid rgba(232,193,114,.1); margin:20px 0;
208
+ }
209
+ #settings-save-btn{
210
+ width:100%; padding:13px; font-size:1rem; font-family:var(--display);
211
+ background:rgba(232,193,114,.12); border:1px solid rgba(232,193,114,.4);
212
+ border-radius:10px; color:var(--gold); cursor:pointer; letter-spacing:.3px;
213
+ transition:background .15s;
214
+ }
215
+ #settings-save-btn:hover{background:rgba(232,193,114,.22)}
216
+ #settings-save-btn:disabled{opacity:.5; cursor:wait}
217
+ /* ---- ending overlays (victory / defeat) ---- */
218
+ #ending-overlay{
219
+ position:fixed; inset:0; z-index:50; display:none; flex-direction:column;
220
+ align-items:center; justify-content:center; padding:40px 24px;
221
+ text-align:center; overflow:hidden;
222
+ }
223
+ #ending-overlay.show{ display:flex }
224
+ #ending-overlay.victory{
225
+ background:radial-gradient(ellipse at 50% 0%, #2e1030 0%, #150920 50%, #08050f 100%);
226
+ }
227
+ #ending-overlay.defeat{
228
+ background:radial-gradient(ellipse at 50% 0%, #1a0808 0%, #0d0505 50%, #050305 100%);
229
+ }
230
+ /* Dark veil over the image so text stays readable */
231
+ #ending-overlay::before{
232
+ content:""; position:absolute; inset:0; pointer-events:none;
233
+ background:var(--ending-dim, rgba(10,6,18,.72));
234
+ z-index:0;
235
+ }
236
+ /* Particle shimmer layer */
237
+ #ending-overlay::after{
238
+ content:""; position:absolute; inset:0; pointer-events:none; z-index:0;
239
+ background-image:
240
+ radial-gradient(circle, rgba(255,255,255,.12) 1px, transparent 1px),
241
+ radial-gradient(circle, rgba(255,255,255,.06) 1px, transparent 1px);
242
+ background-size:120px 120px, 80px 80px;
243
+ background-position:0 0, 40px 40px;
244
+ animation:endingDrift 20s linear infinite;
245
+ opacity:.5;
246
+ }
247
+ #ending-overlay.defeat::after{ opacity:.18 }
248
+ /* All direct children must sit above the pseudo-elements */
249
+ #ending-overlay > *{ position:relative; z-index:1 }
250
+ @keyframes endingDrift{
251
+ from{ background-position:0 0, 40px 40px }
252
+ to { background-position:120px 120px, 160px 160px }
253
+ }
254
+ .ending-icon{ font-size:3.6rem; margin-bottom:16px; animation:endingPulse 2s ease-in-out infinite }
255
+ @keyframes endingPulse{ 0%,100%{transform:scale(1)} 50%{transform:scale(1.12)} }
256
+ .ending-title{
257
+ font-family:var(--display); font-size:2rem; letter-spacing:.15em;
258
+ margin-bottom:10px; position:relative;
259
+ }
260
+ .victory .ending-title{ color:#e8c172 }
261
+ .defeat .ending-title{ color:#c87e7e }
262
+ .ending-subtitle{
263
+ font-size:.78rem; letter-spacing:.3em; color:var(--ink-dim); margin-bottom:28px;
264
+ text-transform:uppercase;
265
+ }
266
+ .ending-divider{
267
+ font-size:.65rem; letter-spacing:.5em; margin-bottom:20px;
268
+ }
269
+ .victory .ending-divider{ color:#a07c3a }
270
+ .defeat .ending-divider{ color:#7c3a3a }
271
+ #ending-text{
272
+ font-family:var(--body); font-size:1.02rem; line-height:1.75;
273
+ max-width:520px; color:var(--ink); font-style:italic;
274
+ margin-bottom:36px; position:relative;
275
+ }
276
+ #ending-replay{
277
+ padding:12px 32px; border-radius:8px; cursor:pointer;
278
+ font-family:var(--display); font-size:.95rem; letter-spacing:.2px;
279
+ border:none; position:relative; transition:opacity .2s;
280
+ }
281
+ #ending-replay:hover{ opacity:.85 }
282
+ .victory #ending-replay{ background:rgba(232,193,114,.2); border:1px solid rgba(232,193,114,.5); color:var(--gold) }
283
+ .defeat #ending-replay{ background:rgba(200,126,126,.15); border:1px solid rgba(200,126,126,.4); color:#c87e7e }
284
  /* ---- book intro overlay ---- */
285
  #intro-book{
286
  position:fixed; inset:0; z-index:30; display:flex; align-items:center; justify-content:center;
 
340
  border:1px solid rgba(255,255,255,.18); border-radius:10px; padding:10px 12px; font-family:var(--body)}
341
  select option{background:var(--dusk-2); color:var(--ink)}
342
  #enter{width:100%; margin-top:16px; padding:14px; font-size:1.05rem}
343
+ #start-progress{margin-top:18px; display:none; text-align:left}
344
+ .sp-step{margin-bottom:12px}
345
+ .sp-step-header{display:flex; justify-content:space-between; align-items:baseline; margin-bottom:5px}
346
+ .sp-step-label{font-size:.78rem; font-family:var(--display); color:var(--gold); letter-spacing:.04em}
347
+ .sp-step-pct{font-size:.75rem; color:var(--ink-dim)}
348
+ .sp-track{height:5px; border-radius:3px; background:rgba(255,255,255,.08); overflow:hidden}
349
+ .sp-fill{height:100%; border-radius:3px; width:0%; transition:width .55s ease}
350
+ .sp-fill.phase-llm{background:linear-gradient(90deg,#b08a4a,var(--gold))}
351
+ .sp-fill.phase-img{background:linear-gradient(90deg,#6a9cc8,#a8d4f0)}
352
+ .sp-note{font-size:.78rem; color:var(--ink-dim); font-style:italic; margin-top:4px; min-height:1.1em; transition:opacity .35s}
353
  .shimmer{color:var(--ink-dim); font-style:italic}
354
  .hidden{display:none !important}
355
  /* ---- journal button (top-right) ---- */
 
478
  .rel-score.neg{color:var(--rose)}
479
  .rel-score.zero{color:var(--ink-dim)}
480
  .rel-offstage{font-size:.7rem; color:rgba(200,190,175,.75); font-style:italic}
481
+ .rel-section-title{
482
+ font-family:var(--display); font-size:.72rem; color:var(--gold); opacity:.65;
483
+ letter-spacing:1.2px; text-transform:uppercase;
484
+ padding:14px 0 6px; border-bottom:1px solid rgba(232,193,114,.12); margin-bottom:8px;
485
+ }
486
+ .bond-graph-wrap{
487
+ padding:8px 0 8px; display:flex; justify-content:center;
488
+ }
489
+ .bond-graph-wrap svg{ width:100%; max-height:280px; display:block; overflow:visible }
490
+ .bond-list{ padding:0 4px 12px }
491
+ .bond-pair{ margin-bottom:7px; padding:6px 9px; background:rgba(255,255,255,.04); border-radius:7px }
492
+ .bond-row{ display:flex; align-items:center; gap:5px; padding:4px 0; font-size:.78rem }
493
+ .bond-row + .bond-row{ border-top:1px solid rgba(255,255,255,.06); margin-top:2px }
494
+ .bond-name{ font-family:var(--display); min-width:56px; color:var(--ink); white-space:nowrap; overflow:hidden; text-overflow:ellipsis }
495
+ .bond-arrow{ color:var(--ink-dim); flex-shrink:0; font-size:.7rem }
496
+ .bond-note{ font-style:italic; flex:1; font-size:.73rem }
497
+ .bond-val{ font-family:var(--display); font-weight:600; min-width:30px; text-align:right; font-size:.78rem }
498
  </style>
499
  </head>
500
  <body>
 
519
  <input id="say" placeholder="say something…" autocomplete="off" />
520
  <button id="send">✓</button>
521
  <button id="mic" class="ghost" title="hold to speak">🎙️</button>
 
522
  </div>
523
  </div>
524
  </div>
525
 
526
+ <!-- Settings button — hidden until game starts -->
527
+ <button id="settings-btn" class="hidden" title="Settings">⚙️</button>
528
+
529
+ <!-- Settings overlay -->
530
+ <div id="settings-overlay">
531
+ <div id="settings-panel">
532
+ <div id="settings-header">
533
+ <h3>⚙️ Settings</h3>
534
+ <button id="settings-close">✕</button>
535
+ </div>
536
+ <div class="settings-row">
537
+ <label>🎵 Music</label>
538
+ <input type="range" id="bgm-vol-slider" min="0" max="100" value="35" />
539
+ <span class="settings-vol-val" id="bgm-vol-val">35%</span>
540
+ </div>
541
+ <div class="settings-row">
542
+ <label>🔊 Voice</label>
543
+ <input type="range" id="tts-vol-slider" min="0" max="100" value="100" />
544
+ <span class="settings-vol-val" id="tts-vol-val">100%</span>
545
+ </div>
546
+ <hr class="settings-divider" />
547
+ <button id="settings-save-btn">💾 Save current game</button>
548
+ </div>
549
+ </div>
550
+
551
  <!-- Journal button — hidden until game starts -->
552
  <button id="journal-btn" class="hidden" title="Story journal">
553
  <span class="jb-icon">📖</span>
 
559
  <div id="journal-overlay">
560
  <div id="journal-header">
561
  <h3>📖 Journal</h3>
562
+ <button id="journal-close" title="Close">✕</button>
 
 
 
 
 
563
  </div>
564
  <div id="journal-tabs">
565
  <button class="jtab active" data-tab="story">Story</button>
 
585
  </div>
586
  </div>
587
 
588
+ <!-- Ending overlay (victory / defeat) -->
589
+ <div id="ending-overlay">
590
+ <div class="ending-icon" id="ending-icon">✦</div>
591
+ <div class="ending-title" id="ending-title">The End</div>
592
+ <div class="ending-subtitle" id="ending-subtitle"></div>
593
+ <div class="ending-divider">· · · · ·</div>
594
+ <p id="ending-text"></p>
595
+ <button id="ending-replay">Play again</button>
596
+ </div>
597
+
598
  <!-- Choice screen: new game or load file -->
599
  <div id="choice-screen" style="position:fixed;inset:0;z-index:10;display:grid;place-items:center;
600
  background:radial-gradient(80% 80% at 50% 30%, var(--dusk-2), var(--dusk-0))">
 
621
  <div class="field"><label>Theme</label><select id="theme"></select></div>
622
  <div class="field"><label>Tone</label><select id="tone"></select></div>
623
  <button id="enter">Enter the story</button>
624
+ <div id="start-progress">
625
+ <div class="sp-step" id="sp-step-llm">
626
+ <div class="sp-step-header">
627
+ <span class="sp-step-label">✦ Writing the story</span>
628
+ <span class="sp-step-pct" id="sp-pct-llm">0%</span>
629
+ </div>
630
+ <div class="sp-track"><div class="sp-fill phase-llm" id="sp-fill-llm"></div></div>
631
+ <div class="sp-note" id="sp-note-llm">Waiting for the AI…</div>
632
+ </div>
633
+ <div class="sp-step" id="sp-step-img" style="opacity:.35">
634
+ <div class="sp-step-header">
635
+ <span class="sp-step-label">🎨 Painting the scene</span>
636
+ <span class="sp-step-pct" id="sp-pct-img">—</span>
637
+ </div>
638
+ <div class="sp-track"><div class="sp-fill phase-img" id="sp-fill-img"></div></div>
639
+ <div class="sp-note" id="sp-note-img">Starts once the story is written</div>
640
+ </div>
641
+ </div>
642
  </div>
643
  </div>
644
 
 
664
  // --- journal ---
665
  let history = [];
666
  let journalTurn = 0;
667
+ let knownChars = []; // updated each render with known_characters from ViewState
668
+ let npcBonds = []; // updated each render with npc_bonds from ViewState
669
+ const spriteCache = {}; // id -> last known sprite_url (persists when char goes off-stage)
670
 
671
  const ACTION_ICONS = { talk:"💬", flirt:"🌸", touch:"🤝", ask:"🤔", silent:"😶", give:"🎁", move:"🚪" };
672
 
 
712
  panel.innerHTML = '<div class="je-empty">No characters met yet…</div>';
713
  return;
714
  }
715
+
716
+ // --- section 1: player↔NPC bars ---
717
  const sorted = [...knownChars].sort((a, b) => b.relationship - a.relationship);
718
+ const barsHtml = sorted.map(ch => {
719
  const rel = ch.relationship ?? 0;
720
  const posW = rel > 0 ? rel.toFixed(1) : "0";
721
  const negW = rel < 0 ? Math.abs(rel).toFixed(1) : "0";
 
726
  ? `<img src="${spriteUrl}" alt="${ch.name}" />`
727
  : `<span>👤</span>`;
728
  const isPresent = (window._presentIds || []).includes(ch.id);
 
729
  return `<div class="rel-entry">
730
  <div class="rel-avatar">${avatarHtml}</div>
731
  <div class="rel-info">
732
+ <div class="rel-name">${ch.name} <span class="rel-offstage">${isPresent ? "on stage" : "away"}</span></div>
733
  <div class="rel-mini-bar">
734
  <div class="rel-mini-neg" style="width:${negW}%"></div>
735
  <div class="rel-mini-pos" style="width:${posW}%"></div>
 
738
  <span class="rel-score ${scoreClass}">${label}</span>
739
  </div>`;
740
  }).join("");
741
+
742
+ // --- section 2: NPC↔NPC bond graph + directed list ---
743
+ let graphHtml = "";
744
+ if (knownChars.length >= 2) {
745
+ // Group bonds by unordered pair; always show BOTH directions (fill missing with neutral 0)
746
+ const bondIndex = {}; // "srcId|tgtId" -> bond object
747
+ for (const b of npcBonds) bondIndex[`${b.source_id}|${b.target_id}`] = b;
748
+
749
+ // Collect all unique unordered pairs from all known characters
750
+ const seenPairs = new Set();
751
+ const pairList = [];
752
+ for (let i = 0; i < knownChars.length; i++) {
753
+ for (let j = i + 1; j < knownChars.length; j++) {
754
+ const a = knownChars[i], b = knownChars[j];
755
+ const key = [a.id, b.id].sort().join("|");
756
+ if (seenPairs.has(key)) continue;
757
+ seenPairs.add(key);
758
+ // Only show pairs where at least one direction has a recorded bond
759
+ const ab = bondIndex[`${a.id}|${b.id}`];
760
+ const ba = bondIndex[`${b.id}|${a.id}`];
761
+ if (!ab && !ba) continue;
762
+ pairList.push({ a, b, ab, ba });
763
+ }
764
+ }
765
+
766
+ const _bondRow = (srcName, tgtName, bond) => {
767
+ const val = bond ? bond.value : 0;
768
+ const note = bond ? bond.note : "";
769
+ const col = _bondColor(note, val);
770
+ const sign = val > 0 ? "+" : "";
771
+ const noteStr = note || (val === 0 ? "neutral" : "");
772
+ return `<div class="bond-row">
773
+ <span class="bond-name">${srcName}</span>
774
+ <span class="bond-arrow">→</span>
775
+ <span class="bond-name">${tgtName}</span>
776
+ <span class="bond-note" style="color:${col}">${noteStr}</span>
777
+ <span class="bond-val" style="color:${col}">${sign}${val}</span>
778
+ </div>`;
779
+ };
780
+
781
+ const bondListHtml = pairList.map(({ a, b, ab, ba }) =>
782
+ `<div class="bond-pair">
783
+ ${_bondRow(a.name, b.name, ab)}
784
+ ${_bondRow(b.name, a.name, ba)}
785
+ </div>`
786
+ ).join("") || `<div class="je-empty" style="font-size:.78rem">No bonds recorded yet</div>`;
787
+
788
+ graphHtml = `<div class="rel-section-title">Between them</div>
789
+ <div class="bond-graph-wrap">${_buildBondGraph(knownChars, npcBonds)}</div>
790
+ <div class="bond-list">${bondListHtml}</div>`;
791
+ }
792
+
793
+ panel.innerHTML =
794
+ `<div class="rel-section-title">With you</div>${barsHtml}${graphHtml}`;
795
+ }
796
+
797
+ // Semantic coloring: note keywords override the numeric value
798
+ const _NEG_NOTE = /jealou|rival|resent|env[iy]|bitter|hostil|scorn|distrust|spite|hate|anger/i;
799
+ const _POS_NOTE = /fond|loyal|protect|admire|camaraderie|trust|warm|friend|love|cherish/i;
800
+ function _bondColor(note, value) {
801
+ if (note && _NEG_NOTE.test(note)) return "#c87e7e";
802
+ if (note && _POS_NOTE.test(note)) return "#7ec8a0";
803
+ return value >= 0 ? "#7ec8a0" : "#c87e7e";
804
+ }
805
+
806
+ function _buildBondGraph(chars, bonds) {
807
+ const W = 340, H = 280, cx = W / 2, cy = H / 2;
808
+ // Use a larger radius now that there's no center player node to avoid
809
+ const R = Math.min(cx, cy) - 44;
810
+
811
+ // Position NPCs in a circle
812
+ const nodes = chars.map((ch, i) => {
813
+ const angle = (2 * Math.PI * i / chars.length) - Math.PI / 2;
814
+ return {
815
+ id: ch.id, name: ch.name,
816
+ x: cx + R * Math.cos(angle),
817
+ y: cy + R * Math.sin(angle),
818
+ rel: ch.relationship ?? 0,
819
+ sprite: ch.sprite_url || spriteCache[ch.id] || null,
820
+ };
821
+ });
822
+ const nodeMap = Object.fromEntries(nodes.map(n => [n.id, n]));
823
+
824
+ // Curved NPC↔NPC bond arcs
825
+ let arcs = "";
826
+ // group bonds by pair to detect bidirectional
827
+ const pairOffset = {};
828
+ for (const b of bonds) {
829
+ const key = [b.source_id, b.target_id].sort().join("|");
830
+ pairOffset[key] = (pairOffset[key] || 0) + 1;
831
+ }
832
+ const pairUsed = {};
833
+ for (const b of bonds) {
834
+ const src = nodeMap[b.source_id], tgt = nodeMap[b.target_id];
835
+ if (!src || !tgt) continue;
836
+ const pairKey = [b.source_id, b.target_id].sort().join("|");
837
+ const side = (pairOffset[pairKey] > 1 && (pairUsed[pairKey] || 0) === 0) ? 1 : -1;
838
+ pairUsed[pairKey] = (pairUsed[pairKey] || 0) + 1;
839
+
840
+ // Perpendicular offset — use a CANONICAL direction (sorted by id) so that both
841
+ // A→B and B→A get the same perpendicular axis; side then reliably puts them
842
+ // on opposite sides instead of accidentally cancelling out.
843
+ const [canonSrc, canonTgt] = b.source_id < b.target_id ? [src, tgt] : [tgt, src];
844
+ const cdx = canonTgt.x - canonSrc.x, cdy = canonTgt.y - canonSrc.y;
845
+ const clen = Math.sqrt(cdx * cdx + cdy * cdy) || 1;
846
+ const perpX = -cdy / clen, perpY = cdx / clen; // canonical perpendicular unit vector
847
+
848
+ const curveStrength = pairOffset[pairKey] > 1 ? 48 : 18;
849
+ const cpx = (src.x + tgt.x) / 2 + perpX * curveStrength * side;
850
+ const cpy = (src.y + tgt.y) / 2 + perpY * curveStrength * side;
851
+
852
+ const col = _bondColor(b.note, b.value);
853
+ const op = (0.35 + Math.abs(b.value) / 100 * 0.65).toFixed(2);
854
+ const sw = (1 + Math.abs(b.value) / 100 * 3.5).toFixed(1);
855
+
856
+ // Arrowhead at 85% along bezier curve (near target)
857
+ const markerId = `arr-${b.source_id}-${b.target_id}`.replace(/[^a-z0-9-]/gi,"_");
858
+ arcs += `<defs><marker id="${markerId}" markerWidth="5" markerHeight="5"
859
+ refX="4" refY="2.5" orient="auto">
860
+ <polygon points="0,0 5,2.5 0,5" fill="${col}" fill-opacity="${op}"/>
861
+ </marker></defs>
862
+ <path d="M${src.x},${src.y} Q${cpx},${cpy} ${tgt.x},${tgt.y}"
863
+ fill="none" stroke="${col}" stroke-width="${sw}" stroke-opacity="${op}"
864
+ stroke-linecap="round" marker-end="url(#${markerId})"/>`;
865
+
866
+ if (b.note) {
867
+ // For bidirectional pairs, push each label further in its own canonical perpendicular
868
+ // direction so the two notes don't stack on top of each other.
869
+ const bidir = pairOffset[pairKey] > 1;
870
+ const baseLx = 0.25 * src.x + 0.5 * cpx + 0.25 * tgt.x;
871
+ const baseLy = 0.25 * src.y + 0.5 * cpy + 0.25 * tgt.y;
872
+ const labelOffsetX = bidir ? perpX * 10 * side : 0;
873
+ const labelOffsetY = bidir ? perpY * 10 * side : -4;
874
+ const lx = baseLx + labelOffsetX;
875
+ const ly = baseLy + labelOffsetY;
876
+ arcs += `<text x="${lx}" y="${ly}" text-anchor="middle"
877
+ font-size="9" fill="${col}"
878
+ paint-order="stroke" stroke="rgba(10,8,18,.85)" stroke-width="3" stroke-linejoin="round"
879
+ font-family="Georgia,serif" font-style="italic">${b.note}</text>`;
880
+ }
881
+ }
882
+
883
+ // NPC circle nodes (sprite or emoji) + name coloured by player relation
884
+ let nodesSvg = "";
885
+ for (const n of nodes) {
886
+ const clipId = `cl_${n.id}`.replace(/[^a-z0-9_]/gi,"_");
887
+ // Border colour by relation to player
888
+ const borderCol = n.rel > 20 ? "#7ec8a0" : n.rel < -20 ? "#c87e7e" : "rgba(232,193,114,.55)";
889
+ const nameCol = n.rel > 20 ? "#9ddcba" : n.rel < -20 ? "#dba0a0" : "rgba(232,193,114,.92)";
890
+ nodesSvg += `<circle cx="${n.x}" cy="${n.y}" r="22"
891
+ fill="rgba(255,255,255,.05)" stroke="${borderCol}" stroke-width="1.8"/>`;
892
+ if (n.sprite) {
893
+ nodesSvg += `<clipPath id="${clipId}"><circle cx="${n.x}" cy="${n.y}" r="20"/></clipPath>
894
+ <image href="${n.sprite}" x="${n.x-20}" y="${n.y-20}" width="40" height="40"
895
+ clip-path="url(#${clipId})" preserveAspectRatio="xMidYMid slice"/>`;
896
+ } else {
897
+ nodesSvg += `<text x="${n.x}" y="${n.y+5}" text-anchor="middle" font-size="16">👤</text>`;
898
+ }
899
+ // Name label with dark stroke outline for readability
900
+ nodesSvg += `<text x="${n.x}" y="${n.y+38}" text-anchor="middle"
901
+ font-size="10.5" fill="${nameCol}" font-family="Georgia,serif"
902
+ paint-order="stroke" stroke="rgba(10,8,18,.9)" stroke-width="3.5" stroke-linejoin="round">${n.name}</text>`;
903
+ }
904
+
905
+ return `<svg viewBox="0 0 ${W} ${H}" xmlns="http://www.w3.org/2000/svg">
906
+ ${arcs}${nodesSvg}
907
+ </svg>`;
908
  }
909
 
910
  // keep track of who's currently on stage for the relations panel
 
973
  function render(v){
974
  if (v.known_characters?.length) {
975
  knownChars = v.known_characters;
 
976
  for (const ch of knownChars) {
977
  if (ch.sprite_url) spriteCache[ch.id] = ch.sprite_url;
978
  }
979
  }
980
+ if (v.npc_bonds !== undefined) npcBonds = v.npc_bonds || [];
981
  $("place").textContent = v.place || "";
982
  $("speaker").textContent = v.speaker || "";
983
  typeOut($("line"), v.dialogue || "");
984
  playTTS(v.audio_b64);
985
+ if (v.current_music) switchMusic(v.current_music);
986
  if (v.backdrop_url && v.backdrop_url !== lastBg){
987
  const bg = $("backdrop");
988
  bg.classList.remove("on");
 
1049
 
1050
  // target chips — show only when multiple characters are on stage
1051
  updateTargetRow(v.present);
1052
+
1053
+ // ── Ending screen ──────────────────────────────────────────────────────────
1054
+ if (v.ended && v.ending_text) {
1055
+ setTimeout(() => showEnding(v.ending_kind, v.ending_text, v.backdrop_url), 1800);
1056
+ }
1057
+ }
1058
+
1059
+ function showEnding(kind, text, backdropUrl) {
1060
+ const overlay = $("ending-overlay");
1061
+ const isDefeat = kind === "defeat";
1062
+ overlay.className = "show " + (isDefeat ? "defeat" : "victory");
1063
+ // Use the generated ending illustration as the overlay background
1064
+ if (backdropUrl) {
1065
+ overlay.style.backgroundImage = `url(${backdropUrl})`;
1066
+ overlay.style.backgroundSize = "cover";
1067
+ overlay.style.backgroundPosition = "center";
1068
+ // Darken overlay content area so text stays readable over the image
1069
+ overlay.style.setProperty("--ending-dim", isDefeat
1070
+ ? "rgba(5,3,5,.78)" : "rgba(10,6,18,.65)");
1071
+ }
1072
+ $("ending-icon").textContent = isDefeat ? "💀" : "💕";
1073
+ $("ending-title").textContent = isDefeat ? "Game Over" : "✦ Fin ✦";
1074
+ $("ending-subtitle").textContent = isDefeat
1075
+ ? "The wanderer walks alone…"
1076
+ : "A warm ending";
1077
+ // Typewrite the epilogue text
1078
+ const el = $("ending-text");
1079
+ el.textContent = "";
1080
+ let i = 0;
1081
+ const iv = setInterval(() => {
1082
+ if (i >= text.length) { clearInterval(iv); return; }
1083
+ el.textContent += text[i++];
1084
+ }, 28);
1085
+ // Replay button label
1086
+ $("ending-replay").textContent = isDefeat ? "Try again" : "Play again";
1087
+ // Music: overlay already triggered set_music via render, but be safe
1088
+ if (isDefeat && !bgmTrackName?.includes("sad")) switchMusic("sad");
1089
+ if (!isDefeat && !bgmTrackName?.includes("romantic")) switchMusic("romantic");
1090
  }
1091
 
1092
  function showNotif(msg){
 
1179
  document.querySelectorAll(".target-chip").forEach(b => b.disabled = state);
1180
  }
1181
 
1182
+ // --- TTS toggle + volume ---
1183
+ let ttsVol = 1.0; // 0–1, controlled by settings slider
1184
  let ttsEnabled = true;
1185
+ // ttsBtn removed from DOM — state managed solely via settings sliders
1186
+ const ttsBtn = { textContent: "", classList: { add:()=>{}, toggle:()=>{}, remove:()=>{} } };
 
 
 
 
 
 
 
1187
 
1188
  function playTTS(audio_b64) {
1189
  if (!ttsEnabled || !audio_b64) return;
 
1193
  audio.id = "vn-audio";
1194
  document.body.appendChild(audio);
1195
  }
1196
+ audio.volume = ttsVol;
1197
  audio.src = audio_b64;
1198
+ audio.play().catch(() => {});
1199
+ }
1200
+
1201
+ // --- BGM (background music) ---
1202
+ const BGM_TRACKS = {
1203
+ calm: "/music/calm.mp3",
1204
+ romantic: "/music/romantic.mp3",
1205
+ dramatic: "/music/dramatic.mp3",
1206
+ mystery: "/music/mystery.mp3",
1207
+ sad: "/music/sad.mp3",
1208
+ joyful: "/music/joyful.mp3",
1209
+ };
1210
+ let bgmMasterVolume = 0.35; // master volume (0–1) — controlled by settings slider
1211
+ const BGM_FADE_OUT_MS = 2800; // old track fades out over this long
1212
+ const BGM_FADE_IN_MS = 3200; // new track fades in over this long
1213
+ const BGM_OVERLAP_MS = 1200; // new track starts this many ms before old finishes
1214
+
1215
+ let bgmEnabled = true;
1216
+ let bgmCurrent = null; // currently playing Audio object
1217
+ let bgmTrackName = null; // track key of bgmCurrent
1218
+
1219
+ // bgmBtn removed from DOM — state managed solely via settings sliders
1220
+ const bgmBtn = { textContent: "", classList: { add:()=>{}, toggle:()=>{}, remove:()=>{} } };
1221
+
1222
+ function switchMusic(name) {
1223
+ if (!name || !BGM_TRACKS[name]) return;
1224
+ if (name === bgmTrackName) return;
1225
+ if (!bgmEnabled) { bgmTrackName = name; return; }
1226
+ _bgmPlay(name);
1227
+ }
1228
+
1229
+ function _bgmPlay(name) {
1230
+ const old = bgmCurrent;
1231
+ bgmTrackName = name;
1232
+
1233
+ const a = new Audio(BGM_TRACKS[name]);
1234
+ a.loop = true;
1235
+ a.volume = 0;
1236
+ bgmCurrent = a;
1237
+
1238
+ // Helper: actually start the audio and fade it in
1239
+ const startFadeIn = () => {
1240
+ const p = a.play();
1241
+ if (p !== undefined) {
1242
+ p.catch(() => {
1243
+ // Autoplay still blocked — retry on the very next user interaction
1244
+ const retry = () => {
1245
+ if (bgmCurrent === a && bgmEnabled) {
1246
+ a.play().then(() => _bgmFade(a, 0, bgmMasterVolume, BGM_FADE_IN_MS)).catch(() => {});
1247
+ }
1248
+ };
1249
+ document.addEventListener("click", retry, { once: true });
1250
+ document.addEventListener("keydown", retry, { once: true });
1251
+ });
1252
+ }
1253
+ _bgmFade(a, 0, bgmMasterVolume, BGM_FADE_IN_MS);
1254
+ };
1255
+
1256
+ if (old) {
1257
+ _bgmFade(old, old.volume, 0, BGM_FADE_OUT_MS, () => { old.pause(); old.src = ""; });
1258
+ setTimeout(startFadeIn, BGM_FADE_OUT_MS - BGM_OVERLAP_MS);
1259
+ } else {
1260
+ startFadeIn();
1261
+ }
1262
+ }
1263
+
1264
+ // Smooth volume ramp using requestAnimationFrame + ease-in-out curve
1265
+ function _bgmFade(audio, fromVol, toVol, ms, onDone) {
1266
+ const start = performance.now();
1267
+ function tick(now) {
1268
+ const raw = Math.min(1, (now - start) / ms);
1269
+ // ease-in-out: smoothstep
1270
+ const t = raw * raw * (3 - 2 * raw);
1271
+ audio.volume = fromVol + (toVol - fromVol) * t;
1272
+ if (raw < 1) {
1273
+ requestAnimationFrame(tick);
1274
+ } else {
1275
+ audio.volume = toVol;
1276
+ if (onDone) onDone();
1277
+ }
1278
+ }
1279
+ requestAnimationFrame(tick);
1280
  }
1281
 
1282
  // --- book overlay dismiss ---
 
1285
  $("say").focus();
1286
  });
1287
 
1288
+ // --- ending replay ---
1289
+ $("ending-replay").addEventListener("click", () => {
1290
+ // Stop music, reset ending overlay, go back to choice screen
1291
+ if (bgmCurrent) { _bgmFade(bgmCurrent, bgmCurrent.volume, 0, 800, () => { bgmCurrent.pause(); bgmCurrent.src = ""; }); bgmCurrent = null; }
1292
+ bgmTrackName = null;
1293
+ $("ending-overlay").className = ""; // hide
1294
+ // Reset game UI state
1295
+ history = []; journalTurn = 0; knownChars = []; npcBonds = [];
1296
+ $("place").textContent = ""; $("speaker").textContent = ""; $("line").textContent = "";
1297
+ $("sprites").innerHTML = ""; lastBg = null;
1298
+ $("backdrop").style.backgroundImage = "none"; $("backdrop").classList.remove("on");
1299
+ $("journal-btn").classList.add("hidden");
1300
+ $("settings-btn").classList.add("hidden");
1301
+ $("enter").disabled = false;
1302
+ $("enter").textContent = "Enter the story";
1303
+ $("choice-screen").classList.remove("hidden");
1304
+ });
1305
+
1306
  // --- choice screen ---
1307
  $("btn-new").addEventListener("click", () => {
1308
  $("choice-screen").classList.add("hidden");
 
1313
  const file = e.target.files[0];
1314
  if (!file) return;
1315
  const text = await file.text();
1316
+
1317
+ // Start a neutral track NOW (user gesture from the file picker is still active)
1318
+ if (bgmEnabled) switchMusic("calm");
1319
+
1320
  busy(true);
1321
  try {
1322
  // Extract client-side journal history before sending state to server
1323
  let parsed;
1324
  try { parsed = JSON.parse(text); } catch { parsed = {}; }
1325
  const savedHistory = Array.isArray(parsed.journal_history) ? parsed.journal_history : [];
1326
+ const savedAudio = parsed.audio_settings || null;
1327
 
1328
  const { data } = await client.predict("/load_file", { data: text });
1329
  $("choice-screen").classList.add("hidden");
 
1333
  history = savedHistory;
1334
  journalTurn = savedHistory.length > 0 ? savedHistory[savedHistory.length - 1].turn : 0;
1335
 
1336
+ // Restore audio settings if present
1337
+ if (savedAudio) {
1338
+ const bgmPct = Math.max(0, Math.min(100, savedAudio.bgm_vol ?? 35));
1339
+ const ttsPct = Math.max(0, Math.min(100, savedAudio.tts_vol ?? 100));
1340
+ bgmMasterVolume = bgmPct / 100;
1341
+ ttsVol = ttsPct / 100;
1342
+ bgmEnabled = bgmPct > 0;
1343
+ ttsEnabled = ttsPct > 0;
1344
+ bgmVolSlider.value = bgmPct;
1345
+ bgmVolVal.textContent = bgmPct + "%";
1346
+ ttsVolSlider.value = ttsPct;
1347
+ ttsVolVal.textContent = ttsPct + "%";
1348
+ if (bgmCurrent) bgmCurrent.volume = bgmMasterVolume;
1349
+ // If there's an explicit saved track and music is enabled, pre-seed the track name
1350
+ // so render()'s switchMusic call (via current_music in ViewState) resumes it.
1351
+ if (savedAudio.bgm_track && bgmEnabled) bgmTrackName = null; // force switchMusic to not skip
1352
+ }
1353
+
1354
+ render(data[0]); // will call switchMusic with current_music from saved GameState flags
1355
+ // Fallback: if ViewState had no current_music but we saved a track, start it now
1356
+ if (savedAudio?.bgm_track && bgmEnabled && !bgmTrackName) {
1357
+ switchMusic(savedAudio.bgm_track);
1358
+ }
1359
  $("journal-btn").classList.remove("hidden");
1360
+ $("settings-btn").classList.remove("hidden");
1361
  } catch(err) { alert("Could not load save: " + (err?.message || err)); }
1362
  busy(false);
1363
  });
1364
 
1365
+ // --- settings panel ---
1366
+ $("settings-btn").addEventListener("click", () => $("settings-overlay").classList.add("open"));
1367
+ $("settings-close").addEventListener("click", () => $("settings-overlay").classList.remove("open"));
1368
+ $("settings-overlay").addEventListener("click", e => {
1369
+ if (e.target === $("settings-overlay")) $("settings-overlay").classList.remove("open");
1370
+ });
1371
+
1372
+ // --- BGM volume slider ---
1373
+ // Moving slider: adjusts master volume live; going to 0 mutes, above 0 unmutes.
1374
+ const bgmVolSlider = $("bgm-vol-slider");
1375
+ const bgmVolVal = $("bgm-vol-val");
1376
+ bgmVolSlider.addEventListener("input", () => {
1377
+ const pct = parseInt(bgmVolSlider.value, 10);
1378
+ bgmVolVal.textContent = pct + "%";
1379
+ bgmMasterVolume = pct / 100;
1380
+ if (pct === 0) {
1381
+ if (bgmEnabled) { // mute: fade out & disable
1382
+ bgmEnabled = false;
1383
+ if (bgmCurrent) {
1384
+ _bgmFade(bgmCurrent, bgmCurrent.volume, 0, 500, () => { bgmCurrent.pause(); bgmCurrent.src = ""; });
1385
+ bgmCurrent = null;
1386
+ }
1387
+ }
1388
+ } else {
1389
+ if (!bgmEnabled) { // unmute: re-enable and restart remembered track
1390
+ bgmEnabled = true;
1391
+ if (bgmTrackName) _bgmPlay(bgmTrackName);
1392
+ } else if (bgmCurrent) { // just change live volume
1393
+ bgmCurrent.volume = bgmMasterVolume;
1394
+ }
1395
+ }
1396
+ bgmBtn.classList.toggle("active", bgmEnabled);
1397
+ bgmBtn.textContent = bgmEnabled ? "🎵" : "🔇";
1398
+ });
1399
+
1400
+ // --- TTS volume slider ---
1401
+ const ttsVolSlider = $("tts-vol-slider");
1402
+ const ttsVolVal = $("tts-vol-val");
1403
+ ttsVolSlider.addEventListener("input", () => {
1404
+ const pct = parseInt(ttsVolSlider.value, 10);
1405
+ ttsVolVal.textContent = pct + "%";
1406
+ ttsVol = pct / 100;
1407
+ ttsEnabled = pct > 0;
1408
+ const a = $("vn-audio"); if (a) a.volume = ttsVol;
1409
+ ttsBtn.classList.toggle("active", ttsEnabled);
1410
+ ttsBtn.textContent = ttsEnabled ? "🔊" : "🔇";
1411
+ });
1412
+
1413
+ // Save button
1414
+ $("settings-save-btn").addEventListener("click", async () => {
1415
+ const btn = $("settings-save-btn");
1416
+ btn.disabled = true;
1417
+ btn.textContent = "Saving…";
1418
  try {
1419
  const { data } = await client.predict("/save_data", {});
 
1420
  const saveObj = JSON.parse(data[0].json);
1421
  saveObj.journal_history = history;
1422
+ saveObj.audio_settings = {
1423
+ bgm_vol: Math.round(bgmMasterVolume * 100),
1424
+ tts_vol: Math.round(ttsVol * 100),
1425
+ bgm_track: bgmTrackName || null,
1426
+ };
1427
  const blob = new Blob([JSON.stringify(saveObj)], { type: "application/json" });
1428
  const a = document.createElement("a");
1429
  a.href = URL.createObjectURL(blob);
1430
  a.download = "ephemeral-hearts-save.json";
1431
  a.click();
1432
  URL.revokeObjectURL(a.href);
1433
+ btn.textContent = " Saved!";
1434
+ setTimeout(() => { btn.textContent = "💾 Save current game"; btn.disabled = false; }, 2000);
1435
+ } catch(err) {
1436
+ console.error("save failed", err);
1437
+ btn.textContent = "⚠️ Failed";
1438
+ setTimeout(() => { btn.textContent = "💾 Save current game"; btn.disabled = false; }, 2000);
1439
+ }
1440
  });
1441
 
1442
+ // tone -> initial BGM track (mirrors engine.py start() logic)
1443
+ const TONE_MUSIC = { romantic:"romantic", flirty:"romantic", dramatic:"dramatic", bittersweet:"sad", comedic:"joyful" };
1444
+
1445
  // --- start ---
1446
  $("enter").addEventListener("click", async () => {
1447
  const btn = $("enter");
1448
  btn.disabled = true;
1449
  const orig = btn.textContent;
1450
  btn.textContent = "✨ Creating your story…";
1451
+
1452
+ // Kick off music NOW while the user gesture is still fresh.
1453
+ if (bgmEnabled) switchMusic(TONE_MUSIC[$("tone").value] || "calm");
1454
+
1455
+ // --- two-phase segmented progress ---
1456
+ const spEl = $("start-progress");
1457
+ spEl.style.display = "block";
1458
+
1459
+ // Per-phase helpers
1460
+ let _spTick = null;
1461
+ const _spNote = (id, msg) => {
1462
+ const el = $(id);
1463
+ el.style.opacity = "0";
1464
+ setTimeout(() => { el.textContent = msg; el.style.opacity = "1"; }, 200);
1465
+ };
1466
+ // Animate fill toward `target` (0-100) at `stepMs` per tick; resolves when target hit
1467
+ const _spCrawl = (fillId, pctId, target, stepMs) => new Promise(resolve => {
1468
+ if (_spTick) { clearInterval(_spTick); _spTick = null; }
1469
+ const fill = $(fillId), pctEl = $(pctId);
1470
+ let cur = parseFloat(fill.style.width) || 0;
1471
+ _spTick = setInterval(() => {
1472
+ cur = Math.min(target, cur + 0.7);
1473
+ fill.style.width = cur + "%";
1474
+ pctEl.textContent = Math.round(cur) + "%";
1475
+ if (cur >= target) { clearInterval(_spTick); _spTick = null; resolve(); }
1476
+ }, stepMs);
1477
+ });
1478
+ const _spFinish = (fillId, pctId, label) => {
1479
+ if (_spTick) { clearInterval(_spTick); _spTick = null; }
1480
+ $(fillId).style.width = "100%";
1481
+ $(pctId).textContent = label || "100%";
1482
+ };
1483
+ const spHide = () => {
1484
+ spEl.style.display = "none";
1485
+ ["sp-fill-llm","sp-fill-img"].forEach(id => { $(id).style.width = "0%"; });
1486
+ };
1487
+
1488
+ // LLM notes cycling (reassuring messages while waiting for the model)
1489
+ const LLM_NOTES = [
1490
+ "The AI is generating your opening scene…",
1491
+ "First load can take 30–60 s while the model warms up…",
1492
+ "Inventing characters, secrets, and a first line just for you…",
1493
+ "Almost done writing — hang on…",
1494
+ ];
1495
+ let _llmNoteIdx = 0;
1496
+ const _llmNoteTick = setInterval(() => {
1497
+ _llmNoteIdx = (_llmNoteIdx + 1) % LLM_NOTES.length;
1498
+ _spNote("sp-note-llm", LLM_NOTES[_llmNoteIdx]);
1499
+ }, 9000);
1500
+
1501
  try {
1502
+ // ── Phase 1 : LLM world init ──────────────────────────────────────────
1503
+ _spNote("sp-note-llm", LLM_NOTES[0]);
1504
+ // Crawl 0→88% slowly — will stop there until the real call returns
1505
+ _spCrawl("sp-fill-llm", "sp-pct-llm", 88, 800);
1506
+
1507
+ const { data: d1 } = await client.predict("/start_text", {
1508
+ theme: $("theme").value,
1509
+ tone: $("tone").value,
1510
+ });
1511
+
1512
+ // LLM done — complete bar 1, unlock bar 2 (stay on setup screen)
1513
+ clearInterval(_llmNoteTick);
1514
+ _spFinish("sp-fill-llm", "sp-pct-llm", "100%");
1515
+ _spNote("sp-note-llm", "Story written ✓");
1516
+ $("sp-step-img").style.opacity = "1";
1517
+ _spNote("sp-note-img", "Generating backdrop and character illustration…");
1518
+ $("sp-pct-img").textContent = "0%";
1519
+
1520
+ // ── Phase 2 : image generation ────────────────────────────────────────
1521
+ // Crawl 0→85% while painter works
1522
+ _spCrawl("sp-fill-img", "sp-pct-img", 85, 350);
1523
+
1524
+ const { data: d2 } = await client.predict("/start_images", {});
1525
+
1526
+ // Everything ready — complete bar 2, then reveal the game
1527
+ _spFinish("sp-fill-img", "sp-pct-img", "100%");
1528
+ _spNote("sp-note-img", "Scene ready ✓");
1529
+ render(d2[0]);
1530
+ addToHistory("", d2[0]);
1531
  $("setup").classList.add("hidden");
 
 
1532
  $("journal-btn").classList.remove("hidden");
1533
+ $("settings-btn").classList.remove("hidden");
1534
+
1535
+ setTimeout(() => {
1536
+ spHide();
1537
+ if (d2[0]?.intro_text) {
1538
+ $("book-text").textContent = d2[0].intro_text;
1539
+ $("intro-book").classList.remove("hidden");
1540
+ }
1541
+ }, 700);
1542
+
1543
  } catch(err) {
1544
  console.error("start failed", err);
1545
+ clearInterval(_llmNoteTick);
1546
+ if (_spTick) { clearInterval(_spTick); _spTick = null; }
1547
+ spHide();
1548
  btn.textContent = "⚠️ Failed — try again";
1549
  btn.disabled = false;
1550
  setTimeout(() => { btn.textContent = orig; }, 3000);
frontend/music/README.md ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Background Music Tracks
2
+
3
+ Place looping MP3 (or OGG) files here. The game expects these exact filenames:
4
+
5
+ | File | When it plays |
6
+ |---|---|
7
+ | `calm.mp3` | Peaceful moments, exploration, default opening |
8
+ | `romantic.mp3` | Soft intimate scenes, growing closeness |
9
+ | `dramatic.mp3` | Tense confrontations, high stakes |
10
+ | `mystery.mp3` | Uncanny atmosphere, secrets revealed |
11
+ | `sad.mp3` | Melancholic, bittersweet, loss |
12
+ | `joyful.mp3` | Playful, comedic, happy scenes |
13
+
14
+ ## Free sources (royalty-free, loop-friendly)
15
+
16
+ - **Kevin MacLeod** — https://incompetech.filmmusic.io (CC BY 4.0)
17
+ - **Pixabay Music** — https://pixabay.com/music/ (free, no attribution needed)
18
+ - **FreeMusicArchive** — https://freemusicarchive.org
19
+
20
+ ## Recommended Kevin MacLeod tracks
21
+
22
+ | Mood | Track name |
23
+ |---|---|
24
+ | calm | "Comfortable Mystery" or "Floating Cities" |
25
+ | romantic | "Sneaky Snitch" or "Heartwarming" |
26
+ | dramatic | "Darkest Child" or "Cipher" |
27
+ | mystery | "Ossuary 5 - Rest" or "Scheming Weasel" |
28
+ | sad | "Sonatina in C Minor" or "Parting of the Ways" |
29
+ | joyful | "Carefree" or "Fluffing a Duck" |
30
+
31
+ Files must be served from this folder — the app mounts `/music` → `frontend/music/`.
32
+ If a file is missing the browser simply plays nothing for that mood (no crash).
visualnovel/characters.py CHANGED
@@ -36,6 +36,16 @@ def present_sheets_block(state: GameState) -> str:
36
  rel_note = " — barely acquainted; unsolicited touch or flirt feels uncomfortable (negative delta)"
37
  else:
38
  rel_note = ""
 
 
 
 
 
 
 
 
 
 
39
  blocks.append(
40
  f"### {c.name} (id: {c.id})\n"
41
  f"- one_line: {c.one_line}\n"
@@ -43,6 +53,7 @@ def present_sheets_block(state: GameState) -> str:
43
  f"- voice: {c.voice or '—'}\n"
44
  f"- goal: {c.goals or '—'}\n"
45
  f"- mood: {c.mood} | feeling toward wanderer: {rel}/100{rel_note}\n"
 
46
  f"- knows: {facts}"
47
  )
48
  return "\n\n".join(blocks) if blocks else "(no spirits on stage — the narrator may speak)"
 
36
  rel_note = " — barely acquainted; unsolicited touch or flirt feels uncomfortable (negative delta)"
37
  else:
38
  rel_note = ""
39
+ # NPC↔NPC bonds — only mention others who are in the cast
40
+ npc_bond_lines: list[str] = []
41
+ for other_id, bond_val in c.npc_relations.items():
42
+ if other_id in state.characters:
43
+ other = state.characters[other_id]
44
+ note = c.npc_relation_notes.get(other_id, "")
45
+ label = f" ({note})" if note else ""
46
+ npc_bond_lines.append(f"{other.name}: {bond_val:+d}{label}")
47
+ npc_bonds_str = "; ".join(npc_bond_lines) if npc_bond_lines else "—"
48
+
49
  blocks.append(
50
  f"### {c.name} (id: {c.id})\n"
51
  f"- one_line: {c.one_line}\n"
 
53
  f"- voice: {c.voice or '—'}\n"
54
  f"- goal: {c.goals or '—'}\n"
55
  f"- mood: {c.mood} | feeling toward wanderer: {rel}/100{rel_note}\n"
56
+ f"- bonds with others: {npc_bonds_str}\n"
57
  f"- knows: {facts}"
58
  )
59
  return "\n\n".join(blocks) if blocks else "(no spirits on stage — the narrator may speak)"
visualnovel/engine.py CHANGED
@@ -23,7 +23,7 @@ from . import config, memory, orchestrator, state
23
  from .llm import get_llm
24
  from .metrics import collector
25
  from .painter import get_painter
26
- from .schemas import DirectorOutput, GameState, SetupForm, SpritePresence, Turn, ViewState
27
  from .stt import get_stt
28
  from .trace import Tracer
29
  from .tts import get_tts
@@ -37,10 +37,24 @@ class Engine:
37
  self.tts = get_tts()
38
  self.tracer = Tracer(config.TRACE_PATH)
39
  self.state: GameState | None = None
 
 
40
 
41
  # -- lifecycle --
42
  def start(self, setup: SetupForm) -> ViewState:
 
 
 
 
 
 
 
43
  self.state, opening = orchestrator.init_world(self.llm, setup)
 
 
 
 
 
44
  self.state.recent_turns.append(
45
  Turn(
46
  player="(arrives)",
@@ -49,11 +63,47 @@ class Engine:
49
  emotion=opening.emotion,
50
  )
51
  )
52
- state.apply_directives(self.state, opening) # sets the speaker's mood
53
  state.save_memory(self.state)
54
  self.tracer.log(event="start", setup=setup.model_dump(), opening=opening.model_dump())
55
  intro = self.state.flags.get("situation_intro", "")
56
- return self._view(opening, intro_text=intro)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
57
 
58
  def transcribe(self, audio_path: str) -> str:
59
  return self.stt.transcribe(audio_path)
@@ -152,7 +202,12 @@ class Engine:
152
  s = self.state
153
  assert s is not None
154
  with collector.measure("painter_backdrop", turn=turn):
155
- backdrop = self.painter.backdrop(s) # cached -> cheap even when unchanged
 
 
 
 
 
156
  present = []
157
  for cid in s.scene.present:
158
  ch = s.characters.get(cid)
@@ -195,6 +250,19 @@ class Engine:
195
  )
196
  )
197
 
 
 
 
 
 
 
 
 
 
 
 
 
 
198
  speaker_ch = s.characters.get(out.speaker)
199
  speaker_name = speaker_ch.name if speaker_ch else "The wood"
200
 
@@ -218,10 +286,13 @@ class Engine:
218
  beat=s.beat,
219
  ended=s.beat == "ended",
220
  ending_text=s.flags.get("ending_text"),
 
221
  turn_index=s.turn_index,
222
  notifications=notifications or [],
223
  intro_text=intro_text,
224
  audio_b64=audio_b64,
 
 
225
  )
226
 
227
 
 
23
  from .llm import get_llm
24
  from .metrics import collector
25
  from .painter import get_painter
26
+ from .schemas import DirectorOutput, GameState, NPCBond, SetupForm, SpritePresence, Turn, ViewState
27
  from .stt import get_stt
28
  from .trace import Tracer
29
  from .tts import get_tts
 
37
  self.tts = get_tts()
38
  self.tracer = Tracer(config.TRACE_PATH)
39
  self.state: GameState | None = None
40
+ self._pending_out: DirectorOutput | None = None
41
+ self._pending_intro: str = ""
42
 
43
  # -- lifecycle --
44
  def start(self, setup: SetupForm) -> ViewState:
45
+ """Full start (used by smoke test / MVP UI). Calls both phases."""
46
+ self.start_text(setup)
47
+ return self.start_images()
48
+
49
+ def start_text(self, setup: SetupForm) -> ViewState:
50
+ """Phase 1 — LLM world-init only. Fast. Returns a text-only ViewState (no images/TTS).
51
+ Sets self.state and stores the opening DirectorOutput for start_images()."""
52
  self.state, opening = orchestrator.init_world(self.llm, setup)
53
+ _tone_music: dict[str, str] = {
54
+ "romantic": "romantic", "flirty": "romantic",
55
+ "dramatic": "dramatic", "bittersweet": "sad", "comedic": "joyful",
56
+ }
57
+ self.state.flags["current_music"] = _tone_music.get(setup.tone, "calm")
58
  self.state.recent_turns.append(
59
  Turn(
60
  player="(arrives)",
 
63
  emotion=opening.emotion,
64
  )
65
  )
66
+ state.apply_directives(self.state, opening)
67
  state.save_memory(self.state)
68
  self.tracer.log(event="start", setup=setup.model_dump(), opening=opening.model_dump())
69
  intro = self.state.flags.get("situation_intro", "")
70
+ # Stash for start_images()
71
+ self._pending_out: DirectorOutput | None = opening
72
+ self._pending_intro: str = intro
73
+ # Build a text-only ViewState so the frontend can show dialogue immediately
74
+ s = self.state
75
+ speaker_ch = s.characters.get(opening.speaker)
76
+ speaker_name = speaker_ch.name if speaker_ch else "The wood"
77
+ known: list[SpritePresence] = []
78
+ for cid, ch in s.characters.items():
79
+ disc = [ch.traits[i] for i in ch.discovered_traits if i < len(ch.traits)]
80
+ known.append(SpritePresence(
81
+ id=ch.id, name=ch.name, mood=ch.mood, sprite_url=None,
82
+ relationship=ch.relationship, public_bio=ch.one_line,
83
+ discovered_traits=disc, total_traits=len(ch.traits),
84
+ secret_goal=ch.goals if ch.goal_unlocked else None,
85
+ ))
86
+ return ViewState(
87
+ speaker=speaker_name,
88
+ dialogue=opening.dialogue,
89
+ emotion=opening.emotion,
90
+ place=s.scene.place,
91
+ backdrop_url=None,
92
+ present=[],
93
+ known_characters=known,
94
+ beat=s.beat,
95
+ turn_index=s.turn_index,
96
+ intro_text=intro,
97
+ current_music=s.flags.get("current_music"),
98
+ npc_bonds=[],
99
+ )
100
+
101
+ def start_images(self) -> ViewState:
102
+ """Phase 2 — paint backdrop + sprite, TTS. Call after start_text().
103
+ Returns the full ViewState."""
104
+ assert self.state is not None and self._pending_out is not None, \
105
+ "call start_text() first"
106
+ return self._view(self._pending_out, intro_text=self._pending_intro)
107
 
108
  def transcribe(self, audio_path: str) -> str:
109
  return self.stt.transcribe(audio_path)
 
202
  s = self.state
203
  assert s is not None
204
  with collector.measure("painter_backdrop", turn=turn):
205
+ if s.beat == "ended":
206
+ # Generate a dedicated ending illustration instead of the regular backdrop
207
+ ending_kind = s.flags.get("ending_kind", "warm")
208
+ backdrop = self.painter.ending_backdrop(s, ending_kind)
209
+ else:
210
+ backdrop = self.painter.backdrop(s) # cached -> cheap even when unchanged
211
  present = []
212
  for cid in s.scene.present:
213
  ch = s.characters.get(cid)
 
250
  )
251
  )
252
 
253
+ # Collect all directed NPC↔NPC bonds for the frontend graph
254
+ npc_bonds: list[NPCBond] = []
255
+ for cid, ch in s.characters.items():
256
+ for other_id, val in ch.npc_relations.items():
257
+ if other_id in s.characters:
258
+ other = s.characters[other_id]
259
+ npc_bonds.append(NPCBond(
260
+ source_id=cid, source_name=ch.name,
261
+ target_id=other_id, target_name=other.name,
262
+ value=val,
263
+ note=ch.npc_relation_notes.get(other_id, ""),
264
+ ))
265
+
266
  speaker_ch = s.characters.get(out.speaker)
267
  speaker_name = speaker_ch.name if speaker_ch else "The wood"
268
 
 
286
  beat=s.beat,
287
  ended=s.beat == "ended",
288
  ending_text=s.flags.get("ending_text"),
289
+ ending_kind=s.flags.get("ending_kind"),
290
  turn_index=s.turn_index,
291
  notifications=notifications or [],
292
  intro_text=intro_text,
293
  audio_b64=audio_b64,
294
+ current_music=s.flags.get("current_music"),
295
+ npc_bonds=npc_bonds,
296
  )
297
 
298
 
visualnovel/llm.py CHANGED
@@ -20,6 +20,11 @@ import sys
20
  from collections.abc import Generator
21
  from typing import Any, Protocol
22
 
 
 
 
 
 
23
  from . import config
24
 
25
 
@@ -143,13 +148,13 @@ class ModalLLM:
143
 
144
  def complete(self, messages: list[dict[str, str]], **kw: Any) -> str:
145
  result = self._backend.complete.remote(messages, **kw)
146
- print(f"[ModalLLM] complete -> {result[:120]!r}")
147
  return result
148
 
149
  def complete_json(self, messages: list[dict[str, str]], schema: dict, **kw: Any) -> dict:
150
- print(f"[ModalLLM] complete_json input messages:\n{messages}\n")
151
  result = self._backend.complete_json.remote(messages, schema, **kw)
152
- print(f"[ModalLLM] complete_json -> {result}")
153
  return result
154
 
155
 
 
20
  from collections.abc import Generator
21
  from typing import Any, Protocol
22
 
23
+
24
+ def _safe_print(msg: str) -> None:
25
+ """Print to stdout, replacing unencodable chars (cp1252 on Windows terminals)."""
26
+ print(msg.encode(sys.stdout.encoding or "utf-8", errors="replace").decode(sys.stdout.encoding or "utf-8", errors="replace"))
27
+
28
  from . import config
29
 
30
 
 
148
 
149
  def complete(self, messages: list[dict[str, str]], **kw: Any) -> str:
150
  result = self._backend.complete.remote(messages, **kw)
151
+ _safe_print(f"[ModalLLM] complete -> {result[:120]!r}")
152
  return result
153
 
154
  def complete_json(self, messages: list[dict[str, str]], schema: dict, **kw: Any) -> dict:
155
+ _safe_print(f"[ModalLLM] complete_json input messages:\n{messages}\n")
156
  result = self._backend.complete_json.remote(messages, schema, **kw)
157
+ _safe_print(f"[ModalLLM] complete_json -> {result}")
158
  return result
159
 
160
 
visualnovel/memory.py CHANGED
@@ -34,8 +34,39 @@ def assemble_context(state: GameState, player_input: str) -> str:
34
  if off_stage:
35
  parts.append("KNOWN BUT OFF STAGE (can return — use their existing id):\n" + "\n".join(off_stage))
36
 
37
- if state.flags:
38
- parts.append("FACTS: " + ", ".join(f"{k}={v}" for k, v in state.flags.items()))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39
 
40
  recent = state.recent_turns[-config.RECENT_TURNS_K :]
41
  if recent:
 
34
  if off_stage:
35
  parts.append("KNOWN BUT OFF STAGE (can return — use their existing id):\n" + "\n".join(off_stage))
36
 
37
+ # ── Ending milestone hints — injected when a character hits ±100 ──────────
38
+ for ch in state.characters.values():
39
+ if ch.relationship >= 100 and ch.id in state.scene.present:
40
+ parts.append(
41
+ f"*** ROMANCE PEAK: {ch.name}'s affection is at MAX (100/100). ***\n"
42
+ f"This turn MUST be their heartfelt confession. Emit ending(kind=\"warm\") "
43
+ f"with a poetic 2-4 sentence epilogue. Also emit set_music=\"romantic\"."
44
+ )
45
+ elif ch.relationship <= -100 and ch.id in state.scene.present:
46
+ parts.append(
47
+ f"*** RELATIONSHIP BROKEN: {ch.name} is at MIN (-100/100). ***\n"
48
+ f"They storm off with a final cutting line. MUST emit exit_character=\"{ch.id}\". "
49
+ f"If the stage becomes empty after this, also emit ending(kind=\"defeat\") "
50
+ f"with a dark 2-4 sentence epilogue. Emit set_music=\"sad\"."
51
+ )
52
+ # If scene already empty and not yet ended — nudge for defeat
53
+ if not state.scene.present and state.beat != "ended" and state.characters:
54
+ parts.append(
55
+ "*** THE STAGE IS EMPTY — the wanderer is completely alone. ***\n"
56
+ "Emit ending(kind=\"defeat\") with a melancholic epilogue. Emit set_music=\"sad\"."
57
+ )
58
+
59
+ # Surface the current music track prominently so the LLM doesn't switch it needlessly.
60
+ current_music = state.flags.get("current_music")
61
+ if current_music:
62
+ parts.append(
63
+ f"CURRENT BGM: \"{current_music}\" — leave set_music null unless a MAJOR tonal "
64
+ f"shift justifies a change (max once every 6-8 turns)."
65
+ )
66
+
67
+ other_flags = {k: v for k, v in state.flags.items() if k != "current_music"}
68
+ if other_flags:
69
+ parts.append("FACTS: " + ", ".join(f"{k}={v}" for k, v in other_flags.items()))
70
 
71
  recent = state.recent_turns[-config.RECENT_TURNS_K :]
72
  if recent:
visualnovel/painter.py CHANGED
@@ -134,6 +134,35 @@ class PainterBase:
134
  negative_prompt=_SPRITE_NEGATIVE,
135
  )
136
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
137
  # -- internals --
138
  def _cached(self, *, kind: str, key: str, prompt: str, seed: int,
139
  negative_prompt: str = "", guidance_scale: float = 0.0,
 
134
  negative_prompt=_SPRITE_NEGATIVE,
135
  )
136
 
137
+ def ending_backdrop(self, state: GameState, kind: str) -> Path:
138
+ """Generate (and cache) a special ending illustration based on the ending kind."""
139
+ style = _backdrop_style(state.style_guide)
140
+ _ENDING_DESCS: dict[str, tuple[str, str]] = {
141
+ "warm": ("cherry blossom park at golden sunset, petals falling softly, "
142
+ "empty bench under blooming trees, warm amber light filtering through branches",
143
+ "romantic warm"),
144
+ "bittersweet": ("misty autumn street at twilight, fallen leaves on cobblestones, "
145
+ "distant lamplight, empty path fading into soft fog",
146
+ "melancholic gentle"),
147
+ "strange": ("surreal moonlit garden, glowing silver motes drifting upward, "
148
+ "impossible geometry, dreamlike luminous plants",
149
+ "mysterious ethereal"),
150
+ "defeat": ("rain-soaked empty park bench at night, fallen leaves in puddles, "
151
+ "single dim lamppost, deserted street receding into darkness",
152
+ "desolate cold"),
153
+ }
154
+ desc, mood = _ENDING_DESCS.get(kind, _ENDING_DESCS["warm"])
155
+ prompt = (
156
+ f"background art, empty scenic environment, wide establishing shot, no humans, "
157
+ f"uninhabited location, {desc}, {mood} atmosphere, {style}, no text"
158
+ )
159
+ seed = (state.seed * 1234567 + sum(ord(c) for c in kind)) % (2 ** 31)
160
+ return self._cached(
161
+ kind="ending", key=kind, prompt=prompt, seed=seed,
162
+ negative_prompt=_BACKDROP_NEGATIVE,
163
+ guidance_scale=config.BACKDROP_GUIDANCE,
164
+ )
165
+
166
  # -- internals --
167
  def _cached(self, *, kind: str, key: str, prompt: str, seed: int,
168
  negative_prompt: str = "", guidance_scale: float = 0.0,
visualnovel/prompts.py CHANGED
@@ -43,11 +43,29 @@ Rules:
43
  - Relationship_delta ranges from -100 to +100. Romantic warmth builds it up; coldness,
44
  insults, or rejection bring it down. React authentically to negative moments — hurt, cold,
45
  quietly withdrawing. Do NOT loop the same response — escalate or shift the dynamic.
46
- - If a character's relationship reaches -100 they have had enough. They storm off,
 
 
 
 
47
  say something final and cutting, and MUST emit exit_character. They will NOT return
48
  unless the story calls for a dramatic reconciliation arc.
 
 
 
49
  - If a character explicitly says goodbye, storms off, or leaves for good -> emit
50
  exit_character with their exact id to remove them from the stage.
 
 
 
 
 
 
 
 
 
 
 
51
  - With multiple characters on stage, they may react to each other (banter, jealousy, a
52
  knowing glance) — but never more than 2 NPC-to-NPC exchanges in a row. After that the
53
  next line MUST address the player directly.
@@ -55,6 +73,19 @@ Rules:
55
  established fact.
56
  - NEVER repeat a line of dialogue verbatim from the recent exchanges. Every response must
57
  move the scene forward — emotionally, narratively, or tonally.
 
 
 
 
 
 
 
 
 
 
 
 
 
58
  - Output MUST be a single JSON object matching the schema. Nothing else.
59
  """
60
 
@@ -105,10 +136,10 @@ _ACTION_HINTS: dict[str, str] = {
105
  "touch": (
106
  "*The wanderer gently touches the character. "
107
  "Check their current relationship value in the character sheet: "
108
- "below 20 touch is UNWANTED, they pull back or react with discomfort/anger "
109
  "(negative relationship_delta); "
110
- "20-50 shy or surprised mixed reaction (small delta either way); "
111
- "above 50 welcomed warmly or with flustering (positive relationship_delta).*"
112
  ),
113
  "give": (
114
  "*The wanderer offers something to the character — "
 
43
  - Relationship_delta ranges from -100 to +100. Romantic warmth builds it up; coldness,
44
  insults, or rejection bring it down. React authentically to negative moments — hurt, cold,
45
  quietly withdrawing. Do NOT loop the same response — escalate or shift the dynamic.
46
+ - If a character's relationship reaches +100 -> this is the romance climax. They
47
+ confess their feelings; the moment is beautiful and emotional. MUST emit
48
+ ending(kind="warm") with 2-4 sentences of poetic epilogue narration (what happens
49
+ next, the future they share, the feeling in the air). Also emit set_music="romantic".
50
+ - If a character's relationship reaches -100 -> they have had enough. They storm off,
51
  say something final and cutting, and MUST emit exit_character. They will NOT return
52
  unless the story calls for a dramatic reconciliation arc.
53
+ - If ALL characters have left the stage after a -100 exit and the scene is now empty ->
54
+ emit ending(kind="defeat") with 2-4 sentences of dark epilogue: the wanderer is left
55
+ alone, their failures echo, the world feels cold. Also emit set_music="sad".
56
  - If a character explicitly says goodbye, storms off, or leaves for good -> emit
57
  exit_character with their exact id to remove them from the stage.
58
+ - NPCs have their own bonds with each other (shown in "bonds with others" on each sheet).
59
+ These bonds drive their behaviour: rivals bicker and compete for the player's attention;
60
+ friends cover for each other and share knowing glances; a jealous NPC makes cutting
61
+ remarks when another gets too close to the player.
62
+ Update bonds via npc_relation_deltas when a meaningful interaction shifts the dynamic —
63
+ e.g. player flirts with A while B watches (B gains jealousy toward A: delta -10 to -20);
64
+ two NPCs have a warm exchange (delta +10 to +20, note "camaraderie");
65
+ an NPC defends another from the player's rudeness (delta +15, note "protects").
66
+ Keep notes short (one word or phrase): "jealousy", "rivalry", "camaraderie",
67
+ "fondness", "protects", "admires", "resents", "envies", "loyal to".
68
+ Only update bonds when something actually happens — not every turn.
69
  - With multiple characters on stage, they may react to each other (banter, jealousy, a
70
  knowing glance) — but never more than 2 NPC-to-NPC exchanges in a row. After that the
71
  next line MUST address the player directly.
 
73
  established fact.
74
  - NEVER repeat a line of dialogue verbatim from the recent exchanges. Every response must
75
  move the scene forward — emotionally, narratively, or tonally.
76
+ - Music: think of it like a film score — one track covers an entire scene or arc.
77
+ Use set_music ONLY for major tonal ruptures (a sudden revelation, a scene that flips
78
+ from lighthearted to tense, a heartbreak, a triumphant moment). As a rule:
79
+ never switch more than once every 6-8 turns, never two switches in a row,
80
+ and NEVER switch just because the dialogue shifted slightly in mood.
81
+ Leave set_music as null on the vast majority of turns.
82
+ Available tracks (use the exact key string):
83
+ "calm" — peaceful ambiance, everyday moments, unhurried exploration
84
+ "romantic" — soft and intimate, growing closeness, tender confessions
85
+ "dramatic" — tense confrontations, high stakes, arguments, shock, revelations
86
+ "mystery" — uncanny atmosphere, secrets surfacing, strange occurrences
87
+ "sad" — melancholy, loss, a bittersweet farewell
88
+ "joyful" — playful, comedic, carefree, warm laughter
89
  - Output MUST be a single JSON object matching the schema. Nothing else.
90
  """
91
 
 
136
  "touch": (
137
  "*The wanderer gently touches the character. "
138
  "Check their current relationship value in the character sheet: "
139
+ "below 20 -> touch is UNWANTED, they pull back or react with discomfort/anger "
140
  "(negative relationship_delta); "
141
+ "20-50 -> shy or surprised mixed reaction (small delta either way); "
142
+ "above 50 -> welcomed warmly or with flustering (positive relationship_delta).*"
143
  ),
144
  "give": (
145
  "*The wanderer offers something to the character — "
visualnovel/schemas.py CHANGED
@@ -18,7 +18,7 @@ from pydantic import BaseModel, Field
18
  # --- small enums (kept as Literals so they show up cleanly in the JSON schema) ---
19
  Emotion = Literal["neutral", "joy", "fear", "anger", "sad", "surprise", "tender"]
20
  Beat = Literal["opening", "rising", "turn", "resolution", "ended"]
21
- EndingKind = Literal["warm", "bittersweet", "strange"]
22
 
23
 
24
  # --------------------------------------------------------------------------- #
@@ -41,6 +41,9 @@ class Character(BaseModel):
41
  discovered_traits: list[int] = Field(default_factory=list) # indices of unlocked traits
42
  goal_unlocked: bool = False
43
  tts_voice_description: str = "" # frozen at first introduction; never updated by directives
 
 
 
44
 
45
 
46
  class Scene(BaseModel):
@@ -83,6 +86,24 @@ class Ending(BaseModel):
83
  text: str
84
 
85
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
86
  class Directives(BaseModel):
87
  scene_change: SceneChange | None = None
88
  new_character: NewCharacter | None = None
@@ -91,6 +112,8 @@ class Directives(BaseModel):
91
  set_flags: dict[str, str] = Field(default_factory=dict)
92
  advance_beat: bool = False
93
  ending: Ending | None = None
 
 
94
 
95
 
96
  class DirectorOutput(BaseModel):
@@ -164,7 +187,10 @@ class ViewState(BaseModel):
164
  beat: Beat = "opening"
165
  ended: bool = False
166
  ending_text: str | None = None
 
167
  turn_index: int = 0
168
  notifications: list[str] = Field(default_factory=list) # popup messages this turn
169
  intro_text: str = "" # shown once in the book overlay at game start; empty on subsequent turns
170
  audio_b64: str | None = None # data:audio/wav;base64,... — absent when TTS is mocked
 
 
 
18
  # --- small enums (kept as Literals so they show up cleanly in the JSON schema) ---
19
  Emotion = Literal["neutral", "joy", "fear", "anger", "sad", "surprise", "tender"]
20
  Beat = Literal["opening", "rising", "turn", "resolution", "ended"]
21
+ EndingKind = Literal["warm", "bittersweet", "strange", "defeat"]
22
 
23
 
24
  # --------------------------------------------------------------------------- #
 
41
  discovered_traits: list[int] = Field(default_factory=list) # indices of unlocked traits
42
  goal_unlocked: bool = False
43
  tts_voice_description: str = "" # frozen at first introduction; never updated by directives
44
+ # NPC↔NPC bonds — keyed by other character id, value -100..100
45
+ npc_relations: dict[str, int] = Field(default_factory=dict)
46
+ npc_relation_notes: dict[str, str] = Field(default_factory=dict) # other_id -> latest label
47
 
48
 
49
  class Scene(BaseModel):
 
86
  text: str
87
 
88
 
89
+ class NPCRelDelta(BaseModel):
90
+ """One directed bond update between two NPCs."""
91
+ source: str # character id who holds the feeling
92
+ target: str # character id the feeling is directed at
93
+ delta: int # change to apply (-100..100)
94
+ note: str = "" # human label: "jealousy", "camaraderie", "rivalry", "fondness", "protects", …
95
+
96
+
97
+ class NPCBond(BaseModel):
98
+ """A directed NPC↔NPC bond for the frontend graph."""
99
+ source_id: str
100
+ source_name: str
101
+ target_id: str
102
+ target_name: str
103
+ value: int # current -100..100
104
+ note: str = ""
105
+
106
+
107
  class Directives(BaseModel):
108
  scene_change: SceneChange | None = None
109
  new_character: NewCharacter | None = None
 
112
  set_flags: dict[str, str] = Field(default_factory=dict)
113
  advance_beat: bool = False
114
  ending: Ending | None = None
115
+ set_music: str | None = None # one of: calm | romantic | dramatic | mystery | sad | joyful
116
+ npc_relation_deltas: list[NPCRelDelta] = Field(default_factory=list)
117
 
118
 
119
  class DirectorOutput(BaseModel):
 
187
  beat: Beat = "opening"
188
  ended: bool = False
189
  ending_text: str | None = None
190
+ ending_kind: str | None = None # "warm"|"bittersweet"|"strange"|"defeat"
191
  turn_index: int = 0
192
  notifications: list[str] = Field(default_factory=list) # popup messages this turn
193
  intro_text: str = "" # shown once in the book overlay at game start; empty on subsequent turns
194
  audio_b64: str | None = None # data:audio/wav;base64,... — absent when TTS is mocked
195
+ current_music: str | None = None # active BGM track name (calm|romantic|dramatic|mystery|sad|joyful)
196
+ npc_bonds: list[NPCBond] = Field(default_factory=list) # all directed NPC↔NPC bonds
visualnovel/state.py CHANGED
@@ -14,7 +14,7 @@ import re
14
  from pathlib import Path
15
 
16
  from . import config
17
- from .schemas import Character, DirectorOutput, GameState, Scene
18
 
19
  _CLAMP = (-100, 100)
20
 
@@ -77,6 +77,24 @@ def apply_directives(state: GameState, out: DirectorOutput) -> list[str]:
77
  state.scene.present.remove(d.exit_character)
78
  effects.append(f"exit_character:{d.exit_character}")
79
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
80
  # arbitrary world flags
81
  if d.set_flags:
82
  state.flags.update(d.set_flags)
 
14
  from pathlib import Path
15
 
16
  from . import config
17
+ from .schemas import Character, DirectorOutput, GameState, NPCRelDelta, Scene
18
 
19
  _CLAMP = (-100, 100)
20
 
 
77
  state.scene.present.remove(d.exit_character)
78
  effects.append(f"exit_character:{d.exit_character}")
79
 
80
+ # NPC↔NPC bond updates
81
+ for bond in d.npc_relation_deltas:
82
+ src, tgt = bond.source, bond.target
83
+ if src in state.characters and tgt in state.characters:
84
+ ch = state.characters[src]
85
+ old_val = ch.npc_relations.get(tgt, 0)
86
+ new_val = max(_CLAMP[0], min(_CLAMP[1], old_val + bond.delta))
87
+ ch.npc_relations[tgt] = new_val
88
+ if bond.note:
89
+ ch.npc_relation_notes[tgt] = bond.note
90
+ effects.append(f"npc_bond:{src}:{tgt}:{new_val}")
91
+
92
+ # music track switch
93
+ _VALID_TRACKS = {"calm", "romantic", "dramatic", "mystery", "sad", "joyful"}
94
+ if d.set_music and d.set_music in _VALID_TRACKS:
95
+ state.flags["current_music"] = d.set_music
96
+ effects.append(f"music:{d.set_music}")
97
+
98
  # arbitrary world flags
99
  if d.set_flags:
100
  state.flags.update(d.set_flags)