SupPepper Claude Sonnet 4.5 commited on
Commit
b4fea55
·
1 Parent(s): ba89557

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

Browse files

- 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>

.gitattributes CHANGED
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ *.mp3 filter=lfs diff=lfs merge=lfs -text
.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,77 @@
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 +273,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 +411,22 @@
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 +451,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 +491,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>
@@ -430,6 +543,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 +586,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 +634,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 +648,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 +660,142 @@ 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 +864,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");
@@ -763,17 +1032,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 +1046,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 ---
@@ -803,12 +1148,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 +1168,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
  /* ---- book intro overlay ---- */
218
  #intro-book{
219
  position:fixed; inset:0; z-index:30; display:flex; align-items:center; justify-content:center;
 
273
  border:1px solid rgba(255,255,255,.18); border-radius:10px; padding:10px 12px; font-family:var(--body)}
274
  select option{background:var(--dusk-2); color:var(--ink)}
275
  #enter{width:100%; margin-top:16px; padding:14px; font-size:1.05rem}
276
+ #start-progress{margin-top:18px; display:none; text-align:left}
277
+ .sp-step{margin-bottom:12px}
278
+ .sp-step-header{display:flex; justify-content:space-between; align-items:baseline; margin-bottom:5px}
279
+ .sp-step-label{font-size:.78rem; font-family:var(--display); color:var(--gold); letter-spacing:.04em}
280
+ .sp-step-pct{font-size:.75rem; color:var(--ink-dim)}
281
+ .sp-track{height:5px; border-radius:3px; background:rgba(255,255,255,.08); overflow:hidden}
282
+ .sp-fill{height:100%; border-radius:3px; width:0%; transition:width .55s ease}
283
+ .sp-fill.phase-llm{background:linear-gradient(90deg,#b08a4a,var(--gold))}
284
+ .sp-fill.phase-img{background:linear-gradient(90deg,#6a9cc8,#a8d4f0)}
285
+ .sp-note{font-size:.78rem; color:var(--ink-dim); font-style:italic; margin-top:4px; min-height:1.1em; transition:opacity .35s}
286
  .shimmer{color:var(--ink-dim); font-style:italic}
287
  .hidden{display:none !important}
288
  /* ---- journal button (top-right) ---- */
 
411
  .rel-score.neg{color:var(--rose)}
412
  .rel-score.zero{color:var(--ink-dim)}
413
  .rel-offstage{font-size:.7rem; color:rgba(200,190,175,.75); font-style:italic}
414
+ .rel-section-title{
415
+ font-family:var(--display); font-size:.72rem; color:var(--gold); opacity:.65;
416
+ letter-spacing:1.2px; text-transform:uppercase;
417
+ padding:14px 0 6px; border-bottom:1px solid rgba(232,193,114,.12); margin-bottom:8px;
418
+ }
419
+ .bond-graph-wrap{
420
+ padding:8px 0 8px; display:flex; justify-content:center;
421
+ }
422
+ .bond-graph-wrap svg{ width:100%; max-height:280px; display:block; overflow:visible }
423
+ .bond-list{ padding:0 4px 12px }
424
+ .bond-pair{ margin-bottom:7px; padding:5px 9px; background:rgba(255,255,255,.04); border-radius:7px }
425
+ .bond-row{ display:flex; align-items:center; gap:5px; padding:2px 0; font-size:.78rem }
426
+ .bond-name{ font-family:var(--display); min-width:56px; color:var(--ink); white-space:nowrap; overflow:hidden; text-overflow:ellipsis }
427
+ .bond-arrow{ color:var(--ink-dim); flex-shrink:0; font-size:.7rem }
428
+ .bond-note{ font-style:italic; flex:1; font-size:.73rem }
429
+ .bond-val{ font-family:var(--display); font-weight:600; min-width:30px; text-align:right; font-size:.78rem }
430
  </style>
431
  </head>
432
  <body>
 
451
  <input id="say" placeholder="say something…" autocomplete="off" />
452
  <button id="send">✓</button>
453
  <button id="mic" class="ghost" title="hold to speak">🎙️</button>
 
454
  </div>
455
  </div>
456
  </div>
457
 
458
+ <!-- Settings button — hidden until game starts -->
459
+ <button id="settings-btn" class="hidden" title="Settings">⚙️</button>
460
+
461
+ <!-- Settings overlay -->
462
+ <div id="settings-overlay">
463
+ <div id="settings-panel">
464
+ <div id="settings-header">
465
+ <h3>⚙️ Settings</h3>
466
+ <button id="settings-close">✕</button>
467
+ </div>
468
+ <div class="settings-row">
469
+ <label>🎵 Music</label>
470
+ <input type="range" id="bgm-vol-slider" min="0" max="100" value="35" />
471
+ <span class="settings-vol-val" id="bgm-vol-val">35%</span>
472
+ </div>
473
+ <div class="settings-row">
474
+ <label>🔊 Voice</label>
475
+ <input type="range" id="tts-vol-slider" min="0" max="100" value="100" />
476
+ <span class="settings-vol-val" id="tts-vol-val">100%</span>
477
+ </div>
478
+ <hr class="settings-divider" />
479
+ <button id="settings-save-btn">💾 Save current game</button>
480
+ </div>
481
+ </div>
482
+
483
  <!-- Journal button — hidden until game starts -->
484
  <button id="journal-btn" class="hidden" title="Story journal">
485
  <span class="jb-icon">📖</span>
 
491
  <div id="journal-overlay">
492
  <div id="journal-header">
493
  <h3>📖 Journal</h3>
494
+ <button id="journal-close" title="Close">✕</button>
 
 
 
 
 
495
  </div>
496
  <div id="journal-tabs">
497
  <button class="jtab active" data-tab="story">Story</button>
 
543
  <div class="field"><label>Theme</label><select id="theme"></select></div>
544
  <div class="field"><label>Tone</label><select id="tone"></select></div>
545
  <button id="enter">Enter the story</button>
546
+ <div id="start-progress">
547
+ <div class="sp-step" id="sp-step-llm">
548
+ <div class="sp-step-header">
549
+ <span class="sp-step-label">✦ Writing the story</span>
550
+ <span class="sp-step-pct" id="sp-pct-llm">0%</span>
551
+ </div>
552
+ <div class="sp-track"><div class="sp-fill phase-llm" id="sp-fill-llm"></div></div>
553
+ <div class="sp-note" id="sp-note-llm">Waiting for the AI…</div>
554
+ </div>
555
+ <div class="sp-step" id="sp-step-img" style="opacity:.35">
556
+ <div class="sp-step-header">
557
+ <span class="sp-step-label">🎨 Painting the scene</span>
558
+ <span class="sp-step-pct" id="sp-pct-img">—</span>
559
+ </div>
560
+ <div class="sp-track"><div class="sp-fill phase-img" id="sp-fill-img"></div></div>
561
+ <div class="sp-note" id="sp-note-img">Starts once the story is written</div>
562
+ </div>
563
+ </div>
564
  </div>
565
  </div>
566
 
 
586
  // --- journal ---
587
  let history = [];
588
  let journalTurn = 0;
589
+ let knownChars = []; // updated each render with known_characters from ViewState
590
+ let npcBonds = []; // updated each render with npc_bonds from ViewState
591
+ const spriteCache = {}; // id -> last known sprite_url (persists when char goes off-stage)
592
 
593
  const ACTION_ICONS = { talk:"💬", flirt:"🌸", touch:"🤝", ask:"🤔", silent:"😶", give:"🎁", move:"🚪" };
594
 
 
634
  panel.innerHTML = '<div class="je-empty">No characters met yet��</div>';
635
  return;
636
  }
637
+
638
+ // --- section 1: player↔NPC bars ---
639
  const sorted = [...knownChars].sort((a, b) => b.relationship - a.relationship);
640
+ const barsHtml = sorted.map(ch => {
641
  const rel = ch.relationship ?? 0;
642
  const posW = rel > 0 ? rel.toFixed(1) : "0";
643
  const negW = rel < 0 ? Math.abs(rel).toFixed(1) : "0";
 
648
  ? `<img src="${spriteUrl}" alt="${ch.name}" />`
649
  : `<span>👤</span>`;
650
  const isPresent = (window._presentIds || []).includes(ch.id);
 
651
  return `<div class="rel-entry">
652
  <div class="rel-avatar">${avatarHtml}</div>
653
  <div class="rel-info">
654
+ <div class="rel-name">${ch.name} <span class="rel-offstage">${isPresent ? "on stage" : "away"}</span></div>
655
  <div class="rel-mini-bar">
656
  <div class="rel-mini-neg" style="width:${negW}%"></div>
657
  <div class="rel-mini-pos" style="width:${posW}%"></div>
 
660
  <span class="rel-score ${scoreClass}">${label}</span>
661
  </div>`;
662
  }).join("");
663
+
664
+ // --- section 2: NPC↔NPC bond graph + directed list ---
665
+ let graphHtml = "";
666
+ if (knownChars.length >= 2) {
667
+ // Group bonds by unordered pair so we can show both directions together
668
+ const pairMap = {};
669
+ for (const b of npcBonds) {
670
+ const key = [b.source_id, b.target_id].sort().join("|");
671
+ if (!pairMap[key]) pairMap[key] = [];
672
+ pairMap[key].push(b);
673
+ }
674
+ const bondListHtml = Object.values(pairMap).map(pairBonds => {
675
+ const rows = pairBonds.map(b => {
676
+ const col = _bondColor(b.note, b.value);
677
+ const sign = b.value > 0 ? "+" : "";
678
+ const noteStr = b.note ? b.note : (b.value === 0 ? "neutral" : "");
679
+ return `<div class="bond-row">
680
+ <span class="bond-name">${b.source_name}</span>
681
+ <span class="bond-arrow">→</span>
682
+ <span class="bond-name">${b.target_name}</span>
683
+ <span class="bond-note" style="color:${col}">${noteStr}</span>
684
+ <span class="bond-val" style="color:${col}">${sign}${b.value}</span>
685
+ </div>`;
686
+ }).join("");
687
+ return `<div class="bond-pair">${rows}</div>`;
688
+ }).join("") || `<div class="je-empty" style="font-size:.78rem">No bonds recorded yet</div>`;
689
+
690
+ graphHtml = `<div class="rel-section-title">Between them</div>
691
+ <div class="bond-graph-wrap">${_buildBondGraph(knownChars, npcBonds)}</div>
692
+ <div class="bond-list">${bondListHtml}</div>`;
693
+ }
694
+
695
+ panel.innerHTML =
696
+ `<div class="rel-section-title">With you</div>${barsHtml}${graphHtml}`;
697
+ }
698
+
699
+ // Semantic coloring: note keywords override the numeric value
700
+ const _NEG_NOTE = /jealou|rival|resent|env[iy]|bitter|hostil|scorn|distrust|spite|hate|anger/i;
701
+ const _POS_NOTE = /fond|loyal|protect|admire|camaraderie|trust|warm|friend|love|cherish/i;
702
+ function _bondColor(note, value) {
703
+ if (note && _NEG_NOTE.test(note)) return "#c87e7e";
704
+ if (note && _POS_NOTE.test(note)) return "#7ec8a0";
705
+ return value >= 0 ? "#7ec8a0" : "#c87e7e";
706
+ }
707
+
708
+ function _buildBondGraph(chars, bonds) {
709
+ const W = 340, H = 280, cx = W / 2, cy = H / 2;
710
+ // Use a larger radius now that there's no center player node to avoid
711
+ const R = Math.min(cx, cy) - 44;
712
+
713
+ // Position NPCs in a circle
714
+ const nodes = chars.map((ch, i) => {
715
+ const angle = (2 * Math.PI * i / chars.length) - Math.PI / 2;
716
+ return {
717
+ id: ch.id, name: ch.name,
718
+ x: cx + R * Math.cos(angle),
719
+ y: cy + R * Math.sin(angle),
720
+ rel: ch.relationship ?? 0,
721
+ sprite: ch.sprite_url || spriteCache[ch.id] || null,
722
+ };
723
+ });
724
+ const nodeMap = Object.fromEntries(nodes.map(n => [n.id, n]));
725
+
726
+ // Curved NPC↔NPC bond arcs
727
+ let arcs = "";
728
+ // group bonds by pair to detect bidirectional
729
+ const pairOffset = {};
730
+ for (const b of bonds) {
731
+ const key = [b.source_id, b.target_id].sort().join("|");
732
+ pairOffset[key] = (pairOffset[key] || 0) + 1;
733
+ }
734
+ const pairUsed = {};
735
+ for (const b of bonds) {
736
+ const src = nodeMap[b.source_id], tgt = nodeMap[b.target_id];
737
+ if (!src || !tgt) continue;
738
+ const pairKey = [b.source_id, b.target_id].sort().join("|");
739
+ const side = (pairOffset[pairKey] > 1 && (pairUsed[pairKey] || 0) === 0) ? 1 : -1;
740
+ pairUsed[pairKey] = (pairUsed[pairKey] || 0) + 1;
741
+
742
+ // Perpendicular offset for the bezier control point
743
+ const dx = tgt.x - src.x, dy = tgt.y - src.y;
744
+ const len = Math.sqrt(dx * dx + dy * dy) || 1;
745
+ const curveStrength = pairOffset[pairKey] > 1 ? 36 : 18;
746
+ const cpx = (src.x + tgt.x) / 2 + (-dy / len) * curveStrength * side;
747
+ const cpy = (src.y + tgt.y) / 2 + (dx / len) * curveStrength * side;
748
+
749
+ const col = _bondColor(b.note, b.value);
750
+ const op = (0.35 + Math.abs(b.value) / 100 * 0.65).toFixed(2);
751
+ const sw = (1 + Math.abs(b.value) / 100 * 3.5).toFixed(1);
752
+
753
+ // Arrowhead at 85% along bezier curve (near target)
754
+ const markerId = `arr-${b.source_id}-${b.target_id}`.replace(/[^a-z0-9-]/gi,"_");
755
+ arcs += `<defs><marker id="${markerId}" markerWidth="5" markerHeight="5"
756
+ refX="4" refY="2.5" orient="auto">
757
+ <polygon points="0,0 5,2.5 0,5" fill="${col}" fill-opacity="${op}"/>
758
+ </marker></defs>
759
+ <path d="M${src.x},${src.y} Q${cpx},${cpy} ${tgt.x},${tgt.y}"
760
+ fill="none" stroke="${col}" stroke-width="${sw}" stroke-opacity="${op}"
761
+ stroke-linecap="round" marker-end="url(#${markerId})"/>`;
762
+
763
+ if (b.note) {
764
+ // Label at midpoint of bezier — use paint-order stroke for legible outline
765
+ const lx = 0.25 * src.x + 0.5 * cpx + 0.25 * tgt.x;
766
+ const ly = 0.25 * src.y + 0.5 * cpy + 0.25 * tgt.y;
767
+ arcs += `<text x="${lx}" y="${ly - 3}" text-anchor="middle"
768
+ font-size="9" fill="${col}"
769
+ paint-order="stroke" stroke="rgba(10,8,18,.85)" stroke-width="3" stroke-linejoin="round"
770
+ font-family="Georgia,serif" font-style="italic">${b.note}</text>`;
771
+ }
772
+ }
773
+
774
+ // NPC circle nodes (sprite or emoji) + name coloured by player relation
775
+ let nodesSvg = "";
776
+ for (const n of nodes) {
777
+ const clipId = `cl_${n.id}`.replace(/[^a-z0-9_]/gi,"_");
778
+ // Border colour by relation to player
779
+ const borderCol = n.rel > 20 ? "#7ec8a0" : n.rel < -20 ? "#c87e7e" : "rgba(232,193,114,.55)";
780
+ const nameCol = n.rel > 20 ? "#9ddcba" : n.rel < -20 ? "#dba0a0" : "rgba(232,193,114,.92)";
781
+ nodesSvg += `<circle cx="${n.x}" cy="${n.y}" r="22"
782
+ fill="rgba(255,255,255,.05)" stroke="${borderCol}" stroke-width="1.8"/>`;
783
+ if (n.sprite) {
784
+ nodesSvg += `<clipPath id="${clipId}"><circle cx="${n.x}" cy="${n.y}" r="20"/></clipPath>
785
+ <image href="${n.sprite}" x="${n.x-20}" y="${n.y-20}" width="40" height="40"
786
+ clip-path="url(#${clipId})" preserveAspectRatio="xMidYMid slice"/>`;
787
+ } else {
788
+ nodesSvg += `<text x="${n.x}" y="${n.y+5}" text-anchor="middle" font-size="16">👤</text>`;
789
+ }
790
+ // Name label with dark stroke outline for readability
791
+ nodesSvg += `<text x="${n.x}" y="${n.y+38}" text-anchor="middle"
792
+ font-size="10.5" fill="${nameCol}" font-family="Georgia,serif"
793
+ paint-order="stroke" stroke="rgba(10,8,18,.9)" stroke-width="3.5" stroke-linejoin="round">${n.name}</text>`;
794
+ }
795
+
796
+ return `<svg viewBox="0 0 ${W} ${H}" xmlns="http://www.w3.org/2000/svg">
797
+ ${arcs}${nodesSvg}
798
+ </svg>`;
799
  }
800
 
801
  // keep track of who's currently on stage for the relations panel
 
864
  function render(v){
865
  if (v.known_characters?.length) {
866
  knownChars = v.known_characters;
 
867
  for (const ch of knownChars) {
868
  if (ch.sprite_url) spriteCache[ch.id] = ch.sprite_url;
869
  }
870
  }
871
+ if (v.npc_bonds !== undefined) npcBonds = v.npc_bonds || [];
872
  $("place").textContent = v.place || "";
873
  $("speaker").textContent = v.speaker || "";
874
  typeOut($("line"), v.dialogue || "");
875
  playTTS(v.audio_b64);
876
+ if (v.current_music) switchMusic(v.current_music);
877
  if (v.backdrop_url && v.backdrop_url !== lastBg){
878
  const bg = $("backdrop");
879
  bg.classList.remove("on");
 
1032
  document.querySelectorAll(".target-chip").forEach(b => b.disabled = state);
1033
  }
1034
 
1035
+ // --- TTS toggle + volume ---
1036
+ let ttsVol = 1.0; // 0–1, controlled by settings slider
1037
  let ttsEnabled = true;
1038
+ // ttsBtn removed from DOM — state managed solely via settings sliders
1039
+ const ttsBtn = { textContent: "", classList: { add:()=>{}, toggle:()=>{}, remove:()=>{} } };
 
 
 
 
 
 
 
1040
 
1041
  function playTTS(audio_b64) {
1042
  if (!ttsEnabled || !audio_b64) return;
 
1046
  audio.id = "vn-audio";
1047
  document.body.appendChild(audio);
1048
  }
1049
+ audio.volume = ttsVol;
1050
  audio.src = audio_b64;
1051
+ audio.play().catch(() => {});
1052
+ }
1053
+
1054
+ // --- BGM (background music) ---
1055
+ const BGM_TRACKS = {
1056
+ calm: "/music/calm.mp3",
1057
+ romantic: "/music/romantic.mp3",
1058
+ dramatic: "/music/dramatic.mp3",
1059
+ mystery: "/music/mystery.mp3",
1060
+ sad: "/music/sad.mp3",
1061
+ joyful: "/music/joyful.mp3",
1062
+ };
1063
+ let bgmMasterVolume = 0.35; // master volume (0–1) — controlled by settings slider
1064
+ const BGM_FADE_OUT_MS = 2800; // old track fades out over this long
1065
+ const BGM_FADE_IN_MS = 3200; // new track fades in over this long
1066
+ const BGM_OVERLAP_MS = 1200; // new track starts this many ms before old finishes
1067
+
1068
+ let bgmEnabled = true;
1069
+ let bgmCurrent = null; // currently playing Audio object
1070
+ let bgmTrackName = null; // track key of bgmCurrent
1071
+
1072
+ // bgmBtn removed from DOM — state managed solely via settings sliders
1073
+ const bgmBtn = { textContent: "", classList: { add:()=>{}, toggle:()=>{}, remove:()=>{} } };
1074
+
1075
+ function switchMusic(name) {
1076
+ if (!name || !BGM_TRACKS[name]) return;
1077
+ if (name === bgmTrackName) return;
1078
+ if (!bgmEnabled) { bgmTrackName = name; return; }
1079
+ _bgmPlay(name);
1080
+ }
1081
+
1082
+ function _bgmPlay(name) {
1083
+ const old = bgmCurrent;
1084
+ bgmTrackName = name;
1085
+
1086
+ const a = new Audio(BGM_TRACKS[name]);
1087
+ a.loop = true;
1088
+ a.volume = 0;
1089
+ bgmCurrent = a;
1090
+
1091
+ // Helper: actually start the audio and fade it in
1092
+ const startFadeIn = () => {
1093
+ const p = a.play();
1094
+ if (p !== undefined) {
1095
+ p.catch(() => {
1096
+ // Autoplay still blocked — retry on the very next user interaction
1097
+ const retry = () => {
1098
+ if (bgmCurrent === a && bgmEnabled) {
1099
+ a.play().then(() => _bgmFade(a, 0, bgmMasterVolume, BGM_FADE_IN_MS)).catch(() => {});
1100
+ }
1101
+ };
1102
+ document.addEventListener("click", retry, { once: true });
1103
+ document.addEventListener("keydown", retry, { once: true });
1104
+ });
1105
+ }
1106
+ _bgmFade(a, 0, bgmMasterVolume, BGM_FADE_IN_MS);
1107
+ };
1108
+
1109
+ if (old) {
1110
+ _bgmFade(old, old.volume, 0, BGM_FADE_OUT_MS, () => { old.pause(); old.src = ""; });
1111
+ setTimeout(startFadeIn, BGM_FADE_OUT_MS - BGM_OVERLAP_MS);
1112
+ } else {
1113
+ startFadeIn();
1114
+ }
1115
+ }
1116
+
1117
+ // Smooth volume ramp using requestAnimationFrame + ease-in-out curve
1118
+ function _bgmFade(audio, fromVol, toVol, ms, onDone) {
1119
+ const start = performance.now();
1120
+ function tick(now) {
1121
+ const raw = Math.min(1, (now - start) / ms);
1122
+ // ease-in-out: smoothstep
1123
+ const t = raw * raw * (3 - 2 * raw);
1124
+ audio.volume = fromVol + (toVol - fromVol) * t;
1125
+ if (raw < 1) {
1126
+ requestAnimationFrame(tick);
1127
+ } else {
1128
+ audio.volume = toVol;
1129
+ if (onDone) onDone();
1130
+ }
1131
+ }
1132
+ requestAnimationFrame(tick);
1133
  }
1134
 
1135
  // --- book overlay dismiss ---
 
1148
  const file = e.target.files[0];
1149
  if (!file) return;
1150
  const text = await file.text();
1151
+
1152
+ // Start a neutral track NOW (user gesture from the file picker is still active)
1153
+ if (bgmEnabled) switchMusic("calm");
1154
+
1155
  busy(true);
1156
  try {
1157
  // Extract client-side journal history before sending state to server
1158
  let parsed;
1159
  try { parsed = JSON.parse(text); } catch { parsed = {}; }
1160
  const savedHistory = Array.isArray(parsed.journal_history) ? parsed.journal_history : [];
1161
+ const savedAudio = parsed.audio_settings || null;
1162
 
1163
  const { data } = await client.predict("/load_file", { data: text });
1164
  $("choice-screen").classList.add("hidden");
 
1168
  history = savedHistory;
1169
  journalTurn = savedHistory.length > 0 ? savedHistory[savedHistory.length - 1].turn : 0;
1170
 
1171
+ // Restore audio settings if present
1172
+ if (savedAudio) {
1173
+ const bgmPct = Math.max(0, Math.min(100, savedAudio.bgm_vol ?? 35));
1174
+ const ttsPct = Math.max(0, Math.min(100, savedAudio.tts_vol ?? 100));
1175
+ bgmMasterVolume = bgmPct / 100;
1176
+ ttsVol = ttsPct / 100;
1177
+ bgmEnabled = bgmPct > 0;
1178
+ ttsEnabled = ttsPct > 0;
1179
+ bgmVolSlider.value = bgmPct;
1180
+ bgmVolVal.textContent = bgmPct + "%";
1181
+ ttsVolSlider.value = ttsPct;
1182
+ ttsVolVal.textContent = ttsPct + "%";
1183
+ if (bgmCurrent) bgmCurrent.volume = bgmMasterVolume;
1184
+ // If there's an explicit saved track and music is enabled, pre-seed the track name
1185
+ // so render()'s switchMusic call (via current_music in ViewState) resumes it.
1186
+ if (savedAudio.bgm_track && bgmEnabled) bgmTrackName = null; // force switchMusic to not skip
1187
+ }
1188
+
1189
+ render(data[0]); // will call switchMusic with current_music from saved GameState flags
1190
+ // Fallback: if ViewState had no current_music but we saved a track, start it now
1191
+ if (savedAudio?.bgm_track && bgmEnabled && !bgmTrackName) {
1192
+ switchMusic(savedAudio.bgm_track);
1193
+ }
1194
  $("journal-btn").classList.remove("hidden");
1195
+ $("settings-btn").classList.remove("hidden");
1196
  } catch(err) { alert("Could not load save: " + (err?.message || err)); }
1197
  busy(false);
1198
  });
