Prompt specification
Build or customize the Three.js 3D scene "Layered insulation conduction 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: Layered insulation conduction explorer
Category: Science & Physics · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/layered-insulation-conduction-explorer-x1476
Scene Description Prompt:
Create a standalone low-poly scene in one HTML file using Three.js from cdnjs. Let viewers add material layers with stated thickness and conductivity; compute ideal steady thermal resistance and show how interfaces contribute to the total under one-dimensional assumptions.
Working Three.js Starter (layered-insulation-conduction-explorer-x1476):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Thermal Stack Lab</title>
<style>
:root {
--ink: #172126;
--muted: #68757a;
--paper: #f4f5ef;
--panel: #fbfcf8;
--line: #dce1d8;
--accent: #dc6849;
--accent-dark: #b94c32;
--cold: #568eae;
--hot: #e26443;
--green: #4e7865;
--shadow: 0 18px 50px rgba(31, 43, 43, 0.10);
}
* {
box-sizing: border-box;
}
html,
body {
margin: 0;
min-height: 100%;
background: var(--paper);
color: var(--ink);
font-family:
Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
body {
overflow: hidden;
}
button,
input {
font: inherit;
}
button {
color: inherit;
}
.app {
height: 100vh;
display: flex;
flex-direction: column;
}
header {
height: 74px;
flex: 0 0 74px;
display: flex;
align-items: center;
justify-content: space-between;
padding: 0 24px;
border-bottom: 1px solid var(--line);
background: rgba(251, 252, 248, 0.94);
backdrop-filter: blur(12px);
z-index: 20;
}
.brand {
display: flex;
align-items: center;
gap: 14px;
}
.brand-mark {
width: 39px;
height: 39px;
position: relative;
transform: rotate(-8deg);
}
.brand-mark span {
position: absolute;
left: 0;
width: 39px;
height: 7px;
border-radius: 2px;
background: var(--ink);
}
.brand-mark span:nth-child(1) {
top: 3px;
background: var(--hot);
transform: skewX(-24deg);
}
.brand-mark span:nth-child(2) {
top: 14px;
transform: skewX(24deg);
}
.brand-mark span:nth-child(3) {
top: 25px;
background: var(--cold);
transform: skewX(-24deg);
}
.brand h1 {
margin: 0;
font-size: 16px;
letter-spacing: 0.15em;
text-transform: uppercase;
}
.brand p {
margin: 3px 0 0;
color: var(--muted);
font-size: 12px;
}
.header-actions {
display: flex;
align-items: center;
gap: 10px;
}
.model-badge {
display: inline-flex;
align-items: center;
gap: 8px;
color: var(--green);
font-size: 11px;
font-weight: 750;
letter-spacing: 0.08em;
text-transform: uppercase;
padding: 9px 12px;
border: 1px solid #cedbd0;
border-radius: 999px;
background: #f1f6ef;
}
.model-badge::before {
content: "";
width: 7px;
height: 7px;
border-radius: 50%;
background: #6c9b77;
box-shadow: 0 0 0 3px rgba(108, 155, 119, 0.14);
}
.button {
border: 1px solid var(--line);
background: white;
border-radius: 9px;
padding: 9px 12px;
cursor: pointer;
font-size: 12px;
font-weight: 700;
transition:
border-color 140ms ease,
transform 140ms ease,
background 140ms ease;
}
.button:hover {
border-color: #aeb8ae;
transform: translateY(-1px);
}
.button.primary {
color: white;
border-color: var(--accent);
background: var(--accent);
}
.button.primary:hover {
background: var(--accent-dark);
}
.workspace {
min-height: 0;
flex: 1;
display: grid;
grid-template-columns: minmax(0, 1fr) 430px;
}
.viewer {
min-width: 0;
min-height: 0;
position: relative;
overflow: hidden;
background:
radial-gradient(circle at 52% 40%, rgba(255, 255, 255, 0.9), transparent 42%),
#e9ede6;
}
#sceneCanvas {
width: 100%;
height: 100%;
display: block;
touch-action: none;
cursor: grab;
}
#sceneCanvas.dragging {
cursor: grabbing;
}
.viewer-top {
position: absolute;
z-index: 4;
top: 20px;
left: 22px;
right: 22px;
display: flex;
justify-content: space-between;
align-items: flex-start;
pointer-events: none;
}
.viewer-kicker {
font-size: 10px;
font-weight: 800;
letter-spacing: 0.16em;
text-transform: uppercase;
color: #77827d;
}
.viewer-title {
margin-top: 6px;
font-size: 23px;
font-weight: 730;
letter-spacing: -0.04em;
}
.viewer-subtitle {
margin-top: 5px;
color: #65716e;
font-size: 12px;
}
.viewer-status {
display: flex;
gap: 7px;
flex-wrap: wrap;
justify-content: flex-end;
}
.status-chip {
border: 1px solid rgba(74, 92, 84, 0.17);
border-radius: 8px;
padding: 7px 9px;
background: rgba(250, 252, 247, 0.78);
backdrop-filter: blur(8px);
color: #51605a;
font-size: 10px;
font-weight: 750;
letter-spacing: 0.05em;
text-transform: uppercase;
}
.viewer-bottom {
position: absolute;
z-index: 4;
left: 22px;
right: 22px;
bottom: 20px;
display: flex;
align-items: flex-end;
justify-content: space-between;
gap: 16px;
pointer-events: none;
}
.legend {
display: flex;
align-items: center;
gap: 13px;
padding: 10px 12px;
border: 1px solid rgba(74, 92, 84, 0.14);
border-radius: 9px;
background: rgba(250, 252, 247, 0.82);
backdrop-filter: blur(8px);
font-size: 11px;
color: #53605c;
}
.legend-item {
display: inline-flex;
align-items: center;
gap: 6px;
}
.legend-dot {
width: 8px;
height: 8px;
border-radius: 50%;
}
.camera-tools {
display: flex;
gap: 6px;
pointer-events: auto;
}
.camera-tools .button {
background: rgba(251, 252, 248, 0.87);
backdrop-filter: blur(8px);
}
.pins {
position: absolute;
inset: 0;
pointer-events: none;
z-index: 3;
overflow: hidden;
}
.layer-pin,
.surface-label {
position: absolute;
left: 0;
top: 0;
will-change: transform;
}
.layer-pin {
pointer-events: auto;
border: 1px solid rgba(60, 76, 70, 0.18);
border-radius: 8px;
padding: 7px 9px;
background: rgba(253, 254, 250, 0.9);
backdrop-filter: blur(7px);
box-shadow: 0 6px 18px rgba(50, 65, 58, 0.08);
text-align: left;
cursor: pointer;
min-width: 115px;
}
.layer-pin strong {
display: block;
max-width: 150px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
font-size: 10px;
letter-spacing: 0.04em;
text-transform: uppercase;
}
.layer-pin span {
display: block;
margin-top: 3px;
color: #74807b;
font-size: 9px;
}
.surface-label {
padding: 6px 9px;
border-radius: 999px;
font-size: 9px;
font-weight: 850;
letter-spacing: 0.12em;
text-transform: uppercase;
color: white;
white-space: nowrap;
}
.surface-label.hot {
background: var(--hot);
}
.surface-label.cold {
background: var(--cold);
}
.sidebar {
min-width: 0;
min-height: 0;
overflow-y: auto;
border-left: 1px solid var(--line);
background: var(--panel);
scrollbar-width: thin;
scrollbar-color: #bdc6bd transparent;
}
.section {
padding: 19px 20px;
border-bottom: 1px solid var(--line);
}
.section-heading {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
margin-bottom: 14px;
}
.section-heading h2 {
margin: 0;
font-size: 11px;
font-weight: 850;
letter-spacing: 0.13em;
text-transform: uppercase;
}
.section-heading p {
margin: 0;
color: var(--muted);
font-size: 10px;
}
.input-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 11px;
}
.input-grid.three {
grid-template-columns: repeat(3, 1fr);
}
.field {
min-width: 0;
}
.field label {
display: block;
margin-bottom: 6px;
color: #697570;
font-size: 9px;
font-weight: 800;
letter-spacing: 0.09em;
text-transform: uppercase;
}
.input-wrap {
position: relative;
}
.input-wrap input {
width: 100%;
min-width: 0;
border: 1px solid var(--line);
border-radius: 8px;
padding: 9px 35px 9px 10px;
outline: none;
background: white;
color: var(--ink);
font-size: 13px;
font-weight: 650;
transition:
border-color 140ms ease,
box-shadow 140ms ease;
}
.input-wrap input:focus {
border-color: #8ba292;
box-shadow: 0 0 0 3px rgba(112, 143, 121, 0.1);
}
.input-wrap .unit {
position: absolute;
right: 9px;
top: 50%;
transform: translateY(-50%);
pointer-events: none;
color: #8a948f;
font-size: 9px;
font-weight: 750;
}
.result-card {
background:
linear-gradient(145deg, rgba(255, 255, 255, 0.96), rgba(242, 246, 238, 0.96));
}
.hero-result {
display: flex;
align-items: flex-end;
gap: 8px;
margin-top: 2px;
}
.hero-result strong {
font-size: 43px;
line-height: 0.95;
letter-spacing: -0.065em;
font-variant-numeric: tabular-nums;
}
.hero-result span {
padding-bottom: 3px;
color: #69746f;
font-size: 12px;
font-weight: 750;
}
.result-caption {
margin-top: 7px;
color: #748079;
font-size: 10px;
}
.metric-grid {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 8px;
margin-top: 16px;
}
.metric {
padding: 10px;
border: 1px solid #e0e5dc;
border-radius: 9px;
background: rgba(255, 255, 255, 0.74);
}
.metric span {
display: block;
margin-bottom: 5px;
color: #7b8580;
font-size: 8px;
font-weight: 800;
letter-spacing: 0.07em;
text-transform: uppercase;
}
.metric strong {
font-size: 17px;
letter-spacing: -0.03em;
font-variant-numeric: tabular-nums;
}
.metric small {
margin-left: 3px;
color: #7b8580;
font-size: 9px;
}
.error-message {
display: none;
margin-top: 10px;
padding: 9px 10px;
border-radius: 8px;
background: #fff0e9;
color: #a9442d;
font-size: 11px;
}
.error-message.visible {
display: block;
}
.resistance-map {
margin-top: 17px;
}
.mini-heading {
display: flex;
justify-content: space-between;
margin-bottom: 8px;
color: #69756f;
font-size: 9px;
font-weight: 800;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.profile {
display: flex;
width: 100%;
height: 29px;
overflow: hidden;
border: 1px solid #d9dfd6;
border-radius: 7px;
background: #edf0ea;
}
.profile-segment {
position: relative;
min-width: 0;
height: 100%;
border-right: 1px solid rgba(255, 255, 255, 0.55);
transition: flex-grow 180ms ease;
}
.profile-segment.interface {
min-width: 3px;
background: #f1a14c;
border-right: 2px solid #fff5df;
}
.profile-segment span {
position: absolute;
inset: 0;
display: grid;
place-items: center;
overflow: hidden;
color: rgba(20, 31, 30, 0.72);
font-size: 8px;
font-weight: 850;
white-space: nowrap;
}
.split-bar {
display: flex;
height: 6px;
margin-top: 7px;
overflow: hidden;
border-radius: 999px;
background: #edf0ea;
}
.split-bar span:first-child {
background: #647d70;
}
.split-bar span:last-child {
background: #f1a14c;
}
.split-labels {
display: flex;
justify-content: space-between;
margin-top: 6px;
color: #79837e;
font-size: 9px;
}
.result-grid {
display: grid;
grid-template-columns: 1fr 112px;
gap: 16px;
align-items: stretch;
margin-top: 17px;
}
.breakdown {
display: flex;
flex-direction: column;
gap: 7px;
}
.breakdown-row {
display: grid;
grid-template-columns: 8px 1fr auto;
gap: 7px;
align-items: center;
font-size: 10px;
}
.breakdown-swatch {
width: 7px;
height: 7px;
border-radius: 2px;
}
.breakdown-name {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
color: #53605b;
}
.breakdown-value {
color: #6e7974;
font-variant-numeric: tabular-nums;
}
.temperature-ladder {
position: relative;
min-height: 155px;
overflow: hidden;
border-radius: 9px;
background: linear-gradient(to top, var(--cold), var(--hot));
box-shadow: inset 0 0 0 1px rgba(34, 48, 43, 0.1);
}
.temperature-ladder::after {
content: "T";
position: absolute;
top: 6px;
right: 7px;
color: rgba(255, 255, 255, 0.8);
font-size: 9px;
font-weight: 850;
}
.temp-marker {
position: absolute;
left: 0;
right: 0;
height: 1px;
background: rgba(255, 255, 255, 0.68);
transform: translateY(-50%);
}
.temp-marker::before {
content: "";
position: absolute;
left: 5px;
top: -3px;
width: 7px;
height: 7px;
border-radius: 50%;
background: white;
box-shadow: 0 1px 4px rgba(0, 0, 0, 0.2);
}
.temp-marker b {
position: absolute;
right: 6px;
top: -10px;
color: white;
font-size: 8px;
font-variant-numeric: tabular-nums;
}
.layer-stack {
display: flex;
flex-direction: column;
gap: 0;
}
.layer-card {
padding: 13px;
border: 1px solid var(--line);
border-radius: 11px;
background: white;
transition:
border-color 140ms ease,
box-shadow 140ms ease;
}
.layer-card.selected {
border-color: #8ba08f;
box-shadow: 0 0 0 3px rgba(94, 125, 105, 0.09);
}
.layer-head {
display: flex;
align-items: center;
gap: 8px;
margin-bottom: 11px;
}
.layer-number {
width: 23px;
height: 23px;
display: grid;
place-items: center;
flex: 0 0 23px;
border-radius: 6px;
background: #edf0e9;
color: #68746e;
font-size: 9px;
font-weight: 850;
}
.color-input {
width: 22px;
height: 22px;
flex: 0 0 22px;
padding: 0;
border: 0;
border-radius: 6px;
background: none;
cursor: pointer;
overflow: hidden;
}
.color-input::-webkit-color-swatch-wrapper {
padding: 0;
}
.color-input::-webkit-color-swatch {
border: 1px solid rgba(0, 0, 0, 0.12);
border-radius: 6px;
}
.name-input {
min-width: 0;
flex: 1;
border: 0;
outline: none;
padding: 3px 0;
background: transparent;
color: var(--ink);
font-size: 12px;
font-weight: 800;
}
.layer-actions {
display: flex;
gap: 4px;
}
.icon-button {
width: 25px;
height: 25px;
display: grid;
place-items: center;
padding: 0;
border: 1px solid #e0e4dc;
border-radius: 6px;
background: #fafbf8;
color: #69746f;
font-size: 11px;
cursor: pointer;
}
.icon-button:hover:not(:disabled) {
border-color: #aeb9af;
background: white;
}
.icon-button.danger:hover {
border-color: #e1a391;
color: #b64e34;
}
.icon-button:disabled {
opacity: 0.35;
cursor: default;
}
.layer-fields {
display: grid;
grid-template-columns: 1fr 1fr 0.8fr;
gap: 8px;
}
.layer-fields .input-wrap input {
padding: 8px 31px 8px 8px;
font-size: 11px;
}
.layer-fields .unit {
right: 7px;
font-size: 8px;
}
.layer-resistance {
margin-top: 9px;
color: #78827d;
font-size: 9px;
text-align: right;
}
.interface-row {
position: relative;
margin: 0 6px;
padding: 12px 0 12px 27px;
}
.interface-row::before {
content: "";
position: absolute;
left: 11px;
top: 0;
bottom: 0;
width: 1px;
background: repeating-linear-gradient(
to bottom,
#bdc7bd 0,
#bdc7bd 4px,
transparent 4px,
transparent 8px
);
}
.interface-row::after {
content: "";
position: absolute;
left: 7px;
top: 50%;
width: 9px;
height: 9px;
transform: translateY(-50%) rotate(45deg);
border: 1px solid #aeb9af;
background: var(--panel);
}
.interface-content {
display: grid;
grid-template-columns: 1fr 118px;
gap: 10px;
align-items: end;
padding: 9px 10px;
border: 1px dashed #d6ddd4;
border-radius: 8px;
background: #f7f9f4;
}
.interface-copy strong {
display: block;
margin-bottom: 4px;
font-size: 9px;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.interface-copy span,
.interface-result {
color: #7b8580;
font-size: 8px;
}
.interface-result {
display: block;
margin-top: 4px;
text-align: right;
}
.add-layer {
width: 100%;
margin-top: 13px;
border-style: dashed;
background: transparent;
}
.assumptions {
padding-bottom: 28px;
}
.assumption-list {
margin: 0;
padding: 0;
list-style: none;
}
.assumption-list li {
position: relative;
margin: 8px 0;
padding-left: 17px;
color: #697570;
font-size: 10px;
line-height: 1.45;
}
.assumption-list li::before {
content: "";
position: absolute;
left: 0;
top: 5px;
width: 6px;
height: 6px;
border-radius: 50%;
background: #819888;
}
code {
padding: 1px 4px;
border-radius: 4px;
background: #e9ede5;
color: #4f5e56;
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
font-size: 0.95em;
}
@media (max-width: 980px) {
body {
overflow: auto;
}
.app {
height: auto;
min-height: 100vh;
}
header {
position: sticky;
top: 0;
}
.workspace {
display: block;
}
.viewer {
height: 58vh;
min-height: 430px;
}
.sidebar {
overflow: visible;
border-left: 0;
border-top: 1px solid var(--line);
}
}
@media (max-width: 560px) {
header {
height: 66px;
flex-basis: 66px;
padding: 0 15px;
}
.brand p,
.model-badge {
display: none;
}
.brand h1 {
font-size: 13px;
}
.viewer-top {
left: 15px;
right: 15px;
top: 15px;
}
.viewer-title {
font-size: 19px;
}
.viewer-status {
display: none;
}
.viewer-bottom {
left: 15px;
right: 15px;
bottom: 14px;
}
.legend {
display: none;
}
.section {
padding: 17px 15px;
}
.result-grid {
grid-template-columns: 1fr;
}
.temperature-ladder {
min-height: 110px;
}
}
</style>
</head>
<body>
<div class="app">
<header>
<div class="brand">
<div class="brand-mark" aria-hidden="true">
<span></span><span></span><span></span>
</div>
<div>
<h1>Thermal Stack Lab</h1>
<p>Layered-material resistance explorer</p>
</div>
</div>
<div class="header-actions">
<div class="model-badge">1D steady-state model</div>
<button class="button" id="exportButton">Export CSV</button>
</div>
</header>
<main class="workspace">
<section class="viewer" aria-label="Interactive three-dimensional material stack">
<canvas id="sceneCanvas"></canvas>
<div class="pins" id="pins"></div>
<div class="viewer-top">
<div>
<div class="viewer-kicker">Assembly view</div>
<div class="viewer-title">Material stack</div>
<div class="viewer-subtitle">Cold side at the base · hot side at the top</div>
</div>
<div class="viewer-status">
<div class="status-chip">Drag to orbit</div>
<div class="status-chip">Scroll to zoom</div>
<div class="status-chip">Click a layer</div>
</div>
</div>
<div class="viewer-bottom">
<div class="legend">
<span class="legend-item">
<span class="legend-dot" style="background: var(--hot)"></span>
Hot surface
</span>
<span class="legend-item">
<span class="legend-dot" style="background: var(--cold)"></span>
Cold surface
</span>
<span class="legend-item">
<span class="legend-dot" style="background: #647d70"></span>
Bulk resistance
</span>
<span class="legend-item">
<span class="legend-dot" style="background: #f1a14c"></span>
Interface resistance
</span>
</div>
<div class="camera-tools">
<button class="button" id="zoomOut" title="Zoom out">−</button>
<button class="button" id="zoomIn" title="Zoom in">+</button>
<button class="button" id="resetCamera">Reset view</button>
</div>
</div>
</section>
<aside class="sidebar">
<section class="section">
<div class="section-heading">
<h2>Boundary conditions</h2>
<p>Uniform area</p>
</div>
<div class="input-grid three">
<div class="field">
<label for="areaInput">Area</label>
<div class="input-wrap">
<input id="areaInput" type="number" min="0.000001" step="0.01" value="0.25" />
<span class="unit">m²</span>
</div>
</div>
<div class="field">
<label for="hotInput">Hot surface</label>
<div class="input-wrap">
<input id="hotInput" type="number" step="1" value="60" />
<span class="unit">°C</span>
</div>
</div>
<div class="field">
<label for="coldInput">Cold surface</label>
<div class="input-wrap">
<input id="coldInput" type="number" step="1" value="20" />
<span class="unit">°C</span>
</div>
</div>
</div>
</section>
<section class="section result-card">
<div class="section-heading">
<h2>Thermal result</h2>
<p id="flowDirection">Hot → cold</p>
</div>
<div class="hero-result">
<strong id="totalResistance">—</strong>
<span>K/W</span>
</div>
<div class="result-caption">Total thermal resistance across the complete stack</div>
<div class="metric-grid">
<div class="metric">
<span>Heat flow</span>
<strong id="heatFlow">—</strong><small>W</small>
</div>
<div class="metric">
<span>Flux</span>
<strong id="heatFlux">—</strong><small>W/m²</small>
</div>
<div class="metric">
<span>U-value</span>
<strong id="uValue">—</strong><small>W/m²K</small>
</div>
</div>
<div class="error-message" id="errorMessage"></div>
<div class="resistance-map">
<div class="mini-heading">
<span>Resistance map</span>
<span id="specificResistance">— m²K/W</span>
</div>
<div class="profile" id="profile"></div>
<div class="split-bar" id="splitBar">
<span style="width: 100%"></span>
<span style="width: 0%"></span>
</div>
<div class="split-labels">
<span id="bulkLabel">Bulk —</span>
<span id="interfaceLabel">Interfaces —</span>
</div>
</div>
<div class="result-grid">
<div class="breakdown" id="breakdown"></div>
<div>
<div class="mini-heading">
<span>Node profile</span>
<span>°C</span>
</div>
<div class="temperature-ladder" id="temperatureLadder"></div>
</div>
</div>
</section>
<section class="section" id="layersPanel">
<div class="section-heading">
<h2>Layers & interfaces</h2>
<p>Cold → hot order</p>
</div>
<div class="layer-stack" id="layerStack"></div>
<button class="button add-layer" id="addLayerButton">+ Add material layer</button>
</section>
<section class="section assumptions">
<div class="section-heading">
<h2>Model assumptions</h2>
<p>Ideal analytical basis</p>
</div>
<ul class="assumption-list">
<li>Steady, one-dimensional heat flow normal to a uniform area.</li>
<li>
Each layer has constant conductivity:
<code>Rᵢ = Lᵢ / (kᵢA)</code>.
</li>
<li>
Optional interface resistance is area-normalized:
<code>Rᶜ = R″ᶜ / A</code>.
</li>
<li>
Perfectly bonded interfaces use <code>R″ᶜ = 0</code>, so their
contribution is zero.
</li>
<li>No convection, radiation, lateral leakage, phase change, or temperature-dependent conductivity.</li>
<li>Surface temperatures are treated as known, isothermal boundaries.</li>
</ul>
</section>
</aside>
</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 $ = (selector) => document.querySelector(selector);
const $$ = (selector) => [...document.querySelectorAll(selector)];
const uid = (() => {
let count = 0;
return (prefix) => `${prefix}-${Date.now().toString(36)}-${count++}`;
})();
const palette = [
"#c97b5c",
"#d6a15f",
"#8a9b78",
"#6f8f9b",
"#9b7b90",
"#b9a06f"
];
const state = {
area: 0.25,
hot: 60,
cold: 20,
selectedLayerId: "layer-1",
layers: [
{
id: "layer-1",
name: "Ceramic fiber",
thicknessMm: 40,
conductivity: 0.12,
color: "#c97b5c"
},
{
id: "layer-2",
name: "Mineral wool",
thicknessMm: 60,
conductivity: 0.036,
color: "#d6a15f"
},
{
id: "layer-3",
name: "Brick",
thicknessMm: 100,
conductivity: 0.62,
color: "#9b765e"
},
{
id: "layer-4",
name: "Aluminium sheet",
thicknessMm: 2,
conductivity: 160,
color: "#9aa7aa"
}
],
boundaries: [
{ id: "boundary-1", rc: 0 },
{ id: "boundary-2", rc: 0 },
{ id: "boundary-3", rc: 0 }
]
};
const canvas = $("#sceneCanvas");
const viewer = $(".viewer");
const layerStack = $("#layerStack");
const pinsContainer = $("#pins");
const scene = new THREE.Scene();
scene.background = new THREE.Color("#e9ede6");
scene.fog = new THREE.Fog("#e9ede6", 13, 28);
const camera = new THREE.PerspectiveCamera(38, 1, 0.1, 100);
const renderer = new THREE.WebGLRenderer({
canvas,
antialias: true,
alpha: false,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.08;
const ambient = new THREE.HemisphereLight("#ffffff", "#88958a", 2.25);
scene.add(ambient);
const keyLight = new THREE.DirectionalLight("#fff6e8", 3.3);
keyLight.position.set(5, 8, 6);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(2048, 2048);
keyLight.shadow.camera.left = -7;
keyLight.shadow.camera.right = 7;
keyLight.shadow.camera.top = 7;
keyLight.shadow.camera.bottom = -7;
keyLight.shadow.normalBias = 0.025;
scene.add(keyLight);
const rimLight = new THREE.DirectionalLight("#b9d7ec", 1.65);
rimLight.position.set(-6, 3, -5);
scene.add(rimLight);
const floor = new THREE.Mesh(
new THREE.PlaneGeometry(30, 30),
new THREE.MeshStandardMaterial({
color: "#e4e8e0",
roughness: 1,
metalness: 0
})
);
floor.rotation.x = -Math.PI / 2;
floor.position.y = -2.35;
floor.receiveShadow = true;
scene.add(floor);
const grid = new THREE.GridHelper(24, 24, "#c4ccc2", "#d5dbd2");
grid.position.y = -2.34;
grid.material.transparent = true;
grid.material.opacity = 0.52;
scene.add(grid);
const stackGroup = new THREE.Group();
const flowGroup = new THREE.Group();
scene.add(stackGroup, flowGroup);
const cameraState = {
yaw: 0.68,
pitch: 0.34,
radius: 9.2,
target: new THREE.Vector3(0, 0, 0)
};
let selectedMeshes = [];
let layerPins = [];
let lastCalculation = null;
const hotSurfaceLabel = document.createElement("div");
hotSurfaceLabel.className = "surface-label hot";
hotSurfaceLabel.textContent = "Hot surface";
pinsContainer.appendChild(hotSurfaceLabel);
const coldSurfaceLabel = document.createElement("div");
coldSurfaceLabel.className = "surface-label cold";
coldSurfaceLabel.textContent = "Cold surface";
pinsContainer.appendChild(coldSurfaceLabel);
function escapeHTML(value) {
return String(value)
.replaceAll("&", "&")
.replaceAll("<", "<")
.replaceAll(">", ">")
.replaceAll('"', """)
.replaceAll("'", "'");
}
function formatNumber(value, digits = 3) {
if (!Number.isFinite(value)) return "—";
const absolute = Math.abs(value);
if (absolute !== 0 && (absolute < 0.001 || absolute >= 100000)) {
return value.toExponential(2);
}
return value.toLocaleString(undefined, {
maximumFractionDigits: digits
});
}
function calculate() {
const area = Number(state.area);
const hot = Number(state.hot);
const cold = Number(state.cold);
if (!Number.isFinite(area) || area <= 0) {
return { valid: false, error: "Area must be greater than zero." };
}
if (!Number.isFinite(hot) || !Number.isFinite(cold)) {
return { valid: false, error: "Enter valid hot and cold surface temperatures." };
}
const layers = [];
for (const layer of state.layers) {
const thicknessMm = Number(layer.thicknessMm);
const conductivity = Number(layer.conductivity);
if (!Number.isFinite(thicknessMm) || thicknessMm <= 0) {
return {
valid: false,
error: `Enter a positive thickness for ${layer.name || "the material layer"}.`
};
}
if (!Number.isFinite(conductivity) || conductivity <= 0) {
return {
valid: false,
error: `Enter a positive conductivity for ${layer.name || "the material layer"}.`
};
}
const bulkR = (thicknessMm / 1000) / (conductivity * area);
layers.push({
...layer,
thicknessMm,
conductivity,
bulkR
});
}
const boundaries = state.boundaries.map((boundary) => {
const rc = Number(boundary.rc);
if (!Number.isFinite(rc) || rc < 0) {
return {
...boundary,
rc: 0,
invalid: true,
contribution: 0
};
}
return {
...boundary,
rc,
contribution: rc / area
};
});
if (boundaries.some((boundary) => boundary.invalid)) {
return { valid: false, error: "Interface contact resistance cannot be negative." };
}
const bulkTotal = layers.reduce((sum, layer) => sum + layer.bulkR, 0);
const interfaceTotal = boundaries.reduce(
(sum, boundary) => sum + boundary.contribution,
0
);
const totalR = bulkTotal + interfaceTotal;
if (!Number.isFinite(totalR) || totalR <= 0) {
return { valid: false, error: "The resulting resistance must be greater than zero." };
}
const heatFlow = (hot - cold) / totalR;
const heatFlux = heatFlow / area;
const uValue = 1 / (totalR * area);
const specificResistance = totalR * area;
const nodes = [cold];
let cumulativeR = 0;
const interfaceTemperatures = [];
for (let i = 0; i < layers.length; i++) {
cumulativeR += layers[i].bulkR;
const layerTopTemperature = cold + heatFlow * cumulativeR;
nodes.push(layerTopTemperature);
if (i < boundaries.length) {
cumulativeR += boundaries[i].contribution;
interfaceTemperatures.push(cold + heatFlow * cumulativeR);
nodes.splice(i + 2, 0, interfaceTemperatures[i]);
}
}
return {
valid: true,
area,
hot,
cold,
layers,
boundaries,
bulkTotal,
interfaceTotal,
totalR,
heatFlow,
heatFlux,
uValue,
specificResistance,
nodes
};
}
function renderEditor() {
layerStack.innerHTML = state.layers
.map((layer, index) => {
const upDisabled = index === 0 ? "disabled" : "";
const downDisabled = index === state.layers.length - 1 ? "disabled" : "";
const deleteDisabled = state.layers.length === 1 ? "disabled" : "";
const selected = layer.id === state.selectedLayerId ? "selected" : "";
const boundary =
index < state.boundaries.length
? `
<div class="interface-row">
<div class="interface-content">
<div class="interface-copy">
<strong>Interface ${index + 1}</strong>
<span>Area-normalized contact resistance</span>
<span class="interface-result" data-boundary-result="${state.boundaries[index].id}">
0.000 K/W
</span>
</div>
<div class="field">
<label for="${state.boundaries[index].id}">R″ contact</label>
<div class="input-wrap">
<input
id="${state.boundaries[index].id}"
type="number"
min="0"
step="0.001"
value="${escapeHTML(state.boundaries[index].rc)}"
data-boundary="${state.boundaries[index].id}"
/>
<span class="unit">m²K/W</span>
</div>
</div>
</div>
</div>
`
: "";
return `
<article class="layer-card ${selected}" data-layer-id="${layer.id}">
<div class="layer-head">
<span class="layer-number">${String(index + 1).padStart(2, "0")}</span>
<input
class="color-input"
type="color"
value="${escapeHTML(layer.color)}"
data-field="color"
aria-label="Layer color"
/>
<input
class="name-input"
type="text"
value="${escapeHTML(layer.name)}"
data-field="name"
aria-label="Material name"
/>
<div class="layer-actions">
<button class="icon-button" data-action="up" ${upDisabled} title="Move layer down toward cold side">↓</button>
<button class="icon-button" data-action="down" ${downDisabled} title="Move layer up toward hot side">↑</button>
<button class="icon-button danger" data-action="delete" ${deleteDisabled} title="Remove layer">×</button>
</div>
</div>
<div class="layer-fields">
<div class="field">
<label>Thickness</label>
<div class="input-wrap">
<input
type="number"
min="0.001"
step="0.1"
value="${escapeHTML(layer.thicknessMm)}"
data-field="thicknessMm"
/>
<span class="unit">mm</span>
</div>
</div>
<div class="field">
<label>Conductivity</label>
<div class="input-wrap">
<input
type="number"
min="0.000001"
step="0.001"
value="${escapeHTML(layer.conductivity)}"
data-field="conductivity"
/>
<span class="unit">W/mK</span>
</div>
</div>
<div class="field">
<label>Order</label>
<div class="input-wrap">
<input type="text" value="${index + 1} / ${state.layers.length}" disabled />
</div>
</div>
</div>
<div class="layer-resistance" data-layer-result="${layer.id}">Calculating resistance…</div>
</article>
${boundary}
`;
})
.join("");
updateLayerStats();
}
function updateLayerStats() {
if (!lastCalculation || !lastCalculation.valid) {
$$("[data-layer-result]").forEach((element) => {
element.textContent = "Resistance unavailable";
});
$$("[data-boundary-result]").forEach((element) => {
element.textContent = "0.000 K/W";
});
return;
}
for (const layer of lastCalculation.layers) {
const element = document.querySelector(`[data-layer-result="${layer.id}"]`);
if (element) {
element.textContent =
`Bulk resistance ${formatNumber(layer.bulkR, 4)} K/W` +
` · ${formatNumber(layer.bulkR * lastCalculation.area, 4)} m²K/W`;
}
}
for (const boundary of lastCalculation.boundaries) {
const element = document.querySelector(
`[data-boundary-result="${boundary.id}"]`
);
if (element) {
element.textContent =
boundary.rc === 0
? "Perfect bond · 0.000 K/W"
: `Contribution ${formatNumber(boundary.contribution, 4)} K/W`;
}
}
}
function renderResults(calculation) {
const errorElement = $("#errorMessage");
if (!calculation.valid) {
$("#totalResistance").textContent = "—";
$("#heatFlow").textContent = "—";
$("#heatFlux").textContent = "—";
$("#uValue").textContent = "—";
$("#specificResistance").textContent = "— m²K/W";
$("#bulkLabel").textContent = "Bulk —";
$("#interfaceLabel").textContent = "Interfaces —";
$("#profile").innerHTML = "";
$("#breakdown").innerHTML = "";
$("#temperatureLadder").innerHTML = "";
$("#splitBar").firstElementChild.style.width = "100%";
$("#splitBar").lastElementChild.style.width = "0%";
errorElement.textContent = calculation.error;
errorElement.classList.add("visible");
return;
}
errorElement.classList.remove("visible");
$("#totalResistance").textContent = formatNumber(calculation.totalR, 4);
$("#heatFlow").textContent = formatNumber(calculation.heatFlow, 3);
$("#heatFlux").textContent = formatNumber(calculation.heatFlux, 2);
$("#uValue").textContent = formatNumber(calculation.uValue, 3);
$("#specificResistance").textContent =
`${formatNumber(calculation.specificResistance, 4)} m²K/W`;
$("#flowDirection").textContent =
calculation.heatFlow >= 0 ? "Hot → cold" : "Cold → hot";
const bulkPercent =
calculation.totalR > 0 ? (calculation.bulkTotal / calculation.totalR) * 100 : 0;
const interfacePercent = 100 - bulkPercent;
$("#bulkLabel").textContent =
`Bulk ${formatNumber(calculation.bulkTotal, 3)} K/W · ${bulkPercent.toFixed(1)}%`;
$("#interfaceLabel").textContent =
`Interfaces ${formatNumber(calculation.interfaceTotal, 3)} K/W · ${interfacePercent.toFixed(1)}%`;
$("#splitBar").firstElementChild.style.width = `${bulkPercent}%`;
$("#splitBar").lastElementChild.style.width = `${interfacePercent}%`;
const profile = $("#profile");
profile.innerHTML = "";
calculation.layers.forEach((layer) => {
const segment = document.createElement("div");
segment.className = "profile-segment";
segment.style.flexGrow = Math.max(layer.bulkR, 0.000001);
segment.style.background = layer.color;
segment.title =
`${layer.name}: ${formatNumber(layer.bulkR, 5)} K/W`;
const share = (layer.bulkR / calculation.totalR) * 100;
if (share > 8) {
const label = document.createElement("span");
label.textContent = `${share.toFixed(0)}%`;
segment.appendChild(label);
}
profile.appendChild(segment);
});
calculation.boundaries.forEach((boundary) => {
if (boundary.contribution <= 0) return;
const segment = document.createElement("div");
segment.className = "profile-segment interface";
segment.style.flexGrow = boundary.contribution;
segment.title = `Interface resistance: ${formatNumber(boundary.contribution, 5)} K/W`;
profile.appendChild(segment);
});
const breakdown = $("#breakdown");
breakdown.innerHTML = "";
calculation.layers.forEach((layer) => {
const row = document.createElement("div");
row.className = "breakdown-row";
const swatch = document.createElement("span");
swatch.className = "breakdown-swatch";
swatch.style.background = layer.color;
const name = document.createElement("span");
name.className = "breakdown-name";
name.textContent = layer.name;
const value = document.createElement("span");
value.className = "breakdown-value";
value.textContent = `${formatNumber(layer.bulkR, 3)} K/W`;
row.append(swatch, name, value);
breakdown.appendChild(row);
});
calculation.boundaries.forEach((boundary, index) => {
const row = document.createElement("div");
row.className = "breakdown-row";
const swatch = document.createElement("span");
swatch.className = "breakdown-swatch";
swatch.style.background = boundary.contribution > 0 ? "#f1a14c" : "#c9d0c7";
const name = document.createElement("span");
name.className = "breakdown-name";
name.textContent = `Interface ${index + 1}`;
const value = document.createElement("span");
value.className = "breakdown-value";
value.textContent = `${formatNumber(boundary.contribution, 3)} K/W`;
row.append(swatch, name, value);
breakdown.appendChild(row);
});
const ladder = $("#temperatureLadder");
ladder.innerHTML = "";
const delta = calculation.hot - calculation.cold;
calculation.nodes.forEach((temperature, index) => {
const marker = document.createElement("div");
marker.className = "temp-marker";
const ratio =
Math.abs(delta) < 1e-9
? 0.5
: (temperature - calculation.cold) / delta;
const clamped = Math.max(0, Math.min(1, ratio));
marker.style.bottom = `${clamped * 100}%`;
const label = document.createElement("b");
label.textContent = `${formatNumber(temperature, 1)}°`;
marker.appendChild(label);
ladder.appendChild(marker);
});
}
function disposeGroup(group) {
const doomed = [];
group.traverse((object) => {
if (object.geometry) doomed.push(object.geometry);
if (object.material) {
if (Array.isArray(object.material)) {
object.material.forEach((material) => doomed.push(material));
} else {
doomed.push(object.material);
}
}
});
doomed.forEach((resource) => resource.dispose?.());
group.clear();
}
function rebuildScene(calculation) {
disposeGroup(stackGroup);
disposeGroup(flowGroup);
selectedMeshes = [];
if (!calculation.valid) return;
const layerData = calculation.layers;
const totalThickness = layerData.reduce(
(sum, layer) => sum + layer.thicknessMm,
0
);
let heights = layerData.map((layer) =>
Math.max(0.12, (layer.thicknessMm / totalThickness) * 3.75)
);
const heightSum = heights.reduce((sum, height) => sum + height, 0);
const maximumHeight = 4.35;
if (heightSum > maximumHeight) {
const scale = maximumHeight / heightSum;
heights = heights.map((height) => height * scale);
}
const gap = state.layers.length > 1 ? 0.12 : 0;
const totalHeight = heights.reduce((sum, height) => sum + height, 0) +
gap * Math.max(0, state.layers.length - 1);
let cursorY = -totalHeight / 2;
layerData.forEach((layer, index) => {
const height = heights[index];
const width = 3.45;
const depth = 2.35;
const geometry = new THREE.BoxGeometry(width, height, depth);
const material = new THREE.MeshStandardMaterial({
color: layer.color,
roughness: 0.78,
metalness: 0.03,
flatShading: true
});
const mesh = new THREE.Mesh(geometry, material);
mesh.position.y = cursorY + height / 2;
mesh.castShadow = true;
mesh.receiveShadow = true;
mesh.userData.layerId = layer.id;
const edges = new THREE.LineSegments(
new THREE.EdgesGeometry(geometry),
new THREE.LineBasicMaterial({
color: "#24302e",
transparent: true,
opacity: 0.24
})
);
mesh.add(edges);
stackGroup.add(mesh);
selectedMeshes.push(mesh);
const studGeometry = new THREE.CylinderGeometry(0.038, 0.045, 0.024, 6);
const studMaterial = new THREE.MeshStandardMaterial({
color: "#35413e",
roughness: 0.62,
metalness: 0.35,
flatShading: true
});
const insetX = width * 0.41;
const insetZ = depth * 0.40;
[
[-insetX, -insetZ],
[insetX, -insetZ],
[-insetX, insetZ],
[insetX, insetZ]
].forEach(([x, z]) => {
const stud = new THREE.Mesh(studGeometry, studMaterial);
stud.position.set(x, height / 2 + 0.014, z);
stud.castShadow = true;
stud.userData.layerId = layer.id;
mesh.add(stud);
selectedMeshes.push(stud);
});
cursorY += height + gap;
});
const topY = totalHeight / 2;
const bottomY = -totalHeight / 2;
const hotPlate = new THREE.Mesh(
new THREE.PlaneGeometry(3.85, 2.72),
new THREE.MeshBasicMaterial({
color: "#e26443",
transparent: true,
opacity: 0.15,
side: THREE.DoubleSide,
depthWrite: false
})
);
hotPlate.rotation.x = -Math.PI / 2;
hotPlate.position.y = topY + 0.035;
flowGroup.add(hotPlate);
const coldPlate = new THREE.Mesh(
new THREE.PlaneGeometry(3.85, 2.72),
new THREE.MeshBasicMaterial({
color: "#568eae",
transparent: true,
opacity: 0.15,
side: THREE.DoubleSide,
depthWrite: false
})
);
coldPlate.rotation.x = -Math.PI / 2;
coldPlate.position.y = bottomY - 0.035;
flowGroup.add(coldPlate);
const arrowDirection = calculation.heatFlow >= 0
? new THREE.Vector3(0, -1, 0)
: new THREE.Vector3(0, 1, 0);
const arrowOriginY = calculation.heatFlow >= 0 ? topY : bottomY;
const heatArrow = new THREE.ArrowHelper(
arrowDirection,
new THREE.Vector3(2.35, arrowOriginY, 0),
Math.max(totalHeight, 0.5),
calculation.heatFlow >= 0 ? 0xe26443 : 0x568eae,
0.24,
0.13
);
flowGroup.add(heatArrow);
updatePins(calculation);
updateSelectionVisuals();
}
function updatePins(calculation) {
layerPins.forEach((pin) => pin.element.remove());
layerPins = [];
if (!calculation.valid) return;
const meshes = stackGroup.children.filter(
(child) => child.userData && child.userData.layerId
);
calculation.layers.forEach((layer, index) => {
const mesh = meshes[index];
if (!mesh) return;
const element = document.createElement("button");
element.className = "layer-pin";
element.type = "button";
const title = document.createElement("strong");
title.textContent = layer.name;
const detail = document.createElement("span");
detail.textContent =
`${formatNumber(layer.thicknessMm, 1)} mm · ${formatNumber(layer.bulkR, 3)} K/W`;
element.append(title, detail);
element.addEventListener("click", () => {
selectLayer(layer.id, true);
});
pinsContainer.appendChild(element);
layerPins.push({
element,
position: new THREE.Vector3(1.85, mesh.position.y + 0.08, 0)
});
});
}
function updateOverlayPositions() {
layerPins.forEach((pin) => {
const projected = pin.position.clone().project(camera);
const visible =
projected.z > -1 &&
projected.z < 1 &&
Math.abs(projected.x) < 1.25 &&
Math.abs(projected.y) < 1.25;
pin.element.style.display = visible ? "block" : "none";
if (!visible) return;
const x = (projected.x * 0.5 + 0.5) * viewer.clientWidth;
const y = (-projected.y * 0.5 + 0.5) * viewer.clientHeight;
pin.element.style.transform =
`translate3d(${x}px, ${y}px, 0) translate(-12%, -50%)`;
});
const hotPosition = new THREE.Vector3(-2.0, lastCalculation?.totalHeight ? 2.35 : 2.1, 0);
const coldPosition = new THREE.Vector3(-2.0, lastCalculation?.totalHeight ? -2.35 : -2.1, 0);
[
[hotSurfaceLabel, hotPosition],
[coldSurfaceLabel, coldPosition]
].forEach(([element, position]) => {
const projected = position.clone().project(camera);
const x = (projected.x * 0.5 + 0.5) * viewer.clientWidth;
const y = (-projected.y * 0.5 + 0.5) * viewer.clientHeight;
element.style.transform =
`translate3d(${x}px, ${y}px, 0) translate(-100%, -50%)`;
});
}
function updateSelectionVisuals() {
selectedMeshes.forEach((mesh) => {
const selected = mesh.userData.layerId === state.selectedLayerId;
const material = mesh.material;
if (material && material.isMeshStandardMaterial) {
material.emissive.set(selected ? "#b9d0bf" : "#000000");
material.emissiveIntensity = selected ? 0.16 : 0;
}
});
$$(".layer-card").forEach((card) => {
card.classList.toggle(
"selected",
card.dataset.layerId === state.selectedLayerId
);
});
}
function selectLayer(id, scrollToCard = false) {
state.selectedLayerId = id;
updateSelectionVisuals();
if (scrollToCard) {
const card = document.querySelector(`[data-layer-id="${id}"]`);
card?.scrollIntoView({ behavior: "smooth", block: "nearest" });
}
}
function updateModel() {
lastCalculation = calculate();
renderResults(lastCalculation);
updateLayerStats();
rebuildScene(lastCalculation);
}
function updateCamera() {
const { yaw, pitch, radius, target } = cameraState;
camera.position.set(
target.x + Math.sin(yaw) * Math.cos(pitch) * radius,
target.y + Math.sin(pitch) * radius,
target.z + Math.cos(yaw) * Math.cos(pitch) * radius
);
camera.lookAt(target);
}
function resize() {
const width = viewer.clientWidth;
const height = viewer.clientHeight;
renderer.setSize(width, height, false);
camera.aspect = width / height;
camera.updateProjectionMatrix();
}
new ResizeObserver(resize).observe(viewer);
resize();
updateCamera();
layerStack.addEventListener("input", (event) => {
const target = event.target;
const layerCard = target.closest(".layer-card");
if (layerCard && target.matches("[data-field]")) {
const layer = state.layers.find(
(item) => item.id === layerCard.dataset.layerId
);
if (!layer) return;
const field = target.dataset.field;
layer[field] = field === "name" || field === "color"
? target.value
: target.value;
state.selectedLayerId = layer.id;
updateModel();
return;
}
if (target.matches("[data-boundary]")) {
const boundary = state.boundaries.find(
(item) => item.id === target.dataset.boundary
);
if (!boundary) return;
boundary.rc = target.value;
updateModel();
}
});
layerStack.addEventListener("click", (event) => {
const card = event.target.closest(".layer-card");
if (!card) return;
if (event.target.closest("button, input")) return;
selectLayer(card.dataset.layerId);
});
layerStack.addEventListener("click", (event) => {
const button = event.target.closest("button[data-action]");
if (!button) return;
const card = button.closest(".layer-card");
const index = state.layers.findIndex(
(layer) => layer.id === card.dataset.layerId
);
if (index < 0) return;
const action = button.dataset.action;
if (action === "up" && index > 0) {
[state.layers[index - 1], state.layers[index]] = [
state.layers[index],
state.layers[index - 1]
];
}
if (action === "down" && index < state.layers.length - 1) {
[state.layers[index + 1], state.layers[index]] = [
state.layers[index],
state.layers[index + 1]
];
}
if (action === "delete" && state.layers.length > 1) {
state.layers.splice(index, 1);
if (index < state.boundaries.length) {
state.boundaries.splice(index, 1);
} else if (index > 0) {
state.boundaries.splice(index - 1, 1);
}
if (!state.layers.some((layer) => layer.id === state.selectedLayerId)) {
state.selectedLayerId = state.layers[0].id;
}
}
renderEditor();
updateModel();
});
$("#addLayerButton").addEventListener("click", () => {
const index = state.layers.length;
state.layers.push({
id: uid("layer"),
name: `Material ${index + 1}`,
thicknessMm: 20,
conductivity: 0.5,
color: palette[index % palette.length]
});
state.boundaries.push({
id: uid("boundary"),
rc: 0
});
state.selectedLayerId = state.layers[index].id;
renderEditor();
updateModel();
const card = document.querySelector(
`[data-layer-id="${state.selectedLayerId}"]`
);
card?.scrollIntoView({ behavior: "smooth", block: "nearest" });
card?.querySelector('[data-field="name"]')?.focus();
card?.querySelector('[data-field="name"]')?.select();
});
[
["#areaInput", "area"],
["#hotInput", "hot"],
["#coldInput", "cold"]
].forEach(([selector, property]) => {
$(selector).addEventListener("input", (event) => {
state[property] = event.target.value;
updateModel();
});
});
$("#resetCamera").addEventListener("click", () => {
cameraState.yaw = 0.68;
cameraState.pitch = 0.34;
cameraState.radius = 9.2;
updateCamera();
});
$("#zoomIn").addEventListener("click", () => {
cameraState.radius = Math.max(4.5, cameraState.radius * 0.88);
updateCamera();
});
$("#zoomOut").addEventListener("click", () => {
cameraState.radius = Math.min(18, cameraState.radius * 1.12);
updateCamera();
});
$("#exportButton").addEventListener("click", () => {
const calculation = calculate();
if (!calculation.valid) return;
const rows = [
["Thermal Stack Lab Export"],
["Model", "1D steady state"],
["Area (m2)", calculation.area],
["Hot surface (C)", calculation.hot],
["Cold surface (C)", calculation.cold],
["Total resistance (K/W)", calculation.totalR],
["Bulk resistance (K/W)", calculation.bulkTotal],
["Interface resistance (K/W)", calculation.interfaceTotal],
["Heat flow (W)", calculation.heatFlow],
["Heat flux (W/m2)", calculation.heatFlux],
["U-value (W/m2K)", calculation.uValue],
[],
["Layer", "Thickness (mm)", "Conductivity (W/mK)", "Bulk R (K/W)"]
];
calculation.layers.forEach((layer) => {
rows.push([
layer.name,
layer.thicknessMm,
layer.conductivity,
layer.bulkR
]);
});
rows.push([]);
rows.push([
"Interface",
"Area-normalized contact R (m2K/W)",
"Contribution (K/W)"
]);
calculation.boundaries.forEach((boundary, index) => {
rows.push([
`Interface ${index + 1}`,
boundary.rc,
boundary.contribution
]);
});
const csv = rows
.map((row) =>
row
.map((value) => `"${String(value ?? "").replaceAll('"', '""')}"`)
.join(",")
)
.join("\n");
const blob = new Blob([csv], { type: "text/csv;charset=utf-8" });
const url = URL.createObjectURL(blob);
const link = document.createElement("a");
link.href = url;
link.download = "thermal-stack.csv";
link.click();
URL.revokeObjectURL(url);
});
let dragging = false;
let pointerX = 0;
let pointerY = 0;
let dragDistance = 0;
canvas.addEventListener("pointerdown", (event) => {
if (event.button !== 0) return;
dragging = true;
dragDistance = 0;
pointerX = event.clientX;
pointerY = event.clientY;
canvas.classList.add("dragging");
canvas.setPointerCapture(event.pointerId);
});
canvas.addEventListener("pointermove", (event) => {
if (!dragging) return;
const deltaX = event.clientX - pointerX;
const deltaY = event.clientY - pointerY;
pointerX = event.clientX;
pointerY = event.clientY;
dragDistance += Math.abs(deltaX) + Math.abs(deltaY);
cameraState.yaw -= deltaX * 0.006;
cameraState.pitch = Math.max(
-0.25,
Math.min(1.35, cameraState.pitch + deltaY * 0.005)
);
updateCamera();
});
canvas.addEventListener("pointerup", (event) => {
dragging = false;
canvas.classList.remove("dragging");
if (dragDistance < 5) {
const rect = canvas.getBoundingClientRect();
const pointer = new THREE.Vector2(
((event.clientX - rect.left) / rect.width) * 2 - 1,
-((event.clientY - rect.top) / rect.height) * 2 + 1
);
const raycaster = new THREE.Raycaster();
raycaster.setFromCamera(pointer, camera);
const hits = raycaster.intersectObjects(selectedMeshes, false);
if (hits.length) {
const layerId = hits[0].object.userData.layerId;
if (layerId) selectLayer(layerId, true);
}
}
});
canvas.addEventListener("pointercancel", () => {
dragging = false;
canvas.classList.remove("dragging");
});
canvas.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraState.radius = Math.max(
4.5,
Math.min(18, cameraState.radius * Math.exp(event.deltaY * 0.001))
);
updateCamera();
},
{ passive: false }
);
canvas.addEventListener("dblclick", () => {
cameraState.yaw = 0.68;
cameraState.pitch = 0.34;
cameraState.radius = 9.2;
updateCamera();
});
renderEditor();
updateModel();
function animate() {
requestAnimationFrame(animate);
updateOverlayPositions();
renderer.render(scene, camera);
}
animate();
</script>
</body>
</html>
```