PF 102 study hub

PF 102 · Pre-final · 4 lessons

Enter the Building → Inside the Island

Midterm made the island yours. Now you step inside it. Double-click a building — you're in. Press Esc — you're back. You write the events that make it happen.

Your progress0 / 26 · 0%

Saved in this browser only. Tick boxes as you go.

Before you start

The one idea

One app, two modes. A variable called mode says where you are, and every handler checks it before acting.

Not allowed

A second HTML page (index-interior.html) as the way in. That's a link, not an event. Don't restart from a blank project either.

Lesson 1 · ~30 min

Enter the Building

No code yet. Play the finished version, then learn the one idea that makes it work: a mode flag that every handler checks.

1.1

Play the finished demo

  1. 1

    Open the finished demo. Click a building: it turns gold and the HUD shows its name (same as midterm). Buildings with a dark door (Cafe, Church, Clinic) can be entered.

  2. 2

    Double-click the Cafe (it has a dark door). You are inside. Look at the badge at the top: Inside: Cafe.

  3. 3

    Move the mouse to look around. Click a table: the HUD names it.

  4. 4

    Press Esc. Then double-click the Church and leave with the Exit building button.

  5. 5

    The whole time, watch the Event trace panel in the bottom-left.

Check ·You entered two different rooms and left both ways (Esc and the button).

1.2

Learn the event map

  1. 1

    Three events change where you are. Say each row out loud: Fire → Listen → Handle → State.

the whole feature in 3 lines
EVENT               LISTEN (main.js)       HANDLE (events.js)         STATE
dblclick building → canvas 'dblclick'  → enterInterior(building) → mode = 'inside'
keydown Escape    → window 'keydown'   → exitInterior()          → mode = 'island'
click Exit button → #exit-btn 'click'  → exitInterior()          → mode = 'island'

Why ·The Exit button is an HTML button sitting on top of the 3D canvas. It is not part of the island. That detail matters in Lesson 3.

1.3

Meet the mode flag

  1. 1

    The browser keeps firing every event wherever you are. So handlers need to know where you are. That's called state.

  2. 2

    Every handler reads mode first and asks: "does my job make sense right now?"

js/events.js
let mode = 'island';          // 'island' | 'inside'
let currentInterior = null;   // which room you are in

Check ·Answer out loud: inside the Cafe, should R reset buildings? Should the camera orbit? (No and no. The handlers must check mode.)

After this lesson you can explain

  • Why the app has two modes, and which variable stores it (mode)
  • The three events that change the mode, and which handler each one calls
  • Why a double-click fires click, click, then dblclick
  • Why a second HTML page is not allowed

Lesson 2 · ~90 min

Wire the Doors

Hands-on. Copy the provided parts (HTML, CSS, the room builder). Then type the events yourself, one small step at a time. Save → refresh → test after every step.

2.1

Copy the provided parts

  1. 1

    These parts are not the lesson (plain HTML, styling, Three.js boxes), so you copy them. Everything after this step you type.

  2. 2

    index.html: paste the mode bar and Event trace right after the #hud div.

  3. 3

    css/style.css: open the finished style.css and copy everything from /* PRE-FINAL · mode bar + event trace */ to the end of the file. Paste it at the bottom of yours.

  4. 4

    js/scene.js: open the finished scene.js and copy the whole block that starts with PRE-FINAL · ENTER THE BUILDING (PROVIDED) to the end of the file. Paste it at the bottom of yours.

  5. 5

    js/scene.js (top + exports): add the three element lookups and three exports below.

index.html
<div id="mode-bar">
  <span id="mode-badge">Island</span>
  <button id="exit-btn" type="button" hidden>Exit building</button>
</div>

<aside id="event-trace" aria-label="Event trace">
  <strong>Event trace</strong>
  <ol id="event-log"></ol>
</aside>
js/scene.js · top
const modeBadge = document.getElementById('mode-badge');
const exitButton = document.getElementById('exit-btn');
const eventLog = document.getElementById('event-log');
js/scene.js · exports
globalThis.edpModeBadge = modeBadge;
globalThis.edpExitButton = exitButton;
globalThis.edpEventLog = eventLog;

