Prompt specification
Build or customize the Three.js 3D scene "Interaction-rule mixing 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: Interaction-rule mixing explorer
Category: Science & Physics · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/interaction-rule-mixing-explorer-x1980
Scene Description Prompt:
Please use Three.js from cdnjs for a low-poly scene based on this idea: interaction-rule mixing explorer. Let users compare explicitly simplified attraction rules in a small particle model; show clustering or mixing qualitatively and state that real solubility depends on more than polarity alone. Return one self-contained HTML file.
Working Three.js Starter (interaction-rule-mixing-explorer-x1980):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Mix Lab — Interaction-Rule Mixing Explorer</title>
<style>
:root {
color-scheme: dark;
--bg: #081018;
--panel: #101a24;
--panel-2: #14212d;
--line: rgba(185, 222, 226, 0.14);
--line-strong: rgba(185, 222, 226, 0.28);
--text: #edf7f6;
--muted: #93a8ae;
--a: #64e6d2;
--b: #ffb45e;
--accent: #b6f36a;
--danger: #ff8e83;
--shadow: 0 24px 70px rgba(0, 0, 0, 0.35);
}
* {
box-sizing: border-box;
}
html,
body {
min-height: 100%;
}
body {
margin: 0;
color: var(--text);
background:
radial-gradient(circle at 14% 4%, rgba(100, 230, 210, 0.10), transparent 28rem),
radial-gradient(circle at 88% 14%, rgba(255, 180, 94, 0.08), transparent 30rem),
var(--bg);
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
font-size: 14px;
line-height: 1.45;
}
button,
input {
font: inherit;
}
button {
color: inherit;
}
button:focus-visible,
input:focus-visible {
outline: 2px solid var(--accent);
outline-offset: 3px;
}
.topbar {
width: min(1540px, calc(100% - 32px));
margin: 0 auto;
padding: 22px 0 18px;
display: flex;
align-items: center;
justify-content: space-between;
gap: 20px;
border-bottom: 1px solid var(--line);
}
.brand {
display: flex;
align-items: center;
gap: 14px;
min-width: 0;
}
.brand-mark {
width: 42px;
height: 42px;
flex: 0 0 auto;
position: relative;
background: linear-gradient(145deg, var(--a), #3daab2);
clip-path: polygon(25% 5%, 75% 5%, 100% 50%, 75% 95%, 25% 95%, 0 50%);
box-shadow: 0 0 34px rgba(100, 230, 210, 0.24);
}
.brand-mark::before,
.brand-mark::after {
content: "";
position: absolute;
width: 8px;
height: 8px;
border-radius: 50%;
background: #0b1720;
}
.brand-mark::before {
left: 10px;
top: 11px;
}
.brand-mark::after {
right: 9px;
bottom: 10px;
background: var(--b);
}
.eyebrow {
margin: 0 0 2px;
color: var(--accent);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.16em;
text-transform: uppercase;
}
h1 {
margin: 0;
font-size: clamp(20px, 2.5vw, 30px);
line-height: 1.1;
letter-spacing: -0.035em;
}
.subtitle {
margin: 6px 0 0;
color: var(--muted);
font-size: 13px;
}
.top-actions {
display: flex;
align-items: center;
justify-content: flex-end;
gap: 10px;
flex-wrap: wrap;
}
.status-pill,
.quiet-button {
border: 1px solid var(--line);
background: rgba(255, 255, 255, 0.035);
border-radius: 999px;
padding: 9px 13px;
color: #c7d9da;
font-size: 12px;
}
.status-pill {
display: inline-flex;
align-items: center;
gap: 8px;
}
.status-dot {
width: 7px;
height: 7px;
border-radius: 50%;
background: var(--accent);
box-shadow: 0 0 12px rgba(182, 243, 106, 0.7);
}
.quiet-button {
cursor: pointer;
transition: border-color 160ms ease, background 160ms ease;
}
.quiet-button:hover {
border-color: var(--line-strong);
background: rgba(255, 255, 255, 0.065);
}
.app {
width: min(1540px, calc(100% - 32px));
margin: 20px auto 34px;
display: grid;
grid-template-columns: 320px minmax(0, 1fr);
gap: 18px;
align-items: start;
}
.panel {
position: sticky;
top: 18px;
overflow: auto;
max-height: calc(100vh - 36px);
padding: 18px;
border: 1px solid var(--line);
border-radius: 18px;
background: linear-gradient(180deg, rgba(20, 33, 45, 0.97), rgba(13, 23, 32, 0.97));
box-shadow: var(--shadow);
scrollbar-width: thin;
scrollbar-color: #334652 transparent;
}
.section {
padding-bottom: 20px;
margin-bottom: 20px;
border-bottom: 1px solid var(--line);
}
.section:last-of-type {
margin-bottom: 0;
}
.section-heading {
display: flex;
align-items: baseline;
justify-content: space-between;
gap: 10px;
margin-bottom: 12px;
}
.section-heading h2,
.section-heading h3 {
margin: 0;
font-size: 13px;
letter-spacing: 0.01em;
}
.section-number {
color: var(--muted);
font: 700 10px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: 0.13em;
}
.help-text {
margin: -4px 0 14px;
color: var(--muted);
font-size: 11.5px;
}
.mode-note {
margin: 0 0 13px;
padding: 9px 10px;
border: 1px solid rgba(182, 243, 106, 0.16);
border-radius: 9px;
background: rgba(182, 243, 106, 0.055);
color: #bfcdb5;
font-size: 11px;
}
.rule-control {
margin: 0 0 16px;
}
.rule-label {
display: grid;
grid-template-columns: 78px 1fr 50px;
align-items: center;
gap: 10px;
margin-bottom: 8px;
}
.rule-label > span:first-child {
color: #d7e6e5;
font-size: 12px;
font-weight: 700;
}
.rule-label output,
.control-label output {
color: var(--accent);
font: 700 12px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
text-align: right;
}
.rule-caption {
grid-column: 2 / 4;
color: var(--muted);
font-size: 10px;
margin-top: -2px;
}
input[type="range"] {
--fill: 50%;
width: 100%;
height: 4px;
margin: 0;
border-radius: 99px;
appearance: none;
background: linear-gradient(
to right,
var(--accent) 0,
var(--accent) var(--fill),
#2a3944 var(--fill),
#2a3944 100%
);
cursor: pointer;
}
input[type="range"]::-webkit-slider-thumb {
width: 15px;
height: 15px;
border: 3px solid #17232c;
border-radius: 50%;
appearance: none;
background: var(--accent);
box-shadow: 0 0 0 1px rgba(182, 243, 106, 0.35);
}
input[type="range"]::-moz-range-thumb {
width: 10px;
height: 10px;
border: 3px solid #17232c;
border-radius: 50%;
background: var(--accent);
}
.preset-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
margin-top: 13px;
}
.preset-button {
min-height: 70px;
padding: 10px;
border: 1px solid var(--line);
border-radius: 10px;
background: rgba(255, 255, 255, 0.025);
text-align: left;
cursor: pointer;
transition: transform 150ms ease, border-color 150ms ease, background 150ms ease;
}
.preset-button:hover {
transform: translateY(-1px);
border-color: var(--line-strong);
background: rgba(255, 255, 255, 0.055);
}
.preset-button.active {
border-color: rgba(182, 243, 106, 0.48);
background: rgba(182, 243, 106, 0.07);
}
.preset-button strong {
display: block;
margin-bottom: 4px;
font-size: 11.5px;
}
.preset-button small {
display: block;
color: var(--muted);
font-size: 10px;
line-height: 1.35;
}
.control-row {
margin-bottom: 16px;
}
.control-label {
display: flex;
align-items: baseline;
justify-content: space-between;
gap: 10px;
margin-bottom: 8px;
color: #d7e6e5;
font-size: 12px;
font-weight: 700;
}
.button-row {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
}
.primary-button,
.secondary-button {
min-height: 40px;
border-radius: 9px;
cursor: pointer;
transition: transform 150ms ease, filter 150ms ease;
}
.primary-button:hover,
.secondary-button:hover {
transform: translateY(-1px);
filter: brightness(1.08);
}
.primary-button {
border: 1px solid rgba(182, 243, 106, 0.42);
background: var(--accent);
color: #15200c;
font-weight: 800;
}
.secondary-button {
border: 1px solid var(--line);
background: rgba(255, 255, 255, 0.045);
color: var(--text);
font-weight: 700;
}
.insight {
padding: 12px;
border: 1px solid rgba(100, 230, 210, 0.17);
border-radius: 11px;
background: linear-gradient(135deg, rgba(100, 230, 210, 0.075), rgba(100, 230, 210, 0.025));
}
.insight-label {
color: var(--a);
font-size: 9px;
font-weight: 800;
letter-spacing: 0.14em;
text-transform: uppercase;
}
.insight strong {
display: block;
margin: 5px 0 3px;
font-size: 12px;
}
.insight p {
margin: 0;
color: var(--muted);
font-size: 10.5px;
line-height: 1.45;
}
.main-area {
min-width: 0;
}
.viewbar {
display: flex;
align-items: center;
justify-content: space-between;
gap: 14px;
margin-bottom: 10px;
min-height: 43px;
}
.segmented {
display: inline-flex;
gap: 3px;
padding: 3px;
border: 1px solid var(--line);
border-radius: 10px;
background: rgba(255, 255, 255, 0.025);
}
.segmented button {
min-height: 33px;
padding: 0 12px;
border: 0;
border-radius: 7px;
background: transparent;
color: var(--muted);
cursor: pointer;
font-size: 11px;
font-weight: 750;
}
.segmented button.active {
background: #243541;
color: var(--text);
box-shadow: inset 0 0 0 1px var(--line);
}
.legend {
display: flex;
align-items: center;
gap: 15px;
color: var(--muted);
font-size: 11px;
}
.legend-item {
display: inline-flex;
align-items: center;
gap: 7px;
}
.legend-dot {
width: 9px;
height: 9px;
border-radius: 2px;
transform: rotate(45deg);
}
.legend-dot.a {
background: var(--a);
box-shadow: 0 0 10px rgba(100, 230, 210, 0.35);
}
.legend-dot.b {
background: var(--b);
box-shadow: 0 0 10px rgba(255, 180, 94, 0.35);
}
.stage {
position: relative;
height: clamp(500px, 67vh, 720px);
overflow: hidden;
border: 1px solid var(--line);
border-radius: 18px;
background:
linear-gradient(rgba(255, 255, 255, 0.017) 1px, transparent 1px),
linear-gradient(90deg, rgba(255, 255, 255, 0.017) 1px, transparent 1px),
radial-gradient(circle at 50% 48%, #142631 0, #0a141d 63%, #081018 100%);
background-size: 30px 30px, 30px 30px, auto;
box-shadow: var(--shadow);
}
#scene {
position: absolute;
inset: 0;
width: 100%;
height: 100%;
display: block;
touch-action: none;
cursor: grab;
}
#scene:active {
cursor: grabbing;
}
.loading {
position: absolute;
inset: 0;
display: grid;
place-items: center;
color: var(--muted);
font-size: 12px;
pointer-events: none;
}
.viewport-overlay {
position: absolute;
top: 0;
bottom: 0;
z-index: 2;
pointer-events: none;
}
.viewport-overlay + .viewport-overlay {
border-left: 1px solid rgba(185, 222, 226, 0.10);
}
.viewport-title {
position: absolute;
top: 14px;
left: 14px;
right: 12px;
display: grid;
grid-template-columns: 24px 1fr;
gap: 3px 8px;
align-items: center;
text-shadow: 0 2px 12px #000;
}
.viewport-index {
grid-row: 1 / 3;
display: grid;
place-items: center;
width: 24px;
height: 24px;
border: 1px solid var(--line-strong);
border-radius: 7px;
background: rgba(8, 16, 24, 0.72);
color: var(--accent);
font: 800 9px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
}
.viewport-title strong {
font-size: 12px;
}
.viewport-title small {
color: var(--muted);
font-size: 9.5px;
}
.viewport-metrics {
position: absolute;
left: 14px;
right: 14px;
bottom: 13px;
display: flex;
gap: 8px;
flex-wrap: wrap;
}
.metric-chip {
padding: 7px 9px;
border: 1px solid var(--line);
border-radius: 8px;
background: rgba(8, 16, 24, 0.78);
backdrop-filter: blur(8px);
color: var(--muted);
font-size: 9px;
line-height: 1.2;
}
.metric-chip b {
display: block;
margin-top: 2px;
color: var(--text);
font: 800 13px/1.1 ui-monospace, SFMono-Regular, Menlo, monospace;
}
.stage-hint {
position: absolute;
top: 14px;
right: 14px;
z-index: 3;
padding: 7px 9px;
border: 1px solid var(--line);
border-radius: 8px;
background: rgba(8, 16, 24, 0.66);
color: var(--muted);
font-size: 9.5px;
pointer-events: none;
}
.comparison-heading {
display: flex;
align-items: baseline;
justify-content: space-between;
gap: 12px;
margin: 18px 2px 9px;
}
.comparison-heading h2 {
margin: 0;
font-size: 13px;
}
.comparison-heading span {
color: var(--muted);
font-size: 10px;
}
.comparison-grid {
display: grid;
grid-template-columns: repeat(3, minmax(0, 1fr));
gap: 10px;
}
.comparison-card {
position: relative;
min-width: 0;
padding: 13px;
border: 1px solid var(--line);
border-radius: 12px;
background: rgba(16, 26, 36, 0.76);
cursor: pointer;
transition: transform 160ms ease, border-color 160ms ease, background 160ms ease;
}
.comparison-card:hover {
transform: translateY(-2px);
border-color: var(--line-strong);
background: rgba(20, 33, 45, 0.96);
}
.comparison-card .card-index {
position: absolute;
top: 12px;
right: 12px;
color: #5e747c;
font: 800 9px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
}
.comparison-card h3 {
margin: 0 24px 3px 0;
font-size: 12px;
}
.comparison-card .card-description {
min-height: 32px;
margin: 0 0 10px;
color: var(--muted);
font-size: 10px;
line-height: 1.4;
}
.rule-values {
display: flex;
gap: 5px;
flex-wrap: wrap;
margin-bottom: 11px;
}
.rule-value {
padding: 3px 6px;
border: 1px solid var(--line);
border-radius: 5px;
color: #b8c9cc;
font: 700 9px/1.2 ui-monospace, SFMono-Regular, Menlo, monospace;
}
.card-metrics {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
margin-bottom: 10px;
}
.card-metric {
padding: 8px;
border-radius: 8px;
background: rgba(255, 255, 255, 0.025);
}
.card-metric span {
display: block;
color: var(--muted);
font-size: 8.5px;
}
.card-metric b {
display: block;
margin-top: 3px;
font: 800 16px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
}
.card-metric:first-child b {
color: var(--a);
}
.card-metric:last-child b {
color: var(--b);
}
.mini-track {
height: 3px;
overflow: hidden;
border-radius: 99px;
background: #293944;
}
.mini-track i {
display: block;
width: 0;
height: 100%;
border-radius: inherit;
background: linear-gradient(90deg, var(--a), var(--b));
transition: width 240ms ease;
}
.explore-link {
color: var(--accent);
font-size: 9.5px;
font-weight: 750;
}
.disclaimer {
margin-top: 12px;
padding: 13px 15px;
border: 1px solid rgba(255, 180, 94, 0.18);
border-radius: 12px;
background: rgba(255, 180, 94, 0.045);
color: #b9c5c2;
font-size: 10.5px;
line-height: 1.55;
}
.disclaimer strong {
color: var(--b);
}
@media (max-width: 1050px) {
.app {
grid-template-columns: 280px minmax(0, 1fr);
}
.stage {
height: 580px;
}
.viewport-title small,
.stage-hint {
display: none;
}
}
@media (max-width: 820px) {
.topbar {
align-items: flex-start;
}
.top-actions .status-pill {
display: none;
}
.app {
grid-template-columns: 1fr;
}
.panel {
position: static;
max-height: none;
}
.stage {
height: 570px;
}
.comparison-grid {
grid-template-columns: 1fr;
}
}
@media (max-width: 560px) {
.topbar,
.app {
width: min(100% - 20px, 1540px);
}
.subtitle {
display: none;
}
.viewbar {
align-items: flex-start;
flex-direction: column;
}
.stage {
height: 520px;
}
.viewport-title {
left: 7px;
right: 7px;
}
.viewport-title strong {
font-size: 9px;
}
.viewport-title small {
display: none;
}
.viewport-index {
width: 20px;
height: 20px;
}
.viewport-metrics {
left: 7px;
right: 7px;
gap: 4px;
}
.metric-chip {
padding: 5px 6px;
font-size: 7.5px;
}
.metric-chip b {
font-size: 10px;
}
}
</style>
</head>
<body>
<header class="topbar">
<div class="brand">
<div class="brand-mark" aria-hidden="true"></div>
<div>
<p class="eyebrow">Qualitative particle sandbox</p>
<h1>Mix Lab</h1>
<p class="subtitle">Compare simplified pairwise attraction rules and watch local order emerge.</p>
</div>
</div>
<div class="top-actions">
<div class="status-pill"><span class="status-dot"></span>Live 3D model</div>
<button class="quiet-button" id="resetCamera" type="button">Reset camera</button>
</div>
</header>
<main class="app">
<aside class="panel" aria-label="Simulation controls">
<section class="section">
<div class="section-heading">
<h2>Interaction rule</h2>
<span class="section-number">01 / RULE</span>
</div>
<p class="help-text">
Positive scores attract; negative scores repel. Scores are dimensionless toy parameters,
not physical energies.
</p>
<p class="mode-note" id="modeNote">
Compare mode uses three fixed presets. Switch to Explore to edit a custom rule.
</p>
<div class="rule-control">
<label class="rule-label" for="ruleAA">
<span>A · A</span>
<input id="ruleAA" type="range" min="-1" max="1.5" step="0.05" value="1.1" />
<output id="ruleAAOut">+1.10</output>
<small class="rule-caption">Same-species A attraction</small>
</label>
</div>
<div class="rule-control">
<label class="rule-label" for="ruleAB">
<span>A · B</span>
<input id="ruleAB" type="range" min="-1" max="1.5" step="0.05" value="-0.35" />
<output id="ruleABOut">−0.35</output>
<small class="rule-caption">Unlike-species attraction</small>
</label>
</div>
<div class="rule-control">
<label class="rule-label" for="ruleBB">
<span>B · B</span>
<input id="ruleBB" type="range" min="-1" max="1.5" step="0.05" value="1.1" />
<output id="ruleBBOut">+1.10</output>
<small class="rule-caption">Same-species B attraction</small>
</label>
</div>
<div class="preset-grid" id="presetGrid" aria-label="Rule presets"></div>
</section>
<section class="section">
<div class="section-heading">
<h2>Conditions</h2>
<span class="section-number">02 / SYSTEM</span>
</div>
<div class="control-row">
<label class="control-label" for="particleCount">
<span>Particle count</span>
<output id="particleCountOut">72</output>
</label>
<input id="particleCount" type="range" min="40" max="96" step="8" value="72" />
</div>
<div class="control-row">
<label class="control-label" for="agitation">
<span>Random agitation</span>
<output id="agitationOut">0.28</output>
</label>
<input id="agitation" type="range" min="0" max="1.2" step="0.02" value="0.28" />
</div>
<div class="control-row">
<label class="control-label" for="speed">
<span>Simulation speed</span>
<output id="speedOut">1.0×</output>
</label>
<input id="speed" type="range" min="0.25" max="2" step="0.05" value="1" />
</div>
<div class="button-row">
<button class="primary-button" id="pauseButton" type="button">Pause</button>
<button class="secondary-button" id="shuffleButton" type="button">Re-seed</button>
</div>
</section>
<section class="insight" aria-live="polite">
<span class="insight-label">Current interpretation</span>
<strong id="insightTitle">Type-selective clustering</strong>
<p id="insightText">
A and B prefer their own kind, so same-species neighborhoods should become more prominent.
</p>
</section>
</aside>
<section class="main-area">
<div class="viewbar">
<div class="segmented" role="tablist" aria-label="View mode">
<button id="exploreTab" type="button" role="tab" aria-selected="false">Explore rule</button>
<button id="compareTab" class="active" type="button" role="tab" aria-selected="true">Compare presets</button>
</div>
<div class="legend" aria-label="Particle legend">
<span class="legend-item"><i class="legend-dot a"></i>Species A</span>
<span class="legend-item"><i class="legend-dot b"></i>Species B</span>
</div>
</div>
<div class="stage" id="stage">
<canvas id="scene" aria-label="Interactive three-dimensional particle simulation"></canvas>
<div class="loading" id="loading">Loading the particle model…</div>
<div id="viewportOverlays"></div>
<div class="stage-hint">Drag to orbit · scroll to zoom</div>
</div>
<div class="comparison-heading">
<h2>Live rule comparison</h2>
<span>Metric: share of each particle’s six nearest neighbors</span>
</div>
<div class="comparison-grid" id="comparisonGrid"></div>
<div class="disclaimer">
<strong>Interpretation boundary:</strong> polarity is only one variable. Real solubility also
depends on molecular size and shape, hydrogen bonding, dispersion forces, entropy,
temperature, solvent structure, and the full solvent–solute free energy. This toy model
demonstrates qualitative clustering and mixing patterns only; it does not predict actual
solubility.
</div>
</section>
</main>
<script type="module">
import * as THREE from "https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
const PRESETS = [
{
id: "like",
name: "Like-like clusters",
short: "Like-like",
description: "A–A and B–B attract; A–B repels.",
values: [1.10, -0.35, 1.10]
},
{
id: "cross",
name: "Opposite attraction",
short: "Cross attraction",
description: "A–B attracts; same-species attraction is weak.",
values: [0.05, 1.20, 0.05]
},
{
id: "neutral",
name: "No preference",
short: "Indifferent",
description: "All pair scores are zero, so species identity is irrelevant.",
values: [0, 0, 0]
}
];
const COLOR_A = new THREE.Color("#64e6d2");
const COLOR_B = new THREE.Color("#ffb45e");
const state = {
compare: true,
paused: false,
count: 72,
agitation: 0.28,
speed: 1,
seed: 73421,
customRule: { aa: 1.10, ab: -0.35, bb: 1.10 },
camera: { theta: 0.72, phi: 1.12, zoom: 1 }
};
const $ = (id) => document.getElementById(id);
const stage = $("stage");
const canvas = $("scene");
const renderer = new THREE.WebGLRenderer({
canvas,
antialias: true,
alpha: true,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.13;
renderer.autoClear = false;
const camera = new THREE.OrthographicCamera(-5, 5, 4, -4, 0.1, 100);
const particleGeometry = new THREE.IcosahedronGeometry(0.34, 0);
const dummy = new THREE.Object3D();
function mulberry32(seed) {
let a = seed >>> 0;
return function () {
a |= 0;
a = (a + 0x6D2B79F5) | 0;
let t = Math.imul(a ^ (a >>> 15), 1 | a);
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
}
function signed(value) {
if (Math.abs(value) < 0.0001) return "0.00";
return `${value > 0 ? "+" : "−"}${Math.abs(value).toFixed(2)}`;
}
class ParticleSimulation {
constructor(count, rule, seed) {
this.count = count;
this.rule = { ...rule };
this.reset(seed);
}
reset(seed) {
this.rng = mulberry32(seed);
this.particles = [];
this.metrics = { mix: 0.5, same: 0.5, cohesion: 0 };
const half = Math.floor(this.count / 2);
const species = [
...Array(half).fill(0),
...Array(this.count - half).fill(1)
];
for (let i = species.length - 1; i > 0; i--) {
const j = Math.floor(this.rng() * (i + 1));
[species[i], species[j]] = [species[j], species[i]];
}
for (let i = 0; i < this.count; i++) {
let x = 0;
let y = 0;
let z = 0;
let accepted = false;
for (let attempt = 0; attempt < 100; attempt++) {
x = (this.rng() - 0.5) * 6.5;
y = (this.rng() - 0.5) * 4.3;
z = (this.rng() - 0.5) * 4.0;
let clear = true;
for (const other of this.particles) {
const dx = x - other.x;
const dy = y - other.y;
const dz = z - other.z;
if (dx * dx + dy * dy + dz * dz < 0.52 * 0.52) {
clear = false;
break;
}
}
if (clear) {
accepted = true;
break;
}
}
this.particles.push({
x,
y,
z,
vx: (this.rng() - 0.5) * 0.08,
vy: (this.rng() - 0.5) * 0.08,
vz: (this.rng() - 0.5) * 0.08,
fx: 0,
fy: 0,
fz: 0,
species: species[i],
rx: this.rng() * Math.PI,
ry: this.rng() * Math.PI,
rz: this.rng() * Math.PI
});
}
this.computeMetrics();
}
pairStrength(a, b) {
if (a === 0 && b === 0) return this.rule.aa;
if (a === 1 && b === 1) return this.rule.bb;
return this.rule.ab;
}
step(dt) {
const particles = this.particles;
const count = particles.length;
const range = 2.5;
const rangeSq = range * range;
const minDistance = 0.68;
for (const p of particles) {
p.fx = -p.x * 0.012;
p.fy = -p.y * 0.012;
p.fz = -p.z * 0.012;
}
for (let i = 0; i < count; i++) {
const a = particles[i];
for (let j = i + 1; j < count; j++) {
const b = particles[j];
let dx = b.x - a.x;
let dy = b.y - a.y;
let dz = b.z - a.z;
let distSq = dx * dx + dy * dy + dz * dz;
if (distSq >= rangeSq) continue;
if (distSq < 0.000001) {
dx = 0.0001;
dy = 0;
dz = 0;
distSq = 0.00000001;
}
const dist = Math.sqrt(distSq);
const nx = dx / dist;
const ny = dy / dist;
const nz = dz / dist;
const q = 1 - dist / range;
const strength = this.pairStrength(a.species, b.species);
const attraction = strength * q * q * 2.4;
let fx = nx * attraction;
let fy = ny * attraction;
let fz = nz * attraction;
if (dist < minDistance) {
const overlap = minDistance - dist;
const separation = overlap * 12;
fx -= nx * separation;
fy -= ny * separation;
fz -= nz * separation;
}
a.fx += fx;
a.fy += fy;
a.fz += fz;
b.fx -= fx;
b.fy -= fy;
b.fz -= fz;
}
}
const damping = Math.exp(-1.9 * dt);
const noise = state.agitation * 0.7 * Math.sqrt(dt);
const boundsX = 3.28;
const boundsY = 2.34;
const boundsZ = 2.18;
for (const p of particles) {
p.vx = (p.vx + p.fx * dt) * damping + (this.rng() - 0.5) * noise;
p.vy = (p.vy + p.fy * dt) * damping + (this.rng() - 0.5) * noise;
p.vz = (p.vz + p.fz * dt) * damping + (this.rng() - 0.5) * noise;
p.x += p.vx * dt;
p.y += p.vy * dt;
p.z += p.vz * dt;
if (p.x < -boundsX || p.x > boundsX) {
p.x = Math.max(-boundsX, Math.min(boundsX, p.x));
p.vx *= -0.55;
}
if (p.y < -boundsY || p.y > boundsY) {
p.y = Math.max(-boundsY, Math.min(boundsY, p.y));
p.vy *= -0.55;
}
if (p.z < -boundsZ || p.z > boundsZ) {
p.z = Math.max(-boundsZ, Math.min(boundsZ, p.z));
p.vz *= -0.55;
}
}
}
computeMetrics() {
const particles = this.particles;
const count = particles.length;
let cross = 0;
let same = 0;
let cohesive = 0;
const neighborCount = Math.min(6, count - 1);
for (let i = 0; i < count; i++) {
const neighbors = [];
for (let j = 0; j < count; j++) {
if (i === j) continue;
const p = particles[i];
const q = particles[j];
const dx = p.x - q.x;
const dy = p.y - q.y;
const dz = p.z - q.z;
neighbors.push({ j, d2: dx * dx + dy * dy + dz * dz });
}
neighbors.sort((a, b) => a.d2 - b.d2);
let localSame = 0;
for (let k = 0; k < neighborCount; k++) {
const other = particles[neighbors[k].j];
if (other.species === particles[i].species) {
same++;
localSame++;
} else {
cross++;
}
}
if (localSame >= 4) cohesive++;
}
const total = Math.max(1, cross + same);
this.metrics = {
mix: cross / total,
same: same / total,
cohesion: cohesive / Math.max(1, count)
};
}
}
function createWorld(simulation) {
const scene = new THREE.Scene();
const hemisphere = new THREE.HemisphereLight(0xc8fff4, 0x18202d, 2.1);
scene.add(hemisphere);
const key = new THREE.DirectionalLight(0xffffff, 2.7);
key.position.set(4, 7, 6);
scene.add(key);
const fill = new THREE.DirectionalLight(0xffc477, 1.2);
fill.position.set(-5, 1, -3);
scene.add(fill);
const vesselGroup = new THREE.Group();
scene.add(vesselGroup);
const boxGeometry = new THREE.BoxGeometry(7.0, 5.0, 4.65);
const glass = new THREE.Mesh(
boxGeometry,
new THREE.MeshBasicMaterial({
color: 0x8dded5,
transparent: true,
opacity: 0.027,
depthWrite: false,
side: THREE.DoubleSide
})
);
vesselGroup.add(glass);
const edges = new THREE.LineSegments(
new THREE.EdgesGeometry(boxGeometry),
new THREE.LineBasicMaterial({
color: 0x8edfd6,
transparent: true,
opacity: 0.28
})
);
vesselGroup.add(edges);
const floor = new THREE.Mesh(
new THREE.CircleGeometry(4.3, 8),
new THREE.MeshBasicMaterial({
color: 0x4abdb6,
transparent: true,
opacity: 0.045,
depthWrite: false,
side: THREE.DoubleSide
})
);
floor.rotation.x = -Math.PI / 2;
floor.position.y = -2.54;
floor.scale.set(0.86, 0.70, 1);
vesselGroup.add(floor);
const particles = new THREE.InstancedMesh(
particleGeometry,
new THREE.MeshStandardMaterial({
color: 0xffffff,
roughness: 0.72,
metalness: 0.04,
flatShading: true
}),
simulation.count
);
particles.instanceMatrix.setUsage(THREE.DynamicDrawUsage);
particles.frustumCulled = false;
scene.add(particles);
for (let i = 0; i < simulation.count; i++) {
particles.setColorAt(
i,
simulation.particles[i].species === 0 ? COLOR_A : COLOR_B
);
}
particles.instanceColor.needsUpdate = true;
const maxSegments = (simulation.count * (simulation.count - 1)) / 2;
const linePositions = new Float32Array(maxSegments * 6);
const lineColors = new Float32Array(maxSegments * 6);
const lineGeometry = new THREE.BufferGeometry();
lineGeometry.setAttribute(
"position",
new THREE.BufferAttribute(linePositions, 3).setUsage(THREE.DynamicDrawUsage)
);
lineGeometry.setAttribute(
"color",
new THREE.BufferAttribute(lineColors, 3).setUsage(THREE.DynamicDrawUsage)
);
lineGeometry.setDrawRange(0, 0);
const links = new THREE.LineSegments(
lineGeometry,
new THREE.LineBasicMaterial({
vertexColors: true,
transparent: true,
opacity: 0.27,
depthWrite: false
})
);
links.frustumCulled = false;
scene.add(links);
return {
scene,
particles,
links,
lineGeometry,
linePositions,
lineColors
};
}
let simulations;
let worlds;
function rebuildSimulations() {
if (worlds) {
for (const world of worlds) {
world.lineGeometry.dispose();
world.links.material.dispose();
world.particles.material.dispose();
}
}
simulations = {
custom: new ParticleSimulation(state.count, state.customRule, state.seed),
presets: PRESETS.map((preset) => {
const rule = {
aa: preset.values[0],
ab: preset.values[1],
bb: preset.values[2]
};
return new ParticleSimulation(state.count, rule, state.seed);
})
};
worlds = [
createWorld(simulations.custom),
...simulations.presets.map((simulation) => createWorld(simulation))
];
for (const world of worlds) updateWorld(world);
updateAllMetrics();
}
function updateWorld(world) {
const simulation = world === worlds[0]
? simulations.custom
: simulations.presets[worlds.indexOf(world) - 1];
const particles = simulation.particles;
for (let i = 0; i < particles.length; i++) {
const p = particles[i];
dummy.position.set(p.x, p.y, p.z);
dummy.rotation.set(p.rx, p.ry, p.rz);
dummy.scale.setScalar(1);
dummy.updateMatrix();
world.particles.setMatrixAt(i, dummy.matrix);
}
world.particles.instanceMatrix.needsUpdate = true;
let segment = 0;
for (let i = 0; i < particles.length; i++) {
const a = particles[i];
for (let j = i + 1; j < particles.length; j++) {
const b = particles[j];
const dx = a.x - b.x;
const dy = a.y - b.y;
const dz = a.z - b.z;
const dist = Math.sqrt(dx * dx + dy * dy + dz * dz);
const strength = simulation.pairStrength(a.species, b.species);
if (strength <= 0.12 || dist > 1.55) continue;
const offset = segment * 6;
world.linePositions[offset] = a.x;
world.linePositions[offset + 1] = a.y;
world.linePositions[offset + 2] = a.z;
world.linePositions[offset + 3] = b.x;
world.linePositions[offset + 4] = b.y;
world.linePositions[offset + 5] = b.z;
const colorA = a.species === 0 ? COLOR_A : COLOR_B;
const colorB = b.species === 0 ? COLOR_A : COLOR_B;
world.lineColors[offset] = colorA.r;
world.lineColors[offset + 1] = colorA.g;
world.lineColors[offset + 2] = colorA.b;
world.lineColors[offset + 3] = colorB.r;
world.lineColors[offset + 4] = colorB.g;
world.lineColors[offset + 5] = colorB.b;
segment++;
}
}
world.lineGeometry.attributes.position.needsUpdate = true;
world.lineGeometry.attributes.color.needsUpdate = true;
world.lineGeometry.setDrawRange(0, segment * 2);
}
function updateCamera(aspect) {
const { theta, phi, zoom } = state.camera;
const radius = 15;
const target = new THREE.Vector3(0, 0, 0);
camera.position.set(
radius * Math.sin(phi) * Math.sin(theta),
radius * Math.cos(phi),
radius * Math.sin(phi) * Math.cos(theta)
);
const desiredWidth = 8.8 / zoom;
const desiredHeight = Math.max(6.8, desiredWidth / aspect);
camera.left = -desiredHeight * aspect / 2;
camera.right = desiredHeight * aspect / 2;
camera.top = desiredHeight / 2;
camera.bottom = -desiredHeight / 2;
camera.updateProjectionMatrix();
camera.lookAt(target);
}
function renderScenes() {
const width = Math.max(1, stage.clientWidth);
const height = Math.max(1, stage.clientHeight);
renderer.setScissorTest(false);
renderer.setViewport(0, 0, width, height);
renderer.clear(true, true, true);
if (state.compare) {
renderer.setScissorTest(true);
for (let i = 0; i < 3; i++) {
const x0 = Math.floor((i * width) / 3);
const x1 = Math.floor(((i + 1) * width) / 3);
const viewportWidth = x1 - x0;
renderer.setViewport(x0, 0, viewportWidth, height);
renderer.setScissor(x0, 0, viewportWidth, height);
renderer.clear(true, true, true);
updateCamera(viewportWidth / height);
renderer.render(worlds[i + 1].scene, camera);
}
} else {
renderer.setScissorTest(false);
renderer.setViewport(0, 0, width, height);
updateCamera(width / height);
renderer.render(worlds[0].scene, camera);
}
}
function buildPresetButtons() {
$("presetGrid").innerHTML = PRESETS.map((preset, index) => `
<button class="preset-button" type="button" data-preset="${index}">
<strong>${preset.short}</strong>
<small>${preset.description}</small>
</button>
`).join("");
$("presetGrid").querySelectorAll("[data-preset]").forEach((button) => {
button.addEventListener("click", () => {
applyPreset(Number(button.dataset.preset));
setMode(false);
});
});
}
function buildComparisonCards() {
$("comparisonGrid").innerHTML = PRESETS.map((preset, index) => `
<article class="comparison-card" tabindex="0" data-card="${index}">
<span class="card-index">0${index + 1}</span>
<h3>${preset.name}</h3>
<p class="card-description">${preset.description}</p>
<div class="rule-values">
<span class="rule-value">A–A ${signed(preset.values[0])}</span>
<span class="rule-value">A–B ${signed(preset.values[1])}</span>
<span class="rule-value">B–B ${signed(preset.values[2])}</span>
</div>
<div class="card-metrics">
<div class="card-metric">
<span>A–B neighbor share</span>
<b id="cardMix${index}">—</b>
</div>
<div class="card-metric">
<span>Same-type share</span>
<b id="cardSame${index}">—</b>
</div>
</div>
<div class="mini-track"><i id="cardBar${index}"></i></div>
<div class="explore-link">Open in Explore →</div>
</article>
`).join("");
$("comparisonGrid").querySelectorAll("[data-card]").forEach((card) => {
const activate = () => {
applyPreset(Number(card.dataset.card));
setMode(false);
};
card.addEventListener("click", activate);
card.addEventListener("keydown", (event) => {
if (event.key === "Enter" || event.key === " ") {
event.preventDefault();
activate();
}
});
});
}
function buildOverlays() {
if (state.compare) {
$("viewportOverlays").innerHTML = PRESETS.map((preset, index) => `
<div class="viewport-overlay" style="left:${index * 100 / 3}%;width:${100 / 3}%">
<div class="viewport-title">
<span class="viewport-index">0${index + 1}</span>
<strong>${preset.short}</strong>
<small>${preset.description}</small>
</div>
<div class="viewport-metrics">
<div class="metric-chip">A–B neighbors<b id="ovMix${index}">—</b></div>
<div class="metric-chip">Same-type neighbors<b id="ovSame${index}">—</b></div>
</div>
</div>
`).join("");
} else {
$("viewportOverlays").innerHTML = `
<div class="viewport-overlay" style="left:0;width:100%">
<div class="viewport-title">
<span class="viewport-index">✦</span>
<strong>Custom mix rule</strong>
<small>Adjust the three pairwise scores in the control panel.</small>
</div>
<div class="viewport-metrics">
<div class="metric-chip">A–B neighbors<b id="ovMixCustom">—</b></div>
<div class="metric-chip">Same-type neighbors<b id="ovSameCustom">—</b></div>
<div class="metric-chip">Local cohesion<b id="ovCohesionCustom">—</b></div>
</div>
</div>
`;
}
}
function setMode(compare) {
state.compare = compare;
$("compareTab").classList.toggle("active", compare);
$("exploreTab").classList.toggle("active", !compare);
$("compareTab").setAttribute("aria-selected", String(compare));
$("exploreTab").setAttribute("aria-selected", String(!compare));
$("modeNote").textContent = compare
? "Compare mode uses three fixed presets. Switch to Explore to edit a custom rule."
: "Explore mode applies your three pair scores to the large particle model.";
buildOverlays();
updateAllMetrics();
}
function applyPreset(index) {
const values = PRESETS[index].values;
state.customRule.aa = values[0];
state.customRule.ab = values[1];
state.customRule.bb = values[2];
$("ruleAA").value = values[0];
$("ruleAB").value = values[1];
$("ruleBB").value = values[2];
if (simulations) {
simulations.custom.rule = { ...state.customRule };
simulations.custom.reset(state.seed);
}
syncRuleControls();
updateInsight();
updateAllMetrics();
}
function syncSlider(input) {
const min = Number(input.min);
const max = Number(input.max);
const value = Number(input.value);
input.style.setProperty("--fill", `${((value - min) / (max - min)) * 100}%`);
}
function syncRuleControls() {
const aa = Number($("ruleAA").value);
const ab = Number($("ruleAB").value);
const bb = Number($("ruleBB").value);
state.customRule = { aa, ab, bb };
$("ruleAAOut").textContent = signed(aa);
$("ruleABOut").textContent = signed(ab);
$("ruleBBOut").textContent = signed(bb);
["ruleAA", "ruleAB", "ruleBB"].forEach((id) => syncSlider($(id)));
const matches = PRESETS.findIndex((preset) =>
Math.abs(preset.values[0] - aa) < 0.001 &&
Math.abs(preset.values[1] - ab) < 0.001 &&
Math.abs(preset.values[2] - bb) < 0.001
);
$("presetGrid").querySelectorAll("[data-preset]").forEach((button) => {
button.classList.toggle("active", Number(button.dataset.preset) === matches);
});
updateInsight();
}
function updateInsight() {
const { aa, ab, bb } = state.customRule;
let title;
let text;
if (aa > bb + 0.25 && ab < 0.2) {
title = "Type-selective clustering";
text = "A and B prefer their own kind, so same-species neighborhoods should become more prominent.";
} else if (ab > aa + 0.35 && ab > bb + 0.35) {
title = "Cross-species association";
text = "A–B attraction is strongest, so unlike particles should occupy more local neighborhoods.";
} else if (
Math.abs(aa - ab) < 0.18 &&
Math.abs(ab - bb) < 0.18
) {
title = "No species preference";
text = "All pair types are treated almost equally; the arrangement should remain comparatively mixed.";
} else if (aa > 0.35 && bb > 0.35 && ab > 0.35) {
title = "Universal cohesion";
text = "All particle types attract, so the system may condense without strong species selectivity.";
} else {
title = "Mixed interaction balance";
text = "Different pair types compete, producing a compromise between clustering, segregation, and mixing.";
}
$("insightTitle").textContent = title;
$("insightText").textContent = text;
}
function updateAllMetrics() {
if (!simulations) return;
simulations.custom.computeMetrics();
simulations.presets.forEach((simulation) => simulation.computeMetrics());
if (state.compare) {
simulations.presets.forEach((simulation, index) => {
const mix = simulation.metrics.mix;
const same = simulation.metrics.same;
$(`ovMix${index}`).textContent = `${Math.round(mix * 100)}%`;
$(`ovSame${index}`).textContent = `${Math.round(same * 100)}%`;
});
} else {
const metrics = simulations.custom.metrics;
$("ovMixCustom").textContent = `${Math.round(metrics.mix * 100)}%`;
$("ovSameCustom").textContent = `${Math.round(metrics.same * 100)}%`;
$("ovCohesionCustom").textContent = `${Math.round(metrics.cohesion * 100)}%`;
}
simulations.presets.forEach((simulation, index) => {
$(`cardMix${index}`).textContent = `${Math.round(simulation.metrics.mix * 100)}%`;
$(`cardSame${index}`).textContent = `${Math.round(simulation.metrics.same * 100)}%`;
$(`cardBar${index}`).style.width = `${simulation.metrics.mix * 100}%`;
});
}
function resetCamera() {
state.camera.theta = 0.72;
state.camera.phi = 1.12;
state.camera.zoom = 1;
}
function resizeRenderer() {
renderer.setSize(Math.max(1, stage.clientWidth), Math.max(1, stage.clientHeight), false);
}
buildPresetButtons();
buildComparisonCards();
syncRuleControls();
buildOverlays();
rebuildSimulations();
$("compareTab").addEventListener("click", () => setMode(true));
$("exploreTab").addEventListener("click", () => setMode(false));
["ruleAA", "ruleAB", "ruleBB"].forEach((id) => {
$(id).addEventListener("input", () => {
syncRuleControls();
if (simulations) simulations.custom.rule = { ...state.customRule };
});
});
$("particleCount").addEventListener("input", () => {
const value = Number($("particleCount").value);
$("particleCountOut").textContent = String(value);
syncSlider($("particleCount"));
});
$("particleCount").addEventListener("change", () => {
state.count = Number($("particleCount").value);
rebuildSimulations();
});
$("agitation").addEventListener("input", () => {
state.agitation = Number($("agitation").value);
$("agitationOut").textContent = state.agitation.toFixed(2);
syncSlider($("agitation"));
});
$("speed").addEventListener("input", () => {
state.speed = Number($("speed").value);
$("speedOut").textContent = `${state.speed.toFixed(2)}×`;
syncSlider($("speed"));
});
$("pauseButton").addEventListener("click", () => {
state.paused = !state.paused;
$("pauseButton").textContent = state.paused ? "Resume" : "Pause";
});
$("shuffleButton").addEventListener("click", () => {
state.seed += 1;
simulations.custom.reset(state.seed);
simulations.presets.forEach((simulation) => simulation.reset(state.seed));
accumulator = 0;
});
$("resetCamera").addEventListener("click", resetCamera);
let dragging = false;
let previousX = 0;
let previousY = 0;
canvas.addEventListener("pointerdown", (event) => {
if (event.button !== 0) return;
dragging = true;
previousX = event.clientX;
previousY = event.clientY;
canvas.setPointerCapture(event.pointerId);
});
canvas.addEventListener("pointermove", (event) => {
if (!dragging) return;
const dx = event.clientX - previousX;
const dy = event.clientY - previousY;
previousX = event.clientX;
previousY = event.clientY;
state.camera.theta -= dx * 0.006;
state.camera.phi = Math.max(0.32, Math.min(2.72, state.camera.phi - dy * 0.005));
});
const stopDragging = (event) => {
dragging = false;
if (canvas.hasPointerCapture(event.pointerId)) {
canvas.releasePointerCapture(event.pointerId);
}
};
canvas.addEventListener("pointerup", stopDragging);
canvas.addEventListener("pointercancel", stopDragging);
canvas.addEventListener("wheel", (event) => {
event.preventDefault();
state.camera.zoom = Math.max(0.62, Math.min(1.75, state.camera.zoom * Math.exp(-event.deltaY * 0.001)));
}, { passive: false });
canvas.addEventListener("dblclick", resetCamera);
window.addEventListener("keydown", (event) => {
const target = event.target;
if (event.code === "Space" && (target === document.body || target === canvas)) {
event.preventDefault();
$("pauseButton").click();
}
});
["particleCount", "agitation", "speed"].forEach((id) => syncSlider($(id)));
const resizeObserver = new ResizeObserver(resizeRenderer);
resizeObserver.observe(stage);
resizeRenderer();
let previousTime = performance.now();
let accumulator = 0;
let frame = 0;
const fixedStep = 1 / 60;
function animate(now) {
const elapsed = Math.min((now - previousTime) / 1000, 0.05);
previousTime = now;
if (!state.paused) {
accumulator += elapsed * state.speed;
let steps = 0;
while (accumulator >= fixedStep && steps < 4) {
simulations.custom.step(fixedStep);
simulations.presets.forEach((simulation) => simulation.step(fixedStep));
accumulator -= fixedStep;
steps++;
}
if (steps === 4) accumulator = 0;
}
for (const world of worlds) updateWorld(world);
renderScenes();
if (frame % 8 === 0) updateAllMetrics();
if (frame === 2) $("loading").remove();
frame++;
requestAnimationFrame(animate);
}
requestAnimationFrame(animate);
</script>
</body>
</html>
```