1199
 
1200
+ // --- settings panel ---
1201
+ $("settings-btn").addEventListener("click", () => $("settings-overlay").classList.add("open"));
1202
+ $("settings-close").addEventListener("click", () => $("settings-overlay").classList.remove("open"));
1203
+ $("settings-overlay").addEventListener("click", e => {
1204
+ if (e.target === $("settings-overlay")) $("settings-overlay").classList.remove("open");
1205
+ });
1206
+
1207
+ // --- BGM volume slider ---
1208
+ // Moving slider: adjusts master volume live; going to 0 mutes, above 0 unmutes.
1209
+ const bgmVolSlider = $("bgm-vol-slider");
1210
+ const bgmVolVal = $("bgm-vol-val");
1211
+ bgmVolSlider.addEventListener("input", () => {
1212
+ const pct = parseInt(bgmVolSlider.value, 10);
1213
+ bgmVolVal.textContent = pct + "%";
1214
+ bgmMasterVolume = pct / 100;
1215
+ if (pct === 0) {
1216
+ if (bgmEnabled) { // mute: fade out & disable
1217
+ bgmEnabled = false;
1218
+ if (bgmCurrent) {
1219
+ _bgmFade(bgmCurrent, bgmCurrent.volume, 0, 500, () => { bgmCurrent.pause(); bgmCurrent.src = ""; });
1220
+ bgmCurrent = null;
1221
+ }
1222
+ }
1223
+ } else {
1224
+ if (!bgmEnabled) { // unmute: re-enable and restart remembered track
1225
+ bgmEnabled = true;
1226
+ if (bgmTrackName) _bgmPlay(bgmTrackName);
1227
+ } else if (bgmCurrent) { // just change live volume
1228
+ bgmCurrent.volume = bgmMasterVolume;
1229
+ }
1230
+ }
1231
+ bgmBtn.classList.toggle("active", bgmEnabled);
1232
+ bgmBtn.textContent = bgmEnabled ? "🎵" : "🔇";
1233
+ });
1234
+
1235
+ // --- TTS volume slider ---
1236
+ const ttsVolSlider = $("tts-vol-slider");
1237
+ const ttsVolVal = $("tts-vol-val");
1238
+ ttsVolSlider.addEventListener("input", () => {
1239
+ const pct = parseInt(ttsVolSlider.value, 10);
1240
+ ttsVolVal.textContent = pct + "%";
1241
+ ttsVol = pct / 100;
1242
+ ttsEnabled = pct > 0;
1243
+ const a = $("vn-audio"); if (a) a.volume = ttsVol;
1244
+ ttsBtn.classList.toggle("active", ttsEnabled);
1245
+ ttsBtn.textContent = ttsEnabled ? "🔊" : "🔇";
1246
+ });
1247
+
1248
+ // Save button
1249
+ $("settings-save-btn").addEventListener("click", async () => {
1250
+ const btn = $("settings-save-btn");
1251
+ btn.disabled = true;
1252
+ btn.textContent = "Saving…";
1253
  try {
1254
  const { data } = await client.predict("/save_data", {});
 
1255
  const saveObj = JSON.parse(data[0].json);
1256
  saveObj.journal_history = history;
1257
+ saveObj.audio_settings = {
1258
+ bgm_vol: Math.round(bgmMasterVolume * 100),
1259
+ tts_vol: Math.round(ttsVol * 100),
1260
+ bgm_track: bgmTrackName || null,
1261
+ };
1262
  const blob = new Blob([JSON.stringify(saveObj)], { type: "application/json" });
1263
  const a = document.createElement("a");
1264
  a.href = URL.createObjectURL(blob);
1265
  a.download = "ephemeral-hearts-save.json";
1266
  a.click();
1267
  URL.revokeObjectURL(a.href);
1268
+ btn.textContent = " Saved!";
1269
+ setTimeout(() => { btn.textContent = "💾 Save current game"; btn.disabled = false; }, 2000);
1270
+ } catch(err) {
1271
+ console.error("save failed", err);
1272
+ btn.textContent = "⚠️ Failed";
1273
+ setTimeout(() => { btn.textContent = "💾 Save current game"; btn.disabled = false; }, 2000);
1274
+ }
1275
  });