Check ·Refresh. You see an Island badge at the top and an empty Event trace panel. Console has no red errors.

2.2

Tag your building (and give it a door)

File: js/scene.js

  1. 1

    Add interior: 'yourKey' to your building in the spots array.

  2. 2

    In the spots.forEach loop, save the tag into userData and add a door for tagged buildings.

spots entry
{ name: 'Cafe', color: 0xfbbf24, x: -10, z: 8, w: 3, h: 2.8, d: 3, interior: 'cafe' },
inside spots.forEach
mesh.userData = { isBuilding: true, name: spot.name, baseColor: spot.color, interior: spot.interior || null };
scene.add(mesh);
buildings.push(mesh);

if (spot.interior) {
  const door = new THREE.Mesh(
    new THREE.BoxGeometry(1, 1.8, 0.1),
    new THREE.MeshStandardMaterial({ color: 0x3b2410, roughness: 0.8 })
  );
  door.position.set(spot.x, 0.9, spot.z + spot.d / 2 + 0.05);
  scene.add(door);
}

Check ·Refresh. Your building has a dark door on its front. Nothing else changes yet.

2.3

Build your room

File: js/scene.js (bottom, after the provided block)

  1. 1

    Call makeInterior with the same key you used in the tag.

  2. 2

    Give it a far-away x (400, −400, 800…). Props use room coordinates: x and z from about −7 to 7.

  3. 3

    Boxes are enough. Name every prop — the name shows in the HUD when clicked.

  4. 4

    Want a better room, or a different building? Follow the interior design guide: room map, free slots, and prop recipes (tables, beds, wall boards).

js/scene.js
makeInterior('cafe', {
  name: 'Cafe',
  x: 400,
  wall: 0xfde68a,
  floor: 0x92400e,
  props: [
    { name: 'Counter', color: 0x78350f, x: 0, z: -5, w: 8, h: 1.2, d: 1.4 },
    { name: 'Table 1', color: 0xf59e0b, x: -4, z: 0, w: 2.4, h: 0.9, d: 2.4 },
    { name: 'Table 2', color: 0xf59e0b, x: 4, z: 0, w: 2.4, h: 0.9, d: 2.4 },
  ],
});

Why ·The camera only draws things up to 300 units away. A room at x = 400 is invisible from the island, and the island is invisible from inside the room. No hiding needed.

2.4

Add the mode flag

File: js/events.js (top, under let hovered)

  1. 1

    Type the two state variables. let, not const — they change.

js/events.js
let mode = 'island';          // 'island' | 'inside'
let currentInterior = null;   // edpInteriors[key] while inside
2.5

Write enterInterior()

File: js/events.js (bottom)

  1. 1

    Guard first: if you're not on the island, leave.

  2. 2

    Look up the room, clean up the midterm selection, flip the mode, move the camera, update the badge and HUD.

js/events.js
function enterInterior(building) {
  if (mode !== 'island') return;                         // guard: already inside?

  const interior = edpInteriors[building.userData.interior];
  if (!interior) return;                                 // key typo? do nothing

  if (selected) paintBuilding(selected, selected.userData.baseColor);
  if (hovered) paintBuilding(hovered, hovered.userData.baseColor);
  selected = null;
  hovered = null;
  resetSurroundings();
  edpRenderer.domElement.style.cursor = 'default';

  mode = 'inside';
  currentInterior = interior;
  document.body.dataset.mode = 'inside';                 // CSS hides the map legend

  edpCamera.position.copy(interior.eye);                 // step into the room
  edpCamera.lookAt(interior.lookAt);
  edpSunSprite.visible = false;                          // no sun through the walls
  edpMoonSprite.visible = false;

  edpModeBadge.textContent = 'Inside: ' + interior.name;
  edpExitButton.hidden = false;
  edpHud.innerHTML =
    '<strong>Inside: ' + interior.name + '</strong>' +
    'Move the mouse to look around · click things · <kbd>Esc</kbd> or <b>Exit</b> to leave';
}
2.6

Double-click a door → enter

