Spaces:
Running
Running
Download index.html from gmDevi/growing-surfaces: direct link, hf CLI and curl.
- Browser
- Download file 165 kB
-
https://huggingface.co/spaces/gmDevi/growing-surfaces/resolve/main/index.html
- Command line
-
hf download hf://spaces/gmDevi/growing-surfaces/index.html
-
curl -L -o index.html https://huggingface.co/spaces/gmDevi/growing-surfaces/resolve/main/index.html
165 kB
<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover"><style>:root{color-scheme:light;padding-top:env(safe-area-inset-top,0px);padding-bottom:env(safe-area-inset-bottom,0px)}body{margin:0;font:14px system-ui,sans-serif}img{max-width:100%}[hidden]{display:none!important}</style><meta name="description" content="Eight brick-dropping games that show KPZ universality, after Martin Hairer's random Tetris. Everything runs in your browser."></head><body><title>Randomly Growing Surfaces</title>
<meta name="claude:viewport-fit-sides" content="cover">
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=IBM+Plex+Sans:wght@400;500;600&family=STIX+Two+Text:ital,wght@0,400;0,600;1,400&display=swap">
<style>
/* Layout: one left-aligned reading column on cool paper; the live figures break out to the full measure as flat plates. */
:root {
--page: #f2f4f7;
--surface: #fbfbfc;
--ink: #14171c;
--ink-2: #474c56;
--ink-3: #747a85;
--rule: #dfe2e7;
--axis: #c0c5cd;
--ground: #d3d7de;
--focus: #2a78d6;
--s1: #2a78d6; --s2: #eb6834; --s3: #1baf7a; --s4: #eda100;
--s5: #e87ba4; --s6: #008300; --s7: #6250d6; --s8: #e34948;
--font-display: "STIX Two Text", Cambria, "Times New Roman", serif;
--font-ui: "IBM Plex Sans", system-ui, -apple-system, "Segoe UI", sans-serif;
--fs-0: 0.75rem; --fs-1: 0.8125rem; --fs-2: 0.9375rem; --fs-3: 1.0625rem; --fs-4: 1.25rem; --fs-5: 1.75rem;
}
@media (prefers-color-scheme: dark) {
:root:not([data-theme="light"]) {
--page: #0c0e11; --surface: #15181d; --ink: #eceef1; --ink-2: #b7bcc4; --ink-3: #878d97;
--rule: #252930; --axis: #3b4049; --ground: #2a2f37; --focus: #6da7ec;
--s1: #3987e5; --s2: #d95926; --s3: #199e70; --s4: #c98500;
--s5: #d55181; --s6: #0ca30c; --s7: #9085e9; --s8: #e66767;
color-scheme: dark;
}
}
:root[data-theme="dark"] {
--page: #0c0e11; --surface: #15181d; --ink: #eceef1; --ink-2: #b7bcc4; --ink-3: #878d97;
--rule: #252930; --axis: #3b4049; --ground: #2a2f37; --focus: #6da7ec;
--s1: #3987e5; --s2: #d95926; --s3: #199e70; --s4: #c98500;
--s5: #d55181; --s6: #0ca30c; --s7: #9085e9; --s8: #e66767;
color-scheme: dark;
}
body {
background: var(--page);
color: var(--ink);
font: 400 var(--fs-3)/1.55 var(--font-display);
-webkit-font-smoothing: antialiased;
}
.page {
max-width: 1200px;
margin: 0 auto;
padding-left: max(16px, env(safe-area-inset-left, 0px));
padding-right: max(16px, env(safe-area-inset-right, 0px));
padding-block: 44px 80px;
display: flex;
flex-direction: column;
gap: 64px;
}
h1, h2, h3, p, figure { margin: 0; }
h1, h2 { font-family: var(--font-display); font-weight: 600; text-wrap: balance; }
a { color: inherit; text-decoration-color: var(--axis); text-underline-offset: 0.18em; }
a:hover { text-decoration-color: currentColor; }
:focus-visible { outline: 2px solid var(--focus); outline-offset: 2px; border-radius: 3px; }
.math { font-family: var(--font-display); font-style: italic; white-space: nowrap; }
.math .rm { font-style: normal; }
.ratio { font-style: italic; font-weight: 400; white-space: nowrap; letter-spacing: 0.02em; }
/* ---- masthead ---- */
.masthead { display: flex; flex-direction: column; gap: 14px; }
.eyebrow {
font: 500 var(--fs-0)/1.3 var(--font-ui);
letter-spacing: 0.09em; text-transform: uppercase; color: var(--ink-3);
}
h1 { font-size: clamp(2.4rem, 1.5rem + 4.2vw, 4.1rem); line-height: 1.02; letter-spacing: -0.012em; }
.lede { font-size: var(--fs-4); line-height: 1.45; color: var(--ink-2); max-width: 62ch; text-wrap: pretty; }
/* ---- sections ---- */
.fig { display: flex; flex-direction: column; gap: 16px; min-width: 0; }
.fig-head { display: flex; flex-direction: column; gap: 10px; max-width: 68ch; }
.fig-head h2 { font-size: var(--fs-5); line-height: 1.15; }
.fig-head p, .prose p { color: var(--ink-2); text-wrap: pretty; }
.caption { font: 400 var(--fs-1)/1.5 var(--font-ui); color: var(--ink-3); max-width: 86ch; }
.caption strong { font-weight: 500; color: var(--ink-2); }
.sr-only { position: absolute; width: 1px; height: 1px; overflow: hidden; clip-path: inset(50%); white-space: nowrap; }
/* ---- controls ---- */
.toolbar {
display: flex; flex-wrap: wrap; align-items: center; gap: 10px 22px;
font: 400 var(--fs-1)/1.2 var(--font-ui); color: var(--ink-2);
}
.toolbar .group { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; }
.toolbar .label { color: var(--ink-3); }
.btn {
font: 500 var(--fs-1)/1 var(--font-ui);
color: var(--ink); background: var(--surface);
border: 1px solid var(--axis); border-radius: 6px;
padding: 8px 12px; min-height: 34px; cursor: pointer;
}
.btn:hover { border-color: var(--ink-3); }
.btn.primary { background: var(--ink); color: var(--page); border-color: var(--ink); min-width: 74px; }
.btn.primary:hover { opacity: 0.88; }
.slider { display: inline-flex; align-items: center; gap: 8px; white-space: nowrap; }
.slider input[type="range"] { width: 132px; accent-color: var(--ink); cursor: pointer; }
.slider output { min-width: 5.2em; color: var(--ink-3); font-variant-numeric: tabular-nums; }
.chips { display: flex; flex-wrap: wrap; gap: 6px; }
.chip {
display: inline-flex; align-items: center; gap: 7px;
font: 400 var(--fs-1)/1 var(--font-ui); color: var(--ink-3);
background: transparent; border: 1px solid var(--rule); border-radius: 999px;
padding: 6px 11px 6px 9px; min-height: 30px; cursor: pointer;
}
.chip .key { opacity: 0.35; }
.chip[aria-pressed="true"] { color: var(--ink); background: var(--surface); border-color: var(--axis); }
.chip[aria-pressed="true"] .key { opacity: 1; }
.chip:hover { border-color: var(--ink-3); }
.key { display: inline-block; width: 14px; height: 4px; border-radius: 2px; background: var(--c, var(--ink-3)); flex: none; }
.key.ring { width: 8px; height: 8px; border-radius: 50%; background: transparent; border: 1.5px solid var(--ink); }
.key.dash { background: repeating-linear-gradient(90deg, var(--ink-3) 0 4px, transparent 4px 7px); }
.key.ink { background: var(--ink); height: 3px; }
.seg { display: inline-flex; border: 1px solid var(--axis); border-radius: 6px; overflow: hidden; background: var(--surface); }
.seg button {
font: 400 var(--fs-1)/1 var(--font-ui); color: var(--ink-2);
background: transparent; border: 0; border-left: 1px solid var(--rule);
padding: 8px 12px; min-height: 34px; cursor: pointer;
}
.seg button:first-child { border-left: 0; }
.seg button[aria-pressed="true"] { background: var(--ink); color: var(--page); }
.seg button .ratio { font-family: var(--font-display); font-size: 1.08em; margin-right: 5px; }
.seg button:focus-visible { outline-offset: -3px; }
/* ---- simulation panels ---- */
.panels { display: grid; gap: 18px 16px; grid-template-columns: repeat(2, minmax(0, 1fr)); }
.panels[data-count="1"] { grid-template-columns: minmax(0, 1fr); }
@media (min-width: 1000px) {
.panels[data-count="3"], .panels[data-count="5"], .panels[data-count="6"] { grid-template-columns: repeat(3, minmax(0, 1fr)); }
.panels[data-count="7"], .panels[data-count="8"] { grid-template-columns: repeat(4, minmax(0, 1fr)); }
}
@media (max-width: 640px) { .panels { grid-template-columns: minmax(0, 1fr); } }
.panel { display: flex; flex-direction: column; gap: 7px; min-width: 0; }
.panel-head { display: flex; align-items: baseline; gap: 8px; min-width: 0; }
.panel-head .key { align-self: center; }
.panel-head h3 { font: 600 var(--fs-2)/1.2 var(--font-ui); white-space: nowrap; }
.panel-head .readout {
margin-left: auto; font: 400 var(--fs-0)/1.2 var(--font-ui); color: var(--ink-3);
font-variant-numeric: tabular-nums; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; min-width: 0;
}
.stage {
position: relative; width: 100%; max-width: 100%; aspect-ratio: 2 / 1; max-height: 420px;
background: var(--surface); border: 1px solid var(--rule); border-radius: 4px; overflow: hidden;
}
.panels[data-count="7"] .stage, .panels[data-count="8"] .stage { aspect-ratio: 3 / 2; }
#l-panels .stage { aspect-ratio: 5 / 2; }
#l-panels[data-count="7"] .stage, #l-panels[data-count="8"] .stage { aspect-ratio: 2 / 1; }
.stage canvas { position: absolute; inset: 0; width: 100%; height: 100%; display: block; }
/* how much of the pile is brick and how much is gaps: a label in the sky above the pile */
.stage .share {
position: absolute; left: 6px; top: 6px; max-width: calc(100% - 12px); padding: 3px 7px; border-radius: 3px;
font: 400 var(--fs-0)/1.2 var(--font-ui); color: var(--ink-2); font-variant-numeric: tabular-nums;
white-space: nowrap; overflow: hidden; text-overflow: ellipsis;
background: var(--surface); background: color-mix(in srgb, var(--surface) 84%, transparent);
}
.stage .share:empty { display: none; }
/* a gap in the making: three tall pictures side by side, on every screen */
.fig-head h3 { font: 600 var(--fs-4)/1.2 var(--font-display); text-wrap: balance; margin-top: 6px; }
#w-panels { grid-template-columns: repeat(3, minmax(0, 1fr)); max-width: 780px; }
#w-panels .stage { aspect-ratio: 1 / 2; max-height: none; }
@media (max-width: 640px) {
#w-panels { gap: 14px 8px; }
#w-panels .panel-head { flex-wrap: wrap; gap: 2px 6px; }
#w-panels .panel-head .key { display: none; }
#w-panels .panel-head h3 { font-size: var(--fs-1); }
#w-panels .panel-head .readout { margin-left: 0; flex-basis: 100%; }
#w-panels .meter { font-size: var(--fs-0); gap: 0 8px; }
}
.panel .rule { font: 400 var(--fs-1)/1.4 var(--font-ui); color: var(--ink-2); text-wrap: pretty; }
.panel .rule .aka { color: var(--ink-3); }
.panel .meter { font: 400 var(--fs-1)/1.4 var(--font-ui); color: var(--ink-2); font-variant-numeric: tabular-nums; display: flex; flex-wrap: wrap; gap: 2px 14px; }
.panel .meter .state { color: var(--ink); font-weight: 500; }
.panel .meter .dim { color: var(--ink-3); }
.lensbar { display: flex; flex-wrap: wrap; align-items: baseline; gap: 4px 18px; font: 400 var(--fs-1)/1.3 var(--font-ui); color: var(--ink-3); font-variant-numeric: tabular-nums; }
.lensbar b { font-weight: 500; color: var(--ink); }
/* ---- charts ---- */
.charts { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 16px; }
@media (max-width: 900px) { .charts { grid-template-columns: minmax(0, 1fr); } }
.chart {
position: relative; min-width: 0; background: var(--surface); border: 1px solid var(--rule); border-radius: 4px;
padding: 16px 16px 12px; display: flex; flex-direction: column; gap: 4px;
}
.chart h3 { font: 600 var(--fs-2)/1.25 var(--font-ui); }
.chart .sub { font: 400 var(--fs-1)/1.4 var(--font-ui); color: var(--ink-2); min-height: 2.8em; }
.chart .plot { position: relative; margin-top: 6px; }
.chart svg { display: block; width: 100%; overflow: visible; font: 400 12px var(--font-ui); }
.chart svg text { fill: var(--ink-3); font-variant-numeric: tabular-nums; }
.chart svg .lbl { fill: var(--ink-2); }
.chart svg .strong { fill: var(--ink); font-weight: 500; }
.chart svg .grid { stroke: var(--rule); stroke-width: 1; }
.chart svg .axisline { stroke: var(--axis); stroke-width: 1; }
.chart-tools { display: flex; flex-wrap: wrap; align-items: center; gap: 8px 18px; font: 400 var(--fs-1)/1.2 var(--font-ui); color: var(--ink-2); margin-top: 2px; }
.tip {
position: absolute; z-index: 3; pointer-events: none; min-width: 150px; max-width: 250px;
background: var(--ink); color: var(--page); border-radius: 6px; padding: 8px 10px;
font: 400 12px/1.35 var(--font-ui); font-variant-numeric: tabular-nums;
}
.tip .tt { font-weight: 600; margin-bottom: 4px; }
.tip .row { display: flex; align-items: center; gap: 7px; white-space: nowrap; }
.tip .row b { font-weight: 600; min-width: 3.6em; text-align: right; }
.tip .row span.nm { opacity: 0.78; }
.tip .key { width: 10px; height: 3px; }
.tip .key.ring { width: 7px; height: 7px; border-color: var(--page); }
.tip .key.ink { background: var(--page); }
.tip .key.dash { background: repeating-linear-gradient(90deg, var(--page) 0 3px, transparent 3px 5px); opacity: 0.7; }
.legend { display: flex; flex-wrap: wrap; gap: 6px; align-items: center; }
.legend .static { display: inline-flex; align-items: center; gap: 7px; font: 400 var(--fs-1)/1 var(--font-ui); color: var(--ink-2); padding: 6px 8px; }
.statusline { display: flex; flex-wrap: wrap; align-items: center; gap: 8px 16px; font: 400 var(--fs-1)/1.3 var(--font-ui); color: var(--ink-3); font-variant-numeric: tabular-nums; }
.statusline .bar { width: 120px; height: 4px; border-radius: 2px; background: var(--rule); overflow: hidden; }
.statusline .bar i { display: block; height: 100%; width: 0; background: var(--ink-2); border-radius: 2px; }
.tablewrap { overflow-x: auto; border: 1px solid var(--rule); border-radius: 4px; background: var(--surface); }
table.stats { border-collapse: collapse; width: 100%; min-width: 640px; font: 400 var(--fs-1)/1.3 var(--font-ui); font-variant-numeric: tabular-nums; }
table.stats caption { caption-side: top; text-align: left; padding: 12px 14px 6px; font: 600 var(--fs-2)/1.25 var(--font-ui); color: var(--ink); }
table.stats th, table.stats td { padding: 8px 12px; text-align: right; white-space: nowrap; }
table.stats tbody td { border-top: 1px solid var(--rule); color: var(--ink-2); }
table.stats thead th { font-weight: 500; color: var(--ink-2); vertical-align: bottom; padding-bottom: 4px; }
table.stats thead tr + tr th { font-weight: 400; color: var(--ink-3); padding-top: 0; padding-bottom: 8px; }
table.stats thead th[colspan] { text-align: center; }
table.stats thead th[rowspan] { padding-bottom: 8px; }
table.stats th:first-child, table.stats td:first-child, table.stats thead tr:first-child th:nth-child(2), table.stats td:nth-child(2) { text-align: left; }
table.stats tbody td:first-child { color: var(--ink); font-weight: 500; }
table.stats td:first-child .key { margin-right: 8px; vertical-align: middle; }
table.stats tbody td.th { color: var(--ink-3); padding-left: 0; }
table.stats tbody td.meas { color: var(--ink); }
.tablewrap.flat { border: 0; border-radius: 0; background: transparent; margin: 6px -4px 8px; }
table.stats.narrow { min-width: 430px; }
table.stats.narrow th, table.stats.narrow td { padding: 7px 8px; }
table.stats.narrow thead tr:first-child th:nth-child(2), table.stats.narrow td:nth-child(2) { text-align: right; }
table.stats.narrow thead th[rowspan] { white-space: normal; }
#f-panels .stage { aspect-ratio: 3 / 2; }
#c-trees .legend { margin: 2px 0 0 -8px; }
/* ---- closing notes ---- */
.notes { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 22px 40px; }
@media (max-width: 760px) { .notes { grid-template-columns: minmax(0, 1fr); } }
.note { min-width: 0; display: flex; flex-direction: column; gap: 6px; }
.note h3 { font: 600 var(--fs-2)/1.3 var(--font-ui); display: flex; align-items: baseline; gap: 10px; flex-wrap: wrap; }
.note h3 .tag { font: 500 var(--fs-0)/1 var(--font-ui); letter-spacing: 0.07em; text-transform: uppercase; color: var(--ink-3); }
.note p { color: var(--ink-2); font-size: var(--fs-3); text-wrap: pretty; }
.sources { font: 400 var(--fs-1)/1.6 var(--font-ui); color: var(--ink-3); max-width: 86ch; border-top: 1px solid var(--rule); padding-top: 18px; }
.sources a { color: var(--ink-2); }
@media (max-width: 640px) {
.page { padding-block: 28px 56px; gap: 48px; }
.slider input[type="range"] { width: 104px; }
}
</style>
<div class="page">
<header class="masthead">
<p class="eyebrow">After Martin Hairer’s random Tetris</p>
<h1>Randomly growing surfaces</h1>
<p class="lede">Pick a column at random, drop a brick, repeat. A rough surface grows, and it looks different for every kind of brick. Step back far enough, though, and very different piles turn out to fluctuate in exactly the same way. That is universality. Here you can watch it happen, then measure it.</p>
</header>
<section class="fig" id="games" aria-labelledby="games-h">
<h2 class="sr-only" id="games-h">The games</h2>
<div class="toolbar">
<div class="group" role="group" aria-label="Games shown">
<span class="label">Games</span>
<div class="chips" id="g-chips"></div>
</div>
</div>
<div class="toolbar">
<div class="group">
<button type="button" class="btn primary" id="g-play">Pause</button>
<button type="button" class="btn" id="g-reset">Start over</button>
</div>
<label class="slider" for="g-zoom">Step back
<input type="range" autocomplete="off" id="g-zoom" min="0" max="10" step="1" value="2">
<output id="g-zoom-out" for="g-zoom"></output>
</label>
<label class="slider" for="g-speed">Speed
<input type="range" autocomplete="off" id="g-speed" min="-6" max="14" step="1" value="0">
<output id="g-speed-out" for="g-speed"></output>
</label>
<div class="group" role="group" aria-label="Colour the bricks by">
<span class="label">Colour by</span>
<div class="seg" id="g-color">
<button type="button" data-color="age" aria-pressed="true">Age</button>
<button type="button" data-color="fam" aria-pressed="false">Family</button>
</div>
</div>
</div>
<div class="panels" id="g-panels" data-count="4"></div>
<p class="caption"><strong>How to read it.</strong> The first four games are the ones Hairer plays in his talks; the other four are classics of the same family. Nobody steers and no line is ever cleared. The dark outline is the surface <span class="math">h</span>(<span class="math">x</span>, <span class="math">t</span>), the top of each column. Shading records when a piece landed, so each band is the surface as it stood at an earlier time. Time <span class="math">t</span> counts pieces dropped per column, and <span class="math">W</span> is the roughness of the surface. The label inside each picture says how much of the pile is brick and how much is gaps; a gap is there for good, because nothing can get under the surface. Drag “Step back” to see the piles from far away. Colouring by family shows who descends from whom; the figure on family trees, further down, explains.</p>
</section>
<section class="fig" id="lens" aria-labelledby="lens-h">
<div class="fig-head">
<h2 id="lens-h">Zoom out by <span class="ratio">1 : 2 : 3</span></h2>
<p>To compare piles, forget the bricks and keep only the surface. Follow it upward as it grows, subtract its average height, and zoom out as time passes. The zoom is lopsided: when 8 times more time has gone by, widths shrink by 4 and heights by 2. Height, width and time scale as <span class="ratio">1 : 2 : 3</span>, the signature of the class named after Kardar, Parisi and Zhang.</p>
<p>Each game gets two rulers of its own, one for height and one for width, set once and never touched again. If the lens fits the game, the curve keeps wriggling but stays the same size and character for good. If it does not fit, the curve swells, flattens or crumples.</p>
</div>
<div class="toolbar">
<div class="group" role="group" aria-label="Lens">
<span class="label">Lens</span>
<div class="seg" id="l-lens">
<button type="button" data-lens="kpz" aria-pressed="true"><span class="ratio">1 : 2 : 3</span>KPZ</button>
<button type="button" data-lens="ew" aria-pressed="false"><span class="ratio">1 : 2 : 4</span>Edwards–Wilkinson</button>
<button type="button" data-lens="bc" aria-pressed="false"><span class="ratio">1 : 1 : 2</span>Brownian castle</button>
</div>
</div>
<div class="group">
<button type="button" class="btn primary" id="l-play">Pause</button>
<button type="button" class="btn" id="l-reset">Zoom out again</button>
<button type="button" class="btn" id="l-blind" aria-pressed="false">Hide the names</button>
</div>
</div>
<div class="toolbar">
<div class="group" role="group" aria-label="Games under the lens">
<span class="label">Games</span>
<div class="chips" id="l-chips"></div>
</div>
</div>
<div class="lensbar" id="l-bar" aria-live="off"></div>
<div class="panels" id="l-panels" data-count="4"></div>
<p class="caption"><strong>How to read it.</strong> Every panel shows the surface minus its mean, in that game’s own rulers. The rulers were set at <span class="math">t</span> = 64 and afterwards grow only by the lens’s exponents. “On screen” compares what you see with that moment, for the height of the curve and for the width of its features. Values that stay near 1 mean the lens has the right exponents for the game.</p>
</section>
<section class="fig" id="measure" aria-labelledby="measure-h">
<div class="fig-head">
<h2 id="measure-h">Measure it</h2>
<p>Two measurements make the claim precise. The roughness <span class="math">W</span>(<span class="math">t</span>) is the standard deviation of the height across the pile. The height distribution is the histogram of all column heights at one moment, shifted and scaled to mean 0 and variance 1. Both are computed live, on fresh piles <span id="m-cols">262,144</span> columns wide.</p>
</div>
<div class="statusline" id="m-status">
<div class="bar" aria-hidden="true"><i id="m-bar"></i></div>
<span id="m-text">Starting…</span>
<button type="button" class="btn" id="m-pause">Pause</button>
<button type="button" class="btn" id="m-more" hidden>Drop more bricks</button>
</div>
<div class="legend" id="m-legend" role="group" aria-label="Series shown in both charts"></div>
<div class="charts">
<div class="chart" id="c-growth">
<h3>Roughness grows as a power of time</h3>
<p class="sub">Both axes are logarithmic, so a power law <span class="math">W</span> ∝ <span class="math">t<sup>β</sup></span> is a straight line of slope <span class="math">β</span>.</p>
<div class="plot"><svg id="ch-growth" role="img" aria-label="Roughness W against time t for each game, on logarithmic axes"></svg></div>
</div>
<div class="chart" id="c-dist">
<h3>One curve for a whole class</h3>
<p class="sub" id="d-sub">Height distribution, standardised.</p>
<div class="plot"><svg id="ch-dist" role="img" aria-label="Standardised height distribution for each game, with the Tracy-Widom and Gaussian curves"></svg></div>
<div class="chart-tools">
<label class="slider" for="d-time">Time
<input type="range" autocomplete="off" id="d-time" min="4" max="20" step="1" value="20">
<output id="d-time-out" for="d-time"></output>
</label>
<div class="seg" id="d-scale" role="group" aria-label="Vertical scale">
<button type="button" data-scale="log" aria-pressed="true">Log scale</button>
<button type="button" data-scale="lin" aria-pressed="false">Linear scale</button>
</div>
</div>
</div>
</div>
<div class="tablewrap">
<table class="stats" id="m-table">
<caption id="m-cap">The numbers behind the charts</caption>
<thead>
<tr>
<th scope="col" rowspan="2">Game</th>
<th scope="col" rowspan="2">Class</th>
<th scope="col" rowspan="2">Roughness <span class="math">W</span></th>
<th scope="colgroup" colspan="2">Exponent <span class="math">β</span></th>
<th scope="colgroup" colspan="2">Skewness</th>
<th scope="colgroup" colspan="2">Excess kurtosis</th>
</tr>
<tr>
<th scope="col">measured</th><th scope="col">class</th>
<th scope="col">measured</th><th scope="col">class</th>
<th scope="col">measured</th><th scope="col">class</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
<div class="fig-head">
<p>The solid curve is the Tracy–Widom distribution for symmetric matrices. It was found in 1996 as the law of the largest eigenvalue of a large random symmetric matrix, and the open circles are exactly that: eigenvalues of random matrices, sampled while you read. Nothing about bricks went into that curve, yet five different games land on it. Games in which slopes slow the growth down, instead of speeding it up, land on its mirror image.</p>
<p>The three games outside the class fall on the bell curve instead, each for its own reason: single squares because columns never talk to each other, sliding squares because smoothing is all they do, hot bricks because a column’s height just counts random events along its ancestry.</p>
</div>
<div class="fig-head">
<h3 id="space-h">Along the surface</h3>
<p>Those two measurements follow the height of single columns. A third looks along the surface at one moment. Take two columns a given distance apart and ask how much their heights typically differ. If the surface is a random walk in space, the difference grows like the square root of the distance. If the columns are independent, it does not grow at all. If the surface has jumps, it grows as fast as the distance itself.</p>
</div>
<div class="charts">
<div class="chart" id="c-space">
<h3>Three kinds of surface</h3>
<p class="sub" id="s-sub">Typical height difference between two columns, against the distance between them.</p>
<div class="legend" id="s-legend" role="group" aria-label="Games shown in this chart"></div>
<div class="plot"><svg id="ch-space" role="img" aria-label="Typical height difference between two columns against the distance between them, for each game, on logarithmic axes"></svg></div>
<div class="chart-tools">
<div class="seg" id="s-units" role="group" aria-label="Units of the two axes">
<button type="button" data-units="raw" aria-pressed="true">Rows and columns</button>
<button type="button" data-units="own" aria-pressed="false">Each game’s own units</button>
</div>
</div>
</div>
<div class="chart" id="c-stable">
<h3 id="s-cap">The eight curves</h3>
<p class="sub">Far apart is the typical difference between two columns that know nothing of each other. Reach is the distance at which the difference gets to half of that. The exponent is the slope of the curve where it climbs, between an eighth and a half of the reach.</p>
<div class="tablewrap flat">
<table class="stats narrow" id="s-table">
<thead>
<tr>
<th scope="col" rowspan="2">Game</th>
<th scope="col" rowspan="2">Far apart</th>
<th scope="col" rowspan="2">Reach</th>
<th scope="colgroup" colspan="2">Exponent</th>
</tr>
<tr><th scope="col">measured</th><th scope="col">class</th></tr>
</thead>
<tbody></tbody>
</table>
</div>
<p class="sub">An exponent of ½ is a random walk in space, 1 a surface with jumps, 0 independent columns. For corner filling the random walk is a theorem, and so are the jumps of hot bricks. For sticky bricks, 2 × 2 blocks and tetrominoes there is only this measurement.</p>
</div>
</div>
<div class="fig-head">
<p>In rows and columns the eight curves sit at eight different levels. Switch to each game’s own units, with distance measured by its reach and difference by its far-apart value, and six of them fall on one another: the five KPZ games and sliding squares are all random walks that forget themselves beyond their reach. Hot bricks climbs twice as steeply, and single squares not at all. This is where the first two numbers of the lens come from. The height of a random walk grows like the square root of its width, <span class="ratio">1 : 2</span>. The height of a surface with jumps grows like its width, <span class="ratio">1 : 1</span>.</p>
</div>
</section>
<section class="fig" id="trees" aria-labelledby="trees-h">
<div class="fig-head">
<h2 id="trees-h">Underneath, family trees</h2>
<p>Every brick comes to rest on or against another brick. Call that one its parent. Each brick then heads a family, itself and all its descendants, and a pile is a forest of families. Below, a brick takes its parent’s colour, except that now and then one is given a fresh colour and founds a family of its own.</p>
</div>
<div class="toolbar">
<div class="group">
<button type="button" class="btn primary" id="f-play">Pause</button>
<button type="button" class="btn" id="f-reset">Start over</button>
</div>
<label class="slider" for="f-speed">Speed
<input type="range" autocomplete="off" id="f-speed" min="-6" max="14" step="1" value="0">
<output id="f-speed-out" for="f-speed"></output>
</label>
<div class="group" role="group" aria-label="Games shown as families">
<span class="label">Games</span>
<div class="chips" id="f-chips"></div>
</div>
</div>
<div class="panels" id="f-panels" data-count="4"></div>
<p class="caption"><strong>How to read it.</strong> Each patch of colour is one family: a founder and everything descended from it. The white channels are the gaps left where one family grew over its neighbour, and the label inside each picture says how much of the pile they take up. Press “Start over” to watch a crowd of one-column families thin out. In single squares, picky squares and sliding squares a brick only ever rests on its own column, so there a family is just a column.</p>
<div class="fig-head">
<p>For sticky bricks, three things follow from the rule in a line or two each. A family always holds one unbroken stretch of the surface. Where two families meet, only the taller one can advance: it gains a column each time a brick falls at the foot of its edge, and the gap it roofs over is never filled. So a family spreads by at most one column per unit of time on each side, and it lives inside an upside-down triangle with its founder at the tip. A family growing with no neighbours fills its triangle exactly: its edges move out at speed one, and its underside rises about 1.6 bricks per column.</p>
</div>
<div class="fig-head">
<h3 id="wedge-h">A gap in the making</h3>
<p>Give one family a head start, a solid block under one side of the floor, and watch a single gap form. The pile on the block, in colour, spreads over the lower pile, in grey, and the wedge left between them is the gap. Its roof is the underside of the overhang. Its floor is the lower pile as it stood when it was covered. The overhang gains ground whenever a piece lands across its edge, which happens at a fixed average rate, while roof and floor each climb at a rate of their own. So both have a fixed slope, set by the game and by nothing else. The floor is the steeper of the two, and that is why every gap closes.</p>
</div>
<div class="toolbar">
<div class="group">
<button type="button" class="btn primary" id="w-play">Pause</button>
<button type="button" class="btn" id="w-reset">Start over</button>
</div>
<label class="slider" for="w-speed">Speed
<input type="range" autocomplete="off" id="w-speed" min="-6" max="10" step="1" value="0">
<output id="w-speed-out" for="w-speed"></output>
</label>
<div class="legend" role="group" aria-label="Lines drawn on each picture">
<span class="static"><span class="key ink"></span>Average roof</span>
<span class="static"><span class="key dash"></span>Average floor</span>
</div>
</div>
<div class="panels" id="w-panels" data-count="3" role="group" aria-labelledby="wedge-h"></div>
<p class="caption"><strong>How to read it.</strong> In colour, the pile that grew on the block; in grey, the pile that grew on the floor; the pale rectangle is the block. The two lines are averages over many runs. For sticky bricks the roof climbs 1.59 rows for every column the overhang advances and the floor 2.14; for tetrominoes 4.2 and 5.3; for 2 × 2 blocks 6.9 and 8.1. Under each picture are the slopes of the run you are watching. They wander around the averages, and the smaller the picture the more they wander. When the lower pile reaches the top, the run starts again.</p>
<div class="fig-head">
<p>In a crowd most families are soon overshadowed. How wide do the survivors get? Start with every column as its own family and count how many still hold some of the surface. In hot bricks the border between two families is a plain random walk, the borders are independent until they meet, and the count follows the classical formula for coalescing random walks, √(2/π<span class="math">t</span>). The survivors are about √<span class="math">t</span> wide. In the KPZ games a border also slides towards the lower side, and the count falls like <span class="math">t</span><sup>−2/3</sup> instead. That exponent is the 2 in <span class="ratio">1 : 2 : 3</span>: a family’s width is the distance over which the surface is correlated.</p>
</div>
<div class="charts">
<div class="chart" id="c-trees">
<h3>Families still alive</h3>
<p class="sub">Families per column that still hold some of the surface, starting from one family per column. Both axes are logarithmic.</p>
<div class="legend" id="f-legend"></div>
<div class="plot"><svg id="ch-trees" role="img" aria-label="Families still alive per column against time, for the five games in which a family can spread sideways"></svg></div>
</div>
<div class="chart" id="c-ftable">
<h3 id="f-cap">Families</h3>
<p class="sub">Mean width is the average stretch of surface held by a surviving family. The decay exponent is measured over the last two doublings of time.</p>
<div class="tablewrap flat">
<table class="stats narrow" id="f-table">
<thead>
<tr>
<th scope="col" rowspan="2">Game</th>
<th scope="col" rowspan="2">Alive per 1,000 columns</th>
<th scope="col" rowspan="2">Mean width</th>
<th scope="colgroup" colspan="2">Decay exponent</th>
</tr>
<tr><th scope="col">measured</th><th scope="col">class</th></tr>
</thead>
<tbody></tbody>
</table>
</div>
<p class="sub">In corner filling a diamond’s parent is the later of the two it sits on. Its families are then the geodesic trees of last-passage percolation, where merging on the scale <span class="math">t</span><sup>2/3</sup> is a theorem (Basu, Sarkar and Sly). For sticky bricks, 2 × 2 blocks and tetrominoes there is a scaling argument (Khanin, Nechaev, Oshanin, Sobolevski and Vasilyev) and this measurement.</p>
</div>
</div>
</section>
<section class="fig" id="known" aria-labelledby="known-h">
<div class="fig-head">
<h2 id="known-h">Proved, and still open</h2>
</div>
<div class="notes">
<div class="note">
<h3>Corner filling <span class="tag">proved</span></h3>
<p>This game is exactly solvable. For a flat start the Tracy–Widom law is a theorem (Sasamoto; Borodin, Ferrari, Prähofer and Sasamoto, 2005–07), and the whole rescaled surface converges to one universal object, the KPZ fixed point (Matetski, Quastel and Remenik, 2021). Its roughness is known down to the constant: <span class="math">W</span><sup>2</sup> → 0.402 <span class="math">t</span><sup>2/3</sup>. Along the surface it is a random walk: started as a coin-flip walk it stays one for ever, and the limit from a flat start looks like Brownian motion over any bounded stretch (Sarkar and Virág, 2021).</p>
</div>
<div class="note">
<h3>The KPZ equation <span class="tag">proved</span></h3>
<p>The continuum model of the class is <span class="math">∂<sub>t</sub>h</span> = ½<span class="math">∂<sub>x</sub></span><sup>2</sup><span class="math">h</span> + ¼(<span class="math">∂<sub>x</sub>h</span>)<sup>2</sup> + <span class="math">ξ</span>, with <span class="math">ξ</span> white noise. The square of a derivative of something that rough has no obvious meaning; Hairer’s 2013 solution theory gave it one. The equation, too, converges to the KPZ fixed point (Quastel and Sarkar; Virág).</p>
</div>
<div class="note">
<h3>Sticky bricks and tetrominoes <span class="tag">open</span></h3>
<p>Sticky bricks, known as ballistic deposition, are presumed to belong to the KPZ class, and the measurements above say the same of 2 × 2 blocks and tetrominoes. None of it is proved: Cannizzaro and Hairer call the large-scale behaviour of ballistic deposition a long-standing open question. What you measured is evidence, not a theorem.</p>
</div>
<div class="note">
<h3>Hot bricks <span class="tag">proved</span></h3>
<p>Run ballistic deposition at infinite temperature and it leaves the class altogether. Cannizzaro and Hairer (2022) proved that the pile converges, under <span class="ratio">1 : 1 : 2</span> scaling, to a new object they named the Brownian castle for its turrets and crannies. It is neither KPZ nor Edwards–Wilkinson. Try the third lens on it.</p>
</div>
</div>
<p class="sources">Sources: Tom Crawford’s interviews with Hairer at the 2019 Heidelberg Laureate Forum, <a href="https://tomrocksmaths.com/2020/12/02/playing-tetris-with-martin-hairer-2014-fields-medal/">Playing Tetris with Martin Hairer</a> and <a href="https://tomrocksmaths.com/2021/03/10/brownian-castles-and-the-yang-mills-millennium-problem-with-martin-hairer-fields-medal-2014">Brownian castles</a>; G. Cannizzaro and M. Hairer, <a href="https://arxiv.org/abs/2010.02766">The Brownian Castle</a>; M. Hairer, <a href="https://arxiv.org/abs/1109.6811">Solving the KPZ equation</a>; K. Matetski, J. Quastel and D. Remenik, <a href="https://arxiv.org/abs/1701.00018">The KPZ fixed point</a>; S. Sarkar and B. Virág, <a href="https://arxiv.org/abs/2002.08496">Brownian absolute continuity of the KPZ fixed point with arbitrary initial condition</a>; K. Khanin, S. Nechaev, G. Oshanin, A. Sobolevski and O. Vasilyev, <a href="https://arxiv.org/abs/1006.4576">Ballistic deposition patterns beneath a growing KPZ interface</a>; R. Basu, S. Sarkar and A. Sly, <a href="https://arxiv.org/abs/1704.05219">Coalescence of geodesics in exactly solvable models of last passage percolation</a>. All simulations run in your browser; every reload drops different bricks.</p>
</section>
</div>
<script>
/* Tracy-Widom GOE density, standardised to mean 0 and variance 1: log g(z) on z = z0 + i*dz.
Computed from the Hastings-McLeod solution of Painleve II; mean -1.2065335746, sd 1.2679830577, skewness 0.293465, excess kurtosis 0.165243. */
var TW_GOE = { z0: -6, dz: 0.05, skew: 0.293465, kurt: 0.165243, logg: [-32.4674,-31.8026,-31.1469,-30.5003,-29.8626,-29.2339,-28.6141,-28.003,-27.4008,-26.8072,-26.2222,-25.6458,-25.0779,-24.5184,-23.9673,-23.4245,-22.89,-22.3637,-21.8455,-21.3354,-20.8332,-20.3391,-19.8528,-19.3743,-18.9036,-18.4407,-17.9853,-17.5376,-17.0973,-16.6646,-16.2392,-15.8211,-15.4104,-15.0069,-14.6105,-14.2212,-13.839,-13.4637,-13.0953,-12.7338,-12.3791,-12.0312,-11.6899,-11.3552,-11.0271,-10.7055,-10.3903,-10.0815,-9.779,-9.4828,-9.1928,-8.9089,-8.6311,-8.3593,-8.0935,-7.8336,-7.5795,-7.3312,-7.0887,-6.8518,-6.6205,-6.3948,-6.1745,-5.9598,-5.7503,-5.5463,-5.3474,-5.1538,-4.9653,-4.782,-4.6036,-4.4303,-4.2618,-4.0983,-3.9395,-3.7855,-3.6362,-3.4915,-3.3514,-3.2159,-3.0848,-2.9582,-2.8359,-2.7179,-2.6042,-2.4947,-2.3893,-2.2881,-2.1909,-2.0976,-2.0084,-1.923,-1.8414,-1.7636,-1.6896,-1.6192,-1.5525,-1.4894,-1.4298,-1.3736,-1.3209,-1.2716,-1.2256,-1.1829,-1.1435,-1.1072,-1.0741,-1.044,-1.0171,-0.9931,-0.9721,-0.954,-0.9388,-0.9264,-0.9168,-0.91,-0.9058,-0.9044,-0.9055,-0.9092,-0.9155,-0.9242,-0.9354,-0.9491,-0.9651,-0.9835,-1.0042,-1.0271,-1.0523,-1.0797,-1.1093,-1.1411,-1.1749,-1.2108,-1.2487,-1.2887,-1.3306,-1.3745,-1.4203,-1.468,-1.5176,-1.569,-1.6222,-1.6772,-1.7339,-1.7924,-1.8526,-1.9145,-1.978,-2.0432,-2.11,-2.1784,-2.2483,-2.3198,-2.3928,-2.4674,-2.5434,-2.6209,-2.6999,-2.7802,-2.862,-2.9452,-3.0298,-3.1158,-3.2031,-3.2917,-3.3817,-3.4729,-3.5655,-3.6593,-3.7544,-3.8508,-3.9483,-4.0471,-4.1471,-4.2484,-4.3508,-4.4543,-4.5591,-4.665,-4.772,-4.8802,-4.9895,-5.0999,-5.2114,-5.324,-5.4377,-5.5524,-5.6682,-5.7851,-5.903,-6.022,-6.142,-6.263,-6.3851,-6.5081,-6.6322,-6.7572,-6.8832,-7.0102,-7.1382,-7.2672,-7.3971,-7.5279,-7.6597,-7.7925,-7.9261,-8.0607,-8.1963,-8.3327,-8.4701,-8.6083,-8.7475,-8.8875,-9.0284,-9.1703,-9.313,-9.4565,-9.601,-9.7463,-9.8924,-10.0394,-10.1873,-10.336,-10.4855,-10.6359,-10.7871,-10.9391,-11.092,-11.2457,-11.4001,-11.5554,-11.7115,-11.8684,-12.0261,-12.1846,-12.3439,-12.504,-12.6648,-12.8265,-12.9889,-13.1521,-13.316,-13.4807,-13.6462,-13.8124,-13.9794,-14.1472,-14.3156,-14.4849,-14.6548,-14.8256,-14.997,-15.1692,-15.3421,-15.5157,-15.6901,-15.8652,-16.041,-16.2175,-16.3947,-16.5727,-16.7513,-16.9307,-17.1107,-17.2915,-17.4729,-17.6551,-17.8379,-18.0214,-18.2056,-18.3905,-18.5761,-18.7623,-18.9493,-19.1369,-19.3251,-19.5141,-19.7037,-19.894,-20.0849,-20.2765,-20.4688,-20.6617,-20.8552,-21.0495,-21.2443,-21.4398,-21.636,-21.8328,-22.0302,-22.2283,-22.427,-22.6264,-22.8264,-23.027,-23.2283,-23.4301,-23.6326,-23.8358,-24.0395] };
/* ENGINE: growth rules on a ring of L = 2^logL columns. Runs unchanged on the page and inside workers. */
function ENGINE() {
'use strict';
// ---- tetromino orientations: 7 pieces x 4 rotations, cells measured from the bounding box's lower-left ----
var BASE = [
[[0, 0], [1, 0], [2, 0], [3, 0]],
[[0, 0], [1, 0], [0, 1], [1, 1]],
[[0, 0], [1, 0], [2, 0], [1, 1]],
[[0, 0], [1, 0], [1, 1], [2, 1]],
[[1, 0], [2, 0], [0, 1], [1, 1]],
[[0, 0], [1, 0], [2, 0], [0, 1]],
[[0, 0], [1, 0], [2, 0], [2, 1]]
];
var NOR = 28;
var OW = new Int32Array(NOR); // width in columns
var OB = new Int32Array(NOR * 4); // lowest cell of the piece in each of its columns
var OT = new Int32Array(NOR * 4); // one above its highest cell in each column
var OX = new Int32Array(NOR * 4); // the four cells
var OY = new Int32Array(NOR * 4);
(function () {
for (var p = 0; p < 7; p++) {
var cells = BASE[p].map(function (c) { return [c[0], c[1]]; });
for (var r = 0; r < 4; r++) {
var k = p * 4 + r, minx = 99, miny = 99, i, w = 0;
for (i = 0; i < 4; i++) { if (cells[i][0] < minx) minx = cells[i][0]; if (cells[i][1] < miny) miny = cells[i][1]; }
for (i = 0; i < 4; i++) { OB[k * 4 + i] = 99; OT[k * 4 + i] = 0; }
for (i = 0; i < 4; i++) {
var cx = cells[i][0] - minx, cy = cells[i][1] - miny;
OX[k * 4 + i] = cx; OY[k * 4 + i] = cy;
if (cx + 1 > w) w = cx + 1;
if (cy < OB[k * 4 + cx]) OB[k * 4 + cx] = cy;
if (cy + 1 > OT[k * 4 + cx]) OT[k * 4 + cx] = cy + 1;
}
OW[k] = w;
cells = cells.map(function (c) { return [-c[1], c[0]]; });
}
}
})();
// ---- random numbers: sfc32, seeded through a 32-bit mixer ----
function seed4(seed) {
var s = new Int32Array(4), z = seed | 0, t;
for (var i = 0; i < 4; i++) {
z = z + 0x9e3779b9 | 0;
t = z ^ (z >>> 16); t = Math.imul(t, 0x21f0aaad); t ^= t >>> 15; t = Math.imul(t, 0x735a2d97); t ^= t >>> 15;
s[i] = t;
}
var a = s[0], b = s[1], c = s[2], d = s[3];
for (i = 0; i < 20; i++) { t = (a + b | 0) + d | 0; d = d + 1 | 0; a = b ^ (b >>> 9); b = c + (c << 3) | 0; c = (c << 21) | (c >>> 11); c = c + t | 0; }
s[0] = a; s[1] = b; s[2] = c; s[3] = d;
return s;
}
// ---- heights-only simulation ----
function Sim(model, logL, seed) {
this.model = model; this.logL = logL; this.L = 1 << logL;
this.h = new Int32Array(this.L);
this.s = seed4(seed);
this.n = 0; // attempts so far; time = n / L
var x;
if (model === 'cor') for (x = 0; x < this.L; x++) this.h[x] = x & 1;
// Families. A brick's parent is the brick it comes to rest on or against. lab[x] is the original column that the
// top brick of column x descends from; it is kept for the games in which a parent can sit in a neighbouring column.
this.lab = null; this.tt = null; this.ev = 0;
if (model === 'bd' || model === 'sq2' || model === 'tet' || model === 'hot' || model === 'cor') {
this.lab = new Int32Array(this.L);
for (x = 0; x < this.L; x++) this.lab[x] = model === 'cor' ? (x | 1) : x; // corner filling: one family per tooth of the floor
}
if (model === 'cor') this.tt = new Int32Array(this.L); // when the top diamond of each column was placed
}
// One attempt = one column chosen uniformly at random. Each loop inlines the generator.
Sim.prototype.run = function (n) {
var h = this.h, s = this.s, sh = 32 - this.logL, mask = this.L - 1;
var a = s[0], b = s[1], c = s[2], d = s[3], t = 0, x = 0, i = 0;
var hc = 0, hl = 0, hr = 0, xl = 0, xr = 0, k4 = 0, w = 0, y0 = 0, v = 0, u = 0;
var lab = this.lab, tt = this.tt, ev = this.ev, lb = 0, am = 0;
switch (this.model) {
case 'rd': // single squares: h(x) -> h(x) + 1
for (i = 0; i < n; i++) {
t = (a + b | 0) + d | 0; d = d + 1 | 0; a = b ^ (b >>> 9); b = c + (c << 3) | 0; c = (c << 21) | (c >>> 11); c = c + t | 0;
x = t >>> sh; h[x] = h[x] + 1 | 0;
}
break;
case 'bd': // sticky bricks: h(x) -> max{h(x-1), h(x)+1, h(x+1)}
for (i = 0; i < n; i++) {
t = (a + b | 0) + d | 0; d = d + 1 | 0; a = b ^ (b >>> 9); b = c + (c << 3) | 0; c = (c << 21) | (c >>> 11); c = c + t | 0;
x = t >>> sh; xl = (x - 1) & mask; xr = (x + 1) & mask; hc = h[x] + 1 | 0; hl = h[xl]; hr = h[xr];
if (hc >= hl && hc >= hr) h[x] = hc; // lands on its own column
else if (hl >= hr) { h[x] = hl; lab[x] = lab[xl]; } // sticks to the left neighbour and joins its family
else { h[x] = hr; lab[x] = lab[xr]; }
}
break;
case 'sq2': // 2x2 blocks: both columns -> max of the two + 2
for (i = 0; i < n; i++) {
t = (a + b | 0) + d | 0; d = d + 1 | 0; a = b ^ (b >>> 9); b = c + (c << 3) | 0; c = (c << 21) | (c >>> 11); c = c + t | 0;
x = t >>> sh; xr = (x + 1) & mask; hc = h[x]; hr = h[xr];
if (hc >= hr) { hc = hc + 2 | 0; lab[xr] = lab[x]; } else { hc = hr + 2 | 0; lab[x] = lab[xr]; } // the family of the column it lands on
h[x] = hc; h[xr] = hc;
}
break;
case 'tet': // tetrominoes: random piece, random rotation, falls until it touches
for (i = 0; i < n; i++) {
t = (a + b | 0) + d | 0; d = d + 1 | 0; a = b ^ (b >>> 9); b = c + (c << 3) | 0; c = (c << 21) | (c >>> 11); c = c + t | 0;
x = t >>> sh;
t = (a + b | 0) + d | 0; d = d + 1 | 0; a = b ^ (b >>> 9); b = c + (c << 3) | 0; c = (c << 21) | (c >>> 11); c = c + t | 0;
k4 = ((t >>> 0) % 28) << 2; w = OW[k4 >> 2];
y0 = h[x] - OB[k4]; am = x; // am: the column the piece comes to rest on
if (w > 1) {
xr = (x + 1) & mask; v = h[xr] - OB[k4 + 1]; if (v > y0) { y0 = v; am = xr; }
if (w > 2) {
xr = (x + 2) & mask; v = h[xr] - OB[k4 + 2]; if (v > y0) { y0 = v; am = xr; }
if (w > 3) { xr = (x + 3) & mask; v = h[xr] - OB[k4 + 3]; if (v > y0) { y0 = v; am = xr; } }
}
}
lb = lab[am];
h[x] = y0 + OT[k4]; lab[x] = lb;
if (w > 1) {
xr = (x + 1) & mask; h[xr] = y0 + OT[k4 + 1]; lab[xr] = lb;
if (w > 2) {
xr = (x + 2) & mask; h[xr] = y0 + OT[k4 + 2]; lab[xr] = lb;
if (w > 3) { xr = (x + 3) & mask; h[xr] = y0 + OT[k4 + 3]; lab[xr] = lb; }
}
}
}
break;
case 'rsos': // picky squares: accepted only where no step higher than one brick results
for (i = 0; i < n; i++) {
t = (a + b | 0) + d | 0; d = d + 1 | 0; a = b ^ (b >>> 9); b = c + (c << 3) | 0; c = (c << 21) | (c >>> 11); c = c + t | 0;
x = t >>> sh; hc = h[x];
if (hc <= h[(x - 1) & mask] && hc <= h[(x + 1) & mask]) h[x] = hc + 1 | 0;
}
break;
case 'fam': // sliding squares: the square rolls to the lowest of x-1, x, x+1
for (i = 0; i < n; i++) {
t = (a + b | 0) + d | 0; d = d + 1 | 0; a = b ^ (b >>> 9); b = c + (c << 3) | 0; c = (c << 21) | (c >>> 11); c = c + t | 0;
x = t >>> sh; xl = (x - 1) & mask; xr = (x + 1) & mask; hc = h[x]; hl = h[xl]; hr = h[xr];
if (hl < hc || hr < hc) { if (hl < hr) x = xl; else if (hr < hl) x = xr; else x = (t & 1) ? xl : xr; }
h[x] = h[x] + 1 | 0;
}
break;
case 'cor': // corner filling (single-step model / TASEP): a notch \/ becomes a peak /\
for (i = 0; i < n; i++) {
t = (a + b | 0) + d | 0; d = d + 1 | 0; a = b ^ (b >>> 9); b = c + (c << 3) | 0; c = (c << 21) | (c >>> 11); c = c + t | 0;
x = t >>> sh; hc = h[x]; xl = (x - 1) & mask; xr = (x + 1) & mask;
if (h[xl] > hc && h[xr] > hc) { // the parent is whichever of the two supporting diamonds arrived later
h[x] = hc + 2 | 0; ev = ev + 1 | 0; lab[x] = tt[xl] >= tt[xr] ? lab[xl] : lab[xr]; tt[x] = ev;
}
}
break;
case 'hot': // hot bricks (0-BD): +1 with prob 1/2, copy the left or the right neighbour with prob 1/4 each
for (i = 0; i < n; i++) {
t = (a + b | 0) + d | 0; d = d + 1 | 0; a = b ^ (b >>> 9); b = c + (c << 3) | 0; c = (c << 21) | (c >>> 11); c = c + t | 0;
x = t >>> sh; u = t & 3;
if (u < 2) h[x] = h[x] + 1 | 0;
else if (u === 2) { xl = (x - 1) & mask; h[x] = h[xl]; lab[x] = lab[xl]; }
else { xr = (x + 1) & mask; h[x] = h[xr]; lab[x] = lab[xr]; }
}
break;
}
s[0] = a; s[1] = b; s[2] = c; s[3] = d;
this.n += n; this.ev = ev;
};
// mean height, central moments, and a histogram of h - round(mean) clipped to [-R, R]
Sim.prototype.stats = function (R) {
var h = this.h, L = this.L, x, sum = 0;
for (x = 0; x < L; x++) sum += h[x];
var mean = sum / L, c = Math.round(mean), hist = new Int32Array(2 * R + 1), dd, d2, m2 = 0, m3 = 0, m4 = 0, i;
for (x = 0; x < L; x++) {
dd = h[x] - mean; d2 = dd * dd; m2 += d2; m3 += d2 * dd; m4 += d2 * d2;
i = h[x] - c + R; if (i < 0) i = 0; else if (i > 2 * R) i = 2 * R; hist[i]++;
}
var trees = -1; // families that still hold some of the surface
if (this.lab) {
var lab = this.lab, mask = L - 1;
trees = 0;
for (x = 0; x < L; x++) if (lab[x] !== lab[(x + 1) & mask]) trees++;
if (trees === 0) trees = 1;
}
return { t: this.n / L, n: L, mean: mean, m2: m2 / L, m3: m3 / L, m4: m4 / L, c: c, hist: hist, trees: trees };
};
// normalised covariance of heights r columns apart
Sim.prototype.corr = function (r, mean, m2) {
var h = this.h, L = this.L, mask = L - 1, x, acc = 0;
for (x = 0; x < L; x++) acc += (h[x] - mean) * (h[(x + r) & mask] - mean);
return acc / L / m2;
};
// distance at which that covariance has fallen to one half
Sim.prototype.xiHalf = function (mean, m2) {
if (!(m2 > 0)) return 0;
var r = 1, c1 = this.corr(1, mean, m2), r0 = 0, c0 = 1;
if (c1 <= 0.5) return (1 - 0.5) / (1 - c1);
while (c1 > 0.5 && r < this.L / 4) { r0 = r; c0 = c1; r *= 2; c1 = this.corr(r, mean, m2); }
if (c1 > 0.5) return r;
while (r - r0 > 1) {
var rm = (r + r0) >> 1, cm = this.corr(rm, mean, m2);
if (cm > 0.5) { r0 = rm; c0 = cm; } else { r = rm; c1 = cm; }
}
return r0 + (c0 - 0.5) / (c0 - c1);
};
// Typical height difference between two columns r = 1, 2, 4, ... apart: half the interquartile range of h(x + r) - h(x),
// so half of all such pairs differ by less. Each lattice value is spread evenly over its own cell, which lets the
// answer move smoothly instead of brick by brick.
Sim.prototype.typical = function (R, nr) {
var h = this.h, L = this.L, mask = L - 1, hist = new Int32Array(2 * R + 1), out = new Float32Array(nr);
var k, r, x, d, i, first, w, a, b, c, cum, q1, q3, lo = 0.25 * L, hi = 0.75 * L;
for (k = 0; k < nr; k++) {
r = 1 << k; if (r >= L) break;
hist.fill(0);
for (x = 0; x < L; x++) { d = h[(x + r) & mask] - h[x] + R; hist[d < 0 ? 0 : d > 2 * R ? 2 * R : d]++; }
first = -1; w = 0;
for (i = 0; i <= 2 * R; i++) if (hist[i] !== 0) {
if (first < 0) first = i;
else { a = w; b = i - first; while (b) { c = a % b; a = b; b = c; } w = a; } // spacing of the values: the gcd of their offsets
}
if (!w) continue; // every pair differs by the same amount
cum = 0; q1 = NaN; q3 = NaN;
for (i = first; i <= 2 * R; i += w) {
c = hist[i]; if (!c) continue;
if (q1 !== q1 && lo < cum + c) q1 = i - R - 0.5 * w + w * (lo - cum) / c;
if (hi < cum + c) { q3 = i - R - 0.5 * w + w * (hi - cum) / c; break; }
cum += c;
}
out[k] = 0.5 * (q3 - q1);
}
return out;
};
// ---- largest eigenvalue of a big random symmetric matrix (GOE), via its tridiagonal form ----
// Only the leading m x m block matters for the top eigenvalue (m ~ 10 n^(1/3)).
function Goe(n, seed) {
this.n = n; this.m = Math.min(n, Math.ceil(10 * Math.pow(n, 1 / 3)));
this.s = seed4(seed);
this.a = new Float64Array(this.m); this.b2 = new Float64Array(this.m);
this.mu = new Float64Array(this.m);
for (var i = 0; i < this.m; i++) this.mu[i] = Math.sqrt(Math.max(n - 1 - i, 1) - 0.5);
this.c = Math.sqrt(2 * n); this.w = Math.pow(n, -1 / 6) / Math.SQRT2;
}
Goe.prototype.sample = function () {
var s = this.s, a = s[0], b = s[1], c = s[2], d = s[3], t, m = this.m, A = this.a, B2 = this.b2, MU = this.mu, i, u1, u2, rad, g1, g2, bb;
for (i = 0; i < m; i++) {
t = (a + b | 0) + d | 0; d = d + 1 | 0; a = b ^ (b >>> 9); b = c + (c << 3) | 0; c = (c << 21) | (c >>> 11); c = c + t | 0;
u1 = ((t >>> 0) + 0.5) / 4294967296;
t = (a + b | 0) + d | 0; d = d + 1 | 0; a = b ^ (b >>> 9); b = c + (c << 3) | 0; c = (c << 21) | (c >>> 11); c = c + t | 0;
u2 = ((t >>> 0) + 0.5) / 4294967296;
rad = Math.sqrt(-2 * Math.log(u1)); g1 = rad * Math.cos(6.283185307179586 * u2); g2 = rad * Math.sin(6.283185307179586 * u2);
A[i] = g1; // diagonal: N(0,1)
bb = (MU[i] + g2 * 0.7071067811865476) * 0.7071067811865476; // chi_k / sqrt 2, chi_k ~ sqrt(k - 1/2) + N(0, 1/2)
B2[i] = bb * bb;
}
s[0] = a; s[1] = b; s[2] = c; s[3] = d;
var lo = this.c - 9 * this.w, hi = this.c + 11 * this.w, mid, q, ok;
function below(x) { // true when every eigenvalue is < x (all pivots of T - x negative)
var q = A[0] - x; if (q >= 0) return false;
for (var j = 1; j < m; j++) { q = A[j] - x - B2[j - 1] / q; if (q >= 0) return false; }
return true;
}
while (!below(hi)) hi += 4 * this.w;
while (below(lo)) lo -= 4 * this.w;
for (i = 0; i < 30; i++) { mid = 0.5 * (lo + hi); if (below(mid)) hi = mid; else lo = mid; }
return (0.5 * (lo + hi) - this.c) / this.w;
};
// ---- job runner: sweeps every model through the checkpoints, a slice at a time ----
function makeRunner(post, sliceMs) {
var job = null, paused = false, timer = null;
var now = (typeof performance !== 'undefined' && performance.now) ? function () { return performance.now(); } : function () { return Date.now(); };
function pump() { if (timer === null) timer = setTimeout(tick, 0); }
function tick() {
timer = null;
if (!job || paused) return;
var t0 = now(), id = job.id;
while (now() - t0 < sliceMs) {
if (!step()) { job = null; post({ type: 'done', id: id }); return; }
}
pump();
}
function newSims() {
job.sims = job.models.map(function (m, j) { return new Sim(m, job.logL, job.seed + 7919 * job.sweep + 104729 * j + 17); });
job.k = 0; job.j = 0; job.left = -1;
}
function step() {
if (job.kind === 'goe') {
var B = 200, y, i, bin, sum = [0, 0, 0, 0], hist = new Int32Array(job.bins);
for (i = 0; i < B; i++) {
y = job.goe.sample();
sum[0] += y; sum[1] += y * y; sum[2] += y * y * y; sum[3] += y * y * y * y;
bin = Math.floor((y - job.lo) / job.dx); if (bin < 0) bin = 0; else if (bin >= job.bins) bin = job.bins - 1; hist[bin]++;
}
job.made += B;
post({ type: 'goe', id: job.id, count: B, sum: sum, hist: hist, lo: job.lo, dx: job.dx });
return job.made < job.total;
}
var sim = job.sims[job.j], L = sim.L;
if (job.left < 0) job.left = Math.round(job.times[job.k] * L) - sim.n;
var chunk = job.left > 1048576 ? 1048576 : job.left;
if (chunk > 0) { sim.run(chunk); job.left -= chunk; }
if (job.left > 0) return true;
var st = sim.stats(job.R);
st.type = 'cp'; st.id = job.id; st.model = sim.model; st.sweep = job.sweep; st.k = job.k;
if (job.xi) { st.xi = sim.xiHalf(st.mean, st.m2); var c1 = sim.corr(1, st.mean, st.m2); st.slope2 = 2 * st.m2 * (1 - c1); }
if (job.typ && job.k % 2 === 0) st.typ = sim.typical(job.R, job.typ); // along the surface, at every other checkpoint
post(st);
job.left = -1; job.j++;
if (job.j >= job.sims.length) {
job.j = 0; job.k++;
if (job.k >= job.times.length) {
job.sweep++;
if (job.sweep >= job.sweeps) return false;
newSims();
}
}
return true;
}
// ---- lens: sims that advance to a requested time and return a sampled window of the surface ----
var lensSims = {};
function lensStep(m) {
var out = [], tr = [];
m.req.forEach(function (q) {
var sim = lensSims[q.key]; if (!sim) return;
var need = Math.round(m.t * sim.L) - sim.n; if (need > 0) sim.run(need);
var h = sim.h, L = sim.L, mask = L - 1, x, sum = 0, m2 = 0, dd, i;
for (x = 0; x < L; x++) sum += h[x];
var mean = sum / L;
for (x = 0; x < L; x++) { dd = h[x] - mean; m2 += dd * dd; }
m2 /= L;
var y = new Float32Array(q.n);
for (i = 0; i < q.n; i++) y[i] = h[Math.floor(q.x0 + i * q.dx) & mask] - mean;
var o = { key: q.key, W: Math.sqrt(m2), y: y };
if (q.xi) o.xi = sim.xiHalf(mean, m2);
out.push(o); tr.push(y.buffer);
});
post({ type: 'lens', id: m.id, t: m.t, out: out }, tr);
}
return {
handle: function (m) {
if (m.cmd === 'ping') { post({ type: 'pong' }); return; }
if (m.cmd === 'lens-init') {
lensSims = {};
m.sims.forEach(function (q) { lensSims[q.key] = new Sim(q.model, m.logL, q.seed | 0); });
return;
}
if (m.cmd === 'lens-step') { lensStep(m); return; }
if (m.cmd === 'start') {
job = { id: m.id, kind: 'grow', models: m.models, logL: m.logL, times: m.times, sweeps: m.sweeps, seed: m.seed | 0, R: m.R || 1024, xi: !!m.xi, typ: m.typ | 0, sweep: m.sweep0 | 0 };
newSims(); paused = false; pump();
} else if (m.cmd === 'goe') {
job = { id: m.id, kind: 'goe', goe: new Goe(m.n, m.seed | 0), total: m.total, made: 0, lo: -8, dx: 0.05, bins: 400 };
paused = false; pump();
} else if (m.cmd === 'pause') { paused = true; }
else if (m.cmd === 'resume') { if (paused) { paused = false; pump(); } }
else if (m.cmd === 'stop') { job = null; }
}
};
}
return { Sim: Sim, Goe: Goe, makeRunner: makeRunner, seed4: seed4, NOR: NOR, OW: OW, OB: OB, OT: OT, OX: OX, OY: OY };
}
(function () {
'use strict';
var E = ENGINE();
var doc = document, root = doc.documentElement;
function $(id) { return doc.getElementById(id); }
function mk(tag, cls, text) { var e = doc.createElement(tag); if (cls) e.className = cls; if (text != null) e.textContent = text; return e; }
function clamp(v, a, b) { return v < a ? a : v > b ? b : v; }
var nf = new Intl.NumberFormat('en-US', { maximumFractionDigits: 0 });
function fint(n) { return nf.format(Math.round(n)); }
function fnum(x, d) { var s = Math.abs(x).toFixed(d); return (x < 0 && +s !== 0 ? '−' : '') + s; }
function fsgn(x, d) { var s = Math.abs(x).toFixed(d); if (+s === 0) return s; return (x < 0 ? '−' : '+') + s; }
function rseed() { return (Math.random() * 4294967296) | 0; }
var reduceMotion = !!(window.matchMedia && matchMedia('(prefers-reduced-motion: reduce)').matches);
var DPR = window.devicePixelRatio || 1;
var HC = navigator.hardwareConcurrency || 4;
// ================= the games =================
// v: rows gained per unit time; g: lattice spacing of heights; refW, refXi: roughness and correlation length at t = 64
var MODELS = [
{ id: 'tet', slot: 1, name: 'Tetrominoes', cls: 'kpz', sign: 1, v: 10.4, g: 1, fill: 'porous', refW: 20.70, refXi: 21.4,
rule: 'A random piece in a random rotation falls until it touches the pile.', aka: 'random Tetris' },
{ id: 'sq2', slot: 2, name: '2 × 2 blocks', cls: 'kpz', sign: 1, v: 8.0, g: 2, fill: 'porous', refW: 19.18, refXi: 12.1,
rule: 'A two-by-two block falls until it touches the pile.', aka: '' },
{ id: 'rd', slot: 3, name: 'Single squares', cls: 'free', sign: 0, v: 1, g: 1, fill: 'compact', refW: 8.0, refXi: 0,
rule: 'A square lands on top of its own column. Columns never interact.', aka: 'random deposition' },
{ id: 'bd', slot: 4, name: 'Sticky bricks', cls: 'kpz', sign: 1, v: 2.12, g: 1, fill: 'porous', refW: 5.88, refXi: 9.4,
rule: 'A brick sticks to the first thing it touches, the side of a neighbour included.', aka: 'ballistic deposition' },
{ id: 'rsos', slot: 5, name: 'Picky squares', cls: 'kpz', sign: -1, v: 0.42, g: 1, fill: 'compact', refW: 2.037, refXi: 6.5,
rule: 'A square is kept only if it leaves no step taller than one brick.', aka: 'restricted solid-on-solid' },
{ id: 'fam', slot: 6, name: 'Sliding squares', cls: 'ew', sign: 0, v: 1, g: 1, fill: 'compact', refW: 1.89, refXi: 7.0,
rule: 'A square slides to the lowest of its own column and the two beside it.', aka: 'deposition with relaxation' },
{ id: 'cor', slot: 7, name: 'Corner filling', cls: 'kpz', sign: -1, v: 0.5, g: 1, fill: 'compact', refW: 2.606, refXi: 8.2,
rule: 'A diamond can only drop into a notch between two neighbours.', aka: 'single-step model, TASEP' },
{ id: 'hot', slot: 8, name: 'Hot bricks', cls: 'bc', sign: 0, v: 0.5, g: 1, fill: 'tint', refW: 5.657, refXi: 3.3,
rule: 'Half the time a column gains a brick. Otherwise it jumps to the height of a neighbour.', aka: '0-ballistic deposition' }
];
var BYID = {}, ORDER = {};
MODELS.forEach(function (M, i) { BYID[M.id] = M; ORDER[M.id] = i; });
var CLASSES = {
kpz: { name: 'KPZ', beta: 1 / 3, betaTxt: '1/3', skew: TW_GOE.skew, kurt: TW_GOE.kurt },
ew: { name: 'Edwards–Wilkinson', beta: 1 / 4, betaTxt: '1/4', skew: 0, kurt: 0 },
free: { name: 'independent columns', beta: 1 / 2, betaTxt: '1/2', skew: 0, kurt: 0 },
bc: { name: 'Brownian castle', beta: 1 / 2, betaTxt: '1/2', skew: 0, kurt: 0 }
};
// ================= colour =================
var THEME = {};
function hex(str) {
str = String(str).trim();
if (str[0] === '#') {
if (str.length === 4) str = '#' + str[1] + str[1] + str[2] + str[2] + str[3] + str[3];
var n = parseInt(str.slice(1), 16);
return [(n >> 16) & 255, (n >> 8) & 255, n & 255];
}
var m = str.match(/[\d.]+/g);
return m && m.length >= 3 ? [+m[0], +m[1], +m[2]] : [128, 128, 128];
}
function lin(c) { c /= 255; return c <= 0.04045 ? c / 12.92 : Math.pow((c + 0.055) / 1.055, 2.4); }
function gam(c) { return c <= 0.0031308 ? 12.92 * c : 1.055 * Math.pow(c, 1 / 2.4) - 0.055; }
function toLab(rgb) {
var r = lin(rgb[0]), g = lin(rgb[1]), b = lin(rgb[2]);
var l = Math.cbrt(0.4122214708 * r + 0.5363325363 * g + 0.0514459929 * b);
var m = Math.cbrt(0.2119034982 * r + 0.6806995451 * g + 0.1073969566 * b);
var s = Math.cbrt(0.0883024619 * r + 0.2817188376 * g + 0.6299787005 * b);
return [0.2104542553 * l + 0.7936177850 * m - 0.0040720468 * s, 1.9779984951 * l - 2.4285922050 * m + 0.4505937099 * s, 0.0259040371 * l + 0.7827717662 * m - 0.8086757660 * s];
}
function labToRgb(L, a, b) {
var k = 1, r = 0, g = 0, bl = 0, i, l, m, s;
for (i = 0; i < 24; i++) {
l = L + 0.3963377774 * a * k + 0.2158037573 * b * k; m = L - 0.1055613458 * a * k - 0.0638541728 * b * k; s = L - 0.0894841775 * a * k - 1.2914855480 * b * k;
l = l * l * l; m = m * m * m; s = s * s * s;
r = 4.0767416621 * l - 3.3077115913 * m + 0.2309699292 * s;
g = -1.2684380046 * l + 2.6097574011 * m - 0.3413193965 * s;
bl = -0.0041960863 * l - 0.7034186147 * m + 1.7076147010 * s;
if (r > -0.0005 && r < 1.0005 && g > -0.0005 && g < 1.0005 && bl > -0.0005 && bl < 1.0005) break;
k *= 0.92;
}
return [Math.round(255 * clamp(gam(clamp(r, 0, 1)), 0, 1)), Math.round(255 * clamp(gam(clamp(g, 0, 1)), 0, 1)), Math.round(255 * clamp(gam(clamp(bl, 0, 1)), 0, 1))];
}
function pack(rgb) { return ((255 << 24) | (rgb[2] << 16) | (rgb[1] << 8) | rgb[0]) >>> 0; }
function css(rgb, a) { return a == null ? 'rgb(' + rgb[0] + ',' + rgb[1] + ',' + rgb[2] + ')' : 'rgba(' + rgb[0] + ',' + rgb[1] + ',' + rgb[2] + ',' + a + ')'; }
function mixc(c1, c2, f) { return [Math.round(c1[0] + (c2[0] - c1[0]) * f), Math.round(c1[1] + (c2[1] - c1[1]) * f), Math.round(c1[2] + (c2[2] - c1[2]) * f)]; }
// Each game's bricks are shades of its own hue; lightness cycles with the time a brick landed.
// Two ramps: one for bricks you can see, one with more contrast for piles seen from far away.
function ramp(a0, b0, lo, hi, jit) {
var lut = new Uint32Array(512), cssLut = new Array(512), ph, j, tri, rgb;
for (ph = 0; ph < 128; ph++) {
tri = 0.5 - 0.5 * Math.cos(2 * Math.PI * ph / 128);
for (j = 0; j < 4; j++) {
rgb = labToRgb(lo + (hi - lo) * tri + (j - 1.5) * jit, a0, b0);
lut[ph * 4 + j] = pack(rgb); cssLut[ph * 4 + j] = css(rgb);
}
}
return { px: lut, css: cssLut };
}
function buildLut(M) {
var series = THEME.series[M.slot - 1], base = toLab(series), L0 = base[0], a0 = base[1], b0 = base[2], lo, hi, near, far;
lo = THEME.dark ? clamp(L0 - 0.15, 0.36, 0.6) : clamp(L0 - 0.13, 0.4, 0.66);
hi = THEME.dark ? clamp(L0 + 0.11, 0.6, 0.84) : clamp(L0 + 0.11, 0.64, 0.88);
near = ramp(a0, b0, lo, hi, 0.026);
M.lut = near.px; M.cssLut = near.css;
M.flyCss = css(labToRgb(Math.min(0.93, hi + 0.04), a0 * 0.8, b0 * 0.8));
if (M.fill === 'compact') far = ramp(a0, b0, lo - 0.04, hi + 0.02, 0.012);
else if (THEME.dark) far = ramp(a0, b0, clamp(L0 - 0.04, 0.5, 0.7), clamp(L0 + 0.2, 0.74, 0.92), 0.02);
else far = ramp(a0, b0, clamp(L0 - 0.3, 0.3, 0.5), clamp(L0 - 0.04, 0.5, 0.72), 0.02);
M.lutFar = far.px;
M.under = M.fill === 'compact' ? pack(labToRgb((lo + hi) / 2, a0, b0)) : M.fill === 'tint' ? pack(mixc(THEME.surface, series, 0.17)) : 0;
M.css = css(series);
M.lostPx = pack(mixc(THEME.surface, series, THEME.dark ? 0.42 : 0.34)); // layers too old to have been kept
M.fillCss = css(series, THEME.dark ? 0.2 : 0.14);
}
function readTheme() {
var cs = getComputedStyle(root), i;
function v(n) { return hex(cs.getPropertyValue(n)); }
THEME.surface = v('--surface'); THEME.ink = v('--ink'); THEME.ink3 = v('--ink-3'); THEME.rule = v('--rule'); THEME.ground = v('--ground');
THEME.series = [];
for (i = 1; i <= 8; i++) THEME.series.push(v('--s' + i));
THEME.dark = toLab(THEME.surface)[0] < 0.5;
THEME.surfaceCss = css(THEME.surface); THEME.inkCss = css(THEME.ink); THEME.ruleCss = css(THEME.rule); THEME.groundCss = css(THEME.ground);
THEME.inkFill = css(THEME.ink, 0.1); THEME.inkSoft = css(THEME.ink, 0.8);
THEME.groundPx = pack(THEME.ground);
THEME.shadePx = pack(mixc(THEME.surface, THEME.ink, 0.08));
THEME.famPx = new Uint32Array(NF); THEME.famCss = [];
for (i = 0; i < NF; i++) { // family colours: twelve hues round the wheel, alternately lighter and darker
var hue = (i * 360 / NF + 15) * Math.PI / 180, frgb = labToRgb(i % 2 ? 0.6 : 0.77, 0.14 * Math.cos(hue), 0.14 * Math.sin(hue));
THEME.famPx[i] = pack(frgb); THEME.famCss.push(css(frgb));
}
THEME.sig = cs.getPropertyValue('--surface') + cs.getPropertyValue('--s1');
MODELS.forEach(buildLut);
}
// ================= a pile you can look at: heights plus every brick =================
var CODE = { rd: 0, bd: 1, sq2: 2, tet: 3, rsos: 4, fam: 5, cor: 6, hot: 7 };
var GROUNDV = 0xFFFFFFFF, NF = 12;
// rows of bricks kept per pile; older rows are forgotten. Fewer on small or low-memory devices.
var DEPTH = (Math.min(window.innerWidth || 1024, (window.screen && screen.width) || 1024) < 700 || (navigator.deviceMemory && navigator.deviceMemory < 4)) ? 512 : 1024;
function Vis(id, logL, seed) {
var L = 1 << logL, x, c, prev = 0;
this.id = id; this.code = CODE[id]; this.logL = logL; this.L = L; this.mask = L - 1;
this.h = new Int32Array(L); // true heights
this.hv = new Int32Array(L); // heights as drawn (pieces still falling are not counted)
this.D = DEPTH; this.dmask = DEPTH - 1; // the newest D rows of bricks are kept
this.grid = new Uint32Array(L * this.D); // 0 = empty, otherwise the index of the drop that put a brick there
this.gcol = new Uint8Array(L * this.D); // the colour of the family each of those bricks belongs to
this.fam = new Uint8Array(L); // family colour of the top brick of each column
this.fid = new Uint32Array(L); // and that family's serial number
this.tt = id === 'cor' ? new Uint32Array(L) : null; // corner filling: when each column's top diamond landed
this.top = this.D; this.n = 0; this.s = E.seed4(seed);
this.ms = (seed ^ 0x2545f491) | 0; if (!this.ms) this.ms = 88172645; // a separate random stream for founding families
this.nfam = 0;
this.flights = []; this.cx = new Int32Array(4); this.cy = new Int32Array(4);
for (x = 0; x < L; x++) { // to begin with, every column is a family of its own
c = (prev + 1 + this.rnd(NF - 1)) % NF; prev = c;
this.fam[x] = c; this.fid[x] = ++this.nfam;
}
if (id === 'cor') for (x = 1; x < L; x += 2) { // the floor is a sawtooth, and its teeth are the founders
this.h[x] = 1; this.hv[x] = 1; this.grid[x] = GROUNDV;
this.fam[x - 1] = this.fam[x]; this.fid[x - 1] = this.fid[x];
}
}
Vis.prototype.rnd = function (n) { var m = this.ms; m ^= m << 13; m ^= m >>> 17; m ^= m << 5; this.ms = m; return (m >>> 0) % n; };
Vis.prototype.ensure = function (y) {
while (this.top <= y) { var r = (this.top & this.dmask) * this.L; this.grid.fill(0, r, r + this.L); this.top++; }
};
// Count drops. Pieces whose column lies within `span` of `xa` are animated when `fly` is set.
// Every piece has a parent, the brick it comes to rest on or against, and joins that brick's family;
// with probability mu / 2^32 it founds a new family instead.
Vis.prototype.step = function (count, fly, xa, span, spawnRow, mu) {
var h = this.h, hv = this.hv, g = this.grid, gc = this.gcol, fam = this.fam, fid = this.fid, tt = this.tt;
var L = this.L, mask = this.mask, dmask = this.dmask, D = this.D, sh = 32 - this.logL, s = this.s;
var a = s[0], b = s[1], c = s[2], d = s[3], t = 0, x = 0, i = 0, j = 0, code = this.code, n = this.n, ms = this.ms, nfam = this.nfam;
var OW = E.OW, OB = E.OB, OT = E.OT, OX = E.OX, OY = E.OY, CX = this.cx, CY = this.cy;
var hc = 0, hl = 0, hr = 0, xl = 0, xr = 0, k4 = 0, w = 0, y0 = 0, v = 0, u = 0, y = 0, nc = 0, sx = 0, val = 0, cxj = 0, cyj = 0, ymin = 0;
var px = 0, fx = 0, wd = 1, col = 0, id = 0, q = 0, idx = 0; // px: column of the parent; fx, wd: the columns the piece ends up on top of
for (i = 0; i < count; i++) {
t = (a + b | 0) + d | 0; d = d + 1 | 0; a = b ^ (b >>> 9); b = c + (c << 3) | 0; c = (c << 21) | (c >>> 11); c = c + t | 0;
x = t >>> sh; n++; nc = 0; sx = 0; px = x; fx = x; wd = 1;
switch (code) {
case 0: y = h[x]; h[x] = y + 1; CX[0] = x; CY[0] = y; nc = 1; break;
case 1:
xl = (x - 1) & mask; xr = (x + 1) & mask; hc = h[x] + 1; hl = h[xl]; hr = h[xr];
if (hc < hl || hc < hr) { if (hl >= hr) { hc = hl; px = xl; } else { hc = hr; px = xr; } }
h[x] = hc; CX[0] = x; CY[0] = hc - 1; nc = 1; break;
case 2:
xr = (x + 1) & mask; hc = h[x]; hr = h[xr]; if (hr > hc) { hc = hr; px = xr; }
h[x] = hc + 2; h[xr] = hc + 2; wd = 2;
CX[0] = x; CY[0] = hc; CX[1] = xr; CY[1] = hc; CX[2] = x; CY[2] = hc + 1; CX[3] = xr; CY[3] = hc + 1; nc = 4; break;
case 3:
t = (a + b | 0) + d | 0; d = d + 1 | 0; a = b ^ (b >>> 9); b = c + (c << 3) | 0; c = (c << 21) | (c >>> 11); c = c + t | 0;
k4 = ((t >>> 0) % 28) << 2; w = OW[k4 >> 2]; wd = w;
y0 = h[x] - OB[k4];
for (j = 1; j < w; j++) { v = h[(x + j) & mask] - OB[k4 + j]; if (v > y0) { y0 = v; px = (x + j) & mask; } }
for (j = 0; j < w; j++) h[(x + j) & mask] = y0 + OT[k4 + j];
for (j = 0; j < 4; j++) { CX[j] = (x + OX[k4 + j]) & mask; CY[j] = y0 + OY[k4 + j]; }
nc = 4; break;
case 4:
hc = h[x]; if (hc <= h[(x - 1) & mask] && hc <= h[(x + 1) & mask]) { h[x] = hc + 1; CX[0] = x; CY[0] = hc; nc = 1; }
break;
case 5:
xl = (x - 1) & mask; xr = (x + 1) & mask; hc = h[x]; hl = h[xl]; hr = h[xr]; v = x;
if (hl < hc || hr < hc) {
if (hl < hr) { v = xl; sx = 1; } else if (hr < hl) { v = xr; sx = -1; } else if (t & 1) { v = xl; sx = 1; } else { v = xr; sx = -1; }
}
y = h[v]; h[v] = y + 1; CX[0] = v; CY[0] = y; nc = 1; px = v; fx = v; break;
case 6:
hc = h[x]; xl = (x - 1) & mask; xr = (x + 1) & mask;
if (h[xl] > hc && h[xr] > hc) { // the parent is whichever of the two supporting diamonds arrived later
px = tt[xl] >= tt[xr] ? xl : xr; tt[x] = n >>> 0;
h[x] = hc + 2; CX[0] = x; CY[0] = hc; CX[1] = x; CY[1] = hc + 1; nc = 2;
}
break;
case 7:
u = t & 3;
if (u < 2) h[x] = h[x] + 1; else if (u === 2) { px = (x - 1) & mask; h[x] = h[px]; } else { px = (x + 1) & mask; h[x] = h[px]; }
hv[x] = h[x]; y = h[x] - 1; if (y >= 0) { CX[0] = x; CY[0] = y; nc = 1; }
break;
}
if (nc === 0) { if (code === 7 && px !== x) { fam[x] = fam[px]; fid[x] = fid[px]; } continue; }
col = fam[px]; id = fid[px];
if (mu) {
ms ^= ms << 13; ms ^= ms >>> 17; ms ^= ms << 5;
if ((ms >>> 0) < mu) { // a founder: give it a colour unlike its parent's and its neighbours'
q = (col + 1 + ((ms >>> 9) % (NF - 1))) % NF;
if (q === fam[(fx - 1) & mask] || q === fam[(fx + wd) & mask]) { q = (q + 1) % NF; if (q === col) q = (q + 1) % NF; }
col = q; id = ++nfam;
}
}
for (j = 0; j < wd; j++) { cxj = (fx + j) & mask; fam[cxj] = col; fid[cxj] = id; }
val = n >>> 0;
if (fly && code !== 7 && ((x - xa) & mask) <= span) {
ymin = CY[0]; for (j = 1; j < nc; j++) if (CY[j] < ymin) ymin = CY[j];
this.flights.push({ x: Array.prototype.slice.call(CX, 0, nc), y: Array.prototype.slice.call(CY, 0, nc), nc: nc, val: val, col: col, sx: sx, drop: Math.max(1, spawnRow - ymin) });
continue;
}
for (j = 0; j < nc; j++) {
cyj = CY[j]; cxj = CX[j];
if (cyj >= this.top) this.ensure(cyj);
if (cyj >= this.top - D) { idx = (cyj & dmask) * L + cxj; g[idx] = val; gc[idx] = col; }
if (code !== 7 && cyj + 1 > hv[cxj]) hv[cxj] = cyj + 1;
}
}
s[0] = a; s[1] = b; s[2] = c; s[3] = d; this.n = n; this.ms = ms; this.nfam = nfam;
};
// let falling pieces drop by `rows`; those that arrive become part of the pile
Vis.prototype.fall = function (rows) {
var F = this.flights, i = 0, f, j, x, y, idx;
while (i < F.length) {
f = F[i]; f.drop -= rows;
if (f.drop <= 0) {
for (j = 0; j < f.nc; j++) {
x = f.x[j]; y = f.y[j];
if (y >= this.top) this.ensure(y);
if (y >= this.top - this.D) { idx = (y & this.dmask) * this.L + x; this.grid[idx] = f.val; this.gcol[idx] = f.col; }
if (y + 1 > this.hv[x]) this.hv[x] = y + 1;
}
F[i] = F[F.length - 1]; F.pop();
} else i++;
}
};
Vis.prototype.rough = function () {
var h = this.h, L = this.L, s = 0, s2 = 0, x, dd, m;
for (x = 0; x < L; x++) s += h[x];
m = s / L;
for (x = 0; x < L; x++) { dd = h[x] - m; s2 += dd * dd; }
return Math.sqrt(s2 / L);
};
// how many different families hold the tops of `cols` columns starting at x0
Vis.prototype.families = function (x0, cols) {
var fid = this.fid, mask = this.mask, c, k = 1;
for (c = 1; c < cols; c++) if (fid[(x0 + c) & mask] !== fid[(x0 + c - 1) & mask]) k++;
return k;
};
// Share of the area under the surface that is brick. What is left is gaps, sealed in for good: nothing gets under the surface.
// 1 for the games that leave no gaps, -1 for hot bricks, which is not a pile of anything.
Vis.prototype.brick = function () {
var c = this.code, h = this.h, L = this.L, s = 0, x;
if (c === 7) return -1;
if (c !== 1 && c !== 2 && c !== 3) return 1;
for (x = 0; x < L; x++) s += h[x];
return s > 0 ? Math.min(1, (c === 1 ? 1 : 4) * this.n / s) : 1; // every drop lands: one cell for a sticky brick, four for the others
};
function shareText(b) {
if (b < 0) return '';
if (b >= 1) return '100% brick · no gaps';
var a = Math.round(1000 * b) / 10;
return fnum(a, 1) + '% brick · ' + fnum(100 - a, 1) + '% gaps';
}
// ================= shared bits of interface =================
function buildChips(host, sel, onChange) {
MODELS.forEach(function (M) {
var b = mk('button', 'chip'); b.type = 'button';
b.setAttribute('aria-pressed', sel.indexOf(M.id) >= 0 ? 'true' : 'false');
var k = mk('span', 'key'); k.style.setProperty('--c', 'var(--s' + M.slot + ')');
b.appendChild(k); b.appendChild(doc.createTextNode(M.name));
b.addEventListener('click', function () {
var i = sel.indexOf(M.id);
if (i >= 0) { if (sel.length === 1) return; sel.splice(i, 1); } else sel.push(M.id);
sel.sort(function (p, q) { return ORDER[p] - ORDER[q]; });
b.setAttribute('aria-pressed', i >= 0 ? 'false' : 'true');
onChange();
});
host.appendChild(b);
});
}
function segmented(host, attr, onPick) {
var segs = host.querySelectorAll('button');
Array.prototype.forEach.call(segs, function (b) {
b.addEventListener('click', function () {
Array.prototype.forEach.call(segs, function (o) { o.setAttribute('aria-pressed', o === b ? 'true' : 'false'); });
onPick(b.dataset[attr]);
});
});
}
function watchSize(stage, cv, cb) {
function apply(w, h) {
w = Math.max(1, Math.round(w)); h = Math.max(1, Math.round(h));
if (cv.width !== w || cv.height !== h) { cv.width = w; cv.height = h; }
cb();
}
if (!window.ResizeObserver) { var r0 = stage.getBoundingClientRect(); apply(r0.width * DPR, r0.height * DPR); return null; }
var ro = new ResizeObserver(function (entries) {
var e = entries[entries.length - 1];
if (e.devicePixelContentBoxSize && e.devicePixelContentBoxSize[0]) apply(e.devicePixelContentBoxSize[0].inlineSize, e.devicePixelContentBoxSize[0].blockSize);
else { var r = stage.getBoundingClientRect(); DPR = window.devicePixelRatio || 1; apply((r.width - 2) * DPR, (r.height - 2) * DPR); }
});
try { ro.observe(stage, { box: 'device-pixel-content-box' }); } catch (err) { ro.observe(stage); }
return ro;
}
function onScreen(el, cb) {
if (!window.IntersectionObserver) { cb(true); return; }
new IntersectionObserver(function (es) { cb(es[es.length - 1].isIntersecting); }, { rootMargin: '80px' }).observe(el);
}
function panelShell(M, withRule) {
var art = mk('article', 'panel');
var head = mk('header', 'panel-head');
var key = mk('span', 'key'); key.style.setProperty('--c', 'var(--s' + M.slot + ')');
var name = mk('h3', null, M.name), ro = mk('span', 'readout');
head.appendChild(key); head.appendChild(name); head.appendChild(ro);
var stage = mk('div', 'stage'), cv = doc.createElement('canvas'), share = mk('span', 'share');
cv.setAttribute('role', 'img');
share.title = 'How much of the area under the surface is brick, and how much is gaps. A gap is sealed in for good: nothing can get under the surface.';
stage.appendChild(cv); stage.appendChild(share);
art.appendChild(head); art.appendChild(stage);
if (withRule) {
var rule = mk('p', 'rule', M.rule);
if (M.aka) { rule.appendChild(doc.createTextNode(' ')); rule.appendChild(mk('span', 'aka', '(' + M.aka + ')')); }
art.appendChild(rule);
}
return { M: M, art: art, key: key, name: name, ro: ro, share: share, stage: stage, cv: cv, ctx: cv.getContext('2d') };
}
function speedLabel(pow) { var m = Math.pow(2, pow / 2); return '×' + (m >= 10 ? Math.round(m) : m >= 1 ? +m.toFixed(1) : +m.toFixed(2)); }
// ================= a view: a row of panels, each showing one pile =================
// Figure 1 colours bricks by age, the family-tree figure by family; both are views.
function zoomList() {
var out = [], minDev = Math.max(1, Math.round(DPR));
[26, 20, 16, 13, 10, 8, 6, 5, 4, 3, 2, 1].forEach(function (s) { var dv = Math.max(minDev, Math.round(s * DPR)); if (out.indexOf(dv) < 0) out.push(dv); });
return out;
}
function makeView(o) {
return { ids: o.ids, host: o.host, withRule: o.withRule, color: o.color, visible: o.visible, onFirstSize: null,
panels: [], running: !reduceMotion, zooms: zoomList(), cell: 13, speed: 0, tick: 0, sized: false };
}
function viewGeom(V, P) {
var cs = V.cell, s = cs / DPR, cells = (P.M.id === 'tet' || P.M.id === 'sq2') ? 4 : P.M.id === 'cor' ? 2 : 1;
P.rows = P.cv.height / cs; P.cols = P.cv.width / cs;
P.fs = s >= 9 ? 0.5 : s <= 2 ? 0.72 : 0.72 - (s - 2) / 7 * 0.22;
P.kph = 128 / (clamp(P.rows * (s >= 5 ? 0.42 : 0.24), 5, 400) / P.M.v * P.sim.L);
// new families: a few dozen for every screenful of bricks, whatever the zoom
P.mu = Math.floor(clamp(60 * cells / (P.cols * P.rows * 0.5), 1 / 8000, 0.2) * 4294967296);
P.snap = true; P.dirty = true;
}
function viewStart(V, P, pregrow) {
P.sim = new Vis(P.M.id, 11, rseed());
P.acc = 0;
viewGeom(V, P);
if (pregrow) P.sim.step(Math.round((P.rows * P.fs * 0.9 / P.M.v) * P.sim.L), false, 0, 0, 0, P.mu);
P.yb = 0; P.snap = true; P.dirty = true; P.roStale = true;
}
function viewBuild(V) {
var host = $(V.host), keep = {};
V.panels.forEach(function (P) { keep[P.M.id] = P; });
V.panels = V.ids.map(function (id) {
var P = keep[id];
if (P) { delete keep[id]; return P; }
P = panelShell(BYID[id], V.withRule);
P.cv.setAttribute('aria-label', BYID[id].name + (V.color === 'fam' ? ': a pile with every brick coloured by its family' : ': a pile growing under this rule'));
P.off = doc.createElement('canvas'); P.offctx = P.off.getContext('2d');
P.fresh = true;
return P;
});
Object.keys(keep).forEach(function (id) { if (keep[id].ro_) keep[id].ro_.disconnect(); keep[id].art.remove(); });
V.panels.forEach(function (P) { host.appendChild(P.art); });
host.dataset.count = V.panels.length;
V.panels.forEach(function (P) {
if (!P.fresh) return;
P.fresh = false;
P.ro_ = watchSize(P.stage, P.cv, function () {
if (P.cv.width < 48 || P.cv.height < 32) return; // not laid out yet (a hidden tab, say): wait for a real size
if (!V.sized) { V.sized = true; if (V.onFirstSize) V.onFirstSize(P); }
if (!P.sim) viewStart(V, P, true); else viewGeom(V, P);
});
});
}
function viewAdvance(V, P, dt) {
var sim = P.sim, cs = V.cell, s = cs / DPR, mask = sim.mask;
var rate = 12 * Math.pow(14 / s, 0.6) * Math.pow(2, V.speed / 2) / (s * P.M.v); // time units per second
var want = rate * sim.L * dt + P.acc, n = Math.floor(want);
P.acc = want - n;
var fly = !reduceMotion && s >= 5 && rate * P.cols <= 60 && P.M.id !== 'hot';
if (!fly && sim.flights.length) sim.fall(1e9);
var cols = Math.ceil(P.cols) + 1, xa = ((sim.L >> 1) - (cols >> 1) - 3) & mask, spawn = Math.floor(P.yb) + Math.ceil(P.rows) + 2;
var t0 = performance.now(), c;
while (n > 0) {
c = n > 4096 ? 4096 : n;
sim.step(c, fly, xa, cols + 2, spawn, P.mu); n -= c;
if (performance.now() - t0 > 5) { P.acc = 0; break; }
}
if (sim.flights.length) sim.fall(Math.max(20, P.rows * 1.3) * dt);
if (sim.n > 4.2e9) viewStart(V, P, false);
P.dirty = true;
}
function viewCamera(V, P, dt) {
var sim = P.sim, hv = sim.hv, mask = sim.mask, cols = Math.ceil(P.cols) + 1, x0 = (sim.L >> 1) - (cols >> 1), c, sum = 0, hmax = 0, hx;
for (c = 0; c < cols; c++) { hx = hv[(x0 + c) & mask]; sum += hx; if (hx > hmax) hmax = hx; }
// keep the mean surface at a fixed level, lower if that is what it takes to keep the peaks in view
var target = Math.max(-1.5, Math.min(sum / cols - P.rows * P.fs, Math.max(hmax - P.rows * 0.92, sum / cols - P.rows * 0.8)));
if (P.snap) { P.yb = target; P.snap = false; }
else if (Math.abs(target - P.yb) > 1e-3) {
// ease towards the surface, but never let a fast-growing pile run away from the view
var lim = P.rows * 0.05;
P.yb += (target - P.yb) * (1 - Math.exp(-dt / 0.3));
if (target - P.yb > lim) P.yb = target - lim; else if (P.yb - target > 2 * lim) P.yb = target + 2 * lim;
P.dirty = true;
}
}
function drawPanel(V, P) {
var sim = P.sim, M = P.M, ctx = P.ctx, W = P.cv.width, H = P.cv.height, cs = V.cell;
if (!sim || W < 2 || H < 2) return;
var cols = Math.ceil(W / cs) + 1, rows = Math.ceil(H / cs) + 1;
var L = sim.L, mask = sim.mask, dmask = sim.dmask, g = sim.grid, gc = sim.gcol, hv = sim.hv, top = sim.top, lo = top - sim.D;
var xLeft = (L >> 1) - (cols >> 1);
var ybC = Math.floor(P.yb), fy = Math.round((P.yb - ybC) * cs);
var offX = Math.floor((W - cols * cs) / 2);
var minDev = Math.max(1, Math.round(DPR));
var diamonds = M.id === 'cor' && cs >= 6 * minDev;
var bricks = cs >= 5 * minDev;
var byFam = V.color === 'fam', famPx = THEME.famPx, famCss = THEME.famCss;
var gw = cs >= 12 * minDev ? Math.max(1, Math.round(DPR * 1.25)) : Math.max(1, Math.round(DPR * 0.75)), gh = (gw % 2) ? 0.5 : 0;
var lw = bricks ? Math.max(1, Math.round(DPR * (cs >= 8 * minDev ? 1.6 : 1))) : Math.max(1, Math.floor(DPR * 0.75)), lh = (lw % 2) ? 0.5 : 0;
var lut = bricks ? M.lut : M.lutFar, kph = P.kph;
var r, c, y, o, v, base, x, X, Y, i, j, f, lat;
function cell(cc, yy) { return yy < 0 ? GROUNDV : (yy >= top || yy < lo) ? 0 : g[(yy & dmask) * L + ((xLeft + cc) & mask)]; }
function shade(vv) { return ((((vv * kph) | 0) & 127) << 2) + (Math.imul(vv, 0x9E3779B1) >>> 30); }
ctx.setTransform(1, 0, 0, 1, 0, 0);
ctx.clearRect(0, 0, W, H);
if (!diamonds) {
if (P.off.width !== cols || P.off.height !== rows || !P.px) {
P.off.width = cols; P.off.height = rows;
P.img = P.offctx.createImageData(cols, rows); P.px = new Uint32Array(P.img.data.buffer);
}
var px = P.px, GC = THEME.groundPx, under = byFam ? (M.under ? THEME.shadePx : 0) : M.under;
for (r = 0; r < rows; r++) {
y = ybC + rows - 1 - r; o = r * cols;
if (y < 0) { px.fill(GC, o, o + cols); continue; }
if (y >= top) { px.fill(0, o, o + cols); continue; }
if (y < lo) { // older than the rows that are kept: a flat band
var lostC = under || (byFam ? THEME.shadePx : M.lostPx);
for (c = 0; c < cols; c++) px[o + c] = y < hv[(xLeft + c) & mask] ? lostC : 0;
continue;
}
base = (y & dmask) * L;
if (byFam) {
for (c = 0; c < cols; c++) {
x = (xLeft + c) & mask; v = g[base + x];
px[o + c] = v === 0 ? ((under && y < hv[x]) ? under : 0) : v === GROUNDV ? GC : famPx[gc[base + x]];
}
} else {
for (c = 0; c < cols; c++) {
x = (xLeft + c) & mask; v = g[base + x];
if (v === 0) px[o + c] = (under && y < hv[x]) ? under : 0;
else if (v === GROUNDV) px[o + c] = GC;
else px[o + c] = lut[((((v * kph) | 0) & 127) << 2) + (Math.imul(v, 0x9E3779B1) >>> 30)];
}
}
}
P.offctx.putImageData(P.img, 0, 0);
ctx.imageSmoothingEnabled = false;
ctx.drawImage(P.off, 0, 0, cols, rows, offX, H + fy - rows * cs, cols * cs, rows * cs);
if (bricks) { // a sliver of background between different pieces
var vr, vu;
ctx.beginPath();
for (r = 0; r < rows; r++) {
y = ybC + rows - 1 - r;
if (y < -1 || y > top) continue;
Y = H + fy - (y + 1 - ybC) * cs;
for (c = -1; c < cols; c++) {
v = cell(c, y); vr = cell(c + 1, y); vu = cell(c, y + 1);
if (v !== vr) { X = offX + (c + 1) * cs + gh; ctx.moveTo(X, Y); ctx.lineTo(X, Y + cs); }
if (v !== vu) { ctx.moveTo(offX + c * cs, Y + gh); ctx.lineTo(offX + (c + 1) * cs, Y + gh); }
}
}
ctx.lineWidth = gw; ctx.strokeStyle = THEME.surfaceCss; ctx.stroke();
}
ctx.beginPath(); // the surface h(x, t)
for (c = -1; c <= cols; c++) {
Y = H + fy - (hv[(xLeft + c) & mask] - ybC) * cs + lh; X = offX + c * cs + lh;
if (c === -1) ctx.moveTo(X, Y); else ctx.lineTo(X, Y);
ctx.lineTo(X + cs, Y);
}
ctx.lineWidth = lw; ctx.lineJoin = 'miter'; ctx.strokeStyle = bricks ? THEME.inkCss : THEME.inkSoft; ctx.stroke();
if (sim.flights.length) {
var inset = bricks ? gw * 0.5 : 0;
ctx.fillStyle = M.flyCss;
for (i = 0; i < sim.flights.length; i++) {
f = sim.flights[i]; lat = f.sx ? f.sx * Math.min(1, f.drop) : 0;
if (byFam) ctx.fillStyle = famCss[f.col];
for (j = 0; j < f.nc; j++) {
c = (f.x[j] - xLeft) & mask; if (c > cols + 4) c -= L;
if (c < -5) continue;
ctx.fillRect(offX + (c + lat) * cs + inset, H + fy - (f.y[j] + 1 + f.drop - ybC) * cs + inset, cs - 2 * inset, cs - 2 * inset);
}
}
}
} else {
var Y0 = H + fy + ybC * cs, cssLut = M.cssLut, yTo = Math.min(top - 1, ybC + rows + 1), base2;
if (Y0 - cs < H + 2) { // the floor: a sawtooth
ctx.beginPath(); ctx.moveTo(offX - 2 * cs, H + 4);
for (c = -2; c <= cols + 1; c++) ctx.lineTo(offX + (c + 0.5) * cs, (((xLeft + c) & mask) & 1) ? Y0 - cs : Y0);
ctx.lineTo(offX + (cols + 2) * cs, H + 4); ctx.closePath();
ctx.fillStyle = THEME.groundCss; ctx.fill();
}
ctx.lineWidth = gw; ctx.strokeStyle = THEME.surfaceCss; ctx.lineJoin = 'round';
for (y = Math.max(0, ybC - 2, lo); y < yTo; y++) {
base = (y & dmask) * L; base2 = ((y + 1) & dmask) * L;
for (c = -1; c <= cols; c++) {
x = (xLeft + c) & mask; v = g[base + x];
if (v === 0 || v === GROUNDV || g[base2 + x] !== v) continue;
X = offX + (c + 0.5) * cs; Y = H + fy - (y + 1 - ybC) * cs;
ctx.beginPath(); ctx.moveTo(X - cs, Y); ctx.lineTo(X, Y - cs); ctx.lineTo(X + cs, Y); ctx.lineTo(X, Y + cs); ctx.closePath();
ctx.fillStyle = byFam ? famCss[gc[base + x]] : cssLut[shade(v)]; ctx.fill(); ctx.stroke();
}
}
ctx.beginPath();
for (c = -2; c <= cols + 1; c++) {
X = offX + (c + 0.5) * cs; Y = H + fy - (hv[(xLeft + c) & mask] - ybC) * cs;
if (c === -2) ctx.moveTo(X, Y); else ctx.lineTo(X, Y);
}
ctx.lineWidth = lw; ctx.strokeStyle = THEME.inkCss; ctx.stroke();
ctx.fillStyle = M.flyCss;
for (i = 0; i < sim.flights.length; i++) {
f = sim.flights[i];
c = (f.x[0] - xLeft) & mask; if (c > cols + 4) c -= L;
if (c < -5) continue;
if (byFam) ctx.fillStyle = famCss[f.col];
X = offX + (c + 0.5) * cs; Y = H + fy - (f.y[0] + 1 + f.drop - ybC) * cs;
ctx.beginPath(); ctx.moveTo(X - cs, Y); ctx.lineTo(X, Y - cs); ctx.lineTo(X + cs, Y); ctx.lineTo(X, Y + cs); ctx.closePath(); ctx.fill();
}
}
P.dirty = false;
}
function viewFrame(V, dt) {
V.tick++;
V.panels.forEach(function (P) {
if (!P.sim) return;
if (!V.visible && !P.dirty) return; // off screen and already drawn: nothing to do
if (V.visible && V.running) viewAdvance(V, P, dt);
viewCamera(V, P, dt);
if (P.dirty) drawPanel(V, P);
if (V.tick % 12 === 0 || P.roStale) {
var tm = P.sim.n / P.sim.L, txt = 't = ' + fnum(tm, tm < 100 ? 1 : 0), cols, k;
if (V.color === 'fam') {
cols = Math.max(1, Math.ceil(P.cols)); k = P.sim.families((P.sim.L >> 1) - (cols >> 1), cols);
txt += ' \u00b7 ' + k + (k === 1 ? ' family' : ' families') + ' on top';
} else txt += ' \u00b7 W = ' + fnum(P.sim.rough(), 1);
P.ro.textContent = txt; P.roStale = false;
if (P.share) { txt = shareText(P.sim.brick()); if (P.share.textContent !== txt) P.share.textContent = txt; }
}
});
}
function viewRedraw(V) { V.panels.forEach(function (P) { P.dirty = true; P.roStale = true; }); }
function viewRezoom(V) { V.panels.forEach(function (P) { if (P.sim) { P.sim.fall(1e9); viewGeom(V, P); P.px = null; } }); }
// ================= figure 1: the games =================
var hero = makeView({ ids: ['tet', 'sq2', 'rd', 'bd'], host: 'g-panels', withRule: true, color: 'age', visible: true });
function heroInit() {
var zoom = $('g-zoom'), zout = $('g-zoom-out'), speed = $('g-speed'), sout = $('g-speed-out'), play = $('g-play');
zoom.max = hero.zooms.length - 1;
function zlabel() { var s = hero.cell / DPR; zout.textContent = '1 brick = ' + (s >= 3 ? Math.round(s) : +s.toFixed(1)) + ' px'; }
hero.pickZoom = function (cssPx) {
var zi = 0, best = 1e9;
hero.zooms.forEach(function (dv, i) { var e = Math.abs(dv / DPR - cssPx); if (e < best) { best = e; zi = i; } });
hero.cell = hero.zooms[zi]; zoom.value = zi; zlabel();
};
hero.pickZoom(13); hero.zlabel = zlabel;
hero.onFirstSize = function (P) { hero.pickZoom(clamp(P.cv.width / DPR / 42, 8, 13)); }; // narrow panels start with smaller bricks
zoom.addEventListener('input', function () { hero.cell = hero.zooms[clamp(Math.round(+zoom.value) || 0, 0, hero.zooms.length - 1)]; zlabel(); viewRezoom(hero); });
speed.addEventListener('input', function () { hero.speed = +speed.value; sout.textContent = speedLabel(hero.speed); });
play.textContent = hero.running ? 'Pause' : 'Play';
play.addEventListener('click', function () { hero.running = !hero.running; play.textContent = hero.running ? 'Pause' : 'Play'; });
$('g-reset').addEventListener('click', function () { hero.panels.forEach(function (P) { viewStart(hero, P, false); }); });
segmented($('g-color'), 'color', function (c) { hero.color = c; viewRedraw(hero); });
buildChips($('g-chips'), hero.ids, function () { viewBuild(hero); });
sout.textContent = speedLabel(hero.speed);
viewBuild(hero);
onScreen($('g-panels'), function (v) { hero.visible = v; });
window.addEventListener('resize', function () {
var now = window.devicePixelRatio || 1;
if (Math.abs(now - DPR) < 0.01) return;
var css = hero.cell / DPR;
DPR = now; hero.zooms = zoomList(); zoom.max = hero.zooms.length - 1; hero.pickZoom(css); viewRezoom(hero);
fams.zooms = zoomList(); fams.cell = fams.zooms[fams.zooms.length - 1]; viewRezoom(fams);
lens.redraw = true;
});
}
// ================= figure 4: family trees =================
var fams = makeView({ ids: ['tet', 'bd', 'cor', 'hot'], host: 'f-panels', withRule: false, color: 'fam', visible: false });
function famsInit() {
var speed = $('f-speed'), sout = $('f-speed-out'), play = $('f-play');
fams.cell = fams.zooms[fams.zooms.length - 1]; // always seen from far away
speed.addEventListener('input', function () { fams.speed = +speed.value; sout.textContent = speedLabel(fams.speed); });
play.textContent = fams.running ? 'Pause' : 'Play';
play.addEventListener('click', function () { fams.running = !fams.running; play.textContent = fams.running ? 'Pause' : 'Play'; });
$('f-reset').addEventListener('click', function () { fams.panels.forEach(function (P) { viewStart(fams, P, false); }); });
buildChips($('f-chips'), fams.ids, function () { viewBuild(fams); });
sout.textContent = speedLabel(fams.speed);
viewBuild(fams);
onScreen($('f-panels'), function (v) { fams.visible = v; });
}
// ================= figure 4, second part: a gap in the making =================
// One family is given a head start: a solid block under the left of the picture. Its pile spreads over the lower one,
// and the gap between the two is a wedge. `slope` holds the long-run averages, in rows per column: roof, then floor.
// `fit` sets the height of the block (rows / fit) and `left` how much of the block stays in view.
var cliff = { ids: ['bd', 'tet', 'sq2'], panels: [], running: !reduceMotion, visible: false, speed: 0, B: 256,
slope: { bd: [1.59, 2.14], tet: [4.2, 5.26], sq2: [6.9, 8.12] },
fit: { bd: 4.6, tet: 6, sq2: 7.6 }, left: { bd: 0.12, tet: 0.3, sq2: 0.36 } };
function cliffGeom(P) {
var s = Math.max(1, Math.round(DPR * 0.67)), W = P.cv.width, H = P.cv.height;
// bricks as fine as a sharp screen can show, but never a picture taller than the rows a pile remembers
while (Math.floor(H / s) > DEPTH / 1.4 || Math.floor(W / s) > 440) s++;
P.s = s; P.cols = Math.floor(W / s); P.rows = Math.floor(H / s);
P.left = Math.max(4, Math.round(P.cols * cliff.left[P.M.id]));
P.step = Math.max(10, Math.round(P.rows / cliff.fit[P.M.id]));
P.total = P.rows / P.M.v; // time for the lower pile to reach the top of the picture
}
function cliffStart(P, frac) {
var sim = P.sim = new Vis(P.M.id, 10, rseed()), L = sim.L, B = cliff.B, x, y;
for (x = 0; x < L; x++) { sim.fam[x] = x < B ? 0 : 1; sim.fid[x] = x < B ? 1 : 2; } // family 1 starts on the block
sim.nfam = 2;
for (x = 0; x < B; x++) { sim.h[x] = sim.hv[x] = P.step; for (y = 0; y < P.step; y++) sim.grid[y * L + x] = GROUNDV; }
P.acc = 0; P.done = false; P.hold = 0; P.edge = 0; P.open = true; P.shut = 0;
P.fitN = 0; P.sk = 0; P.skk = 0; P.sr = 0; P.skr = 0; P.sf = 0; P.skf = 0;
if (frac > 0) { sim.step(Math.round(frac * P.total * L), false, 0, 0, 0, 0); cliffTrack(P); cliffDone(P); }
P.dirty = true; P.roStale = true;
}
// follow the edge of the overhang: each newly covered column gives one point of the roof and one of the floor
function cliffTrack(P) {
var sim = P.sim, L = sim.L, g = sim.grid, gc = sim.gcol, dm = sim.dmask, kmax = P.cols - P.left - 1, x, r, f, i, k, top;
while (P.open && P.edge < kmax) {
x = cliff.B + P.edge;
if (sim.fid[x] !== 1) break; // not covered yet
top = sim.h[x];
for (r = 0; r < top; r++) { i = (r & dm) * L + x; if (g[i] !== 0 && gc[i] === 0) break; } // lowest brick of the upper family: the roof
for (f = r; f > 0 && g[((f - 1) & dm) * L + x] === 0; f--) { /* down through the gap to the lower pile */ }
k = P.edge++;
if (r - f <= 2) { if (++P.shut >= 3) P.open = false; } else P.shut = 0; // roof and floor have met
if (k >= 2 && P.open) { P.fitN++; P.sk += k; P.skk += k * k; P.sr += r; P.skr += k * r; P.sf += f; P.skf += k * f; }
}
}
function cliffDone(P) {
var sim = P.sim, x0 = cliff.B, x1 = cliff.B + P.cols - P.left, x, low = 1e9;
for (x = x0; x < x1; x++) if (sim.h[x] < low) low = sim.h[x];
if (low >= P.rows || sim.n / sim.L > 1.5 * P.total) { P.done = true; P.hold = 2.5; }
}
function cliffSlopes(P) {
var n = P.fitN, den = n * P.skk - P.sk * P.sk;
return n >= 6 && den > 0 ? [(n * P.skr - P.sk * P.sr) / den, (n * P.skf - P.sk * P.sf) / den] : null;
}
function cliffDraw(P) {
var sim = P.sim, ctx = P.ctx, W = P.cv.width, H = P.cv.height, s = P.s, cols = P.cols, rows = P.rows;
if (!sim || W < 2 || H < 2) return;
if (P.off.width !== cols || P.off.height !== rows || !P.px) {
P.off.width = cols; P.off.height = rows;
P.img = P.offctx.createImageData(cols, rows); P.px = new Uint32Array(P.img.data.buffer);
}
var px = P.px, L = sim.L, g = sim.grid, gc = sim.gcol, dm = sim.dmask, top = sim.top, lo = top - sim.D, x0 = cliff.B - P.left;
var up = pack(THEME.series[P.M.slot - 1]), low = pack(mixc(THEME.surface, THEME.ink, THEME.dark ? 0.44 : 0.36)), GC = THEME.groundPx;
var r, c, y, o, base, v;
for (r = 0; r < rows; r++) {
y = rows - 1 - r; o = r * cols;
if (y >= top || y < lo) { px.fill(0, o, o + cols); continue; }
base = (y & dm) * L + x0;
for (c = 0; c < cols; c++) { v = g[base + c]; px[o + c] = v === 0 ? 0 : v === GROUNDV ? GC : gc[base + c] === 0 ? up : low; }
}
P.offctx.putImageData(P.img, 0, 0);
ctx.setTransform(1, 0, 0, 1, 0, 0);
ctx.clearRect(0, 0, W, H);
ctx.imageSmoothingEnabled = false;
ctx.drawImage(P.off, 0, 0, cols, rows, 0, H - rows * s, cols * s, rows * s);
// the average roof (solid) and the average floor (dashed), from the two corners of the block to where they meet
var sl = cliff.slope[P.M.id], kc = Math.min(P.step / (sl[1] - sl[0]), cols - P.left), X0 = P.left * s, lw = Math.max(1, Math.round(1.25 * DPR));
ctx.strokeStyle = THEME.inkCss; ctx.lineWidth = lw; ctx.lineCap = 'butt';
ctx.beginPath(); ctx.moveTo(X0, H - P.step * s); ctx.lineTo(X0 + kc * s, H - (P.step + sl[0] * kc) * s); ctx.stroke();
ctx.setLineDash([5 * DPR, 4 * DPR]);
ctx.beginPath(); ctx.moveTo(X0, H); ctx.lineTo(X0 + kc * s, H - sl[1] * kc * s); ctx.stroke();
ctx.setLineDash([]);
P.dirty = false;
}
function cliffFrame(dt) {
cliff.panels.forEach(function (P) {
var sim = P.sim, want, n, c, t0, sl, tm;
if (!sim) return;
if (!cliff.visible && !P.dirty) return;
if (cliff.visible && cliff.running) {
if (P.done) { P.hold -= dt; if (P.hold <= 0) cliffStart(P, 0); }
else {
want = P.total / 13 * Math.pow(2, cliff.speed / 2) * sim.L * dt + P.acc; n = Math.floor(want); P.acc = want - n;
t0 = performance.now();
while (n > 0) {
c = n > 2048 ? 2048 : n;
sim.step(c, false, 0, 0, 0, 0); n -= c;
if (performance.now() - t0 > 4) { P.acc = 0; break; }
}
cliffTrack(P); cliffDone(P);
P.dirty = true; P.roStale = P.roStale || (++P.tick % 10 === 0);
}
sim = P.sim;
}
if (P.dirty) cliffDraw(P);
if (P.roStale) {
tm = sim.n / sim.L; sl = cliffSlopes(P);
P.ro.textContent = 't = ' + fnum(tm, tm < 100 ? 1 : 0);
P.runA.textContent = sl ? 'roof ' + fnum(sl[0], 1) : 'just starting';
P.runB.textContent = sl ? 'floor ' + fnum(sl[1], 1) : '';
P.roStale = false;
}
});
}
function cliffInit() {
var host = $('w-panels'), speed = $('w-speed'), sout = $('w-speed-out'), play = $('w-play');
if (!host) return;
cliff.ids.forEach(function (id) {
var P = panelShell(BYID[id], false);
P.cv.setAttribute('aria-label', BYID[id].name + ' growing beside a cliff: the pile on the block spreads over the lower pile and leaves a wedge-shaped gap');
P.off = doc.createElement('canvas'); P.offctx = P.off.getContext('2d'); P.tick = 0;
P.meter = mk('p', 'meter'); P.meter.appendChild(mk('span', 'dim', 'This run:'));
P.runA = mk('span', null, ''); P.runB = mk('span', null, '');
P.meter.appendChild(P.runA); P.meter.appendChild(P.runB);
P.art.appendChild(P.meter);
host.appendChild(P.art);
cliff.panels.push(P);
P.ro_ = watchSize(P.stage, P.cv, function () {
if (P.cv.width < 48 || P.cv.height < 64) return; // not laid out yet
cliffGeom(P);
cliffStart(P, reduceMotion ? 1.2 : 0.45); // never an empty picture: start part of the way in
});
});
speed.addEventListener('input', function () { cliff.speed = +speed.value; sout.textContent = speedLabel(cliff.speed); });
sout.textContent = speedLabel(cliff.speed);
play.textContent = cliff.running ? 'Pause' : 'Play';
play.addEventListener('click', function () { cliff.running = !cliff.running; play.textContent = cliff.running ? 'Pause' : 'Play'; });
$('w-reset').addEventListener('click', function () { cliff.panels.forEach(function (P) { if (P.sim) cliffStart(P, 0); }); });
onScreen(host, function (v) { cliff.visible = v; });
}
// ================= workers =================
var WORKER_URL = null, WORKERS_OK = false;
var WORKER_SRC = ENGINE.toString() + ';var E=ENGINE();var r=E.makeRunner(function(m,t){postMessage(m,t||[]);},40);onmessage=function(e){r.handle(e.data);};';
function probeWorkers(cb) { // workers may be unavailable; everything also runs, smaller, on the page itself
var done = false, w = null;
function finish(ok) { if (done) return; done = true; WORKERS_OK = ok; if (w) { try { w.terminate(); } catch (e) { /* gone already */ } } cb(); }
try {
WORKER_URL = URL.createObjectURL(new Blob([WORKER_SRC], { type: 'text/javascript' }));
w = new Worker(WORKER_URL);
w.onmessage = function () { finish(true); };
w.onerror = function () { finish(false); };
w.postMessage({ cmd: 'ping' });
setTimeout(function () { finish(false); }, 2500);
} catch (err) { finish(false); }
}
function spawn(sliceMs) {
if (!WORKERS_OK) return inlineRunner(sliceMs);
var fn = null, dead = false, w = new Worker(WORKER_URL);
w.onmessage = function (e) { if (fn && !dead) fn(e.data); };
return {
real: true,
post: function (m) { if (!dead) w.postMessage(m); },
on: function (f) { fn = f; },
kill: function () { dead = true; w.terminate(); }
};
}
function inlineRunner(sliceMs) {
var fn = null, r = E.makeRunner(function (m) { if (fn) fn(m); }, sliceMs || 6);
return { real: false, post: function (m) { r.handle(m); }, on: function (f) { fn = f; }, kill: function () { fn = null; r.handle({ cmd: 'stop' }); } };
}
// ================= figure 2: the lens =================
var LENSES = { kpz: { beta: 1 / 3, iz: 2 / 3, txt: '1 : 2 : 3' }, ew: { beta: 1 / 4, iz: 1 / 2, txt: '1 : 2 : 4' }, bc: { beta: 1 / 2, iz: 1 / 2, txt: '1 : 1 : 2' } };
var lens = {
ids: ['tet', 'sq2', 'rd', 'bd'], panels: [], workers: [], lens: 'kpz', running: !reduceMotion, blind: false, self: false, visible: false,
t: 1, tEnd: 4096, tRef: 64, logL: 17, U: 24, yr: 3.6, rate: Math.log(4096) / 34, pending: 0, reqId: 0, redraw: true, ready: false, frames: 0, inline: false
};
// rulers: fixed at tRef and grown by the lens exponents; in the blind test each curve is drawn in units of its own
// measured roughness and correlation length instead, so that only its shape is left to go by
function lensRulers(P, t) {
var q = LENSES[lens.lens], f = t / lens.tRef, M = P.M;
var ru = { h: M.refW * Math.pow(f, q.beta), w: (M.refXi || 10) * Math.pow(f, q.iz) };
if (lens.self && P.xiS > 0) ru.w = P.xiS * Math.pow(t / P.xiT, q.iz);
return ru;
}
function lensReset() {
lens.workers.forEach(function (w) { w.kill(); });
if (!WORKERS_OK) { lens.logL = 14; lens.tEnd = 2048; }
var nW = Math.min(WORKERS_OK ? clamp(Math.floor(HC / 4), 1, 4) : 1, lens.panels.length), lists = [], i;
lens.workers = [];
for (i = 0; i < nW; i++) { lens.workers.push(spawn(8)); lists.push([]); }
lens.panels.forEach(function (P, pi) {
P.w = pi % nW; P.frame = null; P.xi = 0; P.xiS = 0; P.xiT = 1;
lists[P.w].push({ key: P.M.id, model: P.M.id, seed: rseed() });
});
lens.workers.forEach(function (w, wi) {
w.on(lensReply);
w.post({ cmd: 'lens-init', logL: lens.logL, sims: lists[wi] });
});
lens.t = 1; lens.pending = 0; lens.reqId++; lens.redraw = true; lens.ready = true; lens.frames = 0;
$('l-play').textContent = lens.running ? 'Pause' : 'Play';
}
function lensRequest(t) {
var L = 1 << lens.logL, lists = lens.workers.map(function () { return []; }), wantXi = (lens.frames % 6 === 0);
lens.panels.forEach(function (P) {
var n = clamp(P.cv.width, 16, 2000), ru = lensRulers(P, t), win = Math.min(L, lens.U * ru.w);
P.reqWin = win; P.reqRulerH = ru.h; P.reqRulerW = ru.w;
lists[P.w].push({ key: P.M.id, x0: L / 2 - win / 2, dx: win / n, n: n, xi: wantXi && P.M.refXi > 0 });
});
lens.reqId++; lens.pending = 0;
lens.workers.forEach(function (w, i) {
if (!lists[i].length) return;
lens.pending++;
w.post({ cmd: 'lens-step', id: lens.reqId, t: t, req: lists[i] });
});
lens.frames++;
}
function lensReply(m) {
if (m.type !== 'lens' || m.id !== lens.reqId) return;
m.out.forEach(function (o) {
var P = null;
lens.panels.forEach(function (Q) { if (Q.M.id === o.key) P = Q; });
if (!P) return;
if (o.xi != null) {
P.xi = o.xi;
var q = LENSES[lens.lens], pred = P.xiS > 0 ? P.xiS * Math.pow(m.t / P.xiT, q.iz) : o.xi;
P.xiS = pred + (o.xi - pred) * (P.xiS > 0 ? 0.2 : 1); P.xiT = m.t;
}
P.frame = { y: o.y, W: o.W, t: m.t, rulerH: lens.self ? Math.max(o.W, 0.3) : P.reqRulerH, rulerW: P.reqRulerW, win: P.reqWin };
});
lens.pending--;
if (lens.pending <= 0) {
lens.pending = 0; lens.t = m.t;
lens.panels.forEach(drawLens);
if (lens.frames % 4 === 0 || !lens.running || lens.t >= lens.tEnd) lensText();
}
}
function drawLens(P) {
var ctx = P.ctx, W = P.cv.width, H = P.cv.height, fr = P.frame;
if (!fr || W < 2 || H < 2) return;
var y = fr.y, n = y.length, mid = H * 0.5, sc = mid / (lens.yr * fr.rulerH), kx = W / n, i;
ctx.setTransform(1, 0, 0, 1, 0, 0);
ctx.clearRect(0, 0, W, H);
ctx.beginPath(); ctx.moveTo(0, H + 2);
for (i = 0; i < n; i++) ctx.lineTo((i + 0.5) * kx, mid - y[i] * sc);
ctx.lineTo(W, H + 2); ctx.closePath();
ctx.fillStyle = lens.blind ? THEME.inkFill : P.M.fillCss; ctx.fill();
ctx.fillStyle = THEME.ruleCss; ctx.fillRect(0, Math.round(mid), W, Math.max(1, Math.round(DPR)));
ctx.beginPath();
for (i = 0; i < n; i++) { if (i === 0) ctx.moveTo(0, mid - y[0] * sc); ctx.lineTo((i + 0.5) * kx, mid - y[i] * sc); }
ctx.lineWidth = Math.max(1, DPR * 1.4); ctx.lineJoin = 'round';
ctx.strokeStyle = lens.blind ? THEME.inkCss : P.M.css; ctx.stroke();
}
function lensText() {
var q = LENSES[lens.lens], t = lens.t;
$('l-bar').innerHTML = '';
var bar = $('l-bar'), a = mk('span'), b = mk('span'), c = mk('span');
a.appendChild(doc.createTextNode('time ')); a.appendChild(mk('b', null, 't = ' + fint(t)));
b.appendChild(doc.createTextNode('zoomed out ')); b.appendChild(mk('b', null, '×' + fnum(Math.pow(t, q.beta), t < 30 ? 1 : 0))); b.appendChild(doc.createTextNode(' in height'));
c.appendChild(mk('b', null, '×' + fnum(Math.pow(t, q.iz), t < 30 ? 1 : 0))); c.appendChild(doc.createTextNode(' in width'));
bar.appendChild(a); bar.appendChild(b); bar.appendChild(c);
if (lens.t >= lens.tEnd) bar.appendChild(mk('span', null, 'end of the run'));
if (lens.self) bar.appendChild(mk('span', null, 'Blind test: each curve is drawn in units of its own roughness and feature width, so only its shape is left to go by.'));
lens.panels.forEach(function (P) {
var fr = P.frame; if (!fr) return;
var rh = fr.W / fr.rulerH, rw = P.M.refXi > 0 && P.xi > 0 ? P.xi / fr.rulerW : NaN, word;
P.meter.innerHTML = '';
if (lens.blind) { P.meter.appendChild(mk('span', 'dim', 'Which game is this?')); return; }
if (lens.self) {
P.meter.appendChild(mk('span', null, 'its own units: ' + fnum(fr.W, fr.W < 10 ? 1 : 0) + ' rows' + (P.xi > 0 ? ' by ' + fint(P.xi) + ' columns' : '')));
return;
}
if (t < lens.tRef) word = 'settling';
else if (rh >= 1.25) word = 'swelling';
else if (rh <= 0.8) word = 'flattening';
else if (rw >= 1.7) word = 'stretching';
else if (rw <= 0.6) word = 'crumpling';
else word = 'holds steady';
P.meter.appendChild(mk('span', 'state', word));
P.meter.appendChild(mk('span', null, 'on screen: height ×' + fnum(rh, 2) + (isNaN(rw) ? '' : ', features ×' + fnum(rw, 2))));
P.meter.appendChild(mk('span', 'dim', 'window ' + fint(fr.win) + ' columns × ' + fint(2 * lens.yr * fr.rulerH) + ' rows'));
});
}
function lensFrame(dt) {
if (!lens.ready || !lens.visible || lens.pending) return;
if (lens.running && lens.t < lens.tEnd && lens.frames > 0) { lensRequest(Math.min(lens.tEnd, lens.t * Math.exp(lens.rate * dt))); lens.redraw = false; }
else if (lens.redraw) { lensRequest(lens.t); lens.redraw = false; }
if (lens.t >= lens.tEnd && lens.running) { lens.running = false; $('l-play').textContent = 'Play'; }
}
function lensLabel(P, i) {
P.name.textContent = lens.blind ? 'Game ' + String.fromCharCode(65 + i) : P.M.name;
P.key.style.setProperty('--c', lens.blind ? 'var(--ink)' : 'var(--s' + P.M.slot + ')');
P.cv.setAttribute('aria-label', (lens.blind ? 'A game' : P.M.name) + ': its surface, mean removed, under the chosen rescaling');
}
function lensBuild() {
var host = $('l-panels');
lens.panels.forEach(function (P) { if (P.ro_) P.ro_.disconnect(); P.art.remove(); });
var ids = lens.ids.slice(), i, j, tmp;
if (lens.blind) for (i = ids.length - 1; i > 0; i--) { j = Math.floor(Math.random() * (i + 1)); tmp = ids[i]; ids[i] = ids[j]; ids[j] = tmp; }
lens.panels = ids.map(function (id, pi) {
var P = panelShell(BYID[id], false);
P.meter = mk('p', 'meter'); P.art.appendChild(P.meter);
lensLabel(P, pi);
host.appendChild(P.art);
P.ro_ = watchSize(P.stage, P.cv, function () { lens.redraw = true; });
return P;
});
host.dataset.count = lens.panels.length;
lensReset();
}
function lensInit() {
var segs = $('l-lens').querySelectorAll('button'), play = $('l-play'), blind = $('l-blind');
Array.prototype.forEach.call(segs, function (b) {
b.addEventListener('click', function () {
lens.lens = b.dataset.lens;
Array.prototype.forEach.call(segs, function (o) { o.setAttribute('aria-pressed', o === b ? 'true' : 'false'); });
lens.redraw = true;
});
});
function again() { lens.running = true; if (lens.blind) lensReset(); else { lens.self = false; lensBuild(); } }
play.addEventListener('click', function () {
if (lens.t >= lens.tEnd) { again(); return; }
lens.running = !lens.running; play.textContent = lens.running ? 'Pause' : 'Play';
});
$('l-reset').addEventListener('click', again);
blind.addEventListener('click', function () {
lens.blind = !lens.blind;
blind.setAttribute('aria-pressed', lens.blind ? 'true' : 'false');
blind.textContent = lens.blind ? 'Show the names' : 'Hide the names';
$('l-chips').parentNode.parentNode.hidden = lens.blind;
if (lens.blind) { lens.self = true; lens.running = true; lensBuild(); }
else { lens.panels.forEach(lensLabel); lens.panels.forEach(drawLens); lensText(); }
});
buildChips($('l-chips'), lens.ids, function () { lens.running = true; lens.self = false; lensBuild(); });
lensBuild();
onScreen($('l-panels'), function (v) { lens.visible = v; });
}
// ================= figure 3: measure =================
var st = {
logL: 18, R: 1024, K: 21, times: [], sweeps: 16, runs: 0, agg: {}, goe: { n: 0, sum: [0, 0, 0, 0], hist: null, lo: -8, dx: 0.05 },
ready: false, show: {}, showGoe: true, hi: null, logy: true, drops: 0, done: 0, total: 0, paused: false, workers: [], live: 0, dirty: true, last: 0, kAvail: -1, inline: false, goeW: null
};
function statsStart() {
st.inline = !WORKERS_OK;
if (st.inline) { st.logL = 16; st.K = 17; st.sweeps = 6; }
st.times = []; for (var k = 0; k < st.K; k++) st.times.push(Math.pow(2, k / 2));
$('m-cols').textContent = fint(1 << st.logL);
$('d-time').max = st.K - 1; $('d-time').value = st.K - 1;
MODELS.forEach(function (M) { st.agg[M.id] = []; st.show[M.id] = true; });
st.ready = true;
statsRun();
}
function statsRun() {
var nW = st.inline ? 1 : clamp(HC - 3, 1, 8), groups = [], i;
for (i = 0; i < nW; i++) groups.push({ load: 0, ids: [] });
var cost = { tet: 2.6, sq2: 1, rd: 0.6, bd: 1, rsos: 1.2, fam: 1.2, cor: 1.2, hot: 1 };
MODELS.slice().sort(function (a, b) { return cost[b.id] - cost[a.id]; }).forEach(function (M) {
groups.sort(function (a, b) { return a.load - b.load; });
groups[0].ids.push(M.id); groups[0].load += cost[M.id];
});
groups = groups.filter(function (gp) { return gp.ids.length; });
st.total += MODELS.length * st.K * st.sweeps; st.live = groups.length; st.runs++;
st.workers = groups.map(function (gp) {
var w = spawn(6);
w.on(statsMsg);
w.post({ cmd: 'start', id: st.runs, models: gp.ids, logL: st.logL, times: st.times, sweeps: st.sweeps, seed: rseed(), R: st.R, typ: sp.NR });
return w;
});
if (st.runs === 1) {
st.goe.hist = new Float64Array(400);
if (st.inline) st.goeLater = true;
else { st.goeW = spawn(6); st.goeW.on(statsMsg); st.goeW.post({ cmd: 'goe', id: 0, n: 100000, seed: rseed(), total: 120000 }); }
}
$('m-more').hidden = true; $('m-pause').hidden = false;
}
function statsMsg(m) {
var i;
if (m.type === 'cp') {
var A = st.agg[m.model], a = A[m.k] || (A[m.k] = { t: st.times[m.k], n: 0, s2: 0, s3: 0, s4: 0, off: 0, sweeps: 0, hist: new Float64Array(2 * st.R + 1) });
a.n += m.n; a.s2 += m.m2 * m.n; a.s3 += m.m3 * m.n; a.s4 += m.m4 * m.n; a.off += (m.mean - m.c) * m.n; a.sweeps++;
if (m.trees > 0) a.trees = (a.trees || 0) + m.trees;
if (m.typ) {
if (!a.typ) { a.typ = new Float64Array(m.typ.length); a.typN = 0; }
for (i = 0; i < m.typ.length; i++) a.typ[i] += m.typ[i];
a.typN++;
}
for (i = 0; i < m.hist.length; i++) a.hist[i] += m.hist[i];
st.drops += m.n * (st.times[m.k] - (m.k ? st.times[m.k - 1] : 0));
st.done++; st.dirty = true;
} else if (m.type === 'goe') {
st.goe.n += m.count;
for (i = 0; i < 4; i++) st.goe.sum[i] += m.sum[i];
for (i = 0; i < m.hist.length; i++) st.goe.hist[i] += m.hist[i];
st.dirty = true;
} else if (m.type === 'done') {
if (m.id === 0) { if (st.goeW) { st.goeW.kill(); st.goeW = null; } return; }
st.live--;
if (st.live <= 0) {
st.workers.forEach(function (w) { if (w.real) w.kill(); });
if (st.goeLater) { st.goeLater = false; st.goeW = st.workers[0]; st.goeW.on(statsMsg); st.goeW.post({ cmd: 'goe', id: 0, n: 100000, seed: rseed(), total: 40000 }); }
st.workers = [];
$('m-more').hidden = false; $('m-pause').hidden = true; st.dirty = true;
}
}
}
function kAvail() {
var k = st.K - 1, ok;
for (; k >= 0; k--) { ok = true; MODELS.forEach(function (M) { if (!st.agg[M.id] || !st.agg[M.id][k]) ok = false; }); if (ok) return k; }
return -1;
}
function seriesW(M) {
var out = [], A = st.agg[M.id], k;
for (k = 0; k < st.K; k++) if (A[k]) out.push({ k: k, t: A[k].t, W: Math.sqrt(A[k].s2 / A[k].n) });
return out;
}
function moments(M, k) {
var A = st.agg[M.id], a = A[k]; if (!a) return null;
var m2 = a.s2 / a.n, m3 = a.s3 / a.n, m4 = a.s4 / a.n, beta = NaN;
if (k >= 4 && A[k - 4]) beta = 0.5 * Math.log(m2 / (A[k - 4].s2 / A[k - 4].n)) / Math.log(a.t / A[k - 4].t);
return { W: Math.sqrt(m2), skew: m3 / Math.pow(m2, 1.5), kurt: m4 / (m2 * m2) - 3, beta: beta, sweeps: a.sweeps };
}
// histogram of one game at checkpoint k, standardised; games with sign < 0 are mirrored
function distSeries(M, k) {
var a = st.agg[M.id][k]; if (!a || !a.n) return null;
var N = a.n, sd = Math.sqrt(a.s2 / N), off = a.off / N, g = M.g, w = g * Math.max(1, Math.round(0.2 * sd / g)), R = st.R;
var o = -Math.floor(w / 2), jmin = Math.floor((-R + 1 - o) / w) + 1, jmax = Math.floor((R - 1 - o) / w) - 1, j, dd, cnt, pts = [], sign = M.sign < 0 ? -1 : 1, i0;
for (j = jmin; j <= jmax; j++) {
cnt = 0; i0 = j * w + o + R;
for (dd = 0; dd < w; dd++) cnt += a.hist[i0 + dd];
if (cnt > 0) pts.push({ z: sign * ((j * w + o + (w - 1) / 2) - off) / sd, p: cnt / (N * w / sd), c: cnt });
}
if (sign < 0) pts.reverse();
return pts;
}
function goeSeries() {
var G = st.goe; if (!G.hist || G.n < 500) return null;
var mu = G.sum[0] / G.n, sd = Math.sqrt(G.sum[1] / G.n - mu * mu), pts = [], j, cnt, q;
for (j = 0; j + 4 <= G.hist.length; j += 4) {
cnt = 0; for (q = 0; q < 4; q++) cnt += G.hist[j + q];
if (cnt > 0) pts.push({ z: (G.lo + (j + 2) * G.dx - mu) / sd, p: cnt / (G.n * 4 * G.dx / sd), c: cnt });
}
return pts;
}
function twLog(z) {
var u = (z - TW_GOE.z0) / TW_GOE.dz, i = Math.floor(u), T = TW_GOE.logg;
if (i < 0) return T[0]; if (i >= T.length - 1) return T[T.length - 1];
return T[i] + (T[i + 1] - T[i]) * (u - i);
}
function gaussLog(z) { return -0.5 * z * z - 0.9189385332046727; }
function interp(pts, z) {
if (!pts || pts.length < 2 || z < pts[0].z || z > pts[pts.length - 1].z) return NaN;
for (var i = 1; i < pts.length; i++) if (pts[i].z >= z) return pts[i - 1].p + (pts[i].p - pts[i - 1].p) * (z - pts[i - 1].z) / (pts[i].z - pts[i - 1].z || 1);
return NaN;
}
// ---- drawing the two charts (SVG) ----
var GR = null, DI = null;
function esc(s) { return String(s).replace(/&/g, '&').replace(/</g, '<'); }
function tickLabel(v) { return v >= 1 ? fint(v) : String(v); }
function drawGrowth() {
var svg = $('ch-growth'), Wd = svg.parentNode.clientWidth, Hd = 340;
if (Wd < 40) return;
var wide = Wd >= 470, m = { l: 40, r: wide ? 126 : 14, t: 12, b: 40 }, pw = Wd - m.l - m.r, ph = Hd - m.t - m.b;
var xmax = (st.K - 1) / 2, y0 = Math.log10(0.45), y1 = Math.log10(95);
function X(t) { return m.l + pw * Math.log2(t) / xmax; }
function Y(w) { return m.t + ph * (1 - (Math.log10(w) - y0) / (y1 - y0)); }
var p = [], i;
svg.setAttribute('viewBox', '0 0 ' + Wd + ' ' + Hd); svg.setAttribute('height', Hd);
[1, 2, 5, 10, 20, 50].forEach(function (v) {
p.push('<line class="grid" x1="' + m.l + '" x2="' + (m.l + pw) + '" y1="' + Y(v).toFixed(1) + '" y2="' + Y(v).toFixed(1) + '"/>');
p.push('<text x="' + (m.l - 8) + '" y="' + (Y(v) + 4).toFixed(1) + '" text-anchor="end">' + v + '</text>');
});
p.push('<line class="axisline" x1="' + m.l + '" x2="' + (m.l + pw) + '" y1="' + (m.t + ph) + '" y2="' + (m.t + ph) + '"/>');
for (i = 0; i <= xmax; i += (pw < 300 ? 4 : 2)) {
p.push('<line class="axisline" x1="' + X(Math.pow(2, i)).toFixed(1) + '" x2="' + X(Math.pow(2, i)).toFixed(1) + '" y1="' + (m.t + ph) + '" y2="' + (m.t + ph + 4) + '"/>');
p.push('<text x="' + X(Math.pow(2, i)).toFixed(1) + '" y="' + (m.t + ph + 18) + '" text-anchor="middle">' + fint(Math.pow(2, i)) + '</text>');
}
p.push('<text class="lbl" x="' + (m.l + pw) + '" y="' + (Hd - 4) + '" text-anchor="end">time t, in pieces dropped per column</text>');
p.push('<text class="lbl" x="' + (m.l - 8) + '" y="' + (m.t + 2) + '" text-anchor="end">W</text>');
// slope fan: what exponents 1/2, 1/3 and 1/4 look like on these axes
var ft0 = 1.5, fw0 = 12, ft1 = ft0 * 16;
[[0.5, 'slope ½'], [1 / 3, '⅓'], [0.25, '¼']].forEach(function (s, si) {
var w1 = fw0 * Math.pow(16, s[0]);
p.push('<line x1="' + X(ft0).toFixed(1) + '" y1="' + Y(fw0).toFixed(1) + '" x2="' + X(ft1).toFixed(1) + '" y2="' + Y(w1).toFixed(1) + '" stroke="var(--ink-3)" stroke-width="1.25"/>');
p.push('<text class="lbl" x="' + (X(ft1) + 5).toFixed(1) + '" y="' + (Y(w1) + 4 + (si === 1 ? 1 : si === 2 ? 5 : -2)).toFixed(1) + '">' + s[1] + '</text>');
});
var ends = [];
MODELS.forEach(function (M) {
if (!st.show[M.id]) return;
var s = seriesW(M); if (!s.length) return;
var dpath = s.map(function (q, qi) { return (qi ? 'L' : 'M') + X(q.t).toFixed(1) + ' ' + Y(Math.max(q.W, 0.46)).toFixed(1); }).join('');
var dim = st.hi && st.hi !== M.id;
p.push('<path d="' + dpath + '" fill="none" stroke="var(--s' + M.slot + ')" stroke-width="2" stroke-linejoin="round" stroke-linecap="round" opacity="' + (dim ? 0.18 : 1) + '"/>');
var e = s[s.length - 1];
p.push('<circle cx="' + X(e.t).toFixed(1) + '" cy="' + Y(e.W).toFixed(1) + '" r="4" fill="var(--s' + M.slot + ')" stroke="var(--surface)" stroke-width="2" opacity="' + (dim ? 0.18 : 1) + '"/>');
ends.push({ M: M, x: X(e.t), y: Y(e.W), ly: Y(e.W), dim: dim });
});
if (wide && ends.length) { // direct labels, nudged apart, with leader lines
ends.sort(function (a, b) { return a.y - b.y; });
var gap = 15, it, moved;
for (it = 0; it < 40; it++) {
moved = false;
for (i = 1; i < ends.length; i++) if (ends[i].ly - ends[i - 1].ly < gap) { var mid = (ends[i].ly + ends[i - 1].ly) / 2; ends[i - 1].ly = mid - gap / 2; ends[i].ly = mid + gap / 2; moved = true; }
if (!moved) break;
}
ends.forEach(function (e) {
e.ly = clamp(e.ly, m.t + 6, m.t + ph - 2);
var lx = m.l + pw + 16;
p.push('<line x1="' + (e.x + 6).toFixed(1) + '" y1="' + e.y.toFixed(1) + '" x2="' + (lx - 3) + '" y2="' + e.ly.toFixed(1) + '" stroke="var(--axis)" stroke-width="1" opacity="' + (e.dim ? 0.3 : 1) + '"/>');
p.push('<text class="lbl" x="' + lx + '" y="' + (e.ly + 4).toFixed(1) + '" opacity="' + (e.dim ? 0.35 : 1) + '">' + esc(e.M.name) + '</text>');
});
}
p.push('<line id="gr-cross" x1="0" x2="0" y1="' + m.t + '" y2="' + (m.t + ph) + '" stroke="var(--ink-3)" stroke-width="1" visibility="hidden"/>');
svg.innerHTML = p.join('');
GR = { m: m, pw: pw, ph: ph, xmax: xmax, X: X, Y: Y, Wd: Wd };
}
function drawDist() {
var svg = $('ch-dist'), Wd = svg.parentNode.clientWidth, Hd = 340;
if (Wd < 40) return;
var m = { l: 46, r: 14, t: 12, b: 40 }, pw = Wd - m.l - m.r, ph = Hd - m.t - m.b, z0 = -4.6, z1 = 5.6, logy = st.logy;
var k = Math.min(+$('d-time').value, st.kAvail), p = [], i, z;
function X(zz) { return m.l + pw * (zz - z0) / (z1 - z0); }
function Y(pp) { return logy ? m.t + ph * (1 - (Math.log10(Math.max(pp, 1e-9)) + 4) / 4.2) : m.t + ph * (1 - pp / 0.47); }
svg.setAttribute('viewBox', '0 0 ' + Wd + ' ' + Hd); svg.setAttribute('height', Hd);
(logy ? [1, 0.1, 0.01, 0.001, 0.0001] : [0.1, 0.2, 0.3, 0.4]).forEach(function (v, vi) {
p.push('<line class="grid" x1="' + m.l + '" x2="' + (m.l + pw) + '" y1="' + Y(v).toFixed(1) + '" y2="' + Y(v).toFixed(1) + '"/>');
p.push('<text x="' + (m.l - 8) + '" y="' + (Y(v) + 4).toFixed(1) + '" text-anchor="end">' + (logy ? (vi < 3 ? String(v) : '10<tspan dy="-5" font-size="9">−' + vi + '</tspan>') : v.toFixed(1)) + '</text>');
});
p.push('<line class="axisline" x1="' + m.l + '" x2="' + (m.l + pw) + '" y1="' + (m.t + ph) + '" y2="' + (m.t + ph) + '"/>');
for (i = -4; i <= 5; i += (pw < 300 ? 2 : 1)) {
p.push('<line class="axisline" x1="' + X(i).toFixed(1) + '" x2="' + X(i).toFixed(1) + '" y1="' + (m.t + ph) + '" y2="' + (m.t + ph + 4) + '"/>');
p.push('<text x="' + X(i).toFixed(1) + '" y="' + (m.t + ph + 18) + '" text-anchor="middle">' + (i < 0 ? '−' + (-i) : i) + '</text>');
}
p.push('<text class="lbl" x="' + (m.l + pw) + '" y="' + (Hd - 4) + '" text-anchor="end">height, in standard deviations from the mean</text>');
p.push('<clipPath id="di-clip"><rect x="' + m.l + '" y="' + (m.t - 2) + '" width="' + pw + '" height="' + (ph + 2) + '"/></clipPath><g clip-path="url(#di-clip)">');
var ga = [], tw = [];
for (z = z0; z <= z1 + 1e-9; z += 0.05) {
ga.push((ga.length ? 'L' : 'M') + X(z).toFixed(1) + ' ' + Y(Math.exp(gaussLog(z))).toFixed(1));
tw.push((tw.length ? 'L' : 'M') + X(z).toFixed(1) + ' ' + Y(Math.exp(twLog(z))).toFixed(1));
}
p.push('<path d="' + ga.join('') + '" fill="none" stroke="var(--ink-3)" stroke-width="9" stroke-linejoin="round" opacity="0.16"/>');
p.push('<path d="' + tw.join('') + '" fill="none" stroke="var(--ink)" stroke-width="9" stroke-linejoin="round" opacity="0.16"/>');
p.push('<path d="' + ga.join('') + '" fill="none" stroke="var(--ink-3)" stroke-width="1.5" stroke-dasharray="5 4"/>');
p.push('<path d="' + tw.join('') + '" fill="none" stroke="var(--ink)" stroke-width="1.5" stroke-linejoin="round"/>');
var data = {};
if (k >= 0) MODELS.forEach(function (M) {
if (!st.show[M.id]) return;
var pts = distSeries(M, k); if (!pts || pts.length < 2) return;
data[M.id] = pts;
var dpath = '', started = false;
pts.forEach(function (q) {
if (q.z < z0 - 0.3 || q.z > z1 + 0.3 || q.c < 12) { return; }
dpath += (started ? 'L' : 'M') + X(q.z).toFixed(1) + ' ' + Y(q.p).toFixed(1); started = true;
});
p.push('<path d="' + dpath + '" fill="none" stroke="var(--s' + M.slot + ')" stroke-width="2" stroke-linejoin="round" opacity="' + (st.hi && st.hi !== M.id ? 0.14 : 1) + '"/>');
});
var gs = st.showGoe ? goeSeries() : null;
if (gs) {
data.goe = gs;
gs.forEach(function (q) {
if (q.z < z0 || q.z > z1 || q.c < 12) return;
p.push('<circle cx="' + X(q.z).toFixed(1) + '" cy="' + Y(q.p).toFixed(1) + '" r="3.2" fill="var(--surface)" stroke="var(--ink)" stroke-width="1.4" opacity="' + (st.hi && st.hi !== 'goe' ? 0.2 : 1) + '"/>');
});
}
p.push('</g>');
p.push('<line id="di-cross" x1="0" x2="0" y1="' + m.t + '" y2="' + (m.t + ph) + '" stroke="var(--ink-3)" stroke-width="1" visibility="hidden"/>');
svg.innerHTML = p.join('');
DI = { m: m, pw: pw, ph: ph, z0: z0, z1: z1, X: X, data: data, k: k, Wd: Wd };
var sub = $('d-sub'), tt = k >= 0 ? st.times[k] : 0;
sub.textContent = k >= 0
? 'Height distribution at t = ' + fint(tt) + ', each game shifted and scaled to mean 0 and variance 1. Picky squares and corner filling are mirrored.' + (logy ? ' The vertical axis is logarithmic.' : '')
: 'Height distribution, each game shifted and scaled to mean 0 and variance 1.';
$('d-time-out').textContent = k >= 0 ? 't = ' + fint(st.times[Math.min(+$('d-time').value, st.K - 1)]) : '';
}
function drawTable() {
var k = Math.min(+$('d-time').value, st.kAvail), body = $('m-table').tBodies[0];
$('m-cap').textContent = k >= 0 ? 'The numbers behind the charts, at t = ' + fint(st.times[k]) : 'The numbers behind the charts';
body.innerHTML = '';
MODELS.forEach(function (M) {
var C = CLASSES[M.cls], mo = k >= 0 ? moments(M, k) : null, tr = doc.createElement('tr'), td, key;
td = doc.createElement('td'); key = mk('span', 'key'); key.style.setProperty('--c', 'var(--s' + M.slot + ')'); td.appendChild(key); td.appendChild(doc.createTextNode(M.name)); tr.appendChild(td);
tr.appendChild(mk('td', null, C.name));
tr.appendChild(mk('td', 'meas', mo ? fnum(mo.W, mo.W < 10 ? 2 : 1) : '…'));
tr.appendChild(mk('td', 'meas', mo && !isNaN(mo.beta) ? fnum(mo.beta, 2) : '…'));
tr.appendChild(mk('td', 'th', C.betaTxt));
tr.appendChild(mk('td', 'meas', mo ? fsgn(mo.skew, 2) : '…'));
tr.appendChild(mk('td', 'th', C.skew ? fsgn(M.sign * C.skew, 2) : '0'));
tr.appendChild(mk('td', 'meas', mo ? fsgn(mo.kurt, 2) : '…'));
tr.appendChild(mk('td', 'th', C.kurt ? fsgn(C.kurt, 2) : '0'));
body.appendChild(tr);
});
}
// ---- families still alive: every column starts as a family; count those that still hold some of the surface ----
var TREE_IDS = ['tet', 'sq2', 'bd', 'cor', 'hot'], TR = null;
function seriesTrees(M) {
var out = [], A = st.agg[M.id], k, L = 1 << st.logL;
for (k = 0; k < st.K; k++) if (A[k] && A[k].trees > 0) out.push({ k: k, t: A[k].t, n: A[k].trees / (A[k].sweeps * L) });
return out;
}
function drawTrees() {
var svg = $('ch-trees'), Wd = svg.parentNode.clientWidth, Hd = 340;
if (Wd < 40) return;
var wide = Wd >= 470, m = { l: 46, r: wide ? 126 : 14, t: 12, b: 40 }, pw = Wd - m.l - m.r, ph = Hd - m.t - m.b;
var xmax = (st.K - 1) / 2, y0 = Math.log10(0.0016), y1 = Math.log10(1.5), p = [], i, t;
function X(tt) { return m.l + pw * Math.log2(tt) / xmax; }
function Y(v) { return m.t + ph * (1 - (Math.log10(v) - y0) / (y1 - y0)); }
svg.setAttribute('viewBox', '0 0 ' + Wd + ' ' + Hd); svg.setAttribute('height', Hd);
[1, 0.1, 0.01].forEach(function (v) {
p.push('<line class="grid" x1="' + m.l + '" x2="' + (m.l + pw) + '" y1="' + Y(v).toFixed(1) + '" y2="' + Y(v).toFixed(1) + '"/>');
p.push('<text x="' + (m.l - 8) + '" y="' + (Y(v) + 4).toFixed(1) + '" text-anchor="end">' + v + '</text>');
});
p.push('<line class="axisline" x1="' + m.l + '" x2="' + (m.l + pw) + '" y1="' + (m.t + ph) + '" y2="' + (m.t + ph) + '"/>');
for (i = 0; i <= xmax; i += (pw < 300 ? 4 : 2)) {
p.push('<line class="axisline" x1="' + X(Math.pow(2, i)).toFixed(1) + '" x2="' + X(Math.pow(2, i)).toFixed(1) + '" y1="' + (m.t + ph) + '" y2="' + (m.t + ph + 4) + '"/>');
p.push('<text x="' + X(Math.pow(2, i)).toFixed(1) + '" y="' + (m.t + ph + 18) + '" text-anchor="middle">' + fint(Math.pow(2, i)) + '</text>');
}
p.push('<text class="lbl" x="' + (m.l + pw) + '" y="' + (Hd - 4) + '" text-anchor="end">time t, in pieces dropped per column</text>');
p.push('<text class="lbl" x="' + (m.l + 8) + '" y="' + (m.t + ph - 10) + '">families alive, per column</text>');
// slope fan: what the exponents 1/2 and 2/3 look like on these axes
var ft0 = 24, fv0 = 0.9, ft1 = ft0 * 16;
[[0.5, 'slope −½'], [2 / 3, '−⅔']].forEach(function (s) {
var v1 = fv0 / Math.pow(16, s[0]);
p.push('<line x1="' + X(ft0).toFixed(1) + '" y1="' + Y(fv0).toFixed(1) + '" x2="' + X(ft1).toFixed(1) + '" y2="' + Y(v1).toFixed(1) + '" stroke="var(--ink-3)" stroke-width="1.25"/>');
p.push('<text class="lbl" x="' + (X(ft1) + 5).toFixed(1) + '" y="' + (Y(v1) + 4).toFixed(1) + '">' + s[1] + '</text>');
});
// hot bricks, exactly: coalescing random walks that each jump at rate 1/2
var ex = [];
for (i = 0; i <= xmax * 8; i++) { t = Math.pow(2, i / 8); if (t >= 2) ex.push((ex.length ? 'L' : 'M') + X(t).toFixed(1) + ' ' + Y(Math.sqrt(2 / (Math.PI * t))).toFixed(1)); }
p.push('<path d="' + ex.join('') + '" fill="none" stroke="var(--ink-3)" stroke-width="1.5" stroke-dasharray="5 4"/>');
var ends = [], data = {};
TREE_IDS.forEach(function (id) {
var M = BYID[id], s = seriesTrees(M); if (!s.length) return;
data[id] = s;
p.push('<path d="' + s.map(function (q, qi) { return (qi ? 'L' : 'M') + X(q.t).toFixed(1) + ' ' + Y(q.n).toFixed(1); }).join('') + '" fill="none" stroke="var(--s' + M.slot + ')" stroke-width="2" stroke-linejoin="round" stroke-linecap="round"/>');
var e = s[s.length - 1];
p.push('<circle cx="' + X(e.t).toFixed(1) + '" cy="' + Y(e.n).toFixed(1) + '" r="4" fill="var(--s' + M.slot + ')" stroke="var(--surface)" stroke-width="2"/>');
ends.push({ M: M, x: X(e.t), y: Y(e.n), ly: Y(e.n) });
});
if (wide && ends.length) {
ends.sort(function (a, b) { return a.y - b.y; });
var gap = 15, it, moved, mid;
for (it = 0; it < 40; it++) {
moved = false;
for (i = 1; i < ends.length; i++) if (ends[i].ly - ends[i - 1].ly < gap) { mid = (ends[i].ly + ends[i - 1].ly) / 2; ends[i - 1].ly = mid - gap / 2; ends[i].ly = mid + gap / 2; moved = true; }
if (!moved) break;
}
ends.forEach(function (e) {
e.ly = clamp(e.ly, m.t + 6, m.t + ph - 2);
var lx = m.l + pw + 16;
p.push('<line x1="' + (e.x + 6).toFixed(1) + '" y1="' + e.y.toFixed(1) + '" x2="' + (lx - 3) + '" y2="' + e.ly.toFixed(1) + '" stroke="var(--axis)" stroke-width="1"/>');
p.push('<text class="lbl" x="' + lx + '" y="' + (e.ly + 4).toFixed(1) + '">' + esc(e.M.name) + '</text>');
});
}
p.push('<line id="tr-cross" x1="0" x2="0" y1="' + m.t + '" y2="' + (m.t + ph) + '" stroke="var(--ink-3)" stroke-width="1" visibility="hidden"/>');
svg.innerHTML = p.join('');
TR = { m: m, pw: pw, xmax: xmax, X: X, data: data };
}
function per1000(v) { v *= 1000; return fnum(v, v >= 100 ? 0 : v >= 10 ? 1 : 2); }
function drawTreeTable() {
var body = $('f-table').tBodies[0], kk = st.K, all = {};
// every row refers to the same moment: the latest time that all five games have reached
TREE_IDS.forEach(function (id) { var s = seriesTrees(BYID[id]); all[id] = s; kk = Math.min(kk, s.length ? s[s.length - 1].k : -1); });
body.innerHTML = '';
TREE_IDS.forEach(function (id) {
var M = BYID[id], e = null, p4 = null, ex = NaN, tr = doc.createElement('tr'), td, key;
all[id].forEach(function (q) { if (q.k === kk) e = q; if (q.k === kk - 4) p4 = q; });
if (e && p4) ex = Math.log(p4.n / e.n) / Math.log(e.t / p4.t);
td = doc.createElement('td'); key = mk('span', 'key'); key.style.setProperty('--c', 'var(--s' + M.slot + ')'); td.appendChild(key); td.appendChild(doc.createTextNode(M.name)); tr.appendChild(td);
tr.appendChild(mk('td', 'meas', e ? per1000(e.n) : '…'));
tr.appendChild(mk('td', 'meas', e ? fint(1 / e.n) + ' columns' : '…'));
tr.appendChild(mk('td', 'meas', !isNaN(ex) ? fnum(ex, 2) : '…'));
tr.appendChild(mk('td', 'th', M.cls === 'bc' ? '1/2' : '2/3'));
body.appendChild(tr);
});
$('f-cap').textContent = kk >= 0 ? 'Families at t = ' + fint(st.times[kk]) : 'Families';
}
function hoverTrees(x, tip) {
var cross = doc.getElementById('tr-cross');
if (!TR || x < TR.m.l - 6 || x > TR.m.l + TR.pw + 6) { if (cross) cross.setAttribute('visibility', 'hidden'); return false; }
var k = clamp(Math.round((x - TR.m.l) / TR.pw * TR.xmax * 2), 0, st.K - 1), t = st.times[k], rows = [];
TREE_IDS.forEach(function (id) { (TR.data[id] || []).forEach(function (q) { if (q.k === k) rows.push({ M: BYID[id], n: q.n }); }); });
if (!rows.length) { if (cross) cross.setAttribute('visibility', 'hidden'); return false; }
rows.sort(function (a, b) { return b.n - a.n; });
if (cross) { cross.setAttribute('x1', TR.X(t)); cross.setAttribute('x2', TR.X(t)); cross.setAttribute('visibility', 'visible'); }
tip.innerHTML = ''; tip.appendChild(mk('div', 'tt', 'Alive per 1,000 columns at t = ' + fint(t)));
rows.forEach(function (q) { tipRow(tip, '', 'var(--s' + q.M.slot + ')', per1000(q.n), q.M.name); });
if (t >= 2) tipRow(tip, 'dash', null, per1000(Math.sqrt(2 / (Math.PI * t))), 'Exact, hot bricks');
return true;
}
// ---- along the surface: how much do two columns differ, against how far apart they are ----
// A random walk in space gives a difference that grows like the square root of the distance, independent columns
// one that does not grow, and a surface with jumps one that grows like the distance itself.
var SP = null, sp = { own: false, show: {}, hi: null, NR: 13 };
function spaceK() { var k = st.kAvail; return k < 0 ? -1 : k - (k % 2); } // measured at every other checkpoint
function spAt(pts, r) { // the curve at any distance, read off along straight lines on logarithmic axes
var n = pts.length, i, f;
if (r <= pts[0].r) return pts[0].v;
if (r >= pts[n - 1].r) return pts[n - 1].v;
for (i = 1; i < n; i++) if (pts[i].r >= r) break;
if (!(pts[i - 1].v > 0) || !(pts[i].v > 0)) return pts[i].v;
f = Math.log(r / pts[i - 1].r) / Math.log(pts[i].r / pts[i - 1].r);
return pts[i - 1].v * Math.pow(pts[i].v / pts[i - 1].v, f);
}
function seriesSpace(M, k) {
var a = k >= 0 ? st.agg[M.id][k] : null; if (!a || !a.typ || !a.typN) return null;
var pts = [], i, n = a.typ.length, far, reach = null, lo, hi, slope = NaN;
for (i = 0; i < n; i++) pts.push({ r: 1 << i, v: a.typ[i] / a.typN });
far = (pts[n - 1].v + pts[n - 2].v + pts[n - 3].v) / 3; // far apart, two columns know nothing of each other
if (!(far > 0)) return null;
for (i = 0; i < n; i++) if (pts[i].v >= far / 2) break; // reach: where the difference gets to half of that
if (i > 0 && i < n && pts[i - 1].v > 0) reach = pts[i - 1].r * Math.pow(2, Math.log(far / 2 / pts[i - 1].v) / Math.log(pts[i].v / pts[i - 1].v));
if (M.cls === 'free') { lo = 1; hi = 8; } // independent columns have no reach: any stretch will do
else if (reach >= 4) { lo = Math.max(1, reach / 8); hi = reach / 2; }
if (hi && hi / lo >= 1.99) slope = Math.log(spAt(pts, hi) / spAt(pts, lo)) / Math.log(hi / lo);
return { pts: pts, far: far, reach: reach, slope: slope };
}
function drawSpace() {
var svg = $('ch-space'); if (!svg) return;
var Wd = svg.parentNode.clientWidth, Hd = 340;
if (Wd < 40) return;
var own = sp.own, wide = Wd >= 470, m = { l: own ? 48 : 40, r: wide && !own ? 126 : 14, t: 12, b: 40 }, pw = Wd - m.l - m.r, ph = Hd - m.t - m.b;
var k = spaceK(), p = [], i, x0 = own ? -5 : 0, x1 = own ? 6 : sp.NR - 1;
var y0 = Math.log10(own ? 0.03 : 0.45), y1 = Math.log10(own ? 1.6 : 95);
function X(r) { return m.l + pw * (Math.log2(r) - x0) / (x1 - x0); }
function Y(v) { return m.t + ph * (1 - (Math.log10(v) - y0) / (y1 - y0)); }
svg.setAttribute('viewBox', '0 0 ' + Wd + ' ' + Hd); svg.setAttribute('height', Hd);
(own ? [0.05, 0.1, 0.2, 0.5, 1] : [1, 2, 5, 10, 20, 50]).forEach(function (v) {
p.push('<line class="grid" x1="' + m.l + '" x2="' + (m.l + pw) + '" y1="' + Y(v).toFixed(1) + '" y2="' + Y(v).toFixed(1) + '"/>');
p.push('<text x="' + (m.l - 8) + '" y="' + (Y(v) + 4).toFixed(1) + '" text-anchor="end">' + (own ? Math.round(v * 100) + '%' : v) + '</text>');
});
p.push('<line class="axisline" x1="' + m.l + '" x2="' + (m.l + pw) + '" y1="' + (m.t + ph) + '" y2="' + (m.t + ph) + '"/>');
for (i = own ? -4 : 0; i <= x1; i += (pw < 300 && !own ? 4 : 2)) {
p.push('<line class="axisline" x1="' + X(Math.pow(2, i)).toFixed(1) + '" x2="' + X(Math.pow(2, i)).toFixed(1) + '" y1="' + (m.t + ph) + '" y2="' + (m.t + ph + 4) + '"/>');
p.push('<text x="' + X(Math.pow(2, i)).toFixed(1) + '" y="' + (m.t + ph + 18) + '" text-anchor="middle">' + (i < 0 ? '1/' + Math.pow(2, -i) : fint(Math.pow(2, i))) + '</text>');
}
p.push('<text class="lbl" x="' + (m.l + pw) + '" y="' + (Hd - 4) + '" text-anchor="end">' + (own ? 'distance, in units of each surface’s own reach' : 'distance between the two columns') + '</text>');
p.push('<text class="lbl" x="' + (m.l + 8) + '" y="' + (m.t + 10) + '">' + (own ? 'typical difference, as a share of its far-apart value' : 'typical difference, in rows') + '</text>');
// slope fan: what the exponents 1/2 and 1 look like on these axes
var fr0 = own ? 5 : 360, fv0 = own ? 0.045 : 0.56, fk = 4; // in the corner the curves leave empty
[[0.5, 'slope ½'], [1, '1']].forEach(function (s) {
var v1 = fv0 * Math.pow(fk, s[0]);
p.push('<line x1="' + X(fr0).toFixed(1) + '" y1="' + Y(fv0).toFixed(1) + '" x2="' + X(fr0 * fk).toFixed(1) + '" y2="' + Y(v1).toFixed(1) + '" stroke="var(--ink-3)" stroke-width="1.25"/>');
p.push('<text class="lbl" x="' + (X(fr0 * fk) + 5).toFixed(1) + '" y="' + (Y(v1) + 4).toFixed(1) + '">' + s[1] + '</text>');
});
p.push('<clipPath id="sp-clip"><rect x="' + m.l + '" y="' + (m.t - 2) + '" width="' + pw + '" height="' + (ph + 2) + '"/></clipPath><g clip-path="url(#sp-clip)">');
var ends = [], data = {}, floor = Math.pow(10, y0) * 1.02;
MODELS.forEach(function (M) {
if (!sp.show[M.id]) return;
var s = seriesSpace(M, k); if (!s) return;
data[M.id] = s;
var dim = sp.hi && sp.hi !== M.id, unit = own ? (s.reach || 0) : 1, dpath, e;
if (own && !unit) { // no reach: the same difference at every distance, a level line
dpath = 'M' + m.l + ' ' + Y(s.pts[0].v / s.far).toFixed(1) + 'L' + (m.l + pw) + ' ' + Y(s.pts[s.pts.length - 1].v / s.far).toFixed(1);
} else {
dpath = s.pts.map(function (q, qi) { return (qi ? 'L' : 'M') + X(q.r / unit).toFixed(1) + ' ' + Y(Math.max(own ? q.v / s.far : q.v, floor)).toFixed(1); }).join('');
}
p.push('<path d="' + dpath + '" fill="none" stroke="var(--s' + M.slot + ')" stroke-width="2" stroke-linejoin="round" stroke-linecap="round" opacity="' + (dim ? 0.18 : 1) + '"/>');
if (!own) {
e = s.pts[s.pts.length - 1];
ends.push({ M: M, x: X(e.r), y: Y(Math.max(e.v, floor)), ly: Y(Math.max(e.v, floor)), dim: dim });
}
});
p.push('</g>');
ends.forEach(function (e) { // end markers sit on the edge of the plot, so they are drawn outside the clip
p.push('<circle cx="' + e.x.toFixed(1) + '" cy="' + e.y.toFixed(1) + '" r="4" fill="var(--s' + e.M.slot + ')" stroke="var(--surface)" stroke-width="2" opacity="' + (e.dim ? 0.18 : 1) + '"/>');
});
if (wide && ends.length) { // direct labels, nudged apart, with leader lines
ends.sort(function (a, b) { return a.y - b.y; });
var gap = 15, it, moved, mid;
for (it = 0; it < 40; it++) {
moved = false;
for (i = 1; i < ends.length; i++) if (ends[i].ly - ends[i - 1].ly < gap) { mid = (ends[i].ly + ends[i - 1].ly) / 2; ends[i - 1].ly = mid - gap / 2; ends[i].ly = mid + gap / 2; moved = true; }
if (!moved) break;
}
ends.forEach(function (e) {
e.ly = clamp(e.ly, m.t + 6, m.t + ph - 2);
var lx = m.l + pw + 16;
p.push('<line x1="' + (e.x + 6).toFixed(1) + '" y1="' + e.y.toFixed(1) + '" x2="' + (lx - 3) + '" y2="' + e.ly.toFixed(1) + '" stroke="var(--axis)" stroke-width="1" opacity="' + (e.dim ? 0.3 : 1) + '"/>');
p.push('<text class="lbl" x="' + lx + '" y="' + (e.ly + 4).toFixed(1) + '" opacity="' + (e.dim ? 0.35 : 1) + '">' + esc(e.M.name) + '</text>');
});
}
p.push('<line id="sp-cross" x1="0" x2="0" y1="' + m.t + '" y2="' + (m.t + ph) + '" stroke="var(--ink-3)" stroke-width="1" visibility="hidden"/>');
svg.innerHTML = p.join('');
SP = { m: m, pw: pw, x0: x0, x1: x1, X: X, data: data, own: own, k: k };
$('s-sub').textContent = 'Typical height difference between two columns, against the distance between them' + (k >= 0 ? ', at t = ' + fint(st.times[k]) : '') + '. Half of all pairs that far apart differ by less. Both axes are logarithmic.';
}
function drawSpaceTable() {
var body = $('s-table').tBodies[0], k = spaceK();
body.innerHTML = '';
MODELS.forEach(function (M) {
var s = seriesSpace(M, k), tr = doc.createElement('tr'), td = doc.createElement('td'), key = mk('span', 'key');
key.style.setProperty('--c', 'var(--s' + M.slot + ')'); td.appendChild(key); td.appendChild(doc.createTextNode(M.name)); tr.appendChild(td);
tr.appendChild(mk('td', 'meas', s ? fnum(s.far, s.far < 10 ? 2 : 1) + ' rows' : '…'));
tr.appendChild(mk('td', 'meas', !s ? '…' : s.reach ? fnum(s.reach, s.reach < 10 ? 1 : 0) + ' columns' : 'none'));
tr.appendChild(mk('td', 'meas', s && !isNaN(s.slope) ? fnum(s.slope, 2) : '…'));
tr.appendChild(mk('td', 'th', M.cls === 'free' ? '0' : M.cls === 'bc' ? '1' : '1/2'));
body.appendChild(tr);
});
$('s-cap').textContent = k >= 0 ? 'The eight curves at t = ' + fint(st.times[k]) : 'The eight curves';
}
function hoverSpace(x, tip) {
var cross = doc.getElementById('sp-cross');
if (!SP || x < SP.m.l - 6 || x > SP.m.l + SP.pw + 6) { if (cross) cross.setAttribute('visibility', 'hidden'); return false; }
var j = clamp(Math.round(SP.x0 + (x - SP.m.l) / SP.pw * (SP.x1 - SP.x0)), SP.x0, SP.x1), d = Math.pow(2, j), rows = [];
MODELS.forEach(function (M) {
var s = SP.data[M.id]; if (!s) return;
if (!SP.own) rows.push({ M: M, v: s.pts[j].v });
else if (!s.reach) rows.push({ M: M, v: 1 });
else if (d * s.reach >= 1 && d * s.reach <= s.pts[s.pts.length - 1].r) rows.push({ M: M, v: spAt(s.pts, d * s.reach) / s.far });
});
if (!rows.length) { if (cross) cross.setAttribute('visibility', 'hidden'); return false; }
rows.sort(function (a, b) { return b.v - a.v; });
if (cross) { cross.setAttribute('x1', SP.X(d)); cross.setAttribute('x2', SP.X(d)); cross.setAttribute('visibility', 'visible'); }
tip.innerHTML = '';
tip.appendChild(mk('div', 'tt', !SP.own ? 'Typical difference, ' + fint(d) + (d === 1 ? ' column apart' : ' columns apart')
: j === 0 ? 'One reach apart' : j < 0 ? 'At 1/' + Math.pow(2, -j) + ' of the reach' : fint(d) + ' reaches apart'));
rows.forEach(function (q) { tipRow(tip, '', 'var(--s' + q.M.slot + ')', SP.own ? Math.round(q.v * 100) + '%' : fnum(q.v, q.v < 10 ? 2 : 1), q.M.name); });
return true;
}
function statsText() {
var frac = st.total ? st.done / st.total : 0, sweepsDone = Math.floor(st.done / (MODELS.length * st.K));
$('m-bar').style.width = (100 * frac).toFixed(1) + '%';
var bricks = st.drops >= 1e9 ? fnum(st.drops / 1e9, 1) + ' billion' : fint(st.drops / 1e6) + ' million';
$('m-text').textContent = st.workers.length
? (st.paused ? 'Paused. ' : '') + 'Pile ' + Math.min(sweepsDone + 1, st.sweeps * st.runs) + ' of ' + (st.sweeps * st.runs) + ' per game, grown to t = ' + fint(st.times[st.K - 1]) + '. ' + bricks + ' pieces dropped so far.'
: 'Done: ' + (st.sweeps * st.runs) + ' piles per game, ' + bricks + ' pieces dropped.';
}
function statsFrame(ts) {
if (!st.ready || !st.dirty || ts - st.last < 220) return;
st.last = ts; st.dirty = false;
st.kAvail = kAvail();
drawGrowth(); drawDist(); drawTable(); drawSpace(); drawSpaceTable(); drawTrees(); drawTreeTable(); statsText();
}
// ---- hover read-outs ----
function tipRow(tip, keyCls, color, value, name) {
var row = mk('div', 'row'), key = mk('span', 'key' + (keyCls ? ' ' + keyCls : ''));
if (color) key.style.setProperty('--c', color);
row.appendChild(key); row.appendChild(mk('b', null, value)); row.appendChild(mk('span', 'nm', name));
tip.appendChild(row);
}
function placeTip(tip, plot, x, y) {
var w = tip.offsetWidth, hgt = tip.offsetHeight, W = plot.clientWidth, left = x + 14;
if (left + w > W) left = x - 14 - w;
tip.style.left = clamp(left, 0, Math.max(0, W - w)) + 'px';
tip.style.top = clamp(y - hgt / 2, 0, Math.max(0, plot.clientHeight - hgt)) + 'px';
}
function hoverSetup(svgId, render) {
var svg = $(svgId), plot = svg.parentNode, tip = mk('div', 'tip'); tip.hidden = true; plot.appendChild(tip);
function move(ev) {
var r = svg.getBoundingClientRect(), ok = render(ev.clientX - r.left, tip);
tip.hidden = !ok; if (ok) placeTip(tip, plot, ev.clientX - r.left, ev.clientY - r.top);
}
svg.addEventListener('pointermove', move); svg.addEventListener('pointerdown', move);
svg.addEventListener('pointerleave', function () { tip.hidden = true; render(-1, tip); });
}
function hoverGrowth(x, tip) {
var cross = doc.getElementById('gr-cross');
if (!GR || x < GR.m.l - 6 || x > GR.m.l + GR.pw + 6) { if (cross) cross.setAttribute('visibility', 'hidden'); return false; }
var k = clamp(Math.round((x - GR.m.l) / GR.pw * GR.xmax * 2), 0, st.K - 1), t = st.times[k], rows = [];
MODELS.forEach(function (M) { var a = st.agg[M.id][k]; if (st.show[M.id] && a) rows.push({ M: M, W: Math.sqrt(a.s2 / a.n) }); });
if (!rows.length) { if (cross) cross.setAttribute('visibility', 'hidden'); return false; }
rows.sort(function (a, b) { return b.W - a.W; });
if (cross) { cross.setAttribute('x1', GR.X(t)); cross.setAttribute('x2', GR.X(t)); cross.setAttribute('visibility', 'visible'); }
tip.innerHTML = ''; tip.appendChild(mk('div', 'tt', 'W at t = ' + fint(t)));
rows.forEach(function (q) { tipRow(tip, '', 'var(--s' + q.M.slot + ')', fnum(q.W, q.W < 10 ? 2 : 1), q.M.name); });
return true;
}
function hoverDist(x, tip) {
var cross = doc.getElementById('di-cross');
if (!DI || x < DI.m.l || x > DI.m.l + DI.pw) { if (cross) cross.setAttribute('visibility', 'hidden'); return false; }
var z = Math.round((DI.z0 + (x - DI.m.l) / DI.pw * (DI.z1 - DI.z0)) * 5) / 5;
if (cross) { cross.setAttribute('x1', DI.X(z)); cross.setAttribute('x2', DI.X(z)); cross.setAttribute('visibility', 'visible'); }
function f(v) { return isNaN(v) ? '–' : v >= 0.01 ? v.toFixed(3) : v.toExponential(1).replace('e-', '·10⁻').replace(/⁻(\d)$/, function (s, dg) { return '⁻' + '⁰¹²³⁴⁵⁶⁷⁸⁹'[+dg]; }); }
tip.innerHTML = ''; tip.appendChild(mk('div', 'tt', 'Density at ' + (z < 0 ? '−' : z > 0 ? '+' : '') + Math.abs(z).toFixed(1) + ' sd'));
tipRow(tip, 'ink', null, f(Math.exp(twLog(z))), 'Tracy–Widom');
tipRow(tip, 'dash', null, f(Math.exp(gaussLog(z))), 'Gaussian');
MODELS.forEach(function (M) { if (DI.data[M.id]) tipRow(tip, '', 'var(--s' + M.slot + ')', f(interp(DI.data[M.id], z)), M.name); });
if (DI.data.goe) tipRow(tip, 'ring', null, f(interp(DI.data.goe, z)), 'Largest eigenvalue');
return true;
}
function statsInit() {
var leg = $('m-legend');
function item(id, label, keyCls, color) {
var b = mk('button', 'chip'); b.type = 'button'; b.setAttribute('aria-pressed', 'true');
var key = mk('span', 'key' + (keyCls ? ' ' + keyCls : '')); if (color) key.style.setProperty('--c', color);
b.appendChild(key); b.appendChild(doc.createTextNode(label));
b.addEventListener('click', function () {
var on = b.getAttribute('aria-pressed') !== 'true';
b.setAttribute('aria-pressed', on ? 'true' : 'false');
if (id === 'goe') st.showGoe = on; else st.show[id] = on;
st.dirty = true; st.last = 0;
});
b.addEventListener('pointerenter', function () { st.hi = id; st.dirty = true; st.last = 0; });
b.addEventListener('pointerleave', function () { st.hi = null; st.dirty = true; st.last = 0; });
b.addEventListener('focus', function () { st.hi = id; st.dirty = true; st.last = 0; });
b.addEventListener('blur', function () { st.hi = null; st.dirty = true; st.last = 0; });
leg.appendChild(b);
}
MODELS.forEach(function (M) { item(M.id, M.name, '', 'var(--s' + M.slot + ')'); });
item('goe', 'Largest eigenvalue of a random matrix', 'ring', null);
var s1 = mk('span', 'static'); s1.appendChild(mk('span', 'key ink')); s1.appendChild(doc.createTextNode('Tracy–Widom')); leg.appendChild(s1);
var s2 = mk('span', 'static'); s2.appendChild(mk('span', 'key dash')); s2.appendChild(doc.createTextNode('Gaussian')); leg.appendChild(s2);
$('d-time').addEventListener('input', function () { st.dirty = true; st.last = 0; });
var segs = $('d-scale').querySelectorAll('button');
Array.prototype.forEach.call(segs, function (b) {
b.addEventListener('click', function () {
st.logy = b.dataset.scale === 'log';
Array.prototype.forEach.call(segs, function (o) { o.setAttribute('aria-pressed', o === b ? 'true' : 'false'); });
st.dirty = true; st.last = 0;
});
});
$('m-pause').addEventListener('click', function () {
st.paused = !st.paused;
this.textContent = st.paused ? 'Resume' : 'Pause';
st.workers.forEach(function (w) { w.post({ cmd: st.paused ? 'pause' : 'resume' }); });
st.dirty = true;
});
$('m-more').addEventListener('click', function () { statsRun(); st.dirty = true; });
doc.addEventListener('visibilitychange', function () {
if (st.paused) return;
st.workers.forEach(function (w) { w.post({ cmd: doc.hidden ? 'pause' : 'resume' }); });
});
hoverSetup('ch-growth', hoverGrowth); hoverSetup('ch-dist', hoverDist); hoverSetup('ch-trees', hoverTrees); hoverSetup('ch-space', hoverSpace);
// the chart along the surface has a legend of its own: click to hide a game, point to pick it out
var sleg = $('s-legend');
MODELS.forEach(function (M) {
var b = mk('button', 'chip'), key = mk('span', 'key'); b.type = 'button'; b.setAttribute('aria-pressed', 'true');
key.style.setProperty('--c', 'var(--s' + M.slot + ')'); b.appendChild(key); b.appendChild(doc.createTextNode(M.name));
sp.show[M.id] = true;
function pick(on) { return function () { sp.hi = on ? M.id : null; st.dirty = true; st.last = 0; }; }
b.addEventListener('click', function () {
sp.show[M.id] = !sp.show[M.id]; b.setAttribute('aria-pressed', sp.show[M.id] ? 'true' : 'false');
st.dirty = true; st.last = 0;
});
b.addEventListener('pointerenter', pick(true)); b.addEventListener('pointerleave', pick(false));
b.addEventListener('focus', pick(true)); b.addEventListener('blur', pick(false));
sleg.appendChild(b);
});
segmented($('s-units'), 'units', function (u) { sp.own = u === 'own'; st.dirty = true; st.last = 0; });
var fleg = $('f-legend');
TREE_IDS.forEach(function (id) {
var it = mk('span', 'static'), key = mk('span', 'key'); key.style.setProperty('--c', 'var(--s' + BYID[id].slot + ')');
it.appendChild(key); it.appendChild(doc.createTextNode(BYID[id].name)); fleg.appendChild(it);
});
var itx = mk('span', 'static'); itx.appendChild(mk('span', 'key dash')); itx.appendChild(doc.createTextNode('Exact, hot bricks')); fleg.appendChild(itx);
if (window.ResizeObserver) {
var cro = new ResizeObserver(function () { st.dirty = true; st.last = 0; });
cro.observe($('c-growth')); cro.observe($('c-trees')); cro.observe($('c-space'));
}
statsStart();
}
// ================= go =================
function refreshTheme() {
readTheme();
viewRedraw(hero); viewRedraw(fams);
cliff.panels.forEach(function (P) { P.dirty = true; });
lens.panels.forEach(drawLens);
}
readTheme();
heroInit(); famsInit(); cliffInit();
probeWorkers(function () { lensInit(); statsInit(); });
if (window.matchMedia) {
var mq = matchMedia('(prefers-color-scheme: dark)');
if (mq.addEventListener) mq.addEventListener('change', refreshTheme); else if (mq.addListener) mq.addListener(refreshTheme);
}
if (window.MutationObserver) new MutationObserver(refreshTheme).observe(root, { attributes: true, attributeFilter: ['data-theme', 'class', 'style'] });
var lastTs = 0, fc = 0, complaints = 0;
function safely(fn, a, b) { // one figure failing must never stop the others
try { fn(a, b); } catch (err) { if (complaints++ < 5 && window.console && console.error) console.error(err); }
}
function everything(dt, ts) {
safely(viewFrame, hero, dt); safely(viewFrame, fams, dt); safely(cliffFrame, dt); safely(lensFrame, dt); safely(statsFrame, ts);
}
function frame(ts) {
requestAnimationFrame(frame); // booked first, so that nothing below can break the chain
var dt = lastTs ? Math.min(0.05, Math.max(0, (ts - lastTs) / 1000)) : 0.016;
lastTs = ts;
if (++fc % 90 === 0) safely(function () { var cs = getComputedStyle(root), sig = cs.getPropertyValue('--surface') + cs.getPropertyValue('--s1'); if (sig !== THEME.sig) refreshTheme(); });
everything(dt, ts);
}
requestAnimationFrame(frame);
// A reload, or an update of the page, can put the sliders back where they were without telling anyone: follow them.
function followControls() {
var z = $('g-zoom'), sp = $('g-speed'), fs = $('f-speed'), zi = clamp(Math.round(+z.value) || 0, 0, hero.zooms.length - 1);
if (hero.sized && hero.zooms[zi] !== hero.cell) { hero.cell = hero.zooms[zi]; hero.zlabel(); viewRezoom(hero); }
if (+sp.value !== hero.speed) { hero.speed = +sp.value; $('g-speed-out').textContent = speedLabel(hero.speed); }
if (+fs.value !== fams.speed) { fams.speed = +fs.value; $('f-speed-out').textContent = speedLabel(fams.speed); }
var ws = $('w-speed');
if (ws && +ws.value !== cliff.speed) { cliff.speed = +ws.value; $('w-speed-out').textContent = speedLabel(cliff.speed); }
}
setTimeout(function () { safely(followControls); }, 500);
setTimeout(function () { safely(followControls); }, 2500);
window.addEventListener('pageshow', function () { safely(followControls); });
window.__gs = { E: E, MODELS: MODELS, hero: hero, fams: fams, cliff: cliff, lens: lens, st: st, Vis: Vis, frame: function (dt) { everything(dt, performance.now()); } };
})();
</script>
</body></html>
<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover"><style>:root{color-scheme:light;padding-top:env(safe-area-inset-top,0px);padding-bottom:env(safe-area-inset-bottom,0px)}body{margin:0;font:14px system-ui,sans-serif}img{max-width:100%}[hidden]{display:none}</style><meta name="description" content="Eight brick-dropping games that show KPZ universality, after Martin Hairer's random Tetris. Everything runs in your browser."></head><body><title>Randomly Growing Surfaces</title>
<meta name="claude:viewport-fit-sides" content="cover">
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=IBM+Plex+Sans:wght@400;500;600&family=STIX+Two+Text:ital,wght@0,400;0,600;1,400&display=swap">
<style>
/* Layout: one left-aligned reading column on cool paper; the live figures break out to the full measure as flat plates. */
:root {
--page: #f2f4f7;
--surface: #fbfbfc;
--ink: #14171c;
--ink-2: #474c56;
--ink-3: #747a85;
--rule: #dfe2e7;
--axis: #c0c5cd;
--ground: #d3d7de;
--focus: #2a78d6;
--s1: #2a78d6; --s2: #eb6834; --s3: #1baf7a; --s4: #eda100;
--s5: #e87ba4; --s6: #008300; --s7: #6250d6; --s8: #e34948;
--font-display: "STIX Two Text", Cambria, "Times New Roman", serif;
--font-ui: "IBM Plex Sans", system-ui, -apple-system, "Segoe UI", sans-serif;
--fs-0: 0.75rem; --fs-1: 0.8125rem; --fs-2: 0.9375rem; --fs-3: 1.0625rem; --fs-4: 1.25rem; --fs-5: 1.75rem;
}
@media (prefers-color-scheme: dark) {
:root:not([data-theme="light"]) {
--page: #0c0e11; --surface: #15181d; --ink: #eceef1; --ink-2: #b7bcc4; --ink-3: #878d97;
--rule: #252930; --axis: #3b4049; --ground: #2a2f37; --focus: #6da7ec;
--s1: #3987e5; --s2: #d95926; --s3: #199e70; --s4: #c98500;
--s5: #d55181; --s6: #0ca30c; --s7: #9085e9; --s8: #e66767;
color-scheme: dark;
}
}
:root[data-theme="dark"] {
--page: #0c0e11; --surface: #15181d; --ink: #eceef1; --ink-2: #b7bcc4; --ink-3: #878d97;
--rule: #252930; --axis: #3b4049; --ground: #2a2f37; --focus: #6da7ec;
--s1: #3987e5; --s2: #d95926; --s3: #199e70; --s4: #c98500;
--s5: #d55181; --s6: #0ca30c; --s7: #9085e9; --s8: #e66767;
color-scheme: dark;
}
body {
background: var(--page);
color: var(--ink);
font: 400 var(--fs-3)/1.55 var(--font-display);
-webkit-font-smoothing: antialiased;
}
.page {
max-width: 1200px;
margin: 0 auto;
padding-left: max(16px, env(safe-area-inset-left, 0px));
padding-right: max(16px, env(safe-area-inset-right, 0px));
padding-block: 44px 80px;
display: flex;
flex-direction: column;
gap: 64px;
}
h1, h2, h3, p, figure { margin: 0; }
h1, h2 { font-family: var(--font-display); font-weight: 600; text-wrap: balance; }
a { color: inherit; text-decoration-color: var(--axis); text-underline-offset: 0.18em; }
a:hover { text-decoration-color: currentColor; }
:focus-visible { outline: 2px solid var(--focus); outline-offset: 2px; border-radius: 3px; }
.math { font-family: var(--font-display); font-style: italic; white-space: nowrap; }
.math .rm { font-style: normal; }
.ratio { font-style: italic; font-weight: 400; white-space: nowrap; letter-spacing: 0.02em; }
/* ---- masthead ---- */
.masthead { display: flex; flex-direction: column; gap: 14px; }
.eyebrow {
font: 500 var(--fs-0)/1.3 var(--font-ui);
letter-spacing: 0.09em; text-transform: uppercase; color: var(--ink-3);
}
h1 { font-size: clamp(2.4rem, 1.5rem + 4.2vw, 4.1rem); line-height: 1.02; letter-spacing: -0.012em; }
.lede { font-size: var(--fs-4); line-height: 1.45; color: var(--ink-2); max-width: 62ch; text-wrap: pretty; }
/* ---- sections ---- */
.fig { display: flex; flex-direction: column; gap: 16px; min-width: 0; }
.fig-head { display: flex; flex-direction: column; gap: 10px; max-width: 68ch; }
.fig-head h2 { font-size: var(--fs-5); line-height: 1.15; }
.fig-head p, .prose p { color: var(--ink-2); text-wrap: pretty; }
.caption { font: 400 var(--fs-1)/1.5 var(--font-ui); color: var(--ink-3); max-width: 86ch; }
.caption strong { font-weight: 500; color: var(--ink-2); }
.sr-only { position: absolute; width: 1px; height: 1px; overflow: hidden; clip-path: inset(50%); white-space: nowrap; }
/* ---- controls ---- */
.toolbar {
display: flex; flex-wrap: wrap; align-items: center; gap: 10px 22px;
font: 400 var(--fs-1)/1.2 var(--font-ui); color: var(--ink-2);
}
.toolbar .group { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; }
.toolbar .label { color: var(--ink-3); }
.btn {
font: 500 var(--fs-1)/1 var(--font-ui);
color: var(--ink); background: var(--surface);
border: 1px solid var(--axis); border-radius: 6px;
padding: 8px 12px; min-height: 34px; cursor: pointer;
}
.btn:hover { border-color: var(--ink-3); }
.btn.primary { background: var(--ink); color: var(--page); border-color: var(--ink); min-width: 74px; }
.btn.primary:hover { opacity: 0.88; }
.slider { display: inline-flex; align-items: center; gap: 8px; white-space: nowrap; }
.slider input[type="range"] { width: 132px; accent-color: var(--ink); cursor: pointer; }
.slider output { min-width: 5.2em; color: var(--ink-3); font-variant-numeric: tabular-nums; }