1276
 
1277
+ // tone -> initial BGM track (mirrors engine.py start() logic)
1278
+ const TONE_MUSIC = { romantic:"romantic", flirty:"romantic", dramatic:"dramatic", bittersweet:"sad", comedic:"joyful" };
1279
+
1280
  // --- start ---
1281
  $("enter").addEventListener("click", async () => {
1282
  const btn = $("enter");
1283
  btn.disabled = true;
1284
  const orig = btn.textContent;
1285
  btn.textContent = "✨ Creating your story…";
1286
+
1287
+ // Kick off music NOW while the user gesture is still fresh.
1288
+ if (bgmEnabled) switchMusic(TONE_MUSIC[$("tone").value] || "calm");
1289
+
1290
+ // --- two-phase segmented progress ---
1291
+ const spEl = $("start-progress");
1292
+ spEl.style.display = "block";
1293
+
1294
+ // Per-phase helpers
1295
+ let _spTick = null;
1296
+ const _spNote = (id, msg) => {
1297
+ const el = $(id);
1298
+ el.style.opacity = "0";
1299
+ setTimeout(() => { el.textContent = msg; el.style.opacity = "1"; }, 200);
1300
+ };
1301
+ // Animate fill toward `target` (0-100) at `stepMs` per tick; resolves when target hit
1302
+ const _spCrawl = (fillId, pctId, target, stepMs) => new Promise(resolve => {
1303
+ if (_spTick) { clearInterval(_spTick); _spTick = null; }
1304
+ const fill = $(fillId), pctEl = $(pctId);
1305
+ let cur = parseFloat(fill.style.width) || 0;
1306
+ _spTick = setInterval(() => {
1307
+ cur = Math.min(target, cur + 0.7);
1308
+ fill.style.width = cur + "%";
1309
+ pctEl.textContent = Math.round(cur) + "%";
1310
+ if (cur >= target) { clearInterval(_spTick); _spTick = null; resolve(); }
1311
+ }, stepMs);
1312
+ });
1313
+ const _spFinish = (fillId, pctId, label) => {
1314
+ if (_spTick) { clearInterval(_spTick); _spTick = null; }
1315
+ $(fillId).style.width = "100%";
1316
+ $(pctId).textContent = label || "100%";
1317
+ };
1318
+ const spHide = () => {
1319
+ spEl.style.display = "none";
1320
+ ["sp-fill-llm","sp-fill-img"].forEach(id => { $(id).style.width = "0%"; });
1321
+ };
1322
+
1323
+ // LLM notes cycling (reassuring messages while waiting for the model)
1324
+ const LLM_NOTES = [
1325
+ "The AI is generating your opening scene…",
1326
+ "First load can take 30–60 s while the model warms up…",
1327
+ "Inventing characters, secrets, and a first line just for you…",
1328
+ "Almost done writing — hang on…",
1329
+ ];
1330
+ let _llmNoteIdx = 0;
1331
+ const _llmNoteTick = setInterval(() => {
1332
+ _llmNoteIdx = (_llmNoteIdx + 1) % LLM_NOTES.length;
1333
+ _spNote("sp-note-llm", LLM_NOTES[_llmNoteIdx]);
1334
+ }, 9000);
1335
+
1336
  try {
1337
+ // ── Phase 1 : LLM world init ──────────────────────────────────────────
1338
+ _spNote("sp-note-llm", LLM_NOTES[0]);
1339
+ // Crawl 0→88% slowly — will stop there until the real call returns
1340
+ _spCrawl("sp-fill-llm", "sp-pct-llm", 88, 800);
1341
+
1342
+ const { data: d1 } = await client.predict("/start_text", {
1343
+ theme: $("theme").value,
1344
+ tone: $("tone").value,
1345
+ });
1346
+
1347
+ // LLM done — complete bar 1, unlock bar 2 (stay on setup screen)
1348
+ clearInterval(_llmNoteTick);
1349
+ _spFinish("sp-fill-llm", "sp-pct-llm", "100%");
1350
+ _spNote("sp-note-llm", "Story written ✓");
1351
+ $("sp-step-img").style.opacity = "1";
1352
+ _spNote("sp-note-img", "Generating backdrop and character illustration…");
1353
+ $("sp-pct-img").textContent = "0%";
1354
+
1355
+ // ── Phase 2 : image generation ────────────────────────────────────────
1356
+ // Crawl 0→85% while painter works
1357
+ _spCrawl("sp-fill-img", "sp-pct-img", 85, 350);
1358
+
1359
+ const { data: d2 } = await client.predict("/start_images", {});
1360
+
1361
+ // Everything ready — complete bar 2, then reveal the game
1362
+ _spFinish("sp-fill-img", "sp-pct-img", "100%");
1363
+ _spNote("sp-note-img", "Scene ready ✓");
1364
+ render(d2[0]);
1365
+ addToHistory("", d2[0]);
1366
  $("setup").classList.add("hidden");
 
 
1367
  $("journal-btn").classList.remove("hidden");
1368
+ $("settings-btn").classList.remove("hidden");
1369
+
1370
+ setTimeout(() => {
1371
+ spHide();
1372
+ if (d2[0]?.intro_text) {
1373
+ $("book-text").textContent = d2[0].intro_text;
1374
+ $("intro-book").classList.remove("hidden");
1375
+ }
1376
+ }, 700);
1377
+
1378
  } catch(err) {
1379
  console.error("start failed", err);
1380
+ clearInterval(_llmNoteTick);
1381
+ if (_spTick) { clearInterval(_spTick); _spTick = null; }
1382
+ spHide();
1383
  btn.textContent = "⚠️ Failed — try again";
1384
  btn.disabled = false;
1385
  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)
@@ -195,6 +245,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
 
@@ -222,6 +285,8 @@ class Engine:
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)
 
245
  )