File: js/events.js · onDoubleClick

  1. 1

    Replace your midterm onDoubleClick with this whole function — do not leave the door check as a comment.

  2. 2

    Single click stays exactly as it was in midterm: select + show the name.

  3. 3

    logEvent is Lesson 3. If the console says it is not defined yet, comment out that one line until Lesson 3.

js/events.js
function onDoubleClick(event) {
  logEvent(event, 'onDoubleClick');
  if (mode === 'inside') return;

  edpRaycaster.setFromCamera(edpMouse, edpCamera);
  const hits = edpRaycaster.intersectObjects(edpBuildings, false);
  if (!hits.length) return;

  const building = hits[0].object;

  if (building.userData.interior) {
    enterInterior(building);
    return;
  }

  edpHud.innerHTML =
    '<strong>' + building.userData.name + ' · details</strong>' +
    'Double-click → <code>dblclick</code> listener → handler → HUD update.<br>' +
    '<em>Same Fire → Listen → Handle pattern as click.</em>';
}

globalThis.onDoubleClick = onDoubleClick;

Check ·Refresh → double-click your building → you're inside and the badge shows its name. Commit: Enter my building on double-click

2.7

Single click inside → name the prop

File: js/events.js · onClick + a new helper

  1. 1

    At the very top of onClick, add the mode check. On the island nothing changes.

  2. 2

    Add inspectInteriorProp: the same raycaster, but tested against the room's props.

top of onClick
if (mode === 'inside') {
  inspectInteriorProp();
  return;
}
js/events.js
function inspectInteriorProp() {
  edpRaycaster.setFromCamera(edpMouse, edpCamera);
  const hits = edpRaycaster.intersectObjects(currentInterior.props, false);
  if (!hits.length) return;

  const prop = hits[0].object;
  paintBuilding(prop, 0xfbbf24);
  setTimeout(function () {
    paintBuilding(prop, prop.userData.baseColor);
  }, 400);
  edpHud.innerHTML =
    '<strong>Inside: ' + currentInterior.name + '</strong>' +
    'You tapped the <b>' + prop.userData.name + '</b> · <kbd>Esc</kbd> or <b>Exit</b> to leave';
}
2.8

exitInterior() + Escape

File: js/events.js

  1. 1

    Write exitInterior with its own guard.

  2. 2

    At the top of onKeyDown, handle Escape first — it's the one key that must work inside. Then block R and B while inside.

js/events.js
function exitInterior() {
  if (mode !== 'inside') return;

  const leftName = currentInterior.name;          // save it BEFORE clearing
  mode = 'island';
  currentInterior = null;
  document.body.dataset.mode = 'island';

  edpSunSprite.visible = !nightMode;
  edpMoonSprite.visible = nightMode;

  edpModeBadge.textContent = 'Island';
  edpExitButton.hidden = true;
  edpHud.innerHTML =
    '<strong>Back on the island</strong>' +
    'You left the ' + leftName + '. Double-click another door, or explore.';
}
top of onKeyDown
if (event.code === 'Escape') {
  event.preventDefault();
  exitInterior();
  return;
}

if (mode === 'inside') return;   // R and B are island-only

Check ·Refresh → enter → press Esc. You're back. Press R and B inside: nothing happens.

2.9

Listen to the Exit button

File: js/events.js + js/main.js

  1. 1

    Add a small handler in events.js.

  2. 2

    Register it in main.js next to your other listeners. Pass the function name with no ().

js/events.js
function onExitButtonClick(event) {
  exitInterior();
}
js/main.js
edpExitButton.addEventListener('click', onExitButtonClick);

Check ·Enter → click Exit building → back on the island. Commit: Exit interior on Escape and HUD button

2.10

Stop orbiting + look around

File: js/main.js · animate() + js/events.js

  1. 1

    In animate(), right after requestAnimationFrame(animate);, skip the orbit and hover while inside.

  2. 2

    Add lookAroundInterior: the mouse position turns your head.

