Преглед изворни кода

feat: 核心循环 + 里世界 + UI 首版(state/rift/ui/march/icons/events + 样式与入口页)

LiuYuYang пре 1 недеља
родитељ
комит
6544ce74b1
11 измењених фајлова са 2963 додато и 268 уклоњено
  1. 454 0
      css/style.css
  2. 92 0
      index.html
  3. 194 168
      js/config.js
  4. 79 0
      js/events-data.js
  5. 156 100
      js/formulas.js
  6. 45 0
      js/icons.js
  7. 56 0
      js/main.js
  8. 255 0
      js/march.js
  9. 254 0
      js/rift.js
  10. 453 0
      js/state.js
  11. 925 0
      js/ui.js

+ 454 - 0
css/style.css

@@ -0,0 +1,454 @@
+/* 《世界树 · 逃离空洞》—— 白 + 深墨蓝 + 建筑蓝灰 + 生命绿/金;线条图解风,无 3D 发光花哨
+   署名:FmodeCode */
+:root {
+  --ink: #121a2b;          /* 深墨蓝 */
+  --ink-2: #1c2740;
+  --ink-3: #2a3855;
+  --paper: #f4f5f2;        /* 白(带一点暖灰) */
+  --paper-2: #ffffff;
+  --line: #d9dee6;         /* 线条 */
+  --line-strong: #b7c0cd;
+  --muted: #6f7b8e;        /* 蓝灰 */
+  --muted-2: #98a3b3;
+  --life: #2fae6b;         /* 生命绿 */
+  --life-soft: #e6f5ec;
+  --gold: #b08427;         /* 金 */
+  --gold-soft: #f7efdc;
+  --brand: #4a6cf7;        /* fmode 蓝 */
+  --brand-2: #6c5ce7;
+  --danger: #c0492e;
+  --crisis: #b0741f;
+  --sky: #5fa8d3;
+  --radius: 10px;
+  --shadow: 0 1px 0 rgba(18, 26, 43, .04), 0 6px 18px rgba(18, 26, 43, .06);
+  --font: "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", "Noto Sans CJK SC", system-ui, -apple-system, "Segoe UI", sans-serif;
+  --mono: "SF Mono", "JetBrains Mono", Menlo, Consolas, monospace;
+}
+
+* { box-sizing: border-box; }
+html, body { height: 100%; }
+body {
+  margin: 0; font-family: var(--font); color: var(--ink); background: var(--paper);
+  -webkit-font-smoothing: antialiased; -webkit-tap-highlight-color: transparent;
+  overflow: hidden;
+}
+button { font-family: inherit; cursor: pointer; }
+button:disabled { cursor: not-allowed; opacity: .45; }
+
+/* ── 布局:PC 三栏 / 手机单栏 + 底部页签 ── */
+#app { display: grid; grid-template-rows: 52px 1fr; height: 100vh; height: 100dvh; }
+.topbar {
+  display: flex; align-items: center; gap: 14px; padding: 0 16px;
+  background: var(--ink); color: #eef1f6; border-bottom: 1px solid #000;
+}
+.brand { display: flex; align-items: center; gap: 9px; font-weight: 700; letter-spacing: .06em; font-size: 15px; white-space: nowrap; }
+.brand svg { width: 22px; height: 22px; }
+.brand small { font-weight: 500; opacity: .55; letter-spacing: .12em; font-size: 11px; margin-left: 2px; }
+.viewport-toggle { display: flex; gap: 4px; align-items: center; margin-left: 6px; }
+.topstats { margin-left: auto; }
+.top-save { border: 1px solid rgba(255,255,255,.2); background: transparent; color: #dfe5ee; border-radius: 7px; padding: 5px 10px; font-size: 12px; white-space: nowrap; }
+.top-save:hover { background: rgba(255,255,255,.1); }
+.vp-btn {
+  border: 1px solid rgba(255,255,255,.18); background: transparent; color: #cfd6e2;
+  font-size: 11px; padding: 4px 8px; border-radius: 6px; cursor: pointer;
+}
+.vp-btn.on { background: rgba(255,255,255,.12); color: #fff; }
+.topstats { display: flex; gap: 18px; align-items: center; overflow: hidden; }
+.tstat { display: flex; flex-direction: column; line-height: 1.15; min-width: 0; }
+.tstat .k { font-size: 10px; color: #8e9bb0; letter-spacing: .1em; }
+.tstat .v { font-size: 14px; font-weight: 650; font-variant-numeric: tabular-nums; white-space: nowrap; }
+.topbar .icon-btn { border: 1px solid rgba(255,255,255,.16); background: transparent; color: #dfe5ee; border-radius: 7px; width: 30px; height: 30px; display: grid; place-items: center; }
+
+.main { display: grid; grid-template-columns: 304px minmax(0, 1fr) 330px; gap: 14px; padding: 14px; min-height: 0; overflow: hidden; }
+.col { display: flex; flex-direction: column; gap: 12px; min-height: 0; overflow-y: auto; scrollbar-width: thin; padding-bottom: 8px; }
+.col > * { flex-shrink: 0; }
+.col.center { overflow: hidden; }
+.panel {
+  background: var(--paper-2); border: 1px solid var(--line); border-radius: var(--radius);
+  box-shadow: var(--shadow); padding: 13px 14px; position: relative;
+}
+.panel.flat { box-shadow: none; background: transparent; border-style: dashed; }
+.panel-title { display: flex; align-items: center; gap: 8px; font-size: 11px; font-weight: 700; letter-spacing: .14em; color: var(--muted); margin: 0 0 10px; text-transform: uppercase; }
+.panel-title .tag { margin-left: auto; font-weight: 500; letter-spacing: 0; text-transform: none; color: var(--muted-2); font-size: 11px; }
+.panel-title::before { content: ""; width: 3px; height: 12px; border-radius: 2px; background: var(--ink); }
+.panel.life .panel-title::before { background: var(--life); }
+.panel.gold .panel-title::before { background: var(--gold); }
+.panel.brand .panel-title::before { background: var(--brand); }
+
+/* ── 数字 ── */
+.num { font-variant-numeric: tabular-nums; font-feature-settings: "tnum"; }
+.big-num { font-size: 30px; font-weight: 700; letter-spacing: -.02em; line-height: 1.1; }
+.big-num small { font-size: 13px; font-weight: 600; color: var(--muted); margin-left: 4px; letter-spacing: 0; }
+.sub-line { font-size: 12px; color: var(--muted); margin-top: 4px; display: flex; flex-wrap: wrap; gap: 4px 10px; }
+.sub-line b { color: var(--ink-3); font-weight: 600; }
+.flash-up { animation: flashUp .6s ease-out; }
+@keyframes flashUp { 0% { color: var(--life); } 100% { color: inherit; } }
+
+/* ── 顶部资源条 ── */
+.res-row { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; }
+.res { border: 1px solid var(--line); border-radius: 9px; padding: 9px 11px; background: linear-gradient(180deg, #fff, #fbfbf9); }
+.res .k { font-size: 11px; color: var(--muted); letter-spacing: .08em; display: flex; align-items: center; gap: 5px; }
+.res .k .dot { width: 6px; height: 6px; border-radius: 50%; background: var(--life); }
+.res .k .dot.gold { background: var(--gold); }
+.res .v { font-size: 20px; font-weight: 700; margin-top: 3px; }
+.res .d { font-size: 11px; color: var(--muted-2); margin-top: 1px; }
+
+/* ── 主线章节 ── */
+.chapter { margin-bottom: 10px; }
+.chapter .ch-title { font-size: 16px; font-weight: 700; display: flex; align-items: baseline; gap: 8px; }
+.chapter .ch-title .idx { font-size: 11px; color: var(--muted); letter-spacing: .1em; font-weight: 600; }
+.chapter .ch-desc { font-size: 12px; color: var(--muted); margin-top: 3px; line-height: 1.55; }
+.esc-track { margin-top: 10px; display: grid; grid-template-columns: 1fr auto; gap: 6px 10px; align-items: center; font-size: 11px; color: var(--muted); }
+.esc-bar { grid-column: 1 / -1; height: 22px; border-radius: 5px; background: #eceff3; border: 1px solid var(--line); position: relative; overflow: hidden; }
+.esc-bar .fill { position: absolute; inset: 0 auto 0 0; background: linear-gradient(90deg, #c9e9d5, var(--life)); transition: width .4s ease; }
+.esc-bar .fill::after { content: ""; position: absolute; right: -1px; top: 0; bottom: 0; width: 2px; background: #1c7a48; }
+.esc-bar .mark { position: absolute; top: 0; bottom: 0; width: 1px; background: var(--line-strong); }
+.esc-bar .mark span { position: absolute; top: 3px; left: 3px; font-size: 9px; color: var(--ink-3); white-space: nowrap; opacity: .8; }
+.esc-bar .mark.done { background: #1c7a48; }
+
+/* ── Marches(连续行军)画布 ── */
+.canvas-wrap {
+  position: relative; border: 1px solid var(--line); border-radius: var(--radius); overflow: hidden;
+  background: var(--paper-2); box-shadow: var(--shadow); flex: 1 1 auto; min-height: 220px;
+}
+#march { width: 100%; height: 100%; display: block; }
+.hud { position: absolute; left: 12px; top: 11px; display: flex; gap: 14px; align-items: flex-start; pointer-events: none; }
+.hud .layer { font-size: 24px; font-weight: 750; letter-spacing: -.02em; line-height: 1; }
+.hud .layer small { font-size: 11px; color: var(--muted); font-weight: 600; margin-left: 3px; letter-spacing: .04em; }
+.hud .meta { font-size: 11px; color: var(--muted); line-height: 1.5; padding-top: 6px; }
+.hud .meta b { color: var(--ink-3); }
+.hud-r { position: absolute; right: 12px; top: 11px; font-size: 11px; color: var(--muted); text-align: right; line-height: 1.5; pointer-events: none; }
+.hud-r b { color: var(--ink); font-size: 13px; }
+.badge-magic { position: absolute; right: 12px; bottom: 12px; background: #f4ecff; border: 1px solid #e1d3f7; color: #6b3fa0; font-size: 11px; padding: 4px 8px; border-radius: 7px; }
+.frozen-veil { position: absolute; inset: 0; background: repeating-linear-gradient(135deg, rgba(18,26,43,.025) 0 10px, rgba(18,26,43,.05) 10px 11px); display: none; }
+.frozen .frozen-veil { display: block; }
+.skip-float { position: absolute; font-size: 12px; font-weight: 700; color: var(--gold); pointer-events: none; text-shadow: 0 1px 0 #fff; animation: floatUp 1.1s ease-out forwards; }
+@keyframes floatUp { 0% { opacity: 0; transform: translateY(6px); } 15% { opacity: 1; } 100% { opacity: 0; transform: translateY(-26px); } }
+
+/* ── 操作条 ── */
+.actions { display: grid; grid-template-columns: repeat(4, 1fr); gap: 8px; }
+.act {
+  border: 1px solid var(--line); background: var(--paper-2); border-radius: 9px; padding: 9px 10px;
+  text-align: left; display: flex; flex-direction: column; gap: 2px; transition: border-color .15s, transform .1s, background .15s;
+}
+.act:hover:not(:disabled) { border-color: var(--ink-3); }
+.act:active:not(:disabled) { transform: translateY(1px); }
+.act .t { font-size: 13px; font-weight: 650; display: flex; align-items: center; gap: 6px; }
+.act .s { font-size: 11px; color: var(--muted); }
+.act.primary { background: var(--ink); border-color: var(--ink); color: #fff; }
+.act.primary .s { color: #a9b6c9; }
+.act.primary:hover:not(:disabled) { background: var(--ink-2); }
+.act.can { border-color: var(--life); box-shadow: 0 0 0 2px var(--life-soft); }
+.act .kbd { margin-left: auto; font-size: 10px; color: var(--muted-2); border: 1px solid var(--line); border-radius: 4px; padding: 0 4px; }
+.act.primary .kbd { color: #8e9bb0; border-color: #3a475f; }
+
+/* ── 升级列表 ── */
+.upg { display: flex; align-items: center; gap: 10px; padding: 9px 0; border-top: 1px dashed var(--line); }
+.upg:first-of-type { border-top: 0; padding-top: 0; }
+.upg .ic { width: 34px; height: 34px; flex: none; border-radius: 8px; display: grid; place-items: center; background: #f1f4f7; border: 1px solid var(--line); }
+.upg .ic svg { width: 22px; height: 22px; }
+.upg .info { flex: 1; min-width: 0; }
+.upg .info .n { font-size: 13px; font-weight: 650; display: flex; gap: 6px; align-items: baseline; }
+.upg .info .n .lv { font-size: 11px; color: var(--muted); font-weight: 500; }
+.upg .info .d { font-size: 11px; color: var(--muted); margin-top: 1px; }
+.upg .info .d b { color: var(--ink-3); }
+.upg .buy {
+  border: 1px solid var(--line-strong); background: #fff; border-radius: 7px; padding: 6px 9px; min-width: 92px;
+  font-size: 11px; display: flex; flex-direction: column; align-items: flex-end; gap: 1px; transition: all .15s;
+}
+.upg .buy .c { font-weight: 700; font-size: 12px; color: var(--ink); }
+.upg .buy .c small { font-weight: 500; color: var(--muted); font-size: 10px; margin-right: 2px; }
+.upg .buy.ok { border-color: var(--life); background: var(--life-soft); color: #1c7a48; }
+.upg .buy.ok .c { color: #1c7a48; }
+.upg .buy:hover:not(:disabled).ok { background: #d7f0e2; }
+.upg .buy .n2 { font-size: 10px; color: var(--muted); }
+.upg.locked { opacity: .55; }
+.upg .lock { font-size: 11px; color: var(--muted); }
+
+/* ── 兵种 ── */
+.races { display: flex; flex-direction: column; gap: 8px; }
+.race-head { display: flex; align-items: center; gap: 7px; font-size: 11px; font-weight: 700; color: var(--muted); letter-spacing: .06em; margin-top: 2px; }
+.race-head .chip { color: #fff; border-radius: 4px; padding: 1px 6px; font-size: 10px; letter-spacing: .04em; }
+.race-head .bond { font-weight: 500; letter-spacing: 0; color: var(--muted); margin-left: auto; font-size: 10.5px; }
+.race-head .bond.on { color: #1c7a48; }
+.life { display: flex; gap: 9px; align-items: center; padding: 6px 0; }
+.life .ic { width: 36px; height: 36px; flex: none; border-radius: 9px; border: 1px solid var(--line); background: #fafbfc; display: grid; place-items: center; }
+.life .ic svg { width: 26px; height: 26px; }
+.life .info { flex: 1; min-width: 0; }
+.life .info .n { font-size: 12.5px; font-weight: 650; display: flex; gap: 6px; align-items: baseline; }
+.life .info .n .lv { font-size: 11px; color: var(--muted); font-weight: 500; }
+.life .info .s { font-size: 10.5px; color: var(--muted-2); }
+.life .buy { font-size: 11px; border: 1px solid var(--line-strong); background: #fff; border-radius: 7px; padding: 5px 8px; min-width: 76px; text-align: right; }
+.life .buy.ok { border-color: var(--life); background: var(--life-soft); color: #1c7a48; }
+.life .buy .c { font-weight: 700; }
+.life.locked { opacity: .5; }
+
+/* ── 永久 / 转生 ── */
+.reb-card { border: 1px solid #e7dcc0; background: linear-gradient(180deg, #fffdf8, var(--gold-soft)); border-radius: 10px; padding: 11px 12px; }
+.reb-card .k { font-size: 11px; color: #8a6d2c; letter-spacing: .08em; }
+.reb-card .v { font-size: 26px; font-weight: 750; color: #7a5a12; margin-top: 2px; }
+.reb-card .v small { font-size: 12px; color: #a5893f; font-weight: 600; margin-left: 4px; }
+.reb-card .line { font-size: 11px; color: #8a6d2c; margin-top: 4px; display: flex; flex-wrap: wrap; gap: 2px 10px; }
+.reb-card .line b { color: #5f470f; }
+.perm { display: flex; align-items: center; gap: 10px; padding: 7px 0; border-top: 1px dashed #e7dcc0; }
+.perm:first-of-type { border-top: 0; }
+.perm .info { flex: 1; }
+.perm .n { font-size: 12.5px; font-weight: 650; }
+.perm .d { font-size: 10.5px; color: var(--muted); }
+.perm .buy { font-size: 11px; border: 1px solid #e0cf9f; background: #fff; border-radius: 7px; padding: 5px 9px; min-width: 78px; text-align: right; }
+.perm .buy.ok { background: #fff8e6; border-color: var(--gold); color: #7a5a12; }
+.perm .buy.ok .c { font-weight: 700; }
+.relics { display: flex; gap: 5px; flex-wrap: wrap; margin-top: 2px; }
+.relic { width: 26px; height: 26px; border-radius: 6px; border: 1px solid #e0cf9f; background: #fffdf6; display: grid; place-items: center; }
+.relic.off { opacity: .3; filter: grayscale(1); }
+.relic svg { width: 16px; height: 16px; }
+
+/* ── 位面 ── */
+.plane-list { display: grid; grid-template-columns: 1fr 1fr; gap: 7px; }
+.plane-card { border: 1px solid var(--line); border-radius: 9px; padding: 8px 9px; background: #fff; text-align: left; position: relative; overflow: hidden; }
+.plane-card .tier { position: absolute; right: 0; top: 0; font-size: 9px; color: #fff; padding: 1px 6px; border-bottom-left-radius: 6px; }
+.plane-card.cur { border-color: var(--ink); box-shadow: inset 0 0 0 1px var(--ink); }
+.plane-card.locked { opacity: .5; }
+.plane-card .nm { font-size: 12.5px; font-weight: 650; margin-top: 2px; }
+.plane-card .met { font-size: 10px; color: var(--muted); margin-top: 1px; }
+.plane-card .bar { height: 4px; border-radius: 2px; background: #eceff3; margin-top: 6px; overflow: hidden; }
+.plane-card .bar i { display: block; height: 100%; border-radius: 2px; }
+.plane-card .ex { font-size: 10px; color: var(--muted); margin-top: 3px; display: flex; justify-content: space-between; }
+.plane-card .ex .an { color: var(--life); font-weight: 700; }
+.plane-note { font-size: 11px; color: var(--muted); margin-top: 8px; line-height: 1.55; }
+.plane-note b { color: var(--ink-3); }
+
+/* 位面主题色带:顶部细线 */
+[data-plane="0"] { --plane-c: #5fa8d3; }
+[data-plane="1"] { --plane-c: #6c5ce7; }
+[data-plane="2"] { --plane-c: #c77dff; }
+[data-plane="3"] { --plane-c: #2dd4bf; }
+.topbar { border-top: 3px solid var(--plane-c, var(--life)); }
+
+/* ── 里世界 ── */
+.rift-top { display: flex; gap: 10px; align-items: center; margin-bottom: 10px; }
+.rift-top .env { flex: 1; }
+.rift-top .env .nm { font-size: 15px; font-weight: 700; }
+.rift-top .env .ds { font-size: 11px; color: var(--muted); }
+.hpbar { height: 14px; border-radius: 4px; background: #eceff3; border: 1px solid var(--line); overflow: hidden; position: relative; }
+.hpbar i { display: block; height: 100%; background: linear-gradient(90deg, #7ad39f, var(--life)); transition: width .25s; }
+.hpbar.enemy i { background: linear-gradient(90deg, #e2a09b, #c0492e); }
+.hpbar .txt { position: absolute; inset: 0; font-size: 10px; display: grid; place-items: center; font-weight: 700; color: var(--ink); font-variant-numeric: tabular-nums; }
+.elite-tag { font-size: 10px; font-weight: 700; padding: 1px 6px; border-radius: 4px; background: var(--ink); color: #fff; letter-spacing: .06em; }
+.elite-tag.boss { background: var(--gold); }
+.taunt { font-size: 12px; color: var(--muted); font-style: italic; margin: 8px 0 4px; line-height: 1.6; border-left: 2px solid var(--line-strong); padding-left: 8px; }
+.steps { display: flex; gap: 4px; align-items: center; margin: 8px 0 10px; }
+.steps i { flex: 1; height: 5px; border-radius: 3px; background: #eceff3; }
+.steps i.past { background: var(--life); }
+.steps i.now { background: var(--gold); }
+.card-opts { display: flex; flex-direction: column; gap: 8px; margin-top: 8px; }
+.opt { border: 1px solid var(--line); background: #fff; border-radius: 9px; padding: 10px 12px; text-align: left; transition: all .15s; }
+.opt:hover { border-color: var(--ink); transform: translateY(-1px); }
+.opt .l { font-size: 13.5px; font-weight: 650; }
+.opt .h { font-size: 11.5px; color: var(--muted); margin-top: 2px; }
+.opt .rule-chip { display: inline-block; font-size: 10px; color: #fff; padding: 1px 6px; border-radius: 4px; margin-right: 4px; }
+.dice-row { display: flex; align-items: center; gap: 8px; margin-top: 10px; }
+.dice { width: 42px; height: 42px; border-radius: 10px; border: 1px solid var(--line-strong); background: #fff; display: grid; place-items: center; font-size: 22px; font-weight: 750; font-variant-numeric: tabular-nums; }
+.dice.rolling { animation: shake .3s linear infinite; }
+@keyframes shake { 0%,100% { transform: rotate(-3deg) } 50% { transform: rotate(3deg) } }
+.cmp { flex: 1; font-size: 12px; line-height: 1.6; }
+.cmp .need { color: var(--danger); font-weight: 650; }
+.cmp .val { font-weight: 750; }
+.cmp .win { color: var(--life); }
+.cmp .lose { color: var(--danger); }
+.roll-label { font-size: 13px; font-weight: 750; padding: 2px 8px; border-radius: 6px; display: inline-block; margin-top: 6px; }
+.roll-label.win { background: var(--life-soft); color: #1c7a48; }
+.roll-label.lose { background: #fbe8e3; color: var(--danger); }
+.roll-label.neutral { background: #f1f3f6; color: var(--ink-3); }
+.fight-btns { display: grid; grid-template-columns: 1fr 92px; gap: 8px; margin-top: 10px; }
+.btn { border: 1px solid var(--ink); background: var(--ink); color: #fff; border-radius: 9px; padding: 11px 12px; font-size: 14px; font-weight: 700; }
+.btn.ghost { background: #fff; color: var(--ink); border-color: var(--line-strong); font-weight: 600; font-size: 12.5px; }
+.btn.danger { background: #fff; color: var(--danger); border-color: #e8bfb5; font-size: 12.5px; }
+.attrs { display: grid; grid-template-columns: repeat(4, 1fr); gap: 6px; margin-top: 10px; }
+.attr { border: 1px solid var(--line); border-radius: 8px; padding: 6px 7px; background: #fafbfc; }
+.attr .k { font-size: 10px; font-weight: 700; letter-spacing: .06em; display: flex; justify-content: space-between; }
+.attr .k .ad { font-weight: 500; color: var(--muted); }
+.attr .v { font-size: 18px; font-weight: 750; font-variant-numeric: tabular-nums; }
+.attr .slot { font-size: 9.5px; color: var(--muted-2); }
+.stepper { display: flex; gap: 4px; margin-top: 3px; }
+.stepper button { flex: 1; border: 1px solid var(--line-strong); background: #fff; border-radius: 5px; font-size: 13px; line-height: 1.4; padding: 0; font-weight: 700; }
+.stepper button:disabled { opacity: .3; }
+
+/* ── 日志 / 事件 ── */
+.feed { display: flex; flex-direction: column; gap: 8px; max-height: 100%; overflow-y: auto; }
+.feed .row { font-size: 12px; color: var(--ink-3); display: flex; align-items: center; gap: 8px; line-height: 1.45; }
+.feed .row time { color: var(--muted-2); font-size: 10.5px; font-variant-numeric: tabular-nums; min-width: 34px; }
+.feed .row.crisis { color: var(--crisis); }
+.feed .row.mile { color: #7a5a12; font-weight: 600; }
+.empty { color: var(--muted-2); font-size: 12px; padding: 8px 0; }
+
+/* ── 底部导航(仅手机) ── */
+.tabbar { display: none; }
+.drawer-mask { display: none; }
+
+/* ── 弹窗 / Toast ── */
+.modal-mask { position: fixed; inset: 0; background: rgba(18,26,43,.38); display: grid; place-items: center; z-index: 50; padding: 16px; backdrop-filter: blur(1px); }
+.modal-mask[hidden] { display: none; }
+.modal { width: min(520px, 100%); background: #fff; border-radius: 14px; border: 1px solid var(--line); box-shadow: 0 20px 60px rgba(18,26,43,.22); overflow: hidden; max-height: 88vh; display: flex; flex-direction: column; animation: pop .18s ease-out; }
+@keyframes pop { from { transform: translateY(8px) scale(.985); opacity: 0; } to { transform: none; opacity: 1; } }
+.modal header { padding: 16px 18px 10px; display: flex; align-items: flex-start; gap: 10px; }
+.modal header .mt { flex: 1; }
+.modal header .mtag { display: inline-block; font-size: 10px; font-weight: 700; letter-spacing: .12em; padding: 2px 7px; border-radius: 4px; background: #f1f3f6; color: var(--muted); margin-bottom: 6px; }
+.modal header .mtag.crisis { background: #fdf1e3; color: #a5620d; }
+.modal header .mtag.mile { background: var(--gold-soft); color: #7a5a12; }
+.modal header .mtag.civ { background: #e9f1fb; color: #2a5f99; }
+.modal header .mtag.rift { background: #f0ecfb; color: #533aa8; }
+.modal h3 { margin: 0; font-size: 18px; letter-spacing: -.01em; }
+.modal .body { padding: 4px 18px 16px; overflow-y: auto; }
+.modal .body p { font-size: 13.5px; line-height: 1.75; color: var(--ink-3); margin: 6px 0 12px; }
+.modal .opts { display: flex; flex-direction: column; gap: 8px; }
+.modal .foot { padding: 0 18px 16px; display: flex; gap: 8px; justify-content: flex-end; }
+.modal textarea { width: 100%; height: 160px; border: 1px solid var(--line-strong); border-radius: 8px; padding: 9px; font-family: var(--mono); font-size: 11px; resize: vertical; }
+.cd { font-size: 12px; color: var(--crisis); font-weight: 650; }
+#toasts { position: fixed; left: 50%; bottom: 22px; transform: translateX(-50%); display: flex; flex-direction: column; gap: 6px; z-index: 60; pointer-events: none; align-items: center; }
+.toast { background: var(--ink); color: #eef1f6; font-size: 12.5px; padding: 8px 14px; border-radius: 999px; box-shadow: 0 8px 24px rgba(18,26,43,.25); animation: toastIn .2s ease-out; max-width: 90vw; }
+.toast.warn { background: #8a4d12; }
+.toast.good { background: #1c6b43; }
+@keyframes toastIn { from { opacity: 0; transform: translateY(6px); } to { opacity: 1; transform: none; } }
+
+/* ── 新手引导 ── */
+.guide { border: 1px solid #cfe6d9; background: var(--life-soft); border-radius: 10px; padding: 10px 12px; display: flex; gap: 10px; align-items: center; }
+.guide .g { flex: 1; font-size: 12.5px; line-height: 1.6; color: #1c5c3a; }
+.guide .g b { color: #123f28; }
+.guide .x { border: 0; background: transparent; color: #1c5c3a; font-size: 16px; padding: 2px 6px; }
+.pulse { animation: pulse 1.8s ease-in-out infinite; }
+@keyframes pulse { 0%,100% { box-shadow: 0 0 0 0 rgba(47,174,107,.0); } 50% { box-shadow: 0 0 0 4px rgba(47,174,107,.18); } }
+
+/* 性能:低端设备关动画 */
+@media (prefers-reduced-motion: reduce) { * { animation: none !important; transition: none !important; } }
+
+/* ══════════ 响应式 ══════════ */
+/* 中等宽度:两栏 */
+@media (max-width: 1180px) {
+  .main { grid-template-columns: 280px minmax(0, 1fr); }
+  .col.right { display: none; }
+  .main.show-right .col.right { display: flex; position: fixed; right: 10px; top: 60px; bottom: 10px; width: 320px; z-index: 20; background: var(--paper); border: 1px solid var(--line); border-radius: 12px; padding: 10px; box-shadow: 0 20px 60px rgba(18,26,43,.2); }
+}
+/* 手机竖屏(≤760px):单栏 */
+@media (max-width: 760px) {
+  #app { grid-template-rows: auto 1fr auto; }
+  .topbar { padding: 0 10px; height: 46px; gap: 8px; }
+  .brand { font-size: 13.5px; }
+  .brand small { display: none; }
+  .topstats { gap: 10px; margin-left: auto; }
+  .topstats .tstat.optional { display: none; }
+  .topstats .tstat .v { font-size: 12.5px; }
+  .viewport-toggle { display: none; }
+  .main { display: block; padding: 8px; overflow-y: auto; padding-bottom: 70px; }
+  .main > .col { display: none; overflow: visible; padding-bottom: 0; }
+  .main > .col.active { display: flex; }
+  .main.show-right .col.right { position: static; width: auto; border: 0; padding: 0; box-shadow: none; background: transparent; display: none; }
+  .main.show-right > .col.center { display: none; }
+  .main.show-right .col.right { display: flex; }
+  .canvas-wrap { min-height: 240px; height: 38vh; flex: none; }
+  .big-num { font-size: 25px; }
+  .res .v { font-size: 17px; }
+  .actions { grid-template-columns: repeat(2, 1fr); }
+  .tabbar {
+    display: grid; grid-template-columns: repeat(4, 1fr); background: #fff; border-top: 1px solid var(--line);
+    padding: 4px 6px calc(4px + env(safe-area-inset-bottom)); gap: 2px; z-index: 30;
+  }
+  .tabbar button { border: 0; background: transparent; color: var(--muted); font-size: 11px; padding: 6px 2px 4px; display: flex; flex-direction: column; align-items: center; gap: 3px; border-radius: 8px; }
+  .tabbar button svg { width: 20px; height: 20px; }
+  .tabbar button.on { color: var(--ink); background: #f1f3f6; font-weight: 700; }
+  .modal { width: 100%; border-radius: 14px 14px 10px 10px; }
+  .modal-mask { align-items: end; padding: 0; }
+  .modal { max-height: 86vh; animation: sheetUp .2s ease-out; }
+  @keyframes sheetUp { from { transform: translateY(30px); opacity: .6 } to { transform: none; opacity: 1 } }
+  .fight-btns { grid-template-columns: 1fr 80px; }
+  .attrs { grid-template-columns: repeat(2, 1fr); }
+  .upg .buy { min-width: 84px; }
+  #toasts { bottom: 76px; }
+}
+
+/* ── 里世界面板(中栏覆盖) ── */
+.rift-panel { border-color: #d9d0f2; background: linear-gradient(180deg, #fbfaff, #fff); }
+.rift-panel[hidden] { display: none; }
+.rift-head { display: flex; align-items: center; gap: 8px; margin-bottom: 8px; }
+.rift-head .nm { font-size: 14px; font-weight: 700; }
+.rift-head .kb { margin-left: auto; font-size: 11px; color: var(--muted); }
+.kv { display: grid; grid-template-columns: repeat(5, 1fr); gap: 6px; font-size: 11px; margin-top: 8px; }
+.kv div { border: 1px solid var(--line); border-radius: 7px; padding: 4px 6px; background: #fff; text-align: center; }
+.kv b { display: block; font-size: 13px; color: var(--ink); font-variant-numeric: tabular-nums; }
+.slot-bar { display: grid; grid-template-columns: repeat(4, 1fr); gap: 6px; margin-top: 8px; }
+.slot { border: 1px solid var(--line); border-radius: 8px; padding: 6px; background: #fff; }
+.slot .h { display: flex; justify-content: space-between; font-size: 10.5px; font-weight: 700; }
+.slot .v { font-size: 18px; font-weight: 750; font-variant-numeric: tabular-nums; }
+.slot .stepper { margin-top: 4px; }
+.energy { display: flex; align-items: center; gap: 6px; font-size: 11px; color: var(--muted); margin-top: 8px; }
+.energy .pips { display: flex; gap: 2px; flex: 1; }
+.energy .pips i { flex: 1; height: 6px; border-radius: 2px; background: #eceff3; }
+.energy .pips i.on { background: #7fb2ff; }
+.fight-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 8px; margin-top: 8px; }
+.fight-grid .box { border: 1px solid var(--line); border-radius: 8px; padding: 8px; background: #fff; }
+.fight-grid .box .k { font-size: 10.5px; color: var(--muted); }
+.fight-grid .box .v { font-size: 22px; font-weight: 750; font-variant-numeric: tabular-nums; }
+.fight-grid .box.enemy .v { color: var(--danger); }
+.roll-bar { display: flex; gap: 6px; margin-top: 8px; }
+.roll-btn { flex: 1; border: 1px solid var(--line-strong); background: #fff; border-radius: 8px; padding: 8px 0; font-size: 15px; font-weight: 750; font-variant-numeric: tabular-nums; transition: transform .12s; }
+.roll-btn:hover { border-color: var(--ink); }
+.roll-btn:active { transform: scale(.97); }
+.roll-btn.hint { border-color: var(--life); background: var(--life-soft); }
+.roll-btn.crit-hint { border-color: var(--gold); background: var(--gold-soft); }
+.log3 { margin-top: 8px; font-size: 11px; color: var(--muted); line-height: 1.6; min-height: 34px; }
+.log3 b { color: var(--ink-3); }
+.pick-oath { display: grid; grid-template-columns: repeat(3, 1fr); gap: 8px; margin-top: 6px; }
+.pick-oath .opt { text-align: center; padding: 10px 8px; }
+.pick-oath .opt .nm { font-size: 13.5px; font-weight: 700; }
+.pick-oath .opt .ds { font-size: 11px; color: var(--muted); margin-top: 4px; }
+.build-hint { font-size: 12px; color: var(--muted); margin-top: 6px; }
+.build-hint b { color: var(--life); }
+.step-dots { display: flex; gap: 4px; margin: 8px 0 2px; }
+.step-dots i { flex: 1; height: 4px; border-radius: 2px; background: #eceff3; }
+.step-dots i.past { background: var(--life); }
+.step-dots i.now { background: var(--gold); }
+.rift-result .big { font-size: 26px; font-weight: 750; color: var(--gold); }
+
+/* ── 布局修正:flex 子项允许收缩,避免被窄列挤压成竖排字 ── */
+.panel-title { flex-wrap: wrap; }
+.panel-title .tag { white-space: normal; text-align: right; }
+.upg .info, .life .info, .perm .info { min-width: 0; }
+.upg .info .n, .life .info .n, .perm .n { flex-wrap: wrap; }
+.upg .info .d, .life .info .s, .perm .d { line-height: 1.5; }
+.life .info .s { line-height: 1.45; }
+.race-head { flex-wrap: wrap; }
+.race-head .bond { margin-left: 0; }
+.main { grid-template-columns: 300px minmax(0, 1fr) 340px; }
+.col.left, .col.right { padding-right: 2px; }
+@media (max-width: 1360px) { .main { grid-template-columns: 286px minmax(0, 1fr) 320px; } }
+.esc-bar .mark span { top: 5px; }
+.canvas-wrap { min-height: 260px; }
+.hud .layer small { font-size: 11px; }
+.upg .buy, .perm .buy { flex: none; }
+
+/* ── 面板/区块显式纵向排列(覆盖 .main > .col 的横向 flex 继承) ── */
+#upgrades, #lives, #rebirth, #perm, #planes, #resources, #mainline, #feed-panel, #rift-live { display: flex; flex-direction: column; }
+#upgrades .panel-title, #lives .panel-title, #perm .panel-title, #planes .panel-title, #rebirth .panel-title, #mainline .panel-title, #resources .panel-title, #feed-panel .panel-title, #rift-live .panel-title { flex-direction: row; align-items: center; }
+#mainline .guide { flex-direction: row; }
+#mainline .esc-track { flex-direction: row; }
+.actions { flex-direction: row; }
+.reb-card .line, .sub-line { flex-direction: row; }
+.plane-list { flex-direction: row; }
+.relics { flex-direction: row; }
+.panel-title { min-width: 0; }
+.panel-title::before { flex: none; }
+#lives { display: grid; grid-template-columns: 1fr 1fr; column-gap: 14px; align-items: start; }
+#lives .panel-title, #lives .race-block, #lives .race-head { grid-column: 1 / -1; }
+#lives .race-head { margin-top: 4px; }
+#lives .life { min-width: 0; }
+#lives .life .info .s { white-space: normal; }
+.actions .act .t, .actions .act .s { white-space: nowrap; }
+@media (max-width: 1360px) { #lives { grid-template-columns: 1fr; } }
+
+/* ── 中栏:画布固定高度,内容溢出时滚动 ── */
+.col.center { overflow-y: auto; }
+.canvas-wrap { flex: 0 0 auto; height: clamp(210px, calc(100vh - 330px), 340px); min-height: 180px; }
+.rift-slot { display: flex; flex-direction: column; }
+.rift-slot[hidden] { display: none; }
+#rift-live { display: flex; flex-direction: column; }
+@media (max-width: 760px) { .canvas-wrap { height: 36vh; min-height: 220px; } }

+ 92 - 0
index.html

@@ -0,0 +1,92 @@
+<!DOCTYPE html>
+<html lang="zh-CN">
+<head>
+  <meta charset="utf-8">
+  <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover, maximum-scale=1">
+  <meta name="theme-color" content="#121a2b">
+  <title>世界树 · 逃离空洞</title>
+  <link rel="stylesheet" href="css/style.css">
+</head>
+<body>
+  <div id="app">
+    <header class="topbar">
+      <div class="brand">
+        <svg viewBox="0 0 24 24" fill="none" aria-hidden="true">
+          <path d="M12 21V9" stroke="#5FD68A" stroke-width="1.6" stroke-linecap="round"/>
+          <path d="M12 14 7 9M12 12l5-5M12 17l-4-3M12 16l4-3" stroke="#5FD68A" stroke-width="1.4" stroke-linecap="round"/>
+          <circle cx="7" cy="9" r="1.6" fill="#5FD68A"/><circle cx="17" cy="7" r="1.6" fill="#B7E4C7"/><circle cx="8" cy="14" r="1.3" fill="#B7E4C7"/><circle cx="16" cy="13" r="1.3" fill="#5FD68A"/>
+          <path d="M4 21h16" stroke="#8e9bb0" stroke-width="1.2" stroke-linecap="round"/>
+        </svg>
+        世界树 <small>· 逃离空洞</small>
+      </div>
+      <div class="topstats" id="topstats"></div>
+      <button class="top-save" aria-label="存档">存档</button>
+      <div class="viewport-toggle" aria-label="视口测试">
+        <button class="vp-btn on" data-vp="auto">自适应</button>
+        <button class="vp-btn" data-vp="phone">手机</button>
+      </div>
+    </header>
+
+    <main class="main" id="main">
+      <!-- 左栏:资源 / 主线 / 升级 -->
+      <section class="col left active" id="col-left">
+        <div class="panel flat" id="resources"></div>
+        <div class="panel" id="mainline"></div>
+        <div class="panel life" id="upgrades"></div>
+      </section>
+
+      <!-- 中栏:连续行军 + 操作 + 兵种 -->
+      <section class="col center active" id="col-center">
+        <div class="canvas-wrap" id="canvas-wrap">
+          <canvas id="march"></canvas>
+          <div class="frozen-veil"></div>
+          <div class="hud" id="hud"></div>
+          <div class="hud-r" id="hud-r"></div>
+          <div id="float-layer"></div>
+          <div class="badge-magic" id="magic-badge" hidden></div>
+        </div>
+        <div class="rift-slot" id="rift-slot" hidden></div>
+        <div class="actions" id="actions"></div>
+        <div class="panel life" id="lives"></div>
+      </section>
+
+      <!-- 右栏:转生 / 永久 / 位面 / 日志 -->
+      <section class="col right" id="col-right">
+        <div class="panel gold" id="rebirth"></div>
+        <div class="panel gold" id="perm"></div>
+        <div class="panel brand" id="planes"></div>
+        <div class="panel" id="feed-panel"><div class="panel-title">行旅记录 <span class="tag">事件流</span></div><div class="feed" id="feed"></div></div>
+      </section>
+    </main>
+
+    <nav class="tabbar" id="tabbar">
+      <button data-tab="left" class="on">
+        <svg viewBox="0 0 24 24" fill="none"><path d="M4 6h16M4 12h16M4 18h10" stroke="currentColor" stroke-width="1.8" stroke-linecap="round"/></svg>成长
+      </button>
+      <button data-tab="center">
+        <svg viewBox="0 0 24 24" fill="none"><path d="M3 17c3-8 6-10 9-6s6 2 9-5" stroke="currentColor" stroke-width="1.8" stroke-linecap="round"/><circle cx="12" cy="11" r="2" fill="currentColor"/></svg>行军
+      </button>
+      <button data-tab="right">
+        <svg viewBox="0 0 24 24" fill="none"><circle cx="12" cy="12" r="8" stroke="currentColor" stroke-width="1.8"/><path d="M12 8v4l3 2" stroke="currentColor" stroke-width="1.8" stroke-linecap="round"/></svg>回溯
+      </button>
+      <button data-tab="rift">
+        <svg viewBox="0 0 24 24" fill="none"><path d="M12 3 4 8v5c0 5 4 7.5 8 8 4-.5 8-3 8-8V8l-8-5Z" stroke="currentColor" stroke-width="1.8" stroke-linejoin="round"/><path d="m9 12 2 2 4-4" stroke="currentColor" stroke-width="1.8" stroke-linecap="round"/></svg>里世界
+      </button>
+    </nav>
+  </div>
+
+  <div class="modal-mask" id="modal-mask" hidden>
+    <div class="modal" id="modal" role="dialog" aria-modal="true">
+      <header>
+        <div class="mt"><span class="mtag" id="modal-tag"></span><h3 id="modal-title"></h3></div>
+        <button class="icon-btn" id="modal-x" title="关闭" style="border:0;background:transparent;font-size:20px;color:var(--muted)">×</button>
+      </header>
+      <div class="body" id="modal-body"></div>
+      <div class="foot" id="modal-foot"></div>
+    </div>
+  </div>
+  <div id="toasts" aria-live="polite"></div>
+
+  <script type="module" src="js/main.js"></script>
+</body>
+</html>

+ 194 - 168
js/config.js

@@ -4,254 +4,280 @@
 
 export const SAVE_KEY = 'worldtree_escape_save_v1';
 export const SAVE_VERSION = 1;
-export const GAME_SEC_PER_TICK = 0.1;         // 逻辑 tick 固定步长(秒),存档秒数计算偏移不超过 0.1s
 
 // ── 主线:逃离室女座空洞(连续空间) ─────────────────────────
-// 主线进度 = K × 抵达层数 L。各章 = 一段连续空间,章内无结算弹窗。
-export const PROGRESS_PER_LAYER = 5;           // 每层 = 主线进度 5 单位
-export const TOTAL_LAYERS = 1000;              // 抵达第 1000 层 = 冲出空洞(主线进度 5000)
-export const MAINLINE_TARGET = PROGRESS_PER_LAYER * TOTAL_LAYERS;
+// 主线进度 P 为连续值;层数 L = √(P/10),第 L 层起点 P = 10L²,层长 P(L+1)−P(L) = 20L+10。
+// 章 = 连续空间中的一段,章内没有结算弹窗;抵达第 1000 层 = 冲出空洞。
+export const TOTAL_LAYERS = 1000;
+export const MAINLINE_TARGET = 10 * TOTAL_LAYERS * TOTAL_LAYERS;   // 1e7
+export function progressOfLayer(L) { return Math.round(10 * L * L * 10) / 10; }
 
 export const CHAPTERS = [
-  { idx: 0, at: 0,    short: '地球',     title: '保护地球',       desc: '空洞前沿已越过柯伊伯带,地球是最后一处有生命的声音。' },
-  { idx: 1, at: 1000, short: '太阳系',   title: '脱离太阳系',     desc: '把整颗星球托进世界树的根系,太阳系成为空洞中的第一枚灯塔。' },
-  { idx: 2, at: 2000, short: '旋臂',     title: '脱离猎户旋臂',   desc: '根系铺满旋臂,星云在树冠下重新聚合为航路。' },
-  { idx: 3, at: 3000, short: '银河',     title: '脱离银河系',     desc: '银河的旋涡在身后合拢,世界树第一次长到了星系之外。' },
-  { idx: 4, at: 4000, short: '本星系群', title: '脱离本星系群',   desc: '本星系群的引力潮被抵消,空洞的边界第一次出现在视野里。' },
-  { idx: 5, at: 5000, short: '空洞外',   title: '冲出空洞',       desc: '室女座空洞之外,还有一片未被规则侵蚀的星空。' },
+  { idx: 0, short: '地球',     title: '保护地球',     desc: '空洞前沿已越过柯伊伯带,地球是最后一处有生命的声音。' },
+  { idx: 1, short: '太阳系',   title: '脱离太阳系',   desc: '把整颗星球托进世界树的根系,太阳系成为空洞中的第一枚灯塔。' },
+  { idx: 2, short: '猎户旋臂', title: '脱离猎户旋臂', desc: '根系铺满旋臂,星云在树冠下重新聚合为航路。' },
+  { idx: 3, short: '银河系',   title: '脱离银河系',   desc: '银河的旋涡在身后合拢,世界树第一次长到了星系之外。' },
+  { idx: 4, short: '本星系群', title: '脱离本星系群', desc: '本星系群的引力潮被抵消,空洞的边界第一次出现在视野里。' },
+  { idx: 5, short: '空洞外',   title: '冲出空洞',     desc: '室女座空洞之外,还有一片未被规则侵蚀的星空。' },
 ];
+for (const ch of CHAPTERS) ch.at = ch.idx * 200;   // 每章 200 层(第 ch.at 层起)
 
-/** 当前主线进度对应的章序号(0..5) */
-export function chapterOf(progress) {
+/** 当前到达的层数对应的章序号(0..5) */
+export function chapterOf(layer) {
   let c = 0;
-  for (const ch of CHAPTERS) if (progress >= ch.at) c = ch.idx;
+  for (const ch of CHAPTERS) if (layer >= ch.at) c = ch.idx;
   return c;
 }
 
-// ── 连续推进:层级 ↔ 进度(L = √(P/10),P = 10L²) ────────────
-export function layerFloat(progress) { return Math.sqrt(Math.max(0, progress) / 10); }
-export function layerLength(L) { return 20 * L + 10; }   // 第 L 层 → L+1 层的长度
-export function layerStart(L) { return 10 * L * L; }     // 第 L 层起点进度
-
-// ── 连续行军的核心时序 ─────────────────────────────────────
-// 单层用时 T(L) = 10L + 4 秒;层中匀速推进。
-// 跳关使「当前层剩余」耗时的期望 = T / (1 + E[k]),即时间维度乘区。
-export const MARCH = { visitBase: 4, visitPerLayer: 10 };
+// ── 连续推进时序 ─────────────────────────────────────
+// 基准:第 L 层用时 T(L) = 4 + 10L 秒(层中匀速)。
+// 实际推进速率(层/秒)= 1 / T(L) × 速度乘区,速度乘区 = √(1.15^L) × 兵种/结晶乘区 × 位面规则。
+export const MARCH = { visitBase: 4, visitPerLayer: 10 };   // 第 L 层基础推进时间 T(L)=4+10L 秒(层中匀速)
 export function visitTime(L) { return MARCH.visitBase + MARCH.visitPerLayer * L; }
+export function baseLayersPerSec(L) { return 1 / visitTime(L); }
 
-export const SKIP = { minK: 1, maxK: 4, factor: 0.5 };
-/** 跳关分布:P(k) = p·P₀(k),P₀(k) ∝ 0.5^(k−1),k ∈ [1,4],归一化和为 p */
+// ── 跳关(时间维度乘区) ─────────────────────────────
+// 每次触发时跳 k 层,k ∈ [1,4],P₀(k) ∝ 0.5^(k−1);触发率 p。E[k] = p × 20/15。
+// 跳关使「每层耗时」的期望 = T / (1 + E[k])。
+export const SKIP = { minK: 1, maxK: 4, factor: 0.5, cap: 0.60 };   // 触发率封顶 60% → 时间乘区上限 1+4×0.6=3.4
 export function skipPlan(pEff) {
-  const { minK: a, maxK: b } = SKIP;
-  const w = [];
-  let sum = 0;
-  for (let k = a; k <= b; k++) { const x = Math.pow(SKIP.factor, k - a); w.push(x); sum += x; }
-  const p = clamp01(pEff, 0.95);
+  const ps = Math.max(0, Math.min(SKIP.cap, Number(pEff) || 0));
   const ks = [], probs = [];
-  for (let k = a; k <= b; k++) { ks.push(k); probs.push(p * w[k - a] / sum); }
-  return { p, ks, probs };
+  let sum = 0;
+  for (let k = SKIP.minK; k <= SKIP.maxK; k++) sum += Math.pow(SKIP.factor, k - SKIP.minK);
+  for (let k = SKIP.minK; k <= SKIP.maxK; k++) {
+    ks.push(k); probs.push(ps * Math.pow(SKIP.factor, k - SKIP.minK) / sum);
+  }
+  return { p: ps, ks, probs };
 }
-/** 跳关期望 E[k] = p × Σ k·P₀(k) = p × (1+2·½+3·¼+4·⅛)/(1+½+¼+⅛) = p × 20/15 */
 export function skipExpectation(pEff) {
   const { ks, probs } = skipPlan(pEff);
   return ks.reduce((s, k, i) => s + k * probs[i], 0);
 }
-/** 时间维度乘区:1 + E[k] */
 export function timeMul(pEff) { return 1 + skipExpectation(pEff); }
 
 // ── 本源产出(指数基础 × 多乘区) ───────────────────────────
-export const ESSENCE_BASE = 1;
-export const ESSENCE_GROWTH = 1.05;            // 每层基础产出 ×1.05
-export function essencePerLayer(layer) { return Math.pow(ESSENCE_GROWTH, layer); }
-
-// 侵蚀前沿:第 L 层本源的额外 ×1.15^L(「深度即财富」)
-export function erosionMult(layer) { return Math.pow(1.15, layer); }
+export const ESSENCE_GROWTH = 1.05;   // 每层本源基础 ×1.05;L^p 层段压缩后有效增长率 e^{0.05−p/L}
+// 侵蚀前沿:本源/推进加成 ×(1+0.03(L−F))(线性;深度 = 慢,但每层本源 ×1.05,形成“深度即财富”)
+export function erosionMult(layer, start = 0) { return 1 + 0.03 * Math.max(0, layer - (start || 0)); }
+// 基础产出:B(L) = 1.05^L
+export function essenceBase(layer) { return Math.pow(ESSENCE_GROWTH, Math.max(0, layer)); }
 
 // ── 本轮升级(消耗本源)几何成本 C = base × ratio^level ───────
 export const COST = {
-  root:    { base: 10,   ratio: 1.08, name: '根须',   desc: '每级 本源产出 +8%(独立乘区)' },
-  canopy:  { base: 60,   ratio: 1.12, name: '树冠',   desc: '每级 跳关概率 +1.5%(上限 95%)' },
-  seedbed: { base: 400,  ratio: 1.10, name: '苗圃',   desc: '每级 兵种技能效果 +25%(开局 ×2)' },
+  root:    { base: 10,  ratio: 1.15, per: 0.10,  name: '根须', desc: '每级本源产出 ×(1+0.1R)^0.6 + 推进速度 ×5%' },
+  canopy:  { base: 60,  ratio: 1.35, per: 0.012, name: '树冠', desc: '每级跳关触发率 +1.2%(封顶 60%)' },
 };
+export const UPGRADE_KINDS = ['root', 'canopy'];
 export function costOf(kind, level) { const c = COST[kind]; return c.base * Math.pow(c.ratio, level); }
-/** 批量购买最优(指数成本恰好可求和):能买 n 个的最大 n(n=∞ 返回 70) */
-export function maxAffordable(kind, level, essence) {
+export function batchCost(kind, level, n) {
   const c = COST[kind];
   const first = c.base * Math.pow(c.ratio, level);
-  if (essence < first) return 0;
-  if (c.ratio === 1) return Math.floor(essence / first);
-  const n = Math.floor(Math.log(essence * (c.ratio - 1) / first + 1) / Math.log(c.ratio));
-  return Math.min(70, Math.max(0, n));
+  return Math.ceil(first * (Math.pow(c.ratio, n) - 1) / (c.ratio - 1));
 }
-/** 第 level..level+n-1 级的合计成本 */
-export function batchCost(kind, level, n) {
+/** 最多能买 n 个(批量购买);封顶 70 级/次 */
+export const PURCHASE_CAP = 12;   // 单次批量购买上限(限制本源→等级的指数扫货)
+export function maxAffordable(kind, level, essence) {
   const c = COST[kind];
   const first = c.base * Math.pow(c.ratio, level);
-  return Math.ceil(first * (Math.pow(c.ratio, n) - 1) / (c.ratio - 1));
+  if (!(essence >= first)) return 0;
+  const n = Math.floor(Math.log(essence * (c.ratio - 1) / first + 1) / Math.log(c.ratio));
+  return Math.min(PURCHASE_CAP, Math.max(0, n));
 }
+/** 根须产出乘区:每级 ×1.10,整体取 ROOT_EXP 次方做层段压缩(防指数发散,见 GDD §6.5) */
+export const ROOT_EXP = 0.6;   // 根须产出层段压缩指数
+export function rootProdMul(level) { return Math.pow(Math.pow(1 + COST.root.per, level || 0), ROOT_EXP); }
+export const rootMul = rootProdMul;
+export const ROOT_SPEED_PER = 0.05;
+export function rootSpeedMul(level) { return Math.pow(1 + ROOT_SPEED_PER, level || 0); }
+export function canopySkip(level) { return Math.min(SKIP.cap, COST.canopy.per * (level || 0)); }
 
-/** 兵种升级成本 cost(L) = base × 1.15^(L−1) */
+// 乘区汇总
+export function multLayer(layer) { return 1 + 0.02 * Math.max(0, layer); }
+export function multCreature(totalLevel) { return 1 + 0.08 * totalLevel; }
+export function multMind(level) { return 1 + 0.15 * (level || 0); }
+export function multRelic(count) { return Math.pow(1.25, count || 0); }
+export function multRebirth(count) { return 1 + 0.10 * (count || 0); }
+export function multExploration(explore) { return 1 + Math.max(0, explore || 0) / 100; }
+
+// ── 兵种(常驻推进跑道,持续生效) ──────────────────────────
+// 等级 n:升级成本 cost × 1.15^(n−1);技能强度 = 1 + per × n。解锁:上一兵种 ≥3 级。
+// 解锁条件:上一兵种达到 3 级。
+export const LIVES = [
+  { id: 'sprout',      race: '生命', name: '萌芽苔',   cost: 25,   eff: { kind: 'prod',    per: 0.05 },  skill: '根系扎入跑道,本源产出 +5%/级', icon: 'sprout' },
+  { id: 'firefly',     race: '生命', name: '萤火虫',   cost: 120,  eff: { kind: 'speed',   per: 0.04 },  skill: '沿根系迁徙,推进速度 +4%/级', icon: 'firefly' },
+  { id: 'rootwalker',  race: '生命', name: '根行者',   cost: 900,  eff: { kind: 'skip',    per: 0.008 }, skill: '在层间挖掘捷径,跳关 +0.8%/级', icon: 'root' },
+  { id: 'arbor',       race: '星穹', name: '星穹古树', cost: 3e3,  eff: { kind: 'prod',    per: 0.10 },  skill: '庇护之树,本源产出 +10%/级', icon: 'tree' },
+  { id: 'cometmoth',   race: '星穹', name: '彗星蛾',   cost: 1.2e4, eff: { kind: 'speed',  per: 0.06 },  skill: '驮着树冠跨越星云,速度 +6%/级', icon: 'moth' },
+  { id: 'constsign',   race: '星穹', name: '星座使',   cost: 8e4,  eff: { kind: 'crystal', per: 0.03 },  skill: '记录星象,炼化收益 +3%/级', icon: 'sign' },
+  { id: 'voideye',     race: '虚空', name: '虚空之眼', cost: 5e5,  eff: { kind: 'skip',    per: 0.015 }, skill: '看穿壁垒,跳关 +1.5%/级', icon: 'eye' },
+  { id: 'entropymaw',  race: '虚空', name: '熵噬之喉', cost: 4e6,  eff: { kind: 'prod',    per: 0.20 },  skill: '吞吐侵蚀的本源,产出 +20%/级', icon: 'maw' },
+  { id: 'lightstrider', race: '虚空', name: '光行者',  cost: 3e7,  eff: { kind: 'speed',   per: 0.10 },  skill: '以光速掠过每一层,速度 +10%/级', icon: 'strider' },
+];
 export const LIFE_RATIO = 1.15;
-export function lifeCostOf(baseCost, level) { return baseCost * Math.pow(LIFE_RATIO, level - 1); }
+export function lifeCostOf(baseCost, n) { return baseCost * Math.pow(LIFE_RATIO, n - 1); }
 
-// ── 永久乘区(时间结晶) ───────────────────────────────
-export const PERM = {
-  mindBase: 15, mindRatio: 1.2, mindPer: 0.15,   // 心智树 h:成本 15×1.2^h,每级全局产出 ×(1+0.15h)
-  relicBase: 4, relicCostMult: 2.5, relicPer: 0.25, // 遗物(有限 8 件):成本 4×2.5^i,每件 本源产出 ×1.25
-  ascBase: 200, ascRatio: 3, ascPer: 0.25,       // 升维(时间结晶):成本 200×3^a,每级 全局产出 ×(1+0.25a)
+export const RACES = {
+  生命: { color: '#5FD68A', need: 2, bond: '共生:同种族达到 2 个兵种,本源产出 ×1.3(每多 1 个 ×1.3)' },
+  星穹: { color: '#7FB2FF', need: 2, bond: '观星:同种族达到 2 个兵种,炼化收益 ×1.3(每多 1 个 ×1.3)' },
+  虚空: { color: '#C08BFF', need: 2, bond: '凝视:同种族达到 2 个兵种,跳关概率 +5%(每个最多 +10%)' },
 };
-export function mindCost(level) { return Math.ceil(PERM.mindBase * Math.pow(PERM.mindRatio, level)); }
-export function mindMul(level) { return 1 + PERM.mindPer * level; }
-export function relicCost(nextIndex) { return Math.ceil(PERM.relicBase * Math.pow(PERM.relicCostMult, nextIndex)); }
+export const RACE_BOND_STEP = 2;
+export const RACE_BOND_MULT = 1.3;
+export const RACE_SKIP_BONUS = 0.05;
+export function raceStacks(race, count) { return Math.max(0, count - (RACES[race].need - 1)); }
+
+// ── 永久乘区(时间结晶,跨轮回) ───────────────────────────
+// 世界树等级 D(核心永久乘区):成本 10 × 1.6^D;每级 本源产出 ×(1+0.05D)、推进速度 ×(1+0.08D)
+export const TREE = { costBase: 100, costRatio: 1.7, prodPer: 0.05, speedPer: 0.08 };
+export function treeCost(level) { return Math.ceil(TREE.costBase * Math.pow(TREE.costRatio, level || 0)); }
+export function treeProdMul(level) { return 1 + TREE.prodPer * (level || 0); }
+export function treeSpeedMul(level) { return 1 + TREE.speedPer * (level || 0); }
+
+// 遗物(8 件):成本 50 × 2.6^i,每件 本源产出 ×1.25
+export const PERM = { relicBase: 50, relicRatio: 2.6, relicPer: 0.25, relicCount: 8 };
+export const PERM_INVEST = ['stem', 'relic'];   // 可花费时间结晶的永久投资项
+export function relicCost(idx) { return Math.ceil(PERM.relicBase * Math.pow(PERM.relicRatio, idx)); }
 export function relicMul(count) { return Math.pow(1 + PERM.relicPer, count || 0); }
-export function ascCost(level) { return Math.ceil(PERM.ascBase * Math.pow(PERM.ascRatio, level)); }
-export function ascMul(level) { return 1 + PERM.ascPer * (level || 0); }
 
-// ── 转生结晶 ───────────────────────────────────────────
-// 单次炼化收益 R = 0.15 × (G+1) × M × (1+log10(1+maxL)) × C₂
-//   G = Σ已锚定位面探索度/100(每锚定 +15%),M = 本源收益乘区(转生时快照),maxL = 本轮最深层
-// 重复炼化同轮回收益衰减 ÷2^已炼化次数(仍然保留「早转 vs 硬熬」)——见 state.js
-export const REBIRTH = {
-  k: 0.15, planeBonus: 0.15, min: 1,
-  inPlaneMul: 0.35,            // 在里世界(时间冻结)中转生:收益 ×0.35(防止占着时空稳定器白拿)
-  autoFrac: 0.5,               // 自动转生冻结 50%
-};
-export function earlyLayer(minL) { return Math.floor(minL * 0.35); }   // 新生世界树起始层 = 最深×35%
-export function rebirthReward({ maxLayer, planeSumPct = 0, incomeMul = 1, rebirthCount = 0, ruleMod = 1 }) {
-  const g = 1 + REBIRTH.planeBonus * (planeSumPct / 100);
-  const raw = REBIRTH.k * (g) * incomeMul * (1 + Math.log10(1 + Math.max(0, maxLayer))) * ruleMod;
+// 自由轮回(首次逃逸后永久解锁):每完成一个完整的“第 1000 层”轮回,自由轮回加成 +10%
+export const FREEDOM = { per: 0.1 };
+export function freedomMul(state) { return 1 + FREEDOM.per * (state.freeCycles || 0); }
+/** 残响(时间结晶的被动加成,不花费):炼化乘区 ×(1+0.02×已炼化次数) */
+export function resonanceMul(state) { return 1 + 0.02 * (state.rebirths || 0); }
+
+/** 遗物定义(固定内容) */
+export const RELICS = [
+  { id: 'seed',   name: '初生之种', desc: '本源产出 ×1.25', icon: 'seed' },
+  { id: 'star',   name: '坠星残片', desc: '本源产出 ×1.25', icon: 'star' },
+  { id: 'gear',   name: '古齿轮',   desc: '本源产出 ×1.25', icon: 'gear' },
+  { id: 'rune',   name: '符文页',   desc: '本源产出 ×1.25', icon: 'rune' },
+  { id: 'hour',   name: '沙漏',     desc: '本源产出 ×1.25', icon: 'hourglass' },
+  { id: 'leaf',   name: '金叶',     desc: '本源产出 ×1.25', icon: 'leaf' },
+  { id: 'orbit',  name: '环轨道',   desc: '本源产出 ×1.25', icon: 'orbit' },
+  { id: 'void',   name: '空洞切片', desc: '本源产出 ×1.25', icon: 'void' },
+];
+
+// ── 转生(时间回溯) ─────────────────────────────────────
+// 单次收益 R = ⌊0.5 × T^1.1 × E × M × ruleMod⌋,保底 1,T = 本轮最深(层)
+//   E = 1 + 已锚定位面探索度总和/100(每位面锚定 +100%)
+//   M = 炼化乘区(兵种技能 × 星穹羁绊 × 探索阶梯 × 跳关加成)
+// 本轮回溯成本 C(T) = 1 + (T/40)²;净收益效率 = R/C。同一轮回内再次炼化收益 ×0.5^n。
+export const REBIRTH = { k: 0.5, power: 1.1, exploreDiv: 100, min: 1, costDiv: 40, decay: 0.5, skipNoteCap: 0.3 };
+export function rebirthCost(T) { return 1 + Math.pow(Math.max(0, T) / REBIRTH.costDiv, 2); }
+export function rebirthReward({ maxLayer = 0, exploreSum = 0, incomeMul = 1, ruleMod = 1 }) {
+  const T = Math.max(0, maxLayer);
+  const E = 1 + exploreSum / REBIRTH.exploreDiv;
+  const raw = REBIRTH.k * Math.pow(T, REBIRTH.power) * E * incomeMul * ruleMod;
   return Math.max(REBIRTH.min, Math.floor(raw));
 }
-/** 预计可炼化结晶(含重生次数衰减 / 里世界折减) */
-export function crystalGain(state, incomeMul) {
-  const base = rebirthReward({
-    maxLayer: state.round?.maxLayer || 0,
-    planeSumPct: state.planeSumPct || 0,
-    incomeMul,
-    ruleMod: PLANE_REBIRTH_MOD[state.currentPlane] || 1,
-  });
-  const decay = Math.pow(0.5, state.round?.refines || 0);
-  const inPlane = state.planeRun?.active ? REBIRTH.inPlaneMul : 1;
-  return Math.max(1, Math.floor(base * decay * inPlane));
+
+// ── 危机:侵蚀前沿 ─────────────────────────────────────
+export const CRISIS = {
+  firstAt: 90, interval: 180, countdown: 120,   // 首次 90 秒,此后每 180 秒一次;响应窗口 120 秒
+  nearEnd: 0.6,
+  penalty: 0.5, penaltySec: 60,
+  reward: 0.3, rewardSec: 90,
+  braceSec: 45, bracePer: 0.5,
+  relaxSkip: 5, holdLayers: 5, expireLayers: 3,
+  relieveCost: 0.25,
+};
+
+// 回溯起始层 F = ⌊RETURN_FRAC × 本轮最深⌋ + 位面起始加成(修仙位面 +100)。不记历史最深。
+export const RETURN_FRAC = 1.0;   // 回溯:下轮起始层 F = ⌊RETURN_FRAC × 本轮最深⌋ + 位面加成
+export function earlyLayer(maxLayerRound, rule) {
+  return Math.floor(RETURN_FRAC * Math.max(0, maxLayerRound)) + ((rule && rule.startBonus) || 0);
 }
 
-// ── 位面 ─────────────────────────────────────────────
+// ── 位面(4 阶,规则松绑梯度) ─────────────────────────────
 export const PLANES = [
-  { id: 0, key: 'real',    tier: '一阶', name: '现实位面', metric: '文明等级',  essence: '认知本源', color: '#5FA8D3', accent: '#9BD1F5',
+  { id: 0, key: 'real', tier: '一阶', name: '现实位面', metric: '文明等级', essence: '认知本源', color: '#5FA8D3', accent: '#9BD1F5',
     lore: '一切规则最严密的地方。这里没有魔法,只有因果、工程与不肯放弃的人。',
-    rule: '坚固因果:世界树生长与本源产出 ×1.00', bonus: '文明演进:文明事件链,科技节点驱动主线' },
-  { id: 1, key: 'tech',    tier: '二阶', name: '科技位面', metric: '自动化覆盖率', essence: '信息本源', color: '#6C5CE7', accent: '#B7A8FF',
+    rule: '坚固因果:全参数基准 ×1.00', bonus: '文明演进:文明事件链驱动主线' },
+  { id: 1, key: 'tech', tier: '二阶', name: '科技位面', metric: '自动化覆盖率', essence: '信息本源', color: '#6C5CE7', accent: '#B7A8FF',
     lore: '无人值守的城市里,机器替人类继续演算。自动化是这个世界唯一的信仰。',
-    rule: '自动化闭环:兵种以自动速度生长,生产不依赖访视', bonus: '时间压缩:世界树推进 ×1.25' },
-  { id: 2, key: 'magic',   tier: '三阶', name: '魔幻位面', metric: '魔力浓度',  essence: '精神本源', color: '#C77DFF', accent: '#F0B2FF',
+    rule: '自动化闭环:兵种免费自动升级(每秒 1 级,最高 60 级)', bonus: '时间压缩:推进速度 ×1.25' },
+  { id: 2, key: 'magic', tier: '三阶', name: '魔幻位面', metric: '魔力浓度', essence: '精神本源', color: '#C77DFF', accent: '#F0B2FF',
     lore: '故事在这里是真实的燃料。只要还有人在讲述,世界就不会熄灭。',
-    rule: '叙事即魔法:每次跳关发生,本源产出 ×1.3(乘法)', bonus: '故事共鸣:跳关概率 +10%' },
+    rule: '叙事即魔法:每次跳关本源产出 ×1.3,持续 12 秒(叠乘,最多 10 层)', bonus: '故事共鸣:跳关触发率 +10%' },
   { id: 3, key: 'xiuxian', tier: '四阶', name: '修仙位面', metric: '灵气浓度', essence: '道之本源', color: '#2DD4BF', accent: '#FFD27A',
     lore: '大道无情,天道有功。修士以百年为一步,而你有世界树。',
-    rule: '大道预算:转生结晶 ×1.5', bonus: '道基:每次转生返还 50% 本源(更低回溯代价)' },
+    rule: '大道预算:转生结晶 ×1.5', bonus: '道基:转生后返还本轮 50% 本源,起始层 +100' },
 ];
-
-/** 位面规则参数(规则即数值:改这里就是松绑) */
 export const PLANE_RULES = [
-  { incomeMult: 1.00, marchMult: 1.00, autoLives: false, skipOnNarrate: 1.0, skipBonus: 0, rebirthMod: 1.0, rebirthKeep: 0, costMult: 1.00 },
-  { incomeMult: 1.00, marchMult: 1.25, autoLives: true,  skipOnNarrate: 1.0, skipBonus: 0, rebirthMod: 1.0, rebirthKeep: 0, costMult: 1.00 },
-  { incomeMult: 1.00, marchMult: 1.00, autoLives: false, skipOnNarrate: 1.3, skipBonus: 0.10, rebirthMod: 1.0, rebirthKeep: 0, costMult: 1.00 },
-  { incomeMult: 1.00, marchMult: 1.00, autoLives: false, skipOnNarrate: 1.0, skipBonus: 0, rebirthMod: 1.5, rebirthKeep: 0.5, costMult: 1.00 },
+  { prodMult: 1.0, speedMult: 1.0, autoLives: false, narrateBoost: 0,    skipMult: 1.0,  rebirthMod: 1.0, rebirthKeep: 0,   startBonus: 0,   costMult: 1.0 },
+  { prodMult: 1.0, speedMult: 1.25, autoLives: true, narrateBoost: 0,    skipMult: 1.0,  rebirthMod: 1.0, rebirthKeep: 0,   startBonus: 0,   costMult: 1.0, autoCap: 5 },
+  { prodMult: 1.0, speedMult: 1.0, autoLives: false, narrateBoost: 1.3,  skipMult: 1.1,  rebirthMod: 1.0, rebirthKeep: 0,   startBonus: 0,   costMult: 1.0 },
+  { prodMult: 1.0, speedMult: 1.0, autoLives: false, narrateBoost: 0,    skipMult: 1.0,  rebirthMod: 1.5, rebirthKeep: 0.5, startBonus: 100, costMult: 1.0 },
 ];
 export const PLANE_REBIRTH_MOD = PLANE_RULES.map((r) => r.rebirthMod);
-export const PLANE_UNLOCK_AT = [   // 前任位面锚定探索度达标即解锁下一阶通道
-  { plane: 1, needSumPct: 50 },
-  { plane: 2, needSumPct: 100 },
-  { plane: 3, needSumPct: 150 },
+export const NARRATE_STACK_CAP = 10;
+export const NARRATE_SEC = 12;
+
+// 解锁:现实位面探索度 100(锚定)→ 二阶;二阶锚定 → 三阶;三阶锚定 → 四阶
+export const PLANE_UNLOCK_AT = [
+  { plane: 1, from: 0 },
+  { plane: 2, from: 1 },
+  { plane: 3, from: 2 },
 ];
 export const EXPLORE_FULL = 100;
-/** 探索度阶梯(按该位面探索度 x):取满足条件的最高一档 */
 export const EXPLORE_TIERS = [
-  { at: 20,  prod: 0.20, crystal: 1.00, label: '本源产出 +20%' },
-  { at: 50,  prod: 0.50, crystal: 1.00, label: '本源产出 +50%' },
+  { at: 20,  prod: 0.20, crystal: 1.0,  label: '本源产出 +20%' },
+  { at: 50,  prod: 0.50, crystal: 1.0,  label: '本源产出 +50%' },
   { at: 80,  prod: 0.80, crystal: 1.15, label: '本源产出 +80%,炼化收益 +15%' },
-  { at: 100, prod: 1.00, crystal: 1.30, label: '本源产出 +100%,炼化 +30%,锚定:后台自动采集', anchor: true },
+  { at: 100, prod: 1.00, crystal: 1.30, label: '本源产出 +100%,炼化 +30%,位面锚定:后台自动采集', anchor: true },
 ];
 export function exploreTierOf(explore) {
-  let t = { at: 0, prod: 0, crystal: 1, label: '' };
+  let t = { at: 0, prod: 0, crystal: 1, label: '未勘探' };
   for (const x of EXPLORE_TIERS) if (explore >= x.at) t = x;
   return t;
 }
 export function planeUnlocked(state, p) {
   if (p === 0) return true;
-  const need = PLANE_UNLOCK_AT[p - 1]?.needSumPct ?? Infinity;
-  return (state.planeSumPct || 0) >= need;
+  const rule = PLANE_UNLOCK_AT.find((u) => u.plane === p);
+  return !!rule && (state.planes?.[rule.from]?.explore || 0) >= EXPLORE_FULL;
 }
-
-// ── 兵种(常驻推进跑道,持续生效) ──────────────────────────
-// eff: prod 本源产出(addition 进同一收益乘区);speed 推进速度;skip 跳关概率;crystal 炼化(addition)
-export const LIVES = [
-  { id: 'sprout', race: '生命', name: '萌芽苔', cost: 25,   eff: { kind: 'prod', per: 0.05 },   skill: '根系扎入跑道,产出越久越旺' },
-  { id: 'firefly',race: '生命', name: '萤火虫', cost: 120,  eff: { kind: 'speed', per: 0.04 },  skill: '沿根系迁徙,替世界树探路' },
-  { id: 'rootwalker', race: '生命', name: '根行者', cost: 900, eff: { kind: 'skip', per: 0.008 }, skill: '在层间挖掘捷径' },
-  { id: 'arbor',  race: '星穹', name: '星穹古树', cost: 3000, eff: { kind: 'prod', per: 0.10 },  skill: '远古先民所化的庇护之树' },
-  { id: 'cometmoth', race: '星穹', name: '彗星蛾', cost: 12000, eff: { kind: 'speed', per: 0.06 }, skill: '驮着树冠跨越星云' },
-  { id: 'constsign', race: '星穹', name: '星座使', cost: 8e4,  eff: { kind: 'crystal', per: 0.03 }, skill: '记录每次回溯的星象,提高炼化' },
-  { id: 'voideye', race: '虚空', name: '虚空之眼', cost: 5e5, eff: { kind: 'skip', per: 0.015 }, skill: '直视空洞,看穿层层壁垒' },
-  { id: 'entropymaw', race: '虚空', name: '熵噬之喉', cost: 4e6, eff: { kind: 'prod', per: 0.20 }, skill: '吞吐被侵蚀的本源' },
-  { id: 'lightstrider', race: '虚空', name: '光行者', cost: 3e7, eff: { kind: 'speed', per: 0.10 }, skill: '以光速掠过每一层' },
-];
-export const RACES = {
-  生命: { color: '#5FD68A', bond: '共生:已解锁 生命 兵种每 3 个 → 本源产出 ×1.25(递归)' },
-  星穹: { color: '#7FB2FF', bond: '观星:已解锁 星穹 兵种每 3 个 → 炼化收益 ×1.25(递归)' },
-  虚空: { color: '#C08BFF', bond: '凝视:已解锁 虚空 兵种每 3 个 → 跳关概率 +5%' },
-};
-export const RACE_BOND_STEP = 3;
-export const RACE_BOND_MULT = 1.25;
-export const RACE_SKIP_BONUS = 0.05;
-
-// ── 跳关标记:魔幻位面用 ───────────────────────────────
-export const NARRATE_STACK_CAP = 10;
-
-// ── 危机:侵蚀前沿 ─────────────────────────────────────
-export const CRISIS = {
-  firstAt: 90, interval: 180, countdown: 120,   // 首次 90s,此后每 180s 一次;响应窗口 120s
-  nearEnd: 0.60,                                // 侵蚀推进到 60% 进度时,前沿逼近剧情
-  penalty: 0.50, penaltySec: 60,                // 未响应:本源产出 ×0.5,持续 60s
-  reward: 0.30, rewardSec: 90,                  // 成功压制:本源产出 ×1.3,持续 90s
-  skipOnRelieve: 5,                             // 「转移前沿」:立即跳 5 层
-};
+export function currentPlaneRule(state) { return PLANE_RULES[state.currentPlane || 0]; }
 
 // ── 里世界肉鸽 ────────────────────────────────────────
+export const LIFE_ECHO_CAP = 40;   // 溯时回响:兵种等级封顶 40 再按 20% 保留
 export const RIFT = {
-  cdSec: 40, runSec: 150, energy: 20, energyPerStep: 1,
-  rules: ['现实位面', '科技位面', '魔幻位面', '修仙位面'],
-  trials: [
-    { name: '规则裂隙',   sub: '残缺的物理法则在此处断裂', need: '知识', needN: 4 },
-    { name: '誓约回廊',   sub: '誓约在此刻生效,也必须在此刻兑现', need: '誓约', needN: 4 },
-    { name: '天问之秤',   sub: '天平只称量信念的重量', need: '信念', needN: 4 },
-    { name: '灰烬法庭',   sub: '一切过错都将在此被审判', need: '裁决', needN: 5 },
-  ],
+  cooldownSec: 45, runSec: 240, energy: 12, energyPerStep: 1,
+  teamSize: 3,      // 选秀 3 选 1
+  floorsPerEnv: 5,  // 每 5 层换域
+  subFlootsPerFight: 4,
 };
+// 里世界环境(每个位面一种场景,用于 UI 命名与配色)
+export const RIFT_ENVS = [
+  { name: '灰烬回廊', desc: '灾变后的城市废墟,路灯仍在为不存在的人亮着。', color: '#5FA8D3' },
+  { name: '演算之海', desc: '无人的服务器阵列深处,数据像潮水一样涨落。', color: '#6C5CE7' },
+  { name: '镜灰王庭', desc: '碎镜拼成的王座,每个倒影都在讲述不同的故事。', color: '#C77DFF' },
+  { name: '九霄残山', desc: '漂浮的山峰残片,灵气稀薄如将灭的烛火。', color: '#2DD4BF' },
+];
 export const RULE_IDS = ['knowledge', 'oath', 'belief', 'judge'];
 export const RULE_NAMES = { knowledge: '知识', oath: '誓约', belief: '信念', judge: '裁决' };
 export const RULE_COLORS = { knowledge: '#5FA8D3', oath: '#7FB2FF', belief: '#5FD68A', judge: '#F0C060' };
-export const RIFT_TEAM_SIZE = 4;
-/** 局内结算:探索度增量 = floor(√最高层 + 1) + ⌊结算分/10⌋;本源 = 探索度增量 × 当前本源秒产 ×8 */
+export const RIFT_TEAM_SIZE = RIFT.teamSize;
 export const RIFT_ESSENCE_SECONDS = 8;
-export function riftExploreDelta(topFloor, score, cleared) {
-  const base = Math.floor(Math.sqrt(Math.max(0, topFloor)) + 1) + Math.floor(Math.max(0, score) / 10);
-  return Math.max(1, Math.round(base * (cleared ? 1.5 : 1)));
+// 里世界结算:探索度增量 = ⌊√(步数+1 + 分数/20)⌋,通关 ×1.5(与 rift.riftResult 同源)
+// 探索度增量:通关 ⌊6 + 分/50⌋,失败 ⌊3 + 分/60⌋(失败也有价值)
+export function riftExploreDelta(steps, score, cleared) {
+  const sc = Math.max(0, score);
+  return cleared ? Math.floor(6 + sc / 50) : Math.floor(3 + sc / 60);
 }
-export function riftShard(score, cleared) { return Math.max(2, Math.floor(score * (cleared ? 0.6 : 0.4))); }
+export const RIFT_PLANE_START = [null, { knowledge: 2 }, { belief: 2 }, { judge: 2 }];   // 每位面在里世界的开局属性
 
 // ── 挂机支线(锚定位面后台采集) ─────────────────────────
-export const ANCHOR_COLLECT_SEC = 60;          // 每 60 秒采集一次
-export const ANCHOR_RATE = 0.02;               // 每次 = 当前本源秒产 ×2%(0 秒开始,连点无效)
+export const ANCHOR_COLLECT_SEC = 60;
+export const ANCHOR_RATE = 0.02;
 
 // ── 离线 ────────────────────────────────────────────
 export const OFFLINE = { capSec: 8 * 3600, eff: 0.6 };
 
 // ── 事件节奏 ─────────────────────────────────────────
 export const EVENT = {
-  civSec: 70,            // 文明事件:平均每 70 秒(现实位面)
-  crisisHintSec: 6,      // 前沿逼近提示
+  lifeKeep: 0.2,          // 溯时回响:转生后兵种等级保留 20%(不超过 LIFE_ECHO_CAP 级;修仙位面 ×2)
+  civSec: 75,
+  crisisHintSec: 6,
+  autoRebirthDefault: 20,
 };
-
-// ── 小工具 ───────────────────────────────────────────
-function clamp01(v, hi) { return Math.max(0, Math.min(hi, Number(v) || 0)); }

+ 79 - 0
js/events-data.js

@@ -0,0 +1,79 @@
+// 内容数据:4 类事件、文明事件链、里世界怪物/奇遇/圣所。
+// 结构可扩展:新增事件只需向数组追加对象。署名:FmodeCode
+
+// ── 危机事件(空洞侵蚀前沿,倒计时压力) ───────────────────
+// options 的 apply 由 state 层执行:{ effect: 'relieve' | 'brace' | 'hold' }
+export const CRISIS_EVENTS = [
+  {
+    id: 'front_wave', title: '侵蚀前沿逼近', tag: '危机',
+    text: '空洞的侵蚀前沿突然加速,灰白色的虚无吞掉了两层根系。树冠上的灯一盏一盏熄灭。',
+    options: [
+      { label: '转移前沿(消耗本源)', hint: `消耗当前本源 25%,立即跳跃 ${5} 层`, effect: 'relieve' },
+      { label: '以根系硬抗', hint: '本源产出 ×1.5 持续 45 秒,随后 ×0.5 持续 60 秒', effect: 'brace' },
+      { label: '暂时退让', hint: '本轮层数 −5,本源产出 ×0.5 持续 60 秒', effect: 'hold' },
+    ],
+  },
+  {
+    id: 'static_rain', title: '静默之雨', tag: '危机',
+    text: '没有声音的雨落了下来。被淋到的根须正在失去颜色——虚空的规则在向主世界渗漏。',
+    options: [
+      { label: '点燃树冠驱散', hint: '消耗本源 15%,获得 90 秒 ×1.3 产出', effect: 'relieve' },
+      { label: '以根系硬抗', hint: '本源产出 ×1.5 持续 45 秒,随后 ×0.5 持续 60 秒', effect: 'brace' },
+      { label: '暂时退让', hint: '本轮层数 −5,本源产出 ×0.5 持续 60 秒', effect: 'hold' },
+    ],
+  },
+  {
+    id: 'void_tide', title: '空洞之潮', tag: '危机',
+    text: '远处传来潮水声,但你清楚那并不是水——是规则成片崩塌时发出的响动。',
+    options: [
+      { label: '逆转潮头', hint: '消耗本源 40%,跳 10 层并清除惩罚', effect: 'relieve' },
+      { label: '以根系硬抗', hint: '本源产出 ×1.5 持续 45 秒,随后 ×0.5 持续 60 秒', effect: 'brace' },
+      { label: '暂时退让', hint: '本轮层数 −8,本源产出 ×0.5 持续 60 秒', effect: 'hold' },
+    ],
+  },
+];
+
+// ── 文明事件(现实位面叙事链,推进文明等级) ──────────────
+// effect: 'progress' 推进文明;'boost' 短时产出;'explore' 加探索度;'future' 下一次文明事件更早
+export const CIV_EVENTS = [
+  { id: 'radio', stage: 0, title: '第一束电波', text: '灾变前夜,有人把最后一条广播发向宇宙:“这里曾有人类。”世界树记住了这段频率。',
+    opts: [
+      { label: '把电波刻进年轮', hint: '文明 +1,本源产出 ×1.2 持续 60 秒', effect: 'boost' },
+      { label: '记录坐标与观测', hint: '文明 +1,探索度 +3', effect: 'explore' },
+    ] },
+  { id: 'nuclear', stage: 1, title: '可控核聚变', text: '在根系深处,第一颗人造太阳被点亮。世界树第一次不再依赖太阳。',
+    opts: [
+      { label: '全力供能', hint: '文明 +2,本源产出 ×1.3 持续 90 秒', effect: 'boost' },
+      { label: '研究护盾理论', hint: '文明 +2,探索度 +5', effect: 'explore' },
+    ] },
+  { id: 'quantum', stage: 1, title: '量子纠缠阵列', text: '两个粒子跨越光年保持着联系,像一棵树的根与叶。',
+    opts: [
+      { label: '搭建信息网', hint: '文明 +2,探索度 +6', effect: 'explore' },
+      { label: '加速研究', hint: '文明 +2,下一次文明事件更快到来', effect: 'future' },
+    ] },
+  { id: 'dyson', stage: 2, title: '戴森云初建', text: '一层薄薄的镜面环开始在恒星外围合拢,世界树的叶脉接入其中。',
+    opts: [
+      { label: '完全展开', hint: '文明 +3,本源产出 ×1.5 持续 90 秒', effect: 'boost' },
+      { label: '留作观测', hint: '文明 +3,探索度 +8', effect: 'explore' },
+    ] },
+  { id: 'warp', stage: 3, title: '曲率航路', text: '航路不再需要用时间丈量。世界树把根须折成一道弯曲的弦。',
+    opts: [
+      { label: '全速铺路', hint: '文明 +3,本源产出 ×1.5 持续 90 秒', effect: 'boost' },
+      { label: '标定空洞边缘', hint: '文明 +3,探索度 +10', effect: 'explore' },
+    ] },
+  { id: 'vacuum', stage: 4, title: '真空零点能', text: '有人在真空里听见了低语:那是虚空在模仿我们的心跳。',
+    opts: [
+      { label: '分离借力', hint: '文明 +4,本源产出 ×1.6 持续 90 秒', effect: 'boost' },
+      { label: '绘制空洞地图', hint: '文明 +4,探索度 +12', effect: 'explore' },
+    ] },
+];
+
+// ── 里程碑播报(转生 / 逃逸节点 / 首次锚定) ──────────────
+export const MILESTONES = {
+  firstRebirth: { title: '回溯锚点建立', text: '时间在你手中打了个结。你回到了灾变前的那一瞬——但这一次,你记得一切。' },
+  planeAnchor: (name) => ({ title: `位面锚定 · ${name}`, text: `时空裂缝在这一位面留下永久坐标。勘探队已驻守,将对位面进行后台自动采集。` }),
+  chapter: (title) => ({ title: `主线里程碑 · ${title}`, text: `世界树穿过了又一道边界。空洞在你身后合拢,而你已看见下一段星空。` }),
+  escape: { title: '冲出空洞', text: '最后一层根系伸向空洞之外。那里没有侵蚀,没有倒计时,只有一片安静的、未被命名的星空。' },
+  epoch: (n) => ({ title: `轮回纪元 · 第 ${n} 次`, text: '时间线再次弯折。旧的结晶在你掌心变冷,新的世界树在废墟上发芽。' }),
+};
+

+ 156 - 100
js/formulas.js

@@ -1,137 +1,193 @@
-// 公式层:由存档状态组装运行时乘区,供 UI / Canvas / 测试复用(纯函数)
+// 公式层:由存档状态组装运行时乘区,供 UI / Canvas / 测试复用(纯函数,无副作用)。
+// 与 GDD.md「数值表」逐条对应。署名:FmodeCode
 import * as C from './config.js';
 
-/**
- * 计算当前全部乘区与速率。
- * @param {object} state 完整存档(见 save.js)
- * @param {object} [over] 可覆盖瞬间值(如危机 buff 用)
- */
-export function computeStats(state) {
-  const p = state.currentPlane ?? 0;
-  const rule = C.PLANE_RULES[p];
-  const lv = state.lives || {};
-  const layer = state.layer || 0;
+const nowSec = () => Date.now() / 1000;
+
+/** 本轮起始层 F(种子的起点) */
+export function F0(state) {
+  return C.earlyLayer(state.maxLayerRound || 0, C.PLANE_RULES[state.currentPlane || 0]);
+}
+
+/** 推进基准(米魔卡点):前 15 层 ×1;之后每深入 1 层,单层推进时间 ×1.063(封顶 ×15) */
+export const GM_GRACE = 15;
+export const GM_EPS = 0.01;
+export function marchBase(layer, start) {
+  // 推进基准 gm(“米魔”卡点):D = L − F
+  //  gm = D^1.5(能量谷包络):推进时间 ∝ √D,即层数 ∝ 推进量的 2/3 次方——每突破一格都需要速度乘区跟上
+  //  跳关把推进量按时间乘区放大:层数对时间乘区的幂次 = 1.5(≈ 任务书“逃逸进度 ^1.5”)
+  const D = Math.max(0, layer - (start || 0));
+  return Math.pow(Math.max(1, D), 1.5);
+}
 
-  // 兵种技能(独立乘区)
-  let skillProd = 1, skillSpeed = 1, skillSkip = 0, skillCrystal = 1;
+/** 兵种技能与“已解锁兵种数”(用于羁绊 / 炼化乘区)——供 stats 与 UI 复用 */
+export function lifeSkill(state) {
+  const lv = state.lives || {};
+  let prod = 1, speed = 1, skip = 0, crystal = 1;
   const byRace = { 生命: 0, 星穹: 0, 虚空: 0 };
+  let total = 0;
   for (const l of C.LIVES) {
-    const level = lv[l.id] || 0;
-    if (!level) continue;
+    const n = lv[l.id] || 0;
+    if (!n) continue;
     byRace[l.race]++;
-    switch (l.eff.kind) {
-      case 'prod': skillProd *= 1 + l.eff.per * level; break;
-      case 'speed': skillSpeed *= 1 + l.eff.per * level; break;
-      case 'skip': skillSkip += l.eff.per * level; break;
-      case 'crystal': skillCrystal *= 1 + l.eff.per * level; break;
-    }
+    total += n;
+    const strength = l.eff.per * n;
+    if (l.eff.kind === 'prod') prod *= 1 + strength;
+    else if (l.eff.kind === 'speed') speed *= 1 + strength;
+    else if (l.eff.kind === 'skip') skip += strength;
+    else if (l.eff.kind === 'crystal') crystal *= 1 + strength;
   }
-
-  // 种族羁绊
-  const stacks = {
-    生命: Math.floor(byRace.生命 / C.RACE_BOND_STEP),
-    星穹: Math.floor(byRace.星穹 / C.RACE_BOND_STEP),
-    虚空: Math.floor(byRace.虚空 / C.RACE_BOND_STEP),
+  const stacks = {};
+  for (const r of Object.keys(C.RACES)) stacks[r] = C.raceStacks(r, byRace[r]);
+  return {
+    prod, speed, skip, crystal, byRace, total, stacks,
+    bondProd: Math.pow(C.RACE_BOND_MULT, stacks.生命),
+    bondCrystal: Math.pow(C.RACE_BOND_MULT, stacks.星穹),
+    bondSkip: Math.min(2, C.RACE_SKIP_BONUS * stacks.虚空),
   };
-  const bondProd = Math.pow(C.RACE_BOND_MULT, stacks.生命);
-  const bondCrystal = Math.pow(C.RACE_BOND_MULT, stacks.星穹);
-  const bondSkip = C.RACE_SKIP_BONUS * stacks.虚空;
+}
+
+/** 跳关触发率(全部可加来源直接相加,封顶 60%) */
+export function skipProbOf(state, sk) {
+  const rule = C.PLANE_RULES[state.currentPlane || 0];
+  const l = sk || lifeSkill(state);
+  const raw = C.canopySkip(state.upgrades?.canopy || 0) + l.skip + l.bondSkip + (rule.skipMult - 1);
+  return Math.min(C.SKIP.cap, raw);
+}
+
+/** 炼化乘区 M(兵种技能 × 星穹羁绊 × 探索阶梯 × 跳关加成 × 自由轮回) */
+export function rebirthMOf(state, sk) {
+  const p = state.currentPlane ?? 0;
+  const l = sk || lifeSkill(state);
+  const tier = C.exploreTierOf(state.planes?.[p]?.explore || 0);
+  const skipNote = 1 + Math.min(C.REBIRTH.skipNoteCap, skipProbOf(state, l) * 0.5);
+  // 见闻:所有位面的探索度之和参与炼化乘区(可回头刷低阶位面补强主世界)
+  const insight = 1 + (state.exploreSum || 0) / 100;
+  return l.crystal * l.bondCrystal * tier.crystal * skipNote * insight * C.freedomMul(state) * C.resonanceMul(state);
+}
+
+/** 速度乘区 M_spd(不含危机、不含卡点) */
+export function speedMulOf(state) {
+  const p = state.currentPlane ?? 0;
+  const l = lifeSkill(state);
+  return C.treeSpeedMul(state.treeLv || 0) * C.rootSpeedMul(state.upgrades?.root || 0)
+    * l.speed * C.PLANE_RULES[p].speedMult;
+}
+
+/**
+ * 全部乘区与速率(GDD §6)。
+ * 本源产出/秒(本轮)= Σ_{k<L−F} 1.05^k × P_root(R) × M_prod
+ * 单层耗时 T(L) = (4+10L) × gm / M_spd;跳关后期望层耗时 = T / (1 + E[k])
+ */
+export function computeStats(state) {
+  const p = state.currentPlane ?? 0;
+  const rule = C.PLANE_RULES[p];
+  const layer = state.layer || 0;
+  const start = F0(state);
+  const now = nowSec();
+  const sk = lifeSkill(state);
+  const frozen = !!state.planeRun?.active;
 
-  // 探索度(当前位面)
   const explore = state.planes?.[p]?.explore || 0;
-  let exProd = 1, exSkip = 0, exCrystal = 1;
-  for (const t of C.EXPLORE_TIERS) {
-    if (explore >= t.at) { exProd = 1 + t.prod; exSkip = t.skip; exCrystal = t.crystal; }
-  }
+  const tier = C.exploreTierOf(explore);
 
-  // 危机即时状态
-  const now = state._now || Date.now() / 1000;
   const cr = state.crisis || {};
-  const crisisBuff = cr.buffUntil > now;
-  const crisisPenalty = cr.penaltyUntil > now;
+  const crisisBuff = (cr.buffUntil || 0) > now;
+  const crisisPenalty = (cr.penaltyUntil || 0) > now;
   const crisisMult = crisisBuff ? 1 + C.CRISIS.reward : crisisPenalty ? 1 - C.CRISIS.penalty : 1;
-  const crisisSpeed = crisisPenalty ? 1 - C.CRISIS.penalty : 1;
 
-  // 产物乘区拆分(独立相乘)
+  const narrSig = state.magic?.sigUntil > now ? state.magic.sig || 0 : 0;
+  const narrate = Math.pow(rule.narrateBoost || 1, Math.min(C.NARRATE_STACK_CAP, narrSig));
+
+  // ── 产出乘区(独立相乘)
   const mults = {
-    layer: C.multLayer(layer),                 // 世界树层数 ×(1+0.02L)
-    root: C.multRoot(state.upgrades.root || 0),// 根须 ×(1+0.05R)
-    erosion: C.erosionMult(layer),             // 侵蚀前沿 ×1.15^L
-    creature: C.multCreature(Object.values(lv)),// 兵种总等级 ×(1+0.08Σ)
-    bond: bondProd,                            // 生命羁绊
-    skill: skillProd,                          // 兵种技能
-    crystalLvl: C.multCrystal(state.crystalLvl || 0), // 心智结晶
-    relic: C.multRelic(state.relics?.length || 0),
-    rebirth: C.multRebirth(state.rebirths || 0),
+    tree: C.treeProdMul(state.treeLv || 0),
+    blood: C.multRebirth(state.rebirths || 0),
     explore: C.multExploration(explore),
+    creature: C.multCreature(sk.total),
+    bond: sk.bondProd,
+    relic: C.relicMul(state.relics?.length || 0),
+    freedom: C.freedomMul(state),
     plane: rule.prodMult,
     crisis: crisisMult,
+    narrate,
   };
-  const prod = mults.layer * mults.root * mults.erosion * mults.creature * mults.bond * mults.skill
-    * mults.crystalLvl * mults.relic * mults.rebirth * mults.explore * mults.plane * mults.crisis;
-
-  const base = C.birthRateRaw(layer);
-
-  // 寻路:每秒推进 = √(1.15^L)/3 × 兵种加速 × 技能 × 心智结晶
-  const speedMul = mults.creature * skillSpeed * mults.crystalLvl * crisisSpeed * (state.currentPlane === 1 ? 1.1 : 1);
-  const layersPerSec = Math.sqrt(mults.erosion) / C.MARCH.baseSecPerLayer * speedMul;
-
-  // 跳关
-  const canopy = (state.upgrades.canopy || 0) * 0.25;
-  const skipP = Math.min(0.95, canopy + skillSkip + bondSkip + exSkip + rule.skipBonus);
+  const prodMul = Object.values(mults).reduce((a, b) => a * b, 1);
+  const rootP = C.rootProdMul(state.upgrades?.root || 0);
+  const rel = Math.max(0, layer - start);
+  const base = rel > 0 ? (Math.pow(C.ESSENCE_GROWTH, rel) - 1) / Math.log(C.ESSENCE_GROWTH) : 0;
+  const prodRaw = base * rootP * prodMul;
+
+  // ── 推进速度
+  const gm = marchBase(layer, start);
+  const speedMul = speedMulOf(state) * (crisisPenalty ? 1 - C.CRISIS.penalty : 1);
+  const layerSec = (C.visitTime(layer) * gm) / speedMul;
+  const layersPerSec = speedMul / (C.visitTime(layer) * gm);
+
+  const skipP = skipProbOf(state, sk);
   const skipExp = C.skipExpectation(skipP);
+  const timeMul = 1 + skipExp;
 
-  // 转生
-  const reward = estimateRebirth(state, { skillCrystal, bondCrystal, exCrystal });
+  const rebirthM = rebirthMOf(state, sk);
+  const reward = rebirthEstimate(state, rebirthM);
 
   return {
-    plane: p, rule, base, prod, mults, bondProd, bondCrystal, bondSkip,
-    skillProd, skillSpeed, skillSkip, skillCrystal,
-    explore, exProd, exSkip, exCrystal,
-    layersPerSec, speedMul, skipP, skipExp,
-    reward, crisisBuff, crisisPenalty,
+    plane: p, rule, start, rel, base, rootP, prodMul, mults, frozen,
+    prodRaw, prod: frozen ? 0 : prodRaw,
+    creatureLv: sk.total, skills: sk, tier, explore,
+    gm, speedMul, layerSec, layersPerSec, minutesPerLayer: (layerSec * timeMul) / 60,
+    skipP, skipExp, timeMul,
+    rebirthM, reward, rebirthCost: C.rebirthCost(state.maxLayerRound || 0),
+    crisisBuff, crisisPenalty, crisisMult, narrate, narrSig, anchored: explore >= C.EXPLORE_FULL,
   };
 }
 
-/** 转生结晶预估(GDD 数值表 §6.4) */
-export function estimateRebirth(state, extra) {
+/** 单次炼化可得结晶(含衰减 / 自由轮回叠加)。state.rebirth() 使用同一函数:UI 预期 = 实得 */
+export function rebirthEstimate(state, M) {
   const p = state.currentPlane ?? 0;
-  const ex = extra || (() => {
-    const explore = state.planes?.[p]?.explore || 0;
-    let exCrystal = 1;
-    for (const t of C.EXPLORE_TIERS) if (explore >= t.at) exCrystal = t.crystal;
-    return { skillCrystal: 1, bondCrystal: 1, exCrystal };
-  })();
-  const skipBonus = Math.min(0.5, (state.stats?.peakSkipP || 0) * 0.5);
-  return C.rebirthReward({
+  const mm = M ?? rebirthMOf(state);
+  const base = C.rebirthReward({
     maxLayer: state.maxLayerRound || 0,
-    crystalSkill: ex.skillCrystal,
-    exploreCrystal: ex.exCrystal,
-    bondCrystal: ex.bondCrystal,
-    relicCount: state.relics?.length || 0,
-    skipBonus,
+    exploreSum: state.exploreSum || 0,
+    incomeMul: mm,
     ruleMod: C.PLANE_REBIRTH_MOD[p] || 1,
   });
+  if (state.planeRun && state.planeRun.state !== 'result') return 0;   // 里世界中主世界冻结:不可回溯
+  return Math.max(1, base);
 }
 
-/** 升级成本:基础 × 位面规则 × (1 − 茎干折扣) */
-export function upgradeCost(state, kind, stats) {
-  const lvl = kind === 'stem' ? state.layer : state.upgrades[kind];
-  const ruleMult = (stats || computeStats(state)).rule.costMult;
-  return Math.ceil(C.costOf(kind, lvl) * ruleMult);
+/** 本轮升级成本 / 批量成本 */
+export function upgradeCost(state, kind) {
+  const rule = C.PLANE_RULES[state.currentPlane || 0];
+  return Math.ceil(C.costOf(kind, state.upgrades?.[kind] || 0) * rule.costMult);
 }
-
-/** 兵种成本 */
-export function lifeCost(state, lifeId, stats) {
+export function upgradeBatchCost(state, kind, n) {
+  const rule = C.PLANE_RULES[state.currentPlane || 0];
+  return Math.ceil(C.batchCost(kind, state.upgrades?.[kind] || 0, n) * rule.costMult);
+}
+/** 兵种升级成本(下一级) */
+export function lifeCost(state, lifeId, atLevel) {
   const def = C.LIVES.find((l) => l.id === lifeId);
-  const level = state.lives?.[lifeId] || 0;
-  const ruleMult = (stats || computeStats(state)).rule.costMult;
-  if (level === 0) return Math.ceil(def.cost * ruleMult);
-  return Math.ceil(C.lifeCostOf(def.cost, level + 1) * ruleMult);
+  const n = atLevel ?? (state.lives?.[lifeId] || 0);
+  const rule = C.PLANE_RULES[state.currentPlane || 0];
+  return Math.ceil(C.lifeCostOf(def.cost, n + 1) * rule.costMult);
+}
+export function lifeUnlocked(state, idx) {
+  if (idx === 0) return true;
+  return (state.lives?.[C.LIVES[idx - 1].id] || 0) >= 3;
 }
 
-/** 时间结晶 → 心智结晶等级成本 */
-export function crystalLvCost(state) { return Math.ceil(C.crystalLevelCost(state.crystalLvl || 0)); }
+/** 永久投资成本(时间结晶) */
+export function permCost(state, kind) {
+  if (kind === 'stem' || kind === 'tree') return C.treeCost(state.treeLv || 0);
+  if (kind === 'relic') return C.relicCost(state.relics?.length || 0);
+  return Infinity;
+}
+
+/** 转生后起始层 */
+export function rebirthFloor(state) {
+  return C.earlyLayer(Math.max(state.maxLayerRound || 0, state.layer || 0), C.PLANE_RULES[state.currentPlane || 0]);
+}
 
-/** 转生后新的层数(基石深度快照) */
-export function rebirthFloor(state) { return C.snapshotFloor(state.maxLayerEver || 0); }
+/** 主线逃逸进度(0~1):连续空间里“抵达的层数 / 1000” */
+export function escapeProgress(state) { return Math.min(1, (state.layer || 0) / C.TOTAL_LAYERS); }

+ 45 - 0
js/icons.js

@@ -0,0 +1,45 @@
+// 手绘 SVG 图标(线性、矢量、可缩放,无外部依赖)。署名:FmodeCode
+const S = (inner, vb = '0 0 32 32') => `<svg viewBox="${vb}" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true">${inner}</svg>`;
+
+export const I = {
+  tree: (c = '#2fae6b') => S(`<path d="M16 29V15" stroke="${c}" stroke-width="2.2" stroke-linecap="round"/>
+    <path d="M16 21 10 16M16 19l6-5M16 24l-4-3M16 23l4-2" stroke="${c}" stroke-width="1.8" stroke-linecap="round"/>
+    <circle cx="10" cy="16" r="2.6" fill="#fff" stroke="${c}" stroke-width="1.8"/><circle cx="22" cy="14" r="2.6" fill="#fff" stroke="${c}" stroke-width="1.8"/>
+    <circle cx="12" cy="21" r="1.8" fill="${c}"/><circle cx="20" cy="21" r="1.8" fill="${c}"/><path d="M7 29h18" stroke="#98a3b3" stroke-width="1.6" stroke-linecap="round"/>`),
+  canopy: (c = '#b08427') => S(`<path d="M16 28V17" stroke="#6f7b8e" stroke-width="2" stroke-linecap="round"/>
+    <path d="M6 14a10 10 0 0 1 20 0" stroke="${c}" stroke-width="2.2" stroke-linecap="round"/>
+    <path d="M10 14a6 6 0 0 1 12 0" stroke="${c}" stroke-width="1.8" stroke-linecap="round"/>
+    <circle cx="24" cy="24" r="2" fill="${c}"/><circle cx="27" cy="19" r="1.3" fill="${c}"/><circle cx="21" cy="27" r="1.2" fill="${c}"/>`),
+  sprout: (c = '#5FD68A') => S(`<path d="M16 28V16" stroke="${c}" stroke-width="2.2" stroke-linecap="round"/>
+    <path d="M16 18c-5 0-8-3-8-7 4 0 8 2 8 7Z" fill="#dcf5e6" stroke="${c}" stroke-width="1.6" stroke-linejoin="round"/>
+    <path d="M16 16c5 0 8-3 8-7-4 0-8 2-8 7Z" fill="#fff" stroke="${c}" stroke-width="1.6" stroke-linejoin="round"/>`),
+  firefly: (c = '#5FD68A') => S(`<circle cx="12" cy="13" r="3" fill="${c}"/><circle cx="22" cy="20" r="2.2" fill="${c}"/><circle cx="20" cy="9" r="1.6" fill="${c}"/>
+    <path d="M9 24l4-4M23 24l-4-4M16 6v3" stroke="#6f7b8e" stroke-width="1.6" stroke-linecap="round"/>`),
+  root: (c = '#5FD68A') => S(`<path d="M16 28V10M16 14l-6 6M16 12l6 7M16 20l-4 6M16 18l4 7" stroke="${c}" stroke-width="2" stroke-linecap="round"/>`),
+  moth: (c = '#7FB2FF') => S(`<path d="M16 12c-2-5-8-8-10-4-2 3 1 9 4 10Z" fill="#e8f0ff" stroke="${c}" stroke-width="1.6" stroke-linejoin="round"/>
+    <path d="M16 12c2-5 8-8 10-4 2 3-1 9-4 10Z" fill="#e8f0ff" stroke="${c}" stroke-width="1.6" stroke-linejoin="round"/>
+    <path d="M16 12v10M14 8l-2-2M18 8l2-2" stroke="${c}" stroke-width="1.6" stroke-linecap="round"/>`),
+  sign: (c = '#7FB2FF') => S(`<circle cx="16" cy="16" r="11" stroke="${c}" stroke-width="1.8"/><circle cx="20" cy="11" r="2.4" fill="${c}"/><circle cx="12" cy="17" r="1.6" fill="${c}"/><circle cx="21" cy="20" r="1.2" fill="${c}"/><path d="M6 16h20M16 6v20" stroke="#d7e3fa" stroke-width="1"/>`),
+  eye: (c = '#C08BFF') => S(`<path d="M4 16s5-8 12-8 12 8 12 8-5 8-12 8S4 16 4 16Z" stroke="${c}" stroke-width="1.9" stroke-linejoin="round"/><circle cx="16" cy="16" r="3.6" fill="${c}"/><circle cx="17.4" cy="14.6" r="1.1" fill="#fff"/>`),
+  maw: (c = '#C08BFF') => S(`<path d="M6 10c6 6 14 6 20 0" stroke="${c}" stroke-width="2" stroke-linecap="round"/><path d="M6 10 9 16 12 11 15 17 18 11 21 16 26 10" stroke="${c}" stroke-width="1.6" stroke-linejoin="round"/><path d="M8 22c4 3 12 3 16 0" stroke="#98a3b3" stroke-width="1.6" stroke-linecap="round"/>`),
+  strider: (c = '#C08BFF') => S(`<circle cx="16" cy="9" r="3" fill="${c}"/><path d="M16 12v7M16 14l-5 3M16 14l5 3M16 19l-4 8M16 19l4 8" stroke="${c}" stroke-width="2" stroke-linecap="round"/>`),
+  crystal: (c = '#b08427') => S(`<path d="M16 4 25 12 20 28h-8L7 12 16 4Z" stroke="${c}" stroke-width="1.9" stroke-linejoin="round" fill="#fdf6e6"/><path d="M16 4v24M7 12l9 5 9-5" stroke="${c}" stroke-width="1.3" stroke-linejoin="round"/>`),
+  seed: (c = '#b08427') => S(`<path d="M16 27c-6-4-8-10-5-15 3-5 9-5 11-2 3 4-1 13-6 17Z" fill="#fdf6e6" stroke="${c}" stroke-width="1.8" stroke-linejoin="round"/><path d="M16 24C15 18 16 14 19 11" stroke="${c}" stroke-width="1.4" stroke-linecap="round"/>`),
+  star: (c = '#b08427') => S(`<path d="m16 5 3 7 7 1-5 5 1 7-6-3-6 3 1-7-5-5 7-1 3-7Z" stroke="${c}" stroke-width="1.8" stroke-linejoin="round" fill="#fdf6e6"/>`),
+  gear: (c = '#b08427') => S(`<circle cx="16" cy="16" r="5" stroke="${c}" stroke-width="1.9"/><path d="M16 5v4M16 23v4M5 16h4M23 16h4M8.2 8.2l2.8 2.8M21 21l2.8 2.8M8.2 23.8 11 21M21 11l2.8-2.8" stroke="${c}" stroke-width="1.9" stroke-linecap="round"/>`),
+  rune: (c = '#b08427') => S(`<rect x="7" y="5" width="18" height="22" rx="2" stroke="${c}" stroke-width="1.8" fill="#fdf6e6"/><path d="M12 11h8M12 15h6M12 19h8M12 23h4" stroke="${c}" stroke-width="1.5" stroke-linecap="round"/>`),
+  hourglass: (c = '#b08427') => S(`<path d="M9 5h14M9 27h14M10 5c0 7 12 7 12 11s-12 4-12 11M22 5c0 7-12 7-12 11s12 4 12 11" stroke="${c}" stroke-width="1.8" stroke-linecap="round"/>`),
+  leaf: (c = '#b08427') => S(`<path d="M25 7C13 7 7 13 8 22c9 1 16-5 17-15Z" fill="#fdf6e6" stroke="${c}" stroke-width="1.8" stroke-linejoin="round"/><path d="M8 24c4-5 8-8 13-11" stroke="${c}" stroke-width="1.5" stroke-linecap="round"/>`),
+  orbit: (c = '#b08427') => S(`<circle cx="16" cy="16" r="4" fill="#fdf6e6" stroke="${c}" stroke-width="1.8"/><ellipse cx="16" cy="16" rx="12" ry="5" stroke="${c}" stroke-width="1.5" transform="rotate(-25 16 16)"/><circle cx="26" cy="9" r="1.8" fill="${c}"/>`),
+  void: (c = '#b08427') => S(`<circle cx="16" cy="16" r="11" stroke="${c}" stroke-width="1.8"/><path d="M16 5v22M5 16h22" stroke="${c}" stroke-width="1.3"/><path d="M9 9l14 14" stroke="#fff" stroke-width="1" opacity=".4"/>`),
+  flag: () => S(`<path d="M9 28V5" stroke="#121a2b" stroke-width="2.2" stroke-linecap="round"/><path d="M10 6h13l-3 5 3 5H10Z" fill="#2fae6b"/>`),
+  rift: () => S(`<path d="M18 4 9 17h6l-3 11 11-16h-7l2-8Z" stroke="#6c5ce7" stroke-width="1.9" stroke-linejoin="round" fill="#f0ecfb"/>`),
+  sword: (c = '#6f7b8e') => S(`<path d="M6 26 22 8l4-4-1 6L9 25" stroke="${c}" stroke-width="2" stroke-linejoin="round"/><path d="M6 20l6 6M4 28l3-3" stroke="${c}" stroke-width="2" stroke-linecap="round"/>`),
+  calendar: () => S(`<rect x="5" y="7" width="22" height="20" rx="3" stroke="currentColor" stroke-width="1.8"/><path d="M5 12h22M11 4v6M21 4v6" stroke="currentColor" stroke-width="1.8" stroke-linecap="round"/>`),
+  coin: () => S(`<circle cx="16" cy="16" r="11" stroke="currentColor" stroke-width="1.8"/><path d="M12 12h8M12 20h8M16 9v14" stroke="currentColor" stroke-width="1.8" stroke-linecap="round"/>`),
+};
+
+/** 遗物 id → 图标 */
+export const relicIcon = (id, c = '#b08427') => (I[id] ? I[id](c) : I.star(c));
+/** 兵种 id → 图标 */
+export const lifeIcon = (id) => (I[id] && I[id]('#5FD68A')) || I.tree();

+ 56 - 0
js/main.js

@@ -0,0 +1,56 @@
+// 入口:读档(含迁移 / 离线结算)→ 启动 UI。署名:FmodeCode
+import * as C from './config.js';
+import * as S from './state.js';
+import { App } from './ui.js';
+
+function boot() {
+  let loaded = null;
+  try { loaded = S.save.load(localStorage); } catch (e) { loaded = null; }
+  let state = loaded ? loaded.state : S.newState();
+  // 极早期存档 / 缺省字段补救:保证 UI 依赖的字段存在
+  if (state && typeof state === 'object') {
+    const d = S.newState();
+    for (const k of Object.keys(d)) if (state[k] === undefined) state[k] = d[k];
+    for (const k of Object.keys(d.upgrades)) if (state.upgrades[k] === undefined) state.upgrades[k] = 0;
+    if (!Array.isArray(state.planes) || state.planes.length < 4) state.planes = d.planes;
+    if (!state.stats) state.stats = d.stats;
+    if (!state.flags) state.flags = {};
+    if (!state.round) state.round = { refines: 0 };
+    if (!state.crisis) state.crisis = d.crisis;
+    if (!state.magic) state.magic = d.magic;
+  }
+  let rift = loaded ? loaded.rift : null;
+  // 里世界对象需带 active 标记以冻结主世界
+  if (rift && rift.run && rift.run.state !== 'result') { rift.run.active = true; }
+  else rift = null;
+  let offline = null;
+  try {
+    if (loaded && !(rift && rift.run)) {
+      const gap = (Date.now() - loaded.savedAt) / 1000;
+      offline = S.applyOffline(state, gap, null);
+    }
+  } catch (e) { offline = null; }
+  const app = new App(state, rift);
+  window.__wt = app;   // 便于调试与自动化验收(只读)
+  app.renderAll();
+  app._lastTickAt = Date.now();
+  if (offline && !offline.skipped) app.pushDialog({ kind: 'offline', data: offline });
+  app.log('世界树已苏醒:空洞的侵蚀仍在继续。', 'mile');
+  S.save.write(localStorage, state, rift);
+  // 页面重新可见 / 获得焦点时补算离线
+  document.addEventListener('visibilitychange', () => {
+    if (!document.hidden) { app._lastTickAt = app._lastTickAt || Date.now(); }
+  });
+  window.addEventListener('focus', () => {
+    const now = Date.now();
+    const gap = (now - (app._lastTickAt || now)) / 1000;
+    app._lastTickAt = now;
+    if (gap > 60 && !state.escaped && !(rift && rift.run)) {
+      const o = S.applyOffline(state, gap, null);
+      if (o && !o.skipped) { app.pushDialog({ kind: 'offline', data: o }); app.renderAll(); }
+    }
+  });
+}
+
+if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', boot);
+else boot();

+ 255 - 0
js/march.js

@@ -0,0 +1,255 @@
+// 连续行军 Canvas:只读 state 快照(由 main.js 传入),不持有游戏状态。
+// 场景:深空 → 星云 → 旋臂 → 星系边界 → 空洞 → 空洞之外;树带向左行进,跳关时世界整体跃迁。署名:FmodeCode
+const SCENES = [
+  { bg0: '#121a2b', bg1: '#1b2a44', star: '#dfe8f5', neb: 'rgba(95,168,211,.10)', tree: '#5FD68A', ground: '#2c4a43', label: '地球外侧 · 柯伊伯带' },
+  { bg0: '#0f1826', bg1: '#1a2745', star: '#e6eeff', neb: 'rgba(108,92,231,.12)', tree: '#7FB2FF', ground: '#2b3550', label: '太阳系边缘 · 奥尔特云' },
+  { bg0: '#16112a', bg1: '#2a1c45', star: '#f1e9ff', neb: 'rgba(199,125,255,.13)', tree: '#C77DFF', ground: '#3d2a52', label: '猎户旋臂 · 星云海' },
+  { bg0: '#0d1524', bg1: '#14213a', star: '#e3ecff', neb: 'rgba(127,178,255,.13)', tree: '#9FE7D2', ground: '#223b45', label: '银河系外缘 · 旋涡边缘' },
+  { bg0: '#0c111c', bg1: '#171b25', star: '#c9d1dd', neb: 'rgba(255,255,255,.05)', tree: '#E8D9A8', ground: '#2b2d33', label: '本星系群 · 引力潮' },
+  { bg0: '#101724', bg1: '#1f2b3d', star: '#ffffff', neb: 'rgba(47,174,107,.12)', tree: '#7BE3A6', ground: '#1f3b30', label: '空洞之外 · 未知星空' },
+];
+
+export class MarchScene {
+  constructor(canvas) {
+    this.cv = canvas;
+    this.ctx = canvas.getContext('2d', { alpha: false });
+    this.dpr = 1; this.w = 0; this.h = 0;
+    this.stars = [];
+    this.trees = [];
+    this.ties = [];
+    this.jump = 0;            // 跳关跃迁强度 0..1
+    this.offset = 0;          // 世界偏移(向左滚动的像素)
+    this.time = 0;
+    this.lastTs = 0;
+    this.running = true;
+    this.ro = null;
+    this._resize();
+    window.addEventListener('resize', () => this._resize());
+    if (typeof ResizeObserver !== 'undefined') { this.ro = new ResizeObserver(() => this._resize()); this.ro.observe(this.cv.parentElement); }
+    this._seed();
+    this._loop = this._loop.bind(this);
+    requestAnimationFrame(this._loop);
+  }
+
+  _resize() {
+    const r = this.cv.parentElement.getBoundingClientRect();
+    this.dpr = Math.min(2, window.devicePixelRatio || 1);
+    this.w = Math.max(200, Math.round(r.width));
+    this.h = Math.max(160, Math.round(r.height));
+    this.cv.width = Math.round(this.w * this.dpr);
+    this.cv.height = Math.round(this.h * this.dpr);
+    this.cv.style.width = this.w + 'px';
+    this.cv.style.height = this.h + 'px';
+    this._seed();
+  }
+
+  _seed() {
+    const rnd = (a, b) => a + Math.random() * (b - a);
+    this.stars = Array.from({ length: 90 }, () => ({ x: rnd(0, this.w), y: rnd(0, this.h * 0.72), r: rnd(0.4, 1.5), a: rnd(0.25, 0.9), sp: rnd(0.05, 0.35) }));
+    // 树带:一串“树”形状,间隔随机
+    this.trees = [];
+    let x = -40;
+    while (x < this.w + 160) {
+      const s = rnd(0.65, 1.05);
+      this.trees.push({ x, s, hue: Math.random(), sway: rnd(0, 6.28) });
+      x += rnd(54, 96) * s;
+    }
+  }
+
+  /** 每帧由外部调用:传入当前视图数据 */
+  update(view) { this.view = view; }
+
+  /** 跳关表现:整体跃迁 + 爆发光 */
+  burst(k) { this.jump = Math.min(1, this.jump + 0.45 + 0.15 * k); }
+
+  _tint(hex, a) {
+    // #rrggbb → rgba
+    const n = parseInt(hex.slice(1), 16);
+    return `rgba(${(n >> 16) & 255},${(n >> 8) & 255},${n & 255},${a})`;
+  }
+
+  _loop(ts) {
+    if (!this.running) return;
+    const dt = Math.min(0.05, (ts - (this.lastTs || ts)) / 1000);
+    this.lastTs = ts;
+    this.time += dt;
+    this._draw(dt);
+    requestAnimationFrame(this._loop);
+  }
+
+  _draw(dt) {
+    const { ctx, w, h } = this;
+    const v = this.view || {};
+    ctx.setTransform(this.dpr, 0, 0, this.dpr, 0, 0);
+    const ch = Math.max(0, Math.min(5, v.chapter || 0));
+    const sc = SCENES[ch];
+    const lo = Math.max(0, ch - 1), hi = Math.min(5, ch + 1);
+    const tCh = (v.chapter || 0) - ch;   // 章节内连续过渡(里程碑附近渐变)
+    const bg = ch;
+    const g = ctx.createLinearGradient(0, 0, 0, h);
+    g.addColorStop(0, SCENES[bg].bg0);
+    g.addColorStop(1, SCENES[bg].bg1);
+    ctx.fillStyle = g;
+    ctx.fillRect(0, 0, w, h);
+
+    // 星云带(斜向柔光)
+    ctx.save();
+    ctx.globalAlpha = 0.9;
+    const neb = ctx.createLinearGradient(0, h * 0.2, w, h * 0.55);
+    neb.addColorStop(0, 'rgba(0,0,0,0)');
+    neb.addColorStop(0.45, sc.neb);
+    neb.addColorStop(1, 'rgba(0,0,0,0)');
+    ctx.fillStyle = neb;
+    ctx.beginPath();
+    ctx.moveTo(0, h * 0.42);
+    for (let x = 0; x <= w; x += 24) ctx.lineTo(x, h * 0.42 + Math.sin(x * 0.012 + this.time * 0.15) * 16 + Math.sin(x * 0.03) * 5);
+    ctx.lineTo(w, h * 0.18); ctx.lineTo(0, h * 0.24); ctx.closePath();
+    ctx.fill();
+    ctx.restore();
+
+    const layerMul = v.layerSec ? 1 : 1;
+    const speedPx = Math.max(0, Math.min(90, 14 + 26 * (v.layersPerSec || 0))) * layerMul; // 层/秒 → 像素/秒
+    const jumpK = this.jump;
+    const camShift = jumpK * 240 * (1 - jumpK) * 3;   // 世界整体横向跃迁
+    const move = speedPx * (1 + 3 * jumpK) * dt;
+    this.offset = (this.offset + move) % 100000;
+    const jitterY = jumpK > 0 ? Math.sin(this.time * 60) * 2 * jumpK : 0;
+
+    // 星空(视差三层)
+    for (const s of this.stars) {
+      const depth = s.r * 1.4;
+      let x = s.x - this.offset * (0.04 + 0.12 * depth) - camShift * (0.1 + depth * 0.4);
+      x = ((x % (w + 20)) + w + 20) % (w + 20) - 10;
+      const a = s.a * (0.6 + 0.4 * Math.sin(this.time * 1.3 + s.x));
+      ctx.fillStyle = this._tint(sc.star, a);
+      ctx.fillRect(x, s.y, s.r, s.r);
+      if (s.r > 1.2) { // 星芒
+        ctx.fillStyle = this._tint(sc.star, a * 0.25);
+        ctx.fillRect(x - 1.5, s.y + s.r / 2 - 0.25, s.r + 3, 0.5);
+      }
+    }
+
+    // 地面(根系基座)
+    const gy = h * 0.8;
+    ctx.fillStyle = SCENES[bg].ground;
+    ctx.globalAlpha = 0.6;
+    ctx.fillRect(0, gy + 26, w, h - gy - 26);
+    ctx.globalAlpha = 1;
+    ctx.strokeStyle = this._tint(sc.star, 0.25);
+    ctx.lineWidth = 1;
+    ctx.beginPath(); ctx.moveTo(0, gy + 26); ctx.lineTo(w, gy + 26); ctx.stroke();
+
+    // 根系(地面上的曲线)
+    ctx.strokeStyle = this._tint(sc.tree, 0.35);
+    ctx.lineWidth = 1.2;
+    for (let k = 0; k < 5; k++) {
+      ctx.beginPath();
+      for (let x = -20; x <= w + 20; x += 12) {
+        const y = gy + 34 + k * 9 + Math.sin((x + this.offset * (0.6 + k * 0.1)) * 0.02 + k) * (8 - k);
+        if (x === -20) ctx.moveTo(x, y); else ctx.lineTo(x, y);
+      }
+      ctx.stroke();
+    }
+
+    // 世界树剪影:带(成排的树)
+    const speed = speedPx * (1 + 2.5 * jumpK);
+    for (const t of this.trees) {
+      let x = t.x - (this.offset * speed / Math.max(1, speedPx)) % (w + 160);
+      x = ((x % (w + 160)) + w + 160) % (w + 160) - 80;
+      const tx = x - camShift;
+      this._tree(ctx, tx, gy + 26, t.s, sc.tree, t.sway + this.time * 0.8);
+    }
+
+    // 跳关:白色跃迁线 + 光点
+    if (jumpK > 0.01) {
+      ctx.save();
+      ctx.globalAlpha = jumpK * 0.8;
+      ctx.strokeStyle = 'rgba(255,255,255,.85)';
+      for (let i = 0; i < 14; i++) {
+        const y = ((i * 61 + this.time * 400) % (h * 0.75));
+        const x = (i * 97 + this.offset * 0.3) % w;
+        ctx.lineWidth = 1 + (i % 3) * 0.5;
+        ctx.beginPath(); ctx.moveTo(x, y); ctx.lineTo(x + 60 + 120 * jumpK, y); ctx.stroke();
+      }
+      ctx.globalAlpha = jumpK * 0.35;
+      ctx.fillStyle = sc.tree;
+      ctx.fillRect(0, 0, w, h);
+      ctx.restore();
+      this.jump = Math.max(0, jumpK - dt * 2.4);
+    }
+
+    // 雾/边界:右侧空洞方向
+    const edge = ctx.createLinearGradient(w * 0.62, 0, w, 0);
+    edge.addColorStop(0, 'rgba(10,14,22,0)');
+    edge.addColorStop(1, ch >= 4 ? 'rgba(240,243,248,.18)' : 'rgba(10,14,22,.55)');
+    ctx.fillStyle = edge;
+    ctx.fillRect(w * 0.62, 0, w * 0.38, h);
+
+    // 当前层列(每 10 层一根刻度)
+    this._marks(ctx, v, gy);
+  }
+
+  _tree(ctx, x, baseY, s, color, sway) {
+    const H = 70 * s;
+    ctx.save();
+    ctx.translate(x, baseY);
+    const lean = Math.sin(sway) * 1.6;
+    ctx.strokeStyle = this._tint(color, 0.85);
+    ctx.lineWidth = 2.2 * s;
+    ctx.lineCap = 'round';
+    ctx.beginPath();
+    ctx.moveTo(0, 0);
+    ctx.quadraticCurveTo(lean, -H * 0.55, lean * 2, -H);
+    ctx.stroke();
+    // 分枝
+    ctx.lineWidth = 1.4 * s;
+    for (const [t0, dir, len] of [[0.45, -1, 14], [0.62, 1, 12], [0.78, -1, 9], [0.88, 1, 7]]) {
+      const bx = lean * (t0 * 2), by = -H * t0;
+      ctx.beginPath();
+      ctx.moveTo(bx, by);
+      ctx.quadraticCurveTo(bx + dir * len * s * 0.6, by - len * s * 0.4, bx + dir * len * s, by - len * s * 0.9);
+      ctx.stroke();
+    }
+    // 树冠:小圆+点
+    ctx.fillStyle = this._tint(color, 0.9);
+    const cx = lean * 2, cy = -H;
+    ctx.beginPath(); ctx.arc(cx, cy, 4.2 * s, 0, Math.PI * 2); ctx.fill();
+    ctx.fillStyle = this._tint(color, 0.5);
+    for (const [dx, dy] of [[-9, 4], [8, 2], [-4, -8], [6, -7], [0, 9]]) {
+      ctx.beginPath(); ctx.arc(cx + dx * s, cy + dy * s, 1.8 * s, 0, Math.PI * 2); ctx.fill();
+    }
+    // 根
+    ctx.strokeStyle = this._tint(color, 0.45);
+    ctx.lineWidth = 1.2 * s;
+    ctx.beginPath(); ctx.moveTo(0, 0); ctx.lineTo(-8 * s, 10 * s); ctx.moveTo(0, 0); ctx.lineTo(9 * s, 9 * s); ctx.stroke();
+    ctx.restore();
+  }
+
+  _marks(ctx, v, gy) {
+    const { w, h } = this;
+    const layer = v.layerFloat || 0;
+    const base = Math.floor(layer / 10) * 10;
+    const frac = (layer - base) / 10;
+    ctx.font = '10px "SF Mono", Menlo, monospace';
+    ctx.textAlign = 'center';
+    for (let i = -1; i < 8; i++) {
+      const L = base + i * 10;
+      if (L < 0) continue;
+      const x = w * 0.18 + (i - frac) * (w * 0.11) + (1 - frac) * 0;
+      if (x < -10 || x > w + 10) continue;
+      const xx = w * 0.18 + (i - frac) * (w * 0.11);
+      const major = L % 50 === 0;
+      ctx.strokeStyle = major ? 'rgba(255,255,255,.55)' : 'rgba(255,255,255,.22)';
+      ctx.lineWidth = major ? 1.4 : 1;
+      ctx.beginPath(); ctx.moveTo(xx, gy + 4); ctx.lineTo(xx, gy + (major ? 20 : 12)); ctx.stroke();
+      ctx.fillStyle = major ? 'rgba(255,255,255,.75)' : 'rgba(255,255,255,.38)';
+      ctx.fillText(String(L), xx, gy + (major ? 32 : 24));
+    }
+    // 当前层指针
+    const px = w * 0.18;
+    ctx.fillStyle = 'rgba(255,255,255,.95)';
+    ctx.beginPath(); ctx.moveTo(px, gy + 26); ctx.lineTo(px - 4, gy + 32); ctx.lineTo(px + 4, gy + 32); ctx.closePath(); ctx.fill();
+  }
+
+  destroy() { this.running = false; }
+}

+ 254 - 0
js/rift.js

@@ -0,0 +1,254 @@
+// 里世界肉鸽:规则引擎(纯数据,不碰 DOM)。隔离局内,不继承主世界永久资源。
+// 一局 = 6 场遭遇(战斗/精英/奇遇/圣所),约 1~5 分钟。署名:FmodeCode
+import * as C from './config.js';
+import { mulberry32, clamp } from './util.js';
+
+export const RULES = ['knowledge', 'oath', 'belief', 'judge'];
+export const RULE_NAME = { knowledge: '知识', oath: '誓约', belief: '信念', judge: '裁决' };
+export const RULE_DESC = {
+  knowledge: '知识 → 攻击:每点攻击 +1.5',
+  oath: '誓约 → 生命:每点最大生命 +9',
+  belief: '信念 → 生命:每点最大生命 +9',
+  judge: '裁决 → 攻击:每点攻击 +2',
+};
+export const ENCOUNTERS = 6;         // 一局推进 6 步,第 6 步为终局
+export const CAP = { knowledge: 30, oath: 30, belief: 30, judge: 30 };
+export const STARTER = 1;            // 每项规则起步 1 点
+
+const MONSTERS = ['灰烬守卫', '蚀影猎犬', '残响歌者', '残影巡游者', '无人电梯', '空洞低语', '镜像拷问者'];
+const ELITES = ['蚀壳巨像', '规则提灯人', '终末回声', '零点行者'];
+const BOSSES = ['灰烬王座', '演算核心', '镜之城主人', '天劫化身'];
+export const TAUNTS = [
+  '你不该记得上一次。', '规则站在我这边。', '树根不会再长出来了。', '你的誓约很轻。', '这一次也一样的。', '尘埃也想逃出去吗?',
+];
+
+const EVENTS = [
+  { id: 'pool', title: '断桥下的光池', text: '桥塌了一半,水面倒映出不是你的脸。光池里漂着一枚还在跳动的规则碎片。',
+    opts: [
+      { label: '伸手打捞', hint: '获得 2 点随机属性,损失 15% 生命', apply: { rules: 2, dmg: 0.15 } },
+      { label: '绕路前行', hint: '恢复 25% 生命,能量 +2', apply: { heal: 0.25, energy: 2 } },
+    ] },
+  { id: 'altar', title: '无名的祭坛', text: '祭坛上刻着:献上你的一部分,换取它曾经的名字。',
+    opts: [
+      { label: '献上记忆', hint: '最高属性 +3,受到 20% 伤害', apply: { topRule: 3, dmg: 0.2 } },
+      { label: '拿走供品', hint: '能量 +4', apply: { energy: 4 } },
+    ] },
+  { id: 'wanderer', title: '迷路的观测者', text: '穿旧外套的观测者正在记录星光。他说记得你轮回之前的样子。',
+    opts: [
+      { label: '交换情报', hint: '知识 +3、裁决 +1', apply: { add: { knowledge: 3, judge: 1 } } },
+      { label: '请他疗伤', hint: '恢复 40% 生命', apply: { heal: 0.4 } },
+      { label: '离开', hint: '能量 +1', apply: { energy: 1 } },
+    ] },
+  { id: 'mirror', title: '会说话的镜子', text: '镜子里是另一个你,它说:“你每次都死在同一个地方。”它没有说错。',
+    opts: [
+      { label: '击碎镜子', hint: '全部属性 +2,同时受到 15% 伤害', apply: { addAll: 2, dmg: 0.15 } },
+      { label: '对它微笑', hint: '能量 +3', apply: { energy: 3 } },
+    ] },
+  { id: 'door', title: '三扇门', text: '三扇门后传来不同的声音:翻页声、祷词声、心跳声。',
+    opts: [
+      { label: '推开翻页的那扇', hint: '知识 +3', apply: { add: { knowledge: 3 } } },
+      { label: '推开祷词的那扇', hint: '誓约 +3', apply: { add: { oath: 3 } } },
+      { label: '推开心跳的那扇', hint: '信念 +3', apply: { add: { belief: 3 } } },
+    ] },
+  { id: 'forge', title: '灰烬铁匠铺', text: '炉火还温着。铁匠不在,桌上有一柄未完工的誓约之剑。',
+    opts: [
+      { label: '锻成剑刃', hint: '裁决 +3', apply: { add: { judge: 3 } } },
+      { label: '带走防具', hint: '信念 +2、誓约 +1', apply: { add: { belief: 2, oath: 1 } } },
+    ] },
+];
+
+export const EXPLORE_GAIN = 1.4;   // 里世界探索度总体缩放(配合 anchors 进入二/三/四阶的门槛)
+export const EXPLORE_MIN_FAIL = 3;
+const OATHS = [
+  { id: 'battle', name: '破阵之愿', desc: '攻击 +3', add: { knowledge: 1, judge: 1 }, atkBonus: 1 },
+  { id: 'warden', name: '守望之愿', desc: '最大生命 +40%,誓约、信念各 +1', hp: 0.4, add: { oath: 1, belief: 1 } },
+  { id: 'seer', name: '先知之愿', desc: '事件强化 ×2(随机属性翻倍、治疗翻倍)', eventMul: 2 },
+];
+
+const rnd = (r, n) => Math.floor(r() * n);
+const pick = (r, arr) => arr[rnd(r, arr.length)];
+
+export function atkOf(s) { return 10 + 1.5 * (s.attrs.knowledge + bonusOf(s, 'knowledge')) + 2 * (s.attrs.judge + bonusOf(s, 'judge')) + ((s.oathObj && s.oathObj.atkBonus) || 0); }
+export function hpMaxOf(s) { return Math.round((40 + 4 * (s.attrs.oath + bonusOf(s, 'oath')) + 1.5 * (s.attrs.belief + bonusOf(s, 'belief'))) * (1 + (s.oathObj?.hp || 0))); }
+/** 敌人威胁 pK:随步数与位面递增,与玩家属性无关(属性只放大你的攻击/生命) */
+export function threatOf(s, step, kind) {
+  const a = s.attrs;
+  const sum = a.knowledge + a.oath + a.belief + a.judge;
+  const p = s.plane || 0, i = step ?? s.step ?? 0;
+  // 敌方威胁 = 你的规则总和 ×(1+10%×步)×1.15^位面——敌人始终比你“多带一点规则”,位面越深越硬(与你的预算密度同序)
+  const base = sum * (1 + 0.1 * i) * Math.pow(1.15, p);
+  return Math.max(1, Math.round(base * (kind === 'boss' ? 1.1 : kind === 'elite' ? 1.05 : 1)));
+}
+export function clampAttr(v, k) { return clamp(+v.toFixed(2), 0, CAP[k]); }
+
+// 本位面在里世界的“规则浓度”:一阶 ×1.00 → 四阶 ×1.30;浓度越高,开局预算点越多(世界树等级的心智加成)
+export function planeDensity(plane) { return Math.pow(1.3, plane || 0); }
+export function riftNewRun(plane, budgetOverride) {
+  const r = mulberry32((Math.random() * 1e9) >>> 0);
+  return {
+    seed: rnd(r, 1e9), plane, step: 0, state: 'build', cleared: false, dead: false,
+    budget: budgetOverride != null ? budgetOverride : Math.round(20 * planeDensity(plane)),   // 开局“本源点”(预算点):一阶 20、二阶 26、三阶 34、四阶 44
+    density: planeDensity(plane),
+    available: { knowledge: 2 + rnd(r, 4), oath: 2 + rnd(r, 4), belief: 2 + rnd(r, 4), judge: 2 + rnd(r, 4) },   // 每类可分配 2~5 格
+    hp: 100, hpMul: 1, dmgMul: 1, energy: C.RIFT.energy + 8, maxEnergy: C.RIFT.energy + 8,
+    attrs: { knowledge: 1, oath: 1, belief: 1, judge: 1 },   // 起步各 1 点,避免空表
+    mouth: null, oathObj: null, immune: false,
+    log: [], score: 0, turns: 0,
+  };
+}
+
+/** 开局自由分配规则:总点数 = budget,每类不超过 available[k] */
+export function pointsSpent(s) { return RULES.reduce((a, k) => a + s.attrs[k], 0); }
+export function pointsLeft(s) { return s.budget - pointsSpent(s); }
+export function isBuildValid(s) { return pointsLeft(s) === 0 && RULES.every((k) => s.attrs[k] >= 1); }
+/** 事件加成(不计入威胁):存于 s.bonus,战斗生效 */
+export function bonusOf(s, k) { return (s.bonus && s.bonus[k]) || 0; }
+export function buildDone(s, oathIdx) {
+  if (!isBuildValid(s)) return false;
+  s.buildDone = true;
+  const o = OATHS[clamp(oathIdx, 0, OATHS.length - 1)];
+  s.oathObj = o;
+  s.hp = hpMaxOf(s);
+  s.state = 'run';
+  riftPrepare(s, 0);
+  return true;
+}
+
+function constDone(s) { return !!s.oathObj; }
+
+export function encounterKind(i) {
+  if (i === ENCOUNTERS - 1) return 'boss';
+  return ['normal', 'event', 'elite', 'normal', 'event'][i] || 'normal';
+}
+
+export function riftPrepare(s, i) {
+  s.step = i;
+  const r = mulberry32((s.seed + i * 7919) >>> 0);
+  const kind = encounterKind(i);
+  if (kind === 'event') {
+    const ev = pick(r, EVENTS);
+    s.state = 'event';
+    s.mouth = { type: 'event', title: ev.title, text: ev.text, opts: ev.opts.map((o, j) => ({ label: o.label, hint: o.hint, j })), ev };
+    return s;
+  }
+  s.state = 'fight';
+  const scale = Math.pow(1.08, s.plane) * Math.pow(1.06, i);
+  // 终局血量按终局威胁校准:恰好需要 3 次左右超杀(能赢,但有压力)
+  const atk0 = atkOf(s);
+  // 敌人血量/攻击 ∝ 你的攻击力(按全局强度计算,不吃本局临时加点):数值不脱钩,打起来始终“几到十几剑”
+  const basis = (s.baseAtk || 10 + 1.5 * 1 + 2 * 1) * Math.pow(s.density || planeDensity(s.plane), 2.2);
+  const gAtk = basis;
+  const kHp = (kind === 'elite' ? 1.5 : 1.0) * Math.pow(1.06, i + s.plane);
+  let hp = gAtk * kHp * 2.6;
+  let dmg = gAtk * 0.04 * (kind === 'boss' ? 1.15 : 1);
+  let name = pick(r, MONSTERS);
+  if (kind === 'elite') name = pick(r, ELITES);
+  if (kind === 'boss') { hp = Math.max(hp, threatOf(s, i, 'boss') * 4.0); name = pick(r, BOSSES); }
+
+
+
+
+
+  s.mouth = {
+    type: kind, name, hp: Math.round(hp), hpMax: Math.round(hp), dmg: Math.round(dmg * 10) / 10,
+    threat: threatOf(s, i, kind), taunt: pick(r, TAUNTS), nextImmunity: !!s.immune, hp0: Math.round(hp),
+  };
+  return s;
+}
+
+export function kindName(k) { return { normal: '战斗', elite: '精英', boss: '终局', event: '奇遇' }[k] || k; }
+
+/**
+ * 挥剑:结果 = 攻击 + 骰面(0..5);pK = 敌人威胁。
+ *   拼招 结果 > pK 且 < pK×1.75 → 敌人 −结果,自己 −3
+ *   超杀 结果 ≥ pK×1.75        → 敌人 −⌊结果×1.75⌋,自己 −1
+ *   阻断 结果 ≤ pK              → 敌人格挡,自己 −5,能量 +1
+ * 誓约最大时,每场第一次受击豁免。
+ */
+export function slash(s, rollVal) {
+  const m = s.mouth;
+  if (s.state !== 'fight' || !m) return null;
+  const roll = clamp(Math.floor(rollVal), 0, 5);
+  // 基础战力 = 攻击(含知识/裁决),每次挥剑再叠一个 0..5 的“临时战意”
+  const value = Math.round(atkOf(s) + roll);
+  const threat = m.threat;
+  let res, dmg = 0, back = 0;
+  const a = s.attrs;
+  const maxK = RULES.reduce((x, y) => (a[y] > a[x] ? y : x), RULES[0]);
+  if (value > threat) {
+    const need = threat * 1.75;
+    if (value >= need) { res = 'crit'; dmg = Math.floor(value * 1.75); back = 1; }
+    else { res = 'win'; dmg = value; back = 3; }
+    // 裁决(攻击属性):拼招/超杀时额外削减 = 裁决 × 1
+    if (maxK === 'judge' || maxK === 'knowledge') dmg += Math.floor((maxK === 'judge' ? a.judge + bonusOf(s, 'judge') : a.knowledge + bonusOf(s, 'knowledge')) * 1);
+  } else {
+    res = 'block'; back = 5; s.energy = Math.min(s.maxEnergy, s.energy + 1);
+  }
+  if (back > 0 && maxK === 'oath' && !s.immune) { back = 0; s.immune = true; }
+  m.hp = Math.max(0, m.hp - dmg);
+  s.hp = Math.min(hpMaxOf(s), s.hp - back);
+  if (maxK === 'belief' && back > 0) s.hp = Math.min(hpMaxOf(s), s.hp + a.belief * 0.5);
+  s.turns++;
+  s.score += res === 'crit' ? 25 : res === 'win' ? 12 : 0;
+  m.lastLog = { res, roll, value, threat, dmg, back };
+  const killed = m.hp <= 0, dead = s.hp <= 0;
+  if (killed) s.score += m.type === 'boss' ? 120 : m.type === 'elite' ? 60 : 30;
+  if (dead) s.dead = true;
+  return { res, roll, value, threat, dmg, back, killed, dead, maxK, mHp: m.hp, mHpMax: m.hpMax, heroHp: s.hp, heroMax: hpMaxOf(s) };
+}
+
+/** 挥剑后的流程:死亡 → 结算;击杀 → 下一步 / 通关 */
+export function afterSlash(s, r) {
+  if (r.dead) { s.state = 'result'; return { dead: true }; }
+  if (r.killed) {
+    if (s.step + 1 >= ENCOUNTERS) { s.state = 'result'; s.cleared = true; return { cleared: true }; }
+    riftPrepare(s, s.step + 1);
+    return { next: true };
+  }
+  return {};
+}
+
+/** 奇遇选择 */
+export function applyOption(s, j) {
+  const m = s.mouth;
+  if (s.state !== 'event' || !m || !m.ev) return null;
+  const opt = m.ev.opts[j];
+  if (!opt) return null;
+  const r = mulberry32((s.seed + s.step * 53 + j) >>> 0);
+  const mul = (s.oathObj && s.oathObj.eventMul) || 1;
+  const a = opt.apply;
+  const msgs = [];
+  s.bonus = s.bonus || {};
+  const addA = (k, n) => { s.bonus[k] = (s.bonus[k] || 0) + n * mul; msgs.push(`${RULE_NAME[k]} +${n * mul}`); };
+  if (a.add) for (const k of Object.keys(a.add)) addA(k, a.add[k]);
+  if (a.addAll) for (const k of RULES) addA(k, a.addAll);
+  if (a.rules) for (let i = 0; i < a.rules; i++) addA(pick(r, RULES), 1);
+  if (a.topRule) {
+    const tot = (k) => s.attrs[k] + (s.bonus[k] || 0);
+    const k = RULES.slice().sort((x, y) => tot(y) - tot(x))[0];
+    addA(k, a.topRule);
+  }
+  if (a.heal) { const v = Math.round(hpMaxOf(s) * a.heal * mul); s.hp = Math.min(hpMaxOf(s), s.hp + v); msgs.push(`生命 +${v}`); }
+  if (a.energy) { s.energy = Math.min(s.maxEnergy, s.energy + a.energy); msgs.push(`能量 +${a.energy}`); }
+  if (a.dmg) { const v = Math.round(hpMaxOf(s) * a.dmg); s.hp = Math.max(1, s.hp - v); msgs.push(`生命 −${v}`); }
+  s.score += 8;
+  if (s.step + 1 >= ENCOUNTERS) { s.state = 'result'; s.cleared = true; return { cleared: true, msg: msgs.join(',') }; }
+  riftPrepare(s, s.step + 1);
+  return { next: true, msg: msgs.join(',') };
+}
+
+/**
+ * 结算:探索度增量 = ⌊√(步数+1 + 分/20)⌋,通关 ×1.5(与 config.riftExploreDelta 同源)
+ * 本源碎片 = max(本源秒产, 10) × 8 × 探索增量/4
+ * 徽记:通关 1 枚;失败但分 ≥ 100 也 1 枚(失败也有价值);已锚定位面不再产出徽记
+ */
+export function riftResult(s, prodPerSec, alreadyAnchored) {
+  const steps = s.step + (s.cleared ? 1 : 0) + 1;
+  // 失败也有价值:探索碎片至少 25% 的固定产出
+  const delta = Math.max(EXPLORE_MIN_FAIL, Math.round(C.riftExploreDelta(steps, s.score, s.cleared) * EXPLORE_GAIN));
+  const essence = Math.max(prodPerSec * 8, 10) * Math.max(1, delta / 16);
+  const shard = alreadyAnchored ? 0 : (s.cleared ? 1 : s.score >= 100 ? 1 : 0);
+  return { explore: delta, essence, score: s.score, shard, cleared: s.cleared, steps };
+}
+
+export { OATHS };

+ 453 - 0
js/state.js

@@ -0,0 +1,453 @@
+// 存档状态层:唯一的可写状态源。tick、采购、转生、事件、里世界结算、存档/迁移/清洗都在这里。
+// DOM 与 Canvas 只读 state 并调用本文件导出的 action(逻辑与渲染分离)。署名:FmodeCode
+import * as C from './config.js';
+import * as F from './formulas.js';
+import * as R from './rift.js';
+import { CIV_EVENTS, MILESTONES } from './events-data.js';
+import { clamp, deepClone, safeNum } from './util.js';
+
+const nowSec = () => Date.now() / 1000;
+
+export function newState() {
+  return {
+    version: C.SAVE_VERSION,
+    createdAt: nowSec(), updatedAt: nowSec(), playSec: 0,
+    // 本轮(临时)
+    essence: 0, layer: 0, maxLayerRound: 0, maxLayerEver: 0,
+    upgrades: { root: 0, canopy: 0 }, lives: {},
+    round: { refines: 0 },
+    // 永久
+    crystals: 0, rebirths: 0, treeLv: 0, relics: [], embers: [], freeCycles: 0,
+    escaped: false, escapeCount: 0,
+    // 位面与探索
+    planes: C.PLANES.map(() => ({ explore: 0, best: 0, runs: 0 })), exploreSum: 0, currentPlane: 0,
+    // 即时状态
+    crisis: { next: C.CRISIS.firstAt, active: false, buffUntil: 0, penaltyUntil: 0 },
+    magic: { sig: 0, sigUntil: 0 },
+    civ: { idx: 0 }, nextCivSec: C.EVENT.civSec,
+    chapterSeen: 0,
+    riftCdSec: 0, planeRun: null,
+    stats: { bestRebirth: 0, totalRuns: 0, bestLayer: 0 },
+    flags: {},
+    autoEvery: 20, autoOn: false,
+  };
+}
+
+/** 自动转生间隔(秒),可在面板调节 5~60 秒;禅定模式(挂机) */
+export function autoRebirthEvery(s) { return clamp(safeNum(s.autoEvery, 20), 5, 60); }
+
+// ── 存档读写 ─────────────────────────────────────────
+export const save = {
+  serialize(state, rift) {
+    return JSON.stringify({ v: C.SAVE_VERSION, t: Date.now(), state, rift: rift || null });
+  },
+  parse(text) {
+    let raw;
+    try { raw = JSON.parse(String(text).trim()); } catch (e) { return { ok: false, error: '不是合法的 JSON' }; }
+    if (!raw || typeof raw !== 'object' || !raw.state || typeof raw.state !== 'object') {
+      return { ok: false, error: '缺少 state 字段,可能不是本游戏的存档' };
+    }
+    const st = migrate(raw);
+    if (!st) return { ok: false, error: '存档版本(v' + raw.v + ')来自更新的版本,无法识别' };
+    return { ok: true, data: st };
+  },
+  load(storage) {
+    try {
+      const text = storage.getItem(C.SAVE_KEY);
+      if (!text) return null;
+      const r = save.parse(text);
+      return r.ok ? r.data : null;
+    } catch (e) { return null; }
+  },
+  write(storage, state, rift) {
+    try { storage.setItem(C.SAVE_KEY, save.serialize(state, rift)); return true; } catch (e) { return false; }
+  },
+  clear(storage) { try { storage.removeItem(C.SAVE_KEY); } catch (e) { /* ignore */ } },
+};
+
+/** 迁移:按版本逐级升级,再用缺省值补齐、清洗数值。新版本在此追加 if (data.v < 2) {...} */
+export function migrate(raw) {
+  let data = raw;
+  if (typeof data.v !== 'number') data.v = 0;
+  if (data.v > C.SAVE_VERSION) return null;
+  if (data.v < 1) {
+    const base = newState();
+    mergeInto(base, data.state || {});
+    data = { v: 1, t: data.t || Date.now(), state: base, rift: data.rift || null };
+  }
+  const base = newState();
+  mergeInto(base, data.state);
+  const st = sanitize(base);
+  return { state: st, rift: sanitizeRift(data.rift), savedAt: safeNum(data.t, Date.now()) };
+}
+
+function mergeInto(dst, src) {
+  if (!src || typeof src !== 'object') return;
+  for (const k of Object.keys(dst)) {
+    if (!(k in src)) continue;
+    const d = dst[k], v = src[k];
+    if (d && typeof d === 'object' && !Array.isArray(d) && v && typeof v === 'object' && !Array.isArray(v)) mergeInto(d, v);
+    else if (Array.isArray(d)) dst[k] = Array.isArray(v) ? v : d;
+    else dst[k] = v;
+  }
+  for (const k of Object.keys(src)) {
+    if (!(k in dst) && (k.startsWith('_') || k === 'planeRun')) dst[k] = src[k];
+  }
+}
+
+function sanitize(s) {
+  const num = (v, def = 0) => Math.max(0, safeNum(v, def));
+  s.essence = num(s.essence); s.layer = num(s.layer); s.maxLayerRound = num(s.maxLayerRound);
+  s.maxLayerEver = Math.max(num(s.maxLayerEver), s.layer);
+  s.crystals = num(s.crystals); s.rebirths = Math.floor(num(s.rebirths));
+  s.treeLv = Math.floor(num(s.treeLv)); s.freeCycles = Math.floor(num(s.freeCycles));
+  s.escapeCount = Math.floor(num(s.escapeCount));
+  s.relics = Array.isArray(s.relics) ? s.relics.filter((x) => C.RELICS.some((r) => r.id === x)).slice(0, C.PERM.relicCount) : [];
+  for (const k of C.UPGRADE_KINDS) s.upgrades[k] = Math.floor(num(s.upgrades[k]));
+  for (const l of C.LIVES) s.lives[l.id] = Math.floor(num(s.lives[l.id]));
+  s.planes = C.PLANES.map((p, i) => {
+    const o = (s.planes && s.planes[i]) || {};
+    return { explore: Math.min(100, num(o.explore)), best: num(o.best), runs: num(o.runs) };
+  });
+  s.currentPlane = clamp(Math.floor(num(s.currentPlane)), 0, C.PLANES.length - 1);
+  if (!C.planeUnlocked(s, s.currentPlane)) s.currentPlane = 0;
+  s.exploreSum = s.planes.reduce((a, p) => a + p.explore, 0);
+  s.round = { refines: Math.floor(num(s.round && s.round.refines)) };
+  s.crisis.next = num(s.crisis.next, C.CRISIS.firstAt);
+  s.nextCivSec = num(s.nextCivSec, C.EVENT.civSec);
+  s.autoEvery = clamp(safeNum(s.autoEvery, 20), 5, 60);
+  s.playSec = num(s.playSec);
+  s.updatedAt = safeNum(s.updatedAt, nowSec());
+  s._skipAcc = clamp(safeNum(s._skipAcc), 0, 1);
+  return s;
+}
+
+export function sanitizeRift(rift) {
+  if (!rift || !rift.run) return null;
+  const run = rift.run;
+  if (!run.attrs || typeof run.attrs !== 'object') return null;
+  if (!['build', 'run', 'fight', 'event', 'result'].includes(run.state)) return null;
+  const out = deepClone(run);
+  out.plane = clamp(Math.floor(safeNum(out.plane)), 0, 3);
+  out.hp = Math.max(0, safeNum(out.hp));
+  out.energy = Math.max(0, safeNum(out.energy, 0));
+  out.step = clamp(Math.floor(safeNum(out.step)), 0, R.ENCOUNTERS - 1);
+  for (const k of R.RULES) out.attrs[k] = Math.max(0, safeNum(out.attrs[k]));
+  return { run: out, pending: rift.pending || null };
+}
+
+// ── 主循环 ───────────────────────────────────────────
+/** 推进 dt 秒;返回本 tick 的表现事件(UI 层呈现)。主世界在里世界进行期间冻结。 */
+export function tick(s, rift, dt) {
+  const out = { skip: null, floor: null, events: [], auto: false, anchors: null, crisis: false, crisisExpire: false };
+  if (!(dt > 0) || !Number.isFinite(dt)) return out;
+  if (rift && rift.run) s.planeRun = rift.run;                     // 与保存层共享同一里世界对象
+  if (rift && rift.run && rift.run.state !== 'result') return out;  // 里世界中:主世界时间冻结
+  s.playSec += dt;
+  s.planeRun = null;
+  if (s.escaped) { s.escapedT = (s.escapedT || 0) + dt; return out; }   // 逃逸完成(禅定仍可自由轮回)
+  const st = F.computeStats(s);
+  const now = nowSec();
+
+  // 跳关:触发率 p 与单层用时 T(L) 决定触发频率,触发后随机跳 1~4 层
+  const plan = C.skipPlan(st.skipP);
+  if (plan.p > 0) {
+    let acc = (s._skipAcc || 0) + plan.p * dt / C.visitTime(s.layer);
+    while (acc >= 1) {
+      acc -= 1;
+      const roll = Math.random();
+      let k = plan.ks[0], accP = 0;
+      for (let i = 0; i < plan.ks.length; i++) { accP += plan.probs[i] / plan.p; if (roll < accP) { k = plan.ks[i]; break; } }
+      out.skip = { from: s.layer, to: s.layer + k, k };
+      s.layer += k;
+      if (s.currentPlane === 2) {
+        s.magic.sig = Math.min(C.NARRATE_STACK_CAP, (s.magic.sig || 0) + 1);
+        s.magic.sigUntil = now + C.NARRATE_SEC;
+      }
+    }
+    s._skipAcc = acc;
+  }
+  s.layer += st.layersPerSec * dt;
+  s.essence += st.prod * dt;
+  s.maxLayerRound = Math.max(s.maxLayerRound, s.layer);
+
+  const fl = Math.floor(s.layer);
+  if (fl > 0 && fl % 10 === 0 && fl !== s._lastFlash) { s._lastFlash = fl; out.floor = fl; }
+
+  // 主线章节里程碑(连续空间:章节只是进度条上的一段,无弹窗结算)
+  const ch = Math.min(5, C.chapterOf(s.layer));
+  if (ch > (s.chapterSeen || 0)) {
+    for (let c = Math.max(1, (s.chapterSeen || 0) + 1); c <= ch; c++) {
+      s.chapterSeen = c;
+      if (c === 5) {
+        s.escaped = true; s.escapedT = 0; s.escapeCount = (s.escapeCount || 0) + 1;
+        s.stats.bestLayer = Math.max(s.stats.bestLayer || 0, s.maxLayerRound);
+        out.events.push({ type: 'milestone', key: 'escape', ...MILESTONES.escape });
+      } else {
+        out.events.push({ type: 'milestone', key: 'chapter' + c, ...MILESTONES.chapter(C.CHAPTERS[c].title) });
+      }
+    }
+    if (s.escaped) return out;
+  }
+
+  // 科技位面:自动化——每秒为已解锁兵种免费 +1 级(上限 autoCap)
+  if (st.rule.autoLives) {
+    let ups = 0;
+    C.LIVES.forEach((l, i) => {
+      const cur = s.lives[l.id] || 0;
+      if (cur < (st.rule.autoCap || 15) && F.lifeUnlocked(s, i)) { s.lives[l.id] = cur + 1; ups++; }
+    });
+    if (ups) out.events.push({ type: 'info', key: 'auto', title: '自动化闭环', text: '兵种被机器自动培育。', quiet: true });
+  }
+
+  // 魔幻位面:叙事共鸣逐层衰减
+  if (s.magic.sig > 0 && now > (s.magic.sigUntil || 0)) {
+    s.magic.sig -= 1;
+    s.magic.sigUntil = s.magic.sig > 0 ? (s.magic.sigUntil || now) + C.NARRATE_SEC : now;
+  }
+
+  // 危机事件计时(UI 层弹窗;窗口内未响应 = 前沿逼近)
+  const c = s.crisis;
+  if (!c.active) {
+    c.next -= dt;
+    if (c.next <= 0) { c.active = true; c.popUntil = dt + C.CRISIS.countdown; c.next = C.CRISIS.interval; out.crisis = true; }
+  } else {
+    c.popUntil -= dt;
+    if (c.popUntil <= 0) { c.active = false; out.crisisExpire = true; }
+  }
+
+  // 文明事件(现实位面)
+  if (s.currentPlane === 0 && s.civ.idx < CIV_EVENTS.length) {
+    s.nextCivSec -= dt;
+    if (s.nextCivSec <= 0) { s.nextCivSec = C.EVENT.civSec; out.events.push({ type: 'civ', civIdx: s.civ.idx }); s.civ.idx++; }
+  }
+
+  // 锚定位面后台采集:每 60 秒按本源秒产 2%/位面
+  const anchored = s.planes.filter((p) => p.explore >= C.EXPLORE_FULL).length;
+  if (anchored) {
+    s._anchorAcc = (s._anchorAcc || 0) + dt;
+    if (s._anchorAcc >= C.ANCHOR_COLLECT_SEC) {
+      s._anchorAcc -= C.ANCHOR_COLLECT_SEC;
+      const gain = st.prodRaw * C.ANCHOR_RATE * anchored * (s.currentPlane === 1 ? 1.25 : 1);
+      s.essence += gain;
+      out.anchors = { count: anchored, gain };
+    }
+  }
+
+  if ((s.riftCdSec || 0) > 0) s.riftCdSec = Math.max(0, s.riftCdSec - dt);
+
+  // 禅定(挂机自动转生):前 60 秒 / 前 10 层不触发,避免读档即空转
+  s._autoT = (s._autoT || 0) + dt;
+  if (s.autoOn && s._autoT >= autoRebirthEvery(s)) {
+    s._autoT = 0;
+    if (s.playSec >= 60 && s.layer >= 10) out.auto = true;
+  }
+  return out;
+}
+
+function syncExplore(s) { s.exploreSum = s.planes.reduce((a, p) => a + p.explore, 0); }
+
+// ── 行动(唯一写入口) ─────────────────────────────────
+/** 本轮升级(批量买满 0.9×本源,单次最多 12 级) */
+export function buyUpgrade(s, kind) {
+  const cur = s.upgrades[kind] || 0;
+  const n = C.maxAffordable(kind, cur, s.essence * 0.9);
+  if (n <= 0) return null;
+  const cost = C.batchCost(kind, cur, n);
+  s.essence -= cost;
+  s.upgrades[kind] = cur + n;
+  return { n, cost };
+}
+
+export function buyLife(s, id) {
+  const idx = C.LIVES.findIndex((l) => l.id === id);
+  if (idx < 0 || !F.lifeUnlocked(s, idx)) return false;
+  const cost = F.lifeCost(s, id);
+  if (s.essence < cost) return false;
+  s.essence -= cost;
+  s.lives[id] = (s.lives[id] || 0) + 1;
+  return true;
+}
+
+/** 永久投资:stem = 世界树等级(时间结晶);relic = 遗物 */
+export function buyTree(s) {
+  const cost = C.treeCost(s.treeLv);
+  if (!(s.crystals >= cost)) return false;
+  s.crystals -= cost;
+  s.treeLv += 1;
+  return true;
+}
+export function buyRelic(s) {
+  if (s.relics.length >= C.PERM.relicCount) return false;
+  const cost = C.relicCost(s.relics.length);
+  if (!(s.crystals >= cost)) return false;
+  s.crystals -= cost;
+  s.relics.push(C.RELICS[s.relics.length].id);
+  return true;
+}
+export function buyPerm(s, kind) { return kind === 'relic' ? buyRelic(s) : kind === 'stem' || kind === 'tree' ? buyTree(s) : false; }
+
+/**
+ * 转生:结算时间结晶并重置本轮。收益公式与 UI 预期共用 F.rebirthEstimate(预期 = 实得)。
+ */
+export function rebirth(s) {
+  if (s.planeRun && s.planeRun.state !== 'result') return { gain: 0, blocked: true, floor: s.layer, T: 0, cost: 1 };
+  const gain = F.rebirthEstimate(s);
+  const finalLayer = s.layer;
+  const rule = C.PLANE_RULES[s.currentPlane || 0];
+  const keep = rule.rebirthKeep ? Math.floor(s.essence * rule.rebirthKeep) : 0;
+  const T = Math.max(s.maxLayerRound || 0, finalLayer);
+  const floor = C.earlyLayer(T, rule);
+  s.maxLayerEver = Math.max(s.maxLayerEver, T);
+  s.stats.bestLayer = Math.max(s.stats.bestLayer || 0, T);
+  if (s.escaped) { s.freeCycles = (s.freeCycles || 0) + 1; s.escaped = false; }
+  s.crystals += gain;
+  s.rebirths += 1;
+  s.stats.bestRebirth = Math.max(s.stats.bestRebirth || 0, gain);
+  s.essence = keep;
+  s.layer = floor;
+  s.maxLayerRound = 0;
+  s.upgrades = { root: 0, canopy: 0 };
+  // 溯时回响:兵种等级保留 20%(修仙位面 ×2),羁绊是轮与轮之间的绳索
+  const keepFrac = C.EVENT.lifeKeep * (rule.rebirthKeep ? 2 : 1);
+  for (const l of C.LIVES) s.lives[l.id] = Math.max(0, Math.floor(Math.min(s.lives[l.id] || 0, C.LIFE_ECHO_CAP) * keepFrac));
+  s.round = { refines: 0 };
+  s.civ = { idx: 0 }; s.nextCivSec = C.EVENT.civSec;
+  s.crisis = { next: C.CRISIS.firstAt, active: false, buffUntil: 0, penaltyUntil: 0 };
+  s.magic = { sig: 0, sigUntil: 0 };
+  s._skipAcc = 0; s._autoT = 0; s._lastFlash = undefined;
+  s.chapterSeen = Math.min(5, C.chapterOf(floor));
+  const evt = s.rebirths === 1
+    ? { type: 'milestone', key: 'firstRebirth', ...MILESTONES.firstRebirth }
+    : { type: 'milestone', key: 'epoch' + (s.rebirths % 10), ...MILESTONES.epoch(s.rebirths) };
+  return { gain, floor, T, event: s.rebirths === 1 || s.rebirths % 10 === 0 ? evt : null, cost: C.rebirthCost(T) };
+}
+
+/** 危机响应:relieve 转移前沿 / brace 以根系硬抗 / hold 暂时退让 */
+export function crisisRespond(s, effect) {
+  const c = s.crisis;
+  if (!c.active) return null;
+  c.active = false;
+  const now = nowSec();
+  const cr = C.CRISIS;
+  if (effect === 'relieve') {
+    const cost = s.essence * cr.relieveCost;
+    s.essence -= cost;
+    s.layer += cr.relaxSkip;
+    s.maxLayerRound = Math.max(s.maxLayerRound, s.layer);
+    c.buffUntil = Math.max(c.buffUntil || 0, now + cr.rewardSec);
+    return `消耗本源 ${Math.floor(cost)},前沿被推回 ${cr.relaxSkip} 层;本源产出 ×${1 + cr.reward}(${cr.rewardSec} 秒)`;
+  }
+  if (effect === 'brace') {
+    c.buffUntil = Math.max(c.buffUntil || 0, now + cr.braceSec);
+    c.penaltyUntil = Math.max(c.penaltyUntil || 0, now + cr.braceSec + cr.penaltySec);
+    return `本源产出 ×${1 + cr.bracePer}(${cr.braceSec} 秒),随后 ×${1 - cr.penalty}(${cr.penaltySec} 秒)`;
+  }
+  s.layer = Math.max(0, s.layer - cr.holdLayers);
+  c.penaltyUntil = Math.max(c.penaltyUntil || 0, now + cr.penaltySec);
+  return `本轮层数 −${cr.holdLayers};本源产出 ×${1 - cr.penalty}(${cr.penaltySec} 秒)`;
+}
+
+/** 危机窗口结束未响应 */
+export function crisisExpire(s) {
+  if (!s.crisis.active) return null;
+  s.crisis.active = false;
+  s.crisis.penaltyUntil = Math.max(s.crisis.penaltyUntil || 0, nowSec() + C.CRISIS.penaltySec);
+  s.layer = Math.max(0, s.layer - C.CRISIS.expireLayers);
+  return `前沿吞没了 ${C.CRISIS.expireLayers} 层根系,本源产出 ×${1 - C.CRISIS.penalty}(${C.CRISIS.penaltySec} 秒)`;
+}
+
+/** 文明事件选择 */
+export function civChoose(s, evIdx, optIdx) {
+  const ev = CIV_EVENTS[evIdx];
+  const opt = ev && ev.opts[optIdx];
+  if (!opt) return null;
+  const now = nowSec();
+  let text;
+  if (opt.effect === 'boost') {
+    s.crisis.buffUntil = Math.max(s.crisis.buffUntil || 0, now + 60);
+    text = '文明产能高涨:本源产出 ×1.3,持续 60 秒。';
+  } else if (opt.effect === 'explore') {
+    const p = s.planes[s.currentPlane];
+    const n = opt.n || 5;
+    p.explore = Math.min(C.EXPLORE_FULL, p.explore + n);
+    syncExplore(s);
+    text = `星图测绘完成:${C.PLANES[s.currentPlane].name}探索度 +${n}。`;
+  } else {
+    s.nextCivSec = 30;
+    text = '研究线索点亮:下一个文明事件将在 30 秒后到来。';
+  }
+  return text;
+}
+
+export function switchPlane(s, p) {
+  if (!C.planeUnlocked(s, p)) return false;
+  if (s.planeRun && s.planeRun.state !== 'result') return false;
+  s.currentPlane = p;
+  s.civ = { idx: 0 };
+  s.nextCivSec = C.EVENT.civSec;
+  return true;
+}
+
+/** 进入里世界(主世界冻结,冷却 45 秒游戏时钟) */
+export function startRift(s) {
+  if ((s.riftCdSec || 0) > 0) return null;
+  if (s.planeRun && s.planeRun.state !== 'result') return s.planeRun;
+  const run = R.riftNewRun(s.currentPlane);
+  run.active = true;
+  s.planeRun = run;
+  return run;
+}
+
+/** 结束里世界并结算(胜负都结算;失败也有探索碎片) */
+export function endRift(s) {
+  const r = s.planeRun;
+  if (!r) return null;
+  const base = F.computeStats(Object.assign({}, s, { planeRun: null })).prodRaw;
+  const plane = s.planes[r.plane];
+  const alreadyAnchored = plane.explore >= C.EXPLORE_FULL;
+  const res = R.riftResult(r, base, alreadyAnchored);
+  const before = plane.explore;
+  plane.explore = Math.min(C.EXPLORE_FULL, plane.explore + res.explore);
+  plane.best = Math.max(plane.best, res.steps);
+  plane.runs += 1;
+  s.essence += res.essence;
+  s.stats.totalRuns = (s.stats.totalRuns || 0) + 1;
+  if (res.shard) s.embers.push(`徽记·${C.PLANES[r.plane].name}`);
+  syncExplore(s);
+  res.anchoredNow = !alreadyAnchored && plane.explore >= C.EXPLORE_FULL;
+  res.planeName = C.PLANES[r.plane].name;
+  res.anchored = plane.explore >= C.EXPLORE_FULL;
+  s.planeRun = null;
+  s.riftCdSec = C.RIFT.cooldownSec;
+  const events = [];
+  if (res.anchoredNow) events.push({ type: 'milestone', key: 'anchor' + r.plane, ...MILESTONES.planeAnchor(res.planeName) });
+  for (const u of C.PLANE_UNLOCK_AT) {
+    if (C.planeUnlocked(s, u.plane) && !s.flags['open' + u.plane]) {
+      s.flags['open' + u.plane] = true;
+      events.push({ type: 'milestone', key: 'open' + u.plane, title: `时空裂缝开启 · ${C.PLANES[u.plane].name}`, text: `${C.PLANES[u.plane].tier}规则模板可进入:${C.PLANES[u.plane].lore}` });
+    }
+  }
+  return { res, events };
+}
+
+/** 离线结算:上限 8 小时,效率 60%(跳关只计入一半) */
+export function applyOffline(s, elapsedSec, rift) {
+  const sec = clamp(elapsedSec, 0, C.OFFLINE.capSec);
+  if (sec < 60 || s.escaped) return null;
+  if (rift && rift.run && rift.run.state !== 'result') return { skipped: true, sec };
+  const st = F.computeStats(s);
+  const eff = C.OFFLINE.eff;
+  const essence = st.prod * sec * eff;
+  const gainLayer = st.layersPerSec * sec * eff * (1 + st.skipExp * 0.5);
+  const fromLayer = s.layer;
+  s.essence += essence;
+  s.layer = Math.min(C.TOTAL_LAYERS, s.layer + gainLayer);
+  s.maxLayerRound = Math.max(s.maxLayerRound, s.layer);
+  s.maxLayerEver = Math.max(s.maxLayerEver, s.layer);
+  s.chapterSeen = Math.max(s.chapterSeen || 0, Math.min(5, C.chapterOf(s.layer)));
+  if (s.layer >= C.TOTAL_LAYERS && !s.escaped) { s.escaped = true; s.escapeCount = (s.escapeCount || 0) + 1; s.escapedT = 0; }
+  return { sec: Math.round(sec), essence, fromLayer, toLayer: s.layer };
+}
+
+export { CIV_EVENTS };

+ 925 - 0
js/ui.js

@@ -0,0 +1,925 @@
+// 表现层:DOM 渲染、弹窗、Toast、里世界交互、存档 UI。只读 state,所有写入都经 state.js 的 action。
+// 署名:FmodeCode
+import * as C from './config.js';
+import * as F from './formulas.js';
+import * as S from './state.js';
+import * as R from './rift.js';
+import { CIV_EVENTS, CRISIS_EVENTS } from './events-data.js';
+import { fmt, fmtPct, fmtTime, esc } from './util.js';
+import { I, lifeIcon, relicIcon } from './icons.js';
+import { MarchScene } from './march.js';
+
+const $ = (s, r = document) => r.querySelector(s);
+const $$ = (s, r = document) => Array.from(r.querySelectorAll(s));
+const BATCH = 12;
+
+export class App {
+  constructor(state, rift) {
+    this.s = state;
+    this.riftRun = rift && rift.run ? rift.run : null;
+    this.cache = new Map();
+    this.scene = new MarchScene($('#march'));
+    this.toasts = [];
+    this.modalOpen = false;
+    this.dialog = null;        // 当前弹窗类型
+    this.dialogQueue = [];
+    this.lastFrame = performance.now();
+    this.lastSave = 0;
+    this.lastRender = 0;
+    this.fps = { n: 0, t: 0, v: 60 };
+    this.bindEvents();
+    this.bindKeys();
+    this.startLoop();
+  }
+
+  // ───────────── 循环 ─────────────
+  startLoop() {
+    let acc = 0;
+    const STEP = 0.2;
+    const loop = (ts) => {
+      const dt = Math.min(0.5, (ts - this.lastFrame) / 1000);
+      this.lastFrame = ts;
+      acc += dt;
+      let guard = 0;
+      while (acc >= STEP && guard++ < 10) { acc -= STEP; this.step(STEP); }
+      if (ts - this.lastRender > 100) { this.lastRender = ts; this.renderDynamic(); }
+      this.fps.n++; this.fps.t += dt;
+      if (this.fps.t >= 1) { this.fps.v = Math.round(this.fps.n / this.fps.t); this.fps.n = 0; this.fps.t = 0; }
+      requestAnimationFrame(loop);
+    };
+    requestAnimationFrame(loop);
+  }
+
+  step(dt) {
+    const s = this.s;
+    const out = S.tick(s, this.riftRun ? { run: this.riftRun } : null, dt);
+    this.riftRun = s.planeRun;
+    // 表现:跳关
+    if (out.skip) { this.scene.burst(1); this.floatLayer(`跃迁 +${out.skip.k}`); }
+    for (const e of out.events) {
+      if (e.quiet) continue;
+      if (e.type === 'civ') this.pushDialog({ kind: 'civ', civIdx: e.civIdx });
+      else if (e.type === 'milestone') this.pushDialog({ kind: 'milestone', data: e });
+      else if (e.type === 'info') this.log(e.title + ':' + e.text, 'info');
+    }
+    if (out.crisis) this.pushDialog({ kind: 'crisis' });
+    if (out.crisisExpire) { const t = S.crisisExpire(s); if (t) this.log(t, 'crisis'); this.toast(t, 'warn'); }
+    if (out.anchors) this.log(`锚定位面后台采集:${out.anchors.count} 个位面 +${fmt(out.anchors.gain)} 本源`, 'anchor');
+    if (out.auto) this.autoHarvest();
+    if (out.floor) this.floatLayer(`${out.floor} 层`);
+    // 存档
+    if (performance.now() - this.lastSave > 30000) { this.lastSave = performance.now(); this.saveNow(); }
+  }
+
+  autoHarvest() {
+    const s = this.s;
+    if (s.planeRun) return;
+    const st = F.computeStats(s);
+    if ((s.maxLayerRound || 0) < 3) return;
+    const r = S.rebirth(s);
+    if (r.event) this.pushDialog({ kind: 'milestone', data: r.event });
+    this.log(`禅定回溯 #${s.rebirths} · +${fmt(r.gain)} 结晶(本轮深度 ${fmt(r.T, { int: true })})`, 'mile');
+    this.toast(`禅定回溯:+${fmt(r.gain)} 时间结晶`, 'good');
+    this.renderStatic();
+  }
+
+  floatLayer(text) {
+    const el = document.createElement('div');
+    el.className = 'skip-float';
+    el.textContent = text;
+    el.style.left = (18 + Math.random() * 30) + '%';
+    el.style.top = (28 + Math.random() * 20) + '%';
+    $('#float-layer').appendChild(el);
+    setTimeout(() => el.remove(), 1200);
+  }
+
+  // ───────────── 渲染 ─────────────
+  renderStatic() { this.renderTop(); this.renderLeft(); this.renderRight(); this.renderRiftPanel(); this.renderDynamic(); }
+
+  renderDynamic() {
+    const s = this.s;
+    const st = F.computeStats(s);
+    this.stats = st;
+    this.renderTop(st);
+    this.renderHud(st);
+    // 资源块
+    this.setText('#res-essence', fmt(s.essence));
+    this.setText('#res-essence-rate', `${fmt(st.prod)} / 秒${st.frozen ? '(冻结)' : ''}`);
+    this.setText('#res-crystal', fmt(s.crystals));
+    this.setText('#res-crystal-rate', s.planes.filter((p) => p.explore >= 100).length ? `锚定采集 ${s.planes.filter((p) => p.explore >= 100).length} 处运行中` : '转生结算,永久');
+    // HUD
+    const lf = s.layer;
+
+    this.html('#hud-r', `<b>${fmt(s.maxLayerRound || 0, { int: true })}</b> 本轮最深<br>时间乘区 <b>×${st.timeMul.toFixed(2)}</b>`);
+    const magic = $('#magic-badge');
+    if (st.narrSig > 0) {
+      this.html('#magic-badge', `叙事共鸣 ×${Math.pow(1.3, Math.min(10, st.narrSig)).toFixed(2)}(${st.narrSig} 层)`);
+      $('#magic-badge').hidden = false;
+    } else $('#magic-badge').hidden = true;
+    // 行动条
+    this.refreshActions();
+    this.refreshAutoButtons();
+    // 转生面板
+    this.refreshRebirth();
+    // 升级按钮状态(价格变化)
+    this.refreshUpgradeButtons();
+    this.refreshLives();
+    // 主世界 canvas
+    const chF = C.chapterOf(lf);
+    this.scene.update({ chapter: chF, layerFloat: lf, layersPerSec: st.layersPerSec, layerSec: st.layerSec });
+    this.setText('#hud-layer', fmt(Math.floor(lf), { int: true }));
+    this.setText('#hud-sub', `第 ${fmt(Math.floor(lf) + 1, { int: true })} 层 · 距下一层 ${fmtPct(lf - Math.floor(lf), 0)}`);
+    this.html('#hud-meta', `${fmt(st.prod)} 本源/秒 · 约 ${st.minutesPerLayer < 0.01 ? '<0.01' : st.minutesPerLayer.toFixed(2)} 分/层(含跳关) · 跳关 ${fmtPct(st.skipP, 0)}`);
+    document.documentElement.style.setProperty('--plane-c', C.PLANES[s.currentPlane].color);
+    $('.topbar').style.borderTopColor = C.PLANES[s.currentPlane].color;
+    // 里世界
+    if (this.riftRun) this.renderRiftLive();
+    // 引导
+    this.refreshGuide(st);
+  }
+
+  renderHud(st) {
+    const lf = this.s.layer;
+    this.setText('#hud-layer', fmt(Math.floor(lf), { int: true }));
+    this.setText('#hud-sub', `第 ${fmt(Math.floor(lf) + 1, { int: true })} 层 · 距下一层 ${fmtPct(Math.min(0.99, lf - Math.floor(lf)), 0)}`);
+    this.html('#hud-meta', `${fmt(st.prod)} 本源/秒 · 约 ${st.minutesPerLayer < 0.01 ? '<0.01' : st.minutesPerLayer.toFixed(2)} 分/层(含跳关) · 跳关触发率 ${fmtPct(st.skipP, 0)}`);
+  }
+
+  setText(sel, v) { const e = $(sel); if (e && e.textContent !== v) e.textContent = v; }
+  html(sel, v) { const e = $(sel); if (e && this.cache.get(sel) !== v) { e.innerHTML = v; this.cache.set(sel, v); } }
+
+  renderTop(st) {
+    if (!st) st = this.stats || F.computeStats(this.s);
+    const s = this.s;
+    const ch = C.chapterOf(s.layer);
+    const t = s.escaped ? (s.escapedT || 0) : null;
+    this.html('#topstats', `
+      <div class="tstat"><span class="k">世界树等级</span><span class="v num">D${s.treeLv}</span></div>
+      <div class="tstat optional"><span class="k">回归</span><span class="v num">${s.rebirths}</span></div>
+      <div class="tstat optional"><span class="k">位面</span><span class="v">${C.PLANES[s.currentPlane].tier} · ${C.PLANES[s.currentPlane].name}</span></div>
+      <div class="tstat"><span class="k">当前章节</span><span class="v">${s.escaped ? '已冲出空洞' : C.CHAPTERS[ch].title}</span></div>`);
+  }
+
+  renderLeft() {
+    const s = this.s;
+    this.html('#resources', `
+      <div class="panel-title">资源 · ${C.PLANES[s.currentPlane].essence}</div>
+      <div class="res-row">
+        <div class="res"><div class="k"><span class="dot"></span>本源 <span style="font-size:10px;color:var(--muted-2)">· 本轮</span></div>
+          <div class="v num" id="res-essence">0</div><div class="d" id="res-essence-rate">0 / 秒</div></div>
+        <div class="res"><div class="k"><span class="dot gold"></span>时间结晶 <span style="font-size:10px;color:var(--muted-2)">· 永久</span></div>
+          <div class="v num" id="res-crystal">0</div><div class="d" id="res-crystal-rate">转生结算,永久</div></div>
+      </div>`);
+    this.renderMainline();
+    this.renderUpgrades();
+  }
+
+  renderMainline() {
+    const s = this.s;
+    const ch = s.escaped ? 5 : C.chapterOf(s.layer);
+    const info = C.CHAPTERS[ch];
+    const prog = Math.min(1, s.layer / C.TOTAL_LAYERS);
+    const marks = C.CHAPTERS.slice(1).map((c) => {
+      const pct = (c.at / C.TOTAL_LAYERS) * 100;
+      return `<div class="mark ${s.layer >= c.at ? 'done' : ''}" style="left:${pct}%"><span>${c.short}</span></div>`;
+    }).join('');
+    let guide = '';
+    if (!s.flags.guideDone) {
+      const step = this.guideStep();
+      if (step) guide = `<div class="guide" style="margin-bottom:10px"><div class="g">${step}</div><button class="x" data-act="guide-x" title="我知道了">×</button></div>`;
+    }
+    this.html('#mainline', `
+      ${guide}
+      <div class="panel-title">主线 · 逃逸进度 <span class="tag">${fmtPct(prog, 2)}</span></div>
+      <div class="chapter">
+        <div class="ch-title"><span class="idx">CH.${ch + 1} / 6</span>${s.escaped ? '冲出空洞 · 自由轮回' : info.title}</div>
+        <div class="ch-desc">${s.escaped ? `空洞已被甩在身后。你已完成 ${s.escapeCount || 1} 次逃逸;禅定循环将继续为你累积自由轮回加成(×${C.freedomMul(s).toFixed(2)})。` : info.desc}</div>
+      </div>
+      <div class="esc-track">
+        <div class="esc-bar"><div class="fill" style="width:${(prog * 100).toFixed(2)}%"></div>${marks}</div>
+        <span>第 ${fmt(Math.floor(s.layer), { int: true })} / 1000 层</span><span>${s.escaped ? '已抵达' : '目标:冲出空洞'}</span>
+      </div>`);
+  }
+
+  guideStep() {
+    const s = this.s;
+    if (s.playSec < 12) return '世界树正在沿连续空间行军。<b>本源</b>在持续生长,先点「升级根须」让它长得更快。';
+    if (s.rebirths === 0 && s.layer < 10) return '推进速度在加深后放缓。<b>本源</b>够了就买「根须」:产出 ×1.10、推进 ×5%。';
+    if (s.rebirths === 0 && s.layer >= 10) return '本节快到顶了——点右侧 <b>「回溯」</b>炼化时间结晶,下一次轮回会更快。';
+    if (s.planes[0].explore < 100 && !s.flags.riftDone2) return '时空裂缝已开启:去 <b>里世界</b> 打一局(约 1~5 分钟),用探索度锚定位面。';
+    return null;
+  }
+
+  refreshGuide(st) {
+    // 小步骤完成标记后自动消失
+    if (this.s.flags.guideDone) return;
+    const step = this.guideStep();
+    const g = $('#mainline .guide .g');
+    if (!step) { const el = $('#mainline .guide'); if (el) el.remove(); return; }
+    if (!g) { this.renderMainline(); return; }
+    if (g.innerHTML !== step) g.innerHTML = step;
+  }
+
+  renderUpgrades() {
+    const s = this.s;
+    const rows = C.UPGRADE_KINDS.map((k) => {
+      const c = C.COST[k];
+      const lv = s.upgrades[k] || 0;
+      const ic = k === 'root' ? I.tree() : I.canopy();
+      return `<div class="upg">
+        <div class="ic">${ic}</div>
+        <div class="info"><div class="n"><span>${c.name}</span><span class="lv">Lv ${lv}</span></div><div class="d" data-desc="${k}">${this.upgradeDesc(k, lv)}</div></div>
+        <button class="buy" data-act="upg" data-k="${k}" id="buy-${k}"><span class="c" id="cost-${k}">—</span><span class="n2">点击购买</span></button>
+      </div>`;
+    }).join('');
+    this.html('#upgrades', `<div class="panel-title">本轮升级</div>${rows}`);
+  }
+
+  upgradeDesc(k, lv) {
+    if (k === 'root') return `产出 <b>×${C.rootProdMul(lv + BATCH / 2).toFixed(2)}</b> · 推进速度 <b>×${C.rootSpeedMul(lv).toFixed(2)}</b>`;
+    return `跳关触发率 <b>${fmtPct(C.canopySkip(lv), 1)}</b>(每级 +1.2%,封顶 60%)`;
+  }
+
+  refreshUpgradeButtons() {
+    const s = this.s;
+    for (const k of C.UPGRADE_KINDS) {
+      const btn = $('#buy-' + k);
+      if (!btn) continue;
+      const lv = s.upgrades[k] || 0;
+      const n = C.maxAffordable(k, lv, s.essence * 0.9);
+      const cost = C.batchCost(k, lv, n);
+      const can = n > 0;
+      btn.disabled = !can;
+      btn.classList.toggle('ok', can);
+      btn.classList.toggle('pulse', can && lv === 0);
+      this.setText('#cost-' + k, can ? `${n} 级 · ${fmt(cost)}` : `${fmt(C.costOf(k, lv))}`);
+      const d = $(`#upgrades [data-desc="${k}"]`);
+      if (d) { const v = this.upgradeDesc(k, lv); if (d.innerHTML !== v) d.innerHTML = v; }
+    }
+  }
+
+  refreshLives() {
+    const s = this.s;
+    if (!this.lifeEls) {
+      const raceHead = (r) => `<div class="race-head"><span class="chip" style="background:${C.RACES[r].color}">${r}</span><span style="font-weight:500;letter-spacing:0;text-transform:none">${C.RACES[r].bond.split(':')[0]}</span><span class="bond" id="bond-${r}"></span></div>`;
+      const lifeRow = (l) => `<div class="life" data-life="${l.id}" id="life-${l.id}"><div class="ic">${lifeIcon(l.icon)}</div><div class="info"><div class="n"><span>${l.name}</span><span class="lv" id="life-desc-${l.id}"></span></div><div class="s">${l.skill}</div></div><button class="buy" data-act="life" data-id="${l.id}" id="life-buy-${l.id}"><span class="c"></span></button></div>`;
+      const block = (r) => `<div class="race-block">${raceHead(r)}${C.LIVES.filter((l) => l.race === r).map(lifeRow).join('')}</div>`;
+      this.html('#lives', `<div class="panel-title">兵种 · 常驻跑道</div>${block('生命')}${block('星穹')}${block('虚空')}`);
+      this.lifeEls = true;
+      this.lifeEls = true;
+    }
+    const sk = F.lifeSkill(s);
+    const bondN = sk.stacks;
+    for (const r of Object.keys(C.RACES)) {
+      const el = $('#bond-' + r);
+      if (el) {
+        const txt = r === '虚空' ? `跳关 +${(bondN[r] * C.RACE_SKIP_BONUS * 100).toFixed(0)}%` : `×${Math.pow(1.3, bondN[r]).toFixed(2)}`;
+        if (el.textContent !== txt) el.textContent = txt;
+        el.classList.toggle('on', bondN[r] > 0);
+      }
+    }
+    C.LIVES.forEach((l, i) => {
+      const row = $('#life-' + l.id);
+      if (!row) return;
+      const unlocked = F.lifeUnlocked(s, i);
+      const lv = s.lives[l.id] || 0;
+      row.classList.toggle('locked', !unlocked);
+      this.setText('#life-desc-' + l.id, unlocked ? `Lv ${lv}` : '未解锁');
+      const btn = $('#life-buy-' + l.id);
+      const cost = F.lifeCost(s, l.id);
+      const can = unlocked && s.essence >= cost;
+      btn.disabled = !can;
+      btn.classList.toggle('ok', can);
+      btn.innerHTML = unlocked ? `<span class="c">${fmt(cost)}</span><span style="font-size:10px;color:var(--muted)">本源</span>` : `<span class="c" style="color:var(--muted)">锁定</span>`;
+    });
+  }
+
+  renderRight() {
+    this.renderRebirthStatic();
+    this.renderPerm();
+    this.renderPlanes();
+  }
+
+  renderRebirthStatic() {
+    this.html('#rebirth', `
+      <div class="panel-title">时间回溯</div>
+      <div class="reb-card">
+        <div class="k">预计炼化</div>
+        <div class="v"><span id="reb-gain">0</span><small>结晶</small></div>
+        <div class="line"><span>本轮深度 <b id="reb-depth">0</b></span><span>回溯代价 <b id="reb-cost">1</b></span><span>收益效率 <b id="reb-eff">—</b></span></div>
+      </div>
+      <div class="actions" style="grid-template-columns:1fr 1fr;margin-top:9px">
+        <button class="act primary" data-act="rebirth" id="btn-rebirth"><span class="t">回溯 ${'<span class="kbd">R</span>'}</span><span class="s" id="reb-sub">炼化时间结晶</span></button>
+        <button class="act" data-act="auto" id="btn-auto"><span class="t">禅定</span><span class="s" id="auto-sub">挂机自动回溯</span></button>
+      </div>
+      <div class="sub-line" style="margin-top:8px"><span>自由轮回加成 <b id="reb-freedom">×1.00</b></span><span>转生衰减 <b id="reb-decay">×1</b></span></div>`);
+  }
+
+  refreshRebirth() {
+    const s = this.s;
+    const st = this.stats || F.computeStats(s);
+    const T = s.maxLayerRound || 0;
+    const gain = st.reward;
+    const cost = C.rebirthCost(T);
+    this.setText('#reb-gain', fmt(gain));
+    this.setText('#reb-depth', fmt(Math.max(T, s.layer || 0), { int: true }));
+    this.setText('#reb-cost', fmt(cost, { int: true }));
+    this.setText('#reb-eff', `×${(gain / Math.max(1, cost)).toFixed(2)}`);
+    const btn = $('#btn-rebirth');
+    btn.classList.toggle('can', gain / Math.max(1, cost) >= 1);
+    const r = F.rebirthFloor(s);
+    const btnS = $('#reb-sub');
+    const sub = s.escaped ? '逃逸完成 · 可自由轮回' : `下一轮回从第 ${fmt(r, { int: true })} 层起飞`;
+    if (btnS.textContent !== sub) btnS.textContent = sub;
+    btn.disabled = (T < 3) || !!s.planeRun;
+    this.setText('#reb-freedom', '×' + C.freedomMul(s).toFixed(2));
+    this.setText('#reb-decay', '×' + Math.pow(0.5, 0).toFixed(0));
+  }
+
+  renderPerm() {
+    const s = this.s;
+    const nextCost = C.treeCost(s.treeLv);
+    const nextProd = C.treeProdMul(s.treeLv + 1) / C.treeProdMul(s.treeLv);
+    const nextSpd = C.treeSpeedMul(s.treeLv + 1) / C.treeSpeedMul(s.treeLv);
+    const relicCost = s.relics.length < 8 ? C.relicCost(s.relics.length) : null;
+    const relics = C.RELICS.map((r, i) => `<div class="relic ${i < s.relics.length ? '' : 'off'}" title="${r.name}:${r.desc}">${relicIcon(r.icon)}</div>`).join('');
+    this.html('#perm', `
+      <div class="panel-title">永久投资 · 时间结晶</div>
+      <div class="perm">
+        <div class="info"><div class="n"><span>世界树等级 <span style="font-size:11px;color:var(--muted);font-weight:500">D${s.treeLv}</span></span></div>
+          <div class="d">产出 ×${nextProd.toFixed(2)} · 速度 ×${nextSpd.toFixed(2)}(永久)</div></div>
+        <button class="buy" data-act="buy-tree" id="buy-tree"><span class="c" id="tree-cost">${fmt(nextCost, { int: true })}</span><span style="font-size:10px;color:var(--muted)">结晶</span></button>
+      </div>
+      <div class="perm">
+        <div class="info"><div class="n"><span>遗物 ${s.relics.length}/8</span></div><div class="d">每件 本源产出 ×1.25(独立乘区)</div>
+          <div class="relics">${relics}</div></div>
+        <button class="buy" data-act="buy-relic" id="buy-relic" ${relicCost == null ? 'disabled' : ''}><span class="c" id="relic-cost">${relicCost == null ? '已收集' : fmt(relicCost, { int: true })}</span><span style="font-size:10px;color:var(--muted)">结晶</span></button>
+      </div>`);
+  }
+
+  refreshPermButtons() {
+    const s = this.s;
+    const tb = $('#buy-tree');
+    if (tb) { const can = s.crystals >= C.treeCost(s.treeLv); tb.disabled = !can; tb.classList.toggle('ok', can); }
+    const rb = $('#buy-relic');
+    if (rb && s.relics.length < 8) { const can = s.crystals >= C.relicCost(s.relics.length); rb.disabled = !can; rb.classList.toggle('ok', can); }
+  }
+
+  renderPlanes() {
+    const s = this.s;
+    const cards = C.PLANES.map((p, i) => {
+      const ex = s.planes[i].explore;
+      const unlocked = C.planeUnlocked(s, i);
+      const tier = C.exploreTierOf(ex);
+      const lock = i > 0 ? C.PLANE_UNLOCK_AT.find((u) => u.plane === i) : null;
+      return `<button class="plane-card ${s.currentPlane === i ? 'cur' : ''} ${unlocked ? '' : 'locked'}" data-act="plane" data-p="${i}" ${unlocked ? '' : 'disabled'}>
+        <span class="tier" style="background:${p.color}">${p.tier}</span>
+        <div class="nm">${p.name}</div>
+        <div class="met">${p.metric} · ${p.essence}</div>
+        <div class="bar"><i style="width:${ex}%;background:${p.color}"></i></div>
+        <div class="ex"><span>探索 ${ex.toFixed(0)}/100 · ${tier.at ? tier.label.split(',')[0] : '未勘探'}</span>${ex >= 100 ? '<span class="an">已锚定</span>' : ''}</div>
+        ${unlocked ? '' : `<div class="ex"><span>需 ${C.PLANES[lock.from].name} 锚定</span></div>`}
+      </button>`;
+    }).join('');
+    const p = C.PLANES[s.currentPlane];
+    this.html('#planes', `<div class="panel-title">位面 · 规则模板</div>
+      <div class="plane-list">${cards}</div>
+      <div class="plane-note"><b>${p.name}规则</b>:${p.rule}<br><b>加成</b>:${p.bonus}</div>`);
+  }
+
+  renderActions() {
+    if (this.actionsKey === 'built') return;
+    this.actionsKey = 'built';
+    const s = this.s;
+    const riftCd = s.riftCdSec || 0;
+    this.html('#actions', `
+      <button class="act primary" data-act="rebirth"><span class="t">回溯 <span class="kbd">R</span></span><span class="s">炼化时间结晶 · 重置本轮</span></button>
+      <button class="act" data-act="rift" id="btn-rift"><span class="t">里世界 <span class="kbd">T</span></span><span class="s" id="rift-sub">${riftCd > 0 ? `冷却 ${Math.ceil(riftCd)} 秒` : '时空裂缝 · 探索位面'}</span></button>
+      <button class="act" data-act="auto" id="btn-auto2"><span class="t">禅定 <span class="kbd">A</span></span><span class="s">${s.autoOn ? `开启 · 每 ${S.autoRebirthEvery(s)} 秒` : '挂机自动回溯'}</span></button>
+      <button class="act" data-act="save"><span class="t">存档</span><span class="s">导出 / 导入 / 重置</span></button>`);
+  }
+
+  refreshAutoButtons() {
+    const s = this.s;
+    for (const id of ['btn-auto', 'btn-auto2']) {
+      const b = $('#' + id);
+      if (!b) continue;
+      b.classList.toggle('primary', !!s.autoOn);
+      b.classList.toggle('can', !s.autoOn && s.rebirths === 0 && s.playSec > 20);
+    }
+    if ($('#auto-sub')) this.setText('#auto-sub', s.autoOn ? `每 ${S.autoRebirthEvery(s)} 秒 · 已开启(点击关闭)` : '挂机时自动回溯');
+  }
+
+  refreshActions() {
+    const s = this.s;
+    const sub = $('#rift-sub');
+    if (sub) { const v = (s.riftCdSec || 0) > 0 ? `冷却 ${Math.ceil(s.riftCdSec)} 秒` : '时空裂缝 · 探索位面'; if (sub.textContent !== v) sub.textContent = v; }
+    const b = $('#btn-rift'); if (b) b.disabled = (s.riftCdSec || 0) > 0;
+    const sub2 = $('#btn-auto2 .s'); if (sub2) { const v = s.autoOn ? `开启 · 每 ${S.autoRebirthEvery(s)} 秒` : '挂机自动回溯'; if (sub2.textContent !== v) sub2.textContent = v; }
+    const a2 = $('#btn-auto2'); if (a2) { a2.classList.toggle('can', !s.autoOn && s.rebirths === 0 && s.playSec > 20); }
+    const cd = $('#plane-cd'); if (cd) { const v = s.planes.filter((p) => p.explore >= 100).length ? `锚定 ${s.planes.filter((p) => p.explore >= 100).length} 处采集中` : '未锚定'; if (cd.textContent !== v) cd.textContent = v; }
+    this.refreshPermButtons();
+  }
+
+  // ───────────── 日志 ─────────────
+  log(text, kind = 'info') {
+    const feed = $('#feed');
+    if (!feed) return;
+    const row = document.createElement('div');
+    row.className = 'row ' + kind;
+    const t = new Date();
+    row.innerHTML = `<time>${String(t.getHours()).padStart(2, '0')}:${String(t.getMinutes()).padStart(2, '0')}:${String(t.getSeconds()).padStart(2, '0')}</time><span>${esc(text)}</span>`;
+    feed.prepend(row);
+    while (feed.children.length > 40) feed.lastChild.remove();
+  }
+
+  toast(text, kind = '') {
+    const el = document.createElement('div');
+    el.className = 'toast ' + kind;
+    el.textContent = text;
+    $('#toasts').appendChild(el);
+    setTimeout(() => { el.style.opacity = '0'; el.style.transition = 'opacity .3s'; setTimeout(() => el.remove(), 320); }, 2400);
+    while ($('#toasts').children.length > 3) $('#toasts').firstChild.remove();
+  }
+
+  // ───────────── 弹窗队列 ─────────────
+  pushDialog(d) {
+    if (d.kind === 'civ' && this.dialog && this.dialog.kind === 'civ') return;
+    this.dialogQueue.push(d);
+    if (!this.modalOpen) this.nextDialog();
+  }
+
+  nextDialog() {
+    const d = this.dialogQueue.shift();
+    if (!d) { this.closeModal(); return; }
+    this.dialog = d;
+    this.openModal(d);
+  }
+
+  beginModal() { this.modalOpen = true; $('#modal-mask').hidden = false; }
+
+  closeModal() {
+    this.modalOpen = false;
+    this.dialog = null;
+    $('#modal-mask').hidden = true;
+  }
+
+  setModal(tag, tagCls, title, bodyHtml, footHtml) {
+    $('#modal-tag').className = 'mtag ' + tagCls;
+    $('#modal-tag').textContent = tag;
+    $('#modal-title').textContent = title;
+    $('#modal-body').innerHTML = bodyHtml;
+    $('#modal-foot').innerHTML = footHtml || '';
+  }
+
+  closeDialog() {
+    this.dialog = null;
+    if (this.dialogQueue.length) this.nextDialog();
+    else this.closeModal();
+  }
+
+  // ───────────── 交互 ─────────────
+  bindKeys() {
+    document.addEventListener('keydown', (e) => {
+      if (e.target && /INPUT|TEXTAREA/.test(e.target.tagName)) return;
+      if (this.riftRun && this.riftRun.state === 'fight' && /^[0-9]$/.test(e.key)) { this.rollRift(+e.key); return; }
+      if (this.riftRun && this.riftRun.state === 'fight' && e.key === 'ArrowRight') { this.rollRift(5); return; }
+      if (this.modalOpen) {
+        if (e.key === 'Escape' && this.dialog && this.dialog.kind !== 'crisis') this.closeDialog();
+        return;
+      }
+      const k = e.key.toLowerCase();
+      if (k === 'r') this.doRebirth();
+      else if (k === 't') this.startRift();
+      else if (k === 'a') this.toggleAuto();
+      else if (k === '1') this.buy('root');
+      else if (k === '2') this.buy('canopy');
+      else if (k === 'q' && this.riftRun) this.rollRift(5);
+    });
+  }
+
+  bindEvents() {
+    $('#main').addEventListener('click', (e) => {
+      const rb = e.target.closest('[data-r]');
+      if (rb) { this.riftAction(rb.dataset.r, rb.dataset.k, rb.dataset.i); return; }
+      const b = e.target.closest('[data-act]');
+      if (!b) return;
+      const act = b.dataset.act;
+      if (act === 'upg') this.buy(b.dataset.k);
+      else if (act === 'life') this.buyLife(b.dataset.id);
+      else if (act === 'rebirth') this.doRebirth();
+      else if (act === 'auto') this.toggleAuto();
+      else if (act === 'rift') this.startRift();
+      else if (act === 'save') this.openSave();
+      else if (act === 'buy-tree') { if (S.buyTree(this.s)) { this.toast(`世界树升至 D${this.s.treeLv}`, 'good'); this.renderPerm(); } }
+      else if (act === 'buy-relic') { if (S.buyRelic(this.s)) { this.toast('获得遗物:' + C.RELICS[this.s.relics.length - 1].name, 'good'); this.renderPerm(); } this.log(`遗物入手:${C.RELICS[this.s.relics.length - 1] ? C.RELICS[this.s.relics.length - 1].name : ''}`, 'mile'); }
+      else if (act === 'plane') this.switchPlane(+b.dataset.p);
+      else if (act === 'guide-x') { this.s.flags.guideDone = true; this.renderMainline(); this.toast('提示已收起。'); }
+  
+      this.saveNow();
+    });
+    $('#modal').addEventListener('click', (e) => {
+      const b = e.target.closest('[data-mact]');
+      if (!b) return;
+      const m = b.dataset.mact;
+      if (m === 'close') this.closeDialog();
+      else if (m === 'crisis') this.answerCrisis(b.dataset.i);
+      else if (m === 'civ') this.answerCiv(+b.dataset.i);
+      else if (m === 'save') this.saveActions(b.dataset.sub);
+    });
+    $('#modal-x').addEventListener('click', () => {
+      if (this.dialog && this.dialog.kind === 'crisis') return;
+      this.closeDialog();
+    });
+    const ts = $('.top-save'); if (ts) ts.addEventListener('click', () => this.openSave());
+    $$('.vp-btn').forEach((b) => b.addEventListener('click', () => {
+      $$('.vp-btn').forEach((x) => x.classList.toggle('on', x === b));
+      document.body.classList.toggle('vp-phone', b.dataset.vp === 'phone');
+      this.scene._resize();
+    }));
+    $$('#tabbar button').forEach((b) => b.addEventListener('click', () => {
+      $$('#tabbar button').forEach((x) => x.classList.toggle('on', x === b));
+      const tab = b.dataset.tab;
+      if (tab === 'rift') { this.startRift(); return; }
+      $$('.main > .col').forEach((c) => c.classList.toggle('active', c.id === 'col-' + tab));
+      $('#main').classList.remove('show-right');
+      this.scene._resize();
+    }));
+    window.addEventListener('beforeunload', () => this.saveNow());
+    document.addEventListener('visibilitychange', () => {
+      if (document.hidden) this.saveNow();
+      else this.checkOffline();
+    });
+  }
+
+  buy(kind) {
+    const r = S.buyUpgrade(this.s, kind);
+    if (r) {
+      const el = $('#buy-' + kind);
+      if (el) { el.style.transform = 'scale(.96)'; setTimeout(() => (el.style.transform = ''), 120); }
+    }
+  }
+
+  buyLife(id) { if (S.buyLife(this.s, id)) this.saveNow(); }
+
+  doRebirth() {
+    const s = this.s;
+    if (s.planeRun) { this.toast('里世界中主世界时间冻结,无法回溯。', 'warn'); return; }
+    if ((s.maxLayerRound || 0) < 3) { this.toast('先让世界树长到第 3 层以上。'); return; }
+    const est = F.rebirthEstimate(s);
+    const r = S.rebirth(s);
+    this.log(`回溯 #${s.rebirths} · 炼化 ${fmt(r.gain)} 结晶 · 种子落在第 ${fmt(r.floor, { int: true })} 层`, 'mile');
+    this.toast(`回溯完成:+${fmt(r.gain)} 时间结晶`, 'good');
+    if (r.event) this.pushDialog({ kind: 'milestone', data: r.event });
+    this.renderLeft(); this.renderRight(); this.renderDynamic();
+    this.saveNow();
+  }
+
+  toggleAuto() {
+    const s = this.s;
+    s.autoOn = !s.autoOn;
+    this.toast(s.autoOn ? `禅定开启:每 ${S.autoRebirthEvery(s)} 秒自动回溯` : '禅定关闭:手动决定回溯时机', s.autoOn ? 'good' : '');
+    this.renderActions(); this.renderDynamic();
+    this.saveNow();
+  }
+
+  switchPlane(p) {
+    if (p === this.s.currentPlane) return;
+    if (S.switchPlane(this.s, p)) {
+      this.log(`切换位面:${C.PLANES[p].name} —— ${C.PLANES[p].rule}`, 'mile');
+      this.toast(`进入${C.PLANES[p].name}:${C.PLANES[p].bonus}`);
+      this.renderLeft(); this.renderRight(); this.renderDynamic();
+    }
+  }
+
+  // ───────────── 事件弹窗 ─────────────
+  showCrisis() {
+    const s = this.s;
+    const ev = CRISIS_EVENTS[(s.escapeCount || 0 + s.rebirths) % CRISIS_EVENTS.length];
+    const left = Math.max(0, Math.ceil((s.crisis.popUntil || 0)));
+    this.setModal('危机事件', 'crisis', ev.title,
+      `<p>${esc(ev.text)}</p><p class="cd">侵蚀前沿正在逼近:<b id="crisis-cd">${left}</b> 秒内不响应,前沿将吞没 3 层根系并压低产出。</p>
+       <div class="opts">${ev.options.map((o, i) => `<button class="opt" data-mact="crisis" data-i="${o.effect}"><div class="l">${esc(o.label)}</div><div class="h">${esc(o.hint)}</div></button>`).join('')}</div>`);
+    this.crisisTimer = setInterval(() => {
+      const e = $('#crisis-cd');
+      const l = Math.max(0, Math.ceil((this.s.crisis.popUntil || 0)));
+      if (e) e.textContent = l;
+      if (l <= 0 || !this.s.crisis.active) { clearInterval(this.crisisTimer); if (this.dialog && this.dialog.kind === 'crisis') this.closeDialog(); }
+    }, 1000);
+  }
+
+  answerCrisis(effect) {
+    const t = S.crisisRespond(this.s, effect);
+    clearInterval(this.crisisTimer);
+    if (t) { this.log('危机响应:' + t, 'crisis'); this.toast(t, 'warn'); }
+    this.closeDialog();
+  }
+
+  showCiv(idx) {
+    const ev = CIV_EVENTS[idx];
+    const stage = C.CHAPTERS[C.chapterOf(this.s.layer)].short;
+    this.setModal(`文明事件 · ${stage}`, 'civ', ev.title,
+      `<p>${esc(ev.text)}</p><div class="opts">${ev.opts.map((o, i) => `<button class="opt" data-mact="civ" data-i="${i}"><div class="l">${esc(o.label)}</div><div class="h">${esc(o.hint)}</div></button>`).join('')}</div>`);
+  }
+
+  answerCiv(i) {
+    const t = S.civChoose(this.s, this.dialog.civIdx, i);
+    if (t) { this.log(`文明事件:${CIV_EVENTS[this.dialog.civIdx].title} —— ${t}`, 'mile'); this.toast(t, 'good'); }
+    this.closeDialog();
+    this.renderRight();
+  }
+
+  showMilestone(d) {
+    this.setModal('里程碑', 'mile', d.title || '里程碑', `<p>${esc(d.text || '')}</p>`,
+      `<button class="btn" data-mact="close">继续前行</button>`);
+    this.log(`【${d.title || '里程碑'}】${d.text || ''}`, 'mile');
+  }
+
+  openModal(d) {
+    this.beginModal();
+    if (d.kind === 'crisis') this.showCrisis();
+    else if (d.kind === 'civ') this.showCiv(d.civIdx);
+    else if (d.kind === 'milestone') this.showMilestone(d.data);
+    else if (d.kind === 'save') this.showSave(this._saveSub);
+    else if (d.kind === 'offline') this.showOffline(d.data);
+    else if (d.kind === 'riftResult') this.showRiftResult(d.data);
+  }
+
+  // ───────────── 存档 ─────────────
+  saveNow() { S.save.write(localStorage, this.s, this.riftRun ? { run: this.riftRun } : null); }
+
+  openSave() { this._saveSub = null; this.dialogQueue.push({ kind: 'save' }); if (!this.modalOpen) this.nextDialog(); }
+
+  showSave(sub) {
+    this._saveSub = sub || null;
+    const s = this.s;
+    if (sub === 'export') {
+      const txt = S.save.serialize(s, this.riftRun ? { run: this.riftRun } : null);
+      this.setModal('存档', '', '导出存档', `<p style="margin-top:0">复制下面的 JSON 字符串保存。导入时粘贴即可恢复(含本轮进度与里世界局内状态)。</p><textarea id="save-text" readonly>${esc(txt)}</textarea>`,
+        `<button class="btn ghost" data-mact="save" data-sub="">返回</button><button class="btn" id="copy-save">复制</button>`);
+      setTimeout(() => {
+        const ta = $('#save-text');
+        const btn = $('#copy-save');
+        const done = () => { btn.textContent = '已复制 ✓'; this.toast('存档已复制到剪贴板', 'good'); };
+        btn.onclick = () => {
+          ta.select();
+          if (navigator.clipboard && navigator.clipboard.writeText) navigator.clipboard.writeText(txt).then(done, () => { document.execCommand('copy'); done(); });
+          else { document.execCommand('copy'); done(); }
+        };
+      }, 0);
+    } else if (sub === 'import') {
+      this.setModal('存档', '', '导入存档', `<p style="margin-top:0">粘贴之前导出的 JSON。非法存档会被拒绝,不会覆盖当前进度。</p><textarea id="save-in" placeholder='{"v":1,"state":{...}}'></textarea><div id="save-msg" style="font-size:12px;color:var(--muted);margin-top:6px"></div>`,
+        `<button class="btn ghost" data-mact="save" data-sub="">返回</button><button class="btn" id="do-import">导入并覆盖</button>`);
+      setTimeout(() => {
+        $('#do-import').onclick = () => {
+          const r = S.save.parse($('#save-in').value);
+          const msg = $('#save-msg');
+          if (!r.ok) { msg.style.color = 'var(--danger)'; msg.textContent = '导入失败:' + r.error; return; }
+          S.save.write(localStorage, r.data.state, r.data.rift);
+          if (window.__wt && window.__wt !== this) { location.reload(); return; }
+          msg.style.color = 'var(--life)'; msg.textContent = '导入成功,正在恢复…';
+          setTimeout(() => location.reload(), 120);
+        };
+      }, 0);
+    } else if (sub === 'reset') {
+      this.setModal('存档', '', '硬重置', `<p style="margin-top:0">将清空本地存档并重新开始,<b>不可撤销</b>。确定要这样做吗?</p>`,
+        `<button class="btn ghost" data-mact="save" data-sub="">取消</button><button class="btn" id="do-reset" style="background:#c0492e;border-color:#c0492e">确认清空</button>`);
+      setTimeout(() => { $('#do-reset').onclick = () => { S.save.clear(localStorage); location.reload(); }; }, 0);
+    } else {
+      const info = S.save.load(localStorage);
+      let when = '尚未存档';
+      try { const raw = JSON.parse(localStorage.getItem(C.SAVE_KEY) || '{}'); when = raw.t ? new Date(raw.t).toLocaleString() : when; } catch (e) { /* ignore */ }
+      this.setModal('存档', '', '存档管理',
+        `<p style="margin-top:0">自动存档:关键操作后 + 每 30 秒 + 关闭页面前。上次保存:<b>${esc(when)}</b>。</p>
+         <div class="opts">
+           <button class="opt" data-mact="save" data-sub="export"><div class="l">导出存档</div><div class="h">生成 JSON 字符串供复制备份</div></button>
+           <button class="opt" data-mact="save" data-sub="import"><div class="l">导入存档</div><div class="h">粘贴 JSON 恢复进度(校验非法输入)</div></button>
+           <button class="opt" data-mact="save" data-sub="reset"><div class="l" style="color:var(--danger)">硬重置</div><div class="h">清空存档,二次确认</div></button>
+         </div>`, `<button class="btn ghost" data-mact="close">关闭</button>`);
+    }
+  }
+
+  saveActions(sub) {
+    if (sub) { this.showSave(sub); return; }
+    this.showSave(null);
+  }
+
+  showOffline(o) {
+    this.setModal('离线收益', '', '你不在的这段时间', `<p style="margin-top:0">离线 <b>${esc(fmtTime(o.sec))}</b>(上限 8 小时,效率 60%)。世界树自己长了一段:</p>
+      <div class="res-row"><div class="res"><div class="k">本源</div><div class="v num">+${fmt(o.essence)}</div></div><div class="res"><div class="k">层数</div><div class="v num">${fmt(o.fromLayer, { int: true })} → ${fmt(o.toLayer, { int: true })}</div></div></div>`,
+      `<button class="btn" data-mact="close">收下</button>`);
+  }
+
+  checkOffline() {
+    // 页面重新可见时按真实时间补算(离线只结算主世界)
+    const now = Date.now();
+    if (!this._lastTickAt) { this._lastTickAt = now; return; }
+    const gap = (now - this._lastTickAt) / 1000;
+    this._lastTickAt = now;
+    if (gap > 60 && !this.s.escaped) {
+      const o = S.applyOffline(this.s, gap, this.riftRun ? { run: this.riftRun } : null);
+      if (o && !o.skipped) { this.lastFrame = performance.now(); this.pushDialog({ kind: 'offline', data: o }); this.renderAll(); }
+    }
+  }
+
+  // ───────────── 里世界 ─────────────
+  startRift() {
+    const s = this.s;
+    if (this.riftRun && this.riftRun.state !== 'result') { this.showTab('center'); this.toast('里世界进行中:主世界已冻结。'); return; }
+    const run = S.startRift(s);
+    if (!run) { this.toast(`时空裂缝冷却中:${Math.ceil(s.riftCdSec)} 秒`, 'warn'); return; }
+    this.riftRun = run;
+    this.log(`进入里世界(${C.PLANES[s.currentPlane].name} · ${C.PLANES[s.currentPlane].tier})`, 'rift');
+    this.showTab('center');
+    this.renderRiftPanel();
+    this.saveNow();
+  }
+
+  showTab(tab) {
+    $$('#tabbar button').forEach((x) => x.classList.toggle('on', x.dataset.tab === tab));
+    $$('.main > .col').forEach((c) => c.classList.toggle('active', c.id === 'col-' + tab));
+    if (window.innerWidth > 760) { $$('.main > .col').forEach((c) => c.classList.add('active')); }
+    requestAnimationFrame(() => this.scene._resize());
+  }
+
+  renderRiftPanel() {
+    const r = this.riftRun;
+    const slot = $('#rift-slot');
+    const wrap = $('#canvas-wrap');
+    if (!r || r.state === 'result') { slot.hidden = true; slot.innerHTML = ''; wrap.hidden = false; $('.actions').hidden = false; this.riftPanelKey = null; return; }
+    slot.hidden = false; wrap.hidden = true; $('.actions').hidden = true;
+    if (!slot.querySelector('#rift-live')) slot.innerHTML = '<div class="panel rift-panel" id="rift-live"></div>';
+    const panel = slot.querySelector('#rift-live');
+    const key = r.state + ':' + r.step + ':' + (r.buildDone ? 1 : 0);
+    if (this.riftPanelKey === key) return;
+    this.riftPanelKey = key;
+    const env = C.RIFT_ENVS[r.plane];
+    if (r.state === 'build') {
+      const left = R.pointsLeft(r);
+      const slots = R.RULES.map((k) => {
+        const v = r.attrs[k]; const cap = r.available[k];
+        return `<div class="slot"><div class="h"><span style="color:${C.RULE_COLORS[k]}">${R.RULE_NAME[k]}</span><span style="color:var(--muted)">${v}/${cap}</span></div>
+          <div class="v">${v}</div>
+          <div class="stepper"><button data-r="and" data-k="${k}">+</button><button data-r="sub" data-k="${k}">−</button></div></div>`;
+      }).join('');
+      panel.innerHTML = `<div class="rift-head"><span class="elite-tag" style="background:${env.color}">里世界 · ${C.PLANES[r.plane].tier}</span><span class="nm">${env.name}</span><span class="kb">规则浓度 ×${r.density.toFixed(2)}</span></div>
+        <div style="font-size:12px;color:var(--muted)">${env.desc}</div>
+        <div class="build-hint">开局分配规则(本源点):剩余 <b>${left}</b> / ${r.budget}——规则总和越高,你可以调动的战力越多,同时敌人的威胁 = 你的规则总和。</div>
+        <div class="slot-bar">${slots}</div>
+        <div style="font-size:11px;color:var(--muted);margin-top:10px;line-height:1.6">知识 → 攻击 +1.5 誓约 → 生命 +4(最大项时首击豁免)<br>信念 → 生命 +1.5(最大项时每次受击回 0.5×信念) 裁决 → 攻击 +2(并额外削敌)</div>
+        <div style="display:grid;grid-template-columns:1fr 96px;gap:8px;margin-top:10px">
+          <button class="btn" data-r="build">进入 ${env.name}</button><button class="btn danger" data-r="abandon">放弃本局</button>
+        </div>`;
+    } else if (r.state === 'event') {
+      const m = r.mouth;
+      panel.innerHTML = `<div class="rift-head"><span class="elite-tag" style="background:${env.color}">奇遇 · 第 ${r.step + 1}/6 幕</span><span class="nm">${esc(m.title)}</span></div>
+        <div class="step-dots">${Array.from({ length: R.ENCOUNTERS }, (_, i) => `<i class="${i < r.step ? 'past' : i === r.step ? 'now' : ''}"></i>`).join('')}</div>
+        <div class="taunt">${esc(m.text)}</div>
+        <div class="card-opts">${m.opts.map((o) => `<button class="opt" data-r="opt" data-i="${o.j}"><div class="l">${esc(o.label)}</div><div class="h">${esc(o.hint)}</div></button>`).join('')}</div>
+        <div class="kv">${this.riftKv(r)}</div>`;
+    } else if (r.state === 'fight' || r.state === 'run') {
+      const m = r.mouth;
+      const hp = R.hpMaxOf(r), hpm = Math.max(0, r.hp);
+      const atk = R.atkOf(r);
+      const kindTag = m.type === 'boss' ? '<span class="elite-tag boss">终局</span>' : m.type === 'elite' ? '<span class="elite-tag">精英</span>' : '<span class="elite-tag" style="background:var(--muted)">战斗</span>';
+      const hints = [0, 1, 2, 3, 4, 5].map((k) => {
+        const v = Math.round(atk + k);
+        const cls = v >= m.threat * 1.75 ? 'crit-hint' : v > m.threat ? 'hint' : '';
+        return `<button class="roll-btn ${cls}" data-r="roll" data-k="${k}">${v}<div style="font-size:9px;font-weight:500;color:var(--muted)">+${k}</div></button>`;
+      }).join('');
+      const last = m.lastLog;
+      panel.innerHTML = `<div class="rift-head"><span class="elite-tag" style="background:${env.color}">${env.name} · 第 ${r.step + 1}/6 幕</span><span class="nm">${esc(m.name)}</span>${kindTag}</div>
+        <div class="taunt">“${esc(m.taunt)}”</div>
+        <div class="hpbar enemy"><i style="width:${(m.hp / m.hpMax * 100).toFixed(1)}%"></i><div class="txt">${fmt(m.hp, { int: true })} / ${fmt(m.hpMax, { int: true })}</div></div>
+        <div class="fight-grid">
+          <div class="box"><div class="k">敌人威胁 pK(拼招需 > pK,超杀 ≥ ×1.75)</div><div class="v">${m.threat}</div></div>
+          <div class="box enemy"><div class="k">你的生命 / 攻击</div><div class="v">${fmt(hpm, { int: true })}<span style="font-size:13px;color:var(--muted)"> / ${fmt(atk, { int: true })}</span></div></div>
+        </div>
+        <div class="roll-bar">${hints}</div>
+        <div style="font-size:10.5px;color:var(--muted-2);margin-top:4px">点击数字 = 挥剑(结果 = 攻击 + 临时战意 0..5;方向键/数字键也可)· <b>Q</b> 全力 5</div>
+        ${last ? `<div class="log3">上一剑:<b>${({ block: '阻断', win: '拼招', crit: '超杀' })[last.res]}</b> ${last.value} vs ${last.threat} 敌人 −${last.dmg},自己 −${last.back}</div>` : `<div class="log3">选择你的战意:拼招(> pK)削敌、超杀(≥1.75×pK)重创并自伤更少,阻断(≤ pK)会被格挡。</div>`}
+        <div class="kv">${this.riftKv(r)}</div>
+        <div style="display:flex;gap:8px;margin-top:8px"><button class="btn ghost" style="flex:1" data-r="abandon">撤退(结算本局)</button></div>`;
+    }
+  }
+
+  riftKv(r) {
+    const stepDots = Array.from({ length: R.ENCOUNTERS }, (_, i) => `<i class="${i < r.step ? 'past' : i === r.step ? 'now' : ''}"></i>`).join('');
+    return `<div>连击/分<b>${r.score}</b></div><div>生命<b>${Math.max(0, Math.round(r.hp))}/${R.hpMaxOf(r)}</b></div><div>攻击<b>${Math.round(R.atkOf(r))}</b></div><div>能量<b>${Math.round(r.energy)}</b></div><div>步数<b>${r.step + 1}/6</b></div>`;
+  }
+
+  renderRiftLive() {
+    const r = this.riftRun;
+    if (!r) return;
+    this.renderRiftPanel();
+    const panel = $('#rift-live');
+    if (!panel || panel.hidden) return;
+    // 战斗中动态部分
+    if ((r.state === 'fight' || r.state === 'run') && r.mouth) {
+      const bar = panel.querySelector('.hpbar.enemy');
+      if (bar) { bar.querySelector('i').style.width = (r.mouth.hp / r.mouth.hpMax * 100).toFixed(1) + '%'; bar.querySelector('.txt').textContent = `${fmt(r.mouth.hp, { int: true })} / ${fmt(r.mouth.hpMax, { int: true })}`; }
+      const kv = panel.querySelector('.kv');
+      if (kv) kv.innerHTML = this.riftKv(r);
+    }
+    if (r.state === 'event' && r.mouth) {
+      const dots = panel.querySelector('.step-dots');
+      if (dots) dots.innerHTML = Array.from({ length: R.ENCOUNTERS }, (_, i) => `<i class="${i < r.step ? 'past' : i === r.step ? 'now' : ''}"></i>`).join('');
+    }
+  }
+
+  riftAction(act, k, i) {
+    if (act === 'and') this.stepRiftInput(k, 1);
+    else if (act === 'sub') this.stepRiftInput(k, -1);
+    else if (act === 'build') this.riftBuild();
+    else if (act === 'abandon') this.confirmAbandon();
+    else if (act === 'opt') this.riftOption(+i);
+    else if (act === 'roll') this.rollRift(+k);
+  }
+
+  confirmAbandon() {
+    const r = this.riftRun;
+    if (!r) return;
+    if (r.state === 'build') { this.abandonRift(); return; }
+    this.setModal('里世界', 'rift', '撤退确认', `<p style="margin-top:0">提前离开本局:按当前进度结算探索碎片(失败也有价值),主世界时间随即恢复。</p>`, `<button class="btn ghost" data-mact="close">继续探索</button><button class="btn" data-mact="save" data-sub="__abandon" id="btn-abandon-ok">确认撤退</button>`);
+    setTimeout(() => { const b = $('#btn-abandon-ok'); if (b) b.onclick = () => { this.closeModal(); this.abandonRift(); }; }, 0);
+  }
+
+  stepRiftInput(k, dir) {
+    const r = this.riftRun;
+    if (!r || r.state !== 'build') return;
+    const cap = r.available[k];
+    if (dir > 0) { if (r.attrs[k] < cap && R.pointsLeft(r) > 0) r.attrs[k]++; }
+    else { if (r.attrs[k] > 1) r.attrs[k]--; }
+    this.riftPanelKey = null;
+    this.renderRiftPanel();
+  }
+
+  riftBuild() {
+    const r = this.riftRun;
+    if (!R.buildDone(r, 0)) { this.toast(`还剩 ${R.pointsLeft(r)} 点规则未分配(每项至少 1).`, 'warn'); return; }
+    this.riftPanelKey = null; this.renderRiftPanel(); this.saveNow();
+  }
+
+  riftOption(j) {
+    const r = this.riftRun;
+    const res = R.applyOption(r, j);
+    if (!res) return;
+    this.toast(res.msg || '');
+    if (res.cleared) this.finishRift();
+    this.riftPanelKey = null; this.renderRiftPanel(); this.saveNow();
+  }
+
+  rollRift(k) {
+    const r = this.riftRun;
+    if (!r || r.state !== 'fight') return;
+    const res = R.slash(r, k);
+    if (!res) return;
+    const a = R.afterSlash(r, res);
+    const label = { block: '阻断 — 被封挡', win: '拼招 — 命中', crit: '超杀 — 重创' }[res.res];
+    this.log(`里世界:${label}(${res.value} vs ${res.threat})`, 'rift');
+    if (a.cleared) this.finishRift();
+    this.riftPanelKey = null; this.renderRiftPanel(); this.saveNow();
+  }
+
+  abandonRift() {
+    const r = this.riftRun;
+    if (!r) return;
+    if (r.state !== 'result') { r.state = 'result'; r.cleared = false; r.dead = true; }
+    this.finishRift();
+  }
+
+  finishRift() {
+    const r = this.riftRun;
+    if (!r) return;
+    const res0 = R.riftResult(r, F.computeStats(Object.assign({}, this.s, { planeRun: null })).prodRaw, this.s.planes[r.plane].explore >= 100);
+    const out = S.endRift(this.s);
+    this.riftRun = null;
+    this.riftPanelKey = null;
+    this.renderRiftPanel();
+    if (!out) return;
+    const { res, events } = out;
+    this.log(`里世界结算:探索度 +${res.explore},本源 +${fmt(res.essence)}${res.shard ? ',徽记 +1' : ''}`, 'rift');
+    this.lastFrame = performance.now();
+    this.pushDialog({ kind: 'riftResult', data: res });
+    events.forEach((e) => this.pushDialog({ kind: 'milestone', data: e }));
+    this.renderLeft(); this.renderRight(); this.renderAll(); this.saveNow();
+  }
+
+  showRiftResult(res) {
+    const anchoredNote = res.anchoredNow ? '<p style="color:#1c7a48"><b>位面已锚定!</b>此后该位面将在后台自动采集本源(每 60 秒按本源秒产 2% 结算),并已解锁下一阶时空裂缝。</p>' : '';
+    this.setModal('里世界结算', 'rift', res.cleared ? '通关 · 位面回声' : '撤离 · 碎片回响',
+      `<p style="margin-top:0">${res.cleared ? '你走完了全部 6 幕,带着这个位面的规则碎片归来。' : '本局未能走完,但失败也有价值:碎片会带回到世界树。'}</p>
+       <div class="res-row">
+         <div class="res"><div class="k">探索度 +</div><div class="v num">${res.explore}</div><div class="d">${res.planeName}</div></div>
+         <div class="res"><div class="k">本源 +</div><div class="v num">${fmt(res.essence)}</div><div class="d">带回主世界</div></div>
+       </div>
+       <div class="sub-line" style="margin-top:10px"><span>得分 <b>${res.score}</b></span><span>徽记 <b>${res.shard ? '+1' : '0'}</b></span><span>步数 <b>${res.steps}/6</b></span><span>当前探索 <b>${res.anchored ? '100(已锚定)' : res.explore + ' 点增量'}</b></span></div>
+       ${anchoredNote}`,
+      `<button class="btn" data-mact="close">回到世界树</button>`);
+  }
+
+  renderAll() { this.renderStatic(); this.renderDynamic(); }
+}
+
+// 小工具:模板里表示空的占位
+function d() { return ''; }