Prompt specification
Build or customize the Three.js 3D scene "Priority Rule Changes Worker Behavior" 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: Priority Rule Changes Worker Behavior
Category: Games & Play · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/priority-rule-changes-worker-behavior-x3524
Scene Description Prompt:
Compare two task-priority policies in a low-poly village, tracking completion times and neglected jobs under identical arrivals. Three.js from cdnjs, one HTML file.
Working Three.js Starter (priority-rule-changes-worker-behavior-x3524):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Village Queue Lab</title>
<style>
:root {
--ink: #17333a;
--muted: #668087;
--paper: #f7f4eb;
--panel: rgba(255, 255, 255, 0.88);
--line: rgba(23, 51, 58, 0.12);
--fifo: #3d7280;
--priority: #ee6d55;
--high: #ed554b;
--normal: #e4aa36;
--low: #36a9b0;
--shadow: 0 14px 40px rgba(29, 59, 64, 0.11);
}
* {
box-sizing: border-box;
}
html,
body {
margin: 0;
width: 100%;
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,
select {
font: inherit;
}
button {
color: inherit;
}
#app {
height: 100dvh;
min-height: 720px;
display: grid;
grid-template-rows: auto auto minmax(310px, 1fr) auto;
gap: 10px;
padding: 10px;
}
.topbar {
min-height: 62px;
display: flex;
align-items: center;
justify-content: space-between;
gap: 20px;
padding: 9px 12px 9px 16px;
border: 1px solid var(--line);
border-radius: 18px;
background: var(--panel);
box-shadow: var(--shadow);
backdrop-filter: blur(14px);
}
.brand {
display: flex;
align-items: center;
gap: 12px;
min-width: 0;
}
.brand-mark {
position: relative;
width: 38px;
height: 38px;
flex: 0 0 auto;
}
.brand-mark::before,
.brand-mark::after {
content: "";
position: absolute;
inset: 6px 2px 15px;
background: var(--priority);
clip-path: polygon(50% 0, 100% 35%, 82% 100%, 18% 100%, 0 35%);
}
.brand-mark::after {
inset: 15px 2px 2px;
background: var(--fifo);
transform: rotate(180deg);
}
.brand h1 {
margin: 0;
font-size: clamp(17px, 2vw, 24px);
letter-spacing: -0.04em;
line-height: 1.05;
}
.brand p {
margin: 5px 0 0;
color: var(--muted);
font-size: 12px;
}
.controls {
display: flex;
align-items: center;
gap: 7px;
flex-wrap: wrap;
justify-content: flex-end;
}
.control-button {
min-height: 36px;
padding: 8px 12px;
border: 1px solid var(--line);
border-radius: 11px;
background: rgba(255, 255, 255, 0.8);
cursor: pointer;
font-size: 12px;
font-weight: 750;
transition:
transform 120ms ease,
background 120ms ease;
}
.control-button:hover {
transform: translateY(-1px);
background: white;
}
.control-button.primary {
min-width: 76px;
border-color: transparent;
background: var(--ink);
color: white;
}
.metric-grid {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 10px;
}
.policy-card {
position: relative;
overflow: hidden;
min-width: 0;
padding: 13px 15px 12px;
border: 1px solid var(--line);
border-radius: 17px;
background: var(--panel);
box-shadow: var(--shadow);
backdrop-filter: blur(14px);
}
.policy-card::before {
content: "";
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 3px;
background: var(--policy-color);
}
.policy-heading {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
margin-bottom: 10px;
}
.policy-name {
display: flex;
align-items: center;
gap: 8px;
min-width: 0;
}
.policy-dot {
width: 9px;
height: 9px;
flex: 0 0 auto;
border-radius: 50%;
background: var(--policy-color);
box-shadow: 0 0 0 4px color-mix(in srgb, var(--policy-color) 16%, transparent);
}
.policy-name strong {
font-size: 14px;
letter-spacing: -0.015em;
}
.policy-name span {
overflow: hidden;
color: var(--muted);
font-size: 11px;
text-overflow: ellipsis;
white-space: nowrap;
}
.badge {
flex: 0 0 auto;
padding: 5px 7px;
border-radius: 999px;
background: color-mix(in srgb, var(--policy-color) 12%, white);
color: var(--policy-color);
font-size: 9px;
font-weight: 900;
letter-spacing: 0.1em;
text-transform: uppercase;
}
.metrics {
display: grid;
grid-template-columns: repeat(4, minmax(0, 1fr));
gap: 8px;
}
.metric {
min-width: 0;
padding-right: 8px;
border-right: 1px solid var(--line);
}
.metric:last-child {
border-right: 0;
}
.metric-label {
display: block;
margin-bottom: 2px;
color: var(--muted);
font-size: 10px;
font-weight: 700;
text-transform: uppercase;
letter-spacing: 0.06em;
}
.metric strong {
display: block;
font-size: clamp(20px, 2.3vw, 29px);
line-height: 1;
letter-spacing: -0.055em;
font-variant-numeric: tabular-nums;
}
.metric small {
display: block;
margin-top: 4px;
overflow: hidden;
color: var(--muted);
font-size: 9px;
text-overflow: ellipsis;
white-space: nowrap;
}
.metric.neglected strong {
color: var(--policy-color);
}
.policy-footer {
display: flex;
justify-content: space-between;
gap: 10px;
margin-top: 9px;
padding-top: 8px;
border-top: 1px solid var(--line);
color: var(--muted);
font-size: 10px;
font-variant-numeric: tabular-nums;
}
.scene-wrap {
position: relative;
min-height: 310px;
overflow: hidden;
border: 1px solid var(--line);
border-radius: 19px;
background: #d8e9e3;
box-shadow: var(--shadow);
}
#sceneCanvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
cursor: grab;
}
#sceneCanvas:active {
cursor: grabbing;
}
.scene-toolbar {
position: absolute;
top: 12px;
left: 12px;
right: 12px;
z-index: 3;
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 10px;
pointer-events: none;
}
.scene-hint,
.scene-status,
.camera-buttons {
border: 1px solid rgba(23, 51, 58, 0.1);
background: rgba(255, 255, 255, 0.82);
box-shadow: 0 8px 22px rgba(29, 59, 64, 0.09);
backdrop-filter: blur(10px);
}
.scene-hint {
padding: 8px 10px;
border-radius: 10px;
color: var(--muted);
font-size: 10px;
font-weight: 750;
letter-spacing: 0.03em;
}
.scene-status {
margin-left: auto;
padding: 8px 10px;
border-radius: 10px;
font-size: 10px;
font-weight: 800;
font-variant-numeric: tabular-nums;
}
.camera-buttons {
position: absolute;
right: 12px;
bottom: 12px;
z-index: 3;
display: flex;
gap: 4px;
padding: 4px;
border-radius: 11px;
}
.camera-buttons button {
border: 0;
border-radius: 8px;
padding: 7px 9px;
background: transparent;
cursor: pointer;
font-size: 10px;
font-weight: 800;
}
.camera-buttons button:hover {
background: rgba(23, 51, 58, 0.08);
}
.scene-legend {
position: absolute;
left: 12px;
bottom: 12px;
z-index: 3;
display: flex;
align-items: center;
gap: 12px;
padding: 8px 10px;
border: 1px solid rgba(23, 51, 58, 0.1);
border-radius: 10px;
background: rgba(255, 255, 255, 0.82);
box-shadow: 0 8px 22px rgba(29, 59, 64, 0.09);
backdrop-filter: blur(10px);
font-size: 10px;
font-weight: 750;
}
.legend-item {
display: flex;
align-items: center;
gap: 5px;
}
.legend-gem {
width: 8px;
height: 8px;
transform: rotate(45deg);
border-radius: 2px;
}
.analytics {
min-height: 182px;
padding: 12px 14px 13px;
border: 1px solid var(--line);
border-radius: 18px;
background: var(--panel);
box-shadow: var(--shadow);
backdrop-filter: blur(14px);
}
.analytics-header {
display: flex;
align-items: center;
justify-content: space-between;
gap: 14px;
margin-bottom: 8px;
}
.analytics-title {
font-size: 12px;
font-weight: 850;
}
.analytics-title span {
margin-left: 7px;
color: var(--muted);
font-size: 10px;
font-weight: 600;
}
#verdict {
overflow: hidden;
color: var(--muted);
font-size: 10px;
text-align: right;
text-overflow: ellipsis;
white-space: nowrap;
}
.charts {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 14px;
}
.chart-card {
min-width: 0;
padding: 6px 8px 4px;
border: 1px solid var(--line);
border-radius: 12px;
background: rgba(255, 255, 255, 0.58);
}
.chart-label {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
padding: 0 3px 2px;
color: var(--muted);
font-size: 9px;
font-weight: 800;
letter-spacing: 0.05em;
text-transform: uppercase;
}
.chart-legend {
display: flex;
gap: 9px;
font-size: 8px;
letter-spacing: 0;
text-transform: none;
}
.chart-legend span {
display: flex;
align-items: center;
gap: 4px;
}
.chart-legend i {
width: 12px;
height: 2px;
border-radius: 2px;
}
.chart-card svg {
display: block;
width: 100%;
height: 105px;
overflow: visible;
}
@media (max-width: 820px) {
body {
overflow: auto;
}
#app {
height: auto;
min-height: 100dvh;
grid-template-rows: auto auto 480px auto;
}
.topbar {
align-items: flex-start;
flex-direction: column;
}
.controls {
justify-content: flex-start;
}
.metrics {
grid-template-columns: repeat(2, minmax(0, 1fr));
}
.policy-footer {
flex-direction: column;
gap: 3px;
}
.charts {
grid-template-columns: 1fr;
}
.analytics-header {
align-items: flex-start;
flex-direction: column;
gap: 5px;
}
#verdict {
text-align: left;
white-space: normal;
}
}
@media (max-width: 570px) {
#app {
grid-template-rows: auto auto 430px auto;
padding: 7px;
gap: 7px;
}
.metric-grid {
grid-template-columns: 1fr;
}
.metrics {
grid-template-columns: repeat(2, minmax(0, 1fr));
}
.metric strong {
font-size: 19px;
}
.scene-hint {
max-width: 145px;
line-height: 1.35;
}
.scene-status {
font-size: 9px;
}
.scene-legend {
gap: 7px;
font-size: 9px;
}
}
</style>
</head>
<body>
<main id="app">
<header class="topbar">
<div class="brand">
<div class="brand-mark" aria-hidden="true"></div>
<div>
<h1>Village Queue Lab</h1>
<p>Identical arrivals. Two task-priority policies. One shared workshop stream.</p>
</div>
</div>
<div class="controls">
<button class="control-button primary" id="playButton" type="button">Pause</button>
<button class="control-button" id="speedButton" type="button">1× speed</button>
<button class="control-button" id="restartButton" type="button">Restart</button>
</div>
</header>
<section class="metric-grid" aria-label="Policy comparison">
<article
class="policy-card"
id="fifoCard"
style="--policy-color: var(--fifo)"
>
<div class="policy-heading">
<div class="policy-name">
<i class="policy-dot"></i>
<strong>FIFO</strong>
<span>Oldest arrival first</span>
</div>
<span class="badge">Baseline</span>
</div>
<div class="metrics">
<div class="metric">
<span class="metric-label">Avg completion</span>
<strong id="fifoAvg">—</strong>
<small>arrival → finished</small>
</div>
<div class="metric">
<span class="metric-label">P90 completion</span>
<strong id="fifoP90">—</strong>
<small>90% within</small>
</div>
<div class="metric neglected">
<span class="metric-label">Neglected</span>
<strong id="fifoNeglected">0</strong>
<small id="fifoNegBreakdown">H 0 · N 0 · L 0</small>
</div>
<div class="metric">
<span class="metric-label">Overdue now</span>
<strong id="fifoOverdue">0</strong>
<small>unfinished jobs</small>
</div>
</div>
<div class="policy-footer">
<span id="fifoDone">0 of 72 jobs completed</span>
<span id="fifoPriority">Priority averages: —</span>
</div>
</article>
<article
class="policy-card"
id="priorityCard"
style="--policy-color: var(--priority)"
>
<div class="policy-heading">
<div class="policy-name">
<i class="policy-dot"></i>
<strong>Strict Priority</strong>
<span>High → normal → low, then FIFO</span>
</div>
<span class="badge">Policy</span>
</div>
<div class="metrics">
<div class="metric">
<span class="metric-label">Avg completion</span>
<strong id="priorityAvg">—</strong>
<small>arrival → finished</small>
</div>
<div class="metric">
<span class="metric-label">P90 completion</span>
<strong id="priorityP90">—</strong>
<small>90% within</small>
</div>
<div class="metric neglected">
<span class="metric-label">Neglected</span>
<strong id="priorityNeglected">0</strong>
<small id="priorityNegBreakdown">H 0 · N 0 · L 0</small>
</div>
<div class="metric">
<span class="metric-label">Overdue now</span>
<strong id="priorityOverdue">0</strong>
<small>unfinished jobs</small>
</div>
</div>
<div class="policy-footer">
<span id="priorityDone">0 of 72 jobs completed</span>
<span id="priorityPriority">Priority averages: —</span>
</div>
</article>
</section>
<section class="scene-wrap" id="sceneWrap" aria-label="Low-poly village simulation">
<canvas id="sceneCanvas"></canvas>
<div class="scene-toolbar">
<div class="scene-hint">DRAG TO ORBIT · SCROLL TO ZOOM</div>
<div class="scene-status" id="sceneStatus">SIM 0s · 0 arrivals</div>
</div>
<div class="scene-legend" aria-label="Priority legend">
<span class="legend-item">
<i class="legend-gem" style="background: var(--high)"></i>
High
</span>
<span class="legend-item">
<i class="legend-gem" style="background: var(--normal)"></i>
Normal
</span>
<span class="legend-item">
<i class="legend-gem" style="background: var(--low)"></i>
Low
</span>
</div>
<div class="camera-buttons">
<button id="resetCamera" type="button">Reset view</button>
<button id="topCamera" type="button">Top view</button>
</div>
</section>
<section class="analytics" aria-label="Simulation charts">
<div class="analytics-header">
<div class="analytics-title">
LIVE COMPARISON
<span>Neglected = deadline passed before completion · H 15s / N 27s / L 42s</span>
</div>
<div id="verdict">Waiting for the first completed jobs…</div>
</div>
<div class="charts">
<div class="chart-card">
<div class="chart-label">
Average completion time
<div class="chart-legend">
<span><i style="background: var(--fifo)"></i>FIFO</span>
<span><i style="background: var(--priority)"></i>Priority</span>
</div>
</div>
<div id="completionChart"></div>
</div>
<div class="chart-card">
<div class="chart-label">
Cumulative neglected jobs
<div class="chart-legend">
<span><i style="background: var(--fifo)"></i>FIFO</span>
<span><i style="background: var(--priority)"></i>Priority</span>
</div>
</div>
<div id="neglectedChart"></div>
</div>
</div>
</section>
</main>
<script type="module">
import * as THREE from "https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// Simulation configuration
// -------------------------------------------------------------------------
const TOTAL_JOBS = 72;
const ARRIVAL_HORIZON = 210;
const BASE_SIM_RATE = 9; // simulation seconds per real second at 1×
const TRAVEL_TIME = 3;
const CHART_TIME_LIMIT = 235;
const PRIORITY = {
HIGH: 2,
NORMAL: 1,
LOW: 0
};
const PRIORITY_NAMES = ["L", "N", "H"];
const POLICY_COLORS = {
fifo: 0x3d7280,
priority: 0xee6d55
};
const $ = (selector) => document.querySelector(selector);
function mulberry32(seed) {
return function random() {
let value = (seed += 0x6d2b79f5);
value = Math.imul(value ^ (value >>> 15), value | 1);
value ^= value + Math.imul(value ^ (value >>> 7), value | 61);
return ((value ^ (value >>> 14)) >>> 0) / 4294967296;
};
}
function createTaskStream() {
const random = mulberry32(20250308);
const tasks = [];
for (let index = 0; index < TOTAL_JOBS; index++) {
const roll = random();
let priority;
if (roll < 0.18) {
priority = PRIORITY.HIGH;
} else if (roll < 0.58) {
priority = PRIORITY.NORMAL;
} else {
priority = PRIORITY.LOW;
}
const baseArrival = (index / (TOTAL_JOBS - 1)) * ARRIVAL_HORIZON;
const arrival = Math.max(0.2, baseArrival + (random() - 0.5) * 4.8);
let serviceDuration;
if (priority === PRIORITY.HIGH) {
serviceDuration = 4 + random() * 3.5;
} else if (priority === PRIORITY.NORMAL) {
serviceDuration = 7 + random() * 5.5;
} else {
serviceDuration = 10 + random() * 6.5;
}
const deadlineWindow =
priority === PRIORITY.HIGH
? 15
: priority === PRIORITY.NORMAL
? 27
: 42;
tasks.push({
id: index,
arrival,
priority,
serviceDuration,
deadline: arrival + deadlineWindow,
source: Math.floor(random() * 6)
});
}
return tasks.sort((a, b) => a.arrival - b.arrival);
}
// This immutable stream is consumed by both policies.
const TASK_STREAM = createTaskStream();
// -------------------------------------------------------------------------
// Three.js setup
// -------------------------------------------------------------------------
const canvas = $("#sceneCanvas");
const sceneWrap = $("#sceneWrap");
const renderer = new THREE.WebGLRenderer({
canvas,
antialias: true,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setClearColor(0xd8e9e3);
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.12;
const scene = new THREE.Scene();
scene.background = new THREE.Color(0xd8e9e3);
scene.fog = new THREE.Fog(0xd8e9e3, 85, 155);
const camera = new THREE.PerspectiveCamera(42, 1, 0.1, 300);
const hemisphere = new THREE.HemisphereLight(0xe9f8ff, 0x71825e, 2.15);
scene.add(hemisphere);
const sun = new THREE.DirectionalLight(0xfff2cf, 3.1);
sun.position.set(-34, 56, 28);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -72;
sun.shadow.camera.right = 72;
sun.shadow.camera.top = 58;
sun.shadow.camera.bottom = -58;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 130;
sun.shadow.bias = -0.00025;
scene.add(sun);
const fill = new THREE.DirectionalLight(0xb8ddeb, 0.8);
fill.position.set(40, 20, -35);
scene.add(fill);
// -------------------------------------------------------------------------
// Shared materials and geometries
// -------------------------------------------------------------------------
const jobGeometry = new THREE.OctahedronGeometry(0.48, 0);
const jobRingGeometry = new THREE.TorusGeometry(0.66, 0.055, 4, 14);
const burstGeometry = new THREE.TetrahedronGeometry(0.13, 0);
const jobMaterials = {
[PRIORITY.HIGH]: new THREE.MeshStandardMaterial({
color: 0xed554b,
emissive: 0x761b16,
emissiveIntensity: 0.45,
roughness: 0.36,
flatShading: true
}),
[PRIORITY.NORMAL]: new THREE.MeshStandardMaterial({
color: 0xe4aa36,
emissive: 0x624006,
emissiveIntensity: 0.28,
roughness: 0.42,
flatShading: true
}),
[PRIORITY.LOW]: new THREE.MeshStandardMaterial({
color: 0x36a9b0,
emissive: 0x0a4146,
emissiveIntensity: 0.25,
roughness: 0.45,
flatShading: true
})
};
const burstMaterials = {
[PRIORITY.HIGH]: new THREE.MeshBasicMaterial({ color: 0xed554b }),
[PRIORITY.NORMAL]: new THREE.MeshBasicMaterial({ color: 0xe4aa36 }),
[PRIORITY.LOW]: new THREE.MeshBasicMaterial({ color: 0x36a9b0 })
};
const roofColors = [0xb84e45, 0x4e7984, 0xc18836, 0x657a52, 0x8c5d77];
const wallColors = [0xf0d49d, 0xe8c98f, 0xd9e4cc, 0xf1dfb8];
// -------------------------------------------------------------------------
// Landscape
// -------------------------------------------------------------------------
function standardMaterial(color, options = {}) {
return new THREE.MeshStandardMaterial({
color,
roughness: 0.86,
flatShading: true,
...options
});
}
const ground = new THREE.Mesh(
new THREE.PlaneGeometry(170, 115),
standardMaterial(0x9fbd83)
);
ground.rotation.x = -Math.PI / 2;
ground.position.y = -0.62;
ground.receiveShadow = true;
scene.add(ground);
const river = new THREE.Mesh(
new THREE.BoxGeometry(4.5, 0.16, 105),
standardMaterial(0x67b8c2, { roughness: 0.3, metalness: 0.05 })
);
river.position.set(0, -0.48, 0);
river.receiveShadow = true;
scene.add(river);
for (let index = 0; index < 10; index++) {
const ripple = new THREE.Mesh(
new THREE.BoxGeometry(1.2 + (index % 3) * 0.35, 0.025, 0.08),
new THREE.MeshBasicMaterial({ color: 0xa8e0df })
);
ripple.position.set(
(index % 2 ? 0.7 : -0.7),
-0.38,
-46 + index * 10
);
scene.add(ripple);
}
function createMountain(x, z, radius, height, color) {
const mountain = new THREE.Mesh(
new THREE.ConeGeometry(radius, height, 5),
standardMaterial(color)
);
mountain.position.set(x, height / 2 - 0.6, z);
mountain.rotation.y = x * 0.017;
mountain.receiveShadow = true;
scene.add(mountain);
}
createMountain(-48, -42, 15, 19, 0x829c91);
createMountain(-22, -48, 12, 15, 0x91a99c);
createMountain(21, -47, 13, 17, 0x829c91);
createMountain(47, -40, 17, 22, 0x91a99c);
// -------------------------------------------------------------------------
// Text sprites
// -------------------------------------------------------------------------
function roundedRect(context, x, y, width, height, radius) {
const r = Math.min(radius, width / 2, height / 2);
context.beginPath();
context.moveTo(x + r, y);
context.lineTo(x + width - r, y);
context.quadraticCurveTo(x + width, y, x + width, y + r);
context.lineTo(x + width, y + height - r);
context.quadraticCurveTo(x + width, y + height, x + width - r, y + height);
context.lineTo(x + r, y + height);
context.quadraticCurveTo(x, y + height, x, y + height - r);
context.lineTo(x, y + r);
context.quadraticCurveTo(x, y, x + r, y);
context.closePath();
}
function makeTextSprite(text, options = {}) {
const width = options.width ?? 512;
const height = options.height ?? 128;
const worldWidth = options.worldWidth ?? 10;
const background = options.background ?? "rgba(23,51,58,0.9)";
const foreground = options.foreground ?? "#ffffff";
const fontSize = options.fontSize ?? 52;
const textCanvas = document.createElement("canvas");
textCanvas.width = width;
textCanvas.height = height;
const context = textCanvas.getContext("2d");
const texture = new THREE.CanvasTexture(textCanvas);
texture.colorSpace = THREE.SRGBColorSpace;
texture.minFilter = THREE.LinearFilter;
const material = new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthTest: false,
depthWrite: false
});
const sprite = new THREE.Sprite(material);
sprite.scale.set(worldWidth, (worldWidth * height) / width, 1);
sprite.renderOrder = 20;
function setText(nextText) {
context.clearRect(0, 0, width, height);
roundedRect(context, 8, 8, width - 16, height - 16, 24);
context.fillStyle = background;
context.fill();
context.fillStyle = foreground;
context.font = `900 ${fontSize}px system-ui, sans-serif`;
context.textAlign = "center";
context.textBaseline = "middle";
context.fillText(nextText, width / 2, height / 2 + 2);
texture.needsUpdate = true;
}
setText(text);
return { sprite, setText };
}
// -------------------------------------------------------------------------
// Village construction
// -------------------------------------------------------------------------
function createHouse(wallColor, roofColor) {
const group = new THREE.Group();
const body = new THREE.Mesh(
new THREE.BoxGeometry(3.7, 2.9, 3.4),
standardMaterial(wallColor)
);
body.position.y = 1.55;
body.castShadow = true;
body.receiveShadow = true;
group.add(body);
const roof = new THREE.Mesh(
new THREE.ConeGeometry(3.35, 2.1, 4),
standardMaterial(roofColor)
);
roof.position.y = 4.02;
roof.rotation.y = Math.PI / 4;
roof.castShadow = true;
group.add(roof);
const door = new THREE.Mesh(
new THREE.BoxGeometry(0.88, 1.7, 0.12),
standardMaterial(0x5a4335)
);
door.position.set(0, 0.95, 1.74);
door.castShadow = true;
group.add(door);
const windowMaterial = standardMaterial(0x9fd9df, {
emissive: 0x214b50,
emissiveIntensity: 0.22,
roughness: 0.35
});
for (const x of [-1.12, 1.12]) {
const windowMesh = new THREE.Mesh(
new THREE.BoxGeometry(0.58, 0.62, 0.1),
windowMaterial
);
windowMesh.position.set(x, 1.85, 1.74);
group.add(windowMesh);
}
const chimney = new THREE.Mesh(
new THREE.BoxGeometry(0.45, 1.15, 0.48),
standardMaterial(0x9b8067)
);
chimney.position.set(0.8, 4.45, -0.5);
chimney.castShadow = true;
group.add(chimney);
return group;
}
function createTree(scale = 1) {
const group = new THREE.Group();
const trunk = new THREE.Mesh(
new THREE.CylinderGeometry(0.19, 0.28, 1.8, 6),
standardMaterial(0x79523a)
);
trunk.position.y = 0.9;
trunk.castShadow = true;
group.add(trunk);
const crown = new THREE.Mesh(
new THREE.ConeGeometry(1.15, 2.9, 6),
standardMaterial(0x4d7752)
);
crown.position.y = 2.65;
crown.castShadow = true;
group.add(crown);
const crownTop = new THREE.Mesh(
new THREE.ConeGeometry(0.82, 2.1, 6),
standardMaterial(0x628b59)
);
crownTop.position.y = 3.9;
crownTop.castShadow = true;
group.add(crownTop);
group.scale.setScalar(scale);
return group;
}
function createWorkshop(accentColor) {
const group = new THREE.Group();
const body = new THREE.Mesh(
new THREE.BoxGeometry(6, 3.8, 4.8),
standardMaterial(0xe9d4a4)
);
body.position.set(0, 2, -1.5);
body.castShadow = true;
body.receiveShadow = true;
group.add(body);
const roof = new THREE.Mesh(
new THREE.ConeGeometry(4.55, 2.25, 4),
standardMaterial(accentColor)
);
roof.position.set(0, 5, -1.5);
roof.rotation.y = Math.PI / 4;
roof.castShadow = true;
group.add(roof);
const door = new THREE.Mesh(
new THREE.BoxGeometry(1.25, 2.2, 0.12),
standardMaterial(0x4e493e)
);
door.position.set(0, 1.18, 0.96);
group.add(door);
const counter = new THREE.Mesh(
new THREE.BoxGeometry(4.1, 0.35, 0.85),
standardMaterial(0x8f6343)
);
counter.position.set(0, 1.25, 1.3);
counter.castShadow = true;
group.add(counter);
for (const x of [-2, 2]) {
const windowMesh = new THREE.Mesh(
new THREE.BoxGeometry(0.9, 0.8, 0.1),
standardMaterial(0x9bd7dd, {
emissive: 0x24545b,
emissiveIntensity: 0.25
})
);
windowMesh.position.set(x, 2.35, 0.96);
group.add(windowMesh);
}
const sign = makeTextSprite("WORKSHOP", {
width: 512,
height: 112,
worldWidth: 5.8,
fontSize: 47,
background: "rgba(255,255,255,0.88)",
foreground: "#294c54"
});
sign.sprite.position.set(0, 4.4, 1.02);
group.add(sign.sprite);
return group;
}
function createWorker(accentColor) {
const group = new THREE.Group();
const legMaterial = standardMaterial(0x334b58);
const shirtMaterial = standardMaterial(accentColor);
const skinMaterial = standardMaterial(0xd9a274);
const leftLeg = new THREE.Mesh(
new THREE.CylinderGeometry(0.12, 0.14, 0.8, 6),
legMaterial
);
leftLeg.position.set(-0.18, 0.42, 0);
leftLeg.castShadow = true;
group.add(leftLeg);
const rightLeg = leftLeg.clone();
rightLeg.position.x = 0.18;
group.add(rightLeg);
const torso = new THREE.Mesh(
new THREE.BoxGeometry(0.75, 0.92, 0.46),
shirtMaterial
);
torso.position.y = 1.25;
torso.castShadow = true;
group.add(torso);
const head = new THREE.Mesh(
new THREE.IcosahedronGeometry(0.32, 0),
skinMaterial
);
head.position.y = 2.02;
head.castShadow = true;
group.add(head);
const hat = new THREE.Mesh(
new THREE.CylinderGeometry(0.36, 0.36, 0.12, 8),
standardMaterial(0xf0d25f)
);
hat.position.y = 2.28;
hat.castShadow = true;
group.add(hat);
const leftArm = new THREE.Mesh(
new THREE.CylinderGeometry(0.1, 0.12, 0.75, 6),
shirtMaterial
);
leftArm.position.set(-0.48, 1.28, 0);
leftArm.rotation.z = -0.18;
leftArm.castShadow = true;
group.add(leftArm);
const rightArm = leftArm.clone();
rightArm.position.x = 0.48;
rightArm.rotation.z = 0.18;
group.add(rightArm);
group.userData = {
torso,
leftArm,
rightArm,
head
};
return group;
}
function createToken(priority) {
const group = new THREE.Group();
const gem = new THREE.Mesh(jobGeometry, jobMaterials[priority]);
gem.castShadow = true;
group.add(gem);
if (priority === PRIORITY.HIGH) {
const ring = new THREE.Mesh(jobRingGeometry, jobMaterials[priority]);
ring.rotation.x = Math.PI / 2;
group.add(ring);
group.userData.ring = ring;
}
group.userData.gem = gem;
return group;
}
function createQueuePad(position, color) {
const pad = new THREE.Mesh(
new THREE.CylinderGeometry(0.58, 0.58, 0.08, 12),
new THREE.MeshStandardMaterial({
color,
transparent: true,
opacity: 0.38,
roughness: 1
})
);
pad.position.copy(position);
pad.position.y = 0.16;
return pad;
}
// -------------------------------------------------------------------------
// Policy world
// -------------------------------------------------------------------------
class VillageWorld {
constructor(policy, originX) {
this.policy = policy;
this.originX = originX;
this.group = new THREE.Group();
this.group.position.x = originX;
scene.add(this.group);
this.jobs = [];
this.queue = [];
this.active = null;
this.effects = [];
this.nextSpawn = 0;
this.completedTurnarounds = [];
this.waitTimes = [];
this.priorityCompletion = {
[PRIORITY.HIGH]: [],
[PRIORITY.NORMAL]: [],
[PRIORITY.LOW]: []
};
this.neglected = {
[PRIORITY.HIGH]: 0,
[PRIORITY.NORMAL]: 0,
[PRIORITY.LOW]: 0
};
this.housePositions = [];
this.buildVillage();
this.worker = createWorker(POLICY_COLORS[policy]);
this.worker.position.set(0, 0, 2.65);
this.group.add(this.worker);
this.board = makeTextSprite("BACKLOG 00", {
width: 420,
height: 120,
worldWidth: 7,
fontSize: 43,
background: policy === "fifo" ? "#3d7280" : "#ee6d55"
});
this.board.sprite.position.set(0, 7.35, -5.5);
this.group.add(this.board.sprite);
}
buildVillage() {
const platform = new THREE.Mesh(
new THREE.BoxGeometry(42, 1.1, 35),
standardMaterial(0xb8c98f)
);
platform.position.y = -0.45;
platform.receiveShadow = true;
this.group.add(platform);
const road = new THREE.Mesh(
new THREE.RingGeometry(8.3, 10.5, 40),
standardMaterial(0x9f9b88)
);
road.rotation.x = -Math.PI / 2;
road.position.y = 0.13;
road.receiveShadow = true;
this.group.add(road);
const innerRoad = new THREE.Mesh(
new THREE.CircleGeometry(3.2, 24),
standardMaterial(0xa5a18e)
);
innerRoad.rotation.x = -Math.PI / 2;
innerRoad.position.y = 0.14;
this.group.add(innerRoad);
const workshop = createWorkshop(POLICY_COLORS[this.policy]);
this.group.add(workshop);
const angles = [-2.75, -1.85, -0.95, 0.25, 1.35, 2.65];
angles.forEach((angle, index) => {
const radius = index === 2 ? 14.8 : 13.7;
const x = Math.cos(angle) * radius;
const z = Math.sin(angle) * radius;
const house = createHouse(
wallColors[(index + (this.policy === "priority" ? 1 : 0)) % wallColors.length],
roofColors[(index + (this.policy === "priority" ? 2 : 0)) % roofColors.length]
);
house.position.set(x, 0.1, z);
house.rotation.y = -angle + Math.PI / 2;
this.group.add(house);
this.housePositions.push(new THREE.Vector3(x, 3.1, z));
const pathLength = radius - 2;
const path = new THREE.Mesh(
new THREE.BoxGeometry(1.15, 0.08, pathLength),
standardMaterial(0xa5a18e)
);
path.position.set(x * 0.51, 0.17, z * 0.51);
path.rotation.y = Math.atan2(x, z);
path.receiveShadow = true;
this.group.add(path);
});
for (let index = 0; index < 7; index++) {
const angle = -2.9 + index * 0.94;
const radius = 17.1 + (index % 2) * 1.1;
const tree = createTree(0.78 + (index % 3) * 0.12);
tree.position.set(
Math.cos(angle) * radius,
0.05,
Math.sin(angle) * radius
);
this.group.add(tree);
}
const queuePadMaterial = new THREE.MeshBasicMaterial({
color: POLICY_COLORS[this.policy],
transparent: true,
opacity: 0.3
});
for (let index = 0; index < 15; index++) {
const position = this.queuePosition(index);
const pad = createQueuePad(position, queuePadMaterial.color);
this.group.add(pad);
}
const policyLabel = makeTextSprite(
this.policy === "fifo" ? "FIFO" : "STRICT PRIORITY",
{
width: 600,
height: 128,
worldWidth: 11,
fontSize: 48,
background:
this.policy === "fifo" ? "rgba(61,114,128,0.94)" : "rgba(238,109,85,0.94)"
}
);
policyLabel.sprite.position.set(0, 10.4, -5.7);
this.group.add(policyLabel.sprite);
const well = new THREE.Group();
const wellBody = new THREE.Mesh(
new THREE.CylinderGeometry(0.9, 1, 0.9, 10),
standardMaterial(0x9a9e91)
);
wellBody.position.y = 0.55;
wellBody.castShadow = true;
well.add(wellBody);
const wellRoof = new THREE.Mesh(
new THREE.ConeGeometry(1.45, 0.8, 4),
standardMaterial(0x70584b)
);
wellRoof.position.y = 1.85;
wellRoof.rotation.y = Math.PI / 4;
wellRoof.castShadow = true;
well.add(wellRoof);
well.position.set(-6, 0.1, -4.5);
this.group.add(well);
}
queuePosition(index) {
const column = index % 5;
const row = Math.floor(index / 5);
return new THREE.Vector3(
2.75 + column * 1.32,
1.18,
4.35 + row * 1.3
);
}
reset() {
for (const job of this.jobs) {
if (job.token) {
this.group.remove(job.token);
}
}
for (const effect of this.effects) {
this.group.remove(effect.mesh);
}
this.jobs = [];
this.queue = [];
this.active = null;
this.effects = [];
this.nextSpawn = 0;
this.completedTurnarounds = [];
this.waitTimes = [];
this.priorityCompletion = {
[PRIORITY.HIGH]: [],
[PRIORITY.NORMAL]: [],
[PRIORITY.LOW]: []
};
this.neglected = {
[PRIORITY.HIGH]: 0,
[PRIORITY.NORMAL]: 0,
[PRIORITY.LOW]: 0
};
this.worker.position.set(0, 0, 2.65);
this.worker.rotation.set(0, 0, 0);
this.board.setText("BACKLOG 00");
}
spawn(task) {
const token = createToken(task.priority);
const source = this.housePositions[task.source].clone();
token.position.copy(source);
this.group.add(token);
const job = {
task,
token,
state: "travel",
travelProgress: 0,
neglected: false,
elapsed: 0
};
this.jobs.push(job);
}
orderedQueue() {
const queue = [...this.queue];
if (this.policy === "fifo") {
queue.sort(
(a, b) =>
a.task.arrival - b.task.arrival || a.task.id - b.task.id
);
} else {
queue.sort(
(a, b) =>
b.task.priority - a.task.priority ||
a.task.arrival - b.task.arrival ||
a.task.id - b.task.id
);
}
return queue;
}
markNeglected(job) {
if (job.neglected) return;
job.neglected = true;
this.neglected[job.task.priority] += 1;
}
dispatch(time) {
if (this.active || this.queue.length === 0) return;
const ordered = this.orderedQueue();
const job = ordered[0];
const queueIndex = this.queue.indexOf(job);
this.queue.splice(queueIndex, 1);
job.state = "active";
job.started = time;
job.elapsed = 0;
this.active = job;
this.waitTimes.push(time - job.task.arrival);
}
completeJob(time) {
const job = this.active;
if (!job) return;
const turnaround = time - job.task.arrival;
this.completedTurnarounds.push(turnaround);
this.priorityCompletion[job.task.priority].push(turnaround);
if (time > job.task.deadline) {
this.markNeglected(job);
}
const burstPosition = job.token.position.clone();
this.group.remove(job.token);
this.createBurst(burstPosition, job.task.priority);
job.state = "complete";
job.token = null;
this.active = null;
}
createBurst(position, priority) {
for (let index = 0; index < 7; index++) {
const mesh = new THREE.Mesh(
burstGeometry,
burstMaterials[priority]
);
mesh.position.copy(position);
this.group.add(mesh);
const angle = (index / 7) * Math.PI * 2;
const velocity = new THREE.Vector3(
Math.cos(angle) * (1.1 + (index % 3) * 0.2),
1.2 + (index % 2) * 0.5,
Math.sin(angle) * (1.1 + (index % 2) * 0.25)
);
this.effects.push({
mesh,
velocity,
life: 0.85
});
}
}
update(time, delta) {
while (
this.nextSpawn < TASK_STREAM.length &&
TASK_STREAM[this.nextSpawn].arrival <= time
) {
this.spawn(TASK_STREAM[this.nextSpawn]);
this.nextSpawn += 1;
}
if (this.active) {
this.active.elapsed += delta;
if (this.active.elapsed >= this.active.task.serviceDuration) {
this.completeJob(time);
}
}
this.dispatch(time);
const orderedQueue = this.orderedQueue();
for (const job of this.jobs) {
if (job.state === "travel") {
job.travelProgress = Math.min(
1,
job.travelProgress + delta / TRAVEL_TIME
);
const queueIndex = orderedQueue.indexOf(job);
const target = this.queuePosition(
queueIndex >= 0 ? queueIndex : Math.min(this.queue.length, 14)
);
const source = this.housePositions[job.task.source];
const eased =
1 - Math.pow(1 - job.travelProgress, 2);
job.token.position.lerpVectors(source, target, eased);
job.token.position.y += Math.sin(time * 6 + job.task.id) * 0.18;
if (job.travelProgress >= 1) {
job.state = "queued";
this.queue.push(job);
}
} else if (job.state === "queued") {
const currentOrder = this.orderedQueue();
const queueIndex = Math.max(0, currentOrder.indexOf(job));
const target = this.queuePosition(queueIndex);
const follow = 1 - Math.exp(-delta * 7);
job.token.position.lerp(target, follow);
job.token.position.y =
target.y + Math.sin(time * 4 + job.task.id) * 0.08;
} else if (job.state === "active") {
const target = new THREE.Vector3(0, 3.05, 1.35);
job.token.position.lerp(target, 1 - Math.exp(-delta * 10));
job.token.scale.setScalar(
1 + Math.sin(time * 8) * 0.08
);
}
if (job.token) {
job.token.rotation.y += delta * 2.3;
if (job.token.userData.ring) {
job.token.userData.ring.rotation.z += delta * 2.8;
}
}
}
// A job becomes neglected as soon as its deadline passes while unfinished.
// A job completed after its deadline is also marked during completion.
for (const job of this.jobs) {
if (
job.state !== "complete" &&
!job.neglected &&
time > job.task.deadline
) {
this.markNeglected(job);
}
}
for (let index = this.effects.length - 1; index >= 0; index--) {
const effect = this.effects[index];
effect.life -= delta;
effect.velocity.y -= 3.6 * delta;
effect.mesh.position.addScaledVector(effect.velocity, delta);
effect.mesh.rotation.x += delta * 3;
effect.mesh.rotation.y += delta * 4;
effect.mesh.scale.setScalar(Math.max(0, effect.life / 0.85));
if (effect.life <= 0) {
this.group.remove(effect.mesh);
this.effects.splice(index, 1);
}
}
const working = Boolean(this.active);
this.worker.userData.torso.position.y =
1.25 + (working ? Math.abs(Math.sin(time * 8)) * 0.07 : 0);
this.worker.userData.leftArm.rotation.x = working
? Math.sin(time * 8) * 0.42
: 0;
this.worker.userData.rightArm.rotation.x = working
? -Math.sin(time * 8) * 0.42
: 0;
}
stats(time) {
const completed = this.completedTurnarounds.length;
const avg = completed
? this.completedTurnarounds.reduce((sum, value) => sum + value, 0) /
completed
: null;
const sorted = [...this.completedTurnarounds].sort((a, b) => a - b);
const p90 = sorted.length
? sorted[Math.floor((sorted.length - 1) * 0.9)]
: null;
const avgWait = this.waitTimes.length
? this.waitTimes.reduce((sum, value) => sum + value, 0) /
this.waitTimes.length
: null;
let overdue = 0;
let backlog = 0;
for (const job of this.jobs) {
if (job.state !== "complete") {
backlog += 1;
if (time > job.task.deadline) overdue += 1;
}
}
const neglected =
this.neglected[PRIORITY.HIGH] +
this.neglected[PRIORITY.NORMAL] +
this.neglected[PRIORITY.LOW];
const priorityAverages = {};
for (const priority of [
PRIORITY.HIGH,
PRIORITY.NORMAL,
PRIORITY.LOW
]) {
const values = this.priorityCompletion[priority];
priorityAverages[priority] = values.length
? values.reduce((sum, value) => sum + value, 0) / values.length
: null;
}
return {
completed,
avg,
p90,
avgWait,
overdue,
backlog,
neglected,
priorityAverages
};
}
}
const fifoWorld = new VillageWorld("fifo", -25);
const priorityWorld = new VillageWorld("priority", 25);
const worlds = [fifoWorld, priorityWorld];
// -------------------------------------------------------------------------
// Camera controls implemented directly, without Three.js addons
// -------------------------------------------------------------------------
const cameraState = {
theta: 0.34,
phi: 0.86,
radius: 82,
target: new THREE.Vector3(0, 1.7, 0)
};
function resetCamera(top = false) {
cameraState.theta = top ? 0 : 0.34;
cameraState.phi = top ? 0.08 : 0.86;
const aspect = Math.max(0.65, sceneWrap.clientWidth / sceneWrap.clientHeight);
const minimumRadius = 52 / (Math.tan(THREE.MathUtils.degToRad(21)) * aspect);
cameraState.radius = THREE.MathUtils.clamp(minimumRadius, 76, 148);
}
function updateCamera() {
const sinPhi = Math.sin(cameraState.phi);
camera.position.set(
cameraState.target.x +
cameraState.radius * sinPhi * Math.sin(cameraState.theta),
cameraState.target.y + cameraState.radius * Math.cos(cameraState.phi),
cameraState.target.z +
cameraState.radius * sinPhi * Math.cos(cameraState.theta)
);
camera.lookAt(cameraState.target);
}
let dragging = false;
let pointerX = 0;
let pointerY = 0;
canvas.addEventListener("pointerdown", (event) => {
dragging = true;
pointerX = event.clientX;
pointerY = event.clientY;
canvas.setPointerCapture(event.pointerId);
});
canvas.addEventListener("pointermove", (event) => {
if (!dragging) return;
const deltaX = event.clientX - pointerX;
const deltaY = event.clientY - pointerY;
cameraState.theta -= deltaX * 0.006;
cameraState.phi = THREE.MathUtils.clamp(
cameraState.phi - deltaY * 0.005,
0.08,
1.25
);
pointerX = event.clientX;
pointerY = event.clientY;
});
function endDrag(event) {
dragging = false;
if (event.pointerId !== undefined && canvas.hasPointerCapture(event.pointerId)) {
canvas.releasePointerCapture(event.pointerId);
}
}
canvas.addEventListener("pointerup", endDrag);
canvas.addEventListener("pointercancel", endDrag);
canvas.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraState.radius = THREE.MathUtils.clamp(
cameraState.radius + event.deltaY * 0.055,
48,
170
);
},
{ passive: false }
);
$("#resetCamera").addEventListener("click", () => resetCamera(false));
$("#topCamera").addEventListener("click", () => resetCamera(true));
// -------------------------------------------------------------------------
// UI and charts
// -------------------------------------------------------------------------
let simulationTime = 0;
let playing = true;
let speed = 1;
let history = [];
let lastHistoryTime = 0;
function formatSeconds(value) {
return value === null ? "—" : `${value.toFixed(1)}s`;
}
function updatePolicyUI(prefix, stats) {
$(`#${prefix}Avg`).textContent = formatSeconds(stats.avg);
$(`#${prefix}P90`).textContent = formatSeconds(stats.p90);
$(`#${prefix}Neglected`).textContent = stats.neglected;
$(`#${prefix}Overdue`).textContent = stats.overdue;
$(`#${prefix}Done`).textContent =
`${stats.completed} of ${TOTAL_JOBS} jobs completed · ` +
`${stats.backlog} unfinished · avg wait ${formatSeconds(stats.avgWait)}`;
const world = prefix === "fifo" ? fifoWorld : priorityWorld;
$(`#${prefix}NegBreakdown`).textContent =
`H ${world.neglected[PRIORITY.HIGH]} · ` +
`N ${world.neglected[PRIORITY.NORMAL]} · ` +
`L ${world.neglected[PRIORITY.LOW]}`;
const h = stats.priorityAverages[PRIORITY.HIGH];
const n = stats.priorityAverages[PRIORITY.NORMAL];
const l = stats.priorityAverages[PRIORITY.LOW];
$(`#${prefix}Priority`).textContent =
`Priority averages: H ${formatSeconds(h)} · ` +
`N ${formatSeconds(n)} · L ${formatSeconds(l)}`;
}
function updateUI() {
const fifoStats = fifoWorld.stats(simulationTime);
const priorityStats = priorityWorld.stats(simulationTime);
updatePolicyUI("fifo", fifoStats);
updatePolicyUI("priority", priorityStats);
fifoWorld.board.setText(
`BACKLOG ${String(fifoStats.backlog).padStart(2, "0")}`
);
priorityWorld.board.setText(
`BACKLOG ${String(priorityStats.backlog).padStart(2, "0")}`
);
const arrived = fifoWorld.nextSpawn;
const completed = fifoStats.completed + priorityStats.completed;
$("#sceneStatus").textContent =
`SIM ${simulationTime.toFixed(0)}s · ${arrived}/${TOTAL_JOBS} arrivals · ` +
`${completed} completed`;
if (fifoStats.avg !== null && priorityStats.avg !== null) {
const averageDifference = priorityStats.avg - fifoStats.avg;
const neglectedDifference = priorityStats.neglected - fifoStats.neglected;
const speedPhrase =
Math.abs(averageDifference) < 0.05
? "the same average completion time"
: `${Math.abs(averageDifference).toFixed(1)}s ${
averageDifference < 0 ? "faster" : "slower"
} average completion`;
const neglectPhrase =
neglectedDifference === 0
? "the same number of neglected jobs"
: `${Math.abs(neglectedDifference)} ${
neglectedDifference < 0 ? "fewer" : "more"
} neglected jobs`;
$("#verdict").textContent =
`Strict Priority currently has ${speedPhrase} and ${neglectPhrase}.`;
} else {
$("#verdict").textContent =
"Both policies are processing the same arrival and task stream.";
}
}
function makePath(key, maxY) {
const left = 43;
const right = 607;
const top = 12;
const bottom = 82;
let path = "";
let penDown = false;
for (const point of history) {
const value = point[key];
if (value === null || value === undefined) {
penDown = false;
continue;
}
const x = left + (point.time / CHART_TIME_LIMIT) * (right - left);
const y = bottom - (value / maxY) * (bottom - top);
path += `${penDown ? "L" : "M"}${x.toFixed(1)},${y.toFixed(1)} `;
penDown = true;
}
return path;
}
function makeChart(keys, maxY, suffix, zeroBased = false) {
const left = 43;
const right = 607;
const top = 12;
const bottom = 82;
const grid = [];
for (let index = 0; index <= 3; index++) {
const y = top + ((bottom - top) * index) / 3;
const value = maxY * (1 - index / 3);
grid.push(
`<line x1="${left}" x2="${right}" y1="${y}" y2="${y}" ` +
`stroke="rgba(23,51,58,0.09)" stroke-width="1" />` +
`<text x="${left - 7}" y="${y + 3}" text-anchor="end" ` +
`font-size="8" fill="#72878b">${value.toFixed(0)}${suffix}</text>`
);
}
const axisLabels = [0, 60, 120, 180, 235].map((time) => {
const x = left + (time / CHART_TIME_LIMIT) * (right - left);
return (
`<text x="${x}" y="101" text-anchor="middle" ` +
`font-size="8" fill="#72878b">${time}s</text>`
);
});
const fifoPath = makePath(keys.fifo, maxY);
const priorityPath = makePath(keys.priority, maxY);
return `
<svg viewBox="0 0 620 108" role="img" aria-label="Policy comparison chart">
${grid.join("")}
${axisLabels.join("")}
<path d="${fifoPath}" fill="none" stroke="#3d7280"
stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round" />
<path d="${priorityPath}" fill="none" stroke="#ee6d55"
stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round" />
</svg>
`;
}
function renderCharts() {
const averageValues = history
.map((point) => point.fifoAvg)
.concat(history.map((point) => point.priorityAvg))
.filter((value) => value !== null);
const averageMax = Math.max(
10,
...averageValues.map((value) => value * 1.12)
);
$("#completionChart").innerHTML = makeChart(
{ fifo: "fifoAvg", priority: "priorityAvg" },
averageMax,
"s"
);
const neglectedMax = Math.max(
4,
...history.map((point) =>
Math.max(point.fifoNeglected, point.priorityNeglected)
)
);
$("#neglectedChart").innerHTML = makeChart(
{ fifo: "fifoNeglected", priority: "priorityNeglected" },
neglectedMax,
""
);
}
function recordHistory() {
const fifoStats = fifoWorld.stats(simulationTime);
const priorityStats = priorityWorld.stats(simulationTime);
history.push({
time: simulationTime,
fifoAvg: fifoStats.avg,
priorityAvg: priorityStats.avg,
fifoNeglected: fifoStats.neglected,
priorityNeglected: priorityStats.neglected
});
renderCharts();
}
function restartSimulation() {
simulationTime = 0;
history = [];
lastHistoryTime = 0;
fifoWorld.reset();
priorityWorld.reset();
recordHistory();
updateUI();
}
$("#playButton").addEventListener("click", () => {
playing = !playing;
$("#playButton").textContent = playing ? "Pause" : "Play";
});
$("#speedButton").addEventListener("click", () => {
speed = speed === 1 ? 2 : speed === 2 ? 4 : 1;
$("#speedButton").textContent = `${speed}× speed`;
});
$("#restartButton").addEventListener("click", restartSimulation);
// -------------------------------------------------------------------------
// Resize and main loop
// -------------------------------------------------------------------------
function resize() {
const width = Math.max(1, sceneWrap.clientWidth);
const height = Math.max(1, sceneWrap.clientHeight);
renderer.setSize(width, height, false);
camera.aspect = width / height;
camera.updateProjectionMatrix();
}
const resizeObserver = new ResizeObserver(resize);
resizeObserver.observe(sceneWrap);
resize();
resetCamera(false);
updateCamera();
recordHistory();
updateUI();
let previousTime = performance.now();
let uiAccumulator = 0;
function animate(now) {
requestAnimationFrame(animate);
const realDelta = Math.min((now - previousTime) / 1000, 0.08);
previousTime = now;
if (playing) {
const simulationDelta = realDelta * BASE_SIM_RATE * speed;
simulationTime += simulationDelta;
fifoWorld.update(simulationTime, simulationDelta);
priorityWorld.update(simulationTime, simulationDelta);
if (simulationTime - lastHistoryTime >= 2) {
lastHistoryTime = simulationTime;
recordHistory();
}
}
updateCamera();
renderer.render(scene, camera);
uiAccumulator += realDelta;
if (uiAccumulator >= 0.15) {
uiAccumulator = 0;
updateUI();
}
}
requestAnimationFrame(animate);
</script>
</body>
</html>
```