24 Commits

Author SHA1 Message Date
Tom Boullay 5968f0f67c fix(repair-ebike): gate scanning on scan intro dialogue
🔍 Lint / 🪄 Check lint (push) Has been cancelled
🔍 Lint / 🎨 Check format (push) Has been cancelled
🔍 Lint / 🔎 Typecheck (push) Has been cancelled
📊 Quality / 🔒 Security Audit (push) Has been cancelled
📊 Quality / 📋 Dependency Freshness (push) Has been cancelled
📊 Quality / 📦 Bundle Size (push) Has been cancelled
🔍 Lint / 🏗 Build (push) Has been cancelled
2026-06-03 07:04:44 +02:00
Tom Boullay a0482aa04b fix(repair-ebike): freeze repair transform and case-driven cooling swap 2026-06-03 07:00:16 +02:00
Tom Boullay 08c10acd48 fix(repair-ebike): stop subtitle leak and fake cooling swap
🔍 Lint / 🪄 Check lint (push) Has been cancelled
🔍 Lint / 🎨 Check format (push) Has been cancelled
🔍 Lint / 🔎 Typecheck (push) Has been cancelled
📊 Quality / 🔒 Security Audit (push) Has been cancelled
📊 Quality / 📋 Dependency Freshness (push) Has been cancelled
📊 Quality / 📦 Bundle Size (push) Has been cancelled
🔍 Lint / 🏗 Build (push) Has been cancelled
2026-06-03 06:47:10 +02:00
Tom Boullay 8d66391fa9 fix(repair-ebike): preserve bike position, unblock scan and reassembly 2026-06-03 06:34:18 +02:00
Tom Boullay 0ab5380b1e docs(repair): document unified ExplodableModel + simplified ebike flow
Update repair-game.md to reflect the recent flow refactor:
- single ExplodableModel mounted across fragmented -> done
- splitSpeed for slower, more deliberate explosion
- ebike repairing simplified to a single 'Changez le refroidisseur' trigger
- ebike done auto-completes on narrateur_ebikerepare's ended event
- narrator ownership table clarified (narrator vs scan sequence vs repair game)
2026-06-03 06:23:36 +02:00
Tom Boullay 5a6596b755 refactor(repair): unify exploded model across phases, simplify ebike flow
- RepairGame: lift a single ExplodableModel mounted across fragmented
  -> done so the model loads once, animates from its real original
  positions, and never re-instantiates between phases. Eliminates the
  position/rotation jumps and re-explosion that occurred when each
  step instantiated its own model.
- ExplodableModel: expose splitSpeed prop so the explode/reassemble
  lerp can be slowed down (REPAIR_FRAGMENT_SPLIT_SPEED = 1.8) for a
  more deliberate visual where each node is seen leaving its origin.
- RepairScanSequence: drop its own ExplodableModel, receive parts
  from the upstream shared instance. Logs the available part names
  when broken-part nodes can't be matched so config drift is visible.
- RepairReassemblyStep: reduced to the completion particles + a
  delayed onSettled callback. The collapse animation is now driven by
  the shared ExplodableModel switching split=false at the reassembling
  phase. After REPAIR_REASSEMBLY_HOLD_MS (1500ms) the upstream flow
  auto-advances to done.
- RepairEbikeRepairTrigger: new minimal interactable for the ebike
  repairing step. Replaces the heavier grabbable-parts UX (cercles,
  ranger pieces) with a single 'Changez le refroidisseur' prompt that
  advances directly to reassembling. Pylon/farm keep RepairRepairingStep.
- RepairCompletionStep: drop the duplicated RepairObjectModel; the
  shared ExplodableModel renders the repaired model at done.
- RepairGame ebike-done: play narrateur_ebikerepare and call
  completeMission on the audio's ended event (with REPAIR_DONE_DIALOGUE_FALLBACK_MS
  fallback). Hands off to pylon without a Validate button.
- EbikeRepairNarrator: drop the done entry; RepairGame owns it now so
  the audio's end event can drive the mission completion handoff.
- RepairGame: drop the window.ebikeParkedPosition livePosition logic.
  Ebike movement is disabled during the repair flow so the static zone
  position is the source of truth, fixing the floating-bike issue
  observed in TestMap.
2026-06-03 06:21:29 +02:00
Tom Boullay 9841b14388 feat(repair): per-node scan voicelines, refroidisseur diagnostic gates scanning -> repairing
The ebike refroidisseur diagnostic line used to fire on the
'repairing' step via EbikeRepairNarrator, AFTER the scan sequence had
already raced through every part on a fixed timer. Visually the red
broken-part highlight appeared and disappeared before the player ever
heard which part was actually broken.

Now the scan sequence itself can carry per-node voice lines via a new
optional config field on each broken part. When the scan lands on a
part that has a voice line:
- the audio is played immediately (with its subtitle);
- the red broken-part highlight is on screen the entire time
  (existing cumulative highlight behaviour from RepairScanSequence);
- the next-part advance is gated on the audio's  event;
- a 15s ceiling fallback (and per-part fallback when manifest is
  missing) keeps the flow from stalling if the audio never resolves.

Cancel paths (component unmount, mission switch, debug rewind) pause
the audio, clear the subtitle, and drop both the  listener and
the fallback timer to avoid leaks or double-advances.

Changes:
- types/repairMission: new optional .
- data/repairMissions: ebike refroidisseur broken part now declares
  .
- RepairScanSequence: per-part effect now branches on .
  Default per-part timer is preserved for parts without an audio line
  (incl. all pylon/farm broken parts and ebike's non-diagnostic parts).
- EbikeRepairNarrator: drop the 'repairing' entry from the step ->
  dialogue map (the diagnostic now plays earlier, during scanning).
  'fragmented' (scan hint) and 'done' (repaired voiceover) are
  unchanged.

End result: player hears 'le refroidisseur a laché...' exactly while
the red sphere is pulsing on the cooling node, and the case opens for
the repairing step the moment the line ends.
2026-06-03 04:20:14 +02:00
Tom Boullay 317db48bcc feat(repair): make fragmented -> scanning event-driven via onSplitSettled
The fragmented -> scanning transition used to fire on a blind
setTimeout of REPAIR_FRAGMENTATION_SEQUENCE_SECONDS regardless of
whether the explode lerp had actually finished. With the new sphere-
reveal flow this got out of sync (sphere grows for 2.5s before
fragmented even mounts), so the timer could fire too early or while
the parts were still flying out.

Now the ExplodedModel emits a single 'settled' callback when its
internal lerp converges on its target (1 = fully exploded, 0 = fully
reassembled). RepairGame listens for settled-at-1 on the fragmented
ExplodableModel and advances to scanning on that event.

The legacy timer is kept as a generous safety net
(REPAIR_FRAGMENTATION_SEQUENCE_SECONDS + 2 seconds) so that if the
model fails to load (no parts -> no settled event ever fires) the
flow can never get stuck on the fragmented step.

Changes:
- ExplodedModel.ts:
  - new ExplodedModelOptions.onSettled: (settledAt: 0 | 1) => void
  - track settledAtTarget to ensure the callback fires exactly once
    per lerp (re-armed when setSplit() flips the target).
- ExplodableModel.tsx: new onSplitSettled prop, forwarded to the
  underlying ExplodedModel via a stable useCallback that reads the
  latest prop through a ref so the instance is not recreated mid-anim.
- RepairGame.tsx:
  - wire onSplitSettled on the fragmented ExplodableModel to
    setMissionStep(mission, 'scanning').
  - keep the existing setTimeout but extend it as a fallback only.

Pylon and farm benefit from the same fix automatically since they
share the same RepairGame fragmented branch.
2026-06-03 04:18:10 +02:00
Tom Boullay fe30596a5a feat(ebike): auto-advance inspected -> fragmented after sphere reveal
The ebike repair flow used to require the player to press E twice in
'inspected' to trigger fragmentation, which:
- duplicated the entry interaction (waiting->inspected was already E)
- gave no visual confirmation that the inspect step did anything
- left the dark focus bubble hidden until *after* the explode happened

Now the bubble's GSAP grow tween (expo.out, 2.5s) starts as soon as the
mission enters 'inspected', visually engulfing the parked bike inside
its dark cocoon before the explode animation kicks in. After the tween
finishes the mission auto-advances to 'fragmented', which mounts the
ExplodableModel at the same parked world position.

Changes:
- RepairFocusBubble: export BUBBLE_GROW_DURATION_SECONDS so the timer
  in RepairGame stays in sync with the actual tween duration.
- RepairGame.shouldFocusBubbleBeActive(step, mission): ebike opens the
  bubble one phase earlier ('inspected'); pylon/farm keep their
  original 'fragmented'+ behaviour to avoid changing their UX.
- RepairGame: add a setTimeout(BUBBLE_GROW_DURATION_SECONDS * 1000)
  scoped to ebike + 'inspected' that calls setMissionStep('fragmented').
- RepairGame: hide the RepairMissionCase + 'press to fragment' prompt
  during ebike's 'inspected' phase (auto-flow doesn't need them).
  Pylon/farm still see the case + prompt during their 'inspected'.
- Ebike.handleInteract: drop the manual 'inspected -> fragmented'
  press-E branch (now dead). The 'waiting -> inspected' E entry is
  preserved as the single mission entry trigger.

useRepairFragmentationInput stays wired for pylon/farm (and as a
both-fists short-circuit for ebike) since its keyboardEnabled is false
and it can only fire on a deliberate gesture during 'inspected'.
2026-06-03 04:14:54 +02:00
Tom Boullay acdcb5515b refactor(ebike): drop redundant 'locked' substate, single entry trigger
The ebike mission previously had two redundant entry-point sub-states
('locked' and 'waiting') that were behaviorally identical from the
player's perspective:
- both showed the same 'Lancer le Repair Game' prompt
- both allowed the press-E handler in Ebike.tsx to jump to 'inspected'

In addition, the locked state caused two latent bugs:
- the static-map ebike node (GameMap) and the live <Ebike> component
  were rendered simultaneously at the same world position
- a generic RepairMissionTrigger anchor sphere was rendered in
  parallel to Ebike's own InteractableObject (two triggers, same area)

Changes:
- useGameStore: ebike's initial currentStep + completeIntroState target
  is now 'waiting' (pylon/farm still init at 'locked' — they need it).
- Ebike.tsx: drop dead === 'locked' branches in repairGameOwnsEbikeModel
  and the press-E handler.
- EbikeRepairNarrator: only reset the played-set on 'waiting'.
- RepairGame: drop 'locked' from the ebike livePosition guard.
- REPAIR_MISSION_TRIGGERS: empty array (the duplicate ebike anchor
  sphere is gone). Keep the array + RepairMissionTrigger component for
  future re-use.
- GameMap: hide the static-map ebike node as soon as
  mainState === 'ebike' (was: only when ebikeStep !== 'locked').
- repairMissionState.getPreviousMissionStep: ebike rewinds from
  'waiting' to 'waiting' (cap), pylon to 'npc-return', farm to 'locked'.

The 'locked' value is intentionally kept in the MissionStep type union
because the farm mission still uses it as a meaningful kickoff state
driving FarmNarrativeFlow's auto-transition to electricienne_history.
2026-06-03 04:02:32 +02:00
Tom Boullay 5ad2e27a89 fix(ui): scope hand-tracking activation + clean MissionNotification video branch
- HandTrackingProvider: drop the physics-mode auto-activation that turned
  the camera/MediaPipe pipeline on whenever any interactable was nearby
  (e.g. walking near the ebike to mount it). Hand tracking is now gated
  *only* by the active repair-mission step (inspected, repairing,
  reassembling, done). When testing in TestMap, set
  mainState=ebike + currentStep=inspected via the GameStateDebugPanel.
- MissionNotification: video branch no longer inherits the CRT-style
  enter/scan/flicker/sepia animations applied to the PNG branch via
  index.css. The webm assets already animate themselves, so the wrapping
  container is rendered with inline styles only (clip-path silhouette
  preserved, but no .__image-wrap::before scan line, no .__image flicker
  filter, no parent enter animation, no drop-shadow).
2026-06-03 03:44:04 +02:00
Tom Boullay 7bcbba4eb1 fix(ui): polish demo-flow overlays
🔍 Lint / 🪄 Check lint (push) Has been cancelled
🔍 Lint / 🎨 Check format (push) Has been cancelled
🔍 Lint / 🔎 Typecheck (push) Has been cancelled
📊 Quality / 🔒 Security Audit (push) Has been cancelled
📊 Quality / 📋 Dependency Freshness (push) Has been cancelled
📊 Quality / 📦 Bundle Size (push) Has been cancelled
🔍 Lint / 🏗 Build (push) Has been cancelled
- OutroVideoOverlay: stagger reveal so 'Next step :' appears immediately and
  'La ferme' fades in 500ms later, instead of both showing at once.
- MissionNotification: enforce 589/211 aspect-ratio + objectFit cover on the
  <video> branch so webm assets (square 2000x2000) render at the same place
  as the legacy PNG notifications instead of shifting the layout.
- HandTrackingTutorial: add a 5000ms fallback timeout that auto-dismisses
  the overlay if MediaPipe never reports a hand (camera blocked, mouse-only
  player), so the screen never stays stuck.