246
  )
247
 
248
+ # Collect all directed NPC↔NPC bonds for the frontend graph
249
+ npc_bonds: list[NPCBond] = []
250
+ for cid, ch in s.characters.items():
251
+ for other_id, val in ch.npc_relations.items():
252
+ if other_id in s.characters:
253
+ other = s.characters[other_id]
254
+ npc_bonds.append(NPCBond(
255
+ source_id=cid, source_name=ch.name,
256
+ target_id=other_id, target_name=other.name,
257
+ value=val,
258
+ note=ch.npc_relation_notes.get(other_id, ""),
259
+ ))
260
+
261
  speaker_ch = s.characters.get(out.speaker)
262
  speaker_name = speaker_ch.name if speaker_ch else "The wood"
263
 
 
285
  notifications=notifications or [],
286
  intro_text=intro_text,
287
  audio_b64=audio_b64,
288
+ current_music=s.flags.get("current_music"),
289
+ npc_bonds=npc_bonds,
290
  )
291
 
292
 
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,17 @@ 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
+ # Surface the current music track prominently so the LLM doesn't switch it needlessly.
38
+ current_music = state.flags.get("current_music")
39
+ if current_music:
40
+ parts.append(
41
+ f"CURRENT BGM: \"{current_music}\" — leave set_music null unless a MAJOR tonal "
42
+ f"shift justifies a change (max once every 6-8 turns)."
43
+ )
44
+
45
+ other_flags = {k: v for k, v in state.flags.items() if k != "current_music"}
46
+ if other_flags:
47
+ parts.append("FACTS: " + ", ".join(f"{k}={v}" for k, v in other_flags.items()))
48
 
