Prompt specification
Build or customize the Three.js 3D scene "Household shopping-budget game" 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: Household shopping-budget game
Category: Architecture & Cities · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/household-shopping-budget-game-x0556
Scene Description Prompt:
Build a self-contained HTML scene with Three.js from cdnjs featuring unit-price comparisons. Create a small market with fixed fictional prices and a shopping list; users choose quantities and packaging while transparent totals track spending, required units, and leftovers. Low-poly.
Working Three.js Starter (household-shopping-budget-game-x0556):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Morning Market — Unit Price Planner</title>
<style>
:root {
--cream: #f5f0e5;
--paper: #fffdf8;
--ink: #24342d;
--muted: #718077;
--line: #dedbcf;
--green: #2e7658;
--green-soft: #e0eee5;
--orange: #d66b42;
--orange-soft: #f8e5da;
--purple: #765a8f;
--shadow: 0 18px 45px rgba(37, 51, 43, 0.12);
}
* {
box-sizing: border-box;
}
html,
body {
margin: 0;
min-height: 100%;
background: var(--cream);
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;
}
.topbar {
height: 72px;
display: flex;
align-items: center;
justify-content: space-between;
padding: 0 28px;
border-bottom: 1px solid rgba(54, 71, 61, 0.12);
background: rgba(255, 253, 248, 0.94);
position: relative;
z-index: 20;
}
.brand {
display: flex;
align-items: center;
gap: 12px;
}
.brand-mark {
width: 38px;
height: 38px;
display: grid;
place-items: center;
border-radius: 12px 12px 12px 4px;
background: var(--green);
color: #fffaf0;
box-shadow: 0 7px 16px rgba(46, 118, 88, 0.22);
}
.brand-mark svg {
width: 23px;
height: 23px;
}
.brand-name {
font-size: 17px;
font-weight: 850;
letter-spacing: -0.03em;
}
.brand-subtitle {
color: var(--muted);
font-size: 11px;
margin-top: 1px;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.topbar-note {
display: flex;
align-items: center;
gap: 9px;
color: var(--muted);
font-size: 12px;
}
.live-dot {
width: 7px;
height: 7px;
border-radius: 50%;
background: var(--green);
box-shadow: 0 0 0 5px var(--green-soft);
}
.app {
height: calc(100vh - 72px);
display: grid;
grid-template-columns: minmax(0, 1fr) 430px;
}
.scene-panel {
min-width: 0;
position: relative;
overflow: hidden;
background:
radial-gradient(circle at 52% 32%, rgba(255, 255, 255, 0.72), transparent 40%),
#e8e5da;
}
#market-canvas {
width: 100%;
height: 100%;
display: block;
touch-action: none;
cursor: grab;
}
#market-canvas:active {
cursor: grabbing;
}
.scene-heading {
position: absolute;
z-index: 5;
top: 26px;
left: 30px;
pointer-events: none;
max-width: 360px;
}
.eyebrow {
color: var(--green);
font-size: 10px;
font-weight: 850;
letter-spacing: 0.17em;
text-transform: uppercase;
}
.scene-heading h1 {
margin: 8px 0 5px;
font-size: clamp(27px, 3vw, 43px);
line-height: 0.98;
letter-spacing: -0.055em;
font-weight: 850;
}
.scene-heading p {
margin: 0;
color: #637069;
font-size: 13px;
line-height: 1.5;
}
.scene-chip {
display: inline-flex;
align-items: center;
gap: 7px;
margin-top: 14px;
padding: 7px 10px;
border: 1px solid rgba(46, 118, 88, 0.16);
border-radius: 999px;
background: rgba(255, 253, 248, 0.76);
backdrop-filter: blur(8px);
color: #4b6256;
font-size: 11px;
font-weight: 700;
}
.scene-chip span {
width: 7px;
height: 7px;
border-radius: 50%;
background: var(--orange);
}
.price-layer {
position: absolute;
inset: 0;
z-index: 6;
pointer-events: none;
}
.price-pin {
position: absolute;
width: 156px;
transform: translate(-50%, -100%);
border: 1px solid rgba(43, 60, 50, 0.12);
border-radius: 13px;
overflow: hidden;
background: rgba(255, 253, 248, 0.94);
box-shadow: 0 10px 25px rgba(45, 57, 50, 0.15);
pointer-events: auto;
transition: border-color 160ms, box-shadow 160ms, opacity 120ms;
backdrop-filter: blur(9px);
}
.price-pin.active {
border-color: rgba(46, 118, 88, 0.65);
box-shadow: 0 12px 30px rgba(46, 118, 88, 0.23);
}
.pin-title {
width: 100%;
display: flex;
align-items: center;
justify-content: space-between;
padding: 8px 10px;
border: 0;
background: var(--green);
color: white;
font-size: 10px;
font-weight: 850;
letter-spacing: 0.08em;
text-transform: uppercase;
cursor: pointer;
}
.pin-title::after {
content: "↗";
opacity: 0.7;
}
.price-option {
width: 100%;
display: grid;
grid-template-columns: 1fr auto;
gap: 2px 8px;
padding: 6px 9px;
border: 0;
border-bottom: 1px solid #ece8df;
background: transparent;
text-align: left;
cursor: pointer;
}
.price-option:last-child {
border-bottom: 0;
}
.price-option:hover,
.price-option.selected {
background: #edf5ef;
}
.price-option strong {
font-size: 11px;
}
.price-option span {
grid-column: 1;
color: var(--muted);
font-size: 9px;
}
.price-option em {
grid-column: 2;
grid-row: 1 / span 2;
align-self: center;
color: var(--green);
font-size: 10px;
font-style: normal;
font-weight: 800;
}
.scene-help {
position: absolute;
z-index: 7;
left: 28px;
bottom: 24px;
display: flex;
align-items: center;
gap: 9px;
padding: 9px 12px;
border: 1px solid rgba(45, 60, 51, 0.1);
border-radius: 999px;
background: rgba(255, 253, 248, 0.84);
color: #637069;
font-size: 11px;
box-shadow: 0 7px 20px rgba(45, 57, 50, 0.08);
backdrop-filter: blur(8px);
pointer-events: none;
}
.mouse-icon {
width: 15px;
height: 20px;
border: 1.5px solid #718077;
border-radius: 8px;
position: relative;
}
.mouse-icon::before {
content: "";
position: absolute;
top: 3px;
left: 5px;
width: 2px;
height: 5px;
border-radius: 2px;
background: #718077;
}
.view-reset {
position: absolute;
z-index: 7;
right: 24px;
bottom: 24px;
border: 1px solid rgba(45, 60, 51, 0.13);
border-radius: 12px;
width: 40px;
height: 40px;
display: grid;
place-items: center;
background: rgba(255, 253, 248, 0.9);
box-shadow: 0 8px 20px rgba(45, 57, 50, 0.1);
cursor: pointer;
backdrop-filter: blur(8px);
}
.view-reset:hover {
background: white;
transform: translateY(-1px);
}
.view-reset svg {
width: 18px;
height: 18px;
}
.sidebar {
min-width: 0;
height: 100%;
overflow-y: auto;
overscroll-behavior: contain;
border-left: 1px solid rgba(54, 71, 61, 0.12);
background: var(--paper);
scrollbar-width: thin;
scrollbar-color: #c8cec8 transparent;
}
.sidebar-section {
padding: 24px 25px;
border-bottom: 1px solid var(--line);
}
.summary-top {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 18px;
}
.summary-top h2 {
margin: 5px 0 0;
font-size: 22px;
letter-spacing: -0.04em;
}
.basket-count {
min-width: 64px;
padding: 9px 10px;
border-radius: 12px;
background: var(--green-soft);
color: var(--green);
text-align: center;
font-size: 11px;
font-weight: 800;
}
.basket-count strong {
display: block;
font-size: 17px;
line-height: 1.1;
}
.spend-row {
display: flex;
align-items: flex-end;
justify-content: space-between;
gap: 16px;
margin-top: 21px;
}
.spend-label {
color: var(--muted);
font-size: 11px;
}
.spend-value {
margin-top: 2px;
font-size: 39px;
line-height: 1;
font-weight: 850;
letter-spacing: -0.055em;
}
.unit-cost {
text-align: right;
}
.unit-cost strong {
display: block;
font-size: 17px;
}
.unit-cost span {
color: var(--muted);
font-size: 10px;
}
.metrics {
display: grid;
grid-template-columns: repeat(2, 1fr);
gap: 8px;
margin-top: 19px;
}
.metric {
min-height: 70px;
padding: 12px;
border: 1px solid #e3e0d7;
border-radius: 13px;
background: #fbfaf5;
}
.metric-label {
color: var(--muted);
font-size: 10px;
font-weight: 700;
}
.metric-value {
margin-top: 7px;
font-size: 21px;
font-weight: 850;
letter-spacing: -0.035em;
}
.metric-note {
margin-top: 2px;
color: #8a948d;
font-size: 9px;
}
.metric.good .metric-value {
color: var(--green);
}
.metric.warn .metric-value {
color: var(--orange);
}
.budget-row {
display: flex;
align-items: center;
justify-content: space-between;
margin-top: 17px;
color: var(--muted);
font-size: 10px;
}
.budget-row strong {
color: var(--ink);
}
.budget-track {
height: 7px;
margin-top: 8px;
overflow: hidden;
border-radius: 999px;
background: #e7e5dc;
}
.budget-fill {
width: 0;
height: 100%;
border-radius: inherit;
background: var(--green);
transition: width 240ms ease, background 180ms ease;
}
.budget-fill.over {
background: var(--orange);
}
.plan-status {
display: flex;
align-items: center;
gap: 8px;
margin-top: 13px;
color: var(--green);
font-size: 11px;
font-weight: 750;
}
.plan-status::before {
content: "";
width: 7px;
height: 7px;
flex: 0 0 auto;
border-radius: 50%;
background: currentColor;
}
.plan-status.shortage {
color: var(--orange);
}
.actions {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
margin-top: 18px;
}
.action-button {
min-height: 38px;
border: 1px solid #d9ddd6;
border-radius: 10px;
background: white;
color: var(--ink);
font-size: 10px;
font-weight: 800;
cursor: pointer;
transition: transform 140ms, border-color 140ms, background 140ms;
}
.action-button:hover {
transform: translateY(-1px);
border-color: #9eb5a8;
background: #f5faf6;
}
.action-button.primary {
border-color: var(--green);
background: var(--green);
color: white;
}
.action-button.primary:hover {
background: #246348;
}
.section-heading {
display: flex;
align-items: flex-end;
justify-content: space-between;
gap: 14px;
margin-bottom: 16px;
}
.section-heading h3 {
margin: 0;
font-size: 17px;
letter-spacing: -0.03em;
}
.section-heading p {
margin: 4px 0 0;
color: var(--muted);
font-size: 10px;
}
.section-count {
color: var(--muted);
font-size: 10px;
white-space: nowrap;
}
.item-list {
display: grid;
gap: 11px;
}
.item-card {
padding: 15px;
border: 1px solid #dfddd4;
border-radius: 16px;
background: white;
transition: border-color 180ms, box-shadow 180ms, transform 180ms;
cursor: pointer;
}
.item-card:hover,
.item-card.active {
border-color: #83a892;
box-shadow: 0 9px 24px rgba(45, 74, 57, 0.09);
transform: translateY(-1px);
}
.item-head {
display: flex;
align-items: center;
gap: 11px;
}
.product-mark {
width: 39px;
height: 39px;
flex: 0 0 auto;
display: grid;
place-items: center;
border-radius: 12px;
color: white;
}
.product-mark svg {
width: 22px;
height: 22px;
}
.item-name {
flex: 1;
min-width: 0;
}
.item-name strong {
display: block;
font-size: 13px;
letter-spacing: -0.02em;
}
.item-name span {
display: block;
margin-top: 3px;
color: var(--muted);
font-size: 10px;
}
.requirement {
flex: 0 0 auto;
padding: 6px 8px;
border-radius: 9px;
background: #f0efe9;
color: #58675e;
font-size: 9px;
font-weight: 800;
text-align: center;
}
.requirement strong {
display: block;
color: var(--ink);
font-size: 13px;
}
.pack-grid {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 6px;
margin-top: 13px;
}
.pack-button {
min-width: 0;
padding: 9px 7px;
border: 1px solid #dedfd8;
border-radius: 10px;
background: #fbfaf7;
text-align: left;
cursor: pointer;
position: relative;
transition: border-color 140ms, background 140ms, transform 140ms;
}
.pack-button:hover {
transform: translateY(-1px);
border-color: #a8b9ad;
}
.pack-button.selected {
border-color: var(--green);
background: var(--green-soft);
box-shadow: inset 0 0 0 1px var(--green);
}
.pack-button strong {
display: block;
font-size: 11px;
white-space: nowrap;
}
.pack-button span {
display: block;
margin-top: 3px;
color: var(--muted);
font-size: 9px;
white-space: nowrap;
}
.pack-button em {
display: block;
margin-top: 5px;
color: var(--green);
font-size: 9px;
font-style: normal;
font-weight: 850;
white-space: nowrap;
}
.best-tag {
position: absolute;
top: -6px;
right: 5px;
padding: 2px 4px;
border-radius: 5px;
background: var(--orange);
color: white;
font-size: 6px;
font-style: normal;
font-weight: 900;
letter-spacing: 0.06em;
text-transform: uppercase;
}
.quantity-row {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
margin-top: 13px;
padding-top: 12px;
border-top: 1px solid #eceae3;
}
.quantity-label {
color: var(--muted);
font-size: 10px;
}
.stepper {
display: flex;
align-items: center;
overflow: hidden;
border: 1px solid #d8dbd5;
border-radius: 9px;
background: #fbfaf6;
}
.stepper button {
width: 29px;
height: 28px;
border: 0;
background: transparent;
cursor: pointer;
font-size: 16px;
}
.stepper button:hover {
background: #e6efe8;
}
.stepper input {
width: 43px;
height: 28px;
padding: 0;
border: 0;
border-left: 1px solid #e1e2dc;
border-right: 1px solid #e1e2dc;
outline: 0;
background: white;
color: var(--ink);
text-align: center;
font-size: 11px;
font-weight: 800;
appearance: textfield;
}
.stepper input::-webkit-inner-spin-button,
.stepper input::-webkit-outer-spin-button {
appearance: none;
margin: 0;
}
.item-result {
display: flex;
justify-content: space-between;
gap: 10px;
margin-top: 10px;
color: var(--muted);
font-size: 9px;
}
.item-result strong {
color: var(--ink);
}
.item-result .over {
color: var(--orange);
}
.item-result .short {
color: #aa4f36;
}
.receipt {
width: 100%;
border-collapse: collapse;
font-size: 10px;
}
.receipt th {
padding: 0 0 9px;
color: #8a948d;
font-size: 8px;
font-weight: 800;
letter-spacing: 0.08em;
text-align: right;
text-transform: uppercase;
}
.receipt th:first-child,
.receipt td:first-child {
text-align: left;
}
.receipt td {
padding: 10px 0;
border-top: 1px solid #ebe8df;
text-align: right;
vertical-align: top;
}
.receipt td:first-child {
font-weight: 750;
}
.receipt small {
display: block;
margin-top: 2px;
color: var(--muted);
font-size: 8px;
font-weight: 400;
}
.receipt-total {
display: flex;
justify-content: space-between;
margin-top: 12px;
padding-top: 13px;
border-top: 2px solid var(--ink);
font-size: 13px;
font-weight: 850;
}
.fine-print {
margin: 13px 0 0;
color: #8a948d;
font-size: 9px;
line-height: 1.55;
}
@media (max-width: 980px) {
body {
overflow: auto;
}
.app {
height: auto;
display: block;
}
.scene-panel {
height: 62vh;
min-height: 470px;
}
.sidebar {
height: auto;
overflow: visible;
border-left: 0;
border-top: 1px solid var(--line);
}
}
@media (max-width: 600px) {
.topbar {
height: 64px;
padding: 0 16px;
}
.brand-subtitle,
.topbar-note {
display: none;
}
.app {
min-height: calc(100vh - 64px);
}
.scene-panel {
height: 54vh;
min-height: 410px;
}
.scene-heading {
top: 18px;
left: 18px;
}
.scene-heading h1 {
font-size: 29px;
}
.scene-heading p {
max-width: 260px;
font-size: 11px;
}
.price-layer {
display: none;
}
.scene-help {
left: 16px;
bottom: 16px;
}
.view-reset {
right: 16px;
bottom: 16px;
}
.sidebar-section {
padding: 22px 17px;
}
.pack-grid {
gap: 4px;
}
.pack-button {
padding: 9px 5px;
}
}
</style>
</head>
<body>
<header class="topbar">
<div class="brand">
<div class="brand-mark" aria-hidden="true">
<svg viewBox="0 0 24 24" fill="none">
<path d="M4 9h16l-1.5 10h-13L4 9Z" stroke="currentColor" stroke-width="1.8"/>
<path d="M8 10 11 3m5 7L13 3M8 14h8" stroke="currentColor" stroke-width="1.8" stroke-linecap="round"/>
</svg>
</div>
<div>
<div class="brand-name">Morning Market</div>
<div class="brand-subtitle">Pantry value planner</div>
</div>
</div>
<div class="topbar-note">
<span class="live-dot"></span>
Three local vendors · fictional prices
</div>
</header>
<main class="app">
<section class="scene-panel" id="scene-panel" aria-label="Interactive low-poly market">
<canvas id="market-canvas"></canvas>
<div class="scene-heading">
<div class="eyebrow">Saturday pantry market</div>
<h1>Small market.<br />Clearer value.</h1>
<p>Compare package rates, build your basket, and see exactly what remains.</p>
<div class="scene-chip"><span></span>47 portions required</div>
</div>
<div class="price-layer" id="price-layer"></div>
<div class="scene-help">
<span class="mouse-icon" aria-hidden="true"></span>
Drag to orbit · scroll to zoom · click a stall
</div>
<button class="view-reset" id="view-reset" aria-label="Reset camera view" title="Reset camera view">
<svg viewBox="0 0 24 24" fill="none" aria-hidden="true">
<path d="M4 4v6h6M5.5 15.5a8 8 0 1 0 .3-8.3L4 10" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"/>
</svg>
</button>
</section>
<aside class="sidebar" aria-label="Shopping planner">
<section class="sidebar-section">
<div class="summary-top">
<div>
<div class="eyebrow">Your market basket</div>
<h2>Pantry plan</h2>
</div>
<div class="basket-count">
<strong id="package-count">3</strong>
packages
</div>
</div>
<div class="spend-row">
<div>
<div class="spend-label">Total spending</div>
<div class="spend-value" id="total-spend">$32.00</div>
</div>
<div class="unit-cost">
<strong id="weighted-rate">$0.68</strong>
<span>per bought portion</span>
</div>
</div>
<div class="metrics">
<div class="metric">
<div class="metric-label">Required</div>
<div class="metric-value" id="required-total">47</div>
<div class="metric-note">planned portions</div>
</div>
<div class="metric good">
<div class="metric-label">Buying</div>
<div class="metric-value" id="bought-total">47</div>
<div class="metric-note">from selected packs</div>
</div>
<div class="metric" id="leftover-metric">
<div class="metric-label">Leftovers</div>
<div class="metric-value" id="leftover-total">0</div>
<div class="metric-note">extra portions</div>
</div>
<div class="metric" id="short-metric">
<div class="metric-label">Short by</div>
<div class="metric-value" id="short-total">0</div>
<div class="metric-note">still needed</div>
</div>
</div>
<div class="budget-row">
<span>Basket cap <strong>$60.00</strong></span>
<span id="budget-label">$32.00 spent</span>
</div>
<div class="budget-track">
<div class="budget-fill" id="budget-fill"></div>
</div>
<div class="plan-status" id="plan-status">Your list is exactly covered</div>
<div class="actions">
<button class="action-button" id="reset-plan">Reset plan</button>
<button class="action-button primary" id="best-rates" title="Selects the lowest price per portion; may create leftovers">
Best unit rates
</button>
</div>
</section>
<section class="sidebar-section">
<div class="section-heading">
<div>
<h3>Shopping list</h3>
<p>Choose a package, then set how many.</p>
</div>
<div class="section-count">3 required items</div>
</div>
<div class="item-list" id="item-list"></div>
</section>
<section class="sidebar-section">
<div class="section-heading">
<div>
<h3>Transparent receipt</h3>
<p>Every portion and leftover accounted for.</p>
</div>
</div>
<table class="receipt">
<thead>
<tr>
<th>Item</th>
<th>Buy</th>
<th>Cost</th>
<th>Left</th>
</tr>
</thead>
<tbody id="receipt-body"></tbody>
</table>
<div class="receipt-total">
<span>Basket total</span>
<span id="receipt-total">$32.00</span>
</div>
<p class="fine-print">
One brew or meal is counted as one portion for the combined totals.
All prices, package sizes, and the $60 basket cap are fictional.
“Best unit rates” chooses the lowest price per portion and may leave extras.
</p>
</section>
</aside>
</main>
<script type="module">
import * as THREE from "https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
/* ---------------------------------------------------------
Shopping data
--------------------------------------------------------- */
const products = [
{
id: "tea",
name: "Hilltop Tea",
shortName: "Hilltop",
unit: "brews",
required: 12,
color: "#d66b42",
mark: `
<svg viewBox="0 0 24 24" fill="none" aria-hidden="true">
<path d="M18.5 4.5C12 4 6.5 7.4 6 13.2c-.3 3.2 2.1 5.5 5.1 5.3 5.7-.4 8.4-6.5 7.4-14Z" fill="currentColor" opacity=".95"/>
<path d="M5 20c2.5-5 6.4-8.6 11.5-11.3" stroke="white" stroke-width="1.4" stroke-linecap="round"/>
</svg>`,
packages: [
{ label: "5-brew pouch", units: 5, price: 3.50 },
{ label: "12-brew box", units: 12, price: 6.00 },
{ label: "24-brew box", units: 24, price: 10.80 }
],
selected: 1,
qty: 1
},
{
id: "rice",
name: "Sunfield Rice",
shortName: "Sunfield",
unit: "meals",
required: 20,
color: "#397966",
mark: `
<svg viewBox="0 0 24 24" fill="none" aria-hidden="true">
<ellipse cx="12" cy="12" rx="5.4" ry="9" transform="rotate(35 12 12)" fill="currentColor"/>
<path d="M9 17c1.6-3.2 3.8-5.7 6.8-7.5" stroke="white" stroke-width="1.2" stroke-linecap="round" opacity=".8"/>
</svg>`,
packages: [
{ label: "10-meal sack", units: 10, price: 8.00 },
{ label: "20-meal sack", units: 20, price: 14.00 },
{ label: "40-meal sack", units: 40, price: 24.00 }
],
selected: 1,
qty: 1
},
{
id: "lentils",
name: "Copper Pot Lentils",
shortName: "Copper Pot",
unit: "meals",
required: 15,
color: "#765a8f",
mark: `
<svg viewBox="0 0 24 24" fill="none" aria-hidden="true">
<circle cx="8" cy="9" r="4" fill="currentColor"/>
<circle cx="16" cy="8" r="4" fill="currentColor" opacity=".9"/>
<circle cx="12" cy="16" r="4" fill="currentColor" opacity=".8"/>
</svg>`,
packages: [
{ label: "5-meal pouch", units: 5, price: 4.50 },
{ label: "15-meal pouch", units: 15, price: 12.00 },
{ label: "30-meal sack", units: 30, price: 20.00 }
],
selected: 1,
qty: 1
}
];
const budget = 60;
const currency = new Intl.NumberFormat("en-US", {
style: "currency",
currency: "USD"
});
const rate = (pack) => pack.price / pack.units;
const bestPackIndex = (product) => {
let best = 0;
product.packages.forEach((pack, index) => {
if (rate(pack) < rate(product.packages[best])) best = index;
});
return best;
};
/* ---------------------------------------------------------
Build shopping controls
--------------------------------------------------------- */
const itemList = document.querySelector("#item-list");
const priceLayer = document.querySelector("#price-layer");
function buildShoppingUI() {
for (const product of products) {
const card = document.createElement("article");
card.className = "item-card";
card.id = `item-${product.id}`;
card.dataset.product = product.id;
card.tabIndex = 0;
const packButtons = product.packages.map((pack, index) => {
const best = index === bestPackIndex(product);
return `
<button class="pack-button" data-pack="${index}"
aria-label="${pack.label}, ${currency.format(pack.price)}, ${currency.format(rate(pack))} per ${product.unit.replace(/s$/, "")}">
${best ? '<span class="best-tag">Best rate</span>' : ""}
<strong>${pack.units} ${product.unit}</strong>
<span>${currency.format(pack.price)}</span>
<em>${currency.format(rate(pack))} each</em>
</button>`;
}).join("");
card.innerHTML = `
<div class="item-head">
<div class="product-mark" style="background:${product.color}">${product.mark}</div>
<div class="item-name">
<strong>${product.name}</strong>
<span>${product.packages[product.selected].label}</span>
</div>
<div class="requirement">
NEED<strong>${product.required}</strong>
</div>
</div>
<div class="pack-grid">${packButtons}</div>
<div class="quantity-row">
<span class="quantity-label">Number of packages</span>
<div class="stepper">
<button data-step="-1" aria-label="Remove one package">−</button>
<input type="number" min="0" max="30" value="${product.qty}" aria-label="${product.name} package quantity">
<button data-step="1" aria-label="Add one package">+</button>
</div>
</div>
<div class="item-result"></div>
`;
card.addEventListener("click", (event) => {
const packButton = event.target.closest("[data-pack]");
if (packButton) {
product.selected = Number(packButton.dataset.pack);
setActiveProduct(product.id);
updateAll();
return;
}
const stepButton = event.target.closest("[data-step]");
if (stepButton) {
product.qty = clamp(product.qty + Number(stepButton.dataset.step), 0, 30);
updateAll();
return;
}
if (!event.target.closest("input")) setActiveProduct(product.id);
});
card.addEventListener("keydown", (event) => {
if (event.key === "Enter" || event.key === " ") {
event.preventDefault();
setActiveProduct(product.id);
}
});
card.querySelector("input").addEventListener("input", (event) => {
const value = Number(event.target.value);
product.qty = Number.isFinite(value) ? clamp(value, 0, 30) : 0;
updateAll();
});
card.querySelector("input").addEventListener("blur", (event) => {
event.target.value = product.qty;
});
itemList.appendChild(card);
}
}
function buildPricePins() {
for (const product of products) {
const pin = document.createElement("div");
pin.className = "price-pin";
pin.dataset.product = product.id;
const options = product.packages.map((pack, index) => {
const best = index === bestPackIndex(product);
return `
<button class="price-option" data-pack="${index}" title="Select ${pack.label}">
<strong>${currency.format(pack.price)}</strong>
<span>${pack.units} ${product.unit}${best ? " · best rate" : ""}</span>
<em>${currency.format(rate(pack))}</em>
</button>`;
}).join("");
pin.innerHTML = `
<button class="pin-title">${product.shortName}</button>
${options}
`;
pin.addEventListener("click", (event) => {
const packButton = event.target.closest("[data-pack]");
if (packButton) {
product.selected = Number(packButton.dataset.pack);
}
setActiveProduct(product.id);
updateAll();
});
priceLayer.appendChild(pin);
}
}
function clamp(value, min, max) {
return Math.min(max, Math.max(min, value));
}
/* ---------------------------------------------------------
Totals and UI synchronization
--------------------------------------------------------- */
let activeProductId = products[0].id;
function calculateTotals() {
let spend = 0;
let required = 0;
let bought = 0;
let leftover = 0;
let shortage = 0;
let packageCount = 0;
const rows = products.map((product) => {
const pack = product.packages[product.selected];
const units = pack.units * product.qty;
const cost = pack.price * product.qty;
const itemLeftover = Math.max(0, units - product.required);
const itemShortage = Math.max(0, product.required - units);
spend += cost;
required += product.required;
bought += units;
leftover += itemLeftover;
shortage += itemShortage;
packageCount += product.qty;
return {
product,
pack,
units,
cost,
itemLeftover,
itemShortage
};
});
return {
spend,
required,
bought,
leftover,
shortage,
packageCount,
rows,
weightedRate: bought ? spend / bought : 0
};
}
function updateAll() {
const totals = calculateTotals();
document.querySelector("#total-spend").textContent = currency.format(totals.spend);
document.querySelector("#weighted-rate").textContent = currency.format(totals.weightedRate);
document.querySelector("#package-count").textContent = totals.packageCount;
document.querySelector("#required-total").textContent = totals.required;
document.querySelector("#bought-total").textContent = totals.bought;
document.querySelector("#leftover-total").textContent = totals.leftover;
document.querySelector("#short-total").textContent = totals.shortage;
document.querySelector("#receipt-total").textContent = currency.format(totals.spend);
const leftoverMetric = document.querySelector("#leftover-metric");
leftoverMetric.classList.toggle("good", totals.leftover === 0);
leftoverMetric.classList.toggle("warn", totals.leftover > 0);
const shortMetric = document.querySelector("#short-metric");
shortMetric.classList.toggle("warn", totals.shortage > 0);
const budgetFill = document.querySelector("#budget-fill");
budgetFill.style.width = `${Math.min(100, (totals.spend / budget) * 100)}%`;
budgetFill.classList.toggle("over", totals.spend > budget);
document.querySelector("#budget-label").textContent =
`${currency.format(totals.spend)} spent${totals.spend > budget ? " · over cap" : ""}`;
const status = document.querySelector("#plan-status");
status.classList.toggle("shortage", totals.shortage > 0);
if (totals.shortage > 0) {
status.textContent = `Still short ${totals.shortage} portion${totals.shortage === 1 ? "" : "s"}`;
} else if (totals.leftover > 0) {
status.textContent = `${totals.leftover} portion${totals.leftover === 1 ? "" : "s"} will remain`;
} else {
status.textContent = "Your list is exactly covered";
}
for (const product of products) {
const card = document.querySelector(`#item-${product.id}`);
const pack = product.packages[product.selected];
card.querySelectorAll(".pack-button").forEach((button) => {
const selected = Number(button.dataset.pack) === product.selected;
button.classList.toggle("selected", selected);
button.setAttribute("aria-pressed", String(selected));
});
card.querySelector(".item-name span").textContent = pack.label;
const quantityInput = card.querySelector("input");
if (document.activeElement !== quantityInput) quantityInput.value = product.qty;
const bought = pack.units * product.qty;
const itemLeftover = Math.max(0, bought - product.required);
const itemShortage = Math.max(0, product.required - bought);
const result = card.querySelector(".item-result");
result.innerHTML = `
<span>
Buying <strong>${bought} ${product.unit}</strong> ·
${currency.format(pack.price * product.qty)}
</span>
<span class="${itemShortage ? "short" : itemLeftover ? "over" : ""}">
${
itemShortage
? `Short ${itemShortage}`
: itemLeftover
? `${itemLeftover} leftover`
: "Exact fit"
}
</span>
`;
}
document.querySelector("#receipt-body").innerHTML = totals.rows.map(({ product, pack, units, cost, itemLeftover }) => `
<tr>
<td>
${product.name}
<small>${pack.units} ${product.unit}/pack</small>
</td>
<td>${units}<small>${product.unit}</small></td>
<td>${currency.format(cost)}<small>${currency.format(rate(pack))}/unit</small></td>
<td>${itemLeftover}<small>${itemLeftover ? "extra" : "exact"}</small></td>
</tr>
`).join("");
document.querySelectorAll(".price-pin").forEach((pin) => {
const product = products.find((item) => item.id === pin.dataset.product);
pin.classList.toggle("active", product.id === activeProductId);
pin.querySelectorAll(".price-option").forEach((button) => {
button.classList.toggle(
"selected",
Number(button.dataset.pack) === product.selected
);
});
});
updateActiveMarker();
}
function setActiveProduct(id) {
activeProductId = id;
document.querySelectorAll(".item-card").forEach((card) => {
card.classList.toggle("active", card.dataset.product === id);
});
updateActiveMarker();
}
document.querySelector("#reset-plan").addEventListener("click", () => {
for (const product of products) {
product.selected = product.id === "tea" ? 1 : product.id === "rice" ? 1 : 1;
product.qty = 1;
}
setActiveProduct(products[0].id);
updateAll();
});
document.querySelector("#best-rates").addEventListener("click", () => {
for (const product of products) {
product.selected = bestPackIndex(product);
product.qty = Math.max(1, Math.ceil(product.required / product.packages[product.selected].units));
}
updateAll();
});
buildShoppingUI();
buildPricePins();
/* ---------------------------------------------------------
Three.js scene
--------------------------------------------------------- */
const canvas = document.querySelector("#market-canvas");
const scenePanel = document.querySelector("#scene-panel");
const renderer = new THREE.WebGLRenderer({
canvas,
antialias: true,
alpha: false,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
const scene = new THREE.Scene();
scene.background = new THREE.Color("#e8e5da");
scene.fog = new THREE.Fog("#e8e5da", 22, 43);
const camera = new THREE.PerspectiveCamera(42, 1, 0.1, 100);
const cameraState = {
yaw: 0.54,
pitch: 0.48,
radius: 15.8,
target: new THREE.Vector3(0, 1.1, 0)
};
const hemi = new THREE.HemisphereLight("#fff8e9", "#738879", 2.0);
scene.add(hemi);
const sun = new THREE.DirectionalLight("#fff2d6", 3.1);
sun.position.set(8, 13, 9);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -12;
sun.shadow.camera.right = 12;
sun.shadow.camera.top = 12;
sun.shadow.camera.bottom = -12;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 35;
sun.shadow.bias = -0.0008;
scene.add(sun);
const fillLight = new THREE.DirectionalLight("#bcd8dc", 1.0);
fillLight.position.set(-9, 7, -5);
scene.add(fillLight);
const material = (color, extra = {}) => new THREE.MeshStandardMaterial({
color,
roughness: 0.83,
metalness: 0,
flatShading: true,
...extra
});
const mats = {
ground: material("#d8d8ca"),
platform: material("#c8b796"),
platformTop: material("#dfd2b8"),
path: material("#e6ddc8"),
wood: material("#8b6748"),
woodLight: material("#b68b61"),
darkWood: material("#5f4939"),
cream: material("#fff3d8"),
green: material("#2e7658"),
orange: material("#d66b42"),
purple: material("#765a8f"),
teal: material("#397966"),
dark: material("#33433d")
};
function box(parent, size, position, mat, rotation = null) {
const mesh = new THREE.Mesh(
new THREE.BoxGeometry(size[0], size[1], size[2]),
mat
);
mesh.position.set(position[0], position[1], position[2]);
if (rotation) mesh.rotation.set(rotation[0], rotation[1], rotation[2]);
mesh.castShadow = true;
mesh.receiveShadow = true;
parent.add(mesh);
return mesh;
}
function cylinder(parent, radiusTop, radiusBottom, height, position, mat, sides = 8) {
const mesh = new THREE.Mesh(
new THREE.CylinderGeometry(radiusTop, radiusBottom, height, sides),
mat
);
mesh.position.set(position[0], position[1], position[2]);
mesh.castShadow = true;
mesh.receiveShadow = true;
parent.add(mesh);
return mesh;
}
function makeSignTexture(text, background, foreground) {
const signCanvas = document.createElement("canvas");
signCanvas.width = 512;
signCanvas.height = 128;
const ctx = signCanvas.getContext("2d");
ctx.fillStyle = background;
ctx.fillRect(0, 0, 512, 128);
ctx.strokeStyle = "rgba(255,255,255,.22)";
ctx.lineWidth = 8;
ctx.strokeRect(12, 12, 488, 104);
ctx.fillStyle = foreground;
ctx.font = "800 48px system-ui, sans-serif";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillText(text.toUpperCase(), 256, 67);
const texture = new THREE.CanvasTexture(signCanvas);
texture.colorSpace = THREE.SRGBColorSpace;
texture.anisotropy = renderer.capabilities.getMaxAnisotropy();
return texture;
}
function makeTree(x, z, scale = 1) {
const group = new THREE.Group();
group.position.set(x, 0, z);
group.scale.setScalar(scale);
cylinder(group, 0.18, 0.25, 1.7, [0, 0.85, 0], material("#70503a"), 7);
const crown = new THREE.Mesh(
new THREE.DodecahedronGeometry(1.0, 0),
material("#668b67")
);
crown.position.y = 2.25;
crown.scale.set(0.9, 1.15, 0.9);
crown.castShadow = true;
group.add(crown);
const crown2 = new THREE.Mesh(
new THREE.IcosahedronGeometry(0.72, 0),
material("#7b9b70")
);
crown2.position.set(0.48, 2.45, 0.12);
crown2.castShadow = true;
group.add(crown2);
scene.add(group);
return group;
}
function makeCrate(parent, x, y, z, color) {
const group = new THREE.Group();
group.position.set(x, y, z);
box(group, [1.1, 0.12, 0.8], [0, 0, 0], material(color));
box(group, [1.1, 0.28, 0.08], [0, 0.12, 0.37], material(color));
box(group, [1.1, 0.28, 0.08], [0, 0.12, -0.37], material(color));
box(group, [0.08, 0.28, 0.8], [-0.51, 0.12, 0], material(color));
box(group, [0.08, 0.28, 0.8], [0.51, 0.12, 0], material(color));
parent.add(group);
return group;
}
function makeStall(product, x, z) {
const group = new THREE.Group();
group.position.set(x, 0, z);
const accent = product.id === "tea" ? mats.orange :
product.id === "rice" ? mats.teal : mats.purple;
// Counter and back wall.
box(group, [3.35, 1.05, 1.3], [0, 0.58, 0.25], mats.wood);
box(group, [3.5, 0.16, 1.55], [0, 1.18, 0.28], mats.woodLight);
box(group, [3.25, 2.15, 0.14], [0, 1.58, -0.68], mats.cream);
box(group, [3.25, 0.18, 0.12], [0, 0.55, -0.58], accent);
// Counter front panels.
for (let i = -1; i <= 1; i++) {
box(group, [0.94, 0.63, 0.08], [i * 1.02, 0.64, 0.93], mats.darkWood);
box(group, [0.8, 0.48, 0.04], [i * 1.02, 0.64, 0.98], accent);
}
// Support posts.
for (const px of [-1.52, 1.52]) {
for (const pz of [-0.72, 1.05]) {
box(group, [0.12, 2.55, 0.12], [px, 1.72, pz], mats.darkWood);
}
}
// Striped awning.
const stripeWidth = 0.49;
for (let i = 0; i < 7; i++) {
const stripeMat = i % 2 === 0 ? accent : mats.cream;
const stripe = box(
group,
[stripeWidth, 0.13, 2.5],
[-1.47 + i * stripeWidth, 3.05, 0.18],
stripeMat,
[-0.035, 0, 0]
);
stripe.material = stripeMat.clone();
stripe.material.side = THREE.DoubleSide;
}
// Front valance.
for (let i = 0; i < 7; i++) {
box(
group,
[stripeWidth, 0.25, 0.08],
[-1.47 + i * stripeWidth, 2.88, 1.4],
i % 2 === 0 ? accent : mats.cream
);
}
// Vendor sign.
const signTexture = makeSignTexture(product.name, `#${product.color.slice(1)}`, "#fffaf0");
const sign = new THREE.Mesh(
new THREE.PlaneGeometry(2.55, 0.62),
new THREE.MeshBasicMaterial({ map: signTexture })
);
sign.position.set(0, 3.62, 1.03);
group.add(sign);
// Small hanging sign frame.
box(group, [2.7, 0.07, 0.12], [0, 3.94, 1.02], mats.darkWood);
// Product displays.
if (product.id === "tea") {
for (let i = 0; i < 7; i++) {
const packet = box(
group,
[0.2, 0.48, 0.08],
[-0.95 + i * 0.31, 1.51, 0.42],
i % 2 ? mats.orange : mats.cream
);
packet.rotation.z = (i % 2 ? 1 : -1) * 0.08;
}
const bowl = new THREE.Mesh(
new THREE.CylinderGeometry(0.34, 0.22, 0.18, 10),
mats.green
);
bowl.position.set(0.95, 1.43, 0.48);
bowl.castShadow = true;
group.add(bowl);
}
if (product.id === "rice") {
for (let i = 0; i < 3; i++) {
const sack = new THREE.Mesh(
new THREE.DodecahedronGeometry(0.42, 0),
material("#e5d7b8")
);
sack.position.set(-0.8 + i * 0.78, 1.61, 0.45);
sack.scale.set(0.85, 1.15, 0.8);
sack.castShadow = true;
group.add(sack);
const tie = cylinder(
group,
0.16,
0.16,
0.12,
[-0.8 + i * 0.78, 2.0, 0.45],
mats.teal,
8
);
tie.rotation.z = 0.12;
}
}
if (product.id === "lentils") {
const crate = makeCrate(group, 0, 1.28, 0.48, "#8a6548");
for (let i = 0; i < 16; i++) {
const lentil = new THREE.Mesh(
new THREE.IcosahedronGeometry(0.1, 0),
material(i % 3 === 0 ? "#c58b43" : "#a86e35")
);
lentil.position.set(
-0.38 + (i % 5) * 0.19,
0.18 + Math.floor(i / 10) * 0.08,
-0.18 + Math.floor((i % 10) / 5) * 0.25
);
lentil.scale.y = 0.55;
lentil.castShadow = true;
crate.add(lentil);
}
}
// Invisible raycast target.
const hitBox = new THREE.Mesh(
new THREE.BoxGeometry(3.5, 3.8, 2.7),
new THREE.MeshBasicMaterial({
transparent: true,
opacity: 0,
depthWrite: false
})
);
hitBox.position.set(0, 1.8, 0.3);
hitBox.userData.productId = product.id;
group.add(hitBox);
scene.add(group);
return { group, hitBox };
}
// Ground and market platform.
const ground = new THREE.Mesh(new THREE.PlaneGeometry(120, 120), mats.ground);
ground.rotation.x = -Math.PI / 2;
ground.position.y = -0.56;
ground.receiveShadow = true;
scene.add(ground);
box(scene, [13.7, 0.55, 8.5], [0, -0.28, -0.35], mats.platform);
box(scene, [13.45, 0.08, 8.25], [0, 0.015, -0.35], mats.platformTop);
// Walkways.
box(scene, [12.8, 0.06, 2.2], [0, 0.08, 2.05], mats.path);
box(scene, [2.0, 0.055, 5.6], [0, 0.075, 0.15], mats.path);
box(scene, [13.0, 0.05, 0.48], [0, 0.085, -2.85], mats.path);
// Decorative paving.
for (let row = 0; row < 2; row++) {
for (let i = 0; i < 11; i++) {
const tile = box(
scene,
[0.82, 0.025, 0.72],
[-5.4 + i * 1.08, 0.12, 1.38 + row * 1.0],
i % 2 ? material("#d9cfb8") : material("#eee3ce")
);
tile.rotation.y = ((i + row) % 2 ? 1 : -1) * 0.015;
}
}
const stallData = [
{ product: products[0], x: -4.15, z: -1.45 },
{ product: products[1], x: 0, z: -1.45 },
{ product: products[2], x: 4.15, z: -1.45 }
];
const hitTargets = [];
const stallPositions = [];
stallData.forEach(({ product, x, z }) => {
const stall = makeStall(product, x, z);
hitTargets.push(stall.hitBox);
stallPositions.push(new THREE.Vector3(x, 4.05, z + 1.1));
});
makeTree(-6.0, -3.2, 1.12);
makeTree(6.0, -3.1, 1.05);
makeTree(-5.9, 3.0, 0.72);
makeTree(6.1, 3.1, 0.74);
// Low-poly shoppers.
function makePerson(shirtColor, skinColor, bagColor) {
const group = new THREE.Group();
const shirt = material(shirtColor);
const skin = material(skinColor);
const trousers = material("#394c46");
const body = new THREE.Mesh(
new THREE.CylinderGeometry(0.22, 0.31, 0.72, 7),
shirt
);
body.position.y = 0.96;
body.castShadow = true;
group.add(body);
const head = new THREE.Mesh(
new THREE.IcosahedronGeometry(0.23, 1),
skin
);
head.position.y = 1.52;
head.castShadow = true;
group.add(head);
box(group, [0.14, 0.52, 0.15], [-0.13, 0.38, 0], trousers);
box(group, [0.14, 0.52, 0.15], [0.13, 0.38, 0], trousers);
box(group, [0.13, 0.55, 0.14], [-0.31, 0.98, 0], shirt);
box(group, [0.13, 0.55, 0.14], [0.31, 0.98, 0], shirt);
box(group, [0.27, 0.32, 0.16], [0.4, 0.58, 0], material(bagColor));
box(group, [0.12, 0.24, 0.04], [0.4, 0.82, 0], material(bagColor));
scene.add(group);
return group;
}
const shopperA = makePerson("#d66b42", "#b87952", "#e5c58b");
const shopperB = makePerson("#765a8f", "#8f5c42", "#9eb5a0");
// Active stall marker.
const activeMarker = new THREE.Mesh(
new THREE.RingGeometry(1.72, 1.82, 48),
new THREE.MeshBasicMaterial({
color: "#2e7658",
transparent: true,
opacity: 0.62,
side: THREE.DoubleSide
})
);
activeMarker.rotation.x = -Math.PI / 2;
activeMarker.position.y = 0.14;
scene.add(activeMarker);
function updateActiveMarker() {
const product = products.find((item) => item.id === activeProductId);
const index = products.indexOf(product);
activeMarker.position.x = stallPositions[index].x;
activeMarker.position.z = stallData[index].z + 0.15;
}
/* ---------------------------------------------------------
Direct camera controls — no addons
--------------------------------------------------------- */
function updateCamera() {
const { yaw, pitch, radius, target } = cameraState;
const horizontal = Math.cos(pitch) * radius;
camera.position.set(
target.x + Math.sin(yaw) * horizontal,
target.y + Math.sin(pitch) * radius,
target.z + Math.cos(yaw) * horizontal
);
camera.lookAt(target);
}
function resetCamera() {
cameraState.yaw = 0.54;
cameraState.pitch = 0.48;
cameraState.radius = 15.8;
cameraState.target.set(0, 1.1, 0);
updateCamera();
}
document.querySelector("#view-reset").addEventListener("click", resetCamera);
const pointers = new Map();
let dragDistance = 0;
let lastPinchDistance = 0;
canvas.addEventListener("pointerdown", (event) => {
canvas.setPointerCapture(event.pointerId);
pointers.set(event.pointerId, { x: event.clientX, y: event.clientY });
dragDistance = 0;
if (pointers.size === 2) {
lastPinchDistance = getPinchDistance();
}
});
canvas.addEventListener("pointermove", (event) => {
const previous = pointers.get(event.pointerId);
if (!previous) return;
const dx = event.clientX - previous.x;
const dy = event.clientY - previous.y;
pointers.set(event.pointerId, { x: event.clientX, y: event.clientY });
dragDistance += Math.hypot(dx, dy);
if (pointers.size === 1) {
cameraState.yaw -= dx * 0.006;
cameraState.pitch = clamp(cameraState.pitch + dy * 0.0045, 0.22, 1.08);
} else if (pointers.size === 2) {
const distance = getPinchDistance();
if (lastPinchDistance > 0 && distance > 0) {
cameraState.radius = clamp(
cameraState.radius * (lastPinchDistance / distance),
9.5,
22
);
}
lastPinchDistance = distance;
}
updateCamera();
});
function endPointer(event, cancelled = false) {
const shouldRaycast = !cancelled && dragDistance < 6 && pointers.size === 1;
pointers.delete(event.pointerId);
if (shouldRaycast) selectStallFromPointer(event);
if (pointers.size < 2) lastPinchDistance = 0;
}
canvas.addEventListener("pointerup", (event) => endPointer(event));
canvas.addEventListener("pointercancel", (event) => endPointer(event, true));
canvas.addEventListener("wheel", (event) => {
event.preventDefault();
cameraState.radius = clamp(
cameraState.radius + event.deltaY * 0.012,
9.5,
22
);
updateCamera();
}, { passive: false });
canvas.addEventListener("dblclick", resetCamera);
function getPinchDistance() {
const values = [...pointers.values()];
if (values.length < 2) return 0;
return Math.hypot(values[0].x - values[1].x, values[0].y - values[1].y);
}
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
function selectStallFromPointer(event) {
const rect = canvas.getBoundingClientRect();
pointer.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;
pointer.y = -((event.clientY - rect.top) / rect.height) * 2 + 1;
raycaster.setFromCamera(pointer, camera);
const hits = raycaster.intersectObjects(hitTargets, false);
if (hits.length) {
const id = hits[0].object.userData.productId;
setActiveProduct(id);
document.querySelector(`#item-${id}`)?.scrollIntoView({
behavior: "smooth",
block: "nearest"
});
}
}
/* ---------------------------------------------------------
Resize and projection
--------------------------------------------------------- */
function resize() {
const width = scenePanel.clientWidth;
const height = scenePanel.clientHeight;
renderer.setSize(width, height, false);
camera.aspect = width / height;
camera.updateProjectionMatrix();
}
const resizeObserver = new ResizeObserver(resize);
resizeObserver.observe(scenePanel);
resize();
const projected = new THREE.Vector3();
function updatePricePins() {
const width = scenePanel.clientWidth;
const height = scenePanel.clientHeight;
document.querySelectorAll(".price-pin").forEach((pin, index) => {
projected.copy(stallPositions[index]).project(camera);
const visible = projected.z > -1 && projected.z < 1;
pin.style.opacity = visible ? "1" : "0";
pin.style.pointerEvents = visible ? "auto" : "none";
pin.style.left = `${(projected.x * 0.5 + 0.5) * width}px`;
pin.style.top = `${(-projected.y * 0.5 + 0.5) * height}px`;
});
}
/* ---------------------------------------------------------
Animation
--------------------------------------------------------- */
const clock = new THREE.Clock();
function animate() {
const elapsed = clock.getElapsedTime();
shopperA.position.set(
-1.9 + Math.sin(elapsed * 0.34) * 2.3,
0.13,
2.25 + Math.sin(elapsed * 0.68) * 0.12
);
shopperA.rotation.y = Math.cos(elapsed * 0.34) > 0 ? 0.1 : -0.1;
shopperB.position.set(
2.0 + Math.sin(elapsed * 0.27 + 2.1) * 2.1,
0.13,
2.55 + Math.cos(elapsed * 0.54 + 1.3) * 0.1
);
shopperB.rotation.y = Math.cos(elapsed * 0.27 + 2.1) > 0 ? -0.1 : 0.1;
activeMarker.material.opacity = 0.52 + Math.sin(elapsed * 2.2) * 0.12;
activeMarker.scale.setScalar(1 + Math.sin(elapsed * 2.2) * 0.012);
updateCamera();
updatePricePins();
renderer.render(scene, camera);
}
setActiveProduct(products[0].id);
updateAll();
updateCamera();
renderer.setAnimationLoop(animate);
</script>
</body>
</html>
```