first commit

This commit is contained in:
Julien Quiaios 2026-10-24 09:46:11 -04:00
commit d2b777d8d1
38 changed files with 6786 additions and 0 deletions

4
.gitignore vendored Normal file
View File

@ -0,0 +1,4 @@
node_modules/
dist/
*.log
tests/shots/

18
CLAUDE.md Normal file
View File

@ -0,0 +1,18 @@
# Consignes pour Claude : projet Escape Game
Escape game point & click 3D (three.js, caméras fixes), piloté par `src/scenarios/<chapitre>/scenario.json`. Voir le README pour le format.
## Vérifier une modification (du plus rapide au plus lent)
1. `npm run check` (~5 s) : typage, tests de logique, build. À lancer **après chaque modification**.
2. `npm run smoke` (~1 min) : la solution de référence rejouée avec de vrais clics 3D. À lancer seulement si la modification touche le monde 3D (`src/worlds/`), le rendu, les caméras ou l'UI.
3. Captures ciblées : `npm run smoke -- --shots`, puis regarder seulement les vues concernées dans `tests/shots/`.
## Règles
- Ne jamais rejouer une partie à la main avec des scripts ad hoc : passer par `walkthrough.json` et `tests/smoke.cjs`.
- En environnement sans GPU, toujours utiliser `?test=1` (pas d'animation, basse qualité). Le rendu 3D est très lent en logiciel.
- Délais d'attente courts (smoke : 20 s par action) : un test bloqué est un test en échec.
- Si l'enchaînement des énigmes change, mettre à jour `walkthrough.json` dans le même changement.
- Un nouveau type de mini-jeu doit avoir un contrôle dans `tests/scenarios.test.ts` (`checkPuzzle`) et une résolution dans `tests/smoke.cjs`.
- Le jugement visuel final (lumière, ombres, fluidité) revient à l'utilisateur, sur sa machine.

145
README.md Normal file
View File

@ -0,0 +1,145 @@
# Escape Game
Escape game point & click façon *Myst*, en 3D temps réel avec three.js et des caméras fixes. On passe d'un point de vue à l'autre par un mouvement de caméra.
Le moteur est piloté par les données : tout le contenu d'un chapitre (points de vue, objets cliquables, inventaire, énigmes, indices, animations) tient dans un `scenario.json`. Le décor 3D est un « monde » dont les objets sont nommés.
## Jouer
- **Sans rien installer** : double-cliquer sur `dist/index.html`. Le jeu tient dans ce seul fichier.
- **En développement** (Node 20.19+ requis) :
```bash
npm install
npm run dev # serveur avec rechargement à chaud
npm run build # régénère dist/index.html
```
- **Petite config** : ajouter `?quality=low` à l'URL, ou exécuter `localStorage.setItem('escape-game:quality','low')` dans la console. Ce mode désactive les ombres et le bloom, et rend en pleine résolution simple.
### Commandes
| Action | Contrôle |
|---|---|
| Examiner / zoomer | clic sur un élément (le curseur change et l'objet est surligné) |
| Tourner à gauche ou à droite | flèches sur les bords gauche et droit de l'écran |
| Reculer | flèche en bas de l'écran, clic droit ou `Échap` |
| Utiliser un objet | clic sur l'objet dans l'inventaire, puis sur la cible |
| Combiner deux objets | clic sur un objet de l'inventaire, puis sur un autre objet de l'inventaire |
| Indice progressif | bouton **Indice** ou `H` |
| Mode debug | `D` : caméra libre (glisser = orbiter, molette = zoom). Affiche l'objet visé et le point 3D. `C` copie le point de vue en JSON `"camera"` |
La partie est sauvegardée automatiquement dans le navigateur (bouton « Continuer » dans le menu).
**Difficulté** (au lancement d'une partie) :
- **Facile** : les objets interactifs s'entourent d'un contour doré et affichent leur nom au survol ;
- **Difficile** : seul le curseur change, et les flèches de navigation restent indiquées.
## Le chapitre 1 : le bureau du professeur
Cinq énigmes enchaînées, pour 15 à 20 minutes de jeu. Attention, la solution est détaillée ci-dessous.
<details>
<summary>Solution</summary>
1. **Combinaison** : une lampe UV dans les tiroirs gauches du bureau, des piles dans le vase. On combine les deux dans l'inventaire pour obtenir une lampe UV allumée.
2. **Déchiffrement** : on éclaire le tableau avec la lampe UV pour révéler un message. On l'ouvre, puis on tourne la roue de César jusqu'au décalage 7 : « Le coffre s'ouvre à l'heure où le temps s'est arrêté ».
3. **Cadenas à molettes**, en bas de la bibliothèque : l'horloge est arrêtée à 10 h 40, le code est donc 1-0-4-0. Le coffret contient une manette.
4. **Mécanisme** : on installe la manette sur le disjoncteur (mur ouest), puis on l'abaisse. Le plafonnier s'allume et le boîtier est sous tension.
5. **Code couleur** : les chiffres 1 (jaune, dans le tableau), 2 (rouge, sur un livre), 3 (bleu, au mur nord) et 4 (vert, près de la porte) donnent la combinaison du boîtier. Elle ouvre le tiroir secret du bureau, qui contient la clé de la porte.
</details>
## Tests
| Commande | Durée | Ce qu'elle vérifie |
|---|---|---|
| `npm test` | ~1 s | Moteur et scénarios sans navigateur : références, cohérence logique, paramètres des mini-jeux, et la solution de référence (`walkthrough.json`) rejouée jusqu'à la victoire |
| `npm run check` | ~5 s | Typage + `npm test` + build |
| `npm run smoke` | ~1 min | Rejoue la solution avec de vrais clics dans le jeu 3D construit (mode `?test=1`) : objets 3D introuvables, zones masquées, erreurs console, écran de victoire |
Options du smoke test : `npm run smoke -- --shots` (une capture par scène dans `tests/shots/`), `--hard`, `--chapter chapitre1`, `--headed`. Il a besoin de Playwright (`npm i -D playwright && npx playwright install chromium`).
La **cohérence logique** (`src/engine/scenarioAnalysis.ts`) détecte notamment :
- un drapeau testé mais jamais levé (faute de frappe) ;
- un objet jamais donné ou qui ne sert à rien ;
- une variable jamais modifiée ;
- une énigme impossible à ouvrir ;
- une scène inaccessible ;
- l'absence de condition de victoire.
**Chaque chapitre a sa solution de référence** dans `walkthrough.json`, une suite d'étapes comme `{ "click": "desk" }`, `{ "use": "key", "on": "lock" }`, `{ "combine": [a, b] }` ou `{ "solve": "cipher" }`, chacune avec des vérifications `expect` optionnelles. Si on modifie l'enchaînement des énigmes, il faut mettre ce fichier à jour.
**Mode test du rendu** : `dist/index.html?test=1` passe en basse qualité, sans animation de caméra ni d'objets.
## Architecture
```
src/
engine/
types.ts format JSON d'un scénario
state.ts état de partie, conditions, sauvegarde
Engine.ts logique : interactions, actions, indices (aucun rendu)
BaseRenderer.ts UI : HUD, inventaire, messages, mini-jeux, flèches, debug
three/ThreeRenderer.ts rendu 3D : caméras, raycast, surlignage, objets animés
scenarioLoader.ts chargement et validation des références
scenarioAnalysis.ts cohérence logique d'un scénario
walkthrough.ts rejoue une solution de référence sans rendu
cursors.ts curseurs (examiner, prendre, flèches...)
audio.ts bruitages synthétisés (provisoires)
puzzles/
registry.ts contrat d'un mini-jeu
colorCode.ts mini-jeu « code couleur »
caesar.ts mini-jeu « roue de César »
worlds/
bureau.ts la pièce 3D construite par code (objets nommés)
textures.ts textures procédurales (canvas)
scenarios/
chapitre1/ scenario.json, walkthrough.json, images/ (icônes)
tests/
engine.test.ts mécaniques du moteur (variables, déclencheurs, combinaisons...)
scenarios.test.ts contrôles de tous les chapitres + solution de référence
smoke.cjs partie complète dans le navigateur (Playwright)
```
### Le format du scénario
- **Scène** : un point de vue, `"camera": { "position", "target", "fov" }`. Les raccourcis `left`, `right` et `back` génèrent les flèches de navigation.
- **Zone cliquable** : `"object": "nomObjet"`, le nom d'un objet du monde 3D. L'objet le plus précis l'emporte : cliquer sur la serrure, qui fait partie de la porte, déclenche la zone « serrure ».
- **Conditions** : `flag:x`, `item:x`, `selected:x`, `solved:x`, et `var:x=3` (également `!=`, `>=`, `<=`, `>`, `<`), avec `!` pour la négation.
- **Actions** :
- `{ "goto" }`, `{ "message" }`, `{ "setFlag" }`, `{ "give" }`, `{ "remove" }`, `{ "puzzle" }`, `{ "sound" }`, `{ "win" }` ;
- les variables : `{ "add": "molette1", "mod": 10 }` et `{ "set": "x", "value": 0 }` ;
- les conditionnelles : `{ "if": [...], "then": [...], "else": [...] }`.
- **Props** : l'état visuel des objets selon les conditions (`visible`, `offset`, `rotation`, `emissive`), ou selon une variable (`spin` : une molette tourne de `step` radians par unité). Tout est animé : tiroir qui coulisse, porte qui s'ouvre, molettes, voyants, plafonnier.
- **Déclencheurs** (`triggers`) : des actions exécutées une seule fois, dès que leurs conditions deviennent vraies. Par exemple, le coffret s'ouvre quand les 4 molettes affichent le bon code.
- **Combinaisons** (`combinations`) : deux objets d'inventaire et les actions à exécuter quand on les combine.
- **Variables initiales** (`vars`) : par exemple, la position de départ des molettes.
### Choix structurants
- **`Engine` ne connaît aucun rendu.** Il parle à une interface `View`.
- **Le monde référence ses objets par leur nom.** `bureau.ts` construit la pièce par code. Un modèle Blender exporté en `.glb` avec les mêmes noms d'objets pourrait le remplacer sans toucher au scénario.
- **Le rendu se fait à la demande.** On ne redessine que pendant un mouvement ou après un changement, ce qui laisse le GPU au repos le reste du temps.
- **Des zones invisibles agrandissent les petites cibles.** Ces zones (clé, chiffre peint dans le tableau) vivent sur un calque à part : le raycast les voit, la caméra non.
- **Deux familles d'énigmes.** Les mécanismes dans le décor (molettes, disjoncteur) se font uniquement en JSON, avec les variables, les props et les déclencheurs. Les mini-jeux en surimpression (`colorCode`, `caesar`) sont des types réutilisables paramétrés en JSON. Pour créer un nouveau type, il suffit d'appeler `registerPuzzle('monType', factory)`.
- **Le validateur** signale en console les références cassées : scène, objet d'inventaire, puzzle, image, ou objet 3D introuvable.
### Ajouter du contenu
1. Ajouter l'objet nommé dans le monde (`worlds/*.ts`).
2. Lancer le jeu, appuyer sur `D`, cadrer la vue à la souris, puis `C` pour copier la caméra.
3. Déclarer la scène et ses `hotspots` dans `scenario.json`.
4. Mettre à jour `walkthrough.json` si l'enchaînement change, puis lancer `npm run check` et `npm run smoke`.
Un nouveau dossier dans `src/scenarios/` apparaît automatiquement comme nouveau chapitre dans le menu.
## Pistes suivantes
- Faire jouer la pièce complète à quelques testeurs pour équilibrer les indices et la difficulté.
- Trancher entre web et Godot.
- Charger un `.glb` modélisé dans Blender à la place du monde procédural.
- Ajouter d'autres types de mini-jeux : taquin, ordre de symboles, mécanismes plus riches.
- Ajouter de vrais sons et une musique d'ambiance.
- Empaqueter en application desktop (Electron ou Tauri), avec Steam en ligne de mire.
- Construire l'éditeur de niveaux sur le format `types.ts`.

12
index.html Normal file
View File

@ -0,0 +1,12 @@
<!doctype html>
<html lang="fr">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Escape Game – POC</title>
</head>
<body>
<div id="app"></div>
<script type="module" src="/src/main.ts"></script>
</body>
</html>

1717
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

27
package.json Normal file
View File

@ -0,0 +1,27 @@
{
"name": "escape-game",
"version": "0.1.0",
"private": true,
"description": "Escape game point & click 3D (style Myst, caméras fixes) – three.js, moteur data-driven",
"type": "module",
"scripts": {
"dev": "vite",
"build": "tsc --noEmit && vite build",
"preview": "vite preview",
"typecheck": "tsc --noEmit",
"test": "vitest run",
"test:watch": "vitest",
"check": "tsc --noEmit && vitest run && vite build",
"smoke": "vite build && node tests/smoke.cjs"
},
"devDependencies": {
"@types/three": "^0.180.0",
"typescript": "^5.9.3",
"vite": "^7.3.7",
"vite-plugin-singlefile": "^2.3.4",
"vitest": "^3.2.7"
},
"dependencies": {
"three": "^0.180.0"
}
}

377
src/engine/BaseRenderer.ts Normal file
View File

@ -0,0 +1,377 @@
import { isMuted, playSound, setMuted } from './audio';
import { cursorCss } from './cursors';
import type { Engine, MessageKind, Transition, View } from './Engine';
import type { CursorKind, Hotspot, PuzzleDef, Scene } from './types';
import { getPuzzleFactory, type PuzzleContext, type PuzzleInstance } from '../puzzles/registry';
export interface RendererOptions {
/** Résout un chemin d'image du scénario ("images/key.svg") en URL utilisable. */
resolveImage(path: string): string;
onWin(): void;
onMenu(): void;
}
export function el<K extends keyof HTMLElementTagNameMap>(tag: K, className?: string, parent?: HTMLElement): HTMLElementTagNameMap[K] {
const e = document.createElement(tag);
if (className) e.className = className;
parent?.appendChild(e);
return e;
}
/** Flèche visible à l'écran pour les bandes de navigation. */
const ARROWS: Record<string, string> = {
__left: 'M20 12H5M11 5l-7 7 7 7',
__right: 'M4 12h15M13 5l7 7-7 7',
__back: 'M12 4v15M5 13l7 7 7-7',
};
function navArrow(id: string): HTMLElement {
const span = el('span', 'nav-arrow');
span.innerHTML = `<svg viewBox="0 0 24 24" aria-hidden="true"><path d="${ARROWS[id] ?? ''}" fill="none" stroke="currentColor" stroke-width="2.6" stroke-linecap="round" stroke-linejoin="round"/></svg>`;
return span;
}
export function formatTime(ms: number): string {
const s = Math.floor(ms / 1000);
return `${String(Math.floor(s / 60)).padStart(2, '0')}:${String(s % 60).padStart(2, '0')}`;
}
/**
* Interface commune autour du rendu : cadre 16:9, HUD et inventaire, messages,
* infobulles, mini-jeux, zones écran (navigation), clavier et mode debug.
* La sous-classe (ThreeRenderer) fournit le contenu de la scène.
*/
export abstract class BaseRenderer implements View {
readonly root: HTMLElement;
protected stage: HTMLElement;
protected sceneLayer: HTMLElement;
protected hotspotsEl: HTMLElement;
protected debugEl: HTMLElement;
protected debug = false;
private messageEl: HTMLElement;
private tooltipEl: HTMLElement;
private puzzleLayer: HTMLElement;
private inventoryEl: HTMLElement;
private timerEl: HTMLElement;
private heldEl: HTMLElement;
private soundBtn: HTMLButtonElement;
private messageTimer: number | undefined;
private clockTimer: number | undefined;
private puzzle: PuzzleInstance | null = null;
private dragStart: [number, number] | null = null;
private dragBox: HTMLElement | null = null;
private onMouseUpBound = (e: MouseEvent) => this.onDebugMouseUp(e);
constructor(
protected engine: Engine,
protected opts: RendererOptions,
) {
const [w, h] = engine.scenario.resolution;
this.root = el('div', 'game');
this.root.style.setProperty('--ratio', String(w / h));
const wrap = el('div', 'stage-wrap', this.root);
this.stage = el('div', 'stage', wrap);
this.sceneLayer = el('div', 'scenes', this.stage);
this.hotspotsEl = el('div', 'hotspots', this.stage);
this.messageEl = el('div', 'message', this.stage);
this.tooltipEl = el('div', 'tooltip', this.stage);
this.puzzleLayer = el('div', 'puzzle-layer', this.stage);
this.debugEl = el('div', 'debug-info', this.stage);
const hud = el('div', 'hud', this.root);
this.inventoryEl = el('div', 'inventory', hud);
const right = el('div', 'hud-right', hud);
this.timerEl = el('div', 'timer', right);
const hintBtn = el('button', 'hud-btn', right);
hintBtn.innerHTML = '<span>?</span> Indice';
hintBtn.title = 'Obtenir un indice (H)';
hintBtn.onclick = () => engine.nextHint();
this.soundBtn = el('button', 'hud-btn', right);
this.soundBtn.onclick = () => {
setMuted(!isMuted());
this.updateSoundBtn();
};
this.updateSoundBtn();
const menuBtn = el('button', 'hud-btn', right);
menuBtn.textContent = 'Menu';
menuBtn.onclick = () => opts.onMenu();
this.heldEl = el('div', 'held-item', this.root);
this.stage.addEventListener('contextmenu', (e) => {
e.preventDefault();
if (!this.puzzle) engine.goBack();
});
this.root.addEventListener('mousemove', (e) => this.onMouseMove(e));
this.stage.addEventListener('mousedown', (e) => this.onDebugMouseDown(e));
window.addEventListener('mouseup', this.onMouseUpBound);
window.addEventListener('keydown', this.onKey);
this.clockTimer = window.setInterval(() => (this.timerEl.textContent = formatTime(engine.state.elapsedMs)), 500);
}
// --- À fournir par le rendu ---------------------------------------------------------
abstract showScene(scene: Scene, transition: Transition): void;
/** Met à jour le contenu de la scène selon l'état (calques, objets 3D...). */
protected abstract refreshStage(instant: boolean): void;
/** Touche supplémentaire (mode debug notamment). */
protected onExtraKey(_e: KeyboardEvent): void {}
protected onDebugChanged(): void {}
/** Texte additionnel affiché dans la barre de debug. */
protected debugExtra(): string {
return '';
}
destroy(): void {
window.removeEventListener('keydown', this.onKey);
window.removeEventListener('mouseup', this.onMouseUpBound);
window.clearInterval(this.clockTimer);
window.clearTimeout(this.messageTimer);
this.puzzle?.destroy?.();
this.root.remove();
}
protected get puzzleOpen(): boolean {
return this.puzzle !== null;
}
private onKey = (e: KeyboardEvent): void => {
if (e.key === 'Escape') {
if (this.puzzle) this.closePuzzle();
else this.engine.goBack();
} else if (e.key === 'h' || e.key === 'H') {
this.engine.nextHint();
} else if (e.key === 'd' || e.key === 'D') {
this.debug = !this.debug;
this.stage.classList.toggle('debug', this.debug);
this.onDebugChanged();
this.refresh();
} else {
this.onExtraKey(e);
}
};
private updateSoundBtn(): void {
this.soundBtn.textContent = isMuted() ? 'Son : off' : 'Son : on';
}
// --- Rafraîchissement -----------------------------------------------------------------
refresh(instant = false): void {
this.refreshStage(instant);
this.renderRectHotspots();
this.renderInventory();
}
/** Zones écran (rect) : flèches de navigation et zones écran éventuelles. */
private renderRectHotspots(): void {
const scene = this.engine.currentScene;
const [w, h] = this.engine.scenario.resolution;
this.hotspotsEl.replaceChildren();
for (const hs of this.engine.activeHotspots(scene)) {
if (!hs.rect) continue;
const isNav = hs.id.startsWith('__');
const zone = el('div', `hotspot${isNav ? ' nav' : ''}`, this.hotspotsEl);
const [x, y, rw, rh] = hs.rect;
Object.assign(zone.style, {
left: `${(x / w) * 100}%`,
top: `${(y / h) * 100}%`,
width: `${(rw / w) * 100}%`,
height: `${(rh / h) * 100}%`,
cursor: this.cursorFor(hs),
});
zone.dataset.id = hs.id;
if (this.debug) zone.dataset.debug = hs.id;
if (isNav) zone.appendChild(navArrow(hs.id));
zone.addEventListener('click', (e) => {
e.stopPropagation();
if (this.dragBox || !this.canInteract()) return;
this.engine.click(hs);
});
zone.addEventListener('mouseenter', (e) => {
this.showTooltip(hs);
this.onMouseMove(e);
});
zone.addEventListener('mouseleave', () => this.hideTooltip());
}
}
/** Une sous-classe peut bloquer les clics (ex. caméra en mouvement). */
protected canInteract(): boolean {
return true;
}
protected cursorFor(hs: Hotspot): string {
if (this.engine.state.selected && !hs.id.startsWith('__')) return cursorCss('use');
let kind: CursorKind = 'look';
if (hs.cursor) kind = hs.cursor;
else {
const first = hs.interactions[hs.interactions.length - 1]?.do[0];
if (first && ('goto' in first || 'puzzle' in first)) kind = 'zoom';
else if (hs.interactions.some((i) => i.do.some((a) => 'give' in a))) kind = 'take';
}
return cursorCss(kind);
}
protected showTooltip(hs: Hotspot): void {
// En Difficile, pas d'infobulle sur les objets (seulement sur la navigation).
if (this.engine.state.difficulty === 'hard' && !hs.id.startsWith('__')) return this.hideTooltip();
const sel = this.engine.state.selected;
const label = sel && hs.label && !hs.id.startsWith('__') ? `Utiliser ${this.engine.getItem(sel)?.name ?? ''} sur : ${hs.label}` : hs.label;
if (!label) return this.hideTooltip();
this.tooltipEl.textContent = label;
this.tooltipEl.classList.add('visible');
}
protected hideTooltip(): void {
this.tooltipEl.classList.remove('visible');
}
// --- Inventaire -------------------------------------------------------------------
private renderInventory(): void {
const state = this.engine.state;
this.inventoryEl.replaceChildren();
const SLOTS = 6;
for (let i = 0; i < SLOTS; i++) {
const slot = el('button', 'slot', this.inventoryEl);
const id = state.inventory[i];
if (!id) {
slot.disabled = true;
continue;
}
const item = this.engine.getItem(id);
const img = el('img', '', slot);
img.src = item ? this.opts.resolveImage(item.icon) : '';
img.alt = item?.name ?? id;
img.draggable = false;
slot.title = item ? `${item.name}${item.description ? ' — ' + item.description : ''}` : id;
slot.dataset.item = id;
slot.classList.toggle('selected', state.selected === id);
slot.onclick = () => {
const sel = this.engine.state.selected;
if (sel && sel !== id) this.engine.combine(sel, id);
else this.engine.selectItem(id);
};
}
const held = state.selected ? this.engine.getItem(state.selected) : undefined;
if (held) {
this.heldEl.style.backgroundImage = `url("${this.opts.resolveImage(held.icon)}")`;
this.heldEl.classList.add('visible');
} else {
this.heldEl.classList.remove('visible');
}
}
// --- Messages ---------------------------------------------------------------------
showMessage(text: string, kind: MessageKind): void {
window.clearTimeout(this.messageTimer);
this.messageEl.className = `message visible ${kind}`;
this.messageEl.textContent = text;
if (kind === 'hint') playSound('beep');
this.messageTimer = window.setTimeout(() => this.hideMessage(), Math.max(3500, text.length * 60));
}
protected hideMessage(): void {
this.messageEl.classList.remove('visible');
}
// --- Puzzles ------------------------------------------------------------------------
openPuzzle(def: PuzzleDef, ctx: PuzzleContext): void {
this.closePuzzle();
const overlay = el('div', 'puzzle-overlay', this.puzzleLayer);
overlay.addEventListener('click', (e) => {
if (e.target === overlay) this.closePuzzle();
});
const box = el('div', 'puzzle-box', overlay);
if (def.title) el('div', 'puzzle-title', box).textContent = def.title;
const close = el('button', 'puzzle-close', box);
close.textContent = '×';
close.title = 'Fermer (Échap)';
close.onclick = () => this.closePuzzle();
const instance = getPuzzleFactory(def.type)(ctx);
box.appendChild(instance.el);
this.puzzle = { el: overlay, destroy: instance.destroy };
this.hideTooltip();
requestAnimationFrame(() => overlay.classList.add('visible'));
}
closePuzzle(): void {
if (!this.puzzle) return;
this.puzzle.destroy?.();
this.puzzle.el.remove();
this.puzzle = null;
}
showWin(): void {
this.closePuzzle();
this.hideMessage();
this.hideTooltip();
this.opts.onWin();
}
// --- Souris : objet tenu, infobulle, outil de debug ------------------------------
protected toImageCoords(e: MouseEvent): [number, number] {
const r = this.stage.getBoundingClientRect();
const [w, h] = this.engine.scenario.resolution;
return [Math.round(((e.clientX - r.left) / r.width) * w), Math.round(((e.clientY - r.top) / r.height) * h)];
}
protected onMouseMove(e: MouseEvent): void {
this.heldEl.style.transform = `translate(${e.clientX + 14}px, ${e.clientY + 14}px)`;
const r = this.stage.getBoundingClientRect();
// Décalage plus grand quand un objet est tenu, pour ne pas masquer son icône.
const dy = this.engine.state.selected ? 62 : 22;
const tx = Math.min(e.clientX - r.left + 18, r.width - this.tooltipEl.offsetWidth - 8);
this.tooltipEl.style.transform = `translate(${tx}px, ${e.clientY - r.top + dy}px)`;
if (this.debug) {
const [x, y] = this.toImageCoords(e);
const extra = this.debugExtra();
this.debugEl.textContent = `DEBUG · scène "${this.engine.currentScene.id}" · écran x=${x} y=${y}${extra ? ' · ' + extra : ''}`;
if (this.dragStart && this.dragBox) {
const [sx, sy] = this.dragStart;
const [w, h] = this.engine.scenario.resolution;
Object.assign(this.dragBox.style, {
left: `${(Math.min(sx, x) / w) * 100}%`,
top: `${(Math.min(sy, y) / h) * 100}%`,
width: `${(Math.abs(x - sx) / w) * 100}%`,
height: `${(Math.abs(y - sy) / h) * 100}%`,
});
}
}
}
/** Mode debug (touche D) : Maj+glisser trace une zone et copie son "rect" JSON. */
private onDebugMouseDown(e: MouseEvent): void {
if (!this.debug || !e.shiftKey || e.button !== 0) return;
e.preventDefault();
e.stopPropagation();
this.dragStart = this.toImageCoords(e);
this.dragBox = el('div', 'drag-box', this.stage);
}
private onDebugMouseUp(e: MouseEvent): void {
if (!this.dragStart || !this.dragBox) return;
const [sx, sy] = this.dragStart;
const [x, y] = this.toImageCoords(e);
const rect = `"rect": [${Math.min(sx, x)}, ${Math.min(sy, y)}, ${Math.abs(x - sx)}, ${Math.abs(y - sy)}]`;
this.copyToClipboard(rect);
const box = this.dragBox;
this.dragStart = null;
window.setTimeout(() => {
box.remove();
this.dragBox = null;
}, 1200);
}
protected copyToClipboard(text: string): void {
console.info(text);
navigator.clipboard?.writeText(text).catch(() => undefined);
this.showMessage(`${text} (copié)`, 'info');
}
}

266
src/engine/Engine.ts Normal file
View File

@ -0,0 +1,266 @@
import { playSound } from './audio';
import { checkAll, saveState, type GameState } from './state';
import type { Action, Hotspot, Interaction, Item, PuzzleDef, Scenario, Scene } from './types';
import type { PuzzleContext } from '../puzzles/registry';
export type MessageKind = 'info' | 'hint' | 'item';
export type Transition = 'fade' | 'zoom-in' | 'zoom-out' | 'turn-left' | 'turn-right' | 'none';
/**
* Ce que le moteur attend d'un rendu (aujourd'hui ThreeRenderer). Le moteur
* ne dépend d'aucune technologie d'affichage.
*/
export interface View {
showScene(scene: Scene, transition: Transition): void;
refresh(): void;
showMessage(text: string, kind: MessageKind): void;
openPuzzle(def: PuzzleDef, ctx: PuzzleContext): void;
closePuzzle(): void;
showWin(): void;
}
/** Bandes de navigation auto-générées (largeur en px dans le repère `resolution`). */
const NAV_SIZE = 90;
export class Engine {
private scenes = new Map<string, Scene>();
private items = new Map<string, Item>();
private puzzles = new Map<string, PuzzleDef>();
private view!: View;
private timer: ReturnType<typeof setInterval> | undefined;
constructor(
public readonly scenario: Scenario,
public readonly state: GameState,
/** Tests : résolution des mini-jeux sans délai d'animation. */
private readonly options: { instant?: boolean } = {},
) {
scenario.scenes.forEach((s) => this.scenes.set(s.id, s));
scenario.items.forEach((i) => this.items.set(i.id, i));
scenario.puzzles.forEach((p) => this.puzzles.set(p.id, p));
for (const [k, v] of Object.entries(scenario.vars ?? {})) if (state.vars[k] === undefined) state.vars[k] = v;
}
attach(view: View): void {
this.view = view;
}
start(): void {
this.view.showScene(this.currentScene, 'fade');
this.view.refresh();
if (this.state.elapsedMs === 0 && this.scenario.intro) {
this.view.showMessage(this.scenario.intro, 'info');
}
this.startTimer();
saveState(this.state);
}
stop(): void {
clearInterval(this.timer);
}
private startTimer(): void {
clearInterval(this.timer);
this.timer = setInterval(() => {
if (this.state.won || (typeof document !== 'undefined' && document.hidden)) return;
this.state.elapsedMs += 1000;
if (this.state.elapsedMs % 10000 === 0) saveState(this.state);
}, 1000);
}
// --- Lecture ------------------------------------------------------------------
get currentScene(): Scene {
const s = this.scenes.get(this.state.scene);
if (!s) throw new Error(`Scène introuvable : ${this.state.scene}`);
return s;
}
getItem(id: string): Item | undefined {
return this.items.get(id);
}
/** Zones actives de la scène, y compris les bandes de navigation générées. */
activeHotspots(scene: Scene): Hotspot[] {
const [w, h] = this.scenario.resolution;
const nav: Hotspot[] = [];
if (scene.left) {
nav.push({ id: '__left', rect: [0, 0, NAV_SIZE, h], cursor: 'left', label: 'Tourner à gauche', interactions: [{ do: [{ goto: scene.left }] }] });
}
if (scene.right) {
nav.push({ id: '__right', rect: [w - NAV_SIZE, 0, NAV_SIZE, h], cursor: 'right', label: 'Tourner à droite', interactions: [{ do: [{ goto: scene.right }] }] });
}
if (scene.back) {
nav.push({ id: '__back', rect: [NAV_SIZE, h - NAV_SIZE, w - 2 * NAV_SIZE, NAV_SIZE], cursor: 'back', label: 'Reculer', interactions: [{ do: [{ goto: scene.back }] }] });
}
const own = scene.hotspots.filter((hs) => checkAll(this.state, hs.visibleWhen));
// Les zones du scénario passent au-dessus des bandes de navigation.
return [...nav, ...own];
}
// --- Interactions -------------------------------------------------------------
/** Clic sur une zone. Renvoie true si une interaction a été exécutée. */
click(hotspot: Hotspot): boolean {
const isNav = hotspot.id.startsWith('__');
const match: Interaction | undefined = hotspot.interactions.find((i) => checkAll(this.state, i.when));
if (this.state.selected && !isNav) {
const usesSelection = match?.when?.some((c) => c === `selected:${this.state.selected}`);
const item = this.getItem(this.state.selected);
// Dans tous les cas, l'objet est « rangé » après usage : on le reprend en main si besoin.
this.state.selected = null;
if (!usesSelection) {
this.view.showMessage(`${item?.name ?? 'Cet objet'} ne sert à rien ici.`, 'info');
this.view.refresh();
return false;
}
}
if (!match) return false;
this.run(match.do);
return true;
}
/** Sélectionner un objet puis cliquer sur un autre objet de l'inventaire. */
/** Renvoie true si la combinaison existe. */
combine(a: string, b: string): boolean {
const combo = this.scenario.combinations?.find((c) => (c.items[0] === a && c.items[1] === b) || (c.items[0] === b && c.items[1] === a));
this.state.selected = null;
if (!combo) {
const na = this.getItem(a)?.name ?? a;
const nb = this.getItem(b)?.name ?? b;
this.view.showMessage(`Combiner « ${na} » et « ${nb} » ne donne rien.`, 'info');
this.view.refresh();
return false;
}
this.run(combo.do);
return true;
}
goBack(): void {
const scene = this.currentScene;
if (this.state.selected) {
this.state.selected = null;
this.view.refresh();
} else if (scene.back) {
this.run([{ goto: scene.back }]);
}
}
selectItem(id: string): void {
this.state.selected = this.state.selected === id ? null : id;
playSound('click');
this.view.refresh();
}
nextHint(): void {
const idx = this.scenario.hints.findIndex((g) => checkAll(this.state, g.when));
if (idx < 0) {
this.view.showMessage('Pas d’indice pour le moment.', 'hint');
return;
}
const group = this.scenario.hints[idx];
const level = this.state.hintLevels[idx] ?? 0;
const shown = Math.min(level, group.hints.length - 1);
if (level < group.hints.length) {
this.state.hintLevels[idx] = level + 1;
this.state.hintsUsed++;
saveState(this.state);
}
const suffix = group.hints.length > 1 ? ` (${shown + 1}/${group.hints.length})` : '';
this.view.showMessage(group.hints[shown] + suffix, 'hint');
this.view.refresh();
}
run(actions: Action[]): void {
for (const action of actions) this.exec(action);
this.runTriggers();
saveState(this.state);
this.view.refresh();
}
/** Exécute les déclencheurs dont les conditions sont devenues vraies (une fois chacun). */
private runTriggers(): void {
for (let pass = 0; pass < 5; pass++) {
const ready = (this.scenario.triggers ?? []).filter((t) => !this.state.fired[t.id] && checkAll(this.state, t.when));
if (!ready.length) return;
for (const t of ready) {
this.state.fired[t.id] = true;
for (const a of t.do) this.exec(a);
}
}
}
private exec(action: Action): void {
if ('goto' in action) {
const from = this.currentScene;
const to = this.scenes.get(action.goto);
if (!to) return console.error(`goto : scène inconnue "${action.goto}"`);
this.state.scene = to.id;
let t: Transition = 'fade';
if (from.left === to.id) t = 'turn-left';
else if (from.right === to.id) t = 'turn-right';
else if (from.back === to.id) t = 'zoom-out';
else if (to.back === from.id) t = 'zoom-in';
playSound('step');
this.view.showScene(to, t);
} else if ('message' in action) {
this.view.showMessage(action.message, 'info');
} else if ('setFlag' in action) {
this.state.flags[action.setFlag] = true;
} else if ('clearFlag' in action) {
delete this.state.flags[action.clearFlag];
} else if ('give' in action) {
if (!this.state.inventory.includes(action.give)) this.state.inventory.push(action.give);
playSound('pickup');
} else if ('remove' in action) {
this.state.inventory = this.state.inventory.filter((i) => i !== action.remove);
if (this.state.selected === action.remove) this.state.selected = null;
} else if ('puzzle' in action) {
this.openPuzzle(action.puzzle);
} else if ('sound' in action) {
playSound(action.sound);
} else if ('add' in action) {
let v = (this.state.vars[action.add] ?? 0) + (action.value ?? 1);
if (action.mod) v = ((v % action.mod) + action.mod) % action.mod;
this.state.vars[action.add] = v;
} else if ('set' in action) {
this.state.vars[action.set] = action.value;
} else if ('if' in action) {
for (const a of checkAll(this.state, action.if) ? action.then : (action.else ?? [])) this.exec(a);
} else if ('win' in action) {
this.state.won = true;
this.state.selected = null;
saveState(this.state);
this.view.showWin();
}
}
private openPuzzle(id: string): void {
const def = this.puzzles.get(id);
if (!def) return console.error(`Puzzle inconnu "${id}"`);
const ctx: PuzzleContext = {
def,
data: this.state.puzzleData[id],
alreadySolved: !!this.state.solved[id],
save: (data) => {
this.state.puzzleData[id] = data;
saveState(this.state);
},
solve: () => {
if (this.state.solved[id]) return;
this.state.solved[id] = true;
playSound('success');
const finish = () => {
this.view.closePuzzle();
this.run(def.onSolve);
};
if (this.options.instant) finish();
else setTimeout(finish, 1100);
},
close: () => this.view.closePuzzle(),
sound: playSound,
};
this.view.openPuzzle(def, ctx);
}
}

112
src/engine/audio.ts Normal file
View File

@ -0,0 +1,112 @@
import type { SoundName } from './types';
/**
* Petits bruitages synthétisés (WebAudio) pour le POC : aucun fichier audio
* à fournir. À remplacer plus tard par de vrais sons.
*/
let ctx: AudioContext | null = null;
let muted = false;
function ac(): AudioContext | null {
if (muted) return null;
try {
ctx ??= new AudioContext();
if (ctx.state === 'suspended') void ctx.resume();
return ctx;
} catch {
return null;
}
}
function tone(freq: number, dur: number, type: OscillatorType = 'sine', vol = 0.15, delay = 0, slideTo?: number) {
const a = ac();
if (!a) return;
const t = a.currentTime + delay;
const osc = a.createOscillator();
const gain = a.createGain();
osc.type = type;
osc.frequency.setValueAtTime(freq, t);
if (slideTo) osc.frequency.exponentialRampToValueAtTime(slideTo, t + dur);
gain.gain.setValueAtTime(vol, t);
gain.gain.exponentialRampToValueAtTime(0.0001, t + dur);
osc.connect(gain).connect(a.destination);
osc.start(t);
osc.stop(t + dur + 0.02);
}
function noise(dur: number, vol = 0.12, delay = 0, freq = 1200) {
const a = ac();
if (!a) return;
const t = a.currentTime + delay;
const buf = a.createBuffer(1, Math.ceil(a.sampleRate * dur), a.sampleRate);
const data = buf.getChannelData(0);
for (let i = 0; i < data.length; i++) data[i] = Math.random() * 2 - 1;
const src = a.createBufferSource();
src.buffer = buf;
const filter = a.createBiquadFilter();
filter.type = 'bandpass';
filter.frequency.value = freq;
const gain = a.createGain();
gain.gain.setValueAtTime(vol, t);
gain.gain.exponentialRampToValueAtTime(0.0001, t + dur);
src.connect(filter).connect(gain).connect(a.destination);
src.start(t);
}
export function playSound(name: SoundName): void {
switch (name) {
case 'click':
tone(900, 0.05, 'square', 0.05);
break;
case 'step':
noise(0.12, 0.06, 0, 400);
break;
case 'beep':
tone(660, 0.08, 'sine', 0.08);
break;
case 'error':
tone(180, 0.25, 'sawtooth', 0.08);
tone(140, 0.3, 'sawtooth', 0.08, 0.12);
break;
case 'success':
[523, 659, 784, 1047].forEach((f, i) => tone(f, 0.25, 'triangle', 0.12, i * 0.09));
break;
case 'drawer':
noise(0.5, 0.15, 0, 300);
tone(90, 0.4, 'sine', 0.2, 0.05, 60);
break;
case 'pickup':
tone(1200, 0.08, 'triangle', 0.1);
tone(1600, 0.12, 'triangle', 0.1, 0.07);
break;
case 'dial':
noise(0.03, 0.12, 0, 3000);
tone(1400, 0.03, 'square', 0.03);
break;
case 'switch':
noise(0.05, 0.3, 0, 900);
tone(70, 0.25, 'square', 0.12, 0.02, 40);
break;
case 'power':
tone(55, 1.2, 'sawtooth', 0.06, 0.1);
tone(110, 1.2, 'sine', 0.06, 0.1);
noise(0.08, 0.15, 0, 4000);
break;
case 'reveal':
[392, 523, 659].forEach((f, i) => tone(f, 0.6, 'sine', 0.07, i * 0.12));
break;
case 'unlock':
noise(0.06, 0.2, 0, 2500);
noise(0.08, 0.25, 0.18, 1800);
tone(220, 0.3, 'square', 0.05, 0.2, 110);
break;
}
}
export function setMuted(value: boolean): void {
muted = value;
}
export function isMuted(): boolean {
return muted;
}

27
src/engine/cursors.ts Normal file
View File

@ -0,0 +1,27 @@
import type { CursorKind } from './types';
/** Curseurs personnalisés (SVG inline) pour signaler le type d'interaction, façon Myst. */
const stroke = 'stroke="#111" stroke-width="2.5" stroke-linejoin="round" stroke-linecap="round"';
const shapes: Record<CursorKind, string> = {
look: `<circle cx="16" cy="16" r="6" fill="#f4e6c8" ${stroke}/><circle cx="16" cy="16" r="2" fill="#111"/>`,
zoom: `<circle cx="13" cy="13" r="8" fill="rgba(244,230,200,.35)" stroke="#f4e6c8" stroke-width="3"/><path d="M19 19l8 8" stroke="#f4e6c8" stroke-width="4" stroke-linecap="round"/><circle cx="13" cy="13" r="8" fill="none" stroke="#111" stroke-width="1"/>`,
take: `<path d="M10 28V14a2 2 0 0 1 4 0v-6a2 2 0 0 1 4 0v6-2a2 2 0 0 1 4 0v4a2 2 0 0 1 4 0v8c0 4-3 6-6 6h-4c-3 0-6-2-6-4z" fill="#f4e6c8" ${stroke}/>`,
use: `<path d="M6 6l8 20 3-8 8-3z" fill="#f4e6c8" ${stroke}/><circle cx="24" cy="24" r="5" fill="#e0a83a" ${stroke}/>`,
// Vraies flèches (tige + pointe) pour la navigation
left: `<path d="M3 16L14 5v7h15v8H14v7z" fill="#f4e6c8" ${stroke}/>`,
right: `<path d="M29 16L18 5v7H3v8h15v7z" fill="#f4e6c8" ${stroke}/>`,
back: `<path d="M16 29L5 18h7V3h8v15h7z" fill="#f4e6c8" ${stroke}/>`,
};
const cache = new Map<CursorKind, string>();
export function cursorCss(kind: CursorKind): string {
let css = cache.get(kind);
if (!css) {
const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 32 32">${shapes[kind]}</svg>`;
css = `url("data:image/svg+xml,${encodeURIComponent(svg)}") 16 16, pointer`;
cache.set(kind, css);
}
return css;
}

View File

@ -0,0 +1,114 @@
import type { Action, Condition, Scenario } from './types';
/**
* Analyse de cohérence « logique » d'un scénario, plus poussée que le
* validateur de références : drapeaux jamais levés, objets jamais obtenus,
* scènes inaccessibles, paramètres de mini-jeux incohérents...
* Utilisée par les tests (npm test) et, plus tard, par l'éditeur de niveaux.
*/
export function analyzeScenario(s: Scenario): string[] {
const errors: string[] = [];
const actions: { where: string; a: Action }[] = [];
const conds: { where: string; c: Condition }[] = [];
const addActions = (where: string, list: Action[]) => {
for (const a of list) {
actions.push({ where, a });
if ('if' in a) {
a.if.forEach((c) => conds.push({ where, c }));
addActions(where, a.then);
addActions(where, a.else ?? []);
}
}
};
const addConds = (where: string, list?: Condition[]) => list?.forEach((c) => conds.push({ where, c }));
for (const sc of s.scenes) {
const ids = new Set<string>();
for (const hs of sc.hotspots) {
const where = `scène ${sc.id} / zone ${hs.id}`;
if (ids.has(hs.id)) errors.push(`${where} : identifiant de zone en double`);
ids.add(hs.id);
addConds(where, hs.visibleWhen);
hs.interactions.forEach((it) => {
addConds(where, it.when);
addActions(where, it.do);
});
}
}
s.puzzles.forEach((p) => addActions(`puzzle ${p.id}`, p.onSolve));
(s.triggers ?? []).forEach((t) => {
addConds(`déclencheur ${t.id}`, t.when);
addActions(`déclencheur ${t.id}`, t.do);
});
(s.combinations ?? []).forEach((c) => addActions(`combinaison ${c.items.join('+')}`, c.do));
s.hints.forEach((h, i) => addConds(`indices #${i}`, h.when));
(s.props ?? []).forEach((p) => addConds(`props ${p.object}`, p.when));
const parse = (c: string) => {
const raw = c.replace(/^!/, '');
const kind = raw.slice(0, raw.indexOf(':'));
const key = kind === 'var' ? raw.slice(4).split(/[=!<>]/)[0] : raw.slice(raw.indexOf(':') + 1);
return { kind, key };
};
// Drapeaux testés mais jamais levés (faute de frappe probable)
const flagsSet = new Set(actions.flatMap(({ a }) => ('setFlag' in a ? [a.setFlag] : [])));
for (const { where, c } of conds) {
const { kind, key } = parse(c);
if (kind === 'flag' && !flagsSet.has(key)) errors.push(`${where} : le drapeau "${key}" n'est jamais levé (setFlag)`);
}
// Objets : obtenus quelque part, et utilisés quelque part
const given = new Set(actions.flatMap(({ a }) => ('give' in a ? [a.give] : [])));
const usedItems = new Set<string>();
for (const { c } of conds) {
const { kind, key } = parse(c);
if (kind === 'item' || kind === 'selected') usedItems.add(key);
}
(s.combinations ?? []).forEach((c) => c.items.forEach((i) => usedItems.add(i)));
for (const item of s.items) {
if (!given.has(item.id)) errors.push(`objet "${item.id}" : jamais donné au joueur (give)`);
if (!usedItems.has(item.id)) errors.push(`objet "${item.id}" : ne sert jamais (ni condition, ni combinaison)`);
}
// Variables lues mais jamais écrites ni initialisées
const varsWritten = new Set([...Object.keys(s.vars ?? {}), ...actions.flatMap(({ a }) => ('add' in a ? [a.add] : 'set' in a ? [a.set] : []))]);
for (const { where, c } of conds) {
const { kind, key } = parse(c);
if (kind === 'var' && !varsWritten.has(key)) errors.push(`${where} : la variable "${key}" n'est jamais modifiée`);
}
for (const p of s.props ?? []) if (p.spin && !varsWritten.has(p.spin.var)) errors.push(`props ${p.object} : variable "${p.spin.var}" jamais modifiée`);
// Énigmes : chacune doit pouvoir être ouverte
const opened = new Set(actions.flatMap(({ a }) => ('puzzle' in a ? [a.puzzle] : [])));
for (const p of s.puzzles) if (!opened.has(p.id)) errors.push(`puzzle "${p.id}" : jamais ouvert (action puzzle)`);
for (const { where, c } of conds) {
const { kind, key } = parse(c);
if (kind === 'solved' && !opened.has(key)) errors.push(`${where} : "${key}" n'est jamais ouvert, il ne peut pas être résolu`);
}
// Déclencheurs : identifiants uniques
const trig = new Set<string>();
for (const t of s.triggers ?? []) {
if (trig.has(t.id)) errors.push(`déclencheur "${t.id}" en double`);
trig.add(t.id);
}
// Scènes accessibles depuis le départ
const edges = new Map<string, string[]>();
for (const sc of s.scenes) {
const out = [sc.left, sc.right, sc.back].filter((x): x is string => !!x);
sc.hotspots.forEach((hs) => hs.interactions.forEach((it) => it.do.forEach((a) => 'goto' in a && out.push(a.goto))));
edges.set(sc.id, out);
}
const seen = new Set([s.startScene]);
const queue = [s.startScene];
while (queue.length) for (const n of edges.get(queue.shift()!) ?? []) if (!seen.has(n)) (seen.add(n), queue.push(n));
for (const sc of s.scenes) if (!seen.has(sc.id)) errors.push(`scène "${sc.id}" : inaccessible depuis "${s.startScene}"`);
// La partie doit pouvoir se gagner
if (!actions.some(({ a }) => 'win' in a)) errors.push('aucune action { "win": true } : la partie ne peut pas être gagnée');
return errors;
}

View File

@ -0,0 +1,104 @@
import { VAR_RE } from './state';
import type { Action, Condition, Scenario } from './types';
/**
* Les scénarios vivent dans src/scenarios/<dossier>/ : un scenario.json et un
* dossier images/. Vite les embarque au build ; plus tard (éditeur, niveaux
* communautaires) on pourra charger le même format depuis un fichier externe.
*/
const scenarioFiles = import.meta.glob('../scenarios/*/scenario.json', { eager: true, import: 'default' }) as Record<string, Scenario>;
const imageUrls = import.meta.glob('../scenarios/*/images/*.{svg,png,jpg,jpeg,webp}', {
eager: true,
query: '?url',
import: 'default',
}) as Record<string, string>;
export interface LoadedScenario {
folder: string;
scenario: Scenario;
resolveImage(path: string): string;
/** Problèmes détectés par le validateur (vide si tout va bien). */
errors: string[];
}
export function listScenarios(): LoadedScenario[] {
return Object.entries(scenarioFiles)
.map(([key, scenario]) => {
const folder = key.split('/')[2];
const resolveImage = (path: string) => {
const url = imageUrls[`../scenarios/${folder}/${path}`];
if (!url) console.warn(`[${folder}] image introuvable : ${path}`);
return url ?? '';
};
const errors = validateScenario(scenario, (p) => !!imageUrls[`../scenarios/${folder}/${p}`]);
return { folder, scenario, resolveImage, errors };
})
.sort((a, b) => a.scenario.difficulty - b.scenario.difficulty || a.folder.localeCompare(b.folder));
}
/** Vérifie la cohérence des références (scènes, objets, puzzles, images). Sert aussi de base au futur éditeur. */
export function validateScenario(s: Scenario, imageExists: (p: string) => boolean): string[] {
const errors: string[] = [];
const scenes = new Set(s.scenes.map((x) => x.id));
const items = new Set(s.items.map((x) => x.id));
const puzzles = new Set(s.puzzles.map((x) => x.id));
const checkConds = (where: string, conds?: Condition[]) =>
conds?.forEach((c) => {
if (/^!?var:/.test(c)) {
if (!VAR_RE.test(c.replace(/^!/, ''))) errors.push(`${where} : condition invalide "${c}"`);
return;
}
const m = /^!?(flag|item|selected|solved):(.+)$/.exec(c);
if (!m) errors.push(`${where} : condition invalide "${c}"`);
else if ((m[1] === 'item' || m[1] === 'selected') && !items.has(m[2])) errors.push(`${where} : objet inconnu "${m[2]}"`);
else if (m[1] === 'solved' && !puzzles.has(m[2])) errors.push(`${where} : puzzle inconnu "${m[2]}"`);
});
const checkActions = (where: string, actions: Action[]): void =>
actions.forEach((a) => {
if ('if' in a) {
checkConds(where, a.if);
checkActions(where, a.then);
checkActions(where, a.else ?? []);
}
if ('remove' in a && !items.has(a.remove)) errors.push(`${where} : objet inconnu "${a.remove}"`);
if ('goto' in a && !scenes.has(a.goto)) errors.push(`${where} : scène inconnue "${a.goto}"`);
if ('give' in a && !items.has(a.give)) errors.push(`${where} : objet inconnu "${a.give}"`);
if ('puzzle' in a && !puzzles.has(a.puzzle)) errors.push(`${where} : puzzle inconnu "${a.puzzle}"`);
});
const checkImage = (where: string, p: string) => {
if (!imageExists(p)) errors.push(`${where} : image manquante "${p}"`);
};
if (!scenes.has(s.startScene)) errors.push(`startScene inconnue "${s.startScene}"`);
if (!s.world) errors.push(`"world" manquant`);
for (const sc of s.scenes) {
if (!sc.camera) errors.push(`scène ${sc.id} : "camera" manquante`);
for (const nav of [sc.left, sc.right, sc.back]) if (nav && !scenes.has(nav)) errors.push(`scène ${sc.id} : navigation vers "${nav}" inconnue`);
for (const hs of sc.hotspots) {
const where = `scène ${sc.id} / zone ${hs.id}`;
if (!hs.rect && !hs.object) errors.push(`${where} : ni "rect" ni "object"`);
checkConds(where, hs.visibleWhen);
hs.interactions.forEach((it) => {
checkConds(where, it.when);
checkActions(where, it.do);
});
}
}
s.items.forEach((it) => checkImage(`objet ${it.id}`, it.icon));
s.puzzles.forEach((p) => checkActions(`puzzle ${p.id}`, p.onSolve));
s.hints.forEach((h, i) => checkConds(`indices #${i}`, h.when));
s.props?.forEach((p, i) => checkConds(`props #${i} (${p.object})`, p.when));
s.triggers?.forEach((t) => {
checkConds(`déclencheur ${t.id}`, t.when);
checkActions(`déclencheur ${t.id}`, t.do);
});
s.combinations?.forEach((c) => {
const where = `combinaison ${c.items.join(' + ')}`;
c.items.forEach((i) => items.has(i) || errors.push(`${where} : objet inconnu "${i}"`));
checkActions(where, c.do);
});
if (errors.length) console.warn(`Scénario "${s.id}" : ${errors.length} problème(s)\n` + errors.join('\n'));
return errors;
}

117
src/engine/state.ts Normal file
View File

@ -0,0 +1,117 @@
import type { Condition, Difficulty } from './types';
export interface GameState {
scenarioId: string;
scene: string;
flags: Record<string, boolean>;
inventory: string[];
selected: string | null;
solved: Record<string, boolean>;
/** État interne libre de chaque mini-jeu (ex. couleurs déjà posées). */
puzzleData: Record<string, unknown>;
/** Niveau d'indice déjà révélé, par groupe d'indices. */
hintLevels: Record<number, number>;
hintsUsed: number;
elapsedMs: number;
won: boolean;
/** Variables numériques (molettes, compteurs...). */
vars: Record<string, number>;
/** Déclencheurs déjà exécutés. */
fired: Record<string, boolean>;
difficulty: Difficulty;
}
export function newState(scenarioId: string, startScene: string, difficulty: Difficulty = 'easy'): GameState {
return {
scenarioId,
vars: {},
fired: {},
difficulty,
scene: startScene,
flags: {},
inventory: [],
selected: null,
solved: {},
puzzleData: {},
hintLevels: {},
hintsUsed: 0,
elapsedMs: 0,
won: false,
};
}
export const VAR_RE = /^var:([\w-]+)(=|!=|>=|<=|>|<)(-?\d+(?:\.\d+)?)$/;
export function checkCondition(state: GameState, cond: Condition): boolean {
const negate = cond.startsWith('!');
const raw = negate ? cond.slice(1) : cond;
if (raw.startsWith('var:')) {
const m = VAR_RE.exec(raw);
if (!m) {
console.warn(`Condition invalide : "${cond}"`);
return false;
}
const v = state.vars[m[1]] ?? 0;
const n = Number(m[3]);
const ok = { '=': v === n, '!=': v !== n, '>=': v >= n, '<=': v <= n, '>': v > n, '<': v < n }[m[2]] ?? false;
return negate ? !ok : ok;
}
const sep = raw.indexOf(':');
const kind = raw.slice(0, sep);
const key = raw.slice(sep + 1);
let result: boolean;
switch (kind) {
case 'flag':
result = !!state.flags[key];
break;
case 'item':
result = state.inventory.includes(key);
break;
case 'selected':
result = state.selected === key;
break;
case 'solved':
result = !!state.solved[key];
break;
default:
console.warn(`Condition inconnue : "${cond}"`);
result = false;
}
return negate ? !result : result;
}
export function checkAll(state: GameState, conds: Condition[] | undefined): boolean {
return !conds || conds.every((c) => checkCondition(state, c));
}
// --- Sauvegarde locale (navigateur / futur Electron) ---------------------------
const SAVE_PREFIX = 'escape-game:save:';
export function saveState(state: GameState): void {
try {
localStorage.setItem(SAVE_PREFIX + state.scenarioId, JSON.stringify(state));
} catch {
/* stockage indisponible : on joue sans sauvegarde */
}
}
export function loadState(scenarioId: string): GameState | null {
try {
const raw = localStorage.getItem(SAVE_PREFIX + scenarioId);
if (!raw) return null;
const saved = JSON.parse(raw) as Partial<GameState>;
// Complète les sauvegardes d'anciennes versions avec les champs récents.
return { ...newState(scenarioId, saved.scene ?? ''), ...saved } as GameState;
} catch {
return null;
}
}
export function clearSave(scenarioId: string): void {
try {
localStorage.removeItem(SAVE_PREFIX + scenarioId);
} catch {
/* ignore */
}
}

View File

@ -0,0 +1,486 @@
import * as THREE from 'three';
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js';
import { RoomEnvironment } from 'three/examples/jsm/environments/RoomEnvironment.js';
import { EffectComposer } from 'three/examples/jsm/postprocessing/EffectComposer.js';
import { OutlinePass } from 'three/examples/jsm/postprocessing/OutlinePass.js';
import { OutputPass } from 'three/examples/jsm/postprocessing/OutputPass.js';
import { RenderPass } from 'three/examples/jsm/postprocessing/RenderPass.js';
import { UnrealBloomPass } from 'three/examples/jsm/postprocessing/UnrealBloomPass.js';
import { BaseRenderer, el, type RendererOptions } from '../BaseRenderer';
import type { Engine, Transition } from '../Engine';
import { checkAll } from '../state';
import type { CameraView, Hotspot, Scene } from '../types';
import { buildWorld, type World } from '../../worlds';
import { PICK_LAYER } from '../../worlds/common';
interface CamPose {
pos: THREE.Vector3;
quat: THREE.Quaternion;
fov: number;
}
interface PropEntry {
obj: THREE.Object3D;
basePos: THREE.Vector3;
baseQuat: THREE.Quaternion;
baseVisible: boolean;
mats: { mat: THREE.MeshStandardMaterial; color: THREE.Color; emissive: THREE.Color; intensity: number }[];
}
interface Tween {
obj: THREE.Object3D;
fromPos: THREE.Vector3;
toPos: THREE.Vector3;
fromQuat: THREE.Quaternion;
toQuat: THREE.Quaternion;
t: number;
dur: number;
}
const ease = (t: number) => (t < 0.5 ? 4 * t * t * t : 1 - Math.pow(-2 * t + 2, 3) / 2);
const round = (n: number) => Math.round(n * 100) / 100;
/**
* Rendu 3D temps réel (three.js) à caméras fixes. Chaque scène du scénario est
* un point de vue ; on passe de l'un à l'autre par un mouvement de caméra.
* Les zones cliquables sont des objets 3D nommés (raycast + contour au survol),
* et les changements d'état visuels sont des règles animées (props).
*/
export class ThreeRenderer extends BaseRenderer {
private gl: THREE.WebGLRenderer;
private scene3d = new THREE.Scene();
private camera = new THREE.PerspectiveCamera(55, 16 / 9, 0.02, 40);
private composer: EffectComposer;
private outline: OutlinePass;
private bloom: UnrealBloomPass;
private world: World;
private raycaster = new THREE.Raycaster();
private pointer = new THREE.Vector2();
private hotspotByName = new Map<string, Hotspot>();
private hovered: Hotspot | null = null;
private camAnim: { from: CamPose; to: CamPose; t: number; dur: number } | null = null;
private props = new Map<string, PropEntry>();
private tweens: Tween[] = [];
private clock = new THREE.Clock();
private raf = 0;
private resizeObs: ResizeObserver;
private controls: OrbitControls | null = null;
private firstScene = true;
private wasAnimating = false;
private downAt: [number, number] = [0, 0];
private debugHit = '';
private loadingEl: HTMLElement;
/** Rendu à la demande : on ne redessine que si quelque chose a changé. */
private dirty = true;
private hoveredObj: THREE.Object3D | null = null;
readonly quality: 'high' | 'low';
/** ?test=1 : basse qualité, caméra et objets sans animation (tests automatisés). */
readonly testMode: boolean;
constructor(engine: Engine, opts: RendererOptions) {
super(engine, opts);
this.stage.classList.add('three');
// Qualité : ?quality=low dans l'URL (ou localStorage "escape-game:quality") pour les petites configs.
const params = new URLSearchParams(location.search);
this.testMode = params.get('test') === '1';
let q: string | null = this.testMode ? 'low' : params.get('quality');
try {
q ??= localStorage.getItem('escape-game:quality');
} catch {
/* ignore */
}
this.quality = q === 'low' ? 'low' : 'high';
const high = this.quality === 'high';
this.gl = new THREE.WebGLRenderer({ antialias: true, powerPreference: 'high-performance' });
this.gl.setPixelRatio(high ? Math.min(window.devicePixelRatio, 2) : 1);
this.gl.outputColorSpace = THREE.SRGBColorSpace;
this.gl.toneMapping = THREE.ACESFilmicToneMapping;
this.gl.toneMappingExposure = 1.15;
this.gl.shadowMap.enabled = high;
this.gl.shadowMap.type = THREE.PCFSoftShadowMap;
this.sceneLayer.appendChild(this.gl.domElement);
this.loadingEl = el('div', 'loading', this.sceneLayer);
this.loadingEl.textContent = 'Chargement de la pièce…';
this.scene3d.background = new THREE.Color('#050607');
this.world = buildWorld(engine.scenario.world ?? 'bureau');
this.scene3d.add(this.world.root);
// Reflets discrets (laiton, miroir) via une carte d'environnement générée.
const pmrem = new THREE.PMREMGenerator(this.gl);
this.scene3d.environment = pmrem.fromScene(new RoomEnvironment(), 0.04).texture;
this.scene3d.environmentIntensity = 0.12;
pmrem.dispose();
this.composer = new EffectComposer(this.gl);
this.composer.addPass(new RenderPass(this.scene3d, this.camera));
this.outline = new OutlinePass(new THREE.Vector2(1280, 720), this.scene3d, this.camera);
Object.assign(this.outline, { edgeStrength: 3.5, edgeGlow: 0.4, edgeThickness: 1.2 });
this.outline.visibleEdgeColor.set('#ffd98a');
this.outline.hiddenEdgeColor.set('#000000');
this.composer.addPass(this.outline);
this.bloom = new UnrealBloomPass(new THREE.Vector2(1280, 720), 0.45, 0.5, 0.82);
if (high) this.composer.addPass(this.bloom);
this.composer.addPass(new OutputPass());
this.indexWorld();
this.raycaster.layers.enable(PICK_LAYER);
const canvas = this.gl.domElement;
canvas.addEventListener('pointermove', (e) => this.onPointerMove(e));
canvas.addEventListener('pointerdown', (e) => (this.downAt = [e.clientX, e.clientY]));
canvas.addEventListener('click', (e) => this.onClick(e));
canvas.addEventListener('pointerleave', () => this.setHovered(null, null));
this.resizeObs = new ResizeObserver(() => this.resize());
this.resizeObs.observe(this.stage);
this.resize();
this.loop();
}
destroy(): void {
cancelAnimationFrame(this.raf);
this.resizeObs.disconnect();
this.controls?.dispose();
this.world.root.traverse((o) => {
const mesh = o as THREE.Mesh;
if (!mesh.isMesh) return;
mesh.geometry.dispose();
for (const m of Array.isArray(mesh.material) ? mesh.material : [mesh.material]) {
(m as THREE.MeshStandardMaterial).map?.dispose();
m.dispose();
}
});
this.composer.dispose();
this.gl.dispose();
super.destroy();
}
// --- Préparation ------------------------------------------------------------------------
/** Mémorise l'état initial des objets pilotés par des règles, et vérifie les noms. */
private indexWorld(): void {
const scenario = this.engine.scenario;
const missing = new Set<string>();
for (const rule of scenario.props ?? []) {
if (this.props.has(rule.object)) continue;
const obj = this.world.root.getObjectByName(rule.object);
if (!obj) {
missing.add(rule.object);
continue;
}
const mats: PropEntry['mats'] = [];
obj.traverse((o) => {
const mesh = o as THREE.Mesh;
if (!mesh.isMesh) return;
for (const m of Array.isArray(mesh.material) ? mesh.material : [mesh.material]) {
const sm = m as THREE.MeshStandardMaterial;
if (sm.emissive) mats.push({ mat: sm, color: sm.color.clone(), emissive: sm.emissive.clone(), intensity: sm.emissiveIntensity });
}
});
this.props.set(rule.object, { obj, basePos: obj.position.clone(), baseQuat: obj.quaternion.clone(), baseVisible: obj.visible, mats });
}
for (const scene of scenario.scenes)
for (const hs of scene.hotspots)
for (const name of ([] as string[]).concat(hs.object ?? [])) if (!this.world.root.getObjectByName(name)) missing.add(name);
if (missing.size) console.warn(`Monde "${scenario.world}" : objets introuvables → ${[...missing].join(', ')}`);
}
private resize(): void {
const w = this.stage.clientWidth;
const h = this.stage.clientHeight;
if (!w || !h) return;
this.gl.setSize(w, h, false);
this.composer.setSize(w, h);
this.camera.aspect = w / h;
this.camera.updateProjectionMatrix();
this.dirty = true;
}
// --- Scènes = points de vue ---------------------------------------------------------------
private poseOf(view: CameraView): CamPose {
const tmp = new THREE.PerspectiveCamera();
tmp.position.set(...view.position);
tmp.lookAt(new THREE.Vector3(...view.target));
return { pos: tmp.position.clone(), quat: tmp.quaternion.clone(), fov: view.fov ?? 55 };
}
private applyPose(p: CamPose): void {
this.camera.position.copy(p.pos);
this.camera.quaternion.copy(p.quat);
if (this.camera.fov !== p.fov) {
this.camera.fov = p.fov;
this.camera.updateProjectionMatrix();
}
}
showScene(scene: Scene, transition: Transition): void {
if (!scene.camera) {
console.error(`Scène "${scene.id}" sans caméra`);
return;
}
const to = this.poseOf(scene.camera);
this.setHovered(null, null);
if (this.controls) this.controls.target.set(...scene.camera.target);
if (this.firstScene || transition === 'none' || this.controls || this.testMode) {
this.applyPose(to);
this.camAnim = null;
} else {
const from: CamPose = { pos: this.camera.position.clone(), quat: this.camera.quaternion.clone(), fov: this.camera.fov };
const dur = transition === 'turn-left' || transition === 'turn-right' ? 0.75 : 0.95;
this.camAnim = { from, to, t: 0, dur };
}
this.refresh(this.firstScene);
this.firstScene = false;
this.dirty = true;
}
protected canInteract(): boolean {
return !this.camAnim;
}
/** Vrai pendant un mouvement de caméra ou d'objet (utile aux tests). */
get busy(): boolean {
return !!this.camAnim || this.tweens.length > 0;
}
// --- État du monde ------------------------------------------------------------------------
protected refreshStage(instant: boolean): void {
this.dirty = true;
const state = this.engine.state;
// Zones 3D actives de la scène courante
this.hotspotByName.clear();
for (const hs of this.engine.activeHotspots(this.engine.currentScene)) {
for (const name of ([] as string[]).concat(hs.object ?? [])) this.hotspotByName.set(name, hs);
}
if (this.hovered && ![...this.hotspotByName.values()].includes(this.hovered)) this.setHovered(null, null);
// Règles d'état (équivalent 3D des calques)
for (const [name, p] of this.props) {
const pos = p.basePos.clone();
const quat = p.baseQuat.clone();
let visible = p.baseVisible;
let emissive: string | null = null;
for (const rule of this.engine.scenario.props ?? []) {
if (rule.object !== name || !checkAll(state, rule.when)) continue;
if (rule.visible !== undefined) visible = rule.visible;
if (rule.offset) pos.add(new THREE.Vector3(...rule.offset));
if (rule.rotation) quat.setFromEuler(new THREE.Euler(...rule.rotation));
if (rule.emissive) emissive = rule.emissive;
if (rule.spin) {
const angle = (state.vars[rule.spin.var] ?? 0) * rule.spin.step;
quat.multiply(new THREE.Quaternion().setFromAxisAngle(new THREE.Vector3(...rule.spin.axis).normalize(), angle));
}
}
p.obj.visible = visible;
for (const m of p.mats) {
if (emissive) {
m.mat.emissive.set(emissive);
m.mat.color.set(emissive);
} else {
m.mat.emissive.copy(m.emissive);
m.mat.color.copy(m.color);
}
m.mat.emissiveIntensity = m.intensity;
}
const moved = !p.obj.position.equals(pos) || p.obj.quaternion.angleTo(quat) > 1e-4;
if (!moved) continue;
this.tweens = this.tweens.filter((t) => t.obj !== p.obj);
if (instant || this.testMode) {
p.obj.position.copy(pos);
p.obj.quaternion.copy(quat);
} else {
// Durée selon l'ampleur : un tiroir glisse lentement, une molette claque vite.
const dur = THREE.MathUtils.clamp(p.obj.position.distanceTo(pos) * 3 + p.obj.quaternion.angleTo(quat) * 0.6, 0.25, 1.2);
this.tweens.push({ obj: p.obj, fromPos: p.obj.position.clone(), toPos: pos, fromQuat: p.obj.quaternion.clone(), toQuat: quat, t: 0, dur });
}
}
}
// --- Souris ---------------------------------------------------------------------------------
private isVisibleDeep(o: THREE.Object3D | null): boolean {
for (let x = o; x; x = x.parent) if (!x.visible) return false;
return true;
}
/** Objet sous le pointeur → zone du scénario (en remontant la hiérarchie). */
private pick(e: MouseEvent): { hs: Hotspot | null; obj: THREE.Object3D | null } {
return this.pickAt(e.clientX, e.clientY);
}
private pickAt(clientX: number, clientY: number): { hs: Hotspot | null; obj: THREE.Object3D | null } {
const r = this.gl.domElement.getBoundingClientRect();
this.pointer.set(((clientX - r.left) / r.width) * 2 - 1, -((clientY - r.top) / r.height) * 2 + 1);
this.raycaster.setFromCamera(this.pointer, this.camera);
const hits = this.raycaster.intersectObject(this.world.root, true);
const hit = hits.find((h) => this.isVisibleDeep(h.object));
if (!hit) {
this.debugHit = '';
return { hs: null, obj: null };
}
const chain: string[] = [];
let found: { hs: Hotspot | null; obj: THREE.Object3D | null } = { hs: null, obj: null };
for (let o: THREE.Object3D | null = hit.object; o && o !== this.world.root; o = o.parent) {
if (o.name) chain.push(o.name);
if (!found.hs && o.name && this.hotspotByName.has(o.name)) found = { hs: this.hotspotByName.get(o.name)!, obj: o };
}
const p = hit.point;
this.debugHit = `objet : ${chain.join(' ‹ ') || '(sans nom)'} · point : [${round(p.x)}, ${round(p.y)}, ${round(p.z)}]`;
return found;
}
private setHovered(hs: Hotspot | null, obj: THREE.Object3D | null): void {
if (obj !== this.hoveredObj) {
this.hoveredObj = obj;
// Contour doré uniquement en mode Facile.
this.outline.selectedObjects = obj && this.engine.state.difficulty === 'easy' ? [obj] : [];
this.dirty = true;
}
if (hs === this.hovered) return;
this.hovered = hs;
this.gl.domElement.style.cursor = hs ? this.cursorFor(hs) : 'default';
if (hs) this.showTooltip(hs);
else this.hideTooltip();
}
private onPointerMove(e: PointerEvent): void {
if (this.puzzleOpen) return;
const { hs, obj } = this.pick(e);
this.setHovered(this.camAnim ? null : hs, this.camAnim ? null : obj);
}
private onClick(e: MouseEvent): void {
if (Math.hypot(e.clientX - this.downAt[0], e.clientY - this.downAt[1]) > 5) return; // glisser (debug)
if (!this.canInteract() || this.puzzleOpen) return;
const { hs } = this.pick(e);
if (hs) this.engine.click(hs);
}
/** Position écran (px) du centre d'un objet nommé : utile aux tests automatisés. */
screenPosOf(name: string): { x: number; y: number } | null {
const obj = this.world.root.getObjectByName(name);
if (!obj) return null;
const center = new THREE.Box3().setFromObject(obj).getCenter(new THREE.Vector3()).project(this.camera);
const r = this.gl.domElement.getBoundingClientRect();
return { x: r.left + ((center.x + 1) / 2) * r.width, y: r.top + ((1 - center.y) / 2) * r.height };
}
/**
* Tests : un point écran où un clic déclenche réellement la zone `hotspotId`
* dans la vue courante (objet visible, non masqué par un autre). null si la
* zone n'est cliquable nulle part : c'est un bug de scène à corriger.
*/
clickablePointFor(hotspotId: string): { x: number; y: number } | null {
const hs = this.engine.activeHotspots(this.engine.currentScene).find((h) => h.id === hotspotId);
if (!hs?.object) return null;
const r = this.gl.domElement.getBoundingClientRect();
for (const name of ([] as string[]).concat(hs.object)) {
const obj = this.world.root.getObjectByName(name);
if (!obj) continue;
const box = new THREE.Box3().setFromObject(obj);
const corners = [0, 1].flatMap((i) => [0, 1].flatMap((j) => [0, 1].map((k) => new THREE.Vector3(i ? box.max.x : box.min.x, j ? box.max.y : box.min.y, k ? box.max.z : box.min.z).project(this.camera))));
const minX = Math.min(...corners.map((c) => c.x));
const maxX = Math.max(...corners.map((c) => c.x));
const minY = Math.min(...corners.map((c) => c.y));
const maxY = Math.max(...corners.map((c) => c.y));
// Centre d'abord, puis une grille de points dans la boîte projetée.
const fractions = [0.5, 0.35, 0.65, 0.2, 0.8, 0.1, 0.9];
for (const fy of fractions)
for (const fx of fractions) {
const nx = minX + (maxX - minX) * fx;
const ny = minY + (maxY - minY) * fy;
if (Math.abs(nx) > 0.98 || Math.abs(ny) > 0.98) continue;
const x = r.left + ((nx + 1) / 2) * r.width;
const y = r.top + ((1 - ny) / 2) * r.height;
// Évite les zones écran (flèches) qui recouvrent la scène
const el = document.elementFromPoint(x, y);
if (el !== this.gl.domElement) continue;
if (this.pickAt(x, y).hs === hs) return { x, y };
}
}
return null;
}
// --- Mode debug : caméra libre + copie du point de vue ----------------------------------------
protected onDebugChanged(): void {
if (this.debug) {
this.camAnim = null;
this.controls = new OrbitControls(this.camera, this.gl.domElement);
this.controls.target.set(...(this.engine.currentScene.camera?.target ?? [0, 1.3, 0]));
this.controls.enableDamping = true;
this.copyHint();
} else {
this.controls?.dispose();
this.controls = null;
const cam = this.engine.currentScene.camera;
if (cam) {
const from: CamPose = { pos: this.camera.position.clone(), quat: this.camera.quaternion.clone(), fov: this.camera.fov };
this.camAnim = { from, to: this.poseOf(cam), t: 0, dur: 0.6 };
}
}
}
private copyHint(): void {
this.showMessage('Debug 3D : glisser = orbiter, molette = zoom, clic droit + glisser = déplacer · C = copier le point de vue · D = quitter', 'info');
}
protected onExtraKey(e: KeyboardEvent): void {
if (this.debug && (e.key === 'c' || e.key === 'C') && this.controls) {
const p = this.camera.position;
const t = this.controls.target;
this.copyToClipboard(`"camera": { "position": [${round(p.x)}, ${round(p.y)}, ${round(p.z)}], "target": [${round(t.x)}, ${round(t.y)}, ${round(t.z)}], "fov": ${round(this.camera.fov)} }`);
}
}
protected debugExtra(): string {
return this.debugHit;
}
// --- Boucle de rendu ------------------------------------------------------------------------
private loop = (): void => {
this.raf = requestAnimationFrame(this.loop);
const dt = Math.min(this.clock.getDelta(), 0.1);
if (this.camAnim) {
const a = this.camAnim;
a.t = Math.min(1, a.t + dt / a.dur);
const k = ease(a.t);
this.camera.position.lerpVectors(a.from.pos, a.to.pos, k);
this.camera.quaternion.slerpQuaternions(a.from.quat, a.to.quat, k);
this.camera.fov = a.from.fov + (a.to.fov - a.from.fov) * k;
this.camera.updateProjectionMatrix();
if (a.t >= 1) this.camAnim = null;
}
for (const tw of this.tweens) {
tw.t = Math.min(1, tw.t + dt / tw.dur);
const k = ease(tw.t);
tw.obj.position.lerpVectors(tw.fromPos, tw.toPos, k);
tw.obj.quaternion.slerpQuaternions(tw.fromQuat, tw.toQuat, k);
}
if (this.tweens.length) {
this.tweens = this.tweens.filter((t) => t.t < 1);
if (!this.tweens.length) this.dirty = true;
}
if (this.camAnim === null && this.wasAnimating) this.dirty = true;
this.wasAnimating = !!this.camAnim;
this.controls?.update();
this.world.update?.(dt);
const animating = !!this.camAnim || this.tweens.length > 0 || !!this.controls || !!this.world.update;
if (!animating && !this.dirty) return;
this.dirty = false;
this.composer.render(dt);
if (!this.loadingEl.classList.contains('done')) {
this.loadingEl.classList.add('done');
window.setTimeout(() => this.loadingEl.remove(), 700);
}
};
}

162
src/engine/types.ts Normal file
View File

@ -0,0 +1,162 @@
/**
* Format de données d'un scénario. Tout le contenu du jeu (scènes, zones
* cliquables, objets, énigmes, indices) est décrit ici, en JSON : c'est ce
* format que le futur éditeur de niveaux produira.
*/
/** Zone écran en pixels dans le repère `resolution` (1280×720) : [x, y, largeur, hauteur]. */
export type Rect = [number, number, number, number];
/**
* Condition sous forme de chaîne, préfixable par « ! » pour la négation :
* - "flag:porte_ouverte" → le drapeau est levé
* - "item:cle" → l'objet est dans l'inventaire
* - "selected:cle" → l'objet est actuellement sélectionné (en main)
* - "solved:panneau" → l'énigme est résolue
* - "var:molette1=4" → variable numérique (opérateurs =, !=, >=, <=, >, <)
* Une liste de conditions est un ET logique.
*/
export type Condition = string;
/** Une action = un objet à clé unique, lisible et facile à écrire à la main. */
export type Action =
| { goto: string }
| { message: string }
| { setFlag: string }
| { clearFlag: string }
| { give: string }
| { remove: string }
| { puzzle: string }
| { sound: SoundName }
| { win: true }
/** Ajoute `value` (1 par défaut) à une variable, modulo `mod` si fourni (molettes). */
| { add: string; value?: number; mod?: number }
| { set: string; value: number }
/** Action conditionnelle. */
| { if: Condition[]; then: Action[]; else?: Action[] };
export type SoundName = 'click' | 'step' | 'success' | 'error' | 'unlock' | 'drawer' | 'pickup' | 'beep' | 'dial' | 'switch' | 'power' | 'reveal';
export type CursorKind = 'look' | 'zoom' | 'take' | 'use' | 'left' | 'right' | 'back';
/** Première interaction dont les conditions sont vraies = celle exécutée. */
export interface Interaction {
when?: Condition[];
do: Action[];
}
export interface Hotspot {
id: string;
/** Zone écran (rare : les bandes de navigation sont générées automatiquement). */
rect?: Rect;
/** Nom(s) d'objet(s) du monde 3D qui déclenchent la zone. */
object?: string | string[];
label?: string;
cursor?: CursorKind;
/** La zone n'existe que si ces conditions sont vraies. */
visibleWhen?: Condition[];
interactions: Interaction[];
}
export type Vec3 = [number, number, number];
/** Point de vue fixe d'une scène. */
export interface CameraView {
position: Vec3;
target: Vec3;
fov?: number;
}
/**
* Règle d'état d'un objet du monde. Les règles dont les conditions sont
* vraies s'appliquent (dans l'ordre) ; les déplacements sont animés.
*/
export interface PropRule {
object: string;
when?: Condition[];
visible?: boolean;
/** Décalage de position (mètres) par rapport à la position initiale. */
offset?: Vec3;
/** Rotation absolue (radians) remplaçant la rotation initiale. */
rotation?: Vec3;
/** Couleur émissive (allume un voyant, une lampe...). */
emissive?: string;
/**
* Rotation pilotée par une variable : angle = valeur × step (radians)
* autour de `axis`, ajoutée à la rotation initiale. Ex. une molette de cadenas.
*/
spin?: { var: string; axis: Vec3; step: number };
}
/** Déclencheur global : s'exécute une seule fois, dès que ses conditions sont vraies. */
export interface Trigger {
id: string;
when: Condition[];
do: Action[];
}
/** Combinaison de deux objets de l'inventaire (sélectionner l'un, cliquer sur l'autre). */
export interface Combination {
items: [string, string];
do: Action[];
}
export type Difficulty = 'easy' | 'hard';
export interface Scene {
id: string;
title?: string;
/** Point de vue de la caméra. */
camera: CameraView;
/** Raccourcis de navigation « à la Myst » : bandes cliquables générées automatiquement. */
left?: string;
right?: string;
back?: string;
hotspots: Hotspot[];
}
export interface Item {
id: string;
name: string;
icon: string;
description?: string;
}
export interface PuzzleDef {
id: string;
/** Type de mini-jeu enregistré dans le registre des puzzles (ex. "colorCode"). */
type: string;
title?: string;
params: Record<string, unknown>;
onSolve: Action[];
}
export interface HintGroup {
when?: Condition[];
hints: string[];
}
export interface Scenario {
id: string;
title: string;
subtitle?: string;
/** 1 (facile) à 5 (expert). */
difficulty: number;
/** Nom du monde 3D à construire (voir src/worlds). */
world: string;
/** États conditionnels des objets du monde. */
props?: PropRule[];
/** Taille de référence de l'écran (ratio d'affichage et repère des rect). */
resolution: [number, number];
startScene: string;
intro?: string;
outro?: string;
items: Item[];
scenes: Scene[];
puzzles: PuzzleDef[];
hints: HintGroup[];
triggers?: Trigger[];
combinations?: Combination[];
/** Valeurs initiales des variables (ex. position de départ des molettes). */
vars?: Record<string, number>;
}

109
src/engine/walkthrough.ts Normal file
View File

@ -0,0 +1,109 @@
import { Engine, type View } from './Engine';
import { checkCondition, newState, type GameState } from './state';
import type { Difficulty, PuzzleDef, Scenario } from './types';
import type { PuzzleContext } from '../puzzles/registry';
/**
* Solution de référence d'un chapitre (walkthrough.json), rejouée par le
* moteur sans aucun rendu : on vérifie en quelques millisecondes que la pièce
* reste terminable après chaque modification du scénario.
*
* Étapes possibles (dans la scène courante, comme le ferait un joueur) :
* { "click": "desk" } clic sur une zone (ou "__left", "__right", "__back")
* { "click": "dial1", "times": 8 } clics répétés
* { "use": "key", "on": "lock" } sélectionner un objet puis cliquer sur une zone
* { "combine": ["uvlamp", "batteries"] } combiner deux objets de l'inventaire
* { "solve": "cipher" } résoudre le mini-jeu ouvert à l'écran
* Chaque étape peut vérifier l'état après coup : "expect": ["item:key", "scene:desk", "won"].
*/
export type WalkStep = ({ click: string; times?: number } | { use: string; on: string } | { combine: [string, string] } | { solve: string }) & {
expect?: string[];
};
export interface Walkthrough {
description?: string;
difficulty?: Difficulty;
steps: WalkStep[];
}
export interface WalkResult {
state: GameState;
log: string[];
/** Première erreur rencontrée (undefined si la solution passe). */
error?: string;
}
class HeadlessView implements View {
messages: string[] = [];
puzzle: { def: PuzzleDef; ctx: PuzzleContext } | null = null;
won = false;
showScene(): void {}
refresh(): void {}
showMessage(text: string): void {
this.messages.push(text);
}
openPuzzle(def: PuzzleDef, ctx: PuzzleContext): void {
this.puzzle = { def, ctx };
}
closePuzzle(): void {
this.puzzle = null;
}
showWin(): void {
this.won = true;
}
}
export function runWalkthrough(scenario: Scenario, wt: Walkthrough): WalkResult {
const state = newState(scenario.id, scenario.startScene, wt.difficulty ?? 'easy');
const engine = new Engine(scenario, state, { instant: true });
const view = new HeadlessView();
engine.attach(view);
const log: string[] = [];
const clickZone = (id: string): string | null => {
const hs = engine.activeHotspots(engine.currentScene).find((h) => h.id === id);
if (!hs) {
const ids = engine
.activeHotspots(engine.currentScene)
.map((h) => h.id)
.join(', ');
return `zone "${id}" absente ou inactive dans la scène "${state.scene}" (zones actives : ${ids})`;
}
const before = view.messages.length;
if (!engine.click(hs)) return `clic sur "${id}" sans effet${view.messages.length > before ? ` : « ${view.messages.at(-1)} »` : ''}`;
return null;
};
for (const [i, step] of wt.steps.entries()) {
const label = `étape ${i + 1} ${JSON.stringify(step)}`;
let err: string | null = null;
if ('click' in step) {
for (let k = 0; k < (step.times ?? 1) && !err; k++) err = clickZone(step.click);
} else if ('use' in step) {
if (!state.inventory.includes(step.use)) err = `l'objet "${step.use}" n'est pas dans l'inventaire (${state.inventory.join(', ') || 'vide'})`;
else {
engine.selectItem(step.use);
err = clickZone(step.on);
}
} else if ('combine' in step) {
const missing = step.combine.filter((it) => !state.inventory.includes(it));
if (missing.length) err = `objets absents de l'inventaire : ${missing.join(', ')}`;
else if (!engine.combine(step.combine[0], step.combine[1])) err = `combinaison ${step.combine.join(' + ')} sans effet`;
} else if ('solve' in step) {
if (view.puzzle?.def.id !== step.solve) err = `le mini-jeu "${step.solve}" n'est pas ouvert (ouvert : ${view.puzzle?.def.id ?? 'aucun'})`;
else view.puzzle.ctx.solve();
}
if (!err)
for (const c of step.expect ?? []) {
const ok = c === 'won' ? state.won : c.startsWith('scene:') ? state.scene === c.slice(6) : checkCondition(state, c);
if (!ok) {
err = `attendu "${c}" non vérifié (scène ${state.scene}, inventaire [${state.inventory.join(', ')}])`;
break;
}
}
if (err) return { state, log, error: `${label} : ${err}` };
log.push(`${label} → scène ${state.scene}${view.messages.length ? ` · « ${view.messages.at(-1)} »` : ''}`);
}
if (!state.won) return { state, log, error: 'la solution se termine sans victoire' };
return { state, log };
}

124
src/main.ts Normal file
View File

@ -0,0 +1,124 @@
import './style.css';
// Chaque module de puzzle s'enregistre dans le registre à l'import.
import './puzzles/colorCode';
import './puzzles/caesar';
import { formatTime, type RendererOptions } from './engine/BaseRenderer';
import { ThreeRenderer } from './engine/three/ThreeRenderer';
import { Engine } from './engine/Engine';
import { listScenarios, type LoadedScenario } from './engine/scenarioLoader';
import { clearSave, loadState, newState } from './engine/state';
import type { Difficulty } from './engine/types';
const app = document.getElementById('app')!;
let renderer: ThreeRenderer | null = null;
let engine: Engine | null = null;
function stars(n: number): string {
return '★'.repeat(n) + '☆'.repeat(Math.max(0, 5 - n));
}
function escapeHtml(s: string): string {
return s.replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c]!);
}
function showMenu(): void {
engine?.stop();
renderer?.destroy();
engine = null;
renderer = null;
const screen = document.createElement('div');
screen.className = 'screen menu';
screen.innerHTML = `
<h1>ESCAPE</h1>
<p class="tagline">Prototype · moteur point &amp; click</p>
<div class="chapters"></div>
<p class="keys">Clic : examiner · flèches : tourner / reculer (ou clic droit, Échap) · objet en main + autre objet : combiner · H : indice · D : mode debug</p>
<p class="keys"><b>Facile</b> : objets surlignés et nommés au survol · <b>Difficile</b> : seul le curseur vous guide</p>`;
const list = screen.querySelector('.chapters')!;
listScenarios().forEach((entry) => {
const { scenario } = entry;
const save = loadState(scenario.id);
const card = document.createElement('div');
card.className = 'chapter';
card.dataset.chapter = entry.folder;
card.innerHTML = `
<div class="chapter-head">
<h2>${escapeHtml(scenario.title)}</h2>
<span class="difficulty" title="Difficulté">${stars(scenario.difficulty)}</span>
</div>
${scenario.subtitle ? `<p>${escapeHtml(scenario.subtitle)}</p>` : ''}
<div class="chapter-actions"></div>`;
const actions = card.querySelector('.chapter-actions')!;
if (save && !save.won) {
const cont = document.createElement('button');
cont.className = 'primary';
cont.textContent = `Continuer (${formatTime(save.elapsedMs)} · ${save.difficulty === 'hard' ? 'difficile' : 'facile'})`;
cont.onclick = () => startGame(entry, false);
actions.appendChild(cont);
}
const label = document.createElement('span');
label.className = 'new-game';
label.textContent = 'Nouvelle partie :';
actions.appendChild(label);
for (const [diff, text] of [
['easy', 'Facile'],
['hard', 'Difficile'],
] as const) {
const play = document.createElement('button');
play.className = !save || save.won ? (diff === 'easy' ? 'primary' : '') : '';
play.dataset.difficulty = diff;
play.textContent = text;
play.onclick = () => startGame(entry, true, diff);
actions.appendChild(play);
}
list.appendChild(card);
});
app.replaceChildren(screen);
}
function startGame(entry: LoadedScenario, fresh: boolean, difficulty: Difficulty = 'easy'): void {
const { scenario } = entry;
if (fresh) clearSave(scenario.id);
const state = (!fresh && loadState(scenario.id)) || newState(scenario.id, scenario.startScene, difficulty);
engine = new Engine(scenario, state);
const opts: RendererOptions = {
resolveImage: entry.resolveImage,
onMenu: showMenu,
onWin: () => window.setTimeout(() => showWin(entry), 1800),
};
renderer = new ThreeRenderer(engine, opts);
engine.attach(renderer);
// Accès console / tests automatisés : window.__escape.engine.state, etc.
(window as unknown as { __escape: unknown }).__escape = { engine, renderer };
app.replaceChildren(renderer.root);
engine.start();
}
function showWin(entry: LoadedScenario): void {
if (!engine) return;
const { state } = engine;
engine.stop();
const screen = document.createElement('div');
screen.className = 'screen win';
screen.innerHTML = `
<h1>Évadé !</h1>
<p class="outro">${escapeHtml(entry.scenario.outro ?? '')}</p>
<div class="stats">
<div><span>${formatTime(state.elapsedMs)}</span>temps</div>
<div><span>${state.hintsUsed}</span>indice${state.hintsUsed > 1 ? 's' : ''}</div>
<div><span>${state.difficulty === 'hard' ? 'Difficile' : 'Facile'}</span>mode</div>
</div>
<button class="primary">Retour au menu</button>`;
screen.querySelector('button')!.onclick = () => {
clearSave(entry.scenario.id);
showMenu();
};
renderer?.root.appendChild(screen);
}
showMenu();

121
src/puzzles/caesar.ts Normal file
View File

@ -0,0 +1,121 @@
import { registerPuzzle, type PuzzleContext } from './registry';
/**
* Mini-jeu « déchiffrement » : un message chiffré par décalage (César) et une
* roue à deux anneaux. Le joueur fait tourner l'anneau intérieur ; la lecture
* du message se met à jour en direct. Résolu quand le bon décalage est trouvé.
* Paramètres JSON :
* { "ciphertext": "SL JVMMYL ...", "shift": 7, "caption": "texte optionnel" }
*/
interface Params {
ciphertext: string;
shift: number;
caption?: string;
}
interface Data {
offset: number;
}
const A = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
const SVGNS = 'http://www.w3.org/2000/svg';
export function caesarDecode(text: string, offset: number): string {
return text.replace(/[A-Z]/g, (c) => A[(A.indexOf(c) - offset + 26 * 10) % 26]);
}
function ring(radius: number, size: number, cls: string): SVGGElement {
const g = document.createElementNS(SVGNS, 'g');
g.setAttribute('class', cls);
for (let i = 0; i < 26; i++) {
const t = document.createElementNS(SVGNS, 'text');
t.textContent = A[i];
t.setAttribute('x', '0');
t.setAttribute('y', String(-radius));
t.setAttribute('font-size', String(size));
t.setAttribute('text-anchor', 'middle');
t.setAttribute('dominant-baseline', 'middle');
t.setAttribute('transform', `rotate(${(i * 360) / 26})`);
g.appendChild(t);
}
return g;
}
function createCaesar(ctx: PuzzleContext<Data>) {
const params = ctx.def.params as unknown as Params;
let offset = ctx.alreadySolved ? params.shift : (ctx.data?.offset ?? 0);
let locked = ctx.alreadySolved;
const root = document.createElement('div');
root.className = 'cz-panel';
root.innerHTML = `
<div class="cz-wheel-wrap">
<svg class="cz-wheel" viewBox="-160 -160 320 320" aria-label="Roue de chiffrement">
<circle r="156" class="cz-outer-disc"/>
<circle r="116" class="cz-inner-disc"/>
<circle r="62" class="cz-hub"/>
<path d="M0 -158 L-7 -146 L7 -146 Z" class="cz-marker"/>
</svg>
<div class="cz-buttons">
<button class="cz-prev" title="Tourner (←)">⟲</button>
<span class="cz-offset"></span>
<button class="cz-next" title="Tourner (→)">⟳</button>
</div>
</div>
<div class="cz-text">
${params.caption ? `<div class="cz-caption">${params.caption}</div>` : ''}
<div class="cz-label">Message chiffré</div>
<div class="cz-cipher"></div>
<div class="cz-label">Lecture avec la roue</div>
<div class="cz-plain"></div>
<div class="cz-help">Anneau extérieur : lettre chiffrée · anneau intérieur : lettre réelle.<br/>Tournez la roue jusqu’à ce que le message ait un sens.</div>
</div>`;
const svg = root.querySelector('svg')!;
const outer = ring(136, 17, 'cz-ring-outer');
const inner = ring(97, 15, 'cz-ring-inner');
svg.insertBefore(outer, svg.querySelector('.cz-hub'));
svg.insertBefore(inner, svg.querySelector('.cz-hub'));
root.querySelector('.cz-cipher')!.textContent = params.ciphertext;
const plainEl = root.querySelector<HTMLElement>('.cz-plain')!;
const offsetEl = root.querySelector<HTMLElement>('.cz-offset')!;
// Rotation cumulée (pas de saut visuel 25 → 0)
let turns = offset;
function paint() {
inner.style.transform = `rotate(${(turns * 360) / 26}deg)`;
offsetEl.textContent = `Décalage ${offset}`;
plainEl.textContent = caesarDecode(params.ciphertext, offset);
root.classList.toggle('solved', locked);
}
function turn(dir: number) {
if (locked) return;
turns += dir;
offset = (((offset + dir) % 26) + 26) % 26;
ctx.sound('dial');
ctx.save({ offset });
paint();
if (offset === params.shift) {
locked = true;
paint();
ctx.solve();
}
}
root.querySelector<HTMLButtonElement>('.cz-prev')!.onclick = () => turn(-1);
root.querySelector<HTMLButtonElement>('.cz-next')!.onclick = () => turn(1);
svg.addEventListener('wheel', (e) => {
e.preventDefault();
turn(e.deltaY > 0 ? 1 : -1);
});
const onKey = (e: KeyboardEvent) => {
if (e.key === 'ArrowLeft') turn(-1);
else if (e.key === 'ArrowRight') turn(1);
};
window.addEventListener('keydown', onKey);
paint();
return { el: root, destroy: () => window.removeEventListener('keydown', onKey) };
}
registerPuzzle('caesar', createCaesar);

115
src/puzzles/colorCode.ts Normal file
View File

@ -0,0 +1,115 @@
import { registerPuzzle, type PuzzleContext } from './registry';
/**
* Mini-jeu « code couleur » : N boutons qui font défiler des couleurs, un
* bouton de validation. Paramètres JSON :
* {
* "colors": [{ "id": "rouge", "label": "Rouge", "hex": "#d64541" }, ...],
* "solution": ["jaune", "rouge", "bleu", "vert"],
* "caption": "texte gravé sur la plaque (optionnel)"
* }
*/
interface ColorDef {
id: string;
label: string;
hex: string;
}
interface Params {
colors: ColorDef[];
solution: string[];
caption?: string;
}
interface Data {
/** Index de couleur par emplacement, -1 = éteint. */
slots: number[];
}
function createColorCode(ctx: PuzzleContext<Data>) {
const params = ctx.def.params as unknown as Params;
const n = params.solution.length;
const slots = ctx.data?.slots?.length === n ? [...ctx.data.slots] : Array<number>(n).fill(-1);
if (ctx.alreadySolved) {
params.solution.forEach((id, i) => (slots[i] = params.colors.findIndex((c) => c.id === id)));
}
let locked = ctx.alreadySolved;
const root = document.createElement('div');
root.className = 'cc-panel';
root.innerHTML = `
<div class="cc-screws"><i></i><i></i><i></i><i></i></div>
<div class="cc-plate">${params.caption ?? ''}</div>
<div class="cc-slots"></div>
<div class="cc-bottom">
<div class="cc-led"></div>
<button class="cc-validate">VALIDER</button>
</div>
<div class="cc-help">Clic : couleur suivante · Clic droit : couleur précédente</div>`;
const slotsEl = root.querySelector<HTMLElement>('.cc-slots')!;
const led = root.querySelector<HTMLElement>('.cc-led')!;
const validate = root.querySelector<HTMLButtonElement>('.cc-validate')!;
const buttons = slots.map((_, i) => {
const wrap = document.createElement('div');
wrap.className = 'cc-slot';
const num = document.createElement('span');
num.className = 'cc-num';
num.textContent = String(i + 1);
const btn = document.createElement('button');
btn.className = 'cc-button';
btn.dataset.slot = String(i);
const cycle = (dir: number) => {
if (locked) return;
const count = params.colors.length;
slots[i] = slots[i] < 0 ? (dir > 0 ? 0 : count - 1) : (slots[i] + dir + count) % count;
ctx.sound('click');
led.className = 'cc-led';
paint();
ctx.save({ slots: [...slots] });
};
btn.onclick = () => cycle(1);
btn.oncontextmenu = (e) => {
e.preventDefault();
e.stopPropagation();
cycle(-1);
};
wrap.append(num, btn);
slotsEl.appendChild(wrap);
return btn;
});
function paint() {
buttons.forEach((btn, i) => {
const c = params.colors[slots[i]];
btn.style.setProperty('--c', c ? c.hex : '#2a2a2a');
btn.classList.toggle('lit', !!c);
btn.title = c ? c.label : 'Éteint';
btn.setAttribute('aria-label', `Emplacement ${i + 1} : ${c ? c.label : 'éteint'}`);
});
if (locked) {
led.className = 'cc-led ok';
validate.disabled = true;
}
}
validate.onclick = () => {
if (locked) return;
const ok = params.solution.every((id, i) => params.colors[slots[i]]?.id === id);
if (ok) {
locked = true;
paint();
root.classList.add('solved');
ctx.solve();
} else {
ctx.sound('error');
led.className = 'cc-led ko';
root.classList.remove('shake');
void root.offsetWidth;
root.classList.add('shake');
}
};
paint();
return { el: root };
}
registerPuzzle('colorCode', createColorCode);

37
src/puzzles/registry.ts Normal file
View File

@ -0,0 +1,37 @@
import type { PuzzleDef, SoundName } from '../engine/types';
/**
* Contrat d'un mini-jeu. Chaque type de puzzle est un module autonome,
* paramétré par le JSON du scénario (PuzzleDef.params) : on écrit un type
* une fois, on le réutilise dans tous les niveaux.
*/
export interface PuzzleContext<TData = unknown> {
def: PuzzleDef;
/** État persistant du mini-jeu (sauvegardé avec la partie). */
data: TData | undefined;
save(data: TData): void;
alreadySolved: boolean;
/** À appeler quand le joueur trouve la solution. */
solve(): void;
close(): void;
sound(name: SoundName): void;
}
export interface PuzzleInstance {
el: HTMLElement;
destroy?(): void;
}
export type PuzzleFactory = (ctx: PuzzleContext<any>) => PuzzleInstance;
const registry = new Map<string, PuzzleFactory>();
export function registerPuzzle(type: string, factory: PuzzleFactory): void {
registry.set(type, factory);
}
export function getPuzzleFactory(type: string): PuzzleFactory {
const f = registry.get(type);
if (!f) throw new Error(`Type de puzzle inconnu : "${type}"`);
return f;
}

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 8.4 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 8.3 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 8.1 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 8.2 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 8.4 KiB

View File

@ -0,0 +1,430 @@
{
"id": "chapitre1",
"title": "Chapitre 1 — Le bureau du professeur",
"subtitle": "Le professeur Lindqvist a disparu en laissant son bureau truffé d’énigmes. Cinq mécanismes vous séparent de la sortie. Durée : 15 à 20 minutes.",
"difficulty": 2,
"world": "bureau",
"resolution": [1280, 720],
"startScene": "north",
"intro": "Vous vous réveillez dans le bureau du professeur Lindqvist. La porte est verrouillée et le plafonnier ne fonctionne plus… Fouillez la pièce : le professeur aimait les secrets.",
"outro": "La clé tourne dans la serrure avec un claquement sec. La porte s’ouvre sur un couloir éclairé… Le professeur Lindqvist cachait bien d’autres secrets. Fin du chapitre 1.",
"vars": { "dial1": 3, "dial2": 7, "dial3": 2, "dial4": 5 },
"items": [
{ "id": "uvlamp", "name": "Lampe UV", "icon": "images/uvlamp.svg", "description": "Une petite lampe à ultraviolets. Elle n’a pas de piles." },
{ "id": "batteries", "name": "Piles", "icon": "images/batteries.svg", "description": "Deux piles, encore chargées." },
{ "id": "uvlampOn", "name": "Lampe UV allumée", "icon": "images/uvlamp_on.svg", "description": "Sa lumière violette révèle les encres invisibles." },
{ "id": "lever", "name": "Manette", "icon": "images/lever.svg", "description": "Une manette à poignée rouge, comme celles des disjoncteurs." },
{ "id": "key", "name": "Clé en laiton", "icon": "images/key.svg", "description": "Une vieille clé, lourde et finement ouvragée." }
],
"combinations": [
{
"items": ["uvlamp", "batteries"],
"do": [
{ "remove": "uvlamp" },
{ "remove": "batteries" },
{ "give": "uvlampOn" },
{ "message": "Vous glissez les piles dans la lampe : une lueur violette s’allume." }
]
}
],
"puzzles": [
{
"id": "cipher",
"type": "caesar",
"title": "Message chiffré",
"params": {
"caption": "Écrit à l’encre invisible sur la toile du tableau.",
"ciphertext": "SL JVMMYL Z'VBCYL H S'OLBYL VB SL ALTWZ Z'LZA HYYLAL",
"shift": 7
},
"onSolve": [{ "message": "« LE COFFRE S’OUVRE À L’HEURE OÙ LE TEMPS S’EST ARRÊTÉ »" }]
},
{
"id": "colorPanel",
"type": "colorCode",
"title": "Boîtier de commande",
"params": {
"caption": "Commande",
"colors": [
{ "id": "red", "label": "Rouge", "hex": "#d64541" },
{ "id": "blue", "label": "Bleu", "hex": "#3a7bd5" },
{ "id": "green", "label": "Vert", "hex": "#3fae5a" },
{ "id": "yellow", "label": "Jaune", "hex": "#f2c230" },
{ "id": "purple", "label": "Violet", "hex": "#8e5bd0" },
{ "id": "white", "label": "Blanc", "hex": "#e8e8e8" }
],
"solution": ["yellow", "red", "blue", "green"]
},
"onSolve": [
{ "setFlag": "drawer_open" },
{ "sound": "drawer" },
{ "message": "Un déclic sourd résonne dans la pièce… quelque chose s’est ouvert du côté du bureau." }
]
}
],
"triggers": [
{
"id": "safeCode",
"when": ["var:dial1=1", "var:dial2=0", "var:dial3=4", "var:dial4=0"],
"do": [
{ "setFlag": "safe_open" },
{ "sound": "unlock" },
{ "message": "1-0-4-0 : clic ! La porte du coffret s’entrouvre." }
]
}
],
"props": [
{ "object": "uvMessage", "when": ["!flag:uv_painting"], "visible": false },
{ "object": "dial1", "spin": { "var": "dial1", "axis": [1, 0, 0], "step": 0.6283 } },
{ "object": "dial2", "spin": { "var": "dial2", "axis": [1, 0, 0], "step": 0.6283 } },
{ "object": "dial3", "spin": { "var": "dial3", "axis": [1, 0, 0], "step": 0.6283 } },
{ "object": "dial4", "spin": { "var": "dial4", "axis": [1, 0, 0], "step": 0.6283 } },
{ "object": "safeDoor", "when": ["flag:safe_open"], "rotation": [0, -1.75, 0] },
{ "object": "leverItem", "when": ["flag:lever_taken"], "visible": false },
{ "object": "breakerLever", "when": ["!flag:lever_installed"], "visible": false },
{ "object": "breakerLever", "when": ["flag:power_on"], "rotation": [2.79, 0, 0] },
{ "object": "breakerLed", "when": ["!flag:power_on"], "emissive": "#ff3b30" },
{ "object": "breakerLed", "when": ["flag:power_on"], "emissive": "#3fe06a" },
{ "object": "ceilingLight", "when": ["!flag:power_on"], "visible": false },
{ "object": "ceilingBulb", "when": ["flag:power_on"], "emissive": "#ffe6b0" },
{ "object": "paintingSpot", "when": ["!flag:power_on"], "visible": false },
{ "object": "panelLed", "when": ["flag:power_on"], "emissive": "#ff3b30" },
{ "object": "panelLamp1", "when": ["solved:colorPanel"], "emissive": "#f2c230" },
{ "object": "panelLamp2", "when": ["solved:colorPanel"], "emissive": "#d64541" },
{ "object": "panelLamp3", "when": ["solved:colorPanel"], "emissive": "#3a7bd5" },
{ "object": "panelLamp4", "when": ["solved:colorPanel"], "emissive": "#3fae5a" },
{ "object": "panelLed", "when": ["solved:colorPanel"], "emissive": "#3fe06a" },
{ "object": "secretDrawer", "when": ["flag:drawer_open"], "offset": [0, 0, 0.3] },
{ "object": "key", "when": ["flag:key_taken"], "visible": false },
{ "object": "door", "when": ["flag:door_open"], "rotation": [0, 1.35, 0] }
],
"scenes": [
{
"id": "north",
"title": "Mur nord — le bureau",
"camera": { "position": [0, 1.6, 0], "target": [0, 1.3, -3], "fov": 55 },
"left": "west",
"right": "east",
"hotspots": [
{ "id": "desk", "label": "Bureau", "object": "desk", "interactions": [{ "do": [{ "goto": "desk" }] }] },
{ "id": "note", "label": "Mot épinglé", "object": "note", "interactions": [{ "do": [{ "goto": "note" }] }] },
{ "id": "digit3", "label": "Inscription", "cursor": "look", "object": "digit3", "interactions": [{ "do": [{ "message": "Un grand « 3 » peint en bleu, à même le papier peint. La peinture a coulé." }] }] },
{ "id": "clock", "label": "Horloge", "object": "clock", "interactions": [{ "do": [{ "goto": "clock" }] }] },
{ "id": "map", "label": "Carte", "object": "map", "interactions": [{ "do": [{ "message": "Une vieille carte de la Baltique, annotée à la main." }] }] }
]
},
{
"id": "east",
"title": "Mur est — la fenêtre",
"camera": { "position": [0, 1.6, 0], "target": [3, 1.3, 0], "fov": 55 },
"left": "north",
"right": "south",
"hotspots": [
{ "id": "window", "label": "Fenêtre", "object": ["window", "curtains"], "interactions": [{ "do": [{ "message": "Des planches sont clouées de l’autre côté de la vitre. Aucune issue par ici." }] }] },
{ "id": "painting", "label": "Tableau", "object": "painting", "interactions": [{ "do": [{ "goto": "painting" }] }] },
{
"id": "vase",
"label": "Vase",
"object": "vase",
"interactions": [
{ "when": ["!flag:batteries_found"], "do": [{ "give": "batteries" }, { "setFlag": "batteries_found" }, { "message": "Quelque chose cliquette au fond du vase… deux piles !" }] },
{ "do": [{ "message": "Des fleurs fanées. Le vase est vide, maintenant." }] }
]
}
]
},
{
"id": "south",
"title": "Mur sud — la porte",
"camera": { "position": [0, 1.6, 0], "target": [0, 1.3, 3], "fov": 55 },
"left": "east",
"right": "west",
"hotspots": [
{ "id": "door", "label": "Porte", "object": "door", "interactions": [{ "do": [{ "goto": "door" }] }] },
{
"id": "panel",
"label": "Boîtier de commande",
"cursor": "zoom",
"object": "panel",
"interactions": [
{ "when": ["solved:colorPanel"], "do": [{ "message": "Les quatre voyants sont allumés. Le boîtier ne répond plus." }] },
{ "when": ["!flag:power_on"], "do": [{ "message": "Le boîtier est éteint : son circuit est coupé. Il doit y avoir un disjoncteur quelque part." }] },
{ "do": [{ "puzzle": "colorPanel" }] }
]
},
{ "id": "digit4", "label": "Inscription", "cursor": "look", "object": "digit4", "interactions": [{ "do": [{ "message": "Un « 4 » vert, peint maladroitement sur les boiseries." }] }] },
{ "id": "mirror", "label": "Miroir", "object": "mirror", "interactions": [{ "do": [{ "message": "Votre reflet a l’air fatigué." }] }] }
]
},
{
"id": "west",
"title": "Mur ouest — la bibliothèque",
"camera": { "position": [0, 1.6, 0], "target": [-3, 1.3, 0], "fov": 55 },
"left": "south",
"right": "north",
"hotspots": [
{ "id": "shelf", "label": "Bibliothèque", "object": "bookshelf", "interactions": [{ "do": [{ "goto": "shelf" }] }] },
{ "id": "safe", "label": "Coffret", "object": "safe", "interactions": [{ "do": [{ "goto": "safe" }] }] },
{ "id": "breaker", "label": "Disjoncteur", "object": "breaker", "interactions": [{ "do": [{ "goto": "breaker" }] }] },
{ "id": "armchair", "label": "Fauteuil", "object": "armchair", "interactions": [{ "do": [{ "message": "Un fauteuil en cuir usé. Rien sous les coussins." }] }] }
]
},
{
"id": "desk",
"title": "Le bureau",
"camera": { "position": [0, 1.45, -1.05], "target": [0, 0.85, -2.7], "fov": 50 },
"back": "north",
"hotspots": [
{ "id": "note", "label": "Mot épinglé", "object": "note", "interactions": [{ "do": [{ "goto": "note" }] }] },
{ "id": "lamp", "label": "Lampe", "object": "lamp", "interactions": [{ "do": [{ "message": "Une lampe de banquier, sur batterie de secours. Sa lumière est chaude et rassurante." }] }] },
{ "id": "inkwell", "label": "Encrier", "object": "inkwell", "interactions": [{ "do": [{ "message": "L’encre a séché depuis longtemps." }] }] },
{ "id": "books", "label": "Livres", "object": "deskBooks", "interactions": [{ "do": [{ "message": "« Chromatisme et mémoire », « Traité des serrures », « Le chiffre de César ». Lectures étranges." }] }] },
{
"id": "drawersLeft",
"label": "Tiroirs",
"object": "drawersLeft",
"interactions": [
{ "when": ["!flag:uvlamp_found"], "do": [{ "give": "uvlamp" }, { "setFlag": "uvlamp_found" }, { "message": "Sous une pile de factures : une petite lampe à ultraviolets. Elle ne s’allume pas, il manque les piles." }] },
{ "do": [{ "message": "Des factures, des crayons, des trombones. Rien d’autre." }] }
]
},
{ "id": "drawersRight", "label": "Tiroirs", "object": "drawersRight", "interactions": [{ "do": [{ "message": "Vides. Quelqu’un a fait le ménage." }] }] },
{
"id": "secretPanel",
"label": "Panneau central",
"visibleWhen": ["!flag:drawer_open"],
"object": "secretDrawer",
"interactions": [{ "do": [{ "sound": "step" }, { "message": "Le panneau sonne creux… mais il n’a ni poignée ni serrure." }] }]
},
{
"id": "secretDrawer",
"label": "Tiroir secret",
"visibleWhen": ["flag:drawer_open", "flag:key_taken"],
"object": "secretDrawer",
"interactions": [{ "do": [{ "message": "Le tiroir secret est vide, maintenant." }] }]
},
{
"id": "key",
"label": "Clé",
"visibleWhen": ["flag:drawer_open", "!flag:key_taken"],
"object": "key",
"interactions": [{ "do": [{ "give": "key" }, { "setFlag": "key_taken" }, { "message": "Vous prenez une clé en laiton. Elle est lourde et froide." }] }]
}
]
},
{
"id": "note",
"title": "Le mot",
"camera": { "position": [0.35, 1.18, -2.62], "target": [0.35, 1.18, -3], "fov": 30 },
"back": "desk",
"hotspots": []
},
{
"id": "clock",
"title": "L’horloge",
"camera": { "position": [-1.9, 1.88, -2.2], "target": [-1.9, 1.94, -3], "fov": 34 },
"back": "north",
"hotspots": [
{ "id": "clockFace", "label": "Horloge", "cursor": "look", "object": "clock", "interactions": [{ "do": [{ "message": "Les aiguilles sont figées. Le temps s’est arrêté, ici." }] }] }
]
},
{
"id": "painting",
"title": "Le tableau",
"camera": { "position": [1.55, 1.72, 1.0], "target": [3, 1.72, 1.0], "fov": 40 },
"back": "east",
"hotspots": [
{
"id": "canvas",
"label": "Paysage",
"cursor": "look",
"object": "paintingCanvas",
"interactions": [
{ "when": ["selected:uvlampOn", "!flag:uv_painting"], "do": [{ "setFlag": "uv_painting" }, { "sound": "reveal" }, { "message": "Sous la lumière violette, des lettres luminescentes apparaissent sur la toile !" }] },
{ "when": ["selected:uvlampOn"], "do": [{ "message": "Le message brille toujours sous la lampe." }] },
{ "do": [{ "message": "Un paysage au crépuscule, signé « A. L. »." }] }
]
},
{ "id": "digit1", "label": "Détail", "cursor": "look", "object": "digit1", "interactions": [{ "do": [{ "message": "Un « 1 » jaune a été ajouté dans le ciel, d’un coup de pinceau rapide." }] }] },
{
"id": "uvText",
"label": "Message luminescent",
"cursor": "zoom",
"visibleWhen": ["flag:uv_painting"],
"object": "uvMessage",
"interactions": [
{ "when": ["solved:cipher"], "do": [{ "message": "« LE COFFRE S’OUVRE À L’HEURE OÙ LE TEMPS S’EST ARRÊTÉ »" }] },
{ "when": ["selected:uvlampOn"], "do": [{ "puzzle": "cipher" }] },
{ "do": [{ "puzzle": "cipher" }] }
]
}
]
},
{
"id": "shelf",
"title": "La bibliothèque",
"camera": { "position": [-1.7, 1.3, -0.08], "target": [-3, 1.25, -0.08], "fov": 40 },
"back": "west",
"hotspots": [
{ "id": "books", "label": "Livres", "cursor": "look", "object": "bookshelf", "interactions": [{ "do": [{ "message": "Cryptographie, chimie, horlogerie… Rien qui ne serve maintenant." }] }] },
{ "id": "book2", "label": "Livre blanc", "cursor": "look", "object": "book2", "interactions": [{ "do": [{ "message": "Un livre sans titre. Un « 2 » rouge est peint à la main sur la tranche." }] }] }
]
},
{
"id": "safe",
"title": "Le coffret",
"camera": { "position": [-1.95, 0.62, -0.36], "target": [-2.7, 0.22, -0.36], "fov": 40 },
"back": "west",
"hotspots": [
{ "id": "dial1", "label": "Molette 1", "cursor": "use", "visibleWhen": ["!flag:safe_open"], "object": "dial1", "interactions": [{ "do": [{ "add": "dial1", "mod": 10 }, { "sound": "dial" }] }] },
{ "id": "dial2", "label": "Molette 2", "cursor": "use", "visibleWhen": ["!flag:safe_open"], "object": "dial2", "interactions": [{ "do": [{ "add": "dial2", "mod": 10 }, { "sound": "dial" }] }] },
{ "id": "dial3", "label": "Molette 3", "cursor": "use", "visibleWhen": ["!flag:safe_open"], "object": "dial3", "interactions": [{ "do": [{ "add": "dial3", "mod": 10 }, { "sound": "dial" }] }] },
{ "id": "dial4", "label": "Molette 4", "cursor": "use", "visibleWhen": ["!flag:safe_open"], "object": "dial4", "interactions": [{ "do": [{ "add": "dial4", "mod": 10 }, { "sound": "dial" }] }] },
{
"id": "safeBody",
"label": "Coffret",
"cursor": "look",
"object": "safe",
"interactions": [
{ "when": ["flag:safe_open"], "do": [{ "message": "Le coffret est ouvert." }] },
{ "do": [{ "message": "Un coffret en acier « Lindqvist & Fils ». Quatre molettes chiffrées le verrouillent." }] }
]
},
{
"id": "lever",
"label": "Manette",
"visibleWhen": ["flag:safe_open", "!flag:lever_taken"],
"object": "leverItem",
"interactions": [{ "do": [{ "give": "lever" }, { "setFlag": "lever_taken" }, { "message": "Une manette à poignée rouge… comme celles des disjoncteurs." }] }]
}
]
},
{
"id": "breaker",
"title": "Le disjoncteur",
"camera": { "position": [-2.05, 1.5, 1.6], "target": [-2.9, 1.42, 1.6], "fov": 40 },
"back": "west",
"hotspots": [
{
"id": "breakerBox",
"label": "Disjoncteur",
"object": "breaker",
"interactions": [
{ "when": ["selected:lever"], "do": [{ "remove": "lever" }, { "setFlag": "lever_installed" }, { "sound": "switch" }, { "message": "La manette s’emboîte parfaitement. Elle est en position haute." }] },
{ "when": ["flag:power_on"], "do": [{ "message": "Le voyant est vert : le courant est rétabli." }] },
{ "when": ["flag:lever_installed"], "do": [{ "message": "La manette est en position haute. Il suffit de l’abaisser." }] },
{ "when": ["item:lever"], "do": [{ "message": "La manette du coffret devrait s’emboîter ici. Sélectionnez-la dans l’inventaire, puis cliquez sur le disjoncteur." }] },
{ "do": [{ "message": "Un disjoncteur dont on a retiré la manette. Impossible de rétablir le courant ainsi." }] }
]
},
{
"id": "breakerLever",
"label": "Abaisser la manette",
"cursor": "use",
"visibleWhen": ["flag:lever_installed", "!flag:power_on"],
"object": "breakerLever",
"interactions": [{ "do": [{ "setFlag": "power_on" }, { "sound": "switch" }, { "sound": "power" }, { "message": "Clac ! Le plafonnier grésille puis s’allume. Le courant est revenu dans la pièce." }] }]
}
]
},
{
"id": "door",
"title": "La porte",
"camera": { "position": [0, 1.35, 1.55], "target": [-0.1, 1.15, 3], "fov": 50 },
"back": "south",
"hotspots": [
{ "id": "doorBody", "label": "Porte", "cursor": "look", "object": "door", "interactions": [{ "do": [{ "message": "Une lourde porte en chêne. Impossible de la forcer." }] }] },
{
"id": "panelSide",
"label": "Boîtier de commande",
"cursor": "zoom",
"object": "panel",
"interactions": [
{ "when": ["solved:colorPanel"], "do": [{ "message": "Les quatre voyants sont allumés. Le boîtier ne répond plus." }] },
{ "when": ["!flag:power_on"], "do": [{ "message": "Le boîtier est éteint : son circuit est coupé. Il doit y avoir un disjoncteur quelque part." }] },
{ "do": [{ "puzzle": "colorPanel" }] }
]
},
{
"id": "lock",
"label": "Serrure",
"cursor": "look",
"object": "lock",
"interactions": [
{ "when": ["selected:key"], "do": [{ "sound": "unlock" }, { "remove": "key" }, { "setFlag": "door_open" }, { "win": true }] },
{ "when": ["item:key"], "do": [{ "message": "Cette clé en laiton devrait aller dans la serrure. Sélectionnez-la dans l’inventaire, puis cliquez ici." }] },
{ "do": [{ "message": "Verrouillée. Le trou de serrure est assez large pour une vieille clé." }] }
]
}
]
}
],
"hints": [
{
"when": ["!item:uvlampOn", "!flag:uv_painting"],
"hints": [
"Fouillez les meubles : les tiroirs du bureau, ce qui traîne sur les murs et les tables…",
"La lampe UV trouvée dans le bureau n’a pas de piles. Le vase posé sur la console, près du tableau, en cache peut-être.",
"Sélectionnez la lampe UV dans l’inventaire, puis cliquez sur les piles pour les combiner."
]
},
{
"when": ["item:uvlampOn", "!flag:uv_painting"],
"hints": [
"Une lampe UV révèle les encres invisibles. Où un artiste laisserait-il un message ?",
"Approchez-vous du tableau, sélectionnez la lampe UV allumée, puis cliquez sur la toile."
]
},
{
"when": ["flag:uv_painting", "!solved:cipher"],
"hints": [
"Chaque lettre a été remplacée par une autre, plus loin dans l’alphabet.",
"Cliquez sur le message lumineux et tournez la roue jusqu’à ce que le texte devienne lisible (décalage 7)."
]
},
{
"when": ["solved:cipher", "!flag:safe_open"],
"hints": [
"À quelle heure le temps s’est-il arrêté dans cette pièce ? Regardez l’horloge de près.",
"Un coffret à molettes est rangé en bas de la bibliothèque.",
"L’horloge indique 10 h 40 : le code du coffret est 1-0-4-0."
]
},
{
"when": ["flag:safe_open", "!flag:power_on"],
"hints": [
"La manette du coffret doit servir à rétablir le courant. Le boîtier près de la porte est éteint…",
"Le disjoncteur est sur le mur ouest, à gauche de la bibliothèque : installez la manette, puis abaissez-la."
]
},
{
"when": ["flag:power_on", "!solved:colorPanel"],
"hints": [
"Le boîtier près de la porte est maintenant sous tension. Relisez le mot épinglé au-dessus du bureau.",
"Quatre chiffres de couleur sont cachés dans la pièce : deux sont peints sur les murs, les deux autres se trouvent sur le tableau et dans la bibliothèque.",
"Sur le boîtier, chaque chiffre indique un emplacement, et sa couleur la couleur à y mettre : 1 jaune, 2 rouge, 3 bleu, 4 vert."
]
},
{
"when": ["flag:drawer_open", "!flag:key_taken"],
"hints": ["Le déclic venait du bureau.", "Le panneau central du bureau s’est ouvert : approchez-vous du bureau pour voir ce qu’il contient."]
},
{
"when": ["flag:key_taken"],
"hints": ["Cette clé doit bien ouvrir quelque chose…", "Sélectionnez la clé dans l’inventaire, puis cliquez sur la serrure de la porte."]
}
]
}

View File

@ -0,0 +1,43 @@
{
"description": "Solution de référence du chapitre 1. Rejouée automatiquement par `npm test` (moteur seul) et `npm run smoke` (vrais clics dans le navigateur).",
"steps": [
{ "click": "desk", "expect": ["scene:desk"] },
{ "click": "drawersLeft", "expect": ["item:uvlamp"] },
{ "click": "__back" },
{ "click": "__right", "expect": ["scene:east"] },
{ "click": "vase", "expect": ["item:batteries"] },
{ "combine": ["uvlamp", "batteries"], "expect": ["item:uvlampOn", "!item:uvlamp"] },
{ "click": "painting", "expect": ["scene:painting"] },
{ "use": "uvlampOn", "on": "canvas", "expect": ["flag:uv_painting"] },
{ "click": "uvText" },
{ "solve": "cipher", "expect": ["solved:cipher"] },
{ "click": "__back" },
{ "click": "__left", "expect": ["scene:north"] },
{ "click": "clock", "expect": ["scene:clock"] },
{ "click": "__back" },
{ "click": "__left", "expect": ["scene:west"] },
{ "click": "safe", "expect": ["scene:safe"] },
{ "click": "dial1", "times": 8 },
{ "click": "dial2", "times": 3 },
{ "click": "dial3", "times": 2 },
{ "click": "dial4", "times": 5, "expect": ["flag:safe_open"] },
{ "click": "lever", "expect": ["item:lever"] },
{ "click": "__back" },
{ "click": "breaker", "expect": ["scene:breaker"] },
{ "use": "lever", "on": "breakerBox", "expect": ["flag:lever_installed", "!item:lever"] },
{ "click": "breakerLever", "expect": ["flag:power_on"] },
{ "click": "__back" },
{ "click": "__left", "expect": ["scene:south"] },
{ "click": "panel" },
{ "solve": "colorPanel", "expect": ["flag:drawer_open"] },
{ "click": "__right" },
{ "click": "__right", "expect": ["scene:north"] },
{ "click": "desk" },
{ "click": "key", "expect": ["item:key"] },
{ "click": "__back" },
{ "click": "__left" },
{ "click": "__left", "expect": ["scene:south"] },
{ "click": "door" },
{ "use": "key", "on": "lock", "expect": ["won"] }
]
}

430
src/style.css Normal file
View File

@ -0,0 +1,430 @@
:root {
--bg: #0b0d0f;
--panel: #15181c;
--line: #2a2f36;
--text: #e9e2d0;
--muted: #9a927f;
--brass: #c9a24a;
--brass-dark: #8a6a25;
--hud-h: 76px;
--serif: Georgia, 'Times New Roman', serif;
}
* { box-sizing: border-box; }
html, body {
margin: 0;
height: 100%;
background: var(--bg);
color: var(--text);
font-family: system-ui, -apple-system, 'Segoe UI', sans-serif;
overflow: hidden;
user-select: none;
}
#app { height: 100%; }
button {
font: inherit;
color: var(--text);
background: #1e2328;
border: 1px solid var(--line);
border-radius: 6px;
padding: 8px 14px;
cursor: pointer;
transition: background .15s, border-color .15s;
}
button:hover:not(:disabled) { background: #272d34; border-color: var(--brass-dark); }
button.primary { background: var(--brass); color: #1a1408; border-color: var(--brass); font-weight: 600; }
button.primary:hover { background: #dbb55c; }
/* ---------- Écrans (menu, victoire) ---------- */
.screen {
position: absolute;
inset: 0;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 18px;
padding: 24px;
background: radial-gradient(ellipse at 50% 35%, #1d2526 0%, #0b0d0f 70%);
text-align: center;
z-index: 50;
}
.screen h1 {
font-family: var(--serif);
font-size: clamp(48px, 9vw, 96px);
letter-spacing: .25em;
margin: 0;
color: var(--brass);
text-shadow: 0 0 40px rgba(201, 162, 74, .3);
}
.tagline { color: var(--muted); margin: -8px 0 18px; letter-spacing: .1em; text-transform: uppercase; font-size: 13px; }
.chapters { display: flex; flex-direction: column; gap: 14px; width: min(520px, 100%); }
.chapter {
text-align: left;
background: rgba(21, 24, 28, .85);
border: 1px solid var(--line);
border-radius: 10px;
padding: 18px 20px;
}
.chapter-head { display: flex; justify-content: space-between; align-items: baseline; gap: 12px; }
.chapter h2 { font-family: var(--serif); font-weight: normal; margin: 0; font-size: 22px; }
.chapter p { color: var(--muted); margin: 8px 0 14px; line-height: 1.5; }
.difficulty { color: var(--brass); letter-spacing: 2px; white-space: nowrap; }
.chapter-actions { display: flex; gap: 10px; flex-wrap: wrap; align-items: center; }
.new-game { color: var(--muted); font-size: 14px; margin-left: 4px; }
.keys { color: var(--muted); font-size: 12px; max-width: 560px; line-height: 1.6; margin-top: 18px; }
.win { background: rgba(5, 6, 7, .88); animation: fadeIn 1.2s ease both; }
.win h1 { letter-spacing: .06em; }
.outro { max-width: 560px; line-height: 1.7; color: var(--text); font-family: var(--serif); font-size: 18px; }
.stats { display: flex; gap: 40px; color: var(--muted); text-transform: uppercase; font-size: 12px; letter-spacing: .1em; }
.stats span { display: block; font-family: var(--serif); font-size: 36px; color: var(--brass); letter-spacing: 0; text-transform: none; }
/* ---------- Jeu ---------- */
.game {
position: relative;
height: 100%;
display: flex;
flex-direction: column;
align-items: center;
}
.stage-wrap {
flex: 1;
width: 100%;
display: flex;
align-items: center;
justify-content: center;
min-height: 0;
}
.stage {
position: relative;
width: min(100vw, calc((100vh - var(--hud-h)) * var(--ratio)));
aspect-ratio: var(--ratio);
overflow: hidden;
background: #000;
}
.scenes, .hotspots { position: absolute; inset: 0; }
@keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } }
.hotspots { pointer-events: none; }
.hotspot { position: absolute; pointer-events: auto; }
.scenes canvas { position: absolute; inset: 0; width: 100% !important; height: 100% !important; display: block; }
.loading {
position: absolute;
inset: 0;
display: grid;
place-items: center;
color: var(--muted);
font-family: var(--serif);
letter-spacing: .1em;
background: #000;
transition: opacity .6s;
pointer-events: none;
z-index: 5;
}
.loading.done { opacity: 0; }
.hotspot.nav[data-id="__left"]:hover { background: linear-gradient(to right, rgba(255, 255, 255, .07), transparent); }
.hotspot.nav[data-id="__right"]:hover { background: linear-gradient(to left, rgba(255, 255, 255, .07), transparent); }
.hotspot.nav[data-id="__back"]:hover { background: linear-gradient(to top, rgba(255, 255, 255, .06), transparent); }
/* Flèches de navigation toujours visibles, mises en avant au survol */
.nav-arrow {
--t: translateY(-50%);
position: absolute;
width: clamp(40px, 4.4vw, 58px);
aspect-ratio: 1;
border-radius: 50%;
display: grid;
place-items: center;
color: #f4e6c8;
background: rgba(8, 9, 10, .5);
border: 1px solid rgba(244, 230, 200, .3);
box-shadow: 0 4px 14px rgba(0, 0, 0, .5);
opacity: .6;
transform: var(--t);
transition: opacity .2s, transform .2s, background .2s, color .2s;
pointer-events: none;
}
.nav-arrow svg { width: 56%; height: 56%; }
.hotspot.nav[data-id="__left"] .nav-arrow { left: 14px; top: 50%; }
.hotspot.nav[data-id="__right"] .nav-arrow { right: 14px; top: 50%; }
.hotspot.nav[data-id="__back"] .nav-arrow { --t: translateX(-50%); bottom: 12px; left: 50%; }
.hotspot.nav:hover .nav-arrow {
opacity: 1;
color: #1a1408;
background: rgba(201, 162, 74, .92);
border-color: #f0d590;
transform: var(--t) scale(1.12);
}
/* Mode debug (touche D) */
.debug .hotspot { outline: 2px dashed rgba(255, 80, 200, .9); background: rgba(255, 80, 200, .12); }
.debug .hotspot.nav { outline-color: rgba(80, 200, 255, .7); background: rgba(80, 200, 255, .06); }
.debug .hotspot::after {
content: attr(data-debug);
position: absolute;
left: 2px;
top: 2px;
font: 11px/1.2 monospace;
background: rgba(0, 0, 0, .7);
color: #fff;
padding: 1px 4px;
}
.debug-info {
display: none;
position: absolute;
top: 0;
left: 0;
right: 0;
font: 12px monospace;
background: rgba(0, 0, 0, .7);
color: #ff8de0;
padding: 4px 8px;
pointer-events: none;
z-index: 30;
}
.debug .debug-info { display: block; }
.drag-box { position: absolute; border: 2px solid #ffe14d; background: rgba(255, 225, 77, .15); pointer-events: none; z-index: 25; }
/* Messages et infobulle */
.message {
position: absolute;
left: 50%;
bottom: 14%;
transform: translate(-50%, 12px);
max-width: min(760px, 86%);
padding: 14px 22px;
background: rgba(8, 9, 10, .86);
border: 1px solid rgba(201, 162, 74, .35);
border-radius: 8px;
font-family: var(--serif);
font-size: clamp(14px, 1.6vw, 18px);
line-height: 1.55;
text-align: center;
opacity: 0;
pointer-events: none;
transition: opacity .3s, transform .3s;
z-index: 20;
box-shadow: 0 10px 40px rgba(0, 0, 0, .6);
}
/* Le message ne bloque jamais les clics sur la scène. */
.message.visible { opacity: 1; transform: translate(-50%, 0); }
.message.hint { border-color: #5aa0d8; }
.message.hint::before { content: 'Indice — '; color: #7fbaea; font-style: italic; }
.tooltip {
position: absolute;
left: 0;
top: 0;
padding: 4px 10px;
background: rgba(0, 0, 0, .75);
border-radius: 4px;
font-size: 13px;
white-space: nowrap;
pointer-events: none;
opacity: 0;
transition: opacity .15s;
z-index: 15;
}
.tooltip.visible { opacity: 1; }
/* HUD */
.hud {
height: var(--hud-h);
width: 100%;
display: flex;
align-items: center;
justify-content: space-between;
gap: 16px;
padding: 0 16px;
background: linear-gradient(#111417, #0b0d0f);
border-top: 1px solid var(--line);
}
.inventory { display: flex; gap: 8px; }
.slot {
width: 56px;
height: 56px;
padding: 4px;
border-radius: 8px;
background: #15191d;
border: 1px solid var(--line);
display: grid;
place-items: center;
}
.slot:disabled { opacity: .45; cursor: default; }
.slot img { width: 100%; height: 100%; object-fit: contain; pointer-events: none; }
.slot.selected { border-color: var(--brass); box-shadow: 0 0 0 2px rgba(201, 162, 74, .35), 0 0 18px rgba(201, 162, 74, .35); background: #242014; }
.hud-right { display: flex; align-items: center; gap: 8px; }
.hud-btn span { display: inline-grid; place-items: center; width: 18px; height: 18px; border-radius: 50%; background: #5aa0d8; color: #08121b; font-weight: 700; font-size: 12px; margin-right: 4px; }
.timer { font-family: var(--serif); color: var(--muted); font-size: 18px; min-width: 64px; text-align: right; margin-right: 6px; font-variant-numeric: tabular-nums; }
.held-item {
position: fixed;
left: 0;
top: 0;
width: 44px;
height: 44px;
background: center / contain no-repeat;
pointer-events: none;
opacity: 0;
z-index: 40;
filter: drop-shadow(0 4px 6px rgba(0, 0, 0, .6));
}
.held-item.visible { opacity: .95; }
/* Puzzles */
.puzzle-layer { position: absolute; inset: 0; pointer-events: none; z-index: 22; }
.puzzle-overlay {
position: absolute;
inset: 0;
display: grid;
place-items: center;
background: rgba(0, 0, 0, .72);
pointer-events: auto;
opacity: 0;
transition: opacity .25s;
}
.puzzle-overlay.visible { opacity: 1; }
.puzzle-box { position: relative; display: flex; flex-direction: column; align-items: center; gap: 10px; }
.puzzle-title { font-family: var(--serif); color: var(--muted); letter-spacing: .15em; text-transform: uppercase; font-size: 13px; }
.puzzle-close { position: absolute; top: -6px; right: -54px; width: 38px; height: 38px; border-radius: 50%; padding: 0; font-size: 22px; line-height: 1; }
/* ---------- Puzzle colorCode ---------- */
.cc-panel {
position: relative;
padding: 34px 40px 22px;
border-radius: 14px;
background:
repeating-linear-gradient(90deg, rgba(255, 255, 255, .025) 0 2px, transparent 2px 5px),
linear-gradient(160deg, #5d6268, #3a3e43 55%, #2c2f33);
border: 2px solid #1c1e21;
box-shadow: inset 0 2px 0 rgba(255, 255, 255, .18), inset 0 -3px 0 rgba(0, 0, 0, .4), 0 25px 60px rgba(0, 0, 0, .8);
display: flex;
flex-direction: column;
align-items: center;
gap: 22px;
width: min(560px, 80vw);
}
.cc-screws i {
position: absolute;
width: 12px;
height: 12px;
border-radius: 50%;
background: radial-gradient(circle at 35% 35%, #b9bdc2, #565a60);
box-shadow: inset 0 0 0 1px #2a2c2f;
}
.cc-screws i::after { content: ''; position: absolute; left: 2px; right: 2px; top: 5px; height: 2px; background: #2a2c2f; transform: rotate(35deg); }
.cc-screws i:nth-child(1) { top: 10px; left: 10px; }
.cc-screws i:nth-child(2) { top: 10px; right: 10px; }
.cc-screws i:nth-child(3) { bottom: 10px; left: 10px; }
.cc-screws i:nth-child(4) { bottom: 10px; right: 10px; }
.cc-plate {
font-family: var(--serif);
font-size: 13px;
letter-spacing: .2em;
text-transform: uppercase;
color: #2a2418;
background: linear-gradient(#d8bf7a, #a8873d);
padding: 6px 16px;
border-radius: 3px;
box-shadow: inset 0 1px 0 rgba(255, 255, 255, .5), 0 1px 2px rgba(0, 0, 0, .5);
}
.cc-slots { display: flex; gap: clamp(14px, 3vw, 30px); }
.cc-slot { display: flex; flex-direction: column; align-items: center; gap: 8px; }
.cc-num { font-family: var(--serif); color: #d7d9dc; font-size: 18px; text-shadow: 0 1px 0 #000; }
.cc-button {
--c: #2a2a2a;
width: clamp(56px, 9vw, 84px);
height: clamp(56px, 9vw, 84px);
border-radius: 50%;
padding: 0;
border: 4px solid #1b1c1e;
background: radial-gradient(circle at 35% 30%, rgba(255, 255, 255, .45), transparent 45%), var(--c);
box-shadow: inset 0 -6px 12px rgba(0, 0, 0, .45), 0 0 0 3px #6b7076, 0 4px 8px rgba(0, 0, 0, .5);
transition: transform .08s, box-shadow .2s;
}
.cc-button:hover:not(:disabled) { background: radial-gradient(circle at 35% 30%, rgba(255, 255, 255, .55), transparent 45%), var(--c); border-color: #1b1c1e; }
.cc-button:active { transform: scale(.94); }
.cc-button.lit { box-shadow: inset 0 -6px 12px rgba(0, 0, 0, .35), 0 0 0 3px #6b7076, 0 0 26px var(--c); }
.cc-bottom { display: flex; align-items: center; gap: 18px; }
.cc-led { width: 18px; height: 18px; border-radius: 50%; background: #3a1a1a; box-shadow: inset 0 0 4px #000, 0 0 0 2px #222; }
.cc-led.ko { background: #ff3b30; box-shadow: 0 0 14px #ff3b30, 0 0 0 2px #222; }
.cc-led.ok { background: #3fe06a; box-shadow: 0 0 16px #3fe06a, 0 0 0 2px #222; }
.cc-validate {
font-family: var(--serif);
letter-spacing: .2em;
font-weight: bold;
background: linear-gradient(#9b2b22, #6b1a14);
border: 2px solid #2b0d0a;
color: #f3dcd4;
padding: 10px 26px;
border-radius: 6px;
box-shadow: 0 4px 0 #2b0d0a;
}
.cc-validate:hover:not(:disabled) { background: linear-gradient(#b0342a, #7b211a); border-color: #2b0d0a; }
.cc-validate:active { transform: translateY(3px); box-shadow: 0 1px 0 #2b0d0a; }
.cc-validate:disabled { opacity: .5; cursor: default; }
.cc-help { font-size: 11px; color: #b6b9bd; opacity: .7; }
.cc-panel.shake { animation: shake .4s; }
.cc-panel.solved .cc-button { animation: pulse 1s ease; }
@keyframes shake {
20%, 60% { transform: translateX(-8px); }
40%, 80% { transform: translateX(8px); }
}
@keyframes pulse { 50% { transform: scale(1.1); } }
/* ---------- Puzzle caesar (roue de chiffrement) ---------- */
.cz-panel {
display: flex;
gap: 28px;
align-items: center;
padding: 26px 30px;
width: min(760px, 86vw);
border-radius: 12px;
background:
radial-gradient(ellipse at 30% 20%, rgba(255, 255, 255, .06), transparent 60%),
linear-gradient(160deg, #3b2a1c, #22170e);
border: 2px solid #120b06;
box-shadow: inset 0 1px 0 rgba(255, 255, 255, .1), 0 25px 60px rgba(0, 0, 0, .8);
}
.cz-wheel-wrap { display: flex; flex-direction: column; align-items: center; gap: 12px; }
.cz-wheel { width: clamp(200px, 24vw, 280px); height: auto; user-select: none; }
.cz-outer-disc { fill: #c9a24a; stroke: #6d4f17; stroke-width: 3; }
.cz-inner-disc { fill: #e9dec4; stroke: #8a7a5a; stroke-width: 2; }
.cz-hub { fill: #3b2a1c; stroke: #c9a24a; stroke-width: 3; }
.cz-marker { fill: #d64541; }
.cz-ring-outer text { fill: #2a1d0c; font-family: var(--serif); font-weight: bold; }
.cz-ring-inner text { fill: #5a2323; font-family: var(--serif); }
.cz-ring-inner { transition: transform .25s ease; }
.cz-buttons { display: flex; align-items: center; gap: 12px; }
.cz-buttons button { width: 44px; height: 44px; border-radius: 50%; font-size: 20px; padding: 0; }
.cz-offset { font-family: var(--serif); color: #e2c983; min-width: 92px; text-align: center; }
.cz-text { flex: 1; display: flex; flex-direction: column; gap: 6px; min-width: 0; }
.cz-caption { font-family: var(--serif); color: #e2c983; font-style: italic; margin-bottom: 6px; }
.cz-label { font-size: 11px; letter-spacing: .14em; text-transform: uppercase; color: #a8906a; margin-top: 8px; }
.cz-cipher, .cz-plain {
font-family: 'Courier New', monospace;
font-size: clamp(14px, 1.6vw, 19px);
letter-spacing: .12em;
line-height: 1.55;
padding: 10px 12px;
border-radius: 6px;
word-break: break-word;
}
.cz-cipher { background: #efe6cf; color: #3a2a6a; }
.cz-plain { background: rgba(0, 0, 0, .35); color: #e9e2d0; border: 1px solid rgba(201, 162, 74, .25); }
.cz-panel.solved .cz-plain { color: #8ff0a8; border-color: #3fe06a; box-shadow: 0 0 18px rgba(63, 224, 106, .25); }
.cz-help { font-size: 12px; color: #b9a988; opacity: .8; line-height: 1.5; margin-top: 8px; }
@media (max-width: 700px) { .cz-panel { flex-direction: column; } }
@media (prefers-reduced-motion: reduce) {
*, *::before, *::after { animation-duration: .01ms !important; transition-duration: .01ms !important; }
}

721
src/worlds/bureau.ts Normal file
View File

@ -0,0 +1,721 @@
import * as THREE from 'three';
import * as T from './textures';
import type { World } from './index';
import { PICK_LAYER } from './common';
/**
* Le bureau du professeur, en 3D, construit par code (primitives + textures
* canvas). Les objets interactifs portent un `name` : c'est ce nom que le
* scenario.json référence. Un modèle Blender (.glb) avec les mêmes noms
* d'objets pourrait remplacer ce fichier sans toucher au scénario.
*
* Repère : mètres, pièce de 6 × 6 × 3 m centrée sur l'origine.
* Nord = z négatif, Est = x positif. Chaque mur a son repère local :
* x = droite de l'écran quand on regarde le mur, y = hauteur, z = vers la pièce.
*/
const ROOM = 6;
const HEIGHT = 3;
// --- Matériaux -------------------------------------------------------------------
const grain = T.woodGrain();
const wood = (color: string, rough = 0.6) => new THREE.MeshStandardMaterial({ color, map: grain, roughness: rough, metalness: 0 });
const M = {
woodDark: wood('#4a2d1a'),
woodMid: wood('#6b4428', 0.5),
woodLight: wood('#8a5c38', 0.45),
woodBlack: wood('#2a1a10', 0.7),
brass: new THREE.MeshStandardMaterial({ color: '#c9a24a', metalness: 0.85, roughness: 0.3 }),
metal: new THREE.MeshStandardMaterial({ color: '#5d6268', metalness: 0.7, roughness: 0.45 }),
dark: new THREE.MeshStandardMaterial({ color: '#120a05', roughness: 1 }),
leather: new THREE.MeshStandardMaterial({ color: '#6e3324', roughness: 0.55 }),
green: new THREE.MeshStandardMaterial({ color: '#3a8a55', roughness: 0.3, metalness: 0.1, side: THREE.DoubleSide }),
curtain: new THREE.MeshStandardMaterial({ color: '#5a1a1f', roughness: 0.9, side: THREE.DoubleSide }),
ceiling: new THREE.MeshStandardMaterial({ color: '#151c1d', roughness: 1 }),
paper: new THREE.MeshStandardMaterial({ color: '#efe6cf', roughness: 0.9 }),
};
// --- Aides de construction --------------------------------------------------------------
function box(w: number, h: number, d: number, mat: THREE.Material | THREE.Material[], x = 0, y = 0, z = 0, name?: string): THREE.Mesh {
const m = new THREE.Mesh(new THREE.BoxGeometry(w, h, d), mat);
m.position.set(x, y, z);
if (name) m.name = name;
return m;
}
function group(name: string | undefined, x = 0, y = 0, z = 0, ...children: THREE.Object3D[]): THREE.Group {
const g = new THREE.Group();
if (name) g.name = name;
g.position.set(x, y, z);
if (children.length) g.add(...children);
return g;
}
function plane(w: number, h: number, mat: THREE.Material, x = 0, y = 0, z = 0, name?: string): THREE.Mesh {
const m = new THREE.Mesh(new THREE.PlaneGeometry(w, h), mat);
m.position.set(x, y, z);
if (name) m.name = name;
return m;
}
/**
* Zone cliquable invisible : agrandit la cible d'un petit objet (clé) ou
* délimite un détail peint dans une texture (chiffre du tableau).
*/
function pickZone(w: number, h: number, x: number, y: number, z: number, name?: string): THREE.Mesh {
const m = plane(w, h, new THREE.MeshBasicMaterial({ side: THREE.DoubleSide }), x, y, z, name);
m.layers.set(PICK_LAYER);
m.userData.noShadow = true;
return m;
}
function decal(tex: THREE.Texture, w: number, h: number, x: number, y: number, z: number, name?: string, rotZ = 0): THREE.Mesh {
// Légère émission pour que la peinture reste lisible dans la pénombre.
const mat = new THREE.MeshStandardMaterial({ map: tex, emissiveMap: tex, emissive: '#ffffff', emissiveIntensity: 0.35, transparent: true, roughness: 0.7, depthWrite: false, polygonOffset: true, polygonOffsetFactor: -2 });
const m = plane(w, h, mat, x, y, z, name);
m.rotation.z = rotZ;
m.userData.noShadow = true;
return m;
}
/** Repère d'un mur : rotation autour de y et position du centre au sol. */
function wallFrame(rotY: number, x: number, z: number): THREE.Group {
const g = new THREE.Group();
g.rotation.y = rotY;
g.position.set(x, 0, z);
return g;
}
/** Mur plein avec ouvertures éventuelles ; UV en mètres (texture répétée). */
function wallMesh(holes: { x: number; y: number; w: number; h: number }[]): THREE.Mesh {
const half = ROOM / 2;
const shape = new THREE.Shape();
shape.moveTo(-half, 0);
shape.lineTo(half, 0);
shape.lineTo(half, HEIGHT);
shape.lineTo(-half, HEIGHT);
shape.closePath();
for (const hole of holes) {
const p = new THREE.Path();
p.moveTo(hole.x - hole.w / 2, hole.y);
p.lineTo(hole.x - hole.w / 2, hole.y + hole.h);
p.lineTo(hole.x + hole.w / 2, hole.y + hole.h);
p.lineTo(hole.x + hole.w / 2, hole.y);
p.closePath();
shape.holes.push(p);
}
const mat = new THREE.MeshStandardMaterial({ map: wallpaperTex, roughness: 0.85, shadowSide: THREE.DoubleSide });
const mesh = new THREE.Mesh(new THREE.ShapeGeometry(shape), mat);
mesh.name = 'mur';
mesh.receiveShadow = true;
mesh.castShadow = true;
return mesh;
}
/** Boiserie basse + cimaise + plinthe entre x0 et x1 (repère du mur). */
function wainscotRun(x0: number, x1: number): THREE.Group {
const w = x1 - x0;
const cx = (x0 + x1) / 2;
const tex = wainscotTex.clone();
tex.wrapS = THREE.RepeatWrapping;
tex.repeat.set(w / 0.8, 1);
tex.needsUpdate = true;
const panel = plane(w, 0.83, new THREE.MeshStandardMaterial({ map: tex, roughness: 0.6 }), cx, 0.12 + 0.415, 0.012);
panel.receiveShadow = true;
return group(
undefined,
0,
0,
0,
panel,
box(w, 0.06, 0.05, M.woodMid, cx, 0.97, 0.025),
box(w, 0.13, 0.025, M.woodBlack, cx, 0.065, 0.0125),
box(w, 0.08, 0.06, M.woodMid, cx, HEIGHT - 0.04, 0.03),
);
}
let wallpaperTex: THREE.CanvasTexture;
let wainscotTex: THREE.CanvasTexture;
// --- Mobilier ------------------------------------------------------------------------
function desk(): THREE.Group {
const top = box(1.66, 0.04, 0.8, M.woodLight, 0, 0.78, 0, 'deskTop');
const pedestal = (name: string, x: number) => {
const g = group(name, x, 0, 0);
g.add(box(0.5, 0.68, 0.72, M.woodDark, 0, 0.42, 0));
for (const y of [0.6, 0.26]) {
g.add(box(0.46, 0.3, 0.02, M.woodMid, 0, y, 0.37));
const handle = new THREE.Mesh(new THREE.CylinderGeometry(0.008, 0.008, 0.1, 12), M.brass);
handle.rotation.z = Math.PI / 2;
handle.position.set(0, y, 0.39);
g.add(handle);
}
for (const fx of [-0.22, 0.22]) for (const fz of [-0.32, 0.32]) g.add(box(0.05, 0.08, 0.05, M.woodBlack, fx, 0.04, fz));
return g;
};
// Tiroir secret : façade sans poignée, identique au bandeau du bureau.
const drawerInside = new THREE.MeshStandardMaterial({ color: '#2a1a0e', roughness: 1 });
const keyGroup = key();
keyGroup.position.set(0.02, -0.042, 0.12);
const secret = group(
'secretDrawer',
0,
0.69,
0,
box(0.58, 0.13, 0.02, M.woodMid, 0, 0, 0.365, 'secretFront'),
box(0.54, 0.01, 0.5, drawerInside, 0, -0.05, 0.11),
box(0.01, 0.1, 0.5, drawerInside, -0.27, 0, 0.11),
box(0.01, 0.1, 0.5, drawerInside, 0.27, 0, 0.11),
box(0.54, 0.1, 0.01, drawerInside, 0, 0, -0.14),
keyGroup,
);
// Lampe de banquier
const base = new THREE.Mesh(new THREE.CylinderGeometry(0.09, 0.1, 0.02, 32), M.brass);
base.position.y = 0.01;
const stem = new THREE.Mesh(new THREE.CylinderGeometry(0.008, 0.008, 0.3, 12), M.brass);
stem.position.y = 0.16;
const shade = new THREE.Mesh(new THREE.CylinderGeometry(0.11, 0.11, 0.38, 32, 1, true, 0, Math.PI), M.green);
shade.rotation.z = Math.PI / 2;
shade.position.y = 0.32;
const bulb = new THREE.Mesh(new THREE.CylinderGeometry(0.02, 0.02, 0.3, 12), new THREE.MeshStandardMaterial({ color: '#fff3d6', emissive: '#ffd59a', emissiveIntensity: 1.6 }));
bulb.rotation.z = Math.PI / 2;
bulb.position.y = 0.3;
bulb.userData.noShadow = true;
const lampLight = new THREE.PointLight('#ffc98a', 2.2, 0, 2);
lampLight.position.set(0, 0.24, 0.05);
lampLight.castShadow = true;
lampLight.shadow.mapSize.set(1024, 1024);
lampLight.shadow.bias = -0.002;
lampLight.shadow.radius = 4;
const lamp = group('lamp', -0.52, 0.8, -0.12, base, stem, shade, bulb, lampLight);
// Livres, encrier
const books = group(
'deskBooks',
0.56,
0.8,
-0.08,
box(0.26, 0.06, 0.2, wood('#6b2a2a', 0.8), 0, 0.03, 0),
box(0.23, 0.05, 0.18, wood('#2a4a6b', 0.8), 0.01, 0.085, 0, undefined),
box(0.2, 0.045, 0.17, wood('#5a5a2a', 0.8), -0.01, 0.133, 0),
);
books.rotation.y = -0.12;
const quill = new THREE.Mesh(new THREE.CylinderGeometry(0.002, 0.004, 0.22, 6), new THREE.MeshStandardMaterial({ color: '#eeeeee' }));
quill.position.set(0.03, 0.11, 0);
quill.rotation.z = -0.5;
const ink = group('inkwell', 0.26, 0.8, -0.05, new THREE.Mesh(new THREE.CylinderGeometry(0.03, 0.035, 0.05, 16), new THREE.MeshStandardMaterial({ color: '#1a2433', roughness: 0.2, metalness: 0.3 })), quill);
(ink.children[0] as THREE.Mesh).position.y = 0.025;
return group(
'desk',
0,
0,
0.4,
top,
pedestal('drawersLeft', -0.55),
pedestal('drawersRight', 0.55),
box(0.6, 0.55, 0.02, M.woodBlack, 0, 0.36, -0.33), // panneau de fond
secret,
lamp,
books,
ink,
);
}
function key(): THREE.Group {
const ring = new THREE.Mesh(new THREE.TorusGeometry(0.022, 0.0065, 12, 32), M.brass);
ring.position.x = -0.06;
const shaft = new THREE.Mesh(new THREE.CylinderGeometry(0.005, 0.005, 0.11, 12), M.brass);
shaft.rotation.z = Math.PI / 2;
shaft.position.x = 0.0;
const bit1 = box(0.008, 0.02, 0.006, M.brass, 0.04, -0.013, 0);
const bit2 = box(0.008, 0.028, 0.006, M.brass, 0.05, -0.017, 0);
const k = group('key', 0, 0, 0, ring, shaft, bit1, bit2, pickZone(0.2, 0.09, -0.01, 0, 0));
k.rotation.x = -Math.PI / 2;
k.rotation.z = 0.25;
k.scale.setScalar(1.3);
return k;
}
// --- Murs ---------------------------------------------------------------------------
function northWall(): THREE.Group {
const g = wallFrame(0, 0, -ROOM / 2);
g.add(wallMesh([]), wainscotRun(-3, 3));
// Horloge
const clock = new THREE.Mesh(new THREE.CylinderGeometry(0.2, 0.2, 0.05, 48), M.woodDark);
clock.rotation.x = Math.PI / 2;
const clockFace = new THREE.Mesh(new THREE.CircleGeometry(0.19, 48), new THREE.MeshStandardMaterial({ map: T.clockFace(), roughness: 0.5 }));
clockFace.position.z = 0.026;
const clockRim = new THREE.Mesh(new THREE.TorusGeometry(0.2, 0.018, 12, 48), M.brass);
clockRim.position.z = 0.025;
g.add(group('clock', -1.9, 1.95, 0.03, clock, clockFace, clockRim));
// Carte encadrée
g.add(group('map', 0, 2.05, 0.02, box(1.0, 0.7, 0.04, M.woodBlack), plane(0.9, 0.6, new THREE.MeshStandardMaterial({ map: T.mapTexture(), roughness: 0.9 }), 0, 0, 0.021)));
// Mot épinglé au-dessus du bureau
const note = plane(0.21, 0.15, new THREE.MeshStandardMaterial({ map: T.noteTexture(), roughness: 0.9 }), 0, 0, 0);
const pin = new THREE.Mesh(new THREE.SphereGeometry(0.008, 12, 8), new THREE.MeshStandardMaterial({ color: '#b33', roughness: 0.3 }));
pin.position.set(0, 0.06, 0.006);
const noteGroup = group('note', 0.35, 1.18, 0.006, note, pin);
noteGroup.rotation.z = -0.06;
g.add(noteGroup);
g.add(decal(T.paintedDigit('3', T.PAINT.blue), 0.8, 0.8, 1.75, 1.35, 0.004, 'digit3', -0.08));
g.add(desk());
return g;
}
function eastWall(): THREE.Group {
const g = wallFrame(-Math.PI / 2, ROOM / 2, 0);
const win = { x: -1.3, y: 0.98, w: 1.1, h: 1.45 };
g.add(wallMesh([win]), wainscotRun(-3, 3));
// Fenêtre condamnée : embrasure, châssis, vitre, planches, ciel nocturne.
const cx = win.x;
const cy = win.y + win.h / 2;
const reveal = M.woodDark;
const frame = group(
'window',
0,
0,
0,
box(win.w + 0.16, 0.08, 0.08, M.woodDark, cx, win.y + win.h + 0.04, 0.0),
box(win.w + 0.24, 0.05, 0.2, M.woodMid, cx, win.y - 0.02, 0.06),
box(0.08, win.h, 0.08, M.woodDark, cx - win.w / 2 - 0.04, cy, 0),
box(0.08, win.h, 0.08, M.woodDark, cx + win.w / 2 + 0.04, cy, 0),
box(win.w, 0.012, 0.22, reveal, cx, win.y + win.h, -0.11),
box(win.w, 0.012, 0.22, reveal, cx, win.y, -0.11),
box(0.012, win.h, 0.22, reveal, cx - win.w / 2, cy, -0.11),
box(0.012, win.h, 0.22, reveal, cx + win.w / 2, cy, -0.11),
box(0.05, win.h, 0.05, M.woodDark, cx, cy, -0.12),
box(win.w, 0.05, 0.05, M.woodDark, cx, cy, -0.12),
plane(win.w, win.h, new THREE.MeshStandardMaterial({ color: '#9fb8d0', transparent: true, opacity: 0.1, roughness: 0.35, metalness: 0 }), cx, cy, -0.14),
plane(win.w + 0.6, win.h + 0.6, new THREE.MeshBasicMaterial({ map: T.nightSky() }), cx, cy, -0.6),
);
const plank1 = box(win.w + 0.2, 0.13, 0.03, M.woodBlack, cx, cy + 0.3, -0.2);
plank1.rotation.z = -0.25;
const plank2 = box(win.w + 0.2, 0.13, 0.03, M.woodBlack, cx, cy - 0.28, -0.2);
plank2.rotation.z = 0.18;
frame.add(plank1, plank2);
g.add(frame);
// Rideaux (plis par déformation d'un plan)
const curtainGeo = () => {
const geo = new THREE.PlaneGeometry(0.42, 2.55, 24, 1);
const pos = geo.attributes.position;
for (let i = 0; i < pos.count; i++) pos.setZ(i, Math.sin(pos.getX(i) * 38) * 0.03);
geo.computeVertexNormals();
return geo;
};
const left = new THREE.Mesh(curtainGeo(), M.curtain);
left.position.set(cx - win.w / 2 - 0.2, 1.4, 0.14);
const right = new THREE.Mesh(curtainGeo(), M.curtain);
right.position.set(cx + win.w / 2 + 0.2, 1.4, 0.14);
const rod = new THREE.Mesh(new THREE.CylinderGeometry(0.015, 0.015, win.w + 0.9, 12), M.brass);
rod.rotation.z = Math.PI / 2;
rod.position.set(cx, 2.68, 0.16);
g.add(group('curtains', 0, 0, 0, left, right, rod));
// Tableau
const fw = 1.2;
const fh = 0.85;
const t = 0.07;
const canvas = plane(fw - 2 * t, fh - 2 * t, new THREE.MeshStandardMaterial({ map: T.paintingCanvas(), roughness: 0.75 }), 0, 0, 0.02, 'paintingCanvas');
const painting = group(
'painting',
1.0,
1.75,
0.03,
box(fw, t, 0.06, M.brass, 0, fh / 2 - t / 2, 0),
box(fw, t, 0.06, M.brass, 0, -fh / 2 + t / 2, 0),
box(t, fh, 0.06, M.brass, -fw / 2 + t / 2, 0, 0),
box(t, fh, 0.06, M.brass, fw / 2 - t / 2, 0, 0),
canvas,
pickZone(0.12, 0.14, 0.33, 0.24, 0.025, 'digit1'),
);
// Message à l'encre invisible : caché tant que la lampe UV ne l'a pas révélé.
const uv = plane(
0.92,
0.41,
new THREE.MeshBasicMaterial({ map: T.uvMessage(["SL JVMMYL Z'VBCYL", "H S'OLBYL VB SL", "ALTWZ Z'LZA HYYLAL"]), transparent: true, depthWrite: false, blending: THREE.AdditiveBlending }),
0,
-0.08,
0.024,
'uvMessage',
);
uv.userData.noShadow = true;
painting.add(uv);
g.add(painting);
// Applique de tableau
const bar = new THREE.Mesh(new THREE.CylinderGeometry(0.02, 0.02, 0.36, 16), M.brass);
bar.rotation.z = Math.PI / 2;
bar.position.set(1.0, 2.27, 0.13);
g.add(bar, box(0.02, 0.06, 0.12, M.brass, 1.0, 2.25, 0.06));
const spot = new THREE.SpotLight('#ffd6a0', 3.5, 3, 0.75, 0.6, 2);
spot.name = 'paintingSpot';
spot.position.set(1.0, 2.3, 0.5);
spot.target.position.set(1.0, 1.65, 0);
g.add(spot, spot.target);
// Console et vase
const vase = new THREE.Mesh(
new THREE.LatheGeometry([new THREE.Vector2(0.0, 0), new THREE.Vector2(0.06, 0.0), new THREE.Vector2(0.09, 0.08), new THREE.Vector2(0.06, 0.2), new THREE.Vector2(0.04, 0.26), new THREE.Vector2(0.05, 0.28)], 32),
new THREE.MeshStandardMaterial({ color: '#2c4a5e', roughness: 0.25, metalness: 0.1 }),
);
const flowers = group(undefined, 0, 0.28, 0);
[
['#c84a5a', -0.05, 0.25],
['#e0b84a', 0.07, 0.2],
['#c84a5a', 0.02, 0.32],
].forEach(([c, x, h]) => {
const stem = new THREE.Mesh(new THREE.CylinderGeometry(0.003, 0.003, h as number, 6), new THREE.MeshStandardMaterial({ color: '#3d6b3d' }));
stem.position.set((x as number) / 2, (h as number) / 2, 0);
stem.rotation.z = -(x as number) * 2;
const head = new THREE.Mesh(new THREE.SphereGeometry(0.025, 12, 8), new THREE.MeshStandardMaterial({ color: c as string, roughness: 0.8 }));
head.position.set(x as number, h as number, 0);
flowers.add(stem, head);
});
const consoleTable = group(
'console',
1.0,
0,
0.22,
box(0.8, 0.04, 0.34, M.woodLight, 0, 0.8, 0),
...[-0.36, 0.36].flatMap((x) => [-0.14, 0.14].map((z) => box(0.035, 0.78, 0.035, M.woodDark, x, 0.39, z))),
group('vase', 0, 0.82, 0, vase, flowers, pickZone(0.24, 0.6, 0, 0.27, 0.1)),
);
g.add(consoleTable);
return g;
}
function southWall(): THREE.Group {
const g = wallFrame(Math.PI, 0, ROOM / 2);
const door = { x: 0, y: 0, w: 1.0, h: 2.15 };
g.add(wallMesh([door]), wainscotRun(-3, -0.58), wainscotRun(0.58, 3));
// Encadrement
g.add(box(0.1, 2.25, 0.05, M.woodBlack, -0.55, 1.125, 0.025), box(0.1, 2.25, 0.05, M.woodBlack, 0.55, 1.125, 0.025), box(1.2, 0.1, 0.05, M.woodBlack, 0, 2.2, 0.025));
// Porte (pivot sur la charnière, côté gauche de l'écran)
const slabW = 0.98;
const slab = group(undefined, slabW / 2, 0, 0);
const doorMat = wood('#5e3b22', 0.55);
slab.add(box(slabW, 2.13, 0.05, doorMat, 0, 1.065, 0));
for (const [x, y, h] of [
[-0.22, 1.6, 0.6],
[0.22, 1.6, 0.6],
[-0.22, 0.62, 0.86],
[0.22, 0.62, 0.86],
]) {
slab.add(box(0.34, h, 0.02, M.woodDark, x, y, 0.03));
slab.add(box(0.28, h - 0.06, 0.012, doorMat, x, y, 0.045));
}
const knob = new THREE.Mesh(new THREE.SphereGeometry(0.035, 24, 16), M.brass);
knob.position.set(0.43, 1.0, 0.07);
const rosette = new THREE.Mesh(new THREE.CylinderGeometry(0.03, 0.03, 0.02, 24), M.brass);
rosette.rotation.x = Math.PI / 2;
rosette.position.set(0.43, 1.0, 0.03);
const lock = group('lock', 0.43, 0.87, 0.03, box(0.05, 0.11, 0.012, M.brass), box(0.012, 0.03, 0.004, M.dark, 0, 0.005, 0.008));
const keyholeDot = new THREE.Mesh(new THREE.CylinderGeometry(0.008, 0.008, 0.004, 16), M.dark);
keyholeDot.rotation.x = Math.PI / 2;
keyholeDot.position.set(0, 0.022, 0.008);
lock.add(keyholeDot);
slab.add(knob, rosette, lock);
const doorPivot = group('door', -slabW / 2, 0, -0.01, slab);
g.add(doorPivot);
// Couloir derrière la porte (visible une fois ouverte)
const corridorMat = new THREE.MeshStandardMaterial({ color: '#2a2018', roughness: 1, side: THREE.BackSide });
const corridor = box(1.6, 2.4, 3.2, corridorMat, 0, 1.2, -1.7);
corridor.receiveShadow = false;
const glow = plane(1.6, 2.4, new THREE.MeshBasicMaterial({ color: '#ffcf8a' }), 0, 1.2, -3.25);
glow.rotation.y = 0;
g.add(corridor, glow);
// Boîtier de commande
const lampMat = () => new THREE.MeshStandardMaterial({ color: '#262626', roughness: 0.3, emissive: '#000000', emissiveIntensity: 2.5 });
const panel = group('panel', 0.95, 1.45, 0.0);
panel.add(box(0.36, 0.46, 0.06, M.metal, 0, 0, 0.03));
panel.add(plane(0.22, 0.042, new THREE.MeshStandardMaterial({ map: T.brassPlate('COMMANDE'), metalness: 0.6, roughness: 0.4 }), 0, 0.18, 0.061));
[
[-0.08, 0.08],
[0.08, 0.08],
[-0.08, -0.06],
[0.08, -0.06],
].forEach(([x, y], i) => {
const l = new THREE.Mesh(new THREE.CylinderGeometry(0.042, 0.042, 0.02, 32), lampMat());
l.rotation.x = Math.PI / 2;
l.position.set(x, y, 0.07);
l.name = `panelLamp${i + 1}`;
l.userData.noShadow = true;
const ring = new THREE.Mesh(new THREE.TorusGeometry(0.045, 0.007, 8, 32), M.metal);
ring.position.set(x, y, 0.07);
panel.add(l, ring);
});
const numbers = plane(0.32, 0.4, new THREE.MeshBasicMaterial({ map: T.panelNumbers(), transparent: true, depthWrite: false }), 0, -0.05, 0.0615);
numbers.userData.noShadow = true;
panel.add(numbers);
const led = new THREE.Mesh(new THREE.SphereGeometry(0.012, 16, 12), new THREE.MeshStandardMaterial({ color: '#3a1a1a', emissive: '#000000', emissiveIntensity: 3 }));
led.position.set(0, -0.19, 0.062);
led.name = 'panelLed';
panel.add(led);
for (const [x, y] of [
[-0.16, 0.21],
[0.16, 0.21],
[-0.16, -0.21],
[0.16, -0.21],
]) {
const s = new THREE.Mesh(new THREE.CylinderGeometry(0.008, 0.008, 0.005, 12), M.brass);
s.rotation.x = Math.PI / 2;
s.position.set(x, y, 0.062);
panel.add(s);
}
g.add(panel, conduit(0.95, 1.68));
// Miroir
const mirror = group('mirror', -1.6, 1.75, 0.02);
const glass = new THREE.Mesh(new THREE.CircleGeometry(0.26, 48), new THREE.MeshStandardMaterial({ color: '#5a7a86', metalness: 0.6, roughness: 0.12 }));
glass.position.z = 0.01;
mirror.add(new THREE.Mesh(new THREE.TorusGeometry(0.27, 0.03, 16, 64), M.brass), glass);
g.add(mirror);
g.add(decal(T.paintedDigit('4', T.PAINT.green), 0.6, 0.6, -1.1, 0.52, 0.016, 'digit4', 0.07));
return g;
}
function westWall(): THREE.Group {
const g = wallFrame(Math.PI / 2, -ROOM / 2, 0);
g.add(wallMesh([]), wainscotRun(-3, 3));
// Bibliothèque
const W = 1.8;
const H = 2.15;
const D = 0.36;
const shelf = group('bookshelf', -0.2, 0, D / 2);
const carcass = M.woodDark;
shelf.add(box(W, H, 0.02, M.woodBlack, 0, H / 2, -D / 2 + 0.01));
shelf.add(box(0.04, H, D, carcass, -W / 2 + 0.02, H / 2, 0), box(0.04, H, D, carcass, W / 2 - 0.02, H / 2, 0));
shelf.add(box(W + 0.08, 0.06, D + 0.04, M.woodMid, 0, H + 0.03, 0.01));
const rows = [0.1, 0.62, 1.14, 1.66];
rows.forEach((y) => shelf.add(box(W - 0.08, 0.03, D - 0.02, M.woodMid, 0, y - 0.015, 0)));
shelf.add(box(W - 0.08, 0.04, D - 0.02, M.woodMid, 0, H - 0.04, 0));
const palette = ['#5a2323', '#23405a', '#2f4a2a', '#5a4a23', '#3a2a4a', '#6b5a3a', '#4a2a1a', '#2a3a3a', '#704030'];
const spineMats = palette.map((c) => new THREE.MeshStandardMaterial({ map: T.spine(c), roughness: 0.7 }));
const sideMats = palette.map((c) => new THREE.MeshStandardMaterial({ color: c, roughness: 0.8 }));
const pages = new THREE.MeshStandardMaterial({ color: '#8f8470', roughness: 0.9 });
let seed = 42;
const rnd = () => {
seed = (seed * 16807) % 2147483647;
return seed / 2147483647;
};
rows.forEach((y, row) => {
let x = -W / 2 + 0.06;
let placed = false;
while (x < W / 2 - 0.1) {
if (row === 0 && x > 0.3) break; // place réservée au coffret
const special = row === 2 && !placed && x > 0.25;
const t = special ? 0.06 : 0.025 + rnd() * 0.04;
const h = special ? 0.38 : 0.26 + rnd() * 0.16;
const d = 0.22 + rnd() * 0.05;
if (!special && rnd() < 0.06) {
x += t + 0.05;
continue;
}
let book: THREE.Mesh;
if (special) {
placed = true;
const cream = new THREE.MeshStandardMaterial({ color: '#e6dcc0', roughness: 0.8 });
const spineMat = new THREE.MeshStandardMaterial({ map: T.specialSpine(), roughness: 0.7 });
book = new THREE.Mesh(new THREE.BoxGeometry(t, h, d), [cream, cream, pages, pages, spineMat, cream]);
book.name = 'book2';
} else {
const k = Math.floor(rnd() * palette.length);
book = new THREE.Mesh(new THREE.BoxGeometry(t, h, d), [sideMats[k], sideMats[k], pages, pages, spineMats[k], sideMats[k]]);
}
book.position.set(x + t / 2, y + h / 2, D / 2 - d / 2 - 0.02);
shelf.add(book);
x += t + 0.003;
}
});
shelf.add(strongbox());
g.add(shelf);
g.add(breaker(), conduit(-1.6, 1.67));
// Fauteuil
const chair = group('armchair', 1.9, 0, 0.55);
chair.add(box(0.8, 0.22, 0.75, M.leather, 0, 0.3, 0));
chair.add(box(0.8, 0.75, 0.2, M.leather, 0, 0.7, -0.3));
chair.add(box(0.16, 0.42, 0.75, M.leather, -0.39, 0.45, 0), box(0.16, 0.42, 0.75, M.leather, 0.39, 0.45, 0));
chair.add(box(0.6, 0.1, 0.55, new THREE.MeshStandardMaterial({ color: '#7a3a28', roughness: 0.5 }), 0, 0.46, 0.05));
for (const fx of [-0.36, 0.36]) for (const fz of [-0.3, 0.3]) chair.add(box(0.06, 0.2, 0.06, M.woodBlack, fx, 0.1, fz));
chair.rotation.y = -0.25;
g.add(chair);
return g;
}
// --- Mécanismes : coffret à molettes, disjoncteur, plafonnier ------------------------------
/** Coffret à code (4 molettes), rangé en bas de la bibliothèque. */
function strongbox(): THREE.Group {
const steel = new THREE.MeshStandardMaterial({ color: '#3d4247', metalness: 0.75, roughness: 0.4 });
const inside = new THREE.MeshStandardMaterial({ color: '#1b1d20', roughness: 0.9 });
const w = 0.4;
const h = 0.3;
const d = 0.28;
const t = 0.015;
const zc = 0.02; // centre en profondeur (face avant à z = 0,16)
const safe = group('safe', 0.56, 0.1, 0);
safe.add(
box(w, t, d, steel, 0, t / 2, zc),
box(w, t, d, steel, 0, h - t / 2, zc),
box(t, h, d, steel, -w / 2 + t / 2, h / 2, zc),
box(t, h, d, steel, w / 2 - t / 2, h / 2, zc),
box(w, h, t, steel, 0, h / 2, zc - d / 2 + t / 2),
box(w - 2 * t, 0.004, d - 2 * t, inside, 0, t + 0.002, zc),
);
// Manette du disjoncteur, posée au fond du coffret
const grip = new THREE.Mesh(new THREE.CylinderGeometry(0.018, 0.018, 0.07, 16), new THREE.MeshStandardMaterial({ color: '#8a1c14', roughness: 0.35 }));
grip.position.x = 0.07;
grip.rotation.z = Math.PI / 2;
const shaft = new THREE.Mesh(new THREE.CylinderGeometry(0.007, 0.007, 0.12, 12), M.metal);
shaft.rotation.z = Math.PI / 2;
const lever = group('leverItem', 0, t + 0.02, zc + 0.02, shaft, grip, pickZone(0.22, 0.12, 0.01, 0, 0));
(lever.children[2] as THREE.Mesh).rotation.x = -Math.PI / 2;
lever.rotation.y = 0.3;
safe.add(lever);
// Porte, pivot sur le bord gauche
const door = group('safeDoor', -w / 2, h / 2, zc + d / 2);
door.add(box(w, h, 0.02, steel, w / 2, 0, 0.01));
door.add(box(w - 0.04, h - 0.04, 0.004, new THREE.MeshStandardMaterial({ color: '#4a5055', metalness: 0.7, roughness: 0.35 }), w / 2, 0, 0.022));
const plate = plane(0.3, 0.05, new THREE.MeshStandardMaterial({ map: T.brassPlate('LINDQVIST & FILS'), metalness: 0.6, roughness: 0.4 }), w / 2, 0.1, 0.025);
door.add(plate);
const digits = T.dialDigits();
const dialMat = new THREE.MeshStandardMaterial({ map: digits, emissiveMap: digits, emissive: '#ffffff', emissiveIntensity: 0.18, roughness: 0.5 });
[-0.105, -0.035, 0.035, 0.105].forEach((dx, i) => {
const wheel = new THREE.Mesh(new THREE.CylinderGeometry(0.03, 0.03, 0.05, 32), [dialMat, M.metal, M.metal]);
wheel.rotation.z = Math.PI / 2;
const dial = group(`dial${i + 1}`, w / 2 + dx, -0.01, 0.04, wheel);
door.add(dial);
});
door.add(box(0.28, 0.08, 0.012, M.dark, w / 2, -0.01, 0.026)); // fente des molettes
const handle = new THREE.Mesh(new THREE.CylinderGeometry(0.01, 0.01, 0.1, 12), M.brass);
handle.position.set(w - 0.05, -0.09, 0.045);
door.add(handle, box(0.03, 0.03, 0.02, M.brass, w - 0.05, -0.09, 0.03));
safe.add(door);
return safe;
}
/** Disjoncteur du circuit du boîtier (mur ouest, à gauche de la bibliothèque). */
function breaker(): THREE.Group {
const grey = new THREE.MeshStandardMaterial({ color: '#6b7076', metalness: 0.5, roughness: 0.5 });
const g = group('breaker', -1.6, 1.45, 0);
g.add(box(0.32, 0.44, 0.1, grey, 0, 0, 0.05));
g.add(plane(0.24, 0.045, new THREE.MeshStandardMaterial({ map: T.brassPlate('DISJONCTEUR'), metalness: 0.6, roughness: 0.4 }), 0, 0.17, 0.101));
g.add(box(0.07, 0.14, 0.02, M.dark, 0, -0.02, 0.105, 'breakerSocket'));
const led = new THREE.Mesh(new THREE.SphereGeometry(0.012, 16, 12), new THREE.MeshStandardMaterial({ color: '#3a1a1a', emissive: '#000000', emissiveIntensity: 3 }));
led.position.set(0.11, 0.13, 0.105);
led.name = 'breakerLed';
led.userData.noShadow = true;
g.add(led);
// Manette installée (cachée tant qu'on ne l'a pas posée), pivot sur l'axe x
const arm = new THREE.Mesh(new THREE.CylinderGeometry(0.008, 0.008, 0.13, 12), M.metal);
arm.position.y = 0.065;
const grip = new THREE.Mesh(new THREE.CylinderGeometry(0.018, 0.018, 0.07, 16), new THREE.MeshStandardMaterial({ color: '#8a1c14', roughness: 0.35 }));
grip.rotation.z = Math.PI / 2;
grip.position.y = 0.13;
const lever = group('breakerLever', 0, -0.02, 0.115, arm, grip, pickZone(0.12, 0.2, 0, 0.08, 0.02));
lever.rotation.x = 0.35;
g.add(lever);
return g;
}
/** Gaine électrique verticale (hors des objets cliquables, pour un contour propre). */
function conduit(x: number, fromY: number): THREE.Mesh {
const m = new THREE.Mesh(new THREE.CylinderGeometry(0.014, 0.014, HEIGHT - fromY, 12), M.metal);
m.position.set(x, (HEIGHT + fromY) / 2, 0.03);
return m;
}
/** Plafonnier : s'allume quand le courant revient. */
function pendant(): THREE.Group {
const cord = new THREE.Mesh(new THREE.CylinderGeometry(0.006, 0.006, 0.55, 8), M.dark);
cord.position.y = -0.275;
const shade = new THREE.Mesh(new THREE.ConeGeometry(0.22, 0.16, 32, 1, true), new THREE.MeshStandardMaterial({ color: '#c9a24a', metalness: 0.8, roughness: 0.35, side: THREE.DoubleSide }));
shade.position.y = -0.6;
const bulb = new THREE.Mesh(new THREE.SphereGeometry(0.05, 16, 12), new THREE.MeshStandardMaterial({ color: '#6a6458', emissive: '#000000', emissiveIntensity: 2 }));
bulb.position.y = -0.68;
bulb.name = 'ceilingBulb';
bulb.userData.noShadow = true;
const light = new THREE.PointLight('#ffe2b8', 9, 0, 2);
light.position.y = -0.72;
light.name = 'ceilingLight';
return group('pendant', 0, HEIGHT, 0, cord, shade, bulb, light);
}
// --- Assemblage ------------------------------------------------------------------------
export function buildBureau(): World {
wallpaperTex = T.wallpaper();
wainscotTex = T.wainscot();
const root = new THREE.Group();
root.name = 'bureau';
// Sol, plafond, tapis
const floor = new THREE.Mesh(new THREE.PlaneGeometry(ROOM, ROOM), new THREE.MeshStandardMaterial({ map: T.floorPlanks(), roughness: 0.55 }));
floor.rotation.x = -Math.PI / 2;
floor.receiveShadow = true;
const ceiling = new THREE.Mesh(new THREE.PlaneGeometry(ROOM, ROOM), M.ceiling);
ceiling.rotation.x = Math.PI / 2;
ceiling.position.y = HEIGHT;
const rug = new THREE.Mesh(new THREE.CircleGeometry(1, 64), new THREE.MeshStandardMaterial({ color: '#4a1e1e', roughness: 1 }));
rug.rotation.x = -Math.PI / 2;
rug.scale.set(1.6, 1.1, 1);
rug.position.set(-1.2, 0.004, 0.1);
const rugBorder = new THREE.Mesh(new THREE.RingGeometry(0.92, 0.95, 64), new THREE.MeshStandardMaterial({ color: '#9a7a3a', roughness: 1 }));
rugBorder.rotation.x = -Math.PI / 2;
rugBorder.scale.set(1.6, 1.1, 1);
rugBorder.position.set(-1.2, 0.005, 0.1);
root.add(floor, ceiling, rug, rugBorder);
root.add(northWall(), eastWall(), southWall(), westWall());
// Éclairage d'ambiance
root.add(new THREE.HemisphereLight('#4a6066', '#2a1a10', 0.8));
const fill = new THREE.PointLight('#ffdcb0', 3.5, 0, 2);
fill.position.set(0, 2.7, 0);
root.add(fill, pendant());
// Clair de lune à travers la fenêtre
const moon = new THREE.DirectionalLight('#9cc4ff', 0.9);
moon.position.set(7, 4.2, -1.3);
moon.target.position.set(0.5, 0, -0.8);
moon.castShadow = true;
moon.shadow.mapSize.set(1024, 1024);
Object.assign(moon.shadow.camera, { left: -3, right: 3, top: 3, bottom: -3, near: 1, far: 15 });
moon.shadow.bias = -0.001;
root.add(moon, moon.target);
root.traverse((o) => {
if ((o as THREE.Mesh).isMesh && !o.userData.noShadow) {
o.castShadow = true;
o.receiveShadow = true;
}
});
floor.castShadow = false;
ceiling.castShadow = false;
return { root };
}

2
src/worlds/common.ts Normal file
View File

@ -0,0 +1,2 @@
/** Calque des zones cliquables invisibles : ignoré par la caméra, vu par le raycast. */
export const PICK_LAYER = 1;

20
src/worlds/index.ts Normal file
View File

@ -0,0 +1,20 @@
import type * as THREE from 'three';
import { buildBureau } from './bureau';
/** Un monde 3D : la racine de la scène, avec des objets nommés. */
export interface World {
root: THREE.Object3D;
/** Appelé à chaque image (animations d'ambiance éventuelles). */
update?(dt: number): void;
}
/** Registre des mondes, référencés par `"world"` dans scenario.json. */
const worlds: Record<string, () => World> = {
bureau: buildBureau,
};
export function buildWorld(name: string): World {
const f = worlds[name];
if (!f) throw new Error(`Monde 3D inconnu : "${name}"`);
return f();
}

469
src/worlds/textures.ts Normal file
View File

@ -0,0 +1,469 @@
import * as THREE from 'three';
/**
* Textures procédurales dessinées sur canvas : aucun fichier image à fournir
* pour le prototype.
*/
export const PAINT = { yellow: '#f2c230', red: '#d64541', blue: '#3a7bd5', green: '#3fae5a' };
function rng(seed: number) {
return () => {
seed |= 0;
seed = (seed + 0x6d2b79f5) | 0;
let t = Math.imul(seed ^ (seed >>> 15), 1 | seed);
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
}
function canvasTexture(w: number, h: number, draw: (g: CanvasRenderingContext2D, w: number, h: number) => void, repeat?: [number, number]): THREE.CanvasTexture {
const c = document.createElement('canvas');
c.width = w;
c.height = h;
draw(c.getContext('2d')!, w, h);
const tex = new THREE.CanvasTexture(c);
tex.colorSpace = THREE.SRGBColorSpace;
tex.anisotropy = 8;
if (repeat) {
tex.wrapS = tex.wrapT = THREE.RepeatWrapping;
tex.repeat.set(repeat[0], repeat[1]);
}
return tex;
}
const SERIF = "Georgia, 'Times New Roman', serif";
const HAND = "'Segoe Script', 'Bradley Hand', 'Brush Script MT', 'Comic Sans MS', cursive";
/** Papier peint : 1 motif = 1/3 m. UV des murs en mètres. */
export function wallpaper(): THREE.CanvasTexture {
return canvasTexture(
256,
256,
(g, w, h) => {
const grad = g.createLinearGradient(0, 0, 0, h);
grad.addColorStop(0, '#2b4446');
grad.addColorStop(1, '#253c3e');
g.fillStyle = grad;
g.fillRect(0, 0, w, h);
g.fillStyle = 'rgba(0,0,0,.2)';
g.fillRect(0, 0, 10, h);
g.fillStyle = 'rgba(216,196,143,.09)';
g.fillRect(126, 0, 4, h);
g.strokeStyle = 'rgba(216,196,143,.11)';
g.lineWidth = 6;
g.beginPath();
g.moveTo(50, 90);
g.quadraticCurveTo(90, 30, 130, 90);
g.quadraticCurveTo(170, 150, 210, 90);
g.stroke();
g.fillStyle = 'rgba(216,196,143,.1)';
g.beginPath();
g.arc(130, 200, 10, 0, Math.PI * 2);
g.fill();
},
[3, 3],
);
}
/** Boiserie basse : un panneau de 0,8 m × 0,83 m. */
export function wainscot(): THREE.CanvasTexture {
return canvasTexture(512, 532, (g, w, h) => {
const r = rng(11);
g.fillStyle = '#4a3020';
g.fillRect(0, 0, w, h);
for (let i = 0; i < 120; i++) {
g.strokeStyle = `rgba(${r() < 0.5 ? '20,10,4' : '120,80,50'},${0.05 + r() * 0.08})`;
g.lineWidth = 1 + r() * 2;
const y = r() * h;
g.beginPath();
g.moveTo(0, y);
g.bezierCurveTo(w * 0.3, y + r() * 8 - 4, w * 0.6, y + r() * 8 - 4, w, y);
g.stroke();
}
const m = 48;
g.fillStyle = 'rgba(0,0,0,.18)';
g.fillRect(m, m, w - 2 * m, h - 2 * m);
g.strokeStyle = 'rgba(0,0,0,.55)';
g.lineWidth = 6;
g.strokeRect(m, m, w - 2 * m, h - 2 * m);
g.strokeStyle = 'rgba(190,140,95,.25)';
g.lineWidth = 3;
g.strokeRect(m + 8, m + 8, w - 2 * m - 16, h - 2 * m - 16);
});
}
/** Parquet : la texture couvre 2 m × 2 m. */
export function floorPlanks(): THREE.CanvasTexture {
return canvasTexture(
1024,
1024,
(g, w, h) => {
const r = rng(5);
const rows = 10;
const ph = h / rows;
for (let i = 0; i < rows; i++) {
let x = -r() * 400;
while (x < w) {
const len = 300 + r() * 400;
const l = 22 + r() * 10;
g.fillStyle = `hsl(25, 38%, ${l}%)`;
g.fillRect(x, i * ph, len, ph);
for (let k = 0; k < 6; k++) {
g.strokeStyle = `rgba(20,10,4,${0.1 + r() * 0.15})`;
g.lineWidth = 1;
const yy = i * ph + r() * ph;
g.beginPath();
g.moveTo(x, yy);
g.lineTo(x + len, yy + r() * 6 - 3);
g.stroke();
}
g.fillStyle = 'rgba(0,0,0,.6)';
g.fillRect(x, i * ph, 3, ph);
x += len;
}
g.fillStyle = 'rgba(0,0,0,.55)';
g.fillRect(0, i * ph, w, 3);
}
},
[3, 3],
);
}
/** Veinage de bois neutre (multiplié par la couleur du matériau). */
export function woodGrain(seed = 3): THREE.CanvasTexture {
return canvasTexture(
256,
256,
(g, w, h) => {
const r = rng(seed);
g.fillStyle = '#cfcfcf';
g.fillRect(0, 0, w, h);
for (let i = 0; i < 70; i++) {
g.strokeStyle = `rgba(0,0,0,${0.04 + r() * 0.1})`;
g.lineWidth = 1 + r() * 3;
const y = r() * h;
g.beginPath();
g.moveTo(0, y);
g.bezierCurveTo(w * 0.33, y + r() * 10 - 5, w * 0.66, y + r() * 10 - 5, w, y);
g.stroke();
}
},
[1, 1],
);
}
/** Chiffre peint à la main, avec coulures (fond transparent). */
export function paintedDigit(ch: string, color: string): THREE.CanvasTexture {
return canvasTexture(512, 512, (g, w, h) => {
const r = rng(ch.charCodeAt(0));
g.fillStyle = color;
g.textAlign = 'center';
g.textBaseline = 'alphabetic';
g.font = `bold 400px ${SERIF}`;
for (let i = 0; i < 6; i++) {
g.globalAlpha = 0.28;
g.fillText(ch, w / 2 + r() * 10 - 5, h * 0.72 + r() * 10 - 5);
}
g.globalAlpha = 0.85;
g.fillText(ch, w / 2, h * 0.72);
for (const [dx, len] of [
[-0.12, 0.2],
[0.06, 0.26],
[0.16, 0.12],
]) {
const x = w / 2 + dx * w;
g.fillRect(x, h * 0.68, 10, h * len);
g.beginPath();
g.arc(x + 5, h * (0.68 + len), 7, 0, Math.PI * 2);
g.fill();
}
g.globalAlpha = 1;
});
}
/** Le tableau : paysage au crépuscule avec un « 1 » jaune discret dans le ciel. */
export function paintingCanvas(): THREE.CanvasTexture {
return canvasTexture(1024, 686, (g, w, h) => {
const sky = g.createLinearGradient(0, 0, 0, h);
sky.addColorStop(0, '#2b4673');
sky.addColorStop(0.6, '#c9805a');
sky.addColorStop(1, '#f0b46a');
g.fillStyle = sky;
g.fillRect(0, 0, w, h);
g.fillStyle = 'rgba(247,211,106,.25)';
g.beginPath();
g.arc(680, 400, 110, 0, Math.PI * 2);
g.fill();
g.fillStyle = '#f7d36a';
g.beginPath();
g.arc(680, 400, 66, 0, Math.PI * 2);
g.fill();
g.fillStyle = '#2f4a32';
g.beginPath();
g.moveTo(0, 470);
g.bezierCurveTo(200, 300, 350, 470, 500, 430);
g.bezierCurveTo(650, 390, 760, 230, 1024, 380);
g.lineTo(1024, h);
g.lineTo(0, h);
g.fill();
g.fillStyle = '#1f3524';
g.beginPath();
g.moveTo(0, 540);
g.bezierCurveTo(250, 450, 500, 560, 1024, 520);
g.lineTo(1024, h);
g.lineTo(0, h);
g.fill();
g.fillStyle = '#3a2a1a';
g.fillRect(200, 440, 70, 52);
g.fillStyle = '#6b2a2a';
g.beginPath();
g.moveTo(188, 444);
g.lineTo(235, 404);
g.lineTo(282, 444);
g.fill();
g.fillStyle = 'rgba(74,106,138,.75)';
g.beginPath();
g.ellipse(800, 590, 160, 16, 0, 0, Math.PI * 2);
g.fill();
// Le chiffre caché
g.fillStyle = PAINT.yellow;
g.font = `bold 72px ${SERIF}`;
g.textAlign = 'center';
g.fillText('1', 900, 150);
g.fillStyle = 'rgba(26,18,8,.7)';
g.font = `italic 22px ${SERIF}`;
g.fillText('A. L.', 940, 660);
// Grain de toile
const r = rng(9);
for (let i = 0; i < 4000; i++) {
g.fillStyle = `rgba(${r() < 0.5 ? '0,0,0' : '255,255,255'},.035)`;
g.fillRect(r() * w, r() * h, 2, 2);
}
});
}
/** Le mot épinglé au mur (lisible en gros plan). */
export function noteTexture(): THREE.CanvasTexture {
return canvasTexture(1024, 732, (g, w, h) => {
g.fillStyle = '#efe6cf';
g.fillRect(0, 0, w, h);
g.fillStyle = 'rgba(201,168,118,.18)';
g.fillRect(0, 0, w, h);
g.fillStyle = 'rgba(154,176,200,.55)';
for (let i = 0; i < 7; i++) g.fillRect(50, 150 + i * 88, w - 100, 2);
g.fillStyle = '#2a2a4a';
g.font = `46px ${HAND}`;
const lines = ['Lindqvist,', 'Ils ont repeint la pièce,', 'mais j’ai laissé les chiffres.', 'Chaque chiffre a sa couleur.', 'Chaque couleur a sa place.'];
lines.forEach((l, i) => g.fillText(l, 64, 138 + i * 88));
g.textAlign = 'right';
g.fillText('— A.', w - 90, 138 + 5 * 88);
});
}
export function mapTexture(): THREE.CanvasTexture {
return canvasTexture(512, 340, (g, w, h) => {
g.fillStyle = '#cdb88a';
g.fillRect(0, 0, w, h);
g.strokeStyle = '#8a6a3a';
g.lineWidth = 4;
g.beginPath();
g.moveTo(50, 90);
g.bezierCurveTo(150, 30, 220, 140, 300, 110);
g.bezierCurveTo(380, 80, 420, 190, 480, 170);
g.moveTo(60, 260);
g.bezierCurveTo(160, 200, 280, 280, 450, 230);
g.stroke();
g.fillStyle = '#8a3a2a';
g.beginPath();
g.moveTo(250, 80);
g.lineTo(262, 125);
g.lineTo(250, 112);
g.lineTo(238, 125);
g.fill();
g.strokeStyle = 'rgba(80,50,20,.5)';
g.lineWidth = 2;
g.beginPath();
g.arc(380, 240, 24, 0, Math.PI * 2);
g.stroke();
});
}
export function clockFace(): THREE.CanvasTexture {
return canvasTexture(512, 512, (g, w) => {
const c = w / 2;
g.fillStyle = '#e9dec4';
g.fillRect(0, 0, w, w);
g.translate(c, c);
g.fillStyle = '#3a2a1a';
for (let i = 0; i < 12; i++) {
g.save();
g.rotate((i * Math.PI) / 6);
g.fillRect(-5, -230, 10, i % 3 ? 26 : 44);
g.restore();
}
g.font = `bold 56px ${SERIF}`;
g.textAlign = 'center';
g.textBaseline = 'middle';
for (const [n, a] of [
['12', 0],
['3', 90],
['6', 180],
['9', 270],
] as const) {
const r = (a * Math.PI) / 180;
g.fillText(n, Math.sin(r) * 160, -Math.cos(r) * 160);
}
// Arrêtée à 10 h 40 (indice du coffret)
g.fillStyle = '#222';
g.save();
g.rotate(((10 + 40 / 60) * Math.PI) / 6);
g.fillRect(-8, -125, 16, 140);
g.restore();
g.save();
g.rotate((40 * Math.PI) / 30);
g.fillRect(-5, -205, 10, 215);
g.restore();
g.beginPath();
g.arc(0, 0, 14, 0, Math.PI * 2);
g.fill();
});
}
export function nightSky(): THREE.CanvasTexture {
return canvasTexture(512, 640, (g, w, h) => {
const r = rng(7);
const grad = g.createLinearGradient(0, 0, 0, h);
grad.addColorStop(0, '#0a1428');
grad.addColorStop(1, '#22385c');
g.fillStyle = grad;
g.fillRect(0, 0, w, h);
for (let i = 0; i < 90; i++) {
g.fillStyle = `rgba(255,255,255,${0.3 + r() * 0.6})`;
g.beginPath();
g.arc(r() * w, r() * h * 0.8, 0.6 + r() * 1.6, 0, Math.PI * 2);
g.fill();
}
const glow = g.createRadialGradient(360, 160, 10, 360, 160, 150);
glow.addColorStop(0, 'rgba(184,212,255,.6)');
glow.addColorStop(1, 'rgba(184,212,255,0)');
g.fillStyle = glow;
g.fillRect(0, 0, w, h);
g.fillStyle = '#f1f0e2';
g.beginPath();
g.arc(360, 160, 48, 0, Math.PI * 2);
g.fill();
g.fillStyle = '#d8d6c4';
g.beginPath();
g.arc(345, 148, 10, 0, Math.PI * 2);
g.fill();
});
}
/** Tranche du livre au « 2 » rouge. */
export function specialSpine(): THREE.CanvasTexture {
return canvasTexture(128, 768, (g, w, h) => {
g.fillStyle = '#e6dcc0';
g.fillRect(0, 0, w, h);
g.fillStyle = '#8a7a5a';
g.fillRect(10, 40, w - 20, 5);
g.fillRect(10, h - 50, w - 20, 5);
g.fillStyle = PAINT.red;
g.font = `bold 120px ${SERIF}`;
g.textAlign = 'center';
for (let i = 0; i < 4; i++) {
g.globalAlpha = 0.35;
g.fillText('2', w / 2 + (i - 1.5) * 2, h / 2 + 44 + (i % 2) * 2);
}
g.globalAlpha = 0.9;
g.fillText('2', w / 2, h / 2 + 44);
});
}
/** Tranche de livre générique avec filets dorés. */
export function spine(color: string): THREE.CanvasTexture {
return canvasTexture(64, 256, (g, w, h) => {
g.fillStyle = color;
g.fillRect(0, 0, w, h);
g.fillStyle = 'rgba(217,184,96,.6)';
g.fillRect(6, 24, w - 12, 5);
g.fillRect(6, 34, w - 12, 2);
g.fillRect(6, h - 36, w - 12, 5);
g.fillStyle = 'rgba(0,0,0,.2)';
g.fillRect(0, 0, 4, h);
g.fillRect(w - 4, 0, 4, h);
});
}
export function brassPlate(text: string): THREE.CanvasTexture {
return canvasTexture(512, 96, (g, w, h) => {
const grad = g.createLinearGradient(0, 0, 0, h);
grad.addColorStop(0, '#e2c983');
grad.addColorStop(1, '#a8873d');
g.fillStyle = grad;
g.fillRect(0, 0, w, h);
g.fillStyle = '#2a2418';
const label = text.split('').join(' ');
let size = 52;
do {
g.font = `${size}px ${SERIF}`;
size -= 2;
} while (g.measureText(label).width > w - 30 && size > 16);
g.textAlign = 'center';
g.textBaseline = 'middle';
g.fillText(label, w / 2, h / 2 + 3);
});
}
export function panelNumbers(): THREE.CanvasTexture {
return canvasTexture(256, 320, (g) => {
g.clearRect(0, 0, 256, 320);
g.fillStyle = '#d7d9dc';
g.font = `40px ${SERIF}`;
g.textAlign = 'center';
g.fillText('1', 64, 118);
g.fillText('2', 192, 118);
g.fillText('3', 64, 230);
g.fillText('4', 192, 230);
});
}
/** Message à l'encre invisible, révélé par la lampe UV (fond transparent). */
export function uvMessage(lines: string[]): THREE.CanvasTexture {
return canvasTexture(1024, 460, (g, w, h) => {
g.clearRect(0, 0, w, h);
g.textAlign = 'center';
g.textBaseline = 'middle';
g.font = `bold 64px 'Courier New', monospace`;
g.shadowColor = '#b48cff';
g.shadowBlur = 24;
g.fillStyle = '#e6d8ff';
lines.forEach((l, i) => g.fillText(l, w / 2, h / 2 + (i - (lines.length - 1) / 2) * 100));
});
}
/** Bande de chiffres 0-9 enroulée autour d'une molette de cadenas. */
export function dialDigits(): THREE.CanvasTexture {
const tex = canvasTexture(1024, 128, (g, w, h) => {
g.fillStyle = '#d9d2bf';
g.fillRect(0, 0, w, h);
g.fillStyle = '#1a1a1a';
g.font = `bold 84px ${SERIF}`;
g.textAlign = 'center';
g.textBaseline = 'middle';
for (let k = 0; k <= 10; k++) {
// Chiffres tournés d'un quart de tour : ils se lisent droits une fois enroulés.
g.save();
g.translate((k * w) / 10, h / 2);
g.rotate(Math.PI / 2);
// Décalage d'une case : la case 1 de la bande est face à l'avant au repos.
g.fillText(String((k + 9) % 10), 0, 4);
g.restore();
g.fillStyle = 'rgba(0,0,0,.25)';
g.fillRect(((k + 0.5) * w) / 10 - 2, 0, 4, h);
g.fillStyle = '#1a1a1a';
}
});
tex.wrapS = THREE.RepeatWrapping;
return tex;
}

124
tests/engine.test.ts Normal file
View File

@ -0,0 +1,124 @@
import { describe, expect, it } from 'vitest';
import { Engine, type View } from '../src/engine/Engine';
import { checkCondition, newState } from '../src/engine/state';
import type { Scenario } from '../src/engine/types';
/** Mini-scénario synthétique pour tester chaque mécanique du moteur isolément. */
function makeEngine(extra: Partial<Scenario> = {}) {
const scenario: Scenario = {
id: 'test',
title: 'Test',
difficulty: 1,
world: 'test',
resolution: [1280, 720],
startScene: 'a',
items: [
{ id: 'x', name: 'X', icon: '' },
{ id: 'y', name: 'Y', icon: '' },
{ id: 'xy', name: 'XY', icon: '' },
],
scenes: [
{
id: 'a',
camera: { position: [0, 0, 0], target: [0, 0, -1] },
right: 'b',
hotspots: [
{ id: 'dial', object: 'dial', interactions: [{ do: [{ add: 'd', mod: 3 }] }] },
{ id: 'door', object: 'door', interactions: [{ when: ['selected:xy'], do: [{ setFlag: 'open' }] }, { do: [{ message: 'fermé' }] }] },
{ id: 'cond', object: 'cond', interactions: [{ do: [{ if: ['var:d=2'], then: [{ setFlag: 'two' }], else: [{ clearFlag: 'two' }] }] }] },
],
},
{ id: 'b', camera: { position: [0, 0, 0], target: [1, 0, 0] }, left: 'a', hotspots: [] },
],
puzzles: [],
hints: [],
combinations: [{ items: ['x', 'y'], do: [{ remove: 'x' }, { remove: 'y' }, { give: 'xy' }] }],
triggers: [{ id: 't', when: ['var:d=2'], do: [{ give: 'x' }] }],
...extra,
};
const state = newState('test', 'a');
const engine = new Engine(scenario, state, { instant: true });
const messages: string[] = [];
const view: View = {
showScene() {},
refresh() {},
showMessage: (t) => void messages.push(t),
openPuzzle() {},
closePuzzle() {},
showWin() {},
};
engine.attach(view);
const hs = (id: string) => engine.activeHotspots(engine.currentScene).find((h) => h.id === id)!;
return { engine, state, messages, hs };
}
describe('conditions', () => {
it('variables et opérateurs', () => {
const s = newState('t', 'a');
s.vars.n = 3;
expect(checkCondition(s, 'var:n=3')).toBe(true);
expect(checkCondition(s, 'var:n>=4')).toBe(false);
expect(checkCondition(s, '!var:n<3')).toBe(true);
expect(checkCondition(s, 'var:absent=0')).toBe(true);
});
});
describe('moteur', () => {
it('add avec modulo (molette) et déclencheur unique', () => {
const { engine, state, hs } = makeEngine();
engine.click(hs('dial'));
engine.click(hs('dial'));
expect(state.vars.d).toBe(2);
expect(state.inventory).toEqual(['x']); // déclencheur exécuté
engine.click(hs('dial'));
expect(state.vars.d).toBe(0); // 3 mod 3
state.inventory = [];
engine.click(hs('dial'));
engine.click(hs('dial'));
expect(state.inventory).toEqual([]); // ne se redéclenche pas
});
it('action conditionnelle if/then/else', () => {
const { engine, state, hs } = makeEngine();
engine.click(hs('cond'));
expect(state.flags.two).toBeUndefined();
state.vars.d = 2;
engine.click(hs('cond'));
expect(state.flags.two).toBe(true);
});
it('combinaison d’objets, puis utilisation de l’objet obtenu', () => {
const { engine, state, hs, messages } = makeEngine();
state.inventory = ['x', 'y'];
expect(engine.combine('y', 'x')).toBe(true); // ordre indifférent
expect(state.inventory).toEqual(['xy']);
expect(engine.click(hs('door'))).toBe(true);
expect(messages.at(-1)).toBe('fermé');
engine.selectItem('xy');
expect(engine.click(hs('door'))).toBe(true);
expect(state.flags.open).toBe(true);
expect(state.selected).toBeNull(); // objet rangé après usage
});
it('objet inadapté : message et désélection', () => {
const { engine, state, hs, messages } = makeEngine();
state.inventory = ['x'];
engine.selectItem('x');
expect(engine.click(hs('dial'))).toBe(false);
expect(messages.at(-1)).toContain('ne sert à rien');
expect(state.selected).toBeNull();
});
it('combinaison inconnue', () => {
const { engine, state } = makeEngine();
state.inventory = ['x', 'xy'];
expect(engine.combine('x', 'xy')).toBe(false);
expect(state.inventory).toEqual(['x', 'xy']);
});
it('navigation générée (flèches)', () => {
const { engine, state, hs } = makeEngine();
engine.click(hs('__right'));
expect(state.scene).toBe('b');
});
});

77
tests/scenarios.test.ts Normal file
View File

@ -0,0 +1,77 @@
import { describe, expect, it } from 'vitest';
import { caesarDecode } from '../src/puzzles/caesar';
import { analyzeScenario } from '../src/engine/scenarioAnalysis';
import { listScenarios } from '../src/engine/scenarioLoader';
import { runWalkthrough, type Walkthrough } from '../src/engine/walkthrough';
import type { PuzzleDef } from '../src/engine/types';
/**
* Pour chaque chapitre de src/scenarios/ :
* 1. références valides (scènes, objets, puzzles, images) ;
* 2. cohérence logique (drapeaux, objets, variables, scènes accessibles) ;
* 3. paramètres des mini-jeux cohérents ;
* 4. la solution de référence (walkthrough.json) mène à la victoire.
*/
const walkthroughs = import.meta.glob('../src/scenarios/*/walkthrough.json', { eager: true, import: 'default' }) as Record<string, Walkthrough>;
const normalize = (s: string) =>
s
.normalize('NFD')
.replace(/[̀-ͯ]/g, '')
.replace(/[’‘]/g, "'")
.replace(/[«»"]/g, '')
.replace(/\s+/g, ' ')
.trim()
.toUpperCase();
/** Contrôles propres à chaque type de mini-jeu. */
function checkPuzzle(p: PuzzleDef): string[] {
const errors: string[] = [];
const params = p.params as Record<string, unknown>;
if (p.type === 'colorCode') {
const colors = (params.colors as { id: string }[]).map((c) => c.id);
const solution = params.solution as string[];
if (!solution?.length) errors.push(`${p.id} : solution vide`);
solution?.forEach((id) => colors.includes(id) || errors.push(`${p.id} : couleur "${id}" absente de la palette`));
} else if (p.type === 'caesar') {
const shift = params.shift as number;
if (!(shift > 0 && shift < 26)) errors.push(`${p.id} : décalage ${shift} hors de 1..25`);
// Si un message de résolution cite le texte clair, il doit correspondre au déchiffrement.
const decoded = normalize(caesarDecode(params.ciphertext as string, shift));
const quoted = p.onSolve.flatMap((a) => ('message' in a && a.message.includes('«') ? [normalize(a.message)] : []));
quoted.forEach((q) => q === decoded || errors.push(`${p.id} : le texte déchiffré « ${decoded} » ne correspond pas au message « ${q} »`));
} else {
errors.push(`${p.id} : type de mini-jeu "${p.type}" sans contrôle dans tests/scenarios.test.ts`);
}
return errors;
}
const scenarios = listScenarios();
it('au moins un chapitre est présent', () => {
expect(scenarios.length).toBeGreaterThan(0);
});
for (const entry of scenarios) {
describe(`chapitre « ${entry.folder} »`, () => {
it('références valides', () => {
expect(entry.errors).toEqual([]);
});
it('cohérence logique', () => {
expect(analyzeScenario(entry.scenario)).toEqual([]);
});
it('paramètres des mini-jeux', () => {
expect(entry.scenario.puzzles.flatMap(checkPuzzle)).toEqual([]);
});
it('la solution de référence mène à la victoire', () => {
const wt = walkthroughs[`../src/scenarios/${entry.folder}/walkthrough.json`];
expect(wt, `walkthrough.json manquant pour ${entry.folder}`).toBeDefined();
const result = runWalkthrough(entry.scenario, wt);
expect(result.error).toBeUndefined();
expect(result.state.won).toBe(true);
});
});
}

189
tests/smoke.cjs Normal file
View File

@ -0,0 +1,189 @@
#!/usr/bin/env node
/**
* Smoke test navigateur : rejoue la solution de référence (walkthrough.json)
* avec de VRAIS clics dans le jeu 3D construit (dist/index.html), en mode test
* (?test=1 : transitions instantanées, basse qualité).
*
* Il vérifie ce que les tests de logique ne voient pas : objets 3D introuvables,
* zones masquées ou impossibles à cliquer, erreurs console, écran de victoire.
*
* npm run smoke tous les chapitres
* npm run smoke -- --chapter chapitre1 --shots --hard
*
* Options : --chapter <dossier> --shots (captures dans tests/shots/)
* --hard (mode Difficile) --headed (fenêtre visible) --timeout <ms>
*
* Prérequis : Playwright (npm i -D playwright && npx playwright install chromium),
* ou un Playwright installé globalement.
*/
const fs = require('node:fs');
const path = require('node:path');
const { execSync } = require('node:child_process');
function loadPlaywright() {
try {
return require('playwright');
} catch {
try {
const globalRoot = execSync('npm root -g', { encoding: 'utf8' }).trim();
return require(path.join(globalRoot, 'playwright'));
} catch {
console.error('Playwright introuvable. Installez-le : npm i -D playwright && npx playwright install chromium');
process.exit(2);
}
}
}
const args = process.argv.slice(2);
const opt = (name) => args.includes(`--${name}`);
const val = (name, def) => {
const i = args.indexOf(`--${name}`);
return i >= 0 ? args[i + 1] : def;
};
const ROOT = path.resolve(__dirname, '..');
const DIST = path.join(ROOT, 'dist', 'index.html');
const SHOTS = path.join(ROOT, 'tests', 'shots');
const TIMEOUT = Number(val('timeout', 20000));
const difficulty = opt('hard') ? 'hard' : 'easy';
if (!fs.existsSync(DIST)) {
console.error('dist/index.html absent : lancez d’abord « npm run build ».');
process.exit(2);
}
const chapters = fs
.readdirSync(path.join(ROOT, 'src', 'scenarios'))
.filter((d) => fs.existsSync(path.join(ROOT, 'src', 'scenarios', d, 'walkthrough.json')))
.filter((d) => !val('chapter') || d === val('chapter'));
/** Évalue une attente du walkthrough sur l'état de partie (même syntaxe que les conditions). */
function check(state, c) {
if (c === 'won') return state.won;
if (c.startsWith('scene:')) return state.scene === c.slice(6);
const neg = c.startsWith('!');
const raw = neg ? c.slice(1) : c;
const [kind, rest] = [raw.slice(0, raw.indexOf(':')), raw.slice(raw.indexOf(':') + 1)];
let ok;
if (kind === 'flag') ok = !!state.flags[rest];
else if (kind === 'item') ok = state.inventory.includes(rest);
else if (kind === 'selected') ok = state.selected === rest;
else if (kind === 'solved') ok = !!state.solved[rest];
else if (kind === 'var') {
const m = /^([\w-]+)(=|!=|>=|<=|>|<)(-?[\d.]+)$/.exec(rest);
const v = state.vars[m[1]] ?? 0;
const n = Number(m[3]);
ok = { '=': v === n, '!=': v !== n, '>=': v >= n, '<=': v <= n, '>': v > n, '<': v < n }[m[2]];
}
return neg ? !ok : ok;
}
(async () => {
const { chromium } = loadPlaywright();
const browser = await chromium.launch({
headless: !opt('headed'),
// Permet le rendu WebGL logiciel sur les machines sans GPU (serveurs, CI).
args: ['--enable-unsafe-swiftshader', '--ignore-gpu-blocklist'],
});
let failed = false;
for (const chapter of chapters) {
const wt = JSON.parse(fs.readFileSync(path.join(ROOT, 'src', 'scenarios', chapter, 'walkthrough.json'), 'utf8'));
const page = await browser.newPage({ viewport: { width: 960, height: 600 } });
page.setDefaultTimeout(TIMEOUT);
const problems = [];
// Les messages de performance du pilote GL (rendu logiciel, captures) ne sont pas des bugs du jeu.
const ignored = /GL Driver Message|GPU stall/;
page.on('console', (m) => ['error', 'warning'].includes(m.type()) && !ignored.test(m.text()) && problems.push(`console ${m.type()} : ${m.text()}`));
page.on('pageerror', (e) => problems.push(`erreur JS : ${e.message}`));
const t0 = Date.now();
console.log(`\n▶ ${chapter} (${wt.steps.length} étapes, mode ${difficulty})`);
const state = () => page.evaluate(() => window.__escape.engine.state);
const idle = async () => {
await page.waitForFunction(() => window.__escape && !window.__escape.renderer.busy, null, { polling: 100 });
await page.waitForTimeout(80);
};
const shot = async (name) => {
if (!opt('shots')) return;
fs.mkdirSync(SHOTS, { recursive: true });
await page.screenshot({ path: path.join(SHOTS, `${chapter}-${name}.png`) });
};
const clickZone = async (id) => {
if (id.startsWith('__')) return page.click(`[data-id="${id}"]`);
const pt = await page.evaluate((h) => window.__escape.renderer.clickablePointFor(h), id);
if (!pt) {
// Zone écran (rect) éventuelle
const rect = await page.$(`.hotspot[data-id="${id}"]`);
if (rect) return rect.click();
const s = await state();
throw new Error(`zone "${id}" introuvable ou impossible à cliquer dans la scène "${s.scene}" (objet masqué, hors champ ou zone inactive)`);
}
await page.mouse.move(pt.x, pt.y);
await page.mouse.click(pt.x, pt.y);
};
const slot = (item) => page.click(`.slot[data-item="${item}"]`);
try {
await page.goto(`file://${DIST}?test=1`);
await page.click(`.chapter[data-chapter="${chapter}"] button[data-difficulty="${difficulty}"]`);
await idle();
await shot('00-depart');
for (const [i, step] of wt.steps.entries()) {
const label = `étape ${String(i + 1).padStart(2)} ${JSON.stringify(step)}`;
try {
const sceneBefore = (await state()).scene;
if ('click' in step) {
for (let k = 0; k < (step.times ?? 1); k++) {
await clickZone(step.click);
await idle();
}
} else if ('use' in step) {
await slot(step.use);
await clickZone(step.on);
} else if ('combine' in step) {
await slot(step.combine[0]);
await slot(step.combine[1]);
} else if ('solve' in step) {
const def = await page.evaluate((id) => window.__escape.engine.scenario.puzzles.find((p) => p.id === id), step.solve);
if (def.type === 'colorCode') {
const ids = def.params.colors.map((c) => c.id);
for (const [slotIdx, colorId] of def.params.solution.entries())
for (let k = 0; k <= ids.indexOf(colorId); k++) await page.click(`.cc-button[data-slot="${slotIdx}"]`);
await page.click('.cc-validate');
} else if (def.type === 'caesar') {
for (let k = 0; k < def.params.shift; k++) await page.click('.cz-next');
} else {
throw new Error(`type de mini-jeu "${def.type}" non géré par tests/smoke.cjs`);
}
await page.waitForFunction((id) => window.__escape.engine.state.solved[id], step.solve);
await page.waitForSelector('.puzzle-overlay', { state: 'detached' });
}
await idle();
const s = await state();
for (const c of step.expect ?? []) if (!check(s, c)) throw new Error(`attendu "${c}" non vérifié (scène ${s.scene}, inventaire [${s.inventory.join(', ')}])`);
if (s.scene !== sceneBefore) await shot(`${String(i + 1).padStart(2, '0')}-${s.scene}`);
console.log(` ✓ ${label}`);
} catch (e) {
throw new Error(`${label}\n → ${e.message.split('\n')[0]}`);
}
}
await page.waitForSelector('.screen.win', { timeout: 5000 });
await shot('99-victoire');
if (problems.length) throw new Error(`problèmes détectés pendant la partie :\n ${problems.join('\n ')}`);
console.log(`✔ ${chapter} : victoire en ${((Date.now() - t0) / 1000).toFixed(1)} s`);
} catch (e) {
failed = true;
fs.mkdirSync(SHOTS, { recursive: true });
const file = path.join(SHOTS, `${chapter}-ECHEC.png`);
await page.screenshot({ path: file }).catch(() => undefined);
console.error(`✘ ${chapter} : ${e.message}`);
if (problems.length) console.error(` ${problems.join('\n ')}`);
console.error(` capture : ${path.relative(ROOT, file)}`);
}
await page.close();
}
await browser.close();
process.exit(failed ? 1 : 0);
})();

16
tsconfig.json Normal file
View File

@ -0,0 +1,16 @@
{
"compilerOptions": {
"target": "ES2022",
"module": "ESNext",
"moduleResolution": "Bundler",
"lib": ["ES2022", "DOM", "DOM.Iterable"],
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"resolveJsonModule": true,
"isolatedModules": true,
"skipLibCheck": true,
"types": ["vite/client"]
},
"include": ["src", "tests", "vitest.config.ts"]
}

12
vite.config.ts Normal file
View File

@ -0,0 +1,12 @@
import { defineConfig } from 'vite';
import { viteSingleFile } from 'vite-plugin-singlefile';
// Le build produit un unique dist/index.html (JS, CSS et images inlinés) :
// jouable en double-cliquant dessus, sans serveur.
export default defineConfig({
base: './',
plugins: [viteSingleFile()],
build: {
assetsInlineLimit: Number.MAX_SAFE_INTEGER,
},
});

9
vitest.config.ts Normal file
View File

@ -0,0 +1,9 @@
import { defineConfig } from 'vitest/config';
// Tests de logique : moteur + scénarios, sans navigateur ni 3D (quelques millisecondes).
export default defineConfig({
test: {
include: ['tests/**/*.test.ts'],
environment: 'node',
},
});