js/main.js · inside animate()
if (mode === 'inside') {
  lookAroundInterior();
  edpRenderer.render(edpScene, edpCamera);
  return;
}
js/events.js
function lookAroundInterior() {
  const yaw = edpMouse.x * 0.7;       // left / right, about ±40°
  const pitch = edpMouse.y * 0.25;    // up / down
  const eye = currentInterior.eye;
  edpCamera.position.copy(eye);
  edpCamera.lookAt(
    eye.x + Math.sin(yaw) * 10,
    eye.y + pitch * 10,
    eye.z - Math.cos(yaw) * 10
  );
}

Check ·Inside, moving the mouse left turns the view left. The camera no longer orbits. Leaving makes it orbit again.

Why ·Watch the sign of yaw. With -edpMouse.x the camera turns the opposite way from your mouse and the cursor feels stuck. Real bug from building this demo — one minus sign.

After this lesson you can explain

  • Why enterInterior and exitInterior both start with a guard clause
  • How userData.interior connects a building to its room
  • Why addEventListener('click', onExitButtonClick) has no ()
  • Why return inside animate() doesn't stop the loop

Lesson 3 · ~45 min

Who Ate the Exit Click?

The CLO3 lesson. Add an X-ray to your app, break the Exit button on purpose, explain what happened, then fix it.

3.1

Add the Event trace (your X-ray)

File: js/events.js

  1. 1

    Paste logEvent at the bottom of events.js (provided — it only writes lines into the panel).

  2. 2

    Call it as the first line of onClick, onDoubleClick, and onExitButtonClick, and inside the Escape check of onKeyDown.

js/events.js
function logEvent(event, handlerName) {
  const target = event.target === window ? 'window' : event.target.id || event.target.tagName.toLowerCase();
  const current = event.currentTarget === window ? 'window' : event.currentTarget.id || event.currentTarget.tagName.toLowerCase();
  const line = document.createElement('li');
  line.innerHTML =
    '<code>' + event.type + '</code> → <b>' + handlerName + '</b>' +
    ' <span>target: ' + target + ' · listener on: ' + current + ' · mode: ' + mode + '</span>';
  edpEventLog.prepend(line);
  while (edpEventLog.children.length > 5) edpEventLog.lastChild.remove();
}
first line of each handler
logEvent(event, 'onClick');

Check ·Double-click your building. The trace shows click, click, dblclick (newest on top).

3.2

Learn to read one line

  1. 1

    target = the element you actually clicked (event.target).

  2. 2

    listener on = the element whose listener is running right now (event.currentTarget).

  3. 3

    When those two are different, the event bubbled up to reach that listener.

example line
click → onExitButtonClick
target: exit-btn · listener on: exit-btn · mode: inside
3.3

Break it on purpose

File: js/main.js

  1. 1

    Comment out the canvas click listener. Listen on the whole window instead.

  2. 2

    Save → refresh → enter your building → click Exit building.

  3. 3

    Watch the HUD and the trace. The "Back on the island" message disappears straight away.

js/main.js
// edpRenderer.domElement.addEventListener('click', onClick);
window.addEventListener('click', onClick);
what the trace shows
click → onClick              target: exit-btn · listener on: window   · mode: island
click → onExitButtonClick    target: exit-btn · listener on: exit-btn · mode: inside
3.4

Explain what happened

  1. 1

    You clicked the button (the target) → onExitButtonClick ran → mode became 'island'.

  2. 2

    The same click bubbled up the page: button → mode-bar → body → html → document → window.

  3. 3

    window had a click listener → onClick ran too. The mode was already 'island', so it raycast, hit nothing, and called resetHud().

  4. 4

    The canvas is not in that path. The button and the canvas are siblings, not parent and child.

Why ·The mode guard was correct — but by the time the bubble reached window, the mode had already changed. The problem was where the listener lived.

3.5

Fix it (and say why)

  1. 1

    Fix A · listen on the right element (default): put the canvas listener back. Only canvas clicks should pick buildings.

  2. 2

    Fix B · check the target: if (event.target !== edpRenderer.domElement) return; at the top of onClick. Use it when you really need a page-wide listener.

  3. 3

    Fix C · stop the bubble: event.stopPropagation() in onExitButtonClick. Last resort — it hides the click from every parent listener.

  4. 4

    Put Fix A back before you move on.

