Prompt specification
Build or customize the Three.js 3D scene "Stack and queue token containers" 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: Stack and queue token containers
Category: Algorithms & Systems · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/stack-and-queue-token-containers-x1909
Scene Description Prompt:
Please use Three.js from cdnjs for a low-poly scene based on this idea: stack and queue token containers. Build a vertical stack and a horizontal queue using uniquely numbered tokens; label insertion and removal ends so last-in-first-out and first-in-first-out behavior remain distinct. Return one self-contained HTML file.
Working Three.js Starter (stack-and-queue-token-containers-x1909):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Stack & Queue — Low-Poly Token Scene</title>
<style>
:root {
color-scheme: dark;
--insert: #55dfae;
--remove: #ff7485;
--panel: rgba(12, 19, 36, 0.82);
--border: rgba(255, 255, 255, 0.13);
--text: #f4f7ff;
--muted: #9ba9c2;
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: #0b1020;
color: var(--text);
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
#scene {
position: fixed;
inset: 0;
}
#scene canvas {
display: block;
width: 100%;
height: 100%;
outline: none;
cursor: grab;
touch-action: none;
}
#scene canvas:active {
cursor: grabbing;
}
.brand,
.legend,
.controls {
position: fixed;
z-index: 10;
}
.brand {
top: 22px;
left: 24px;
max-width: 390px;
pointer-events: none;
text-shadow: 0 2px 18px rgba(0, 0, 0, 0.45);
}
.eyebrow {
margin: 0 0 7px;
color: var(--insert);
font-size: 11px;
font-weight: 800;
letter-spacing: 0.2em;
text-transform: uppercase;
}
.brand h1 {
margin: 0;
font-size: clamp(25px, 3vw, 39px);
line-height: 1;
letter-spacing: -0.04em;
}
.brand p {
margin: 10px 0 0;
color: var(--muted);
font-size: 13px;
line-height: 1.5;
}
.legend {
top: 22px;
right: 24px;
display: flex;
gap: 9px;
pointer-events: none;
}
.legend span,
.count {
display: inline-flex;
align-items: center;
gap: 7px;
min-height: 30px;
padding: 7px 10px;
border: 1px solid var(--border);
border-radius: 999px;
background: var(--panel);
backdrop-filter: blur(12px);
color: #d9e2f4;
font-size: 11px;
font-weight: 750;
letter-spacing: 0.03em;
}
.legend span::before,
.count::before {
width: 7px;
height: 7px;
border-radius: 50%;
background: currentColor;
content: "";
box-shadow: 0 0 12px currentColor;
}
.legend .insert {
color: var(--insert);
}
.legend .remove {
color: var(--remove);
}
.controls {
bottom: 20px;
left: 50%;
width: min(900px, calc(100% - 32px));
padding: 12px;
transform: translateX(-50%);
border: 1px solid var(--border);
border-radius: 18px;
background: var(--panel);
box-shadow: 0 20px 60px rgba(0, 0, 0, 0.38);
backdrop-filter: blur(18px);
}
.control-row {
display: flex;
align-items: stretch;
justify-content: center;
gap: 10px;
}
.control-group {
display: flex;
align-items: center;
gap: 7px;
padding: 6px;
border: 1px solid rgba(255, 255, 255, 0.09);
border-radius: 12px;
background: rgba(255, 255, 255, 0.035);
}
.group-name {
min-width: 92px;
padding: 0 8px;
}
.group-name strong,
.group-name small {
display: block;
}
.group-name strong {
font-size: 12px;
letter-spacing: 0.03em;
}
.group-name small {
margin-top: 3px;
color: var(--muted);
font-size: 10px;
}
.count {
min-height: 24px;
padding: 5px 8px;
color: #dce5f7;
font-variant-numeric: tabular-nums;
}
.count::before {
display: none;
}
button {
min-height: 38px;
padding: 0 14px;
border: 1px solid transparent;
border-radius: 9px;
color: #08131b;
background: var(--insert);
font: inherit;
font-size: 12px;
font-weight: 850;
cursor: pointer;
transition:
transform 140ms ease,
filter 140ms ease,
opacity 140ms ease;
}
button:hover:not(:disabled) {
filter: brightness(1.09);
transform: translateY(-1px);
}
button:active:not(:disabled) {
transform: translateY(1px);
}
button:focus-visible {
outline: 2px solid white;
outline-offset: 2px;
}
button:disabled {
opacity: 0.28;
cursor: not-allowed;
}
button.remove {
color: #260a10;
background: var(--remove);
}
button.reset {
color: #dce5f7;
border-color: var(--border);
background: rgba(255, 255, 255, 0.08);
}
.readout {
display: flex;
justify-content: space-between;
gap: 16px;
margin-top: 9px;
padding: 0 5px;
color: var(--muted);
font-size: 11px;
}
#log {
color: #c9d5e8;
}
.hint {
white-space: nowrap;
}
@media (max-width: 760px) {
.brand {
top: 16px;
left: 16px;
}
.brand p,
.legend {
display: none;
}
.controls {
bottom: 10px;
width: calc(100% - 20px);
padding: 9px;
}
.control-row {
flex-wrap: wrap;
}
.control-group {
flex: 1 1 280px;
}
.group-name {
min-width: 74px;
}
button {
padding: 0 11px;
}
.readout {
font-size: 10px;
}
.hint {
display: none;
}
}
</style>
</head>
<body>
<div id="scene"></div>
<header class="brand">
<p class="eyebrow">Low-poly data structures</p>
<h1>Stack + Queue</h1>
<p>
Numbered tokens demonstrate LIFO and FIFO behavior. Every token has a
globally unique ID.
</p>
</header>
<div class="legend" aria-hidden="true">
<span class="insert">Insertion end</span>
<span class="remove">Removal end</span>
</div>
<section class="controls" aria-label="Token operations">
<div class="control-row">
<div class="control-group">
<div class="group-name">
<strong>Stack · LIFO</strong>
<small>insert / remove top</small>
</div>
<span class="count" id="stackCount">5 / 6</span>
<button id="pushBtn" type="button">Push</button>
<button id="popBtn" class="remove" type="button">Pop</button>
</div>
<div class="control-group">
<div class="group-name">
<strong>Queue · FIFO</strong>
<small>insert left / remove right</small>
</div>
<span class="count" id="queueCount">5 / 6</span>
<button id="enqueueBtn" type="button">Enqueue</button>
<button id="dequeueBtn" class="remove" type="button">Dequeue</button>
</div>
<button id="resetBtn" class="reset" type="button">Reset</button>
</div>
<div class="readout">
<span id="log" aria-live="polite">Ready.</span>
<span class="hint">Drag to orbit · Wheel to zoom · 0 resets the view</span>
</div>
</section>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// Scene and renderer
// -------------------------------------------------------------------------
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x0b1020);
scene.fog = new THREE.Fog(0x0b1020, 25, 70);
const camera = new THREE.PerspectiveCamera(38, 1, 0.1, 100);
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.12;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
const canvas = renderer.domElement;
canvas.tabIndex = 0;
canvas.setAttribute(
"aria-label",
"Interactive low-poly scene showing a vertical LIFO stack and horizontal FIFO queue"
);
document.getElementById("scene").appendChild(canvas);
const hemisphere = new THREE.HemisphereLight(0xc8dcff, 0x182033, 2.15);
scene.add(hemisphere);
const keyLight = new THREE.DirectionalLight(0xfff3dc, 3.1);
keyLight.position.set(-4, 11, 8);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(2048, 2048);
keyLight.shadow.camera.left = -14;
keyLight.shadow.camera.right = 14;
keyLight.shadow.camera.top = 10;
keyLight.shadow.camera.bottom = -10;
keyLight.shadow.camera.near = 1;
keyLight.shadow.camera.far = 35;
keyLight.shadow.bias = -0.0007;
scene.add(keyLight);
const fillLight = new THREE.DirectionalLight(0x77c7ff, 1.35);
fillLight.position.set(9, 5, -6);
scene.add(fillLight);
const rimLight = new THREE.PointLight(0xff6f91, 18, 18, 2);
rimLight.position.set(-5, 5, -4);
scene.add(rimLight);
// -------------------------------------------------------------------------
// Low-level helpers
// -------------------------------------------------------------------------
const STACK_CAPACITY = 6;
const QUEUE_CAPACITY = 6;
const STACK_X = -3.45;
const STACK_BASE_Y = 0.58;
const STACK_STEP = 0.49;
const QUEUE_Y = 0.66;
const QUEUE_SLOTS = [0.65, 1.75, 2.85, 3.95, 5.05, 6.15];
const QUEUE_CENTER = 3.4;
const INSERT_COLOR = 0x55dfae;
const REMOVE_COLOR = 0xff7485;
const palette = [
0xff9866,
0xf4c95d,
0x55d6ad,
0x55bce8,
0x9a88f8,
0xf07eb9,
0x8bd450,
0xffbd59,
0x5eead4,
0x60a5fa
];
function standardMaterial(color, options = {}) {
return new THREE.MeshStandardMaterial({
color,
roughness: 0.68,
metalness: 0.08,
flatShading: true,
...options
});
}
function addBox(size, position, color, options = {}) {
const mesh = new THREE.Mesh(
new THREE.BoxGeometry(size.x, size.y, size.z),
standardMaterial(color, options.material || {})
);
mesh.position.copy(position);
mesh.castShadow = options.castShadow ?? true;
mesh.receiveShadow = options.receiveShadow ?? true;
scene.add(mesh);
return mesh;
}
function roundedRectPath(ctx, x, y, width, height, radius) {
const r = Math.min(radius, width / 2, height / 2);
ctx.beginPath?.();
ctx.moveTo(x + r, y);
ctx.lineTo(x + width - r, y);
ctx.quadraticCurveTo(x + width, y, x + width, y + r);
ctx.lineTo(x + width, y + height - r);
ctx.quadraticCurveTo(
x + width,
y + height,
x + width - r,
y + height
);
ctx.lineTo(x + r, y + height);
ctx.quadraticCurveTo(x, y + height, x, y + height - r);
ctx.lineTo(x, y + r);
ctx.quadraticCurveTo(x, y, x + r, y);
ctx.closePath();
}
function beveledBoxGeometry(width, height, depth, radius = 0.12, bevel = 0.06) {
const shape = new THREE.Shape();
roundedRectPath(shape, -width / 2, -height / 2, width, height, radius);
const geometry = new THREE.ExtrudeGeometry(shape, {
depth: Math.max(0.01, depth - bevel * 2),
steps: 1,
bevelEnabled: true,
bevelSegments: 1,
bevelSize: bevel,
bevelThickness: bevel,
curveSegments: 1
});
geometry.center();
geometry.computeVertexNormals();
return geometry;
}
function makeTextSprite(text, options = {}) {
const canvasWidth = options.canvasWidth ?? 1024;
const canvasHeight = options.canvasHeight ?? 256;
const labelCanvas = document.createElement("canvas");
labelCanvas.width = canvasWidth;
labelCanvas.height = canvasHeight;
const ctx = labelCanvas.getContext("2d");
const inset = 12;
const radius = options.radius ?? 34;
if (options.background !== null) {
roundedRectPath(
ctx,
inset,
inset,
canvasWidth - inset * 2,
canvasHeight - inset * 2,
radius
);
ctx.fillStyle = options.background ?? "rgba(9, 15, 30, 0.82)";
ctx.fill();
if (options.border !== null) {
ctx.lineWidth = options.borderWidth ?? 4;
ctx.strokeStyle = options.border ?? "rgba(255,255,255,0.16)";
ctx.stroke();
}
}
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillStyle = options.color ?? "#f5f7ff";
ctx.font = `${options.weight ?? 800} ${options.fontSize ?? 82}px Inter, system-ui, sans-serif`;
ctx.fillText(
text,
canvasWidth / 2,
canvasHeight / 2 + (options.textOffsetY ?? 0),
canvasWidth - 80
);
const texture = new THREE.CanvasTexture(labelCanvas);
texture.colorSpace = THREE.SRGBColorSpace;
texture.minFilter = THREE.LinearFilter;
texture.magFilter = THREE.LinearFilter;
texture.generateMipmaps = false;
const material = new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthTest: false,
depthWrite: false,
toneMapped: false
});
const sprite = new THREE.Sprite(material);
sprite.scale.set(options.scaleX ?? 2, options.scaleY ?? 0.5, 1);
sprite.renderOrder = 50;
return sprite;
}
// -------------------------------------------------------------------------
// Floor, pedestals, and container details
// -------------------------------------------------------------------------
const floor = new THREE.Mesh(
new THREE.PlaneGeometry(32, 20),
standardMaterial(0x10182a, { roughness: 0.92, metalness: 0.02 })
);
floor.rotation.x = -Math.PI / 2;
floor.position.y = -0.01;
floor.receiveShadow = true;
scene.add(floor);
const grid = new THREE.GridHelper(30, 30, 0x31405a, 0x202c42);
grid.position.y = 0.006;
grid.material.transparent = true;
grid.material.opacity = 0.42;
scene.add(grid);
const stackPedestal = new THREE.Mesh(
new THREE.CylinderGeometry(1.25, 1.38, 0.28, 6),
standardMaterial(0x27243a)
);
stackPedestal.position.set(STACK_X, 0.15, 0);
stackPedestal.rotation.y = Math.PI / 6;
stackPedestal.castShadow = true;
stackPedestal.receiveShadow = true;
scene.add(stackPedestal);
const queuePedestal = new THREE.Mesh(
beveledBoxGeometry(7.25, 0.28, 1.65, 0.18, 0.06),
standardMaterial(0x18243a)
);
queuePedestal.position.set(QUEUE_CENTER, 0.15, 0);
queuePedestal.castShadow = true;
queuePedestal.receiveShadow = true;
scene.add(queuePedestal);
// Rear frame for the vertical stack.
addBox(
new THREE.Vector3(0.11, 3.45, 0.11),
new THREE.Vector3(STACK_X - 0.92, 1.9, -0.72),
0x46526d
);
addBox(
new THREE.Vector3(0.11, 3.45, 0.11),
new THREE.Vector3(STACK_X + 0.92, 1.9, -0.72),
0x46526d
);
addBox(
new THREE.Vector3(1.95, 0.11, 0.11),
new THREE.Vector3(STACK_X, 3.58, -0.72),
0x56627d
);
// Low rails and slot dividers for the horizontal queue.
addBox(
new THREE.Vector3(7.0, 0.1, 0.09),
new THREE.Vector3(QUEUE_CENTER, 0.43, -0.68),
0x465a78
);
addBox(
new THREE.Vector3(7.0, 0.07, 0.08),
new THREE.Vector3(QUEUE_CENTER, 0.36, 0.72),
0x2d3e59
);
for (let i = 1; i < QUEUE_SLOTS.length; i++) {
const dividerX = (QUEUE_SLOTS[i - 1] + QUEUE_SLOTS[i]) / 2;
addBox(
new THREE.Vector3(0.035, 0.025, 1.05),
new THREE.Vector3(dividerX, 0.305, 0),
0x52627a,
{ castShadow: false }
);
}
// Colored end posts.
addBox(
new THREE.Vector3(0.12, 0.82, 0.12),
new THREE.Vector3(0.12, 0.72, -0.57),
INSERT_COLOR
);
addBox(
new THREE.Vector3(0.12, 0.82, 0.12),
new THREE.Vector3(6.7, 0.72, -0.57),
REMOVE_COLOR
);
// -------------------------------------------------------------------------
// In-world titles and end labels
// -------------------------------------------------------------------------
const stackTitle = makeTextSprite("STACK / LIFO", {
scaleX: 3.0,
scaleY: 0.66,
fontSize: 86,
color: "#f6f8ff",
border: "rgba(255,255,255,0.18)"
});
stackTitle.position.set(STACK_X, 5.02, 0);
scene.add(stackTitle);
const stackSubtitle = makeTextSprite("LAST IN, FIRST OUT", {
scaleX: 2.6,
scaleY: 0.46,
fontSize: 64,
color: "#b9c6dd",
background: null,
border: null
});
stackSubtitle.position.set(STACK_X, 4.57, 0);
scene.add(stackSubtitle);
const queueTitle = makeTextSprite("QUEUE / FIFO", {
scaleX: 3.0,
scaleY: 0.66,
fontSize: 86,
color: "#f6f8ff",
border: "rgba(255,255,255,0.18)"
});
queueTitle.position.set(QUEUE_CENTER, 3.2, 0);
scene.add(queueTitle);
const queueSubtitle = makeTextSprite("FIRST IN, FIRST OUT", {
scaleX: 2.6,
scaleY: 0.46,
fontSize: 64,
color: "#b9c6dd",
background: null,
border: null
});
queueSubtitle.position.set(QUEUE_CENTER, 2.79, 0);
scene.add(queueSubtitle);
function addArrow(direction, origin, length, color) {
const arrow = new THREE.ArrowHelper(
direction,
origin,
length,
color,
0.28,
0.19
);
arrow.line.material.transparent = true;
arrow.line.material.opacity = 0.9;
scene.add(arrow);
return arrow;
}
// Stack insertion and removal both occur at the top.
addArrow(
new THREE.Vector3(0, -1, 0),
new THREE.Vector3(STACK_X - 0.63, 4.2, 0),
0.95,
INSERT_COLOR
);
addArrow(
new THREE.Vector3(0, 1, 0),
new THREE.Vector3(STACK_X + 0.62, 3.25, 0),
0.95,
REMOVE_COLOR
);
const stackInsertLabel = makeTextSprite("INSERT / PUSH", {
scaleX: 1.7,
scaleY: 0.38,
fontSize: 68,
color: "#a9ffdd",
background: "rgba(8,35,31,0.88)",
border: "rgba(85,223,174,0.42)"
});
stackInsertLabel.position.set(STACK_X - 1.38, 4.12, 0);
scene.add(stackInsertLabel);
const stackRemoveLabel = makeTextSprite("REMOVE / POP", {
scaleX: 1.85,
scaleY: 0.38,
fontSize: 68,
color: "#ffc1c8",
background: "rgba(42,15,27,0.88)",
border: "rgba(255,116,133,0.42)"
});
stackRemoveLabel.position.set(STACK_X + 1.48, 4.12, 0);
scene.add(stackRemoveLabel);
// Queue insertion is on the left; removal is on the right.
addArrow(
new THREE.Vector3(1, 0, 0),
new THREE.Vector3(-0.62, 1.62, 0),
1.08,
INSERT_COLOR
);
addArrow(
new THREE.Vector3(1, 0, 0),
new THREE.Vector3(6.55, 1.62, 0),
1.1,
REMOVE_COLOR
);
const queueInsertLabel = makeTextSprite("INSERT / ENQUEUE", {
scaleX: 2.05,
scaleY: 0.4,
fontSize: 68,
color: "#a9ffdd",
background: "rgba(8,35,31,0.88)",
border: "rgba(85,223,174,0.42)"
});
queueInsertLabel.position.set(-0.78, 2.06, 0);
scene.add(queueInsertLabel);
const queueRemoveLabel = makeTextSprite("REMOVE / DEQUEUE", {
scaleX: 2.2,
scaleY: 0.4,
fontSize: 68,
color: "#ffc1c8",
background: "rgba(42,15,27,0.88)",
border: "rgba(255,116,133,0.42)"
});
queueRemoveLabel.position.set(7.36, 2.06, 0);
scene.add(queueRemoveLabel);
// -------------------------------------------------------------------------
// Tokens and their IDs
// -------------------------------------------------------------------------
const stackTokens = [];
const queueTokens = [];
const allTokens = new Set();
let nextTokenId = 11;
function tokenColor(id) {
return palette[(id - 1) % palette.length];
}
function createToken(id, kind) {
const group = new THREE.Group();
const color = tokenColor(id);
const material = standardMaterial(color);
const topColor = new THREE.Color(color).lerp(
new THREE.Color(0xffffff),
0.2
);
if (kind === "stack") {
const body = new THREE.Mesh(
new THREE.CylinderGeometry(0.73, 0.78, 0.43, 6, 1, false),
material
);
body.rotation.y = Math.PI / 6;
body.castShadow = true;
body.receiveShadow = true;
group.add(body);
const top = new THREE.Mesh(
new THREE.CylinderGeometry(0.56, 0.56, 0.035, 6),
standardMaterial(topColor, { roughness: 0.58 })
);
top.position.y = 0.23;
top.rotation.y = Math.PI / 6;
top.castShadow = true;
group.add(top);
const rim = new THREE.Mesh(
new THREE.TorusGeometry(0.56, 0.026, 4, 6),
standardMaterial(0xffffff, {
roughness: 0.45,
metalness: 0.12
})
);
rim.rotation.x = Math.PI / 2;
rim.position.y = 0.252;
group.add(rim);
} else {
const body = new THREE.Mesh(
beveledBoxGeometry(0.92, 0.64, 0.76, 0.12, 0.07),
material
);
body.castShadow = true;
body.receiveShadow = true;
group.add(body);
const inset = new THREE.Mesh(
new THREE.BoxGeometry(0.68, 0.025, 0.52),
standardMaterial(topColor, { roughness: 0.58 })
);
inset.position.y = 0.332;
inset.castShadow = true;
group.add(inset);
}
const numberSprite = makeTextSprite(String(id).padStart(2, "0"), {
canvasWidth: 256,
canvasHeight: 128,
scaleX: 0.58,
scaleY: 0.29,
fontSize: 78,
color: "#ffffff",
background: "rgba(8,14,27,0.80)",
border: "rgba(255,255,255,0.26)",
borderWidth: 5,
radius: 24
});
numberSprite.position.set(0, 0, 0);
numberSprite.renderOrder = 80;
group.add(numberSprite);
scene.add(group);
const token = { id, kind, group };
allTokens.add(token);
return token;
}
function disposeToken(token) {
if (!token || !allTokens.has(token)) return;
scene.remove(token.group);
token.group.traverse((object) => {
if (object.geometry) object.geometry.dispose();
if (object.material) {
const materials = Array.isArray(object.material)
? object.material
: [object.material];
for (const material of materials) {
if (material.map) material.map.dispose();
material.dispose();
}
}
});
allTokens.delete(token);
}
// -------------------------------------------------------------------------
// Lightweight tween system
// -------------------------------------------------------------------------
const tweens = new Map();
function easeOutCubic(value) {
return 1 - Math.pow(1 - value, 3);
}
function moveToken(token, destination, duration = 560, options = {}) {
const key = token.group.uuid;
tweens.delete(key);
const fromPosition = token.group.position.clone();
const fromScale = token.group.scale.clone();
const toScale = options.toScale
? new THREE.Vector3(...options.toScale)
: new THREE.Vector3(1, 1, 1);
tweens.set(key, {
start: performance.now(),
duration,
update(progress) {
token.group.position.lerpVectors(
fromPosition,
destination,
progress
);
token.group.scale.lerpVectors(fromScale, toScale, progress);
},
complete: options.complete
});
}
function updateTweens(now) {
for (const [key, tween] of Array.from(tweens.entries())) {
const progress = Math.min(
1,
Math.max(0, (now - tween.start) / tween.duration)
);
tween.update(easeOutCubic(progress));
if (progress === 1) {
tweens.delete(key);
if (tween.complete) tween.complete();
}
}
}
// -------------------------------------------------------------------------
// Data-structure operations
// -------------------------------------------------------------------------
const stackCountEl = document.getElementById("stackCount");
const queueCountEl = document.getElementById("queueCount");
const pushBtn = document.getElementById("pushBtn");
const popBtn = document.getElementById("popBtn");
const enqueueBtn = document.getElementById("enqueueBtn");
const dequeueBtn = document.getElementById("dequeueBtn");
const resetBtn = document.getElementById("resetBtn");
const logEl = document.getElementById("log");
function announce(message) {
logEl.textContent = message;
}
function updateControls() {
stackCountEl.textContent = `${stackTokens.length} / ${STACK_CAPACITY}`;
queueCountEl.textContent = `${queueTokens.length} / ${QUEUE_CAPACITY}`;
pushBtn.disabled = stackTokens.length >= STACK_CAPACITY;
popBtn.disabled = stackTokens.length === 0;
enqueueBtn.disabled = queueTokens.length >= QUEUE_CAPACITY;
dequeueBtn.disabled = queueTokens.length === 0;
}
function pushToken() {
if (stackTokens.length >= STACK_CAPACITY) return;
const id = nextTokenId++;
const token = createToken(id, "stack");
stackTokens.push(token);
const targetY = STACK_BASE_Y + (stackTokens.length - 1) * STACK_STEP;
token.group.position.set(STACK_X, targetY + 1.3, 0);
token.group.scale.setScalar(0.74);
moveToken(
token,
new THREE.Vector3(STACK_X, targetY, 0),
560
);
updateControls();
announce(`Token ${id} pushed onto the stack.`);
}
function popToken() {
const token = stackTokens.pop();
if (!token) return;
const destination = token.group.position.clone();
destination.y += 1.3;
moveToken(token, destination, 470, {
toScale: [0.7, 0.7, 0.7],
complete: () => disposeToken(token)
});
updateControls();
announce(`Token ${token.id} popped from the top.`);
}
function enqueueToken() {
if (queueTokens.length >= QUEUE_CAPACITY) return;
const id = nextTokenId++;
const token = createToken(id, "queue");
// Newest token enters at the left end.
queueTokens.unshift(token);
token.group.position.set(QUEUE_SLOTS[0] - 1.25, QUEUE_Y, 0);
token.group.scale.setScalar(0.74);
queueTokens.forEach((queueToken, index) => {
moveToken(
queueToken,
new THREE.Vector3(QUEUE_SLOTS[index], QUEUE_Y, 0),
560
);
});
updateControls();
announce(`Token ${id} enqueued at the insertion end.`);
}
function dequeueToken() {
// The rightmost token is the oldest one.
const token = queueTokens.pop();
if (!token) return;
const destination = token.group.position.clone();
destination.x += 1.35;
moveToken(token, destination, 500, {
toScale: [0.7, 0.7, 0.7],
complete: () => disposeToken(token)
});
updateControls();
announce(`Token ${token.id} dequeued from the removal end.`);
}
function resetScene() {
tweens.clear();
for (const token of Array.from(allTokens)) {
disposeToken(token);
}
stackTokens.length = 0;
queueTokens.length = 0;
nextTokenId = 11;
// Stack IDs are ordered bottom-to-top: 1 was inserted before 5.
for (let id = 1; id <= 5; id++) {
const token = createToken(id, "stack");
const index = stackTokens.length;
token.group.position.set(
STACK_X,
STACK_BASE_Y + index * STACK_STEP,
0
);
stackTokens.push(token);
}
// Queue IDs are ordered newest-to-oldest from left to right.
// Token 10 is newest; token 6 is oldest and exits first.
for (let id = 10; id >= 6; id--) {
const token = createToken(id, "queue");
const index = queueTokens.length;
token.group.position.set(QUEUE_SLOTS[index], QUEUE_Y, 0);
queueTokens.push(token);
}
updateControls();
announce("Reset — token 5 is on the stack top and token 6 is at the queue exit.");
}
pushBtn.addEventListener("click", pushToken);
popBtn.addEventListener("click", popToken);
enqueueBtn.addEventListener("click", enqueueToken);
dequeueBtn.addEventListener("click", dequeueToken);
resetBtn.addEventListener("click", resetScene);
// -------------------------------------------------------------------------
// Custom camera controls: orbit, zoom, and keyboard access
// -------------------------------------------------------------------------
const cameraTarget = new THREE.Vector3(1.05, 1.62, 0);
let cameraTheta = 0.1;
let cameraPhi = 1.12;
let cameraRadius = 16;
let dragging = false;
let lastPointerX = 0;
let lastPointerY = 0;
function fittedRadius() {
const verticalFov = THREE.MathUtils.degToRad(camera.fov);
const horizontalFov = 2 * Math.atan(Math.tan(verticalFov / 2) * camera.aspect);
const verticalDistance = 3.6 / Math.tan(verticalFov / 2);
const horizontalDistance = 7.5 / Math.tan(horizontalFov / 2);
return THREE.MathUtils.clamp(
Math.max(verticalDistance, horizontalDistance) * 1.15,
11,
48
);
}
function updateCamera() {
const sinPhi = Math.sin(cameraPhi);
camera.position.set(
cameraTarget.x + cameraRadius * sinPhi * Math.sin(cameraTheta),
cameraTarget.y + cameraRadius * Math.cos(cameraPhi),
cameraTarget.z + cameraRadius * sinPhi * Math.cos(cameraTheta)
);
camera.lookAt(cameraTarget);
}
function resetCamera() {
cameraTheta = 0.1;
cameraPhi = 1.12;
cameraRadius = fittedRadius();
updateCamera();
}
canvas.addEventListener("pointerdown", (event) => {
if (event.button !== 0) return;
dragging = true;
lastPointerX = event.clientX;
lastPointerY = event.clientY;
canvas.setPointerCapture(event.pointerId);
canvas.focus({ preventScroll: true });
});
canvas.addEventListener("pointermove", (event) => {
if (!dragging) return;
const deltaX = event.clientX - lastPointerX;
const deltaY = event.clientY - lastPointerY;
lastPointerX = event.clientX;
lastPointerY = event.clientY;
cameraTheta -= deltaX * 0.006;
cameraPhi = THREE.MathUtils.clamp(
cameraPhi - deltaY * 0.005,
0.38,
1.46
);
});
function endPointerDrag(event) {
dragging = false;
if (canvas.hasPointerCapture(event.pointerId)) {
canvas.releasePointerCapture(event.pointerId);
}
}
canvas.addEventListener("pointerup", endPointerDrag);
canvas.addEventListener("pointercancel", endPointerDrag);
canvas.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraRadius = THREE.MathUtils.clamp(
cameraRadius * Math.exp(event.deltaY * 0.001),
9,
50
);
},
{ passive: false }
);
canvas.addEventListener("dblclick", resetCamera);
canvas.addEventListener("contextmenu", (event) => event.preventDefault());
canvas.addEventListener("keydown", (event) => {
let handled = true;
switch (event.key) {
case "ArrowLeft":
cameraTheta += 0.08;
break;
case "ArrowRight":
cameraTheta -= 0.08;
break;
case "ArrowUp":
cameraPhi = Math.max(0.38, cameraPhi - 0.06);
break;
case "ArrowDown":
cameraPhi = Math.min(1.46, cameraPhi + 0.06);
break;
case "+":
case "=":
cameraRadius = Math.max(9, cameraRadius * 0.9);
break;
case "-":
cameraRadius = Math.min(50, cameraRadius * 1.1);
break;
case "0":
resetCamera();
break;
default:
handled = false;
}
if (handled) event.preventDefault();
});
// -------------------------------------------------------------------------
// Resize and render loop
// -------------------------------------------------------------------------
function resize() {
const width = window.innerWidth;
const height = window.innerHeight;
camera.aspect = width / height;
camera.updateProjectionMatrix();
renderer.setSize(width, height, false);
}
window.addEventListener("resize", resize);
resize();
resetCamera();
resetScene();
function animate(now) {
requestAnimationFrame(animate);
updateTweens(now);
updateCamera();
renderer.render(scene, camera);
}
requestAnimationFrame(animate);
</script>
</body>
</html>
```