🎮ArcadeLab

荒辙工坊 · Dustline Motorworks

by SilverScout93
6301 lines200.8 KB
▶ Play
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
<meta name="theme-color" content="#181c1a">
<title>荒辙工坊 · Dustline Motorworks</title>
<style>
:root {
  color-scheme:dark;
  --bg:#1a1d1b;
  --panel:#242825;
  --panel2:#2d322e;
  --ink:#f0eee2;
  --muted:#a3aaa0;
  --edge:#444942;
  --acid:#f5c641;
  --teal:#91c1ad;
  --mono:"IBM Plex Mono","SFMono-Regular",Consolas,"Liberation Mono",monospace;
  --sans:"Barlow","Noto Sans CJK SC","Microsoft YaHei","PingFang SC",system-ui,sans-serif;
}
* {
  box-sizing:border-box;
}
html {
  min-height:100%;
  background:var(--bg);
}
body {
  margin:0;
  color:var(--ink);
  font:14px/1.45 var(--sans);
  background:radial-gradient(ellipse at 12% 0%,#292e28 0,transparent 50%),var(--bg);
  min-height:100vh;
}
button,input,select {
  font:inherit;
  color:inherit;
}
button {
  cursor:pointer;
  border:0;
  background:none;
  padding:0;
  -webkit-tap-highlight-color:transparent;
}
button:disabled {
  opacity:.36;
  cursor:default;
}
button:focus-visible,a:focus-visible,input:focus-visible,select:focus-visible,[tabindex]:focus-visible {
  outline:2px solid #ffcf49;
  outline-offset:3px;
}
button {
  transition:background .14s,color .14s,border-color .14s,transform .12s;
}
button:active:not(:disabled) {
  transform:translateY(1px);
}
[hidden] {
  display:none!important;
}
h1,h2,h3,p {
  margin:0;
}
canvas {
  display:block;
}
.ico {
  width:18px;
  height:18px;
  flex:none;
}
.mono,.value,kbd {
  font-family:var(--mono);
  font-variant-numeric:tabular-nums;
}
.top {
  height:65px;
  background:#141715;
  border-bottom:1px solid #363c35;
}
.top-inner,.wrap {
  max-width:1570px;
  margin:auto;
  padding-left:clamp(16px,3.2vw,54px);
  padding-right:clamp(16px,3.2vw,54px);
}
.top-inner {
  height:100%;
  display:flex;
  align-items:center;
  gap:clamp(20px,4vw,67px);
}
.brand {
  display:flex;
  align-items:center;
  gap:11px;
  white-space:nowrap;
  text-align:left;
}
.brand-mark {
  width:40px;
  height:40px;
  background:var(--acid);
  border-radius:4px;
  display:grid;
  place-items:center;
}
.brand-mark canvas {
  width:34px;
  height:34px;
}
.brand-name {
  font-size:20px;
  line-height:1.12;
  letter-spacing:2px;
  font-weight:950;
}
.brand-en {
  display:block;
  margin-top:4px;
  font:700 9px/1 var(--mono);
  letter-spacing:1.55px;
  color:#b0b6aa;
}
.nav {
  align-self:stretch;
  display:flex;
  align-items:stretch;
  gap:clamp(10px,2vw,34px);
}
.nav button {
  position:relative;
  display:flex;
  align-items:center;
  gap:8px;
  font-size:13px;
  font-weight:700;
  color:#a8afa5;
  padding:0 3px;
}
.nav button:hover,.nav button.active {
  color:var(--ink);
}
.nav button.active:after {
  content:"";
  position:absolute;
  width:100%;
  height:3px;
  bottom:0;
  left:0;
  background:var(--acid);
}
.nav button.active .ico {
  color:var(--acid);
}
.top-actions {
  margin-left:auto;
  display:flex;
  align-items:center;
  gap:12px;
}
.wallet {
  display:flex;
  gap:7px;
  align-items:center;
  color:var(--acid);
  font:700 14px var(--mono);
  white-space:nowrap;
}
.top-sep {
  height:23px;
  border-left:1px solid var(--edge);
  margin:0 2px;
}
.icon-btn,.tool {
  display:inline-flex;
  align-items:center;
  justify-content:center;
  flex:none;
  border:1px solid var(--edge);
  border-radius:4px;
  width:32px;
  height:32px;
  color:#cbd0c7;
  background:#252a26;
}
.icon-btn:hover,.tool:hover,.btn:hover {
  background:#394139;
  border-color:#687267;
}
.icon-btn.quiet {
  background:transparent;
  border-color:transparent;
  width:27px;
}
.icon-btn.quiet:hover {
  background:#343b34;
}
.page-head {
  min-height:87px;
  display:flex;
  justify-content:space-between;
  align-items:center;
  gap:12px;
  padding:16px 0;
}
.heading h1 {
  font-weight:900;
  font-size:clamp(26px,2.5vw,37px);
  line-height:1.18;
  letter-spacing:1px;
}
.heading p {
  color:var(--muted);
  font-size:12px;
  margin-top:5px;
}
.head-actions,.inline,.tiny-actions {
  display:flex;
  align-items:center;
  gap:10px;
}
.saved {
  color:#b5c0b1;
  display:flex;
  align-items:center;
  gap:7px;
  font-size:12px;
}
.led {
  width:7px;
  height:7px;
  border-radius:50%;
  display:inline-block;
  background:#87c098;
  box-shadow:0 0 0 3px #86ba8c17;
}
.btn {
  display:inline-flex;
  align-items:center;
  justify-content:center;
  gap:8px;
  border:1px solid var(--edge);
  border-radius:4px;
  min-height:35px;
  padding:7px 13px;
  background:var(--panel2);
  font-weight:700;
  font-size:13px;
}
.btn.primary {
  background:var(--acid);
  border-color:var(--acid);
  color:#20251e;
}
.btn.primary:hover {
  background:#ffdb68;
}
.btn.subtle {
  background:transparent;
}
.btn.subtle:hover {
  background:var(--panel2);
}
.btn.danger {
  color:#fcac94;
}
.layout {
  display:grid;
  grid-template-columns:minmax(0,1fr) clamp(264px,24vw,342px);
  gap:17px;
  align-items:start;
}
.left,.right {
  min-width:0;
  display:grid;
  gap:15px;
}
.panel {
  border:1px solid var(--edge);
  border-radius:6px;
  background:var(--panel);
  overflow:hidden;
}
.build-stage {
  display:grid;
  grid-template-columns:minmax(0,1fr) clamp(180px,18vw,238px);
  min-width:0;
}
.layer-panel {
  min-width:0;
  background:#252a27;
  border-left:1px solid #414940;
  color:#e7eadb;
  display:flex;
  flex-direction:column;
}
.layer-head {
  display:flex;
  align-items:center;
  justify-content:space-between;
  gap:8px;
  padding:12px 11px 9px;
  border-bottom:1px solid #414940;
}
.layer-head small {
  display:block;
  color:#9ea99a;
  font:700 8px/1 var(--mono);
  letter-spacing:1.6px;
}
.layer-head h2 {
  margin-top:4px;
  font-size:17px;
  letter-spacing:.5px;
}
.layer-head .layer-add {
  width:30px;
  height:30px;
  display:grid;
  place-items:center;
  border:1px solid #647060;
  border-radius:4px;
  color:#f7d56c;
  background:#30382f;
  font-size:22px;
  line-height:1;
}
.layer-head .layer-add:hover {
  background:#3e493d;
}
.layers-list {
  flex:1;
  min-height:0;
  overflow:auto;
}
.layer-row {
  position:relative;
  display:flex;
  align-items:stretch;
  min-height:65px;
  border-bottom:1px solid #3b423d;
  transition:background .14s,transform .14s,opacity .14s;
}
.layer-row:hover {
  background:#303730;
}
.layer-row.active {
  background:#117df0;
  color:#fff;
}
.layer-row.reordering {
  opacity:.75;
  transform:scale(.985);
  box-shadow:0 0 0 1px #f5c641 inset;
}
.layer-eye {
  width:38px;
  flex:none;
  border-right:1px solid #3f4840;
  display:grid;
  place-items:center;
  color:#d9ddd0;
}
.layer-eye:hover {
  color:#f5c641;
  background:#3b443a;
}
.layer-eye .ico {
  width:20px;
  height:20px;
}
.layer-row.active .layer-eye {
  border-color:#5ca7f6;
}
.layer-main {
  flex:1;
  min-width:0;
  display:flex;
  align-items:center;
  gap:9px;
  padding:7px 7px 7px 9px;
  text-align:left;
}
.layer-thumb {
  width:52px;
  height:46px;
  flex:none;
  border-radius:7px;
  background-color:#f3f3ed;
  background-image:linear-gradient(45deg,#e5e5df 25%,transparent 25%),linear-gradient(-45deg,#e5e5df 25%,transparent 25%),linear-gradient(45deg,transparent 75%,#e5e5df 75%),linear-gradient(-45deg,transparent 75%,#e5e5df 75%);
  background-size:16px 16px;
  background-position:0 0,0 8px,8px -8px,-8px 0;
  overflow:hidden;
}
.layer-main span {
  min-width:0;
}
.layer-main b {
  display:block;
  overflow:hidden;
  text-overflow:ellipsis;
  white-space:nowrap;
  font-size:14px;
}
.layer-main small {
  display:block;
  margin-top:2px;
  color:#aab2a4;
  font:10px var(--mono);
}
.layer-row.active .layer-main small {
  color:#dbeeff;
}
.layer-drag {
  align-self:center;
  color:#8d978a;
  font:700 16px/1 var(--mono);
  letter-spacing:-3px;
  padding:0 6px 0 0;
  cursor:grab;
}
.layer-foot {
  padding:9px 11px 10px;
  border-top:1px solid #414940;
  color:#99a499;
  font-size:10px;
  line-height:1.45;
}
.layer-foot strong {
  color:#ead18b;
  font-weight:700;
}
.layer-row.hidden-layer {
  opacity:.58;
}
.layer-row.hidden-layer .layer-thumb {
  filter:grayscale(.7);
}
.drawing {
  position:relative;
  background:#cfcdb9;
  color:#28362f;
  height:clamp(315px,43.4vh,485px);
  isolation:isolate;
}
.drawing canvas#bench,.scene-canvas {
  width:100%;
  height:100%;
  touch-action:none;
}
.board-title {
  position:absolute;
  top:17px;
  left:18px;
  display:flex;
  align-items:center;
  gap:9px;
  pointer-events:none;
}
.board-title .rivet-label {
  width:4px;
  height:34px;
  background:#45544b;
}
.board-title small {
  font:700 9px var(--mono);
  letter-spacing:1.6px;
  display:block;
  color:#4b5c50;
  margin-bottom:1px;
}
.board-title b {
  font-size:18px;
  font-weight:900;
  letter-spacing:.3px;
}
.board-title button {
  pointer-events:auto;
  color:#48574d;
  width:26px;
  height:26px;
  display:grid;
  place-items:center;
  opacity:.85;
}
.board-title .ico {
  width:15px;
  height:15px;
}
.board-top-tools {
  position:absolute;
  top:13px;
  right:13px;
  display:flex;
  gap:4px;
}
.paper-btn {
  width:28px;
  height:28px;
  display:grid;
  place-items:center;
  border-radius:3px;
  color:#3b493e;
  background:#d8d9c789;
  border:1px solid #929b88;
}
.paper-btn:hover {
  background:#e7e7d3;
}
.paper-btn .ico {
  width:15px;
  height:15px;
}
.board-tools {
  position:absolute;
  bottom:12px;
  left:14px;
  right:14px;
  display:flex;
  justify-content:space-between;
  align-items:end;
  pointer-events:none;
  gap:5px;
}
.tool-group {
  pointer-events:auto;
  display:flex;
  align-items:center;
  background:#27312b;
  box-shadow:0 2px 3px #1e231e33;
  border:1px solid #384238;
  border-radius:4px;
  padding:2px;
  gap:1px;
}
.tool {
  background:transparent;
  border:0;
  color:#d4d8c7;
  width:29px;
  height:28px;
  border-radius:2px;
}
.tool.active {
  background:var(--acid);
  color:#242b24;
}
.tool.on {
  color:var(--acid);
  background:#40493c;
}
.tool .ico {
  width:15px;
  height:15px;
}
.group-rule {
  height:15px;
  border-left:1px solid #536154;
  margin:0 2px;
}
.zoom-label {
  font:700 10px var(--mono);
  text-align:center;
  min-width:38px;
  color:#d9ddcf;
}
.draw-status {
  display:flex;
  justify-content:space-between;
  align-items:center;
  gap:8px;
  min-height:34px;
  background:#2b302a;
  border-top:1px solid #4e5549;
  padding:6px 13px;
  font-size:11px;
  color:#c5cdc0;
}
.draw-status .inline {
  gap:6px;
  white-space:nowrap;
}
.draw-status .ico {
  width:14px;
  height:14px;
  color:#a7c5a4;
}
.status-right {
  color:#aab4a6;
  text-align:right;
}
.title-row {
  display:flex;
  align-items:center;
  justify-content:space-between;
  gap:7px;
}
.title-row h2,.side-title {
  font-size:16px;
  letter-spacing:.5px;
  font-weight:850;
  display:flex;
  align-items:center;
  gap:8px;
}
.title-row h2 .ico,.side-title .ico {
  color:var(--acid);
  width:17px;
  height:17px;
}
.rack {
  padding:13px 15px 15px;
}
.count {
  display:inline-block;
  color:#c0c9b9;
  font:700 10px var(--mono);
  background:#363d35;
  border:1px solid #495247;
  border-radius:3px;
  padding:2px 5px;
  letter-spacing:0;
}
.rack-controls {
  display:flex;
  gap:4px;
}
.rack-controls button {
  width:25px;
  height:24px;
}
.rack-controls .ico {
  width:13px;
  height:13px;
}
.categories {
  display:flex;
  gap:4px;
  margin:10px 0;
  overflow-x:auto;
  scrollbar-width:thin;
}
.cat {
  color:#b8c0b3;
  font-size:12px;
  padding:4px 11px;
  border:1px solid transparent;
  border-radius:3px;
  white-space:nowrap;
}
.cat:hover {
  background:#393e36;
}
.cat.active {
  background:#484433;
  border-color:#71623b;
  color:#ffda68;
}
.parts {
  display:flex;
  gap:8px;
  overflow-x:auto;
  scrollbar-width:thin;
  scrollbar-color:#596251 transparent;
  scroll-snap-type:x proximity;
  padding:1px 0 4px;
}
.part-card {
  scroll-snap-align:start;
  position:relative;
  flex:0 0 calc((100% - 40px)/6);
  min-width:87px;
  display:flex;
  flex-direction:column;
  align-items:stretch;
  border:1px solid #465044;
  border-radius:4px;
  background:linear-gradient(147deg,#353b32,#2a302b);
  text-align:left;
  overflow:hidden;
  min-height:92px;
}
.part-card:hover {
  border-color:#899476;
  background:#3c4539;
}
.part-card.active {
  border-color:var(--acid);
  box-shadow:inset 0 0 0 1px var(--acid);
}
.part-card canvas {
  width:100%;
  height:55px;
}
.part-caption {
  padding:5px 8px 7px;
  background:#272d27;
  border-top:1px solid #3c453a;
  display:flex;
  align-items:center;
  justify-content:space-between;
  gap:2px;
}
.part-caption b {
  font-size:12px;
  white-space:nowrap;
}
.part-id {
  position:absolute;
  top:4px;
  left:6px;
  color:#a1a99b;
  font:8px var(--mono);
}
.part-plus {
  font:14px var(--mono);
  color:#9aa58e;
}
.contract .side-title {
  padding:12px 15px;
  border-bottom:1px solid var(--edge);
  justify-content:space-between;
}
.side-title span,.stat-head {
  display:flex;
  align-items:center;
  gap:8px;
}
.side-title small {
  font:10px var(--mono);
  color:#b4bcae;
  letter-spacing:1px;
}
.land-card {
  height:clamp(132px,17.7vh,183px);
  position:relative;
  isolation:isolate;
  border-bottom:1px solid #504a3b;
  overflow:hidden;
  background:#ca8857;
}
.land-card canvas {
  width:100%;
  height:100%;
}
.land-caption {
  position:absolute;
  inset:auto 0 0;
  padding:22px 15px 11px;
  color:#fff2d7;
  background:linear-gradient(transparent,#271e18cb);
}
.land-caption small {
  font:700 9px var(--mono);
  letter-spacing:1.4px;
  color:#f4d8a2;
}
.land-caption h2 {
  font-size:clamp(22px,2vw,30px);
  font-weight:950;
  line-height:1.25;
  letter-spacing:1px;
}
.contract-info,.stats {
  padding:13px 15px;
}
.contract-info .detail {
  display:flex;
  justify-content:space-between;
  align-items:center;
  gap:8px;
  font-size:12px;
  margin:0 0 7px;
}
.detail span:first-child {
  color:#b2bbac;
}
.detail strong {
  font-size:12px;
  font-weight:650;
}
.gold {
  color:var(--acid);
}
.launch {
  width:100%;
  justify-content:space-between;
  margin-top:5px;
  height:39px;
  padding:0 12px;
  font-size:14px;
}
.launch span {
  display:flex;
  align-items:center;
  gap:8px;
}
.stats .title-row {
  margin-bottom:10px;
}
.stat {
  margin-top:9px;
}
.stat-label {
  display:flex;
  justify-content:space-between;
  align-items:center;
  font-size:12px;
  color:#c4cbbb;
}
.stat-label strong {
  font:700 12px var(--mono);
  color:#e0e4d7;
}
.meter {
  height:4px;
  margin-top:5px;
  background:#454c40;
  border-radius:1px;
  overflow:hidden;
}
.meter i {
  display:block;
  height:100%;
  background:#dfb94c;
}
.stat:nth-of-type(3) i {
  background:#9ab9a2;
}
.stat:nth-of-type(4) i {
  background:#cc8c66;
}
.stat-mini {
  display:flex;
  justify-content:space-between;
  padding-top:10px;
  margin-top:12px;
  border-top:1px solid #41483e;
  color:#b6bfae;
  font-size:11px;
}
.foot {
  display:flex;
  align-items:center;
  justify-content:space-between;
  gap:10px;
  flex-wrap:wrap;
  margin:16px 0 19px;
  color:#939f91;
  font-size:11px;
}
.keys,.key-item {
  display:inline-flex;
  gap:7px;
  align-items:center;
}
.keys {
  gap:13px;
  flex-wrap:wrap;
}
kbd {
  border:1px solid #4d564a;
  color:#c2c9bb;
  border-radius:3px;
  background:#2a302a;
  padding:1px 4px;
  font-size:10px;
}
.help-foot {
  display:flex;
  align-items:center;
  gap:3px;
  font-size:11px;
  color:#c1c6ac;
}
.help-foot .ico {
  width:12px;
  height:12px;
}
.inspect {
  display:flex;
  gap:6px;
  align-items:center;
  flex-wrap:wrap;
  padding:7px 10px;
  border-top:1px solid var(--edge);
  background:#32382e;
  font-size:11px;
}
.inspect strong {
  color:#ffda72;
  margin-right:4px;
}
.inspect button {
  padding:3px 7px;
  border-radius:3px;
  background:#242a24;
  border:1px solid #525d4e;
}
.inspect button:hover {
  border-color:var(--acid);
}
.inspect .desc {
  color:#c2ccba;
  flex:1;
  min-width:80px;
}
.toast {
  position:fixed;
  bottom:20px;
  left:50%;
  transform:translateX(-50%);
  padding:9px 15px;
  border-radius:4px;
  background:#202921;
  color:#fff1ce;
  border:1px solid #a38c51;
  box-shadow:0 4px 18px #0005;
  z-index:30;
  max-width:min(92vw,570px);
  text-align:center;
  font-size:13px;
  pointer-events:none;
}
.modal-wrap {
  position:fixed;
  inset:0;
  z-index:20;
  background:#0c110fba;
  display:grid;
  place-items:center;
  padding:16px;
}
.dialog {
  width:min(520px,100%);
  max-height:88dvh;
  overflow:auto;
  background:#252b25;
  border:1px solid #6a735e;
  border-top:3px solid var(--acid);
  border-radius:6px;
  box-shadow:0 18px 80px #0007;
  padding:20px;
}
.dialog.wide {
  width:min(800px,100%);
}
.dialog-title {
  display:flex;
  justify-content:space-between;
  align-items:center;
  margin-bottom:15px;
  gap:9px;
}
.dialog h2 {
  font-size:22px;
}
.dialog h3 {
  font-size:14px;
  color:#f3cd67;
  margin:14px 0 5px;
}
.dialog p {
  color:#c6cebf;
  font-size:13px;
  line-height:1.7;
}
.dialog .actions {
  display:flex;
  gap:8px;
  flex-wrap:wrap;
  margin-top:16px;
}
.dialog input,.dialog select {
  width:100%;
  padding:9px 11px;
  background:#1b211c;
  border:1px solid #5b6555;
  border-radius:3px;
  margin:6px 0;
}
.help-grid {
  display:grid;
  grid-template-columns:auto 1fr;
  gap:6px 12px;
  font-size:13px;
  color:#d0d7c9;
}
.help-grid b {
  color:#f0dda4;
}
.gallery,.perks {
  display:grid;
  grid-template-columns:repeat(auto-fit,minmax(164px,1fr));
  gap:10px;
  margin:10px 0;
}
.blue-card,.upgrade,.perk,.record {
  border:1px solid #475142;
  border-radius:4px;
  background:#2d342c;
  padding:10px;
}
.blue-card canvas {
  background:#c3c5ae;
  border-radius:3px;
  width:100%;
  height:88px;
  margin-bottom:7px;
}
.blue-card h3,.upgrade h3,.perk h3 {
  margin:0 0 3px;
  font-size:15px;
  color:var(--ink);
}
.blue-card p,.perk p,.upgrade p {
  font-size:12px;
}
.blue-card .actions {
  margin-top:8px;
}
.record,.upgrade {
  display:flex;
  justify-content:space-between;
  align-items:center;
  gap:10px;
  margin-top:7px;
}
.record small,.upgrade small {
  display:block;
  color:#b6bfac;
  margin-top:3px;
}
.perk {
  border-color:#687753;
  text-align:left;
  padding:12px;
}
.perk:hover {
  background:#3d4637;
  border-color:var(--acid);
}
.perk .ico {
  color:var(--acid);
  margin-bottom:10px;
}
.result-num {
  font:800 34px var(--mono);
  color:#f5cd5a;
}
.result-grid {
  display:flex;
  gap:25px;
  margin:10px 0;
}
.result-grid small {
  display:block;
  font-size:12px;
  color:#b8c3af;
}
.danger-text {
  color:#ffab8b;
}
.battle-top {
  display:flex;
  justify-content:space-between;
  align-items:center;
  gap:8px;
  padding:10px 0;
}
.battle-top .inline {
  flex-wrap:wrap;
}
.battle-top h1 {
  font-size:20px;
}
.tag {
  border:1px solid #56604e;
  padding:2px 7px;
  font:10px var(--mono);
  color:#d2d6bd;
  border-radius:3px;
}
.battle-frame {
  height:clamp(360px,calc(100dvh - 182px),850px);
  position:relative;
  border:1px solid #51574b;
  border-radius:6px;
  background:#d59c68;
  overflow:hidden;
  isolation:isolate;
}
.hud {
  pointer-events:none;
  position:absolute;
  inset:0;
}
.hud-left,.hud-right {
  position:absolute;
  top:12px;
  background:#1b241eeb;
  color:#f1f2da;
  border:1px solid #7e846957;
  padding:10px 12px;
  border-radius:4px;
  min-width:148px;
}
.hud-left {
  left:12px;
}
.hud-right {
  right:12px;
  max-width:46%;
  text-align:right;
}
.hud-left b,.hud-right b {
  display:block;
  font-size:13px;
}
.hud-right small,.hud-left small {
  display:block;
  color:#d0d6bb;
  font-size:10px;
  margin-top:4px;
}
.hud-meter {
  height:5px;
  background:#61705a;
  margin:5px 0 3px;
}
.hud-meter i {
  display:block;
  height:100%;
  background:#c1d99c;
}
.hud-meter.energy i {
  background:#e9bd53;
}
.hud-meter.heat i {
  background:#e59169;
}
.hud-center {
  position:absolute;
  left:50%;
  top:16px;
  transform:translateX(-50%);
  color:#232c23;
  background:#efcd75e8;
  padding:5px 12px;
  font-weight:800;
  font-size:12px;
  border-radius:3px;
  max-width:45%;
  text-align:center;
}
.touchbar {
  position:absolute;
  bottom:12px;
  left:12px;
  right:12px;
  display:flex;
  justify-content:space-between;
  gap:6px;
  pointer-events:none;
}
.touch-group {
  display:flex;
  gap:6px;
}
.touch-button {
  pointer-events:auto;
  touch-action:none;
  user-select:none;
  background:#202920d9;
  border:1px solid #9fa68a9c;
  border-radius:5px;
  color:#f8edc8;
  font-size:13px;
  font-weight:800;
  min-width:44px;
  height:39px;
  padding:0 9px;
  display:grid;
  place-items:center;
}
.touch-button.hot,.touch-button:active {
  background:#dec054;
  color:#20271f;
}
.drive-strip {
  display:flex;
  gap:10px;
  justify-content:space-between;
  align-items:center;
  margin-top:12px;
  font-size:12px;
  color:#b9c3b3;
}
.dialog details {
  margin:10px 0;
}
.dialog summary {
  cursor:pointer;
  font-weight:700;
  color:#f0d080;
}
.number-grid {
  display:grid;
  grid-template-columns:repeat(auto-fit,minmax(160px,1fr));
  gap:7px 15px;
  margin-top:12px;
}
.number-label {
  font-size:12px;
  color:#d5ddcc;
}
.mobile-launch {
  display:none;
}
.heading {
  min-width:0;
}
.head-actions {
  flex-shrink:0;
}
.mod-btn {
  display:inline-flex;
  align-items:center;
  gap:5px;
  color:#d3c58c;
  font-size:11px;
  padding:4px 6px;
  border:1px solid #515746;
  border-radius:3px;
}
.mod-btn .ico {
  width:13px;
  height:13px;
}
.mod-btn:hover {
  background:#3c4335;
}
.manifest-row {
  display:flex;
  width:100%;
  padding:8px 7px;
  border-bottom:1px solid #455040;
  justify-content:space-between;
  gap:6px;
  text-align:left;
}
.manifest-row:hover {
  background:#374135;
}
.manifest-row span {
  font-size:12px;
  color:#b7c4ad;
}
#contractHud {
  color:#e3cd92;
}
@media(min-width:1600px) {
  .drawing {
    height:480px;
  }
  .part-card canvas {
    height:68px;
  }
}
@media(max-width:1000px) {
  .top-inner,.wrap {
    padding-left:16px;
    padding-right:16px;
  }
  .top-inner {
    gap:25px;
  }
  .layout {
    grid-template-columns:minmax(0,1fr) 248px;
    gap:12px;
  }
  .part-card {
    flex-basis:calc((100% - 24px)/4);
  }
  .right,.left {
    gap:12px;
  }
  .drawing {
    height:clamp(300px,44vh,430px);
  }
  .build-stage {
    grid-template-columns:minmax(0,1fr) 188px;
  }
  .brand-en {
    letter-spacing:1px;
  }
  .rack {
    padding:11px;
  }
  .contract-info,.stats {
    padding:11px 12px;
  }
}
@media(max-width:760px) {
  .mobile-launch {
    display:inline-flex;
  }
  .top {
    height:55px;
  }
  .top-inner {
    gap:14px;
  }
  .nav {
    gap:13px;
  }
  .nav button {
    font-size:12px;
  }
  .nav .ico {
    display:none;
  }
  .brand-mark {
    width:32px;
    height:32px;
  }
  .brand-mark canvas {
    width:28px;
    height:28px;
  }
  .brand {
    gap:7px;
  }
  .brand-name {
    font-size:16px;
    letter-spacing:1px;
  }
  .brand-en {
    font-size:7px;
  }
  .top-actions {
    gap:5px;
  }
  .page-head {
    min-height:72px;
  }
  .layout {
    grid-template-columns:minmax(0,1fr);
  }
  .right {
    grid-template-columns:1.05fr 1fr;
    align-items:start;
  }
  .drawing {
    height:clamp(290px,47vh,420px);
  }
  .build-stage {
    grid-template-columns:minmax(0,1fr) 176px;
  }
  .layer-thumb {
    width:43px;
    height:40px;
  }
  .layer-main {
    gap:6px;
    padding-left:6px;
  }
  .part-card {
    flex-basis:calc((100% - 40px)/6);
  }
  .land-card {
    height:124px;
  }
  .status-right {
    font-size:10px;
  }
  .saved {
    font-size:10px;
  }
  .foot {
    margin:12px 0;
  }
  .battle-frame {
    height:calc(100dvh - 164px);
  }
  .hud-center {
    top:85px;
    max-width:75%;
  }
}
@media(max-width:520px) {
  .head-actions .btn {
    padding:5px 7px;
    font-size:12px;
    min-height:32px;
  }
  .head-actions .btn .ico {
    width:15px;
    height:15px;
  }
  .top-inner,.wrap {
    padding-left:10px;
    padding-right:10px;
  }
  .top-inner {
    gap:10px;
  }
  .nav {
    gap:8px;
  }
  .nav button {
    font-size:11px;
  }
  .top-sep {
    display:none;
  }
  .brand-en {
    display:none;
  }
  .brand-name {
    font-size:15px;
  }
  .top-actions .quiet {
    width:22px;
  }
  .wallet {
    font-size:12px;
    gap:3px;
  }
  .wallet .ico {
    width:15px;
  }
  .heading p {
    font-size:11px;
  }
  .head-actions {
    gap:7px;
  }
  .saved {
    display:none;
  }
  .page-head {
    padding:12px 0;
  }
  .drawing {
    height:clamp(260px,40vh,365px);
  }
  .build-stage {
    grid-template-columns:1fr;
  }
  .layer-panel {
    border-left:0;
    border-top:1px solid #414940;
    max-height:260px;
  }
  .layers-list {
    display:grid;
    grid-template-columns:repeat(2,minmax(0,1fr));
  }
  .layer-row {
    min-height:58px;
  }
  .layer-foot {
    display:none;
  }
  .board-title {
    top:11px;
    left:11px;
  }
  .board-title b {
    font-size:16px;
  }
  .board-tools {
    left:7px;
    right:7px;
    bottom:7px;
  }
  .tool {
    width:26px;
    height:26px;
  }
  .zoom-label {
    min-width:31px;
  }
  .part-card {
    flex-basis:calc((100% - 24px)/4);
    min-width:76px;
  }
  .cat {
    padding:3px 7px;
  }
  .categories {
    gap:1px;
  }
  .rack {
    padding:9px;
  }
  .right {
    grid-template-columns:1fr;
  }
  .right .stats {
    order:2;
  }
  .land-card {
    height:135px;
  }
  .inspect .desc {
    flex-basis:100%;
  }
  .battle-top h1 {
    font-size:16px;
  }
  .battle-top .tag {
    display:none;
  }
  .hud-left,.hud-right {
    padding:6px 8px;
    min-width:111px;
    top:7px;
  }
  .hud-left {
    left:7px;
  }
  .hud-right {
    right:7px;
  }
  .hud-right small {
    font-size:9px;
  }
  .drive-strip {
    display:none;
  }
  .battle-frame {
    height:calc(100dvh - 120px);
    min-height:270px;
  }
  .touchbar {
    left:6px;
    right:6px;
    bottom:7px;
  }
  .touch-group {
    gap:4px;
  }
  .touch-button {
    min-width:35px;
    padding:0 7px;
  }
  .board-top-tools {
    top:9px;
    right:9px;
  }
}
@media(max-height:570px) and (orientation:landscape) {
  body.in-battle .top {
    display:none;
  }
  .battle-top {
    padding:4px 0;
  }
  .battle-frame {
    height:calc(100dvh - 49px);
    min-height:190px;
  }
  .drive-strip {
    display:none;
  }
  .hud-center {
    top:10px;
  }
  .modal-wrap {
    padding:6px;
  }
  .dialog {
    max-height:95dvh;
  }
}
@media(max-width:370px) {
  .brand>span:last-child {
    display:none;
  }
  .top-inner {
    gap:7px;
  }
  .heading p {
    max-width:185px;
  }
}
@media(prefers-reduced-motion:reduce) {
  * {
    scroll-behavior:auto!important;
    transition:none!important;
  }
}
</style>
<link rel="stylesheet" href="/Static/css/Global.css"/><link rel="stylesheet" href="/Web/css/Global.css"/><link rel="stylesheet" href="/Web/css/OneOpenAI.css"/><link rel="stylesheet" href="/Static/css/Global.css"/><link rel="stylesheet" href="/Web/css/Global.css"/><link rel="stylesheet" href="/Web/css/OneOpenAI.css"/><script src="/_ooa/custom.js" data-oneopenai-custom-js></script><script src="/_ooa/frontend-runtime-guard.js" data-oneopenai-runtime-guard></script><script src="/_ooa/pet.js" data-oneopenai-pet-js defer></script><script src="/_ooa/user-custom.js" data-oneopenai-user-custom-js defer></script><link rel="stylesheet" href="/Static/css/Global.css"/><link rel="stylesheet" href="/Web/css/Global.css"/><link rel="stylesheet" href="/Web/css/OneOpenAI.css"/></head>
<body>
<header class="top"><div class="top-inner">
<button class="brand" data-act="garage" title="荒辙工坊 · 装配车间"><span class="brand-mark"><canvas data-icon="brand"></canvas></span><span><span class="brand-name">荒辙工坊</span><span class="brand-en">DUSTLINE MOTORWORKS</span></span></button>
<nav class="nav" aria-label="车库导航"><button class="active" data-act="garage" id="navGarage"><i data-icon="wrench"></i>装配车间</button><button data-act="library"><i data-icon="layers"></i>蓝图库</button><button data-act="records"><i data-icon="chart"></i>远征记录</button></nav>
<div class="top-actions"><span class="wallet" title="齿币 · 用于车间改良"><i data-icon="nut"></i><span id="bank">0</span></span><span class="top-sep"></span><button class="icon-btn quiet" data-act="sound" id="audioBtn" aria-label="切换音效" title="切换音效"><i data-icon="mute"></i></button><button class="icon-btn quiet" data-act="help" aria-label="操作手册" title="操作手册"><i data-icon="help"></i></button></div>
</div></header>
<main class="wrap">
<section id="garage">
<div class="page-head"><div class="heading"><h1>装配车间</h1><p>选取零件装到图纸上,打造你的荒原战车。</p></div><div class="head-actions"><span class="saved"><i class="led"></i><span id="saveLabel">蓝图已保存</span></span><button class="btn" data-act="test"><i data-icon="gauge"></i>试车场</button><button class="btn primary mobile-launch" data-act="launch"><i data-icon="flag"></i>出征</button></div></div>
<div class="layout"><div class="left">
<section class="panel"><div class="build-stage"><div class="drawing" id="drawing"><canvas id="bench" tabindex="0" aria-label="战车装配图,点选或拖动零件"></canvas>
<div class="board-title"><span class="rivet-label"></span><div><small>ACTIVE BLUEPRINT</small><b id="rigName"></b></div><button data-act="rename" aria-label="重命名蓝图" title="重命名"><i data-icon="edit"></i></button></div>
<div class="board-top-tools"><button class="paper-btn" data-act="manifest" aria-label="装配清单" title="装配清单 · 选择被遮住的零件"><i data-icon="list"></i></button><button class="paper-btn" data-act="undo" id="undoBtn" aria-label="撤销" title="撤销 Ctrl+Z"><i data-icon="undo"></i></button><button class="paper-btn" data-act="redo" id="redoBtn" aria-label="重做" title="重做 Ctrl+Y"><i data-icon="redo"></i></button></div>
<div class="board-tools"><div class="tool-group"><button class="tool active" data-act="select" id="selectTool" title="选择 V" aria-label="选择"><i data-icon="cursor"></i></button><button class="tool" data-act="pan" id="panTool" title="平移 H" aria-label="平移"><i data-icon="hand"></i></button><span class="group-rule"></span><button class="tool on" data-act="snap" id="snapTool" title="网格吸附 G" aria-label="网格吸附"><i data-icon="grid"></i></button><button class="tool" data-act="links" id="linkTool" title="查看连接与重心" aria-label="查看连接与重心"><i data-icon="link"></i></button></div>
<div class="tool-group"><button class="tool" data-act="zoomOut" aria-label="缩小" title="缩小"><i data-icon="minus"></i></button><span class="zoom-label" id="zoomRead">100%</span><button class="tool" data-act="zoomIn" aria-label="放大" title="放大"><i data-icon="plus"></i></button><span class="group-rule"></span><button class="tool" data-act="fit" aria-label="全车居中" title="全车居中"><i data-icon="fit"></i></button></div></div>
</div><aside class="layer-panel" id="layerPanel" aria-label="图层"><div class="layer-head"><div><small>STACK ORDER</small><h2>图层</h2></div><button class="layer-add" data-act="addLayer" aria-label="新增图层" title="新增图层">+</button></div><div class="layers-list" id="layersList"></div><div class="layer-foot"><strong>长按并拖动</strong>图层可调整顺序。当前蓝色图层是编辑目标。跨层连接只允许自由关节与万向铰链。</div></aside></div><div class="draw-status"><span class="inline"><i data-icon="link"></i><span id="connection"></span></span><span id="boardHint" class="status-right">拖动移动零件 · 滚轮缩放</span></div><div id="inspector" class="inspect" hidden></div></section>
<section class="rack panel"><div class="title-row"><h2><i data-icon="parts"></i>零件架 <span class="count" id="partCount"></span></h2><div class="rack-controls"><button class="icon-btn" data-act="rackPrev" aria-label="前一组零件"><i data-icon="left"></i></button><button class="icon-btn" data-act="rackNext" aria-label="后一组零件"><i data-icon="right"></i></button></div></div><div class="categories" id="categories" aria-label="零件分类"></div><div class="parts" id="parts"></div></section>
</div><aside class="right"><section class="contract panel"><h2 class="side-title"><span><i data-icon="compass"></i>远征合约</span><small>SECTOR 01</small></h2><div class="land-card"><canvas id="contractArt"></canvas><div class="land-caption"><small>SALT RIDGE</small><h2>盐脊荒原</h2></div></div><div class="contract-info"><div class="detail"><span>本段目标</span><strong>击破 2 辆敌车,抵达信标</strong></div><div class="detail"><span>过境报酬</span><strong class="gold">45 齿币</strong></div><button class="btn primary launch" data-act="launch"><span><i data-icon="flag"></i>开始远征</span><i data-icon="arrow"></i></button></div></section>
<section class="panel stats"><div class="title-row"><h2><i data-icon="sliders"></i>战车参数</h2><button class="mod-btn" data-act="upgrades" aria-label="车间改良" title="永久改良"><i data-icon="tune"></i>改良</button></div><div class="stat"><div class="stat-label"><span>整车质量</span><strong id="massText"></strong></div><div class="meter"><i id="massBar"></i></div></div><div class="stat"><div class="stat-label"><span>核心耐久</span><strong id="hpText"></strong></div><div class="meter"><i id="hpBar"></i></div></div><div class="stat"><div class="stat-label"><span>驱动功率</span><strong id="powerText"></strong></div><div class="meter"><i id="powerBar"></i></div></div><div class="stat-mini"><span id="weaponsText"></span><span id="wheelText"></span></div></section></aside></div>
<footer class="foot"><div class="keys"><span class="key-item"><kbd>R</kbd> 旋转</span><span class="key-item"><kbd>Q</kbd> 镜像</span><span class="key-item"><kbd>Del</kbd> 拆除</span><span class="key-item"><kbd>Esc</kbd> 取消放置</span></div><button class="help-foot" data-act="help">完整操作 <i data-icon="right"></i></button></footer>
</section>
<section id="battle" hidden><div class="battle-top"><div class="inline"><h1 id="battleTitle"></h1><span class="tag" id="seedView"></span></div><div class="inline"><button class="btn" data-act="pause"><i data-icon="pause"></i>暂停</button><button class="btn" data-act="leave"><i data-icon="exit"></i>回车间</button></div></div><div class="battle-frame"><canvas class="scene-canvas" id="field" tabindex="0" aria-label="荒原战场"></canvas><div class="hud"><div class="hud-left"><b id="coreHud"></b><div class="hud-meter"><i id="coreFill"></i></div><small id="energyHud"></small><div class="hud-meter energy"><i id="energyFill"></i></div><small id="heatHud"></small><div class="hud-meter heat"><i id="heatFill"></i></div></div><div class="hud-right"><b id="objective"></b><small id="progressHud"></small><small id="enemyHud"></small><small id="contractHud"></small></div><div class="hud-center" id="banner" hidden></div></div><div class="touchbar"><div class="touch-group"><button class="touch-button" data-hold="left" aria-label="向左驾驶"><i data-icon="left"></i></button><button class="touch-button" data-hold="right" aria-label="向右驾驶"><i data-icon="right"></i></button></div><div class="touch-group"><button class="touch-button" data-act="recover">扶正</button><button class="touch-button" data-hold="boost">推进</button><button class="touch-button" data-hold="fire">开火</button></div></div></div><div class="drive-strip"><div class="keys"><span><kbd>A</kbd> <kbd>D</kbd> 驾驶</span><span><kbd>空格</kbd> 锁敌开火</span><span><kbd>鼠标</kbd> 手动瞄准</span><span><kbd>E</kbd> 推进</span><span><kbd>R</kbd> 扶正</span></div><span id="speedRead" class="mono"></span></div></section>
</main><div class="modal-wrap" id="overlay" hidden><section role="dialog" aria-modal="true" aria-labelledby="modalTitle" class="dialog" id="dialog"><div class="dialog-title"><h2 id="modalTitle"></h2><button id="modalClose" class="icon-btn" data-act="close" aria-label="关闭"><i data-icon="x"></i></button></div><div id="modalBody"></div></section></div><div class="toast" role="status" id="toast" hidden></div><input type="file" id="importFile" accept=".json,application/json" hidden>

<script>
// 零件目录、蓝图格式与本地存档
"use strict";

const $ = id => document.getElementById(id),
  TAU = Math.PI * 2,
  RAD = Math.PI / 180;
const clamp = (v, a, b) => Math.max(a, Math.min(b, v)),
  lerp = (a, b, t) => a + (b - a) * t,
  sq = x => x * x,
  normA = a => Math.atan2(Math.sin(a), Math.cos(a)),
  copy = o => JSON.parse(JSON.stringify(o)),
  num = (x, f = 0) => Number.isFinite(x) ? x : f;
const esc = s => String(s).replace(/[&<>"']/g, c => ({
  "&": "&amp;",
  "<": "&lt;",
  ">": "&gt;",
  '"': "&quot;",
  "'": "&#39;"
})[c]);
function rnd(seed) {
  let a = seed >>> 0;
  return () => {
    a += 0x6D2B79F5;
    let t = Math.imul(a ^ a >>> 15, 1 | a);
    t = t + Math.imul(t ^ t >>> 7, 61 | t) ^ t;
    return ((t ^ t >>> 14) >>> 0) / 4294967296;
  };
}
function hash(i, s = 1) {
  let h = Math.imul(i | 0, 0x45d9f3b) ^ Math.imul(s | 0, 0x27d4eb2d);
  h = Math.imul(h ^ h >>> 16, 0x45d9f3b);
  return ((h ^ h >>> 16) >>> 0) / 4294967296;
}
function smooth(x, s) {
  const i = Math.floor(x),
    t = x - i;
  return lerp(hash(i, s), hash(i + 1, s), t * t * (3 - 2 * t));
}
function rotate(x, y, a) {
  const c = Math.cos(a),
    s = Math.sin(a);
  return {
    x: x * c - y * s,
    y: x * s + y * c
  };
}
function poly(c, pts, fill, edge = "#252c26", w = 1.5) {
  c.beginPath();
  c.moveTo(pts[0], pts[1]);
  for (let i = 2; i < pts.length; i += 2) c.lineTo(pts[i], pts[i + 1]);
  c.closePath();
  if (fill) {
    c.fillStyle = fill;
    c.fill();
  }
  if (edge) {
    c.strokeStyle = edge;
    c.lineWidth = w;
    c.stroke();
  }
}
function line(c, pts, col = "#36413a", w = 1) {
  c.beginPath();
  c.moveTo(pts[0], pts[1]);
  for (let i = 2; i < pts.length; i += 2) c.lineTo(pts[i], pts[i + 1]);
  c.strokeStyle = col;
  c.lineWidth = w;
  c.stroke();
}
function rect(c, x, y, w, h, fill, edge = null, lw = 1) {
  if (fill) {
    c.fillStyle = fill;
    c.fillRect(x, y, w, h);
  }
  if (edge) {
    c.strokeStyle = edge;
    c.lineWidth = lw;
    c.strokeRect(x, y, w, h);
  }
}
function circ(c, x, y, r, fill, edge = null, w = 1) {
  if (r <= 0) return;
  c.beginPath();
  c.arc(x, y, r, 0, TAU);
  if (fill) {
    c.fillStyle = fill;
    c.fill();
  }
  if (edge) {
    c.strokeStyle = edge;
    c.lineWidth = w;
    c.stroke();
  }
}
function txt(c, str, x, y, size, col, align = "left", font = "monospace", weight = "700") {
  c.fillStyle = col;
  c.font = weight + " " + size + "px " + font;
  c.textAlign = align;
  c.fillText(str, x, y);
}
const CJK = '"Noto Sans CJK SC","Microsoft YaHei",sans-serif';
function bolt(c, x, y, r = 1.8) {
  circ(c, x, y, r, "#c6bc91", "#28312c", .8);
  line(c, [x - r * .5, y + r * .4, x + r * .5, y - r * .4], "#53594b", .65);
}
function fitCanvas(cv) {
  const r = cv.getBoundingClientRect(),
    w = Math.max(1, r.width),
    h = Math.max(1, r.height),
    d = Math.min(2, window.devicePixelRatio || 1),
    ww = Math.round(w * d),
    hh = Math.round(h * d);
  if (cv.width !== ww || cv.height !== hh) {
    cv.width = ww;
    cv.height = hh;
  }
  const c = cv.getContext("2d");
  c.setTransform(ww / w, 0, 0, hh / h, 0, 0);
  c.lineJoin = "round";
  c.lineCap = "round";
  return {
    c,
    w,
    h
  };
}
const iconPaths = {
  list: "M4 5h2 M9 5h12 M4 12h2 M9 12h12 M4 19h2 M9 19h12",
  wrench: "M14 5a5 5 0 0 0-6 6L3 16a2 2 0 0 0 4 4l6-6a5 5 0 0 0 6-7l-3 3-3-1-1-2 3-3",
  layers: "M3 8l9-5 9 5-9 5z M3 12l9 5 9-5 M3 16l9 5 9-5",
  eye: "M2.5 12s3.4-6 9.5-6 9.5 6 9.5 6-3.4 6-9.5 6-9.5-6-9.5-6 M12 9a3 3 0 1 0 0 6 3 3 0 0 0 0-6",
  eyeOff: "M3 3l18 18 M10.6 6.3A10.8 10.8 0 0 1 12 6c6.1 0 9.5 6 9.5 6a18 18 0 0 1-3.3 3.9 M6.5 6.8C3.8 8.4 2.5 12 2.5 12s3.4 6 9.5 6c1.2 0 2.3-.2 3.3-.6",
  chart: "M4 20h17 M6 16v-4 M12 16V7 M18 16V3",
  nut: "M8 3h8l5 8-5 9H8l-5-9z M15.5 11.5a3.5 3.5 0 1 1-7 0 3.5 3.5 0 0 1 7 0",
  mute: "M3 9h4l5-5v16l-5-5H3z M16 9l5 6 M21 9l-5 6",
  sound: "M3 9h4l5-5v16l-5-5H3z M15 8q4 4 0 8 M18 5q7 7 0 14",
  help: "M21 12a9 9 0 1 1-18 0 9 9 0 0 1 18 0 M9 9q0-3 3-3t3 3q0 1.5-2 2.5L12 13v1 M12 17h.1",
  gauge: "M3 17a9 9 0 1 1 18 0z M12 14l5-6 M5.5 13h1 M8 8.5l1 1 M12 6v1",
  edit: "M4 19l1-5L16 3l4 4L9 18z M13 6l4 4",
  undo: "M8 5L3 10l5 5 M4 10h10q7 0 6 8",
  redo: "M16 5l5 5-5 5 M20 10H10q-7 0-6 8",
  cursor: "M4 3l15 9-7 2-3 7z",
  hand: "M5 14V9q0-3 3-1V5q1-3 3 0V3q2-2 3 1v1q2-3 3 1v4q3-3 3 1l-1 6q-1 5-6 5-3 0-5-3l-5-6q-1-3 2-1z",
  grid: "M4 4h16v16H4z M4 10h16 M10 4v16",
  link: "M9 14l6-6 M8 10l-3 3q-3 3 0 6t6 0l3-3 M11 8l3-3q3-3 6 0t0 6l-3 3",
  minus: "M5 12h14",
  plus: "M5 12h14 M12 5v14",
  fit: "M3 9V3h6 M15 3h6v6 M21 15v6h-6 M9 21H3v-6",
  left: "M15 5l-7 7 7 7",
  right: "M9 5l7 7-7 7",
  arrow: "M3 12h17 M14 5l7 7-7 7",
  parts: "M3 12l5-3 5 3v6l-5 3-5-3z M13 6l4-3 5 3v5l-5 3-4-3z M3 12l5 3 5-3 M8 15v6",
  compass: "M21 12a9 9 0 1 1-18 0 9 9 0 0 1 18 0 M15.5 7l-2 6-5 3 2-6z",
  sliders: "M3 6h4 M11 6h10 M3 12h10 M17 12h4 M3 18h3 M10 18h11 M7 4h4v4H7z M13 10h4v4h-4z M6 16h4v4H6z",
  tune: "M5 4v16 M12 4v16 M19 4v16 M2 9h6 M9 16h6 M16 7h6",
  flag: "M5 21V4l5-1 5 2 6-1-2 8-5 1-5-2-4 1",
  pause: "M7 4h3v16H7z M14 4h3v16h-3z",
  exit: "M10 4H4v16h6 M8 12h13 M16 7l5 5-5 5",
  x: "M5 5l14 14 M19 5L5 19",
  shield: "M12 2l8 3v6q-1 6-8 11-7-5-8-11V5z",
  zap: "M14 2L4 14h7l-1 8 10-14h-7z",
  target: "M20 12a8 8 0 1 1-16 0 8 8 0 0 1 16 0 M2 12h5 M17 12h5 M12 2v5 M12 17v5",
  repair: "M3 9h6V3h6v6h6v6h-6v6H9v-6H3z"
};
function iconMarkup(k) {
  return '<i data-icon="' + k + '"></i>';
}
function paintIcons(root = document) {
  root.querySelectorAll("[data-icon]").forEach(el => {
    const name = el.dataset.icon;
    let cv = el;
    if (el.tagName !== "CANVAS") {
      cv = document.createElement("canvas");
      cv.className = "ico";
      cv.dataset.icon = name;
      el.replaceWith(cv);
    }
    cv.setAttribute("aria-hidden", "true");
    cv.width = cv.height = 64;
    const c = cv.getContext("2d");
    c.scale(64 / 24, 64 / 24);
    c.lineWidth = 1.7;
    c.lineCap = c.lineJoin = "round";
    const col = getComputedStyle(cv).color;
    c.strokeStyle = col;
    c.fillStyle = col;
    if (name === "brand") {
      const ink = "#232b22";
      poly(c, [2, 17, 8, 5, 13, 5, 7, 17], ink, null);
      poly(c, [9, 17, 15, 5, 21, 5, 15, 17], ink, null);
      poly(c, [2, 19, 16, 19, 22, 9, 23, 12, 18, 21, 1, 21], ink, null);
    } else if (iconPaths[name]) c.stroke(new Path2D(iconPaths[name]));
  });
}
// Parts are authored in the same local units in the editor and the physics simulation.
const catalogue = [["wood", "木块", "结构", 36, 31, 9, 62, 4, "轻质方材,适合填充车体或垫高安装点。"], ["beam", "木条", "结构", 96, 12, 10, 56, 3, "可伸缩的轻型横梁,能把轮轴或工具伸向远处。"], ["wheel", "越野轮", "行走", 49, 49, 15, 76, 8, "轻量驱动轮,接地时提供牵引。"], ["micro", "轻型轮", "行走", 38, 38, 9, 61, 8, "小半径轻轮,转向灵活,适合侦察车和多轮底盘。"], ["hinge", "自由关节", "连接", 20, 20, 5, 65, 7, "子部件围绕销轴摆动,可搭建拖车和摆臂。"], ["gimbal", "万向铰链", "连接", 24, 24, 9, 78, 7, "双轴万向座,适合给喷口或炮塔提供可调安装角。"], ["motor", "活塞引擎", "动力", 45, 33, 29, 102, 5, "为接地车轮增加 58 kW 驱动力。"], ["reactor", "磁流反应堆", "动力", 42, 38, 34, 112, 5, "紧凑动力核心,为车轮提供额外驱动功率。"], ["pulse", "脉冲连发器", "武装", 47, 19, 17, 79, 8, "快速发射光脉冲,适合中近距离持续射击。"], ["cannon", "磁轨重炮", "武装", 52, 28, 28, 96, 8, "低射速重型炮,后坐力大,但单发冲击更强。"], ["truss", "钢桁架", "结构", 140, 16, 24, 126, 2, "可调长度的高强度主梁。"], ["plate", "斜面装甲", "结构", 51, 27, 23, 140, 6, "保护后方零件,同时为核心增加耐久。"], ["bumper", "缓冲护梁", "结构", 64, 20, 18, 118, 6, "厚重的碰撞护梁,适合保护核心和吸收正面冲击。"], ["spring", "弹性铰链", "连接", 32, 16, 8, 72, 7, "带回正弹簧的铰链,适合安装随地起伏的轮组。"], ["mud", "重型胎", "行走", 61, 61, 23, 108, 8, "大半径与深胎纹适合陡坡和重车。"], ["arc", "弧光抛射器", "武装", 42, 24, 23, 81, 8, "抛出弧光球,越过矮坡并造成范围伤害。"], ["ram", "撞角", "武装", 45, 22, 16, 123, 6, "可伸缩的撞击部件,提高近身碰撞伤害。"], ["saw", "动力锯盘", "武装", 40, 40, 20, 98, 8, "持续切削与锯齿接触的敌方部件。"], ["boost", "矢量喷口", "动力", 40, 23, 15, 80, 5, "燃气向喷口后方喷出,产生与喷流相反方向的矢量推力。"], ["cell", "储能电池", "装置", 29, 29, 11, 67, 5, "扩大推进电量与电盾的储备。"], ["tank", "推进剂舱", "装置", 34, 37, 23, 82, 5, "增加可用推进剂容量,让火箭喷口持续更久。"], ["ward", "护盾线圈", "装置", 36, 23, 19, 83, 6, "受到冲击时消耗电量,吸收部分伤害。"], ["cooler", "散热格栅", "装置", 34, 23, 10, 65, 5, "加快武器散热,缩短过热停火时间。"], ["vent", "高流量排热器", "装置", 39, 26, 14, 72, 5, "排出武器和反应堆热量,提升整车冷却效率。"], ["sensor", "追踪天线", "装置", 26, 39, 8, 55, 5, "扩大锁敌稳定度,让远程武器更容易保持射界。"], ["skid", "滑橇", "行走", 53, 12, 7, 76, 4, "可伸缩的低阻护底,触地时仍能滑行。"], ["core", "驾驶核心", "结构", 69, 49, 46, 180, 6, "全车的连接根部。核心耗尽后远征结束。"]];
const D = Object.fromEntries(catalogue.map(([id, name, cat, w, h, m, hp, z, desc]) => [id, {
  id,
  name,
  cat,
  w,
  h,
  m,
  hp,
  z,
  desc
}]));
const wheelType = t => t === "wheel" || t === "mud" || t === "micro",
  jointType = t => t === "hinge" || t === "spring" || t === "gimbal",
  // Springs remain same-layer joints. Only these two parts may bridge layers.
  crossLayerJoint = t => t === "hinge" || t === "gimbal",
  ranged = t => t === "pulse" || t === "arc" || t === "cannon",
  variable = t => ["beam", "truss", "ram", "skid"].includes(t);
const wp = p => D[p.type].w * (p.len || 1),
  massOf = p => D[p.type].m * (p.len || 1);
const DEFAULT_LAYER_SPECS = [
  ["layer-1", "图层1"],
  ["layer-2", "图层2"],
  ["layer-3", "图层3"]
];
function defaultLayers() {
  return DEFAULT_LAYER_SPECS.map(([id, name]) => ({
    id,
    name,
    visible: true
  }));
}
function part(id, type, x, y, parent, rot = 0, len = 1, flip = 1) {
  return {
    id,
    type,
    x,
    y,
    parent,
    rot,
    len,
    flip,
    layer: null
  };
}
// A layer boundary is transparent only at a free joint or a gimbal. Every
// other part pair must stay on the same layer to be linked or treated as a
// physical contact in the editor.
function layerLinkAllowed(a, b) {
  return !!a && !!b && (a.layer === b.layer || crossLayerJoint(a.type) || crossLayerJoint(b.type));
}
function layerCollisionAllowed(a, b) {
  return layerLinkAllowed(a, b);
}
function baseRig() {
  const layers = defaultLayers();
  return {
    name: "游隼 MK.I",
    layers,
    activeLayer: layers.at(-1).id,
    parts: [part(1, "core", -9, -10, null), part(2, "truss", 0, 17, 1, 0, 1.28), part(3, "motor", -62, -1, 2), part(4, "beam", -42, 18, 2, -.055, 1.03), part(5, "plate", 52, 1, 2), part(6, "ram", 91, 11, 5), part(7, "mud", -76, 32, 2), part(8, "wheel", 77, 38, 2), part(9, "pulse", 2, -40, 1), part(10, "boost", -80, 3, 3)].map(p => ({ ...p, layer: layers.at(-1).id }))
  };
}
function haulerRig() {
  return {
    name: "驮鹿 / 铰接牵引车",
    parts: [part(1, "core", 18, -11, null), part(2, "truss", 15, 15, 1, 0, .85), part(3, "motor", 65, 0, 2), part(4, "wheel", 63, 34, 2), part(5, "mud", -21, 28, 2), part(6, "hinge", -43, 15, 2), part(7, "beam", -83, 15, 6, 0, .85), part(8, "wood", -91, -4, 7), part(9, "wheel", -107, 35, 7), part(10, "arc", 18, -42, 1), part(11, "plate", 83, 11, 3)]
  };
}
function sawRig() {
  return {
    name: "砂鲨 / 近战突击车",
    parts: [part(1, "core", -8, -10, null), part(2, "truss", 0, 15, 1), part(3, "motor", -54, -4, 2), part(4, "mud", -60, 30, 2), part(5, "mud", 47, 30, 2), part(6, "spring", 65, 8, 2), part(7, "beam", 86, 6, 6, -.12, .55), part(8, "saw", 110, 1, 7), part(9, "ward", -8, -42, 1), part(10, "boost", -75, 4, 3)]
  };
}
function rotorRig() {
  const layers = defaultLayers();
  layers[0].name = "支撑层";
  layers[1].name = "旋臂层";
  layers[2].name = "喷口层";
  const p = (id, type, x, y, parent, rot, len, flip, layer) => ({
    ...part(id, type, x, y, parent, rot, len, flip),
    layer
  });
  return {
    name: "矢量旋臂 / 防碰撞测试",
    layers,
    activeLayer: layers[1].id,
    parts: [
      p(1, "core", 0, 0, null, 0, 1, 1, layers[0].id),
      p(2, "truss", 0, 27, 1, 0, .56, 1, layers[0].id),
      p(3, "motor", -32, 2, 1, 0, 1, 1, layers[0].id),
      p(4, "wheel", -35, 49, 2, 0, 1, 1, layers[0].id),
      p(5, "wheel", 35, 49, 2, 0, 1, 1, layers[0].id),
      p(6, "hinge", 52, 6, 2, 0, 1, 1, layers[0].id),
      p(7, "beam", 97, 6, 6, 0, .9, 1, layers[1].id),
      p(8, "boost", 119, 6, 7, Math.PI / 2, 1, 1, layers[1].id),
      p(9, "cell", 91, -17, 7, 0, 1, 1, layers[1].id),
      p(10, "cooler", 82, 24, 7, 0, 1, 1, layers[1].id)
    ]
  };
}
function rotorClearanceReport(rig) {
  const support = rig.parts.find(p => p.id === 2),
    arm = rig.parts.find(p => p.id === 7),
    pivot = rig.parts.find(p => p.id === 6),
    jet = rig.parts.find(p => p.id === 8);
  if (!support || !arm || !pivot || !jet) return {
    ok: false,
    minClearance: -Infinity,
    torque: 0
  };
  let minClearance = Infinity;
  for (let i = 0; i <= 48; i++) {
    const angle = lerp(-1.45, 1.45, i / 48),
      offset = rotate(arm.x - pivot.x, arm.y - pivot.y, angle),
      sample = {
        ...arm,
        x: pivot.x + offset.x,
        y: pivot.y + offset.y,
        rot: angle
      };
    minClearance = Math.min(minClearance, separation(support, sample));
  }
  const torque = (jet.x - pivot.x) * Math.sin(jet.rot) - (jet.y - pivot.y) * Math.cos(jet.rot);
  return {
    ok: minClearance > 0 && Math.abs(torque) > 8,
    minClearance,
    torque
  };
}
const catalogOrder = catalogue.map(p => p[0]).filter(t => t !== "core");
function bounds(ps) {
  let a = Infinity,
    b = Infinity,
    e = -Infinity,
    f = -Infinity;
  for (const p of ps) {
    const co = Math.abs(Math.cos(p.rot)),
      si = Math.abs(Math.sin(p.rot)),
      w = wp(p) / 2,
      h = D[p.type].h / 2,
      dx = wheelType(p.type) || p.type === "saw" ? w : co * w + si * h,
      dy = wheelType(p.type) || p.type === "saw" ? h : si * w + co * h;
    a = Math.min(a, p.x - dx);
    e = Math.max(e, p.x + dx);
    b = Math.min(b, p.y - dy);
    f = Math.max(f, p.y + dy);
  }
  return {
    l: a,
    t: b,
    r: e,
    b: f,
    w: e - a,
    h: f - b
  };
}
function rigStats(parts, up = {}) {
  const count = t => parts.filter(p => p.type === t).length;
  return {
    mass: Math.round(parts.reduce((a, p) => a + massOf(p), 0)),
    hp: Math.round((180 + count("plate") * 22 + count("bumper") * 12) * (1 + (up.armor || 0) * .10)),
    power: Math.round((16 + count("motor") * 58 + count("reactor") * 42) * (1 + (up.drive || 0) * .1)),
    wheels: parts.filter(p => wheelType(p.type)).length,
    weapons: parts.filter(p => D[p.type].cat === "武装").length
  };
}
const BUILD_LIMIT = 65536;
function validateRig(raw) {
  if (!raw || typeof raw.name !== "string" || !Array.isArray(raw.parts) || !raw.parts.length || raw.parts.length > 72) throw Error("蓝图需要 1 至 72 个部件。");
  const ids = new Set(),
    rawLayers = Array.isArray(raw.layers) ? raw.layers : [],
    layers = [],
    layerIds = new Set();
  for (const item of rawLayers) {
    if (!item || typeof item.id !== "string" || layerIds.has(item.id)) continue;
    const id = item.id.slice(0, 32),
      name = String(item.name || "图层").trim().slice(0, 24) || "图层";
    layers.push({ id, name, visible: item.visible !== false });
    layerIds.add(id);
  }
  if (!layers.length) for (const [id, name] of DEFAULT_LAYER_SPECS) {
    layers.push({ id, name, visible: true });
    layerIds.add(id);
  }
  const topLayer = layers.at(-1).id,
    activeLayer = layerIds.has(raw.activeLayer) ? raw.activeLayer : topLayer,
    ps = raw.parts.map(q => {
      if (!q || !Object.hasOwn(D, q.type) || !Number.isSafeInteger(q.id) || q.id <= 0 || ids.has(q.id) || ![q.x, q.y, q.rot].every(Number.isFinite) || Math.abs(q.x) > BUILD_LIMIT || Math.abs(q.y) > BUILD_LIMIT) throw Error("零件坐标或编号无效。");
      ids.add(q.id);
      const p = part(q.id, q.type, q.x, q.y, Number.isSafeInteger(q.parent) ? q.parent : null, normA(q.rot), variable(q.type) ? clamp(num(q.len, 1), .45, 2.2) : 1, q.flip === -1 ? -1 : 1);
      p.layer = layerIds.has(q.layer) ? q.layer : topLayer;
      return p;
    });
  if (ps.filter(p => p.type === "core").length !== 1) throw Error("需要且只允许一个驾驶核心。");
  const map = new Map(ps.map(p => [p.id, p]));
  for (const p of ps) {
    if (p.type === "core") p.parent = null;
    if (!map.has(p.parent)) p.parent = null;
    const parent = map.get(p.parent);
    if (parent && !layerLinkAllowed(p, parent)) p.parent = null;
    const seen = new Set();
    let n = p;
    while (n) {
      if (seen.has(n.id)) throw Error("蓝图中存在循环连接。");
      seen.add(n.id);
      n = map.get(n.parent);
    }
  }
  return {
    name: raw.name.trim().slice(0, 32) || "自制战车",
    layers,
    activeLayer,
    parts: ps
  };
}
const SAVE = "dustline.motorworks.zh.v1";
let storeOK = true;
function loadState() {
  const s = {
    rig: baseRig(),
    slots: [],
    bank: 0,
    best: 0,
    records: [],
    up: {
      armor: 0,
      drive: 0,
      cooling: 0
    },
    sound: false
  };
  try {
    const a = JSON.parse(localStorage.getItem(SAVE) || "null");
    if (!a) return s;
    try {
      s.rig = validateRig(a.rig);
    } catch {}
    s.slots = (Array.isArray(a.slots) ? a.slots : []).slice(0, 12).flatMap(v => {
      try {
        return [validateRig(v)];
      } catch {
        return [];
      }
    });
    s.records = (Array.isArray(a.records) ? a.records : []).filter(r => r && Number.isFinite(r.sector) && Number.isFinite(r.seed)).slice(0, 20);
    s.bank = Math.max(0, Math.floor(num(a.bank)));
    s.best = Math.max(0, Math.floor(num(a.best)));
    for (const k in s.up) s.up[k] = clamp(Math.floor(num(a.up?.[k])), 0, 6);
    s.sound = !!a.sound;
  } catch {
    storeOK = false;
  }
  return s;
}
let S = loadState(),
  scene = "garage",
  run = null,
  modalKind = "",
  modalLast = null,
  toastTimer = 0;
function persist() {
  try {
    localStorage.setItem(SAVE, JSON.stringify(S));
    storeOK = true;
  } catch {
    storeOK = false;
  }
  $("saveLabel").textContent = storeOK ? "蓝图已保存" : "本次会话";
  $("bank").textContent = String(S.bank);
}
function toast(msg) {
  $("toast").textContent = msg;
  $("toast").hidden = false;
  clearTimeout(toastTimer);
  toastTimer = setTimeout(() => $("toast").hidden = true, 2400);
}
let audioCtx = null;
const AUDIO = {
  master: null,
  sfx: null,
  ambience: null,
  engineBus: null,
  noiseBuffer: null,
  battleActive: false,
  engineNodes: [],
  engineLevel: null,
  windLevel: null,
  boostLevel: null,
  engineOsc: null,
  engineSub: null,
  boostOsc: null,
  boostActive: false,
  last: Object.create(null)
};
function audioEnsure() {
  if (!S.sound) return false;
  try {
    const Ctx = window.AudioContext || window.webkitAudioContext;
    if (!Ctx) return false;
    audioCtx ??= new Ctx();
    if (!AUDIO.master) {
      const compressor = audioCtx.createDynamicsCompressor();
      compressor.threshold.value = -22;
      compressor.knee.value = 18;
      compressor.ratio.value = 4;
      compressor.attack.value = .004;
      compressor.release.value = .24;
      AUDIO.master = audioCtx.createGain();
      AUDIO.master.gain.value = .72;
      AUDIO.master.connect(compressor).connect(audioCtx.destination);
      AUDIO.sfx = audioCtx.createGain();
      AUDIO.sfx.gain.value = .88;
      AUDIO.sfx.connect(AUDIO.master);
      AUDIO.ambience = audioCtx.createGain();
      AUDIO.ambience.gain.value = .25;
      AUDIO.ambience.connect(AUDIO.master);
      AUDIO.engineBus = audioCtx.createGain();
      AUDIO.engineBus.gain.value = .34;
      AUDIO.engineBus.connect(AUDIO.master);
    }
    if (audioCtx.state === "suspended") audioCtx.resume().catch(() => {});
    return true;
  } catch {
    return false;
  }
}
function audioBus(name = "sfx") {
  return AUDIO[name] || AUDIO.sfx;
}
function audioOsc({
  freq = 440,
  end = freq * .62,
  duration = .08,
  shape = "triangle",
  volume = .03,
  delay = 0,
  attack = .004,
  bus = "sfx"
} = {}) {
  if (!audioEnsure()) return;
  try {
    const t = audioCtx.currentTime + delay,
      o = audioCtx.createOscillator(),
      g = audioCtx.createGain();
    o.type = shape;
    o.frequency.setValueAtTime(Math.max(12, freq), t);
    o.frequency.exponentialRampToValueAtTime(Math.max(12, end), t + duration);
    g.gain.setValueAtTime(.0001, t);
    g.gain.linearRampToValueAtTime(volume, t + Math.min(attack, duration * .3));
    g.gain.exponentialRampToValueAtTime(.0001, t + duration);
    o.connect(g).connect(audioBus(bus));
    o.start(t);
    o.stop(t + duration + .025);
  } catch {}
}
function noiseBuffer() {
  if (AUDIO.noiseBuffer || !audioEnsure()) return AUDIO.noiseBuffer;
  const length = Math.max(1, Math.floor(audioCtx.sampleRate * 2));
  AUDIO.noiseBuffer = audioCtx.createBuffer(1, length, audioCtx.sampleRate);
  const data = AUDIO.noiseBuffer.getChannelData(0);
  for (let i = 0; i < length; i++) data[i] = Math.random() * 2 - 1;
  return AUDIO.noiseBuffer;
}
function audioNoise({
  duration = .12,
  volume = .025,
  frequency = 900,
  filter = "bandpass",
  q = .8,
  delay = 0,
  bus = "sfx"
} = {}) {
  if (!audioEnsure()) return;
  try {
    const t = audioCtx.currentTime + delay,
      src = audioCtx.createBufferSource(),
      filterNode = audioCtx.createBiquadFilter(),
      g = audioCtx.createGain();
    src.buffer = noiseBuffer();
    filterNode.type = filter;
    filterNode.frequency.setValueAtTime(Math.max(30, frequency), t);
    filterNode.Q.value = q;
    g.gain.setValueAtTime(.0001, t);
    g.gain.linearRampToValueAtTime(volume, t + Math.min(.006, duration * .18));
    g.gain.exponentialRampToValueAtTime(.0001, t + duration);
    src.connect(filterNode).connect(g).connect(audioBus(bus));
    src.start(t);
    src.stop(t + duration + .025);
  } catch {}
}
function audioThrottle(key, gap = .08) {
  const now = performance.now() / 1000;
  if ((AUDIO.last[key] || -Infinity) + gap > now) return false;
  AUDIO.last[key] = now;
  return true;
}
function tone(freq, duration = .08, shape = "triangle", volume = .035, end = freq * .52) {
  audioOsc({
    freq,
    duration,
    shape,
    volume,
    end
  });
}
function sfxUi(kind = "tap") {
  if (!S.sound) return;
  if (kind === "nav") {
    audioOsc({ freq: 270, end: 430, duration: .055, shape: "square", volume: .014 });
    audioOsc({ freq: 540, end: 760, duration: .045, shape: "triangle", volume: .009, delay: .035 });
    return;
  }
  if (kind === "tool") {
    audioOsc({ freq: 730, end: 430, duration: .045, shape: "square", volume: .012 });
    return;
  }
  if (kind === "part") {
    audioOsc({ freq: 210, end: 120, duration: .06, shape: "triangle", volume: .015 });
    audioNoise({ duration: .035, frequency: 1800, volume: .012 });
    return;
  }
  if (kind === "positive") {
    audioOsc({ freq: 420, end: 610, duration: .08, shape: "triangle", volume: .018 });
    audioOsc({ freq: 610, end: 830, duration: .1, shape: "sine", volume: .014, delay: .07 });
    return;
  }
  if (kind === "negative") {
    audioOsc({ freq: 180, end: 88, duration: .14, shape: "sawtooth", volume: .019 });
    return;
  }
  if (kind === "modal") {
    audioOsc({ freq: 230, end: 360, duration: .08, shape: "triangle", volume: .012 });
    audioOsc({ freq: 460, end: 620, duration: .1, shape: "sine", volume: .009, delay: .05 });
    return;
  }
  if (kind === "close") {
    audioOsc({ freq: 430, end: 220, duration: .07, shape: "triangle", volume: .01 });
    return;
  }
  audioOsc({ freq: 520, end: 290, duration: .045, shape: "triangle", volume: .011 });
}
function sfxInstall() {
  if (!S.sound) return;
  audioOsc({ freq: 118, end: 54, duration: .13, shape: "square", volume: .026 });
  audioOsc({ freq: 680, end: 240, duration: .08, shape: "triangle", volume: .018, delay: .025 });
  audioNoise({ duration: .08, frequency: 1450, volume: .018, delay: .018 });
}
function sfxRemove() {
  if (!S.sound) return;
  audioOsc({ freq: 92, end: 38, duration: .15, shape: "sawtooth", volume: .024 });
  audioNoise({ duration: .1, frequency: 620, volume: .022 });
}
function sfxRotate() {
  if (!S.sound || !audioThrottle("rotate", .045)) return;
  audioOsc({ freq: 760, end: 350, duration: .045, shape: "square", volume: .014 });
  audioNoise({ duration: .03, frequency: 2100, volume: .009, delay: .012 });
}
function sfxUndo(back = true) {
  if (!S.sound) return;
  const base = back ? 360 : 510;
  audioOsc({ freq: base, end: base * .72, duration: .08, shape: "triangle", volume: .018 });
  audioOsc({ freq: base * 1.35, end: base * 1.05, duration: .1, shape: "triangle", volume: .014, delay: .06 });
}
function sfxLaunch() {
  if (!S.sound) return;
  audioOsc({ freq: 48, end: 92, duration: .42, shape: "sawtooth", volume: .034 });
  audioOsc({ freq: 97, end: 196, duration: .28, shape: "triangle", volume: .022, delay: .12 });
  audioNoise({ duration: .28, frequency: 140, filter: "lowpass", volume: .025, delay: .08 });
}
function sfxRecover() {
  if (!S.sound) return;
  audioOsc({ freq: 95, end: 210, duration: .3, shape: "sawtooth", volume: .025 });
  audioOsc({ freq: 250, end: 520, duration: .22, shape: "triangle", volume: .017, delay: .12 });
  audioNoise({ duration: .22, frequency: 360, volume: .018, delay: .03 });
}
function sfxShot(arc, gain = 1) {
  if (!S.sound) return;
  if (arc) {
    audioOsc({ freq: 112, end: 42, duration: .18, shape: "sawtooth", volume: .035 * gain });
    audioOsc({ freq: 246, end: 96, duration: .2, shape: "triangle", volume: .02 * gain, delay: .018 });
    audioNoise({ duration: .13, frequency: 580, filter: "lowpass", volume: .026 * gain, delay: .01 });
  } else {
    audioOsc({ freq: 470, end: 160, duration: .075, shape: "square", volume: .024 * gain });
    audioOsc({ freq: 930, end: 420, duration: .065, shape: "triangle", volume: .014 * gain, delay: .012 });
    audioNoise({ duration: .045, frequency: 1900, volume: .012 * gain });
  }
}
function sfxImpact(arc, playerHit = false) {
  if (!S.sound || !audioThrottle(arc ? "arcImpact" : "pulseImpact", arc ? .12 : .045)) return;
  const gain = playerHit ? 1.1 : .72;
  if (arc) {
    audioOsc({ freq: 74, end: 28, duration: .28, shape: "sine", volume: .044 * gain });
    audioNoise({ duration: .24, frequency: 420, filter: "lowpass", volume: .042 * gain });
  } else {
    audioOsc({ freq: 155, end: 70, duration: .09, shape: "triangle", volume: .024 * gain });
    audioNoise({ duration: .07, frequency: 1100, volume: .022 * gain });
  }
}
function sfxExplosion(scale = 1) {
  if (!S.sound) return;
  const gain = clamp(scale, .55, 1.35);
  audioOsc({ freq: 65, end: 22, duration: .48, shape: "sawtooth", volume: .052 * gain });
  audioOsc({ freq: 132, end: 33, duration: .34, shape: "triangle", volume: .026 * gain, delay: .02 });
  audioNoise({ duration: .36, frequency: 180, filter: "lowpass", volume: .055 * gain, delay: .01 });
  audioNoise({ duration: .2, frequency: 1500, volume: .022 * gain, delay: .03 });
}
function sfxPickup() {
  if (!S.sound) return;
  audioOsc({ freq: 520, end: 690, duration: .12, shape: "sine", volume: .022 });
  audioOsc({ freq: 690, end: 930, duration: .14, shape: "sine", volume: .018, delay: .08 });
  audioOsc({ freq: 1040, end: 1240, duration: .16, shape: "triangle", volume: .011, delay: .16 });
}
function sfxAlert() {
  if (!S.sound || !audioThrottle("alert", .5)) return;
  audioOsc({ freq: 640, end: 470, duration: .16, shape: "square", volume: .018 });
  audioOsc({ freq: 640, end: 470, duration: .16, shape: "square", volume: .018, delay: .19 });
  audioNoise({ duration: .06, frequency: 1750, volume: .008, delay: .08 });
}
function sfxGate() {
  if (!S.sound) return;
  audioOsc({ freq: 196, end: 196, duration: .3, shape: "sine", volume: .025 });
  audioOsc({ freq: 247, end: 247, duration: .32, shape: "sine", volume: .022, delay: .03 });
  audioOsc({ freq: 294, end: 294, duration: .38, shape: "sine", volume: .019, delay: .06 });
  audioOsc({ freq: 588, end: 770, duration: .22, shape: "triangle", volume: .014, delay: .17 });
}
function sfxReward() {
  if (!S.sound) return;
  audioOsc({ freq: 820, end: 1120, duration: .08, shape: "sine", volume: .015 });
  audioOsc({ freq: 1120, end: 1480, duration: .1, shape: "sine", volume: .013, delay: .07 });
}
function sfxOverheat() {
  if (!S.sound) return;
  audioOsc({ freq: 190, end: 280, duration: .16, shape: "square", volume: .018 });
  audioOsc({ freq: 190, end: 280, duration: .16, shape: "square", volume: .018, delay: .2 });
  audioNoise({ duration: .14, frequency: 680, volume: .015, delay: .05 });
}
function sfxLanding(severity, enemy = false) {
  if (!S.sound || enemy || severity < 170 || !audioThrottle("landing", .22)) return;
  const gain = clamp(severity / 420, .35, 1.05);
  audioOsc({ freq: 92, end: 42, duration: .16, shape: "triangle", volume: .024 * gain });
  audioNoise({ duration: .1, frequency: 240, filter: "lowpass", volume: .024 * gain });
}
function sfxDamage() {
  if (!S.sound || !audioThrottle("damage", .09)) return;
  audioOsc({ freq: 110, end: 52, duration: .11, shape: "sawtooth", volume: .025 });
  audioNoise({ duration: .07, frequency: 640, volume: .022 });
}
function sfxFailure() {
  if (!S.sound) return;
  audioOsc({ freq: 210, end: 92, duration: .28, shape: "sawtooth", volume: .028 });
  audioOsc({ freq: 150, end: 48, duration: .42, shape: "triangle", volume: .022, delay: .12 });
  audioNoise({ duration: .28, frequency: 190, filter: "lowpass", volume: .03, delay: .04 });
}
function sfxBoostStart() {
  if (!S.sound) return;
  audioOsc({ freq: 150, end: 330, duration: .16, shape: "sawtooth", volume: .022 });
  audioNoise({ duration: .18, frequency: 1150, volume: .024 });
}
function sfxBoostStop() {
  if (!S.sound) return;
  audioOsc({ freq: 280, end: 95, duration: .14, shape: "triangle", volume: .014 });
}
function audioStartBattle() {
  if (!audioEnsure()) return;
  audioStopBattle();
  try {
    const now = audioCtx.currentTime,
      engineLevel = audioCtx.createGain(),
      windLevel = audioCtx.createGain(),
      boostLevel = audioCtx.createGain(),
      engineOsc = audioCtx.createOscillator(),
      engineSub = audioCtx.createOscillator(),
      boostOsc = audioCtx.createOscillator(),
      engineNoise = audioCtx.createBufferSource(),
      windNoise = audioCtx.createBufferSource(),
      engineFilter = audioCtx.createBiquadFilter(),
      windFilter = audioCtx.createBiquadFilter(),
      boostFilter = audioCtx.createBiquadFilter();
    engineLevel.gain.value = .0001;
    windLevel.gain.value = .0001;
    boostLevel.gain.value = .0001;
    engineOsc.type = "sawtooth";
    engineOsc.frequency.value = 54;
    engineSub.type = "sine";
    engineSub.frequency.value = 27;
    boostOsc.type = "square";
    boostOsc.frequency.value = 165;
    engineFilter.type = "lowpass";
    engineFilter.frequency.value = 820;
    engineFilter.Q.value = .6;
    windFilter.type = "bandpass";
    windFilter.frequency.value = 900;
    windFilter.Q.value = .55;
    boostFilter.type = "bandpass";
    boostFilter.frequency.value = 1150;
    boostFilter.Q.value = .9;
    engineNoise.buffer = noiseBuffer();
    windNoise.buffer = noiseBuffer();
    engineNoise.loop = true;
    windNoise.loop = true;
    engineOsc.connect(engineFilter).connect(engineLevel).connect(AUDIO.engineBus);
    engineSub.connect(engineLevel);
    engineNoise.connect(engineFilter);
    windNoise.connect(windFilter).connect(windLevel).connect(AUDIO.ambience);
    boostOsc.connect(boostFilter).connect(boostLevel).connect(AUDIO.engineBus);
    engineLevel.gain.setTargetAtTime(.0001, now, .01);
    windLevel.gain.setTargetAtTime(.0001, now, .01);
    boostLevel.gain.setTargetAtTime(.0001, now, .01);
    for (const node of [engineOsc, engineSub, boostOsc, engineNoise, windNoise]) node.start(now);
    AUDIO.engineNodes = [engineOsc, engineSub, boostOsc, engineNoise, windNoise];
    AUDIO.engineLevel = engineLevel;
    AUDIO.windLevel = windLevel;
    AUDIO.boostLevel = boostLevel;
    AUDIO.engineOsc = engineOsc;
    AUDIO.engineSub = engineSub;
    AUDIO.boostOsc = boostOsc;
    AUDIO.boostActive = false;
    AUDIO.battleActive = true;
  } catch {}
}
function audioStopBattle() {
  if (!AUDIO.battleActive) return;
  const now = audioCtx?.currentTime || 0;
  for (const node of AUDIO.engineNodes) {
    try {
      node.stop(now + .12);
    } catch {}
  }
  if (AUDIO.engineLevel) AUDIO.engineLevel.gain.setTargetAtTime(.0001, now, .035);
  if (AUDIO.windLevel) AUDIO.windLevel.gain.setTargetAtTime(.0001, now, .035);
  if (AUDIO.boostLevel) AUDIO.boostLevel.gain.setTargetAtTime(.0001, now, .035);
  AUDIO.engineNodes = [];
  AUDIO.engineLevel = null;
  AUDIO.windLevel = null;
  AUDIO.boostLevel = null;
  AUDIO.engineOsc = null;
  AUDIO.engineSub = null;
  AUDIO.boostOsc = null;
  AUDIO.boostActive = false;
  AUDIO.battleActive = false;
}
function audioUpdateBattle() {
  if (scene !== "battle" || !run || !run.player || run.player.dead || !S.sound) {
    audioStopBattle();
    return;
  }
  if (!AUDIO.battleActive) audioStartBattle();
  if (!AUDIO.battleActive || !audioEnsure()) return;
  const p = run.player,
    now = audioCtx.currentTime,
    speed = Math.abs(p.root.vx),
    rpm = clamp(speed / 220 + Math.abs(p.throttle) * .4 + (p.grounded ? .12 : 0), .08, 1.45),
    quiet = modalKind || run.pending || p.dead,
    engineGain = quiet ? .002 : .008 + rpm * .022,
    windGain = quiet ? .001 : .0015 + clamp(speed / 300, 0, 1) * .012,
    boosting = !!(p.boost && p.energy > 2 && p.jetN > 0 && !quiet);
  AUDIO.engineLevel?.gain.setTargetAtTime(engineGain, now, .08);
  AUDIO.windLevel?.gain.setTargetAtTime(windGain, now, .1);
  AUDIO.boostLevel?.gain.setTargetAtTime(boosting ? .026 : .0001, now, .045);
  AUDIO.engineOsc?.frequency.setTargetAtTime(48 + rpm * 78, now, .08);
  AUDIO.engineSub?.frequency.setTargetAtTime(24 + rpm * 38, now, .08);
  AUDIO.boostOsc?.frequency.setTargetAtTime(145 + rpm * 54, now, .06);
  if (boosting !== AUDIO.boostActive) {
    AUDIO.boostActive = boosting;
    if (boosting) sfxBoostStart();else sfxBoostStop();
  }
}

// 程序绘制的车辆、机械部件与荒原背景
const INK = "#26312d",
  DARK = "#343e38",
  STEEL = "#879385",
  LIGHT = "#c0c6aa",
  ORANGE = "#d48340",
  HONEY = "#e9ab57",
  RUST = "#96563a";
const BIOMES = [{
  name: "盐脊荒原",
  en: "SALT RIDGE",
  sky1: "#e8a165",
  sky2: "#f4d495",
  sun: "#ffde94",
  far: "#d79c77",
  mid: "#bb795a",
  near: "#8f5945",
  rock: "#674638",
  top: "#d99d59",
  soil: "#945e40",
  deep: "#674637",
  grass: "#9b7246"
}, {
  name: "靛风峡谷",
  en: "INDIGO PASS",
  sky1: "#787c98",
  sky2: "#e4b5a3",
  sun: "#f7cfb3",
  far: "#a594a1",
  mid: "#887b90",
  near: "#655e74",
  rock: "#484c5c",
  top: "#b6a2aa",
  soil: "#796e80",
  deep: "#545465",
  grass: "#929398"
}, {
  name: "铜锈矿带",
  en: "VERDIGRIS MINE",
  sky1: "#83aba4",
  sky2: "#e2cf9c",
  sun: "#ffe1a6",
  far: "#a2ae97",
  mid: "#829783",
  near: "#5b786d",
  rock: "#415b50",
  top: "#c2ad71",
  soil: "#867855",
  deep: "#60614c",
  grass: "#8f9465"
}, {
  name: "余烬盆地",
  en: "EMBER BASIN",
  sky1: "#b96e62",
  sky2: "#efba83",
  sun: "#ffdb99",
  far: "#cf8d79",
  mid: "#ae6c61",
  near: "#854e47",
  rock: "#633d37",
  top: "#cb895e",
  soil: "#965f48",
  deep: "#71463d",
  grass: "#a97b50"
}];
let grainTile;
function grain(c, x, y, w, h, alpha = .06) {
  if (!grainTile) {
    grainTile = document.createElement("canvas");
    grainTile.width = grainTile.height = 96;
    const g = grainTile.getContext("2d"),
      im = g.createImageData(96, 96),
      r = rnd(9812);
    for (let j = 0; j < im.data.length; j += 4) {
      const v = r() > .47 ? 255 : 0;
      im.data[j] = im.data[j + 1] = im.data[j + 2] = v;
      im.data[j + 3] = Math.round(35 + r() * 140);
    }
    g.putImageData(im, 0, 0);
  }
  c.save();
  c.globalAlpha *= alpha;
  c.fillStyle = c.createPattern(grainTile, "repeat");
  c.fillRect(x, y, w, h);
  c.restore();
}
function derrick(c, x, y, z, col) {
  c.save();
  c.translate(x, y);
  c.scale(z, z);
  line(c, [-14, 0, -4, -44, 4, -44, 13, 0], col, 2.4);
  for (let i = 0; i < 4; i++) {
    const yy = -i * 10;
    line(c, [-12 + i * 2, yy, 10 - i * 2, yy - 10, -10 + i * 2, yy - 10, 11 - i * 2, yy], col, .9);
  }
  rect(c, -9, -47, 16, 4, col);
  line(c, [-3, -48, 9, -58, 21, -54], col, 2);
  line(c, [20, -55, 20, -32], col, .7);
  line(c, [-12, -23, 13, -23], col, 1);
  c.restore();
}
function mesa(c, w, h, off, seed, base, amp, unit, col, lit) {
  const n0 = Math.floor(off / unit) - 2,
    n1 = Math.ceil((off + w) / unit) + 1;
  let points = [-unit, h + 2];
  const facets = [];
  for (let i = n0; i <= n1; i++) {
    const x = i * unit - off,
      v = hash(i, seed),
      depth = base - amp * (.08 + .31 * hash(i, seed + 1)),
      peak = base - amp * (.55 + .55 * v),
      ledge = unit * (.01 + .19 * hash(i, seed + 2));
    const p = [x, depth, x + .16 * unit, depth - .045 * amp, x + .25 * unit, depth - .15 * amp, x + .32 * unit, peak + .17 * amp, x + .36 * unit, peak + .14 * amp, x + .39 * unit, peak, x + .50 * unit + ledge, peak - amp * .025, x + .52 * unit + ledge, peak + .145 * amp, x + .57 * unit + ledge, peak + .165 * amp, x + .62 * unit + ledge, depth - .11 * amp, x + .83 * unit, depth - .06 * amp, x + unit, base - amp * (.08 + .31 * hash(i + 1, seed + 1))];
    points.push(...p);
    facets.push({
      x,
      depth,
      peak,
      ledge
    });
  }
  points.push(w + unit, h + 2);
  poly(c, points, col, null);
  if (lit) {
    c.save();
    c.globalAlpha *= .47;
    for (const {
      x,
      depth,
      peak,
      ledge
    } of facets) {
      poly(c, [x + .39 * unit, peak, x + .5 * unit + ledge, peak - .025 * amp, x + .47 * unit + ledge, peak + .13 * amp, x + .42 * unit, peak + .15 * amp, x + .35 * unit, depth - .1 * amp, x + .29 * unit, depth], lit, null);
      line(c, [x + .46 * unit, peak + .20 * amp, x + .48 * unit + ledge, peak + .19 * amp], lit, Math.max(1, amp * .022));
      line(c, [x + .4 * unit, peak + .30 * amp, x + .5 * unit, peak + .30 * amp], lit, 1);
      for (let j = 0; j < 4; j++) {
        const xx = x + (.45 + j * .028) * unit;
        line(c, [xx, peak + (.27 + j * .035) * amp, xx - .013 * unit, peak + (.48 + j * .023) * amp], lit, .7);
      }
    }
    c.restore();
  }
}
function landscape(c, w, h, offset, seed, bio, thumb = false, t = 0) {
  const g = c.createLinearGradient(0, 0, 0, h);
  g.addColorStop(0, bio.sky1);
  g.addColorStop(.82, bio.sky2);
  c.fillStyle = g;
  c.fillRect(0, 0, w, h);
  const sx = w * (thumb ? .72 : .74) - Math.sin(offset * .00012) * w * .06,
    sy = h * (thumb ? .27 : .23),
    sr = h * (thumb ? .235 : .118);
  c.save();
  c.globalAlpha = .15;
  circ(c, sx, sy, sr * 1.2, bio.sun);
  c.restore();
  circ(c, sx, sy, sr, bio.sun);
  for (let i = 0; i < (thumb ? 7 : 15); i++) {
    const r = hash(i, seed + 21),
      y = h * (.06 + hash(i, 12 + seed) * .40),
      ww = (.035 + .12 * r) * w,
      period = w * 1.35,
      xx = ((hash(i, 22 + seed) * period - offset * .038 + t * (i % 3 + 1) * .18) % period + period) % period - .15 * w;
    c.save();
    c.globalAlpha = .20 + .13 * r;
    poly(c, [xx, y, xx + ww * .2, y - .004 * h, xx + ww * .72, y - .004 * h, xx + ww, y, xx + ww * .85, y + h * .006, xx + ww * .10, y + h * .008], bio.sun, null);
    c.restore();
  }
  const u = thumb ? h * .86 : h * .56;
  mesa(c, w, h, offset * .085 + seed % 97, seed + 11, h * .66, h * .24, u, bio.far, null);
  mesa(c, w, h, offset * .17 + u * .33, seed + 4, h * .78, h * .39, u * 1.19, bio.mid, bio.far);
  mesa(c, w, h, offset * .26 + u * .6, seed + 32, h * .93, h * .30, u * .93, bio.near, bio.mid);
  if (thumb) {
    const yy = h * .88;
    derrick(c, w * .29, yy, h * .0082, bio.rock);
    line(c, [w * .10, yy + 3, w * .12, yy - h * .20], bio.rock, 1.5);
    line(c, [w * .105, yy - h * .16, w * .24, yy - h * .12, w * .28, yy - h * .19], bio.rock, .7);
    poly(c, [0, h * .90, w * .12, h * .83, w * .29, h * .86, w * .56, h * .98, w * .77, h * .85, w, h * .79, w, h, 0, h], bio.rock, null);
    for (let i = 0; i < 4; i++) {
      const x = w * (.14 + i * .037),
        y = h * (.24 + hash(i, 89) * .11);
      line(c, [x - 3, y - 1, x, y + 1, x + 4, y - 2], bio.near, .8);
    }
    grain(c, 0, 0, w, h, .085);
  }
}
function drawTire(c, r, spin, big, team) {
  c.save();
  c.rotate(spin);
  c.lineJoin = "round";
  const lugs = big ? 19 : 17;
  for (let i = 0; i < lugs; i++) {
    c.save();
    c.rotate(i * TAU / lugs);
    poly(c, [-r * .15, -r * .85, -r * .12, -r * .99, r * .10, -r, r * .18, -r * .87], i % 3 === 0 ? "#4e5448" : "#424a40", "#212b27", Math.max(.8, r * .045));
    line(c, [-r * .1, -r * .963, r * .055, -r * .974], "#92917a", r * .035);
    c.restore();
  }
  circ(c, 0, 0, r * .902, "#39423b", "#202a26", r * .06);
  circ(c, 0, 0, r * .735, "#4a5347", "#636e5d", r * .033);
  circ(c, 0, 0, r * .636, "#242e2a", "#202722", r * .046);
  circ(c, 0, 0, r * .554, team ? "#a17660" : "#bb9b63", "#d1bf8b", r * .05);
  circ(c, 0, 0, r * .447, "#767b64", "#4c554a", r * .055);
  for (let i = 0; i < 6; i++) {
    c.save();
    c.rotate(i * TAU / 6);
    poly(c, [-r * .08, -r * .43, r * .09, -r * .43, r * .115, -r * .30, 0, -r * .26, -r * .12, -r * .31], "#333e36", null);
    bolt(c, 0, -r * .371, r * .033);
    c.restore();
  }
  circ(c, 0, 0, r * .239, team ? "#c27b5c" : "#c79a58", "#30392e", r * .06);
  circ(c, 0, 0, r * .133, "#5c6757", "#d3b979", r * .035);
  line(c, [-r * .05, r * .045, r * .053, -r * .05], "#29372d", r * .035);
  c.restore();
}
function wheelMount(c, r, heavy, team) {
  c.save();
  const ww = r * .93;
  line(c, [-ww * .82, -r * .55, -ww * .42, -r * 1.03, ww * .24, -r * 1.04, ww * .8, -r * .76], "#29382e", r * .10);
  if (heavy) {
    poly(c, [-ww * .93, -r * .58, -ww * .63, -r * .91, -ww * .34, -r * 1.05, ww * .34, -r * 1.04, ww * .65, -r * .90, ww * .70, -r * .80, ww * .33, -r * .9, -ww * .32, -r * .91, -ww * .75, -r * .64], team ? "#996654" : "#a87543", INK, .86);
    line(c, [-ww * .59, -r * .92, -ww * .31, -r * 1.01, ww * .29, -r * 1.01], "#d7ad73", .8);
    for (let i = 0; i < 3; i++) line(c, [-ww * .38 + i * 3, -r * .94, -ww * .34 + i * 3, -r * .99], INK, .65);
  }
  c.restore();
}
function drawCockpit(c, team) {
  const paint = team ? "#b56654" : ORANGE,
    hi = team ? "#d99776" : "#f0bb6a";
  line(c, [-23, -16, -30, -46], "#2d3933", 1.35);
  poly(c, [-30, -46, -41, -45, -49, -48, -45, -41, -33, -40, -29, -41], team ? "#a79b7a" : "#bb6345", "#3d4439", .8);
  poly(c, [-36, 12, -34, -5, -26, -21, -15, -29, 8, -29, 28, -12, 34, 11, 28, 22, -26, 23], DARK, INK, 2.2);
  poly(c, [-34, 8, -30, -9, -20, -24, 6, -25, 24, -12, 30, 8, 15, 17, -23, 17], paint, INK, 1.6);
  poly(c, [-25, -8, -17, -21, -7, -21, -10, -6], "#617c76", INK, 1.5);
  poly(c, [-7, -6, -4, -22, 5, -22, 20, -10, 20, -5], "#89aca0", INK, 1.7);
  poly(c, [-2, -9, 1, -20, 5, -20, 15, -12, 2, -8], "#bac6a6", null);
  line(c, [-28, -12, -18, -25, 7, -25, 23, -12], hi, 2.1);
  poly(c, [-32, -3, 20, -3, 31, 5, 27, 15, 12, 17, -32, 15], paint, INK, 1.2);
  poly(c, [-33, 13, 26, 12, 24, 20, -28, 21, -36, 17], "#7a8070", INK, 1.5);
  poly(c, [-24, -1, -6, -2, -6, 12, -29, 12], "#d9c398", "#524e3e", .7);
  txt(c, team ? "X" : "07", -17, 9, 11, "#394337", "center", "monospace", "900");
  line(c, [0, 0, -1, 11, 13, 10, 18, 0], hi, .9);
  rect(c, 7, 1, 7, 2, "#3e4539");
  for (let i = 0; i < 3; i++) line(c, [21 + i * 2, 4, 19 + i * 2, 9], "#684f36", 1.1);
  poly(c, [26, -9, 31, -7, 31, -2, 27, 0, 24, -3], "#f3d897", INK, 1.1);
  line(c, [-4, -9, 0, -21, 1, -21], "#d0d9bb", .78);
  line(c, [10, -10, 14, -13], "#b6cebb", 1);
  line(c, [-31, 10, -29, 0, -26, -3], "#e7af68", .9);
  for (let i = 0; i < 4; i++) line(c, [1 + i * 2.6, 13, 3 + i * 2.6, 11], "#9a8a68", .6);
  rect(c, -25, -28, 29, 3, "#6a7161", INK, 1);
  line(c, [-19, -29, -19, -31, 3, -31, 7, -27], INK, 1.4);
  for (const [x, y] of [[-30, 5], [22, 10], [-25, 17], [18, 16]]) bolt(c, x, y, 1.15);
}
function drawPart(c, p, o = {}) {
  const t = p.type,
    d = D[t],
    w = wp(p),
    h = d.h,
    team = o.team,
    orange = team ? "#b96f55" : ORANGE,
    highlight = team ? "#d69877" : HONEY;
  c.save();
  c.translate(p.x, p.y);
  c.rotate(p.rot || 0);
  c.scale(p.flip || 1, 1);
  c.lineJoin = c.lineCap = "round";
  if (wheelType(t)) {
    if (!o.loose) wheelMount(c, w / 2, t === "mud", team);
    drawTire(c, w / 2, o.spin || 0, t === "mud", team);
  } else if (t === "core") drawCockpit(c, team);else if (t === "truss") {
    poly(c, [-w / 2, -h / 2 + 2, -w / 2 + 3, -h / 2, w / 2, -h / 2, w / 2 - 2, h / 2, -w / 2, h / 2], "#313c35", INK, 1.8);
    const n = Math.max(3, Math.round(w / 17)),
      step = (w - 8) / n;
    for (let i = 0; i < n; i++) {
      const x = -w / 2 + 4 + i * step;
      line(c, [x, -h / 2 + 3, x + step / 2, h / 2 - 3, x + step, -h / 2 + 3], "#899483", 2.8);
    }
    rect(c, -w / 2, -h / 2, w, 3, "#a8ae96", INK, .7);
    rect(c, -w / 2, h / 2 - 3, w, 3, "#7c8878", INK, .7);
    for (let i = 0; i <= n; i++) bolt(c, -w / 2 + 4 + i * step, -h / 2 + 1.5, 1.1);
  } else if (t === "wood" || t === "beam") {
    const hh = h / 2,
      ww = w / 2;
    poly(c, [-ww + 1, -hh + 1, ww - 3, -hh, ww, hh - 2, -ww + 3, hh], t === "wood" ? "#bc8650" : "#c99454", INK, 1.6);
    line(c, [-ww + 3, -hh + 2, ww - 3, -hh + 1], "#e2b878", 1.2);
    const n = t === "wood" ? 5 : 3;
    for (let j = 1; j <= n; j++) {
      const y = -hh + j / (n + 1) * h;
      line(c, [-ww + 3, y, -ww * .53, y - 1, -ww * .15, y + .6, ww * .24, y - .2, ww - 4, y + .7], j % 2 ? "#8b5f3e" : "#a8784a", .72);
    }
    if (t === "wood") line(c, [-ww + 2, 0, ww - 4, -1], "#6c5037", 1.3);
    for (const k of [-1, 1]) {
      const x = k * (ww - (t === "wood" ? 5 : 8));
      rect(c, x - 1.8, -hh + 1, 3.8, h - 2, "#7d7960", "#4a5146", .65);
      bolt(c, x, -hh + 3, .95);
      bolt(c, x, hh - 3, .95);
    }
  } else if (t === "motor") {
    poly(c, [-22, -6, -17, -12, 15, -12, 22, -5, 21, 12, 17, 16, -21, 15], "#666e5f", INK, 1.6);
    for (let i = 0; i < 3; i++) {
      const x = -17 + i * 10;
      rect(c, x, -14, 7, 13, "#838e7b", INK, 1);
      for (let j = 0; j < 3; j++) rect(c, x - 1, -13 + j * 3, 9, 1.3, "#343f35");
      rect(c, x, -16, 7, 2, highlight, INK, .7);
    }
    line(c, [-20, 3, -25, 0, -25, -14, -29, -18, -29, -24], "#27332d", 4.4);
    line(c, [-24, -1, -24, -14, -28, -19, -28, -23], "#a1a38a", 1.3);
    rect(c, -33, -25, 8, 3, "#586154", INK, .8);
    rect(c, -17, -1, 33, 12, "#4d594d", INK, 1);
    for (let x = -12; x < 13; x += 4) line(c, [x, 1, x - 2, 8], "#b5af85", 1.2);
    circ(c, 17, 5, 4.2, orange, INK, 1.2);
    bolt(c, 17, 5, 1.4);
    line(c, [-19, -4, -13, -2, 1, -2, 7, -6, 16, -6], "#2c3931", 1.9);
    line(c, [-19, -4, -13, -3, 1, -3, 7, -7, 15, -7], "#bd9868", .9);
    for (let j = 0; j < 3; j++) line(c, [-15 + j * 10, -12, -12 + j * 10, -11], "#c8c6a2", .65);
  } else if (t === "reactor") {
    poly(c, [-21, -13, 12, -13, 22, -5, 20, 13, -14, 15, -23, 6], "#4f635b", INK, 1.7);
    circ(c, 0, 1, 10, "#31453f", "#a2c1a6", 1.3);
    circ(c, 0, 1, 5.5, "#d5d88e", "#e5b15e", 1);
    line(c, [-3, 1, 0, -4, 3, 1, 0, 6], "#586f5c", 1.5);
    for (let i = -1; i <= 1; i++) rect(c, -17 + i * 7, -11, 3, 4, highlight, INK, .7);
  } else if (t === "plate" || t === "ram" || t === "bumper") {
    const a = w / 2,
      b = h / 2;
    if (t === "bumper") {
      poly(c, [-a, -b + 3, -a + 7, -b, a - 5, -b + 1, a, -b + 5, a - 4, b - 3, -a + 6, b, -a, b - 4], orange, INK, 1.8);
      poly(c, [-a + 7, -b + 4, a - 8, -b + 3, a - 6, -b + 7, -a + 10, -b + 8], highlight, null);
      line(c, [-a + 12, 0, a - 10, 0], "#4b5146", 2);
      for (const x of [-a + 8, a - 9]) bolt(c, x, 0, 1.5);
    } else if (t === "plate") {
      poly(c, [-a, b - 2, -a + 2, -b + 2, -a + 12, -b, a - 6, -1, a, b - 5, a - 5, b], orange, INK, 1.7);
      poly(c, [-a + 5, -b + 4, -a + 12, -b + 2, a - 6, 0, a - 5, 3, -a + 9, -b + 5], highlight, null);
      poly(c, [-a + 1, b - 5, a - 4, b - 5, a - 6, b, -a + 1, b], "#767d69", INK, .9);
      line(c, [-a + 7, -b + 7, -a + 8, 3, a - 8, 5], "#8b5638", .8);
      for (let i = 0; i < 4; i++) line(c, [-a + 14 + i * 3, -4, -a + 12 + i * 3, 1], INK, 1.2);
      bolt(c, -a + 6, 5, 1.45);
      bolt(c, a - 9, 6, 1.05);
    } else {
      poly(c, [-a, -b + 2, -a + 7, -b, a, 2, a - 4, b - 1, -a, b], "#828c77", INK, 1.7);
      poly(c, [-a + 4, -b + 1, -a + 8, -b, a, 2, a - 4, 3], LIGHT, null);
      poly(c, [-a + 4, -b + 4, -a + 13, -b + 6, -a + 9, b - 1, -a + 1, b - 1], orange, INK, .8);
      line(c, [-a + 16, -3, a - 4, 3, -a + 13, b - 3], "#465344", 1);
      bolt(c, -a + 5, 1, 1.6);
    }
  } else if (jointType(t)) {
    if (t === "spring") {
      rect(c, -16, -4, 32, 8, STEEL, INK, 1.4);
      let pp = [-10, 0];
      for (let i = 0; i < 8; i++) pp.push(-9 + i * 2.6, i % 2 ? 5 : -5);
      pp.push(12, 0);
      line(c, pp, "#303a30", 3.1);
      line(c, pp, highlight, 1.35);
      circ(c, -13, 0, 4, LIGHT, INK, 1.4);
      bolt(c, -13, 0, 1.3);
      circ(c, 13, 0, 4, LIGHT, INK, 1.4);
    } else if (t === "gimbal") {
      rect(c, -12, -10, 24, 20, "#68796e", INK, 1.4);
      circ(c, 0, 0, 8.5, "#b0b995", INK, 1.2);
      circ(c, 0, 0, 4, "#47584e", "#d7c678", 1);
      line(c, [-15, -5, 15, 5], "#d8ac65", 1.1);
      line(c, [-15, 5, 15, -5], "#536457", 1);
      bolt(c, -8, -8, 1);
      bolt(c, 8, 8, 1);
    } else {
      poly(c, [-10, 0, -6, -8, 5, -8, 10, 0, 6, 8, -5, 8], STEEL, INK, 1.6);
      circ(c, 0, 0, 6.7, highlight, INK, 1.1);
      circ(c, 0, 0, 3, "#545e50", INK, 1);
      line(c, [-2, 2, 2, -2], LIGHT, .9);
    }
  } else if (ranged(t)) {
    poly(c, [-11, 3, 10, 3, 14, 9, -13, 9], DARK, INK, 1.35);
    rect(c, -10, 8, 23, 2.3, STEEL, INK, .7);
    c.save();
    c.rotate(o.aimPart ?? -.055);
    if (t === "pulse") {
      poly(c, [-20, -6, -16, -9, 4, -9, 11, -4, 8, 4, -17, 5, -22, 2], orange, INK, 1.4);
      rect(c, -13, -8, 14, 3, "#a2ac96", INK, .7);
      rect(c, 5, -6, 20, 4, "#9ea999", INK, .9);
      rect(c, 8, -1, 15, 3, "#768675", INK, .8);
      rect(c, 20, -7, 7, 10, "#53685e", INK, 1.2);
      rect(c, 25, -5, 2.5, 4, "#9ddad1");
      for (let i = 0; i < 3; i++) line(c, [-17 + 3 * i, -3, -15 + 3 * i, 1], INK, 1);
      bolt(c, 1, -2, 1.8);
    } else if (t === "arc") {
      poly(c, [-18, -7, -12, -11, 8, -11, 17, -6, 16, 5, -14, 7, -20, 2], STEEL, INK, 1.6);
      rect(c, 4, -8, 17, 11, "#687c70", INK, 1.1);
      rect(c, 14, -10, 8, 15, "#a28a60", INK, 1.2);
      rect(c, 20, -7, 2, 8, "#b8e3aa");
      for (let i = 0; i < 3; i++) rect(c, -11 + i * 4, -9, 2.5, 12, highlight, INK, .5);
    } else if (t === "cannon") {
      poly(c, [-22, -9, -12, -13, 12, -12, 19, -7, 18, 7, 10, 12, -13, 10, -22, 5], "#65756c", INK, 1.7);
      rect(c, -10, -10, 21, 20, "#4c5b53", INK, 1);
      rect(c, -4, -6, 27, 12, "#8c9a83", INK, 1.1);
      rect(c, 19, -4, 18, 8, "#3d4942", INK, 1.2);
      rect(c, 33, -2, 7, 4, highlight, INK, .8);
      bolt(c, -6, -6, 1.5);
      bolt(c, -6, 6, 1.5);
    }
    if (o.flash) {
      poly(c, [24, -5, 33, -7, 30, -4, 42, -3, 31, -1, 34, 2, 24, 0], "#ffdf82", null);
    }
    c.restore();
    circ(c, 0, 4, 3.6, "#7b8874", INK, 1);
    bolt(c, 0, 4, 1.3);
  } else if (t === "saw") {
    c.save();
    c.rotate(o.spin || 0);
    let pts = [];
    for (let i = 0; i < 17; i++) {
      let a = i * TAU / 17;
      for (const [r, b] of [[17, 0], [20, .12], [16, .27]]) pts.push(Math.cos(a + b) * r, Math.sin(a + b) * r);
    }
    poly(c, pts, "#adb5a0", INK, 1.35);
    circ(c, 0, 0, 12, "#768775", INK, 1.2);
    for (let i = 0; i < 5; i++) {
      let a = i * TAU / 5;
      circ(c, Math.cos(a) * 8, Math.sin(a) * 8, 1.8, INK);
    }
    circ(c, 0, 0, 5, orange, INK, 1.3);
    bolt(c, 0, 0, 2);
    c.restore();
  } else if (t === "boost") {
    poly(c, [-23, -11, -11, -14, 10, -11, 19, -6, 19, 6, 10, 11, -11, 14, -23, 9, -16, 4, -16, -4], STEEL, INK, 1.6);
    poly(c, [-23, -6, -13, -4, -13, 4, -23, 6], "#3b4941", INK, 1.2);
    circ(c, -21, 0, 4.2, "#1e2a26", "#d2a35c", 1);
    rect(c, -8, -9, 7, 18, orange, INK, 1);
    rect(c, 3, -7, 11, 14, "#485a51", INK, .8);
    for (let j = 0; j < 3; j++) rect(c, 4 + j * 3, -5, 1.5, 10, "#d5bf87");
    if (o.active) {
      poly(c, [-24, -3, -39, -7, -32, -1, -51, 0, -32, 2, -40, 7, -24, 3], "#ffb958", null);
      poly(c, [-24, -2, -35, -3, -30, 0, -43, 1, -30, 2, -35, 4, -24, 2], "#fff0a0", null);
      line(c, [-30, 0, -47, 0], "#f7d781", 1.7);
    }
  } else if (t === "cell") {
    rect(c, -11, -15, 4, 3, LIGHT, INK, .7);
    rect(c, 7, -15, 4, 3, LIGHT, INK, .7);
    rect(c, -14, -12, 28, 25, "#799184", INK, 1.5);
    rect(c, -13, -12, 26, 4, DARK);
    rect(c, -10, -4, 20, 12, "#a2aa83", INK, .8);
    poly(c, [0, -3, -5, 3, -1, 3, -2, 7, 5, 0, 1, 0, 3, -3], DARK, null);
  } else if (t === "tank") {
    rect(c, -17, -13, 34, 26, "#826a52", INK, 1.5);
    rect(c, -13, -9, 26, 18, "#b08b59", INK, .9);
    line(c, [-9, -6, 9, -6, 9, 6, -9, 6, -9, -6], "#574c3c", 1.1);
    rect(c, -4, -17, 8, 4, "#a6b098", INK, .8);
    for (let i = -1; i <= 1; i++) bolt(c, i * 11, 0, 1.1);
  } else if (t === "sensor") {
    rect(c, -11, -17, 22, 29, "#566e67", INK, 1.4);
    rect(c, -7, -12, 14, 10, "#9bbcae", INK, .8);
    line(c, [0, -12, 0, -25, 9, -32], "#34443d", 1.5);
    circ(c, 10, -32, 3, "#e2bd6d", INK, 1);
    for (let i = 0; i < 3; i++) line(c, [-7, 4 + i * 4, 7, 4 + i * 4], "#c0c6aa", .9);
  } else if (t === "vent") {
    poly(c, [-20, -10, 20, -10, 16, 11, -16, 11], "#6c7e73", INK, 1.5);
    for (let i = -12; i <= 12; i += 6) line(c, [i, -6, i - 4, 7], "#d6d0aa", 1.5);
    line(c, [-13, -13, 13, -13], "#c9aa69", 1.1);
  } else if (t === "ward") {
    poly(c, [-18, 6, -13, -3, 13, -3, 18, 6, 16, 10, -16, 10], STEEL, INK, 1.35);
    for (let i = -1; i <= 1; i++) {
      rect(c, i * 8 - 1.5, -10, 3, 14, DARK);
      for (let j = 0; j < 4; j++) rect(c, i * 8 - 3, -8 + j * 2.5, 6, 1.4, "#b18552");
    }
    line(c, [-13, -6, -9, -10, 0, -7, 7, -12, 13, -8], "#9fdac8", 1.3);
  } else if (t === "cooler") {
    rect(c, -17, -11, 34, 22, STEEL, INK, 1.5);
    rect(c, -14, -8, 28, 16, DARK);
    for (let i = -11; i < 13; i += 4) line(c, [i, -6, i - 2, 6], LIGHT, 1.3);
    bolt(c, 13, 8, 1.1);
  } else if (t === "skid") {
    poly(c, [-w / 2, -4, -w / 2 + 7, 0, w / 2 - 8, 0, w / 2, -6, w / 2 - 2, 1, w / 2 - 7, 5, -w / 2 + 5, 5], LIGHT, INK, 1.5);
  }
  if (o.damage > .34) {
    c.globalAlpha = clamp(o.damage, 0, 1) * .86;
    line(c, [-w * .16, -h * .24, -w * .09, -h * .03, -w * .16, h * .06, -w * .05, h * .22], "#543d32", 1.3);
    if (o.damage > .7) line(c, [w * .19, -h * .2, w * .12, -h * .02, w * .19, h * .08], "#543d32", 1.1);
  }
  c.restore();
}
function ordered(ps) {
  return [...ps].sort((a, b) => layerIndex(a.layer) - layerIndex(b.layer) || D[a.type].z - D[b.type].z || a.id - b.id);
}
function diagramRig(c, ps, options = {}) {
  for (const p of ordered(ps)) drawPart(c, p, options);
}
function miniRig(canvas, rig) {
  const {
      c,
      w,
      h
    } = fitCanvas(canvas),
    bb = bounds(rig.parts),
    z = Math.min((w - 24) / (bb.w + 10), (h - 8) / (bb.h + 21));
  rect(c, 0, 0, w, h, "#c8cbb5");
  c.save();
  c.translate(w / 2 - z * (bb.l + bb.r) / 2, h / 2 - z * ((bb.t + bb.b) / 2 - 4));
  c.scale(z, z);
  diagramRig(c, rig.parts);
  c.restore();
  grain(c, 0, 0, w, h, .05);
}
function partThumb(canvas, t) {
  const {
    c,
    w,
    h
  } = fitCanvas(canvas);
  c.clearRect(0, 0, w, h);
  const d = D[t],
    z = Math.min((w - 16) / (d.w + 6), (h - 12) / (d.h + (t === "motor" ? 15 : 2)), 1.12);
  c.save();
  c.translate(w * .52, h * .56);
  c.scale(z, z);
  c.rotate(t === "beam" || t === "truss" ? -.12 : 0);
  drawPart(c, part(1, t, 0, 0, null));
  c.restore();
}

// 图层栈。layers 按底层到顶层保存,界面从顶层向下展示。
function layerById(id) {
  return S.rig.layers.find(layer => layer.id === id) || null;
}
function activeLayerId() {
  if (!layerById(S.rig.activeLayer)) S.rig.activeLayer = S.rig.layers.at(-1)?.id;
  return S.rig.activeLayer;
}
function activeLayer() {
  return layerById(activeLayerId());
}
function layerIndex(id) {
  return S.rig.layers.findIndex(layer => layer.id === id);
}
function layerVisible(id) {
  return layerById(id)?.visible !== false;
}
function partVisible(p) {
  return layerVisible(p.layer);
}
function layerPartOpaque(p) {
  return p.layer === activeLayerId() || crossLayerJoint(p.type);
}
function crossLayerLink(a, b) {
  return layerCollisionAllowed(a, b);
}
function editablePart(p) {
  return !!p && p.layer === activeLayerId();
}
function sameLayerDescendants(id) {
  const all = descendants(S.rig.parts, id),
    layer = activeLayerId();
  return new Set([...all].filter(v => pickPart(v)?.layer === layer));
}
function ensureEditableLayer() {
  const layer = activeLayer();
  if (!layer) return false;
  if (!layer.visible) {
    toast("当前图层已隐藏,请先点击眼睛显示");
    return false;
  }
  return true;
}
function layerThumb(canvas, layerId) {
  const { c, w, h } = fitCanvas(canvas),
    parts = S.rig.parts.filter(p => p.layer === layerId),
    bb = parts.length ? bounds(parts) : { l: -30, r: 30, t: -20, b: 20, w: 60, h: 40 },
    z = Math.min((w - 8) / Math.max(20, bb.w + 10), (h - 8) / Math.max(20, bb.h + 10));
  c.clearRect(0, 0, w, h);
  c.save();
  c.translate(w / 2 - z * (bb.l + bb.r) / 2, h / 2 - z * (bb.t + bb.b) / 2);
  c.scale(z, z);
  for (const p of ordered(parts)) drawPart(c, p, { team: false });
  c.restore();
}
function refreshLayers() {
  const list = $("layersList");
  if (!list) return;
  const active = activeLayerId(),
    rows = [...S.rig.layers].reverse().map(layer => {
      const count = S.rig.parts.filter(p => p.layer === layer.id).length,
        eye = layer.visible ? "eye" : "eyeOff",
        cls = ["layer-row", layer.id === active ? "active" : "", layer.visible ? "" : "hidden-layer"].filter(Boolean).join(" ");
      return '<div class="' + cls + '" data-layer-id="' + esc(layer.id) + '" tabindex="0" role="button" aria-pressed="' + (layer.id === active) + '"><button class="layer-eye" data-layer-visibility="' + esc(layer.id) + '" aria-label="' + (layer.visible ? "隐藏" : "显示") + layer.name + '" title="' + (layer.visible ? "隐藏图层" : "显示图层") + '">' + iconMarkup(eye) + '</button><button class="layer-main" data-layer-select="' + esc(layer.id) + '"><canvas class="layer-thumb" data-layer-thumb="' + esc(layer.id) + '" aria-hidden="true"></canvas><span><b>' + esc(layer.name) + '</b><small>' + count + ' 件' + (layer.id === S.rig.layers.at(-1)?.id ? " · 顶层" : "") + '</small></span></button><span class="layer-drag" aria-hidden="true">⋮⋮</span></div>';
    }).join("");
  list.innerHTML = rows + '<div class="layer-row background-row" aria-label="背景"><span class="layer-eye" aria-hidden="true">' + iconMarkup("eye") + '</span><span class="layer-main"><span class="layer-thumb"></span><span><b>背景</b><small>工作台</small></span></span></div>';
  paintIcons(list);
  for (const cv of list.querySelectorAll("[data-layer-thumb]")) layerThumb(cv, cv.dataset.layerThumb);
}
function selectLayer(id) {
  if (!layerById(id)) return;
  S.rig.activeLayer = id;
  E.sel = null;
  E.anchor = null;
  refreshLayers();
  updateTools();
  benchDirty = true;
}
function toggleLayer(id) {
  const layer = layerById(id);
  if (!layer) return;
  checkpoint();
  layer.visible = !layer.visible;
  if (!layer.visible && activeLayerId() === id) {
    const next = [...S.rig.layers].reverse().find(v => v.visible);
    if (next) S.rig.activeLayer = next.id;
  }
  refreshEditor();
  toast(layer.visible ? "已显示「" + layer.name + "」" : "已隐藏「" + layer.name + "」");
}
function addLayer() {
  checkpoint();
  const n = S.rig.layers.length + 1,
    id = "layer-" + Date.now().toString(36) + "-" + n,
    layer = { id, name: "图层" + n, visible: true };
  S.rig.layers.push(layer);
  S.rig.activeLayer = id;
  refreshEditor();
  toast("已新增「" + layer.name + "」并设为顶层");
}
function reorderLayer(id, beforeId) {
  if (!id || id === beforeId) return false;
  const from = S.rig.layers.findIndex(v => v.id === id),
    to = S.rig.layers.findIndex(v => v.id === beforeId);
  if (from < 0 || to < 0) return false;
  const [item] = S.rig.layers.splice(from, 1);
  S.rig.layers.splice(to, 0, item);
  refreshLayers();
  benchDirty = true;
  persist();
  return true;
}

// 蓝图编辑、命中检测、连接树与撤销
const E = {
  sel: null,
  tool: "select",
  place: null,
  cat: "全部",
  snap: true,
  links: false,
  zoom: 1,
  ref: 2,
  cx: 0,
  cy: 0,
  hover: null,
  ghost: null,
  anchor: null,
  angle: 0,
  mirror: 1,
  len: 1,
  drag: null,
  undo: [],
  redo: []
};
let benchDirty = true,
  editCache = {
    missing: [],
    connected: new Set()
  };
const pickPart = id => S.rig.parts.find(p => p.id === id);
function descendants(ps, id) {
  const found = new Set([id]);
  let size = -1;
  while (size !== found.size) {
    size = found.size;
    for (const p of ps) if (found.has(p.parent)) found.add(p.id);
  }
  return found;
}
function pointDist(p, x, y) {
  const d = D[p.type],
    v = rotate(x - p.x, y - p.y, -p.rot);
  if (wheelType(p.type) || p.type === "saw" || p.type === "hinge") return Math.hypot(v.x, v.y) - wp(p) / 2;
  const dx = Math.abs(v.x) - wp(p) / 2,
    dy = Math.abs(v.y) - d.h / 2;
  return Math.hypot(Math.max(0, dx), Math.max(0, dy)) + Math.min(0, Math.max(dx, dy));
}
function separation(a, b) {
  const dx = b.x - a.x,
    dy = b.y - a.y,
    round = p => wheelType(p.type) || p.type === "saw" || p.type === "hinge",
    axes = [a.rot, a.rot + Math.PI / 2, b.rot, b.rot + Math.PI / 2, Math.atan2(dy, dx)];
  function rad(p, ang) {
    return round(p) ? wp(p) / 2 : Math.abs(Math.cos(ang - p.rot)) * wp(p) / 2 + Math.abs(Math.sin(ang - p.rot)) * D[p.type].h / 2;
  }
  let gap = -Infinity;
  for (const ang of axes) gap = Math.max(gap, Math.abs(dx * Math.cos(ang) + dy * Math.sin(ang)) - rad(a, ang) - rad(b, ang));
  return gap;
}
function mountFor(p, exclude = new Set(), preferred = null) {
  let best = null,
    score = Infinity;
  for (const a of S.rig.parts) {
    if (a.id === p.id || exclude.has(a.id) || !partVisible(a) || !crossLayerLink(p, a)) continue;
    const gap = separation(p, a);
    if (gap > 18) continue;
    const rank = Math.max(0, gap) * 2.1 + Math.max(-10, pointDist(a, p.x, p.y)) + .11 * Math.hypot(p.x - a.x, p.y - a.y) - (a.id === preferred ? 29 : 0) - (jointType(a.type) ? 9 : 0);
    if (rank < score) {
      best = a;
      score = rank;
    }
  }
  return best;
}
function connectivity() {
  const ps = S.rig.parts,
    core = ps.find(p => p.type === "core"),
    set = new Set([core.id]);
  let last = -1;
  while (last !== set.size) {
    last = set.size;
    for (const p of ps) {
      const parent = pickPart(p.parent);
      if (!set.has(p.id) && parent && set.has(p.parent) && crossLayerLink(p, parent) && separation(p, parent) <= 23) set.add(p.id);
    }
  }
  editCache = {
    connected: set,
    missing: ps.filter(p => !set.has(p.id))
  };
  return editCache;
}
function checkpoint() {
  E.undo.push(copy(S.rig));
  if (E.undo.length > 60) E.undo.shift();
  E.redo = [];
}
function timeTravel(back) {
  const from = back ? E.undo : E.redo,
    to = back ? E.redo : E.undo;
  if (!from.length) return;
  to.push(copy(S.rig));
  S.rig = from.pop();
  resetTool();
  refreshEditor();
  sfxUndo(back);
}
function resetTool() {
  E.tool = "select";
  E.place = null;
  E.sel = null;
  E.ghost = null;
  E.hover = null;
  E.drag = null;
  E.anchor = null;
}
function editChanged() {
  refreshEditor();
  sfxUi("tool");
}
function refreshEditor(save = true) {
  const r = S.rig,
    st = rigStats(r.parts, S.up);
  connectivity();
  $("rigName").textContent = r.name;
  $("connection").textContent = editCache.missing.length ? editCache.missing.length + " 件尚未接入核心" : r.parts.length + " 件零件 · 全车已连接";
  $("connection").classList.toggle("danger-text", !!editCache.missing.length);
  $("massText").textContent = st.mass + " kg";
  $("hpText").textContent = st.hp + " HP";
  $("powerText").textContent = st.power + " kW";
  for (const [id, v] of [["massBar", st.mass / 370], ["hpBar", st.hp / 320], ["powerBar", st.power / 145]]) $(id).style.width = clamp(v * 100, 3, 100) + "%";
  $("weaponsText").textContent = "武装挂载  " + st.weapons;
  $("wheelText").textContent = "接地轮组  " + st.wheels;
  $("undoBtn").disabled = !E.undo.length;
  $("redoBtn").disabled = !E.redo.length;
  updateTools();
  refreshLayers();
  if (save) persist();
  benchDirty = true;
}
function updateTools() {
  const picked = pickPart(E.sel),
    p = editablePart(picked) ? picked : null,
    active = E.tool === "place" ? E.place : p?.type,
    ins = $("inspector");
  $("selectTool").classList.toggle("active", E.tool === "select");
  $("panTool").classList.toggle("active", E.tool === "pan");
  $("snapTool").classList.toggle("on", E.snap);
  $("linkTool").classList.toggle("on", E.links);
  $("snapTool").setAttribute("aria-pressed", E.snap);
  $("linkTool").setAttribute("aria-pressed", E.links);
  $("zoomRead").textContent = Math.round(E.zoom * 100) + "%";
  $("bench").style.cursor = E.tool === "pan" ? "grab" : E.tool === "place" ? "crosshair" : "default";
  $("boardHint").textContent = E.tool === "place" ? "点击图纸安装 · Esc 结束" : E.tool === "pan" ? "拖动画布平移" : E.tool === "remount" ? "点击相邻零件,设为新母件" : "拖动移动零件 · 滚轮缩放";
  for (const el of $("parts").children) {
    el.classList.toggle("active", el.dataset.part === E.place);
    el.setAttribute("aria-pressed", el.dataset.part === E.place);
  }
  ins.hidden = !active;
  if (active) {
    ins.innerHTML = '<strong>' + D[active].name + '</strong><span class="desc">' + D[active].desc + '</span><button data-act="rotate">旋转</button><button data-act="mirror">镜像</button><button data-act="tunePart">精调</button>' + (variable(active) ? '<button data-act="shorter">缩短</button><button data-act="longer">伸长</button>' : '') + (E.tool !== "place" && p && p.type !== "core" ? '<button data-act="remount">改接</button><button data-act="copyPart">复制</button><button data-act="remove">拆除</button>' : '') + '<button data-act="select">完成</button>';
  }
  paintIcons($("drawing"));
  benchDirty = true;
}
function rack(cat = E.cat) {
  E.cat = cat;
  const cats = ["全部", "结构", "连接", "行走", "动力", "武装", "装置"];
  const cs = $("categories");
  cs.innerHTML = cats.map(v => '<button class="cat ' + (v === cat ? 'active' : '') + '" data-cat="' + v + '">' + v + '</button>').join("");
  const ids = catalogOrder.filter(t => cat === "全部" || D[t].cat === cat);
  $("partCount").textContent = ids.length + " 件";
  const cont = $("parts");
  cont.innerHTML = ids.map(t => '<button class="part-card" data-part="' + t + '" title="' + D[t].name + ' · ' + D[t].desc + '"><canvas aria-hidden="true"></canvas><span class="part-id">P' + String(catalogOrder.indexOf(t) + 1).padStart(2, "0") + '</span><span class="part-caption"><b>' + D[t].name + '</b><span class="part-plus">+</span></span></button>').join("");
  cont.scrollLeft = 0;
  paintRack();
  updateTools();
}
function paintRack() {
  for (const el of $("parts").children) partThumb(el.querySelector("canvas"), el.dataset.part);
}
function fitEditor() {
  const b = bounds(S.rig.parts),
    r = $("bench").getBoundingClientRect();
  E.ref = clamp(Math.min(r.width * .64 / (b.w + 10), r.height * .66 / (b.h + 9)), .2, 3.25);
  E.zoom = 1;
  E.cx = (b.l + b.r) / 2;
  E.cy = (b.t + b.b) / 2 - 3;
  benchDirty = true;
  $("zoomRead").textContent = "100%";
}
function matrix() {
  const r = $("bench").getBoundingClientRect(),
    z = E.ref * E.zoom;
  return {
    z,
    ox: r.width * .50 - E.cx * z,
    oy: r.height * .51 - E.cy * z,
    w: r.width,
    h: r.height
  };
}
function localPoint(ev) {
  const r = $("bench").getBoundingClientRect(),
    m = matrix(),
    sx = ev.clientX - r.left,
    sy = ev.clientY - r.top;
  return {
    x: (sx - m.ox) / m.z,
    y: (sy - m.oy) / m.z,
    sx,
    sy
  };
}
function doZoom(f, xy = null) {
  const before = matrix();
  E.zoom = clamp(E.zoom * f, .32, 3.4);
  if (xy) {
    const after = matrix();
    E.cx += (xy.sx - before.ox) / before.z - (xy.sx - after.ox) / after.z;
    E.cy += (xy.sy - before.oy) / before.z - (xy.sy - after.oy) / after.z;
  }
  $("zoomRead").textContent = Math.round(E.zoom * 100) + "%";
  benchDirty = true;
  if (audioThrottle("zoom", .08)) sfxUi("tool");
}
function hitPart(pt) {
  const ord = ordered(S.rig.parts).reverse();
  return ord.find(p => p.layer === activeLayerId() && partVisible(p) && pointDist(p, pt.x, pt.y) < Math.min(5, 3 / matrix().z));
}
function drawOutline(c, p, col, dash = true) {
  c.save();
  c.translate(p.x, p.y);
  c.rotate(p.rot);
  c.strokeStyle = col;
  c.lineWidth = 1.25 / matrix().z;
  if (dash) c.setLineDash([4 / matrix().z, 3 / matrix().z]);
  if (wheelType(p.type) || p.type === "saw") {
    c.beginPath();
    c.arc(0, 0, wp(p) / 2 + 2, 0, TAU);
    c.stroke();
  } else c.strokeRect(-wp(p) / 2 - 2, -D[p.type].h / 2 - 2, wp(p) + 4, D[p.type].h + 4);
  c.restore();
}
function drawBench() {
  if (!benchDirty || scene !== "garage") return;
  benchDirty = false;
  const {
      c,
      w,
      h
    } = fitCanvas($("bench")),
    m = matrix(),
    z = m.z,
    b = bounds(S.rig.parts),
    screen = (x, y) => ({
      x: m.ox + x * z,
      y: m.oy + y * z
    });
  const g = c.createLinearGradient(0, 0, w, h);
  g.addColorStop(0, "#dadaca");
  g.addColorStop(.62, "#d0d2bd");
  g.addColorStop(1, "#bfc4ad");
  c.fillStyle = g;
  c.fillRect(0, 0, w, h);
  const small = 8 * z,
    major = 40 * z;
  function grid(step, col) {
    c.beginPath();
    for (let x = (m.ox % step + step) % step; x < w; x += step) {
      c.moveTo(x, 0);
      c.lineTo(x, h);
    }
    for (let y = (m.oy % step + step) % step; y < h; y += step) {
      c.moveTo(0, y);
      c.lineTo(w, y);
    }
    c.strokeStyle = col;
    c.lineWidth = .7;
    c.stroke();
  }
  if (small > 5) grid(small, "#67775c27");
  grid(major, "#61735b54");
  grain(c, 0, 0, w, h, .055);
  for (let x = (m.ox % major + major) % major; x < w; x += major) {
    line(c, [x, 0, x, 5], "#6b79626b", .8);
    line(c, [x, h - 4, x, h], "#6b79626b", .8);
  }
  for (let y = (m.oy % major + major) % major; y < h; y += major) {
    line(c, [0, y, 5, y], "#6b79626b", .8);
    line(c, [w - 4, y, w, y], "#6b79626b", .8);
  }
  const left = screen(b.l, b.b),
    right = screen(b.r, b.b);
  c.save();
  c.globalAlpha = .13;
  c.fillStyle = "#4b5644";
  c.beginPath();
  c.ellipse((left.x + right.x) / 2, left.y + 3, Math.max(5, b.w * z * .53), Math.max(2, 3 * z), 0, 0, TAU);
  c.fill();
  c.restore();
  c.save();
  c.translate(m.ox, m.oy);
  c.scale(z, z);
  const visibleParts = S.rig.parts.filter(partVisible);
  for (const p of ordered(visibleParts)) {
    c.save();
    c.globalAlpha = layerPartOpaque(p) ? 1 : .48;
    drawPart(c, p);
    c.restore();
  }
  for (const p of editCache.missing) if (partVisible(p)) drawOutline(c, p, "#ba4934");
  if (E.links) {
    for (const p of visibleParts) {
      const a = pickPart(p.parent);
      if (a && partVisible(a) && crossLayerLink(p, a)) {
        line(c, [p.x, p.y, a.x, a.y], "#276e5acf", 1.35 / z);
        circ(c, p.x, p.y, 2.5 / z, "#e6d297", "#315748", 1 / z);
      }
    }
    const mass = S.rig.parts.reduce((n, p) => n + massOf(p), 0),
      cx = S.rig.parts.reduce((n, p) => n + p.x * massOf(p), 0) / mass,
      cy = S.rig.parts.reduce((n, p) => n + p.y * massOf(p), 0) / mass;
    circ(c, cx, cy, 6 / z, "#e6cf75", "#2a584a", 1.5 / z);
    line(c, [cx - 9 / z, cy, cx + 9 / z, cy], "#2a584a", 1 / z);
    line(c, [cx, cy - 9 / z, cx, cy + 9 / z], "#2a584a", 1 / z);
  }
  if (E.sel && pickPart(E.sel)) drawOutline(c, pickPart(E.sel), "#97562a", false);else if (E.hover && pickPart(E.hover) && E.tool === "select") drawOutline(c, pickPart(E.hover), "#4d725b");
  if (E.tool === "place" && E.ghost) {
    const p = E.ghost,
      target = mountFor(p, new Set(), E.anchor);
    c.save();
    c.globalAlpha = .7;
    drawPart(c, p);
    c.restore();
    drawOutline(c, p, target ? "#277551" : "#b44732");
    if (target) {
      line(c, [p.x, p.y, target.x, target.y], "#267858", 1.6 / z);
      circ(c, target.x, target.y, 4 / z, "#eacf72", "#285a44", 1 / z);
    }
  }
  c.restore();
  const dimY = left.y + Math.max(13, 8 * z);
  if (dimY < h - 11 && left.x > -60 && right.x < w + 60) {
    const middle = (left.x + right.x) / 2;
    const col = "#53664f";
    line(c, [left.x, left.y + 5, left.x, dimY + 4], col, .7);
    line(c, [right.x, right.y + 5, right.x, dimY + 4], col, .7);
    line(c, [left.x, dimY, middle - 30, dimY], col, .7);
    line(c, [middle + 30, dimY, right.x, dimY], col, .7);
    for (const x of [left.x, right.x]) line(c, [x - 2, dimY + 3, x + 2, dimY - 3], col, .9);
    txt(c, (b.w / 40).toFixed(2) + " m", middle, dimY + 3, 10, col, "center");
  }
  if (w > 535 && !E.drag && !E.ghost && !E.links && E.zoom < 1.55) {
    const p = pickPart(E.sel) || S.rig.parts.find(q => q.type === "core"),
      pt = screen(p.x, p.y),
      tx = clamp(pt.x + Math.max(80, w * .15), 110, w - 103),
      ty = clamp(pt.y - 85, 64, h - 75);
    line(c, [pt.x + 9, pt.y - 7, tx - 14, ty, tx + 59, ty], "#657a648c", .9);
    circ(c, pt.x + 9, pt.y - 7, 2.5, "#d5d6bd", "#61715b", 1);
    txt(c, D[p.type].name, tx - 9, ty - 5, 10, "#52674f", "left", CJK, "600");
  }
}
function gridNum(n) {
  return E.snap ? Math.round(n / 4) * 4 : Math.round(n * 10) / 10;
}
function choosePart(t) {
  if (!catalogOrder.includes(t) || !ensureEditableLayer()) return;
  E.anchor = E.sel;
  E.tool = "place";
  E.place = t;
  E.angle = 0;
  E.mirror = 1;
  E.len = 1;
  E.ghost = null;
  E.hover = null;
  updateTools();
  sfxUi("part");
}
function ghostAt(pt) {
  const p = part(0, E.place, clamp(gridNum(pt.x), -BUILD_LIMIT, BUILD_LIMIT), clamp(gridNum(pt.y), -BUILD_LIMIT, BUILD_LIMIT), null, E.angle, E.len, E.mirror);
  p.layer = activeLayerId();
  return p;
}
function install(pt) {
  if (!ensureEditableLayer()) return;
  if (S.rig.parts.length >= 72) {
    toast("蓝图最多可装 72 件零件");
    return;
  }
  const p = ghostAt(pt),
    a = mountFor(p, new Set(), E.anchor);
  checkpoint();
  p.id = 1;
  while (pickPart(p.id)) p.id++;
  p.parent = a?.id ?? null;
  S.rig.parts.push(p);
  E.anchor = p.id;
  E.ghost = null;
  editChanged();
  sfxInstall();
  if (!a) toast("该零件尚未连接。拖到车体旁即可接入。");
}
function alter(kind) {
  const isPlace = E.tool === "place",
    p = pickPart(E.sel);
  if (!isPlace && (!p || !editablePart(p) || !ensureEditableLayer())) return;
  if (isPlace) {
    if (kind === "rotate") E.angle = normA(E.angle + 15 * RAD);
    if (kind === "mirror") E.mirror *= -1;
    if (kind === "longer" || kind === "shorter") E.len = clamp(E.len + (kind === "longer" ? .15 : -.15), .45, 2.2);
    if (E.ghost) {
      E.ghost.rot = E.angle;
      E.ghost.flip = E.mirror;
      E.ghost.len = E.len;
    }
    benchDirty = true;
    if (kind === "rotate") sfxRotate();else sfxUi("tool");
    return;
  }
  checkpoint();
  if (kind === "rotate") {
    const ids = sameLayerDescendants(p.id);
    for (const q of S.rig.parts) if (ids.has(q.id)) {
      const d = rotate(q.x - p.x, q.y - p.y, 15 * RAD);
      q.x = p.x + d.x;
      q.y = p.y + d.y;
      q.rot = normA(q.rot + 15 * RAD);
    }
  } else if (kind === "mirror") p.flip *= -1;else if (variable(p.type)) p.len = clamp(p.len + (kind === "longer" ? .15 : -.15), .45, 2.2);
  editChanged();
  if (kind === "rotate") sfxRotate();else sfxUi("tool");
}
function removePart() {
  const p = pickPart(E.sel);
  if (!p || !editablePart(p) || !ensureEditableLayer() || p.type === "core" || E.tool === "place") return;
  checkpoint();
  const ps = S.rig.parts.filter(q => q.id !== p.id);
  S.rig.parts = ps;
  for (const kid of ps.filter(q => q.parent === p.id)) kid.parent = mountFor(kid, descendants(ps, kid.id), p.parent)?.id ?? null;
  E.sel = null;
  editChanged();
  sfxRemove();
}
let layerPress = null;
function bindLayers() {
  const list = $("layersList");
  if (!list) return;
  list.addEventListener("click", ev => {
    const eye = ev.target.closest("[data-layer-visibility]");
    if (eye) {
      ev.preventDefault();
      ev.stopPropagation();
      toggleLayer(eye.dataset.layerVisibility);
      return;
    }
    const select = ev.target.closest("[data-layer-select]");
    if (select) {
      ev.preventDefault();
      ev.stopPropagation();
      selectLayer(select.dataset.layerSelect);
    }
  });
  list.addEventListener("keydown", ev => {
    const row = ev.target.closest(".layer-row[data-layer-id]");
    if (row && (ev.key === "Enter" || ev.key === " ")) {
      ev.preventDefault();
      selectLayer(row.dataset.layerId);
    }
  });
  list.addEventListener("pointerdown", ev => {
    const row = ev.target.closest(".layer-row[data-layer-id]");
    if (!row || ev.target.closest(".layer-eye")) return;
    const id = row.dataset.layerId;
    layerPress = { id, row, x: ev.clientX, y: ev.clientY, reordering: false, moved: false, timer: setTimeout(() => {
      if (!layerPress || layerPress.id !== id || layerPress.moved) return;
      layerPress.reordering = true;
      checkpoint();
      row.classList.add("reordering");
      list.setPointerCapture?.(ev.pointerId);
      toast("正在调整图层顺序");
    }, 480) };
  });
  list.addEventListener("pointermove", ev => {
    const d = layerPress;
    if (!d) return;
    if (!d.reordering) {
      if (Math.hypot(ev.clientX - d.x, ev.clientY - d.y) > 8) {
        d.moved = true;
        clearTimeout(d.timer);
      }
      return;
    }
    const target = document.elementFromPoint(ev.clientX, ev.clientY)?.closest?.(".layer-row[data-layer-id]");
    if (!target || target.dataset.layerId === d.id) return;
    if (reorderLayer(d.id, target.dataset.layerId)) {
      layerPress.row = [...list.querySelectorAll("[data-layer-id]")].find(node => node.dataset.layerId === d.id);
      layerPress.row?.classList.add("reordering");
    }
  });
  const end = ev => {
    const d = layerPress;
    if (!d) return;
    clearTimeout(d.timer);
    d.row?.classList.remove("reordering");
    if (d.reordering) {
      refreshEditor();
    } else if (!d.moved) {
      selectLayer(d.id);
    }
    layerPress = null;
  };
  list.addEventListener("pointerup", end);
  list.addEventListener("pointercancel", end);
}

function bindBench() {
  const cv = $("bench");
  cv.addEventListener("contextmenu", e => e.preventDefault());
  cv.addEventListener("wheel", ev => {
    ev.preventDefault();
    doZoom(ev.deltaY < 0 ? 1.12 : 1 / 1.12, localPoint(ev));
  }, {
    passive: false
  });
  cv.addEventListener("pointerdown", ev => {
    if (modalKind || E.drag) return;
    cv.focus({
      preventScroll: true
    });
    const q = localPoint(ev);
    if (ev.button === 2 && E.tool === "place") {
      resetTool();
      updateTools();
      return;
    }
    if (ev.button === 1 || ev.button === 2 || E.tool === "pan") {
      E.drag = {
        kind: "pan",
        start: q,
        cx: E.cx,
        cy: E.cy,
        id: ev.pointerId
      };
      cv.setPointerCapture(ev.pointerId);
      return;
    }
    if (E.tool === "place") {
      install(q);
      return;
    }
    if (E.tool === "remount") {
      const p = pickPart(E.sel),
        ids = descendants(S.rig.parts, p.id),
        target = ordered(S.rig.parts).reverse().find(a => !ids.has(a.id) && pointDist(a, q.x, q.y) < 3);
      setMother(target);
      return;
    }
    const p = hitPart(q);
    E.sel = p?.id ?? null;
    E.hover = null;
    if (p) {
      const ids = sameLayerDescendants(p.id);
      E.drag = {
        id: ev.pointerId,
        kind: "part",
        p: p.id,
        layer: activeLayerId(),
        start: q,
        ids,
        orig: S.rig.parts.filter(a => ids.has(a.id)).map(a => ({
          id: a.id,
          x: a.x,
          y: a.y
        })),
        moved: false
      };
      cv.setPointerCapture(ev.pointerId);
    }
    updateTools();
  });
  cv.addEventListener("pointermove", ev => {
    const q = localPoint(ev),
      d = E.drag;
    if (d && d.id !== ev.pointerId) return;
    if (d?.kind === "part" && activeLayerId() !== d.layer) {
      E.drag = null;
      benchDirty = true;
      return;
    }
    if (d?.kind === "pan") {
      const z = matrix().z;
      E.cx = d.cx - (q.sx - d.start.sx) / z;
      E.cy = d.cy - (q.sy - d.start.sy) / z;
    } else if (d?.kind === "part") {
      if (!d.moved && Math.hypot(q.sx - d.start.sx, q.sy - d.start.sy) < 3) return;
      if (!d.moved) {
        checkpoint();
        d.moved = true;
      }
      const dx = clamp(gridNum(q.x - d.start.x), -BUILD_LIMIT - Math.min(...d.orig.map(p => p.x)), BUILD_LIMIT - Math.max(...d.orig.map(p => p.x))),
        dy = clamp(gridNum(q.y - d.start.y), -BUILD_LIMIT - Math.min(...d.orig.map(p => p.y)), BUILD_LIMIT - Math.max(...d.orig.map(p => p.y)));
      for (const a of d.orig) {
        const p = pickPart(a.id);
        p.x = a.x + dx;
        p.y = a.y + dy;
      }
    } else if (E.tool === "place") E.ghost = ghostAt(q);else E.hover = hitPart(q)?.id ?? null;
    benchDirty = true;
  });
  const end = ev => {
    const d = E.drag;
    if (!d || d.id !== ev.pointerId) return;
    E.drag = null;
    if (d.kind === "part" && d.moved) {
      const p = pickPart(d.p);
      if (p && editablePart(p) && p.type !== "core") p.parent = mountFor(p, d.ids, p.parent)?.id ?? null;
      editChanged();
    }
    benchDirty = true;
  };
  cv.addEventListener("pointerup", end);
  cv.addEventListener("pointercancel", end);
  cv.addEventListener("pointerleave", () => {
    E.ghost = null;
    E.hover = null;
    benchDirty = true;
  });
}

// 固定步长动力学、铰接约束、敌车决策与战斗
// World units are pixels and seconds. Each rigid group carries its own mass and moment of inertia.
const STEP = 1 / 90,
  GRAV = 720,
  keys = new Set(),
  hold = new Map();
let pointerAim = null,
  aimScreen = null,
  firePointer = null;
function down(k) {
  return keys.has(k) || Array.from(hold.values()).includes(k);
}
function clearInput() {
  keys.clear();
  hold.clear();
  pointerAim = null;
  aimScreen = null;
  firePointer = null;
  document.querySelectorAll(".touch-button.hot").forEach(b => b.classList.remove("hot"));
}
const ROAD_START = -750,
  ROAD_STEP = 8;
const SURFACE = {
  gravel: {
    name: "碎石坡",
    color: "#b29369",
    grip: .61,
    heavy: .88
  },
  salt: {
    name: "盐晶层",
    color: "#c9c8a0",
    grip: .73,
    heavy: .88
  },
  ore: {
    name: "导电矿脉",
    color: "#99b5a1",
    grip: .91,
    heavy: 1.02
  }
};
function makeRoad(r) {
  const s = r.landSeed,
    rng = rnd(s ^ 0x71be3),
    rough = 1 + Math.min(.5, (r.sector - 1) * .07);
  r.bands = [];
  const features = [];
  for (let x = 505 + rng() * 140; x < r.length - 130; x += 410 + rng() * 210) {
    const width = 128 + rng() * 112,
      kinds = ["gravel", "salt", "ore"];
    r.bands.push({
      x,
      end: x + width,
      type: kinds[Math.floor(rng() * kinds.length)]
    });
    features.push({
      x: x + width * .55,
      r: 105 + rng() * 82,
      h: (rng() < .55 ? -1 : 1) * (20 + rng() * 29) * rough
    });
  }
  const n = Math.ceil((r.length + 1100 - ROAD_START) / ROAD_STEP) + 1;
  r.heights = new Float64Array(n);
  for (let i = 0; i < n; i++) {
    const x = ROAD_START + i * ROAD_STEP,
      d = clamp((x - 180) / 260, 0, 1);
    let y = 250 + d * rough * ((smooth(x / 302, s) * 2 - 1) * 57 + (smooth(x / 132, s + 9) * 2 - 1) * 19 + (smooth(x / 57, s + 19) * 2 - 1) * 5 + Math.sin(x * .006 + s % 24) * 17);
    for (const f of features) {
      const k = (x - f.x) / f.r;
      if (Math.abs(k) < 1) y += f.h * (1 - k * k) ** 2;
    }
    r.heights[i] = y;
  }
}
function ground(x) {
  const a = run.heights,
    k = clamp((x - ROAD_START) / ROAD_STEP, 0, a.length - 1.00001),
    i = Math.floor(k);
  return lerp(a[i], a[i + 1], k - i);
}
function roadAt(x) {
  for (const band of run.bands) if (x >= band.x && x <= band.end) return SURFACE[band.type];
  return null;
}
const JOBS = [{
  id: "care",
  name: "安全运送",
  goal: "过境时核心 ≥ 60%",
  met: r => r.player.core.hp >= r.player.maxCore * .6
}, {
  id: "supply",
  name: "沿途回收",
  goal: "拾取全部补给箱",
  met: r => r.packages.every(b => b.used)
}, {
  id: "cool",
  name: "热量管控",
  goal: "本段全程不过热",
  met: r => !r.jobOverheat
}, {
  id: "wheel",
  name: "轴组保全",
  goal: "至少保住两只车轮",
  met: r => r.player.wheelN >= 2
}, {
  id: "upright",
  name: "独立驾驶",
  goal: "本段不使用扶正",
  met: r => !r.jobRecovered
}];
function jobPay(r) {
  return 14 + r.sector * 3;
}
function groundSlope(x) {
  return (ground(x + 2) - ground(x - 2)) * .25;
}
function pose(p) {
  const b = p.body,
    r = rotate(p.x, p.y, b.a);
  return {
    x: b.x + r.x,
    y: b.y + r.y,
    a: b.a + p.rot,
    rx: r.x,
    ry: r.y
  };
}
function glob(b, pt) {
  const r = rotate(pt.x, pt.y, b.a);
  return {
    x: b.x + r.x,
    y: b.y + r.y,
    rx: r.x,
    ry: r.y
  };
}
function kick(b, rx, ry, jx, jy) {
  b.vx += jx * b.im;
  b.vy += jy * b.im;
  b.w += (rx * jy - ry * jx) * b.ii;
}
function countLive(v, t) {
  let n = 0;
  for (const p of v.parts) if (!p.dead && p.type === t) n++;
  return n;
}
function makeVehicle(rig, enemy, at, ai = null) {
  const src = rig.parts.map(p => ({
    ...p
  }));
  if (enemy) for (const p of src) {
    p.x = -p.x;
    p.rot = -p.rot;
    p.flip *= -1;
  }
  const root = src.find(p => p.type === "core"),
    map = new Map(src.map(p => [p.id, p]));
  const v = {
    name: rig.name,
    enemy,
    ai,
    parts: src,
    groups: [],
    joints: [],
    core: root,
    dead: false,
    energy: 0,
    heat: 0,
    overheated: false,
    hitCD: 0,
    sawCD: 0,
    recoverCD: 0,
    look: enemy ? -1 : 1,
    throttle: 0,
    fire: false,
    boost: false,
    brake: false,
    readout: "",
    grounded: 0,
    damageFlash: 0,
    shieldFlash: 0,
    travel: 0,
    maxCore: 0,
    mod: enemy ? {
      power: 1,
      dmg: 1,
      cool: 1,
      shield: 0
    } : run.mods
  };
  const st = rigStats(src, enemy ? {} : S.up),
    groups = new Map();
  function groupKey(p) {
    if (p.gid !== undefined) return p.gid;
    const a = map.get(p.parent);
    return p.gid = a ? jointType(a.type) ? a.id : groupKey(a) : 0;
  }
  let yshift = Infinity;
  for (const p of src) {
    const key = groupKey(p);
    if (!groups.has(key)) groups.set(key, []);
    groups.get(key).push(p);
    const x = at + p.x - root.x;
    const limb = wheelType(p.type) ? D[p.type].h / 2 : Math.abs(Math.cos(p.rot)) * D[p.type].h / 2 + Math.abs(Math.sin(p.rot)) * wp(p) / 2;
    yshift = Math.min(yshift, ground(x) - p.y - limb - 4);
  }
  const offset = at - root.x;
  for (const [gid, ps] of groups) {
    const mass = ps.reduce((a, p) => a + massOf(p), 0),
      cx = ps.reduce((a, p) => a + p.x * massOf(p), 0) / mass,
      cy = ps.reduce((a, p) => a + p.y * massOf(p), 0) / mass;
    const I = ps.reduce((a, p) => a + massOf(p) * (sq(p.x - cx) + sq(p.y - cy) + (sq(wp(p)) + sq(D[p.type].h)) / 12), 0);
    const b = {
      x: offset + cx,
      y: yshift + cy,
      a: 0,
      vx: 0,
      vy: 0,
      w: 0,
      mass,
      im: 1 / mass,
      ii: 1 / Math.max(500, I),
      cx,
      cy,
      gid,
      ps,
      off: false
    };
    v.groups.push(b);
    for (const p of ps) {
      p.ax = p.x;
      p.ay = p.y;
      p.x -= cx;
      p.y -= cy;
      p.body = b;
      p.max = p.type === "core" ? st.hp : D[p.type].hp;
      p.max *= enemy ? Math.min(2.35, .61 + (run.sector - 1) * .135 + (ai?.elite ? .18 : 0)) : 1;
      p.hp = p.max;
      p.cool = enemy ? .68 : 0;
      p.aim = enemy ? Math.PI : -.05;
      p.flash = 0;
      p.spin = 0;
      p.dead = false;
    }
  }
  for (const b of v.groups) if (b.gid) {
    const j = map.get(b.gid),
      a = j.body;
    v.joints.push({
      pin: j,
      a,
      b,
      pa: {
        x: j.x,
        y: j.y
      },
      pb: {
        x: j.ax - b.cx,
        y: j.ay - b.cy
      }
    });
  }
  v.root = root.body;
  v.maxCore = root.max;
  v.maxEnergy = 80 + countLive(v, "cell") * 38 + countLive(v, "tank") * 24;
  v.energy = v.maxEnergy;
  v.ordered = ordered(src);
  v.groupMap = map;
  updateDrive(v);
  return v;
}
function updateDrive(v) {
  const mass = v.parts.reduce((m, p) => m + (p.dead ? 0 : massOf(p)), 0);
  v.power = (16 + 58 * countLive(v, "motor")) * (v.enemy ? 1 : 1 + S.up.drive * .1) * v.mod.power;
  v.speed = clamp(80 + v.power / Math.max(25, mass) * 410, 38, 308);
  v.wheelN = v.parts.filter(p => !p.dead && wheelType(p.type)).length;
  v.rangedN = v.parts.filter(p => !p.dead && ranged(p.type)).length;
  v.cooling = (14 + countLive(v, "cooler") * 7 + countLive(v, "vent") * 11) * (v.enemy ? 1 : 1 + S.up.cooling * .13) * v.mod.cool;
  v.aimRate = 8.3 + countLive(v, "sensor") * 1.6;
  v.jetN = countLive(v, "boost");
  v.shield = countLive(v, "ward") * .32 + v.mod.shield;
  v.canMelee = v.parts.some(p => !p.dead && (p.type === "saw" || p.type === "ram"));
}
function remass(v) {
  for (const b of v.groups) {
    const ps = b.ps.filter(p => !p.dead);
    if (!ps.length) {
      b.off = true;
      continue;
    }
    const m = ps.reduce((a, p) => a + massOf(p), 0),
      dx = ps.reduce((a, p) => a + p.x * massOf(p), 0) / m,
      dy = ps.reduce((a, p) => a + p.y * massOf(p), 0) / m;
    const r = rotate(dx, dy, b.a);
    b.x += r.x;
    b.y += r.y;
    b.vx -= b.w * r.y;
    b.vy += b.w * r.x;
    for (const p of b.ps) {
      p.x -= dx;
      p.y -= dy;
    }
    for (const j of v.joints) {
      if (j.a === b) {
        j.pa.x -= dx;
        j.pa.y -= dy;
      }
      if (j.b === b) {
        j.pb.x -= dx;
        j.pb.y -= dy;
      }
    }
    b.mass = m;
    b.im = 1 / m;
    b.ii = 1 / Math.max(500, ps.reduce((a, p) => a + massOf(p) * (sq(p.x) + sq(p.y) + (sq(wp(p)) + sq(D[p.type].h)) / 12), 0));
  }
  updateDrive(v);
}
function tyreContact(v, b, x, y, r, part, dt) {
  const t = part.type,
    s = groundSlope(x),
    inv = 1 / Math.hypot(1, s),
    nx = s * inv,
    ny = -inv,
    pen = (y - ground(x)) * inv + r;
  if (pen <= 0) return false;
  const tx = inv,
    ty = s * inv,
    rx = x - b.x - nx * r,
    ry = y - b.y - ny * r,
    vx = b.vx - b.w * ry,
    vy = b.vy + b.w * rx,
    vn = vx * nx + vy * ny,
    vt = vx * tx + vy * ty,
    cn = rx * ny - ry * nx,
    ct = rx * ty - ry * tx,
    isWheel = wheelType(t),
    eff = 1 / (b.im + cn * cn * b.ii),
    normal = Math.max(0, (clamp(pen * (isWheel ? 18 : 23), 0, 235) - vn) * eff * (isWheel ? .52 : .46));
  if (!normal) return false;
  const impact = -vn - (isWheel ? 390 : t === "skid" ? 345 : 295);
  if (impact > 0 && (!v.landHit || impact > v.landHit.severity)) v.landHit = {
    part,
    severity: impact,
    x,
    y
  };
  kick(b, rx, ry, nx * normal, ny * normal);
  let friction,
    rate,
    desired = 0;
  if (isWheel) {
    v.grounded++;
    const patch = roadAt(x);
    friction = (t === "mud" ? 1.68 : 1.43) * (patch ? t === "mud" ? patch.heavy : patch.grip : 1);
    desired = v.speed * v.throttle;
    rate = v.brake ? 15 : Math.abs(v.throttle) > .06 ? 4 : .28;
  } else {
    friction = t === "skid" ? .13 : .64;
    rate = 5;
  }
  const tang = clamp((desired - vt) / (b.im + ct * ct * b.ii) * Math.min(1, rate * dt), -normal * friction, normal * friction);
  kick(b, rx, ry, tx * tang, ty * tang);
  return true;
}
function solvePin(j, dt) {
  const a = j.a,
    b = j.b,
    pa = glob(a, j.pa),
    pb = glob(b, j.pb),
    ex = pb.x - pa.x,
    ey = pb.y - pa.y;
  const k11 = a.im + b.im + pa.ry * pa.ry * a.ii + pb.ry * pb.ry * b.ii,
    k12 = -pa.rx * pa.ry * a.ii - pb.rx * pb.ry * b.ii,
    k22 = a.im + b.im + pa.rx * pa.rx * a.ii + pb.rx * pb.rx * b.ii,
    det = k11 * k22 - k12 * k12;
  if (det < 1e-12) return;
  const vx = b.vx - b.w * pb.ry - a.vx + a.w * pa.ry + clamp(ex * .20 / dt, -170, 170),
    vy = b.vy + b.w * pb.rx - a.vy - a.w * pa.rx + clamp(ey * .20 / dt, -170, 170),
    jx = (-k22 * vx + k12 * vy) / det,
    jy = (k12 * vx - k11 * vy) / det;
  kick(a, pa.rx, pa.ry, -jx, -jy);
  kick(b, pb.rx, pb.ry, jx, jy);
}
function pinSpring(j, dt) {
  const a = j.a,
    b = j.b,
    da = normA(b.a - a.a),
    spring = j.pin.type === "spring",
    lim = spring ? .72 : 1.60,
    ex = da - clamp(da, -lim, lim),
    wr = b.w - a.w,
    target = -ex * 20 - (spring ? da * 4.2 : 0);
  const impulse = (target - wr) / (a.ii + b.ii) * Math.min(1, dt * (Math.abs(ex) > .01 ? 24 : spring ? 10 : 1.2));
  a.w -= impulse * a.ii;
  b.w += impulse * b.ii;
}
function stepVehicle(v, dt) {
  v.landHit = null;
  v.landCD = Math.max(0, (v.landCD || 0) - dt);
  v.grounded = 0;
  v.hitCD = Math.max(0, v.hitCD - dt);
  v.sawCD = Math.max(0, v.sawCD - dt);
  v.recoverCD = Math.max(0, v.recoverCD - dt);
  v.damageFlash = Math.max(0, v.damageFlash - dt);
  v.shieldFlash = Math.max(0, v.shieldFlash - dt);
  v.heat = Math.max(0, v.heat - v.cooling * dt);
  if (v.heat < 36) v.overheated = false;
  const fieldCharge = roadAt(v.root.x) === SURFACE.ore ? 9 : 0;
  const boost = v.boost && v.energy > 2 && v.jetN > 0;
  v.energy = clamp(v.energy + (boost ? 1 : 10 + fieldCharge) * dt, 0, v.maxEnergy);
  if (boost) {
    v.energy = Math.max(0, v.energy - (25 + v.jetN * 2) * dt);
    const thrust = 195 + v.jetN * 95;
    for (const p of v.parts) {
      if (p.dead || p.type !== "boost") continue;
      const q = pose(p),
        flip = p.flip || 1,
        ca = Math.cos(q.a) * flip,
        sa = Math.sin(q.a) * flip,
        impulse = thrust * p.body.mass * dt;
      kick(p.body, q.rx, q.ry, ca * impulse, sa * impulse);
    }
  }
  for (const b of v.groups) {
    if (b.off) continue;
    b.vy += GRAV * dt;
    b.vx *= Math.exp(-.12 * dt);
    b.w *= Math.exp(-1.10 * dt);
    for (const p of b.ps) {
      if (p.dead) continue;
      const q = pose(p),
        t = p.type;
      if (wheelType(t)) {
        const hit = tyreContact(v, b, q.x, q.y, D[t].h / 2, p, dt);
        p.spin += dt * (hit ? (b.vx - b.w * q.ry) / (D[t].h / 2) : v.throttle * 4) * (p.flip || 1);
      } else if (t === "saw") {
        tyreContact(v, b, q.x, q.y, D[t].h * .46, p, dt);
        p.spin += dt * 9;
      } else {
        const co = Math.cos(q.a),
          si = Math.sin(q.a),
          ww = wp(p) * .46,
          hh = D[t].h * .46;
        for (const ex of [-ww, ww]) for (const ey of [-hh, hh]) tyreContact(v, b, q.x + ex * co - ey * si, q.y + ex * si + ey * co, 1.2, p, dt);
      }
    }
  }
  for (const j of v.joints) if (!j.pin.dead && !j.b.off && !j.a.off) pinSpring(j, dt);
  for (let i = 0; i < 4; i++) for (const j of v.joints) if (!j.pin.dead && !j.b.off && !j.a.off) solvePin(j, dt);
  for (const b of v.groups) {
    if (b.off) continue;
    b.vx = clamp(b.vx, -465, 465);
    b.vy = clamp(b.vy, -490, 600);
    b.w = clamp(b.w, -7, 7);
    b.x += b.vx * dt;
    b.y += b.vy * dt;
    b.a = normA(b.a + b.w * dt);
  }
  if (v.landHit && v.landCD === 0) {
    const hit = v.landHit;
    v.landCD = .7;
    damage(v, hit.part, clamp(hit.severity * .13, 2, 34));
    addFx(hit.x, hit.y, 4, "spark");
    sfxLanding(hit.severity, v.enemy);
    if (!v.enemy) run.shake = Math.max(run.shake, .10);
  }
  const q = pose(v.core),
    wall = clamp(q.x, -110, run.length + 225);
  if (wall !== q.x) {
    for (const b of v.groups) {
      b.x += wall - q.x;
      b.vx *= .65;
    }
  }
  v.travel = Math.max(v.travel, q.x);
  if (q.y > ground(q.x) + 180) recover(v, true);
}
function recover(v, forced = false) {
  if (!v || v.dead || !forced && v.recoverCD > 0) {
    if (v && !v.enemy && !forced) toast("扶正装置冷却中 · " + Math.ceil(v.recoverCD) + " 秒");
    return;
  }
  const x = clamp(pose(v.core).x, 0, run.length),
    root = v.core;
  let off = Infinity;
  for (const p of v.parts) if (!p.dead) {
    const px = x + p.ax - root.ax;
    off = Math.min(off, ground(px) - p.ay - D[p.type].h / 2 - 15);
  }
  for (const b of v.groups) {
    if (b.off) continue;
    const p = b.ps.find(p => !p.dead);
    b.x = x + p.ax - root.ax - p.x;
    b.y = off + p.ay - p.y;
    b.vx = b.vy = b.w = b.a = 0;
  }
  v.recoverCD = 4.5;
  if (!v.enemy) {
    if (!forced) run.jobRecovered = true;
    showBanner("已扶正 · 重新接地", 1.1);
    sfxRecover();
  }
}
function enemyDesign(sector, r, idx) {
  const forms = ["游击", "炮手", "冲锋", "机械臂", "炮塔堡垒", "剪切者", "蜂巢侦察"],
    mode = forms[Math.floor(r() * forms.length)],
    span = 52 + Math.floor(r() * 30),
    elite = sector % 4 === 0 && idx === sectorTarget(sector) - 1,
    ps = [part(1, "core", -5, -8, null), part(2, "truss", 0, 17, 1, 0, (span * 2 + 15) / 140), part(3, "motor", -span + 9, 1, 2)];
  let next = 4;
  const add = (type, x, y, parent = 2, rot = 0, len = 1, flip = 1) => ps.push(part(next++, type, x, y, parent, rot, len, flip));
  if (mode === "机械臂" || mode === "剪切者") {
    add("reactor", -span + 7, -3, 2);
    add("mud", -span, 58 - D.mud.h / 2, 2);
    add("micro", span, 57 - D.micro.h / 2, 2);
    add("bumper", span + 28, 8, 2);
    add("plate", span * .55, 2, 2, -.08);
    add("ward", -7, -42, 1);
    add("sensor", 24, -39, 1);
    add("hinge", -span - 7, 15, 2);
    add("wood", -span - 43, 12, next - 1, -.08, .92);
    add("gimbal", -span - 78, 11, next - 1, 0, 1);
    add("boost", -span - 103, 4, next - 1, Math.PI, 1, -1);
    add("saw", -span - 126, 4, next - 1, 0);
    if (mode === "剪切者") {
      add("hinge", span + 5, 16, 2);
      add("beam", span + 39, 13, next - 1, .08, .74);
      add("gimbal", span + 74, 12, next - 1);
      add("saw", span + 99, 12, next - 1);
      add("cooler", -span + 4, -25, 3);
    } else {
      add("tank", -span + 10, -28, 3);
      add("cell", span - 10, -28, 2);
    }
  } else if (mode === "炮塔堡垒") {
    add("reactor", -span + 7, -3, 2);
    add("tank", -span + 17, -27, 3);
    add("cell", span - 12, -28, 2);
    add("mud", -span, 58 - D.mud.h / 2, 2);
    add("mud", span, 58 - D.mud.h / 2, 2);
    add("bumper", span + 31, 8, 2);
    add("plate", span * .55, 2, 2, -.08);
    add("plate", -span * .52, 2, 2, .08);
    add("cannon", 4, -42, 1);
    add("arc", 30, -44, 1);
    add("ward", -24, -42, 1);
    add("cooler", -span + 3, -23, 3);
    add("vent", span - 8, -22, 2);
    add("sensor", 18, -67, 1);
    add("skid", 0, 62, 2, 0, 1.1);
  } else if (mode === "蜂巢侦察") {
    add("motor", span - 16, -3, 2);
    add("wood", -span - 7, 8, 2, 0, 1.16);
    add("spring", -30, 20, 2, 0, 1);
    add("micro", -span, 53 - D.micro.h / 2, 2);
    add("micro", -18, 53 - D.micro.h / 2, 2);
    add("micro", 18, 53 - D.micro.h / 2, 2);
    add("micro", span, 53 - D.micro.h / 2, 2);
    add("gimbal", span + 25, -4, 2);
    add("pulse", span + 54, -18, next - 1);
    add("arc", 0, -44, 1);
    add("sensor", -20, -42, 1);
    add("cell", -span + 12, -26, 2);
    add("boost", -span - 28, 2, 2, Math.PI, 1, -1);
    add("skid", 0, 61, 2, 0, .85);
  } else {
    const rear = r() < .54 ? "mud" : "wheel",
      front = r() < .5 ? "mud" : "wheel";
    add(rear, -span, 58 - D[rear].h / 2, 2);
    add(front, span, 58 - D[front].h / 2, 2);
    add("plate", span * .60, 3, 2);
    if (mode === "冲锋") {
      add("ram", span + 18, 9, next - 1);
      const saw = r() < .60;
      add(saw ? "saw" : "pulse", span + 35, 4, next - 1);
      if (saw && sector > 1) add("pulse", -2, -39, 1);
    } else {
      add(mode === "炮手" ? "arc" : "pulse", -1, -39, 1);
      if (mode === "炮手" || elite) add("cannon", 28, -39, 1);
    }
    if (r() < .55) add("wood", -span - 10, 10, 2);
    if (elite || sector > 2 && r() < .5) add(r() < .5 ? "ward" : "cooler", -span + 5, -24, 3);
    if (sector >= 3 && (elite || r() < .33)) {
      add("hinge", -span - 7, 15, 2);
      add("beam", -span - 42, 17, next - 1, 0, .82);
      add("wheel", -span - 73, 34, next - 1);
      add(elite ? "arc" : r() < .48 ? "ward" : "cooler", -span - 68, -2, next - 1);
    }
  }
  if (sector > 2 && mode !== "炮塔堡垒" && r() < .42) add("vent", -span + 30, -24, 2);
  const first = ["赤砂", "骨钉", "沙狐", "铜牙", "火绒", "灰翎", "盐锤", "锯臂", "蜂巢"],
    suffix = mode === "机械臂" ? "臂虎机" : mode === "剪切者" ? "双锯" : mode === "炮塔堡垒" ? "堡垒" : mode === "蜂巢侦察" ? "蜂群" : mode === "冲锋" ? "撞手" : mode === "炮手" ? "弧炮" : "游骑";
  return {
    rig: {
      name: first[Math.floor(r() * first.length)] + (elite ? "领车" : suffix),
      parts: ps
    },
    ai: {
      mode,
      elite,
      think: 0,
      stuck: 0,
      unstick: 0,
      temper: r(),
      aggression: .72 + r() * .52,
      rangeBias: .84 + r() * .32,
      phase: r() * TAU,
      reaction: .10 + r() * .12,
      fireBias: .68 + r() * .32,
      lastX: 0,
      dummy: false
    }
  };
}
function enemyShapeKey(design) {
  return design.rig.parts.map(p => [p.type, p.parent, Math.round(p.x), Math.round(p.y), Math.round(p.rot * 100), Math.round((p.len || 1) * 100), p.flip || 1].join(":")).join("|");
}
function uniqueEnemyDesign(sector, r, idx, registry) {
  let design = null,
    key = "";
  for (let attempt = 0; attempt < 24; attempt++) {
    const candidate = enemyDesign(sector, r, idx);
    key = enemyShapeKey(candidate);
    if (!registry.shapes.has(key)) {
      design = candidate;
      break;
    }
    design = candidate;
  }
  if (!design) design = enemyDesign(sector, r, idx);
  if (registry.shapes.has(key)) {
    const movable = design.rig.parts.find(p => p.id !== 1 && (p.type === "pulse" || p.type === "arc" || p.type === "cannon" || p.type === "ram")) || design.rig.parts[1],
      baseRot = movable?.rot || 0;
    let tweak = 0;
    do {
      if (movable) movable.rot = normA(baseRot + (((registry.shapes.size + tweak) % 11) - 5) * .03);
      key = enemyShapeKey(design);
      tweak++;
    } while (registry.shapes.has(key) && tweak < 24);
  }
  registry.shapes.add(key);
  const base = design.rig.name;
  let name = base;
  while (registry.names.has(name)) name = base + "·" + (++registry.serial);
  registry.names.add(name);
  design.rig.name = name;
  design.ai.serial = registry.serial;
  return design;
}
function sectorTarget(n) {
  return Math.min(5, 2 + Math.floor((n - 1) / 2));
}
function weaponProfile(type) {
  if (type === "arc") return {
    arc: true,
    speed: 416,
    g: 310,
    damage: 41,
    cooldown: 1.22,
    heat: 22,
    recoil: 440,
    life: 3.4
  };
  if (type === "cannon") return {
    arc: false,
    speed: 475,
    g: 24,
    damage: 34,
    cooldown: .72,
    heat: 16,
    recoil: 230,
    life: 2.2
  };
  return {
    arc: false,
    speed: 555,
    g: 18,
    damage: 18,
    cooldown: .27,
    heat: 9,
    recoil: 90,
    life: 1.85
  };
}
function solution(p, v, point, target, manual = false) {
  const q = pose(p),
    profile = weaponProfile(p.type),
    speed = profile.speed,
    g = profile.g;
  let dx = point.x - q.x,
    dy = point.y - q.y,
    t = clamp(Math.hypot(dx, dy) / speed, 0, .98);
  if (target && !manual) {
    const lead = v.enemy ? .65 + (v.ai.temper || 0) * .31 : .9;
    dx += target.root.vx * t * lead;
    dy += clamp(target.root.vy, -65, 65) * t * lead;
  }
  const dist2 = dx * dx + dy * dy,
    A = speed * speed + g * dy,
    disc = A * A - g * g * dist2;
  if (disc > 0) t = Math.sqrt(2 * dist2 / (A + Math.sqrt(disc)));else t = clamp(Math.sqrt(dist2) / speed, .05, 1.7);
  return {
    a: Math.atan2(dy - g * t * t * .5, dx),
    time: t,
    speed,
    g,
    possible: disc > 0
  };
}
function clearWeaponPath(p, v, enemy) {
  const candidate = enemy.groupMap.get(v.ai?.targetId),
    target = candidate && !candidate.dead ? candidate : enemy.core;
  const q = pose(p),
    s = solution(p, v, pose(target), enemy);
  if (!s.possible) return false;
  for (let i = 1; i < 8; i++) {
    const t = s.time * i / 8,
      x = q.x + Math.cos(s.a) * s.speed * t,
      y = q.y + Math.sin(s.a) * s.speed * t + s.g * t * t / 2;
    if (y > ground(x) - 3) return false;
  }
  return true;
}
function clearShot(v, enemy) {
  return v.parts.some(p => !p.dead && ranged(p.type) && clearWeaponPath(p, v, enemy));
}
// The sightline samples use the same height field as wheels and projectiles.
function sightBlocked(start, x, y) {
  for (let i = 1; i <= 6; i++) {
    const f = i / 7,
      px = lerp(start.x, x, f);
    if (lerp(start.y, y, f) > ground(px) - 3) return true;
  }
  return false;
}
function chooseTargetPart(enemy, target) {
  const origin = pose(enemy.core),
    ai = enemy.ai;
  if (run.sector === 1 && ai.temper < .66) return target.core;
  let best = target.core,
    bestScore = -Infinity;
  for (const p of target.parts) {
    if (p.dead) continue;
    const q = pose(p);
    if (sightBlocked(origin, q.x, q.y)) continue;
    let score = p === target.core ? 4.5 : ranged(p.type) ? ["游击", "蜂巢侦察", "炮塔堡垒", "炮手"].includes(ai.mode) ? 6 : 3.4 : wheelType(p.type) ? ["冲锋", "机械臂", "剪切者"].includes(ai.mode) ? 5.4 : 1.4 : p.type === "motor" ? 3.1 : p.type === "gimbal" || p.type === "hinge" ? 2.8 : 0;
    score += (1 - p.hp / p.max) * 2.5 + clamp((pose(target.core).y - q.y) / 80, -1, 1);
    if (score > bestScore) {
      best = p;
      bestScore = score;
    }
  }
  return best;
}
function findCover(enemy, attacker, away) {
  const p = pose(enemy.core),
    source = pose(attacker.core);
  let best = away,
    bestScore = -Infinity;
  for (const dir of [away, 0, -away]) {
    const x = clamp(p.x + dir * 128, 10, run.length + 70),
      y = ground(x) - 47;
    const score = (sightBlocked(source, x, y) ? 3.8 : 0) + clamp(Math.abs(x - source.x) / 570, 0, 1) - Math.abs(groundSlope(x)) * .56 - (dir === 0 ? .16 : 0);
    if (score > bestScore) {
      bestScore = score;
      best = dir;
    }
  }
  return best;
}
function incomingArc(v) {
  const p = pose(v.core);
  for (const s of run.shots) {
    if (s.owner.enemy || !s.arc) continue;
    for (const t of [.20, .44, .67]) {
      const x = s.x + s.vx * t,
        y = s.y + s.vy * t + s.g * t * t * .5;
      if (Math.abs(x - (p.x + v.root.vx * t)) < 69 && Math.abs(y - p.y) < 47) return x;
    }
  }
  return null;
}
function driveAI(v, dt) {
  const ai = v.ai;
  if (ai.dummy) {
    v.throttle = 0;
    v.fire = v.boost = false;
    v.readout = "试车靶";
    return;
  }
  ai.think -= dt;
  ai.unstick = Math.max(0, ai.unstick - dt);
  if (ai.think > 0) return;
  ai.think = (ai.reaction || .13) + ai.temper * .08;
  const p = pose(v.core),
    t = pose(run.player.core),
    dx = t.x - p.x,
    dir = Math.sign(dx) || v.look,
    dist = Math.abs(dx),
    clear = v.rangedN && clearShot(v, run.player),
    melee = ["冲锋", "机械臂", "剪切者"].includes(ai.mode) || !v.rangedN;
  const weave = Math.sin(run.time * (.65 + ai.temper * .8) + (ai.phase || 0)) * (melee ? .10 : .26);
  let steer = 0;
  v.look = dir;
  v.boost = false;
  v.brake = false;
  ai.targetId = chooseTargetPart(v, run.player).id;
  const preferredBase = melee ? 32 : ["炮手", "炮塔堡垒"].includes(ai.mode) ? 385 : ai.mode === "蜂巢侦察" ? 315 : 265,
    preferred = preferredBase * (ai.rangeBias || 1),
    weak = v.core.hp / v.maxCore < .32;
  if (ai.unstick > 0) {
    steer = -dir;
    v.readout = "倒车脱困";
  } else if ((v.overheated || weak && v.rangedN) && dist < preferred + 45 && p.x > 80 && p.x < run.length + 60) {
    steer = findCover(v, run.player, -dir);
    v.readout = v.overheated ? "寻找掩体" : "拉开距离";
  } else if (dist > preferred + 42 || !clear && !melee) {
    steer = clamp(dir + weave, -1, 1);
    v.readout = !clear && dist < 500 ? "寻找射界" : "接近目标";
  } else if (melee) {
    steer = clamp(dir + weave, -1, 1);
    v.readout = "冲撞";
    v.boost = dist > 60 && dist < (ai.mode === "机械臂" || ai.mode === "剪切者" ? 310 : 245) && v.energy > 24 && (ai.aggression || 1) > .82;
  } else if (dist < preferred - 70) {
    steer = clamp(-dir + weave, -1, 1);
    v.readout = "调整射距";
  } else {
    v.brake = true;
    v.readout = "架炮瞄准";
  }
  const danger = ai.temper > .32 ? incomingArc(v) : null;
  if (danger !== null && ai.unstick <= 0) {
    steer = Math.sign(p.x - danger) || -dir;
    v.boost = v.energy > 32;
    v.brake = false;
    v.readout = "规避弧光";
  }
  const slope = groundSlope(p.x + steer * 62) * steer,
    drop = ground(p.x + steer * 135) - ground(p.x);
  if (steer && slope > .38 && drop > 34 && Math.abs(v.root.vx) > 112) {
    steer *= .5;
    v.readout = "控速下坡";
  }
  if (steer && slope < -.43 && v.energy > 30 && Math.abs(v.root.vx) < 65) v.boost = true;
  if (Math.abs(steer) > .7 && Math.abs(v.root.vx) < 12) ai.stuck += ai.think;else ai.stuck = Math.max(0, ai.stuck - ai.think * .5);
  if (ai.stuck > 1.8) {
    ai.unstick = .7;
    ai.stuck = 0;
    if (Math.abs(v.root.a) > 1.15 && v.recoverCD <= 0) recover(v);
  }
  if (Math.abs(v.root.a) > 1.9 && v.recoverCD <= 0) recover(v);
  v.throttle = steer;
  const firePulse = .5 + .5 * Math.sin(run.time * (1.05 + ai.temper * .8) + (ai.phase || 0));
  v.fire = !!clear && dist < (["炮手", "炮塔堡垒"].includes(ai.mode) ? 700 : 575) && !v.overheated && (firePulse < (ai.fireBias || 1) || ai.mode === "炮塔堡垒");
}
function closestEnemy() {
  const p = pose(run.player.core);
  let best = null,
    dist = Infinity;
  for (const e of run.enemies) {
    if (e.dead) continue;
    const q = pose(e.core),
      d = Math.hypot(q.x - p.x, q.y - p.y);
    if (d < dist) {
      best = e;
      dist = d;
    }
  }
  return best;
}
function stepWeapons(v, dt) {
  if (v.dead) return;
  const target = v.enemy ? run.player : closestEnemy(),
    manual = !v.enemy && firePointer !== null && pointerAim,
    origin = pose(v.core),
    point = manual || (!target ? {
      x: origin.x + v.look * 420,
      y: origin.y - 18
    } : pose(v.enemy && target.groupMap.get(v.ai.targetId) && !target.groupMap.get(v.ai.targetId).dead ? target.groupMap.get(v.ai.targetId) : target.core));
  for (const p of v.parts) {
    if (p.dead || !ranged(p.type)) continue;
    p.cool = Math.max(0, p.cool - dt);
    p.flash = Math.max(0, p.flash - dt);
    const q = pose(p),
      s = solution(p, v, point, manual ? null : target, !!manual);
    let goal = s.a;
    if (v.enemy) goal += Math.sin(run.time * 2.15 + p.id + v.ai.temper * 17) * (.026 - v.ai.temper * .013);
    const err = normA(goal - p.aim);
    p.aim = normA(p.aim + clamp(err, -dt * (v.enemy ? 3.7 : v.aimRate), dt * (v.enemy ? 3.7 : v.aimRate)));
    if (!v.fire || v.overheated || p.cool > 0 || Math.abs(err) > (v.enemy ? .21 : .3)) continue;
    if (v.enemy && !clearWeaponPath(p, v, target)) continue;
    const profile = weaponProfile(p.type),
      arc = profile.arc,
      a = p.aim,
      ca = Math.cos(a),
      sa = Math.sin(a),
      mx = q.x + ca * 26,
      my = q.y + sa * 26;
    run.shots.push({
      x: mx,
      y: my,
      px: mx,
      py: my,
      vx: ca * s.speed,
      vy: sa * s.speed,
      g: s.g,
      owner: v,
      arc,
      life: profile.life,
      damage: profile.damage * (v.enemy ? Math.min(1.32, .60 + .077 * (run.sector - 1)) : v.mod.dmg)
    });
    p.cool = profile.cooldown * (v.enemy ? 1.35 : 1);
    p.flash = .08;
    v.heat = clamp(v.heat + profile.heat, 0, 100);
    if (v.heat >= 99.9) {
      v.overheated = true;
      if (!v.enemy) run.jobOverheat = true;
      if (!v.enemy) sfxOverheat();
    }
    kick(p.body, q.rx, q.ry, -ca * profile.recoil, -sa * profile.recoil);
    addFx(mx, my, 3, "spark");
    sfxShot(arc, v.enemy ? .52 : 1);
  }
}
function segHit(p, x, y, ex, ey) {
  const q = pose(p),
    v = rotate(x - q.x, y - q.y, -q.a),
    d = rotate(ex - x, ey - y, -q.a),
    ww = wp(p) / 2 + 1.7,
    hh = D[p.type].h / 2 + 1.7;
  if (wheelType(p.type) || p.type === "saw" || p.type === "hinge") {
    const a = d.x * d.x + d.y * d.y,
      b = 2 * (v.x * d.x + v.y * d.y),
      k = v.x * v.x + v.y * v.y - ww * ww;
    if (k <= 0) return 0;
    const disc = b * b - 4 * a * k;
    if (disc < 0 || a < 1e-10) return Infinity;
    const t = (-b - Math.sqrt(disc)) / (2 * a);
    return t >= 0 && t <= 1 ? t : Infinity;
  }
  let t0 = 0,
    t1 = 1;
  for (const [start, delta, half] of [[v.x, d.x, ww], [v.y, d.y, hh]]) {
    if (Math.abs(delta) < 1e-8) {
      if (Math.abs(start) > half) return Infinity;
      continue;
    }
    let a = (-half - start) / delta,
      b = (half - start) / delta;
    if (a > b) [a, b] = [b, a];
    t0 = Math.max(t0, a);
    t1 = Math.min(t1, b);
    if (t0 > t1) return Infinity;
  }
  return t0;
}
function addFx(x, y, n, kind, col = null) {
  const fr = run.visual;
  for (let i = 0; i < n; i++) {
    if (run.fx.length >= 180) run.fx.shift();
    const s = kind === "smoke",
      life = s ? .45 + fr() * .4 : .18 + fr() * .35;
    run.fx.push({
      x,
      y,
      vx: (fr() - .5) * (s ? 33 : 155),
      vy: (s ? -19 : -44) - fr() * (s ? 35 : 90),
      life,
      max: life,
      size: s ? 5 + fr() * 5 : 1.2 + fr() * 2.4,
      kind,
      col: col || (s ? "#5c584a" : fr() < .5 ? "#f9cb69" : "#b58e59")
    });
  }
}
function shed(v, p) {
  const q = pose(p);
  if (run.debris.length >= 42) run.debris.shift();
  run.debris.push({
    part: {
      ...part(p.id, p.type, 0, 0, null, p.rot, p.len, p.flip)
    },
    x: q.x,
    y: q.y,
    a: p.body.a,
    vx: p.body.vx + (run.visual() - .5) * 58,
    vy: p.body.vy - 40 - run.visual() * 38,
    w: (run.visual() - .5) * 5,
    life: 2.2,
    team: v.enemy
  });
  addFx(q.x, q.y, 4, "spark");
}
function award(coins) {
  if (run.trial) return;
  run.earned += coins;
  S.bank += coins;
  persist();
  if (coins > 0 && audioThrottle("reward", .16)) sfxReward();
}
function damage(v, p, amount) {
  if (v.dead || p.dead || amount <= 0) return;
  if (!v.enemy) sfxDamage();
  const absorb = Math.min(v.energy * .9, amount * clamp(v.shield, 0, .68));
  v.energy -= absorb / .9;
  amount -= absorb;
  if (absorb > 0) v.shieldFlash = .12;
  v.damageFlash = .11;
  p.hp -= amount;
  if (p !== v.core) v.core.hp -= amount * (p.type === "plate" ? .13 : .27);
  if (v.core.hp <= 0) {
    killVehicle(v);
    return;
  }
  if (p.hp <= 0) {
    const ids = descendants(v.parts, p.id);
    for (const q of v.parts) if (!q.dead && ids.has(q.id)) {
      shed(v, q);
      q.dead = true;
    }
    remass(v);
  }
}
function killVehicle(v) {
  if (v.dead) return;
  v.dead = true;
  const q = pose(v.core);
  for (const p of v.parts) if (!p.dead) shed(v, p);
  addFx(q.x, q.y, 22, "spark");
  addFx(q.x, q.y, 10, "smoke");
  run.shake = Math.max(run.shake, .43);
  sfxExplosion(v.enemy ? .9 : 1.25);
  if (v.enemy) {
    run.legKills++;
    run.kills++;
    if (!run.trial) {
      const n = 10 + run.sector * 2;
      award(n);
      showBanner("击破 " + v.name + "  ·  +" + n + " 齿币", 1.7);
    } else {
      run.respawn = 2.8;
      showBanner("命中靶车 · 即将更换", 1.5);
    }
  } else {
    run.pending = "lost";
    sfxFailure();
  }
}
function explode(x, y, shot, direct = null) {
  addFx(x, y, shot.arc ? 16 : 5, "spark");
  sfxImpact(shot.arc, !!(shot.owner.enemy && direct));
  if (!shot.arc) return;
  addFx(x, y, 6, "smoke");
  run.shake = Math.max(run.shake, .13);
  const targets = shot.owner.enemy ? [run.player] : run.enemies;
  for (const v of targets) {
    if (v.dead) continue;
    let hit = null,
      dist = Infinity;
    for (const p of v.parts) if (!p.dead && p !== direct) {
      const q = pose(p),
        d = Math.max(0, Math.hypot(q.x - x, q.y - y) - Math.max(wp(p), D[p.type].h) * .32);
      if (d < dist) {
        hit = p;
        dist = d;
      }
    }
    if (hit && dist < 77) damage(v, hit, shot.damage * .65 * (1 - dist / 85));
  }
}
function simShots(dt) {
  for (let i = run.shots.length - 1; i >= 0; i--) {
    const s = run.shots[i];
    s.life -= dt;
    let ex = s.x + s.vx * dt,
      ey = s.y + s.vy * dt + s.g * dt * dt / 2;
    s.vy += s.g * dt;
    let best = Infinity,
      victim = null,
      hit = null;
    const vehicles = s.owner.enemy ? [run.player] : run.enemies;
    for (const v of vehicles) {
      if (v.dead) continue;
      for (const p of v.parts) {
        if (p.dead) continue;
        const t = segHit(p, s.x, s.y, ex, ey);
        if (t < best) {
          best = t;
          victim = v;
          hit = p;
        }
      }
    }
    if (ey >= ground(ex)) {
      let lo = 0,
        hi = 1;
      for (let k = 0; k < 6; k++) {
        const mid = (lo + hi) / 2,
          xx = lerp(s.x, ex, mid);
        if (lerp(s.y, ey, mid) > ground(xx)) hi = mid;else lo = mid;
      }
      if (hi < best) {
        best = hi;
        hit = victim = null;
      }
    }
    if (best <= 1) {
      const x = lerp(s.x, ex, best),
        y = lerp(s.y, ey, best);
      if (hit) {
        damage(victim, hit, s.damage);
        const b = hit.body;
        kick(b, x - b.x, y - b.y, s.vx * (s.arc ? 1.2 : .45), s.vy * .45);
      }
      explode(x, y, s, hit);
      run.shots.splice(i, 1);
    } else if (s.life <= 0) run.shots.splice(i, 1);else {
      s.px = s.x;
      s.py = s.y;
      s.x = ex;
      s.y = ey;
    }
  }
}
function manifold(p, a, q, b) {
  const round = t => wheelType(t) || t === "saw" || t === "hinge",
    dx = b.x - a.x,
    dy = b.y - a.y;
  if (Math.abs(dx) > (wp(p) + D[p.type].h + wp(q) + D[q.type].h) * .5 + 1 || Math.abs(dy) > 135) return null;
  const angles = [a.a, a.a + Math.PI / 2, b.a, b.a + Math.PI / 2, Math.atan2(dy, dx)];
  function span(p, ang, axis) {
    return round(p.type) ? wp(p) / 2 : Math.abs(Math.cos(axis - ang)) * wp(p) / 2 + Math.abs(Math.sin(axis - ang)) * D[p.type].h / 2;
  }
  let dep = Infinity,
    nx = 1,
    ny = 0;
  for (const ang of angles) {
    const xx = Math.cos(ang),
      yy = Math.sin(ang),
      dot = dx * xx + dy * yy,
      over = span(p, a.a, ang) + span(q, b.a, ang) - Math.abs(dot);
    if (over <= 0) return null;
    if (over < dep) {
      dep = over;
      nx = xx * (dot >= 0 ? 1 : -1);
      ny = yy * (dot >= 0 ? 1 : -1);
    }
  }
  return {
    dep,
    nx,
    ny
  };
}
function collide(u, v) {
  if (u.dead || v.dead) return;
  const uc = pose(u.core),
    vc = pose(v.core);
  if (Math.abs(uc.x - vc.x) > u.extent + v.extent + 40) return;
  let best = null,
    sawU = null,
    sawV = null;
  for (const p of u.parts) {
    if (p.dead) continue;
    const a = pose(p);
    for (const q of v.parts) {
      if (q.dead) continue;
      const b = pose(q),
        m = manifold(p, a, q, b);
      if (!m) continue;
      const c = {
        ...m,
        p,
        q,
        x: (a.x + b.x) / 2,
        y: (a.y + b.y) / 2
      };
      if (p.type === "saw") sawU = c;
      if (q.type === "saw") sawV = c;
      if (!best || m.dep > best.dep) best = c;
    }
  }
  if (!best) return;
  const {
      p,
      q,
      nx,
      ny,
      x,
      y,
      dep
    } = best,
    a = p.body,
    b = q.body,
    ax = x - a.x,
    ay = y - a.y,
    bx = x - b.x,
    by = y - b.y,
    vx = b.vx - b.w * by - a.vx + a.w * ay,
    vy = b.vy + b.w * bx - a.vy - a.w * ax,
    spd = -(vx * nx + vy * ny),
    ca = ax * ny - ay * nx,
    cb = bx * ny - by * nx,
    J = Math.max(0, (spd * 1.05 + Math.min(40, dep * 3)) / (a.im + b.im + ca * ca * a.ii + cb * cb * b.ii));
  kick(a, ax, ay, -nx * J, -ny * J);
  kick(b, bx, by, nx * J, ny * J);
  const corr = Math.min(4, Math.max(0, dep - 1.2) * .29) / (a.im + b.im);
  a.x -= nx * corr * a.im;
  a.y -= ny * corr * a.im;
  b.x += nx * corr * b.im;
  b.y += ny * corr * b.im;
  if (sawU && u.sawCD <= 0) {
    damage(v, sawU.q, 15 * u.mod.dmg);
    u.sawCD = .24;
    addFx(sawU.x, sawU.y, 4, "spark");
  }
  if (!v.dead && sawV && v.sawCD <= 0) {
    damage(u, sawV.p, 12 * v.mod.dmg);
    v.sawCD = .28;
    addFx(sawV.x, sawV.y, 4, "spark");
  }
  if (spd > 33 && u.hitCD <= 0 && v.hitCD <= 0 && !u.dead && !v.dead) {
    u.hitCD = v.hitCD = .55;
    damage(v, q, clamp(spd * .18, 5, 44) * (p.type === "ram" ? 1.85 : 1) * u.mod.dmg);
    damage(u, p, clamp(spd * .13, 4, 34) * (q.type === "ram" ? 1.85 : 1) * v.mod.dmg);
    addFx(x, y, 8, "spark");
    run.shake = Math.max(run.shake, .12);
  }
}

// 种子地图、出征流程、画面与奖励
function createRun(trial = false, seed = null) {
  if (connectivity().missing.length) {
    E.links = true;
    updateTools();
    toast("请先把红框零件拖到车体旁,或将它拆除");
    return;
  }
  closeModal(true);
  clearInput();
  resetTool();
  scene = "battle";
  const fallback = () => Math.floor(Math.random() * 4294967296);
  let fresh;
  try {
    fresh = crypto.getRandomValues(new Uint32Array(1))[0];
  } catch {
    fresh = fallback();
  }
  run = {
    trial,
    seed: (seed ?? fresh) >>> 0,
    sector: 1,
    kills: 0,
    earned: 0,
    totalTime: 0,
    cleared: 0,
    recorded: false,
    mods: {
      power: 1,
      dmg: 1,
      cool: 1,
      shield: 0
    },
    carry: 1,
    enemyRegistry: {
      shapes: new Set(),
      names: new Set(),
      serial: 0
    },
    shake: 0
  };
  $("garage").hidden = true;
  $("battle").hidden = false;
  document.body.classList.add("in-battle");
  startLeg();
  sfxLaunch();
  audioStartBattle();
  $("field").focus({
    preventScroll: true
  });
  window.scrollTo(0, 0);
}
function startLeg() {
  const r = run;
  r.landSeed = (r.seed ^ Math.imul(r.sector, 2654435761)) >>> 0;
  r.rng = rnd(r.landSeed + 5);
  r.visual = rnd(r.landSeed + 24);
  r.bio = BIOMES[(r.sector - 1) % BIOMES.length];
  r.need = r.trial ? 1 : sectorTarget(r.sector);
  r.length = r.trial ? 1900 : 1250 + r.need * 665;
  r.legKills = 0;
  r.time = 0;
  r.pending = "";
  r.respawn = 0;
  r.shots = [];
  r.fx = [];
  r.debris = [];
  r.enemies = [];
  r.packages = [];
  r.plan = [];
  r.banner = "";
  r.bannerTime = 0;
  r.shake = 0;
  r.spawned = 0;
  makeRoad(r);
  const jobs = JOBS.filter(j => j.id !== "wheel" || S.rig.parts.filter(p => wheelType(p.type)).length >= 2);
  r.job = jobs[Math.floor(hash(r.sector, r.seed ^ 0x173) * jobs.length)];
  r.jobOverheat = false;
  r.jobRecovered = false;
  r.jobWon = false;
  for (let i = 0; i < r.need; i++) {
    const x = r.trial ? 670 : 745 + i * (r.length - 930) / Math.max(1, r.need - 1) + (r.rng() - .5) * 120;
    const design = uniqueEnemyDesign(r.sector, r.rng, i, r.enemyRegistry);
    r.plan.push({
      x,
      trigger: r.trial ? 80 : Math.max(80, x - 590),
      design
    });
  }
  if (!r.trial) {
    for (let i = 0; i < r.need; i++) r.packages.push({
      x: 435 + i * (r.length - 740) / Math.max(1, r.need - 1),
      used: false
    });
  }
  r.player = makeVehicle(S.rig, false, 65);
  r.player.extent = Math.max(...r.player.parts.map(p => Math.hypot(p.ax - r.player.core.ax, p.ay - r.player.core.ay) + wp(p) / 2));
  r.player.core.hp = r.player.maxCore * clamp(r.carry, .2, 1);
  r.camX = 105;
  r.camY = ground(65);
  r.hudAt = -5;
  $("battleTitle").textContent = r.trial ? "试车场" : "第 " + String(r.sector).padStart(2, "0") + " 段 · " + r.bio.name;
  $("seedView").textContent = "SEED " + r.seed.toString(16).toUpperCase().padStart(8, "0");
  showBanner(r.trial ? "向右试车 · 前方有可刷新的靶车" : "沿荒原向右行驶,寻找敌车", 3.6);
  if (r.sector > 1) sfxLaunch();
  clearInput();
  updateHud();
  drawBattle();
}
function spawnEnemy(plan) {
  const d = plan.design;
  if (run.trial) d.ai.dummy = true;
  const e = makeVehicle(d.rig, true, plan.x, {
    ...d.ai
  });
  e.extent = Math.max(...e.parts.map(p => Math.hypot(p.ax - e.core.ax, p.ay - e.core.ay) + wp(p) / 2));
  run.enemies.push(e);
  if (!run.trial) {
    showBanner("前方接敌 · " + e.name, 1.7);
    sfxAlert();
  }
}
function showBanner(msg, dur = 2) {
  if (!run) return;
  run.banner = msg;
  run.bannerTime = dur;
  $("banner").textContent = msg;
  $("banner").hidden = false;
}
function frameWorld(dt) {
  const r = run,
    pl = r.player;
  if (firePointer !== null && aimScreen) resolvePointerAim();
  r.time += dt;
  r.totalTime += dt;
  r.bannerTime = Math.max(0, r.bannerTime - dt);
  r.shake = Math.max(0, r.shake - dt * 1.5);
  pl.throttle = (down("right") ? 1 : 0) - (down("left") ? 1 : 0);
  pl.brake = down("brake");
  if (pl.brake) pl.throttle = 0;
  if (pl.throttle) pl.look = Math.sign(pl.throttle);
  pl.fire = down("fire") || firePointer !== null;
  pl.boost = down("boost");
  const before = pose(pl.core);
  while (r.spawned < r.plan.length && Math.max(pl.travel, before.x) >= r.plan[r.spawned].trigger) {
    spawnEnemy(r.plan[r.spawned]);
    r.spawned++;
  }
  if (r.trial && r.respawn > 0) {
    r.respawn -= dt;
    if (r.respawn <= 0) {
      r.enemies = r.enemies.filter(e => !e.dead);
      spawnEnemy({
        x: clamp(before.x + 355, 440, r.length - 90),
        design: uniqueEnemyDesign(r.sector, r.rng, r.kills + r.spawned, r.enemyRegistry)
      });
    }
  }
  stepVehicle(pl, dt);
  stepWeapons(pl, dt);
  for (const e of r.enemies) if (!e.dead) {
    driveAI(e, dt);
    stepVehicle(e, dt);
    stepWeapons(e, dt);
    collide(pl, e);
  }
  for (let i = 0; i < r.enemies.length; i++) for (let j = i + 1; j < r.enemies.length; j++) if (!r.enemies[i].dead && !r.enemies[j].dead) {
    /* Allies yield to the vehicle ahead. */const a = r.enemies[i],
      b = r.enemies[j],
      ax = pose(a.core).x,
      bx = pose(b.core).x;
    if (Math.abs(ax - bx) < 128 && Math.abs(ax - bx) > 8) {
      const k = Math.sign(ax - bx) * 42 * dt;
      a.root.vx += k;
      b.root.vx -= k;
    }
  }
  simShots(dt);
  const p = pose(pl.core);
  for (const pack of r.packages) if (!pack.used && !pl.dead && Math.abs(p.x - pack.x) < 76 && Math.abs(p.y - ground(pack.x)) < 145) {
    pack.used = true;
    pl.core.hp = Math.min(pl.maxCore, pl.core.hp + 18);
    pl.energy = Math.min(pl.maxEnergy, pl.energy + 25);
    award(5);
    showBanner("回收补给 · 核心 +18  /  齿币 +5", 1.7);
    sfxPickup();
  }
  if (!r.trial && !pl.dead && r.legKills >= r.need && p.x >= r.length - 68 && !r.pending) {
    r.pending = "gate";
    r.cleared = r.sector;
    r.jobWon = r.job.met(r);
    award(35 + 10 * r.sector + (r.jobWon ? jobPay(r) : 0));
    S.best = Math.max(S.best, r.cleared);
    persist();
    sfxGate();
  }
  if (pl.grounded && Math.abs(pl.root.vx) > 78 && r.visual() < dt * 9) addFx(p.x - pl.look * 52, ground(p.x - pl.look * 52) - 2, 1, "smoke", r.bio.top);
  if (pl.boost && pl.energy > 2 && pl.jetN > 0 && r.visual() < dt * 17) {
    for (const jet of pl.parts) {
      if (jet.dead || jet.type !== "boost") continue;
      const jq = pose(jet),
        flip = jet.flip || 1,
        ca = Math.cos(jq.a) * flip,
        sa = Math.sin(jq.a) * flip;
      addFx(jq.x - ca * 25, jq.y - sa * 25, 2, "spark", "#dfb05a");
    }
  }
  for (let i = r.fx.length - 1; i >= 0; i--) {
    const f = r.fx[i];
    f.life -= dt;
    if (f.life <= 0) {
      r.fx.splice(i, 1);
      continue;
    }
    f.x += f.vx * dt;
    f.y += f.vy * dt;
    f.vy += (f.kind === "smoke" ? -8 : 245) * dt;
  }
  for (let i = r.debris.length - 1; i >= 0; i--) {
    const d = r.debris[i];
    d.life -= dt;
    if (d.life <= 0) {
      r.debris.splice(i, 1);
      continue;
    }
    d.vy += GRAV * .8 * dt;
    d.x += d.vx * dt;
    d.y += d.vy * dt;
    d.a += d.w * dt;
    const floor = ground(d.x) - D[d.part.type].h * .36;
    if (d.y > floor) {
      d.y = floor;
      d.vy = -Math.abs(d.vy) * .21;
      d.vx *= .87;
      d.w *= .82;
    }
  }
  const target = closestEnemy(),
    ex = target ? pose(target.core).x : p.x + pl.look * 135,
    focus = p.x + clamp((ex - p.x) * .23 + pl.root.vx * .16, -103, 135);
  r.camX = lerp(r.camX, focus, 1 - Math.exp(-3.6 * dt));
  r.camY = lerp(r.camY, Math.min(ground(p.x), p.y + 65), 1 - Math.exp(-3.8 * dt));
  if (r.time - r.hudAt > .12) {
    updateHud();
    r.hudAt = r.time;
  }
  if (r.pending) {
    const why = r.pending;
    r.pending = "";
    if (why === "lost") endResult(false);else gateMenu();
  }
}
function updateHud() {
  const r = run;
  if (!r) return;
  const p = r.player,
    core = Math.max(0, Math.ceil(p.core.hp)),
    pct = clamp(core / p.maxCore * 100, 0, 100),
    pos = pose(p.core),
    e = closestEnemy();
  $("coreHud").textContent = "核心  " + core + " / " + Math.round(p.maxCore);
  $("coreFill").style.width = pct + "%";
  $("coreFill").style.background = pct < 30 ? "#e58971" : "#b8d69b";
  $("energyHud").textContent = "电量  " + Math.round(p.energy) + " / " + p.maxEnergy;
  $("energyFill").style.width = p.energy / p.maxEnergy * 100 + "%";
  $("heatHud").textContent = p.overheated ? "过热 · 冷却中" : "热量  " + Math.round(p.heat) + "%";
  $("heatFill").style.width = p.heat + "%";
  $("objective").textContent = r.trial ? "靶车击破  " + r.legKills : "敌车击破  " + r.legKills + " / " + r.need;
  $("progressHud").textContent = r.trial ? "无限试车 · 可随时回车间" : "信标 " + Math.round(Math.max(0, r.length - pos.x) / 40) + " m " + (r.length >= pos.x ? "→" : "←") + "  ·  收益 " + r.earned;
  $("enemyHud").textContent = e ? (pose(e.core).x < pos.x ? "← " : "→ ") + e.name + "  " + Math.round(Math.abs(pose(e.core).x - pos.x) / 40) + " m  ·  " + (e.readout || "侦察") : r.trial ? "向右驶入靶区" : r.legKills >= r.need ? "信标已启用" : "继续前进,搜索荒原";
  $("speedRead").textContent = (Math.abs(p.root.vx) / 40 * 3.6).toFixed(1) + " km/h";
  $("contractHud").textContent = r.trial ? "" : "加约 · " + r.job.goal + "  +" + jobPay(r);
  $("banner").hidden = !r.bannerTime;
}
function fieldMatrix() {
  const cv = $("field"),
    rect = cv.getBoundingClientRect(),
    w = rect.width,
    h = rect.height,
    z = clamp(Math.min(w / 720, h / 327), .38, 1.85);
  return {
    w,
    h,
    z,
    ox: w * .47 - run.camX * z,
    oy: h * .72 - run.camY * z
  };
}
function drawGround(c, left, right, bottom, bio) {
  const pts = [],
    start = Math.floor(left / 10) * 10 - 10,
    end = right + 14;
  for (let x = start; x <= end + 10; x += 10) pts.push(x, ground(x));
  poly(c, [...pts, pts.at(-2), bottom, start, bottom], bio.soil, null);
  function strip(off, breadth, col, scale, seed) {
    const upper = [],
      lower = [];
    for (let i = 0; i < pts.length; i += 2) {
      const x = pts[i],
        y = pts[i + 1] + off + (smooth(x / scale, seed) - .5) * breadth;
      upper.push(x, y);
      lower.unshift(x, y + breadth * (.45 + smooth(x / (scale * 1.2), seed + 1)));
    }
    poly(c, [...upper, ...lower], col, null);
  }
  strip(29, 8, bio.deep, 98, 17);
  strip(59, 18, bio.deep, 142, 9);
  strip(112, 26, bio.deep, 217, 19);
  strip(15, 3, bio.top, 64, 3);
  strip(83, 4, bio.top, 126, 4);
  const surface = [];
  for (let i = pts.length - 2; i >= 0; i -= 2) surface.push(pts[i], pts[i + 1] + 4 + hash(Math.round(pts[i] / 10), run.landSeed) * 3);
  poly(c, [...pts, ...surface], bio.top, null);
  line(c, pts, bio.rock, 1.6);
  for (let i = Math.floor(left / 28) - 1; i < right / 28 + 1; i++) {
    const r = hash(i, run.landSeed + 46),
      x = i * 28 + 15 * r,
      y = ground(x);
    if (r > .62) {
      const s = 1.2 + r * 2;
      poly(c, [x - s * 2, y, x - s, y - s, x + s * .5, y - s * 1.2, x + s * 1.6, y], bio.grass, bio.rock, .55);
    } else if (r < .18) {
      line(c, [x - 4, y - 3, x, y + 1, x - 1, y - 7], bio.grass, 1);
      line(c, [x, y, x + 4, y - 5], bio.grass, .8);
    }
    const yy = y + 11 + hash(i, 43) * 54;
    line(c, [x + 5, yy, x + 9 + r * 5, yy - 1], bio.deep, 1.25);
  }
}
function drawGate(c, x, y, open) {
  c.save();
  c.translate(x, y);
  poly(c, [-18, 0, -12, -7, 10, -7, 18, 0], STEEL, INK, 1.5);
  rect(c, -5, -88, 9, 82, "#92917a", INK, 1.8);
  for (let i = 0; i < 5; i++) poly(c, [-4, -13 - i * 12, 3, -18 - i * 12, 3, -14 - i * 12, -4, -9 - i * 12], DARK, null);
  poly(c, [-5, -84, 22, -84, 29, -76, 22, -68, -5, -68], open ? "#c5c878" : "#cf9759", INK, 1.6);
  line(c, [5, -76, 20, -76, 15, -80], INK, 1.6);
  circ(c, -1, -91, 4, open ? "#b9f1b2" : "#e2a077", INK, 1.4);
  c.restore();
}
function drawPack(c, x, y, t) {
  c.save();
  c.translate(x, y);
  poly(c, [-13, -17, 10, -17, 15, -13, 15, -1, -14, -1], HONEY, INK, 1.3);
  rect(c, -14, -15, 29, 3, "#ad7846", INK, .7);
  rect(c, -8, -16, 3, 15, STEEL, INK, .7);
  rect(c, 6, -16, 3, 15, STEEL, INK, .7);
  line(c, [-1, -10, -1, -5, -4, -5, 3, -5], "#444d38", 1.2);
  const a = Math.sin(t * 3) * 1.6;
  line(c, [-4, -25 + a, 0, -22 + a, 4, -25 + a], "#705232", 1.5);
  c.restore();
}
function drawVehicle(c, v) {
  if (v.dead) return;
  const cp = pose(v.core);
  c.save();
  c.globalAlpha = .19;
  const shadowY = ground(cp.x) + 1;
  c.fillStyle = "#362d28";
  c.beginPath();
  c.ellipse(cp.x, shadowY, clamp(v.extent * .72, 37, 95), 4, groundSlope(cp.x), 0, TAU);
  c.fill();
  c.restore();
  let top = Infinity;
  for (const p of v.ordered) {
    if (p.dead) continue;
    const b = p.body,
      q = pose(p),
      d = D[p.type],
      a = normA(p.aim - q.a),
      aimPart = Math.atan2(Math.sin(a), Math.cos(a) * p.flip);
    top = Math.min(top, q.y - (Math.abs(Math.cos(q.a)) * d.h + Math.abs(Math.sin(q.a)) * wp(p)) / 2);
    c.save();
    c.translate(b.x, b.y);
    c.rotate(b.a);
    drawPart(c, p, {
      team: v.enemy,
      spin: p.spin,
      aimPart,
      damage: 1 - p.hp / p.max,
      active: v.boost && v.energy > 2 && v.jetN > 0,
      flash: p.flash > 0
    });
    c.restore();
  }
  if (v.shieldFlash > 0) {
    c.save();
    c.globalAlpha = v.shieldFlash * 2.5;
    circ(c, cp.x, cp.y, 57, "#a9f5da", "#b5ffe5", 2);
    c.restore();
  }
  if (v.enemy) {
    const label = v.name + " · " + (v.readout || "侦察");
    c.font = "600 9px " + CJK;
    const ww = Math.max(66, c.measureText(label).width + 12);
    rect(c, cp.x - ww / 2, top - 27, ww, 18, "#322f29e8", "#b69374", .7);
    txt(c, label, cp.x, top - 15, 9, "#ffe2b4", "center", CJK, "600");
    rect(c, cp.x - ww / 2, top - 9, ww, 2.5, "#564139");
    rect(c, cp.x - ww / 2, top - 9, ww * clamp(v.core.hp / v.maxCore, 0, 1), 2.5, "#e58f66");
  }
}
function drawBattle() {
  if (scene !== "battle" || !run) return;
  const cv = $("field"),
    {
      c,
      w,
      h
    } = fitCanvas(cv),
    r = run,
    m = fieldMatrix(),
    z = m.z,
    t = r.time;
  landscape(c, w, h, r.camX * z, r.landSeed, r.bio, false, t);
  const kickY = r.shake > 0 ? Math.sin(t * 78) * r.shake * 4 : 0,
    ox = m.ox,
    oy = m.oy + kickY,
    left = -ox / z - 22,
    right = (w - ox) / z + 22,
    bottom = (h - oy) / z + 4;
  c.save();
  c.translate(ox, oy);
  c.scale(z, z);
  for (let i = Math.floor(left / 376) - 1; i <= Math.ceil(right / 376); i++) {
    const x = i * 376 + hash(i, r.landSeed + 90) * 155;
    const yy = ground(x);
    if (hash(i, 8) > .40) {
      c.save();
      c.globalAlpha = .75;
      derrick(c, x, yy, .52 + hash(i, 9) * .7, r.bio.near);
      c.restore();
    } else {
      line(c, [x, yy, x + 3, yy - 29], r.bio.near, 2);
      line(c, [x + 3, yy - 25, x + 13, yy - 22], r.bio.near, 1);
    }
  }
  drawGround(c, left, right, bottom, r.bio);
  for (const band of r.bands) {
    if (band.x > right || band.end < left) continue;
    const surf = SURFACE[band.type];
    for (let x = band.x; x < band.end; x += 8) {
      const k = hash(Math.round(x), r.landSeed),
        y = ground(x);
      line(c, [x, y + 1.2, x + 3 + k * 2, ground(x + 4) + 1.4], surf.color, 1.6);
      if (k > .68) poly(c, [x, y + 1, x + 1.5, y - (band.type === "gravel" ? 1.4 : 3.4), x + 3.6, y + 1], surf.color, r.bio.grass, .5);
    }
    if (band.x > left - 36 && band.x < right + 25) {
      const y = ground(band.x);
      line(c, [band.x, y, band.x - 1, y - 18], r.bio.rock, 1.2);
      rect(c, band.x - 14, y - 25, 28, 10, "#4b5041", r.bio.rock, .7);
      txt(c, surf.name, band.x, y - 18, 6.5, "#eee2b5", "center", CJK);
    }
  }
  if (!r.trial && r.length > left - 70 && r.length < right + 70) drawGate(c, r.length, ground(r.length), r.legKills >= r.need);
  for (const pack of r.packages) if (!pack.used && pack.x > left - 35 && pack.x < right + 35) drawPack(c, pack.x, ground(pack.x), t);
  for (const d of r.debris) {
    c.save();
    c.globalAlpha = clamp(d.life * 1.6, 0, .85);
    c.translate(d.x, d.y);
    c.rotate(d.a);
    drawPart(c, d.part, {
      team: d.team
    });
    c.restore();
  }
  for (const e of r.enemies) drawVehicle(c, e);
  drawVehicle(c, r.player);
  for (const s of r.shots) {
    const col = s.owner.enemy ? "#ff9c6e" : "#94e5d9";
    line(c, [s.x - s.vx * .027, s.y - s.vy * .027, s.x, s.y], s.owner.enemy ? "#884f40" : "#447b70", s.arc ? 4 : 3.2);
    line(c, [s.x - s.vx * .024, s.y - s.vy * .024, s.x, s.y], col, s.arc ? 2.8 : 1.65);
    circ(c, s.x, s.y, s.arc ? 4.7 : 2.5, s.arc ? "#ffe293" : "#fff1cf", s.owner.enemy ? "#b66147" : "#6d907c", .9);
  }
  for (const f of r.fx) {
    c.save();
    const k = f.life / f.max;
    c.globalAlpha = (f.kind === "smoke" ? .4 : .95) * k;
    if (f.kind === "smoke") circ(c, f.x, f.y, f.size * (1.5 - k * .5), f.col);else line(c, [f.x - f.vx * .016, f.y - f.vy * .016, f.x, f.y], f.col, f.size);
    c.restore();
  }
  if (pointerAim && firePointer !== null) {
    const {
      x,
      y
    } = pointerAim;
    circ(c, x, y, 6, null, "#f8e3aa", 1 / z);
    line(c, [x - 10, y, x - 4, y], "#f8e3aa", 1 / z);
    line(c, [x + 4, y, x + 10, y], "#f8e3aa", 1 / z);
  }
  c.restore();
  grain(c, 0, 0, w, h, .027);
  if (r.player.damageFlash > 0) {
    c.save();
    c.globalAlpha = r.player.damageFlash * .48;
    rect(c, 0, 0, w, h, "#ef7d51");
    c.restore();
  }
}
const PERKS = [{
  id: "dmg",
  name: "过载电容",
  text: "本次远征的武器与撞击伤害提高 22%。",
  icon: "target"
}, {
  id: "power",
  name: "高扭矩齿轮",
  text: "本次远征的驱动功率提高 25%。",
  icon: "tune"
}, {
  id: "cool",
  name: "导热鳍片",
  text: "本次远征的散热速度提高 30%。",
  icon: "sliders"
}, {
  id: "shield",
  name: "磁偏护层",
  text: "用电量再吸收 12% 的来袭伤害。",
  icon: "shield"
}, {
  id: "heal",
  name: "野战大修",
  text: "将核心完全修复,再驶入下一地段。",
  icon: "repair"
}];
function gateMenu() {
  const r = run,
    prng = rnd(r.landSeed ^ 9191),
    pool = [...PERKS];
  for (let i = pool.length - 1; i > 0; i--) {
    const j = Math.floor(prng() * (i + 1));
    [pool[i], pool[j]] = [pool[j], pool[i]];
  }
  r.offers = pool.slice(0, 3);
  r.carry = clamp(r.player.core.hp / r.player.maxCore + .14, .2, 1);
  const next = BIOMES[r.sector % BIOMES.length];
  showModal("第 " + r.sector + " 段已通关", '<p>过境报酬 ' + (35 + r.sector * 10) + ' 齿币。' + (r.jobWon ? "已完成「" + r.job.name + "」,另得 " + jobPay(r) + " 齿币。" : "加约「" + r.job.name + "」未完成。") + '补给站将补齐掉落的零件,修复 14% 核心耐久。选一项改装,驶向' + next.name + '。</p><div class="perks">' + r.offers.map(p => '<button class="perk" data-perk="' + p.id + '">' + iconMarkup(p.icon) + '<h3>' + p.name + '</h3><p>' + p.text + '</p></button>').join("") + '</div><div class="actions"><button class="btn" data-act="cashout">结算回车间</button></div>', "gate", true, true);
}
function pickPerk(id) {
  const r = run;
  if (modalKind !== "gate" || !r.offers.some(p => p.id === id)) return;
  if (id === "dmg") r.mods.dmg *= 1.22;
  if (id === "power") r.mods.power *= 1.25;
  if (id === "cool") r.mods.cool *= 1.3;
  if (id === "shield") r.mods.shield = Math.min(.6, r.mods.shield + .12);
  if (id === "heal") r.carry = 1;
  sfxUi("positive");
  r.sector++;
  closeModal(true);
  startLeg();
}
function logRun(result) {
  const r = run;
  if (!r || r.trial || r.recorded) return;
  r.recorded = true;
  S.records.unshift({
    seed: r.seed,
    sector: r.sector,
    cleared: r.cleared,
    kills: r.kills,
    coins: r.earned,
    time: Math.round(r.totalTime),
    name: S.rig.name,
    result
  });
  S.records = S.records.slice(0, 20);
  S.best = Math.max(S.best, r.cleared);
  persist();
}
function endResult(retired) {
  const r = run;
  audioStopBattle();
  if (r.trial) {
    showModal("试车结束", '<p>核心已耗尽。回车间调整蓝图,或重置本次试车。</p><div class="actions"><button class="btn primary" data-act="home">回车间</button><button class="btn" data-act="repeatTest">重新试车</button></div>', "result", false, true);
    return;
  }
  const label = retired ? "主动撤回" : "核心损毁";
  logRun(label);
  showModal(retired ? "远征已结算" : "战车失去动力", '<p>' + esc(S.rig.name) + ' · ' + label + ' · 第 ' + r.sector + ' 段 ' + r.bio.name + '</p><div class="result-grid"><div><b class="result-num">' + r.cleared + '</b><small>已过地段</small></div><div><b class="result-num">' + r.kills + '</b><small>击破敌车</small></div><div><b class="result-num">' + r.earned + '</b><small>已入账齿币</small></div></div><p>地形种子 <span class="mono">' + r.seed.toString(16).toUpperCase().padStart(8, "0") + '</span></p><div class="actions"><button class="btn primary" data-act="home">返回车间</button><button class="btn" data-act="replay">同种子再战</button></div>', "result", false, true);
}
function goHome() {
  audioStopBattle();
  closeModal(true);
  clearInput();
  run = null;
  scene = "garage";
  $("battle").hidden = true;
  $("garage").hidden = false;
  document.body.classList.remove("in-battle");
  refreshEditor(false);
  fitEditor();
  paintSide();
  paintRack();
  window.scrollTo(0, 0);
}
function requestLeave() {
  if (scene !== "battle") return;
  if (run.trial) {
    goHome();
    return;
  }
  showModal("返回装配车间?", '<p>本次远征将在这里结算,已取得的 ' + run.earned + ' 齿币已入账。当前蓝图可继续改装。</p><div class="actions"><button class="btn primary" data-act="close">继续远征</button><button class="btn" data-act="cashout">结算撤回</button></div>', "leave");
}
function resolvePointerAim() {
  const m = fieldMatrix();
  pointerAim = {
    x: (aimScreen.x * m.w - m.ox) / m.z,
    y: (aimScreen.y * m.h - m.oy) / m.z
  };
}
function setPointer(ev) {
  if (scene !== "battle") return;
  const r = $("field").getBoundingClientRect();
  aimScreen = {
    x: (ev.clientX - r.left) / r.width,
    y: (ev.clientY - r.top) / r.height
  };
  resolvePointerAim();
}
function bindBattle() {
  const cv = $("field");
  cv.addEventListener("contextmenu", e => e.preventDefault());
  cv.addEventListener("pointerdown", ev => {
    if (modalKind || ev.button !== 0) return;
    cv.focus({
      preventScroll: true
    });
    firePointer = ev.pointerId;
    setPointer(ev);
    cv.setPointerCapture(ev.pointerId);
  });
  cv.addEventListener("pointermove", ev => {
    if (ev.pointerId === firePointer) setPointer(ev);
  });
  const release = ev => {
    if (firePointer === ev.pointerId) {
      firePointer = null;
      pointerAim = null;
      aimScreen = null;
    }
  };
  cv.addEventListener("pointerup", release);
  cv.addEventListener("pointercancel", release);
  for (const b of document.querySelectorAll("[data-hold]")) {
    b.addEventListener("pointerdown", ev => {
      ev.preventDefault();
      if (modalKind) return;
      b.setPointerCapture(ev.pointerId);
      hold.set(ev.pointerId, b.dataset.hold);
      b.classList.add("hot");
    });
    const stop = ev => {
      hold.delete(ev.pointerId);
      b.classList.remove("hot");
    };
    b.addEventListener("pointerup", stop);
    b.addEventListener("pointercancel", stop);
  }
}

// 车间菜单、蓝图管理、输入与游戏循环
function openNav(key) {
  const nav = document.querySelectorAll(".nav button");
  for (const b of nav) b.classList.toggle("active", b.dataset.act === key);
  paintIcons(document.querySelector(".nav"));
}
function showModal(title, html, kind, wide = false, locked = false) {
  if (!modalKind) modalLast = document.activeElement;
  modalKind = kind;
  clearInput();
  $("modalTitle").textContent = title;
  $("modalBody").innerHTML = html;
  $("dialog").classList.toggle("wide", wide);
  $("modalClose").hidden = locked;
  $("overlay").hidden = false;
  paintIcons($("dialog"));
  for (const el of $("modalBody").querySelectorAll("[data-mini]")) {
    const rig = gallerySource(el.dataset.mini);
    if (rig) miniRig(el, rig);
  }
  const target = $("modalBody").querySelector("input,button") || $("modalClose");
  target?.focus({
    preventScroll: true
  });
  sfxUi("modal");
  openNav(kind === "library" ? "library" : kind === "records" ? "records" : "garage");
}
function closeModal(force = false) {
  if (!force && (modalKind === "gate" || modalKind === "result")) return;
  const was = modalKind;
  modalKind = "";
  $("overlay").hidden = true;
  openNav("garage");
  if (was) {
    const el = scene === "battle" ? $("field") : modalLast;
    if (el?.isConnected) el.focus({
      preventScroll: true
    });
    modalLast = null;
    sfxUi("close");
  }
}
function preciseEdit() {
  const placing = E.tool === "place",
    p = pickPart(E.sel),
    type = placing ? E.place : editablePart(p) ? p.type : null;
  if (!type || !ensureEditableLayer()) return;
  const field = (id, label, v, step) => '<label class="number-label" for="' + id + '">' + label + '<input id="' + id + '" type="number" step="' + step + '" value="' + v + '"></label>';
  let html = '<p>' + D[type].name + ' · 可输入任意角度。移动或旋转母件时,其子结构会一起移动。</p><div class="number-grid">';
  html += field("exactAngle", "安装角度(度)", +(normA(placing ? E.angle : p.rot) / RAD).toFixed(3), "any");
  if (variable(type)) html += field("exactLength", "零件长度(%)", +((placing ? E.len : p.len) * 100).toFixed(2), "any");
  if (!placing) {
    html += field("exactX", "水平坐标(米)", +(p.x / 40).toFixed(4), "any");
    html += field("exactY", "垂直坐标(米,向下为正)", +(p.y / 40).toFixed(4), "any");
  }
  html += '</div><div class="actions"><button class="btn primary" data-act="applyTune">应用参数</button><button class="btn" data-act="close">取消</button></div>';
  showModal("精确装配", html, "tune");
}
function applyTune() {
  const value = id => {
      const v = $(id).value.trim();
      return v === "" ? NaN : Number(v);
    },
    placing = E.tool === "place",
    p = pickPart(E.sel),
    type = placing ? E.place : editablePart(p) ? p.type : null;
  if (!type || !ensureEditableLayer()) return;
  const angle = value("exactAngle") * RAD,
    length = variable(type) ? value("exactLength") / 100 : 1;
  if (!Number.isFinite(angle) || !Number.isFinite(length) || length < .45 || length > 2.2) {
    toast("请输入有效角度,可调件长度为 45% 至 220%");
    return;
  }
  if (placing) {
    E.angle = normA(angle);
    E.len = length;
    if (E.ghost) {
      E.ghost.rot = E.angle;
      E.ghost.len = length;
    }
    closeModal();
    updateTools();
    return;
  }
  const x = value("exactX") * 40,
    y = value("exactY") * 40;
  if (!Number.isFinite(x) || !Number.isFinite(y)) {
    toast("请输入有效的位置坐标");
    return;
  }
  const ids = sameLayerDescendants(p.id),
    turn = normA(angle - p.rot),
    origin = {
      x: p.x,
      y: p.y
    },
    moved = [];
  for (const child of S.rig.parts) if (ids.has(child.id)) {
    const d = rotate(child.x - origin.x, child.y - origin.y, turn),
      xx = x + d.x,
      yy = y + d.y;
    if (Math.max(Math.abs(xx), Math.abs(yy)) > BUILD_LIMIT) {
      toast("坐标超过图纸范围");
      return;
    }
    moved.push({
      child,
      x: xx,
      y: yy
    });
  }
  checkpoint();
  for (const item of moved) {
    item.child.x = item.x;
    item.child.y = item.y;
    item.child.rot = normA(item.child.rot + turn);
  }
  p.len = length;
  if (p.type !== "core") p.parent = mountFor(p, ids, p.parent)?.id ?? null;
  closeModal();
  editChanged();
}
function setMother(target) {
  const p = pickPart(E.sel);
  if (!p || !editablePart(p) || !target || !ensureEditableLayer()) {
    toast("请选择靠近当前零件的母件");
    return;
  }
  if (descendants(S.rig.parts, p.id).has(target.id)) {
    toast("母件不能选自身或子部件");
    return;
  }
  if (!crossLayerLink(p, target)) {
    toast("不同图层只能通过自由关节或万向铰链连接");
    return;
  }
  if (separation(p, target) > 23) {
    toast("两个零件距离太远,先把它们移近");
    return;
  }
  checkpoint();
  p.parent = target.id;
  E.tool = "select";
  editChanged();
  toast("已连接到 " + D[target.type].name);
}
function manifest() {
  const re = E.tool === "remount";
  showModal(re ? "选择新的母件" : "装配清单", '<p>' + (re ? "选择与当前部件相邻的零件。" : "点选清单中的部件,可调整被遮住的安装点。") + '</p>' + S.rig.parts.map(p => {
    const parent = pickPart(p.parent),
      s = p.type === "core" ? "连接根部" : parent ? "母件 #" + parent.id + " " + D[parent.type].name : "尚未连接";
    return '<button class="manifest-row" data-select-id="' + p.id + '"><b>#' + p.id + ' ' + D[p.type].name + '</b><span>' + s + '</span></button>';
  }).join(""), "manifest");
}
function manual() {
  showModal("车手手册", '<h3>第一辆车</h3><p>游隼已经可以出发。点击「开始远征」,向右驾驶,按住空格锁定最近的敌车。击破本段敌车后开到信标,选择补给,再进入下一段。</p><h3>自由装配</h3><p>点零件架,再点图纸安装。绿线指向它将连接的母件,红框表示仍然悬空。连续点击可重复安装。点选零件后拖动会带上它的子结构。「改接」可指定新的母件,图纸右上角清单可以选中被遮挡的零件。先选中关节,再安装邻近的横梁或轮组,就能组成独立摆臂。跨图层只能由自由关节或万向铰链连接,其它不同图层的零件不会互相碰撞。</p><div class="help-grid"><b>R / Q</b><span>每次旋转 15° / 水平镜像,可用「精调」输入任意角度</span><b>V / H / G</b><span>选择 / 平移 / 网格吸附</span><b>滚轮 / 右键拖动</b><span>缩放 / 平移图纸</span><b>Del / Ctrl+Z</b><span>拆除选中件 / 撤销;Ctrl+Y 重做</span></div><h3>荒原驾驶</h3><p>矢量喷口会沿自身安装方向产生推力,喷流从喷口后方喷出。旋转或镜像喷口,就能改变火箭推力方向。</p><div class="help-grid"><b>A D / ← →</b><span>向左、向右驾驶,S 或 ↓ 制动</span><b>空格 / 鼠标左键</b><span>锁敌开火 / 按住指向位置射击</span><b>E 或 Shift</b><span>按住消耗电量推进</span><b>R / Esc</b><span>扶正战车 / 暂停</span></div><h3>维修与成长</h3><p>碎石和盐晶地带的轻轮容易打滑,重型胎抓地更好。导电矿脉会加快充电。每段还有一份随机加约,满足右上角条件可多赚齿币。黄色补给箱可补充核心耐久和电量。重摔会伤到先着地的部件,轮胎和滑橇能缓冲落地冲击。装甲能挡住射线,零件断裂后,连接在它上面的部件会一并脱落。击破敌车和通过信标都能获得齿币,可在「战车参数」的改良按钮购买永久升级。</p><p>蓝图和记录保存在当前浏览器。蓝图库可导出设计,也可载入 JSON 蓝图。触屏可用画面下方按钮驾驶与开火。</p>', "help", true);
}
const templates = [baseRig, haulerRig, sawRig, rotorRig];
function gallerySource(key) {
  const [kind, index] = String(key).split("-");
  return kind === "t" ? templates[Number(index)]?.() : S.slots[Number(index)];
}
function galleryCard(key) {
  const v = gallerySource(key),
    st = rigStats(v.parts),
    rotorTest = key === "t-3" ? rotorClearanceReport(v) : null,
    details = v.parts.length + " 件 · " + st.mass + " kg · " + st.weapons + " 个武装" + (rotorTest ? " · 摆动最小间隙 " + Math.max(0, rotorTest.minClearance).toFixed(1) + " · 扭矩 " + Math.abs(rotorTest.torque).toFixed(1) : "");
  return '<div class="blue-card"><canvas data-mini="' + key + '" aria-hidden="true"></canvas><h3>' + esc(v.name) + '</h3><p>' + details + '</p><div class="actions"><button class="btn" data-load="' + key + '">装载蓝图</button>' + (key[0] === "s" ? '<button class="btn subtle" data-drop="' + key.slice(2) + '">删除</button>' : '') + '</div></div>';
}
function openLibrary() {
  const inGame = scene === "battle";
  if (inGame) {
    showModal("当前出征蓝图", '<p>' + esc(S.rig.name) + ' · ' + S.rig.parts.length + ' 件。返回车间后可以更改装配或装载其他蓝图。</p><div class="actions"><button class="btn primary" data-act="close">继续驾驶</button><button class="btn" data-act="leave">回车间</button></div>', "library");
    return;
  }
  showModal("蓝图库", '<p>当前设计「' + esc(S.rig.name) + '」会自动保存。把喜欢的版本另存为车位,即可随时换装。</p><div class="actions"><button class="btn primary" data-act="saveSlot">保存到新车位</button><button class="btn" data-act="export">导出 JSON</button><button class="btn" data-act="import">导入 JSON</button><button class="btn subtle" data-act="blank">从核心新建</button></div><h3>工坊原型与测试项目</h3><div class="gallery">' + templates.map((_, i) => galleryCard("t-" + i)).join("") + '</div><h3>我的车位 · ' + S.slots.length + ' / 12</h3>' + (S.slots.length ? '<div class="gallery">' + S.slots.map((_, i) => galleryCard("s-" + i)).join("") + '</div>' : '<p>保存当前设计后,它会出现在这里。</p>'), "library", true);
}
function loadRig(v) {
  const rig = validateRig(v);
  checkpoint();
  S.rig = rig;
  resetTool();
  refreshEditor();
  closeModal(true);
  fitEditor();
  sfxUi("positive");
  toast("已装载「" + rig.name + "」");
}
function exportRig() {
  const blob = new Blob([JSON.stringify({
      format: "dustline-blueprint",
      version: 1,
      ...S.rig
    }, null, 2)], {
      type: "application/json"
    }),
    url = URL.createObjectURL(blob),
    a = document.createElement("a");
  a.href = url;
  a.download = (S.rig.name.replace(/[^\p{L}\p{N}_-]+/gu, "_") || "rig") + ".json";
  document.body.appendChild(a);
  a.click();
  a.remove();
  setTimeout(() => URL.revokeObjectURL(url), 1500);
}
const UP = {
  armor: {
    name: "核心加固",
    desc: "每级增加 10% 核心耐久。"
  },
  drive: {
    name: "传动改良",
    desc: "每级增加 10% 整车功率。"
  },
  cooling: {
    name: "冷却导管",
    desc: "每级加快 13% 散热。"
  }
};
function upgradeCost(k) {
  return 35 + S.up[k] * 30;
}
function showUpgrades() {
  showModal("车间永久改良", '<p>现有 <b class="gold">' + S.bank + ' 齿币</b>。改良对以后从车间驶出的所有战车生效。</p>' + Object.entries(UP).map(([k, a]) => '<div class="upgrade"><div><h3>' + a.name + ' <small>Lv.' + S.up[k] + ' / 6</small></h3><p>' + a.desc + '</p></div><button class="btn" data-up="' + k + '" ' + (S.up[k] >= 6 || S.bank < upgradeCost(k) ? "disabled" : "") + '>' + (S.up[k] >= 6 ? "已满级" : upgradeCost(k) + " 齿币") + '</button></div>').join(""), "upgrade");
}
function showRecords() {
  showModal("远征记录", '<div class="result-grid"><div><b class="result-num">' + S.best + '</b><small>最远通关段数</small></div><div><b class="result-num">' + S.bank + '</b><small>可用齿币</small></div></div>' + (S.records.length ? S.records.map((r, i) => '<div class="record"><div><strong>' + esc(r.name || "荒原战车") + '</strong><small>通过 ' + Math.max(0, num(r.cleared)) + ' 段 · 击破 ' + Math.max(0, num(r.kills)) + ' 辆 · +' + Math.max(0, num(r.coins)) + ' 齿币 · ' + Math.floor(num(r.time) / 60) + '分' + num(r.time) % 60 + '秒</small><small class="mono">SEED ' + (r.seed >>> 0).toString(16).toUpperCase().padStart(8, "0") + '</small></div>' + (scene === "garage" ? '<button class="btn" data-seed-index="' + i + '">重跑</button>' : '') + '</div>').join("") : '<p>完成第一次远征后,这里会记录通关段数、收益和地形种子。可用新蓝图重跑同一片荒原。</p>') + (scene === "garage" ? '<div class="actions"><button class="btn" data-act="upgrades">车间改良</button></div>' : ''), "records", true);
}
function pauseGame() {
  if (scene !== "battle" || modalKind) return;
  showModal("驾驶已暂停", '<p>' + esc(S.rig.name) + ' · ' + (run.trial ? "试车场" : run.bio.name) + '</p><div class="actions"><button class="btn primary" data-act="close">继续驾驶</button><button class="btn" data-act="help">操作手册</button><button class="btn" data-act="leave">回车间</button></div>', "pause");
}
function renameRig() {
  showModal("命名蓝图", '<label for="newName">战车名称</label><input id="newName" maxlength="32" value="' + esc(S.rig.name) + '"><div class="actions"><button class="btn primary" data-act="applyName">保存名称</button><button class="btn" data-act="close">取消</button></div>', "rename");
  $("newName").select();
}
function soundIcon() {
  $("audioBtn").innerHTML = iconMarkup(S.sound ? "sound" : "mute");
  $("audioBtn").title = S.sound ? "关闭音效" : "开启音效";
  $("audioBtn").setAttribute("aria-label", $("audioBtn").title);
  paintIcons($("audioBtn"));
}
function paintSide() {
  if (scene !== "garage") return;
  const {
    c,
    w,
    h
  } = fitCanvas($("contractArt"));
  landscape(c, w, h, 0, 139, BIOMES[0], true);
}
function action(k) {
  switch (k) {
    case "garage":
      if (scene === "battle") requestLeave();else closeModal(true);
      break;
    case "library":
      openLibrary();
      break;
    case "records":
      showRecords();
      break;
    case "help":
      manual();
      break;
    case "sound":
      S.sound = !S.sound;
      persist();
      soundIcon();
      if (S.sound) sfxUi("positive");else audioStopBattle();
      toast(S.sound ? "音效已开启" : "音效已关闭");
      break;
    case "close":
      closeModal();
      break;
    case "test":
      createRun(true);
      break;
    case "launch":
      createRun(false);
      break;
    case "tunePart":
      preciseEdit();
      break;
    case "applyTune":
      applyTune();
      break;
    case "manifest":
      manifest();
      break;
    case "remount":
      if (E.sel) {
        E.tool = "remount";
        E.place = null;
        E.links = true;
        updateTools();
        toast("点击相邻部件,或从装配清单选择母件");
      }
      break;
    case "rename":
      renameRig();
      break;
    case "applyName":
      {
        const val = $("newName")?.value.trim();
        if (!val) {
          toast("请输入蓝图名称");
          break;
        }
        checkpoint();
        S.rig.name = val.slice(0, 32);
        refreshEditor();
        closeModal();
        break;
      }
    case "select":
      resetTool();
      updateTools();
      break;
    case "pan":
      resetTool();
      E.tool = "pan";
      updateTools();
      break;
    case "snap":
      E.snap = !E.snap;
      updateTools();
      break;
    case "links":
      E.links = !E.links;
      updateTools();
      break;
    case "addLayer":
      addLayer();
      break;
    case "undo":
      timeTravel(true);
      break;
    case "redo":
      timeTravel(false);
      break;
    case "zoomIn":
      doZoom(1.2);
      break;
    case "zoomOut":
      doZoom(1 / 1.2);
      break;
    case "fit":
      fitEditor();
      break;
    case "remove":
      removePart();
      break;
    case "rotate":
    case "mirror":
    case "longer":
    case "shorter":
      alter(k);
      break;
    case "copyPart":
      {
        const p = pickPart(E.sel);
        if (p && p.type !== "core") {
          choosePart(p.type);
          E.angle = p.rot;
          E.len = p.len;
          E.mirror = p.flip;
        }
        break;
      }
    case "rackPrev":
    case "rackNext":
      $("parts").scrollBy({
        left: (k === "rackNext" ? 1 : -1) * $("parts").clientWidth * .85,
        behavior: "smooth"
      });
      break;
    case "upgrades":
      showUpgrades();
      break;
    case "pause":
      pauseGame();
      break;
    case "recover":
      if (scene === "battle" && !modalKind) recover(run.player);
      break;
    case "leave":
      requestLeave();
      break;
    case "cashout":
      endResult(true);
      break;
    case "home":
      goHome();
      break;
    case "replay":
      createRun(false, run.seed);
      break;
    case "repeatTest":
      createRun(true, run.seed);
      break;
    case "saveSlot":
      if (S.slots.length >= 12) {
        toast("车位已满,可删除旧车位后再保存");
        break;
      }
      S.slots.push(copy(S.rig));
      persist();
      openLibrary();
      toast("已保存到新车位");
      break;
    case "export":
      exportRig();
      break;
    case "import":
      $("importFile").value = "";
      $("importFile").click();
      break;
    case "blank":
      loadRig({
        name: "自制底盘",
        parts: [part(1, "core", 0, 0, null)]
      });
      break;
  }
}
function bindUI() {
  document.addEventListener("click", ev => {
    const b = ev.target.closest("button");
    if (!b || b.disabled) return;
    const uiKind = b.closest(".nav") ? "nav" : b.classList.contains("part-card") ? "part" : b.classList.contains("tool") ? "tool" : "tap";
    sfxUi(uiKind);
    const d = b.dataset;
    if (d.selectId !== undefined) {
      const p = pickPart(Number(d.selectId));
      closeModal();
      if (p && p.layer !== activeLayerId()) selectLayer(p.layer);
      if (E.tool === "remount") setMother(p);else {
        resetTool();
        E.sel = p?.id ?? null;
        updateTools();
      }
      return;
    }
    if (d.act) {
      action(d.act);
      return;
    }
    if (d.cat) {
      rack(d.cat);
      return;
    }
    if (d.part) {
      choosePart(d.part);
      return;
    }
    if (d.perk) {
      pickPerk(d.perk);
      return;
    }
    if (d.load) {
      const rig = gallerySource(d.load);
      if (rig) loadRig(rig);
      return;
    }
    if (d.drop !== undefined) {
      const i = Number(d.drop);
      if (!S.slots[i]) return;
      showModal("删除这个车位?", '<p>' + esc(S.slots[i].name) + '</p><div class="actions"><button class="btn" data-act="library">保留</button><button class="btn danger" data-confirm-drop="' + i + '">删除车位</button></div>', "delete");
      return;
    }
    if (d.confirmDrop !== undefined) {
      S.slots.splice(Number(d.confirmDrop), 1);
      persist();
      openLibrary();
      return;
    }
    if (d.up && Object.hasOwn(UP, d.up)) {
      const cost = upgradeCost(d.up);
      if (S.bank >= cost && S.up[d.up] < 6) {
        S.bank -= cost;
        S.up[d.up]++;
        refreshEditor();
        showUpgrades();
        tone(360, .14, "triangle", .04, 580);
      }
      return;
    }
    if (d.seedIndex !== undefined && scene === "garage") {
      const r = S.records[Number(d.seedIndex)];
      if (r) createRun(false, r.seed);
    }
  });
  $("overlay").addEventListener("click", ev => {
    if (ev.target === $("overlay")) closeModal();
  });
  $("importFile").addEventListener("change", async () => {
    const f = $("importFile").files[0];
    if (!f) return;
    try {
      if (f.size > 180000) throw Error("蓝图文件过大。");
      const raw = JSON.parse(await f.text());
      loadRig(validateRig(raw));
    } catch (err) {
      toast("无法载入蓝图 · " + (err instanceof SyntaxError ? "JSON 格式有误" : err.message));
    }
  });
  const keyMap = {
    KeyA: "left",
    ArrowLeft: "left",
    KeyD: "right",
    ArrowRight: "right",
    KeyS: "brake",
    ArrowDown: "brake",
    Space: "fire",
    KeyE: "boost",
    ShiftLeft: "boost",
    ShiftRight: "boost"
  };
  const pressedCodes = new Set();
  document.addEventListener("keydown", ev => {
    if (modalKind) {
      if (ev.code === "Escape") {
        ev.preventDefault();
        closeModal();
        return;
      }
      if (modalKind === "rename" && ev.code === "Enter") {
        ev.preventDefault();
        action("applyName");
      }
      if (ev.key === "Tab") {
        const options = [...$("dialog").querySelectorAll("button:not(:disabled),input,summary")].filter(el => el.offsetParent !== null);
        if (!options.length) return;
        const first = options[0],
          last = options.at(-1);
        if (ev.shiftKey && document.activeElement === first) {
          ev.preventDefault();
          last.focus();
        } else if (!ev.shiftKey && document.activeElement === last) {
          ev.preventDefault();
          first.focus();
        }
      }
      return;
    }
    if (scene === "battle") {
      const k = keyMap[ev.code];
      if (k) {
        ev.preventDefault();
        pressedCodes.add(ev.code);
        keys.add(k);
      } else if (ev.code === "KeyR" && !ev.repeat) {
        ev.preventDefault();
        action("recover");
      } else if (ev.code === "Escape" || ev.code === "KeyP") {
        ev.preventDefault();
        pauseGame();
      }
      return;
    }
    if (ev.target instanceof HTMLInputElement) return;
    if (ev.ctrlKey || ev.metaKey) {
      if (ev.code === "KeyZ" || ev.code === "KeyY") {
        ev.preventDefault();
        timeTravel(ev.code === "KeyZ" && !ev.shiftKey);
      }
      return;
    }
    const acts = {
      KeyR: "rotate",
      KeyQ: "mirror",
      KeyV: "select",
      KeyH: "pan",
      KeyG: "snap",
      Delete: "remove",
      Backspace: "remove",
      Escape: "select"
    };
    if (acts[ev.code]) {
      ev.preventDefault();
      if (!ev.repeat) action(acts[ev.code]);
    }
  });
  document.addEventListener("keyup", ev => {
    const k = keyMap[ev.code];
    if (k) {
      pressedCodes.delete(ev.code);
      if (![...pressedCodes].some(code => keyMap[code] === k)) keys.delete(k);
    }
  });
  window.addEventListener("blur", () => {
    pressedCodes.clear();
    clearInput();
    if (scene === "battle" && !modalKind) pauseGame();
  });
  document.addEventListener("visibilitychange", () => {
    if (document.hidden) {
      pressedCodes.clear();
      clearInput();
      if (scene === "battle" && !modalKind) pauseGame();
    }
  });
}
let acc = 0,
  lastFrame = 0;
function frame(ts) {
  const dt = Math.max(0, Math.min(.1, (ts - (lastFrame || ts)) / 1000));
  lastFrame = ts;
  if (scene === "battle") {
    if (!modalKind) {
      acc += dt;
      for (let steps = 0; acc >= STEP && steps < 9 && !modalKind; steps++) {
        frameWorld(STEP);
        acc -= STEP;
      }
      if (modalKind) acc = 0;
      drawBattle();
    } else acc = 0;
  } else {
    acc = 0;
    drawBench();
  }
  audioUpdateBattle();
  requestAnimationFrame(frame);
}
paintIcons();
bindBench();
bindLayers();
bindBattle();
bindUI();
rack();
refreshEditor();
fitEditor();
paintSide();
soundIcon();
let oldWidth = $("bench").clientWidth,
  oldHeight = $("bench").clientHeight,
  resizeTicket = 0;
const resize = () => {
  cancelAnimationFrame(resizeTicket);
  resizeTicket = requestAnimationFrame(() => {
    if (scene === "garage") {
      if ($("bench").clientWidth !== oldWidth || $("bench").clientHeight !== oldHeight) {
        oldWidth = $("bench").clientWidth;
        oldHeight = $("bench").clientHeight;
        fitEditor();
      }
      paintRack();
      paintSide();
      benchDirty = true;
    } else drawBattle();
    if (modalKind === "library") for (const el of $("modalBody").querySelectorAll("[data-mini]")) miniRig(el, gallerySource(el.dataset.mini));
  });
};
window.addEventListener("resize", resize);
requestAnimationFrame(frame);
</script>
<script src="/Static/js/jquery.js"></script><script src="/Static/js/Global.js"></script><script src="/Web/js/Global.js"></script><script src="/Web/js/OneOpenAI.js"></script><script src="/Static/js/jquery.js"></script><script src="/Static/js/Global.js"></script><script src="/Web/js/Global.js"></script><script src="/Web/js/OneOpenAI.js"></script><script type="module" src="https://static.cloudflareinsights.com/beacon.min.js/vce701823e78c4301a35b7e07294d87301792088814092" integrity="sha512-UKNk8GbxkABxKcXYuLkO16EleLGUkcvJWtpSNmExE0Too3ZaFAxTscNWEc1OdAv5/BikHawapSCaiD2XCmp+Bw==" data-cf-beacon='{"version":"2024.11.0","token":"30828c5c269e4769af1a3a82bcc7279c","spa":2}' crossorigin="anonymous"></script>
<script src="/Static/js/jquery.js"></script><script src="/Static/js/Global.js"></script><script src="/Web/js/Global.js"></script><script src="/Web/js/OneOpenAI.js"></script></body>
</html>

Game Source: 荒辙工坊 · Dustline Motorworks

Creator: SilverScout93

Libraries: none

Complexity: complex (6301 lines, 200.8 KB)

The full source code is displayed above on this page.

Remix Instructions

To remix this game, copy the source code above and modify it. Add a ARCADELAB header at the top with "remix_of: dustline-motorworks-silverscout93" to link back to the original. Then publish at arcadelab.ai/publish.