2026-06-03 03:27:18 +02:00
Tom Boullay 712fb851ad feat(outro): add fade-to-black transition screen with 'Next step: La ferme' before outro video, mute all game audio during playback 2026-06-03 03:08:12 +02:00
Tom Boullay d8b916d31f fix(types): satisfy strict tsc for production build (deploy unblock)
🔍 Lint / 🪄 Check lint (push) Has been cancelled
🔍 Lint / 🎨 Check format (push) Has been cancelled
🔍 Lint / 🔎 Typecheck (push) Has been cancelled
📊 Quality / 🔒 Security Audit (push) Has been cancelled
📊 Quality / 📋 Dependency Freshness (push) Has been cancelled
📊 Quality / 📦 Bundle Size (push) Has been cancelled
🔍 Lint / 🏗 Build (push) Has been cancelled
2026-06-03 02:40:54 +02:00
Tom Boullay e9808f8473 fix(ebike): force-stop narrator audio + clear subtitle when leaving ebike state 2026-06-03 02:35:37 +02:00
Tom Boullay 0ddecaa494 fix(ebike): pause repair narrator audio when leaving ebike main state 2026-06-03 02:28:12 +02:00
Tom Boullay 6c36440016 update: srt 2026-06-03 02:25:20 +02:00
Tom Boullay f20c6b9961 docs(repair-game): document ebike narrator cues 2026-06-03 02:12:19 +02:00
Tom Boullay 47b69b01d2 feat(ebike): play narrator cues during repair flow (scan hint, diagnostic, completion) 2026-06-03 02:11:45 +02:00
Tom Boullay 8b0dd31014 Update SiteNamingScreen.tsx 2026-06-03 02:11:15 +02:00
Tom Boullay 171af683f5 feat(dialogues): split ebike repair narration into diagnostic and completion cues 2026-06-03 02:09:57 +02:00
Tom Boullay f820bee64f Merge branch 'develop' of https://git.fabrik.mathieu-chavanel.fr/math-pixel/La-Fabrik into develop
🔍 Lint / 🪄 Check lint (push) Has been cancelled
🔍 Lint / 🎨 Check format (push) Has been cancelled
🔍 Lint / 🔎 Typecheck (push) Has been cancelled
📊 Quality / 🔒 Security Audit (push) Has been cancelled
📊 Quality / 📋 Dependency Freshness (push) Has been cancelled
📊 Quality / 📦 Bundle Size (push) Has been cancelled
🔍 Lint / 🏗 Build (push) Has been cancelled
2026-06-03 02:05:29 +02:00
math-pixel 1538ef93a5 Merge pull request 'Feat/polish-mission2' (#14) from feat/polish-mission-2 into develop
🔍 Lint / 🪄 Check lint (push) Has been cancelled
🔍 Lint / 🎨 Check format (push) Has been cancelled
🔍 Lint / 🔎 Typecheck (push) Has been cancelled
📊 Quality / 🔒 Security Audit (push) Has been cancelled
📊 Quality / 📋 Dependency Freshness (push) Has been cancelled
📊 Quality / 📦 Bundle Size (push) Has been cancelled
🔍 Lint / 🏗 Build (push) Has been cancelled
Reviewed-on: #14
2026-06-03 00:03:54 +00:00
Tom Boullay 96be49d358 fix(missions): point notifications to existing webm assets 2026-06-03 02:02:10 +02:00
41 changed files with 1206 additions and 291 deletions
+42 -41
View File
@@ -163,23 +163,20 @@ Both paths move to `fragmented`.
### Fragmented
File:
Files:
```txt
src/components/three/models/ExplodableModel.tsx
src/utils/three/ExplodedModel.ts
```
The mission object is shown split apart. A timer then moves the mission to `scanning`.
The mission object is shown split apart. `RepairGame` mounts a **single** `ExplodableModel` instance for the entire repair flow (`fragmented` -> `done`) so the model loads once, animates from its real authored positions, and is never re-instantiated when the player advances to scanning, repairing, reassembling or done. This eliminates the visible position/rotation jumps and re-explosion that occurred when each step instantiated its own model.
`ExplodedModel.createParts` walks the GLTF tree recursively, descending through any single mesh-bearing wrapper node (e.g. `Scene > Moto > Eclatement` for the Ebike) until it reaches a node with multiple mesh-bearing children. Those children are the natural "explosion groups" authored by the modeler. This avoids exploding raw leaf meshes in local space when the model has extra empty wrapper nodes above the intended group.
When mounted, `RepairGame` applies `RepairMissionConfig.modelRotation` and `modelScale` to the fragmented model so it lines up with the source inspection model in world space (e.g. the parked Ebike using `EBIKE_WORLD_ROTATION_Y` / `EBIKE_WORLD_SCALE`).
When mounted, `RepairGame` applies `RepairMissionConfig.modelRotation` and `modelScale` to the shared model so it lines up with the source inspection model in world space (e.g. the parked Ebike using `EBIKE_WORLD_ROTATION_Y` / `EBIKE_WORLD_SCALE`). The explode/reassemble lerp speed is configurable via `splitSpeed` (default `REPAIR_FRAGMENT_SPLIT_SPEED = 1.8`, ~1.5s) so each node is clearly seen leaving its origin.
The default delay comes from:
```txt
REPAIR_FRAGMENTATION_SEQUENCE_SECONDS
```
Transition out is event-driven: the model fires `onSplitSettled(1)` when the lerp converges and `RepairGame` advances to `scanning`. A `REPAIR_FRAGMENTATION_SEQUENCE_SECONDS + 2` fallback timer guards against load failures.
### Scanning
@@ -189,50 +186,33 @@ File:
src/components/three/gameplay/RepairScanSequence.tsx
```
The scan sequence:
The scan sequence is now stateless w.r.t. the model: it receives `parts: ExplodedPart[]` from the upstream shared `ExplodableModel` and:
- keeps the exploded model visible
- receives model parts from `ExplodableModel`
- advances an active part index over time
- renders `RepairScanVisual` on the active part
- reveals broken-part highlights when configured broken parts have been reached
- reveals broken-part highlights cumulatively as scan progresses
- when the active part has a `voiceLineId`, gates the advance on the audio's `ended` event (with a 15s ceiling fallback) so the diagnostic line plays in full
- returns `RepairScannedBrokenPart[]` when done
Broken-part lookup first tries `brokenParts[].nodeName`. If no configured node matches, it falls back to the first available exploded parts. This fallback is useful while GLTF node names are still unstable, but precise `nodeName` config is safer for production.
Broken-part lookup uses `brokenParts[].nodeName` against the exploded parts (deep traverse). When a configured node can't be matched, the available part names are logged so config drift is visible in the console.
### Repairing
File:
For pylon/farm:
```txt
src/components/three/gameplay/RepairRepairingStep.tsx
```
This is the densest gameplay step.
This is the densest gameplay step. It renders install target, placeholder markers, grabbable replacement parts, grabbable broken parts to store, placement feedback and a ready-to-install prompt. Validation requires the correct replacement part placed AND every scanned broken part deposited.
It renders:
- install target
- placeholder markers
- grabbable replacement parts
- grabbable broken parts to store
- placement feedback
- ready-to-install prompt
Important local state:
- `placedPartIds`: replacement parts that snapped near a placeholder
- `depositedBrokenPartIds`: broken parts stored in the case
- `showBlockedInstallFeedback`: temporary visual feedback when install is attempted too early
Validation:
For ebike (mission 1, simplified):
```txt
correct replacement part placed
AND every scanned broken part deposited
src/components/three/gameplay/RepairEbikeRepairTrigger.tsx
```
Only then does the install target call `onRepair()` and move to `reassembling`.
Replaces the heavier grabbable UX with a single "Changez le refroidisseur" prompt. Pressing E advances directly to `reassembling`. The cercles décoratifs and grabbable parts are omitted to keep the first repair experience low-friction.
### Reassembling
@@ -242,23 +222,24 @@ File:
src/components/three/gameplay/RepairReassemblyStep.tsx
```
The exploded model animates back into assembled form and completion particles play. A timer then moves the mission to `done`.
The shared `ExplodableModel` flips `split=false`, animating each node back to its original position (inverse of fragmented). `RepairReassemblyStep` itself is now reduced to:
Mission configs can override the default reassembly duration.
- the completion particles
- a `delayMs` timer (`REPAIR_REASSEMBLY_HOLD_MS = 1500`) that fires `onSettled` so `RepairGame` auto-advances to `done`
### Done
File:
For pylon/farm:
```txt
src/components/three/gameplay/RepairCompletionStep.tsx
```
The repaired object remains visible. The player validates the completion target, then:
The shared exploded model (now reassembled) remains visible. The player validates a green completion target, the case closes and exits, then `completeMission(mission)` advances the global game progression.
1. the repair case closes
2. the case plays its exit animation
3. `completeMission(mission)` advances the global game progression
For ebike (mission 1, auto-complete):
`RepairGame` plays `narrateur_ebikerepare` directly on entry to `done`. When the audio's `ended` event fires (with `REPAIR_DONE_DIALOGUE_FALLBACK_MS = 6000` fallback) `completeMission("ebike")` is called automatically and the world hands off to the pylon mission. The bubble shrinks via `shouldFocusBubbleBeActive(done) === false`. No Validate button is shown.
## Focus Bubble
@@ -275,6 +256,26 @@ While the player is in `fragmented`, `scanning`, `repairing` or `reassembling`,
The bubble is mounted both in `GameStageContent` (production scene) and `TestMap` (physics test scene) so the behaviour matches in both contexts.
## Narrator Audio (Ebike Mission)
`EbikeRepairNarrator` (`src/components/game/EbikeRepairNarrator.tsx`) is a headless component mounted in `src/pages/page.tsx` next to `EbikeIntroSequence`. It subscribes to `useGameStore` and plays one-shot narrator cues at specific repair-step transitions for the `ebike` mission only:
| Step entered | Dialogue ID | Audio file | Subtitle | Owner |
| ------------ | ------------------------------------ | ---------------------------------- | -------- | ---------------------- |
| `fragmented` | `narrateur_galetscan` | `narrateur_galetscan.mp3` | cue 6 | `EbikeRepairNarrator` |
| `scanning` | `narrateur_refroidisseur_diagnostic` | `narrateur_refroidisseurcassé.mp3` | cue 24 | `RepairScanSequence`\* |
| `done` | `narrateur_ebikerepare` | `narrateur_ebikeréparé.mp3` | cue 7 | `RepairGame`\*\* |
\* The diagnostic line is triggered by the scan sequence when it lands on the broken part configured with `voiceLineId` (refroidisseur for ebike). The advance to `repairing` is gated on the audio's `ended` event so the line plays in full with the red highlight on screen.
\*\* `RepairGame` plays the success line directly on entering `done` so the audio's `ended` event can drive `completeMission` and hand off to pylon. A `REPAIR_DONE_DIALOGUE_FALLBACK_MS` timer guards against load failures. `EbikeRepairNarrator` no longer owns this cue.
A `useRef<Set<MissionStep>>` guards against double-fires (StrictMode, re-renders) and is cleared when the mission rolls back to `locked` or `waiting`, so debug-panel replays still trigger the narration.
Cue 7 was previously a single subtitle covering both the diagnostic line and the "Eeeet voilà!" completion line. It was split into cue 7 (completion only) and a new cue 24 (diagnostic) so the two sentences can be triggered at independent moments — they correspond to two distinct `.mp3` files.
The breakdown line (`narrateur_ebikecasse`, cue 5) is still triggered by `EbikeIntroSequence` at distance threshold, not by this component. Pylon and farm narrator cues are not yet wired through `EbikeRepairNarrator`; the same per-mission lookup pattern can be extended when those flows need narration.
## Repair Case Details
The case model implementation lives in:
+6
View File
@@ -69,6 +69,12 @@
"audio": "/sounds/dialogue/narrateur_ebikeréparé.mp3",
"subtitleCueIndex": 7
},
{
"id": "narrateur_refroidisseur_diagnostic",
"voice": "narrateur",
"audio": "/sounds/dialogue/narrateur_refroidisseurcassé.mp3",
"subtitleCueIndex": 24
},
{
"id": "narrateur_ordredemandedelaide",
"voice": "narrateur",
@@ -24,7 +24,7 @@ So? Pretty amazing, right? Anyway, these rollers will scan the components to fin
7
00:00:00,000 --> 00:00:04,992
Perfect! The cooler gave out, you can replace it with one of the components from your pack. Aaaand there we go! It runs like clockwork! Go on, hurry!
Aaaand there we go! It runs like clockwork! Go on, hurry!
8
00:00:00,000 --> 00:00:04,512
@@ -90,6 +90,10 @@ Here, this is a dashboard. You can imagine that if your fridge or oven breaks do
00:00:00,000 --> 00:00:07,500
The electrician helped you at the Power Plant? Aaaaah, that's what I love here: everyone helps each other, nobody judges anyone, it's like a real little family.
24
00:00:00,000 --> 00:00:05,500
Perfect! The cooler gave out, you can replace it with one of the components from your pack.
25
00:00:07,500 --> 00:00:19,100
You should know the electrician has quite a special story. She was born in the north of the continent, in the city of Kalska. She grew up happily with her mother Edith, her father Jordan, and her two little brothers, Malo and Justin.
@@ -1,6 +1,6 @@
1
00:00:00,000 --> 00:00:08,000
Hey !! Comment ça va ? Tu as besoin d'aide pour poser les galets ?
Hey !! Comment ça va ? Tu as besoin d'aide pour redresser le poteau ?
2
00:00:00,000 --> 00:00:08,000
@@ -1,6 +1,6 @@
1
00:00:00,000 --> 00:00:09,000
Bonjour à toi, futur habitant d'Altéra ! Aujourd'hui tu vas découvrir le rôle de technicien au sein de La Fabrik qui s'occupe des technologies et réparation Low-Tech.
Bonjour à toi, futur habitant d'Altéra ! Aujourd'hui tu vas découvrir le rôle de technicien au sein de La Fabrik, qui s'occupe des technologies et des réparations low-tech.
2
00:00:09,000 --> 00:00:11,592
@@ -8,7 +8,7 @@ Avant de commencer, comment tu t'appelles ?
3
00:00:00,000 --> 00:00:10,824
Très bien ! On va commencer pas à pas pour te montrer comment fonctionne l'atelier. Ensuite, tu commenceras ta journée et tu pourras te rendre compte de l'impact positif qu'a la Fabrik sur la communauté et le quartier.
Très bien ! On va avancer pas à pas pour te montrer comment fonctionne l'atelier. Ensuite, tu commenceras ta journée et tu pourras te rendre compte de l'impact positif qu'a La Fabrik sur la communauté et le quartier.
4
00:00:00,000 --> 00:00:06,072
@@ -16,7 +16,7 @@ Allez go ! Il faudrait que tu ailles à la ferme, on cherche à améliorer quelq
5
00:00:00,000 --> 00:00:12,720
Quoi ? Ton E-Bike est cassé ? Bon c'est pas très grave, ça arrive ! Utilise les deux galets qui sont sur tes gants. Ce sont de véritables bijoux technologiques. Poses en un en-dessous du vélo, et un au-dessus.
Quoi ? Ton E-Bike est cassé ? Bon, ce n'est pas très grave, ça arrive ! Utilise les deux galets qui sont sur tes gants. Ce sont de véritables bijoux technologiques. Poses-en un en dessous du vélo, et un au-dessus.
6
00:00:00,000 --> 00:00:08,064
@@ -24,7 +24,7 @@ Alors ? Pas magnifique ça ? Enfin bref, ces galets vont scanner les composants
7
00:00:00,000 --> 00:00:04,992
Parfait ! C'est le refroidisseur qui a lâché, tu peux le remplacer avec un des composants de ton pack. Eeeet voilà ! Il fonctionne comme une horloge ! Allez fonce !
Eeeet voilà ! Il fonctionne comme une horloge ! Allez fonce !
8
00:00:00,000 --> 00:00:04,512
@@ -32,7 +32,7 @@ N'hésite pas à aller demander de l'aide si tu as besoin, tout le monde est sup
9
00:00:00,000 --> 00:00:08,880
Oh woooow !! T'as vu ça ???? Tous les feux, ordinateurs et lumières se sont éteints !! Faut vite que t'aille au Centre de l'Énergie, on ne peut même plus renvoyer les appareils réparés !
Oh woooow !! T'as vu ça ???? Tous les feux, ordinateurs et lumières se sont éteints !! Il faut vite que tu ailles au Centre de l'Énergie, on ne peut même plus renvoyer les appareils réparés !
10
00:00:00,000 --> 00:00:09,840
@@ -48,7 +48,7 @@ Booon, grâce à toi j'ai pu finir mon urgence ! Oh mais t'arrives bientôt à l
13
00:00:00,000 --> 00:00:11,760
Bon, fini le moment émotion haha ! Pour la ferme, comme je te l'ai dis, ici, il faut qu'on change l'irrigation. Durant les périodes de sécheresse, les habitants se plaignent d'un souci. Vois ce que tu peux faire.
Bon, fini le moment émotion haha ! Pour la ferme, comme je te l'ai dit, ici, il faut qu'on change l'irrigation. Durant les périodes de sécheresse, les habitants se plaignent d'un souci. Vois ce que tu peux faire.
14
00:00:00,000 --> 00:00:04,560
@@ -60,7 +60,7 @@ Ouiii ! C'est ça ! On aimerait ne plus pomper l'eau dans le lac, sinon on va é
16
00:00:00,000 --> 00:00:10,944
L'ancien refroidisseur de ton E-Bike ?? Mais oui !! Hahaha, très bonne idée ! Combiné aux anciens tuyaux du lac, on va pouvoir faire quelque chose de cool ! Met tout ça entre tes pads !
L'ancien refroidisseur de ton E-Bike ?? Mais oui !! Hahaha, très bonne idée ! Combiné aux anciens tuyaux du lac, on va pouvoir faire quelque chose de cool ! Mets tout ça entre tes pads !
17
00:00:00,000 --> 00:00:05,712
@@ -68,7 +68,7 @@ Le refroidisseur de ton E-Bike est cassé, mais on peut encore en faire quelque
18
00:00:00,000 --> 00:00:10,032
Ma-gni-fique ! Je vois que Gilbert t'as aidé haha, il est adorable celui-là ! Tu as fait du super boulot ! Et grâce à toi, le quartier est amélioré.
Ma-gni-fique ! Je vois que Gilbert t'a aidé haha, il est adorable celui-là ! Tu as fait du super boulot ! Et grâce à toi, le quartier est amélioré.
19
00:00:00,000 --> 00:00:11,520
@@ -80,28 +80,32 @@ Allez bonne chance ! J'ai du boulot !
21
00:00:00,000 --> 00:00:33,600
Bienvenue dans ton atelier !! Alors ? Ça claque hein ? Bon je te présente en rapide tout ce qu'il y a : ici c'est ton plan de travail. Dans les tuyaux, ce sont des objets des résidents du quartier qui sont tombés en panne qui attendent d'être réparés. Une fois réparé, tu mets l'objet dans ce tuyau et ça repart chez la bonne personne.
Bienvenue dans ton atelier !! Alors ? Ça claque hein ? Bon, je te présente rapidement tout ce qu'il y a : ici, c'est ton plan de travail. Dans les tuyaux, ce sont des objets des résidents du quartier qui sont tombés en panne et qui attendent d'être réparés. Une fois l'objet réparé, tu le mets dans ce tuyau et ça repart chez la bonne personne.
22
00:00:00,000 --> 00:00:14,760
Ici, c'est un tableau de bord. T'imagines bien que si ton frigo ou ton four tombe en panne, tu ne vas pas pouvoir le mettre dans le tuyau haha ! Donc ici, ça te signale quand des résidents ont un objet volumineux tombé en panne, ou quand il y a un problème dans la ville. Oh oh... j'ai une urgence, il va bientôt falloir que je te laisse ! Donc tiens, tes outils pour pouvoir réparer la plupart des choses : une mini imprimante 3D à base de déchets électroniques, des gants Pousse Pièces pour désassembler les objets, ainsi qu'un pack de Relance !
Ici, c'est un tableau de bord. T'imagines bien que si ton frigo ou ton four tombe en panne, tu ne vas pas pouvoir le mettre dans le tuyau haha ! Donc ici, ça te signale quand des résidents ont un objet volumineux tombé en panne, ou quand il y a un problème dans la ville. Oh oh... j'ai une urgence, il va bientôt falloir que je te laisse ! Donc tiens, tes outils pour pouvoir réparer la plupart des choses : une mini-imprimante 3D à base de déchets électroniques, des gants Pousse-Pièces pour désassembler les objets, ainsi qu'un pack de Relance !
23
00:00:00,000 --> 00:00:07,500
L'électricienne t'a aidé à la Centrale ? Aaaaah c'est ça que j'adore ici, tout le monde s'entraide, personne se juge, une vraie petite famille.
24
00:00:00,000 --> 00:00:05,500
Parfait ! C'est le refroidisseur qui a lâché, tu peux le remplacer avec un des composants de ton pack.
25
00:00:07,500 --> 00:00:19,100
Sache que l'électricienne a une histoire assez particulière. Elle est née au nord du continent, dans la ville de Kalska. Elle a grandit heureuse, avec sa mère Edith, son père Jordan et ses deux petits frères Malo et Justin.
Sache que l'électricienne a une histoire assez particulière. Elle est née au nord du continent, dans la ville de Kalska. Elle a grandi heureuse, avec sa mère Edith, son père Jordan et ses deux petits frères Malo et Justin.
26
00:00:19,100 --> 00:00:30,600
Il y a quelques années de ça, comme tu le sais, c'est les pays du Nord, qui par grande surprise, ont été obligés de migrer en premier. Ils ont alors entamé leur périple, pays par pays, ville par ville, village par village.
Il y a quelques années de ça, comme tu le sais, ce sont les pays du Nord qui, par grande surprise, ont été obligés de migrer en premier. Ils ont alors entamé leur périple, pays par pays, ville par ville, village par village.
27
00:00:30,600 --> 00:00:42,800
Un jour de marche comme les autres depuis plusieurs mois, une tempête climatique les a pris de court. S'étant séparés pour trouver des vivres dans le village, le père et un des deux frères sont malheureusement partis. C'est tragique.
Un jour de marche comme les autres depuis plusieurs mois, une tempête climatique les a pris de court. S'étant séparés pour trouver des vivres dans le village, le père et l'un des deux frères sont malheureusement partis. C'est tragique.
28
00:00:42,800 --> 00:00:54,000
Mais un beau jour, ils sont tombés ici, par hasard dans leur périple. On les a accueillis les bras ouverts et ils ont pu se reconstruire doucement parmi nous et font partie intégrante de la communauté aujourd'hui.
Mais un beau jour, ils sont tombés ici, par hasard, dans leur périple. On les a accueillis les bras ouverts, ils ont pu se reconstruire doucement parmi nous et font partie intégrante de la communauté aujourd'hui.
+5 -9
View File
@@ -73,7 +73,6 @@ export function Ebike({
const updateEbikeSounds = useEbikeSounds();
const repairGameOwnsEbikeModel =
mainState === "ebike" &&
ebikeStep !== "locked" &&
ebikeStep !== "waiting" &&
ebikeStep !== "inspected";
@@ -362,18 +361,15 @@ export function Ebike({
if (window.ebikeBreakdownActive === true) return;
if (movementMode === "walk") {
if (
mainState === "ebike" &&
(ebikeStep === "locked" || ebikeStep === "waiting")
) {
if (mainState === "ebike" && ebikeStep === "waiting") {
setMissionStep("ebike", "inspected");
return;
}
if (mainState === "ebike" && ebikeStep === "inspected") {
setMissionStep("ebike", "fragmented");
return;
}
// Note: inspected -> fragmented is no longer driven by press-E.
// It auto-advances after the focus bubble's grow tween (see
// RepairGame, gated on BUBBLE_GROW_DURATION_SECONDS), so the
// sphere visibly engulfs the bike before the explode animation.
const cameraOffset = new THREE.Vector3(
...EBIKE_CAMERA_TRANSFORM.position,
+4 -1
View File
@@ -181,9 +181,12 @@ export const EbikeGPSMap: React.FC<EbikeGPSMapProps> = ({
// Sync texture into uniform when it changes (canvas resize)
useEffect(() => {
const mapUniform = shaderMat.uniforms.map;
if (!mapUniform) return;
// External Three.js material uniform sync — intentional side effect.
// eslint-disable-next-line react-hooks/immutability
shaderMat.uniforms.map.value = texture;
mapUniform.value = texture;
}, [shaderMat, texture]);
// Cleanup on unmount
@@ -146,16 +146,6 @@ export function EbikeIntroSequence(): React.JSX.Element | null {
return null;
}
if (mainState == "pylon") {
if (pylonStep === "approaching") {
return <MissionNotification mission="pylon" visible />;
}
if (pylonStep === "narrator-outro") {
return <MissionNotification mission="farm" visible />;
}
return null;
}
if (
introStep !== "reveal" &&
introStep !== "await-ebike-mount" &&
@@ -0,0 +1,97 @@
import { useEffect, useRef } from "react";
import { useGameStore } from "@/managers/stores/useGameStore";
import { useSubtitleStore } from "@/managers/stores/useSubtitleStore";
import type { MissionStep } from "@/types/gameplay/repairMission";
import { loadDialogueManifest } from "@/utils/dialogues/loadDialogueManifest";
import { playDialogueById } from "@/utils/dialogues/playDialogue";
/**
* Previously played the ebike repair cues directly. `RepairGame` now
* owns the repair-game cue timings that gate gameplay transitions
* (`fragmented` waits for `narrateur_galetscan`, `done` waits for
* `narrateur_ebikerepare`). This component remains as the central
* safety cleanup for legacy/queued ebike narrator audio.
*
* The `narrateur_refroidisseur_diagnostic` line is triggered by the
* scan sequence itself when it lands on the refroidisseur node
* (configured via `RepairMissionPartConfig.voiceLineId` on the broken
* part). The `narrateur_ebikerepare` line is triggered by RepairGame
* directly at the `done` step so its `ended` event can drive the
* mission completion handoff.
*
* Each cue is one-shot per mission run; the played-set resets when the
* mission state rolls back to `waiting` so debug-panel replays still
* trigger the narration.
*
* Audio AND subtitles are strictly scoped to `mainState === "ebike"`. If
* the player leaves the ebike main state mid-line (debug panel jump,
* mission transition, etc.), the active audio is paused and the
* subtitle is force-cleared so nothing bleeds into pylon/farm/outro.
*/
const STEP_TO_DIALOGUE_ID: Partial<Record<MissionStep, string>> = {};
function stopAudio(audio: HTMLAudioElement | null): void {
if (!audio) return;
if (!audio.paused) {
audio.pause();
audio.currentTime = 0;
}
}
export function EbikeRepairNarrator(): null {
const mainState = useGameStore((state) => state.mainState);
const ebikeStep = useGameStore((state) => state.ebike.currentStep);
const playedRef = useRef<Set<MissionStep>>(new Set());
const activeAudioRef = useRef<HTMLAudioElement | null>(null);
useEffect(() => {
if (ebikeStep === "waiting") {
playedRef.current.clear();
}
}, [ebikeStep]);
// Belt-and-suspenders: any time we are NOT in the ebike main state,
// make sure no narrator audio or subtitle from this component is
// lingering. This catches races where the audio started a tick before
// the main state flipped and the per-step cleanup hadn't propagated
// yet (subtitle event still queued, etc.).
useEffect(() => {
if (mainState === "ebike") return;
stopAudio(activeAudioRef.current);
activeAudioRef.current = null;
useSubtitleStore.getState().clearActiveSubtitle();
}, [mainState]);
useEffect(() => {
if (mainState !== "ebike") return;
const dialogueId = STEP_TO_DIALOGUE_ID[ebikeStep];
if (!dialogueId) return;
if (playedRef.current.has(ebikeStep)) return;
playedRef.current.add(ebikeStep);
let cancelled = false;
void (async () => {
const manifest = await loadDialogueManifest();
if (cancelled || !manifest) return;
const audio = await playDialogueById(manifest, dialogueId);
if (cancelled) {
stopAudio(audio);
useSubtitleStore.getState().clearActiveSubtitle();
return;
}
activeAudioRef.current = audio;
})();
return () => {
cancelled = true;
stopAudio(activeAudioRef.current);
activeAudioRef.current = null;
useSubtitleStore.getState().clearActiveSubtitle();
};
}, [mainState, ebikeStep]);
return null;
}
@@ -3,7 +3,8 @@ import { useGameStore } from "@/managers/stores/useGameStore";
import { useSubtitleStore } from "@/managers/stores/useSubtitleStore";
import { AudioManager } from "@/managers/AudioManager";
const HISTOIRE_AUDIO_PATH = "/sounds/dialogue/narrateur_histoireelectricienne.mp3";
const HISTOIRE_AUDIO_PATH =
"/sounds/dialogue/narrateur_histoireelectricienne.mp3";
const OUTRO_DELAY_MS = 5_000; // delay after audio ends before transitioning to outro
/**
@@ -78,9 +79,12 @@ function useHistoireSubtitlePlayback(
({ start, end }) => t >= start && t < end,
);
if (idx >= 0) {
const text = HISTOIRE_BLOCKS[idx];
if (text === undefined) return;
setActiveSubtitle({
speaker: "Narrateur",
text: HISTOIRE_BLOCKS[idx],
text,
});
}
}
@@ -136,7 +140,9 @@ export function FarmNarrativeFlow(): null {
// After the audio finishes, wait 5 s then transition to outro.
// The timeout ID is kept in a ref so we can cancel on unmount.
const outroTimeoutRef = useRef<ReturnType<typeof window.setTimeout> | null>(null);
const outroTimeoutRef = useRef<ReturnType<typeof window.setTimeout> | null>(
null,
);
useEffect(() => {
return () => {
@@ -33,7 +33,9 @@ export function PylonDownedPylon(): React.JSX.Element | null {
);
// Snap to terrain so the downed/upright model sits flush on the ground,
// matching the Y adjustment that InstancedMapAsset applies to the same node.
const position = useTerrainSnappedPosition(pylonAnchor ?? PYLON_WORLD_POSITION);
const position = useTerrainSnappedPosition(
pylonAnchor ?? PYLON_WORLD_POSITION,
);
const [isStraightening, setIsStraightening] = useState(false);
// Keeps the pylon upright after the animation completes while
// PylonFarmerNPC plays the post-raise audio sequence.
@@ -63,7 +65,9 @@ export function PylonDownedPylon(): React.JSX.Element | null {
if (!group) return;
if (!isStraightening || straightenStartRef.current === null) {
group.rotation.set(...(isRaised ? PYLON_UPRIGHT_ROTATION : PYLON_DOWNED_ROTATION));
group.rotation.set(
...(isRaised ? PYLON_UPRIGHT_ROTATION : PYLON_DOWNED_ROTATION),
);
return;
}
@@ -104,11 +108,7 @@ export function PylonDownedPylon(): React.JSX.Element | null {
if (!shouldRender) return null;
return (
<group
ref={groupRef}
position={position}
rotation={PYLON_DOWNED_ROTATION}
>
<group ref={groupRef} position={position} rotation={PYLON_DOWNED_ROTATION}>
<primitive object={scene.clone(true)} />
{isPylonInteractive ? (
<InteractableObject
@@ -159,7 +159,9 @@ function PylonFarmerNPCContent(): React.JSX.Element {
} else if (step === "done") {
// NPC reappears at repair completion — position at the post-raise spot,
// facing the pylon, playing idle.
currentPosRef.current.set(...PYLON_FARMER_NPC_AFTER_POSITION_pylone_straight);
currentPosRef.current.set(
...PYLON_FARMER_NPC_AFTER_POSITION_pylone_straight,
);
savedRotationYRef.current = faceToward(
currentPosRef.current,
PYLON_WORLD_POSITION,
@@ -28,11 +28,9 @@ export function PylonNarrativeFlow(): React.JSX.Element | null {
void (async () => {
// 1. Play the generator powerdown sound effect
const sfx = AudioManager.getInstance().playSound(
PYLON_POWERDOWN_SFX,
1,
{ category: "sfx" },
);
const sfx = AudioManager.getInstance().playSound(PYLON_POWERDOWN_SFX, 1, {
category: "sfx",
});
// 2. Wait for it to finish (or skip if it can't load)
if (sfx) {
+1 -1
View File
@@ -14,7 +14,7 @@ import {
stopCurrentDialogue,
} from "@/utils/dialogues/playDialogue";
const TYPEWRITER_CHAR_DELAY_MS = 70;
const TYPEWRITER_CHAR_DELAY_MS = 150;
// Fallback in case nothing else triggers the typewriter (audio failed to
// load, no subtitles, "ended" never fires). Long enough not to fire
// before the narration on a slow load.
@@ -1,5 +1,4 @@
import { useEffect, useState } from "react";
import { RepairObjectModel } from "@/components/three/gameplay/RepairObjectModel";
import { RepairPromptVideo } from "@/components/three/gameplay/RepairPromptVideo";
import { RepairMissionCase } from "@/components/three/gameplay/RepairMissionCase";
import { TriggerObject } from "@/components/three/interaction/TriggerObject";
@@ -40,11 +39,12 @@ export function RepairCompletionStep({
onExitComplete={onComplete}
/>
<RepairObjectModel
label={config.label}
modelPath={config.modelPath}
scale={config.modelScale ?? 1}
/>
{/*
The repaired model is now rendered by the shared ExplodableModel
in RepairGame (split=false at done) so a single instance covers
the whole repair flow. Rendering RepairObjectModel here would
duplicate the model on top of the unified one.
*/}
{!isClosingCase ? (
<TriggerObject
@@ -0,0 +1,57 @@
import { GrabbableObject } from "@/components/three/interaction/GrabbableObject";
import { RepairObjectModel } from "@/components/three/gameplay/RepairObjectModel";
import type { Vector3Tuple } from "@/types/three/three";
interface RepairEbikeRepairTriggerProps {
anchor: Vector3Tuple;
installed: boolean;
}
const REPLACEMENT_MODEL_PATH = "/models/refroidisseur/model.gltf";
/**
* Ebike-specific fake replacement flow: the broken radiator node is
* hidden in the shared ExplodableModel, a grabbable copy appears at the
* same anchor, then RepairGame/RepairMissionCase controls the install
* interaction and this component swaps the copy for a fresh glowing part.
*/
export function RepairEbikeRepairTrigger({
anchor,
installed,
}: RepairEbikeRepairTriggerProps): React.JSX.Element {
return (
<group>
{!installed ? (
<GrabbableObject
position={anchor}
colliders="ball"
handControlled
lockUntilGrab
label="Retirer le refroidisseur"
>
<RepairObjectModel
label="Refroidisseur"
modelPath={REPLACEMENT_MODEL_PATH}
scale={0.24}
/>
</GrabbableObject>
) : (
<group position={anchor}>
<RepairObjectModel
label="Refroidisseur"
modelPath={REPLACEMENT_MODEL_PATH}
scale={0.24}
/>
<mesh>
<sphereGeometry args={[0.65, 32, 16]} />
<meshBasicMaterial color="#22c55e" transparent opacity={0.18} />
</mesh>
<mesh rotation={[Math.PI / 2, 0, 0]}>
<torusGeometry args={[0.72, 0.025, 8, 96]} />
<meshBasicMaterial color="#86efac" transparent opacity={0.85} />
</mesh>
</group>
)}
</group>
);
}
@@ -4,7 +4,12 @@ import * as THREE from "three";
import { useRepairFocusStore } from "@/managers/stores/useRepairFocusStore";
const BUBBLE_RADIUS_METERS = 10;
const BUBBLE_GROW_DURATION_SECONDS = 2.5;
/**
* Duration of the GSAP `expo.out` grow tween. Exported so step-driven
* code (e.g. `RepairGame` advancing inspected -> fragmented) can wait
* the same amount of time before triggering the next phase.
*/
export const BUBBLE_GROW_DURATION_SECONDS = 2.5;
const BUBBLE_SHRINK_DURATION_SECONDS = 1.2;
const BUBBLE_COLOR = "#060814";
const BUBBLE_OPACITY = 0.92;
+419 -43
View File
@@ -1,4 +1,4 @@
import { Suspense, useEffect, useMemo, useState } from "react";
import { Suspense, useEffect, useMemo, useRef, useState } from "react";
import { useGLTF } from "@react-three/drei";
import { ExplodableModel } from "@/components/three/models/ExplodableModel";
import type { ExplodedNodeAnchors } from "@/components/three/models/ExplodableModel";
@@ -7,17 +7,36 @@ import type {
RepairCasePlaceholder,
} from "@/components/three/gameplay/RepairCaseModel";
import { RepairCompletionStep } from "@/components/three/gameplay/RepairCompletionStep";
import { RepairEbikeRepairTrigger } from "@/components/three/gameplay/RepairEbikeRepairTrigger";
import { RepairInspectionObject } from "@/components/three/gameplay/RepairInspectionObject";
import { RepairMissionCase } from "@/components/three/gameplay/RepairMissionCase";
import { BUBBLE_GROW_DURATION_SECONDS } from "@/components/three/gameplay/RepairFocusBubble";
import { RepairRepairingStep } from "@/components/three/gameplay/RepairRepairingStep";
import { RepairReassemblyStep } from "@/components/three/gameplay/RepairReassemblyStep";
import { RepairScanSequence } from "@/components/three/gameplay/RepairScanSequence";
import { REPAIR_CASE_MODEL_PATH } from "@/data/gameplay/repairCaseConfig";
import { REPAIR_FRAGMENTATION_SEQUENCE_SECONDS } from "@/data/gameplay/repairGameConfig";
import {
REPAIR_FRAGMENT_SPLIT_DURATION_SECONDS,
REPAIR_DONE_DIALOGUE_FALLBACK_MS,
REPAIR_FRAGMENTATION_SEQUENCE_SECONDS,
REPAIR_FRAGMENT_SPLIT_SPEED,
REPAIR_REASSEMBLY_HOLD_MS,
} from "@/data/gameplay/repairGameConfig";
import { REPAIR_MISSIONS } from "@/data/gameplay/repairMissions";
import {
EBIKE_REPAIRED_DIALOGUE_ID,
EBIKE_SCAN_HINT_DIALOGUE_ID,
} from "@/data/ebike/ebikeConfig";
import { useRepairFragmentationInput } from "@/hooks/gameplay/useRepairFragmentationInput";
import { useRepairMissionStep } from "@/hooks/gameplay/useRepairMissionStep";
import { useTerrainSnappedPosition } from "@/hooks/three/useTerrainHeight";
import { loadDialogueManifest } from "@/utils/dialogues/loadDialogueManifest";
import {
clearQueuedDialogues,
playDialogueById,
stopCurrentDialogue,
} from "@/utils/dialogues/playDialogue";
import { useSubtitleStore } from "@/managers/stores/useSubtitleStore";
import type {
MissionStep,
RepairMissionConfig,
@@ -27,6 +46,7 @@ import type {
import { useGameStore } from "@/managers/stores/useGameStore";
import { useRepairFocusStore } from "@/managers/stores/useRepairFocusStore";
import type { ModelTransformProps, Vector3Tuple } from "@/types/three/three";
import type { ExplodedPart } from "@/utils/three/ExplodedModel";
import { toVector3Scale } from "@/utils/three/scale";
interface RepairGameProps extends Required<
@@ -41,6 +61,11 @@ interface RepairMissionAssetPreloaderProps {
config: RepairMissionConfig;
}
interface EbikeRepairTransform {
position: Vector3Tuple;
rotationY: number;
}
function RepairMissionAssetPreloader({
config,
}: RepairMissionAssetPreloaderProps): null {
@@ -54,6 +79,20 @@ function RepairMissionAssetPreloader({
return null;
}
const REPAIR_PHASES: readonly MissionStep[] = [
"fragmented",
"scanning",
"repairing",
"reassembling",
"done",
];
const SPLIT_PHASES: readonly MissionStep[] = [
"fragmented",
"scanning",
"repairing",
];
export function RepairGame({
mission,
position,
@@ -73,22 +112,57 @@ export function RepairGame({
const [scannedBrokenParts, setScannedBrokenParts] = useState<
readonly RepairScannedBrokenPart[]
>([]);
// For the ebike mission, use the bike's live parked world position once
// the repair flow leaves the waiting/locked phase so the repair happens
// wherever the player parked the bike, not at the static zone anchor.
// window.ebikeParkedPosition is set by Ebike when the player drops the
// bike and stays stable through the rest of the repair flow.
const [explodedParts, setExplodedParts] = useState<readonly ExplodedPart[]>(
[],
);
const [ebikeRepairTransform, setEbikeRepairTransform] =
useState<EbikeRepairTransform | null>(null);
const [ebikeCoolingInstalled, setEbikeCoolingInstalled] = useState(false);
const fragmentedSplitSettledRef = useRef(false);
const fragmentedDialogueDoneRef = useRef(false);
const reassemblyDoneTimeoutRef = useRef<number | null>(null);
// Ebike-specific: once the repair starts, keep the entire repair flow
// exactly where the bike currently is. `Ebike` owns the live parked
// position while inspected is showing; RepairGame takes over the model
// from fragmented onward and must reuse that same world transform.
const livePosition = useMemo<Vector3Tuple>(() => {
if (mission !== "ebike" || mainState !== mission) return position;
if (step === "locked" || step === "waiting") return position;
if (mission !== "ebike" || step === "waiting") return position;
if (ebikeRepairTransform) return ebikeRepairTransform.position;
const parked = window.ebikeParkedPosition;
if (!parked) return position;
return [parked[0], parked[1], parked[2]];
}, [mainState, mission, position, step]);
}, [ebikeRepairTransform, mission, position, step]);
const usesLiveEbikePosition = mission === "ebike" && step !== "waiting";
const parsedScale = toVector3Scale(scale);
const snappedPosition = useTerrainSnappedPosition(livePosition);
const terrainSnappedPosition = useTerrainSnappedPosition(livePosition);
const snappedPosition = usesLiveEbikePosition
? livePosition
: terrainSnappedPosition;
const readyForFragmentation = step === "inspected";
const brokenNodeNames = useMemo(() => getBrokenNodeNames(config), [config]);
const isRepairPhase = (REPAIR_PHASES as readonly MissionStep[]).includes(
step,
);
const isSplitPhase = (SPLIT_PHASES as readonly MissionStep[]).includes(step);
const isRepairing = step === "repairing";
const repairModelRotation: Vector3Tuple =
mission === "ebike" && ebikeRepairTransform
? [0, ebikeRepairTransform.rotationY, 0]
: (config.modelRotation ?? [0, 0, 0]);
const ebikeBrokenNodeName = config.brokenParts[0]?.targetNodeName;
const ebikeBrokenWorldAnchor = ebikeBrokenNodeName
? brokenAnchors[ebikeBrokenNodeName]
: undefined;
const ebikeBrokenLocalAnchor = ebikeBrokenWorldAnchor
? ([
ebikeBrokenWorldAnchor[0] - snappedPosition[0],
ebikeBrokenWorldAnchor[1] - snappedPosition[1],
ebikeBrokenWorldAnchor[2] - snappedPosition[2],
] satisfies Vector3Tuple)
: ([0, 1, 0] satisfies Vector3Tuple);
useRepairFragmentationInput({
enabled: mainState === mission && readyForFragmentation,
@@ -104,6 +178,7 @@ export function RepairGame({
setCaseAnchors({});
setBrokenAnchors({});
setScannedBrokenParts([]);
setEbikeCoolingInstalled(false);
}, 0);
return () => {
@@ -111,6 +186,54 @@ export function RepairGame({
};
}, [mainState, mission, step]);
useEffect(() => {
if (mission !== "ebike") return undefined;
if (mainState !== "ebike" || step === "waiting") {
const timeoutId = window.setTimeout(() => {
setEbikeRepairTransform(null);
setEbikeCoolingInstalled(false);
}, 0);
return () => {
window.clearTimeout(timeoutId);
};
}
if (ebikeRepairTransform) return undefined;
const parked = window.ebikeParkedPosition;
const rotationY =
window.ebikeParkedRotation ?? config.modelRotation?.[1] ?? 0;
const snapshot: EbikeRepairTransform = {
position: parked ? [parked[0], parked[1], parked[2]] : position,
rotationY,
};
const timeoutId = window.setTimeout(() => {
setEbikeRepairTransform(snapshot);
}, 0);
return () => {
window.clearTimeout(timeoutId);
};
}, [
config.modelRotation,
ebikeRepairTransform,
mainState,
mission,
position,
step,
]);
useEffect(() => {
if (mission !== "ebike") return;
if (mainState === "ebike") return;
clearQueuedDialogues();
stopCurrentDialogue();
useSubtitleStore.getState().clearActiveSubtitle();
}, [mainState, mission]);
// Drive the global focus bubble: active during the immersive repair
// phases so the world dims/hides outside the dark sphere shroud.
const focusCenterX = snappedPosition[0];
@@ -118,7 +241,7 @@ export function RepairGame({
const focusCenterZ = snappedPosition[2];
useEffect(() => {
const inFocusPhase =
mainState === mission && shouldFocusBubbleBeActive(step);
mainState === mission && shouldFocusBubbleBeActive(step, mission);
if (inFocusPhase) {
useRepairFocusStore
.getState()
@@ -130,20 +253,243 @@ export function RepairGame({
return undefined;
}, [mainState, mission, step, focusCenterX, focusCenterY, focusCenterZ]);
// Ebike-only: auto-advance inspected -> fragmented once the focus
// bubble's grow tween has finished isolating the bike inside the dark
// cocoon. The 2.5s delay matches BUBBLE_GROW_DURATION_SECONDS so the
// fragmentation visual coincides with the fully-formed shroud.
useEffect(() => {
if (mainState !== mission) return undefined;
if (step !== "fragmented") return undefined;
if (mission !== "ebike") return undefined;
if (step !== "inspected") return undefined;
const timeoutId = window.setTimeout(() => {
setMissionStep(mission, "scanning");
}, REPAIR_FRAGMENTATION_SEQUENCE_SECONDS * 1000);
setMissionStep(mission, "fragmented");
}, BUBBLE_GROW_DURATION_SECONDS * 1000);
return () => {
window.clearTimeout(timeoutId);
};
}, [mainState, mission, setMissionStep, step]);
// fragmented -> scanning is now driven by `onSplitSettled` from the
// shared ExplodableModel below (fires once the lerp actually
// converges on progress=1). The legacy
// REPAIR_FRAGMENTATION_SEQUENCE_SECONDS timer is kept as a safety-net
// fallback in case the model fails to load (no settled event) so the
// flow can never get stuck on the fragmented step.
useEffect(() => {
if (mainState !== mission) return undefined;
if (step !== "fragmented") return undefined;
if (mission === "ebike") return undefined;
const timeoutId = window.setTimeout(
() => {
setMissionStep(mission, "scanning");
},
(REPAIR_FRAGMENTATION_SEQUENCE_SECONDS + 2) * 1000,
);
return () => {
window.clearTimeout(timeoutId);
};
}, [mainState, mission, setMissionStep, step]);
useEffect(() => {
if (mainState !== mission) return undefined;
if (mission !== "ebike") return undefined;
if (step !== "fragmented") return undefined;
fragmentedSplitSettledRef.current = false;
fragmentedDialogueDoneRef.current = false;
let cancelled = false;
let activeAudio: HTMLAudioElement | null = null;
let fallbackTimeoutId: number | null = null;
const tryAdvance = (): void => {
if (cancelled) return;
if (!fragmentedSplitSettledRef.current) return;
if (!fragmentedDialogueDoneRef.current) return;
setMissionStep(mission, "scanning");
};
const markDialogueDone = (): void => {
if (cancelled) return;
fragmentedDialogueDoneRef.current = true;
tryAdvance();
};
void (async () => {
const manifest = await loadDialogueManifest();
if (cancelled) return;
const audio = manifest
? await playDialogueById(manifest, EBIKE_SCAN_HINT_DIALOGUE_ID)
: null;
if (cancelled) {
if (audio && !audio.paused) {
audio.pause();
audio.currentTime = 0;
}
useSubtitleStore.getState().clearActiveSubtitle();
return;
}
activeAudio = audio;
if (audio) {
audio.addEventListener("ended", markDialogueDone, { once: true });
fallbackTimeoutId = window.setTimeout(markDialogueDone, 15000);
} else {
fallbackTimeoutId = window.setTimeout(markDialogueDone, 1000);
}
})();
return () => {
cancelled = true;
if (activeAudio) {
activeAudio.removeEventListener("ended", markDialogueDone);
if (!activeAudio.paused) {
activeAudio.pause();
activeAudio.currentTime = 0;
}
}
if (fallbackTimeoutId !== null) {
window.clearTimeout(fallbackTimeoutId);
}
useSubtitleStore.getState().clearActiveSubtitle();
};
}, [mainState, mission, setMissionStep, step]);
useEffect(() => {
if (mainState !== mission) return undefined;
if (step !== "reassembling") return undefined;
const timeoutId = window.setTimeout(() => {
setMissionStep(mission, "done");
}, REPAIR_REASSEMBLY_HOLD_MS + 4000);
return () => {
window.clearTimeout(timeoutId);
};
}, [mainState, mission, setMissionStep, step]);
// Ebike-only: at `done`, play the success narrator line and complete
// the mission when the audio ends (handing off to pylon). A fallback
// timer guarantees the transition even if the audio fails.
useEffect(() => {
if (mainState !== mission) return undefined;
if (mission !== "ebike") return undefined;
if (step !== "done") return undefined;
let cancelled = false;
let activeAudio: HTMLAudioElement | null = null;
let fallbackTimeoutId: number | null = null;
const finish = (): void => {
if (cancelled) return;
cancelled = true;
completeMission(mission);
};
void (async () => {
const manifest = await loadDialogueManifest();
if (cancelled) return;
const audio = manifest
? await playDialogueById(manifest, EBIKE_REPAIRED_DIALOGUE_ID)
: null;
if (cancelled) {
if (audio && !audio.paused) {
audio.pause();
audio.currentTime = 0;
}
useSubtitleStore.getState().clearActiveSubtitle();
return;
}
activeAudio = audio;
if (audio) {
audio.addEventListener("ended", finish, { once: true });
fallbackTimeoutId = window.setTimeout(
finish,
REPAIR_DONE_DIALOGUE_FALLBACK_MS,
);
} else {
fallbackTimeoutId = window.setTimeout(
finish,
REPAIR_DONE_DIALOGUE_FALLBACK_MS,
);
}
})();
return () => {
cancelled = true;
if (activeAudio) {
activeAudio.removeEventListener("ended", finish);
if (!activeAudio.paused) {
activeAudio.pause();
activeAudio.currentTime = 0;
}
}
if (fallbackTimeoutId !== null) {
window.clearTimeout(fallbackTimeoutId);
}
useSubtitleStore.getState().clearActiveSubtitle();
};
}, [completeMission, mainState, mission, step]);
// The shared ExplodableModel resets its parts to a fresh array each
// time it remounts (i.e. when leaving the repair flow back to
// waiting/inspected). The cached `explodedParts` will be overwritten
// by `onPartsReady` on the next mount; we don't need an explicit
// reset because no rendered code path uses the stale parts outside
// the repair phases.
// Settled callback: drives event-based transitions out of the
// explode/reassemble lerp.
const stepRef = useRef(step);
useEffect(() => {
stepRef.current = step;
}, [step]);
const handleSplitSettled = useMemo(
() => (settledAt: 0 | 1) => {
const currentStep = stepRef.current;
if (settledAt === 1 && currentStep === "fragmented") {
if (mission === "ebike") {
fragmentedSplitSettledRef.current = true;
if (fragmentedDialogueDoneRef.current) {
setMissionStep(mission, "scanning");
}
return;
}
setMissionStep(mission, "scanning");
}
if (settledAt === 0 && currentStep === "reassembling") {
if (reassemblyDoneTimeoutRef.current !== null) {
window.clearTimeout(reassemblyDoneTimeoutRef.current);
}
reassemblyDoneTimeoutRef.current = window.setTimeout(() => {
reassemblyDoneTimeoutRef.current = null;
setMissionStep(mission, "done");
}, REPAIR_REASSEMBLY_HOLD_MS);
}
},
[mission, setMissionStep],
);
useEffect(() => {
return () => {
if (reassemblyDoneTimeoutRef.current !== null) {
window.clearTimeout(reassemblyDoneTimeoutRef.current);
}
};
}, []);
function handleEbikeCoolingInstall(): void {
if (ebikeCoolingInstalled) return;
setEbikeCoolingInstalled(true);
window.setTimeout(() => {
setMissionStep(mission, "reassembling");
}, 450);
}
if (mainState !== mission) return null;
if (step === "locked") return null;
@@ -160,34 +506,49 @@ export function RepairGame({
onInspect={() => setMissionStep(mission, "inspected")}
/>
) : null}
{step === "fragmented" ? (
{/*
Single ExplodableModel mounted across the entire repair flow
(fragmented -> done) so the model loads once, animates from
its real original positions, never re-instantiates between
phases, and stays at a stable transform. `split` toggles drive
the explode/reassemble lerps in place.
*/}
{isRepairPhase ? (
<ExplodableModel
modelPath={config.modelPath}
rotation={config.modelRotation ?? [0, 0, 0]}
rotation={repairModelRotation}
scale={config.modelScale ?? 1}
split
split={isSplitPhase}
splitSpeed={REPAIR_FRAGMENT_SPLIT_SPEED}
splitDurationSeconds={REPAIR_FRAGMENT_SPLIT_DURATION_SECONDS}
onPartsReady={setExplodedParts}
onSplitSettled={handleSplitSettled}
{...(isRepairing
? {
hideNodeNames: brokenNodeNames,
nodeAnchorNames: brokenNodeNames,
onNodeAnchorsChange: setBrokenAnchors,
}
: {})}
/>
) : null}
{step === "scanning" ? (
<RepairScanSequence
config={config}
parts={explodedParts}
onComplete={(brokenParts) => {
setScannedBrokenParts(brokenParts);
setMissionStep(mission, "repairing");
}}
/>
) : null}
{step === "repairing" ? (
<>
<ExplodableModel
modelPath={config.modelPath}
rotation={config.modelRotation ?? [0, 0, 0]}
scale={config.modelScale ?? 1}
split
hideNodeNames={brokenNodeNames}
nodeAnchorNames={brokenNodeNames}
onNodeAnchorsChange={setBrokenAnchors}
{step === "repairing" && mission === "ebike" ? (
<RepairEbikeRepairTrigger
anchor={ebikeBrokenLocalAnchor}
installed={ebikeCoolingInstalled}
/>
) : null}
{step === "repairing" && mission !== "ebike" ? (
<RepairRepairingStep
anchors={caseAnchors}
brokenAnchors={brokenAnchors}
@@ -196,30 +557,37 @@ export function RepairGame({
placeholders={casePlaceholders}
onRepair={() => setMissionStep(mission, "reassembling")}
/>
</>
) : null}
{step === "reassembling" ? (
<RepairReassemblyStep
config={config}
onComplete={() => setMissionStep(mission, "done")}
/>
) : null}
{step === "done" && mission !== "pylon" ? (
{step === "reassembling" ? <RepairReassemblyStep /> : null}
{step === "done" && mission !== "pylon" && mission !== "ebike" ? (
<RepairCompletionStep
config={config}
onComplete={() => completeMission(mission)}
/>
) : null}
{step !== "waiting" && step !== "done" && step !== "reassembling" ? (
{step !== "waiting" &&
step !== "done" &&
step !== "reassembling" &&
// Ebike's inspected phase is a 2.5s sphere-reveal cinematic that
// auto-advances to fragmented; the case + "press to fragment"
// prompt would only flash on screen, so suppress them here.
!(mission === "ebike" && step === "inspected") ? (
<RepairMissionCase
config={config}
onPlaceholdersChange={setCasePlaceholders}
onAnchorsChange={setCaseAnchors}
open={step === "repairing"}
zoomed={step === "repairing"}
showFragmentationPrompt={readyForFragmentation}
open={mission !== "ebike" && step === "repairing"}
zoomed={mission !== "ebike" && step === "repairing"}
showFragmentationPrompt={
readyForFragmentation && mission !== "ebike"
}
{...(mission === "ebike" && step === "repairing"
? { interactLabel: "Changez le refroidisseur" }
: {})}
onInteract={
readyForFragmentation
mission === "ebike" && step === "repairing"
? handleEbikeCoolingInstall
: readyForFragmentation && mission !== "ebike"
? () => setMissionStep(mission, "fragmented")
: undefined
}
@@ -234,7 +602,15 @@ function shouldKeepRepairRuntimeState(step: MissionStep): boolean {
return step === "repairing" || step === "reassembling" || step === "done";
}
function shouldFocusBubbleBeActive(step: MissionStep): boolean {
function shouldFocusBubbleBeActive(
step: MissionStep,
mission: RepairMissionId,
): boolean {
// Ebike opens the focus bubble one phase earlier (inspected) so the
// sphere visibly engulfs the bike during the inspect-then-explode
// build-up. Pylon/farm keep their original behaviour where the bubble
// appears once the model has fragmented.
if (mission === "ebike" && step === "inspected") return true;
return (
step === "fragmented" ||
step === "scanning" ||
@@ -25,6 +25,7 @@ interface RepairMissionCaseProps {
open?: boolean;
zoomed?: boolean;
showFragmentationPrompt?: boolean;
interactLabel?: string;
onInteract?: (() => void) | undefined;
}
@@ -37,6 +38,7 @@ export function RepairMissionCase({
open = false,
zoomed = false,
showFragmentationPrompt = false,
interactLabel,
onInteract,
}: RepairMissionCaseProps): React.JSX.Element {
const casePosition = zoomed
@@ -51,7 +53,7 @@ export function RepairMissionCase({
<TriggerObject
position={casePosition}
colliders="ball"
label={`Ouvrir ${config.label}`}
label={interactLabel ?? `Ouvrir ${config.label}`}
radius={REPAIR_INTERACTION_RADIUS}
onTrigger={onInteract}
>
@@ -1,45 +1,15 @@
import { useEffect, useState } from "react";
import { RepairCompletionParticles } from "@/components/three/gameplay/RepairCompletionParticles";
import { ExplodableModel } from "@/components/three/models/ExplodableModel";
import { REPAIR_REASSEMBLY_SECONDS } from "@/data/gameplay/repairGameConfig";
import type { RepairMissionConfig } from "@/types/gameplay/repairMission";
interface RepairReassemblyStepProps {
config: RepairMissionConfig;
onComplete: () => void;
}
export function RepairReassemblyStep({
config,
onComplete,
}: RepairReassemblyStepProps): React.JSX.Element {
const [split, setSplit] = useState(true);
const reassemblySeconds =
config.reassemblySeconds ?? REPAIR_REASSEMBLY_SECONDS;
useEffect(() => {
const closeTimeoutId = window.setTimeout(() => {
setSplit(false);
}, 50);
const completeTimeoutId = window.setTimeout(() => {
onComplete();
}, reassemblySeconds * 1000);
return () => {
window.clearTimeout(closeTimeoutId);
window.clearTimeout(completeTimeoutId);
};
}, [onComplete, reassemblySeconds]);
return (
<group>
<ExplodableModel
modelPath={config.modelPath}
scale={config.modelScale ?? 1}
split={split}
splitDistance={1.2}
/>
<RepairCompletionParticles />
</group>
);
/**
* Visual layer for the reassembly phase. The actual collapse animation
* (parts lerping back to their original positions) is driven by the
* shared ExplodableModel mounted upstream by RepairGame, which keeps a
* single instance alive across fragmented -> done so the model never
* reloads or jumps between phases.
*
* This component now only renders the completion particles and emits a
* settled signal after `delayMs` so the upstream flow can advance.
*/
export function RepairReassemblyStep(): React.JSX.Element {
return <RepairCompletionParticles />;
}
@@ -1,8 +1,7 @@
import { useEffect, useState } from "react";
import { useEffect, useMemo, useRef, useState } from "react";
import * as THREE from "three";
import { RepairBrokenPartHighlight } from "@/components/three/gameplay/RepairBrokenPartHighlight";
import { RepairBrokenPartPrompt } from "@/components/three/gameplay/RepairBrokenPartPrompt";
import { ExplodableModel } from "@/components/three/models/ExplodableModel";
import { RepairScanVisual } from "@/components/three/gameplay/RepairScanVisual";
import { REPAIR_SCAN_PART_SECONDS } from "@/data/gameplay/repairGameConfig";
import type {
@@ -12,9 +11,20 @@ import type {
} from "@/types/gameplay/repairMission";
import { logger } from "@/utils/core/Logger";
import type { ExplodedPart } from "@/utils/three/ExplodedModel";
import { loadDialogueManifest } from "@/utils/dialogues/loadDialogueManifest";
import { playDialogueById } from "@/utils/dialogues/playDialogue";
import { useSubtitleStore } from "@/managers/stores/useSubtitleStore";
interface RepairScanSequenceProps {
config: RepairMissionConfig;
/**
* Parts of the (already mounted) ExplodableModel managed upstream by
* RepairGame. The scan sequence drives its visuals against these
* parts so the model isn't re-instantiated when entering the scanning
* phase (which would cause the explosion animation to replay and the
* world transform to differ between phases).
*/
parts: readonly ExplodedPart[];
onComplete: (brokenParts: readonly RepairScannedBrokenPart[]) => void;
}
@@ -27,25 +37,112 @@ const warnedMissingScanParts = new Set<string>();
export function RepairScanSequence({
config,
parts,
onComplete,
}: RepairScanSequenceProps): React.JSX.Element {
const [parts, setParts] = useState<readonly ExplodedPart[]>([]);
const [activePartIndex, setActivePartIndex] = useState(0);
const activePart = parts[activePartIndex];
const scanPartSeconds = config.scanPartSeconds ?? REPAIR_SCAN_PART_SECONDS;
const brokenPartMatches = getBrokenPartMatches(parts, config);
const brokenPartMatches = useMemo(
() => getBrokenPartMatches(parts, config),
[parts, config],
);
const visibleBrokenPartMatches = brokenPartMatches.filter(
(match) => match.partIndex <= activePartIndex,
);
const onCompleteRef = useRef(onComplete);
useEffect(() => {
onCompleteRef.current = onComplete;
}, [onComplete]);
useEffect(() => {
if (parts.length === 0) return undefined;
// Look up which (if any) broken-part config corresponds to the
// currently active scan part. When the active part has a
// `voiceLineId`, gate the advance on the audio's `ended` event so
// the diagnostic line plays in full (with its red broken-part
// highlight already on screen) before transitioning to the next
// scan part — and ultimately to the repairing step.
const activeBrokenMatch = brokenPartMatches.find(
(match) => match.partIndex === activePartIndex,
);
const activeVoiceLineId = activeBrokenMatch?.config.voiceLineId;
if (activeVoiceLineId) {
let cancelled = false;
let activeAudio: HTMLAudioElement | null = null;
let fallbackTimeoutId: number | null = null;
const advance = (): void => {
if (cancelled) return;
cancelled = true;
setActivePartIndex((currentIndex) => {
const nextIndex = currentIndex + 1;
if (nextIndex >= parts.length) {
window.setTimeout(() => {
onCompleteRef.current(getScannedBrokenParts(parts, config));
}, 0);
return currentIndex;
}
return nextIndex;
});
};
void (async () => {
const manifest = await loadDialogueManifest();
if (cancelled) return;
const audio = manifest
? await playDialogueById(manifest, activeVoiceLineId)
: null;
if (cancelled) {
if (audio && !audio.paused) {
audio.pause();
audio.currentTime = 0;
}
useSubtitleStore.getState().clearActiveSubtitle();
return;
}
activeAudio = audio;
if (audio) {
audio.addEventListener("ended", advance, { once: true });
// Fallback: if the audio errors or never fires `ended`, still
// advance after a generous ceiling so the flow can't stall.
fallbackTimeoutId = window.setTimeout(advance, 15000);
} else {
// No audio (manifest missing) — advance after the default
// per-part dwell so we don't get stuck on this part.
fallbackTimeoutId = window.setTimeout(
advance,
scanPartSeconds * 1000,
);
}
})();
return () => {
cancelled = true;
if (activeAudio) {
activeAudio.removeEventListener("ended", advance);
if (!activeAudio.paused) {
activeAudio.pause();
activeAudio.currentTime = 0;
}
}
if (fallbackTimeoutId !== null) {
window.clearTimeout(fallbackTimeoutId);
}
useSubtitleStore.getState().clearActiveSubtitle();
};
}
const timeoutId = window.setTimeout(() => {
setActivePartIndex((currentIndex) => {
const nextIndex = currentIndex + 1;
if (nextIndex >= parts.length) {
onComplete(getScannedBrokenParts(parts, config));
window.setTimeout(() => {
onCompleteRef.current(getScannedBrokenParts(parts, config));
}, 0);
return currentIndex;
}
@@ -56,16 +153,10 @@ export function RepairScanSequence({
return () => {
window.clearTimeout(timeoutId);
};
}, [activePartIndex, config, onComplete, parts, scanPartSeconds]);
}, [activePartIndex, brokenPartMatches, config, parts, scanPartSeconds]);
return (
<group>
<ExplodableModel
modelPath={config.modelPath}
scale={config.modelScale ?? 1}
split
onPartsReady={setParts}
/>
<RepairScanVisual target={activePart?.object} />
{visibleBrokenPartMatches.map((match) => {
const part = parts[match.partIndex];
@@ -133,6 +224,7 @@ function getBrokenPartMatches(
logger.warn("RepairScan", "Broken parts missing from exploded model", {
missionId: config.id,
missingIds,
availablePartNames: parts.map((part) => part.object.name),
});
}
}
@@ -148,11 +240,20 @@ function objectContainsNodeName(
object: THREE.Object3D,
nodeName: string,
): boolean {
if (object.name === nodeName) return true;
const normalizedNodeName = nodeName.toLowerCase();
const objectName = object.name.toLowerCase();
if (objectName === normalizedNodeName) return true;
if (objectName.includes(normalizedNodeName)) return true;
if (normalizedNodeName.includes(objectName)) return true;
let found = false;
object.traverse((child) => {
if (child.name === nodeName) {
const childName = child.name.toLowerCase();
if (
childName === normalizedNodeName ||
childName.includes(normalizedNodeName) ||
normalizedNodeName.includes(childName)
) {
found = true;
}
});
@@ -1,4 +1,4 @@
import { useEffect, useRef } from "react";
import { useEffect, useRef, useState } from "react";
import { useFrame, useThree } from "@react-three/fiber";
import { RigidBody } from "@react-three/rapier";
import type { RapierRigidBody } from "@react-three/rapier";
@@ -35,6 +35,7 @@ interface GrabbableObjectProps {
label?: string;
handControlled?: boolean;
disabled?: boolean;
lockUntilGrab?: boolean;
onGrabChange?: (held: boolean) => void;
onPositionChange?: (position: THREE.Vector3) => void;
onSnap?: (position: THREE.Vector3) => void;
@@ -134,6 +135,7 @@ export function GrabbableObject({
label = GRAB_DEFAULT_LABEL,
handControlled = false,
disabled = false,
lockUntilGrab = false,
onGrabChange,
onPositionChange,
onSnap,
@@ -148,6 +150,7 @@ export function GrabbableObject({
const rbRef = useRef<RapierRigidBody>(null);
const isHolding = useRef(false);
const isHandHolding = useRef(false);
const [hasBeenGrabbed, setHasBeenGrabbed] = useState(false);
const snapTween = useRef<gsap.core.Tween | null>(null);
useEffect(() => {
@@ -288,6 +291,7 @@ export function GrabbableObject({
const hadHit = Boolean(hit);
if (hadHit) {
setHasBeenGrabbed(true);
isHandHolding.current = true;
InteractionManager.getInstance().setHandHolding(true);
onGrabChange?.(true);
@@ -330,7 +334,7 @@ export function GrabbableObject({
<group ref={spaceRef}>
<RigidBody
ref={rbRef}
type="dynamic"
type={lockUntilGrab && !hasBeenGrabbed ? "fixed" : "dynamic"}
colliders={colliders}
position={position}
>
@@ -344,6 +348,7 @@ export function GrabbableObject({
position={position}
bodyRef={rbRef}
onPress={() => {
setHasBeenGrabbed(true);
isHolding.current = true;
onGrabChange?.(true);
}}
@@ -1,5 +1,5 @@
import type { ReactNode } from "react";
import { Component, useEffect, useMemo, useRef } from "react";
import { Component, useCallback, useEffect, useMemo, useRef } from "react";
import * as THREE from "three";
import { useFrame } from "@react-three/fiber";
import { useLoggedGLTF } from "@/hooks/three/useLoggedGLTF";
@@ -71,7 +71,19 @@ interface ExplodableModelInnerProps extends ModelTransformProps {
modelPath: string;
split: boolean;
splitDistance?: number;
/**
* Lerp speed for the explode/reassemble animation. Lower = slower.
* Defaults to ExplodedModel's internal default (6) when omitted.
*/
splitSpeed?: number;
splitDurationSeconds?: number;
onPartsReady?: (parts: readonly ExplodedPart[]) => void;
/**
* Fired once each time the explode/reassemble lerp converges on its
* target. `settledAt` is 1 when the parts have fully separated, 0
* when they have fully snapped back to their original positions.
*/
onSplitSettled?: (settledAt: 0 | 1) => void;
hideNodeNames?: readonly string[];
nodeAnchorNames?: readonly string[];
onNodeAnchorsChange?: (anchors: ExplodedNodeAnchors) => void;
@@ -100,7 +112,10 @@ function ExplodableModelInner({
rotation = [0, 0, 0],
scale = 1,
splitDistance = 1.2,
splitSpeed,
splitDurationSeconds,
onPartsReady,
onSplitSettled,
hideNodeNames,
nodeAnchorNames,
onNodeAnchorsChange,
@@ -112,9 +127,32 @@ function ExplodableModelInner({
scale,
});
const model = useClonedObject(scene);
// Keep the latest callback in a ref so the ExplodedModel instance can
// be created once per `model` and still call the most recent prop
// when the lerp settles. Reading `.current` happens only inside the
// settled-callback (invoked from update(), never during render).
const onSplitSettledRef = useRef(onSplitSettled);
useEffect(() => {
onSplitSettledRef.current = onSplitSettled;
}, [onSplitSettled]);
const handleSettled = useCallback((settledAt: 0 | 1) => {
onSplitSettledRef.current?.(settledAt);
}, []);
const explodedModel = useMemo(
() => new ExplodedModel(model, { distance: splitDistance }),
[model, splitDistance],
() =>
// The `handleSettled` callback only reads `onSplitSettledRef.current`
// when invoked from `update()` (useFrame), never during render.
// eslint-disable-next-line react-hooks/refs
new ExplodedModel(model, {
distance: splitDistance,
...(splitDurationSeconds !== undefined
? { durationSeconds: splitDurationSeconds }
: {}),
...(splitSpeed !== undefined ? { speed: splitSpeed } : {}),
onSettled: handleSettled,
}),
[model, splitDistance, splitDurationSeconds, splitSpeed, handleSettled],
);
const parsedScale = toVector3Scale(scale);
const anchorSignatureRef = useRef("");
+41 -4
View File
@@ -1,6 +1,17 @@
import { MISSION_NOTIFICATION_IMAGE_PATHS } from "@/data/gameplay/missionNotifications";
import type { RepairMissionId } from "@/types/gameplay/repairMission";
// Reference aspect ratio of the original PNG mission notifications
// (589 × 211). Webm assets are square (2000 × 2000), so without this hint the
// <video> element renders at the wrong dimensions and shifts the layout.
const NOTIFICATION_ASPECT_RATIO = "589 / 211";
// Same clip-path as `.mission-notification__image-wrap` in index.css. Inlined
// here so the video branch can re-use the silhouette without inheriting the
// scan-line `::before` and CRT animations applied to the PNG branch.
const NOTIFICATION_CLIP_PATH =
"polygon(0 0, 100% 0, 100% 69%, 88% 100%, 0 100%)";
interface MissionNotificationProps {
mission?: RepairMissionId;
imagePath?: string;
@@ -19,13 +30,37 @@ export function MissionNotification({
return (
<div
className={`mission-notification${visible ? "" : " mission-notification--hidden"}`}
// Webm assets already animate themselves; suppress the CRT entrance
// flicker + drop-shadow that index.css applies to all .mission-notification
// nodes so the video plays in a clean container.
style={
isVideo
? {
animation: "none",
filter: "none",
}
: undefined
}
aria-live="polite"
>
<div className="mission-notification__glow" />
<span className="mission-notification__image-wrap">
{isVideo ? null : <div className="mission-notification__glow" />}
{isVideo ? (
<span
style={{
position: "relative",
display: "block",
overflow: "hidden",
clipPath: NOTIFICATION_CLIP_PATH,
}}
>
<video
className="mission-notification__image"
style={{
display: "block",
width: "100%",
height: "auto",
aspectRatio: NOTIFICATION_ASPECT_RATIO,
objectFit: "cover",
}}
src={src}
aria-label="Nouvel objectif de mission"
autoPlay
@@ -34,14 +69,16 @@ export function MissionNotification({
playsInline
preload="auto"
/>
</span>
) : (
<span className="mission-notification__image-wrap">
<img
className="mission-notification__image"
src={src}
alt="Nouvel objectif de mission"
/>
)}
</span>
)}
</div>
);
}
+135 -10
View File
@@ -1,22 +1,48 @@
import { useEffect, useRef, useState } from "react";
import type { AudioCategory } from "@/data/audioConfig";
import { AudioManager } from "@/managers/AudioManager";
const OUTRO_VIDEO_SRC = "/cinematics/outro.mp4";
const TRANSITION_FADE_MS = 600;
const TRANSITION_HOLD_MS = 2000;
const TRANSITION_TEXT_FADE_MS = 500;
// Delay between "Next step :" appearing and "La ferme" fading in.
const TRANSITION_LAFERME_DELAY_MS = 500;
const MUTED_CATEGORIES: readonly AudioCategory[] = ["music", "sfx", "dialogue"];
type Stage =
| "hidden"
| "fading-in"
| "showing-text"
| "fading-text-out"
| "video";
/**
* Full-screen video overlay that plays once after the outro drone-shot
* cinematic ends. Triggered by the "outro-cinematic-complete" window event
* dispatched from GameCinematics.tsx.
* End-of-demo overlay. Triggered by the "outro-cinematic-complete" window
* event dispatched from GameCinematics.tsx.
*
* Sequence:
* 1. Fade to black (TRANSITION_FADE_MS)
* 2. Reveal "Next step: La ferme" text + hold (TRANSITION_HOLD_MS)
* 3. Fade text out (TRANSITION_TEXT_FADE_MS)
* 4. Play `outro.mp4` full-screen with all game audio muted
*/
export function OutroVideoOverlay(): React.JSX.Element | null {
const [visible, setVisible] = useState(false);
const [stage, setStage] = useState<Stage>("hidden");
const [lafermeVisible, setLafermeVisible] = useState(false);
const videoRef = useRef<HTMLVideoElement>(null);
const savedVolumesRef = useRef<Partial<Record<AudioCategory, number>>>({});
useEffect(() => {
function handleCinematicComplete(): void {
setVisible(true);
setStage("fading-in");
}
window.addEventListener("outro-cinematic-complete", handleCinematicComplete);
window.addEventListener(
"outro-cinematic-complete",
handleCinematicComplete,
);
return () => {
window.removeEventListener(
"outro-cinematic-complete",
@@ -25,12 +51,80 @@ export function OutroVideoOverlay(): React.JSX.Element | null {
};
}, []);
// Drive the transition timeline.
useEffect(() => {
if (!visible) return;
void videoRef.current?.play();
}, [visible]);
if (stage === "fading-in") {
const timer = window.setTimeout(
() => setStage("showing-text"),
TRANSITION_FADE_MS,
);
return () => window.clearTimeout(timer);
}
if (stage === "showing-text") {
const timer = window.setTimeout(
() => setStage("fading-text-out"),
TRANSITION_HOLD_MS,
);
return () => window.clearTimeout(timer);
}
if (stage === "fading-text-out") {
const timer = window.setTimeout(
() => setStage("video"),
TRANSITION_TEXT_FADE_MS,
);
return () => window.clearTimeout(timer);
}
return undefined;
}, [stage]);
if (!visible) return null;
// Stagger the second word ("La ferme") so it fades in after "Next step :"
// is already visible.
useEffect(() => {
if (stage === "showing-text") {
const timer = window.setTimeout(
() => setLafermeVisible(true),
TRANSITION_LAFERME_DELAY_MS,
);
return () => window.clearTimeout(timer);
}
if (stage === "hidden" || stage === "fading-in") {
// Reset the staged reveal so a re-triggered outro replays correctly.
// eslint-disable-next-line react-hooks/set-state-in-effect
setLafermeVisible(false);
}
return undefined;
}, [stage]);
// Mute all game audio while the video is showing; restore on cleanup so
// a re-mounted page doesn't stay silent.
useEffect(() => {
if (stage !== "video") return;
const audioManager = AudioManager.getInstance();
const saved: Partial<Record<AudioCategory, number>> = {};
for (const category of MUTED_CATEGORIES) {
saved[category] = audioManager.getCategoryVolume(category);
audioManager.setCategoryVolume(category, 0);
}
savedVolumesRef.current = saved;
void videoRef.current?.play();
return () => {
for (const category of MUTED_CATEGORIES) {
const previous = savedVolumesRef.current[category];
if (previous !== undefined) {
audioManager.setCategoryVolume(category, previous);
}
}
savedVolumesRef.current = {};
};
}, [stage]);
if (stage === "hidden") return null;
const showText = stage === "showing-text" || stage === "fading-text-out";
const textOpacity = stage === "showing-text" ? 1 : 0;
return (
<div
@@ -42,14 +136,45 @@ export function OutroVideoOverlay(): React.JSX.Element | null {
display: "flex",
alignItems: "center",
justifyContent: "center",
opacity: stage === "fading-in" ? 0 : 1,
transition: `opacity ${TRANSITION_FADE_MS}ms ease-out`,
pointerEvents: stage === "video" ? "auto" : "none",
}}
aria-hidden={stage !== "video"}
>
{showText ? (
<div
style={{
color: "#F2F2F2",
textAlign: "center",
textShadow: "0 7px 14.4px rgba(0, 0, 0, 0.25)",
fontFamily: "Inter, system-ui, sans-serif",
fontSize: "clamp(24px, 4vw, 48px)",
fontWeight: 700,
letterSpacing: "-1.3px",
opacity: textOpacity,
transition: `opacity ${TRANSITION_TEXT_FADE_MS}ms ease-in`,
}}
>
Next step :{" "}
<span
style={{
opacity: lafermeVisible ? 1 : 0,
transition: `opacity ${TRANSITION_TEXT_FADE_MS}ms ease-in`,
}}
>
La ferme
</span>
</div>
) : null}
{stage === "video" ? (
<video
ref={videoRef}
src={OUTRO_VIDEO_SRC}
style={{ width: "100%", height: "100%", objectFit: "cover" }}
playsInline
/>
) : null}
</div>
);
}
@@ -14,6 +14,11 @@ const HAND_TUTORIAL_STEPS: ReadonlySet<MissionStep> = new Set([
"inspected",
]);
// Fallback: if hand detection never fires (camera blocked, MediaPipe failure,
// player using mouse), the tutorial auto-dismisses after this delay so it
// never blocks the screen indefinitely.
const HAND_TUTORIAL_FALLBACK_TIMEOUT_MS = 5000;
/**
* First-time hand-tracking tutorial. Visible during the early ebike repair
* steps until MediaPipe actually detects a hand on screen. Once dismissed it
@@ -39,6 +44,17 @@ export function HandTrackingTutorial(): React.JSX.Element | null {
}
}, [handsDetected, dismissed]);
// Fallback timeout: dismiss the tutorial even if no hand is ever detected,
// so the overlay never gets stuck on screen.
useEffect(() => {
if (!isInShowWindow || dismissed) return undefined;
const timer = window.setTimeout(
() => setDismissed(true),
HAND_TUTORIAL_FALLBACK_TIMEOUT_MS,
);
return () => window.clearTimeout(timer);
}, [isInShowWindow, dismissed]);
if (!isInShowWindow || dismissed) return null;
return (
+3 -5
View File
@@ -1,4 +1,4 @@
import { useEffect, useRef, useState } from "react";
import { useEffect, useRef } from "react";
import { useFrame, useThree } from "@react-three/fiber";
import * as THREE from "three";
import { isDebugEnabled } from "@/utils/debug/isDebugEnabled";
@@ -50,11 +50,10 @@ export function ZoneDetection({
zone,
onEnter,
height,
}: ZoneDetectionProps): React.JSX.Element {
}: ZoneDetectionProps): React.JSX.Element | null {
const camera = useThree((state) => state.camera);
const hasTriggeredRef = useRef(false);
const onEnterRef = useRef(onEnter);
const [isActive, setIsActive] = useState(false);
useEffect(() => {
onEnterRef.current = onEnter;
@@ -75,9 +74,8 @@ export function ZoneDetection({
if (_cameraPos.y > zone.position[1] + zoneHeight / 2) return;
hasTriggeredRef.current = true;
setIsActive(true);
onEnterRef.current();
});
return <ZoneDebugVisual zone={zone} active={isActive} />;
return null;
}
+4
View File
@@ -33,3 +33,7 @@ export const EBIKE_SOUNDS = {
} as const;
export const EBIKE_BREAKDOWN_DIALOGUE_ID = "narrateur_ebikecasse";
export const EBIKE_SCAN_HINT_DIALOGUE_ID = "narrateur_galetscan";
export const EBIKE_DIAGNOSTIC_DIALOGUE_ID =
"narrateur_refroidisseur_diagnostic";
export const EBIKE_REPAIRED_DIALOGUE_ID = "narrateur_ebikerepare";
+3 -3
View File
@@ -5,7 +5,7 @@ export const INTRO_MISSION_NOTIFICATION_IMAGE_PATH =
export const MISSION_NOTIFICATION_IMAGE_PATHS: Record<RepairMissionId, string> =
{
ebike: "/assets/world/UI/ebike-mission-notification.webm",
pylon: "/assets/world/UI/pylon-mission-notification.webm",
farm: "/assets/world/UI/farm-mission-notification.webm",
ebike: "/assets/world/UI/ebike.webm",
pylon: "/assets/world/UI/centrale.webm",
farm: "/assets/world/UI/laferme.webm",
};
+20
View File
@@ -3,3 +3,23 @@ export const REPAIR_FRAGMENTATION_SEQUENCE_SECONDS = 4;
export const REPAIR_INTERACTION_RADIUS = 10;
export const REPAIR_SCAN_PART_SECONDS = 1.2;
export const REPAIR_REASSEMBLY_SECONDS = 1.4;
/**
* Lerp speed used by the shared ExplodableModel during the repair flow.
* Lower = slower, more deliberate explosion so the player can see each
* node clearly leave its original position. The default ExplodedModel
* speed (6) finishes in ~0.5s which feels rushed.
*/
export const REPAIR_FRAGMENT_SPLIT_SPEED = 1.8;
export const REPAIR_FRAGMENT_SPLIT_DURATION_SECONDS = 1.5;
/**
* Delay between the end of the inverse-explosion (parts settled back to
* their original positions) and the auto-transition to the `done` step.
* Used by the ebike repair flow so the reassembly particles can play
* before the bubble starts shrinking.
*/
export const REPAIR_REASSEMBLY_HOLD_MS = 1500;
/**
* Fallback timer for the ebike `done` -> mission-complete transition
* when the narrator audio fails to fire its `ended` event.
*/
export const REPAIR_DONE_DIALOGUE_FALLBACK_MS = 6000;
+8 -7
View File
@@ -20,13 +20,14 @@ const REPAIR_MISSION_POSITIONS = {
farm: [-24, 0, 42],
} as const satisfies Record<RepairMissionId, Vector3Tuple>;
export const REPAIR_MISSION_TRIGGERS = [
{
mission: "ebike",
label: "Réparer l'e-bike",
radius: 4,
},
] as const satisfies readonly RepairMissionTriggerConfig[];
// Currently empty: the ebike mission entry point is handled directly by
// `Ebike.tsx`'s own InteractableObject ("Lancer le Repair Game"), and the
// pylon/farm missions transition through their narrative flows
// (PylonNarrativeFlow / FarmNarrativeFlow). Keep the array typed so we
// can re-introduce a generic anchor trigger in the future without
// touching the consumer in `GameStageContent.tsx`.
export const REPAIR_MISSION_TRIGGERS: readonly RepairMissionTriggerConfig[] =
[];
export const REPAIR_MISSION_POSITION_ENTRIES = Object.entries(
REPAIR_MISSION_POSITIONS,
+21 -3
View File
@@ -10,6 +10,7 @@ const REPAIR_MISSION_ID_VALUES: ReadonlySet<string> = new Set(
export const MISSION_STEPS = [
"locked",
"electricienne_history",
"approaching",
"arrived",
"npc-return",
@@ -30,12 +31,20 @@ const PYLON_ONLY_MISSION_STEPS = new Set<MissionStep>([
"npc-return",
"narrator-outro",
]);
const FARM_ONLY_MISSION_STEPS = new Set<MissionStep>(["electricienne_history"]);
export function getMissionStepsFor(
mission: RepairMissionId,
): readonly MissionStep[] {
if (mission === "pylon") return MISSION_STEPS;
return MISSION_STEPS.filter((step) => !PYLON_ONLY_MISSION_STEPS.has(step));
return MISSION_STEPS.filter((step) => {
if (mission !== "pylon" && PYLON_ONLY_MISSION_STEPS.has(step)) {
return false;
}
if (mission !== "farm" && FARM_ONLY_MISSION_STEPS.has(step)) {
return false;
}
return true;
});
}
export function isRepairMissionId(value: string): value is RepairMissionId {
@@ -53,6 +62,8 @@ export function getNextMissionStep(
switch (step) {
case "locked":
return mission === "pylon" ? "approaching" : "waiting";
case "electricienne_history":
return "done";
case "approaching":
return "arrived";
case "arrived":
@@ -85,6 +96,8 @@ export function getPreviousMissionStep(
switch (step) {
case "locked":
return "locked";
case "electricienne_history":
return "locked";
case "approaching":
return "locked";
case "arrived":
@@ -92,7 +105,12 @@ export function getPreviousMissionStep(
case "npc-return":
return "arrived";
case "waiting":
return mission === "pylon" ? "npc-return" : "locked";
// Ebike no longer has a "locked" entry state — its mission starts
// directly at "waiting". Pylon rewinds to its NPC return loop, farm
// rewinds to its narrative-driven locked kickoff.
if (mission === "pylon") return "npc-return";
if (mission === "farm") return "locked";
return "waiting";
case "inspected":
return "waiting";
case "fragmented":
+7 -3
View File
@@ -4,6 +4,7 @@ import type {
RepairMissionId,
} from "@/types/gameplay/repairMission";
import {
EBIKE_DIAGNOSTIC_DIALOGUE_ID,
EBIKE_WORLD_ROTATION_Y,
EBIKE_WORLD_SCALE,
} from "@/data/ebike/ebikeConfig";
@@ -36,9 +37,12 @@ export const REPAIR_MISSIONS: Record<RepairMissionId, RepairMissionConfig> = {
id: "ebike-cooling-core",
label: "Cooling core",
modelPath: "/models/refroidisseur/model.gltf",
nodeName: "refroidisseur",
targetNodeName: "refroidisseur",
nodeName: "Radiateur",
targetNodeName: "Radiateur",
caseSlotName: "placeholder_1",
// Plays during the scan landing on the refroidisseur node;
// the scan sequence advances on this audio's `ended` event.
voiceLineId: EBIKE_DIAGNOSTIC_DIALOGUE_ID,
},
],
replacementParts: [
@@ -47,7 +51,7 @@ export const REPAIR_MISSIONS: Record<RepairMissionId, RepairMissionConfig> = {
label: "Refroidisseur",
modelPath: "/models/refroidisseur/model.gltf",
caseAnchor: "refroidisseur",
targetNodeName: "refroidisseur",
targetNodeName: "Radiateur",
},
{
id: "ebike-cable-right-distractor",
+2 -2
View File
@@ -131,7 +131,7 @@ function completeIntroState(state: GameState): GameStateUpdate {
},
ebike: {
...state.ebike,
currentStep: "locked",
currentStep: "waiting",
},
};
}
@@ -265,7 +265,7 @@ function createInitialGameState(): GameState {
isEbikeUnlocked: false,
},
ebike: {
currentStep: "locked",
currentStep: "waiting",
dialogueAudio: null,
isRepaired: false,
},
+2
View File
@@ -4,6 +4,7 @@ import { Canvas } from "@react-three/fiber";
import * as THREE from "three";
import { DebugPerf } from "@/components/debug/DebugPerf";
import { EbikeIntroSequence } from "@/components/game/EbikeIntroSequence";
import { EbikeRepairNarrator } from "@/components/game/EbikeRepairNarrator";
import { AppLoadingIndicator } from "@/components/ui/AppLoadingIndicator";
import { DialogMessage } from "@/components/ui/DialogMessage";
import { GameUI } from "@/components/ui/GameUI";
@@ -259,6 +260,7 @@ export function HomePage(): React.JSX.Element | null {
) : null}
{renderIntroOverlay()}
<EbikeIntroSequence />
<EbikeRepairNarrator />
</HandTrackingProvider>
);
}
@@ -1,9 +1,7 @@
import type { ReactNode } from "react";
import { useEffect, useState } from "react";
import { HAND_TRACKING_LINGER_MS } from "@/data/handTrackingConfig";
import { useSceneMode } from "@/hooks/debug/useSceneMode";
import { useDebugStore } from "@/hooks/debug/useDebugStore";
import { useInteraction } from "@/hooks/interaction/useInteraction";
import {
HAND_TRACKING_IDLE_SNAPSHOT,
HandTrackingContext,
@@ -25,8 +23,14 @@ export function HandTrackingProvider({
}: {
children: ReactNode;
}): React.JSX.Element {
const sceneMode = useSceneMode();
const repairNeedsHands = useGameStore((state) => {
// Hand tracking is gated *only* by the active repair-mission step. We
// intentionally do NOT activate it from generic interactable proximity
// (e.g. standing next to the ebike to mount it) — that previously caused
// hand tracking to spin up around any interactable in the physics
// (TestMap) scene mode, even though the player wasn't in a step that
// actually uses hands. Use the GameStateDebugPanel to set
// mainState=ebike + currentStep=inspected when testing in TestMap.
const requested = useGameStore((state) => {
switch (state.mainState) {
case "ebike":
return REPAIR_HAND_TRACKING_STEPS.has(state.ebike.currentStep);
@@ -39,10 +43,6 @@ export function HandTrackingProvider({
return false;
}
});
const { nearby, holding, handHolding } = useInteraction();
const requested =
repairNeedsHands ||
(sceneMode === "physics" && (nearby || holding || handHolding));
// Keep the runtime active a little after `requested` turns off so
// MediaPipe has time to initialize the webcam + model + first frame
+9
View File
@@ -48,6 +48,15 @@ export interface RepairMissionPartConfig {
*/
caseLockGroup?: string;
modelPath?: string;
/**
* Optional dialogue id to play when the scan sequence lands on this
* part. The scan sequence will pause on this part for the duration
* of the audio (instead of the default `scanPartSeconds` timer) and
* advance to the next part on the audio's `ended` event. Use this to
* deliver a node-specific diagnostic line (e.g. ebike refroidisseur
* -> "narrateur_refroidisseur_diagnostic").
*/
voiceLineId?: string;
}
export interface RepairScannedBrokenPart {
+7 -2
View File
@@ -3,10 +3,15 @@ import type { MapNode, MapNodeInstanceTransform } from "@/types/map/mapScene";
export function mapNodeToInstanceTransform(
node: MapNode,
): MapNodeInstanceTransform {
return {
id: node.id,
const transform: MapNodeInstanceTransform = {
position: node.position,
rotation: node.rotation,
scale: node.scale,
};
if (node.id !== undefined) {
transform.id = node.id;
}
return transform;
}
+26 -1
View File
@@ -9,6 +9,14 @@ export interface ExplodedPart {
interface ExplodedModelOptions {
distance?: number;
speed?: number;
durationSeconds?: number;
/**
* Fired exactly once each time the lerp converges on a target value
* (1 = fully exploded, 0 = fully reassembled). Useful for chaining
* the next mission step on actual animation completion rather than a
* blind timer.
*/
onSettled?: (settledAt: 0 | 1) => void;
}
const _center = new THREE.Vector3();
@@ -18,17 +26,26 @@ export class ExplodedModel {
private readonly parts: ExplodedPart[] = [];
private readonly distance: number;
private readonly speed: number;
private readonly durationSeconds: number | undefined;
private readonly onSettled?: (settledAt: 0 | 1) => void;
private progress = 0;
private targetProgress = 0;
private settledAtTarget = true;
constructor(model: THREE.Object3D, options: ExplodedModelOptions = {}) {
this.distance = options.distance ?? 1.2;
this.speed = options.speed ?? 6;
this.durationSeconds = options.durationSeconds;
if (options.onSettled) this.onSettled = options.onSettled;
this.parts = this.createParts(model);
}
setSplit(split: boolean): void {
this.targetProgress = split ? 1 : 0;
const next = split ? 1 : 0;
if (next !== this.targetProgress) {
this.targetProgress = next;
this.settledAtTarget = false;
}
}
getParts(): readonly ExplodedPart[] {
@@ -39,6 +56,14 @@ export class ExplodedModel {
const diff = this.targetProgress - this.progress;
if (Math.abs(diff) < 0.001) {
this.progress = this.targetProgress;
if (!this.settledAtTarget) {
this.settledAtTarget = true;
this.onSettled?.(this.targetProgress === 1 ? 1 : 0);
}
} else if (this.durationSeconds !== undefined) {
const direction = diff > 0 ? 1 : -1;
this.progress += direction * (delta / this.durationSeconds);
this.progress = THREE.MathUtils.clamp(this.progress, 0, 1);
} else {
this.progress += diff * Math.min(delta * this.speed, 1);
}
+5 -3
View File
@@ -323,9 +323,11 @@ function MapNodeInstance({
}): React.JSX.Element | null {
const isGeneratedModel = isGeneratedMapModelName(node.name);
const mainState = useGameStore((state) => state.mainState);
const ebikeStep = useGameStore((state) => state.ebike.currentStep);
const hideEbikeMapModel =
node.name === "ebike" && mainState === "ebike" && ebikeStep !== "locked";
// The static-map ebike node is replaced by the live `Ebike` component
// (rendered from GameStageContent) as soon as the ebike mission begins,
// so hide the static one to avoid a dual-render at the same world
// position.
const hideEbikeMapModel = node.name === "ebike" && mainState === "ebike";
useEffect(() => {
if (modelUrl !== null || isGeneratedModel) return;
+1 -13
View File
@@ -6,9 +6,6 @@ import { FarmNarrativeFlow } from "@/components/gameplay/farm/FarmNarrativeFlow"
import { PylonDownedPylon } from "@/components/gameplay/pylon/PylonDownedPylon";
import { PylonLightingEffect } from "@/components/gameplay/pylon/PylonLightingEffect";
import { PylonNarrativeFlow } from "@/components/gameplay/pylon/PylonNarrativeFlow";
import { ZoneDebugVisual } from "@/components/zone/ZoneDetection";
import { PYLON_APPROACH_ZONE, PYLON_ARRIVED_ZONE } from "@/data/gameplay/zones";
import { isDebugEnabled } from "@/utils/debug/isDebugEnabled";
import {
REPAIR_MISSION_POSITION_ENTRIES,
REPAIR_MISSION_TRIGGERS,
@@ -18,7 +15,6 @@ import {
OUTRO_STAGE_ANCHOR,
} from "@/data/gameplay/gameStageAnchors";
import { useGameStore } from "@/managers/stores/useGameStore";
import { useRepairFocusStore } from "@/managers/stores/useRepairFocusStore";
import { useRepairMissionAnchorStore } from "@/managers/stores/useRepairMissionAnchorStore";
import {
isFarmNarrativeStep,
@@ -92,14 +88,12 @@ export function GameStageContent(): React.JSX.Element {
const mainState = useGameStore((state) => state.mainState);
const pylonStep = useGameStore((state) => state.pylon.currentStep);
const anchors = useRepairMissionAnchorStore((state) => state.anchors);
const repairFocusActive = useRepairFocusStore((state) => state.active);
const farmStep = useGameStore((state) => state.farm.currentStep);
const pylonInNarrative =
mainState === "pylon" && isPylonNarrativeStep(pylonStep);
const farmInNarrative =
mainState === "farm" && isFarmNarrativeStep(farmStep);
const farmInNarrative = mainState === "farm" && isFarmNarrativeStep(farmStep);
return (
<>
@@ -107,12 +101,6 @@ export function GameStageContent(): React.JSX.Element {
<Ebike position={EBIKE_WORLD_POSITION} />
<PylonLightingEffect />
<PylonDownedPylon />
{isDebugEnabled() && !repairFocusActive ? (
<>
<ZoneDebugVisual zone={PYLON_APPROACH_ZONE} active={false} />
<ZoneDebugVisual zone={PYLON_ARRIVED_ZONE} active={false} />
</>
) : null}
{mainState === "pylon" ? <PylonNarrativeFlow /> : null}
{mainState === "farm" ? <FarmNarrativeFlow /> : null}
{REPAIR_MISSION_POSITION_ENTRIES.map(({ mission }) => {