Prompt specification
Build or customize the Three.js 3D scene "Density and mixing comparison 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: Density and mixing comparison explorer
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/density-and-mixing-comparison-explorer-x1464
Scene Description Prompt:
Density and mixing comparison explorer. Let viewers compare immiscible layered fluids with a labeled miscible mixing example; show that density alone does not imply permanent sharp boundaries. Please build this with Three.js from cdnjs in one self-contained HTML file, using visible voxel blocks.
Working Three.js Starter (density-and-mixing-comparison-explorer-x1464):
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Density ≠ Boundary — Voxel Mixing Explorer</title>
<style>
:root {
color-scheme: dark;
--bg: #071018;
--panel: #0d1823;
--panel-2: #111e2a;
--line: rgba(168, 196, 218, 0.15);
--text: #edf7ff;
--muted: #91a7b9;
--teal: #35d6c4;
--amber: #ffa654;
--blue: #72a8ff;
--violet: #b39aff;
--radius: 18px;
}
* {
box-sizing: border-box;
}
html,
body {
min-height: 100%;
margin: 0;
}
body {
background:
radial-gradient(circle at 12% 0%, rgba(53, 214, 196, 0.11), transparent 30rem),
radial-gradient(circle at 88% 8%, rgba(179, 154, 255, 0.10), transparent 32rem),
var(--bg);
color: var(--text);
font-family:
Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
button,
input {
font: inherit;
}
button {
color: inherit;
}
.app {
width: min(1540px, calc(100% - 32px));
margin: 0 auto;
padding: 28px 0 36px;
}
.topbar {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 28px;
margin-bottom: 22px;
}
.brand {
display: flex;
gap: 15px;
align-items: flex-start;
}
.brand-mark {
position: relative;
width: 45px;
height: 45px;
flex: 0 0 auto;
margin-top: 2px;
border: 1px solid rgba(53, 214, 196, 0.38);
border-radius: 13px;
background:
linear-gradient(135deg, rgba(53, 214, 196, 0.22), rgba(114, 168, 255, 0.04)),
rgba(9, 20, 29, 0.8);
box-shadow: 0 12px 35px rgba(0, 0, 0, 0.28);
}
.brand-mark::before,
.brand-mark::after {
content: "";
position: absolute;
border-radius: 3px;
}
.brand-mark::before {
width: 12px;
height: 12px;
left: 9px;
top: 10px;
background: var(--teal);
box-shadow: 12px 0 0 var(--amber);
}
.brand-mark::after {
width: 12px;
height: 12px;
left: 9px;
top: 24px;
background: rgba(53, 214, 196, 0.55);
box-shadow: 12px 0 0 rgba(255, 166, 84, 0.55);
}
.eyebrow {
margin: 0 0 6px;
color: var(--teal);
font-size: 11px;
font-weight: 800;
letter-spacing: 0.16em;
text-transform: uppercase;
}
h1 {
margin: 0;
font-size: clamp(26px, 3vw, 42px);
font-weight: 760;
letter-spacing: -0.045em;
line-height: 1.05;
}
h1 span {
color: #849cad;
font-weight: 450;
}
.subtitle {
max-width: 760px;
margin: 10px 0 0;
color: var(--muted);
font-size: 14px;
line-height: 1.55;
}
.top-meta {
display: flex;
flex-wrap: wrap;
justify-content: flex-end;
gap: 8px;
padding-top: 5px;
}
.pill {
display: inline-flex;
align-items: center;
gap: 7px;
min-height: 30px;
padding: 6px 10px;
border: 1px solid var(--line);
border-radius: 999px;
background: rgba(12, 25, 36, 0.75);
color: #b9cad7;
font-size: 11px;
font-weight: 700;
letter-spacing: 0.04em;
white-space: nowrap;
}
.pill::before {
content: "";
width: 6px;
height: 6px;
border-radius: 50%;
background: var(--teal);
box-shadow: 0 0 12px rgba(53, 214, 196, 0.8);
}
.workspace {
display: grid;
grid-template-columns: 292px minmax(0, 1fr);
gap: 16px;
align-items: start;
}
.sidebar {
display: grid;
gap: 14px;
}
.card {
border: 1px solid var(--line);
border-radius: var(--radius);
background:
linear-gradient(145deg, rgba(255, 255, 255, 0.025), transparent 55%),
rgba(12, 24, 35, 0.88);
box-shadow: 0 18px 45px rgba(0, 0, 0, 0.18);
}
.controls-card {
padding: 19px;
}
.card-title {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
margin-bottom: 17px;
}
.card-title h2 {
margin: 0;
font-size: 14px;
font-weight: 750;
}
.card-title small {
color: #71899c;
font-size: 10px;
font-weight: 750;
letter-spacing: 0.11em;
text-transform: uppercase;
}
.control {
margin: 0 0 19px;
}
.control:last-of-type {
margin-bottom: 0;
}
.control-head {
display: flex;
align-items: baseline;
justify-content: space-between;
gap: 10px;
margin-bottom: 8px;
}
.control-head label {
color: #c6d5df;
font-size: 12px;
font-weight: 650;
}
.control-head output {
color: var(--teal);
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
font-size: 11px;
font-weight: 750;
}
.control small {
display: block;
margin-top: 7px;
color: #70879a;
font-size: 10px;
line-height: 1.45;
}
input[type="range"] {
width: 100%;
height: 4px;
margin: 4px 0;
border-radius: 99px;
outline: none;
appearance: none;
background: linear-gradient(90deg, var(--teal) var(--fill, 50%), #243746 var(--fill, 50%));
cursor: pointer;
}
input[type="range"]::-webkit-slider-thumb {
width: 15px;
height: 15px;
border: 3px solid #0d1a25;
border-radius: 50%;
appearance: none;
background: #d9fff8;
box-shadow: 0 0 0 1px rgba(53, 214, 196, 0.65), 0 0 14px rgba(53, 214, 196, 0.38);
}
input[type="range"]::-moz-range-thumb {
width: 11px;
height: 11px;
border: 3px solid #0d1a25;
border-radius: 50%;
background: #d9fff8;
box-shadow: 0 0 0 1px rgba(53, 214, 196, 0.65);
}
.button-row {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 9px;
margin-top: 20px;
}
.button {
min-height: 39px;
border: 1px solid var(--line);
border-radius: 11px;
background: #142635;
color: #dceaf3;
font-size: 11px;
font-weight: 750;
cursor: pointer;
transition:
transform 140ms ease,
border-color 140ms ease,
background 140ms ease;
}
.button:hover {
transform: translateY(-1px);
border-color: rgba(53, 214, 196, 0.45);
background: #193044;
}
.button.primary {
border-color: rgba(53, 214, 196, 0.32);
background: rgba(53, 214, 196, 0.13);
color: #bafff3;
}
.button.ghost {
grid-column: 1 / -1;
min-height: 34px;
background: transparent;
color: #8299ab;
}
.legend-card,
.reading-card {
padding: 18px 19px;
}
.legend-row {
display: grid;
grid-template-columns: 12px 1fr auto;
gap: 10px;
align-items: center;
margin: 12px 0;
}
.swatch {
width: 11px;
height: 11px;
border-radius: 3px;
box-shadow: 0 0 14px currentColor;
}
.swatch.low {
color: var(--teal);
background: var(--teal);
}
.swatch.high {
color: var(--amber);
background: var(--amber);
}
.legend-row b {
display: block;
font-size: 11px;
font-weight: 720;
}
.legend-row small {
display: block;
margin-top: 2px;
color: #748b9e;
font-size: 9px;
}
.density-number {
color: #a8bdcb;
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
font-size: 10px;
}
.legend-note {
margin: 13px 0 0;
padding-top: 12px;
border-top: 1px solid var(--line);
color: #7890a2;
font-size: 10px;
line-height: 1.5;
}
.reading-card {
position: relative;
overflow: hidden;
}
.reading-card::after {
content: "";
position: absolute;
width: 110px;
height: 110px;
right: -42px;
bottom: -48px;
border-radius: 50%;
background: rgba(179, 154, 255, 0.12);
filter: blur(4px);
pointer-events: none;
}
.reading-card h2 {
margin: 0 0 9px;
font-size: 13px;
}
.reading-card p {
position: relative;
z-index: 1;
margin: 0;
color: #8fa5b6;
font-size: 11px;
line-height: 1.65;
}
.reading-card strong {
color: #dce9f1;
font-weight: 720;
}
.progress-wrap {
position: relative;
z-index: 1;
margin-top: 15px;
}
.progress-label {
display: flex;
justify-content: space-between;
margin-bottom: 7px;
color: #7f96a8;
font-size: 9px;
font-weight: 700;
letter-spacing: 0.06em;
text-transform: uppercase;
}
.progress-track {
height: 5px;
overflow: hidden;
border-radius: 99px;
background: #213442;
}
.progress-fill {
width: 0;
height: 100%;
border-radius: inherit;
background: linear-gradient(90deg, var(--teal), var(--violet));
box-shadow: 0 0 14px rgba(179, 154, 255, 0.4);
transition: width 120ms linear;
}
.visual-card {
min-width: 0;
overflow: hidden;
border: 1px solid var(--line);
border-radius: 22px;
background: #0b1420;
box-shadow: 0 26px 70px rgba(0, 0, 0, 0.28);
}
.stage {
position: relative;
height: clamp(620px, 73vh, 760px);
overflow: hidden;
background:
linear-gradient(
90deg,
rgba(13, 34, 47, 0.98) 0%,
rgba(9, 22, 34, 0.98) 49.8%,
rgba(36, 24, 45, 0.98) 50.2%,
rgba(21, 17, 32, 0.98) 100%
);
}
.stage.vertical {
background:
linear-gradient(
180deg,
rgba(13, 34, 47, 0.98) 0%,
rgba(9, 22, 34, 0.98) 49.8%,
rgba(36, 24, 45, 0.98) 50.2%,
rgba(21, 17, 32, 0.98) 100%
);
}
#view {
position: absolute;
inset: 0;
width: 100%;
height: 100%;
display: block;
cursor: grab;
touch-action: none;
}
#view.dragging {
cursor: grabbing;
}
.split-ui {
position: absolute;
inset: 0;
z-index: 2;
display: grid;
grid-template-columns: 1fr 1fr;
pointer-events: none;
}
.split-ui.vertical {
grid-template-columns: 1fr;
grid-template-rows: 1fr 1fr;
}
.panel-ui {
position: relative;
min-width: 0;
min-height: 0;
}
.panel-ui::before {
content: "";
position: absolute;
inset: 0;
background: linear-gradient(180deg, rgba(5, 12, 19, 0.56), transparent 26%, transparent 76%, rgba(5, 12, 19, 0.26));
pointer-events: none;
}
.panel-heading {
position: absolute;
top: 22px;
left: 23px;
right: 23px;
}
.panel-chip {
display: inline-flex;
align-items: center;
gap: 7px;
margin-bottom: 8px;
padding: 5px 8px;
border: 1px solid rgba(53, 214, 196, 0.28);
border-radius: 999px;
background: rgba(11, 35, 43, 0.62);
color: #a7fff2;
font-size: 9px;
font-weight: 800;
letter-spacing: 0.11em;
text-transform: uppercase;
}
.panel-chip.right {
border-color: rgba(179, 154, 255, 0.3);
background: rgba(42, 29, 57, 0.67);
color: #d7cbff;
}
.panel-chip::before {
content: "";
width: 5px;
height: 5px;
border-radius: 50%;
background: currentColor;
box-shadow: 0 0 9px currentColor;
}
.panel-heading h2 {
margin: 0;
font-size: clamp(18px, 2vw, 25px);
font-weight: 740;
letter-spacing: -0.035em;
}
.panel-heading p {
max-width: 330px;
margin: 6px 0 0;
color: #8fa6b7;
font-size: 11px;
line-height: 1.5;
}
.profile-card {
position: absolute;
left: 20px;
bottom: 19px;
width: min(205px, calc(100% - 40px));
padding: 10px 11px 9px;
border: 1px solid rgba(170, 201, 221, 0.14);
border-radius: 13px;
background: rgba(6, 14, 22, 0.67);
backdrop-filter: blur(12px);
}
.profile-head {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
margin-bottom: 4px;
}
.profile-head b {
color: #b8cbd7;
font-size: 9px;
font-weight: 750;
letter-spacing: 0.07em;
text-transform: uppercase;
}
.profile-head span {
color: #6f8799;
font-size: 8px;
}
.profile-card svg {
display: block;
width: 100%;
height: 49px;
overflow: visible;
}
.profile-axis {
fill: #60798b;
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
font-size: 6px;
}
.profile-line {
fill: none;
stroke: var(--teal);
stroke-width: 2;
stroke-linecap: round;
stroke-linejoin: round;
filter: drop-shadow(0 0 4px rgba(53, 214, 196, 0.35));
}
.profile-line.right {
stroke: var(--violet);
filter: drop-shadow(0 0 4px rgba(179, 154, 255, 0.35));
}
.panel-status {
position: absolute;
right: 20px;
bottom: 23px;
max-width: 145px;
padding: 7px 10px;
border: 1px solid rgba(255, 255, 255, 0.11);
border-radius: 999px;
background: rgba(7, 15, 23, 0.64);
color: #bdd0dc;
font-size: 9px;
font-weight: 700;
text-align: right;
backdrop-filter: blur(10px);
}
.panel-status.right {
color: #d5c9f8;
}
.stage-footer {
display: flex;
align-items: center;
justify-content: space-between;
gap: 18px;
min-height: 48px;
padding: 11px 18px;
border-top: 1px solid var(--line);
background: #0b1520;
color: #70889b;
font-size: 10px;
}
.stage-footer strong {
color: #b8cad7;
font-weight: 650;
}
.time-readout {
flex: 0 0 auto;
color: #8da3b4;
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
font-size: 10px;
}
.method-note {
margin: 13px 3px 0;
color: #5f788b;
font-size: 10px;
line-height: 1.55;
}
@media (max-width: 980px) {
.workspace {
grid-template-columns: 1fr;
}
.visual-card {
order: -1;
}
.sidebar {
grid-template-columns: repeat(3, minmax(0, 1fr));
align-items: start;
}
.button.ghost {
grid-column: auto;
}
}
@media (max-width: 720px) {
.app {
width: min(100% - 20px, 1540px);
padding-top: 20px;
}
.topbar {
display: block;
}
.top-meta {
justify-content: flex-start;
margin-top: 16px;
}
.sidebar {
grid-template-columns: 1fr;
}
.stage {
height: 780px;
}
.panel-heading {
top: 17px;
left: 17px;
right: 17px;
}
.panel-heading p {
max-width: 280px;
}
.profile-card {
left: 13px;
bottom: 13px;
width: 175px;
}
.panel-status {
right: 13px;
bottom: 17px;
}
.stage-footer {
align-items: flex-start;
}
}
</style>
</head>
<body>
<main class="app">
<header class="topbar">
<div class="brand">
<div class="brand-mark" aria-hidden="true"></div>
<div>
<p class="eyebrow">Voxel mixing laboratory</p>
<h1>Density <span>≠</span> Boundary</h1>
<p class="subtitle">
A matched comparison: both samples begin with the same density step,
but only the miscible pair can diffuse across the interface.
</p>
</div>
</div>
<div class="top-meta">
<span class="pill">Linked views</span>
<span class="pill">Three.js core</span>
<span class="pill">Drag to orbit</span>
</div>
</header>
<div class="workspace">
<aside class="sidebar">
<section class="card controls-card">
<div class="card-title">
<h2>Experiment controls</h2>
<small>Matched pair</small>
</div>
<div class="control">
<div class="control-head">
<label for="density">Density contrast</label>
<output id="densityOutput">+0.85</output>
</div>
<input id="density" type="range" min="0.2" max="1.6" step="0.05" value="0.85" />
<small>
Low phase: ρ = 1.00. The high phase changes in both samples.
</small>
</div>
<div class="control">
<div class="control-head">
<label for="mixRate">Miscible diffusion rate</label>
<output id="mixOutput">1.25×</output>
</div>
<input id="mixRate" type="range" min="0.4" max="2.5" step="0.05" value="1.25" />
<small>
Changes only the miscible sample. The immiscible phase boundary stays locked.
</small>
</div>
<div class="control">
<div class="control-head">
<label for="speed">Simulation speed</label>
<output id="speedOutput">1.00×</output>
</div>
<input id="speed" type="range" min="0.25" max="2" step="0.05" value="1" />
</div>
<div class="button-row">
<button class="button primary" id="playButton" type="button">Ⅱ Pause</button>
<button class="button" id="resetButton" type="button">↺ Reset pair</button>
<button class="button ghost" id="cameraButton" type="button">Reset linked camera</button>
</div>
</section>
<section class="card legend-card">
<div class="card-title">
<h2>Tracer labels</h2>
<small>Equal voxels</small>
</div>
<div class="legend-row">
<span class="swatch low"></span>
<div>
<b>Fluid A · low density</b>
<small>teal tracer</small>
</div>
<span class="density-number" id="rhoLow">1.00</span>
</div>
<div class="legend-row">
<span class="swatch high"></span>
<div>
<b>Fluid B · high density</b>
<small>amber tracer</small>
</div>
<span class="density-number" id="rhoHigh">1.85</span>
</div>
<p class="legend-note">
Colors identify the source components. Blended colors indicate
molecular mixing, not a third material.
</p>
</section>
<section class="card reading-card">
<p class="eyebrow">Reading the result</p>
<h2>Density is not the whole rule</h2>
<p>
Both samples begin with the <strong>same density step</strong>.
The immiscible pair keeps a clean edge. The miscible pair develops
a broad transition and approaches a uniform mixture.
<strong>A density contrast can favor stratification, but it cannot
guarantee a permanent sharp interface.</strong>
</p>
<div class="progress-wrap">
<div class="progress-label">
<span>Miscible mixing progress</span>
<span id="progressText">0%</span>
</div>
<div class="progress-track">
<div class="progress-fill" id="progressFill"></div>
</div>
</div>
</section>
</aside>
<section>
<div class="visual-card">
<div class="stage" id="stage">
<canvas id="view" aria-label="Interactive side-by-side voxel simulation"></canvas>
<div class="split-ui" id="splitUI">
<div class="panel-ui">
<div class="panel-heading">
<div class="panel-chip">Immiscible pair</div>
<h2>Sharp phase interface</h2>
<p>
Density ordering separates the phases, while immiscibility
prevents molecular crossing.
</p>
</div>
<div class="profile-card">
<div class="profile-head">
<b>Density profile</b>
<span>height ↑</span>
</div>
<svg viewBox="0 0 100 49" role="img" aria-label="Immiscible density profile">
<line x1="7" y1="42" x2="93" y2="42" stroke="#334c5e" stroke-width="0.7" />
<line x1="7" y1="42" x2="7" y2="4" stroke="#334c5e" stroke-width="0.7" />
<path id="profileLeft" class="profile-line" d="" />
<text class="profile-axis" x="7" y="48">ρ low</text>
<text class="profile-axis" x="79" y="48">ρ high</text>
</svg>
</div>
<div class="panel-status" aria-live="polite">
Boundary persists
</div>
</div>
<div class="panel-ui">
<div class="panel-heading">
<div class="panel-chip right">Miscible pair</div>
<h2>Interface dissolves</h2>
<p>
The same density contrast is present, but molecular diffusion
lets the labeled components interpenetrate.
</p>
</div>
<div class="profile-card">
<div class="profile-head">
<b>Density profile</b>
<span>height ↑</span>
</div>
<svg viewBox="0 0 100 49" role="img" aria-label="Miscible density profile">
<line x1="7" y1="42" x2="93" y2="42" stroke="#493e60" stroke-width="0.7" />
<line x1="7" y1="42" x2="7" y2="4" stroke="#493e60" stroke-width="0.7" />
<path id="profileRight" class="profile-line right" d="" />
<text class="profile-axis" x="7" y="48">ρ low</text>
<text class="profile-axis" x="79" y="48">ρ high</text>
</svg>
</div>
<div class="panel-status right" id="mixStatus" aria-live="polite">
Interface present
</div>
</div>
</div>
</div>
<div class="stage-footer">
<span>
<strong>Matched start</strong> · linked camera · drag to orbit · scroll to zoom
</span>
<span class="time-readout" id="timeReadout">t = 00:00.0</span>
</div>
</div>
<p class="method-note">
Educational lattice model: equal-volume voxels represent equal-volume
portions of two components. The right panel uses conservative local
diffusion on a six-neighbor grid; the left panel permits no diffusion.
It illustrates the role of miscibility rather than solving full fluid dynamics.
</p>
</section>
</div>
</main>
<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 stage = $("stage");
const canvas = $("view");
const splitUI = $("splitUI");
const renderer = new THREE.WebGLRenderer({
canvas,
antialias: true,
alpha: true,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 1.75));
renderer.setClearColor(0x000000, 0);
renderer.outputColorSpace = THREE.SRGBColorSpace;
// ---------------------------------------------------------------------
// Voxel grid
// ---------------------------------------------------------------------
const NX = 11;
const NY = 15;
const NZ = 7;
const CELL_COUNT = NX * NY * NZ;
const PITCH = 0.225;
const VOXEL_SIZE = 0.205;
const GRID_WIDTH = NX * PITCH;
const GRID_HEIGHT = NY * PITCH;
const GRID_DEPTH = NZ * PITCH;
const INTERFACE_ROW = Math.floor(NY * 0.52);
const LOW_COLOR = new THREE.Color(0x35d6c4);
const HIGH_COLOR = new THREE.Color(0xffa654);
const MIXED_COLOR = new THREE.Color();
const initialPattern = new Float32Array(CELL_COUNT);
const leftState = new Float32Array(CELL_COUNT);
const rightState = new Float32Array(CELL_COUNT);
const nextState = new Float32Array(CELL_COUNT);
function gridIndex(x, y, z) {
return x + NX * (y + NY * z);
}
function buildInitialPattern() {
for (let z = 0; z < NZ; z++) {
for (let y = 0; y < NY; y++) {
// c = 1 means low-density teal fluid.
// The dense amber fluid begins below the lighter fluid.
const c = y >= INTERFACE_ROW ? 1 : 0;
for (let x = 0; x < NX; x++) {
initialPattern[gridIndex(x, y, z)] = c;
}
}
}
leftState.set(initialPattern);
rightState.set(initialPattern);
}
buildInitialPattern();
function standardDeviation(values, mean = null) {
let sum = 0;
for (let i = 0; i < values.length; i++) sum += values[i];
const average = mean === null ? sum / values.length : mean;
let variance = 0;
for (let i = 0; i < values.length; i++) {
const delta = values[i] - average;
variance += delta * delta;
}
return Math.sqrt(variance / values.length);
}
let initialMean = 0;
for (let i = 0; i < CELL_COUNT; i++) initialMean += initialPattern[i];
initialMean /= CELL_COUNT;
const initialStdDev = standardDeviation(initialPattern, initialMean);
// ---------------------------------------------------------------------
// Scene construction
// ---------------------------------------------------------------------
function createVoxelScene(accentColor, floorColor) {
const scene = new THREE.Scene();
const geometry = new THREE.BoxGeometry(VOXEL_SIZE, VOXEL_SIZE, VOXEL_SIZE);
const material = new THREE.MeshStandardMaterial({
color: 0xffffff,
roughness: 0.39,
metalness: 0.045
});
const voxels = new THREE.InstancedMesh(geometry, material, CELL_COUNT);
voxels.instanceMatrix.setUsage(THREE.StaticDrawUsage);
voxels.frustumCulled = false;
const transform = new THREE.Object3D();
let index = 0;
for (let z = 0; z < NZ; z++) {
for (let y = 0; y < NY; y++) {
for (let x = 0; x < NX; x++) {
transform.position.set(
(x - (NX - 1) * 0.5) * PITCH,
(y - (NY - 1) * 0.5) * PITCH,
(z - (NZ - 1) * 0.5) * PITCH
);
transform.updateMatrix();
voxels.setMatrixAt(index++, transform.matrix);
}
}
}
voxels.setColorAt(0, LOW_COLOR);
voxels.instanceColor.setUsage(THREE.DynamicDrawUsage);
scene.add(voxels);
const floorY = -GRID_HEIGHT * 0.5 - 0.15;
const floor = new THREE.Mesh(
new THREE.PlaneGeometry(GRID_WIDTH + 1.15, GRID_DEPTH + 1.15),
new THREE.MeshStandardMaterial({
color: floorColor,
roughness: 0.92,
metalness: 0.02
})
);
floor.rotation.x = -Math.PI / 2;
floor.position.y = floorY;
scene.add(floor);
const grid = new THREE.GridHelper(
GRID_WIDTH + 1.0,
18,
accentColor,
0x294052
);
grid.position.y = floorY + 0.006;
grid.material.transparent = true;
grid.material.opacity = 0.17;
grid.material.depthWrite = false;
scene.add(grid);
const tankGeometry = new THREE.BoxGeometry(
GRID_WIDTH + 0.07,
GRID_HEIGHT + 0.07,
GRID_DEPTH + 0.07
);
const tankEdges = new THREE.EdgesGeometry(tankGeometry);
const tankFrame = new THREE.LineSegments(
tankEdges,
new THREE.LineBasicMaterial({
color: accentColor,
transparent: true,
opacity: 0.35
})
);
scene.add(tankFrame);
const upArrow = new THREE.ArrowHelper(
new THREE.Vector3(0, 1, 0),
new THREE.Vector3(-GRID_WIDTH * 0.5 - 0.34, floorY + 0.02, 0),
0.77,
0x7d9aad,
0.13,
0.08
);
upArrow.line.material.transparent = true;
upArrow.line.material.opacity = 0.58;
upArrow.cone.material.transparent = true;
upArrow.cone.material.opacity = 0.58;
scene.add(upArrow);
const hemisphere = new THREE.HemisphereLight(0xc9e9ff, 0x17202b, 1.65);
scene.add(hemisphere);
const key = new THREE.DirectionalLight(0xffffff, 2.5);
key.position.set(4.5, 7, 5.5);
scene.add(key);
const rim = new THREE.PointLight(accentColor, 10, 9, 2);
rim.position.set(-3.2, 2.2, -2.7);
scene.add(rim);
const fill = new THREE.PointLight(0x789dff, 7, 8, 2);
fill.position.set(3.6, 0.4, 3.2);
scene.add(fill);
return { scene, voxels };
}
const leftView = createVoxelScene(0x4ca7c3, 0x102330);
const rightView = createVoxelScene(0x8766bc, 0x211827);
function updateVoxelColors(mesh, state) {
for (let i = 0; i < CELL_COUNT; i++) {
const c = THREE.MathUtils.clamp(state[i], 0, 1);
if (c >= 0.999) {
mesh.setColorAt(i, LOW_COLOR);
} else if (c <= 0.001) {
mesh.setColorAt(i, HIGH_COLOR);
} else {
MIXED_COLOR.lerpColors(HIGH_COLOR, LOW_COLOR, c);
mesh.setColorAt(i, MIXED_COLOR);
}
}
mesh.instanceColor.needsUpdate = true;
}
updateVoxelColors(leftView.voxels, leftState);
updateVoxelColors(rightView.voxels, rightState);
// ---------------------------------------------------------------------
// Direct camera controls; no examples or addon modules are used.
// ---------------------------------------------------------------------
const camera = new THREE.PerspectiveCamera(34, 1, 0.1, 100);
const orbit = {
yaw: -0.48,
pitch: 0.16,
distance: 8.0
};
const defaultOrbit = { ...orbit };
function updateCamera(aspect) {
camera.aspect = aspect;
camera.position.set(
Math.sin(orbit.yaw) * Math.cos(orbit.pitch) * orbit.distance,
Math.sin(orbit.pitch) * orbit.distance,
Math.cos(orbit.yaw) * Math.cos(orbit.pitch) * orbit.distance
);
camera.lookAt(0, -0.02, 0);
camera.updateProjectionMatrix();
}
const pointer = {
active: false,
id: null,
x: 0,
y: 0
};
canvas.addEventListener("pointerdown", (event) => {
pointer.active = true;
pointer.id = event.pointerId;
pointer.x = event.clientX;
pointer.y = event.clientY;
canvas.classList.add("dragging");
canvas.setPointerCapture(event.pointerId);
});
canvas.addEventListener("pointermove", (event) => {
if (!pointer.active || event.pointerId !== pointer.id) return;
const dx = event.clientX - pointer.x;
const dy = event.clientY - pointer.y;
pointer.x = event.clientX;
pointer.y = event.clientY;
orbit.yaw -= dx * 0.006;
orbit.pitch = THREE.MathUtils.clamp(orbit.pitch + dy * 0.005, -0.25, 0.82);
});
function releasePointer(event) {
if (event.pointerId !== pointer.id) return;
pointer.active = false;
pointer.id = null;
canvas.classList.remove("dragging");
}
canvas.addEventListener("pointerup", releasePointer);
canvas.addEventListener("pointercancel", releasePointer);
canvas.addEventListener("contextmenu", (event) => event.preventDefault());
canvas.addEventListener(
"wheel",
(event) => {
event.preventDefault();
orbit.distance = THREE.MathUtils.clamp(
orbit.distance + event.deltaY * 0.006,
5.2,
13
);
},
{ passive: false }
);
$("cameraButton").addEventListener("click", () => {
orbit.yaw = defaultOrbit.yaw;
orbit.pitch = defaultOrbit.pitch;
orbit.distance = defaultOrbit.distance;
});
// ---------------------------------------------------------------------
// Diffusion model
// ---------------------------------------------------------------------
let densityContrast = Number($("density").value);
let mixingRate = Number($("mixRate").value);
let playbackSpeed = Number($("speed").value);
let running = true;
let simulationTime = 0;
function diffuseRightSample() {
const k = Math.min(0.075, 0.014 * mixingRate);
for (let z = 0; z < NZ; z++) {
for (let y = 0; y < NY; y++) {
for (let x = 0; x < NX; x++) {
const index = gridIndex(x, y, z);
const center = rightState[index];
let neighborSum = 0;
let degree = 0;
if (x > 0) {
neighborSum += rightState[gridIndex(x - 1, y, z)];
degree++;
}
if (x < NX - 1) {
neighborSum += rightState[gridIndex(x + 1, y, z)];
degree++;
}
if (y > 0) {
neighborSum += rightState[gridIndex(x, y - 1, z)];
degree++;
}
if (y < NY - 1) {
neighborSum += rightState[gridIndex(x, y + 1, z)];
degree++;
}
if (z > 0) {
neighborSum += rightState[gridIndex(x, y, z - 1)];
degree++;
}
if (z < NZ - 1) {
neighborSum += rightState[gridIndex(x, y, z + 1)];
degree++;
}
nextState[index] = THREE.MathUtils.clamp(
center + k * (neighborSum - degree * center),
0,
1
);
}
}
}
// Restore the global component fraction to keep the model conservative.
let sum = 0;
for (let i = 0; i < CELL_COUNT; i++) sum += nextState[i];
const correction = (initialMean * CELL_COUNT - sum) / CELL_COUNT;
for (let i = 0; i < CELL_COUNT; i++) {
rightState[i] = THREE.MathUtils.clamp(nextState[i] + correction, 0, 1);
}
}
// ---------------------------------------------------------------------
// Density profile graphics
// ---------------------------------------------------------------------
const profileLeft = $("profileLeft");
const profileRight = $("profileRight");
const chartBottom = 42;
const chartTop = 4;
const chartSpan = chartBottom - chartTop;
const chartLowX = 8;
const chartHighX = 92;
function updateLeftProfile() {
const boundaryBottomY =
chartBottom - ((INTERFACE_ROW - 1) / (NY - 1)) * chartSpan;
const boundaryTopY =
chartBottom - (INTERFACE_ROW / (NY - 1)) * chartSpan;
profileLeft.setAttribute(
"d",
[
`M ${chartHighX} ${chartBottom}`,
`L ${chartHighX} ${boundaryBottomY}`,
`L ${chartLowX} ${boundaryTopY}`,
`L ${chartLowX} ${chartTop}`
].join(" ")
);
}
function updateRightProfile() {
const rowConcentration = new Float32Array(NY);
const rowCounts = new Uint16Array(NY);
for (let z = 0; z < NZ; z++) {
for (let y = 0; y < NY; y++) {
for (let x = 0; x < NX; x++) {
rowConcentration[y] += rightState[gridIndex(x, y, z)];
rowCounts[y]++;
}
}
}
const points = [];
for (let y = 0; y < NY; y++) {
const c = rowConcentration[y] / rowCounts[y];
const highFraction = 1 - c;
const px = chartLowX + (chartHighX - chartLowX) * highFraction;
const py = chartBottom - (y / (NY - 1)) * chartSpan;
points.push(`${px.toFixed(2)} ${py.toFixed(2)}`);
}
profileRight.setAttribute("d", `M ${points.join(" L ")}`);
}
function updateDensityLabels() {
const lowDensity = 1;
const highDensity = lowDensity + densityContrast;
$("densityOutput").textContent = `+${densityContrast.toFixed(2)}`;
$("rhoLow").textContent = lowDensity.toFixed(2);
$("rhoHigh").textContent = highDensity.toFixed(2);
}
function updateProgress() {
const currentStd = standardDeviation(rightState, initialMean);
const progress = THREE.MathUtils.clamp(
1 - currentStd / initialStdDev,
0,
1
);
const percent = Math.round(progress * 100);
$("progressFill").style.width = `${percent}%`;
$("progressText").textContent = `${percent}%`;
if (progress > 0.96) {
$("mixStatus").textContent = "Uniformly mixed";
} else if (progress > 0.62) {
$("mixStatus").textContent = "Interface dispersing";
} else if (progress > 0.20) {
$("mixStatus").textContent = "Transition zone forming";
} else {
$("mixStatus").textContent = "Interface present";
}
}
function updateRangeFill(input) {
const min = Number(input.min);
const max = Number(input.max);
const value = Number(input.value);
const percent = ((value - min) / (max - min)) * 100;
input.style.setProperty("--fill", `${percent}%`);
}
const densityInput = $("density");
const mixInput = $("mixRate");
const speedInput = $("speed");
densityInput.addEventListener("input", () => {
densityContrast = Number(densityInput.value);
updateRangeFill(densityInput);
updateDensityLabels();
});
mixInput.addEventListener("input", () => {
mixingRate = Number(mixInput.value);
$("mixOutput").textContent = `${mixingRate.toFixed(2)}×`;
updateRangeFill(mixInput);
});
speedInput.addEventListener("input", () => {
playbackSpeed = Number(speedInput.value);
$("speedOutput").textContent = `${playbackSpeed.toFixed(2)}×`;
updateRangeFill(speedInput);
});
$("playButton").addEventListener("click", () => {
running = !running;
$("playButton").textContent = running ? "Ⅱ Pause" : "▶ Play";
});
$("resetButton").addEventListener("click", () => {
leftState.set(initialPattern);
rightState.set(initialPattern);
simulationTime = 0;
updateVoxelColors(leftView.voxels, leftState);
updateVoxelColors(rightView.voxels, rightState);
updateLeftProfile();
updateRightProfile();
updateProgress();
});
[densityInput, mixInput, speedInput].forEach(updateRangeFill);
updateDensityLabels();
updateLeftProfile();
updateRightProfile();
updateProgress();
// ---------------------------------------------------------------------
// Rendering and responsive split layout
// ---------------------------------------------------------------------
let layoutMode = "horizontal";
function resize() {
const width = Math.max(1, stage.clientWidth);
const height = Math.max(1, stage.clientHeight);
renderer.setSize(width, height, false);
layoutMode = width < 720 ? "vertical" : "horizontal";
stage.classList.toggle("vertical", layoutMode === "vertical");
splitUI.classList.toggle("vertical", layoutMode === "vertical");
}
const resizeObserver = new ResizeObserver(resize);
resizeObserver.observe(stage);
resize();
function renderViewport(view, x, y, width, height) {
renderer.setViewport(x, y, width, height);
renderer.setScissor(x, y, width, height);
updateCamera(width / Math.max(height, 1));
renderer.render(view.scene, camera);
}
function renderScenes() {
const width = Math.max(1, stage.clientWidth);
const height = Math.max(1, stage.clientHeight);
renderer.setScissorTest(true);
if (layoutMode === "horizontal") {
const leftWidth = Math.floor(width / 2);
const rightWidth = width - leftWidth;
renderViewport(leftView, 0, 0, leftWidth, height);
renderViewport(rightView, leftWidth, 0, rightWidth, height);
} else {
const topHeight = Math.floor(height / 2);
const bottomHeight = height - topHeight;
renderViewport(leftView, 0, height - topHeight, width, topHeight);
renderViewport(rightView, 0, 0, width, bottomHeight);
}
}
// ---------------------------------------------------------------------
// Animation loop
// ---------------------------------------------------------------------
const FIXED_STEP = 1 / 30;
let accumulator = 0;
let previousTime = performance.now();
let profileFrame = 0;
function animate(now) {
const frameDelta = Math.min(0.05, (now - previousTime) / 1000);
previousTime = now;
if (running) {
accumulator += frameDelta * playbackSpeed;
while (accumulator >= FIXED_STEP) {
diffuseRightSample();
simulationTime += FIXED_STEP;
accumulator -= FIXED_STEP;
}
}
updateVoxelColors(rightView.voxels, rightState);
profileFrame++;
if (profileFrame % 5 === 0) {
updateRightProfile();
updateProgress();
}
const minutes = Math.floor(simulationTime / 60);
const seconds = simulationTime - minutes * 60;
$("timeReadout").textContent =
`t = ${String(minutes).padStart(2, "0")}:${seconds.toFixed(1).padStart(4, "0")}`;
renderScenes();
requestAnimationFrame(animate);
}
requestAnimationFrame(animate);
</script>
</body>
</html>
```