Prompt specification
Build or customize the Three.js 3D scene "Repeated-sampling convergence explorer" inside the active workspace.
Engineering Constraints:
1. Runtime & Orbit: Use Three.js r160 with OrbitControls (damping enabled) and ACESFilmicToneMapping.
2. Frame Timing: Drive all motion strictly with clock.getDelta() so animation speed is FPS-independent.
3. Viewport Hygiene: Handle window resize cleanly, cap DPR at Math.min(window.devicePixelRatio, 2), and dispose geometries/materials/renderer on unmount.
Scene Metadata:
Scene: Repeated-sampling convergence explorer
Category: Algorithms & Systems · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/repeated-sampling-convergence-explorer-x1796
Scene Description Prompt:
Adjust probability and trial count across seeded low-poly coin experiments; illustrate long-run convergence without predicting the next toss. Three.js from cdnjs, standalone HTML.
Acceptance criteria: Make the 3D evidence and sampling display visible in the very first 1100×800 viewport. No required evidence should be below an independent scroll area at initialization.
Technical checks: Place the low-poly coins and repeated-sampling results within the initial 1100×800 view. Keep the required evidence visible without scrolling.
Return one complete HTML document. The file must run in a sandbox allowing inline scripts and the cdnjs Three.js r160 module. Construct procedural assets, use local event handlers and avoid remote assets, runtime network requests besides Three.js, pointer lock and native form submission. Keep the main requested geometry visible in the initial view.
Working Three.js Starter (repeated-sampling-convergence-explorer-x1796):
```html
<!doctype html>
<html lang="pt-BR">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Convergência — experimentos de moeda low-poly</title>
<style>
:root {
color-scheme: dark;
--bg: #07101c;
--panel: #0c1727;
--panel-2: #101d30;
--line: rgba(167, 196, 225, 0.14);
--text: #eef5ff;
--muted: #94a8bf;
--gold: #f2c45c;
--gold-soft: #ffe4a2;
--cyan: #72d8e7;
--pink: #ee8ca5;
--green: #8fe0ae;
--radius: 16px;
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: var(--bg);
}
body {
color: var(--text);
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
font-size: 14px;
}
button,
input {
font: inherit;
}
button:focus-visible,
input:focus-visible {
outline: 2px solid var(--cyan);
outline-offset: 2px;
}
.app {
width: 100%;
height: 100%;
display: grid;
grid-template-rows: 70px minmax(0, 1fr);
background:
radial-gradient(circle at 12% 5%, rgba(63, 107, 152, 0.15), transparent 31%),
linear-gradient(145deg, #07101c 0%, #091321 52%, #06101a 100%);
}
.topbar {
display: flex;
align-items: center;
justify-content: space-between;
gap: 18px;
padding: 0 18px;
border-bottom: 1px solid var(--line);
background: rgba(6, 14, 25, 0.78);
backdrop-filter: blur(14px);
}
.brand {
min-width: 0;
display: flex;
align-items: center;
gap: 13px;
}
.brand-mark {
position: relative;
width: 38px;
height: 38px;
flex: 0 0 auto;
border: 3px solid var(--gold);
border-radius: 50%;
background: linear-gradient(145deg, #ffe39a, #c68c26);
box-shadow: inset 0 0 0 4px rgba(91, 55, 12, 0.18), 0 6px 20px rgba(242, 196, 92, 0.16);
}
.brand-mark::before,
.brand-mark::after {
content: "";
position: absolute;
top: 8px;
bottom: 8px;
width: 4px;
border-radius: 2px;
background: #7d5316;
}
.brand-mark::before {
left: 10px;
}
.brand-mark::after {
right: 10px;
}
.brand-copy {
min-width: 0;
}
h1 {
margin: 0;
overflow: hidden;
font-size: clamp(16px, 1.6vw, 21px);
line-height: 1.1;
letter-spacing: -0.02em;
text-overflow: ellipsis;
white-space: nowrap;
}
.subtitle {
margin-top: 4px;
color: var(--muted);
font-size: 11px;
letter-spacing: 0.02em;
white-space: nowrap;
}
.top-status {
display: flex;
align-items: center;
justify-content: flex-end;
gap: 10px;
flex-wrap: wrap;
}
.status-pill,
.no-forecast {
display: inline-flex;
align-items: center;
min-height: 30px;
padding: 6px 10px;
border: 1px solid var(--line);
border-radius: 999px;
color: #c9d7e7;
background: rgba(18, 34, 52, 0.66);
font-size: 10px;
font-weight: 750;
letter-spacing: 0.07em;
text-transform: uppercase;
white-space: nowrap;
}
.status-pill::before {
content: "";
width: 7px;
height: 7px;
margin-right: 7px;
border-radius: 50%;
background: var(--green);
box-shadow: 0 0 10px rgba(143, 224, 174, 0.7);
}
.status-pill.dirty {
color: var(--gold-soft);
border-color: rgba(242, 196, 92, 0.28);
}
.status-pill.dirty::before {
background: var(--gold);
box-shadow: 0 0 10px rgba(242, 196, 92, 0.7);
}
.no-forecast {
color: var(--cyan);
border-color: rgba(114, 216, 231, 0.24);
background: rgba(114, 216, 231, 0.07);
}
main {
min-height: 0;
display: grid;
grid-template-columns: minmax(0, 1.42fr) minmax(390px, 0.92fr);
gap: 12px;
padding: 12px 14px 14px;
}
.panel {
min-width: 0;
min-height: 0;
overflow: hidden;
border: 1px solid var(--line);
border-radius: var(--radius);
background: linear-gradient(160deg, rgba(17, 30, 48, 0.97), rgba(8, 18, 31, 0.97));
box-shadow: 0 20px 55px rgba(0, 0, 0, 0.22);
}
.stage {
position: relative;
isolation: isolate;
background:
radial-gradient(circle at 44% 38%, rgba(54, 84, 119, 0.2), transparent 37%),
linear-gradient(180deg, #0b1727, #07111e);
}
#viewport {
position: absolute;
inset: 0;
}
#viewport canvas {
width: 100%;
height: 100%;
display: block;
cursor: grab;
touch-action: none;
}
#viewport canvas:active {
cursor: grabbing;
}
.stage-head {
position: absolute;
z-index: 3;
top: 16px;
left: 17px;
right: 17px;
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 12px;
pointer-events: none;
}
.eyebrow {
margin-bottom: 5px;
color: var(--gold);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.13em;
text-transform: uppercase;
}
.stage-title {
margin: 0;
font-size: clamp(17px, 1.7vw, 22px);
letter-spacing: -0.025em;
}
.stage-subtitle {
margin-top: 5px;
color: var(--muted);
font-size: 11px;
}
.camera-reset {
pointer-events: auto;
min-height: 31px;
padding: 7px 10px;
border: 1px solid var(--line);
border-radius: 10px;
color: #dbe7f5;
background: rgba(7, 16, 28, 0.72);
cursor: pointer;
font-size: 11px;
}
.camera-reset:hover {
border-color: rgba(114, 216, 231, 0.35);
color: var(--cyan);
}
.stage-bottom {
position: absolute;
z-index: 3;
left: 16px;
right: 16px;
bottom: 15px;
display: flex;
align-items: flex-end;
justify-content: space-between;
gap: 14px;
pointer-events: none;
}
.result-card,
.sequence-card {
border: 1px solid rgba(167, 196, 225, 0.15);
border-radius: 13px;
background: rgba(6, 15, 27, 0.78);
box-shadow: 0 12px 30px rgba(0, 0, 0, 0.2);
backdrop-filter: blur(10px);
}
.result-card {
min-width: 196px;
padding: 10px 12px;
}
.result-label {
color: var(--muted);
font-size: 9px;
font-weight: 750;
letter-spacing: 0.1em;
text-transform: uppercase;
}
.result-main {
display: flex;
align-items: baseline;
gap: 8px;
margin-top: 3px;
}
#replay-result {
color: var(--gold-soft);
font-size: 20px;
font-weight: 850;
letter-spacing: -0.02em;
}
#replay-index {
color: #c4d2e3;
font-size: 11px;
font-variant-numeric: tabular-nums;
}
.sequence-card {
max-width: 285px;
padding: 9px 10px 10px;
}
.sequence-title {
margin-bottom: 7px;
color: var(--muted);
font-size: 9px;
font-weight: 750;
letter-spacing: 0.09em;
text-transform: uppercase;
}
#sequence-chips {
display: flex;
gap: 5px;
justify-content: flex-end;
}
.sequence-chip {
width: 13px;
height: 13px;
border-radius: 50%;
border: 2px solid rgba(255, 255, 255, 0.17);
background: var(--cyan);
box-shadow: 0 2px 7px rgba(0, 0, 0, 0.25);
}
.sequence-chip.heads {
background: var(--gold);
}
.sequence-chip.tails {
background: var(--cyan);
}
.webgl-error {
position: absolute;
inset: 50% auto auto 50%;
width: min(420px, calc(100% - 40px));
padding: 18px;
transform: translate(-50%, -50%);
border: 1px solid rgba(238, 140, 165, 0.35);
border-radius: 12px;
color: #ffdce4;
background: rgba(47, 13, 25, 0.88);
text-align: center;
}
.sampling {
display: grid;
grid-template-rows: auto auto auto auto minmax(170px, 1fr) auto;
gap: 10px;
padding: 14px;
}
.section-head {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
}
.section-title {
margin: 0;
font-size: 16px;
letter-spacing: -0.015em;
}
.section-kicker {
color: var(--muted);
font-size: 10px;
text-align: right;
}
.controls {
padding: 10px;
border: 1px solid var(--line);
border-radius: 13px;
background: rgba(5, 13, 24, 0.44);
}
.control-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 10px 12px;
}
.field {
min-width: 0;
}
.field label {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
margin-bottom: 6px;
color: #b7c7d9;
font-size: 10px;
font-weight: 700;
letter-spacing: 0.035em;
text-transform: uppercase;
}
.field output {
color: var(--gold-soft);
font-size: 11px;
font-variant-numeric: tabular-nums;
}
input[type="range"] {
width: 100%;
height: 18px;
margin: 0;
accent-color: var(--gold);
cursor: pointer;
}
input[type="number"] {
width: 100%;
height: 31px;
padding: 6px 8px;
border: 1px solid rgba(167, 196, 225, 0.18);
border-radius: 8px;
color: var(--text);
background: #0b1727;
font-size: 12px;
font-variant-numeric: tabular-nums;
}
input[type="number"]:hover,
input[type="number"]:focus {
border-color: rgba(114, 216, 231, 0.46);
}
.actions {
display: grid;
grid-template-columns: 1.12fr 0.88fr 0.7fr;
gap: 6px;
align-self: end;
}
.action {
min-height: 31px;
padding: 6px 7px;
border: 1px solid rgba(167, 196, 225, 0.17);
border-radius: 8px;
color: #d9e5f2;
background: #142338;
cursor: pointer;
font-size: 10px;
font-weight: 750;
white-space: nowrap;
}
.action:hover {
border-color: rgba(114, 216, 231, 0.42);
color: var(--cyan);
}
.action.primary {
border-color: rgba(242, 196, 92, 0.42);
color: #20170a;
background: linear-gradient(135deg, #f8d77e, #dda843);
}
.action.primary:hover {
color: #20170a;
filter: brightness(1.08);
}
.stats {
display: grid;
grid-template-columns: repeat(4, minmax(0, 1fr));
gap: 7px;
}
.stat {
min-width: 0;
padding: 8px 8px 7px;
border: 1px solid var(--line);
border-radius: 10px;
background: rgba(16, 30, 48, 0.7);
}
.stat-name {
overflow: hidden;
color: var(--muted);
font-size: 8px;
font-weight: 750;
letter-spacing: 0.08em;
text-overflow: ellipsis;
text-transform: uppercase;
white-space: nowrap;
}
.stat-value {
margin-top: 3px;
overflow: hidden;
color: #f5f9ff;
font-size: clamp(13px, 1.3vw, 16px);
font-weight: 820;
font-variant-numeric: tabular-nums;
letter-spacing: -0.02em;
text-overflow: ellipsis;
white-space: nowrap;
}
.stat-value.gold {
color: var(--gold-soft);
}
.outcome-bar {
height: 8px;
overflow: hidden;
display: flex;
border-radius: 999px;
background: #17263a;
}
#bar-heads {
width: 50%;
background: linear-gradient(90deg, #d69e36, #f7cf72);
transition: width 220ms ease;
}
#bar-tails {
width: 50%;
background: linear-gradient(90deg, #54bdcd, #89e5ee);
transition: width 220ms ease;
}
.chart-block {
min-height: 0;
display: flex;
flex-direction: column;
overflow: hidden;
border: 1px solid var(--line);
border-radius: 13px;
background: rgba(4, 12, 22, 0.52);
}
.chart-head {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
padding: 9px 10px 6px;
}
.chart-title {
color: #dce8f5;
font-size: 11px;
font-weight: 750;
}
.legend {
display: flex;
align-items: center;
gap: 9px;
color: var(--muted);
font-size: 8px;
white-space: nowrap;
}
.legend span {
display: inline-flex;
align-items: center;
gap: 4px;
}
.legend i {
width: 13px;
height: 2px;
display: inline-block;
background: currentColor;
}
.legend .observed {
color: var(--gold);
}
.legend .target {
color: var(--pink);
}
.legend .band {
color: var(--cyan);
}
#chart {
width: 100%;
min-height: 0;
flex: 1;
display: block;
}
.chart-note {
padding: 0 10px 7px;
color: #738aa3;
font-size: 8px;
text-align: right;
}
.insight {
padding: 9px 10px;
border: 1px solid rgba(114, 216, 231, 0.16);
border-radius: 12px;
background: linear-gradient(135deg, rgba(114, 216, 231, 0.07), rgba(242, 196, 92, 0.04));
}
.insight-top {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
margin-bottom: 4px;
}
.insight-title {
color: var(--cyan);
font-size: 9px;
font-weight: 800;
letter-spacing: 0.09em;
text-transform: uppercase;
}
#band-status {
padding: 3px 6px;
border-radius: 999px;
color: var(--green);
background: rgba(143, 224, 174, 0.09);
font-size: 8px;
font-weight: 750;
white-space: nowrap;
}
#band-status.outside {
color: var(--gold-soft);
background: rgba(242, 196, 92, 0.09);
}
#insight-text {
margin: 0;
color: #c2d1e0;
font-size: 10px;
line-height: 1.4;
}
.insight-note {
margin-top: 4px;
color: #8298b0;
font-size: 9px;
line-height: 1.35;
}
@media (max-width: 900px), (max-height: 650px) {
html,
body {
height: auto;
min-height: 100%;
overflow: auto;
}
.app {
height: auto;
min-height: 100vh;
grid-template-rows: auto auto;
}
.topbar {
min-height: 70px;
padding: 12px 14px;
}
.top-status .no-forecast {
display: none;
}
main {
grid-template-columns: 1fr;
overflow: visible;
}
.stage {
height: 520px;
}
.sampling {
min-height: 660px;
}
}
@media (max-width: 560px) {
.subtitle,
.status-pill {
display: none;
}
.stage-bottom {
align-items: stretch;
flex-direction: column;
}
.sequence-card {
max-width: none;
}
#sequence-chips {
justify-content: flex-start;
}
.control-grid {
grid-template-columns: 1fr;
}
.actions {
grid-template-columns: 1fr 1fr 1fr;
}
}
</style>
</head>
<body>
<div class="app">
<header class="topbar">
<div class="brand">
<div class="brand-mark" aria-hidden="true"></div>
<div class="brand-copy">
<h1>Convergência de moeda · laboratório seeded</h1>
<div class="subtitle">Evidência empírica reproduzível em 3D low-poly, sem previsão do próximo lançamento</div>
</div>
</div>
<div class="top-status">
<span class="no-forecast">Histórico, não previsão</span>
<span class="status-pill" id="status-pill">Experimento pronto</span>
</div>
</header>
<main>
<section class="panel stage" aria-label="Evidência tridimensional da moeda">
<div id="viewport" aria-label="Cena 3D procedural com moeda low-poly e amostras recentes"></div>
<div class="stage-head">
<div>
<div class="eyebrow">Evidência 3D</div>
<h2 class="stage-title">Moeda procedural < 12 lados</h2>
<div class="stage-subtitle">Arraste para orbitar · roda para zoom · geometria gerada localmente</div>
</div>
<button class="camera-reset" id="camera-reset" type="button">Restaurar câmera</button>
</div>
<div class="stage-bottom">
<div class="result-card">
<div class="result-label">Última amostra reproduzida</div>
<div class="result-main">
<span id="replay-result">CARA</span>
<span id="replay-index">1 / 10.000</span>
</div>
</div>
<div class="sequence-card">
<div class="sequence-title">Janela recente · CARA / COROA</div>
<div id="sequence-chips" aria-label="Amostras recentes"></div>
</div>
</div>
</section>
<section class="panel sampling" aria-label="Controles e resultado da amostragem">
<div class="section-head">
<div>
<div class="eyebrow">Amostragem</div>
<h2 class="section-title">Experimento completo</h2>
</div>
<div class="section-kicker" id="experiment-meta">semente 240731 · N = 10.000</div>
</div>
<div class="controls">
<div class="control-grid">
<div class="field">
<label for="probability">Probabilidade de cara <output id="probability-output">50%</output></label>
<input id="probability" type="range" min="0" max="1" step="0.01" value="0.5">
</div>
<div class="field">
<label for="trials">Número de ensaios</label>
<input id="trials" type="number" min="100" max="100000" step="100" value="10000" inputmode="numeric">
</div>
<div class="field">
<label for="seed">Semente</label>
<input id="seed" type="number" min="0" max="4294967295" step="1" value="240731" inputmode="numeric">
</div>
<div class="actions">
<button class="action primary" id="apply" type="button">Aplicar</button>
<button class="action" id="play-pause" type="button">Pausar</button>
<button class="action" id="jump-end" type="button">Final</button>
</div>
</div>
</div>
<div class="stats" aria-label="Estatísticas do experimento">
<div class="stat">
<div class="stat-name">Amostras</div>
<div class="stat-value" id="stat-n">10.000</div>
</div>
<div class="stat">
<div class="stat-name">Caras</div>
<div class="stat-value gold" id="stat-heads">—</div>
</div>
<div class="stat">
<div class="stat-name">Coroas</div>
<div class="stat-value" id="stat-tails">—</div>
</div>
<div class="stat">
<div class="stat-name">Frequência</div>
<div class="stat-value" id="stat-frequency">—</div>
</div>
</div>
<div class="outcome-bar" aria-label="Proporção de caras e coroas">
<div id="bar-heads"></div>
<div id="bar-tails"></div>
</div>
<div class="chart-block">
<div class="chart-head">
<div class="chart-title">Frequência acumulada</div>
<div class="legend" aria-label="Legenda do gráfico">
<span class="band"><i></i>banda 95%</span>
<span class="target"><i></i>p</span>
<span class="observed"><i></i>observada</span>
</div>
</div>
<canvas id="chart" aria-label="Gráfico da frequência observada ao longo dos ensaios"></canvas>
<div class="chart-note">Escala horizontal logarítmica de N · curva completa já calculada</div>
</div>
<div class="insight">
<div class="insight-top">
<span class="insight-title">Leitura da convergência</span>
<span id="band-status">Dentro da banda</span>
</div>
<p id="insight-text">Calculando o experimento…</p>
<div class="insight-note">p é a taxa-alvo configurada. Ela não informa qual será o próximo resultado.</div>
</div>
</section>
</main>
</div>
<script type="module">
import * as THREE from "https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
const $ = (id) => document.getElementById(id);
const formatInt = new Intl.NumberFormat("pt-BR");
const formatPct = (value, digits = 2) =>
new Intl.NumberFormat("pt-BR", {
style: "percent",
minimumFractionDigits: digits,
maximumFractionDigits: digits
}).format(value);
const probabilityInput = $("probability");
const probabilityOutput = $("probability-output");
const trialsInput = $("trials");
const seedInput = $("seed");
const applyButton = $("apply");
const playPauseButton = $("play-pause");
const jumpEndButton = $("jump-end");
const statusPill = $("status-pill");
const experimentMeta = $("experiment-meta");
const replayResult = $("replay-result");
const replayIndex = $("replay-index");
const sequenceChips = $("sequence-chips");
const chart = $("chart");
const chartContext = chart.getContext("2d");
const state = {
p: 0.5,
n: 10000,
seed: 240731,
results: new Uint8Array(0),
cumulativeHeads: new Uint32Array(1),
heads: 0,
tails: 0,
currentIndex: -1,
replayElapsed: 0,
playing: true,
dirty: false
};
function mulberry32(seed) {
let a = seed >>> 0;
return function () {
a = (a + 0x6D2B79F5) >>> 0;
let t = a;
t = Math.imul(t ^ (t >>> 15), t | 1);
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
}
function readParameters() {
const p = Math.min(1, Math.max(0, Number(probabilityInput.value) || 0));
const n = Math.min(100000, Math.max(100, Math.round(Number(trialsInput.value) || 100)));
const seed = Math.min(4294967295, Math.max(0, Math.round(Number(seedInput.value) || 0)));
probabilityInput.value = String(p);
trialsInput.value = String(n);
seedInput.value = String(seed);
return { p, n, seed };
}
function markDirty() {
state.dirty = true;
statusPill.textContent = "Parâmetros alterados";
statusPill.classList.add("dirty");
}
probabilityInput.addEventListener("input", () => {
probabilityOutput.value = `${Math.round(Number(probabilityInput.value) * 100)}%`;
probabilityOutput.textContent = probabilityOutput.value;
markDirty();
});
trialsInput.addEventListener("input", markDirty);
seedInput.addEventListener("input", markDirty);
function buildExperiment({ p, n, seed }) {
const random = mulberry32(seed);
const results = new Uint8Array(n);
const cumulativeHeads = new Uint32Array(n + 1);
let heads = 0;
for (let i = 0; i < n; i += 1) {
const isHead = random() < p;
results[i] = isHead ? 1 : 0;
heads += isHead ? 1 : 0;
cumulativeHeads[i + 1] = heads;
}
state.p = p;
state.n = n;
state.seed = seed;
state.results = results;
state.cumulativeHeads = cumulativeHeads;
state.heads = heads;
state.tails = n - heads;
state.currentIndex = -1;
state.replayElapsed = 0;
state.playing = true;
state.dirty = false;
statusPill.textContent = "Experimento pronto";
statusPill.classList.remove("dirty");
experimentMeta.textContent = `semente ${formatInt.format(seed)} · N = ${formatInt.format(n)}`;
playPauseButton.textContent = "Pausar";
updateStatistics();
drawChart();
onReplayStep(0);
}
function updateStatistics() {
const frequency = state.heads / state.n;
const error = Math.abs(frequency - state.p);
const standardError = Math.sqrt((state.p * (1 - state.p)) / state.n);
const band = 1.96 * standardError;
const insideBand = error <= band;
$("stat-n").textContent = formatInt.format(state.n);
$("stat-heads").textContent = formatInt.format(state.heads);
$("stat-tails").textContent = formatInt.format(state.tails);
$("stat-frequency").textContent = formatPct(frequency);
$("bar-heads").style.width = `${frequency * 100}%`;
$("bar-tails").style.width = `${(1 - frequency) * 100}%`;
$("insight-text").textContent =
`f = ${formatPct(frequency)} · |f − p| = ${formatPct(error)} · banda 95% de referência: ±${formatPct(band)} em N = ${formatInt.format(state.n)}.`;
const status = $("band-status");
status.textContent = insideBand ? "Dentro da banda" : "Fora da banda";
status.classList.toggle("outside", !insideBand);
}
function resizeChart() {
const rect = chart.getBoundingClientRect();
if (rect.width < 2 || rect.height < 2) return;
const ratio = Math.min(window.devicePixelRatio || 1, 2);
chart.width = Math.round(rect.width * ratio);
chart.height = Math.round(rect.height * ratio);
chartContext.setTransform(ratio, 0, 0, ratio, 0, 0);
drawChart();
}
function drawChart() {
if (!state.n || !chartContext) return;
const rect = chart.getBoundingClientRect();
const width = rect.width;
const height = rect.height;
if (width < 2 || height < 2) return;
const ctx = chartContext;
ctx.clearRect(0, 0, width, height);
const left = 37;
const right = 11;
const top = 8;
const bottom = 24;
const plotWidth = Math.max(1, width - left - right);
const plotHeight = Math.max(1, height - top - bottom);
const logMax = Math.log10(Math.max(10, state.n));
const xAt = (sampleIndex) => {
const logValue = Math.log10(Math.max(1, sampleIndex + 1));
return left + (logValue / logMax) * plotWidth;
};
const yAt = (frequency) => top + (1 - frequency) * plotHeight;
ctx.save();
ctx.font = "9px Inter, system-ui, sans-serif";
ctx.textBaseline = "middle";
for (const level of [0, 0.25, 0.5, 0.75, 1]) {
const y = yAt(level);
ctx.beginPath();
ctx.moveTo(left, y);
ctx.lineTo(width - right, y);
ctx.strokeStyle = level === state.p ? "rgba(238,140,165,0.16)" : "rgba(167,196,225,0.10)";
ctx.lineWidth = 1;
ctx.stroke();
ctx.fillStyle = "#70859d";
ctx.textAlign = "right";
ctx.fillText(`${Math.round(level * 100)}%`, left - 7, y);
}
const xTicks = [1, 10, 100, 1000, 10000, 100000].filter((tick) => tick <= state.n);
ctx.textAlign = "center";
ctx.textBaseline = "top";
for (const tick of xTicks) {
const x = left + (Math.log10(tick) / logMax) * plotWidth;
ctx.beginPath();
ctx.moveTo(x, top);
ctx.lineTo(x, height - bottom);
ctx.strokeStyle = "rgba(167,196,225,0.065)";
ctx.stroke();
ctx.fillStyle = "#70859d";
ctx.fillText(tick >= 1000 ? `${tick / 1000}k` : String(tick), x, height - bottom + 7);
}
const upper = [];
const lower = [];
const steps = 280;
for (let step = 0; step <= steps; step += 1) {
const u = step / steps;
const sampleIndex = Math.min(state.n - 1, Math.max(0, Math.round(Math.pow(10, u * logMax) - 1)));
const sampleSize = sampleIndex + 1;
const error = 1.96 * Math.sqrt((state.p * (1 - state.p)) / sampleSize);
upper.push([xAt(sampleIndex), yAt(Math.min(1, state.p + error))]);
lower.push([xAt(sampleIndex), yAt(Math.max(0, state.p - error))]);
}
ctx.beginPath();
upper.forEach(([x, y], index) => index === 0 ? ctx.moveTo(x, y) : ctx.lineTo(x, y));
[...lower].reverse().forEach(([x, y]) => ctx.lineTo(x, y));
ctx.closePath();
ctx.fillStyle = "rgba(114,216,231,0.10)";
ctx.fill();
ctx.beginPath();
ctx.moveTo(left, yAt(state.p));
ctx.lineTo(width - right, yAt(state.p));
ctx.setLineDash([5, 4]);
ctx.strokeStyle = "#ee8ca5";
ctx.lineWidth = 1.4;
ctx.stroke();
ctx.setLineDash([]);
ctx.beginPath();
for (let step = 0; step <= steps; step += 1) {
const u = step / steps;
const sampleIndex = Math.min(state.n - 1, Math.max(0, Math.round(Math.pow(10, u * logMax) - 1)));
const frequency = state.cumulativeHeads[sampleIndex + 1] / (sampleIndex + 1);
const x = xAt(sampleIndex);
const y = yAt(frequency);
step === 0 ? ctx.moveTo(x, y) : ctx.lineTo(x, y);
}
ctx.strokeStyle = "#f2c45c";
ctx.lineWidth = 2;
ctx.lineJoin = "round";
ctx.stroke();
const finalFrequency = state.heads / state.n;
const finalX = xAt(state.n - 1);
const finalY = yAt(finalFrequency);
ctx.beginPath();
ctx.arc(finalX, finalY, 3.3, 0, Math.PI * 2);
ctx.fillStyle = "#ffe4a2";
ctx.fill();
ctx.fillStyle = "#9eb1c7";
ctx.textAlign = "right";
ctx.textBaseline = "bottom";
ctx.fillText("N (log)", width - right, height - 2);
ctx.restore();
}
applyButton.addEventListener("click", () => {
buildExperiment(readParameters());
});
playPauseButton.addEventListener("click", () => {
if (state.currentIndex >= state.n - 1) {
state.replayElapsed = 0;
state.currentIndex = -1;
state.playing = true;
onReplayStep(0);
} else {
state.playing = !state.playing;
}
playPauseButton.textContent = state.playing ? "Pausar" : "Reproduzir";
});
jumpEndButton.addEventListener("click", () => {
state.playing = false;
state.replayElapsed = state.n * 220;
state.currentIndex = state.n - 1;
playPauseButton.textContent = "Reproduzir";
onReplayStep(state.n - 1);
});
const chipElements = [];
for (let i = 0; i < 12; i += 1) {
const chip = document.createElement("span");
chip.className = "sequence-chip";
chip.title = "Amostra histórica";
sequenceChips.appendChild(chip);
chipElements.push(chip);
}
let sceneApi = null;
function onReplayStep(index) {
if (index < 0 || index >= state.n) return;
state.currentIndex = index;
const result = state.results[index];
replayResult.textContent = result ? "CARA" : "COROA";
replayResult.style.color = result ? "var(--gold-soft)" : "var(--cyan)";
replayIndex.textContent = `${formatInt.format(index + 1)} / ${formatInt.format(state.n)}`;
const start = Math.max(0, index - 11);
for (let slot = 0; slot < chipElements.length; slot += 1) {
const sourceIndex = start + slot;
const chip = chipElements[slot];
if (sourceIndex >= state.n) {
chip.style.opacity = "0.2";
chip.className = "sequence-chip";
continue;
}
const head = state.results[sourceIndex] === 1;
chip.style.opacity = sourceIndex === index ? "1" : "0.68";
chip.className = `sequence-chip ${head ? "heads" : "tails"}`;
}
if (sceneApi) sceneApi.updateSample(result, index);
}
function createScene() {
const viewport = $("viewport");
const renderer = new THREE.WebGLRenderer({
antialias: true,
alpha: true,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
renderer.setClearColor(0x000000, 0);
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.08;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
viewport.appendChild(renderer.domElement);
const scene = new THREE.Scene();
scene.fog = new THREE.Fog(0x081321, 8, 18);
const camera = new THREE.PerspectiveCamera(38, 1, 0.1, 40);
const view = {
radius: 7.25,
phi: 1.17,
theta: 0.36,
target: new THREE.Vector3(0.05, 0.92, 0)
};
function updateCamera() {
const spherical = new THREE.Spherical(view.radius, view.phi, view.theta);
camera.position.setFromSpherical(spherical).add(view.target);
camera.lookAt(view.target);
}
function resize() {
const width = Math.max(1, viewport.clientWidth);
const height = Math.max(1, viewport.clientHeight);
renderer.setSize(width, height, false);
camera.aspect = width / height;
camera.updateProjectionMatrix();
updateCamera();
}
const resizeObserver = new ResizeObserver(resize);
resizeObserver.observe(viewport);
resize();
const hemisphere = new THREE.HemisphereLight(0xb9d8ff, 0x101522, 2.25);
scene.add(hemisphere);
const keyLight = new THREE.DirectionalLight(0xffedc4, 4.2);
keyLight.position.set(-3.5, 6.5, 4.5);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(1024, 1024);
keyLight.shadow.camera.left = -6;
keyLight.shadow.camera.right = 6;
keyLight.shadow.camera.top = 6;
keyLight.shadow.camera.bottom = -6;
keyLight.shadow.bias = -0.0008;
scene.add(keyLight);
const rimLight = new THREE.PointLight(0x5ed8ef, 18, 9, 2);
rimLight.position.set(3.5, 2.8, -1.5);
scene.add(rimLight);
const warmLight = new THREE.PointLight(0xffb83f, 11, 6, 2);
warmLight.position.set(-2.8, 1.2, 2.5);
scene.add(warmLight);
const floorMaterial = new THREE.MeshStandardMaterial({
color: 0x091522,
roughness: 0.92,
metalness: 0.05
});
const floor = new THREE.Mesh(new THREE.PlaneGeometry(28, 28), floorMaterial);
floor.rotation.x = -Math.PI / 2;
floor.position.y = -0.18;
floor.receiveShadow = true;
scene.add(floor);
const grid = new THREE.GridHelper(20, 20, 0x35506a, 0x20354b);
grid.position.y = -0.165;
grid.material.transparent = true;
grid.material.opacity = 0.18;
scene.add(grid);
const pedestalMaterial = new THREE.MeshStandardMaterial({
color: 0x17283c,
roughness: 0.56,
metalness: 0.28,
flatShading: true
});
const pedestalTopMaterial = new THREE.MeshStandardMaterial({
color: 0x263c55,
roughness: 0.38,
metalness: 0.44,
flatShading: true
});
const pedestal = new THREE.Mesh(
new THREE.CylinderGeometry(1.18, 1.34, 0.38, 12),
pedestalMaterial
);
pedestal.position.set(-0.6, 0.02, 0.1);
pedestal.castShadow = true;
pedestal.receiveShadow = true;
scene.add(pedestal);
const pedestalTop = new THREE.Mesh(
new THREE.CylinderGeometry(1.1, 1.1, 0.055, 12),
pedestalTopMaterial
);
pedestalTop.position.set(-0.6, 0.225, 0.1);
pedestalTop.castShadow = true;
pedestalTop.receiveShadow = true;
scene.add(pedestalTop);
const pedestalRing = new THREE.Mesh(
new THREE.TorusGeometry(0.92, 0.025, 4, 24),
new THREE.MeshBasicMaterial({
color: 0xf2c45c,
transparent: true,
opacity: 0.44
})
);
pedestalRing.rotation.x = Math.PI / 2;
pedestalRing.position.set(-0.6, 0.263, 0.1);
scene.add(pedestalRing);
const coinRoot = new THREE.Group();
coinRoot.position.set(-0.6, 1.3, 0.12);
coinRoot.scale.setScalar(1.13);
scene.add(coinRoot);
const coinTilt = new THREE.Group();
coinTilt.rotation.x = Math.PI / 2;
coinRoot.add(coinTilt);
const edgeMaterial = new THREE.MeshStandardMaterial({
color: 0x9b671b,
roughness: 0.33,
metalness: 0.82,
flatShading: true
});
const faceMaterial = new THREE.MeshStandardMaterial({
color: 0xf0bd4e,
roughness: 0.34,
metalness: 0.76,
flatShading: true
});
const backMaterial = new THREE.MeshStandardMaterial({
color: 0xd49a32,
roughness: 0.42,
metalness: 0.72,
flatShading: true
});
const coinMesh = new THREE.Mesh(
new THREE.CylinderGeometry(0.77, 0.77, 0.19, 12, 1, false),
[edgeMaterial, faceMaterial, backMaterial]
);
coinMesh.castShadow = true;
coinMesh.receiveShadow = true;
coinTilt.add(coinMesh);
const rimMaterial = new THREE.MeshStandardMaterial({
color: 0xffd878,
roughness: 0.26,
metalness: 0.82,
flatShading: true
});
const rim = new THREE.Mesh(
new THREE.TorusGeometry(0.59, 0.035, 4, 12),
rimMaterial
);
rim.rotation.x = Math.PI / 2;
rim.position.y = 0.108;
rim.castShadow = true;
coinTilt.add(rim);
const emblemMaterial = new THREE.MeshStandardMaterial({
color: 0xffdf83,
roughness: 0.28,
metalness: 0.7,
flatShading: true
});
const emblem = new THREE.Mesh(
new THREE.CylinderGeometry(0.255, 0.255, 0.042, 5),
emblemMaterial
);
emblem.position.y = 0.112;
emblem.castShadow = true;
coinTilt.add(emblem);
const rail = new THREE.Mesh(
new THREE.BoxGeometry(2.05, 0.075, 0.38),
pedestalTopMaterial
);
rail.position.set(1.18, 0.25, 0.03);
rail.castShadow = true;
rail.receiveShadow = true;
scene.add(rail);
const tokenGeometry = new THREE.CylinderGeometry(0.115, 0.115, 0.06, 8);
const tokens = [];
for (let i = 0; i < 12; i += 1) {
const tokenMaterials = [
new THREE.MeshStandardMaterial({ color: 0x876126, roughness: 0.48, metalness: 0.55, flatShading: true }),
new THREE.MeshStandardMaterial({ color: 0xf2c45c, roughness: 0.34, metalness: 0.66, flatShading: true }),
new THREE.MeshStandardMaterial({ color: 0xdca33e, roughness: 0.38, metalness: 0.62, flatShading: true })
];
const token = new THREE.Mesh(tokenGeometry, tokenMaterials);
token.rotation.x = Math.PI / 2;
token.position.set(
0.35 + i * 0.15,
0.49 + (i % 3) * 0.075,
0.03 + Math.sin(i * 0.82) * 0.11
);
token.castShadow = true;
token.userData.materials = tokenMaterials;
scene.add(token);
tokens.push(token);
}
const haloMaterial = new THREE.MeshBasicMaterial({
color: 0x4b91b5,
transparent: true,
opacity: 0.17,
depthWrite: false
});
const halo = new THREE.Mesh(new THREE.TorusGeometry(2.15, 0.025, 4, 32), haloMaterial);
halo.position.set(-0.2, 1.45, -2.25);
scene.add(halo);
const halo2 = new THREE.Mesh(
new THREE.TorusGeometry(1.66, 0.018, 4, 28),
new THREE.MeshBasicMaterial({
color: 0xf2c45c,
transparent: true,
opacity: 0.14,
depthWrite: false
})
);
halo2.position.set(-0.2, 1.45, -2.22);
scene.add(halo2);
let currentAngle = 0;
let targetAngle = 0;
function updateSample(result, index) {
targetAngle += Math.PI;
const start = Math.max(0, index - 11);
for (let slot = 0; slot < tokens.length; slot += 1) {
const sourceIndex = start + slot;
const token = tokens[slot];
const head = state.results[sourceIndex] === 1;
const color = head ? 0xf2c45c : 0x72d8e7;
const emissive = head ? 0x5f3808 : 0x123f47;
token.userData.materials[1].color.setHex(color);
token.userData.materials[1].emissive.setHex(emissive);
token.userData.materials[1].emissiveIntensity = sourceIndex === index ? 0.42 : 0.12;
token.scale.setScalar(sourceIndex === index ? 1.28 : 1);
}
}
let dragging = false;
let pointerX = 0;
let pointerY = 0;
renderer.domElement.addEventListener("pointerdown", (event) => {
dragging = true;
pointerX = event.clientX;
pointerY = event.clientY;
renderer.domElement.setPointerCapture(event.pointerId);
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (!dragging) return;
const deltaX = event.clientX - pointerX;
const deltaY = event.clientY - pointerY;
pointerX = event.clientX;
pointerY = event.clientY;
view.theta -= deltaX * 0.006;
view.phi = Math.min(1.48, Math.max(0.76, view.phi - deltaY * 0.005));
updateCamera();
});
renderer.domElement.addEventListener("pointerup", (event) => {
dragging = false;
if (renderer.domElement.hasPointerCapture(event.pointerId)) {
renderer.domElement.releasePointerCapture(event.pointerId);
}
});
renderer.domElement.addEventListener("pointercancel", () => {
dragging = false;
});
renderer.domElement.addEventListener("wheel", (event) => {
event.preventDefault();
view.radius = Math.min(9.4, Math.max(5.35, view.radius + event.deltaY * 0.003));
updateCamera();
}, { passive: false });
$("camera-reset").addEventListener("click", () => {
view.radius = 7.25;
view.phi = 1.17;
view.theta = 0.36;
updateCamera();
});
const clock = new THREE.Clock();
renderer.setAnimationLoop(() => {
const delta = Math.min(clock.getDelta(), 0.05);
const elapsed = clock.elapsedTime;
coinRoot.position.y = 1.31 + Math.sin(elapsed * 1.65) * 0.045;
coinRoot.rotation.z = Math.sin(elapsed * 0.7) * 0.025;
currentAngle += (targetAngle - currentAngle) * (1 - Math.exp(-delta * 7.5));
coinRoot.rotation.y = currentAngle;
halo.rotation.z = elapsed * 0.025;
halo2.rotation.z = -elapsed * 0.018;
renderer.render(scene, camera);
});
return { updateSample };
}
try {
sceneApi = createScene();
} catch (error) {
console.error(error);
const errorMessage = document.createElement("div");
errorMessage.className = "webgl-error";
errorMessage.textContent = "Não foi possível iniciar o WebGL. A amostragem 2D permanece disponível, mas a evidência 3D exige aceleração gráfica habilitada.";
$("viewport").appendChild(errorMessage);
}
const chartObserver = new ResizeObserver(resizeChart);
chartObserver.observe(chart);
probabilityOutput.value = "50%";
probabilityOutput.textContent = "50%";
buildExperiment(readParameters());
requestAnimationFrame(resizeChart);
let previousTime = performance.now();
function updateReplay(now) {
const delta = Math.min(100, now - previousTime);
previousTime = now;
if (state.playing) {
state.replayElapsed += delta;
const nextIndex = Math.min(state.n - 1, Math.floor(state.replayElapsed / 220));
if (nextIndex !== state.currentIndex) onReplayStep(nextIndex);
if (state.currentIndex >= state.n - 1) {
state.playing = false;
playPauseButton.textContent = "Reproduzir";
}
}
requestAnimationFrame(updateReplay);
}
requestAnimationFrame(updateReplay);
</script>
</body>
</html>
```