Prompt specification
Build or customize the Three.js 3D scene "Student Afternoon Planning 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: Student Afternoon Planning Game
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/student-afternoon-planning-game-x3176
Scene Description Prompt:
Create a single self-contained HTML file using Three.js from cdnjs that shows opportunity costs of mutually exclusive choices. Create a bedroom, sports court, and library linked to a finite afternoon clock. Let users schedule activities and expose travel time and mutually exclusive appointments. Voxel style.
Acceptance criteria: Implement add and remove with local inline JavaScript buttons. Move an activity and verify that the real displayed itinerary and travel-time checks update.
Technical checks: Use local buttons to add or remove activities. Update the visible schedule and travel-time conflict checks after an activity is moved or added.
Return one complete HTML document. The file must run in a sandbox allowing inline scripts and the cdnjs Three.js r160 module. Construct procedural assets, use local event handlers and avoid remote assets, runtime network requests besides Three.js, pointer lock and native form submission. Keep the main requested geometry visible in the initial view.
Working Three.js Starter (student-afternoon-planning-game-x3176):
```html
<!DOCTYPE html>
<html lang="pt-BR">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Voxel de Escolhas — Custo de Oportunidade</title>
<style>
:root {
--ink: #173f3a;
--muted: #6d7e79;
--paper: #f7f4ec;
--panel: #fffdf7;
--line: #dedbd0;
--orange: #ef8354;
--teal: #2a9d8f;
--purple: #7566d8;
--red: #c84c4c;
--green: #247a5a;
--shadow: 0 10px 30px rgba(25, 55, 49, 0.12);
}
* { box-sizing: border-box; }
html, body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
color: var(--ink);
background: #dce9e4;
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
}
button, select { font: inherit; }
button {
cursor: pointer;
}
button:focus-visible,
select:focus-visible,
.activity-card:focus-visible {
outline: 3px solid rgba(42, 157, 143, 0.35);
outline-offset: 2px;
}
#app {
display: grid;
grid-template-columns: minmax(0, 1fr) minmax(390px, 430px);
width: 100%;
height: 100%;
}
#stage {
position: relative;
min-width: 0;
min-height: 0;
overflow: hidden;
background: linear-gradient(180deg, #dcebea 0%, #eaf0df 100%);
}
#stage canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
}
.scene-heading {
position: absolute;
z-index: 3;
top: 22px;
left: 24px;
max-width: min(460px, calc(100% - 48px));
pointer-events: none;
}
.eyebrow {
display: inline-flex;
align-items: center;
gap: 7px;
padding: 6px 9px;
border-radius: 7px;
background: rgba(255, 253, 247, 0.9);
border: 1px solid rgba(23, 63, 58, 0.12);
box-shadow: 0 5px 14px rgba(30, 70, 60, 0.09);
color: var(--teal);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.13em;
text-transform: uppercase;
}
.eyebrow::before {
content: "";
width: 7px;
height: 7px;
border-radius: 2px;
background: var(--orange);
box-shadow: 3px 3px 0 rgba(239, 131, 84, 0.28);
}
.scene-heading h1 {
margin: 10px 0 4px;
font-size: clamp(25px, 3vw, 43px);
line-height: 0.98;
letter-spacing: -0.055em;
text-shadow: 0 2px 0 rgba(255, 255, 255, 0.55);
}
.scene-heading p {
max-width: 420px;
margin: 8px 0 0;
color: #4e6b64;
font-size: 13px;
line-height: 1.45;
}
#clock-hud {
position: absolute;
z-index: 5;
top: 20px;
right: 20px;
width: 224px;
padding: 13px;
border: 1px solid rgba(23, 63, 58, 0.13);
border-radius: 13px;
background: rgba(255, 253, 247, 0.94);
box-shadow: var(--shadow);
backdrop-filter: blur(8px);
}
.clock-line {
display: flex;
align-items: baseline;
justify-content: space-between;
gap: 8px;
}
#clockTime {
font-size: 28px;
font-weight: 850;
letter-spacing: -0.055em;
font-variant-numeric: tabular-nums;
}
.clock-caption {
color: var(--muted);
font-size: 9px;
font-weight: 800;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.progress-track {
height: 6px;
margin: 8px 0 10px;
overflow: hidden;
border-radius: 10px;
background: #e5e5dc;
}
#clockProgress {
width: 0;
height: 100%;
border-radius: inherit;
background: linear-gradient(90deg, var(--orange), var(--teal));
transition: width 0.25s ease;
}
.clock-actions {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 6px;
}
.small-button {
min-height: 30px;
border: 1px solid #d8ddd5;
border-radius: 7px;
background: #f7f8f3;
color: var(--ink);
font-size: 11px;
font-weight: 750;
}
.small-button:hover { background: #eaf1eb; }
#placeChips {
position: absolute;
z-index: 4;
left: 22px;
bottom: 22px;
display: flex;
flex-wrap: wrap;
gap: 7px;
max-width: calc(100% - 44px);
}
.place-chip {
display: flex;
align-items: center;
gap: 7px;
padding: 8px 11px;
border: 1px solid rgba(23, 63, 58, 0.15);
border-radius: 8px;
background: rgba(255, 253, 247, 0.92);
color: var(--ink);
box-shadow: 0 5px 15px rgba(30, 60, 55, 0.1);
font-size: 11px;
font-weight: 800;
}
.place-chip i {
width: 9px;
height: 9px;
border-radius: 2px;
background: var(--dot-color);
box-shadow: 2px 2px 0 rgba(23, 63, 58, 0.15);
}
.place-chip:hover,
.place-chip.active {
transform: translateY(-1px);
border-color: var(--teal);
}
#stageHint {
position: absolute;
z-index: 3;
right: 20px;
bottom: 20px;
padding: 7px 10px;
border-radius: 7px;
background: rgba(23, 63, 58, 0.78);
color: #f8faf4;
font-size: 10px;
font-weight: 650;
pointer-events: none;
}
#toast {
position: absolute;
z-index: 10;
left: 50%;
bottom: 76px;
max-width: calc(100% - 40px);
padding: 11px 15px;
border-radius: 9px;
background: var(--ink);
color: white;
box-shadow: var(--shadow);
font-size: 12px;
font-weight: 700;
text-align: center;
opacity: 0;
transform: translate(-50%, 12px);
transition: opacity 0.2s ease, transform 0.2s ease;
pointer-events: none;
}
#toast.show {
opacity: 1;
transform: translate(-50%, 0);
}
#dashboard {
position: relative;
z-index: 8;
min-width: 0;
overflow-y: auto;
padding: 22px 22px 30px;
border-left: 1px solid rgba(23, 63, 58, 0.14);
background:
linear-gradient(rgba(255, 253, 247, 0.96), rgba(255, 253, 247, 0.96)),
repeating-linear-gradient(45deg, transparent 0 12px, rgba(23, 63, 58, 0.03) 12px 13px);
box-shadow: -10px 0 35px rgba(30, 60, 55, 0.08);
scrollbar-width: thin;
scrollbar-color: #bac8bf transparent;
}
.panel-kicker {
color: var(--teal);
font-size: 10px;
font-weight: 850;
letter-spacing: 0.14em;
text-transform: uppercase;
}
.panel-header h2 {
margin: 5px 0 8px;
font-size: 27px;
line-height: 1;
letter-spacing: -0.045em;
}
.panel-header p {
margin: 0 0 14px;
color: var(--muted);
font-size: 12px;
line-height: 1.5;
}
.status-banner {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
min-height: 39px;
margin: 12px 0;
padding: 9px 11px;
border: 1px solid #b9d7c7;
border-radius: 9px;
background: #e8f5ec;
color: var(--green);
font-size: 10px;
font-weight: 850;
letter-spacing: 0.04em;
}
.status-banner.bad {
border-color: #e7b5ad;
background: #fff0ec;
color: var(--red);
}
.status-banner::before {
content: "";
width: 8px;
height: 8px;
flex: 0 0 auto;
border-radius: 50%;
background: currentColor;
box-shadow: 0 0 0 4px rgba(42, 157, 143, 0.12);
}
.summary-grid {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 7px;
margin: 10px 0 17px;
}
.metric {
padding: 10px 9px;
border: 1px solid var(--line);
border-radius: 10px;
background: #fffefa;
}
.metric strong {
display: block;
font-size: 20px;
line-height: 1;
letter-spacing: -0.04em;
font-variant-numeric: tabular-nums;
}
.metric span {
display: block;
margin-top: 5px;
color: var(--muted);
font-size: 9px;
font-weight: 750;
text-transform: uppercase;
letter-spacing: 0.06em;
}
section {
margin-top: 17px;
}
.section-title {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
margin: 0 0 8px;
font-size: 12px;
font-weight: 850;
letter-spacing: 0.02em;
}
.section-title small {
color: var(--muted);
font-size: 9px;
font-weight: 650;
}
.add-box {
padding: 12px;
border: 1px solid #d8ddd4;
border-radius: 12px;
background: #f1f4eb;
}
.form-grid {
display: grid;
grid-template-columns: 1fr 0.78fr;
gap: 8px;
}
.field label {
display: block;
margin: 0 0 5px;
color: #5d716a;
font-size: 9px;
font-weight: 800;
letter-spacing: 0.07em;
text-transform: uppercase;
}
select {
width: 100%;
height: 39px;
padding: 0 31px 0 10px;
border: 1px solid #cad2c9;
border-radius: 8px;
background: #fffefa;
color: var(--ink);
font-size: 11px;
font-weight: 700;
}
#addForm > button {
width: 100%;
height: 41px;
margin-top: 8px;
border: 0;
border-radius: 8px;
background: var(--ink);
color: white;
box-shadow: 0 4px 0 #0e2d29;
font-size: 12px;
font-weight: 850;
}
#addForm > button:hover { background: #22584f; }
#addForm > button:active { transform: translateY(2px); box-shadow: 0 2px 0 #0e2d29; }
.hint {
margin: 8px 1px 0;
color: var(--muted);
font-size: 10px;
line-height: 1.45;
}
.timeline-grid {
display: grid;
grid-template-columns: repeat(5, minmax(0, 1fr));
gap: 6px;
}
.slot {
position: relative;
min-width: 0;
min-height: 45px;
padding: 7px 5px;
overflow: hidden;
border: 1px dashed #c9d0c7;
border-radius: 7px;
background: #fffefa;
color: #64756f;
text-align: left;
}
.slot::after {
content: "";
position: absolute;
left: 0;
right: 0;
bottom: 0;
height: 4px;
background: var(--slot-color, transparent);
}
.slot.busy {
border-style: solid;
border-color: #b8ccc2;
background: #eef5ec;
}
.slot.selected {
border-color: var(--teal);
box-shadow: inset 0 0 0 1px var(--teal);
}
.slot.drop-target {
transform: translateY(-2px);
border-color: var(--orange);
background: #fff0e7;
}
.slot b {
display: block;
font-size: 10px;
font-variant-numeric: tabular-nums;
}
.slot span {
display: block;
margin-top: 4px;
overflow: hidden;
color: #8a9792;
font-size: 8px;
white-space: nowrap;
text-overflow: ellipsis;
}
.agenda-list {
display: grid;
gap: 8px;
}
.activity-card {
position: relative;
padding: 10px 10px 9px 13px;
overflow: hidden;
border: 1px solid #d9ddd5;
border-radius: 10px;
background: #fffefa;
box-shadow: 0 3px 0 rgba(23, 63, 58, 0.03);
cursor: grab;
}
.activity-card::before {
content: "";
position: absolute;
inset: 0 auto 0 0;
width: 5px;
background: var(--accent);
}
.activity-card.selected {
border-color: var(--accent);
box-shadow: 0 0 0 2px color-mix(in srgb, var(--accent) 17%, transparent);
}
.activity-card:active { cursor: grabbing; }
.card-top {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 8px;
}
.card-title {
margin: 0;
font-size: 12px;
font-weight: 850;
}
.card-place {
margin-top: 3px;
color: var(--muted);
font-size: 9px;
font-weight: 700;
}
.card-time {
flex: 0 0 auto;
padding: 4px 6px;
border-radius: 5px;
background: color-mix(in srgb, var(--accent) 13%, white);
color: var(--ink);
font-size: 9px;
font-weight: 850;
font-variant-numeric: tabular-nums;
}
.card-actions {
display: flex;
gap: 5px;
margin-top: 9px;
}
.card-actions button {
min-height: 27px;
padding: 0 8px;
border: 1px solid #d7ddd5;
border-radius: 6px;
background: #f7f8f3;
color: var(--ink);
font-size: 9px;
font-weight: 800;
}
.card-actions button:hover:not(:disabled) {
border-color: #9cb9af;
background: #eaf2ec;
}
.card-actions button:disabled {
cursor: not-allowed;
opacity: 0.38;
}
.card-actions .remove {
margin-left: auto;
color: var(--red);
}
.itinerary {
padding: 4px 0;
}
.itin-row {
display: grid;
grid-template-columns: 54px 15px 1fr;
align-items: center;
gap: 8px;
min-height: 45px;
}
.itin-time {
color: var(--ink);
font-size: 10px;
font-weight: 850;
font-variant-numeric: tabular-nums;
text-align: right;
}
.itin-time small {
display: block;
margin-top: 2px;
color: #9aa49f;
font-size: 8px;
font-weight: 700;
}
.itin-dot {
width: 11px;
height: 11px;
border: 2px solid white;
border-radius: 3px;
background: var(--dot);
box-shadow: 0 0 0 1px rgba(23, 63, 58, 0.18);
}
.itin-copy b {
display: block;
font-size: 11px;
}
.itin-copy span {
display: block;
margin-top: 3px;
color: var(--muted);
font-size: 9px;
}
.itin-leg {
display: flex;
align-items: center;
gap: 6px;
min-height: 28px;
margin-left: 61px;
padding-left: 17px;
border-left: 2px dotted #b9c5bd;
color: var(--green);
font-size: 9px;
font-weight: 700;
}
.itin-leg.bad {
border-left-color: #e2a097;
color: var(--red);
}
.itin-leg span {
font-size: 13px;
line-height: 1;
}
.check-list {
display: grid;
gap: 6px;
}
.check-row {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 10px;
padding: 8px 9px;
border: 1px solid #cce0d3;
border-radius: 8px;
background: #eef8f0;
color: var(--green);
}
.check-row.bad {
border-color: #efc0b7;
background: #fff0ec;
color: var(--red);
}
.check-row strong {
font-size: 9px;
line-height: 1.35;
}
.check-row span {
flex: 0 0 auto;
max-width: 145px;
font-size: 8px;
line-height: 1.4;
text-align: right;
font-variant-numeric: tabular-nums;
}
.opportunity {
margin-top: 18px;
padding: 13px;
border: 1px solid #dfd2bd;
border-radius: 12px;
background: #fff5df;
}
.opportunity h3 {
margin: 0 0 6px;
color: #805522;
font-size: 11px;
letter-spacing: 0.05em;
text-transform: uppercase;
}
.opportunity p {
margin: 0;
color: #765a35;
font-size: 11px;
line-height: 1.45;
}
.opportunity .opp-meta {
display: block;
margin-top: 8px;
color: #9a7b4f;
font-size: 9px;
font-weight: 750;
}
.restore-button {
width: 100%;
height: 36px;
margin-top: 10px;
border: 1px solid #cbd5cc;
border-radius: 8px;
background: #fffefa;
color: var(--ink);
font-size: 10px;
font-weight: 800;
}
.restore-button:hover { background: #eef3ea; }
.empty {
padding: 15px;
border: 1px dashed #cbd2ca;
border-radius: 9px;
color: var(--muted);
font-size: 10px;
text-align: center;
}
@media (max-width: 900px) {
#app {
grid-template-columns: 1fr;
grid-template-rows: 54vh 46vh;
}
#dashboard {
padding: 17px 17px 28px;
border-top: 1px solid rgba(23, 63, 58, 0.14);
border-left: 0;
box-shadow: 0 -8px 24px rgba(30, 60, 55, 0.08);
}
.scene-heading {
top: 14px;
left: 15px;
}
.scene-heading h1 { font-size: 27px; }
.scene-heading p { display: none; }
#clock-hud {
top: 12px;
right: 12px;
width: 178px;
padding: 9px;
}
#clockTime { font-size: 22px; }
#placeChips { left: 13px; bottom: 13px; }
#stageHint { display: none; }
}
@media (max-width: 520px) {
#app { grid-template-rows: 48vh 52vh; }
.scene-heading h1 { font-size: 23px; }
.scene-heading .eyebrow { font-size: 8px; }
#clock-hud { width: 150px; }
.clock-caption { display: none; }
.place-chip { padding: 6px 8px; font-size: 9px; }
.summary-grid { grid-template-columns: repeat(3, 1fr); }
}
</style>
</head>
<body>
<main id="app">
<section id="stage" aria-label=" Diorama tridimensional em estilo voxel">
<div class="scene-heading">
<div class="eyebrow">Laboratório de escolhas · 13:00—18:00</div>
<h1>Uma tarde.<br>Um lugar por vez.</h1>
<p>Cada atividade bloqueia tempo e exige deslocamento. Sobreposições revelam o custo de oportunidade de escolher uma rota.</p>
</div>
<div id="clock-hud">
<div class="clock-line">
<span id="clockTime">13:00</span>
<span class="clock-caption">Relógio da tarde</span>
</div>
<div class="progress-track"><div id="clockProgress"></div></div>
<div class="clock-actions">
<button id="clockToggle" class="small-button" type="button">Pausar</button>
<button id="clockReset" class="small-button" type="button">Reiniciar</button>
</div>
</div>
<div id="placeChips" aria-label="Escolher local para adicionar">
<button class="place-chip" type="button" data-place="bedroom" style="--dot-color:#ef8354"><i></i>Quarto</button>
<button class="place-chip" type="button" data-place="court" style="--dot-color:#2a9d8f"><i></i>Quadra</button>
<button class="place-chip" type="button" data-place="library" style="--dot-color:#7566d8"><i></i>Biblioteca</button>
</div>
<div id="stageHint">Arraste para girar · roda para zoom · botão direito para mover</div>
<div id="toast" role="status" aria-live="polite"></div>
</section>
<aside id="dashboard">
<header class="panel-header">
<div class="panel-kicker">Escolhas mutuamente exclusivas</div>
<h2>Monte seu itinerário</h2>
<p>Adicione atividades, arraste os cartões ou use os botões de 30 minutos. O relógio e as checagens são atualizados em tempo real.</p>
</header>
<div id="globalStatus" class="status-banner">ITINERÁRIO VIÁVEL</div>
<div class="summary-grid">
<div class="metric"><strong id="activityCount">3</strong><span>atividades</span></div>
<div class="metric"><strong id="travelTotal">35 min</strong><span>deslocamento</span></div>
<div class="metric"><strong id="pendingTotal">0</strong><span>pendências</span></div>
</div>
<section>
<h3 class="section-title">Adicionar atividade <small>13:00—18:00</small></h3>
<form id="addForm" class="add-box">
<div class="form-grid">
<div class="field">
<label for="activityType">Atividade e local</label>
<select id="activityType">
<option value="bedroom">Foco no quarto</option>
<option value="court">Jogo na quadra</option>
<option value="library" selected>Leitura na biblioteca</option>
</select>
</div>
<div class="field">
<label for="startTime">Início</label>
<select id="startTime"></select>
</div>
</div>
<button type="button" id="addActivity">+ Adicionar atividade</button>
</form>
<p class="hint">Dica: a opção inicial começa às 14:00 para mostrar como uma nova escolha pode entrar em conflito.</p>
</section>
<section>
<h3 class="section-title">Linha do tempo <small>clique ou arraste para mover</small></h3>
<div id="timeline" class="timeline-grid"></div>
<p class="hint">Selecione um cartão e clique em outro horário, ou arraste o cartão diretamente para a grade.</p>
</section>
<section>
<h3 class="section-title">Cartões editáveis <small>movimento em blocos de 30 min</small></h3>
<div id="agendaList" class="agenda-list"></div>
</section>
<section>
<h3 class="section-title">Itinerário real</h3>
<div id="itinerary" class="itinerary"></div>
</section>
<section>
<h3 class="section-title">Checagens de conflito e viagem</h3>
<div id="checks" class="check-list"></div>
</section>
<section class="opportunity">
<h3>Custo de oportunidade</h3>
<p id="oppText"></p>
<span id="oppMeta" class="opp-meta"></span>
</section>
<button id="restoreDemo" class="restore-button" type="button">Restaurar o exemplo inicial</button>
</aside>
</main>
<script type="module">
import * as THREE from "https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
const $ = (selector) => document.querySelector(selector);
const stage = $("#stage");
const START = 13 * 60;
const END = 18 * 60;
const STEP = 30;
const locations = {
bedroom: { label: "Quarto", color: "#ef8354", anchor: new THREE.Vector3(-6.2, 0, -2.05) },
court: { label: "Quadra", color: "#2a9d8f", anchor: new THREE.Vector3(6.0, 0, 1.0) },
library: { label: "Biblioteca", color: "#7566d8", anchor: new THREE.Vector3(0, 0, -2.8) }
};
const templates = {
bedroom: { title: "Foco silencioso", duration: 90, color: "#ef8354" },
court: { title: "Jogo na quadra", duration: 60, color: "#2a9d8f" },
library: { title: "Leitura guiada", duration: 60, color: "#7566d8" }
};
const travel = {
bedroom: { bedroom: 0, court: 20, library: 15 },
court: { bedroom: 20, court: 0, library: 15 },
library: { bedroom: 15, court: 15, library: 0 }
};
let nextId = 10;
let selectedId = null;
let draggedId = null;
let simMinutes = START;
let clockRunning = true;
let toastTimer = null;
function defaultSchedule() {
return [
{ id: 1, type: "bedroom", location: "bedroom", title: "Foco silencioso", start: 13 * 60, duration: 90, color: "#ef8354" },
{ id: 2, type: "court", location: "court", title: "Jogo na quadra", start: 15 * 60, duration: 60, color: "#2a9d8f" },
{ id: 3, type: "library", location: "library", title: "Leitura guiada", start: 16 * 60 + 30, duration: 60, color: "#7566d8" }
];
}
let schedule = defaultSchedule();
function formatTime(minutes) {
const h = Math.floor(minutes / 60);
const m = minutes % 60;
return `${String(h).padStart(2, "0")}:${String(m).padStart(2, "0")}`;
}
function showToast(message) {
const toast = $("#toast");
toast.textContent = message;
toast.classList.add("show");
clearTimeout(toastTimer);
toastTimer = setTimeout(() => toast.classList.remove("show"), 2600);
}
function analyzeSchedule() {
const sorted = [...schedule].sort((a, b) => a.start - b.start || a.id - b.id);
const checks = [];
for (let i = 0; i < sorted.length - 1; i++) {
const a = sorted[i];
const b = sorted[i + 1];
const overlap = Math.max(0, Math.min(a.start + a.duration, b.start + b.duration) - Math.max(a.start, b.start));
const gap = Math.max(0, b.start - (a.start + a.duration));
const required = travel[a.location][b.location];
checks.push({
a,
b,
overlap,
gap,
required,
ok: overlap === 0 && gap >= required,
issue: overlap > 0 ? "overlap" : (gap < required ? "travel" : null)
});
}
let disputedMinutes = 0;
for (let minute = START; minute < END; minute++) {
const simultaneous = schedule.filter((activity) => activity.start <= minute && activity.start + activity.duration > minute).length;
if (simultaneous > 1) disputedMinutes++;
}
const overlapPairs = checks.filter((check) => check.overlap > 0);
const travelIssues = checks.filter((check) => check.issue === "travel");
const totalTravel = checks.reduce((sum, check) => sum + check.required, 0);
return {
sorted,
checks,
overlapPairs,
travelIssues,
totalTravel,
disputedMinutes,
pending: overlapPairs.length + travelIssues.length
};
}
function renderTimeline(analysis) {
const timeline = $("#timeline");
let html = "";
for (let slot = START; slot < END; slot += STEP) {
const slotEnd = slot + STEP;
const occupying = analysis.sorted.filter((activity) => activity.start < slotEnd && activity.start + activity.duration > slot);
const selected = schedule.find((activity) => activity.id === selectedId && activity.start === slot);
const busyClass = occupying.length ? "busy" : "";
const selectedClass = selected ? "selected" : "";
const color = occupying[0]?.color || "transparent";
const label = occupying.length ? occupying.map((activity) => locations[activity.location].label).join(" + ") : "livre";
const title = occupying.length
? occupying.map((activity) => `${activity.title}: ${formatTime(activity.start)}—${formatTime(activity.start + activity.duration)}`).join("; ")
: `${formatTime(slot)}: livre`;
html += `
<button type="button" class="slot ${busyClass} ${selectedClass}" data-slot="${slot}" style="--slot-color:${color}" title="${title}" aria-label="${title}">
<b>${formatTime(slot)}</b>
<span>${label}</span>
</button>`;
}
timeline.innerHTML = html;
}
function renderCards(analysis) {
const list = $("#agendaList");
if (!analysis.sorted.length) {
list.innerHTML = `<div class="empty">Nenhuma atividade. Adicione uma escolha para começar.</div>`;
return;
}
list.innerHTML = analysis.sorted.map((activity) => {
const selected = activity.id === selectedId ? "selected" : "";
const canMoveEarlier = activity.start - STEP >= START;
const canMoveLater = activity.start + activity.duration + STEP <= END;
return `
<article class="activity-card ${selected}" data-id="${activity.id}" draggable="true" tabindex="0" style="--accent:${activity.color}" aria-label="${activity.title}, ${formatTime(activity.start)} a ${formatTime(activity.start + activity.duration)}">
<div class="card-top">
<div>
<h4 class="card-title">${activity.title}</h4>
<div class="card-place">${locations[activity.location].label} · ${activity.duration} min</div>
</div>
<span class="card-time">${formatTime(activity.start)}—${formatTime(activity.start + activity.duration)}</span>
</div>
<div class="card-actions">
<button type="button" data-action="earlier" ${canMoveEarlier ? "" : "disabled"} title="Mover 30 minutos para mais cedo">← 30 min</button>
<button type="button" data-action="later" ${canMoveLater ? "" : "disabled"} title="Mover 30 minutos para mais tarde">30 min →</button>
<button type="button" class="remove" data-action="remove" title="Remover atividade">Remover</button>
</div>
</article>`;
}).join("");
}
function renderItinerary(analysis) {
const container = $("#itinerary");
if (!analysis.sorted.length) {
container.innerHTML = `<div class="empty">O itinerário está vazio.</div>`;
return;
}
let html = "";
analysis.sorted.forEach((activity, index) => {
if (index > 0) {
const previous = analysis.sorted[index - 1];
const check = analysis.checks.find((item) => item.a.id === previous.id && item.b.id === activity.id);
const samePlace = previous.location === activity.location;
let legText;
if (check.overlap > 0) {
legText = `Sobreposição de ${check.overlap} min · viagem impossível`;
} else if (samePlace) {
legText = `${check.gap} min de pausa · mesmo local`;
} else {
legText = `${check.gap} min livres · ${check.required} min de viagem necessária`;
}
html += `
<div class="itin-leg ${check.ok ? "" : "bad"}">
<span>↓</span>${legText}
</div>`;
}
html += `
<div class="itin-row">
<div class="itin-time">${formatTime(activity.start)}<small>até ${formatTime(activity.start + activity.duration)}</small></div>
<div class="itin-dot" style="--dot:${activity.color}"></div>
<div class="itin-copy">
<b>${activity.title}</b>
<span>${locations[activity.location].label} · ${activity.duration} min</span>
</div>
</div>`;
});
container.innerHTML = html;
}
function renderChecks(analysis) {
const container = $("#checks");
if (!analysis.checks.length) {
container.innerHTML = `<div class="empty">Adicione outra atividade para comparar a próxima viagem.</div>`;
return;
}
container.innerHTML = analysis.checks.map((check) => {
let detail;
if (check.overlap > 0) {
detail = `${check.overlap} min de sobreposição; escolha uma das atividades`;
} else if (check.gap < check.required) {
detail = `${check.gap} min livres / ${check.required} min necessários`;
} else {
detail = `${check.gap} min livres / ${check.required} min necessários`;
}
return `
<div class="check-row ${check.ok ? "" : "bad"}">
<strong>${check.ok ? "✓" : "!"} ${locations[check.a.location].label} → ${locations[check.b.location].label}</strong>
<span>${detail}</span>
</div>`;
}).join("");
}
function renderSchedule() {
const analysis = analyzeSchedule();
$("#activityCount").textContent = analysis.sorted.length;
$("#travelTotal").textContent = `${analysis.totalTravel} min`;
$("#pendingTotal").textContent = analysis.pending;
const status = $("#globalStatus");
if (analysis.pending) {
status.textContent = `ATENÇÃO: ${analysis.pending} ${analysis.pending === 1 ? "pendência" : "pendências"} no itinerário`;
status.classList.add("bad");
} else {
status.textContent = "ITINERÁRIO VIÁVEL";
status.classList.remove("bad");
}
if (analysis.disputedMinutes > 0) {
$("#oppText").textContent = `${analysis.disputedMinutes} min estão disputados por duas ou mais atividades. Escolher uma delas torna as demais inacessíveis nesse intervalo.`;
} else if (analysis.travelIssues.length) {
$("#oppText").textContent = "Não há sobreposição direta, mas uma transição não tem tempo suficiente para o deslocamento. A atividade seguinte pode ser perdida.";
} else {
$("#oppText").textContent = "Nenhum minuto é disputado diretamente. As pausas preservam as três escolhas e os deslocamentos cabem na tarde.";
}
$("#oppMeta").textContent = `${analysis.checks.length} transições avaliadas · ${analysis.pending} pendência(s) · ${analysis.totalTravel} min de viagem`;
renderTimeline(analysis);
renderCards(analysis);
renderItinerary(analysis);
renderChecks(analysis);
updateSceneSchedule(analysis);
}
function moveActivity(id, newStart) {
const activity = schedule.find((item) => item.id === id);
if (!activity) return;
if (newStart < START || newStart + activity.duration > END) {
showToast("Esse movimento ultrapassaria o relógio da tarde.");
return;
}
activity.start = newStart;
selectedId = id;
renderSchedule();
showToast(`${activity.title} movido para ${formatTime(newStart)}. Itinerário e viagens recalculados.`);
}
function populateStartTimes(type, preferred) {
const duration = templates[type].duration;
const select = $("#startTime");
const valid = [];
for (let minute = START; minute + duration <= END; minute += STEP) valid.push(minute);
let chosen = Number(preferred);
if (!valid.includes(chosen)) chosen = valid[0];
select.innerHTML = valid.map((minute) => `<option value="${minute}">${formatTime(minute)}</option>`).join("");
select.value = String(chosen);
}
// ---------- Three.js: diorama voxel ----------
const scene = new THREE.Scene();
scene.background = new THREE.Color("#dce9e4");
scene.fog = new THREE.Fog("#dce9e4", 30, 55);
const camera = new THREE.OrthographicCamera(-12, 12, 9, -9, 0.1, 100);
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 1.8));
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.05;
stage.prepend(renderer.domElement);
const hemi = new THREE.HemisphereLight("#f6fff4", "#687c71", 2.15);
scene.add(hemi);
const sun = new THREE.DirectionalLight("#fff4dc", 3.2);
sun.position.set(-9, 17, 11);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -18;
sun.shadow.camera.right = 18;
sun.shadow.camera.top = 15;
sun.shadow.camera.bottom = -15;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 45;
sun.shadow.bias = -0.0007;
scene.add(sun);
const fill = new THREE.DirectionalLight("#b9e9e5", 0.75);
fill.position.set(12, 7, -8);
scene.add(fill);
function material(color, extra = {}) {
return new THREE.MeshStandardMaterial({ color, roughness: 0.88, metalness: 0, ...extra });
}
function box(parent, width, height, depth, color, x = 0, y = 0, z = 0, extra = {}) {
const mesh = new THREE.Mesh(
new THREE.BoxGeometry(width, height, depth),
material(color, extra)
);
mesh.position.set(x, y, z);
mesh.castShadow = true;
mesh.receiveShadow = true;
parent.add(mesh);
return mesh;
}
function makeLabel(text, color = "#173f3a", background = "rgba(255,253,247,0.94)", width = 3.4) {
const canvas = document.createElement("canvas");
canvas.width = 512;
canvas.height = 128;
const context = canvas.getContext("2d");
context.fillStyle = background;
context.fillRect(8, 8, 496, 112);
context.strokeStyle = "rgba(23,63,58,0.22)";
context.lineWidth = 5;
context.strokeRect(8, 8, 496, 112);
context.fillStyle = color;
context.font = "800 48px system-ui, sans-serif";
context.textAlign = "center";
context.textBaseline = "middle";
context.fillText(text, 256, 66);
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
const sprite = new THREE.Sprite(new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthWrite: false
}));
sprite.scale.set(width, width * 0.25, 1);
return sprite;
}
function horizontalPath(x1, x2, z, width = 0.9) {
const length = Math.abs(x2 - x1);
box(scene, length, 0.055, width, "#d9c8a5", (x1 + x2) / 2, 0.065, z);
const dashCount = Math.max(1, Math.floor(length / 1.35));
for (let i = 0; i < dashCount; i++) {
const x = x1 + (x2 - x1) * ((i + 0.5) / dashCount);
box(scene, 0.42, 0.025, 0.08, "#f4e9ce", x, 0.105, z);
}
}
function verticalPath(z1, z2, x, width = 0.9) {
const length = Math.abs(z2 - z1);
box(scene, width, 0.055, length, "#d9c8a5", x, 0.065, (z1 + z2) / 2);
const dashCount = Math.max(1, Math.floor(length / 1.35));
for (let i = 0; i < dashCount; i++) {
const z = z1 + (z2 - z1) * ((i + 0.5) / dashCount);
box(scene, 0.08, 0.025, 0.42, "#f4e9ce", x, 0.105, z);
}
}
function buildBedroom() {
const group = new THREE.Group();
group.position.set(-6.3, 0, -3.6);
scene.add(group);
box(group, 5.4, 0.28, 4.4, "#d8c8a7", 0, 0.08, 0);
box(group, 5.4, 2.8, 0.24, "#efd8c4", 0, 1.48, -2.08);
box(group, 0.24, 2.8, 4.4, "#efd8c4", -2.58, 1.48, 0);
box(group, 0.24, 1.0, 4.4, "#e4c9b4", 2.58, 0.58, 0);
box(group, 5.55, 0.18, 0.22, "#b97758", 0, 2.93, -2.08);
box(group, 0.22, 0.18, 4.45, "#b97758", -2.58, 2.93, 0);
box(group, 1.55, 1.3, 0.13, "#7db8c7", -1.25, 1.65, -1.92, { emissive: "#315d69", emissiveIntensity: 0.08 });
box(group, 0.09, 1.3, 0.17, "#fffaf0", -1.25, 1.65, -1.84);
box(group, 1.55, 0.09, 0.17, "#fffaf0", -1.25, 1.65, -1.84);
box(group, 2.25, 0.42, 1.7, "#8d654c", -0.85, 0.43, -0.45);
box(group, 2.05, 0.27, 1.52, "#f3eee2", -0.85, 0.78, -0.45);
box(group, 1.55, 0.16, 1.55, "#ef8354", -0.63, 0.97, -0.43);
box(group, 0.72, 0.18, 1.13, "#fff8e9", -1.45, 1.01, -0.45);
box(group, 1.65, 0.08, 1.25, "#779e91", 1.25, 0.28, 0.55);
box(group, 1.45, 0.16, 0.72, "#a36b42", 1.25, 0.9, -0.95);
box(group, 0.12, 0.72, 0.12, "#604638", 0.62, 0.61, -0.95);
box(group, 0.12, 0.72, 0.12, "#604638", 1.88, 0.61, -0.95);
box(group, 0.65, 0.08, 0.42, "#f0d36f", 1.45, 1.04, -0.95);
box(group, 0.08, 0.46, 0.08, "#405c56", 0.72, 1.25, -0.95);
box(group, 0.48, 0.3, 0.42, "#f0d36f", 0.72, 1.58, -0.95);
const label = makeLabel("QUARTO", "#9b4e2f");
label.position.set(0, 3.65, 0);
group.add(label);
}
function buildLibrary() {
const group = new THREE.Group();
group.position.set(0, 0, -4.15);
scene.add(group);
box(group, 5.5, 0.28, 4.25, "#d7c7a7", 0, 0.08, 0);
box(group, 5.5, 3.15, 0.24, "#e6dcc7", 0, 1.65, -2.02);
box(group, 0.24, 3.15, 4.25, "#d6c6a8", -2.63, 1.65, 0);
box(group, 0.24, 1.15, 4.25, "#d6c6a8", 2.63, 0.65, 0);
box(group, 5.65, 0.18, 0.25, "#806247", 0, 3.22, -2.02);
function shelf(x) {
box(group, 1.45, 2.05, 0.38, "#76583f", x, 1.22, -1.65);
const colors = ["#ef8354", "#2a9d8f", "#7566d8", "#e9c46a", "#e76f51"];
for (let row = 0; row < 3; row++) {
const y = 0.66 + row * 0.53;
box(group, 1.23, 0.09, 0.48, "#9c7653", x, y, -1.55);
for (let book = 0; book < 6; book++) {
const h = 0.25 + ((book + row) % 3) * 0.055;
box(group, 0.13, h, 0.25, colors[(book + row) % colors.length], x - 0.48 + book * 0.19, y + h / 2 + 0.04, -1.49);
}
}
}
shelf(-1.65);
shelf(1.65);
box(group, 1.85, 0.15, 1.15, "#b97848", 0, 0.98, 0.15);
box(group, 0.18, 0.78, 0.18, "#765238", -0.65, 0.55, 0.15);
box(group, 0.18, 0.78, 0.18, "#765238", 0.65, 0.55, 0.15);
box(group, 0.68, 0.08, 0.52, "#f5edda", 0, 1.1, 0.1);
box(group, 0.42, 0.42, 0.08, "#7566d8", 0.16, 1.19, 0.1);
box(group, 0.58, 0.12, 0.58, "#7566d8", 0, 0.48, 0.9);
const label = makeLabel("BIBLIOTECA", "#5544aa");
label.position.set(0, 3.85, 0);
group.add(label);
}
function buildCourt() {
const group = new THREE.Group();
group.position.set(6, 0, 0.8);
scene.add(group);
box(group, 7.3, 0.3, 6.3, "#3b8f88", 0, 0.08, 0);
box(group, 6.65, 0.05, 5.65, "#5aa69b", 0, 0.255, 0);
const white = "#f5f1de";
box(group, 6.65, 0.035, 0.08, white, 0, 0.31, -2.8);
box(group, 6.65, 0.035, 0.08, white, 0, 0.31, 2.8);
box(group, 0.08, 0.035, 5.6, white, -3.3, 0.31, 0);
box(group, 0.08, 0.035, 5.6, white, 3.3, 0.31, 0);
box(group, 0.07, 0.035, 5.6, white, 0, 0.31, 0);
box(group, 0.95, 0.04, 2.15, "#72b4a6", 2.55, 0.32, -1.65);
box(group, 0.95, 0.04, 2.15, "#72b4a6", 2.55, 0.32, 1.65);
function hoop(z) {
box(group, 0.12, 1.65, 0.12, "#f2e7cc", -2.72, 1.1, z);
box(group, 0.62, 0.82, 0.1, "#f2e7cc", -2.42, 1.75, z);
box(group, 0.42, 0.06, 0.35, "#ef8354", -2.12, 1.45, z);
}
hoop(-2.35);
hoop(2.35);
const label = makeLabel("QUADRA", "#176f66");
label.position.set(0, 3.25, 0);
group.add(label);
}
function buildClock() {
const group = new THREE.Group();
group.position.set(0, 0, 2.7);
scene.add(group);
box(group, 1.75, 0.32, 1.25, "#9b7954", 0, 0.25, 0);
box(group, 1.42, 2.05, 0.9, "#c39a67", 0, 1.35, 0);
box(group, 1.82, 1.82, 0.2, "#405b57", 0, 2.35, 0.42);
box(group, 1.62, 1.62, 0.1, "#fff7df", 0, 2.35, 0.56);
for (let i = 0; i < 12; i++) {
const angle = i / 12 * Math.PI * 2;
const x = Math.sin(angle) * 0.64;
const y = Math.cos(angle) * 0.64;
const marker = box(group, i % 3 === 0 ? 0.1 : 0.065, i % 3 === 0 ? 0.16 : 0.1, 0.06, "#38504d", x, 2.35 + y, 0.64);
marker.rotation.z = -angle;
}
const hourPivot = new THREE.Group();
hourPivot.position.set(0, 2.35, 0.7);
box(hourPivot, 0.13, 0.64, 0.07, "#28443f", 0, 0.25, 0);
group.add(hourPivot);
const minutePivot = new THREE.Group();
minutePivot.position.set(0, 2.35, 0.77);
box(minutePivot, 0.085, 0.88, 0.06, "#ef8354", 0, 0.36, 0);
group.add(minutePivot);
box(group, 0.17, 0.17, 0.1, "#ef8354", 0, 2.35, 0.84);
const label = makeLabel("13:00—18:00", "#335c54", "rgba(255,247,223,0.96)", 3.0);
label.position.set(0, 3.75, 0);
group.add(label);
return { hourPivot, minutePivot };
}
function buildTree(x, z, scale = 1) {
const group = new THREE.Group();
group.position.set(x, 0, z);
group.scale.setScalar(scale);
scene.add(group);
box(group, 0.28, 1.3, 0.28, "#7f5a3c", 0, 0.67, 0);
box(group, 1.25, 0.8, 1.15, "#4d8b62", 0, 1.55, 0);
box(group, 0.78, 0.62, 0.82, "#66a46e", -0.18, 2.12, 0.03);
box(group, 0.6, 0.5, 0.58, "#7ab47a", 0.45, 1.78, -0.05);
}
function buildWorld() {
box(scene, 24, 0.72, 17, "#6d8f73", 0, -0.52, 0);
box(scene, 23.5, 0.18, 16.5, "#9fb982", 0, -0.08, 0);
horizontalPath(-6.3, 0, -3.0, 1.05);
verticalPath(-3.0, 2.7, 0, 1.05);
horizontalPath(-6.3, 0, 2.7, 1.05);
verticalPath(-3.0, 2.7, -6.3, 0.8);
horizontalPath(0, 6, 2.7, 1.05);
verticalPath(0.8, 2.7, 6, 1.05);
for (let x = -10; x <= 10; x += 2.5) {
box(scene, 0.035, 0.015, 15.5, "#93aa7b", x, 0.025, 0);
}
for (let z = -7; z <= 7; z += 2.5) {
box(scene, 23, 0.015, 0.035, "#93aa7b", 0, 0.026, z);
}
buildBedroom();
buildLibrary();
buildCourt();
buildTree(-10.3, -5.7, 1.05);
buildTree(-9.7, 4.7, 0.85);
buildTree(-2.5, 5.8, 0.78);
buildTree(9.8, 5.4, 1.0);
buildTree(10.2, -5.2, 0.75);
buildTree(-9.8, 0.4, 0.65);
for (let i = 0; i < 18; i++) {
const x = -10.7 + ((i * 3.73) % 21.4);
const z = -6.8 + ((i * 2.41) % 13.6);
if (Math.abs(x + 6.3) < 3 || Math.abs(x) < 3 || Math.abs(x - 6) < 3.8) continue;
box(scene, 0.18, 0.18, 0.18, i % 2 ? "#e7c86d" : "#e8836b", x, 0.12, z);
}
}
buildWorld();
const clockHands = buildClock();
const scheduleMarkers = new THREE.Group();
scene.add(scheduleMarkers);
const halos = {};
for (const [key, location] of Object.entries(locations)) {
const group = new THREE.Group();
group.position.copy(location.anchor);
const haloMaterial = new THREE.MeshBasicMaterial({ color: location.color, transparent: true, opacity: 0.22 });
const horizontal = box(group, 1.15, 0.035, 0.08, location.color, 0, 0.08, 0, { transparent: true, opacity: 0.22 });
const horizontal2 = box(group, 1.15, 0.035, 0.08, location.color, 0, 0.08, 0, { transparent: true, opacity: 0.22 });
const vertical = box(group, 0.08, 0.035, 1.15, location.color, 0, 0.08, 0, { transparent: true, opacity: 0.22 });
const vertical2 = box(group, 0.08, 0.035, 1.15, location.color, 0, 0.08, 0, { transparent: true, opacity: 0.22 });
horizontal.position.z = -0.55;
horizontal2.position.z = 0.55;
vertical.position.x = -0.55;
vertical2.position.x = 0.55;
horizontal.material = haloMaterial;
horizontal2.material = haloMaterial;
vertical.material = haloMaterial;
vertical2.material = haloMaterial;
scene.add(group);
halos[key] = { group, material: haloMaterial };
}
const person = new THREE.Group();
const personBody = box(person, 0.34, 0.48, 0.25, "#ef8354", 0, 0.54, 0);
box(person, 0.29, 0.29, 0.28, "#f2c7a5", 0, 0.94, 0);
box(person, 0.34, 0.12, 0.34, "#405b57", 0, 1.1, 0);
box(person, 0.16, 0.25, 0.17, "#315a54", -0.1, 0.22, 0);
box(person, 0.16, 0.25, 0.17, "#315a54", 0.1, 0.22, 0);
scene.add(person);
function clearMarkers() {
while (scheduleMarkers.children.length) {
const child = scheduleMarkers.children[0];
child.traverse((object) => {
if (object.geometry) object.geometry.dispose();
if (object.material) object.material.dispose();
});
scheduleMarkers.remove(child);
}
}
function updateSceneSchedule(analysis) {
clearMarkers();
const counts = { bedroom: 0, court: 0, library: 0 };
const badLocations = new Set();
analysis.overlapPairs.forEach((check) => {
badLocations.add(check.a.location);
badLocations.add(check.b.location);
});
analysis.travelIssues.forEach((check) => {
badLocations.add(check.a.location);
badLocations.add(check.b.location);
});
analysis.sorted.forEach((activity) => {
const localIndex = counts[activity.location]++;
const anchor = locations[activity.location].anchor;
const pin = new THREE.Mesh(
new THREE.BoxGeometry(0.42, 0.42, 0.42),
material(activity.color, { emissive: activity.color, emissiveIntensity: 0.18 })
);
pin.position.set(
anchor.x + ((localIndex % 3) - 1) * 0.52,
1.35 + Math.floor(localIndex / 3) * 0.52,
anchor.z
);
pin.castShadow = true;
pin.userData.baseY = pin.position.y;
pin.userData.phase = localIndex * 0.8;
scheduleMarkers.add(pin);
const cap = new THREE.Mesh(
new THREE.BoxGeometry(0.24, 0.18, 0.24),
material("#fff8e9")
);
cap.position.y = 0.28;
pin.add(cap);
});
for (const [key, halo] of Object.entries(halos)) {
if (badLocations.has(key)) {
halo.material.color.set("#d64f4f");
halo.material.opacity = 0.62;
} else {
const activeHere = schedule.find((activity) => activity.location === key && simMinutes >= activity.start && simMinutes < activity.start + activity.duration);
halo.material.color.set(activeHere ? activeHere.color : locations[key].color);
halo.material.opacity = activeHere ? 0.55 : 0.18;
}
}
}
function updatePerson() {
const sorted = [...schedule].sort((a, b) => a.start - b.start);
const active = sorted.find((activity) => simMinutes >= activity.start && simMinutes < activity.start + activity.duration);
let position = new THREE.Vector3(0, 0, 2.7);
if (active) {
position = locations[active.location].anchor.clone();
personBody.material.color.set(active.color);
} else {
const previous = [...sorted].reverse().find((activity) => activity.start + activity.duration <= simMinutes);
const next = sorted.find((activity) => activity.start >= simMinutes);
if (previous && next) {
const required = travel[previous.location][next.location];
const travelEnd = previous.start + previous.duration + required;
if (simMinutes < travelEnd && required > 0) {
const t = THREE.MathUtils.clamp((simMinutes - (previous.start + previous.duration)) / required, 0, 1);
position = locations[previous.location].anchor.clone().lerp(locations[next.location].anchor, t);
} else {
position = locations[next.location].anchor.clone();
}
} else if (previous) {
position = locations[previous.location].anchor.clone();
} else if (next) {
position = locations[next.location].anchor.clone();
}
}
person.position.x = position.x;
person.position.z = position.z;
person.position.y = 0.08 + Math.sin(performance.now() * 0.004) * 0.025;
}
function updateClockUI() {
$("#clockTime").textContent = formatTime(simMinutes);
$("#clockProgress").style.width = `${((simMinutes - START) / (END - START)) * 100}%`;
const hour = Math.floor(simMinutes / 60) % 12;
const minute = simMinutes % 60;
const hourAngle = -((hour + minute / 60) / 12) * Math.PI * 2;
const minuteAngle = -(minute / 60) * Math.PI * 2;
clockHands.hourPivot.rotation.z = hourAngle;
clockHands.minutePivot.rotation.z = minuteAngle;
$("#clockToggle").textContent = simMinutes >= END ? "Reiniciar" : (clockRunning ? "Pausar" : "Continuar");
}
// ---------- Controles de câmera, implementados sem addons ----------
const cameraTarget = new THREE.Vector3(0, 0, -0.35);
let cameraYaw = 0.56;
let cameraElevation = 15.5;
let cameraZoom = 1;
let dragging = false;
let dragButton = 0;
let lastPointerX = 0;
let lastPointerY = 0;
function updateCamera() {
camera.position.set(
cameraTarget.x + Math.sin(cameraYaw) * 22,
cameraTarget.y + cameraElevation,
cameraTarget.z + Math.cos(cameraYaw) * 22
);
camera.lookAt(cameraTarget);
}
function resize() {
const width = Math.max(1, stage.clientWidth);
const height = Math.max(1, stage.clientHeight);
const aspect = width / height;
const frustumHeight = 18.2;
camera.left = -frustumHeight * aspect / 2;
camera.right = frustumHeight * aspect / 2;
camera.top = frustumHeight / 2;
camera.bottom = -frustumHeight / 2;
camera.zoom = cameraZoom;
camera.updateProjectionMatrix();
renderer.setSize(width, height, false);
updateCamera();
}
renderer.domElement.addEventListener("pointerdown", (event) => {
dragging = true;
dragButton = event.button;
lastPointerX = event.clientX;
lastPointerY = event.clientY;
renderer.domElement.setPointerCapture(event.pointerId);
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (!dragging) return;
const dx = event.clientX - lastPointerX;
const dy = event.clientY - lastPointerY;
lastPointerX = event.clientX;
lastPointerY = event.clientY;
if (dragButton === 0) {
cameraYaw -= dx * 0.008;
cameraElevation = THREE.MathUtils.clamp(cameraElevation + dy * 0.045, 8, 24);
} else {
const right = new THREE.Vector3(Math.cos(cameraYaw), 0, -Math.sin(cameraYaw));
const forward = new THREE.Vector3(-Math.sin(cameraYaw), 0, -Math.cos(cameraYaw));
cameraTarget.addScaledVector(right, -dx * 0.015);
cameraTarget.addScaledVector(forward, -dy * 0.015);
}
updateCamera();
});
function endPointer(event) {
dragging = false;
if (renderer.domElement.hasPointerCapture(event.pointerId)) {
renderer.domElement.releasePointerCapture(event.pointerId);
}
}
renderer.domElement.addEventListener("pointerup", endPointer);
renderer.domElement.addEventListener("pointercancel", endPointer);
renderer.domElement.addEventListener("contextmenu", (event) => event.preventDefault());
renderer.domElement.addEventListener("wheel", (event) => {
event.preventDefault();
cameraZoom = THREE.MathUtils.clamp(cameraZoom * Math.exp(-event.deltaY * 0.001), 0.72, 1.75);
camera.zoom = cameraZoom;
camera.updateProjectionMatrix();
}, { passive: false });
renderer.domElement.addEventListener("dblclick", () => {
cameraYaw = 0.56;
cameraElevation = 15.5;
cameraTarget.set(0, 0, -0.35);
cameraZoom = 1;
camera.zoom = 1;
camera.updateProjectionMatrix();
updateCamera();
});
new ResizeObserver(resize).observe(stage);
// ---------- Eventos locais da interface ----------
$("#addActivity").addEventListener("click", () => {
const type = $("#activityType").value;
const template = templates[type];
const start = Number($("#startTime").value);
const activity = {
id: nextId++,
type,
location: type,
title: template.title,
start,
duration: template.duration,
color: template.color
};
schedule.push(activity);
selectedId = activity.id;
renderSchedule();
showToast(`${activity.title} adicionado às ${formatTime(start)}. Itinerário e checagens atualizados.`);
});
$("#activityType").addEventListener("change", () => {
populateStartTimes($("#activityType").value, Number($("#startTime").value));
document.querySelectorAll(".place-chip").forEach((chip) => {
chip.classList.toggle("active", chip.dataset.place === $("#activityType").value);
});
});
document.querySelectorAll(".place-chip").forEach((chip) => {
chip.addEventListener("click", () => {
$("#activityType").value = chip.dataset.place;
$("#activityType").dispatchEvent(new Event("change"));
showToast(`${locations[chip.dataset.place].label} selecionado para a próxima atividade.`);
});
});
$("#agendaList").addEventListener("click", (event) => {
const card = event.target.closest(".activity-card");
if (!card) return;
const id = Number(card.dataset.id);
const button = event.target.closest("button[data-action]");
if (!button) {
selectedId = id;
renderSchedule();
return;
}
const activity = schedule.find((item) => item.id === id);
if (!activity) return;
if (button.dataset.action === "remove") {
schedule = schedule.filter((item) => item.id !== id);
if (selectedId === id) selectedId = null;
renderSchedule();
showToast("Atividade removida. O itinerário foi recalculado.");
} else if (button.dataset.action === "earlier") {
moveActivity(id, activity.start - STEP);
} else if (button.dataset.action === "later") {
moveActivity(id, activity.start + STEP);
}
});
$("#agendaList").addEventListener("dragstart", (event) => {
const card = event.target.closest(".activity-card");
if (!card) return;
draggedId = Number(card.dataset.id);
selectedId = draggedId;
event.dataTransfer.effectAllowed = "move";
event.dataTransfer.setData("text/plain", String(draggedId));
});
$("#agendaList").addEventListener("dragend", () => {
draggedId = null;
document.querySelectorAll(".drop-target").forEach((element) => element.classList.remove("drop-target"));
});
$("#timeline").addEventListener("click", (event) => {
const slot = event.target.closest(".slot");
if (!slot) return;
if (selectedId === null) {
showToast("Selecione um cartão ou arraste uma atividade para mover.");
return;
}
moveActivity(selectedId, Number(slot.dataset.slot));
});
$("#timeline").addEventListener("dragover", (event) => {
const slot = event.target.closest(".slot");
if (!slot) return;
event.preventDefault();
event.dataTransfer.dropEffect = "move";
slot.classList.add("drop-target");
});
$("#timeline").addEventListener("dragleave", (event) => {
const slot = event.target.closest(".slot");
if (slot && !slot.contains(event.relatedTarget)) slot.classList.remove("drop-target");
});
$("#timeline").addEventListener("drop", (event) => {
event.preventDefault();
const slot = event.target.closest(".slot");
if (!slot) return;
const id = Number(event.dataTransfer.getData("text/plain") || draggedId);
document.querySelectorAll(".drop-target").forEach((element) => element.classList.remove("drop-target"));
if (Number.isFinite(id)) moveActivity(id, Number(slot.dataset.slot));
});
$("#clockToggle").addEventListener("click", () => {
if (simMinutes >= END) {
simMinutes = START;
clockRunning = true;
} else {
clockRunning = !clockRunning;
}
updateClockUI();
});
$("#clockReset").addEventListener("click", () => {
simMinutes = START;
clockRunning = true;
updateClockUI();
showToast("Relógio reiniciado às 13:00.");
});
$("#restoreDemo").addEventListener("click", () => {
schedule = defaultSchedule();
selectedId = 1;
renderSchedule();
showToast("Exemplo inicial restaurado.");
});
populateStartTimes("library", 14 * 60);
document.querySelector('.place-chip[data-place="library"]').classList.add("active");
renderSchedule();
updateClockUI();
resize();
setInterval(() => {
if (!clockRunning) return;
simMinutes = Math.min(END, simMinutes + 5);
if (simMinutes >= END) clockRunning = false;
updateClockUI();
}, 1200);
function animate(time) {
requestAnimationFrame(animate);
updatePerson();
scheduleMarkers.children.forEach((pin, index) => {
pin.position.y = pin.userData.baseY + Math.sin(time * 0.0025 + pin.userData.phase) * 0.09;
pin.rotation.y = time * 0.0007 + index;
});
renderer.render(scene, camera);
}
requestAnimationFrame(animate);
</script>
</body>
</html>
```