49
  recent = state.recent_turns[-config.RECENT_TURNS_K :]
50
  if recent:
visualnovel/prompts.py CHANGED
@@ -43,11 +43,22 @@ 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 +66,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 +129,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 -> 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
+ - NPCs have their own bonds with each other (shown in "bonds with others" on each sheet).
52
+ These bonds drive their behaviour: rivals bicker and compete for the player's attention;
53
+ friends cover for each other and share knowing glances; a jealous NPC makes cutting
54
+ remarks when another gets too close to the player.
55
+ Update bonds via npc_relation_deltas when a meaningful interaction shifts the dynamic —
56
+ e.g. player flirts with A while B watches (B gains jealousy toward A: delta -10 to -20);
57
+ two NPCs have a warm exchange (delta +10 to +20, note "camaraderie");
58
+ an NPC defends another from the player's rudeness (delta +15, note "protects").
59
+ Keep notes short (one word or phrase): "jealousy", "rivalry", "camaraderie",
60
+ "fondness", "protects", "admires", "resents", "envies", "loyal to".
61
+ Only update bonds when something actually happens — not every turn.
62
  - With multiple characters on stage, they may react to each other (banter, jealousy, a
63
  knowing glance) — but never more than 2 NPC-to-NPC exchanges in a row. After that the