js/main.js
edpRenderer.domElement.addEventListener('click', onClick);
// window.addEventListener('click', onClick);

Check ·Enter → Exit. The trace shows only onExitButtonClick, and "Back on the island" stays on screen.

After this lesson you can explain

  • The difference between event.target and event.currentTarget
  • Why the Exit click reached window but not the canvas
  • When to use Fix A, B, or C — and why stopPropagation() is last
  • preventDefault() (stops the browser's action) vs stopPropagation() (stops the climb)

Lesson 4 · ~2–3 min demo each

Inside Checkpoint

Make it yours, write it up, push it, then demo it. A classmate enters and leaves your building; you explain every event that fired.

4.1

Make it yours

  1. 1

    Your enterable building must be your own (renaming the demo Cafe doesn't count).

  2. 2

    Campus ideas: ferry terminal, canteen, gym, chapel, library, clinic.

  3. 3

    Stretch: a second building with a different room, or a prop that does something special when clicked.

4.2

Pass the four hard gates

  1. 1

    Enter and exit are handlers + a mode flag in the same page (no second HTML page).

  2. 2

    Double-clicking while inside does not enter again.

  3. 3

    The Exit button works without also running onClick (check the trace).

  4. 4

    You can write enterInterior / exitInterior from memory and say which events fire them.

4.3

README + commits

File: README.md

  1. 1

    Add a My Interiors section.

  2. 2

    Push at least three meaningful commits: enter path, exit path, README.

README.md
## My Interiors

| Building | Enter | Exit | Inside you can… |
|---|---|---|---|
| Canteen | double-click the canteen | Esc / Exit button | click the counter to see the menu |
terminal
git commit -m "Enter canteen on double-click (mode flag + enterInterior)"
git commit -m "Exit interior on Escape and HUD button"
git commit -m "README: My Interiors"
git push
4.4

Practise the demo

  1. 1

    Island: show midterm click still works. Point at the badge.

  2. 2

    Inside: hand the mouse to a classmate. They double-click your door, look around, click a prop.

  3. 3

    Out: they press Esc, enter again, then use the Exit button. Show the Event trace.

  4. 4

    For each path, say it out loud using the pattern below.

say this
When the user double-clicks the ____ (FIRE),
main.js listens with canvas 'dblclick' (LISTEN),
events.js runs enterInterior() (HANDLE),
and mode becomes 'inside' — you can see it in the badge (STATE).
4.5

Paper drill (laptop closed)

  1. 1

    Write both functions from memory, including the guard line.

  2. 2

    Trace: "I double-click my building. List every handler that runs, in order."

  3. 3

    Trace: "I'm inside and click Exit. List every handler that runs, in order."

paper
function enterInterior(building) — fired by: ______________________
function exitInterior()          — fired by: ______________ and ______________

After this lesson you can explain

  • Fire → Listen → Handle → State for entering and for both ways out
  • One handler that behaves differently inside, and why
  • What would break if the click listener lived on window

Submit

Same edp-lab repo as midterm. One link. A classmate must be able to enter and leave without you touching the keyboard.

DeliverableWhat to turn in
RepoYour same edp-lab fork URL on GitHub
READMEA My Interiors section
Commits3+ meaningful commits: enter, exit, README
Live demo2–3 minutes · a classmate enters and leaves your building
Paper drillenterInterior / exitInterior from memory + which events fire them

Rubric · 50 points

Points go to events and state, not 3D art. Points ÷ 50 × 100 = your checkpoint %.

CriteriaWhat the grader checksPts
EnterDouble-click your building → inside its room10
ExitEsc returns to the island · camera orbits again · badge resets10
Mode guardsNo re-enter inside · R/B/dblclick island-only · midterm click still works10
Mode visibleBadge / HUD shows Island vs Inside: …5
Event flow (CLO3)Explains target vs currentTarget and why Exit must not bubble into onClick5
Git + README3+ meaningful commits · My Interiors section5
Paper drillBoth functions from memory + which events fire them5

Midterm island broken? Fix the midterm baseline first — don't build doors on a broken island.