64
  next line MUST address the player directly.
 
66
  established fact.
67
  - NEVER repeat a line of dialogue verbatim from the recent exchanges. Every response must
68
  move the scene forward — emotionally, narratively, or tonally.
69
+ - Music: think of it like a film score — one track covers an entire scene or arc.
70
+ Use set_music ONLY for major tonal ruptures (a sudden revelation, a scene that flips
71
+ from lighthearted to tense, a heartbreak, a triumphant moment). As a rule:
72
+ never switch more than once every 6-8 turns, never two switches in a row,
73
+ and NEVER switch just because the dialogue shifted slightly in mood.
74
+ Leave set_music as null on the vast majority of turns.
75
+ Available tracks (use the exact key string):
76
+ "calm" — peaceful ambiance, everyday moments, unhurried exploration
77
+ "romantic" — soft and intimate, growing closeness, tender confessions
78
+ "dramatic" — tense confrontations, high stakes, arguments, shock, revelations
79
+ "mystery" — uncanny atmosphere, secrets surfacing, strange occurrences
80
+ "sad" — melancholy, loss, a bittersweet farewell
81
+ "joyful" — playful, comedic, carefree, warm laughter
82
  - Output MUST be a single JSON object matching the schema. Nothing else.
83
  """
84
 
 
129
  "touch": (
130
  "*The wanderer gently touches the character. "
131
  "Check their current relationship value in the character sheet: "
132
+ "below 20 -> touch is UNWANTED, they pull back or react with discomfort/anger "
133
  "(negative relationship_delta); "
134
+ "20-50 -> shy or surprised mixed reaction (small delta either way); "
135
+ "above 50 -> welcomed warmly or with flustering (positive relationship_delta).*"
136
  ),
137
  "give": (
138
  "*The wanderer offers something to the character — "
visualnovel/schemas.py CHANGED
@@ -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):
@@ -168,3 +191,5 @@ class ViewState(BaseModel):
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
 
 
 
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):
 
191
  notifications: list[str] = Field(default_factory=list) # popup messages this turn
192
  intro_text: str = "" # shown once in the book overlay at game start; empty on subsequent turns
193
  audio_b64: str | None = None # data:audio/wav;base64,... — absent when TTS is mocked
194
+ current_music: str | None = None # active BGM track name (calm|romantic|dramatic|mystery|sad|joyful)
195
+ 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)